@fungi.computer/oyster 0.9.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 (96) hide show
  1. package/README.md +46 -2
  2. package/dist/agents.d.ts +82 -23
  3. package/dist/agents.js +187 -40
  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/computer-control-port.d.ts +20 -1
  24. package/dist/embed-metafiles.d.ts +8 -0
  25. package/dist/embed-metafiles.js +2 -0
  26. package/dist/embed-scripts.d.ts +8 -0
  27. package/dist/embed-scripts.js +3 -0
  28. package/dist/host.d.ts +3 -1
  29. package/dist/host.js +6 -1
  30. package/dist/mcp.d.ts +128 -0
  31. package/dist/mcp.js +63 -1
  32. package/dist/page/embed-challenge.d.ts +19 -0
  33. package/dist/page/embed-challenge.js +45 -0
  34. package/dist/page/embed-error.d.ts +2 -0
  35. package/dist/page/embed-error.js +16 -0
  36. package/dist/page/embed-loader-protocol.d.ts +12 -0
  37. package/dist/page/embed-loader-protocol.js +29 -0
  38. package/dist/standalone/agent-computers.d.ts +12 -1
  39. package/dist/standalone/agent-computers.js +35 -0
  40. package/dist/standalone/agent-connections.d.ts +50 -0
  41. package/dist/standalone/agent-connections.js +214 -0
  42. package/dist/standalone/agent-model-choice.d.ts +7 -3
  43. package/dist/standalone/agent-model-choice.js +33 -4
  44. package/dist/standalone/agents.d.ts +224 -9
  45. package/dist/standalone/agents.js +485 -115
  46. package/dist/standalone/browser.d.ts +16 -3
  47. package/dist/standalone/browser.js +54 -5
  48. package/dist/standalone/channel-session-door.d.ts +4 -0
  49. package/dist/standalone/channel-session-door.js +72 -0
  50. package/dist/standalone/computer-control.js +55 -1
  51. package/dist/standalone/computer-fleet.d.ts +21 -0
  52. package/dist/standalone/computer-fleet.js +30 -6
  53. package/dist/standalone/computer.d.ts +20 -1
  54. package/dist/standalone/computer.js +63 -1
  55. package/dist/standalone/model-key-vault.d.ts +50 -0
  56. package/dist/standalone/model-key-vault.js +147 -0
  57. package/dist/standalone/owner-routes.d.ts +4 -3
  58. package/dist/standalone/owner-routes.js +7 -1
  59. package/dist/standalone/registry.d.ts +23 -0
  60. package/dist/standalone/registry.js +30 -0
  61. package/dist/standalone/visitor-edge.d.ts +36 -0
  62. package/dist/standalone/visitor-edge.js +67 -0
  63. package/dist/standalone/visitor-proof.d.ts +23 -0
  64. package/dist/standalone/visitor-proof.js +67 -0
  65. package/dist/standalone/web.d.ts +10 -0
  66. package/dist/standalone/web.js +34 -0
  67. package/dist/standalone/website-channels.d.ts +134 -0
  68. package/dist/standalone/website-channels.js +262 -0
  69. package/dist/standalone/worker-routes.d.ts +6 -1
  70. package/dist/standalone/worker-routes.js +4 -0
  71. package/dist/standalone/worker.d.ts +2 -1
  72. package/dist/standalone/worker.js +13 -1
  73. package/dist/testing/capabilities.d.ts +3 -0
  74. package/dist/testing/capabilities.js +1 -0
  75. package/dist/testing/installation.d.ts +4 -2
  76. package/dist/testing/installation.js +7 -2
  77. package/dist/web/index.d.ts +3 -0
  78. package/dist/web/index.js +3 -0
  79. package/dist/web/search-contract.d.ts +19 -0
  80. package/dist/web/search-contract.js +14 -0
  81. package/dist/web/search.d.ts +25 -0
  82. package/dist/web/search.js +123 -0
  83. package/dist/web/source.d.ts +46 -0
  84. package/dist/web/source.js +335 -0
  85. package/dist/workers-git.js +3 -2
  86. package/docs/api/agents.md +184 -39
  87. package/docs/api/apps.md +129 -111
  88. package/docs/api/browser.md +115 -8
  89. package/docs/api/build-contract.md +27 -21
  90. package/docs/api/build.md +55 -54
  91. package/docs/api/git.md +3 -3
  92. package/docs/api/host.md +69 -60
  93. package/docs/api/mcp.md +81 -44
  94. package/docs/api/workers-git.md +6 -6
  95. package/docs/api/workers.md +53 -47
  96. package/package.json +52 -22
