@wrongstack/core 0.1.4 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- import { c as ContentBlock, a0 as Context, v as Tool, B as ToolResultBlock, F as ToolUseBlock, h as Provider, R as Request, k as Response, T as TextBlock, a5 as RunOptions, W as WrongStackError, J as JSONSchema, U as Usage, n as SessionEvent, o as SessionMetadata, p as SessionStore } from './provider-DovtyuM8.js';
2
- import { p as PermissionPolicy, S as SecretScrubber, R as Renderer, B as EventBus, W as WireFamily, t as ProviderConfig, A as Container, X as Pipeline, _ as ReadonlyPipeline, b as Config, g as Logger, D as EventName, G as Listener } from './secret-scrubber-qU3AwEiI.js';
1
+ import { c as ContentBlock, a0 as Context, v as Tool, B as ToolResultBlock, F as ToolUseBlock, h as Provider, R as Request, k as Response, T as TextBlock, a5 as RunOptions, W as WrongStackError, J as JSONSchema, U as Usage, n as SessionEvent, o as SessionMetadata, p as SessionStore } from './provider-txgB0Oq9.js';
2
+ import { t as PermissionPolicy, S as SecretScrubber, y as Renderer, O as EventBus, W as WireFamily, x as ProviderConfig, N as Container, a2 as Pipeline, a5 as ReadonlyPipeline, b as Config, g as Logger, Q as EventName, U as Listener } from './mode-Pjt5vMS6.js';
3
3
 
4
4
  type AttachmentKind = 'text' | 'image' | 'file';
