@wrongstack/core 0.1.2 → 0.1.4
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/LICENSE +17 -13
- package/dist/defaults/index.d.ts +738 -138
- package/dist/defaults/index.js +2507 -975
- package/dist/defaults/index.js.map +1 -1
- package/dist/index.d.ts +27 -8
- package/dist/index.js +3271 -1057
- package/dist/index.js.map +1 -1
- package/dist/kernel/index.d.ts +5 -3
- package/dist/kernel/index.js +89 -11
- package/dist/kernel/index.js.map +1 -1
- package/dist/provider-DovtyuM8.d.ts +813 -0
- package/dist/{secret-scrubber-Dax_Ou_o.d.ts → secret-scrubber-qU3AwEiI.d.ts} +126 -457
- package/dist/{tool-executor-DjnMELMV.d.ts → session-reader-DR4u3bu9.d.ts} +445 -59
- package/dist/{system-prompt-BG3nks8P.d.ts → system-prompt--mzZnenv.d.ts} +1 -1
- package/dist/types/index.d.ts +4 -3
- package/dist/types/index.js +153 -5
- package/dist/types/index.js.map +1 -1
- package/dist/utils/index.d.ts +42 -1
- package/dist/utils/index.js +122 -3
- package/dist/utils/index.js.map +1 -1
- package/package.json +15 -4
package/dist/types/index.js
CHANGED
|
@@ -21,21 +21,159 @@ function asText(content) {
|
|
|
21
21
|
return content.filter((b) => b.type === "text").map((b) => b.text).join("");
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
// src/types/errors.ts
|
|
25
|
+
var WrongStackError = class extends Error {
|
|
26
|
+
code;
|
|
27
|
+
subsystem;
|
|
28
|
+
severity;
|
|
29
|
+
recoverable;
|
|
30
|
+
context;
|
|
31
|
+
constructor(opts) {
|
|
32
|
+
super(opts.message, { cause: opts.cause });
|
|
33
|
+
this.name = "WrongStackError";
|
|
34
|
+
this.code = opts.code;
|
|
35
|
+
this.subsystem = opts.subsystem;
|
|
36
|
+
this.severity = opts.severity ?? "error";
|
|
37
|
+
this.recoverable = opts.recoverable ?? false;
|
|
38
|
+
this.context = opts.context;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Render a one-line user-facing description.
|
|
42
|
+
* Subclasses should override for domain-specific formatting.
|
|
43
|
+
*/
|
|
44
|
+
describe() {
|
|
45
|
+
const ctx = this.context ? ` ${formatContext(this.context)}` : "";
|
|
46
|
+
return `${this.code}: ${this.message}${ctx}`;
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
function formatContext(ctx) {
|
|
50
|
+
const parts = Object.entries(ctx).filter(([, v]) => v !== void 0).slice(0, 3).map(([k, v]) => `${k}=${String(v)}`);
|
|
51
|
+
return parts.length > 0 ? `[${parts.join(" ")}]` : "";
|
|
52
|
+
}
|
|
53
|
+
var ToolError = class extends WrongStackError {
|
|
54
|
+
toolName;
|
|
55
|
+
constructor(opts) {
|
|
56
|
+
super({
|
|
57
|
+
message: opts.message,
|
|
58
|
+
code: opts.code,
|
|
59
|
+
subsystem: "tool",
|
|
60
|
+
recoverable: opts.recoverable,
|
|
61
|
+
context: { tool: opts.toolName, ...opts.context },
|
|
62
|
+
cause: opts.cause
|
|
63
|
+
});
|
|
64
|
+
this.name = "ToolError";
|
|
65
|
+
this.toolName = opts.toolName;
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
var ConfigError = class extends WrongStackError {
|
|
69
|
+
constructor(opts) {
|
|
70
|
+
super({
|
|
71
|
+
message: opts.message,
|
|
72
|
+
code: opts.code,
|
|
73
|
+
subsystem: "config",
|
|
74
|
+
severity: "fatal",
|
|
75
|
+
recoverable: false,
|
|
76
|
+
context: opts.context,
|
|
77
|
+
cause: opts.cause
|
|
78
|
+
});
|
|
79
|
+
this.name = "ConfigError";
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
var PluginError = class extends WrongStackError {
|
|
83
|
+
pluginName;
|
|
84
|
+
constructor(opts) {
|
|
85
|
+
super({
|
|
86
|
+
message: opts.message,
|
|
87
|
+
code: opts.code,
|
|
88
|
+
subsystem: "plugin",
|
|
89
|
+
severity: "error",
|
|
90
|
+
recoverable: opts.code === "PLUGIN_MISSING_DEPENDENCY",
|
|
91
|
+
context: { plugin: opts.pluginName, ...opts.context },
|
|
92
|
+
cause: opts.cause
|
|
93
|
+
});
|
|
94
|
+
this.name = "PluginError";
|
|
95
|
+
this.pluginName = opts.pluginName;
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
var AgentError = class extends WrongStackError {
|
|
99
|
+
constructor(opts) {
|
|
100
|
+
super({
|
|
101
|
+
message: opts.message,
|
|
102
|
+
code: opts.code,
|
|
103
|
+
subsystem: "agent",
|
|
104
|
+
severity: opts.code === "AGENT_ABORTED" ? "warning" : "error",
|
|
105
|
+
recoverable: opts.recoverable ?? opts.code === "AGENT_ITERATION_LIMIT",
|
|
106
|
+
context: opts.context,
|
|
107
|
+
cause: opts.cause
|
|
108
|
+
});
|
|
109
|
+
this.name = "AgentError";
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
function toWrongStackError(err, code = "AGENT_RUN_FAILED") {
|
|
113
|
+
if (err instanceof WrongStackError) return err;
|
|
114
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
115
|
+
return new AgentError({
|
|
116
|
+
message,
|
|
117
|
+
code: code === "UNKNOWN" ? "AGENT_RUN_FAILED" : code,
|
|
118
|
+
cause: err
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
var SessionError = class extends WrongStackError {
|
|
122
|
+
sessionId;
|
|
123
|
+
constructor(opts) {
|
|
124
|
+
super({
|
|
125
|
+
message: opts.message,
|
|
126
|
+
code: opts.code,
|
|
127
|
+
subsystem: "session",
|
|
128
|
+
severity: opts.code === "SESSION_WRITE_FAILED" ? "error" : "warning",
|
|
129
|
+
recoverable: opts.code !== "SESSION_CORRUPTED",
|
|
130
|
+
context: { sessionId: opts.sessionId, ...opts.context },
|
|
131
|
+
cause: opts.cause
|
|
132
|
+
});
|
|
133
|
+
this.name = "SessionError";
|
|
134
|
+
this.sessionId = opts.sessionId;
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
function isWrongStackError(err) {
|
|
138
|
+
return err instanceof WrongStackError;
|
|
139
|
+
}
|
|
140
|
+
function isToolError(err) {
|
|
141
|
+
return err instanceof ToolError;
|
|
142
|
+
}
|
|
143
|
+
function isConfigError(err) {
|
|
144
|
+
return err instanceof ConfigError;
|
|
145
|
+
}
|
|
146
|
+
function isPluginError(err) {
|
|
147
|
+
return err instanceof PluginError;
|
|
148
|
+
}
|
|
149
|
+
function isSessionError(err) {
|
|
150
|
+
return err instanceof SessionError;
|
|
151
|
+
}
|
|
152
|
+
function isAgentError(err) {
|
|
153
|
+
return err instanceof AgentError;
|
|
154
|
+
}
|
|
155
|
+
|
|
24
156
|
// src/types/provider.ts
|
|
25
|
-
var ProviderError = class extends
|
|
157
|
+
var ProviderError = class extends WrongStackError {
|
|
26
158
|
status;
|
|
27
159
|
retryable;
|
|
28
160
|
providerId;
|
|
29
161
|
body;
|
|
30
|
-
cause;
|
|
31
162
|
constructor(message, status, retryable, providerId, opts = {}) {
|
|
32
|
-
super(
|
|
163
|
+
super({
|
|
164
|
+
message,
|
|
165
|
+
code: providerStatusToCode(status, opts.body?.type),
|
|
166
|
+
subsystem: "provider",
|
|
167
|
+
severity: status >= 500 ? "error" : "warning",
|
|
168
|
+
recoverable: retryable,
|
|
169
|
+
context: { providerId, status },
|
|
170
|
+
cause: opts.cause
|
|
171
|
+
});
|
|
33
172
|
this.name = "ProviderError";
|
|
34
173
|
this.status = status;
|
|
35
174
|
this.retryable = retryable;
|
|
36
175
|
this.providerId = providerId;
|
|
37
176
|
this.body = opts.body;
|
|
38
|
-
this.cause = opts.cause;
|
|
39
177
|
}
|
|
40
178
|
/**
|
|
41
179
|
* Render a one-line, user-facing description. Designed for the CLI/TUI
|
|
@@ -76,6 +214,16 @@ function describeStatus(status, type) {
|
|
|
76
214
|
function truncate(s, n) {
|
|
77
215
|
return s.length <= n ? s : `${s.slice(0, n - 1)}\u2026`;
|
|
78
216
|
}
|
|
217
|
+
function providerStatusToCode(status, type) {
|
|
218
|
+
if (status === 0) return "PROVIDER_NETWORK_ERROR";
|
|
219
|
+
if (type === "rate_limit_error" || status === 429) return "PROVIDER_RATE_LIMITED";
|
|
220
|
+
if (type === "authentication_error" || status === 401) return "PROVIDER_AUTH_FAILED";
|
|
221
|
+
if (type === "overloaded_error" || status === 529) return "PROVIDER_OVERLOADED";
|
|
222
|
+
if (type === "invalid_request_error" || status === 400) return "PROVIDER_INVALID_REQUEST";
|
|
223
|
+
if (status === 408) return "PROVIDER_NETWORK_ERROR";
|
|
224
|
+
if (status >= 500) return "PROVIDER_SERVER_ERROR";
|
|
225
|
+
return "PROVIDER_INVALID_REQUEST";
|
|
226
|
+
}
|
|
79
227
|
|
|
80
228
|
// src/types/secret-vault.ts
|
|
81
229
|
var ENCRYPTED_PREFIX = "enc:v1:";
|
|
@@ -291,6 +439,6 @@ function topologicalSort(graph) {
|
|
|
291
439
|
return result;
|
|
292
440
|
}
|
|
293
441
|
|
|
294
|
-
export { DEFAULT_MODES, DEFAULT_SPEC_TEMPLATE, ENCRYPTED_PREFIX, ProviderError, asBlocks, asText, computeTaskProgress, findCriticalPath, isImageBlock, isTextBlock, isToolResultBlock, isToolUseBlock, topologicalSort };
|
|
442
|
+
export { AgentError, ConfigError, DEFAULT_MODES, DEFAULT_SPEC_TEMPLATE, ENCRYPTED_PREFIX, PluginError, ProviderError, SessionError, ToolError, WrongStackError, asBlocks, asText, computeTaskProgress, findCriticalPath, isAgentError, isConfigError, isImageBlock, isPluginError, isSessionError, isTextBlock, isToolError, isToolResultBlock, isToolUseBlock, isWrongStackError, toWrongStackError, topologicalSort };
|
|
295
443
|
//# sourceMappingURL=index.js.map
|
|
296
444
|
//# sourceMappingURL=index.js.map
|
package/dist/types/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/types/blocks.ts","../../src/types/messages.ts","../../src/types/provider.ts","../../src/types/secret-vault.ts","../../src/types/mode.ts","../../src/types/spec.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A,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\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","import type { ContentBlock, TextBlock } from './blocks.js';\nimport type { Message } from './messages.js';\nimport type { Tool } from './tool.js';\n\nexport interface Usage {\n input: number;\n output: number;\n cacheRead?: number;\n cacheWrite?: number;\n}\n\nexport interface Capabilities {\n tools: boolean;\n parallelTools: boolean;\n vision: boolean;\n streaming: boolean;\n promptCache: boolean;\n systemPrompt: boolean;\n jsonMode: boolean;\n maxContext: number;\n cacheControl: 'native' | 'auto' | 'none';\n}\n\nexport interface Request {\n model: string;\n system?: TextBlock[];\n messages: Message[];\n tools?: Tool[];\n maxTokens: number;\n temperature?: number;\n topP?: number;\n stopSequences?: string[];\n toolChoice?: 'auto' | 'required' | 'none' | { type: 'tool'; name: string };\n}\n\nexport type StopReason = 'end_turn' | 'tool_use' | 'max_tokens' | 'stop_sequence' | 'refusal';\n\nexport interface Response {\n content: ContentBlock[];\n stopReason: StopReason;\n usage: Usage;\n model: string;\n}\n\nexport type StreamEvent =\n | { type: 'message_start'; model: string }\n | { type: 'content_block_start'; kind: 'text' | 'tool_use'; id?: string; name?: string }\n | { type: 'content_block_stop'; index: number }\n | { type: 'text_delta'; text: string }\n | { type: 'tool_use_start'; id: string; name: string }\n | { type: 'tool_use_input_delta'; id: string; partial: string }\n | { type: 'tool_use_stop'; id: string; input: unknown }\n | { type: 'message_stop'; stopReason: StopReason; usage: Usage };\n\nexport interface Provider {\n readonly id: string;\n readonly capabilities: Capabilities;\n /** Canonical streaming entry point. `complete()` defaults to a wrapper that\n * aggregates this stream — providers may override for non-streaming wires. */\n stream(req: Request, opts: { signal: AbortSignal }): AsyncIterable<StreamEvent>;\n complete(req: Request, opts: { signal: AbortSignal }): Promise<Response>;\n}\n\n/**\n * Structured body parsed from a provider's HTTP error response. Populated\n * best-effort: providers return JSON shaped differently (Anthropic uses\n * `{error: {type, message}}`, OpenAI uses `{error: {message, code}}`,\n * Google uses `{error: {status, message}}`), so the fields here are the\n * intersection that's usable for rendering and routing.\n */\nexport interface ProviderErrorBody {\n /** Provider-specific kind, e.g. \"overloaded_error\", \"rate_limit_error\", \"invalid_request_error\". */\n type?: string;\n /** Human-readable explanation from the provider. */\n message?: string;\n /** Provider request id, when present in the body or headers. */\n requestId?: string;\n /** Parsed Retry-After header (or equivalent body hint) in milliseconds. */\n retryAfterMs?: number;\n /** The raw response body (truncated), kept for debugging. */\n raw?: string;\n}\n\nexport class ProviderError extends Error {\n public readonly status: number;\n public readonly retryable: boolean;\n public readonly providerId: string;\n public readonly body?: ProviderErrorBody;\n public override readonly cause?: unknown;\n\n constructor(\n message: string,\n status: number,\n retryable: boolean,\n providerId: string,\n opts: { body?: ProviderErrorBody; cause?: unknown } = {},\n ) {\n super(message);\n this.name = 'ProviderError';\n this.status = status;\n this.retryable = retryable;\n this.providerId = providerId;\n this.body = opts.body;\n this.cause = opts.cause;\n }\n\n /**\n * Render a one-line, user-facing description. Designed for the CLI/TUI\n * status line and the agent's retry warning. Avoids dumping raw JSON\n * (which is what users see today when a 529 lands and the log message\n * includes the full `{\"type\":\"error\",...}` body).\n *\n * Examples:\n * \"minimax-coding-plan overloaded (529): High traffic detected. Upgrade for highspeed model. [req 06534785201de9c0…]\"\n * \"openai rate limited (429): Retry after 12s\"\n * \"anthropic invalid request (400): messages.0.role must be one of 'user'|'assistant'\"\n * \"groq HTTP 500 (server error)\"\n */\n describe(): string {\n const kind = describeStatus(this.status, this.body?.type);\n const head = `${this.providerId} ${kind}`;\n const detail = this.body?.message?.trim();\n const reqId = this.body?.requestId\n ? ` [req ${this.body.requestId.slice(0, 16)}${this.body.requestId.length > 16 ? '…' : ''}]`\n : '';\n if (detail && detail.length > 0) {\n return `${head}: ${truncate(detail, 240)}${reqId}`;\n }\n return `${head}${reqId}`;\n }\n}\n\nfunction describeStatus(status: number, type?: string): string {\n if (status === 0) return 'network error';\n if (type === 'overloaded_error' || status === 529) return `overloaded (${status})`;\n if (type === 'rate_limit_error' || status === 429) return `rate limited (${status})`;\n if (type === 'authentication_error' || status === 401) return `auth failed (${status})`;\n if (type === 'permission_error' || status === 403) return `forbidden (${status})`;\n if (type === 'not_found_error' || status === 404) return `not found (${status})`;\n if (type === 'invalid_request_error' || status === 400) return `invalid request (${status})`;\n if (status === 408) return `timeout (${status})`;\n if (status >= 500 && status < 600) return `HTTP ${status} (server error)`;\n if (type) return `${type} (${status})`;\n return `HTTP ${status}`;\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length <= n ? s : `${s.slice(0, n - 1)}…`;\n}\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,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AAE,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}"]}
|
package/dist/utils/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
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';
|
|
2
3
|
|
|
3
4
|
interface AtomicWriteOptions {
|
|
4
5
|
mode?: number;
|
|
@@ -85,4 +86,44 @@ declare function createToolOutputSerializer(opts?: ToolOutputSerializerOptions):
|
|
|
85
86
|
capBytes: number;
|
|
86
87
|
};
|
|
87
88
|
|
|
88
|
-
|
|
89
|
+
/**
|
|
90
|
+
* Shared token estimation with JSON.stringify caching.
|
|
91
|
+
* Avoids repeated stringification of tool input objects.
|
|
92
|
+
*/
|
|
93
|
+
/**
|
|
94
|
+
* 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.
|
|
97
|
+
*/
|
|
98
|
+
declare function estimateToolInputTokens(input: unknown): number;
|
|
99
|
+
/**
|
|
100
|
+
* Estimate tokens for a tool_result content.
|
|
101
|
+
*/
|
|
102
|
+
declare function estimateToolResultTokens(content: string | unknown): number;
|
|
103
|
+
/**
|
|
104
|
+
* Estimate tokens for a text block.
|
|
105
|
+
*/
|
|
106
|
+
declare function estimateTextTokens(text: string): number;
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Minimal JSON Schema validator — covers the subset needed for plugin
|
|
110
|
+
* configSchema validation and tool inputSchema sanity checks. Intentionally
|
|
111
|
+
* small (~80 lines, zero deps) and tolerant: unknown keywords are ignored so
|
|
112
|
+
* authors can mix in non-standard extensions without breaking validation.
|
|
113
|
+
*
|
|
114
|
+
* NOT for full JSON Schema 2020-12 conformance. If a plugin needs $ref,
|
|
115
|
+
* conditional schemas, format validation, or anything else exotic, it should
|
|
116
|
+
* bring its own ajv-based validator and call this only for the cheap path.
|
|
117
|
+
*/
|
|
118
|
+
|
|
119
|
+
interface ValidationError {
|
|
120
|
+
path: string;
|
|
121
|
+
message: string;
|
|
122
|
+
}
|
|
123
|
+
interface ValidationResult {
|
|
124
|
+
ok: boolean;
|
|
125
|
+
errors: ValidationError[];
|
|
126
|
+
}
|
|
127
|
+
declare function validateAgainstSchema(value: unknown, schema: JSONSchema): ValidationResult;
|
|
128
|
+
|
|
129
|
+
export { type AtomicWriteOptions, type NewlineStyle, type SafeParseResult, type ToolOutputSerializerOptions, type UnifiedDiffOptions, type ValidationError, type ValidationResult, atomicWrite, color, compileGlob, createToolOutputSerializer, detectNewlineStyle, ensureDir, estimateTextTokens, estimateToolInputTokens, estimateToolResultTokens, matchAny, matchGlob, normalizeToLf, safeParse, safeStringify, sanitizeJsonString, stripAnsi, toStyle, unifiedDiff, validateAgainstSchema };
|
package/dist/utils/index.js
CHANGED
|
@@ -16,8 +16,11 @@ async function atomicWrite(targetPath, content, opts = {}) {
|
|
|
16
16
|
}
|
|
17
17
|
try {
|
|
18
18
|
const fh = await fs.open(tmp, "r+");
|
|
19
|
-
|
|
20
|
-
|
|
19
|
+
try {
|
|
20
|
+
await fh.sync();
|
|
21
|
+
} finally {
|
|
22
|
+
await fh.close();
|
|
23
|
+
}
|
|
21
24
|
} catch {
|
|
22
25
|
}
|
|
23
26
|
let mode;
|
|
@@ -456,6 +459,122 @@ function createToolOutputSerializer(opts = {}) {
|
|
|
456
459
|
return { serialize, enforceCap, capBytes };
|
|
457
460
|
}
|
|
458
461
|
|
|
459
|
-
|
|
462
|
+
// src/utils/token-estimate.ts
|
|
463
|
+
var RoughTokenEstimate = (text) => Math.max(1, Math.ceil(text.length / 4));
|
|
464
|
+
function estimateToolInputTokens(input) {
|
|
465
|
+
if (typeof input === "string") return RoughTokenEstimate(input);
|
|
466
|
+
if (input !== null && typeof input === "object" && "__tokenEstimate" in input) {
|
|
467
|
+
return input.__tokenEstimate;
|
|
468
|
+
}
|
|
469
|
+
const str = typeof input === "object" ? JSON.stringify(input) : String(input);
|
|
470
|
+
const estimate = RoughTokenEstimate(str);
|
|
471
|
+
if (input !== null && typeof input === "object" && !Array.isArray(input)) {
|
|
472
|
+
input.__tokenEstimate = estimate;
|
|
473
|
+
}
|
|
474
|
+
return estimate;
|
|
475
|
+
}
|
|
476
|
+
function estimateToolResultTokens(content) {
|
|
477
|
+
if (typeof content === "string") return RoughTokenEstimate(content);
|
|
478
|
+
return RoughTokenEstimate(JSON.stringify(content));
|
|
479
|
+
}
|
|
480
|
+
function estimateTextTokens(text) {
|
|
481
|
+
return RoughTokenEstimate(text);
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// src/utils/json-schema-validate.ts
|
|
485
|
+
function validateAgainstSchema(value, schema) {
|
|
486
|
+
const errors = [];
|
|
487
|
+
walk(value, schema, "", errors);
|
|
488
|
+
return { ok: errors.length === 0, errors };
|
|
489
|
+
}
|
|
490
|
+
function walk(value, schema, path3, errors) {
|
|
491
|
+
if (schema.enum !== void 0) {
|
|
492
|
+
if (!schema.enum.some((e) => deepEqual(e, value))) {
|
|
493
|
+
errors.push({
|
|
494
|
+
path: path3 || "<root>",
|
|
495
|
+
message: `expected one of ${JSON.stringify(schema.enum)}, got ${JSON.stringify(value)}`
|
|
496
|
+
});
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
if (typeof schema.type === "string") {
|
|
501
|
+
if (!checkType(value, schema.type)) {
|
|
502
|
+
errors.push({
|
|
503
|
+
path: path3 || "<root>",
|
|
504
|
+
message: `expected ${schema.type}, got ${describeType(value)}`
|
|
505
|
+
});
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
if (schema.type === "object" && isPlainObject(value)) {
|
|
510
|
+
const obj = value;
|
|
511
|
+
for (const req of schema.required ?? []) {
|
|
512
|
+
if (!(req in obj)) {
|
|
513
|
+
errors.push({ path: joinPath(path3, req), message: "required property missing" });
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
if (schema.properties) {
|
|
517
|
+
for (const [key, subSchema] of Object.entries(schema.properties)) {
|
|
518
|
+
if (key in obj) {
|
|
519
|
+
walk(obj[key], subSchema, joinPath(path3, key), errors);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
if (schema.type === "array" && Array.isArray(value) && schema.items) {
|
|
525
|
+
value.forEach((item, i) => walk(item, schema.items, `${path3}[${i}]`, errors));
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
function checkType(value, type) {
|
|
529
|
+
switch (type) {
|
|
530
|
+
case "string":
|
|
531
|
+
return typeof value === "string";
|
|
532
|
+
case "number":
|
|
533
|
+
return typeof value === "number" && !Number.isNaN(value);
|
|
534
|
+
case "integer":
|
|
535
|
+
return typeof value === "number" && Number.isInteger(value);
|
|
536
|
+
case "boolean":
|
|
537
|
+
return typeof value === "boolean";
|
|
538
|
+
case "null":
|
|
539
|
+
return value === null;
|
|
540
|
+
case "array":
|
|
541
|
+
return Array.isArray(value);
|
|
542
|
+
case "object":
|
|
543
|
+
return isPlainObject(value);
|
|
544
|
+
default:
|
|
545
|
+
return true;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
function isPlainObject(v) {
|
|
549
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
550
|
+
}
|
|
551
|
+
function describeType(v) {
|
|
552
|
+
if (v === null) return "null";
|
|
553
|
+
if (Array.isArray(v)) return "array";
|
|
554
|
+
return typeof v;
|
|
555
|
+
}
|
|
556
|
+
function joinPath(parent, key) {
|
|
557
|
+
if (!parent) return key;
|
|
558
|
+
return `${parent}.${key}`;
|
|
559
|
+
}
|
|
560
|
+
function deepEqual(a, b) {
|
|
561
|
+
if (a === b) return true;
|
|
562
|
+
if (typeof a !== typeof b) return false;
|
|
563
|
+
if (a === null || b === null) return a === b;
|
|
564
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
565
|
+
return a.length === b.length && a.every((v, i) => deepEqual(v, b[i]));
|
|
566
|
+
}
|
|
567
|
+
if (typeof a === "object" && typeof b === "object") {
|
|
568
|
+
const ak = Object.keys(a);
|
|
569
|
+
const bk = Object.keys(b);
|
|
570
|
+
if (ak.length !== bk.length) return false;
|
|
571
|
+
return ak.every(
|
|
572
|
+
(k) => deepEqual(a[k], b[k])
|
|
573
|
+
);
|
|
574
|
+
}
|
|
575
|
+
return false;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
export { atomicWrite, color, compileGlob, createToolOutputSerializer, detectNewlineStyle, ensureDir, estimateTextTokens, estimateToolInputTokens, estimateToolResultTokens, matchAny, matchGlob, normalizeToLf, projectHash, resolveWstackPaths, safeParse, safeStringify, sanitizeJsonString, stripAnsi, toStyle, unifiedDiff, validateAgainstSchema };
|
|
460
579
|
//# sourceMappingURL=index.js.map
|
|
461
580
|
//# sourceMappingURL=index.js.map
|