glove-foundry 0.5.1 → 0.6.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.
Files changed (44) hide show
  1. package/README.md +104 -15
  2. package/dist/{chunk-GKZLWD5M.js → chunk-7F7QVO6I.js} +4 -1
  3. package/dist/chunk-B36BGF5R.js +530 -0
  4. package/dist/{chunk-5NFLGHOC.js → chunk-K2EU63MB.js} +216 -29
  5. package/dist/{chunk-KBMD4RYU.js → chunk-OBTOFA7W.js} +63 -198
  6. package/dist/{chunk-LW5PJ2FN.js → chunk-RSU7NEDK.js} +9 -3
  7. package/dist/{chunk-TH5ETCG2.js → chunk-TFGETZYH.js} +198 -11
  8. package/dist/{chunk-SGF3CFUR.js → chunk-X6EWEWWM.js} +942 -57
  9. package/dist/cli.js +8 -5
  10. package/dist/client-DWPYe_Nc.d.ts +888 -0
  11. package/dist/client.d.ts +2 -1
  12. package/dist/client.js +1 -1
  13. package/dist/{client-DcsnudMI.d.ts → definition-A8o11aez.d.ts} +195 -812
  14. package/dist/execution-agent.js +5 -4
  15. package/dist/execution-daemon.js +37 -2
  16. package/dist/execution-loader.js +5 -4
  17. package/dist/index.d.ts +8 -3
  18. package/dist/index.js +39 -14
  19. package/dist/voice.d.ts +168 -0
  20. package/dist/voice.js +348 -0
  21. package/docs/building-with-foundry.md +32 -21
  22. package/docs/durable-execution.md +56 -0
  23. package/docs/release-verification.md +1 -1
  24. package/package.json +16 -9
  25. package/templates/minimal/README.md +34 -8
  26. package/templates/minimal/agents/assistant/agent.ts +24 -10
  27. package/templates/minimal/foundry.application.ts +11 -3
  28. package/templates/minimal/gitignore +1 -0
  29. package/templates/minimal/lib/file-store.ts +95 -0
  30. package/templates/travel-concierge/README.md +46 -12
  31. package/templates/travel-concierge/agents/concierge/agent.ts +10 -4
  32. package/templates/travel-concierge/agents/concierge/composition.ts +9 -2
  33. package/templates/travel-concierge/agents/concierge/flights.ts +43 -0
  34. package/templates/travel-concierge/agents/concierge/instances.ts +42 -0
  35. package/templates/travel-concierge/agents/concierge/memory/traveller.memory.ts +13 -8
  36. package/templates/travel-concierge/agents/concierge/tools/convert-currency.tool.ts +34 -0
  37. package/templates/travel-concierge/agents/concierge/workbench.ts +4 -1
  38. package/templates/travel-concierge/foundry.application.ts +15 -6
  39. package/templates/travel-concierge/gitignore +1 -0
  40. package/templates/travel-concierge/lib/demo-model.ts +89 -25
  41. package/templates/travel-concierge/lib/file-context.ts +60 -0
  42. package/templates/travel-concierge/lib/file-store.ts +95 -0
  43. package/templates/minimal/agents/assistant/tools/current-time.tool.ts +0 -17
  44. package/templates/travel-concierge/agents/concierge/tools/find-flights.tool.ts +0 -49
