@tidegap/core 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/README.md +1 -1
  2. package/dist/agent-snippet.d.ts +30 -0
  3. package/dist/agent-snippet.js +120 -0
  4. package/dist/channels/commands.d.ts +137 -0
  5. package/dist/channels/commands.js +377 -0
  6. package/dist/channels/delivery-codes.d.ts +9 -0
  7. package/dist/channels/delivery-codes.js +53 -0
  8. package/dist/channels/digest.d.ts +102 -0
  9. package/dist/channels/digest.js +146 -0
  10. package/dist/channels/format.d.ts +138 -0
  11. package/dist/channels/format.js +425 -0
  12. package/dist/channels/index.d.ts +15 -0
  13. package/dist/channels/index.js +15 -0
  14. package/dist/channels/kinds/command.d.ts +13 -0
  15. package/dist/channels/kinds/command.js +65 -0
  16. package/dist/channels/kinds/discord.d.ts +16 -0
  17. package/dist/channels/kinds/discord.js +67 -0
  18. package/dist/channels/kinds/email.d.ts +20 -0
  19. package/dist/channels/kinds/email.js +162 -0
  20. package/dist/channels/kinds/index.d.ts +8 -0
  21. package/dist/channels/kinds/index.js +17 -0
  22. package/dist/channels/kinds/ntfy.d.ts +25 -0
  23. package/dist/channels/kinds/ntfy.js +163 -0
  24. package/dist/channels/kinds/pushover.d.ts +11 -0
  25. package/dist/channels/kinds/pushover.js +77 -0
  26. package/dist/channels/kinds/shared.d.ts +25 -0
  27. package/dist/channels/kinds/shared.js +39 -0
  28. package/dist/channels/kinds/shortcuts.d.ts +9 -0
  29. package/dist/channels/kinds/shortcuts.js +45 -0
  30. package/dist/channels/kinds/slack.d.ts +8 -0
  31. package/dist/channels/kinds/slack.js +57 -0
  32. package/dist/channels/kinds/telegram.d.ts +4 -0
  33. package/dist/channels/kinds/telegram.js +26 -0
  34. package/dist/channels/kinds/webhook.d.ts +30 -0
  35. package/dist/channels/kinds/webhook.js +177 -0
  36. package/dist/channels/payload.d.ts +36 -0
  37. package/dist/channels/payload.js +61 -0
  38. package/dist/channels/plan.d.ts +24 -0
  39. package/dist/channels/plan.js +66 -0
  40. package/dist/channels/registry.d.ts +191 -0
  41. package/dist/channels/registry.js +125 -0
  42. package/dist/channels/telegram.d.ts +110 -0
  43. package/dist/channels/telegram.js +168 -0
  44. package/dist/channels/types.d.ts +107 -0
  45. package/dist/channels/types.js +26 -0
  46. package/dist/claude-tools.d.ts +29 -0
  47. package/dist/claude-tools.js +49 -0
  48. package/dist/data/tables.generated.d.ts +6 -0
  49. package/dist/data/tables.generated.js +37 -0
  50. package/dist/energy.d.ts +84 -0
  51. package/dist/energy.js +138 -0
  52. package/dist/grid.d.ts +17 -2
  53. package/dist/grid.js +43 -4
  54. package/dist/handoff.d.ts +171 -0
  55. package/dist/handoff.js +482 -0
  56. package/dist/history.d.ts +17 -0
  57. package/dist/history.js +14 -1
  58. package/dist/index.d.ts +49 -15
  59. package/dist/index.js +36 -8
  60. package/dist/job-cadence.d.ts +76 -0
  61. package/dist/job-cadence.js +240 -0
  62. package/dist/jobs.d.ts +183 -0
  63. package/dist/jobs.js +917 -0
  64. package/dist/notify.d.ts +11 -0
  65. package/dist/notify.js +19 -4
  66. package/dist/postpone.d.ts +113 -0
  67. package/dist/postpone.js +185 -0
  68. package/dist/providers/anthropic.js +14 -8
  69. package/dist/providers/base.d.ts +145 -2
  70. package/dist/providers/base.js +41 -1
  71. package/dist/providers/budget.d.ts +25 -0
  72. package/dist/providers/budget.js +57 -0
  73. package/dist/providers/defaults.js +4 -0
  74. package/dist/providers/defer.d.ts +16 -0
  75. package/dist/providers/defer.js +31 -0
  76. package/dist/providers/gemini.d.ts +4 -0
  77. package/dist/providers/gemini.js +34 -24
  78. package/dist/providers/http.d.ts +40 -0
  79. package/dist/providers/http.js +82 -0
  80. package/dist/providers/index.d.ts +2 -2
  81. package/dist/providers/index.js +1 -1
  82. package/dist/providers/ollama.d.ts +4 -0
  83. package/dist/providers/ollama.js +32 -25
  84. package/dist/providers/openai.js +11 -9
  85. package/dist/providers/timeout.d.ts +36 -0
  86. package/dist/providers/timeout.js +71 -0
  87. package/dist/quota.d.ts +7 -2
  88. package/dist/quota.js +12 -27
  89. package/dist/readiness.d.ts +205 -0
  90. package/dist/readiness.js +326 -0
  91. package/dist/redact.d.ts +42 -0
  92. package/dist/redact.js +110 -0
  93. package/dist/region-host.d.ts +30 -0
  94. package/dist/region-host.js +69 -0
  95. package/dist/region.d.ts +102 -20
  96. package/dist/region.js +175 -23
  97. package/dist/run-limits.d.ts +268 -0
  98. package/dist/run-limits.js +572 -0
  99. package/dist/run-session.d.ts +36 -0
  100. package/dist/run-session.js +72 -0
  101. package/dist/schedule-job.d.ts +118 -0
  102. package/dist/schedule-job.js +243 -0
  103. package/dist/scheduler.d.ts +391 -18
  104. package/dist/scheduler.js +1341 -177
  105. package/dist/sign.d.ts +8 -1
  106. package/dist/sign.js +49 -3
  107. package/dist/storage/sqlite.d.ts +183 -5
  108. package/dist/storage/sqlite.js +720 -19
  109. package/dist/task-events.d.ts +117 -0
  110. package/dist/task-events.js +345 -0
  111. package/dist/tool-surface.d.ts +31 -2
  112. package/dist/tool-surface.js +390 -65
  113. package/dist/types.d.ts +267 -3
  114. package/dist/types.js +6 -1
  115. package/dist/zone-time.d.ts +22 -0
  116. package/dist/zone-time.js +76 -0
  117. package/package.json +13 -5
  118. package/dist/aggregator.d.ts.map +0 -1
  119. package/dist/aggregator.js.map +0 -1
  120. package/dist/budget.d.ts.map +0 -1
  121. package/dist/budget.js.map +0 -1
  122. package/dist/data/tables.generated.d.ts.map +0 -1
  123. package/dist/data/tables.generated.js.map +0 -1
  124. package/dist/energy.d.ts.map +0 -1
  125. package/dist/energy.js.map +0 -1
  126. package/dist/grid.d.ts.map +0 -1
  127. package/dist/grid.js.map +0 -1
  128. package/dist/history.d.ts.map +0 -1
  129. package/dist/history.js.map +0 -1
  130. package/dist/index.d.ts.map +0 -1
  131. package/dist/index.js.map +0 -1
  132. package/dist/notify.d.ts.map +0 -1
  133. package/dist/notify.js.map +0 -1
  134. package/dist/paths.d.ts.map +0 -1
  135. package/dist/paths.js.map +0 -1
  136. package/dist/providers/anthropic.d.ts.map +0 -1
  137. package/dist/providers/anthropic.js.map +0 -1
  138. package/dist/providers/base.d.ts.map +0 -1
  139. package/dist/providers/base.js.map +0 -1
  140. package/dist/providers/defaults.d.ts.map +0 -1
  141. package/dist/providers/defaults.js.map +0 -1
  142. package/dist/providers/gemini.d.ts.map +0 -1
  143. package/dist/providers/gemini.js.map +0 -1
  144. package/dist/providers/index.d.ts.map +0 -1
  145. package/dist/providers/index.js.map +0 -1
  146. package/dist/providers/ollama.d.ts.map +0 -1
  147. package/dist/providers/ollama.js.map +0 -1
  148. package/dist/providers/openai.d.ts.map +0 -1
  149. package/dist/providers/openai.js.map +0 -1
  150. package/dist/quota.d.ts.map +0 -1
  151. package/dist/quota.js.map +0 -1
  152. package/dist/recommend.d.ts.map +0 -1
  153. package/dist/recommend.js.map +0 -1
  154. package/dist/redact.d.ts.map +0 -1
  155. package/dist/redact.js.map +0 -1
  156. package/dist/region.d.ts.map +0 -1
  157. package/dist/region.js.map +0 -1
  158. package/dist/routing.d.ts.map +0 -1
  159. package/dist/routing.js.map +0 -1
  160. package/dist/scheduler.d.ts.map +0 -1
  161. package/dist/scheduler.js.map +0 -1
  162. package/dist/select-window.d.ts.map +0 -1
  163. package/dist/select-window.js.map +0 -1
  164. package/dist/sign.d.ts.map +0 -1
  165. package/dist/sign.js.map +0 -1
  166. package/dist/storage/sqlite.d.ts.map +0 -1
  167. package/dist/storage/sqlite.js.map +0 -1
  168. package/dist/tool-surface.d.ts.map +0 -1
  169. package/dist/tool-surface.js.map +0 -1
  170. package/dist/types.d.ts.map +0 -1
  171. package/dist/types.js.map +0 -1
