@wirecat/cli-core 0.684.0 → 0.685.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/dist/cli/bot/api-http.d.ts +10 -2
  3. package/dist/cli/bot/api-http.js +50 -45
  4. package/dist/cli/context.d.ts +6 -1
  5. package/dist/cli/context.js +16 -2
  6. package/dist/cli/documents/testing/index.d.ts +1 -1
  7. package/dist/cli/documents/testing/index.js +1 -1
  8. package/dist/cli/documents/testing/source-contract.d.ts +34 -1
  9. package/dist/cli/documents/testing/source-contract.js +153 -1
  10. package/dist/cli/documents/testing/source.d.ts +2 -0
  11. package/dist/cli/documents/testing/source.js +8 -1
  12. package/dist/cli/index.d.ts +4 -2
  13. package/dist/cli/index.js +4 -2
  14. package/dist/cli/profile-token.js +13 -3
  15. package/dist/cli/program.js +6 -4
  16. package/dist/cli/service-api-manifest.d.ts +40 -0
  17. package/dist/cli/service-api-manifest.js +106 -0
  18. package/dist/cli/service-api.d.ts +29 -30
  19. package/dist/cli/service-api.js +133 -53
  20. package/dist/crm/digest.d.ts +1 -1
  21. package/dist/crm/digest.js +9 -1
  22. package/dist/crm/testing/index.d.ts +1 -1
  23. package/dist/crm/testing/source-contract.d.ts +26 -1
  24. package/dist/crm/testing/source-contract.js +102 -0
  25. package/dist/crm/testing/source.d.ts +2 -0
  26. package/dist/crm/testing/source.js +6 -0
  27. package/dist/http/link-fetch.d.ts +10 -0
  28. package/dist/http/link-fetch.js +28 -0
  29. package/dist/meetings/import.d.ts +1 -1
  30. package/dist/meetings/import.js +2 -0
  31. package/dist/meetings/index.d.ts +1 -0
  32. package/dist/meetings/index.js +1 -0
  33. package/dist/meetings/pull.d.ts +2 -0
  34. package/dist/meetings/pull.js +18 -0
  35. package/dist/meetings/search-store.d.ts +2 -0
  36. package/dist/meetings/search-store.js +16 -1
  37. package/dist/meetings/store.d.ts +3 -0
  38. package/dist/services/meeting-hit-search.d.ts +2 -3
  39. package/dist/services/meeting-hit-search.js +2 -17
  40. package/dist/services/search-all-meetings.d.ts +1 -1
  41. package/dist/store/sqlite/deals.d.ts +0 -2
  42. package/dist/store/sqlite/deals.js +0 -1
  43. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -5,6 +5,61 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.685.0 — 16.11.2026
9
+
10
+ ### Added
11
+
12
+ - **`serviceApiCommand` reads the generated manifest whole** (`import * as manifest from "./generated/manifest.js"`,
13
+ cli-base 0.108.0's `generate`): the base URL from `servers` (a variable at its default only when its `enum` lists
14
+ it; a free one such as `{subdomain}` needs `baseUrl`, and either must be https), the sign-in header from the
15
+ operation's `security` and the manifest's `securitySchemes` (`Authorization: Bearer`, `OAuth <token>` for an `http`
16
+ scheme named so, an API key header that never follows a redirect; none for `security: []`, the token still sent for an
17
+ optional sign-in), and `--all` on a read with a `pagination` and no permission key, which reads each page by its
18
+ cursor, offset, page number or next link in one run. It ends on an empty page or the `total`, stops with an error on
19
+ a repeated page or past 500 pages, and refuses a next link on another host, so the token never goes there. Paging by
20
+ page number needs the first page given (`--page 0` or `1`). A CLI passes `token`, and `headers` only for what the
21
+ scheme does not cover.
22
+ - **`linkFetch({ hosts })`** fetches a link the service returned (a download or upload URL, a signed file URL): only to
23
+ the listed hosts, only over https, and a request carrying `authorization`, `cookie` or `proxy-authorization` is
24
+ refused before it leaves, as is a service's own key header named in `signIn`.
25
+ - **Fault cases in `documentSourceContract` and `crmSourceContract`**, opt-in through the fixture's new `faults`; a case
26
+ whose hook is absent passes without running. Documents: a child that answers 403 or 404 (the error code, and a sync
27
+ that imports the rest and names the refused file), a clock ten minutes off either way, a second profile on the same
28
+ token, an interrupted sync that goes on instead of over, and a slow provider under the MCP's 45 s deadline. With
29
+ `faults.sync`, the CLI's own sync wiring runs these against `syncDocuments`. CRM: `get` gives `null` for a 403 or
30
+ 404, the skew and same-token checks, a full list cut after one page and resumed in a new run, and a source that
31
+ pages inside one call ending it with the budget's own error once the budget is spent. `fakeDocumentSource().deny` and `fakeCrmSource().deny` fake the refusals.
32
+
33
+ ### Changed — may break callers
34
+
35
+ - **`store.deals.pipeline()` no longer returns `since`**, the UTC day of `window.since`. Read `window.since` (an ISO
36
+ time) instead; memo, the last reader, stopped using it in cli-memo#862.
37
+ - **`serviceApiCommand` and `serviceApiPermissions` take the manifest's `permissions`** (`<group>.delete`,
38
+ `<group>.share`, each with the body fields or query flags that make it apply unless absent or `false`) in place of `deleteKey`,
39
+ `deletingFields` and `deletingBodies`. A `bodyPermissions` key the manifest does not name stops the build. A key also applies to a read: a call whose flag deletes, as an upload link
40
+ with `overwrite=true`, goes through the guard. `bodyPermissions` keeps a CLI's own test of a body, each with its key
41
+ and a `when` for `--dry-run`. An operation that deletes without a `.delete` key in the manifest stops the build:
42
+ generate with `permissions`. `ServiceApiOperation` and `serviceApiDeletes` are gone; `serviceApiKeys` gives the keys
43
+ one call checks.
44
+ - **cli-base 0.108.0** is the lowest version the peer range accepts.
45
+
46
+ ### Fixed
47
+
48
+ - **The CRM digest writes its own few words in Spanish too** ("ganada", "nuevo responsable", "contactos nuevos"). It
49
+ had only English and Russian, so an owner in Spanish read English words in a Spanish digest.
50
+ - **A generated API command's `--limit` or `--page`** (Yandex Disk's `limit`, HubSpot's) is the service's own: the CLI's paging
51
+ settings no longer read it (in a run, a `--dry-run` preview and discovery alike), so `--page 0` or `--page 1 --all`
52
+ is no longer refused. `withoutOwnPaging(command, flags)` leaves such flags out for a CLI's own settings call.
53
+ - **A sign-in still lands in the file when the OS keyring does not answer.** cli-base 0.108.0 reports an unreachable
54
+ keyring as `keyring.unreachable` instead of "not signed in"; `ProfileTokenStore.write` no longer fails on it while it
55
+ looks up the named secrets it keeps beside the token.
56
+ - **`search all` finds the words of meeting transcripts after `meetings sync`.** It reads meetings only from their
57
+ search index, and nothing but `search meetings` built that index, so a synced call's transcript was never found
58
+ and the answer named the account under `missing`. `meetings sync` and `meetings import` now index what they saved
59
+ before they answer, through the store's optional `indexSearch`; a failure to index is a warning in the report. A
60
+ sync its budget stopped leaves the index to the next run. `refreshMeetingIndex` moved to `@wirecat/cli-core/meetings`
61
+ and is still exported from the services.
62
+
8
63
  ## 0.684.0 — 16.11.2026
