@capybara-hq/testing 0.1.0-rc.2 → 0.1.0-rc.20
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/dist/containers.d.ts +7 -2
- package/dist/containers.js +7 -3
- package/dist/dual-replica.d.ts +11 -2
- package/dist/dual-replica.js +48 -0
- package/dist/fake-channel.d.ts +31 -2
- package/dist/fake-channel.js +29 -2
- package/dist/fake-e2b.d.ts +34 -0
- package/dist/fake-e2b.js +95 -1
- package/dist/fake-git-server.d.ts +32 -4
- package/dist/fake-git-server.js +87 -19
- 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 +21 -4
- package/dist/fixtures.js +30 -4
- package/dist/index.d.ts +7 -5
- package/dist/index.js +4 -2
- package/dist/kernel-helpers.d.ts +40 -16
- package/dist/kernel-helpers.js +44 -13
- package/dist/model-conformance.d.ts +5 -0
- package/dist/model-conformance.js +33 -1
- package/dist/replica-runner.js +16 -8
- package/dist/sandbox-native-conformance.d.ts +31 -0
- package/dist/sandbox-native-conformance.js +153 -0
- package/fixtures/extensions/fake-client/.capybara-plugin/plugin.json +11 -0
- package/fixtures/extensions/fake-client/client/styles/fake.css +11 -0
- package/fixtures/extensions/fake-client/package.json +12 -0
- package/fixtures/extensions/fake-client/src/client.tsx +51 -0
- package/fixtures/extensions/fake-client/src/index.ts +43 -0
- package/fixtures/extensions/fake-client/themes/fake.json +11 -0
- package/fixtures/extensions/fake-client-broken/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-client-broken/package.json +12 -0
- package/fixtures/extensions/fake-client-broken/src/client.tsx +22 -0
- package/fixtures/extensions/fake-client-broken/src/index.ts +27 -0
- 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-context/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-context/package.json +12 -0
- package/fixtures/extensions/fake-context/src/index.ts +81 -0
- package/fixtures/extensions/fake-dep-provider/src/index.ts +1 -1
- package/fixtures/extensions/fake-dep-requirer/src/index.ts +1 -1
- package/fixtures/extensions/fake-embed/src/index.ts +26 -26
- package/fixtures/extensions/fake-im/.capybara-plugin/plugin.json +7 -1
- package/fixtures/extensions/fake-im/guides/fake-im-app.md +32 -0
- package/fixtures/extensions/fake-im/guides/fake-im-app.zh.md +32 -0
- package/fixtures/extensions/fake-im/src/channel.ts +3 -1
- package/fixtures/extensions/fake-im/src/checks.ts +94 -0
- package/fixtures/extensions/fake-im/src/index.ts +36 -1
- package/fixtures/extensions/fake-lifecycle/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-lifecycle/migrations/0001_init.sql +16 -0
- package/fixtures/extensions/fake-lifecycle/package.json +12 -0
- package/fixtures/extensions/fake-lifecycle/src/index.ts +72 -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 +62 -3
- 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/fixtures/plugins/fake-theme/.capybara-plugin/plugin.json +7 -0
- package/fixtures/plugins/fake-theme/fonts/FakeSans.woff2 +1 -0
- package/fixtures/plugins/fake-theme/logo.svg +1 -0
- package/fixtures/plugins/fake-theme/package.json +8 -0
- package/fixtures/plugins/fake-theme/themes/neon-grid.json +13 -0
- package/fixtures/plugins/fake-theme/themes/paper.json +12 -0
- 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` |
|
|
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
|
-
|
|
88
|
-
|
|
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
|
|
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,10 @@ 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, 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";
|
|
25
27
|
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,
|
|
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,10 @@ 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
23
|
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
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";
|
|
25
27
|
export { openSse } from "./sse.js";
|
package/dist/kernel-helpers.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type ConversationEvent, type
|
|
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
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
* `
|
|
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<
|
|
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,49 @@ 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:
|
|
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<
|
|
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>;
|
|
69
90
|
/**
|
|
70
91
|
* A new account joins the org through an invitation (created by `owner`, accepted with `login`
|
|
71
92
|
* and {@link TEST_PASSWORD}); returns the account id and its signed-in request function.
|
|
72
93
|
*/
|
|
73
|
-
export declare function joinOrg(k: Pick<
|
|
94
|
+
export declare function joinOrg(k: Pick<TestKernel, "http">, owner: KernelRequest, orgId: string, name: string, role?: "member" | "admin"): Promise<{
|
|
74
95
|
accountId: string;
|
|
75
96
|
req: KernelRequest;
|
|
76
97
|
}>;
|
|
77
98
|
/**
|
|
78
|
-
* Creates an org-visible agent; returns its id.
|
|
79
|
-
*
|
|
99
|
+
* Creates an org-visible agent; returns its id. An agent has every tool the org offers unless
|
|
100
|
+
* `disabledTools` turns it off (tools default-on spec), and every skill on in the org unless
|
|
101
|
+
* `disabledSkills` turns it off (skills default-on spec); with several tools model-fake answers
|
|
102
|
+
* ordinary messages instead of calling one.
|
|
80
103
|
*/
|
|
81
104
|
export declare function createAgent(req: KernelRequest, orgId: string, opts?: {
|
|
82
105
|
model?: {
|
|
83
106
|
provider: string;
|
|
84
107
|
model: string;
|
|
85
108
|
};
|
|
86
|
-
|
|
109
|
+
disabledTools?: unknown[];
|
|
110
|
+
disabledSkills?: unknown[];
|
|
87
111
|
}): Promise<string>;
|
|
88
112
|
/** Creates a conversation with the agent; returns its id. */
|
|
89
113
|
export declare function createConversation(req: KernelRequest, orgId: string, agentId: string): Promise<string>;
|
|
90
114
|
/** Posts a user message; returns its event seq. */
|
|
91
115
|
export declare function postMessage(req: KernelRequest, orgId: string, conversationId: string, text: string): Promise<number>;
|
|
92
116
|
/** Every event of a conversation, in seq order (read from the database). */
|
|
93
|
-
export declare function eventsOf(db:
|
|
117
|
+
export declare function eventsOf(db: KernelSchemaDb, conversationId: string): Promise<ConversationEvent[]>;
|
|
94
118
|
/** Waits for the first event matching `pred` and returns it. */
|
|
95
|
-
export declare function waitForEvent(db:
|
|
119
|
+
export declare function waitForEvent(db: KernelSchemaDb, conversationId: string, pred: (e: ConversationEvent) => boolean, timeoutMs?: number, label?: string): Promise<ConversationEvent>;
|
|
96
120
|
/** Waits for the conversation's `n`-th terminal event (run_finished / run_failed / run_aborted). */
|
|
97
|
-
export declare function waitForTerminal(db:
|
|
121
|
+
export declare function waitForTerminal(db: KernelSchemaDb, conversationId: string, n?: number, timeoutMs?: number): Promise<ConversationEvent[]>;
|
|
98
122
|
/**
|
|
99
123
|
* Waits until an IM card's message id is recorded (`channel_card_messages`). The kernel writes it in
|
|
100
124
|
* the transaction after the card is sent; a click before that is treated as "not a card of this
|
|
101
125
|
* conversation", so a test waits for this before it clicks, not only for the platform to get it.
|
|
102
126
|
*/
|
|
103
|
-
export declare function cardRecorded(db:
|
|
127
|
+
export declare function cardRecorded(db: KernelSchemaDb, card: {
|
|
104
128
|
messageId: string;
|
|
105
129
|
} | {
|
|
106
130
|
kind: "approval" | "question";
|
package/dist/kernel-helpers.js
CHANGED
|
@@ -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,
|
|
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
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
* `
|
|
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
|
|
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
|
-
|
|
76
|
-
|
|
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
|
-
|
|
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) {
|
|
@@ -150,8 +178,10 @@ export async function joinOrg(k, owner, orgId, name, role = "member") {
|
|
|
150
178
|
return { accountId: accepted.json().account.id, req };
|
|
151
179
|
}
|
|
152
180
|
/**
|
|
153
|
-
* Creates an org-visible agent; returns its id.
|
|
154
|
-
*
|
|
181
|
+
* Creates an org-visible agent; returns its id. An agent has every tool the org offers unless
|
|
182
|
+
* `disabledTools` turns it off (tools default-on spec), and every skill on in the org unless
|
|
183
|
+
* `disabledSkills` turns it off (skills default-on spec); with several tools model-fake answers
|
|
184
|
+
* ordinary messages instead of calling one.
|
|
155
185
|
*/
|
|
156
186
|
export async function createAgent(req, orgId, opts = {}) {
|
|
157
187
|
const res = await req({
|
|
@@ -162,7 +192,8 @@ export async function createAgent(req, orgId, opts = {}) {
|
|
|
162
192
|
name: "Helper",
|
|
163
193
|
instructions: "Be helpful.",
|
|
164
194
|
model: opts.model ?? { provider: "model-fake", model: "fake-1" },
|
|
165
|
-
|
|
195
|
+
disabledTools: opts.disabledTools ?? [],
|
|
196
|
+
...(opts.disabledSkills !== undefined && { disabledSkills: opts.disabledSkills }),
|
|
166
197
|
},
|
|
167
198
|
visibility: "org",
|
|
168
199
|
},
|
|
@@ -4,6 +4,11 @@ interface TargetCommon {
|
|
|
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;
|
|
@@ -1,4 +1,4 @@
|
|
|
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) {
|
|
@@ -260,6 +260,38 @@ export function describeModelProviderConformance(name, setup) {
|
|
|
260
260
|
expect(done.stopReason).toBe("end_turn");
|
|
261
261
|
expect(textOf(done.content).toUpperCase()).toContain(s.word);
|
|
262
262
|
});
|
|
263
|
+
describe("embedding", () => {
|
|
264
|
+
const inputs = ["alpha", "bravo", "charlie"];
|
|
265
|
+
const run = async () => {
|
|
266
|
+
const emb = t.expect.embedding;
|
|
267
|
+
const provider = t.provider;
|
|
268
|
+
if (!emb || !provider.embed)
|
|
269
|
+
throw new Error("the target declares embedding but has no embed");
|
|
270
|
+
const req = { model: emb.model, input: inputs, dimensions: emb.dimensions };
|
|
271
|
+
const res = await provider.embed(req, { signal: new AbortController().signal });
|
|
272
|
+
const models = await provider.listModels();
|
|
273
|
+
const info = models.find((m) => m.id === emb.model)?.embedding;
|
|
274
|
+
return { req, res, info };
|
|
275
|
+
};
|
|
276
|
+
it("embeds a batch in order", async (ctx) => {
|
|
277
|
+
if (!t.expect.embedding)
|
|
278
|
+
return ctx.skip();
|
|
279
|
+
const { res } = await run();
|
|
280
|
+
expect(res.vectors).toHaveLength(inputs.length);
|
|
281
|
+
for (const v of res.vectors)
|
|
282
|
+
expect(v).toHaveLength(t.expect.embedding.dimensions);
|
|
283
|
+
expect(res.usage.inputTokens).toBeGreaterThanOrEqual(0);
|
|
284
|
+
});
|
|
285
|
+
it("embed result passes validateEmbedResult", async (ctx) => {
|
|
286
|
+
if (!t.expect.embedding)
|
|
287
|
+
return ctx.skip();
|
|
288
|
+
const { req, res, info } = await run();
|
|
289
|
+
expect(info).toBeDefined();
|
|
290
|
+
if (!info)
|
|
291
|
+
return;
|
|
292
|
+
expect(validateEmbedResult(req, info, res)).toBeNull();
|
|
293
|
+
});
|
|
294
|
+
});
|
|
263
295
|
it("abort", async () => {
|
|
264
296
|
const ac = new AbortController();
|
|
265
297
|
const it = streamOf(t, base(), ac.signal)[Symbol.asyncIterator]();
|
package/dist/replica-runner.js
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
/**
|
|
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
|
-
|
|
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>;
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { posix } from "node:path";
|
|
3
|
+
/**
|
|
4
|
+
* Checks ordinary native API compatibility in a fixture-owned temporary root. Each invocation
|
|
5
|
+
* gets a fresh operation. Passing does not establish OS enforcement or permission capabilities.
|
|
6
|
+
* The fixture owns setup and cleanup; no official plugin, database or network service is used.
|
|
7
|
+
*/
|
|
8
|
+
export async function runSandboxNativeConformance(fixture) {
|
|
9
|
+
const path = (name) => posix.join(fixture.root, name);
|
|
10
|
+
const signal = new AbortController().signal;
|
|
11
|
+
const fresh = async () => {
|
|
12
|
+
const operation = await fixture.operation();
|
|
13
|
+
assert(operation.list && operation.scan, "Native conformance requires list and scan");
|
|
14
|
+
return operation;
|
|
15
|
+
};
|
|
16
|
+
const read = async (name, maxBytes) => (await fresh()).readFile(path(name), { maxBytes, signal });
|
|
17
|
+
const stat = async (name) => (await fresh()).stat(path(name), signal);
|
|
18
|
+
const write = async (name, data) => (await fresh()).writeFile(path(name), data, signal);
|
|
19
|
+
const list = async (name, limit) => (await fresh()).list(path(name), { limit, signal });
|
|
20
|
+
const scan = async (name) => (await fresh()).scan(path(name), { signal });
|
|
21
|
+
const directory = (name) => ({ path: path(name), kind: "directory" });
|
|
22
|
+
const file = (name) => ({
|
|
23
|
+
path: path(name),
|
|
24
|
+
kind: "file",
|
|
25
|
+
data: new Uint8Array(),
|
|
26
|
+
});
|
|
27
|
+
const link = (name, target) => ({
|
|
28
|
+
path: path(name),
|
|
29
|
+
kind: "symlink",
|
|
30
|
+
target: path(target),
|
|
31
|
+
});
|
|
32
|
+
const candidates = (names) => names.map((name) => ({
|
|
33
|
+
path: path(name),
|
|
34
|
+
suggestedName: posix.basename(name),
|
|
35
|
+
}));
|
|
36
|
+
try {
|
|
37
|
+
assert.equal(await stat("missing"), null, "missing stat must return null");
|
|
38
|
+
assert.equal(await read("missing", 10), null, "missing read must return null");
|
|
39
|
+
assert.equal(await list("missing", 10), null, "missing list must return null");
|
|
40
|
+
assert.deepEqual(await scan("missing"), [], "missing scan must be empty");
|
|
41
|
+
await fixture.seed([directory("empty")]);
|
|
42
|
+
assert.equal((await stat("empty"))?.isDir, true);
|
|
43
|
+
assert.equal(await read("empty", 10), null, "directory read must return null");
|
|
44
|
+
assert.deepEqual(await list("empty", 0), { entries: [], truncated: false });
|
|
45
|
+
const bytes = new Uint8Array([0, 255, 128, 10, 65, 0]);
|
|
46
|
+
await write("parents/nested/binary", bytes);
|
|
47
|
+
assert.deepEqual(await stat("parents/nested/binary"), { size: 6, isDir: false });
|
|
48
|
+
assert.deepEqual(await read("parents/nested/binary", 6), { data: bytes, truncated: false });
|
|
49
|
+
assert.deepEqual(await read("parents/nested/binary", 100), { data: bytes, truncated: false });
|
|
50
|
+
assert.deepEqual(await read("parents/nested/binary", 3), {
|
|
51
|
+
data: new Uint8Array([0, 255, 128]),
|
|
52
|
+
truncated: true,
|
|
53
|
+
});
|
|
54
|
+
assert.deepEqual(await read("parents/nested/binary", 0), {
|
|
55
|
+
data: new Uint8Array(),
|
|
56
|
+
truncated: true,
|
|
57
|
+
});
|
|
58
|
+
await write("parents/nested/binary", new Uint8Array());
|
|
59
|
+
assert.deepEqual(await read("parents/nested/binary", 0), {
|
|
60
|
+
data: new Uint8Array(),
|
|
61
|
+
truncated: false,
|
|
62
|
+
});
|
|
63
|
+
assert.deepEqual(await stat("parents/nested/binary"), { size: 0, isDir: false });
|
|
64
|
+
assert.equal(await stat("parents/nested/binary/missing"), null);
|
|
65
|
+
assert.equal(await read("parents/nested/binary/missing", 10), null);
|
|
66
|
+
assert.equal(await list("parents/nested/binary/missing", 10), null);
|
|
67
|
+
assert.deepEqual(await scan("parents/nested/binary/missing"), []);
|
|
68
|
+
await assert.rejects(() => list("parents/nested/binary", 5));
|
|
69
|
+
await assert.rejects(() => scan("parents/nested/binary"));
|
|
70
|
+
await fixture.seed([
|
|
71
|
+
directory("listing/B"),
|
|
72
|
+
file("listing/a"),
|
|
73
|
+
file("listing/\u{1f600}"),
|
|
74
|
+
file("listing/\ue000"),
|
|
75
|
+
link("listing/alias", "listing/B"),
|
|
76
|
+
link("listing/dangling", "listing/missing"),
|
|
77
|
+
link("file-link", "listing/a"),
|
|
78
|
+
]);
|
|
79
|
+
assert.deepEqual(await list("listing", 0), { entries: [], truncated: true });
|
|
80
|
+
assert.deepEqual(await list("listing", 2), {
|
|
81
|
+
entries: [
|
|
82
|
+
{ name: "B", isDir: true },
|
|
83
|
+
{ name: "a", isDir: false },
|
|
84
|
+
],
|
|
85
|
+
truncated: true,
|
|
86
|
+
});
|
|
87
|
+
assert.deepEqual(await list("listing", 6), {
|
|
88
|
+
entries: [
|
|
89
|
+
{ name: "B", isDir: true },
|
|
90
|
+
{ name: "a", isDir: false },
|
|
91
|
+
{ name: "alias", isDir: true },
|
|
92
|
+
{ name: "dangling", isDir: false },
|
|
93
|
+
{ name: "\u{1f600}", isDir: false },
|
|
94
|
+
{ name: "\ue000", isDir: false },
|
|
95
|
+
],
|
|
96
|
+
truncated: false,
|
|
97
|
+
});
|
|
98
|
+
await write("file-link", bytes);
|
|
99
|
+
assert.deepEqual(await read("listing/a", 6), { data: bytes, truncated: false });
|
|
100
|
+
assert.deepEqual(await stat("file-link"), { size: 6, isDir: false });
|
|
101
|
+
assert.deepEqual(await list("listing/alias", 1), { entries: [], truncated: false });
|
|
102
|
+
assert.equal(await read("listing/dangling", 10), null);
|
|
103
|
+
await assert.rejects(() => write("listing/dangling", bytes));
|
|
104
|
+
assert.equal(await stat("listing/missing"), null, "dangling writes must not create a target");
|
|
105
|
+
await fixture.seed([file("percent/a%2f%ZZ/AGENTS.md"), file("percent/a%5c%/AGENTS.md")]);
|
|
106
|
+
assert.deepEqual(await scan("percent"), candidates(["percent/a%2f%ZZ", "percent/a%5c%"]));
|
|
107
|
+
const longName = "x".repeat(65);
|
|
108
|
+
await fixture.seed([
|
|
109
|
+
file("scan/AGENTS.md"),
|
|
110
|
+
file("scan/a/.git"),
|
|
111
|
+
file("scan/a/deep/AGENTS.md"),
|
|
112
|
+
file("scan/a/deep/too-deep/.git"),
|
|
113
|
+
directory("scan/false-hit/AGENTS.md"),
|
|
114
|
+
file("scan/.hidden/.git"),
|
|
115
|
+
file("scan/node_modules/.git"),
|
|
116
|
+
file("scan/Library/.git"),
|
|
117
|
+
file("scan/a/node_modules/.git"),
|
|
118
|
+
file("scan/a/Library/.git"),
|
|
119
|
+
file(`scan/${longName}/.git`),
|
|
120
|
+
file(`scan/${longName}/valid/.git`),
|
|
121
|
+
file("scan/ leading/.git"),
|
|
122
|
+
file("scan/ trailing /.git"),
|
|
123
|
+
file("scan/ leading/valid/.git"),
|
|
124
|
+
link("scan/link", "scan/a"),
|
|
125
|
+
]);
|
|
126
|
+
assert.deepEqual(await scan("scan"), candidates([
|
|
127
|
+
"scan",
|
|
128
|
+
"scan/ leading/valid",
|
|
129
|
+
"scan/a",
|
|
130
|
+
"scan/a/Library",
|
|
131
|
+
"scan/a/deep",
|
|
132
|
+
`scan/${longName}/valid`,
|
|
133
|
+
]), "scan must descend past hits and invalid names, and apply depth/skips exactly");
|
|
134
|
+
await fixture.seed([
|
|
135
|
+
...Array.from({ length: 51 }, (_, i) => file(`results/b${String(i).padStart(3, "0")}/.git`)),
|
|
136
|
+
file("results/a/deep/.git"),
|
|
137
|
+
]);
|
|
138
|
+
assert.deepEqual(await scan("results"), candidates([
|
|
139
|
+
"results/a/deep",
|
|
140
|
+
...Array.from({ length: 49 }, (_, i) => `results/b${String(i).padStart(3, "0")}`),
|
|
141
|
+
]), "scan truncates to 50 only after sorting all visited candidates");
|
|
142
|
+
await fixture.seed([
|
|
143
|
+
...Array.from({ length: 500 }, (_, i) => directory(`visits/d${String(i).padStart(3, "0")}`)),
|
|
144
|
+
file("visits/d498/.git"),
|
|
145
|
+
file("visits/d499/.git"),
|
|
146
|
+
file("visits/d000/deep/.git"),
|
|
147
|
+
]);
|
|
148
|
+
assert.deepEqual(await scan("visits"), candidates(["visits/d498"]), "base counts as visit one; breadth-first visit 500 includes d498, excludes d499 and depth two");
|
|
149
|
+
}
|
|
150
|
+
finally {
|
|
151
|
+
await fixture.dispose();
|
|
152
|
+
}
|
|
153
|
+
}
|