package/README.md CHANGED
@@ -265,6 +265,19 @@ export OYSTER_OWNER_KEY=$(openssl rand -hex 24)
265
265
  printf '%s' "$OYSTER_OWNER_KEY" | npx wrangler secret put OYSTER_OWNER_KEY
266
266
  ```
267
267
 
268
+ ### Set the credential key (to bring your own model keys)
269
+
270
+ Model API keys you add in Settings are sealed on your Oyster under a 32-byte
271
+ credential key held as a host secret. Generate it at install; it is never in the
272
+ repository, storage or logs. Without it, adding a model key is refused.
273
+
274
+ ```sh
275
+ openssl rand -base64 32 | tr '+/' '-_' | tr -d '=\n' |
276
+ npx wrangler secret put OYSTER_CREDENTIAL_KEY
277
+ ```
278
+
279
+ Keep a copy: losing it makes the sealed keys unreadable, and you re-add them.
280
+
268
281
  ### Install the starter Apps
269
282
 
270
283
  ```sh
@@ -518,8 +531,39 @@ deploy with `wrangler deploy`. Sign in at `/login`.
518
531
  Oyster is owner-only. A browser signs in only with the owner key, through
519
532
  `/login` and its `SameSite=Strict` session cookie. Named keys sign in only by
520
533
  header (`Authorization`), for MCP, Git and the API; no cookie admits a named
521
- key. Anonymous requests reach only `/login`, `robots.txt` and digest-pinned
522
- 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`).
523
567
 
524
568
  The celld example is a limited trial, not the full Cloudflare setup above. It
525
569
  requires access to Fungi's private celld fork. Use
package/dist/agents.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import type { TenantPrincipal } from "./tenant.js";
2
+ import type { ModelKeyRecord, ModelKeyRefusal, ModelKeySealInput } from "./standalone/model-key-vault.js";
3
+ export type { ModelKeyRefusal, ModelKeySealInput, } from "./standalone/model-key-vault.js";
2
4
  import { type Routes } from "./authorization.js";
3
5
  import type { AppToolPolicy } from "./apps/tools.js";
4
6
  import * as Schema from "effect/Schema";
@@ -38,27 +40,51 @@ export type PendingAgentPolicy = Readonly<{
38
40
  status: "pending";
39
41
  revision: string;
40
42
  }>;
41
- /** One remote MCP server connected to an Agent; its bearer token is never returned. */
42
- export type AgentMcpServer = Readonly<{
43
- serverId: string;
44
- /** 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>()`. */
45
49
  name: string;
50
+ label: string;
51
+ kind: "mcp" | "openapi";
46
52
  url: string;
47
- 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
+ }>[];
48
60
  }>;
49
- /** An owner's request to connect one remote MCP server to an Agent. */
50
- export type AgentMcpServerInput = typeof agentMcpServerInputSchema.Type;
51
- /** Why connecting an MCP server was refused. */
52
- export type AgentMcpServerRefusal = Readonly<{
53
- error: "not_found" | "duplicate_name" | "limit";
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;
54
65
  }>;
55
- /** At most this many MCP servers per Agent. */
56
- export declare const maxAgentMcpServers = 16;
57
- /** Owner input for one MCP server: a guest identifier, an `https:` endpoint and an optional bearer. */
58
- export declare const agentMcpServerInputSchema: Schema.Struct<{
66
+ /** Why a connection change was refused. */
67
+ export type ConnectionRefusal = Readonly<{
68
+ error: "not_found" | "duplicate_name" | "limit" | "invalid_endpoint";
69
+ }>;
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<{
59
76
  readonly name: Schema.String;
60
77
  readonly url: Schema.String;
61
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
+ }>>;
62
88
  }>;
63
89
  /** This Agent's App-tool policy, in the shape Apps read it. */
