@luxass/pi-schedule 0.0.0-stage → 0.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026-PRESENT Lucas Nørgård
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,35 @@
1
- # Temporary Holding Version
1
+ # @luxass/pi-schedule
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Schedule prompts to run later in a [Pi](https://pi.dev) conversation, once or on a repeat. When a job is due, its prompt arrives in the chat and Pi works on it.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pi install npm:@luxass/pi-schedule
9
+ ```
10
+
11
+ To try it from this repository, run `pi -e ./packages/pi-schedule`.
12
+
13
+ ## Use
14
+
15
+ Ask Pi to do something later, such as "in 20 minutes, check whether CI on #57 is green" or "every 30 minutes, check the deploy log". The model schedules a job with a name, a prompt, and a time:
16
+
17
+ - `delay` runs the job after a duration, such as `90s`, `20m`, `1h30m`, or `2d`.
18
+ - `at` runs it at a local time. `18:00` means the next time the clock shows 18:00. A date and time such as `2026-12-24T09:00` also works. Add `Z` or an offset for another time zone.
19
+ - `every` repeats the job, at most once a minute. The first run is at `delay` or `at`, or one interval from now.
20
+ - `skip_if_late` skips a run that would start more than this long after its time, such as `5m`, because Pi was closed or busy. Ask for it with work that must not happen much later, such as a merge or a deploy. A skipped run shows in the chat but does not start a turn.
21
+
22
+ When a job is due and Pi is idle, its prompt arrives as a message and starts a turn. If Pi is working, the job waits until Pi finishes, so it never interrupts a turn. A repeating job that came due several times while it waited runs once.
23
+
24
+ To run an agent at a set time, put the agent in the prompt. With [`@luxass/pi-subagents`](../pi-subagents/README.md), the model can start it when the job runs.
25
+
26
+ | Control | Action |
27
+ | ----------- | ---------------------------------------------------------------------- |
28
+ | `/schedule` | List pending jobs with their next run, then choose one to cancel. |
29
+ | Footer | Shows the next job and its countdown, such as `⏰ check-ci in 12m +1`. |
30
+
31
+ You can also ask the model to list or cancel jobs.
32
+
33
+ Jobs belong to the session. `/reload` and `/resume` keep them, and `/new` and `/fork` start without them. A job that came due while Pi was closed runs once when you open the session again, and its message says how late it is. If the job has `skip_if_late` and is later than that, it is skipped instead. Jobs run only in the interactive terminal and RPC mode. In print and JSON mode, a scheduled job waits for the next interactive run of the session.
34
+
35
+ A session can have up to 20 pending jobs, each at most a year ahead.
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@luxass/pi-schedule",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.0",
4
+ "description": "Schedule prompts to run later or on a repeat in a Pi conversation.",
5
+ "keywords": [
6
+ "pi",
7
+ "pi-extension",
8
+ "pi-package",
9
+ "schedule"
10
+ ],
11
+ "license": "MIT",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/luxass/agent-extensions",
15
+ "directory": "packages/pi-schedule"
16
+ },
17
+ "files": [
18
+ "src",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "type": "module",
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "devDependencies": {
27
+ "@earendil-works/pi-coding-agent": "1.6.0",
28
+ "@earendil-works/pi-tui": "1.6.0"
29
+ },
30
+ "peerDependencies": {
31
+ "@earendil-works/pi-coding-agent": "*",
32
+ "@earendil-works/pi-tui": "*",
33
+ "typebox": "*"
34
+ },
35
+ "pi": {
36
+ "image": "https://raw.githubusercontent.com/luxass/agent-extensions/main/packages/pi-schedule/docs/cover.png",
37
+ "extensions": [
38
+ "./src/index.ts"
39
+ ]
40
+ },
41
+ "scripts": {
42
+ "lint": "oxlint .",
43
+ "lint:fix": "oxlint --fix .",
44
+ "fmt": "oxfmt .",
45
+ "fmt:check": "oxfmt --check .",
46
+ "typecheck": "tsc -p tsconfig.json",
47
+ "test": "node --test \"test/**/*.test.ts\""
48
+ }
6
49
  }
package/src/index.ts ADDED
@@ -0,0 +1,39 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+
3
+ import { JobScheduler, SCHEDULE_DUE_MESSAGE } from "./jobs.ts";
4
+ import { registerScheduleTools } from "./tools.ts";
5
+ import { installScheduleStatus, registerScheduleCommand, renderScheduleDueMessage } from "./ui.ts";
6
+
7
+ /** Pi entry point for @luxass/pi-schedule. */
8
+ export default function piSchedule(pi: ExtensionAPI): void {
9
+ let scheduler: JobScheduler | undefined;
10
+ let removeStatus: (() => void) | undefined;
11
+
12
+ function stop(): void {
13
+ removeStatus?.();
14
+ removeStatus = undefined;
15
+ scheduler?.dispose();
16
+ scheduler = undefined;
17
+ }
18
+
19
+ pi.registerMessageRenderer(SCHEDULE_DUE_MESSAGE, renderScheduleDueMessage);
20
+
21
+ // Registered here, not in session_start: on /reload Pi redraws the chat before session_start,
22
+ // and it can only draw the calls of tools it already knows.
23
+ registerScheduleTools(pi, () => scheduler);
24
+ registerScheduleCommand(pi, () => scheduler);
25
+
26
+ // /new, /resume, /fork, and /reload load a new runtime, so this runs again for each session.
27
+ pi.on("session_start", (_event, ctx) => {
28
+ stop();
29
+ // Print and JSON modes exit after their prompt. Their jobs run in the next interactive run.
30
+ scheduler = new JobScheduler(pi, ctx, ctx.sessionManager.getSessionId(), ctx.hasUI);
31
+ scheduler.restore();
32
+ if (ctx.hasUI) removeStatus = installScheduleStatus(ctx, scheduler);
33
+ scheduler.start();
34
+ });
35
+
36
+ pi.on("agent_start", () => scheduler?.agentStarted());
37
+ pi.on("agent_settled", () => scheduler?.agentSettled());
38
+ pi.on("session_shutdown", () => stop());
39
+ }
package/src/jobs.ts ADDED
@@ -0,0 +1,336 @@
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+
5
+ import { formatScheduleDuration, formatScheduleTime } from "./time.ts";
6
+
7
+ /** Custom entry type that saves job snapshots in the session. The last snapshot of a job wins. */
8
+ export const SCHEDULE_JOB_ENTRY = "schedule-job";
9
+
10
+ /** Custom message type that brings due jobs into the conversation. */
11
+ export const SCHEDULE_DUE_MESSAGE = "schedule-due";
12
+
13
+ /** Pending jobs one session can have at once. */
14
+ export const MAX_PENDING_JOBS = 20;
15
+
16
+ /** Shortest repeat interval, so a repeating job cannot keep the model busy without a pause. */
17
+ export const MIN_REPEAT_MS = 60_000;
18
+
19
+ /** Furthest ahead a job can run. */
20
+ export const MAX_AHEAD_MS = 366 * 24 * 60 * 60 * 1000;
21
+
22
+ /**
23
+ * Longest single timer. Node's timers stop while the computer sleeps, so a long timer would fire
24
+ * late after a sleep. Short timers check the clock again soon after the computer wakes up.
25
+ */
26
+ const MAX_TIMER_MS = 60_000;
27
+
28
+ /** Time between checks while Pi is busy without an agent run, such as during compaction. */
29
+ const IDLE_CHECK_MS = 1000;
30
+
31
+ /** A job that runs this much after its time is reported as late. */
32
+ const LATE_AFTER_MS = 60_000;
33
+
34
+ const JOB_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
35
+
36
+ export type ScheduledJobStatus = "pending" | "done" | "skipped" | "cancelled";
37
+
38
+ /** One scheduled prompt. Saved in the session with `pi.appendEntry`. */
39
+ export interface ScheduledJob {
40
+ /** Session that owns the job. A forked session copies entries but not jobs. */
41
+ sessionId: string;
42
+ id: string;
43
+ name: string;
44
+ prompt: string;
45
+ createdAt: number;
46
+ /** When the job runs next. */
47
+ dueAt: number;
48
+ /** Repeat interval in milliseconds. Missing for a job that runs once. */
49
+ every?: number;
50
+ /**
51
+ * Longest time in milliseconds a run may start after its time, because Pi was closed or busy.
52
+ * A later run is skipped. Missing when a run may start any time later.
53
+ */
54
+ skipIfLate?: number;
55
+ status: ScheduledJobStatus;
56
+ runs: number;
57
+ lastRunAt?: number;
58
+ }
59
+
60
+ /** One job in a due message, as it was when it ran or was skipped. */
61
+ export interface DueJob {
62
+ name: string;
63
+ prompt: string;
64
+ dueAt: number;
65
+ /** When the job ran, or would have run if it was skipped. */
66
+ ranAt: number;
67
+ every?: number;
68
+ /** When a repeating job runs again. */
69
+ nextAt?: number;
70
+ skipIfLate?: number;
71
+ /** The run started too late for `skipIfLate`, so it did not run. */
72
+ skipped?: boolean;
73
+ }
74
+
75
+ /** Details of a due message, for its renderer. Not sent to the model. */
76
+ export interface ScheduleDueDetails {
77
+ jobs: DueJob[];
78
+ }
79
+
80
+ export interface NewScheduledJob {
81
+ name: string;
82
+ prompt: string;
83
+ dueAt: number;
84
+ every?: number;
85
+ skipIfLate?: number;
86
+ }
87
+
88
+ /** Whether a due job ran late enough to say so. */
89
+ export function isLateJob(job: DueJob): boolean {
90
+ return job.ranAt - job.dueAt >= LATE_AFTER_MS;
91
+ }
92
+
93
+ /** What the model reads when a job is due or skipped. */
94
+ function dueJobText(job: DueJob): string {
95
+ const repeat =
96
+ job.every && job.nextAt
97
+ ? `It repeats every ${formatScheduleDuration(job.every)}. The next run is at ${formatScheduleTime(job.nextAt, job.ranAt)}. Keep it unless the user asks you to cancel it.`
98
+ : undefined;
99
+ if (job.skipped) {
100
+ // The prompt is left out, so the model is not tempted to do the skipped work anyway.
101
+ const limit = formatScheduleDuration(job.skipIfLate ?? 0);
102
+ const late = formatScheduleDuration(job.ranAt - job.dueAt, "down");
103
+ return [
104
+ `Scheduled job ${job.name} was skipped. It was due at ${formatScheduleTime(job.dueAt, job.ranAt)}, but it could only start ${late} late, and it may start at most ${limit} late. Do not do it now unless the user asks.`,
105
+ ...(repeat ? [repeat] : []),
106
+ ].join("\n");
107
+ }
108
+ const notes: string[] = [];
109
+ if (isLateJob(job)) {
110
+ notes.push(
111
+ `It was due at ${formatScheduleTime(job.dueAt, job.ranAt)} and runs ${formatScheduleDuration(job.ranAt - job.dueAt, "down")} late.`,
112
+ );
113
+ }
114
+ if (repeat) notes.push(repeat);
115
+ const header = `Scheduled job ${job.name} is due. It was scheduled earlier in this conversation. Do it now.`;
116
+ return [header, ...notes, "", job.prompt].join("\n");
117
+ }
118
+
119
+ /**
120
+ * Keeps the session's jobs, runs them when they are due, and saves every change.
121
+ *
122
+ * A due job starts a turn when Pi is idle. While Pi works, due jobs wait until it settles, so a
123
+ * job never interrupts a turn. A repeating job that was due several times while it waited runs
124
+ * once. A run that would start later than the job's `skipIfLate` is skipped and reported
125
+ * without starting a turn.
126
+ */
127
+ export class JobScheduler {
128
+ private readonly jobs = new Map<string, ScheduledJob>();
129
+ private readonly listeners = new Set<() => void>();
130
+ private timer: ReturnType<typeof setTimeout> | undefined;
131
+ private busy = false;
132
+ private closed = false;
133
+ private readonly pi: ExtensionAPI;
134
+ private readonly ctx: ExtensionContext;
135
+ readonly sessionId: string;
136
+ /**
137
+ * Whether this Pi runs jobs. Print and JSON modes exit after their prompt, so they save jobs
138
+ * for the next interactive run of the session instead.
139
+ */
140
+ readonly runsJobs: boolean;
141
+
142
+ // Plain fields instead of constructor parameter properties, which Node's type stripping
143
+ // cannot run in tests.
144
+ constructor(pi: ExtensionAPI, ctx: ExtensionContext, sessionId: string, runsJobs: boolean) {
145
+ this.pi = pi;
146
+ this.ctx = ctx;
147
+ this.sessionId = sessionId;
148
+ this.runsJobs = runsJobs;
149
+ }
150
+
151
+ /** Restores the session's jobs from all branches. Jobs belong to the session, not a branch. */
152
+ restore(): void {
153
+ for (const entry of this.ctx.sessionManager.getEntries()) {
154
+ if (entry.type !== "custom" || entry.customType !== SCHEDULE_JOB_ENTRY) continue;
155
+ const job = entry.data as ScheduledJob | undefined;
156
+ if (job?.sessionId !== this.sessionId) continue;
157
+ this.jobs.set(job.id, { ...job });
158
+ }
159
+ }
160
+
161
+ /** Starts the timer. Jobs that came due while Pi was closed run as soon as Pi is idle. */
162
+ start(): void {
163
+ // After session_start, so Pi has finished opening the session before a job starts a turn.
164
+ this.setTimer(0);
165
+ }
166
+
167
+ /** Pending jobs, the next one first. */
168
+ pending(): ScheduledJob[] {
169
+ return [...this.jobs.values()]
170
+ .filter((job) => job.status === "pending")
171
+ .toSorted((left, right) => left.dueAt - right.dueAt);
172
+ }
173
+
174
+ /** The pending job with this name. */
175
+ find(name: string): ScheduledJob | undefined {
176
+ return this.pending().find((job) => job.name === name);
177
+ }
178
+
179
+ /** Adds a job. Throws before saving anything if the job is invalid. */
180
+ add(input: NewScheduledJob): ScheduledJob {
181
+ if (this.closed) throw new Error("The scheduler is shutting down.");
182
+ const now = Date.now();
183
+ const prompt = input.prompt.trim();
184
+ if (!prompt) throw new Error("A scheduled job needs a non-empty prompt.");
185
+ if (!JOB_NAME_PATTERN.test(input.name)) {
186
+ throw new Error(`Job name "${input.name}" must be lowercase words joined by hyphens.`);
187
+ }
188
+ if (this.find(input.name)) {
189
+ throw new Error(`A pending job is already named "${input.name}". Choose another name.`);
190
+ }
191
+ if (this.pending().length >= MAX_PENDING_JOBS) {
192
+ throw new Error(
193
+ `This session already has ${MAX_PENDING_JOBS} pending jobs. Cancel one before adding another.`,
194
+ );
195
+ }
196
+ if (input.dueAt <= now) throw new Error("The job's time has already passed.");
197
+ if (input.dueAt - now > MAX_AHEAD_MS) throw new Error("A job can run at most a year ahead.");
198
+ if (input.every !== undefined && input.every < MIN_REPEAT_MS) {
199
+ throw new Error("A repeating job must repeat at most once a minute.");
200
+ }
201
+ if (input.skipIfLate !== undefined && input.skipIfLate <= 0) {
202
+ throw new Error("skip_if_late must be longer than zero.");
203
+ }
204
+
205
+ const job: ScheduledJob = {
206
+ sessionId: this.sessionId,
207
+ id: randomUUID(),
208
+ name: input.name,
209
+ prompt,
210
+ createdAt: now,
211
+ dueAt: input.dueAt,
212
+ ...(input.every === undefined ? {} : { every: input.every }),
213
+ ...(input.skipIfLate === undefined ? {} : { skipIfLate: input.skipIfLate }),
214
+ status: "pending",
215
+ runs: 0,
216
+ };
217
+ this.jobs.set(job.id, job);
218
+ this.persist(job);
219
+ this.check();
220
+ return job;
221
+ }
222
+
223
+ /** Cancels a pending job by name. */
224
+ cancel(name: string): ScheduledJob {
225
+ const job = this.find(name);
226
+ if (!job) throw new Error(`No pending job is named "${name}".`);
227
+ job.status = "cancelled";
228
+ this.persist(job);
229
+ this.check();
230
+ return job;
231
+ }
232
+
233
+ /** Subscribes UI to job changes. Returns the unsubscribe function. */
234
+ subscribe(listener: () => void): () => void {
235
+ this.listeners.add(listener);
236
+ return () => this.listeners.delete(listener);
237
+ }
238
+
239
+ /** The main session started a run, so due jobs wait until it settles. */
240
+ agentStarted(): void {
241
+ this.busy = true;
242
+ }
243
+
244
+ /** The main session will not continue by itself, so due jobs can run. */
245
+ agentSettled(): void {
246
+ this.busy = false;
247
+ // Pi defers sends made inside agent_settled, so check after the event instead.
248
+ this.setTimer(0);
249
+ }
250
+
251
+ /** Stops the timer. Saved jobs stay pending for the next start of the session. */
252
+ dispose(): void {
253
+ this.closed = true;
254
+ this.clearTimer();
255
+ this.listeners.clear();
256
+ }
257
+
258
+ private check(): void {
259
+ this.clearTimer();
260
+ if (this.closed || !this.runsJobs) return;
261
+ const now = Date.now();
262
+ const due = this.pending().filter((job) => job.dueAt <= now);
263
+ if (due.length && !this.busy) {
264
+ // Compaction and branch summaries can keep Pi busy without an agent run.
265
+ if (!this.ctx.isIdle()) {
266
+ this.setTimer(IDLE_CHECK_MS);
267
+ return;
268
+ }
269
+ this.run(due, now);
270
+ }
271
+ // Due jobs that wait for a busy Pi need no timer: agent_settled checks again.
272
+ const next = Math.min(
273
+ ...this.pending()
274
+ .filter((job) => job.dueAt > now)
275
+ .map((job) => job.dueAt),
276
+ );
277
+ if (Number.isFinite(next)) this.setTimer(Math.min(next - now, MAX_TIMER_MS));
278
+ }
279
+
280
+ private run(due: ScheduledJob[], now: number): void {
281
+ const items: DueJob[] = [];
282
+ for (const job of due) {
283
+ const skipped = job.skipIfLate !== undefined && now - job.dueAt > job.skipIfLate;
284
+ const item: DueJob = {
285
+ name: job.name,
286
+ prompt: job.prompt,
287
+ dueAt: job.dueAt,
288
+ ranAt: now,
289
+ ...(job.skipIfLate === undefined ? {} : { skipIfLate: job.skipIfLate }),
290
+ ...(skipped ? { skipped } : {}),
291
+ };
292
+ if (!skipped) {
293
+ job.runs++;
294
+ job.lastRunAt = now;
295
+ }
296
+ if (job.every) {
297
+ // Keep the rhythm after a short wait. After a long one, count from now.
298
+ const next = job.dueAt + job.every;
299
+ job.dueAt = next > now ? next : now + job.every;
300
+ Object.assign(item, { every: job.every, nextAt: job.dueAt });
301
+ } else {
302
+ job.status = skipped ? "skipped" : "done";
303
+ }
304
+ this.persist(job);
305
+ items.push(item);
306
+ }
307
+ this.pi.sendMessage<ScheduleDueDetails>(
308
+ {
309
+ customType: SCHEDULE_DUE_MESSAGE,
310
+ content: items.map(dueJobText).join("\n\n---\n\n"),
311
+ display: true,
312
+ details: { jobs: items },
313
+ },
314
+ // Skipped jobs are only reported. The model reads the report with the next prompt.
315
+ { triggerTurn: items.some((item) => !item.skipped) },
316
+ );
317
+ }
318
+
319
+ private setTimer(delay: number): void {
320
+ this.clearTimer();
321
+ if (this.closed) return;
322
+ this.timer = setTimeout(() => this.check(), Math.max(0, delay));
323
+ // A waiting job must not keep Pi's process alive.
324
+ this.timer.unref();
325
+ }
326
+
327
+ private clearTimer(): void {
328
+ clearTimeout(this.timer);
329
+ this.timer = undefined;
330
+ }
331
+
332
+ private persist(job: ScheduledJob): void {
333
+ this.pi.appendEntry(SCHEDULE_JOB_ENTRY, { ...job });
334
+ for (const listener of this.listeners) listener();
335
+ }
336
+ }
package/src/time.ts ADDED
@@ -0,0 +1,114 @@
1
+ const SECOND = 1000;
2
+ const MINUTE = 60 * SECOND;
3
+ const HOUR = 60 * MINUTE;
4
+ const DAY = 24 * HOUR;
5
+
6
+ const DURATION_UNITS: Record<string, number> = {
7
+ s: SECOND,
8
+ sec: SECOND,
9
+ secs: SECOND,
10
+ second: SECOND,
11
+ seconds: SECOND,
12
+ m: MINUTE,
13
+ min: MINUTE,
14
+ mins: MINUTE,
15
+ minute: MINUTE,
16
+ minutes: MINUTE,
17
+ h: HOUR,
18
+ hr: HOUR,
19
+ hrs: HOUR,
20
+ hour: HOUR,
21
+ hours: HOUR,
22
+ d: DAY,
23
+ day: DAY,
24
+ days: DAY,
25
+ };
26
+
27
+ /** One `<number><unit>` part of a duration, such as `1h` or `30 minutes`. */
28
+ const DURATION_PART = /(\d+)\s*([a-z]+)\s*/y;
29
+
30
+ /** `HH:MM` on a 24-hour clock. */
31
+ const CLOCK_TIME = /^(\d{1,2}):(\d{2})$/;
32
+
33
+ /** ISO 8601 date and time. Without `Z` or an offset, JavaScript reads it as local time. */
34
+ const ISO_DATE_TIME =
35
+ /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?$/i;
36
+
37
+ /**
38
+ * Reads a duration such as `90s`, `20m`, `1h30m`, `1h 30m`, or `2 days` in milliseconds.
39
+ * Returns `undefined` for anything else, including zero.
40
+ */
41
+ export function parseScheduleDuration(text: string): number | undefined {
42
+ const input = text.trim().toLowerCase();
43
+ if (!input) return undefined;
44
+ let total = 0;
45
+ DURATION_PART.lastIndex = 0;
46
+ while (DURATION_PART.lastIndex < input.length) {
47
+ const match = DURATION_PART.exec(input);
48
+ if (!match) return undefined;
49
+ const unit = DURATION_UNITS[match[2] ?? ""];
50
+ if (!unit) return undefined;
51
+ total += Number(match[1]) * unit;
52
+ }
53
+ return total > 0 && Number.isSafeInteger(total) ? total : undefined;
54
+ }
55
+
56
+ /**
57
+ * Reads a local clock time (`18:00`, the next time the clock shows it) or an ISO 8601 date and
58
+ * time. Returns the time in milliseconds since the epoch, or `undefined` when it is not a time.
59
+ */
60
+ export function parseScheduleTime(text: string, now: number): number | undefined {
61
+ const input = text.trim();
62
+ const clock = CLOCK_TIME.exec(input);
63
+ if (clock) {
64
+ const hours = Number(clock[1]);
65
+ const minutes = Number(clock[2]);
66
+ if (hours > 23 || minutes > 59) return undefined;
67
+ const time = new Date(now);
68
+ time.setHours(hours, minutes, 0, 0);
69
+ if (time.getTime() <= now) time.setDate(time.getDate() + 1);
70
+ return time.getTime();
71
+ }
72
+ if (!ISO_DATE_TIME.test(input)) return undefined;
73
+ const time = Date.parse(input.replace(" ", "T"));
74
+ return Number.isNaN(time) ? undefined : time;
75
+ }
76
+
77
+ /**
78
+ * Short duration for people and the model: `45s`, `12m`, `1h 5m`, or `2d 3h`.
79
+ * Rounds up by default, so a countdown never shows less time than is left. Round down to
80
+ * report time that has passed, such as how late a job runs.
81
+ */
82
+ export function formatScheduleDuration(
83
+ milliseconds: number,
84
+ rounding: "up" | "down" = "up",
85
+ ): string {
86
+ const whole = rounding === "up" ? Math.ceil : Math.floor;
87
+ const seconds = Math.max(0, whole(milliseconds / SECOND));
88
+ if (seconds < 60) return `${seconds}s`;
89
+ const minutes = whole(seconds / 60);
90
+ if (minutes < 60) return `${minutes}m`;
91
+ const days = Math.floor(minutes / (24 * 60));
92
+ const hours = Math.floor((minutes % (24 * 60)) / 60);
93
+ if (days > 0) return hours ? `${days}d ${hours}h` : `${days}d`;
94
+ const rest = minutes % 60;
95
+ return rest ? `${hours}h ${rest}m` : `${hours}h`;
96
+ }
97
+
98
+ function pad(value: number): string {
99
+ return String(value).padStart(2, "0");
100
+ }
101
+
102
+ /** Local time of day, with the date when it is not today: `18:00` or `2026-12-24 09:00`. */
103
+ export function formatScheduleTime(time: number, now: number): string {
104
+ const date = new Date(time);
105
+ const clock = `${pad(date.getHours())}:${pad(date.getMinutes())}`;
106
+ if (date.toDateString() === new Date(now).toDateString()) return clock;
107
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${clock}`;
108
+ }
109
+
110
+ /** When a job runs, relative to now: `18:00 (in 20m)`, or `due` once its time has passed. */
111
+ export function formatScheduleDue(time: number, now: number): string {
112
+ if (time <= now) return "due";
113
+ return `${formatScheduleTime(time, now)} (in ${formatScheduleDuration(time - now)})`;
114
+ }
package/src/tools.ts ADDED
@@ -0,0 +1,166 @@
1
+ import type { AgentToolResult, ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+
4
+ import type { JobScheduler, ScheduledJob } from "./jobs.ts";
5
+ import {
6
+ formatScheduleDue,
7
+ formatScheduleDuration,
8
+ parseScheduleDuration,
9
+ parseScheduleTime,
10
+ } from "./time.ts";
11
+
12
+ /**
13
+ * Gives the session's scheduler, or nothing before a session has started. The tools are registered
14
+ * in the extension's default function, where no session exists yet.
15
+ */
16
+ export type JobSchedulerSource = () => JobScheduler | undefined;
17
+
18
+ function requireScheduler(getScheduler: JobSchedulerSource): JobScheduler {
19
+ const scheduler = getScheduler();
20
+ if (!scheduler)
21
+ throw new Error("Scheduled jobs are not available until the session has started.");
22
+ return scheduler;
23
+ }
24
+
25
+ function toolResult(text: string): AgentToolResult<undefined> {
26
+ return { content: [{ type: "text", text }], details: undefined };
27
+ }
28
+
29
+ /** One line per job: name, next run, repeat interval, and the first line of the prompt. */
30
+ export function scheduledJobLine(job: ScheduledJob, now: number): string {
31
+ const every = job.every ? ` · every ${formatScheduleDuration(job.every)}` : "";
32
+ const skip = job.skipIfLate ? ` · skip if ${formatScheduleDuration(job.skipIfLate)} late` : "";
33
+ const prompt = job.prompt.split("\n")[0] ?? "";
34
+ return `${job.name} · ${formatScheduleDue(job.dueAt, now)}${every}${skip} · ${prompt}`;
35
+ }
36
+
37
+ const scheduleParameters = Type.Object({
38
+ name: Type.String({
39
+ description:
40
+ "Unique name among pending jobs: lowercase words joined by hyphens, such as check-ci.",
41
+ }),
42
+ prompt: Type.String({
43
+ description:
44
+ "What to do when the job runs. It arrives later as a new message, maybe after compaction, so make it complete on its own.",
45
+ }),
46
+ delay: Type.Optional(
47
+ Type.String({ description: 'Run after this long, such as "90s", "20m", "1h30m", or "2d".' }),
48
+ ),
49
+ at: Type.Optional(
50
+ Type.String({
51
+ description:
52
+ 'Run at this local time: "18:00" for the next time the clock shows it, or "2026-12-24T09:00". Add Z or an offset for another time zone.',
53
+ }),
54
+ ),
55
+ every: Type.Optional(
56
+ Type.String({
57
+ description:
58
+ 'Repeat at this interval, at least "1m", such as "30m". The first run is at delay or at, or one interval from now.',
59
+ }),
60
+ ),
61
+ skip_if_late: Type.Optional(
62
+ Type.String({
63
+ description:
64
+ 'Skip a run that would start more than this long after its time because Pi was closed or busy, such as "5m". Use it for work that must not happen much later, such as a merge or a deploy. Without it, a late run still happens.',
65
+ }),
66
+ ),
67
+ });
68
+
69
+ /** Registers schedule_job, list_scheduled_jobs, and cancel_scheduled_job. */
70
+ export function registerScheduleTools(pi: ExtensionAPI, getScheduler: JobSchedulerSource): void {
71
+ pi.registerTool({
72
+ name: "schedule_job",
73
+ label: "Schedule job",
74
+ description:
75
+ "Schedule a prompt to run later in this conversation, once or repeatedly. Use it only when the user asks for something to happen later or on a repeat. When the job is due, its prompt arrives as a new message and starts a turn. If you are working then, it waits until you finish. Give delay or at, every, or every with one of them.",
76
+ promptSnippet: "Run a prompt later or on a repeat in this conversation",
77
+ parameters: scheduleParameters,
78
+ async execute(_toolCallId, params) {
79
+ const scheduler = requireScheduler(getScheduler);
80
+ const now = Date.now();
81
+ if (params.delay !== undefined && params.at !== undefined) {
82
+ throw new Error("Give either delay or at, not both.");
83
+ }
84
+
85
+ let every: number | undefined;
86
+ if (params.every !== undefined) {
87
+ every = parseScheduleDuration(params.every);
88
+ if (every === undefined) {
89
+ throw new Error(`every "${params.every}" is not a duration such as "30m" or "2h".`);
90
+ }
91
+ }
92
+
93
+ let skipIfLate: number | undefined;
94
+ if (params.skip_if_late !== undefined) {
95
+ skipIfLate = parseScheduleDuration(params.skip_if_late);
96
+ if (skipIfLate === undefined) {
97
+ throw new Error(
98
+ `skip_if_late "${params.skip_if_late}" is not a duration such as "5m" or "1h".`,
99
+ );
100
+ }
101
+ }
102
+
103
+ let dueAt: number | undefined;
104
+ if (params.delay !== undefined) {
105
+ const delay = parseScheduleDuration(params.delay);
106
+ if (delay === undefined) {
107
+ throw new Error(`delay "${params.delay}" is not a duration such as "20m" or "1h30m".`);
108
+ }
109
+ dueAt = now + delay;
110
+ } else if (params.at !== undefined) {
111
+ dueAt = parseScheduleTime(params.at, now);
112
+ if (dueAt === undefined) {
113
+ throw new Error(`at "${params.at}" is not a time such as "18:00" or "2026-12-24T09:00".`);
114
+ }
115
+ } else if (every !== undefined) {
116
+ dueAt = now + every;
117
+ } else {
118
+ throw new Error("Give delay, at, or every.");
119
+ }
120
+
121
+ const job = scheduler.add({
122
+ name: params.name,
123
+ prompt: params.prompt,
124
+ dueAt,
125
+ every,
126
+ skipIfLate,
127
+ });
128
+ const repeat = job.every ? `, then every ${formatScheduleDuration(job.every)}` : "";
129
+ const skip = job.skipIfLate
130
+ ? ` A run that would start more than ${formatScheduleDuration(job.skipIfLate)} late is skipped.`
131
+ : "";
132
+ const later = scheduler.runsJobs
133
+ ? ""
134
+ : " Pi is not running interactively, so the job runs when this session is next open in the terminal.";
135
+ return toolResult(
136
+ `Scheduled ${job.name} for ${formatScheduleDue(job.dueAt, now)}${repeat}.${skip}${later} Its prompt arrives by itself. Do not wait for it or check on it.`,
137
+ );
138
+ },
139
+ });
140
+
141
+ pi.registerTool({
142
+ name: "list_scheduled_jobs",
143
+ label: "Scheduled jobs",
144
+ description: "List this session's pending scheduled jobs, the next one first.",
145
+ parameters: Type.Object({}),
146
+ async execute() {
147
+ const jobs = requireScheduler(getScheduler).pending();
148
+ if (!jobs.length) return toolResult("No jobs are scheduled.");
149
+ const now = Date.now();
150
+ return toolResult(jobs.map((job) => scheduledJobLine(job, now)).join("\n"));
151
+ },
152
+ });
153
+
154
+ pi.registerTool({
155
+ name: "cancel_scheduled_job",
156
+ label: "Cancel job",
157
+ description: "Cancel a pending scheduled job by name. A repeating job stops repeating.",
158
+ parameters: Type.Object({
159
+ name: Type.String({ description: "Name of the pending job." }),
160
+ }),
161
+ async execute(_toolCallId, params) {
162
+ const job = requireScheduler(getScheduler).cancel(params.name);
163
+ return toolResult(`Cancelled ${job.name}.`);
164
+ },
165
+ });
166
+ }
package/src/ui.ts ADDED
@@ -0,0 +1,98 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ MessageRenderer,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import { Box, Spacer, Text } from "@earendil-works/pi-tui";
7
+
8
+ import { isLateJob, type JobScheduler, type ScheduleDueDetails } from "./jobs.ts";
9
+ import { formatScheduleDuration } from "./time.ts";
10
+ import { scheduledJobLine, type JobSchedulerSource } from "./tools.ts";
11
+
12
+ /** Key of the next-job countdown in the footer's status line. */
13
+ export const SCHEDULE_STATUS = "schedule";
14
+
15
+ /** How often the countdown updates. It changes the text only when the shown time changes. */
16
+ const STATUS_INTERVAL_MS = 1000;
17
+
18
+ /** Draws a due message as one block per job: its name, when it ran or was skipped, and its prompt. */
19
+ export const renderScheduleDueMessage: MessageRenderer<ScheduleDueDetails> = (
20
+ message,
21
+ options,
22
+ theme,
23
+ ) => {
24
+ const jobs = message.details?.jobs ?? [];
25
+ if (!jobs.length) return undefined;
26
+ const box = new Box(options.outputPad, 1, (text) => theme.bg("customMessageBg", text));
27
+ jobs.forEach((job, index) => {
28
+ if (index > 0) box.addChild(new Spacer(1));
29
+ const late = job.skipped || isLateJob(job);
30
+ const notes = [
31
+ ...(late ? [`${formatScheduleDuration(job.ranAt - job.dueAt, "down")} late`] : []),
32
+ ...(job.skipped && job.skipIfLate ? [`limit ${formatScheduleDuration(job.skipIfLate)}`] : []),
33
+ ...(job.every ? [`every ${formatScheduleDuration(job.every)}`] : []),
34
+ ];
35
+ const label = job.skipped
36
+ ? theme.fg("warning", theme.bold("Skipped"))
37
+ : theme.fg("toolTitle", theme.bold("Scheduled"));
38
+ const suffix = notes.length ? theme.fg("muted", ` · ${notes.join(" · ")}`) : "";
39
+ box.addChild(new Text(`${label} ${job.name}${suffix}`, 0, 0));
40
+ box.addChild(new Text(theme.fg(job.skipped ? "muted" : "text", job.prompt), 0, 0));
41
+ });
42
+ return box;
43
+ };
44
+
45
+ /**
46
+ * Shows the next job in the footer's status line, for example `⏰ check-ci in 12m`, with the
47
+ * number of further jobs. Hidden when no job is pending. Returns the function that removes it.
48
+ */
49
+ export function installScheduleStatus(ctx: ExtensionContext, scheduler: JobScheduler): () => void {
50
+ let shown: string | undefined;
51
+ const update = () => {
52
+ const [next, ...rest] = scheduler.pending();
53
+ let text: string | undefined;
54
+ if (next) {
55
+ const left = next.dueAt - Date.now();
56
+ const when = left > 0 ? `in ${formatScheduleDuration(left)}` : "due";
57
+ text = `⏰ ${next.name} ${when}${rest.length ? ` +${rest.length}` : ""}`;
58
+ }
59
+ if (text === shown) return;
60
+ shown = text;
61
+ ctx.ui.setStatus(SCHEDULE_STATUS, text);
62
+ };
63
+ const unsubscribe = scheduler.subscribe(update);
64
+ const timer = setInterval(update, STATUS_INTERVAL_MS);
65
+ timer.unref();
66
+ update();
67
+ return () => {
68
+ clearInterval(timer);
69
+ unsubscribe();
70
+ ctx.ui.setStatus(SCHEDULE_STATUS, undefined);
71
+ };
72
+ }
73
+
74
+ /** Registers `/schedule`, which lists pending jobs and cancels the one you choose. */
75
+ export function registerScheduleCommand(pi: ExtensionAPI, getScheduler: JobSchedulerSource): void {
76
+ pi.registerCommand("schedule", {
77
+ description: "Show scheduled jobs and cancel one",
78
+ handler: async (_args, ctx) => {
79
+ const scheduler = getScheduler();
80
+ if (!scheduler || !ctx.hasUI) return;
81
+ const jobs = scheduler.pending();
82
+ if (!jobs.length) {
83
+ ctx.ui.notify("No jobs are scheduled.", "info");
84
+ return;
85
+ }
86
+ const now = Date.now();
87
+ const lines = jobs.map((job) => scheduledJobLine(job, now));
88
+ const choice = await ctx.ui.select("Scheduled jobs · choose one to cancel", lines);
89
+ const job = choice === undefined ? undefined : jobs[lines.indexOf(choice)];
90
+ if (!job) return;
91
+ const confirmed = await ctx.ui.confirm(`Cancel ${job.name}?`, job.prompt);
92
+ // The job can run or be cancelled while the dialog is open.
93
+ if (!confirmed || scheduler.find(job.name)?.id !== job.id) return;
94
+ scheduler.cancel(job.name);
95
+ ctx.ui.notify(`Cancelled ${job.name}.`, "info");
96
+ },
97
+ });
98
+ }