@tidegap/core 0.19.0 → 0.21.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/README.md +1 -1
- package/dist/agent-snippet.d.ts +30 -0
- package/dist/agent-snippet.js +120 -0
- package/dist/channels/commands.d.ts +137 -0
- package/dist/channels/commands.js +377 -0
- package/dist/channels/delivery-codes.d.ts +9 -0
- package/dist/channels/delivery-codes.js +53 -0
- package/dist/channels/digest.d.ts +102 -0
- package/dist/channels/digest.js +146 -0
- package/dist/channels/format.d.ts +138 -0
- package/dist/channels/format.js +425 -0
- package/dist/channels/index.d.ts +15 -0
- package/dist/channels/index.js +15 -0
- package/dist/channels/kinds/command.d.ts +13 -0
- package/dist/channels/kinds/command.js +65 -0
- package/dist/channels/kinds/discord.d.ts +16 -0
- package/dist/channels/kinds/discord.js +67 -0
- package/dist/channels/kinds/email.d.ts +20 -0
- package/dist/channels/kinds/email.js +162 -0
- package/dist/channels/kinds/index.d.ts +8 -0
- package/dist/channels/kinds/index.js +17 -0
- package/dist/channels/kinds/ntfy.d.ts +25 -0
- package/dist/channels/kinds/ntfy.js +163 -0
- package/dist/channels/kinds/pushover.d.ts +11 -0
- package/dist/channels/kinds/pushover.js +77 -0
- package/dist/channels/kinds/shared.d.ts +25 -0
- package/dist/channels/kinds/shared.js +39 -0
- package/dist/channels/kinds/shortcuts.d.ts +9 -0
- package/dist/channels/kinds/shortcuts.js +45 -0
- package/dist/channels/kinds/slack.d.ts +8 -0
- package/dist/channels/kinds/slack.js +57 -0
- package/dist/channels/kinds/telegram.d.ts +4 -0
- package/dist/channels/kinds/telegram.js +26 -0
- package/dist/channels/kinds/webhook.d.ts +30 -0
- package/dist/channels/kinds/webhook.js +177 -0
- package/dist/channels/payload.d.ts +36 -0
- package/dist/channels/payload.js +61 -0
- package/dist/channels/plan.d.ts +24 -0
- package/dist/channels/plan.js +66 -0
- package/dist/channels/registry.d.ts +191 -0
- package/dist/channels/registry.js +125 -0
- package/dist/channels/telegram.d.ts +110 -0
- package/dist/channels/telegram.js +168 -0
- package/dist/channels/types.d.ts +107 -0
- package/dist/channels/types.js +26 -0
- package/dist/claude-tools.d.ts +29 -0
- package/dist/claude-tools.js +49 -0
- package/dist/data/tables.generated.d.ts +6 -0
- package/dist/data/tables.generated.js +37 -0
- package/dist/energy.d.ts +84 -0
- package/dist/energy.js +138 -0
- package/dist/grid.d.ts +17 -2
- package/dist/grid.js +43 -4
- package/dist/handoff.d.ts +171 -0
- package/dist/handoff.js +482 -0
- package/dist/history.d.ts +17 -0
- package/dist/history.js +14 -1
- package/dist/index.d.ts +49 -15
- package/dist/index.js +36 -8
- package/dist/job-cadence.d.ts +76 -0
- package/dist/job-cadence.js +240 -0
- package/dist/jobs.d.ts +183 -0
- package/dist/jobs.js +917 -0
- package/dist/notify.d.ts +11 -0
- package/dist/notify.js +19 -4
- package/dist/postpone.d.ts +113 -0
- package/dist/postpone.js +185 -0
- package/dist/providers/anthropic.js +14 -8
- package/dist/providers/base.d.ts +145 -2
- package/dist/providers/base.js +41 -1
- package/dist/providers/budget.d.ts +25 -0
- package/dist/providers/budget.js +57 -0
- package/dist/providers/defaults.js +4 -0
- package/dist/providers/defer.d.ts +16 -0
- package/dist/providers/defer.js +31 -0
- package/dist/providers/gemini.d.ts +4 -0
- package/dist/providers/gemini.js +34 -24
- package/dist/providers/http.d.ts +40 -0
- package/dist/providers/http.js +82 -0
- package/dist/providers/index.d.ts +2 -2
- package/dist/providers/index.js +1 -1
- package/dist/providers/ollama.d.ts +4 -0
- package/dist/providers/ollama.js +32 -25
- package/dist/providers/openai.js +11 -9
- package/dist/providers/timeout.d.ts +36 -0
- package/dist/providers/timeout.js +71 -0
- package/dist/quota.d.ts +7 -2
- package/dist/quota.js +12 -27
- package/dist/readiness.d.ts +205 -0
- package/dist/readiness.js +326 -0
- package/dist/redact.d.ts +42 -0
- package/dist/redact.js +110 -0
- package/dist/region-host.d.ts +30 -0
- package/dist/region-host.js +69 -0
- package/dist/region.d.ts +102 -20
- package/dist/region.js +175 -23
- package/dist/run-limits.d.ts +268 -0
- package/dist/run-limits.js +572 -0
- package/dist/run-session.d.ts +36 -0
- package/dist/run-session.js +72 -0
- package/dist/schedule-job.d.ts +118 -0
- package/dist/schedule-job.js +243 -0
- package/dist/scheduler.d.ts +391 -18
- package/dist/scheduler.js +1341 -177
- package/dist/sign.d.ts +8 -1
- package/dist/sign.js +49 -3
- package/dist/storage/sqlite.d.ts +183 -5
- package/dist/storage/sqlite.js +720 -19
- package/dist/task-events.d.ts +117 -0
- package/dist/task-events.js +345 -0
- package/dist/tool-surface.d.ts +31 -2
- package/dist/tool-surface.js +390 -65
- package/dist/types.d.ts +267 -3
- package/dist/types.js +6 -1
- package/dist/zone-time.d.ts +22 -0
- package/dist/zone-time.js +76 -0
- package/package.json +13 -5
- package/dist/aggregator.d.ts.map +0 -1
- package/dist/aggregator.js.map +0 -1
- package/dist/budget.d.ts.map +0 -1
- package/dist/budget.js.map +0 -1
- package/dist/data/tables.generated.d.ts.map +0 -1
- package/dist/data/tables.generated.js.map +0 -1
- package/dist/energy.d.ts.map +0 -1
- package/dist/energy.js.map +0 -1
- package/dist/grid.d.ts.map +0 -1
- package/dist/grid.js.map +0 -1
- package/dist/history.d.ts.map +0 -1
- package/dist/history.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/notify.d.ts.map +0 -1
- package/dist/notify.js.map +0 -1
- package/dist/paths.d.ts.map +0 -1
- package/dist/paths.js.map +0 -1
- package/dist/providers/anthropic.d.ts.map +0 -1
- package/dist/providers/anthropic.js.map +0 -1
- package/dist/providers/base.d.ts.map +0 -1
- package/dist/providers/base.js.map +0 -1
- package/dist/providers/defaults.d.ts.map +0 -1
- package/dist/providers/defaults.js.map +0 -1
- package/dist/providers/gemini.d.ts.map +0 -1
- package/dist/providers/gemini.js.map +0 -1
- package/dist/providers/index.d.ts.map +0 -1
- package/dist/providers/index.js.map +0 -1
- package/dist/providers/ollama.d.ts.map +0 -1
- package/dist/providers/ollama.js.map +0 -1
- package/dist/providers/openai.d.ts.map +0 -1
- package/dist/providers/openai.js.map +0 -1
- package/dist/quota.d.ts.map +0 -1
- package/dist/quota.js.map +0 -1
- package/dist/recommend.d.ts.map +0 -1
- package/dist/recommend.js.map +0 -1
- package/dist/redact.d.ts.map +0 -1
- package/dist/redact.js.map +0 -1
- package/dist/region.d.ts.map +0 -1
- package/dist/region.js.map +0 -1
- package/dist/routing.d.ts.map +0 -1
- package/dist/routing.js.map +0 -1
- package/dist/scheduler.d.ts.map +0 -1
- package/dist/scheduler.js.map +0 -1
- package/dist/select-window.d.ts.map +0 -1
- package/dist/select-window.js.map +0 -1
- package/dist/sign.d.ts.map +0 -1
- package/dist/sign.js.map +0 -1
- package/dist/storage/sqlite.d.ts.map +0 -1
- package/dist/storage/sqlite.js.map +0 -1
- package/dist/tool-surface.d.ts.map +0 -1
- package/dist/tool-surface.js.map +0 -1
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js.map +0 -1
package/dist/history.js
CHANGED
|
@@ -130,6 +130,15 @@ export function deadlineKindLabel(record, quota = {}) {
|
|
|
130
130
|
const resetAt = new Date(deadlineMs + schedule.marginH * 3_600_000);
|
|
131
131
|
return `${label}, reset_at ${resetAt.toISOString()}, margin_h ${schedule.marginH}`;
|
|
132
132
|
}
|
|
133
|
+
/**
|
|
134
|
+
* The error of a row whose Batch submit a forced stop interrupted (batch 25
|
|
135
|
+
* KTD5). The provider may hold a batch for it, so no path runs it again:
|
|
136
|
+
* `retryTask` and the Python `retry_task` refuse it, and the sweep does not
|
|
137
|
+
* retry it. The text is the marker; `test/fixtures/interrupted-batch-submit.json`
|
|
138
|
+
* shares it with the Python core. It lives here, not in `jobs.ts`, so this
|
|
139
|
+
* module imports nothing from `jobs.ts` (which imports `deriveTitle` from here).
|
|
140
|
+
*/
|
|
141
|
+
export const BATCH_SUBMIT_INTERRUPTED_ERROR = "interrupted: the tick stopped during the Batch submit; the provider may have accepted the batch, so check the provider's batch list before you enqueue the task again";
|
|
133
142
|
const PENDING = new Set(["queued", "scheduled", "submitted", "running"]);
|
|
134
143
|
/** True when the task repeats (a stored rule other than `none`). */
|
|
135
144
|
export function isRepeating(record) {
|
|
@@ -146,8 +155,12 @@ export function taskActions(record) {
|
|
|
146
155
|
stopSeries: pending && isRepeating(record),
|
|
147
156
|
reschedule: movable && providerCall,
|
|
148
157
|
runNow: movable && providerCall,
|
|
149
|
-
|
|
158
|
+
later: movable && providerCall,
|
|
159
|
+
// A command job's occurrence has no conversation to continue.
|
|
160
|
+
reply: record.status === "completed" && providerCall && spec?.provider !== "command",
|
|
150
161
|
markRead: record.status === "completed" || record.status === "failed",
|
|
162
|
+
// The same rule as `Scheduler.retryLater` refuses by.
|
|
163
|
+
retry: record.status === "failed" && providerCall && !record.jobId && record.error !== BATCH_SUBMIT_INTERRUPTED_ERROR,
|
|
151
164
|
};
|
|
152
165
|
}
|
|
153
166
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -38,38 +38,72 @@
|
|
|
38
38
|
* host (scripts, notebooks) rather than being bundled into a third-party
|
|
39
39
|
* plugin, so its `os.environ` fallbacks stay for ergonomics.
|
|
40
40
|
*/
|
|
41
|
-
export { CarbonBudgetExceededError, defer, InvalidDeadlineError, LAST_TICK_META_KEY, pickBestWindow, Scheduler, TaskActionError, } from "./scheduler.js";
|
|
42
|
-
export type { ReplyOptions, RescheduleTarget, SchedulerOptions, TickAdapters, } from "./scheduler.js";
|
|
41
|
+
export { CarbonBudgetExceededError, COMMAND_MAX_CHARS, defer, InvalidDeadlineError, LAST_TICK_META_KEY, pickBestWindow, Scheduler, TaskActionError, } from "./scheduler.js";
|
|
42
|
+
export type { ReplyOptions, RescheduleTarget, SchedulerOptions, ActorOptions, RetryResult, TickAdapters, TickDetails, TickOptions, LockedTick, } from "./scheduler.js";
|
|
43
43
|
export { recommendWindow } from "./recommend.js";
|
|
44
44
|
export { TITLE_MAX_CHARS, deadlineKindLabel, deriveTitle, displayTitle, isRepeating, isValidSessionId, resumeCommand, SESSION_ID_PATTERN, shellQuote, taskActions, stripControlChars, capHistory, HISTORY_MAX_CHARS, taskHistory, taskPrompt, taskResultText, } from "./history.js";
|
|
45
45
|
export type { TaskActions } from "./history.js";
|
|
46
|
+
export { assessReadiness, oldestTickRun, pendingProvidersFromStore, problemLine, readTickRunners, readTickSleep, sleepReadNeeded, runnersFromSnapshot, sleptBetween, snapshotIsFresh, TICKER_CODES, tickIntervalFor, TICK_RUNNERS_META_KEY, TICK_BY_META_KEY, TICK_SLEEP_META_KEY, writeTickRunners, writeTickSleep, } from "./readiness.js";
|
|
47
|
+
export type { DaemonFact, OldestRun, Readiness, ReadinessCode, ReadinessFacts, ReadinessProblem, RunnerFact, SleepReading, TickRunnersSnapshot, } from "./readiness.js";
|
|
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
|
+
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, isRedactedTask, runPreview, 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, runCallback, runCommand, splitMessage, taskDoneMessage, taskFailedMessage, eventTitle, jobDigestText, jobNextLabel, jobPausedMessage, jobPausedTitle, jobTitle, zoneTimeLabel, telegramChatId, TELEGRAM_API_BASE, TELEGRAM_CALL_TIMEOUT_MS, TELEGRAM_CALLBACK_MAX_BYTES, TELEGRAM_MESSAGE_MAX, TELEGRAM_PREVIEW_CHARS, TelegramClient, TelegramError, } from "./channels/index.js";
|
|
51
|
+
export type { CallbackAction, CallbackActionName, CallbackOutcome, Channel, ChannelCommand, ChannelEvent, ChannelKind, CleanWindowEvent, DeliveryCode, DeliverySpec, DigestCovers, DigestEvent, DigestInput, JobDigestLine, JobPausedNotice, FieldErrorCode, FieldInput, FieldOption, FieldValidation, FieldValues, KindDescriptor, KindDescriptorData, KindErrorText, KindField, KindPreset, KindStep, NotificationLevel, NotificationPayload, PayloadEvent, QuietMode, RegistryKind, CommandContext, EventKind, InlineButton, InlineKeyboard, LaterArg, OutgoingMessage, SendJob, TaskRef, TelegramCallbackQuery, TelegramChannelConfig, TelegramChat, TelegramClientOptions, TelegramErrorKind, TelegramMessage, TelegramUpdate, TelegramUser, } from "./channels/index.js";
|
|
46
52
|
export { scoreCandidates, previewRouting, parseCandidate, parseCandidates, candidateId, normalizeRouteWeights, priceForModel, DEFAULT_ROUTE_WEIGHTS, ROUTING_PREVIEW_DISCLOSURE, SCORE_TIE_EPSILON, InvalidCandidateError, InvalidRouteWeightsError, MissingPriceError, } from "./routing.js";
|
|
47
53
|
export type { RouteWeights, RoutingCandidate, RoutingDecision, RoutingPreview, ScoredCandidate, LatencyClass, ModelPrice, ScoreCandidatesOptions, } from "./routing.js";
|
|
48
54
|
export { selectWindow, inDeadlineEntries, TOLERANCE_FLOOR_G, TOLERANCE_FRACTION, } from "./select-window.js";
|
|
49
55
|
export type { SelectWindowOptions, SelectWindowResult, } from "./select-window.js";
|
|
50
56
|
export { ASSUMED_KWH_PER_CALL, classifyBand, aggregateStats, aggregateByRegion, bandHistogram, achievements, } from "./aggregator.js";
|
|
51
57
|
export type { CarbonStats, RegionStats, BandHistogram, Achievement, } from "./aggregator.js";
|
|
52
|
-
export { NOTIFY_PREVIEW_CHARS, WIN_NOTIFY_BODY_VAR, WIN_NOTIFY_TITLE_VAR, osNotifyCommand, taskNotificationContent, } from "./notify.js";
|
|
58
|
+
export { NOTIFY_PREVIEW_CHARS, WIN_NOTIFY_BODY_VAR, WIN_NOTIFY_TITLE_VAR, firstErrorLine, osNotifyCommand, taskNotificationContent, } from "./notify.js";
|
|
53
59
|
export type { OsNotifyCommand, OsNotifyOptions } from "./notify.js";
|
|
60
|
+
export { CLAUDE_CODE_TOOL_ALLOWLIST, DEFAULT_CLAUDE_CODE_TOOLS, DEFAULT_ORIGIN_TOOLS, claudeCodeToolsError, includesFileTool, includesWebTool, } from "./claude-tools.js";
|
|
61
|
+
export { HANDOFF_PATH_MAX_CHARS, HANDOFF_PROFILES, PROFILE_TOOLS, defaultDbPath, handoffCwdError, isDefaultLedger, latestResultFile, nodeHandoffFs, outputPathError, profileTools, PROTECTED_HOME_DIRS, resultFileText, resultPathError, removeWakeMarker, sameTools, taskWorkShape, WAKE_MARKER_MAX_AGE_MS, wakeError, wakeMarkerPath, wakeMarkersDir, writeWakeMarker, } from "./handoff.js";
|
|
62
|
+
export type { HandoffFs, HandoffFsEntry, HandoffPathContext, HandoffProfile, HandoffSpec, ProfileChoice, TaskWorkShape, } from "./handoff.js";
|
|
63
|
+
export { forkCommand, freshReasonText, runSessionSummary, shortSessionId, taskOrigin, tokensLabel } from "./run-session.js";
|
|
64
|
+
export type { FreshReason, RunSession, RunSessionMode } from "./run-session.js";
|
|
54
65
|
export { carbonBudgetConfigPath, carbonBudgetStatus, carbonBudgetUsage, loadCarbonBudgetConfig, parseKeyValues, KEY_PREFIX, receiptCarbonG, windowBounds, } from "./budget.js";
|
|
55
66
|
export type { CarbonAlert, CarbonBudgetConfig, CarbonBudgetEnv, CarbonBudgetStatus, CarbonBudgetUsage, CarbonBudgetWindowKind, LoadCarbonBudgetOptions, } from "./budget.js";
|
|
56
67
|
export { DEFAULT_QUOTA_MARGIN_H, loadQuotaResetConfig, nextQuotaReset, prepareTick, previousQuotaReset, replanSweep, resolveQuotaDeadline, resolveQuotaProvider, sweepQuotaDeadlines, } from "./quota.js";
|
|
57
68
|
export type { LoadQuotaResetOptions, QuotaResetConfig, QuotaResetSchedule, ResolveQuotaProviderResult, } from "./quota.js";
|
|
58
|
-
export { mockGridFeed, electricityMapsFeed, ukCarbonIntensityFeed, eiaFeed, entsoeFeed, wattTimeFeed, multiSourceGridFeed, buildDefaultGridFeed, } from "./grid.js";
|
|
59
|
-
export type { GridFeedCredentials } from "./grid.js";
|
|
60
|
-
export type { DeferOptions, GridFeed, GridForecast, GridForecastEntry, GridSignalType, CarbonReceipt, DeadlineKind, ProviderCallSpec, ProviderName, RecommendAlternative, RecommendOptions, RecommendResult, RepeatRule, TaskRecord, TaskMessage, TaskOriginHost, TaskStatus, TickResult, TickResultEntry, } from "./types.js";
|
|
61
|
-
export {
|
|
62
|
-
export
|
|
63
|
-
export {
|
|
64
|
-
export
|
|
65
|
-
export {
|
|
66
|
-
export type {
|
|
67
|
-
export {
|
|
69
|
+
export { mockGridFeed, electricityMapsFeed, ukCarbonIntensityFeed, eiaFeed, entsoeFeed, wattTimeFeed, multiSourceGridFeed, buildDefaultGridFeed, regionDataSource, } from "./grid.js";
|
|
70
|
+
export type { GridFeedCredentials, RegionDataSource } from "./grid.js";
|
|
71
|
+
export type { DeferOptions, GridFeed, GridForecast, GridForecastEntry, GridSignalType, CarbonReceipt, ReceiptModelEntry, TokenCounts, DeadlineKind, ProviderCallOrigin, ProviderCallSpec, ProviderName, RecommendAlternative, RecommendOptions, RecommendResult, RepeatRule, TaskRecord, TaskMessage, TaskOriginHost, TaskStatus, TickResult, TickResultEntry, JobCadence, JobCaps, JobNotify, JobOutcome, JobRecord, JobStatus, JobTemplate, JobTools, JobWindow, Occurrence, Weekday, } from "./types.js";
|
|
72
|
+
export { DEFAULT_JOB_CAPS } from "./types.js";
|
|
73
|
+
export { guaranteeText, isCalendarAnchored, JobScheduleError, MAX_EVERY_HOURS, MIN_EVERY_HOURS, nextOccurrence, parseCadence, parseWindow, validateJobSchedule, } from "./job-cadence.js";
|
|
74
|
+
export type { JobSchedule, NextOccurrenceInput } from "./job-cadence.js";
|
|
75
|
+
export { localToUtcMs, systemTimeZone } from "./zone-time.js";
|
|
76
|
+
export { createJob, getJob, JOB_AUTO_PAUSE_FAILURES, JOB_AUTO_PAUSE_PREFIX, jobAutoPauseReason, JOB_INTERRUPTED_ERROR, JOB_SECRET_NAME, JobActionError, jobHistory, jobRunLimits, listJobs, pauseJob, removeJob, resumeJob, runJobNow, sweepJobs, updateJob, } from "./jobs.js";
|
|
77
|
+
export type { JobActionOptions, JobCapsPatch, JobHistoryEntry, JobInput, JobPatch, JobSweepResult, JobUpdateOptions } from "./jobs.js";
|
|
78
|
+
export { AnthropicAdapter, OpenAIAdapter, GeminiAdapter, OllamaAdapter, DEFAULT_MODEL_BY_PROVIDER, NonRetryableError, permanentError, ProviderRefusalError, } from "./providers/index.js";
|
|
79
|
+
export { budgetMaxTokens, BudgetExceededError } from "./providers/budget.js";
|
|
80
|
+
export { MAX_TIMER_MS, withLlmTimeout } from "./providers/timeout.js";
|
|
81
|
+
export type { LlmRequestOptions } from "./providers/timeout.js";
|
|
82
|
+
export { httpFetch, limitDispatcher } from "./providers/http.js";
|
|
83
|
+
export { redactPrompt, SCRUB_MIN_LENGTH, scrubCutEdges, scrubValues } from "./redact.js";
|
|
84
|
+
export { retryWithBackoff } from "./scheduler.js";
|
|
85
|
+
export { ProviderDeferError } from "./providers/defer.js";
|
|
86
|
+
export type { BatchHandle, DispatchOptions, DispatchOrigin, DispatchResult, ModelUsage, ProviderAdapter, RunDetails, } from "./providers/index.js";
|
|
87
|
+
export { SESSION_NOTICE_MAX_AGE_MS, SESSION_NOTICES_SINCE_META_KEY, TaskStore } from "./storage/sqlite.js";
|
|
88
|
+
export { PROGRESS_BUSY_MS, PROGRESS_GAP_MS, PROGRESS_LINE_MAX_CHARS, PROGRESS_MAX_EVENTS, PROGRESS_QUIET_MS, TASK_EVENT_KINDS, cleanProgressText, createProgressRecorder, attemptLines, eventSummary, formatTaskEvent, isTaskEventKind, normalizeActor, progressLine, taskEventJson, } from "./task-events.js";
|
|
89
|
+
export type { ProgressRecorder, TaskEvent, TaskEventActor, TaskEventInput, TaskEventKind } from "./task-events.js";
|
|
90
|
+
export type { SessionNotice, TaskListFilter, TaskStoreOptions } from "./storage/sqlite.js";
|
|
91
|
+
export { FALLBACK_REGION, REGION_SETTING_KEY, REGION_CATALOG, TIMEZONE_REGION, APPROXIMATE_TIMEZONE_REGION, catalogZone, closestRegions, COUNTRY_ALIASES, regionForTimezone, guessRegionFromTimeZone, hostTimeZone, detectRegionFromTimezone, ignoredRegionMessage, loadRegionSetting, resolveRegion, } from "./region.js";
|
|
92
|
+
export { checkRequestedRegion, regionRequestUrl, regionSettingReader, unknownRegionMessage, } from "./region-host.js";
|
|
93
|
+
export type { RegionSettingReaderOptions } from "./region-host.js";
|
|
94
|
+
export type { RegionApproximation, RegionCatalogEntry, RegionResolution, RegionSource, ResolveRegionInput, } from "./region.js";
|
|
95
|
+
export { BATCH_LLM_TIMEOUT_NOTE, CAPS_VERSION, DURATION_FORM_ERROR, DURATION_RANGE_ERROR, DURATION_ZERO_ERROR, DurationError, FAILURE_CLASSES, MAX_RETRIES, NO_TIME_LEFT_TEXT, RETRIES_ERROR, RETRY_DELAY_ERROR, RUN_LIMITS, attemptNumber, capValueError, classifyFailure, describeRunLimit, durationSeconds, failureFactsOf, finalFailureError, formatDuration, formatRunLimitValue, isRetryableFailure, isRunLimitCap, loadRunLimitSettings, mayRunAsBatch, parseDuration, parseRetries, parseRetryDelay, parseRunLimitValue, planRetry, resolveRunLimits, resolveTaskRunLimits, retryPolicyOf, retryPolicyText, runLimitDefinition, runLimitSettingsFromValues, runLimitValueError, runLimitsDetails, runLimitsFromDetails, runLimitsText, taskRunLimitsView, timeLimitError, versionedCaps, } from "./run-limits.js";
|
|
96
|
+
export type { DurationValue, FailureClass, FailureFacts, FinalReason, IgnoredRunLimitLine, LoadRunLimitSettingsOptions, ResolvedRunLimit, ResolvedRunLimits, RetryPlan, RunLimitDefinition, RunLimitDetail, RunLimitName, RunLimitSettings, RunLimitsDetails, RunLimitSource, TaskRunLimitsView, } from "./run-limits.js";
|
|
97
|
+
export { DEFAULT_PUE, LEGACY_KWH_PER_TASK, MODEL_ENERGY_COEFFICIENTS, MODEL_FAMILIES, ENERGY_SOURCES, normalizeModelName, lookupModelEnergy, resolveModelEnergy, estimateEnergyKwh, gramsForIntensity, TOKEN_COUNTS_PARTIAL_TEXT, TOKEN_COUNTS_TYPICAL_TEXT, } from "./energy.js";
|
|
68
98
|
export type { EnergySourceTier, EnergyResolutionTier, ModelLifecycleStatus, ModelEnergyCoefficients, ModelFamily, ResolvedModelEnergy, EstimateEnergyOpts, } from "./energy.js";
|
|
69
|
-
export { ALL_TOOL_HOSTS, TOOL_SURFACE, getToolDef, getToolDefOrThrow, toolsForHost, paramHosts, paramIncludedForHost, paramsForHost, paramOptionalForHost, neutralSurfaceForHost, } from "./tool-surface.js";
|
|
70
|
-
export
|
|
99
|
+
export { ALL_TOOL_HOSTS, TOOL_SURFACE, getToolDef, getToolDefOrThrow, toolsForHost, descriptionForHost, paramHosts, paramIncludedForHost, paramsForHost, paramOptionalForHost, neutralSurfaceForHost, } from "./tool-surface.js";
|
|
100
|
+
export { commandJobRefusal, QUEUE_ADD_COMMAND_LINE, endJobOfTask, isJobRepeat, JOB_ONLY_PARAMS, JOB_REPEATS, jobParamsRefusal, jobToolsFor, jobToolView, jobUnsupportedRefusal, llmTimeoutArg, retryCapsArgs, scheduleJobInput, } from "./schedule-job.js";
|
|
101
|
+
export type { JobRepeat, JobToolView, ScheduleJobArgs } from "./schedule-job.js";
|
|
102
|
+
export type { ToolHost, ToolParamKind, ToolParam, ToolAnnotations, CanonicalToolDef, } from "./tool-surface.js";
|
|
71
103
|
export { canonicalize, defaultSigningKeyPath, loadOrCreateSigningKey, signReceipt, verifyReceipt, } from "./sign.js";
|
|
72
104
|
export type { SigningKeyOptions, SigningKeyPair, VerifyOutcome, VerifyResult, } from "./sign.js";
|
|
73
105
|
export { TIDEGAP_HOME_DIR, resolveTidegapHome, tidegapPath, } from "./paths.js";
|
|
74
106
|
export type { ResolveHomeOptions } from "./paths.js";
|
|
107
|
+
export { AGENT_HOSTS, AGENTS_BLOCK, agentSnippet, isAgentHost, renderAgentSnippet, } from "./agent-snippet.js";
|
|
108
|
+
export type { AgentHost, AgentSnippet, AgentSnippetFile } from "./agent-snippet.js";
|
|
75
109
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -38,26 +38,54 @@
|
|
|
38
38
|
* host (scripts, notebooks) rather than being bundled into a third-party
|
|
39
39
|
* plugin, so its `os.environ` fallbacks stay for ergonomics.
|
|
40
40
|
*/
|
|
41
|
-
export { CarbonBudgetExceededError, defer, InvalidDeadlineError, LAST_TICK_META_KEY, pickBestWindow, Scheduler, TaskActionError, } from "./scheduler.js";
|
|
41
|
+
export { CarbonBudgetExceededError, COMMAND_MAX_CHARS, defer, InvalidDeadlineError, LAST_TICK_META_KEY, pickBestWindow, Scheduler, TaskActionError, } from "./scheduler.js";
|
|
42
42
|
export { recommendWindow } from "./recommend.js";
|
|
43
43
|
// Task visibility (v0.17): titles, history, display helpers.
|
|
44
44
|
export { TITLE_MAX_CHARS, deadlineKindLabel, deriveTitle, displayTitle, isRepeating, isValidSessionId, resumeCommand, SESSION_ID_PATTERN, shellQuote, taskActions, stripControlChars, capHistory, HISTORY_MAX_CHARS, taskHistory, taskPrompt, taskResultText, } from "./history.js";
|
|
45
|
+
// Readiness (coherence KTD1 to KTD3).
|
|
46
|
+
export { assessReadiness, oldestTickRun, pendingProvidersFromStore, problemLine, readTickRunners, readTickSleep, sleepReadNeeded, runnersFromSnapshot, sleptBetween, snapshotIsFresh, TICKER_CODES, tickIntervalFor, TICK_RUNNERS_META_KEY, TICK_BY_META_KEY, TICK_SLEEP_META_KEY, writeTickRunners, writeTickSleep, } from "./readiness.js";
|
|
47
|
+
// "Later" presets (coherence KTD4 to KTD6).
|
|
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
|
+
// 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, isRedactedTask, runPreview, 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, runCallback, runCommand, splitMessage, taskDoneMessage, taskFailedMessage, eventTitle, jobDigestText, jobNextLabel, jobPausedMessage, jobPausedTitle, jobTitle, zoneTimeLabel, telegramChatId, TELEGRAM_API_BASE, TELEGRAM_CALL_TIMEOUT_MS, TELEGRAM_CALLBACK_MAX_BYTES, TELEGRAM_MESSAGE_MAX, TELEGRAM_PREVIEW_CHARS, TelegramClient, TelegramError, } from "./channels/index.js";
|
|
45
51
|
// Cross-provider routing (ROADMAP item 1).
|
|
46
52
|
export { scoreCandidates, previewRouting, parseCandidate, parseCandidates, candidateId, normalizeRouteWeights, priceForModel, DEFAULT_ROUTE_WEIGHTS, ROUTING_PREVIEW_DISCLOSURE, SCORE_TIE_EPSILON, InvalidCandidateError, InvalidRouteWeightsError, MissingPriceError, } from "./routing.js";
|
|
47
53
|
export { selectWindow, inDeadlineEntries, TOLERANCE_FLOOR_G, TOLERANCE_FRACTION, } from "./select-window.js";
|
|
48
54
|
export { ASSUMED_KWH_PER_CALL, classifyBand, aggregateStats, aggregateByRegion, bandHistogram, achievements, } from "./aggregator.js";
|
|
49
55
|
// Aggregate carbon-budget alerts (ROADMAP item 4).
|
|
50
56
|
// Desktop notifications (v0.17): pure command builder, hosts spawn it.
|
|
51
|
-
export { NOTIFY_PREVIEW_CHARS, WIN_NOTIFY_BODY_VAR, WIN_NOTIFY_TITLE_VAR, osNotifyCommand, taskNotificationContent, } from "./notify.js";
|
|
57
|
+
export { NOTIFY_PREVIEW_CHARS, WIN_NOTIFY_BODY_VAR, WIN_NOTIFY_TITLE_VAR, firstErrorLine, osNotifyCommand, taskNotificationContent, } from "./notify.js";
|
|
58
|
+
export { CLAUDE_CODE_TOOL_ALLOWLIST, DEFAULT_CLAUDE_CODE_TOOLS, DEFAULT_ORIGIN_TOOLS, claudeCodeToolsError, includesFileTool, includesWebTool, } from "./claude-tools.js";
|
|
59
|
+
export { HANDOFF_PATH_MAX_CHARS, HANDOFF_PROFILES, PROFILE_TOOLS, defaultDbPath, handoffCwdError, isDefaultLedger, latestResultFile, nodeHandoffFs, outputPathError, profileTools, PROTECTED_HOME_DIRS, resultFileText, resultPathError, removeWakeMarker, sameTools, taskWorkShape, WAKE_MARKER_MAX_AGE_MS, wakeError, wakeMarkerPath, wakeMarkersDir, writeWakeMarker, } from "./handoff.js";
|
|
60
|
+
export { forkCommand, freshReasonText, runSessionSummary, shortSessionId, taskOrigin, tokensLabel } from "./run-session.js";
|
|
52
61
|
export { carbonBudgetConfigPath, carbonBudgetStatus, carbonBudgetUsage, loadCarbonBudgetConfig, parseKeyValues, KEY_PREFIX, receiptCarbonG, windowBounds, } from "./budget.js";
|
|
53
62
|
// Quota-reset deadlines and the shared pre-tick step (v0.17).
|
|
54
63
|
export { DEFAULT_QUOTA_MARGIN_H, loadQuotaResetConfig, nextQuotaReset, prepareTick, previousQuotaReset, replanSweep, resolveQuotaDeadline, resolveQuotaProvider, sweepQuotaDeadlines, } from "./quota.js";
|
|
55
|
-
export { mockGridFeed, electricityMapsFeed, ukCarbonIntensityFeed, eiaFeed, entsoeFeed, wattTimeFeed, multiSourceGridFeed, buildDefaultGridFeed, } from "./grid.js";
|
|
56
|
-
export {
|
|
57
|
-
|
|
58
|
-
export {
|
|
59
|
-
|
|
60
|
-
export {
|
|
64
|
+
export { mockGridFeed, electricityMapsFeed, ukCarbonIntensityFeed, eiaFeed, entsoeFeed, wattTimeFeed, multiSourceGridFeed, buildDefaultGridFeed, regionDataSource, } from "./grid.js";
|
|
65
|
+
export { DEFAULT_JOB_CAPS } from "./types.js";
|
|
66
|
+
// Floating recurring jobs: cadence, window and anchor math (KTD5).
|
|
67
|
+
export { guaranteeText, isCalendarAnchored, JobScheduleError, MAX_EVERY_HOURS, MIN_EVERY_HOURS, nextOccurrence, parseCadence, parseWindow, validateJobSchedule, } from "./job-cadence.js";
|
|
68
|
+
// IANA zone helpers shared by the quota and job code.
|
|
69
|
+
export { localToUtcMs, systemTimeZone } from "./zone-time.js";
|
|
70
|
+
// Floating recurring jobs: actions and the job sweep (KTD2, KTD9).
|
|
71
|
+
export { createJob, getJob, JOB_AUTO_PAUSE_FAILURES, JOB_AUTO_PAUSE_PREFIX, jobAutoPauseReason, JOB_INTERRUPTED_ERROR, JOB_SECRET_NAME, JobActionError, jobHistory, jobRunLimits, listJobs, pauseJob, removeJob, resumeJob, runJobNow, sweepJobs, updateJob, } from "./jobs.js";
|
|
72
|
+
export { AnthropicAdapter, OpenAIAdapter, GeminiAdapter, OllamaAdapter, DEFAULT_MODEL_BY_PROVIDER, NonRetryableError, permanentError, ProviderRefusalError, } from "./providers/index.js";
|
|
73
|
+
export { budgetMaxTokens, BudgetExceededError } from "./providers/budget.js";
|
|
74
|
+
export { MAX_TIMER_MS, withLlmTimeout } from "./providers/timeout.js";
|
|
75
|
+
export { httpFetch, limitDispatcher } from "./providers/http.js";
|
|
76
|
+
export { redactPrompt, SCRUB_MIN_LENGTH, scrubCutEdges, scrubValues } from "./redact.js";
|
|
77
|
+
export { retryWithBackoff } from "./scheduler.js";
|
|
78
|
+
export { ProviderDeferError } from "./providers/defer.js";
|
|
79
|
+
export { SESSION_NOTICE_MAX_AGE_MS, SESSION_NOTICES_SINCE_META_KEY, TaskStore } from "./storage/sqlite.js";
|
|
80
|
+
export { PROGRESS_BUSY_MS, PROGRESS_GAP_MS, PROGRESS_LINE_MAX_CHARS, PROGRESS_MAX_EVENTS, PROGRESS_QUIET_MS, TASK_EVENT_KINDS, cleanProgressText, createProgressRecorder, attemptLines, eventSummary, formatTaskEvent, isTaskEventKind, normalizeActor, progressLine, taskEventJson, } from "./task-events.js";
|
|
81
|
+
export { FALLBACK_REGION, REGION_SETTING_KEY, REGION_CATALOG, TIMEZONE_REGION, APPROXIMATE_TIMEZONE_REGION, catalogZone, closestRegions, COUNTRY_ALIASES, regionForTimezone, guessRegionFromTimeZone, hostTimeZone, detectRegionFromTimezone, ignoredRegionMessage, loadRegionSetting, resolveRegion, } from "./region.js";
|
|
82
|
+
export { checkRequestedRegion, regionRequestUrl, regionSettingReader, unknownRegionMessage, } from "./region-host.js";
|
|
83
|
+
export { BATCH_LLM_TIMEOUT_NOTE, CAPS_VERSION, DURATION_FORM_ERROR, DURATION_RANGE_ERROR, DURATION_ZERO_ERROR, DurationError, FAILURE_CLASSES, MAX_RETRIES, NO_TIME_LEFT_TEXT, RETRIES_ERROR, RETRY_DELAY_ERROR, RUN_LIMITS, attemptNumber, capValueError, classifyFailure, describeRunLimit, durationSeconds, failureFactsOf, finalFailureError, formatDuration, formatRunLimitValue, isRetryableFailure, isRunLimitCap, loadRunLimitSettings, mayRunAsBatch, parseDuration, parseRetries, parseRetryDelay, parseRunLimitValue, planRetry, resolveRunLimits, resolveTaskRunLimits, retryPolicyOf, retryPolicyText, runLimitDefinition, runLimitSettingsFromValues, runLimitValueError, runLimitsDetails, runLimitsFromDetails, runLimitsText, taskRunLimitsView, timeLimitError, versionedCaps, } from "./run-limits.js";
|
|
84
|
+
export { DEFAULT_PUE, LEGACY_KWH_PER_TASK, MODEL_ENERGY_COEFFICIENTS, MODEL_FAMILIES, ENERGY_SOURCES, normalizeModelName, lookupModelEnergy, resolveModelEnergy, estimateEnergyKwh, gramsForIntensity, TOKEN_COUNTS_PARTIAL_TEXT, TOKEN_COUNTS_TYPICAL_TEXT, } from "./energy.js";
|
|
85
|
+
export { ALL_TOOL_HOSTS, TOOL_SURFACE, getToolDef, getToolDefOrThrow, toolsForHost, descriptionForHost, paramHosts, paramIncludedForHost, paramsForHost, paramOptionalForHost, neutralSurfaceForHost, } from "./tool-surface.js";
|
|
86
|
+
// schedule_task sugar for floating recurring jobs (KTD16), shared by both hosts.
|
|
87
|
+
export { commandJobRefusal, QUEUE_ADD_COMMAND_LINE, endJobOfTask, isJobRepeat, JOB_ONLY_PARAMS, JOB_REPEATS, jobParamsRefusal, jobToolsFor, jobToolView, jobUnsupportedRefusal, llmTimeoutArg, retryCapsArgs, scheduleJobInput, } from "./schedule-job.js";
|
|
61
88
|
export { canonicalize, defaultSigningKeyPath, loadOrCreateSigningKey, signReceipt, verifyReceipt, } from "./sign.js";
|
|
62
89
|
export { TIDEGAP_HOME_DIR, resolveTidegapHome, tidegapPath, } from "./paths.js";
|
|
90
|
+
export { AGENT_HOSTS, AGENTS_BLOCK, agentSnippet, isAgentHost, renderAgentSnippet, } from "./agent-snippet.js";
|
|
63
91
|
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cadence, window and anchor math of floating recurring jobs (KTD5).
|
|
3
|
+
*
|
|
4
|
+
* Pure functions, no I/O. A job runs once per period, at the cleanest hour
|
|
5
|
+
* inside `[earliest, deadline]` of its next occurrence:
|
|
6
|
+
*
|
|
7
|
+
* - Run-anchored (`daily` or `every N hours`, no window): the next run is
|
|
8
|
+
* due one period after the last run started, never sooner than half a
|
|
9
|
+
* period after it. With no last run (a new or resumed job) it is due one
|
|
10
|
+
* period from now. A deadline that is not after now falls back to the
|
|
11
|
+
* no-last-run rule, so an overdue job never gets a past deadline.
|
|
12
|
+
* - Calendar-anchored (any window, `weekdays`, `weekly`): slots are local
|
|
13
|
+
* wall-clock windows in the job's IANA zone on allowed days; no window
|
|
14
|
+
* means the whole local day. The next slot is the first one that starts
|
|
15
|
+
* after the last run and ends after now.
|
|
16
|
+
*
|
|
17
|
+
* DST: a local time that does not exist (spring forward) moves forward to
|
|
18
|
+
* the next valid minute; a repeated local time (fall back) uses its first
|
|
19
|
+
* instant. A slot that DST collapses keeps its nominal length.
|
|
20
|
+
*
|
|
21
|
+
* Catch-up (R6) needs no extra rule: a job keeps one live occurrence, an
|
|
22
|
+
* overdue one is simply due on the next tick, and its successor is computed
|
|
23
|
+
* from that run's start.
|
|
24
|
+
*/
|
|
25
|
+
import type { JobCadence, JobWindow, Occurrence } from "./types.js";
|
|
26
|
+
/** A schedule input the user gave that breaks a rule; the message names the rule. */
|
|
27
|
+
export declare class JobScheduleError extends Error {
|
|
28
|
+
constructor(message: string);
|
|
29
|
+
}
|
|
30
|
+
/** The part of a job that decides when it runs. */
|
|
31
|
+
export interface JobSchedule {
|
|
32
|
+
cadence: JobCadence;
|
|
33
|
+
window?: JobWindow;
|
|
34
|
+
/** IANA zone. */
|
|
35
|
+
timeZone: string;
|
|
36
|
+
}
|
|
37
|
+
/** Inputs of {@link nextOccurrence}; instants as ISO strings, Dates or epoch ms. */
|
|
38
|
+
export interface NextOccurrenceInput {
|
|
39
|
+
now: Date | string | number;
|
|
40
|
+
/** Start of the job's last run, if it ever ran (ignored on resume). */
|
|
41
|
+
lastRunStart?: Date | string | number;
|
|
42
|
+
/**
|
|
43
|
+
* Deadline of an occurrence the user skipped. The successor is anchored
|
|
44
|
+
* on it: a calendar job takes the first slot starting at or after it, a
|
|
45
|
+
* run-anchored job counts from it.
|
|
46
|
+
*/
|
|
47
|
+
skippedDeadline?: Date | string | number;
|
|
48
|
+
}
|
|
49
|
+
export declare const MIN_EVERY_HOURS = 2;
|
|
50
|
+
export declare const MAX_EVERY_HOURS = 168;
|
|
51
|
+
/**
|
|
52
|
+
* Parse a window `HH:MM-HH:MM` in local time. An end at or before the start
|
|
53
|
+
* crosses midnight; an end equal to the start is refused.
|
|
54
|
+
*/
|
|
55
|
+
export declare function parseWindow(text: string): JobWindow;
|
|
56
|
+
/**
|
|
57
|
+
* Parse a cadence: `daily`, `weekdays`, `weekly:<days>` (or `weekly <days>`,
|
|
58
|
+
* days comma-separated) or `every <N>h` (also `every <N> hours`).
|
|
59
|
+
*/
|
|
60
|
+
export declare function parseCadence(text: string): JobCadence;
|
|
61
|
+
/**
|
|
62
|
+
* Check a schedule against the rules and return it normalized (weekly days
|
|
63
|
+
* deduplicated, Monday first). Throws {@link JobScheduleError} naming the
|
|
64
|
+
* broken rule.
|
|
65
|
+
*/
|
|
66
|
+
export declare function validateJobSchedule(schedule: JobSchedule): JobSchedule;
|
|
67
|
+
/** True when the schedule runs in calendar slots rather than from the last run. */
|
|
68
|
+
export declare function isCalendarAnchored(schedule: JobSchedule): boolean;
|
|
69
|
+
/**
|
|
70
|
+
* The next occurrence of a job. Throws {@link JobScheduleError} on a
|
|
71
|
+
* schedule that breaks a rule (see {@link validateJobSchedule}).
|
|
72
|
+
*/
|
|
73
|
+
export declare function nextOccurrence(schedule: JobSchedule, input: NextOccurrenceInput): Occurrence;
|
|
74
|
+
/** The guarantee a schedule gives, as one sentence (R4). */
|
|
75
|
+
export declare function guaranteeText(schedule: JobSchedule): string;
|
|
76
|
+
//# sourceMappingURL=job-cadence.d.ts.map
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cadence, window and anchor math of floating recurring jobs (KTD5).
|
|
3
|
+
*
|
|
4
|
+
* Pure functions, no I/O. A job runs once per period, at the cleanest hour
|
|
5
|
+
* inside `[earliest, deadline]` of its next occurrence:
|
|
6
|
+
*
|
|
7
|
+
* - Run-anchored (`daily` or `every N hours`, no window): the next run is
|
|
8
|
+
* due one period after the last run started, never sooner than half a
|
|
9
|
+
* period after it. With no last run (a new or resumed job) it is due one
|
|
10
|
+
* period from now. A deadline that is not after now falls back to the
|
|
11
|
+
* no-last-run rule, so an overdue job never gets a past deadline.
|
|
12
|
+
* - Calendar-anchored (any window, `weekdays`, `weekly`): slots are local
|
|
13
|
+
* wall-clock windows in the job's IANA zone on allowed days; no window
|
|
14
|
+
* means the whole local day. The next slot is the first one that starts
|
|
15
|
+
* after the last run and ends after now.
|
|
16
|
+
*
|
|
17
|
+
* DST: a local time that does not exist (spring forward) moves forward to
|
|
18
|
+
* the next valid minute; a repeated local time (fall back) uses its first
|
|
19
|
+
* instant. A slot that DST collapses keeps its nominal length.
|
|
20
|
+
*
|
|
21
|
+
* Catch-up (R6) needs no extra rule: a job keeps one live occurrence, an
|
|
22
|
+
* overdue one is simply due on the next tick, and its successor is computed
|
|
23
|
+
* from that run's start.
|
|
24
|
+
*/
|
|
25
|
+
import { isValidTimeZone, localTime, localToUtcMs } from "./zone-time.js";
|
|
26
|
+
/** A schedule input the user gave that breaks a rule; the message names the rule. */
|
|
27
|
+
export class JobScheduleError extends Error {
|
|
28
|
+
constructor(message) {
|
|
29
|
+
super(message);
|
|
30
|
+
this.name = "JobScheduleError";
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
const MINUTE_MS = 60_000;
|
|
34
|
+
const HOUR_MS = 60 * MINUTE_MS;
|
|
35
|
+
const DAY_MS = 24 * HOUR_MS;
|
|
36
|
+
/** Index = `Date.getUTCDay()`. */
|
|
37
|
+
const WEEKDAY_BY_INDEX = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
|
|
38
|
+
/** Display and storage order. */
|
|
39
|
+
const WEEKDAY_ORDER = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
|
|
40
|
+
const WEEKDAY_NAMES = {
|
|
41
|
+
monday: "mon",
|
|
42
|
+
tuesday: "tue",
|
|
43
|
+
wednesday: "wed",
|
|
44
|
+
thursday: "thu",
|
|
45
|
+
friday: "fri",
|
|
46
|
+
saturday: "sat",
|
|
47
|
+
sunday: "sun",
|
|
48
|
+
};
|
|
49
|
+
const WORK_DAYS = new Set(["mon", "tue", "wed", "thu", "fri"]);
|
|
50
|
+
export const MIN_EVERY_HOURS = 2;
|
|
51
|
+
export const MAX_EVERY_HOURS = 168;
|
|
52
|
+
const HHMM = /^(\d{1,2}):(\d{2})$/;
|
|
53
|
+
/** `HH:MM` to minutes after midnight, or undefined when malformed. */
|
|
54
|
+
function minutesOf(hhmm) {
|
|
55
|
+
const m = HHMM.exec(hhmm.trim());
|
|
56
|
+
if (!m)
|
|
57
|
+
return undefined;
|
|
58
|
+
const h = Number(m[1]);
|
|
59
|
+
const mi = Number(m[2]);
|
|
60
|
+
if (h > 23 || mi > 59)
|
|
61
|
+
return undefined;
|
|
62
|
+
return h * 60 + mi;
|
|
63
|
+
}
|
|
64
|
+
function hhmm(minutes) {
|
|
65
|
+
return `${String(Math.floor(minutes / 60)).padStart(2, "0")}:${String(minutes % 60).padStart(2, "0")}`;
|
|
66
|
+
}
|
|
67
|
+
/** One weekday name (`mon` or `monday`, any case). */
|
|
68
|
+
function parseWeekday(raw) {
|
|
69
|
+
const v = raw.trim().toLowerCase();
|
|
70
|
+
if (WEEKDAY_ORDER.includes(v))
|
|
71
|
+
return v;
|
|
72
|
+
const full = WEEKDAY_NAMES[v];
|
|
73
|
+
if (full)
|
|
74
|
+
return full;
|
|
75
|
+
throw new JobScheduleError(`unknown day "${raw.trim()}"; use mon, tue, wed, thu, fri, sat or sun`);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Parse a window `HH:MM-HH:MM` in local time. An end at or before the start
|
|
79
|
+
* crosses midnight; an end equal to the start is refused.
|
|
80
|
+
*/
|
|
81
|
+
export function parseWindow(text) {
|
|
82
|
+
const parts = text.split("-");
|
|
83
|
+
const start = parts.length === 2 ? minutesOf(parts[0]) : undefined;
|
|
84
|
+
const end = parts.length === 2 ? minutesOf(parts[1]) : undefined;
|
|
85
|
+
if (start === undefined || end === undefined) {
|
|
86
|
+
throw new JobScheduleError(`window "${text}" must look like HH:MM-HH:MM, for example 00:00-08:00`);
|
|
87
|
+
}
|
|
88
|
+
if (start === end)
|
|
89
|
+
throw new JobScheduleError("window start and end must differ");
|
|
90
|
+
return { start: hhmm(start), end: hhmm(end) };
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Parse a cadence: `daily`, `weekdays`, `weekly:<days>` (or `weekly <days>`,
|
|
94
|
+
* days comma-separated) or `every <N>h` (also `every <N> hours`).
|
|
95
|
+
*/
|
|
96
|
+
export function parseCadence(text) {
|
|
97
|
+
const v = text.trim().toLowerCase();
|
|
98
|
+
if (v === "daily")
|
|
99
|
+
return { kind: "daily" };
|
|
100
|
+
if (v === "weekdays")
|
|
101
|
+
return { kind: "weekdays" };
|
|
102
|
+
const weekly = /^weekly(?:[:\s](.*))?$/.exec(v);
|
|
103
|
+
if (weekly) {
|
|
104
|
+
const days = (weekly[1] ?? "").split(",").filter((d) => d.trim() !== "").map(parseWeekday);
|
|
105
|
+
return { kind: "weekly", days };
|
|
106
|
+
}
|
|
107
|
+
const every = /^every[:\s]\s*(\d+)\s*(?:h|hours?)$/.exec(v);
|
|
108
|
+
if (every)
|
|
109
|
+
return { kind: "hours", every: Number(every[1]) };
|
|
110
|
+
throw new JobScheduleError(`unknown cadence "${text.trim()}"; use daily, weekdays, weekly:mon,thu or every 6h`);
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Check a schedule against the rules and return it normalized (weekly days
|
|
114
|
+
* deduplicated, Monday first). Throws {@link JobScheduleError} naming the
|
|
115
|
+
* broken rule.
|
|
116
|
+
*/
|
|
117
|
+
export function validateJobSchedule(schedule) {
|
|
118
|
+
if (typeof schedule.timeZone !== "string" || !isValidTimeZone(schedule.timeZone)) {
|
|
119
|
+
throw new JobScheduleError(`unknown time zone "${String(schedule.timeZone)}"; use an IANA name such as Europe/Berlin`);
|
|
120
|
+
}
|
|
121
|
+
const c = schedule.cadence;
|
|
122
|
+
let cadence;
|
|
123
|
+
switch (c?.kind) {
|
|
124
|
+
case "daily":
|
|
125
|
+
case "weekdays":
|
|
126
|
+
cadence = { kind: c.kind };
|
|
127
|
+
break;
|
|
128
|
+
case "weekly": {
|
|
129
|
+
const days = new Set((Array.isArray(c.days) ? c.days : []).map((d) => parseWeekday(String(d))));
|
|
130
|
+
if (days.size === 0)
|
|
131
|
+
throw new JobScheduleError("weekly: pick at least one day");
|
|
132
|
+
cadence = { kind: "weekly", days: WEEKDAY_ORDER.filter((d) => days.has(d)) };
|
|
133
|
+
break;
|
|
134
|
+
}
|
|
135
|
+
case "hours":
|
|
136
|
+
if (!Number.isInteger(c.every) || c.every < MIN_EVERY_HOURS || c.every > MAX_EVERY_HOURS) {
|
|
137
|
+
throw new JobScheduleError(`every N hours needs a whole N from ${MIN_EVERY_HOURS} to ${MAX_EVERY_HOURS}`);
|
|
138
|
+
}
|
|
139
|
+
cadence = { kind: "hours", every: c.every };
|
|
140
|
+
break;
|
|
141
|
+
default:
|
|
142
|
+
throw new JobScheduleError(`unknown cadence ${JSON.stringify(c?.kind)}`);
|
|
143
|
+
}
|
|
144
|
+
if (!schedule.window)
|
|
145
|
+
return { cadence, timeZone: schedule.timeZone };
|
|
146
|
+
if (cadence.kind === "hours") {
|
|
147
|
+
throw new JobScheduleError("a window works only with daily, weekdays or weekly; every N hours counts from the last run");
|
|
148
|
+
}
|
|
149
|
+
return { cadence, window: parseWindow(`${schedule.window.start}-${schedule.window.end}`), timeZone: schedule.timeZone };
|
|
150
|
+
}
|
|
151
|
+
/** True when the schedule runs in calendar slots rather than from the last run. */
|
|
152
|
+
export function isCalendarAnchored(schedule) {
|
|
153
|
+
return schedule.window !== undefined || schedule.cadence.kind === "weekdays" || schedule.cadence.kind === "weekly";
|
|
154
|
+
}
|
|
155
|
+
/** The run-anchored period in ms (`daily` = 24 h). */
|
|
156
|
+
function periodMs(cadence) {
|
|
157
|
+
return cadence.kind === "hours" ? cadence.every * HOUR_MS : DAY_MS;
|
|
158
|
+
}
|
|
159
|
+
function toMs(v) {
|
|
160
|
+
const ms = typeof v === "number" ? v : typeof v === "string" ? Date.parse(v) : v.getTime();
|
|
161
|
+
if (!Number.isFinite(ms))
|
|
162
|
+
throw new JobScheduleError(`invalid instant ${JSON.stringify(v)}`);
|
|
163
|
+
return ms;
|
|
164
|
+
}
|
|
165
|
+
/** The slot that starts on local date y-mo-d, or undefined on a day the cadence skips. */
|
|
166
|
+
function slotOn(y, mo, d, schedule) {
|
|
167
|
+
const weekday = WEEKDAY_BY_INDEX[new Date(Date.UTC(y, mo, d)).getUTCDay()];
|
|
168
|
+
const c = schedule.cadence;
|
|
169
|
+
if (c.kind === "weekdays" && !WORK_DAYS.has(weekday))
|
|
170
|
+
return undefined;
|
|
171
|
+
if (c.kind === "weekly" && !c.days.includes(weekday))
|
|
172
|
+
return undefined;
|
|
173
|
+
const tz = schedule.timeZone;
|
|
174
|
+
if (!schedule.window) {
|
|
175
|
+
return { start: localToUtcMs(y, mo, d, 0, 0, tz), end: localToUtcMs(y, mo, d + 1, 0, 0, tz) };
|
|
176
|
+
}
|
|
177
|
+
const startMin = minutesOf(schedule.window.start);
|
|
178
|
+
const endMin = minutesOf(schedule.window.end);
|
|
179
|
+
const crosses = endMin <= startMin;
|
|
180
|
+
const start = localToUtcMs(y, mo, d, Math.floor(startMin / 60), startMin % 60, tz);
|
|
181
|
+
let end = localToUtcMs(y, mo, d + (crosses ? 1 : 0), Math.floor(endMin / 60), endMin % 60, tz);
|
|
182
|
+
// A DST gap can swallow the slot (02:00-03:00 on a spring-forward day):
|
|
183
|
+
// keep its nominal length from the moved start.
|
|
184
|
+
if (end <= start)
|
|
185
|
+
end = start + ((endMin - startMin + 24 * 60) % (24 * 60)) * MINUTE_MS;
|
|
186
|
+
return { start, end };
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* The next occurrence of a job. Throws {@link JobScheduleError} on a
|
|
190
|
+
* schedule that breaks a rule (see {@link validateJobSchedule}).
|
|
191
|
+
*/
|
|
192
|
+
export function nextOccurrence(schedule, input) {
|
|
193
|
+
const s = validateJobSchedule(schedule);
|
|
194
|
+
const now = toMs(input.now);
|
|
195
|
+
const lastRun = input.lastRunStart !== undefined ? toMs(input.lastRunStart) : undefined;
|
|
196
|
+
const skipped = input.skippedDeadline !== undefined ? toMs(input.skippedDeadline) : undefined;
|
|
197
|
+
const iso = (ms) => new Date(ms).toISOString();
|
|
198
|
+
if (!isCalendarAnchored(s)) {
|
|
199
|
+
const period = periodMs(s.cadence);
|
|
200
|
+
const base = skipped ?? lastRun;
|
|
201
|
+
if (base !== undefined && base + period > now) {
|
|
202
|
+
return { earliest: iso(Math.max(base + period / 2, now)), deadline: iso(base + period), anchor: "run" };
|
|
203
|
+
}
|
|
204
|
+
return { earliest: iso(now), deadline: iso(now + period), anchor: "run" };
|
|
205
|
+
}
|
|
206
|
+
// A slot that ends after now starts at most one local day before now, so
|
|
207
|
+
// the search starts on yesterday's local date.
|
|
208
|
+
const local = new Date(localTime(now, s.timeZone));
|
|
209
|
+
const [y, mo, d] = [local.getUTCFullYear(), local.getUTCMonth(), local.getUTCDate()];
|
|
210
|
+
const after = Math.max(now, skipped ?? now);
|
|
211
|
+
const days = Math.ceil((after - now) / DAY_MS) + 16;
|
|
212
|
+
for (let k = -1; k <= days; k++) {
|
|
213
|
+
const slot = slotOn(y, mo, d + k, s);
|
|
214
|
+
if (!slot || slot.end <= now)
|
|
215
|
+
continue;
|
|
216
|
+
if (lastRun !== undefined && slot.start <= lastRun)
|
|
217
|
+
continue;
|
|
218
|
+
if (skipped !== undefined && slot.start < skipped)
|
|
219
|
+
continue;
|
|
220
|
+
return { earliest: iso(Math.max(slot.start, now)), deadline: iso(slot.end), anchor: "calendar" };
|
|
221
|
+
}
|
|
222
|
+
// Unreachable for a validated schedule: every cadence has a slot each week.
|
|
223
|
+
throw new JobScheduleError("no slot found in the next two weeks");
|
|
224
|
+
}
|
|
225
|
+
function dayList(days) {
|
|
226
|
+
const names = days.map((d) => d[0].toUpperCase() + d.slice(1));
|
|
227
|
+
return names.length === 1 ? names[0] : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
|
|
228
|
+
}
|
|
229
|
+
/** The guarantee a schedule gives, as one sentence (R4). */
|
|
230
|
+
export function guaranteeText(schedule) {
|
|
231
|
+
const s = validateJobSchedule(schedule);
|
|
232
|
+
if (!isCalendarAnchored(s)) {
|
|
233
|
+
const h = periodMs(s.cadence) / HOUR_MS;
|
|
234
|
+
return `runs at least every ${h} h, never sooner than ${h / 2} h after the last run`;
|
|
235
|
+
}
|
|
236
|
+
const c = s.cadence;
|
|
237
|
+
const days = c.kind === "weekly" ? `every ${dayList(c.days)}` : c.kind === "weekdays" ? "every weekday (Mon-Fri)" : "every day";
|
|
238
|
+
return s.window ? `runs ${days} between ${s.window.start} and ${s.window.end}` : `runs once ${days}, any time of day`;
|
|
239
|
+
}
|
|
240
|
+
//# sourceMappingURL=job-cadence.js.map
|