package/dist/voice.js ADDED
@@ -0,0 +1,348 @@
1
+ import {
2
+ renderDeliveries
3
+ } from "./chunk-B36BGF5R.js";
4
+
5
+ // src/voice.ts
6
+ import { createServer } from "node:http";
7
+ import { RealtimeAgent } from "glove-voice-s2s";
8
+ import { WebSocketServer } from "ws";
9
+ var VOICE_EXCLUDED_FOUNDRY_TOOLS = Object.freeze([
10
+ "glove_foundry_spawn",
11
+ "glove_foundry_sleep",
12
+ "glove_foundry_background",
13
+ "glove_foundry_schedules",
14
+ "glove_foundry_conversations",
15
+ "glove_foundry_workspace",
16
+ "glove_foundry_shared_inbox",
17
+ "glove_foundry_tasks",
18
+ "glove_foundry_environment"
19
+ ]);
20
+ var MAX_UPDATE_HOLD_MS = 8e3;
21
+ function announceDelegationUpdate(update) {
22
+ if (update.kind === "result") {
23
+ return [
24
+ `The ${update.agent} agent finished "${update.task}" (delegation ${update.delegationId}).`,
25
+ `Its result: ${update.result}`,
26
+ "Tell the caller what matters, briefly and in plain speech."
27
+ ].join("\n");
28
+ }
29
+ if (update.kind === "question") {
30
+ return [
31
+ `The ${update.agent} agent, working on "${update.task}", asks: ${update.question}`,
32
+ `If you already know the answer, reply with glove_foundry_reply (delegation ${update.delegationId}).`,
33
+ "Otherwise ask the caller, then reply with their answer."
34
+ ].join("\n");
35
+ }
36
+ return [
37
+ `The ${update.agent} agent could not finish "${update.task}" (delegation ${update.delegationId}): ${update.error}`,
38
+ "Let the caller know, briefly."
39
+ ].join("\n");
40
+ }
41
+ function gatedTools(agent) {
42
+ return agent.tools.filter((tool) => tool.requiresPermission !== void 0 && tool.requiresPermission !== false).map((tool) => tool.name);
43
+ }
44
+ function voiceCall(options) {
45
+ return async (agent, context) => {
46
+ if (context.request.source?.kind === "delegation") {
47
+ if (options.offCall) return options.offCall(agent, context);
48
+ await agent.store.appendMessages([{ sender: "user", text: context.messageText }]);
49
+ return { endedBecause: "not a call", durationMs: 0, turns: 0, updatesSpoken: 0 };
50
+ }
51
+ const startedAt = Date.now();
52
+ const excludeTools = [.../* @__PURE__ */ new Set([
53
+ ...VOICE_EXCLUDED_FOUNDRY_TOOLS,
54
+ ...gatedTools(agent),
55
+ ...options.realtime?.excludeTools ?? []
56
+ ])];
57
+ const realtime = new RealtimeAgent({ ...options.realtime, agent, excludeTools });
58
+ const keepTranscript = options.transcript !== false;
59
+ let saving = Promise.resolve();
60
+ const save = (messages) => {
61
+ if (!keepTranscript) return;
62
+ saving = saving.then(() => agent.store.appendMessages(messages)).catch((cause) => {
63
+ context.emit({
64
+ type: "foundry.voice.transcript.error",
65
+ data: { message: cause instanceof Error ? cause.message : String(cause) }
66
+ });
67
+ });
68
+ };
69
+ let turns = 0;
70
+ let updatesSpoken = 0;
71
+ let agentSpeaking = false;
72
+ let userSpeaking = false;
73
+ realtime.on("user_said", (text) => save([{ sender: "user", text }]));
74
+ realtime.on("agent_said", (text) => {
75
+ turns++;
76
+ save([{ sender: "agent", text }]);
77
+ });
78
+ realtime.on("error", (error) => {
79
+ context.emit({ type: "foundry.voice.error", data: { message: error.message } });
80
+ });
81
+ realtime.on("tool_started", (name) => context.emit({ type: "foundry.voice.tool", data: { name, phase: "start" } }));
82
+ realtime.on("tool_finished", (name) => context.emit({ type: "foundry.voice.tool", data: { name, phase: "done" } }));
83
+ const announce = options.announce ?? announceDelegationUpdate;
84
+ const queue = [];
85
+ let heldSince = 0;
86
+ let retry;
87
+ const pump = () => {
88
+ if (queue.length === 0 || !realtime.isConnected) return;
89
+ const waited = Date.now() - heldSince;
90
+ if ((agentSpeaking || userSpeaking) && waited < MAX_UPDATE_HOLD_MS) {
91
+ if (!retry) {
92
+ retry = setTimeout(() => {
93
+ retry = void 0;
94
+ pump();
95
+ }, 250);
96
+ }
97
+ return;
98
+ }
99
+ 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");
102
+ if (text) realtime.inject(text, { respond: true });
103
+ updatesSpoken += batch.length;
104
+ context.emit({
105
+ type: "foundry.voice.updates.spoken",
106
+ data: { delegationIds: batch.map((update) => update.delegationId) }
107
+ });
108
+ };
109
+ realtime.adapter.on("agent_speech_started", () => {
110
+ agentSpeaking = true;
111
+ });
112
+ realtime.adapter.on("agent_speech_stopped", () => {
113
+ agentSpeaking = false;
114
+ pump();
115
+ });
116
+ realtime.adapter.on("user_speech_started", () => {
117
+ userSpeaking = true;
118
+ });
119
+ realtime.adapter.on("user_speech_stopped", () => {
120
+ userSpeaking = false;
121
+ pump();
122
+ });
123
+ realtime.adapter.on("interrupted", () => {
124
+ agentSpeaking = false;
125
+ });
126
+ const stopListening = context.onDelegationUpdate((updates) => {
127
+ if (queue.length === 0) heldSince = Date.now();
128
+ queue.push(...updates);
129
+ pump();
130
+ });
131
+ const room = typeof options.room === "function" ? await options.room(context) : options.room;
132
+ const idleMs = options.idleMs ?? 12e4;
133
+ const maxDurationMs = options.maxDurationMs ?? 30 * 6e4;
134
+ let finish;
135
+ const ended = new Promise((resolveEnded) => {
136
+ let done = false;
137
+ finish = (reason) => {
138
+ if (done) return;
139
+ done = true;
140
+ resolveEnded(reason);
141
+ };
142
+ });
143
+ let connected = 0;
144
+ let greeted = false;
145
+ let idleTimer;
146
+ const armIdle = () => {
147
+ if (idleTimer) clearTimeout(idleTimer);
148
+ idleTimer = setTimeout(() => finish("idle"), idleMs);
149
+ };
150
+ const call = {
151
+ realtime,
152
+ runId: context.runId,
153
+ emit: context.emit,
154
+ joined() {
155
+ connected++;
156
+ if (idleTimer) clearTimeout(idleTimer);
157
+ idleTimer = void 0;
158
+ context.emit({ type: "foundry.voice.caller.joined", data: { connected } });
159
+ if (!greeted && options.greeting) {
160
+ greeted = true;
161
+ realtime.inject(options.greeting, { respond: true });
162
+ }
163
+ pump();
164
+ },
165
+ left() {
166
+ connected = Math.max(0, connected - 1);
167
+ context.emit({ type: "foundry.voice.caller.left", data: { connected } });
168
+ if (connected === 0) armIdle();
169
+ },
170
+ say(text) {
171
+ save([{ sender: "user", text }]);
172
+ realtime.inject(text, { respond: true });
173
+ },
174
+ end: (reason) => finish(reason)
175
+ };
176
+ const onAbort = () => finish("cancelled");
177
+ const maxTimer = setTimeout(() => finish("time limit"), maxDurationMs);
178
+ let started = false;
179
+ try {
180
+ await realtime.start();
181
+ started = true;
182
+ if (options.openDelayMs) {
183
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, options.openDelayMs));
184
+ }
185
+ await room.open(call);
186
+ if (connected === 0) armIdle();
187
+ context.signal.addEventListener("abort", onAbort, { once: true });
188
+ if (context.signal.aborted) onAbort();
189
+ context.emit({ type: "foundry.voice.call.open", data: { tools: realtime.exposedTools.map((tool) => tool.name) } });
190
+ const endedBecause = await ended;
191
+ context.emit({ type: "foundry.voice.call.ended", data: { endedBecause } });
192
+ return { endedBecause, durationMs: Date.now() - startedAt, turns, updatesSpoken };
193
+ } finally {
194
+ clearTimeout(maxTimer);
195
+ if (idleTimer) clearTimeout(idleTimer);
196
+ if (retry) clearTimeout(retry);
197
+ context.signal.removeEventListener("abort", onAbort);
198
+ await stopListening();
199
+ if (queue.length > 0) save([{ sender: "user", text: renderDeliveries(queue.splice(0)) }]);
200
+ try {
201
+ await room.close();
202
+ } catch {
203
+ }
204
+ if (started) await realtime.stop().catch(() => void 0);
205
+ await saving;
206
+ }
207
+ };
208
+ }
209
+ function resample(pcm, from, to) {
210
+ if (from === to) return pcm;
211
+ const output = new Int16Array(Math.floor(pcm.length * to / from));
212
+ const ratio = from / to;
213
+ for (let index = 0; index < output.length; index++) {
214
+ const position = index * ratio;
215
+ const left = Math.floor(position);
216
+ const right = Math.min(left + 1, pcm.length - 1);
217
+ const fraction = position - left;
218
+ output[index] = pcm[left] * (1 - fraction) + pcm[right] * fraction | 0;
219
+ }
220
+ return output;
221
+ }
222
+ function bytes(data) {
223
+ if (Buffer.isBuffer(data)) return data;
224
+ if (Array.isArray(data)) return Buffer.concat(data);
225
+ return Buffer.from(data);
226
+ }
227
+ function webSocketRoom(options) {
228
+ const sampleRate = options.sampleRate ?? 16e3;
229
+ const path = options.path ?? "/call";
230
+ let server;
231
+ let sockets;
232
+ let caller = null;
233
+ return {
234
+ async open(call) {
235
+ const { realtime } = call;
236
+ const send = (message) => {
237
+ if (caller?.readyState === 1) caller.send(JSON.stringify(message));
238
+ };
239
+ let turnId = 0;
240
+ let turnOpen = false;
241
+ realtime.on("user_said", (text) => send({ t: "utterance", text }));
242
+ realtime.on("agent_delta", (text) => {
243
+ if (!turnOpen) {
244
+ turnOpen = true;
245
+ turnId++;
246
+ }
247
+ send({ t: "speech", turnId, text });
248
+ });
249
+ realtime.on("agent_said", () => {
250
+ if (!turnOpen) return;
251
+ turnOpen = false;
252
+ send({ t: "speech_end", turnId });
253
+ });
254
+ realtime.on("tool_started", (name) => send({ t: "tool", name, phase: "start" }));
255
+ realtime.on("tool_finished", (name) => send({ t: "tool", name, phase: "done" }));
256
+ realtime.on("error", (error) => send({ t: "error", message: error.message }));
257
+ realtime.adapter.on("audio", (pcm, format) => {
258
+ if (caller?.readyState !== 1) return;
259
+ const out = resample(pcm, format.sampleRate, sampleRate);
260
+ caller.send(out.buffer.slice(out.byteOffset, out.byteOffset + out.byteLength), { binary: true });
261
+ });
262
+ realtime.adapter.on("interrupted", () => {
263
+ turnOpen = false;
264
+ send({ t: "clear" });
265
+ });
266
+ realtime.adapter.on("user_speech_stopped", () => send({ t: "state", state: "thinking" }));
267
+ realtime.adapter.on("agent_speech_started", () => send({ t: "state", state: "speaking" }));
268
+ realtime.adapter.on("agent_speech_stopped", () => send({ t: "state", state: "listening" }));
269
+ server = createServer((request, response) => {
270
+ if (new URL(request.url ?? "/", "http://localhost").pathname !== "/health") {
271
+ response.writeHead(404).end("not found");
272
+ return;
273
+ }
274
+ response.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
275
+ response.end(JSON.stringify({ ok: true, connected: Boolean(caller) }));
276
+ });
277
+ sockets = new WebSocketServer({ server, path });
278
+ sockets.on("connection", (socket, request) => {
279
+ const url = new URL(request.url ?? "/", "http://localhost");
280
+ if (url.searchParams.get("token") !== options.token) {
281
+ socket.close(4403, "invalid room token");
282
+ return;
283
+ }
284
+ const replaced = caller;
285
+ caller = socket;
286
+ if (replaced) {
287
+ replaced.close(4400, "replaced by another caller");
288
+ call.left();
289
+ }
290
+ call.joined();
291
+ send({
292
+ t: "ready",
293
+ sessionId: call.runId,
294
+ agent: options.agentName ?? "agent",
295
+ model: options.model ?? "",
296
+ tools: realtime.exposedTools.map((tool) => tool.name)
297
+ });
298
+ send({ t: "state", state: "listening" });
299
+ socket.on("message", (data, isBinary) => {
300
+ if (isBinary) {
301
+ const chunk = bytes(data);
302
+ const pcm = new Int16Array(chunk.buffer.slice(chunk.byteOffset, chunk.byteOffset + chunk.byteLength));
303
+ realtime.sendAudio(resample(pcm, sampleRate, realtime.adapter.inputFormat.sampleRate));
304
+ return;
305
+ }
306
+ let message;
307
+ try {
308
+ message = JSON.parse(data.toString());
309
+ } catch {
310
+ send({ t: "error", message: "Ignored a message that was not JSON." });
311
+ return;
312
+ }
313
+ if (message.t === "say" && message.text.trim()) {
314
+ const text = message.text.trim();
315
+ send({ t: "utterance", text });
316
+ call.say(text);
317
+ } else if (message.t === "barge_in") {
318
+ realtime.adapter.interrupt();
319
+ }
320
+ });
321
+ const detach = () => {
322
+ if (caller !== socket) return;
323
+ caller = null;
324
+ call.left();
325
+ };
326
+ socket.on("close", detach);
327
+ socket.on("error", detach);
328
+ });
329
+ await new Promise((resolveListen, rejectListen) => {
330
+ server.once("error", rejectListen);
331
+ server.listen(options.port, options.host ?? "127.0.0.1", () => resolveListen());
332
+ });
333
+ call.emit({ type: "foundry.voice.room.ready", data: { port: options.port, path } });
334
+ },
335
+ async close() {
336
+ caller?.close(1001, "call ended");
337
+ caller = null;
338
+ sockets?.close();
339
+ if (server?.listening) await new Promise((resolveClose) => server.close(() => resolveClose()));
340
+ }
341
+ };
342
+ }
343
+ export {
344
+ VOICE_EXCLUDED_FOUNDRY_TOOLS,
345
+ announceDelegationUpdate,
346
+ voiceCall,
347
+ webSocketRoom
348
+ };
@@ -38,7 +38,7 @@ Native Glove media parts may include a human-facing `name`. A custom `run` handl
38
38
  persist or normalize those parts and then call `context.defaultRun(enrichedMessage)`
