@jackchen_me/open-multi-agent 0.2.0 → 1.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 (117) hide show
  1. package/README.md +87 -20
  2. package/dist/agent/agent.d.ts +15 -1
  3. package/dist/agent/agent.d.ts.map +1 -1
  4. package/dist/agent/agent.js +144 -10
  5. package/dist/agent/agent.js.map +1 -1
  6. package/dist/agent/loop-detector.d.ts +39 -0
  7. package/dist/agent/loop-detector.d.ts.map +1 -0
  8. package/dist/agent/loop-detector.js +122 -0
  9. package/dist/agent/loop-detector.js.map +1 -0
  10. package/dist/agent/pool.d.ts +2 -1
  11. package/dist/agent/pool.d.ts.map +1 -1
  12. package/dist/agent/pool.js +4 -2
  13. package/dist/agent/pool.js.map +1 -1
  14. package/dist/agent/runner.d.ts +23 -1
  15. package/dist/agent/runner.d.ts.map +1 -1
  16. package/dist/agent/runner.js +113 -12
  17. package/dist/agent/runner.js.map +1 -1
  18. package/dist/index.d.ts +3 -1
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +2 -0
  21. package/dist/index.js.map +1 -1
  22. package/dist/llm/adapter.d.ts +4 -1
  23. package/dist/llm/adapter.d.ts.map +1 -1
  24. package/dist/llm/adapter.js +11 -0
  25. package/dist/llm/adapter.js.map +1 -1
  26. package/dist/llm/copilot.d.ts.map +1 -1
  27. package/dist/llm/copilot.js +2 -1
  28. package/dist/llm/copilot.js.map +1 -1
  29. package/dist/llm/gemini.d.ts +65 -0
  30. package/dist/llm/gemini.d.ts.map +1 -0
  31. package/dist/llm/gemini.js +317 -0
  32. package/dist/llm/gemini.js.map +1 -0
  33. package/dist/llm/grok.d.ts +21 -0
  34. package/dist/llm/grok.d.ts.map +1 -0
  35. package/dist/llm/grok.js +24 -0
  36. package/dist/llm/grok.js.map +1 -0
  37. package/dist/llm/openai-common.d.ts +8 -1
  38. package/dist/llm/openai-common.d.ts.map +1 -1
  39. package/dist/llm/openai-common.js +35 -2
  40. package/dist/llm/openai-common.js.map +1 -1
  41. package/dist/llm/openai.d.ts +1 -1
  42. package/dist/llm/openai.d.ts.map +1 -1
  43. package/dist/llm/openai.js +20 -2
  44. package/dist/llm/openai.js.map +1 -1
  45. package/dist/orchestrator/orchestrator.d.ts.map +1 -1
  46. package/dist/orchestrator/orchestrator.js +89 -9
  47. package/dist/orchestrator/orchestrator.js.map +1 -1
  48. package/dist/task/queue.d.ts +31 -2
  49. package/dist/task/queue.d.ts.map +1 -1
  50. package/dist/task/queue.js +69 -2
  51. package/dist/task/queue.js.map +1 -1
  52. package/dist/tool/text-tool-extractor.d.ts +32 -0
  53. package/dist/tool/text-tool-extractor.d.ts.map +1 -0
  54. package/dist/tool/text-tool-extractor.js +187 -0
  55. package/dist/tool/text-tool-extractor.js.map +1 -0
  56. package/dist/types.d.ts +139 -7
  57. package/dist/types.d.ts.map +1 -1
  58. package/dist/utils/trace.d.ts +12 -0
  59. package/dist/utils/trace.d.ts.map +1 -0
  60. package/dist/utils/trace.js +30 -0
  61. package/dist/utils/trace.js.map +1 -0
  62. package/package.json +18 -2
  63. package/.github/ISSUE_TEMPLATE/bug_report.md +0 -40
  64. package/.github/ISSUE_TEMPLATE/feature_request.md +0 -23
  65. package/.github/pull_request_template.md +0 -14
  66. package/.github/workflows/ci.yml +0 -23
  67. package/CLAUDE.md +0 -72
  68. package/CODE_OF_CONDUCT.md +0 -48
  69. package/CONTRIBUTING.md +0 -72
  70. package/DECISIONS.md +0 -43
  71. package/README_zh.md +0 -217
  72. package/SECURITY.md +0 -17
  73. package/examples/01-single-agent.ts +0 -131
  74. package/examples/02-team-collaboration.ts +0 -167
  75. package/examples/03-task-pipeline.ts +0 -201
  76. package/examples/04-multi-model-team.ts +0 -261
  77. package/examples/05-copilot-test.ts +0 -49
  78. package/examples/06-local-model.ts +0 -199
  79. package/examples/07-fan-out-aggregate.ts +0 -209
  80. package/examples/08-gemma4-local.ts +0 -203
  81. package/examples/09-gemma4-auto-orchestration.ts +0 -162
  82. package/src/agent/agent.ts +0 -473
  83. package/src/agent/pool.ts +0 -278
  84. package/src/agent/runner.ts +0 -413
  85. package/src/agent/structured-output.ts +0 -126
  86. package/src/index.ts +0 -167
  87. package/src/llm/adapter.ts +0 -87
  88. package/src/llm/anthropic.ts +0 -389
  89. package/src/llm/copilot.ts +0 -551
  90. package/src/llm/openai-common.ts +0 -255
  91. package/src/llm/openai.ts +0 -272
  92. package/src/memory/shared.ts +0 -181
  93. package/src/memory/store.ts +0 -124
  94. package/src/orchestrator/orchestrator.ts +0 -977
  95. package/src/orchestrator/scheduler.ts +0 -352
  96. package/src/task/queue.ts +0 -394
  97. package/src/task/task.ts +0 -239
  98. package/src/team/messaging.ts +0 -232
  99. package/src/team/team.ts +0 -334
  100. package/src/tool/built-in/bash.ts +0 -187
  101. package/src/tool/built-in/file-edit.ts +0 -154
  102. package/src/tool/built-in/file-read.ts +0 -105
  103. package/src/tool/built-in/file-write.ts +0 -81
  104. package/src/tool/built-in/grep.ts +0 -362
  105. package/src/tool/built-in/index.ts +0 -50
  106. package/src/tool/executor.ts +0 -178
  107. package/src/tool/framework.ts +0 -557
  108. package/src/types.ts +0 -391
  109. package/src/utils/semaphore.ts +0 -89
  110. package/tests/semaphore.test.ts +0 -57
  111. package/tests/shared-memory.test.ts +0 -122
  112. package/tests/structured-output.test.ts +0 -331
  113. package/tests/task-queue.test.ts +0 -244
  114. package/tests/task-retry.test.ts +0 -368
  115. package/tests/task-utils.test.ts +0 -155
  116. package/tests/tool-executor.test.ts +0 -193
  117. package/tsconfig.json +0 -25
