@tidegap/core 0.21.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/handoff.js CHANGED
@@ -14,6 +14,7 @@ import { homedir, tmpdir } from "node:os";
14
14
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
15
15
  import { isValidSessionId } from "./history.js";
16
16
  import { resolveTidegapHome } from "./paths.js";
17
+ import { SESSION_NOTICE_MAX_AGE_MS } from "./storage/sqlite.js";
17
18
  export const HANDOFF_PROFILES = ["read", "web", "none"];
18
19
  /** The tools of each profile. `read` is scoped to the run's folder by the adapter. */
19
20
  export const PROFILE_TOOLS = {
@@ -339,8 +340,12 @@ export function taskWorkShape(record) {
339
340
  const resultPath = str(spec?.handoff?.resultPath);
340
341
  if (resultPath)
341
342
  out.resultPath = resultPath;
342
- if (spec?.handoff?.wake === true)
343
+ // A run of a bound job is a wake task too; the job sweep decides whether it wakes (KTD10).
344
+ if (spec?.handoff?.wake === true || typeof spec?.jobWake?.session === "string")
343
345
  out.wake = true;
346
+ const rule = typeof spec?.jobWake?.session === "string" ? spec.jobWake.on : undefined;
347
+ if (rule === "failures" || rule === "match")
348
+ out.wakeRule = rule;
344
349
  const command = oneOff ? str(spec.command?.run) : undefined;
345
350
  if (command)
346
351
  out.command = command;
@@ -387,6 +392,20 @@ export function defaultDbPath() {
387
392
  return legacyPath;
388
393
  return newPath;
389
394
  }
395
+ /**
396
+ * The `wake:` line of a task's work shape, or undefined when it does not
397
+ * wake: a one-off wake task wakes when it finishes; a run of a bound job
398
+ * says the job's rule, since most of its runs do not wake.
399
+ */
400
+ export function wakeShapeText(shape) {
401
+ if (!shape.wake)
402
+ return undefined;
403
+ if (shape.wakeRule === "failures")
404
+ return "failures (wakes its idle session only if the run fails after its retries)";
405
+ if (shape.wakeRule === "match")
406
+ return "match (wakes its idle session only if the run's output matches the job's pattern)";
407
+ return "on (wakes its idle session when it finishes)";
408
+ }
390
409
  /**
391
410
  * True when `dbPath` is the default ledger. The session notice and wake
392
411
  * markers under `~/.tidegap/sessions` belong to it: the plugin's hooks
@@ -414,8 +433,6 @@ export function isDefaultLedger(dbPath) {
414
433
  };
415
434
  return real(dbPath) === real(defaultDbPath());
416
435
  }
417
- /** A wake marker with no wake task left to wait for goes this long after its last refresh (the waiter refreshes it at every Stop). */
418
- export const WAKE_MARKER_MAX_AGE_MS = 12 * 3_600_000;
419
436
  /** `~/.tidegap/sessions/wake`: one marker per session with a task to wake it for. */
420
437
  export function wakeMarkersDir(home = resolveTidegapHome()) {
421
438
  return join(home, "sessions", "wake");
@@ -479,4 +496,92 @@ export function removeWakeMarker(sessionId, dir = wakeMarkersDir()) {
479
496
  // already gone
480
497
  }
481
498
  }
499
+ /** Statuses of a task that may still finish. */
500
+ const OPEN = ["queued", "scheduled", "running", "submitted"];
501
+ /** True for a task queued with wake, and for a run of a job bound to a session. */
502
+ export function isWakeTask(record) {
503
+ return taskWorkShape(record).wake === true;
504
+ }
505
+ /**
506
+ * True when a session notice wakes its session: a run of a bound job when
507
+ * the job sweep's decision says so, any other completed or failed wake
508
+ * task. A cancel is someone's own act: it never spends a turn.
509
+ */
510
+ export function noticeWakes(n) {
511
+ return n.jobNotice ? n.jobNotice.wake : isWakeTask(n.record) && n.record.status !== "cancelled";
512
+ }
513
+ /**
514
+ * The wake tasks still to come of one session, or of every session when
515
+ * `sessionId` is undefined: not finished yet, or completed and waiting for
516
+ * its result file (its notice comes once the file is). A row that completed
517
+ * more than {@link SESSION_NOTICE_MAX_AGE_MS} ago no longer counts: it can
518
+ * never be a notice.
519
+ */
520
+ export function wakeTasksToCome(store, sessionId, now) {
521
+ const oldest = now.getTime() - SESSION_NOTICE_MAX_AGE_MS;
522
+ return [
523
+ ...store.list({ ...(sessionId === undefined ? {} : { originSessionId: sessionId }), status: OPEN }),
524
+ ...store
525
+ .listResultFilesDue()
526
+ .filter((r) => (sessionId === undefined || r.originSessionId === sessionId) && Date.parse(r.completedAt ?? "") >= oldest),
527
+ ].filter(isWakeTask);
528
+ }
529
+ /**
530
+ * True when a session has something left to wait for (KTD11): an open wake
531
+ * task, a wake task waiting for its result file, an unclaimed notice that
532
+ * wakes, or an active job bound to it. The bound job counts so a waiter
533
+ * does not stop between a run's finish and the sweep's decision. With
534
+ * `since`, only a task queued after it and a job bound after it count (a
535
+ * second look after a removal); a run of a bound job counts through its
536
+ * job's bind time only, since every run is a fresh row and would keep the
537
+ * 7-day rule from ever ending the marker. An unclaimed wake notice counts
538
+ * whatever its time. The reads go against the job sweep's write order
539
+ * (run, then notice, then job): the job first, so a run that finishes
540
+ * between two reads is seen by one of them. `notices` is the session's
541
+ * notice list when the caller has just read it. Throws when the ledger
542
+ * cannot be read.
543
+ */
544
+ export function sessionHasWaitWork(store, sessionId, now = new Date(), opts = {}) {
545
+ const { since } = opts;
546
+ const after = (at) => since === undefined || Date.parse(at ?? "") > since;
547
+ if (store.listJobs({ status: "active" }).some((j) => j.wake && j.originSessionId === sessionId && after(j.wake.boundAt)))
548
+ return true;
549
+ if ((opts.notices ?? store.listSessionNotices({ sessionId, now })).some(noticeWakes))
550
+ return true;
551
+ return wakeTasksToCome(store, sessionId, now).some((t) => since === undefined || (t.jobId === undefined && after(t.enqueuedAt)));
552
+ }
553
+ /**
554
+ * Remove a session's wake marker, then look once more
555
+ * ({@link sessionHasWaitWork}, from `since` when given), and write the
556
+ * marker again when the session has something left or the read fails. A
557
+ * writer commits its row (or job) before it writes the marker, so work
558
+ * added while the caller decided is either seen here or writes its marker
559
+ * after the removal. Returns "removed", "kept" or "unread" (the read
560
+ * failed). Never throws.
561
+ */
562
+ export function removeWakeMarkerUnlessPending(store, sessionId, dir = wakeMarkersDir(), now = new Date(), since) {
563
+ removeWakeMarker(sessionId, dir);
564
+ let left;
565
+ try {
566
+ left = sessionHasWaitWork(store, sessionId, now, { since }) ? "kept" : "removed";
567
+ }
568
+ catch {
569
+ left = "unread";
570
+ }
571
+ // An unread ledger keeps the marker's old time, so the sweep's 7-day rule still counts from it.
572
+ if (left !== "removed")
573
+ writeWakeMarker(sessionId, dir, left === "unread" && since !== undefined ? new Date(since) : now);
574
+ return left;
575
+ }
576
+ /**
577
+ * The agent's own act ended something a session waited for (a cancel, a
578
+ * job removed, paused or unbound): drop the session's marker now unless
579
+ * it has something left (KTD12). Only on the default ledger, whose markers
580
+ * these are; `sessionId` undefined does nothing. Never throws.
581
+ */
582
+ export function releaseWakeMarker(store, dbPath, sessionId) {
583
+ if (!store || !sessionId || !isValidSessionId(sessionId) || !dbPath || !isDefaultLedger(dbPath))
584
+ return;
585
+ removeWakeMarkerUnlessPending(store, sessionId);
586
+ }
482
587
  //# sourceMappingURL=handoff.js.map
package/dist/history.d.ts CHANGED
@@ -26,6 +26,10 @@ export declare function deriveTitle(text: string, redactPatterns?: string[]): st
26
26
  export declare function taskPrompt(record: TaskRecord<unknown>): string | undefined;
27
27
  /** The model's reply text of a completed provider-call task, when present. */
28
28
  export declare function taskResultText(record: TaskRecord<unknown>): string | undefined;
29
+ /** A command job's summary (the reply of its summarize step), when the run has one. */
30
+ export declare function taskSummaryText(record: TaskRecord<unknown>): string | undefined;
31
+ /** Why a command job's summarize step gave no summary, when it failed. */
32
+ export declare function taskSummaryError(record: TaskRecord<unknown>): string | undefined;
29
33
  /**
30
34
  * The task's full conversation, oldest first: prior turns stored in
31
35
  * `body_json.messages`, then the prompt as the user turn, then the result
package/dist/history.js CHANGED
@@ -59,8 +59,20 @@ export function taskPrompt(record) {
59
59
  }
60
60
  /** The model's reply text of a completed provider-call task, when present. */
61
61
  export function taskResultText(record) {
62
+ return resultString(record, "text");
63
+ }
64
+ /** A command job's summary (the reply of its summarize step), when the run has one. */
65
+ export function taskSummaryText(record) {
66
+ return resultString(record, "summary");
67
+ }
68
+ /** Why a command job's summarize step gave no summary, when it failed. */
69
+ export function taskSummaryError(record) {
70
+ return resultString(record, "summaryError");
71
+ }
72
+ function resultString(record, key) {
62
73
  const r = record.result;
63
- return r && typeof r === "object" && typeof r.text === "string" ? r.text : undefined;
74
+ const v = r && typeof r === "object" ? r[key] : undefined;
75
+ return typeof v === "string" ? v : undefined;
64
76
  }
65
77
  /**
66
78
  * The task's full conversation, oldest first: prior turns stored in
package/dist/index.d.ts CHANGED
@@ -41,14 +41,14 @@
41
41
  export { CarbonBudgetExceededError, COMMAND_MAX_CHARS, defer, InvalidDeadlineError, LAST_TICK_META_KEY, pickBestWindow, Scheduler, TaskActionError, } from "./scheduler.js";
42
42
  export type { ReplyOptions, RescheduleTarget, SchedulerOptions, ActorOptions, RetryResult, TickAdapters, TickDetails, TickOptions, LockedTick, } from "./scheduler.js";
43
43
  export { recommendWindow } from "./recommend.js";
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";
44
+ export { TITLE_MAX_CHARS, deadlineKindLabel, deriveTitle, displayTitle, isRepeating, isValidSessionId, resumeCommand, SESSION_ID_PATTERN, shellQuote, taskActions, stripControlChars, capHistory, HISTORY_MAX_CHARS, taskHistory, taskPrompt, taskResultText, taskSummaryError, taskSummaryText, } from "./history.js";
45
45
  export type { TaskActions } from "./history.js";
46
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
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, 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";
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, runVerdict, 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, jobEndedBody, jobEndedMessage, jobEndedTitle, 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, JobEndedNotice, 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";
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";
54
54
  export { selectWindow, inDeadlineEntries, TOLERANCE_FLOOR_G, TOLERANCE_FRACTION, } from "./select-window.js";
@@ -58,7 +58,7 @@ export type { CarbonStats, RegionStats, BandHistogram, Achievement, } from "./ag
58
58
  export { NOTIFY_PREVIEW_CHARS, WIN_NOTIFY_BODY_VAR, WIN_NOTIFY_TITLE_VAR, firstErrorLine, osNotifyCommand, taskNotificationContent, } from "./notify.js";
59
59
  export type { OsNotifyCommand, OsNotifyOptions } from "./notify.js";
60
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";
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, wakeShapeText, isWakeTask, noticeWakes, releaseWakeMarker, removeWakeMarkerUnlessPending, sessionHasWaitWork, wakeTasksToCome, wakeError, wakeMarkerPath, wakeMarkersDir, writeWakeMarker, } from "./handoff.js";
62
62
  export type { HandoffFs, HandoffFsEntry, HandoffPathContext, HandoffProfile, HandoffSpec, ProfileChoice, TaskWorkShape, } from "./handoff.js";
63
63
  export { forkCommand, freshReasonText, runSessionSummary, shortSessionId, taskOrigin, tokensLabel } from "./run-session.js";
64
64
  export type { FreshReason, RunSession, RunSessionMode } from "./run-session.js";
@@ -68,13 +68,15 @@ export { DEFAULT_QUOTA_MARGIN_H, loadQuotaResetConfig, nextQuotaReset, prepareTi
68
68
  export type { LoadQuotaResetOptions, QuotaResetConfig, QuotaResetSchedule, ResolveQuotaProviderResult, } from "./quota.js";
69
69
  export { mockGridFeed, electricityMapsFeed, ukCarbonIntensityFeed, eiaFeed, entsoeFeed, wattTimeFeed, multiSourceGridFeed, buildDefaultGridFeed, regionDataSource, } from "./grid.js";
70
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";
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, JobEndReason, JobNoticeReason, JobWake, JobTemplate, JobTools, JobWindow, Occurrence, Weekday, } from "./types.js";
72
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";
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
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";
76
+ export { createJob, getJob, JOB_AUTO_PAUSE_FAILURES, JOB_AUTO_PAUSE_PREFIX, jobAutoPauseReason, jobEndsText, jobEndText, JOB_INTERRUPTED_ERROR, JOB_MAX_COUNT, DEFAULT_SUMMARIZE_PROMPT, JOB_SECRET_NAME, JobActionError, jobHistory, jobRunLimits, jobWakeSession, listJobs, pauseJob, removeJob, resumeJob, runJobNow, sweepJobs, updateJob, } from "./jobs.js";
77
+ export type { JobActionOptions, JobCapsPatch, JobHistoryEntry, JobInput, JobPatch, JobSweepResult, JobUpdateOptions, JobWakeInput } from "./jobs.js";
78
+ 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";
79
+ export type { JobWakeRule, WakeMatch } from "./job-wake.js";
78
80
  export { AnthropicAdapter, OpenAIAdapter, GeminiAdapter, OllamaAdapter, DEFAULT_MODEL_BY_PROVIDER, NonRetryableError, permanentError, ProviderRefusalError, } from "./providers/index.js";
79
81
  export { budgetMaxTokens, BudgetExceededError } from "./providers/budget.js";
80
82
  export { MAX_TIMER_MS, withLlmTimeout } from "./providers/timeout.js";
@@ -87,7 +89,7 @@ export type { BatchHandle, DispatchOptions, DispatchOrigin, DispatchResult, Mode
87
89
  export { SESSION_NOTICE_MAX_AGE_MS, SESSION_NOTICES_SINCE_META_KEY, TaskStore } from "./storage/sqlite.js";
88
90
  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
91
  export type { ProgressRecorder, TaskEvent, TaskEventActor, TaskEventInput, TaskEventKind } from "./task-events.js";
90
- export type { SessionNotice, TaskListFilter, TaskStoreOptions } from "./storage/sqlite.js";
92
+ export type { JobNotice, SessionNotice, TaskListFilter, TaskStoreOptions } from "./storage/sqlite.js";
91
93
  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
94
  export { checkRequestedRegion, regionRequestUrl, regionSettingReader, unknownRegionMessage, } from "./region-host.js";
93
95
  export type { RegionSettingReaderOptions } from "./region-host.js";
@@ -97,7 +99,7 @@ export type { DurationValue, FailureClass, FailureFacts, FinalReason, IgnoredRun
97
99
  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";
98
100
  export type { EnergySourceTier, EnergyResolutionTier, ModelLifecycleStatus, ModelEnergyCoefficients, ModelFamily, ResolvedModelEnergy, EstimateEnergyOpts, } from "./energy.js";
99
101
  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";
102
+ export { commandJobRefusal, QUEUE_ADD_COMMAND_LINE, endJobOfTask, isJobRepeat, JOB_ONLY_PARAMS, JOB_REPEATS, jobParamsRefusal, jobToolsFor, jobToolView, jobUnsupportedRefusal, jobWakeArgs, llmTimeoutArg, retryCapsArgs, scheduleJobInput, } from "./schedule-job.js";
101
103
  export type { JobRepeat, JobToolView, ScheduleJobArgs } from "./schedule-job.js";
102
104
  export type { ToolHost, ToolParamKind, ToolParam, ToolAnnotations, CanonicalToolDef, } from "./tool-surface.js";
103
105
  export { canonicalize, defaultSigningKeyPath, loadOrCreateSigningKey, signReceipt, verifyReceipt, } from "./sign.js";
package/dist/index.js CHANGED
@@ -41,13 +41,13 @@
41
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
- 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";
44
+ export { TITLE_MAX_CHARS, deadlineKindLabel, deriveTitle, displayTitle, isRepeating, isValidSessionId, resumeCommand, SESSION_ID_PATTERN, shellQuote, taskActions, stripControlChars, capHistory, HISTORY_MAX_CHARS, taskHistory, taskPrompt, taskResultText, taskSummaryError, taskSummaryText, } from "./history.js";
45
45
  // Readiness (coherence KTD1 to KTD3).
46
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
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, 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";
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, runVerdict, 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, jobEndedBody, jobEndedMessage, jobEndedTitle, 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
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";
@@ -56,7 +56,7 @@ export { ASSUMED_KWH_PER_CALL, classifyBand, aggregateStats, aggregateByRegion,
56
56
  // Desktop notifications (v0.17): pure command builder, hosts spawn it.
57
57
  export { NOTIFY_PREVIEW_CHARS, WIN_NOTIFY_BODY_VAR, WIN_NOTIFY_TITLE_VAR, firstErrorLine, osNotifyCommand, taskNotificationContent, } from "./notify.js";
58
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";
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, wakeShapeText, isWakeTask, noticeWakes, releaseWakeMarker, removeWakeMarkerUnlessPending, sessionHasWaitWork, wakeTasksToCome, wakeError, wakeMarkerPath, wakeMarkersDir, writeWakeMarker, } from "./handoff.js";
60
60
  export { forkCommand, freshReasonText, runSessionSummary, shortSessionId, taskOrigin, tokensLabel } from "./run-session.js";
61
61
  export { carbonBudgetConfigPath, carbonBudgetStatus, carbonBudgetUsage, loadCarbonBudgetConfig, parseKeyValues, KEY_PREFIX, receiptCarbonG, windowBounds, } from "./budget.js";
62
62
  // Quota-reset deadlines and the shared pre-tick step (v0.17).
@@ -64,11 +64,13 @@ export { DEFAULT_QUOTA_MARGIN_H, loadQuotaResetConfig, nextQuotaReset, prepareTi
64
64
  export { mockGridFeed, electricityMapsFeed, ukCarbonIntensityFeed, eiaFeed, entsoeFeed, wattTimeFeed, multiSourceGridFeed, buildDefaultGridFeed, regionDataSource, } from "./grid.js";
65
65
  export { DEFAULT_JOB_CAPS } from "./types.js";
66
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";
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
69
  export { localToUtcMs, systemTimeZone } from "./zone-time.js";
70
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";
71
+ export { createJob, getJob, JOB_AUTO_PAUSE_FAILURES, JOB_AUTO_PAUSE_PREFIX, jobAutoPauseReason, jobEndsText, jobEndText, JOB_INTERRUPTED_ERROR, JOB_MAX_COUNT, DEFAULT_SUMMARIZE_PROMPT, JOB_SECRET_NAME, JobActionError, jobHistory, jobRunLimits, jobWakeSession, listJobs, pauseJob, removeJob, resumeJob, runJobNow, sweepJobs, updateJob, } from "./jobs.js";
72
+ // Wake rules of a job bound to a session (KTD7, KTD9).
73
+ 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";
72
74
  export { AnthropicAdapter, OpenAIAdapter, GeminiAdapter, OllamaAdapter, DEFAULT_MODEL_BY_PROVIDER, NonRetryableError, permanentError, ProviderRefusalError, } from "./providers/index.js";
73
75
  export { budgetMaxTokens, BudgetExceededError } from "./providers/budget.js";
74
76
  export { MAX_TIMER_MS, withLlmTimeout } from "./providers/timeout.js";
@@ -84,7 +86,7 @@ export { BATCH_LLM_TIMEOUT_NOTE, CAPS_VERSION, DURATION_FORM_ERROR, DURATION_RAN
84
86
  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
87
  export { ALL_TOOL_HOSTS, TOOL_SURFACE, getToolDef, getToolDefOrThrow, toolsForHost, descriptionForHost, paramHosts, paramIncludedForHost, paramsForHost, paramOptionalForHost, neutralSurfaceForHost, } from "./tool-surface.js";
86
88
  // 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";
89
+ export { commandJobRefusal, QUEUE_ADD_COMMAND_LINE, endJobOfTask, isJobRepeat, JOB_ONLY_PARAMS, JOB_REPEATS, jobParamsRefusal, jobToolsFor, jobToolView, jobUnsupportedRefusal, jobWakeArgs, llmTimeoutArg, retryCapsArgs, scheduleJobInput, } from "./schedule-job.js";
88
90
  export { canonicalize, defaultSigningKeyPath, loadOrCreateSigningKey, signReceipt, verifyReceipt, } from "./sign.js";
89
91
  export { TIDEGAP_HOME_DIR, resolveTidegapHome, tidegapPath, } from "./paths.js";
90
92
  export { AGENT_HOSTS, AGENTS_BLOCK, agentSnippet, isAgentHost, renderAgentSnippet, } from "./agent-snippet.js";
@@ -73,4 +73,14 @@ export declare function isCalendarAnchored(schedule: JobSchedule): boolean;
73
73
  export declare function nextOccurrence(schedule: JobSchedule, input: NextOccurrenceInput): Occurrence;
74
74
  /** The guarantee a schedule gives, as one sentence (R4). */
75
75
  export declare function guaranteeText(schedule: JobSchedule): string;
76
+ /**
77
+ * The end bound of a job's `until`, in ms: a slot must start before it.
78
+ * `YYYY-MM-DD` is the last local day in `timeZone` on which a slot may
79
+ * start, so the bound is the next local midnight; an ISO instant with `Z`
80
+ * or an offset is the bound itself. Throws {@link JobScheduleError} on any
81
+ * other text, a day that does not exist (`2026-02-30`) included.
82
+ */
83
+ export declare function untilBoundMs(until: string, timeZone: string): number;
84
+ /** A job's end date in words: `after 2026-11-17 (Europe/Berlin)` for a day, `before <instant>` for an instant. */
85
+ export declare function untilText(until: string, timeZone: string): string;
76
86
  //# sourceMappingURL=job-cadence.d.ts.map
@@ -237,4 +237,38 @@ export function guaranteeText(schedule) {
237
237
  const days = c.kind === "weekly" ? `every ${dayList(c.days)}` : c.kind === "weekdays" ? "every weekday (Mon-Fri)" : "every day";
238
238
  return s.window ? `runs ${days} between ${s.window.start} and ${s.window.end}` : `runs once ${days}, any time of day`;
239
239
  }
240
+ const UNTIL_DAY = /^(\d{4})-(\d{2})-(\d{2})$/;
241
+ const UNTIL_INSTANT = /^(\d{4}-\d{2}-\d{2})T(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,3})?)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;
242
+ /** `[year, month (1-12), day]` of a real calendar day `YYYY-MM-DD`, or undefined. */
243
+ function calendarDay(text) {
244
+ const m = UNTIL_DAY.exec(text);
245
+ if (!m)
246
+ return undefined;
247
+ const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
248
+ const check = new Date(Date.UTC(y, mo - 1, d));
249
+ return check.getUTCFullYear() === y && check.getUTCMonth() === mo - 1 && check.getUTCDate() === d ? [y, mo, d] : undefined;
250
+ }
251
+ /**
252
+ * The end bound of a job's `until`, in ms: a slot must start before it.
253
+ * `YYYY-MM-DD` is the last local day in `timeZone` on which a slot may
254
+ * start, so the bound is the next local midnight; an ISO instant with `Z`
255
+ * or an offset is the bound itself. Throws {@link JobScheduleError} on any
256
+ * other text, a day that does not exist (`2026-02-30`) included.
257
+ */
258
+ export function untilBoundMs(until, timeZone) {
259
+ const day = calendarDay(until);
260
+ if (day)
261
+ return localToUtcMs(day[0], day[1] - 1, day[2] + 1, 0, 0, timeZone);
262
+ const instant = UNTIL_INSTANT.exec(until);
263
+ if (instant && calendarDay(instant[1])) {
264
+ const ms = Date.parse(until);
265
+ if (Number.isFinite(ms))
266
+ return ms;
267
+ }
268
+ throw new JobScheduleError(`until "${until}" must be a day YYYY-MM-DD or an ISO instant with Z or an offset`);
269
+ }
270
+ /** A job's end date in words: `after 2026-11-17 (Europe/Berlin)` for a day, `before <instant>` for an instant. */
271
+ export function untilText(until, timeZone) {
272
+ return UNTIL_DAY.test(until) ? `after ${until} (${timeZone})` : `before ${until}`;
273
+ }
240
274
  //# sourceMappingURL=job-cadence.js.map
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Wake rules of a job bound to a Claude Code session (KTD7, KTD9): the rule
3
+ * text the hosts take, the pattern checks on add and edit, and the bounded
4
+ * match the job sweep runs on a completed run's result text.
5
+ *
6
+ * The pattern is a JavaScript regular expression with the `m` flag (`^`
7
+ * and `$` match at each line). The match reads at most
8
+ * {@link JOB_WAKE_TEXT_MAX_CHARS} of the text and runs inside `vm` with a
9
+ * {@link JOB_WAKE_MATCH_TIMEOUT_MS} limit, so a pattern that backtracks
10
+ * without end cannot hold the tick. A match that times out counts as
11
+ * matched: a broken pattern wakes once rather than missing an alert.
12
+ */
13
+ /** The longest wake pattern. */
14
+ export declare const JOB_WAKE_PATTERN_MAX_CHARS = 200;
15
+ /** How much of a run's result text the pattern reads (64 KiB of characters). */
16
+ export declare const JOB_WAKE_TEXT_MAX_CHARS: number;
17
+ /** How long one match may run. */
18
+ export declare const JOB_WAKE_MATCH_TIMEOUT_MS = 50;
19
+ /** A wake rule as a host gives it: `never` unbinds the job. */
20
+ export type JobWakeRule = {
21
+ on: "never";
22
+ } | {
23
+ on: "failures";
24
+ } | {
25
+ on: "match";
26
+ pattern: string;
27
+ };
28
+ /** Why a wake rule or pattern was refused. */
29
+ export declare class JobWakeError extends Error {
30
+ constructor(message: string);
31
+ }
32
+ /** What `--wake` takes. */
33
+ export declare const JOB_WAKE_FORMS = "never, failures or match=<pattern>";
34
+ /**
35
+ * Why a wake pattern is refused, or undefined when it is fine: it must be
36
+ * a string of 1 to {@link JOB_WAKE_PATTERN_MAX_CHARS} characters that
37
+ * compiles with the `m` flag and does not match the empty string (it would
38
+ * wake on every run).
39
+ */
40
+ export declare function wakePatternError(pattern: unknown): string | undefined;
41
+ /** The rule `--wake never|failures|match=<pattern>` names. Throws {@link JobWakeError}. */
42
+ export declare function parseWakeRule(text: string): JobWakeRule;
43
+ /** What one bounded match found: `timedOut` (or `broken`, a stored pattern that no longer compiles) counts as matched. */
44
+ export interface WakeMatch {
45
+ matched: boolean;
46
+ timedOut?: boolean;
47
+ broken?: boolean;
48
+ }
49
+ /**
50
+ * Test `pattern` (flag `m`) against the first {@link JOB_WAKE_TEXT_MAX_CHARS}
51
+ * of `text`, in a fresh `vm` context with a {@link JOB_WAKE_MATCH_TIMEOUT_MS}
52
+ * limit. Never throws.
53
+ */
54
+ export declare function matchWake(pattern: string, text: string, timeoutMs?: number): WakeMatch;
55
+ //# sourceMappingURL=job-wake.d.ts.map
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Wake rules of a job bound to a Claude Code session (KTD7, KTD9): the rule
3
+ * text the hosts take, the pattern checks on add and edit, and the bounded
4
+ * match the job sweep runs on a completed run's result text.
5
+ *
6
+ * The pattern is a JavaScript regular expression with the `m` flag (`^`
7
+ * and `$` match at each line). The match reads at most
8
+ * {@link JOB_WAKE_TEXT_MAX_CHARS} of the text and runs inside `vm` with a
9
+ * {@link JOB_WAKE_MATCH_TIMEOUT_MS} limit, so a pattern that backtracks
10
+ * without end cannot hold the tick. A match that times out counts as
11
+ * matched: a broken pattern wakes once rather than missing an alert.
12
+ */
13
+ import { createContext, runInContext } from "node:vm";
14
+ /** The longest wake pattern. */
15
+ export const JOB_WAKE_PATTERN_MAX_CHARS = 200;
16
+ /** How much of a run's result text the pattern reads (64 KiB of characters). */
17
+ export const JOB_WAKE_TEXT_MAX_CHARS = 64 * 1024;
18
+ /** How long one match may run. */
19
+ export const JOB_WAKE_MATCH_TIMEOUT_MS = 50;
20
+ /** Why a wake rule or pattern was refused. */
21
+ export class JobWakeError extends Error {
22
+ constructor(message) {
23
+ super(message);
24
+ this.name = "JobWakeError";
25
+ }
26
+ }
27
+ /** What `--wake` takes. */
28
+ export const JOB_WAKE_FORMS = "never, failures or match=<pattern>";
29
+ /**
30
+ * Why a wake pattern is refused, or undefined when it is fine: it must be
31
+ * a string of 1 to {@link JOB_WAKE_PATTERN_MAX_CHARS} characters that
32
+ * compiles with the `m` flag and does not match the empty string (it would
33
+ * wake on every run).
34
+ */
35
+ export function wakePatternError(pattern) {
36
+ if (typeof pattern !== "string" || pattern === "")
37
+ return "the wake pattern must be a non-empty string";
38
+ if (pattern.length > JOB_WAKE_PATTERN_MAX_CHARS)
39
+ return `the wake pattern is longer than ${JOB_WAKE_PATTERN_MAX_CHARS} characters`;
40
+ // The pattern is the user's own text: it compiles and runs only inside the bounded vm match.
41
+ const empty = boundedTest(pattern, "", JOB_WAKE_MATCH_TIMEOUT_MS);
42
+ if (empty.error !== undefined)
43
+ return `the wake pattern is not a valid regular expression: ${empty.error}`;
44
+ if (empty.timedOut)
45
+ return `the wake pattern takes longer than ${JOB_WAKE_MATCH_TIMEOUT_MS} ms on an empty output; make it simpler`;
46
+ if (empty.matched)
47
+ return "the wake pattern matches an empty output, so it would wake on every run; make it name what to look for";
48
+ return undefined;
49
+ }
50
+ /** Compile `pattern` (flag `m`) and test it on `text` in a fresh `vm` context with a time limit. Never throws. */
51
+ function boundedTest(pattern, text, timeoutMs) {
52
+ const context = createContext({ pattern, text });
53
+ try {
54
+ return { matched: runInContext(`new RegExp(pattern, "m").test(text)`, context, { timeout: timeoutMs }) === true };
55
+ }
56
+ catch (err) {
57
+ if (err?.code === "ERR_SCRIPT_EXECUTION_TIMEOUT")
58
+ return { matched: false, timedOut: true };
59
+ // An error from inside the context is not an instance of this realm's Error.
60
+ const message = err?.message;
61
+ return { matched: false, error: typeof message === "string" ? message : String(err) };
62
+ }
63
+ }
64
+ /** The rule `--wake never|failures|match=<pattern>` names. Throws {@link JobWakeError}. */
65
+ export function parseWakeRule(text) {
66
+ const value = text.trim();
67
+ if (value === "never" || value === "failures")
68
+ return { on: value };
69
+ if (value.startsWith("match=")) {
70
+ const pattern = value.slice("match=".length);
71
+ const error = wakePatternError(pattern);
72
+ if (error)
73
+ throw new JobWakeError(error);
74
+ return { on: "match", pattern };
75
+ }
76
+ throw new JobWakeError(`--wake must be ${JOB_WAKE_FORMS}`);
77
+ }
78
+ /**
79
+ * Test `pattern` (flag `m`) against the first {@link JOB_WAKE_TEXT_MAX_CHARS}
80
+ * of `text`, in a fresh `vm` context with a {@link JOB_WAKE_MATCH_TIMEOUT_MS}
81
+ * limit. Never throws.
82
+ */
83
+ export function matchWake(pattern, text, timeoutMs = JOB_WAKE_MATCH_TIMEOUT_MS) {
84
+ const r = boundedTest(pattern, text.slice(0, JOB_WAKE_TEXT_MAX_CHARS), timeoutMs);
85
+ if (r.timedOut)
86
+ return { matched: true, timedOut: true };
87
+ if (r.error !== undefined)
88
+ return { matched: true, broken: true };
89
+ return { matched: r.matched };
90
+ }
91
+ //# sourceMappingURL=job-wake.js.map
package/dist/jobs.d.ts CHANGED
@@ -27,10 +27,11 @@
27
27
  * rule). The sweep never throws.