39
39
  to keep the standard Glove loop and conversation semantics.
40
40
 
41
- The generated project depends on the exact Glove versions the `glove-foundry` that created it was built against. That is not tidiness: a narrower range makes the package manager install a second copy of `glove-js`, and the two `JsSession` classes then fail to type-match.
41
+ The generated project depends on caret ranges of the Glove versions the `glove-foundry` that created it was built against (for example `^0.4.2` when it was built with `glove-js@0.4.2`). That is not tidiness: an older range makes the package manager install a second copy of `glove-js`, and the two `JsSession` classes then fail to type-match.
42
42
 
43
43
  ### Templates
44
44
 
@@ -63,11 +63,13 @@ A directory holding a Next.js app is detected, so `--target` is usually unnecess
63
63
  | `foundry/agents/**` | The agents |
64
64
  | `foundry/foundry.application.ts` | Data adapter, accounts, routes |
65
65
  | `foundry/package.json` | `{"type":"module"}`, scoping ESM to the agents |
66
+ | `foundry/lib/**` | The template's helpers, such as the durable transcript store |
67
+ | `foundry/.gitignore` | Ignores `foundry/.data/`, where runtime data, transcripts and memory are written |
66
68
  | `foundry.config.mts` | Points the runtime at `foundry/agents` |
