@tidegap/core 0.23.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.
- package/dist/channels/commands.js +3 -2
- package/dist/channels/format.d.ts +0 -2
- package/dist/channels/format.js +10 -19
- package/dist/channels/telegram.d.ts +13 -1
- package/dist/channels/telegram.js +11 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +3 -3
- package/dist/jobs.d.ts +46 -3
- package/dist/jobs.js +250 -35
- package/dist/redact.d.ts +3 -2
- package/dist/redact.js +8 -2
- package/dist/schedule-job.d.ts +3 -2
- package/dist/schedule-job.js +6 -5
- package/dist/scheduler.d.ts +9 -1
- package/dist/scheduler.js +11 -4
- package/dist/storage/sqlite.js +7 -3
- package/dist/types.d.ts +14 -1
- package/dist/zone-time.d.ts +2 -0
- package/dist/zone-time.js +11 -0
- package/package.json +1 -1
|
@@ -225,10 +225,11 @@ async function runJobAction(action, ref, ctx, listing) {
|
|
|
225
225
|
}
|
|
226
226
|
if (action === "pause")
|
|
227
227
|
return `Paused: ${title}.`;
|
|
228
|
-
if (action === "run")
|
|
229
|
-
return `Runs at the next tick: ${title}.`;
|
|
230
228
|
const after = ctx.getJob(job.jobId);
|
|
231
229
|
const next = after?.pendingTaskId ? jobNextLabel(after, ctx.getTask(after.pendingTaskId), ctx.now()) : undefined;
|
|
230
|
+
// An extra run: the planned run keeps its time.
|
|
231
|
+
if (action === "run")
|
|
232
|
+
return next && next !== JOB_RUNNING_NOW ? `Runs at the next tick: ${title}. The planned run stays: next ${next}.` : `Runs at the next tick: ${title}.`;
|
|
232
233
|
if (next === JOB_RUNNING_NOW)
|
|
233
234
|
return `Resumed: ${title}. A run is in progress.`;
|
|
234
235
|
return next ? `Resumed: ${title}. Next ${next}.` : `Resumed: ${title}.`;
|
|
@@ -137,8 +137,6 @@ export declare function queueMessage(records: readonly TaskRecord<unknown>[], no
|
|
|
137
137
|
};
|
|
138
138
|
/** A job's title: one line, at most 80 characters, else the job id. */
|
|
139
139
|
export declare function jobTitle(job: JobRecord): string;
|
|
140
|
-
/** `HH:MM` in `timeZone` when `at` falls on the same day there as `now`, else `Ddd HH:MM`. */
|
|
141
|
-
export declare function zoneTimeLabel(at: Date, now: Date, timeZone: string): string;
|
|
142
140
|
/** The {@link jobNextLabel} of a job whose occurrence is running. */
|
|
143
141
|
export declare const JOB_RUNNING_NOW = "running now";
|
|
144
142
|
/**
|
package/dist/channels/format.js
CHANGED
|
@@ -19,11 +19,11 @@
|
|
|
19
19
|
* | replies and `/result` | none |
|
|
20
20
|
*/
|
|
21
21
|
import { displayTitle, formatBytes, isRedactedTask, sendableAttachments, stripControlChars, taskActions, taskAttachments, taskAttachmentsSkipped, taskResultText, taskSummaryError, taskSummaryText, } from "../history.js";
|
|
22
|
-
import { JOB_AUTO_PAUSE_FAILURES, jobAutoPauseReason, jobEndText } from "../jobs.js";
|
|
22
|
+
import { JOB_AUTO_PAUSE_FAILURES, jobAutoPauseReason, jobEndText, jobLastRun, jobNextRun, runOutcome } from "../jobs.js";
|
|
23
23
|
import { clip, firstErrorLine, oneLine } from "../notify.js";
|
|
24
24
|
import { localTimeLabel } from "../postpone.js";
|
|
25
25
|
import { problemLine, TICKER_CODES } from "../readiness.js";
|
|
26
|
-
import {
|
|
26
|
+
import { zoneTimeLabel } from "../zone-time.js";
|
|
27
27
|
import { redactPrompt } from "../redact.js";
|
|
28
28
|
import { freshReasonText, shortSessionId } from "../run-session.js";
|
|
29
29
|
import { TELEGRAM_CALLBACK_MAX_BYTES, TELEGRAM_MESSAGE_MAX } from "./telegram.js";
|
|
@@ -387,17 +387,6 @@ function cadenceText(cadence) {
|
|
|
387
387
|
return `at least every ${cadence.every} h`;
|
|
388
388
|
}
|
|
389
389
|
}
|
|
390
|
-
/** `HH:MM` in `timeZone` when `at` falls on the same day there as `now`, else `Ddd HH:MM`. */
|
|
391
|
-
export function zoneTimeLabel(at, now, timeZone) {
|
|
392
|
-
const parts = (d) => {
|
|
393
|
-
// An unknown zone falls back to the system zone.
|
|
394
|
-
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" });
|
|
395
|
-
const p = Object.fromEntries(fmt.formatToParts(d).map((x) => [x.type, x.value]));
|
|
396
|
-
return { day: `${p.year}-${p.month}-${p.day}`, weekday: p.weekday, time: `${p.hour}:${p.minute}` };
|
|
397
|
-
};
|
|
398
|
-
const a = parts(at);
|
|
399
|
-
return a.day === parts(now).day ? a.time : `${a.weekday} ${a.time}`;
|
|
400
|
-
}
|
|
401
390
|
/** The {@link jobNextLabel} of a job whose occurrence is running. */
|
|
402
391
|
export const JOB_RUNNING_NOW = "running now";
|
|
403
392
|
/**
|
|
@@ -433,14 +422,16 @@ function jobLine(job, taskOf, now) {
|
|
|
433
422
|
return `${jobTitle(job)} - ${pausedText(job)}`;
|
|
434
423
|
const parts = [jobTitle(job)];
|
|
435
424
|
parts.push(job.window ? `${cadenceText(job.cadence)} ${job.window.start}-${job.window.end}` : cadenceText(job.cadence));
|
|
436
|
-
const next = jobNextLabel(job,
|
|
425
|
+
const next = jobNextLabel(job, jobNextRun({ get: taskOf }, job), now);
|
|
437
426
|
if (next)
|
|
438
427
|
parts.push(next === JOB_RUNNING_NOW ? next : `next ${next}`);
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
428
|
+
// The last run is an occurrence that ran, never a cancelled one.
|
|
429
|
+
const last = jobLastRun({ get: taskOf }, job);
|
|
430
|
+
const outcome = last && runOutcome(last);
|
|
431
|
+
if (outcome) {
|
|
432
|
+
const at = when(last.completedAt, now, (t) => zoneTimeLabel(t, now, job.timeZone));
|
|
433
|
+
const count = outcome === "failed" && job.consecutiveFailures > 0 ? ` (${job.consecutiveFailures} of ${JOB_AUTO_PAUSE_FAILURES})` : "";
|
|
434
|
+
parts.push(`last ${outcome}${at ? ` ${at}` : ""}${count}`);
|
|
444
435
|
}
|
|
445
436
|
return parts.join(" - ");
|
|
446
437
|
}
|
|
@@ -62,10 +62,22 @@ export declare class TelegramError extends Error {
|
|
|
62
62
|
readonly status?: number | undefined;
|
|
63
63
|
/** Seconds Telegram asked to wait (429). */
|
|
64
64
|
readonly retryAfterS?: number | undefined;
|
|
65
|
+
/**
|
|
66
|
+
* Telegram may have done the call: the time limit ended it (the
|
|
67
|
+
* request may have reached Telegram), or Telegram answered 2xx with a
|
|
68
|
+
* body that is not `ok`. A message sent this way may have arrived.
|
|
69
|
+
*/
|
|
70
|
+
readonly maybeDelivered: boolean;
|
|
65
71
|
name: string;
|
|
66
72
|
constructor(message: string, kind: TelegramErrorKind, method: string, status?: number | undefined,
|
|
67
73
|
/** Seconds Telegram asked to wait (429). */
|
|
68
|
-
retryAfterS?: number | undefined
|
|
74
|
+
retryAfterS?: number | undefined,
|
|
75
|
+
/**
|
|
76
|
+
* Telegram may have done the call: the time limit ended it (the
|
|
77
|
+
* request may have reached Telegram), or Telegram answered 2xx with a
|
|
78
|
+
* body that is not `ok`. A message sent this way may have arrived.
|
|
79
|
+
*/
|
|
80
|
+
maybeDelivered?: boolean);
|
|
69
81
|
}
|
|
70
82
|
/** The Bot API methods that upload a file. */
|
|
71
83
|
export type TelegramFileMethod = "sendPhoto" | "sendDocument";
|
|
@@ -22,15 +22,23 @@ export class TelegramError extends Error {
|
|
|
22
22
|
method;
|
|
23
23
|
status;
|
|
24
24
|
retryAfterS;
|
|
25
|
+
maybeDelivered;
|
|
25
26
|
name = "TelegramError";
|
|
26
27
|
constructor(message, kind, method, status,
|
|
27
28
|
/** Seconds Telegram asked to wait (429). */
|
|
28
|
-
retryAfterS
|
|
29
|
+
retryAfterS,
|
|
30
|
+
/**
|
|
31
|
+
* Telegram may have done the call: the time limit ended it (the
|
|
32
|
+
* request may have reached Telegram), or Telegram answered 2xx with a
|
|
33
|
+
* body that is not `ok`. A message sent this way may have arrived.
|
|
34
|
+
*/
|
|
35
|
+
maybeDelivered = false) {
|
|
29
36
|
super(message);
|
|
30
37
|
this.kind = kind;
|
|
31
38
|
this.method = method;
|
|
32
39
|
this.status = status;
|
|
33
40
|
this.retryAfterS = retryAfterS;
|
|
41
|
+
this.maybeDelivered = maybeDelivered;
|
|
34
42
|
}
|
|
35
43
|
}
|
|
36
44
|
/** True for an `http://127.0.0.1[:port]` or `http://localhost[:port]` base (KTD13: tests and QA only). */
|
|
@@ -95,7 +103,7 @@ export class TelegramClient {
|
|
|
95
103
|
const code = err?.cause?.code;
|
|
96
104
|
const why = typeof code === "string" && /^[A-Z_]+$/.test(code) ? ` (${code})` : "";
|
|
97
105
|
if (timedOut)
|
|
98
|
-
throw new TelegramError(`Telegram ${method}: timed out`, "network", method);
|
|
106
|
+
throw new TelegramError(`Telegram ${method}: timed out`, "network", method, undefined, undefined, true);
|
|
99
107
|
if (err?.name === "AbortError") {
|
|
100
108
|
throw new TelegramError(`Telegram ${method}: aborted`, "network", method);
|
|
101
109
|
}
|
|
@@ -122,7 +130,7 @@ export class TelegramClient {
|
|
|
122
130
|
throw new TelegramError(msg, "conflict", method, status);
|
|
123
131
|
if (status === 429)
|
|
124
132
|
throw new TelegramError(msg, "rate_limited", method, status, env.parameters?.retry_after);
|
|
125
|
-
throw new TelegramError(msg, res.ok ? "api" : "http", method, status);
|
|
133
|
+
throw new TelegramError(msg, res.ok ? "api" : "http", method, status, undefined, res.ok);
|
|
126
134
|
}
|
|
127
135
|
return env.result;
|
|
128
136
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -47,7 +47,7 @@ export { assessReadiness, oldestTickRun, pendingProvidersFromStore, problemLine,
|
|
|
47
47
|
export type { DaemonFact, OldestRun, Readiness, ReadinessCode, ReadinessFacts, ReadinessProblem, RunnerFact, SleepReading, TickRunnersSnapshot, } from "./readiness.js";
|
|
48
48
|
export { LIMIT_RESET_HINT_META_KEY, NEEDS_RESET_TIME, POSTPONE_LABELS, POSTPONE_PRESETS, localTimeLabel, MORNING_START_H, plannedStart, postponeOptions, readLimitResetHint, resolveLimitReset, resolvePostpone, taskProvider, TONIGHT_START_H, writeLimitResetHint, } from "./postpone.js";
|
|
49
49
|
export type { LimitReset, LimitResetSource, PostponeOption, PostponePreset, PostponeTarget, ResolvedPostpone, } from "./postpone.js";
|
|
50
|
-
export { CALLBACK_ACTIONS, CALLBACK_PRESETS, cleanWindowMessage, commandContextFor, callbackFits, encodeCallback, CHANNEL_KINDS, channelQuiet, DELIVERY_CODES, descriptorData, EVENT_KINDS, keepsSecret, eventMessage, isChannelKind, isQuietTime, KIND_DESCRIPTORS, payloadFor, testPayload, TEST_MESSAGE_TEXT, validateFields, WEBHOOK_BODY_VERSION, webhookBody, PUSHOVER_MESSAGES_PATH, isLoopbackSmtpHost, HELP_TEXT, telegramCommands, isLoopbackApiBase, runPreview, runVerdict, NOTICE_EMOJI, noticeStatus, runSummary, structureSummary, LATER_GRAMMAR, laterMenuMessage, laterTarget, LISTING_TTL_MS, messageTitle, nextClockTime, notReadyMessage, osChannel, parseCallback, parseCommand, planNotifications, foldIntoDigest, buildDigest, digestAt, digestDue, parseDigestAt, DEFAULT_DIGEST_AT, DIGEST_AT_META_KEY, DIGEST_LAST_META_KEY, DIGEST_LIST_MAX, DIGEST_SENT_META_KEY, DIGEST_MAX_WINDOW_MS, QUEUE_LIST_MAX, QueueListing, queueMessage, RESULT_MAX_PARTS, resultMessages, attachmentLine, ATTACHMENT_LINE_CHARS, runCallback, runCommand, splitMessage, taskDoneMessage, taskFailedMessage, eventTitle, jobDigestText, jobNextLabel, jobEndedBody, jobEndedMessage, jobEndedTitle, jobPausedMessage, jobPausedTitle, jobTitle,
|
|
50
|
+
export { CALLBACK_ACTIONS, CALLBACK_PRESETS, cleanWindowMessage, commandContextFor, callbackFits, encodeCallback, CHANNEL_KINDS, channelQuiet, DELIVERY_CODES, descriptorData, EVENT_KINDS, keepsSecret, eventMessage, isChannelKind, isQuietTime, KIND_DESCRIPTORS, payloadFor, testPayload, TEST_MESSAGE_TEXT, validateFields, WEBHOOK_BODY_VERSION, webhookBody, PUSHOVER_MESSAGES_PATH, isLoopbackSmtpHost, HELP_TEXT, telegramCommands, isLoopbackApiBase, runPreview, runVerdict, NOTICE_EMOJI, noticeStatus, runSummary, structureSummary, LATER_GRAMMAR, laterMenuMessage, laterTarget, LISTING_TTL_MS, messageTitle, nextClockTime, notReadyMessage, osChannel, parseCallback, parseCommand, planNotifications, foldIntoDigest, buildDigest, digestAt, digestDue, parseDigestAt, DEFAULT_DIGEST_AT, DIGEST_AT_META_KEY, DIGEST_LAST_META_KEY, DIGEST_LIST_MAX, DIGEST_SENT_META_KEY, DIGEST_MAX_WINDOW_MS, QUEUE_LIST_MAX, QueueListing, queueMessage, RESULT_MAX_PARTS, resultMessages, attachmentLine, ATTACHMENT_LINE_CHARS, runCallback, runCommand, splitMessage, taskDoneMessage, taskFailedMessage, eventTitle, jobDigestText, jobNextLabel, jobEndedBody, jobEndedMessage, jobEndedTitle, jobPausedMessage, jobPausedTitle, jobTitle, telegramChatId, TELEGRAM_API_BASE, TELEGRAM_CALL_TIMEOUT_MS, TELEGRAM_UPLOAD_TIMEOUT_MS, TELEGRAM_CALLBACK_MAX_BYTES, TELEGRAM_MESSAGE_MAX, TELEGRAM_PREVIEW_CHARS, TelegramClient, TelegramError, } from "./channels/index.js";
|
|
51
51
|
export type { CallbackAction, CallbackActionName, CallbackOutcome, Channel, ChannelCommand, ChannelEvent, ChannelKind, CleanWindowEvent, DeliveryCode, DeliverySpec, DigestCovers, DigestEvent, DigestInput, JobDigestLine, NoticeStatus, StructuredSummary, JobEndedNotice, JobPausedNotice, FieldErrorCode, FieldInput, FieldOption, FieldValidation, FieldValues, KindDescriptor, KindDescriptorData, KindErrorText, KindField, KindPreset, KindStep, NotificationLevel, NotificationPayload, PayloadEvent, QuietMode, RegistryKind, CommandContext, EventKind, InlineButton, InlineKeyboard, LaterArg, OutgoingFiles, OutgoingMessage, TelegramFileMethod, TelegramUpload, SendJob, TaskRef, TelegramCallbackQuery, TelegramChannelConfig, TelegramChat, TelegramClientOptions, TelegramErrorKind, TelegramMessage, TelegramUpdate, TelegramUser, } from "./channels/index.js";
|
|
52
52
|
export { scoreCandidates, previewRouting, parseCandidate, parseCandidates, candidateId, normalizeRouteWeights, priceForModel, DEFAULT_ROUTE_WEIGHTS, ROUTING_PREVIEW_DISCLOSURE, SCORE_TIE_EPSILON, InvalidCandidateError, InvalidRouteWeightsError, MissingPriceError, } from "./routing.js";
|
|
53
53
|
export type { RouteWeights, RoutingCandidate, RoutingDecision, RoutingPreview, ScoredCandidate, LatencyClass, ModelPrice, ScoreCandidatesOptions, } from "./routing.js";
|
|
@@ -72,10 +72,10 @@ export type { DeferOptions, GridFeed, GridForecast, GridForecastEntry, GridSigna
|
|
|
72
72
|
export { DEFAULT_JOB_CAPS } from "./types.js";
|
|
73
73
|
export { guaranteeText, isCalendarAnchored, JobScheduleError, MAX_EVERY_HOURS, MIN_EVERY_HOURS, nextOccurrence, parseCadence, parseWindow, untilBoundMs, untilText, validateJobSchedule, } from "./job-cadence.js";
|
|
74
74
|
export type { JobSchedule, NextOccurrenceInput } from "./job-cadence.js";
|
|
75
|
-
export { localToUtcMs, systemTimeZone } from "./zone-time.js";
|
|
75
|
+
export { localToUtcMs, systemTimeZone, zoneTimeLabel } from "./zone-time.js";
|
|
76
76
|
export { loadNoticeLanguage, NOTICE_LANGUAGE_KEY, NoticeLanguageError, parseNoticeLanguage } from "./notice-language.js";
|
|
77
77
|
export type { NoticeLanguage, NoticeLanguageSetting } from "./notice-language.js";
|
|
78
|
-
export { createJob, getJob, JOB_AUTO_PAUSE_FAILURES, JOB_AUTO_PAUSE_PREFIX, jobAutoPauseReason, jobEndsText, jobEndText, JOB_INTERRUPTED_ERROR, JOB_MAX_COUNT, DEFAULT_SUMMARIZE_PROMPT, effectiveSummarizePrompt, isDefaultSummarizePrompt, JOB_SECRET_NAME, JobActionError, jobHistory, jobRunLimits, jobWakeSession, listJobs, pauseJob, removeJob, resumeJob, runJobNow, sweepJobs, updateJob, } from "./jobs.js";
|
|
78
|
+
export { createJob, getJob, JOB_AUTO_PAUSE_FAILURES, JOB_AUTO_PAUSE_PREFIX, jobAutoPauseReason, jobEndsText, jobEndText, JOB_INTERRUPTED_ERROR, JOB_MAX_COUNT, DEFAULT_SUMMARIZE_PROMPT, effectiveSummarizePrompt, isDefaultSummarizePrompt, JOB_SECRET_NAME, JobActionError, isExtraRunId, jobHistory, jobLastRun, jobNextRun, jobRunLimits, jobWakeSession, listJobs, pauseJob, removeJob, resumeJob, runJobNow, runNowRefusal, runOutcome, sweepJobs, updateJob, } from "./jobs.js";
|
|
79
79
|
export type { JobActionOptions, JobCapsPatch, JobHistoryEntry, JobInput, JobPatch, JobSweepResult, JobUpdateOptions, JobWakeInput } from "./jobs.js";
|
|
80
80
|
export { JOB_WAKE_FORMS, JOB_WAKE_MATCH_TIMEOUT_MS, JOB_WAKE_PATTERN_MAX_CHARS, JOB_WAKE_TEXT_MAX_CHARS, JobWakeError, matchWake, parseWakeRule, wakePatternError, } from "./job-wake.js";
|
|
81
81
|
export type { JobWakeRule, WakeMatch } from "./job-wake.js";
|
package/dist/index.js
CHANGED
|
@@ -47,7 +47,7 @@ export { assessReadiness, oldestTickRun, pendingProvidersFromStore, problemLine,
|
|
|
47
47
|
// "Later" presets (coherence KTD4 to KTD6).
|
|
48
48
|
export { LIMIT_RESET_HINT_META_KEY, NEEDS_RESET_TIME, POSTPONE_LABELS, POSTPONE_PRESETS, localTimeLabel, MORNING_START_H, plannedStart, postponeOptions, readLimitResetHint, resolveLimitReset, resolvePostpone, taskProvider, TONIGHT_START_H, writeLimitResetHint, } from "./postpone.js";
|
|
49
49
|
// Channels: registry, Telegram client, bot commands and texts (coherence KTD10 to KTD15).
|
|
50
|
-
export { CALLBACK_ACTIONS, CALLBACK_PRESETS, cleanWindowMessage, commandContextFor, callbackFits, encodeCallback, CHANNEL_KINDS, channelQuiet, DELIVERY_CODES, descriptorData, EVENT_KINDS, keepsSecret, eventMessage, isChannelKind, isQuietTime, KIND_DESCRIPTORS, payloadFor, testPayload, TEST_MESSAGE_TEXT, validateFields, WEBHOOK_BODY_VERSION, webhookBody, PUSHOVER_MESSAGES_PATH, isLoopbackSmtpHost, HELP_TEXT, telegramCommands, isLoopbackApiBase, runPreview, runVerdict, NOTICE_EMOJI, noticeStatus, runSummary, structureSummary, LATER_GRAMMAR, laterMenuMessage, laterTarget, LISTING_TTL_MS, messageTitle, nextClockTime, notReadyMessage, osChannel, parseCallback, parseCommand, planNotifications, foldIntoDigest, buildDigest, digestAt, digestDue, parseDigestAt, DEFAULT_DIGEST_AT, DIGEST_AT_META_KEY, DIGEST_LAST_META_KEY, DIGEST_LIST_MAX, DIGEST_SENT_META_KEY, DIGEST_MAX_WINDOW_MS, QUEUE_LIST_MAX, QueueListing, queueMessage, RESULT_MAX_PARTS, resultMessages, attachmentLine, ATTACHMENT_LINE_CHARS, runCallback, runCommand, splitMessage, taskDoneMessage, taskFailedMessage, eventTitle, jobDigestText, jobNextLabel, jobEndedBody, jobEndedMessage, jobEndedTitle, jobPausedMessage, jobPausedTitle, jobTitle,
|
|
50
|
+
export { CALLBACK_ACTIONS, CALLBACK_PRESETS, cleanWindowMessage, commandContextFor, callbackFits, encodeCallback, CHANNEL_KINDS, channelQuiet, DELIVERY_CODES, descriptorData, EVENT_KINDS, keepsSecret, eventMessage, isChannelKind, isQuietTime, KIND_DESCRIPTORS, payloadFor, testPayload, TEST_MESSAGE_TEXT, validateFields, WEBHOOK_BODY_VERSION, webhookBody, PUSHOVER_MESSAGES_PATH, isLoopbackSmtpHost, HELP_TEXT, telegramCommands, isLoopbackApiBase, runPreview, runVerdict, NOTICE_EMOJI, noticeStatus, runSummary, structureSummary, LATER_GRAMMAR, laterMenuMessage, laterTarget, LISTING_TTL_MS, messageTitle, nextClockTime, notReadyMessage, osChannel, parseCallback, parseCommand, planNotifications, foldIntoDigest, buildDigest, digestAt, digestDue, parseDigestAt, DEFAULT_DIGEST_AT, DIGEST_AT_META_KEY, DIGEST_LAST_META_KEY, DIGEST_LIST_MAX, DIGEST_SENT_META_KEY, DIGEST_MAX_WINDOW_MS, QUEUE_LIST_MAX, QueueListing, queueMessage, RESULT_MAX_PARTS, resultMessages, attachmentLine, ATTACHMENT_LINE_CHARS, runCallback, runCommand, splitMessage, taskDoneMessage, taskFailedMessage, eventTitle, jobDigestText, jobNextLabel, jobEndedBody, jobEndedMessage, jobEndedTitle, jobPausedMessage, jobPausedTitle, jobTitle, telegramChatId, TELEGRAM_API_BASE, TELEGRAM_CALL_TIMEOUT_MS, TELEGRAM_UPLOAD_TIMEOUT_MS, TELEGRAM_CALLBACK_MAX_BYTES, TELEGRAM_MESSAGE_MAX, TELEGRAM_PREVIEW_CHARS, TelegramClient, TelegramError, } from "./channels/index.js";
|
|
51
51
|
// Cross-provider routing (ROADMAP item 1).
|
|
52
52
|
export { scoreCandidates, previewRouting, parseCandidate, parseCandidates, candidateId, normalizeRouteWeights, priceForModel, DEFAULT_ROUTE_WEIGHTS, ROUTING_PREVIEW_DISCLOSURE, SCORE_TIE_EPSILON, InvalidCandidateError, InvalidRouteWeightsError, MissingPriceError, } from "./routing.js";
|
|
53
53
|
export { selectWindow, inDeadlineEntries, TOLERANCE_FLOOR_G, TOLERANCE_FRACTION, } from "./select-window.js";
|
|
@@ -66,11 +66,11 @@ export { DEFAULT_JOB_CAPS } from "./types.js";
|
|
|
66
66
|
// Floating recurring jobs: cadence, window and anchor math (KTD5).
|
|
67
67
|
export { guaranteeText, isCalendarAnchored, JobScheduleError, MAX_EVERY_HOURS, MIN_EVERY_HOURS, nextOccurrence, parseCadence, parseWindow, untilBoundMs, untilText, validateJobSchedule, } from "./job-cadence.js";
|
|
68
68
|
// IANA zone helpers shared by the quota and job code.
|
|
69
|
-
export { localToUtcMs, systemTimeZone } from "./zone-time.js";
|
|
69
|
+
export { localToUtcMs, systemTimeZone, zoneTimeLabel } from "./zone-time.js";
|
|
70
70
|
// The notice language a job's summarize step writes in (`tidegap language`).
|
|
71
71
|
export { loadNoticeLanguage, NOTICE_LANGUAGE_KEY, NoticeLanguageError, parseNoticeLanguage } from "./notice-language.js";
|
|
72
72
|
// Floating recurring jobs: actions and the job sweep (KTD2, KTD9).
|
|
73
|
-
export { createJob, getJob, JOB_AUTO_PAUSE_FAILURES, JOB_AUTO_PAUSE_PREFIX, jobAutoPauseReason, jobEndsText, jobEndText, JOB_INTERRUPTED_ERROR, JOB_MAX_COUNT, DEFAULT_SUMMARIZE_PROMPT, effectiveSummarizePrompt, isDefaultSummarizePrompt, JOB_SECRET_NAME, JobActionError, jobHistory, jobRunLimits, jobWakeSession, listJobs, pauseJob, removeJob, resumeJob, runJobNow, sweepJobs, updateJob, } from "./jobs.js";
|
|
73
|
+
export { createJob, getJob, JOB_AUTO_PAUSE_FAILURES, JOB_AUTO_PAUSE_PREFIX, jobAutoPauseReason, jobEndsText, jobEndText, JOB_INTERRUPTED_ERROR, JOB_MAX_COUNT, DEFAULT_SUMMARIZE_PROMPT, effectiveSummarizePrompt, isDefaultSummarizePrompt, JOB_SECRET_NAME, JobActionError, isExtraRunId, jobHistory, jobLastRun, jobNextRun, jobRunLimits, jobWakeSession, listJobs, pauseJob, removeJob, resumeJob, runJobNow, runNowRefusal, runOutcome, sweepJobs, updateJob, } from "./jobs.js";
|
|
74
74
|
// Wake rules of a job bound to a session (KTD7, KTD9).
|
|
75
75
|
export { JOB_WAKE_FORMS, JOB_WAKE_MATCH_TIMEOUT_MS, JOB_WAKE_PATTERN_MAX_CHARS, JOB_WAKE_TEXT_MAX_CHARS, JobWakeError, matchWake, parseWakeRule, wakePatternError, } from "./job-wake.js";
|
|
76
76
|
export { AnthropicAdapter, OpenAIAdapter, GeminiAdapter, OllamaAdapter, DEFAULT_MODEL_BY_PROVIDER, NonRetryableError, permanentError, ProviderRefusalError, } from "./providers/index.js";
|
package/dist/jobs.d.ts
CHANGED
|
@@ -20,6 +20,11 @@
|
|
|
20
20
|
* occurrence;
|
|
21
21
|
* - no occurrence on an active job: materializes one.
|
|
22
22
|
*
|
|
23
|
+
* Run now adds an extra run beside the tracked occurrence
|
|
24
|
+
* (`<job_id>~<seq>x`, tracked as `extraTaskId`), which the sweep records
|
|
25
|
+
* on its own: it becomes the last run, gets the job's retries, and never
|
|
26
|
+
* moves the schedule, the failure count or the runs left.
|
|
27
|
+
*
|
|
23
28
|
* Every job write is a compare-and-set on `revision`. Pause, edit and
|
|
24
29
|
* remove write the job row first, then cancel the tracked occurrence; a
|
|
25
30
|
* sweep whose job write misses leaves its insert to the next pass, which
|
|
@@ -31,6 +36,7 @@ import { type JobWakeRule } from "./job-wake.js";
|
|
|
31
36
|
import { type SleepReading } from "./readiness.js";
|
|
32
37
|
import type { Scheduler } from "./scheduler.js";
|
|
33
38
|
import { type ResolvedRunLimits } from "./run-limits.js";
|
|
39
|
+
import type { TaskStore } from "./storage/sqlite.js";
|
|
34
40
|
import { type JobCadence, type JobCaps, type JobEndReason, type JobNotify, type JobRecord, type JobTemplate, type JobWindow, type TaskRecord, type TaskStatus } from "./types.js";
|
|
35
41
|
/** Why a job action was refused; `code` maps to an HTTP status in the hosts. */
|
|
36
42
|
export declare class JobActionError extends Error {
|
|
@@ -197,6 +203,8 @@ export declare function jobWakeSession(job: Pick<JobRecord, "wake" | "originSess
|
|
|
197
203
|
* the scheduler's settings reader, or without one the settings file.
|
|
198
204
|
*/
|
|
199
205
|
export declare function jobRunLimits(job: JobRecord, scheduler?: Scheduler): ResolvedRunLimits;
|
|
206
|
+
/** True for an extra run's id (`<job>~<seq>x`, which run now adds) or one of its retries (`...xr`, `...xr2`). */
|
|
207
|
+
export declare function isExtraRunId(taskId: string): boolean;
|
|
200
208
|
/**
|
|
201
209
|
* The job sweep (KTD2): for every job, record the outcome of its finished
|
|
202
210
|
* occurrence and keep one live occurrence per active job. Never throws.
|
|
@@ -217,11 +225,46 @@ export declare function pauseJob(scheduler: Scheduler, jobId: string, opts?: Job
|
|
|
217
225
|
/** Resume a paused job: counter reset, one occurrence from now, no backfill (R8). */
|
|
218
226
|
export declare function resumeJob(scheduler: Scheduler, jobId: string, opts?: JobActionOptions): Promise<JobRecord>;
|
|
219
227
|
/**
|
|
220
|
-
* Run a job
|
|
221
|
-
*
|
|
222
|
-
*
|
|
228
|
+
* Run a job once more, now (AS10): an extra run, a new occurrence
|
|
229
|
+
* `<job_id>~<seq>x` of the job's template, due on the next tick, beside the
|
|
230
|
+
* planned occurrence, which keeps its time. Refused on a paused, ended or
|
|
231
|
+
* removed job, and while a run of the job is running or starts within 5
|
|
232
|
+
* minutes ({@link runNowRefusal}). A pending extra run that starts later
|
|
233
|
+
* (the retry of an earlier one) is replaced by this one. An extra run is
|
|
234
|
+
* not a slot: it does not count toward `count`, `until` does not stop it,
|
|
235
|
+
* and it leaves the schedule and the failure count alone; it gets the
|
|
236
|
+
* job's retries. Returns the extra run.
|
|
223
237
|
*/
|
|
224
238
|
export declare function runJobNow(scheduler: Scheduler, jobId: string, opts?: JobActionOptions): Promise<TaskRecord<unknown>>;
|
|
239
|
+
/**
|
|
240
|
+
* Why run now is refused for an active job at `nowMs`, or undefined: a run
|
|
241
|
+
* of the job (the planned occurrence or an extra run) is running, or starts
|
|
242
|
+
* within 5 minutes; an extra run that has not started always counts as
|
|
243
|
+
* starting.
|
|
244
|
+
*/
|
|
245
|
+
export declare function runNowRefusal(store: Pick<TaskStore, "get">, job: JobRecord, nowMs: number): string | undefined;
|
|
246
|
+
/**
|
|
247
|
+
* The job's next run: of its tracked occurrence and its extra run, the live
|
|
248
|
+
* one that runs first (a running one, else the one due first), or undefined.
|
|
249
|
+
*/
|
|
250
|
+
export declare function jobNextRun(store: Pick<TaskStore, "get">, job: JobRecord): TaskRecord<unknown> | undefined;
|
|
251
|
+
/** `ok` for an occurrence that completed, `failed` for one that failed; undefined for one that did not run (pending, running or cancelled). */
|
|
252
|
+
export declare function runOutcome(row: Pick<TaskRecord<unknown>, "status">): "ok" | "failed" | undefined;
|
|
253
|
+
/**
|
|
254
|
+
* The job's last run: the occurrence `lastTaskId` names when it ran
|
|
255
|
+
* (completed or failed), else, with `list`, the job's newest completed or
|
|
256
|
+
* failed occurrence (a job row from before this rule can name a cancelled
|
|
257
|
+
* one). A cancelled occurrence is never the last run.
|
|
258
|
+
*/
|
|
259
|
+
export declare function jobLastRun(store: {
|
|
260
|
+
get(taskId: string): TaskRecord<unknown> | undefined;
|
|
261
|
+
list?(filter: {
|
|
262
|
+
jobId: string;
|
|
263
|
+
status: readonly TaskStatus[];
|
|
264
|
+
newestFirst: boolean;
|
|
265
|
+
limit: number;
|
|
266
|
+
}): TaskRecord<unknown>[];
|
|
267
|
+
}, job: Pick<JobRecord, "jobId" | "lastTaskId">): TaskRecord<unknown> | undefined;
|
|
225
268
|
/** Remove a job: it stops and is hidden; its rows and history stay (AS11). */
|
|
226
269
|
export declare function removeJob(scheduler: Scheduler, jobId: string, opts?: JobActionOptions): Promise<JobRecord>;
|
|
227
270
|
/** One job, removed ones included; undefined when the id is unknown. */
|
package/dist/jobs.js
CHANGED
|
@@ -20,6 +20,11 @@
|
|
|
20
20
|
* occurrence;
|
|
21
21
|
* - no occurrence on an active job: materializes one.
|
|
22
22
|
*
|
|
23
|
+
* Run now adds an extra run beside the tracked occurrence
|
|
24
|
+
* (`<job_id>~<seq>x`, tracked as `extraTaskId`), which the sweep records
|
|
25
|
+
* on its own: it becomes the last run, gets the job's retries, and never
|
|
26
|
+
* moves the schedule, the failure count or the runs left.
|
|
27
|
+
*
|
|
23
28
|
* Every job write is a compare-and-set on `revision`. Pause, edit and
|
|
24
29
|
* remove write the job row first, then cancel the tracked occurrence; a
|
|
25
30
|
* sweep whose job write misses leaves its insert to the next pass, which
|
|
@@ -35,7 +40,7 @@ import { isCalendarAnchored, JobScheduleError, nextOccurrence, untilBoundMs, unt
|
|
|
35
40
|
import { sleptBetween } from "./readiness.js";
|
|
36
41
|
import { capValueError, classifyFailure, FAILURE_CLASSES, isRetryableFailure, isRunLimitCap, loadRunLimitSettings, planRetry, resolveTaskRunLimits, retryPolicyOf, runLimitsFromDetails, versionedCaps, } from "./run-limits.js";
|
|
37
42
|
import { canonicalize } from "./sign.js";
|
|
38
|
-
import { systemTimeZone } from "./zone-time.js";
|
|
43
|
+
import { systemTimeZone, zoneTimeLabel } from "./zone-time.js";
|
|
39
44
|
import { DEFAULT_JOB_CAPS, } from "./types.js";
|
|
40
45
|
/** Why a job action was refused; `code` maps to an HTTP status in the hosts. */
|
|
41
46
|
export class JobActionError extends Error {
|
|
@@ -129,6 +134,13 @@ export function jobAutoPauseReason(pauseReason) {
|
|
|
129
134
|
}
|
|
130
135
|
/** Grace on top of the caps before a running occurrence counts as interrupted. */
|
|
131
136
|
const INTERRUPT_GRACE_MS = 5 * MINUTE_MS;
|
|
137
|
+
/**
|
|
138
|
+
* An extra run's deadline is this long after run now: its retries must fit
|
|
139
|
+
* in it, and a deadline at most a day away never goes to a Batch API.
|
|
140
|
+
*/
|
|
141
|
+
const EXTRA_RUN_WINDOW_MS = 24 * 60 * MINUTE_MS;
|
|
142
|
+
/** Run now is refused when a run of the job starts within this time: that run is the one asked for. */
|
|
143
|
+
const RUN_NOW_SOON_MS = 5 * MINUTE_MS;
|
|
132
144
|
export const JOB_INTERRUPTED_ERROR = "interrupted: the tick stopped during the run";
|
|
133
145
|
// The Batch submit marker lives in history.ts (`taskActions` reads it), so history.ts imports nothing from this module.
|
|
134
146
|
export { BATCH_SUBMIT_INTERRUPTED_ERROR };
|
|
@@ -348,18 +360,22 @@ export function jobRunLimits(job, scheduler) {
|
|
|
348
360
|
function scheduleOf(job) {
|
|
349
361
|
return { cadence: job.cadence, window: job.window, timeZone: job.timeZone };
|
|
350
362
|
}
|
|
351
|
-
/** Sequence number of an occurrence id `<job>~<seq>`,
|
|
363
|
+
/** Sequence number of an occurrence id `<job>~<seq>`, a retry `<job>~<seq>r`, `<job>~<seq>r2`, ..., or an extra run `<job>~<seq>x` and its retries. */
|
|
352
364
|
function seqOf(taskId) {
|
|
353
|
-
const m = /~(\d+)(?:r\d*)?$/.exec(taskId);
|
|
365
|
+
const m = /~(\d+)x?(?:r\d*)?$/.exec(taskId);
|
|
354
366
|
return m ? Number(m[1]) : 0;
|
|
355
367
|
}
|
|
356
|
-
/** Which retry of its slot an occurrence id is: 0 for `<job>~<seq>`, 1 for `...r`, k for `...rk`. */
|
|
368
|
+
/** Which retry of its slot (or extra run) an occurrence id is: 0 for `<job>~<seq>`, 1 for `...r`, k for `...rk`. */
|
|
357
369
|
function retryOrdinal(taskId) {
|
|
358
|
-
const m = /~\d+r(\d*)$/.exec(taskId);
|
|
370
|
+
const m = /~\d+x?r(\d*)$/.exec(taskId);
|
|
359
371
|
if (!m)
|
|
360
372
|
return 0;
|
|
361
373
|
return m[1] ? Number(m[1]) : 1;
|
|
362
374
|
}
|
|
375
|
+
/** True for an extra run's id (`<job>~<seq>x`, which run now adds) or one of its retries (`...xr`, `...xr2`). */
|
|
376
|
+
export function isExtraRunId(taskId) {
|
|
377
|
+
return /~\d+x(?:r\d*)?$/.test(taskId);
|
|
378
|
+
}
|
|
363
379
|
/** The id of retry `k` of the slot of `taskId`: `<job>~<seq>r`, then `r2`, `r3`, ... */
|
|
364
380
|
function retryIdOf(taskId, k) {
|
|
365
381
|
const base = taskId.replace(/r\d*$/, "");
|
|
@@ -406,16 +422,16 @@ function failureClassOf(scheduler, row) {
|
|
|
406
422
|
* for none: its class must allow a retry, the slot must have retries left
|
|
407
423
|
* by the job's retry policy (its own value, the settings, the default), and
|
|
408
424
|
* retry k starts the retry delay times 2^(k−1) after now, no later than the
|
|
409
|
-
* slot's deadline.
|
|
425
|
+
* slot's deadline. `used` is the retries the slot (or extra run) used.
|
|
410
426
|
*/
|
|
411
|
-
function jobRetryAt(scheduler, job, failed, nowMs) {
|
|
427
|
+
function jobRetryAt(scheduler, job, failed, nowMs, used = job.retryUsed) {
|
|
412
428
|
if (!isRetryableFailure(failureClassOf(scheduler, failed)))
|
|
413
429
|
return undefined;
|
|
414
430
|
const deadline = Date.parse(failed.deadline ?? "");
|
|
415
431
|
if (!Number.isFinite(deadline))
|
|
416
432
|
return undefined;
|
|
417
433
|
const plan = planRetry({
|
|
418
|
-
attempt:
|
|
434
|
+
attempt: used + 1,
|
|
419
435
|
...retryPolicyOf(jobRunLimits(job, scheduler)),
|
|
420
436
|
failedAt: nowMs,
|
|
421
437
|
deadline,
|
|
@@ -471,18 +487,21 @@ function emptyResult() {
|
|
|
471
487
|
async function sweepJob(scheduler, jobId, now, result, opts = {}) {
|
|
472
488
|
const store = ledgerOf(scheduler);
|
|
473
489
|
const nowMs = now.getTime();
|
|
490
|
+
await sweepExtraRun(scheduler, jobId, now, result, opts);
|
|
474
491
|
/** Rows this call inserted: cleaned up when every job write misses. */
|
|
475
492
|
const inserted = [];
|
|
476
493
|
/** Runs whose notice this call decided: a second attempt does not match the pattern again. */
|
|
477
494
|
const notices = new Set();
|
|
478
495
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
479
496
|
const job = store.getJob(jobId);
|
|
480
|
-
|
|
497
|
+
// An ended job keeps no occurrence; its extra run was the step above.
|
|
498
|
+
if (!job || job.pauseReason === CORRUPT || job.status === "ended")
|
|
481
499
|
return;
|
|
482
500
|
const tracked = pendingRow(store, job);
|
|
501
|
+
// An extra run (run now) lives beside the tracked occurrence: never an orphan.
|
|
483
502
|
const orphans = store
|
|
484
503
|
.list({ jobId, status: LIVE_STATUSES })
|
|
485
|
-
.filter((t) => t.taskId !== job.pendingTaskId);
|
|
504
|
+
.filter((t) => t.taskId !== job.pendingTaskId && !isExtraRunId(t.taskId));
|
|
486
505
|
// An inactive job keeps no pending occurrence (stop-flag-first rule).
|
|
487
506
|
if (job.status !== "active") {
|
|
488
507
|
let cancelled = false;
|
|
@@ -524,15 +543,14 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
|
|
|
524
543
|
let slotEnded = false;
|
|
525
544
|
if (tracked) {
|
|
526
545
|
next.pendingTaskId = undefined;
|
|
527
|
-
next.lastTaskId = tracked.taskId;
|
|
528
546
|
next.lastRunStartedAt = dispatchedEvent(scheduler, tracked.taskId)?.at ?? job.lastRunStartedAt;
|
|
547
|
+
// Only an occurrence that ran becomes the last run: a cancel (a skip or a job action) never does.
|
|
548
|
+
recordLastRun(store, next, tracked);
|
|
529
549
|
if (tracked.status === "completed") {
|
|
530
|
-
next.lastOutcome = "ok";
|
|
531
550
|
next.consecutiveFailures = 0;
|
|
532
551
|
slotEnded = true;
|
|
533
552
|
}
|
|
534
553
|
else if (tracked.status === "failed") {
|
|
535
|
-
next.lastOutcome = "failed";
|
|
536
554
|
// A run stopped during its Batch submit may have a batch at the
|
|
537
555
|
// provider, and a failed LLM step ran its command already: neither
|
|
538
556
|
// class retries, nor a permanent failure.
|
|
@@ -555,7 +573,6 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
|
|
|
555
573
|
}
|
|
556
574
|
else if (!ACTION_CANCEL_REASONS.has(cancelReason(scheduler, tracked.taskId) ?? "")) {
|
|
557
575
|
// A plain cancel of an occurrence is a skip: the counter stays.
|
|
558
|
-
next.lastOutcome = "skipped";
|
|
559
576
|
skippedDeadline = tracked.deadline;
|
|
560
577
|
}
|
|
561
578
|
}
|
|
@@ -644,6 +661,9 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
|
|
|
644
661
|
if (PENDING.has(t.status))
|
|
645
662
|
cancelOccurrence(scheduler, t.taskId, jobId, "ended", opts.actor);
|
|
646
663
|
}
|
|
664
|
+
// This pass ended or auto-paused the job: its pending extra run is cancelled now, before a tick can start it.
|
|
665
|
+
if (job.status === "active" && next.status !== "active" && next.extraTaskId)
|
|
666
|
+
await sweepExtraRun(scheduler, jobId, now, result, opts);
|
|
647
667
|
return;
|
|
648
668
|
}
|
|
649
669
|
}
|
|
@@ -656,6 +676,98 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
|
|
|
656
676
|
for (const id of inserted)
|
|
657
677
|
cancelOccurrence(scheduler, id, jobId, latest?.status === "paused" ? "paused" : "removed", opts.actor);
|
|
658
678
|
}
|
|
679
|
+
/**
|
|
680
|
+
* Make `run` the job's last run in `next` when it ran (completed or
|
|
681
|
+
* failed) and finished no earlier than the current last run: a regular
|
|
682
|
+
* occurrence and an extra run can finish in either order.
|
|
683
|
+
*/
|
|
684
|
+
function recordLastRun(store, next, run) {
|
|
685
|
+
const outcome = runOutcome(run);
|
|
686
|
+
if (!outcome)
|
|
687
|
+
return;
|
|
688
|
+
const last = next.lastTaskId && next.lastTaskId !== run.taskId ? store.get(next.lastTaskId) : undefined;
|
|
689
|
+
if (last && runOutcome(last) && Date.parse(last.completedAt ?? "") > Date.parse(run.completedAt ?? ""))
|
|
690
|
+
return;
|
|
691
|
+
next.lastTaskId = run.taskId;
|
|
692
|
+
next.lastOutcome = outcome;
|
|
693
|
+
}
|
|
694
|
+
/** The cancel reason a job's state gives a pending row of it: paused, removed or ended. */
|
|
695
|
+
function stoppedReason(status) {
|
|
696
|
+
return status === "removed" ? "removed" : status === "ended" ? "ended" : "paused";
|
|
697
|
+
}
|
|
698
|
+
/**
|
|
699
|
+
* The extra-run step of the sweep (run now). A live extra run is left
|
|
700
|
+
* alone, except a pending one the job no longer runs (the job stopped, or
|
|
701
|
+
* an edit changed what it runs), which is cancelled, and, in the daemon
|
|
702
|
+
* sweep, a running one its tick left, which fails as interrupted. A
|
|
703
|
+
* finished one is recorded once: a completed or failed one becomes the
|
|
704
|
+
* last run; a failure gets the job's retries while the job is active (the
|
|
705
|
+
* retry is the new extra run); a cancelled one records nothing. An extra
|
|
706
|
+
* run never moves the schedule anchor, the failure count or the runs left.
|
|
707
|
+
* An extra-run row the job does not track (a crash between run now's
|
|
708
|
+
* insert and its job write, or a retry insert whose job write missed) is
|
|
709
|
+
* adopted once no extra run is live; older pending ones are cancelled.
|
|
710
|
+
*/
|
|
711
|
+
async function sweepExtraRun(scheduler, jobId, now, result, opts) {
|
|
712
|
+
const store = ledgerOf(scheduler);
|
|
713
|
+
const nowMs = now.getTime();
|
|
714
|
+
const notices = new Set();
|
|
715
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
716
|
+
const job = store.getJob(jobId);
|
|
717
|
+
if (!job || job.pauseReason === CORRUPT)
|
|
718
|
+
return;
|
|
719
|
+
const extra = job.extraTaskId ? store.get(job.extraTaskId) : undefined;
|
|
720
|
+
if (extra && LIVE.has(extra.status)) {
|
|
721
|
+
if (PENDING.has(extra.status)) {
|
|
722
|
+
const reason = job.status !== "active" ? stoppedReason(job.status) : runsCurrentTemplate(extra, job) ? undefined : "edited";
|
|
723
|
+
if (reason && cancelOccurrence(scheduler, extra.taskId, jobId, reason, opts.actor))
|
|
724
|
+
continue;
|
|
725
|
+
}
|
|
726
|
+
else if (extra.status === "running" && opts.interruptCheck) {
|
|
727
|
+
const outcome = interrupted(scheduler, store, job, extra, nowMs, opts.interruptCheck.sleepNow);
|
|
728
|
+
if (outcome === "failed") {
|
|
729
|
+
result.interrupted.push(extra.taskId);
|
|
730
|
+
result.messages.push(`job ${jobId}: ${extra.taskId} ${JOB_INTERRUPTED_ERROR}`);
|
|
731
|
+
continue;
|
|
732
|
+
}
|
|
733
|
+
if (outcome === "submitted") {
|
|
734
|
+
result.messages.push(`job ${jobId}: ${extra.taskId} back to submitted: the tick stopped while it polled the batch`);
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
// Untracked extra-run rows are adopted only when no extra run is live: run now inserts its row before its job write.
|
|
740
|
+
const strays = store.list({ jobId, status: LIVE_STATUSES }).filter((t) => t.taskId !== job.extraTaskId && isExtraRunId(t.taskId));
|
|
741
|
+
if (!job.extraTaskId && strays.length === 0)
|
|
742
|
+
return;
|
|
743
|
+
const next = { ...job, extraTaskId: undefined, updatedAt: now.toISOString() };
|
|
744
|
+
if (extra) {
|
|
745
|
+
recordLastRun(store, next, extra);
|
|
746
|
+
const used = retryOrdinal(extra.taskId);
|
|
747
|
+
const retryAt = extra.status === "failed" && job.status === "active" ? jobRetryAt(scheduler, job, extra, nowMs, used) : undefined;
|
|
748
|
+
if (retryAt !== undefined) {
|
|
749
|
+
const retryId = retryIdOf(extra.taskId, used + 1);
|
|
750
|
+
if (await materialize(scheduler, job, retryId, retryAt, Date.parse(extra.deadline), "retry")) {
|
|
751
|
+
result.retried.push(retryId);
|
|
752
|
+
result.materialized.push(retryId);
|
|
753
|
+
}
|
|
754
|
+
next.extraTaskId = retryId;
|
|
755
|
+
}
|
|
756
|
+
else if (extra.status === "completed" || extra.status === "failed") {
|
|
757
|
+
recordJobNotice(store, job, extra, true, false, result, notices);
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
if (next.extraTaskId === undefined && strays.length > 0) {
|
|
761
|
+
next.extraTaskId = strays[strays.length - 1].taskId;
|
|
762
|
+
for (const t of strays.slice(0, -1))
|
|
763
|
+
if (PENDING.has(t.status))
|
|
764
|
+
cancelOccurrence(scheduler, t.taskId, jobId, "duplicate");
|
|
765
|
+
}
|
|
766
|
+
if (store.updateJobIf(next, job.revision))
|
|
767
|
+
return;
|
|
768
|
+
}
|
|
769
|
+
result.messages.push(`job ${jobId}: the job row kept changing; its extra run is left for the next sweep`);
|
|
770
|
+
}
|
|
659
771
|
/**
|
|
660
772
|
* The session notice of a finished run of a bound job (KTD9), written as a
|
|
661
773
|
* `session_notice` event when the run has a reason: `failed` when its slot
|
|
@@ -753,7 +865,7 @@ function firstOccurrence(job, tracked, nowMs, skippedDeadline, opts) {
|
|
|
753
865
|
const occ = nextOccurrence(schedule, { now: nowMs, lastRunStart, skippedDeadline });
|
|
754
866
|
return { earliest: Date.parse(occ.earliest), deadline: Date.parse(occ.deadline), anchor: occ.anchor };
|
|
755
867
|
}
|
|
756
|
-
async function materialize(scheduler, job, taskId, earliest, deadline, anchor) {
|
|
868
|
+
async function materialize(scheduler, job, taskId, earliest, deadline, anchor, runNow) {
|
|
757
869
|
const t = job.template;
|
|
758
870
|
return scheduler.materializeOccurrence({
|
|
759
871
|
taskId,
|
|
@@ -765,7 +877,7 @@ async function materialize(scheduler, job, taskId, earliest, deadline, anchor) {
|
|
|
765
877
|
originHost: job.originHost && TASK_ORIGIN_HOSTS.has(job.originHost) ? job.originHost : undefined,
|
|
766
878
|
originCwd: t.cwd,
|
|
767
879
|
originSessionId: jobWakeSession(job),
|
|
768
|
-
}, { job_id: job.jobId, seq: seqOf(taskId), anchor });
|
|
880
|
+
}, { job_id: job.jobId, seq: seqOf(taskId), anchor }, runNow ? { runNow } : {});
|
|
769
881
|
}
|
|
770
882
|
/**
|
|
771
883
|
* How long a run may last before the time rule frees it: its time limits
|
|
@@ -877,7 +989,10 @@ export async function sweepJobs(scheduler, now = new Date(), opts = {}) {
|
|
|
877
989
|
const store = scheduler.ledger();
|
|
878
990
|
if (!store)
|
|
879
991
|
return result;
|
|
880
|
-
|
|
992
|
+
// A removed or ended job is swept only while it tracks a row: a run that has not finished, or one not recorded yet.
|
|
993
|
+
jobs = store
|
|
994
|
+
.listJobs({ status: ["active", "paused", "removed", "ended"] })
|
|
995
|
+
.filter((j) => j.status === "active" || j.status === "paused" || j.pendingTaskId !== undefined || j.extraTaskId !== undefined);
|
|
881
996
|
}
|
|
882
997
|
catch (err) {
|
|
883
998
|
result.messages.push(`job sweep: cannot read the ledger: ${errMessage(err)}`);
|
|
@@ -1085,30 +1200,130 @@ export async function resumeJob(scheduler, jobId, opts = {}) {
|
|
|
1085
1200
|
return store.getJob(jobId);
|
|
1086
1201
|
}
|
|
1087
1202
|
/**
|
|
1088
|
-
* Run a job
|
|
1089
|
-
*
|
|
1090
|
-
*
|
|
1203
|
+
* Run a job once more, now (AS10): an extra run, a new occurrence
|
|
1204
|
+
* `<job_id>~<seq>x` of the job's template, due on the next tick, beside the
|
|
1205
|
+
* planned occurrence, which keeps its time. Refused on a paused, ended or
|
|
1206
|
+
* removed job, and while a run of the job is running or starts within 5
|
|
1207
|
+
* minutes ({@link runNowRefusal}). A pending extra run that starts later
|
|
1208
|
+
* (the retry of an earlier one) is replaced by this one. An extra run is
|
|
1209
|
+
* not a slot: it does not count toward `count`, `until` does not stop it,
|
|
1210
|
+
* and it leaves the schedule and the failure count alone; it gets the
|
|
1211
|
+
* job's retries. Returns the extra run.
|
|
1091
1212
|
*/
|
|
1092
1213
|
export async function runJobNow(scheduler, jobId, opts = {}) {
|
|
1093
1214
|
const store = ledgerOf(scheduler);
|
|
1094
|
-
|
|
1215
|
+
requireRunnable(requireJob(store, jobId));
|
|
1216
|
+
// Record what finished first: the sweep may end the job, or pause it after its third failed slot.
|
|
1217
|
+
await sweepJob(scheduler, jobId, new Date(), emptyResult(), { actor: opts.actor });
|
|
1218
|
+
const job = requireJob(store, jobId);
|
|
1219
|
+
requireRunnable(job);
|
|
1220
|
+
const nowMs = Date.now();
|
|
1221
|
+
const busy = runNowRefusal(store, job, nowMs);
|
|
1222
|
+
if (busy)
|
|
1223
|
+
throw new JobActionError(busy);
|
|
1224
|
+
let seq = job.nextSeq;
|
|
1225
|
+
while (!(await materialize(scheduler, job, `${jobId}~${seq}x`, nowMs, nowMs + EXTRA_RUN_WINDOW_MS, "run_now", { actor: opts.actor })))
|
|
1226
|
+
seq++;
|
|
1227
|
+
const taskId = `${jobId}~${seq}x`;
|
|
1228
|
+
let replaced;
|
|
1229
|
+
try {
|
|
1230
|
+
writeJob(store, jobId, (j) => {
|
|
1231
|
+
requireRunnable(j);
|
|
1232
|
+
const next = { ...j, extraTaskId: taskId, nextSeq: Math.max(j.nextSeq, seq + 1) };
|
|
1233
|
+
// A sweep may have adopted the row already.
|
|
1234
|
+
if (j.extraTaskId === taskId)
|
|
1235
|
+
return next;
|
|
1236
|
+
// Another run now may have won the race since the check above.
|
|
1237
|
+
const raced = runNowRefusal(store, j, nowMs);
|
|
1238
|
+
if (raced)
|
|
1239
|
+
throw new JobActionError(raced);
|
|
1240
|
+
const prior = j.extraTaskId ? store.get(j.extraTaskId) : undefined;
|
|
1241
|
+
replaced = prior && PENDING.has(prior.status) ? prior.taskId : undefined;
|
|
1242
|
+
// A prior extra run that finished since the sweep above is recorded here; this run replaces its retry.
|
|
1243
|
+
if (prior)
|
|
1244
|
+
recordLastRun(store, next, prior);
|
|
1245
|
+
return next;
|
|
1246
|
+
});
|
|
1247
|
+
}
|
|
1248
|
+
catch (err) {
|
|
1249
|
+
cancelOccurrence(scheduler, taskId, jobId, "duplicate", opts.actor);
|
|
1250
|
+
throw err;
|
|
1251
|
+
}
|
|
1252
|
+
if (replaced)
|
|
1253
|
+
cancelOccurrence(scheduler, replaced, jobId, "duplicate", opts.actor);
|
|
1254
|
+
return store.get(taskId);
|
|
1255
|
+
}
|
|
1256
|
+
/**
|
|
1257
|
+
* Why run now is refused for an active job at `nowMs`, or undefined: a run
|
|
1258
|
+
* of the job (the planned occurrence or an extra run) is running, or starts
|
|
1259
|
+
* within 5 minutes; an extra run that has not started always counts as
|
|
1260
|
+
* starting.
|
|
1261
|
+
*/
|
|
1262
|
+
export function runNowRefusal(store, job, nowMs) {
|
|
1263
|
+
for (const id of [job.pendingTaskId, job.extraTaskId]) {
|
|
1264
|
+
const row = id ? store.get(id) : undefined;
|
|
1265
|
+
if (!row || !LIVE.has(row.status))
|
|
1266
|
+
continue;
|
|
1267
|
+
if (row.status === "running" || row.status === "submitted")
|
|
1268
|
+
return "an occurrence is already running";
|
|
1269
|
+
const start = dueAt(row);
|
|
1270
|
+
const extraDue = id === job.extraTaskId && row.intensitySource === "expedited";
|
|
1271
|
+
if (extraDue || start <= nowMs + RUN_NOW_SOON_MS) {
|
|
1272
|
+
const at = zoneTimeLabel(new Date(Number.isFinite(start) ? Math.max(start, nowMs) : nowMs), new Date(nowMs), job.timeZone);
|
|
1273
|
+
return `a run is already starting at ${at} (${row.taskId})`;
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
return undefined;
|
|
1277
|
+
}
|
|
1278
|
+
/**
|
|
1279
|
+
* When a pending row becomes due, by the tick's rule: its planned time, or
|
|
1280
|
+
* its earliest start when that is later (a usage-limit deferral); NaN for a
|
|
1281
|
+
* row with no planned time, which is not due.
|
|
1282
|
+
*/
|
|
1283
|
+
function dueAt(row) {
|
|
1284
|
+
const planned = Date.parse(row.scheduledFor ?? "");
|
|
1285
|
+
const earliest = Date.parse(row.notBefore ?? "");
|
|
1286
|
+
return earliest > planned ? earliest : planned;
|
|
1287
|
+
}
|
|
1288
|
+
/** Refuse an action that runs the job on a removed, ended, corrupt or paused one. */
|
|
1289
|
+
function requireRunnable(job) {
|
|
1095
1290
|
requireEditable(job);
|
|
1096
1291
|
refuseIfPaused(job);
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1292
|
+
}
|
|
1293
|
+
/**
|
|
1294
|
+
* The job's next run: of its tracked occurrence and its extra run, the live
|
|
1295
|
+
* one that runs first (a running one, else the one due first), or undefined.
|
|
1296
|
+
*/
|
|
1297
|
+
export function jobNextRun(store, job) {
|
|
1298
|
+
const startOf = (t) => {
|
|
1299
|
+
if (t.status === "running" || t.status === "submitted")
|
|
1300
|
+
return Number.NEGATIVE_INFINITY;
|
|
1301
|
+
const due = dueAt(t);
|
|
1302
|
+
return Number.isNaN(due) ? Number.POSITIVE_INFINITY : due;
|
|
1303
|
+
};
|
|
1304
|
+
let next;
|
|
1305
|
+
for (const id of [job.pendingTaskId, job.extraTaskId]) {
|
|
1306
|
+
const row = id ? store.get(id) : undefined;
|
|
1307
|
+
if (row && LIVE.has(row.status) && (!next || startOf(row) < startOf(next)))
|
|
1308
|
+
next = row;
|
|
1108
1309
|
}
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1310
|
+
return next;
|
|
1311
|
+
}
|
|
1312
|
+
/** `ok` for an occurrence that completed, `failed` for one that failed; undefined for one that did not run (pending, running or cancelled). */
|
|
1313
|
+
export function runOutcome(row) {
|
|
1314
|
+
return row.status === "completed" ? "ok" : row.status === "failed" ? "failed" : undefined;
|
|
1315
|
+
}
|
|
1316
|
+
/**
|
|
1317
|
+
* The job's last run: the occurrence `lastTaskId` names when it ran
|
|
1318
|
+
* (completed or failed), else, with `list`, the job's newest completed or
|
|
1319
|
+
* failed occurrence (a job row from before this rule can name a cancelled
|
|
1320
|
+
* one). A cancelled occurrence is never the last run.
|
|
1321
|
+
*/
|
|
1322
|
+
export function jobLastRun(store, job) {
|
|
1323
|
+
const last = job.lastTaskId ? store.get(job.lastTaskId) : undefined;
|
|
1324
|
+
if (last && runOutcome(last))
|
|
1325
|
+
return last;
|
|
1326
|
+
return store.list?.({ jobId: job.jobId, status: ["completed", "failed"], newestFirst: true, limit: 1 })[0];
|
|
1112
1327
|
}
|
|
1113
1328
|
/** Refuse run now on a paused job, naming the failure when the job paused itself. */
|
|
1114
1329
|
function refuseIfPaused(job) {
|
package/dist/redact.d.ts
CHANGED
|
@@ -19,8 +19,9 @@ export declare const DEFAULT_REDACTION_PATTERNS: ReadonlyArray<RegExp>;
|
|
|
19
19
|
* token that starts with one of them at a cut end: the cut key is too short
|
|
20
20
|
* for its full pattern. `prefix` is a regex source (`Bearer` takes any
|
|
21
21
|
* whitespace after it). `boundary` is true where the pattern starts at a word
|
|
22
|
-
* boundary; `sk
|
|
23
|
-
*
|
|
22
|
+
* boundary; `sk-`, the Telegram token and the Discord webhook path have none,
|
|
23
|
+
* so they are found inside a word too (the Telegram prefix carries its own
|
|
24
|
+
* "no digit before" rule). A new pattern adds its prefix here.
|
|
24
25
|
*/
|
|
25
26
|
export declare const VENDOR_KEY_PREFIXES: ReadonlyArray<{
|
|
26
27
|
prefix: string;
|
package/dist/redact.js
CHANGED
|
@@ -22,6 +22,9 @@ export const DEFAULT_REDACTION_PATTERNS = [
|
|
|
22
22
|
/\bAIza[0-9A-Za-z_\-]{35}\b/g, // Google API key
|
|
23
23
|
/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g, // Slack tokens
|
|
24
24
|
/\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g, // JWT
|
|
25
|
+
// Telegram bot token. No word boundary before it: a Bot API URL puts "bot" right in front.
|
|
26
|
+
/(?<!\d)\d{8,10}:[A-Za-z0-9_-]{35}(?![A-Za-z0-9_-])/g,
|
|
27
|
+
/(?<=discord(?:app)?\.com\/api(?:\/v\d+)?\/webhooks\/\d+\/)[A-Za-z0-9_-]{30,}/g, // Discord webhook token; the id stays
|
|
25
28
|
];
|
|
26
29
|
/**
|
|
27
30
|
* The token prefixes {@link DEFAULT_REDACTION_PATTERNS} match, each with the
|
|
@@ -29,8 +32,9 @@ export const DEFAULT_REDACTION_PATTERNS = [
|
|
|
29
32
|
* token that starts with one of them at a cut end: the cut key is too short
|
|
30
33
|
* for its full pattern. `prefix` is a regex source (`Bearer` takes any
|
|
31
34
|
* whitespace after it). `boundary` is true where the pattern starts at a word
|
|
32
|
-
* boundary; `sk
|
|
33
|
-
*
|
|
35
|
+
* boundary; `sk-`, the Telegram token and the Discord webhook path have none,
|
|
36
|
+
* so they are found inside a word too (the Telegram prefix carries its own
|
|
37
|
+
* "no digit before" rule). A new pattern adds its prefix here.
|
|
34
38
|
*/
|
|
35
39
|
export const VENDOR_KEY_PREFIXES = [
|
|
36
40
|
{ prefix: "sk-", body: "A-Za-z0-9_\\-", boundary: false },
|
|
@@ -41,6 +45,8 @@ export const VENDOR_KEY_PREFIXES = [
|
|
|
41
45
|
{ prefix: "AIza", body: "0-9A-Za-z_\\-", boundary: true },
|
|
42
46
|
{ prefix: "xox", body: "A-Za-z0-9-", boundary: true },
|
|
43
47
|
{ prefix: "eyJ", body: "A-Za-z0-9_\\-.", boundary: true },
|
|
48
|
+
{ prefix: "(?<!\\d)\\d{8,10}:", body: "A-Za-z0-9_\\-", boundary: false },
|
|
49
|
+
{ prefix: "discord(?:app)?\\.com/api(?:/v\\d+)?/webhooks/\\d+/", body: "A-Za-z0-9_\\-", boundary: false },
|
|
44
50
|
];
|
|
45
51
|
/** One regex per prefix: the prefix and at least one body character, up to the end of the text. */
|
|
46
52
|
const TRAILING_KEY = VENDOR_KEY_PREFIXES.map(({ prefix, body, boundary, ignoreCase }) => new RegExp(`${boundary ? "(?<![A-Za-z0-9_])" : ""}${prefix}[${body}]+$`, ignoreCase ? "i" : ""));
|
package/dist/schedule-job.d.ts
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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. */
|
package/dist/schedule-job.js
CHANGED
|
@@ -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
|
|
235
|
-
const live =
|
|
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
|
-
...(
|
|
243
|
+
...(lastOutcome ? { lastOutcome } : {}),
|
|
243
244
|
...(job.pauseReason ? { pauseReason: job.pauseReason } : {}),
|
|
244
245
|
};
|
|
245
246
|
}
|
package/dist/scheduler.d.ts
CHANGED
|
@@ -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
|
|
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
|
-
|
|
370
|
-
|
|
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
|
}
|
package/dist/storage/sqlite.js
CHANGED
|
@@ -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
|
|
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
|
-
/**
|
|
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). */
|
package/dist/zone-time.d.ts
CHANGED
|
@@ -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
|