@wirecat/cli-core 0.623.0 → 0.625.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 +85 -0
- package/dist/background/backfill.d.ts +1 -1
- package/dist/background/backfill.js +1 -1
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/background/report/stored-templates.d.ts +21 -3
- package/dist/background/report/stored-templates.js +34 -6
- package/dist/background/schedules.d.ts +10 -20
- package/dist/background/schedules.js +8 -162
- package/dist/background/timers.d.ts +19 -0
- package/dist/background/timers.js +175 -0
- package/dist/background/when.d.ts +28 -7
- package/dist/background/when.js +55 -11
- package/dist/calendar/prepare.d.ts +14 -0
- package/dist/cli/app-doctor-command.js +2 -1
- package/dist/cli/envelope.d.ts +28 -0
- package/dist/cli/index.d.ts +3 -2
- package/dist/cli/index.js +3 -2
- package/dist/cli/schedule/schedule-command.d.ts +100 -3
- package/dist/cli/schedule/schedule-command.js +276 -118
- package/dist/cli/templates-command.js +45 -20
- package/dist/domain/display-names.d.ts +5 -2
- package/dist/domain/display-names.js +13 -4
- package/dist/domain/person-kinds.d.ts +9 -0
- package/dist/domain/person-kinds.js +67 -0
- package/dist/domain/records-table.d.ts +61 -0
- package/dist/domain/records-table.js +382 -0
- package/dist/entities/index.d.ts +2 -1
- package/dist/entities/list-results.d.ts +2 -0
- package/dist/entities/list-results.js +2 -0
- package/dist/entities/template.d.ts +1 -1
- package/dist/entities/template.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/mcp/surface.js +23 -2
- package/dist/meetings/mcp/index.d.ts +15 -15
- package/dist/services/index.d.ts +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/metadata.d.ts +1 -1
- package/dist/services/search-harder.d.ts +6 -1
- package/dist/services/search-harder.js +9 -2
- package/dist/store/index.d.ts +2 -1
- package/dist/store/index.js +2 -0
- package/dist/store/people.d.ts +4 -3
- package/dist/store/sqlite/people-list.d.ts +23 -8
- package/dist/store/sqlite/people-list.js +189 -65
- package/package.json +2 -2
- package/parity.json +29 -0
|
@@ -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 {
|
|
10
|
-
import { describeWhen, findProgram, lastRun, listSchedules, NOTIFY_WHEN, notifyOf, readSchedule, recordSkip, runSchedule, SCHEDULE_DEFAULTS, SKIP_REASONS, scheduleFile, scheduleName, spentToday, timerFor, WEEKDAYS, } 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
|
|
42
|
-
|
|
43
|
-
|
|
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,19 +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
|
-
const
|
|
53
|
-
if (
|
|
54
|
-
throw new CliError("validation_error",
|
|
55
|
-
const day = word?.toLowerCase().slice(0, 3);
|
|
56
|
-
if (word !== undefined && !WEEKDAYS.includes(day ?? ""))
|
|
57
|
-
throw new CliError("validation_error", `--at takes a weekday, ${WEEKDAYS.join(", ")}; not "${word}"`);
|
|
58
|
-
if (every && (day !== undefined || parseDuration(every, "--every") !== 86_400_000)) {
|
|
59
|
-
throw new CliError("validation_error", day === undefined
|
|
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
|
|
60
70
|
? "--at runs once a day; leave out --every, or use --every 1d"
|
|
61
|
-
: "
|
|
71
|
+
: "weekly" in when
|
|
72
|
+
? "a weekday in --at runs once a week; leave out --every"
|
|
73
|
+
: "--at sets the times; leave out --every");
|
|
62
74
|
}
|
|
63
|
-
return
|
|
75
|
+
return when;
|
|
64
76
|
}
|
|
65
77
|
const minutes = parseDuration(every ?? "", "--every") / 60_000;
|
|
66
78
|
if (!Number.isInteger(minutes) || minutes < minimum) {
|
|
@@ -92,7 +104,7 @@ const scheduleAnswer = ({ environment, createdAt, to, ...schedule }, extra) => (
|
|
|
92
104
|
});
|
|
93
105
|
const withWhen = (command) => command
|
|
94
106
|
.option("--every <duration>", "repeat: 30m, 2h, 1d")
|
|
95
|
-
.option("--at <HH:MM>", `every day at this local time; 'mon 09:00' once a week (${WEEKDAYS.join(", ")})
|
|
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])
|
|
96
108
|
.option("--at-time <time>", "one run: 30m, 2d from now, or an ISO time; the schedule removes itself after it")
|
|
97
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))
|
|
98
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))]);
|
|
@@ -180,13 +192,15 @@ export const ownerLanguageOf = async (env) => {
|
|
|
180
192
|
}
|
|
181
193
|
};
|
|
182
194
|
/** The templates the owner saved for a report, read without migrating the store; none when there is no store. */
|
|
183
|
-
const reportTemplatesOf = (env) => async (kind, language) => {
|
|
195
|
+
const reportTemplatesOf = (env, schedule) => async (kind, language) => {
|
|
184
196
|
const path = storePath(env);
|
|
185
197
|
if (!existsSync(path))
|
|
186
198
|
return {};
|
|
187
199
|
const database = await openCache(path);
|
|
188
200
|
try {
|
|
189
|
-
const bodies =
|
|
201
|
+
const bodies = Object.assign({}, ...reportKeysOf(kind, schedule)
|
|
202
|
+
.reverse()
|
|
203
|
+
.map((key) => storedTemplateBodies(database, key, language)));
|
|
190
204
|
return Object.fromEntries(REPORT_CHANNELS.flatMap((channel) => (channel in bodies ? [[channel, bodies[channel]]] : [])));
|
|
191
205
|
}
|
|
192
206
|
finally {
|
|
@@ -205,6 +219,171 @@ export const backfillScheduleRun = (command, app, env, file, { at, input, agentR
|
|
|
205
219
|
...(input === undefined ? {} : { input }),
|
|
206
220
|
...(signal ? { signal } : {}),
|
|
207
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
|
+
};
|
|
208
387
|
/**
|
|
209
388
|
* Runs the CLI's own commands, or an agent, later or on a timer — through systemd (Linux), launchd
|
|
210
389
|
* (macOS) or Task Scheduler (Windows). Every timer runs `schedule exec <file>`; the schedule file holds
|
|
@@ -216,36 +395,27 @@ export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInpu
|
|
|
216
395
|
const prepare = (self, resolving = {}) => {
|
|
217
396
|
const context = contextOf(self, resolving);
|
|
218
397
|
const system = environmentOf(self).system ?? thisMachine();
|
|
219
|
-
const
|
|
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);
|
|
220
407
|
const say = (value, lines) => renderAnswer(self, context, itemOf(value), () => lines.join("\n"));
|
|
221
408
|
const timer = () => timerFor(app, system, context.env);
|
|
222
|
-
|
|
223
|
-
const readOnly = readOnlyLockOf(app, context.env);
|
|
224
|
-
const environment = () => ({
|
|
225
|
-
[`${app.envPrefix}_PROFILE`]: context.profile,
|
|
226
|
-
...locationVariables(app, context.env),
|
|
227
|
-
// The timer starts with almost no PATH; an agent runs `max` and its own tools by name.
|
|
228
|
-
...(context.env.PATH ? { PATH: context.env.PATH } : {}),
|
|
229
|
-
...(readOnly ? { [readOnly]: "1" } : {}),
|
|
230
|
-
});
|
|
409
|
+
const environment = () => scheduleEnvironment(site);
|
|
231
410
|
const save = async (schedule) => {
|
|
232
|
-
const file =
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
const owner = readSchedule(file).environment[`${app.envPrefix}_PROFILE`];
|
|
236
|
-
if (owner && owner !== context.profile) {
|
|
237
|
-
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}`);
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
writeSecurely(file, `${JSON.stringify(schedule, null, 2)}\n`, 0o600);
|
|
241
|
-
await timer().install(schedule, [...system.entry, "schedule", "exec", file]);
|
|
242
|
-
say(scheduleAnswer(schedule, { file, timer: timer().where(schedule.name), replaced }), [
|
|
243
|
-
`${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" : ""}.`,
|
|
244
414
|
`It runs: ${schedule.kind === "agent" ? shown(schedule.argv) : `${app.command} ${shown(schedule.argv)}`}`,
|
|
245
415
|
`Output: ${join(dirname(file), "runs")} · now: ${lineOf(self, `schedule run ${schedule.name}`)} · stop: ${lineOf(self, `schedule remove ${schedule.name}`)}`,
|
|
246
416
|
]);
|
|
247
417
|
};
|
|
248
|
-
return { context, system, state, say, timer, environment, save };
|
|
418
|
+
return { context, system, state, say, timer, environment, save, site };
|
|
249
419
|
};
|
|
250
420
|
/**
|
|
251
421
|
* Why a run does not start now, or nothing: an agent whose runs reached the day's cost cap waits for tomorrow, and
|
|
@@ -266,14 +436,9 @@ export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInpu
|
|
|
266
436
|
return undefined;
|
|
267
437
|
const schedule = readSchedule(file);
|
|
268
438
|
const { mailWaitMinutes, mailBatch, maxCostPerDay } = limitsOf(self, schedule);
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
const why = `today's runs cost ${usd(spent)}, the ${usd(maxCostPerDay)} a day allowed; it runs again tomorrow`;
|
|
273
|
-
recordSkip(file, why, SKIP_REASONS.costDayCap);
|
|
274
|
-
return { why, reason: SKIP_REASONS.costDayCap };
|
|
275
|
-
}
|
|
276
|
-
}
|
|
439
|
+
const capped = dayCapReached(file, schedule, maxCostPerDay);
|
|
440
|
+
if (capped)
|
|
441
|
+
return capped;
|
|
277
442
|
const holder = schedule.onNewMail;
|
|
278
443
|
if (holder === undefined || !newMail)
|
|
279
444
|
return undefined;
|
|
@@ -332,7 +497,7 @@ export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInpu
|
|
|
332
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)`)
|
|
333
498
|
.addOption(new Option("--max-cost <usd>", "claude only: stop a run that costs more than this, in US dollars").argParser(Number))
|
|
334
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) {
|
|
335
|
-
const {
|
|
500
|
+
const { site, save } = prepare(this);
|
|
336
501
|
const options = this.opts();
|
|
337
502
|
if (options.onNewMail !== undefined && !HOLDER.test(options.onNewMail))
|
|
338
503
|
throw new CliError("validation_error", `--on-new-mail takes a holder: lower-case letters, digits and dashes`);
|
|
@@ -344,60 +509,19 @@ export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInpu
|
|
|
344
509
|
if (mailBatch !== undefined && !(Number.isSafeInteger(mailBatch) && mailBatch >= 1))
|
|
345
510
|
throw new CliError("validation_error", "--mail-batch takes a count of emails, 1 or more");
|
|
346
511
|
const mailWaitMinutes = options.mailWait === undefined ? undefined : Math.ceil(parseDuration(options.mailWait, "--mail-wait") / 60_000);
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
const modelFlag = model ? ["--model", model] : [];
|
|
352
|
-
const program = findProgram(harness, context.env, system.platform);
|
|
353
|
-
if (!program)
|
|
354
|
-
throw new CliError("not_found", `${harness} is not on PATH`);
|
|
355
|
-
const folders = agentClis.flatMap((one) => {
|
|
356
|
-
const paths = resolvePaths({ appName: one.appName, prefix: one.envPrefix, env: context.env });
|
|
357
|
-
return [paths.state, paths.config, paths.cache];
|
|
358
|
-
});
|
|
359
|
-
const argv = harness === "claude"
|
|
360
|
-
? [
|
|
361
|
-
program,
|
|
362
|
-
"-p",
|
|
363
|
-
prompt,
|
|
364
|
-
// The owner's own settings may let every tool run (bypassPermissions); here only the CLI may.
|
|
365
|
-
"--permission-mode",
|
|
366
|
-
"dontAsk",
|
|
367
|
-
"--allowedTools",
|
|
368
|
-
...agentClis.map((one) => `Bash(${one.command}:*)`),
|
|
369
|
-
"--no-session-persistence",
|
|
370
|
-
...modelFlag,
|
|
371
|
-
...((settings.leanStart ?? true) ? LEAN_CLAUDE : []),
|
|
372
|
-
...(options.maxCost ? ["--max-budget-usd", String(options.maxCost)] : []),
|
|
373
|
-
]
|
|
374
|
-
: [
|
|
375
|
-
program,
|
|
376
|
-
"exec",
|
|
377
|
-
"--skip-git-repo-check",
|
|
378
|
-
"--ephemeral",
|
|
379
|
-
"--sandbox",
|
|
380
|
-
"workspace-write",
|
|
381
|
-
// The CLIs reach their provider and write the store and their own state, and nothing else.
|
|
382
|
-
"-c",
|
|
383
|
-
"sandbox_workspace_write.network_access=true",
|
|
384
|
-
...modelFlag,
|
|
385
|
-
...[dirname(storePath(context.env)), ...folders].flatMap((dir) => ["--add-dir", dir]),
|
|
386
|
-
prompt,
|
|
387
|
-
];
|
|
388
|
-
await save({
|
|
389
|
-
name: scheduleName(name),
|
|
390
|
-
kind: "agent",
|
|
391
|
-
argv,
|
|
512
|
+
await save(agentSchedule(site, {
|
|
513
|
+
name,
|
|
514
|
+
harness,
|
|
515
|
+
prompt,
|
|
392
516
|
when: whenOf(options, options.onNewMail ? GATED_AGENT_MINIMUM_MINUTES : AGENT_MINIMUM_MINUTES),
|
|
393
|
-
|
|
394
|
-
|
|
517
|
+
...(options.model === undefined ? {} : { model: options.model }),
|
|
518
|
+
...(options.maxCost ? { maxCost: options.maxCost } : {}),
|
|
519
|
+
...(options.maxCostPerDay === undefined ? {} : { maxCostPerDay: options.maxCostPerDay }),
|
|
395
520
|
...(options.onNewMail ? { onNewMail: options.onNewMail } : {}),
|
|
396
521
|
...(mailWaitMinutes === undefined ? {} : { mailWaitMinutes }),
|
|
397
522
|
...(mailBatch === undefined ? {} : { mailBatch }),
|
|
398
|
-
...(options.maxCostPerDay === undefined ? {} : { maxCostPerDay: options.maxCostPerDay }),
|
|
399
523
|
...deliveryOf(options),
|
|
400
|
-
});
|
|
524
|
+
}));
|
|
401
525
|
});
|
|
402
526
|
if (newMail)
|
|
403
527
|
command.commands
|
|
@@ -417,6 +541,7 @@ export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInpu
|
|
|
417
541
|
name: schedule.name,
|
|
418
542
|
kind: schedule.kind,
|
|
419
543
|
when: describeWhen(schedule.when),
|
|
544
|
+
...(schedule.paused ? { paused: true } : {}),
|
|
420
545
|
notify: notifyOf(schedule),
|
|
421
546
|
...(schedule.to?.length ? { deliverTo: schedule.to } : {}),
|
|
422
547
|
last: lastRun(scheduleFile(state, schedule.name)) ?? null,
|
|
@@ -439,10 +564,10 @@ export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInpu
|
|
|
439
564
|
return "";
|
|
440
565
|
}
|
|
441
566
|
return rows
|
|
442
|
-
.map(({ name, kind, when, notify, deliverTo, last, spentTodayUsd, maxCostPerDayUsd }) => [
|
|
567
|
+
.map(({ name, kind, when, paused, notify, deliverTo, last, spentTodayUsd, maxCostPerDayUsd }) => [
|
|
443
568
|
name,
|
|
444
569
|
kind,
|
|
445
|
-
when,
|
|
570
|
+
paused ? `${when}, paused` : when,
|
|
446
571
|
`notify ${notify}`,
|
|
447
572
|
...(deliverTo ? [`to ${deliverTo.join(", ")}`] : []),
|
|
448
573
|
last
|
|
@@ -469,22 +594,28 @@ export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInpu
|
|
|
469
594
|
effects: REMOTE_WRITE,
|
|
470
595
|
examples: [`${app.command} personal schedule run health`],
|
|
471
596
|
})
|
|
472
|
-
.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")
|
|
473
598
|
.argument("<name>", "the schedule's name, as `schedule list` shows it")
|
|
474
|
-
.
|
|
475
|
-
|
|
476
|
-
|
|
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 });
|
|
477
608
|
if (skip !== undefined) {
|
|
478
609
|
return say({ name, skipped: true, why: skip.why, reason: skip.reason }, [`${name}: skipped — ${skip.why}`]);
|
|
479
610
|
}
|
|
480
|
-
const last = await
|
|
481
|
-
timer: timer(),
|
|
482
|
-
agentRuns,
|
|
483
|
-
ownerLanguage: ownerLanguageOf,
|
|
484
|
-
reportTemplates: reportTemplatesOf,
|
|
611
|
+
const last = await runScheduleNow(this, site, file, {
|
|
485
612
|
...(agentInput ? { agentInput } : {}),
|
|
486
|
-
...(
|
|
487
|
-
})
|
|
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
|
+
}
|
|
488
619
|
say(snakeKeys({ name, ...last }), [`${name}: exit ${last.exitCode} — ${last.output}`]);
|
|
489
620
|
if (last.exitCode !== 0)
|
|
490
621
|
setExitCode(this, 1);
|
|
@@ -496,14 +627,38 @@ export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInpu
|
|
|
496
627
|
.description("stop a schedule and remove its timer; its past output stays")
|
|
497
628
|
.argument("<name>", "the schedule's name, as `schedule list` shows it")
|
|
498
629
|
.action(async function (name) {
|
|
499
|
-
const { state, say,
|
|
500
|
-
|
|
501
|
-
if (!existsSync(file))
|
|
630
|
+
const { state, say, site } = prepare(this);
|
|
631
|
+
if (!existsSync(scheduleFile(state, scheduleName(name))))
|
|
502
632
|
throw new CliError("not_found", `no schedule ${name} — \`${lineOf(this, "schedule list")}\``);
|
|
503
|
-
await
|
|
504
|
-
rmSync(file, { force: true });
|
|
633
|
+
await removeSchedule(site, name);
|
|
505
634
|
say({ name, removed: true }, [`Removed ${name}.`]);
|
|
506
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));
|
|
507
662
|
annotate(command.command("exec"), {
|
|
508
663
|
effects: REMOTE_WRITE,
|
|
509
664
|
examples: [`${app.command} schedule exec ~/.local/share/${app.appName}/schedules/health/schedule.json`],
|
|
@@ -513,6 +668,9 @@ export const scheduleCommandFor = ({ app, context: contextOf, newMail, agentInpu
|
|
|
513
668
|
.action(async function (file) {
|
|
514
669
|
// A timer starts it with no profile named; the schedule's own environment carries the profile.
|
|
515
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;
|
|
516
674
|
if ((await waits(this, file, { timed: true })) !== undefined)
|
|
517
675
|
return;
|
|
518
676
|
const last = await untilChildEnds(this, (signal) => runSchedule(app, system, context.env, file, {
|