@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
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Per-call budget of an API adapter (jobs KTD8): a job's `maxBudgetUsd`
3
+ * becomes a `maxTokens` ceiling through the list prices in
4
+ * `data/prices.json`. A call whose input alone costs more than the budget is
5
+ * refused before it is sent.
6
+ *
7
+ * The input is estimated at 4 characters per token; the cost uses list
8
+ * prices, not the caller's negotiated rate, so the ceiling is an estimate.
9
+ */
10
+ import { NonRetryableError, type DispatchOptions } from "./base.js";
11
+ /** The call's input alone costs more than its budget. */
12
+ export declare class BudgetExceededError extends NonRetryableError {
13
+ constructor(model: string, inputUsd: number, budgetUsd: number);
14
+ }
15
+ /**
16
+ * The `maxTokens` to send. Without `options.maxBudgetUsd`: `options.maxTokens`
17
+ * as given. With it: the smaller of `options.maxTokens` (else `adapterDefault`)
18
+ * and what the budget leaves after the input; a ceiling above
19
+ * {@link OPEN_CEILING_TOKENS} with no explicit or default value is not sent.
20
+ * A model missing from the price table keeps the adapter default and logs
21
+ * one line. Throws {@link BudgetExceededError} when the input alone costs
22
+ * more than the budget.
23
+ */
24
+ export declare function budgetMaxTokens(model: string, prompt: string, options: DispatchOptions, adapterDefault?: number): number | undefined;
25
+ //# sourceMappingURL=budget.d.ts.map
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Per-call budget of an API adapter (jobs KTD8): a job's `maxBudgetUsd`
3
+ * becomes a `maxTokens` ceiling through the list prices in
4
+ * `data/prices.json`. A call whose input alone costs more than the budget is
5
+ * refused before it is sent.
6
+ *
7
+ * The input is estimated at 4 characters per token; the cost uses list
8
+ * prices, not the caller's negotiated rate, so the ceiling is an estimate.
9
+ */
10
+ import { priceForModel } from "../routing.js";
11
+ import { conversation, NonRetryableError } from "./base.js";
12
+ /** Above this many output tokens the ceiling is not sent: the model's own limit applies. */
13
+ const OPEN_CEILING_TOKENS = 32_000;
14
+ /** The call's input alone costs more than its budget. */
15
+ export class BudgetExceededError extends NonRetryableError {
16
+ constructor(model, inputUsd, budgetUsd) {
17
+ super(`stopped: budget ${budgetUsd} USD is below the input cost of about ${inputUsd.toFixed(4)} USD for ${model}; not sent`, { stopped_by: "budget" });
18
+ this.name = "BudgetExceededError";
19
+ }
20
+ }
21
+ /** Models with no price that already logged their one line. */
22
+ const unpriced = new Set();
23
+ /**
24
+ * The `maxTokens` to send. Without `options.maxBudgetUsd`: `options.maxTokens`
25
+ * as given. With it: the smaller of `options.maxTokens` (else `adapterDefault`)
26
+ * and what the budget leaves after the input; a ceiling above
27
+ * {@link OPEN_CEILING_TOKENS} with no explicit or default value is not sent.
28
+ * A model missing from the price table keeps the adapter default and logs
29
+ * one line. Throws {@link BudgetExceededError} when the input alone costs
30
+ * more than the budget.
31
+ */
32
+ export function budgetMaxTokens(model, prompt, options, adapterDefault) {
33
+ const budget = options.maxBudgetUsd;
34
+ if (budget === undefined || !(budget > 0))
35
+ return options.maxTokens;
36
+ const price = priceForModel(model);
37
+ if (!price) {
38
+ if (!unpriced.has(model)) {
39
+ unpriced.add(model);
40
+ // eslint-disable-next-line no-console
41
+ console.warn(`[tidegap] no price for ${model} in data/prices.json; its budget cap is not applied`);
42
+ }
43
+ return options.maxTokens;
44
+ }
45
+ const chars = [options.system ?? "", ...conversation(prompt, options).map((m) => m.content)].join("").length;
46
+ const inputUsd = (Math.ceil(chars / 4) / 1_000_000) * price.inUsdPerMtok;
47
+ if (inputUsd >= budget)
48
+ throw new BudgetExceededError(model, inputUsd, budget);
49
+ if (!(price.outUsdPerMtok > 0))
50
+ return options.maxTokens;
51
+ const allowed = Math.max(1, Math.floor(((budget - inputUsd) / price.outUsdPerMtok) * 1_000_000));
52
+ const wanted = options.maxTokens ?? adapterDefault;
53
+ if (wanted !== undefined)
54
+ return Math.min(wanted, allowed);
55
+ return allowed <= OPEN_CEILING_TOKENS ? allowed : undefined;
56
+ }
57
+ //# sourceMappingURL=budget.js.map
@@ -11,5 +11,9 @@ export const DEFAULT_MODEL_BY_PROVIDER = Object.freeze({
11
11
  openai: "gpt-6-sol",
12
12
  gemini: "gemini-3.8-flash",
13
13
  ollama: "llama3.1",
14
+ // Claude Code picks its own default model; the adapter omits --model.
15
+ "claude-code": "default",
16
+ // A command job's shell step has no model.
17
+ command: "none",
14
18
  });
