@wirecat/cli-core 0.660.0 → 0.661.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.
- package/CHANGELOG.md +68 -0
- package/dist/attachments/markup.js +2 -11
- package/dist/calendar/mcp/index.js +23 -17
- package/dist/cli/bot/api-http.d.ts +43 -0
- package/dist/cli/bot/api-http.js +160 -0
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.js +1 -0
- package/dist/cli/messenger/rankings-command.js +2 -1
- package/dist/cli/messenger/serve-command.js +7 -2
- package/dist/cli/messenger/tasks-command.d.ts +7 -2
- package/dist/cli/messenger/tasks-command.js +6 -3
- package/dist/cli/schedule/schedule-command.js +3 -0
- package/dist/domain/html-entities.d.ts +5 -0
- package/dist/domain/html-entities.js +56 -0
- package/dist/domain/locator.js +12 -4
- package/dist/domain/references.js +11 -3
- package/dist/entities/listings.d.ts +4 -4
- package/dist/entities/listings.js +2 -2
- package/dist/mail/headers.js +3 -3
- package/dist/mail/parse.js +9 -8
- package/dist/mail/resume.d.ts +4 -1
- package/dist/mail/resume.js +11 -2
- package/dist/mail/retry.d.ts +2 -1
- package/dist/mail/retry.js +6 -4
- package/dist/mail/sender-scores.js +1 -6
- package/dist/mail/stored.d.ts +4 -1
- package/dist/mail/stored.js +6 -1
- package/dist/mail/sync.js +8 -3
- package/dist/mail/testing/fake.d.ts +2 -0
- package/dist/mail/testing/fake.js +3 -1
- package/dist/mcp/all-profiles.js +8 -18
- package/dist/mcp/app-server.js +1 -16
- package/dist/mcp/bot/server.js +9 -7
- package/dist/mcp/caller.js +2 -1
- package/dist/mcp/prompts.js +17 -2
- package/dist/mcp/server.js +10 -16
- package/dist/mcp/stdio-wire.d.ts +5 -2
- package/dist/mcp/stdio-wire.js +39 -12
- package/dist/mcp/tool.js +3 -1
- package/dist/mcp/tools/messages-photo.js +4 -2
- package/dist/meetings/cli/search.js +8 -2
- package/dist/meetings/hit-query.js +11 -6
- package/dist/sends/guard.js +7 -1
- package/dist/services/listings.js +2 -1
- package/dist/services/message-resolution.js +6 -3
- package/dist/store/sqlite/mention-drain.d.ts +4 -1
- package/dist/store/sqlite/mention-drain.js +7 -3
- package/dist/store/sqlite/messages.js +12 -1
- package/dist/store/sqlite/query-filter.d.ts +1 -0
- package/dist/store/sqlite/query-filter.js +2 -2
- package/dist/store/sqlite/tags.js +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,74 @@ 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.661.0 — 14.11.2026
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **`httpApiExecutor` runs a generated OpenAPI operation without a hand-written `execute`.** Give it to
|
|
13
|
+
`generatedApiCommand` with the server address, the CLI's host-checked fetch, its headers (the sign-in, a pinned
|
|
14
|
+
API version) and its guarded write. It fills the path, repeats an array query value, sends the JSON body and
|
|
15
|
+
prints the answer. Every operation that is not a read goes through the CLI's `write`, so a level of `ask` asks and
|
|
16
|
+
the journal records it; `--dry-run` previews before anything is sent. These are refused before any request: an id
|
|
17
|
+
of `.` or `..`, a path that does not start with one `/`, a body that is not JSON, a multipart body, an operation
|
|
18
|
+
that answers with a credential, and an undeclared host. The service's own error text is never repeated. A 401 and
|
|
19
|
+
a 403 name the sign-in or the access (`auth.failed`, `access.denied`). A write that got no answer, a 5xx, or a 2xx
|
|
20
|
+
whose answer cannot be read is `outcome_unknown`. `httpApiRequest` gives the request alone, for a test or a preview.
|
|
21
|
+
|
|
22
|
+
### Changed — may break callers
|
|
23
|
+
|
|
24
|
+
- **Dates in list queries, and the calendar MCP tools, read the computer's zone.** `today` and a bare date in
|
|
25
|
+
`tasks list`, `meetings list`, `chats list`, `tags list` and the other list queries started in UTC; the calendar
|
|
26
|
+
tools' `timezone` defaulted to UTC, so `event_create` at `10:00` made an 11:00 Madrid event. Both now read the
|
|
27
|
+
local zone, as search and the CLI do.
|
|
28
|
+
- **`messages_photo` takes `attachment`, from 1,** as `attachments_show` and `messages download --attachment` do. It
|
|
29
|
+
took `index` from 0; a number past the last file now says how many files the message has.
|
|
30
|
+
- **`tasks --due` with a date alone is the end of that day,** not its midnight, so a task due on the 20th is not
|
|
31
|
+
overdue all day. `schedule --at-time` refuses a date alone, as `messages send --at-time` does.
|
|
32
|
+
- **An event two accounts hold is read only from the account named.** `event_show` and `event_people` without
|
|
33
|
+
`account_id` refuse it with the accounts to choose from, as the calendar write tools do, and the answer names the
|
|
34
|
+
one account read.
|
|
35
|
+
|
|
36
|
+
### Fixed
|
|
37
|
+
|
|
38
|
+
- **`documents show` says more text follows after emoji.** `has_more` compared the part's length in UTF-16 units
|
|
39
|
+
with the whole text's length in code points, so a part holding emoji, or another character outside the Basic
|
|
40
|
+
Multilingual Plane, could report no more text before the end and a reader stopped early. `text_offset`,
|
|
41
|
+
`text_length`, `--cursor` and `--max-chars` all count Unicode code points: the next part starts at `text_offset`
|
|
42
|
+
plus the code points of `text` (`[...text].length` in JavaScript, not `text.length`), and a part never splits a
|
|
43
|
+
surrogate pair. A combining mark is a code point of its own, so a cut may fall between a letter and its accent.
|
|
44
|
+
- **A stale copy no longer overwrites a newer edit.** A history page fetched before `serve` saw an edit turned the
|
|
45
|
+
text back, filed the edit as the old version and dropped its vectors.
|
|
46
|
+
- **`serve` stops auto-replies as soon as `replies.send` is denied,** without a restart.
|
|
47
|
+
- **A stdio MCP server closes after a client cancels a call and closes stdin,** and stops on SIGINT or SIGTERM while
|
|
48
|
+
answers are pending. A call cancelled while it waited in the queue never runs, so a cancelled send does not go out.
|
|
49
|
+
The bot server answers a one-shot pipe's calls before it closes, as the other servers do.
|
|
50
|
+
- **`mcp serve --profiles all` refuses with the shared error object** (`validation_error`, `authentication_error`,
|
|
51
|
+
`outcome_unknown`), not plain text.
|
|
52
|
+
- **An MCP answer counts once against the 4 MB limit,** as the CLI counts what it prints; an answer of about 2 MB
|
|
53
|
+
failed with `output.too-large` over MCP alone.
|
|
54
|
+
- **An HTTP MCP client can no longer pass on a caller** meant only for the every-profile server's own connections.
|
|
55
|
+
- **`t.me` links name Telegram chats only,** never a chat of another messenger that shares the username.
|
|
56
|
+
- **Mail:** a plain address beside a bracketed one in To or Cc is kept (`alice@x.com, "Bob" <bob@y.com>`); HTML
|
|
57
|
+
mail decodes numeric and typographic entities (`’`, `—`); an email kept as an envelope stays one while a
|
|
58
|
+
run cannot read its headers; a resumed sync follows every rule field, not only from, domain and list id;
|
|
59
|
+
`--retry-attachments` stops on the signal; listed mail is ordered by instant.
|
|
60
|
+
- **The send guard** refuses a send time it cannot read, and counts a journal line with an unreadable time in the
|
|
61
|
+
hour it was written.
|
|
62
|
+
- **A malformed `%` escape in a reference** (`msg:telegram/1/2/%E0`) is a `validation_error`, not an unknown failure.
|
|
63
|
+
- **`--chat` finds a chat the owner left when several accounts are read,** as with one account.
|
|
64
|
+
- **A configured `limit` above 100 no longer breaks `stats messages top`;** it is capped at the ranking's 100.
|
|
65
|
+
- **`search meetings`:** `date>=30d` works with `--until-time`, `--since-time` takes `7d`, and `budget && project:X`
|
|
66
|
+
or `budget +project:X` leave no dangling operator.
|
|
67
|
+
- **The MCP `review` prompt** writes `since` as the query reads it: `1d ago` as `date>1d`, an ISO time as its UTC
|
|
68
|
+
instant.
|
|
69
|
+
- **The calendar MCP tools** refuse a `limit` over 1000 and an empty attendee.
|
|
70
|
+
- **The tag list** pages without repeating or skipping rows that tie.
|
|
71
|
+
- **`listedOf` labels the owner's own stored mail `Sent`.** A stored email has no folder, so mail the
|
|
72
|
+
owner sent from an IMAP mailbox or without a Gmail `Sent` label looked received. A rule or a cleanup judged from
|
|
73
|
+
stored mail then saw no sender the owner wrote to: "replied" was false and scores that depend on it came out
|
|
74
|
+
wrong. `scoreSenders` did this step on its own; it now uses `listedOf` as it is.
|
|
75
|
+
|
|
8
76
|
## 0.660.0 — 14.11.2026
|
|
9
77
|
|
|
10
78
|
### 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
|
-
"
|
|
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: {
|
|
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" &&
|
|
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
|
-
|
|
222
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
365
|
+
zone: timezoneOf(args.timezone),
|
|
360
366
|
names: {
|
|
361
367
|
notify: "notify: true or false",
|
|
362
368
|
id: "operation_id",
|
|
@@ -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
|
+
};
|
package/dist/cli/index.d.ts
CHANGED
|
@@ -57,6 +57,7 @@ export { askBeforeWrite } from "./ask-before-write.js";
|
|
|
57
57
|
export { actorOf } from "./author.js";
|
|
58
58
|
export { type BaseStagesCommandOptions, baseStagesCommand } from "./base-stages-command.js";
|
|
59
59
|
export type { ApiCommandInput, ApiCommands } from "./bot/api.js";
|
|
60
|
+
export { type HttpApiExecutorOptions, type HttpApiRequest, httpApiExecutor, httpApiRequest } from "./bot/api-http.js";
|
|
60
61
|
export { apiFlagOf, apiJson, apiOptionKey, apiPlainJson, checkApiBody, checkApiParameter, parseApiJson, readApiBody, } from "./bot/api-input.js";
|
|
61
62
|
export { prepareRpcApiBody, type RpcApiBody } from "./bot/api-rpc.js";
|
|
62
63
|
export { type BotContext, botContext, botWords } from "./bot/context.js";
|
package/dist/cli/index.js
CHANGED
|
@@ -50,6 +50,7 @@ export { openAppStore } from "./app-store.js";
|
|
|
50
50
|
export { askBeforeWrite } from "./ask-before-write.js";
|
|
51
51
|
export { actorOf } from "./author.js";
|
|
52
52
|
export { baseStagesCommand } from "./base-stages-command.js";
|
|
53
|
+
export { httpApiExecutor, httpApiRequest } from "./bot/api-http.js";
|
|
53
54
|
export { apiFlagOf, apiJson, apiOptionKey, apiPlainJson, checkApiBody, checkApiParameter, parseApiJson, readApiBody, } from "./bot/api-input.js";
|
|
54
55
|
export { prepareRpcApiBody } from "./bot/api-rpc.js";
|
|
55
56
|
export { botContext, botWords } from "./bot/context.js";
|
|
@@ -61,7 +61,8 @@ export const rankingsTopCommand = (messenger, target) => {
|
|
|
61
61
|
return services.rankings.top(target, {
|
|
62
62
|
...params,
|
|
63
63
|
...sync,
|
|
64
|
-
|
|
64
|
+
// A configured limit is a listing's page; a ranking takes at most 100 rows, so it is capped, not refused.
|
|
65
|
+
limit: params.limit ?? Math.min(context.settings.limit, 100),
|
|
65
66
|
signal: environmentOf(this).commandSignal ?? environmentOf(this).signal,
|
|
66
67
|
...(saved ? { saved } : {}),
|
|
67
68
|
});
|
|
@@ -80,7 +80,7 @@ export const serveCommand = (messenger) => {
|
|
|
80
80
|
});
|
|
81
81
|
};
|
|
82
82
|
const counts = {};
|
|
83
|
-
const rules = replying(context, messenger, Date.parse(startedAt));
|
|
83
|
+
const rules = replying(context, messenger, Date.parse(startedAt), () => messenger.resolveSettings(this.optsWithGlobals(), { env: context.env }));
|
|
84
84
|
const tasks = tasking(context, warn);
|
|
85
85
|
const { handled, startSyncDelayMs, outdated: outdatedHook } = environmentOf(this);
|
|
86
86
|
const count = (event) => {
|
|
@@ -226,7 +226,7 @@ const NO_REPLIES = {
|
|
|
226
226
|
stop: () => { },
|
|
227
227
|
summary: () => ({}),
|
|
228
228
|
};
|
|
229
|
-
const replying = (context, messenger, since) => {
|
|
229
|
+
const replying = (context, messenger, since, reload) => {
|
|
230
230
|
if (messenger.autoReplies === false)
|
|
231
231
|
return NO_REPLIES;
|
|
232
232
|
const controller = new AbortController();
|
|
@@ -252,6 +252,11 @@ const replying = (context, messenger, since) => {
|
|
|
252
252
|
if (connection === undefined || controller.signal.aborted)
|
|
253
253
|
return;
|
|
254
254
|
const open = connection;
|
|
255
|
+
// serve runs for days: `config set permissions.replies.send deny` must stop the next reply, as it stops the next
|
|
256
|
+
// MCP call. The send guard reads the same settings.
|
|
257
|
+
const current = reload();
|
|
258
|
+
settings.permissions = current.permissions;
|
|
259
|
+
settings.permissionSources = current.permissionSources;
|
|
255
260
|
const answer = await replyTo({
|
|
256
261
|
rulesPath: repliesPathFor(app, profile, env),
|
|
257
262
|
statePath: repliesStatePathFor(app, profile, env),
|
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import { Command } from "commander";
|
|
2
2
|
import { type Messenger } from "./context.js";
|
|
3
|
-
/**
|
|
4
|
-
|
|
3
|
+
/**
|
|
4
|
+
* `none` clears a date; anything else is a time ahead. Not `null`: commander stores a parser's `null` as "". With
|
|
5
|
+
* `end`, a date alone is the end of that day: a task due on the 20th is not overdue all of the 20th.
|
|
6
|
+
*/
|
|
7
|
+
export declare const dateOrNone: (flag: string, { end }?: {
|
|
8
|
+
end?: boolean;
|
|
9
|
+
}) => (typed: string) => "none" | Date;
|
|
5
10
|
/** What waits on the owner — kept in the local store by `src/tasks/`; nothing here reaches the messenger. */
|
|
6
11
|
export declare const tasksCommand: (messenger: Messenger) => Command;
|
|
7
12
|
export declare const tasksStatsCommand: (messenger: Messenger) => Command;
|
|
@@ -96,8 +96,11 @@ const pairLine = (pair) => [
|
|
|
96
96
|
`${pair.task?.title ?? ""} | ${pair.other.title}`,
|
|
97
97
|
`(${pair.reasons.join(", ")})`,
|
|
98
98
|
].join(" ");
|
|
99
|
-
/**
|
|
100
|
-
|
|
99
|
+
/**
|
|
100
|
+
* `none` clears a date; anything else is a time ahead. Not `null`: commander stores a parser's `null` as "". With
|
|
101
|
+
* `end`, a date alone is the end of that day: a task due on the 20th is not overdue all of the 20th.
|
|
102
|
+
*/
|
|
103
|
+
export const dateOrNone = (flag, { end = false } = {}) => (typed) => typed.trim().toLowerCase() === "none" ? "none" : new Date(aheadOf(typed, flag, Date.now(), { end }));
|
|
101
104
|
const durationOf = (flag) => (typed) => {
|
|
102
105
|
const wanted = typed.trim();
|
|
103
106
|
const ms = Date.now() - momentOf(wanted, flag);
|
|
@@ -108,7 +111,7 @@ const durationOf = (flag) => (typed) => {
|
|
|
108
111
|
const planOptions = (command, verb) => command
|
|
109
112
|
.option("--title <title>", `one line: the action and its object — ${verb}`)
|
|
110
113
|
.option("--description <text>", "the detail, in Markdown: who owes whom, done when, next step, keywords")
|
|
111
|
-
.option("--due <time>", "when it must be done: an ISO 8601 time or 2h, 3d from now; none clears it", dateOrNone("--due"))
|
|
114
|
+
.option("--due <time>", "when it must be done: an ISO 8601 time or 2h, 3d from now; none clears it", dateOrNone("--due", { end: true }))
|
|
112
115
|
.option("--remind-time <time>", "when to look at it again: an ISO 8601 time or 2h, 3d from now; none clears it", dateOrNone("--remind-time"))
|
|
113
116
|
.option("--assignee <person...>", "who does it: sender (whoever sent the task's message) or person:<id>; none clears it. Leave it out when " +
|
|
114
117
|
"unsure: a task with no assignee is better than none");
|
|
@@ -52,6 +52,9 @@ const whenOf = ({ every, at = [], atTime }, minimum) => {
|
|
|
52
52
|
throw new CliError("validation_error", "say when: --every <30m|2h|1d>, --at HH:MM (daily) or --at 'mon HH:MM' (weekly), repeated for more times, or --at-time <30m|2d|ISO time>");
|
|
53
53
|
}
|
|
54
54
|
if (atTime) {
|
|
55
|
+
// As messages send --at-time: a date alone would be its midnight, which nobody means by "send on the 20th".
|
|
56
|
+
if (/^\d{4}-\d{2}-\d{2}$/.test(atTime.trim()))
|
|
57
|
+
throw new CliError("validation_error", `--at-time needs a time of day as well: ${atTime.trim()}T09:00`);
|
|
55
58
|
const time = aheadOf(atTime, "--at-time");
|
|
56
59
|
if (time <= Date.now())
|
|
57
60
|
throw new CliError("validation_error", "--at-time is in the past");
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTML character references as text, in one pass so `&lt;` stays the text `<`. Numeric ones are all decoded;
|
|
3
|
+
* of the named ones, those that mail and calendar invitations use. An unknown name stays as written.
|
|
4
|
+
*/
|
|
5
|
+
export declare const decodeEntities: (text: string) => string;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
const NAMED = {
|
|
2
|
+
amp: "&",
|
|
3
|
+
lt: "<",
|
|
4
|
+
gt: ">",
|
|
5
|
+
quot: '"',
|
|
6
|
+
apos: "'",
|
|
7
|
+
nbsp: "\u00a0",
|
|
8
|
+
shy: "\u00ad",
|
|
9
|
+
ensp: "\u2002",
|
|
10
|
+
emsp: "\u2003",
|
|
11
|
+
thinsp: "\u2009",
|
|
12
|
+
zwnj: "\u200c",
|
|
13
|
+
zwj: "\u200d",
|
|
14
|
+
lsquo: "‘",
|
|
15
|
+
rsquo: "’",
|
|
16
|
+
sbquo: "‚",
|
|
17
|
+
ldquo: "“",
|
|
18
|
+
rdquo: "”",
|
|
19
|
+
bdquo: "„",
|
|
20
|
+
laquo: "«",
|
|
21
|
+
raquo: "»",
|
|
22
|
+
lsaquo: "‹",
|
|
23
|
+
rsaquo: "›",
|
|
24
|
+
ndash: "–",
|
|
25
|
+
mdash: "—",
|
|
26
|
+
hellip: "…",
|
|
27
|
+
bull: "•",
|
|
28
|
+
middot: "·",
|
|
29
|
+
copy: "©",
|
|
30
|
+
reg: "®",
|
|
31
|
+
trade: "™",
|
|
32
|
+
euro: "€",
|
|
33
|
+
pound: "£",
|
|
34
|
+
yen: "¥",
|
|
35
|
+
cent: "¢",
|
|
36
|
+
deg: "°",
|
|
37
|
+
plusmn: "±",
|
|
38
|
+
times: "×",
|
|
39
|
+
divide: "÷",
|
|
40
|
+
sect: "§",
|
|
41
|
+
para: "¶",
|
|
42
|
+
iexcl: "¡",
|
|
43
|
+
iquest: "¿",
|
|
44
|
+
};
|
|
45
|
+
const character = (code, entity) => code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : entity;
|
|
46
|
+
/**
|
|
47
|
+
* HTML character references as text, in one pass so `&lt;` stays the text `<`. Numeric ones are all decoded;
|
|
48
|
+
* of the named ones, those that mail and calendar invitations use. An unknown name stays as written.
|
|
49
|
+
*/
|
|
50
|
+
export const decodeEntities = (text) => text.replace(/&(#x[0-9a-f]{1,6}|#\d{1,7}|[a-z]{2,8});/gi, (entity, body) => {
|
|
51
|
+
if (body[0] !== "#")
|
|
52
|
+
return NAMED[body] ?? NAMED[body.toLowerCase()] ?? entity;
|
|
53
|
+
return body[1] === "x" || body[1] === "X"
|
|
54
|
+
? character(Number.parseInt(body.slice(2), 16), entity)
|
|
55
|
+
: character(Number(body.slice(1)), entity);
|
|
56
|
+
});
|
package/dist/domain/locator.js
CHANGED
|
@@ -6,9 +6,17 @@ export const isLocator = (reference) => reference.trim().startsWith(SCHEME);
|
|
|
6
6
|
export const parseLocator = (reference) => {
|
|
7
7
|
const trimmed = reference.trim();
|
|
8
8
|
const parts = trimmed.startsWith(SCHEME) ? trimmed.slice(SCHEME.length).split("/") : [];
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
const
|
|
9
|
+
const malformed = () => new CliError("validation_error", `"${singleLine(reference)}" is not a message locator — expected msg:<provider>/<account>/<chat>/<message>`);
|
|
10
|
+
if (parts.length !== 4 || parts.some((part) => part === ""))
|
|
11
|
+
throw malformed();
|
|
12
|
+
const decoded = (part) => {
|
|
13
|
+
try {
|
|
14
|
+
return decodeURIComponent(part);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
throw malformed();
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
const [provider, account, chat, message] = parts.map(decoded);
|
|
13
21
|
return { provider, account, chat, message };
|
|
14
22
|
};
|