@openadapter/koda-agent-core 1.0.0-beta.3

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 (52) hide show
  1. package/README.md +488 -0
  2. package/dist/agent-loop.d.ts +23 -0
  3. package/dist/agent-loop.js +1 -0
  4. package/dist/agent.d.ts +117 -0
  5. package/dist/agent.js +1 -0
  6. package/dist/harness/agent-harness.d.ts +94 -0
  7. package/dist/harness/agent-harness.js +1 -0
  8. package/dist/harness/compaction/branch-summarization.d.ts +52 -0
  9. package/dist/harness/compaction/branch-summarization.js +38 -0
  10. package/dist/harness/compaction/compaction.d.ts +94 -0
  11. package/dist/harness/compaction/compaction.js +106 -0
  12. package/dist/harness/compaction/utils.d.ts +24 -0
  13. package/dist/harness/compaction/utils.js +17 -0
  14. package/dist/harness/env/nodejs.d.ts +50 -0
  15. package/dist/harness/env/nodejs.js +1 -0
  16. package/dist/harness/messages.d.ts +50 -0
  17. package/dist/harness/messages.js +17 -0
  18. package/dist/harness/prompt-templates.d.ts +47 -0
  19. package/dist/harness/prompt-templates.js +5 -0
  20. package/dist/harness/session/jsonl-repo.d.ts +25 -0
  21. package/dist/harness/session/jsonl-repo.js +1 -0
  22. package/dist/harness/session/jsonl-storage.d.ts +32 -0
  23. package/dist/harness/session/jsonl-storage.js +5 -0
  24. package/dist/harness/session/memory-repo.d.ts +17 -0
  25. package/dist/harness/session/memory-repo.js +1 -0
  26. package/dist/harness/session/memory-storage.d.ts +24 -0
  27. package/dist/harness/session/memory-storage.js +1 -0
  28. package/dist/harness/session/repo-utils.d.ts +10 -0
  29. package/dist/harness/session/repo-utils.js +1 -0
  30. package/dist/harness/session/session.d.ts +32 -0
  31. package/dist/harness/session/session.js +1 -0
  32. package/dist/harness/session/uuid.d.ts +1 -0
  33. package/dist/harness/session/uuid.js +1 -0
  34. package/dist/harness/skills.d.ts +43 -0
  35. package/dist/harness/skills.js +10 -0
  36. package/dist/harness/system-prompt.d.ts +2 -0
  37. package/dist/harness/system-prompt.js +2 -0
  38. package/dist/harness/types.d.ts +614 -0
  39. package/dist/harness/types.js +1 -0
  40. package/dist/harness/utils/shell-output.d.ts +13 -0
  41. package/dist/harness/utils/shell-output.js +1 -0
  42. package/dist/harness/utils/truncate.d.ts +69 -0
  43. package/dist/harness/utils/truncate.js +5 -0
  44. package/dist/index.d.ts +19 -0
  45. package/dist/index.js +1 -0
  46. package/dist/node.d.ts +2 -0
  47. package/dist/node.js +1 -0
  48. package/dist/proxy.d.ts +68 -0
  49. package/dist/proxy.js +2 -0
  50. package/dist/types.d.ts +392 -0
  51. package/dist/types.js +0 -0
  52. package/package.json +68 -0