64
90
  export type AgentToolPolicyStatus = Readonly<{
@@ -123,12 +149,40 @@ export type OysterAgents = Readonly<{
123
149
  approveAppToolPolicy(agentId: string, principal: TenantPrincipal, level: AppToolPolicy["level"], expectedRevision: string | null, actor: AgentPolicyActor): Promise<AppToolPolicy | PendingAgentPolicy | Readonly<{
124
150
  error: "not_found" | "revision_conflict" | "not_granted";
125
151
  }>>;
126
- /** An Agent's connected MCP servers, or `null` when there is no such Agent. */
127
- mcpServers(agentId: string): Promise<readonly AgentMcpServer[] | null>;
128
- /** Connect one remote MCP server; the Agent's next run sees its tools. */
129
- addMcpServer(agentId: string, input: AgentMcpServerInput): Promise<AgentMcpServer | AgentMcpServerRefusal>;
130
- /** Disconnect one MCP server; `false` when the Agent or server is unknown. */
131
- removeMcpServer(agentId: string, serverId: string): Promise<boolean>;
152
+ /** The instance's sealed model keys, never their secrets. */
153
+ modelKeys(): Promise<readonly ModelKeyRecord[]>;
154
+ /** Validate with the provider, then seal one key; or an explicit refusal. */
155
+ sealModelKey(input: ModelKeySealInput): Promise<ModelKeyRecord | Readonly<{
156
+ error: ModelKeyRefusal;
157
+ }>>;
158
+ /** Remove one key; Agents that chose it then fail with `key_removed`. */
159
+ removeModelKey(keyId: string): Promise<"deleted" | "absent">;
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;
132
186
  /** Serve this Agent's Shiitake and Knapsack Session browser transports. */
133
187
  fetch(agentId: string, request: Request): Promise<Response | null>;
134
188
  /** This member's Session and Workflow review rows, admitted by the host. */
@@ -143,7 +197,12 @@ export declare function agentCapabilities(agents: OysterAgents): readonly Oyster
143
197
  /** Host-owned direct approval under the admitted owner; never an App capability. */
144
198
  export declare function agentApprovalRoutes(agents: OysterAgents): Routes<OysterEnv>;
145
199
  /**
146
- * Host-owned Agent MCP server custody for the owner directly; never an App
147
- * capability. Bearer tokens go in and never come back out.
200
+ * Host-owned model-key custody for the owner directly. A key goes in once and
201
+ * never comes back out; listings carry provider, label and times only.
202
+ */
203
+ export declare function modelKeyRoutes(agents: OysterAgents): Routes<OysterEnv>;
204
+ /**
205
+ * Host-owned connection custody for the owner directly; never an App
206
+ * capability. Tokens go in and never come back out.
148
207
  */
149
- 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, {
@@ -329,7 +359,16 @@ async function approvePolicy(agents, principal, actor, agentId, body) {
329
359
  }
330
360
  /** Host-owned direct approval under the admitted owner; never an App capability. */
331
361
  export function agentApprovalRoutes(agents) {
332
- return routes()
362
+ return (routes()
363
+ // One owner read for the settings panel: every Agent with its model choice.
364
+ .get("/api/agent-models", owner("direct"), async () => {
365
+ const rows = await Promise.all((await agents.list()).map(async (item) => ({
366
+ agentId: item.agentId,
367
+ name: item.name,
368
+ choice: await agents.readModelChoice(item.agentId),
369
+ })));
370
+ return Response.json({ agents: rows });
371
+ })
333
372
  .get("/api/agent-models/:agentId", owner("direct"), async (context) => {
334
373
  const agentId = context.req.param("agentId");
335
374
  if (!agentIdPattern.test(agentId))
@@ -365,47 +404,155 @@ export function agentApprovalRoutes(agents) {
365
404
  expectedRevision: await agents.policyRevision(agentId),
366
405
  });
367
406
  })
368
- .put("/api/agent-policies/:agentId", owner("direct"), async (context, { principal }) => approvePolicy(agents, principal, "owner-direct", context.req.param("agentId"), await context.req.text()));
407
+ .put("/api/agent-policies/:agentId", owner("direct"), async (context, { principal }) => approvePolicy(agents, principal, "owner-direct", context.req.param("agentId"), await context.req.text())));
369
408
  }
370
- const serverIdPattern = /^[a-z0-9_-]{1,64}$/u;
371
- const mcpRefusalStatus = { not_found: 404, duplicate_name: 409, limit: 409 };
409
+ const keyIdPattern = /^cred_[A-Za-z0-9_-]{1,64}$/u;
410
+ const sealRequestSchema = Schema.Struct({
411
+ provider: Schema.Literals(["anthropic", "openai", "openrouter"]),
412
+ label: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(64)),
413
+ apiKey: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(16_384)),
414
+ });
415
+ const modelKeyRefusalStatus = {
416
+ invalid_key: 400,
417
+ key_rejected: 422,
418
+ provider_unavailable: 502,
419
+ custody_unavailable: 503,
420
+ key_removed: 404,
421
+ target_denied: 400,
422
+ limit: 409,
423
+ };
372
424
  /**
373
- * Host-owned Agent MCP server custody for the owner directly; never an App
374
- * capability. Bearer tokens go in and never come back out.
425
+ * Host-owned model-key custody for the owner directly. A key goes in once and
426
+ * never comes back out; listings carry provider, label and times only.
375
427
  */
