@tidegap/core 0.20.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.
Files changed (54) hide show
  1. package/dist/channels/digest.js +4 -4
  2. package/dist/channels/format.d.ts +30 -4
  3. package/dist/channels/format.js +125 -22
  4. package/dist/channels/payload.js +8 -6
  5. package/dist/channels/plan.js +3 -2
  6. package/dist/channels/types.d.ts +17 -1
  7. package/dist/energy.d.ts +7 -0
  8. package/dist/energy.js +7 -0
  9. package/dist/grid.d.ts +10 -2
  10. package/dist/grid.js +14 -5
  11. package/dist/handoff.d.ts +88 -6
  12. package/dist/handoff.js +177 -20
  13. package/dist/history.d.ts +19 -0
  14. package/dist/history.js +24 -1
  15. package/dist/index.d.ts +24 -18
  16. package/dist/index.js +16 -12
  17. package/dist/job-cadence.d.ts +10 -0
  18. package/dist/job-cadence.js +34 -0
  19. package/dist/job-wake.d.ts +55 -0
  20. package/dist/job-wake.js +91 -0
  21. package/dist/jobs.d.ts +74 -17
  22. package/dist/jobs.js +420 -75
  23. package/dist/notify.d.ts +9 -0
  24. package/dist/notify.js +17 -3
  25. package/dist/providers/anthropic.js +8 -6
  26. package/dist/providers/base.d.ts +47 -9
  27. package/dist/providers/base.js +29 -4
  28. package/dist/providers/gemini.d.ts +3 -0
  29. package/dist/providers/gemini.js +9 -6
  30. package/dist/providers/http.d.ts +40 -0
  31. package/dist/providers/http.js +82 -0
  32. package/dist/providers/index.d.ts +1 -1
  33. package/dist/providers/index.js +1 -1
  34. package/dist/providers/ollama.d.ts +3 -0
  35. package/dist/providers/ollama.js +8 -5
  36. package/dist/providers/openai.js +7 -5
  37. package/dist/providers/timeout.d.ts +26 -8
  38. package/dist/providers/timeout.js +53 -15
  39. package/dist/readiness.d.ts +39 -3
  40. package/dist/readiness.js +73 -1
  41. package/dist/run-limits.d.ts +268 -0
  42. package/dist/run-limits.js +572 -0
  43. package/dist/schedule-job.d.ts +41 -2
  44. package/dist/schedule-job.js +70 -2
  45. package/dist/scheduler.d.ts +161 -17
  46. package/dist/scheduler.js +485 -128
  47. package/dist/storage/sqlite.d.ts +52 -5
  48. package/dist/storage/sqlite.js +200 -33
  49. package/dist/task-events.d.ts +19 -4
  50. package/dist/task-events.js +51 -5
  51. package/dist/tool-surface.js +62 -7
  52. package/dist/types.d.ts +72 -11
  53. package/dist/types.js +1 -3
  54. package/package.json +5 -2
package/dist/handoff.js CHANGED
@@ -9,11 +9,12 @@
9
9
  * and only Tidegap writes a result file, as a new file, never through a
10
10
  * link.
11
11
  */