15
19
  //# sourceMappingURL=defaults.js.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * A provider asks the scheduler to put a running task back in the queue
3
+ * until `retryAt` instead of failing it (for example a subscription usage
4
+ * limit that resets at a known time). Not retried; the series does not roll.
5
+ */
6
+ export declare class ProviderDeferError extends Error {
7
+ readonly retryAt: Date;
8
+ name: string;
9
+ constructor(message: string, retryAt: Date);
10
+ }
11
+ /**
12
+ * The `retryAt` of a defer request, or undefined. Matches by `instanceof`
13
+ * or by name, because the CLI and core can load separate copies of the class.
14
+ */
15
+ export declare function deferRetryAt(err: unknown): Date | undefined;
16
+ //# sourceMappingURL=defer.d.ts.map
@@ -0,0 +1,31 @@
1
+ /**
2
+ * A provider asks the scheduler to put a running task back in the queue
3
+ * until `retryAt` instead of failing it (for example a subscription usage
4
+ * limit that resets at a known time). Not retried; the series does not roll.
5
+ */
6
+ export class ProviderDeferError extends Error {
7
+ retryAt;
8
+ name = "ProviderDeferError";
9
+ constructor(message, retryAt) {
10
+ super(message);
11
+ this.retryAt = retryAt;
12
+ }
13
+ }
14
+ /**
15
+ * The `retryAt` of a defer request, or undefined. Matches by `instanceof`
16
+ * or by name, because the CLI and core can load separate copies of the class.
17
+ */
18
+ export function deferRetryAt(err) {
19
+ if (!err || typeof err !== "object")
20
+ return undefined;
21
+ const e = err;
22
+ if (!(err instanceof ProviderDeferError) && e.name !== "ProviderDeferError")
23
+ return undefined;
24
+ const at = e.retryAt instanceof Date
25
+ ? e.retryAt
26
+ : typeof e.retryAt === "string" || typeof e.retryAt === "number"
27
+ ? new Date(e.retryAt)
28
+ : undefined;
29
+ return at && Number.isFinite(at.getTime()) ? at : undefined;
30
+ }
31
+ //# sourceMappingURL=defer.js.map
@@ -25,12 +25,16 @@
25
25
  * `retrieveBatch`. The scheduler feature-detects that and keeps Gemini tasks
26
26
  * on the sync path (batch-incapable adapters are a first-class case).
27
27
  */
28
+ import type { Dispatcher } from "undici";
28
29
  import type { DispatchOptions, DispatchResult, ProviderAdapter } from "./base.js";
29
30
  /** Minimal shape of the `fetch` we depend on (injectable for tests). */
