@wirecat/cli-core 0.660.0 → 0.662.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 (79) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/dist/attachments/markup.js +2 -11
  3. package/dist/calendar/mcp/index.js +23 -17
  4. package/dist/cli/ai-model-command.js +3 -3
  5. package/dist/cli/bot/api-http.d.ts +43 -0
  6. package/dist/cli/bot/api-http.js +160 -0
  7. package/dist/cli/command-availability.d.ts +1 -1
  8. package/dist/cli/command-availability.js +4 -4
  9. package/dist/cli/dry-run-guard.js +7 -5
  10. package/dist/cli/early-refusal.d.ts +1 -1
  11. package/dist/cli/early-refusal.js +2 -2
  12. package/dist/cli/effects.d.ts +9 -2
  13. package/dist/cli/effects.js +16 -4
  14. package/dist/cli/index.d.ts +2 -1
  15. package/dist/cli/index.js +2 -1
  16. package/dist/cli/messenger/admin-moderation-command.js +2 -2
  17. package/dist/cli/messenger/archive-commands.js +2 -2
  18. package/dist/cli/messenger/context.d.ts +2 -2
  19. package/dist/cli/messenger/context.js +5 -3
  20. package/dist/cli/messenger/rankings-command.js +2 -1
  21. package/dist/cli/messenger/serve-command.js +7 -2
  22. package/dist/cli/messenger/tasks-command.d.ts +7 -2
  23. package/dist/cli/messenger/tasks-command.js +8 -4
  24. package/dist/cli/preview.js +3 -5
  25. package/dist/cli/program.js +2 -2
  26. package/dist/cli/schedule/schedule-command.js +3 -0
  27. package/dist/cli/shadowed-options.d.ts +7 -0
  28. package/dist/cli/shadowed-options.js +26 -0
  29. package/dist/crm/cli/index.js +4 -2
  30. package/dist/domain/html-entities.d.ts +5 -0
  31. package/dist/domain/html-entities.js +56 -0
  32. package/dist/domain/locator.js +12 -4
  33. package/dist/domain/references.js +11 -3
  34. package/dist/entities/listings.d.ts +4 -4
  35. package/dist/entities/listings.js +2 -2
  36. package/dist/kit/sync-after-install.d.ts +10 -1
  37. package/dist/kit/sync-after-install.js +35 -11
  38. package/dist/mail/headers.js +3 -3
  39. package/dist/mail/parse.js +9 -8
  40. package/dist/mail/resume.d.ts +4 -1
  41. package/dist/mail/resume.js +11 -2
  42. package/dist/mail/retry.d.ts +2 -1
  43. package/dist/mail/retry.js +6 -4
  44. package/dist/mail/sender-scores.js +1 -6
  45. package/dist/mail/server-search.js +3 -3
  46. package/dist/mail/stored.d.ts +4 -1
  47. package/dist/mail/stored.js +6 -1
  48. package/dist/mail/sync.js +8 -3
  49. package/dist/mail/testing/fake.d.ts +2 -0
  50. package/dist/mail/testing/fake.js +3 -1
  51. package/dist/mcp/all-profiles.js +8 -18
  52. package/dist/mcp/app-server.js +1 -16
  53. package/dist/mcp/bot/server.js +9 -7
  54. package/dist/mcp/caller.js +2 -1
  55. package/dist/mcp/prompts.js +17 -2
  56. package/dist/mcp/server.js +14 -20
  57. package/dist/mcp/stdio-wire.d.ts +5 -2
  58. package/dist/mcp/stdio-wire.js +39 -12
  59. package/dist/mcp/tool.js +6 -4
  60. package/dist/mcp/tools/messages-photo.js +4 -2
  61. package/dist/meetings/cli/search.js +8 -2
  62. package/dist/meetings/hit-query.js +11 -6
  63. package/dist/meetings/mcp/index.d.ts +15 -15
  64. package/dist/sends/guard.js +11 -21
  65. package/dist/sends/keyed-guard.d.ts +1 -1
  66. package/dist/sends/keyed-guard.js +2 -1
  67. package/dist/sends/permissions.d.ts +14 -0
  68. package/dist/sends/permissions.js +32 -0
  69. package/dist/services/listings.js +2 -1
  70. package/dist/services/message-resolution.js +6 -3
  71. package/dist/services/server-search.js +1 -1
  72. package/dist/store/sqlite/mention-drain.d.ts +4 -1
  73. package/dist/store/sqlite/mention-drain.js +7 -3
  74. package/dist/store/sqlite/messages.js +12 -1
  75. package/dist/store/sqlite/query-filter.d.ts +1 -0
  76. package/dist/store/sqlite/query-filter.js +2 -2
  77. package/dist/store/sqlite/tags.js +1 -1
  78. package/package.json +1 -1
  79. package/parity.json +2 -1
