@capybara-hq/testing 0.1.0-rc.3 → 0.1.0-rc.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/containers.d.ts +7 -2
  2. package/dist/containers.js +7 -3
  3. package/dist/dual-replica.d.ts +15 -1
  4. package/dist/dual-replica.js +49 -0
  5. package/dist/fake-channel.d.ts +51 -3
  6. package/dist/fake-channel.js +71 -3
  7. package/dist/fake-e2b.d.ts +34 -0
  8. package/dist/fake-e2b.js +95 -1
  9. package/dist/fake-git-server.d.ts +32 -4
  10. package/dist/fake-git-server.js +87 -19
  11. package/dist/fake-lark.d.ts +12 -1
  12. package/dist/fake-lark.js +63 -10
  13. package/dist/fake-oauth-server.d.ts +16 -2
  14. package/dist/fake-oauth-server.js +21 -1
  15. package/dist/fake-slack.d.ts +17 -1
  16. package/dist/fake-slack.js +98 -0
  17. package/dist/fake-telegram.d.ts +173 -0
  18. package/dist/fake-telegram.js +632 -0
  19. package/dist/fixtures.d.ts +25 -7
  20. package/dist/fixtures.js +35 -7
  21. package/dist/index.d.ts +12 -8
  22. package/dist/index.js +8 -4
  23. package/dist/kernel-helpers.d.ts +16 -4
  24. package/dist/kernel-helpers.js +39 -4
  25. package/dist/media-samples.d.ts +2 -0
  26. package/dist/media-samples.js +2 -0
  27. package/dist/model-conformance.d.ts +15 -10
  28. package/dist/model-conformance.js +87 -14
  29. package/dist/push-conformance.d.ts +31 -0
  30. package/dist/push-conformance.js +160 -0
  31. package/dist/replica-runner.js +2 -0
  32. package/dist/sandbox-native-conformance.d.ts +31 -0
  33. package/dist/sandbox-native-conformance.js +153 -0
  34. package/dist/sandbox-permission-conformance.d.ts +307 -0
  35. package/dist/sandbox-permission-conformance.js +1475 -0
  36. package/fixtures/extensions/fake-client/.capybara-plugin/plugin.json +11 -0
  37. package/fixtures/extensions/fake-client/client/styles/fake.css +11 -0
  38. package/fixtures/extensions/fake-client/package.json +12 -0
  39. package/fixtures/extensions/fake-client/src/client.tsx +51 -0
  40. package/fixtures/extensions/fake-client/src/index.ts +43 -0
  41. package/fixtures/extensions/fake-client/themes/fake.json +11 -0
  42. package/fixtures/extensions/fake-client-broken/.capybara-plugin/plugin.json +7 -0
  43. package/fixtures/extensions/fake-client-broken/package.json +12 -0
  44. package/fixtures/extensions/fake-client-broken/src/client.tsx +22 -0
  45. package/fixtures/extensions/fake-client-broken/src/index.ts +27 -0
  46. package/fixtures/extensions/fake-config-form/.capybara-plugin/plugin.json +11 -0
  47. package/fixtures/extensions/fake-config-form/package.json +12 -0
  48. package/fixtures/extensions/fake-config-form/src/index.ts +205 -0
  49. package/fixtures/extensions/fake-connector/src/index.ts +41 -21
  50. package/fixtures/extensions/fake-context/.capybara-plugin/plugin.json +7 -0
  51. package/fixtures/extensions/fake-context/package.json +12 -0
  52. package/fixtures/extensions/fake-context/src/index.ts +81 -0
  53. package/fixtures/extensions/fake-dep-provider/src/index.ts +1 -1
  54. package/fixtures/extensions/fake-dep-requirer/src/index.ts +1 -1
  55. package/fixtures/extensions/fake-embed/src/index.ts +26 -26
  56. package/fixtures/extensions/fake-im/.capybara-plugin/plugin.json +7 -1
  57. package/fixtures/extensions/fake-im/guides/fake-im-app.md +32 -0
  58. package/fixtures/extensions/fake-im/guides/fake-im-app.zh.md +32 -0
  59. package/fixtures/extensions/fake-im/src/channel.ts +22 -1
  60. package/fixtures/extensions/fake-im/src/checks.ts +94 -0
  61. package/fixtures/extensions/fake-im/src/index.ts +45 -2
  62. package/fixtures/extensions/fake-lifecycle/.capybara-plugin/plugin.json +7 -0
  63. package/fixtures/extensions/fake-lifecycle/migrations/0001_init.sql +16 -0
  64. package/fixtures/extensions/fake-lifecycle/package.json +12 -0
  65. package/fixtures/extensions/fake-lifecycle/src/index.ts +72 -0
  66. package/fixtures/extensions/fake-openapi/src/index.ts +46 -34
  67. package/fixtures/extensions/fake-push/.capybara-plugin/plugin.json +13 -0
  68. package/fixtures/extensions/fake-push/guides/fake-push-key.md +6 -0
  69. package/fixtures/extensions/fake-push/guides/fake-push-key.zh.md +6 -0
  70. package/fixtures/extensions/fake-push/migrations/0001_sends.sql +9 -0
  71. package/fixtures/extensions/fake-push/package.json +12 -0
  72. package/fixtures/extensions/fake-push/src/check.ts +40 -0
  73. package/fixtures/extensions/fake-push/src/index.ts +48 -0
  74. package/fixtures/extensions/fake-push/src/push.ts +103 -0
  75. package/fixtures/extensions/fake-storage-user/src/index.ts +1 -1
  76. package/fixtures/extensions/fake-tools-ui/skills/fake-notes/SKILL.md +1 -1
  77. package/fixtures/extensions/fake-tools-ui/src/index.ts +62 -3
  78. package/fixtures/extensions/fake-web/.capybara-plugin/plugin.json +7 -0
  79. package/fixtures/extensions/fake-web/package.json +12 -0
  80. package/fixtures/extensions/fake-web/src/index.ts +22 -0
  81. package/fixtures/extensions/fake-web/src/web.ts +183 -0
  82. package/fixtures/extensions/fake-web-2/.capybara-plugin/plugin.json +7 -0
  83. package/fixtures/extensions/fake-web-2/package.json +12 -0
  84. package/fixtures/extensions/fake-web-2/src/index.ts +16 -0
  85. package/fixtures/extensions/fake-web-2/src/web.ts +183 -0
  86. package/fixtures/plugins/fake-theme/.capybara-plugin/plugin.json +7 -0
  87. package/fixtures/plugins/fake-theme/fonts/FakeSans.woff2 +1 -0
  88. package/fixtures/plugins/fake-theme/logo.svg +1 -0
  89. package/fixtures/plugins/fake-theme/package.json +8 -0
  90. package/fixtures/plugins/fake-theme/themes/neon-grid.json +13 -0
  91. package/fixtures/plugins/fake-theme/themes/paper.json +12 -0
  92. package/package.json +6 -5