376
- export function agentMcpServerRoutes(agents) {
428
+ export function modelKeyRoutes(agents) {
429
+ return routes()
430
+ .get("/api/model-keys", owner("direct"), async () => Response.json({ keys: await agents.modelKeys() }))
431
+ .post("/api/model-keys", owner("direct"), async (context) => {
432
+ const length = Number(context.req.header("content-length") ?? "0");
433
+ if (length > 32 * 1024)
434
+ return refusal(413, "Request too large");
435
+ const input = Schema.decodeUnknownOption(Schema.fromJsonString(sealRequestSchema), { onExcessProperty: "error" })(await context.req.text());
436
+ if (input._tag === "None")
437
+ return refusal(400, "Choose a provider, name the key and paste it");
438
+ const sealed = await agents.sealModelKey(input.value);
439
+ return "error" in sealed
440
+ ? refusal(modelKeyRefusalStatus[sealed.error], sealed.error)
441
+ : Response.json(sealed, { status: 201 });
442
+ })
443
+ .delete("/api/model-keys/:keyId", owner("direct"), async (context) => {
444
+ const keyId = context.req.param("keyId");
445
+ if (!keyIdPattern.test(keyId))
446
+ return refusal(404, "No such key");
447
+ return (await agents.removeModelKey(keyId)) === "deleted"
448
+ ? new Response(null, { status: 204 })
449
+ : refusal(404, "No such key");
450
+ });
451
+ }
452
+ const connectionIdPattern = /^[A-Za-z0-9_.:-]{1,128}$/u;
453
+ const connectionRefusalStatus = {
454
+ not_found: 404,
455
+ duplicate_name: 409,
456
+ limit: 409,
457
+ invalid_endpoint: 400,
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
+ });
466
+ /**
467
+ * Host-owned connection custody for the owner directly; never an App
468
+ * capability. Tokens go in and never come back out.
469
+ */
470
+ export function connectionRoutes(agents) {
377
471
  return (routes()
378
- // One owner read for the settings panel: every Agent with its servers.
379
- .get("/api/agent-mcp-servers", owner("direct"), async () => {
380
- const listed = await agents.list();
381
- const rows = await Promise.all(listed.map(async (item) => ({
382
- agentId: item.agentId,
383
- name: item.name,
384
- servers: (await agents.mcpServers(item.agentId)) ?? [],
385
- })));
386
- 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
+ });
387
483
  })
388
- .post("/api/agent-mcp-servers/:agentId", owner("direct"), async (context) => {
389
- if (!agentIdPattern.test(context.req.param("agentId")))
390
- return refusal(404, "No such agent");
484
+ .post("/api/connections", owner("direct"), async (context) => {
391
485
  const length = Number(context.req.header("content-length") ?? "0");
392
486
  if (length > 16 * 1024)
393
487
  return refusal(413, "Request too large");
394
- 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());
395
489
  if (input._tag === "None")
396
490
  return refusal(400, "Name the server (lowercase letters, digits, _) and give its https:// endpoint");
397
- 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);
398
494
  return "error" in added
399
- ? refusal(mcpRefusalStatus[added.error], added.error)
495
+ ? refusal(connectionRefusalStatus[added.error], added.error)
400
496
  : Response.json(added, { status: 201 });
401
497
  })
402
- .delete("/api/agent-mcp-servers/:agentId/:serverId", owner("direct"), async (context) => {
403
- const serverId = context.req.param("serverId");
404
- if (!agentIdPattern.test(context.req.param("agentId")) ||
405
- !serverIdPattern.test(serverId))
406
- return refusal(404, "No such server");
407
- 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))
408
555
  ? new Response(null, { status: 204 })
409
- : refusal(404, "No such server");
556
+ : refusal(404, "No such connection");
410
557
  }));
411
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>;