@fungi.computer/oyster 0.10.0 → 0.11.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 (63) hide show
  1. package/README.md +33 -2
  2. package/dist/agents.d.ts +66 -22
  3. package/dist/agents.js +128 -38
  4. package/dist/authorization.d.ts +25 -3
  5. package/dist/authorization.js +47 -14
  6. package/dist/browser/capability-source.d.ts +23 -5
  7. package/dist/browser/capability-source.js +19 -22
  8. package/dist/browser/index.d.ts +2 -1
  9. package/dist/browser/index.js +1 -0
  10. package/dist/browser/live-view.d.ts +38 -0
  11. package/dist/browser/live-view.js +179 -0
  12. package/dist/channels/binding.d.ts +2 -0
  13. package/dist/channels/run-decision.d.ts +33 -0
  14. package/dist/channels/run-decision.js +25 -0
  15. package/dist/channels/visitor-channel.d.ts +84 -14
  16. package/dist/channels/visitor-channel.js +55 -32
  17. package/dist/channels/visitor-edge.d.ts +18 -2
  18. package/dist/channels/visitor-edge.js +67 -5
  19. package/dist/channels/visitors.d.ts +4 -0
  20. package/dist/channels/visitors.js +22 -1
  21. package/dist/channels/web-binding.d.ts +117 -0
  22. package/dist/channels/web-binding.js +227 -0
  23. package/dist/embed-metafiles.d.ts +8 -0
  24. package/dist/embed-metafiles.js +2 -0
  25. package/dist/embed-scripts.d.ts +8 -0
  26. package/dist/embed-scripts.js +3 -0
  27. package/dist/host.d.ts +3 -1
  28. package/dist/host.js +6 -1
  29. package/dist/page/embed-challenge.d.ts +19 -0
  30. package/dist/page/embed-challenge.js +45 -0
  31. package/dist/page/embed-error.d.ts +2 -0
  32. package/dist/page/embed-error.js +16 -0
  33. package/dist/page/embed-loader-protocol.d.ts +12 -0
  34. package/dist/page/embed-loader-protocol.js +29 -0
  35. package/dist/standalone/agent-connections.d.ts +22 -19
  36. package/dist/standalone/agent-connections.js +150 -106
  37. package/dist/standalone/agents.d.ts +168 -14
  38. package/dist/standalone/agents.js +310 -17
  39. package/dist/standalone/browser.d.ts +14 -2
  40. package/dist/standalone/browser.js +52 -4
  41. package/dist/standalone/channel-session-door.d.ts +4 -0
  42. package/dist/standalone/channel-session-door.js +72 -0
  43. package/dist/standalone/owner-routes.d.ts +4 -3
  44. package/dist/standalone/owner-routes.js +7 -1
  45. package/dist/standalone/visitor-edge.d.ts +36 -0
  46. package/dist/standalone/visitor-edge.js +67 -0
  47. package/dist/standalone/visitor-proof.d.ts +23 -0
  48. package/dist/standalone/visitor-proof.js +67 -0
  49. package/dist/standalone/website-channels.d.ts +134 -0
  50. package/dist/standalone/website-channels.js +262 -0
  51. package/dist/standalone/worker-routes.d.ts +4 -1
  52. package/dist/standalone/worker-routes.js +3 -0
  53. package/dist/standalone/worker.d.ts +2 -1
  54. package/dist/standalone/worker.js +4 -0
  55. package/dist/testing/capabilities.d.ts +3 -0
  56. package/dist/testing/capabilities.js +1 -0
  57. package/dist/testing/installation.d.ts +4 -2
  58. package/dist/testing/installation.js +7 -2
  59. package/dist/workers-git.js +2 -2
  60. package/docs/api/agents.md +103 -36
  61. package/docs/api/browser.md +115 -8
  62. package/docs/api/workers-git.md +6 -6
  63. package/package.json +31 -6
package/README.md CHANGED
@@ -531,8 +531,39 @@ deploy with `wrangler deploy`. Sign in at `/login`.
531
531
  Oyster is owner-only. A browser signs in only with the owner key, through
532
532
  `/login` and its `SameSite=Strict` session cookie. Named keys sign in only by
533
533
  header (`Authorization`), for MCP, Git and the API; no cookie admits a named