67
69
  | `lib/foundry.ts` | A typed client your app imports |
68
70
  | `app/api/<agent>/route.ts` | An example route handler |
69
71
 
70
- Your `package.json` keeps its name, scripts, and dependencies; it gains `foundry:dev`, `foundry:start`, and the Glove packages. Nothing it already owns is overwritten.
72
+ Your `package.json` keeps its name, scripts, and unrelated dependencies; it gains `foundry:dev` and `foundry:start`. The Glove packages, `effect` and `zod` are set to the ranges this Foundry requires, replacing any version the app already declared (an app on `zod@3` is moved to `zod@4`). Every other file the app owns is left untouched; Foundry's runtime data goes to `foundry/.data/`, ignored by `foundry/.gitignore`.
71
73
 
72
74
  The runtime is a separate process from `next dev`, deliberately — it holds durable state and should not restart when a component changes. The app reaches it over HTTP through `lib/foundry.ts`, so no part of the agent graph is bundled into your app, and `FoundryRoutes` stays a type-only import.
73
75
 
@@ -725,31 +727,39 @@ For typed `goals`, `facts`, `forms`, and `contextProviders` fields, see
725
727
  [Guided conversations](./guidance.md). They mount native runners and providers
726
728
  and expose typed execution handles; no custom layer is required.
