@hivemagnus/ardent 3.1.3 → 3.2.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/README.md +504 -16
- package/dist/a2a-client.d.ts +26 -4
- package/dist/a2a-client.js +91 -23
- package/dist/a2a-push-inbox.d.ts +2 -0
- package/dist/a2a-push-inbox.js +7 -0
- package/dist/a2a-push.d.ts +1 -1
- package/dist/a2a-push.js +26 -18
- package/dist/a2a-server.d.ts +17 -0
- package/dist/a2a-server.js +91 -14
- package/dist/a2a.d.ts +19 -1
- package/dist/a2a.js +197 -27
- package/dist/api.d.ts +2 -0
- package/dist/api.js +160 -22
- package/dist/artifact-manifests.d.ts +344 -5
- package/dist/artifact-manifests.js +413 -20
- package/dist/artifact-transfer.d.ts +113 -0
- package/dist/artifact-transfer.js +517 -0
- package/dist/artifacts.d.ts +86 -0
- package/dist/artifacts.js +249 -1
- package/dist/backend-events.d.ts +2 -1
- package/dist/backend-events.js +1 -1
- package/dist/channel-catchup.d.ts +67 -0
- package/dist/channel-catchup.js +108 -0
- package/dist/channels.d.ts +35 -0
- package/dist/channels.js +152 -4
- package/dist/cli.js +28 -3
- package/dist/codex-protocol.d.ts +22 -0
- package/dist/codex-protocol.js +19 -0
- package/dist/codex.d.ts +32 -3
- package/dist/codex.js +91 -17
- package/dist/config.d.ts +25 -2
- package/dist/config.js +41 -4
- package/dist/development.d.ts +6 -6
- package/dist/execution-state.d.ts +245 -0
- package/dist/execution-state.js +236 -0
- package/dist/execution.d.ts +135 -0
- package/dist/execution.js +178 -0
- package/dist/index.d.ts +7 -4
- package/dist/index.js +5 -3
- package/dist/job-engine.d.ts +2 -1
- package/dist/job-engine.js +33 -4
- package/dist/lineage.d.ts +106 -0
- package/dist/lineage.js +145 -0
- package/dist/llamacpp.d.ts +32 -2
- package/dist/llamacpp.js +69 -33
- package/dist/mattermost.d.ts +8 -0
- package/dist/mattermost.js +250 -36
- package/dist/mission-tools.js +41 -5
- package/dist/missions.d.ts +5 -1
- package/dist/missions.js +10 -5
- package/dist/plugin-evidence.js +2 -1
- package/dist/plugin-sdk.d.ts +3 -0
- package/dist/plugin-sdk.js +3 -0
- package/dist/plugins.d.ts +108 -2
- package/dist/plugins.js +131 -1
- package/dist/preview.d.ts +1 -0
- package/dist/preview.js +4 -1
- package/dist/recovery.d.ts +155 -0
- package/dist/recovery.js +216 -0
- package/dist/research.d.ts +1 -1
- package/dist/retry.d.ts +143 -0
- package/dist/retry.js +127 -0
- package/dist/runtime.d.ts +56 -4
- package/dist/runtime.js +727 -125
- package/dist/store.d.ts +62 -7
- package/dist/store.js +86 -15
- package/dist/team-artifacts.d.ts +130 -112
- package/dist/team-artifacts.js +123 -151
- package/dist/team-child.d.ts +4 -1
- package/dist/team-child.js +21 -2
- package/dist/team-contract.d.ts +1 -1
- package/dist/telegram.d.ts +2 -0
- package/dist/telegram.js +83 -47
- package/dist/tool-scheduler.d.ts +84 -0
- package/dist/tool-scheduler.js +226 -0
- package/dist/tools.d.ts +78 -4
- package/dist/tools.js +34 -7
- package/package.json +16 -9
- package/profiles/assistant/config.yaml +2 -1
package/dist/lineage.js
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { ExecutionContextSchema, ExecutionSource, localTaskId } from './execution.js';
|
|
3
|
+
const Related = z.object({ ref: z.string(), local_task_id: z.string(), source: ExecutionSource, created_ms: z.number().int() });
|
|
4
|
+
export const ToolLineageState = z.enum(['attempted', 'succeeded', 'failed', 'denied', 'not_dispatched']);
|
|
5
|
+
/** What Ardent knows locally about a task's place in its causal tree, rebuilt from SQLite. */
|
|
6
|
+
export const TaskLineageSchema = z.object({
|
|
7
|
+
task_id: z.string(),
|
|
8
|
+
/** Absent for a task accepted before execution ancestry was recorded. */
|
|
9
|
+
execution: ExecutionContextSchema.optional(),
|
|
10
|
+
source: ExecutionSource.optional(),
|
|
11
|
+
/** The task trace (W3C); each model call is a child span. */
|
|
12
|
+
traceparent: z.string().optional(),
|
|
13
|
+
parent: z.object({ ref: z.string(), local_task_id: z.string().optional() }).optional(),
|
|
14
|
+
/** Local tasks whose parent is this task (A2A children on this instance, team children). */
|
|
15
|
+
children: z.array(Related),
|
|
16
|
+
/** Local tasks that continue this one after an operator recovery decision. */
|
|
17
|
+
continuations: z.array(Related),
|
|
18
|
+
model_attempts: z.array(z.object({ step: z.number().int(), attempt: z.number().int(), backend: z.string().nullable(),
|
|
19
|
+
request_id: z.string().nullable(), ref: z.string().nullable(), started_ms: z.number().int(), usage: z.unknown().nullable(),
|
|
20
|
+
repair: z.boolean().optional() })),
|
|
21
|
+
tools: z.array(z.object({ call_id: z.string(), name: z.string(), effect: z.string().nullable(), state: ToolLineageState })),
|
|
22
|
+
artifacts: z.array(z.object({ sha256: z.string(), name: z.string(), mime: z.string().nullable(), size: z.number().int().nullable(),
|
|
23
|
+
artifact_id: z.string().nullable(), source: z.enum(['manifest', 'artifact_registered', 'research_artifacts']), created_ms: z.number().int(),
|
|
24
|
+
/** Manifest version and `provenance.execution` (1.1), for artifacts in the manifest table. */
|
|
25
|
+
schema_version: z.string().optional(), execution: z.object({ root: z.string(), task: z.string().optional(), step: z.string().optional() }).optional(),
|
|
26
|
+
rendition_of: z.string().optional() }))
|
|
27
|
+
});
|
|
28
|
+
const record = z.record(z.string(), z.unknown());
|
|
29
|
+
const text = (value) => typeof value === 'string' ? value : null;
|
|
30
|
+
const integer = (value) => typeof value === 'number' && Number.isSafeInteger(value) ? value : null;
|
|
31
|
+
const MAX_EVENTS = 20_000;
|
|
32
|
+
const ManifestRow = z.object({ artifact_id: z.string(), sha256: z.string(), name: z.string(), mime: z.string(), size: z.number().int(),
|
|
33
|
+
manifest_json: z.string(), created_ms: z.number().int() });
|
|
34
|
+
const ManifestView = z.object({ schema_version: z.string().optional(),
|
|
35
|
+
provenance: z.object({ execution: z.object({ root: z.string(), task: z.string().optional(), step: z.string().optional() }).optional() }).optional(),
|
|
36
|
+
rendition: z.object({ of_sha256: z.string() }).optional() });
|
|
37
|
+
function allEvents(store, taskId) {
|
|
38
|
+
const events = [];
|
|
39
|
+
for (let after = 0; events.length < MAX_EVENTS;) {
|
|
40
|
+
const page = store.events(taskId, after, 500);
|
|
41
|
+
events.push(...page);
|
|
42
|
+
if (page.length < 500)
|
|
43
|
+
break;
|
|
44
|
+
after = page[page.length - 1].sequence;
|
|
45
|
+
}
|
|
46
|
+
return events;
|
|
47
|
+
}
|
|
48
|
+
function related(value) {
|
|
49
|
+
return { ref: value.self_ref, local_task_id: value.task_id, source: value.source, created_ms: value.created_ms };
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The lineage of a local task: its execution context and parent, local children
|
|
53
|
+
* and continuations, model attempts with their request ids, tool calls and
|
|
54
|
+
* artifacts. Model attempts, tools and artifacts come from the task journal, so
|
|
55
|
+
* tasks accepted before ancestry was recorded still list them.
|
|
56
|
+
*/
|
|
57
|
+
export function taskLineage(store, instance, taskId) {
|
|
58
|
+
if (!store.get(taskId))
|
|
59
|
+
return undefined;
|
|
60
|
+
const execution = store.executions.get(taskId);
|
|
61
|
+
const linked = execution ? store.executions.children(execution.self_ref) : [];
|
|
62
|
+
const parentRef = execution?.parent_ref ?? undefined;
|
|
63
|
+
const parentLocal = parentRef ? localTaskId(instance, parentRef) : undefined;
|
|
64
|
+
const modelAttempts = [];
|
|
65
|
+
const tools = new Map();
|
|
66
|
+
const artifacts = new Map();
|
|
67
|
+
let open;
|
|
68
|
+
const ordinals = new Map();
|
|
69
|
+
for (const event of allEvents(store, taskId)) {
|
|
70
|
+
const detail = record.safeParse(event.detail).data ?? {};
|
|
71
|
+
if (event.kind === 'model_started') {
|
|
72
|
+
const step = integer(detail.step) ?? 0;
|
|
73
|
+
const ordinal = (ordinals.get(step) ?? 0) + 1;
|
|
74
|
+
ordinals.set(step, ordinal);
|
|
75
|
+
open = { step, attempt: integer(detail.attempt) ?? ordinal, backend: text(detail.backend), request_id: text(detail.request_id),
|
|
76
|
+
ref: text(detail.ref), started_ms: event.created_ms, usage: null, ...(detail.repair === true ? { repair: true } : {}) };
|
|
77
|
+
modelAttempts.push(open);
|
|
78
|
+
}
|
|
79
|
+
else if ((event.kind === 'model_result' || event.kind === 'model_repair_result') && open) {
|
|
80
|
+
open.usage = detail.usage ?? null;
|
|
81
|
+
open = undefined;
|
|
82
|
+
}
|
|
83
|
+
else if (event.kind === 'tool_attempt' || event.kind === 'tool_result' || event.kind === 'tool_not_dispatched' || event.kind === 'tool_denied_by_plugin') {
|
|
84
|
+
const callId = text(detail.id);
|
|
85
|
+
if (!callId)
|
|
86
|
+
continue;
|
|
87
|
+
const entry = tools.get(callId) ?? { call_id: callId, name: text(detail.name) ?? '', effect: null, state: 'attempted' };
|
|
88
|
+
if (event.kind === 'tool_attempt')
|
|
89
|
+
entry.effect = text(detail.effect) ?? entry.effect;
|
|
90
|
+
else if (event.kind === 'tool_denied_by_plugin')
|
|
91
|
+
entry.state = 'denied';
|
|
92
|
+
else if (event.kind === 'tool_not_dispatched')
|
|
93
|
+
entry.state = 'not_dispatched';
|
|
94
|
+
else if (entry.state !== 'denied')
|
|
95
|
+
entry.state = record.safeParse(detail.result).data?.ok === true ? 'succeeded' : 'failed';
|
|
96
|
+
tools.set(callId, entry);
|
|
97
|
+
}
|
|
98
|
+
else if (event.kind === 'artifact_registered') {
|
|
99
|
+
const sha256 = text(detail.sha256);
|
|
100
|
+
if (sha256)
|
|
101
|
+
artifacts.set(sha256, { sha256, name: text(detail.name) ?? '', mime: text(detail.mime), size: integer(detail.size),
|
|
102
|
+
artifact_id: text(detail.artifact_id), source: 'artifact_registered', created_ms: event.created_ms });
|
|
103
|
+
}
|
|
104
|
+
else if (event.kind === 'research_artifacts') {
|
|
105
|
+
for (const value of [detail.report, detail.markdown]) {
|
|
106
|
+
const item = record.safeParse(value).data;
|
|
107
|
+
const sha256 = text(item?.sha256);
|
|
108
|
+
if (!item || !sha256 || artifacts.has(sha256))
|
|
109
|
+
continue;
|
|
110
|
+
artifacts.set(sha256, { sha256, name: text(item.name) ?? '', mime: text(item.media_type), size: integer(item.bytes),
|
|
111
|
+
artifact_id: null, source: 'research_artifacts', created_ms: event.created_ms });
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
// Registered manifests (including expired and renditions) are authoritative over journal entries for the same digest.
|
|
116
|
+
if (store.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='artifact_manifests'").get()) {
|
|
117
|
+
const rows = store.db.prepare('SELECT artifact_id,sha256,name,mime,size,manifest_json,created_ms FROM artifact_manifests WHERE task_id=? ORDER BY created_ms, artifact_id LIMIT 500').all(taskId);
|
|
118
|
+
for (const raw of rows) {
|
|
119
|
+
const row = ManifestRow.safeParse(raw).data;
|
|
120
|
+
if (!row)
|
|
121
|
+
continue;
|
|
122
|
+
let manifest;
|
|
123
|
+
try {
|
|
124
|
+
manifest = ManifestView.safeParse(JSON.parse(row.manifest_json)).data;
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
manifest = undefined;
|
|
128
|
+
}
|
|
129
|
+
artifacts.set(row.sha256, { sha256: row.sha256, name: row.name, mime: row.mime, size: row.size, artifact_id: row.artifact_id, source: 'manifest',
|
|
130
|
+
created_ms: row.created_ms, ...(manifest?.schema_version ? { schema_version: manifest.schema_version } : {}),
|
|
131
|
+
...(manifest?.provenance?.execution ? { execution: manifest.provenance.execution } : {}),
|
|
132
|
+
...(manifest?.rendition?.of_sha256 ? { rendition_of: manifest.rendition.of_sha256 } : {}) });
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return {
|
|
136
|
+
task_id: taskId,
|
|
137
|
+
...(execution ? { execution: execution.context, source: execution.source, traceparent: execution.traceparent } : {}),
|
|
138
|
+
...(parentRef ? { parent: { ref: parentRef, ...(parentLocal && store.get(parentLocal) ? { local_task_id: parentLocal } : {}) } } : {}),
|
|
139
|
+
children: linked.filter(item => item.source !== 'continuation').map(related),
|
|
140
|
+
continuations: linked.filter(item => item.source === 'continuation').map(related),
|
|
141
|
+
model_attempts: modelAttempts,
|
|
142
|
+
tools: [...tools.values()],
|
|
143
|
+
artifacts: [...artifacts.values()].sort((a, b) => a.created_ms - b.created_ms)
|
|
144
|
+
};
|
|
145
|
+
}
|
package/dist/llamacpp.d.ts
CHANGED
|
@@ -30,6 +30,30 @@ export type LlamaCapabilities = {
|
|
|
30
30
|
reasoningFormat: string | null;
|
|
31
31
|
chatFormat: string | null;
|
|
32
32
|
};
|
|
33
|
+
/** One repeated model request, for the task journal (`model_retry`). */
|
|
34
|
+
export type ModelRetryEvent = {
|
|
35
|
+
operation: 'complete' | 'count_tokens';
|
|
36
|
+
attempt: number;
|
|
37
|
+
reason: string;
|
|
38
|
+
delay_ms: number;
|
|
39
|
+
};
|
|
40
|
+
/** Optional per-request settings for `complete` and `countInputTokens`. */
|
|
41
|
+
export type LlamaRequestOptions = {
|
|
42
|
+
/**
|
|
43
|
+
* Extra outbound request headers (for example execution context). They never replace
|
|
44
|
+
* `Authorization`, `Content-Type` or `Accept`, and invalid names or values are dropped.
|
|
45
|
+
*/
|
|
46
|
+
requestHeaders?: Record<string, string> | undefined;
|
|
47
|
+
/** Absolute epoch-ms deadline (the task deadline). No retry starts at or after it. */
|
|
48
|
+
deadlineMs?: number | undefined;
|
|
49
|
+
/** Called before each retry wait. */
|
|
50
|
+
onRetry?: ((event: ModelRetryEvent) => void) | undefined;
|
|
51
|
+
/** Test seams for backoff jitter and the clock. */
|
|
52
|
+
random?: (() => number) | undefined;
|
|
53
|
+
now?: (() => number) | undefined;
|
|
54
|
+
};
|
|
55
|
+
/** Caller headers first, so the backend's own `Content-Type`, `Accept` and `Authorization` win. */
|
|
56
|
+
export declare function mergeRequestHeaders(own: Record<string, string>, extra: Record<string, string> | undefined): Record<string, string>;
|
|
33
57
|
export declare function llamaEndpoint(base: string, operation: 'chat/completions' | 'chat/completions/input_tokens' | 'models'): URL;
|
|
34
58
|
export declare function sseData(stream: ReadableStream<Uint8Array>): AsyncGenerator<string>;
|
|
35
59
|
export declare class NativeLlmBackend {
|
|
@@ -38,7 +62,13 @@ export declare class NativeLlmBackend {
|
|
|
38
62
|
readonly env: NodeJS.ProcessEnv;
|
|
39
63
|
constructor(config: ArdentConfig['providers']['llamacpp'], env?: NodeJS.ProcessEnv);
|
|
40
64
|
discover(): Promise<LlamaCapabilities>;
|
|
41
|
-
countInputTokens(messages: ChatMessage[], tools: object[], signal: AbortSignal): Promise<number | null>;
|
|
42
|
-
|
|
65
|
+
countInputTokens(messages: ChatMessage[], tools: object[], signal: AbortSignal, options?: LlamaRequestOptions): Promise<number | null>;
|
|
66
|
+
/**
|
|
67
|
+
* One model call. A transport failure or a 408/425/429/5xx response is repeated under the
|
|
68
|
+
* `llamacpp` policy only before any response byte is consumed, never after the gateway says
|
|
69
|
+
* `x-hive-retry: exhausted`, and never past `options.deadlineMs` or the request timeout. A
|
|
70
|
+
* stream that fails after its first chunk is never repeated.
|
|
71
|
+
*/
|
|
72
|
+
complete(messages: ChatMessage[], tools: object[], signal: AbortSignal, stream?: boolean, onText?: (chunk: string) => void, onEvent?: BackendEventSink, options?: LlamaRequestOptions): Promise<ModelReply>;
|
|
43
73
|
}
|
|
44
74
|
export { NativeLlmBackend as LlamaCppBackend };
|
package/dist/llamacpp.js
CHANGED
|
@@ -1,6 +1,24 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
2
|
import { resolveReference } from './config.js';
|
|
3
|
+
import { AttemptError, isTransportError, responseFailure, retryWithPolicy } from './retry.js';
|
|
4
|
+
const PROTECTED_HEADERS = new Set(['authorization', 'content-type', 'accept']);
|
|
5
|
+
const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}$/;
|
|
6
|
+
/** Caller headers first, so the backend's own `Content-Type`, `Accept` and `Authorization` win. */
|
|
7
|
+
export function mergeRequestHeaders(own, extra) {
|
|
8
|
+
const merged = {};
|
|
9
|
+
for (const [name, value] of Object.entries(extra ?? {})) {
|
|
10
|
+
if (typeof value !== 'string' || !HEADER_NAME.test(name) || PROTECTED_HEADERS.has(name.toLowerCase()))
|
|
11
|
+
continue;
|
|
12
|
+
if (value.length > 8192 || /[\r\n\0]/.test(value))
|
|
13
|
+
continue;
|
|
14
|
+
merged[name] = value;
|
|
15
|
+
}
|
|
16
|
+
return { ...merged, ...own };
|
|
17
|
+
}
|
|
18
|
+
function retryObserver(operation, options) {
|
|
19
|
+
return record => { if (record.delayMs !== null)
|
|
20
|
+
options?.onRetry?.({ operation, attempt: record.attempt, reason: record.reason, delay_ms: record.delayMs }); };
|
|
21
|
+
}
|
|
4
22
|
export function llamaEndpoint(base, operation) {
|
|
5
23
|
const url = new URL(base);
|
|
6
24
|
const path = url.pathname.replace(/\/$/, '');
|
|
@@ -57,23 +75,37 @@ export class NativeLlmBackend {
|
|
|
57
75
|
this.#discovery ??= this.#discover();
|
|
58
76
|
return this.#discovery;
|
|
59
77
|
}
|
|
60
|
-
async countInputTokens(messages, tools, signal) {
|
|
78
|
+
async countInputTokens(messages, tools, signal, options) {
|
|
61
79
|
const base = resolveReference(this.config.base_url, this.env);
|
|
62
80
|
const model = resolveReference(this.config.model, this.env);
|
|
63
81
|
if (!base || !model)
|
|
64
82
|
throw new Error('llama.cpp endpoint/model is unconfigured');
|
|
65
83
|
const token = this.env[this.config.api_key_env];
|
|
84
|
+
const endpoint = llamaEndpoint(base, 'chat/completions/input_tokens');
|
|
85
|
+
const headers = mergeRequestHeaders({ 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) }, options?.requestHeaders);
|
|
86
|
+
const body = JSON.stringify({ model, messages, tools });
|
|
66
87
|
try {
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
88
|
+
// Counting has no effect, so a transient failure is repeated before the estimator takes over.
|
|
89
|
+
return await retryWithPolicy('llamacpp', async () => {
|
|
90
|
+
let response;
|
|
91
|
+
try {
|
|
92
|
+
response = await fetch(endpoint, { method: 'POST', redirect: 'manual', signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]), headers, body });
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
if (isTransportError(error))
|
|
96
|
+
throw new AttemptError('llama.cpp token count transport failed', { network: true }, { cause: error });
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
99
|
+
if (response.status === 404 || response.status === 405) {
|
|
100
|
+
await response.body?.cancel().catch(() => { });
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
if (!response.ok) {
|
|
104
|
+
await response.body?.cancel().catch(() => { });
|
|
105
|
+
throw new AttemptError(`llama.cpp token count HTTP ${response.status}`, responseFailure(response, options?.now));
|
|
106
|
+
}
|
|
107
|
+
return z.object({ input_tokens: z.number().int().nonnegative() }).parse(await response.json()).input_tokens;
|
|
108
|
+
}, { signal, deadlineMs: options?.deadlineMs, effect: 'none', onAttempt: retryObserver('count_tokens', options), random: options?.random, now: options?.now });
|
|
77
109
|
}
|
|
78
110
|
catch (error) {
|
|
79
111
|
if (signal.aborted)
|
|
@@ -111,12 +143,19 @@ export class NativeLlmBackend {
|
|
|
111
143
|
sampling: { temperature: settings?.params?.temperature ?? null, topP: settings?.params?.top_p ?? null },
|
|
112
144
|
reasoningFormat: settings?.params?.reasoning_format ?? null, chatFormat: settings?.params?.chat_format ?? null };
|
|
113
145
|
}
|
|
114
|
-
|
|
146
|
+
/**
|
|
147
|
+
* One model call. A transport failure or a 408/425/429/5xx response is repeated under the
|
|
148
|
+
* `llamacpp` policy only before any response byte is consumed, never after the gateway says
|
|
149
|
+
* `x-hive-retry: exhausted`, and never past `options.deadlineMs` or the request timeout. A
|
|
150
|
+
* stream that fails after its first chunk is never repeated.
|
|
151
|
+
*/
|
|
152
|
+
async complete(messages, tools, signal, stream = true, onText, onEvent, options) {
|
|
115
153
|
const base = resolveReference(this.config.base_url, this.env);
|
|
116
154
|
const model = resolveReference(this.config.model, this.env);
|
|
117
155
|
if (!base || !model)
|
|
118
156
|
throw new Error('llama.cpp endpoint/model is unconfigured');
|
|
119
157
|
const endpoint = llamaEndpoint(base, 'chat/completions');
|
|
158
|
+
const startedMs = (options?.now ?? Date.now)();
|
|
120
159
|
const controller = new AbortController();
|
|
121
160
|
const timer = setTimeout(() => controller.abort(), this.config.request_timeout_seconds * 1000);
|
|
122
161
|
const abort = () => controller.abort();
|
|
@@ -131,30 +170,27 @@ export class NativeLlmBackend {
|
|
|
131
170
|
if (tools.length && capabilities?.supportsTools === false)
|
|
132
171
|
throw new Error('llama.cpp chat template does not support tools');
|
|
133
172
|
onEvent?.({ kind: 'started', backend: 'llamacpp' });
|
|
134
|
-
|
|
135
|
-
|
|
173
|
+
const headers = mergeRequestHeaders({ 'Content-Type': 'application/json', Accept: stream ? 'text/event-stream' : 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) }, options?.requestHeaders);
|
|
174
|
+
const body = JSON.stringify({ model, messages, tools, stream, max_tokens: this.config.max_output_tokens ?? 4096, ...(this.config.reasoning_effort ? { reasoning_effort: this.config.reasoning_effort } : {}), ...(stream ? { stream_options: { include_usage: true } } : {}) });
|
|
175
|
+
// The request timeout bounds every attempt and wait together, so it is a deadline too.
|
|
176
|
+
const deadlineMs = Math.min(startedMs + this.config.request_timeout_seconds * 1000, options?.deadlineMs ?? Number.POSITIVE_INFINITY);
|
|
177
|
+
// A stop on a retryable failure keeps the message (`llama.cpp HTTP 429`) and adds why it stopped.
|
|
178
|
+
const response = await retryWithPolicy('llamacpp', async () => {
|
|
179
|
+
let attempt;
|
|
136
180
|
try {
|
|
137
|
-
|
|
181
|
+
attempt = await fetch(endpoint, { method: 'POST', headers, body, redirect: 'manual', signal: controller.signal });
|
|
138
182
|
}
|
|
139
183
|
catch (error) {
|
|
140
|
-
if (
|
|
141
|
-
throw error;
|
|
142
|
-
|
|
143
|
-
continue;
|
|
144
|
-
}
|
|
145
|
-
if (attempt === 0 && (response.status === 429 || response.status === 503)) {
|
|
146
|
-
await response.body?.cancel();
|
|
147
|
-
const retryAfter = Number(response.headers.get('retry-after'));
|
|
148
|
-
const waitMs = Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(2000, retryAfter * 1000) : 200;
|
|
149
|
-
await delay(waitMs, undefined, { signal: controller.signal });
|
|
150
|
-
continue;
|
|
184
|
+
if (!controller.signal.aborted && isTransportError(error))
|
|
185
|
+
throw new AttemptError('llama.cpp transport failed before response', { network: true }, { cause: error });
|
|
186
|
+
throw error;
|
|
151
187
|
}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
188
|
+
if (attempt.ok)
|
|
189
|
+
return attempt;
|
|
190
|
+
// The error body is discarded unread, so nothing of this response reaches the caller.
|
|
191
|
+
await attempt.body?.cancel().catch(() => { });
|
|
192
|
+
throw new AttemptError(`llama.cpp HTTP ${attempt.status}`, responseFailure(attempt, options?.now));
|
|
193
|
+
}, { signal: controller.signal, deadlineMs, effect: 'none', onAttempt: retryObserver('complete', options), random: options?.random, now: options?.now });
|
|
158
194
|
if (!stream) {
|
|
159
195
|
const raw = await response.json();
|
|
160
196
|
const parsed = FullResponse.parse(raw);
|
package/dist/mattermost.d.ts
CHANGED
|
@@ -16,6 +16,14 @@ export declare class MattermostAdapter {
|
|
|
16
16
|
username: string;
|
|
17
17
|
}>;
|
|
18
18
|
handlePost(raw: unknown, channelType: string, signal?: AbortSignal, freshOnly?: boolean): Promise<void>;
|
|
19
|
+
/** Answer posts whose task execution recovery resumed or continued, until `signal` aborts. Call after `initialize`. */
|
|
20
|
+
watchRecovered(signal: AbortSignal): Promise<void>;
|
|
21
|
+
/**
|
|
22
|
+
* Catch up every readable channel. Runs when a connection opens (`freshOnly`
|
|
23
|
+
* false: a claimed post without a recorded reply finishes its owner path) and
|
|
24
|
+
* on the 30 s timer (`freshOnly`: claimed posts are left alone). Returns the
|
|
25
|
+
* number of posts handed to the channel path.
|
|
26
|
+
*/
|
|
19
27
|
reconcile(freshOnly?: boolean, signal?: AbortSignal): Promise<number>;
|
|
20
28
|
connectOnce(signal: AbortSignal): Promise<void>;
|
|
21
29
|
run(signal: AbortSignal): Promise<void>;
|