@wirecat/cli-core 0.683.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 (55) hide show
  1. package/CHANGELOG.md +89 -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 +5 -2
  13. package/dist/cli/index.js +5 -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 +73 -0
  19. package/dist/cli/service-api.js +260 -0
  20. package/dist/cli/shared-command-exports.d.ts +1 -0
  21. package/dist/cli/shared-command-exports.js +2 -0
  22. package/dist/crm/cli/index.js +25 -38
  23. package/dist/crm/digest.d.ts +1 -1
  24. package/dist/crm/digest.js +9 -1
  25. package/dist/crm/index.d.ts +1 -1
  26. package/dist/crm/index.js +1 -1
  27. package/dist/crm/testing/index.d.ts +1 -1
  28. package/dist/crm/testing/source-contract.d.ts +26 -1
  29. package/dist/crm/testing/source-contract.js +102 -0
  30. package/dist/crm/testing/source.d.ts +2 -0
  31. package/dist/crm/testing/source.js +6 -0
  32. package/dist/crm/viewer.d.ts +14 -1
  33. package/dist/crm/viewer.js +38 -1
  34. package/dist/http/link-fetch.d.ts +10 -0
  35. package/dist/http/link-fetch.js +28 -0
  36. package/dist/meetings/import.d.ts +1 -1
  37. package/dist/meetings/import.js +2 -0
  38. package/dist/meetings/index.d.ts +1 -0
  39. package/dist/meetings/index.js +1 -0
  40. package/dist/meetings/pull.d.ts +2 -0
  41. package/dist/meetings/pull.js +18 -0
  42. package/dist/meetings/search-store.d.ts +2 -0
  43. package/dist/meetings/search-store.js +16 -1
  44. package/dist/meetings/store.d.ts +3 -0
  45. package/dist/oauth/requests.js +48 -13
  46. package/dist/services/deal-context.d.ts +1 -1
  47. package/dist/services/deal-context.js +2 -1
  48. package/dist/services/meeting-hit-search.d.ts +2 -3
  49. package/dist/services/meeting-hit-search.js +2 -17
  50. package/dist/services/organization-context.js +22 -12
  51. package/dist/services/search-all-meetings.d.ts +1 -1
  52. package/dist/store/sqlite/crm-activities.js +9 -3
  53. package/dist/store/sqlite/deals.d.ts +0 -2
  54. package/dist/store/sqlite/deals.js +0 -1
  55. package/package.json +3 -3
