@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
@@ -1,11 +1,24 @@
1
1
  import type { CapabilitySource } from "@fungi.computer/mycelium";
2
- import { type BrowserBinding } from "../browser/index.js";
2
+ import { type BrowserBinding, type SaveBrowserFile } from "../browser/index.js";
3
3
  /**
4
4
  * The agent's `cloudBrowser` tool on a standalone Oyster, or an empty source
5
5
  * when the deployment declares no BROWSER binding. Driven sessions only: no
6
- * Quick Reads, no Computer save, no member handoff on this host.
6
+ * Quick Reads. `handoff` pauses the lease and returns the owner's live view;
7
+ * `channel` stays null until the host supplies a conversations owner, which
8
+ * is the seam a channel Session's conversation handoff plugs into. Screenshots
9
+ * and PDFs save to an attached Computer through `saveFile`.
7
10
  */
8
11
  export declare function standaloneBrowserSource(binding: BrowserBinding | undefined, identity: () => Readonly<{
9
12
  teamId: string;
10
13
  agentId: string;
11
- }>): CapabilitySource;
14
+ }>, saveFile: SaveBrowserFile): CapabilitySource;
15
+ /**
16
+ * The Agent DO's side of the owner's live view. The browser singleton lives in
17
+ * this isolate, so the Worker's owner-admitted `/agents/:agentId/cloud-browser`
18
+ * route forwards here and this calls `Browser.member` on the Agent's own
19
+ * lease. Admission is the Worker's; this only serves already-admitted requests.
20
+ */
21
+ export declare function standaloneBrowserLiveView(binding: BrowserBinding | undefined, identity: () => Readonly<{
22
+ teamId: string;
23
+ agentId: string;
24
+ }>): (request: Request) => Promise<Response>;
@@ -1,4 +1,5 @@
1
- import { bindingSessions, browserCapabilitySource, createBrowser, } from "../browser/index.js";
1
+ import { match } from "path-to-regexp";
2
+ import { bindingSessions, browserCapabilitySource, createBrowser, liveView, liveViewPaths, } from "../browser/index.js";
2
3
  import { causeClass } from "../cause-class.js";
3
4
  /**
4
5
  * A standalone Oyster's `BrowserHost`: its own Workers BROWSER binding, no
@@ -41,12 +42,19 @@ function standaloneBrowser(binding) {
41
42
  }
42
43
  return browser;
43
44
  }
45
+ /** The owner-admitted live-view base for one Agent's lease (see `agents.ts`'s cloud-browser route). */
46
+ function viewBase(agentId, leaseId) {
47
+ return `/agents/${encodeURIComponent(agentId)}/cloud-browser/${encodeURIComponent(leaseId)}`;
48
+ }
44
49
  /**
45
50
  * The agent's `cloudBrowser` tool on a standalone Oyster, or an empty source
46
51
  * when the deployment declares no BROWSER binding. Driven sessions only: no
47
- * Quick Reads, no Computer save, no member handoff on this host.
52
+ * Quick Reads. `handoff` pauses the lease and returns the owner's live view;
53
+ * `channel` stays null until the host supplies a conversations owner, which
54
+ * is the seam a channel Session's conversation handoff plugs into. Screenshots
55
+ * and PDFs save to an attached Computer through `saveFile`.
48
56
  */
49
- export function standaloneBrowserSource(binding, identity) {
57
+ export function standaloneBrowserSource(binding, identity, saveFile) {
50
58
  if (binding === undefined)
51
59
  return {
52
60
  id: "cloud-browser",
@@ -66,7 +74,48 @@ export function standaloneBrowserSource(binding, identity) {
66
74
  },
67
75
  },
68
76
  quickReads: false,
69
- saveFile: null,
70
- requestHandoff: null,
77
+ saveFile,
78
+ handoff: {
79
+ channel: null,
80
+ viewPath: (owner, leaseId) => liveViewPaths(viewBase(owner.agentId, leaseId)).view,
81
+ },
71
82
  });
72
83
  }