package/CHANGELOG.md CHANGED
@@ -5,6 +5,95 @@ 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.662.0 — 14.11.2026
9
+
10
+ ### Added
11
+
12
+ - **`writesOwnerFiles(command)`** marks a command that writes the owner's files outside the store through a folder it
13
+ does not take as an option, such as a saved job's folder. It stays a write that `readonly` stops.
14
+ - **`syncAfterInstallCases` takes `profileLevels`** (`{ variable, keys }`): for each key, the sync must run with the
15
+ profile's own level at `readonly` and be refused at `deny`.
16
+
17
+ ### Changed — may break callers
18
+
19
+ - **A `readonly` level no longer stops a sync.** A command that only fetches from the service into the local store
20
+ (`fetchesOnly`: `sync`, `messages sync`, `contacts sync`, `metadata sync`, `store gaps repair`,
21
+ `stats messages counters sync`) runs under any `readonly` level: the profile's own key, a group key such as
22
+ `messages`, or setup's "read only" answer. This holds on the command line, in `--dry-run` previews, in help and
23
+ over MCP. `--sync-first` and a server search run at `readonly` too. `deny` still refuses them. A profile that
24
+ relied on `readonly` to stop syncing now syncs; set the key to `deny` to stop it.
25
+ - **An MCP server no longer offers a sign-in through its read tool.** A command marked `logsInOrOut` that fetches
26
+ (`session start`) counts as a write over MCP. On the command line nothing changes.
27
+ - **`models ai check` is marked as reaching another service**, so `readonly` stops its paid request.
28
+
29
+ ## 0.661.0 — 14.11.2026
30
+
31
+ ### Added
32
+
33
+ - **`httpApiExecutor` runs a generated OpenAPI operation without a hand-written `execute`.** Give it to
34
+ `generatedApiCommand` with the server address, the CLI's host-checked fetch, its headers (the sign-in, a pinned
35
+ API version) and its guarded write. It fills the path, repeats an array query value, sends the JSON body and
36
+ prints the answer. Every operation that is not a read goes through the CLI's `write`, so a level of `ask` asks and
37
+ the journal records it; `--dry-run` previews before anything is sent. These are refused before any request: an id
38
+ of `.` or `..`, a path that does not start with one `/`, a body that is not JSON, a multipart body, an operation
39
+ that answers with a credential, and an undeclared host. The service's own error text is never repeated. A 401 and
40
+ a 403 name the sign-in or the access (`auth.failed`, `access.denied`). A write that got no answer, a 5xx, or a 2xx
41
+ whose answer cannot be read is `outcome_unknown`. `httpApiRequest` gives the request alone, for a test or a preview.
42
+
43
+ ### Changed — may break callers
44
+
45
+ - **Dates in list queries, and the calendar MCP tools, read the computer's zone.** `today` and a bare date in
46
+ `tasks list`, `meetings list`, `chats list`, `tags list` and the other list queries started in UTC; the calendar
47
+ tools' `timezone` defaulted to UTC, so `event_create` at `10:00` made an 11:00 Madrid event. Both now read the
48
+ local zone, as search and the CLI do.
49
+ - **`messages_photo` takes `attachment`, from 1,** as `attachments_show` and `messages download --attachment` do. It
50
+ took `index` from 0; a number past the last file now says how many files the message has.
51
+ - **`tasks --due` with a date alone is the end of that day,** not its midnight, so a task due on the 20th is not
52
+ overdue all day. `schedule --at-time` refuses a date alone, as `messages send --at-time` does.
53
+ - **An event two accounts hold is read only from the account named.** `event_show` and `event_people` without
54
+ `account_id` refuse it with the accounts to choose from, as the calendar write tools do, and the answer names the
55
+ one account read.
56
+
57
+ ### Fixed
58
+
59
+ - **`documents show` says more text follows after emoji.** `has_more` compared the part's length in UTF-16 units
60
+ with the whole text's length in code points, so a part holding emoji, or another character outside the Basic
61
+ Multilingual Plane, could report no more text before the end and a reader stopped early. `text_offset`,
62
+ `text_length`, `--cursor` and `--max-chars` all count Unicode code points: the next part starts at `text_offset`
63
+ plus the code points of `text` (`[...text].length` in JavaScript, not `text.length`), and a part never splits a
64
+ surrogate pair. A combining mark is a code point of its own, so a cut may fall between a letter and its accent.
65
+ - **A stale copy no longer overwrites a newer edit.** A history page fetched before `serve` saw an edit turned the
66
+ text back, filed the edit as the old version and dropped its vectors.
67
+ - **`serve` stops auto-replies as soon as `replies.send` is denied,** without a restart.
68
+ - **A stdio MCP server closes after a client cancels a call and closes stdin,** and stops on SIGINT or SIGTERM while
69
+ answers are pending. A call cancelled while it waited in the queue never runs, so a cancelled send does not go out.
70
+ The bot server answers a one-shot pipe's calls before it closes, as the other servers do.
71
+ - **`mcp serve --profiles all` refuses with the shared error object** (`validation_error`, `authentication_error`,
72
+ `outcome_unknown`), not plain text.
73
+ - **An MCP answer counts once against the 4 MB limit,** as the CLI counts what it prints; an answer of about 2 MB
74
+ failed with `output.too-large` over MCP alone.
75
+ - **An HTTP MCP client can no longer pass on a caller** meant only for the every-profile server's own connections.
76
+ - **`t.me` links name Telegram chats only,** never a chat of another messenger that shares the username.
77
+ - **Mail:** a plain address beside a bracketed one in To or Cc is kept (`alice@x.com, "Bob" <bob@y.com>`); HTML
78
+ mail decodes numeric and typographic entities (`&rsquo;`, `&mdash;`); an email kept as an envelope stays one while a
79
+ run cannot read its headers; a resumed sync follows every rule field, not only from, domain and list id;
80
+ `--retry-attachments` stops on the signal; listed mail is ordered by instant.
81
+ - **The send guard** refuses a send time it cannot read, and counts a journal line with an unreadable time in the
82
+ hour it was written.
83
+ - **A malformed `%` escape in a reference** (`msg:telegram/1/2/%E0`) is a `validation_error`, not an unknown failure.
84
+ - **`--chat` finds a chat the owner left when several accounts are read,** as with one account.
85
+ - **A configured `limit` above 100 no longer breaks `stats messages top`;** it is capped at the ranking's 100.
86
+ - **`search meetings`:** `date>=30d` works with `--until-time`, `--since-time` takes `7d`, and `budget && project:X`
87
+ or `budget +project:X` leave no dangling operator.
88
+ - **The MCP `review` prompt** writes `since` as the query reads it: `1d ago` as `date>1d`, an ISO time as its UTC
89
+ instant.
90
+ - **The calendar MCP tools** refuse a `limit` over 1000 and an empty attendee.
91
+ - **The tag list** pages without repeating or skipping rows that tie.
92
+ - **`listedOf` labels the owner's own stored mail `Sent`.** A stored email has no folder, so mail the
93
+ owner sent from an IMAP mailbox or without a Gmail `Sent` label looked received. A rule or a cleanup judged from
94
+ stored mail then saw no sender the owner wrote to: "replied" was false and scores that depend on it came out
95
+ wrong. `scoreSenders` did this step on its own; it now uses `listedOf` as it is.
96
+
8
97
  ## 0.660.0 — 14.11.2026
