@jackchen_me/open-multi-agent 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 (133) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +280 -0
  3. package/dist/agent/agent.d.ts +121 -0
  4. package/dist/agent/agent.d.ts.map +1 -0
  5. package/dist/agent/agent.js +294 -0
  6. package/dist/agent/agent.js.map +1 -0
  7. package/dist/agent/pool.d.ts +128 -0
  8. package/dist/agent/pool.d.ts.map +1 -0
  9. package/dist/agent/pool.js +236 -0
  10. package/dist/agent/pool.js.map +1 -0
  11. package/dist/agent/runner.d.ts +120 -0
  12. package/dist/agent/runner.d.ts.map +1 -0
  13. package/dist/agent/runner.js +274 -0
  14. package/dist/agent/runner.js.map +1 -0
  15. package/dist/index.d.ts +73 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +87 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/llm/adapter.d.ts +38 -0
  20. package/dist/llm/adapter.d.ts.map +1 -0
  21. package/dist/llm/adapter.js +46 -0
  22. package/dist/llm/adapter.js.map +1 -0
  23. package/dist/llm/anthropic.d.ts +56 -0
  24. package/dist/llm/anthropic.d.ts.map +1 -0
  25. package/dist/llm/anthropic.js +307 -0
  26. package/dist/llm/anthropic.js.map +1 -0
  27. package/dist/llm/openai.d.ts +62 -0
  28. package/dist/llm/openai.d.ts.map +1 -0
  29. package/dist/llm/openai.js +424 -0
  30. package/dist/llm/openai.js.map +1 -0
  31. package/dist/memory/shared.d.ts +86 -0
  32. package/dist/memory/shared.d.ts.map +1 -0
  33. package/dist/memory/shared.js +155 -0
  34. package/dist/memory/shared.js.map +1 -0
  35. package/dist/memory/store.d.ts +64 -0
  36. package/dist/memory/store.d.ts.map +1 -0
  37. package/dist/memory/store.js +103 -0
  38. package/dist/memory/store.js.map +1 -0
  39. package/dist/orchestrator/orchestrator.d.ts +173 -0
  40. package/dist/orchestrator/orchestrator.d.ts.map +1 -0
  41. package/dist/orchestrator/orchestrator.js +698 -0
  42. package/dist/orchestrator/orchestrator.js.map +1 -0
  43. package/dist/orchestrator/scheduler.d.ts +112 -0
  44. package/dist/orchestrator/scheduler.d.ts.map +1 -0
  45. package/dist/orchestrator/scheduler.js +282 -0
  46. package/dist/orchestrator/scheduler.js.map +1 -0
  47. package/dist/task/queue.d.ts +160 -0
  48. package/dist/task/queue.d.ts.map +1 -0
  49. package/dist/task/queue.js +337 -0
  50. package/dist/task/queue.js.map +1 -0
  51. package/dist/task/task.d.ts +86 -0
  52. package/dist/task/task.d.ts.map +1 -0
  53. package/dist/task/task.js +201 -0
  54. package/dist/task/task.js.map +1 -0
  55. package/dist/team/messaging.d.ts +106 -0
  56. package/dist/team/messaging.d.ts.map +1 -0
  57. package/dist/team/messaging.js +182 -0
  58. package/dist/team/messaging.js.map +1 -0
  59. package/dist/team/team.d.ts +141 -0
  60. package/dist/team/team.d.ts.map +1 -0
  61. package/dist/team/team.js +282 -0
  62. package/dist/team/team.js.map +1 -0
  63. package/dist/tool/built-in/bash.d.ts +12 -0
  64. package/dist/tool/built-in/bash.d.ts.map +1 -0
  65. package/dist/tool/built-in/bash.js +133 -0
  66. package/dist/tool/built-in/bash.js.map +1 -0
  67. package/dist/tool/built-in/file-edit.d.ts +14 -0
  68. package/dist/tool/built-in/file-edit.d.ts.map +1 -0
  69. package/dist/tool/built-in/file-edit.js +130 -0
  70. package/dist/tool/built-in/file-edit.js.map +1 -0
  71. package/dist/tool/built-in/file-read.d.ts +12 -0
  72. package/dist/tool/built-in/file-read.d.ts.map +1 -0
  73. package/dist/tool/built-in/file-read.js +82 -0
  74. package/dist/tool/built-in/file-read.js.map +1 -0
  75. package/dist/tool/built-in/file-write.d.ts +11 -0
  76. package/dist/tool/built-in/file-write.d.ts.map +1 -0
  77. package/dist/tool/built-in/file-write.js +70 -0
  78. package/dist/tool/built-in/file-write.js.map +1 -0
  79. package/dist/tool/built-in/grep.d.ts +15 -0
  80. package/dist/tool/built-in/grep.d.ts.map +1 -0
  81. package/dist/tool/built-in/grep.js +287 -0
  82. package/dist/tool/built-in/grep.js.map +1 -0
  83. package/dist/tool/built-in/index.d.ts +36 -0
  84. package/dist/tool/built-in/index.d.ts.map +1 -0
  85. package/dist/tool/built-in/index.js +45 -0
  86. package/dist/tool/built-in/index.js.map +1 -0
  87. package/dist/tool/executor.d.ts +71 -0
  88. package/dist/tool/executor.d.ts.map +1 -0
  89. package/dist/tool/executor.js +116 -0
  90. package/dist/tool/executor.js.map +1 -0
  91. package/dist/tool/framework.d.ts +143 -0
  92. package/dist/tool/framework.d.ts.map +1 -0
  93. package/dist/tool/framework.js +371 -0
  94. package/dist/tool/framework.js.map +1 -0
  95. package/dist/types.d.ts +285 -0
  96. package/dist/types.d.ts.map +1 -0
  97. package/dist/types.js +8 -0
  98. package/dist/types.js.map +1 -0
  99. package/dist/utils/semaphore.d.ts +47 -0
  100. package/dist/utils/semaphore.d.ts.map +1 -0
  101. package/dist/utils/semaphore.js +85 -0
  102. package/dist/utils/semaphore.js.map +1 -0
  103. package/examples/01-single-agent.ts +131 -0
  104. package/examples/02-team-collaboration.ts +167 -0
  105. package/examples/03-task-pipeline.ts +201 -0
  106. package/examples/04-multi-model-team.ts +261 -0
  107. package/package.json +49 -0
  108. package/src/agent/agent.ts +364 -0
  109. package/src/agent/pool.ts +278 -0
  110. package/src/agent/runner.ts +413 -0
  111. package/src/index.ts +166 -0
  112. package/src/llm/adapter.ts +74 -0
  113. package/src/llm/anthropic.ts +388 -0
  114. package/src/llm/openai.ts +522 -0
  115. package/src/memory/shared.ts +181 -0
  116. package/src/memory/store.ts +124 -0
  117. package/src/orchestrator/orchestrator.ts +851 -0
  118. package/src/orchestrator/scheduler.ts +352 -0
  119. package/src/task/queue.ts +394 -0
  120. package/src/task/task.ts +232 -0
  121. package/src/team/messaging.ts +230 -0
  122. package/src/team/team.ts +334 -0
  123. package/src/tool/built-in/bash.ts +187 -0
  124. package/src/tool/built-in/file-edit.ts +154 -0
  125. package/src/tool/built-in/file-read.ts +105 -0
  126. package/src/tool/built-in/file-write.ts +81 -0
  127. package/src/tool/built-in/grep.ts +362 -0
  128. package/src/tool/built-in/index.ts +50 -0
  129. package/src/tool/executor.ts +178 -0
  130. package/src/tool/framework.ts +557 -0
  131. package/src/types.ts +362 -0
  132. package/src/utils/semaphore.ts +89 -0
  133. package/tsconfig.json +25 -0