84
+ /**
85
+ * The Agent DO's side of the owner's live view. The browser singleton lives in
86
+ * this isolate, so the Worker's owner-admitted `/agents/:agentId/cloud-browser`
87
+ * route forwards here and this calls `Browser.member` on the Agent's own
88
+ * lease. Admission is the Worker's; this only serves already-admitted requests.
89
+ */
90
+ export function standaloneBrowserLiveView(binding, identity) {
91
+ const route = match("/cloud-browser/:leaseId/:part");
92
+ const handlers = (leaseId) => {
93
+ if (binding === undefined)
94
+ return null;
95
+ const { teamId, agentId } = identity();
96
+ const browser = standaloneBrowser(binding);
97
+ return liveView((action, signal) => browser.member(teamId, leaseId, action, signal), liveViewPaths(viewBase(agentId, leaseId)), (event, cause) => {
98
+ console.warn("Oyster browser", {
99
+ kind: event,
100
+ cause: causeClass(cause),
101
+ });
102
+ });
103
+ };
104
+ const none = () => Response.json({ error: "no_browser" }, { status: 404 });
105
+ return (request) => {
106
+ const found = route(new URL(request.url).pathname);
107
+ if (found === false)
108
+ return Promise.resolve(none());
109
+ const { leaseId, part } = found.params;
110
+ const view = handlers(leaseId);
111
+ if (view === null)
112
+ return Promise.resolve(none());
113
+ if (part === "view" && request.method === "GET")
114
+ return Promise.resolve(view.page());
115
+ if (part === "frame" && request.method === "GET")
116
+ return view.frame(request.signal);
117
+ if (part === "input" && request.method === "POST")
118
+ return view.input(request, request.signal);
119
+ return Promise.resolve(none());
120
+ };
121
+ }
@@ -0,0 +1,4 @@
1
+ import type { ShiitakeOwnerAgent } from "@fungi.computer/shiitake/cloudflare";
2
+ import type { ChannelConversations, SessionDoor } from "../channels/conversations.js";
3
+ /** Translate a standalone Agent's Shiitake owner into Oyster's channel Session port. */
4
+ export declare function channelSessionDoor(open: () => Promise<ShiitakeOwnerAgent>, deliverGrants: (sessionId: string) => void, conversations: () => ChannelConversations): SessionDoor;
@@ -0,0 +1,72 @@
1
+ import { authorMeta } from "@fungi.computer/agar/agents";
2
+ import { ShiitakeError } from "@fungi.computer/shiitake";
3
+ import { participantSnapshot, visitorPendingPrompt, visitorSnapshot, } from "@fungi.computer/shiitake/client";
4
+ import { visitorStream } from "@fungi.computer/shiitake/server-visitor-stream";
5
+ /** Translate a standalone Agent's Shiitake owner into Oyster's channel Session port. */
6
+ export function channelSessionDoor(open, deliverGrants, conversations) {
7
+ const policy = () => conversations();
8
+ return {
9
+ createSession: async (requestId) => (await open()).createSession(requestId),
10
+ deliverGrants,
11
+ withdraw: async (sessionId, requestId) => (await open()).session(sessionId).withdraw(requestId),
12
+ latestPending: async (sessionId, visitor) => {
13
+ const prompt = await (await open())
14
+ .withMeta(authorMeta(visitor))
15
+ .session(sessionId)
16
+ .latestPending();
17
+ return prompt === null ? null : visitorPendingPrompt(prompt, visitor.id);
18
+ },
19
+ participantDocument: async (sessionId, visitorId, options) => {
20
+ const snapshot = await (await open()).session(sessionId).read(options);
21
+ return JSON.stringify(visitorSnapshot(participantSnapshot(snapshot, policy()), visitorId));
22
+ },
23
+ participantStream: async (sessionId, visitorId, options) => {
24
+ let watch;
25
+ try {
26
+ watch = await (await open()).session(sessionId).watch();
27
+ }
28
+ catch (cause) {
29
+ options.release();
30
+ throw cause;
31
+ }
32
+ return visitorStream({
33
+ ...options,
34
+ watch,
35
+ visitorId,
36
+ filter: (snapshot) => participantSnapshot(snapshot, policy()),
37
+ read: async () => (await open()).session(sessionId).read(),
38
+ onError: (event, cause) => {
39
+ console.warn(event, cause);
40
+ },
41
+ });
42
+ },
43
+ prompt: async (sessionId, { requestId, text, meta }) => {
44
+ // The conversation row exists now, so its channel admission is known;
45
+ // deliver Agent tools before the first run can call one.
46
+ deliverGrants(sessionId);
47
+ const agent = await open();
48
+ return await agent.withMeta(meta).session(sessionId).command({
49
+ type: "prompt",
50
+ requestId,
51
+ text,
52
+ delivery: "followUp",
53
+ });
54
+ },
55
+ line: async (sessionId, input) => {
56
+ const agent = await open();
57
+ const meta = input.author === "operator" ? authorMeta(input.identity) : input.meta;
58
+ await agent.withMeta(meta).session(sessionId).command({
59
+ type: "operator",
60
+ requestId: input.requestId,
61
+ author: input.author,
62
+ text: input.text,
63
+ });
64
+ },
65
+ errorKind: (error, requestId) => error instanceof ShiitakeError &&
66
+ error.boundary === "contract" &&
67
+ error.cause === "closed" &&
68
+ error.requestId === requestId
69
+ ? "closed_request"
70
+ : null,
71
+ };
72
+ }
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { computerStateSchema, } from "@fungi.computer/computer/fleet";
2
+ import { computerBackendViewSchema, computerStateSchema, } from "@fungi.computer/computer/fleet";
3
3
  import { teamComputerDirectorySchema } from "@fungi.computer/nacre/workbench";