@@ -38,12 +38,17 @@ export declare const DEFAULT_CONTAINER_STARTS = 4;
38
38
  * `key` is the slot set (tests use their own).
39
39
  */
40
40
  export declare function withStartSlot<T>(start: () => Promise<T>, key?: string): Promise<T>;
41
+ /** The PostgreSQL image tests run on: PostgreSQL 17 with pgvector, as in the compose files. */
42
+ export declare const TEST_PG_IMAGE = "pgvector/pgvector:pg17";
41
43
  /**
42
- * Start a throwaway PostgreSQL 17 container. `tuned` is for the run-wide shared instance: many files
43
- * connect at once (raise `max_connections`), and durability is irrelevant for tests (no fsync).
44
+ * Start a throwaway PostgreSQL 17 container (`TEST_PG_IMAGE` unless `image` names another, e.g.
45
+ * plain `postgres:17` to test a server without pgvector). `tuned` is for the run-wide shared
46
+ * instance: many files connect at once (raise `max_connections`), and durability is irrelevant for
47
+ * tests (no fsync).
44
48
  */
45
49
  export declare function startPostgresContainer(opts?: {
46
50
  tuned?: boolean;
51
+ image?: string;
47
52
  }): Promise<TestContainer>;
48
53
  /** Start a throwaway Valkey 8 container, returning `redis://host:port`. */
