@wirecat/cli-core 0.696.0 → 0.698.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 (70) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/dist/cli/bot/api-http.d.ts +1 -1
  3. package/dist/cli/bot/api-http.js +77 -5
  4. package/dist/cli/bot/api-input.d.ts +5 -0
  5. package/dist/cli/bot/api-input.js +55 -0
  6. package/dist/cli/bot/api.d.ts +2 -0
  7. package/dist/cli/bot/api.js +12 -3
  8. package/dist/cli/documents/folders.d.ts +2 -0
  9. package/dist/cli/documents/library.d.ts +2 -0
  10. package/dist/cli/documents/library.js +5 -1
  11. package/dist/cli/documents/queries.d.ts +4 -0
  12. package/dist/cli/documents/queries.js +7 -1
  13. package/dist/cli/messenger/mcp-command.js +53 -4
  14. package/dist/cli/messenger/store-maintenance-command.js +3 -2
  15. package/dist/cli/schedule/schedule-command.js +9 -4
  16. package/dist/cli/service-api-manifest.js +25 -18
  17. package/dist/cli/service-api.js +6 -2
  18. package/dist/conversations/link.d.ts +5 -2
  19. package/dist/conversations/link.js +27 -9
  20. package/dist/crm/manifest/manifest.d.ts +2 -0
  21. package/dist/crm/manifest/manifest.js +2 -1
  22. package/dist/crm/manifest/map.d.ts +7 -2
  23. package/dist/crm/manifest/map.js +16 -9
  24. package/dist/crm/testing/manifest-fake.js +31 -2
  25. package/dist/domain/tracker.d.ts +100 -0
  26. package/dist/domain/tracker.js +28 -0
  27. package/dist/errors/reasons.js +1 -0
  28. package/dist/manifest/index.d.ts +17 -5
  29. package/dist/manifest/index.js +26 -8
  30. package/dist/mcp/all-profiles.d.ts +9 -0
  31. package/dist/mcp/all-profiles.js +56 -14
  32. package/dist/ports/wirecat-tools.js +7 -0
  33. package/dist/store/exports.d.ts +1 -0
  34. package/dist/store/exports.js +1 -0
  35. package/dist/store/recover.js +2 -0
  36. package/dist/store/sqlite/account-purge.js +1 -0
  37. package/dist/store/sqlite/batches.js +5 -2
  38. package/dist/store/sqlite/crm-files.d.ts +3 -0
  39. package/dist/store/sqlite/crm-files.js +2 -2
  40. package/dist/store/sqlite/manifest.js +2 -0
  41. package/dist/store/sqlite/migrations.generated.js +17 -0
  42. package/dist/store/sqlite/schema.d.ts +252 -0
  43. package/dist/store/sqlite/schema.js +28 -0
  44. package/dist/store/sqlite/tracker.d.ts +82 -0
  45. package/dist/store/sqlite/tracker.js +210 -0
  46. package/dist/store/store.d.ts +3 -0
  47. package/dist/store/store.js +5 -0
  48. package/dist/tracker/cli/index.d.ts +24 -0
  49. package/dist/tracker/cli/index.js +292 -0
  50. package/dist/tracker/index.d.ts +8 -0
  51. package/dist/tracker/index.js +7 -0
  52. package/dist/tracker/manifest/manifest.d.ts +76 -0
  53. package/dist/tracker/manifest/manifest.js +139 -0
  54. package/dist/tracker/manifest/map.d.ts +10 -0
  55. package/dist/tracker/manifest/map.js +86 -0
  56. package/dist/tracker/manifest/source.d.ts +18 -0
  57. package/dist/tracker/manifest/source.js +174 -0
  58. package/dist/tracker/source.d.ts +55 -0
  59. package/dist/tracker/source.js +1 -0
  60. package/dist/tracker/sync.d.ts +60 -0
  61. package/dist/tracker/sync.js +254 -0
  62. package/dist/tracker/tasks.d.ts +18 -0
  63. package/dist/tracker/tasks.js +29 -0
  64. package/dist/tracker/testing/index.d.ts +2 -0
  65. package/dist/tracker/testing/index.js +2 -0
  66. package/dist/tracker/testing/source-contract.d.ts +46 -0
  67. package/dist/tracker/testing/source-contract.js +246 -0
  68. package/dist/tracker/testing/source.d.ts +31 -0
  69. package/dist/tracker/testing/source.js +141 -0
  70. package/package.json +12 -4