534
- key. Anonymous requests reach only `/login`, `robots.txt` and digest-pinned
535
- shell and App UI bytes.
534
+ key. Anonymous requests reach only `/login`, `robots.txt`, digest-pinned shell
535
+ and App UI bytes, and the website chat described next.
536
+
537
+ ### Website chat on a separate site
538
+
539
+ Owner-only means only the owner signs in to Oyster; it does not stop you from
540
+ putting an Agent on a public website. In Settings, choose Channels, then Add
541
+ website: pick the Agent, give the address of your site and a brief, and paste
542
+ the script tag Oyster shows you into that site:
543
+
544
+ ```html
545
+ <script
546
+ src="https://your-oyster.example/embed/v1.js"
547
+ data-site="site_pk_…"
548
+ data-theme="auto"
549
+ async
550
+ ></script>
551
+ ```
552
+
553
+ Visitors are anonymous channel parties of that one Agent, never Oyster
554
+ principals, keys or App callers. They talk to the Agent itself, with its own
555
+ tools and permissions and the persona you wrote added to its instructions; they
556
+ cannot sign in to Oyster or reach your account. Each site has its own key, a
557
+ list of allowed origins, rate limits per visitor and per network address, and a
558
+ pause switch; a new site key stops the old code at once. The same page can
559
+ require a Cloudflare Turnstile check before a visitor can chat, and shows the
560
+ conversations so you can read what visitors said.
561
+
562
+ The surface is closed until you set two host secrets, each at least 32 bytes:
563
+ `OYSTER_WEBSITE_PROOF_KEY` signs a visitor's identity between the public edge
564
+ and the website Agent, and `OYSTER_WEBSITE_ADDRESS_KEY` salts the hashed network
565
+ address used for rate limits. For Turnstile, set `TURNSTILE_SITE_KEY` and
566
+ `TURNSTILE_SECRET_KEY` (or `TURNSTILE=off` for local use over `http`).
536
567
 
537
568
  The celld example is a limited trial, not the full Cloudflare setup above. It
538
569
  requires access to Fungi's private celld fork. Use
package/dist/agents.d.ts CHANGED
@@ -40,27 +40,51 @@ export type PendingAgentPolicy = Readonly<{
40
40
  status: "pending";
41
41
  revision: string;
42
42
  }>;