@@ -0,0 +1,522 @@
1
+ /**
2
+ * @fileoverview OpenAI adapter implementing {@link LLMAdapter}.
3
+ *
4
+ * Converts between the framework's internal {@link ContentBlock} types and the
5
+ * OpenAI Chat Completions wire format. Key mapping decisions:
6
+ *
7
+ * - Framework `tool_use` blocks in assistant messages → OpenAI `tool_calls`
8
+ * - Framework `tool_result` blocks in user messages → OpenAI `tool` role messages
9
+ * - Framework `image` blocks in user messages → OpenAI image content parts
10
+ * - System prompt in {@link LLMChatOptions} → prepended `system` message
11
+ *
12
+ * Because OpenAI and Anthropic use fundamentally different role-based structures
13
+ * for tool calling (Anthropic embeds tool results in user-role content arrays;
14
+ * OpenAI uses a dedicated `tool` role), the conversion necessarily splits
15
+ * `tool_result` blocks out into separate top-level messages.
16
+ *
17
+ * API key resolution order:
18
+ * 1. `apiKey` constructor argument
19
+ * 2. `OPENAI_API_KEY` environment variable
20
+ *
21
+ * @example
22
+ * ```ts
23
+ * import { OpenAIAdapter } from './openai.js'
24
+ *
25
+ * const adapter = new OpenAIAdapter()
26
+ * const response = await adapter.chat(messages, {
27
+ * model: 'gpt-5.4',
28
+ * maxTokens: 1024,
29
+ * })
30
+ * ```
31
+ */
32
+
33
+ import OpenAI from 'openai'
34
+ import type {
35
+ ChatCompletion,
36
+ ChatCompletionAssistantMessageParam,
37
+ ChatCompletionChunk,
38
+ ChatCompletionMessageParam,
39
+ ChatCompletionMessageToolCall,
40
+ ChatCompletionTool,
41
+ ChatCompletionToolMessageParam,
42
+ ChatCompletionUserMessageParam,
43
+ } from 'openai/resources/chat/completions/index.js'
44
+
45
+ import type {
46
+ ContentBlock,
47
+ LLMAdapter,
48
+ LLMChatOptions,
49
+ LLMMessage,
50
+ LLMResponse,
51
+ LLMStreamOptions,
52
+ LLMToolDef,
53
+ StreamEvent,
54
+ TextBlock,
55
+ ToolUseBlock,
56
+ } from '../types.js'
57
+
58
+ // ---------------------------------------------------------------------------
59
+ // Internal helpers — framework → OpenAI
60
+ // ---------------------------------------------------------------------------
61
+
62
+ /**
63
+ * Convert a framework {@link LLMToolDef} to an OpenAI {@link ChatCompletionTool}.
64
+ *
65
+ * OpenAI wraps the function definition inside a `function` key and a `type`
66
+ * discriminant. The `inputSchema` is already a JSON Schema object.
67
+ */
68
+ function toOpenAITool(tool: LLMToolDef): ChatCompletionTool {
69
+ return {
70
+ type: 'function',
71
+ function: {
72
+ name: tool.name,
73
+ description: tool.description,
74
+ parameters: tool.inputSchema as Record<string, unknown>,
75
+ },
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Determine whether a framework message contains any `tool_result` content
81
+ * blocks, which must be serialised as separate OpenAI `tool`-role messages.
82
+ */
83
+ function hasToolResults(msg: LLMMessage): boolean {
84
+ return msg.content.some((b) => b.type === 'tool_result')
85
+ }
86
+
87
+ /**
88
+ * Convert a single framework {@link LLMMessage} into one or more OpenAI
89
+ * {@link ChatCompletionMessageParam} entries.
90
+ *
91
+ * The expansion is necessary because OpenAI represents tool results as
92
+ * top-level messages with role `tool`, whereas in our model they are content
93
+ * blocks inside a `user` message.
94
+ *
95
+ * Expansion rules:
96
+ * - A `user` message containing only text/image blocks → single user message
97
+ * - A `user` message containing `tool_result` blocks → one `tool` message per
98
+ * tool_result block; any remaining text/image blocks are folded into an
99
+ * additional user message prepended to the group
100
+ * - An `assistant` message → single assistant message with optional tool_calls
101
+ */
102
+ function toOpenAIMessages(messages: LLMMessage[]): ChatCompletionMessageParam[] {
103
+ const result: ChatCompletionMessageParam[] = []
104
+
105
+ for (const msg of messages) {
106
+ if (msg.role === 'assistant') {
107
+ result.push(toOpenAIAssistantMessage(msg))
108
+ } else {
109
+ // user role
110
+ if (!hasToolResults(msg)) {
111
+ result.push(toOpenAIUserMessage(msg))
112
+ } else {
113
+ // Split: text/image blocks become a user message (if any exist), then
114
+ // each tool_result block becomes an independent tool message.
115
+ const nonToolBlocks = msg.content.filter((b) => b.type !== 'tool_result')
116
+ if (nonToolBlocks.length > 0) {
117
+ result.push(toOpenAIUserMessage({ role: 'user', content: nonToolBlocks }))
118
+ }
119
+
120
+ for (const block of msg.content) {
121
+ if (block.type === 'tool_result') {
122
+ const toolMsg: ChatCompletionToolMessageParam = {
123
+ role: 'tool',
124
+ tool_call_id: block.tool_use_id,
125
+ content: block.content,
126
+ }
127
+ result.push(toolMsg)
128
+ }
129
+ }
130
+ }
131
+ }
132
+ }
133
+
134
+ return result
135
+ }
136
+
137
+ /**
138
+ * Convert a `user`-role framework message into an OpenAI user message.
139
+ * Image blocks are converted to the OpenAI image_url content part format.
140
+ */
141
+ function toOpenAIUserMessage(msg: LLMMessage): ChatCompletionUserMessageParam {
142
+ // If the entire content is a single text block, use the compact string form
143
+ // to keep the request payload smaller.
144
+ if (msg.content.length === 1 && msg.content[0]?.type === 'text') {
145
+ return { role: 'user', content: msg.content[0].text }
146
+ }
147
+
148
+ type ContentPart = OpenAI.Chat.ChatCompletionContentPartText | OpenAI.Chat.ChatCompletionContentPartImage
149
+ const parts: ContentPart[] = []
150
+
151
+ for (const block of msg.content) {
152
+ if (block.type === 'text') {
153
+ parts.push({ type: 'text', text: block.text })
154
+ } else if (block.type === 'image') {
155
+ parts.push({
156
+ type: 'image_url',
157
+ image_url: {
158
+ url: `data:${block.source.media_type};base64,${block.source.data}`,
159
+ },
160
+ })
161
+ }
162
+ // tool_result blocks are handled by the caller (toOpenAIMessages); skip here.
163
+ }
164
+
165
+ return { role: 'user', content: parts }
166
+ }
167
+
168
+ /**
169
+ * Convert an `assistant`-role framework message into an OpenAI assistant message.
170
+ *
171
+ * Any `tool_use` blocks become `tool_calls`; `text` blocks become the message content.
172
+ */
173
+ function toOpenAIAssistantMessage(msg: LLMMessage): ChatCompletionAssistantMessageParam {
174
+ const toolCalls: ChatCompletionMessageToolCall[] = []
175
+ const textParts: string[] = []
176
+
177
+ for (const block of msg.content) {
178
+ if (block.type === 'tool_use') {
179
+ toolCalls.push({
180
+ id: block.id,
181
+ type: 'function',
182
+ function: {
183
+ name: block.name,
184
+ arguments: JSON.stringify(block.input),
185
+ },
186
+ })
187
+ } else if (block.type === 'text') {
188
+ textParts.push(block.text)
189
+ }
190
+ }
191
+
192
+ const assistantMsg: ChatCompletionAssistantMessageParam = {
193
+ role: 'assistant',
194
+ content: textParts.length > 0 ? textParts.join('') : null,
195
+ }
196
+
197
+ if (toolCalls.length > 0) {
198
+ assistantMsg.tool_calls = toolCalls
199
+ }
200
+
201
+ return assistantMsg
202
+ }
203
+
204
+ // ---------------------------------------------------------------------------
205
+ // Internal helpers — OpenAI → framework
206
+ // ---------------------------------------------------------------------------
207
+
208
+ /**
209
+ * Convert an OpenAI {@link ChatCompletion} into a framework {@link LLMResponse}.
210
+ *
211
+ * We take only the first choice (index 0), consistent with how the framework
212
+ * is designed for single-output agents.
213
+ */
214
+ function fromOpenAICompletion(completion: ChatCompletion): LLMResponse {
215
+ const choice = completion.choices[0]
216
+ if (choice === undefined) {
217
+ throw new Error('OpenAI returned a completion with no choices')
218
+ }
219
+
220
+ const content: ContentBlock[] = []
221
+ const message = choice.message
222
+
223
+ if (message.content !== null && message.content !== undefined) {
224
+ const textBlock: TextBlock = { type: 'text', text: message.content }
225
+ content.push(textBlock)
226
+ }
227
+
228
+ for (const toolCall of message.tool_calls ?? []) {
229
+ let parsedInput: Record<string, unknown> = {}
230
+ try {
231
+ const parsed: unknown = JSON.parse(toolCall.function.arguments)
232
+ if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
233
+ parsedInput = parsed as Record<string, unknown>
234
+ }
235
+ } catch {
236
+ // Malformed arguments from the model — surface as empty object.
237
+ }
238
+
239
+ const toolUseBlock: ToolUseBlock = {
240
+ type: 'tool_use',
241
+ id: toolCall.id,
242
+ name: toolCall.function.name,
243
+ input: parsedInput,
244
+ }
245
+ content.push(toolUseBlock)
246
+ }
247
+
248
+ const stopReason = normalizeFinishReason(choice.finish_reason ?? 'stop')
249
+
250
+ return {
251
+ id: completion.id,
252
+ content,
253
+ model: completion.model,
254
+ stop_reason: stopReason,
255
+ usage: {
256
+ input_tokens: completion.usage?.prompt_tokens ?? 0,
257
+ output_tokens: completion.usage?.completion_tokens ?? 0,
258
+ },
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Normalize an OpenAI `finish_reason` string to the framework's canonical
264
+ * stop-reason vocabulary so consumers never need to branch on provider-specific
265
+ * strings.
266
+ *
267
+ * Mapping:
268
+ * - `'stop'` → `'end_turn'`
269
+ * - `'tool_calls'` → `'tool_use'`
270
+ * - `'length'` → `'max_tokens'`
271
+ * - `'content_filter'` → `'content_filter'`
272
+ * - anything else → passed through unchanged
273
+ */
274
+ function normalizeFinishReason(reason: string): string {
275
+ switch (reason) {
276
+ case 'stop': return 'end_turn'
277
+ case 'tool_calls': return 'tool_use'
278
+ case 'length': return 'max_tokens'
279
+ case 'content_filter': return 'content_filter'
280
+ default: return reason
281
+ }
282
+ }
283
+
284
+ // ---------------------------------------------------------------------------
285
+ // Adapter implementation
286
+ // ---------------------------------------------------------------------------
287
+
288
+ /**
289
+ * LLM adapter backed by the OpenAI Chat Completions API.
290
+ *
291
+ * Thread-safe — a single instance may be shared across concurrent agent runs.
292
+ */
293
+ export class OpenAIAdapter implements LLMAdapter {
294
+ readonly name = 'openai'
295
+
296
+ readonly #client: OpenAI
297
+
298
+ constructor(apiKey?: string) {
299
+ this.#client = new OpenAI({
300
+ apiKey: apiKey ?? process.env['OPENAI_API_KEY'],
301
+ })
302
+ }
303
+
304
+ // -------------------------------------------------------------------------
305
+ // chat()
306
+ // -------------------------------------------------------------------------
307
+
308
+ /**
309
+ * Send a synchronous (non-streaming) chat request and return the complete
310
+ * {@link LLMResponse}.
311
+ *
312
+ * Throws an `OpenAI.APIError` on non-2xx responses. Callers should catch and
313
+ * handle these (e.g. rate limits, context length exceeded).
314
+ */
315
+ async chat(messages: LLMMessage[], options: LLMChatOptions): Promise<LLMResponse> {
316
+ const openAIMessages = buildOpenAIMessageList(messages, options.systemPrompt)
317
+
318
+ const completion = await this.#client.chat.completions.create(
319
+ {
320
+ model: options.model,
321
+ messages: openAIMessages,
322
+ max_tokens: options.maxTokens,
323
+ temperature: options.temperature,
324
+ tools: options.tools ? options.tools.map(toOpenAITool) : undefined,
325
+ stream: false,
326
+ },
327
+ {
328
+ signal: options.abortSignal,
329
+ },
330
+ )
331
+
332
+ return fromOpenAICompletion(completion)
333
+ }
334
+
335
+ // -------------------------------------------------------------------------
336
+ // stream()
337
+ // -------------------------------------------------------------------------
338
+
339
+ /**
340
+ * Send a streaming chat request and yield {@link StreamEvent}s incrementally.
341
+ *
342
+ * Sequence guarantees match {@link AnthropicAdapter.stream}:
343
+ * - Zero or more `text` events
344
+ * - Zero or more `tool_use` events (emitted once per tool call, after
345
+ * arguments have been fully assembled)
346
+ * - Exactly one terminal event: `done` or `error`
347
+ */
348
+ async *stream(
349
+ messages: LLMMessage[],
350
+ options: LLMStreamOptions,
351
+ ): AsyncIterable<StreamEvent> {
352
+ const openAIMessages = buildOpenAIMessageList(messages, options.systemPrompt)
353
+
354
+ // We request usage in the final chunk so we can include it in the `done` event.
355
+ const streamResponse = await this.#client.chat.completions.create(
356
+ {
357
+ model: options.model,
358
+ messages: openAIMessages,
359
+ max_tokens: options.maxTokens,
360
+ temperature: options.temperature,
361
+ tools: options.tools ? options.tools.map(toOpenAITool) : undefined,
362
+ stream: true,
363
+ stream_options: { include_usage: true },
364
+ },
365
+ {
366
+ signal: options.abortSignal,
367
+ },
368
+ )
369
+
370
+ // Accumulate state across chunks.
371
+ let completionId = ''
372
+ let completionModel = ''
373
+ let finalFinishReason: string = 'stop'
374
+ let inputTokens = 0
375
+ let outputTokens = 0
376
+
377
+ // tool_calls are streamed piecemeal; key = tool call index
378
+ const toolCallBuffers = new Map<
379
+ number,
380
+ { id: string; name: string; argsJson: string }
381
+ >()
382
+
383
+ // Full text accumulator for the `done` response.
384
+ let fullText = ''
385
+
386
+ try {
387
+ for await (const chunk of streamResponse) {
388
+ completionId = chunk.id
389
+ completionModel = chunk.model
390
+
391
+ // Usage is only populated in the final chunk when stream_options.include_usage is set.
392
+ if (chunk.usage !== null && chunk.usage !== undefined) {
393
+ inputTokens = chunk.usage.prompt_tokens
394
+ outputTokens = chunk.usage.completion_tokens
395
+ }
396
+
397
+ const choice: ChatCompletionChunk.Choice | undefined = chunk.choices[0]
398
+ if (choice === undefined) continue
399
+
400
+ const delta = choice.delta
401
+
402
+ // --- text delta ---
403
+ if (delta.content !== null && delta.content !== undefined) {
404
+ fullText += delta.content
405
+ const textEvent: StreamEvent = { type: 'text', data: delta.content }
406
+ yield textEvent
407
+ }
408
+
409
+ // --- tool call delta ---
410
+ for (const toolCallDelta of delta.tool_calls ?? []) {
411
+ const idx = toolCallDelta.index
412
+
413
+ if (!toolCallBuffers.has(idx)) {
414
+ toolCallBuffers.set(idx, {
415
+ id: toolCallDelta.id ?? '',
416
+ name: toolCallDelta.function?.name ?? '',
417
+ argsJson: '',
418
+ })
419
+ }
420
+
421
+ const buf = toolCallBuffers.get(idx)
422
+ // buf is guaranteed to exist: we just set it above.
423
+ if (buf !== undefined) {
424
+ if (toolCallDelta.id) buf.id = toolCallDelta.id
425
+ if (toolCallDelta.function?.name) buf.name = toolCallDelta.function.name
426
+ if (toolCallDelta.function?.arguments) {
427
+ buf.argsJson += toolCallDelta.function.arguments
428
+ }
429
+ }
430
+ }
431
+
432
+ if (choice.finish_reason !== null && choice.finish_reason !== undefined) {
433
+ finalFinishReason = choice.finish_reason
434
+ }
435
+ }
436
+
437
+ // Emit accumulated tool_use events after the stream ends.
438
+ const finalToolUseBlocks: ToolUseBlock[] = []
439
+ for (const buf of toolCallBuffers.values()) {
440
+ let parsedInput: Record<string, unknown> = {}
441
+ try {
442
+ const parsed: unknown = JSON.parse(buf.argsJson)
443
+ if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
444
+ parsedInput = parsed as Record<string, unknown>
445
+ }
446
+ } catch {
447
+ // Malformed JSON — surface as empty object.
448
+ }
449
+
450
+ const toolUseBlock: ToolUseBlock = {
451
+ type: 'tool_use',
452
+ id: buf.id,
453
+ name: buf.name,
454
+ input: parsedInput,
455
+ }
456
+ finalToolUseBlocks.push(toolUseBlock)
457
+ const toolUseEvent: StreamEvent = { type: 'tool_use', data: toolUseBlock }
458
+ yield toolUseEvent
459
+ }
460
+
461
+ // Build the complete content array for the done response.
462
+ const doneContent: ContentBlock[] = []
463
+ if (fullText.length > 0) {
464
+ const textBlock: TextBlock = { type: 'text', text: fullText }
465
+ doneContent.push(textBlock)
466
+ }
467
+ doneContent.push(...finalToolUseBlocks)
468
+
469
+ const finalResponse: LLMResponse = {
470
+ id: completionId,
471
+ content: doneContent,
472
+ model: completionModel,
473
+ stop_reason: normalizeFinishReason(finalFinishReason),
474
+ usage: { input_tokens: inputTokens, output_tokens: outputTokens },
475
+ }
476
+
477
+ const doneEvent: StreamEvent = { type: 'done', data: finalResponse }
478
+ yield doneEvent
479
+ } catch (err) {
480
+ const error = err instanceof Error ? err : new Error(String(err))
481
+ const errorEvent: StreamEvent = { type: 'error', data: error }
482
+ yield errorEvent
483
+ }
484
+ }
485
+ }
486
+
487
+ // ---------------------------------------------------------------------------
488
+ // Private utility
489
+ // ---------------------------------------------------------------------------
490
+
491
+ /**
492
+ * Prepend a system message when `systemPrompt` is provided, then append the
493
+ * converted conversation messages.
494
+ *
495
+ * OpenAI represents system instructions as a message with `role: 'system'`
496
+ * at the top of the array, not as a separate API parameter.
497
+ */
498
+ function buildOpenAIMessageList(
499
+ messages: LLMMessage[],
500
+ systemPrompt: string | undefined,
501
+ ): ChatCompletionMessageParam[] {
502
+ const result: ChatCompletionMessageParam[] = []
503
+
504
+ if (systemPrompt !== undefined && systemPrompt.length > 0) {
505
+ result.push({ role: 'system', content: systemPrompt })
506
+ }
507
+
508
+ result.push(...toOpenAIMessages(messages))
509
+ return result
510
+ }
511
+
512
+ // Re-export types that consumers of this module commonly need alongside the adapter.
513
+ export type {
514
+ ContentBlock,
515
+ LLMAdapter,
516
+ LLMChatOptions,
517
+ LLMMessage,
518
+ LLMResponse,
519
+ LLMStreamOptions,
520
+ LLMToolDef,
521
+ StreamEvent,
522
+ }
@@ -0,0 +1,181 @@
1
+ /**
2
+ * @fileoverview Shared memory layer for teams of cooperating agents.
3
+ *
4
+ * Each agent writes under its own namespace (`<agentName>/<key>`) so entries
5
+ * remain attributable, while any agent may read any entry. The
6
+ * {@link SharedMemory.getSummary} method produces a human-readable digest
7
+ * suitable for injecting into an agent's context window.
8
+ */
9
+
10
+ import type { MemoryEntry, MemoryStore } from '../types.js'
11
+ import { InMemoryStore } from './store.js'
12
+
13
+ // ---------------------------------------------------------------------------
14
+ // SharedMemory
15
+ // ---------------------------------------------------------------------------
16
+
17
+ /**
18
+ * Namespaced shared memory for a team of agents.
19
+ *
20
+ * Writes are namespaced as `<agentName>/<key>` so that entries from different
21
+ * agents never collide and are always attributable. Reads are namespace-aware
22
+ * but also accept fully-qualified keys, making cross-agent reads straightforward.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * const mem = new SharedMemory()
27
+ *
28
+ * await mem.write('researcher', 'findings', 'TypeScript 5.5 ships const type params')
29
+ * await mem.write('coder', 'plan', 'Implement feature X using const type params')
30
+ *
31
+ * const entry = await mem.read('researcher/findings')
32
+ * const all = await mem.listByAgent('researcher')
33
+ * const summary = await mem.getSummary()
34
+ * ```
35
+ */
36
+ export class SharedMemory {
37
+ private readonly store: InMemoryStore
38
+
39
+ constructor() {
40
+ this.store = new InMemoryStore()
41
+ }
42
+
43
+ // ---------------------------------------------------------------------------
44
+ // Write
45
+ // ---------------------------------------------------------------------------
46
+
47
+ /**
48
+ * Write `value` under the namespaced key `<agentName>/<key>`.
49
+ *
50
+ * Metadata is merged with a `{ agent: agentName }` marker so consumers can
51
+ * identify provenance when iterating all entries.
52
+ *
53
+ * @param agentName - The writing agent's name (used as a namespace prefix).
54
+ * @param key - Logical key within the agent's namespace.
55
+ * @param value - String value to store (serialise objects before writing).
56
+ * @param metadata - Optional extra metadata stored alongside the entry.
57
+ */
58
+ async write(
59
+ agentName: string,
60
+ key: string,
61
+ value: string,
62
+ metadata?: Record<string, unknown>,
63
+ ): Promise<void> {
64
+ const namespacedKey = SharedMemory.namespaceKey(agentName, key)
65
+ await this.store.set(namespacedKey, value, {
66
+ ...metadata,
67
+ agent: agentName,
68
+ })
69
+ }
70
+
71
+ // ---------------------------------------------------------------------------
72
+ // Read
73
+ // ---------------------------------------------------------------------------
74
+
75
+ /**
76
+ * Read an entry by its fully-qualified key (`<agentName>/<key>`).
77
+ *
78
+ * Returns `null` when the key is absent.
79
+ */
80
+ async read(key: string): Promise<MemoryEntry | null> {
81
+ return this.store.get(key)
82
+ }
83
+
84
+ // ---------------------------------------------------------------------------
85
+ // List
86
+ // ---------------------------------------------------------------------------
87
+
88
+ /** Returns every entry in the shared store, regardless of agent. */
89
+ async listAll(): Promise<MemoryEntry[]> {
90
+ return this.store.list()
91
+ }
92
+
93
+ /**
94
+ * Returns all entries written by `agentName` (i.e. those whose key starts
95
+ * with `<agentName>/`).
96
+ */
97
+ async listByAgent(agentName: string): Promise<MemoryEntry[]> {
98
+ const prefix = SharedMemory.namespaceKey(agentName, '')
99
+ const all = await this.store.list()
100
+ return all.filter((entry) => entry.key.startsWith(prefix))
101
+ }
102
+
103
+ // ---------------------------------------------------------------------------
104
+ // Summary
105
+ // ---------------------------------------------------------------------------
106
+
107
+ /**
108
+ * Produces a human-readable summary of all entries in the store.
109
+ *
110
+ * The output is structured as a markdown-style block, grouped by agent, and
111
+ * is designed to be prepended to an agent's system prompt or injected as a
112
+ * user turn so the agent has context about what its teammates know.
113
+ *
114
+ * Returns an empty string when the store is empty.
115
+ *
116
+ * @example
117
+ * ```
118
+ * ## Shared Team Memory
119
+ *
120
+ * ### researcher
121
+ * - findings: TypeScript 5.5 ships const type params
122
+ *
123
+ * ### coder
124
+ * - plan: Implement feature X using const type params
125
+ * ```
126
+ */
127
+ async getSummary(): Promise<string> {
128
+ const all = await this.store.list()
129
+ if (all.length === 0) return ''
130
+
131
+ // Group entries by agent name.
132
+ const byAgent = new Map<string, Array<{ localKey: string; value: string }>>()
133
+ for (const entry of all) {
134
+ const slashIdx = entry.key.indexOf('/')
135
+ const agent = slashIdx === -1 ? '_unknown' : entry.key.slice(0, slashIdx)
136
+ const localKey = slashIdx === -1 ? entry.key : entry.key.slice(slashIdx + 1)
137
+
138
+ let group = byAgent.get(agent)
139
+ if (!group) {
140
+ group = []
141
+ byAgent.set(agent, group)
142
+ }
143
+ group.push({ localKey, value: entry.value })
144
+ }
145
+
146
+ const lines: string[] = ['## Shared Team Memory', '']
147
+ for (const [agent, entries] of byAgent) {
148
+ lines.push(`### ${agent}`)
149
+ for (const { localKey, value } of entries) {
150
+ // Truncate long values so the summary stays readable in a context window.
151
+ const displayValue =
152
+ value.length > 200 ? `${value.slice(0, 197)}…` : value
153
+ lines.push(`- ${localKey}: ${displayValue}`)
154
+ }
155
+ lines.push('')
156
+ }
157
+
158
+ return lines.join('\n').trimEnd()
159
+ }
160
+
161
+ // ---------------------------------------------------------------------------
162
+ // Store access
163
+ // ---------------------------------------------------------------------------
164
+
165
+ /**
166
+ * Returns the underlying {@link MemoryStore} so callers that only need the
167
+ * raw key-value interface can receive a properly typed reference without
168
+ * accessing private fields via bracket notation.
169
+ */
170
+ getStore(): MemoryStore {
171
+ return this.store
172
+ }
173
+
174
+ // ---------------------------------------------------------------------------
175
+ // Private helpers
176
+ // ---------------------------------------------------------------------------
177
+
178
+ private static namespaceKey(agentName: string, key: string): string {
179
+ return `${agentName}/${key}`
180
+ }
181
+ }