28
28
  */
29
29
  import { BATCH_SUBMIT_INTERRUPTED_ERROR } from "./history.js";
30
+ import { type JobWakeRule } from "./job-wake.js";
30
31
  import { type SleepReading } from "./readiness.js";
31
32
  import type { Scheduler } from "./scheduler.js";
32
33
  import { type ResolvedRunLimits } from "./run-limits.js";
33
- import { type JobCadence, type JobCaps, type JobNotify, type JobRecord, type JobTemplate, type JobWindow, type TaskRecord, type TaskStatus } from "./types.js";
34
+ import { type JobCadence, type JobCaps, type JobEndReason, type JobNotify, type JobRecord, type JobTemplate, type JobWindow, type TaskRecord, type TaskStatus } from "./types.js";
34
35
  /** Why a job action was refused; `code` maps to an HTTP status in the hosts. */
35
36
  export declare class JobActionError extends Error {
36
37
  /** `invalid` = bad input (400), `not_found` (404), `conflict` = the state forbids it (409). */
@@ -68,7 +69,26 @@ export interface JobInput {
68
69
  * AS9): it may run from now until then. Later ones follow the cadence.
69
70
  */
70
71
  deadline?: string | Date;
72
+ /**
73
+ * The end date: `YYYY-MM-DD` (the last local day a slot may start,
74
+ * inclusive) or an ISO instant (a slot must start before it).
75
+ */
76
+ until?: string | null;
77
+ /** Runs from now before the job ends, 1 to {@link JOB_MAX_COUNT}. */
78
+ count?: number | null;
79
+ /**
80
+ * Bind the job to the Claude Code session that sets it (KTD8). Never read
81
+ * from the job JSON: only a host that runs in the session sets it.
82
+ */
83
+ wake?: JobWakeInput;
71
84
  }
