@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.
package/dist/jobs.js CHANGED
@@ -28,8 +28,10 @@
28
28
  */
29
29
  import { randomBytes } from "node:crypto";
30
30
  import { DEFAULT_MODEL_BY_PROVIDER } from "./providers/defaults.js";
31
- import { BATCH_SUBMIT_INTERRUPTED_ERROR, deriveTitle } from "./history.js";
32
- import { isCalendarAnchored, JobScheduleError, nextOccurrence, validateJobSchedule } from "./job-cadence.js";
31
+ import { wakeError } from "./handoff.js";
32
+ import { BATCH_SUBMIT_INTERRUPTED_ERROR, deriveTitle, taskResultText } from "./history.js";
33
+ import { JOB_WAKE_FORMS, matchWake, wakePatternError } from "./job-wake.js";
34
+ import { isCalendarAnchored, JobScheduleError, nextOccurrence, untilBoundMs, untilText, validateJobSchedule } from "./job-cadence.js";
33
35
  import { sleptBetween } from "./readiness.js";
34
36
  import { capValueError, classifyFailure, FAILURE_CLASSES, isRetryableFailure, isRunLimitCap, loadRunLimitSettings, planRetry, resolveTaskRunLimits, retryPolicyOf, runLimitsFromDetails, versionedCaps, } from "./run-limits.js";
35
37
  import { canonicalize } from "./sign.js";
@@ -73,13 +75,28 @@ const ORIGIN_HOSTS = new Set(["page", "cli", "mcp", "openclaw"]);
73
75
  const TASK_ORIGIN_HOSTS = new Set(["cli", "mcp", "openclaw"]);
74
76
  /** A job secret name: what the command sees as an environment variable. */
75
77
  export const JOB_SECRET_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
78
+ /**
79
+ * The prompt `tidegap jobs add --summarize` stores when the user gives none.
80
+ * It is stored as text on the job, so a later change here leaves existing
81
+ * jobs as they are.
82
+ */
83
+ export const DEFAULT_SUMMARIZE_PROMPT = [
84
+ "You write the message a person reads on their phone when this scheduled job finishes. The job title and the command output follow.",
85
+ "Line 1: the verdict in one short sentence: all fine, or what needs attention.",
86
+ "Then a blank line and one to three short sentences: only what changed or what to do next. Give a number only when it changed or crossed a limit. Name a metric only when the reader needs the name to act.",
87
+ "Plain text only: no headings, lists, tables, markdown or code. Do not repeat the output.",
88
+ "Write in the language of the job title.",
89
+ "If the output is empty or you cannot tell what it means, say so on line 1.",
90
+ ].join("\n");
76
91
  const LIVE_STATUSES = ["queued", "scheduled", "running", "submitted"];
77
92
  const PENDING_STATUSES = ["queued", "scheduled"];
78
93
  const LIVE = new Set(LIVE_STATUSES);
79
94
  const PENDING = new Set(PENDING_STATUSES);
80
95
  /** Cancel reasons a job action writes; any other cancel of an occurrence is a skip. */
81
- const ACTION_CANCEL_REASONS = new Set(["paused", "edited", "removed", "duplicate"]);
96
+ const ACTION_CANCEL_REASONS = new Set(["paused", "edited", "removed", "duplicate", "ended"]);
82
97
  const MINUTE_MS = 60_000;
98
+ /** The most runs a job's `count` may ask for. */
99
+ export const JOB_MAX_COUNT = 1000;
83
100
  /** Failed slots in a row that pause a job. */
84
101
  export const JOB_AUTO_PAUSE_FAILURES = 3;
85
102
  /** How `pauseReason` starts when the third failed slot paused the job: `auto: <first error line>`. */
@@ -194,6 +211,75 @@ function validNotify(v) {
194
211
  throw new JobActionError("notify must be every_run, failures or summary", "invalid");
195
212
  return v;
196
213
  }