5
5
  interface AttachmentMeta {
@@ -405,7 +405,6 @@ declare class Agent {
405
405
  private get errorHandler();
406
406
  private get permission();
407
407
  private get scrubber();
408
- private get compactor();
409
408
  private get renderer();
410
409
  register(tool: Tool): void;
411
410
  use(plugin: Plugin, api: PluginAPI): Promise<void>;
@@ -442,7 +441,8 @@ declare class Agent {
442
441
  private waitForConfirm;
443
442
  private executeSingleWithDecision;
444
443
  /**
445
- * Run context window pipeline if compactor is present.
444
+ * Run context window pipeline. The pipeline may be empty, or it may contain
445
+ * middleware with its own injected dependencies.
446
446
  */
447
447
  private compactContextIfNeeded;
448
448
  }
@@ -578,32 +578,6 @@ interface Plugin {
578
578
  teardown?(api: PluginAPI): void | Promise<void>;
579
579
  }
580
580
 
581
- interface Mode {
582
- id: string;
583
- name: string;
584
- description: string;
585
- /** Additional prompt text injected into system prompt when mode is active */
586
- prompt: string;
587
- /** Tags for tool_search filtering */
588
- tags?: string[];
589
- /** Tools that should be prioritized/highlighted when this mode is active */
590
- toolPreferences?: string[];
591
- }
592
- interface ModeManifest {
593
- modes: Mode[];
594
- defaultMode?: string;
595
- }
596
- interface ModeStore {
597
- getActiveMode(): Promise<Mode | null>;
598
- setActiveMode(modeId: string | null): Promise<void>;
599
- listModes(): Promise<Mode[]>;
600
- getMode(modeId: string): Promise<Mode | null>;
601
- }
602
- interface ModeConfig {
603
- directory: string;
604
- }
605
- declare const DEFAULT_MODES: Mode[];
606
-
607
581
  type BridgeMessageType = 'task' | 'result' | 'progress' | 'error' | 'heartbeat' | 'stop' | 'delegate';
608
582
  interface BridgeMessage<T = unknown> {
609
583
  id: string;
@@ -708,6 +682,37 @@ interface SubagentConfig {
708
682
  tools?: string[];
709
683
  model?: string;
710
684
  priority?: number;
685
+ /**
686
+ * Provider registry id (e.g. `'anthropic'`, `'openai'`, `'google'`).
687
+ * Allows a director to mix providers across siblings — one subagent on
688
+ * Sonnet, another on GPT-5, another on Haiku. Falls back to the
689
+ * factory's default provider when omitted, which is the legacy
690
+ * single-provider behavior.
691
+ */
692
+ provider?: string;
693
+ /**
694
+ * Per-subagent session JSONL path. When omitted the orchestrator-
695
+ * supplied factory derives a path under `<sessionRoot>/<runId>/`.
696
+ * Override to redirect the transcript elsewhere (long-term storage,
697
+ * a different filesystem, etc.).
698
+ */
699
+ sessionPath?: string;
700
+ /**
701
+ * Additional text appended to the role's base system prompt. Does not
702
+ * replace it. Useful for last-mile guidance like "you may only call
703
+ * read tools, never write" or "respond in JSON only".
704
+ */
705
+ systemPromptOverride?: string;
706
+ /**
707
+ * Routing for streaming output. `'director'` (default) forwards
708
+ * text/tool events to the parent's FleetBus so the director can read
709
+ * the subagent's stream. `'silent'` keeps everything subagent-local;
710
+ * the director only sees the final task result. `'user'` forwards
711
+ * direct to the user-facing renderer (gate this behind an explicit
712
+ * config flag — it can confuse the chat surface).
713
+ */
714
+ textStream?: 'director' | 'silent' | 'user';
715
+ toolStream?: 'director' | 'silent' | 'user';
711
716
  }
712
717
  interface TaskResult<T = unknown> {
713
718
  subagentId: string;
@@ -832,7 +837,14 @@ interface CoordinatorStatus {
832
837
  interface SubagentContext {
833
838
  subagentId: string;
834
839
  tasks: TaskSpec[];
835
- parentBridge: AgentBridge;
840
+ /**
841
+ * Two-phase initialization: `spawn()` creates the subagent before the
842
+ * bridge is wired (`setSubagentBridge()`), so `parentBridge` is nullable
843
+ * by design. Readers must `hasParentBridge()`-guard or null-check before
844
+ * use; the prior `null as unknown as AgentBridge` cast was a type lie
845
+ * that hid this from the compiler.
846
+ */
847
+ parentBridge: AgentBridge | null;
836
848
  doneCondition: DoneCondition;
837
849
  maxConcurrent: number;
838
850
  }
@@ -1072,4 +1084,4 @@ interface DefaultSessionReaderOptions {
1072
1084
  store: SessionStore;
1073
1085
  }
1074
1086
 
1075
- export { type Span as $, type AddAttachmentInput as A, type BridgeMessage as B, type ConfirmAwaiter as C, DEFAULT_MODES as D, ENCRYPTED_PREFIX as E, type ModeStore as F, type MultiAgentConfig as G, type HealthCheck as H, type MultiAgentCoordinator as I, type PluginAPI as J, type PluginCapabilities as K, type PluginDependency as L, type MCPRegistryView as M, type PluginPipelines as N, type ProviderFactory as O, type Plugin as P, type ProviderRegistryView as Q, type SessionEventType as R, type SecretVault as S, type SessionExportOptions as T, type SessionQuery as U, type SessionReader as V, type SessionSearchHit as W, type SessionSearchQuery as X, type SessionSummaryLite as Y, type SlashCommand as Z, type SlashCommandRegistryView as _, type AgentBridge as a, type SpawnResult as a0, type SpecAnalysis as a1, type SpecApiEndpoint as a2, type SpecRequirement as a3, type SpecSection as a4, type SpecSectionType as a5, type SpecStatus as a6, type SpecTemplate as a7, type SpecValidationResult as a8, type Specification as a9, type ToolRegistryView as aA, type Tracer as aB, computeTaskProgress as aC, findCriticalPath as aD, topologicalSort as aE, ToolRegistry as aF, ProviderRegistry as aG, Agent as aH, type AgentInit as aI, type AgentInput as aJ, type AgentPipelines as aK, BudgetExceededError as aL, type BudgetKind as aM, type BudgetLimits as aN, type BudgetUsage as aO, DEFAULT_MAX_ITERATIONS as aP, type ProviderFactory$1 as aQ, type RunResult as aR, SubagentBudget as aS, type UserInputPayload as aT, createDefaultPipelines as aU, type SubagentConfig as aa, type SubagentContext as ab, type SubagentRunContext as ac, type SubagentRunOutcome as ad, type SubagentRunner as ae, type TaskAssignment as af, type TaskDelegation as ag, type TaskDependency as ah, type TaskEdge as ai, type TaskFilter as aj, type TaskGraph as ak, type TaskNode as al, type TaskPriority as am, type TaskProgress as an, type TaskResult as ao, type TaskSort as ap, type TaskSpec as aq, type TaskStatus as ar, type TaskType as as, type ToolBatchResult as at, type ToolConfirmPendingResult as au, type ToolExecution as av, type ToolExecutionOutput as aw, type ToolExecutorInit as ax, type ToolExecutorOptions as ay, type ToolExecutorStrategy as az, type AgentBridgeConfig as b, type AggregateHealth as c, type Attachment as d, type AttachmentKind as e, type AttachmentMeta as f, type AttachmentRef as g, type AttachmentStore as h, type BridgeMessageType as i, type BridgeTransport as j, type CoordinatorEvents as k, type CoordinatorStatus as l, type CriticalPathResult as m, DEFAULT_SPEC_TEMPLATE as n, type DefaultSessionReaderOptions as o, type DoneCondition as p, type HealthCheckResult as q, type HealthRegistry as r, type HealthStatus as s, type MetricLabels as t, type MetricSeries as u, type MetricsSink as v, type MetricsSnapshot as w, type Mode as x, type ModeConfig as y, type ModeManifest as z };
1087
+ export { type SpecSection as $, type AddAttachmentInput as A, type BridgeMessage as B, type ConfirmAwaiter as C, DEFAULT_SPEC_TEMPLATE as D, ENCRYPTED_PREFIX as E, type PluginDependency as F, type PluginPipelines as G, type HealthCheck as H, type ProviderFactory as I, type ProviderRegistryView as J, type SessionEventType as K, type SessionExportOptions as L, type MCPRegistryView as M, type SessionQuery as N, type SessionReader as O, type Plugin as P, type SessionSearchHit as Q, type SessionSearchQuery as R, type SecretVault as S, type SessionSummaryLite as T, type SlashCommand as U, type SlashCommandRegistryView as V, type Span as W, type SpawnResult as X, type SpecAnalysis as Y, type SpecApiEndpoint as Z, type SpecRequirement as _, type AgentBridge as a, type SpecSectionType as a0, type SpecStatus as a1, type SpecTemplate as a2, type SpecValidationResult as a3, type Specification as a4, type SubagentConfig as a5, type SubagentContext as a6, type SubagentRunContext as a7, type SubagentRunOutcome as a8, type SubagentRunner as a9, ToolRegistry as aA, ProviderRegistry as aB, Agent as aC, type AgentInit as aD, type AgentInput as aE, type AgentPipelines as aF, BudgetExceededError as aG, type BudgetKind as aH, type BudgetLimits as aI, type BudgetUsage as aJ, DEFAULT_MAX_ITERATIONS as aK, type ProviderFactory$1 as aL, type RunResult as aM, SubagentBudget as aN, type UserInputPayload as aO, createDefaultPipelines as aP, type TaskAssignment as aa, type TaskDelegation as ab, type TaskDependency as ac, type TaskEdge as ad, type TaskFilter as ae, type TaskGraph as af, type TaskNode as ag, type TaskPriority as ah, type TaskProgress as ai, type TaskResult as aj, type TaskSort as ak, type TaskSpec as al, type TaskStatus as am, type TaskType as an, type ToolBatchResult as ao, type ToolConfirmPendingResult as ap, type ToolExecution as aq, type ToolExecutionOutput as ar, type ToolExecutorInit as as, type ToolExecutorOptions as at, type ToolExecutorStrategy as au, type ToolRegistryView as av, type Tracer as aw, computeTaskProgress as ax, findCriticalPath as ay, topologicalSort as az, type AgentBridgeConfig as b, type AggregateHealth as c, type Attachment as d, type AttachmentKind as e, type AttachmentMeta as f, type AttachmentRef as g, type AttachmentStore as h, type BridgeMessageType as i, type BridgeTransport as j, type CoordinatorEvents as k, type CoordinatorStatus as l, type CriticalPathResult as m, type DefaultSessionReaderOptions as n, type DoneCondition as o, type HealthCheckResult as p, type HealthRegistry as q, type HealthStatus as r, type MetricLabels as s, type MetricSeries as t, type MetricsSink as u, type MetricsSnapshot as v, type MultiAgentConfig as w, type MultiAgentCoordinator as x, type PluginAPI as y, type PluginCapabilities as z };
@@ -0,0 +1,23 @@
1
+ import { v as Tool, T as TextBlock } from './provider-txgB0Oq9.js';
2
+
3
+ /** Model capabilities relevant to prompt composition. */
4
+ interface ModelCapabilities {
5
+ maxContextTokens: number;
6
+ supportsTools: boolean;
7
+ supportsVision: boolean;
8
+ supportsReasoning: boolean;
9
+ }
10
+ interface BuildContext {
11
+ cwd: string;
12
+ projectRoot: string;
13
+ tools: Tool[];
14
+ /** Provider id (e.g. "anthropic", "minimax-coding-plan"). */
15
+ provider?: string;
16
+ /** Model id (e.g. "claude-sonnet-4-6", "MiniMax-M2.7"). */
17
+ model?: string;
18
+ }
19
+ interface SystemPromptBuilder {
20
+ build(ctx: BuildContext): Promise<TextBlock[]>;
21
+ }
22
+
23
+ export type { BuildContext as B, ModelCapabilities as M, SystemPromptBuilder as S };
@@ -1,4 +1,4 @@
1
- export { A as AgentError, C as CacheStats, a as Capabilities, b as ConfigError, c as ContentBlock, E as ErrorCode, d as ErrorSeverity, e as ErrorSubsystem, I as ImageBlock, J as JSONSchema, M as Message, f as MessageRole, P as Permission, g as PluginError, h as Provider, i as ProviderError, j as ProviderErrorBody, R as Request, k as Response, l as ResumedSession, S as SessionData, m as SessionError, n as SessionEvent, o as SessionMetadata, p as SessionStore, q as SessionSummary, r as SessionWriter, s as StopReason, t as StreamEvent, T as TextBlock, u as TokenCounter, v as Tool, w as ToolCallContext, x as ToolError, y as ToolFinalEvent, z as ToolProgressEvent, B as ToolResultBlock, D as ToolStreamEvent, F as ToolUseBlock, U as Usage, W as WrongStackError, G as asBlocks, H as asText, K as isAgentError, L as isConfigError, N as isImageBlock, O as isPluginError, Q as isSessionError, V as isTextBlock, X as isToolError, Y as isToolResultBlock, Z as isToolUseBlock, _ as isWrongStackError, $ as toWrongStackError } from '../provider-DovtyuM8.js';
2
- export { C as CompactReport, a as Compactor, b as Config, c as ConfigLoader, d as ConfigStore, e as ContextConfig, E as ErrorHandler, F as FeaturesConfig, I as InputReader, L as LogConfig, f as LogLevel, g as Logger, M as MCPServerConfig, h as MemoryEntry, i as MemoryScope, j as MemoryStore, k as ModelsDevModel, l as ModelsDevPayload, m as ModelsDevProvider, n as ModelsRegistry, P as PathResolver, o as PermissionDecision, p as PermissionPolicy, q as PluginConfig, r as PromptOption, s as ProviderApiKey, t as ProviderConfig, R as Renderer, u as ResolvedModel, v as ResolvedProvider, w as RetryPolicy, S as SecretScrubber, x as SkillLoader, y as SkillManifest, T as ToolsConfig, z as TrustPolicy, W as WireFamily } from '../secret-scrubber-qU3AwEiI.js';
3
- export { A as AddAttachmentInput, a as AgentBridge, b as AgentBridgeConfig, c as AggregateHealth, d as Attachment, e as AttachmentKind, f as AttachmentMeta, g as AttachmentRef, h as AttachmentStore, B as BridgeMessage, i as BridgeMessageType, j as BridgeTransport, C as ConfirmAwaiter, k as CoordinatorEvents, l as CoordinatorStatus, m as CriticalPathResult, D as DEFAULT_MODES, n as DEFAULT_SPEC_TEMPLATE, o as DefaultSessionReaderOptions, p as DoneCondition, E as ENCRYPTED_PREFIX, H as HealthCheck, q as HealthCheckResult, r as HealthRegistry, s as HealthStatus, M as MCPRegistryView, t as MetricLabels, u as MetricSeries, v as MetricsSink, w as MetricsSnapshot, x as Mode, y as ModeConfig, z as ModeManifest, F as ModeStore, G as MultiAgentConfig, I as MultiAgentCoordinator, P as Plugin, J as PluginAPI, K as PluginCapabilities, L as PluginDependency, N as PluginPipelines, O as ProviderFactory, Q as ProviderRegistryView, S as SecretVault, R as SessionEventType, T as SessionExportOptions, U as SessionQuery, V as SessionReader, W as SessionSearchHit, X as SessionSearchQuery, Y as SessionSummaryLite, Z as SlashCommand, _ as SlashCommandRegistryView, $ as Span, a0 as SpawnResult, a1 as SpecAnalysis, a2 as SpecApiEndpoint, a3 as SpecRequirement, a4 as SpecSection, a5 as SpecSectionType, a6 as SpecStatus, a7 as SpecTemplate, a8 as SpecValidationResult, a9 as Specification, aa as SubagentConfig, ab as SubagentContext, ac as SubagentRunContext, ad as SubagentRunOutcome, ae as SubagentRunner, af as TaskAssignment, ag as TaskDelegation, ah as TaskDependency, ai as TaskEdge, aj as TaskFilter, ak as TaskGraph, al as TaskNode, am as TaskPriority, an as TaskProgress, ao as TaskResult, ap as TaskSort, aq as TaskSpec, ar as TaskStatus, as as TaskType, at as ToolBatchResult, au as ToolConfirmPendingResult, av as ToolExecution, aw as ToolExecutionOutput, ax as ToolExecutorInit, ay as ToolExecutorOptions, az as ToolExecutorStrategy, aA as ToolRegistryView, aB as Tracer, aC as computeTaskProgress, aD as findCriticalPath, aE as topologicalSort } from '../session-reader-DR4u3bu9.js';
4
- export { B as BuildContext, S as SystemPromptBuilder } from '../system-prompt--mzZnenv.js';
1
+ export { A as AgentError, C as CacheStats, a as Capabilities, b as ConfigError, c as ContentBlock, E as ErrorCode, d as ErrorSeverity, e as ErrorSubsystem, I as ImageBlock, J as JSONSchema, M as Message, f as MessageRole, P as Permission, g as PluginError, h as Provider, i as ProviderError, j as ProviderErrorBody, R as Request, k as Response, l as ResumedSession, S as SessionData, m as SessionError, n as SessionEvent, o as SessionMetadata, p as SessionStore, q as SessionSummary, r as SessionWriter, s as StopReason, t as StreamEvent, T as TextBlock, u as TokenCounter, v as Tool, w as ToolCallContext, x as ToolError, y as ToolFinalEvent, z as ToolProgressEvent, B as ToolResultBlock, D as ToolStreamEvent, F as ToolUseBlock, U as Usage, W as WrongStackError, G as asBlocks, H as asText, K as isAgentError, L as isConfigError, N as isImageBlock, O as isPluginError, Q as isSessionError, V as isTextBlock, X as isToolError, Y as isToolResultBlock, Z as isToolUseBlock, _ as isWrongStackError, $ as toWrongStackError } from '../provider-txgB0Oq9.js';
2
+ export { C as CompactReport, a as Compactor, b as Config, c as ConfigLoader, d as ConfigStore, e as ContextConfig, D as DEFAULT_MODES, E as ErrorHandler, F as FeaturesConfig, I as InputReader, L as LogConfig, f as LogLevel, g as Logger, M as MCPServerConfig, h as MemoryEntry, i as MemoryScope, j as MemoryStore, k as Mode, l as ModeConfig, m as ModeManifest, n as ModeStore, o as ModelsDevModel, p as ModelsDevPayload, q as ModelsDevProvider, r as ModelsRegistry, P as PathResolver, s as PermissionDecision, t as PermissionPolicy, u as PluginConfig, v as PromptOption, w as ProviderApiKey, x as ProviderConfig, R as RecoveryDecision, y as Renderer, z as ResolvedModel, A as ResolvedProvider, B as RetryPolicy, S as SecretScrubber, G as SkillEntry, H as SkillLoader, J as SkillManifest, T as ToolsConfig, K as TrustPolicy, W as WireFamily } from '../mode-Pjt5vMS6.js';
3
+ export { A as AddAttachmentInput, a as AgentBridge, b as AgentBridgeConfig, c as AggregateHealth, d as Attachment, e as AttachmentKind, f as AttachmentMeta, g as AttachmentRef, h as AttachmentStore, B as BridgeMessage, i as BridgeMessageType, j as BridgeTransport, C as ConfirmAwaiter, k as CoordinatorEvents, l as CoordinatorStatus, m as CriticalPathResult, D as DEFAULT_SPEC_TEMPLATE, n as DefaultSessionReaderOptions, o as DoneCondition, E as ENCRYPTED_PREFIX, H as HealthCheck, p as HealthCheckResult, q as HealthRegistry, r as HealthStatus, M as MCPRegistryView, s as MetricLabels, t as MetricSeries, u as MetricsSink, v as MetricsSnapshot, w as MultiAgentConfig, x as MultiAgentCoordinator, P as Plugin, y as PluginAPI, z as PluginCapabilities, F as PluginDependency, G as PluginPipelines, I as ProviderFactory, J as ProviderRegistryView, S as SecretVault, K as SessionEventType, L as SessionExportOptions, N as SessionQuery, O as SessionReader, Q as SessionSearchHit, R as SessionSearchQuery, T as SessionSummaryLite, U as SlashCommand, V as SlashCommandRegistryView, W as Span, X as SpawnResult, Y as SpecAnalysis, Z as SpecApiEndpoint, _ as SpecRequirement, $ as SpecSection, a0 as SpecSectionType, a1 as SpecStatus, a2 as SpecTemplate, a3 as SpecValidationResult, a4 as Specification, a5 as SubagentConfig, a6 as SubagentContext, a7 as SubagentRunContext, a8 as SubagentRunOutcome, a9 as SubagentRunner, aa as TaskAssignment, ab as TaskDelegation, ac as TaskDependency, ad as TaskEdge, ae as TaskFilter, af as TaskGraph, ag as TaskNode, ah as TaskPriority, ai as TaskProgress, aj as TaskResult, ak as TaskSort, al as TaskSpec, am as TaskStatus, an as TaskType, ao as ToolBatchResult, ap as ToolConfirmPendingResult, aq as ToolExecution, ar as ToolExecutionOutput, as as ToolExecutorInit, at as ToolExecutorOptions, au as ToolExecutorStrategy, av as ToolRegistryView, aw as Tracer, ax as computeTaskProgress, ay as findCriticalPath, az as topologicalSort } from '../session-reader-9sOTgmeC.js';
4
+ export { B as BuildContext, M as ModelCapabilities, S as SystemPromptBuilder } from '../system-prompt-vAB0F54-.js';
@@ -385,16 +385,33 @@ var DEFAULT_SPEC_TEMPLATE = {
385
385
 
386
386
  // src/types/task-graph.ts
387
387
  function computeTaskProgress(graph) {
388
- const nodes = Array.from(graph.nodes.values());
389
- const total = nodes.length;
390
- const completed = nodes.filter((n) => n.status === "completed").length;
391
- const pending = nodes.filter((n) => n.status === "pending").length;
392
- const inProgress = nodes.filter((n) => n.status === "in_progress").length;
393
- const blocked = nodes.filter((n) => n.status === "blocked").length;
394
- const failed = nodes.filter((n) => n.status === "failed").length;
395
- const review = nodes.filter((n) => n.status === "review").length;
396
- const estimatedHours = nodes.reduce((sum, n) => sum + (n.estimateHours ?? 0), 0);
397
- const actualHours = nodes.reduce((sum, n) => sum + (n.actualHours ?? 0), 0);
388
+ let completed = 0, pending = 0, inProgress = 0, blocked = 0, failed = 0, review = 0;
389
+ let estimatedHours = 0, actualHours = 0;
390
+ for (const n of graph.nodes.values()) {
391
+ switch (n.status) {
392
+ case "completed":
393
+ completed++;
394
+ break;
395
+ case "pending":
396
+ pending++;
397
+ break;
398
+ case "in_progress":
399
+ inProgress++;
400
+ break;
401
+ case "blocked":
402
+ blocked++;
403
+ break;
404
+ case "failed":
405
+ failed++;
406
+ break;
407
+ case "review":
408
+ review++;
409
+ break;
410
+ }
411
+ estimatedHours += n.estimateHours ?? 0;
412
+ actualHours += n.actualHours ?? 0;
413
+ }
414
+ const total = graph.nodes.size;
398
415
  return {
399
416
  total,
400
417
  pending,
@@ -421,16 +438,18 @@ function findCriticalPath(graph) {
421
438
  }
422
439
  function topologicalSort(graph) {
423
440
  const visited = /* @__PURE__ */ new Set();
441
+ const inStack = /* @__PURE__ */ new Set();
424
442
  const result = [];
425
443
  function visit(id) {
444
+ if (inStack.has(id)) return;
426
445
  if (visited.has(id)) return;
446
+ if (!graph.nodes.has(id)) return;
427
447
  visited.add(id);
428
- const node = graph.nodes.get(id);
429
- if (!node) return;
430
- const outgoing = graph.edges.filter((e) => e.from === id);
431
- for (const edge of outgoing) {
432
- visit(edge.to);
448
+ inStack.add(id);
449
+ for (const edge of graph.edges) {
450
+ if (edge.from === id) visit(edge.to);
433
451
  }
452
+ inStack.delete(id);
434
453
  result.push(id);
435
454
  }
436
455
  for (const rootId of graph.rootNodes) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/types/blocks.ts","../../src/types/messages.ts","../../src/types/errors.ts","../../src/types/provider.ts","../../src/types/secret-vault.ts","../../src/types/mode.ts","../../src/types/spec.ts","../../src/types/task-graph.ts"],"names":[],"mappings":";AAoDO,SAAS,YAAY,CAAA,EAAiC;AAC3D,EAAA,OAAO,EAAE,IAAA,KAAS,MAAA;AACpB;AACO,SAAS,eAAe,CAAA,EAAoC;AACjE,EAAA,OAAO,EAAE,IAAA,KAAS,UAAA;AACpB;AACO,SAAS,kBAAkB,CAAA,EAAuC;AACvE,EAAA,OAAO,EAAE,IAAA,KAAS,aAAA;AACpB;AACO,SAAS,aAAa,CAAA,EAAkC;AAC7D,EAAA,OAAO,EAAE,IAAA,KAAS,OAAA;AACpB;;;ACtDO,SAAS,SAAS,OAAA,EAAkD;AACzE,EAAA,OAAO,OAAO,OAAA,KAAY,QAAA,GAAW,CAAC,EAAE,MAAM,MAAA,EAAQ,IAAA,EAAM,OAAA,EAAS,CAAA,GAAI,OAAA;AAC3E;AAEO,SAAS,OAAO,O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CAAM,KAAK,EAAE,CAAA;AAAA,IACf;AAEA,IAAA,MAAA,CAAO,KAAK,EAAE,CAAA;AAAA,EAChB;AAEA,EAAA,KAAA,MAAW,MAAA,IAAU,MAAM,SAAA,EAAW;AACpC,IAAA,KAAA,CAAM,MAAM,CAAA;AAAA,EACd;AAEA,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["export interface TextBlock {\n type: 'text';\n text: string;\n cache_control?: { type: 'ephemeral' };\n}\n\nexport interface ToolUseBlock {\n type: 'tool_use';\n id: string;\n name: string;\n input: Record<string, unknown>;\n /**\n * Provider-specific opaque metadata captured from the wire response.\n * Echoed back verbatim in the next request so providers that bind\n * extra state to function calls keep working. Example: Gemini's\n * `thoughtSignature` — required for tool-use turns with thinking\n * models, otherwise the next request fails with 400 \"Function call\n * is missing a thought_signature in functionCall parts\".\n *\n * Keys are namespaced by intent so multiple wires can coexist:\n * - `google.thoughtSignature` — Gemini signed-thought blob\n * Other providers can add their own keys without colliding.\n */\n providerMeta?: Record<string, unknown>;\n}\n\nexport interface ToolResultBlock {\n type: 'tool_result';\n tool_use_id: string;\n /**\n * The original tool name. Useful for providers like Google Gemini that\n * need the tool name in `functionResponse.name` — the tool_use_id is\n * only a session-local identifier and is not stable across replays.\n * Always set by ToolExecutor; may be absent on manually-constructed blocks.\n */\n name?: string;\n content: string;\n is_error?: boolean;\n}\n\nexport interface ImageBlock {\n type: 'image';\n source: {\n type: 'base64' | 'url';\n media_type?: string;\n data?: string;\n url?: string;\n };\n}\n\nexport type ContentBlock = TextBlock | ToolUseBlock | ToolResultBlock | ImageBlock;\n\nexport function isTextBlock(b: ContentBlock): b is TextBlock {\n return b.type === 'text';\n}\nexport function isToolUseBlock(b: ContentBlock): b is ToolUseBlock {\n return b.type === 'tool_use';\n}\nexport function isToolResultBlock(b: ContentBlock): b is ToolResultBlock {\n return b.type === 'tool_result';\n}\nexport function isImageBlock(b: ContentBlock): b is ImageBlock {\n return b.type === 'image';\n}\n","import type { ContentBlock } from './blocks.js';\n\nexport type MessageRole = 'user' | 'assistant' | 'system';\n\nexport interface Message {\n role: MessageRole;\n content: string | ContentBlock[];\n}\n\nexport function asBlocks(content: string | ContentBlock[]): ContentBlock[] {\n return typeof content === 'string' ? [{ type: 'text', text: content }] : content;\n}\n\nexport function asText(content: string | ContentBlock[]): string {\n if (typeof content === 'string') return content;\n return content\n .filter((b) => b.type === 'text')\n .map((b) => (b as { text: string }).text)\n .join('');\n}\n","/**\r\n * WrongStack error hierarchy.\r\n *\r\n * Every error thrown by the framework is a `WrongStackError` with a\r\n * machine-readable `code`, a `subsystem` tag, and a `severity` level.\r\n * This lets consumers (CLI, TUI, plugins, tests) branch on structured\r\n * data instead of parsing error messages.\r\n */\r\n\r\n// ── Error codes ──────────────────────────────────────────────────────\r\n\r\nexport type ErrorCode =\r\n // Provider\r\n | 'PROVIDER_RATE_LIMITED'\r\n | 'PROVIDER_AUTH_FAILED'\r\n | 'PROVIDER_OVERLOADED'\r\n | 'PROVIDER_INVALID_REQUEST'\r\n | 'PROVIDER_SERVER_ERROR'\r\n | 'PROVIDER_NETWORK_ERROR'\r\n | 'PROVIDER_CONTEXT_OVERFLOW'\r\n // Tool\r\n | 'TOOL_NOT_FOUND'\r\n | 'TOOL_PERMISSION_DENIED'\r\n | 'TOOL_EXECUTION_FAILED'\r\n | 'TOOL_TIMEOUT'\r\n | 'TOOL_INPUT_INVALID'\r\n // Config\r\n | 'CONFIG_INVALID'\r\n | 'CONFIG_NOT_FOUND'\r\n | 'CONFIG_PARSE_FAILED'\r\n | 'CONFIG_MIGRATION_NEEDED'\r\n // Plugin\r\n | 'PLUGIN_LOAD_FAILED'\r\n | 'PLUGIN_API_MISMATCH'\r\n | 'PLUGIN_MISSING_DEPENDENCY'\r\n // Agent\r\n | 'AGENT_ITERATION_LIMIT'\r\n | 'AGENT_CONTEXT_OVERFLOW'\r\n | 'AGENT_ABORTED'\r\n | 'AGENT_RUN_FAILED'\r\n // Session\r\n | 'SESSION_NOT_FOUND'\r\n | 'SESSION_CORRUPTED'\r\n | 'SESSION_WRITE_FAILED'\r\n // Container / Registry\r\n | 'CONTAINER_TOKEN_ALREADY_BOUND'\r\n | 'CONTAINER_TOKEN_NOT_BOUND'\r\n | 'REGISTRY_DUPLICATE'\r\n | 'REGISTRY_NOT_FOUND'\r\n // General\r\n | 'UNKNOWN';\r\n\r\nexport type ErrorSubsystem = 'provider' | 'tool' | 'config' | 'plugin' | 'agent' | 'session' | 'container' | 'general';\r\nexport type ErrorSeverity = 'fatal' | 'error' | 'warning';\r\n\r\n// ── Base error class ─────────────────────────────────────────────────\r\n\r\nexport class WrongStackError extends Error {\r\n readonly code: ErrorCode;\r\n readonly subsystem: ErrorSubsystem;\r\n readonly severity: ErrorSeverity;\r\n readonly recoverable: boolean;\r\n readonly context?: Record<string, unknown>;\r\n\r\n constructor(opts: {\r\n message: string;\r\n code: ErrorCode;\r\n subsystem: ErrorSubsystem;\r\n severity?: ErrorSeverity;\r\n recoverable?: boolean;\r\n context?: Record<string, unknown>;\r\n cause?: unknown;\r\n }) {\r\n super(opts.message, { cause: opts.cause });\r\n this.name = 'WrongStackError';\r\n this.code = opts.code;\r\n this.subsystem = opts.subsystem;\r\n this.severity = opts.severity ?? 'error';\r\n this.recoverable = opts.recoverable ?? false;\r\n this.context = opts.context;\r\n }\r\n\r\n /**\r\n * Render a one-line user-facing description.\r\n * Subclasses should override for domain-specific formatting.\r\n */\r\n describe(): string {\r\n const ctx = this.context ? ` ${formatContext(this.context)}` : '';\r\n return `${this.code}: ${this.message}${ctx}`;\r\n }\r\n}\r\n\r\nfunction formatContext(ctx: Record<string, unknown>): string {\r\n const parts = Object.entries(ctx)\r\n .filter(([, v]) => v !== undefined)\r\n .slice(0, 3)\r\n .map(([k, v]) => `${k}=${String(v)}`);\r\n return parts.length > 0 ? `[${parts.join(' ')}]` : '';\r\n}\r\n\r\n// ── Specific error classes ───────────────────────────────────────────\r\n\r\n/**\r\n * Tool execution errors — thrown by ToolExecutor and individual tools.\r\n */\r\nexport class ToolError extends WrongStackError {\r\n readonly toolName: string;\r\n\r\n constructor(opts: {\r\n message: string;\r\n code: Extract<ErrorCode, 'TOOL_NOT_FOUND' | 'TOOL_PERMISSION_DENIED' | 'TOOL_EXECUTION_FAILED' | 'TOOL_TIMEOUT' | 'TOOL_INPUT_INVALID'>;\r\n toolName: string;\r\n recoverable?: boolean;\r\n context?: Record<string, unknown>;\r\n cause?: unknown;\r\n }) {\r\n super({\r\n message: opts.message,\r\n code: opts.code,\r\n subsystem: 'tool',\r\n recoverable: opts.recoverable,\r\n context: { tool: opts.toolName, ...opts.context },\r\n cause: opts.cause,\r\n });\r\n this.name = 'ToolError';\r\n this.toolName = opts.toolName;\r\n }\r\n}\r\n\r\n/**\r\n * Config loading / validation errors.\r\n */\r\nexport class ConfigError extends WrongStackError {\r\n constructor(opts: {\r\n message: string;\r\n code: Extract<ErrorCode, 'CONFIG_INVALID' | 'CONFIG_NOT_FOUND' | 'CONFIG_PARSE_FAILED' | 'CONFIG_MIGRATION_NEEDED'>;\r\n context?: Record<string, unknown>;\r\n cause?: unknown;\r\n }) {\r\n super({\r\n message: opts.message,\r\n code: opts.code,\r\n subsystem: 'config',\r\n severity: 'fatal',\r\n recoverable: false,\r\n context: opts.context,\r\n cause: opts.cause,\r\n });\r\n this.name = 'ConfigError';\r\n }\r\n}\r\n\r\n/**\r\n * Plugin loading / lifecycle errors.\r\n */\r\nexport class PluginError extends WrongStackError {\r\n readonly pluginName: string;\r\n\r\n constructor(opts: {\r\n message: string;\r\n code: Extract<ErrorCode, 'PLUGIN_LOAD_FAILED' | 'PLUGIN_API_MISMATCH' | 'PLUGIN_MISSING_DEPENDENCY'>;\r\n pluginName: string;\r\n context?: Record<string, unknown>;\r\n cause?: unknown;\r\n }) {\r\n super({\r\n message: opts.message,\r\n code: opts.code,\r\n subsystem: 'plugin',\r\n severity: 'error',\r\n recoverable: opts.code === 'PLUGIN_MISSING_DEPENDENCY',\r\n context: { plugin: opts.pluginName, ...opts.context },\r\n cause: opts.cause,\r\n });\r\n this.name = 'PluginError';\r\n this.pluginName = opts.pluginName;\r\n }\r\n}\r\n\r\n/**\r\n * Agent runtime errors — thrown by Agent.run when a non-WrongStackError\r\n * escapes the inner loop, so callers always see a structured error.\r\n */\r\nexport class AgentError extends WrongStackError {\r\n constructor(opts: {\r\n message: string;\r\n code: Extract<ErrorCode, 'AGENT_ITERATION_LIMIT' | 'AGENT_CONTEXT_OVERFLOW' | 'AGENT_ABORTED' | 'AGENT_RUN_FAILED'>;\r\n recoverable?: boolean;\r\n context?: Record<string, unknown>;\r\n cause?: unknown;\r\n }) {\r\n super({\r\n message: opts.message,\r\n code: opts.code,\r\n subsystem: 'agent',\r\n severity: opts.code === 'AGENT_ABORTED' ? 'warning' : 'error',\r\n recoverable: opts.recoverable ?? opts.code === 'AGENT_ITERATION_LIMIT',\r\n context: opts.context,\r\n cause: opts.cause,\r\n });\r\n this.name = 'AgentError';\r\n }\r\n}\r\n\r\n/**\r\n * Wrap an arbitrary thrown value into a `WrongStackError` so the caller\r\n * always gets a structured error. Pass-throughs WrongStackError instances\r\n * unchanged; raw `Error`s and primitives get an `AGENT_RUN_FAILED` wrapper\r\n * with the original preserved as `cause`.\r\n */\r\nexport function toWrongStackError(err: unknown, code: Extract<ErrorCode, 'AGENT_RUN_FAILED' | 'AGENT_ABORTED' | 'UNKNOWN'> = 'AGENT_RUN_FAILED'): WrongStackError {\r\n if (err instanceof WrongStackError) return err;\r\n const message = err instanceof Error ? err.message : String(err);\r\n return new AgentError({\r\n message,\r\n code: code === 'UNKNOWN' ? 'AGENT_RUN_FAILED' : code,\r\n cause: err,\r\n });\r\n}\r\n\r\n/**\r\n * Session storage errors.\r\n */\r\nexport class SessionError extends WrongStackError {\r\n readonly sessionId?: string;\r\n\r\n constructor(opts: {\r\n message: string;\r\n code: Extract<ErrorCode, 'SESSION_NOT_FOUND' | 'SESSION_CORRUPTED' | 'SESSION_WRITE_FAILED'>;\r\n sessionId?: string;\r\n context?: Record<string, unknown>;\r\n cause?: unknown;\r\n }) {\r\n super({\r\n message: opts.message,\r\n code: opts.code,\r\n subsystem: 'session',\r\n severity: opts.code === 'SESSION_WRITE_FAILED' ? 'error' : 'warning',\r\n recoverable: opts.code !== 'SESSION_CORRUPTED',\r\n context: { sessionId: opts.sessionId, ...opts.context },\r\n cause: opts.cause,\r\n });\r\n this.name = 'SessionError';\r\n this.sessionId = opts.sessionId;\r\n }\r\n}\r\n\r\n// ── Type guards ──────────────────────────────────────────────────────\r\n\r\nexport function isWrongStackError(err: unknown): err is WrongStackError {\r\n return err instanceof WrongStackError;\r\n}\r\n\r\nexport function isToolError(err: unknown): err is ToolError {\r\n return err instanceof ToolError;\r\n}\r\n\r\nexport function isConfigError(err: unknown): err is ConfigError {\r\n return err instanceof ConfigError;\r\n}\r\n\r\nexport function isPluginError(err: unknown): err is PluginError {\r\n return err instanceof PluginError;\r\n}\r\n\r\nexport function isSessionError(err: unknown): err is SessionError {\r\n return err instanceof SessionError;\r\n}\r\n\r\nexport function isAgentError(err: unknown): err is AgentError {\r\n return err instanceof AgentError;\r\n}\r\n","import type { ContentBlock, TextBlock } from './blocks.js';\r\nimport type { Message } from './messages.js';\r\nimport type { Tool } from './tool.js';\r\nimport type { ErrorCode } from './errors.js';\r\nimport { WrongStackError } from './errors.js';\r\n\r\nexport interface Usage {\r\n input: number;\r\n output: number;\r\n cacheRead?: number;\r\n cacheWrite?: number;\r\n}\r\n\r\nexport interface Capabilities {\r\n tools: boolean;\r\n parallelTools: boolean;\r\n vision: boolean;\r\n streaming: boolean;\r\n promptCache: boolean;\r\n systemPrompt: boolean;\r\n jsonMode: boolean;\r\n maxContext: number;\r\n cacheControl: 'native' | 'auto' | 'none';\r\n}\r\n\r\nexport interface Request {\r\n model: string;\r\n system?: TextBlock[];\r\n messages: Message[];\r\n tools?: Tool[];\r\n maxTokens: number;\r\n temperature?: number;\r\n topP?: number;\r\n stopSequences?: string[];\r\n toolChoice?: 'auto' | 'required' | 'none' | { type: 'tool'; name: string };\r\n}\r\n\r\nexport type StopReason = 'end_turn' | 'tool_use' | 'max_tokens' | 'stop_sequence' | 'refusal';\r\n\r\nexport interface Response {\r\n content: ContentBlock[];\r\n stopReason: StopReason;\r\n usage: Usage;\r\n model: string;\r\n}\r\n\r\nexport type StreamEvent =\r\n | { type: 'message_start'; model: string }\r\n | { type: 'content_block_start'; kind: 'text' | 'tool_use'; id?: string; name?: string }\r\n | { type: 'content_block_stop'; index: number }\r\n | { type: 'text_delta'; text: string }\r\n | { type: 'tool_use_start'; id: string; name: string }\r\n | { type: 'tool_use_input_delta'; id: string; partial: string }\r\n | { type: 'tool_use_stop'; id: string; input: unknown; providerMeta?: Record<string, unknown> }\r\n | { type: 'message_stop'; stopReason: StopReason; usage: Usage };\r\n\r\nexport interface Provider {\r\n readonly id: string;\r\n readonly capabilities: Capabilities;\r\n /** Canonical streaming entry point. `complete()` defaults to a wrapper that\r\n * aggregates this stream — providers may override for non-streaming wires. */\r\n stream(req: Request, opts: { signal: AbortSignal }): AsyncIterable<StreamEvent>;\r\n complete(req: Request, opts: { signal: AbortSignal }): Promise<Response>;\r\n}\r\n\r\n/**\r\n * Structured body parsed from a provider's HTTP error response. Populated\r\n * best-effort: providers return JSON shaped differently (Anthropic uses\r\n * `{error: {type, message}}`, OpenAI uses `{error: {message, code}}`,\r\n * Google uses `{error: {status, message}}`), so the fields here are the\r\n * intersection that's usable for rendering and routing.\r\n */\r\nexport interface ProviderErrorBody {\r\n /** Provider-specific kind, e.g. \"overloaded_error\", \"rate_limit_error\", \"invalid_request_error\". */\r\n type?: string;\r\n /** Human-readable explanation from the provider. */\r\n message?: string;\r\n /** Provider request id, when present in the body or headers. */\r\n requestId?: string;\r\n /** Parsed Retry-After header (or equivalent body hint) in milliseconds. */\r\n retryAfterMs?: number;\r\n /** The raw response body (truncated), kept for debugging. */\r\n raw?: string;\r\n}\r\n\r\nexport class ProviderError extends WrongStackError {\r\n public readonly status: number;\r\n public readonly retryable: boolean;\r\n public readonly providerId: string;\r\n public readonly body?: ProviderErrorBody;\r\n\r\n constructor(\r\n message: string,\r\n status: number,\r\n retryable: boolean,\r\n providerId: string,\r\n opts: { body?: ProviderErrorBody; cause?: unknown } = {},\r\n ) {\r\n super({\r\n message,\r\n code: providerStatusToCode(status, opts.body?.type),\r\n subsystem: 'provider',\r\n severity: status >= 500 ? 'error' : 'warning',\r\n recoverable: retryable,\r\n context: { providerId, status },\r\n cause: opts.cause,\r\n });\r\n this.name = 'ProviderError';\r\n this.status = status;\r\n this.retryable = retryable;\r\n this.providerId = providerId;\r\n this.body = opts.body;\r\n }\r\n\r\n /**\r\n * Render a one-line, user-facing description. Designed for the CLI/TUI\r\n * status line and the agent's retry warning. Avoids dumping raw JSON\r\n * (which is what users see today when a 529 lands and the log message\r\n * includes the full `{\"type\":\"error\",...}` body).\r\n *\r\n * Examples:\r\n * \"minimax-coding-plan overloaded (529): High traffic detected. Upgrade for highspeed model. [req 06534785201de9c0…]\"\r\n * \"openai rate limited (429): Retry after 12s\"\r\n * \"anthropic invalid request (400): messages.0.role must be one of 'user'|'assistant'\"\r\n * \"groq HTTP 500 (server error)\"\r\n */\r\n override describe(): string {\r\n const kind = describeStatus(this.status, this.body?.type);\r\n const head = `${this.providerId} ${kind}`;\r\n const detail = this.body?.message?.trim();\r\n const reqId = this.body?.requestId\r\n ? ` [req ${this.body.requestId.slice(0, 16)}${this.body.requestId.length > 16 ? '…' : ''}]`\r\n : '';\r\n if (detail && detail.length > 0) {\r\n return `${head}: ${truncate(detail, 240)}${reqId}`;\r\n }\r\n return `${head}${reqId}`;\r\n }\r\n}\r\n\r\nfunction describeStatus(status: number, type?: string): string {\r\n if (status === 0) return 'network error';\r\n if (type === 'overloaded_error' || status === 529) return `overloaded (${status})`;\r\n if (type === 'rate_limit_error' || status === 429) return `rate limited (${status})`;\r\n if (type === 'authentication_error' || status === 401) return `auth failed (${status})`;\r\n if (type === 'permission_error' || status === 403) return `forbidden (${status})`;\r\n if (type === 'not_found_error' || status === 404) return `not found (${status})`;\r\n if (type === 'invalid_request_error' || status === 400) return `invalid request (${status})`;\r\n if (status === 408) return `timeout (${status})`;\r\n if (status >= 500 && status < 600) return `HTTP ${status} (server error)`;\r\n if (type) return `${type} (${status})`;\r\n return `HTTP ${status}`;\r\n}\r\n\r\nfunction truncate(s: string, n: number): string {\r\n return s.length <= n ? s : `${s.slice(0, n - 1)}…`;\r\n}\r\n\r\nfunction providerStatusToCode(status: number, type?: string): ErrorCode {\r\n if (status === 0) return 'PROVIDER_NETWORK_ERROR';\r\n if (type === 'rate_limit_error' || status === 429) return 'PROVIDER_RATE_LIMITED';\r\n if (type === 'authentication_error' || status === 401) return 'PROVIDER_AUTH_FAILED';\r\n if (type === 'overloaded_error' || status === 529) return 'PROVIDER_OVERLOADED';\r\n if (type === 'invalid_request_error' || status === 400) return 'PROVIDER_INVALID_REQUEST';\r\n if (status === 408) return 'PROVIDER_NETWORK_ERROR';\r\n if (status >= 500) return 'PROVIDER_SERVER_ERROR';\r\n return 'PROVIDER_INVALID_REQUEST';\r\n}\r\n","/**\n * SecretVault encrypts secrets-at-rest in config files. The wire format is\n * `enc:v1:<base64-iv>:<base64-tag>:<base64-ciphertext>`. Plaintext strings\n * (those that do not match this prefix) are passed through unchanged so that\n * existing configs and env-var-derived values keep working.\n *\n * The vault is intentionally NOT designed to defeat a determined local\n * attacker who can read both the config file and the key file — that level\n * of secrecy needs the OS keychain. The goal is to keep keys from being\n * visible in screen shares, accidental log captures, and `cat config.json`\n * over someone's shoulder.\n */\nexport interface SecretVault {\n encrypt(plaintext: string): string;\n decrypt(value: string): string;\n isEncrypted(value: string): boolean;\n}\n\nexport const ENCRYPTED_PREFIX = 'enc:v1:';\n","export interface Mode {\n id: string;\n name: string;\n description: string;\n /** Additional prompt text injected into system prompt when mode is active */\n prompt: string;\n /** Tags for tool_search filtering */\n tags?: string[];\n /** Tools that should be prioritized/highlighted when this mode is active */\n toolPreferences?: string[];\n}\n\nexport interface ModeManifest {\n modes: Mode[];\n defaultMode?: string;\n}\n\nexport interface ModeStore {\n getActiveMode(): Promise<Mode | null>;\n setActiveMode(modeId: string | null): Promise<void>;\n listModes(): Promise<Mode[]>;\n getMode(modeId: string): Promise<Mode | null>;\n}\n\nexport interface ModeConfig {\n directory: string;\n}\n\nexport const DEFAULT_MODES: Mode[] = [\n {\n id: 'default',\n name: 'Default',\n description: 'General-purpose coding assistant',\n prompt: '',\n tags: ['general'],\n },\n {\n id: 'code-reviewer',\n name: 'Code Reviewer',\n description: 'Focus on code quality, best practices, and potential bugs',\n prompt: `## Code Reviewer Mode\n\nWhen reviewing code:\n- Look for potential bugs, race conditions, and edge cases\n- Check for security vulnerabilities (SQL injection, XSS, CSRF, etc.)\n- Evaluate error handling completeness\n- Assess code readability and maintainability\n- Check for performance anti-patterns\n- Verify test coverage for critical paths\n- Ensure naming conventions are followed`,\n tags: ['review', 'quality', 'security'],\n toolPreferences: ['read', 'grep', 'git', 'diff', 'test'],\n },\n {\n id: 'code-auditor',\n name: 'Code Auditor',\n description: 'Security-focused code analysis',\n prompt: `## Code Auditor Mode\n\nWhen auditing code for security:\n- Identify injection vulnerabilities (SQL, Command, XSS, LDAP)\n- Check authentication and authorization patterns\n- Look for sensitive data exposure (secrets, PII in logs)\n- Verify cryptographic implementations\n- Check for insecure dependencies or configurations\n- Assess input validation and output encoding\n- Look for timing attacks and information leakage`,\n tags: ['security', 'audit', 'compliance'],\n toolPreferences: ['grep', 'read', 'audit', 'bash'],\n },\n {\n id: 'architect',\n name: 'Software Architect',\n description: 'Design patterns, scalability, and system design',\n prompt: `## Architect Mode\n\nWhen designing or reviewing architecture:\n- Evaluate scalability and future growth\n- Check for appropriate design patterns\n- Assess coupling and cohesion\n- Look forSOLID principle violations\n- Evaluate data modeling decisions\n- Check for eventual consistency issues\n- Assess API design and contract stability\n- Consider operational aspects (monitoring, logging, deployment)`,\n tags: ['architecture', 'design', 'scalability'],\n toolPreferences: ['read', 'glob', 'tree', 'diff'],\n },\n {\n id: 'debugger',\n name: 'Debugger',\n description: 'Root cause analysis and error investigation',\n prompt: `## Debugger Mode\n\nWhen investigating bugs:\n- Reproduce the issue with minimal steps\n- Check error messages and stack traces thoroughly\n- Look for related logs and historical context\n- Verify assumptions about data flow\n- Check for race conditions in async code\n- Validate environment and configuration\n- Use binary search to isolate the root cause\n- Verify fixes with tests before considering done`,\n tags: ['debug', 'investigation', 'error-resolution'],\n toolPreferences: ['read', 'grep', 'bash', 'logs', 'test'],\n },\n {\n id: 'tester',\n name: 'QA Engineer',\n description: 'Test coverage, edge cases, and quality assurance',\n prompt: `## Tester Mode\n\nWhen testing or writing tests:\n- Cover happy path and error paths equally\n- Think about edge cases and boundary conditions\n- Check for missing null/undefined handling tests\n- Verify error messages are tested\n- Look for race condition tests in async code\n- Assess mutation testing opportunities\n- Check for integration test gaps\n- Verify test isolation and cleanup`,\n tags: ['testing', 'qa', 'quality'],\n toolPreferences: ['read', 'grep', 'test', 'bash'],\n },\n {\n id: 'devops',\n name: 'DevOps Engineer',\n description: 'Infrastructure, deployment, and operations',\n prompt: `## DevOps Mode\n\nWhen working on infrastructure:\n- Check for containerization and deployment readiness\n- Verify CI/CD pipeline configurations\n- Assess monitoring and alerting setup\n- Look for health check endpoints\n- Check for graceful shutdown handling\n- Verify backup and disaster recovery plans\n- Assess secrets management\n- Check for resource limits and quotas`,\n tags: ['devops', 'infrastructure', 'operations'],\n toolPreferences: ['read', 'bash', 'grep', 'logs', 'git'],\n },\n {\n id: 'refactorer',\n name: 'Refactorer',\n description: 'Code improvement and modernization',\n prompt: `## Refactorer Mode\n\nWhen refactoring code:\n- Maintain existing behavior — tests must pass before and after\n- Make one change at a time, verify after each\n- Prefer small, focused commits\n- Preserve API contracts unless explicitly changing\n- Remove dead code and comments\n- Improve naming as you go\n- Don't mix formatting changes with logic changes\n- Keep performance in mind — don't regress`,\n tags: ['refactor', 'modernization', 'improvement'],\n toolPreferences: ['read', 'edit', 'test', 'git', 'grep'],\n },\n];","export type SpecStatus = 'draft' | 'review' | 'approved' | 'implemented' | 'deprecated';\nexport type SpecSectionType = 'overview' | 'requirements' | 'architecture' | 'api' | 'data' | 'security' | 'acceptance';\n\nexport interface SpecSection {\n type: SpecSectionType;\n title: string;\n content: string;\n level: number;\n children?: SpecSection[];\n}\n\nexport interface SpecRequirement {\n id: string;\n type: 'functional' | 'non-functional' | 'security' | 'performance' | 'ux';\n priority: 'critical' | 'high' | 'medium' | 'low';\n description: string;\n acceptanceCriteria: string[];\n blockedBy?: string[];\n implements?: string[];\n}\n\nexport interface SpecApiEndpoint {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n path: string;\n description: string;\n request?: Record<string, unknown>;\n response?: Record<string, unknown>;\n auth?: boolean;\n}\n\nexport interface Specification {\n id: string;\n title: string;\n version: string;\n status: SpecStatus;\n overview: string;\n sections: SpecSection[];\n requirements: SpecRequirement[];\n apiEndpoints?: SpecApiEndpoint[];\n dependencies?: string[];\n createdAt: number;\n updatedAt: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface SpecAnalysis {\n specId: string;\n completeness: number; // 0-100\n coverage: {\n requirements: number;\n apiEndpoints: number;\n edgeCases: number;\n errorHandling: number;\n };\n gaps: string[];\n risks: { requirement: string; risk: string; severity: 'high' | 'medium' | 'low' }[];\n suggestions: string[];\n}\n\nexport interface SpecValidationResult {\n valid: boolean;\n errors: { path: string; message: string }[];\n warnings: { path: string; message: string }[];\n}\n\nexport interface SpecTemplate {\n id: string;\n name: string;\n description: string;\n sections: Omit<SpecSection, 'content'>[];\n defaultRequirements: Omit<SpecRequirement, 'id' | 'description'>[];\n}\n\nexport const DEFAULT_SPEC_TEMPLATE: SpecTemplate = {\n id: 'default',\n name: 'Default Feature Spec',\n description: 'Standard template for feature specifications',\n sections: [\n { type: 'overview', title: 'Overview', level: 1 },\n { type: 'requirements', title: 'Requirements', level: 1 },\n { type: 'architecture', title: 'Architecture', level: 1 },\n { type: 'api', title: 'API Design', level: 1 },\n { type: 'data', title: 'Data Model', level: 1 },\n { type: 'security', title: 'Security', level: 1 },\n { type: 'acceptance', title: 'Acceptance Criteria', level: 1 },\n ],\n defaultRequirements: [\n { type: 'functional', priority: 'high', acceptanceCriteria: [], blockedBy: [], implements: [] },\n { type: 'non-functional', priority: 'medium', acceptanceCriteria: [], blockedBy: [], implements: [] },\n ],\n};","export type TaskStatus = 'pending' | 'in_progress' | 'blocked' | 'failed' | 'review' | 'completed';\nexport type TaskPriority = 'critical' | 'high' | 'medium' | 'low';\nexport type TaskType = 'feature' | 'bugfix' | 'refactor' | 'docs' | 'test' | 'chore';\n\nexport interface TaskNode {\n id: string;\n title: string;\n description: string;\n type: TaskType;\n priority: TaskPriority;\n status: TaskStatus;\n assignee?: string;\n estimateHours?: number;\n actualHours?: number;\n tags?: string[];\n specRequirementId?: string;\n parentId?: string;\n children?: string[];\n createdAt: number;\n updatedAt: number;\n completedAt?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface TaskEdge {\n id: string;\n from: string;\n to: string;\n type: 'blocks' | 'depends_on' | 'relates_to' | 'implements';\n weight?: number;\n}\n\nexport interface TaskGraph {\n id: string;\n specId: string;\n title: string;\n nodes: Map<string, TaskNode>;\n edges: TaskEdge[];\n rootNodes: string[];\n createdAt: number;\n updatedAt: number;\n}\n\nexport interface TaskDependency {\n taskId: string;\n blockedBy: string[];\n blocking: string[];\n}\n\nexport interface TaskAssignment {\n taskId: string;\n assignee: string;\n assignedAt: number;\n}\n\nexport interface TaskProgress {\n total: number;\n pending: number;\n inProgress: number;\n blocked: number;\n failed: number;\n review: number;\n completed: number;\n percentComplete: number;\n estimatedHours: number;\n actualHours: number;\n}\n\nexport interface TaskFilter {\n status?: TaskStatus[];\n priority?: TaskPriority[];\n type?: TaskType[];\n assignee?: string[];\n tags?: string[];\n specRequirementId?: string;\n}\n\nexport interface TaskSort {\n field: 'priority' | 'createdAt' | 'updatedAt' | 'status';\n direction: 'asc' | 'desc';\n}\n\nexport interface CriticalPathResult {\n taskIds: string[];\n totalEstimateHours: number;\n bottleneckTasks: string[];\n}\n\nexport function computeTaskProgress(graph: TaskGraph): TaskProgress {\n const nodes = Array.from(graph.nodes.values());\n const total = nodes.length;\n const completed = nodes.filter((n) => n.status === 'completed').length;\n const pending = nodes.filter((n) => n.status === 'pending').length;\n const inProgress = nodes.filter((n) => n.status === 'in_progress').length;\n const blocked = nodes.filter((n) => n.status === 'blocked').length;\n const failed = nodes.filter((n) => n.status === 'failed').length;\n const review = nodes.filter((n) => n.status === 'review').length;\n\n const estimatedHours = nodes.reduce((sum, n) => sum + (n.estimateHours ?? 0), 0);\n const actualHours = nodes.reduce((sum, n) => sum + (n.actualHours ?? 0), 0);\n\n return {\n total,\n pending,\n inProgress,\n blocked,\n failed,\n review,\n completed,\n percentComplete: total > 0 ? Math.round((completed / total) * 100) : 0,\n estimatedHours,\n actualHours,\n };\n}\n\nexport function findCriticalPath(graph: TaskGraph): CriticalPathResult {\n const nodes = Array.from(graph.nodes.values());\n const criticalNodes = nodes.filter((n) => n.priority === 'critical');\n const bottleneckTasks = criticalNodes\n .filter((n) => graph.edges.some((e) => e.to === n.id && e.type === 'depends_on'))\n .map((n) => n.id);\n\n const totalEstimateHours = criticalNodes.reduce((sum, n) => sum + (n.estimateHours ?? 0), 0);\n\n return {\n taskIds: criticalNodes.map((n) => n.id),\n totalEstimateHours,\n bottleneckTasks,\n };\n}\n\nexport function topologicalSort(graph: TaskGraph): string[] {\n const visited = new Set<string>();\n const result: string[] = [];\n\n function visit(id: string) {\n if (visited.has(id)) return;\n visited.add(id);\n\n const node = graph.nodes.get(id);\n if (!node) return;\n\n const outgoing = graph.edges.filter((e) => e.from === id);\n for (const edge of outgoing) {\n visit(edge.to);\n }\n\n result.push(id);\n }\n\n for (const rootId of graph.rootNodes) {\n visit(rootId);\n }\n\n return result;\n}"]}
1
+ {"version":3,"sources":["../../src/types/blocks.ts","../../src/types/messages.ts","../../src/types/errors.ts","../../src/types/provider.ts","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EAAkB;AAE/B,IAAA,IAAI,OAAA,CAAQ,GAAA,CAAI,EAAE,CAAA,EAAG;AACrB,IAAA,IAAI,OAAA,CAAQ,GAAA,CAAI,EAAE,CAAA,EAAG;AACrB,IAAA,IAAI,CAAC,KAAA,CAAM,KAAA,CAAM,GAAA,CAAI,EAAE,CAAA,EAAG;AAE1B,IAAA,OAAA,CAAQ,IAAI,EAAE,CAAA;AACd,IAAA,OAAA,CAAQ,IAAI,EAAE,CAAA;AAEd,IAAA,KAAA,MAAW,IAAA,IAAQ,MAAM,KAAA,EAAO;AAC9B,MAAA,IAAI,IAAA,CAAK,IAAA,KAAS,EAAA,EAAI,KAAA,CAAM,KAAK,EAAE,CAAA;AAAA,IACrC;AAEA,IAAA,OAAA,CAAQ,OAAO,EAAE,CAAA;AACjB,IAAA,MAAA,CAAO,KAAK,EAAE,CAAA;AAAA,EAChB;AAEA,EAAA,KAAA,MAAW,MAAA,IAAU,MAAM,SAAA,EAAW;AACpC,IAAA,KAAA,CAAM,MAAM,CAAA;AAAA,EACd;AAEA,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["export interface TextBlock {\n type: 'text';\n text: string;\n cache_control?: { type: 'ephemeral' };\n}\n\nexport interface ToolUseBlock {\n type: 'tool_use';\n id: string;\n name: string;\n input: Record<string, unknown>;\n /**\n * Provider-specific opaque metadata captured from the wire response.\n * Echoed back verbatim in the next request so providers that bind\n * extra state to function calls keep working. Example: Gemini's\n * `thoughtSignature` — required for tool-use turns with thinking\n * models, otherwise the next request fails with 400 \"Function call\n * is missing a thought_signature in functionCall parts\".\n *\n * Keys are namespaced by intent so multiple wires can coexist:\n * - `google.thoughtSignature` — Gemini signed-thought blob\n * Other providers can add their own keys without colliding.\n */\n providerMeta?: Record<string, unknown>;\n}\n\nexport interface ToolResultBlock {\n type: 'tool_result';\n tool_use_id: string;\n /**\n * The original tool name. Useful for providers like Google Gemini that\n * need the tool name in `functionResponse.name` — the tool_use_id is\n * only a session-local identifier and is not stable across replays.\n * Always set by ToolExecutor; may be absent on manually-constructed blocks.\n */\n name?: string;\n content: string;\n is_error?: boolean;\n}\n\nexport interface ImageBlock {\n type: 'image';\n source: {\n type: 'base64' | 'url';\n media_type?: string;\n data?: string;\n url?: string;\n };\n}\n\nexport type ContentBlock = TextBlock | ToolUseBlock | ToolResultBlock | ImageBlock;\n\nexport function isTextBlock(b: ContentBlock): b is TextBlock {\n return b.type === 'text';\n}\nexport function isToolUseBlock(b: ContentBlock): b is ToolUseBlock {\n return b.type === 'tool_use';\n}\nexport function isToolResultBlock(b: ContentBlock): b is ToolResultBlock {\n return b.type === 'tool_result';\n}\nexport function isImageBlock(b: ContentBlock): b is ImageBlock {\n return b.type === 'image';\n}\n","import type { ContentBlock } from './blocks.js';\n\nexport type MessageRole = 'user' | 'assistant' | 'system';\n\nexport interface Message {\n role: MessageRole;\n content: string | ContentBlock[];\n}\n\nexport function asBlocks(content: string | ContentBlock[]): ContentBlock[] {\n return typeof content === 'string' ? [{ type: 'text', text: content }] : content;\n}\n\nexport function asText(content: string | ContentBlock[]): string {\n if (typeof content === 'string') return content;\n return content\n .filter((b) => b.type === 'text')\n .map((b) => (b as { text: string }).text)\n .join('');\n}\n","/**\r\n * WrongStack error hierarchy.\r\n *\r\n * Every error thrown by the framework is a `WrongStackError` with a\r\n * machine-readable `code`, a `subsystem` tag, and a `severity` level.\r\n * This lets consumers (CLI, TUI, plugins, tests) branch on structured\r\n * data instead of parsing error messages.\r\n */\r\n\r\n// ── Error codes ──────────────────────────────────────────────────────\r\n\r\nexport type ErrorCode =\r\n // Provider\r\n | 'PROVIDER_RATE_LIMITED'\r\n | 'PROVIDER_AUTH_FAILED'\r\n | 'PROVIDER_OVERLOADED'\r\n | 'PROVIDER_INVALID_REQUEST'\r\n | 'PROVIDER_SERVER_ERROR'\r\n | 'PROVIDER_NETWORK_ERROR'\r\n | 'PROVIDER_CONTEXT_OVERFLOW'\r\n // Tool\r\n | 'TOOL_NOT_FOUND'\r\n | 'TOOL_PERMISSION_DENIED'\r\n | 'TOOL_EXECUTION_FAILED'\r\n | 'TOOL_TIMEOUT'\r\n | 'TOOL_INPUT_INVALID'\r\n // Config\r\n | 'CONFIG_INVALID'\r\n | 'CONFIG_NOT_FOUND'\r\n | 'CONFIG_PARSE_FAILED'\r\n | 'CONFIG_MIGRATION_NEEDED'\r\n // Plugin\r\n | 'PLUGIN_LOAD_FAILED'\r\n | 'PLUGIN_API_MISMATCH'\r\n | 'PLUGIN_MISSING_DEPENDENCY'\r\n // Agent\r\n | 'AGENT_ITERATION_LIMIT'\r\n | 'AGENT_CONTEXT_OVERFLOW'\r\n | 'AGENT_ABORTED'\r\n | 'AGENT_RUN_FAILED'\r\n // Session\r\n | 'SESSION_NOT_FOUND'\r\n | 'SESSION_CORRUPTED'\r\n | 'SESSION_WRITE_FAILED'\r\n // Container / Registry\r\n | 'CONTAINER_TOKEN_ALREADY_BOUND'\r\n | 'CONTAINER_TOKEN_NOT_BOUND'\r\n | 'REGISTRY_DUPLICATE'\r\n | 'REGISTRY_NOT_FOUND'\r\n // General\r\n | 'UNKNOWN';\r\n\r\nexport type ErrorSubsystem = 'provider' | 'tool' | 'config' | 'plugin' | 'agent' | 'session' | 'container' | 'general';\r\nexport type ErrorSeverity = 'fatal' | 'error' | 'warning';\r\n\r\n// ── Base error class ─────────────────────────────────────────────────\r\n\r\nexport class WrongStackError extends Error {\r\n readonly code: ErrorCode;\r\n readonly subsystem: ErrorSubsystem;\r\n readonly severity: ErrorSeverity;\r\n readonly recoverable: boolean;\r\n readonly context?: Record<string, unknown>;\r\n\r\n constructor(opts: {\r\n message: string;\r\n code: ErrorCode;\r\n subsystem: ErrorSubsystem;\r\n severity?: ErrorSeverity;\r\n recoverable?: boolean;\r\n context?: Record<string, unknown>;\r\n cause?: unknown;\r\n }) {\r\n super(opts.message, { cause: opts.cause });\r\n this.name = 'WrongStackError';\r\n this.code = opts.code;\r\n this.subsystem = opts.subsystem;\r\n this.severity = opts.severity ?? 'error';\r\n this.recoverable = opts.recoverable ?? false;\r\n this.context = opts.context;\r\n }\r\n\r\n /**\r\n * Render a one-line user-facing description.\r\n * Subclasses should override for domain-specific formatting.\r\n */\r\n describe(): string {\r\n const ctx = this.context ? ` ${formatContext(this.context)}` : '';\r\n return `${this.code}: ${this.message}${ctx}`;\r\n }\r\n}\r\n\r\nfunction formatContext(ctx: Record<string, unknown>): string {\r\n const parts = Object.entries(ctx)\r\n .filter(([, v]) => v !== undefined)\r\n .slice(0, 3)\r\n .map(([k, v]) => `${k}=${String(v)}`);\r\n return parts.length > 0 ? `[${parts.join(' ')}]` : '';\r\n}\r\n\r\n// ── Specific error classes ───────────────────────────────────────────\r\n\r\n/**\r\n * Tool execution errors — thrown by ToolExecutor and individual tools.\r\n */\r\nexport class ToolError extends WrongStackError {\r\n readonly toolName: string;\r\n\r\n constructor(opts: {\r\n message: string;\r\n code: Extract<ErrorCode, 'TOOL_NOT_FOUND' | 'TOOL_PERMISSION_DENIED' | 'TOOL_EXECUTION_FAILED' | 'TOOL_TIMEOUT' | 'TOOL_INPUT_INVALID'>;\r\n toolName: string;\r\n recoverable?: boolean;\r\n context?: Record<string, unknown>;\r\n cause?: unknown;\r\n }) {\r\n super({\r\n message: opts.message,\r\n code: opts.code,\r\n subsystem: 'tool',\r\n recoverable: opts.recoverable,\r\n context: { tool: opts.toolName, ...opts.context },\r\n cause: opts.cause,\r\n });\r\n this.name = 'ToolError';\r\n this.toolName = opts.toolName;\r\n }\r\n}\r\n\r\n/**\r\n * Config loading / validation errors.\r\n */\r\nexport class ConfigError extends WrongStackError {\r\n constructor(opts: {\r\n message: string;\r\n code: Extract<ErrorCode, 'CONFIG_INVALID' | 'CONFIG_NOT_FOUND' | 'CONFIG_PARSE_FAILED' | 'CONFIG_MIGRATION_NEEDED'>;\r\n context?: Record<string, unknown>;\r\n cause?: unknown;\r\n }) {\r\n super({\r\n message: opts.message,\r\n code: opts.code,\r\n subsystem: 'config',\r\n severity: 'fatal',\r\n recoverable: false,\r\n context: opts.context,\r\n cause: opts.cause,\r\n });\r\n this.name = 'ConfigError';\r\n }\r\n}\r\n\r\n/**\r\n * Plugin loading / lifecycle errors.\r\n */\r\nexport class PluginError extends WrongStackError {\r\n readonly pluginName: string;\r\n\r\n constructor(opts: {\r\n message: string;\r\n code: Extract<ErrorCode, 'PLUGIN_LOAD_FAILED' | 'PLUGIN_API_MISMATCH' | 'PLUGIN_MISSING_DEPENDENCY'>;\r\n pluginName: string;\r\n context?: Record<string, unknown>;\r\n cause?: unknown;\r\n }) {\r\n super({\r\n message: opts.message,\r\n code: opts.code,\r\n subsystem: 'plugin',\r\n severity: 'error',\r\n recoverable: opts.code === 'PLUGIN_MISSING_DEPENDENCY',\r\n context: { plugin: opts.pluginName, ...opts.context },\r\n cause: opts.cause,\r\n });\r\n this.name = 'PluginError';\r\n this.pluginName = opts.pluginName;\r\n }\r\n}\r\n\r\n/**\r\n * Agent runtime errors — thrown by Agent.run when a non-WrongStackError\r\n * escapes the inner loop, so callers always see a structured error.\r\n */\r\nexport class AgentError extends WrongStackError {\r\n constructor(opts: {\r\n message: string;\r\n code: Extract<ErrorCode, 'AGENT_ITERATION_LIMIT' | 'AGENT_CONTEXT_OVERFLOW' | 'AGENT_ABORTED' | 'AGENT_RUN_FAILED'>;\r\n recoverable?: boolean;\r\n context?: Record<string, unknown>;\r\n cause?: unknown;\r\n }) {\r\n super({\r\n message: opts.message,\r\n code: opts.code,\r\n subsystem: 'agent',\r\n severity: opts.code === 'AGENT_ABORTED' ? 'warning' : 'error',\r\n recoverable: opts.recoverable ?? opts.code === 'AGENT_ITERATION_LIMIT',\r\n context: opts.context,\r\n cause: opts.cause,\r\n });\r\n this.name = 'AgentError';\r\n }\r\n}\r\n\r\n/**\r\n * Wrap an arbitrary thrown value into a `WrongStackError` so the caller\r\n * always gets a structured error. Pass-throughs WrongStackError instances\r\n * unchanged; raw `Error`s and primitives get an `AGENT_RUN_FAILED` wrapper\r\n * with the original preserved as `cause`.\r\n */\r\nexport function toWrongStackError(err: unknown, code: Extract<ErrorCode, 'AGENT_RUN_FAILED' | 'AGENT_ABORTED' | 'UNKNOWN'> = 'AGENT_RUN_FAILED'): WrongStackError {\r\n if (err instanceof WrongStackError) return err;\r\n const message = err instanceof Error ? err.message : String(err);\r\n return new AgentError({\r\n message,\r\n code: code === 'UNKNOWN' ? 'AGENT_RUN_FAILED' : code,\r\n cause: err,\r\n });\r\n}\r\n\r\n/**\r\n * Session storage errors.\r\n */\r\nexport class SessionError extends WrongStackError {\r\n readonly sessionId?: string;\r\n\r\n constructor(opts: {\r\n message: string;\r\n code: Extract<ErrorCode, 'SESSION_NOT_FOUND' | 'SESSION_CORRUPTED' | 'SESSION_WRITE_FAILED'>;\r\n sessionId?: string;\r\n context?: Record<string, unknown>;\r\n cause?: unknown;\r\n }) {\r\n super({\r\n message: opts.message,\r\n code: opts.code,\r\n subsystem: 'session',\r\n severity: opts.code === 'SESSION_WRITE_FAILED' ? 'error' : 'warning',\r\n recoverable: opts.code !== 'SESSION_CORRUPTED',\r\n context: { sessionId: opts.sessionId, ...opts.context },\r\n cause: opts.cause,\r\n });\r\n this.name = 'SessionError';\r\n this.sessionId = opts.sessionId;\r\n }\r\n}\r\n\r\n// ── Type guards ──────────────────────────────────────────────────────\r\n\r\nexport function isWrongStackError(err: unknown): err is WrongStackError {\r\n return err instanceof WrongStackError;\r\n}\r\n\r\nexport function isToolError(err: unknown): err is ToolError {\r\n return err instanceof ToolError;\r\n}\r\n\r\nexport function isConfigError(err: unknown): err is ConfigError {\r\n return err instanceof ConfigError;\r\n}\r\n\r\nexport function isPluginError(err: unknown): err is PluginError {\r\n return err instanceof PluginError;\r\n}\r\n\r\nexport function isSessionError(err: unknown): err is SessionError {\r\n return err instanceof SessionError;\r\n}\r\n\r\nexport function isAgentError(err: unknown): err is AgentError {\r\n return err instanceof AgentError;\r\n}\r\n","import type { ContentBlock, TextBlock } from './blocks.js';\r\nimport type { Message } from './messages.js';\r\nimport type { Tool } from './tool.js';\r\nimport type { ErrorCode } from './errors.js';\r\nimport { WrongStackError } from './errors.js';\r\n\r\nexport interface Usage {\r\n input: number;\r\n output: number;\r\n cacheRead?: number;\r\n cacheWrite?: number;\r\n}\r\n\r\nexport interface Capabilities {\r\n tools: boolean;\r\n parallelTools: boolean;\r\n vision: boolean;\r\n streaming: boolean;\r\n promptCache: boolean;\r\n systemPrompt: boolean;\r\n jsonMode: boolean;\r\n maxContext: number;\r\n cacheControl: 'native' | 'auto' | 'none';\r\n}\r\n\r\nexport interface Request {\r\n model: string;\r\n system?: TextBlock[];\r\n messages: Message[];\r\n tools?: Tool[];\r\n maxTokens: number;\r\n temperature?: number;\r\n topP?: number;\r\n stopSequences?: string[];\r\n toolChoice?: 'auto' | 'required' | 'none' | { type: 'tool'; name: string };\r\n}\r\n\r\nexport type StopReason = 'end_turn' | 'tool_use' | 'max_tokens' | 'stop_sequence' | 'refusal';\r\n\r\nexport interface Response {\r\n content: ContentBlock[];\r\n stopReason: StopReason;\r\n usage: Usage;\r\n model: string;\r\n}\r\n\r\nexport type StreamEvent =\r\n | { type: 'message_start'; model: string }\r\n | { type: 'content_block_start'; kind: 'text' | 'tool_use'; id?: string; name?: string }\r\n | { type: 'content_block_stop'; index: number }\r\n | { type: 'text_delta'; text: string }\r\n | { type: 'tool_use_start'; id: string; name: string }\r\n | { type: 'tool_use_input_delta'; id: string; partial: string }\r\n | { type: 'tool_use_stop'; id: string; input: unknown; providerMeta?: Record<string, unknown> }\r\n | { type: 'message_stop'; stopReason: StopReason; usage: Usage };\r\n\r\nexport interface Provider {\r\n readonly id: string;\r\n readonly capabilities: Capabilities;\r\n /** Canonical streaming entry point. `complete()` defaults to a wrapper that\r\n * aggregates this stream — providers may override for non-streaming wires. */\r\n stream(req: Request, opts: { signal: AbortSignal }): AsyncIterable<StreamEvent>;\r\n complete(req: Request, opts: { signal: AbortSignal }): Promise<Response>;\r\n}\r\n\r\n/**\r\n * Structured body parsed from a provider's HTTP error response. Populated\r\n * best-effort: providers return JSON shaped differently (Anthropic uses\r\n * `{error: {type, message}}`, OpenAI uses `{error: {message, code}}`,\r\n * Google uses `{error: {status, message}}`), so the fields here are the\r\n * intersection that's usable for rendering and routing.\r\n */\r\nexport interface ProviderErrorBody {\r\n /** Provider-specific kind, e.g. \"overloaded_error\", \"rate_limit_error\", \"invalid_request_error\". */\r\n type?: string;\r\n /** Human-readable explanation from the provider. */\r\n message?: string;\r\n /** Provider request id, when present in the body or headers. */\r\n requestId?: string;\r\n /** Parsed Retry-After header (or equivalent body hint) in milliseconds. */\r\n retryAfterMs?: number;\r\n /** The raw response body (truncated to ~2 KB), kept for debugging. */\r\n raw?: string;\r\n /** True when `raw` was truncated; check `rawLength` for the original size. */\r\n truncated?: boolean;\r\n /** Original length of the response body in bytes, when `truncated` is true. */\r\n rawLength?: number;\r\n}\r\n\r\nexport class ProviderError extends WrongStackError {\r\n public readonly status: number;\r\n public readonly retryable: boolean;\r\n public readonly providerId: string;\r\n public readonly body?: ProviderErrorBody;\r\n\r\n constructor(\r\n message: string,\r\n status: number,\r\n retryable: boolean,\r\n providerId: string,\r\n opts: { body?: ProviderErrorBody; cause?: unknown } = {},\r\n ) {\r\n super({\r\n message,\r\n code: providerStatusToCode(status, opts.body?.type),\r\n subsystem: 'provider',\r\n severity: status >= 500 ? 'error' : 'warning',\r\n recoverable: retryable,\r\n context: { providerId, status },\r\n cause: opts.cause,\r\n });\r\n this.name = 'ProviderError';\r\n this.status = status;\r\n this.retryable = retryable;\r\n this.providerId = providerId;\r\n this.body = opts.body;\r\n }\r\n\r\n /**\r\n * Render a one-line, user-facing description. Designed for the CLI/TUI\r\n * status line and the agent's retry warning. Avoids dumping raw JSON\r\n * (which is what users see today when a 529 lands and the log message\r\n * includes the full `{\"type\":\"error\",...}` body).\r\n *\r\n * Examples:\r\n * \"minimax-coding-plan overloaded (529): High traffic detected. Upgrade for highspeed model. [req 06534785201de9c0…]\"\r\n * \"openai rate limited (429): Retry after 12s\"\r\n * \"anthropic invalid request (400): messages.0.role must be one of 'user'|'assistant'\"\r\n * \"groq HTTP 500 (server error)\"\r\n */\r\n override describe(): string {\r\n const kind = describeStatus(this.status, this.body?.type);\r\n const head = `${this.providerId} ${kind}`;\r\n const detail = this.body?.message?.trim();\r\n const reqId = this.body?.requestId\r\n ? ` [req ${this.body.requestId.slice(0, 16)}${this.body.requestId.length > 16 ? '…' : ''}]`\r\n : '';\r\n if (detail && detail.length > 0) {\r\n return `${head}: ${truncate(detail, 240)}${reqId}`;\r\n }\r\n return `${head}${reqId}`;\r\n }\r\n}\r\n\r\nfunction describeStatus(status: number, type?: string): string {\r\n if (status === 0) return 'network error';\r\n if (type === 'overloaded_error' || status === 529) return `overloaded (${status})`;\r\n if (type === 'rate_limit_error' || status === 429) return `rate limited (${status})`;\r\n if (type === 'authentication_error' || status === 401) return `auth failed (${status})`;\r\n if (type === 'permission_error' || status === 403) return `forbidden (${status})`;\r\n if (type === 'not_found_error' || status === 404) return `not found (${status})`;\r\n if (type === 'invalid_request_error' || status === 400) return `invalid request (${status})`;\r\n if (status === 408) return `timeout (${status})`;\r\n if (status >= 500 && status < 600) return `HTTP ${status} (server error)`;\r\n if (type) return `${type} (${status})`;\r\n return `HTTP ${status}`;\r\n}\r\n\r\nfunction truncate(s: string, n: number): string {\r\n return s.length <= n ? s : `${s.slice(0, n - 1)}…`;\r\n}\r\n\r\nfunction providerStatusToCode(status: number, type?: string): ErrorCode {\r\n if (status === 0) return 'PROVIDER_NETWORK_ERROR';\r\n if (type === 'rate_limit_error' || status === 429) return 'PROVIDER_RATE_LIMITED';\r\n if (type === 'authentication_error' || status === 401) return 'PROVIDER_AUTH_FAILED';\r\n if (type === 'overloaded_error' || status === 529) return 'PROVIDER_OVERLOADED';\r\n if (type === 'invalid_request_error' || status === 400) return 'PROVIDER_INVALID_REQUEST';\r\n if (status === 408) return 'PROVIDER_NETWORK_ERROR';\r\n if (status >= 500) return 'PROVIDER_SERVER_ERROR';\r\n return 'PROVIDER_INVALID_REQUEST';\r\n}\r\n","/**\n * SecretVault encrypts secrets-at-rest in config files. The wire format is\n * `enc:v1:<base64-iv>:<base64-tag>:<base64-ciphertext>`. Plaintext strings\n * (those that do not match this prefix) are passed through unchanged so that\n * existing configs and env-var-derived values keep working.\n *\n * The vault is intentionally NOT designed to defeat a determined local\n * attacker who can read both the config file and the key file — that level\n * of secrecy needs the OS keychain. The goal is to keep keys from being\n * visible in screen shares, accidental log captures, and `cat config.json`\n * over someone's shoulder.\n */\nexport interface SecretVault {\n encrypt(plaintext: string): string;\n decrypt(value: string): string;\n isEncrypted(value: string): boolean;\n}\n\nexport const ENCRYPTED_PREFIX = 'enc:v1:';\n","export interface Mode {\n id: string;\n name: string;\n description: string;\n /** Additional prompt text injected into system prompt when mode is active */\n prompt: string;\n /** Tags for tool_search filtering */\n tags?: string[];\n /** Tools that should be prioritized/highlighted when this mode is active */\n toolPreferences?: string[];\n}\n\nexport interface ModeManifest {\n modes: Mode[];\n defaultMode?: string;\n}\n\nexport interface ModeStore {\n getActiveMode(): Promise<Mode | null>;\n setActiveMode(modeId: string | null): Promise<void>;\n listModes(): Promise<Mode[]>;\n getMode(modeId: string): Promise<Mode | null>;\n}\n\nexport interface ModeConfig {\n directory: string;\n}\n\nexport const DEFAULT_MODES: Mode[] = [\n {\n id: 'default',\n name: 'Default',\n description: 'General-purpose coding assistant',\n prompt: '',\n tags: ['general'],\n },\n {\n id: 'code-reviewer',\n name: 'Code Reviewer',\n description: 'Focus on code quality, best practices, and potential bugs',\n prompt: `## Code Reviewer Mode\n\nWhen reviewing code:\n- Look for potential bugs, race conditions, and edge cases\n- Check for security vulnerabilities (SQL injection, XSS, CSRF, etc.)\n- Evaluate error handling completeness\n- Assess code readability and maintainability\n- Check for performance anti-patterns\n- Verify test coverage for critical paths\n- Ensure naming conventions are followed`,\n tags: ['review', 'quality', 'security'],\n toolPreferences: ['read', 'grep', 'git', 'diff', 'test'],\n },\n {\n id: 'code-auditor',\n name: 'Code Auditor',\n description: 'Security-focused code analysis',\n prompt: `## Code Auditor Mode\n\nWhen auditing code for security:\n- Identify injection vulnerabilities (SQL, Command, XSS, LDAP)\n- Check authentication and authorization patterns\n- Look for sensitive data exposure (secrets, PII in logs)\n- Verify cryptographic implementations\n- Check for insecure dependencies or configurations\n- Assess input validation and output encoding\n- Look for timing attacks and information leakage`,\n tags: ['security', 'audit', 'compliance'],\n toolPreferences: ['grep', 'read', 'audit', 'bash'],\n },\n {\n id: 'architect',\n name: 'Software Architect',\n description: 'Design patterns, scalability, and system design',\n prompt: `## Architect Mode\n\nWhen designing or reviewing architecture:\n- Evaluate scalability and future growth\n- Check for appropriate design patterns\n- Assess coupling and cohesion\n- Look forSOLID principle violations\n- Evaluate data modeling decisions\n- Check for eventual consistency issues\n- Assess API design and contract stability\n- Consider operational aspects (monitoring, logging, deployment)`,\n tags: ['architecture', 'design', 'scalability'],\n toolPreferences: ['read', 'glob', 'tree', 'diff'],\n },\n {\n id: 'debugger',\n name: 'Debugger',\n description: 'Root cause analysis and error investigation',\n prompt: `## Debugger Mode\n\nWhen investigating bugs:\n- Reproduce the issue with minimal steps\n- Check error messages and stack traces thoroughly\n- Look for related logs and historical context\n- Verify assumptions about data flow\n- Check for race conditions in async code\n- Validate environment and configuration\n- Use binary search to isolate the root cause\n- Verify fixes with tests before considering done`,\n tags: ['debug', 'investigation', 'error-resolution'],\n toolPreferences: ['read', 'grep', 'bash', 'logs', 'test'],\n },\n {\n id: 'tester',\n name: 'QA Engineer',\n description: 'Test coverage, edge cases, and quality assurance',\n prompt: `## Tester Mode\n\nWhen testing or writing tests:\n- Cover happy path and error paths equally\n- Think about edge cases and boundary conditions\n- Check for missing null/undefined handling tests\n- Verify error messages are tested\n- Look for race condition tests in async code\n- Assess mutation testing opportunities\n- Check for integration test gaps\n- Verify test isolation and cleanup`,\n tags: ['testing', 'qa', 'quality'],\n toolPreferences: ['read', 'grep', 'test', 'bash'],\n },\n {\n id: 'devops',\n name: 'DevOps Engineer',\n description: 'Infrastructure, deployment, and operations',\n prompt: `## DevOps Mode\n\nWhen working on infrastructure:\n- Check for containerization and deployment readiness\n- Verify CI/CD pipeline configurations\n- Assess monitoring and alerting setup\n- Look for health check endpoints\n- Check for graceful shutdown handling\n- Verify backup and disaster recovery plans\n- Assess secrets management\n- Check for resource limits and quotas`,\n tags: ['devops', 'infrastructure', 'operations'],\n toolPreferences: ['read', 'bash', 'grep', 'logs', 'git'],\n },\n {\n id: 'refactorer',\n name: 'Refactorer',\n description: 'Code improvement and modernization',\n prompt: `## Refactorer Mode\n\nWhen refactoring code:\n- Maintain existing behavior — tests must pass before and after\n- Make one change at a time, verify after each\n- Prefer small, focused commits\n- Preserve API contracts unless explicitly changing\n- Remove dead code and comments\n- Improve naming as you go\n- Don't mix formatting changes with logic changes\n- Keep performance in mind — don't regress`,\n tags: ['refactor', 'modernization', 'improvement'],\n toolPreferences: ['read', 'edit', 'test', 'git', 'grep'],\n },\n];","export type SpecStatus = 'draft' | 'review' | 'approved' | 'implemented' | 'deprecated';\nexport type SpecSectionType = 'overview' | 'requirements' | 'architecture' | 'api' | 'data' | 'security' | 'acceptance';\n\nexport interface SpecSection {\n type: SpecSectionType;\n title: string;\n content: string;\n level: number;\n children?: SpecSection[];\n}\n\nexport interface SpecRequirement {\n id: string;\n type: 'functional' | 'non-functional' | 'security' | 'performance' | 'ux';\n priority: 'critical' | 'high' | 'medium' | 'low';\n description: string;\n acceptanceCriteria: string[];\n blockedBy?: string[];\n implements?: string[];\n}\n\nexport interface SpecApiEndpoint {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n path: string;\n description: string;\n request?: Record<string, unknown>;\n response?: Record<string, unknown>;\n auth?: boolean;\n}\n\nexport interface Specification {\n id: string;\n title: string;\n version: string;\n status: SpecStatus;\n overview: string;\n sections: SpecSection[];\n requirements: SpecRequirement[];\n apiEndpoints?: SpecApiEndpoint[];\n dependencies?: string[];\n createdAt: number;\n updatedAt: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface SpecAnalysis {\n specId: string;\n completeness: number; // 0-100\n coverage: {\n requirements: number;\n apiEndpoints: number;\n edgeCases: number;\n errorHandling: number;\n };\n gaps: string[];\n risks: { requirement: string; risk: string; severity: 'high' | 'medium' | 'low' }[];\n suggestions: string[];\n}\n\nexport interface SpecValidationResult {\n valid: boolean;\n errors: { path: string; message: string }[];\n warnings: { path: string; message: string }[];\n}\n\nexport interface SpecTemplate {\n id: string;\n name: string;\n description: string;\n sections: Omit<SpecSection, 'content'>[];\n defaultRequirements: Omit<SpecRequirement, 'id' | 'description'>[];\n}\n\nexport const DEFAULT_SPEC_TEMPLATE: SpecTemplate = {\n id: 'default',\n name: 'Default Feature Spec',\n description: 'Standard template for feature specifications',\n sections: [\n { type: 'overview', title: 'Overview', level: 1 },\n { type: 'requirements', title: 'Requirements', level: 1 },\n { type: 'architecture', title: 'Architecture', level: 1 },\n { type: 'api', title: 'API Design', level: 1 },\n { type: 'data', title: 'Data Model', level: 1 },\n { type: 'security', title: 'Security', level: 1 },\n { type: 'acceptance', title: 'Acceptance Criteria', level: 1 },\n ],\n defaultRequirements: [\n { type: 'functional', priority: 'high', acceptanceCriteria: [], blockedBy: [], implements: [] },\n { type: 'non-functional', priority: 'medium', acceptanceCriteria: [], blockedBy: [], implements: [] },\n ],\n};","export type TaskStatus = 'pending' | 'in_progress' | 'blocked' | 'failed' | 'review' | 'completed';\r\nexport type TaskPriority = 'critical' | 'high' | 'medium' | 'low';\r\nexport type TaskType = 'feature' | 'bugfix' | 'refactor' | 'docs' | 'test' | 'chore';\r\n\r\nexport interface TaskNode {\r\n id: string;\r\n title: string;\r\n description: string;\r\n type: TaskType;\r\n priority: TaskPriority;\r\n status: TaskStatus;\r\n assignee?: string;\r\n estimateHours?: number;\r\n actualHours?: number;\r\n tags?: string[];\r\n specRequirementId?: string;\r\n parentId?: string;\r\n children?: string[];\r\n createdAt: number;\r\n updatedAt: number;\r\n completedAt?: number;\r\n metadata?: Record<string, unknown>;\r\n}\r\n\r\nexport interface TaskEdge {\r\n id: string;\r\n from: string;\r\n to: string;\r\n type: 'blocks' | 'depends_on' | 'relates_to' | 'implements';\r\n weight?: number;\r\n}\r\n\r\nexport interface TaskGraph {\r\n id: string;\r\n specId: string;\r\n title: string;\r\n nodes: Map<string, TaskNode>;\r\n edges: TaskEdge[];\r\n rootNodes: string[];\r\n createdAt: number;\r\n updatedAt: number;\r\n}\r\n\r\nexport interface TaskDependency {\r\n taskId: string;\r\n blockedBy: string[];\r\n blocking: string[];\r\n}\r\n\r\nexport interface TaskAssignment {\r\n taskId: string;\r\n assignee: string;\r\n assignedAt: number;\r\n}\r\n\r\nexport interface TaskProgress {\r\n total: number;\r\n pending: number;\r\n inProgress: number;\r\n blocked: number;\r\n failed: number;\r\n review: number;\r\n completed: number;\r\n percentComplete: number;\r\n estimatedHours: number;\r\n actualHours: number;\r\n}\r\n\r\nexport interface TaskFilter {\r\n status?: TaskStatus[];\r\n priority?: TaskPriority[];\r\n type?: TaskType[];\r\n assignee?: string[];\r\n tags?: string[];\r\n specRequirementId?: string;\r\n}\r\n\r\nexport interface TaskSort {\r\n field: 'priority' | 'createdAt' | 'updatedAt' | 'status';\r\n direction: 'asc' | 'desc';\r\n}\r\n\r\nexport interface CriticalPathResult {\r\n taskIds: string[];\r\n totalEstimateHours: number;\r\n bottleneckTasks: string[];\r\n}\r\n\r\nexport function computeTaskProgress(graph: TaskGraph): TaskProgress {\r\n let completed = 0, pending = 0, inProgress = 0, blocked = 0, failed = 0, review = 0;\r\n let estimatedHours = 0, actualHours = 0;\r\n for (const n of graph.nodes.values()) {\r\n switch (n.status) {\r\n case 'completed': completed++; break;\r\n case 'pending': pending++; break;\r\n case 'in_progress': inProgress++; break;\r\n case 'blocked': blocked++; break;\r\n case 'failed': failed++; break;\r\n case 'review': review++; break;\r\n }\r\n estimatedHours += n.estimateHours ?? 0;\r\n actualHours += n.actualHours ?? 0;\r\n }\r\n const total = graph.nodes.size;\r\n\r\n return {\r\n total,\r\n pending,\r\n inProgress,\r\n blocked,\r\n failed,\r\n review,\r\n completed,\r\n percentComplete: total > 0 ? Math.round((completed / total) * 100) : 0,\r\n estimatedHours,\r\n actualHours,\r\n };\r\n}\r\n\r\nexport function findCriticalPath(graph: TaskGraph): CriticalPathResult {\r\n const nodes = Array.from(graph.nodes.values());\r\n const criticalNodes = nodes.filter((n) => n.priority === 'critical');\r\n const bottleneckTasks = criticalNodes\r\n .filter((n) => graph.edges.some((e) => e.to === n.id && e.type === 'depends_on'))\r\n .map((n) => n.id);\r\n\r\n const totalEstimateHours = criticalNodes.reduce((sum, n) => sum + (n.estimateHours ?? 0), 0);\r\n\r\n return {\r\n taskIds: criticalNodes.map((n) => n.id),\r\n totalEstimateHours,\r\n bottleneckTasks,\r\n };\r\n}\r\n\r\nexport function topologicalSort(graph: TaskGraph): string[] {\r\n const visited = new Set<string>();\r\n const inStack = new Set<string>();\r\n const result: string[] = [];\r\n\r\n function visit(id: string): void {\r\n // Cycle: callers must detect cycles up-front if they care; we just stop recursing.\r\n if (inStack.has(id)) return;\r\n if (visited.has(id)) return;\r\n if (!graph.nodes.has(id)) return;\r\n\r\n visited.add(id);\r\n inStack.add(id);\r\n\r\n for (const edge of graph.edges) {\r\n if (edge.from === id) visit(edge.to);\r\n }\r\n\r\n inStack.delete(id);\r\n result.push(id);\r\n }\r\n\r\n for (const rootId of graph.rootNodes) {\r\n visit(rootId);\r\n }\r\n\r\n return result;\r\n}"]}
@@ -1,5 +1,5 @@
1
- export { W as WstackPathOptions, a as WstackPaths, p as projectHash, r as resolveWstackPaths } from '../wstack-paths-D24ynAz1.js';
2
- import { J as JSONSchema } from '../provider-DovtyuM8.js';
1
+ export { W as WstackPathOptions, a as WstackPaths, p as projectHash, r as resolveWstackPaths } from '../wstack-paths-BGu2INTm.js';
2
+ import { J as JSONSchema } from '../provider-txgB0Oq9.js';
3
3
 
4
4
  interface AtomicWriteOptions {
5
5
  mode?: number;
@@ -15,11 +15,17 @@ interface SafeParseResult<T> {
15
15
  }
16
16
  declare function safeParse<T = unknown>(input: string, maxBytes?: number): SafeParseResult<T>;
17
17
  declare function safeStringify(value: unknown, pretty?: boolean): string;
18
- /** Attempt to parse JSON5-style input and return a valid JSON string.
19
- * Handles trailing commas, single-line comments, and unquoted keys
20
- * that are common in provider output.
18
+ /**
19
+ * Attempt to parse JSON5-style input and return a valid JSON string.
20
+ * Handles trailing commas, single-line comments, and unquoted keys
21
+ * that are common in provider output.
22
+ *
23
+ * Returns the sanitized string if it parses successfully as JSON,
24
+ * or `null` if the input cannot be made valid. Callers use this to
25
+ * decide whether to proceed with the parsed result or fall back to
26
+ * raw handling.
21
27
  */
22
- declare function sanitizeJsonString(s: string): string;
28
+ declare function sanitizeJsonString(s: string): string | null;
23
29
 
24
30
  type NewlineStyle = 'lf' | 'crlf' | 'cr';
25
31
  declare function detectNewlineStyle(text: string): NewlineStyle;
@@ -50,9 +56,8 @@ declare function stripAnsi(s: string): string;
50
56
  * Minimal glob matcher for trust patterns.
51
57
  * Supports: *, **, ?, character classes [abc], [a-z], negation [!...] or [^...].
52
58
  *
53
- * Both `[!...]` (shell glob convention) and `[^...]` (regex convention) are
54
- * accepted because users coming from either world will reach for what they
55
- * know; rejecting one silently fails open in a security-sensitive context.
59
+ * Compiled regexes are cached so repeated calls with the same pattern
60
+ * avoid recompilation overhead.
56
61
  */
57
62
  declare function compileGlob(pattern: string): RegExp;
58
63
  declare function matchGlob(pattern: string, input: string): boolean;
@@ -92,8 +97,8 @@ declare function createToolOutputSerializer(opts?: ToolOutputSerializerOptions):
92
97
  */
93
98
  /**
94
99
  * Estimate tokens for a tool_use block input.
95
- * Caches the stringified result on the input object itself to avoid
96
- * repeated JSON.stringify calls during context window checks.
100
+ * Caches the stringified result keyed by the stable string representation
101
+ * to avoid repeated JSON.stringify calls during context window checks.
97
102
  */
98
103
  declare function estimateToolInputTokens(input: unknown): number;
99
104
  /**