@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
@@ -7,6 +7,15 @@ import { AgentArchiveRefused, AgentCreateRefused, } from "@fungi.computer/shiita
7
7
  import { AgentDelegation, AgentDisclosureRefused, machineAgentCodecs, } from "@fungi.computer/shiitake/delegation";
8
8
  import { FungiMessageMetaSchema } from "@fungi.computer/agar/agents";
9
9
  import { agentMail } from "./agent-mail.js";
10
+ import { createChannelConversations, } from "../channels/conversations.js";
11
+ import { transcriptLine, } from "@fungi.computer/nacre/website-channels";
12
+ import { personChannelInstructions, } from "../channels/web-binding.js";
13
+ import { decideChannelRunSafely } from "../channels/run-decision.js";
14
+ import { createWebsiteChannelOwner, websiteOutcome, } from "./website-channels.js";
15
+ import { channelSessionDoor } from "./channel-session-door.js";
16
+ import { createAuthenticatedVisitorChannel } from "../channels/visitor-channel.js";
17
+ import { verifyVisitor } from "./visitor-proof.js";
18
+ import { createVisitorStreamSlots } from "../channels/visitor-stream-slots.js";
10
19
  import { createStandaloneMachineEnrollment, standaloneMachineAgentHome, standaloneMachineLinkAuthority, } from "./machine-link.js";
11
20
  import { createMachineLinkFences, MachineEnrollmentRefused, MachineLinkRefused, createMachineAgentClient, } from "../machine-link/index.js";
12
21
  import { memberInboxItemSchema } from "@fungi.computer/puffball/inbox";
@@ -20,16 +29,18 @@ import { memberInboxItemSchema } from "@fungi.computer/puffball/inbox";
20
29
  import { agentDirectoryForScope } from "./agent-directory.js";
21
30
  import { createAgentComputers, } from "../agent-computers.js";
22
31
  import { createAgentComputerSource, readAgentComputerConnections, } from "../agent-computer-source.js";
23
- import { standaloneAgentComputerPorts, } from "./agent-computers.js";
32
+ import { standaloneAgentComputerPorts, standaloneBrowserSave, } from "./agent-computers.js";
24
33
  import { FleetGrantRefused, } from "@fungi.computer/computer/fleet";
25
34
  import { homeExtension, homeGrant, } from "@fungi.computer/shiitake-extensions/home/host";
26
35
  import { homeContract } from "@fungi.computer/shiitake-extensions/home";
27
36
  import { DurableObject } from "cloudflare:workers";
28
37
  import { ShiitakeDO } from "@fungi.computer/shiitake/cloudflare";
29
38
  import { agentStoreKeeping } from "./agent-store.js";
39
+ import { createInstanceCredentialStore, createModelKeyVault, ModelKeyRefused, } from "./model-key-vault.js";
30
40
  import { agentArchiveOwner } from "./agent-archive-owner.js";
31
41
  import { agentArchiveProjection } from "../agent-archive-projection.js";
32
- import { standaloneBrowserSource } from "./browser.js";
42
+ import { standaloneBrowserLiveView, standaloneBrowserSource, } from "./browser.js";
43
+ import { standaloneWebSource } from "./web.js";
33
44
  import { configuredProviderEgress, providerFetch, } from "@fungi.computer/veil/gatekeeper";
34
45
  import { createAssistantMessageEventStream } from "@earendil-works/pi-ai/utils/event-stream";
35
46
  import { agentModelChoice, agentModelChoiceSchema, AgentModelRefused, selectAgentModel, } from "./agent-model-choice.js";
