evolcore 0.0.7 → 0.0.9

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 (230) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +38 -4
  3. package/dist/agents/baseagent.js +117 -24
  4. package/dist/agents/claude-runner.js +31 -2
  5. package/dist/agents/codex-app-server-client.js +37 -2
  6. package/dist/agents/codex-runner.js +11 -3
  7. package/dist/aun/aid/control-aid.js +40 -27
  8. package/dist/aun/aid/domain.js +23 -0
  9. package/dist/aun/msg/group.js +9 -9
  10. package/dist/aun/msg/p2p.js +11 -6
  11. package/dist/aun/msg/upload.js +43 -29
  12. package/dist/aun/outbox.js +48 -5
  13. package/dist/channels/aun.js +225 -71
  14. package/dist/cli/aun-commands.js +10 -7
  15. package/dist/cli/bench.js +4 -3
  16. package/dist/cli/daemon-commands.js +208 -68
  17. package/dist/cli/data-command.js +62 -35
  18. package/dist/cli/index.js +11 -1
  19. package/dist/cli/init-channel.js +1 -1
  20. package/dist/cli/init.js +112 -17
  21. package/dist/cli/model.js +5 -5
  22. package/dist/cli/restart-monitor.js +102 -22
  23. package/dist/config/builtin-role-templates.js +4 -3
  24. package/dist/config/config-field-policy.js +6 -2
  25. package/dist/config/config-manager.js +79 -11
  26. package/dist/config/gateway-config.js +80 -35
  27. package/dist/config/role-schema.js +18 -3
  28. package/dist/config/role-service.js +3 -3
  29. package/dist/config/role-store.js +4 -3
  30. package/dist/config-store.js +19 -3
  31. package/dist/core/auth/operation-authorizer.js +3 -1
  32. package/dist/core/baseagent-loader.js +5 -3
  33. package/dist/core/bootstrap-service.js +0 -12
  34. package/dist/core/capability/providers/codex-capability-provider.js +2 -2
  35. package/dist/core/channel-loader.js +15 -2
  36. package/dist/core/command/command-handler.js +1 -1
  37. package/dist/core/command/evol-menu-version-gate.js +3 -2
  38. package/dist/core/command/menu-handler.js +50 -28
  39. package/dist/core/command/menu-protocol.js +7 -4
  40. package/dist/core/command/slash-handler.js +4 -4
  41. package/dist/core/data-migration.js +517 -24
  42. package/dist/core/inference/text-inference.js +18 -5
  43. package/dist/core/message/message-bridge.js +17 -6
  44. package/dist/core/message/response-engine.js +22 -3
  45. package/dist/core/model/config-scope.js +3 -3
  46. package/dist/core/permission/tool-policy.js +18 -0
  47. package/dist/core/protected-paths.js +12 -1
  48. package/dist/index.js +794 -725
  49. package/dist/ipc.js +3 -1
  50. package/dist/product.js +1 -0
  51. package/dist/utils/autostart.js +27 -0
  52. package/dist/utils/codex-cli.js +39 -0
  53. package/dist/utils/cross-platform.js +147 -18
  54. package/dist/utils/ecweb-utils.js +15 -2
  55. package/dist/utils/instance-registry.js +43 -6
  56. package/dist/utils/macos-autostart.js +179 -0
  57. package/dist/utils/process-introspect.js +7 -3
  58. package/dist/utils/windows-autostart.js +130 -0
  59. package/ecagent/dist/agent-loop.d.ts +1 -1
  60. package/ecagent/dist/agent-loop.js +1 -1
  61. package/ecagent/dist/agent.d.ts +1 -1
  62. package/ecagent/dist/agent.js +1 -1
  63. package/ecagent/dist/harness/agent-harness.d.ts +1 -1
  64. package/ecagent/dist/harness/compaction/branch-summarization.d.ts +1 -1
  65. package/ecagent/dist/harness/compaction/compaction.d.ts +1 -1
  66. package/ecagent/dist/harness/compaction/utils.d.ts +1 -1
  67. package/ecagent/dist/harness/messages.d.ts +1 -1
  68. package/ecagent/dist/harness/session/session.d.ts +1 -1
  69. package/ecagent/dist/harness/types.d.ts +1 -1
  70. package/ecagent/dist/proxy.d.ts +1 -1
  71. package/ecagent/dist/proxy.js +1 -1
  72. package/ecagent/dist/types.d.ts +1 -1
  73. package/kits/migrations/migrate-role-config-v5.mjs +27 -2
  74. package/kits/rules/01-overview.md +3 -2
  75. package/kits/schemas/_meta.json +2 -1
  76. package/kits/schemas/agent-config.schema.10.json +19 -1
  77. package/kits/schemas/daemon.schema.4.json +136 -0
  78. package/kits/schemas/defaults.schema.4.json +15 -1
  79. package/kits/schemas/relation-config.schema.8.json +22 -1
  80. package/kits/schemas/role-config.schema.1.json +2 -2
  81. package/package.json +2 -4
  82. package/ecagent/dist/agent-loop.d.ts.map +0 -1
  83. package/ecagent/dist/agent-loop.js.map +0 -1
  84. package/ecagent/dist/agent.d.ts.map +0 -1
  85. package/ecagent/dist/agent.js.map +0 -1
  86. package/ecagent/dist/harness/agent-harness.d.ts.map +0 -1
  87. package/ecagent/dist/harness/agent-harness.js.map +0 -1
  88. package/ecagent/dist/harness/compaction/branch-summarization.d.ts.map +0 -1
  89. package/ecagent/dist/harness/compaction/branch-summarization.js.map +0 -1
  90. package/ecagent/dist/harness/compaction/compaction.d.ts.map +0 -1
  91. package/ecagent/dist/harness/compaction/compaction.js.map +0 -1
  92. package/ecagent/dist/harness/compaction/utils.d.ts.map +0 -1
  93. package/ecagent/dist/harness/compaction/utils.js.map +0 -1
  94. package/ecagent/dist/harness/env/nodejs.d.ts.map +0 -1
  95. package/ecagent/dist/harness/env/nodejs.js.map +0 -1
  96. package/ecagent/dist/harness/messages.d.ts.map +0 -1
  97. package/ecagent/dist/harness/messages.js.map +0 -1
  98. package/ecagent/dist/harness/prompt-templates.d.ts.map +0 -1
  99. package/ecagent/dist/harness/prompt-templates.js.map +0 -1
  100. package/ecagent/dist/harness/session/jsonl-repo.d.ts.map +0 -1
  101. package/ecagent/dist/harness/session/jsonl-repo.js.map +0 -1
  102. package/ecagent/dist/harness/session/jsonl-storage.d.ts.map +0 -1
  103. package/ecagent/dist/harness/session/jsonl-storage.js.map +0 -1
  104. package/ecagent/dist/harness/session/memory-repo.d.ts.map +0 -1
  105. package/ecagent/dist/harness/session/memory-repo.js.map +0 -1
  106. package/ecagent/dist/harness/session/memory-storage.d.ts.map +0 -1
  107. package/ecagent/dist/harness/session/memory-storage.js.map +0 -1
  108. package/ecagent/dist/harness/session/repo-utils.d.ts.map +0 -1
  109. package/ecagent/dist/harness/session/repo-utils.js.map +0 -1
  110. package/ecagent/dist/harness/session/session.d.ts.map +0 -1
  111. package/ecagent/dist/harness/session/session.js.map +0 -1
  112. package/ecagent/dist/harness/session/uuid.d.ts.map +0 -1
  113. package/ecagent/dist/harness/session/uuid.js.map +0 -1
  114. package/ecagent/dist/harness/skills.d.ts.map +0 -1
  115. package/ecagent/dist/harness/skills.js.map +0 -1
  116. package/ecagent/dist/harness/system-prompt.d.ts.map +0 -1
  117. package/ecagent/dist/harness/system-prompt.js.map +0 -1
  118. package/ecagent/dist/harness/types.d.ts.map +0 -1
  119. package/ecagent/dist/harness/types.js.map +0 -1
  120. package/ecagent/dist/harness/utils/shell-output.d.ts.map +0 -1
  121. package/ecagent/dist/harness/utils/shell-output.js.map +0 -1
  122. package/ecagent/dist/harness/utils/truncate.d.ts.map +0 -1
  123. package/ecagent/dist/harness/utils/truncate.js.map +0 -1
  124. package/ecagent/dist/index.d.ts.map +0 -1
  125. package/ecagent/dist/index.js.map +0 -1
  126. package/ecagent/dist/node.d.ts.map +0 -1
  127. package/ecagent/dist/node.js.map +0 -1
  128. package/ecagent/dist/proxy.d.ts.map +0 -1
  129. package/ecagent/dist/proxy.js.map +0 -1
  130. package/ecagent/dist/runtime/api/lazy.d.ts.map +0 -1
  131. package/ecagent/dist/runtime/api/lazy.js.map +0 -1
  132. package/ecagent/dist/runtime/api/pi-messages.d.ts.map +0 -1
  133. package/ecagent/dist/runtime/api/pi-messages.js.map +0 -1
  134. package/ecagent/dist/runtime/api/pi-messages.lazy.d.ts.map +0 -1
  135. package/ecagent/dist/runtime/api/pi-messages.lazy.js.map +0 -1
  136. package/ecagent/dist/runtime/auth/context.d.ts.map +0 -1
  137. package/ecagent/dist/runtime/auth/context.js.map +0 -1
  138. package/ecagent/dist/runtime/auth/credential-store.d.ts.map +0 -1
  139. package/ecagent/dist/runtime/auth/credential-store.js.map +0 -1
  140. package/ecagent/dist/runtime/auth/helpers.d.ts.map +0 -1
  141. package/ecagent/dist/runtime/auth/helpers.js.map +0 -1
  142. package/ecagent/dist/runtime/auth/resolve.d.ts.map +0 -1
  143. package/ecagent/dist/runtime/auth/resolve.js.map +0 -1
  144. package/ecagent/dist/runtime/auth/types.d.ts.map +0 -1
  145. package/ecagent/dist/runtime/auth/types.js.map +0 -1
  146. package/ecagent/dist/runtime/compat.d.ts.map +0 -1
  147. package/ecagent/dist/runtime/compat.js.map +0 -1
  148. package/ecagent/dist/runtime/index.d.ts.map +0 -1
  149. package/ecagent/dist/runtime/index.js.map +0 -1
  150. package/ecagent/dist/runtime/models.d.ts.map +0 -1
  151. package/ecagent/dist/runtime/models.js.map +0 -1
  152. package/ecagent/dist/runtime/oauth.d.ts.map +0 -1
  153. package/ecagent/dist/runtime/oauth.js.map +0 -1
  154. package/ecagent/dist/runtime/providers/faux.d.ts.map +0 -1
  155. package/ecagent/dist/runtime/providers/faux.js.map +0 -1
  156. package/ecagent/dist/runtime/types.d.ts.map +0 -1
  157. package/ecagent/dist/runtime/types.js.map +0 -1
  158. package/ecagent/dist/runtime/utils/diagnostics.d.ts.map +0 -1
  159. package/ecagent/dist/runtime/utils/diagnostics.js.map +0 -1
  160. package/ecagent/dist/runtime/utils/event-stream.d.ts.map +0 -1
  161. package/ecagent/dist/runtime/utils/event-stream.js.map +0 -1
  162. package/ecagent/dist/runtime/utils/headers.d.ts.map +0 -1
  163. package/ecagent/dist/runtime/utils/headers.js.map +0 -1
  164. package/ecagent/dist/runtime/utils/json-parse.d.ts.map +0 -1
  165. package/ecagent/dist/runtime/utils/json-parse.js.map +0 -1
  166. package/ecagent/dist/runtime/utils/oauth/types.d.ts.map +0 -1
  167. package/ecagent/dist/runtime/utils/oauth/types.js.map +0 -1
  168. package/ecagent/dist/runtime/utils/overflow.d.ts.map +0 -1
  169. package/ecagent/dist/runtime/utils/overflow.js.map +0 -1
  170. package/ecagent/dist/runtime/utils/provider-env.d.ts.map +0 -1
  171. package/ecagent/dist/runtime/utils/provider-env.js.map +0 -1
  172. package/ecagent/dist/runtime/utils/retry.d.ts.map +0 -1
  173. package/ecagent/dist/runtime/utils/retry.js.map +0 -1
  174. package/ecagent/dist/runtime/utils/typebox-helpers.d.ts.map +0 -1
  175. package/ecagent/dist/runtime/utils/typebox-helpers.js.map +0 -1
  176. package/ecagent/dist/runtime/utils/validation.d.ts.map +0 -1
  177. package/ecagent/dist/runtime/utils/validation.js.map +0 -1
  178. package/ecagent/dist/types.d.ts.map +0 -1
  179. package/ecagent/dist/types.js.map +0 -1
  180. package/ecagent/package.json +0 -93
  181. package/ecagent/src/agent-loop.ts +0 -792
  182. package/ecagent/src/agent.ts +0 -575
  183. package/ecagent/src/harness/agent-harness.ts +0 -1029
  184. package/ecagent/src/harness/compaction/branch-summarization.ts +0 -261
  185. package/ecagent/src/harness/compaction/compaction.ts +0 -753
  186. package/ecagent/src/harness/compaction/utils.ts +0 -144
  187. package/ecagent/src/harness/env/nodejs.ts +0 -569
  188. package/ecagent/src/harness/messages.ts +0 -164
  189. package/ecagent/src/harness/prompt-templates.ts +0 -267
  190. package/ecagent/src/harness/session/jsonl-repo.ts +0 -179
  191. package/ecagent/src/harness/session/jsonl-storage.ts +0 -314
  192. package/ecagent/src/harness/session/memory-repo.ts +0 -50
  193. package/ecagent/src/harness/session/memory-storage.ts +0 -133
  194. package/ecagent/src/harness/session/repo-utils.ts +0 -51
  195. package/ecagent/src/harness/session/session.ts +0 -338
  196. package/ecagent/src/harness/session/uuid.ts +0 -54
  197. package/ecagent/src/harness/skills.ts +0 -375
  198. package/ecagent/src/harness/system-prompt.ts +0 -34
  199. package/ecagent/src/harness/types.ts +0 -838
  200. package/ecagent/src/harness/utils/shell-output.ts +0 -135
  201. package/ecagent/src/harness/utils/truncate.ts +0 -344
  202. package/ecagent/src/index.ts +0 -46
  203. package/ecagent/src/node.ts +0 -2
  204. package/ecagent/src/proxy.ts +0 -367
  205. package/ecagent/src/runtime/api/lazy.ts +0 -70
  206. package/ecagent/src/runtime/api/pi-messages.lazy.ts +0 -4
  207. package/ecagent/src/runtime/api/pi-messages.ts +0 -436
  208. package/ecagent/src/runtime/auth/context.ts +0 -45
  209. package/ecagent/src/runtime/auth/credential-store.ts +0 -47
  210. package/ecagent/src/runtime/auth/helpers.ts +0 -46
  211. package/ecagent/src/runtime/auth/resolve.ts +0 -141
  212. package/ecagent/src/runtime/auth/types.ts +0 -182
  213. package/ecagent/src/runtime/compat.ts +0 -158
  214. package/ecagent/src/runtime/index.ts +0 -31
  215. package/ecagent/src/runtime/models.ts +0 -452
  216. package/ecagent/src/runtime/oauth.ts +0 -1
  217. package/ecagent/src/runtime/providers/faux.ts +0 -538
  218. package/ecagent/src/runtime/types.ts +0 -718
  219. package/ecagent/src/runtime/utils/diagnostics.ts +0 -45
  220. package/ecagent/src/runtime/utils/event-stream.ts +0 -88
  221. package/ecagent/src/runtime/utils/headers.ts +0 -18
  222. package/ecagent/src/runtime/utils/json-parse.ts +0 -124
  223. package/ecagent/src/runtime/utils/oauth/types.ts +0 -79
  224. package/ecagent/src/runtime/utils/overflow.ts +0 -165
  225. package/ecagent/src/runtime/utils/provider-env.ts +0 -52
  226. package/ecagent/src/runtime/utils/retry.ts +0 -101
  227. package/ecagent/src/runtime/utils/typebox-helpers.ts +0 -24
  228. package/ecagent/src/runtime/utils/validation.ts +0 -310
  229. package/ecagent/src/types.ts +0 -430
  230. package/ecagent/tsconfig.build.json +0 -32
