@alexnetrebskii/hive-agent 0.5.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 (66) hide show
  1. package/README.md +425 -0
  2. package/dist/agent.d.ts +24 -0
  3. package/dist/agent.d.ts.map +1 -0
  4. package/dist/agent.js +277 -0
  5. package/dist/agent.js.map +1 -0
  6. package/dist/context.d.ts +52 -0
  7. package/dist/context.d.ts.map +1 -0
  8. package/dist/context.js +124 -0
  9. package/dist/context.js.map +1 -0
  10. package/dist/executor.d.ts +29 -0
  11. package/dist/executor.d.ts.map +1 -0
  12. package/dist/executor.js +349 -0
  13. package/dist/executor.js.map +1 -0
  14. package/dist/index.d.ts +16 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +20 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/prompt.d.ts +31 -0
  19. package/dist/prompt.d.ts.map +1 -0
  20. package/dist/prompt.js +84 -0
  21. package/dist/prompt.js.map +1 -0
  22. package/dist/providers/index.d.ts +11 -0
  23. package/dist/providers/index.d.ts.map +1 -0
  24. package/dist/providers/index.js +8 -0
  25. package/dist/providers/index.js.map +1 -0
  26. package/dist/providers/llm/base.d.ts +7 -0
  27. package/dist/providers/llm/base.d.ts.map +1 -0
  28. package/dist/providers/llm/base.js +7 -0
  29. package/dist/providers/llm/base.js.map +1 -0
  30. package/dist/providers/llm/claude.d.ts +31 -0
  31. package/dist/providers/llm/claude.d.ts.map +1 -0
  32. package/dist/providers/llm/claude.js +180 -0
  33. package/dist/providers/llm/claude.js.map +1 -0
  34. package/dist/providers/llm/openai.d.ts +25 -0
  35. package/dist/providers/llm/openai.d.ts.map +1 -0
  36. package/dist/providers/llm/openai.js +171 -0
  37. package/dist/providers/llm/openai.js.map +1 -0
  38. package/dist/providers/logger/base.d.ts +7 -0
  39. package/dist/providers/logger/base.d.ts.map +1 -0
  40. package/dist/providers/logger/base.js +7 -0
  41. package/dist/providers/logger/base.js.map +1 -0
  42. package/dist/providers/logger/console.d.ts +29 -0
  43. package/dist/providers/logger/console.d.ts.map +1 -0
  44. package/dist/providers/logger/console.js +71 -0
  45. package/dist/providers/logger/console.js.map +1 -0
  46. package/dist/providers/repository/base.d.ts +7 -0
  47. package/dist/providers/repository/base.d.ts.map +1 -0
  48. package/dist/providers/repository/base.js +7 -0
  49. package/dist/providers/repository/base.js.map +1 -0
  50. package/dist/providers/repository/memory.d.ts +21 -0
  51. package/dist/providers/repository/memory.d.ts.map +1 -0
  52. package/dist/providers/repository/memory.js +50 -0
  53. package/dist/providers/repository/memory.js.map +1 -0
  54. package/dist/review.d.ts +68 -0
  55. package/dist/review.d.ts.map +1 -0
  56. package/dist/review.js +263 -0
  57. package/dist/review.js.map +1 -0
  58. package/dist/todo.d.ts +73 -0
  59. package/dist/todo.d.ts.map +1 -0
  60. package/dist/todo.js +320 -0
  61. package/dist/todo.js.map +1 -0
  62. package/dist/types.d.ts +257 -0
  63. package/dist/types.d.ts.map +1 -0
  64. package/dist/types.js +5 -0
  65. package/dist/types.js.map +1 -0
  66. package/package.json +43 -0
