confused-ai-core 0.1.0

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.
Files changed (114) hide show
  1. package/FEATURES.md +169 -0
  2. package/package.json +119 -0
  3. package/src/agent.ts +187 -0
  4. package/src/agentic/index.ts +87 -0
  5. package/src/agentic/runner.ts +386 -0
  6. package/src/agentic/types.ts +91 -0
  7. package/src/artifacts/artifact.ts +417 -0
  8. package/src/artifacts/index.ts +42 -0
  9. package/src/artifacts/media.ts +304 -0
  10. package/src/cli/index.ts +122 -0
  11. package/src/core/base-agent.ts +151 -0
  12. package/src/core/context-builder.ts +106 -0
  13. package/src/core/index.ts +8 -0
  14. package/src/core/schemas.ts +17 -0
  15. package/src/core/types.ts +158 -0
  16. package/src/create-agent.ts +309 -0
  17. package/src/debug-logger.ts +188 -0
  18. package/src/dx/agent.ts +88 -0
  19. package/src/dx/define-agent.ts +183 -0
  20. package/src/dx/dev-logger.ts +57 -0
  21. package/src/dx/index.ts +11 -0
  22. package/src/errors.ts +175 -0
  23. package/src/execution/engine.ts +522 -0
  24. package/src/execution/graph-builder.ts +362 -0
  25. package/src/execution/index.ts +8 -0
  26. package/src/execution/types.ts +257 -0
  27. package/src/execution/worker-pool.ts +308 -0
  28. package/src/extensions/index.ts +123 -0
  29. package/src/guardrails/allowlist.ts +155 -0
  30. package/src/guardrails/index.ts +17 -0
  31. package/src/guardrails/types.ts +159 -0
  32. package/src/guardrails/validator.ts +265 -0
  33. package/src/index.ts +74 -0
  34. package/src/knowledge/index.ts +5 -0
  35. package/src/knowledge/types.ts +52 -0
  36. package/src/learning/in-memory-store.ts +72 -0
  37. package/src/learning/index.ts +6 -0
  38. package/src/learning/types.ts +42 -0
  39. package/src/llm/cache.ts +300 -0
  40. package/src/llm/index.ts +22 -0
  41. package/src/llm/model-resolver.ts +81 -0
  42. package/src/llm/openai-provider.ts +313 -0
  43. package/src/llm/openrouter-provider.ts +29 -0
  44. package/src/llm/types.ts +131 -0
  45. package/src/memory/in-memory-store.ts +255 -0
  46. package/src/memory/index.ts +7 -0
  47. package/src/memory/types.ts +193 -0
  48. package/src/memory/vector-store.ts +251 -0
  49. package/src/observability/console-logger.ts +123 -0
  50. package/src/observability/index.ts +12 -0
  51. package/src/observability/metrics.ts +85 -0
  52. package/src/observability/otlp-exporter.ts +417 -0
  53. package/src/observability/tracer.ts +105 -0
  54. package/src/observability/types.ts +341 -0
  55. package/src/orchestration/agent-adapter.ts +33 -0
  56. package/src/orchestration/index.ts +34 -0
  57. package/src/orchestration/load-balancer.ts +151 -0
  58. package/src/orchestration/mcp-types.ts +59 -0
  59. package/src/orchestration/message-bus.ts +192 -0
  60. package/src/orchestration/orchestrator.ts +349 -0
  61. package/src/orchestration/pipeline.ts +66 -0
  62. package/src/orchestration/supervisor.ts +107 -0
  63. package/src/orchestration/swarm.ts +1099 -0
  64. package/src/orchestration/toolkit.ts +47 -0
  65. package/src/orchestration/types.ts +339 -0
  66. package/src/planner/classical-planner.ts +383 -0
  67. package/src/planner/index.ts +8 -0
  68. package/src/planner/llm-planner.ts +353 -0
  69. package/src/planner/types.ts +227 -0
  70. package/src/planner/validator.ts +297 -0
  71. package/src/production/circuit-breaker.ts +290 -0
  72. package/src/production/graceful-shutdown.ts +251 -0
  73. package/src/production/health.ts +333 -0
  74. package/src/production/index.ts +57 -0
  75. package/src/production/latency-eval.ts +62 -0
  76. package/src/production/rate-limiter.ts +287 -0
  77. package/src/production/resumable-stream.ts +289 -0
  78. package/src/production/types.ts +81 -0
  79. package/src/sdk/index.ts +374 -0
  80. package/src/session/db-driver.ts +50 -0
  81. package/src/session/in-memory-store.ts +235 -0
  82. package/src/session/index.ts +12 -0
  83. package/src/session/sql-store.ts +315 -0
  84. package/src/session/sqlite-store.ts +61 -0
  85. package/src/session/types.ts +153 -0
  86. package/src/tools/base-tool.ts +223 -0
  87. package/src/tools/browser-tool.ts +123 -0
  88. package/src/tools/calculator-tool.ts +265 -0
  89. package/src/tools/file-tools.ts +394 -0
  90. package/src/tools/github-tool.ts +432 -0
  91. package/src/tools/hackernews-tool.ts +187 -0
  92. package/src/tools/http-tool.ts +118 -0
  93. package/src/tools/index.ts +99 -0
  94. package/src/tools/jira-tool.ts +373 -0
  95. package/src/tools/notion-tool.ts +322 -0
  96. package/src/tools/openai-tool.ts +236 -0
  97. package/src/tools/registry.ts +131 -0
  98. package/src/tools/serpapi-tool.ts +234 -0
  99. package/src/tools/shell-tool.ts +118 -0
  100. package/src/tools/slack-tool.ts +327 -0
  101. package/src/tools/telegram-tool.ts +127 -0
  102. package/src/tools/types.ts +229 -0
  103. package/src/tools/websearch-tool.ts +335 -0
  104. package/src/tools/wikipedia-tool.ts +177 -0
  105. package/src/tools/yfinance-tool.ts +33 -0
  106. package/src/voice/index.ts +17 -0
  107. package/src/voice/voice-provider.ts +228 -0
  108. package/tests/artifact.test.ts +241 -0
  109. package/tests/circuit-breaker.test.ts +171 -0
  110. package/tests/health.test.ts +192 -0
  111. package/tests/llm-cache.test.ts +186 -0
  112. package/tests/rate-limiter.test.ts +161 -0
  113. package/tsconfig.json +29 -0
  114. package/vitest.config.ts +47 -0
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Minimal agent() — best DX: one import, one call.
3
+ *
4
+ * agent('You are helpful.')
5
+ * agent({ instructions: '...', model: 'openai:gpt-4o' })
6
+ */
7
+
8
+ import type { CreateAgentResult } from '../create-agent.js';
9
+ import type { CreateAgentOptions } from '../create-agent.js';
10
+ import { createAgent } from '../create-agent.js';
11
+ import { HttpClientTool } from '../tools/http-tool.js';
12
+ import { BrowserTool } from '../tools/browser-tool.js';
13
+ import { createDevLogger } from './dev-logger.js';
14
+ import { createDevToolMiddleware } from './dev-logger.js';
15
+
16
+ /** Minimal options when using agent({ ... }) */
17
+ export type AgentMinimalOptions = Partial<
18
+ Omit<CreateAgentOptions, 'name' | 'instructions'> & {
19
+ /** System instructions (required unless using agent(instructions) form) */
20
+ instructions: string;
21
+ /** Agent name (default: 'Agent') */
22
+ name?: string;
23
+ /** Enable dev mode: console + tool logging */
24
+ dev?: boolean;
25
+ }
26
+ >;
27
+
28
+ /**
29
+ * Create an agent with the best DX: minimal surface, smart defaults.
30
+ *
31
+ * One-argument form (instructions only):
32
+ * const runnable = agent('You are a helpful assistant.');
33
+ *
34
+ * Options form:
35
+ * const runnable = agent({
36
+ * instructions: 'You are helpful.',
37
+ * model: 'openai:gpt-4o',
38
+ * dev: true,
39
+ * });
40
+ *
41
+ * Returns the same runnable as createAgent() (run, createSession, getSessionMessages).
42
+ */
43
+ export function agent(instructionsOrOptions: string | AgentMinimalOptions): CreateAgentResult {
44
+ const isString = typeof instructionsOrOptions === 'string';
45
+ const options: CreateAgentOptions = isString
46
+ ? {
47
+ name: 'Agent',
48
+ instructions: instructionsOrOptions,
49
+ tools: [new HttpClientTool(), new BrowserTool()],
50
+ }
51
+ : {
52
+ name: instructionsOrOptions.name ?? 'Agent',
53
+ instructions: instructionsOrOptions.instructions ?? '',
54
+ model: instructionsOrOptions.model,
55
+ apiKey: instructionsOrOptions.apiKey,
56
+ baseURL: instructionsOrOptions.baseURL,
57
+ openRouter: instructionsOrOptions.openRouter,
58
+ llm: instructionsOrOptions.llm,
59
+ tools: instructionsOrOptions.tools ?? [new HttpClientTool(), new BrowserTool()],
60
+ toolMiddleware: instructionsOrOptions.toolMiddleware,
61
+ sessionStore: instructionsOrOptions.sessionStore,
62
+ guardrails: instructionsOrOptions.guardrails,
63
+ maxSteps: instructionsOrOptions.maxSteps,
64
+ timeoutMs: instructionsOrOptions.timeoutMs,
65
+ retry: instructionsOrOptions.retry,
66
+ logger: instructionsOrOptions.logger,
67
+ learningMode: instructionsOrOptions.learningMode,
68
+ userProfileStore: instructionsOrOptions.userProfileStore,
69
+ memoryStore: instructionsOrOptions.memoryStore,
70
+ ragEngine: instructionsOrOptions.ragEngine,
71
+ inputSchema: instructionsOrOptions.inputSchema,
72
+ outputSchema: instructionsOrOptions.outputSchema,
73
+ };
74
+
75
+ if (!options.instructions?.trim()) {
76
+ throw new Error('agent() requires instructions. Use agent("...") or agent({ instructions: "..." }).');
77
+ }
78
+
79
+ if (!isString && (instructionsOrOptions as AgentMinimalOptions).dev) {
80
+ options.logger = options.logger ?? createDevLogger();
81
+ options.toolMiddleware = [
82
+ ...(options.toolMiddleware ?? []),
83
+ createDevToolMiddleware(),
84
+ ];
85
+ }
86
+
87
+ return createAgent(options);
88
+ }
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Fluent agent builder — best DX: discoverable, chainable, typed.
3
+ *
4
+ * defineAgent()
5
+ * .name('Assistant')
6
+ * .instructions('You are helpful.')
7
+ * .model('openai:gpt-4o')
8
+ * .tools([new HttpClientTool()])
9
+ * .withSession()
10
+ * .dev()
11
+ * .build()
12
+ */
13
+
14
+ import type { CreateAgentOptions, CreateAgentResult } from '../create-agent.js';
15
+ import type { SessionStore } from '../session/types.js';
16
+ import type { GuardrailEngine } from '../guardrails/types.js';
17
+ import type { z } from 'zod';
18
+ import { createAgent } from '../create-agent.js';
19
+ import { InMemorySessionStore } from '../session/index.js';
20
+ import { HttpClientTool } from '../tools/http-tool.js';
21
+ import { BrowserTool } from '../tools/browser-tool.js';
22
+ import { createDevLogger } from './dev-logger.js';
23
+ import { createDevToolMiddleware } from './dev-logger.js';
24
+
25
+ export interface DefineAgentOptions
26
+ extends Pick<
27
+ CreateAgentOptions,
28
+ | 'name'
29
+ | 'instructions'
30
+ | 'model'
31
+ | 'apiKey'
32
+ | 'baseURL'
33
+ | 'openRouter'
34
+ | 'tools'
35
+ | 'toolMiddleware'
36
+ | 'sessionStore'
37
+ | 'guardrails'
38
+ | 'maxSteps'
39
+ | 'timeoutMs'
40
+ | 'retry'
41
+ | 'logger'
42
+ | 'learningMode'
43
+ | 'userProfileStore'
44
+ | 'memoryStore'
45
+ | 'ragEngine'
46
+ | 'inputSchema'
47
+ | 'outputSchema'
48
+ > {
49
+ /** Enable dev mode: console logger + tool call logging */
50
+ dev?: boolean;
51
+ }
52
+
53
+ /**
54
+ * Fluent builder for creating agents with best DX.
55
+ * Chain methods and call .build() to get a runnable agent.
56
+ */
57
+ export function defineAgent(): AgentBuilder {
58
+ return new AgentBuilder({});
59
+ }
60
+
61
+ class AgentBuilder {
62
+ private options: Partial<DefineAgentOptions> = {};
63
+
64
+ constructor(options: Partial<DefineAgentOptions>) {
65
+ this.options = { ...options };
66
+ }
67
+
68
+ /** Set agent name */
69
+ name(name: string): AgentBuilder {
70
+ return new AgentBuilder({ ...this.options, name });
71
+ }
72
+
73
+ /** Set system instructions (required before build) */
74
+ instructions(instructions: string): AgentBuilder {
75
+ return new AgentBuilder({ ...this.options, instructions });
76
+ }
77
+
78
+ /** Set model: id or "provider:model_id" (e.g. openai:gpt-4o, ollama:llama3.2) */
79
+ model(model: string): AgentBuilder {
80
+ return new AgentBuilder({ ...this.options, model });
81
+ }
82
+
83
+ /** Set API key (overrides env) */
84
+ apiKey(apiKey: string): AgentBuilder {
85
+ return new AgentBuilder({ ...this.options, apiKey });
86
+ }
87
+
88
+ /** Set base URL (e.g. Ollama) */
89
+ baseURL(baseURL: string): AgentBuilder {
90
+ return new AgentBuilder({ ...this.options, baseURL });
91
+ }
92
+
93
+ /** Set OpenRouter config */
94
+ openRouter(config: { apiKey?: string; model?: string }): AgentBuilder {
95
+ return new AgentBuilder({ ...this.options, openRouter: config });
96
+ }
97
+
98
+ /** Set tools (array or registry). Omit for default HTTP + browser tools. */
99
+ tools(tools: CreateAgentOptions['tools']): AgentBuilder {
100
+ return new AgentBuilder({ ...this.options, tools });
101
+ }
102
+
103
+ /** Set session store. Call with no args for in-memory; pass store for DB. */
104
+ withSession(store?: SessionStore): AgentBuilder {
105
+ return new AgentBuilder({ ...this.options, sessionStore: store ?? new InMemorySessionStore() });
106
+ }
107
+
108
+ /** Set guardrails. Pass false to disable. */
109
+ withGuardrails(guardrails: GuardrailEngine | false): AgentBuilder {
110
+ return new AgentBuilder({ ...this.options, guardrails });
111
+ }
112
+
113
+ /** Max agentic steps */
114
+ maxSteps(n: number): AgentBuilder {
115
+ return new AgentBuilder({ ...this.options, maxSteps: n });
116
+ }
117
+
118
+ /** Run timeout in ms */
119
+ timeoutMs(ms: number): AgentBuilder {
120
+ return new AgentBuilder({ ...this.options, timeoutMs: ms });
121
+ }
122
+
123
+ /** Retry policy */
124
+ retry(policy: CreateAgentOptions['retry']): AgentBuilder {
125
+ return new AgentBuilder({ ...this.options, retry: policy });
126
+ }
127
+
128
+ /** Type-safe input schema (Zod) */
129
+ inputSchema<T>(schema: z.ZodType<T>): AgentBuilder {
130
+ return new AgentBuilder({ ...this.options, inputSchema: schema });
131
+ }
132
+
133
+ /** Type-safe output schema (Zod) */
134
+ outputSchema<T>(schema: z.ZodType<T>): AgentBuilder {
135
+ return new AgentBuilder({ ...this.options, outputSchema: schema });
136
+ }
137
+
138
+ /** Enable dev mode: console logger + tool call logging */
139
+ dev(): AgentBuilder {
140
+ return new AgentBuilder({ ...this.options, dev: true });
141
+ }
142
+
143
+ /** Build and return a runnable agent */
144
+ build(): CreateAgentResult {
145
+ const opts = this.options;
146
+ if (!opts.instructions?.trim()) {
147
+ throw new Error('defineAgent().build() requires instructions. Call .instructions("...") first.');
148
+ }
149
+
150
+ const createOpts: CreateAgentOptions = {
151
+ name: opts.name ?? 'Agent',
152
+ instructions: opts.instructions,
153
+ model: opts.model,
154
+ apiKey: opts.apiKey,
155
+ baseURL: opts.baseURL,
156
+ openRouter: opts.openRouter,
157
+ tools: opts.tools ?? [new HttpClientTool(), new BrowserTool()],
158
+ toolMiddleware: opts.toolMiddleware,
159
+ sessionStore: opts.sessionStore ?? new InMemorySessionStore(),
160
+ guardrails: opts.guardrails,
161
+ maxSteps: opts.maxSteps,
162
+ timeoutMs: opts.timeoutMs,
163
+ retry: opts.retry,
164
+ logger: opts.logger,
165
+ learningMode: opts.learningMode,
166
+ userProfileStore: opts.userProfileStore,
167
+ memoryStore: opts.memoryStore,
168
+ ragEngine: opts.ragEngine,
169
+ inputSchema: opts.inputSchema,
170
+ outputSchema: opts.outputSchema,
171
+ };
172
+
173
+ if (opts.dev) {
174
+ createOpts.logger = createOpts.logger ?? createDevLogger();
175
+ createOpts.toolMiddleware = [
176
+ ...(createOpts.toolMiddleware ?? []),
177
+ createDevToolMiddleware(),
178
+ ];
179
+ }
180
+
181
+ return createAgent(createOpts);
182
+ }
183
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Dev-mode logger: tool calls, steps, and agent lifecycle for best DX.
3
+ */
4
+
5
+ import type { Logger } from '../observability/types.js';
6
+
7
+ const P = '[ConfusedAI]';
8
+
9
+ function formatMeta(meta?: Record<string, unknown>): string {
10
+ if (!meta || Object.keys(meta).length === 0) return '';
11
+ return ' ' + JSON.stringify(meta);
12
+ }
13
+
14
+ /**
15
+ * Logger that prints tool calls, steps, and debug info in development.
16
+ * Use with createAgent({ dev: true }) or defineAgent().dev().build().
17
+ */
18
+ export function createDevLogger(): Logger {
19
+ return {
20
+ debug(message: string, _context?: Partial<Record<string, unknown>>, metadata?: Record<string, unknown>) {
21
+ console.debug(`${P} ${message}${formatMeta(metadata)}`);
22
+ },
23
+ info(message: string, _context?: Partial<Record<string, unknown>>, metadata?: Record<string, unknown>) {
24
+ console.info(`${P} ${message}${formatMeta(metadata)}`);
25
+ },
26
+ warn(message: string, _context?: Partial<Record<string, unknown>>, metadata?: Record<string, unknown>) {
27
+ console.warn(`${P} ${message}${formatMeta(metadata)}`);
28
+ },
29
+ error(message: string, _context?: Partial<Record<string, unknown>>, metadata?: Record<string, unknown>) {
30
+ console.error(`${P} ${message}${formatMeta(metadata)}`);
31
+ },
32
+ fatal(message: string, _context?: Partial<Record<string, unknown>>, metadata?: Record<string, unknown>) {
33
+ console.error(`${P} [FATAL] ${message}${formatMeta(metadata)}`);
34
+ },
35
+ child(_additionalContext: Partial<Record<string, unknown>>) {
36
+ return createDevLogger();
37
+ },
38
+ };
39
+ }
40
+
41
+ /**
42
+ * Create tool middleware that logs every tool call/result in dev (best DX).
43
+ */
44
+ export function createDevToolMiddleware(): import('../tools/types.js').ToolMiddleware {
45
+ return {
46
+ beforeExecute(tool, params) {
47
+ console.debug(`${P} 🔧 tool.call ${tool.name}`, params);
48
+ },
49
+ afterExecute(tool, result, _ctx) {
50
+ const preview = result.success ? JSON.stringify(result.data).slice(0, 80) : result.error?.message ?? 'error';
51
+ console.debug(`${P} 🔧 tool.done ${tool.name} (${result.executionTimeMs}ms)`, preview);
52
+ },
53
+ onError(tool, err, _ctx) {
54
+ console.debug(`${P} 🔧 tool.error ${tool.name}`, err.message);
55
+ },
56
+ };
57
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Best DX for creating agents in TypeScript.
3
+ *
4
+ * - agent(instructions) or agent({ instructions, model, dev }) — minimal, one call
5
+ * - defineAgent().instructions('...').model('...').dev().build() — fluent, discoverable
6
+ * - createDevLogger() / createDevToolMiddleware() — dev-mode visibility
7
+ */
8
+
9
+ export { agent, type AgentMinimalOptions } from './agent.js';
10
+ export { defineAgent, type DefineAgentOptions } from './define-agent.js';
11
+ export { createDevLogger, createDevToolMiddleware } from './dev-logger.js';
package/src/errors.ts ADDED
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Production-grade structured errors for the agent framework.
3
+ * Industry-standard error codes and context for observability and handling.
4
+ */
5
+
6
+ /** Error codes for programmatic handling and metrics */
7
+ export const ErrorCode = {
8
+ /** Agent run failed (generic) */
9
+ AGENT_ERROR: 'AGENT_ERROR',
10
+ /** LLM provider call failed */
11
+ LLM_ERROR: 'LLM_ERROR',
12
+ /** Tool execution failed */
13
+ TOOL_ERROR: 'TOOL_ERROR',
14
+ /** Tool validation (parameters) failed */
15
+ TOOL_VALIDATION_ERROR: 'TOOL_VALIDATION_ERROR',
16
+ /** Guardrail check failed */
17
+ GUARDRAIL_VIOLATION: 'GUARDRAIL_VIOLATION',
18
+ /** Run or step timed out */
19
+ TIMEOUT: 'TIMEOUT',
20
+ /** Run was cancelled (e.g. AbortSignal) */
21
+ CANCELLED: 'CANCELLED',
22
+ /** Invalid configuration or parameters */
23
+ CONFIG_ERROR: 'CONFIG_ERROR',
24
+ /** Session or persistence error */
25
+ SESSION_ERROR: 'SESSION_ERROR',
26
+ /** Permission denied for tool or resource */
27
+ PERMISSION_DENIED: 'PERMISSION_DENIED',
28
+ /** Max steps reached without final answer */
29
+ MAX_STEPS: 'MAX_STEPS',
30
+ } as const;
31
+
32
+ export type ErrorCodeType = (typeof ErrorCode)[keyof typeof ErrorCode];
33
+
34
+ /** Base agent error with code and context */
35
+ export class AgentError extends Error {
36
+ readonly code: ErrorCodeType;
37
+ readonly cause?: Error;
38
+ readonly context?: Record<string, unknown>;
39
+
40
+ constructor(
41
+ message: string,
42
+ options: {
43
+ code?: ErrorCodeType;
44
+ cause?: Error;
45
+ context?: Record<string, unknown>;
46
+ } = {}
47
+ ) {
48
+ super(message);
49
+ this.name = 'AgentError';
50
+ this.code = options.code ?? ErrorCode.AGENT_ERROR;
51
+ this.cause = options.cause;
52
+ this.context = options.context;
53
+ Object.setPrototypeOf(this, AgentError.prototype);
54
+ }
55
+
56
+ toJSON(): Record<string, unknown> {
57
+ return {
58
+ name: this.name,
59
+ message: this.message,
60
+ code: this.code,
61
+ context: this.context,
62
+ cause: this.cause?.message,
63
+ };
64
+ }
65
+ }
66
+
67
+ /** LLM provider or API failure */
68
+ export class LLMError extends AgentError {
69
+ constructor(
70
+ message: string,
71
+ options: { cause?: Error; context?: Record<string, unknown> } = {}
72
+ ) {
73
+ super(message, { ...options, code: ErrorCode.LLM_ERROR });
74
+ this.name = 'LLMError';
75
+ Object.setPrototypeOf(this, LLMError.prototype);
76
+ }
77
+ }
78
+
79
+ /** Tool execution or validation failure (exception; for result errors see tools/types ToolError) */
80
+ export class ToolExecutionError extends AgentError {
81
+ readonly toolName?: string;
82
+
83
+ constructor(
84
+ message: string,
85
+ options: {
86
+ cause?: Error;
87
+ toolName?: string;
88
+ context?: Record<string, unknown>;
89
+ code?: ErrorCodeType;
90
+ } = {}
91
+ ) {
92
+ super(message, {
93
+ ...options,
94
+ code: options.code ?? ErrorCode.TOOL_ERROR,
95
+ });
96
+ this.name = 'ToolExecutionError';
97
+ this.toolName = options.toolName;
98
+ Object.setPrototypeOf(this, ToolExecutionError.prototype);
99
+ }
100
+ }
101
+
102
+ /** Guardrail check failed */
103
+ export class GuardrailError extends AgentError {
104
+ readonly rule?: string;
105
+
106
+ constructor(
107
+ message: string,
108
+ options: { rule?: string; context?: Record<string, unknown> } = {}
109
+ ) {
110
+ super(message, { ...options, code: ErrorCode.GUARDRAIL_VIOLATION });
111
+ this.name = 'GuardrailError';
112
+ this.rule = options.rule;
113
+ Object.setPrototypeOf(this, GuardrailError.prototype);
114
+ }
115
+ }
116
+
117
+ /** Run or step timeout */
118
+ export class TimeoutError extends AgentError {
119
+ readonly timeoutMs?: number;
120
+
121
+ constructor(
122
+ message: string,
123
+ options: { timeoutMs?: number; context?: Record<string, unknown> } = {}
124
+ ) {
125
+ super(message, { ...options, code: ErrorCode.TIMEOUT });
126
+ this.name = 'TimeoutError';
127
+ this.timeoutMs = options.timeoutMs;
128
+ Object.setPrototypeOf(this, TimeoutError.prototype);
129
+ }
130
+ }
131
+
132
+ /** Run cancelled (e.g. AbortController) */
133
+ export class CancellationError extends AgentError {
134
+ constructor(message = 'Run was cancelled', options: { context?: Record<string, unknown> } = {}) {
135
+ super(message, { ...options, code: ErrorCode.CANCELLED });
136
+ this.name = 'CancellationError';
137
+ Object.setPrototypeOf(this, CancellationError.prototype);
138
+ }
139
+ }
140
+
141
+ /** Configuration or setup error */
142
+ export class ConfigError extends AgentError {
143
+ constructor(
144
+ message: string,
145
+ options: { cause?: Error; context?: Record<string, unknown> } = {}
146
+ ) {
147
+ super(message, { ...options, code: ErrorCode.CONFIG_ERROR });
148
+ this.name = 'ConfigError';
149
+ Object.setPrototypeOf(this, ConfigError.prototype);
150
+ }
151
+ }
152
+
153
+ /** Session store or persistence error */
154
+ export class SessionError extends AgentError {
155
+ constructor(
156
+ message: string,
157
+ options: { cause?: Error; context?: Record<string, unknown> } = {}
158
+ ) {
159
+ super(message, { ...options, code: ErrorCode.SESSION_ERROR });
160
+ this.name = 'SessionError';
161
+ Object.setPrototypeOf(this, SessionError.prototype);
162
+ }
163
+ }
164
+
165
+ /** Permission denied for tool or resource */
166
+ export class PermissionError extends AgentError {
167
+ constructor(
168
+ message: string,
169
+ options: { context?: Record<string, unknown> } = {}
170
+ ) {
171
+ super(message, { ...options, code: ErrorCode.PERMISSION_DENIED });
172
+ this.name = 'PermissionError';
173
+ Object.setPrototypeOf(this, PermissionError.prototype);
174
+ }
175
+ }