30
31
  type FetchLike = (url: string, init: {
31
32
  method: string;
32
33
  headers: Record<string, string>;
33
34
  body: string;
35
+ signal?: AbortSignal;
36
+ /** The undici dispatcher of the call's time limit; a fetch that does not know it ignores it. */
37
+ dispatcher?: Dispatcher;
34
38
  }) => Promise<{
35
39
  ok: boolean;
36
40
  status: number;
@@ -25,7 +25,10 @@
25
25
  * `retrieveBatch`. The scheduler feature-detects that and keeps Gemini tasks
26
26
  * on the sync path (batch-incapable adapters are a first-class case).
27
27
  */
28
- import { conversation } from "./base.js";
28
+ import { conversation, httpError, permanentError } from "./base.js";
29
+ import { budgetMaxTokens } from "./budget.js";
30
+ import { httpFetch } from "./http.js";
31
+ import { withLlmTimeout } from "./timeout.js";
29
32
  const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
30
33
  export class GeminiAdapter {
31
34
  provider = "gemini";
@@ -42,15 +45,17 @@ export class GeminiAdapter {
42
45
  }
43
46
  async dispatch(model, prompt, options = {}) {
44
47
  if (!this.apiKey) {
45
- throw new Error("GeminiAdapter: no API key. Set GEMINI_API_KEY (or GOOGLE_API_KEY) or pass { apiKey } to the constructor.");
48
+ throw permanentError("GeminiAdapter: no API key. Set GEMINI_API_KEY (or GOOGLE_API_KEY) or pass { apiKey } to the constructor.");
46
49
  }
47
- const fetchImpl = this.fetchImpl ?? globalThis.fetch;
50
+ // undici's fetch: it takes the dispatcher of the call's time limit (http.ts).
51
+ const fetchImpl = this.fetchImpl ?? httpFetch;
48
52
  if (typeof fetchImpl !== "function") {
49
- throw new Error("GeminiAdapter: no fetch implementation available. Pass { fetchImpl } or run on a runtime with global fetch.");
53
+ throw permanentError("GeminiAdapter: no fetch implementation available. Pass { fetchImpl } or run on a runtime with global fetch.");
50
54
  }
55
+ const maxTokens = budgetMaxTokens(model, prompt, options);
51
56
  const generationConfig = {};
52
- if (options.maxTokens !== undefined) {
53
- generationConfig.maxOutputTokens = options.maxTokens;
57
+ if (maxTokens !== undefined) {
58
+ generationConfig.maxOutputTokens = maxTokens;
54
59
  }
55
60
  if (options.temperature !== undefined) {
56
61
  generationConfig.temperature = options.temperature;
@@ -70,25 +75,30 @@ export class GeminiAdapter {
70
75
  // The API key rides in the `x-goog-api-key` header (keeping it out of the
71
76
  // URL / access logs) rather than the legacy `?key=` query parameter.
72
77
  const url = `${this.baseUrl}/models/${encodeURIComponent(model)}:generateContent`;
73
- const res = await fetchImpl(url, {
74
- method: "POST",
75
- headers: {
76
- "content-type": "application/json",
77
- "x-goog-api-key": this.apiKey,
78
- },
79
- body: JSON.stringify(body),
80
- });
81
- if (!res.ok) {
82
- let detail = "";
83
- try {
84
- detail = (await res.text()).slice(0, 300);
78
+ const apiKey = this.apiKey;
79
+ const data = (await withLlmTimeout(this.provider, options.timeoutMs, async (request) => {
80
+ const res = await fetchImpl(url, {
81
+ method: "POST",
82
+ headers: {
83
+ "content-type": "application/json",
84
+ "x-goog-api-key": apiKey,
85
+ },
86
+ body: JSON.stringify(body),
87
+ ...(request ? { signal: request.signal } : {}),
88
+ ...(request?.fetchOptions ? { dispatcher: request.fetchOptions.dispatcher } : {}),
89
+ });
90
+ if (!res.ok) {
91
+ let detail = "";
92
+ try {
93
+ detail = (await res.text()).slice(0, 300);
94
+ }
95
+ catch {
96
+ detail = "(no response body)";
97
+ }
98
+ throw httpError(`Gemini API ${res.status}: ${detail}`, res.status);
85
99
  }
86
- catch {
87
- detail = "(no response body)";
88
- }
89
- throw new Error(`Gemini API ${res.status}: ${detail}`);
90
- }
91
- const data = (await res.json());
100
+ return res.json();
101
+ }, options.signal));
92
102
  const text = (data.candidates?.[0]?.content?.parts ?? [])
93
103
  .map((p) => (typeof p.text === "string" ? p.text : ""))
94
104
  .join("");
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The HTTP layer of a model call with a resolved LLM time limit. Node's
3
+ * `fetch` (undici) ends any request whose response headers, or a gap in
4
+ * its body, take longer than 300 seconds, whatever the caller's own timer
5
+ * says: a 10-minute limit, or `none`, would stop at 5 minutes. A call that
6
+ * runs under a limit therefore gets its own undici dispatcher, per call,
7
+ * whose header and body timeouts follow the limit (`0`, no timeout, for
8
+ * `none`). Library code never sets the global dispatcher.
9
+ *
10
+ * The dispatcher belongs to the `undici` package, so a call that takes it
11
+ * goes through that package's `fetch` ({@link httpFetch}), the SDK clients
12
+ * included, rather than the `fetch` bundled with the running Node.
13
+ *
14
+ * A bundle that leaves `undici` out (the OpenClaw plugin, whose bundle may
15
+ * read no environment, which undici does) aliases it to an empty module:
16
+ * then Node's own `fetch` applies, with its 300-second header wait.
17
+ */
18
+ import * as undici from "undici";
19
+ import type { Dispatcher } from "undici";
20
+ /**
21
+ * The `fetch` that takes a dispatcher of {@link limitDispatcher}: the
22
+ * `undici` package's, for a call that carries one. Every other call goes
23
+ * through the global `fetch`, so an SDK's checks of that `fetch` (the
24
+ * OpenAI SDK's `FormData` probe) and its uploads see the classes of the
25
+ * running Node. A global `fetch` the host replaced (a test double, an
26
+ * instrumentation layer) is used as is, without the dispatcher, which only
27
+ * the `undici` package's own `fetch` knows; so is Node's without `undici`,
28
+ * and so is a call with a global `FormData` body (file uploads, which run
29
+ * under no time limit).
30
+ */
31
+ export declare const httpFetch: typeof undici.fetch;
32
+ /** {@link httpFetch} as an SDK client's `fetch` option takes it. */
33
+ export declare const sdkFetch: typeof globalThis.fetch;
34
+ /**
35
+ * The dispatcher of a call under `timeoutMs`: header and body timeouts of
36
+ * the limit plus a margin, or none for `"none"`. Undefined without a limit
37
+ * (a direct library call): Node's default applies.
38
+ */
39
+ export declare function limitDispatcher(timeoutMs: number | "none" | undefined): Dispatcher | undefined;
40
+ //# sourceMappingURL=http.d.ts.map
@@ -0,0 +1,82 @@
1
+ /**
2
+ * The HTTP layer of a model call with a resolved LLM time limit. Node's
3
+ * `fetch` (undici) ends any request whose response headers, or a gap in
4
+ * its body, take longer than 300 seconds, whatever the caller's own timer
5
+ * says: a 10-minute limit, or `none`, would stop at 5 minutes. A call that
6
+ * runs under a limit therefore gets its own undici dispatcher, per call,
7
+ * whose header and body timeouts follow the limit (`0`, no timeout, for
8
+ * `none`). Library code never sets the global dispatcher.
9
+ *
10
+ * The dispatcher belongs to the `undici` package, so a call that takes it
11
+ * goes through that package's `fetch` ({@link httpFetch}), the SDK clients
12
+ * included, rather than the `fetch` bundled with the running Node.
13
+ *
14
+ * A bundle that leaves `undici` out (the OpenClaw plugin, whose bundle may
15
+ * read no environment, which undici does) aliases it to an empty module:
16
+ * then Node's own `fetch` applies, with its 300-second header wait.
17
+ */
18
+ import * as undici from "undici";
19
+ /** The `undici` package, or nothing in a bundle that leaves it out. */
20
+ const lib = undici;
21
+ /**
22
+ * Margin on top of the limit: the labelled time limit of `withLlmTimeout`
23
+ * fires first, and undici's coarse timers never end a call before it.
24
+ */
25
+ const DISPATCHER_MARGIN_MS = 30_000;
26
+ /** Node's own `fetch` as this module found it. */
27
+ const nodeFetch = globalThis.fetch;
28
+ /**
29
+ * A body the `undici` package's `fetch` cannot send: Node's global
30
+ * `FormData` is another class than the package's, which that `fetch` would
31
+ * send as the text `[object FormData]` (an SDK file upload, such as the
32
+ * OpenAI Batch input file).
33
+ */
34
+ function foreignFormData(body) {
35
+ return typeof FormData !== "undefined" && body instanceof FormData && !(lib.FormData && body instanceof lib.FormData);
36
+ }
37
+ /**
38
+ * The `fetch` that takes a dispatcher of {@link limitDispatcher}: the
39
+ * `undici` package's, for a call that carries one. Every other call goes
40
+ * through the global `fetch`, so an SDK's checks of that `fetch` (the
41
+ * OpenAI SDK's `FormData` probe) and its uploads see the classes of the
42
+ * running Node. A global `fetch` the host replaced (a test double, an
43
+ * instrumentation layer) is used as is, without the dispatcher, which only
44
+ * the `undici` package's own `fetch` knows; so is Node's without `undici`,
45
+ * and so is a call with a global `FormData` body (file uploads, which run
46
+ * under no time limit).
47
+ */
48
+ export const httpFetch = ((input, init) => {
49
+ const { dispatcher, ...rest } = init ?? {};
50
+ if (dispatcher && lib.fetch && globalThis.fetch === nodeFetch && !foreignFormData(rest.body))
51
+ return lib.fetch(input, init);
52
+ return globalThis.fetch(input, rest);
53
+ });
54
+ /** {@link httpFetch} as an SDK client's `fetch` option takes it. */
55
+ export const sdkFetch = httpFetch;
56
+ /** One dispatcher per limit, reused: each holds its own connection pool. */
57
+ const dispatchers = new Map();
58
+ const MAX_DISPATCHERS = 16;
59
+ /**
60
+ * The dispatcher of a call under `timeoutMs`: header and body timeouts of
61
+ * the limit plus a margin, or none for `"none"`. Undefined without a limit
62
+ * (a direct library call): Node's default applies.
63
+ */
64
+ export function limitDispatcher(timeoutMs) {
65
+ if (timeoutMs === undefined || !lib.Agent)
66
+ return undefined;
67
+ if (timeoutMs !== "none" && !(Number.isFinite(timeoutMs) && timeoutMs > 0))
68
+ return undefined;
69
+ const cached = dispatchers.get(timeoutMs);
70
+ if (cached)
71
+ return cached;
72
+ const timeout = timeoutMs === "none" ? 0 : timeoutMs + DISPATCHER_MARGIN_MS;
73
+ const dispatcher = new lib.Agent({ headersTimeout: timeout, bodyTimeout: timeout });
74
+ if (dispatchers.size >= MAX_DISPATCHERS) {
75
+ const [oldest, agent] = dispatchers.entries().next().value;
76
+ dispatchers.delete(oldest);
77
+ void agent.close().catch(() => undefined);
78
+ }
79
+ dispatchers.set(timeoutMs, dispatcher);
80
+ return dispatcher;
81
+ }
82
+ //# sourceMappingURL=http.js.map
@@ -1,5 +1,5 @@
1
- export type { BatchHandle, DispatchOptions, DispatchResult, ProviderAdapter, } from "./base.js";
2
- export { ProviderRefusalError } from "./base.js";
1
+ export type { BatchHandle, DispatchOptions, DispatchOrigin, DispatchResult, ModelUsage, ProviderAdapter, RunDetails, } from "./base.js";
2
+ export { NonRetryableError, permanentError, ProviderRefusalError } from "./base.js";
3
3
  export { AnthropicAdapter } from "./anthropic.js";
4
4
  export { OpenAIAdapter } from "./openai.js";
5
5
  export { GeminiAdapter } from "./gemini.js";
@@ -1,4 +1,4 @@
1
- export { ProviderRefusalError } from "./base.js";
1
+ export { NonRetryableError, permanentError, ProviderRefusalError } from "./base.js";
2
2
  export { AnthropicAdapter } from "./anthropic.js";
3
3
  export { OpenAIAdapter } from "./openai.js";
4
4
  export { GeminiAdapter } from "./gemini.js";
@@ -18,12 +18,16 @@
18
18
  * the receipt math applies the caller's grid intensity exactly as it does for
19
19
  * hosted providers. There is no special-cased "local" carbon logic here.
20
20
  */
21
+ import type { Dispatcher } from "undici";
21
22
  import type { DispatchOptions, DispatchResult, ProviderAdapter } from "./base.js";
22
23
  /** Minimal shape of the `fetch` we depend on (injectable for tests). */
23
24
  type FetchLike = (url: string, init: {
24
25
  method: string;
25
26
  headers: Record<string, string>;
26
27
  body: string;
28
+ signal?: AbortSignal;
29
+ /** The undici dispatcher of the call's time limit; a fetch that does not know it ignores it. */
30
+ dispatcher?: Dispatcher;
27
31
  }) => Promise<{
28
32
  ok: boolean;
29
33
  status: number;
@@ -18,7 +18,9 @@
18
18
  * the receipt math applies the caller's grid intensity exactly as it does for
19
19
  * hosted providers. There is no special-cased "local" carbon logic here.
20
20
  */
21
- import { conversation } from "./base.js";
21
+ import { conversation, httpError, permanentError } from "./base.js";
22
+ import { httpFetch } from "./http.js";
23
+ import { withLlmTimeout } from "./timeout.js";
22
24
  const DEFAULT_HOST = "http://localhost:11434";
23
25
  /** Normalize a host string into a scheme-qualified base URL with no trailing slash. */
24
26
  function normalizeHost(raw) {
@@ -43,9 +45,10 @@ export class OllamaAdapter {
43
45
  return true;
44
46
  }
45
47
  async dispatch(model, prompt, options = {}) {
46
- const fetchImpl = this.fetchImpl ?? globalThis.fetch;
48
+ // undici's fetch: it takes the dispatcher of the call's time limit (http.ts).
49
+ const fetchImpl = this.fetchImpl ?? httpFetch;
47
50
  if (typeof fetchImpl !== "function") {
48
- throw new Error("OllamaAdapter: no fetch implementation available. Pass { fetchImpl } or run on a runtime with global fetch.");
51
+ throw permanentError("OllamaAdapter: no fetch implementation available. Pass { fetchImpl } or run on a runtime with global fetch.");
49
52
  }
50
53
  const ollamaOptions = {};
51
54
  if (options.temperature !== undefined) {
@@ -67,31 +70,35 @@ export class OllamaAdapter {
67
70
  body.options = ollamaOptions;
68
71
  }
69
72
  const url = `${this.host}/api/chat`;
70
- let res;
71
- try {
72
- res = await fetchImpl(url, {
73
- method: "POST",
74
- headers: { "content-type": "application/json" },
75
- body: JSON.stringify(body),
76
- });
77
- }
78
- catch (err) {
79
- // Connection refused / DNS / TLS — the local server is not reachable.
80
- const detail = err instanceof Error ? err.message : String(err);
81
- throw new Error(`OllamaAdapter: could not reach Ollama at ${this.host} (${detail}). ` +
82
- `Is \`ollama serve\` running? Set OLLAMA_HOST to override the address.`);
83
- }
84
- if (!res.ok) {
85
- let detail = "";
73
+ const data = (await withLlmTimeout(this.provider, options.timeoutMs, async (request) => {
74
+ let res;
86
75
  try {
87
- detail = (await res.text()).slice(0, 300);
76
+ res = await fetchImpl(url, {
77
+ method: "POST",
78
+ headers: { "content-type": "application/json" },
79
+ body: JSON.stringify(body),
80
+ ...(request ? { signal: request.signal } : {}),
81
+ ...(request?.fetchOptions ? { dispatcher: request.fetchOptions.dispatcher } : {}),
82
+ });
88
83
  }
89
- catch {
90
- detail = "(no response body)";
84
+ catch (err) {
85
+ // Connection refused / DNS / TLS — the local server is not reachable.
86
+ const detail = err instanceof Error ? err.message : String(err);
87
+ throw new Error(`OllamaAdapter: could not reach Ollama at ${this.host} (${detail}). ` +
88
+ `Is \`ollama serve\` running? Set OLLAMA_HOST to override the address.`);
91
89
  }
92
- throw new Error(`Ollama API ${res.status}: ${detail}`);
93
- }
94
- const data = (await res.json());
90
+ if (!res.ok) {
91
+ let detail = "";
92
+ try {
93
+ detail = (await res.text()).slice(0, 300);
94
+ }
95
+ catch {
96
+ detail = "(no response body)";
97
+ }
98
+ throw httpError(`Ollama API ${res.status}: ${detail}`, res.status);
99
+ }
100
+ return res.json();
101
+ }, options.signal));
95
102
  const inputTokens = data.prompt_eval_count;
96
103
  const outputTokens = data.eval_count;
97
104
  return {
@@ -9,7 +9,10 @@
9
9
  * (50% off, 24h SLA). OpenAI's batch input is a JSONL file uploaded
10
10
  * to /v1/files, then referenced by id from POST /v1/batches.
11
11
  */
12
- import { conversation } from "./base.js";
12
+ import { conversation, permanentError } from "./base.js";
13
+ import { budgetMaxTokens } from "./budget.js";
14
+ import { sdkFetch } from "./http.js";
15
+ import { withLlmTimeout } from "./timeout.js";
13
16
  /** o-series reasoning models (o1, o3, o4-mini, …). */
14
17
  function isOSeriesModel(model) {
15
18
  return /^o\d/.test(model.trim().toLowerCase());
@@ -57,13 +60,11 @@ export class OpenAIAdapter {
57
60
  return Boolean(this.client) || Boolean(this.apiKey);
58
61
  }
59
62
  async dispatch(model, prompt, options = {}) {
63
+ const maxTokens = budgetMaxTokens(model, prompt, options);
60
64
  const client = await this.getClient();
61
65
  const messages = chatMessages(prompt, options);
62
- const res = (await client.chat.completions.create({
63
- model,
64
- messages,
65
- ...completionParams(model, options),
66
- }));
66
+ const req = { model, messages, ...completionParams(model, { ...options, maxTokens }) };
67
+ const res = (await withLlmTimeout(this.provider, options.timeoutMs, (request) => (request ? client.chat.completions.create(req, request) : client.chat.completions.create(req)), options.signal));
67
68
  const text = res.choices?.[0]?.message?.content ?? "";
68
69
  return {
69
70
  text,
@@ -181,7 +182,7 @@ export class OpenAIAdapter {
181
182
  if (this.client)
182
183
  return this.client;
183
184
  if (!this.apiKey) {
184
- throw new Error("OpenAIAdapter: no API key. Set OPENAI_API_KEY or pass { apiKey } to the constructor.");
185
+ throw permanentError("OpenAIAdapter: no API key. Set OPENAI_API_KEY or pass { apiKey } to the constructor.");
185
186
  }
186
187
  let OpenAI;
187
188
  try {
@@ -190,12 +191,13 @@ export class OpenAIAdapter {
190
191
  "default" in mod ? mod.default : mod.OpenAI;
191
192
  }
192
193
  catch (err) {
193
- throw new Error("OpenAIAdapter: `openai` SDK is not installed. Run `pnpm add openai`.");
194
+ throw permanentError("OpenAIAdapter: `openai` SDK is not installed. Run `pnpm add openai`.");
194
195
  }
195
196
  // maxRetries: 0 — Tidegap's scheduler owns the retry policy
196
197
  // (retryWithBackoff); letting the SDK retry too multiplies attempts
197
198
  // and can double-bill ambiguous network errors.
198
- this.client = new OpenAI({ apiKey: this.apiKey, maxRetries: 0 });
199
+ // The undici fetch takes the dispatcher of each call's time limit (http.ts).
200
+ this.client = new OpenAI({ apiKey: this.apiKey, maxRetries: 0, fetch: sdkFetch });
199
201
  return this.client;
200
202
  }
201
203
  }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The LLM time limit of an API adapter: the limit the scheduler resolved
3
+ * when the run started reaches the adapter as `timeoutMs`. The call gets an
4
+ * abort signal, and the dispatch rejects when the limit passes, even when
5
+ * the client ignores the signal. An SDK client also gets the limit as its
6
+ * own request timeout, so its default (10 minutes) cannot end a longer call
7
+ * first, unlabelled; with `"none"` it gets the longest timer it takes and
8
+ * Tidegap sets none. The error names the cap in its details (`stopped_by:
9
+ * "llm_timeout"`), so no caller reads the message text for it, and it is
10
+ * not retried: the limit is spent.
11
+ *
12
+ * The caller's `signal` (a cancel of the task while it runs) aborts the call
13
+ * the same way, at once, with a `stopped: the task was cancelled` error.
14
+ *
15
+ * Under a limit, `none` included, the request also carries an undici
16
+ * dispatcher whose header and body timeouts follow the limit
17
+ * (`fetchOptions.dispatcher`, see `http.ts`), so Node's 300-second header
18
+ * timeout cannot end the call first: no hidden ceiling remains.
19
+ */
20
+ import type { Dispatcher } from "undici";
21
+ /** The longest delay `setTimeout` honours; a larger one fires at once. Every timer that takes a user's limit clamps to it. */
22
+ export declare const MAX_TIMER_MS: number;
23
+ /**
24
+ * What an SDK request takes: the abort signal; with a time limit, its own
25
+ * timeout (the same limit, clamped) and the dispatcher of that limit, which
26
+ * a `fetch` call passes as `dispatcher` (through `httpFetch`).
27
+ */
28
+ export interface LlmRequestOptions {
29
+ signal: AbortSignal;
30
+ timeout?: number;
31
+ fetchOptions?: {
32
+ dispatcher: Dispatcher;
33
+ };
34
+ }
35
+ export declare function withLlmTimeout<T>(provider: string, timeoutMs: number | "none" | undefined, call: (request: LlmRequestOptions | undefined) => Promise<T>, signal?: AbortSignal): Promise<T>;
36
+ //# sourceMappingURL=timeout.d.ts.map
@@ -0,0 +1,71 @@
1
+ /**
2
+ * The LLM time limit of an API adapter: the limit the scheduler resolved
3
+ * when the run started reaches the adapter as `timeoutMs`. The call gets an
4
+ * abort signal, and the dispatch rejects when the limit passes, even when
5
+ * the client ignores the signal. An SDK client also gets the limit as its
6
+ * own request timeout, so its default (10 minutes) cannot end a longer call
7
+ * first, unlabelled; with `"none"` it gets the longest timer it takes and
8
+ * Tidegap sets none. The error names the cap in its details (`stopped_by:
9
+ * "llm_timeout"`), so no caller reads the message text for it, and it is
10
+ * not retried: the limit is spent.
11
+ *
12
+ * The caller's `signal` (a cancel of the task while it runs) aborts the call
13
+ * the same way, at once, with a `stopped: the task was cancelled` error.
14
+ *
15
+ * Under a limit, `none` included, the request also carries an undici
16
+ * dispatcher whose header and body timeouts follow the limit
17
+ * (`fetchOptions.dispatcher`, see `http.ts`), so Node's 300-second header
18
+ * timeout cannot end the call first: no hidden ceiling remains.
19
+ */
20
+ import { NonRetryableError } from "./base.js";
21
+ import { limitDispatcher } from "./http.js";
22
+ /** The longest delay `setTimeout` honours; a larger one fires at once. Every timer that takes a user's limit clamps to it. */
23
+ export const MAX_TIMER_MS = 2 ** 31 - 1;
24
+ /** The error of a call stopped because its task was cancelled. */
25
+ function cancelledError(provider) {
26
+ return new NonRetryableError(`${provider}: stopped: the task was cancelled`);
27
+ }
28
+ export async function withLlmTimeout(provider, timeoutMs, call, signal) {
29
+ const unlimited = timeoutMs === "none";
30
+ const limited = typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0;
31
+ if (!limited && !unlimited && !signal)
32
+ return call(undefined);
33
+ if (signal?.aborted)
34
+ throw cancelledError(provider);
35
+ const controller = new AbortController();
36
+ const limit = limited ? Math.min(timeoutMs, MAX_TIMER_MS) : undefined;
37
+ const sdkTimeout = unlimited ? MAX_TIMER_MS : limit;
38
+ let timer;
39
+ let onAbort;
40
+ const stopped = new Promise((_, reject) => {
41
+ // Each rejects before the abort, so a client that rejects on abort at once cannot win the race.
42
+ if (limit !== undefined) {
43
+ timer = setTimeout(() => {
44
+ reject(new NonRetryableError(`${provider}: timed out after ${timeoutMs / 1000}s`, { stopped_by: "llm_timeout" }));
45
+ controller.abort();
46
+ }, limit);
47
+ }
48
+ if (signal) {
49
+ onAbort = () => {
50
+ reject(cancelledError(provider));
51
+ controller.abort();
52
+ };
53
+ signal.addEventListener("abort", onAbort, { once: true });
54
+ }
55
+ });
56
+ try {
57
+ const dispatcher = limitDispatcher(timeoutMs);
58
+ const request = {
59
+ signal: controller.signal,
60
+ ...(sdkTimeout !== undefined ? { timeout: sdkTimeout } : {}),
61
+ ...(dispatcher ? { fetchOptions: { dispatcher } } : {}),
62
+ };
63
+ return await Promise.race([call(request), stopped]);
64
+ }
65
+ finally {
66
+ clearTimeout(timer);
67
+ if (onAbort)
68
+ signal.removeEventListener("abort", onAbort);
69
+ }
70
+ }
71
+ //# sourceMappingURL=timeout.js.map