43
- /** One remote MCP server connected to an Agent; its bearer token is never returned. */
44
- export type AgentMcpServer = Readonly<{
45
- serverId: string;
46
- /** The guest calls this server's tools as `env.mcp.<name>.<tool>()`. */
43
+ /** What an Agent may do with one connection: everything, only reads, or named tools. */
44
+ export type ConnectionAccess = "all" | "read" | readonly string[];
45
+ /** One connection as its owner sees it; no secret, locator or token ever appears. */
46
+ export type OysterConnection = Readonly<{
47
+ connectionId: string;
48
+ /** The guest calls an MCP server's tools as `env.mcp.<name>.<tool>()`. */
47
49
  name: string;
50
+ label: string;
51
+ kind: "mcp" | "openapi";
48
52
  url: string;
49
- hasBearer: boolean;
53
+ auth: "none" | "token" | "oauth";
54
+ /** `pending` waits for the owner to sign in at the server; `reconnect_required` needs a new sign-in. */
55
+ state: "connected" | "pending" | "reconnect_required";
56
+ grants: readonly Readonly<{
57
+ agentId: string;
58
+ access: ConnectionAccess;
59
+ }>[];
50
60
  }>;
51
- /** An owner's request to connect one remote MCP server to an Agent. */
52
- export type AgentMcpServerInput = typeof agentMcpServerInputSchema.Type;
53
- /** Why connecting an MCP server was refused. */
54
- export type AgentMcpServerRefusal = Readonly<{
61
+ /** A newly added connection; `authorizeUrl` is where the owner signs in, when the server uses OAuth. */
62
+ export type ConnectionAdded = Readonly<{
63
+ connectionId: string;
64
+ authorizeUrl: string | null;
65
+ }>;
66
+ /** Why a connection change was refused. */
67
+ export type ConnectionRefusal = Readonly<{
55
68
  error: "not_found" | "duplicate_name" | "limit" | "invalid_endpoint";
56
69
  }>;
57
- /** At most this many MCP servers per Agent. */
58
- export declare const maxAgentMcpServers = 16;
59
- /** Owner input for one MCP server: a guest identifier, an `https:` endpoint and an optional bearer. */
60
- export declare const agentMcpServerInputSchema: Schema.Struct<{
70
+ /** An owner's request to connect one remote MCP server. */
71
+ export type ConnectionInput = typeof connectionInputSchema.Type;
72
+ /** At most this many connections per Agent. */
73
+ export declare const maxAgentConnections = 16;
74
+ /** Owner input for one MCP connection: a guest identifier, an `https:` endpoint and an optional bearer. */
75
+ export declare const connectionInputSchema: Schema.Struct<{
61
76
  readonly name: Schema.String;
62
77
  readonly url: Schema.String;
63
78
  readonly bearer: Schema.NullOr<Schema.String>;
79
+ /**
80
+ * Sign in at the server instead of pasting a token. Without a client the
81
+ * server's dynamic registration is used; with one, the secret is sealed.
82
+ */
83
+ readonly oauth: Schema.optional<Schema.Struct<{
84
+ readonly clientId: Schema.optional<Schema.String>;
85
+ readonly clientSecret: Schema.optional<Schema.String>;
86
+ readonly scope: Schema.optional<Schema.String>;
87
+ }>>;
64
88
  }>;
65
89
  /** This Agent's App-tool policy, in the shape Apps read it. */
66
90
  export type AgentToolPolicyStatus = Readonly<{
@@ -133,12 +157,32 @@ export type OysterAgents = Readonly<{
133
157
  }>>;
134
158
  /** Remove one key; Agents that chose it then fail with `key_removed`. */
135
159
  removeModelKey(keyId: string): Promise<"deleted" | "absent">;
136
- /** An Agent's connected MCP servers, or `null` when there is no such Agent. */
137
- mcpServers(agentId: string): Promise<readonly AgentMcpServer[] | null>;
138
- /** Connect one remote MCP server; the Agent's next run sees its tools. */
139
- addMcpServer(agentId: string, input: AgentMcpServerInput): Promise<AgentMcpServer | AgentMcpServerRefusal>;
140
- /** Disconnect one MCP server; `false` when the Agent or server is unknown. */
141
- removeMcpServer(agentId: string, serverId: string): Promise<boolean>;
160
+ /** Every connection with the Agents that may use it. */
161
+ connections(): Promise<readonly OysterConnection[]>;
162
+ /** Connect one remote MCP server; no Agent has it until the owner grants it. */
163
+ addConnection(input: ConnectionInput): Promise<ConnectionAdded | ConnectionRefusal>;
164
+ /** Give an Agent access to a connection, or change how much it has. */
165
+ grantConnection(connectionId: string, agentId: string, access: ConnectionAccess): Promise<Readonly<{
166
+ ok: true;
167
+ }> | ConnectionRefusal>;
168
+ /** End one Agent's access; `false` when it had none. */
169
+ ungrantConnection(connectionId: string, agentId: string): Promise<boolean>;
170
+ /** Disconnect for everyone; `false` when the connection is unknown. */
171
+ removeConnection(connectionId: string): Promise<boolean>;
172
+ /** The tool names an MCP connection offers, for choosing a narrower grant. */
173
+ connectionTools(connectionId: string): Promise<readonly string[] | ConnectionRefusal>;
174
+ /** Settle a sign-in: the authorization server's redirect, by state and code. */
175
+ completeMcpConnection(query: Readonly<{
176
+ state: string;
177
+ code: string;
178
+ iss: string | undefined;
179
+ }>): Promise<Readonly<{
180
+ ok: true;
181
+ }> | Readonly<{
182
+ error: string;
183
+ }>>;
184
+ /** The exact redirect URL an owner registers with an OAuth app. */
185
+ mcpCallbackUrl(): string;
142
186
  /** Serve this Agent's Shiitake and Knapsack Session browser transports. */
143
187
  fetch(agentId: string, request: Request): Promise<Response | null>;
144
188
  /** This member's Session and Workflow review rows, admitted by the host. */
@@ -158,7 +202,7 @@ export declare function agentApprovalRoutes(agents: OysterAgents): Routes<Oyster
158
202
  */
159
203
  export declare function modelKeyRoutes(agents: OysterAgents): Routes<OysterEnv>;
160
204
  /**
161
- * Host-owned Agent MCP server custody for the owner directly; never an App
162
- * capability. Bearer tokens go in and never come back out.
205
+ * Host-owned connection custody for the owner directly; never an App
206
+ * capability. Tokens go in and never come back out.
163
207
  */
164
- export declare function agentMcpServerRoutes(agents: OysterAgents): Routes<OysterEnv>;
208
+ export declare function connectionRoutes(agents: OysterAgents): Routes<OysterEnv>;
package/dist/agents.js CHANGED
@@ -5,10 +5,10 @@ import {} from "./host.js";
5
5
  import { agentAvatarSchema } from "./agent-avatars.js";
6
6
  import { computerTargetParam } from "./computer-target.js";
7
7
  import { agentAvatar, agentList, agentManage, agentRename, agentSessionRead, agentSessionWrite, agentToolPolicy, } from "@fungi.computer/agar/agents";
8
- /** At most this many MCP servers per Agent. */
9
- export const maxAgentMcpServers = 16;
10
- /** Owner input for one MCP server: a guest identifier, an `https:` endpoint and an optional bearer. */
11
- export const agentMcpServerInputSchema = Schema.Struct({
8
+ /** At most this many connections per Agent. */
9
+ export const maxAgentConnections = 16;
10
+ /** Owner input for one MCP connection: a guest identifier, an `https:` endpoint and an optional bearer. */
11
+ export const connectionInputSchema = Schema.Struct({
12
12
  name: Schema.String.check(Schema.isPattern(/^[a-z][a-z0-9_]{0,31}$/u)),
13
13
  url: Schema.String.check(Schema.isMaxLength(2_048), Schema.makeFilter((value) => {
14
14
  if (!URL.canParse(value))
@@ -22,6 +22,15 @@ export const agentMcpServerInputSchema = Schema.Struct({
22
22
  : "Use an https:// MCP endpoint without credentials or a fragment";
23
23
  })),
24
24
  bearer: Schema.NullOr(Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(4_096), Schema.isPattern(/^[\x21-\x7e]+$/u))),
25
+ /**
26
+ * Sign in at the server instead of pasting a token. Without a client the
27
+ * server's dynamic registration is used; with one, the secret is sealed.
28
+ */
29
+ oauth: Schema.optional(Schema.Struct({
30
+ clientId: Schema.optional(Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(512))),
31
+ clientSecret: Schema.optional(Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(4_096), Schema.isPattern(/^[\x21-\x7e]+$/u))),
32
+ scope: Schema.optional(Schema.String.check(Schema.isMaxLength(512), Schema.isPattern(/^[\x21-\x7e ]+$/u))),
33
+ })),
25
34
  });
26
35
  const createSchema = Schema.Struct({
27
36
  name: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)),
@@ -64,7 +73,9 @@ export function agentCapabilities(agents) {
64
73
  {
65
74
  ...shared,
66
75
  id: "agent.manage",
67
- ownerDirect: ownerAgentRoutes(agents, "direct"),
76
+ ownerDirect: routes()
77
+ .include(ownerAgentRoutes(agents, "direct"))
78
+ .include(cloudBrowserViewRoutes(agents)),
68
79
  permission: "agent.manage",
69
80
  version: agentManage.version,
70
81
  methods: {
@@ -135,6 +146,21 @@ export function agentCapabilities(agents) {
135
146
  },
136
147
  ];
137
148
  }
149
+ /**
150
+ * The person's live view of a paused cloud-browser lease: the owner, direct
151
+ * only (never an App acting for them), served by the Agent that holds the lease.
152
+ */
153
+ function cloudBrowserViewRoutes(agents) {
154
+ return routes().on(["GET", "POST"], "/agents/:agentId/cloud-browser/*", owner("direct"), async (context) => {
155
+ const agentId = context.req.param("agentId");
156
+ if (!agentIdPattern.test(agentId))
157
+ return refusal(404, "No such agent");
158
+ const incoming = context.req.raw;
159
+ const path = new URL(incoming.url).pathname.slice(`/agents/${agentId}`.length);
160
+ const response = await agents.fetch(agentId, new Request(`https://agent.internal${path}`, incoming));
161
+ return response ?? refusal(404, "No such agent");
162
+ });
163
+ }
138
164
  /** The owner capability: create, archive and restore, never Session transport. */
139
165
  function ownerAgentRoutes(agents, via) {
140
166
  return routes()
@@ -151,8 +177,8 @@ function ownerAgentRoutes(agents, via) {
151
177
  // are approved the same way direct owner approval is, with no second path.
152
178
  return Response.json(await agents.create(body.value.name, body.value.requestId, principal, "owner-direct", avatar?.data));
153
179
  })
154
- .post("/agents/:agentId/archive", owner(via), (context, { principal }) => changeArchive(agents, context.req.param("agentId"), true, principal))
155
- .post("/agents/:agentId/unarchive", owner(via), (context, { principal }) => changeArchive(agents, context.req.param("agentId"), false, principal));
180
+ .post("/agents/:agentId/archive", owner(via), (context, admission) => changeArchive(agents, context.req.param("agentId"), true, admission))
181
+ .post("/agents/:agentId/unarchive", owner(via), (context, admission) => changeArchive(agents, context.req.param("agentId"), false, admission));
156
182
  }
157
183
  function createAgentRoutes(agents) {
158
184
  return (routes()
@@ -230,9 +256,9 @@ function createAgentRoutes(agents) {
230
256
  const response = await agents.fetch(agentId, new Request(target, incoming));
231
257
  return response ?? refusal(404, "No such agent");
232
258
  })
233
- .get("/member/inbox", agentCollection(), async (_context, { authority, reaches }) => {
259
+ .get("/member/inbox", agentCollection(), async (_context, { authority, everyAgent, reaches }) => {
234
260
  const inbox = await agents.inbox();
235
- if (authority.kind === "owner")
261
+ if (everyAgent)
236
262
  return Response.json({
237
263
  items: inbox.items,
238
264
  next: null,
@@ -247,7 +273,9 @@ function createAgentRoutes(agents) {
247
273
  next: null,
248
274
  // The global revision changes for ungranted Agents too. Key feeds have
249
275
  // no scoped event stream, so expose neither that revision nor its events.
250
- cursor: 0,
276
+ // An owner's narrowed App keeps the owner's change stream, which
277
+ // announces only a `reset`, so it keeps the revision that stream resumes from.
278
+ cursor: authority.kind === "owner" ? inbox.revision : 0,
251
279
  });
252
280
  })
253
281
  .get("/member/inbox/notices", owner("direct-or-app"), () => Response.json({ items: [], next: null }))
@@ -292,9 +320,11 @@ function createAgentRoutes(agents) {
292
320
  }));
293
321
  }
294
322
  /** Owner-only archive transition; creator Agents use their own control tool. */
295
- async function changeArchive(agents, agentId, archived, principal) {
323
+ async function changeArchive(agents, agentId, archived, { principal, delegatesAgent }) {
296
324
  if (!agentIdPattern.test(agentId))
297
325
  return refusal(404, "No such agent");
326
+ if (!delegatesAgent(agentId))
327
+ return refusal(403, "Agent access denied");
298
328
  const result = await agents.setArchived(agentId, archived, principal);
299
329
  if ("error" in result)
300
330
  return Response.json(result, {
@@ -419,50 +449,110 @@ export function modelKeyRoutes(agents) {
419
449
  : refusal(404, "No such key");
420
450
  });
421
451
  }
422
- const serverIdPattern = /^[a-z0-9_-]{1,64}$/u;
423
- const mcpRefusalStatus = {
452
+ const connectionIdPattern = /^[A-Za-z0-9_.:-]{1,128}$/u;
453
+ const connectionRefusalStatus = {
424
454
  not_found: 404,
425
455
  duplicate_name: 409,
426
456
  limit: 409,
427
457
  invalid_endpoint: 400,
428
458
  };
459
+ const accessSchema = Schema.Struct({
460
+ access: Schema.Union([
461
+ Schema.Literal("all"),
462
+ Schema.Literal("read"),
463
+ Schema.Array(Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256))).check(Schema.isMaxLength(256)),
464
+ ]),
465
+ });
429
466
  /**
430
- * Host-owned Agent MCP server custody for the owner directly; never an App
431
- * capability. Bearer tokens go in and never come back out.
467
+ * Host-owned connection custody for the owner directly; never an App
468
+ * capability. Tokens go in and never come back out.
432
469
  */
433
- export function agentMcpServerRoutes(agents) {
470
+ export function connectionRoutes(agents) {
434
471
  return (routes()
435
- // One owner read for the settings panel: every Agent with its servers.
436
- .get("/api/agent-mcp-servers", owner("direct"), async () => {
437
- const listed = await agents.list();
438
- const rows = await Promise.all(listed.map(async (item) => ({
439
- agentId: item.agentId,
440
- name: item.name,
441
- servers: (await agents.mcpServers(item.agentId)) ?? [],
442
- })));
443
- return Response.json({ agents: rows });
472
+ // One owner read for the settings panel: every connection and every Agent.
473
+ .get("/api/connections", owner("direct"), async () => {
474
+ const [connections, listed] = await Promise.all([
475
+ agents.connections(),
476
+ agents.list(),
477
+ ]);
478
+ return Response.json({
479
+ callbackUrl: agents.mcpCallbackUrl(),
480
+ agents: listed.map(({ agentId, name }) => ({ agentId, name })),
481
+ connections,
482
+ });
444
483
  })
445
- .post("/api/agent-mcp-servers/:agentId", owner("direct"), async (context) => {
446
- if (!agentIdPattern.test(context.req.param("agentId")))
447
- return refusal(404, "No such agent");
484
+ .post("/api/connections", owner("direct"), async (context) => {
448
485
  const length = Number(context.req.header("content-length") ?? "0");
449
486
  if (length > 16 * 1024)
450
487
  return refusal(413, "Request too large");
451
- const input = Schema.decodeUnknownOption(Schema.fromJsonString(agentMcpServerInputSchema), { onExcessProperty: "error" })(await context.req.text());
488
+ const input = Schema.decodeUnknownOption(Schema.fromJsonString(connectionInputSchema), { onExcessProperty: "error" })(await context.req.text());
452
489
  if (input._tag === "None")
453
490
  return refusal(400, "Name the server (lowercase letters, digits, _) and give its https:// endpoint");
454
- const added = await agents.addMcpServer(context.req.param("agentId"), input.value);
491
+ if (input.value.oauth !== undefined && input.value.bearer !== null)
492
+ return refusal(400, "Choose a token or sign-in, not both");
493
+ const added = await agents.addConnection(input.value);
455
494
  return "error" in added
456
- ? refusal(mcpRefusalStatus[added.error], added.error)
495
+ ? refusal(connectionRefusalStatus[added.error], added.error)
457
496
  : Response.json(added, { status: 201 });
458
497
  })
459
- .delete("/api/agent-mcp-servers/:agentId/:serverId", owner("direct"), async (context) => {
460
- const serverId = context.req.param("serverId");
461
- if (!agentIdPattern.test(context.req.param("agentId")) ||
462
- !serverIdPattern.test(serverId))
463
- return refusal(404, "No such server");
464
- return (await agents.removeMcpServer(context.req.param("agentId"), serverId))
498
+ // The authorization server's redirect: the owner's browser, signed in.
499
+ .get("/api/connections/callback", owner("direct"), async (context) => {
500
+ const query = context.req.query();
501
+ if (query.error !== undefined ||
502
+ query.state === undefined ||
503
+ query.code === undefined)
504
+ return refusal(400, "The sign-in was not completed");
505
+ const settled = await agents.completeMcpConnection({
506
+ state: query.state,
507
+ code: query.code,
508
+ iss: query.iss,
509
+ });
510
+ return "error" in settled
511
+ ? refusal(400, "The sign-in could not be completed")
512
+ : new Response(null, { status: 303, headers: { location: "/" } });
513
+ })
514
+ .get("/api/connections/:connectionId/tools", owner("direct"), async (context) => {
515
+ const connectionId = context.req.param("connectionId");
516
+ if (!connectionIdPattern.test(connectionId))
517
+ return refusal(404, "No such connection");
518
+ const tools = await agents.connectionTools(connectionId);
519
+ return "error" in tools
520
+ ? refusal(connectionRefusalStatus[tools.error], tools.error)
521
+ : Response.json({ tools });
522
+ })
523
+ .put("/api/connections/:connectionId/agents/:agentId", owner("direct"), async (context) => {
524
+ const connectionId = context.req.param("connectionId");
525
+ const agentId = context.req.param("agentId");
526
+ if (!connectionIdPattern.test(connectionId) ||
527
+ !agentIdPattern.test(agentId))
528
+ return refusal(404, "No such connection");
529
+ const length = Number(context.req.header("content-length") ?? "0");
530
+ if (length > 64 * 1024)
531
+ return refusal(413, "Request too large");
532
+ const input = Schema.decodeUnknownOption(Schema.fromJsonString(accessSchema), { onExcessProperty: "error" })(await context.req.text());
533
+ if (input._tag === "None")
534
+ return refusal(400, "Choose all, read, or a list of tools");
535
+ const granted = await agents.grantConnection(connectionId, agentId, input.value.access);
536
+ return "error" in granted
537
+ ? refusal(connectionRefusalStatus[granted.error], granted.error)
538
+ : new Response(null, { status: 204 });
539
+ })
540
+ .delete("/api/connections/:connectionId/agents/:agentId", owner("direct"), async (context) => {
541
+ const connectionId = context.req.param("connectionId");
542
+ const agentId = context.req.param("agentId");
543
+ if (!connectionIdPattern.test(connectionId) ||
544
+ !agentIdPattern.test(agentId))
545
+ return refusal(404, "No such connection");
546
+ return (await agents.ungrantConnection(connectionId, agentId))
547
+ ? new Response(null, { status: 204 })
548
+ : refusal(404, "No such access");
549
+ })
550
+ .delete("/api/connections/:connectionId", owner("direct"), async (context) => {
551
+ const connectionId = context.req.param("connectionId");
552
+ if (!connectionIdPattern.test(connectionId))
553
+ return refusal(404, "No such connection");
554
+ return (await agents.removeConnection(connectionId))
465
555
  ? new Response(null, { status: 204 })
466
- : refusal(404, "No such server");
556
+ : refusal(404, "No such connection");
467
557
  }));
468
558
  }
@@ -16,6 +16,7 @@ import { Hono, type Context, type Env, type ErrorHandler } from "hono";
16
16
  import type { MiddlewareHandler } from "hono/types";
17
17
  import * as Schema from "effect/Schema";
18
18
  import type { HostActor } from "@fungi.computer/puffball/app";
19
+ import type { ApprovedGrant } from "./apps/installation.js";
19
20
  import type { AppToolPolicy } from "./apps/tools.js";
20
21
  import { type LiveOysterKey } from "./keys.js";
21
22
  import type { CapabilityEnv, OysterAuthResult, OysterHost } from "./host.js";
@@ -119,8 +120,18 @@ export type RequestFacts = Readonly<{
119
120
  principal: () => Promise<OysterAuthResult>;
120
121
  /** Whether an App sent this request (the page bridge, or any capability call). */
121
122
  mediated: boolean;
123
+ /** The Agents this request's delegated App grant selects. */
124
+ agents: AgentCeiling;
122
125
  ports: AuthorityPorts;
123
126
  }>;
127
+ /**
128
+ * The Agents an App's admitted capability grant reaches: every Agent its
129
+ * principal reaches, or exactly the selected ones. A request no App
130
+ * capability narrowed carries `"all"`; principal reach still decides.
131
+ */
132
+ export type AgentCeiling = "all" | ReadonlySet<string>;
133
+ /** An admitted grant's resources as an Agent ceiling; a non-Agent selection reaches no Agent. */
134
+ export declare function agentCeiling(resources: ApprovedGrant["resources"]): AgentCeiling;
124
135
  /** Every requirement kind; the law test proves each has both outcomes. */
125
136
  export type RequirementKind = "public" | "door" | "owner" | "member" | "app" | "apps" | "agent" | "agents" | "computer";
126
137
  /** How the law and the host table read one route's requirement. */
@@ -162,6 +173,8 @@ export type OwnerOrigin = "owner-direct" | "app";
162
173
  export type OwnerAdmission = Readonly<{
163
174
  principal: OwnerPrincipal;
164
175
  origin: OwnerOrigin;
176
+ /** Whether the App grant that carried this request selects this Agent. */
177
+ delegatesAgent: (agentId: string) => boolean;
165
178
  }>;
166
179
  /**
167
180
  * The owner only. `direct` also refuses an App-mediated request (one the
@@ -202,8 +215,16 @@ export type AgentAdmission = Readonly<{
202
215
  * the owner, or a key granted `agents.use` for that Agent id.
203
216
  */
204
217
  export declare function agent(id?: (facts: RequestFacts) => Promise<string | null>): Requirement<AgentAdmission>;
205
- /** Agents (and their inbox rows): the owner sees all, a key its granted Agents. */
206
- export declare function agents(): Requirement<CollectionAdmission<string>>;
218
+ /** What an Agent collection route receives. */
219
+ export type AgentCollectionAdmission = CollectionAdmission<string> & Readonly<{
220
+ /** Whether {@link CollectionAdmission.reaches} admits every Agent, so nothing needs filtering. */
221
+ everyAgent: boolean;
222
+ }>;
223
+ /**
224
+ * Agents (and their inbox rows): the owner sees all, a key its granted
225
+ * Agents, and either only within the App grant that carried the request.
226
+ */
227
+ export declare function agents(): Requirement<AgentCollectionAdmission>;
207
228
  /** The host's Computer, its workspace files and media: see {@link reachesComputer}. */
208
229
  export declare function computer(): Requirement<Readonly<{
209
230
  principal: TenantPrincipal;
@@ -302,6 +323,7 @@ export declare function serveDoors<E extends Env>(table: Routes<E>): ServedTable
302
323
  * admission, read from `c.env`: the App already holds the capability, and
303
324
  * each route still decides its own resource. Every request here is
304
325
  * App-mediated, however it was admitted (a header or a browser socket's
305
- * query), so `owner("direct")` always refuses inside a capability.
326
+ * query), so `owner("direct")` always refuses inside a capability, and
327
+ * every Agent decision stays within the admitted grant's selection.
306
328
  */
307
329
  export declare function serveCapability(table: Routes<CapabilityEnv>, ports: AuthorityPorts): ServedTable<CapabilityEnv>;
@@ -145,6 +145,15 @@ export function allowsMachineEnrollment(key) {
145
145
  key.grants[0]?.capability === "machine.enroll" &&
146
146
  oysterKeyVocabulary.grantsAllow(key.grants, "machine.enroll"));
147
147
  }
148
+ /** An admitted grant's resources as an Agent ceiling; a non-Agent selection reaches no Agent. */
149
+ export function agentCeiling(resources) {
150
+ return resources === "tenant-scope"
151
+ ? "all"
152
+ : new Set(resources.flatMap((resource) => resource.kind === "agent" ? [resource.id] : []));
153
+ }
154
+ function withinCeiling(ceiling, agentId) {
155
+ return ceiling === "all" || ceiling.has(agentId);
156
+ }
148
157
  /** A refusal this module returns before any handler runs. */
149
158
  function refused(status, error) {
150
159
  return Response.json({ error }, { status });
@@ -224,7 +233,11 @@ export function owner(via) {
224
233
  const origin = facts.mediated ? "app" : "owner-direct";
225
234
  if (via === "direct" && origin === "app")
226
235
  return refused(403, "Owner direct only");
227
- return { principal, origin };
236
+ return {
237
+ principal,
238
+ origin,
239
+ delegatesAgent: (agentId) => withinCeiling(facts.agents, agentId),
240
+ };
228
241
  });
229
242
  }
230
243
  /**
@@ -280,12 +293,16 @@ export function agent(id = (facts) => Promise.resolve(facts.param("agentId") ??
280
293
  const agentId = await id(facts);
281
294
  if (agentId === null)
282
295
  return refused(400, "Name the Agent");
283
- if (!reachesAgent(authority, agentId))
296
+ if (!reachesAgent(authority, agentId) ||
297
+ !withinCeiling(facts.agents, agentId))
284
298
  return refused(403, "Agent access denied");
285
299
  return { authority, principal: authority.principal, agentId };
286
300
  });
287
301
  }
288
- /** Agents (and their inbox rows): the owner sees all, a key its granted Agents. */
302
+ /**
303
+ * Agents (and their inbox rows): the owner sees all, a key its granted
304
+ * Agents, and either only within the App grant that carried the request.
305
+ */
289
306
  export function agents() {
290
307
  return requirement({ kind: "agents" }, async (facts) => {
291
308
  const authority = await signedInAuthority(facts);
@@ -293,7 +310,9 @@ export function agents() {
293
310
  return authority;
294
311
  return {
295
312
  authority,
296
- reaches: (agentId) => Promise.resolve(reachesAgent(authority, agentId)),
313
+ everyAgent: authority.kind === "owner" && facts.agents === "all",
314
+ reaches: (agentId) => Promise.resolve(reachesAgent(authority, agentId) &&
315
+ withinCeiling(facts.agents, agentId)),
297
316
  };
298
317
  });
299
318
  }
@@ -390,7 +409,7 @@ export class Routes {
390
409
  this.#entries.push({
391
410
  kind: "route",
392
411
  declaration: { methods, path, requirement: record.declared },
393
- mount: (hono, principal, ports, mediated) => {
412
+ mount: (hono, principal, ports, delegation) => {
394
413
  // One admission per request, shared down the middleware chain.
395
414
  const admittedFor = new WeakMap();
396
415
  const gate = async (context, next) => {
@@ -402,7 +421,7 @@ export class Routes {
402
421
  return decoded._tag === "Some" ? decoded.value : null;
403
422
  },
404
423
  principal: () => principal(context),
405
- mediated: mediated(context.req.raw),
424
+ ...delegation(context),
406
425
  ports,
407
426
  });
408
427
  if (admitted instanceof Response)
@@ -441,8 +460,14 @@ export function routes() {
441
460
  function declarationsOf(table) {
442
461
  return recordOf(table).entries.flatMap((entry) => entry.kind === "route" ? [entry.declaration] : declarationsOf(entry.table));
443
462
  }
444
- /** The page bridge names the installation an App call comes from. */
445
- const bridged = (request) => request.headers.has("X-Oyster-Installation");
463
+ /**
464
+ * The page bridge names the installation an App call comes from. A host
465
+ * route it reaches is no capability, so no capability grant narrows it.
466
+ */
467
+ const bridged = (context) => ({
468
+ mediated: context.req.raw.headers.has("X-Oyster-Installation"),
469
+ agents: "all",
470
+ });
446
471
  /**
447
472
  * Serve one table: the only `Hono` the Oyster host builds. Each route runs
448
473
  * its requirement first, then its middleware, then its handler. Nothing a
@@ -488,10 +513,10 @@ function serveTable(table, principal, ports, rules) {
488
513
  hono.route("/", serveTable(entry.table, principal, ports, {
489
514
  headers: [],
490
515
  serverTiming: null,
491
- mediated: rules.mediated,
516
+ delegation: rules.delegation,
492
517
  }));
493
518
  else
494
- entry.mount(hono, principal, ports, rules.mediated);
519
+ entry.mount(hono, principal, ports, rules.delegation);
495
520
  const handler = errorHandler();
496
521
  if (handler !== undefined)
497
522
  hono.onError(handler);
@@ -519,7 +544,7 @@ export function serveHost(table, authenticate, ports, options = {}) {
519
544
  serverTiming: Object.hasOwn(options, "serverTiming")
520
545
  ? (options.serverTiming ?? null)
521
546
  : null,
522
- mediated: bridged,
547
+ delegation: bridged,
523
548
  }));
524
549
  }
525
550
  /**
@@ -528,15 +553,23 @@ export function serveHost(table, authenticate, ports, options = {}) {
528
553
  * principal is refused, never admitted.
529
554
  */
530
555
  export function serveDoors(table) {
531
- return servedView(serveTable(table, () => Promise.resolve({ kind: "refused", status: 401 }), { liveKey: () => Promise.resolve(null), appToolPolicy: () => null }, { headers: [], serverTiming: null, mediated: bridged }));
556
+ return servedView(serveTable(table, () => Promise.resolve({ kind: "refused", status: 401 }), { liveKey: () => Promise.resolve(null), appToolPolicy: () => null }, { headers: [], serverTiming: null, delegation: bridged }));
532
557
  }
533
558
  /**
534
559
  * Serve one capability's declared table under the host dispatcher's
535
560
  * admission, read from `c.env`: the App already holds the capability, and
536
561
  * each route still decides its own resource. Every request here is
537
562
  * App-mediated, however it was admitted (a header or a browser socket's
538
- * query), so `owner("direct")` always refuses inside a capability.
563
+ * query), so `owner("direct")` always refuses inside a capability, and
564
+ * every Agent decision stays within the admitted grant's selection.
539
565
  */
540
566
  export function serveCapability(table, ports) {
541
- return servedView(serveTable(table, (context) => Promise.resolve({ kind: "admitted", principal: context.env.principal }), ports, { headers: [], serverTiming: null, mediated: () => true }));
567
+ return servedView(serveTable(table, (context) => Promise.resolve({ kind: "admitted", principal: context.env.principal }), ports, {
568
+ headers: [],
569
+ serverTiming: null,
570
+ delegation: (context) => ({
571
+ mediated: true,
572
+ agents: agentCeiling(context.env.grant.resources),
573
+ }),
574
+ }));
542
575
  }