@wirecat/cli-core 0.622.0 → 0.624.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 (69) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/dist/background/backfill.d.ts +1 -1
  3. package/dist/background/backfill.js +1 -1
  4. package/dist/background/budget.d.ts +2 -0
  5. package/dist/background/report/stored-templates.d.ts +21 -3
  6. package/dist/background/report/stored-templates.js +34 -6
  7. package/dist/background/schedules.d.ts +10 -27
  8. package/dist/background/schedules.js +8 -167
  9. package/dist/background/timers.d.ts +19 -0
  10. package/dist/background/timers.js +175 -0
  11. package/dist/background/when.d.ts +49 -0
  12. package/dist/background/when.js +84 -0
  13. package/dist/calendar/mcp/index.d.ts +12 -12
  14. package/dist/calendar/prepare.d.ts +14 -0
  15. package/dist/cli/app-doctor-command.js +2 -1
  16. package/dist/cli/envelope.d.ts +28 -0
  17. package/dist/cli/index.d.ts +3 -2
  18. package/dist/cli/index.js +3 -2
  19. package/dist/cli/messenger/messages-search-command.js +4 -0
  20. package/dist/cli/program.js +6 -3
  21. package/dist/cli/schedule/schedule-command.d.ts +100 -3
  22. package/dist/cli/schedule/schedule-command.js +277 -113
  23. package/dist/cli/templates-command.js +45 -20
  24. package/dist/domain/display-names.d.ts +19 -0
  25. package/dist/domain/display-names.js +59 -0
  26. package/dist/domain/person-kinds.d.ts +9 -0
  27. package/dist/domain/person-kinds.js +67 -0
  28. package/dist/entities/index.d.ts +2 -1
  29. package/dist/entities/list-results.d.ts +2 -0
  30. package/dist/entities/list-results.js +2 -0
  31. package/dist/entities/template.d.ts +1 -1
  32. package/dist/entities/template.js +1 -1
  33. package/dist/errors/reasons.js +1 -0
  34. package/dist/index.d.ts +1 -0
  35. package/dist/index.js +1 -0
  36. package/dist/mcp/surface.js +23 -2
  37. package/dist/search/lucene/resolved.d.ts +1 -0
  38. package/dist/search/lucene/types.d.ts +8 -0
  39. package/dist/search/lucene/types.js +7 -0
  40. package/dist/services/index.d.ts +1 -1
  41. package/dist/services/index.js +1 -1
  42. package/dist/services/messages-combined.js +3 -2
  43. package/dist/services/messages-discovery.js +3 -2
  44. package/dist/services/messages-search.js +1 -0
  45. package/dist/services/messages.d.ts +2 -0
  46. package/dist/services/people.js +1 -1
  47. package/dist/services/search-harder.d.ts +6 -1
  48. package/dist/services/search-harder.js +9 -2
  49. package/dist/store/identity-links.d.ts +3 -3
  50. package/dist/store/identity-links.js +3 -3
  51. package/dist/store/index.d.ts +3 -0
  52. package/dist/store/index.js +3 -0
  53. package/dist/store/people.d.ts +21 -2
  54. package/dist/store/people.js +35 -15
  55. package/dist/store/sqlite/lucene.js +12 -11
  56. package/dist/store/sqlite/manifest.js +1 -0
  57. package/dist/store/sqlite/migrations.generated.js +7 -0
  58. package/dist/store/sqlite/name-traces.d.ts +17 -0
  59. package/dist/store/sqlite/name-traces.js +112 -0
  60. package/dist/store/sqlite/notes.js +6 -3
  61. package/dist/store/sqlite/people-list.d.ts +59 -0
  62. package/dist/store/sqlite/people-list.js +275 -0
  63. package/dist/store/sqlite/person-match-scan.js +33 -0
  64. package/dist/store/sqlite/person-ties.d.ts +14 -0
  65. package/dist/store/sqlite/person-ties.js +66 -0
  66. package/dist/store/sqlite/schema.d.ts +16 -0
  67. package/dist/store/sqlite/schema.js +3 -0
  68. package/package.json +3 -3
  69. package/parity.json +29 -0
