@johnhenry/browsermesh-apps 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +443 -1
- package/package.json +18 -3
- package/src/agent-runtime.mjs +342 -0
- package/src/chunk-replication.mjs +751 -0
- package/src/cloud-storage-backend.mjs +932 -0
- package/src/cloud-storage.mjs +799 -0
- package/src/compat.mjs +98 -0
- package/src/gpu-kernel.mjs +242 -0
- package/src/gpu.mjs +101 -7
- package/src/grant-log.mjs +840 -0
- package/src/index.mjs +32 -2
- package/src/kernel-mesh.mjs +56 -0
- package/src/key-distribution.mjs +525 -0
- package/src/manifest-sync.mjs +363 -0
- package/src/mesh-agent-swarm.mjs +376 -0
- package/src/mesh-bootstrap.mjs +1481 -0
- package/src/mesh-compute.mjs +397 -0
- package/src/mesh-dht.mjs +182 -0
- package/src/mesh-fetch.mjs +246 -0
- package/src/mesh-hardening.mjs +226 -0
- package/src/mesh-health.mjs +282 -0
- package/src/mesh-keepalive.mjs +353 -0
- package/src/mesh-kv.mjs +673 -0
- package/src/mesh-orchestrator-tools.mjs +251 -0
- package/src/mesh-orchestrator.mjs +343 -0
- package/src/mesh-relay-backend.mjs +289 -0
- package/src/mesh-relay-host.mjs +362 -0
- package/src/mesh-rpc.mjs +300 -0
- package/src/mesh-service.mjs +403 -0
- package/src/mesh-swarm.mjs +677 -0
- package/src/mesh-sync.mjs +253 -0
- package/src/mesh-timestamp.mjs +265 -0
- package/src/mesh-torrent.mjs +683 -0
- package/src/mesh-verification.mjs +367 -0
- package/src/mesh-websocket.mjs +722 -0
- package/src/observability-bridge.mjs +453 -0
- package/src/orchestrator.mjs +18 -5
- package/src/peer-agent-swarm.mjs +12 -1
- package/src/peer-chat.mjs +230 -61
- package/src/peer-compute.mjs +66 -3
- package/src/peer-escrow.mjs +350 -1
- package/src/peer-files.mjs +362 -168
- package/src/peer-ipfs.mjs +205 -10
- package/src/peer-node.mjs +127 -19
- package/src/peer-registry.mjs +242 -18
- package/src/peer-routing.mjs +369 -5
- package/src/peer-terminal.mjs +400 -130
- package/src/signaling.mjs +231 -0
- package/src/webrtc-negotiator.mjs +209 -0
- package/src/peer-session.mjs +0 -937
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agent-runtime.mjs -- Phase 2 of the agent tool-calling runtime plan (issue
|
|
3
|
+
* #90): the tool-dispatch conversation loop that sits on top of Phase 1's
|
|
4
|
+
* `BrowserToolRegistry` (`compat.mjs`, PR #141).
|
|
5
|
+
*
|
|
6
|
+
* This is NOT a `MeshService` -- it never touches `PeerNode`, `attach()`, or
|
|
7
|
+
* `ctx`. It is a standalone composition-root utility, the same category as
|
|
8
|
+
* `cloud-storage.mjs`'s `CloudStorage` class: a caller constructs it directly
|
|
9
|
+
* (typically once per conversation/session) and drives it with `.run()`. No
|
|
10
|
+
* mesh wiring happens here at all -- if a tool's `.execute()` needs to reach
|
|
11
|
+
* a peer, that's the tool's own business (see e.g. `orchestrator.mjs`'s
|
|
12
|
+
* `Meshctl*Tool`s, wired to a real `MeshOrchestrator` in Phase 3/4).
|
|
13
|
+
*
|
|
14
|
+
* ---------------------------------------------------------------------------
|
|
15
|
+
* REQUIRED DEPENDENCIES -- `registry` AND `llmFn`, BOTH CHECKED HERE DIRECTLY
|
|
16
|
+
*
|
|
17
|
+
* Matches the "bring-your-own executor, required, no default shipped"
|
|
18
|
+
* pattern `mesh-compute.mjs`'s `executeFn` and `mesh-agent-swarm.mjs`'s
|
|
19
|
+
* `agentProxy` already established (issue #86's resolved design pass) --
|
|
20
|
+
* `createAgentSwarmService()` throws immediately, before constructing
|
|
21
|
+
* anything, if `agentProxy` is missing; this file does the same for both of
|
|
22
|
+
* its own required collaborators:
|
|
23
|
+
*
|
|
24
|
+
* - `registry` -- a `BrowserToolRegistry` instance (`compat.mjs`, Phase 1).
|
|
25
|
+
* Duck-typed (`.listSpecs`/`.get` both functions) rather than
|
|
26
|
+
* `instanceof`-checked, for the same cross-package "standalone use"
|
|
27
|
+
* reason `BrowserToolRegistry.register()` itself duck-types its
|
|
28
|
+
* argument -- this package vendors its own copy of `BrowserTool`/
|
|
29
|
+
* `BrowserToolRegistry` (see `compat.mjs`'s header), so a registry built
|
|
30
|
+
* against `browsermesh-core`'s copy is not `instanceof`
|
|
31
|
+
* `browsermesh-apps`'s class even though it has the identical shape.
|
|
32
|
+
* - `llmFn` -- REQUIRED, no default implementation is provided by this
|
|
33
|
+
* file or this package. browsermesh never takes a dependency on a
|
|
34
|
+
* specific LLM vendor's SDK (see the agent-runtime plan's "Context"
|
|
35
|
+
* section) -- the runtime provides the real tool-registry/dispatch loop;
|
|
36
|
+
* the caller supplies the actual "ask an LLM what to do next" step.
|
|
37
|
+
*
|
|
38
|
+
* ---------------------------------------------------------------------------
|
|
39
|
+
* THE `llmFn` SHAPE -- `async llmFn(messages, toolSpecs) -> { content?, toolCalls? }`
|
|
40
|
+
*
|
|
41
|
+
* - `messages` -- the full running conversation so far, an array of
|
|
42
|
+
* `{ role, ... }` entries (see "MESSAGE SHAPES" below for the exact
|
|
43
|
+
* entries this file appends).
|
|
44
|
+
* - `toolSpecs` -- `registry.listSpecs()`, i.e. every registered tool's
|
|
45
|
+
* `.spec` (`{ name, description, parameters, required_permission }`,
|
|
46
|
+
* see `compat.mjs`'s `BrowserTool.spec` getter) -- this is what `llmFn`
|
|
47
|
+
* hands to whatever real LLM API it wraps as that API's tool/function
|
|
48
|
+
* definitions.
|
|
49
|
+
* - Return value: `{ content?: string, toolCalls?: [{ id, name, arguments }] }`.
|
|
50
|
+
* - `toolCalls` present and non-empty -- the LLM wants to invoke one or
|
|
51
|
+
* more tools before answering; `run()` dispatches each one (see
|
|
52
|
+
* "DISPATCH" below) and calls `llmFn` again with the results appended.
|
|
53
|
+
* - `toolCalls` absent/empty and `content` present -- treated as the
|
|
54
|
+
* final answer; `run()` returns it and stops.
|
|
55
|
+
* - `llmFn` may legitimately need several `await`s of its own (an HTTP
|
|
56
|
+
* call, retries, etc.) -- that is entirely its own business; this
|
|
57
|
+
* loop just awaits whatever it returns.
|
|
58
|
+
*
|
|
59
|
+
* WORKED EXAMPLE -- wrapping a real LLM API's tool-calling response format.
|
|
60
|
+
* No real network call is made here; this shows only the shape translation
|
|
61
|
+
* an `llmFn` implementation is responsible for, both directions:
|
|
62
|
+
*
|
|
63
|
+
* ```js
|
|
64
|
+
* import { createAgentRuntime } from '@johnhenry/browsermesh-apps';
|
|
65
|
+
*
|
|
66
|
+
* // Suppose `realClient.chat(...)` is a real LLM SDK's chat-completion call
|
|
67
|
+
* // and it returns messages shaped like:
|
|
68
|
+
* // { role: 'assistant',
|
|
69
|
+
* // content: [
|
|
70
|
+
* // { type: 'text', text: 'Let me check that for you.' },
|
|
71
|
+
* // { type: 'tool_use', id: 'call_1', name: 'dht_lookup', input: { key: 'foo' } },
|
|
72
|
+
* // ] }
|
|
73
|
+
* // (a content-block style, e.g. Anthropic's Messages API shape) -- OR,
|
|
74
|
+
* // for a flatter OpenAI-style API:
|
|
75
|
+
* // { role: 'assistant', content: null,
|
|
76
|
+
* // tool_calls: [{ id: 'call_1', function: { name: 'dht_lookup', arguments: '{"key":"foo"}' } }] }
|
|
77
|
+
*
|
|
78
|
+
* async function llmFn(messages, toolSpecs) {
|
|
79
|
+
* // 1. Translate `toolSpecs` ({name, description, parameters,
|
|
80
|
+
* // required_permission}) into the vendor's own tool-definition shape.
|
|
81
|
+
* // Most vendor APIs want {name, description, input_schema/parameters}
|
|
82
|
+
* // -- `required_permission` is browsermesh-specific and has no vendor
|
|
83
|
+
* // equivalent, so it's simply dropped here (or kept out-of-band for
|
|
84
|
+
* // the caller's own policy layer -- see `checkAccess()` precedent in
|
|
85
|
+
* // mesh-compute.mjs/mesh-agent-swarm.mjs for where that belongs).
|
|
86
|
+
* const vendorTools = toolSpecs.map(({ name, description, parameters }) => (
|
|
87
|
+
* { name, description, input_schema: parameters }
|
|
88
|
+
* ));
|
|
89
|
+
*
|
|
90
|
+
* // 2. Translate `messages` (see "MESSAGE SHAPES" below) into the
|
|
91
|
+
* // vendor's own conversation format. Exactly how depends on the
|
|
92
|
+
* // vendor; sketched here rather than fully implemented.
|
|
93
|
+
* const vendorMessages = messages.map(toVendorMessage);
|
|
94
|
+
*
|
|
95
|
+
* // const response = await realClient.chat({ messages: vendorMessages, tools: vendorTools });
|
|
96
|
+
* const response = { role: 'assistant', content: [
|
|
97
|
+
* { type: 'text', text: 'Let me check that for you.' },
|
|
98
|
+
* { type: 'tool_use', id: 'call_1', name: 'dht_lookup', input: { key: 'foo' } },
|
|
99
|
+
* ] }; // stand-in for the real API call
|
|
100
|
+
*
|
|
101
|
+
* // 3. Translate the vendor's response back into this file's
|
|
102
|
+
* // {content?, toolCalls?} shape.
|
|
103
|
+
* const textBlocks = response.content.filter((b) => b.type === 'text');
|
|
104
|
+
* const toolUseBlocks = response.content.filter((b) => b.type === 'tool_use');
|
|
105
|
+
* return {
|
|
106
|
+
* content: textBlocks.length ? textBlocks.map((b) => b.text).join('') : undefined,
|
|
107
|
+
* toolCalls: toolUseBlocks.length
|
|
108
|
+
* ? toolUseBlocks.map((b) => ({ id: b.id, name: b.name, arguments: b.input }))
|
|
109
|
+
* : undefined,
|
|
110
|
+
* };
|
|
111
|
+
* }
|
|
112
|
+
*
|
|
113
|
+
* const runtime = createAgentRuntime({ registry, llmFn });
|
|
114
|
+
* const result = await runtime.run('What is stored under "foo"?');
|
|
115
|
+
* console.log(result.content);
|
|
116
|
+
* ```
|
|
117
|
+
*
|
|
118
|
+
* ---------------------------------------------------------------------------
|
|
119
|
+
* MESSAGE SHAPES -- what actually gets pushed onto the running conversation
|
|
120
|
+
* (`.getMessages()`), in order, for one tool-calling round:
|
|
121
|
+
*
|
|
122
|
+
* 1. `{ role: 'user', content: string }` -- appended once per `run()` call,
|
|
123
|
+
* from its `userMessage` argument.
|
|
124
|
+
* 2. `{ role: 'assistant', content, toolCalls }` -- the raw `llmFn`
|
|
125
|
+
* response, tagged with `role: 'assistant'`, appended VERBATIM (whatever
|
|
126
|
+
* `content`/`toolCalls` `llmFn` returned) so the next `llmFn` call sees
|
|
127
|
+
* an accurate record of what the assistant itself said/asked for. This
|
|
128
|
+
* also means a response with BOTH `content` and `toolCalls` set is
|
|
129
|
+
* preserved faithfully (some vendor APIs allow an assistant turn to
|
|
130
|
+
* include prose alongside a tool call) -- `run()` only treats a
|
|
131
|
+
* response as the FINAL answer when `toolCalls` is absent/empty,
|
|
132
|
+
* matching the plan's stop condition exactly.
|
|
133
|
+
* 3. One `{ role: 'tool', tool_call_id, name, content }` entry PER
|
|
134
|
+
* dispatched tool call, in the same order `toolCalls` was returned:
|
|
135
|
+
* - `tool_call_id` echoes the call's `id`, so an `llmFn` can correlate
|
|
136
|
+
* results back to requests (the OpenAI/Anthropic tool-result
|
|
137
|
+
* convention this shape is deliberately modeled on, per the plan's
|
|
138
|
+
* own suggested shape).
|
|
139
|
+
* - `name` is included too (redundant with `tool_call_id` for a
|
|
140
|
+
* vendor that tracks calls by id, but convenient for `llmFn`
|
|
141
|
+
* implementations/log output that key off the tool name directly).
|
|
142
|
+
* - `content` is always a STRING: `JSON.stringify(result)` of whatever
|
|
143
|
+
* `tool.execute()` resolved to (`BrowserTool.execute()` results are
|
|
144
|
+
* typically plain objects like `{success, output, error}`, not
|
|
145
|
+
* strings -- see `tools.mjs`'s existing tools -- so this file
|
|
146
|
+
* normalizes to a string the same way most chat APIs expect tool
|
|
147
|
+
* results to arrive).
|
|
148
|
+
*
|
|
149
|
+
* ---------------------------------------------------------------------------
|
|
150
|
+
* DISPATCH -- a single bad tool call must not crash the loop
|
|
151
|
+
*
|
|
152
|
+
* For each `{id, name, arguments}` in `toolCalls`:
|
|
153
|
+
* - `registry.get(name)` not found -- synthesized error result
|
|
154
|
+
* `{ success: false, error: 'Unknown tool "<name>"' }` is appended as
|
|
155
|
+
* that call's tool-result message; NO exception is thrown and the loop
|
|
156
|
+
* continues normally (an LLM hallucinating a tool name is exactly the
|
|
157
|
+
* kind of thing that should come back as information for the NEXT
|
|
158
|
+
* `llmFn` call, not a crash).
|
|
159
|
+
* - `tool.execute(arguments)` throws OR rejects -- caught, synthesized as
|
|
160
|
+
* `{ success: false, error: err.message || String(err) }`, same
|
|
161
|
+
* treatment. This matches `mesh-compute.mjs`'s/`mesh-agent-swarm.mjs`'s
|
|
162
|
+
* own "a failing inbound request gets an explicit error response, not a
|
|
163
|
+
* silent drop or a crash" precedent, one layer over: here the "response"
|
|
164
|
+
* is a tool-result message fed back into the SAME conversation loop
|
|
165
|
+
* rather than a wire reply to a remote peer.
|
|
166
|
+
* - Every tool call in a batch is dispatched even if an earlier one in the
|
|
167
|
+
* same batch failed -- one failure does not skip the rest.
|
|
168
|
+
*
|
|
169
|
+
* ---------------------------------------------------------------------------
|
|
170
|
+
* `maxTurns` -- DEFAULT 10, RETURNS A TRUNCATED RESULT RATHER THAN THROWING
|
|
171
|
+
*
|
|
172
|
+
* A "turn" here is one `llmFn` call. If `maxTurns` calls to `llmFn` have all
|
|
173
|
+
* come back asking for more tool calls (never a plain `content`-only
|
|
174
|
+
* response), `run()` stops issuing further `llmFn` calls and resolves with
|
|
175
|
+
* `{ content: <last assistant content, if any>, toolCalls: <last requested
|
|
176
|
+
* calls>, truncated: true }` instead of throwing.
|
|
177
|
+
*
|
|
178
|
+
* Rationale (this file's own judgment call, since the plan left it open):
|
|
179
|
+
* an agent loop hitting a turn limit is a normal, expected outcome for a
|
|
180
|
+
* long-running or looping task -- not necessarily a bug -- and a real
|
|
181
|
+
* caller building a chat UI (the `.getMessages()`/`.reset()` surface below
|
|
182
|
+
* exists specifically for that use case) is much better served by a
|
|
183
|
+
* partial result it can inspect, show to a user, or resume from (the
|
|
184
|
+
* conversation is left exactly as it stood -- nothing is rolled back) than
|
|
185
|
+
* by a thrown exception that forces it to unwind and lose that state. A
|
|
186
|
+
* caller that genuinely wants a hard failure on truncation can simply check
|
|
187
|
+
* `result.truncated` and throw itself.
|
|
188
|
+
*
|
|
189
|
+
* ---------------------------------------------------------------------------
|
|
190
|
+
* No browser-only imports at module level.
|
|
191
|
+
*/
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* @param {unknown} registry
|
|
195
|
+
* @returns {boolean}
|
|
196
|
+
*/
|
|
197
|
+
function looksLikeRegistry(registry) {
|
|
198
|
+
return !!registry
|
|
199
|
+
&& typeof registry.listSpecs === 'function'
|
|
200
|
+
&& typeof registry.get === 'function';
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Default cap on `llmFn` round-trips per `run()` call -- see module doc comment's "maxTurns" section. */
|
|
204
|
+
const DEFAULT_MAX_TURNS = 10;
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Build a `{success: false, error}`-shaped result for a tool call this loop
|
|
208
|
+
* could not (or did not) run -- see module doc comment's "DISPATCH" section.
|
|
209
|
+
* @param {string} error
|
|
210
|
+
* @returns {{success: false, error: string}}
|
|
211
|
+
*/
|
|
212
|
+
function toolError(error) {
|
|
213
|
+
return { success: false, error };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Run every requested tool call against `registry`, one at a time, in order.
|
|
218
|
+
* Neither an unknown tool name nor a throwing/rejecting `.execute()` stops
|
|
219
|
+
* the batch -- see module doc comment's "DISPATCH" section.
|
|
220
|
+
*
|
|
221
|
+
* @param {import('./compat.mjs').BrowserToolRegistry} registry
|
|
222
|
+
* @param {Array<{id: string, name: string, arguments: object}>} toolCalls
|
|
223
|
+
* @param {(event: string, data: object) => void} log
|
|
224
|
+
* @returns {Promise<Array<{role: 'tool', tool_call_id: string, name: string, content: string}>>}
|
|
225
|
+
*/
|
|
226
|
+
async function dispatchToolCalls(registry, toolCalls, log) {
|
|
227
|
+
const results = [];
|
|
228
|
+
for (const call of toolCalls) {
|
|
229
|
+
const { id, name, arguments: args } = call || {};
|
|
230
|
+
let result;
|
|
231
|
+
const tool = name != null ? registry.get(name) : undefined;
|
|
232
|
+
if (!tool) {
|
|
233
|
+
result = toolError(`Unknown tool "${name}"`);
|
|
234
|
+
log('agent-runtime:unknown-tool', { id, name });
|
|
235
|
+
} else {
|
|
236
|
+
try {
|
|
237
|
+
result = await tool.execute(args);
|
|
238
|
+
} catch (err) {
|
|
239
|
+
result = toolError(err?.message || String(err));
|
|
240
|
+
log('agent-runtime:tool-threw', { id, name, error: result.error });
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
results.push({
|
|
244
|
+
role: 'tool',
|
|
245
|
+
tool_call_id: id,
|
|
246
|
+
name,
|
|
247
|
+
content: JSON.stringify(result),
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
return results;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Create a standalone agent tool-calling runtime: a running conversation
|
|
255
|
+
* plus a dispatch loop between a caller-supplied `llmFn` and a
|
|
256
|
+
* `BrowserToolRegistry`. See module doc comment for the full design
|
|
257
|
+
* writeup (required dependencies, the `llmFn` shape with a worked example,
|
|
258
|
+
* message shapes, dispatch error handling, `maxTurns` behavior).
|
|
259
|
+
*
|
|
260
|
+
* @param {object} opts
|
|
261
|
+
* @param {import('./compat.mjs').BrowserToolRegistry} opts.registry
|
|
262
|
+
* REQUIRED. Duck-typed (`.listSpecs`/`.get` both functions) rather than
|
|
263
|
+
* `instanceof`-checked -- see module doc comment.
|
|
264
|
+
* @param {(messages: object[], toolSpecs: object[]) => Promise<{content?: string, toolCalls?: Array<{id: string, name: string, arguments: object}>}>} opts.llmFn
|
|
265
|
+
* REQUIRED. No default implementation is provided by this package -- see
|
|
266
|
+
* module doc comment.
|
|
267
|
+
* @param {number} [opts.maxTurns=10] - Constructor-level default cap on
|
|
268
|
+
* `llmFn` round-trips per `run()` call; overridable per-call via
|
|
269
|
+
* `run(userMessage, { maxTurns })`.
|
|
270
|
+
* @param {(event: string, data: object) => void} [opts.onLog]
|
|
271
|
+
* @returns {{
|
|
272
|
+
* run: (userMessage: string, runOpts?: {maxTurns?: number}) => Promise<{content?: string, toolCalls?: object[], truncated?: boolean}>,
|
|
273
|
+
* getMessages: () => object[],
|
|
274
|
+
* reset: () => void,
|
|
275
|
+
* }}
|
|
276
|
+
*/
|
|
277
|
+
export function createAgentRuntime({ registry, llmFn, maxTurns = DEFAULT_MAX_TURNS, onLog } = {}) {
|
|
278
|
+
if (!looksLikeRegistry(registry)) {
|
|
279
|
+
throw new TypeError(
|
|
280
|
+
'createAgentRuntime: registry is required (a BrowserToolRegistry-shaped object ' +
|
|
281
|
+
'implementing listSpecs() and get(name) -- see compat.mjs\'s BrowserToolRegistry) -- got ' +
|
|
282
|
+
(registry && registry.constructor ? registry.constructor.name : String(registry))
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
if (typeof llmFn !== 'function') {
|
|
286
|
+
throw new TypeError(
|
|
287
|
+
'createAgentRuntime: llmFn is required (an async function ' +
|
|
288
|
+
'(messages, toolSpecs) -> {content?, toolCalls?} -- see module doc comment for the ' +
|
|
289
|
+
'exact shape and a worked example). No default llmFn is provided by this package.'
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const log = onLog || (() => {});
|
|
294
|
+
|
|
295
|
+
/** @type {object[]} */
|
|
296
|
+
let messages = [];
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* @param {string} userMessage
|
|
300
|
+
* @param {{maxTurns?: number}} [runOpts]
|
|
301
|
+
* @returns {Promise<{content?: string, toolCalls?: object[], truncated?: boolean}>}
|
|
302
|
+
*/
|
|
303
|
+
async function run(userMessage, runOpts = {}) {
|
|
304
|
+
const turnLimit = runOpts.maxTurns ?? maxTurns;
|
|
305
|
+
|
|
306
|
+
messages.push({ role: 'user', content: userMessage });
|
|
307
|
+
|
|
308
|
+
let lastResponse;
|
|
309
|
+
for (let turn = 0; turn < turnLimit; turn++) {
|
|
310
|
+
const toolSpecs = registry.listSpecs();
|
|
311
|
+
const response = await llmFn(messages, toolSpecs);
|
|
312
|
+
lastResponse = response;
|
|
313
|
+
|
|
314
|
+
messages.push({ role: 'assistant', ...response });
|
|
315
|
+
|
|
316
|
+
const toolCalls = response && Array.isArray(response.toolCalls) ? response.toolCalls : [];
|
|
317
|
+
if (toolCalls.length === 0) {
|
|
318
|
+
log('agent-runtime:final', { turn, content: response?.content });
|
|
319
|
+
return { content: response?.content, toolCalls: undefined };
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
log('agent-runtime:tool-calls', { turn, count: toolCalls.length, names: toolCalls.map((c) => c?.name) });
|
|
323
|
+
const toolResults = await dispatchToolCalls(registry, toolCalls, log);
|
|
324
|
+
messages.push(...toolResults);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
log('agent-runtime:truncated', { maxTurns: turnLimit });
|
|
328
|
+
return {
|
|
329
|
+
content: lastResponse?.content,
|
|
330
|
+
toolCalls: lastResponse?.toolCalls,
|
|
331
|
+
truncated: true,
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
return {
|
|
336
|
+
run,
|
|
337
|
+
/** @returns {object[]} a copy of the running conversation -- mutating it does not affect the runtime's own state. */
|
|
338
|
+
getMessages: () => [...messages],
|
|
339
|
+
/** Clears the running conversation back to empty, e.g. to start a fresh chat in the same runtime instance. */
|
|
340
|
+
reset: () => { messages = []; },
|
|
341
|
+
};
|
|
342
|
+
}
|