package/README.md CHANGED
@@ -1,24 +1,29 @@
1
1
  # Open Multi-Agent
2
2
 
3
- Build AI agent teams that decompose goals into tasks automatically. Define agents with roles and tools, describe a goal — the framework plans the task graph, schedules dependencies, and runs everything in parallel.
3
+ TypeScript framework for multi-agent orchestration. One `runTeam()` call from goal to result — the framework decomposes it into tasks, resolves dependencies, and runs agents in parallel.
4
4
 
5
- 3 runtime dependencies. 27 source files. One `runTeam()` call from goal to result.
5
+ 3 runtime dependencies · 33 source files · Deploys anywhere Node.js runs · Mentioned in [Latent Space](https://www.latent.space/p/ainews-a-quiet-april-fools) AI News
6
6
 
7
7
  [![GitHub stars](https://img.shields.io/github/stars/JackChen-me/open-multi-agent)](https://github.com/JackChen-me/open-multi-agent/stargazers)
8
8
  [![license](https://img.shields.io/github/license/JackChen-me/open-multi-agent)](./LICENSE)
9
9
  [![TypeScript](https://img.shields.io/badge/TypeScript-5.6-blue)](https://www.typescriptlang.org/)
10
+ [![coverage](https://img.shields.io/badge/coverage-71%25-brightgreen)](https://github.com/JackChen-me/open-multi-agent/actions)
10
11
 
11
12
  **English** | [中文](./README_zh.md)
12
13
 
13
14
  ## Why Open Multi-Agent?
14
15
 
15
- - **Auto Task Decomposition** — Describe a goal in plain text. A built-in coordinator agent breaks it into a task DAG with dependencies and assignees no manual orchestration needed.
16
- - **Multi-Agent Teams** — Define agents with different roles, tools, and even different models. They collaborate through a message bus and shared memory.
17
- - **Task DAG Scheduling** — Tasks have dependencies. The framework resolves them topologically dependent tasks wait, independent tasks run in parallel.
18
- - **Model Agnostic** — Claude, GPT, Gemma 4, and local models (Ollama, vLLM, LM Studio) in the same team. Swap models per agent via `baseURL`.
16
+ - **Goal In, Result Out** — `runTeam(team, "Build a REST API")`. A coordinator agent auto-decomposes the goal into a task DAG with dependencies and assignees, runs independent tasks in parallel, and synthesizes the final output. No manual task definitions or graph wiring required.
17
+ - **TypeScript-Native** — Built for the Node.js ecosystem. `npm install`, import, run. No Python runtime, no subprocess bridge, no sidecar services. Embed in Express, Next.js, serverless functions, or CI/CD pipelines.
18
+ - **Auditable and Lightweight** — 3 runtime dependencies (`@anthropic-ai/sdk`, `openai`, `zod`). 33 source files. The entire codebase is readable in an afternoon.
19
+ - **Model Agnostic** — Claude, GPT, Gemma 4, and local models (Ollama, vLLM, LM Studio, llama.cpp server) in the same team. Swap models per agent via `baseURL`.
20
+ - **Multi-Agent Collaboration** — Agents with different roles, tools, and models collaborate through a message bus and shared memory.
19
21
  - **Structured Output** — Add `outputSchema` (Zod) to any agent. Output is parsed as JSON, validated, and auto-retried once on failure. Access typed results via `result.structured`.
20
22
  - **Task Retry** — Set `maxRetries` on tasks for automatic retry with exponential backoff. Failed attempts accumulate token usage for accurate billing.
21
- - **In-Process Execution** — No subprocess overhead. Everything runs in one Node.js process. Deploy to serverless, Docker, CI/CD.
23
+ - **Human-in-the-Loop** — Optional `onApproval` callback on `runTasks()`. After each batch of tasks completes, your callback decides whether to proceed or abort remaining work.
24
+ - **Lifecycle Hooks** — `beforeRun` / `afterRun` on `AgentConfig`. Intercept the prompt before execution or post-process results after. Throw from either hook to abort.
25
+ - **Loop Detection** — `loopDetection` on `AgentConfig` catches stuck agents repeating the same tool calls or text output. Configurable action: warn (default), terminate, or custom callback.
26
+ - **Observability** — Optional `onTrace` callback emits structured spans for every LLM call, tool execution, task, and agent run — with timing, token usage, and a shared `runId` for correlation. Zero overhead when not subscribed, zero extra dependencies.
22
27
 
23
28
  ## Quick Start
24
29
 
@@ -28,7 +33,12 @@ Requires Node.js >= 18.
28
33
  npm install @jackchen_me/open-multi-agent
29
34
  ```
30
35
 
31
- Set `ANTHROPIC_API_KEY` (and optionally `OPENAI_API_KEY` or `GITHUB_TOKEN` for Copilot) in your environment. Local models via Ollama require no API key — see [example 06](examples/06-local-model.ts).
36
+ Set the API key for your provider. Local models via Ollama require no API key — see [example 06](examples/06-local-model.ts).
37
+
38
+ - `ANTHROPIC_API_KEY`
39
+ - `OPENAI_API_KEY`
40
+ - `GEMINI_API_KEY`
41
+ - `GITHUB_TOKEN` (for Copilot)
32
42
 
33
43
  Three agents, one goal — the framework handles the rest:
34
44
 
@@ -100,12 +110,6 @@ Tokens: 12847 output tokens
100
110
  | Auto-orchestrated team | `runTeam()` | Give a goal, framework plans and executes |
101
111
  | Explicit pipeline | `runTasks()` | You define the task graph and assignments |
102
112
 
103
- ## Contributors
104
-
105
- <a href="https://github.com/JackChen-me/open-multi-agent/graphs/contributors">
106
- <img src="https://contrib.rocks/image?repo=JackChen-me/open-multi-agent" />
107
- </a>
108
-
109
113
  ## Examples
110
114
 
111
115
  All examples are runnable scripts in [`examples/`](./examples/). Run any of them with `npx tsx`:
@@ -123,8 +127,12 @@ npx tsx examples/01-single-agent.ts
123
127
  | [05 — Copilot](examples/05-copilot-test.ts) | GitHub Copilot as an LLM provider |
124
128
  | [06 — Local Model](examples/06-local-model.ts) | Ollama + Claude in one pipeline via `baseURL` (works with vLLM, LM Studio, etc.) |
125
129
  | [07 — Fan-Out / Aggregate](examples/07-fan-out-aggregate.ts) | `runParallel()` MapReduce — 3 analysts in parallel, then synthesize |
126
- | [08 — Gemma 4 Local](examples/08-gemma4-local.ts) | Pure-local Gemma 4 agent team with tool-calling — zero API cost |
127
- | [09 — Gemma 4 Auto-Orchestration](examples/09-gemma4-auto-orchestration.ts) | `runTeam()` with Gemma 4 as coordinator auto task decomposition, fully local |
130
+ | [08 — Gemma 4 Local](examples/08-gemma4-local.ts) | `runTasks()` + `runTeam()` with local Gemma 4 via Ollama — zero API cost |
131
+ | [09 — Structured Output](examples/09-structured-output.ts) | `outputSchema` (Zod) on AgentConfigvalidated JSON via `result.structured` |
132
+ | [10 — Task Retry](examples/10-task-retry.ts) | `maxRetries` / `retryDelayMs` / `retryBackoff` with `task_retry` progress events |
133
+ | [11 — Trace Observability](examples/11-trace-observability.ts) | `onTrace` callback — structured spans for LLM calls, tools, tasks, and agents |
134
+ | [12 — Grok](examples/12-grok.ts) | Same as example 02 (`runTeam()` collaboration) with Grok (`XAI_API_KEY`) |
135
+ | [13 — Gemini](examples/13-gemini.ts) | Gemini adapter smoke test with `gemini-2.5-flash` (`GEMINI_API_KEY`) |
128
136
 
129
137
  ## Architecture
130
138
 
@@ -158,6 +166,8 @@ npx tsx examples/01-single-agent.ts
158
166
  │ - stream() │ │ - AnthropicAdapter │
159
167
  └────────┬──────────┘ │ - OpenAIAdapter │
160
168
  │ │ - CopilotAdapter │
169
+ │ │ - GeminiAdapter │
170
+ │ │ - GrokAdapter │
161
171
  │ └──────────────────────┘
162
172
  ┌────────▼──────────┐
163
173
  │ AgentRunner │ ┌──────────────────────┐
@@ -183,12 +193,55 @@ npx tsx examples/01-single-agent.ts
183
193
  |----------|--------|---------|--------|
184
194
  | Anthropic (Claude) | `provider: 'anthropic'` | `ANTHROPIC_API_KEY` | Verified |
185
195
  | OpenAI (GPT) | `provider: 'openai'` | `OPENAI_API_KEY` | Verified |
196
+ | Grok (xAI) | `provider: 'grok'` | `XAI_API_KEY` | Verified |
186
197
  | GitHub Copilot | `provider: 'copilot'` | `GITHUB_TOKEN` | Verified |
198
+ | Gemini | `provider: 'gemini'` | `GEMINI_API_KEY` | Verified |
187
199
  | Ollama / vLLM / LM Studio | `provider: 'openai'` + `baseURL` | — | Verified |
200
+ | llama.cpp server | `provider: 'openai'` + `baseURL` | — | Verified |
188
201
 
189
202
  Verified local models with tool-calling: **Gemma 4** (see [example 08](examples/08-gemma4-local.ts)).
190
203
 
191
- Any OpenAI-compatible API should work via `provider: 'openai'` + `baseURL` (DeepSeek, Groq, Mistral, Qwen, MiniMax, etc.). These providers have not been fully verified yet — contributions welcome via [#25](https://github.com/JackChen-me/open-multi-agent/issues/25).
204
+ Any OpenAI-compatible API should work via `provider: 'openai'` + `baseURL` (DeepSeek, Groq, Mistral, Qwen, MiniMax, etc.). **Grok now has first-class support** via `provider: 'grok'`.
205
+
206
+ ### Local Model Tool-Calling
207
+
208
+ The framework supports tool-calling with local models served by Ollama, vLLM, LM Studio, or llama.cpp. Tool-calling is handled natively by these servers via the OpenAI-compatible API.
209
+
210
+ **Verified models:** Gemma 4, Llama 3.1, Qwen 3, Mistral, Phi-4. See the full list at [ollama.com/search?c=tools](https://ollama.com/search?c=tools).
211
+
212
+ **Fallback extraction:** If a local model returns tool calls as text instead of using the `tool_calls` wire format (common with thinking models or misconfigured servers), the framework automatically extracts them from the text output.
213
+
214
+ **Timeout:** Local inference can be slow. Use `timeoutMs` on `AgentConfig` to prevent indefinite hangs:
215
+
216
+ ```typescript
217
+ const localAgent: AgentConfig = {
218
+ name: 'local',
219
+ model: 'llama3.1',
220
+ provider: 'openai',
221
+ baseURL: 'http://localhost:11434/v1',
222
+ apiKey: 'ollama',
223
+ tools: ['bash', 'file_read'],
224
+ timeoutMs: 120_000, // abort after 2 minutes
225
+ }
226
+ ```
227
+
228
+ **Troubleshooting:**
229
+ - Model not calling tools? Ensure it appears in Ollama's [Tools category](https://ollama.com/search?c=tools). Not all models support tool-calling.
230
+ - Using Ollama? Update to the latest version (`ollama update`) — older versions have known tool-calling bugs.
231
+ - Proxy interfering? Use `no_proxy=localhost` when running against local servers.
232
+
233
+ ### LLM Configuration Examples
234
+
235
+ ```typescript
236
+ const grokAgent: AgentConfig = {
237
+ name: 'grok-agent',
238
+ provider: 'grok',
239
+ model: 'grok-4',
240
+ systemPrompt: 'You are a helpful assistant.',
241
+ }
242
+ ```
243
+
244
+ (Set your `XAI_API_KEY` environment variable — no `baseURL` needed anymore.)
192
245
 
193
246
  ## Contributing
194
247
 
@@ -198,16 +251,30 @@ Issues, feature requests, and PRs are welcome. Some areas where contributions wo
198
251
  - **Examples** — Real-world workflows and use cases.
199
252
  - **Documentation** — Guides, tutorials, and API docs.
200
253
 
254
+ ## Author
255
+
256
+ > JackChen — Ex PM (¥100M+ revenue), now indie builder. Follow on [X](https://x.com/JackChen_x) for AI Agent insights.
257
+
258
+ ## Contributors
259
+
260
+ <a href="https://github.com/JackChen-me/open-multi-agent/graphs/contributors">
261
+ <img src="https://contrib.rocks/image?repo=JackChen-me/open-multi-agent&v=20260405" />
262
+ </a>
263
+
201
264
  ## Star History
202
265
 
203
266
  <a href="https://star-history.com/#JackChen-me/open-multi-agent&Date">
204
267
  <picture>
205
- <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=JackChen-me/open-multi-agent&type=Date&theme=dark&v=20260403" />
206
- <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=JackChen-me/open-multi-agent&type=Date&v=20260403" />
207
- <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=JackChen-me/open-multi-agent&type=Date&v=20260403" />
268
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=JackChen-me/open-multi-agent&type=Date&theme=dark&v=20260405" />
269
+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=JackChen-me/open-multi-agent&type=Date&v=20260405" />
270
+ <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=JackChen-me/open-multi-agent&type=Date&v=20260405" />
208
271
  </picture>
209
272
  </a>
210
273
 
274
+ ## Translations
275
+
276
+ Help translate this README — [open a PR](https://github.com/JackChen-me/open-multi-agent/pulls).
277
+
211
278
  ## License
212
279
 
213
280
  MIT
@@ -25,6 +25,7 @@
25
25
  import type { AgentConfig, AgentState, AgentRunResult, LLMMessage, StreamEvent, ToolUseContext } from '../types.js';
26
26
  import type { ToolDefinition as FrameworkToolDefinition, ToolRegistry } from '../tool/framework.js';
27
27
  import type { ToolExecutor } from '../tool/executor.js';
28
+ import { type RunOptions } from './runner.js';
28
29
  /**
29
30
  * High-level wrapper around {@link AgentRunner} that manages conversation
30
31
  * history, state transitions, and tool lifecycle.
@@ -61,7 +62,7 @@ export declare class Agent {
61
62
  *
62
63
  * Use this for one-shot queries where past context is irrelevant.
63
64
  */
64
- run(prompt: string): Promise<AgentRunResult>;
65
+ run(prompt: string, runOptions?: Partial<RunOptions>): Promise<AgentRunResult>;
65
66
  /**
66
67
  * Run `prompt` as part of the ongoing conversation.
67
68
  *
@@ -104,6 +105,8 @@ export declare class Agent {
104
105
  * Handles state transitions and error wrapping.
105
106
  */
106
107
  private executeRun;
108
+ /** Emit an `agent` trace event if `onTrace` is provided. */
109
+ private emitAgentTrace;
107
110
  /**
108
111
  * Validate agent output against the configured `outputSchema`.
109
112
  * On first validation failure, retry once with error feedback.
@@ -114,6 +117,17 @@ export declare class Agent {
114
117
  * Handles state transitions and error wrapping.
115
118
  */
116
119
  private executeStream;
120
+ /** Extract the prompt text from the last user message to build hook context. */
121
+ private buildBeforeRunHookContext;
122
+ /**
123
+ * Apply a (possibly modified) hook context back to the messages array.
124
+ *
125
+ * Only text blocks in the last user message are replaced; non-text content
126
+ * (images, tool results) is preserved. The array element is replaced (not
127
+ * mutated in place) so that shallow copies of the original array (e.g. from
128
+ * `prompt()`) are not affected.
129
+ */
130
+ private applyHookContext;
117
131
  private transitionTo;
118
132
  private transitionToError;
119
133
  private toAgentRunResult;
@@ -1 +1 @@
1
- {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../../src/agent/agent.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,KAAK,EACV,WAAW,EACX,UAAU,EACV,cAAc,EACd,UAAU,EACV,WAAW,EAEX,cAAc,EACf,MAAM,aAAa,CAAA;AACpB,OAAO,KAAK,EAAE,cAAc,IAAI,uBAAuB,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAA;AACnG,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AA0BvD;;;GAGG;AACH,qBAAa,KAAK;IAChB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAA;IAE5B,OAAO,CAAC,MAAM,CAA2B;IACzC,OAAO,CAAC,KAAK,CAAY;IACzB,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAc;IAC5C,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAc;IAC5C,OAAO,CAAC,cAAc,CAAmB;IAEzC;;;;;;;OAOG;gBAED,MAAM,EAAE,WAAW,EACnB,YAAY,EAAE,YAAY,EAC1B,YAAY,EAAE,YAAY;IAkB5B;;;;;OAKG;YACW,SAAS;IA0CvB;;;;;;;OAOG;IACG,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC;IAQlD;;;;;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AGG;IACH,gBAAgB,CAAC,WAAW,CAAC,EAAE,WAAW,GAAG,cAAc;CAU5D"}
@@ -22,6 +22,7 @@
22
22
  * console.log(result.output)
23
23
  * ```
24
24
  */
25
+ import { emitTrace, generateRunId } from '../utils/trace.js';
25
26
  import { createAdapter } from '../llm/adapter.js';
26
27
  import { AgentRunner } from './runner.js';
27
28
  import { buildStructuredOutputInstruction, extractJSON, validateOutput, } from './structured-output.js';
@@ -29,6 +30,21 @@ import { buildStructuredOutputInstruction, extractJSON, validateOutput, } from '
29
30
  // Internal helpers
30
31
  // ---------------------------------------------------------------------------
31
32
  const ZERO_USAGE = { input_tokens: 0, output_tokens: 0 };
33
+ /**
34
+ * Combine two {@link AbortSignal}s so that aborting either one cancels the
35
+ * returned signal. Works on Node 18+ (no `AbortSignal.any` required).
36
+ */
37
+ function mergeAbortSignals(a, b) {
38
+ const controller = new AbortController();
39
+ if (a.aborted || b.aborted) {
40
+ controller.abort();
41
+ return controller.signal;
42
+ }
43
+ const abort = () => controller.abort();
44
+ a.addEventListener('abort', abort, { once: true });
45
+ b.addEventListener('abort', abort, { once: true });
46
+ return controller.signal;
47
+ }
32
48
  function addUsage(a, b) {
33
49
  return {
34
50
  input_tokens: a.input_tokens + b.input_tokens,
@@ -101,6 +117,7 @@ export class Agent {
101
117
  allowedTools: this.config.tools,
102
118
  agentName: this.name,
103
119
  agentRole: this.config.systemPrompt?.slice(0, 50) ?? 'assistant',
120
+ loopDetection: this.config.loopDetection,
104
121
  };
105
122
  this.runner = new AgentRunner(adapter, this._toolRegistry, this._toolExecutor, runnerOptions);
106
123
  return this.runner;
@@ -116,11 +133,11 @@ export class Agent {
116
133
  *
117
134
  * Use this for one-shot queries where past context is irrelevant.
118
135
  */
119
- async run(prompt) {
136
+ async run(prompt, runOptions) {
120
137
  const messages = [
121
138
  { role: 'user', content: [{ type: 'text', text: prompt }] },
122
139
  ];
123
- return this.executeRun(messages);
140
+ return this.executeRun(messages, runOptions);
124
141
  }
125
142
  /**
126
143
  * Run `prompt` as part of the ongoing conversation.
@@ -130,6 +147,7 @@ export class Agent {
130
147
  *
131
148
  * Use this for multi-turn interactions.
132
149
  */
150
+ // TODO(#18): accept optional RunOptions to forward trace context
133
151
  async prompt(message) {
134
152
  const userMessage = {
135
153
  role: 'user',
@@ -148,6 +166,7 @@ export class Agent {
148
166
  *
149
167
  * Like {@link run}, this does not use or update the persistent history.
150
168
  */
169
+ // TODO(#18): accept optional RunOptions to forward trace context
151
170
  async *stream(prompt) {
152
171
  const messages = [
153
172
  { role: 'user', content: [{ type: 'text', text: prompt }] },
@@ -206,28 +225,65 @@ export class Agent {
206
225
  * Shared execution path used by both `run` and `prompt`.
207
226
  * Handles state transitions and error wrapping.
208
227
  */
209
- async executeRun(messages) {
228
+ async executeRun(messages, callerOptions) {
210
229
  this.transitionTo('running');
230
+ const agentStartMs = Date.now();
211
231
  try {
232
+ // --- beforeRun hook ---
233
+ if (this.config.beforeRun) {
234
+ const hookCtx = this.buildBeforeRunHookContext(messages);
235
+ const modified = await this.config.beforeRun(hookCtx);
236
+ this.applyHookContext(messages, modified, hookCtx.prompt);
237
+ }
212
238
  const runner = await this.getRunner();
239
+ const internalOnMessage = (msg) => {
240
+ this.state.messages.push(msg);
241
+ callerOptions?.onMessage?.(msg);
242
+ };
243
+ // Auto-generate runId when onTrace is provided but runId is missing
244
+ const needsRunId = callerOptions?.onTrace && !callerOptions.runId;
245
+ // Create a fresh timeout signal per run (not per runner) so that
246
+ // each run() / prompt() call gets its own timeout window.
247
+ const timeoutSignal = this.config.timeoutMs !== undefined && this.config.timeoutMs > 0
248
+ ? AbortSignal.timeout(this.config.timeoutMs)
249
+ : undefined;
250
+ // Merge caller-provided abortSignal with the timeout signal so that
251
+ // either cancellation source is respected.
252
+ const callerAbort = callerOptions?.abortSignal;
253
+ const effectiveAbort = timeoutSignal && callerAbort
254
+ ? mergeAbortSignals(timeoutSignal, callerAbort)
255
+ : timeoutSignal ?? callerAbort;
213
256
  const runOptions = {
214
- onMessage: msg => {
215
- this.state.messages.push(msg);
216
- },
257
+ ...callerOptions,
258
+ onMessage: internalOnMessage,
259
+ ...(needsRunId ? { runId: generateRunId() } : undefined),
260
+ ...(effectiveAbort ? { abortSignal: effectiveAbort } : undefined),
217
261
  };
218
262
  const result = await runner.run(messages, runOptions);
219
263
  this.state.tokenUsage = addUsage(this.state.tokenUsage, result.tokenUsage);
220
264
  // --- Structured output validation ---
221
265
  if (this.config.outputSchema) {
222
- return this.validateStructuredOutput(messages, result, runner, runOptions);
266
+ let validated = await this.validateStructuredOutput(messages, result, runner, runOptions);
267
+ // --- afterRun hook ---
268
+ if (this.config.afterRun) {
269
+ validated = await this.config.afterRun(validated);
270
+ }
271
+ this.emitAgentTrace(callerOptions, agentStartMs, validated);
272
+ return validated;
273
+ }
274
+ let agentResult = this.toAgentRunResult(result, true);
275
+ // --- afterRun hook ---
276
+ if (this.config.afterRun) {
277
+ agentResult = await this.config.afterRun(agentResult);
223
278
  }
224
279
  this.transitionTo('completed');
225
- return this.toAgentRunResult(result, true);
280
+ this.emitAgentTrace(callerOptions, agentStartMs, agentResult);
281
+ return agentResult;
226
282
  }
227
283
  catch (err) {
228
284
  const error = err instanceof Error ? err : new Error(String(err));
229
285
  this.transitionToError(error);
230
- return {
286
+ const errorResult = {
231
287
  success: false,
232
288
  output: error.message,
233
289
  messages: [],
@@ -235,8 +291,28 @@ export class Agent {
235
291
  toolCalls: [],
236
292
  structured: undefined,
237
293
  };
294
+ this.emitAgentTrace(callerOptions, agentStartMs, errorResult);
295
+ return errorResult;
238
296
  }
239
297
  }
298
+ /** Emit an `agent` trace event if `onTrace` is provided. */
299
+ emitAgentTrace(options, startMs, result) {
300
+ if (!options?.onTrace)
301
+ return;
302
+ const endMs = Date.now();
303
+ emitTrace(options.onTrace, {
304
+ type: 'agent',
305
+ runId: options.runId ?? '',
306
+ taskId: options.taskId,
307
+ agent: options.traceAgent ?? this.name,
308
+ turns: result.messages.filter(m => m.role === 'assistant').length,
309
+ tokens: result.tokenUsage,
310
+ toolCalls: result.toolCalls.length,
311
+ startMs,
312
+ endMs,
313
+ durationMs: endMs - startMs,
314
+ });
315
+ }
240
316
  /**
241
317
  * Validate agent output against the configured `outputSchema`.
242
318
  * On first validation failure, retry once with error feedback.
@@ -316,12 +392,28 @@ export class Agent {
316
392
  async *executeStream(messages) {
317
393
  this.transitionTo('running');
318
394
  try {
395
+ // --- beforeRun hook ---
396
+ if (this.config.beforeRun) {
397
+ const hookCtx = this.buildBeforeRunHookContext(messages);
398
+ const modified = await this.config.beforeRun(hookCtx);
399
+ this.applyHookContext(messages, modified, hookCtx.prompt);
400
+ }
319
401
  const runner = await this.getRunner();
320
- for await (const event of runner.stream(messages)) {
402
+ // Fresh timeout per stream call, same as executeRun.
403
+ const timeoutSignal = this.config.timeoutMs !== undefined && this.config.timeoutMs > 0
404
+ ? AbortSignal.timeout(this.config.timeoutMs)
405
+ : undefined;
406
+ for await (const event of runner.stream(messages, timeoutSignal ? { abortSignal: timeoutSignal } : {})) {
321
407
  if (event.type === 'done') {
322
408
  const result = event.data;
323
409
  this.state.tokenUsage = addUsage(this.state.tokenUsage, result.tokenUsage);
410
+ let agentResult = this.toAgentRunResult(result, true);
411
+ if (this.config.afterRun) {
412
+ agentResult = await this.config.afterRun(agentResult);
413
+ }
324
414
  this.transitionTo('completed');
415
+ yield { type: 'done', data: agentResult };
416
+ continue;
325
417
  }
326
418
  else if (event.type === 'error') {
327
419
  const error = event.data instanceof Error
@@ -339,6 +431,47 @@ export class Agent {
339
431
  }
340
432
  }
341
433
  // -------------------------------------------------------------------------
434
+ // Hook helpers
435
+ // -------------------------------------------------------------------------
436
+ /** Extract the prompt text from the last user message to build hook context. */
437
+ buildBeforeRunHookContext(messages) {
438
+ let prompt = '';
439
+ for (let i = messages.length - 1; i >= 0; i--) {
440
+ if (messages[i].role === 'user') {
441
+ prompt = messages[i].content
442
+ .filter((b) => b.type === 'text')
443
+ .map(b => b.text)
444
+ .join('');
445
+ break;
446
+ }
447
+ }
448
+ // Strip hook functions to avoid circular self-references in the context
449
+ const { beforeRun, afterRun, ...agentInfo } = this.config;
450
+ return { prompt, agent: agentInfo };
451
+ }
452
+ /**
453
+ * Apply a (possibly modified) hook context back to the messages array.
454
+ *
455
+ * Only text blocks in the last user message are replaced; non-text content
456
+ * (images, tool results) is preserved. The array element is replaced (not
457
+ * mutated in place) so that shallow copies of the original array (e.g. from
458
+ * `prompt()`) are not affected.
459
+ */
460
+ applyHookContext(messages, ctx, originalPrompt) {
461
+ if (ctx.prompt === originalPrompt)
462
+ return;
463
+ for (let i = messages.length - 1; i >= 0; i--) {
464
+ if (messages[i].role === 'user') {
465
+ const nonTextBlocks = messages[i].content.filter(b => b.type !== 'text');
466
+ messages[i] = {
467
+ role: 'user',
468
+ content: [{ type: 'text', text: ctx.prompt }, ...nonTextBlocks],
469
+ };
470
+ break;
471
+ }
472
+ }
473
+ }
474
+ // -------------------------------------------------------------------------
342
475
  // State transition helpers
343
476
  // -------------------------------------------------------------------------
344
477
  transitionTo(status) {
@@ -358,6 +491,7 @@ export class Agent {
358
491
  tokenUsage: result.tokenUsage,
359
492
  toolCalls: result.toolCalls,
360
493
  structured,
494
+ ...(result.loopDetected ? { loopDetected: true } : {}),
361
495
  };
362
496
  }
363
497
  // -------------------------------------------------------------------------
@@ -1 +1 @@
1
- {"version":3,"file":"agent.js","sourceRoot":"","sources":["../../src/agent/agent.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAaH,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AACjD,OAAO,EAAE,WAAW,EAAuD,MAAM,aAAa,CAAA;AAC9F,OAAO,EACL,gCAAgC,EAChC,WAAW,EACX,cAAc,GACf,MAAM,wBAAwB,CAAA;AAE/B,8EAA8E;AAC9E,mBAAmB;AACnB,8EAA8E;AAE9E,MAAM,UAAU,GAAe,EAAE,YAAY,EAAE,CAAC,EAAE,aAAa,EAAE,CAAC,EAAE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;YACL,OAAO;YACP,MAAM,EAAE,MAAM,CAAC,MAAM;YACrB,QAAQ,EAAE,MAAM,CAAC,QAAQ;YACzB,UAAU,EAAE,MAAM,CAAC,UAAU;YAC7B,SAAS,EAAE,MAAM,CAAC,SAAS;YAC3B,UAAU;YACV,GAAG,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACvD,CAAA;IACH,CAAC;IAED,4EAA4E;IAC5E,4EAA4E;IAC5E,4EAA4E;IAE5E;;;OAGG;IACH,gBAAgB,CAAC,WAAyB;QACxC,OAAO;YACL,KAAK,EAAE;gBACL,IAAI,EAAE,IAAI,CAAC,IAAI;gBACf,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,WAAW;gBAC3D,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK;aACzB;YACD,WAAW;SACZ,CAAA;IACH,CAAC;CACF"}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * @fileoverview Sliding-window loop detector for the agent conversation loop.
3
+ *
4
+ * Tracks tool-call signatures and text outputs across turns to detect when an
5
+ * agent is stuck repeating the same actions. Used by {@link AgentRunner} when
6
+ * {@link LoopDetectionConfig} is provided.
7
+ */
8
+ import type { LoopDetectionConfig, LoopDetectionInfo } from '../types.js';
9
+ export declare class LoopDetector {
10
+ private readonly maxRepeats;
11
+ private readonly windowSize;
12
+ private readonly toolSignatures;
13
+ private readonly textOutputs;
14
+ constructor(config?: LoopDetectionConfig);
15
+ /**
16
+ * Record a turn's tool calls. Returns detection info when a loop is found.
17
+ */
18
+ recordToolCalls(blocks: ReadonlyArray<{
19
+ name: string;
20
+ input: Record<string, unknown>;
21
+ }>): LoopDetectionInfo | null;
22
+ /**
23
+ * Record a turn's text output. Returns detection info when a loop is found.
24
+ */
25
+ recordText(text: string): LoopDetectionInfo | null;
26
+ /**
27
+ * Deterministic JSON signature for a set of tool calls.
28
+ * Sorts calls by name (for multi-tool turns) and keys within each input.
29
+ */
30
+ private computeToolSignature;
31
+ /** Push an entry and trim the buffer to `windowSize`. */
32
+ private push;
33
+ /**
34
+ * Count how many consecutive identical entries exist at the tail of `buffer`.
35
+ * Returns 1 when the last entry is unique.
36
+ */
37
+ private consecutiveRepeats;
38
+ }
39
+ //# sourceMappingURL=loop-detector.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loop-detector.d.ts","sourceRoot":"","sources":["../../src/agent/loop-detector.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAwBzE,qBAAa,YAAY;IACvB,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAQ;IACnC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAQ;IAEnC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAe;IAC9C,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAe;gBAE/B,MAAM,GAAE,mBAAwB;IAO5C;;OAEG;IACH,eAAe,CACb,MAAM,EAAE,aAAa,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,CAAC,GACtE,iBAAiB,GAAG,IAAI;IAoB3B;;OAEG;IACH,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,iBAAiB,GAAG,IAAI;IAuBlD;;;OAGG;IACH,OAAO,CAAC,oBAAoB;IAa5B,yDAAyD;IACzD,OAAO,CAAC,IAAI;IAOZ;;;OAGG;IACH,OAAO,CAAC,kBAAkB;CAU3B"}