9
98
 
10
99
  ### Added
@@ -1,4 +1,5 @@
1
1
  import iconv from "iconv-lite";
2
+ import { decodeEntities } from "../domain/html-entities.js";
2
3
  import { ReaderLimit } from "./container.js";
3
4
  import { MAX_TEXT_CHARS } from "./limits.js";
4
5
  /** Groups whose text is not the document's: fonts, styles, metadata, pictures, field codes. */
@@ -140,7 +141,6 @@ const HTML_DROPPED_CLOSE = new Map(["script", "style", "head", "noscript", "temp
140
141
  new RegExp(`<\\/${name}\\s*>`, "gi"),
141
142
  ]));
142
143
  const HTML_BLOCK = /<\/?(p|div|br|li|ul|ol|tr|h[1-6]|blockquote|pre|section|article|header|footer|table|hr)\b[^>]*>/gi;
143
- const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: "\u00a0" };
144
144
  // Past the last `>` no tag can close, yet `[^>]*` would rescan to the end from every `<` there: quadratic on `<<<<…`.
145
145
  const replaceTags = (source, tag, replacement) => {
146
146
  const end = source.lastIndexOf(">") + 1;
@@ -176,18 +176,9 @@ export const htmlText = (source) => {
176
176
  // An unclosed comment eats the rest unchanged, as the plain `<!--[\s\S]*?-->` left it, without a rescan per `<!--`.
177
177
  const uncommented = source.replace(/<!--[\s\S]*?(-->|$)/g, (comment, close) => (close ? "" : comment));
178
178
  const blocks = replaceTags(dropHidden(uncommented).replace(/<\/t[dh]\s*>/gi, "\t"), HTML_BLOCK, "\n");
179
- return (replaceTags(blocks, /<[^>]*>/g, "")
180
- .replace(/&(#x[0-9a-f]{1,6}|#\d{1,7}|[a-z]{2,8});/gi, (entity, body) => {
181
- const lower = body.toLowerCase();
182
- if (lower.startsWith("#x"))
183
- return safeChar(Number.parseInt(lower.slice(2), 16), entity);
184
- if (lower.startsWith("#"))
185
- return safeChar(Number(lower.slice(1)), entity);
186
- return ENTITIES[lower] ?? entity;
187
- })
179
+ return (decodeEntities(replaceTags(blocks, /<[^>]*>/g, ""))
188
180
  // From the start of a run only: `[ \t]+\n` alone rescans a long run of spaces from each of them.
189
181
  .replace(/(?<![ \t\u00a0])[ \t\u00a0]+\n/g, "\n")
190
182
  .replace(/\n{3,}/g, "\n\n")
191
183
  .trim());
192
184
  };
193
- const safeChar = (code, fallback) => code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : fallback;
@@ -1,4 +1,5 @@
1
1
  import { CliError, errorObjectOf, mcpErrorResult } from "@wirecat/cli-base";
2
+ import { timezoneOf } from "@wirecat/cli-base/query";
2
3
  import { listOf } from "../../cli/envelope.js";
3
4
  import { isCliFailure } from "../../errors/failures.js";
4
5
  import { listed } from "../../meetings/index.js";
@@ -32,7 +33,7 @@ export const calendarTools = [
32
33
  "[a TO b}), ends_at>=, changed_at>= (events new, moved or cancelled since, each with change and was), " +
33
34
  "overlapping:true (timed events that clash, each with overlaps), calendar:<id>, event_type:<kind>, and " +
34
35
  "-event_type:<kind> to leave one kind out; a date in the zone given, " +
35
- "UTC when absent; without starts_at or ends_at, from today on",
36
+ "the computer's zone when absent, as the CLI reads it; without starts_at or ends_at, from today on",
36
37
  properties: {
37
38
  account_id: integer,
38
39
  query: text,
@@ -79,7 +80,10 @@ const notify = {
79
80
  };
80
81
  const fields = {
81
82
  title: text,
82
- start_time: { ...text, description: "when it starts: a time in `timezone` (UTC when absent), or one with its own" },
83
+ start_time: {
84
+ ...text,
85
+ description: "when it starts: a time in `timezone` (the computer's zone when absent), or one with its own",
86
+ },
83
87
  end_time: { ...text, description: "when it ends" },
84
88
  start_date: { ...text, description: "the first day of an all-day event, YYYY-MM-DD" },
85
89
  end_date: { ...text, description: "the last day of an all-day event" },
@@ -178,6 +182,8 @@ const argumentsOf = (name, input) => {
178
182
  if (["account_id", "limit", "page"].includes(key) &&
179
183
  (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1))
180
184
  throw new CliError("validation_error", `${key} must be a positive integer`);
185
+ else if (key === "limit" && value > 1000)
186
+ throw new CliError("validation_error", "limit is at most 1000 events per page");
181
187
  else if ([
182
188
  "query",
183
189
  "timezone",
@@ -198,7 +204,8 @@ const argumentsOf = (name, input) => {
198
204
  throw new CliError("validation_error", `${key} must be text`);
199
205
  else if (["notify", "series", "following"].includes(key) && typeof value !== "boolean")
200
206
  throw new CliError("validation_error", `${key} must be true or false`);
201
- else if (key === "attendees" && (!Array.isArray(value) || value.some((one) => typeof one !== "string")))
207
+ else if (key === "attendees" &&
208
+ (!Array.isArray(value) || value.some((one) => typeof one !== "string" || !one.trim())))
202
209
  throw new CliError("validation_error", "attendees must be a list of email addresses");
203
210
  else if (key === "response" && !EVENT_RESPONSES.includes(value))
204
211
  throw new CliError("validation_error", `response is one of ${EVENT_RESPONSES.join(", ")}`);
@@ -217,18 +224,13 @@ export const callCalendarTool = async (store, name, input, { accountIds, failure
217
224
  throw new CliError("not_found", `no calendar account ${asked} here`);
218
225
  const accounts = asked === undefined ? [...accountIds] : [asked];
219
226
  const event = () => eventIdOf(args.event);
227
+ // An event shared by two accounts has a copy, and a response, in each: one is read only when it is named.
220
228
  const eventIn = async () => {
221
- for (const accountId of accounts)
222
- try {
223
- return { accountId, details: await eventOf(store, accountId, event()) };
224
- }
225
- catch (error) {
226
- if (!isCliFailure(error) || error.code !== "not_found")
227
- throw error;
228
- }
229
- throw new CliError("not_found", `no event ${args.event} in ${asked === undefined ? "these accounts" : "this account"}`);
229
+ const accountId = await accountFor(accounts, asked, (id) => eventOf(store, id, event()), `event ${args.event}`);
230
+ return { accountId, details: await eventOf(store, accountId, event()) };
230
231
  };
231
232
  let answer;
233
+ let read = accounts;
232
234
  if (writing) {
233
235
  const written = await writeTool(store, name, args, { asked, accounts, now, writes });
234
236
  const result = { accounts: [written.account], ...written.result, untrusted: CALENDAR_UNTRUSTED_FIELDS };
@@ -247,18 +249,22 @@ export const callCalendarTool = async (store, name, input, { accountIds, failure
247
249
  case "events_list":
248
250
  answer = await eventsList(store, args, accounts, now);
249
251
  break;
250
- case "event_show":
251
- answer = await eventAnswer((await eventIn()).details);
252
+ case "event_show": {
253
+ const { accountId, details } = await eventIn();
254
+ read = [accountId];
255
+ answer = await eventAnswer(details);
252
256
  break;
257
+ }
253
258
  case "event_people": {
254
259
  const { accountId } = await eventIn();
260
+ read = [accountId];
255
261
  answer = await peopleAnswer(store, accountId, { event: event() });
256
262
  break;
257
263
  }
258
264
  default:
259
265
  answer = await reviewsAnswer(store, accounts);
260
266
  }
261
- const result = { accounts, ...answer, untrusted: CALENDAR_UNTRUSTED_FIELDS };
267
+ const result = { accounts: read, ...answer, untrusted: CALENDAR_UNTRUSTED_FIELDS };
262
268
  return agentResult({
263
269
  content: [{ type: "text", text: JSON.stringify(result) }],
264
270
  structuredContent: result,
@@ -290,7 +296,7 @@ const eventsList = async (store, args, accounts, now) => {
290
296
  const filter = await eventsFilter(args.query, {
291
297
  store,
292
298
  accountId,
293
- zone: args.timezone ?? "UTC",
299
+ zone: timezoneOf(args.timezone),
294
300
  now,
295
301
  });
296
302
  return merging
@@ -356,7 +362,7 @@ const writeTool = async (store, name, args, { asked, accounts, now, writes, }) =
356
362
  // WC-MCP-7: nobody is here to answer, and a form would teach people to click yes; the levels decide.
357
363
  ask: async () => { },
358
364
  now,
359
- zone: args.timezone ?? "UTC",
365
+ zone: timezoneOf(args.timezone),
360
366
  names: {
361
367
  notify: "notify: true or false",
362
368
  id: "operation_id",
@@ -6,7 +6,7 @@ import { localOnly, localOnlyRefusal } from "../models/local-only.js";
6
6
  import { agentOf } from "../runs/run-context.js";
7
7
  import { readSecret } from "../terminal/prompt.js";
8
8
  import { environmentOf } from "./context.js";
9
- import { FETCH, grantsAuthority, LOCAL_READ, LOCAL_WRITE, NO_EFFECTS } from "./effects.js";
9
+ import { FETCH, grantsAuthority, LOCAL_READ, LOCAL_WRITE, NO_EFFECTS, reachesOtherService } from "./effects.js";
10
10
  import { itemOf } from "./envelope.js";
11
11
  const imagesNote = (setting) => `images you add to memory are sent to ${new URL(aiBaseUrl(setting)).host} to be read${setting.provider === "ollama" ? " (on this computer)" : ", so they leave this computer"}`;
12
12
  const view = (app, options, setting) => {
@@ -175,12 +175,12 @@ export const aiModelCommand = (app, options) => {
175
175
  writeAiSetting(path, kept);
176
176
  options.output(itemOf({ ...view(app, options, kept), changed: images !== undefined }), this);
177
177
  });
178
- annotate(ai.command("check"), {
178
+ reachesOtherService(annotate(ai.command("check"), {
179
179
  effects: FETCH,
180
180
  mcp: false,
181
181
  output: { entity: "ai_model_check" },
182
182
  examples: [`${app.command} models ai check`],
183
- })
183
+ }))
184
184
  .summary("send one short paid request and say what is wrong")
185
185
  .description("send one short request (billed by the provider, usually under a cent) and say what is wrong")
186
186
  .option("--from-app", "you did this in WireCat Desktop")
@@ -0,0 +1,43 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import type { ManifestOperation } from "@wirecat/cli-base/codegen";
3
+ import { type FetchLike } from "@wirecat/cli-base/http";
4
+ import type { Command } from "commander";
5
+ import type { ApiCommandInput } from "./api.js";
6
+ export interface HttpApiRequest {
7
+ method: string;
8
+ url: URL;
9
+ headers: Headers;
10
+ body?: string;
11
+ }
12
+ export interface HttpApiExecutorOptions {
13
+ /** The service's name in messages: "Notion". */
14
+ service: string;
15
+ /** The server the spec names, `https://api.notion.com`; a path template is appended to its path. */
16
+ baseUrl: string;
17
+ /** The caller's host-checked fetch (cli-base `hostFetch`), with whatever retry and pace it wraps. */
18
+ fetch: (command: Command) => FetchLike;
19
+ /** Read before any guard asks, so a missing sign-in fails first; these win over a header flag of the same name. */
20
+ headers: (command: Command, operation: ManifestOperation) => Record<string, string> | Promise<Record<string, string>>;
21
+ /**
22
+ * Every operation that is not a read goes through here: the CLI's guarded write, where a level of `ask` asks and
23
+ * the journal records it. What it returns is the answer printed.
24
+ */
25
+ write: (command: Command, operation: ManifestOperation, send: () => Promise<unknown>) => Promise<unknown>;
26
+ /** A read's scope, such as the CLI's run; by default the request is just sent. */
27
+ read?: (command: Command, operation: ManifestOperation, send: () => Promise<unknown>) => Promise<unknown>;
28
+ /**
29
+ * The service's own refusal, from its status and parsed answer; `undefined` keeps the shared one. Never asked for a
30
+ * write that failed on the service's side: that is always `outcome_unknown`.
31
+ */
32
+ failure?: (status: number, answer: unknown, operation: ManifestOperation) => CliError | undefined;
33
+ maxBytes?: number;
34
+ }
35
+ /** One generated HTTP operation and its flags as the request they stand for; nothing is sent. */
36
+ export declare const httpApiRequest: (operation: ManifestOperation, input: ApiCommandInput, baseUrl: string) => HttpApiRequest;
37
+ /**
38
+ * The `execute` of `generatedApiCommand` for any OpenAPI CLI: fills the path, adds the query, sends the JSON body
39
+ * 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).
42
+ */
43
+ export declare const httpApiExecutor: (options: HttpApiExecutorOptions) => (command: Command, operation: ManifestOperation, input: ApiCommandInput) => Promise<void>;
@@ -0,0 +1,160 @@
1
+ import { CliError, wallClock } from "@wirecat/cli-base";
2
+ import { providerWaitMs, readJsonResponse, statusToCode } from "@wirecat/cli-base/http";
3
+ import { providerRequest } from "../command-runs.js";
4
+ import { outputFor } from "../context.js";
5
+ import { itemOf, renderAnswer } from "../envelope.js";
6
+ import { parseApiJson } from "./api-input.js";
7
+ const LARGEST_ANSWER = 16 * 1024 * 1024;
8
+ /** `new URL` folds a `.` or `..` segment into its parent, so such an id would reach another endpoint. */
9
+ const segment = (name, value) => {
10
+ if (value === undefined || value === "" || value === "." || value === "..")
11
+ throw new CliError("validation_error", `${name} must name one item; an empty, "." or ".." id is refused`);
12
+ return encodeURIComponent(value);
13
+ };
14
+ /** One generated HTTP operation and its flags as the request they stand for; nothing is sent. */
15
+ export const httpApiRequest = (operation, input, baseUrl) => {
16
+ const { binding } = operation;
17
+ if (binding.kind !== "http")
18
+ throw new CliError("configuration_error", `${operation.command} is not an HTTP operation`);
19
+ if (operation.request?.contentType)
20
+ throw new CliError("validation_error", `${operation.command} sends ${operation.request.contentType}, which the generated command cannot send; nothing was sent`, { sent: false });
21
+ if (operation.response?.sensitive)
22
+ throw new CliError("validation_error", `${operation.command} answers with a credential, which the generated command never prints; nothing was sent`, { sent: false });
23
+ if (Object.keys(input.fields).length > 0)
24
+ throw new CliError("configuration_error", `${operation.command} has body fields as flags, which HTTP cannot send`);
25
+ if (!/^\/(?!\/)/.test(binding.path))
26
+ throw new CliError("configuration_error", `${operation.command} has a path that does not start with one /`);
27
+ const base = new URL(baseUrl);
28
+ const path = binding.path.replace(/\{([^}]+)\}/g, (_, name) => segment(name, input.path[name]));
29
+ const url = new URL(`${base.pathname.replace(/\/$/, "")}${path}`, base.origin);
30
+ for (const [name, raw] of Object.entries(input.query)) {
31
+ const parameter = operation.parameters.find((one) => one.in === "query" && one.name === name);
32
+ if (parameter?.schema.type === "array")
33
+ for (const item of raw.split(","))
34
+ url.searchParams.append(name, item.trim());
35
+ else
36
+ url.searchParams.set(name, raw);
37
+ }
38
+ const headers = new Headers(input.headers);
39
+ const body = input.body?.trim() ? input.body : undefined;
40
+ // The command's checkBody may not parse the body; text that is not JSON never reaches the service.
41
+ if (body !== undefined)
42
+ parseApiJson(body);
43
+ if (body !== undefined)
44
+ headers.set("content-type", "application/json");
45
+ headers.set("accept", "application/json");
46
+ return { method: binding.method, url, headers, ...(body === undefined ? {} : { body }) };
47
+ };
48
+ /** `/v1/pages/{page_id}` → `/v1/pages/:page_id`: the run record keeps the template, never an id. */
49
+ const templateOf = (path) => path.replace(/\{([^}]+)\}/g, ":$1");
50
+ const answerOf = async (response, maxBytes) => {
51
+ if (response.status === 204 || !response.body || response.headers.get("content-length") === "0")
52
+ return {};
53
+ return readJsonResponse(response, { maxBytes });
54
+ };
55
+ /**
56
+ * The `execute` of `generatedApiCommand` for any OpenAPI CLI: fills the path, adds the query, sends the JSON body
57
+ * 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).
60
+ */
61
+ export const httpApiExecutor = (options) => async (command, operation, input) => {
62
+ 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
+ for (const [name, value] of Object.entries(await options.headers(command, operation)))
66
+ 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
108
+ ? await options.write(command, operation, send)
109
+ : await (options.read ?? ((_command, _operation, call) => call()))(command, operation, send);
110
+ renderAnswer(command, outputFor(command), itemOf(answer));
111
+ };
112
+ const unanswered = (service, writes, error) => {
113
+ // A refusal before sending (an undeclared host) changed nothing; a write stopped in flight may have landed (WC-LIFE-9).
114
+ if (error instanceof CliError && (!writes || error.details?.sent === false))
115
+ return error;
116
+ if (writes)
117
+ return new CliError("outcome_unknown", `${service} did not answer a write; check it before repeating the write`, {
118
+ retryable: false,
119
+ });
120
+ return error?.name === "TimeoutError"
121
+ ? new CliError("timeout", `${service} did not answer in time`, { retryable: true })
122
+ : new CliError("network_error", `${service} could not be reached`, { retryable: true });
123
+ };
124
+ /** The service took the request; only its answer is lost, so a write must not look safe to send again. */
125
+ const unreadable = (service, writes, status) => writes
126
+ ? new CliError("outcome_unknown", `${service} took the write but its answer could not be read; check it before repeating the write`, {
127
+ status,
128
+ retryable: false,
129
+ })
130
+ : new CliError("invalid_response", `${service} sent an answer that could not be read`, { status, retryable: true });
131
+ const refusal = (service, operation, response, writes) => {
132
+ const { status } = response;
133
+ if (status === 429) {
134
+ const wait = providerWaitMs(response.headers, wallClock);
135
+ return new CliError("rate_limited", `${service} asked to slow down; retry the command later`, {
136
+ status,
137
+ retryable: true,
138
+ ...(wait === undefined ? {} : { retry_after_ms: wait }),
139
+ });
140
+ }
141
+ if (status >= 500 && writes)
142
+ return new CliError("outcome_unknown", `${service} failed during a write; check it before repeating the write`, {
143
+ status,
144
+ retryable: false,
145
+ });
146
+ if (status === 401)
147
+ return new CliError("authentication_error", `${service} refused the sign-in; sign in again`, {
148
+ reason: "auth.failed",
149
+ status,
150
+ });
151
+ if (status === 403)
152
+ return new CliError("permission_error", `${service} denied ${operation.command} to this account`, {
153
+ reason: "access.denied",
154
+ status,
155
+ });
156
+ return new CliError(statusToCode(status), `${service} refused ${operation.command} (HTTP ${status})`, {
157
+ status,
158
+ retryable: status >= 500,
159
+ });
160
+ };
@@ -16,5 +16,5 @@ export interface CommandAvailability {
16
16
  }
17
17
  /** Discovery and execution use the same permission decision. */
18
18
  export declare const commandAvailability: (info: AvailabilityCommand, levels: Readonly<Record<PermissionKey, Level>>, keyOf?: (path: readonly string[]) => PermissionKey | null | undefined, authority?: (path: readonly string[]) => boolean, readOnly?: boolean, mcp?: boolean, declared?: CommandPermissions,
19
- /** Whether a command only fetches into the store (`fetchesOnlyAt`): setup's "read only" answer lets it run. */
19
+ /** Whether a command only fetches into the store (`fetchesOnlyAt`): a `readonly` level lets it run. */
20
20
  fetches?: (path: readonly string[]) => boolean) => CommandAvailability;
@@ -1,13 +1,13 @@
1
1
  import { writes } from "@wirecat/cli-base/standards";
2
- import { AUTHORITY_KEY, authorityAllowed, BOT_API_KEY, botApiAllowed, CEILING_KEY, isBotApi, keyForCommand, levelFor, readKeysForCommand, } from "../sends/permissions.js";
2
+ import { AUTHORITY_KEY, authorityAllowed, BOT_API_KEY, botApiAllowed, isBotApi, keyForCommand, levelFor, readKeysForCommand, } from "../sends/permissions.js";
3
3
  import { changesMessenger } from "./effects.js";
4
4
  /** Discovery and execution use the same permission decision. */
5
5
  export const commandAvailability = (info, levels, keyOf, authority, readOnly = false, mcp = true, declared,
6
- /** Whether a command only fetches into the store (`fetchesOnlyAt`): setup's "read only" answer lets it run. */
6
+ /** Whether a command only fetches into the store (`fetchesOnlyAt`): a `readonly` level lets it run. */
7
7
  fetches) => {
8
8
  const declaredKey = declared?.keyOf(info.path);
9
9
  const key = declared ? declaredKey : (keyOf?.(info.path) ?? keyForCommand(info.path));
10
- const { level, key: named } = key ? levelFor(levels, key, declared?.defaults) : { level: "allow", key: null };
10
+ const { level } = key ? levelFor(levels, key, declared?.defaults) : { level: "allow" };
11
11
  const judged = { ...(key ? { permission: key } : {}), level };
12
12
  const blocked = (reason, permission) => ({
13
13
  available: false,
@@ -27,7 +27,7 @@ fetches) => {
27
27
  return blocked(`the profile requires ${BOT_API_KEY}: allow`, BOT_API_KEY);
28
28
  if (level === "deny")
29
29
  return blocked(`the profile denies ${key}`);
30
- if (level === "readonly" && writes(info.effects) && !(named === CEILING_KEY && fetches?.(info.path) === true))
30
+ if (level === "readonly" && writes(info.effects) && fetches?.(info.path) !== true)
31
31
  return blocked(`${key} is readonly in this profile`);
32
32
  const denied = (declared ? [] : readKeysForCommand(info.path)).find((read) => levelFor(levels, read).level === "deny");
33
33
  return denied ? blocked(`the profile denies ${denied}`, denied) : { available: true, ...judged };
@@ -5,6 +5,7 @@ import { outputFor } from "./context.js";
5
5
  import { changesAuthority } from "./effects.js";
6
6
  import { itemOf, renderAnswer, snakeKeys } from "./envelope.js";
7
7
  import { previewBody } from "./preview.js";
8
+ import { shareShadowedOptions } from "./shadowed-options.js";
8
9
  const descendants = (command, into = new Set()) => {
9
10
  into.add(command);
10
11
  for (const child of command.commands)
@@ -18,13 +19,14 @@ const descendants = (command, into = new Set()) => {
18
19
  */
19
20
  const previewWrites = (messenger) => (hooked, action) => {
20
21
  // Each command carries its own hook, so one a CLI moves under its own group keeps it.
21
- if (hooked !== action || action.optsWithGlobals().dryRun !== true)
22
+ if (hooked !== action)
22
23
  return;
23
- // `run` hands the global flag to a command's own --dry-run; another host's program does not.
24
- if (action.options.some((option) => option.long === "--dry-run")) {
25
- action.setOptionValue("dryRun", true);
24
+ // `run` hands a global flag to the command's own option of that name; another host's program does not.
25
+ shareShadowedOptions(action);
26
+ if (action.optsWithGlobals().dryRun !== true)
27
+ return;
28
+ if (action.options.some((option) => option.long === "--dry-run"))
26
29
  return;
27
- }
28
30
  if (!writes(metaOf(action).effects) && !changesAuthority(action))
29
31
  return;
30
32
  // Commander reads the handler after the hooks, so swapping it here stops the write; each run builds its program anew.
@@ -30,7 +30,7 @@ export declare const refuseWriteBeforeConnecting: (action: Command, { app, env,
30
30
  }) => void;
31
31
  /**
32
32
  * A command of a CLI that declares its own keys (`commandPermissions`), refused by its key before anything connects:
33
- * `deny` stops it, `readonly` stops a write (setup's "read only" answer still lets a fetch into the store run), and
33
+ * `deny` stops it, `readonly` stops a write but lets a fetch into the store run, whichever key set it, and
34
34
  * the read-only lock stops a write to the service; a command that declares no effects counts as both. `ask` is left to the write
35
35
  * guard, which can put the question. A saved or `--permission` key that names no command stops every keyed command;
36
36
  * housekeeping still runs, so `config unset` can remove it. Under the lock a non-messenger CLI still previews a
@@ -96,7 +96,7 @@ export const refuseWriteBeforeConnecting = (action, { app, env, dryRun, resolve
96
96
  };
97
97
  /**
98
98
  * A command of a CLI that declares its own keys (`commandPermissions`), refused by its key before anything connects:
99
- * `deny` stops it, `readonly` stops a write (setup's "read only" answer still lets a fetch into the store run), and
99
+ * `deny` stops it, `readonly` stops a write but lets a fetch into the store run, whichever key set it, and
100
100
  * the read-only lock stops a write to the service; a command that declares no effects counts as both. `ask` is left to the write
101
101
  * guard, which can put the question. A saved or `--permission` key that names no command stops every keyed command;
102
102
  * housekeeping still runs, so `config unset` can remove it. Under the lock a non-messenger CLI still previews a
@@ -126,7 +126,7 @@ export const refuseByCommandPermissions = (action, permissions, { app, env, dryR
126
126
  throw new CliError("permission_error", `profile ${settings.profile} denies ${key} (permissions.${named} is deny, from the ` +
127
127
  `${settings.permissionSources[named ?? ""] ?? "default"})`, { permission: key });
128
128
  }
129
- if (level === "readonly" && writes(effects) && !(named === CEILING_KEY && fetchesOnly(action)))
129
+ if (level === "readonly" && writes(effects) && !fetchesOnly(action))
130
130
  throw levelRefusal({
131
131
  profile: settings.profile,
132
132
  command: app.command,
@@ -61,11 +61,18 @@ export declare const narrowsUnderLock: <T extends Command>(command: T) => T;
61
61
  export declare const admittedUnderLock: (command: Command) => boolean;
62
62
  /** A local edit remains an edit even when it first fetches metadata from the messenger. */
63
63
  export declare const changesStore: <T extends Command>(command: T) => T;
64
+ /**
65
+ * Marks a command that writes the owner's files outside the store through a folder it does not take as an option, a
66
+ * saved job's folder say: it stays a write, which a `readonly` level stops.
67
+ */
68
+ export declare const writesOwnerFiles: <T extends Command>(command: T) => T;
64
69
  /**
65
70
  * Reads the provider and only keeps what it read in the owner's store — a sync, a list that refreshes it. An MCP server
66
71
  * offers it through the read tool (owner ruling, 2026-10-27; WC-CMD-17): it changes nothing at the provider or for
67
- * other people. A local edit (`changesStore`), an authority change, a call to another service (`reachesOtherService`,
68
- * a model download) and a command that saves files (a download, a folder to write into) stay writes.
72
+ * other people. A local edit (`changesStore`), an authority change, a call to another service
73
+ * (`reachesOtherService`, a model download) and a command that saves files (a download, a folder to write into,
74
+ * `writesOwnerFiles`) stay writes. A sign-in (`logsInOrOut`) counts as a fetch, so a `readonly` level lets the owner
75
+ * sign in, but no MCP server runs one through its read tool.
69
76
  */
70
77
  export declare const fetchesOnly: (command: Command) => boolean;
71
78
  /** `fetchesOnly` by command path under `root`, as an MCP catalogue asks it; an unknown path is not one. */
@@ -104,16 +104,28 @@ export const changesStore = (command) => {
104
104
  STORE_WRITES.add(command);
105
105
  return command;
106
106
  };
107
+ const OWNER_FILES = new WeakSet();
108
+ /**
109
+ * Marks a command that writes the owner's files outside the store through a folder it does not take as an option, a
110
+ * saved job's folder say: it stays a write, which a `readonly` level stops.
111
+ */
112
+ export const writesOwnerFiles = (command) => {
113
+ OWNER_FILES.add(command);
114
+ return command;
115
+ };
107
116
  /** A download or a folder to write into: files outside the store, which the owner places, not an agent. */
108
- const savesFiles = (command) => command.name() === "download" ||
117
+ const savesFiles = (command) => OWNER_FILES.has(command) ||
118
+ command.name() === "download" ||
109
119
  [...command.options.map((option) => option.attributeName()), ...command.registeredArguments.map((one) => one.name())]
110
120
  .map((name) => name.toLowerCase())
111
121
  .some((name) => name === "dir" || name.endsWith("dir") || name === "output");
112
122
  /**
113
123
  * Reads the provider and only keeps what it read in the owner's store — a sync, a list that refreshes it. An MCP server
114
124
  * offers it through the read tool (owner ruling, 2026-10-27; WC-CMD-17): it changes nothing at the provider or for
115
- * other people. A local edit (`changesStore`), an authority change, a call to another service (`reachesOtherService`,
116
- * a model download) and a command that saves files (a download, a folder to write into) stay writes.
125
+ * other people. A local edit (`changesStore`), an authority change, a call to another service
126
+ * (`reachesOtherService`, a model download) and a command that saves files (a download, a folder to write into,
127
+ * `writesOwnerFiles`) stay writes. A sign-in (`logsInOrOut`) counts as a fetch, so a `readonly` level lets the owner
128
+ * sign in, but no MCP server runs one through its read tool.
117
129
  */
118
130
  export const fetchesOnly = (command) => {
119
131
  const effects = metaOf(command).effects;
@@ -160,7 +172,7 @@ const writesFileNow = (command) => {
160
172
  * What an MCP server runs through `read`: a command that only fetches into the store (`fetchesOnly`), and one whose
161
173
  * only write is a file the tool cannot name (`writesFileOnlyWith`).
162
174
  */
163
- export const readsOverMcp = (command) => fetchesOnly(command) || FILE_OPTION.has(command);
175
+ export const readsOverMcp = (command) => (fetchesOnly(command) && !LOGIN.has(command)) || FILE_OPTION.has(command);
164
176
  /** `readsOverMcp` by command path under `root`, as an MCP catalogue asks it; an unknown path is not one. */
165
177
  export const readsOverMcpAt = (root) => (path) => {
166
178
  let at = root;