@wrongstack/core 0.1.4 → 0.1.7
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.
- package/README.md +155 -0
- package/dist/defaults/index.d.ts +68 -33
- package/dist/defaults/index.js +559 -239
- package/dist/defaults/index.js.map +1 -1
- package/dist/index.d.ts +26 -12
- package/dist/index.js +745 -322
- package/dist/index.js.map +1 -1
- package/dist/kernel/index.d.ts +5 -4
- package/dist/kernel/index.js +2 -1
- package/dist/kernel/index.js.map +1 -1
- package/dist/{secret-scrubber-qU3AwEiI.d.ts → mode-Pjt5vMS6.d.ts} +94 -3
- package/dist/{provider-DovtyuM8.d.ts → provider-txgB0Oq9.d.ts} +27 -30
- package/dist/{session-reader-DR4u3bu9.d.ts → session-reader-7AutWHut.d.ts} +13 -32
- package/dist/system-prompt-vAB0F54-.d.ts +23 -0
- package/dist/types/index.d.ts +4 -4
- package/dist/types/index.js +34 -15
- package/dist/types/index.js.map +1 -1
- package/dist/utils/index.d.ts +16 -11
- package/dist/utils/index.js +40 -13
- package/dist/utils/index.js.map +1 -1
- package/dist/{wstack-paths-D24ynAz1.d.ts → wstack-paths-BGu2INTm.d.ts} +7 -0
- package/package.json +7 -4
- package/dist/system-prompt--mzZnenv.d.ts +0 -16
package/dist/types/index.d.ts
CHANGED
|
@@ -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-
|
|
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
|
|
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
|
|
4
|
-
export { B as BuildContext, S as SystemPromptBuilder } from '../system-prompt
|
|
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-7AutWHut.js';
|
|
4
|
+
export { B as BuildContext, M as ModelCapabilities, S as SystemPromptBuilder } from '../system-prompt-vAB0F54-.js';
|
package/dist/types/index.js
CHANGED
|
@@ -385,16 +385,33 @@ var DEFAULT_SPEC_TEMPLATE = {
|
|
|
385
385
|
|
|
386
386
|
// src/types/task-graph.ts
|
|
387
387
|
function computeTaskProgress(graph) {
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
const
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
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
|
-
|
|
429
|
-
|
|
430
|
-
|
|
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) {
|
package/dist/types/index.js.map
CHANGED
|
@@ -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,K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GAAA,CAAI,EAAE,CAAA,EAAG;AACrB,IAAA,OAAA,CAAQ,IAAI,EAAE,CAAA;AAEd,IAAA,MAAM,IAAA,GAAO,KAAA,CAAM,KAAA,CAAM,GAAA,CAAI,EAAE,CAAA;AAC/B,IAAA,IAAI,CAAC,IAAA,EAAM;AAEX,IAAA,MAAM,QAAA,GAAW,MAAM,KAAA,CAAM,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,SAAS,EAAE,CAAA;AACxD,IAAA,KAAA,MAAW,QAAQ,QAAA,EAAU;AAC3B,MAAA,KAAA,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","../../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,OAAA,EAA0C;AAC/D,EAAA,IAAI,OAAO,OAAA,KAAY,QAAA,EAAU,OAAO,OAAA;AACxC,EAAA,OAAO,OAAA,CACJ,MAAA,CAAO,CAAC,CAAA,KAAM,EAAE,IAAA,KAAS,MAAM,CAAA,CAC/B,GAAA,CAAI,CAAC,CAAA,KAAO,CAAA,CAAuB,IAAI,CAAA,CACvC,KAAK,EAAE,CAAA;AACZ;;;ACsCO,IAAM,eAAA,GAAN,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AA,IAAiB,CAAA,CAAA,EAAI,CAAC,CAAA;AAE3F,EAAA,OAAO;AAAA,IACL,SAAS,aAAA,CAAc,GAAA,CAAI,CAAC,CAAA,KAAM,EAAE,EAAE,CAAA;AAAA,IACtC,kBAAA;AAAA,IACA;AAAA,GACF;AACF;AAEO,SAAS,gBAAgB,KAAA,EAA4B;AAC1D,EAAA,MAAM,OAAA,uBAAc,GAAA,EAAY;AAChC,EAAA,MAAM,OAAA,uBAAc,GAAA,EAAY;AAChC,EAAA,MAAM,SAAmB,EAAC;AAE1B,EAAA,SAAS,MAAM,EAAA,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}"]}
|
package/dist/utils/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { W as WstackPathOptions, a as WstackPaths, p as projectHash, r as resolveWstackPaths } from '../wstack-paths-
|
|
2
|
-
import { J as JSONSchema } from '../provider-
|
|
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
|
-
/**
|
|
19
|
-
*
|
|
20
|
-
*
|
|
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
|
-
*
|
|
54
|
-
*
|
|
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
|
|
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
|
/**
|
package/dist/utils/index.js
CHANGED
|
@@ -88,7 +88,7 @@ function sanitizeJsonString(s) {
|
|
|
88
88
|
JSON.parse(out);
|
|
89
89
|
return out;
|
|
90
90
|
} catch {
|
|
91
|
-
return
|
|
91
|
+
return null;
|
|
92
92
|
}
|
|
93
93
|
}
|
|
94
94
|
function stripSingleLineComments(s) {
|
|
@@ -178,7 +178,22 @@ function stripAnsi(s) {
|
|
|
178
178
|
|
|
179
179
|
// src/utils/glob-match.ts
|
|
180
180
|
function escapeRegex(s) {
|
|
181
|
-
return s.replace(/[.+^${}()
|
|
181
|
+
return s.replace(/[.+^${}()|\\]/g, "\\$&");
|
|
182
|
+
}
|
|
183
|
+
var COMPILED_GLOB_CACHE = /* @__PURE__ */ new Map();
|
|
184
|
+
var CACHE_MAX_SIZE = 2e3;
|
|
185
|
+
function getCachedGlob(pattern) {
|
|
186
|
+
const cached = COMPILED_GLOB_CACHE.get(pattern);
|
|
187
|
+
if (cached) return cached;
|
|
188
|
+
if (COMPILED_GLOB_CACHE.size >= CACHE_MAX_SIZE) {
|
|
189
|
+
const keys = [...COMPILED_GLOB_CACHE.keys()];
|
|
190
|
+
for (let i = 0; i < Math.floor(CACHE_MAX_SIZE / 4); i++) {
|
|
191
|
+
COMPILED_GLOB_CACHE.delete(keys[i]);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
const re = compileGlob(pattern);
|
|
195
|
+
COMPILED_GLOB_CACHE.set(pattern, re);
|
|
196
|
+
return re;
|
|
182
197
|
}
|
|
183
198
|
function compileGlob(pattern) {
|
|
184
199
|
let i = 0;
|
|
@@ -227,7 +242,7 @@ function compileGlob(pattern) {
|
|
|
227
242
|
return new RegExp(re);
|
|
228
243
|
}
|
|
229
244
|
function matchGlob(pattern, input) {
|
|
230
|
-
return
|
|
245
|
+
return getCachedGlob(pattern).test(input);
|
|
231
246
|
}
|
|
232
247
|
function matchAny(patterns, input) {
|
|
233
248
|
return patterns.some((p) => matchGlob(p, input));
|
|
@@ -394,6 +409,7 @@ function resolveWstackPaths(opts) {
|
|
|
394
409
|
const projectDir = path2.join(globalRoot, "projects", hash);
|
|
395
410
|
return {
|
|
396
411
|
globalRoot,
|
|
412
|
+
configDir: globalRoot,
|
|
397
413
|
globalConfig: path2.join(globalRoot, "config.json"),
|
|
398
414
|
secretsKey: path2.join(globalRoot, ".key"),
|
|
399
415
|
globalMemory: path2.join(globalRoot, "memory.md"),
|
|
@@ -452,7 +468,6 @@ function createToolOutputSerializer(opts = {}) {
|
|
|
452
468
|
}
|
|
453
469
|
const half = Math.floor(available / 2);
|
|
454
470
|
const first = text.slice(0, half);
|
|
455
|
-
Buffer.byteLength(first, "utf8");
|
|
456
471
|
const second = text.slice(text.length - half);
|
|
457
472
|
return { text: `${first}${marker}${second}`, newBudget: 0 };
|
|
458
473
|
}
|
|
@@ -461,21 +476,33 @@ function createToolOutputSerializer(opts = {}) {
|
|
|
461
476
|
|
|
462
477
|
// src/utils/token-estimate.ts
|
|
463
478
|
var RoughTokenEstimate = (text) => Math.max(1, Math.ceil(text.length / 4));
|
|
479
|
+
var ESTIMATE_CACHE = /* @__PURE__ */ new Map();
|
|
480
|
+
var ESTIMATE_CACHE_MAX_SIZE = 1e4;
|
|
481
|
+
function getCachedEstimate(key, compute) {
|
|
482
|
+
const existing = ESTIMATE_CACHE.get(key);
|
|
483
|
+
if (existing !== void 0) return existing;
|
|
484
|
+
if (ESTIMATE_CACHE.size >= ESTIMATE_CACHE_MAX_SIZE) {
|
|
485
|
+
const keys = [...ESTIMATE_CACHE.keys()];
|
|
486
|
+
for (let i = 0; i < Math.floor(ESTIMATE_CACHE_MAX_SIZE / 4); i++) {
|
|
487
|
+
ESTIMATE_CACHE.delete(keys[i]);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
const estimate = compute();
|
|
491
|
+
ESTIMATE_CACHE.set(key, estimate);
|
|
492
|
+
return estimate;
|
|
493
|
+
}
|
|
464
494
|
function estimateToolInputTokens(input) {
|
|
465
495
|
if (typeof input === "string") return RoughTokenEstimate(input);
|
|
466
|
-
if (input
|
|
467
|
-
return input
|
|
496
|
+
if (input === null || typeof input !== "object") {
|
|
497
|
+
return RoughTokenEstimate(String(input));
|
|
468
498
|
}
|
|
469
|
-
const
|
|
470
|
-
|
|
471
|
-
if (input !== null && typeof input === "object" && !Array.isArray(input)) {
|
|
472
|
-
input.__tokenEstimate = estimate;
|
|
473
|
-
}
|
|
474
|
-
return estimate;
|
|
499
|
+
const key = JSON.stringify(input);
|
|
500
|
+
return getCachedEstimate(key, () => RoughTokenEstimate(key));
|
|
475
501
|
}
|
|
476
502
|
function estimateToolResultTokens(content) {
|
|
477
503
|
if (typeof content === "string") return RoughTokenEstimate(content);
|
|
478
|
-
|
|
504
|
+
const key = JSON.stringify(content);
|
|
505
|
+
return getCachedEstimate(key, () => RoughTokenEstimate(key));
|
|
479
506
|
}
|
|
480
507
|
function estimateTextTokens(text) {
|
|
481
508
|
return RoughTokenEstimate(text);
|