@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
@@ -1,11 +1,14 @@
1
1
  import { Command } from "commander";
2
- import { type AgentCli, type AgentInput, type Schedule } from "../../background/schedules.js";
2
+ import { type AgentCli, type AgentInput, type LastRun, type Notify, type Schedule, type SkipReason, type Slot, type When } from "../../background/schedules.js";
3
+ import { type ServerSystem } from "../../background/system.js";
3
4
  import { type MailWaiting } from "../../mail/marks.js";
4
5
  import { type AppIdentity } from "../../ports/app.js";
5
6
  import { type AnswerOutput } from "../envelope.js";
6
7
  import type { DeclaredSetting } from "../setting-defaults.js";
7
8
  declare const HARNESSES: readonly ["claude", "codex"];
8
- type Harness = (typeof HARNESSES)[number];
9
+ export type Harness = (typeof HARNESSES)[number];
10
+ /** One `--at`: `HH:MM` every day, or weekdays and a time, `mon 09:00` or `mon,fri 09:00`. */
11
+ export declare const slotsOfAt: (at: string) => Slot[];
9
12
  export interface ScheduleHost {
10
13
  app: AppIdentity;
11
14
  context(command: Command, resolving?: {
@@ -54,7 +57,101 @@ export declare const backfillScheduleRun: (command: Command, app: AppIdentity, e
54
57
  at: Date;
55
58
  input?: string;
56
59
  agentRuns?: readonly AgentCli[];
57
- }) => Promise<import("../../background/schedules.js").LastRun>;
60
+ }) => Promise<LastRun>;
61
+ /** Where a schedule is written and for whom: the CLI, the machine, the run's variables and its profile. */
62
+ export interface ScheduleSite {
63
+ app: AppIdentity;
64
+ system: ServerSystem;
65
+ env: NodeJS.ProcessEnv;
66
+ profile: string;
67
+ /** Other CLIs an agent may run besides this one, each under its own read-only lock. */
68
+ agentRuns?: readonly AgentCli[];
69
+ /** The config file's agent-schedule settings. */
70
+ limits?: ScheduleLimits;
71
+ }
72
+ /** The tool's state folder, which holds its schedules. */
73
+ export declare const scheduleState: ({ app, env }: Pick<ScheduleSite, "app" | "env">) => string;
74
+ /** An agent schedule as `schedule agent` makes it; the caller has checked the flags it was given. */
75
+ export interface AgentScheduleSpec {
76
+ name: string;
77
+ harness: Harness;
78
+ prompt: string;
79
+ when: When;
80
+ /** An alias or a model id; "" for the harness's own default; absent for the config file's, else ours. */
81
+ model?: string;
82
+ /** Claude only: a run that costs more is stopped, in US dollars. */
83
+ maxCost?: number;
84
+ maxCostPerDay?: number;
85
+ onNewMail?: string;
86
+ mailWaitMinutes?: number;
87
+ mailBatch?: number;
88
+ notify?: Notify;
89
+ to?: string[];
90
+ paused?: boolean;
91
+ }
92
+ /** The schedule `spec` describes, with the harness's argv built here, never by the caller: its limits live in it. */
93
+ export declare const agentSchedule: (site: ScheduleSite, spec: AgentScheduleSpec) => Schedule;
94
+ /**
95
+ * Writes the schedule's file and puts it on its timer, or takes it off when it is paused. A name another profile's
96
+ * schedule holds is refused.
97
+ */
98
+ export declare const writeSchedule: (site: ScheduleSite, schedule: Schedule) => Promise<{
99
+ file: string;
100
+ timer: string;
101
+ replaced: boolean;
102
+ }>;
103
+ /**
104
+ * Takes a schedule off its timer and keeps its file, or puts it back. It keeps the profile it was made for, as pausing
105
+ * names no new one.
106
+ */
107
+ export declare const pauseSchedule: (site: ScheduleSite, name: string, paused: boolean) => Promise<{
108
+ file: string;
109
+ timer: string;
110
+ replaced: boolean;
111
+ schedule: {
112
+ name: string;
113
+ kind: "command" | "agent";
114
+ argv: string[];
115
+ when: When;
116
+ environment: Record<string, string>;
117
+ createdAt: string;
118
+ onNewMail?: string;
119
+ mailWaitMinutes?: number;
120
+ mailBatch?: number;
121
+ maxCostPerDay?: number;
122
+ notify?: Notify;
123
+ to?: string[];
124
+ } | {
125
+ name: string;
126
+ kind: "command" | "agent";
127
+ argv: string[];
128
+ when: When;
129
+ environment: Record<string, string>;
130
+ createdAt: string;
131
+ onNewMail?: string;
132
+ mailWaitMinutes?: number;
133
+ mailBatch?: number;
134
+ maxCostPerDay?: number;
135
+ notify?: Notify;
136
+ to?: string[];
137
+ paused: true;
138
+ };
139
+ }>;
140
+ /** Takes the schedule off its timer and removes its file; its past runs stay. */
141
+ export declare const removeSchedule: (site: ScheduleSite, name: string) => Promise<void>;
142
+ /**
143
+ * Runs the schedule in `file` now, as `schedule run` does: its report rendered with the owner's language and templates
144
+ * and sent along `routes` (its own when absent, none when empty). A stop of the command stops the agent.
145
+ */
146
+ export declare const runScheduleNow: (command: Command, site: ScheduleSite, file: string, { routes, agentInput }?: {
147
+ routes?: readonly string[];
148
+ agentInput?: AgentInput;
149
+ }) => Promise<LastRun | {
150
+ skipped: {
151
+ why: string;
152
+ reason: SkipReason;
153
+ };
154
+ }>;
58
155
  /**
59
156
  * Runs the CLI's own commands, or an agent, later or on a timer — through systemd (Linux), launchd
60
157
  * (macOS) or Task Scheduler (Windows). Every timer runs `schedule exec <file>`; the schedule file holds
@@ -6,8 +6,8 @@ import { Argument, Command, Option } from "commander";
6
6
  import { backfillSchedule } from "../../background/backfill.js";
7
7
  import { parseRoute, ROUTE_HELP, routeText } from "../../background/deliver.js";
8
8
  import { REPORT_CHANNELS } from "../../background/report/render.js";
9
- import { keyOfKind } from "../../background/report/stored-templates.js";
10
- import { describeWhen, findProgram, lastRun, listSchedules, NOTIFY_WHEN, notifyOf, readSchedule, recordSkip, runSchedule, SCHEDULE_DEFAULTS, SKIP_REASONS, scheduleFile, scheduleName, spentToday, timerFor, } from "../../background/schedules.js";
9
+ import { reportKeysOf } from "../../background/report/stored-templates.js";
10
+ import { calendarOf, describeWhen, findProgram, isCalendar, lastRun, listSchedules, NOTIFY_WHEN, notifyOf, readSchedule, recordSkip, runSchedule, SCHEDULE_DEFAULTS, SKIP_REASONS, scheduleFile, scheduleName, slotsOf, spentToday, timerFor, WEEKDAYS, } from "../../background/schedules.js";
11
11
  import { thisMachine } from "../../background/system.js";
12
12
  import { locationVariables } from "../../background/units.js";
13
13
  import { parseDuration } from "../../domain/duration.js";
@@ -38,9 +38,24 @@ const isModel = (model) => /^([A-Za-z0-9][\w.:/@[\]-]*)?$/.test(model);
38
38
  * through the CLI, and the rest was most of its starting context. Auth, `--permission-mode` and `--allowedTools` hold.
39
39
  */