@@ -43,7 +54,6 @@ import { agentScheduleBindingArgs, appAgentScheduleListInputSchema, agentSchedul
43
54
  import { readAgentSchedulePage, controlAgentSchedule, } from "@fungi.computer/shiitake-extensions/schedules/client";
44
55
  import { agentScheduleTargetSchema } from "@fungi.computer/shiitake-extensions/schedules";
45
56
  import { createAgentAvatarStore, } from "../agent-avatars.js";
46
- import { defineIdFamily } from "@fungi.computer/cairn";
47
57
  import { agentIds, createAgentDirectory, createFleetSessions, commandSettlementSchema, DirectoryError, } from "@fungi.computer/shiitake/fleet";
48
58
  import { appToolPolicySchema } from "../apps/index.js";
49
59
  import { oysterPrincipalId } from "../host.js";
@@ -51,7 +61,6 @@ import { oysterPrincipalIsOwner } from "../authorization.js";
51
61
  import { defaultTenant, tenantIdSchema, tenantScope, } from "../tenant.js";
52
62
  import { createCodemodeSandbox } from "@fungi.computer/mycelium/workers";
53
63
  import { forageDiscoveryInstructions } from "@fungi.computer/mycelium/effect";
54
- import { maxAgentMcpServers, } from "../agents.js";
55
64
  /** Own transport evidence and exact-message decisions for one model lease. */
56
65
  function observedModels(model, defaults) {
57
66
  return {
@@ -191,39 +200,6 @@ const policyDirectorySchema = Schema.Struct({
191
200
  directoryName: Schema.NonEmptyString,
192
201
  tenantId: tenantIdSchema,
193
202
  });
194
- /** This Agent's remote MCP servers; the bearer stays in this Durable Object. */
195
- const storedMcpServersSchema = Schema.Array(Schema.Struct({
196
- serverId: Schema.NonEmptyString,
197
- name: Schema.NonEmptyString,
198
- url: Schema.NonEmptyString,
199
- bearer: Schema.NullOr(Schema.NonEmptyString),
200
- }));
201
- const mcpServersKey = "agent-mcp-servers";
202
- const mcpServerIds = defineIdFamily({
203
- family: "oyster-mcp",
204
- version: 1,
205
- kinds: { server: { prefix: "mcp" } },
206
- });
207
- /** The Knapsack connection for one stored server; its bearer goes only to that endpoint. */
208
- function mcpConnection(server) {
209
- const connection = {
210
- id: `mcp.${server.serverId}`,
211
- name: server.name,
212
- url: new URL(server.url),
213
- };
214
- if (server.bearer === null)
215
- return connection;
216
- return {
217
- ...connection,
218
- headers: { authorization: `Bearer ${server.bearer}` },
219
- };
220
- }
221
- const toMcpServer = (stored) => ({
222
- serverId: stored.serverId,
223
- name: stored.name,
224
- url: stored.url,
225
- hasBearer: stored.bearer !== null,
226
- });
227
203
  const instructions = [
228
204
  forageDiscoveryInstructions,
229
205
  "Attached Computers are independent env.computers.<name> modules, including their Files and execute operations; no App is needed. Discover their exact operations before calling.",
@@ -260,6 +236,187 @@ export class StandaloneAgentBase extends ShiitakeDO {
260
236
  setArchived(archived) {
261
237
  return this.archiveControl().setArchived(archived);
262
238
  }
239
+ channelOwner;
240
+ channelDoor;
241
+ acquireChannelStream = createVisitorStreamSlots();
242
+ /** The website bindings that name this Agent, as the directory last said. */
243
+ websiteBindings = new Map();
244
+ /** The owner's current record of one binding; hosts and tests supply it. */
245
+ readChannelBinding(bindingId) {
246
+ return agentDirectoryForScope(this.env, tenantScope(defaultTenant, this.env.OYSTER_ORIGIN)).websiteBinding(bindingId);
247
+ }
248
+ /**
249
+ * Read one binding afresh from its owner: suspension, persona and edits are
250
+ * never stale. A binding that names another Agent is not this Agent's.
251
+ */
252
+ async loadChannelBinding(bindingId) {
253
+ const binding = await this.readChannelBinding(bindingId);
254
+ if (binding === null || binding.agentId !== this.ctx.id.name) {
255
+ this.websiteBindings.delete(bindingId);
256
+ return null;
257
+ }
258
+ this.websiteBindings.set(bindingId, binding);
259
+ return binding;
260
+ }
261
+ /** A web host shares its edge's private assertion key with its Agent. */
262
+ channelProofKey() {
263
+ return this.env.OYSTER_WEBSITE_PROOF_KEY ?? null;
264
+ }
265
+ /**
266
+ * The one per-Session decision, with the binding read afresh: an owner
267
+ * Session is private, a visitor's runs only while its binding is active.
268
+ * Tools and permissions stay the Agent's own either way.
269
+ */
270
+ async channelRun(sessionId) {
271
+ const conversation = sessionId === undefined
272
+ ? null
273
+ : this.channelConversations().sessionConversation(sessionId);
274
+ if (conversation !== null)
275
+ await this.loadChannelBinding(conversation.bindingId);
276
+ return this.cachedChannelRun(sessionId);
277
+ }
278
+ /** The same decision from what this Agent already read; unknown denies. */
279
+ cachedChannelRun(sessionId) {
280
+ return decideChannelRunSafely(() => {
281
+ const conversation = sessionId === undefined
282
+ ? null
283
+ : this.channelConversations().sessionConversation(sessionId);
284
+ return {
285
+ conversationBindingId: conversation?.bindingId ?? null,
286
+ binding: conversation === null
287
+ ? null
288
+ : (this.websiteBindings.get(conversation.bindingId) ?? null),
289
+ };
290
+ }, sessionId ?? "none", (cause) => {
291
+ console.error("channel run decision failed", cause);
292
+ });
293
+ }
294
+ /** Shiitake calls instructions.load at the start of the actual model turn.
295
+ * Capture that command before any asynchronous guidance can change the
296
+ * handoff version; participant projection otherwise hides its reply. A
297
+ * visitor's Session adds the fixed channel rules and the owner's persona to
298
+ * the Agent's own instructions, never replacing them. */
299
+ channelInstructions(source) {
300
+ return {
301
+ load: async (input) => {
302
+ const conversation = this.channelConversations().sessionConversation(input.sessionId);
303
+ if (conversation === null)
304
+ return source.load(input);
305
+ this.channelConversations().captureTurn(input.sessionId, input.commandId);
306
+ const decision = await this.channelRun(input.sessionId);
307
+ if (decision.kind !== "channel")
308
+ throw new Error("Website channel binding is unavailable");
309
+ const base = await source.load(input);
310
+ return {
311
+ revision: `${base.revision}+website-${String(decision.binding.authorityVersion)}`,
312
+ text: `${base.text}\n\n${personChannelInstructions(decision.binding.persona)}`,
313
+ };
314
+ },
315
+ };
316
+ }
317
+ /** Owner read of one website's conversations; the host admits the owner first. */
318
+ async websiteConversations(bindingId) {
319
+ const binding = await this.loadChannelBinding(bindingId);
320
+ return binding === null ? [] : this.channelConversations().list(bindingId);
321
+ }
322
+ /** Owner read of one conversation of a website, from its Session. */
323
+ async websiteTranscript(bindingId, sessionId) {
324
+ const binding = await this.loadChannelBinding(bindingId);
325
+ const conversation = this.channelConversations().sessionConversation(sessionId);
326
+ if (binding === null || conversation?.bindingId !== bindingId)
327
+ return null;
328
+ const snapshot = await (await this.shiitake())
329
+ .session(sessionId)
330
+ .read({ limit: 200 });
331
+ return {
332
+ sessionId,
333
+ label: conversation.label,
334
+ lines: snapshot.messages.flatMap((message) => {
335
+ const line = transcriptLine(message);
336
+ return line === null ? [] : [line];
337
+ }),
338
+ };
339
+ }
340
+ channelBinding(bindingId) {
341
+ return this.websiteBindings.get(bindingId) ?? null;
342
+ }
343
+ channelSessionDoor() {
344
+ return (this.channelDoor ??= channelSessionDoor(() => this.shiitake(), () => {
345
+ // A visitor's Session runs on this Agent's own tools; nothing to deliver.
346
+ }, () => this.channelConversations()));
347
+ }
348
+ /**
349
+ * Compose Oyster's channel owner on this Agent's real store and Shiitake.
350
+ * A host must supply its own binding lookup after authenticating its edge;
351
+ * this does not install an inbound route or mint provider credentials.
352
+ */
353
+ channelConversations() {
354
+ if (this.channelOwner !== undefined)
355
+ return this.channelOwner;
356
+ const owner = createChannelConversations({
357
+ sql: this.ctx.storage.sql,
358
+ transactionSync: (body) => this.ctx.storage.transactionSync(body),
359
+ binding: (id) => this.channelBinding(id),
360
+ door: this.channelSessionDoor(),
361
+ now: () => Date.now(),
362
+ });
363
+ return (this.channelOwner = owner);
364
+ }
365
+ /**
366
+ * Internal DO RPC only: the HTTP edge authenticates once in the central
367
+ * visitor owner, then selects this Agent. No bearer or client-provided
368
+ * visitor id enters this method. Its caller retains the SSE recheck callback.
369
+ */
370
+ visitorConversation() {
371
+ const conversations = this.channelConversations();
372
+ return createAuthenticatedVisitorChannel({
373
+ binding: (id) => this.channelBinding(id),
374
+ conversations: () => conversations,
375
+ sessionDoor: () => this.channelSessionDoor(),
376
+ intake: (event) => conversations.receive(event),
377
+ acquireStream: this.acquireChannelStream,
378
+ now: () => Date.now(),
379
+ });
380
+ }
381
+ async verifiedVisitor(bindingId, visitor) {
382
+ const binding = await this.loadChannelBinding(bindingId);
383
+ if (binding?.lifecycle !== "active")
384
+ throw new Error("Website channel binding is unavailable");
385
+ return verifyVisitor(bindingId, visitor, this.channelProofKey());
386
+ }
387
+ async sendChannelVisitor(bindingId, visitor, requestId, text) {
388
+ const verified = await this.verifiedVisitor(bindingId, visitor);
389
+ return this.visitorConversation().send(bindingId, verified, requestId, text);
390
+ }
391
+ async withdrawChannelVisitor(bindingId, visitor, requestId) {
392
+ const verified = await this.verifiedVisitor(bindingId, visitor);
393
+ return this.visitorConversation().withdraw(bindingId, verified, requestId);
394
+ }
395
+ async latestPendingChannelVisitor(bindingId, visitor) {
396
+ const verified = await this.verifiedVisitor(bindingId, visitor);
397
+ return this.visitorConversation().latestPending(bindingId, verified);
398
+ }
399
+ async openChannelVisitor(bindingId, visitor, options) {
400
+ const verified = await this.verifiedVisitor(bindingId, visitor);
401
+ return this.visitorConversation().open(bindingId, verified, options);
402
+ }
403
+ /**
404
+ * A stream is reauthorized at every beat by the central visitor owner, not
405
+ * by a callback held across this Durable Object's RPC boundary: the site must
406
+ * still be active and the visitor still live.
407
+ */
408
+ async watchChannelVisitor(bindingId, visitor) {
409
+ const verified = await this.verifiedVisitor(bindingId, visitor);
410
+ return this.visitorConversation().watch(bindingId, verified, async (visitorId) => {
411
+ const binding = await this.loadChannelBinding(bindingId);
412
+ return (binding?.lifecycle === "active" &&
413
+ (await this.channelVisitorLive(bindingId, visitorId)));
414
+ });
415
+ }
416
+ /** Whether the central visitor owner still serves this visitor. */
417
+ channelVisitorLive(bindingId, visitorId) {
418
+ return agentDirectoryForScope(this.env, tenantScope(defaultTenant, this.env.OYSTER_ORIGIN)).websiteVisitorLive(bindingId, visitorId);
419
+ }
263
420
  /** Each installed Release's verified catalog surface, built once per Release for this Agent's lifetime. */
264
421
  #appSurfaces;
265
422
  uiOwner;
@@ -304,22 +461,25 @@ export class StandaloneAgentBase extends ShiitakeDO {
304
461
  for (const invalidate of this.computerInvalidations)
305
462
  invalidate();
306
463
  }
464
+ computerAccess() {
465
+ return {
466
+ computer: (computerId) => this.env.COMPUTER.getByName(computerId),
467
+ admit: async (captured) => {
468
+ const pin = await this.policyDirectory();
469
+ if (pin?.directoryName !== captured.scopeId)
470
+ throw new FleetGrantRefused();
471
+ return this.env.AGENT_DIRECTORY.getByName(pin.directoryName).admitAgentComputer({
472
+ scopeId: captured.scopeId,
473
+ agentId: captured.agentId,
474
+ attachment: captured.attachment,
475
+ }, pin.tenantId);
476
+ },
477
+ };
478
+ }
307
479
  computerConnections() {
308
480
  return {
309
481
  read: () => this.computerSnapshot,
310
- connect: (connection) => standaloneAgentComputerPorts({
311
- computer: (computerId) => this.env.COMPUTER.getByName(computerId),
312
- admit: async (captured) => {
313
- const pin = await this.policyDirectory();
314
- if (pin?.directoryName !== captured.scopeId)
315
- throw new FleetGrantRefused();
316
- return this.env.AGENT_DIRECTORY.getByName(pin.directoryName).admitAgentComputer({
317
- scopeId: captured.scopeId,
318
- agentId: captured.agentId,
319
- attachment: captured.attachment,
320
- }, pin.tenantId);
321
- },
322
- }, connection),
482
+ connect: (connection) => standaloneAgentComputerPorts(this.computerAccess(), connection),
323
483
  };
324
484
  }
325
485
  /** Revalidate the owner's generation before reusing a Home or tool snapshot. */
@@ -384,6 +544,11 @@ export class StandaloneAgentBase extends ShiitakeDO {
384
544
  }
385
545
  hostFetch(request) {
386
546
  const pathname = new URL(request.url).pathname;
547
+ if (pathname.startsWith("/cloud-browser/"))
548
+ return standaloneBrowserLiveView(this.env.BROWSER, () => ({
549
+ teamId: this.env.OYSTER_ORIGIN,
550
+ agentId: this.ctx.id.name ?? "agent",
551
+ }))(request);
387
552
  if (pathname.startsWith("/browser/"))
388
553
  return this.ui().then((connection) => connection.fetch(request));
389
554
  // The Home command reads attachments inside a synchronous state transaction.
@@ -590,8 +755,39 @@ export class StandaloneAgentBase extends ShiitakeDO {
590
755
  ? this.hostFor(scope)
591
756
  : null;
592
757
  }
758
+ /** The instance directory that owns this Agent's sealed model keys. */
759
+ async keyDirectory() {
760
+ const pin = await this.policyDirectory();
761
+ if (pin === null)
762
+ throw new AgentModelRefused("key_not_connected");
763
+ return this.env.AGENT_DIRECTORY.getByName(pin.directoryName);
764
+ }
765
+ /** The instance directory that owns this Agent's MCP connections and their credentials. */
766
+ async mcpDirectory() {
767
+ const pin = await this.policyDirectory();
768
+ if (pin === null)
769
+ throw new Error("Agent directory is unavailable");
770
+ return this.env.AGENT_DIRECTORY.getByName(pin.directoryName);
771
+ }
772
+ agentName() {
773
+ const name = this.ctx.id.name;
774
+ if (name === undefined)
775
+ throw new Error("Agent has no name");
776
+ return name;
777
+ }
778
+ /** A byok choice must name a stored key of the chosen provider. */
779
+ async admitKey(choice) {
780
+ if (choice.keySource !== "byok" || choice.keyId === undefined)
781
+ return;
782
+ const record = await (await this.keyDirectory()).modelKey(choice.keyId);
783
+ if (record === null)
784
+ throw new AgentModelRefused("key_removed");
785
+ if (record.provider !== choice.model.providerId)
786
+ throw new AgentModelRefused("key_source_mismatch");
787
+ }
593
788
  choice() {
594
- return agentModelChoice(this.ctx.storage, (choice) => {
789
+ return agentModelChoice(this.ctx.storage, async (choice) => {
790
+ await this.admitKey(choice);
595
791
  if (choice.keySource === "ai-gateway" &&
596
792
  configuredProviderEgress(this.env).baseUrl("ai-gateway") === null)
597
793
  throw new AgentModelRefused("key_not_connected");
@@ -640,6 +836,32 @@ export class StandaloneAgentBase extends ShiitakeDO {
640
836
  }
641
837
  async sourceFor(choice) {
642
838
  const modelChoice = await selectAgentModel(choice);
839
+ if (choice.keySource === "byok" && choice.keyId !== undefined) {
840
+ await this.admitKey(choice);
841
+ const directory = await this.keyDirectory();
842
+ const keyId = choice.keyId;
843
+ const streamOptions = {
844
+ // Pi needs some credential to build its request; the vault replaces it.
845
+ apiKey: "oyster-model-key",
846
+ fetch: async (input, init) => {
847
+ const request = new Request(input, init);
848
+ const sent = await directory.sendModelKey(keyId, {
849
+ url: request.url,
850
+ method: request.method,
851
+ headers: [...request.headers],
852
+ body: request.body === null ? null : await request.text(),
853
+ });
854
+ if (!(sent instanceof Response))
855
+ throw new AgentModelRefused(sent.error === "key_removed"
856
+ ? "key_removed"
857
+ : "key_not_connected");
858
+ return sent;
859
+ },
860
+ };
861
+ if (choice.model.reasoning !== undefined)
862
+ streamOptions.reasoning = choice.model.reasoning;
863
+ return observedModels(normalizeModel(modelChoice), streamOptions);
864
+ }
643
865
  if (choice.keySource === "ai-gateway") {
644
866
  const egress = configuredProviderEgress(this.env);
645
867
  const baseUrl = egress.baseUrl("ai-gateway");
@@ -712,50 +934,21 @@ export class StandaloneAgentBase extends ShiitakeDO {
712
934
  }
713
935
  /** Listeners from live codemode acquisitions, told when the server list changes. */
714
936
  mcpInvalidations = new Set();
715
- async storedMcpServers() {
716
- const stored = await this.ctx.storage.get(mcpServersKey);
717
- return stored === undefined
718
- ? []
719
- : Schema.decodeUnknownSync(storedMcpServersSchema)(stored);
720
- }
721
- async writeMcpServers(servers) {
722
- await this.ctx.storage.put(mcpServersKey, servers);
937
+ /** Host-only: the directory told us this Agent's connections changed. */
938
+ invalidateMcpConnections() {
723
939
  for (const invalidate of this.mcpInvalidations)
724
940
  invalidate();
725
941
  }
726
- /** Host-only: this Agent's MCP servers, without their bearer tokens. */
727
- async mcpServers() {
728
- return (await this.storedMcpServers()).map(toMcpServer);
729
- }
730
- /** Host-only: connect one remote MCP server, admitted by the owner route. */
731
- async addMcpServer(input) {
732
- const servers = await this.storedMcpServers();
733
- if (servers.some((server) => server.name === input.name))
734
- return { error: "duplicate_name" };
735
- if (servers.length >= maxAgentMcpServers)
736
- return { error: "limit" };
737
- const added = {
738
- serverId: mcpServerIds.server.generate(),
739
- name: input.name,
740
- url: new URL(input.url).href,
741
- bearer: input.bearer,
742
- };
743
- await this.writeMcpServers([...servers, added]);
744
- return toMcpServer(added);
745
- }
746
- /** Host-only: disconnect one MCP server. */
747
- async removeMcpServer(serverId) {
748
- const servers = await this.storedMcpServers();
749
- const kept = servers.filter((server) => server.serverId !== serverId);
750
- if (kept.length === servers.length)
751
- return false;
752
- await this.writeMcpServers(kept);
753
- return true;
754
- }
942
+ /**
943
+ * A full override must retain channelSource and channelInstructions:
944
+ * dropping them removes a suspended website's run refusal and turn capture.
945
+ */
755
946
  async shiitakeOptions() {
756
- const [{ oysterAgentExtensions }, { Knapsack }] = await Promise.all([
947
+ const [{ oysterAgentExtensions }, { Knapsack }, { agentMcpSourceOptions }, { mcpRequestData },] = await Promise.all([
757
948
  import("@fungi.computer/shiitake-extensions/roster/conversation-agents"),
758
949
  import("@fungi.computer/knapsack"),
950
+ import("./agent-connections.js"),
951
+ import("@fungi.computer/veil/connections"),
759
952
  ]);
760
953
  const conversationAgents = await this.conversationAgents();
761
954
  const computerSource = createAgentComputerSource({
@@ -770,11 +963,20 @@ export class StandaloneAgentBase extends ShiitakeDO {
770
963
  const principal = {
771
964
  actor: { kind: "agent", agentId: this.ctx.id.name ?? "agent" },
772
965
  };
966
+ const channelSource = (source) => ({
967
+ ...source,
968
+ acquire: async (context) => (await this.channelRun(context.session?.sessionId)).kind !== "denied"
969
+ ? source.acquire(context)
970
+ : {
971
+ snapshot: { version: "channel-denied", modules: [] },
972
+ release: () => Promise.resolve(),
973
+ },
974
+ });
773
975
  return {
774
976
  model: this.modelSource(),
775
977
  meta: { schema: FungiMessageMetaSchema },
776
978
  ...this.mail().host,
777
- instructions: {
979
+ instructions: this.channelInstructions({
778
980
  load: async () => {
779
981
  const { appApprovalInstructions } = await import("../mcp.js");
780
982
  return {
@@ -782,7 +984,7 @@ export class StandaloneAgentBase extends ShiitakeDO {
782
984
  text: instructions + "\n" + appApprovalInstructions,
783
985
  };
784
986
  },
785
- },
987
+ }),
786
988
  tools: {
787
989
  sources: [
788
990
  {
@@ -810,16 +1012,12 @@ export class StandaloneAgentBase extends ShiitakeDO {
810
1012
  return computerSource.acquire(context);
811
1013
  },
812
1014
  },
813
- Knapsack.mcpServers({
814
- id: "agent-mcp",
815
- read: async () => {
816
- const servers = await this.storedMcpServers();
817
- return {
818
- // Secret-free: ids and endpoints, never the bearer.
819
- version: JSON.stringify(servers.map((server) => [server.serverId, server.url])),
820
- servers: servers.map(mcpConnection),
821
- };
822
- },
1015
+ Knapsack.mcpServers(agentMcpSourceOptions({
1016
+ // Like attached Computers: an Agent not yet pinned to its
1017
+ // directory has no connections, rather than a failing source.
1018
+ read: async () => (await this.policyDirectory()) === null
1019
+ ? { revision: 0, connections: [] }
1020
+ : (await this.mcpDirectory()).mcpProjection(this.agentName()),
823
1021
  subscribe: (invalidate) => {
824
1022
  this.mcpInvalidations.add(invalidate);
825
1023
  return () => this.mcpInvalidations.delete(invalidate);
@@ -830,16 +1028,25 @@ export class StandaloneAgentBase extends ShiitakeDO {
830
1028
  reason: error.reason,
831
1029
  });
832
1030
  },
833
- // The Worker's own egress: public internet only.
834
- fetch: (url, init) => fetch(url, init),
835
- }),
1031
+ // Completed by the owner, which holds the credential.
1032
+ fetch: async (ref, request) => {
1033
+ const answer = await (await this.mcpDirectory()).mcpFetch(this.agentName(), ref, await mcpRequestData(request));
1034
+ if ("error" in answer)
1035
+ throw new Error(`MCP connection refused: ${answer.error}`);
1036
+ return answer;
1037
+ },
1038
+ })),
836
1039
  conversationAgents.control(() => this.controlDirectory()),
837
1040
  (await this.ui()).source,
1041
+ standaloneWebSource(this.env),
838
1042
  standaloneBrowserSource(this.env.BROWSER, () => ({
839
1043
  teamId: this.env.OYSTER_ORIGIN,
840
1044
  agentId: principal.actor.agentId,
841
- })),
842
- ],
1045
+ }), standaloneBrowserSave({
1046
+ admit: this.computerAccess().admit,
1047
+ write: (computerId, grant, path, bytes) => this.env.COMPUTER.getByName(computerId).fileWrite(grant, path, bytes),
1048
+ }, () => this.computerSnapshot)),
1049
+ ].map(channelSource),
843
1050
  sandbox: createCodemodeSandbox(this.env.LOADER, "oyster-workerd"),
844
1051
  },
845
1052
  extensions: {
@@ -850,7 +1057,9 @@ export class StandaloneAgentBase extends ShiitakeDO {
850
1057
  prepare: async () => {
851
1058
  await this.preparedComputerSnapshot();
852
1059
  },
853
- read: () => readAgentComputerConnections(this.computerConnections()).map(({ name, attachmentId, files }) => ({
1060
+ read: ({ sessionId }) => (this.cachedChannelRun(sessionId).kind !== "denied"
1061
+ ? readAgentComputerConnections(this.computerConnections())
1062
+ : []).map(({ name, attachmentId, files }) => ({
854
1063
  name,
855
1064
  attachmentId,
856
1065
  port: files.port,
@@ -955,6 +1164,97 @@ export class AgentDirectory extends DurableObject {
955
1164
  archived(agentId) {
956
1165
  return this.archiveProjection().archived(agentId);
957
1166
  }
1167
+ modelKeys() {
1168
+ const storage = this.ctx.storage;
1169
+ return createModelKeyVault({
1170
+ credentialKey: this.env.OYSTER_CREDENTIAL_KEY,
1171
+ storage: credentialStorage(storage),
1172
+ });
1173
+ }
1174
+ /** Domain refusals cross the DO RPC boundary as data, not as Error prototypes. */
1175
+ async sealModelKey(input) {
1176
+ try {
1177
+ return await this.modelKeys().seal(input);
1178
+ }
1179
+ catch (error) {
1180
+ if (error instanceof ModelKeyRefused)
1181
+ return { error: error.reason };
1182
+ throw error;
1183
+ }
1184
+ }
1185
+ listModelKeys() {
1186
+ return this.modelKeys().list();
1187
+ }
1188
+ modelKey(keyId) {
1189
+ return this.modelKeys().get(keyId);
1190
+ }
1191
+ removeModelKey(keyId) {
1192
+ return this.modelKeys().remove(keyId);
1193
+ }
1194
+ /** Host-only: the one place a stored key meets a provider request. */
1195
+ async sendModelKey(keyId, request) {
1196
+ try {
1197
+ return await this.modelKeys().send(keyId, new Request(request.url, {
1198
+ method: request.method,
1199
+ headers: request.headers.map(([name, value]) => [name, value]),
1200
+ body: request.body,
1201
+ }));
1202
+ }
1203
+ catch (error) {
1204
+ if (error instanceof ModelKeyRefused)
1205
+ return { error: error.reason };
1206
+ throw error;
1207
+ }
1208
+ }
1209
+ mcpOwner;
1210
+ /** Loaded on the first MCP request: the SDK and OpenAPI decoders stay out of startup. */
1211
+ async mcpConnections() {
1212
+ const { createAgentMcpConnections } = await import("./agent-connections.js");
1213
+ const storage = this.ctx.storage;
1214
+ return (this.mcpOwner ??= createAgentMcpConnections({
1215
+ ownerId: this.ctx.id.name ?? "agents",
1216
+ store: storage,
1217
+ vault: createInstanceCredentialStore({
1218
+ credentialKey: this.env.OYSTER_CREDENTIAL_KEY,
1219
+ storage: credentialStorage(storage),
1220
+ }),
1221
+ // The Worker's own egress: public internet only.
1222
+ send: (request) => fetch(request),
1223
+ hasAgent: (agentId) => this.has(agentId),
1224
+ notify: (agentId) => this.env.AGENTS.getByName(agentId).invalidateMcpConnections(),
1225
+ callbackUrl: mcpCallbackUrl(this.env.OYSTER_ORIGIN),
1226
+ }));
1227
+ }
1228
+ /** Host-only: every connection with the Agents that may use it, never a credential. */
1229
+ async connections() {
1230
+ return (await this.mcpConnections()).list();
1231
+ }
1232
+ async addConnection(input) {
1233
+ return (await this.mcpConnections()).add(input);
1234
+ }
1235
+ async grantConnection(connectionId, agentId, access) {
1236
+ return (await this.mcpConnections()).grant(connectionId, agentId, access);
1237
+ }
1238
+ async ungrantConnection(connectionId, agentId) {
1239
+ return (await this.mcpConnections()).ungrant(connectionId, agentId);
1240
+ }
1241
+ async removeConnection(connectionId) {
1242
+ return (await this.mcpConnections()).remove(connectionId);
1243
+ }
1244
+ async connectionTools(connectionId) {
1245
+ return (await this.mcpConnections()).tools(connectionId);
1246
+ }
1247
+ async completeMcpConnection(query) {
1248
+ return (await this.mcpConnections()).complete(query);
1249
+ }
1250
+ /** Secret-free grants for one Agent: ids, versions and endpoints. */
1251
+ async mcpProjection(agentId) {
1252
+ return (await this.mcpConnections()).projection(agentId);
1253
+ }
1254
+ /** Host-only: complete one Agent MCP request; the credential opens only here. */
1255
+ async mcpFetch(agentId, ref, request) {
1256
+ return (await this.mcpConnections()).fetch(agentId, ref, request);
1257
+ }
958
1258
  computers;
959
1259
  computerNames = new Map();
960
1260
  directory;
@@ -1286,6 +1586,64 @@ export class AgentDirectory extends DurableObject {
1286
1586
  provenance: { actor: oysterPrincipalId(owner), via: captured.agentId },
1287
1587
  };
1288
1588
  }
1589
+ websiteChannelsOwner;
1590
+ websites() {
1591
+ return (this.websiteChannelsOwner ??= createWebsiteChannelOwner({
1592
+ sql: this.ctx.storage.sql,
1593
+ transactionSync: (body) => this.ctx.storage.transactionSync(body),
1594
+ agentExists: (agentId) => this.has(agentId),
1595
+ agentIdentity: (agentId) => {
1596
+ const id = agentIds.agent.parse(agentId);
1597
+ if (!id.ok || this.archived(agentId))
1598
+ return null;
1599
+ const entry = this.directory.read(this.grant(), id.value);
1600
+ return entry === null
1601
+ ? null
1602
+ : { name: entry.name, avatar: this.avatars.read(agentId) };
1603
+ },
1604
+ }));
1605
+ }
1606
+ /** Owner read of every website bound to one of this tenant's Agents. */
1607
+ websiteList(principal) {
1608
+ if (!oysterPrincipalIsOwner(principal))
1609
+ return { error: "not_granted" };
1610
+ return this.websites().bindings.list();
1611
+ }
1612
+ /** Owner-only: put a chosen Agent behind a new site key. */
1613
+ websiteCreate(principal, input, requestId) {
1614
+ if (!oysterPrincipalIsOwner(principal))
1615
+ return { error: "not_granted" };
1616
+ return websiteOutcome(() => this.websites().bindings.create(input, requestId));
1617
+ }
1618
+ /** Owner-only edit, fenced by the version the owner last read. */
1619
+ websiteUpdate(principal, bindingId, input) {
1620
+ if (!oysterPrincipalIsOwner(principal))
1621
+ return { error: "not_granted" };
1622
+ return websiteOutcome(() => this.websites().bindings.update(bindingId, input));
1623
+ }
1624
+ /** Host-only: the binding a website Agent serves, read fresh on every use. */
1625
+ websiteBinding(bindingId) {
1626
+ return this.websites().bindings.read(bindingId);
1627
+ }
1628
+ /** Host-only public lookup: a site key resolves to its site, or to nothing. */
1629
+ websiteSite(siteKey) {
1630
+ return this.websites().site(siteKey);
1631
+ }
1632
+ websiteMint(bindingId, siteKey, addressHash) {
1633
+ return this.websites().visitors.mint(this.websites().bindings.read(bindingId), siteKey, addressHash);
1634
+ }
1635
+ websiteRefresh(bindingId, refreshSecret) {
1636
+ return this.websites().visitors.refresh(this.websites().bindings.read(bindingId), refreshSecret);
1637
+ }
1638
+ websiteRotate(bindingId, siteKey, accessToken, addressHash) {
1639
+ return this.websites().visitors.rotate(this.websites().bindings.read(bindingId), siteKey, accessToken, addressHash);
1640
+ }
1641
+ websiteVisitorLive(bindingId, visitorId) {
1642
+ return this.websites().visitors.live(bindingId, visitorId);
1643
+ }
1644
+ websiteAuthenticate(bindingId, accessToken) {
1645
+ return this.websites().visitors.authenticate(bindingId, accessToken);
1646
+ }
1289
1647
  list(options) {
1290
1648
  const archived = this.archiveProjection().archivedIds();
1291
1649
  return this.directory
@@ -1560,6 +1918,15 @@ export class AgentDirectory extends DurableObject {
1560
1918
  this.ctx.storage.sql.exec("INSERT INTO counters(name, value) VALUES('revision', 1) ON CONFLICT(name) DO UPDATE SET value=value+1");
1561
1919
  }
1562
1920
  }
1921
+ /** Where an authorization server returns the owner after a sign-in. */
1922
+ const mcpCallbackUrl = (origin) => new URL("/api/connections/callback", origin).href;
1923
+ /** The directory's Durable Object storage as the credential store's key-value port. */
1924
+ const credentialStorage = (storage) => ({
1925
+ get: (key) => storage.get(key),
1926
+ put: (key, value) => storage.put(key, value),
1927
+ delete: (key) => storage.delete(key),
1928
+ list: async (prefix) => new Map(await storage.list({ prefix })),
1929
+ });
1563
1930
  const everyOperation = [
1564
1931
  "agent.read",
1565
1932
  "agent.send",
@@ -1631,6 +1998,9 @@ export function standaloneAgents(env, scope) {
1631
1998
  return { error: "not_found" };
1632
1999
  return env.AGENTS.getByName(agentId).setModelChoice(choice);
1633
2000
  },
2001
+ modelKeys: () => directory().listModelKeys(),
2002
+ sealModelKey: (input) => directory().sealModelKey(input),
2003
+ removeModelKey: (keyId) => directory().removeModelKey(keyId),
1634
2004
  policyStatus: async (agentId) => directory().policyStatus(agentId),
1635
2005
  appToolPolicy: (actor) => directory().appToolPolicy(actor, scope?.tenantId ?? defaultTenant),
1636
2006
  policyRevision: (agentId) => directory().policyRevision(agentId),
@@ -1643,14 +2013,14 @@ export function standaloneAgents(env, scope) {
1643
2013
  return { error: "not_found" };
1644
2014
  return directory().approveAppToolPolicy(agentId, principal, level, expectedRevision, actor, scope?.tenantId ?? defaultTenant);
1645
2015
  },
1646
- mcpServers: async (agentId) => (await directory().has(agentId))
1647
- ? await env.AGENTS.getByName(agentId).mcpServers()
1648
- : null,
1649
- addMcpServer: async (agentId, input) => (await directory().has(agentId))
1650
- ? await env.AGENTS.getByName(agentId).addMcpServer(input)
1651
- : { error: "not_found" },
1652
- removeMcpServer: async (agentId, serverId) => (await directory().has(agentId)) &&
1653
- (await env.AGENTS.getByName(agentId).removeMcpServer(serverId)),
2016
+ connections: () => directory().connections(),
2017
+ addConnection: (input) => directory().addConnection(input),
2018
+ grantConnection: (connectionId, agentId, access) => directory().grantConnection(connectionId, agentId, access),
2019
+ ungrantConnection: (connectionId, agentId) => directory().ungrantConnection(connectionId, agentId),
2020
+ removeConnection: (connectionId) => directory().removeConnection(connectionId),
2021
+ connectionTools: (connectionId) => directory().connectionTools(connectionId),
2022
+ completeMcpConnection: (query) => directory().completeMcpConnection(query),
2023
+ mcpCallbackUrl: () => mcpCallbackUrl(env.OYSTER_ORIGIN),
1654
2024
  fetch: async (agentId, request) => {
1655
2025
  const home = await directory().agentHome(agentId);
1656
2026
  if (home?.kind === "machine") {