@tidegap/core 0.21.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.
@@ -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 rows = db
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
- /** What a notice needs from a task body: a checked Claude Code origin and the result file path. */
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 person's read
700
- * marker does not matter here.
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
  }
@@ -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`,
@@ -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);
@@ -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
- export type JobStatus = "active" | "paused" | "removed";
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.21.0",
3
+ "version": "0.22.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.51.0",
58
+ "openai": "^7.53.0",
59
59
  "typescript": "^5.6.3",
60
60
  "vitest": "^4.1.12"
61
61
  },