package/README.md ADDED
@@ -0,0 +1,488 @@
1
+ # @openadapter/koda-agent-core
2
+
3
+ Stateful agent with tool execution and event streaming. Built on `@openadapter/koda-ai`.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @openadapter/koda-agent-core
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```typescript
14
+ import { Agent } from "@openadapter/koda-agent-core";
15
+ import { getModel } from "@openadapter/koda-ai";
16
+
17
+ const agent = new Agent({
18
+ initialState: {
19
+ systemPrompt: "You are a helpful assistant.",
20
+ model: getModel("anthropic", "claude-sonnet-4-20250514"),
21
+ },
22
+ });
23
+
24
+ agent.subscribe((event) => {
25
+ if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
26
+ // Stream just the new text chunk
27
+ process.stdout.write(event.assistantMessageEvent.delta);
28
+ }
29
+ });
30
+
31
+ await agent.prompt("Hello!");
32
+ ```
33
+
34
+ ## Core Concepts
35
+
36
+ ### AgentMessage vs LLM Message
37
+
38
+ The agent works with `AgentMessage`, a flexible type that can include:
39
+ - Standard LLM messages (`user`, `assistant`, `toolResult`)
40
+ - Custom app-specific message types via declaration merging
41
+
42
+ LLMs only understand `user`, `assistant`, and `toolResult`. The `convertToLlm` function bridges this gap by filtering and transforming messages before each LLM call.
43
+
44
+ ### Message Flow
45
+
46
+ ```
47
+ AgentMessage[] → transformContext() → AgentMessage[] → convertToLlm() → Message[] → LLM
48
+ (optional) (required)
49
+ ```
50
+
51
+ 1. **transformContext**: Prune old messages, inject external context
52
+ 2. **convertToLlm**: Filter out UI-only messages, convert custom types to LLM format
53
+
54
+ ## Event Flow
55
+
56
+ The agent emits events for UI updates. Understanding the event sequence helps build responsive interfaces.
57
+
58
+ ### prompt() Event Sequence
59
+
60
+ When you call `prompt("Hello")`:
61
+
62
+ ```
63
+ prompt("Hello")
64
+ ├─ agent_start
65
+ ├─ turn_start
66
+ ├─ message_start { message: userMessage } // Your prompt
67
+ ├─ message_end { message: userMessage }
68
+ ├─ message_start { message: assistantMessage } // LLM starts responding
69
+ ├─ message_update { message: partial... } // Streaming chunks
70
+ ├─ message_update { message: partial... }
71
+ ├─ message_end { message: assistantMessage } // Complete response
72
+ ├─ turn_end { message, toolResults: [] }
73
+ └─ agent_end { messages: [...] }
74
+ ```
75
+
76
+ ### With Tool Calls
77
+
78
+ If the assistant calls tools, the loop continues:
79
+
80
+ ```
81
+ prompt("Read config.json")
82
+ ├─ agent_start
83
+ ├─ turn_start
84
+ ├─ message_start/end { userMessage }
85
+ ├─ message_start { assistantMessage with toolCall }
86
+ ├─ message_update...
87
+ ├─ message_end { assistantMessage }
88
+ ├─ tool_execution_start { toolCallId, toolName, args }
89
+ ├─ tool_execution_update { partialResult } // If tool streams
90
+ ├─ tool_execution_end { toolCallId, result }
91
+ ├─ message_start/end { toolResultMessage }
92
+ ├─ turn_end { message, toolResults: [toolResult] }
93
+
94
+ ├─ turn_start // Next turn
95
+ ├─ message_start { assistantMessage } // LLM responds to tool result
96
+ ├─ message_update...
97
+ ├─ message_end
98
+ ├─ turn_end
99
+ └─ agent_end
100
+ ```
101
+
102
+ Tool execution mode is configurable:
103
+
104
+ - `parallel` (default): preflight tool calls sequentially, execute allowed tools concurrently, emit `tool_execution_end` as soon as each tool is finalized, then emit toolResult messages and `turn_end.toolResults` in assistant source order
105
+ - `sequential`: execute tool calls one by one, matching the historical behavior
106
+
107
+ In parallel mode, tool completion events follow tool completion order, but persisted toolResult messages still follow assistant source order.
108
+
109
+ The mode can be set globally via `toolExecution` in the agent config, or per-tool via `executionMode` on `AgentTool`. If any tool call in a batch targets a tool with `executionMode: "sequential"`, the entire batch executes sequentially regardless of the global setting.
110
+
111
+ The `beforeToolCall` hook runs after `tool_execution_start` and validated argument parsing. It can block execution. The `afterToolCall` hook runs after tool execution finishes and before `tool_execution_end` and final tool result message events are emitted.
112
+
113
+ Tools can also return `terminate: true` to hint that the automatic follow-up LLM call should be skipped. The loop only stops early when every finalized tool result in that batch sets `terminate: true`. Mixed batches continue normally.
114
+
115
+ Low-level loop callers can set `shouldStopAfterTurn` to stop gracefully after the current turn completes:
116
+
117
+ ```typescript
118
+ const stream = agentLoop(prompts, context, {
119
+ model,
120
+ convertToLlm,
121
+ shouldStopAfterTurn: async ({ message, toolResults, context, newMessages }) => {
122
+ return shouldCompactBeforeNextTurn(context.messages);
123
+ },
124
+ });
125
+ ```
126
+
127
+ `shouldStopAfterTurn` runs after `turn_end` is emitted and after the assistant response and any tool executions have completed normally. If it returns `true`, the loop emits `agent_end` and exits before polling steering or follow-up queues, and before starting another LLM call. It does not abort the provider stream, does not cancel running tools, and does not alter the assistant message stop reason.
128
+
129
+ When you use the `Agent` class, assistant `message_end` processing is treated as a barrier before tool preflight begins. That means `beforeToolCall` sees agent state that already includes the assistant message that requested the tool call.
130
+
131
+ ### continue() Event Sequence
132
+
133
+ `continue()` resumes from existing context without adding a new message. Use it for retries after errors.
134
+
135
+ ```typescript
136
+ // After an error, retry from current state
137
+ await agent.continue();
138
+ ```
139
+
140
+ The last message in context must be `user` or `toolResult` (not `assistant`).
141
+
142
+ ### Event Types
143
+
144
+ | Event | Description |
145
+ |-------|-------------|
146
+ | `agent_start` | Agent begins processing |
147
+ | `agent_end` | Final event for the run. Awaited subscribers for this event still count toward settlement |
148
+ | `turn_start` | New turn begins (one LLM call + tool executions) |
149
+ | `turn_end` | Turn completes with assistant message and tool results |
150
+ | `message_start` | Any message begins (user, assistant, toolResult) |
151
+ | `message_update` | **Assistant only.** Includes `assistantMessageEvent` with delta |
152
+ | `message_end` | Message completes |
153
+ | `tool_execution_start` | Tool begins |
154
+ | `tool_execution_update` | Tool streams progress |
155
+ | `tool_execution_end` | Tool completes |
156
+
157
+ `Agent.subscribe()` listeners are awaited in registration order. `agent_end` means no more loop events will be emitted, but `await agent.waitForIdle()` and `await agent.prompt(...)` only settle after awaited `agent_end` listeners finish.
158
+
159
+ ## Agent Options
160
+
161
+ ```typescript
162
+ const agent = new Agent({
163
+ // Initial state
164
+ initialState: {
165
+ systemPrompt: string,
166
+ model: Model<any>,
167
+ thinkingLevel: "off" | "minimal" | "low" | "medium" | "high" | "xhigh",
168
+ tools: AgentTool<any>[],
169
+ messages: AgentMessage[],
170
+ },
171
+
172
+ // Convert AgentMessage[] to LLM Message[] (required for custom message types)
173
+ convertToLlm: (messages) => messages.filter(...),
174
+
175
+ // Transform context before convertToLlm (for pruning, compaction)
176
+ transformContext: async (messages, signal) => pruneOldMessages(messages),
177
+
178
+ // Steering mode: "one-at-a-time" (default) or "all"
179
+ steeringMode: "one-at-a-time",
180
+
181
+ // Follow-up mode: "one-at-a-time" (default) or "all"
182
+ followUpMode: "one-at-a-time",
183
+
184
+ // Custom stream function (for proxy backends)
185
+ streamFn: streamProxy,
186
+
187
+ // Session ID for provider caching
188
+ sessionId: "session-123",
189
+
190
+ // Dynamic API key resolution (for expiring OAuth tokens)
191
+ getApiKey: async (provider) => refreshToken(),
192
+
193
+ // Tool execution mode: "parallel" (default) or "sequential"
194
+ toolExecution: "parallel",
195
+
196
+ // Preflight each tool call after args are validated. Can block execution.
197
+ beforeToolCall: async ({ toolCall, args, context }) => {
198
+ if (toolCall.name === "bash") {
199
+ return { block: true, reason: "bash is disabled" };
200
+ }
201
+ },
202
+
203
+ // Postprocess each tool result before final tool events are emitted.
204
+ afterToolCall: async ({ toolCall, result, isError, context }) => {
205
+ if (toolCall.name === "notify_done" && !isError) {
206
+ return { terminate: true };
207
+ }
208
+ if (!isError) {
209
+ return { details: { ...result.details, audited: true } };
210
+ }
211
+ },
212
+
213
+ // Custom thinking budgets for token-based providers
214
+ thinkingBudgets: {
215
+ minimal: 128,
216
+ low: 512,
217
+ medium: 1024,
218
+ high: 2048,
219
+ },
220
+ });
221
+ ```
222
+
223
+ ## Agent State
224
+
225
+ ```typescript
226
+ interface AgentState {
227
+ systemPrompt: string;
228
+ model: Model<any>;
229
+ thinkingLevel: ThinkingLevel;
230
+ tools: AgentTool<any>[];
231
+ messages: AgentMessage[];
232
+ readonly isStreaming: boolean;
233
+ readonly streamingMessage?: AgentMessage;
234
+ readonly pendingToolCalls: ReadonlySet<string>;
235
+ readonly errorMessage?: string;
236
+ }
237
+ ```
238
+
239
+ Access state via `agent.state`.
240
+
241
+ Assigning `agent.state.tools = [...]` or `agent.state.messages = [...]` copies the top-level array before storing it. Mutating the returned array mutates the current agent state.
242
+
243
+ During streaming, `agent.state.streamingMessage` contains the current partial assistant message.
244
+
245
+ `agent.state.isStreaming` remains `true` until the run fully settles, including awaited `agent_end` subscribers.
246
+
247
+ ## Methods
248
+
249
+ ### Prompting
250
+
251
+ ```typescript
252
+ // Text prompt
253
+ await agent.prompt("Hello");
254
+
255
+ // With images
256
+ await agent.prompt("What's in this image?", [
257
+ { type: "image", data: base64Data, mimeType: "image/jpeg" }
258
+ ]);
259
+
260
+ // AgentMessage directly
261
+ await agent.prompt({ role: "user", content: "Hello", timestamp: Date.now() });
262
+
263
+ // Continue from current context (last message must be user or toolResult)
264
+ await agent.continue();
265
+ ```
266
+
267
+ ### State Management
268
+
269
+ ```typescript
270
+ agent.state.systemPrompt = "New prompt";
271
+ agent.state.model = getModel("openai", "gpt-4o");
272
+ agent.state.thinkingLevel = "medium";
273
+ agent.state.tools = [myTool];
274
+ agent.toolExecution = "sequential";
275
+ agent.beforeToolCall = async ({ toolCall }) => undefined;
276
+ agent.afterToolCall = async ({ toolCall, result }) => undefined;
277
+ agent.state.messages = newMessages; // top-level array is copied
278
+ agent.state.messages.push(message);
279
+ agent.reset();
280
+ ```
281
+
282
+ ### Session and Thinking Budgets
283
+
284
+ ```typescript
285
+ agent.sessionId = "session-123";
286
+
287
+ agent.thinkingBudgets = {
288
+ minimal: 128,
289
+ low: 512,
290
+ medium: 1024,
291
+ high: 2048,
292
+ };
293
+ ```
294
+
295
+ ### Control
296
+
297
+ ```typescript
298
+ agent.abort(); // Cancel current operation
299
+ await agent.waitForIdle(); // Wait for completion
300
+ ```
301
+
302
+ ### Events
303
+
304
+ ```typescript
305
+ const unsubscribe = agent.subscribe(async (event, signal) => {
306
+ if (event.type === "agent_end") {
307
+ // Final barrier work for the run
308
+ await flushSessionState(signal);
309
+ }
310
+ });
311
+ unsubscribe();
312
+ ```
313
+
314
+ ## Steering and Follow-up
315
+
316
+ Steering messages let you interrupt the agent while tools are running. Follow-up messages let you queue work after the agent would otherwise stop.
317
+
318
+ ```typescript
319
+ agent.steeringMode = "one-at-a-time";
320
+ agent.followUpMode = "one-at-a-time";
321
+
322
+ // While agent is running tools
323
+ agent.steer({
324
+ role: "user",
325
+ content: "Stop! Do this instead.",
326
+ timestamp: Date.now(),
327
+ });
328
+
329
+ // After the agent finishes its current work
330
+ agent.followUp({
331
+ role: "user",
332
+ content: "Also summarize the result.",
333
+ timestamp: Date.now(),
334
+ });
335
+
336
+ const steeringMode = agent.steeringMode;
337
+ const followUpMode = agent.followUpMode;
338
+
339
+ agent.clearSteeringQueue();
340
+ agent.clearFollowUpQueue();
341
+ agent.clearAllQueues();
342
+ ```
343
+
344
+ Use clearSteeringQueue, clearFollowUpQueue, or clearAllQueues to drop queued messages.
345
+
346
+ When steering messages are detected after a turn completes:
347
+ 1. All tool calls from the current assistant message have already finished
348
+ 2. Steering messages are injected
349
+ 3. The LLM responds on the next turn
350
+
351
+ Follow-up messages are checked only when there are no more tool calls and no steering messages. If any are queued, they are injected and another turn runs.
352
+
353
+ ## Custom Message Types
354
+
355
+ Extend `AgentMessage` via declaration merging:
356
+
357
+ ```typescript
358
+ declare module "@openadapter/koda-agent-core" {
359
+ interface CustomAgentMessages {
360
+ notification: { role: "notification"; text: string; timestamp: number };
361
+ }
362
+ }
363
+
364
+ // Now valid
365
+ const msg: AgentMessage = { role: "notification", text: "Info", timestamp: Date.now() };
366
+ ```
367
+
368
+ Handle custom types in `convertToLlm`:
369
+
370
+ ```typescript
371
+ const agent = new Agent({
372
+ convertToLlm: (messages) => messages.flatMap(m => {
373
+ if (m.role === "notification") return []; // Filter out
374
+ return [m];
375
+ }),
376
+ });
377
+ ```
378
+
379
+ ## Tools
380
+
381
+ Define tools using `AgentTool`:
382
+
383
+ ```typescript
384
+ import { Type } from "typebox";
385
+
386
+ const readFileTool: AgentTool = {
387
+ name: "read_file",
388
+ label: "Read File", // For UI display
389
+ description: "Read a file's contents",
390
+ parameters: Type.Object({
391
+ path: Type.String({ description: "File path" }),
392
+ }),
393
+ // Override execution mode for this tool (optional).
394
+ // "sequential" forces the entire batch to run one at a time.
395
+ // "parallel" allows concurrent execution with other tool calls.
396
+ // If omitted, the global toolExecution config applies.
397
+ executionMode: "sequential",
398
+ execute: async (toolCallId, params, signal, onUpdate) => {
399
+ const content = await fs.readFile(params.path, "utf-8");
400
+
401
+ // Optional: stream progress
402
+ onUpdate?.({ content: [{ type: "text", text: "Reading..." }], details: {} });
403
+
404
+ // Optional: add `terminate: true` here to skip the automatic follow-up LLM call
405
+ // when every finalized tool result in the batch does the same.
406
+ return {
407
+ content: [{ type: "text", text: content }],
408
+ details: { path: params.path, size: content.length },
409
+ };
410
+ },
411
+ };
412
+
413
+ agent.state.tools = [readFileTool];
414
+ ```
415
+
416
+ ### Error Handling
417
+
418
+ **Throw an error** when a tool fails. Do not return error messages as content.
419
+
420
+ ```typescript
421
+ execute: async (toolCallId, params, signal, onUpdate) => {
422
+ if (!fs.existsSync(params.path)) {
423
+ throw new Error(`File not found: ${params.path}`);
424
+ }
425
+ // Return content only on success
426
+ return { content: [{ type: "text", text: "..." }] };
427
+ }
428
+ ```
429
+
430
+ Thrown errors are caught by the agent and reported to the LLM as tool errors with `isError: true`.
431
+
432
+ Return `terminate: true` from `execute()` or `afterToolCall` to hint that the agent should stop after the current tool batch. This only takes effect when every finalized tool result in the batch is terminating. The hint is runtime-only; emitted `toolResult` transcript messages remain standard LLM tool results.
433
+
434
+ ## Proxy Usage
435
+
436
+ For browser apps that proxy through a backend:
437
+
438
+ ```typescript
439
+ import { Agent, streamProxy } from "@openadapter/koda-agent-core";
440
+
441
+ const agent = new Agent({
442
+ streamFn: (model, context, options) =>
443
+ streamProxy(model, context, {
444
+ ...options,
445
+ authToken: "...",
446
+ proxyUrl: "https://your-server.com",
447
+ }),
448
+ });
449
+ ```
450
+
451
+ ## Low-Level API
452
+
453
+ For direct control without the Agent class:
454
+
455
+ ```typescript
456
+ import { agentLoop, agentLoopContinue } from "@openadapter/koda-agent-core";
457
+
458
+ const context: AgentContext = {
459
+ systemPrompt: "You are helpful.",
460
+ messages: [],
461
+ tools: [],
462
+ };
463
+
464
+ const config: AgentLoopConfig = {
465
+ model: getModel("openai", "gpt-4o"),
466
+ convertToLlm: (msgs) => msgs.filter(m => ["user", "assistant", "toolResult"].includes(m.role)),
467
+ toolExecution: "parallel", // overridden by per-tool executionMode if set
468
+ beforeToolCall: async ({ toolCall, args, context }) => undefined,
469
+ afterToolCall: async ({ toolCall, result, isError, context }) => undefined,
470
+ };
471
+
472
+ const userMessage = { role: "user", content: "Hello", timestamp: Date.now() };
473
+
474
+ for await (const event of agentLoop([userMessage], context, config)) {
475
+ console.log(event.type);
476
+ }
477
+
478
+ // Continue from existing context
479
+ for await (const event of agentLoopContinue(context, config)) {
480
+ console.log(event.type);
481
+ }
482
+ ```
483
+
484
+ These low-level streams are observational. They preserve event order, but they do not wait for your async event handling to settle before later producer phases continue. If you need message processing to act as a barrier before tool preflight, use the `Agent` class instead of raw `agentLoop()` or `agentLoopContinue()`.
485
+
486
+ ## License
487
+
488
+ MIT
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Agent loop that works with AgentMessage throughout.
3
+ * Transforms to Message[] only at the LLM call boundary.
4
+ */
5
+ import { EventStream } from "@openadapter/koda-ai";
6
+ import type { AgentContext, AgentEvent, AgentLoopConfig, AgentMessage, StreamFn } from "./types.ts";
7
+ export type AgentEventSink = (event: AgentEvent) => Promise<void> | void;
8
+ /**
9
+ * Start an agent loop with a new prompt message.
10
+ * The prompt is added to the context and events are emitted for it.
11
+ */
12
+ export declare function agentLoop(prompts: AgentMessage[], context: AgentContext, config: AgentLoopConfig, signal?: AbortSignal, streamFn?: StreamFn): EventStream<AgentEvent, AgentMessage[]>;
13
+ /**
14
+ * Continue an agent loop from the current context without adding a new message.
15
+ * Used for retries - context already has user message or tool results.
16
+ *
17
+ * **Important:** The last message in context must convert to a `user` or `toolResult` message
18
+ * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.
19
+ * This cannot be validated here since `convertToLlm` is only called once per turn.
20
+ */
21
+ export declare function agentLoopContinue(context: AgentContext, config: AgentLoopConfig, signal?: AbortSignal, streamFn?: StreamFn): EventStream<AgentEvent, AgentMessage[]>;
22
+ export declare function runAgentLoop(prompts: AgentMessage[], context: AgentContext, config: AgentLoopConfig, emit: AgentEventSink, signal?: AbortSignal, streamFn?: StreamFn): Promise<AgentMessage[]>;
23
+ export declare function runAgentLoopContinue(context: AgentContext, config: AgentLoopConfig, emit: AgentEventSink, signal?: AbortSignal, streamFn?: StreamFn): Promise<AgentMessage[]>;
@@ -0,0 +1 @@
1
+ var N=Object.defineProperty;var g=(e,t)=>N(e,"name",{value:t,configurable:!0});import{EventStream as K,streamSimple as M,validateToolArguments as I}from"@openadapter/koda-ai";function z(e,t,n,o,s){const r=k();return q(e,t,n,async a=>{r.push(a)},o,s).then(a=>{r.end(a)}),r}g(z,"agentLoop");function G(e,t,n,o){if(e.messages.length===0)throw new Error("Cannot continue: no messages in context");if(e.messages[e.messages.length-1].role==="assistant")throw new Error("Cannot continue from message role: assistant");const s=k();return F(e,t,async r=>{s.push(r)},n,o).then(r=>{s.end(r)}),s}g(G,"agentLoopContinue");async function q(e,t,n,o,s,r){const a=[...e],l={...t,messages:[...t.messages,...e]};await o({type:"agent_start"}),await o({type:"turn_start"});for(const i of e)await o({type:"message_start",message:i}),await o({type:"message_end",message:i});return await b(l,a,n,s,o,r),a}g(q,"runAgentLoop");async function F(e,t,n,o,s){if(e.messages.length===0)throw new Error("Cannot continue: no messages in context");if(e.messages[e.messages.length-1].role==="assistant")throw new Error("Cannot continue from message role: assistant");const r=[],a={...e};return await n({type:"agent_start"}),await n({type:"turn_start"}),await b(a,r,t,o,n,s),r}g(F,"runAgentLoopContinue");function k(){return new K(e=>e.type==="agent_end",e=>e.type==="agent_end"?e.messages:[])}g(k,"createAgentStream");async function b(e,t,n,o,s,r){let a=e,l=n,i=!0;const c=Number(process.env.KODA_MAX_STEPS)||30;let m=0,u=await l.getSteeringMessages?.()||[];for(;;){let d=!0;for(;d||u.length>0;){if(i?i=!1:await s({type:"turn_start"}),u.length>0){for(const f of u)await s({type:"message_start",message:f}),await s({type:"message_end",message:f}),a.messages.push(f),t.push(f);u=[]}const p=await O(a,l,o,s,r);if(t.push(p),m++,p.stopReason==="error"||p.stopReason==="aborted"){await s({type:"turn_end",message:p,toolResults:[]}),await s({type:"agent_end",messages:t});return}const y=p.content.filter(f=>f.type==="toolCall"),C=[];if(d=!1,y.length>0){const f=await B(a,p,l,o,s);C.push(...f.messages),d=!f.terminate;for(const T of C)a.messages.push(T),t.push(T)}if(await s({type:"turn_end",message:p,toolResults:C}),m>=c&&d){await s({type:"agent_end",messages:t});return}const L={message:p,toolResults:C,context:a,newMessages:t},_=await l.prepareNextTurn?.(L);if(_&&(a=_.context??a,l={...l,model:_.model??l.model,reasoning:_.thinkingLevel===void 0?l.reasoning:_.thinkingLevel==="off"?void 0:_.thinkingLevel}),await l.shouldStopAfterTurn?.({message:p,toolResults:C,context:a,newMessages:t})){await s({type:"agent_end",messages:t});return}u=await l.getSteeringMessages?.()||[]}const w=await l.getFollowUpMessages?.()||[];if(w.length>0){u=w;continue}break}await s({type:"agent_end",messages:t})}g(b,"runLoop");async function O(e,t,n,o,s){let r=e.messages;t.transformContext&&(r=await t.transformContext(r,n));const a=await t.convertToLlm(r),l={systemPrompt:e.systemPrompt,messages:a,tools:e.tools},i=s||M,c=(t.getApiKey?await t.getApiKey(t.model.provider):void 0)||t.apiKey,m=await i(t.model,l,{...t,apiKey:c,signal:n});let u=null,d=!1;for await(const p of m)switch(p.type){case"start":u=p.partial,e.messages.push(u),d=!0,await o({type:"message_start",message:{...u}});break;case"text_start":case"text_delta":case"text_end":case"thinking_start":case"thinking_delta":case"thinking_end":case"toolcall_start":case"toolcall_delta":case"toolcall_end":u&&(u=p.partial,e.messages[e.messages.length-1]=u,await o({type:"message_update",assistantMessageEvent:p,message:{...u}}));break;case"done":case"error":{const y=await m.result();return d?e.messages[e.messages.length-1]=y:e.messages.push(y),d||await o({type:"message_start",message:{...y}}),await o({type:"message_end",message:y}),y}}const w=await m.result();return d?e.messages[e.messages.length-1]=w:(e.messages.push(w),await o({type:"message_start",message:{...w}})),await o({type:"message_end",message:w}),w}g(O,"streamAssistantResponse");async function B(e,t,n,o,s){const r=t.content.filter(l=>l.type==="toolCall"),a=r.some(l=>e.tools?.find(i=>i.name===l.name)?.executionMode==="sequential");return n.toolExecution==="sequential"||a?D(e,t,r,n,o,s):U(e,t,r,n,o,s)}g(B,"executeToolCalls");async function D(e,t,n,o,s,r){const a=[],l=[];for(const i of n){await r({type:"tool_execution_start",toolCallId:i.id,toolName:i.name,args:i.arguments});const c=await v(e,t,i,o,s);let m;if(c.kind==="immediate")m={toolCall:i,result:c.result,isError:c.isError};else{const d=await A(c,s,r);m=await S(e,t,c,d,o,s)}await E(m,r);const u=R(m);if(await P(u,r),a.push(m),l.push(u),s?.aborted)break}return{messages:l,terminate:x(a)}}g(D,"executeToolCallsSequential");async function U(e,t,n,o,s,r){const a=[];for(const c of n){await r({type:"tool_execution_start",toolCallId:c.id,toolName:c.name,args:c.arguments});const m=await v(e,t,c,o,s);if(m.kind==="immediate"){const u={toolCall:c,result:m.result,isError:m.isError};if(await E(u,r),a.push(u),s?.aborted)break;continue}if(a.push(async()=>{const u=await A(m,s,r),d=await S(e,t,m,u,o,s);return await E(d,r),d}),s?.aborted)break}const l=await Promise.all(a.map(c=>typeof c=="function"?c():Promise.resolve(c))),i=[];for(const c of l){const m=R(c);await P(m,r),i.push(m)}return{messages:i,terminate:x(l)}}g(U,"executeToolCallsParallel");function x(e){return e.length>0&&e.every(t=>t.result.terminate===!0)}g(x,"shouldTerminateToolBatch");function X(e,t){if(!e.prepareArguments)return t;const n=e.prepareArguments(t.arguments);return n===t.arguments?t:{...t,arguments:n}}g(X,"prepareToolCallArguments");async function v(e,t,n,o,s){const r=e.tools?.find(a=>a.name===n.name);if(!r)return{kind:"immediate",result:h(`Tool ${n.name} not found`),isError:!0};try{const a=X(r,n),l=I(r,a);if(o.beforeToolCall){const i=await o.beforeToolCall({assistantMessage:t,toolCall:n,args:l,context:e},s);if(s?.aborted)return{kind:"immediate",result:h("Operation aborted"),isError:!0};if(i?.block)return{kind:"immediate",result:h(i.reason||"Tool execution was blocked"),isError:!0}}return s?.aborted?{kind:"immediate",result:h("Operation aborted"),isError:!0}:{kind:"prepared",toolCall:n,tool:r,args:l}}catch(a){return{kind:"immediate",result:h(a instanceof Error?a.message:String(a)),isError:!0}}}g(v,"prepareToolCall");async function A(e,t,n){const o=[];try{const s=await e.tool.execute(e.toolCall.id,e.args,t,r=>{o.push(Promise.resolve(n({type:"tool_execution_update",toolCallId:e.toolCall.id,toolName:e.toolCall.name,args:e.toolCall.arguments,partialResult:r})))});return await Promise.all(o),{result:s,isError:!1}}catch(s){return await Promise.all(o),{result:h(s instanceof Error?s.message:String(s)),isError:!0}}}g(A,"executePreparedToolCall");async function S(e,t,n,o,s,r){let a=o.result,l=o.isError;if(s.afterToolCall)try{const i=await s.afterToolCall({assistantMessage:t,toolCall:n.toolCall,args:n.args,result:a,isError:l,context:e},r);i&&(a={content:i.content??a.content,details:i.details??a.details,terminate:i.terminate??a.terminate},l=i.isError??l)}catch(i){a=h(i instanceof Error?i.message:String(i)),l=!0}return{toolCall:n.toolCall,result:a,isError:l}}g(S,"finalizeExecutedToolCall");function h(e){return{content:[{type:"text",text:e}],details:{}}}g(h,"createErrorToolResult");async function E(e,t){await t({type:"tool_execution_end",toolCallId:e.toolCall.id,toolName:e.toolCall.name,result:e.result,isError:e.isError})}g(E,"emitToolExecutionEnd");function R(e){return{role:"toolResult",toolCallId:e.toolCall.id,toolName:e.toolCall.name,content:e.result.content,details:e.result.details,isError:e.isError,timestamp:Date.now()}}g(R,"createToolResultMessage");async function P(e,t){await t({type:"message_start",message:e}),await t({type:"message_end",message:e})}g(P,"emitToolResultMessage");export{z as agentLoop,G as agentLoopContinue,q as runAgentLoop,F as runAgentLoopContinue};
@@ -0,0 +1,117 @@
1
+ import { type ImageContent, type Message, type SimpleStreamOptions, type ThinkingBudgets, type Transport } from "@openadapter/koda-ai";
2
+ import type { AfterToolCallContext, AfterToolCallResult, AgentEvent, AgentLoopTurnUpdate, AgentMessage, AgentState, BeforeToolCallContext, BeforeToolCallResult, QueueMode, StreamFn, ToolExecutionMode } from "./types.ts";
3
+ export type { QueueMode } from "./types.ts";
4
+ /** Options for constructing an {@link Agent}. */
5
+ export interface AgentOptions {
6
+ initialState?: Partial<Omit<AgentState, "pendingToolCalls" | "isStreaming" | "streamingMessage" | "errorMessage">>;
7
+ convertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
8
+ transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
9
+ streamFn?: StreamFn;
10
+ getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
11
+ onPayload?: SimpleStreamOptions["onPayload"];
12
+ onResponse?: SimpleStreamOptions["onResponse"];
13
+ beforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;
14
+ afterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;
15
+ prepareNextTurn?: (signal?: AbortSignal) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;
16
+ steeringMode?: QueueMode;
17
+ followUpMode?: QueueMode;
18
+ sessionId?: string;
19
+ thinkingBudgets?: ThinkingBudgets;
20
+ transport?: Transport;
21
+ maxRetryDelayMs?: number;
22
+ toolExecution?: ToolExecutionMode;
23
+ }
24
+ /**
25
+ * Stateful wrapper around the low-level agent loop.
26
+ *
27
+ * `Agent` owns the current transcript, emits lifecycle events, executes tools,
28
+ * and exposes queueing APIs for steering and follow-up messages.
29
+ */
30
+ export declare class Agent {
31
+ private _state;
32
+ private readonly listeners;
33
+ private readonly steeringQueue;
34
+ private readonly followUpQueue;
35
+ convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
36
+ transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
37
+ streamFn: StreamFn;
38
+ getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
39
+ onPayload?: SimpleStreamOptions["onPayload"];
40
+ onResponse?: SimpleStreamOptions["onResponse"];
41
+ beforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;
42
+ afterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;
43
+ prepareNextTurn?: (signal?: AbortSignal) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;
44
+ private activeRun?;
45
+ /** Session identifier forwarded to providers for cache-aware backends. */
46
+ sessionId?: string;
47
+ /** Optional per-level thinking token budgets forwarded to the stream function. */
48
+ thinkingBudgets?: ThinkingBudgets;
49
+ /** Preferred transport forwarded to the stream function. */
50
+ transport: Transport;
51
+ /** Optional cap for provider-requested retry delays. */
52
+ maxRetryDelayMs?: number;
53
+ /** Tool execution strategy for assistant messages that contain multiple tool calls. */
54
+ toolExecution: ToolExecutionMode;
55
+ constructor(options?: AgentOptions);
56
+ /**
57
+ * Subscribe to agent lifecycle events.
58
+ *
59
+ * Listener promises are awaited in subscription order and are included in
60
+ * the current run's settlement. Listeners also receive the active abort
61
+ * signal for the current run.
62
+ *
63
+ * `agent_end` is the final emitted event for a run, but the agent does not
64
+ * become idle until all awaited listeners for that event have settled.
65
+ */
66
+ subscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void;
67
+ /**
68
+ * Current agent state.
69
+ *
70
+ * Assigning `state.tools` or `state.messages` copies the provided top-level array.
71
+ */
72
+ get state(): AgentState;
73
+ /** Controls how queued steering messages are drained. */
74
+ set steeringMode(mode: QueueMode);
75
+ get steeringMode(): QueueMode;
76
+ /** Controls how queued follow-up messages are drained. */
77
+ set followUpMode(mode: QueueMode);
78
+ get followUpMode(): QueueMode;
79
+ /** Queue a message to be injected after the current assistant turn finishes. */
80
+ steer(message: AgentMessage): void;
81
+ /** Queue a message to run only after the agent would otherwise stop. */
82
+ followUp(message: AgentMessage): void;
83
+ /** Remove all queued steering messages. */
84
+ clearSteeringQueue(): void;
85
+ /** Remove all queued follow-up messages. */
86
+ clearFollowUpQueue(): void;
87
+ /** Remove all queued steering and follow-up messages. */
88
+ clearAllQueues(): void;
89
+ /** Returns true when either queue still contains pending messages. */
90
+ hasQueuedMessages(): boolean;
91
+ /** Active abort signal for the current run, if any. */
92
+ get signal(): AbortSignal | undefined;
93
+ /** Abort the current run, if one is active. */
94
+ abort(): void;
95
+ /**
96
+ * Resolve when the current run and all awaited event listeners have finished.
97
+ *
98
+ * This resolves after `agent_end` listeners settle.
99
+ */
100
+ waitForIdle(): Promise<void>;
101
+ /** Clear transcript state, runtime state, and queued messages. */
102
+ reset(): void;
103
+ /** Start a new prompt from text, a single message, or a batch of messages. */
104
+ prompt(message: AgentMessage | AgentMessage[]): Promise<void>;
105
+ prompt(input: string, images?: ImageContent[]): Promise<void>;
106
+ /** Continue from the current transcript. The last message must be a user or tool-result message. */
107
+ continue(): Promise<void>;
108
+ private normalizePromptInput;
109
+ private runPromptMessages;
110
+ private runContinuation;
111
+ private createContextSnapshot;
112
+ private createLoopConfig;
113
+ private runWithLifecycle;
114
+ private handleRunFailure;
115
+ private finishRun;
116
+ private processEvents;
117
+ }
package/dist/agent.js ADDED
@@ -0,0 +1 @@
1
+ var l=Object.defineProperty;var n=(a,e)=>l(a,"name",{value:e,configurable:!0});import{streamSimple as u}from"@openadapter/koda-ai";import{runAgentLoop as h,runAgentLoopContinue as g}from"./agent-loop.js";function c(a){return a.filter(e=>e.role==="user"||e.role==="assistant"||e.role==="toolResult")}n(c,"defaultConvertToLlm");const m={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},d={id:"unknown",name:"unknown",api:"unknown",provider:"unknown",baseUrl:"",reasoning:!1,input:[],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:0,maxTokens:0};function p(a){let e=a?.tools?.slice()??[],t=a?.messages?.slice()??[];return{systemPrompt:a?.systemPrompt??"",model:a?.model??d,thinkingLevel:a?.thinkingLevel??"off",get tools(){return e},set tools(s){e=s.slice()},get messages(){return t},set messages(s){t=s.slice()},isStreaming:!1,streamingMessage:void 0,pendingToolCalls:new Set,errorMessage:void 0}}n(p,"createMutableAgentState");class o{static{n(this,"PendingMessageQueue")}messages=[];mode;constructor(e){this.mode=e}enqueue(e){this.messages.push(e)}hasItems(){return this.messages.length>0}drain(){if(this.mode==="all"){const t=this.messages.slice();return this.messages=[],t}const e=this.messages[0];return e?(this.messages=this.messages.slice(1),[e]):[]}clear(){this.messages=[]}}class _{static{n(this,"Agent")}_state;listeners=new Set;steeringQueue;followUpQueue;convertToLlm;transformContext;streamFn;getApiKey;onPayload;onResponse;beforeToolCall;afterToolCall;prepareNextTurn;activeRun;sessionId;thinkingBudgets;transport;maxRetryDelayMs;toolExecution;constructor(e={}){this._state=p(e.initialState),this.convertToLlm=e.convertToLlm??c,this.transformContext=e.transformContext,this.streamFn=e.streamFn??u,this.getApiKey=e.getApiKey,this.onPayload=e.onPayload,this.onResponse=e.onResponse,this.beforeToolCall=e.beforeToolCall,this.afterToolCall=e.afterToolCall,this.prepareNextTurn=e.prepareNextTurn,this.steeringQueue=new o(e.steeringMode??"one-at-a-time"),this.followUpQueue=new o(e.followUpMode??"one-at-a-time"),this.sessionId=e.sessionId,this.thinkingBudgets=e.thinkingBudgets,this.transport=e.transport??"auto",this.maxRetryDelayMs=e.maxRetryDelayMs,this.toolExecution=e.toolExecution??"parallel"}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get state(){return this._state}set steeringMode(e){this.steeringQueue.mode=e}get steeringMode(){return this.steeringQueue.mode}set followUpMode(e){this.followUpQueue.mode=e}get followUpMode(){return this.followUpQueue.mode}steer(e){this.steeringQueue.enqueue(e)}followUp(e){this.followUpQueue.enqueue(e)}clearSteeringQueue(){this.steeringQueue.clear()}clearFollowUpQueue(){this.followUpQueue.clear()}clearAllQueues(){this.clearSteeringQueue(),this.clearFollowUpQueue()}hasQueuedMessages(){return this.steeringQueue.hasItems()||this.followUpQueue.hasItems()}get signal(){return this.activeRun?.abortController.signal}abort(){this.activeRun?.abortController.abort()}waitForIdle(){return this.activeRun?.promise??Promise.resolve()}reset(){this._state.messages=[],this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this._state.errorMessage=void 0,this.clearFollowUpQueue(),this.clearSteeringQueue()}async prompt(e,t){if(this.activeRun)throw new Error("Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.");const s=this.normalizePromptInput(e,t);await this.runPromptMessages(s)}async continue(){if(this.activeRun)throw new Error("Agent is already processing. Wait for completion before continuing.");const e=this._state.messages[this._state.messages.length-1];if(!e)throw new Error("No messages to continue from");if(e.role==="assistant"){const t=this.steeringQueue.drain();if(t.length>0){await this.runPromptMessages(t,{skipInitialSteeringPoll:!0});return}const s=this.followUpQueue.drain();if(s.length>0){await this.runPromptMessages(s);return}throw new Error("Cannot continue from message role: assistant")}await this.runContinuation()}normalizePromptInput(e,t){if(Array.isArray(e))return e;if(typeof e!="string")return[e];const s=[{type:"text",text:e}];return t&&t.length>0&&s.push(...t),[{role:"user",content:s,timestamp:Date.now()}]}async runPromptMessages(e,t={}){await this.runWithLifecycle(async s=>{await h(e,this.createContextSnapshot(),this.createLoopConfig(t),r=>this.processEvents(r),s,this.streamFn)})}async runContinuation(){await this.runWithLifecycle(async e=>{await g(this.createContextSnapshot(),this.createLoopConfig(),t=>this.processEvents(t),e,this.streamFn)})}createContextSnapshot(){return{systemPrompt:this._state.systemPrompt,messages:this._state.messages.slice(),tools:this._state.tools.slice()}}createLoopConfig(e={}){let t=e.skipInitialSteeringPoll===!0;return{model:this._state.model,reasoning:this._state.thinkingLevel==="off"?void 0:this._state.thinkingLevel,sessionId:this.sessionId,onPayload:this.onPayload,onResponse:this.onResponse,transport:this.transport,thinkingBudgets:this.thinkingBudgets,maxRetryDelayMs:this.maxRetryDelayMs,toolExecution:this.toolExecution,beforeToolCall:this.beforeToolCall,afterToolCall:this.afterToolCall,prepareNextTurn:this.prepareNextTurn?async()=>await this.prepareNextTurn?.(this.signal):void 0,convertToLlm:this.convertToLlm,transformContext:this.transformContext,getApiKey:this.getApiKey,getSteeringMessages:n(async()=>t?(t=!1,[]):this.steeringQueue.drain(),"getSteeringMessages"),getFollowUpMessages:n(async()=>this.followUpQueue.drain(),"getFollowUpMessages")}}async runWithLifecycle(e){if(this.activeRun)throw new Error("Agent is already processing.");const t=new AbortController;let s=n(()=>{},"resolvePromise");const r=new Promise(i=>{s=i});this.activeRun={promise:r,resolve:s,abortController:t},this._state.isStreaming=!0,this._state.streamingMessage=void 0,this._state.errorMessage=void 0;try{await e(t.signal)}catch(i){await this.handleRunFailure(i,t.signal.aborted)}finally{this.finishRun()}}async handleRunFailure(e,t){const s={role:"assistant",content:[{type:"text",text:""}],api:this._state.model.api,provider:this._state.model.provider,model:this._state.model.id,usage:m,stopReason:t?"aborted":"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()};await this.processEvents({type:"message_start",message:s}),await this.processEvents({type:"message_end",message:s}),await this.processEvents({type:"turn_end",message:s,toolResults:[]}),await this.processEvents({type:"agent_end",messages:[s]})}finishRun(){this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this.activeRun?.resolve(),this.activeRun=void 0}async processEvents(e){switch(e.type){case"message_start":this._state.streamingMessage=e.message;break;case"message_update":this._state.streamingMessage=e.message;break;case"message_end":this._state.streamingMessage=void 0,this._state.messages.push(e.message);break;case"tool_execution_start":{const s=new Set(this._state.pendingToolCalls);s.add(e.toolCallId),this._state.pendingToolCalls=s;break}case"tool_execution_end":{const s=new Set(this._state.pendingToolCalls);s.delete(e.toolCallId),this._state.pendingToolCalls=s;break}case"turn_end":e.message.role==="assistant"&&e.message.errorMessage&&(this._state.errorMessage=e.message.errorMessage);break;case"agent_end":this._state.streamingMessage=void 0;break}const t=this.activeRun?.abortController.signal;if(!t)throw new Error("Agent listener invoked outside active run");for(const s of this.listeners)await s(e,t)}}export{_ as Agent};