@tidegap/core 0.20.0 → 0.22.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.js +4 -4
- package/dist/channels/format.d.ts +30 -4
- package/dist/channels/format.js +125 -22
- package/dist/channels/payload.js +8 -6
- package/dist/channels/plan.js +3 -2
- package/dist/channels/types.d.ts +17 -1
- package/dist/energy.d.ts +7 -0
- package/dist/energy.js +7 -0
- package/dist/grid.d.ts +10 -2
- package/dist/grid.js +14 -5
- package/dist/handoff.d.ts +88 -6
- package/dist/handoff.js +177 -20
- package/dist/history.d.ts +19 -0
- package/dist/history.js +24 -1
- package/dist/index.d.ts +24 -18
- package/dist/index.js +16 -12
- 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 +74 -17
- package/dist/jobs.js +420 -75
- package/dist/notify.d.ts +9 -0
- package/dist/notify.js +17 -3
- package/dist/providers/anthropic.js +8 -6
- package/dist/providers/base.d.ts +47 -9
- package/dist/providers/base.js +29 -4
- package/dist/providers/gemini.d.ts +3 -0
- package/dist/providers/gemini.js +9 -6
- package/dist/providers/http.d.ts +40 -0
- package/dist/providers/http.js +82 -0
- package/dist/providers/index.d.ts +1 -1
- package/dist/providers/index.js +1 -1
- package/dist/providers/ollama.d.ts +3 -0
- package/dist/providers/ollama.js +8 -5
- package/dist/providers/openai.js +7 -5
- package/dist/providers/timeout.d.ts +26 -8
- package/dist/providers/timeout.js +53 -15
- package/dist/readiness.d.ts +39 -3
- package/dist/readiness.js +73 -1
- package/dist/run-limits.d.ts +268 -0
- package/dist/run-limits.js +572 -0
- package/dist/schedule-job.d.ts +41 -2
- package/dist/schedule-job.js +70 -2
- package/dist/scheduler.d.ts +161 -17
- package/dist/scheduler.js +485 -128
- package/dist/storage/sqlite.d.ts +52 -5
- package/dist/storage/sqlite.js +200 -33
- package/dist/task-events.d.ts +19 -4
- package/dist/task-events.js +51 -5
- package/dist/tool-surface.js +62 -7
- package/dist/types.d.ts +72 -11
- package/dist/types.js +1 -3
- package/package.json +5 -2
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. */
|
|
@@ -147,8 +157,27 @@ export declare class TaskStore {
|
|
|
147
157
|
* transaction, and only when the update hit.
|
|
148
158
|
*/
|
|
149
159
|
transitionIf(record: TaskRecord<unknown>, expectedStatuses: readonly TaskStatus[], unchangedSince?: TaskRecord<unknown>, event?: TaskEventInput): boolean;
|
|
150
|
-
/**
|
|
151
|
-
|
|
160
|
+
/**
|
|
161
|
+
* Append one event to a task's log in its own transaction. `busyMs` bounds
|
|
162
|
+
* the wait for another writer's lock for this write only (a progress line
|
|
163
|
+
* of a running command must not hold the tick for seconds): past it the
|
|
164
|
+
* write throws SQLITE_BUSY. The connection's own busy timeout is restored
|
|
165
|
+
* in `finally`, so no other write gets the short wait. It only shortens
|
|
166
|
+
* the wait: a connection whose own timeout is already shorter (or cannot
|
|
167
|
+
* be read) keeps it.
|
|
168
|
+
*/
|
|
169
|
+
recordEvent(taskId: string, event: TaskEventInput, opts?: {
|
|
170
|
+
busyMs?: number;
|
|
171
|
+
}): void;
|
|
172
|
+
/** How many events of `kind` a task has: one `COUNT(*)`, no rows read. */
|
|
173
|
+
countTaskEvents(taskId: string, kind: TaskEventKind): number;
|
|
174
|
+
/**
|
|
175
|
+
* Merge `details` into the newest `kind` event of a task: a fact learned
|
|
176
|
+
* after another writer recorded the event (the tick that stopped a
|
|
177
|
+
* cancelled run adds `stopped_run`). Returns false when the task has no
|
|
178
|
+
* such event.
|
|
179
|
+
*/
|
|
180
|
+
annotateEvent(taskId: string, kind: TaskEventKind, details: Record<string, unknown>): boolean;
|
|
152
181
|
/**
|
|
153
182
|
* A task's events, oldest first. `limit` keeps the newest `limit` rows.
|
|
154
183
|
* Rows with an unknown kind (a newer writer) are skipped.
|
|
@@ -175,8 +204,10 @@ export declare class TaskStore {
|
|
|
175
204
|
* that finishes again is a new notice), and finished at or after
|
|
176
205
|
* {@link SESSION_NOTICES_SINCE_META_KEY} and within
|
|
177
206
|
* {@link SESSION_NOTICE_MAX_AGE_MS}. A completed task that asked for a
|
|
178
|
-
* result file waits until its `result_file` event exists. A
|
|
179
|
-
*
|
|
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.
|
|
180
211
|
*/
|
|
181
212
|
listSessionNotices(opts?: {
|
|
182
213
|
sessionId?: string;
|
|
@@ -194,6 +225,15 @@ export declare class TaskStore {
|
|
|
194
225
|
via: string;
|
|
195
226
|
session_id: string;
|
|
196
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;
|
|
197
237
|
/**
|
|
198
238
|
* Completed tasks that asked for a result file (`handoff.resultPath` in
|
|
199
239
|
* the body) and have no `result_file` event yet, oldest first, whichever
|
|
@@ -255,6 +295,13 @@ export declare class TaskStore {
|
|
|
255
295
|
setMeta(key: string, value: string): void;
|
|
256
296
|
/** Remove one meta value; a missing key is a no-op. */
|
|
257
297
|
deleteMeta(key: string): void;
|
|
298
|
+
/**
|
|
299
|
+
* Compare-and-set one meta value across processes: write `next` (delete
|
|
300
|
+
* the key when `next` is undefined) only while the stored value is still
|
|
301
|
+
* `expected` (undefined: the key is absent). Returns whether it wrote. Two
|
|
302
|
+
* processes that read the same value cannot both win.
|
|
303
|
+
*/
|
|
304
|
+
setMetaIf(key: string, expected: string | undefined, next: string | undefined): boolean;
|
|
258
305
|
/** Every channel row, oldest first; a row with an unknown kind or bad JSON is skipped. */
|
|
259
306
|
listChannels(): Channel[];
|
|
260
307
|
/** Insert or replace a channel row (pairing the same chat again replaces it). */
|
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
|
|
@@ -591,9 +630,47 @@ export class TaskStore {
|
|
|
591
630
|
return hit;
|
|
592
631
|
});
|
|
593
632
|
}
|
|
594
|
-
/**
|
|
595
|
-
|
|
596
|
-
|
|
633
|
+
/**
|
|
634
|
+
* Append one event to a task's log in its own transaction. `busyMs` bounds
|
|
635
|
+
* the wait for another writer's lock for this write only (a progress line
|
|
636
|
+
* of a running command must not hold the tick for seconds): past it the
|
|
637
|
+
* write throws SQLITE_BUSY. The connection's own busy timeout is restored
|
|
638
|
+
* in `finally`, so no other write gets the short wait. It only shortens
|
|
639
|
+
* the wait: a connection whose own timeout is already shorter (or cannot
|
|
640
|
+
* be read) keeps it.
|
|
641
|
+
*/
|
|
642
|
+
recordEvent(taskId, event, opts = {}) {
|
|
643
|
+
const bound = opts.busyMs === undefined || this.txDepth > 0 ? undefined : Math.max(0, Math.floor(opts.busyMs));
|
|
644
|
+
const own = bound === undefined ? NaN : Number(this.db.prepare("PRAGMA busy_timeout").get()?.["timeout"]);
|
|
645
|
+
if (bound === undefined || !Number.isFinite(own) || own <= bound) {
|
|
646
|
+
this.tx(() => this.insertEvent(taskId, event));
|
|
647
|
+
return;
|
|
648
|
+
}
|
|
649
|
+
this.db.exec(`PRAGMA busy_timeout = ${bound}`);
|
|
650
|
+
try {
|
|
651
|
+
this.tx(() => this.insertEvent(taskId, event));
|
|
652
|
+
}
|
|
653
|
+
finally {
|
|
654
|
+
this.db.exec(`PRAGMA busy_timeout = ${own}`);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
/** How many events of `kind` a task has: one `COUNT(*)`, no rows read. */
|
|
658
|
+
countTaskEvents(taskId, kind) {
|
|
659
|
+
const row = this.db.prepare("SELECT COUNT(*) AS n FROM task_events WHERE task_id = ? AND kind = ?").get(taskId, kind);
|
|
660
|
+
return Number(row?.["n"] ?? 0);
|
|
661
|
+
}
|
|
662
|
+
/**
|
|
663
|
+
* Merge `details` into the newest `kind` event of a task: a fact learned
|
|
664
|
+
* after another writer recorded the event (the tick that stopped a
|
|
665
|
+
* cancelled run adds `stopped_run`). Returns false when the task has no
|
|
666
|
+
* such event.
|
|
667
|
+
*/
|
|
668
|
+
annotateEvent(taskId, kind, details) {
|
|
669
|
+
const res = this.db
|
|
670
|
+
.prepare(`UPDATE task_events SET details = json_patch(details, ?)
|
|
671
|
+
WHERE id = (SELECT id FROM task_events WHERE task_id = ? AND kind = ? ORDER BY id DESC LIMIT 1)`)
|
|
672
|
+
.run(safeStringify(details) ?? "{}", taskId, kind);
|
|
673
|
+
return Number(res.changes) === 1;
|
|
597
674
|
}
|
|
598
675
|
/**
|
|
599
676
|
* A task's events, oldest first. `limit` keeps the newest `limit` rows.
|
|
@@ -658,8 +735,10 @@ export class TaskStore {
|
|
|
658
735
|
* that finishes again is a new notice), and finished at or after
|
|
659
736
|
* {@link SESSION_NOTICES_SINCE_META_KEY} and within
|
|
660
737
|
* {@link SESSION_NOTICE_MAX_AGE_MS}. A completed task that asked for a
|
|
661
|
-
* result file waits until its `result_file` event exists. A
|
|
662
|
-
*
|
|
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.
|
|
663
742
|
*/
|
|
664
743
|
listSessionNotices(opts = {}) {
|
|
665
744
|
const now = opts.now ?? new Date();
|
|
@@ -670,7 +749,11 @@ export class TaskStore {
|
|
|
670
749
|
.prepare(`SELECT t.*,
|
|
671
750
|
(SELECT e.details FROM task_events e
|
|
672
751
|
WHERE e.task_id = t.task_id AND e.kind = 'result_file'
|
|
673
|
-
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
|
|
674
757
|
FROM tasks t
|
|
675
758
|
WHERE t.status IN ('completed', 'failed', 'cancelled')${bySession}
|
|
676
759
|
AND t.completed_at >= ? AND t.completed_at >= ?
|
|
@@ -688,8 +771,12 @@ export class TaskStore {
|
|
|
688
771
|
const resultFile = fileEvent && typeof fileEvent === "object" && !Array.isArray(fileEvent) ? fileEvent : undefined;
|
|
689
772
|
if (body.resultPath && row.status === "completed" && !resultFile)
|
|
690
773
|
continue;
|
|
774
|
+
const jobNotice = row.job_id != null ? jobNoticeOf(row.notice_job) : undefined;
|
|
775
|
+
if (row.job_id != null && !jobNotice)
|
|
776
|
+
continue;
|
|
691
777
|
out.push({
|
|
692
778
|
record: rowToRecord(row),
|
|
779
|
+
...(jobNotice ? { jobNotice } : {}),
|
|
693
780
|
...(body.resultPath ? { resultPath: body.resultPath } : {}),
|
|
694
781
|
...(resultFile ? { resultFile } : {}),
|
|
695
782
|
});
|
|
@@ -718,6 +805,37 @@ export class TaskStore {
|
|
|
718
805
|
return Number(res.changes) === 1;
|
|
719
806
|
});
|
|
720
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
|
+
}
|
|
721
839
|
/**
|
|
722
840
|
* Completed tasks that asked for a result file (`handoff.resultPath` in
|
|
723
841
|
* the body) and have no `result_file` event yet, oldest first, whichever
|
|
@@ -930,6 +1048,23 @@ export class TaskStore {
|
|
|
930
1048
|
deleteMeta(key) {
|
|
931
1049
|
this.db.prepare(`DELETE FROM meta WHERE key = ?`).run(key);
|
|
932
1050
|
}
|
|
1051
|
+
/**
|
|
1052
|
+
* Compare-and-set one meta value across processes: write `next` (delete
|
|
1053
|
+
* the key when `next` is undefined) only while the stored value is still
|
|
1054
|
+
* `expected` (undefined: the key is absent). Returns whether it wrote. Two
|
|
1055
|
+
* processes that read the same value cannot both win.
|
|
1056
|
+
*/
|
|
1057
|
+
setMetaIf(key, expected, next) {
|
|
1058
|
+
return this.tx(() => {
|
|
1059
|
+
if (this.getMeta(key) !== expected)
|
|
1060
|
+
return false;
|
|
1061
|
+
if (next === undefined)
|
|
1062
|
+
this.deleteMeta(key);
|
|
1063
|
+
else
|
|
1064
|
+
this.setMeta(key, next);
|
|
1065
|
+
return true;
|
|
1066
|
+
});
|
|
1067
|
+
}
|
|
933
1068
|
/** Every channel row, oldest first; a row with an unknown kind or bad JSON is skipped. */
|
|
934
1069
|
listChannels() {
|
|
935
1070
|
const rows = this.db.prepare(`SELECT * FROM channels ORDER BY created_at, id`).all();
|
|
@@ -1098,10 +1233,12 @@ const JOB_COLUMNS = [
|
|
|
1098
1233
|
"time_zone", "runner", "template_json", "caps_json", "notify", "origin_host", "origin_cwd", "created_by",
|
|
1099
1234
|
"created_at", "updated_at", "revision", "next_seq", "pending_task_id", "last_task_id", "last_run_started_at",
|
|
1100
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",
|
|
1101
1237
|
];
|
|
1102
1238
|
/** Columns `updateJobIf` writes: everything except the identity and the revision. */
|
|
1103
1239
|
const JOB_MUTABLE_COLUMNS = JOB_COLUMNS.filter((c) => !["job_id", "created_at", "created_by", "origin_host", "origin_cwd", "revision"].includes(c));
|
|
1104
|
-
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"]);
|
|
1105
1242
|
const JOB_NOTIFY = new Set(["every_run", "failures", "summary"]);
|
|
1106
1243
|
const JOB_OUTCOMES = new Set(["ok", "failed", "skipped"]);
|
|
1107
1244
|
function jobParams(job) {
|
|
@@ -1132,12 +1269,31 @@ function jobParams(job) {
|
|
|
1132
1269
|
last_run_started_at: job.lastRunStartedAt ?? null,
|
|
1133
1270
|
last_outcome: job.lastOutcome ?? null,
|
|
1134
1271
|
consecutive_failures: job.consecutiveFailures,
|
|
1135
|
-
retry_used: job.retryUsed
|
|
1272
|
+
retry_used: job.retryUsed,
|
|
1136
1273
|
pause_reason: job.pauseReason ?? null,
|
|
1137
1274
|
paused_at: job.pausedAt ?? null,
|
|
1138
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,
|
|
1139
1283
|
};
|
|
1140
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
|
+
}
|
|
1141
1297
|
/** The template stored for a job, or undefined when it is not a template object. */
|
|
1142
1298
|
function parseTemplate(raw, runner) {
|
|
1143
1299
|
const t = safeParse(raw);
|
|
@@ -1168,6 +1324,11 @@ function rowToCadence(row) {
|
|
|
1168
1324
|
return undefined;
|
|
1169
1325
|
}
|
|
1170
1326
|
}
|
|
1327
|
+
/** The `retry_used` column as a count: a row from before held 0 or 1 (true), which reads as that many retries. */
|
|
1328
|
+
function retryCount(raw) {
|
|
1329
|
+
const n = Number(raw ?? 0);
|
|
1330
|
+
return Number.isInteger(n) && n > 0 ? n : 0;
|
|
1331
|
+
}
|
|
1171
1332
|
/**
|
|
1172
1333
|
* A job row as a record. A row whose template (or cadence) does not parse
|
|
1173
1334
|
* reads as `paused` with reason `corrupt template` instead of throwing, so
|
|
@@ -1205,12 +1366,18 @@ function rowToJob(row) {
|
|
|
1205
1366
|
lastRunStartedAt: str(row.last_run_started_at),
|
|
1206
1367
|
lastOutcome: JOB_OUTCOMES.has(row.last_outcome) ? row.last_outcome : undefined,
|
|
1207
1368
|
consecutiveFailures: Number(row.consecutive_failures ?? 0),
|
|
1208
|
-
retryUsed:
|
|
1369
|
+
retryUsed: retryCount(row.retry_used),
|
|
1209
1370
|
pauseReason: str(row.pause_reason),
|
|
1210
1371
|
pausedAt: str(row.paused_at),
|
|
1211
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),
|
|
1212
1379
|
};
|
|
1213
|
-
if ((!template || !cadence) && job.status !== "removed") {
|
|
1380
|
+
if ((!template || !cadence) && job.status !== "removed" && job.status !== "ended") {
|
|
1214
1381
|
job.status = "paused";
|
|
1215
1382
|
job.pauseReason = "corrupt template";
|
|
1216
1383
|
}
|
package/dist/task-events.d.ts
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
* Task events (audit trail): one row per change of a task, in the ledger's
|
|
3
3
|
* `task_events` table, written in the same transaction as the task write.
|
|
4
4
|
* Shared by both cores; the Python core writes `dispatched`, `completed`,
|
|
5
|
-
* `failed` and `cancelled` rows with the same shape.
|
|
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", "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`,
|
|
@@ -37,14 +37,24 @@ export declare function normalizeActor(actor: unknown): TaskEventActor;
|
|
|
37
37
|
export declare function isTaskEventKind(kind: unknown): kind is TaskEventKind;
|
|
38
38
|
/**
|
|
39
39
|
* The details of one event: `from` / `to` timing for moves and run-now,
|
|
40
|
-
* provider and model for created / dispatched / completed / failed
|
|
41
|
-
* first line of the error for failed, then `extra`.
|
|
40
|
+
* provider and model for created / dispatched / completed / failed /
|
|
41
|
+
* attempt_failed, the first line of the error for failed, then `extra`.
|
|
42
42
|
*/
|
|
43
43
|
export declare function eventDetails(kind: TaskEventKind, prev: TaskRecord<unknown> | undefined, next: TaskRecord<unknown>, extra?: Record<string, unknown>): Record<string, unknown>;
|
|
44
44
|
/** The kind a status change implies when the writer named none (terminal moves only). */
|
|
45
45
|
export declare function impliedEventKind(prevStatus: string, nextStatus: string): TaskEventKind | undefined;
|
|
46
46
|
/** A one-line summary of the details, or "". */
|
|
47
47
|
export declare function eventSummary(e: Pick<TaskEvent, "kind" | "details">): string;
|
|
48
|
+
/**
|
|
49
|
+
* One line per failed attempt the retry policy queued again, since the
|
|
50
|
+
* newest `created` event or manual retry, for the text views: key
|
|
51
|
+
* `attempt_<n>`, text `failed <at> (<class>): <error>; next attempt from
|
|
52
|
+
* <retry_at>`. `events` are oldest first.
|
|
53
|
+
*/
|
|
54
|
+
export declare function attemptLines(events: readonly Pick<TaskEvent, "at" | "kind" | "details">[]): {
|
|
55
|
+
key: string;
|
|
56
|
+
text: string;
|
|
57
|
+
}[];
|
|
48
58
|
/** `<at> <kind> by <actor>[ - <summary>]`, one line. */
|
|
49
59
|
export declare function formatTaskEvent(e: Pick<TaskEvent, "at" | "kind" | "actor" | "details">): string;
|
|
50
60
|
/** The API / JSON shape of one event. */
|
|
@@ -62,6 +72,11 @@ export declare const PROGRESS_GAP_MS = 15000;
|
|
|
62
72
|
export declare const PROGRESS_MAX_EVENTS = 24;
|
|
63
73
|
/** Longest progress line. */
|
|
64
74
|
export declare const PROGRESS_LINE_MAX_CHARS = 200;
|
|
75
|
+
/**
|
|
76
|
+
* Longest wait of one progress write for another writer's lock, in ms. The
|
|
77
|
+
* tick writes progress on its event loop; past this the line is dropped.
|
|
78
|
+
*/
|
|
79
|
+
export declare const PROGRESS_BUSY_MS = 100;
|
|
65
80
|
/**
|
|
66
81
|
* Untrusted output text without terminal escape sequences, control
|
|
67
82
|
* characters (a tab becomes a space), line separators or bidirectional
|
package/dist/task-events.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Task events (audit trail): one row per change of a task, in the ledger's
|
|
3
3
|
* `task_events` table, written in the same transaction as the task write.
|
|
4
4
|
* Shared by both cores; the Python core writes `dispatched`, `completed`,
|
|
5
|
-
* `failed` and `cancelled` rows with the same shape.
|
|
5
|
+
* `failed`, `attempt_failed` and `cancelled` rows with the same shape.
|
|
6
6
|
*/
|
|
7
7
|
import { includesWebTool } from "./claude-tools.js";
|
|
8
8
|
import { stripControlChars } from "./history.js";
|
|
@@ -15,6 +15,11 @@ export const TASK_EVENT_KINDS = [
|
|
|
15
15
|
"dispatched",
|
|
16
16
|
"completed",
|
|
17
17
|
"failed",
|
|
18
|
+
// A run failed and the retry policy queued another attempt: the task is
|
|
19
|
+
// `scheduled` again. Not terminal: no notice, wake, result file or series
|
|
20
|
+
// roll. Details: `attempt`, `failure_class`, `error` (first line),
|
|
21
|
+
// `retry_at`, and the run's own keys (`steps`, `stopped_by`).
|
|
22
|
+
"attempt_failed",
|
|
18
23
|
"deferred",
|
|
19
24
|
"replied",
|
|
20
25
|
// A Claude Code session was told the task finished (its prompt hook, a
|
|
@@ -24,6 +29,10 @@ export const TASK_EVENT_KINDS = [
|
|
|
24
29
|
// The tick wrote the task's result file, or could not (`written: false`
|
|
25
30
|
// with the error). At most one per task.
|
|
26
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",
|
|
27
36
|
// A line a long `command` run printed while it ran (`line`, `seq`), within
|
|
28
37
|
// the caps of `createProgressRecorder`.
|
|
29
38
|
"progress",
|
|
@@ -104,11 +113,11 @@ function providerModel(bodyJson) {
|
|
|
104
113
|
}
|
|
105
114
|
}
|
|
106
115
|
const MOVE_KINDS = new Set(["rescheduled", "postponed", "expedited"]);
|
|
107
|
-
const SPEC_KINDS = new Set(["created", "dispatched", "completed", "failed"]);
|
|
116
|
+
const SPEC_KINDS = new Set(["created", "dispatched", "completed", "failed", "attempt_failed"]);
|
|
108
117
|
/**
|
|
109
118
|
* The details of one event: `from` / `to` timing for moves and run-now,
|
|
110
|
-
* provider and model for created / dispatched / completed / failed
|
|
111
|
-
* first line of the error for failed, then `extra`.
|
|
119
|
+
* provider and model for created / dispatched / completed / failed /
|
|
120
|
+
* attempt_failed, the first line of the error for failed, then `extra`.
|
|
112
121
|
*/
|
|
113
122
|
export function eventDetails(kind, prev, next, extra = {}) {
|
|
114
123
|
const out = {};
|
|
@@ -164,6 +173,11 @@ export function eventSummary(e) {
|
|
|
164
173
|
case "deferred":
|
|
165
174
|
parts.push(`retry at ${short(d.retry_at)}`);
|
|
166
175
|
break;
|
|
176
|
+
case "attempt_failed":
|
|
177
|
+
parts.push(`attempt ${typeof d.attempt === "number" ? d.attempt : "?"} (${short(d.failure_class)})`, `retry at ${short(d.retry_at)}`);
|
|
178
|
+
if (typeof d.error === "string")
|
|
179
|
+
parts.push(d.error);
|
|
180
|
+
break;
|
|
167
181
|
case "replied":
|
|
168
182
|
parts.push(`reply ${short(d.child_task_id)}`);
|
|
169
183
|
break;
|
|
@@ -173,6 +187,11 @@ export function eventSummary(e) {
|
|
|
173
187
|
case "result_file":
|
|
174
188
|
parts.push(d.written === true ? `written ${short(d.path)}` : `not written: ${short(d.error)}`);
|
|
175
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;
|
|
176
195
|
case "progress":
|
|
177
196
|
if (typeof d.line === "string")
|
|
178
197
|
parts.push(d.line);
|
|
@@ -189,6 +208,28 @@ export function eventSummary(e) {
|
|
|
189
208
|
parts.push(d.reason);
|
|
190
209
|
return parts.join("; ");
|
|
191
210
|
}
|
|
211
|
+
/**
|
|
212
|
+
* One line per failed attempt the retry policy queued again, since the
|
|
213
|
+
* newest `created` event or manual retry, for the text views: key
|
|
214
|
+
* `attempt_<n>`, text `failed <at> (<class>): <error>; next attempt from
|
|
215
|
+
* <retry_at>`. `events` are oldest first.
|
|
216
|
+
*/
|
|
217
|
+
export function attemptLines(events) {
|
|
218
|
+
const out = [];
|
|
219
|
+
for (const e of events) {
|
|
220
|
+
if (e.kind === "created" || (e.kind === "rescheduled" && e.details?.reason === "retry"))
|
|
221
|
+
out.length = 0;
|
|
222
|
+
if (e.kind !== "attempt_failed")
|
|
223
|
+
continue;
|
|
224
|
+
const d = e.details ?? {};
|
|
225
|
+
const n = typeof d.attempt === "number" ? d.attempt : out.length + 1;
|
|
226
|
+
const cls = typeof d.failure_class === "string" ? ` (${d.failure_class})` : "";
|
|
227
|
+
const error = typeof d.error === "string" ? `: ${d.error}` : "";
|
|
228
|
+
const next = typeof d.retry_at === "string" ? `; next attempt from ${d.retry_at}` : "";
|
|
229
|
+
out.push({ key: `attempt_${n}`, text: `failed ${e.at}${cls}${error}${next}` });
|
|
230
|
+
}
|
|
231
|
+
return out;
|
|
232
|
+
}
|
|
192
233
|
/** `<at> <kind> by <actor>[ - <summary>]`, one line. */
|
|
193
234
|
export function formatTaskEvent(e) {
|
|
194
235
|
const summary = eventSummary(e);
|
|
@@ -206,6 +247,11 @@ export const PROGRESS_GAP_MS = 15_000;
|
|
|
206
247
|
export const PROGRESS_MAX_EVENTS = 24;
|
|
207
248
|
/** Longest progress line. */
|
|
208
249
|
export const PROGRESS_LINE_MAX_CHARS = 200;
|
|
250
|
+
/**
|
|
251
|
+
* Longest wait of one progress write for another writer's lock, in ms. The
|
|
252
|
+
* tick writes progress on its event loop; past this the line is dropped.
|
|
253
|
+
*/
|
|
254
|
+
export const PROGRESS_BUSY_MS = 100;
|
|
209
255
|
/** Terminal escape sequences (CSI, OSC and two-character escapes): removed whole, not only their ESC. */
|
|
210
256
|
const TERMINAL_ESCAPES = /\u001b\[[0-?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|\u001b[@-Z\\-_]/g;
|
|
211
257
|
/** Line and paragraph separators (become a space) and bidirectional controls (removed). */
|
|
@@ -276,7 +322,7 @@ export function createProgressRecorder(write, opts = {}) {
|
|
|
276
322
|
write({ line, seq });
|
|
277
323
|
}
|
|
278
324
|
catch {
|
|
279
|
-
// A busy ledger costs this line, not the run.
|
|
325
|
+
// A busy ledger costs this line (at most PROGRESS_BUSY_MS of waiting), not the run.
|
|
280
326
|
}
|
|
281
327
|
};
|
|
282
328
|
return {
|