@capybara-hq/testing 0.1.0-rc.0 → 0.1.0-rc.10
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 +7 -1
- package/dist/dual-replica.d.ts +35 -10
- package/dist/dual-replica.js +37 -12
- package/dist/fake-channel.d.ts +15 -2
- package/dist/fake-channel.js +11 -2
- package/dist/fake-e2b.d.ts +36 -1
- package/dist/fake-e2b.js +95 -1
- package/dist/fake-git-server.js +3 -1
- package/dist/fake-oauth-server.d.ts +16 -2
- package/dist/fake-oauth-server.js +21 -1
- package/dist/fake-telegram.d.ts +165 -0
- package/dist/fake-telegram.js +569 -0
- package/dist/fixtures.d.ts +8 -4
- package/dist/fixtures.js +10 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +2 -1
- package/dist/kernel-helpers.d.ts +38 -16
- package/dist/kernel-helpers.js +42 -13
- package/dist/model-conformance.d.ts +5 -0
- package/dist/model-conformance.js +33 -1
- package/dist/replica-runner.js +17 -9
- package/fixtures/extensions/fake-config-form/.capybara-plugin/plugin.json +11 -0
- package/fixtures/extensions/fake-config-form/package.json +12 -0
- package/fixtures/extensions/fake-config-form/src/index.ts +205 -0
- package/fixtures/extensions/fake-im/.capybara-plugin/plugin.json +33 -1
- package/fixtures/extensions/fake-im/guides/app.long-connection.yaml.tmpl +5 -0
- package/fixtures/extensions/fake-im/guides/app.webhook.json.tmpl +8 -0
- package/fixtures/extensions/fake-storage-user/src/index.ts +1 -1
- package/fixtures/extensions/fake-tools-ui/skills/fake-notes/SKILL.md +1 -1
- package/fixtures/extensions/fake-tools-ui/src/index.ts +1 -1
- package/fixtures/extensions/fake-web/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-web/package.json +12 -0
- package/fixtures/extensions/fake-web/src/index.ts +22 -0
- package/fixtures/extensions/fake-web/src/web.ts +183 -0
- package/fixtures/extensions/fake-web-2/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-web-2/package.json +12 -0
- package/fixtures/extensions/fake-web-2/src/index.ts +16 -0
- package/fixtures/extensions/fake-web-2/src/web.ts +183 -0
- package/package.json +6 -5
package/README.md
CHANGED
|
@@ -14,7 +14,8 @@ npm install --save-dev @capybara-hq/testing
|
|
|
14
14
|
platform), live in
|
|
15
15
|
`fixtures/extensions/<name>` in the plugin pack layout; `packFixture(name, outDir)` packs one
|
|
16
16
|
into a plugin tgz (needs the optional peer `@capybara-hq/plugin-tools` installed), `fakeExtensionEntry(name)` gives its
|
|
17
|
-
`src/index.ts` for loading by path in
|
|
17
|
+
`src/index.ts` for loading by path (in `createDualReplicaHarness` wherever this package is
|
|
18
|
+
installed; in an in-process kernel when vitest transforms the kernel). A test that edits a fake before packing
|
|
18
19
|
(bump the version, add a migration) packs a copy of `fakeExtensionDir(name)` instead, e.g. with
|
|
19
20
|
the kernel tests' `packPluginDir(fakeExtensionDir("fake-tools-ui"), edit)`, which copies the
|
|
20
21
|
directory to a temp dir and runs `edit` on the copy.
|
|
@@ -24,6 +25,11 @@ npm install --save-dev @capybara-hq/testing
|
|
|
24
25
|
`openSse`, `truncateTables`, `pidOwningLocalPort`, and the kernel's `createDb` / `kernelDb`. With
|
|
25
26
|
these a plugin's tests import only the SDK and this package (plus model-fake, the scripted model
|
|
26
27
|
provider, to drive agent runs).
|
|
28
|
+
- `createDualReplicaHarness` starts each replica as a plain `node` child process. When an entry of
|
|
29
|
+
`extensions` is a TypeScript file (the plugin under test's `src/index.ts`, whose imports say
|
|
30
|
+
`./x.js`, or `fakeExtensionEntry(name)`), the replicas run under tsx, a dependency of this
|
|
31
|
+
package, resolved from it; no `NODE_OPTIONS` loader is needed. Packed plugins and package names
|
|
32
|
+
load in plain Node, as in production.
|
|
27
33
|
- How extension tests are written: "Test template (dual-replica)" in
|
|
28
34
|
[.agents/skills/writing-extensions](https://github.com/capybara-hq/core/tree/main/.agents/skills/writing-extensions).
|
|
29
35
|
- The repository: [capybara-hq/core](https://github.com/capybara-hq/core).
|
package/dist/dual-replica.d.ts
CHANGED
|
@@ -1,21 +1,30 @@
|
|
|
1
1
|
import type { BootstrapManifest } from "@capybara-hq/plugin-sdk";
|
|
2
2
|
/** 双副本测试工具的选项。 */
|
|
3
3
|
export interface DualReplicaOptions {
|
|
4
|
-
/**
|
|
4
|
+
/**
|
|
5
|
+
* Extensions to load (absolute paths, file URLs, or package names resolved from `resolveFrom`).
|
|
6
|
+
* A TypeScript entry (the plugin under test's `src/index.ts`, `fakeExtensionEntry(...)`) makes
|
|
7
|
+
* the replicas run under tsx, which this package ships ({@link needsTypeScript}), also when
|
|
8
|
+
* this package is installed from npm; nothing needs to be set in `NODE_OPTIONS`.
|
|
9
|
+
*/
|
|
5
10
|
extensions: string[];
|
|
6
|
-
/**
|
|
11
|
+
/**
|
|
12
|
+
* Where extensions named by package resolve from; default the caller's `process.cwd()` (the
|
|
13
|
+
* `resolveFrom` of `createKernelApp`).
|
|
14
|
+
*/
|
|
7
15
|
resolveFrom?: string;
|
|
8
16
|
/** 部署级插件配置,按插件名索引。 */
|
|
9
17
|
extensionConfig?: Record<string, unknown>;
|
|
10
18
|
/**
|
|
11
|
-
* The bootstrap step (package ecosystem spec §7): every replica's kernel gets `
|
|
19
|
+
* The bootstrap step (package ecosystem spec §7): every replica's kernel gets `bootstrap: { dir }`
|
|
12
20
|
* and `bootstrapManifest: manifest`, so the replicas run it at start (once across them, under the
|
|
13
|
-
* advisory lock) before loading extensions, as
|
|
14
|
-
*
|
|
15
|
-
*
|
|
21
|
+
* advisory lock) before loading extensions, as `capybara start` does. `dir` is the optional
|
|
22
|
+
* offline directory (its `*.tgz` files are matched to the entries by sha512); the other entries
|
|
23
|
+
* are downloaded from `packages.npmRegistry` (set it in `config`, e.g. to a
|
|
24
|
+
* `startFakeNpmRegistry`). Build both with the kernel tests' `bootstrapFixture` helper.
|
|
16
25
|
*/
|
|
17
26
|
bootstrap?: {
|
|
18
|
-
dir
|
|
27
|
+
dir?: string;
|
|
19
28
|
manifest: BootstrapManifest;
|
|
20
29
|
};
|
|
21
30
|
/**
|
|
@@ -103,10 +112,26 @@ export interface Harness {
|
|
|
103
112
|
stop(): Promise<void>;
|
|
104
113
|
}
|
|
105
114
|
/**
|
|
106
|
-
*
|
|
107
|
-
*
|
|
115
|
+
* tsx's ESM loader, resolved from this package (tsx is one of its dependencies), as a URL for
|
|
116
|
+
* `--import`. Absolute, so it never depends on what the replica's cwd or the caller's repository
|
|
117
|
+
* has installed.
|
|
118
|
+
*/
|
|
119
|
+
export declare const TSX_LOADER: string;
|
|
120
|
+
/**
|
|
121
|
+
* Whether a replica needs a TypeScript loader for `extensions`: true when one is a TypeScript file,
|
|
122
|
+
* such as the plugin under test by path (`plugins/<name>/src/index.ts`, whose imports say `./x.js`)
|
|
123
|
+
* or a fake extension of this package (`fakeExtensionEntry`). Plain Node strips types, but does
|
|
124
|
+
* not map `./x.js` to `./x.ts` and refuses to strip types under `node_modules`, where this package
|
|
125
|
+
* and its fakes live once installed from npm.
|
|
126
|
+
*/
|
|
127
|
+
export declare function needsTypeScript(extensions: readonly string[]): boolean;
|
|
128
|
+
/**
|
|
129
|
+
* The replica's node arguments. A `.ts` runner (this repository, source) always runs under tsx
|
|
130
|
+
* with the source export condition. A compiled `.js` runner (installed from npm) gets tsx only when
|
|
131
|
+
* `typescript` is set ({@link needsTypeScript}): extensions loaded as packed plugins or by package
|
|
132
|
+
* name then run in plain Node, as in production, so a packaging bug is not hidden by the loader.
|
|
108
133
|
*/
|
|
109
|
-
export declare function runnerArgv(runnerPath: string): string[];
|
|
134
|
+
export declare function runnerArgv(runnerPath: string, typescript?: boolean): string[];
|
|
110
135
|
/**
|
|
111
136
|
* 子进程的环境变量。`.ts` 的 runner 额外设置 `TSX_TSCONFIG_PATH` 指向仓库的 tsconfig.base.json:
|
|
112
137
|
* tsx 只认子进程 cwd 下(且 include 覆盖到的)tsconfig,否则内核源码丢掉 experimentalDecorators,
|
package/dist/dual-replica.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
3
4
|
import { extname, resolve } from "node:path";
|
|
4
|
-
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
5
6
|
import { createFreshDatabase, sharedPgAdminUrl, startPostgresContainer, startTestRedis, } from "./containers.js";
|
|
6
7
|
/** 副本在响应头里标明自己的序号(runner 把 `http.replicaId` 设为 `"0"` / `"1"`)。 */
|
|
7
8
|
export const REPLICA_HEADER = "x-capybara-replica";
|
|
@@ -22,13 +23,34 @@ const STDERR_TAIL = 4000;
|
|
|
22
23
|
/** runner 与本文件同目录;源码下是 .ts,编译后是 .js。 */
|
|
23
24
|
const runnerPath = fileURLToPath(new URL(`./replica-runner${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
|
|
24
25
|
/**
|
|
25
|
-
*
|
|
26
|
-
*
|
|
26
|
+
* tsx's ESM loader, resolved from this package (tsx is one of its dependencies), as a URL for
|
|
27
|
+
* `--import`. Absolute, so it never depends on what the replica's cwd or the caller's repository
|
|
28
|
+
* has installed.
|
|
27
29
|
*/
|
|
28
|
-
export
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
30
|
+
export const TSX_LOADER = pathToFileURL(createRequire(import.meta.url).resolve("tsx")).href;
|
|
31
|
+
/** An extension entry that is a TypeScript file (a path or a file URL), as opposed to a package. */
|
|
32
|
+
const TS_ENTRY = /\.[cm]?tsx?$/i;
|
|
33
|
+
/**
|
|
34
|
+
* Whether a replica needs a TypeScript loader for `extensions`: true when one is a TypeScript file,
|
|
35
|
+
* such as the plugin under test by path (`plugins/<name>/src/index.ts`, whose imports say `./x.js`)
|
|
36
|
+
* or a fake extension of this package (`fakeExtensionEntry`). Plain Node strips types, but does
|
|
37
|
+
* not map `./x.js` to `./x.ts` and refuses to strip types under `node_modules`, where this package
|
|
38
|
+
* and its fakes live once installed from npm.
|
|
39
|
+
*/
|
|
40
|
+
export function needsTypeScript(extensions) {
|
|
41
|
+
return extensions.some((e) => TS_ENTRY.test(e));
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The replica's node arguments. A `.ts` runner (this repository, source) always runs under tsx
|
|
45
|
+
* with the source export condition. A compiled `.js` runner (installed from npm) gets tsx only when
|
|
46
|
+
* `typescript` is set ({@link needsTypeScript}): extensions loaded as packed plugins or by package
|
|
47
|
+
* name then run in plain Node, as in production, so a packaging bug is not hidden by the loader.
|
|
48
|
+
*/
|
|
49
|
+
export function runnerArgv(runnerPath, typescript = false) {
|
|
50
|
+
if (runnerPath.endsWith(".ts")) {
|
|
51
|
+
return ["--import", TSX_LOADER, "--conditions=@capybara-hq/source", runnerPath];
|
|
52
|
+
}
|
|
53
|
+
return typescript ? ["--import", TSX_LOADER, runnerPath] : [runnerPath];
|
|
32
54
|
}
|
|
33
55
|
/** 仓库根的 tsconfig.base.json(仅 monorepo 源码态存在)。 */
|
|
34
56
|
const REPO_TSCONFIG = fileURLToPath(new URL("../../../tsconfig.base.json", import.meta.url));
|
|
@@ -41,8 +63,8 @@ export function runnerEnv(runnerPath, env = process.env) {
|
|
|
41
63
|
return runnerPath.endsWith(".ts") ? { ...env, TSX_TSCONFIG_PATH: REPO_TSCONFIG } : env;
|
|
42
64
|
}
|
|
43
65
|
/** 启动一个副本子进程,等它通过 IPC 报告 ready。失败时抛出带 输出尾部的错误(不含配置)。 */
|
|
44
|
-
async function startReplica(config, index) {
|
|
45
|
-
const child = spawn(process.execPath, runnerArgv(runnerPath), {
|
|
66
|
+
async function startReplica(config, index, typescript) {
|
|
67
|
+
const child = spawn(process.execPath, runnerArgv(runnerPath, typescript), {
|
|
46
68
|
stdio: ["ignore", "pipe", "pipe", "ipc"],
|
|
47
69
|
env: runnerEnv(runnerPath),
|
|
48
70
|
cwd: fileURLToPath(new URL("..", import.meta.url)),
|
|
@@ -145,7 +167,9 @@ export async function createDualReplicaHarness(opts) {
|
|
|
145
167
|
masterKey: randomBytes(32).toString("base64"),
|
|
146
168
|
extensions: opts.extensions,
|
|
147
169
|
...(opts.bootstrap !== undefined && {
|
|
148
|
-
|
|
170
|
+
bootstrap: {
|
|
171
|
+
...(opts.bootstrap.dir !== undefined && { dir: resolve(opts.bootstrap.dir) }),
|
|
172
|
+
},
|
|
149
173
|
bootstrapManifest: opts.bootstrap.manifest,
|
|
150
174
|
}),
|
|
151
175
|
// 副本进程的 cwd 不是调用方的 cwd,相对路径必须先按调用方 cwd 绝对化再经 IPC 传过去
|
|
@@ -154,7 +178,8 @@ export async function createDualReplicaHarness(opts) {
|
|
|
154
178
|
overrides: opts.config ?? {},
|
|
155
179
|
};
|
|
156
180
|
const roles = opts.roles ?? [ALL_ROLES, ALL_ROLES];
|
|
157
|
-
const
|
|
181
|
+
const typescript = needsTypeScript(opts.extensions);
|
|
182
|
+
const started = await Promise.allSettled(roles.map((r, i) => startReplica({ ...config, roles: [...r] }, i, typescript)));
|
|
158
183
|
for (const s of started)
|
|
159
184
|
if (s.status === "fulfilled")
|
|
160
185
|
runners.push(s.value.runner);
|
|
@@ -210,7 +235,7 @@ export async function createDualReplicaHarness(opts) {
|
|
|
210
235
|
if (stopPromise)
|
|
211
236
|
throw new Error("harness is stopped");
|
|
212
237
|
const index = handles.length;
|
|
213
|
-
const started = await startReplica({ ...config, roles: [...extraRoles] }, index);
|
|
238
|
+
const started = await startReplica({ ...config, roles: [...extraRoles] }, index, typescript);
|
|
214
239
|
runners.push(started.runner);
|
|
215
240
|
// A stop() that began while this replica was starting must not leave it running
|
|
216
241
|
if (stopPromise) {
|
package/dist/fake-channel.d.ts
CHANGED
|
@@ -40,7 +40,7 @@ export interface FakeChannelSent {
|
|
|
40
40
|
pid: number;
|
|
41
41
|
/** 内核给的幂等键(`ChannelSendArgs.idempotencyKey`)。 */
|
|
42
42
|
idempotencyKey?: string;
|
|
43
|
-
/**
|
|
43
|
+
/** The language the kernel gave (`ChannelSendArgs.locale`: the recipient's, else the org's). */
|
|
44
44
|
locale?: "zh" | "en";
|
|
45
45
|
at: number;
|
|
46
46
|
}
|
|
@@ -71,6 +71,12 @@ export interface FakeDirectoryBook {
|
|
|
71
71
|
/** 整轮同步开始的次数(不带游标的请求数)。 */
|
|
72
72
|
starts(): number;
|
|
73
73
|
}
|
|
74
|
+
/** Which `/send` or `/update` requests a {@link FakeChannelServer.failNext} failure applies to. */
|
|
75
|
+
export interface FakeChannelFailMatch {
|
|
76
|
+
chatId?: string;
|
|
77
|
+
/** The message's text contains it. */
|
|
78
|
+
textIncludes?: string;
|
|
79
|
+
}
|
|
74
80
|
/** 插件工具经 `POST /posts` 发出的一条记录。 */
|
|
75
81
|
export interface FakeChannelPost {
|
|
76
82
|
body: Record<string, unknown>;
|
|
@@ -101,8 +107,11 @@ export interface FakeChannelServer {
|
|
|
101
107
|
* 让接下来 `count` 次 `/send`(或 `/update`)返回该状态码(不记录);`retryAfterMs` 与 `reason` 放进响应体,
|
|
102
108
|
* 测试插件据此抛 `ChannelSendError`(429 / 5xx 可重试,带等待时长;其他不可重试,带失败原因)。
|
|
103
109
|
* `delayMs`:失败响应推迟这么久才返回(模拟慢的失败请求,让会话的后续事件在投递任务持锁期间到达)。
|
|
110
|
+
* `match`: only matching requests count and fail; a string is a chat id, an object also matches
|
|
111
|
+
* text (`textIncludes`: the message's text contains it). Without it the next requests to any chat
|
|
112
|
+
* fail, so a late delivery from an earlier test can take the failure meant for the request under test.
|
|
104
113
|
*/
|
|
105
|
-
failNext(path: "/send" | "/update", status: number, count?: number, retryAfterMs?: number, reason?: "auth" | "target_gone" | "rejected" | "too_large", delayMs?: number): void;
|
|
114
|
+
failNext(path: "/send" | "/update", status: number, count?: number, retryAfterMs?: number, reason?: "auth" | "target_gone" | "rejected" | "too_large", delayMs?: number, match?: string | FakeChannelFailMatch): void;
|
|
106
115
|
/**
|
|
107
116
|
* Delay the response of the next `count` successful `/send` (or `/update`) requests by `delayMs`.
|
|
108
117
|
* The message is recorded (visible in `sent` / `updated`) as soon as the request arrives; only the
|
|
@@ -135,6 +144,10 @@ export declare function startFakeChannelServer(opts?: FakeChannelServerOptions):
|
|
|
135
144
|
export interface FakeSenderProfile {
|
|
136
145
|
displayName?: string;
|
|
137
146
|
avatarUrl?: string;
|
|
147
|
+
/** The sender's IANA time zone on the platform (channel@1 `sender.timeZone`). */
|
|
148
|
+
timeZone?: string;
|
|
149
|
+
/** The sender's language tag on the platform (channel@1 `sender.locale`). */
|
|
150
|
+
locale?: string;
|
|
138
151
|
}
|
|
139
152
|
/** 私聊文本消息(chat id 为 `dm-<externalId>`);`profile` 给了就带上发言人的显示名 / 头像。 */
|
|
140
153
|
export declare function fakeDm(messageId: string, externalId: string, text: string, tenantId?: string, profile?: FakeSenderProfile): InboundEvent;
|
package/dist/fake-channel.js
CHANGED
|
@@ -61,7 +61,11 @@ export async function startFakeChannelServer(opts = {}) {
|
|
|
61
61
|
};
|
|
62
62
|
const sendOrUpdate = async (req, res, path) => {
|
|
63
63
|
const body = await readBody(req);
|
|
64
|
-
const
|
|
64
|
+
const parsed = JSON.parse(body);
|
|
65
|
+
const matches = (m) => m === undefined ||
|
|
66
|
+
((m.chatId === undefined || m.chatId === parsed.target?.chatId) &&
|
|
67
|
+
(m.textIncludes === undefined || (parsed.message?.text ?? "").includes(m.textIncludes)));
|
|
68
|
+
const f = failures.find((x) => x.path === path && x.left > 0 && matches(x.match));
|
|
65
69
|
if (f) {
|
|
66
70
|
f.left--;
|
|
67
71
|
if (f.delayMs !== undefined)
|
|
@@ -203,7 +207,7 @@ export async function startFakeChannelServer(opts = {}) {
|
|
|
203
207
|
duplicateSends,
|
|
204
208
|
posts,
|
|
205
209
|
users,
|
|
206
|
-
failNext(path, status, count = 1, retryAfterMs, reason, delayMs) {
|
|
210
|
+
failNext(path, status, count = 1, retryAfterMs, reason, delayMs, match) {
|
|
207
211
|
failures.push({
|
|
208
212
|
path,
|
|
209
213
|
status,
|
|
@@ -211,6 +215,9 @@ export async function startFakeChannelServer(opts = {}) {
|
|
|
211
215
|
...(retryAfterMs !== undefined && { retryAfterMs }),
|
|
212
216
|
...(reason !== undefined && { reason }),
|
|
213
217
|
...(delayMs !== undefined && { delayMs }),
|
|
218
|
+
...(match !== undefined && {
|
|
219
|
+
match: typeof match === "string" ? { chatId: match } : match,
|
|
220
|
+
}),
|
|
214
221
|
});
|
|
215
222
|
},
|
|
216
223
|
delayNext(path, delayMs, opts = {}) {
|
|
@@ -261,6 +268,8 @@ const senderOf = (externalId, tenantId, profile = {}) => ({
|
|
|
261
268
|
tenantId,
|
|
262
269
|
...(profile.displayName !== undefined && { displayName: profile.displayName }),
|
|
263
270
|
...(profile.avatarUrl !== undefined && { avatarUrl: profile.avatarUrl }),
|
|
271
|
+
...(profile.timeZone !== undefined && { timeZone: profile.timeZone }),
|
|
272
|
+
...(profile.locale !== undefined && { locale: profile.locale }),
|
|
264
273
|
});
|
|
265
274
|
/** 私聊文本消息(chat id 为 `dm-<externalId>`);`profile` 给了就带上发言人的显示名 / 头像。 */
|
|
266
275
|
export function fakeDm(messageId, externalId, text, tenantId = "t1", profile) {
|
package/dist/fake-e2b.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* A programmable fake E2B (for the tests of the sandbox-e2b plugin in capybara-hq/plugins), following
|
|
3
|
+
* the `e2b` JS SDK 2.58.0 and the E2B docs (checked 2026-10-21):
|
|
3
4
|
*
|
|
4
5
|
* - **控制面 API**(请求头 `X-API-KEY`,不符 → 401 `{code, message}`):
|
|
5
6
|
* `POST /v2/sandboxes`(建沙箱,回 201 `{sandboxID, templateID, envdVersion, envdAccessToken, domain}`)、
|
|
@@ -18,6 +19,21 @@
|
|
|
18
19
|
* 本机只有一个用户,权限隔离测不了,测试改为核对请求里的用户)。进程以新会话启动(与 setsid 等价),
|
|
19
20
|
* 客户端断开**不会**结束进程(与 envd 一致),只有 SendSignal、杀进程脚本或删沙箱才会。
|
|
20
21
|
*
|
|
22
|
+
* - **Template build** (the routes `Template.build(Template().fromImage(image), alias)` calls, e2b 2.58.0
|
|
23
|
+
* `buildApi`; all need `X-API-KEY`): `POST /v3/templates` (body `{name, tags?, cpuCount?, memoryMB?}`,
|
|
24
|
+
* `name` may carry `:tag`; 202 `{templateID, buildID, names, aliases, tags, public}`),
|
|
25
|
+
* `GET /templates/{templateID}/files/{hash}` (upload link of a COPY step; `{present: true}`),
|
|
26
|
+
* `POST /v2/templates/{templateID}/builds/{buildID}` (body `{fromImage, steps, force, startCmd?,
|
|
27
|
+
* readyCmd?}`; 202, and {@link FakeE2BOptions.templateBuildMs} starts counting), `GET
|
|
28
|
+
* /templates/{templateID}/builds/{buildID}/status?logsOffset=` (`{buildID, templateID, status:
|
|
29
|
+
* waiting | building | ready, logEntries, logs}`), `GET /templates/aliases/{alias}` (200
|
|
30
|
+
* `{templateID, public}`, else 404). A template (including the seeded `templates`) creates
|
|
31
|
+
* sandboxes by alias or templateID; one still building answers 404; template names never
|
|
32
|
+
* registered are accepted as before.
|
|
33
|
+
* - **Pause**: `POST /sandboxes/{id}/pause` with `{memory: false}` (the SDK's `mode: "filesystem"`)
|
|
34
|
+
* ends all processes and keeps the files; otherwise (also an empty body) processes stay.
|
|
35
|
+
* {@link FakeE2BServer.removeSandbox} simulates a lost paused sandbox.
|
|
36
|
+
*
|
|
21
37
|
* `connect` 带 `memory: false`(SDK 的 `onResume: "reboot"`)时结束该沙箱的全部进程(冷启动)。
|
|
22
38
|
* SendSignal 只杀指定进程(不是进程组)。
|
|
23
39
|
*
|
|
@@ -31,6 +47,19 @@ export interface FakeE2BOptions {
|
|
|
31
47
|
pageSize?: number;
|
|
32
48
|
/** create / connect 返回的沙箱 `domain`(默认 null,即用客户端配置的域名)。 */
|
|
33
49
|
domain?: string | null;
|
|
50
|
+
/** Existing template aliases (treated as built). */
|
|
51
|
+
templates?: string[];
|
|
52
|
+
/** Milliseconds from triggering a template build to `ready` (default 0). */
|
|
53
|
+
templateBuildMs?: number;
|
|
54
|
+
}
|
|
55
|
+
export interface FakeE2BTemplate {
|
|
56
|
+
templateID: string;
|
|
57
|
+
alias: string;
|
|
58
|
+
/** The image it was built from (undefined for a seeded template). */
|
|
59
|
+
image?: string | undefined;
|
|
60
|
+
buildID?: string | undefined;
|
|
61
|
+
/** When it becomes `ready` (ms timestamp); undefined until the build is triggered (waiting). */
|
|
62
|
+
readyAt?: number | undefined;
|
|
34
63
|
}
|
|
35
64
|
export interface FakeE2BSandbox {
|
|
36
65
|
id: string;
|
|
@@ -40,6 +69,8 @@ export interface FakeE2BSandbox {
|
|
|
40
69
|
/** 当前的超时(秒):建沙箱时给的,connect 只会把它调大。 */
|
|
41
70
|
timeout: number;
|
|
42
71
|
autoPause: boolean;
|
|
72
|
+
/** Whether the last pause kept memory (`pause` body `memory` is not false). */
|
|
73
|
+
pausedWithMemory?: boolean;
|
|
43
74
|
/** 建沙箱请求体里的出站设置(原样记录)。 */
|
|
44
75
|
allowInternetAccess?: boolean;
|
|
45
76
|
network?: unknown;
|
|
@@ -70,6 +101,8 @@ export interface FakeE2BServer {
|
|
|
70
101
|
url: string;
|
|
71
102
|
apiKey: string;
|
|
72
103
|
sandboxes: Map<string, FakeE2BSandbox>;
|
|
104
|
+
/** Templates by alias. */
|
|
105
|
+
templates: Map<string, FakeE2BTemplate>;
|
|
73
106
|
calls: FakeE2BCall[];
|
|
74
107
|
/**
|
|
75
108
|
* 下一个匹配的请求回 `status`:默认 E2B 的错误格式 JSON `{code: status, message}`;`raw` 时回纯文本
|
|
@@ -89,6 +122,8 @@ export interface FakeE2BServer {
|
|
|
89
122
|
withholdAccessToken: boolean;
|
|
90
123
|
/** 沙箱直接消失(杀掉它的进程、删掉根目录)。 */
|
|
91
124
|
expire(id: string): Promise<void>;
|
|
125
|
+
/** Same as {@link FakeE2BServer.expire}: simulates a lost paused sandbox (connect then answers 404). */
|
|
126
|
+
removeSandbox(id: string): Promise<void>;
|
|
92
127
|
/** 沙箱内路径在本机上的位置。 */
|
|
93
128
|
hostPath(id: string, sandboxPath: string): string;
|
|
94
129
|
/** 沙箱里还在跑的进程(由 Start 启动、尚未退出的)。 */
|
package/dist/fake-e2b.js
CHANGED
|
@@ -84,6 +84,12 @@ export async function startFakeE2B(opts = {}) {
|
|
|
84
84
|
await chmod(join(shims, "setsid"), 0o755);
|
|
85
85
|
const sandboxes = new Map();
|
|
86
86
|
const procs = new Map();
|
|
87
|
+
const templates = new Map();
|
|
88
|
+
for (const alias of opts.templates ?? [])
|
|
89
|
+
templates.set(alias, { templateID: `t${randomBytes(6).toString("hex")}`, alias });
|
|
90
|
+
const buildMs = opts.templateBuildMs ?? 0;
|
|
91
|
+
const templateByRef = (ref) => templates.get(ref) ?? [...templates.values()].find((t) => t.templateID === ref);
|
|
92
|
+
const ready = (t) => t.readyAt !== undefined && Date.now() >= t.readyAt;
|
|
87
93
|
const calls = [];
|
|
88
94
|
const fails = [];
|
|
89
95
|
const reboots = new Map();
|
|
@@ -122,12 +128,13 @@ export async function startFakeE2B(opts = {}) {
|
|
|
122
128
|
};
|
|
123
129
|
const newSandbox = async (body) => {
|
|
124
130
|
const id = `i${randomBytes(9).toString("hex")}`;
|
|
131
|
+
const tpl = templateByRef(String(body.templateID));
|
|
125
132
|
const root = join(base, id);
|
|
126
133
|
for (const d of ROOT_DIRS)
|
|
127
134
|
await mkdir(join(root, d), { recursive: true });
|
|
128
135
|
const s = {
|
|
129
136
|
id,
|
|
130
|
-
templateID: String(body.templateID),
|
|
137
|
+
templateID: tpl?.templateID ?? String(body.templateID),
|
|
131
138
|
metadata: body.metadata ?? {},
|
|
132
139
|
state: "running",
|
|
133
140
|
timeout: typeof body.timeout === "number" ? body.timeout : 300,
|
|
@@ -160,6 +167,11 @@ export async function startFakeE2B(opts = {}) {
|
|
|
160
167
|
sendJson(res, 400, { code: 400, message: "templateID is required" });
|
|
161
168
|
return;
|
|
162
169
|
}
|
|
170
|
+
const tpl = templateByRef(body.templateID);
|
|
171
|
+
if (tpl?.buildID !== undefined && !ready(tpl)) {
|
|
172
|
+
sendJson(res, 404, { code: 404, message: `template '${body.templateID}' is not ready` });
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
163
175
|
const s = await newSandbox(body);
|
|
164
176
|
sendJson(res, 201, {
|
|
165
177
|
sandboxID: s.id,
|
|
@@ -235,9 +247,89 @@ export async function startFakeE2B(opts = {}) {
|
|
|
235
247
|
return;
|
|
236
248
|
}
|
|
237
249
|
s.state = "paused";
|
|
250
|
+
s.pausedWithMemory = body.memory !== false;
|
|
251
|
+
if (!s.pausedWithMemory) {
|
|
252
|
+
// filesystem-only snapshot: the processes are gone, the files stay
|
|
253
|
+
for (const p of procs.get(s.id) ?? [])
|
|
254
|
+
killGroup(p);
|
|
255
|
+
procs.delete(s.id);
|
|
256
|
+
}
|
|
238
257
|
sendJson(res, 204);
|
|
239
258
|
return;
|
|
240
259
|
}
|
|
260
|
+
if (method === "POST" && path === "/v3/templates") {
|
|
261
|
+
const name = typeof body.name === "string" ? body.name : "";
|
|
262
|
+
if (name === "") {
|
|
263
|
+
sendJson(res, 400, { code: 400, message: "name is required" });
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
const alias = name.split(":")[0];
|
|
267
|
+
const tags = Array.isArray(body.tags) ? body.tags : [];
|
|
268
|
+
const t = templates.get(alias) ?? {
|
|
269
|
+
templateID: `t${randomBytes(6).toString("hex")}`,
|
|
270
|
+
alias,
|
|
271
|
+
};
|
|
272
|
+
t.buildID = randomBytes(8).toString("hex");
|
|
273
|
+
t.readyAt = undefined;
|
|
274
|
+
t.image = undefined;
|
|
275
|
+
templates.set(alias, t);
|
|
276
|
+
sendJson(res, 202, {
|
|
277
|
+
templateID: t.templateID,
|
|
278
|
+
buildID: t.buildID,
|
|
279
|
+
names: [name],
|
|
280
|
+
aliases: [alias],
|
|
281
|
+
tags,
|
|
282
|
+
public: false,
|
|
283
|
+
});
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
m = /^\/templates\/([^/]+)\/files\/([^/]+)$/.exec(path);
|
|
287
|
+
if (m && method === "GET") {
|
|
288
|
+
sendJson(res, 200, { present: true });
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
m = /^\/v2\/templates\/([^/]+)\/builds\/([^/]+)$/.exec(path);
|
|
292
|
+
if (m && method === "POST") {
|
|
293
|
+
const t = templateByRef(m[1]);
|
|
294
|
+
if (!t || t.buildID !== m[2]) {
|
|
295
|
+
sendJson(res, 404, { code: 404, message: "build not found" });
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
if (typeof body.fromImage !== "string") {
|
|
299
|
+
sendJson(res, 400, { code: 400, message: "fromImage is required" });
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
t.image = body.fromImage;
|
|
303
|
+
t.readyAt = Date.now() + buildMs;
|
|
304
|
+
sendJson(res, 202);
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
m = /^\/templates\/([^/]+)\/builds\/([^/]+)\/status$/.exec(path);
|
|
308
|
+
if (m && method === "GET") {
|
|
309
|
+
const t = templateByRef(m[1]);
|
|
310
|
+
if (!t || t.buildID !== m[2]) {
|
|
311
|
+
sendJson(res, 404, { code: 404, message: "build not found" });
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
sendJson(res, 200, {
|
|
315
|
+
buildID: t.buildID,
|
|
316
|
+
templateID: t.templateID,
|
|
317
|
+
status: t.readyAt === undefined ? "waiting" : ready(t) ? "ready" : "building",
|
|
318
|
+
logEntries: [],
|
|
319
|
+
logs: [],
|
|
320
|
+
});
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
m = /^\/templates\/aliases\/([^/]+)$/.exec(path);
|
|
324
|
+
if (m && method === "GET") {
|
|
325
|
+
const t = templates.get(decodeURIComponent(m[1]));
|
|
326
|
+
if (!t) {
|
|
327
|
+
sendJson(res, 404, { code: 404, message: `template '${m[1]}' not found` });
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
sendJson(res, 200, { templateID: t.templateID, public: false });
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
241
333
|
m = /^\/sandboxes\/([^/]+)$/.exec(path);
|
|
242
334
|
if (m && method === "DELETE") {
|
|
243
335
|
if (!sandboxes.has(m[1]))
|
|
@@ -454,6 +546,7 @@ export async function startFakeE2B(opts = {}) {
|
|
|
454
546
|
url,
|
|
455
547
|
apiKey,
|
|
456
548
|
sandboxes,
|
|
549
|
+
templates,
|
|
457
550
|
calls,
|
|
458
551
|
failNext(match, status, message = `fake failure ${status}`, opts = {}) {
|
|
459
552
|
fails.push({ match, status, message, raw: opts.raw === true });
|
|
@@ -469,6 +562,7 @@ export async function startFakeE2B(opts = {}) {
|
|
|
469
562
|
hangs.push(match);
|
|
470
563
|
},
|
|
471
564
|
expire: destroy,
|
|
565
|
+
removeSandbox: destroy,
|
|
472
566
|
hostPath(id, sandboxPath) {
|
|
473
567
|
const s = sandboxes.get(id);
|
|
474
568
|
if (!s)
|
package/dist/fake-git-server.js
CHANGED
|
@@ -129,8 +129,10 @@ function serveCgi(root, req, res) {
|
|
|
129
129
|
res.writeHead(h.status, h.headers);
|
|
130
130
|
res.write(head.subarray(h.bodyStart));
|
|
131
131
|
});
|
|
132
|
+
// A child that could not be spawned emits 'error' and then 'close': only the first writes a head
|
|
133
|
+
// (a second writeHead throws ERR_HTTP_HEADERS_SENT, an uncaught exception).
|
|
132
134
|
p.on("close", () => {
|
|
133
|
-
if (!headDone)
|
|
135
|
+
if (!headDone && !res.headersSent)
|
|
134
136
|
res.writeHead(502);
|
|
135
137
|
res.end();
|
|
136
138
|
});
|
|
@@ -19,6 +19,15 @@ export interface FakeOAuthServerOptions {
|
|
|
19
19
|
scopesSupported?: string[];
|
|
20
20
|
/** 元数据里的 `code_challenge_methods_supported`;null = 不声明。默认 `["S256"]`。 */
|
|
21
21
|
pkceMethods?: string[] | null;
|
|
22
|
+
/**
|
|
23
|
+
* How the token endpoint answers. `"oauth"` (default): RFC 6749 (`token_type: "Bearer"`, errors
|
|
24
|
+
* as 400 / 401 `{ error }`). `"slack"`: like Slack's `oauth.v2.user.access`: success is
|
|
25
|
+
* `{ ok: true, token_type: "user", ... }`, every error is HTTP 200 `{ ok: false, error }` with
|
|
26
|
+
* Slack's codes where they differ (`invalid_code`, `invalid_refresh_token`, `invalid_client_id`).
|
|
27
|
+
*/
|
|
28
|
+
dialect?: "oauth" | "slack";
|
|
29
|
+
/** The `token_type` of successful token responses (default: `Bearer`; `user` with dialect slack). */
|
|
30
|
+
tokenType?: string;
|
|
22
31
|
}
|
|
23
32
|
/** 令牌端点收到的一次请求(不含任何密钥)。 */
|
|
24
33
|
export interface FakeTokenRequest {
|
|
@@ -28,8 +37,10 @@ export interface FakeTokenRequest {
|
|
|
28
37
|
scope: string | undefined;
|
|
29
38
|
/** 客户端认证方式:Basic 头、表单里的 client_secret、或只有 client_id。 */
|
|
30
39
|
clientAuth: "basic" | "post" | "none";
|
|
31
|
-
/** 本次响应的 HTTP
|
|
40
|
+
/** 本次响应的 HTTP 状态(dialect slack: errors are 200 too). */
|
|
32
41
|
status: number;
|
|
42
|
+
/** The error code answered, if any (as sent: Slack's code with dialect slack). */
|
|
43
|
+
error?: string;
|
|
33
44
|
}
|
|
34
45
|
export interface FakeOAuthServer {
|
|
35
46
|
/** issuer(`http://127.0.0.1:<port>`),也是各端点的基址。 */
|
|
@@ -45,7 +56,10 @@ export interface FakeOAuthServer {
|
|
|
45
56
|
issuedSecrets(): string[];
|
|
46
57
|
/** 作废全部 access token(refresh token 仍有效):资源服务随之返回 401。 */
|
|
47
58
|
revokeAccessTokens(): void;
|
|
48
|
-
/**
|
|
59
|
+
/**
|
|
60
|
+
* 作废全部 refresh token:之后的刷新返回 `invalid_grant`(dialect slack: HTTP 200
|
|
61
|
+
* `{ ok: false, error: "invalid_refresh_token" }`)。
|
|
62
|
+
*/
|
|
49
63
|
revokeRefreshTokens(): void;
|
|
50
64
|
/** 下一次授权请求以该 OAuth 错误回跳。 */
|
|
51
65
|
denyNext(error: string, description?: string): void;
|
|
@@ -19,6 +19,16 @@ const json = (res, status, body) => {
|
|
|
19
19
|
*/
|
|
20
20
|
export async function startFakeOAuthServer(opts = {}) {
|
|
21
21
|
let dcr = opts.dcr ?? true;
|
|
22
|
+
const slack = opts.dialect === "slack";
|
|
23
|
+
const tokenType = opts.tokenType ?? (slack ? "user" : "Bearer");
|
|
24
|
+
/** RFC 6749 error code -> Slack's code for the same failure (dialect slack). */
|
|
25
|
+
const slackCode = (error, grantType) => {
|
|
26
|
+
if (error === "invalid_grant")
|
|
27
|
+
return grantType === "refresh_token" ? "invalid_refresh_token" : "invalid_code";
|
|
28
|
+
if (error === "invalid_client")
|
|
29
|
+
return "invalid_client_id";
|
|
30
|
+
return error;
|
|
31
|
+
};
|
|
22
32
|
const ttl = opts.accessTokenTtl ?? 3600;
|
|
23
33
|
const clients = new Map((opts.clients ?? []).map((c) => [
|
|
24
34
|
c.clientId,
|
|
@@ -53,7 +63,11 @@ export async function startFakeOAuthServer(opts = {}) {
|
|
|
53
63
|
const accessToken = rand("at_");
|
|
54
64
|
access.set(accessToken, { expiresAt: ttl > 0 ? Date.now() + ttl * 1000 : null });
|
|
55
65
|
secrets.add(accessToken);
|
|
56
|
-
const body = {
|
|
66
|
+
const body = {
|
|
67
|
+
...(slack && { ok: true }),
|
|
68
|
+
access_token: accessToken,
|
|
69
|
+
token_type: tokenType,
|
|
70
|
+
};
|
|
57
71
|
if (ttl > 0)
|
|
58
72
|
body.expires_in = ttl;
|
|
59
73
|
if (scope !== undefined)
|
|
@@ -108,7 +122,13 @@ export async function startFakeOAuthServer(opts = {}) {
|
|
|
108
122
|
return json(res, tokenFailures.status, tokenFailures.body ?? { message: "fake failure" });
|
|
109
123
|
}
|
|
110
124
|
const fail = (status, error) => {
|
|
125
|
+
if (slack) {
|
|
126
|
+
entry.status = 200;
|
|
127
|
+
entry.error = slackCode(error, grantType);
|
|
128
|
+
return json(res, 200, { ok: false, error: entry.error });
|
|
129
|
+
}
|
|
111
130
|
entry.status = status;
|
|
131
|
+
entry.error = error;
|
|
112
132
|
json(res, status, { error, error_description: `fake: ${error}` });
|
|
113
133
|
};
|
|
114
134
|
const client = authenticate(req, form);
|