@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.
- package/dist/channels/digest.js +4 -4
- package/dist/channels/format.d.ts +30 -4
- package/dist/channels/format.js +125 -22
- package/dist/channels/payload.js +8 -6
- package/dist/channels/plan.js +3 -2
- package/dist/channels/types.d.ts +17 -1
- package/dist/energy.d.ts +7 -0
- package/dist/energy.js +7 -0
- package/dist/grid.d.ts +10 -2
- package/dist/grid.js +14 -5
- package/dist/handoff.d.ts +88 -6
- package/dist/handoff.js +177 -20
- package/dist/history.d.ts +19 -0
- package/dist/history.js +24 -1
- package/dist/index.d.ts +24 -18
- package/dist/index.js +16 -12
- package/dist/job-cadence.d.ts +10 -0
- package/dist/job-cadence.js +34 -0
- package/dist/job-wake.d.ts +55 -0
- package/dist/job-wake.js +91 -0
- package/dist/jobs.d.ts +74 -17
- package/dist/jobs.js +420 -75
- package/dist/notify.d.ts +9 -0
- package/dist/notify.js +17 -3
- package/dist/providers/anthropic.js +8 -6
- package/dist/providers/base.d.ts +47 -9
- package/dist/providers/base.js +29 -4
- package/dist/providers/gemini.d.ts +3 -0
- package/dist/providers/gemini.js +9 -6
- package/dist/providers/http.d.ts +40 -0
- package/dist/providers/http.js +82 -0
- package/dist/providers/index.d.ts +1 -1
- package/dist/providers/index.js +1 -1
- package/dist/providers/ollama.d.ts +3 -0
- package/dist/providers/ollama.js +8 -5
- package/dist/providers/openai.js +7 -5
- package/dist/providers/timeout.d.ts +26 -8
- package/dist/providers/timeout.js +53 -15
- package/dist/readiness.d.ts +39 -3
- package/dist/readiness.js +73 -1
- package/dist/run-limits.d.ts +268 -0
- package/dist/run-limits.js +572 -0
- package/dist/schedule-job.d.ts +41 -2
- package/dist/schedule-job.js +70 -2
- package/dist/scheduler.d.ts +161 -17
- package/dist/scheduler.js +485 -128
- package/dist/storage/sqlite.d.ts +52 -5
- package/dist/storage/sqlite.js +200 -33
- package/dist/task-events.d.ts +19 -4
- package/dist/task-events.js +51 -5
- package/dist/tool-surface.js +62 -7
- package/dist/types.d.ts +72 -11
- package/dist/types.js +1 -3
- package/package.json +5 -2
package/dist/notify.d.ts
CHANGED
|
@@ -39,8 +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;
|
|
42
44
|
/** `text` cut to `max` characters (code points) plus an ellipsis. */
|
|
43
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;
|
|
44
53
|
/**
|
|
45
54
|
* Notification title and body for a finished task: the task title (or id),
|
|
46
55
|
* a redacted one-line preview of the result (completed) or the first line
|
package/dist/notify.js
CHANGED
|
@@ -72,7 +72,8 @@ 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
|
-
|
|
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();
|
|
@@ -82,6 +83,20 @@ export function clip(text, max) {
|
|
|
82
83
|
const chars = Array.from(text);
|
|
83
84
|
return chars.length > max ? `${chars.slice(0, max).join("")}…` : text;
|
|
84
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
|
+
}
|
|
85
100
|
function grams(receipt) {
|
|
86
101
|
if (receipt && typeof receipt.actualCarbonGCo2 === "number") {
|
|
87
102
|
return `${receipt.actualCarbonGCo2} gCO2e`;
|
|
@@ -100,10 +115,9 @@ export function taskNotificationContent(record) {
|
|
|
100
115
|
const name = clip(oneLine(record.title ?? "") || record.taskId, 80);
|
|
101
116
|
const show = `tidegap queue show ${record.taskId}`;
|
|
102
117
|
if (record.status === "failed") {
|
|
103
|
-
const firstErr = (record.error ?? "").split(/\r?\n/).find((l) => l.trim()) ?? "unknown error";
|
|
104
118
|
return {
|
|
105
119
|
title: `Tidegap: failed: ${name}`,
|
|
106
|
-
body: `${
|
|
120
|
+
body: `${firstErrorLine(record.error) ?? "unknown error"}\n${show}`,
|
|
107
121
|
};
|
|
108
122
|
}
|
|
109
123
|
const r = record.result;
|
|
@@ -10,8 +10,9 @@
|
|
|
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
14
|
import { budgetMaxTokens } from "./budget.js";
|
|
15
|
+
import { sdkFetch } from "./http.js";
|
|
15
16
|
import { withLlmTimeout } from "./timeout.js";
|
|
16
17
|
/**
|
|
17
18
|
* Output ceiling when the caller sets none. The `claude-api` skill's
|
|
@@ -69,7 +70,7 @@ export class AnthropicAdapter {
|
|
|
69
70
|
...requestParams(model, prompt, { ...options, maxTokens }),
|
|
70
71
|
metadata: options.metadata ? { user_id: undefined, ...options.metadata } : undefined,
|
|
71
72
|
};
|
|
72
|
-
const res = (await withLlmTimeout(this.provider, options.timeoutMs, (request) => request ? client.messages.create(req, request) : client.messages.create(req)));
|
|
73
|
+
const res = (await withLlmTimeout(this.provider, options.timeoutMs, (request) => (request ? client.messages.create(req, request) : client.messages.create(req)), options.signal));
|
|
73
74
|
assertNotRefused(res, model);
|
|
74
75
|
return {
|
|
75
76
|
text: messageText(res),
|
|
@@ -172,7 +173,7 @@ export class AnthropicAdapter {
|
|
|
172
173
|
if (this.client)
|
|
173
174
|
return this.client;
|
|
174
175
|
if (!this.apiKey) {
|
|
175
|
-
throw
|
|
176
|
+
throw permanentError("AnthropicAdapter: no API key. Set ANTHROPIC_API_KEY or pass { apiKey } to the constructor.");
|
|
176
177
|
}
|
|
177
178
|
let Anthropic;
|
|
178
179
|
try {
|
|
@@ -183,12 +184,13 @@ export class AnthropicAdapter {
|
|
|
183
184
|
: mod.Anthropic;
|
|
184
185
|
}
|
|
185
186
|
catch (err) {
|
|
186
|
-
throw
|
|
187
|
+
throw permanentError("AnthropicAdapter: @anthropic-ai/sdk is not installed. Run `pnpm add @anthropic-ai/sdk`.");
|
|
187
188
|
}
|
|
188
189
|
// maxRetries: 0 — Tidegap's scheduler owns the retry policy
|
|
189
190
|
// (retryWithBackoff); letting the SDK retry too multiplies attempts
|
|
190
|
-
// and can double-bill ambiguous network errors.
|
|
191
|
-
|
|
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 });
|
|
192
194
|
return this.client;
|
|
193
195
|
}
|
|
194
196
|
}
|
package/dist/providers/base.d.ts
CHANGED
|
@@ -56,10 +56,21 @@ export interface DispatchOptions {
|
|
|
56
56
|
*/
|
|
57
57
|
origin?: DispatchOrigin;
|
|
58
58
|
/**
|
|
59
|
-
*
|
|
60
|
-
*
|
|
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.
|
|
61
63
|
*/
|
|
62
|
-
timeoutMs?: number;
|
|
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;
|
|
63
74
|
/**
|
|
64
75
|
* Per-call budget in USD (a job's `maxBudgetUsd`). `claude-code` passes it
|
|
65
76
|
* as `--max-budget-usd`; API adapters cap `maxTokens` with it and refuse a
|
|
@@ -77,8 +88,8 @@ export interface DispatchOptions {
|
|
|
77
88
|
command?: ProviderCallSpec["command"];
|
|
78
89
|
/** The tool-less summarize step after the shell step (`command` adapter only). */
|
|
79
90
|
summarize?: ProviderCallSpec["summarize"];
|
|
80
|
-
/** The job's caps (`command` adapter only; other adapters get `timeoutMs` and `maxBudgetUsd`). */
|
|
81
|
-
caps?: JobCaps
|
|
91
|
+
/** The job's output and budget caps (`command` adapter only; other adapters get `timeoutMs` and `maxBudgetUsd`). */
|
|
92
|
+
caps?: Partial<JobCaps>;
|
|
82
93
|
/**
|
|
83
94
|
* A line the run printed while it runs, already scrubbed of secrets (the
|
|
84
95
|
* `command` adapter calls it). The scheduler records it as a `progress`
|
|
@@ -162,24 +173,51 @@ export interface DispatchResult {
|
|
|
162
173
|
session?: RunSession;
|
|
163
174
|
/** Extra keys for the `completed` event; not on the receipt. */
|
|
164
175
|
details?: RunDetails;
|
|
176
|
+
/**
|
|
177
|
+
* A command job's summary: the trimmed reply of its summarize step, for
|
|
178
|
+
* the person who reads the notice. `text` stays the command's output.
|
|
179
|
+
*/
|
|
180
|
+
summary?: string;
|
|
181
|
+
/** Why a command job's summarize step gave no summary; the run still completed with its output. */
|
|
182
|
+
summaryError?: string;
|
|
165
183
|
}
|
|
166
184
|
/**
|
|
167
|
-
* An error the
|
|
168
|
-
*
|
|
185
|
+
* An error the call must not resend at once (`retryWithBackoff`): the call
|
|
186
|
+
* may have done work (a shell step that ran), or resending cannot help (a
|
|
169
187
|
* budget the input alone exceeds). `details` go on the `failed` event.
|
|
188
|
+
* `permanent` is for the retry policy of the task: a retry cannot fix it (a
|
|
189
|
+
* refusal, missing setup, a request the provider rejects), so the task
|
|
190
|
+
* fails at once instead of trying again later.
|
|
170
191
|
*/
|
|
171
192
|
export declare class NonRetryableError extends Error {
|
|
172
193
|
readonly nonRetryable = true;
|
|
173
194
|
readonly details?: RunDetails;
|
|
174
|
-
|
|
195
|
+
readonly permanent: boolean;
|
|
196
|
+
/** Set when a tick's stop ended the run (`run`) or its Batch submit (`batch_submit`); `classifyFailure` reads it. */
|
|
197
|
+
readonly interrupted?: "run" | "batch_submit";
|
|
198
|
+
constructor(message: string, details?: RunDetails, opts?: {
|
|
199
|
+
permanent?: boolean;
|
|
200
|
+
interrupted?: "run" | "batch_submit";
|
|
201
|
+
});
|
|
175
202
|
}
|
|
203
|
+
/** A {@link NonRetryableError} that a retry of the task cannot fix: missing setup, a refusal, a rejected request. */
|
|
204
|
+
export declare function permanentError(message: string, details?: RunDetails): NonRetryableError;
|
|
205
|
+
/**
|
|
206
|
+
* The error of an HTTP answer that is not OK, for an adapter that calls
|
|
207
|
+
* `fetch` itself: a request the provider rejects ({@link isPermanentStatus})
|
|
208
|
+
* is permanent; anything else is a plain error, which the retry policy reads
|
|
209
|
+
* as transient. No status rides on it, so the call is not resent at once.
|
|
210
|
+
*/
|
|
211
|
+
export declare function httpError(message: string, status: number): Error;
|
|
176
212
|
/**
|
|
177
213
|
* Thrown when the provider declined the request (Anthropic
|
|
178
214
|
* `stop_reason: "refusal"`). The call returned HTTP 200, but its content
|
|
179
215
|
* is not an answer, so it must not be recorded as a completed task.
|
|
180
|
-
* Carries no HTTP status, so the scheduler does not
|
|
216
|
+
* Carries no HTTP status, so the scheduler does not resend it, and it is
|
|
217
|
+
* permanent: a later attempt would be declined too.
|
|
181
218
|
*/
|
|
182
219
|
export declare class ProviderRefusalError extends Error {
|
|
220
|
+
readonly permanent = true;
|
|
183
221
|
readonly provider: string;
|
|
184
222
|
readonly model: string;
|
|
185
223
|
/** Refusal category from `stop_details.category` ("cyber", "bio", ...), or null. */
|
package/dist/providers/base.js
CHANGED
|
@@ -19,32 +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
|
}
|
|
26
27
|
/**
|
|
27
|
-
* An error the
|
|
28
|
-
*
|
|
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
|
|
29
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.
|
|
30
34
|
*/
|
|
31
35
|
export class NonRetryableError extends Error {
|
|
32
36
|
nonRetryable = true;
|
|
33
37
|
details;
|
|
34
|
-
|
|
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 = {}) {
|
|
35
42
|
super(message);
|
|
36
43
|
this.name = "NonRetryableError";
|
|
37
44
|
if (details)
|
|
38
45
|
this.details = details;
|
|
46
|
+
this.permanent = opts.permanent === true;
|
|
47
|
+
if (opts.interrupted)
|
|
48
|
+
this.interrupted = opts.interrupted;
|
|
39
49
|
}
|
|
40
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
|
+
}
|
|
41
64
|
/**
|
|
42
65
|
* Thrown when the provider declined the request (Anthropic
|
|
43
66
|
* `stop_reason: "refusal"`). The call returned HTTP 200, but its content
|
|
44
67
|
* is not an answer, so it must not be recorded as a completed task.
|
|
45
|
-
* Carries no HTTP status, so the scheduler does not
|
|
68
|
+
* Carries no HTTP status, so the scheduler does not resend it, and it is
|
|
69
|
+
* permanent: a later attempt would be declined too.
|
|
46
70
|
*/
|
|
47
71
|
export class ProviderRefusalError extends Error {
|
|
72
|
+
permanent = true;
|
|
48
73
|
provider;
|
|
49
74
|
model;
|
|
50
75
|
/** Refusal category from `stop_details.category` ("cyber", "bio", ...), or null. */
|
|
@@ -25,6 +25,7 @@
|
|
|
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: {
|
|
@@ -32,6 +33,8 @@ type FetchLike = (url: string, init: {
|
|
|
32
33
|
headers: Record<string, string>;
|
|
33
34
|
body: string;
|
|
34
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;
|
|
35
38
|
}) => Promise<{
|
|
36
39
|
ok: boolean;
|
|
37
40
|
status: number;
|
package/dist/providers/gemini.js
CHANGED
|
@@ -25,8 +25,9 @@
|
|
|
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
29
|
import { budgetMaxTokens } from "./budget.js";
|
|
30
|
+
import { httpFetch } from "./http.js";
|
|
30
31
|
import { withLlmTimeout } from "./timeout.js";
|
|
31
32
|
const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
|
|
32
33
|
export class GeminiAdapter {
|
|
@@ -44,11 +45,12 @@ export class GeminiAdapter {
|
|
|
44
45
|
}
|
|
45
46
|
async dispatch(model, prompt, options = {}) {
|
|
46
47
|
if (!this.apiKey) {
|
|
47
|
-
throw
|
|
48
|
+
throw permanentError("GeminiAdapter: no API key. Set GEMINI_API_KEY (or GOOGLE_API_KEY) or pass { apiKey } to the constructor.");
|
|
48
49
|
}
|
|
49
|
-
|
|
50
|
+
// undici's fetch: it takes the dispatcher of the call's time limit (http.ts).
|
|
51
|
+
const fetchImpl = this.fetchImpl ?? httpFetch;
|
|
50
52
|
if (typeof fetchImpl !== "function") {
|
|
51
|
-
throw
|
|
53
|
+
throw permanentError("GeminiAdapter: no fetch implementation available. Pass { fetchImpl } or run on a runtime with global fetch.");
|
|
52
54
|
}
|
|
53
55
|
const maxTokens = budgetMaxTokens(model, prompt, options);
|
|
54
56
|
const generationConfig = {};
|
|
@@ -83,6 +85,7 @@ export class GeminiAdapter {
|
|
|
83
85
|
},
|
|
84
86
|
body: JSON.stringify(body),
|
|
85
87
|
...(request ? { signal: request.signal } : {}),
|
|
88
|
+
...(request?.fetchOptions ? { dispatcher: request.fetchOptions.dispatcher } : {}),
|
|
86
89
|
});
|
|
87
90
|
if (!res.ok) {
|
|
88
91
|
let detail = "";
|
|
@@ -92,10 +95,10 @@ export class GeminiAdapter {
|
|
|
92
95
|
catch {
|
|
93
96
|
detail = "(no response body)";
|
|
94
97
|
}
|
|
95
|
-
throw
|
|
98
|
+
throw httpError(`Gemini API ${res.status}: ${detail}`, res.status);
|
|
96
99
|
}
|
|
97
100
|
return res.json();
|
|
98
|
-
}));
|
|
101
|
+
}, options.signal));
|
|
99
102
|
const text = (data.candidates?.[0]?.content?.parts ?? [])
|
|
100
103
|
.map((p) => (typeof p.text === "string" ? p.text : ""))
|
|
101
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
1
|
export type { BatchHandle, DispatchOptions, DispatchOrigin, DispatchResult, ModelUsage, ProviderAdapter, RunDetails, } from "./base.js";
|
|
2
|
-
export { NonRetryableError, ProviderRefusalError } 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";
|
package/dist/providers/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { NonRetryableError, 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,6 +18,7 @@
|
|
|
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: {
|
|
@@ -25,6 +26,8 @@ type FetchLike = (url: string, init: {
|
|
|
25
26
|
headers: Record<string, string>;
|
|
26
27
|
body: string;
|
|
27
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;
|
|
28
31
|
}) => Promise<{
|
|
29
32
|
ok: boolean;
|
|
30
33
|
status: number;
|
package/dist/providers/ollama.js
CHANGED
|
@@ -18,7 +18,8 @@
|
|
|
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";
|
|
22
23
|
import { withLlmTimeout } from "./timeout.js";
|
|
23
24
|
const DEFAULT_HOST = "http://localhost:11434";
|
|
24
25
|
/** Normalize a host string into a scheme-qualified base URL with no trailing slash. */
|
|
@@ -44,9 +45,10 @@ export class OllamaAdapter {
|
|
|
44
45
|
return true;
|
|
45
46
|
}
|
|
46
47
|
async dispatch(model, prompt, options = {}) {
|
|
47
|
-
|
|
48
|
+
// undici's fetch: it takes the dispatcher of the call's time limit (http.ts).
|
|
49
|
+
const fetchImpl = this.fetchImpl ?? httpFetch;
|
|
48
50
|
if (typeof fetchImpl !== "function") {
|
|
49
|
-
throw
|
|
51
|
+
throw permanentError("OllamaAdapter: no fetch implementation available. Pass { fetchImpl } or run on a runtime with global fetch.");
|
|
50
52
|
}
|
|
51
53
|
const ollamaOptions = {};
|
|
52
54
|
if (options.temperature !== undefined) {
|
|
@@ -76,6 +78,7 @@ export class OllamaAdapter {
|
|
|
76
78
|
headers: { "content-type": "application/json" },
|
|
77
79
|
body: JSON.stringify(body),
|
|
78
80
|
...(request ? { signal: request.signal } : {}),
|
|
81
|
+
...(request?.fetchOptions ? { dispatcher: request.fetchOptions.dispatcher } : {}),
|
|
79
82
|
});
|
|
80
83
|
}
|
|
81
84
|
catch (err) {
|
|
@@ -92,10 +95,10 @@ export class OllamaAdapter {
|
|
|
92
95
|
catch {
|
|
93
96
|
detail = "(no response body)";
|
|
94
97
|
}
|
|
95
|
-
throw
|
|
98
|
+
throw httpError(`Ollama API ${res.status}: ${detail}`, res.status);
|
|
96
99
|
}
|
|
97
100
|
return res.json();
|
|
98
|
-
}));
|
|
101
|
+
}, options.signal));
|
|
99
102
|
const inputTokens = data.prompt_eval_count;
|
|
100
103
|
const outputTokens = data.eval_count;
|
|
101
104
|
return {
|
package/dist/providers/openai.js
CHANGED
|
@@ -9,8 +9,9 @@
|
|
|
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
13
|
import { budgetMaxTokens } from "./budget.js";
|
|
14
|
+
import { sdkFetch } from "./http.js";
|
|
14
15
|
import { withLlmTimeout } from "./timeout.js";
|
|
15
16
|
/** o-series reasoning models (o1, o3, o4-mini, …). */
|
|
16
17
|
function isOSeriesModel(model) {
|
|
@@ -63,7 +64,7 @@ export class OpenAIAdapter {
|
|
|
63
64
|
const client = await this.getClient();
|
|
64
65
|
const messages = chatMessages(prompt, options);
|
|
65
66
|
const req = { model, messages, ...completionParams(model, { ...options, maxTokens }) };
|
|
66
|
-
const res = (await withLlmTimeout(this.provider, options.timeoutMs, (request) => request ? client.chat.completions.create(req, request) : client.chat.completions.create(req)));
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
}
|
|
@@ -1,18 +1,36 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The
|
|
3
|
-
* reaches the adapter as `timeoutMs`. The call gets an
|
|
4
|
-
* dispatch rejects when the limit passes, even when
|
|
5
|
-
* signal. An SDK client also gets the limit as its
|
|
6
|
-
* its default (10 minutes) cannot end a longer call
|
|
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:
|
|
7
9
|
* "llm_timeout"`), so no caller reads the message text for it, and it is
|
|
8
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.
|
|
9
19
|
*/
|
|
20
|
+
import type { Dispatcher } from "undici";
|
|
10
21
|
/** The longest delay `setTimeout` honours; a larger one fires at once. Every timer that takes a user's limit clamps to it. */
|
|
11
22
|
export declare const MAX_TIMER_MS: number;
|
|
12
|
-
/**
|
|
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
|
+
*/
|
|
13
28
|
export interface LlmRequestOptions {
|
|
14
29
|
signal: AbortSignal;
|
|
15
|
-
timeout
|
|
30
|
+
timeout?: number;
|
|
31
|
+
fetchOptions?: {
|
|
32
|
+
dispatcher: Dispatcher;
|
|
33
|
+
};
|
|
16
34
|
}
|
|
17
|
-
export declare function withLlmTimeout<T>(provider: string, timeoutMs: number | undefined, call: (request: LlmRequestOptions | undefined) => Promise<T
|
|
35
|
+
export declare function withLlmTimeout<T>(provider: string, timeoutMs: number | "none" | undefined, call: (request: LlmRequestOptions | undefined) => Promise<T>, signal?: AbortSignal): Promise<T>;
|
|
18
36
|
//# sourceMappingURL=timeout.d.ts.map
|