4
4
  const inventoryComputer = z.strictObject({
5
5
  computerId: z.string(),
@@ -14,6 +14,26 @@ const inventoryPage = z.strictObject({
14
14
  const inventoryError = z.strictObject({
15
15
  error: z.string(),
16
16
  });
17
+ const backendList = z.strictObject({
18
+ backends: z.array(computerBackendViewSchema),
19
+ });
20
+ const attachedBackend = z.strictObject({ backendId: z.string() });
21
+ const detachedBackend = z.strictObject({ detached: z.boolean() });
22
+ /** A typed refusal from the owner-admitted fleet, as the MCP result kinds. */
23
+ function refusedKind(result) {
24
+ const error = inventoryError.safeParse(result);
25
+ if (!error.success)
26
+ return undefined;
27
+ switch (error.data.error) {
28
+ case "request_conflict":
29
+ return "conflict";
30
+ case "invalid":
31
+ case "not_enabled":
32
+ return "invalid";
33
+ default:
34
+ return "denied";
35
+ }
36
+ }
17
37
  /** MCP control speaks to the same owner-admitted durable fleet as HTTP. */
18
38
  export function standaloneComputerControl(registry, memberId) {
19
39
  const fleet = (request) => registry.computerFleet(memberId, request);
@@ -58,5 +78,39 @@ export function standaloneComputerControl(registry, memberId) {
58
78
  computer: { computerId: computer.computerId, name: computer.name },
59
79
  };
60
80
  },
81
+ backends: async (computerId) => backendList.parse(available(await fleet({ operation: "backends", computerId }))).backends,
82
+ attachLocal: async (input) => {
83
+ let result;
84
+ try {
85
+ result = await fleet({ operation: "attach-local", request: input });
86
+ }
87
+ catch {
88
+ // The attachment may have committed; the caller retries its requestId.
89
+ return { kind: "uncertain" };
90
+ }
91
+ if (result === null)
92
+ return { kind: "denied" };
93
+ const refused = refusedKind(result);
94
+ if (refused !== undefined)
95
+ return { kind: refused };
96
+ return { kind: "attached", ...attachedBackend.parse(result) };
97
+ },
98
+ detachLocal: async (input) => {
99
+ let result;
100
+ try {
101
+ result = await fleet({ operation: "detach-local", request: input });
102
+ }
103
+ catch {
104
+ return { kind: "uncertain" };
105
+ }
106
+ if (result === null)
107
+ return { kind: "denied" };
108
+ const refused = refusedKind(result);
109
+ if (refused === "conflict")
110
+ return { kind: "uncertain" };
111
+ if (refused !== undefined)
112
+ return { kind: refused };
113
+ return { kind: "detached", ...detachedBackend.parse(result) };
114
+ },
61
115
  };
62
116
  }
@@ -26,6 +26,27 @@ export declare const standaloneFleetRequestSchema: z.ZodDiscriminatedUnion<[z.Zo
26
26
  start: "start";
27
27
  }>;
28
28
  computerId: z.ZodString;
29
+ }, z.core.$strict>, z.ZodObject<{
30
+ operation: z.ZodLiteral<"backends">;
31
+ computerId: z.ZodString;
32
+ }, z.core.$strict>, z.ZodObject<{
33
+ operation: z.ZodLiteral<"attach-local">;
34
+ request: z.ZodObject<{
35
+ computerId: z.ZodString;
36
+ publicKey: z.ZodBase64;
37
+ hostLabel: z.ZodLazy<z.ZodString>;
38
+ folderLabel: z.ZodLazy<z.ZodString>;
39
+ requestId: z.ZodString;
40
+ }, z.core.$strict>;
41
+ }, z.core.$strict>, z.ZodObject<{
42
+ operation: z.ZodLiteral<"detach-local">;
43
+ request: z.ZodUnion<readonly [z.ZodLazy<z.ZodObject<{
44
+ computerId: z.ZodString;
45
+ backendId: z.ZodString;
46
+ }, z.core.$strict>>, z.ZodObject<{
47
+ computerId: z.ZodString;
48
+ requestId: z.ZodString;
49
+ }, z.core.$strict>]>;
29
50
  }, z.core.$strict>, z.ZodObject<{
30
51
  operation: z.ZodEnum<{
31
52
  "read-internet-access": "read-internet-access";
@@ -1,7 +1,7 @@
1
1
  import { endTime, startTime } from "hono/timing";
2
2
  import { HTTPException } from "hono/http-exception";
3
3
  import { z } from "zod";
4
- import { computerCreateRequestSchema, computerPageSchema, } from "@fungi.computer/computer/fleet";
4
+ import { computerCreateRequestSchema, computerPageSchema, localBackendAttachSchema, localBackendDetachRequestSchema, localBackendDetachSchema, } from "@fungi.computer/computer/fleet";
5
5
  import {} from "../host.js";
6
6
  import { oysterPrincipalIsOwner, owner as ownerRoute, routes as routeTable, } from "../authorization.js";
7
7
  import { computerTargetParam } from "../computer-target.js";
@@ -20,6 +20,21 @@ export const standaloneFleetRequestSchema = z.discriminatedUnion("operation", [
20
20
  operation: z.enum(["read", "resolve", "state", "start", "select"]),
21
21
  computerId: fleetComputerId,
22
22
  }),
23
+ z.strictObject({
24
+ operation: z.literal("backends"),
25
+ computerId: fleetComputerId,
26
+ }),
27
+ z.strictObject({
28
+ operation: z.literal("attach-local"),
29
+ request: localBackendAttachSchema,
30
+ }),
31
+ z.strictObject({
32
+ operation: z.literal("detach-local"),
33
+ request: z.union([
34
+ localBackendDetachSchema,
35
+ localBackendDetachRequestSchema,
36
+ ]),
37
+ }),
23
38
  z.strictObject({
24
39
  operation: z.enum(["read-internet-access", "read-keep-awake"]),
25
40
  computerId: fleetComputerId,
@@ -34,11 +49,20 @@ function fleetStatus(result) {
34
49
  if (result === null)
35
50
  return 404;
36
51
  if ("error" in result)
37
- return result.error === "owner_required"
38
- ? 403
39
- : result.error === "partial_init"
40
- ? 503
41
- : 409;
52
+ switch (result.error) {
53
+ case "owner_required":
54
+ case "not_owner":
55
+ case "local_limit":
56
+ case "unknown_computer":
57
+ return 403;
58
+ case "invalid":
59
+ case "not_enabled":
60
+ return 400;
61
+ case "partial_init":
62
+ return 503;
63
+ default:
64
+ return 409;
65
+ }
42
66
  return 200;
43
67
  }
44
68
  function fleetResponse(result) {
@@ -8,7 +8,7 @@ import { ComputerDO as NativeComputerDO, type AttachedBackend, type ComputerEnv,
8
8
  import { patchInputSchema, patchOutputSchema } from "@fungi.computer/knapsack/files-patch";
9
9
  import { listOutputSchema, writeOutputSchema, mkdirOutputSchema, computerPortsOutputSchema, computerPortOutputSchema, computerPortRemovalOutputSchema, processListOutputSchema, processKillOutputSchema, computerOperationResultSchema, type ComputerExecutionHostHooks, type ComputerValue } from "@fungi.computer/computer-contract";
10
10
  import { type WorkflowGitCredential, type WorkflowGitPassGrant } from "@fungi.computer/braid/runtime";
11
- import { type ComputerAction, type ComputerGrant } from "@fungi.computer/computer/fleet";
11
+ import { type ComputerAction, type ComputerBackendView, type ComputerGrant, type LocalBackendAttachInput, type LocalBackendDetachInput } from "@fungi.computer/computer/fleet";
12
12
  import type { InvocationFrame } from "../invocation.js";
13
13
  import { type OysterCapability } from "../host.js";
14
14
  import type { OysterBindingRow, OysterInvocationHost, OysterWorkerEnv, OysterWorkspace } from "../workers.js";
@@ -71,6 +71,7 @@ export type ComputerFetch = {
71
71
  export type StandaloneAgentComputerRpc = ComputerFilesRpc & Readonly<{
72
72
  tool(authority: ComputerGrant, capabilityId: string, input: ComputerValue): Promise<StandaloneComputerResult>;
73
73
  filePatch(authority: ComputerGrant, input: z.output<typeof patchInputSchema>): Promise<z.output<typeof patchOutputSchema>>;
74
+ fileWrite(authority: ComputerGrant, path: string, bytes: Uint8Array): Promise<void>;
74
75
  }>;
75
76
  /** Durable workspace and existing backings, with fleet checks at native acceptance. */
76
77
  export declare class ComputerDO extends NativeComputerDO implements ComputerFetch, StandaloneAgentComputerRpc {
@@ -79,6 +80,24 @@ export declare class ComputerDO extends NativeComputerDO implements ComputerFetc
79
80
  constructor(state: DurableObjectState, previewBindings: StandaloneComputerOwnerEnv);
80
81
  /** Install the fleet's creation projection before exposing its new identity. */
81
82
  initializeFleetBackings(backings: readonly AttachedBackend[]): void;
83
+ /** The owner's attached backends with live status. Reads wake nothing. */
84
+ readBackends(authority: ComputerGrant, actor: string): ComputerBackendView[];
85
+ /** Attach the owner's machine; a replay of the same request returns it. */
86
+ attachLocalBackend(authority: ComputerGrant, actor: string, input: LocalBackendAttachInput): {
87
+ backendId: string;
88
+ error?: undefined;
89
+ } | {
90
+ error: "request_conflict" | "invalid" | "not_owner" | "unknown_computer" | "not_enabled" | "local_limit";
91
+ backendId?: undefined;
92
+ };
93
+ /** Detach the owner's machine and close its live connection. */
94
+ detachLocalBackend(authority: ComputerGrant, actor: string, input: LocalBackendDetachInput): {
95
+ detached: boolean;
96
+ error?: undefined;
97
+ } | {
98
+ error: "request_conflict" | "invalid" | "not_owner" | "unknown_computer" | "not_enabled" | "local_limit";
99
+ detached?: undefined;
100
+ };
82
101
  /** An admitted fleet control starts exactly this Computer's hosted backend. */
83
102
  startHostedComputer(authority: ComputerGrant): Promise<{
84
103
  state: "running";
@@ -14,7 +14,7 @@ import { ComputerDO as NativeComputerDO, ComputerOperationConflictError, } from
14
14
  import { patchInputSchema, patchOutputSchema, } from "@fungi.computer/knapsack/files-patch";
15
15
  import { ComputerFileConflict, computerExecutionRequestSchema, computerValueSchema, computerPortInputSchema, listInputSchema, listOutputSchema, readBytesInputSchema, writeInputSchema, replaceInputSchema, writeOutputSchema, mkdirOutputSchema, computerPortsOutputSchema, computerPortOutputSchema, computerPortRemovalOutputSchema, processListOutputSchema, processKillOutputSchema, computerOperationResultSchema, mintComputerRequestId, processIdInputSchema, } from "@fungi.computer/computer-contract";
16
16
  import { workflowGitExecutionEnvironment, workflowGitPassGrantSchema, } from "@fungi.computer/braid/runtime";
17
- import { checkComputerGrant, computerActionSchema, computerGrantSchema, createFleetBacking, FleetGrantRefused, FleetLifecycle, } from "@fungi.computer/computer/fleet";
17
+ import { checkComputerGrant, computerActionSchema, computerGrantSchema, ComputerBackingError, createFleetBacking, FleetGrantRefused, FleetLifecycle, } from "@fungi.computer/computer/fleet";
18
18
  import { AppInstanceError, selectionOf } from "../index.js";
19
19
  import {} from "../cloudflare.js";
20
20
  import { computerSlots } from "../computer.js";
@@ -160,6 +160,68 @@ export class ComputerDO extends NativeComputerDO {
160
160
  owner.ensure();
161
161
  this.#backends = owner.computerCreated(this.#id(), z.array(hostedBackingSchema).parse(backings)).backends;
162
162
  }
163
+ /**
164
+ * The attached set changed in storage: rebuild the Workspace now, so a
165
+ * detached machine's live connection closes before the control returns.
166
+ */
167
+ #attachedSetChanged() {
168
+ this.#backends = undefined;
169
+ this.workspace();
170
+ }
171
+ /** The owner's attached backends with live status. Reads wake nothing. */
172
+ readBackends(authority, actor) {
173
+ this.#accept(authority, "backing");
174
+ // Describing first gives a never-used Computer its creation record.
175
+ const described = this.describeBackends();
176
+ const owners = createFleetBacking(this.state.storage).localOwners(this.#id());
177
+ return described.map((backend) => ({
178
+ id: backend.id,
179
+ kind: backend.kind,
180
+ status: backend.status,
181
+ queuePosition: null,
182
+ hostId: backend.hostId ?? null,
183
+ hostLabel: backend.hostLabel ?? null,
184
+ folderLabel: backend.folderLabel ?? null,
185
+ detachable: owners.get(backend.id) === actor,
186
+ }));
187
+ }
188
+ /** Attach the owner's machine; a replay of the same request returns it. */
189
+ attachLocalBackend(authority, actor, input) {
190
+ this.#accept(authority, "backing");
191
+ // The default Computer gains its creation record on first read.
192
+ this.attachedBackends();
193
+ try {
194
+ const result = createFleetBacking(this.state.storage).attachLocal(actor, {
195
+ ...input,
196
+ computerId: this.#id(),
197
+ });
198
+ this.#attachedSetChanged();
199
+ return { backendId: result.backendId };
200
+ }
201
+ catch (cause) {
202
+ if (cause instanceof ComputerBackingError)
203
+ return { error: cause.code };
204
+ throw cause;
205
+ }
206
+ }
207
+ /** Detach the owner's machine and close its live connection. */
208
+ detachLocalBackend(authority, actor, input) {
209
+ this.#accept(authority, "backing");
210
+ this.attachedBackends();
211
+ try {
212
+ const result = createFleetBacking(this.state.storage).detachLocal(actor, {
213
+ ...input,
214
+ computerId: this.#id(),
215
+ });
216
+ this.#attachedSetChanged();
217
+ return { detached: result.detached };
218
+ }
219
+ catch (cause) {
220
+ if (cause instanceof ComputerBackingError)
221
+ return { error: cause.code };
222
+ throw cause;
223
+ }
224
+ }
163
225
  /** An admitted fleet control starts exactly this Computer's hosted backend. */
164
226
  async startHostedComputer(authority) {
165
227
  this.#accept(authority, "start");
@@ -0,0 +1,50 @@
1
+ import { type CredentialRecord, type CredentialStorage } from "@fungi.computer/veil/credential-store";
2
+ import { type ModelKeyRecord, type ModelKeyVault } from "@fungi.computer/veil/model-keys";
3
+ /**
4
+ * This instance's own model-key owner. Provider API keys are sealed (AES-GCM)
5
+ * under a key derived from the instance master secret, a host secret that never
6
+ * enters the repository, storage or a log. A key leaves the vault only inside
7
+ * the request it is sent with; listings carry no secret.
8
+ */
9
+ /** Why a key could not be stored or used; stable, secret-free. */
10
+ export type ModelKeyRefusal = "invalid_key" | "key_rejected" | "provider_unavailable" | "custody_unavailable" | "key_removed" | "target_denied" | "limit";
11
+ export declare class ModelKeyRefused extends Error {
12
+ readonly reason: ModelKeyRefusal;
13
+ constructor(reason: ModelKeyRefusal);
14
+ }
15
+ export type { ModelKeyRecord };
16
+ /** What the owner submits to seal one provider key. */
17
+ export type ModelKeySealInput = Readonly<{
18
+ provider: string;
19
+ label: string;
20
+ apiKey: string;
21
+ }>;
22
+ export type ModelKeyStorage = CredentialStorage;
23
+ /**
24
+ * The instance's one encrypted credential store. Listing and removal need no
25
+ * key; sealing and opening refuse without one.
26
+ */
27
+ export declare function createInstanceCredentialStore(options: {
28
+ storage: CredentialStorage;
29
+ credentialKey: string | undefined;
30
+ now?: () => number;
31
+ }): {
32
+ put(input: {
33
+ kind: string;
34
+ label: string;
35
+ secret: string;
36
+ }): Promise<CredentialRecord>;
37
+ list(kind?: string): Promise<readonly CredentialRecord[]>;
38
+ get(credentialId: string): Promise<CredentialRecord | null>;
39
+ remove(credentialId: string): Promise<"deleted" | "absent">;
40
+ withSecret<T>(credentialId: string, action: (secret: string, record: CredentialRecord) => Promise<T> | T): Promise<T>;
41
+ };
42
+ export declare function createModelKeyVault(options: {
43
+ storage: ModelKeyStorage;
44
+ /** The instance credential key (32 bytes, base64url); absent means no custody. */
45
+ credentialKey: string | undefined;
46
+ fetch?: typeof globalThis.fetch;
47
+ now?: () => number;
48
+ }): ModelKeyVault & Readonly<{
49
+ get: (keyId: string) => Promise<ModelKeyRecord | null>;
50
+ }>;
@@ -0,0 +1,147 @@
1
+ import { createCredentialSealer, createCredentialStore, CredentialError, } from "@fungi.computer/veil/credential-store";
2
+ import { isModelKeyProvider, modelKeyForwardedHeaders, modelKeyBaseUrl, modelKeyTarget, modelKeyValidationRequest, modelKeyValidationResult, } from "@fungi.computer/veil/model-keys";
3
+ export class ModelKeyRefused extends Error {
4
+ reason;
5
+ constructor(reason) {
6
+ super(reason);
7
+ this.reason = reason;
8
+ this.name = "ModelKeyRefused";
9
+ }
10
+ }
11
+ const kindOf = (provider) => `model-key/${provider}`;
12
+ const providerOf = (kind) => {
13
+ const provider = kind.slice("model-key/".length);
14
+ if (!isModelKeyProvider(provider))
15
+ throw new ModelKeyRefused("invalid_key");
16
+ return provider;
17
+ };
18
+ const maxKeyLength = 16_384;
19
+ const publicRecord = (record) => ({
20
+ keyId: record.credentialId,
21
+ provider: providerOf(record.kind),
22
+ label: record.label,
23
+ createdAt: record.createdAt,
24
+ validatedAt: record.validatedAt,
25
+ });
26
+ /** Anthropic authenticates with `x-api-key`; the others take a bearer token. */
27
+ function authenticated(provider, headers, apiKey) {
28
+ const next = new Headers(headers);
29
+ if (provider === "anthropic")
30
+ next.set("x-api-key", apiKey);
31
+ else
32
+ next.set("authorization", `Bearer ${apiKey}`);
33
+ return next;
34
+ }
35
+ /**
36
+ * The instance's one encrypted credential store. Listing and removal need no
37
+ * key; sealing and opening refuse without one.
38
+ */
39
+ export function createInstanceCredentialStore(options) {
40
+ const unavailable = () => Promise.reject(new CredentialError("unavailable"));
41
+ const sealer = options.credentialKey === undefined
42
+ ? { seal: unavailable, open: unavailable }
43
+ : createCredentialSealer({
44
+ activeKeyId: "instance",
45
+ keys: { instance: options.credentialKey },
46
+ }, "fungi.oyster.credentials.v1");
47
+ const storeOptions = {
48
+ storage: options.storage,
49
+ sealer,
50
+ };
51
+ if (options.now !== undefined)
52
+ storeOptions.now = options.now;
53
+ return createCredentialStore(storeOptions);
54
+ }
55
+ export function createModelKeyVault(options) {
56
+ const send = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
57
+ const credentialKey = options.credentialKey;
58
+ const credentials = createInstanceCredentialStore(options);
59
+ const store = () => credentials;
60
+ const custody = async (work) => {
61
+ try {
62
+ return await work();
63
+ }
64
+ catch (cause) {
65
+ if (cause instanceof CredentialError)
66
+ throw new ModelKeyRefused(cause.code === "absent"
67
+ ? "key_removed"
68
+ : cause.code === "limit"
69
+ ? "limit"
70
+ : "custody_unavailable");
71
+ throw cause;
72
+ }
73
+ };
74
+ return {
75
+ /** Validate with one cheap authenticated read, then store only the sealed key. */
76
+ async seal(input) {
77
+ const { provider, label, apiKey } = input;
78
+ if (!isModelKeyProvider(provider) ||
79
+ provider === "openai-compatible" ||
80
+ label.length === 0 ||
81
+ label.length > 64 ||
82
+ apiKey.length === 0 ||
83
+ apiKey.length > maxKeyLength)
84
+ throw new ModelKeyRefused("invalid_key");
85
+ if (credentialKey === undefined)
86
+ throw new ModelKeyRefused("custody_unavailable");
87
+ const baseUrl = modelKeyBaseUrl(provider);
88
+ const probe = modelKeyValidationRequest({ provider, baseUrl }, AbortSignal.timeout(15_000));
89
+ let status;
90
+ try {
91
+ const response = await send(new Request(probe, {
92
+ headers: authenticated(provider, probe.headers, apiKey),
93
+ }));
94
+ status = response.status;
95
+ await response.body?.cancel();
96
+ }
97
+ catch {
98
+ // Transport text can echo request headers; surface only the typed cause.
99
+ throw new ModelKeyRefused("provider_unavailable");
100
+ }
101
+ const verdict = modelKeyValidationResult(status);
102
+ if (verdict === "rejected")
103
+ throw new ModelKeyRefused("key_rejected");
104
+ if (verdict === "unavailable")
105
+ throw new ModelKeyRefused("provider_unavailable");
106
+ return publicRecord(await custody(() => credentials.put({ kind: kindOf(provider), label, secret: apiKey })));
107
+ },
108
+ async list() {
109
+ return (await custody(() => store().list()))
110
+ .filter((record) => record.kind.startsWith("model-key/"))
111
+ .map(publicRecord);
112
+ },
113
+ async get(keyId) {
114
+ const record = await custody(() => store().get(keyId));
115
+ return record === null ? null : publicRecord(record);
116
+ },
117
+ remove(keyId) {
118
+ return custody(() => store().remove(keyId));
119
+ },
120
+ /** Send one provider request with the key attached; the caller's auth is dropped. */
121
+ send(keyId, request) {
122
+ return custody(() => store().withSecret(keyId, (apiKey, record) => {
123
+ const provider = providerOf(record.kind);
124
+ let target;
125
+ try {
126
+ target = modelKeyTarget({
127
+ locator: record.credentialId,
128
+ provider,
129
+ baseUrl: modelKeyBaseUrl(provider),
130
+ }, request);
131
+ }
132
+ catch {
133
+ throw new ModelKeyRefused("target_denied");
134
+ }
135
+ // `duplex` is a Node/Workers extension lib.dom's RequestInit omits.
136
+ const init = {
137
+ method: request.method,
138
+ headers: authenticated(provider, modelKeyForwardedHeaders(request), apiKey),
139
+ body: request.method === "GET" ? null : request.body,
140
+ signal: request.signal,
141
+ duplex: "half",
142
+ };
143
+ return send(new Request(target, init));
144
+ }));
145
+ },
146
+ };
147
+ }