727
729
 
728
- Voice is a host adapter, not a second agent-definition vocabulary. Keep realtime
729
- audio, provider turn detection, interruption, telephony, and device access in the
730
- host. Delegate substantive work to a persisted Foundry instance and conversation
731
- through the native client or `/v1/responses`; the resulting run stays durable and
732
- observable.
730
+ A voice agent is an ordinary definition whose model is `s2sDrivenModel(...)`
731
+ and whose `run` is `voiceCall(...)` from `glove-foundry/voice`. The call hosts
732
+ `RealtimeAgent` over the assembled Glove, so the session gets the definition's
733
+ prompt, tools, memory and runtime context. It saves what both sides say to the
734
+ conversation store and ends when the room closes, nobody is connected for
735
+ `idleMs`, the run is cancelled, or `maxDurationMs` passes. A room is any
736
+ `{ open(call), close() }`; `webSocketRoom` serves PCM16 over one WebSocket and
737
+ other transports (LiveKit, a phone bridge) report `call.joined()` and
738
+ `call.left()` the same way.
739
+
740
+ Keep the call thin. Durable, slow or approval-gated work belongs to a delegate:
741
+ list workers in `delegates`, and the call speaks their results and questions at
742
+ the next pause in speech. `voiceCall` keeps Foundry's bookkeeping tools and any
743
+ tool with `requiresPermission` off the call, because a realtime session runs
744
+ tools directly and would skip the approval. A delegation result that arrives
745
+ after the caller hangs up runs as an ordinary turn (`source.kind` is
746
+ `"delegation"`); by default `voiceCall` saves it to the conversation, or pass
747
+ `offCall` to handle it, for instance with a text model.
733
748
 
734
749
  Use `glove-voice-s2s` for Gemini Live, OpenAI Realtime, or GPT-Live and `glove-voice` for a
735
- speech-to-text / Glove / text-to-speech pipeline. A realtime host can expose a
736
- delegation tool backed by the typed Foundry client, or mount `RealtimeAgent` against
737
- the assembled Glove in a scoped layer. Stop the voice session in the layer's
738
- cleanup. Keep provider credentials and audio device access in the host adapter.
750
+ speech-to-text / Glove / text-to-speech pipeline.
739
751
 
740
752
  GPT-Live selects `provider: "openai-live"` in `s2sDrivenModel` or
