connectonion 0.0.1

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 (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +362 -0
  3. package/dist/connect.d.ts +35 -0
  4. package/dist/connect.d.ts.map +1 -0
  5. package/dist/connect.js +149 -0
  6. package/dist/console.d.ts +30 -0
  7. package/dist/console.d.ts.map +1 -0
  8. package/dist/console.js +124 -0
  9. package/dist/core/agent.d.ts +233 -0
  10. package/dist/core/agent.d.ts.map +1 -0
  11. package/dist/core/agent.js +500 -0
  12. package/dist/examples/comprehensive-test.js +314 -0
  13. package/dist/examples/simple-test.js +80 -0
  14. package/dist/history/index.d.ts +42 -0
  15. package/dist/history/index.d.ts.map +1 -0
  16. package/dist/history/index.js +140 -0
  17. package/dist/index.d.ts +20 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +53 -0
  20. package/dist/llm/anthropic.d.ts +23 -0
  21. package/dist/llm/anthropic.d.ts.map +1 -0
  22. package/dist/llm/anthropic.js +139 -0
  23. package/dist/llm/gemini.d.ts +20 -0
  24. package/dist/llm/gemini.d.ts.map +1 -0
  25. package/dist/llm/gemini.js +136 -0
  26. package/dist/llm/index.d.ts +18 -0
  27. package/dist/llm/index.d.ts.map +1 -0
  28. package/dist/llm/index.js +76 -0
  29. package/dist/llm/llm-do.d.ts +8 -0
  30. package/dist/llm/llm-do.d.ts.map +1 -0
  31. package/dist/llm/llm-do.js +25 -0
  32. package/dist/llm/noop.d.ts +16 -0
  33. package/dist/llm/noop.d.ts.map +1 -0
  34. package/dist/llm/noop.js +23 -0
  35. package/dist/llm/openai.d.ts +21 -0
  36. package/dist/llm/openai.d.ts.map +1 -0
  37. package/dist/llm/openai.js +131 -0
  38. package/dist/src/core/agent.js +368 -0
  39. package/dist/src/history/index.js +140 -0
  40. package/dist/src/index.js +34 -0
  41. package/dist/src/llm/index.js +22 -0
  42. package/dist/src/llm/openai.js +78 -0
  43. package/dist/src/tools/tool-utils.js +348 -0
  44. package/dist/src/types.js +8 -0
  45. package/dist/tools/email.d.ts +13 -0
  46. package/dist/tools/email.d.ts.map +1 -0
  47. package/dist/tools/email.js +98 -0
  48. package/dist/tools/replay.d.ts +19 -0
  49. package/dist/tools/replay.d.ts.map +1 -0
  50. package/dist/tools/replay.js +62 -0
  51. package/dist/tools/tool-executor.d.ts +58 -0
  52. package/dist/tools/tool-executor.d.ts.map +1 -0
  53. package/dist/tools/tool-executor.js +100 -0
  54. package/dist/tools/tool-utils.d.ts +133 -0
  55. package/dist/tools/tool-utils.d.ts.map +1 -0
  56. package/dist/tools/tool-utils.js +380 -0
  57. package/dist/tools/xray.d.ts +58 -0
  58. package/dist/tools/xray.d.ts.map +1 -0
  59. package/dist/tools/xray.js +110 -0
  60. package/dist/trust/index.d.ts +26 -0
  61. package/dist/trust/index.d.ts.map +1 -0
  62. package/dist/trust/index.js +47 -0
  63. package/dist/trust/tools.d.ts +4 -0
  64. package/dist/trust/tools.d.ts.map +1 -0
  65. package/dist/trust/tools.js +71 -0
  66. package/dist/types.d.ts +141 -0
  67. package/dist/types.d.ts.map +1 -0
  68. package/dist/types.js +10 -0
  69. package/package.json +63 -0
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ /**
3
+ * @purpose Dual-output logging system (terminal + optional file) that mirrors Python SDK UX with colored terminal output and @xray tool tracing
4
+ * @llm-note
5
+ * Dependencies: imports from [node:fs, node:path] | imported by [src/core/agent.ts, src/tools/tool-executor.ts] | tested by agent tests
6
+ * Data flow: receives log messages/xray traces → formats with timestamps/colors → writes to stderr + optional file (.co/logs/{name}.log)
7
+ * State/Effects: writes to stderr via console.error | appends to logFile if configured | creates log directories with fs.mkdirSync
8
+ * Integration: exposes print(message), printXray(toolName, args, result, timing, context) | used by Agent for all output | ANSI color support via isTTY detection
9
+ */
10
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ var desc = Object.getOwnPropertyDescriptor(m, k);
13
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
14
+ desc = { enumerable: true, get: function() { return m[k]; } };
15
+ }
16
+ Object.defineProperty(o, k2, desc);
17
+ }) : (function(o, m, k, k2) {
18
+ if (k2 === undefined) k2 = k;
19
+ o[k2] = m[k];
20
+ }));
21
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
22
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
23
+ }) : function(o, v) {
24
+ o["default"] = v;
25
+ });
26
+ var __importStar = (this && this.__importStar) || (function () {
27
+ var ownKeys = function(o) {
28
+ ownKeys = Object.getOwnPropertyNames || function (o) {
29
+ var ar = [];
30
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
31
+ return ar;
32
+ };
33
+ return ownKeys(o);
34
+ };
35
+ return function (mod) {
36
+ if (mod && mod.__esModule) return mod;
37
+ var result = {};
38
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
39
+ __setModuleDefault(result, mod);
40
+ return result;
41
+ };
42
+ })();
43
+ Object.defineProperty(exports, "__esModule", { value: true });
44
+ exports.Console = void 0;
45
+ const fs = __importStar(require("fs"));
46
+ const path = __importStar(require("path"));
47
+ class Console {
48
+ constructor(logFile) {
49
+ this.logPath = logFile;
50
+ this.colorEnabled = !!process.stderr.isTTY || process.env.FORCE_COLOR === '1';
51
+ if (this.logPath)
52
+ this.initLogFile();
53
+ }
54
+ initLogFile() {
55
+ const dir = path.dirname(this.logPath);
56
+ if (!fs.existsSync(dir))
57
+ fs.mkdirSync(dir, { recursive: true });
58
+ const header = `\n============================================================\n` +
59
+ `Session started: ${new Date().toISOString()}\n` +
60
+ `============================================================\n\n`;
61
+ fs.appendFileSync(this.logPath, header, 'utf-8');
62
+ }
63
+ print(message) {
64
+ const timestamp = new Date().toTimeString().split(' ')[0];
65
+ const line = `${this.dim(timestamp)} ${this.stylize(message)}`;
66
+ // stderr-like behavior
67
+ console.error(line);
68
+ if (this.logPath) {
69
+ fs.appendFileSync(this.logPath, `[${timestamp}] ${this.toPlain(message)}\n`, 'utf-8');
70
+ }
71
+ }
72
+ printXray(toolName, toolArgs, result, timingMs, context) {
73
+ // Simple tabular block
74
+ this.print(`@xray: ${toolName}`);
75
+ if (context?.agent)
76
+ this.print(` agent: ${context.agent}`);
77
+ if (context?.userPrompt)
78
+ this.print(` task: ${context.userPrompt.slice(0, 80)}`);
79
+ if (context?.iteration != null)
80
+ this.print(` iteration: ${context.iteration}`);
81
+ for (const [k, v] of Object.entries(toolArgs || {})) {
82
+ const s = String(v);
83
+ this.print(` ${k}: ${s.length > 120 ? s.slice(0, 120) + '...' : s}`);
84
+ }
85
+ const rs = String(result);
86
+ this.print(` result: ${rs.length > 120 ? rs.slice(0, 120) + '...' : rs}`);
87
+ this.print(` timing: ${timingMs.toFixed(1)}ms`);
88
+ }
89
+ toPlain(message) {
90
+ return message
91
+ .replace(/\[[^\]]+\]/g, '')
92
+ .replace('→', '->')
93
+ .replace('←', '<-')
94
+ .replace('✓', '[OK]')
95
+ .replace('✗', '[ERROR]');
96
+ }
97
+ stylize(msg) {
98
+ // Simple heuristic coloring similar to Python Rich output
99
+ if (!this.colorEnabled)
100
+ return msg;
101
+ if (msg.startsWith('→'))
102
+ return this.yellow(msg);
103
+ if (msg.startsWith('←'))
104
+ return this.green(msg);
105
+ if (msg.startsWith('✓'))
106
+ return this.green(msg);
107
+ if (msg.startsWith('✗'))
108
+ return this.red(msg);
109
+ if (msg.startsWith('@xray'))
110
+ return this.cyan(msg);
111
+ if (msg.startsWith('INPUT:'))
112
+ return this.bold(msg);
113
+ return msg;
114
+ }
115
+ // Color helpers
116
+ code(s, c) { return this.colorEnabled ? `\x1b[${c}m${s}\x1b[0m` : s; }
117
+ green(s) { return this.code(s, 32); }
118
+ red(s) { return this.code(s, 31); }
119
+ yellow(s) { return this.code(s, 33); }
120
+ cyan(s) { return this.code(s, 36); }
121
+ dim(s) { return this.code(s, 2); }
122
+ bold(s) { return this.code(s, 1); }
123
+ }
124
+ exports.Console = Console;
@@ -0,0 +1,233 @@
1
+ /**
2
+ * @purpose Main Agent orchestrator that combines LLM reasoning with parallel tool execution, multi-turn conversations, and interactive debugging
3
+ * @llm-note
4
+ * Dependencies: imports from [src/types, src/llm/index, src/console, src/tools/tool-utils, src/trust/index, node:fs, node:dotenv, node:readline] | imported by [src/index.ts] | tested by [tests/agent.test.ts, tests/e2e/*.test.ts]
5
+ * Data flow: receives user prompt → lazy-init messages array (system + user) → LLM loop (max 10 iterations) → parallel tool execution via Promise.all → adds tool results to messages → repeats until no tool calls → returns final text response
6
+ * State/Effects: mutates this.messages (persistent conversation state) | writes to Console (stderr + optional file) | reads systemPrompt from file if path provided | reads env for API keys/config
7
+ * Integration: exposes input(prompt, maxIterations?), resetConversation(), addTool(), removeTool(), getTools(), executeTool(), autoDebug(), getSession(), getTrust() | uses createLLM() factory | tool execution at line 285-302 (parallel) | main loop at line 221-267
8
+ * Performance: parallel tool execution via Promise.all | no caching | tool map for O(1) lookup | max 10 iterations default (configurable)
9
+ * ⚠️ messages persist across input() calls until resetConversation() | @xray tools pause execution in debug mode | tool errors returned to LLM for retry
10
+ */
11
+ import { AgentConfig, Tool, Message, ToolResult } from '../types';
12
+ /**
13
+ * Agent class - The core of ConnectOnion
14
+ *
15
+ * An Agent combines:
16
+ * - LLM for intelligence and reasoning
17
+ * - Tools for taking actions
18
+ * - In-memory session (messages + trace)
19
+ * - System prompts for personality
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * // Create a simple agent with a calculator tool
24
+ * function add(a: number, b: number): number {
25
+ * return a + b;
26
+ * }
27
+ *
28
+ * const agent = new Agent({
29
+ * name: 'calculator',
30
+ * tools: [add],
31
+ * systemPrompt: 'You are a helpful math assistant.'
32
+ * });
33
+ *
34
+ * const response = await agent.input('What is 5 plus 3?');
35
+ * console.log(response); // "5 plus 3 equals 8"
36
+ * ```
37
+ */
38
+ export declare class Agent {
39
+ /** Unique identifier for this agent */
40
+ private name;
41
+ /** System prompt that defines the agent's behavior and personality */
42
+ private systemPrompt;
43
+ /** Maximum number of iterations for tool calling loops */
44
+ private maxIterations;
45
+ /** Array of tools available to this agent */
46
+ private tools;
47
+ /** Quick lookup map for tools by name */
48
+ private toolMap;
49
+ /** LLM instance for generating responses */
50
+ private llm;
51
+ /** Session interface aligned with Python: messages + trace */
52
+ /** Persistent conversation messages for multi-turn interactions */
53
+ private messages;
54
+ /** Console for terminal + optional file logging */
55
+ private console;
56
+ /** Current iteration counter for logging */
57
+ private currentIteration;
58
+ /** Debug flag to pause at @xray tools */
59
+ private debugEnabled;
60
+ /** Trust configuration object */
61
+ private _trust;
62
+ /** In-memory trace entries for xray-style introspection */
63
+ private trace;
64
+ /** Last user prompt, for xray context */
65
+ private lastUserPrompt;
66
+ /**
67
+ * Creates a new Agent instance
68
+ *
69
+ * @param config - Configuration object for the agent
70
+ * @param config.name - Unique name for the agent (used for behavior tracking)
71
+ * @param config.llm - Optional custom LLM instance
72
+ * @param config.tools - Array of tools (functions, class instances, or Tool objects)
73
+ * @param config.systemPrompt - System prompt defining agent behavior
74
+ * @param config.apiKey - API key for LLM provider (uses env var if not provided)
75
+ * @param config.model - Model to use (default: 'gpt-4o-mini')
76
+ * @param config.maxIterations - Max iterations for tool calling (default: 10)
77
+ *
78
+ * @example
79
+ * ```typescript
80
+ * // With environment variable for API key
81
+ * const agent = new Agent({
82
+ * name: 'my-agent',
83
+ * tools: [myTool1, myTool2]
84
+ * });
85
+ *
86
+ * // With explicit API key
87
+ * const agent = new Agent({
88
+ * name: 'my-agent',
89
+ * apiKey: 'sk-...',
90
+ * model: 'gpt-4',
91
+ * tools: [myTool]
92
+ * });
93
+ * ```
94
+ */
95
+ constructor(config: AgentConfig);
96
+ /**
97
+ * Process user input and generate a response
98
+ *
99
+ * This is the main entry point for interacting with the agent.
100
+ * The agent will:
101
+ * 1. Process the input prompt
102
+ * 2. Decide whether to use tools
103
+ * 3. Execute any necessary tool calls
104
+ * 4. Generate a final response
105
+ *
106
+ * @param prompt - The user's input prompt
107
+ * @param maxIterations - Override the default max iterations for this request
108
+ * @returns The agent's response as a string
109
+ *
110
+ * @example
111
+ * ```typescript
112
+ * const response = await agent.input('What is the weather in NYC?');
113
+ * console.log(response);
114
+ *
115
+ * // With custom iteration limit for complex tasks
116
+ * const response = await agent.input(
117
+ * 'Analyze this data and create a report',
118
+ * 20 // Allow more iterations for complex task
119
+ * );
120
+ * ```
121
+ */
122
+ input(prompt: string, maxIterations?: number): Promise<string>;
123
+ /**
124
+ * Execute multiple tool calls in parallel
125
+ *
126
+ * @param toolCalls - Array of tool calls to execute
127
+ * @returns Array of results with their corresponding call IDs
128
+ *
129
+ * @private
130
+ */
131
+ private executeToolCalls;
132
+ /**
133
+ * Execute a single tool call
134
+ *
135
+ * @param name - Name of the tool to execute
136
+ * @param args - Arguments to pass to the tool
137
+ * @param callId - Unique identifier for this tool call
138
+ * @returns The result of the tool execution
139
+ *
140
+ * @private
141
+ */
142
+ private executeToolCall;
143
+ /** Pause at @xray breakpoint with basic interactive menu */
144
+ private pauseAtBreakpoint;
145
+ /** Start a debugging session. If prompt provided, runs single session. */
146
+ autoDebug(prompt?: string): Promise<string | void>;
147
+ /** Get trust configuration */
148
+ getTrust(): any;
149
+ /**
150
+ * Get the current in-memory session (messages + tool execution trace)
151
+ */
152
+ getSession(): {
153
+ messages: Message[];
154
+ trace: {
155
+ tool_name: string;
156
+ timing: number;
157
+ status: string;
158
+ args?: any;
159
+ result?: any;
160
+ iteration?: number;
161
+ }[];
162
+ iteration: number;
163
+ user_prompt: string;
164
+ };
165
+ /**
166
+ * Clear the in-memory tool execution trace for this session
167
+ */
168
+ clearHistory(): void;
169
+ /**
170
+ * Get all available tools for this agent
171
+ *
172
+ * @returns Array of Tool objects
173
+ *
174
+ * @example
175
+ * ```typescript
176
+ * const tools = agent.getTools();
177
+ * console.log('Available tools:');
178
+ * tools.forEach(tool => {
179
+ * console.log(`- ${tool.name}: ${tool.description}`);
180
+ * });
181
+ * ```
182
+ */
183
+ getTools(): Tool[];
184
+ /**
185
+ * List tool names for quick inspection
186
+ */
187
+ listTools(): string[];
188
+ /**
189
+ * Dynamically add a new tool to the agent
190
+ *
191
+ * @param tool - Tool to add (function, class instance, or Tool object)
192
+ *
193
+ * @example
194
+ * ```typescript
195
+ * // Add a function as a tool
196
+ * function newTool(param: string): string {
197
+ * return `Processed: ${param}`;
198
+ * }
199
+ * agent.addTool(newTool);
200
+ *
201
+ * // Add a class instance
202
+ * class MyService {
203
+ * getData(): string { return 'data'; }
204
+ * }
205
+ * agent.addTool(new MyService());
206
+ * ```
207
+ */
208
+ addTool(tool: Tool | Function | any): void;
209
+ /**
210
+ * Remove a tool by name
211
+ *
212
+ * @param name - Name of the tool to remove
213
+ * @returns true if the tool was found and removed, false otherwise
214
+ *
215
+ * @example
216
+ * ```typescript
217
+ * const removed = agent.removeTool('oldTool');
218
+ * if (removed) {
219
+ * console.log('Tool removed successfully');
220
+ * }
221
+ * ```
222
+ */
223
+ removeTool(name: string): boolean;
224
+ /**
225
+ * Execute a single tool by name with arguments (manual invocation)
226
+ */
227
+ executeTool(name: string, args?: Record<string, any>): Promise<ToolResult>;
228
+ /**
229
+ * Reset the conversation, keeping tools and configuration intact
230
+ */
231
+ resetConversation(): void;
232
+ }
233
+ //# sourceMappingURL=agent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../../src/core/agent.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EACL,WAAW,EACX,IAAI,EAEJ,OAAO,EACP,UAAU,EACX,MAAM,UAAU,CAAC;AAalB;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,qBAAa,KAAK;IAChB,uCAAuC;IACvC,OAAO,CAAC,IAAI,CAAS;IAErB,sEAAsE;IAC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