glove-foundry 0.6.1 → 0.8.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/dist/voice.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import {
2
- renderDeliveries
3
- } from "./chunk-B36BGF5R.js";
2
+ renderDeliveries,
3
+ renderMeshMessages
4
+ } from "./chunk-J6NHL4SM.js";
4
5
 
5
6
  // src/voice.ts
6
7
  import { createServer } from "node:http";
@@ -38,12 +39,33 @@ function announceDelegationUpdate(update) {
38
39
  "Let the caller know, briefly."
39
40
  ].join("\n");
40
41
  }
42
+ function announceMeshMessage(message) {
43
+ const who = `${message.from.name} (${message.from.agentId})`;
44
+ if (message.kind === "reply") {
45
+ return [
46
+ `${who} replied to what you sent them (thread ${message.threadId}):`,
47
+ message.content,
48
+ "Tell the caller what matters, briefly and in plain speech."
49
+ ].join("\n");
50
+ }
51
+ if (message.kind === "failed") {
52
+ return [
53
+ `${who} could not finish (thread ${message.threadId}): ${message.content}`,
54
+ "Let the caller know, briefly."
55
+ ].join("\n");
56
+ }
57
+ return [
58
+ `${who} asks (thread ${message.threadId}): ${message.content}`,
59
+ `If you already know the answer, reply with glove_mesh_send_message to "${message.from.agentId}" with in_reply_to "${message.id}".`,
60
+ "Otherwise ask the caller, then reply with their answer."
61
+ ].join("\n");
62
+ }
41
63
  function gatedTools(agent) {
42
64
  return agent.tools.filter((tool) => tool.requiresPermission !== void 0 && tool.requiresPermission !== false).map((tool) => tool.name);
43
65
  }