49
54
  export declare function startRedisContainer(opts?: {
@@ -90,12 +90,16 @@ export async function withStartSlot(start, key = START_SLOTS_KEY) {
90
90
  r.disconnect();
91
91
  }
92
92
  }
93
+ /** The PostgreSQL image tests run on: PostgreSQL 17 with pgvector, as in the compose files. */
94
+ export const TEST_PG_IMAGE = "pgvector/pgvector:pg17";
93
95
  /**
94
- * Start a throwaway PostgreSQL 17 container. `tuned` is for the run-wide shared instance: many files
95
- * connect at once (raise `max_connections`), and durability is irrelevant for tests (no fsync).
96
+ * Start a throwaway PostgreSQL 17 container (`TEST_PG_IMAGE` unless `image` names another, e.g.
97
+ * plain `postgres:17` to test a server without pgvector). `tuned` is for the run-wide shared
98
+ * instance: many files connect at once (raise `max_connections`), and durability is irrelevant for
99
+ * tests (no fsync).
96
100
  */
97
101
  export async function startPostgresContainer(opts = {}) {
98
- const image = new PostgreSqlContainer("postgres:17");
102
+ const image = new PostgreSqlContainer(opts.image ?? TEST_PG_IMAGE);
99
103
  if (opts.tuned) {
100
104
  image.withCommand([
101
105
  "postgres",
@@ -108,7 +108,21 @@ export interface Harness {
108
108
  * 另一个副本照常工作。已退出时是空操作。
109
109
  */
110
110
  kill(index: number): Promise<void>;
111
- /** 停两个副本(15s 后 SIGKILL)、删临时库、关自有容器;幂等。 */
111
+ /**
112
+ * Stops replica `index` gracefully, through the kernel's own shutdown (as `stop()` does for all of
113
+ * them), and waits for it to exit; the other replicas keep working. A stop stuck for 10 s ends
114
+ * with the replica's own forced exit (code 1), and the harness SIGKILLs it after 15 s. Like after
115
+ * `kill`, `request()` keeps rotating to the stopped replica and requests to it throw. A no-op
116
+ * when it already exited.
117
+ */
118
+ stopReplica(index: number): Promise<void>;
119
+ /**
120
+ * 停两个副本(15s 后 SIGKILL)、删临时库、关自有容器;幂等。Before the replicas stop it asserts
121
+ * that they left no queued run without its job (neither in the outbox nor in BullMQ: the "queue
122
+ * lost jobs" canary of the kernel's run-orphan-check, transactional outbox spec §11); after the
123
+ * cleanup it rejects naming such runs, or with the check's own error. A database or Redis it
124
+ * cannot reach skips the check.
125
+ */
112
126
  stop(): Promise<void>;
113
127
  }
114
128
  /**
@@ -3,6 +3,7 @@ import { randomBytes } from "node:crypto";
3
3
  import { createRequire } from "node:module";
4
4
  import { extname, resolve } from "node:path";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
6
+ import { Redis } from "ioredis";
6
7
  import { createFreshDatabase, sharedPgAdminUrl, startPostgresContainer, startTestRedis, } from "./containers.js";
7
8
  /** 副本在响应头里标明自己的序号(runner 把 `http.replicaId` 设为 `"0"` / `"1"`)。 */
8
9
  export const REPLICA_HEADER = "x-capybara-replica";
@@ -20,6 +21,41 @@ const ALL_ROLES = ["api", "worker", "gateway"];
20
21
  const STOP_TIMEOUT_MS = 15_000;
21
22
  const START_TIMEOUT_MS = 60_000;
22
23
  const STDERR_TAIL = 4000;
24
+ /**
25
+ * The queued runs of the harness's database whose job is neither in the outbox nor in BullMQ (the
26
+ * kernel's `queuedRunsWithoutJob`; a BullMQ job is the hash `bull:<queue>:<jobId>`). Null only when
27
+ * the database or Redis cannot be reached (a test that stopped them: the check is skipped); any
28
+ * other error is thrown.
29
+ */
30
+ async function queuedOrphansOf(dbUrl, redisUrl) {
31
+ // loaded here, not at the top: a process that only spawns replicas (or is killed) never needs
32
+ // the kernel in its own module graph
33
+ const { createDb, kernelDb, queuedRunsWithoutJob } = await import("@capybara-hq/kernel");
34
+ const { sql } = await import("kysely");
35
+ const raw = createDb(dbUrl, 1, () => { }, { connectTimeoutMs: 5000 });
36
+ const redis = new Redis(redisUrl, {
37
+ lazyConnect: true,
38
+ connectTimeout: 5000,
39
+ maxRetriesPerRequest: 1,
40
+ retryStrategy: () => null,
41
+ });
42
+ redis.on("error", () => { });
43
+ try {
44
+ try {
45
+ await redis.connect();
46
+ await sql `SELECT 1`.execute(raw);
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ const found = await queuedRunsWithoutJob(kernelDb(raw), async (queue, jobId) => (await redis.exists(`bull:${queue}:${jobId}`)) === 1, { minAgeMs: 0 });
52
+ return found.map((c) => `${c.runId} (conversation ${c.conversationId}, job ${c.jobId})`);
53
+ }
54
+ finally {
55
+ redis.disconnect();
56
+ await raw.destroy().catch(() => { });
57
+ }
58
+ }
23
59
  /** runner 与本文件同目录;源码下是 .ts,编译后是 .js。 */
24
60
  const runnerPath = fileURLToPath(new URL(`./replica-runner${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
25
61
  /**
@@ -120,6 +156,8 @@ export async function createDualReplicaHarness(opts) {
120
156
  const runners = [];
121
157
  let dropDb;
122
158
  let stopPromise;
159
+ /** Set once both replicas started: `stop()` then checks for queued runs without a job. */
160
+ let checkOrphans;
123
161
  const stopRunner = async (r) => {
124
162
  if (r.child.exitCode !== null || r.child.signalCode !== null)
125
163
  return;
@@ -138,9 +176,18 @@ export async function createDualReplicaHarness(opts) {
138
176
  };
139
177
  const stop = () => {
140
178
  stopPromise ??= (async () => {
179
+ const checked = await checkOrphans?.().then((orphans) => ({ orphans }), (error) => ({ error }));
141
180
  await Promise.allSettled(runners.map(stopRunner));
142
181
  await Promise.allSettled([dropDb?.()]);
143
182
  await Promise.allSettled(owned.map((c) => c.stop()));
183
+ if (checked && "error" in checked)
184
+ throw checked.error;
185
+ const orphans = checked?.orphans ?? null;
186
+ if (orphans !== null && orphans.length > 0) {
187
+ throw new Error(`the replicas left ${orphans.length} queued run(s) without a job (neither owed by the ` +
188
+ `outbox nor in BullMQ; the run-orphan-check would report "the queue lost jobs"): ` +
189
+ orphans.join(", "));
190
+ }
144
191
  })();
145
192
  return stopPromise;
146
193
  };
@@ -216,6 +263,7 @@ export async function createDualReplicaHarness(opts) {
216
263
  };
217
264
  let calls = 0;
218
265
  let extraChain = Promise.resolve();
266
+ checkOrphans = () => queuedOrphansOf(db.url, redisUrl);
219
267
  const kill = async (index) => {
220
268
  const { runner: r } = runnerAt(index);
221
269
  if (r.child.exitCode === null && r.child.signalCode === null)
@@ -228,6 +276,7 @@ export async function createDualReplicaHarness(opts) {
228
276
  redisUrl,
229
277
  stop,
230
278
  kill,
279
+ stopReplica: (index) => stopRunner(runnerAt(index).runner),
231
280
  startExtraReplica(extraRoles) {
232
281
  // Extra starts run one at a time: the index is the next free slot when the start begins,
233
282
  // and a failed start appends nothing, so there are never holes in the replica indexes
@@ -11,6 +11,9 @@ import type { CardAction, ChannelTarget, DirectoryMember, InboundEvent, Outbound
11
11
  * `code_challenge`(S256)的,换 token 必须带对应的 `codeVerifier`,否则 `invalid_grant`。
12
12
  * - **通讯录**:`GET /d/<key>/members?cursor=<n>` 按页返回 {@link FakeChannelServer.book} 的成员,可让某页失败、让第一页挂起。
13
13
  * - **其他写操作**:`POST /posts` 记下插件工具发的「公告」(`posts`),供断言工具确实执行(且只执行一次)。
14
+ * - **Setup checks**: `POST /checks` records each call of a `fake-im` setup check (`checks`), so a
15
+ * test can count third-party calls across replicas; {@link FakeChannelServer.holdChecks} makes
16
+ * the answers wait (a slow platform API).
14
17
  *
15
18
  * - **Webhook** (the platform calling the kernel): {@link signFakeWebhook} signs a body with HMAC-SHA256
16
19
  * for the `x-fake-signature` header; {@link fakeWebhookEvents} / {@link fakeWebhookChallenge} build bodies.
@@ -40,7 +43,22 @@ export interface FakeChannelSent {
40
43
  pid: number;
41
44
  /** 内核给的幂等键(`ChannelSendArgs.idempotencyKey`)。 */
42
45
  idempotencyKey?: string;
43
- /** 内核给的组织语言(`ChannelSendArgs.locale`)。 */
46
+ /** The language the kernel gave (`ChannelSendArgs.locale`: the recipient's, else the org's). */
47
+ locale?: "zh" | "en";
48
+ at: number;
49
+ }
50
+ /** A file the bot uploaded (`POST /send-file`). */
51
+ export interface FakeChannelSentFile {
52
+ appId: string;
53
+ target: ChannelTarget;
54
+ name: string;
55
+ contentType: string;
56
+ kind: "image" | "file";
57
+ data: Buffer;
58
+ sha256: string;
59
+ messageId: string;
60
+ pid: number;
61
+ idempotencyKey?: string;
44
62
  locale?: "zh" | "en";
45
63
  at: number;
46
64
  }
@@ -71,6 +89,21 @@ export interface FakeDirectoryBook {
71
89
  /** 整轮同步开始的次数(不带游标的请求数)。 */
72
90
  starts(): number;
73
91
  }
92
+ /** Which `/send`, `/update` or `/send-file` requests a {@link FakeChannelServer.failNext} failure applies to. */
93
+ export interface FakeChannelFailMatch {
94
+ chatId?: string;
95
+ /** The message's text (for `/send-file`: the file name) contains it. */
96
+ textIncludes?: string;
97
+ }
98
+ /** A `fake-im` setup check's call of `POST /checks`. */
99
+ export interface FakeChannelCheckCall {
100
+ /** The check id. */
101
+ check: string;
102
+ connectionId: string;
103
+ /** The process (replica) that made it (`x-pid`). */
104
+ pid: number;
105
+ at: number;
106
+ }
74
107
  /** 插件工具经 `POST /posts` 发出的一条记录。 */
75
108
  export interface FakeChannelPost {
76
109
  body: Record<string, unknown>;
@@ -93,23 +126,34 @@ export interface FakeChannelServer {
93
126
  updated: FakeChannelSent[];
94
127
  /** 命中幂等键、被平台去重的发送请求(没有产生新消息)。 */
95
128
  duplicateSends: FakeChannelSent[];
129
+ /** Files the bot uploaded (`/send-file`), after dedupe. */
130
+ sentFiles: FakeChannelSentFile[];
131
+ /** `/send-file` requests that hit an idempotency key already seen (no new message). */
132
+ duplicateFiles: FakeChannelSentFile[];
96
133
  /** 插件工具发的公告。 */
97
134
  posts: FakeChannelPost[];
135
+ /** Calls of `fake-im` setup checks (`POST /checks`). */
136
+ checks: FakeChannelCheckCall[];
137
+ /** `POST /checks` answers only once `hold` resolves (null: at once). */
138
+ holdChecks(hold: Promise<void> | null): void;
98
139
  /** 平台用户(OAuth 登录用),按 externalId 索引。 */
99
140
  users: Map<string, FakeChannelUser>;
100
141
  /**
101
142
  * 让接下来 `count` 次 `/send`(或 `/update`)返回该状态码(不记录);`retryAfterMs` 与 `reason` 放进响应体,
102
143
  * 测试插件据此抛 `ChannelSendError`(429 / 5xx 可重试,带等待时长;其他不可重试,带失败原因)。
103
144
  * `delayMs`:失败响应推迟这么久才返回(模拟慢的失败请求,让会话的后续事件在投递任务持锁期间到达)。
145
+ * `match`: only matching requests count and fail; a string is a chat id, an object also matches
146
+ * text (`textIncludes`: the message's text contains it). Without it the next requests to any chat
147
+ * fail, so a late delivery from an earlier test can take the failure meant for the request under test.
104
148
  */
105
- failNext(path: "/send" | "/update", status: number, count?: number, retryAfterMs?: number, reason?: "auth" | "target_gone" | "rejected" | "too_large", delayMs?: number): void;
149
+ failNext(path: "/send" | "/update" | "/send-file", status: number, count?: number, retryAfterMs?: number, reason?: "auth" | "target_gone" | "rejected" | "too_large", delayMs?: number, match?: string | FakeChannelFailMatch): void;
106
150
  /**
107
151
  * Delay the response of the next `count` successful `/send` (or `/update`) requests by `delayMs`.
108
152
  * The message is recorded (visible in `sent` / `updated`) as soon as the request arrives; only the
109
153
  * response carrying its `messageId` is late (a slow platform API, or a sender that dies mid-call).
110
154
  * `onlyCards`: count and delay only requests whose message carries cards.
111
155
  */
112
- delayNext(path: "/send" | "/update", delayMs: number, opts?: {
156
+ delayNext(path: "/send" | "/update" | "/send-file", delayMs: number, opts?: {
113
157
  count?: number;
114
158
  onlyCards?: boolean;
115
159
  }): void;
@@ -135,6 +179,10 @@ export declare function startFakeChannelServer(opts?: FakeChannelServerOptions):
135
179
  export interface FakeSenderProfile {
136
180
  displayName?: string;
137
181
  avatarUrl?: string;
182
+ /** The sender's IANA time zone on the platform (channel@1 `sender.timeZone`). */
183
+ timeZone?: string;
184
+ /** The sender's language tag on the platform (channel@1 `sender.locale`). */
185
+ locale?: string;
138
186
  }
139
187
  /** 私聊文本消息(chat id 为 `dm-<externalId>`);`profile` 给了就带上发言人的显示名 / 头像。 */
140
188
  export declare function fakeDm(messageId: string, externalId: string, text: string, tenantId?: string, profile?: FakeSenderProfile): InboundEvent;
@@ -20,11 +20,16 @@ export async function startFakeChannelServer(opts = {}) {
20
20
  const sent = [];
21
21
  const updated = [];
22
22
  const duplicateSends = [];
23
+ const sentFiles = [];
24
+ const duplicateFiles = [];
23
25
  const posts = [];
26
+ const checks = [];
27
+ let checkHold = null;
24
28
  const users = new Map();
25
29
  const books = new Map();
26
30
  const codes = new Map();
27
31
  const byKey = new Map();
32
+ const fileByKey = new Map();
28
33
  const failures = [];
29
34
  const delays = [];
30
35
  const live = new Map();
@@ -61,7 +66,12 @@ export async function startFakeChannelServer(opts = {}) {
61
66
  };
62
67
  const sendOrUpdate = async (req, res, path) => {
63
68
  const body = await readBody(req);
64
- const f = failures.find((x) => x.path === path && x.left > 0);
69
+ const parsed = JSON.parse(body);
70
+ const matches = (m) => m === undefined ||
71
+ ((m.chatId === undefined || m.chatId === parsed.target?.chatId) &&
72
+ (m.textIncludes === undefined ||
73
+ (parsed.message?.text ?? parsed.file?.name ?? "").includes(m.textIncludes)));
74
+ const f = failures.find((x) => x.path === path && x.left > 0 && matches(x.match));
65
75
  if (f) {
66
76
  f.left--;
67
77
  if (f.delayMs !== undefined)
@@ -69,6 +79,41 @@ export async function startFakeChannelServer(opts = {}) {
69
79
  json(res, f.status, { retryAfterMs: f.retryAfterMs ?? null, reason: f.reason ?? null });
70
80
  return;
71
81
  }
82
+ if (path === "/send-file") {
83
+ const fb = JSON.parse(body);
84
+ const data = Buffer.from(fb.file.data, "base64");
85
+ const fkey = fb.idempotencyKey ? `${fb.appId}\u0000${fb.idempotencyKey}` : undefined;
86
+ const fseen = fkey !== undefined ? fileByKey.get(fkey) : undefined;
87
+ const fid = fseen ?? `of_${++seq}`;
88
+ const frec = {
89
+ appId: fb.appId,
90
+ target: fb.target,
91
+ name: fb.file.name,
92
+ contentType: fb.file.contentType,
93
+ kind: fb.file.kind,
94
+ data,
95
+ sha256: createHash("sha256").update(data).digest("hex"),
96
+ messageId: fid,
97
+ pid: pidOf(req),
98
+ ...(fb.idempotencyKey !== undefined && { idempotencyKey: fb.idempotencyKey }),
99
+ ...(fb.locale !== undefined && { locale: fb.locale }),
100
+ at: Date.now(),
101
+ };
102
+ if (fseen !== undefined && dedupe)
103
+ duplicateFiles.push(frec);
104
+ else {
105
+ sentFiles.push(frec);
106
+ if (fkey !== undefined && fseen === undefined)
107
+ fileByKey.set(fkey, fid);
108
+ }
109
+ const fd = delays.find((x) => x.path === path && x.left > 0);
110
+ if (fd) {
111
+ fd.left--;
112
+ await new Promise((r) => setTimeout(r, fd.delayMs));
113
+ }
114
+ json(res, 200, { messageId: fid });
115
+ return;
116
+ }
72
117
  const b = JSON.parse(body);
73
118
  const key = b.idempotencyKey ? `${b.appId}\u0000${b.idempotencyKey}` : undefined;
74
119
  const seen = path === "/send" && key !== undefined ? byKey.get(key) : undefined;
@@ -159,7 +204,7 @@ export async function startFakeChannelServer(opts = {}) {
159
204
  const route = `${req.method} ${u.pathname}`;
160
205
  if (route === "GET /connect")
161
206
  return connect(req, res, u);
162
- if (route === "POST /send" || route === "POST /update") {
207
+ if (route === "POST /send" || route === "POST /update" || route === "POST /send-file") {
163
208
  return sendOrUpdate(req, res, u.pathname);
164
209
  }
165
210
  if (route === "POST /bot/verify") {
@@ -173,6 +218,18 @@ export async function startFakeChannelServer(opts = {}) {
173
218
  tenantId: b.tenant ?? "t1",
174
219
  });
175
220
  }
221
+ if (route === "POST /checks") {
222
+ const b = JSON.parse((await readBody(req)) || "{}");
223
+ checks.push({
224
+ check: String(b.check ?? ""),
225
+ connectionId: String(b.connectionId ?? ""),
226
+ pid: pidOf(req),
227
+ at: Date.now(),
228
+ });
229
+ if (checkHold)
230
+ await checkHold;
231
+ return json(res, 200, { ok: true });
232
+ }
176
233
  if (route === "GET /oauth/authorize")
177
234
  return authorize(res, u);
178
235
  if (route === "POST /oauth/token")
@@ -201,9 +258,15 @@ export async function startFakeChannelServer(opts = {}) {
201
258
  sent,
202
259
  updated,
203
260
  duplicateSends,
261
+ sentFiles,
262
+ duplicateFiles,
204
263
  posts,
264
+ checks,
265
+ holdChecks(hold) {
266
+ checkHold = hold;
267
+ },
205
268
  users,
206
- failNext(path, status, count = 1, retryAfterMs, reason, delayMs) {
269
+ failNext(path, status, count = 1, retryAfterMs, reason, delayMs, match) {
207
270
  failures.push({
208
271
  path,
209
272
  status,
@@ -211,6 +274,9 @@ export async function startFakeChannelServer(opts = {}) {
211
274
  ...(retryAfterMs !== undefined && { retryAfterMs }),
212
275
  ...(reason !== undefined && { reason }),
213
276
  ...(delayMs !== undefined && { delayMs }),
277
+ ...(match !== undefined && {
278
+ match: typeof match === "string" ? { chatId: match } : match,
279
+ }),
214
280
  });
215
281
  },
216
282
  delayNext(path, delayMs, opts = {}) {
@@ -261,6 +327,8 @@ const senderOf = (externalId, tenantId, profile = {}) => ({
261
327
  tenantId,
262
328
  ...(profile.displayName !== undefined && { displayName: profile.displayName }),
263
329
  ...(profile.avatarUrl !== undefined && { avatarUrl: profile.avatarUrl }),
330
+ ...(profile.timeZone !== undefined && { timeZone: profile.timeZone }),
331
+ ...(profile.locale !== undefined && { locale: profile.locale }),
264
332
  });
265
333
  /** 私聊文本消息(chat id 为 `dm-<externalId>`);`profile` 给了就带上发言人的显示名 / 头像。 */
266
334
  export function fakeDm(messageId, externalId, text, tenantId = "t1", profile) {
@@ -19,6 +19,21 @@
19
19
  * 本机只有一个用户,权限隔离测不了,测试改为核对请求里的用户)。进程以新会话启动(与 setsid 等价),
20
20
  * 客户端断开**不会**结束进程(与 envd 一致),只有 SendSignal、杀进程脚本或删沙箱才会。
21
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
+ *
22
37
  * `connect` 带 `memory: false`(SDK 的 `onResume: "reboot"`)时结束该沙箱的全部进程(冷启动)。
23
38
  * SendSignal 只杀指定进程(不是进程组)。
24
39
  *
@@ -32,6 +47,19 @@ export interface FakeE2BOptions {
32
47
  pageSize?: number;
33
48
  /** create / connect 返回的沙箱 `domain`(默认 null,即用客户端配置的域名)。 */
34
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;
35
63
  }
36
64
  export interface FakeE2BSandbox {
37
65
  id: string;
@@ -41,6 +69,8 @@ export interface FakeE2BSandbox {
41
69
  /** 当前的超时(秒):建沙箱时给的,connect 只会把它调大。 */
42
70
  timeout: number;
43
71
  autoPause: boolean;
72
+ /** Whether the last pause kept memory (`pause` body `memory` is not false). */
73
+ pausedWithMemory?: boolean;
44
74
  /** 建沙箱请求体里的出站设置(原样记录)。 */
45
75
  allowInternetAccess?: boolean;
46
76
  network?: unknown;
@@ -71,6 +101,8 @@ export interface FakeE2BServer {
71
101
  url: string;
72
102
  apiKey: string;
73
103
  sandboxes: Map<string, FakeE2BSandbox>;
104
+ /** Templates by alias. */
105
+ templates: Map<string, FakeE2BTemplate>;
74
106
  calls: FakeE2BCall[];
75
107
  /**
76
108
  * 下一个匹配的请求回 `status`:默认 E2B 的错误格式 JSON `{code: status, message}`;`raw` 时回纯文本
@@ -90,6 +122,8 @@ export interface FakeE2BServer {
90
122
  withholdAccessToken: boolean;
91
123
  /** 沙箱直接消失(杀掉它的进程、删掉根目录)。 */
92
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>;
93
127
  /** 沙箱内路径在本机上的位置。 */
94
128
  hostPath(id: string, sandboxPath: string): string;
95
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)