@capybara-hq/testing 0.1.0-rc.2 → 0.1.0-rc.21

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 (74) hide show
  1. package/dist/containers.d.ts +7 -2
  2. package/dist/containers.js +7 -3
  3. package/dist/dual-replica.d.ts +11 -2
  4. package/dist/dual-replica.js +48 -0
  5. package/dist/fake-channel.d.ts +31 -2
  6. package/dist/fake-channel.js +29 -2
  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-oauth-server.d.ts +16 -2
  12. package/dist/fake-oauth-server.js +21 -1
  13. package/dist/fake-telegram.d.ts +165 -0
  14. package/dist/fake-telegram.js +569 -0
  15. package/dist/fixtures.d.ts +21 -4
  16. package/dist/fixtures.js +30 -4
  17. package/dist/index.d.ts +8 -5
  18. package/dist/index.js +6 -3
  19. package/dist/kernel-helpers.d.ts +48 -16
  20. package/dist/kernel-helpers.js +73 -13
  21. package/dist/model-conformance.d.ts +11 -10
  22. package/dist/model-conformance.js +38 -14
  23. package/dist/replica-runner.js +16 -8
  24. package/dist/sandbox-native-conformance.d.ts +31 -0
  25. package/dist/sandbox-native-conformance.js +153 -0
  26. package/dist/sandbox-permission-conformance.d.ts +60 -0
  27. package/dist/sandbox-permission-conformance.js +486 -0
  28. package/fixtures/extensions/fake-client/.capybara-plugin/plugin.json +11 -0
  29. package/fixtures/extensions/fake-client/client/styles/fake.css +11 -0
  30. package/fixtures/extensions/fake-client/package.json +12 -0
  31. package/fixtures/extensions/fake-client/src/client.tsx +51 -0
  32. package/fixtures/extensions/fake-client/src/index.ts +43 -0
  33. package/fixtures/extensions/fake-client/themes/fake.json +11 -0
  34. package/fixtures/extensions/fake-client-broken/.capybara-plugin/plugin.json +7 -0
  35. package/fixtures/extensions/fake-client-broken/package.json +12 -0
  36. package/fixtures/extensions/fake-client-broken/src/client.tsx +22 -0
  37. package/fixtures/extensions/fake-client-broken/src/index.ts +27 -0
  38. package/fixtures/extensions/fake-config-form/.capybara-plugin/plugin.json +11 -0
  39. package/fixtures/extensions/fake-config-form/package.json +12 -0
  40. package/fixtures/extensions/fake-config-form/src/index.ts +205 -0
  41. package/fixtures/extensions/fake-context/.capybara-plugin/plugin.json +7 -0
  42. package/fixtures/extensions/fake-context/package.json +12 -0
  43. package/fixtures/extensions/fake-context/src/index.ts +81 -0
  44. package/fixtures/extensions/fake-dep-provider/src/index.ts +1 -1
  45. package/fixtures/extensions/fake-dep-requirer/src/index.ts +1 -1
  46. package/fixtures/extensions/fake-embed/src/index.ts +26 -26
  47. package/fixtures/extensions/fake-im/.capybara-plugin/plugin.json +7 -1
  48. package/fixtures/extensions/fake-im/guides/fake-im-app.md +32 -0
  49. package/fixtures/extensions/fake-im/guides/fake-im-app.zh.md +32 -0
  50. package/fixtures/extensions/fake-im/src/channel.ts +3 -1
  51. package/fixtures/extensions/fake-im/src/checks.ts +94 -0
  52. package/fixtures/extensions/fake-im/src/index.ts +36 -1
  53. package/fixtures/extensions/fake-lifecycle/.capybara-plugin/plugin.json +7 -0
  54. package/fixtures/extensions/fake-lifecycle/migrations/0001_init.sql +16 -0
  55. package/fixtures/extensions/fake-lifecycle/package.json +12 -0
  56. package/fixtures/extensions/fake-lifecycle/src/index.ts +72 -0
  57. package/fixtures/extensions/fake-storage-user/src/index.ts +1 -1
  58. package/fixtures/extensions/fake-tools-ui/skills/fake-notes/SKILL.md +1 -1
  59. package/fixtures/extensions/fake-tools-ui/src/index.ts +62 -3
  60. package/fixtures/extensions/fake-web/.capybara-plugin/plugin.json +7 -0
  61. package/fixtures/extensions/fake-web/package.json +12 -0
  62. package/fixtures/extensions/fake-web/src/index.ts +22 -0
  63. package/fixtures/extensions/fake-web/src/web.ts +183 -0
  64. package/fixtures/extensions/fake-web-2/.capybara-plugin/plugin.json +7 -0
  65. package/fixtures/extensions/fake-web-2/package.json +12 -0
  66. package/fixtures/extensions/fake-web-2/src/index.ts +16 -0
  67. package/fixtures/extensions/fake-web-2/src/web.ts +183 -0
  68. package/fixtures/plugins/fake-theme/.capybara-plugin/plugin.json +7 -0
  69. package/fixtures/plugins/fake-theme/fonts/FakeSans.woff2 +1 -0
  70. package/fixtures/plugins/fake-theme/logo.svg +1 -0
  71. package/fixtures/plugins/fake-theme/package.json +8 -0
  72. package/fixtures/plugins/fake-theme/themes/neon-grid.json +13 -0
  73. package/fixtures/plugins/fake-theme/themes/paper.json +12 -0
  74. package/package.json +6 -5
package/dist/fixtures.js CHANGED
@@ -13,13 +13,19 @@ import { fileURLToPath } from "node:url";
13
13
  * | `fake-connector` | `connector@1` kind `fake`: an MCP client for `startFakeMcpServer` (auth, one 401 retry, connectorData routes from `_meta["fake/route"]`, onToolsChanged, onElicit incl. `-32042`, resources, prompts, inspect); endpoint `{ url, headers?, notesText? }`; template `fake-demo`; deployment config `allowInsecureLoopback` (default true), `inspectAuth` (`bearer` / `api_key`), `kind` (default `fake`; `mcp` lets clients that know only the official kinds drive it) |