9
64
 
10
65
  ### Added
@@ -8,6 +8,8 @@ export interface HttpApiRequest {
8
8
  url: URL;
9
9
  headers: Headers;
10
10
  body?: string;
11
+ /** `manual` for a request whose sign-in header a redirect to another host would carry along. */
12
+ redirect?: "follow" | "manual" | "error";
11
13
  }
12
14
  export interface HttpApiExecutorOptions {
13
15
  /** The service's name in messages: "Notion". */
@@ -34,10 +36,16 @@ export interface HttpApiExecutorOptions {
34
36
  }
35
37
  /** One generated HTTP operation and its flags as the request they stand for; nothing is sent. */
36
38
  export declare const httpApiRequest: (operation: ManifestOperation, input: ApiCommandInput, baseUrl: string) => HttpApiRequest;
39
+ /** What one exchange needs: the service's name, the fetch, its own refusals and the answer's size limit. */
40
+ export type HttpApiSendOptions = Pick<HttpApiExecutorOptions, "service" | "fetch" | "failure" | "maxBytes">;
41
+ /**
42
+ * Sends one request, records it in the run by its path template, never an id, and gives the parsed answer. A write
43
+ * that got no answer is `outcome_unknown` (WC-LIFE-9); the service's own error text is never repeated (WC-SECR-6).
44
+ */
45
+ export declare const httpApiSend: (options: HttpApiSendOptions) => (command: Command, operation: ManifestOperation, request: HttpApiRequest) => Promise<unknown>;
37
46
  /**
38
47
  * The `execute` of `generatedApiCommand` for any OpenAPI CLI: fills the path, adds the query, sends the JSON body
39
48
  * with the caller's headers through the caller's fetch, and prints the answer. Nothing here retries: a write is
40
- * never sent twice, since the first may have landed (WC-OUT-20). The service's own error text is never repeated,
41
- * since it can quote what was sent (WC-SECR-6).
49
+ * never sent twice, since the first may have landed (WC-OUT-20).
42
50
  */
43
51
  export declare const httpApiExecutor: (options: HttpApiExecutorOptions) => (command: Command, operation: ManifestOperation, input: ApiCommandInput) => Promise<void>;
@@ -52,59 +52,64 @@ const answerOf = async (response, maxBytes) => {
52
52
  return {};
53
53
  return readJsonResponse(response, { maxBytes });
54
54
  };
55
+ /**
56
+ * Sends one request, records it in the run by its path template, never an id, and gives the parsed answer. A write
57
+ * that got no answer is `outcome_unknown` (WC-LIFE-9); the service's own error text is never repeated (WC-SECR-6).
58
+ */
59
+ export const httpApiSend = (options) => async (command, operation, request) => {
60
+ const writes = operation.effect !== "read";
61
+ const template = templateOf(operation.binding.kind === "http" ? operation.binding.path : "");
62
+ const end = providerRequest(`${request.method} ${template}`, undefined, {
63
+ method: request.method,
64
+ endpointTemplate: template,
65
+ transport: "http",
66
+ });
67
+ let response;
68
+ try {
69
+ response = await options.fetch(command)(request.url, {
70
+ method: request.method,
71
+ headers: request.headers,
72
+ ...(request.body === undefined ? {} : { body: request.body }),
73
+ ...(request.redirect === undefined ? {} : { redirect: request.redirect }),
74
+ });
75
+ }
76
+ catch (error) {
77
+ const failed = unanswered(options.service, writes, error);
78
+ end({ error: failed });
79
+ throw failed;
80
+ }
81
+ const { status } = response;
82
+ let answer;
83
+ try {
84
+ answer = await answerOf(response, options.maxBytes ?? LARGEST_ANSWER);
85
+ }
86
+ catch {
87
+ if (response.ok) {
88
+ end({ status });
89
+ throw unreadable(options.service, writes, status);
90
+ }
91
+ }
92
+ if (!response.ok) {
93
+ const failed = status >= 500 && writes
94
+ ? refusal(options.service, operation, response, writes)
95
+ : (options.failure?.(status, answer, operation) ?? refusal(options.service, operation, response, writes));
96
+ end({ status, error: failed });
97
+ throw failed;
98
+ }
99
+ end({ status });
100
+ return answer;
101
+ };
55
102
  /**
56
103
  * The `execute` of `generatedApiCommand` for any OpenAPI CLI: fills the path, adds the query, sends the JSON body
57
104
  * with the caller's headers through the caller's fetch, and prints the answer. Nothing here retries: a write is
58
- * never sent twice, since the first may have landed (WC-OUT-20). The service's own error text is never repeated,
59
- * since it can quote what was sent (WC-SECR-6).
105
+ * never sent twice, since the first may have landed (WC-OUT-20).
60
106
  */
61
107
  export const httpApiExecutor = (options) => async (command, operation, input) => {
62
108
  const request = httpApiRequest(operation, input, options.baseUrl);
63
- const writes = operation.effect !== "read";
64
- const template = templateOf(operation.binding.kind === "http" ? operation.binding.path : "");
65
109
  for (const [name, value] of Object.entries(await options.headers(command, operation)))
66
110
  request.headers.set(name, value);
67
- const send = async () => {
68
- const end = providerRequest(`${request.method} ${template}`, undefined, {
69
- method: request.method,
70
- endpointTemplate: template,
71
- transport: "http",
72
- });
73
- let response;
74
- try {
75
- response = await options.fetch(command)(request.url, {
76
- method: request.method,
77
- headers: request.headers,
78
- ...(request.body === undefined ? {} : { body: request.body }),
79
- });
80
- }
81
- catch (error) {
82
- const failed = unanswered(options.service, writes, error);
83
- end({ error: failed });
84
- throw failed;
85
- }
86
- const { status } = response;
87
- let answer;
88
- try {
89
- answer = await answerOf(response, options.maxBytes ?? LARGEST_ANSWER);
90
- }
91
- catch {
92
- if (response.ok) {
93
- end({ status });
94
- throw unreadable(options.service, writes, status);
95
- }
96
- }
97
- if (!response.ok) {
98
- const failed = status >= 500 && writes
99
- ? refusal(options.service, operation, response, writes)
100
- : (options.failure?.(status, answer, operation) ?? refusal(options.service, operation, response, writes));
101
- end({ status, error: failed });
102
- throw failed;
103
- }
104
- end({ status });
105
- return answer;
106
- };
107
- const answer = writes
111
+ const send = () => httpApiSend(options)(command, operation, request);
112
+ const answer = operation.effect !== "read"
108
113
  ? await options.write(command, operation, send)
109
114
  : await (options.read ?? ((_command, _operation, call) => call()))(command, operation, send);
110
115
  renderAnswer(command, outputFor(command), itemOf(answer));
@@ -129,7 +129,12 @@ export declare const runBudgetOf: (command: Command, requests?: number) => RunBu
129
129
  export declare const setExitCode: (command: Command, code: number) => void;
130
130
  export declare const provide: (program: Command, environment: BaseEnvironment) => void;
131
131
  export declare const environmentOf: <E extends BaseEnvironment = BaseEnvironment>(command: Command) => E;
132
- /** The command's flags with an MCP server's `--permission` levels first: they reach a run on its agent, never in argv. */
132
+ /** A generated API command's own `--page`, `--limit` or `--all` is the service's parameter, not the CLI's paging. */
133
+ export declare const withoutOwnPaging: <F extends object>(command: Command, flags: F) => F;
134
+ /**
135
+ * The command's flags as settings read them, an MCP server's `--permission` levels first: they reach a run on its
136
+ * agent, never in argv.
137
+ */
133
138
  export declare const withAgentLevels: <F extends {
134
139
  permission?: string[];
135
140
  }>(command: Command, flags: F) => F;
@@ -41,10 +41,24 @@ export const provide = (program, environment) => {
41
41
  environments.set(program, environment);
42
42
  };
43
43
  export const environmentOf = (command) => (environments.get(rootOf(command)) ?? {});
44
- /** The command's flags with an MCP server's `--permission` levels first: they reach a run on its agent, never in argv. */
44
+ const PAGING = ["page", "limit", "all"];
45
+ /** A generated API command's own `--page`, `--limit` or `--all` is the service's parameter, not the CLI's paging. */
46
+ export const withoutOwnPaging = (command, flags) => {
47
+ if (metaOf(command).origin !== "generated")
48
+ return flags;
49
+ const own = PAGING.filter((name) => command.options.some((option) => option.attributeName() === name));
50
+ return own.length > 0
51
+ ? Object.fromEntries(Object.entries(flags).filter(([name]) => !own.includes(name)))
52
+ : flags;
53
+ };
54
+ /**
55
+ * The command's flags as settings read them, an MCP server's `--permission` levels first: they reach a run on its
56
+ * agent, never in argv.
57
+ */
45
58
  export const withAgentLevels = (command, flags) => {
46
59
  const overrides = environmentOf(command).agent?.overrides ?? [];
47
- return overrides.length > 0 ? { ...flags, permission: [...overrides, ...(flags.permission ?? [])] } : flags;
60
+ const read = withoutOwnPaging(command, flags);
61
+ return overrides.length > 0 ? { ...read, permission: [...overrides, ...(read.permission ?? [])] } : read;
48
62
  };
49
63
  /**
50
64
  * The input and output `readSecret` uses for this command: the run's own, so a prompt goes where the run's other
@@ -1,3 +1,3 @@
1
1
  export { type DocumentCommandsFixture, documentCommandsContract, SHARED_DOCUMENT_PATHS, SHARED_MIRROR_PATHS, } from "./commands-contract.js";
2
2
  export { FAKE_FOLDER, type FakeDocumentSource, fakeDocumentSource, fakeFile } from "./source.js";
3
- export { type DocumentSourceFixture, documentSourceContract } from "./source-contract.js";
3
+ export { type DocumentFaultRun, type DocumentSourceFaults, type DocumentSourceFixture, documentSourceContract, } from "./source-contract.js";
@@ -1,3 +1,3 @@
1
1
  export { documentCommandsContract, SHARED_DOCUMENT_PATHS, SHARED_MIRROR_PATHS, } from "./commands-contract.js";
2
2
  export { FAKE_FOLDER, fakeDocumentSource, fakeFile } from "./source.js";
3
- export { documentSourceContract } from "./source-contract.js";
3
+ export { documentSourceContract, } from "./source-contract.js";
@@ -1,5 +1,36 @@
1
- import type { DocumentSource, SourceFile } from "../../../documents.js";
1
+ import { type Deadline, type RunBudget } from "../../../background/budget.js";
2
+ import type { DocumentSource, SourceFile, SyncResult } from "../../../documents.js";
2
3
  import type { ContractCase } from "../../../meetings/index.js";
4
+ /** What one sync of a fault case may be given: the CLI passes each on to `syncDocuments`. */
5
+ export interface DocumentFaultRun<M extends SourceFile = SourceFile> {
6
+ /** Wraps the source the CLI builds for this run: the case counts its calls, slows them or cuts them off. */
7
+ wrap(source: DocumentSource<M>): DocumentSource<M>;
8
+ budget?: RunBudget;
9
+ deadline?: Deadline;
10
+ signal?: AbortSignal;
11
+ now?(): number;
12
+ }
13
+ /** Faults a case injects; each is opt-in, and a case whose hook is absent passes without running. */
14
+ export interface DocumentSourceFaults<M extends SourceFile = SourceFile> {
15
+ /**
16
+ * Makes one document below the root answer HTTP `status` from now on, as the provider would, and names it. It stays
17
+ * listed in its folder, and the fixture holds at least one other document that still answers.
18
+ */
19
+ deny?(status: 403 | 404): string | Promise<string>;
20
+ /** A source over the same provider whose own clock runs `ms` ahead of the provider's, behind when negative. */
21
+ skewed?(ms: number): DocumentSource<M> | Promise<DocumentSource<M>>;
22
+ /** A source for a second profile signed in with the same token. */
23
+ sameToken?(): DocumentSource<M> | Promise<DocumentSource<M>>;
24
+ /**
25
+ * The CLI's own sync of the root over this fixture's provider, its state and index kept between calls, and the ids
26
+ * it holds after the call, all calls together. Given, the cases also check a sync: a fault skipped, an interrupted run resumed, the
27
+ * MCP deadline kept.
28
+ */
29
+ sync?(run: DocumentFaultRun<M>): Promise<{
30
+ result: SyncResult;
31
+ saved: readonly string[];
32
+ }>;
33
+ }
3
34
  /** One adapter over recorded or faked responses, fresh for each case. */
4
35
  export interface DocumentSourceFixture<M extends SourceFile = SourceFile> {
5
36
  source: DocumentSource<M>;
@@ -22,6 +53,8 @@ export interface DocumentSourceFixture<M extends SourceFile = SourceFile> {
22
53
  }>;
23
54
  /** An id the provider does not know; absent skips that case. */
24
55
  missing?: string;
56
+ /** Faults for the opt-in fault cases. */
57
+ faults?: DocumentSourceFaults<M>;
25
58
  }
26
59
  /** What every documents adapter answers, whatever the provider: run each case in the adapter's tests. */
27
60
  export declare const documentSourceContract: <M extends SourceFile>(make: () => DocumentSourceFixture<M> | Promise<DocumentSourceFixture<M>>) => ContractCase[];
@@ -1,5 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { isCliError } from "@wirecat/cli-base";
3
+ import { runBudget } from "../../../background/budget.js";
4
+ import { DEFAULT_AGENT_COOPERATIVE_MS } from "../../execution.js";
3
5
  const MAX_ENTRIES = 500;
4
6
  const walk = async ({ source, root, isFolder }) => {
5
7
  const seen = new Map();
@@ -21,6 +23,44 @@ const walk = async ({ source, root, isFolder }) => {
21
23
  /** What the sync imports: a file, or a folder the provider calls a document too. */
22
24
  const isImported = (fixture, entry) => !fixture.isFolder(entry) || fixture.isDocument?.(entry) === true;
23
25
  const isTime = (value) => value === undefined || !Number.isNaN(Date.parse(value));
26
+ /** Within any change feed's overlap: a computer's clock that is off by more is broken, not skewed. */
27
+ const SKEW_MS = 10 * 60_000;
28
+ /** Slow enough that a run under the MCP deadline cannot read the fixture's tree in one go. */
29
+ const SLOW_CALL_MS = 15_000;
30
+ const MOST_SYNCS = 50;
31
+ const READS = new Set(["metadata", "children", "childrenPage", "content", "bytes", "startToken", "changes"]);
32
+ /** The source with `before` run ahead of each provider read: the case counts, slows or cuts off the calls. */
33
+ const watched = (source, before) => new Proxy(source, {
34
+ get(target, name) {
35
+ const value = Reflect.get(target, name);
36
+ if (typeof value !== "function")
37
+ return value;
38
+ // Bound to the adapter itself: a class with #private fields refuses a proxy as `this`.
39
+ if (!READS.has(String(name)))
40
+ return value.bind(target);
41
+ return (...args) => {
42
+ before();
43
+ return value.apply(target, args);
44
+ };
45
+ },
46
+ });
47
+ /**
48
+ * Syncs until the walk is done and nothing is left but reported errors, and gives the last call's answer and ids and
49
+ * how many reads the calls made. A file the provider refuses stays pending with its error, sync after sync.
50
+ */
51
+ const finish = async (sync) => {
52
+ let reads = 0;
53
+ for (let call = 1; call <= MOST_SYNCS; call++) {
54
+ const { result, saved } = await sync({
55
+ wrap: (source) => watched(source, () => {
56
+ reads++;
57
+ }),
58
+ });
59
+ if (!result.walk && result.pending === result.errors.length)
60
+ return { result, saved: [...saved].sort(), reads };
61
+ }
62
+ throw new assert.AssertionError({ message: `the sync is still unfinished after ${MOST_SYNCS} calls` });
63
+ };
24
64
  /** What every documents adapter answers, whatever the provider: run each case in the adapter's tests. */
25
65
  export const documentSourceContract = (make) => {
26
66
  const cases = [
@@ -151,5 +191,117 @@ export const documentSourceContract = (make) => {
151
191
  await assert.rejects(source.metadata(missing), (error) => isCliError(error) && error.code === "not_found");
152
192
  },
153
193
  });
154
- return cases;
194
+ return [...cases, ...faultCases(make)];
155
195
  };
196
+ const faultCases = (make) => [
197
+ ...[403, 404].map((status) => ({
198
+ name: `faults: a child that answers ${status} is ${status === 403 ? "permission_error" : "not_found"}, and a sync skips it and imports the rest`,
199
+ async run() {
200
+ const fixture = await make();
201
+ const deny = fixture.faults?.deny;
202
+ if (!deny)
203
+ return;
204
+ const id = await deny(status);
205
+ const code = status === 403 ? "permission_error" : "not_found";
206
+ await assert.rejects(fixture.source.content(id), (error) => isCliError(error) && error.code === code, `content(${id}) after a ${status} is ${code}`);
207
+ const sync = fixture.faults?.sync;
208
+ if (!sync)
209
+ return;
210
+ const { result, saved } = await finish(sync);
211
+ assert.ok(!saved.includes(id), `the sync does not hold ${id}, which answers ${status}`);
212
+ assert.ok(saved.length > 0, `the sync imports the documents that still answer beside ${id}`);
213
+ if (status === 403)
214
+ assert.ok([...result.errors, ...result.skipped].some((one) => one.id === id), `the sync names ${id} among its errors or skipped files, not silently left out`);
215
+ },
216
+ })),
217
+ {
218
+ name: "faults: a clock off by ten minutes either way loses no change",
219
+ async run() {
220
+ const first = await make();
221
+ if (!first.faults?.skewed || !first.change)
222
+ return;
223
+ for (const ms of [SKEW_MS, -SKEW_MS]) {
224
+ const fixture = ms === SKEW_MS ? first : await make();
225
+ const source = (await fixture.faults?.skewed?.(ms));
226
+ const token = await source.startToken();
227
+ await fixture.change?.();
228
+ const page = await source.changes(token);
229
+ assert.ok(page.items.length > 0, `a change is in the feed with this computer's clock ${ms / 60_000} min off`);
230
+ }
231
+ },
232
+ },
233
+ {
234
+ name: "faults: a second profile on the same token is the same account and sees the same tree",
235
+ async run() {
236
+ const fixture = await make();
237
+ const other = await fixture.faults?.sameToken?.();
238
+ if (!other)
239
+ return;
240
+ assert.equal(await other.identity(), await fixture.source.identity(), "both profiles name one account");
241
+ const ids = async (source) => (await walk({ ...fixture, source })).map((entry) => entry.id).sort();
242
+ assert.deepEqual(await ids(other), await ids(fixture.source), "both profiles list the same tree");
243
+ },
244
+ },
245
+ {
246
+ name: "faults: an interrupted sync goes on where it stopped and ends with what one whole sync holds",
247
+ async run() {
248
+ const whole = await make();
249
+ if (!whole.faults?.sync)
250
+ return;
251
+ const expected = await finish(whole.faults.sync);
252
+ const fixture = await make();
253
+ const sync = fixture.faults?.sync;
254
+ const stop = new AbortController();
255
+ let reads = 0;
256
+ const cut = await sync({
257
+ signal: stop.signal,
258
+ wrap: (source) => watched(source, () => {
259
+ if (++reads > 2)
260
+ stop.abort();
261
+ }),
262
+ }).then(({ result }) => result.complete === false, (error) => {
263
+ if (!stop.signal.aborted)
264
+ throw error;
265
+ return true;
266
+ });
267
+ assert.ok(stop.signal.aborted, "the fixture's tree takes more than two reads, so the run is cut short");
268
+ assert.ok(cut, "the cut run stops: it is cancelled or answers complete: false, it does not read on");
269
+ const resumed = await finish(sync);
270
+ assert.deepEqual(resumed.saved, expected.saved, "the resumed sync holds what one whole sync does");
271
+ assert.ok(resumed.reads < expected.reads, "the resumed sync reads less than a whole one: it went on, not over");
272
+ },
273
+ },
274
+ {
275
+ name: "faults: under the MCP's 45 s deadline a slow provider's sync stops in time, and the next goes on",
276
+ async run() {
277
+ const whole = await make();
278
+ if (!whole.faults?.sync)
279
+ return;
280
+ const expected = await finish(whole.faults.sync);
281
+ const fixture = await make();
282
+ const sync = fixture.faults?.sync;
283
+ let clock = 0;
284
+ const now = () => clock;
285
+ let stopped = false;
286
+ for (let call = 1; call <= MOST_SYNCS; call++) {
287
+ const deadline = { endsAt: clock + DEFAULT_AGENT_COOPERATIVE_MS, ms: DEFAULT_AGENT_COOPERATIVE_MS };
288
+ const { result, saved } = await sync({
289
+ budget: runBudget({ deadline, now, requestMs: SLOW_CALL_MS }),
290
+ deadline,
291
+ now,
292
+ wrap: (source) => watched(source, () => {
293
+ clock += SLOW_CALL_MS;
294
+ }),
295
+ });
296
+ assert.ok(clock <= deadline.endsAt, `sync ${call} ended by its deadline, ${clock - deadline.endsAt} ms late`);
297
+ if (!result.walk && result.pending === result.errors.length) {
298
+ assert.ok(stopped, "a slow provider's tree takes more than one run under the deadline");
299
+ assert.deepEqual([...saved].sort(), expected.saved, "the runs together hold what one whole sync does");
300
+ return;
301
+ }
302
+ stopped = true;
303
+ }
304
+ throw new assert.AssertionError({ message: `the sync is still unfinished after ${MOST_SYNCS} runs` });
305
+ },
306
+ },
307
+ ];
@@ -8,6 +8,8 @@ export interface FakeDocumentSource extends DocumentSource {
8
8
  put(file: SourceFile, text?: string): void;
9
9
  /** Takes one out, and lists it as removed in the next change feed. */
10
10
  remove(id: string): void;
11
+ /** Makes one file answer as a provider's 403 or 404 does, from now on. */
12
+ deny(id: string, status: 403 | 404): void;
11
13
  }
12
14
  /**
13
15
  * A provider in memory: a root folder, a nested folder and two text files, with a change feed and a cursor. With
@@ -21,8 +21,12 @@ export const fakeDocumentSource = (account = "alpha", options = {}) => {
21
21
  const texts = new Map();
22
22
  let feed = [];
23
23
  let cursor = 0;
24
+ const denied = new Map();
24
25
  const metadata = async (id) => {
25
- const found = files.get(id);
26
+ const status = denied.get(id);
27
+ if (status === 403)
28
+ throw new CliError("permission_error", "the synthetic file is not shared with this account");
29
+ const found = status === 404 ? undefined : files.get(id);
26
30
  if (!found)
27
31
  throw new CliError("not_found", "no such synthetic file", { reason: "document.not-found" });
28
32
  return structuredClone(found);
@@ -37,6 +41,9 @@ export const fakeDocumentSource = (account = "alpha", options = {}) => {
37
41
  texts.set(file.id, text);
38
42
  feed.push({ id: file.id, removed: false, file: structuredClone(file) });
39
43
  },
44
+ deny(id, status) {
45
+ denied.set(id, status);
46
+ },
40
47
  remove(id) {
41
48
  files.delete(id);
42
49
  texts.delete(id);
@@ -10,6 +10,7 @@ export { documentEntry, documentEntryDetails, documentSource, LISTING_ENTITIES,
10
10
  export { syncProgress } from "../entities/store-records.js";
11
11
  export { isCliFailure, isCommanderFailure, storeDamaged } from "../errors/failures.js";
12
12
  export { type AppErrors, failureContext } from "../errors/reasons.js";
13
+ export { linkFetch } from "../http/link-fetch.js";
13
14
  export { mailFindingFieldsHelp } from "../mail/findings.js";
14
15
  export { botInstructions } from "../mcp/bot/instructions.js";
15
16
  export type { BotServerOptions, RunBotCommand } from "../mcp/bot/server.js";
@@ -79,7 +80,7 @@ export type { AppCompletionOptions, CompletionRequest } from "./complete-command
79
80
  export { refuseUnknownKey } from "./config-command.js";
80
81
  export { type ConfigIssue, type ConfigIssueKind, checkConfigText, issueMessage, readConfigFile, readConfigText, settingPathOf, withoutSetting, } from "./config-issues.js";
81
82
  export { loadSnakeCaseConfig } from "./config-keys.js";
82
- export { type AgentRun, type BaseContext, type BaseEnvironment, baseContext, environmentOf, inCommandRun, outputFor, provide, runBudgetOf, secretInputOf, withAgentLevels, } from "./context.js";
83
+ export { type AgentRun, type BaseContext, type BaseEnvironment, baseContext, environmentOf, inCommandRun, outputFor, provide, runBudgetOf, secretInputOf, withAgentLevels, withoutOwnPaging, } from "./context.js";
83
84
  export { addContractInfo, type ContractEvidenceOptions, contractEvidence } from "./contract-evidence.js";
84
85
  export { sharedCommandTemplate } from "./contract-templates.js";
85
86
  export { csvCell, csvRecords, writeCsv } from "./csv.js";
@@ -150,7 +151,8 @@ export { fieldsOf, projectFields } from "./result-fields.js";
150
151
  export { HARNESSES, type Harness, harnessesOn, harnessInfo, harnessOfArgv, isHarness, reportsCost, } from "./schedule/harnesses.js";
151
152
  export { type AgentScheduleSpec, agentSchedule, backfillScheduleRun, pauseSchedule, removeSchedule, runScheduleNow, SCHEDULE_SETTINGS, type ScheduleHost, type ScheduleLimits, type ScheduleSite, scheduleLimitsOf, scheduleState, slotsOfAt, writeSchedule, } from "./schedule/schedule-command.js";
152
153
  export { deniedKinds, deniedKindsOf, type LeftOut, type SearchedKind } from "./search-left-out.js";
153
- export { type ServiceApiOperation, type ServiceApiOptions, type ServiceApiPermissionsInput, serviceApiDeletes, serviceApiPermissions, } from "./service-api.js";
154
+ export { type BodyPermission, type ServiceApiOptions, type ServiceApiPermissionsInput, serviceApiKeys, serviceApiPermissions, } from "./service-api.js";
155
+ export { manifestBaseUrl, type ServiceApiManifest } from "./service-api-manifest.js";
154
156
  export { type DeclaredSetting, type SettingRow, settingRows, withSettingDefaults } from "./setting-defaults.js";
155
157
  export { type Config, type Configuration, count, first, flag, fromFile, type GlobalFlags, NONE_NAMED, namedProfile, type ProfileKind, plain, type ResolveOptions, type Settings, type SettingsExtension, type SettingsExtensionContext, type Source, settingsFor, } from "./settings.js";
156
158
  export { type PermissionAnswer, readSetupAnswers, type SetupAnswers, setupPermissionCeiling } from "./setup-answers.js";
package/dist/cli/index.js CHANGED
@@ -10,6 +10,7 @@ export { documentEntry, documentEntryDetails, documentSource, LISTING_ENTITIES,
10
10
  export { syncProgress } from "../entities/store-records.js";
11
11
  export { isCliFailure, isCommanderFailure, storeDamaged } from "../errors/failures.js";
12
12
  export { failureContext } from "../errors/reasons.js";
13
+ export { linkFetch } from "../http/link-fetch.js";
13
14
  export { mailFindingFieldsHelp } from "../mail/findings.js";
14
15
  export { botInstructions } from "../mcp/bot/instructions.js";
15
16
  export { callMeetingPreparationTool, meetingPreparationTool } from "../mcp/meeting-preparation.js";
@@ -70,7 +71,7 @@ export { compactText, entityRows, GENERIC_ROW, rowShapeOf, rowsOfEntity, SHARED_
70
71
  export { refuseUnknownKey } from "./config-command.js";
71
72
  export { checkConfigText, issueMessage, readConfigFile, readConfigText, settingPathOf, withoutSetting, } from "./config-issues.js";
72
73
  export { loadSnakeCaseConfig } from "./config-keys.js";
73
- export { baseContext, environmentOf, inCommandRun, outputFor, provide, runBudgetOf, secretInputOf, withAgentLevels, } from "./context.js";
74
+ export { baseContext, environmentOf, inCommandRun, outputFor, provide, runBudgetOf, secretInputOf, withAgentLevels, withoutOwnPaging, } from "./context.js";
74
75
  export { addContractInfo, contractEvidence } from "./contract-evidence.js";
75
76
  export { sharedCommandTemplate } from "./contract-templates.js";
76
77
  export { csvCell, csvRecords, writeCsv } from "./csv.js";
@@ -139,7 +140,8 @@ export { fieldsOf, projectFields } from "./result-fields.js";
139
140
  export { HARNESSES, harnessesOn, harnessInfo, harnessOfArgv, isHarness, reportsCost, } from "./schedule/harnesses.js";
140
141
  export { agentSchedule, backfillScheduleRun, pauseSchedule, removeSchedule, runScheduleNow, SCHEDULE_SETTINGS, scheduleLimitsOf, scheduleState, slotsOfAt, writeSchedule, } from "./schedule/schedule-command.js";
141
142
  export { deniedKinds, deniedKindsOf } from "./search-left-out.js";
142
- export { serviceApiDeletes, serviceApiPermissions, } from "./service-api.js";
143
+ export { serviceApiKeys, serviceApiPermissions, } from "./service-api.js";
144
+ export { manifestBaseUrl } from "./service-api-manifest.js";
143
145
  export { settingRows, withSettingDefaults } from "./setting-defaults.js";
144
146
  export { count, first, flag, fromFile, NONE_NAMED, namedProfile, plain, settingsFor, } from "./settings.js";
145
147
  export { readSetupAnswers, setupPermissionCeiling } from "./setup-answers.js";
@@ -1,4 +1,4 @@
1
- import { CliError, Credentials, isMovedRun, resolvePaths, } from "@wirecat/cli-base";
1
+ import { CliError, Credentials, isCliError, isMovedRun, resolvePaths, } from "@wirecat/cli-base";
2
2
  import { envName } from "../ports/app.js";
3
3
  /**
4
4
  * What one profile's entry holds when it keeps more than its token: the token and named secrets, as one JSON value
@@ -81,8 +81,7 @@ export class ProfileTokenStore {
81
81
  }
82
82
  /** The token; the profile's named secrets stay as they were. */
83
83
  write(profile, token, storage = "keyring") {
84
- const held = this.#held(profile);
85
- return this.#put(profile, { ...held, token }, storage);
84
+ return this.#put(profile, { ...this.#heldUnlessUnreachable(profile), token }, storage);
86
85
  }
87
86
  /** The token and every named secret: the whole entry, as `session end` wants. */
88
87
  remove(profile) {
@@ -127,6 +126,17 @@ export class ProfileTokenStore {
127
126
  #held(profile) {
128
127
  return unpack(this.#stored.read(accountOf(profile))?.secret);
129
128
  }
129
+ /** A sign-in must still land, in the file, when the keyring does not answer; what the keyring held stays there. */
130
+ #heldUnlessUnreachable(profile) {
131
+ try {
132
+ return this.#held(profile);
133
+ }
134
+ catch (error) {
135
+ if (isCliError(error) && error.details.reason === "keyring.unreachable")
136
+ return unpack(undefined);
137
+ throw error;
138
+ }
139
+ }
130
140
  /** `file` also forgets the keyring copy, so a later read cannot find the secret the owner asked to keep elsewhere. */
131
141
  #put(profile, held, storage) {
132
142
  const value = pack(held);
@@ -22,7 +22,7 @@ import { commandPathOf } from "./command-contract.js";
22
22
  import { enterCommandServer } from "./command-server.js";
23
23
  import { exitCodeSet } from "./command-server-request.js";
24
24
  import { entityRows } from "./compact.js";
25
- import { outputFieldsOf, outputFor, provide } from "./context.js";
25
+ import { outputFieldsOf, outputFor, provide, withoutOwnPaging } from "./context.js";
26
26
  import { refuseByCommandPermissions, refuseOfflineCommand, refuseWriteBeforeConnecting } from "./early-refusal.js";
27
27
  import { admittedUnderLock, changesAuthorityAt, changesAuthorityNow, fetchesOnlyAt, fileOptionOf, isLogin, isStoreChange, judgedEffects, judgedTargets, storeChangeRefusal, } from "./effects.js";
28
28
  import { itemOf, renderAnswer, snakeKeys } from "./envelope.js";
@@ -272,7 +272,8 @@ const runOnce = async (argv, definition, options) => {
272
272
  runCommand: (words, given) => run(words, definition, given),
273
273
  discoveryAvailability: (info) => {
274
274
  const inspected = info.path.reduce((parent, word) => parent?.commands.find((one) => one.name() === word), program);
275
- const flags = (inspected ?? program).optsWithGlobals();
275
+ const shown = inspected ?? program;
276
+ const flags = withoutOwnPaging(shown, shown.optsWithGlobals());
276
277
  const env = options.env ?? process.env;
277
278
  if (!flags.profile && !env[envName(definition.app, "PROFILE")])
278
279
  return undefined;
@@ -308,6 +309,7 @@ const runOnce = async (argv, definition, options) => {
308
309
  provide(program, environment);
309
310
  program.hook("preAction", async (_root, action) => {
310
311
  const flags = action.optsWithGlobals();
312
+ const own = withoutOwnPaging(action, flags);
311
313
  const commandEnv = options.env ?? process.env;
312
314
  const argvLog = commandEnv[envName(definition.app, "TEST_ARGV_LOG")];
313
315
  if (argvLog)
@@ -412,7 +414,7 @@ const runOnce = async (argv, definition, options) => {
412
414
  process.on("SIGINT", sigint).on("SIGTERM", sigterm);
413
415
  const target = options.relayed || options.agent || flags.dryRun
414
416
  ? undefined
415
- : relayTarget(definition.app, action, flags, () => (definition.configuration ?? settingsFor(definition.app)).resolveSettings(flags, {
417
+ : relayTarget(definition.app, action, flags, () => (definition.configuration ?? settingsFor(definition.app)).resolveSettings(own, {
416
418
  env: commandEnv,
417
419
  needsProfile: false,
418
420
  readOnly: true,
@@ -461,7 +463,7 @@ const runOnce = async (argv, definition, options) => {
461
463
  throw control.failure();
462
464
  }
463
465
  if (flags.dryRun && !localPreview) {
464
- const resolved = (definition.configuration ?? settingsFor(definition.app)).resolveSettings(flags, {
466
+ const resolved = (definition.configuration ?? settingsFor(definition.app)).resolveSettings(own, {
465
467
  kind: path[0] === "bot" ? "bot" : "personal",
466
468
  env: options.env ?? process.env,
467
469
  readOnly: true,