@tidegap/core 0.22.0 → 0.24.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.
Files changed (40) hide show
  1. package/dist/channels/commands.js +3 -2
  2. package/dist/channels/digest.d.ts +4 -1
  3. package/dist/channels/digest.js +6 -2
  4. package/dist/channels/format.d.ts +44 -19
  5. package/dist/channels/format.js +113 -77
  6. package/dist/channels/index.d.ts +1 -0
  7. package/dist/channels/index.js +1 -0
  8. package/dist/channels/kinds/discord.js +2 -2
  9. package/dist/channels/kinds/email.js +2 -1
  10. package/dist/channels/kinds/ntfy.js +9 -1
  11. package/dist/channels/kinds/pushover.js +4 -3
  12. package/dist/channels/kinds/shared.d.ts +4 -1
  13. package/dist/channels/kinds/shared.js +6 -1
  14. package/dist/channels/kinds/slack.js +2 -2
  15. package/dist/channels/notice.d.ts +42 -0
  16. package/dist/channels/notice.js +142 -0
  17. package/dist/channels/payload.d.ts +3 -0
  18. package/dist/channels/payload.js +16 -5
  19. package/dist/channels/telegram.d.ts +31 -1
  20. package/dist/channels/telegram.js +34 -12
  21. package/dist/history.d.ts +101 -0
  22. package/dist/history.js +95 -0
  23. package/dist/index.d.ts +8 -6
  24. package/dist/index.js +6 -4
  25. package/dist/jobs.d.ts +53 -5
  26. package/dist/jobs.js +279 -42
  27. package/dist/notice-language.d.ts +37 -0
  28. package/dist/notice-language.js +67 -0
  29. package/dist/providers/base.d.ts +7 -0
  30. package/dist/redact.d.ts +3 -2
  31. package/dist/redact.js +8 -2
  32. package/dist/schedule-job.d.ts +3 -2
  33. package/dist/schedule-job.js +6 -5
  34. package/dist/scheduler.d.ts +9 -1
  35. package/dist/scheduler.js +13 -5
  36. package/dist/storage/sqlite.js +7 -3
  37. package/dist/types.d.ts +14 -1
  38. package/dist/zone-time.d.ts +2 -0
  39. package/dist/zone-time.js +11 -0
  40. package/package.json +2 -2
@@ -113,11 +113,12 @@ export interface JobToolView {
113
113
  status: JobRecord["status"];
114
114
  /** The guarantee in words, e.g. "runs every day between 00:00 and 08:00". */
115
115
  guarantee: string;
116
- /** Planned hour of the job's live run, if one is planned. */
116
+ /** Planned hour of the job's next live run (the planned one or an extra run, whichever runs first). */
117
117
  nextRun?: string;
118
118
  /** Id of that run. */
119
119
  nextTaskId?: string;
120
- lastOutcome?: JobRecord["lastOutcome"];
120
+ /** Outcome of the last occurrence that ran; a cancelled one never counts. */
121
+ lastOutcome?: "ok" | "failed";
121
122
  pauseReason?: string;
122
123
  }
123
124
  /** One job's list view: guarantee, next run, last result. */
@@ -11,7 +11,7 @@
11
11
  import { includesFileTool, includesWebTool } from "./claude-tools.js";
12
12
  import { guaranteeText, parseWindow, validateJobSchedule } from "./job-cadence.js";
13
13
  import { wakePatternError } from "./job-wake.js";
14
- import { getJob, removeJob } from "./jobs.js";
14
+ import { getJob, jobLastRun, jobNextRun, removeJob, runOutcome } from "./jobs.js";
15
15
  import { DURATION_FORM_ERROR, parseDuration, parseRetryDelay, RETRY_DELAY_ERROR, runLimitValueError, } from "./run-limits.js";
16
16
  import { systemTimeZone } from "./zone-time.js";
17
17
  /** The `repeat` values that create a job. */
@@ -228,18 +228,19 @@ export function scheduleJobInput(args, now = new Date()) {
228
228
  ...(args.wake !== undefined ? { wake: args.wake } : {}),
229
229
  };
230
230
  }
231
- const LIVE = new Set(["queued", "scheduled", "running", "submitted"]);
232
231
  /** One job's list view: guarantee, next run, last result. */
