glove-foundry 0.7.0 → 0.9.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 CHANGED
@@ -11,6 +11,19 @@ Build guided conversations with first-class, lazy `goals`, `facts`, `forms`, and
11
11
  evidence and answers. See [the guidance handbook](./docs/guidance.md) for scope,
12
12
  durable SQLite setup, preparation, and a runnable example.
13
13
 
14
+ ## Agents are data
15
+
16
+ A definition (`agents/<route>/agent.ts`) is everything a kind of agent can be,
17
+ like a server-rendered page that renders any props. The agents themselves are
18
+ instances, and who each one is lives in data: its `name`, `description`,
19
+ `context`, `installations` and `workspaceId`. Write one `bot` definition, not a
20
+ definition per bot; adding a bot, renaming it or giving it an app is a write
21
+ (`createAgent`, `configureAgent`, `install`), never a deploy. Read names, jobs
22
+ and per-user settings from the instance in resolvers, branch on its data rather
23
+ than its id, and let agents change their own data with tools. Split definitions
24
+ only by what a kind of agent can do or must load. See
25
+ [Agents are data](https://glove.dterminal.net/foundry/docs/agents-are-data).
26
+
14
27
  ## Your first agent application
15
28
 
16
29
  Dependency installation is selected by default in the setup wizard. Foundry runs
@@ -258,6 +271,25 @@ export default defineAgent({
258
271
 
259
272
  Credential acquisition and refresh still belong to `mcpAdapterFor`; persisted installation config should contain only a reference such as an environment-variable or vault-record name.
260
273
 
274
+ ### Apps people connect
275
+
276
+ When each person connects their own account (Gmail, Linear, a calendar), put the provider's MCP server on a Foundry app. The app opens it with the installation's account, decides per tool, and also owns the sends and incoming events:
277
+
278
+ ```ts
279
+ export default defineApp({
280
+ description: "Gmail: read mail, send as the owner, new mail as it arrives",
281
+ outbound: [gmail], // glove_app_gmail__gmail_send, delivered by Foundry after approval
282
+ connections: [gmailWatch], // new mail into a playbook
283
+ mcp: {
284
+ entry: { name: "gmail", description: "Read the owner's mail", url: "https://gmailmcp.googleapis.com/mcp/v1" },
285
+ auth: (session) => ({ authorization: `Bearer ${(session as GoogleSession).accessToken}` }), // inside accountSessions.withSession
286
+ tools: (tool) => (tool.readOnly ? "allow" : "ask"), // or "hide"
287
+ },
288
+ })
289
+ ```
290
+
291
+ Install it with `accountId`. `defineRepl({ programmaticTools: { select: ({ apps }) => apps.flatMap((app) => app.tools.filter((tool) => tool.readOnly)), keepDirect: false } })` gives the reads to the program as `gmail.search_threads(...)` and takes them out of the direct tool list. Keep accounts in your own store and hand Foundry an `AccountDirectory` through `defineApplication({ services })`; `fileTopologyStore(file)` keeps the routes and bindings you write at runtime.
292
+
261
293
  ## Background playbooks and lazy provisioning
262
294
 
263
295
  A playbook is serializable runtime policy. It is composed by an agent resolver or frontend from transmission primitives, then persisted on the instance. Executable normalization, authentication, predicates, serialization, and delivery live on the transmission definition.
@@ -317,7 +349,7 @@ store. Foundry does not fabricate history from retained runs or UI state.
317
349
  ## Least-privilege subagents
318
350
 
319
351
  Subagents may declare fixed tools or project an invocation-time subset from the
320
- fully assembled parent. That lets a delegate inherit an installed application or
352
+ fully assembled parent. That lets a subagent inherit an installed application or
321
353
  MCP read operation without receiving the parent's write/admin surface. The
322
354
  projection is resolved only when the subagent is called, after instance
323
355
  installations and message-dependent assembly have completed.
@@ -325,7 +357,7 @@ installations and message-dependent assembly have completed.
325
357
  ```ts
326
358
  import { getToolJsonSchema } from "glove-core"
327
359
 
328
- // Names of tools the parent has mounted that the delegate may use.
360
+ // Names of tools the parent has mounted that the subagent may use.
329
361
  const READ_ONLY = new Set(["web_search", "web_read", "workspace_read_file"])
330
362
 
331
363
  defineSubagent({
@@ -347,7 +379,7 @@ defineSubagent({
347
379
  The child keeps its isolated store, compaction policy, model, prompt and skills.
348
380
  Its `layers` and `subscribers` mount when the subagent is invoked and are
349
381
  disposed when its request ends. Parent subscribers still receive the subagent
350
- lifecycle bracket, so delegation remains visible in the same run trace.
382
+ lifecycle bracket, so the subagent call remains visible in the same run trace.
351
383
 
352
384
  ## Layered agents: delegates
353
385
 
@@ -401,6 +433,50 @@ delegations appear in the interactor's runtime context, and
401
433
  `runtime.listDelegations()` lists them all. See
402
434
  [`examples/foundry-layered-assistant`](../../examples/foundry-layered-assistant).
403
435
 
436
+ ## Messaging existing agents: the hosted mesh
437
+
438
+ Workers an agent owns belong in `delegates` or `durableSubagents`. When the
439
+ agents are peers that already exist, each its own instance in one workspace (a
440
+ person's bots, say), Foundry can host [Glove Mesh](../glove-mesh) between
441
+ them. `mesh: true` gives an agent `glove_mesh_list_agents`,
442
+ `glove_mesh_send_message`, `glove_mesh_broadcast` and `glove_mesh_acknowledge`,
443
+ and it messages its peers by instance id. Its peers are the other instances in
444
+ its workspace, so who is on a team is data.
445
+
446
+ ```ts
447
+ // agents/bot/agent.ts — one definition; every bot is an instance
448
+ export default defineAgent({
449
+ description: "One of a person's bots",
450
+ model: botModel,
451
+ systemPrompt: botPrompt,
452
+ mesh: { waitMs: 60_000 },
453
+ })
454
+
455
+ // your application — the bots are instances in the person's workspace
456
+ await foundry.createAgent("bot", { id: "ada-sales", workspaceId: "ada", name: "Sales" })
457
+ await foundry.createAgent("bot", { id: "ada-ops", workspaceId: "ada", name: "Ops" })
458
+ ```
459
+
460
+ A new message starts a thread: a conversation on the recipient. The recipient's
461
+ final reply goes back on its own; a failed or cancelled run sends a failure. It
462
+ can ask back with `glove_mesh_send_message`, and the sender answers with
463
+ `in_reply_to`. Messages reach a run that is listening (`ctx.onMeshMessage`, used
464
+ by `voiceCall`) directly. Otherwise they wait until the conversation is free and
465
+ start one run (`source.kind` `"mesh"`) carrying everything that arrived, as
466
+ `<mesh-message>` blocks. A blocking send waits up to `waitMs` (default 90 s)
467
+ inside the same run, so a worker holding a browser or sandbox session keeps it;
468
+ after that the run suspends and the reply starts a new run. Open threads appear
469
+ in the sender's runtime context, and `runtime.listThreads()` lists them.
470
+ Mesh messages ride the same event journal as delegation updates, so they are
471
+ handed over again after a restart.
472
+
473
+ `peers(self, peer)` narrows who an agent may message, from data; an agent can
474
+ always answer whoever messaged it. `mount(ctx)` decides per run whether the
475
+ tools are there, so a scheduled research run can be kept from messaging anyone.
476
+ A `mesh` value with an `adapter` is the raw Glove Mesh transport instead
477
+ (`FoundryMeshConfig`). See
478
+ [`examples/foundry-bot-crew`](../../examples/foundry-bot-crew).
479
+
404
480
  ## Voice calls
405
481
 
406
482
  `glove-foundry/voice` runs an agent as a live call. Use it as the definition's
@@ -417,7 +493,7 @@ run: voiceCall({
417
493
 
418
494
  The call uses the assembled agent's prompt, tools and runtime context, saves
419
495
  what both sides say to the conversation store, and speaks delegation results
420
- and questions at the next pause. Foundry's bookkeeping tools and any tool that
496
+ and questions, and mesh messages, at the next pause. Foundry's bookkeeping tools and any tool that
421
497
  needs an approval stay off the call; delegate that work instead. A room is any
422
498
  `{ open(call), close() }`: `webSocketRoom` serves PCM16 over one WebSocket, and
423
499
  a LiveKit or phone room calls `call.joined()` and `call.left()` the same way.
@@ -251,7 +251,7 @@ async function readJson(path) {
251
251
  function requestRecord(value) {
252
252
  if (!value || typeof value !== "object") return null;
253
253
  const item = value;
254
- const valid = typeof item.id === "string" && COMMAND_ID.test(item.id) && typeof item.runId === "string" && (item.type === "transmit" || item.type === "agent.message") && typeof item.requestedAt === "string" && typeof item.expiresAt === "string";
254
+ const valid = typeof item.id === "string" && COMMAND_ID.test(item.id) && typeof item.runId === "string" && (item.type === "transmit" || item.type === "agent.message" || item.type === "mesh") && typeof item.requestedAt === "string" && typeof item.expiresAt === "string";
255
255
  if (!valid) return null;
256
256
  if (item.command !== void 0) {
257
257
  const command = item.command;
@@ -382,11 +382,11 @@ async function waitForFoundryCoreCommandResult(directory, request, signal, optio
382
382
  }
383
383
  if (signal.aborted) {
384
384
  await cancelFoundryCoreCommandRequest(directory, request.id, "cancelled");
385
- throw new Error("Foundry transmission call was cancelled.");
385
+ throw new Error(request.type === "mesh" ? "The mesh call was cancelled." : "Foundry transmission call was cancelled.");
386
386
  }
387
387
  if (Date.parse(request.expiresAt) <= Date.now()) {
388
388
  await cancelFoundryCoreCommandRequest(directory, request.id, "expired");
389
- throw new Error("Foundry transmission call timed out.");
389
+ throw new Error(request.type === "mesh" ? "The mesh call timed out." : "Foundry transmission call timed out.");
390
390
  }
391
391
  await new Promise((resolveWait) => setTimeout(resolveWait, 50));
392
392
  }
@@ -413,7 +413,7 @@ import { z as z2 } from "zod";
413
413
 
414
414
  // src/capabilities.ts
415
415
  import { Effect as Effect2 } from "effect";
416
- import { mountMcp } from "glove-mcp";
416
+ import { connectMcpEntry, mountMcp, mountMcpToolSet } from "glove-mcp";
417
417
  import {
418
418
  useContext,
419
419
  useEpisodicCurator,
@@ -482,6 +482,9 @@ function defineSharedTool(options) {
482
482
  function defineAgentApplication(options) {
483
483
  if (options.id) assertCapabilityId(options.id, "agent application");
484
484
  const label = options.id ?? "<application file route>";
485
+ if (options.mcp && (!options.mcp.entry || !["object", "function"].includes(typeof options.mcp.entry))) {
486
+ throw new Error(`Application "${label}" declares mcp without an entry.`);
487
+ }
485
488
  const inbound = Object.freeze([...options.inbound ?? []]);
486
489
  const outbound = Object.freeze([...options.outbound ?? []]);
487
490
  for (const transmission of inbound) {
@@ -670,6 +673,89 @@ function mountAgentDefinitionMemory(options) {
670
673
  }
671
674
  });
672
675
  }
676
+ function appNamespace(id) {
677
+ return id.replace(/[^A-Za-z0-9_]/g, "_");
678
+ }
679
+ function mountAppMcp(application, context, options, guard = (tool) => tool) {
680
+ return Effect2.gen(function* () {
681
+ const spec = application.mcp;
682
+ if (spec.auth && !context.withAccountSession) {
683
+ throw new Error(
684
+ `App "${application.id}" connects with an account. Install it with an account and give the agent definition accountSessions.`
685
+ );
686
+ }
687
+ const source = typeof spec.entry === "function" ? spec.entry(context) : spec.entry;
688
+ const resolved = Effect2.isEffect(source) ? yield* source : source instanceof Promise ? yield* Effect2.tryPromise({ try: () => source, catch: (cause) => cause }) : source;
689
+ const entry = identifyMcpEntry(resolved, appNamespace(application.id));
690
+ const credentials = () => Effect2.runPromise(context.withAccountSession(
691
+ "mcp:connect",
692
+ (session) => Effect2.tryPromise({
693
+ try: async () => spec.auth(session, context),
694
+ catch: (cause) => cause
695
+ })
696
+ ));
697
+ const adapter = {
698
+ identifier: `foundry-app:${application.id}`,
699
+ getActive: async () => [entry.id],
700
+ activate: async () => void 0,
701
+ deactivate: async () => void 0,
702
+ ...spec.auth ? entry.transport?.kind === "stdio" ? { getStdioEnvironment: async () => credentials() } : { getAuthHeaders: async () => credentials() } : {}
703
+ };
704
+ const decisions = /* @__PURE__ */ new Map();
705
+ const decide = (tool) => {
706
+ if (application.restrictions && !application.restrictions.tools?.includes(tool.name)) return false;
707
+ const described = {
708
+ name: tool.name,
709
+ ...tool.description ? { description: tool.description } : {},
710
+ readOnly: tool.annotations?.readOnlyHint === true,
711
+ destructive: tool.annotations?.destructiveHint === true
712
+ };
713
+ const decision = spec.tools ? spec.tools(described, context) : described.readOnly ? "allow" : "ask";
714
+ if (decision !== "allow" && decision !== "ask" && decision !== "hide") {
715
+ throw new Error(
716
+ `App "${application.id}" returned "${String(decision)}" for tool "${tool.name}". Return "allow", "ask" or "hide".`
717
+ );
718
+ }
719
+ decisions.set(`${entry.id}__${tool.name}`, { decision, readOnly: described.readOnly });
720
+ return decision !== "hide";
721
+ };
722
+ const toolSet = yield* Effect2.tryPromise({
723
+ try: async () => {
724
+ const connection = await connectMcpEntry({
725
+ adapter,
726
+ entry,
727
+ clientInfo: { name: `glove-foundry:${application.id}`, version: "1" },
728
+ filterTools: decide
729
+ });
730
+ try {
731
+ return await mountMcpToolSet({
732
+ glove: options.context.glove,
733
+ connection,
734
+ entry,
735
+ // Foundry's agents run in server mode, where bridged MCP tools would
736
+ // never ask. The app's decision sets the approval instead.
737
+ wrapTool: (tool) => {
738
+ const decided = decisions.get(tool.name);
739
+ return guard(decided ? { ...tool, requiresPermission: decided.decision === "ask" } : tool);
740
+ }
741
+ });
742
+ } catch (cause) {
743
+ await connection.close().catch(() => void 0);
744
+ throw cause;
745
+ }
746
+ },
747
+ catch: (cause) => cause
748
+ });
749
+ options.onCleanup?.(() => toolSet.dispose());
750
+ options.context.emit({
751
+ type: "foundry.application.mcp.mounted",
752
+ data: { id: application.id, tools: toolSet.toolNames }
753
+ });
754
+ const readOnly = /* @__PURE__ */ new Map();
755
+ for (const [name, decided] of decisions) readOnly.set(name, decided.readOnly);
756
+ return { toolSet, readOnly };
757
+ });
758
+ }
673
759
  function installRegistry(options) {
674
760
  return Effect2.gen(function* () {
675
761
  const tools = indexRegistry(options.registry.tools, "shared tool");
@@ -731,9 +817,23 @@ function installRegistry(options) {
731
817
  const application = definition;
732
818
  const restrictedContext = application.restrictions && headlessContext.withAccountSession ? { ...headlessContext, withAccountSession: (operation, use) => application.restrictions.operations?.includes(operation) ? headlessContext.withAccountSession(operation, use) : Effect2.fail(new Error(`Application "${application.id}" does not permit operation "${operation}".`)) } : headlessContext;
733
819
  const contribution = application.install ? yield* application.install(restrictedContext) : void 0;
734
- for (const tool of contribution?.tools ?? []) {
735
- if (!application.restrictions || application.restrictions.tools?.includes(tool.name)) options.context.glove.fold(guardedTool(tool, installation));
736
- }
820
+ const ownTools = (contribution?.tools ?? []).filter((tool) => !application.restrictions || application.restrictions.tools?.includes(tool.name));
821
+ for (const tool of ownTools) options.context.glove.fold(guardedTool(tool, installation));
822
+ const mounted = application.mcp ? yield* mountAppMcp(application, restrictedContext, options, (tool) => guardedTool(tool, installation)) : void 0;
823
+ options.onApp?.(Object.freeze({
824
+ id: application.id,
825
+ description: application.description,
826
+ ...installation.accountId ? { accountId: installation.accountId } : {},
827
+ get tools() {
828
+ return [
829
+ ...ownTools.map((tool) => ({ name: tool.name })),
830
+ ...(mounted?.toolSet.toolNames ?? []).map((name) => ({
831
+ name,
832
+ readOnly: mounted?.readOnly.get(name) ?? true
833
+ }))
834
+ ];
835
+ }
836
+ }));
737
837
  } else {
738
838
  const mcpDefinition = definition;
739
839
  const headlessContext = (() => {
@@ -939,6 +1039,14 @@ function defineCall(options) {
939
1039
  }
940
1040
  return Object.freeze({ ...options });
941
1041
  }
1042
+ function isMeshTransport(mesh) {
1043
+ if (mesh === void 0 || mesh === true) return false;
1044
+ return typeof mesh === "function" || typeof mesh === "object" && mesh !== null && "adapter" in mesh;
1045
+ }
1046
+ function hostedMeshOptions(mesh) {
1047
+ if (mesh === void 0 || isMeshTransport(mesh)) return void 0;
1048
+ return mesh === true ? {} : mesh;
1049
+ }
942
1050
  var ROUTE_PATTERN = /^[a-z][a-z0-9-]*(?:\/[a-z][a-z0-9-]*)*$/;
943
1051
  function assertAgentRoute(route) {
944
1052
  if (!ROUTE_PATTERN.test(route)) {
@@ -981,6 +1089,20 @@ function validateDefinition(options, route) {
981
1089
  if (options.answerWaitMs !== void 0 && (!Number.isFinite(options.answerWaitMs) || options.answerWaitMs < 0)) {
982
1090
  throw new Error(`Foundry agent "${id ?? "<file route>"}" answerWaitMs must be a non-negative number.`);
983
1091
  }
1092
+ if (options.mesh !== void 0 && options.mesh !== true && !isMeshTransport(options.mesh)) {
1093
+ if (typeof options.mesh !== "object" || options.mesh === null) {
1094
+ throw new Error(`Foundry agent "${id ?? "<file route>"}" mesh must be true, hosted-mesh options, or a mesh config with an adapter.`);
1095
+ }
1096
+ if (options.mesh.mount !== void 0 && typeof options.mesh.mount !== "function") {
1097
+ throw new Error(`Foundry agent "${id ?? "<file route>"}" mesh.mount must be a function of the run's context.`);
1098
+ }
1099
+ if (options.mesh.peers !== void 0 && typeof options.mesh.peers !== "function") {
1100
+ throw new Error(`Foundry agent "${id ?? "<file route>"}" mesh.peers must be a function of (self, peer).`);
1101
+ }
1102
+ if (options.mesh.waitMs !== void 0 && (!Number.isFinite(options.mesh.waitMs) || options.mesh.waitMs < 0)) {
1103
+ throw new Error(`Foundry agent "${id ?? "<file route>"}" mesh.waitMs must be a non-negative number.`);
1104
+ }
1105
+ }
984
1106
  if (options.inboxes !== void 0 && typeof options.inboxes !== "function") {
985
1107
  throw new Error(
986
1108
  `Foundry agent "${id ?? "<file route>"}" inboxes must be a lazy resolver function.`
@@ -1202,6 +1324,8 @@ export {
1202
1324
  FOUNDRY_AGENT_FILE_ENV,
1203
1325
  FOUNDRY_EXECUTION_MARKER,
1204
1326
  defineCall,
1327
+ isMeshTransport,
1328
+ hostedMeshOptions,
1205
1329
  internalAgentName,
1206
1330
  routeFromInternalAgentName,
1207
1331
  isFoundryAgentDefinition,