apps 1.0.0-beta.4 → 2.0.0-next.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 +10 -48
- package/check-publish.mjs +7 -0
- package/package.json +27 -56
- package/src/Access.ts +37 -0
- package/src/Accounts.ts +468 -0
- package/src/App.ts +11 -0
- package/src/Ask.ts +156 -0
- package/src/Changes.ts +13 -0
- package/src/Http.ts +30 -0
- package/src/Provider.ts +146 -0
- package/src/Session.ts +52 -0
- package/src/Settings.ts +164 -0
- package/src/contract.ts +852 -0
- package/src/css-modules.d.ts +2 -0
- package/src/desktop/Desktop.ts +192 -0
- package/src/desktop/bridge.ts +62 -0
- package/src/desktop/errors.ts +88 -0
- package/src/desktop/index.ts +15 -0
- package/src/entry.ts +48 -0
- package/src/index.ts +16 -4
- package/src/internal/defects.ts +62 -0
- package/src/internal/files.ts +369 -0
- package/src/internal/host.ts +17 -0
- package/src/internal/query.ts +114 -0
- package/src/internal/records.ts +838 -0
- package/src/internal/retention.ts +87 -0
- package/src/internal/retries.ts +185 -0
- package/src/internal/telemetry.ts +167 -0
- package/src/migrations.ts +110 -0
- package/src/page/Accounts.ts +27 -0
- package/src/page/Changes.ts +126 -0
- package/src/page/Session.ts +46 -0
- package/src/page/client.ts +107 -0
- package/src/page/errors.ts +15 -0
- package/src/page/http.ts +21 -0
- package/src/page/index.ts +18 -0
- package/src/page/paths.ts +22 -0
- package/src/providers/anthropic.ts +26 -0
- package/src/providers/github.ts +49 -0
- package/src/providers/google.ts +67 -0
- package/src/providers/openai.ts +62 -0
- package/src/providers/slack.ts +81 -0
- package/src/runtime.ts +1540 -0
- package/src/testing.ts +660 -0
- package/src/text-modules.d.ts +5 -0
- package/src/theme.css +50 -0
- package/dist/authoring/index.d.ts +0 -422
- package/dist/authoring/index.js +0 -36
- package/dist/chunk-2DVKSPQH.js +0 -312
- package/dist/chunk-4OZFMCTT.js +0 -17
- package/dist/chunk-535V5K64.js +0 -155
- package/dist/chunk-B7NEUIJL.js +0 -14
- package/dist/chunk-DP6UJCMX.js +0 -27
- package/dist/chunk-QA72XJZU.js +0 -41
- package/dist/chunk-S5KFP4JQ.js +0 -20
- package/dist/chunk-XYT6GZ7M.js +0 -99
- package/dist/http/index.d.ts +0 -9
- package/dist/http/index.js +0 -6
- package/dist/index.d.ts +0 -4
- package/dist/index.js +0 -48
- package/dist/manifest/contract.d.ts +0 -63
- package/dist/manifest/contract.js +0 -8
- package/dist/manifest/index.d.ts +0 -20
- package/dist/manifest/index.js +0 -16
- package/dist/mcp/client.d.ts +0 -9
- package/dist/mcp/index.d.ts +0 -11
- package/dist/mcp/index.js +0 -7
- package/dist/openapi/index.d.ts +0 -14
- package/dist/openapi/index.js +0 -7
- package/dist/openapi/mapper.d.ts +0 -7
- package/dist/runner/index.d.ts +0 -4
- package/dist/runner/index.js +0 -66
- package/dist/runner/protocol.d.ts +0 -33
- package/dist/runner/protocol.js +0 -8
- package/dist/runtime/index.d.ts +0 -83
- package/dist/runtime/index.js +0 -12
- package/dist/workerd/index.d.ts +0 -7
- package/dist/workerd/index.js +0 -10
- package/src/authoring/index.ts +0 -686
- package/src/http/index.ts +0 -26
- package/src/manifest/contract.ts +0 -64
- package/src/manifest/index.ts +0 -156
- package/src/mcp/client.ts +0 -59
- package/src/mcp/index.ts +0 -42
- package/src/openapi/index.ts +0 -70
- package/src/openapi/mapper.ts +0 -25
- package/src/runner/index.ts +0 -80
- package/src/runner/protocol.ts +0 -54
- package/src/runtime/index.ts +0 -554
- package/src/workerd/index.ts +0 -17
package/src/testing.ts
ADDED
|
@@ -0,0 +1,660 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `apps/testing`: run an app's code on a laptop, with no Executor.
|
|
3
|
+
*
|
|
4
|
+
* The app's Layer is built on the same Effect services the runtime gives it on
|
|
5
|
+
* Executor: `SqlClient` over a SQLite file (or memory), Effect's own
|
|
6
|
+
* single-process cluster and workflow engine over that database,
|
|
7
|
+
* `KeyValueStore` in a table, `HttpRouter`, `FileSystem` in memory, `Config`
|
|
8
|
+
* from the settings a test gives, and stand-ins for linked accounts. Time is
|
|
9
|
+
* Effect's `TestClock`: `advance` moves it and runs whatever came due, so a
|
|
10
|
+
* workflow that sleeps a day is tested in a second. Running the real engine is
|
|
11
|
+
* the point: it is what catches replay mistakes, such as reading the clock
|
|
12
|
+
* outside an activity.
|
|
13
|
+
*
|
|
14
|
+
* ```ts
|
|
15
|
+
* import { it, expect } from "@effect/vitest"
|
|
16
|
+
* import * as Testing from "apps/testing"
|
|
17
|
+
* import app from "../index.ts"
|
|
18
|
+
*
|
|
19
|
+
* it.effect("a note is added", () =>
|
|
20
|
+
* Effect.gen(function*() {
|
|
21
|
+
* const notes = yield* Testing.make(app, { migrations: new URL("../migrations", import.meta.url) })
|
|
22
|
+
* const added = yield* notes.callTool("add_note", { text: "hi" }, { as: "u1" })
|
|
23
|
+
* expect(added.structured).toMatchObject({ text: "hi" })
|
|
24
|
+
* }).pipe(Effect.scoped))
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
import {
|
|
28
|
+
Cause,
|
|
29
|
+
Clock,
|
|
30
|
+
ConfigProvider,
|
|
31
|
+
Context,
|
|
32
|
+
Duration,
|
|
33
|
+
Effect,
|
|
34
|
+
Exit,
|
|
35
|
+
Inspectable,
|
|
36
|
+
Layer,
|
|
37
|
+
Logger,
|
|
38
|
+
Scope,
|
|
39
|
+
} from "effect";
|
|
40
|
+
import { ClusterWorkflowEngine, Sharding, SingleRunner } from "effect/cluster";
|
|
41
|
+
import * as Digest from "effect/crypto/Digest";
|
|
42
|
+
import { FetchHttpClient, HttpClient, HttpEffect, HttpRouter } from "effect/http";
|
|
43
|
+
import { KeyValueStore } from "effect/persistence";
|
|
44
|
+
import { Migrator, SqlClient } from "effect/sql";
|
|
45
|
+
import { TestClock } from "effect/testing";
|
|
46
|
+
import { DurableClock } from "effect/workflow";
|
|
47
|
+
import { readdirSync, readFileSync } from "node:fs";
|
|
48
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
49
|
+
import path from "node:path";
|
|
50
|
+
import {
|
|
51
|
+
type AccountCredential,
|
|
52
|
+
type AccountOwnerEntry,
|
|
53
|
+
type AccountRef,
|
|
54
|
+
type CallerIdentity,
|
|
55
|
+
type FileInfo,
|
|
56
|
+
type HostCapabilities,
|
|
57
|
+
type HostFiles,
|
|
58
|
+
IDENTITY_HEADER,
|
|
59
|
+
type Result,
|
|
60
|
+
} from "./contract.ts";
|
|
61
|
+
import * as Access from "./Access.ts";
|
|
62
|
+
import { isPublic } from "./Access.ts";
|
|
63
|
+
import * as Accounts from "./Accounts.ts";
|
|
64
|
+
import * as Settings from "./Settings.ts";
|
|
65
|
+
import * as Files from "./internal/files.ts";
|
|
66
|
+
import { Host } from "./internal/host.ts";
|
|
67
|
+
import { migrationKey, sqlMigrationByStatement } from "./migrations.ts";
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* `@effect/sql-sqlite-node` is an optional peer of `apps`: a deploy never installs it, and an
|
|
71
|
+
* author's tests do. Loaded here, so `apps` itself does not need it.
|
|
72
|
+
*/
|
|
73
|
+
const sqliteNode = Effect.tryPromise({
|
|
74
|
+
try: () => import("@effect/sql-sqlite-node/SqliteClient"),
|
|
75
|
+
catch: () =>
|
|
76
|
+
new Error(
|
|
77
|
+
'apps/testing runs the app on SQLite through "@effect/sql-sqlite-node". Add it to your test dependencies: bun add -d @effect/sql-sqlite-node@4.1.6',
|
|
78
|
+
),
|
|
79
|
+
}).pipe(Effect.orDie);
|
|
80
|
+
|
|
81
|
+
export interface Options {
|
|
82
|
+
/** The app's `migrations/` folder. */
|
|
83
|
+
readonly migrations?: URL | string | undefined;
|
|
84
|
+
/** Settings and secrets, as `Config` reads them. */
|
|
85
|
+
readonly settings?: Readonly<Record<string, string>> | undefined;
|
|
86
|
+
/**
|
|
87
|
+
* Linked accounts: `"<account>"` for an `app` account, `"<account>:<userId>"` for a member's
|
|
88
|
+
* (split at the first colon). Each value is the token, or the credential with its fields,
|
|
89
|
+
* expiry, scopes and the account's label. Anything else is not linked. A token the app reports
|
|
90
|
+
* as rejected is not renewed: the next request for it says the account needs reconnecting.
|
|
91
|
+
*/
|
|
92
|
+
readonly tokens?: Readonly<Record<string, string | TestCredential>> | undefined;
|
|
93
|
+
/**
|
|
94
|
+
* The HTTP client the app gets, in place of `fetch`: its own requests and every linked
|
|
95
|
+
* account's `http` go through it, so a test can answer as the service would. Default: `fetch`.
|
|
96
|
+
*/
|
|
97
|
+
readonly http?: HttpClient.HttpClient | undefined;
|
|
98
|
+
/**
|
|
99
|
+
* Which of the app's log lines are also printed, with their cause: `"errors"` (the default)
|
|
100
|
+
* prints what it logs at `Error` and above, `"all"` everything, `"none"` nothing. Every line is
|
|
101
|
+
* kept for `logs` either way.
|
|
102
|
+
*/
|
|
103
|
+
readonly print?: "errors" | "all" | "none" | undefined;
|
|
104
|
+
/**
|
|
105
|
+
* Where the test clock starts, in epoch milliseconds or as a `Date`. Default: the real time
|
|
106
|
+
* when the test starts, so what the app writes sorts after data seeded from today.
|
|
107
|
+
*/
|
|
108
|
+
readonly now?: number | Date | undefined;
|
|
109
|
+
/** A SQLite file, to keep the data between runs. Default: in memory. */
|
|
110
|
+
readonly database?: string | undefined;
|
|
111
|
+
readonly appUrl?: string | undefined;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export interface TestCredential {
|
|
115
|
+
readonly token: string;
|
|
116
|
+
readonly fields?: Readonly<Record<string, string>> | undefined;
|
|
117
|
+
readonly expiresAt?: number | null | undefined;
|
|
118
|
+
readonly scopes?: ReadonlyArray<string> | undefined;
|
|
119
|
+
readonly label?: string | undefined;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export interface ToolCall {
|
|
123
|
+
readonly resultType: string;
|
|
124
|
+
readonly isError: boolean;
|
|
125
|
+
/** The tool's result, decoded from `structuredContent`. */
|
|
126
|
+
readonly structured: unknown;
|
|
127
|
+
/** The first text block. */
|
|
128
|
+
readonly text: string | undefined;
|
|
129
|
+
/** For `input_required`: each question, by key. */
|
|
130
|
+
readonly questions: Readonly<Record<string, { readonly message: string }>>;
|
|
131
|
+
/** For `input_required`: hand back with the answers. */
|
|
132
|
+
readonly requestState: string | undefined;
|
|
133
|
+
/**
|
|
134
|
+
* What the app logged as an error while the call ran, each with its cause in full: a tool that
|
|
135
|
+
* died answers the agent only "internal server error", and its defect is here.
|
|
136
|
+
*/
|
|
137
|
+
readonly errors: ReadonlyArray<string>;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** One line the app logged. */
|
|
141
|
+
export interface LogLine {
|
|
142
|
+
readonly time: number;
|
|
143
|
+
readonly level: string;
|
|
144
|
+
readonly message: string;
|
|
145
|
+
/** The cause, rendered with `Cause.pretty`, when the line carries one. */
|
|
146
|
+
readonly cause: string | undefined;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export interface CallOptions {
|
|
150
|
+
/**
|
|
151
|
+
* The member making the call (their user id). Default: nobody signed in, who reaches only the
|
|
152
|
+
* paths the app declares public (`Access.declare`), as on Executor; anything else answers 401.
|
|
153
|
+
*/
|
|
154
|
+
readonly as?: string | undefined;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export interface TestApp {
|
|
158
|
+
/** An HTTP request to the app, as `as`. */
|
|
159
|
+
readonly fetch: (
|
|
160
|
+
input: string | Request,
|
|
161
|
+
options?: CallOptions & { readonly init?: RequestInit | undefined },
|
|
162
|
+
) => Effect.Effect<Response>;
|
|
163
|
+
/** Call one of the app's tools over its MCP server. Answers questions with `answers`. */
|
|
164
|
+
readonly callTool: (
|
|
165
|
+
name: string,
|
|
166
|
+
args: unknown,
|
|
167
|
+
options?: CallOptions & {
|
|
168
|
+
readonly answers?: Readonly<Record<string, unknown>> | undefined;
|
|
169
|
+
readonly requestState?: string | undefined;
|
|
170
|
+
},
|
|
171
|
+
) => Effect.Effect<ToolCall>;
|
|
172
|
+
/** Move the clock forward and run everything that came due, until the app is quiet. */
|
|
173
|
+
readonly advance: (duration: Duration.Input) => Effect.Effect<void>;
|
|
174
|
+
/** Run everything due now, until the app is quiet. */
|
|
175
|
+
readonly settle: Effect.Effect<void>;
|
|
176
|
+
/** The app's database. */
|
|
177
|
+
readonly sql: SqlClient.SqlClient;
|
|
178
|
+
/** Everything the app has logged so far, oldest first. */
|
|
179
|
+
readonly logs: Effect.Effect<ReadonlyArray<LogLine>>;
|
|
180
|
+
/**
|
|
181
|
+
* Fire the app's account hooks as Executor does. `link` reads the account's profile (through
|
|
182
|
+
* `http`) and runs `onLink` with the external id it found. `unlink` runs `onUnlink` while the
|
|
183
|
+
* token still works, then ends the link: the account answers `NotLinked` after it. `account` is
|
|
184
|
+
* `"<account>"` for an `app` account or `"<account>:<userId>"` for a member's, and must be in
|
|
185
|
+
* `tokens`; the hook sees its `label` there (default "Default"). A hook has 30 seconds, as on
|
|
186
|
+
* Executor. Fails as the hook failed.
|
|
187
|
+
*/
|
|
188
|
+
readonly link: (account: string, options?: HookOptions) => Effect.Effect<void, unknown>;
|
|
189
|
+
readonly unlink: (account: string, options?: HookOptions) => Effect.Effect<void, unknown>;
|
|
190
|
+
/** As after a deploy: `onLink` with `cause: "deploy"` for every linked account. */
|
|
191
|
+
readonly redeploy: Effect.Effect<void, unknown>;
|
|
192
|
+
/** As when a member leaves: every account they linked is unlinked, hook first. */
|
|
193
|
+
readonly leave: (userId: string) => Effect.Effect<void, unknown>;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export interface HookOptions {
|
|
197
|
+
/** Why the hook fires. Default: `link` for `link`, `unlink` for `unlink`. */
|
|
198
|
+
readonly cause?: "link" | "deploy" | "unlink" | "removed" | undefined;
|
|
199
|
+
/** The account's id at the provider, as its profile would say. Default: none. */
|
|
200
|
+
readonly externalId?: string | undefined;
|
|
201
|
+
/** The delivery's id; repeat one to stand for a retried delivery. Default: a fresh one. */
|
|
202
|
+
readonly id?: string | undefined;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const ok = <A>(value: A): Result<A> => ({ ok: true, value });
|
|
206
|
+
const fail = (reason: string, message: string): Result<never> => ({
|
|
207
|
+
ok: false,
|
|
208
|
+
error: { reason, message },
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* The test's files, in memory. Each file is kept as the chunks it was written in, joined only
|
|
213
|
+
* when it is read whole, so appending and streaming stay linear in the file's size.
|
|
214
|
+
*/
|
|
215
|
+
const memoryFiles = (): HostFiles => {
|
|
216
|
+
const files = new Map<string, { chunks: Array<Uint8Array>; size: number }>();
|
|
217
|
+
const directories = new Set<string>(["/"]);
|
|
218
|
+
const parent = (file: string) => file.slice(0, file.lastIndexOf("/")) || "/";
|
|
219
|
+
const info = (file: string): Result<FileInfo> =>
|
|
220
|
+
directories.has(file)
|
|
221
|
+
? ok({ type: "Directory", size: 0, mtime: null })
|
|
222
|
+
: files.has(file)
|
|
223
|
+
? ok({ type: "File", size: files.get(file)!.size, mtime: null })
|
|
224
|
+
: fail("NotFound", file);
|
|
225
|
+
const whole = (file: string): Uint8Array => {
|
|
226
|
+
const entry = files.get(file)!;
|
|
227
|
+
if (entry.chunks.length === 1) return entry.chunks[0]!;
|
|
228
|
+
const joined = new Uint8Array(entry.size);
|
|
229
|
+
let at = 0;
|
|
230
|
+
for (const chunk of entry.chunks) {
|
|
231
|
+
joined.set(chunk, at);
|
|
232
|
+
at += chunk.length;
|
|
233
|
+
}
|
|
234
|
+
entry.chunks = [joined];
|
|
235
|
+
return joined;
|
|
236
|
+
};
|
|
237
|
+
return {
|
|
238
|
+
read: async (file) => (files.has(file) ? ok(whole(file).slice()) : fail("NotFound", file)),
|
|
239
|
+
stream: async (file, options) => {
|
|
240
|
+
const entry = files.get(file);
|
|
241
|
+
if (entry === undefined) return fail("NotFound", file);
|
|
242
|
+
const start = options?.offset ?? 0;
|
|
243
|
+
const end = Math.min(
|
|
244
|
+
entry.size,
|
|
245
|
+
options?.length === undefined ? entry.size : start + options.length,
|
|
246
|
+
);
|
|
247
|
+
const pieces: Array<Uint8Array> = [];
|
|
248
|
+
let at = 0;
|
|
249
|
+
for (const chunk of entry.chunks) {
|
|
250
|
+
const from = Math.max(start - at, 0);
|
|
251
|
+
const to = Math.min(end - at, chunk.length);
|
|
252
|
+
if (to > from) pieces.push(chunk.slice(from, to));
|
|
253
|
+
at += chunk.length;
|
|
254
|
+
}
|
|
255
|
+
return ok(
|
|
256
|
+
new ReadableStream<Uint8Array>({
|
|
257
|
+
pull: (controller) => {
|
|
258
|
+
const next = pieces.shift();
|
|
259
|
+
if (next === undefined) controller.close();
|
|
260
|
+
else controller.enqueue(next);
|
|
261
|
+
},
|
|
262
|
+
}),
|
|
263
|
+
);
|
|
264
|
+
},
|
|
265
|
+
write: async (file, data, options) => {
|
|
266
|
+
if (!directories.has(parent(file))) return fail("NotFound", parent(file));
|
|
267
|
+
if (options?.exclusive === true && files.has(file)) return fail("AlreadyExists", file);
|
|
268
|
+
const entry =
|
|
269
|
+
options?.append === true && files.has(file)
|
|
270
|
+
? files.get(file)!
|
|
271
|
+
: { chunks: new Array<Uint8Array>(), size: 0 };
|
|
272
|
+
const add = (chunk: Uint8Array) => {
|
|
273
|
+
entry.chunks.push(chunk.slice());
|
|
274
|
+
entry.size += chunk.length;
|
|
275
|
+
};
|
|
276
|
+
if (data instanceof Uint8Array) add(data);
|
|
277
|
+
else {
|
|
278
|
+
const reader = data.getReader();
|
|
279
|
+
for (;;) {
|
|
280
|
+
const { done, value } = await reader.read();
|
|
281
|
+
if (done) break;
|
|
282
|
+
add(value);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
files.set(file, entry);
|
|
286
|
+
return ok(null);
|
|
287
|
+
},
|
|
288
|
+
stat: async (file) => info(file),
|
|
289
|
+
list: async (dir) => {
|
|
290
|
+
if (!directories.has(dir)) return fail("NotFound", dir);
|
|
291
|
+
const prefix = dir === "/" ? "/" : `${dir}/`;
|
|
292
|
+
const names = new Set<string>();
|
|
293
|
+
for (const key of [...files.keys(), ...directories]) {
|
|
294
|
+
if (key !== dir && key.startsWith(prefix))
|
|
295
|
+
names.add(key.slice(prefix.length).split("/")[0]!);
|
|
296
|
+
}
|
|
297
|
+
return ok([...names].sort());
|
|
298
|
+
},
|
|
299
|
+
makeDirectory: async (dir) => {
|
|
300
|
+
let current = "";
|
|
301
|
+
for (const part of dir.split("/").filter(Boolean)) {
|
|
302
|
+
current += `/${part}`;
|
|
303
|
+
directories.add(current);
|
|
304
|
+
}
|
|
305
|
+
return ok(null);
|
|
306
|
+
},
|
|
307
|
+
copy: async (from, to) => {
|
|
308
|
+
if (!files.has(from)) return fail("NotFound", from);
|
|
309
|
+
const source = files.get(from)!;
|
|
310
|
+
files.set(to, { chunks: [...source.chunks], size: source.size });
|
|
311
|
+
return ok(null);
|
|
312
|
+
},
|
|
313
|
+
rename: async (from, to) => {
|
|
314
|
+
if (!files.has(from)) return fail("NotFound", from);
|
|
315
|
+
files.set(to, files.get(from)!);
|
|
316
|
+
files.delete(from);
|
|
317
|
+
return ok(null);
|
|
318
|
+
},
|
|
319
|
+
remove: async (file) =>
|
|
320
|
+
files.delete(file) || directories.delete(file) ? ok(null) : fail("NotFound", file),
|
|
321
|
+
};
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
const capabilities = (
|
|
325
|
+
options: Options,
|
|
326
|
+
tokens: Map<string, string | TestCredential>,
|
|
327
|
+
): HostCapabilities => {
|
|
328
|
+
const rejected = new Set<string>();
|
|
329
|
+
const key = (account: AccountRef) =>
|
|
330
|
+
account.owner.kind === "app" ? account.name : `${account.name}:${account.owner.userId}`;
|
|
331
|
+
const credential = (entry: string): TestCredential | undefined => {
|
|
332
|
+
const value = tokens.get(entry);
|
|
333
|
+
return typeof value === "string" ? { token: value } : value;
|
|
334
|
+
};
|
|
335
|
+
return {
|
|
336
|
+
accounts: {
|
|
337
|
+
token: async (account): Promise<Result<AccountCredential>> => {
|
|
338
|
+
const found = credential(key(account));
|
|
339
|
+
if (found === undefined) return fail("NotLinked", `${key(account)} is not linked`);
|
|
340
|
+
if (rejected.has(key(account)))
|
|
341
|
+
return fail("NeedsReconnection", `${key(account)} needs to be reconnected`);
|
|
342
|
+
return ok({
|
|
343
|
+
token: found.token,
|
|
344
|
+
fields: found.fields ?? {},
|
|
345
|
+
expiresAt: found.expiresAt ?? null,
|
|
346
|
+
scopes: found.scopes ?? [],
|
|
347
|
+
});
|
|
348
|
+
},
|
|
349
|
+
owners: async (name): Promise<Result<ReadonlyArray<AccountOwnerEntry>>> =>
|
|
350
|
+
ok(
|
|
351
|
+
[...tokens.keys()].flatMap((entry): ReadonlyArray<AccountOwnerEntry> => {
|
|
352
|
+
const separator = entry.indexOf(":");
|
|
353
|
+
const account = separator === -1 ? entry : entry.slice(0, separator);
|
|
354
|
+
if (account !== name) return [];
|
|
355
|
+
const label = credential(entry)?.label;
|
|
356
|
+
return [
|
|
357
|
+
separator === -1
|
|
358
|
+
? { owner: { kind: "app" }, label: label ?? "Default" }
|
|
359
|
+
: {
|
|
360
|
+
owner: { kind: "user", userId: entry.slice(separator + 1) },
|
|
361
|
+
label: label ?? entry.slice(separator + 1),
|
|
362
|
+
},
|
|
363
|
+
];
|
|
364
|
+
}),
|
|
365
|
+
),
|
|
366
|
+
rejected: async (account) => {
|
|
367
|
+
rejected.add(key(account));
|
|
368
|
+
return ok({ renewed: false });
|
|
369
|
+
},
|
|
370
|
+
},
|
|
371
|
+
settings: {
|
|
372
|
+
read: async () => ok({ values: { ...options.settings }, version: "test", url: null }),
|
|
373
|
+
},
|
|
374
|
+
files: memoryFiles(),
|
|
375
|
+
clock: { setWake: async () => {} },
|
|
376
|
+
telemetry: { export: async () => {} },
|
|
377
|
+
};
|
|
378
|
+
};
|
|
379
|
+
|
|
380
|
+
const loadMigrations = (folder: URL | string | undefined) =>
|
|
381
|
+
Effect.promise(async () => {
|
|
382
|
+
const record: Record<string, Effect.Effect<void, unknown, SqlClient.SqlClient>> = {};
|
|
383
|
+
if (folder === undefined) return record;
|
|
384
|
+
const dir = folder instanceof URL ? fileURLToPath(folder) : folder;
|
|
385
|
+
for (const file of readdirSync(dir).sort()) {
|
|
386
|
+
const name = migrationKey(file);
|
|
387
|
+
if (name === undefined) continue;
|
|
388
|
+
const full = path.join(dir, file);
|
|
389
|
+
record[name] = file.endsWith(".sql")
|
|
390
|
+
? sqlMigrationByStatement(readFileSync(full, "utf8"))
|
|
391
|
+
: (
|
|
392
|
+
(await import(pathToFileURL(full).href)) as {
|
|
393
|
+
default: Effect.Effect<void, unknown, SqlClient.SqlClient>;
|
|
394
|
+
}
|
|
395
|
+
).default;
|
|
396
|
+
}
|
|
397
|
+
return record;
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
const mcpBody = (method: string, params: Record<string, unknown>) =>
|
|
401
|
+
JSON.stringify({
|
|
402
|
+
jsonrpc: "2.0",
|
|
403
|
+
id: 1,
|
|
404
|
+
method,
|
|
405
|
+
params: {
|
|
406
|
+
...params,
|
|
407
|
+
_meta: {
|
|
408
|
+
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
|
|
409
|
+
"io.modelcontextprotocol/clientCapabilities": { elicitation: { form: {} } },
|
|
410
|
+
"io.modelcontextprotocol/clientInfo": { name: "apps/testing", version: "1" },
|
|
411
|
+
},
|
|
412
|
+
},
|
|
413
|
+
});
|
|
414
|
+
|
|
415
|
+
interface McpToolResult {
|
|
416
|
+
readonly resultType?: string;
|
|
417
|
+
readonly isError?: boolean;
|
|
418
|
+
readonly structuredContent?: unknown;
|
|
419
|
+
readonly content?: ReadonlyArray<{ readonly type: string; readonly text?: string }>;
|
|
420
|
+
readonly inputRequests?: Readonly<
|
|
421
|
+
Record<string, { readonly params?: { readonly message?: string } }>
|
|
422
|
+
>;
|
|
423
|
+
readonly requestState?: string;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/** Build the app for a test. Its resources close with the surrounding scope. */
|
|
427
|
+
export const make = (
|
|
428
|
+
app: Layer.Layer<never, unknown, unknown>,
|
|
429
|
+
options: Options = {},
|
|
430
|
+
): Effect.Effect<TestApp, never, Scope.Scope> =>
|
|
431
|
+
Effect.gen(function* () {
|
|
432
|
+
const scope = yield* Effect.scope;
|
|
433
|
+
const startAt = options.now ?? Date.now();
|
|
434
|
+
yield* TestClock.setTime(startAt instanceof Date ? startAt.getTime() : startAt);
|
|
435
|
+
const clock = yield* Clock.Clock;
|
|
436
|
+
const testClockForEveryFiber = Layer.succeed(Clock.Clock, clock);
|
|
437
|
+
const SqliteNode = yield* sqliteNode;
|
|
438
|
+
const sqlContext = yield* Layer.buildWithScope(
|
|
439
|
+
SqliteNode.layer({ filename: options.database ?? ":memory:" }),
|
|
440
|
+
scope,
|
|
441
|
+
).pipe(Effect.orDie);
|
|
442
|
+
const sqlLayer = Layer.succeedContext(sqlContext);
|
|
443
|
+
const migrations = yield* loadMigrations(options.migrations);
|
|
444
|
+
const lines: Array<LogLine> = [];
|
|
445
|
+
const print = options.print ?? "errors";
|
|
446
|
+
const capture = Logger.make((log) => {
|
|
447
|
+
const message = (Array.isArray(log.message) ? log.message : [log.message])
|
|
448
|
+
.map((part) => (typeof part === "string" ? part : Inspectable.toStringUnknown(part)))
|
|
449
|
+
.join(" ");
|
|
450
|
+
const cause = log.cause.reasons.length === 0 ? undefined : Cause.pretty(log.cause);
|
|
451
|
+
const line: LogLine = { time: log.date.getTime(), level: log.logLevel, message, cause };
|
|
452
|
+
lines.push(line);
|
|
453
|
+
const severe = log.logLevel === "Error" || log.logLevel === "Fatal";
|
|
454
|
+
if (print === "all" || (print === "errors" && severe)) {
|
|
455
|
+
console.error(`[app ${line.level}] ${message}${cause === undefined ? "" : `\n${cause}`}`);
|
|
456
|
+
}
|
|
457
|
+
});
|
|
458
|
+
yield* Migrator.make({})({
|
|
459
|
+
loader: Migrator.fromRecord(migrations),
|
|
460
|
+
table: "apps_migrations",
|
|
461
|
+
}).pipe(Effect.provide(sqlLayer), Effect.orDie);
|
|
462
|
+
|
|
463
|
+
const linked = new Map(Object.entries(options.tokens ?? {}));
|
|
464
|
+
const host = capabilities(options, linked);
|
|
465
|
+
const cluster = SingleRunner.layer({
|
|
466
|
+
shardingConfig: { shardsPerGroup: 1, entityMessagePollInterval: Duration.minutes(10) },
|
|
467
|
+
}).pipe(
|
|
468
|
+
Layer.provide([sqlLayer, Digest.layerWebCrypto, testClockForEveryFiber]),
|
|
469
|
+
Layer.provide(ConfigProvider.layer(ConfigProvider.fromEnvRecord({}))),
|
|
470
|
+
);
|
|
471
|
+
const platform = Layer.mergeAll(
|
|
472
|
+
ClusterWorkflowEngine.layer.pipe(Layer.provideMerge(cluster)),
|
|
473
|
+
sqlLayer,
|
|
474
|
+
HttpRouter.layer,
|
|
475
|
+
options.http === undefined
|
|
476
|
+
? FetchHttpClient.layer
|
|
477
|
+
: Layer.succeed(HttpClient.HttpClient, options.http),
|
|
478
|
+
KeyValueStore.layerSql({ table: "apps_key_value" }).pipe(Layer.provide(sqlLayer)),
|
|
479
|
+
Files.layer(host.files),
|
|
480
|
+
Layer.succeed(Host, {
|
|
481
|
+
capabilities: host,
|
|
482
|
+
appId: "test",
|
|
483
|
+
appUrl: options.appUrl ?? "http://app.test",
|
|
484
|
+
}),
|
|
485
|
+
ConfigProvider.layer(Settings.configProvider({ ...options.settings }, null)),
|
|
486
|
+
Layer.succeed(DurableClock.InMemoryThreshold, Duration.zero),
|
|
487
|
+
Logger.layer([capture]),
|
|
488
|
+
testClockForEveryFiber,
|
|
489
|
+
);
|
|
490
|
+
const context = (yield* Layer.buildWithScope(
|
|
491
|
+
app.pipe(Layer.provideMerge(platform)) as Layer.Layer<unknown, unknown, never>,
|
|
492
|
+
scope,
|
|
493
|
+
).pipe(Effect.orDie)) as Context.Context<
|
|
494
|
+
HttpRouter.HttpRouter | SqlClient.SqlClient | Sharding.Sharding | HttpClient.HttpClient
|
|
495
|
+
>;
|
|
496
|
+
const handler = HttpEffect.toWebHandlerWith(context)(
|
|
497
|
+
Context.get(context, HttpRouter.HttpRouter).asHttpEffect() as never,
|
|
498
|
+
) as (request: Request) => Promise<Response>;
|
|
499
|
+
const sql = Context.get(context, SqlClient.SqlClient);
|
|
500
|
+
const sharding = Context.get(context, Sharding.Sharding);
|
|
501
|
+
|
|
502
|
+
const withCaller = (request: Request, as: string | undefined) => {
|
|
503
|
+
const headers = new Headers(request.headers);
|
|
504
|
+
headers.delete(IDENTITY_HEADER);
|
|
505
|
+
if (as !== undefined) {
|
|
506
|
+
const identity: CallerIdentity = { user: { id: as }, organization: { id: "local" } };
|
|
507
|
+
headers.set(IDENTITY_HEADER, JSON.stringify(identity));
|
|
508
|
+
}
|
|
509
|
+
return new Request(request, { headers });
|
|
510
|
+
};
|
|
511
|
+
const fetch: TestApp["fetch"] = (input, callOptions) => {
|
|
512
|
+
const request =
|
|
513
|
+
typeof input === "string"
|
|
514
|
+
? new Request(new URL(input, "http://app.test"), callOptions?.init)
|
|
515
|
+
: input;
|
|
516
|
+
if (
|
|
517
|
+
callOptions?.as === undefined &&
|
|
518
|
+
!isPublic(Access.declarations.public, new URL(request.url).pathname)
|
|
519
|
+
)
|
|
520
|
+
return Effect.succeed(new Response("Sign in to reach this app", { status: 401 }));
|
|
521
|
+
return Effect.promise(() => handler(withCaller(request, callOptions?.as)));
|
|
522
|
+
};
|
|
523
|
+
|
|
524
|
+
const realPause = Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, 5)));
|
|
525
|
+
const quiet = Effect.suspend(
|
|
526
|
+
() =>
|
|
527
|
+
sql<{
|
|
528
|
+
n: number;
|
|
529
|
+
}>`SELECT count(*) AS n FROM cluster_messages WHERE processed = 0 AND (deliver_at IS NULL OR deliver_at <= ${clock.currentTimeMillisUnsafe()})`,
|
|
530
|
+
).pipe(Effect.map((rows) => rows[0]!.n === 0));
|
|
531
|
+
const settle = Effect.gen(function* () {
|
|
532
|
+
let quietRounds = 0;
|
|
533
|
+
for (let round = 0; round < 400 && quietRounds < 3; round++) {
|
|
534
|
+
yield* sharding.pollStorage;
|
|
535
|
+
yield* realPause;
|
|
536
|
+
quietRounds = (yield* quiet) ? quietRounds + 1 : 0;
|
|
537
|
+
}
|
|
538
|
+
}).pipe(Effect.orDie);
|
|
539
|
+
|
|
540
|
+
const refOf = (account: string): AccountRef => {
|
|
541
|
+
const separator = account.indexOf(":");
|
|
542
|
+
return separator === -1
|
|
543
|
+
? { name: account, owner: { kind: "app" } }
|
|
544
|
+
: {
|
|
545
|
+
name: account.slice(0, separator),
|
|
546
|
+
owner: { kind: "user", userId: account.slice(separator + 1) },
|
|
547
|
+
};
|
|
548
|
+
};
|
|
549
|
+
const hook = (kind: "linked" | "unlinking", account: string, hookOptions?: HookOptions) =>
|
|
550
|
+
Effect.gen(function* () {
|
|
551
|
+
const entry = linked.get(account);
|
|
552
|
+
if (entry === undefined)
|
|
553
|
+
return yield* Effect.die(
|
|
554
|
+
new Error(
|
|
555
|
+
`${account} is not linked: a hook fires only for a linked account, so add it to tokens`,
|
|
556
|
+
),
|
|
557
|
+
);
|
|
558
|
+
const ref = refOf(account);
|
|
559
|
+
const label = (typeof entry === "string" ? undefined : entry.label) ?? "Default";
|
|
560
|
+
let externalId = hookOptions?.externalId ?? null;
|
|
561
|
+
if (kind === "linked" && hookOptions?.externalId === undefined) {
|
|
562
|
+
const profile = yield* Accounts.readProfile(ref);
|
|
563
|
+
if (profile.status === "ok") externalId = profile.info["externalId"] ?? null;
|
|
564
|
+
}
|
|
565
|
+
yield* Accounts.runHooks(
|
|
566
|
+
{
|
|
567
|
+
id: hookOptions?.id ?? crypto.randomUUID(),
|
|
568
|
+
kind,
|
|
569
|
+
cause: hookOptions?.cause ?? (kind === "linked" ? "link" : "unlink"),
|
|
570
|
+
account: { ...ref, label, externalId },
|
|
571
|
+
},
|
|
572
|
+
externalId,
|
|
573
|
+
).pipe(Effect.timeout(Duration.seconds(30)));
|
|
574
|
+
}).pipe(
|
|
575
|
+
Effect.ensuring(Effect.sync(() => kind === "unlinking" && linked.delete(account))),
|
|
576
|
+
Effect.provide(context),
|
|
577
|
+
);
|
|
578
|
+
const every = (
|
|
579
|
+
accounts: ReadonlyArray<string>,
|
|
580
|
+
run: (account: string) => Effect.Effect<void, unknown>,
|
|
581
|
+
) =>
|
|
582
|
+
Effect.flatMap(
|
|
583
|
+
Effect.forEach(accounts, (account) => Effect.exit(run(account))),
|
|
584
|
+
(exits) => {
|
|
585
|
+
const failed = exits.find(Exit.isFailure);
|
|
586
|
+
return failed === undefined ? Effect.void : Effect.failCause(failed.cause);
|
|
587
|
+
},
|
|
588
|
+
);
|
|
589
|
+
|
|
590
|
+
return {
|
|
591
|
+
fetch,
|
|
592
|
+
callTool: (name, args, callOptions) =>
|
|
593
|
+
Effect.gen(function* () {
|
|
594
|
+
const before = lines.length;
|
|
595
|
+
const params: Record<string, unknown> = { name, arguments: args };
|
|
596
|
+
if (callOptions?.answers !== undefined) params["inputResponses"] = callOptions.answers;
|
|
597
|
+
if (callOptions?.requestState !== undefined)
|
|
598
|
+
params["requestState"] = callOptions.requestState;
|
|
599
|
+
const response = yield* fetch(
|
|
600
|
+
new Request("http://app.test/mcp", {
|
|
601
|
+
method: "POST",
|
|
602
|
+
headers: {
|
|
603
|
+
"content-type": "application/json",
|
|
604
|
+
accept: "application/json, text/event-stream",
|
|
605
|
+
"mcp-protocol-version": "2026-07-28",
|
|
606
|
+
"mcp-method": "tools/call",
|
|
607
|
+
"mcp-name": name,
|
|
608
|
+
},
|
|
609
|
+
body: mcpBody("tools/call", params),
|
|
610
|
+
}),
|
|
611
|
+
{ as: callOptions?.as },
|
|
612
|
+
);
|
|
613
|
+
if (response.status === 401)
|
|
614
|
+
return yield* Effect.die(
|
|
615
|
+
new Error(
|
|
616
|
+
`${name}: nobody is signed in, and Executor refuses a tool call with no caller. Pass { as: "<user id>" }.`,
|
|
617
|
+
),
|
|
618
|
+
);
|
|
619
|
+
const reply = (yield* Effect.promise(() => response.json())) as {
|
|
620
|
+
readonly result?: McpToolResult;
|
|
621
|
+
readonly error?: { readonly message: string };
|
|
622
|
+
};
|
|
623
|
+
if (reply.result === undefined)
|
|
624
|
+
return yield* Effect.die(new Error(reply.error?.message ?? "no result"));
|
|
625
|
+
const result = reply.result;
|
|
626
|
+
const questions: Record<string, { readonly message: string }> = {};
|
|
627
|
+
for (const [key, request] of Object.entries(result.inputRequests ?? {})) {
|
|
628
|
+
questions[key] = { message: request.params?.message ?? "" };
|
|
629
|
+
}
|
|
630
|
+
return {
|
|
631
|
+
resultType: result.resultType ?? "complete",
|
|
632
|
+
isError: result.isError === true,
|
|
633
|
+
structured: result.structuredContent,
|
|
634
|
+
text: result.content?.find((block) => block.type === "text")?.text,
|
|
635
|
+
questions,
|
|
636
|
+
requestState: result.requestState,
|
|
637
|
+
errors: lines
|
|
638
|
+
.slice(before)
|
|
639
|
+
.filter((line) => line.level === "Error" || line.level === "Fatal")
|
|
640
|
+
.map((line) => line.cause ?? line.message),
|
|
641
|
+
} satisfies ToolCall;
|
|
642
|
+
}),
|
|
643
|
+
advance: (duration) => Effect.andThen(TestClock.adjust(duration), settle),
|
|
644
|
+
settle,
|
|
645
|
+
sql,
|
|
646
|
+
logs: Effect.sync(() => [...lines]),
|
|
647
|
+
link: (account, hookOptions) => hook("linked", account, hookOptions),
|
|
648
|
+
unlink: (account, hookOptions) => hook("unlinking", account, hookOptions),
|
|
649
|
+
redeploy: every([...linked.keys()], (account) =>
|
|
650
|
+
hook("linked", account, { cause: "deploy" }),
|
|
651
|
+
),
|
|
652
|
+
leave: (userId) =>
|
|
653
|
+
Effect.suspend(() =>
|
|
654
|
+
every(
|
|
655
|
+
[...linked.keys()].filter((account) => account.endsWith(`:${userId}`)),
|
|
656
|
+
(account) => hook("unlinking", account),
|
|
657
|
+
),
|
|
658
|
+
),
|
|
659
|
+
} satisfies TestApp;
|
|
660
|
+
});
|