@@ -1,792 +0,0 @@
1
- /**
2
- * Agent loop that works with AgentMessage throughout.
3
- * Transforms to Message[] only at the LLM call boundary.
4
- */
5
-
6
- import {
7
- type AssistantMessage,
8
- type Context,
9
- EventStream,
10
- streamSimple,
11
- type ToolResultMessage,
12
- validateToolArguments,
13
- } from "ecagent/runtime/compat";
14
- import type {
15
- AgentContext,
16
- AgentEvent,
17
- AgentLoopConfig,
18
- AgentMessage,
19
- AgentTool,
20
- AgentToolCall,
21
- AgentToolResult,
22
- StreamFn,
23
- } from "./types.ts";
24
-
25
- export type AgentEventSink = (event: AgentEvent) => Promise<void> | void;
26
-
27
- /**
28
- * Start an agent loop with a new prompt message.
29
- * The prompt is added to the context and events are emitted for it.
30
- */
31
- export function agentLoop(
32
- prompts: AgentMessage[],
33
- context: AgentContext,
34
- config: AgentLoopConfig,
35
- signal?: AbortSignal,
36
- streamFn?: StreamFn,
37
- ): EventStream<AgentEvent, AgentMessage[]> {
38
- const stream = createAgentStream();
39
-
40
- void runAgentLoop(
41
- prompts,
42
- context,
43
- config,
44
- async (event) => {
45
- stream.push(event);
46
- },
47
- signal,
48
- streamFn,
49
- ).then((messages) => {
50
- stream.end(messages);
51
- });
52
-
53
- return stream;
54
- }
55
-
56
- /**
57
- * Continue an agent loop from the current context without adding a new message.
58
- * Used for retries - context already has user message or tool results.
59
- *
60
- * **Important:** The last message in context must convert to a `user` or `toolResult` message
61
- * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.
62
- * This cannot be validated here since `convertToLlm` is only called once per turn.
63
- */
64
- export function agentLoopContinue(
65
- context: AgentContext,
66
- config: AgentLoopConfig,
67
- signal?: AbortSignal,
68
- streamFn?: StreamFn,
69
- ): EventStream<AgentEvent, AgentMessage[]> {
70
- if (context.messages.length === 0) {
71
- throw new Error("Cannot continue: no messages in context");
72
- }
73
-
74
- if (context.messages[context.messages.length - 1].role === "assistant") {
75
- throw new Error("Cannot continue from message role: assistant");
76
- }
77
-
78
- const stream = createAgentStream();
79
-
80
- void runAgentLoopContinue(
81
- context,
82
- config,
83
- async (event) => {
84
- stream.push(event);
85
- },
86
- signal,
87
- streamFn,
88
- ).then((messages) => {
89
- stream.end(messages);
90
- });
91
-
92
- return stream;
93
- }
94
-
95
- export async function runAgentLoop(
96
- prompts: AgentMessage[],
97
- context: AgentContext,
98
- config: AgentLoopConfig,
99
- emit: AgentEventSink,
100
- signal?: AbortSignal,
101
- streamFn?: StreamFn,
102
- ): Promise<AgentMessage[]> {
103
- const newMessages: AgentMessage[] = [...prompts];
104
- const currentContext: AgentContext = {
105
- ...context,
106
- messages: [...context.messages, ...prompts],
107
- };
108
-
109
- await emit({ type: "agent_start" });
110
- await emit({ type: "turn_start" });
111
- for (const prompt of prompts) {
112
- await emit({ type: "message_start", message: prompt });
113
- await emit({ type: "message_end", message: prompt });
114
- }
115
-
116
- await runLoop(currentContext, newMessages, config, signal, emit, streamFn);
117
- return newMessages;
118
- }
119
-
120
- export async function runAgentLoopContinue(
121
- context: AgentContext,
122
- config: AgentLoopConfig,
123
- emit: AgentEventSink,
124
- signal?: AbortSignal,
125
- streamFn?: StreamFn,
126
- ): Promise<AgentMessage[]> {
127
- if (context.messages.length === 0) {
128
- throw new Error("Cannot continue: no messages in context");
129
- }
130
-
131
- if (context.messages[context.messages.length - 1].role === "assistant") {
132
- throw new Error("Cannot continue from message role: assistant");
133
- }
134
-
135
- const newMessages: AgentMessage[] = [];
136
- const currentContext: AgentContext = { ...context };
137
-
138
- await emit({ type: "agent_start" });
139
- await emit({ type: "turn_start" });
140
-
141
- await runLoop(currentContext, newMessages, config, signal, emit, streamFn);
142
- return newMessages;
143
- }
144
-
145
- function createAgentStream(): EventStream<AgentEvent, AgentMessage[]> {
146
- return new EventStream<AgentEvent, AgentMessage[]>(
147
- (event: AgentEvent) => event.type === "agent_end",
148
- (event: AgentEvent) => (event.type === "agent_end" ? event.messages : []),
149
- );
150
- }
151
-
152
- /**
153
- * Main loop logic shared by agentLoop and agentLoopContinue.
154
- */
155
- async function runLoop(
156
- initialContext: AgentContext,
157
- newMessages: AgentMessage[],
158
- initialConfig: AgentLoopConfig,
159
- signal: AbortSignal | undefined,
160
- emit: AgentEventSink,
161
- streamFn?: StreamFn,
162
- ): Promise<void> {
163
- let currentContext = initialContext;
164
- let config = initialConfig;
165
- let firstTurn = true;
166
- // Check for steering messages at start (user may have typed while waiting)
167
- let pendingMessages: AgentMessage[] = (await config.getSteeringMessages?.()) || [];
168
-
169
- // Outer loop: continues when queued follow-up messages arrive after agent would stop
170
- while (true) {
171
- let hasMoreToolCalls = true;
172
-
173
- // Inner loop: process tool calls and steering messages
174
- while (hasMoreToolCalls || pendingMessages.length > 0) {
175
- if (!firstTurn) {
176
- await emit({ type: "turn_start" });
177
- } else {
178
- firstTurn = false;
179
- }
180
-
181
- // Process pending messages (inject before next assistant response)
182
- if (pendingMessages.length > 0) {
183
- for (const message of pendingMessages) {
184
- await emit({ type: "message_start", message });
185
- await emit({ type: "message_end", message });
186
- currentContext.messages.push(message);
187
- newMessages.push(message);
188
- }
189
- pendingMessages = [];
190
- }
191
-
192
- // Stream assistant response
193
- const message = await streamAssistantResponse(currentContext, config, signal, emit, streamFn);
194
- newMessages.push(message);
195
-
196
- if (message.stopReason === "error" || message.stopReason === "aborted") {
197
- await emit({ type: "turn_end", message, toolResults: [] });
198
- await emit({ type: "agent_end", messages: newMessages });
199
- return;
200
- }
201
-
202
- // Check for tool calls
203
- const toolCalls = message.content.filter((c) => c.type === "toolCall");
204
-
205
- const toolResults: ToolResultMessage[] = [];
206
- hasMoreToolCalls = false;
207
- if (toolCalls.length > 0) {
208
- // A "length" stop means the output was cut off by the token limit, so
209
- // every tool call in the message may carry truncated arguments. Fail
210
- // them all instead of executing potentially borked calls.
211
- const executedToolBatch =
212
- message.stopReason === "length"
213
- ? await failToolCallsFromTruncatedMessage(toolCalls, emit)
214
- : await executeToolCalls(currentContext, message, config, signal, emit);
215
- toolResults.push(...executedToolBatch.messages);
216
- hasMoreToolCalls = !executedToolBatch.terminate;
217
-
218
- for (const result of toolResults) {
219
- currentContext.messages.push(result);
220
- newMessages.push(result);
221
- }
222
- }
223
-
224
- await emit({ type: "turn_end", message, toolResults });
225
-
226
- const nextTurnContext = {
227
- message,
228
- toolResults,
229
- context: currentContext,
230
- newMessages,
231
- };
232
- const nextTurnSnapshot = await config.prepareNextTurn?.(nextTurnContext);
233
- if (nextTurnSnapshot) {
234
- currentContext = nextTurnSnapshot.context ?? currentContext;
235
- config = {
236
- ...config,
237
- model: nextTurnSnapshot.model ?? config.model,
238
- reasoning:
239
- nextTurnSnapshot.thinkingLevel === undefined
240
- ? config.reasoning
241
- : nextTurnSnapshot.thinkingLevel === "off"
242
- ? undefined
243
- : nextTurnSnapshot.thinkingLevel,
244
- };
245
- }
246
-
247
- if (
248
- await config.shouldStopAfterTurn?.({
249
- message,
250
- toolResults,
251
- context: currentContext,
252
- newMessages,
253
- })
254
- ) {
255
- await emit({ type: "agent_end", messages: newMessages });
256
- return;
257
- }
258
-
259
- pendingMessages = (await config.getSteeringMessages?.()) || [];
260
- }
261
-
262
- // Agent would stop here. Check for follow-up messages.
263
- const followUpMessages = (await config.getFollowUpMessages?.()) || [];
264
- if (followUpMessages.length > 0) {
265
- // Set as pending so inner loop processes them
266
- pendingMessages = followUpMessages;
267
- continue;
268
- }
269
-
270
- // No more messages, exit
271
- break;
272
- }
273
-
274
- await emit({ type: "agent_end", messages: newMessages });
275
- }
276
-
277
- /**
278
- * Stream an assistant response from the LLM.
279
- * This is where AgentMessage[] gets transformed to Message[] for the LLM.
280
- */
281
- async function streamAssistantResponse(
282
- context: AgentContext,
283
- config: AgentLoopConfig,
284
- signal: AbortSignal | undefined,
285
- emit: AgentEventSink,
286
- streamFn?: StreamFn,
287
- ): Promise<AssistantMessage> {
288
- // Apply context transform if configured (AgentMessage[] → AgentMessage[])
289
- let messages = context.messages;
290
- if (config.transformContext) {
291
- messages = await config.transformContext(messages, signal);
292
- }
293
-
294
- // Convert to LLM-compatible messages (AgentMessage[] → Message[])
295
- const llmMessages = await config.convertToLlm(messages);
296
-
297
- // Build LLM context
298
- const llmContext: Context = {
299
- systemPrompt: context.systemPrompt,
300
- messages: llmMessages,
301
- tools: context.tools,
302
- };
303
-
304
- const streamFunction = streamFn || streamSimple;
305
-
306
- // Resolve API key (important for expiring tokens)
307
- const resolvedApiKey =
308
- (config.getApiKey ? await config.getApiKey(config.model.provider) : undefined) || config.apiKey;
309
-
310
- const response = await streamFunction(config.model, llmContext, {
311
- ...config,
312
- apiKey: resolvedApiKey,
313
- signal,
314
- });
315
-
316
- let partialMessage: AssistantMessage | null = null;
317
- let addedPartial = false;
318
-
319
- for await (const event of response) {
320
- switch (event.type) {
321
- case "start":
322
- partialMessage = event.partial;
323
- context.messages.push(partialMessage);
324
- addedPartial = true;
325
- await emit({ type: "message_start", message: { ...partialMessage } });
326
- break;
327
-
328
- case "text_start":
329
- case "text_delta":
330
- case "text_end":
331
- case "thinking_start":
332
- case "thinking_delta":
333
- case "thinking_end":
334
- case "toolcall_start":
335
- case "toolcall_delta":
336
- case "toolcall_end":
337
- if (partialMessage) {
338
- partialMessage = event.partial;
339
- context.messages[context.messages.length - 1] = partialMessage;
340
- await emit({
341
- type: "message_update",
342
- assistantMessageEvent: event,
343
- message: { ...partialMessage },
344
- });
345
- }
346
- break;
347
-
348
- case "done":
349
- case "error": {
350
- const finalMessage = await response.result();
351
- if (addedPartial) {
352
- context.messages[context.messages.length - 1] = finalMessage;
353
- } else {
354
- context.messages.push(finalMessage);
355
- }
356
- if (!addedPartial) {
357
- await emit({ type: "message_start", message: { ...finalMessage } });
358
- }
359
- await emit({ type: "message_end", message: finalMessage });
360
- return finalMessage;
361
- }
362
- }
363
- }
364
-
365
- const finalMessage = await response.result();
366
- if (addedPartial) {
367
- context.messages[context.messages.length - 1] = finalMessage;
368
- } else {
369
- context.messages.push(finalMessage);
370
- await emit({ type: "message_start", message: { ...finalMessage } });
371
- }
372
- await emit({ type: "message_end", message: finalMessage });
373
- return finalMessage;
374
- }
375
-
376
- /**
377
- * Fail all tool calls from an assistant message that was truncated by the
378
- * output token limit. Streamed tool-call arguments are finalized with a
379
- * best-effort JSON salvage parser, so a truncated message can yield tool calls
380
- * whose arguments parse and validate but are silently incomplete. None of them
381
- * are safe to execute; report each as an error so the model can re-issue them.
382
- */
383
- async function failToolCallsFromTruncatedMessage(
384
- toolCalls: AgentToolCall[],
385
- emit: AgentEventSink,
386
- ): Promise<ExecutedToolCallBatch> {
387
- const messages: ToolResultMessage[] = [];
388
- for (const toolCall of toolCalls) {
389
- await emit({
390
- type: "tool_execution_start",
391
- toolCallId: toolCall.id,
392
- toolName: toolCall.name,
393
- args: toolCall.arguments,
394
- });
395
- const finalized: FinalizedToolCallOutcome = {
396
- toolCall,
397
- result: createErrorToolResult(
398
- `Tool call "${toolCall.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`,
399
- ),
400
- isError: true,
401
- };
402
- await emitToolExecutionEnd(finalized, emit);
403
- const toolResultMessage = createToolResultMessage(finalized);
404
- await emitToolResultMessage(toolResultMessage, emit);
405
- messages.push(toolResultMessage);
406
- }
407
- return { messages, terminate: false };
408
- }
409
-
410
- /**
411
- * Execute tool calls from an assistant message.
412
- */
413
- async function executeToolCalls(
414
- currentContext: AgentContext,
415
- assistantMessage: AssistantMessage,
416
- config: AgentLoopConfig,
417
- signal: AbortSignal | undefined,
418
- emit: AgentEventSink,
419
- ): Promise<ExecutedToolCallBatch> {
420
- const toolCalls = assistantMessage.content.filter((c) => c.type === "toolCall");
421
- const hasSequentialToolCall = toolCalls.some(
422
- (tc) => currentContext.tools?.find((t) => t.name === tc.name)?.executionMode === "sequential",
423
- );
424
- if (config.toolExecution === "sequential" || hasSequentialToolCall) {
425
- return executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, signal, emit);
426
- }
427
- return executeToolCallsParallel(currentContext, assistantMessage, toolCalls, config, signal, emit);
428
- }
429
-
430
- type ExecutedToolCallBatch = {
431
- messages: ToolResultMessage[];
432
- terminate: boolean;
433
- };
434
-
435
- async function executeToolCallsSequential(
436
- currentContext: AgentContext,
437
- assistantMessage: AssistantMessage,
438
- toolCalls: AgentToolCall[],
439
- config: AgentLoopConfig,
440
- signal: AbortSignal | undefined,
441
- emit: AgentEventSink,
442
- ): Promise<ExecutedToolCallBatch> {
443
- const finalizedCalls: FinalizedToolCallOutcome[] = [];
444
- const messages: ToolResultMessage[] = [];
445
-
446
- for (const toolCall of toolCalls) {
447
- await emit({
448
- type: "tool_execution_start",
449
- toolCallId: toolCall.id,
450
- toolName: toolCall.name,
451
- args: toolCall.arguments,
452
- });
453
-
454
- const preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);
455
- let finalized: FinalizedToolCallOutcome;
456
- if (preparation.kind === "immediate") {
457
- finalized = {
458
- toolCall,
459
- result: preparation.result,
460
- isError: preparation.isError,
461
- };
462
- } else {
463
- const executed = await executePreparedToolCall(preparation, signal, emit);
464
- finalized = await finalizeExecutedToolCall(
465
- currentContext,
466
- assistantMessage,
467
- preparation,
468
- executed,
469
- config,
470
- signal,
471
- );
472
- }
473
-
474
- await emitToolExecutionEnd(finalized, emit);
475
- const toolResultMessage = createToolResultMessage(finalized);
476
- await emitToolResultMessage(toolResultMessage, emit);
477
- finalizedCalls.push(finalized);
478
- messages.push(toolResultMessage);
479
-
480
- if (signal?.aborted) {
481
- break;
482
- }
483
- }
484
-
485
- return {
486
- messages,
487
- terminate: shouldTerminateToolBatch(finalizedCalls),
488
- };
489
- }
490
-
491
- async function executeToolCallsParallel(
492
- currentContext: AgentContext,
493
- assistantMessage: AssistantMessage,
494
- toolCalls: AgentToolCall[],
495
- config: AgentLoopConfig,
496
- signal: AbortSignal | undefined,
497
- emit: AgentEventSink,
498
- ): Promise<ExecutedToolCallBatch> {
499
- const finalizedCalls: FinalizedToolCallEntry[] = [];
500
-
501
- for (const toolCall of toolCalls) {
502
- await emit({
503
- type: "tool_execution_start",
504
- toolCallId: toolCall.id,
505
- toolName: toolCall.name,
506
- args: toolCall.arguments,
507
- });
508
-
509
- const preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);
510
- if (preparation.kind === "immediate") {
511
- const finalized = {
512
- toolCall,
513
- result: preparation.result,
514
- isError: preparation.isError,
515
- } satisfies FinalizedToolCallOutcome;
516
- await emitToolExecutionEnd(finalized, emit);
517
- finalizedCalls.push(finalized);
518
- if (signal?.aborted) {
519
- break;
520
- }
521
- continue;
522
- }
523
-
524
- finalizedCalls.push(async () => {
525
- const executed = await executePreparedToolCall(preparation, signal, emit);
526
- const finalized = await finalizeExecutedToolCall(
527
- currentContext,
528
- assistantMessage,
529
- preparation,
530
- executed,
531
- config,
532
- signal,
533
- );
534
- await emitToolExecutionEnd(finalized, emit);
535
- return finalized;
536
- });
537
- if (signal?.aborted) {
538
- break;
539
- }
540
- }
541
-
542
- const orderedFinalizedCalls = await Promise.all(
543
- finalizedCalls.map((entry) => (typeof entry === "function" ? entry() : Promise.resolve(entry))),
544
- );
545
- const messages: ToolResultMessage[] = [];
546
- for (const finalized of orderedFinalizedCalls) {
547
- const toolResultMessage = createToolResultMessage(finalized);
548
- await emitToolResultMessage(toolResultMessage, emit);
549
- messages.push(toolResultMessage);
550
- }
551
-
552
- return {
553
- messages,
554
- terminate: shouldTerminateToolBatch(orderedFinalizedCalls),
555
- };
556
- }
557
-
558
- type PreparedToolCall = {
559
- kind: "prepared";
560
- toolCall: AgentToolCall;
561
- tool: AgentTool<any>;
562
- args: unknown;
563
- };
564
-
565
- type ImmediateToolCallOutcome = {
566
- kind: "immediate";
567
- result: AgentToolResult<any>;
568
- isError: boolean;
569
- };
570
-
571
- type ExecutedToolCallOutcome = {
572
- result: AgentToolResult<any>;
573
- isError: boolean;
574
- };
575
-
576
- type FinalizedToolCallOutcome = {
577
- toolCall: AgentToolCall;
578
- result: AgentToolResult<any>;
579
- isError: boolean;
580
- };
581
-
582
- type FinalizedToolCallEntry = FinalizedToolCallOutcome | (() => Promise<FinalizedToolCallOutcome>);
583
-
584
- function shouldTerminateToolBatch(finalizedCalls: FinalizedToolCallOutcome[]): boolean {
585
- return finalizedCalls.length > 0 && finalizedCalls.every((finalized) => finalized.result.terminate === true);
586
- }
587
-
588
- function prepareToolCallArguments(tool: AgentTool<any>, toolCall: AgentToolCall): AgentToolCall {
589
- if (!tool.prepareArguments) {
590
- return toolCall;
591
- }
592
- const preparedArguments = tool.prepareArguments(toolCall.arguments);
593
- if (preparedArguments === toolCall.arguments) {
594
- return toolCall;
595
- }
596
- return {
597
- ...toolCall,
598
- arguments: preparedArguments as Record<string, any>,
599
- };
600
- }
601
-
602
- async function prepareToolCall(
603
- currentContext: AgentContext,
604
- assistantMessage: AssistantMessage,
605
- toolCall: AgentToolCall,
606
- config: AgentLoopConfig,
607
- signal: AbortSignal | undefined,
608
- ): Promise<PreparedToolCall | ImmediateToolCallOutcome> {
609
- const tool = currentContext.tools?.find((t) => t.name === toolCall.name);
610
- if (!tool) {
611
- return {
612
- kind: "immediate",
613
- result: createErrorToolResult(`Tool ${toolCall.name} not found`),
614
- isError: true,
615
- };
616
- }
617
-
618
- try {
619
- const preparedToolCall = prepareToolCallArguments(tool, toolCall);
620
- const validatedArgs = validateToolArguments(tool, preparedToolCall);
621
- if (config.beforeToolCall) {
622
- const beforeResult = await config.beforeToolCall(
623
- {
624
- assistantMessage,
625
- toolCall,
626
- args: validatedArgs,
627
- context: currentContext,
628
- },
629
- signal,
630
- );
631
- if (signal?.aborted) {
632
- return {
633
- kind: "immediate",
634
- result: createErrorToolResult("Operation aborted"),
635
- isError: true,
636
- };
637
- }
638
- if (beforeResult?.block) {
639
- return {
640
- kind: "immediate",
641
- result: createErrorToolResult(beforeResult.reason || "Tool execution was blocked"),
642
- isError: true,
643
- };
644
- }
645
- }
646
- if (signal?.aborted) {
647
- return {
648
- kind: "immediate",
649
- result: createErrorToolResult("Operation aborted"),
650
- isError: true,
651
- };
652
- }
653
- return {
654
- kind: "prepared",
655
- toolCall,
656
- tool,
657
- args: validatedArgs,
658
- };
659
- } catch (error) {
660
- return {
661
- kind: "immediate",
662
- result: createErrorToolResult(error instanceof Error ? error.message : String(error)),
663
- isError: true,
664
- };
665
- }
666
- }
667
-
668
- async function executePreparedToolCall(
669
- prepared: PreparedToolCall,
670
- signal: AbortSignal | undefined,
671
- emit: AgentEventSink,
672
- ): Promise<ExecutedToolCallOutcome> {
673
- const updateEvents: Promise<void>[] = [];
674
- let acceptingUpdates = true;
675
-
676
- try {
677
- const result = await prepared.tool.execute(
678
- prepared.toolCall.id,
679
- prepared.args as never,
680
- signal,
681
- (partialResult) => {
682
- if (!acceptingUpdates) return;
683
- updateEvents.push(
684
- Promise.resolve(
685
- emit({
686
- type: "tool_execution_update",
687
- toolCallId: prepared.toolCall.id,
688
- toolName: prepared.toolCall.name,
689
- args: prepared.toolCall.arguments,
690
- partialResult,
691
- }),
692
- ),
693
- );
694
- },
695
- );
696
- acceptingUpdates = false;
697
- await Promise.all(updateEvents);
698
- return { result, isError: false };
699
- } catch (error) {
700
- acceptingUpdates = false;
701
- await Promise.all(updateEvents);
702
- return {
703
- result: createErrorToolResult(error instanceof Error ? error.message : String(error)),
704
- isError: true,
705
- };
706
- } finally {
707
- acceptingUpdates = false;
708
- }
709
- }
710
-
711
- async function finalizeExecutedToolCall(
712
- currentContext: AgentContext,
713
- assistantMessage: AssistantMessage,
714
- prepared: PreparedToolCall,
715
- executed: ExecutedToolCallOutcome,
716
- config: AgentLoopConfig,
717
- signal: AbortSignal | undefined,
718
- ): Promise<FinalizedToolCallOutcome> {
719
- let result = executed.result;
720
- let isError = executed.isError;
721
-
722
- if (config.afterToolCall) {
723
- try {
724
- const afterResult = await config.afterToolCall(
725
- {
726
- assistantMessage,
727
- toolCall: prepared.toolCall,
728
- args: prepared.args,
729
- result,
730
- isError,
731
- context: currentContext,
732
- },
733
- signal,
734
- );
735
- if (afterResult) {
736
- result = {
737
- ...result,
738
- content: afterResult.content ?? result.content,
739
- details: afterResult.details ?? result.details,
740
- terminate: afterResult.terminate ?? result.terminate,
741
- };
742
- isError = afterResult.isError ?? isError;
743
- }
744
- } catch (error) {
745
- result = createErrorToolResult(error instanceof Error ? error.message : String(error));
746
- isError = true;
747
- }
748
- }
749
-
750
- return {
751
- toolCall: prepared.toolCall,
752
- result,
753
- isError,
754
- };
755
- }
756
-
757
- function createErrorToolResult(message: string): AgentToolResult<any> {
758
- return {
759
- content: [{ type: "text", text: message }],
760
- details: {},
761
- };
762
- }
763
-
764
- async function emitToolExecutionEnd(finalized: FinalizedToolCallOutcome, emit: AgentEventSink): Promise<void> {
765
- await emit({
766
- type: "tool_execution_end",
767
- toolCallId: finalized.toolCall.id,
768
- toolName: finalized.toolCall.name,
769
- result: finalized.result,
770
- isError: finalized.isError,
771
- });
772
- }
773
-
774
- function createToolResultMessage(finalized: FinalizedToolCallOutcome): ToolResultMessage {
775
- return {
776
- role: "toolResult",
777
- toolCallId: finalized.toolCall.id,
778
- toolName: finalized.toolCall.name,
779
- // Untyped tools (JS extensions) can return results without content; normalize
780
- // so the null never enters session history or provider payloads.
781
- content: finalized.result.content ?? [],
782
- details: finalized.result.details,
783
- ...(finalized.result.addedToolNames?.length ? { addedToolNames: finalized.result.addedToolNames } : {}),
784
- isError: finalized.isError,
785
- timestamp: Date.now(),
786
- };
787
- }
788
-
789
- async function emitToolResultMessage(toolResultMessage: ToolResultMessage, emit: AgentEventSink): Promise<void> {
790
- await emit({ type: "message_start", message: toolResultMessage });
791
- await emit({ type: "message_end", message: toolResultMessage });
792
- }