@@ -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,
@@ -0,0 +1,40 @@
1
+ import type { ApiServer, ManifestOperation, Pagination, SecurityRequirement, SecurityScheme } from "@wirecat/cli-base/codegen";
2
+ import type { ApiCommandInput } from "./bot/api.js";
3
+ /** What `generate` writes into a CLI's `generated/manifest.ts`: `import * as manifest from "./generated/manifest.js"`. */
4
+ export interface ServiceApiManifest {
5
+ operations: readonly ManifestOperation[];
6
+ servers?: readonly ApiServer[];
7
+ securitySchemes?: Readonly<Record<string, SecurityScheme>>;
8
+ security?: readonly SecurityRequirement[];
9
+ }
10
+ /**
11
+ * The first server the spec names. A variable is filled with its default only when its `enum` lists the choices: a
12
+ * free one (`{subdomain}`) names the owner's own host, which the default would send the token past.
13
+ */
14
+ export declare const manifestBaseUrl: (manifest: ServiceApiManifest, given?: string) => string;
15
+ type Auth = {
16
+ name: string;
17
+ value: (token: string) => string;
18
+ };
19
+ /**
20
+ * The header that carries the sign-in for one operation, from the first scheme of its requirements the api can send;
21
+ * `undefined` for one that needs none (`security: []`, or only `{}`). A manifest without schemes signs in with a bearer
22
+ * token, as most services do. An optional sign-in (`[{}, { oauth: [] }]`) still sends the token.
23
+ */
24
+ export declare const authHeader: (manifest: ServiceApiManifest, operation: ManifestOperation) => Auth | undefined;
25
+ export declare const parameterValue: (input: ApiCommandInput, parameter: {
26
+ in: "query" | "body";
27
+ name: string;
28
+ }) => unknown;
29
+ /** One page's items, and how to ask for the next: new flags, the next page's whole URL, or `undefined` at the end. */
30
+ export interface PageStep {
31
+ items: readonly unknown[];
32
+ next?: {
33
+ input: ApiCommandInput;
34
+ } | {
35
+ url: string;
36
+ };
37
+ }
38
+ /** Reads one answer by the manifest's pagination: where its items are and what the next request is. */
39
+ export declare const nextPage: (pagination: Pagination, input: ApiCommandInput, answer: unknown) => PageStep;
40
+ export {};
@@ -0,0 +1,106 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { apiJson, parseApiJson } from "./bot/api-input.js";
3
+ /**
4
+ * The first server the spec names. A variable is filled with its default only when its `enum` lists the choices: a
5
+ * free one (`{subdomain}`) names the owner's own host, which the default would send the token past.
6
+ */
7
+ export const manifestBaseUrl = (manifest, given) => {
8
+ const server = manifest.servers?.[0];
9
+ if (given === undefined && !server)
10
+ throw new CliError("configuration_error", "the manifest names no server; give the api a baseUrl");
11
+ const url = given ??
12
+ server.url.replace(/\{([^}]+)\}/g, (_, name) => {
13
+ const variable = server?.variables?.[name];
14
+ if (variable?.default === undefined || !variable.enum?.includes(variable.default))
15
+ throw new CliError("configuration_error", `the server's {${name}} is the owner's own; give the api a baseUrl`);
16
+ return variable.default;
17
+ });
18
+ if (!/^https:\/\//.test(url))
19
+ throw new CliError("configuration_error", `the api's server ${url} is not https`);
20
+ return url;
21
+ };
22
+ const BEARER = { name: "authorization", value: (token) => `Bearer ${token}` };
23
+ /** The header one scheme signs in with; `undefined` for one the api cannot send (basic, a key in the query). */
24
+ const headerOf = (scheme) => {
25
+ if (scheme.type === "apiKey")
26
+ return scheme.in === "header" && scheme.name
27
+ ? { name: scheme.name.toLowerCase(), value: (token) => token }
28
+ : undefined;
29
+ if (scheme.type === "http") {
30
+ if (!scheme.scheme || /^bearer$/i.test(scheme.scheme))
31
+ return BEARER;
32
+ return /^(basic|digest)$/i.test(scheme.scheme)
33
+ ? undefined
34
+ : { name: "authorization", value: (token) => `${scheme.scheme} ${token}` };
35
+ }
36
+ return scheme.type === "oauth2" || scheme.type === "openIdConnect" ? BEARER : undefined;
37
+ };
38
+ /**
39
+ * The header that carries the sign-in for one operation, from the first scheme of its requirements the api can send;
40
+ * `undefined` for one that needs none (`security: []`, or only `{}`). A manifest without schemes signs in with a bearer
41
+ * token, as most services do. An optional sign-in (`[{}, { oauth: [] }]`) still sends the token.
42
+ */
43
+ export const authHeader = (manifest, operation) => {
44
+ const requirements = operation.security ?? manifest.security;
45
+ if (requirements?.every((one) => Object.keys(one).length === 0))
46
+ return undefined;
47
+ if (!manifest.securitySchemes)
48
+ return BEARER;
49
+ const names = (requirements ?? []).flatMap((one) => Object.keys(one));
50
+ for (const name of names) {
51
+ const scheme = manifest.securitySchemes[name];
52
+ const auth = scheme && headerOf(scheme);
53
+ if (auth)
54
+ return auth;
55
+ }
56
+ if (names.length === 0)
57
+ return BEARER;
58
+ throw new CliError("configuration_error", `${operation.command} signs in by ${names.join(" or ")}, which the api cannot send`);
59
+ };
60
+ const at = (value, path) => path
61
+ .split(".")
62
+ .reduce((inner, key) => (inner && typeof inner === "object" ? inner[key] : undefined), value);
63
+ const numberOf = (value) => {
64
+ const number = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number(String(value));
65
+ return Number.isFinite(number) ? number : undefined;
66
+ };
67
+ export const parameterValue = (input, parameter) => parameter.in === "query"
68
+ ? input.query[parameter.name]
69
+ : input.body === undefined
70
+ ? undefined
71
+ : parseApiJson(input.body)?.[parameter.name];
72
+ const withValue = (input, parameter, value) => {
73
+ if (parameter.in === "query")
74
+ return { ...input, query: { ...input.query, [parameter.name]: String(value) } };
75
+ const body = input.body === undefined ? {} : parseApiJson(input.body);
76
+ return { ...input, body: apiJson({ ...body, [parameter.name]: value }) };
77
+ };
78
+ /** Reads one answer by the manifest's pagination: where its items are and what the next request is. */
79
+ export const nextPage = (pagination, input, answer) => {
80
+ const listed = pagination.items === undefined ? [answer] : at(answer, pagination.items);
81
+ const items = Array.isArray(listed) ? listed : [];
82
+ switch (pagination.style) {
83
+ case "cursor": {
84
+ const cursor = at(answer, pagination.next);
85
+ const more = pagination.hasMore === undefined || at(answer, pagination.hasMore) !== false;
86
+ return more && typeof cursor === "string" && cursor !== ""
87
+ ? { items, next: { input: withValue(input, pagination.cursor, cursor) } }
88
+ : { items };
89
+ }
90
+ case "offset":
91
+ case "page": {
92
+ const parameter = pagination.style === "offset" ? pagination.offset : pagination.page;
93
+ const total = pagination.total === undefined ? undefined : numberOf(at(answer, pagination.total));
94
+ const current = numberOf(parameterValue(input, parameter)) ?? (pagination.style === "offset" ? 0 : 1);
95
+ const next = pagination.style === "offset" ? current + items.length : current + 1;
96
+ // A short page is not the last: a service may cap the page below the limit asked for. Only a total or an
97
+ // empty page ends it.
98
+ const last = items.length === 0 || (total !== undefined && pagination.style === "offset" && next >= total);
99
+ return last ? { items } : { items, next: { input: withValue(input, parameter, next) } };
100
+ }
101
+ case "link": {
102
+ const url = at(answer, pagination.next);
103
+ return typeof url === "string" && url !== "" ? { items, next: { url } } : { items };
104
+ }
105
+ }
106
+ };
@@ -0,0 +1,73 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import type { ManifestOperation, SchemaNode } from "@wirecat/cli-base/codegen";
3
+ import type { FetchLike } from "@wirecat/cli-base/http";
4
+ import { Command } from "commander";
5
+ import type * as v from "valibot";
6
+ import type { AppIdentity } from "../ports/app.js";
7
+ import type { Level, PermissionKey } from "../sends/permissions.js";
8
+ import { type ApiCommandInput } from "./bot/api.js";
9
+ import type { ConditionalKey } from "./permission-keys.js";
10
+ import { type ServiceApiManifest } from "./service-api-manifest.js";
11
+ import type { Configuration } from "./settings.js";
12
+ /** A key a call's body implies in a way no flag names, as notion's `agent-batch` with an action `delete`. */
13
+ export interface BodyPermission {
14
+ key: PermissionKey;
15
+ /** When it applies, in a few words, for `--dry-run` and discovery. */
16
+ when: string;
17
+ /** The body parsed by lossless-json: a number is a `LosslessNumber`. */
18
+ applies: (body: unknown) => boolean;
19
+ }
20
+ /** What both halves of the group, the permissions and the command, are built from. */
21
+ export interface ServiceApiPermissionsInput {
22
+ manifest: ServiceApiManifest;
23
+ /** By command name: keys beside the manifest's `permissions`, for a body the generator cannot read. */
24
+ bodyPermissions?: Readonly<Record<string, readonly BodyPermission[]>>;
25
+ }
26
+ export interface ServiceApiOptions extends ServiceApiPermissionsInput {
27
+ app: AppIdentity;
28
+ configuration: Configuration;
29
+ /** The service's name in messages: "Notion". */
30
+ service: string;
31
+ /** In place of the manifest's first server. */
32
+ baseUrl?: string;
33
+ /** The host-checked fetch with the CLI's pace and its retry of reads (cli-base `retrying` over `hostFetch`). */
34
+ fetch: (command: Command) => FetchLike;
35
+ /** The profile's token, sent in the header the operation's security scheme names. Read before any guard asks. */
36
+ token: (command: Command) => string | Promise<string>;
37
+ /** Headers beside the sign-in, such as the API version. */
38
+ headers?: (command: Command, operation: ManifestOperation) => Record<string, string>;
39
+ /** Loaded only once an operation is about to check its input: a large spec is megabytes of code. */
40
+ schemas: () => Promise<Readonly<Record<string, v.GenericSchema>>>;
41
+ /** Loaded only by `api show`. */
42
+ definitions: () => Promise<Readonly<Record<string, SchemaNode>>>;
43
+ /** Operations the spec has and the CLI does not offer, each with why; `api show` names the reason. */
44
+ excluded?: readonly {
45
+ id: string;
46
+ reason: string;
47
+ }[];
48
+ /** Fields `api show` adds to every answer, such as the API version the commands send. */
49
+ shown?: Readonly<Record<string, unknown>>;
50
+ failure?: (status: number, answer: unknown, operation: ManifestOperation) => CliError | undefined;
51
+ }
52
+ /** The keys one call checks beside `api.<operation>`: the manifest's that apply, and the CLI's from the body. */
53
+ export declare const serviceApiKeys: (input: ServiceApiPermissionsInput, operation: ManifestOperation, call: ApiCommandInput) => PermissionKey[];
54
+ /**
55
+ * The group's half of `commandPermissions`: the keys each operation also checks, for `--dry-run` and discovery, and
56
+ * `ask` for each of them and for every operation that deletes. A CLI with keys of its own merges each field with its
57
+ * own, never spreads one over the other. `ask` stops at a terminal; over MCP it goes ahead, so `deny` is what stops an
58
+ * agent.
59
+ */
60
+ export declare const serviceApiPermissions: (input: ServiceApiPermissionsInput) => {
61
+ alsoChecks: (path: readonly string[]) => readonly (PermissionKey | ConditionalKey)[];
62
+ defaults: Readonly<Record<PermissionKey, Level>>;
63
+ /** The keys, so a profile may name one that no command path spells. */
64
+ extra: readonly PermissionKey[];
65
+ };
66
+ /**
67
+ * The raw API of an OpenAPI service as one group: `api list` and `api show` without a request, and one command per
68
+ * operation of the generated manifest, sent to its server with the sign-in its security scheme names. Every write goes
69
+ * through the profile's guard on `api.<operation>` and on each manifest key that applies to the call (`files.delete`
70
+ * when `permanently` is true); the journal records that it ran, never its body. A read that pages takes `--all`. There
71
+ * is no free-form `api call`: a request is always one operation of the spec, with its own key (SEC-196).
72
+ */
73
+ export declare const serviceApiCommand: (options: ServiceApiOptions) => Command;
@@ -0,0 +1,260 @@
1
+ import { CliError, isCliError } from "@wirecat/cli-base";
2
+ import { annotate } from "@wirecat/cli-base/commands";
3
+ import { Command } from "commander";
4
+ import { guardFor } from "../sends/guard.js";
5
+ import { guardedWrite } from "../sends/guarded.js";
6
+ import { keyedGuard } from "../sends/keyed-guard.js";
7
+ import { levelFor } from "../sends/permissions.js";
8
+ import { newOperationId } from "../sends/send-id.js";
9
+ import { refusedPlace } from "../sends/upload.js";
10
+ import { generatedApiCommand } from "./bot/api.js";
11
+ import { httpApiRequest, httpApiSend } from "./bot/api-http.js";
12
+ import { checkApiBody, checkApiParameter, parseApiJson, readApiBody } from "./bot/api-input.js";
13
+ import { baseContext, outputFor } from "./context.js";
14
+ import { NO_EFFECTS } from "./effects.js";
15
+ import { itemOf, listOf, renderAnswer } from "./envelope.js";
16
+ import { queryTerms, termField, withQuery } from "./list-query.js";
17
+ import { terminalAsker } from "./messenger/ask.js";
18
+ import { authHeader, manifestBaseUrl, nextPage, parameterValue, } from "./service-api-manifest.js";
19
+ /** How far `--all` reads: a service that never stops paging must not run a command forever. */
20
+ const MOST_PAGES = 500;
21
+ const isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
22
+ const keyOf = (operation) => `api.${operation.command}`;
23
+ const permissionsOf = (operation) => operation.permissions ?? [];
24
+ /** By its method too: an override may have marked a DELETE as a plain write. */
25
+ const destructive = (operation) => operation.effect === "destructive" || (operation.binding.kind === "http" && operation.binding.method === "DELETE");
26
+ const flagsOf = ({ body = [], query = [] }) => [...body, ...query];
27
+ /** A flag counts unless it is absent or plainly false: a service may read `1` or `True` as true. */
28
+ const set = (value) => value !== undefined && value !== null && value !== false && value !== "false";
29
+ /** Whether a manifest key applies to this call: always, or when one of its flags is set. */
30
+ const applies = (permission, body, input) => flagsOf(permission).length === 0 ||
31
+ (permission.body ?? []).some((field) => isObject(body) && set(body[field])) ||
32
+ (permission.query ?? []).some((name) => set(input.query[name]));
33
+ /** The keys one call checks beside `api.<operation>`: the manifest's that apply, and the CLI's from the body. */
34
+ export const serviceApiKeys = (input, operation, call) => {
35
+ const body = call.body?.trim() ? parseApiJson(call.body) : undefined;
36
+ const keys = [
37
+ ...permissionsOf(operation)
38
+ .filter((permission) => applies(permission, body, call))
39
+ .map(({ key }) => key),
40
+ ...(input.bodyPermissions?.[operation.command] ?? []).filter((one) => one.applies(body)).map(({ key }) => key),
41
+ ];
42
+ return [...new Set(keys)];
43
+ };
44
+ /**
45
+ * The group's half of `commandPermissions`: the keys each operation also checks, for `--dry-run` and discovery, and
46
+ * `ask` for each of them and for every operation that deletes. A CLI with keys of its own merges each field with its
47
+ * own, never spreads one over the other. `ask` stops at a terminal; over MCP it goes ahead, so `deny` is what stops an
48
+ * agent.
49
+ */
50
+ export const serviceApiPermissions = (input) => {
51
+ const checks = new Map();
52
+ for (const operation of input.manifest.operations)
53
+ checks.set(operation.command, [
54
+ ...permissionsOf(operation).map((permission) => flagsOf(permission).length === 0
55
+ ? permission.key
56
+ : { key: permission.key, when: `with ${flagsOf(permission).join(" or ")} set` }),
57
+ ...(input.bodyPermissions?.[operation.command] ?? []).map(({ key, when }) => ({ key, when })),
58
+ ]);
59
+ const keys = [...new Set([...checks.values()].flat().map((one) => (typeof one === "string" ? one : one.key)))];
60
+ return {
61
+ extra: keys,
62
+ alsoChecks: (path) => (path[0] === "api" && path.length === 2 ? (checks.get(path[1] ?? "") ?? []) : []),
63
+ defaults: {
64
+ ...Object.fromEntries(keys.map((key) => [key, "ask"])),
65
+ ...Object.fromEntries(input.manifest.operations.filter(destructive).map((operation) => [keyOf(operation), "ask"])),
66
+ },
67
+ };
68
+ };
69
+ const rowOf = (operation) => ({
70
+ command: operation.command,
71
+ method: operation.binding.kind === "http" ? operation.binding.method : "",
72
+ path: operation.binding.kind === "http" ? operation.binding.path : "",
73
+ effect: operation.effect,
74
+ summary: operation.summary ?? "",
75
+ });
76
+ const API_QUERY = {
77
+ entity: "api_operation",
78
+ backend: "native",
79
+ fields: [
80
+ termField("effect", "enum", "effect:destructive", { values: ["read", "write", "destructive"] }),
81
+ termField("tag", "kw", "tag:Pages"),
82
+ ],
83
+ };
84
+ /**
85
+ * The raw API of an OpenAPI service as one group: `api list` and `api show` without a request, and one command per
86
+ * operation of the generated manifest, sent to its server with the sign-in its security scheme names. Every write goes
87
+ * through the profile's guard on `api.<operation>` and on each manifest key that applies to the call (`files.delete`
88
+ * when `permanently` is true); the journal records that it ran, never its body. A read that pages takes `--all`. There
89
+ * is no free-form `api call`: a request is always one operation of the spec, with its own key (SEC-196).
90
+ */
91
+ export const serviceApiCommand = (options) => {
92
+ const { app, configuration, manifest } = options;
93
+ // A credential-returning operation needs a bot's `--store-token`; a service CLI signs in through `session` instead.
94
+ const operations = manifest.operations.filter((operation) => !operation.response?.sensitive);
95
+ const baseUrl = manifestBaseUrl(manifest, options.baseUrl);
96
+ const base = new URL(baseUrl);
97
+ const own = serviceApiPermissions(options);
98
+ // The group's own levels hold even where the CLI's permissions left them out.
99
+ const defaults = { ...own.defaults, ...configuration.permissions?.defaults };
100
+ const unguarded = operations.filter((operation) => destructive(operation) && !permissionsOf(operation).some(({ key }) => key.endsWith(".delete")));
101
+ if (unguarded.length > 0)
102
+ throw new CliError("configuration_error", `${unguarded.map(({ command }) => command).join(", ")} can delete, but the manifest gives no delete key: generate with \`permissions\``);
103
+ const named = new Set(manifest.operations.flatMap((operation) => permissionsOf(operation).map(({ key }) => key)));
104
+ const unnamed = Object.values(options.bodyPermissions ?? {})
105
+ .flat()
106
+ .filter(({ key }) => !named.has(key));
107
+ if (unnamed.length > 0)
108
+ throw new CliError("configuration_error", `bodyPermissions name ${unnamed.map(({ key }) => key).join(", ")}, which the manifest does not: the keys come from \`permissions\``);
109
+ let schemas;
110
+ const loaded = () => {
111
+ if (!schemas)
112
+ throw new CliError("configuration_error", "the api schemas were not loaded before the command ran");
113
+ return schemas;
114
+ };
115
+ const send = httpApiSend({
116
+ service: options.service,
117
+ fetch: options.fetch,
118
+ ...(options.failure ? { failure: options.failure } : {}),
119
+ });
120
+ const operationOf = (name) => {
121
+ const found = operations.find((operation) => operation.command === name || operation.id === name);
122
+ if (found)
123
+ return found;
124
+ const left = options.excluded?.find((one) => one.id === name) ??
125
+ (manifest.operations.some((one) => one.command === name || one.id === name)
126
+ ? { reason: "it returns a credential, which is never printed" }
127
+ : undefined);
128
+ throw new CliError("not_found", left
129
+ ? `${name} is not offered: ${left.reason}`
130
+ : `no ${options.service} API operation ${name}; see ${app.command} api list`);
131
+ };
132
+ const signed = async (command, operation, request) => {
133
+ const auth = authHeader(manifest, operation);
134
+ if (auth)
135
+ request.headers.set(auth.name, auth.value(await options.token(command)));
136
+ // A redirect to another host drops only the standard sign-in headers; an API key header would go along.
137
+ if (auth && auth.name !== "authorization")
138
+ request.redirect = "manual";
139
+ for (const [name, value] of Object.entries(options.headers?.(command, operation) ?? {}))
140
+ request.headers.set(name, value);
141
+ return request;
142
+ };
143
+ const write = async (command, operation, extra, request) => {
144
+ const { settings, env, renderer, run } = baseContext(command, configuration.resolveSettings);
145
+ const operationId = newOperationId();
146
+ const guard = keyedGuard((ask) => guardFor(app, { ...settings, sendsPerHour: Number.MAX_SAFE_INTEGER, permissionDefaults: defaults }, renderer.warn, env, ask), terminalAsker(command), (key) => levelFor(settings.permissions, key, defaults).level, extra);
147
+ const guarded = { chatId: null, kind: "edit", key: keyOf(operation), operationId };
148
+ guard.refuse(guarded);
149
+ try {
150
+ const result = await guardedWrite(guard, guarded, () => run(() => send(command, operation, request)));
151
+ return { operation_id: operationId, result };
152
+ }
153
+ catch (error) {
154
+ if (isCliError(error) && error.code === "outcome_unknown")
155
+ throw new CliError("outcome_unknown", error.message, { ...error.details, operation_id: operationId });
156
+ throw error;
157
+ }
158
+ };
159
+ /** Every page, in one run; a next page on another host is never sent the sign-in. */
160
+ const allPages = async (command, operation, input) => {
161
+ const pagination = operation.pagination;
162
+ // Services number pages from 0 or from 1, and the manifest does not say which.
163
+ if (pagination.style === "page" && parameterValue(input, pagination.page) === undefined)
164
+ throw new CliError("validation_error", `--all on ${operation.command} needs the first page: give --${pagination.page.name} 0 or 1, as ${options.service} counts`);
165
+ const items = [];
166
+ const asked = new Set();
167
+ let call = input;
168
+ let url;
169
+ await baseContext(command, configuration.resolveSettings).run(async () => {
170
+ for (let page = 0;; page++) {
171
+ if (page >= MOST_PAGES)
172
+ throw new CliError("validation_error", `${operation.command} has more than ${MOST_PAGES} pages; narrow it with its own flags, or page it yourself`);
173
+ const request = await signed(command, operation, httpApiRequest(operation, call, baseUrl));
174
+ if (url !== undefined)
175
+ request.url = url;
176
+ const key = `${request.url.href} ${request.body ?? ""}`;
177
+ if (asked.has(key))
178
+ throw new CliError("invalid_response", `${options.service} gave the same next page twice; nothing more read`);
179
+ asked.add(key);
180
+ const step = nextPage(pagination, call, await send(command, operation, request));
181
+ for (const item of step.items)
182
+ items.push(item);
183
+ if (!step.next)
184
+ return;
185
+ if ("url" in step.next) {
186
+ url = new URL(step.next.url, request.url);
187
+ if (url.origin !== base.origin)
188
+ throw new CliError("invalid_response", `${options.service} pointed the next page at another host`);
189
+ }
190
+ else
191
+ call = step.next.input;
192
+ }
193
+ });
194
+ renderAnswer(command, outputFor(command), listOf(`api ${operation.command}`, { items, limit: items.length, has_more: false }));
195
+ };
196
+ const generated = generatedApiCommand({
197
+ operations,
198
+ checkParameter: (name, schema, raw) => checkApiParameter(name, schema, raw, loaded()),
199
+ checkBody: (operation, text) => checkApiBody(operation, text, loaded()),
200
+ readBody: (command, body) => {
201
+ if (body.bodyFile !== undefined && body.bodyFile !== "-") {
202
+ const { env } = baseContext(command, configuration.resolveSettings);
203
+ if (refusedPlace(body.bodyFile, app, env))
204
+ throw new CliError("validation_error", `--body-file may not read ${body.bodyFile}: it holds sign-ins or state`);
205
+ }
206
+ return readApiBody(body);
207
+ },
208
+ execute: async (command, operation, input) => {
209
+ const extra = serviceApiKeys(options, operation, input);
210
+ if (operation.pagination && command.opts().all === true) {
211
+ if (operation.effect !== "read" || extra.length > 0)
212
+ throw new CliError("validation_error", `--all reads only; this call of ${operation.command} is guarded by ${extra.join(", ") || "its write"}`);
213
+ return allPages(command, operation, input);
214
+ }
215
+ const request = await signed(command, operation, httpApiRequest(operation, input, baseUrl));
216
+ const answer = operation.effect === "read" && extra.length === 0
217
+ ? await baseContext(command, configuration.resolveSettings).run(() => send(command, operation, request))
218
+ : await write(command, operation, extra, request);
219
+ renderAnswer(command, outputFor(command), itemOf(answer));
220
+ },
221
+ });
222
+ const list = withQuery(annotate(new Command("list"), {
223
+ effects: NO_EFFECTS,
224
+ examples: [`${app.command} api list`, `${app.command} api list effect:destructive --json=command,path`],
225
+ }), API_QUERY)
226
+ .description(`list every ${options.service} API operation this CLI offers, without calling ${options.service}`)
227
+ .action(function (words) {
228
+ const terms = queryTerms(words, API_QUERY, "api list");
229
+ const effect = terms.get("effect");
230
+ const tag = terms.get("tag");
231
+ const items = operations
232
+ .filter((one) => (!effect || one.effect === effect) && (!tag || one.tags.includes(tag)))
233
+ .map(rowOf);
234
+ renderAnswer(this, outputFor(this), listOf("api list", { items, limit: items.length, has_more: false }));
235
+ });
236
+ const show = annotate(new Command("show"), {
237
+ effects: NO_EFFECTS,
238
+ examples: [`${app.command} api show ${operations[0]?.command ?? "<operation>"} --json`],
239
+ })
240
+ .description(`show one operation's parameters and request schema, without calling ${options.service}`)
241
+ .argument("<operation>", "the operation, as api list prints it")
242
+ .action(async function (name) {
243
+ const operation = operationOf(name);
244
+ const definitions = await options.definitions();
245
+ const schema = operation.request?.schema ? definitions[operation.request.schema] : undefined;
246
+ renderAnswer(this, outputFor(this), itemOf({ operation, ...options.shown, ...(schema ? { request_schema: schema } : {}) }));
247
+ });
248
+ const group = annotate(new Command("api"), { effects: NO_EFFECTS }).description(`the raw ${options.service} API, one command per operation of its OpenAPI document`);
249
+ group.addCommand(list).addCommand(show);
250
+ const load = async () => {
251
+ schemas ??= await options.schemas();
252
+ };
253
+ for (const child of generated.commands) {
254
+ const operation = operations.find((one) => one.command === child.name());
255
+ if (operation?.pagination && !operation.parameters.some(({ name }) => name === "all"))
256
+ child.option("--all", "read every page, as the API pages it");
257
+ group.addCommand(child.hook("preAction", load));
258
+ }
259
+ return group;
260
+ };
@@ -563,6 +563,7 @@ export declare const appMcpCommand: (app: import("./entry.js").AppIdentity, conf
563
563
  export declare const botAdminsCommand: (bot: import("./index.js").BotMessenger) => import("commander").Command;
564
564
  export declare const botMembersCommand: (bot: import("./index.js").BotMessenger) => import("commander").Command;
565
565
  export declare const generatedApiCommand: (api: import("./bot/api.js").ApiCommands) => import("commander").Command;
566
+ export declare const serviceApiCommand: (options: import("./service-api.js").ServiceApiOptions) => import("commander").Command;
566
567
  export declare const botCommand: (bot: import("./index.js").BotMessenger) => import("commander").Command;
567
568
  export declare const botMcpCommand: (bot: import("./index.js").BotMessenger) => import("commander").Command;
568
569
  export declare const botMessagesCommand: (bot: import("./index.js").BotMessenger) => import("commander").Command;
@@ -55,6 +55,7 @@ import { topicsCommand as topicsCommandDefinition } from "./messenger/topics-com
55
55
  import { watchCommand as watchCommandDefinition } from "./messenger/watch-command.js";
56
56
  import { runsCommand as runsCommandDefinition } from "./runs/command.js";
57
57
  import { scheduleCommandFor as scheduleCommandForDefinition } from "./schedule/schedule-command.js";
58
+ import { serviceApiCommand as serviceApiCommandDefinition } from "./service-api.js";
58
59
  import { setupCommand as setupCommandDefinition } from "./setup-command.js";
59
60
  import { sharedCommand as protectedCommand } from "./shared-contracts.js";
60
61
  import { skillCommand as skillCommandDefinition } from "./skill-command.js";
@@ -67,6 +68,7 @@ export const appMcpCommand = sharedCommand(appMcpCommandDefinition);
67
68
  export const botAdminsCommand = sharedCommand(botAdminsCommandDefinition);
68
69
  export const botMembersCommand = sharedCommand(botMembersCommandDefinition);
69
70
  export const generatedApiCommand = sharedCommand(generatedApiCommandDefinition);
71
+ export const serviceApiCommand = sharedCommand(serviceApiCommandDefinition);
70
72
  export const botCommand = sharedCommand(botCommandDefinition);
71
73
  export const botMcpCommand = sharedCommand(botMcpCommandDefinition);
72
74
  export const botMessagesCommand = sharedCommand(botMessagesCommandDefinition);