214
+ /** A valid `until` for a job in `timeZone`, or undefined for none; a bound already past is refused. */
215
+ function validUntil(v, timeZone, nowMs) {
216
+ if (v === undefined || v === null)
217
+ return undefined;
218
+ if (typeof v !== "string")
219
+ throw new JobActionError("until must be a day YYYY-MM-DD or an ISO instant", "invalid");
220
+ const text = v.trim();
221
+ let bound;
222
+ try {
223
+ bound = untilBoundMs(text, timeZone);
224
+ }
225
+ catch (err) {
226
+ if (err instanceof JobScheduleError)
227
+ throw new JobActionError(err.message, "invalid");
228
+ throw err;
229
+ }
230
+ if (bound <= nowMs)
231
+ throw new JobActionError(`until "${text}" has passed; give a later day or instant`, "invalid");
232
+ return text;
233
+ }
234
+ /** A valid `count`, or undefined for none. */
235
+ function validCount(v) {
236
+ if (v === undefined || v === null)
237
+ return undefined;
238
+ if (typeof v !== "number" || !Number.isInteger(v) || v < 1 || v > JOB_MAX_COUNT) {
239
+ throw new JobActionError(`count must be a whole number from 1 to ${JOB_MAX_COUNT}`, "invalid");
240
+ }
241
+ return v;
242
+ }
243
+ /** What an end reason says: `its end date (<until>) passed` or `its runs are done`. */
244
+ export function jobEndText(reason, until) {
245
+ return reason === "until" ? `its end date${until ? ` (${until})` : ""} passed` : "its runs are done";
246
+ }
247
+ /**
248
+ * A job's end condition in words, or undefined for a job with none:
249
+ * `ends after 2026-11-17 (Europe/Berlin)`, `3 runs left`, or both joined by `; `.
250
+ */
251
+ export function jobEndsText(job) {
252
+ const parts = [];
253
+ if (job.until !== undefined)
254
+ parts.push(`ends ${untilText(job.until, job.timeZone)}`);
255
+ if (job.runsLeft !== undefined)
256
+ parts.push(`${job.runsLeft} ${job.runsLeft === 1 ? "run" : "runs"} left`);
257
+ return parts.length > 0 ? parts.join("; ") : undefined;
258
+ }
259
+ /**
260
+ * The binding a wake input gives, checked: `never` clears both fields; a
261
+ * rule needs a Claude Code session ({@link wakeError}) and, for `match`, a
262
+ * pattern {@link wakePatternError} accepts. `boundAt` is `now`.
263
+ */
264
+ function validWake(input, now) {
265
+ if (input.on === "never")
266
+ return { wake: undefined, originSessionId: undefined };
267
+ if (input.on !== "failures" && input.on !== "match")
268
+ throw new JobActionError(`wake must be ${JOB_WAKE_FORMS}`, "invalid");
269
+ const refused = wakeError(true, { agent: input.agent }, input.sessionId);
270
+ if (refused)
271
+ throw new JobActionError(refused, "invalid");
272
+ if (input.on === "failures")
273
+ return { wake: { on: "failures", boundAt: now.toISOString() }, originSessionId: input.sessionId };
274
+ const patternError = wakePatternError(input.pattern);
275
+ if (patternError)
276
+ throw new JobActionError(patternError, "invalid");
277
+ return { wake: { on: "match", pattern: input.pattern, boundAt: now.toISOString() }, originSessionId: input.sessionId };
278
+ }
279
+ /** The session a job wakes, or undefined when it is not bound. */
280
+ export function jobWakeSession(job) {
281
+ return job.wake && job.originSessionId ? job.originSessionId : undefined;
282
+ }
197
283
  function newJobId(store) {
198
284
  for (;;) {
199
285
  const id = `job-${randomBytes(4).toString("hex")}`;
@@ -204,6 +290,9 @@ function newJobId(store) {
204
290
  /** The occurrence body a job's template runs (Data shapes in the plan). */
205
291
  function occurrenceBody(job) {
206
292
  const t = job.template;
293
+ const session = jobWakeSession(job);
294
+ // A bound job's runs carry the rule and the session, never `origin` (KTD7).
295
+ const jobWake = session ? { jobWake: { on: job.wake.on, session } } : {};
207
296
  if (t.runner === "prompt") {
208
297
  return {
209
298
  type: "provider_call",
@@ -212,6 +301,7 @@ function occurrenceBody(job) {
212
301
  prompt: t.prompt,
213
302
  tools: TOOLS[t.tools],
214
303
  caps: job.caps,
304
+ ...jobWake,
215
305
  };
216
306
  }
217
307
  return {
@@ -222,6 +312,7 @@ function occurrenceBody(job) {
222
312
  command: { run: t.command, cwd: t.cwd, secrets: t.secrets },
223
313
  summarize: t.summarize ? { provider: t.summarize.provider, model: t.summarize.model } : undefined,
224
314
  caps: job.caps,
315
+ ...jobWake,
225
316
  };
226
317
  }
227
318
  /**
@@ -333,10 +424,10 @@ function cancelOccurrence(scheduler, taskId, jobId, reason, actor) {
333
424
  const row = scheduler.cancelTask(taskId, { actor, details: { job_id: jobId, reason }, expectedStatus: PENDING_STATUSES });
334
425
  return row.status === "cancelled";
335
426
  }
336
- /** The run fields of an occurrence body: what an edit of the template changes (KTD2). */
427
+ /** The run fields of an occurrence body: what an edit of the template or the wake binding changes (KTD2, KTD7). */
337
428
  function runFields(spec) {
338
- const { provider, model, prompt, tools, caps, command, summarize } = spec;
339
- return canonicalize({ provider, model, prompt, tools: tools ?? [], caps, command, summarize });
429
+ const { provider, model, prompt, tools, caps, command, summarize, jobWake } = spec;
430
+ return canonicalize({ provider, model, prompt, tools: tools ?? [], caps, command, summarize, jobWake });
340
431
  }
341
432
  /** True when a stored occurrence runs what the job's current template gives. */
342
433
  function runsCurrentTemplate(row, job) {
@@ -348,7 +439,7 @@ function runsCurrentTemplate(row, job) {
348
439
  }
349
440
  }
350
441
  function emptyResult() {
351
- return { messages: [], materialized: [], retried: [], autoPaused: [], interrupted: [] };
442
+ return { messages: [], materialized: [], retried: [], autoPaused: [], interrupted: [], ended: [], sessionNotices: [] };
352
443
  }
353
444
  /**
354
445
  * One job's step of the sweep: record the tracked occurrence's outcome and
@@ -360,6 +451,8 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
360
451
  const nowMs = now.getTime();
361
452
  /** Rows this call inserted: cleaned up when every job write misses. */
362
453
  const inserted = [];
454
+ /** Runs whose notice this call decided: a second attempt does not match the pattern again. */
455
+ const notices = new Set();
363
456
  for (let attempt = 0; attempt < 3; attempt++) {
364
457
  const job = store.getJob(jobId);
365
458
  if (!job || job.pauseReason === CORRUPT)
@@ -398,13 +491,15 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
398
491
  }
399
492
  return;
400
493
  }
401
- if (!tracked && job.status !== "active")
494
+ if (!tracked && job.status !== "active" && !(job.status === "paused" && pausedEndReason(job, nowMs)))
402
495
  return;
403
496
  // The tracked occurrence ended (or there is none): record the outcome.
404
497
  const next = { ...job, updatedAt: now.toISOString() };
405
498
  let successor = job.status === "active" ? "next" : "none";
406
499
  let skippedDeadline;
407
500
  let retryAt;
501
+ /** The tracked slot ended for good: completed, or failed with no retry left. */
502
+ let slotEnded = false;
408
503
  if (tracked) {
409
504
  next.pendingTaskId = undefined;
410
505
  next.lastTaskId = tracked.taskId;
@@ -412,6 +507,7 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
412
507
  if (tracked.status === "completed") {
413
508
  next.lastOutcome = "ok";
414
509
  next.consecutiveFailures = 0;
510
+ slotEnded = true;
415
511
  }
416
512
  else if (tracked.status === "failed") {
417
513
  next.lastOutcome = "failed";
@@ -423,6 +519,7 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
423
519
  successor = "retry";
424
520
  }
425
521
  else {
522
+ slotEnded = true;
426
523
  next.consecutiveFailures = job.consecutiveFailures + 1;
427
524
  if (successor === "next" && next.consecutiveFailures >= JOB_AUTO_PAUSE_FAILURES) {
428
525
  successor = "none";
@@ -463,7 +560,24 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
463
560
  // occurrence of the new template instead; the failure is not counted.
464
561
  if (retryId && edited.includes(retryId))
465
562
  successor = "next";
466
- const adopt = adoptable[adoptable.length - 1];
563
+ if (slotEnded && next.runsLeft !== undefined)
564
+ next.runsLeft = Math.max(0, next.runsLeft - 1);
565
+ // The end wins over the auto-pause: a last slot that also paused the job ends it.
566
+ const endReason = successor === "retry" ? undefined : jobEndReason(next, job.status, tracked, nowMs, skippedDeadline, opts);
567
+ if (endReason) {
568
+ successor = "none";
569
+ if (next.status === "paused" && job.status === "active") {
570
+ result.autoPaused = result.autoPaused.filter((id) => id !== jobId);
571
+ next.pauseReason = job.pauseReason;
572
+ next.pausedAt = job.pausedAt;
573
+ next.pauseNotifiedAt = job.pauseNotifiedAt;
574
+ }
575
+ next.status = "ended";
576
+ next.endedAt = now.toISOString();
577
+ next.endReason = endReason;
578
+ next.endNotifiedAt = undefined;
579
+ }
580
+ const adopt = endReason ? undefined : adoptable[adoptable.length - 1];
467
581
  let taskId;
468
582
  if (adopt) {
469
583
  taskId = adopt.taskId;
@@ -494,10 +608,22 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
494
608
  }
495
609
  }
496
610
  next.pendingTaskId = taskId;
611
+ // The run's session notice goes in before the job write, so a reader
612
+ // never sees the job ended (or moved on) without it (KTD9).
613
+ if (tracked && successor !== "retry")
614
+ recordJobNotice(store, job, tracked, slotEnded, endReason !== undefined, result, notices);
497
615
  // A miss: another writer moved the job meanwhile. The next pass adopts
498
616
  // the insert on an active job, or cancels it on an inactive one.
499
- if (store.updateJobIf(next, job.revision))
617
+ if (store.updateJobIf(next, job.revision)) {
618
+ if (endReason) {
619
+ result.ended.push(jobId);
620
+ // The sweep skips an ended job, so no later pass cancels a stray pending row.
621
+ for (const t of orphans)
622
+ if (PENDING.has(t.status))
623
+ cancelOccurrence(scheduler, t.taskId, jobId, "ended", opts.actor);
624
+ }
500
625
  return;
626
+ }
501
627
  }
502
628
  result.messages.push(`job ${jobId}: the job row kept changing; left for the next sweep`);
503
629
  // No pass is left to cancel this call's insert on a job that stopped
@@ -508,6 +634,78 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
508
634
  for (const id of inserted)
509
635
  cancelOccurrence(scheduler, id, jobId, latest?.status === "paused" ? "paused" : "removed", opts.actor);
510
636
  }
637
+ /**
638
+ * The session notice of a finished run of a bound job (KTD9), written as a
639
+ * `session_notice` event when the run has a reason: `failed` when its slot
640
+ * failed for good, `matched` when the job is under `match`, the run
641
+ * completed and its result text matches, `ended` when this outcome ends the
642
+ * job. It wakes the session for `failed` under `failures` and for
643
+ * `matched`, while the job is active. A run of another session (made before a rebind), or of a job
644
+ * no longer bound, gets nothing.
645
+ */
646
+ function recordJobNotice(store, job, run, slotEnded, ended, result, decided) {
647
+ const session = jobWakeSession(job);
648
+ if (!session || run.originSessionId !== session || decided.has(run.taskId) || !run.completedAt)
649
+ return;
650
+ decided.add(run.taskId);
651
+ const reasons = [];
652
+ const failed = run.status === "failed" && slotEnded;
653
+ if (failed)
654
+ reasons.push("failed");
655
+ if (job.wake.on === "match" && run.status === "completed") {
656
+ const m = matchWake(job.wake.pattern ?? "", taskResultText(run) ?? "");
657
+ if (m.timedOut)
658
+ result.messages.push(`job ${job.jobId}: ${run.taskId}: the wake pattern timed out; counted as matched`);
659
+ if (m.broken)
660
+ result.messages.push(`job ${job.jobId}: ${run.taskId}: the wake pattern does not compile; counted as matched`);
661
+ if (m.matched)
662
+ reasons.push("matched");
663
+ }
664
+ if (ended)
665
+ reasons.push("ended");
666
+ if (reasons.length === 0)
667
+ return;
668
+ // A run that finished after someone paused or removed its job is a notice for the next prompt, not a wake.
669
+ const wake = job.status === "active" && ((failed && job.wake.on === "failures") || reasons.includes("matched"));
670
+ if (store.recordSessionNotice(run.taskId, { reasons, wake }))
671
+ result.sessionNotices.push(run.taskId);
672
+ }
673
+ /** The `until` bound of a job in ms, or undefined when it has none or the stored text does not parse. */
674
+ function untilBound(job) {
675
+ if (job.until === undefined)
676
+ return undefined;
677
+ try {
678
+ return untilBoundMs(job.until, job.timeZone);
679
+ }
680
+ catch {
681
+ return undefined;
682
+ }
683
+ }
684
+ /** Why a paused job ends with no run: its runs are done, or its end date passed. */
685
+ function pausedEndReason(job, nowMs) {
686
+ if (job.runsLeft !== undefined && job.runsLeft <= 0)
687
+ return "count";
688
+ const bound = untilBound(job);
689
+ return bound !== undefined && bound <= nowMs ? "until" : undefined;
690
+ }
691
+ /**
692
+ * Why `next` ends instead of getting its next occurrence, or undefined. An
693
+ * active job ends when its runs are done or its next regular occurrence
694
+ * would start at or after the `until` bound; a paused one when its runs are
695
+ * done or the bound passed. `status` is the job's status before this pass.
696
+ */
697
+ function jobEndReason(next, status, tracked, nowMs, skippedDeadline, opts) {
698
+ if (status === "paused")
699
+ return pausedEndReason(next, nowMs);
700
+ if (status !== "active")
701
+ return undefined;
702
+ if (next.runsLeft !== undefined && next.runsLeft <= 0)
703
+ return "count";
704
+ const bound = untilBound(next);
705
+ if (bound === undefined)
706
+ return undefined;
707
+ return firstOccurrence(next, tracked, nowMs, skippedDeadline, opts).earliest >= bound ? "until" : undefined;
708
+ }
511
709
  /** `[earliest, deadline]` of the next regular occurrence, in ms. */
512
710
  function firstOccurrence(job, tracked, nowMs, skippedDeadline, opts) {
513
711
  if (opts.firstDeadline !== undefined && !tracked) {
@@ -544,6 +742,7 @@ async function materialize(scheduler, job, taskId, earliest, deadline, anchor) {
544
742
  bodyJson: JSON.stringify(occurrenceBody(job)),
545
743
  originHost: job.originHost && TASK_ORIGIN_HOSTS.has(job.originHost) ? job.originHost : undefined,
546
744
  originCwd: t.cwd,
745
+ originSessionId: jobWakeSession(job),
547
746
  }, { job_id: job.jobId, seq: seqOf(taskId), anchor });
548
747
  }
549
748
  /**
@@ -656,7 +855,7 @@ export async function sweepJobs(scheduler, now = new Date(), opts = {}) {
656
855
  const store = scheduler.ledger();
657
856
  if (!store)
658
857
  return result;
659
- jobs = store.listJobs().filter((j) => j.status !== "removed" || j.pendingTaskId !== undefined);
858
+ jobs = store.listJobs({ status: ["active", "paused", "removed"] }).filter((j) => j.status !== "removed" || j.pendingTaskId !== undefined);
660
859
  }
661
860
  catch (err) {
662
861
  result.messages.push(`job sweep: cannot read the ledger: ${errMessage(err)}`);
@@ -674,6 +873,8 @@ export async function sweepJobs(scheduler, now = new Date(), opts = {}) {
674
873
  result.messages.push(`materialized job occurrence ${id}`);
675
874
  for (const id of result.autoPaused)
676
875
  result.messages.push(`paused job ${id} after ${JOB_AUTO_PAUSE_FAILURES} failed runs`);
876
+ for (const id of result.ended)
877
+ result.messages.push(`ended job ${id}`);
677
878
  return result;
678
879
  }
679
880
  /** Create a job and its first occurrence. Throws {@link JobActionError} on bad input. */
@@ -710,7 +911,18 @@ export async function createJob(scheduler, input, opts = {}) {
710
911
  nextSeq: 1,
711
912
  consecutiveFailures: 0,
712
913
  retryUsed: 0,
914
+ until: validUntil(input.until, schedule.timeZone, now.getTime()),
915
+ runsLeft: validCount(input.count),
916
+ ...(input.wake ? validWake(input.wake, now) : {}),
713
917
  };
918
+ // A job that would end before its first run is a mistake, not a job.
919
+ const bound = untilBound(job);
920
+ if (bound !== undefined) {
921
+ const first = firstOccurrence(job, undefined, now.getTime(), undefined, { firstDeadline }).earliest;
922
+ if (first >= bound) {
923
+ throw new JobActionError(`until "${job.until}" comes before the first run (${new Date(first).toISOString()}); give a later day or instant`, "invalid");
924
+ }
925
+ }
714
926
  store.insertJob(job);
715
927
  try {
716
928
  await sweepJob(scheduler, job.jobId, now, emptyResult(), { firstDeadline, actor: opts.actor });
@@ -749,10 +961,12 @@ function requireJob(store, jobId) {
749
961
  function pendingRow(store, job) {
750
962
  return job.pendingTaskId ? store.get(job.pendingTaskId) : undefined;
751
963
  }
752
- /** Refuse every action but remove on a removed job or one whose stored template does not parse. */
964
+ /** Refuse every action but remove on a removed or ended job, or one whose stored template does not parse. */
753
965
  function requireEditable(job) {
754
966
  if (job.status === "removed")
755
967
  throw new JobActionError("job was removed");
968
+ if (job.status === "ended")
969
+ throw new JobActionError(`job ended (${jobEndText(job.endReason, job.until)}); add a new job`);
756
970
  if (job.pauseReason === CORRUPT)
757
971
  throw new JobActionError(`job ${job.jobId} has a corrupt template; remove it and create it again`);
758
972
  }
@@ -801,6 +1015,13 @@ export async function updateJob(scheduler, jobId, patch, opts = {}) {
801
1015
  template: patch.template !== undefined ? validTemplate(patch.template) : job.template,
802
1016
  caps: validCaps(job.caps, patch.caps),
803
1017
  notify: patch.notify !== undefined ? validNotify(patch.notify) : job.notify,
1018
+ // A new zone moves a day bound, so the kept `until` is checked again.
1019
+ until: patch.until !== undefined || schedule.timeZone !== job.timeZone
1020
+ ? validUntil(patch.until !== undefined ? patch.until : job.until, schedule.timeZone, Date.now())
1021
+ : job.until,
1022
+ runsLeft: patch.count !== undefined ? validCount(patch.count) : job.runsLeft,
1023
+ // A wake edit rebinds the job to the session that makes it; a page edit keeps the binding.
1024
+ ...(patch.wake !== undefined ? validWake(patch.wake, new Date()) : {}),
804
1025
  };
805
1026
  });
806
1027
  cancelPending(scheduler, store, before, "edited", opts.actor);
@@ -855,7 +1076,8 @@ export async function runJobNow(scheduler, jobId, opts = {}) {
855
1076
  if (!row || !LIVE.has(row.status)) {
856
1077
  await sweepJob(scheduler, jobId, new Date(), emptyResult(), { actor: opts.actor });
857
1078
  job = requireJob(store, jobId);
858
- // The sweep may have just auto-paused the job (its third failed slot).
1079
+ // The sweep may have just ended the job or auto-paused it (its third failed slot).
1080
+ requireEditable(job);
859
1081
  refuseIfPaused(job);
860
1082
  row = pendingRow(store, job);
861
1083
  }
@@ -889,7 +1111,7 @@ export async function removeJob(scheduler, jobId, opts = {}) {
889
1111
  export function getJob(scheduler, jobId) {
890
1112
  return ledgerOf(scheduler).getJob(jobId);
891
1113
  }
892
- /** Jobs, oldest first; removed jobs are hidden unless asked for. */
1114
+ /** Jobs, oldest first; removed and ended jobs are hidden unless asked for. */
893
1115
  export function listJobs(scheduler, opts = {}) {
894
1116
  return ledgerOf(scheduler).listJobs(opts.includeRemoved ? {} : { status: ["active", "paused"] });
895
1117
  }
@@ -173,6 +173,13 @@ export interface DispatchResult {
173
173
  session?: RunSession;
174
174
  /** Extra keys for the `completed` event; not on the receipt. */
175
175
  details?: RunDetails;
176
+ /**
177
+ * A command job's summary: the trimmed reply of its summarize step, for
178
+ * the person who reads the notice. `text` stays the command's output.
179
+ */
180
+ summary?: string;
181
+ /** Why a command job's summarize step gave no summary; the run still completed with its output. */
182
+ summaryError?: string;
176
183
  }
177
184
  /**
178
185
  * An error the call must not resend at once (`retryWithBackoff`): the call
@@ -8,7 +8,8 @@
8
8
  * series path. Agents never create command jobs (KD10): a shell-like
9
9
  * argument is refused with the CLI command the user runs instead.
10
10
  */
11
- import { type JobInput } from "./jobs.js";
11
+ import { type JobWakeRule } from "./job-wake.js";
12
+ import { type JobInput, type JobWakeInput } from "./jobs.js";
12
13
  import { type DurationValue } from "./run-limits.js";
13
14
  import type { Scheduler } from "./scheduler.js";
14
15
  import type { JobRecord, JobTools, ProviderName } from "./types.js";
@@ -18,7 +19,7 @@ export type JobRepeat = (typeof JOB_REPEATS)[number];
18
19
  /** True when `repeat` creates a job rather than a one-off task or a series. */
19
20
  export declare function isJobRepeat(repeat: unknown): repeat is JobRepeat;
20
21
  /** Parameters that only mean something with a job repeat. */
21
- export declare const JOB_ONLY_PARAMS: readonly ["every_hours", "days", "window", "time_zone"];
22
+ export declare const JOB_ONLY_PARAMS: readonly ["every_hours", "days", "window", "time_zone", "until", "count", "wake_match"];
22
23
  /** The CLI line that queues a one-off shell command task, which only the user runs. */
23
24
  export declare const QUEUE_ADD_COMMAND_LINE = "tidegap queue add --runner command --cwd <dir> --by <when> '<cmd>'";
24
25
  /**
@@ -45,6 +46,16 @@ export declare function jobUnsupportedRefusal(args: Record<string, unknown>): st
45
46
  * has already refused a list that mixes the two (claudeCodeToolsError).
46
47
  */
47
48
  export declare function jobToolsFor(tools: readonly string[]): JobTools;
49
+ /**
50
+ * The wake rule of a `schedule_task` job call (KTD8), or undefined for
51
+ * none: `wake_session: true` wakes on a failed run, `wake_match` on a run
52
+ * whose output matches (with `wake_session` omitted or true). Throws an
53
+ * Error with a plain message.
54
+ */
55
+ export declare function jobWakeArgs(args: {
56
+ wake_session?: unknown;
57
+ wake_match?: unknown;
58
+ }): JobWakeRule | undefined;
48
59
  /** What both hosts pass to build a prompt job from a `schedule_task` call. */
49
60
  export interface ScheduleJobArgs {
50
61
  prompt: string;
@@ -66,6 +77,11 @@ export interface ScheduleJobArgs {
66
77
  /** The job's own retries per slot and retry delay in ms (`retries`, `retry_delay`); unset follows the settings. */
67
78
  retries?: number;
68
79
  retryDelayMs?: number;
80
+ /** The job's end date (`YYYY-MM-DD` or an ISO instant) and its run count. */
81
+ until?: string;
82
+ count?: number;
83
+ /** Bind the job to the session the call came from (MCP only). */
84
+ wake?: JobWakeInput;
69
85
  host: "mcp" | "openclaw";
70
86
  }
71
87
  /**
@@ -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"]);
@@ -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));
@@ -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 person's read
198
- * marker does not matter here.
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