85
+ /** A wake rule with the session that sets it; `never` unbinds the job and needs no session. */
86
+ export type JobWakeInput = JobWakeRule & {
87
+ /** The session to wake. */
88
+ sessionId?: string;
89
+ /** The origin's agent: a wake needs `claude-code`. */
90
+ agent?: string;
91
+ };
72
92
  /** The fields {@link updateJob} can change; `window: null` removes the window. */
73
93
  export interface JobPatch {
74
94
  title?: string;
@@ -78,6 +98,12 @@ export interface JobPatch {
78
98
  template?: JobTemplate;
79
99
  caps?: JobCapsPatch;
80
100
  notify?: JobNotify;
101
+ /** A new end date; `null` clears it. */
102
+ until?: string | null;
103
+ /** Runs left from now; `null` clears the bound. */
104
+ count?: number | null;
105
+ /** A new wake binding (to the session that sets it), or `never` to unbind. */
106
+ wake?: JobWakeInput;
81
107
  }
82
108
  /**
83
109
  * Caps a caller sets: a value sets the key. `null` removes a time limit, so
@@ -129,9 +155,21 @@ export interface JobSweepResult {
129
155
  autoPaused: string[];
130
156
  /** Running occurrences failed as interrupted this pass. */
131
157
  interrupted: string[];
158
+ /** Jobs that reached their end date or ran their runs this pass. */
159
+ ended: string[];
160
+ /** Runs of bound jobs that became session notices this pass. */
161
+ sessionNotices: string[];
132
162
  }
