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
@@ -1,28 +1,42 @@
1
- import { MemoryStore } from "glove-core";
2
1
  import { createAdapter } from "glove-core/models/providers";
3
- import { composeAgent, defineAgent } from "glove-foundry";
4
- import currentTime from "./tools/current-time.tool.js";
2
+ import { defineAgent } from "glove-foundry";
3
+ import { z } from "zod";
4
+ import { FileStore } from "../../lib/file-store.js";
5
5
 
6
6
  /**
7
7
  * The file path is the identity: this is the agent `assistant`.
8
8
  *
9
9
  * Every field may be a value or a function; a function is called per run with
10
- * the request context. Add capabilities as sibling files — `tools/*.tool.ts`,
11
- * `apps/*.app.ts`, `memory/*.memory.ts` — and compose them below.
10
+ * the request context. Each run executes in its own process, so state that must
11
+ * outlive one message — like the conversation below — lives on disk.
12
12
  */
13
13
  export default defineAgent({
14
14
  description: "A general-purpose Glove assistant",
15
- components: composeAgent(currentTime),
16
- store: ({ conversationId }) => new MemoryStore(`assistant:${conversationId}`),
17
15
  model: () => createAdapter({
18
16
  provider: "openrouter",
19
17
  model: process.env.OPENROUTER_MODEL ?? "openai/gpt-4.1-mini",
20
18
  stream: true,
21
19
  }),
22
- systemPrompt: (_agent, { message, history }) => [
20
+
21
+ // Durable history: without it the assistant forgets the previous message.
22
+ store: ({ conversationId }) => FileStore.open(conversationId),
23
+
24
+ systemPrompt: (_agent, { history }) => [
23
25
  "You are a precise, practical assistant.",
24
- `Current request: ${message.text}`,
25
- `Prior messages: ${history.length}`,
26
+ `Prior messages in this conversation: ${history.length}.`,
26
27
  ].join("\n"),
28
+
29
+ // Tools listed here are on every instance of this agent. To make a tool
30
+ // installable per instance instead, put it in tools/<name>.tool.ts with
31
+ // defineSharedTool, add it to composeAgent(...), and install it (see README).
32
+ tools: [{
33
+ name: "current_time",
34
+ description: "Return the current ISO timestamp",
35
+ inputSchema: z.object({}),
36
+ async do() {
37
+ return { status: "success", data: new Date().toISOString() };
38
+ },
39
+ }],
40
+
27
41
  compactionInstructions: () => "Preserve decisions, open work, and important context.",
28
42
  });
@@ -1,7 +1,15 @@
1
- import { MemoryFoundryDataAdapter, defineApplication } from "glove-foundry";
1
+ import { FileFoundryDataAdapter, defineApplication } from "glove-foundry";
2
+ import { fileURLToPath } from "node:url";
2
3
 
3
- /** Swap this adapter for your own to persist instances across restarts. */
4
- export const data = new MemoryFoundryDataAdapter();
4
+ /**
5
+ * Instances, conversations, schedules and workspace data are saved to
6
+ * `.data/foundry.json`, so they survive restarts — including the restart
7
+ * `dev` performs every time you save a file. Delete `.data/` to start fresh.
8
+ * Use a database-backed adapter when several hosts share one runtime.
9
+ */
10
+ export const data = new FileFoundryDataAdapter({
11
+ file: fileURLToPath(new URL("./.data/foundry.json", import.meta.url)),
12
+ });
5
13
 
6
14
  export default defineApplication({
7
15
  name: "{{projectName}}",
@@ -1,3 +1,4 @@
1
1
  node_modules
2
2
  .env.local
3
3
  .foundry/manifest.json
4
+ .data
@@ -0,0 +1,95 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import {
6
+ MemoryStore,
7
+ type InboxItem,
8
+ type Message,
9
+ type Task,
10
+ type TokenConsumptionCounter,
11
+ } from "glove-core";
12
+
13
+ /** Transcripts live in `.data/transcripts`, beside this project's `lib` folder. */
14
+ const TRANSCRIPTS = fileURLToPath(new URL("../.data/transcripts/", import.meta.url));
15
+
16
+ interface SavedConversation {
17
+ readonly messages: Message[];
18
+ readonly turns: number;
19
+ readonly tokens: TokenConsumptionCounter;
20
+ readonly tasks: Task[];
21
+ readonly inbox: InboxItem[];
22
+ }
23
+
24
+ /**
25
+ * Foundry runs every message in a fresh process, so a plain `MemoryStore`
26
+ * would start each turn with no history. This one loads the conversation from
27
+ * a JSON file and rewrites it after every change.
28
+ *
29
+ * One host, one active run per conversation. Replace it with a database-backed
30
+ * StoreAdapter when several hosts share conversations.
31
+ */
32
+ export class FileStore extends MemoryStore {
33
+ private restoring = false;
34
+
35
+ private constructor(conversationId: string, private readonly file: string) {
36
+ super(conversationId);
37
+ }
38
+
39
+ static async open(conversationId: string, directory = TRANSCRIPTS): Promise<FileStore> {
40
+ const name = createHash("sha256").update(conversationId).digest("hex").slice(0, 32);
41
+ const store = new FileStore(conversationId, join(directory, `${name}.json`));
42
+ await store.restore();
43
+ return store;
44
+ }
45
+
46
+ private async restore(): Promise<void> {
47
+ let saved: SavedConversation;
48
+ try {
49
+ saved = JSON.parse(await readFile(this.file, "utf8")) as SavedConversation;
50
+ } catch (error) {
51
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
52
+ throw error;
53
+ }
54
+ this.restoring = true;
55
+ try {
56
+ await this.appendMessages(saved.messages);
57
+ await this.addTokens(saved.tokens);
58
+ for (let turn = 0; turn < saved.turns; turn++) await this.incrementTurn();
59
+ await this.addTasks(saved.tasks);
60
+ for (const item of saved.inbox) await this.addInboxItem(item);
61
+ } finally {
62
+ this.restoring = false;
63
+ }
64
+ }
65
+
66
+ private async save(): Promise<void> {
67
+ if (this.restoring) return;
68
+ const saved: SavedConversation = {
69
+ messages: await this.getMessages(),
70
+ turns: await this.getTurnCount(),
71
+ tokens: await this.getTokenConsumption(),
72
+ tasks: await this.getTasks(),
73
+ inbox: await this.getInboxItems(),
74
+ };
75
+ await mkdir(dirname(this.file), { recursive: true });
76
+ const temporary = `${this.file}.${process.pid}.tmp`;
77
+ await writeFile(temporary, JSON.stringify(saved));
78
+ await rename(temporary, this.file);
79
+ }
80
+
81
+ override async appendMessages(messages: Message[]) { await super.appendMessages(messages); await this.save(); }
82
+ override async addTokens(usage: TokenConsumptionCounter) { await super.addTokens(usage); await this.save(); }
83
+ override async incrementTurn() { await super.incrementTurn(); await this.save(); }
84
+ override async resetCounters() { await super.resetCounters(); await this.save(); }
85
+ override async addTasks(tasks: Task[]) { await super.addTasks(tasks); await this.save(); }
86
+ override async updateTask(id: string, updates: Partial<Pick<Task, "status" | "content" | "activeForm">>) {
87
+ await super.updateTask(id, updates);
88
+ await this.save();
89
+ }
90
+ override async addInboxItem(item: InboxItem) { await super.addInboxItem(item); await this.save(); }
91
+ override async updateInboxItem(id: string, updates: Partial<Pick<InboxItem, "status" | "response" | "resolved_at">>) {
92
+ await super.updateInboxItem(id, updates);
93
+ await this.save();
94
+ }
95
+ }
@@ -19,9 +19,15 @@ cp .env.example .env.local # optional: add OPENROUTER_API_KEY for real answe
19
19
  Then open **http://127.0.0.1:4141** and press **Start a run**.
20
20
 
21
21
  Choose **concierge** and send “Find a flight to Nairobi.” Open the resulting run
22
- to follow its model calls, tool calls and result. This is a deterministic demo:
23
- flights, calendar and messaging are examples, not live provider integrations.
24
- Change `agents/concierge/agent.ts`, save, and try another run to see the reload.
22
+ to follow its model calls, the `find_flights` tool call and the result. Send a
23
+ follow-up in the same conversation (the **Chat** page is easiest): the concierge
24
+ remembers the earlier turn. This is a deterministic demo: flights, calendar and
25
+ messaging are examples, not live provider integrations. Change
26
+ `agents/concierge/agent.ts`, save, and try another run to see the reload.
27
+
28
+ The run drawer creates a new instance by default. Pick **concierge-demo** instead
29
+ to use the seeded instance that has the calendar app and currency tool installed
30
+ and may reply over chat — see [Send it a chat message](#send-it-a-chat-message).
25
31
 
26
32
  To get live model answers, put your own `OPENROUTER_API_KEY` in `.env.local`, then
27
33
  restart the dev server. Never commit that file. The wizard does not collect keys.
@@ -33,7 +39,7 @@ Setting a model key does not connect a real calendar or messenger by itself.
33
39
  - Run `{{installCommand}}` again if installation was interrupted; project files are retained.
34
40
  - If port 4141 is occupied, run the local `glove foundry dev --port 4142` command and open that address.
35
41
  - If a run fails, open its event trace; a provider rate limit is different from a typecheck failure.
36
- - In-memory demo state resets across workers/restarts. Read **Going to production** before storing real user work.
42
+ - State lives in `.data/` and survives restarts. Delete `.data/` to start fresh (for example after renaming an installed tool). Read **Going to production** before storing real user work.
37
43
 
38
44
  ---
39
45
 
@@ -57,23 +63,28 @@ One definition serves many instances. Two travellers can run the same concierge
57
63
  ```
58
64
  agents/concierge/
59
65
  agent.ts the agent. start here
60
- composition.ts composeAgent(...) — what it is built from
61
- tools/find-flights.tool.ts a shared tool
66
+ composition.ts composeAgent(...) — the installable catalogue
67
+ flights.ts find_flights: always on, every instance
68
+ tools/convert-currency.tool.ts a shared tool an instance installs
62
69
  apps/calendar.app.ts an application an instance installs
70
+ instances.ts the seeded concierge-demo instance + its binding
63
71
  transmissions/messaging.transmission.ts Telegram/WhatsApp-shaped transport
64
72
  events/message-received.event.ts an inbound event
65
73
  events/message-sent.event.ts an outbound event
66
74
  predicates/mentions-trip.predicate.ts routing logic, kept out of the agent
67
- memory/traveller.memory.ts ambient context across conversations
75
+ memory/traveller.memory.ts ambient context, saved per instance
68
76
  schedules/trip-countdown.ts recurring work
69
77
  layers/trip-context.layer.ts direct access to the native Glove runtime
70
78
  subscribers/usage.subscriber.ts observation without behaviour change
71
- workbench.ts the agent's VFS + JavaScript REPL
79
+ workbench.ts the agent's VFS (persisted) + JavaScript REPL
72
80
  topology.ts accounts and routes (runtime data)
73
81
 
74
- foundry.application.ts data adapter, accounts, routes
82
+ foundry.application.ts data adapter, accounts, routes, bindings
75
83
  foundry.config.ts port, execution policy
76
84
  lib/demo-model.ts keyless model — delete once you have a key
85
+ lib/file-store.ts durable conversation transcripts
86
+ lib/file-context.ts durable traveller memory
87
+ .data/ runtime state (git-ignored). delete to reset
77
88
  src/client.ts a typed client for these agents
78
89
  .foundry/routes.d.ts generated. do not edit
79
90
  ```
@@ -105,7 +116,10 @@ Assembly fields such as tools, memory, and schedules accept **a value or a funct
105
116
 
106
117
  ### Add a tool
107
118
 
108
- Create `agents/concierge/tools/weather.tool.ts`, default-export `defineSharedTool({...})`, then add it to `composition.ts`. That is the whole loop — the dev server picks it up and regenerates types.
119
+ Two ways, depending on who should have it:
120
+
121
+ - **Every instance:** export a plain tool object and add it to the agent's `tools` field, like `find_flights` in `flights.ts`.
122
+ - **Instances that opt in:** create `agents/concierge/tools/weather.tool.ts`, default-export `defineSharedTool({...})`, add it to `composition.ts`, and install it on an instance (below), like `convert-currency`. Composing makes it available; installing mounts it.
109
123
 
110
124
  ### Add a second agent
111
125
 
@@ -113,7 +127,7 @@ Create `agents/<name>/agent.ts`. It is immediately routable, appears in the insp
113
127
 
114
128
  ### Give an instance a capability
115
129
 
116
- Applications and MCP servers stay inert until an instance installs one. From the inspector, open the instance and install `calendar`; or over the API:
130
+ Shared tools, applications and MCP servers stay inert until an instance installs them. `instances.ts` seeds `concierge-demo` with `convert-currency` and `calendar` installed. To install on another instance, use the API (the inspector shows installations but does not change them):
117
131
 
118
132
  ```bash
119
133
  curl -X PUT http://127.0.0.1:4141/api/installations \
@@ -121,6 +135,26 @@ curl -X PUT http://127.0.0.1:4141/api/installations \
121
135
  -d '{"agentId":"<instance-id>","kind":"application","id":"calendar","config":{"calendarId":"primary"}}'
122
136
  ```
123
137
 
138
+ ### Send it a chat message
139
+
140
+ The calendar app owns the messaging transmission, and `concierge-demo` has both the
141
+ app installed and a **binding** (in `instances.ts`) that lets it reply on the
142
+ outbound route. Its `traveller-chat` playbook is written onto the instance during
143
+ its first run, so send it one message first (Chat page, or **Start a run** with
144
+ `concierge-demo` selected). Then deliver an inbound chat message:
145
+
146
+ ```bash
147
+ curl -X POST http://127.0.0.1:4141/api/transmissions/traveller-inbound/fire \
148
+ -H 'content-type: application/json' \
149
+ -d '{"eventId":"evt-1","threadKey":"thread-42","raw":{"threadId":"thread-42","text":"Any flight to Nairobi in April?"}}'
150
+ ```
151
+
152
+ The message mentions a flight, so the playbook matches and starts a run. The agent
153
+ searches flights and replies through the generated `glove_app_calendar__messaging_send`
154
+ tool; the demo transport prints `[telegram] -> thread-42: …` in the terminal running
155
+ `{{devCommand}}`. An instance without the binding cannot send: delivery fails with
156
+ "agent has no enabled bindings".
157
+
124
158
  ### Connect a real chat app
125
159
 
126
160
  `transmissions/messaging.transmission.ts` has the shape; only `deliver` needs a real call.
@@ -190,7 +224,7 @@ Filters live in the URL, so `/runs?status=failed` is a link you can send. Press
190
224
 
191
225
  ## Going to production
192
226
 
193
- 1. **Persist each store.** `MemoryFoundryDataAdapter` in `foundry.application.ts` is disposable. Use `FileFoundryDataAdapter` for single-host runtime data or a transactional database adapter for multiple hosts. Also replace the agent's `MemoryStore` with a durable conversation store, provide durable native memory adapters (such as `glove-memory/sqlite` on Node 22.13+), and persist the working-environment VFS. Persisting one does not persist the others.
227
+ 1. **Choose where state lives.** Each run executes in its own process, so everything the next message needs is on disk under `.data/`: runtime data (`FileFoundryDataAdapter`), transcripts (`lib/file-store.ts`), traveller memory (`lib/file-context.ts`) and the VFS (`foundryDataEnvironmentPersistence`). These are single-host. For several hosts, replace each with a database-backed adapter — persisting one does not persist the others. See [Persistence](https://glove.dterminal.net/foundry/docs/persistence).
194
228
  2. **Delete `lib/demo-model.ts`** and the fallback in `agent.ts` once `OPENROUTER_API_KEY` is set.
195
229
  3. **Own your credentials.** Foundry stores account *references*, never secrets. Keep tokens in your own adapter or secret manager.
196
230
  4. **Run `{{startCommand}}`** rather than `dev` — no file watching, no restart-on-change.
@@ -1,12 +1,13 @@
1
- import { MemoryStore } from "glove-core";
2
1
  import { createAdapter } from "glove-core/models/providers";
3
2
  import { composePlaybook, defineAgent } from "glove-foundry";
4
3
  import { DemoModel } from "../../lib/demo-model.js";
4
+ import { FileStore } from "../../lib/file-store.js";
5
5
  import reply from "./actions/reply.action.js";
6
6
  import calendar from "./apps/calendar.app.js";
7
7
  import { conciergeComponents } from "./composition.js";
8
8
  import messageReceived from "./events/message-received.event.js";
9
9
  import messageSent from "./events/message-sent.event.js";
10
+ import { findFlights } from "./flights.js";
10
11
  import tripContext from "./layers/trip-context.layer.js";
11
12
  import travellerMemory from "./memory/traveller.memory.js";
12
13
  import mentionsTrip from "./predicates/mentions-trip.predicate.js";
@@ -67,15 +68,20 @@ export default defineAgent({
67
68
  tags: ["travel", "example"],
68
69
  components: conciergeComponents,
69
70
 
70
- // Persisted context, per conversation.
71
+ // Each run executes in its own process, so anything that must outlive one
72
+ // message lives on disk: the transcript here, traveller memory in memory/.
71
73
  memory: [travellerMemory],
72
- store: ({ conversationId }) => new MemoryStore(`concierge:${conversationId}`),
74
+ store: ({ conversationId }) => FileStore.open(conversationId),
73
75
  model,
74
76
 
77
+ // Always on: every instance can search flights. Installable capabilities
78
+ // (calendar, convert-currency) mount only where an instance installed them.
79
+ tools: [findFlights],
80
+
75
81
  // The prompt is built per run, so it can name what is actually mounted.
76
82
  systemPrompt: (_agent, { message, history, installations }) => [
77
83
  "You are a travel concierge. You are practical and you never invent bookings.",
78
- "Use find_flights for availability, and the calendar tools before proposing dates.",
84
+ "Use find_flights for availability, and the calendar tools (when installed) before proposing dates.",
79
85
  `Traveller asked: ${message.text}`,
80
86
  `Prior messages: ${history.length}.`,
81
87
  `Installed for this instance: ${installations.map((item) => `${item.kind}:${item.id}`).join(", ") || "nothing yet"}.`,
@@ -3,15 +3,22 @@ import calendar from "./apps/calendar.app.js";
3
3
  import tripContext from "./layers/trip-context.layer.js";
4
4
  import travellerMemory from "./memory/traveller.memory.js";
5
5
  import usage from "./subscribers/usage.subscriber.js";
6
- import findFlights from "./tools/find-flights.tool.js";
6
+ import convertCurrency from "./tools/convert-currency.tool.js";
7
7
 
8
8
  /**
9
+ * The catalogue: everything this agent's instances are *allowed* to use.
10
+ *
11
+ * - `calendar` and `convertCurrency` are installable. They mount only on an
12
+ * instance that installs them (see instances.ts).
13
+ * - `travellerMemory`, `tripContext` and `usage` are definition surfaces; they
14
+ * are also selected in agent.ts (`memory`, `layers`, `subscribers`).
15
+ *
9
16
  * Composition is by value, not by string id. Rename a file and the import
10
17
  * breaks at compile time instead of failing at runtime.
11
18
  */
12
19
  export const conciergeComponents = composeAgent(
13
20
  calendar,
14
- findFlights,
21
+ convertCurrency,
15
22
  travellerMemory,
16
23
  tripContext,
17
24
  usage,
@@ -0,0 +1,43 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * Searching flights is the concierge's core job, so the tool lives in the
5
+ * agent's `tools` field: every instance has it, nothing to install. Compare
6
+ * `tools/convert-currency.tool.ts`, which an instance opts into.
7
+ *
8
+ * The sample data is deliberately local so a fresh project runs offline.
9
+ * Replace `search` with a call to your own inventory or a provider API.
10
+ */
11
+ const SAMPLE_FLIGHTS = [
12
+ { carrier: "Kestrel Air", from: "LIS", to: "NBO", depart: "08:40", hours: 9.5, price: 612 },
13
+ { carrier: "Meridian", from: "LIS", to: "NBO", depart: "13:15", hours: 11, price: 494 },
14
+ { carrier: "Northwind", from: "LIS", to: "NBO", depart: "22:05", hours: 9, price: 738 },
15
+ ] as const;
16
+
17
+ function search(from: string, to: string, maxPrice: number) {
18
+ const origin = from.trim().toUpperCase();
19
+ const destination = to.trim().toUpperCase();
20
+ return SAMPLE_FLIGHTS.filter((flight) =>
21
+ (!origin || flight.from === origin) &&
22
+ (!destination || flight.to === destination) &&
23
+ flight.price <= maxPrice
24
+ );
25
+ }
26
+
27
+ export const findFlights = {
28
+ name: "find_flights",
29
+ description:
30
+ "Search flights between two IATA airport codes. Returns carrier, departure time, duration and price in USD.",
31
+ inputSchema: z.object({
32
+ from: z.string().describe("Origin IATA code, for example LIS"),
33
+ to: z.string().describe("Destination IATA code, for example NBO"),
34
+ maxPrice: z.number().default(5_000).describe("Highest acceptable price in USD"),
35
+ }),
36
+ async do({ from, to, maxPrice }: { from: string; to: string; maxPrice: number }) {
37
+ const matches = search(from, to, maxPrice);
38
+ if (matches.length === 0) {
39
+ return { status: "success" as const, data: { matches: [], note: "No flight matched those constraints." } };
40
+ }
41
+ return { status: "success" as const, data: { matches } };
42
+ },
43
+ };
@@ -0,0 +1,42 @@
1
+ import { defineAgentInstance, defineBinding, install } from "glove-foundry";
2
+ import concierge from "./agent.js";
3
+ import calendar from "./apps/calendar.app.js";
4
+ import convertCurrency from "./tools/convert-currency.tool.js";
5
+ import { travellerAccount, travellerOutbound } from "./topology.js";
6
+ import messaging, { sendMessage } from "./transmissions/messaging.transmission.js";
7
+
8
+ /**
9
+ * A ready-made instance, seeded into the data adapter on first start
10
+ * (foundry.application.ts). It has what a new instance created from the
11
+ * inspector does not: installed capabilities and permission to reply.
12
+ *
13
+ * Choose `concierge-demo` in the inspector's run drawer or WebChat to use it.
14
+ */
15
+ export const conciergeDemo = defineAgentInstance(concierge, {
16
+ id: "concierge-demo",
17
+ workspaceId: "demo",
18
+ context: { budgetUsd: 2_500 },
19
+ installations: [
20
+ install(convertCurrency, { home: "EUR" }),
21
+ install(calendar, { calendarId: "primary", timezone: "Europe/Lisbon" }, { account: travellerAccount }),
22
+ ],
23
+ // Filled in by agent.ts's `playbooks` resolver on this instance's first run.
24
+ playbooks: [],
25
+ });
26
+
27
+ /**
28
+ * Outbound messages need a binding: the runtime's record that this instance
29
+ * may send through this route. Without one, a reply fails with
30
+ * "agent has no enabled bindings".
31
+ */
32
+ export const conciergeDemoReplies = defineBinding({
33
+ id: "concierge-demo-replies",
34
+ agent: conciergeDemo,
35
+ application: calendar,
36
+ transmission: messaging,
37
+ account: travellerAccount,
38
+ route: travellerOutbound,
39
+ capabilities: [sendMessage],
40
+ reply: { mode: "route", route: travellerOutbound },
41
+ enabled: true,
42
+ });
@@ -1,19 +1,24 @@
1
1
  import { Effect } from "effect";
2
2
  import { defineMemory } from "glove-foundry";
3
- import { MemorySchema } from "glove-memory/core";
4
- import { InMemoryContextAdapter } from "glove-memory/in-memory";
3
+ import { fileURLToPath } from "node:url";
4
+ import { FileContextAdapter } from "../../../lib/file-context.js";
5
5
 
6
6
  /**
7
- * Ambient context the concierge should carry between conversations: seat
8
- * preference, home airport, who is travelling. The adapter is replaceable —
9
- * point it at a durable store when you outgrow the in-memory one.
7
+ * Ambient context the concierge carries between conversations: seat
8
+ * preference, home airport, who is travelling. One file per agent instance, so
9
+ * two travellers never share a profile. The model reads it every turn and can
10
+ * update it with the context tools.
10
11
  */
11
- const schema = new MemorySchema();
12
- const context = new InMemoryContextAdapter({ schema });
12
+ const directory = new URL("../../../.data/memory/", import.meta.url);
13
13
 
14
14
  const travellerMemory = defineMemory({
15
15
  description: "What we already know about this traveller",
16
- context: { adapter: () => Effect.succeed(context) },
16
+ context: {
17
+ adapter: ({ agentId }) =>
18
+ Effect.promise(() =>
19
+ FileContextAdapter.open(fileURLToPath(new URL(`${encodeURIComponent(agentId)}.json`, directory))),
20
+ ),
21
+ },
17
22
  });
18
23
 
19
24
  export default travellerMemory;
@@ -0,0 +1,34 @@
1
+ import { Effect } from "effect";
2
+ import { defineSharedTool } from "glove-foundry";
3
+ import { z } from "zod";
4
+
5
+ /**
6
+ * A shared tool is installable: it is in the agent's catalogue (composition.ts)
7
+ * but mounts only on instances that install it — see `instances.ts`, where the
8
+ * demo instance installs it with a home currency. One file, one default export,
9
+ * and the filename is the id: `convert-currency`.
10
+ *
11
+ * The rates are fixed sample values. Replace `RATES` with a live rate source.
12
+ */
13
+ const RATES: Readonly<Record<string, number>> = { USD: 1, EUR: 0.92, GBP: 0.79, KES: 129 };
14
+
15
+ const convertCurrency = defineSharedTool({
16
+ description: "Convert a USD price into the traveller's home currency",
17
+ config: z.object({ home: z.enum(["USD", "EUR", "GBP", "KES"]).default("USD") }),
18
+ create: ({ config }) => Effect.sync(() => {
19
+ const rate = RATES[config.home]!;
20
+ return {
21
+ name: "convert_currency",
22
+ description: `Convert an amount in USD into ${config.home}, the traveller's home currency.`,
23
+ inputSchema: z.object({ amountUsd: z.number().describe("Price in USD") }),
24
+ async do({ amountUsd }: { amountUsd: number }) {
25
+ return {
26
+ status: "success" as const,
27
+ data: { currency: config.home, amount: Math.round(amountUsd * rate * 100) / 100, rate },
28
+ };
29
+ },
30
+ };
31
+ }),
32
+ });
33
+
34
+ export default convertCurrency;
@@ -1,5 +1,5 @@
1
1
  import { JsSession, defineFn } from "glove-js";
2
- import { defineRepl, defineWorkingEnvironment } from "glove-foundry";
2
+ import { defineRepl, defineWorkingEnvironment, foundryDataEnvironmentPersistence } from "glove-foundry";
3
3
  import { z } from "zod";
4
4
 
5
5
  /**
@@ -11,6 +11,9 @@ import { z } from "zod";
11
11
  */
12
12
  export const conciergeWorkspace = defineWorkingEnvironment({
13
13
  options: { limits: { maxVfsBytes: 16 * 1024 * 1024 } },
14
+ // The environment closes after every run; this snapshots its files into the
15
+ // data adapter and restores them on the next run of the same instance.
16
+ persistence: foundryDataEnvironmentPersistence({ scope: "agent" }),
14
17
  });
15
18
 
16
19
  export function conciergeRepl(actor: string, budgetUsd: number) {
@@ -1,18 +1,27 @@
1
- import { MemoryFoundryDataAdapter, defineApplication } from "glove-foundry";
1
+ import { FileFoundryDataAdapter, defineApplication } from "glove-foundry";
2
+ import { fileURLToPath } from "node:url";
3
+ import { conciergeDemo, conciergeDemoReplies } from "./agents/concierge/instances.js";
2
4
  import { travellerAccount, travellerInbound, travellerOutbound } from "./agents/concierge/topology.js";
3
5
 
4
6
  /**
5
7
  * The application is where runtime data enters: which adapter persists
6
- * instances, which accounts and routes exist. `MemoryFoundryDataAdapter` keeps
7
- * everything in process, so restarting `pnpm dev` starts clean. Swap it for
8
- * your own adapter to persist across restarts.
8
+ * instances, which accounts, routes and bindings exist.
9
+ *
10
+ * Instances, conversations, schedules, workspace data and the concierge's VFS
11
+ * are saved to `.data/foundry.json`, so they survive restarts — including the
12
+ * restart `dev` performs every time you save a file. `conciergeDemo` is seeded
13
+ * on first start. Delete `.data/` to start fresh. Use a database-backed adapter
14
+ * when several hosts share one runtime.
9
15
  */
10
- export const data = new MemoryFoundryDataAdapter();
16
+ export const data = new FileFoundryDataAdapter({
17
+ file: fileURLToPath(new URL("./.data/foundry.json", import.meta.url)),
18
+ agents: [conciergeDemo],
19
+ });
11
20
 
12
21
  export default defineApplication({
13
22
  name: "{{projectName}}",
14
23
  data,
15
24
  accounts: [travellerAccount],
16
25
  routes: [travellerInbound, travellerOutbound],
17
- bindings: [],
26
+ bindings: [conciergeDemoReplies],
18
27
  });
@@ -1,3 +1,4 @@
1
1
  node_modules
2
2
  .env.local
3
3
  .foundry/manifest.json
4
+ .data