741
- `createS2SAdapter`. Its Responses backend chooses the exposed Glove tools; this
742
- does not turn a voice session into a durable Foundry run. For durable work, expose
743
- a delegation tool that calls the target instance/conversation through the Foundry
744
- client. The host owns continuous PCM pacing (including silence), timestamped
745
- transcript fragments, playback and avatar utterance boundaries, and awaited
746
- shutdown for final usage. The adapter does not implement Live client delegation
747
- or browser WebRTC. Read the [GPT-Live guide](../../glove-voice-s2s/README.md#gpt-live)
753
+ `createS2SAdapter`. The host owns continuous PCM pacing (including silence),
754
+ timestamped transcript fragments, playback and avatar utterance boundaries, and
755
+ awaited shutdown for final usage. The adapter does not implement Live client
756
+ delegation or browser WebRTC. Read the [GPT-Live guide](../../glove-voice-s2s/README.md#gpt-live)
748
757
  before adapting an existing room example; Realtime VAD and final-turn assumptions
749
758
  do not apply.
750
759
 
751
- `examples/foundry-braind-storm` demonstrates a voice lead delegating durable work
752
- to Foundry agents. Phone bridges, LiveKit rooms and native audio hosts can use the
760
+ `examples/foundry-layered-assistant` is a fast interactor with personal memory
761
+ that takes text or calls and delegates to a coder and a researcher.
762
+ `examples/foundry-braind-storm` runs its briefing line on `voiceCall`. Phone bridges, LiveKit rooms and native audio hosts can use the
753
763
  same instance/conversation boundary. Messenger-specific voice gateways and codecs
754
764
  are consumer adapters, not built-in Foundry telephony services.
755
765
 
@@ -788,4 +798,5 @@ run cleanup. See the [document adapter](../../glove-env-documents/README.md).
788
798
  - VFS persistence, remote storage, and locking remain adapter-owned.
789
799
  - Transmissions own executable integration logic; playbooks remain serializable policy.
790
800
  - Provider adapters own credential acquisition and refresh.
791
- - Voice and device hosts own audio transport while Foundry owns the durable agent run.
801
+ - Voice rooms own audio transport; `voiceCall` owns the session and the transcript; Foundry owns the durable run.
802
+ - Interactors keep the person's context; workers keep one task's. Delegation results and questions come back to the conversation that delegated.
@@ -0,0 +1,56 @@
1
+ # Durable execution and recoverable agent steps
2
+
3
+ Configure persistent execution on the application, then declare agent stages using only Foundry primitives:
4
+
5
+ ```ts
6
+ import { defineApplication, defineAgent, defineAgentSteps, durableExecution } from "glove-foundry";
7
+
8
+ export const application = defineApplication({
9
+ name: "Assistant",
10
+ execution: durableExecution({ directory: "/data/foundry/execution" }),
11
+ });
12
+
13
+ export default defineAgent({
14
+ description: "Prepare a report and deliver its result",
15
+ steps: defineAgentSteps()
16
+ .step("prepare-report", { version: "1" }, async (_agent, context) => {
17
+ return { text: await context.defaultRun() };
18
+ })
19
+ .step("prepare-delivery", { replay: "idempotent" }, async (_agent, context, report) => {
20
+ return deliveryOutbox.put(context.step.idempotencyKey, report);
21
+ })
22
+ .build(),
23
+ });
24
+ ```
25
+
26
+ Each callback receives the assembled agent, the usual Foundry handler context and the previous stage's typed result. The first stage receives `null`. `context.step` provides its name and stable `idempotencyKey`; `context.execution` provides `durable` and `attempt`. Do not combine `steps` with `run` or `handler`. Ordinary handlers retain one attempt. A memory application also retains one attempt, even with a step plan.
27
+
28
+ Set `execution.maxAttempts` in `foundry.config.ts` (for example 3). Durable plans resume with the same run, droid instance and conversation IDs. Completed steps reuse their saved JSON output without invoking their callbacks. Assembly is lazy and shared by the unfinished stages within an attempt, with cleanup on success or failure. Foundry snapshots configured VFS and guidance before allowing native step completion.
29
+
30
+ ## Replay safety
31
+
32
+ The default policy is `replay: "never"`: a stage which started but has no saved completion stops recovery with an unknown-outcome error. It may have changed an external system. Inspect the result before starting new work. `replay: "idempotent"` permits repeating a stage using the same operation key; the operation must actually honor that key or otherwise be safe to repeat. Retries do not guarantee exactly-once external effects.
33
+
34
+ Step names must be unique. Names, order, explicit versions and replay policies form a persisted plan identity. Changing any of them prevents an existing plan from resuming against incompatible code. Bump `version` when a callback's meaning or output shape changes. Values must be JSON, at most 4 MiB per stage result; return `null` instead of `undefined`.
35
+
36
+ Wrap a whole model turn in one default-policy stage when its tools can mutate external systems. A completed turn can be reused for delivery without new model usage. An interrupted model turn needs inspection; individual thoughts, streams and tool calls are not resumed.
37
+
38
+ ## Execution ownership
39
+
40
+ Foundry translates its plan into Station's existing `.step(...).build()` executor. Station owns `runs` and `runs_steps`, completed-output reuse, attempts, claims, lease renewal, cancellation and expired-lease recovery. There is no Foundry checkpoint table, step loop, retry loop or result cache. A private admission decorator enforces Foundry replay policy using the native step records. Native SQLite claimed-step methods atomically fence writes against lease loss, expiry and cancellation. No Station imports or storage APIs are required in an agent definition.
41
+
42
+ This preview requires the companion `station-adapter-sqlite@3.0.1-foundry.0` preview for claimed-step writes. Pin both local packages until equivalent upstream releases exist. Station's recovery executor itself is unchanged.
43
+
44
+ Use Node 22.13+ and one persistent local volume private to the application. Keep `/data/foundry/execution/execution.sqlite` and its WAL state across deployments. Back it up with SQLite's backup mechanism or while stopped. Do not run two Foundry applications against the same directory. This configuration is single-host durability, not distributed failover.
45
+
46
+ Persist instances, conversations and workspace data through their own application adapters too. Programmatic setup supplies `applicationFilePath`, so daemon and attempts load the same infrastructure. For sequential conversation writes use `maxConcurrent: 1` and `retryBackoffMs: 0`; native retry backoff can otherwise admit newer work first. Terminal and cancelled runs remain terminal. One-shot activations reuse their accepted native run.
47
+
48
+ ## Upgrading the unpublished checkpoint preview
49
+
50
+ The old `context.execution.step` and `recovery: "checkpointed"` API has been removed. Convert handlers to `defineAgentSteps`. Before upgrading, finish or explicitly cancel previously attempted pending/running jobs. Startup refuses to reinterpret such jobs. Once safe, a one-time migration removes the old `foundry_checkpoints` table while preserving native run history and durable conversation artifacts. This migration closes before the native queue opens.
51
+
52
+ ## Limits and verification
53
+
54
+ This does not restore JavaScript stacks, pending permission dialogs or temporary browser/sandbox sessions. Those resources have independent persistence and explicit restore facilities; export artifacts to durable storage. Recovery is bounded by `maxAttempts`; exhausted or unsafe runs remain failed and visible through Foundry's APIs. Native stage completion appears as `run.step.completed`, with no stage inputs or outputs copied into the event.
55
+
56
+ `tests/durable-execution.test.ts` hard-kills the daemon and verifies native step rows, same-run recovery, completed-stage reuse, stable keys, FIFO queue behavior, cancellation, unsafe replay refusal and preview-store retirement without model calls.
@@ -38,7 +38,7 @@ The Glove Foundry and Glove skills guided integration against native primitives
38
38
 
39
39
  | Surface | Result |
40
40
  | --- | --- |
41
- | Entire publish build graph | Passed, including ordered legacy Glovebox dependencies; no publishing command run |
41
+ | Entire publish build graph | Passed; no publishing command run |
42
42
  | Foundry runtime suite | 80 passed, including real completed/cancelled worker process cleanup |
43
43
  | New initializer and existing scaffold tests | 11 passed; terminal policy, flags, piped setup, invalid options, Next.js preservation, versions, and all four package-manager dispatch paths |
44
44
  | Interactive terminal | Selected minimal starter and npm; confirmed generation; separately cancelled with Ctrl+C and verified no output directory |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "glove-foundry",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "An Effect-native, file-routed framework for typed, observable Glove agent applications",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -39,6 +39,10 @@
39
39
  "./station": {
40
40
  "types": "./dist/station.d.ts",
41
41
  "import": "./dist/station.js"
42
+ },
43
+ "./voice": {
44
+ "types": "./dist/voice.d.ts",
45
+ "import": "./dist/voice.js"
42
46
  }
43
47
  },
44
48
  "files": [
@@ -67,23 +71,26 @@
67
71
  "station-signal": "^3.0.0",
68
72
  "station-schedules": "^3.0.0",
69
73
  "tsx": "^4.21.0",
74
+ "ws": "8.19.0",
70
75
  "zod": "^4.3.6",
71
76
  "station-daemon": "^3.0.0",
72
77
  "station-client": "^3.0.0",
73
78
  "station-beacon": "^3.0.0",
74
79
  "station-broadcast": "^3.0.0",
75
- "glove-core": "4.3.0",
76
- "glove-facts": "0.1.4",
77
- "glove-lisp": "0.5.2",
78
- "glove-js": "0.5.2",
79
- "glove-mcp": "1.2.2",
80
- "glove-memory": "2.2.2",
81
- "glove-python": "0.4.2",
82
- "glove-mesh": "0.1.7",
80
+ "glove-facts": "0.1.5",
81
+ "glove-js": "0.5.3",
82
+ "glove-lisp": "0.5.3",
83
+ "glove-core": "4.4.0",
84
+ "glove-memory": "2.3.0",
85
+ "glove-mcp": "1.2.3",
86
+ "glove-mesh": "0.2.0",
87
+ "glove-python": "0.4.3",
88
+ "glove-voice-s2s": "0.4.3",
83
89
  "glove-working-environment": "0.7.0"
84
90
  },
85
91
  "devDependencies": {
86
92
  "@types/node": "^25.2.3",
93
+ "@types/ws": "8.18.1",
87
94
  "tsup": "^8.5.1",
88
95
  "typescript": "^5.9.3"
89
96
  },
@@ -17,7 +17,9 @@ cp .env.example .env.local # add your OPENROUTER_API_KEY
17
17
 
18
18
  Then open **http://127.0.0.1:4141** and press **Start a run**.
19
19
 
20
- Choose **assistant**, send a short request, and open the run to inspect its events.
20
+ Choose **assistant**, ask "What time is it?", and open the run to inspect its events —
21
+ including the `current_time` tool call. Send a follow-up in the same conversation
22
+ (the **Chat** page is easiest): the assistant remembers the earlier turn.
21
23
  Edit `agents/assistant/agent.ts`, save, and run again. The dev server reloads your
22
24
  definition. Run `{{typecheckCommand}}` and `{{lintCommand}}` after changes.
23
25
 
@@ -26,14 +28,22 @@ yourself and restart the dev server. Do not commit the key. If a run fails, chec
26
28
  the trace for authentication or rate-limit errors. If port 4141 is occupied, use
27
29
  the local `glove foundry dev --port 4142` command.
28
30
 
29
- ## Before using real data
31
+ ## Where state lives
30
32
 
31
- The starter uses disposable in-memory storage. Configure durable Foundry runtime
32
- data, a durable Glove conversation store, native memory adapters, and VFS
33
- persistence independently. For a single host, Foundry includes
34
- `FileFoundryDataAdapter`; `glove-memory/sqlite` supports Node 22.13+. Use your own
35
- transactional adapters across hosts. A non-loopback listener requires an
33
+ Foundry runs every message in a fresh process, so nothing an agent needs on the
34
+ next message can live only in memory. The starter keeps it on disk under `.data/`
35
+ (git-ignored):
36
+
37
+ | What | Where | Wired in |
38
+ | --- | --- | --- |
39
+ | Instances, conversations, schedules, workspace data | `.data/foundry.json` | `foundry.application.ts` (`FileFoundryDataAdapter`) |
40
+ | Conversation transcripts | `.data/transcripts/` | `agents/assistant/agent.ts` (`store`, using `lib/file-store.ts`) |
41
+
42
+ State therefore survives the restart `{{devCommand}}` performs on every save. Delete
43
+ `.data/` to start fresh. Both adapters are single-host: use database-backed
44
+ adapters when several hosts share one runtime. A non-loopback listener requires an
36
45
  application-owned `requestAuthorization` adapter and a deliberate network boundary.
46
+ See https://glove.dterminal.net/foundry/docs/persistence.
37
47
 
38
48
  ## The one idea to understand first
39
49
 
@@ -58,7 +68,23 @@ Any file matching these names under an agent folder is discovered automatically.
58
68
  | `layers/*.layer.ts` | Native Glove setup | `defineLayer` |
59
69
  | `subscribers/*.subscriber.ts` | An observer | `defineSubscriber` |
60
70
 
61
- Create the file, add it to `composeAgent(...)`, and the dev server picks it up and regenerates types.
71
+ ### Two ways to add a tool
72
+
73
+ - **Every instance has it:** add a tool object to the agent's `tools` array, like
74
+ `current_time` in `agents/assistant/agent.ts`. Save, and the next run has it.
75
+ - **Instances opt in:** create `agents/assistant/tools/<name>.tool.ts` with
76
+ `defineSharedTool`, list it in the agent's `components: composeAgent(...)`, then
77
+ install it on an instance. Composing makes it *available*, not mounted:
78
+
79
+ ```bash
80
+ curl -X PUT http://127.0.0.1:4141/api/installations \
81
+ -H 'content-type: application/json' \
82
+ -d '{"agentId":"<instance-id>","kind":"tool","id":"<name>"}'
83
+ ```
84
+
85
+ You can also install with `install(...)` when creating an instance in code, or
86
+ `client.install(...)`. The inspector shows installations but does not change them.
87
+ Apps and MCP servers work the same way.
62
88
 
63
89
  Schedules are data, not auto-discovered file routes. You may keep a `defineSchedule`
64
90
  value in an ordinary colocated module and import it into the agent's lazy