44
66
  function voiceCall(options) {
45
67
  return async (agent, context) => {
46
- if (context.request.source?.kind === "delegation") {
68
+ if (context.request.source?.kind === "delegation" || context.request.source?.kind === "mesh") {
47
69
  if (options.offCall) return options.offCall(agent, context);
48
70
  await agent.store.appendMessages([{ sender: "user", text: context.messageText }]);
49
71
  return { endedBecause: "not a call", durationMs: 0, turns: 0, updatesSpoken: 0 };
@@ -81,7 +103,17 @@ function voiceCall(options) {
81
103
  realtime.on("tool_started", (name) => context.emit({ type: "foundry.voice.tool", data: { name, phase: "start" } }));
82
104
  realtime.on("tool_finished", (name) => context.emit({ type: "foundry.voice.tool", data: { name, phase: "done" } }));
83
105
  const announce = options.announce ?? announceDelegationUpdate;
106
+ const announceMesh = options.announceMesh ?? announceMeshMessage;
84
107
  const queue = [];
108
+ const meshSide = (message) => message.threadId === context.conversationId ? "recipient" : "starter";
109
+ const rendered = (batch) => {
110
+ const updates = batch.flatMap((item) => "update" in item ? [item.update] : []);
111
+ const messages = batch.flatMap((item) => "mesh" in item ? [item.mesh] : []);
112
+ return [
113
+ updates.length ? renderDeliveries(updates) : "",
114
+ messages.length ? renderMeshMessages(messages, meshSide) : ""
115
+ ].filter(Boolean).join("\n\n");
116
+ };
85
117
  let heldSince = 0;
86
118
  let retry;
87
119
  const pump = () => {
@@ -97,13 +129,16 @@ function voiceCall(options) {
97
129
  return;
98
130
  }
99
131
  const batch = queue.splice(0);
100
- save([{ sender: "user", text: renderDeliveries(batch) }]);
101
- const text = batch.map(announce).filter((line) => Boolean(line)).join("\n\n");
132
+ save([{ sender: "user", text: rendered(batch) }]);
133
+ const text = batch.map((item) => "update" in item ? announce(item.update) : announceMesh(item.mesh)).filter((line) => Boolean(line)).join("\n\n");
102
134
  if (text) realtime.inject(text, { respond: true });
103
135
  updatesSpoken += batch.length;
104
136
  context.emit({
105
137
  type: "foundry.voice.updates.spoken",
106
- data: { delegationIds: batch.map((update) => update.delegationId) }
138
+ data: {
139
+ delegationIds: batch.flatMap((item) => "update" in item ? [item.update.delegationId] : []),
140
+ threadIds: batch.flatMap((item) => "mesh" in item ? [item.mesh.threadId] : [])
141
+ }
107
142
  });
108
143
  };
109
144
  realtime.adapter.on("agent_speech_started", () => {
@@ -123,11 +158,16 @@ function voiceCall(options) {
123
158
  realtime.adapter.on("interrupted", () => {
124
159
  agentSpeaking = false;
125
160
  });
126
- const stopListening = context.onDelegationUpdate((updates) => {
161
+ const hear = (items) => {
127
162
  if (queue.length === 0) heldSince = Date.now();
128
- queue.push(...updates);
163
+ queue.push(...items);
129
164
  pump();
130
- });
165
+ };
166
+ const stopUpdates = context.onDelegationUpdate((updates) => hear(updates.map((update) => ({ update }))));
167
+ const stopMesh = context.onMeshMessage((messages) => hear(messages.map((mesh) => ({ mesh }))));
168
+ const stopListening = async () => {
169
+ await Promise.all([stopUpdates(), stopMesh()]);
170
+ };
131
171
  const room = typeof options.room === "function" ? await options.room(context) : options.room;
132
172
  const idleMs = options.idleMs ?? 12e4;
133
173
  const maxDurationMs = options.maxDurationMs ?? 30 * 6e4;
@@ -196,7 +236,7 @@ function voiceCall(options) {
196
236
  if (retry) clearTimeout(retry);
197
237
  context.signal.removeEventListener("abort", onAbort);
198
238
  await stopListening();
199
- if (queue.length > 0) save([{ sender: "user", text: renderDeliveries(queue.splice(0)) }]);
239
+ if (queue.length > 0) save([{ sender: "user", text: rendered(queue.splice(0)) }]);
200
240
  try {
201
241
  await room.close();
202
242
  } catch {
@@ -343,6 +383,7 @@ function webSocketRoom(options) {
343
383
  export {
344
384
  VOICE_EXCLUDED_FOUNDRY_TOOLS,
345
385
  announceDelegationUpdate,
386
+ announceMeshMessage,
346
387
  voiceCall,
347
388
  webSocketRoom
348
389
  };
package/docs/README.md CHANGED
@@ -7,7 +7,7 @@ These package-local documents provide the implementation-level companion referen
7
7
  - [Building with Foundry](./building-with-foundry.md): project layout and complete authoring flow.
8
8
  - [Architecture](./architecture.md): definitions, instances, subscriptions, connections, and adapter boundaries.
9
9
  - [HTTP files and host secrets](../../glove-working-environment/HTTP-AND-SECRETS.md): secure downloads/uploads, HTTP calls, keystore references, and per-instance storage.
10
- - [Inspector](./inspector.md): page hierarchy, run traces, live updates, and the operator API.
10
+ - [Inspector](./inspector.md): page hierarchy, runs opened like DevTools (Network, Console, Context), live updates, and the operator API.
11
11
  - [Evaluation checklist](./evaluation-checklist.md): concrete review criteria and verification commands.
12
12
  - [Implementation backlog](./implementation-backlog.md): remaining follow-up work, if any.
13
13
 
@@ -165,6 +165,14 @@ Session loops and goal continuation are composable
165
165
  agent policy over this data and normal scheduled activations. They do not introduce
166
166
  a second scheduler, memory store, filesystem, or agent loop.
167
167
 
168
+ ## Durable addressed events
169
+
170
+ Foundry's controller journals events before dispatch. A target is an exact agent instance and owned conversation. Direct durable-worker messages, task starts and updates, and inbound transmissions share this layer. The data adapter atomically claims target-scoped event IDs and stores pending, acknowledged or expired records; completed IDs remain for deduplication. The file adapter persists them across controller restarts.
171
+
172
+ The controller owns wake/defer deadlines and conversation admission. A live process receives native Glove events; a new event turn calls `processEvents` rather than synthesizing a user message. The internal execution envelope carries events separately from the application payload. Runtime-context providers continue to expose changing snapshots, including open durable-worker tasks. A local handoff directory is a transient transport, not an inbox or a durability boundary.
173
+
174
+ A successful execution result carries consumed-event receipts. The controller reconciles those receipts before replaying unfinished delivery on startup. A crash can repeat work between a side effect and acknowledgment, so delivery is at least once and effects should use event IDs for idempotency. Archival retains pending events; worker purge removes the owned journal and deduplication records. See [durable subagents](./durable-subagents.md) for authoring, policy, permissions and lifecycle details.
175
+
168
176
  ## Working environment and REPL boundary
169
177
 
170
178
  Foundry owns contextual selection, mounting, lifecycle, and observability. The native packages retain their own semantics:
@@ -139,7 +139,7 @@ export default defineApplication({
139
139
  })
140
140
  ```
141
141
 
142
- `FileFoundryDataAdapter` coordinates sibling execution processes with an advisory lock and commits by atomic rename. It persists instances, subscriptions, delivery claims, activations, conversations, workspace data, VFS snapshots, inbox items, tasks, and non-secret environment data. Use a transactional database adapter when several hosts need to share the same state.
142
+ `FileFoundryDataAdapter` coordinates sibling execution processes with an advisory lock and commits by atomic rename. It persists instances, subscriptions, delivery claims, addressed events and receipts, activations, conversations, workspace data, VFS snapshots, inbox items, tasks, and non-secret environment data. Use a transactional database adapter when several hosts need to share the same state.
143
143
 
144
144
  ## The filesystem is the static registry
145
145
 
@@ -190,6 +190,21 @@ export default defineAgent({
190
190
 
191
191
  An agent definition describes lazy assembly. It never declares request input or result output; those are Foundry contracts. An agent definition is also not an instance. Instances are durable data and may be created, updated, removed, or reconstructed independently.
192
192
 
193
+ ### Agents are data
194
+
195
+ A definition is everything a kind of agent can be, like a server-rendered page
196
+ that renders any props. Each agent is an instance, and who it is lives on the
197
+ instance: `name`, `description`, `context`, `installations` and `workspaceId`.
198
+ Write one definition per kind of agent, never one per agent. A person making a
199
+ bot, renaming it or giving it an app is a write (`createAgent`,
200
+ `configureAgent`, `install`), not a deploy. Read names, jobs and per-user
201
+ settings from the instance in resolvers, branch on its data (`context.routines`)
202
+ rather than its id, and let agents change their own data with tools, such as a
203
+ `take_job` tool that writes `name` and `description` with `ctx.data.putAgent`.
204
+ A workspace is a tenant: its agents share workspace entries, and with `mesh` they are peers.
205
+ Add a definition only when a kind of agent runs differently, loads different
206
+ dependencies, or must never have another kind's tools.
207
+
193
208
  ## Define and compose colocated pieces
194
209
 
195
210
  ```ts
@@ -263,6 +278,65 @@ servers from stalling a run indefinitely.
263
278
  Stdio-only idle and lifetime limits can recycle memory-heavy children without
264
279
  interrupting in-flight calls; adapter environment values are resolved again on reopen.
265
280
 
281
+ ### Apps people connect
282
+
283
+ When a person connects one of their own accounts (their Gmail, their Linear),
284
+ connect it through an app, not a bare MCP definition. The app is the unit they
285
+ connect, and it holds everything about that provider: the MCP server whose
286
+ tools the agent uses, the account they open with, the transmissions that carry
287
+ events in and deliveries out, and the connection that listens.
288
+
289
+ ```ts
290
+ // agents/assistant/apps/gmail.app.ts
291
+ export default defineApp({
292
+ description: "Gmail: search, read and draft, send with approval, hear about new mail",
293
+ config: z.object({ alwaysAllow: z.array(z.string()).default([]) }),
294
+ inbound: [gmail], // new mail, as events
295
+ outbound: [gmail], // sending, delivered by Foundry
296
+ connections: [gmailWatch], // users.watch + Pub/Sub, one per account
297
+ mcp: {
298
+ entry: { name: "Gmail", url: "https://gmailmcp.googleapis.com/mcp/v1" },
299
+ // Runs inside the agent's accountSessions; Foundry never holds the token.
300
+ auth: (session) => ({ authorization: `Bearer ${(session as GoogleSession).accessToken}` }),
301
+ // "allow", "ask" or "hide" per tool. Default: read-only tools run, the rest ask.
302
+ tools: (tool, { config }) =>
303
+ tool.readOnly || config.alwaysAllow.includes(tool.name) ? "allow" : "ask",
304
+ },
305
+ })
306
+ ```
307
+
308
+ Install it with the person's account: `install(gmailApp, config, { account })`
309
+ in code, or `{ kind: "application", id: "gmail", accountId }` over HTTP. The
310
+ server's tools mount as `gmail__search_threads` and so on, opened with that
311
+ account; a stdio server gets `auth`'s result as its environment instead. An app
312
+ whose `mcp` has `auth` refuses an installation without an account, and its
313
+ connection closes when the run ends.
314
+
315
+ Splitting the work this way keeps each part where it is safest:
316
+
317
+ - **Reads and drafts** come from the provider's MCP server, through the app's
318
+ tool policy.
319
+ - **Sends** belong in an outbound transmission when the provider's server has
320
+ none or when the send should not run in the agent: Foundry delivers it in its
321
+ own process, with the route's account session, after the exact input is
322
+ approved, and only for a run whose bindings grant the route.
323
+ - **Incoming events** (new mail, a webhook) are an inbound transmission. A
324
+ connection keeps the provider subscription alive per account; a playbook on
325
+ the instance decides which agent hears them.
326
+
327
+ An app that is only an MCP server (Linear's, Google Calendar's) needs only
328
+ `mcp`. Accounts belong to your application: your OAuth callback stores the
329
+ account and its tokens, your `accountSessions` resolves and refreshes them,
330
+ and Foundry reads accounts through your account directory (see "Runtime
331
+ topology is data").
332
+
333
+ An agent can put its own policy around an app's generated send in
334
+ `configure(agent, ctx)`: replace the tool with one whose `requiresPermission`
335
+ applies the person's rules and whose `do` calls the original tool's `run`.
336
+ Glove asks for approval from the tool the model calls, so the wrapper's rule
337
+ is the one that counts, and delivery still happens in Foundry's process.
338
+ `configure` sees the instance, its conversation and the data adapter.
339
+
266
340
  ## Mount optional capabilities
267
341
 
268
342
  Use `configure(agent, context)` to call capability packages' mount functions on the assembled agent. Register resource teardown with `context.onCleanup(() => handle.close())`; callbacks run in reverse order after execution, including failed setup or cancellation. Register cleanup as soon as you acquire a resource, before any later setup can fail.
@@ -344,6 +418,21 @@ export default defineAgent({
344
418
 
345
419
  `workingEnvironment` and `repl` accept the same direct-value-or-lazy-resolver shape as the other assembly fields. JavaScript, Python, and Lisp sessions are supported through one discriminated `defineRepl` API. Foundry exposes the mounted `workingEnvironment`, its guarded `vfs` handle, and the native `repl` session to layers, `configure`, calls, and `run` handlers.
346
420
 
421
+ Installed apps arrive grouped. `select` receives `apps`, one entry per
422
+ installed app with its live tools already named for code, grouped under the
423
+ app and marked read-only where the server says so. Selecting an app's reads
424
+ gives the agent `gmail.search_threads(...)` and `linear.list_issues(...)` in one
425
+ program. `keepDirect: false` takes the selected tools out of the model's direct
426
+ tool list, so a large app catalogue stays out of context; a tool that needs
427
+ approval always stays direct.
428
+
429
+ ```ts
430
+ programmaticTools: {
431
+ select: ({ apps }) => apps.flatMap((app) => app.tools.filter((tool) => tool.readOnly)),
432
+ keepDirect: false,
433
+ }
434
+ ```
435
+
347
436
  `programmaticTools` turns an explicit least-privilege projection of the live
348
437
  agent tool registry into functions inside that sandbox. The selector runs after
349
438
  application transmissions, instance-installed tools and MCPs, calls, memory,
@@ -547,6 +636,28 @@ export const ticketInbound = defineInboundRoute({
547
636
 
548
637
  `accessRef` is opaque to Foundry. Credential acquisition and refresh belong to the user-owned account-session adapter.
549
638
 
639
+ Foundry never creates accounts. When people connect accounts at runtime, keep
640
+ them in your own store and give Foundry a read-only `AccountDirectory` over it.
641
+ Supplying `services` replaces `defineApplication({ accounts })`, so list any
642
+ code-defined accounts in your directory too. Routes and bindings you write when
643
+ someone connects (`putRoute`, `putBinding`) live in the topology store; on a
644
+ single host, `fileTopologyStore(file)` keeps them across restarts.
645
+
646
+ ```ts
647
+ export default defineApplication({
648
+ name: "Assistants",
649
+ data,
650
+ services: Layer.mergeAll(
651
+ myAccountDirectory, // reads your accounts table
652
+ fileTopologyStore(join(dataDir, "topology.json")),
653
+ memoryEventStore,
654
+ ),
655
+ })
656
+ ```
657
+
658
+ Application connections find their account through that directory, so a newly
659
+ connected account starts its connection on the next reconciliation.
660
+
550
661
  ## Runtime-composed playbooks and dynamic installations
551
662
 
552
663
  ```ts
@@ -629,6 +740,10 @@ glove_foundry_schedule({
629
740
  timing: { kind: "every", interval: "24h" },
630
741
  })
631
742
 
743
+ // Deliver through an outbound route this instance's playbooks declare.
744
+ // It asks for approval whenever the route's transmission requires it:
745
+ glove_foundry_transmit({ routeId: "support-replies", payload: { message: "Done." } })
746
+
632
747
  // Suspend this conversation and wake the same instance later:
633
748
  glove_foundry_sleep({
634
749
  kind: "for",
@@ -698,9 +813,13 @@ during active work through the typed steering operation.
698
813
  ## Effect approvals
699
814
 
700
815
  A Glove tool can set `requiresPermission: true` or return a boolean from
701
- `requiresPermission(input)`. In Foundry, an unset decision becomes a public,
702
- expiring approval record rather than an unresolved in-process display promise.
703
- The worker pauses; a trusted host lists and resolves the exact request:
816
+ `requiresPermission(input)`. In Foundry, an unset decision becomes a stored
817
+ approval record rather than an unresolved in-process display promise. The worker
818
+ waits `approvals.waitMs` (60 s); if nobody decides, the run suspends at that call
819
+ and the approval stays open (7 days, through restarts). A trusted host lists and
820
+ resolves the exact request, or opens one by id from a link
821
+ (`client.approval(id)`); a decision after the run suspended resumes the
822
+ conversation at the waiting call:
704
823
 
705
824
  ```ts
706
825
  const [approval] = await client.approvals({
@@ -744,7 +863,9 @@ tool with `requiresPermission` off the call, because a realtime session runs
744
863
  tools directly and would skip the approval. A delegation result that arrives
745
864
  after the caller hangs up runs as an ordinary turn (`source.kind` is
746
865
  `"delegation"`); by default `voiceCall` saves it to the conversation, or pass
747
- `offCall` to handle it, for instance with a text model.
866
+ `offCall` to handle it, for instance with a text model. A call's agent on the
867
+ hosted mesh hears messages from its peers the same way (`announceMeshMessage`,
868
+ or your own `announce`); one that arrives after the call is a `"mesh"` turn.
748
869
 
749
870
  Use `glove-voice-s2s` for Gemini Live, OpenAI Realtime, or GPT-Live and `glove-voice` for a
750
871
  speech-to-text / Glove / text-to-speech pipeline.
@@ -793,10 +914,21 @@ run cleanup. See the [document adapter](../../glove-env-documents/README.md).
793
914
  - IDs appear when definitions are serialized into durable data.
794
915
  - Runtime data IDs remain explicit because users and adapters create those records.
795
916
  - Applications, shared tools, and MCPs mount only when an instance installs them.
917
+ - A person's accounts connect through apps: MCP for tools, transmissions for sends and events, connections for subscriptions, your own account directory and `accountSessions` for credentials.
796
918
  - Memory and inboxes are agent-definition surfaces and may resolve from current context/message.
797
919
  - Working environments and one native REPL are agent-definition surfaces and may resolve from current context/message.
798
920
  - VFS persistence, remote storage, and locking remain adapter-owned.
799
921
  - Transmissions own executable integration logic; playbooks remain serializable policy.
800
922
  - Provider adapters own credential acquisition and refresh.
801
923
  - Voice rooms own audio transport; `voiceCall` owns the session and the transcript; Foundry owns the durable run.
924
+ - A definition is what a kind of agent can be; each agent, its name and its job are instance data.
802
925
  - Interactors keep the person's context; workers keep one task's. Delegation results and questions come back to the conversation that delegated.
926
+ - Agents that already exist as peers in one workspace can message each other on the hosted mesh. Replies come back to the conversation that sent the message.
927
+
928
+ ## Durable subagents
929
+
930
+ Use `defineAgent({ durableSubagents: { research: { agent: researcher, inherit: { memory: "shared" } } } })`
931
+ for persistent owned workers. Existing task delegation can target the `research` name;
932
+ `glove_foundry_message` sends spontaneous messages to that worker or back to its parent.
933
+ See [Durable subagents](durable-subagents.md) for app permission modifiers, independent
934
+ run limits, direct client messaging, persistence boundaries, and archive/purge semantics.