@fungi.computer/oyster 0.37.2 → 0.38.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -4
- package/dist/agents.js +9 -2
- package/dist/app-builds.d.ts +1 -1
- package/dist/app-region.d.ts +94 -0
- package/dist/app-region.js +316 -0
- package/dist/authorization.d.ts +58 -9
- package/dist/authorization.js +56 -11
- package/dist/boot-host-script.js +1 -1
- package/dist/build/candidate-builder.d.ts +1 -1
- package/dist/build/candidate-cli.mjs +284 -17
- package/dist/build/effect.d.ts +3 -3
- package/dist/build/submission-contract.d.ts +1 -1
- package/dist/build/workspace-build.d.ts +2 -2
- package/dist/channels/discord-replies.d.ts +8 -1
- package/dist/channels/discord-replies.js +80 -29
- package/dist/cloudflare.d.ts +1 -0
- package/dist/cloudflare.js +11 -0
- package/dist/credential-migration-001.d.ts +14 -0
- package/dist/credential-migration-001.js +13 -0
- package/dist/credential-migration-002.d.ts +38 -0
- package/dist/credential-migration-002.js +74 -0
- package/dist/embed-metafiles.js +2 -2
- package/dist/embed-scripts.js +1 -1
- package/dist/host.d.ts +2 -0
- package/dist/host.js +20 -1
- package/dist/index.d.ts +15 -1
- package/dist/index.js +19 -0
- package/dist/invocation.d.ts +165 -0
- package/dist/invocation.js +67 -0
- package/dist/keys.d.ts +4 -3
- package/dist/keys.js +5 -4
- package/dist/mcp-owner.d.ts +4 -3
- package/dist/mcp-owner.js +3 -2
- package/dist/page/mount.js +5 -1
- package/dist/page/region.d.ts +6 -0
- package/dist/page/region.js +12 -0
- package/dist/page-config.d.ts +2 -0
- package/dist/page-config.js +2 -0
- package/dist/page-script.js +2 -2
- package/dist/source/seed-receipt.d.ts +1 -1
- package/dist/source/template-seed.d.ts +1 -1
- package/dist/standalone/agent-connections.d.ts +49 -1
- package/dist/standalone/agent-connections.js +101 -12
- package/dist/standalone/agent-self.js +2 -1
- package/dist/standalone/agents.d.ts +7 -3
- package/dist/standalone/agents.js +42 -19
- package/dist/standalone/computer-fleet.d.ts +12 -6
- package/dist/standalone/computer-fleet.js +70 -29
- package/dist/standalone/computer.js +39 -14
- package/dist/standalone/instance.d.ts +3 -1
- package/dist/standalone/instance.js +8 -0
- package/dist/standalone/model-key-vault.d.ts +33 -4
- package/dist/standalone/model-key-vault.js +74 -17
- package/dist/standalone/preview.js +11 -10
- package/dist/standalone/try-cli.d.ts +12 -2
- package/dist/standalone/try-cli.js +170 -32
- package/dist/standalone/try-worker.d.ts +2 -0
- package/dist/standalone/try-worker.js +15 -0
- package/dist/standalone/worker.js +3 -3
- package/dist/standalone/workflow-host.d.ts +1 -1
- package/dist/standalone/workflows.d.ts +3 -3
- package/dist/standalone/workflows.js +7 -0
- package/dist/testing/capabilities.d.ts +2 -0
- package/dist/testing/capabilities.js +2 -0
- package/dist/webhook-custody.d.ts +14 -3
- package/dist/webhook-custody.js +165 -43
- package/dist/webhooks.d.ts +1 -1
- package/dist/webhooks.js +15 -3
- package/dist/workers-git.d.ts +24 -8
- package/dist/workers-git.js +105 -15
- package/dist/workers.d.ts +16 -0
- package/dist/workers.js +95 -5
- package/docs/api/apps.md +31 -31
- package/docs/api/authorization.md +119 -17
- package/docs/api/build-contract.md +8 -8
- package/docs/api/build.md +163 -174
- package/docs/api/cloudflare.md +171 -0
- package/docs/api/host.md +1 -0
- package/docs/api/index.md +23 -0
- package/docs/api/invocation.md +623 -23
- package/docs/api/keys.md +6 -6
- package/docs/api/pack.md +3 -3
- package/docs/api/page/mount.md +22 -20
- package/docs/api/workers-git.md +273 -157
- package/docs/api/workers.md +257 -175
- package/package.json +19 -18
package/README.md
CHANGED
|
@@ -194,10 +194,11 @@ npx @fungi.computer/oyster install-apps
|
|
|
194
194
|
```
|
|
195
195
|
|
|
196
196
|
Your workers.dev subdomain is on the Workers & Pages overview in the Cloudflare
|
|
197
|
-
dashboard. `OYSTER_CREDENTIAL_KEY` seals the model API keys you add in Settings
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
197
|
+
dashboard. `OYSTER_CREDENTIAL_KEY` seals the model API keys you add in Settings
|
|
198
|
+
and the webhook, subscription and Discord reply secrets Oyster stores; without
|
|
199
|
+
it those features refuse as unavailable. Keep a copy, because losing it makes
|
|
200
|
+
those secrets unreadable. Set `OYSTER_ORIGIN` in `wrangler.jsonc` if you deploy
|
|
201
|
+
again later, since every deploy replaces the Worker's variables.
|
|
201
202
|
|
|
202
203
|
The first `install-apps` takes about 15 to 20 minutes, mostly building the seven
|
|
203
204
|
Apps on your Computer, two at a time. It prints a line per step and a timing
|
package/dist/agents.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { agent, agents as agentCollection, owner, routes, } from "./authorization.js";
|
|
2
2
|
import * as Schema from "effect/Schema";
|
|
3
|
+
import { agentNameSchema } from "@fungi.computer/agar/agents";
|
|
3
4
|
import { z } from "zod";
|
|
4
5
|
import {} from "./host.js";
|
|
5
6
|
import { agentAvatarSchema } from "./agent-avatars.js";
|
|
@@ -192,6 +193,9 @@ function ownerAgentRoutes(agents, via) {
|
|
|
192
193
|
const body = Schema.decodeUnknownOption(createSchema)(await context.req.json());
|
|
193
194
|
if (body._tag === "None")
|
|
194
195
|
return refusal(400, "Name the agent");
|
|
196
|
+
const name = agentNameSchema.safeParse(body.value.name);
|
|
197
|
+
if (!name.success)
|
|
198
|
+
return refusal(400, "Name the agent");
|
|
195
199
|
const avatar = body.value.avatar === undefined
|
|
196
200
|
? undefined
|
|
197
201
|
: agentAvatarSchema.safeParse(body.value.avatar);
|
|
@@ -199,7 +203,7 @@ function ownerAgentRoutes(agents, via) {
|
|
|
199
203
|
return refusal(400, "Choose a valid avatar");
|
|
200
204
|
// The owner's own authenticated request creates this Agent; its App tools
|
|
201
205
|
// are approved the same way direct owner approval is, with no second path.
|
|
202
|
-
return Response.json(await agents.create(
|
|
206
|
+
return Response.json(await agents.create(name.data, body.value.requestId, principal, "owner-direct", avatar?.data));
|
|
203
207
|
})
|
|
204
208
|
.post("/agents/:agentId/archive", owner(via), (context, admission) => changeArchive(agents, context.req.param("agentId"), true, admission))
|
|
205
209
|
.post("/agents/:agentId/unarchive", owner(via), (context, admission) => changeArchive(agents, context.req.param("agentId"), false, admission));
|
|
@@ -232,7 +236,10 @@ function createAgentRoutes(agents) {
|
|
|
232
236
|
const body = Schema.decodeUnknownOption(renameSchema)(await context.req.json());
|
|
233
237
|
if (body._tag === "None")
|
|
234
238
|
return refusal(400, "Name the agent");
|
|
235
|
-
const
|
|
239
|
+
const name = agentNameSchema.safeParse(body.value.name);
|
|
240
|
+
if (!name.success)
|
|
241
|
+
return refusal(400, "Name the agent");
|
|
242
|
+
const result = await agents.rename(agentId, name.data, principal);
|
|
236
243
|
if ("error" in result)
|
|
237
244
|
return refusal(result.error === "not_found"
|
|
238
245
|
? 404
|
package/dist/app-builds.d.ts
CHANGED
|
@@ -69,7 +69,7 @@ declare const oysterBuildSourceSchema: Schema.Struct<{
|
|
|
69
69
|
readonly backend: Schema.Union<readonly [Schema.Null, Schema.Struct<{
|
|
70
70
|
readonly entry: Schema.optional<Schema.String>;
|
|
71
71
|
readonly runtime: Schema.Struct<{
|
|
72
|
-
readonly kind: Schema.
|
|
72
|
+
readonly kind: Schema.Literals<readonly ["durable-facet", "region"]>;
|
|
73
73
|
readonly stateSchema: Schema.Number;
|
|
74
74
|
}>;
|
|
75
75
|
readonly compatibilityDate: Schema.String;
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { AppMethodCallContext } from "@fungi.computer/puffball/app-method-runtime";
|
|
2
|
+
import { type AppRegionEvent, type AppRegionReply } from "@fungi.computer/puffball/backend";
|
|
3
|
+
/** The socket operations a Region supervisor uses; App code never sees one. */
|
|
4
|
+
export type AppRegionSocket = Pick<WebSocket, "send" | "close" | "serializeAttachment" | "deserializeAttachment" | "readyState">;
|
|
5
|
+
/**
|
|
6
|
+
* The native Durable Object surface a Region supervisor uses: hibernating
|
|
7
|
+
* WebSockets and the Instance's one shared alarm. App code never sees it.
|
|
8
|
+
*/
|
|
9
|
+
export type AppRegionNative<Socket extends AppRegionSocket = WebSocket, Client = WebSocket> = Readonly<{
|
|
10
|
+
/** A fresh client/server socket pair for one admitted upgrade. */
|
|
11
|
+
pair(): {
|
|
12
|
+
client: Client;
|
|
13
|
+
server: Socket;
|
|
14
|
+
};
|
|
15
|
+
/** Accept the server socket for hibernation under the Region tag. */
|
|
16
|
+
accept(server: Socket): void;
|
|
17
|
+
/**
|
|
18
|
+
* Every Region socket on this Instance, including one the server closed
|
|
19
|
+
* whose client has not yet answered the close.
|
|
20
|
+
*/
|
|
21
|
+
sockets(): readonly Socket[];
|
|
22
|
+
/** The App's persisted next wake, or null. */
|
|
23
|
+
readWake(): number | null;
|
|
24
|
+
/** Persist or clear the App's next wake. */
|
|
25
|
+
writeWake(at: number | null): void;
|
|
26
|
+
/** Lower the shared native alarm; never postpones another owner's wake. */
|
|
27
|
+
scheduleWake(at: number): Promise<void>;
|
|
28
|
+
/** The 101 response that hands the client socket to the browser. */
|
|
29
|
+
upgraded(client: Client): Response;
|
|
30
|
+
/** The supervisor's clock, in epoch milliseconds. */
|
|
31
|
+
now(): number;
|
|
32
|
+
}>;
|
|
33
|
+
/** Run one bounded event in the App, under the Instance's current authority. */
|
|
34
|
+
export type AppRegionDeliver = (event: AppRegionEvent) => Promise<AppRegionReply>;
|
|
35
|
+
/**
|
|
36
|
+
* Supervisor-enforced bounds on one Instance's Region. App code cannot raise
|
|
37
|
+
* them; each refusal ends only the socket that crossed it.
|
|
38
|
+
*/
|
|
39
|
+
export declare const appRegionLimits: {
|
|
40
|
+
/**
|
|
41
|
+
* Region sockets per Instance, counting ones still closing (each holds a
|
|
42
|
+
* native socket until its client answers); the next connect gets 429.
|
|
43
|
+
*/
|
|
44
|
+
readonly socketsPerInstance: 256;
|
|
45
|
+
/** One caller's share of those sockets; the next connect gets 429. */
|
|
46
|
+
readonly socketsPerCaller: 32;
|
|
47
|
+
/** Connects one caller may make in each one-minute window; then 429. */
|
|
48
|
+
readonly connectsPerCallerPerMinute: 30;
|
|
49
|
+
/** Inbound messages one socket may send per one-second window. */
|
|
50
|
+
readonly messagesPerSecond: 32;
|
|
51
|
+
/**
|
|
52
|
+
* Bytes the App may send to one socket per one-second window. Workers
|
|
53
|
+
* sockets expose no bufferedAmount, so a consumer that cannot take this is
|
|
54
|
+
* closed (1013) instead of buffered without limit.
|
|
55
|
+
*/
|
|
56
|
+
readonly sendBytesPerSecond: 524288;
|
|
57
|
+
/** The earliest App wake is this long after the event that asked for it. */
|
|
58
|
+
readonly minWakeDelayMs: 1000;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* Supervisor-owned Region lifecycle: native sockets and alarms stay here; the
|
|
62
|
+
* App receives only bounded Region events and answers with a bounded reply.
|
|
63
|
+
*/
|
|
64
|
+
export declare function createAppRegion<Socket extends AppRegionSocket, Client>(native: AppRegionNative<Socket, Client>, deliver: AppRegionDeliver): {
|
|
65
|
+
/**
|
|
66
|
+
* Accept an already-admitted connection; the caller comes from the host.
|
|
67
|
+
* Its connect runs in the admitting frame, later events in fresh ones.
|
|
68
|
+
*/
|
|
69
|
+
connect(caller: AppMethodCallContext, deliverConnect?: AppRegionDeliver): Promise<Response>;
|
|
70
|
+
/** Deliver one bounded text frame from an attested socket. */
|
|
71
|
+
message(socket: Socket, data: string | ArrayBuffer): Promise<void>;
|
|
72
|
+
/**
|
|
73
|
+
* The browser closed: send the server's half of the close, then tell the
|
|
74
|
+
* App if the socket was attested.
|
|
75
|
+
*/
|
|
76
|
+
close(socket: Socket, code: number, reason: string): Promise<void>;
|
|
77
|
+
/** Deliver the App's wake when due; the shared alarm may fire for others. */
|
|
78
|
+
alarm(): Promise<void>;
|
|
79
|
+
/** Disable or removal: close every socket and drop the App's wake; data stays. */
|
|
80
|
+
fence(reason: string): void;
|
|
81
|
+
};
|
|
82
|
+
/** One Instance's Region supervisor. */
|
|
83
|
+
export type AppRegion = ReturnType<typeof createAppRegion>;
|
|
84
|
+
/** The Durable Object surface a Region needs: hibernating sockets and SQLite. */
|
|
85
|
+
export type AppRegionDurableState = Pick<DurableObjectState, "acceptWebSocket" | "getWebSockets" | "getTags"> & Readonly<{
|
|
86
|
+
storage: Pick<DurableObjectStorage, "sql">;
|
|
87
|
+
}>;
|
|
88
|
+
/**
|
|
89
|
+
* Native hibernating sockets and a persisted wake in the supervisor's own
|
|
90
|
+
* SQLite. The supervisor's shared alarm is lowered through `scheduleWake`.
|
|
91
|
+
*/
|
|
92
|
+
export declare function durableAppRegionNative(ctx: AppRegionDurableState, scheduleWake: (at: number) => Promise<void>): AppRegionNative;
|
|
93
|
+
/** Whether a hibernated socket a Durable Object woke for is a Region socket. */
|
|
94
|
+
export declare function isAppRegionSocket(ctx: Pick<DurableObjectState, "getTags">, socket: WebSocket): boolean;
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import { defineIdFamily } from "@fungi.computer/cairn/id";
|
|
2
|
+
import * as z from "zod";
|
|
3
|
+
import { AppInstanceError } from "./index.js";
|
|
4
|
+
import { appMethodCallerSchema } from "@fungi.computer/puffball/app-method-runtime";
|
|
5
|
+
import { appRegionReplySchema, maxAppRegionMessageBytes, } from "@fungi.computer/puffball/backend";
|
|
6
|
+
/** `WebSocket.OPEN`: a socket neither side has started to close. */
|
|
7
|
+
const openState = 1;
|
|
8
|
+
/** One supervisor-minted id per accepted socket; never chosen by the browser. */
|
|
9
|
+
const regionIds = defineIdFamily({
|
|
10
|
+
family: "app-region",
|
|
11
|
+
version: 1,
|
|
12
|
+
kinds: { connection: { prefix: "region_conn" } },
|
|
13
|
+
});
|
|
14
|
+
/** Text frames only, bounded before App code runs. */
|
|
15
|
+
const regionFrameSchema = z
|
|
16
|
+
.string()
|
|
17
|
+
.refine((data) => new TextEncoder().encode(data).byteLength <= maxAppRegionMessageBytes);
|
|
18
|
+
/** Only the host stamps this at admission; it survives hibernation natively. */
|
|
19
|
+
const attachmentSchema = z.strictObject({
|
|
20
|
+
connection: z.string().min(1).max(64),
|
|
21
|
+
caller: z.unknown(),
|
|
22
|
+
});
|
|
23
|
+
const closeCodes = {
|
|
24
|
+
normal: 1000,
|
|
25
|
+
unsupported: 1003,
|
|
26
|
+
policy: 1008,
|
|
27
|
+
refused: 1011,
|
|
28
|
+
/** The browser is not draining what the App sends. */
|
|
29
|
+
slowConsumer: 1013,
|
|
30
|
+
fenced: 4403,
|
|
31
|
+
/** The browser sent more messages than its window admits. */
|
|
32
|
+
tooManyMessages: 4429,
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Supervisor-enforced bounds on one Instance's Region. App code cannot raise
|
|
36
|
+
* them; each refusal ends only the socket that crossed it.
|
|
37
|
+
*/
|
|
38
|
+
export const appRegionLimits = {
|
|
39
|
+
/**
|
|
40
|
+
* Region sockets per Instance, counting ones still closing (each holds a
|
|
41
|
+
* native socket until its client answers); the next connect gets 429.
|
|
42
|
+
*/
|
|
43
|
+
socketsPerInstance: 256,
|
|
44
|
+
/** One caller's share of those sockets; the next connect gets 429. */
|
|
45
|
+
socketsPerCaller: 32,
|
|
46
|
+
/** Connects one caller may make in each one-minute window; then 429. */
|
|
47
|
+
connectsPerCallerPerMinute: 30,
|
|
48
|
+
/** Inbound messages one socket may send per one-second window. */
|
|
49
|
+
messagesPerSecond: 32,
|
|
50
|
+
/**
|
|
51
|
+
* Bytes the App may send to one socket per one-second window. Workers
|
|
52
|
+
* sockets expose no bufferedAmount, so a consumer that cannot take this is
|
|
53
|
+
* closed (1013) instead of buffered without limit.
|
|
54
|
+
*/
|
|
55
|
+
sendBytesPerSecond: 524_288,
|
|
56
|
+
/** The earliest App wake is this long after the event that asked for it. */
|
|
57
|
+
minWakeDelayMs: 1_000,
|
|
58
|
+
};
|
|
59
|
+
const windowMs = 1_000;
|
|
60
|
+
const connectWindowMs = 60_000;
|
|
61
|
+
/** One caller: the host-stamped scope and actor, never anything the browser sent. */
|
|
62
|
+
const callerKey = (caller) => JSON.stringify([caller.scope, caller.actor]);
|
|
63
|
+
const utf8Bytes = (data) => new TextEncoder().encode(data).byteLength;
|
|
64
|
+
/** A close code a server may send back: never 1005, 1006 or 1015. */
|
|
65
|
+
const echoCloseCode = (code) => code === 1000 ||
|
|
66
|
+
(code >= 1001 &&
|
|
67
|
+
code <= 1014 &&
|
|
68
|
+
code !== 1004 &&
|
|
69
|
+
code !== 1005 &&
|
|
70
|
+
code !== 1006) ||
|
|
71
|
+
(code >= 3000 && code <= 4999)
|
|
72
|
+
? code
|
|
73
|
+
: closeCodes.normal;
|
|
74
|
+
/**
|
|
75
|
+
* Supervisor-owned Region lifecycle: native sockets and alarms stay here; the
|
|
76
|
+
* App receives only bounded Region events and answers with a bounded reply.
|
|
77
|
+
*/
|
|
78
|
+
export function createAppRegion(native, deliver) {
|
|
79
|
+
// Per-connection windows live in memory: a socket busy enough to cross a
|
|
80
|
+
// bound keeps its Durable Object awake, so hibernation never resets one.
|
|
81
|
+
const windows = new Map();
|
|
82
|
+
const windowOf = (connection) => {
|
|
83
|
+
const now = native.now();
|
|
84
|
+
const current = windows.get(connection);
|
|
85
|
+
if (current !== undefined && now - current.start < windowMs)
|
|
86
|
+
return current;
|
|
87
|
+
const fresh = { start: now, messages: 0, sentBytes: 0 };
|
|
88
|
+
windows.set(connection, fresh);
|
|
89
|
+
return fresh;
|
|
90
|
+
};
|
|
91
|
+
const connects = new Map();
|
|
92
|
+
const regionFull = (reason) => Response.json({ error: "region_full", reason }, { status: 429 });
|
|
93
|
+
const attachment = (socket) => {
|
|
94
|
+
const parsed = attachmentSchema.safeParse(socket.deserializeAttachment());
|
|
95
|
+
if (!parsed.success)
|
|
96
|
+
return null;
|
|
97
|
+
const caller = appMethodCallerSchema.safeParse(parsed.data.caller);
|
|
98
|
+
return caller.success
|
|
99
|
+
? { connection: parsed.data.connection, caller: caller.data }
|
|
100
|
+
: null;
|
|
101
|
+
};
|
|
102
|
+
const apply = async (raw) => {
|
|
103
|
+
const reply = appRegionReplySchema.parse(raw);
|
|
104
|
+
// A socket already closing (by the App, a bound or a fence) stays listed
|
|
105
|
+
// until its client answers; it receives nothing more.
|
|
106
|
+
const open = new Map();
|
|
107
|
+
for (const socket of native.sockets()) {
|
|
108
|
+
if (socket.readyState !== openState)
|
|
109
|
+
continue;
|
|
110
|
+
const stamp = attachment(socket);
|
|
111
|
+
if (stamp !== null)
|
|
112
|
+
open.set(stamp.connection, socket);
|
|
113
|
+
}
|
|
114
|
+
for (const { connection, data } of reply.send ?? []) {
|
|
115
|
+
const socket = open.get(connection);
|
|
116
|
+
if (socket === undefined)
|
|
117
|
+
continue;
|
|
118
|
+
const window = windowOf(connection);
|
|
119
|
+
window.sentBytes += utf8Bytes(data);
|
|
120
|
+
if (window.sentBytes > appRegionLimits.sendBytesPerSecond) {
|
|
121
|
+
// Drop instead of buffering: this consumer is not keeping up. Its
|
|
122
|
+
// window stays until the client's close, so nothing resets it.
|
|
123
|
+
open.delete(connection);
|
|
124
|
+
socket.close(closeCodes.slowConsumer, "Region consumer too slow");
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
// Only an open socket is sent to: a send after close throws, and one
|
|
128
|
+
// socket must never abort the rest of the reply.
|
|
129
|
+
if (socket.readyState === openState)
|
|
130
|
+
socket.send(data);
|
|
131
|
+
}
|
|
132
|
+
for (const connection of reply.close ?? []) {
|
|
133
|
+
open.get(connection)?.close(closeCodes.normal, "Closed by App");
|
|
134
|
+
open.delete(connection);
|
|
135
|
+
}
|
|
136
|
+
if (reply.wakeAt === null)
|
|
137
|
+
native.writeWake(null);
|
|
138
|
+
else if (reply.wakeAt !== undefined) {
|
|
139
|
+
// A wake at or before now would re-enter the App at once, forever.
|
|
140
|
+
const at = Math.max(reply.wakeAt, native.now() + appRegionLimits.minWakeDelayMs);
|
|
141
|
+
native.writeWake(at);
|
|
142
|
+
await native.scheduleWake(at);
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
return {
|
|
146
|
+
/**
|
|
147
|
+
* Accept an already-admitted connection; the caller comes from the host.
|
|
148
|
+
* Its connect runs in the admitting frame, later events in fresh ones.
|
|
149
|
+
*/
|
|
150
|
+
async connect(caller, deliverConnect = deliver) {
|
|
151
|
+
const stamped = appMethodCallerSchema.parse(caller);
|
|
152
|
+
const sockets = native.sockets();
|
|
153
|
+
if (sockets.length >= appRegionLimits.socketsPerInstance)
|
|
154
|
+
return regionFull("Region socket limit reached");
|
|
155
|
+
const key = callerKey(stamped);
|
|
156
|
+
const held = sockets.filter((socket) => {
|
|
157
|
+
const stamp = attachment(socket);
|
|
158
|
+
return stamp !== null && callerKey(stamp.caller) === key;
|
|
159
|
+
}).length;
|
|
160
|
+
if (held >= appRegionLimits.socketsPerCaller)
|
|
161
|
+
return regionFull("Region socket share reached");
|
|
162
|
+
const now = native.now();
|
|
163
|
+
const recent = connects.get(key);
|
|
164
|
+
const window = recent !== undefined && now - recent.start < connectWindowMs
|
|
165
|
+
? recent
|
|
166
|
+
: { start: now, count: 0 };
|
|
167
|
+
if (window.count >= appRegionLimits.connectsPerCallerPerMinute)
|
|
168
|
+
return regionFull("Region connect rate reached");
|
|
169
|
+
window.count += 1;
|
|
170
|
+
connects.set(key, window);
|
|
171
|
+
for (const [other, { start }] of connects)
|
|
172
|
+
if (now - start >= connectWindowMs)
|
|
173
|
+
connects.delete(other);
|
|
174
|
+
const { client, server } = native.pair();
|
|
175
|
+
const connection = regionIds.connection.generate();
|
|
176
|
+
native.accept(server);
|
|
177
|
+
server.serializeAttachment({ connection, caller: stamped });
|
|
178
|
+
try {
|
|
179
|
+
await apply(await deliverConnect({
|
|
180
|
+
kind: "connect",
|
|
181
|
+
connection,
|
|
182
|
+
caller: stamped,
|
|
183
|
+
}));
|
|
184
|
+
}
|
|
185
|
+
catch (cause) {
|
|
186
|
+
// A refused connect leaves no accepted socket behind.
|
|
187
|
+
server.close(closeCodes.refused, "Region connect refused");
|
|
188
|
+
throw cause;
|
|
189
|
+
}
|
|
190
|
+
return native.upgraded(client);
|
|
191
|
+
},
|
|
192
|
+
/** Deliver one bounded text frame from an attested socket. */
|
|
193
|
+
async message(socket, data) {
|
|
194
|
+
// workerd keeps delivering until the peer answers a close; a socket the
|
|
195
|
+
// server already closed never reaches App code again.
|
|
196
|
+
if (socket.readyState !== openState)
|
|
197
|
+
return;
|
|
198
|
+
const stamp = attachment(socket);
|
|
199
|
+
if (stamp === null) {
|
|
200
|
+
socket.close(closeCodes.policy, "Region connection unattested");
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
const window = windowOf(stamp.connection);
|
|
204
|
+
window.messages += 1;
|
|
205
|
+
if (window.messages > appRegionLimits.messagesPerSecond) {
|
|
206
|
+
socket.close(closeCodes.tooManyMessages, "Region message rate exceeded");
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
const frame = regionFrameSchema.safeParse(data);
|
|
210
|
+
if (!frame.success) {
|
|
211
|
+
socket.close(closeCodes.unsupported, "Region frames are bounded text");
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
try {
|
|
215
|
+
await apply(await deliver({
|
|
216
|
+
kind: "message",
|
|
217
|
+
connection: stamp.connection,
|
|
218
|
+
data: frame.data,
|
|
219
|
+
}));
|
|
220
|
+
}
|
|
221
|
+
catch (cause) {
|
|
222
|
+
// A refused event (disabled, revoked, changed) ends only this socket.
|
|
223
|
+
socket.close(closeCodes.refused, "Region event refused");
|
|
224
|
+
if (!(cause instanceof AppInstanceError))
|
|
225
|
+
throw cause;
|
|
226
|
+
}
|
|
227
|
+
},
|
|
228
|
+
/**
|
|
229
|
+
* The browser closed: send the server's half of the close, then tell the
|
|
230
|
+
* App if the socket was attested.
|
|
231
|
+
*/
|
|
232
|
+
async close(socket, code, reason) {
|
|
233
|
+
socket.close(echoCloseCode(code), reason.slice(0, 120));
|
|
234
|
+
const stamp = attachment(socket);
|
|
235
|
+
if (stamp === null)
|
|
236
|
+
return;
|
|
237
|
+
windows.delete(stamp.connection);
|
|
238
|
+
try {
|
|
239
|
+
await apply(await deliver({ kind: "close", connection: stamp.connection }));
|
|
240
|
+
}
|
|
241
|
+
catch (cause) {
|
|
242
|
+
// A fenced Region's sockets close without an App to tell.
|
|
243
|
+
if (!(cause instanceof AppInstanceError))
|
|
244
|
+
throw cause;
|
|
245
|
+
}
|
|
246
|
+
},
|
|
247
|
+
/** Deliver the App's wake when due; the shared alarm may fire for others. */
|
|
248
|
+
async alarm() {
|
|
249
|
+
const at = native.readWake();
|
|
250
|
+
if (at === null)
|
|
251
|
+
return;
|
|
252
|
+
if (at > native.now()) {
|
|
253
|
+
await native.scheduleWake(at);
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
native.writeWake(null);
|
|
257
|
+
await apply(await deliver({ kind: "alarm" }));
|
|
258
|
+
},
|
|
259
|
+
/** Disable or removal: close every socket and drop the App's wake; data stays. */
|
|
260
|
+
fence(reason) {
|
|
261
|
+
native.writeWake(null);
|
|
262
|
+
for (const socket of native.sockets())
|
|
263
|
+
if (socket.readyState === openState)
|
|
264
|
+
socket.close(closeCodes.fenced, reason.slice(0, 120));
|
|
265
|
+
},
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
/** Only sockets this tag marks belong to the Region; others are never touched. */
|
|
269
|
+
const regionSocketTag = "app-region";
|
|
270
|
+
const wakeRowSchema = z.strictObject({ wake_at: z.number().int().nullable() });
|
|
271
|
+
/**
|
|
272
|
+
* Native hibernating sockets and a persisted wake in the supervisor's own
|
|
273
|
+
* SQLite. The supervisor's shared alarm is lowered through `scheduleWake`.
|
|
274
|
+
*/
|
|
275
|
+
export function durableAppRegionNative(ctx, scheduleWake) {
|
|
276
|
+
// Created when the first Region socket is accepted, so an Instance that
|
|
277
|
+
// never served one keeps no Region state and has no Region sockets to close.
|
|
278
|
+
const hasWakeTable = () => ctx.storage.sql
|
|
279
|
+
.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='app_region_wake'")
|
|
280
|
+
.toArray().length > 0;
|
|
281
|
+
const createRegionTable = () => {
|
|
282
|
+
ctx.storage.sql.exec("CREATE TABLE IF NOT EXISTS app_region_wake (id INTEGER PRIMARY KEY CHECK (id = 1), wake_at INTEGER) STRICT");
|
|
283
|
+
};
|
|
284
|
+
return {
|
|
285
|
+
pair: () => {
|
|
286
|
+
const pair = new WebSocketPair();
|
|
287
|
+
return { client: pair[0], server: pair[1] };
|
|
288
|
+
},
|
|
289
|
+
accept: (server) => {
|
|
290
|
+
createRegionTable();
|
|
291
|
+
ctx.acceptWebSocket(server, [regionSocketTag]);
|
|
292
|
+
},
|
|
293
|
+
sockets: () => (hasWakeTable() ? ctx.getWebSockets(regionSocketTag) : []),
|
|
294
|
+
readWake: () => {
|
|
295
|
+
if (!hasWakeTable())
|
|
296
|
+
return null;
|
|
297
|
+
const row = ctx.storage.sql
|
|
298
|
+
.exec("SELECT wake_at FROM app_region_wake WHERE id = 1")
|
|
299
|
+
.toArray()[0];
|
|
300
|
+
return row === undefined ? null : wakeRowSchema.parse(row).wake_at;
|
|
301
|
+
},
|
|
302
|
+
writeWake: (at) => {
|
|
303
|
+
if (at === null && !hasWakeTable())
|
|
304
|
+
return;
|
|
305
|
+
createRegionTable();
|
|
306
|
+
ctx.storage.sql.exec("INSERT INTO app_region_wake (id, wake_at) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET wake_at = excluded.wake_at", at);
|
|
307
|
+
},
|
|
308
|
+
scheduleWake,
|
|
309
|
+
upgraded: (client) => new Response(null, { status: 101, webSocket: client }),
|
|
310
|
+
now: () => Date.now(),
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
/** Whether a hibernated socket a Durable Object woke for is a Region socket. */
|
|
314
|
+
export function isAppRegionSocket(ctx, socket) {
|
|
315
|
+
return ctx.getTags(socket).includes(regionSocketTag);
|
|
316
|
+
}
|
package/dist/authorization.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ import type { TeamRole } from "@fungi.computer/cairn/team-role";
|
|
|
7
7
|
*
|
|
8
8
|
* Who may reach what is decided here once, from one {@link Authority}: the
|
|
9
9
|
* owner reaches everything; a named key reaches exactly its Ear Tag grants
|
|
10
|
-
* (Apps, Agents,
|
|
10
|
+
* (Apps, Agents, Computers); an Agent reaches its App tool policy. An
|
|
11
11
|
* anonymous request reaches only the public routes: sign-in, robots.txt and
|
|
12
12
|
* digest-pinned assets. The App gate
|
|
13
13
|
* (`apps/gate.ts`) still owns App-declaration rules; it asks this module for a
|
|
@@ -34,8 +34,51 @@ import type { TenantPrincipal } from "./tenant.js";
|
|
|
34
34
|
export declare function keyAppAccess(key: LiveOysterKey, installationId: string): AppToolPolicy | null;
|
|
35
35
|
/** Agent access is scoped to the granted Agent ids, never inferred from App grants. */
|
|
36
36
|
export declare function keyAgentAccess(key: LiveOysterKey, agentId: string): boolean;
|
|
37
|
-
/**
|
|
38
|
-
|
|
37
|
+
/**
|
|
38
|
+
* Whether a live key's `computer.use` grant reaches this Computer: every
|
|
39
|
+
* Computer (`all`), or one its selected ids name. Off by default. A host with
|
|
40
|
+
* no Computer id (`null`) is reached only by an `all` grant.
|
|
41
|
+
*/
|
|
42
|
+
export declare function keyComputer(key: LiveOysterKey, computerId: string | null): boolean;
|
|
43
|
+
/**
|
|
44
|
+
* How an App call a key made re-admits the Computer its frame captured. A key
|
|
45
|
+
* with no `computer.use` grant never chose a Computer: its App reaches the
|
|
46
|
+
* owner's Computer through the App's own approved permissions, exactly as
|
|
47
|
+
* before keys could target Computers (`owner-computer`). A key with a
|
|
48
|
+
* `computer.use` grant reaches only a Computer that grant names, still held by
|
|
49
|
+
* the key's owner (`granted`); any other Computer is `refused`.
|
|
50
|
+
*/
|
|
51
|
+
export type KeyFrameComputer = Readonly<{
|
|
52
|
+
kind: "owner-computer";
|
|
53
|
+
}> | Readonly<{
|
|
54
|
+
kind: "granted";
|
|
55
|
+
owner: string;
|
|
56
|
+
}> | Readonly<{
|
|
57
|
+
kind: "refused";
|
|
58
|
+
}>;
|
|
59
|
+
/** Decide {@link KeyFrameComputer} for one live key; a dead key is refused. */
|
|
60
|
+
export declare function keyFrameComputer(key: LiveOysterKey | null, computerId: string): KeyFrameComputer;
|
|
61
|
+
/**
|
|
62
|
+
* Which Computer one key request uses. A key with no `computer.use` grant,
|
|
63
|
+
* or one over all Computers, follows the owner's current selection as it
|
|
64
|
+
* always has, and only the owner names another. A key granted selected
|
|
65
|
+
* Computers uses its own, so the owner switching Computers never moves it:
|
|
66
|
+
* its one Computer, or among several the one `requested` names.
|
|
67
|
+
*/
|
|
68
|
+
export type KeyComputerChoice = Readonly<{
|
|
69
|
+
kind: "owner-selection";
|
|
70
|
+
}> | Readonly<{
|
|
71
|
+
kind: "granted";
|
|
72
|
+
computerId: string;
|
|
73
|
+
/** The key's owner, who must still hold that Computer. */
|
|
74
|
+
owner: string;
|
|
75
|
+
}> | Readonly<{
|
|
76
|
+
kind: "refused";
|
|
77
|
+
status: 400 | 403;
|
|
78
|
+
error: string;
|
|
79
|
+
}>;
|
|
80
|
+
/** Decide {@link KeyComputerChoice} from a key's live grants; a dead key names nothing. */
|
|
81
|
+
export declare function keyComputerChoice(key: LiveOysterKey | null, requested: string | null): KeyComputerChoice;
|
|
39
82
|
/** The owner, as every owner route receives it. */
|
|
40
83
|
export type OwnerPrincipal = Readonly<{
|
|
41
84
|
actor: Extract<HostActor, {
|
|
@@ -57,9 +100,14 @@ export type AuthorityPorts = Readonly<{
|
|
|
57
100
|
appToolPolicy: (actor: Extract<HostActor, {
|
|
58
101
|
kind: "agent";
|
|
59
102
|
}>) => AppToolPolicy | null | Promise<AppToolPolicy | null>;
|
|
103
|
+
/**
|
|
104
|
+
* The Computer this host's requests reach. A host with none omits it, and
|
|
105
|
+
* then only a key granted every Computer passes a Computer requirement.
|
|
106
|
+
*/
|
|
107
|
+
computerId?: string | null;
|
|
60
108
|
}>;
|
|
61
|
-
/** A host's own ports: its key store's liveness
|
|
62
|
-
export declare function hostAuthorityPorts(host: Pick<OysterHost, "keys" | "appToolPolicy">): AuthorityPorts;
|
|
109
|
+
/** A host's own ports: its key store's liveness, its Agents' tool policy and its Computer. */
|
|
110
|
+
export declare function hostAuthorityPorts(host: Pick<OysterHost, "keys" | "appToolPolicy" | "computerId">): AuthorityPorts;
|
|
63
111
|
/**
|
|
64
112
|
* One request's authority, resolved once from its principal. A key carries
|
|
65
113
|
* its live grants, or `null` once it is no longer live, which reaches nothing.
|
|
@@ -86,11 +134,12 @@ export declare function authorityOf(principal: TenantPrincipal, ports: Authority
|
|
|
86
134
|
/** Whether this authority reaches one Agent and its Sessions. Only the owner and granted keys do. */
|
|
87
135
|
export declare function reachesAgent(authority: Authority, agentId: string): boolean;
|
|
88
136
|
/**
|
|
89
|
-
* Whether this authority reaches
|
|
90
|
-
*
|
|
91
|
-
* Agents reach a Computer only through their own
|
|
137
|
+
* Whether this authority reaches one Computer, its workspace files and the
|
|
138
|
+
* media written there. Members do; a key only with `computer.use` naming that
|
|
139
|
+
* Computer or all of them; Agents reach a Computer only through their own
|
|
140
|
+
* attachment owner.
|
|
92
141
|
*/
|
|
93
|
-
export declare function reachesComputer(authority: Authority): boolean;
|
|
142
|
+
export declare function reachesComputer(authority: Authority, computerId: string | null): boolean;
|
|
94
143
|
/**
|
|
95
144
|
* A key's or Agent's tool access to one installation, in the App gate's
|
|
96
145
|
* policy shape; `null` when it reaches none. Members and the owner hold
|