133
163
  /** A job secret name: what the command sees as an environment variable. */
134
164
  export declare const JOB_SECRET_NAME: RegExp;
165
+ /**
166
+ * The prompt `tidegap jobs add --summarize` stores when the user gives none.
167
+ * It is stored as text on the job, so a later change here leaves existing
168
+ * jobs as they are.
169
+ */
170
+ export declare const DEFAULT_SUMMARIZE_PROMPT: string;
171
+ /** The most runs a job's `count` may ask for. */
172
+ export declare const JOB_MAX_COUNT = 1000;
135
173
  /** Failed slots in a row that pause a job. */
136
174
  export declare const JOB_AUTO_PAUSE_FAILURES = 3;
137
175
  /** How `pauseReason` starts when the third failed slot paused the job: `auto: <first error line>`. */
@@ -140,6 +178,15 @@ export declare const JOB_AUTO_PAUSE_PREFIX = "auto: ";
140
178
  export declare function jobAutoPauseReason(pauseReason: string | undefined): string | undefined;
141
179
  export declare const JOB_INTERRUPTED_ERROR = "interrupted: the tick stopped during the run";
142
180
  export { BATCH_SUBMIT_INTERRUPTED_ERROR };
181
+ /** What an end reason says: `its end date (<until>) passed` or `its runs are done`. */
182
+ export declare function jobEndText(reason: JobEndReason | undefined, until?: string): string;
183
+ /**
184
+ * A job's end condition in words, or undefined for a job with none:
185
+ * `ends after 2026-11-17 (Europe/Berlin)`, `3 runs left`, or both joined by `; `.
186
+ */
187
+ export declare function jobEndsText(job: Pick<JobRecord, "until" | "runsLeft" | "timeZone">): string | undefined;
188
+ /** The session a job wakes, or undefined when it is not bound. */
189
+ export declare function jobWakeSession(job: Pick<JobRecord, "wake" | "originSessionId">): string | undefined;
143
190
  /**
144
191
  * The time limits a run of `job` gets if it starts now, with their sources:
145
192
  * the scheduler's settings reader, or without one the settings file.
@@ -174,7 +221,7 @@ export declare function runJobNow(scheduler: Scheduler, jobId: string, opts?: Jo
174
221
  export declare function removeJob(scheduler: Scheduler, jobId: string, opts?: JobActionOptions): Promise<JobRecord>;
175
222
  /** One job, removed ones included; undefined when the id is unknown. */
176
223
  export declare function getJob(scheduler: Scheduler, jobId: string): JobRecord | undefined;
177
- /** Jobs, oldest first; removed jobs are hidden unless asked for. */
224
+ /** Jobs, oldest first; removed and ended jobs are hidden unless asked for. */
178
225
  export declare function listJobs(scheduler: Scheduler, opts?: {
179
226
  includeRemoved?: boolean;
180
227
  }): JobRecord[];