233
232
  export function jobToolView(scheduler, job) {
234
- const row = job.pendingTaskId ? scheduler.ledger()?.get(job.pendingTaskId) : undefined;
235
- const live = row && LIVE.has(row.status) ? row : undefined;
233
+ const store = scheduler.ledger();
234
+ const live = store ? jobNextRun(store, job) : undefined;
235
+ const last = store ? jobLastRun(store, job) : undefined;
236
+ const lastOutcome = last ? runOutcome(last) : undefined;
236
237
  return {
237
238
  jobId: job.jobId,
238
239
  title: job.title,
239
240
  status: job.status,
240
241
  guarantee: guaranteeText({ cadence: job.cadence, window: job.window, timeZone: job.timeZone }),
241
242
  ...(live ? { nextTaskId: live.taskId, nextRun: live.scheduledFor ?? live.notBefore } : {}),
242
- ...(job.lastOutcome ? { lastOutcome: job.lastOutcome } : {}),
243
+ ...(lastOutcome ? { lastOutcome } : {}),
243
244
  ...(job.pauseReason ? { pauseReason: job.pauseReason } : {}),
244
245
  };
245
246
  }
@@ -337,6 +337,10 @@ export declare class Scheduler {
337
337
  * nothing, when the row exists. Planning picks the cleanest forecast hour
338
338
  * inside `[earliest, deadline]`, or leaves the row unplanned for
339
339
  * `replanSweep` when the forecast does not reach it (or fails).
340
+ *
341
+ * `runNow` (a job's extra run): the row is due now as a run-now row is
342
+ * (`scheduledFor` now, no `notBefore`, `intensitySource: "expedited"`, so
343
+ * never the Batch API), with no planning; `actor` is on its `created` event.
340
344
  */
341
345
  materializeOccurrence(occ: {
342
346
  taskId: string;
@@ -349,7 +353,11 @@ export declare class Scheduler {
349
353
  originCwd?: string;
350
354
  /** The session a bound job wakes; its runs become that session's notices (KTD7). */
351
355
  originSessionId?: string;
352
- }, details: Record<string, unknown>): Promise<boolean>;
356
+ }, details: Record<string, unknown>, opts?: {
357
+ runNow?: {
358
+ actor?: string;
359
+ };
360
+ }): Promise<boolean>;
353
361
  /**
354
362
  * Defer a task. Returns a promise that resolves with the task's eventual
355
363
  * result when Tidegap dispatches it.
package/dist/scheduler.js CHANGED
@@ -353,8 +353,12 @@ export class Scheduler {
353
353
  * nothing, when the row exists. Planning picks the cleanest forecast hour
354
354
  * inside `[earliest, deadline]`, or leaves the row unplanned for
355
355
  * `replanSweep` when the forecast does not reach it (or fails).
356
+ *
357
+ * `runNow` (a job's extra run): the row is due now as a run-now row is
358
+ * (`scheduledFor` now, no `notBefore`, `intensitySource: "expedited"`, so
359
+ * never the Batch API), with no planning; `actor` is on its `created` event.
356
360
  */
357
- async materializeOccurrence(occ, details) {
361
+ async materializeOccurrence(occ, details, opts = {}) {
358
362
  if (!this.store)
359
363
  throw new Error("materializeOccurrence: jobs need a ledger (dbPath)");
360
364
  const earliestMs = Date.parse(occ.earliest);
@@ -366,8 +370,9 @@ export class Scheduler {
366
370
  region: this.defaultRegion(),
367
371
  bodyJson: occ.bodyJson,
368
372
  deadline: new Date(deadlineMs).toISOString(),
369
- notBefore: new Date(earliestMs).toISOString(),
370
- scheduledFor: new Date(Math.min(earliestMs + MINUTE_MS, deadlineMs)).toISOString(),
373
+ ...(opts.runNow
374
+ ? { scheduledFor: new Date().toISOString(), intensitySource: "expedited" }
375
+ : { notBefore: new Date(earliestMs).toISOString(), scheduledFor: new Date(Math.min(earliestMs + MINUTE_MS, deadlineMs)).toISOString() }),
371
376
  title: occ.title,
372
377
  originHost: occ.originHost,
373
378
  originCwd: occ.originCwd,
@@ -375,12 +380,14 @@ export class Scheduler {
375
380
  repeat: "none",
376
381
  jobId: occ.jobId,
377
382
  };
378
- const created = this.eventFor(undefined, record, { kind: "created", actor: "system", details });
383
+ const created = this.eventFor(undefined, record, { kind: "created", actor: opts.runNow?.actor ?? "system", details });
379
384
  if (!this.store.insertIfAbsent(record, created))
380
385
  return false;
381
386
  if (record.originSessionId)
382
387
  this.store.startSessionNotices(new Date(record.enqueuedAt));
383
388
  this.cacheRow(record);
389
+ if (opts.runNow)
390
+ return true;
384
391
  try {
385
392
  await this.scheduleProviderCall(record.taskId, new Date(deadlineMs));
386
393
  }
@@ -3047,7 +3054,7 @@ function checkedCaps(caps, keys, what) {
3047
3054
  * Dispatch options of a run: its resolved time limits, the caps' budget,
3048
3055
  * and for a row with `job_id` its working directory and job id. A
3049
3056
  * `claude-code` row without a job gets its handoff folder. A `command` body
3050
- * also hands over its shell and summarize steps.
3057
+ * also hands over its task id (for its attachments), shell and summarize steps.
3051
3058
  */
3052
3059
  function jobDispatchOptions(record, spec, limits) {
3053
3060
  const out = {};
@@ -3068,6 +3075,7 @@ function jobDispatchOptions(record, spec, limits) {
3068
3075
  out.cwd = spec.handoff.cwd;
3069
3076
  }
3070
3077
  if (spec.provider === "command") {
3078
+ out.taskId = record.taskId;
3071
3079
  if (spec.command)
3072
3080
  out.command = spec.command;
3073
3081
  if (spec.summarize)
@@ -189,7 +189,8 @@ CREATE TABLE IF NOT EXISTS jobs (
189
189
  end_reason TEXT,
190
190
  end_notified_at TEXT,
191
191
  wake_json TEXT,
192
- origin_session_id TEXT
192
+ origin_session_id TEXT,
193
+ extra_task_id TEXT
193
194
  );
194
195
  CREATE INDEX IF NOT EXISTS jobs_status_idx ON jobs(status);
195
196
  `;
@@ -268,7 +269,7 @@ function columnAdder(db, table) {
268
269
  }
269
270
  };
270
271
  }
271
- /** The `jobs` columns added after the table first shipped: the job lifetime, then the wake binding. */
272
+ /** The `jobs` columns added after the table first shipped: the job lifetime, the wake binding, then the extra run. */
272
273
  function ensureJobColumns(db) {
273
274
  const addColumn = columnAdder(db, "jobs");
274
275
  addColumn("until", "TEXT");
@@ -278,6 +279,7 @@ function ensureJobColumns(db) {
278
279
  addColumn("end_notified_at", "TEXT");
279
280
  addColumn("wake_json", "TEXT");
280
281
  addColumn("origin_session_id", "TEXT");
282
+ addColumn("extra_task_id", "TEXT");
281
283
  }
282
284
  const REPEAT_RULES = new Set(["none", "daily", "weekly", "quota_reset"]);
283
285
  /** Every column of the tasks table, in INSERT order. */
@@ -1233,7 +1235,7 @@ const JOB_COLUMNS = [
1233
1235
  "time_zone", "runner", "template_json", "caps_json", "notify", "origin_host", "origin_cwd", "created_by",
1234
1236
  "created_at", "updated_at", "revision", "next_seq", "pending_task_id", "last_task_id", "last_run_started_at",
1235
1237
  "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",
1238
+ "until", "runs_left", "ended_at", "end_reason", "end_notified_at", "wake_json", "origin_session_id", "extra_task_id",
1237
1239
  ];
1238
1240
  /** Columns `updateJobIf` writes: everything except the identity and the revision. */
1239
1241
  const JOB_MUTABLE_COLUMNS = JOB_COLUMNS.filter((c) => !["job_id", "created_at", "created_by", "origin_host", "origin_cwd", "revision"].includes(c));
@@ -1280,6 +1282,7 @@ function jobParams(job) {
1280
1282
  end_notified_at: job.endNotifiedAt ?? null,
1281
1283
  wake_json: job.wake ? JSON.stringify(job.wake) : null,
1282
1284
  origin_session_id: job.originSessionId ?? null,
1285
+ extra_task_id: job.extraTaskId ?? null,
1283
1286
  };
1284
1287
  }
1285
1288
  /** A job row's wake rule and session, both or neither: a rule that does not parse binds nothing. */
@@ -1362,6 +1365,7 @@ function rowToJob(row) {
1362
1365
  revision: Number(row.revision),
1363
1366
  nextSeq: Number(row.next_seq),
1364
1367
  pendingTaskId: str(row.pending_task_id),
1368
+ extraTaskId: str(row.extra_task_id),
1365
1369
  lastTaskId: str(row.last_task_id),
1366
1370
  lastRunStartedAt: str(row.last_run_started_at),
1367
1371
  lastOutcome: JOB_OUTCOMES.has(row.last_outcome) ? row.last_outcome : undefined,
package/dist/types.d.ts CHANGED
@@ -728,7 +728,11 @@ export interface JobWake {
728
728
  }
729
729
  /** Why a run of a bound job is a session notice. */
730
730
  export type JobNoticeReason = "failed" | "matched" | "ended";
731
- /** Outcome of a job's last finished occurrence. */
731
+ /**
732
+ * Outcome of a job's last run: `ok` (completed) or `failed`. `skipped` is
733
+ * read from rows written before a cancelled occurrence stopped counting as
734
+ * the last run; the sweep no longer writes it.
735
+ */
732
736
  export type JobOutcome = "ok" | "failed" | "skipped";
733
737
  /** One row of the `jobs` table. */
734
738
  export interface JobRecord {
@@ -755,8 +759,17 @@ export interface JobRecord {
755
759
  nextSeq: number;
756
760
  /** The one live occurrence the sweep tracks. */
757
761
  pendingTaskId?: string;
762
+ /**
763
+ * The extra run that run now added (`<job_id>~<seq>x`, its retries
764
+ * `<job_id>~<seq>xr`, `...xr2`), live or finished and not yet recorded.
765
+ * It runs beside the planned occurrence and does not move it.
766
+ */
767
+ extraTaskId?: string;
768
+ /** The last occurrence that ran (completed or failed), a regular one or an extra run; never a cancelled one. */
758
769
  lastTaskId?: string;
770
+ /** When the last regular occurrence started: the anchor of the next one. An extra run does not move it. */
759
771
  lastRunStartedAt?: string;
772
+ /** Outcome of {@link lastTaskId}. */
760
773
  lastOutcome?: JobOutcome;
761
774
  consecutiveFailures: number;
762
775
  /** The retries the current slot used, 0 to the job's retries (`retry_used`; a row from before held 0 or 1). */
@@ -19,4 +19,6 @@ export declare function localTime(ms: number, tz: string): number;
19
19
  * a local time inside a DST gap gives the first instant after the gap.
20
20
  */
21
21
  export declare function localToUtcMs(y: number, mo: number, d: number, h: number, mi: number, tz: string): number;
22
+ /** `HH:MM` in `timeZone` when `at` falls on the same day there as `now`, else `Ddd HH:MM`. */
23
+ export declare function zoneTimeLabel(at: Date, now: Date, timeZone: string): string;
22
24
  //# sourceMappingURL=zone-time.d.ts.map
package/dist/zone-time.js CHANGED
@@ -73,4 +73,15 @@ export function localToUtcMs(y, mo, d, h, mi, tz) {
73
73
  }
74
74
  return hi;
75
75
  }
76
+ /** `HH:MM` in `timeZone` when `at` falls on the same day there as `now`, else `Ddd HH:MM`. */
77
+ export function zoneTimeLabel(at, now, timeZone) {
78
+ const parts = (d) => {
79
+ // An unknown zone falls back to the system zone.
80
+ const fmt = new Intl.DateTimeFormat("en-US", { timeZone: isValidTimeZone(timeZone) ? timeZone : undefined, weekday: "short", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23" });
81
+ const p = Object.fromEntries(fmt.formatToParts(d).map((x) => [x.type, x.value]));
82
+ return { day: `${p.year}-${p.month}-${p.day}`, weekday: p.weekday, time: `${p.hour}:${p.minute}` };
83
+ };
84
+ const a = parts(at);
85
+ return a.day === parts(now).day ? a.time : `${a.weekday} ${a.time}`;
86
+ }
76
87
  //# sourceMappingURL=zone-time.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tidegap/core",
3
- "version": "0.22.0",
3
+ "version": "0.24.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.53.0",
58
+ "openai": "^7.57.0",
59
59
  "typescript": "^5.6.3",
60
60
  "vitest": "^4.1.12"
61
61
  },