12
- import { chmodSync, lstatSync, mkdirSync, realpathSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
12
+ import { chmodSync, existsSync, lstatSync, mkdirSync, realpathSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
13
13
  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;
@@ -373,8 +378,61 @@ export function wakeError(wake, origin, sessionId) {
373
378
  }
374
379
  return undefined;
375
380
  }
376
- /** 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). */
377
- export const WAKE_MARKER_MAX_AGE_MS = 12 * 3_600_000;
381
+ /**
382
+ * The default ledger, `~/.tidegap/queue.db`: the one the CLI, the tick
383
+ * and the plugin's hooks read when no path is given. When only the legacy
384
+ * `~/.ebb/queue.sqlite` exists, that file is returned, so its data stays
385
+ * visible. The MCP server's own default is `queue.db` with no legacy
386
+ * fallback; it creates that file at start, so the two agree from then on.
387
+ */
388
+ export function defaultDbPath() {
389
+ const newPath = join(resolveTidegapHome(), "queue.db");
390
+ const legacyPath = join(homedir(), ".ebb", "queue.sqlite");
391
+ if (!existsSync(newPath) && existsSync(legacyPath))
392
+ return legacyPath;
393
+ return newPath;
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
+ }
409
+ /**
410
+ * True when `dbPath` is the default ledger. The session notice and wake
411
+ * markers under `~/.tidegap/sessions` belong to it: the plugin's hooks
412
+ * read that ledger only, so a pass over another ledger must neither
413
+ * create nor remove them, and a wake for a task in another ledger could
414
+ * never fire. Compares real paths; a missing file compares by
415
+ * its folder's real path and its name.
416
+ */
417
+ export function isDefaultLedger(dbPath) {
418
+ if (dbPath === ":memory:")
419
+ return false;
420
+ // A missing file resolves through its folder, so a linked home still matches.
421
+ const real = (path) => {
422
+ try {
423
+ return realpathSync.native(path);
424
+ }
425
+ catch {
426
+ try {
427
+ return join(realpathSync.native(dirname(path)), basename(path));
428
+ }
429
+ catch {
430
+ return resolve(path);
431
+ }
432
+ }
433
+ };
434
+ return real(dbPath) === real(defaultDbPath());
435
+ }
378
436
  /** `~/.tidegap/sessions/wake`: one marker per session with a task to wake it for. */
379
437
  export function wakeMarkersDir(home = resolveTidegapHome()) {
380
438
  return join(home, "sessions", "wake");
@@ -385,9 +443,11 @@ export function wakeMarkerPath(sessionId, dir = wakeMarkersDir()) {
385
443
  }
386
444
  /**
387
445
  * Create or refresh a session's wake marker (file `0600`, folder `0700`),
388
- * so the plugin's Stop hook starts its waiter. Returns the error message,
389
- * or undefined. Something other than a regular file at the path is left
390
- * alone and reported.
446
+ * so the plugin's Stop hook starts its waiter; its time is `now`. Returns
447
+ * the error message, or undefined. Something other than a regular file at
448
+ * the path is left alone and reported. A waiter or the sweep may remove
449
+ * or write the marker at the same moment: a refresh that finds it gone
450
+ * creates it, and a create that finds one there refreshes it.
391
451
  */
392
452
  export function writeWakeMarker(sessionId, dir = wakeMarkersDir(), now = new Date()) {
393
453
  const path = wakeMarkerPath(sessionId, dir);
@@ -396,20 +456,29 @@ export function writeWakeMarker(sessionId, dir = wakeMarkersDir(), now = new Dat
396
456
  try {
397
457
  mkdirSync(dir, { recursive: true, mode: 0o700 });
398
458
  chmodSync(dir, 0o700);
399
- let there;
400
- try {
401
- there = lstatSync(path);
402
- }
403
- catch {
404
- there = undefined;
459
+ for (let attempt = 0;; attempt++) {
460
+ let there;
461
+ try {
462
+ there = lstatSync(path);
463
+ }
464
+ catch {
465
+ there = undefined;
466
+ }
467
+ if (there && !there.isFile())
468
+ return `${path} is not a regular file`;
469
+ try {
470
+ if (!there)
471
+ writeFileSync(path, `${now.toISOString()}\n`, { mode: 0o600, flag: "wx" });
472
+ utimesSync(path, now, now);
473
+ return undefined;
474
+ }
475
+ catch (err) {
476
+ // Removed or created by another writer since the look: look once more.
477
+ const code = err.code;
478
+ if (attempt > 0 || (code !== "ENOENT" && code !== "EEXIST"))
479
+ throw err;
480
+ }
405
481
  }
406
- if (there && !there.isFile())
407
- return `${path} is not a regular file`;
408
- if (there)
409
- utimesSync(path, now, now);
410
- else
411
- writeFileSync(path, `${now.toISOString()}\n`, { mode: 0o600, flag: "wx" });
412
- return undefined;
413
482
  }
414
483
  catch (err) {
415
484
  return err.message;
@@ -427,4 +496,92 @@ export function removeWakeMarker(sessionId, dir = wakeMarkersDir()) {
427
496
  // already gone
428
497
  }
429
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
+ }
430
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
@@ -70,7 +74,22 @@ export interface TaskActions {
70
74
  reply: boolean;
71
75
  /** Finished (completed or failed): mark read or unread. */
72
76
  markRead: boolean;
77
+ /**
78
+ * Failed provider-call one-off task, a `command` task included: retry it
79
+ * by hand (due on the next tick). A run of a job, and a run that stopped
80
+ * during its Batch submit, are refused.
81
+ */
82
+ retry: boolean;
73
83
  }
84
+ /**
85
+ * The error of a row whose Batch submit a forced stop interrupted (batch 25
86
+ * KTD5). The provider may hold a batch for it, so no path runs it again:
87
+ * `retryTask` and the Python `retry_task` refuse it, and the sweep does not
88
+ * retry it. The text is the marker; `test/fixtures/interrupted-batch-submit.json`
89
+ * shares it with the Python core. It lives here, not in `jobs.ts`, so this
90
+ * module imports nothing from `jobs.ts` (which imports `deriveTitle` from here).
91
+ */
92
+ export declare 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";
74
93
  /** True when the task repeats (a stored rule other than `none`). */
75
94
  export declare function isRepeating(record: Pick<TaskRecord<unknown>, "repeat">): boolean;
76
95
  /** Allowed actions for `record`; see {@link TaskActions}. */
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
@@ -130,6 +142,15 @@ export function deadlineKindLabel(record, quota = {}) {
130
142
  const resetAt = new Date(deadlineMs + schedule.marginH * 3_600_000);
131
143
  return `${label}, reset_at ${resetAt.toISOString()}, margin_h ${schedule.marginH}`;
132
144
  }
145
+ /**
146
+ * The error of a row whose Batch submit a forced stop interrupted (batch 25
147
+ * KTD5). The provider may hold a batch for it, so no path runs it again:
148
+ * `retryTask` and the Python `retry_task` refuse it, and the sweep does not
149
+ * retry it. The text is the marker; `test/fixtures/interrupted-batch-submit.json`
150
+ * shares it with the Python core. It lives here, not in `jobs.ts`, so this
151
+ * module imports nothing from `jobs.ts` (which imports `deriveTitle` from here).
152
+ */
153
+ 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
154
  const PENDING = new Set(["queued", "scheduled", "submitted", "running"]);
134
155
  /** True when the task repeats (a stored rule other than `none`). */
135
156
  export function isRepeating(record) {
@@ -150,6 +171,8 @@ export function taskActions(record) {
150
171
  // A command job's occurrence has no conversation to continue.
151
172
  reply: record.status === "completed" && providerCall && spec?.provider !== "command",
152
173
  markRead: record.status === "completed" || record.status === "failed",
174
+ // The same rule as `Scheduler.retryLater` refuses by.
175
+ retry: record.status === "failed" && providerCall && !record.jobId && record.error !== BATCH_SUBMIT_INTERRUPTED_ERROR,
153
176
  };
154
177
  }
155
178
  /**
package/dist/index.d.ts CHANGED
@@ -39,26 +39,26 @@
39
39
  * plugin, so its `os.environ` fallbacks stay for ergonomics.
40
40
  */
41
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, TickAdapters, TickOptions, } 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
- 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
- export { assessReadiness, 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, Readiness, ReadinessCode, ReadinessFacts, ReadinessProblem, RunnerFact, SleepReading, TickRunnersSnapshot, } from "./readiness.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
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, 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";
55
55
  export type { SelectWindowOptions, SelectWindowResult, } from "./select-window.js";
56
56
  export { ASSUMED_KWH_PER_CALL, classifyBand, aggregateStats, aggregateByRegion, bandHistogram, achievements, } from "./aggregator.js";
57
57
  export type { CarbonStats, RegionStats, BandHistogram, Achievement, } from "./aggregator.js";
58
- 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";
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, handoffCwdError, 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,32 +68,38 @@ 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_RETRY_DELAY_MS, JOB_SECRET_NAME, JobActionError, jobHistory, listJobs, pauseJob, removeJob, resumeJob, runJobNow, sweepJobs, updateJob, } from "./jobs.js";
77
- export type { JobActionOptions, JobHistoryEntry, JobInput, JobPatch, JobSweepResult, JobUpdateOptions } from "./jobs.js";
78
- export { AnthropicAdapter, OpenAIAdapter, GeminiAdapter, OllamaAdapter, DEFAULT_MODEL_BY_PROVIDER, NonRetryableError, ProviderRefusalError, } from "./providers/index.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";
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
- export { MAX_TIMER_MS } from "./providers/timeout.js";
82
+ export { MAX_TIMER_MS, withLlmTimeout } from "./providers/timeout.js";
83
+ export type { LlmRequestOptions } from "./providers/timeout.js";
84
+ export { httpFetch, limitDispatcher } from "./providers/http.js";
81
85
  export { redactPrompt, SCRUB_MIN_LENGTH, scrubCutEdges, scrubValues } from "./redact.js";
82
86
  export { retryWithBackoff } from "./scheduler.js";
83
87
  export { ProviderDeferError } from "./providers/defer.js";
84
88
  export type { BatchHandle, DispatchOptions, DispatchOrigin, DispatchResult, ModelUsage, ProviderAdapter, RunDetails, } from "./providers/index.js";
85
89
  export { SESSION_NOTICE_MAX_AGE_MS, SESSION_NOTICES_SINCE_META_KEY, TaskStore } from "./storage/sqlite.js";
86
- export { PROGRESS_GAP_MS, PROGRESS_LINE_MAX_CHARS, PROGRESS_MAX_EVENTS, PROGRESS_QUIET_MS, TASK_EVENT_KINDS, cleanProgressText, createProgressRecorder, eventSummary, formatTaskEvent, isTaskEventKind, normalizeActor, progressLine, taskEventJson, } from "./task-events.js";
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";
87
91
  export type { ProgressRecorder, TaskEvent, TaskEventActor, TaskEventInput, TaskEventKind } from "./task-events.js";
88
- export type { SessionNotice, TaskListFilter, TaskStoreOptions } from "./storage/sqlite.js";
92
+ export type { JobNotice, SessionNotice, TaskListFilter, TaskStoreOptions } from "./storage/sqlite.js";
89
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";
90
94
  export { checkRequestedRegion, regionRequestUrl, regionSettingReader, unknownRegionMessage, } from "./region-host.js";
91
95
  export type { RegionSettingReaderOptions } from "./region-host.js";
92
96
  export type { RegionApproximation, RegionCatalogEntry, RegionResolution, RegionSource, ResolveRegionInput, } from "./region.js";
93
- export { DEFAULT_PUE, LEGACY_KWH_PER_TASK, MODEL_ENERGY_COEFFICIENTS, MODEL_FAMILIES, ENERGY_SOURCES, normalizeModelName, lookupModelEnergy, resolveModelEnergy, estimateEnergyKwh, gramsForIntensity, } from "./energy.js";
97
+ 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";
98
+ export type { DurationValue, FailureClass, FailureFacts, FinalReason, IgnoredRunLimitLine, LoadRunLimitSettingsOptions, ResolvedRunLimit, ResolvedRunLimits, RetryPlan, RunLimitDefinition, RunLimitDetail, RunLimitName, RunLimitSettings, RunLimitsDetails, RunLimitSource, TaskRunLimitsView, } from "./run-limits.js";
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";
94
100
  export type { EnergySourceTier, EnergyResolutionTier, ModelLifecycleStatus, ModelEnergyCoefficients, ModelFamily, ResolvedModelEnergy, EstimateEnergyOpts, } from "./energy.js";
95
101
  export { ALL_TOOL_HOSTS, TOOL_SURFACE, getToolDef, getToolDefOrThrow, toolsForHost, descriptionForHost, paramHosts, paramIncludedForHost, paramsForHost, paramOptionalForHost, neutralSurfaceForHost, } from "./tool-surface.js";
96
- export { commandJobRefusal, QUEUE_ADD_COMMAND_LINE, endJobOfTask, isJobRepeat, JOB_ONLY_PARAMS, JOB_REPEATS, jobParamsRefusal, jobToolsFor, jobToolView, jobUnsupportedRefusal, 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";
97
103
  export type { JobRepeat, JobToolView, ScheduleJobArgs } from "./schedule-job.js";
98
104
  export type { ToolHost, ToolParamKind, ToolParam, ToolAnnotations, CanonicalToolDef, } from "./tool-surface.js";
99
105
  export { canonicalize, defaultSigningKeyPath, loadOrCreateSigningKey, signReceipt, verifyReceipt, } from "./sign.js";
package/dist/index.js CHANGED
@@ -41,22 +41,22 @@
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
- export { assessReadiness, 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";
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, 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";
54
54
  export { ASSUMED_KWH_PER_CALL, classifyBand, aggregateStats, aggregateByRegion, bandHistogram, achievements, } from "./aggregator.js";
55
55
  // Aggregate carbon-budget alerts (ROADMAP item 4).
56
56
  // Desktop notifications (v0.17): pure command builder, hosts spawn it.
57
- 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
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, handoffCwdError, 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,25 +64,29 @@ 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_RETRY_DELAY_MS, JOB_SECRET_NAME, JobActionError, jobHistory, listJobs, pauseJob, removeJob, resumeJob, runJobNow, sweepJobs, updateJob, } from "./jobs.js";
72
- export { AnthropicAdapter, OpenAIAdapter, GeminiAdapter, OllamaAdapter, DEFAULT_MODEL_BY_PROVIDER, NonRetryableError, ProviderRefusalError, } from "./providers/index.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";
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
- export { MAX_TIMER_MS } from "./providers/timeout.js";
76
+ export { MAX_TIMER_MS, withLlmTimeout } from "./providers/timeout.js";
77
+ export { httpFetch, limitDispatcher } from "./providers/http.js";
75
78
  export { redactPrompt, SCRUB_MIN_LENGTH, scrubCutEdges, scrubValues } from "./redact.js";
76
79
  export { retryWithBackoff } from "./scheduler.js";
77
80
  export { ProviderDeferError } from "./providers/defer.js";
78
81
  export { SESSION_NOTICE_MAX_AGE_MS, SESSION_NOTICES_SINCE_META_KEY, TaskStore } from "./storage/sqlite.js";
79
- export { PROGRESS_GAP_MS, PROGRESS_LINE_MAX_CHARS, PROGRESS_MAX_EVENTS, PROGRESS_QUIET_MS, TASK_EVENT_KINDS, cleanProgressText, createProgressRecorder, eventSummary, formatTaskEvent, isTaskEventKind, normalizeActor, progressLine, taskEventJson, } from "./task-events.js";
82
+ 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";
80
83
  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";
81
84
  export { checkRequestedRegion, regionRequestUrl, regionSettingReader, unknownRegionMessage, } from "./region-host.js";
82
- export { DEFAULT_PUE, LEGACY_KWH_PER_TASK, MODEL_ENERGY_COEFFICIENTS, MODEL_FAMILIES, ENERGY_SOURCES, normalizeModelName, lookupModelEnergy, resolveModelEnergy, estimateEnergyKwh, gramsForIntensity, } from "./energy.js";
85
+ 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";
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";
83
87
  export { ALL_TOOL_HOSTS, TOOL_SURFACE, getToolDef, getToolDefOrThrow, toolsForHost, descriptionForHost, paramHosts, paramIncludedForHost, paramsForHost, paramOptionalForHost, neutralSurfaceForHost, } from "./tool-surface.js";
84
88
  // schedule_task sugar for floating recurring jobs (KTD16), shared by both hosts.
85
- export { commandJobRefusal, QUEUE_ADD_COMMAND_LINE, endJobOfTask, isJobRepeat, JOB_ONLY_PARAMS, JOB_REPEATS, jobParamsRefusal, jobToolsFor, jobToolView, jobUnsupportedRefusal, 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";
86
90
  export { canonicalize, defaultSigningKeyPath, loadOrCreateSigningKey, signReceipt, verifyReceipt, } from "./sign.js";
87
91
  export { TIDEGAP_HOME_DIR, resolveTidegapHome, tidegapPath, } from "./paths.js";
88
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