package/dist/notify.d.ts CHANGED
@@ -39,6 +39,17 @@ export interface OsNotifyOptions {
39
39
  export declare function osNotifyCommand(platform: NodeJS.Platform, title: string, body: string, opts?: OsNotifyOptions): OsNotifyCommand | null;
40
40
  /** Characters of result text shown in a notification body. */
41
41
  export declare const NOTIFY_PREVIEW_CHARS = 140;
42
+ /** `text` default-redacted, control characters removed, whitespace runs joined, trimmed. */
43
+ export declare function oneLine(text: string): string;
44
+ /** `text` cut to `max` characters (code points) plus an ellipsis. */
45
+ export declare function clip(text: string, max: number): string;
46
+ /**
47
+ * The first line of a task's error that has visible text once redacted,
48
+ * stripped of control characters and made one line, cut to `max`
49
+ * characters: the line every failure notice and channel message shows.
50
+ * Undefined when no line has visible text.
51
+ */
52
+ export declare function firstErrorLine(error: string | undefined, max?: number): string | undefined;
42
53
  /**
43
54
  * Notification title and body for a finished task: the task title (or id),
44
55
  * a redacted one-line preview of the result (completed) or the first line
package/dist/notify.js CHANGED
@@ -72,15 +72,31 @@ export function osNotifyCommand(platform, title, body, opts = {}) {
72
72
  }
73
73
  /** Characters of result text shown in a notification body. */
74
74
  export const NOTIFY_PREVIEW_CHARS = 140;
75
- function oneLine(text) {
75
+ /** `text` default-redacted, control characters removed, whitespace runs joined, trimmed. */
76
+ export function oneLine(text) {
76
77
  return stripControlChars(redactPrompt(text, undefined))
77
78
  .replace(/\s+/g, " ")
78
79
  .trim();
79
80
  }
80
- function clip(text, max) {
81
+ /** `text` cut to `max` characters (code points) plus an ellipsis. */
82
+ export function clip(text, max) {
81
83
  const chars = Array.from(text);
82
84
  return chars.length > max ? `${chars.slice(0, max).join("")}…` : text;
83
85
  }
86
+ /**
87
+ * The first line of a task's error that has visible text once redacted,
88
+ * stripped of control characters and made one line, cut to `max`
89
+ * characters: the line every failure notice and channel message shows.
90
+ * Undefined when no line has visible text.
91
+ */
92
+ export function firstErrorLine(error, max = NOTIFY_PREVIEW_CHARS) {
93
+ for (const line of (error ?? "").split(/\r?\n/)) {
94
+ const text = oneLine(line);
95
+ if (text)
96
+ return clip(text, max);
97
+ }
98
+ return undefined;
99
+ }
84
100
  function grams(receipt) {
85
101
  if (receipt && typeof receipt.actualCarbonGCo2 === "number") {
86
102
  return `${receipt.actualCarbonGCo2} gCO2e`;
@@ -99,10 +115,9 @@ export function taskNotificationContent(record) {
99
115
  const name = clip(oneLine(record.title ?? "") || record.taskId, 80);
100
116
  const show = `tidegap queue show ${record.taskId}`;
101
117
  if (record.status === "failed") {
102
- const firstErr = (record.error ?? "").split(/\r?\n/).find((l) => l.trim()) ?? "unknown error";
103
118
  return {
104
119
  title: `Tidegap: failed: ${name}`,
105
- body: `${clip(oneLine(firstErr), NOTIFY_PREVIEW_CHARS)}\n${show}`,
120
+ body: `${firstErrorLine(record.error) ?? "unknown error"}\n${show}`,
106
121
  };
107
122
  }
108
123
  const r = record.result;
@@ -0,0 +1,113 @@
1
+ /**
2
+ * "Later" (coherence KTD4 to KTD6): move a pending task so it never runs
3
+ * earlier than its current planned start. One preset vocabulary for every
4
+ * surface (KTD15), resolved in the process's local time zone. Pure apart
5
+ * from the limit-reset hint, which the helpers read and write through the
6
+ * store's meta table.
7
+ *
8
+ * `Scheduler.postponeTask` turns a resolved target into a reschedule: delay
9
+ * presets and `after_limit_reset` become `{notBefore}` (the scheduler's
10
+ * `startFields` rule: the deadline rises to at least `notBefore + 2 h` and
11
+ * a later one is kept), day presets become `{dayStart, dayEnd}` (the
12
+ * deadline is the window end), and a pin becomes `{at}`.
13
+ */
14
+ import type { RescheduleTarget } from "./scheduler.js";
15
+ import type { TaskRecord } from "./types.js";
16
+ /** Preset ids every surface maps to (KTD15). */
17
+ export type PostponePreset = "1h" | "tonight" | "tomorrow_morning" | "after_limit_reset";
18
+ /** Presets in display order. */
19
+ export declare const POSTPONE_PRESETS: readonly PostponePreset[];
20
+ /** Display labels of the presets (KTD15). */
21
+ export declare const POSTPONE_LABELS: Readonly<Record<PostponePreset, string>>;
22
+ /** Target of {@link Scheduler.postponeTask}: a preset, a delay or an exact pin. */
23
+ export type PostponeTarget =
24
+ /** `resetAt` applies to `after_limit_reset` only and wins over every other reset source. */
25
+ {
26
+ preset: PostponePreset;
27
+ resetAt?: string | Date;
28
+ }
29
+ /** Not before the planned start plus `delayMs` (the CLI's `+<dur>`). */
30
+ | {
31
+ delayMs: number;
32
+ }
33
+ /** An exact time (a picked time). */
34
+ | {
35
+ until: string | Date;
36
+ };
37
+ /** A known limit reset and where it came from (`caller`, `hint`, or the source's own name). */
38
+ export interface LimitReset {
39
+ at: Date;
40
+ source: string;
41
+ }
42
+ /**
43
+ * The plugged-in reset source (KTD5), for example the CLI usage module's
44
+ * Claude limit reset. Returns null when it knows no reset for `task`.
45
+ */
46
+ export type LimitResetSource = (task: TaskRecord<unknown>, now: Date) => LimitReset | null | Promise<LimitReset | null>;
47
+ /** One entry of {@link postponeOptions}; `not_before` is ISO-8601, null when unavailable. */
48
+ export interface PostponeOption {
49
+ preset: PostponePreset;
50
+ label: string;
51
+ not_before: string | null;
52
+ available: boolean;
53
+ reason?: string;
54
+ }
55
+ /** Ledger meta key of the last reset time a caller gave (`{at, provider}`). */
56
+ export declare const LIMIT_RESET_HINT_META_KEY = "limit_reset_hint";
57
+ /** The meta part of a `TaskStore` the hint helpers need. */
58
+ export interface MetaStore {
59
+ getMeta(key: string): string | undefined;
60
+ setMeta(key: string, value: string): void;
61
+ }
62
+ /** Local hour the `tonight` preset starts; also the start of a channel's quiet hours (KTD10). */
63
+ export declare const TONIGHT_START_H = 22;
64
+ /** Local hour the `tomorrow_morning` preset starts; also the end of a channel's quiet hours (KTD10). */
65
+ export declare const MORNING_START_H = 9;
66
+ export declare const NEEDS_RESET_TIME = "needs the reset time";
67
+ /** The stored hint, when it is still in the future. */
68
+ export declare function readLimitResetHint(store: MetaStore | undefined, now: Date): LimitReset | null;
69
+ /** Store a caller-given reset as the hint for later tasks. */
70
+ export declare function writeLimitResetHint(store: MetaStore | undefined, at: Date, provider: string | undefined): void;
71
+ /**
72
+ * The reset `after_limit_reset` waits for (R14): the plugged-in source,
73
+ * else a still-future stored hint. A caller-given `reset_at` is handled by
74
+ * the caller before this, because it wins over both.
75
+ */
76
+ export declare function resolveLimitReset(record: TaskRecord<unknown>, now: Date, source: LimitResetSource | undefined, store: MetaStore | undefined): Promise<LimitReset | null>;
77
+ /** The provider of a provider-call task, if the body parses. */
78
+ export declare function taskProvider(record: TaskRecord<unknown>): string | undefined;
79
+ /**
80
+ * The planned start (KTD4): `scheduledFor` if in the future, else a future
81
+ * `notBefore`, else now. `future` is false for "now", where any target at
82
+ * or after now is later.
83
+ */
84
+ export declare function plannedStart(record: TaskRecord<unknown>, now: Date): {
85
+ at: Date;
86
+ future: boolean;
87
+ };
88
+ /** "23:00" on the local day of `now`, else "2026-10-23 23:00". */
89
+ export declare function localTimeLabel(at: Date, now: Date): string;
90
+ /** A resolved postpone: the earliest start and the reschedule that writes it. */
91
+ export type ResolvedPostpone = {
92
+ ok: true;
93
+ notBefore: Date;
94
+ reschedule: RescheduleTarget;
95
+ } | {
96
+ ok: false;
97
+ reason: string;
98
+ };
99
+ /**
100
+ * Resolve `target` for `record` at `now` (KTD4). `reset` is the reset an
101
+ * `after_limit_reset` target uses (already resolved by precedence); a
102
+ * target's own `resetAt` wins over it. Refuses a task that is not movable,
103
+ * a window with less than one hour left, a missing reset, and any start at
104
+ * or before the planned start.
105
+ */
106
+ export declare function resolvePostpone(record: TaskRecord<unknown>, target: PostponeTarget, now: Date, reset: LimitReset | null): ResolvedPostpone;
107
+ /**
108
+ * The presets for `record` with their resolved earliest start (KTD6), for
109
+ * every surface: the API's `later_options`, the page menu, the clients and
110
+ * the Telegram buttons. `reset` is the known limit reset, or null.
111
+ */
112
+ export declare function postponeOptions(record: TaskRecord<unknown>, now: Date, reset: LimitReset | null): PostponeOption[];
113
+ //# sourceMappingURL=postpone.d.ts.map
@@ -0,0 +1,185 @@
1
+ /**
2
+ * "Later" (coherence KTD4 to KTD6): move a pending task so it never runs
3
+ * earlier than its current planned start. One preset vocabulary for every
4
+ * surface (KTD15), resolved in the process's local time zone. Pure apart
5
+ * from the limit-reset hint, which the helpers read and write through the
6
+ * store's meta table.
7
+ *
8
+ * `Scheduler.postponeTask` turns a resolved target into a reschedule: delay
9
+ * presets and `after_limit_reset` become `{notBefore}` (the scheduler's
10
+ * `startFields` rule: the deadline rises to at least `notBefore + 2 h` and
11
+ * a later one is kept), day presets become `{dayStart, dayEnd}` (the
12
+ * deadline is the window end), and a pin becomes `{at}`.
13
+ */
14
+ import { taskActions } from "./history.js";
15
+ /** Presets in display order. */
16
+ export const POSTPONE_PRESETS = ["1h", "tonight", "tomorrow_morning", "after_limit_reset"];
17
+ /** Display labels of the presets (KTD15). */
18
+ export const POSTPONE_LABELS = {
19
+ "1h": "One hour later",
20
+ tonight: "Tonight",
21
+ tomorrow_morning: "Tomorrow morning",
22
+ after_limit_reset: "After limit reset",
23
+ };
24
+ /** Ledger meta key of the last reset time a caller gave (`{at, provider}`). */
25
+ export const LIMIT_RESET_HINT_META_KEY = "limit_reset_hint";
26
+ const MINUTE_MS = 60_000;
27
+ const HOUR_MS = 3_600_000;
28
+ /** `after_limit_reset` waits this long past the reset. */
29
+ const RESET_MARGIN_MS = 5 * MINUTE_MS;
30
+ /** Local hour the `tonight` preset starts; also the start of a channel's quiet hours (KTD10). */
31
+ export const TONIGHT_START_H = 22;
32
+ const TONIGHT_END_H = 6;
33
+ /** Local hour the `tomorrow_morning` preset starts; also the end of a channel's quiet hours (KTD10). */
34
+ export const MORNING_START_H = 9;
35
+ const MORNING_END_H = 12;
36
+ export const NEEDS_RESET_TIME = "needs the reset time";
37
+ /** The stored hint, when it is still in the future. */
38
+ export function readLimitResetHint(store, now) {
39
+ const raw = store?.getMeta(LIMIT_RESET_HINT_META_KEY);
40
+ if (!raw)
41
+ return null;
42
+ try {
43
+ const at = new Date(JSON.parse(raw).at ?? "");
44
+ return at.getTime() > now.getTime() ? { at, source: "hint" } : null;
45
+ }
46
+ catch {
47
+ return null;
48
+ }
49
+ }
50
+ /** Store a caller-given reset as the hint for later tasks. */
51
+ export function writeLimitResetHint(store, at, provider) {
52
+ store?.setMeta(LIMIT_RESET_HINT_META_KEY, JSON.stringify({ at: at.toISOString(), ...(provider ? { provider } : {}) }));
53
+ }
54
+ /**
55
+ * The reset `after_limit_reset` waits for (R14): the plugged-in source,
56
+ * else a still-future stored hint. A caller-given `reset_at` is handled by
57
+ * the caller before this, because it wins over both.
58
+ */
59
+ export async function resolveLimitReset(record, now, source, store) {
60
+ const plugged = source ? await source(record, now) : null;
61
+ return plugged ?? readLimitResetHint(store, now);
62
+ }
63
+ /** The provider of a provider-call task, if the body parses. */
64
+ export function taskProvider(record) {
65
+ try {
66
+ return JSON.parse(record.bodyJson ?? "").provider;
67
+ }
68
+ catch {
69
+ return undefined;
70
+ }
71
+ }
72
+ /**
73
+ * The planned start (KTD4): `scheduledFor` if in the future, else a future
74
+ * `notBefore`, else now. `future` is false for "now", where any target at
75
+ * or after now is later.
76
+ */
77
+ export function plannedStart(record, now) {
78
+ for (const iso of [record.scheduledFor, record.notBefore]) {
79
+ const t = iso ? Date.parse(iso) : Number.NaN;
80
+ if (Number.isFinite(t) && t > now.getTime())
81
+ return { at: new Date(t), future: true };
82
+ }
83
+ return { at: now, future: false };
84
+ }
85
+ /** A local wall-clock instant `dayOffset` days after `base`'s local day. */
86
+ function localAt(base, dayOffset, hour) {
87
+ return new Date(base.getFullYear(), base.getMonth(), base.getDate() + dayOffset, hour, 0, 0, 0);
88
+ }
89
+ /** "23:00" on the local day of `now`, else "2026-10-23 23:00". */
90
+ export function localTimeLabel(at, now) {
91
+ const p = (n) => String(n).padStart(2, "0");
92
+ const time = `${p(at.getHours())}:${p(at.getMinutes())}`;
93
+ const sameDay = at.getFullYear() === now.getFullYear() && at.getMonth() === now.getMonth() && at.getDate() === now.getDate();
94
+ return sameDay ? time : `${at.getFullYear()}-${p(at.getMonth() + 1)}-${p(at.getDate())} ${time}`;
95
+ }
96
+ /**
97
+ * Resolve `target` for `record` at `now` (KTD4). `reset` is the reset an
98
+ * `after_limit_reset` target uses (already resolved by precedence); a
99
+ * target's own `resetAt` wins over it. Refuses a task that is not movable,
100
+ * a window with less than one hour left, a missing reset, and any start at
101
+ * or before the planned start.
102
+ */
103
+ export function resolvePostpone(record, target, now, reset) {
104
+ if (!taskActions(record).later) {
105
+ return { ok: false, reason: `task is ${record.status}; only queued or scheduled provider-call tasks can move` };
106
+ }
107
+ const planned = plannedStart(record, now);
108
+ let start;
109
+ let reschedule;
110
+ if ("until" in target) {
111
+ start = target.until instanceof Date ? target.until : new Date(target.until);
112
+ if (Number.isNaN(start.getTime()))
113
+ return { ok: false, reason: `not an ISO-8601 time: ${JSON.stringify(target.until)}` };
114
+ reschedule = { at: start };
115
+ }
116
+ else if ("delayMs" in target) {
117
+ if (!Number.isFinite(target.delayMs) || target.delayMs <= 0) {
118
+ return { ok: false, reason: "a delay must be a positive duration" };
119
+ }
120
+ start = new Date(planned.at.getTime() + target.delayMs);
121
+ reschedule = { notBefore: start };
122
+ }
123
+ else if (target.preset === "1h") {
124
+ start = new Date(planned.at.getTime() + HOUR_MS);
125
+ reschedule = { notBefore: start };
126
+ }
127
+ else if (target.preset === "after_limit_reset") {
128
+ let at;
129
+ if (target.resetAt !== undefined) {
130
+ at = target.resetAt instanceof Date ? target.resetAt : new Date(target.resetAt);
131
+ if (Number.isNaN(at.getTime()))
132
+ return { ok: false, reason: `reset time is not ISO-8601: ${JSON.stringify(target.resetAt)}` };
133
+ if (at.getTime() <= now.getTime())
134
+ return { ok: false, reason: `the reset time ${at.toISOString()} is in the past` };
135
+ }
136
+ else {
137
+ at = reset?.at;
138
+ }
139
+ if (!at)
140
+ return { ok: false, reason: NEEDS_RESET_TIME };
141
+ start = new Date(Math.max(at.getTime(), now.getTime()) + RESET_MARGIN_MS);
142
+ reschedule = { notBefore: start };
143
+ }
144
+ else if (target.preset === "tonight" || target.preset === "tomorrow_morning") {
145
+ let end;
146
+ if (target.preset === "tomorrow_morning") {
147
+ start = localAt(now, 1, MORNING_START_H);
148
+ end = localAt(now, 1, MORNING_END_H);
149
+ }
150
+ else if (now.getHours() < TONIGHT_END_H) {
151
+ start = now;
152
+ end = localAt(now, 0, TONIGHT_END_H);
153
+ }
154
+ else {
155
+ start = new Date(Math.max(localAt(now, 0, TONIGHT_START_H).getTime(), now.getTime()));
156
+ end = localAt(now, 1, TONIGHT_END_H);
157
+ }
158
+ if (end.getTime() - start.getTime() < HOUR_MS)
159
+ return { ok: false, reason: "less than one hour of tonight is left" };
160
+ reschedule = { dayStart: start, dayEnd: end };
161
+ }
162
+ else {
163
+ return { ok: false, reason: `unknown preset ${JSON.stringify(target.preset)}` };
164
+ }
165
+ const later = planned.future ? start.getTime() > planned.at.getTime() : start.getTime() >= now.getTime();
166
+ if (!later) {
167
+ return { ok: false, reason: `already planned for ${localTimeLabel(planned.at, now)}` };
168
+ }
169
+ return { ok: true, notBefore: start, reschedule };
170
+ }
171
+ /**
172
+ * The presets for `record` with their resolved earliest start (KTD6), for
173
+ * every surface: the API's `later_options`, the page menu, the clients and
174
+ * the Telegram buttons. `reset` is the known limit reset, or null.
175
+ */
176
+ export function postponeOptions(record, now, reset) {
177
+ return POSTPONE_PRESETS.map((preset) => {
178
+ const res = resolvePostpone(record, { preset }, now, reset);
179
+ const base = { preset, label: POSTPONE_LABELS[preset] };
180
+ return res.ok
181
+ ? { ...base, not_before: res.notBefore.toISOString(), available: true }
182
+ : { ...base, not_before: null, available: false, reason: res.reason };
183
+ });
184
+ }
185
+ //# sourceMappingURL=postpone.js.map
@@ -10,7 +10,10 @@
10
10
  * - messages.batches.create — Batch API (50% off, 24h SLA)
11
11
  */
12
12
  import { normalizeModelName } from "../energy.js";
13
- import { conversation, ProviderRefusalError } from "./base.js";
13
+ import { conversation, permanentError, ProviderRefusalError } from "./base.js";
14
+ import { budgetMaxTokens } from "./budget.js";
15
+ import { sdkFetch } from "./http.js";
16
+ import { withLlmTimeout } from "./timeout.js";
14
17
  /**
15
18
  * Output ceiling when the caller sets none. The `claude-api` skill's
16
19
  * non-streaming default: large enough not to truncate normal answers,
@@ -61,11 +64,13 @@ export class AnthropicAdapter {
61
64
  return Boolean(this.client) || Boolean(this.apiKey);
62
65
  }
63
66
  async dispatch(model, prompt, options = {}) {
67
+ const maxTokens = budgetMaxTokens(model, prompt, options, DEFAULT_MAX_TOKENS);
64
68
  const client = await this.getClient();
65
- const res = (await client.messages.create({
66
- ...requestParams(model, prompt, options),
69
+ const req = {
70
+ ...requestParams(model, prompt, { ...options, maxTokens }),
67
71
  metadata: options.metadata ? { user_id: undefined, ...options.metadata } : undefined,
68
- }));
72
+ };
73
+ const res = (await withLlmTimeout(this.provider, options.timeoutMs, (request) => (request ? client.messages.create(req, request) : client.messages.create(req)), options.signal));
69
74
  assertNotRefused(res, model);
70
75
  return {
71
76
  text: messageText(res),
@@ -168,7 +173,7 @@ export class AnthropicAdapter {
168
173
  if (this.client)
169
174
  return this.client;
170
175
  if (!this.apiKey) {
171
- throw new Error("AnthropicAdapter: no API key. Set ANTHROPIC_API_KEY or pass { apiKey } to the constructor.");
176
+ throw permanentError("AnthropicAdapter: no API key. Set ANTHROPIC_API_KEY or pass { apiKey } to the constructor.");
172
177
  }
173
178
  let Anthropic;
174
179
  try {
@@ -179,12 +184,13 @@ export class AnthropicAdapter {
179
184
  : mod.Anthropic;
180
185
  }
181
186
  catch (err) {
182
- throw new Error("AnthropicAdapter: @anthropic-ai/sdk is not installed. Run `pnpm add @anthropic-ai/sdk`.");
187
+ throw permanentError("AnthropicAdapter: @anthropic-ai/sdk is not installed. Run `pnpm add @anthropic-ai/sdk`.");
183
188
  }
184
189
  // maxRetries: 0 — Tidegap's scheduler owns the retry policy
185
190
  // (retryWithBackoff); letting the SDK retry too multiplies attempts
186
- // and can double-bill ambiguous network errors.
187
- this.client = new Anthropic({ apiKey: this.apiKey, maxRetries: 0 });
191
+ // and can double-bill ambiguous network errors. The undici fetch takes
192
+ // the dispatcher of each call's time limit (http.ts).
193
+ this.client = new Anthropic({ apiKey: this.apiKey, maxRetries: 0, fetch: sdkFetch });
188
194
  return this.client;
189
195
  }
190
196
  }
@@ -19,7 +19,16 @@
19
19
  * Adapter modules import the vendor SDK lazily so the package can be
20
20
  * installed without forcing both SDK dependencies on every consumer.
21
21
  */
22
- import type { TaskMessage } from "../types.js";
22
+ import type { RunSession } from "../run-session.js";
23
+ import type { JobCaps, ProviderCallSpec, TaskMessage } from "../types.js";
24
+ /** The agent session a task came from (KTD13). Only `claude-code` runs receive it. */
25
+ export interface DispatchOrigin {
26
+ sessionId: string;
27
+ /** The session's project directory. */
28
+ cwd: string;
29
+ agent: "claude-code" | "codex";
30
+ transcriptPath?: string;
31
+ }
23
32
  export interface DispatchOptions {
24
33
  /** Sampling temperature; vendor-specific defaults if omitted. */
25
34
  temperature?: number;
@@ -36,9 +45,98 @@ export interface DispatchOptions {
36
45
  * empty means a single-turn request, exactly as before.
37
46
  */
38
47
  messages?: TaskMessage[];
48
+ /**
49
+ * Claude Code tool names for a `claude-code` run (`[]` = none). Absent
50
+ * means the adapter's default. Other adapters ignore it.
51
+ */
52
+ tools?: string[];
53
+ /**
54
+ * The session that queued the task, for a run that resumes a copy of it.
55
+ * The scheduler passes it to `claude-code` tasks only.
56
+ */
57
+ origin?: DispatchOrigin;
58
+ /**
59
+ * The LLM time limit of this call in ms, or `"none"` for no limit (the
60
+ * scheduler resolves it when the run starts). Absent, the adapter applies
61
+ * its own default. For the `command` adapter it is the summarize step's
62
+ * limit.
63
+ */
64
+ timeoutMs?: number | "none";
65
+ /** The command time limit of the shell step in ms, or `"none"` (`command` adapter only). */
66
+ commandTimeoutMs?: number | "none";
67
+ /**
68
+ * Aborted when the task is cancelled while it runs (the scheduler checks
69
+ * the row's status while it holds the run). The `command` and
70
+ * `claude-code` adapters stop the process group as at their time limit;
71
+ * the API adapters abort the request. The dispatch then rejects.
72
+ */
73
+ signal?: AbortSignal;
74
+ /**
75
+ * Per-call budget in USD (a job's `maxBudgetUsd`). `claude-code` passes it
76
+ * as `--max-budget-usd`; API adapters cap `maxTokens` with it and refuse a
77
+ * call whose input alone costs more (KTD8).
78
+ */
79
+ maxBudgetUsd?: number;
80
+ /**
81
+ * Working directory of a job occurrence (KTD8). `claude-code` runs fresh
82
+ * there, never as a fork of a session; `~` is the home folder.
83
+ */
84
+ cwd?: string;
85
+ /** The job the occurrence belongs to; the `command` adapter refuses a call without one. */
86
+ jobId?: string;
87
+ /** The shell step of a command job occurrence (`command` adapter only). */
88
+ command?: ProviderCallSpec["command"];
89
+ /** The tool-less summarize step after the shell step (`command` adapter only). */
90
+ summarize?: ProviderCallSpec["summarize"];
91
+ /** The job's output and budget caps (`command` adapter only; other adapters get `timeoutMs` and `maxBudgetUsd`). */
92
+ caps?: Partial<JobCaps>;
93
+ /**
94
+ * A line the run printed while it runs, already scrubbed of secrets (the
95
+ * `command` adapter calls it). The scheduler records it as a `progress`
96
+ * event within the core caps; an adapter that has no output to report
97
+ * never calls it.
98
+ */
99
+ onProgress?: (line: string) => void;
100
+ /**
101
+ * The run's output ended (the `command` adapter calls it when its shell
102
+ * step ends, before a summarize step): nothing more is recorded, and a
103
+ * line still waiting for its slot is dropped.
104
+ */
105
+ onProgressEnd?: () => void;
106
+ }
107
+ /**
108
+ * Extra keys for the occurrence's `completed` or `failed` event (KTD7):
109
+ * the steps that ran, which cap stopped the run, whether output was cut.
110
+ * Never in the signed receipt.
111
+ */
112
+ export interface RunDetails {
113
+ /** Steps of the run, in order: `command`, `prompt`. */
114
+ steps?: string[];
115
+ /** The cap that stopped the run: `command_timeout`, `llm_timeout`, `budget`. */
116
+ stopped_by?: "command_timeout" | "llm_timeout" | "budget";
117
+ /** True when the command output went over `outputCapBytes` and the rest was dropped. */
118
+ truncated?: boolean;
39
119
  }
40
120
  /** Prior turns followed by the current prompt as the last user turn. */
41
121
  export declare function conversation(prompt: string, options?: Pick<DispatchOptions, "messages">): TaskMessage[];
122
+ /**
123
+ * The tokens one model used in a run (KTD9). `inputTokens` counts fresh
124
+ * input plus cache writes; cache reads are not counted. A count the model
125
+ * did not report is absent: the bill then uses the typical count, as on the
126
+ * single-model path (`billModelUsage`).
127
+ */
128
+ export interface ModelUsage {
129
+ model: string;
130
+ inputTokens?: number;
131
+ outputTokens?: number;
132
+ /**
133
+ * Set only when `inputTokens` is absent because one input part was not a
134
+ * count: the sum of the parts that were counts. The bill charges the input
135
+ * at the larger of this and the typical input count, and the receipt
136
+ * leaves the input out. Adapter-to-core input only, never on a receipt.
137
+ */
138
+ partialInputTokens?: number;
139
+ }
42
140
  export interface DispatchResult {
43
141
  /** The model's text reply, concatenated across content blocks. */
44
142
  text: string;
@@ -47,9 +145,18 @@ export interface DispatchResult {
47
145
  inputTokens?: number;
48
146
  outputTokens?: number;
49
147
  totalTokens?: number;
148
+ /** As `ModelUsage.partialInputTokens`, for the single-model path. */
149
+ partialInputTokens?: number;
50
150
  };
51
151
  /** Vendor identifier we used (e.g. "claude-sonnet-5", "gpt-6-sol"). */
52
152
  model: string;
153
+ /**
154
+ * The tokens of each model the run used (KTD9). With two or more billed
155
+ * entries the scheduler bills each model with its own coefficients and
156
+ * writes the breakdown to the receipt; otherwise it bills `usage` under
157
+ * `model`, as before.
158
+ */
159
+ modelUsage?: ModelUsage[];
53
160
  /** Vendor name: "anthropic" | "openai" | "..." */
54
161
  provider: string;
55
162
  /** Raw vendor response object. Inspect at your own risk. */
@@ -60,14 +167,50 @@ export interface DispatchResult {
60
167
  * means `text` is truncated. Absent when the provider does not report one.
61
168
  */
62
169
  stopReason?: string;
170
+ /** Tools the run could use (claude-code only). Recorded on the receipt. */
171
+ tools?: string[];
172
+ /** Where the run happened: a fork of the origin session or a fresh one (claude-code only). Recorded on the receipt. */
173
+ session?: RunSession;
174
+ /** Extra keys for the `completed` event; not on the receipt. */
175
+ details?: RunDetails;
176
+ }
177
+ /**
178
+ * An error the call must not resend at once (`retryWithBackoff`): the call
179
+ * may have done work (a shell step that ran), or resending cannot help (a
180
+ * budget the input alone exceeds). `details` go on the `failed` event.
181
+ * `permanent` is for the retry policy of the task: a retry cannot fix it (a
182
+ * refusal, missing setup, a request the provider rejects), so the task
183
+ * fails at once instead of trying again later.
184
+ */
185
+ export declare class NonRetryableError extends Error {
186
+ readonly nonRetryable = true;
187
+ readonly details?: RunDetails;
188
+ readonly permanent: boolean;
189
+ /** Set when a tick's stop ended the run (`run`) or its Batch submit (`batch_submit`); `classifyFailure` reads it. */
190
+ readonly interrupted?: "run" | "batch_submit";
191
+ constructor(message: string, details?: RunDetails, opts?: {
192
+ permanent?: boolean;
193
+ interrupted?: "run" | "batch_submit";
194
+ });
63
195
  }
196
+ /** A {@link NonRetryableError} that a retry of the task cannot fix: missing setup, a refusal, a rejected request. */
197
+ export declare function permanentError(message: string, details?: RunDetails): NonRetryableError;
198
+ /**
199
+ * The error of an HTTP answer that is not OK, for an adapter that calls
200
+ * `fetch` itself: a request the provider rejects ({@link isPermanentStatus})
201
+ * is permanent; anything else is a plain error, which the retry policy reads
202
+ * as transient. No status rides on it, so the call is not resent at once.
203
+ */
204
+ export declare function httpError(message: string, status: number): Error;
64
205
  /**
65
206
  * Thrown when the provider declined the request (Anthropic
66
207
  * `stop_reason: "refusal"`). The call returned HTTP 200, but its content
67
208
  * is not an answer, so it must not be recorded as a completed task.
68
- * Carries no HTTP status, so the scheduler does not retry it.
209
+ * Carries no HTTP status, so the scheduler does not resend it, and it is
210
+ * permanent: a later attempt would be declined too.
69
211
  */
70
212
  export declare class ProviderRefusalError extends Error {
213
+ readonly permanent = true;
71
214
  readonly provider: string;
72
215
  readonly model: string;
73
216
  /** Refusal category from `stop_details.category` ("cyber", "bio", ...), or null. */
@@ -19,17 +19,57 @@
19
19
  * Adapter modules import the vendor SDK lazily so the package can be
20
20
  * installed without forcing both SDK dependencies on every consumer.
21
21
  */
22
+ import { isPermanentStatus } from "../run-limits.js";
22
23
  /** Prior turns followed by the current prompt as the last user turn. */
23
24
  export function conversation(prompt, options = {}) {
24
25
  return [...(options.messages ?? []), { role: "user", content: prompt }];
25
26
  }
27
+ /**
28
+ * An error the call must not resend at once (`retryWithBackoff`): the call
29
+ * may have done work (a shell step that ran), or resending cannot help (a
30
+ * budget the input alone exceeds). `details` go on the `failed` event.
31
+ * `permanent` is for the retry policy of the task: a retry cannot fix it (a
32
+ * refusal, missing setup, a request the provider rejects), so the task
33
+ * fails at once instead of trying again later.
34
+ */
35
+ export class NonRetryableError extends Error {
36
+ nonRetryable = true;
37
+ details;
38
+ permanent;
39
+ /** Set when a tick's stop ended the run (`run`) or its Batch submit (`batch_submit`); `classifyFailure` reads it. */
40
+ interrupted;
41
+ constructor(message, details, opts = {}) {
42
+ super(message);
43
+ this.name = "NonRetryableError";
44
+ if (details)
45
+ this.details = details;
46
+ this.permanent = opts.permanent === true;
47
+ if (opts.interrupted)
48
+ this.interrupted = opts.interrupted;
49
+ }
50
+ }
51
+ /** A {@link NonRetryableError} that a retry of the task cannot fix: missing setup, a refusal, a rejected request. */
52
+ export function permanentError(message, details) {
53
+ return new NonRetryableError(message, details, { permanent: true });
54
+ }
55
+ /**
56
+ * The error of an HTTP answer that is not OK, for an adapter that calls
57
+ * `fetch` itself: a request the provider rejects ({@link isPermanentStatus})
58
+ * is permanent; anything else is a plain error, which the retry policy reads
59
+ * as transient. No status rides on it, so the call is not resent at once.
60
+ */
61
+ export function httpError(message, status) {
62
+ return isPermanentStatus(status) ? permanentError(message) : new Error(message);
63
+ }
26
64
  /**
27
65
  * Thrown when the provider declined the request (Anthropic
28
66
  * `stop_reason: "refusal"`). The call returned HTTP 200, but its content
29
67
  * is not an answer, so it must not be recorded as a completed task.
30
- * Carries no HTTP status, so the scheduler does not retry it.
68
+ * Carries no HTTP status, so the scheduler does not resend it, and it is
69
+ * permanent: a later attempt would be declined too.
31
70
  */
32
71
  export class ProviderRefusalError extends Error {
72
+ permanent = true;
33
73
  provider;
34
74
  model;
35
75
  /** Refusal category from `stop_details.category` ("cyber", "bio", ...), or null. */