@johnhenry/browsermesh-apps 0.2.0 → 0.4.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 +232 -1
- package/package.json +7 -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 +859 -0
- package/src/compat.mjs +98 -0
- package/src/grant-log.mjs +840 -0
- package/src/index.mjs +34 -2
- 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 +1131 -12
- 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-rpc.mjs +300 -0
- package/src/mesh-service.mjs +403 -0
- package/src/mesh-swarm.mjs +677 -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 +33 -2
- package/src/peer-routing.mjs +369 -5
- package/src/peer-terminal.mjs +400 -130
- package/src/serverless-executor-andbox.mjs +136 -0
- package/src/serverless-fetch.mjs +70 -0
- package/src/serverless-functions.mjs +67 -0
- package/src/serverless-peer-select.mjs +69 -0
- package/src/serverless-proxy.mjs +127 -0
- package/src/serverless-router.mjs +115 -0
- package/src/serverless-sites.mjs +116 -0
- package/src/serverless-static.mjs +202 -0
- package/src/serverless-wire.mjs +87 -0
- package/src/peer-session.mjs +0 -937
package/README.md
CHANGED
|
@@ -21,6 +21,10 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
|
|
|
21
21
|
| scheduler | `MeshScheduler`, `TaskQueue` |
|
|
22
22
|
| consensus | `ConsensusManager`, `Proposal`, `Ballot` |
|
|
23
23
|
| orchestrator | `MeshOrchestrator` + meshctl BrowserTool subclasses |
|
|
24
|
+
| mesh-orchestrator | `createOrchestratorService` (`MeshService` wrapper: real, gated wire dispatch for `execOnPod`/`deploySkill`/`drainPod`, ungated local aggregation for `listPods`/`getPodStatus`/`topPods`) |
|
|
25
|
+
| compat | `BrowserTool`, `BrowserToolRegistry` (base class + registry an LLM-drivable agent loop dispatches tool calls through) |
|
|
26
|
+
| agent-runtime | `createAgentRuntime` (the LLM tool-calling dispatch loop: bring-your-own `llmFn`, real registry-backed tool execution) |
|
|
27
|
+
| mesh-orchestrator-tools | `registerOrchestratorTools`, `createOrchestratorToolRegistry` (wires the 8 real `Meshctl*Tool`s into a `BrowserToolRegistry` against a real, attached `MeshOrchestrator`) |
|
|
24
28
|
| audit | `AuditChain`, `AuditStore`, `detectFork`, `buildMerkleRoot` |
|
|
25
29
|
| visualizations | `TopologyLayout`, `TrustGraphLayout`, `TrustHeatmap` |
|
|
26
30
|
| devtools | `MeshInspector`, `MeshInspectTool` |
|
|
@@ -39,7 +43,6 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
|
|
|
39
43
|
| peer-registry | `PeerRegistry` |
|
|
40
44
|
| peer-routing | `MeshRouter`, `ServerSharing` |
|
|
41
45
|
| peer-services | `ServiceAdvertiser`, `ServiceBrowser` |
|
|
42
|
-
| peer-session | `PeerSession`, `SessionManager` |
|
|
43
46
|
| peer-terminal | `TerminalHost`, `TerminalClient` |
|
|
44
47
|
| peer-timestamp | `TimestampAuthority`, `TimestampProof` |
|
|
45
48
|
| peer-torrent | `TorrentManager` |
|
|
@@ -47,6 +50,13 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
|
|
|
47
50
|
| marketplace-ui | `SkillMarketplace` |
|
|
48
51
|
| mesh-relay-host | `MeshRelayHost` |
|
|
49
52
|
| mesh-relay-backend | `MeshRelayBackend` |
|
|
53
|
+
| mesh-service | `attachService`, `MeshService` (attach convention) |
|
|
54
|
+
| cloud-storage-backend | `CloudStorageBackend` |
|
|
55
|
+
| grant-log | `GrantLog`, `createGrantLogService` |
|
|
56
|
+
| key-distribution | `createKeyDistributionService` |
|
|
57
|
+
| manifest-sync | `createManifestSyncService` |
|
|
58
|
+
| chunk-replication | `createChunkReplicationService` |
|
|
59
|
+
| cloud-storage | `CloudStorage`, `CloudStorageNotFoundError` (the ergonomic S3-like SDK) |
|
|
50
60
|
|
|
51
61
|
## GPU compute
|
|
52
62
|
|
|
@@ -243,6 +253,74 @@ inherited `Backend` "not implemented" throws). See
|
|
|
243
253
|
simulated mesh connection) and
|
|
244
254
|
`test/real-peer/mesh-relay.test.mjs` for the real-WebRTC, real-TCP proof.
|
|
245
255
|
|
|
256
|
+
## CloudStorage bucket authorization and key distribution
|
|
257
|
+
|
|
258
|
+
`grant-log.mjs`'s `GrantLog` (`createGrantLogService()`) is a replicated,
|
|
259
|
+
Ed25519-signed append-log of `grant`/`revoke` records per bucket resource
|
|
260
|
+
(`s3:<bucketId>`), used to propagate a CloudStorage bucket's access-control
|
|
261
|
+
decisions to every peer independently enforcing them (each peer replays the
|
|
262
|
+
merged log into its own, unmodified `PeerRegistry.grantCapabilities()`/
|
|
263
|
+
`revokeCapabilities()`).
|
|
264
|
+
|
|
265
|
+
`key-distribution.mjs`'s `createKeyDistributionService()` builds on top of
|
|
266
|
+
`GrantLog`'s change notifications: whenever a peer's merged, effective grants
|
|
267
|
+
on a bucket go from none to some, a peer that already holds that bucket's
|
|
268
|
+
AES-256-GCM key (`cloud-storage-backend.mjs`'s `CloudStorageBackend`) sends it
|
|
269
|
+
to the newly-granted peer over a dedicated, signed, point-to-point channel,
|
|
270
|
+
encrypted to a companion X25519 key the recipient generates and advertises
|
|
271
|
+
for exactly this purpose (Ed25519 identity keys can't do ECDH directly, and
|
|
272
|
+
this repo intentionally has no Ed25519-to-X25519 conversion utility -- see
|
|
273
|
+
that file's own doc comment for the full writeup, including why the wrap/
|
|
274
|
+
unwrap step itself reuses `browsermesh-core`'s existing `wrapKeyForMember()`/
|
|
275
|
+
`unwrapKeyForMember()` rather than adding a new crypto primitive).
|
|
276
|
+
|
|
277
|
+
**Permanent limitation, not a bug to fix later:** revoking a peer's grant
|
|
278
|
+
(via `GrantLog.revoke()`) stops *future* key distribution and *future* chunk
|
|
279
|
+
replication to that peer, but cannot retroactively erase a key -- or any
|
|
280
|
+
plaintext already decrypted with it -- already delivered to that peer before
|
|
281
|
+
the revoke. A bucket's AES key is never rotated on revoke anywhere in this
|
|
282
|
+
plan. Any since-revoked peer that retained the key (or any chunk ciphertext
|
|
283
|
+
plus the key) can still decrypt that data offline, forever. This is a
|
|
284
|
+
fundamental property of any scheme that hands symmetric key material to
|
|
285
|
+
multiple independent parties -- the same is true of, say, a downloaded S3
|
|
286
|
+
object whose bucket policy changes afterward -- not something a future phase
|
|
287
|
+
of this plan is expected to close.
|
|
288
|
+
|
|
289
|
+
## CloudStorage: the ergonomic SDK
|
|
290
|
+
|
|
291
|
+
`cloud-storage.mjs`'s `CloudStorage` class is the actual developer-facing
|
|
292
|
+
surface the whole plan above was building toward:
|
|
293
|
+
|
|
294
|
+
```js
|
|
295
|
+
import { CloudStorage as s3 } from '@johnhenry/browsermesh-apps'
|
|
296
|
+
const store = new s3({ bucket: 'my-bucket', node: peerNode })
|
|
297
|
+
await store.becomeAdmin() // bootstrap: this peer owns the bucket
|
|
298
|
+
await store.grant(otherPubKey, ['read', 'write'])
|
|
299
|
+
const { durability, replicatedTo } = await store.put('key', data)
|
|
300
|
+
const bytes = await store.get('key') // falls back to a remote peer request if not held locally
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
It composes `CloudStorageBackend` (local, durable, encrypted-at-rest reads/
|
|
304
|
+
writes) with `createGrantLogService()`, `createKeyDistributionService()`,
|
|
305
|
+
`createManifestSyncService()`, and `createChunkReplicationService()` — all
|
|
306
|
+
four attached via `attachService()` with no `network` required — behind
|
|
307
|
+
`put`/`get`/`delete`/`list` plus bucket-admin methods
|
|
308
|
+
(`becomeAdmin`/`grant`/`revoke`/`designateReplica`/`effectiveGrants`). See
|
|
309
|
+
`src/cloud-storage.mjs`'s own module doc comment for the full design
|
|
310
|
+
writeup, including several real gaps the plan's original brief left open and
|
|
311
|
+
exactly how each was resolved.
|
|
312
|
+
|
|
313
|
+
`examples/09-cloud-storage.mjs` is the full story end to end, runnable with
|
|
314
|
+
plain `node`. `test/real-peer/cloud-storage.test.mjs` proves the identical
|
|
315
|
+
composition over an actual WebRTC connection. **New to building a
|
|
316
|
+
mesh-native service yourself?** `docs/building-mesh-services.md` is the
|
|
317
|
+
reusable guide this phase (K, the plan's capstone) produced — the
|
|
318
|
+
`MeshService` attach contract, the control/data-plane transport split, the
|
|
319
|
+
CRDT-manifest-plus-content-addressed-chunk pattern, the signed
|
|
320
|
+
GrantLog pattern, and the key-distribution pattern, each with pointers to
|
|
321
|
+
the real code, written so the *next* mesh-native service doesn't have to
|
|
322
|
+
rediscover these same design questions from scratch.
|
|
323
|
+
|
|
246
324
|
## Putting it all together: sync + kernel-gated mesh + relay on one connection
|
|
247
325
|
|
|
248
326
|
Every composition layer above (`enableSync`, a `Kernel` wired via
|
|
@@ -269,6 +347,159 @@ it (harmless -- those envelopes are just plain objects with a `.type` field
|
|
|
269
347
|
tenant code can filter on itself if it cares, but worth knowing rather than
|
|
270
348
|
assuming the view is pre-filtered).
|
|
271
349
|
|
|
350
|
+
## `fetch()`/`WebSocket`-shaped mesh access: `browserMeshFetch` and `BrowserMeshWebSocket`
|
|
351
|
+
|
|
352
|
+
Two web-standard-API-shaped wrappers over a mesh connection, so existing
|
|
353
|
+
code that already expects `fetch(url) -> Response` or `new WebSocket(url)`
|
|
354
|
+
can reach a mesh-addressable pod (`mesh://podId/path`) without learning
|
|
355
|
+
`PeerNode`'s raw `sendTo()`/`onIncomingData()` API. Both are built on
|
|
356
|
+
`mesh-rpc.mjs`'s `createMeshRpcService()`, a general-purpose request/response
|
|
357
|
+
transport over the same `ctx.sendTo()`/`ctx.onIncomingData()` convention
|
|
358
|
+
every `MeshService` in this family uses (attach it via
|
|
359
|
+
`attachService(peerNode, network, createMeshRpcService({ onRequest }))`, or
|
|
360
|
+
pass it through `createMeshNode({ services: [...] })`).
|
|
361
|
+
|
|
362
|
+
**Authorization boundary, stated explicitly because it's easy to miss:**
|
|
363
|
+
neither transport checks `registry.checkAccess()` against any fixed
|
|
364
|
+
resource/scope -- a general-purpose RPC/duplex channel has no fixed resource
|
|
365
|
+
to check a scope against. Deciding what `{method, path}` combinations (for
|
|
366
|
+
`browserMeshFetch`) or which `(fromPubKey, path)` connections (for
|
|
367
|
+
`BrowserMeshWebSocket`) are allowed is the *responding pod's own*
|
|
368
|
+
`onRequest`/`onConnection` handler's job, the same way a real HTTP server's
|
|
369
|
+
application code owns its own authorization, not its TCP/TLS transport
|
|
370
|
+
layer.
|
|
371
|
+
|
|
372
|
+
### `browserMeshFetch`
|
|
373
|
+
|
|
374
|
+
`createBrowserMeshFetch(meshRpcApi) -> (url, init) => Promise<Response>` binds
|
|
375
|
+
once to a live `mesh-rpc` service's `api` (the `{ request }` object
|
|
376
|
+
`attachService()` returns as `.api`) and hands back a plain function whose
|
|
377
|
+
call signature matches real `fetch(url, init)` exactly -- so it can be
|
|
378
|
+
dropped in anywhere something expects "a fetch-shaped function", with no
|
|
379
|
+
adapter:
|
|
380
|
+
|
|
381
|
+
```js
|
|
382
|
+
import { attachService, createMeshRpcService, createBrowserMeshFetch } from '@johnhenry/browsermesh-apps'
|
|
383
|
+
|
|
384
|
+
// on the peer being called:
|
|
385
|
+
attachService(bobNode, undefined, createMeshRpcService({
|
|
386
|
+
onRequest: async ({ method, path, body }) => {
|
|
387
|
+
if (method === 'GET' && path === '/status') return { status: 200, body: { ok: true } }
|
|
388
|
+
return { status: 404, body: { error: 'not found' } }
|
|
389
|
+
},
|
|
390
|
+
}))
|
|
391
|
+
|
|
392
|
+
// on the calling peer:
|
|
393
|
+
const { api } = attachService(aliceNode, undefined, createMeshRpcService({}))
|
|
394
|
+
const browserMeshFetch = createBrowserMeshFetch(api)
|
|
395
|
+
|
|
396
|
+
const res = await browserMeshFetch('mesh://bob-pod-id/status')
|
|
397
|
+
const data = await res.json() // { ok: true }
|
|
398
|
+
```
|
|
399
|
+
|
|
400
|
+
Error-vs-reject semantics deliberately match real `fetch()`, not a Service
|
|
401
|
+
Worker interceptor's "always resolve some Response" convention: a malformed
|
|
402
|
+
`mesh://`/`*.mesh.local` URL throws a `TypeError` *synchronously*, before any
|
|
403
|
+
Promise exists; a responding pod's `onRequest` throwing or returning a
|
|
404
|
+
non-2xx `status` still resolves a genuine `Response` (status/headers/body
|
|
405
|
+
shaped from whatever it returned); only a transport-level failure -- no
|
|
406
|
+
matching response within the timeout, or the peer being unreachable --
|
|
407
|
+
*rejects* the returned promise, matching what a real network-level `fetch()`
|
|
408
|
+
failure means.
|
|
409
|
+
|
|
410
|
+
### `BrowserMeshWebSocket`
|
|
411
|
+
|
|
412
|
+
A class implementing the standard `WebSocket` *instance* surface
|
|
413
|
+
(`readyState`, `onopen`/`onmessage`/`onerror`/`onclose`,
|
|
414
|
+
`addEventListener`/`removeEventListener`, `send()`, `close()`) over a
|
|
415
|
+
persistent mesh envelope channel. **One real, deliberate deviation from the
|
|
416
|
+
standard constructor:** `new WebSocket(url)` needs no extra arguments
|
|
417
|
+
because a browser's networking stack is an ambient, process-wide resource --
|
|
418
|
+
there is no mesh equivalent, so `new BrowserMeshWebSocket(url, opts)`
|
|
419
|
+
requires `opts.peerNode` (anything exposing `podId`, `sendTo()`,
|
|
420
|
+
`onIncomingData()` -- a real `PeerNode` satisfies this). Everything else
|
|
421
|
+
matches the standard instance shape as closely as this transport allows.
|
|
422
|
+
|
|
423
|
+
```js
|
|
424
|
+
import { BrowserMeshWebSocket, attachService, createMeshWebSocketService } from '@johnhenry/browsermesh-apps'
|
|
425
|
+
|
|
426
|
+
// on the peer accepting connections -- the ONLY side that needs a MeshService
|
|
427
|
+
// attached; a client-role BrowserMeshWebSocket subscribes directly to its
|
|
428
|
+
// own peerNode and needs nothing pre-attached:
|
|
429
|
+
attachService(bobNode, undefined, createMeshWebSocketService({
|
|
430
|
+
onConnection: (fromPubKey, path) => path === '/chat', // accept/reject policy lives here
|
|
431
|
+
onIncomingConnection: (session) => {
|
|
432
|
+
session.onmessage = (event) => session.send(`echo: ${event.data}`)
|
|
433
|
+
},
|
|
434
|
+
}))
|
|
435
|
+
|
|
436
|
+
// on the connecting peer:
|
|
437
|
+
const socket = new BrowserMeshWebSocket('mesh://bob-pod-id/chat', { peerNode: aliceNode })
|
|
438
|
+
socket.onopen = () => socket.send('hello')
|
|
439
|
+
socket.onmessage = (event) => console.log(event.data) // 'echo: hello'
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
The accept/reject handshake is `createMeshWebSocketService({ onConnection })`'s
|
|
443
|
+
job entirely: `onConnection(fromPubKey, path) -> boolean|Promise<boolean>`
|
|
444
|
+
decides per inbound connection attempt. No `onConnection` registered means
|
|
445
|
+
every inbound connection is rejected (the safe default -- an "open door" is a
|
|
446
|
+
worse default than an RPC transport's "not implemented" 501). A rejected
|
|
447
|
+
attempt fires the connecting side's `onerror` then `onclose` with code
|
|
448
|
+
`4403`; a connection that never gets a response within the open timeout
|
|
449
|
+
(10s default) closes with code `1006`, mirroring real `WebSocket`'s own
|
|
450
|
+
abnormal-closure code. `send()` throws `InvalidStateError` both before OPEN
|
|
451
|
+
*and* after CLOSE -- the latter a deliberate deviation from the WHATWG spec
|
|
452
|
+
(which silently drops a post-close `send()`), judged a worse default for
|
|
453
|
+
mesh code than a loud, discoverable throw. `close()` is a one-directional
|
|
454
|
+
notification, not a two-phase closing handshake -- there's no TCP-level
|
|
455
|
+
half-open state to model over a persistent mesh envelope channel. See
|
|
456
|
+
`src/mesh-websocket.mjs`'s module doc comment for the full wire-protocol and
|
|
457
|
+
binary-encoding (base64-over-JSON) writeup.
|
|
458
|
+
|
|
459
|
+
`examples/08-mesh-fetch-websocket.mjs` runs both APIs together end to end
|
|
460
|
+
(request/response, and a duplex exchange including both the accept and
|
|
461
|
+
reject halves of the handshake) over a simulated in-process connection.
|
|
462
|
+
|
|
463
|
+
**Considered, deferred:** extending this same "web-standard-API-shaped
|
|
464
|
+
wrapper" treatment to `WebTransport`/`RTCDataChannel` was evaluated and
|
|
465
|
+
deliberately not scoped here -- see `browsermesh-fetch-websocket.md`'s own
|
|
466
|
+
"Considered, deferred" section for the reasoning (mostly: avoid adding more
|
|
467
|
+
unconsumed wrapper surface before these two have a real caller).
|
|
468
|
+
|
|
469
|
+
## LLM tool-calling: `BrowserToolRegistry` and `createAgentRuntime`
|
|
470
|
+
|
|
471
|
+
A second, deliberately different composition pattern from `MeshService`:
|
|
472
|
+
where `MeshService`/`attachService()` (above) is "how a capability attaches
|
|
473
|
+
to a `PeerNode`," `BrowserTool`/`BrowserToolRegistry`/`createAgentRuntime`
|
|
474
|
+
is "how you expose local OR mesh-backed capabilities to an LLM-driven agent
|
|
475
|
+
loop." `compat.mjs`'s `BrowserToolRegistry` holds any number of `BrowserTool`
|
|
476
|
+
instances (`register`/`get`/`list`/`listSpecs`/`unregister`); `agent-runtime.mjs`'s
|
|
477
|
+
`createAgentRuntime({registry, llmFn})` is the actual conversation loop —
|
|
478
|
+
**browsermesh never calls a real LLM API itself** (no Anthropic/OpenAI SDK
|
|
479
|
+
dependency anywhere in this family); `llmFn(messages, toolSpecs) ->
|
|
480
|
+
{content?, toolCalls?}` is a required, caller-supplied callback, matching
|
|
481
|
+
`mesh-compute.mjs`'s `executeFn`/`mesh-agent-swarm.mjs`'s `agentProxy`
|
|
482
|
+
"bring your own X" precedent.
|
|
483
|
+
|
|
484
|
+
`mesh-orchestrator-tools.mjs`'s `registerOrchestratorTools()` is the worked
|
|
485
|
+
example of wiring a *mesh-backed* capability into this pattern: it
|
|
486
|
+
constructs `orchestrator.mjs`'s 8 real `Meshctl*Tool`s
|
|
487
|
+
(`meshctl_pods`/`meshctl_status`/`meshctl_exec`/`meshctl_deploy`/
|
|
488
|
+
`meshctl_top`/`meshctl_compute`/`meshctl_expose`/`meshctl_drain`) against a
|
|
489
|
+
real, attached `mesh-orchestrator.mjs` service, so an LLM-requested
|
|
490
|
+
`meshctl_exec` tool call really dispatches through that service's
|
|
491
|
+
`checkAccess()`-gated wire protocol to a real remote peer.
|
|
492
|
+
`createMeshNode({enableAgentRuntime: true, enableOrchestrator: true})` wires
|
|
493
|
+
all of this for you, returning `node.toolRegistry` pre-populated and ready
|
|
494
|
+
to drive `createAgentRuntime({registry: node.toolRegistry, llmFn})`.
|
|
495
|
+
|
|
496
|
+
`examples/11-agent-tool-calling.mjs` runs the whole story end to end over
|
|
497
|
+
two real `createMeshNode()` peers, with a deterministic test `llmFn`. See
|
|
498
|
+
`docs/building-mesh-services.md`'s own "`BrowserTool`/`BrowserToolRegistry`/
|
|
499
|
+
agent runtime" section for the full design writeup, including two real bugs
|
|
500
|
+
found while building it and the recommended DI pattern for new tools going
|
|
501
|
+
forward.
|
|
502
|
+
|
|
272
503
|
## License
|
|
273
504
|
|
|
274
505
|
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@johnhenry/browsermesh-apps",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Application layer: marketplace, chat, payments, compute, orchestration, and agent tools for BrowserMesh",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.mjs",
|
|
@@ -26,7 +26,8 @@
|
|
|
26
26
|
"@johnhenry/browsermesh-sync": ">=0.0.0 <1.0.0",
|
|
27
27
|
"@johnhenry/browsermesh-discovery": ">=0.0.1 <1.0.0",
|
|
28
28
|
"@johnhenry/browsermesh-kernel": ">=0.0.0 <1.0.0",
|
|
29
|
-
"@johnhenry/browsermesh-netway": ">=0.0.0 <1.0.0"
|
|
29
|
+
"@johnhenry/browsermesh-netway": ">=0.0.0 <1.0.0",
|
|
30
|
+
"@johnhenry/andbox": ">=0.0.1 <1.0.0"
|
|
30
31
|
},
|
|
31
32
|
"peerDependenciesMeta": {
|
|
32
33
|
"@johnhenry/browsermesh-transport": {
|
|
@@ -43,10 +44,13 @@
|
|
|
43
44
|
},
|
|
44
45
|
"@johnhenry/browsermesh-netway": {
|
|
45
46
|
"optional": true
|
|
47
|
+
},
|
|
48
|
+
"@johnhenry/andbox": {
|
|
49
|
+
"optional": true
|
|
46
50
|
}
|
|
47
51
|
},
|
|
48
52
|
"devDependencies": {
|
|
49
|
-
"node-datachannel": "^0.33.
|
|
53
|
+
"node-datachannel": "^0.33.4",
|
|
50
54
|
"fake-indexeddb": "^6.2.5",
|
|
51
55
|
"webgpu": "^0.6.1"
|
|
52
56
|
},
|
|
@@ -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
|
+
}
|