@tidegap/core 0.21.0 → 0.23.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/dist/channels/digest.d.ts +4 -1
- package/dist/channels/digest.js +7 -3
- package/dist/channels/format.d.ts +61 -19
- package/dist/channels/format.js +181 -51
- package/dist/channels/index.d.ts +1 -0
- package/dist/channels/index.js +1 -0
- package/dist/channels/kinds/discord.js +2 -2
- package/dist/channels/kinds/email.js +2 -1
- package/dist/channels/kinds/ntfy.js +9 -1
- package/dist/channels/kinds/pushover.js +4 -3
- package/dist/channels/kinds/shared.d.ts +4 -1
- package/dist/channels/kinds/shared.js +6 -1
- package/dist/channels/kinds/slack.js +2 -2
- package/dist/channels/notice.d.ts +42 -0
- package/dist/channels/notice.js +142 -0
- package/dist/channels/payload.d.ts +3 -0
- package/dist/channels/payload.js +19 -6
- package/dist/channels/plan.js +3 -2
- package/dist/channels/telegram.d.ts +18 -0
- package/dist/channels/telegram.js +23 -9
- package/dist/channels/types.d.ts +17 -1
- package/dist/grid.d.ts +10 -2
- package/dist/grid.js +14 -5
- package/dist/handoff.d.ts +66 -3
- package/dist/handoff.js +108 -3
- package/dist/history.d.ts +105 -0
- package/dist/history.js +108 -1
- package/dist/index.d.ts +15 -11
- package/dist/index.js +10 -6
- package/dist/job-cadence.d.ts +10 -0
- package/dist/job-cadence.js +34 -0
- package/dist/job-wake.d.ts +55 -0
- package/dist/job-wake.js +91 -0
- package/dist/jobs.d.ts +54 -2
- package/dist/jobs.js +258 -14
- package/dist/notice-language.d.ts +37 -0
- package/dist/notice-language.js +67 -0
- package/dist/providers/base.d.ts +14 -0
- package/dist/schedule-job.d.ts +18 -2
- package/dist/schedule-job.js +22 -2
- package/dist/scheduler.d.ts +2 -0
- package/dist/scheduler.js +5 -1
- package/dist/storage/sqlite.d.ts +24 -3
- package/dist/storage/sqlite.js +135 -28
- package/dist/task-events.d.ts +1 -1
- package/dist/task-events.js +9 -0
- package/dist/tool-surface.js +25 -1
- package/dist/types.d.ts +41 -1
- package/package.json +2 -2
package/dist/schedule-job.js
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
*/
|
|
11
11
|
import { includesFileTool, includesWebTool } from "./claude-tools.js";
|
|
12
12
|
import { guaranteeText, parseWindow, validateJobSchedule } from "./job-cadence.js";
|
|
13
|
+
import { wakePatternError } from "./job-wake.js";
|
|
13
14
|
import { getJob, removeJob } from "./jobs.js";
|
|
14
15
|
import { DURATION_FORM_ERROR, parseDuration, parseRetryDelay, RETRY_DELAY_ERROR, runLimitValueError, } from "./run-limits.js";
|
|
15
16
|
import { systemTimeZone } from "./zone-time.js";
|
|
@@ -20,7 +21,7 @@ export function isJobRepeat(repeat) {
|
|
|
20
21
|
return typeof repeat === "string" && JOB_REPEATS.includes(repeat);
|
|
21
22
|
}
|
|
22
23
|
/** Parameters that only mean something with a job repeat. */
|
|
23
|
-
export const JOB_ONLY_PARAMS = ["every_hours", "days", "window", "time_zone"];
|
|
24
|
+
export const JOB_ONLY_PARAMS = ["every_hours", "days", "window", "time_zone", "until", "count", "wake_match"];
|
|
24
25
|
/** Argument names that would make the run execute a shell command. */
|
|
25
26
|
const SHELL_KEYS = ["command", "cmd", "shell", "script"];
|
|
26
27
|
/** The CLI line that queues a one-off shell command task, which only the user runs. */
|
|
@@ -77,7 +78,6 @@ const JOB_UNSUPPORTED_PARAMS = [
|
|
|
77
78
|
"cwd",
|
|
78
79
|
"permission_profile",
|
|
79
80
|
"result_path",
|
|
80
|
-
"wake_session",
|
|
81
81
|
"redact_in_receipt",
|
|
82
82
|
"quota_provider",
|
|
83
83
|
"deliver",
|
|
@@ -110,6 +110,23 @@ export function jobToolsFor(tools) {
|
|
|
110
110
|
return "web";
|
|
111
111
|
return "none";
|
|
112
112
|
}
|
|
113
|
+
/**
|
|
114
|
+
* The wake rule of a `schedule_task` job call (KTD8), or undefined for
|
|
115
|
+
* none: `wake_session: true` wakes on a failed run, `wake_match` on a run
|
|
116
|
+
* whose output matches (with `wake_session` omitted or true). Throws an
|
|
117
|
+
* Error with a plain message.
|
|
118
|
+
*/
|
|
119
|
+
export function jobWakeArgs(args) {
|
|
120
|
+
if (args.wake_match === undefined)
|
|
121
|
+
return args.wake_session === true ? { on: "failures" } : undefined;
|
|
122
|
+
if (args.wake_session === false) {
|
|
123
|
+
throw new Error("wake_match wakes the session on a matching run: omit wake_session or set it to true, or drop wake_match");
|
|
124
|
+
}
|
|
125
|
+
const error = wakePatternError(args.wake_match);
|
|
126
|
+
if (error)
|
|
127
|
+
throw new Error(`wake_match: ${error}`);
|
|
128
|
+
return { on: "match", pattern: args.wake_match };
|
|
129
|
+
}
|
|
113
130
|
/**
|
|
114
131
|
* The `llm_timeout` tool argument in ms or `"none"`, or undefined when it
|
|
115
132
|
* is absent. Throws an Error whose message names the grammar and `none`.
|
|
@@ -206,6 +223,9 @@ export function scheduleJobInput(args, now = new Date()) {
|
|
|
206
223
|
originCwd: args.cwd,
|
|
207
224
|
...(caps && Object.keys(caps).length > 0 ? { caps } : {}),
|
|
208
225
|
...(args.deadline !== undefined ? { deadline: args.deadline } : {}),
|
|
226
|
+
...(args.until !== undefined ? { until: args.until } : {}),
|
|
227
|
+
...(args.count !== undefined ? { count: args.count } : {}),
|
|
228
|
+
...(args.wake !== undefined ? { wake: args.wake } : {}),
|
|
209
229
|
};
|
|
210
230
|
}
|
|
211
231
|
const LIVE = new Set(["queued", "scheduled", "running", "submitted"]);
|
package/dist/scheduler.d.ts
CHANGED
|
@@ -347,6 +347,8 @@ export declare class Scheduler {
|
|
|
347
347
|
bodyJson: string;
|
|
348
348
|
originHost?: TaskRecord["originHost"];
|
|
349
349
|
originCwd?: string;
|
|
350
|
+
/** The session a bound job wakes; its runs become that session's notices (KTD7). */
|
|
351
|
+
originSessionId?: string;
|
|
350
352
|
}, details: Record<string, unknown>): Promise<boolean>;
|
|
351
353
|
/**
|
|
352
354
|
* Defer a task. Returns a promise that resolves with the task's eventual
|
package/dist/scheduler.js
CHANGED
|
@@ -371,12 +371,15 @@ export class Scheduler {
|
|
|
371
371
|
title: occ.title,
|
|
372
372
|
originHost: occ.originHost,
|
|
373
373
|
originCwd: occ.originCwd,
|
|
374
|
+
...(occ.originSessionId ? { originSessionId: occ.originSessionId } : {}),
|
|
374
375
|
repeat: "none",
|
|
375
376
|
jobId: occ.jobId,
|
|
376
377
|
};
|
|
377
378
|
const created = this.eventFor(undefined, record, { kind: "created", actor: "system", details });
|
|
378
379
|
if (!this.store.insertIfAbsent(record, created))
|
|
379
380
|
return false;
|
|
381
|
+
if (record.originSessionId)
|
|
382
|
+
this.store.startSessionNotices(new Date(record.enqueuedAt));
|
|
380
383
|
this.cacheRow(record);
|
|
381
384
|
try {
|
|
382
385
|
await this.scheduleProviderCall(record.taskId, new Date(deadlineMs));
|
|
@@ -3044,7 +3047,7 @@ function checkedCaps(caps, keys, what) {
|
|
|
3044
3047
|
* Dispatch options of a run: its resolved time limits, the caps' budget,
|
|
3045
3048
|
* and for a row with `job_id` its working directory and job id. A
|
|
3046
3049
|
* `claude-code` row without a job gets its handoff folder. A `command` body
|
|
3047
|
-
* also hands over its shell and summarize steps.
|
|
3050
|
+
* also hands over its task id (for its attachments), shell and summarize steps.
|
|
3048
3051
|
*/
|
|
3049
3052
|
function jobDispatchOptions(record, spec, limits) {
|
|
3050
3053
|
const out = {};
|
|
@@ -3065,6 +3068,7 @@ function jobDispatchOptions(record, spec, limits) {
|
|
|
3065
3068
|
out.cwd = spec.handoff.cwd;
|
|
3066
3069
|
}
|
|
3067
3070
|
if (spec.provider === "command") {
|
|
3071
|
+
out.taskId = record.taskId;
|
|
3068
3072
|
if (spec.command)
|
|
3069
3073
|
out.command = spec.command;
|
|
3070
3074
|
if (spec.summarize)
|
package/dist/storage/sqlite.d.ts
CHANGED
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
* JSON-serializable are stored as `{ "_repr": "<toString>" }` so audit
|
|
56
56
|
* trails survive odd values without crashing the store.
|
|
57
57
|
*/
|
|
58
|
-
import { type DeadlineKind, type JobRecord, type JobStatus, type TaskRecord, type TaskStatus } from "../types.js";
|
|
58
|
+
import { type DeadlineKind, type JobNoticeReason, type JobRecord, type JobStatus, type TaskRecord, type TaskStatus } from "../types.js";
|
|
59
59
|
import { type Channel } from "../channels/types.js";
|
|
60
60
|
import { type TaskEvent, type TaskEventActor, type TaskEventInput, type TaskEventKind } from "../task-events.js";
|
|
61
61
|
interface SqliteDatabase {
|
|
@@ -110,9 +110,19 @@ export interface TaskStoreOptions {
|
|
|
110
110
|
export declare const SESSION_NOTICES_SINCE_META_KEY = "session_notices_since";
|
|
111
111
|
/** A finished task stays a session notice for this long. */
|
|
112
112
|
export declare const SESSION_NOTICE_MAX_AGE_MS: number;
|
|
113
|
+
/**
|
|
114
|
+
* The job sweep's decision on one run of a bound job (`session_notice`
|
|
115
|
+
* event): why the run is a session notice, and whether it wakes the session.
|
|
116
|
+
*/
|
|
117
|
+
export interface JobNotice {
|
|
118
|
+
reasons: JobNoticeReason[];
|
|
119
|
+
wake: boolean;
|
|
120
|
+
}
|
|
113
121
|
/** One finished task a Claude Code session has not been told about. */
|
|
114
122
|
export interface SessionNotice {
|
|
115
123
|
record: TaskRecord<unknown>;
|
|
124
|
+
/** For a run of a job: the sweep's decision, which a job row needs to be a notice at all. */
|
|
125
|
+
jobNotice?: JobNotice;
|
|
116
126
|
/** The result file the task asked for (`handoff.resultPath` of its body). */
|
|
117
127
|
resultPath?: string;
|
|
118
128
|
/** Details of the newest `result_file` event, when one was recorded. */
|
|
@@ -194,8 +204,10 @@ export declare class TaskStore {
|
|
|
194
204
|
* that finishes again is a new notice), and finished at or after
|
|
195
205
|
* {@link SESSION_NOTICES_SINCE_META_KEY} and within
|
|
196
206
|
* {@link SESSION_NOTICE_MAX_AGE_MS}. A completed task that asked for a
|
|
197
|
-
* result file waits until its `result_file` event exists. A
|
|
198
|
-
*
|
|
207
|
+
* result file waits until its `result_file` event exists. A run of a job
|
|
208
|
+
* (`job_id` set) is a notice only when the job sweep wrote a
|
|
209
|
+
* `session_notice` event for this finish; its details come back as
|
|
210
|
+
* {@link SessionNotice.jobNotice}. A person's read marker does not matter here.
|
|
199
211
|
*/
|
|
200
212
|
listSessionNotices(opts?: {
|
|
201
213
|
sessionId?: string;
|
|
@@ -213,6 +225,15 @@ export declare class TaskStore {
|
|
|
213
225
|
via: string;
|
|
214
226
|
session_id: string;
|
|
215
227
|
}, actor?: TaskEventActor): boolean;
|
|
228
|
+
/**
|
|
229
|
+
* Record the job sweep's decision on a run of a bound job: a
|
|
230
|
+
* `session_notice` event (actor `tick`) whose details carry the run's
|
|
231
|
+
* `completed_at`, written only when the run has none for this finish.
|
|
232
|
+
* Returns true iff this call wrote it.
|
|
233
|
+
*/
|
|
234
|
+
recordSessionNotice(taskId: string, notice: JobNotice): boolean;
|
|
235
|
+
/** The job sweep's decision on a run's current finish, or undefined when it wrote none. */
|
|
236
|
+
sessionNoticeOf(record: Pick<TaskRecord<unknown>, "taskId" | "completedAt">): JobNotice | undefined;
|
|
216
237
|
/**
|
|
217
238
|
* Completed tasks that asked for a result file (`handoff.resultPath` in
|
|
218
239
|
* the body) and have no `result_file` event yet, oldest first, whichever
|
package/dist/storage/sqlite.js
CHANGED
|
@@ -182,7 +182,14 @@ CREATE TABLE IF NOT EXISTS jobs (
|
|
|
182
182
|
retry_used INTEGER NOT NULL DEFAULT 0,
|
|
183
183
|
pause_reason TEXT,
|
|
184
184
|
paused_at TEXT,
|
|
185
|
-
pause_notified_at TEXT
|
|
185
|
+
pause_notified_at TEXT,
|
|
186
|
+
until TEXT,
|
|
187
|
+
runs_left INTEGER,
|
|
188
|
+
ended_at TEXT,
|
|
189
|
+
end_reason TEXT,
|
|
190
|
+
end_notified_at TEXT,
|
|
191
|
+
wake_json TEXT,
|
|
192
|
+
origin_session_id TEXT
|
|
186
193
|
);
|
|
187
194
|
CREATE INDEX IF NOT EXISTS jobs_status_idx ON jobs(status);
|
|
188
195
|
`;
|
|
@@ -203,26 +210,7 @@ CREATE INDEX IF NOT EXISTS jobs_status_idx ON jobs(status);
|
|
|
203
210
|
* routed through the Batch API (status "submitted")
|
|
204
211
|
*/
|
|
205
212
|
function ensureColumns(db) {
|
|
206
|
-
const
|
|
207
|
-
.prepare(`SELECT name FROM pragma_table_info('tasks')`)
|
|
208
|
-
.all();
|
|
209
|
-
const have = new Set(rows.map((r) => r.name));
|
|
210
|
-
/** Returns true iff THIS call added the column. */
|
|
211
|
-
const addColumn = (name, type) => {
|
|
212
|
-
if (have.has(name))
|
|
213
|
-
return false;
|
|
214
|
-
try {
|
|
215
|
-
db.exec(`ALTER TABLE tasks ADD COLUMN ${name} ${type}`);
|
|
216
|
-
return true;
|
|
217
|
-
}
|
|
218
|
-
catch (err) {
|
|
219
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
220
|
-
// Another process migrated between our pragma check and the ALTER.
|
|
221
|
-
if (!/duplicate column name/i.test(msg))
|
|
222
|
-
throw err;
|
|
223
|
-
return false;
|
|
224
|
-
}
|
|
225
|
-
};
|
|
213
|
+
const addColumn = columnAdder(db, "tasks");
|
|
226
214
|
addColumn("body_json", "TEXT");
|
|
227
215
|
addColumn("estimated_carbon_g", "REAL");
|
|
228
216
|
addColumn("deadline", "TEXT");
|
|
@@ -257,6 +245,40 @@ function ensureColumns(db) {
|
|
|
257
245
|
addColumn("job_id", "TEXT");
|
|
258
246
|
db.exec(`CREATE INDEX IF NOT EXISTS tasks_job_idx ON tasks(job_id)`);
|
|
259
247
|
}
|
|
248
|
+
/**
|
|
249
|
+
* The `addColumn(name, type)` of one table's migrations: adds the column
|
|
250
|
+
* when the table lacks it, and returns true iff THIS call added it.
|
|
251
|
+
*/
|
|
252
|
+
function columnAdder(db, table) {
|
|
253
|
+
const rows = db.prepare(`SELECT name FROM pragma_table_info('${table}')`).all();
|
|
254
|
+
const have = new Set(rows.map((r) => r.name));
|
|
255
|
+
return (name, type) => {
|
|
256
|
+
if (have.has(name))
|
|
257
|
+
return false;
|
|
258
|
+
try {
|
|
259
|
+
db.exec(`ALTER TABLE ${table} ADD COLUMN ${name} ${type}`);
|
|
260
|
+
return true;
|
|
261
|
+
}
|
|
262
|
+
catch (err) {
|
|
263
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
264
|
+
// Another process migrated between our pragma check and the ALTER.
|
|
265
|
+
if (!/duplicate column name/i.test(msg))
|
|
266
|
+
throw err;
|
|
267
|
+
return false;
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
/** The `jobs` columns added after the table first shipped: the job lifetime, then the wake binding. */
|
|
272
|
+
function ensureJobColumns(db) {
|
|
273
|
+
const addColumn = columnAdder(db, "jobs");
|
|
274
|
+
addColumn("until", "TEXT");
|
|
275
|
+
addColumn("runs_left", "INTEGER");
|
|
276
|
+
addColumn("ended_at", "TEXT");
|
|
277
|
+
addColumn("end_reason", "TEXT");
|
|
278
|
+
addColumn("end_notified_at", "TEXT");
|
|
279
|
+
addColumn("wake_json", "TEXT");
|
|
280
|
+
addColumn("origin_session_id", "TEXT");
|
|
281
|
+
}
|
|
260
282
|
const REPEAT_RULES = new Set(["none", "daily", "weekly", "quota_reset"]);
|
|
261
283
|
/** Every column of the tasks table, in INSERT order. */
|
|
262
284
|
const INSERT_COLUMNS = [
|
|
@@ -378,15 +400,31 @@ function safeParse(s) {
|
|
|
378
400
|
export const SESSION_NOTICES_SINCE_META_KEY = "session_notices_since";
|
|
379
401
|
/** A finished task stays a session notice for this long. */
|
|
380
402
|
export const SESSION_NOTICE_MAX_AGE_MS = 7 * 86_400_000;
|
|
381
|
-
|
|
403
|
+
const JOB_NOTICE_REASONS = new Set(["failed", "matched", "ended"]);
|
|
404
|
+
/** A `session_notice` event's details as a {@link JobNotice}, or undefined when they are not one. */
|
|
405
|
+
function jobNoticeOf(raw) {
|
|
406
|
+
const d = typeof raw === "string" ? safeParse(raw) : raw;
|
|
407
|
+
if (!d || typeof d !== "object" || Array.isArray(d))
|
|
408
|
+
return undefined;
|
|
409
|
+
const { reasons, wake } = d;
|
|
410
|
+
if (!Array.isArray(reasons))
|
|
411
|
+
return undefined;
|
|
412
|
+
const known = reasons.filter((r) => typeof r === "string" && JOB_NOTICE_REASONS.has(r));
|
|
413
|
+
return known.length > 0 ? { reasons: known, wake: wake === true } : undefined;
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* What a notice needs from a task body: a checked Claude Code origin (or,
|
|
417
|
+
* on a run of a bound job, its `jobWake`) and the result file path.
|
|
418
|
+
*/
|
|
382
419
|
function noticeBody(bodyJson) {
|
|
383
420
|
if (typeof bodyJson !== "string")
|
|
384
421
|
return { checked: false };
|
|
385
422
|
try {
|
|
386
423
|
const body = JSON.parse(bodyJson);
|
|
387
424
|
const resultPath = body?.handoff?.resultPath;
|
|
425
|
+
const jobWake = body?.jobWake;
|
|
388
426
|
return {
|
|
389
|
-
checked: body?.origin?.agent === "claude-code",
|
|
427
|
+
checked: body?.origin?.agent === "claude-code" || (typeof jobWake === "object" && jobWake !== null),
|
|
390
428
|
...(typeof resultPath === "string" && resultPath !== "" ? { resultPath } : {}),
|
|
391
429
|
};
|
|
392
430
|
}
|
|
@@ -442,6 +480,7 @@ export class TaskStore {
|
|
|
442
480
|
}
|
|
443
481
|
this.db.exec(SCHEMA);
|
|
444
482
|
ensureColumns(this.db);
|
|
483
|
+
ensureJobColumns(this.db);
|
|
445
484
|
// The ledger stores prompts (redacted only at terminal transitions)
|
|
446
485
|
// next to a 0600 signing key — keep the DB and its WAL side-files
|
|
447
486
|
// out of reach of other local users. Best-effort: never fail open
|
|
@@ -696,8 +735,10 @@ export class TaskStore {
|
|
|
696
735
|
* that finishes again is a new notice), and finished at or after
|
|
697
736
|
* {@link SESSION_NOTICES_SINCE_META_KEY} and within
|
|
698
737
|
* {@link SESSION_NOTICE_MAX_AGE_MS}. A completed task that asked for a
|
|
699
|
-
* result file waits until its `result_file` event exists. A
|
|
700
|
-
*
|
|
738
|
+
* result file waits until its `result_file` event exists. A run of a job
|
|
739
|
+
* (`job_id` set) is a notice only when the job sweep wrote a
|
|
740
|
+
* `session_notice` event for this finish; its details come back as
|
|
741
|
+
* {@link SessionNotice.jobNotice}. A person's read marker does not matter here.
|
|
701
742
|
*/
|
|
702
743
|
listSessionNotices(opts = {}) {
|
|
703
744
|
const now = opts.now ?? new Date();
|
|
@@ -708,7 +749,11 @@ export class TaskStore {
|
|
|
708
749
|
.prepare(`SELECT t.*,
|
|
709
750
|
(SELECT e.details FROM task_events e
|
|
710
751
|
WHERE e.task_id = t.task_id AND e.kind = 'result_file'
|
|
711
|
-
ORDER BY e.id DESC LIMIT 1) AS notice_result_file
|
|
752
|
+
ORDER BY e.id DESC LIMIT 1) AS notice_result_file,
|
|
753
|
+
(SELECT e.details FROM task_events e
|
|
754
|
+
WHERE e.task_id = t.task_id AND e.kind = 'session_notice'
|
|
755
|
+
AND json_extract(e.details, '$.completed_at') IS t.completed_at
|
|
756
|
+
ORDER BY e.id DESC LIMIT 1) AS notice_job
|
|
712
757
|
FROM tasks t
|
|
713
758
|
WHERE t.status IN ('completed', 'failed', 'cancelled')${bySession}
|
|
714
759
|
AND t.completed_at >= ? AND t.completed_at >= ?
|
|
@@ -726,8 +771,12 @@ export class TaskStore {
|
|
|
726
771
|
const resultFile = fileEvent && typeof fileEvent === "object" && !Array.isArray(fileEvent) ? fileEvent : undefined;
|
|
727
772
|
if (body.resultPath && row.status === "completed" && !resultFile)
|
|
728
773
|
continue;
|
|
774
|
+
const jobNotice = row.job_id != null ? jobNoticeOf(row.notice_job) : undefined;
|
|
775
|
+
if (row.job_id != null && !jobNotice)
|
|
776
|
+
continue;
|
|
729
777
|
out.push({
|
|
730
778
|
record: rowToRecord(row),
|
|
779
|
+
...(jobNotice ? { jobNotice } : {}),
|
|
731
780
|
...(body.resultPath ? { resultPath: body.resultPath } : {}),
|
|
732
781
|
...(resultFile ? { resultFile } : {}),
|
|
733
782
|
});
|
|
@@ -756,6 +805,37 @@ export class TaskStore {
|
|
|
756
805
|
return Number(res.changes) === 1;
|
|
757
806
|
});
|
|
758
807
|
}
|
|
808
|
+
/**
|
|
809
|
+
* Record the job sweep's decision on a run of a bound job: a
|
|
810
|
+
* `session_notice` event (actor `tick`) whose details carry the run's
|
|
811
|
+
* `completed_at`, written only when the run has none for this finish.
|
|
812
|
+
* Returns true iff this call wrote it.
|
|
813
|
+
*/
|
|
814
|
+
recordSessionNotice(taskId, notice) {
|
|
815
|
+
return this.tx(() => {
|
|
816
|
+
const res = this.db
|
|
817
|
+
.prepare(`INSERT INTO task_events (task_id, at, kind, actor, details)
|
|
818
|
+
SELECT t.task_id, ?, 'session_notice', 'tick', json_set(?, '$.completed_at', t.completed_at)
|
|
819
|
+
FROM tasks t
|
|
820
|
+
WHERE t.task_id = ? AND t.completed_at IS NOT NULL
|
|
821
|
+
AND NOT EXISTS (SELECT 1 FROM task_events n
|
|
822
|
+
WHERE n.task_id = t.task_id AND n.kind = 'session_notice'
|
|
823
|
+
AND json_extract(n.details, '$.completed_at') IS t.completed_at)`)
|
|
824
|
+
.run(new Date().toISOString(), JSON.stringify({ reasons: notice.reasons, wake: notice.wake }), taskId);
|
|
825
|
+
return Number(res.changes) === 1;
|
|
826
|
+
});
|
|
827
|
+
}
|
|
828
|
+
/** The job sweep's decision on a run's current finish, or undefined when it wrote none. */
|
|
829
|
+
sessionNoticeOf(record) {
|
|
830
|
+
if (!record.completedAt)
|
|
831
|
+
return undefined;
|
|
832
|
+
const row = this.db
|
|
833
|
+
.prepare(`SELECT details FROM task_events
|
|
834
|
+
WHERE task_id = ? AND kind = 'session_notice' AND json_extract(details, '$.completed_at') = ?
|
|
835
|
+
ORDER BY id DESC LIMIT 1`)
|
|
836
|
+
.get(record.taskId, record.completedAt);
|
|
837
|
+
return row ? jobNoticeOf(row.details) : undefined;
|
|
838
|
+
}
|
|
759
839
|
/**
|
|
760
840
|
* Completed tasks that asked for a result file (`handoff.resultPath` in
|
|
761
841
|
* the body) and have no `result_file` event yet, oldest first, whichever
|
|
@@ -1153,10 +1233,12 @@ const JOB_COLUMNS = [
|
|
|
1153
1233
|
"time_zone", "runner", "template_json", "caps_json", "notify", "origin_host", "origin_cwd", "created_by",
|
|
1154
1234
|
"created_at", "updated_at", "revision", "next_seq", "pending_task_id", "last_task_id", "last_run_started_at",
|
|
1155
1235
|
"last_outcome", "consecutive_failures", "retry_used", "pause_reason", "paused_at", "pause_notified_at",
|
|
1236
|
+
"until", "runs_left", "ended_at", "end_reason", "end_notified_at", "wake_json", "origin_session_id",
|
|
1156
1237
|
];
|
|
1157
1238
|
/** Columns `updateJobIf` writes: everything except the identity and the revision. */
|
|
1158
1239
|
const JOB_MUTABLE_COLUMNS = JOB_COLUMNS.filter((c) => !["job_id", "created_at", "created_by", "origin_host", "origin_cwd", "revision"].includes(c));
|
|
1159
|
-
const JOB_STATUSES = new Set(["active", "paused", "removed"]);
|
|
1240
|
+
const JOB_STATUSES = new Set(["active", "paused", "removed", "ended"]);
|
|
1241
|
+
const JOB_END_REASONS = new Set(["until", "count"]);
|
|
1160
1242
|
const JOB_NOTIFY = new Set(["every_run", "failures", "summary"]);
|
|
1161
1243
|
const JOB_OUTCOMES = new Set(["ok", "failed", "skipped"]);
|
|
1162
1244
|
function jobParams(job) {
|
|
@@ -1191,8 +1273,27 @@ function jobParams(job) {
|
|
|
1191
1273
|
pause_reason: job.pauseReason ?? null,
|
|
1192
1274
|
paused_at: job.pausedAt ?? null,
|
|
1193
1275
|
pause_notified_at: job.pauseNotifiedAt ?? null,
|
|
1276
|
+
until: job.until ?? null,
|
|
1277
|
+
runs_left: job.runsLeft ?? null,
|
|
1278
|
+
ended_at: job.endedAt ?? null,
|
|
1279
|
+
end_reason: job.endReason ?? null,
|
|
1280
|
+
end_notified_at: job.endNotifiedAt ?? null,
|
|
1281
|
+
wake_json: job.wake ? JSON.stringify(job.wake) : null,
|
|
1282
|
+
origin_session_id: job.originSessionId ?? null,
|
|
1194
1283
|
};
|
|
1195
1284
|
}
|
|
1285
|
+
/** A job row's wake rule and session, both or neither: a rule that does not parse binds nothing. */
|
|
1286
|
+
function wakeBinding(row) {
|
|
1287
|
+
const w = safeParse(row.wake_json);
|
|
1288
|
+
const session = row.origin_session_id;
|
|
1289
|
+
if (!w || typeof w !== "object" || typeof session !== "string" || session === "" || typeof w.boundAt !== "string")
|
|
1290
|
+
return {};
|
|
1291
|
+
if (w.on === "failures")
|
|
1292
|
+
return { wake: { on: "failures", boundAt: w.boundAt }, originSessionId: session };
|
|
1293
|
+
if (w.on === "match" && typeof w.pattern === "string")
|
|
1294
|
+
return { wake: { on: "match", pattern: w.pattern, boundAt: w.boundAt }, originSessionId: session };
|
|
1295
|
+
return {};
|
|
1296
|
+
}
|
|
1196
1297
|
/** The template stored for a job, or undefined when it is not a template object. */
|
|
1197
1298
|
function parseTemplate(raw, runner) {
|
|
1198
1299
|
const t = safeParse(raw);
|
|
@@ -1269,8 +1370,14 @@ function rowToJob(row) {
|
|
|
1269
1370
|
pauseReason: str(row.pause_reason),
|
|
1270
1371
|
pausedAt: str(row.paused_at),
|
|
1271
1372
|
pauseNotifiedAt: str(row.pause_notified_at),
|
|
1373
|
+
until: str(row.until),
|
|
1374
|
+
runsLeft: row.runs_left === null || row.runs_left === undefined ? undefined : Number(row.runs_left),
|
|
1375
|
+
endedAt: str(row.ended_at),
|
|
1376
|
+
endReason: JOB_END_REASONS.has(row.end_reason) ? row.end_reason : undefined,
|
|
1377
|
+
endNotifiedAt: str(row.end_notified_at),
|
|
1378
|
+
...wakeBinding(row),
|
|
1272
1379
|
};
|
|
1273
|
-
if ((!template || !cadence) && job.status !== "removed") {
|
|
1380
|
+
if ((!template || !cadence) && job.status !== "removed" && job.status !== "ended") {
|
|
1274
1381
|
job.status = "paused";
|
|
1275
1382
|
job.pauseReason = "corrupt template";
|
|
1276
1383
|
}
|
package/dist/task-events.d.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* `failed`, `attempt_failed` and `cancelled` rows with the same shape.
|
|
6
6
|
*/
|
|
7
7
|
import type { TaskRecord } from "./types.js";
|
|
8
|
-
export declare const TASK_EVENT_KINDS: readonly ["created", "rescheduled", "postponed", "expedited", "cancelled", "dispatched", "completed", "failed", "attempt_failed", "deferred", "replied", "notified", "result_file", "progress"];
|
|
8
|
+
export declare const TASK_EVENT_KINDS: readonly ["created", "rescheduled", "postponed", "expedited", "cancelled", "dispatched", "completed", "failed", "attempt_failed", "deferred", "replied", "notified", "result_file", "session_notice", "progress"];
|
|
9
9
|
export type TaskEventKind = (typeof TASK_EVENT_KINDS)[number];
|
|
10
10
|
/**
|
|
11
11
|
* Who made the change: `agent:<host>`, `page`, `client:<name>`, `cli`,
|
package/dist/task-events.js
CHANGED
|
@@ -29,6 +29,10 @@ export const TASK_EVENT_KINDS = [
|
|
|
29
29
|
// The tick wrote the task's result file, or could not (`written: false`
|
|
30
30
|
// with the error). At most one per task.
|
|
31
31
|
"result_file",
|
|
32
|
+
// The job sweep decided that a run of a job bound to a session is a
|
|
33
|
+
// session notice: `reasons` (failed, matched, ended) and `wake`. At most one
|
|
34
|
+
// per finish: details carry the run's `completed_at`. Node core only.
|
|
35
|
+
"session_notice",
|
|
32
36
|
// A line a long `command` run printed while it ran (`line`, `seq`), within
|
|
33
37
|
// the caps of `createProgressRecorder`.
|
|
34
38
|
"progress",
|
|
@@ -183,6 +187,11 @@ export function eventSummary(e) {
|
|
|
183
187
|
case "result_file":
|
|
184
188
|
parts.push(d.written === true ? `written ${short(d.path)}` : `not written: ${short(d.error)}`);
|
|
185
189
|
break;
|
|
190
|
+
case "session_notice":
|
|
191
|
+
if (Array.isArray(d.reasons))
|
|
192
|
+
parts.push(d.reasons.filter((r) => typeof r === "string").join(", "));
|
|
193
|
+
parts.push(d.wake === true ? "wakes the session" : "no wake");
|
|
194
|
+
break;
|
|
186
195
|
case "progress":
|
|
187
196
|
if (typeof d.line === "string")
|
|
188
197
|
parts.push(d.line);
|
package/dist/tool-surface.js
CHANGED
|
@@ -323,7 +323,14 @@ export const TOOL_SURFACE = [
|
|
|
323
323
|
kind: "boolean",
|
|
324
324
|
optional: true,
|
|
325
325
|
hosts: ["mcp"],
|
|
326
|
-
description: "true wakes this Claude Code session when the task finishes, if it sits idle, within 12 hours after its last turn ended: the session starts a turn by itself with the notice. A wake spends a model turn while nobody may be watching, so set it only when the user wants the result acted on at once. Rejected outside a Claude Code session, and when this server's ledger is not the default ~/.tidegap/queue.db (TIDEGAP_DB_PATH set elsewhere): the plugin's hooks read only that one. Omit (default false) to get the notice with the next prompt.",
|
|
326
|
+
description: "true wakes this Claude Code session when the task finishes, if it sits idle, within 12 hours after its last turn ended: the session starts a turn by itself with the notice. A wake spends a model turn while nobody may be watching, so set it only when the user wants the result acted on at once. Rejected outside a Claude Code session, and when this server's ledger is not the default ~/.tidegap/queue.db (TIDEGAP_DB_PATH set elsewhere): the plugin's hooks read only that one. Omit (default false) to get the notice with the next prompt. With a job repeat, true binds the job to this session and wakes it on a run that failed for good (after its retries); only those runs and the job's end reach the session.",
|
|
327
|
+
},
|
|
328
|
+
{
|
|
329
|
+
name: "wake_match",
|
|
330
|
+
kind: "string",
|
|
331
|
+
optional: true,
|
|
332
|
+
hosts: ["mcp"],
|
|
333
|
+
description: "With a job repeat only: a JavaScript regular expression, e.g. '^ALERT' (flag m, so ^ and $ match at each line; at most 200 characters; one that matches an empty output is rejected). A run whose output matches wakes this session; a run that failed for good comes with the next prompt; other runs never reach the session. Tidegap tests the pattern after the run: the notice names the run id, its status and 'matched', never the output. Omit wake_session or set it true.",
|
|
327
334
|
},
|
|
328
335
|
{
|
|
329
336
|
name: "dry_run",
|
|
@@ -421,6 +428,23 @@ export const TOOL_SURFACE = [
|
|
|
421
428
|
optional: true,
|
|
422
429
|
description: "IANA zone that window and days are read in, e.g. 'Europe/Berlin'; take it from the user's location. Defaults to the host's system zone. Only with a job repeat.",
|
|
423
430
|
},
|
|
431
|
+
{
|
|
432
|
+
name: "until",
|
|
433
|
+
kind: "string",
|
|
434
|
+
optional: true,
|
|
435
|
+
hosts: ["mcp"],
|
|
436
|
+
description: "When a job ends: a day 'YYYY-MM-DD' (the last local day in time_zone a run may start, e.g. '2026-11-17' for \"for 5 days\") or an ISO instant with Z or an offset (a run must start before it). The job then ends by itself and sends one final notice. Only with a job repeat; omit for a job that runs until it is removed.",
|
|
437
|
+
},
|
|
438
|
+
{
|
|
439
|
+
name: "count",
|
|
440
|
+
kind: "number",
|
|
441
|
+
integer: true,
|
|
442
|
+
min: 1,
|
|
443
|
+
max: 1000,
|
|
444
|
+
optional: true,
|
|
445
|
+
hosts: ["mcp"],
|
|
446
|
+
description: "How many runs a job makes before it ends by itself, 1 to 1000, e.g. 5 for \"five times\". A retry is part of its run; a skipped run does not count. Only with a job repeat; with until too, the job ends at whichever comes first. Omit for a job that runs until it is removed.",
|
|
447
|
+
},
|
|
424
448
|
{
|
|
425
449
|
name: "llm_timeout",
|
|
426
450
|
kind: "string",
|
package/dist/types.d.ts
CHANGED
|
@@ -469,6 +469,14 @@ export interface ProviderCallSpec {
|
|
|
469
469
|
provider: ProviderName;
|
|
470
470
|
model?: string;
|
|
471
471
|
};
|
|
472
|
+
/**
|
|
473
|
+
* On a run of a job bound to a session: its wake rule and the session.
|
|
474
|
+
* Never `origin`, the adapter's fork input: a job run never forks a session.
|
|
475
|
+
*/
|
|
476
|
+
jobWake?: {
|
|
477
|
+
on: "failures" | "match";
|
|
478
|
+
session: string;
|
|
479
|
+
};
|
|
472
480
|
/**
|
|
473
481
|
* Per-run caps: a job occurrence's, or the time limits a one-off task
|
|
474
482
|
* was queued with (only the keys the caller set, with `capsVersion`).
|
|
@@ -703,7 +711,23 @@ export interface JobCaps {
|
|
|
703
711
|
export declare const DEFAULT_JOB_CAPS: Readonly<JobCaps>;
|
|
704
712
|
/** Which runs of a job notify: every run, failures only, or the digest only. */
|
|
705
713
|
export type JobNotify = "every_run" | "failures" | "summary";
|
|
706
|
-
|
|
714
|
+
/** `ended`: the job reached its end date or ran its runs; it keeps its history and only `remove` applies. */
|
|
715
|
+
export type JobStatus = "active" | "paused" | "removed" | "ended";
|
|
716
|
+
/** Why a job ended: its `until` bound passed, or its runs are done. */
|
|
717
|
+
export type JobEndReason = "until" | "count";
|
|
718
|
+
/**
|
|
719
|
+
* The wake rule of a job bound to a Claude Code session: wake it on a run
|
|
720
|
+
* whose slot failed for good (`failures`), or on a completed run whose
|
|
721
|
+
* result text matches `pattern` (`match`; a JavaScript regular expression
|
|
722
|
+
* with the `m` flag). `boundAt` is when the session bound the job.
|
|
723
|
+
*/
|
|
724
|
+
export interface JobWake {
|
|
725
|
+
on: "failures" | "match";
|
|
726
|
+
pattern?: string;
|
|
727
|
+
boundAt: string;
|
|
728
|
+
}
|
|
729
|
+
/** Why a run of a bound job is a session notice. */
|
|
730
|
+
export type JobNoticeReason = "failed" | "matched" | "ended";
|
|
707
731
|
/** Outcome of a job's last finished occurrence. */
|
|
708
732
|
export type JobOutcome = "ok" | "failed" | "skipped";
|
|
709
733
|
/** One row of the `jobs` table. */
|
|
@@ -741,6 +765,22 @@ export interface JobRecord {
|
|
|
741
765
|
pauseReason?: string;
|
|
742
766
|
pausedAt?: string;
|
|
743
767
|
pauseNotifiedAt?: string;
|
|
768
|
+
/**
|
|
769
|
+
* The end date as given: `YYYY-MM-DD` (the last local day in the job's
|
|
770
|
+
* zone on which a slot may start) or an ISO instant (a slot must start
|
|
771
|
+
* before it).
|
|
772
|
+
*/
|
|
773
|
+
until?: string;
|
|
774
|
+
/** Runs left before the job ends; a slot that ends for good takes one off. */
|
|
775
|
+
runsLeft?: number;
|
|
776
|
+
endedAt?: string;
|
|
777
|
+
endReason?: JobEndReason;
|
|
778
|
+
/** When the final notice of an ended job was claimed. */
|
|
779
|
+
endNotifiedAt?: string;
|
|
780
|
+
/** The wake rule; the job is bound only when this and {@link originSessionId} are both set. */
|
|
781
|
+
wake?: JobWake;
|
|
782
|
+
/** The Claude Code session the job wakes. */
|
|
783
|
+
originSessionId?: string;
|
|
744
784
|
}
|
|
745
785
|
/** Next occurrence of a job: run no earlier than `earliest`, finish by `deadline`. */
|
|
746
786
|
export interface Occurrence {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tidegap/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.23.0",
|
|
4
4
|
"description": "Carbon-aware scheduling for agentic AI workflows — core TypeScript library.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Vitalii Borovyk",
|
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
"@anthropic-ai/sdk": "^0.137.0",
|
|
56
56
|
"@types/better-sqlite3": "^7.6.13",
|
|
57
57
|
"@types/node": "^22.20.5",
|
|
58
|
-
"openai": "^7.
|
|
58
|
+
"openai": "^7.57.0",
|
|
59
59
|
"typescript": "^5.6.3",
|
|
60
60
|
"vitest": "^4.1.12"
|
|
61
61
|
},
|