40
40
  const LEAN_CLAUDE = ["--tools", "Bash", "--strict-mcp-config", "--disable-slash-commands", "--setting-sources", ""];
41
- const whenOf = ({ every, at, atTime }, minimum) => {
42
- if ([every ?? at, atTime].filter(Boolean).length !== 1) {
43
- throw new CliError("validation_error", "say when: --every <30m|2h|1d>, --at HH:MM (daily), or --at-time <30m|2d|ISO time>");
41
+ const CLOCK = /^([01]\d|2[0-3]):[0-5]\d$/;
42
+ /** One `--at`: `HH:MM` every day, or weekdays and a time, `mon 09:00` or `mon,fri 09:00`. */
43
+ export const slotsOfAt = (at) => {
44
+ const [, words, clock = ""] = /^\s*(?:([a-z,]+)\s+)?(\S+)\s*$/i.exec(at) ?? [];
45
+ if (!CLOCK.test(clock))
46
+ throw new CliError("validation_error", `--at takes HH:MM, or a weekday and HH:MM such as 'mon 09:00' or 'mon,fri 09:00'; not "${at}"`);
47
+ if (words === undefined)
48
+ return [{ at: clock }];
49
+ return words.split(",").map((word) => {
50
+ const day = word.toLowerCase().slice(0, 3);
51
+ if (!WEEKDAYS.includes(day))
52
+ throw new CliError("validation_error", `--at takes a weekday, ${WEEKDAYS.join(", ")}; not "${word}"`);
53
+ return { at: clock, on: day };
54
+ });
55
+ };
56
+ const whenOf = ({ every, at = [], atTime }, minimum) => {
57
+ if ([every ?? at[0], atTime].filter(Boolean).length !== 1 || (atTime && at.length > 0)) {
58
+ 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>");
44
59
  }
45
60
  if (atTime) {
46
61
  const time = aheadOf(atTime, "--at-time");
@@ -48,13 +63,16 @@ const whenOf = ({ every, at, atTime }, minimum) => {
48
63
  throw new CliError("validation_error", "--at-time is in the past");
49
64
  return { once: new Date(time).toISOString() };
50
65
  }
51
- if (at) {
52
- if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(at))
53
- throw new CliError("validation_error", `--at takes HH:MM, not "${at}"`);
54
- if (every && parseDuration(every, "--every") !== 86_400_000) {
55
- throw new CliError("validation_error", "--at runs once a day; leave out --every, or use --every 1d");
66
+ if (at.length > 0) {
67
+ const when = calendarOf(at.flatMap(slotsOfAt));
68
+ if (every && ("calendar" in when || "weekly" in when || parseDuration(every, "--every") !== 86_400_000)) {
69
+ throw new CliError("validation_error", "daily" in when
70
+ ? "--at runs once a day; leave out --every, or use --every 1d"
71
+ : "weekly" in when
72
+ ? "a weekday in --at runs once a week; leave out --every"
73
+ : "--at sets the times; leave out --every");
56
74
  }
57
- return { daily: at };
75
+ return when;
58
76
  }
59
77
  const minutes = parseDuration(every ?? "", "--every") / 60_000;
60
78
  if (!Number.isInteger(minutes) || minutes < minimum) {
@@ -86,7 +104,7 @@ const scheduleAnswer = ({ environment, createdAt, to, ...schedule }, extra) => (
86
104
  });
87
105
  const withWhen = (command) => command
88
106
  .option("--every <duration>", "repeat: 30m, 2h, 1d")
89
- .option("--at <HH:MM>", "every day at this local time")
107
+ .option("--at <HH:MM>", `every day at this local time; 'mon 09:00' once a week, 'mon,fri 09:00' on several days (${WEEKDAYS.join(", ")}); repeat it for more times`, (at, all = []) => [...all, at])
90
108
  .option("--at-time <time>", "one run: 30m, 2d from now, or an ISO time; the schedule removes itself after it")
91
109
  .addOption(new Option("--notify-on <when>", "desktop notice after a run (default failures for an agent that repeats with --every, else always)").choices(NOTIFY_WHEN))
92
110
  .option("--deliver-to <route>", `also send the result, when --notify-on says so, by the owner's own tg or mail: ${ROUTE_HELP}; repeat it for more`, (route, routes = []) => [...routes, routeText(parseRoute(route))]);
@@ -174,13 +192,15 @@ export const ownerLanguageOf = async (env) => {
174
192
  }
175
193
  };
176
194
  /** The templates the owner saved for a report, read without migrating the store; none when there is no store. */
177
- const reportTemplatesOf = (env) => async (kind, language) => {
195
+ const reportTemplatesOf = (env, schedule) => async (kind, language) => {
178
196
  const path = storePath(env);
179
197
  if (!existsSync(path))
180
198
  return {};
181
199
  const database = await openCache(path);
182
200
  try {
183
- const bodies = storedTemplateBodies(database, keyOfKind(kind), language);
201
+ const bodies = Object.assign({}, ...reportKeysOf(kind, schedule)
202
+ .reverse()
203
+ .map((key) => storedTemplateBodies(database, key, language)));
184
204
  return Object.fromEntries(REPORT_CHANNELS.flatMap((channel) => (channel in bodies ? [[channel, bodies[channel]]] : [])));
185
205
  }
186
206
  finally {
@@ -199,6 +219,171 @@ export const backfillScheduleRun = (command, app, env, file, { at, input, agentR
199
219
  ...(input === undefined ? {} : { input }),
200
220
  ...(signal ? { signal } : {}),
201
221
  }));
222
+ /** The tool's state folder, which holds its schedules. */
223
+ export const scheduleState = ({ app, env }) => resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).state;
224
+ /** The variables a run gets on top of the timer's: the profile, where the files are, PATH. Never a credential. */
225
+ const scheduleEnvironment = ({ app, env, profile }) => {
226
+ // The command line refuses a schedule under the lock; a caller that gets here still passes the lock on.
227
+ const readOnly = readOnlyLockOf(app, env);
228
+ return {
229
+ [`${app.envPrefix}_PROFILE`]: profile,
230
+ ...locationVariables(app, env),
231
+ // The timer starts with almost no PATH; an agent runs the CLI and its own tools by name.
232
+ ...(env.PATH ? { PATH: env.PATH } : {}),
233
+ ...(readOnly ? { [readOnly]: "1" } : {}),
234
+ };
235
+ };
236
+ /** The schedule `spec` describes, with the harness's argv built here, never by the caller: its limits live in it. */
237
+ export const agentSchedule = (site, spec) => {
238
+ const { app, system, env, agentRuns = [], limits = {} } = site;
239
+ const { harness, prompt, when } = spec;
240
+ const minimum = spec.onNewMail ? GATED_AGENT_MINIMUM_MINUTES : AGENT_MINIMUM_MINUTES;
241
+ if ("every" in when && !(Number.isInteger(when.every) && when.every >= minimum))
242
+ throw new CliError("validation_error", `an agent repeats at least every ${minimum} minutes, in whole minutes`);
243
+ if (isCalendar(when)) {
244
+ const slots = slotsOf(when);
245
+ if (slots.length === 0 || slots.some((slot) => !CLOCK.test(slot.at) || (slot.on && !WEEKDAYS.includes(slot.on))))
246
+ throw new CliError("validation_error", "an agent's times are HH:MM, each on any day or one weekday");
247
+ }
248
+ if (spec.model !== undefined && !isModel(spec.model))
249
+ throw new CliError("validation_error", `--model takes an alias such as sonnet or a model id, not "${spec.model}"`);
250
+ const model = spec.model ?? limits.models?.[harness] ?? AGENT_MODELS[harness];
251
+ const modelFlag = model ? ["--model", model] : [];
252
+ const program = findProgram(harness, env, system.platform);
253
+ if (!program)
254
+ throw new CliError("not_found", `${harness} is not on PATH`);
255
+ const agentClis = [app, ...agentRuns];
256
+ const folders = agentClis.flatMap((one) => {
257
+ const paths = resolvePaths({ appName: one.appName, prefix: one.envPrefix, env });
258
+ return [paths.state, paths.config, paths.cache];
259
+ });
260
+ const argv = harness === "claude"
261
+ ? [
262
+ program,
263
+ "-p",
264
+ prompt,
265
+ // The owner's own settings may let every tool run (bypassPermissions); here only the CLI may.
266
+ "--permission-mode",
267
+ "dontAsk",
268
+ "--allowedTools",
269
+ ...agentClis.map((one) => `Bash(${one.command}:*)`),
270
+ "--no-session-persistence",
271
+ ...modelFlag,
272
+ ...((limits.leanStart ?? true) ? LEAN_CLAUDE : []),
273
+ ...(spec.maxCost ? ["--max-budget-usd", String(spec.maxCost)] : []),
274
+ ]
275
+ : [
276
+ program,
277
+ "exec",
278
+ "--skip-git-repo-check",
279
+ "--ephemeral",
280
+ "--sandbox",
281
+ "workspace-write",
282
+ // The CLIs reach their provider and write the store and their own state, and nothing else.
283
+ "-c",
284
+ "sandbox_workspace_write.network_access=true",
285
+ ...modelFlag,
286
+ ...[dirname(storePath(env)), ...folders].flatMap((dir) => ["--add-dir", dir]),
287
+ prompt,
288
+ ];
289
+ return {
290
+ name: scheduleName(spec.name),
291
+ kind: "agent",
292
+ argv,
293
+ when: spec.when,
294
+ environment: scheduleEnvironment(site),
295
+ createdAt: new Date().toISOString(),
296
+ ...(spec.onNewMail ? { onNewMail: spec.onNewMail } : {}),
297
+ ...(spec.mailWaitMinutes === undefined ? {} : { mailWaitMinutes: spec.mailWaitMinutes }),
298
+ ...(spec.mailBatch === undefined ? {} : { mailBatch: spec.mailBatch }),
299
+ ...(spec.maxCostPerDay === undefined ? {} : { maxCostPerDay: spec.maxCostPerDay }),
300
+ ...(spec.notify ? { notify: spec.notify } : {}),
301
+ ...(spec.to?.length ? { to: spec.to } : {}),
302
+ ...(spec.paused ? { paused: true } : {}),
303
+ };
304
+ };
305
+ /**
306
+ * Writes the schedule's file and puts it on its timer, or takes it off when it is paused. A name another profile's
307
+ * schedule holds is refused.
308
+ */
309
+ export const writeSchedule = async (site, schedule) => {
310
+ const { app, system, env, profile } = site;
311
+ const file = scheduleFile(scheduleState(site), schedule.name);
312
+ const replaced = existsSync(file);
313
+ if (replaced) {
314
+ const owner = readSchedule(file).environment[`${app.envPrefix}_PROFILE`];
315
+ if (owner && owner !== profile) {
316
+ throw new CliError("validation_error", `schedule ${schedule.name} already runs for profile ${owner}; name this one for ${profile}, e.g. ${schedule.name}-${profile}`);
317
+ }
318
+ }
319
+ writeSecurely(file, `${JSON.stringify(schedule, null, 2)}\n`, 0o600);
320
+ const timer = timerFor(app, system, env);
321
+ if (schedule.paused)
322
+ await timer.remove(schedule.name);
323
+ else
324
+ await timer.install(schedule, [...system.entry, "schedule", "exec", file]);
325
+ return { file, timer: timer.where(schedule.name), replaced };
326
+ };
327
+ /** Why an agent schedule may not start today: its runs cost the day's cap. Recorded as the run's skip. */
328
+ const dayCapReached = (file, schedule, maxCostPerDay) => {
329
+ if (schedule.kind !== "agent" || maxCostPerDay <= 0)
330
+ return undefined;
331
+ const spent = spentToday(file);
332
+ if (spent < maxCostPerDay)
333
+ return undefined;
334
+ const why = `today's runs cost ${usd(spent)}, the ${usd(maxCostPerDay)} a day allowed; it runs again tomorrow`;
335
+ recordSkip(file, why, SKIP_REASONS.costDayCap);
336
+ return { why, reason: SKIP_REASONS.costDayCap };
337
+ };
338
+ /** Refuses a route the schedule was not given: it would send the owner's report somewhere he never said. */
339
+ const ownRoutes = (schedule, routes) => {
340
+ const own = schedule.to ?? [];
341
+ const other = (routes ?? []).filter((route) => !own.includes(route));
342
+ if (other.length)
343
+ throw new CliError("validation_error", `--deliver-to takes only ${schedule.name}'s own routes (${own.join(", ") || "it has none"}); not ${other.join(", ")}`);
344
+ };
345
+ /**
346
+ * Takes a schedule off its timer and keeps its file, or puts it back. It keeps the profile it was made for, as pausing
347
+ * names no new one.
348
+ */
349
+ export const pauseSchedule = async (site, name, paused) => {
350
+ const file = scheduleFile(scheduleState(site), scheduleName(name));
351
+ if (!existsSync(file))
352
+ throw new CliError("not_found", `no schedule ${name}`);
353
+ const { paused: _, ...schedule } = readSchedule(file);
354
+ const owner = schedule.environment[`${site.app.envPrefix}_PROFILE`] ?? site.profile;
355
+ const kept = paused ? { ...schedule, paused: true } : schedule;
356
+ return { schedule: kept, ...(await writeSchedule({ ...site, profile: owner }, kept)) };
357
+ };
358
+ /** Takes the schedule off its timer and removes its file; its past runs stay. */
359
+ export const removeSchedule = async (site, name) => {
360
+ const file = scheduleFile(scheduleState(site), scheduleName(name));
361
+ if (!existsSync(file))
362
+ throw new CliError("not_found", `no schedule ${name}`);
363
+ await timerFor(site.app, site.system, site.env).remove(name);
364
+ rmSync(file, { force: true });
365
+ };
366
+ /**
367
+ * Runs the schedule in `file` now, as `schedule run` does: its report rendered with the owner's language and templates
368
+ * and sent along `routes` (its own when absent, none when empty). A stop of the command stops the agent.
369
+ */
370
+ export const runScheduleNow = async (command, site, file, { routes, agentInput } = {}) => {
371
+ const schedule = readSchedule(file);
372
+ ownRoutes(schedule, routes);
373
+ const maxCostPerDay = schedule.maxCostPerDay ?? site.limits?.maxCostPerDay ?? SCHEDULE_DEFAULTS.maxCostPerDay;
374
+ const capped = dayCapReached(file, schedule, maxCostPerDay);
375
+ if (capped)
376
+ return { skipped: capped };
377
+ return untilChildEnds(command, (signal) => runSchedule(site.app, site.system, site.env, file, {
378
+ timer: timerFor(site.app, site.system, site.env),
379
+ agentRuns: site.agentRuns ?? [],
380
+ ownerLanguage: ownerLanguageOf,
381
+ reportTemplates: reportTemplatesOf,
382
+ ...(agentInput ? { agentInput } : {}),
383
+ ...(routes ? { routes } : {}),
384
+ ...(signal ? { signal } : {}),
385
+ }));
386
+ };
202
387
  /**
203
388
  * Runs the CLI's own commands, or an agent, later or on a timer — through systemd (Linux), launchd
204
389
  * (macOS) or Task Scheduler (Windows). Every timer runs `schedule exec <file>`; the schedule file holds
@@ -210,36 +395,27 @@ export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInpu
210
395
  const prepare = (self, resolving = {}) => {
211
396
  const context = contextOf(self, resolving);
212
397
  const system = environmentOf(self).system ?? thisMachine();
213
- const state = resolvePaths({ appName: app.appName, prefix: app.envPrefix, env: context.env }).state;
398
+ const site = {
399
+ app,
400
+ system,
401
+ env: context.env,
402
+ profile: context.profile,
403
+ agentRuns,
404
+ limits: configured?.(self) ?? {},
405
+ };
406
+ const state = scheduleState(site);
214
407
  const say = (value, lines) => renderAnswer(self, context, itemOf(value), () => lines.join("\n"));
215
408
  const timer = () => timerFor(app, system, context.env);
216
- // The command line refuses a schedule under the lock; a caller that gets here still passes the lock on.
217
- const readOnly = readOnlyLockOf(app, context.env);
218
- const environment = () => ({
219
- [`${app.envPrefix}_PROFILE`]: context.profile,
220
- ...locationVariables(app, context.env),
221
- // The timer starts with almost no PATH; an agent runs `max` and its own tools by name.
222
- ...(context.env.PATH ? { PATH: context.env.PATH } : {}),
223
- ...(readOnly ? { [readOnly]: "1" } : {}),
224
- });
409
+ const environment = () => scheduleEnvironment(site);
225
410
  const save = async (schedule) => {
226
- const file = scheduleFile(state, schedule.name);
227
- const replaced = existsSync(file);
228
- if (replaced) {
229
- const owner = readSchedule(file).environment[`${app.envPrefix}_PROFILE`];
230
- if (owner && owner !== context.profile) {
231
- throw new CliError("validation_error", `schedule ${schedule.name} already runs for profile ${owner}; name this one for ${context.profile}, e.g. ${schedule.name}-${context.profile}`);
232
- }
233
- }
234
- writeSecurely(file, `${JSON.stringify(schedule, null, 2)}\n`, 0o600);
235
- await timer().install(schedule, [...system.entry, "schedule", "exec", file]);
236
- say(scheduleAnswer(schedule, { file, timer: timer().where(schedule.name), replaced }), [
237
- `${replaced ? "Replaced" : "Added"} ${schedule.name}: ${describeWhen(schedule.when)}.`,
411
+ const { file, timer: where, replaced } = await writeSchedule(site, schedule);
412
+ say(scheduleAnswer(schedule, { file, timer: where, replaced }), [
413
+ `${replaced ? "Replaced" : "Added"} ${schedule.name}: ${describeWhen(schedule.when)}${schedule.paused ? ", paused" : ""}.`,
238
414
  `It runs: ${schedule.kind === "agent" ? shown(schedule.argv) : `${app.command} ${shown(schedule.argv)}`}`,
239
415
  `Output: ${join(dirname(file), "runs")} · now: ${lineOf(self, `schedule run ${schedule.name}`)} · stop: ${lineOf(self, `schedule remove ${schedule.name}`)}`,
240
416
  ]);
241
417
  };
242
- return { context, system, state, say, timer, environment, save };
418
+ return { context, system, state, say, timer, environment, save, site };
243
419
  };
244
420
  /**
245
421
  * Why a run does not start now, or nothing: an agent whose runs reached the day's cost cap waits for tomorrow, and
@@ -260,14 +436,9 @@ export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInpu
260
436
  return undefined;
261
437
  const schedule = readSchedule(file);
262
438
  const { mailWaitMinutes, mailBatch, maxCostPerDay } = limitsOf(self, schedule);
263
- if (schedule.kind === "agent" && maxCostPerDay > 0) {
264
- const spent = spentToday(file);
265
- if (spent >= maxCostPerDay) {
266
- const why = `today's runs cost ${usd(spent)}, the ${usd(maxCostPerDay)} a day allowed; it runs again tomorrow`;
267
- recordSkip(file, why, SKIP_REASONS.costDayCap);
268
- return { why, reason: SKIP_REASONS.costDayCap };
269
- }
270
- }
439
+ const capped = dayCapReached(file, schedule, maxCostPerDay);
440
+ if (capped)
441
+ return capped;
271
442
  const holder = schedule.onNewMail;
272
443
  if (holder === undefined || !newMail)
273
444
  return undefined;
@@ -326,7 +497,7 @@ export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInpu
326
497
  .option("--model <model>", `the model it runs on: an alias such as sonnet, or a model id; "" for the harness's default (default sonnet for claude, codex's own for codex, or the config file's)`)
327
498
  .addOption(new Option("--max-cost <usd>", "claude only: stop a run that costs more than this, in US dollars").argParser(Number))
328
499
  .addOption(new Option("--max-cost-per-day <usd>", `claude only: start no run for the rest of the day once its runs cost this much, in US dollars; 0 for no cap (default ${SCHEDULE_DEFAULTS.maxCostPerDay}, or the config file's)`).argParser(Number))).action(async function (name, harness, prompt) {
329
- const { context, system, environment, save } = prepare(this);
500
+ const { site, save } = prepare(this);
330
501
  const options = this.opts();
331
502
  if (options.onNewMail !== undefined && !HOLDER.test(options.onNewMail))
332
503
  throw new CliError("validation_error", `--on-new-mail takes a holder: lower-case letters, digits and dashes`);
@@ -338,60 +509,19 @@ export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInpu
338
509
  if (mailBatch !== undefined && !(Number.isSafeInteger(mailBatch) && mailBatch >= 1))
339
510
  throw new CliError("validation_error", "--mail-batch takes a count of emails, 1 or more");
340
511
  const mailWaitMinutes = options.mailWait === undefined ? undefined : Math.ceil(parseDuration(options.mailWait, "--mail-wait") / 60_000);
341
- if (options.model !== undefined && !isModel(options.model))
342
- throw new CliError("validation_error", `--model takes an alias such as sonnet or a model id, not "${options.model}"`);
343
- const settings = configured?.(this) ?? {};
344
- const model = options.model ?? settings.models?.[harness] ?? AGENT_MODELS[harness];
345
- const modelFlag = model ? ["--model", model] : [];
346
- const program = findProgram(harness, context.env, system.platform);
347
- if (!program)
348
- throw new CliError("not_found", `${harness} is not on PATH`);
349
- const folders = agentClis.flatMap((one) => {
350
- const paths = resolvePaths({ appName: one.appName, prefix: one.envPrefix, env: context.env });
351
- return [paths.state, paths.config, paths.cache];
352
- });
353
- const argv = harness === "claude"
354
- ? [
355
- program,
356
- "-p",
357
- prompt,
358
- // The owner's own settings may let every tool run (bypassPermissions); here only the CLI may.
359
- "--permission-mode",
360
- "dontAsk",
361
- "--allowedTools",
362
- ...agentClis.map((one) => `Bash(${one.command}:*)`),
363
- "--no-session-persistence",
364
- ...modelFlag,
365
- ...((settings.leanStart ?? true) ? LEAN_CLAUDE : []),
366
- ...(options.maxCost ? ["--max-budget-usd", String(options.maxCost)] : []),
367
- ]
368
- : [
369
- program,
370
- "exec",
371
- "--skip-git-repo-check",
372
- "--ephemeral",
373
- "--sandbox",
374
- "workspace-write",
375
- // The CLIs reach their provider and write the store and their own state, and nothing else.
376
- "-c",
377
- "sandbox_workspace_write.network_access=true",
378
- ...modelFlag,
379
- ...[dirname(storePath(context.env)), ...folders].flatMap((dir) => ["--add-dir", dir]),
380
- prompt,
381
- ];
382
- await save({
383
- name: scheduleName(name),
384
- kind: "agent",
385
- argv,
512
+ await save(agentSchedule(site, {
513
+ name,
514
+ harness,
515
+ prompt,
386
516
  when: whenOf(options, options.onNewMail ? GATED_AGENT_MINIMUM_MINUTES : AGENT_MINIMUM_MINUTES),
387
- environment: environment(),
388
- createdAt: new Date().toISOString(),
517
+ ...(options.model === undefined ? {} : { model: options.model }),
518
+ ...(options.maxCost ? { maxCost: options.maxCost } : {}),
519
+ ...(options.maxCostPerDay === undefined ? {} : { maxCostPerDay: options.maxCostPerDay }),
389
520
  ...(options.onNewMail ? { onNewMail: options.onNewMail } : {}),
390
521
  ...(mailWaitMinutes === undefined ? {} : { mailWaitMinutes }),
391
522
  ...(mailBatch === undefined ? {} : { mailBatch }),
392
- ...(options.maxCostPerDay === undefined ? {} : { maxCostPerDay: options.maxCostPerDay }),
393
523
  ...deliveryOf(options),
394
- });
524
+ }));
395
525
  });
396
526
  if (newMail)
397
527
  command.commands
@@ -411,6 +541,7 @@ export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInpu
411
541
  name: schedule.name,
412
542
  kind: schedule.kind,
413
543
  when: describeWhen(schedule.when),
544
+ ...(schedule.paused ? { paused: true } : {}),
414
545
  notify: notifyOf(schedule),
415
546
  ...(schedule.to?.length ? { deliverTo: schedule.to } : {}),
416
547
  last: lastRun(scheduleFile(state, schedule.name)) ?? null,
@@ -433,10 +564,10 @@ export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInpu
433
564
  return "";
434
565
  }
435
566
  return rows
436
- .map(({ name, kind, when, notify, deliverTo, last, spentTodayUsd, maxCostPerDayUsd }) => [
567
+ .map(({ name, kind, when, paused, notify, deliverTo, last, spentTodayUsd, maxCostPerDayUsd }) => [
437
568
  name,
438
569
  kind,
439
- when,
570
+ paused ? `${when}, paused` : when,
440
571
  `notify ${notify}`,
441
572
  ...(deliverTo ? [`to ${deliverTo.join(", ")}`] : []),
442
573
  last
@@ -463,22 +594,28 @@ export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInpu
463
594
  effects: REMOTE_WRITE,
464
595
  examples: [`${app.command} personal schedule run health`],
465
596
  })
466
- .description("run a schedule now, as its timer would, and wait for it")
597
+ .description("run a schedule now, as its timer would, and wait for it; a paused one runs too")
467
598
  .argument("<name>", "the schedule's name, as `schedule list` shows it")
468
- .action(async function (name) {
469
- const { context, system, state, say, timer } = prepare(this);
470
- const skip = await waits(this, scheduleFile(state, scheduleName(name)), { timed: false });
599
+ .option("--no-notify", "keep the result here: send it along none of its routes")
600
+ .option("--deliver-to <route>", "send it along only this one of its own routes; repeat it for more", (route, routes = []) => [...routes, routeText(parseRoute(route))])
601
+ .action(async function (name, given) {
602
+ const { state, say, site } = prepare(this);
603
+ const file = scheduleFile(state, scheduleName(name));
604
+ const routes = given.notify ? given.deliverTo : [];
605
+ if (!given.notify && given.deliverTo)
606
+ throw new CliError("validation_error", "--no-notify sends nothing; leave out --deliver-to, or leave out --no-notify");
607
+ const skip = await waits(this, file, { timed: false });
471
608
  if (skip !== undefined) {
472
609
  return say({ name, skipped: true, why: skip.why, reason: skip.reason }, [`${name}: skipped — ${skip.why}`]);
473
610
  }
474
- const last = await untilChildEnds(this, (signal) => runSchedule(app, system, context.env, scheduleFile(state, scheduleName(name)), {
475
- timer: timer(),
476
- agentRuns,
477
- ownerLanguage: ownerLanguageOf,
478
- reportTemplates: reportTemplatesOf,
611
+ const last = await runScheduleNow(this, site, file, {
479
612
  ...(agentInput ? { agentInput } : {}),
480
- ...(signal ? { signal } : {}),
481
- }));
613
+ ...(routes ? { routes } : {}),
614
+ });
615
+ if (!("exitCode" in last)) {
616
+ const { why, reason } = last.skipped;
617
+ return say({ name, skipped: true, why, reason }, [`${name}: skipped — ${why}`]);
618
+ }
482
619
  say(snakeKeys({ name, ...last }), [`${name}: exit ${last.exitCode} — ${last.output}`]);
483
620
  if (last.exitCode !== 0)
484
621
  setExitCode(this, 1);
@@ -490,14 +627,38 @@ export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInpu
490
627
  .description("stop a schedule and remove its timer; its past output stays")
491
628
  .argument("<name>", "the schedule's name, as `schedule list` shows it")
492
629
  .action(async function (name) {
493
- const { state, say, timer } = prepare(this);
494
- const file = scheduleFile(state, scheduleName(name));
495
- if (!existsSync(file))
630
+ const { state, say, site } = prepare(this);
631
+ if (!existsSync(scheduleFile(state, scheduleName(name))))
496
632
  throw new CliError("not_found", `no schedule ${name} — \`${lineOf(this, "schedule list")}\``);
497
- await timer().remove(name);
498
- rmSync(file, { force: true });
633
+ await removeSchedule(site, name);
499
634
  say({ name, removed: true }, [`Removed ${name}.`]);
500
635
  });
636
+ const setPaused = (paused) => async function (name) {
637
+ const { state, say, site } = prepare(this);
638
+ const file = scheduleFile(state, scheduleName(name));
639
+ if (!existsSync(file))
640
+ throw new CliError("not_found", `no schedule ${name} — \`${lineOf(this, "schedule list")}\``);
641
+ const { schedule, timer } = await pauseSchedule(site, name, paused);
642
+ say({ name, paused, timer }, [
643
+ paused
644
+ ? `Paused ${name}: no timer starts it; ${lineOf(this, `schedule run ${name}`)} still does.`
645
+ : `Resumed ${name}: ${describeWhen(schedule.when)}.`,
646
+ ]);
647
+ };
648
+ grantsAuthority(annotate(command.command("pause"), {
649
+ effects: LOCAL_WRITE,
650
+ examples: [`${app.command} personal schedule pause health`],
651
+ }))
652
+ .description("take a schedule off its timer and keep it; run runs it, resume puts it back")
653
+ .argument("<name>", "the schedule's name, as `schedule list` shows it")
654
+ .action(setPaused(true));
655
+ grantsAuthority(annotate(command.command("resume"), {
656
+ effects: LOCAL_WRITE,
657
+ examples: [`${app.command} personal schedule resume health`],
658
+ }))
659
+ .description("put a paused schedule back on its timer")
660
+ .argument("<name>", "the schedule's name, as `schedule list` shows it")
661
+ .action(setPaused(false));
501
662
  annotate(command.command("exec"), {
502
663
  effects: REMOTE_WRITE,
503
664
  examples: [`${app.command} schedule exec ~/.local/share/${app.appName}/schedules/health/schedule.json`],
@@ -507,6 +668,9 @@ export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInpu
507
668
  .action(async function (file) {
508
669
  // A timer starts it with no profile named; the schedule's own environment carries the profile.
509
670
  const { context, system, timer } = prepare(this, { needsProfile: false });
671
+ // A timer left behind by a pause that could not remove it must not run the schedule.
672
+ if (existsSync(file) && readSchedule(file).paused)
673
+ return;
510
674
  if ((await waits(this, file, { timed: true })) !== undefined)
511
675
  return;
512
676
  const last = await untilChildEnds(this, (signal) => runSchedule(app, system, context.env, file, {