package/CHANGELOG.md CHANGED
@@ -5,6 +5,114 @@ 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.624.0 — 09.11.2026
9
+
10
+ ### Added
11
+
12
+ - `schedule agent|command --at` repeats: `--at 08:30 --at 18:00` runs twice a day, `--at 'mon,fri 09:00'` (or one
13
+ `--at` per weekday) on several days, all on one timer: one `OnCalendar=` per time under systemd, an array of
14
+ `StartCalendarInterval` under launchd, one trigger per time in Task Scheduler. `schedule list` says
15
+ `daily at 08:30, 18:00` or `weekly on Mon, Fri at 09:00`. One `--at` is saved and listed as before.
16
+ - `schedule pause <name>` takes a schedule off its timer and keeps it; `schedule run` still runs it, `schedule resume`
17
+ puts it back. `schedule list` marks it `paused: true`.
18
+ - `schedule run <name> --no-notify` keeps the result here: no route and no desktop notice. `--deliver-to <route>`
19
+ (repeatable) sends it along only those, which must be the schedule's own, whatever its `--notify-on` says.
20
+ - `templates show|edit|preview|reset report/<schedule>`: an agent schedule's own digest templates. A run of that
21
+ schedule renders with them, else with the owner's `report/morning-digest`, else with the shipped ones; `templates
22
+ show` and `list` call that middle case `source: "inherited"`. A schedule named after another message's key
23
+ (`weekly-gaps`) has no key of its own, and a removed schedule's templates can still be shown and reset.
24
+ - For a tool that keeps its own digests (memo): `agentSchedule`, `writeSchedule`, `pauseSchedule`, `removeSchedule`
25
+ and `runScheduleNow` build, save, pause, remove and run an agent schedule as the `schedule` commands do (the routes
26
+ and the day's cost cap checked the same way); `slotsOfAt` reads one `--at`; `parseRoute` and `routeText` read a
27
+ route; `slotsOf`, `calendarOf`, `runsBetween`, `previousRun` and `nextRun` read a calendar schedule's times.
28
+ - **`harderRanking(result)` gives the `--harder` outcome as cli-base 0.94.0's `meta.ranking`.** A CLI that offers
29
+ `search all --harder` puts it into its answer's `meta`, so a program such as WireCat Desktop reads whether the
30
+ model's order was used, why not (`reason_id`), which provider, model and endpoint, how many hits were sent, the cost
31
+ and, new in the result, the tokens (`usage`) instead of an English note. cli-base goes to 0.94.0.
32
+
33
+ ### Changed — may break callers
34
+
35
+ - `template.source` gains `inherited`. A schedule's `When` gains `{ calendar: Slot[] }` for more than one time; code that switches over every `When` needs
36
+ the new case, or `slotsOf` for any calendar shape. A host's `reportTemplates` now gets the schedule's name as its
37
+ second argument.
38
+ - **The MCP `<app>_read` and `<app>_write` tools list a short answer schema: 3,323 characters for the three tools in
39
+ place of 17,278.** It names only what an agent acts on: `items` or `item`, `page.has_more`, `next`, `missing`, and
40
+ `meta` as an open object that points at `<app>_tools_search`, whose match still gives each command's full answer.
41
+ `_write` lists only `item`, `next` and `meta`, all a write answers with. The server still checks every answer
42
+ against the full cli-base envelope, so nothing an answer carries changes. Every client paid the full schema twice
43
+ on each connect, and cli-base 0.94.0's `meta.ranking` added 2,800 characters more. Watch for: a
44
+ client that built types from the listed `outputSchema` now gets open objects; it reads the full answer from
45
+ `<app>_tools_search`. An agent eval found no loss: 39 of 42 tasks with either listing, on half the input tokens
46
+ ([cli-testing](https://github.com/WireCatLabs/cli-testing/tree/main/performance/agents/mcp-short-listing)).
47
+ - **`store.people.list` lists one kind of person at a time**, `person` by default, instead of hiding everyone with no
48
+ tie. `kind` is `person`, `organization`, `automated`, `unsorted` or `all`; the `all` option and `hidden` are gone,
49
+ and `counts` gives how many each kind holds. The first rule that holds decides the kind, and `kindSignals` names
50
+ it: the owner, people added by hand and task assignees are a `person`; a bot, a no-reply address, a sender most of
51
+ whose mail is in the bulk box, a sender memo scored `bulk_never_replied`, or a name such as «Notifications» or
52
+ «Рассылка» is `automated`; an identity an organization owns, a shared role address (`info@`) or a legal form or
53
+ company word in the name (ООО, LLC, Airlines, Hotel, Team…) is an `organization`; a named person with a tie is a
54
+ `person`; everyone else, with no tie or nothing to show as a name, is `unsorted`.
55
+ - `sort` takes `interactions` (the default: most messages and mail from them first), `recent`, `name` or `tasks`.
56
+ - Each listed person has `kind`, `kindSignals`, `contact` (the phone, else the email, else `@username`),
57
+ `messagesFrom` and `lastContact`. On a synthetic store of 51,000 people and 1.5 million messages a list takes about
58
+ 0.5–0.6 s on a loaded machine and 1.9 s sorted by `recent`; a name search reads only the people it found
59
+ ([cli-testing `performance/people/kinds`](https://github.com/WireCatLabs/cli-testing/tree/main/performance/people/kinds)).
60
+ - An unknown `kind` or `sort` is refused. A sender counts as bulk mail from 3 letters on; a role address makes an
61
+ `organization` only when every address of the person is one.
62
+ - `displayName` reads a messenger's placeholder for a missing name (`null`, «Без имени», `Deleted Account`) as no
63
+ name, so the username, phone or email shows instead; `nameKey` gives such a name no key, so two deleted
64
+ accounts are never proposed as one person.
65
+
66
+ ### Fixed
67
+
68
+ - **`doctor --online` asks npm through `hostFetch`**, which reaches only `registry.npmjs.org`. cli-base 0.94.0's
69
+ `raw-network` lint reported the global `fetch` it fell back to. The model gateway and OpenAI transcription keep the
70
+ global `fetch` in the lint baseline: they call an endpoint the owner configures (OpenRouter, a local server), so no
71
+ host list can be declared in advance.
72
+
73
+ ## 0.623.0 — 09.11.2026
74
+
75
+ ### Added
76
+
77
+ - `store.people.list({ query, all, sort, limit, offset })`: people a page at a time, with `total` and `hidden`, each
78
+ with a cleaned `displayName` (no wrapping quotes or spaces; a name with no letter or digit shows the username, phone
79
+ or email), the first username, phone and email, and `ties`. By default it lists only people with a tie to the
80
+ owner: a one-to-one chat, a group of at most 10 (`SMALL_GROUP_MEMBERS`; a group of unknown size counts as large),
81
+ mail the owner wrote to them, a meeting or calendar entry, a CRM, or the address book. The owner, people added by
82
+ hand and anyone assigned a task are always listed; `all` adds the rest. Ties are read on every call; on a synthetic
83
+ store of 51,000 identities a first page takes about 100 ms
84
+ ([cli-testing `performance/people/ties`](https://github.com/WireCatLabs/cli-testing/tree/main/performance/people/ties)).
85
+ - `store.people.similar(name, { limit })`: people whose name has a word starting with each typed word, in any order,
86
+ the same name first (`sameName`), for a form that adds a person.
87
+ - `store.people.saveAddressBook`: `contacts sync` now marks who is in the account's address book, and unmarks who left
88
+ it (`account_identities.address_book`, store version 61). Sync contacts once after upgrading: until then nobody has
89
+ the address-book tie.
90
+ - The people matcher proposes two people with one name (case, quotes, punctuation and word order set aside) who share
91
+ a phone, an address, a chat or a company's mail domain, as an `identity_link` with signal `name`. It never joins
92
+ them; a free mailbox's domain (gmail.com) or a role address (`info@`) is no trace, and a name more than six people
93
+ have is skipped.
94
+ - `store.people.ties(refs)`: why each person is shown, as the list gives it.
95
+ - `displayName` and `nameKey` from the package root.
96
+ - `schedule … --at 'mon 09:00'`: a weekday before the time makes a weekly run (systemd
97
+ `OnCalendar=Mon *-*-* 09:00:00`, launchd `Weekday`, Task Scheduler's weekly trigger). With `--every` it is refused.
98
+ - **`search messages --timeout 30s` may search for up to about 29 seconds.** A search stopped at 2 seconds whatever
99
+ time its caller gave the run, so a valid query over a large store failed in WireCat Desktop. With an explicit
100
+ `--timeout` (or `<PREFIX>_TIMEOUT`) the search uses that time less a second to answer; the error's `limit_ms` names
101
+ the limit that applied. Without one it stays 2 seconds, for agents and MCP too.
102
+
103
+ ### Changed — may break callers
104
+
105
+ - `IDENTITY_LINK_SIGNALS` gains `name`, and a schedule's `When` gains `{ weekly, on }`: code that switches over every
106
+ signal or every `When` needs the new case. `AccountPeople` and `PeopleStore` gain `saveAddressBook`, `list`,
107
+ `similar` and `ties`, so a hand-written fake of either needs them.
108
+
109
+ ### Fixed
110
+
111
+ - **A file's link that a program guessed waits for review again.** Since 0.621.0 every unconfirmed relationship a
112
+ file wrote became reported by the file's account, a guess (`provenance: "scan"`) included. Only a link whose
113
+ provenance names the file's own source, such as Drive's owner and last editor (`google-drive:files.get`), is
114
+ reported now.
115
+
8
116
  ## 0.622.0 — 09.11.2026
9
117
 
10
118
  ### Added
@@ -17,5 +17,5 @@ export declare const backfillSchedule: (app: AppIdentity, system: ServerSystem,
17
17
  killAfterMs?: number;
18
18
  agentRuns?: readonly AgentCli[];
19
19
  ownerLanguage?: (env: NodeJS.ProcessEnv) => Promise<string>;
20
- reportTemplates?: (env: NodeJS.ProcessEnv) => StoredTemplates;
20
+ reportTemplates?: (env: NodeJS.ProcessEnv, schedule: string) => StoredTemplates;
21
21
  }) => Promise<LastRun>;
@@ -31,7 +31,7 @@ export const backfillSchedule = async (app, system, env, file, { at, input, now
31
31
  now: at.getTime(),
32
32
  links: sharedLinks(runEnv),
33
33
  env: runEnv,
34
- ...(reportTemplates ? { templates: reportTemplates(runEnv) } : {}),
34
+ ...(reportTemplates ? { templates: reportTemplates(runEnv, schedule.name) } : {}),
35
35
  });
36
36
  if (!prepared)
37
37
  return last;
@@ -4,6 +4,8 @@ export type BudgetStop = "requests" | "deadline" | "cancelled";
4
4
  export interface Deadline {
5
5
  endsAt: number;
6
6
  ms: number;
7
+ /** A person or a script set it (`--timeout`, `<PREFIX>_TIMEOUT`), not the command's default. */
8
+ explicit?: true;
7
9
  }
8
10
  /**
9
11
  * A sync asks it before each request to the source, so the run stops on its own, saves where it is, and says
@@ -28,6 +28,23 @@ export declare const templateKeyOf: (key: string) => {
28
28
  readonly kind: "schedule-failed";
29
29
  readonly about: "the message sent when a scheduled run fails";
30
30
  } | undefined;
31
+ /** The key of one schedule's own digest templates. */
32
+ export declare const scheduleReportKey: (schedule: string) => string;
33
+ /**
34
+ * A key of `TEMPLATE_KEYS`, or `report/<schedule>` for a schedule the tool has: that schedule's own digest templates,
35
+ * which `schedule` names.
36
+ */
37
+ export declare const reportKeyOf: (key: string, schedules: readonly string[]) => {
38
+ key: string;
39
+ kind: MessageKind;
40
+ about: string;
41
+ schedule?: string;
42
+ } | undefined;
43
+ /**
44
+ * Where a digest's template comes from, first stored one wins: the schedule's own, then the owner's morning-digest
45
+ * template (a digest schedule made before names existed may be called anything), then the shipped one.
46
+ */
47
+ export declare const reportKeysOf: (kind: MessageKind, schedule?: string) => string[];
31
48
  export declare const keyOfKind: (kind: MessageKind) => TemplateKey;
32
49
  /** The languages cli-core ships a template in for `kind`: a stored template in another one would never be used. */
33
50
  export declare const shippedLanguages: (kind: MessageKind) => string[];
@@ -37,7 +54,7 @@ export declare const shippedLanguages: (kind: MessageKind) => string[];
37
54
  */
38
55
  export declare const sampleView: (kind: MessageKind, language: string, now: number) => MessageView;
39
56
  /** The newest `<run>.report.json` of `kind` the tool's schedules wrote, or undefined; only the digest keeps one. */
40
- export declare const lastReport: (state: string, kind: MessageKind) => {
57
+ export declare const lastReport: (state: string, kind: MessageKind, schedule?: string) => {
41
58
  path: string;
42
59
  document: string;
43
60
  } | undefined;
@@ -51,16 +68,17 @@ export interface TemplateCheck {
51
68
  * Whether `body` may be saved for one channel: it is rendered against the synthetic sample and against the last real
52
69
  * report, when the tool has one, with the platform rules that run at send time. Any problem refuses the save.
53
70
  */
54
- export declare const checkTemplateSave: ({ kind, channel, language, body, state, now, }: {
71
+ export declare const checkTemplateSave: ({ kind, channel, language, body, state, now, schedule, }: {
55
72
  kind: MessageKind;
56
73
  channel: ReportChannel;
57
74
  language: string;
58
75
  body: string;
59
76
  state: string;
60
77
  now: number;
78
+ schedule?: string;
61
79
  }) => Promise<TemplateCheck[]>;
62
80
  /** The view a preview renders: the last real report when there is one, else the sample. */
63
- export declare const previewView: (state: string, kind: MessageKind, language: string, now: number) => {
81
+ export declare const previewView: (state: string, kind: MessageKind, language: string, now: number, schedule?: string) => {
64
82
  against: string;
65
83
  view: MessageView;
66
84
  };
@@ -14,6 +14,33 @@ export const TEMPLATE_KEYS = [
14
14
  { key: "notice/schedule-failed", kind: "schedule-failed", about: "the message sent when a scheduled run fails" },
15
15
  ];
16
16
  export const templateKeyOf = (key) => TEMPLATE_KEYS.find((one) => one.key === key);
17
+ const DIGEST_KEY = "report/morning-digest";
18
+ /** The key of one schedule's own digest templates. */
19
+ export const scheduleReportKey = (schedule) => `report/${schedule}`;
20
+ /**
21
+ * A key of `TEMPLATE_KEYS`, or `report/<schedule>` for a schedule the tool has: that schedule's own digest templates,
22
+ * which `schedule` names.
23
+ */
24
+ export const reportKeyOf = (key, schedules) => {
25
+ const known = templateKeyOf(key);
26
+ if (known)
27
+ return known;
28
+ const schedule = key.startsWith("report/") ? key.slice("report/".length) : "";
29
+ return schedule && schedules.includes(schedule)
30
+ ? { key, kind: "morning-digest", about: `the ${schedule} digest`, schedule }
31
+ : undefined;
32
+ };
33
+ /**
34
+ * Where a digest's template comes from, first stored one wins: the schedule's own, then the owner's morning-digest
35
+ * template (a digest schedule made before names existed may be called anything), then the shipped one.
36
+ */
37
+ export const reportKeysOf = (kind, schedule) => {
38
+ const key = keyOfKind(kind);
39
+ // A schedule named after another message's key (weekly-gaps) has no key of its own.
40
+ return kind === "morning-digest" && schedule && !templateKeyOf(scheduleReportKey(schedule))
41
+ ? [scheduleReportKey(schedule), DIGEST_KEY]
42
+ : [key];
43
+ };
17
44
  export const keyOfKind = (kind) => TEMPLATE_KEYS.find((one) => one.kind === kind).key;
18
45
  const TEMPLATES = fileURLToPath(new URL("./templates/", import.meta.url));
19
46
  /** The languages cli-core ships a template in for `kind`: a stored template in another one would never be used. */
@@ -45,11 +72,12 @@ export const sampleView = (kind, language, now) => {
45
72
  return view;
46
73
  };
47
74
  /** The newest `<run>.report.json` of `kind` the tool's schedules wrote, or undefined; only the digest keeps one. */
48
- export const lastReport = (state, kind) => {
75
+ export const lastReport = (state, kind, schedule) => {
49
76
  const folder = schedulesDir(state);
50
77
  if (kind !== "morning-digest" || !existsSync(folder))
51
78
  return undefined;
52
- const files = readdirSync(folder).flatMap((name) => {
79
+ const names = schedule === undefined ? readdirSync(folder) : [schedule];
80
+ const files = names.flatMap((name) => {
53
81
  const runs = join(folder, name, "runs");
54
82
  return existsSync(runs)
55
83
  ? readdirSync(runs)
@@ -69,8 +97,8 @@ export const lastReport = (state, kind) => {
69
97
  * Whether `body` may be saved for one channel: it is rendered against the synthetic sample and against the last real
70
98
  * report, when the tool has one, with the platform rules that run at send time. Any problem refuses the save.
71
99
  */
72
- export const checkTemplateSave = async ({ kind, channel, language, body, state, now, }) => {
73
- const last = lastReport(state, kind);
100
+ export const checkTemplateSave = async ({ kind, channel, language, body, state, now, schedule, }) => {
101
+ const last = lastReport(state, kind, schedule);
74
102
  const views = [
75
103
  ["sample", sampleView(kind, language, now)],
76
104
  ...(last ? [[last.path, viewOf(last.document, language, now)]] : []),
@@ -78,8 +106,8 @@ export const checkTemplateSave = async ({ kind, channel, language, body, state,
78
106
  return Promise.all(views.flatMap(([against, view]) => view ? [checkTemplate(view, channel, body).then((check) => ({ against, ...check }))] : []));
79
107
  };
80
108
  /** The view a preview renders: the last real report when there is one, else the sample. */
81
- export const previewView = (state, kind, language, now) => {
82
- const last = lastReport(state, kind);
109
+ export const previewView = (state, kind, language, now, schedule) => {
110
+ const last = lastReport(state, kind, schedule);
83
111
  const view = last && viewOf(last.document, language, now);
84
112
  return view ? { against: last.path, view } : { against: "sample", view: sampleView(kind, language, now) };
85
113
  };
@@ -2,14 +2,10 @@ import { type AppIdentity } from "../ports/app.js";
2
2
  import { type Delivery } from "./deliver.js";
3
3
  import { type ReportRun, type StoredTemplates } from "./report/render.js";
4
4
  import type { ServerSystem } from "./system.js";
5
- /** Minutes between runs, a daily local time, or one local moment. */
6
- export type When = {
7
- every: number;
8
- } | {
9
- daily: string;
10
- } | {
11
- once: string;
12
- };
5
+ import type { Timer } from "./timers.js";
6
+ import type { When } from "./when.js";
7
+ export { launchdTimer, systemdTimer, type Timer, timerFor, windowsTimer } from "./timers.js";
8
+ export { type CalendarWhen, calendarOf, describeWhen, isCalendar, nextRun, previousRun, runsBetween, type Slot, slotsOf, WEEKDAYS, type Weekday, type When, } from "./when.js";
13
9
  export interface Schedule {
14
10
  name: string;
15
11
  kind: "command" | "agent";
@@ -30,6 +26,8 @@ export interface Schedule {
30
26
  notify?: Notify;
31
27
  /** `--deliver-to`'s routes (`telegram-bot:<profile>/<chat>`, `email:<profile>/<address>`), answered as `deliver_to`. */
32
28
  to?: string[];
29
+ /** Kept with no timer: `schedule run` still runs it, and `schedule resume` puts the timer back. */
30
+ paused?: true;
33
31
  }
34
32
  export declare const NOTIFY_WHEN: readonly ["always", "failures", "never"];
35
33
  export type Notify = (typeof NOTIFY_WHEN)[number];
@@ -144,23 +142,6 @@ export declare const scheduledRuns: (state: string) => {
144
142
  last: LastRun | undefined;
145
143
  }[];
146
144
  export declare const listSchedules: (state: string, filter?: Partial<Pick<Schedule, "name" | "kind">>) => Schedule[];
147
- export declare const describeWhen: (when: When) => string;
148
- /** How one operating system starts `argv` at the schedule's times. Every timer runs the same thing: `<cli> schedule exec <file>`. */
149
- export interface Timer {
150
- install: (schedule: Schedule, argv: string[]) => Promise<void>;
151
- remove: (name: string) => Promise<void>;
152
- /** Where the timer lives, for the owner to look at. */
153
- where: (name: string) => string;
154
- }
155
- export declare const systemdTimer: (app: AppIdentity, system: ServerSystem, env: NodeJS.ProcessEnv, home: string) => Timer;
156
- export declare const launchdTimer: (app: AppIdentity, system: ServerSystem, env: NodeJS.ProcessEnv, home: string) => Timer;
157
- /**
158
- * Task Scheduler through PowerShell's ScheduledTasks module. The values travel in variables, never in
159
- * the script, so nothing needs quoting for PowerShell; Windows has no per-task environment, which is why
160
- * the runner reads its variables from the schedule file.
161
- */
162
- export declare const windowsTimer: (app: AppIdentity, system: ServerSystem, env: NodeJS.ProcessEnv) => Timer;
163
- export declare const timerFor: (app: AppIdentity, system: ServerSystem, env: NodeJS.ProcessEnv) => Timer;
164
145
  /** The shared `links` settings; a config file that cannot be read keeps the default rather than stop a digest. */
165
146
  export declare const sharedLinks: (env: NodeJS.ProcessEnv) => import("../domain/links.js").LinkConfig;
166
147
  /** A desktop notification; a machine without one loses only the notice, never the run. */
@@ -183,7 +164,7 @@ export declare const CREDENTIALS_UNREACHABLE = "credentials.unreachable";
183
164
  * keyring, so a run that fails for that reason is tried again, a minute then up to 15 minutes apart, for up to
184
165
  * 12 hours. A schedule that repeats every few minutes is left to its next tick; a run by hand fails at once.
185
166
  */
186
- export declare const runSchedule: (app: AppIdentity, system: ServerSystem, env: NodeJS.ProcessEnv, file: string, { now, timer, signal, killAfterMs, untilUnlocked, wait, agentRuns, agentInput, ownerLanguage, reportTemplates, skipRepeatedInput, }?: {
167
+ export declare const runSchedule: (app: AppIdentity, system: ServerSystem, env: NodeJS.ProcessEnv, file: string, { now, timer, signal, killAfterMs, untilUnlocked, wait, agentRuns, agentInput, ownerLanguage, reportTemplates, skipRepeatedInput, routes: chosen, }?: {
187
168
  now?: () => Date;
188
169
  timer?: Timer;
189
170
  signal?: AbortSignal;
@@ -196,12 +177,14 @@ export declare const runSchedule: (app: AppIdentity, system: ServerSystem, env:
196
177
  /** The owner's first language, read only when the answer is a report; Russian when the host cannot say. */
197
178
  ownerLanguage?: (env: NodeJS.ProcessEnv) => Promise<string>;
198
179
  /** The owner's stored report templates; the shipped ones when the host gives none. */
199
- reportTemplates?: (env: NodeJS.ProcessEnv) => StoredTemplates;
180
+ reportTemplates?: (env: NodeJS.ProcessEnv, schedule: string) => StoredTemplates;
200
181
  /**
201
182
  * Leave out a mail-gated agent whose input is the one its last run ended well on. The mark did not move, so the
202
183
  * run would only meet the same input again and pay for it; new mail changes the input.
203
184
  */
204
185
  skipRepeatedInput?: boolean;
186
+ /** Where this run goes instead of the schedule's own routes; `[]` keeps it here. */
187
+ routes?: readonly string[];
205
188
  }) => Promise<LastRun>;
206
189
  /** One run of the schedule's command or agent: its output in `runs/`, its result in `last.json`. */
207
190
  export declare const attemptSchedule: (app: AppIdentity, system: ServerSystem, env: NodeJS.ProcessEnv, schedule: Schedule, folder: string, { now, signal, killAfterMs, agentRuns, agentInput, skipRepeatedInput, at, }: {
@@ -12,6 +12,8 @@ import { readSharedSection, sharedConfigPath } from "../store/shared-config.js";
12
12
  import { deliver } from "./deliver.js";
13
13
  import { causeOf, gapsView, noticeView, weeklyGapsOf } from "./report/messages.js";
14
14
  import { prepareMessage, prepareReport, } from "./report/render.js";
15
+ export { launchdTimer, systemdTimer, timerFor, windowsTimer } from "./timers.js";
16
+ export { calendarOf, describeWhen, isCalendar, nextRun, previousRun, runsBetween, slotsOf, WEEKDAYS, } from "./when.js";
15
17
  export const NOTIFY_WHEN = ["always", "failures", "never"];
16
18
  /** A repeating agent would otherwise notify on every tick; any other schedule runs rarely enough to say each result. */
17
19
  export const notifyOf = (schedule) => schedule.notify ?? (schedule.kind === "agent" && "every" in schedule.when ? "failures" : "always");
@@ -186,168 +188,6 @@ export const listSchedules = (state, filter = {}) => existsSync(schedulesDir(sta
186
188
  (filter.kind === undefined || schedule.kind === filter.kind))
187
189
  .sort((a, b) => a.name.localeCompare(b.name))
188
190
  : [];
189
- export const describeWhen = (when) => "every" in when
190
- ? `every ${when.every % 1440 === 0 ? `${when.every / 1440}d` : when.every % 60 === 0 ? `${when.every / 60}h` : `${when.every}m`}`
191
- : "daily" in when
192
- ? `daily at ${when.daily}`
193
- : `once at ${when.once}`;
194
- /** A local wall-clock time, as both systemd's `OnCalendar=` and PowerShell's parser take it. */
195
- const localStamp = (iso) => {
196
- const at = new Date(iso);
197
- const two = (n) => String(n).padStart(2, "0");
198
- return `${at.getFullYear()}-${two(at.getMonth() + 1)}-${two(at.getDate())} ${two(at.getHours())}:${two(at.getMinutes())}:${two(at.getSeconds())}`;
199
- };
200
- const systemdQuote = (value) => `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("%", "%%").replaceAll("$", "$$$$")}"`;
201
- const xml = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
202
- const checked = async (system, env, argv, allowFailure = false) => {
203
- const ran = await system.run(argv, env);
204
- if (ran.code !== 0 && !allowFailure) {
205
- throw new CliError("configuration_error", `${argv[0]} failed: ${(ran.stderr || ran.stdout).trim()}`);
206
- }
207
- return ran;
208
- };
209
- export const systemdTimer = (app, system, env, home) => {
210
- const folder = join(env.XDG_CONFIG_HOME ?? join(home, ".config"), "systemd", "user");
211
- const unit = (name) => `${app.command}-schedule-${name}`;
212
- return {
213
- where: (name) => join(folder, `${unit(name)}.timer`),
214
- install: async (schedule, argv) => {
215
- const { when } = schedule;
216
- writeSecurely(join(folder, `${unit(schedule.name)}.service`), [
217
- "[Unit]",
218
- `Description=${app.command} schedule ${schedule.name}`,
219
- "",
220
- "[Service]",
221
- "Type=oneshot",
222
- `ExecStart=${argv.map(systemdQuote).join(" ")}`,
223
- "",
224
- ].join("\n"), 0o644);
225
- writeSecurely(join(folder, `${unit(schedule.name)}.timer`), [
226
- "[Unit]",
227
- `Description=${app.command} schedule ${schedule.name} — ${describeWhen(when)}`,
228
- "",
229
- "[Timer]",
230
- ...("every" in when
231
- ? // From when a run ends: counted from its start, a run longer than the interval left no next run.
232
- [`OnActiveSec=${when.every}min`, `OnUnitInactiveSec=${when.every}min`]
233
- : // Persistent: a run missed while the machine slept happens when it wakes.
234
- [`OnCalendar=${"daily" in when ? `*-*-* ${when.daily}:00` : localStamp(when.once)}`, "Persistent=true"]),
235
- "",
236
- "[Install]",
237
- "WantedBy=timers.target",
238
- "",
239
- ].join("\n"), 0o644);
240
- await checked(system, env, ["systemctl", "--user", "daemon-reload"]);
241
- await checked(system, env, ["systemctl", "--user", "enable", "--now", `${unit(schedule.name)}.timer`]);
242
- },
243
- remove: async (name) => {
244
- await checked(system, env, ["systemctl", "--user", "disable", "--now", `${unit(name)}.timer`], true);
245
- rmSync(join(folder, `${unit(name)}.timer`), { force: true });
246
- rmSync(join(folder, `${unit(name)}.service`), { force: true });
247
- await checked(system, env, ["systemctl", "--user", "daemon-reload"]);
248
- },
249
- };
250
- };
251
- export const launchdTimer = (app, system, env, home) => {
252
- const folder = join(home, "Library", "LaunchAgents");
253
- const label = (name) => `${app.appName}.schedule.${name}`;
254
- const plist = (name) => join(folder, `${label(name)}.plist`);
255
- const domain = `gui/${system.uid}`;
256
- const calendar = (when) => {
257
- if ("every" in when)
258
- return [` <key>StartInterval</key><integer>${when.every * 60}</integer>`];
259
- const [hour, minute] = ("daily" in when ? when.daily : localStamp(when.once).slice(11, 16)).split(":").map(Number);
260
- const once = "once" in when ? new Date(when.once) : undefined;
261
- return [
262
- " <key>StartCalendarInterval</key>",
263
- " <dict>",
264
- // launchd has no year: a one-off is a yearly date, and the run removes it.
265
- ...(once
266
- ? [
267
- ` <key>Month</key><integer>${once.getMonth() + 1}</integer>`,
268
- ` <key>Day</key><integer>${once.getDate()}</integer>`,
269
- ]
270
- : []),
271
- ` <key>Hour</key><integer>${hour}</integer>`,
272
- ` <key>Minute</key><integer>${minute}</integer>`,
273
- " </dict>",
274
- ];
275
- };
276
- return {
277
- where: plist,
278
- install: async (schedule, argv) => {
279
- await checked(system, env, ["launchctl", "bootout", `${domain}/${label(schedule.name)}`], true);
280
- writeSecurely(plist(schedule.name), [
281
- '<?xml version="1.0" encoding="UTF-8"?>',
282
- '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
283
- '<plist version="1.0">',
284
- "<dict>",
285
- ` <key>Label</key><string>${xml(label(schedule.name))}</string>`,
286
- " <key>ProgramArguments</key>",
287
- " <array>",
288
- ...argv.map((word) => ` <string>${xml(word)}</string>`),
289
- " </array>",
290
- ...calendar(schedule.when),
291
- "</dict>",
292
- "</plist>",
293
- "",
294
- ].join("\n"), 0o644);
295
- await checked(system, env, ["launchctl", "bootstrap", domain, plist(schedule.name)]);
296
- },
297
- remove: async (name) => {
298
- await checked(system, env, ["launchctl", "bootout", `${domain}/${label(name)}`], true);
299
- rmSync(plist(name), { force: true });
300
- },
301
- };
302
- };
303
- /**
304
- * Task Scheduler through PowerShell's ScheduledTasks module. The values travel in variables, never in
305
- * the script, so nothing needs quoting for PowerShell; Windows has no per-task environment, which is why
306
- * the runner reads its variables from the schedule file.
307
- */
308
- export const windowsTimer = (app, system, env) => {
309
- const path = `\\${app.appName}\\`;
310
- const powershell = (script, values, allowFailure = false) => checked(system, { ...env, ...values }, ["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script], allowFailure);
311
- return {
312
- where: (name) => `Task Scheduler ${path}${name}`,
313
- install: async (schedule, [exe = "", ...args]) => {
314
- const { when } = schedule;
315
- await powershell([
316
- "$ErrorActionPreference = 'Stop'",
317
- "$action = New-ScheduledTaskAction -Execute $env:WIRECAT_EXE -Argument $env:WIRECAT_ARGS",
318
- "$trigger = switch ($env:WIRECAT_KIND) {",
319
- " 'every' { New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes ([int]$env:WIRECAT_MINUTES)) }",
320
- " 'daily' { New-ScheduledTaskTrigger -Daily -At $env:WIRECAT_AT }",
321
- " 'once' { New-ScheduledTaskTrigger -Once -At ([datetime]::ParseExact($env:WIRECAT_AT, 'yyyy-MM-dd HH:mm:ss', $null)) }",
322
- "}",
323
- "$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -MultipleInstances IgnoreNew",
324
- "Register-ScheduledTask -TaskName $env:WIRECAT_NAME -TaskPath $env:WIRECAT_PATH -Action $action -Trigger $trigger -Settings $settings -Force | Out-Null",
325
- ].join("\n"), {
326
- WIRECAT_EXE: exe,
327
- WIRECAT_ARGS: args.map((word) => `"${word.replaceAll('"', '\\"')}"`).join(" "),
328
- WIRECAT_KIND: "every" in when ? "every" : "daily" in when ? "daily" : "once",
329
- WIRECAT_MINUTES: "every" in when ? String(when.every) : "",
330
- WIRECAT_AT: "daily" in when ? when.daily : "once" in when ? localStamp(when.once) : "",
331
- WIRECAT_NAME: schedule.name,
332
- WIRECAT_PATH: path,
333
- });
334
- },
335
- remove: async (name) => {
336
- await powershell("Unregister-ScheduledTask -TaskName $env:WIRECAT_NAME -TaskPath $env:WIRECAT_PATH -Confirm:$false", { WIRECAT_NAME: name, WIRECAT_PATH: path }, true);
337
- },
338
- };
339
- };
340
- export const timerFor = (app, system, env) => {
341
- if (system.platform === "win32")
342
- return windowsTimer(app, system, env);
343
- if (!env.HOME)
344
- throw new CliError("configuration_error", "HOME is not set, so there is nowhere to put the timer");
345
- if (system.platform === "linux")
346
- return systemdTimer(app, system, env, env.HOME);
347
- if (system.platform === "darwin")
348
- return launchdTimer(app, system, env, env.HOME);
349
- throw new CliError("validation_error", `${app.command} schedule knows Linux, macOS and Windows, not ${system.platform}`);
350
- };
351
191
  /** The shared `links` settings; a config file that cannot be read keeps the default rather than stop a digest. */
352
192
  export const sharedLinks = (env) => {
353
193
  try {
@@ -463,7 +303,7 @@ const pause = (ms, signal) => new Promise((resolve) => {
463
303
  * keyring, so a run that fails for that reason is tried again, a minute then up to 15 minutes apart, for up to
464
304
  * 12 hours. A schedule that repeats every few minutes is left to its next tick; a run by hand fails at once.
465
305
  */
466
- export const runSchedule = async (app, system, env, file, { now = () => new Date(), timer, signal, killAfterMs = KILL_AFTER_MS, untilUnlocked = false, wait = pause, agentRuns = [], agentInput, ownerLanguage = async () => "ru", reportTemplates, skipRepeatedInput = false, } = {}) => {
306
+ export const runSchedule = async (app, system, env, file, { now = () => new Date(), timer, signal, killAfterMs = KILL_AFTER_MS, untilUnlocked = false, wait = pause, agentRuns = [], agentInput, ownerLanguage = async () => "ru", reportTemplates, skipRepeatedInput = false, routes: chosen, } = {}) => {
467
307
  const schedule = readSchedule(file);
468
308
  const folder = join(file, "..");
469
309
  const runs = join(folder, "runs");
@@ -510,7 +350,7 @@ export const runSchedule = async (app, system, env, file, { now = () => new Date
510
350
  now: now().getTime(),
511
351
  links: sharedLinks(runEnv),
512
352
  env: runEnv,
513
- ...(reportTemplates ? { templates: reportTemplates(runEnv) } : {}),
353
+ ...(reportTemplates ? { templates: reportTemplates(runEnv, schedule.name) } : {}),
514
354
  })
515
355
  : undefined;
516
356
  const latestText = join(folder, "latest.txt");
@@ -530,7 +370,8 @@ export const runSchedule = async (app, system, env, file, { now = () => new Date
530
370
  if (!kept.has(stampOf(file)))
531
371
  rmSync(join(runs, file), { force: true });
532
372
  const title = `${app.command} ${schedule.name}`;
533
- const mode = notifyOf(schedule);
373
+ // Routes the owner named for this run go whatever the schedule's notify says; none named, nobody is told.
374
+ const mode = chosen === undefined ? notifyOf(schedule) : chosen.length ? "always" : "never";
534
375
  if (agent && exitCode === 0) {
535
376
  if (mode === "always" && !announcedByDesktop(join(folder, ".."), schedule.name)) {
536
377
  const first = readFileSync(output, "utf8")
@@ -544,7 +385,7 @@ export const runSchedule = async (app, system, env, file, { now = () => new Date
544
385
  else if (exitCode !== 0 && mode !== "never") {
545
386
  await notify(system, env, title, `failed (exit ${exitCode}) — ${errors}`);
546
387
  }
547
- const routes = schedule.to ?? [];
388
+ const routes = chosen ?? schedule.to ?? [];
548
389
  const locked = readOnlyLockOf(app, runEnv);
549
390
  const sendAlong = async (parcel) => {
550
391
  const deliveries = await deliver(system, runEnv, routes, parcel, {
@@ -561,7 +402,7 @@ export const runSchedule = async (app, system, env, file, { now = () => new Date
561
402
  const messageOptions = async () => ({
562
403
  language: await ownerLanguage(runEnv).catch(() => "ru"),
563
404
  linkOf: (ref) => linkFor(ref, { form: "web", config: sharedLinks(runEnv), env: runEnv }),
564
- ...(reportTemplates ? { templates: reportTemplates(runEnv) } : {}),
405
+ ...(reportTemplates ? { templates: reportTemplates(runEnv, schedule.name) } : {}),
565
406
  });
566
407
  if (routes.length > 0 && (exitCode === 0 ? mode === "always" : mode !== "never")) {
567
408
  const at = shortTime(last.at);
@@ -0,0 +1,19 @@
1
+ import type { AppIdentity } from "../ports/app.js";
2
+ import type { Schedule } from "./schedules.js";
3
+ import type { ServerSystem } from "./system.js";
4
+ /** How one operating system starts `argv` at the schedule's times. Every timer runs the same thing: `<cli> schedule exec <file>`. */
5
+ export interface Timer {
6
+ install: (schedule: Schedule, argv: string[]) => Promise<void>;
7
+ remove: (name: string) => Promise<void>;
8
+ /** Where the timer lives, for the owner to look at. */
9
+ where: (name: string) => string;
10
+ }
11
+ export declare const systemdTimer: (app: AppIdentity, system: ServerSystem, env: NodeJS.ProcessEnv, home: string) => Timer;
12
+ export declare const launchdTimer: (app: AppIdentity, system: ServerSystem, env: NodeJS.ProcessEnv, home: string) => Timer;
13
+ /**
14
+ * Task Scheduler through PowerShell's ScheduledTasks module. The values travel in variables, never in
15
+ * the script, so nothing needs quoting for PowerShell; Windows has no per-task environment, which is why
16
+ * the runner reads its variables from the schedule file.
17
+ */
18
+ export declare const windowsTimer: (app: AppIdentity, system: ServerSystem, env: NodeJS.ProcessEnv) => Timer;
19
+ export declare const timerFor: (app: AppIdentity, system: ServerSystem, env: NodeJS.ProcessEnv) => Timer;