14
14
  * | `fake-openapi` | `connector@1` kind `openapi` (the web wizard's OpenAPI flow): reads a small JSON document (`securitySchemes` as auth hints, `operations` as tools) from the endpoint's `specUrl`, calls operations over HTTP with the injected auth; endpoint `{ specUrl, baseUrl?, operations? }`; deployment config `allowInsecureLoopback` (default true) |
15
15
  * | `fake-object-store` | `object-store@1` on the `startTestS3()` container (deployment config as `TestS3` gives it; POST-policy presign) |
16
- * | `fake-tools-ui` | tool `write`, view `tasks`, a migration, skill `fake-notes`, template `fake-notes` (for fake-connector); no storage |
16
+ * | `fake-tools-ui` | tools `write` and `web-only` (`sources` web and channel_dm; returns its call context), view `tasks`, a migration, skill `fake-notes`, template `fake-notes` (for fake-connector); no storage |
17
17
  * | `fake-storage-user` | tools `note` / `read_note` through `ctx.storage` (`permissions.storage`) |
18
+ * | `fake-lifecycle` | observes `org.member_removed`, `agent.deleted` and `org.deleted`; a migration with tables `calls` (every call) and `deliveries` (every call that succeeded), each row the mount and the payload; deployment config `failTimes` (default 0): the first `failTimes` calls of each (mount, payload) throw, and `label` (optional, at most 10 characters, overridable per org: an invalid org copy) |
18
19
  * | `fake-embed` | embeds `panel` (page) and `panel-conv` (conversation), static `/ui/panel.js`, token-checked routes, SSE over `ctx.bus` |
19
20
  * | `fake-bootstrap-a` | `model-provider@2` with a required secret `apiKey` (pending configuration until set) |
20
21
  * | `fake-bootstrap-b` | `object-store@1` kept in its own PG table; `bucket` + secret `secretKey` |
21
22
  * | `fake-dep-provider` / `fake-dep-requirer` | a dependency pair on `counter@1` (the requirer's plugin.json depends on the provider) |
22
23
  * | `fake-im` | a whole IM platform for `startFakeChannelServer`: `channel@1` (cards, edits, threads, webhook inbound), `identity-source@1`, `directory@1` (org config `url` of a directory book) and tool `post_announcement` (default policy ask, posts to the platform); deployment config `platformUrl`, `tenant`, `clientId`, secret `clientSecret`. Its `src/index.ts` also exports `makeFakeImChannel`, `fakeImIdentitySource`, `fakeImDirectory` for test extensions that need one part |
24
+ * | `fake-web` / `fake-web-2` | `web-search@1` and `web-fetch@1`, scripted by a prefix of the query or of the fetched URL's path (`error:<kind>`, `throw:`, `hang:`, `redirect:<url>`, `junk:`, `empty:`, `big:<n>`; see `makeFakeWeb`); results name the provider; org config secret `token`, `configured()` iff it is set (throws for `throw:configured`); calls recorded on `globalThis.__fakeWeb` (`fakeWebProbe`) |
25
+ * | `fake-context` | `context@1` scripted by its deployment config (`text`, default "fake context"; `mode` `ok` / `null` / `throw` / `hang`); calls recorded on `globalThis.__fakeContext` (`fakeContextProbe`); tool `note` (`sources` web and channel_dm) |
26
+ * | `fake-client` | client extension (`permissions.client`, no extension point): components `hud` (`conversation.properties.section`, server view with `data`), `brand` (`shell.brand`, renders `builtin` in `data-testid="fake-client-brand"`), `empty` (`conversation.empty`), `frame` (`conversation.composer.frame`) and `fx` (`shell.overlay`); `client/styles/fake.css` (outline-color on `button.primary` and the composer's buttons, `--cx-fake-client-run` while `run=running`); an `events` listener storing the last event type; theme `fake`; `suggestedAppearance` = theme `fake` + `shell.brand` -> `brand` |
27
+ * | `fake-client-broken` | client code that throws: component `boom` (render), a `run.started` events listener, and a `conversation.empty` replacement (render) |
28
+ * | `fake-config-form` | display name 表单样例 / Form sample; no extension point: an openai-compatible-shaped deployment config (endpoints with a preset menu, an API key per endpoint in the secret record `apiKeys`, model rows, advanced fields, localized custom issues) carrying the config form hints of the extension config forms spec §6, for the web form e2e |
23
29
  */
24
30
  export const FAKE_EXTENSIONS = [
25
31
  "fake-connector",
@@ -27,18 +33,36 @@ export const FAKE_EXTENSIONS = [
27
33
  "fake-object-store",
28
34
  "fake-tools-ui",
29
35
  "fake-storage-user",
36
+ "fake-lifecycle",
30
37
  "fake-embed",
31
38
  "fake-bootstrap-a",
32
39
  "fake-bootstrap-b",
33
40
  "fake-dep-provider",
34
41
  "fake-dep-requirer",
35
42
  "fake-im",
43
+ "fake-web",
44
+ "fake-web-2",
45
+ "fake-context",
46
+ "fake-config-form",
47
+ "fake-client",
48
+ "fake-client-broken",
36
49
  ];
50
+ /**
51
+ * Fake plugins without an extension (declarative: they live in `fixtures/plugins/<name>`, same
52
+ * pack layout).
53
+ *
54
+ * | name | provides / covers |
55
+ * |---|---|
56
+ * | `fake-theme` | themes `neon-grid` (dark only, wordmark, font `FakeSans`, logo) and `paper` (light and dark); passes `capybara-plugin check` |
57
+ */
58
+ export const FAKE_PLUGINS = ["fake-theme"];
37
59
  /** `fixtures/extensions/` of this package (same path from `src/` and from `dist/`). */
38
60
  const FIXTURES_DIR = fileURLToPath(new URL("../fixtures/extensions/", import.meta.url));
61
+ /** `fixtures/plugins/` of this package. */
62
+ const PLUGINS_DIR = fileURLToPath(new URL("../fixtures/plugins/", import.meta.url));
39
63
  /** The plugin directory of a fake (pack layout), for `packFixture` or a packer of your own. */
40
64
  export function fakeExtensionDir(name) {
41
- return join(FIXTURES_DIR, name);
65
+ return join(FAKE_PLUGINS.includes(name) ? PLUGINS_DIR : FIXTURES_DIR, name);
42
66
  }
43
67
  /**
44
68
  * The extension entry `src/index.ts` of a fake, for kernel configs that load extensions by path
@@ -84,8 +108,10 @@ async function packer() {
84
108
  * leaves no files in the fixture directory.
85
109
  */
86
110
  export async function packFixture(name, outDir) {
87
- if (!FAKE_EXTENSIONS.includes(name))
88
- throw new Error(`unknown fake extension ${String(name)}`);
111
+ const known = FAKE_EXTENSIONS.includes(name) ||
112
+ FAKE_PLUGINS.includes(name);
113
+ if (!known)
114
+ throw new Error(`unknown fake extension or plugin ${String(name)}`);
89
115
  const pack = await packer();
90
116
  const r = await pack(fakeExtensionDir(name), outDir);
91
117
  return { file: r.file, bytes: new Uint8Array(await readFile(r.file)), sha256: r.sha256 };
package/dist/index.d.ts CHANGED
@@ -3,13 +3,13 @@
3
3
  * package and the SDK: the database helpers and types, and model-visible texts, queue names and
4
4
  * keys the kernel owns (assert on them instead of copying their values).
5
5
  */
6
- export { type ConversationEvent, createDb, gatewayReplicasKey, type Kernel, type KernelConfig, type KernelDb, kernelDb, MAINTENANCE_QUEUE_NAME, runJobId, SANDBOX_LOCK_TTL_MS, SANDBOX_RECREATED_NOTICE, SANDBOX_STARTED_NOTICE, SANDBOX_SUSPEND_JOB, UNKNOWN_RESULT_TEXT, } from "@capybara-hq/kernel";
7
- export { createFreshDatabase, startTestPostgres, startTestRedis, startTestS3, TEST_S3_IMAGE, type TestContainer, type TestS3, } from "./containers.js";
6
+ export { type ConversationEvent, createDb, gatewayReplicasKey, type KernelConfig, type KernelSchemaDb, kernelDb, MAINTENANCE_QUEUE_NAME, runJobId, SANDBOX_LOCK_TTL_MS, SANDBOX_RESTARTED_NOTICE, SANDBOX_STARTED_NOTICE, SANDBOX_SUSPEND_JOB, UNKNOWN_RESULT_TEXT, } from "@capybara-hq/kernel";
7
+ export { createFreshDatabase, startPostgresContainer, startTestPostgres, startTestRedis, startTestS3, TEST_PG_IMAGE, TEST_S3_IMAGE, type TestContainer, type TestS3, } from "./containers.js";
8
8
  export { createDualReplicaHarness, type DualReplicaOptions, type ExtraReplicaHandle, type Harness, REPLICA_HEADER, type ReplicaHandle, type ReplicaResponse, replicaOf, } from "./dual-replica.js";
9
9
  export { assertExtensionSecretsReachable, extensionDeploymentSecretValues, } from "./extension-config.js";
10
- export { FAKE_CHANNEL_BAD_SECRET, FAKE_WEBHOOK_SIGNATURE_HEADER, type FakeChannelPost, type FakeChannelSent, type FakeChannelServer, type FakeChannelServerOptions, type FakeChannelStream, type FakeChannelUser, type FakeDirectoryBook, type FakeSenderProfile, fakeCardAction, fakeDirectoryMember, fakeDm, fakeGroupMessage, fakeWebhookChallenge, fakeWebhookEvents, signFakeWebhook, startFakeChannelServer, } from "./fake-channel.js";
10
+ export { FAKE_CHANNEL_BAD_SECRET, FAKE_WEBHOOK_SIGNATURE_HEADER, type FakeChannelCheckCall, type FakeChannelFailMatch, type FakeChannelPost, type FakeChannelSent, type FakeChannelServer, type FakeChannelServerOptions, type FakeChannelStream, type FakeChannelUser, type FakeDirectoryBook, type FakeSenderProfile, fakeCardAction, fakeDirectoryMember, fakeDm, fakeGroupMessage, fakeWebhookChallenge, fakeWebhookEvents, signFakeWebhook, startFakeChannelServer, } from "./fake-channel.js";
11
11
  export { type FakeE2BCall, type FakeE2BMatch, type FakeE2BOptions, type FakeE2BSandbox, type FakeE2BServer, startFakeE2B, } from "./fake-e2b.js";
12
- export { type FakeGitCommitOptions, type FakeGitRequest, type FakeGitServer, startFakeGitServer, } from "./fake-git-server.js";
12
+ export { type FakeGitCommitOptions, type FakeGitRequest, type FakeGitServer, type FakeGitServerOptions, startFakeGitServer, } from "./fake-git-server.js";
13
13
  export { encryptLarkWebhook, type FakeLarkAck, type FakeLarkApi, type FakeLarkButton, type FakeLarkCall, type FakeLarkDepartment, type FakeLarkFailure, type FakeLarkMessage, type FakeLarkOptions, type FakeLarkServer, type FakeLarkUser, findLarkButton, larkCardAction, larkMessageEvent, signLarkWebhook, startFakeLark, } from "./fake-lark.js";
14
14
  export { type FakeMarketplace, type FakeMarketplaceRequest, startFakeMarketplace, } from "./fake-marketplace.js";
15
15
  export { type FakeMcpCallInfo, type FakeMcpHandlerContext, type FakeMcpPrompt, type FakeMcpRequest, type FakeMcpResource, FakeMcpRpcError, type FakeMcpServer, type FakeMcpServerOptions, type FakeMcpTool, startFakeMcpServer, } from "./fake-mcp-server.js";
@@ -18,8 +18,11 @@ export { type FakeNpmPackage, type FakeNpmRegistry, npmProvenanceAttestations, s
18
18
  export { type FakeOAuthClient, type FakeOAuthServer, type FakeOAuthServerOptions, type FakeTokenRequest, startFakeOAuthServer, } from "./fake-oauth-server.js";
19
19
  export { defaultFakeOpenApiSpec, type FakeOpenApiRequest, type FakeOpenApiServer, type FakeOpenApiServerOptions, type FakePet, startFakeOpenApiServer, } from "./fake-openapi-server.js";
20
20
  export { type FakeSlackAck, type FakeSlackCall, type FakeSlackFailure, type FakeSlackMessage, type FakeSlackOptions, type FakeSlackServer, type FakeSlackUser, findSlackButton, signSlackWebhook, slackBlockAction, slackDmEvent, slackEventCallback, slackInteractiveForm, slackMentionEvent, startFakeSlack, } from "./fake-slack.js";
21
+ export { type FakeTelegramBot, type FakeTelegramCall, type FakeTelegramFailure, type FakeTelegramMessage, type FakeTelegramOptions, type FakeTelegramServer, findTelegramButton, startFakeTelegram, type TgChat, type TgUser, telegramCallback, telegramGroupMessage, telegramPrivateMessage, telegramWebhookHeaders, } from "./fake-telegram.js";
21
22
  export { FAKE_EXTENSIONS, type FakeExtensionName, fakeExtensionDir, fakeExtensionEntry, type PackedFixture, packFixture, } from "./fixtures.js";
22
- export { cardRecorded, cookieRequest, createAgent, createConversation, createLocalAccount, createOrg, eventsOf, joinOrg, type KernelRequest, type KernelRequestOptions, type KernelResponse, login, pidOwningLocalPort, postMessage, sleep, startTestKernel, TEST_PASSWORD, testKernelConfig, truncateTables, waitFor, waitForEvent, waitForTerminal, } from "./kernel-helpers.js";
23
+ export { cardRecorded, cookieRequest, createAgent, createConversation, createLocalAccount, createOrg, enableModelProviders, eventsOf, joinOrg, type KernelApp, type KernelRequest, type KernelRequestOptions, type KernelResponse, login, pidOwningLocalPort, postMessage, sleep, startTestKernel, TEST_PASSWORD, type TestKernel, testKernelConfig, truncateTables, waitFor, waitForEvent, waitForTerminal, } from "./kernel-helpers.js";
23
24
  export { isPngBase64, pdfBase64, pdfSampleWord, redPngBase64, solidPngBase64, } from "./media-samples.js";
24
25
  export { type ConformanceTarget, checkDeclaredParameters, describeModelProviderConformance, MEDIA_SAMPLES, thinkingReplayParams, } from "./model-conformance.js";
26
+ export { type NativeFixtureEntry, runSandboxNativeConformance, type SandboxNativeFixture, } from "./sandbox-native-conformance.js";
27
+ export { runSandboxPermissionConformance, type SandboxPermissionEndpoint, type SandboxPermissionFixture, type SandboxPermissionGrant, } from "./sandbox-permission-conformance.js";
25
28
  export { openSse, type SseClient, type SseMessage } from "./sse.js";
package/dist/index.js CHANGED
@@ -3,8 +3,8 @@
3
3
  * package and the SDK: the database helpers and types, and model-visible texts, queue names and
4
4
  * keys the kernel owns (assert on them instead of copying their values).
5
5
  */
6
- export { createDb, gatewayReplicasKey, kernelDb, MAINTENANCE_QUEUE_NAME, runJobId, SANDBOX_LOCK_TTL_MS, SANDBOX_RECREATED_NOTICE, SANDBOX_STARTED_NOTICE, SANDBOX_SUSPEND_JOB, UNKNOWN_RESULT_TEXT, } from "@capybara-hq/kernel";
7
- export { createFreshDatabase, startTestPostgres, startTestRedis, startTestS3, TEST_S3_IMAGE, } from "./containers.js";
6
+ export { createDb, gatewayReplicasKey, kernelDb, MAINTENANCE_QUEUE_NAME, runJobId, SANDBOX_LOCK_TTL_MS, SANDBOX_RESTARTED_NOTICE, SANDBOX_STARTED_NOTICE, SANDBOX_SUSPEND_JOB, UNKNOWN_RESULT_TEXT, } from "@capybara-hq/kernel";
7
+ export { createFreshDatabase, startPostgresContainer, startTestPostgres, startTestRedis, startTestS3, TEST_PG_IMAGE, TEST_S3_IMAGE, } from "./containers.js";
8
8
  export { createDualReplicaHarness, REPLICA_HEADER, replicaOf, } from "./dual-replica.js";
9
9
  export { assertExtensionSecretsReachable, extensionDeploymentSecretValues, } from "./extension-config.js";
10
10
  export { FAKE_CHANNEL_BAD_SECRET, FAKE_WEBHOOK_SIGNATURE_HEADER, fakeCardAction, fakeDirectoryMember, fakeDm, fakeGroupMessage, fakeWebhookChallenge, fakeWebhookEvents, signFakeWebhook, startFakeChannelServer, } from "./fake-channel.js";
@@ -18,8 +18,11 @@ export { npmProvenanceAttestations, startFakeNpmRegistry, } from "./fake-npm-reg
18
18
  export { startFakeOAuthServer, } from "./fake-oauth-server.js";
19
19
  export { defaultFakeOpenApiSpec, startFakeOpenApiServer, } from "./fake-openapi-server.js";
20
20
  export { findSlackButton, signSlackWebhook, slackBlockAction, slackDmEvent, slackEventCallback, slackInteractiveForm, slackMentionEvent, startFakeSlack, } from "./fake-slack.js";
21
+ export { findTelegramButton, startFakeTelegram, telegramCallback, telegramGroupMessage, telegramPrivateMessage, telegramWebhookHeaders, } from "./fake-telegram.js";
21
22
  export { FAKE_EXTENSIONS, fakeExtensionDir, fakeExtensionEntry, packFixture, } from "./fixtures.js";
22
- export { cardRecorded, cookieRequest, createAgent, createConversation, createLocalAccount, createOrg, eventsOf, joinOrg, login, pidOwningLocalPort, postMessage, sleep, startTestKernel, TEST_PASSWORD, testKernelConfig, truncateTables, waitFor, waitForEvent, waitForTerminal, } from "./kernel-helpers.js";
23
+ export { cardRecorded, cookieRequest, createAgent, createConversation, createLocalAccount, createOrg, enableModelProviders, eventsOf, joinOrg, login, pidOwningLocalPort, postMessage, sleep, startTestKernel, TEST_PASSWORD, testKernelConfig, truncateTables, waitFor, waitForEvent, waitForTerminal, } from "./kernel-helpers.js";
23
24
  export { isPngBase64, pdfBase64, pdfSampleWord, redPngBase64, solidPngBase64, } from "./media-samples.js";
24
25
  export { checkDeclaredParameters, describeModelProviderConformance, MEDIA_SAMPLES, thinkingReplayParams, } from "./model-conformance.js";
26
+ export { runSandboxNativeConformance, } from "./sandbox-native-conformance.js";
27
+ export { runSandboxPermissionConformance, } from "./sandbox-permission-conformance.js";
25
28
  export { openSse } from "./sse.js";
@@ -1,4 +1,4 @@
1
- import { type ConversationEvent, type Kernel, type KernelConfig, type KernelDb, type KernelHttp, type LogLevel } from "@capybara-hq/kernel";
1
+ import { type ConversationEvent, type KernelConfig, type KernelHttp, type KernelSchemaDb, type LogLevel, startKernelApp } from "@capybara-hq/kernel";
2
2
  import { type Kysely } from "kysely";
3
3
  /**
4
4
  * Helpers for extension tests that run a real kernel: in process (`startTestKernel` +
@@ -33,11 +33,32 @@ export declare function testKernelConfig(urls: {
33
33
  * it before creating anything.
34
34
  */
35
35
  export declare function assertOfflineOfficialMarketplace(config: KernelConfig, allow?: boolean): void;
36
+ /** The kernel's Nest application (what `createKernelApp` / `startKernelApp` return). */
37
+ export type KernelApp = Awaited<ReturnType<typeof startKernelApp>>;
38
+ /** A running in-process kernel ({@link startTestKernel}). */
39
+ export interface TestKernel {
40
+ /**
41
+ * The kernel's Nest application. Core's own tests reach a kernel service with `app.get(Class)`;
42
+ * a plugin test cannot import kernel classes (`plugin-test-imports`), so it drives the kernel
43
+ * through `http` and the helpers of this package.
44
+ */
45
+ readonly app: KernelApp;
46
+ /** In-process HTTP: `inject` requests, list the routes. */
47
+ readonly http: KernelHttp;
48
+ /**
49
+ * The port the kernel listens on (an ephemeral one with `http.port: 0`); undefined after
50
+ * `close()`.
51
+ */
52
+ readonly port: number | undefined;
53
+ /** Stops the kernel (the stop phases within their budgets, then Redis and the pool); idempotent. */
54
+ close(): Promise<void>;
55
+ }
36
56
  /**
37
- * Creates and starts an in-process kernel. Logs are discarded unless `log` is given (JSON lines at
38
- * `log.level` and above go to `log.write`, e.g. to assert a secret never reaches the log).
39
- * Extensions named by package resolve from `resolveFrom` (default `process.cwd()`). Stop it with
40
- * `stop()`.
57
+ * Creates and starts an in-process kernel (`startKernelApp`; it listens on `config.http.port`).
58
+ * The kernel gets no process-wide signal handlers: a test stops it with `close()`. Logs are
59
+ * discarded unless `log` is given (JSON lines at `log.level` and above go to `log.write`, e.g. to
60
+ * assert a secret never reaches the log). Extensions named by package resolve from `resolveFrom`
61
+ * (default `process.cwd()`).
41
62
  */
42
63
  export declare function startTestKernel(config: KernelConfig, opts?: {
43
64
  resolveFrom?: string;
@@ -47,7 +68,7 @@ export declare function startTestKernel(config: KernelConfig, opts?: {
47
68
  };
48
69
  /** Only for a test about the real default: allow the official marketplace at its real URL. */
49
70
  allowOfficialMarketplace?: boolean;
50
- }): Promise<Kernel>;
71
+ }): Promise<TestKernel>;
51
72
  /** Options of a {@link KernelRequest} call (`http.inject` options; `csrf: false` drops the header). */
52
73
  export type KernelRequestOptions = Parameters<KernelHttp["inject"]>[0] & {
53
74
  csrf?: boolean;
@@ -61,46 +82,57 @@ export type KernelRequest = (opts: KernelRequestOptions) => Promise<KernelRespon
61
82
  /** A request function with its own cookie jar (signed out until a response sets cookies). */
62
83
  export declare function cookieRequest(http: KernelHttp): KernelRequest;
63
84
  /** Creates a local account with {@link TEST_PASSWORD}; returns its id. */
64
- export declare function createLocalAccount(db: KernelDb, login: string, displayName?: string): Promise<string>;
85
+ export declare function createLocalAccount(db: KernelSchemaDb, login: string, displayName?: string): Promise<string>;
65
86
  /** Signs in over HTTP and returns the user's request function. */
66
- export declare function login(k: Pick<Kernel, "http">, name: string, password?: string): Promise<KernelRequest>;
87
+ export declare function login(k: Pick<TestKernel, "http">, name: string, password?: string): Promise<KernelRequest>;
67
88
  /** Creates an org as `req`'s user (who becomes its owner); returns its id. */
68
89
  export declare function createOrg(req: KernelRequest, name?: string): Promise<string>;
90
+ /**
91
+ * Switches on in `orgId`, through the org's extension switch (`PUT
92
+ * /api/v1/orgs/:orgId/extensions/:name`; `req` is an org admin), every model provider the kernel
93
+ * loaded that is not on there yet, and returns their names. A model provider is on only in the
94
+ * orgs that enabled it (like every other extension), so a test that saves or runs an agent in a
95
+ * new org calls this first; `only` limits it to those providers.
96
+ */
97
+ export declare function enableModelProviders(req: KernelRequest, orgId: string, only?: readonly string[]): Promise<string[]>;
69
98
  /**
70
99
  * A new account joins the org through an invitation (created by `owner`, accepted with `login`
71
100
  * and {@link TEST_PASSWORD}); returns the account id and its signed-in request function.
72
101
  */
73
- export declare function joinOrg(k: Pick<Kernel, "http">, owner: KernelRequest, orgId: string, name: string, role?: "member" | "admin"): Promise<{
102
+ export declare function joinOrg(k: Pick<TestKernel, "http">, owner: KernelRequest, orgId: string, name: string, role?: "member" | "admin"): Promise<{
74
103
  accountId: string;
75
104
  req: KernelRequest;
76
105
  }>;
77
106
  /**
78
- * Creates an org-visible agent; returns its id. Without `tools` the agent has none (model-fake then
79
- * answers ordinary messages instead of calling the first tool).
107
+ * Creates an org-visible agent; returns its id. An agent has every tool the org offers unless
108
+ * `disabledTools` turns it off (tools default-on spec), and every skill on in the org unless
109
+ * `disabledSkills` turns it off (skills default-on spec); with several tools model-fake answers
110
+ * ordinary messages instead of calling one.
80
111
  */
81
112
  export declare function createAgent(req: KernelRequest, orgId: string, opts?: {
82
113
  model?: {
83
114
  provider: string;
84
115
  model: string;
85
116
  };
86
- tools?: unknown[];
117
+ disabledTools?: unknown[];
118
+ disabledSkills?: unknown[];
87
119
  }): Promise<string>;
88
120
  /** Creates a conversation with the agent; returns its id. */
89
121
  export declare function createConversation(req: KernelRequest, orgId: string, agentId: string): Promise<string>;
90
122
  /** Posts a user message; returns its event seq. */
91
123
  export declare function postMessage(req: KernelRequest, orgId: string, conversationId: string, text: string): Promise<number>;
92
124
  /** Every event of a conversation, in seq order (read from the database). */
93
- export declare function eventsOf(db: KernelDb, conversationId: string): Promise<ConversationEvent[]>;
125
+ export declare function eventsOf(db: KernelSchemaDb, conversationId: string): Promise<ConversationEvent[]>;
94
126
  /** Waits for the first event matching `pred` and returns it. */
95
- export declare function waitForEvent(db: KernelDb, conversationId: string, pred: (e: ConversationEvent) => boolean, timeoutMs?: number, label?: string): Promise<ConversationEvent>;
127
+ export declare function waitForEvent(db: KernelSchemaDb, conversationId: string, pred: (e: ConversationEvent) => boolean, timeoutMs?: number, label?: string): Promise<ConversationEvent>;
96
128
  /** Waits for the conversation's `n`-th terminal event (run_finished / run_failed / run_aborted). */
97
- export declare function waitForTerminal(db: KernelDb, conversationId: string, n?: number, timeoutMs?: number): Promise<ConversationEvent[]>;
129
+ export declare function waitForTerminal(db: KernelSchemaDb, conversationId: string, n?: number, timeoutMs?: number): Promise<ConversationEvent[]>;
98
130
  /**
99
131
  * Waits until an IM card's message id is recorded (`channel_card_messages`). The kernel writes it in
100
132
  * the transaction after the card is sent; a click before that is treated as "not a card of this
101
133
  * conversation", so a test waits for this before it clicks, not only for the platform to get it.
102
134
  */
103
- export declare function cardRecorded(db: KernelDb, card: {
135
+ export declare function cardRecorded(db: KernelSchemaDb, card: {
104
136
  messageId: string;
105
137
  } | {
106
138
  kind: "approval" | "question";
@@ -1,7 +1,8 @@
1
1
  import { execFile } from "node:child_process";
2
+ import { EventEmitter } from "node:events";
2
3
  import { readdir, readFile, readlink } from "node:fs/promises";
3
4
  import { promisify } from "node:util";
4
- import { AccountsService, createKernel, createLogger, KernelConfigSchema, MARKETPLACE_OFFICIAL_URL_DEFAULT, } from "@capybara-hq/kernel";
5
+ import { AccountsModule, AccountsService, closeKernelApp, createLogger, KernelConfigSchema, kernelAppHttp, kernelAppPort, MARKETPLACE_OFFICIAL_URL_DEFAULT, openKernelCliOverPool, startKernelApp, } from "@capybara-hq/kernel";
5
6
  import { sql } from "kysely";
6
7
  /**
7
8
  * Helpers for extension tests that run a real kernel: in process (`startTestKernel` +
@@ -60,20 +61,33 @@ export function assertOfflineOfficialMarketplace(config, allow = false) {
60
61
  "marketplaces.official.url at a fake, or build the config with testKernelConfig");
61
62
  }
62
63
  /**
63
- * Creates and starts an in-process kernel. Logs are discarded unless `log` is given (JSON lines at
64
- * `log.level` and above go to `log.write`, e.g. to assert a secret never reaches the log).
65
- * Extensions named by package resolve from `resolveFrom` (default `process.cwd()`). Stop it with
66
- * `stop()`.
64
+ * Creates and starts an in-process kernel (`startKernelApp`; it listens on `config.http.port`).
65
+ * The kernel gets no process-wide signal handlers: a test stops it with `close()`. Logs are
66
+ * discarded unless `log` is given (JSON lines at `log.level` and above go to `log.write`, e.g. to
67
+ * assert a secret never reaches the log). Extensions named by package resolve from `resolveFrom`
68
+ * (default `process.cwd()`).
67
69
  */
68
70
  export async function startTestKernel(config, opts = {}) {
69
71
  assertOfflineOfficialMarketplace(config, opts.allowOfficialMarketplace);
70
- const k = await createKernel(config, {
72
+ const app = await startKernelApp(config, {
71
73
  env: {},
72
74
  logger: createLogger(opts.log?.level ?? "error", { write: opts.log?.write ?? (() => { }) }),
73
75
  ...(opts.resolveFrom !== undefined && { resolveFrom: opts.resolveFrom }),
74
- });
75
- await k.start();
76
- return k;
76
+ },
77
+ // A signal source of its own: a test kernel never handles the process's SIGTERM / SIGINT
78
+ { signals: new EventEmitter() });
79
+ return testKernelOf(app);
80
+ }
81
+ /** The {@link TestKernel} view of a started kernel application. */
82
+ function testKernelOf(app) {
83
+ return {
84
+ app,
85
+ http: kernelAppHttp(app),
86
+ get port() {
87
+ return kernelAppPort(app);
88
+ },
89
+ close: () => closeKernelApp(app),
90
+ };
77
91
  }
78
92
  /** A request function with its own cookie jar (signed out until a response sets cookies). */
79
93
  export function cookieRequest(http) {
@@ -110,7 +124,21 @@ function expectStatus(res, status, what) {
110
124
  }
111
125
  /** Creates a local account with {@link TEST_PASSWORD}; returns its id. */
112
126
  export async function createLocalAccount(db, login, displayName = login) {
113
- return (await new AccountsService(db).createLocal({ login, password: TEST_PASSWORD, displayName })).id;
127
+ // the accounts module over the caller's Kysely; closing the context leaves it open
128
+ const app = await openKernelCliOverPool(db, {
129
+ logger: createLogger("error"),
130
+ modules: [AccountsModule],
131
+ });
132
+ try {
133
+ return (await app.get(AccountsService).createLocal({
134
+ login,
135
+ password: TEST_PASSWORD,
136
+ displayName,
137
+ })).id;
138
+ }
139
+ finally {
140
+ await app.close();
141
+ }
114
142
  }
115
143
  /** Signs in over HTTP and returns the user's request function. */
116
144
  export async function login(k, name, password = TEST_PASSWORD) {
@@ -129,6 +157,35 @@ export async function createOrg(req, name = "Acme") {
129
157
  expectStatus(res, 201, "create org");
130
158
  return res.json().org.id;
131
159
  }
160
+ /**
161
+ * Switches on in `orgId`, through the org's extension switch (`PUT
162
+ * /api/v1/orgs/:orgId/extensions/:name`; `req` is an org admin), every model provider the kernel
163
+ * loaded that is not on there yet, and returns their names. A model provider is on only in the
164
+ * orgs that enabled it (like every other extension), so a test that saves or runs an agent in a
165
+ * new org calls this first; `only` limits it to those providers.
166
+ */
167
+ export async function enableModelProviders(req, orgId, only) {
168
+ const list = await req({ method: "GET", url: `/api/v1/orgs/${orgId}/extensions` });
169
+ expectStatus(list, 200, "list the org's extensions");
170
+ const { extensions } = list.json();
171
+ const enabled = [];
172
+ for (const e of extensions) {
173
+ if (e.enabled || !e.available)
174
+ continue;
175
+ if (!e.provides.some((p) => p.startsWith("model-provider@")))
176
+ continue;
177
+ if (only !== undefined && !only.includes(e.plugin))
178
+ continue;
179
+ const on = await req({
180
+ method: "PUT",
181
+ url: `/api/v1/orgs/${orgId}/extensions/${encodeURIComponent(e.plugin)}`,
182
+ payload: { enabled: true },
183
+ });
184
+ expectStatus(on, 200, `enable ${e.plugin}`);
185
+ enabled.push(e.plugin);
186
+ }
187
+ return enabled;
188
+ }
132
189
  /**
133
190
  * A new account joins the org through an invitation (created by `owner`, accepted with `login`
134
191
  * and {@link TEST_PASSWORD}); returns the account id and its signed-in request function.
@@ -150,8 +207,10 @@ export async function joinOrg(k, owner, orgId, name, role = "member") {
150
207
  return { accountId: accepted.json().account.id, req };
151
208
  }
152
209
  /**
153
- * Creates an org-visible agent; returns its id. Without `tools` the agent has none (model-fake then
154
- * answers ordinary messages instead of calling the first tool).
210
+ * Creates an org-visible agent; returns its id. An agent has every tool the org offers unless
211
+ * `disabledTools` turns it off (tools default-on spec), and every skill on in the org unless
212
+ * `disabledSkills` turns it off (skills default-on spec); with several tools model-fake answers
213
+ * ordinary messages instead of calling one.
155
214
  */
156
215
  export async function createAgent(req, orgId, opts = {}) {
157
216
  const res = await req({
@@ -162,7 +221,8 @@ export async function createAgent(req, orgId, opts = {}) {
162
221
  name: "Helper",
163
222
  instructions: "Be helpful.",
164
223
  model: opts.model ?? { provider: "model-fake", model: "fake-1" },
165
- tools: opts.tools ?? [],
224
+ disabledTools: opts.disabledTools ?? [],
225
+ ...(opts.disabledSkills !== undefined && { disabledSkills: opts.disabledSkills }),
166
226
  },
167
227
  visibility: "org",
168
228
  },
@@ -1,26 +1,27 @@
1
- import { type ModelInfo, type ModelParameter, type ModelProvider, type ModelProviderV1, type ParamValue } from "@capybara-hq/plugin-sdk";
1
+ import { type ModelInfo, type ModelParameter, type ModelProvider, type ParamValue } from "@capybara-hq/plugin-sdk";
2
2
  interface TargetCommon {
3
3
  model: string;
4
4
  expect: {
5
5
  thinking: boolean;
6
6
  caching: boolean;
7
+ /** Set when the provider lists an embedding model: runs the embedding cases. */
8
+ embedding?: {
9
+ model: string;
10
+ dimensions: number;
11
+ };
7
12
  };
8
13
  /** caching 用例的稳定前缀大小(约 token 数),默认 5000。 */
9
14
  cachePrefixTokens?: number;
10
15
  teardown(): Promise<void>;
11
16
  }
12
17
  /**
13
- * 被测供应商:`contract` 缺省为 1(`model-provider@1`);`@2` 插件须给 `contract: 2` 与插件名
14
- * (用于校验厂商专有参数的键名前缀)。
18
+ * The provider under test (`model-provider@2`) and its plugin name (checks the key prefix of
19
+ * vendor-specific parameters).
15
20
  */
16
- export type ConformanceTarget = TargetCommon & ({
17
- contract?: 1;
18
- provider: ModelProviderV1;
19
- } | {
20
- contract: 2;
21
+ export type ConformanceTarget = TargetCommon & {
21
22
  plugin: string;
22
23
  provider: ModelProvider;
23
- });
24
+ };
24
25
  /**
25
26
  * `@2` 参数声明检查:每个模型的 `parameters` 须通过 `assertValidDeclarations`,
26
27
  * 每个声明的默认值须通过 `validateParams`。返回问题列表(形如 `<模型 id>: <原因>`),无问题为空。
@@ -56,6 +57,6 @@ export declare const MEDIA_SAMPLES: {
56
57
  readonly word: "MANGO";
57
58
  };
58
59
  };
59
- /** model-provider 一致性套件(`@1` 与 `@2`):每个供应商插件都应通过。 */
60
+ /** The model-provider conformance suite (`@2`): every provider plugin should pass it. */
60
61
  export declare function describeModelProviderConformance(name: string, setup: () => Promise<ConformanceTarget>): void;
61
62
  export {};
@@ -1,11 +1,9 @@
1
- import { assertValidDeclarations, EFFORT_VALUES, isModelError, sanitizeParams, validateParams, } from "@capybara-hq/plugin-sdk";
1
+ import { assertValidDeclarations, EFFORT_VALUES, isModelError, sanitizeParams, validateEmbedResult, validateParams, } from "@capybara-hq/plugin-sdk";
2
2
  import { afterAll, beforeAll, describe, expect, it } from "vitest";
3
3
  import { pdfBase64, redPngBase64 } from "./media-samples.js";
4
4
  function streamOf(t, req, signal) {
5
5
  const { params, ...rest } = req;
6
- if (t.contract === 2)
7
- return t.provider.stream({ ...rest, params: params ?? {} }, { signal });
8
- return t.provider.stream(rest, { signal });
6
+ return t.provider.stream({ ...rest, params: params ?? {} }, { signal });
9
7
  }
10
8
  /**
11
9
  * `@2` 参数声明检查:每个模型的 `parameters` 须通过 `assertValidDeclarations`,
@@ -81,7 +79,7 @@ export const MEDIA_SAMPLES = {
81
79
  },
82
80
  };
83
81
  const textOf = (content) => content.map((b) => (b.type === "text" ? b.text : "")).join("");
84
- /** model-provider 一致性套件(`@1` 与 `@2`):每个供应商插件都应通过。 */
82
+ /** The model-provider conformance suite (`@2`): every provider plugin should pass it. */
85
83
  export function describeModelProviderConformance(name, setup) {
86
84
  describe(`model-provider conformance: ${name}`, () => {
87
85
  let t;
@@ -145,16 +143,12 @@ export function describeModelProviderConformance(name, setup) {
145
143
  }));
146
144
  expect(second.done.content.some((b) => b.type === "text")).toBe(true);
147
145
  });
148
- /** 思考用例的参数:`@1` 发 `effort: "high"`;`@2` 见 {@link thinkingReplayParams}。 */
146
+ /** The thinking case's parameters, see {@link thinkingReplayParams}. */
149
147
  const thinkingOver = async () => {
150
- if (t.contract !== 2)
151
- return { effort: "high" };
152
148
  const info = (await t.provider.listModels()).find((m) => m.id === t.model);
153
149
  return { params: thinkingReplayParams(info?.parameters ?? []) };
154
150
  };
155
- it("declares valid parameters", async (ctx) => {
156
- if (t.contract !== 2)
157
- return ctx.skip();
151
+ it("declares valid parameters", async () => {
158
152
  expect(checkDeclaredParameters(t.plugin, await t.provider.listModels())).toEqual([]);
159
153
  });
160
154
  it("thinking replay", async (ctx) => {
@@ -211,10 +205,8 @@ export function describeModelProviderConformance(name, setup) {
211
205
  }));
212
206
  expect(done.content.length).toBeGreaterThan(0);
213
207
  });
214
- /** `@2` 模型的能力声明;`@1` 返回 null(媒体用例只对 `@2` 跑)。 */
208
+ /** The model's declared capabilities (null when it is not listed). */
215
209
  const caps = async () => {
216
- if (t.contract !== 2)
217
- return null;
218
210
  const info = (await t.provider.listModels()).find((m) => m.id === t.model);
219
211
  return info?.capabilities ?? null;
220
212
  };
@@ -260,6 +252,38 @@ export function describeModelProviderConformance(name, setup) {
260
252
  expect(done.stopReason).toBe("end_turn");
261
253
  expect(textOf(done.content).toUpperCase()).toContain(s.word);
262
254
  });
255
+ describe("embedding", () => {
256
+ const inputs = ["alpha", "bravo", "charlie"];
257
+ const run = async () => {
258
+ const emb = t.expect.embedding;
259
+ const provider = t.provider;
260
+ if (!emb || !provider.embed)
261
+ throw new Error("the target declares embedding but has no embed");
262
+ const req = { model: emb.model, input: inputs, dimensions: emb.dimensions };
263
+ const res = await provider.embed(req, { signal: new AbortController().signal });
264
+ const models = await provider.listModels();
265
+ const info = models.find((m) => m.id === emb.model)?.embedding;
266
+ return { req, res, info };
267
+ };
268
+ it("embeds a batch in order", async (ctx) => {
269
+ if (!t.expect.embedding)
270
+ return ctx.skip();
271
+ const { res } = await run();
272
+ expect(res.vectors).toHaveLength(inputs.length);
273
+ for (const v of res.vectors)
274
+ expect(v).toHaveLength(t.expect.embedding.dimensions);
275
+ expect(res.usage.inputTokens).toBeGreaterThanOrEqual(0);
276
+ });
277
+ it("embed result passes validateEmbedResult", async (ctx) => {
278
+ if (!t.expect.embedding)
279
+ return ctx.skip();
280
+ const { req, res, info } = await run();
281
+ expect(info).toBeDefined();
282
+ if (!info)
283
+ return;
284
+ expect(validateEmbedResult(req, info, res)).toBeNull();
285
+ });
286
+ });
263
287
  it("abort", async () => {
264
288
  const ac = new AbortController();
265
289
  const it = streamOf(t, base(), ac.signal)[Symbol.asyncIterator]();
@@ -1,5 +1,10 @@
1
- import { createKernel, KernelConfigSchema } from "@capybara-hq/kernel";
2
- let kernel;
1
+ import { EventEmitter } from "node:events";
2
+ import { KernelConfigSchema, kernelAppPort, startKernelApp } from "@capybara-hq/kernel";
3
+ /**
4
+ * The replica's signal source: the stop message (or the parent going away) raises SIGTERM on it, so
5
+ * the kernel stops through the same shutdown path as `capybara start` — also while it is starting.
6
+ */
7
+ const signals = new EventEmitter();
3
8
  const isPlainObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4
9
  /** 深合并:普通对象逐键递归,其余(含数组)由 `over` 整体替换。 */
5
10
  function deepMerge(base, over) {
@@ -27,22 +32,25 @@ async function startKernel(c) {
27
32
  log: { level: "error" },
28
33
  };
29
34
  const config = KernelConfigSchema.parse(deepMerge(base, c.overrides));
30
- kernel = await createKernel(config, {
35
+ const app = await startKernelApp(config, {
31
36
  resolveFrom: c.resolveFrom,
32
37
  ...(c.bootstrap !== undefined && { bootstrap: c.bootstrap }),
33
38
  ...(c.bootstrapManifest !== undefined && { bootstrapManifest: c.bootstrapManifest }),
34
- });
35
- await kernel.start();
36
- process.send?.({ type: "ready", port: kernel.port });
39
+ }, { signals, exit: (code) => process.exit(code) });
40
+ process.send?.({ type: "ready", port: kernelAppPort(app) });
37
41
  }
38
42
  let exiting = false;
39
- /** 停内核后退出;内核停机卡住时 10 秒后强制退出。 */
43
+ /** Stops the kernel, then exits; a stop stuck for 10 s exits with 1. */
40
44
  function shutdown() {
41
45
  if (exiting)
42
46
  return;
43
47
  exiting = true;
44
48
  setTimeout(() => process.exit(1), 10_000).unref();
45
- (kernel?.stop() ?? Promise.resolve()).finally(() => process.exit(0));
49
+ // No kernel handlers yet (still building) or any more (the start failed): nothing to stop
50
+ if (signals.listenerCount("SIGTERM") === 0)
51
+ process.exit(0);
52
+ else
53
+ signals.emit("SIGTERM", "SIGTERM");
46
54
  }
47
55
  // 父进程(含被 SIGKILL)消失后 IPC 通道断开,副本自行退出,不留孤儿
48
56
  process.on("disconnect", shutdown);
@@ -0,0 +1,31 @@
1
+ import type { SandboxOperation } from "@capybara-hq/plugin-sdk";
2
+ /** Fixture setup only. All paths and symlink targets are absolute and inside the owned root. */
3
+ export type NativeFixtureEntry = {
4
+ path: string;
5
+ kind: "directory";
6
+ } | {
7
+ path: string;
8
+ kind: "file";
9
+ data: Uint8Array;
10
+ } | {
11
+ path: string;
12
+ kind: "symlink";
13
+ target: string;
14
+ };
15
+ /** Supplies isolated ordinary files and fresh native operations; never a permission grant. */
16
+ export interface SandboxNativeFixture {
17
+ /** An empty owned temporary directory, expressed as an absolute POSIX device path. */
18
+ root: string;
19
+ /** A new operation ID for each factory call, consumed by one native method invocation. */
20
+ operation(): Promise<Pick<SandboxOperation, "readFile" | "writeFile" | "stat" | "list" | "scan">>;
21
+ /** Creates entries and their parents inside root; preserves entries from earlier seed calls. */
22
+ seed(entries: readonly NativeFixtureEntry[]): Promise<void>;
23
+ /** Removes fixture-owned resources, including after an assertion failure. */
24
+ dispose(): Promise<void>;
25
+ }
26
+ /**
27
+ * Checks ordinary native API compatibility in a fixture-owned temporary root. Each invocation
28
+ * gets a fresh operation. Passing does not establish OS enforcement or permission capabilities.
29
+ * The fixture owns setup and cleanup; no official plugin, database or network service is used.
30
+ */
31
+ export declare function runSandboxNativeConformance(fixture: SandboxNativeFixture): Promise<void>;