package/CHANGELOG.md CHANGED
@@ -5,6 +5,99 @@ 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.698.0 — 18.11.2026
9
+
10
+ ### Added
11
+
12
+ - **`folders list` of a documents CLI names each chosen folder.** A row has `name`, the folder's name when `folders add`
13
+ kept it, and `path` when the CLI gives `folderPath` to `documentLibraryCommands`. A folder shown only by its id
14
+ (ydisk's `resource_id`) now has words. A CLI that lists its own folders still answers `{ id }`.
15
+ - **ydisk joins `WIRECAT_TOOLS`.** Yandex Disk (`ydisk`, `@wirecat/yandex-disk-cli`) is on npm since 0.1.0, so every
16
+ CLI's first screen ("Works with") and first-run list of other WireCat tools now name it, and an upload refuses a file
17
+ from its folders (`yandex-disk-cli`, `YDISK_`) as it does for the other tools.
18
+ - **`auth.verify.active` in `wirecat.config.ts`** names where the token check's answer says the token still works.
19
+ Attio's `GET /v2/self` answers 200 `{ "active": false }` to an unknown, revoked or deleted token; a CLI can now
20
+ refuse that sign-in instead of failing on a missing id.
21
+ - **`valueAt` from `@wirecat/cli-core/manifest`** reads a dotted path into an answer as the source manifest does, so
22
+ a CLI's sign-in reads `auth.verify`'s paths the same way.
23
+
24
+ ### Changed — may break callers
25
+
26
+ - **cli-core needs `@wirecat/cli-base` 0.117.0 or later**, whose command vocabulary has the tracker's nouns and whose
27
+ `signInPlace` and `fakeApi` know a Basic sign-in.
28
+ - **The tracker's commands follow the command vocabulary**, so `cli-dev lint` passes a tracker CLI (with cli-base
29
+ 0.117.0, which has `issues`, `teams`, `states` and `labels`). Each list narrows by its query, as `deals list` does:
30
+ `issues list team:<id> project:<id> assignee:none state:<id> type:started label:<id>`, and `archived:include` on
31
+ every list, in place of `--team`, `--project`, `--assignee`, `--state`, `--type`, `--label` and `--archived`.
32
+ `type:` repeats for any of several types. `issues task` is `issues assign`: it makes the issue the owner's task
33
+ and changes nothing in the tracker; its `--due` reads times as `tasks --due` does (a day is its end, `3d` works). `issues search --any` is gone.
34
+ See [Trackers](docs/dev/TRACKER.md#commands).
35
+
36
+ ### Fixed
37
+
38
+ - **The `api` group tells a Basic scheme by its type, so a newer cli-base cannot change who signs.** cli-base #643
39
+ makes `signInPlace` sign Basic, and cli-core told Basic apart by `signInPlace` answering `undefined`. With that
40
+ cli-base, a call that offers Basic and a token would be signed with Basic, and a token without a user name would be
41
+ sent in base64, not refused with "run session start --login <name>". Both rules now hold with either cli-base.
42
+ - **A conversation never mixes the topics of a forum group.** A message's parent is a message of its own topic or
43
+ thread, or the thread's first message when that has text, as a WhatsApp community post its comments answer. In a
44
+ Telegram forum every message of a topic replies to the topic's empty first message: taken as a reply, it chained a
45
+ whole topic, and through those first messages' sender every topic, into one conversation, and its chunks mixed
46
+ topics. A messenger reply into another topic, an agent's answer naming one, and the rules never link across. The
47
+ linking-rules version is 6, so every chat built before reads as outdated and is rebuilt; a chunk whose text is
48
+ unchanged keeps its vector. `conversations batches next` now asks the agent about a message whose only reply is
49
+ one the build does not link.
50
+ - **A value the service cleared clears the stored copy.** A path past the end of a list, or under a `null` the
51
+ service sent, is now `null`, not "not sent": Attio's `values.job_title.0.value` on an empty list used to keep the
52
+ old position ([CRM.md](docs/dev/CRM.md#a-source-from-a-manifest)). Watch for: an `each` rule under such
53
+ a `null` now gives an empty list, so the record's links are cleared too.
54
+ - **`crmManifestFake` takes its own answer when a value is one of several types.** It wrote a mapped value into a
55
+ sample of the union's first branch, and its strict fake refused the row: every contract case of an Attio CLI
56
+ failed. The row is now sampled from the branch each mapped path needs, through objects, lists and `allOf`.
57
+ - **`<tool> mcp serve --profiles all` starts on a computer with no profile yet.** It answers the handshake and lists
58
+ the same tools a profile's own server lists (`<tool>_tools_search`, `<tool>_read`, and `<tool>_write` where a
59
+ command writes), each taking `profile`, and every call is refused with a `configuration_error` that names the
60
+ command to set up the first profile: `<tool> personal setup`, `<tool> personal session start` for a CLI that signs
61
+ in with a session, or `<tool> personal …` for one with neither. Before, it exited before the handshake, so
62
+ directories such as Glama, which start the server in an empty container to read its tools, marked WireCat servers
63
+ as not deployable. Nothing picks or makes a profile: which tools are listed never follows a profile's permissions,
64
+ so the list is built from the program itself. `mcp serve` with no profile named, and `--profiles` with a name that
65
+ does not exist, are still refused.
66
+ - **`schedule command` and `schedule agent` help no longer shows a messenger's commands in a CLI that is not a
67
+ messenger.** b24 showed `-- messages list <chat> --limit 50` and `b24 personal search messages 'date>1d'`, which it
68
+ does not have. A CLI with `messenger: false` now shows `-- doctor` and `b24 doctor`: these CLIs share no search or
69
+ sync command, and every CLI has `doctor`.
70
+
71
+ ## 0.697.0 — 17.11.2026
72
+
73
+ ### Added
74
+
75
+ - **The `api` group and `serviceApiCall` send a GraphQL operation** of a manifest that cli-base 0.115.0 generates
76
+ from a schema. Each call is one POST of the document `graphqlDocument` builds, never sent again on a redirect.
77
+ The variables are `--body` as one object with each flag over it, read by its schema: digits as written, `true` or
78
+ `false`, JSON for an input object. A variable the operation does not declare, or a required one left out, is
79
+ refused before anything is sent. The flags of a GraphQL operation are its body and stay out of the run's files.
80
+ - **`errors[]` is a failure even at HTTP 200.** A CLI's own `failure` names it first; else its `extensions.code`
81
+ does, repeated only when it is a plain constant, never the service's message. A write is `outcome_unknown` unless
82
+ the code says nothing ran and no data came back. The answer is `data.<field>`; `--all` pages by `pageInfo`.
83
+ - **`ApiCommandInput.selection`** gives a source a deeper selection than the generated one. `api list` and the run
84
+ record name a GraphQL operation as `POST` `query/issues`.
85
+ - **A tracker CLI can be described as data: `trackerSourceFromManifest`.** A `TrackerManifest` names, for each kind,
86
+ the list, changes and ids operations of the generated API and maps our fields to paths in a row, in the CRM
87
+ manifest's rule language. Over GraphQL each call may send its own selection, and `parseTrackerManifest` refuses a
88
+ map path the selection leaves out. `wirecat.config` takes `category: "tracker"` with its `source`, and
89
+ `spec.kind: "graphql"`. See [Trackers](docs/dev/TRACKER.md#a-tracker-described-as-data).
90
+ - **Issue trackers get their own category: `@wirecat/cli-core/tracker`.** A tracker CLI writes one `TrackerSource`
91
+ and gets the copy in the shared store (store version 70: `tracker_items` and the word index `tracker_item_words`),
92
+ `syncTracker` (changes by cursor, deletions by a daily id pass, a run budget that resumes where it stopped),
93
+ `addTrackerCommands` (`sync`, `issues list|show|search|task`, and `projects`, `teams`, `users`, `states`, `labels`
94
+ lists), and `/tracker/testing` with `trackerSourceContract` and `fakeTrackerSource`. `issues task` makes an issue
95
+ the owner's task by a link, copying only its key. See [Trackers](docs/dev/TRACKER.md).
96
+
97
+ ### Changed — may break callers
98
+
99
+ - **cli-core needs `@wirecat/cli-base` 0.115.0 or later**, whose manifest has the `graphql` binding.
100
+
8
101
  ## 0.696.0 — 17.11.2026
9
102
 
10
103
  ### Added
@@ -1,5 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import type { ManifestOperation } from "@wirecat/cli-base/codegen";
2
+ import { type ManifestOperation } from "@wirecat/cli-base/codegen";
3
3
  import { type FetchLike } from "@wirecat/cli-base/http";
4
4
  import type { Command } from "commander";
5
5
  import type { ApiCommandInput } from "./api.js";
@@ -1,9 +1,10 @@
1
1
  import { CliError, wallClock } from "@wirecat/cli-base";
2
+ import { graphqlDocument } from "@wirecat/cli-base/codegen";
2
3
  import { providerWaitMs, readJsonResponse, statusToCode } from "@wirecat/cli-base/http";
3
4
  import { providerRequest } from "../command-runs.js";
4
5
  import { outputFor } from "../context.js";
5
6
  import { itemOf, renderAnswer } from "../envelope.js";
6
- import { parseApiJson, sendsBytes } from "./api-input.js";
7
+ import { apiJson, graphqlVariables, parseApiJson, sendsBytes } from "./api-input.js";
7
8
  const LARGEST_ANSWER = 16 * 1024 * 1024;
8
9
  /** `new URL` folds a `.` or `..` segment into its parent, so such an id would reach another endpoint. */
9
10
  const segment = (name, value) => {
@@ -21,12 +22,14 @@ export const unsendableBody = (operation) => {
21
22
  /** One generated HTTP operation and its flags as the request they stand for; nothing is sent. */
22
23
  export const httpApiRequest = (operation, input, baseUrl) => {
23
24
  const { binding } = operation;
24
- if (binding.kind !== "http")
25
+ if (binding.kind !== "http" && binding.kind !== "graphql")
25
26
  throw new CliError("configuration_error", `${operation.command} is not an HTTP operation`);
26
27
  if (unsendableBody(operation))
27
28
  throw new CliError("validation_error", `${operation.command} sends ${operation.request?.contentType}, which the generated command cannot send; nothing was sent`, { sent: false });
28
29
  if (operation.response?.sensitive)
29
30
  throw new CliError("validation_error", `${operation.command} answers with a credential, which the generated command never prints; nothing was sent`, { sent: false });
31
+ if (binding.kind === "graphql")
32
+ return graphqlRequest(operation, binding, input, baseUrl);
30
33
  if (Object.keys(input.fields).length > 0)
31
34
  throw new CliError("configuration_error", `${operation.command} has body fields as flags, which HTTP cannot send`);
32
35
  if (!/^\/(?!\/)/.test(binding.path))
@@ -58,8 +61,70 @@ export const httpApiRequest = (operation, input, baseUrl) => {
58
61
  headers.set("content-type", "application/json");
59
62
  return { method: binding.method, url, headers, ...(body === undefined ? {} : { body }) };
60
63
  };
64
+ /** One GraphQL operation as a POST of its one document to the endpoint, with its variables. */
65
+ const graphqlRequest = (operation, binding, input, baseUrl) => {
66
+ const variables = graphqlVariables(operation, input.body, input.fields);
67
+ const headers = new Headers(input.headers);
68
+ headers.set("accept", "application/json");
69
+ headers.set("content-type", "application/json");
70
+ const query = graphqlDocument(binding, input.selection);
71
+ // A 307 or 308 would send the variables again, to wherever it points.
72
+ return { method: "POST", url: new URL(baseUrl), headers, body: apiJson({ query, variables }), redirect: "error" };
73
+ };
61
74
  /** `/v1/pages/{page_id}` → `/v1/pages/:page_id`: the run record keeps the template, never an id. */
62
75
  const templateOf = (path) => path.replace(/\{([^}]+)\}/g, ":$1");
76
+ /** What the run record names a request by: the path template, or a GraphQL operation's root field. */
77
+ const endpointOf = (operation) => operation.binding.kind === "http"
78
+ ? templateOf(operation.binding.path)
79
+ : operation.binding.kind === "graphql"
80
+ ? `${operation.binding.operation}/${operation.binding.field}`
81
+ : "";
82
+ // Common GraphQL server codes (Apollo's names) as the CLI's; any other is the provider's.
83
+ const GRAPHQL_CODES = {
84
+ UNAUTHENTICATED: "authentication_error",
85
+ AUTHENTICATION_ERROR: "authentication_error",
86
+ FORBIDDEN: "permission_error",
87
+ RATELIMITED: "rate_limited",
88
+ BAD_USER_INPUT: "validation_error",
89
+ GRAPHQL_VALIDATION_FAILED: "validation_error",
90
+ INVALID_INPUT: "validation_error",
91
+ };
92
+ // A refusal of these kinds means the service did nothing, so a write that got one is not in doubt.
93
+ const NOTHING_RAN = new Set(["authentication_error", "permission_error", "rate_limited", "validation_error"]);
94
+ /**
95
+ * A GraphQL answer comes with HTTP 200 even when it failed: `errors[]` is the failure, named by the CLI's own
96
+ * `failure`, else by its first `extensions.code`, never by the service's message (WC-SECR-6). A write that failed in
97
+ * any other way, or answered data too, may have landed (WC-LIFE-9). Otherwise the answer is `data.<field>`.
98
+ */
99
+ const graphqlAnswer = (options, operation, answer) => {
100
+ const { binding } = operation;
101
+ if (binding.kind !== "graphql")
102
+ return answer;
103
+ const { data, errors } = (answer ?? {});
104
+ if (Array.isArray(errors) && errors.length > 0) {
105
+ const own = options.failure?.(200, answer, operation);
106
+ if (own)
107
+ throw own;
108
+ const raw = errors[0]?.extensions?.code;
109
+ // The code is the service's text too: only a plain constant is repeated.
110
+ const code = typeof raw === "string" && /^[A-Z][A-Z0-9_]{0,40}$/.test(raw) ? raw : undefined;
111
+ const known = (code && GRAPHQL_CODES[code]) || "provider_error";
112
+ const writes = operation.effect !== "read";
113
+ if (writes && (!NOTHING_RAN.has(known) || data?.[binding.field] != null))
114
+ return outcomeUnknown(options.service);
115
+ throw new CliError(known, `${options.service} refused ${operation.command}${code ? ` (${code})` : ""}`, {
116
+ retryable: known === "rate_limited",
117
+ });
118
+ }
119
+ if (!data || !(binding.field in data))
120
+ throw new CliError("invalid_response", `${options.service} answered ${operation.command} without data.${binding.field}`);
121
+ return data[binding.field];
122
+ };
123
+ const outcomeUnknown = (service) => {
124
+ throw new CliError("outcome_unknown", `${service} did not confirm a write; check it before repeating the write`, {
125
+ retryable: false,
126
+ });
127
+ };
63
128
  const answerOf = async (response, maxBytes) => {
64
129
  if (response.status === 204 || !response.body || response.headers.get("content-length") === "0")
65
130
  return {};
@@ -71,7 +136,7 @@ const answerOf = async (response, maxBytes) => {
71
136
  */
72
137
  export const httpApiSend = (options) => async (command, operation, request) => {
73
138
  const writes = operation.effect !== "read";
74
- const template = templateOf(operation.binding.kind === "http" ? operation.binding.path : "");
139
+ const template = endpointOf(operation);
75
140
  const end = providerRequest(`${request.method} ${template}`, undefined, {
76
141
  method: request.method,
77
142
  endpointTemplate: template,
@@ -109,8 +174,15 @@ export const httpApiSend = (options) => async (command, operation, request) => {
109
174
  end({ status, error: failed });
110
175
  throw failed;
111
176
  }
112
- end({ status });
113
- return answer;
177
+ try {
178
+ const result = graphqlAnswer(options, operation, answer);
179
+ end({ status });
180
+ return result;
181
+ }
182
+ catch (error) {
183
+ end({ status, error });
184
+ throw error;
185
+ }
114
186
  };
115
187
  /**
116
188
  * The `execute` of `generatedApiCommand` for any OpenAPI CLI: fills the path, adds the query, sends the JSON body
@@ -15,3 +15,8 @@ export declare const checkApiBody: (operation: ManifestOperation, text: string |
15
15
  export declare const parseApiJson: (text: string) => unknown;
16
16
  export declare const apiJson: (value: unknown) => string;
17
17
  export declare const apiPlainJson: (value: unknown) => unknown;
18
+ /**
19
+ * A GraphQL operation's variables: the body's (`--body`, all of them as one object) with each flag over it, read by
20
+ * the variable's schema. A name the operation does not declare, or a required one left out, is refused unsent.
21
+ */
22
+ export declare const graphqlVariables: (operation: ManifestOperation, body: string | undefined, fields: Readonly<Record<string, string>>) => Record<string, unknown>;
@@ -118,3 +118,58 @@ const finite = (key, value) => {
118
118
  };
119
119
  export const apiJson = (value) => stringify(value, finite) ?? "null";
120
120
  export const apiPlainJson = (value) => JSON.parse(stringify(value, (key, inner) => isLosslessNumber(inner) && !isSafeNumber(inner.value) ? inner.toString() : finite(key, inner)) ?? "null");
121
+ /** A JSON object with no lossless number at its top: what a GraphQL body of variables must be. */
122
+ const isVariables = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && !isLosslessNumber(value);
123
+ /**
124
+ * A GraphQL operation's variables: the body's (`--body`, all of them as one object) with each flag over it, read by
125
+ * the variable's schema. A name the operation does not declare, or a required one left out, is refused unsent.
126
+ */
127
+ export const graphqlVariables = (operation, body, fields) => {
128
+ const { binding } = operation;
129
+ if (binding.kind !== "graphql")
130
+ throw new CliError("configuration_error", `${operation.command} is not a GraphQL operation`);
131
+ const given = body?.trim() ? parseApiJson(body) : {};
132
+ if (!isVariables(given))
133
+ throw new CliError("validation_error", `${operation.command} takes its variables as one JSON object`, {
134
+ sent: false,
135
+ });
136
+ const variables = { ...given };
137
+ for (const [name, raw] of Object.entries(fields)) {
138
+ const schema = operation.parameters.find((one) => one.in === "body" && one.name === name)?.schema;
139
+ variables[name] = flagValue(operation, name, raw, schema?.type);
140
+ }
141
+ const unknown = Object.keys(variables).filter((name) => !(name in binding.variables));
142
+ if (unknown.length > 0)
143
+ throw new CliError("validation_error", `${operation.command} has no variable ${unknown.join(", ")}`, {
144
+ sent: false,
145
+ });
146
+ const missing = Object.entries(binding.variables)
147
+ .filter(([name, type]) => type.endsWith("!") && variables[name] == null)
148
+ .map(([name]) => `--${apiFlagOf(name)}`);
149
+ if (missing.length > 0)
150
+ throw new CliError("validation_error", `${operation.command} needs ${missing.join(", ")}`, { sent: false });
151
+ return variables;
152
+ };
153
+ const DECIMAL = /^-?\d+(\.\d+)?$/;
154
+ const flagValue = (operation, name, raw, type) => {
155
+ const flag = `--${apiFlagOf(name)} of ${operation.command}`;
156
+ if (type === "integer" || type === "number") {
157
+ // Number() would take 0x10 and 1e1, and round a long id; the digits go as written.
158
+ if (!(type === "integer" ? DIGITS : DECIMAL).test(raw.trim()))
159
+ throw new CliError("validation_error", `${flag} takes ${type === "integer" ? "a whole number" : "a number"}`, {
160
+ sent: false,
161
+ });
162
+ return new LosslessNumber(raw.trim());
163
+ }
164
+ if (type === "boolean") {
165
+ if (raw !== "true" && raw !== "false")
166
+ throw new CliError("validation_error", `${flag} takes true or false`, { sent: false });
167
+ return raw === "true";
168
+ }
169
+ if (type === "object" || type === "array" || type === "unknown")
170
+ return parseApiJson(raw);
171
+ // An input object or a list given as JSON; an enum's value, behind a ref too, is a bare word.
172
+ if (type === "ref" && /^\s*[{["]/.test(raw))
173
+ return parseApiJson(raw);
174
+ return raw;
175
+ };
@@ -10,6 +10,8 @@ export interface ApiCommandInput {
10
10
  bytes?: Uint8Array<ArrayBuffer>;
11
11
  bodySource?: "argument" | "stdin" | "file";
12
12
  tokenProfile?: string;
13
+ /** A GraphQL operation's selection in place of its default, for a source that needs more than one level. */
14
+ selection?: string;
13
15
  }
14
16
  export interface ApiCommands {
15
17
  operations: readonly ManifestOperation[];
@@ -3,7 +3,7 @@ import { annotate } from "@wirecat/cli-base/commands";
3
3
  import { Command, Option } from "commander";
4
4
  import { secretInput } from "../../runs/run-context.js";
5
5
  import { REMOTE_READ, REMOTE_WRITE } from "../effects.js";
6
- import { apiFlagOf, apiOptionKey, readApiBody, readApiBytes, sendsBytes } from "./api-input.js";
6
+ import { apiFlagOf, apiJson, apiOptionKey, graphqlVariables, readApiBody, readApiBytes, sendsBytes, } from "./api-input.js";
7
7
  const scalarOf = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? String(value) : undefined;
8
8
  export const generatedApiCommand = (api) => {
9
9
  const group = new Command("api").description(api.description ?? "every operation of the official Bot API, generated from its schema");
@@ -11,7 +11,9 @@ export const generatedApiCommand = (api) => {
11
11
  for (const operation of api.operations) {
12
12
  const binding = operation.binding.kind === "http"
13
13
  ? `${operation.binding.method} ${operation.binding.path}`
14
- : operation.binding.name;
14
+ : operation.binding.kind === "graphql"
15
+ ? `${operation.binding.operation} ${operation.binding.field}`
16
+ : operation.binding.name;
15
17
  const command = annotate(new Command(operation.command), {
16
18
  effects: operation.effect === "read" ? REMOTE_READ : REMOTE_WRITE,
17
19
  }).description(`${operation.summary ?? operation.id} — ${operation.effect} (${binding})`);
@@ -19,6 +21,9 @@ export const generatedApiCommand = (api) => {
19
21
  if (parameter.sensitive)
20
22
  continue;
21
23
  const option = new Option(`--${apiFlagOf(parameter.name)} <value>`, parameter.description?.split("\n")[0] ?? parameter.name);
24
+ // A GraphQL flag is the request body, which never reaches the run's files (SEC-196).
25
+ if (operation.binding.kind === "graphql" && parameter.in === "body")
26
+ secretInput(option);
22
27
  if (parameter.required && parameter.in !== "body") {
23
28
  // A required parameter the spec gives a default (Notion's `Notion-Version`) is sent with it, never asked for.
24
29
  const fallback = scalarOf(parameter.schema.default);
@@ -85,7 +90,11 @@ export const generatedApiCommand = (api) => {
85
90
  input.bodySource = options.body === "-" ? "stdin" : "argument";
86
91
  else if (options.bodyFile !== undefined)
87
92
  input.bodySource = options.bodyFile === "-" ? "stdin" : "file";
88
- const body = operation.binding.kind === "rpc" ? text : api.checkBody ? api.checkBody(operation, text) : text;
93
+ // A GraphQL body is all the variables: the flags join it here, so the schema check sees what is sent.
94
+ const given = operation.binding.kind === "graphql" ? apiJson(graphqlVariables(operation, text, input.fields)) : text;
95
+ if (operation.binding.kind === "graphql")
96
+ input.fields = {};
97
+ const body = operation.binding.kind === "rpc" ? text : api.checkBody ? api.checkBody(operation, given) : given;
89
98
  if (body !== undefined)
90
99
  input.body = body;
91
100
  await api.execute(this, operation, input);
@@ -12,6 +12,8 @@ export interface DocumentFolderCommands {
12
12
  /** The selected profile's chosen folders, narrowed by `id:`. */
13
13
  list(filter: Record<string, string>): {
14
14
  id: string;
15
+ name?: string;
16
+ path?: string;
15
17
  }[];
16
18
  /** Forgets the folder; answers its id. */
17
19
  remove(input: string): string;
@@ -55,6 +55,8 @@ export interface DocumentLibraryOptions<M extends SourceFile> {
55
55
  coverage: string;
56
56
  /** The accounts a document names, for `identities list`; none when the provider shows none. */
57
57
  people?: DocumentKnowledgePort["people"];
58
+ /** Where a chosen folder is at the provider, for `folders list`: a Disk path. Unset: the answer has no path. */
59
+ folderPath?(folder: M): string | undefined;
58
60
  /** The CLI's own `folders browse`. */
59
61
  browse?(folders: Command, tools: DocumentLibraryTools<M>): void;
60
62
  }
@@ -297,7 +297,11 @@ export const documentLibraryCommands = (options) => {
297
297
  },
298
298
  list: (filter) => roots()
299
299
  .filter((id) => filter.id === undefined || filter.id === id)
300
- .map((id) => ({ id })),
300
+ .map((id) => {
301
+ const file = files().folders().files?.[id];
302
+ const path = file ? options.folderPath?.(file) : undefined;
303
+ return { id, ...(file ? { name: file.name } : {}), ...(path ? { path } : {}) };
304
+ }),
301
305
  remove: (input) => {
302
306
  const id = options.idOf(input);
303
307
  const chosen = files().folders();
@@ -5,6 +5,10 @@ import type { Fact, Memory } from "../../store/index.js";
5
5
  import { type QueryWords } from "../list-query.js";
6
6
  export declare const folderRow: v.StrictObjectSchema<{
7
7
  readonly id: v.StringSchema<undefined>;
8
+ /** The folder as `folders add` named it; left out for a folder chosen before its name was kept. */
9
+ readonly name: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
10
+ /** Where the provider says it is, when the CLI gives a `folderPath`: a Disk path. */
11
+ readonly path: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
8
12
  }, undefined>;
9
13
  export declare const mirrorRow: v.StrictObjectSchema<{
10
14
  readonly id: v.StringSchema<undefined>;
@@ -9,7 +9,13 @@ const registry = (entity, schema, native, examples) => ({
9
9
  backend: "native",
10
10
  fields: queryFieldsOf(schema, { native, examples }).map((field) => field.native ? { ...field, operators: ["term", "phrase"] } : field),
11
11
  });
12
- export const folderRow = v.strictObject({ id: v.string() });
12
+ export const folderRow = v.strictObject({
13
+ id: v.string(),
14
+ /** The folder as `folders add` named it; left out for a folder chosen before its name was kept. */
15
+ name: v.optional(v.string()),
16
+ /** Where the provider says it is, when the CLI gives a `folderPath`: a Disk path. */
17
+ path: v.optional(v.string()),
18
+ });
13
19
  export const mirrorRow = v.strictObject({ id: v.string(), path: v.string(), folder: v.string() });
14
20
  export const tagRow = v.strictObject({ tag: v.string() });
15
21
  export const linkRow = v.looseObject({
@@ -2,7 +2,7 @@ import { spawn } from "node:child_process";
2
2
  import { realpathSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { CliError, resolvePaths, visibleControls } from "@wirecat/cli-base";
5
- import { annotate } from "@wirecat/cli-base/commands";
5
+ import { annotate, describeProgram } from "@wirecat/cli-base/commands";
6
6
  import { installerOf } from "@wirecat/cli-base/update";
7
7
  import { Command } from "commander";
8
8
  import { ATTACHMENT_LIMIT_ENV } from "../../attachments/limits.js";
@@ -10,7 +10,7 @@ import { mcpUrlOf, portOf, publicUrlOf } from "../../http/public-url.js";
10
10
  import { httpLockFile } from "../../mcp/http/state.js";
11
11
  import { envName } from "../../ports/app.js";
12
12
  import { environmentOf } from "../context.js";
13
- import { grantsAuthority, LOCAL_READ, LOCAL_WRITE, REMOTE_WRITE } from "../effects.js";
13
+ import { grantsAuthority, LOCAL_READ, LOCAL_WRITE, REMOTE_WRITE, readsOverMcpAt } from "../effects.js";
14
14
  import { itemOf, renderAnswer } from "../envelope.js";
15
15
  import { MCP_HTTP_DEFAULT_PORT, mcpServerCommand } from "../mcp-server-command.js";
16
16
  import { rootOf } from "../profile.js";
@@ -325,8 +325,11 @@ const serveProfiles = async (self, context, host, flags, set) => {
325
325
  throw new CliError("validation_error", `${bots.join(", ")} ${bots.length === 1 ? "is a bot profile" : "are bot profiles"}, served by \`${app.command} <profile> bot mcp serve\``);
326
326
  // `all` reads the profiles again for each session, so one set up while the server runs appears.
327
327
  const profiles = () => set.profiles().filter((profile) => state(profile) !== "bot");
328
- if (profiles().length === 0)
329
- throw new CliError("configuration_error", `no ${app.command} profile on this computer yet — set one up, then run \`${app.command} mcp serve --profiles all\` again`);
328
+ // A directory starts the server in an empty container only to list its tools: it starts, and each call says how
329
+ // to set up a profile. Nothing here picks or makes one.
330
+ const setup = `no ${app.command} profile on this computer yet — set one up with \`${firstProfileCommand(self, app)}\` ` +
331
+ "(any name in place of personal), then connect again";
332
+ let catalogue;
330
333
  const given = environmentOf(self).mcp ?? {};
331
334
  const execPath = given.execPath ?? process.execPath;
332
335
  const scriptPath = given.scriptPath ?? realpathSync(process.argv[1] ?? "");
@@ -340,6 +343,14 @@ const serveProfiles = async (self, context, host, flags, set) => {
340
343
  signIn: (profile) => `profile ${profile} is not signed in — run \`${app.command} ${profile} setup\`, or sign in from WireCat Desktop, ` +
341
344
  "then try again. If the owner did not choose this profile, ask which one.",
342
345
  child: (profile) => ({ command: execPath, args: [scriptPath, profile, "mcp", "serve", ...tightened], env }),
346
+ catalogue: () => {
347
+ catalogue ??= catalogueOf(self, app);
348
+ catalogue.catch(() => {
349
+ catalogue = undefined;
350
+ });
351
+ return catalogue;
352
+ },
353
+ setup,
343
354
  instructions: await host.instructions(profiles()),
344
355
  note: (line) => context.renderer.note(line),
345
356
  };
@@ -384,6 +395,44 @@ const serveProfiles = async (self, context, host, flags, set) => {
384
395
  ...(signal ? { signal } : {}),
385
396
  });
386
397
  };
398
+ /** `tg personal setup`, or `notion personal session start` for a CLI that signs in with a session. */
399
+ const firstProfileCommand = (self, app) => {
400
+ const root = rootOf(self);
401
+ if (root.commands.some((one) => one.name() === "setup"))
402
+ return `${app.command} personal setup`;
403
+ const session = root.commands.find((one) => one.name() === "session");
404
+ if (session?.commands.some((one) => one.name() === "start"))
405
+ return `${app.command} personal session start`;
406
+ return `${app.command} personal …`;
407
+ };
408
+ /**
409
+ * The tools a profile's server lists, built in this process from the program: which tools a server lists never
410
+ * follows a profile's permissions (they decide each command's availability inside the search), so no profile is
411
+ * needed, read or made.
412
+ */
413
+ const catalogueOf = async (self, app) => {
414
+ const [{ McpServer }, { registerCommands }, { toolsFromCommands }, { listedTools }] = await Promise.all([
415
+ import("@modelcontextprotocol/server"),
416
+ import("../../mcp/surface.js"),
417
+ import("../../mcp/agent.js"),
418
+ import("../../mcp/all-profiles.js"),
419
+ ]);
420
+ const root = rootOf(self);
421
+ const refuse = async () => {
422
+ throw new CliError("configuration_error", `no ${app.command} profile on this computer yet`);
423
+ };
424
+ const commands = Object.fromEntries(toolsFromCommands(describeProgram(root), {
425
+ includeUnavailable: true,
426
+ exclude: [["bot"], ["mcp"]],
427
+ fetchOnly: readsOverMcpAt(root),
428
+ }).map((one) => [
429
+ one.command,
430
+ { title: one.title, description: one.description, writes: one.writes, input: one.input, run: refuse },
431
+ ]));
432
+ const server = new McpServer({ name: app.command, version: app.version }, { capabilities: { tools: {} } });
433
+ registerCommands(server, app.command, commands, app.errors, undefined, app.messenger);
434
+ return listedTools(server);
435
+ };
387
436
  const TAIL_LINES = 20;
388
437
  const TAIL_BYTES = 2_000;
389
438
  const TAIL_WAIT_MS = 500;
@@ -16,7 +16,7 @@ import { migrate } from "../../store/migrations.js";
16
16
  import { openCache } from "../../store/open.js";
17
17
  import { storePath } from "../../store/path.js";
18
18
  import { deleteCopy, repairStore } from "../../store/repair.js";
19
- import { drainNoteIndex, dropAllUnusedVectors, fillSearchIndex, fillStems, involvementStoreOver, noteIndexState, openSqlite, openStore, orphanPointers, pendingNormalization, resetAttachmentWords, resetCrmFileWords, resetNoteIndex, resetSearchIndex, resetStems, rollBack, searchIndexState, stemmerCache, stemsState, vectorIndexCounts, } from "../../store/store.js";
19
+ import { drainNoteIndex, dropAllUnusedVectors, fillSearchIndex, fillStems, involvementStoreOver, noteIndexState, openSqlite, openStore, orphanPointers, pendingNormalization, resetAttachmentWords, resetCrmFileWords, resetNoteIndex, resetSearchIndex, resetStems, resetTrackerItemWords, rollBack, searchIndexState, stemmerCache, stemsState, vectorIndexCounts, } from "../../store/store.js";
20
20
  import { environmentOf, outputFor } from "../context.js";
21
21
  import { destroysNothing, grantsAuthority, LOCAL_READ, LOCAL_WRITE } from "../effects.js";
22
22
  import { itemOf, renderAnswer, snakeKeys } from "../envelope.js";
@@ -327,6 +327,7 @@ const inspect = (path) => reading(path, (database) => {
327
327
  ...(stems ? [["message_stems", indexIntegrity(database, "message_stems", 0)]] : []),
328
328
  ...(schema.version > 0 ? [["attachment_words", indexIntegrity(database, "attachment_words", 0)]] : []),
329
329
  ...(schema.version >= 68 ? [["crm_file_words", indexIntegrity(database, "crm_file_words", 0)]] : []),
330
+ ...(schema.version >= 70 ? [["tracker_item_words", indexIntegrity(database, "tracker_item_words", 0)]] : []),
330
331
  ]);
331
332
  const size = bytesOf(path) + bytesOf(`${path}-wal`);
332
333
  const { bavail, bsize } = statfsSync(dirname(path));
@@ -531,7 +532,7 @@ const reindexCommand = (owner) => destroysNothing(annotate(new Command("rebuild"
531
532
  throw new CliError("validation_error", `the store is behind this build — \`${lineOf(this, "store migrate")}\` first`);
532
533
  }
533
534
  resetSearchIndex(database);
534
- const fileTexts = resetAttachmentWords(database) + resetCrmFileWords(database);
535
+ const fileTexts = resetAttachmentWords(database) + resetCrmFileWords(database) + resetTrackerItemWords(database);
535
536
  const words = buildWordIndex(database, (note) => renderer.note(note));
536
537
  return {
537
538
  path,
@@ -107,9 +107,12 @@ const deliveryOf = ({ notifyOn, deliverTo }) => ({
107
107
  ...(deliverTo?.length ? { to: deliverTo } : {}),
108
108
  });
109
109
  /** What the schedule command needs of a CLI: who it is and, per command, where it prints and which profile runs. */
110
- /** `skill show follow-ups` exists only for messenger CLIs; any other CLI gets a read-only summary it can run. */
110
+ /**
111
+ * `skill show follow-ups` exists only for messenger CLIs. The others share no search or sync command, so their example
112
+ * names `doctor`, which every CLI has and which takes no profile there.
113
+ */
111
114
  const promptExample = (app) => app.messenger === false
112
- ? `summarize what came in during the last day: ${app.command} personal search messages 'date>1d' --newest --limit 20`
115
+ ? `say what needs attention in this installation: ${app.command} doctor`
113
116
  : `run the daily follow-up review: ${app.command} skill show follow-ups`;
114
117
  /** The agent-schedule settings a host with `newMail` writes into its config file's top level (WC-CMD-30). */
115
118
  export const SCHEDULE_SETTINGS = [
@@ -375,6 +378,8 @@ export const runScheduleNow = async (command, site, file, { routes, agentInput }
375
378
  */
376
379
  export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInput, limits: configured, agentRuns = [], }) => {
377
380
  const agentClis = [app, ...agentRuns];
381
+ const messenger = app.messenger !== false;
382
+ const commandExample = messenger ? "messages list <chat> --limit 50" : "doctor";
378
383
  const command = new Command("schedule").description(`run a ${app.command} command or an agent later or on a timer (systemd, launchd, Task Scheduler); an agent cannot send`);
379
384
  const prepare = (self, resolving = {}) => {
380
385
  const context = contextOf(self, resolving);
@@ -462,9 +467,9 @@ export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInpu
462
467
  `${app.command} personal schedule command morning-check --at 08:00 -- doctor`,
463
468
  ],
464
469
  }))
465
- .description(`run ${app.command} <args…> on a timer — reads save what they read, so this is how a chat's history fills the store`)
470
+ .description(`run ${app.command} <args…> on a timer — reads save what they read, so this is how ${messenger ? "a chat's history fills the store" : "the store stays current"}`)
466
471
  .argument("<name>", "lowercase letters, digits and dashes")
467
- .argument("<args...>", `the ${app.command} command after its name, e.g. -- messages list <chat> --limit 50`)).action(async function (name, args) {
472
+ .argument("<args...>", `the ${app.command} command after its name, e.g. -- ${commandExample}`)).action(async function (name, args) {
468
473
  const { environment, save } = prepare(this);
469
474
  if (args[0] === "schedule")
470
475
  throw new CliError("validation_error", "a schedule cannot run schedule");