package/README.md ADDED
@@ -0,0 +1,425 @@
1
+ # Hive Agent
2
+
3
+ Minimal TypeScript agent framework inspired by Claude Code architecture.
4
+
5
+ ## Features
6
+
7
+ - **Stateless design** - Works in Firebase Functions, serverless environments
8
+ - **No built-in tools** - You define your own tools
9
+ - **External history** - Accepts/returns conversation history (for Firestore, etc.)
10
+ - **Sub-agents** - Spawn specialized agents for complex tasks
11
+ - **Multi-provider** - Claude and OpenAI support, easily extensible
12
+ - **Interactive** - Built-in `__ask_user__` tool for clarifying questions
13
+ - **Progress tracking** - Todo lists and real-time progress callbacks
14
+ - **Prompt caching** - Claude prompt caching for cost reduction
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ pnpm add @alexnetrebskii/hive-agent
20
+ ```
21
+
22
+ ## Quick Start
23
+
24
+ ```typescript
25
+ import { Hive, ClaudeProvider } from '@alexnetrebskii/hive-agent'
26
+
27
+ const provider = new ClaudeProvider({
28
+ apiKey: process.env.ANTHROPIC_API_KEY
29
+ })
30
+
31
+ const agent = new Hive({
32
+ systemPrompt: 'You are a helpful assistant.',
33
+ tools: [],
34
+ llm: provider
35
+ })
36
+
37
+ const result = await agent.run('Hello!')
38
+ console.log(result.response)
39
+ ```
40
+
41
+ ## Defining Tools
42
+
43
+ ```typescript
44
+ import type { Tool } from '@alexnetrebskii/hive-agent'
45
+
46
+ const weatherTool: Tool = {
47
+ name: 'get_weather',
48
+ description: 'Get current weather for a city',
49
+ parameters: {
50
+ type: 'object',
51
+ properties: {
52
+ city: { type: 'string', description: 'City name' }
53
+ },
54
+ required: ['city']
55
+ },
56
+ execute: async ({ city }) => {
57
+ const weather = await fetchWeather(city)
58
+ return { success: true, data: weather }
59
+ }
60
+ }
61
+
62
+ const agent = new Hive({
63
+ systemPrompt: 'You help users check weather.',
64
+ tools: [weatherTool],
65
+ llm: provider
66
+ })
67
+ ```
68
+
69
+ ## Sub-Agents
70
+
71
+ Spawn specialized agents for complex tasks:
72
+
73
+ ```typescript
74
+ import type { SubAgentConfig } from '@alexnetrebskii/hive-agent'
75
+
76
+ const researchAgent: SubAgentConfig = {
77
+ name: 'researcher',
78
+ description: 'Research topics in depth using web search',
79
+ systemPrompt: 'You research topics thoroughly and summarize findings.',
80
+ tools: [webSearchTool, readUrlTool]
81
+ }
82
+
83
+ const agent = new Hive({
84
+ systemPrompt: 'You help users with various tasks.',
85
+ tools: [calculatorTool],
86
+ agents: [researchAgent],
87
+ llm: provider
88
+ })
89
+
90
+ // Agent can now use __task__ tool to delegate to researcher
91
+ const result = await agent.run('Research the latest AI developments')
92
+ ```
93
+
94
+ ### Per-Agent Providers
95
+
96
+ Each sub-agent can use different models or providers:
97
+
98
+ ```typescript
99
+ import { ClaudeProvider, OpenAIProvider } from '@alexnetrebskii/hive-agent'
100
+
101
+ const claudeProvider = new ClaudeProvider({ apiKey: '...' })
102
+ const openaiProvider = new OpenAIProvider({ apiKey: '...', model: 'gpt-4o' })
103
+
104
+ const fastAgent: SubAgentConfig = {
105
+ name: 'fast_helper',
106
+ description: 'Quick tasks using GPT-4o',
107
+ systemPrompt: '...',
108
+ tools: [...],
109
+ llm: openaiProvider, // Uses OpenAI instead of parent's Claude
110
+ maxIterations: 5
111
+ }
112
+
113
+ const agent = new Hive({
114
+ systemPrompt: '...',
115
+ tools: [...],
116
+ agents: [fastAgent],
117
+ llm: claudeProvider // Main agent uses Claude
118
+ })
119
+ ```
120
+
121
+ ## Conversation History
122
+
123
+ ### Automatic (with Repository Provider)
124
+
125
+ Pass a `conversationId` and Hive automatically loads/saves history:
126
+
127
+ ```typescript
128
+ import { Hive, ClaudeProvider, MemoryRepository } from '@alexnetrebskii/hive-agent'
129
+
130
+ const agent = new Hive({
131
+ systemPrompt: '...',
132
+ tools: [...],
133
+ llm: new ClaudeProvider({ apiKey: '...' }),
134
+ repository: new MemoryRepository() // Or your custom provider
135
+ })
136
+
137
+ // Hive automatically loads and saves history using conversationId
138
+ const result = await agent.run(userMessage, {
139
+ conversationId: 'user-123-chat-456' // Identity for the conversation
140
+ })
141
+
142
+ // Next message continues the conversation automatically
143
+ const result2 = await agent.run(nextMessage, {
144
+ conversationId: 'user-123-chat-456'
145
+ })
146
+ ```
147
+
148
+ ### Custom Repository Provider
149
+
150
+ Implement `RepositoryProvider` for your database:
151
+
152
+ ```typescript
153
+ import type { RepositoryProvider, Message } from '@alexnetrebskii/hive-agent'
154
+
155
+ class FirestoreRepository implements RepositoryProvider {
156
+ constructor(private db: Firestore) {}
157
+
158
+ async getHistory(conversationId: string): Promise<Message[]> {
159
+ const doc = await this.db.collection('chats').doc(conversationId).get()
160
+ return doc.exists ? doc.data()?.messages || [] : []
161
+ }
162
+
163
+ async saveHistory(conversationId: string, messages: Message[]): Promise<void> {
164
+ await this.db.collection('chats').doc(conversationId).set({ messages })
165
+ }
166
+ }
167
+
168
+ const agent = new Hive({
169
+ systemPrompt: '...',
170
+ tools: [...],
171
+ llm: provider,
172
+ repository: new FirestoreRepository(db)
173
+ })
174
+ ```
175
+
176
+ ### Manual History Management
177
+
178
+ Alternatively, manage history yourself:
179
+
180
+ ```typescript
181
+ // Load history from database
182
+ const history = await db.collection('chats').doc(chatId).get()
183
+
184
+ // Run agent with history
185
+ const result = await agent.run(userMessage, {
186
+ history: history.data()?.messages || []
187
+ })
188
+
189
+ // Save updated history
190
+ await db.collection('chats').doc(chatId).set({
191
+ messages: result.history
192
+ })
193
+ ```
194
+
195
+ ## Interactive Questions
196
+
197
+ Agent can pause to ask clarifying questions:
198
+
199
+ ```typescript
200
+ const result = await agent.run('Create a database schema')
201
+
202
+ if (result.status === 'needs_input') {
203
+ // Show question to user
204
+ console.log(result.pendingQuestion?.question)
205
+ console.log(result.pendingQuestion?.options)
206
+
207
+ // Save state and wait for user response
208
+ // When user responds, run again with the same history
209
+ const answer = await getUserInput()
210
+ const continued = await agent.run(answer, { history: result.history })
211
+ }
212
+ ```
213
+
214
+ ## Interruption & Cancellation
215
+
216
+ Stop a running agent when user clicks "Stop" or sends a new message:
217
+
218
+ ### Using AbortController (in-memory)
219
+
220
+ ```typescript
221
+ const controller = new AbortController()
222
+
223
+ // Start agent
224
+ const resultPromise = agent.run(message, {
225
+ conversationId,
226
+ signal: controller.signal
227
+ })
228
+
229
+ // User clicks "Stop" button
230
+ controller.abort()
231
+
232
+ const result = await resultPromise
233
+ if (result.status === 'interrupted') {
234
+ console.log(`Stopped after ${result.interrupted?.iterationsCompleted} iterations`)
235
+ // result.history contains partial work
236
+ }
237
+ ```
238
+
239
+ ### Using Firestore (for Telegram bots)
240
+
241
+ ```typescript
242
+ // Start task and store reference
243
+ const taskRef = db.collection('tasks').doc(taskId)
244
+ await taskRef.set({ status: 'running', chatId })
245
+
246
+ const result = await agent.run(message, {
247
+ conversationId: chatId,
248
+ shouldContinue: async () => {
249
+ const doc = await taskRef.get()
250
+ return doc.data()?.status === 'running'
251
+ }
252
+ })
253
+
254
+ // Handle result
255
+ if (result.status === 'interrupted') {
256
+ // User stopped or sent new message
257
+ await sendMessage(chatId, 'Task stopped')
258
+ } else {
259
+ await sendMessage(chatId, result.response)
260
+ }
261
+
262
+ // --- In another handler (when user clicks Stop or sends new message) ---
263
+ await taskRef.update({ status: 'stopped' })
264
+ ```
265
+
266
+ ### Continuing Partial Work
267
+
268
+ When interrupted, `result.history` contains the work done so far:
269
+
270
+ ```typescript
271
+ const result = await agent.run(message, { signal })
272
+
273
+ if (result.status === 'interrupted') {
274
+ // Option 1: Discard partial work, start fresh
275
+ const fresh = await agent.run(newMessage, { conversationId })
276
+
277
+ // Option 2: Continue from where we left off
278
+ const continued = await agent.run(newMessage, {
279
+ history: result.history // Include partial work
280
+ })
281
+ }
282
+ ```
283
+
284
+ ## Progress Callbacks
285
+
286
+ Get real-time feedback during execution:
287
+
288
+ ```typescript
289
+ import { ConsoleLogger } from '@alexnetrebskii/hive-agent'
290
+
291
+ const logger = {
292
+ ...new ConsoleLogger({ level: 'info' }),
293
+ onProgress: (update) => {
294
+ // update.type: 'thinking' | 'tool_start' | 'tool_end' | 'sub_agent_start' | 'sub_agent_end'
295
+ console.log(`${update.type}: ${update.message}`)
296
+ }
297
+ }
298
+
299
+ const agent = new Hive({
300
+ systemPrompt: '...',
301
+ tools: [...],
302
+ llm: provider,
303
+ logger
304
+ })
305
+ ```
306
+
307
+ ## Prompt Caching (Claude)
308
+
309
+ Reduce costs with Claude's prompt caching:
310
+
311
+ ```typescript
312
+ const result = await agent.run(message, {
313
+ history,
314
+ cache: {
315
+ enabled: true,
316
+ cacheSystemPrompt: true, // Cache system prompt
317
+ cacheTools: true, // Cache tool definitions
318
+ cacheHistory: true // Cache conversation history
319
+ }
320
+ })
321
+
322
+ // Check cache usage
323
+ console.log(result.usage?.cacheReadInputTokens)
324
+ console.log(result.usage?.cacheCreationInputTokens)
325
+ ```
326
+
327
+ ## Configuration
328
+
329
+ ```typescript
330
+ interface HiveConfig {
331
+ systemPrompt: string
332
+ tools: Tool[]
333
+ agents?: SubAgentConfig[]
334
+
335
+ llm: LLMProvider
336
+ logger?: LogProvider
337
+ repository?: RepositoryProvider
338
+
339
+ maxIterations?: number // Default: 50
340
+ maxContextTokens?: number // Default: 100000
341
+ contextStrategy?: 'truncate_old' | 'summarize' | 'error'
342
+
343
+ thinkingMode?: 'none' | 'enabled'
344
+ thinkingBudget?: number
345
+
346
+ review?: ReviewConfig
347
+ }
348
+ ```
349
+
350
+ ## Providers
351
+
352
+ ### Claude (Anthropic)
353
+
354
+ ```typescript
355
+ import { ClaudeProvider } from '@alexnetrebskii/hive-agent'
356
+
357
+ const provider = new ClaudeProvider({
358
+ apiKey: process.env.ANTHROPIC_API_KEY,
359
+ model: 'claude-sonnet-4-20250514', // Default
360
+ maxTokens: 8192
361
+ })
362
+ ```
363
+
364
+ ### OpenAI
365
+
366
+ ```typescript
367
+ import { OpenAIProvider } from '@alexnetrebskii/hive-agent'
368
+
369
+ const provider = new OpenAIProvider({
370
+ apiKey: process.env.OPENAI_API_KEY,
371
+ model: 'gpt-4o', // Default
372
+ maxTokens: 4096,
373
+ baseURL: 'https://api.openai.com/v1' // Optional, for proxies
374
+ })
375
+ ```
376
+
377
+ ## API Reference
378
+
379
+ ### AgentResult
380
+
381
+ ```typescript
382
+ interface AgentResult {
383
+ response: string // Final text response
384
+ history: Message[] // Full conversation history
385
+ toolCalls: ToolCallLog[] // Log of all tool invocations
386
+ thinking?: string[] // Thinking blocks (if enabled)
387
+ todos?: TodoItem[] // Current todo list
388
+ pendingQuestion?: PendingQuestion // If status is 'needs_input'
389
+ status: 'complete' | 'needs_input'
390
+ usage?: {
391
+ totalInputTokens: number
392
+ totalOutputTokens: number
393
+ cacheCreationInputTokens?: number
394
+ cacheReadInputTokens?: number
395
+ }
396
+ }
397
+ ```
398
+
399
+ ### Tool
400
+
401
+ ```typescript
402
+ interface Tool {
403
+ name: string
404
+ description: string
405
+ parameters: JSONSchema
406
+ execute: (params: Record<string, unknown>, context: ToolContext) => Promise<ToolResult>
407
+ }
408
+
409
+ interface ToolResult {
410
+ success: boolean
411
+ data?: unknown
412
+ error?: string
413
+ }
414
+
415
+ interface ToolContext {
416
+ remainingTokens: number
417
+ conversationId?: string
418
+ userId?: string
419
+ metadata?: Record<string, unknown>
420
+ }
421
+ ```
422
+
423
+ ## License
424
+
425
+ MIT
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Hive Agent
3
+ *
4
+ * Main agent class that orchestrates tool execution, sub-agents, and context management.
5
+ */
6
+ import type { HiveConfig, RunOptions, AgentResult } from './types.js';
7
+ /**
8
+ * Hive Agent Class
9
+ */
10
+ export declare class Hive {
11
+ readonly config: HiveConfig;
12
+ private contextManager;
13
+ private tools;
14
+ constructor(config: HiveConfig);
15
+ /**
16
+ * Get tools including internal tools for a specific run
17
+ */
18
+ private getRunTools;
19
+ /**
20
+ * Run the agent with a user message
21
+ */
22
+ run(message: string, options?: RunOptions): Promise<AgentResult>;
23
+ }
24
+ //# sourceMappingURL=agent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EACV,UAAU,EAGV,UAAU,EACV,WAAW,EAIZ,MAAM,YAAY,CAAA;AA8KnB;;GAEG;AACH,qBAAa,IAAI;IACf,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAA;IAC3B,OAAO,CAAC,cAAc,CAAgB;IACtC,OAAO,CAAC,KAAK,CAAQ;gBAET,MAAM,EAAE,UAAU;IA2B9B;;OAEG;IACH,OAAO,CAAC,WAAW;IAanB;;OAEG;IACG,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,UAAe,GAAG,OAAO,CAAC,WAAW,CAAC;CAsF3E"}