@tidegap/core 0.20.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.
- package/dist/channels/digest.js +3 -3
- package/dist/channels/format.d.ts +11 -0
- package/dist/channels/format.js +26 -8
- package/dist/energy.d.ts +7 -0
- package/dist/energy.js +7 -0
- package/dist/handoff.d.ts +22 -3
- package/dist/handoff.js +69 -17
- package/dist/history.d.ts +15 -0
- package/dist/history.js +11 -0
- package/dist/index.d.ts +17 -13
- package/dist/index.js +12 -10
- package/dist/jobs.d.ts +25 -15
- package/dist/jobs.js +186 -63
- 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 +40 -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 +23 -0
- package/dist/schedule-job.js +48 -0
- package/dist/scheduler.d.ts +159 -17
- package/dist/scheduler.js +482 -128
- package/dist/storage/sqlite.d.ts +28 -2
- package/dist/storage/sqlite.js +65 -5
- package/dist/task-events.d.ts +19 -4
- package/dist/task-events.js +42 -5
- package/dist/tool-surface.js +38 -7
- package/dist/types.d.ts +31 -10
- package/dist/types.js +1 -3
- package/package.json +5 -2
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
|
|
@@ -1,33 +1,71 @@
|
|
|
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
|
*/
|
|
10
20
|
import { NonRetryableError } from "./base.js";
|
|
21
|
+
import { limitDispatcher } from "./http.js";
|
|
11
22
|
/** The longest delay `setTimeout` honours; a larger one fires at once. Every timer that takes a user's limit clamps to it. */
|
|
12
23
|
export const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
13
|
-
|
|
14
|
-
|
|
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)
|
|
15
32
|
return call(undefined);
|
|
33
|
+
if (signal?.aborted)
|
|
34
|
+
throw cancelledError(provider);
|
|
16
35
|
const controller = new AbortController();
|
|
17
|
-
const limit = Math.min(timeoutMs, MAX_TIMER_MS);
|
|
36
|
+
const limit = limited ? Math.min(timeoutMs, MAX_TIMER_MS) : undefined;
|
|
37
|
+
const sdkTimeout = unlimited ? MAX_TIMER_MS : limit;
|
|
18
38
|
let timer;
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
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
|
+
}
|
|
25
55
|
});
|
|
26
56
|
try {
|
|
27
|
-
|
|
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]);
|
|
28
64
|
}
|
|
29
65
|
finally {
|
|
30
66
|
clearTimeout(timer);
|
|
67
|
+
if (onAbort)
|
|
68
|
+
signal.removeEventListener("abort", onAbort);
|
|
31
69
|
}
|
|
32
70
|
}
|
|
33
71
|
//# sourceMappingURL=timeout.js.map
|
package/dist/readiness.d.ts
CHANGED
|
@@ -5,7 +5,10 @@
|
|
|
5
5
|
* A fact nobody can observe is "unknown" and raises no problem (R2).
|
|
6
6
|
*/
|
|
7
7
|
import type { MetaStore } from "./postpone.js";
|
|
8
|
-
import type
|
|
8
|
+
import { type DurationValue } from "./run-limits.js";
|
|
9
|
+
import type { TickDetails } from "./scheduler.js";
|
|
10
|
+
import type { TaskEvent } from "./task-events.js";
|
|
11
|
+
import type { TaskRecord, TaskStatus } from "./types.js";
|
|
9
12
|
/**
|
|
10
13
|
* The tick daemon as the host sees it. `installed` = the unit file exists
|
|
11
14
|
* and whether it is loaded was not probed; `unknown` = nothing on this
|
|
@@ -95,9 +98,22 @@ export interface ReadinessFacts {
|
|
|
95
98
|
runners: RunnerFact | null;
|
|
96
99
|
/** Pending provider-call tasks by provider. */
|
|
97
100
|
pendingByProvider: Record<string, number>;
|
|
101
|
+
/**
|
|
102
|
+
* The oldest `running` row a locked Node tick dispatched ({@link oldestTickRun}).
|
|
103
|
+
* The tick runs due rows one at a time, so this run holds every other due
|
|
104
|
+
* task while it lasts.
|
|
105
|
+
*/
|
|
106
|
+
oldestRun?: OldestRun | null;
|
|
98
107
|
now?: Date;
|
|
99
108
|
}
|
|
100
|
-
|
|
109
|
+
/** A run that holds the tick: its task, when its dispatch began, and its time limit when known. */
|
|
110
|
+
export interface OldestRun {
|
|
111
|
+
taskId: string;
|
|
112
|
+
/** ISO-8601 time of its `dispatched` event. */
|
|
113
|
+
startedAt: string;
|
|
114
|
+
timeLimit?: DurationValue;
|
|
115
|
+
}
|
|
116
|
+
export type ReadinessCode = "no_daemon" | "daemon_not_loaded" | "daemon_stale" | "long_run" | "no_runner";
|
|
101
117
|
/** Problems of the ticker, not of the runners: only a process outside the tick can see them (KTD11). */
|
|
102
118
|
export declare const TICKER_CODES: readonly ReadinessCode[];
|
|
103
119
|
export interface ReadinessProblem {
|
|
@@ -110,11 +126,13 @@ export interface ReadinessProblem {
|
|
|
110
126
|
provider?: string;
|
|
111
127
|
/** `no_runner` only: pending tasks of that provider. */
|
|
112
128
|
tasks?: number;
|
|
129
|
+
/** `long_run` only: the task that holds the tick. */
|
|
130
|
+
task_id?: string;
|
|
113
131
|
}
|
|
114
132
|
/** The readiness result every surface shows; JSON as-is in the API and MCP. */
|
|
115
133
|
export interface Readiness {
|
|
116
134
|
ready: boolean;
|
|
117
|
-
/** Ordered `no_daemon`, `daemon_not_loaded`, `daemon_stale`, `no_runner`. */
|
|
135
|
+
/** Ordered `no_daemon`, `daemon_not_loaded`, `daemon_stale`, `long_run`, `no_runner`. */
|
|
118
136
|
problems: ReadinessProblem[];
|
|
119
137
|
/** The first problem's sentence plus its fix; null when ready. */
|
|
120
138
|
line: string | null;
|
|
@@ -166,4 +184,22 @@ export declare function pendingProvidersFromStore(store: {
|
|
|
166
184
|
bodyJson?: string;
|
|
167
185
|
}>;
|
|
168
186
|
}): Record<string, number>;
|
|
187
|
+
/** A row's newest event, progress lines aside, when it is a dispatch by a locked tick: its tick and time. */
|
|
188
|
+
export declare function tickDispatch(events: readonly TaskEvent[]): {
|
|
189
|
+
tick: TickDetails;
|
|
190
|
+
at: string;
|
|
191
|
+
} | undefined;
|
|
192
|
+
/**
|
|
193
|
+
* The oldest `running` row a locked Node tick dispatched (the readiness
|
|
194
|
+
* `long_run` fact), or null. A row another writer runs (the Python tick, the
|
|
195
|
+
* MCP server) holds no Node tick and is left out. So is a Batch row: it is
|
|
196
|
+
* `running` only while a poll checks its batch, and its dispatch is the
|
|
197
|
+
* submit, hours before.
|
|
198
|
+
*/
|
|
199
|
+
export declare function oldestTickRun(store: {
|
|
200
|
+
list(filter: {
|
|
201
|
+
status: TaskStatus;
|
|
202
|
+
}): Array<Pick<TaskRecord<unknown>, "taskId" | "bodyJson" | "batchId">>;
|
|
203
|
+
listTaskEvents(taskId: string): TaskEvent[];
|
|
204
|
+
}): OldestRun | null;
|
|
169
205
|
//# sourceMappingURL=readiness.d.ts.map
|