@hivemagnus/ardent 3.1.4 → 3.2.1
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 +479 -6
- 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 +15 -8
- package/profiles/assistant/config.yaml +2 -1
package/dist/config.js
CHANGED
|
@@ -5,6 +5,7 @@ import { dirname, isAbsolute, join, resolve } from 'node:path';
|
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
6
6
|
import YAML from 'yaml';
|
|
7
7
|
import { z } from 'zod';
|
|
8
|
+
import { instanceRefProblem } from './execution.js';
|
|
8
9
|
const envName = /^[A-Z][A-Z0-9_]*$/;
|
|
9
10
|
const pathName = /^[A-Za-z0-9._-]+\.md$/;
|
|
10
11
|
function safeUrl(value) {
|
|
@@ -39,13 +40,21 @@ const ianaTimezone = z.string().min(1).max(100).refine(value => {
|
|
|
39
40
|
const NoMemory = z.object({ provider: z.literal('none') }).strict();
|
|
40
41
|
export const HiveMemConfigSchema = z.object({ provider: z.literal('hivemem'), base_url: urlReference, token_env: z.string().regex(envName), agent_id: z.string().min(1).max(100), workspace_id: z.string().min(1).max(100), default_scope: z.enum(['private', 'project']).default('private') }).strict();
|
|
41
42
|
const TelegramChannel = z.object({ enabled: z.boolean().default(false), token_env: z.string().regex(envName).default('TELEGRAM_BOT_TOKEN'), allowed_user_ids: z.array(z.number().int().positive()).default([]), allowed_chat_ids: z.array(z.number().int()).default([]), receive_mode: z.literal('polling').default('polling') }).strict();
|
|
42
|
-
|
|
43
|
+
/** Missed-post recovery. The walk reads at most `max_posts` posts back to the saved boundary; older posts are skipped, not answered. */
|
|
44
|
+
const mattermostCatchupDefault = { max_posts: 2000, max_age_hours: 24 };
|
|
45
|
+
const MattermostCatchup = z.object({ max_posts: z.number().int().min(1).max(10_000).default(2000), max_age_hours: z.number().int().min(1).max(8760).default(24) }).strict();
|
|
46
|
+
const MattermostChannel = z.object({ enabled: z.boolean().default(false), base_url: urlReference.default('${MATTERMOST_URL}'), token_env: z.string().regex(envName).default('MATTERMOST_TOKEN'), allowed_user_ids: z.array(z.string().min(1)).default([]), allowed_channel_ids: z.array(z.string().min(1)).default([]), require_mention: z.boolean().default(true), reply_mode: z.enum(['thread', 'flat']).default('thread'), catchup: MattermostCatchup.default(mattermostCatchupDefault) }).strict();
|
|
43
47
|
/** A plugin module specifier: an npm package name, or an absolute path / file URL to an ES module. */
|
|
44
48
|
const pluginSpecifier = z.string().min(1).max(500).refine(value => /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*(?:\/[A-Za-z0-9._-]+)*$/.test(value) || value.startsWith('/') || value.startsWith('file://'), 'Expected an npm package name, an absolute path, or a file:// URL');
|
|
45
49
|
const magnusControlDefault = { enabled: false, base_url: '${ARDENT_MAGNUS_API_URL}', token_env: 'ARDENT_MAGNUS_READ_TOKEN' };
|
|
46
50
|
const a2aRateLimitDefault = { enabled: true, ip_requests_per_minute: 600, ip_burst: 120, peer_requests_per_minute: 300, peer_burst: 60, max_concurrent_tasks_per_peer: 16, trusted_proxies: [] };
|
|
47
51
|
const a2aDefault = { rate_limit: a2aRateLimitDefault, enabled: false, protocol_version: '1.0', bindings: ['jsonrpc', 'http-json'], public_url: '${ARDENT_A2A_PUBLIC_URL}', listen_host: '127.0.0.1', peers_file: 'peers.yaml', hermes_compat: false };
|
|
48
52
|
const researchDefault = { enabled: false, searxng_url: '${ARDENT_SEARXNG_URL}', firecrawl_url: '${ARDENT_FIRECRAWL_URL}', firecrawl_token_env: 'FIRECRAWL_API_KEY' };
|
|
53
|
+
/** Default for `execution.max_parallel_tool_calls`. */
|
|
54
|
+
export const DEFAULT_MAX_PARALLEL_TOOL_CALLS = 4;
|
|
55
|
+
/** Task concurrency when neither `max_parallel_tasks` nor the deprecated `max_parallel_tools` is set. */
|
|
56
|
+
export const DEFAULT_MAX_PARALLEL_TASKS = 3;
|
|
57
|
+
export const MAX_PARALLEL_TOOLS_DEPRECATION = 'notice: execution.max_parallel_tools is deprecated: it limits tasks; set max_parallel_tasks';
|
|
49
58
|
export const ConfigSchema = z.object({
|
|
50
59
|
schema_version: z.literal(1),
|
|
51
60
|
profile: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/),
|
|
@@ -54,8 +63,21 @@ export const ConfigSchema = z.object({
|
|
|
54
63
|
/** IANA timezone for schedules and dates shown to the model. Defaults to the host zone. */
|
|
55
64
|
timezone: ianaTimezone.default(systemTimezone),
|
|
56
65
|
identity: z.object({ soul_file: z.string().regex(pathName).default('SOUL.md'), identity_file: z.string().regex(pathName).default('IDENTITY.md') }).strict().default({ soul_file: 'SOUL.md', identity_file: 'IDENTITY.md' }),
|
|
57
|
-
execution: z.object({ backend: z.enum(['llamacpp', 'codex']), max_model_steps: z.number().int().min(1).max(200), max_tool_calls: z.number().int().min(0).max(500),
|
|
58
|
-
|
|
66
|
+
execution: z.object({ backend: z.enum(['llamacpp', 'codex']), max_model_steps: z.number().int().min(1).max(200), max_tool_calls: z.number().int().min(0).max(500),
|
|
67
|
+
/** Tasks running at once (the runtime caps it at 4). */
|
|
68
|
+
max_parallel_tasks: z.number().int().min(1).max(16).optional(),
|
|
69
|
+
/** Parallel-eligible tool calls in flight at once within one model turn. */
|
|
70
|
+
max_parallel_tool_calls: z.number().int().min(1).max(16).default(DEFAULT_MAX_PARALLEL_TOOL_CALLS),
|
|
71
|
+
/** Deprecated: despite its name it limits tasks. Used only when `max_parallel_tasks` is absent. */
|
|
72
|
+
max_parallel_tools: z.number().int().min(1).max(16).optional(),
|
|
73
|
+
deadline_seconds: z.number().int().min(1).max(86400), max_delegation_depth: z.number().int().min(0).max(8),
|
|
74
|
+
/** Execution recovery after a crash or restart. Disabled, interrupted tasks are held as `unknown` as before. */
|
|
75
|
+
recovery: z.object({ enabled: z.boolean().default(true) }).strict().default({ enabled: true }),
|
|
76
|
+
/** Longest deadline an operator may give `retry_with_new_deadline`. Defaults to `deadline_seconds`. */
|
|
77
|
+
recovery_max_new_deadline_seconds: z.number().int().min(1).max(86400).optional() }).strict(),
|
|
78
|
+
providers: z.object({ llamacpp: provider, codex: z.object({ command: z.string().min(1).max(500), model: z.string().min(1).max(200), auth_mode: z.enum(['chatgpt', 'api_key']).default('chatgpt'), approval_policy: z.literal('never'), sandbox: z.literal('read-only'),
|
|
79
|
+
/** Keep task threads durable (not ephemeral) and record their ids, so execution recovery can verify and resume them. */
|
|
80
|
+
durable_threads: z.boolean().default(true) }).strict() }).strict(),
|
|
59
81
|
/** Long-term memory. `none` (default) disables memory tools; `hivemem` uses a HiveMem server. */
|
|
60
82
|
memory: z.discriminatedUnion('provider', [NoMemory, HiveMemConfigSchema]).default({ provider: 'none' }),
|
|
61
83
|
research: z.object({ enabled: z.boolean().default(false), searxng_url: urlReference.default('${ARDENT_SEARXNG_URL}'), firecrawl_url: urlReference.default('${ARDENT_FIRECRAWL_URL}'), firecrawl_token_env: z.string().regex(envName).default('FIRECRAWL_API_KEY') }).strict().default(researchDefault),
|
|
@@ -114,6 +136,18 @@ export function resolveReference(value, env = process.env) {
|
|
|
114
136
|
return value;
|
|
115
137
|
return env[match[1] ?? ''];
|
|
116
138
|
}
|
|
139
|
+
/** The configured task concurrency, before the runtime's cap of 4. */
|
|
140
|
+
export function maxParallelTasks(config) {
|
|
141
|
+
return config.execution.max_parallel_tasks ?? config.execution.max_parallel_tools ?? DEFAULT_MAX_PARALLEL_TASKS;
|
|
142
|
+
}
|
|
143
|
+
/** Advisory notices, prefixed `notice:`. They never make a profile unready. */
|
|
144
|
+
export function configNotices(config) {
|
|
145
|
+
return config.execution.max_parallel_tasks === undefined && config.execution.max_parallel_tools !== undefined
|
|
146
|
+
? [MAX_PARALLEL_TOOLS_DEPRECATION] : [];
|
|
147
|
+
}
|
|
148
|
+
/** Whether a `runtimeProblems` entry is an advisory notice rather than a problem. */
|
|
149
|
+
export function isConfigNotice(problem) { return problem.startsWith('notice: '); }
|
|
150
|
+
/** Unresolved runtime dependencies, followed by advisory notices (see `isConfigNotice`). */
|
|
117
151
|
export function runtimeProblems(config, env = process.env) {
|
|
118
152
|
const problems = [];
|
|
119
153
|
const need = (field, value) => {
|
|
@@ -152,7 +186,10 @@ export function runtimeProblems(config, env = process.env) {
|
|
|
152
186
|
if (!env[config.integrations.magnus_control.token_env])
|
|
153
187
|
problems.push('Magnus Control read token is missing');
|
|
154
188
|
}
|
|
155
|
-
|
|
189
|
+
const instance = instanceRefProblem(env);
|
|
190
|
+
if (instance)
|
|
191
|
+
problems.push(instance);
|
|
192
|
+
return [...problems, ...configNotices(config)];
|
|
156
193
|
}
|
|
157
194
|
export function redactedConfig(config) {
|
|
158
195
|
return structuredClone(config); // Values are references only; no resolution is performed here.
|
package/dist/development.d.ts
CHANGED
|
@@ -5,12 +5,12 @@ import type { TaskStore } from './store.js';
|
|
|
5
5
|
export declare const DevelopmentKind: z.ZodString;
|
|
6
6
|
export declare const DevelopmentSource: z.ZodObject<{
|
|
7
7
|
kind: z.ZodEnum<{
|
|
8
|
+
task: "task";
|
|
9
|
+
artifact: "artifact";
|
|
8
10
|
identity: "identity";
|
|
9
11
|
memory: "memory";
|
|
10
12
|
skill: "skill";
|
|
11
13
|
url: "url";
|
|
12
|
-
task: "task";
|
|
13
|
-
artifact: "artifact";
|
|
14
14
|
note: "note";
|
|
15
15
|
}>;
|
|
16
16
|
ref: z.ZodString;
|
|
@@ -39,12 +39,12 @@ export declare const DevelopmentRecordSchema: z.ZodObject<{
|
|
|
39
39
|
after_sha256: z.ZodNullable<z.ZodString>;
|
|
40
40
|
sources: z.ZodArray<z.ZodObject<{
|
|
41
41
|
kind: z.ZodEnum<{
|
|
42
|
+
task: "task";
|
|
43
|
+
artifact: "artifact";
|
|
42
44
|
identity: "identity";
|
|
43
45
|
memory: "memory";
|
|
44
46
|
skill: "skill";
|
|
45
47
|
url: "url";
|
|
46
|
-
task: "task";
|
|
47
|
-
artifact: "artifact";
|
|
48
48
|
note: "note";
|
|
49
49
|
}>;
|
|
50
50
|
ref: z.ZodString;
|
|
@@ -59,12 +59,12 @@ export declare const DevelopmentNoteInput: z.ZodObject<{
|
|
|
59
59
|
body: z.ZodString;
|
|
60
60
|
sources: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
61
61
|
kind: z.ZodEnum<{
|
|
62
|
+
task: "task";
|
|
63
|
+
artifact: "artifact";
|
|
62
64
|
identity: "identity";
|
|
63
65
|
memory: "memory";
|
|
64
66
|
skill: "skill";
|
|
65
67
|
url: "url";
|
|
66
|
-
task: "task";
|
|
67
|
-
artifact: "artifact";
|
|
68
68
|
note: "note";
|
|
69
69
|
}>;
|
|
70
70
|
ref: z.ZodString;
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type Database from './sqlite.js';
|
|
3
|
+
import type { ChatMessage } from './llamacpp.js';
|
|
4
|
+
import { type ToolResult } from './tools.js';
|
|
5
|
+
/**
|
|
6
|
+
* Execution checkpoints: what a running task needs to continue after a crash
|
|
7
|
+
* or restart, written at fixed boundaries in the same SQLite transaction as the
|
|
8
|
+
* journal event they belong to.
|
|
9
|
+
*
|
|
10
|
+
* - `execution_state`: the exact model transcript (llama.cpp) or thread
|
|
11
|
+
* identifiers (Codex) after the last completed boundary, with the task's
|
|
12
|
+
* evidence and tool-call count.
|
|
13
|
+
* - `tool_invocations`: one row per tool call, `dispatched` before invocation
|
|
14
|
+
* and settled with its result after. A `dispatched` row whose effect is not
|
|
15
|
+
* `read` is an unknown effect: it needs reconciliation, never a retry.
|
|
16
|
+
* - `task_recovery`: the recovery status the planner and operators set.
|
|
17
|
+
*
|
|
18
|
+
* Execution checkpoints are separate from context checkpoints
|
|
19
|
+
* (`context_checkpoints`); neither reads the other. Tools, mission scope,
|
|
20
|
+
* memory grants, caller and ownership are never taken from a checkpoint: they
|
|
21
|
+
* are re-derived from their owning stores when a task resumes.
|
|
22
|
+
*/
|
|
23
|
+
export declare const InvocationState: z.ZodEnum<{
|
|
24
|
+
dispatched: "dispatched";
|
|
25
|
+
succeeded: "succeeded";
|
|
26
|
+
failed_no_effect: "failed_no_effect";
|
|
27
|
+
failed_unknown: "failed_unknown";
|
|
28
|
+
reconciled_applied: "reconciled_applied";
|
|
29
|
+
reconciled_not_applied: "reconciled_not_applied";
|
|
30
|
+
operator_applied: "operator_applied";
|
|
31
|
+
operator_not_applied: "operator_not_applied";
|
|
32
|
+
not_dispatched: "not_dispatched";
|
|
33
|
+
}>;
|
|
34
|
+
export type InvocationState = z.infer<typeof InvocationState>;
|
|
35
|
+
export declare const RecoveryStatus: z.ZodEnum<{
|
|
36
|
+
ready: "ready";
|
|
37
|
+
reconciling: "reconciling";
|
|
38
|
+
resumed: "resumed";
|
|
39
|
+
awaiting_decision: "awaiting_decision";
|
|
40
|
+
unsupported: "unsupported";
|
|
41
|
+
resolved: "resolved";
|
|
42
|
+
}>;
|
|
43
|
+
export type RecoveryStatus = z.infer<typeof RecoveryStatus>;
|
|
44
|
+
export declare const RecoveryAction: z.ZodEnum<{
|
|
45
|
+
mark_applied: "mark_applied";
|
|
46
|
+
mark_not_applied: "mark_not_applied";
|
|
47
|
+
retry_with_new_deadline: "retry_with_new_deadline";
|
|
48
|
+
abandon: "abandon";
|
|
49
|
+
}>;
|
|
50
|
+
export type RecoveryAction = z.infer<typeof RecoveryAction>;
|
|
51
|
+
export declare const RecoveryReason: z.ZodObject<{
|
|
52
|
+
code: z.ZodString;
|
|
53
|
+
message: z.ZodString;
|
|
54
|
+
}, z.core.$strip>;
|
|
55
|
+
export type RecoveryReason = z.infer<typeof RecoveryReason>;
|
|
56
|
+
export declare const PendingCall: z.ZodObject<{
|
|
57
|
+
call_id: z.ZodString;
|
|
58
|
+
tool: z.ZodString;
|
|
59
|
+
effect: z.ZodString;
|
|
60
|
+
dispatched_at: z.ZodNullable<z.ZodString>;
|
|
61
|
+
reconcilable: z.ZodBoolean;
|
|
62
|
+
}, z.core.$strip>;
|
|
63
|
+
export type PendingCall = z.infer<typeof PendingCall>;
|
|
64
|
+
export declare const RecoveryCheckpoint: z.ZodObject<{
|
|
65
|
+
step: z.ZodNumber;
|
|
66
|
+
completed_calls: z.ZodNumber;
|
|
67
|
+
pending_calls: z.ZodArray<z.ZodObject<{
|
|
68
|
+
call_id: z.ZodString;
|
|
69
|
+
tool: z.ZodString;
|
|
70
|
+
effect: z.ZodString;
|
|
71
|
+
dispatched_at: z.ZodNullable<z.ZodString>;
|
|
72
|
+
reconcilable: z.ZodBoolean;
|
|
73
|
+
}, z.core.$strip>>;
|
|
74
|
+
}, z.core.$strip>;
|
|
75
|
+
export type RecoveryCheckpoint = z.infer<typeof RecoveryCheckpoint>;
|
|
76
|
+
export declare const RecoveryDecision: z.ZodObject<{
|
|
77
|
+
action: z.ZodEnum<{
|
|
78
|
+
mark_applied: "mark_applied";
|
|
79
|
+
mark_not_applied: "mark_not_applied";
|
|
80
|
+
retry_with_new_deadline: "retry_with_new_deadline";
|
|
81
|
+
abandon: "abandon";
|
|
82
|
+
}>;
|
|
83
|
+
by: z.ZodString;
|
|
84
|
+
at: z.ZodString;
|
|
85
|
+
note: z.ZodOptional<z.ZodString>;
|
|
86
|
+
}, z.core.$strip>;
|
|
87
|
+
export type RecoveryDecision = z.infer<typeof RecoveryDecision>;
|
|
88
|
+
/** States that settle a call: its outcome is recorded and is reused, never re-dispatched. */
|
|
89
|
+
export declare const SETTLED_STATES: ReadonlySet<InvocationState>;
|
|
90
|
+
/** Settled states that prove the call had no effect. */
|
|
91
|
+
export declare const NO_EFFECT_STATES: ReadonlySet<InvocationState>;
|
|
92
|
+
declare const SourceEvidence: z.ZodObject<{
|
|
93
|
+
url: z.ZodString;
|
|
94
|
+
extracted: z.ZodBoolean;
|
|
95
|
+
title: z.ZodString;
|
|
96
|
+
published_at: z.ZodNullable<z.ZodString>;
|
|
97
|
+
retrieved_at: z.ZodNullable<z.ZodString>;
|
|
98
|
+
content_sha256: z.ZodNullable<z.ZodString>;
|
|
99
|
+
}, z.core.$strip>;
|
|
100
|
+
export type EvidenceSnapshot = {
|
|
101
|
+
sourceIds: Set<string>;
|
|
102
|
+
sources: Map<string, z.infer<typeof SourceEvidence>>;
|
|
103
|
+
artifactIds: Set<string>;
|
|
104
|
+
researchAttempted: boolean;
|
|
105
|
+
};
|
|
106
|
+
export declare const CodexThreadState: z.ZodObject<{
|
|
107
|
+
thread_id: z.ZodString;
|
|
108
|
+
durable: z.ZodBoolean;
|
|
109
|
+
turns: z.ZodArray<z.ZodObject<{
|
|
110
|
+
id: z.ZodString;
|
|
111
|
+
started_ms: z.ZodNumber;
|
|
112
|
+
}, z.core.$strip>>;
|
|
113
|
+
}, z.core.$strip>;
|
|
114
|
+
export type CodexThreadState = z.infer<typeof CodexThreadState>;
|
|
115
|
+
export type ExecutionState = {
|
|
116
|
+
task_id: string;
|
|
117
|
+
attempt: number;
|
|
118
|
+
step: number;
|
|
119
|
+
backend: 'llamacpp' | 'codex';
|
|
120
|
+
messages: ChatMessage[];
|
|
121
|
+
evidence: EvidenceSnapshot;
|
|
122
|
+
tool_count: number;
|
|
123
|
+
codex: CodexThreadState | null;
|
|
124
|
+
updated_ms: number;
|
|
125
|
+
};
|
|
126
|
+
export type ToolInvocation = {
|
|
127
|
+
task_id: string;
|
|
128
|
+
call_id: string;
|
|
129
|
+
attempt: number;
|
|
130
|
+
step: number | null;
|
|
131
|
+
name: string;
|
|
132
|
+
effect: string;
|
|
133
|
+
args_sha256: string;
|
|
134
|
+
args: unknown;
|
|
135
|
+
idempotency_key: string;
|
|
136
|
+
state: InvocationState;
|
|
137
|
+
result: ToolResult | null;
|
|
138
|
+
dispatched_ms: number | null;
|
|
139
|
+
settled_ms: number | null;
|
|
140
|
+
};
|
|
141
|
+
export type TaskRecoveryRow = {
|
|
142
|
+
task_id: string;
|
|
143
|
+
status: RecoveryStatus;
|
|
144
|
+
reason: RecoveryReason;
|
|
145
|
+
attempt: number;
|
|
146
|
+
checkpoint: RecoveryCheckpoint | null;
|
|
147
|
+
continuation_task_id: string | null;
|
|
148
|
+
decided: RecoveryDecision | null;
|
|
149
|
+
updated_ms: number;
|
|
150
|
+
};
|
|
151
|
+
/** The digest of a call's full (uncompacted) arguments, to prove a re-dispatch sends exactly what was dispatched. */
|
|
152
|
+
export declare function argumentsDigest(args: unknown): string;
|
|
153
|
+
/** The invocation state a recorded tool result settles a call in. */
|
|
154
|
+
export declare function settledState(result: ToolResult): InvocationState;
|
|
155
|
+
/** A stored checkpoint that does not match its digest or schema. It is never used. */
|
|
156
|
+
export declare class InvalidCheckpointError extends Error {
|
|
157
|
+
}
|
|
158
|
+
export declare class ExecutionStates {
|
|
159
|
+
#private;
|
|
160
|
+
readonly db: Database;
|
|
161
|
+
constructor(db: Database);
|
|
162
|
+
/** The task's checkpoint; throws `InvalidCheckpointError` when it fails its digest or schema. */
|
|
163
|
+
get(taskId: string): ExecutionState | undefined;
|
|
164
|
+
/** Whether a task has a checkpoint row, valid or not. */
|
|
165
|
+
has(taskId: string): boolean;
|
|
166
|
+
/** Upsert the checkpoint. Call inside the boundary transaction. `codex` keeps the stored value when undefined. */
|
|
167
|
+
upsert(taskId: string, value: {
|
|
168
|
+
attempt: number;
|
|
169
|
+
step: number;
|
|
170
|
+
backend: 'llamacpp' | 'codex';
|
|
171
|
+
messages: readonly ChatMessage[];
|
|
172
|
+
evidence: EvidenceSnapshot;
|
|
173
|
+
toolCount: number;
|
|
174
|
+
codex?: CodexThreadState | null;
|
|
175
|
+
}): void;
|
|
176
|
+
invocations(taskId: string): ToolInvocation[];
|
|
177
|
+
invocation(taskId: string, callId: string): ToolInvocation | undefined;
|
|
178
|
+
/**
|
|
179
|
+
* Record a call as `dispatched` before it is invoked. A repeated call id
|
|
180
|
+
* replaces its row (a re-dispatch of an unsettled read or idempotent call
|
|
181
|
+
* keeps its idempotency key). `compactArgs` is what is stored; `fullArgs`
|
|
182
|
+
* only feeds the digest.
|
|
183
|
+
*/
|
|
184
|
+
dispatch(taskId: string, call: {
|
|
185
|
+
callId: string;
|
|
186
|
+
attempt: number;
|
|
187
|
+
step: number | null;
|
|
188
|
+
name: string;
|
|
189
|
+
effect: string;
|
|
190
|
+
fullArgs: unknown;
|
|
191
|
+
compactArgs: unknown;
|
|
192
|
+
idempotencyKey: string;
|
|
193
|
+
}): void;
|
|
194
|
+
/** Record a call that was never dispatched (cancelled or over the limit before dispatch). */
|
|
195
|
+
notDispatched(taskId: string, call: {
|
|
196
|
+
callId: string;
|
|
197
|
+
attempt: number;
|
|
198
|
+
step: number | null;
|
|
199
|
+
name: string;
|
|
200
|
+
effect: string;
|
|
201
|
+
fullArgs: unknown;
|
|
202
|
+
compactArgs: unknown;
|
|
203
|
+
idempotencyKey: string;
|
|
204
|
+
}, result: ToolResult): void;
|
|
205
|
+
/** Settle a call with its outcome. */
|
|
206
|
+
settle(taskId: string, callId: string, state: InvocationState, result: ToolResult): void;
|
|
207
|
+
/** Copy a row to another task (a continuation), optionally settled differently. Keeps the idempotency key. */
|
|
208
|
+
copy(from: ToolInvocation, toTaskId: string, override: {
|
|
209
|
+
state: InvocationState;
|
|
210
|
+
result: ToolResult | null;
|
|
211
|
+
} | undefined): void;
|
|
212
|
+
/**
|
|
213
|
+
* Whether the task has an effect that may have happened without a recorded
|
|
214
|
+
* outcome: an unsettled non-read call, a call settled with an unknown
|
|
215
|
+
* effect, or (from a database older than these tables) a non-read
|
|
216
|
+
* `tool_attempt` with no invocation row.
|
|
217
|
+
*/
|
|
218
|
+
uncertain(taskId: string): boolean;
|
|
219
|
+
/** `tool_attempt` events with no invocation row: calls journaled before execution checkpoints existed. */
|
|
220
|
+
legacyAttempts(taskId: string): Array<{
|
|
221
|
+
call_id: string | null;
|
|
222
|
+
name: string;
|
|
223
|
+
effect: string | null;
|
|
224
|
+
settled: boolean;
|
|
225
|
+
}>;
|
|
226
|
+
recovery(taskId: string): TaskRecoveryRow | undefined;
|
|
227
|
+
/** Recovery rows for several tasks (task lists). */
|
|
228
|
+
recoveries(taskIds: readonly string[]): Map<string, TaskRecoveryRow>;
|
|
229
|
+
setRecovery(taskId: string, value: {
|
|
230
|
+
status: RecoveryStatus;
|
|
231
|
+
reason: RecoveryReason;
|
|
232
|
+
attempt: number;
|
|
233
|
+
checkpoint?: RecoveryCheckpoint | null;
|
|
234
|
+
continuationTaskId?: string | null;
|
|
235
|
+
decided?: RecoveryDecision | null;
|
|
236
|
+
}): void;
|
|
237
|
+
/** Tasks currently in each open recovery status (for `GET /api/v1/status`). */
|
|
238
|
+
counts(): {
|
|
239
|
+
ready: number;
|
|
240
|
+
reconciling: number;
|
|
241
|
+
awaiting_decision: number;
|
|
242
|
+
unsupported: number;
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
export {};
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { ChatMessageSchema } from '@hivemagnus/emberfold';
|
|
4
|
+
import { ToolResultSchema } from './tools.js';
|
|
5
|
+
/**
|
|
6
|
+
* Execution checkpoints: what a running task needs to continue after a crash
|
|
7
|
+
* or restart, written at fixed boundaries in the same SQLite transaction as the
|
|
8
|
+
* journal event they belong to.
|
|
9
|
+
*
|
|
10
|
+
* - `execution_state`: the exact model transcript (llama.cpp) or thread
|
|
11
|
+
* identifiers (Codex) after the last completed boundary, with the task's
|
|
12
|
+
* evidence and tool-call count.
|
|
13
|
+
* - `tool_invocations`: one row per tool call, `dispatched` before invocation
|
|
14
|
+
* and settled with its result after. A `dispatched` row whose effect is not
|
|
15
|
+
* `read` is an unknown effect: it needs reconciliation, never a retry.
|
|
16
|
+
* - `task_recovery`: the recovery status the planner and operators set.
|
|
17
|
+
*
|
|
18
|
+
* Execution checkpoints are separate from context checkpoints
|
|
19
|
+
* (`context_checkpoints`); neither reads the other. Tools, mission scope,
|
|
20
|
+
* memory grants, caller and ownership are never taken from a checkpoint: they
|
|
21
|
+
* are re-derived from their owning stores when a task resumes.
|
|
22
|
+
*/
|
|
23
|
+
export const InvocationState = z.enum(['dispatched', 'succeeded', 'failed_no_effect', 'failed_unknown', 'reconciled_applied',
|
|
24
|
+
'reconciled_not_applied', 'operator_applied', 'operator_not_applied', 'not_dispatched']);
|
|
25
|
+
export const RecoveryStatus = z.enum(['ready', 'reconciling', 'resumed', 'awaiting_decision', 'unsupported', 'resolved']);
|
|
26
|
+
export const RecoveryAction = z.enum(['mark_applied', 'mark_not_applied', 'retry_with_new_deadline', 'abandon']);
|
|
27
|
+
export const RecoveryReason = z.object({ code: z.string().regex(/^[A-Z][A-Z0-9_]{1,63}$/), message: z.string().max(1000) });
|
|
28
|
+
export const PendingCall = z.object({ call_id: z.string(), tool: z.string(), effect: z.string(), dispatched_at: z.string().nullable(), reconcilable: z.boolean() });
|
|
29
|
+
export const RecoveryCheckpoint = z.object({ step: z.number().int(), completed_calls: z.number().int().min(0), pending_calls: z.array(PendingCall) });
|
|
30
|
+
export const RecoveryDecision = z.object({ action: RecoveryAction, by: z.string().max(128), at: z.string(), note: z.string().max(2000).optional() });
|
|
31
|
+
/** States that settle a call: its outcome is recorded and is reused, never re-dispatched. */
|
|
32
|
+
export const SETTLED_STATES = new Set(['succeeded', 'failed_no_effect', 'failed_unknown', 'reconciled_applied',
|
|
33
|
+
'reconciled_not_applied', 'operator_applied', 'operator_not_applied']);
|
|
34
|
+
/** Settled states that prove the call had no effect. */
|
|
35
|
+
export const NO_EFFECT_STATES = new Set(['failed_no_effect', 'reconciled_not_applied', 'operator_not_applied', 'not_dispatched']);
|
|
36
|
+
const SourceEvidence = z.object({ url: z.string(), extracted: z.boolean(), title: z.string(), published_at: z.string().nullable(),
|
|
37
|
+
retrieved_at: z.string().nullable(), content_sha256: z.string().nullable() });
|
|
38
|
+
const EvidenceJson = z.object({ source_ids: z.array(z.string()), sources: z.array(z.tuple([z.string(), SourceEvidence])),
|
|
39
|
+
artifact_ids: z.array(z.string()), research_attempted: z.boolean() });
|
|
40
|
+
export const CodexThreadState = z.object({ thread_id: z.string().min(1).max(256), durable: z.boolean(),
|
|
41
|
+
turns: z.array(z.object({ id: z.string().min(1).max(256), started_ms: z.number().int() })).max(256) });
|
|
42
|
+
const StateRow = z.object({ task_id: z.string(), attempt: z.number().int(), step: z.number().int(), backend: z.enum(['llamacpp', 'codex']),
|
|
43
|
+
messages_json: z.string(), evidence_json: z.string(), tool_count: z.number().int(), codex_json: z.string().nullable(), sha256: z.string(), updated_ms: z.number().int() });
|
|
44
|
+
const InvocationRow = z.object({ task_id: z.string(), call_id: z.string(), attempt: z.number().int(), step: z.number().int().nullable(), name: z.string(),
|
|
45
|
+
effect: z.string(), args_sha256: z.string(), args_json: z.string(), idempotency_key: z.string(), state: InvocationState, result_json: z.string().nullable(),
|
|
46
|
+
dispatched_ms: z.number().int().nullable(), settled_ms: z.number().int().nullable() });
|
|
47
|
+
const RecoveryRow = z.object({ task_id: z.string(), status: RecoveryStatus, reason_json: z.string(), attempt: z.number().int(), checkpoint_json: z.string().nullable(),
|
|
48
|
+
continuation_task_id: z.string().nullable(), decided_json: z.string().nullable(), updated_ms: z.number().int() });
|
|
49
|
+
/** The digest of a call's full (uncompacted) arguments, to prove a re-dispatch sends exactly what was dispatched. */
|
|
50
|
+
export function argumentsDigest(args) {
|
|
51
|
+
return createHash('sha256').update(JSON.stringify(args ?? null)).digest('hex');
|
|
52
|
+
}
|
|
53
|
+
/** The invocation state a recorded tool result settles a call in. */
|
|
54
|
+
export function settledState(result) {
|
|
55
|
+
return result.ok ? 'succeeded' : result.effect === 'none' ? 'failed_no_effect' : 'failed_unknown';
|
|
56
|
+
}
|
|
57
|
+
function evidenceJson(evidence) {
|
|
58
|
+
return JSON.stringify({ source_ids: [...evidence.sourceIds], sources: [...evidence.sources], artifact_ids: [...evidence.artifactIds], research_attempted: evidence.researchAttempted });
|
|
59
|
+
}
|
|
60
|
+
function stateDigest(messagesJson, evidence, codex, toolCount, step) {
|
|
61
|
+
return createHash('sha256').update(JSON.stringify([messagesJson, evidence, codex, toolCount, step])).digest('hex');
|
|
62
|
+
}
|
|
63
|
+
/** A stored checkpoint that does not match its digest or schema. It is never used. */
|
|
64
|
+
export class InvalidCheckpointError extends Error {
|
|
65
|
+
}
|
|
66
|
+
export class ExecutionStates {
|
|
67
|
+
db;
|
|
68
|
+
constructor(db) {
|
|
69
|
+
this.db = db;
|
|
70
|
+
db.exec(`CREATE TABLE IF NOT EXISTS execution_state (
|
|
71
|
+
task_id TEXT PRIMARY KEY REFERENCES tasks(id), attempt INTEGER NOT NULL, step INTEGER NOT NULL,
|
|
72
|
+
backend TEXT NOT NULL, messages_json TEXT NOT NULL, evidence_json TEXT NOT NULL,
|
|
73
|
+
tool_count INTEGER NOT NULL, codex_json TEXT, sha256 TEXT NOT NULL, updated_ms INTEGER NOT NULL);
|
|
74
|
+
CREATE TABLE IF NOT EXISTS tool_invocations (
|
|
75
|
+
task_id TEXT NOT NULL REFERENCES tasks(id), call_id TEXT NOT NULL, attempt INTEGER NOT NULL,
|
|
76
|
+
step INTEGER, name TEXT NOT NULL, effect TEXT NOT NULL, args_sha256 TEXT NOT NULL, args_json TEXT NOT NULL,
|
|
77
|
+
idempotency_key TEXT NOT NULL, state TEXT NOT NULL CHECK(state IN ('dispatched','succeeded','failed_no_effect',
|
|
78
|
+
'failed_unknown','reconciled_applied','reconciled_not_applied','operator_applied','operator_not_applied','not_dispatched')),
|
|
79
|
+
result_json TEXT, dispatched_ms INTEGER, settled_ms INTEGER, PRIMARY KEY(task_id, call_id));
|
|
80
|
+
CREATE TABLE IF NOT EXISTS task_recovery (
|
|
81
|
+
task_id TEXT PRIMARY KEY REFERENCES tasks(id), status TEXT NOT NULL, reason_json TEXT NOT NULL,
|
|
82
|
+
attempt INTEGER NOT NULL, checkpoint_json TEXT, continuation_task_id TEXT, decided_json TEXT, updated_ms INTEGER NOT NULL);
|
|
83
|
+
CREATE INDEX IF NOT EXISTS task_recovery_status ON task_recovery(status);`);
|
|
84
|
+
}
|
|
85
|
+
/** The task's checkpoint; throws `InvalidCheckpointError` when it fails its digest or schema. */
|
|
86
|
+
get(taskId) {
|
|
87
|
+
const raw = this.db.prepare('SELECT * FROM execution_state WHERE task_id=?').get(taskId);
|
|
88
|
+
if (!raw)
|
|
89
|
+
return undefined;
|
|
90
|
+
const row = StateRow.parse(raw);
|
|
91
|
+
if (stateDigest(row.messages_json, row.evidence_json, row.codex_json, row.tool_count, row.step) !== row.sha256)
|
|
92
|
+
throw new InvalidCheckpointError('Execution checkpoint does not match its digest');
|
|
93
|
+
try {
|
|
94
|
+
const messages = z.array(ChatMessageSchema).parse(JSON.parse(row.messages_json));
|
|
95
|
+
const evidence = EvidenceJson.parse(JSON.parse(row.evidence_json));
|
|
96
|
+
const codex = row.codex_json === null ? null : CodexThreadState.parse(JSON.parse(row.codex_json));
|
|
97
|
+
return { task_id: row.task_id, attempt: row.attempt, step: row.step, backend: row.backend, messages, tool_count: row.tool_count, codex,
|
|
98
|
+
evidence: { sourceIds: new Set(evidence.source_ids), sources: new Map(evidence.sources), artifactIds: new Set(evidence.artifact_ids), researchAttempted: evidence.research_attempted },
|
|
99
|
+
updated_ms: row.updated_ms };
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
throw new InvalidCheckpointError('Execution checkpoint is malformed');
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/** Whether a task has a checkpoint row, valid or not. */
|
|
106
|
+
has(taskId) { return this.db.prepare('SELECT 1 FROM execution_state WHERE task_id=?').get(taskId) !== undefined; }
|
|
107
|
+
/** Upsert the checkpoint. Call inside the boundary transaction. `codex` keeps the stored value when undefined. */
|
|
108
|
+
upsert(taskId, value) {
|
|
109
|
+
const messagesJson = JSON.stringify(value.messages);
|
|
110
|
+
const evidence = evidenceJson(value.evidence);
|
|
111
|
+
const codex = value.codex === undefined ? this.#codexJson(taskId) : value.codex === null ? null : JSON.stringify(CodexThreadState.parse(value.codex));
|
|
112
|
+
this.db.prepare(`INSERT INTO execution_state(task_id,attempt,step,backend,messages_json,evidence_json,tool_count,codex_json,sha256,updated_ms)
|
|
113
|
+
VALUES (?,?,?,?,?,?,?,?,?,?) ON CONFLICT(task_id) DO UPDATE SET attempt=excluded.attempt,step=excluded.step,backend=excluded.backend,
|
|
114
|
+
messages_json=excluded.messages_json,evidence_json=excluded.evidence_json,tool_count=excluded.tool_count,codex_json=excluded.codex_json,
|
|
115
|
+
sha256=excluded.sha256,updated_ms=excluded.updated_ms`)
|
|
116
|
+
.run(taskId, value.attempt, value.step, value.backend, messagesJson, evidence, value.toolCount, codex, stateDigest(messagesJson, evidence, codex, value.toolCount, value.step), Date.now());
|
|
117
|
+
}
|
|
118
|
+
#codexJson(taskId) {
|
|
119
|
+
const row = this.db.prepare('SELECT codex_json FROM execution_state WHERE task_id=?').get(taskId);
|
|
120
|
+
return row ? z.object({ codex_json: z.string().nullable() }).parse(row).codex_json : null;
|
|
121
|
+
}
|
|
122
|
+
invocations(taskId) {
|
|
123
|
+
return this.db.prepare('SELECT * FROM tool_invocations WHERE task_id=? ORDER BY COALESCE(dispatched_ms, settled_ms, 0), call_id').all(taskId).map(raw => this.#invocation(raw));
|
|
124
|
+
}
|
|
125
|
+
invocation(taskId, callId) {
|
|
126
|
+
const raw = this.db.prepare('SELECT * FROM tool_invocations WHERE task_id=? AND call_id=?').get(taskId, callId);
|
|
127
|
+
return raw ? this.#invocation(raw) : undefined;
|
|
128
|
+
}
|
|
129
|
+
#invocation(raw) {
|
|
130
|
+
const row = InvocationRow.parse(raw);
|
|
131
|
+
const result = row.result_json === null ? null : ToolResultSchema.safeParse(JSON.parse(row.result_json)).data ?? null;
|
|
132
|
+
return { task_id: row.task_id, call_id: row.call_id, attempt: row.attempt, step: row.step, name: row.name, effect: row.effect,
|
|
133
|
+
args_sha256: row.args_sha256, args: JSON.parse(row.args_json), idempotency_key: row.idempotency_key, state: row.state,
|
|
134
|
+
result, dispatched_ms: row.dispatched_ms, settled_ms: row.settled_ms };
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Record a call as `dispatched` before it is invoked. A repeated call id
|
|
138
|
+
* replaces its row (a re-dispatch of an unsettled read or idempotent call
|
|
139
|
+
* keeps its idempotency key). `compactArgs` is what is stored; `fullArgs`
|
|
140
|
+
* only feeds the digest.
|
|
141
|
+
*/
|
|
142
|
+
dispatch(taskId, call) {
|
|
143
|
+
this.#write(taskId, call, 'dispatched', null, Date.now(), null);
|
|
144
|
+
}
|
|
145
|
+
/** Record a call that was never dispatched (cancelled or over the limit before dispatch). */
|
|
146
|
+
notDispatched(taskId, call, result) {
|
|
147
|
+
const prior = this.invocation(taskId, call.callId);
|
|
148
|
+
// A later batch must not erase an earlier receipt for the same id.
|
|
149
|
+
if (prior && SETTLED_STATES.has(prior.state) && prior.step === call.step)
|
|
150
|
+
return;
|
|
151
|
+
this.#write(taskId, call, 'not_dispatched', result, null, Date.now());
|
|
152
|
+
}
|
|
153
|
+
#write(taskId, call, state, result, dispatched, settled) {
|
|
154
|
+
this.db.prepare(`INSERT INTO tool_invocations(task_id,call_id,attempt,step,name,effect,args_sha256,args_json,idempotency_key,state,result_json,dispatched_ms,settled_ms)
|
|
155
|
+
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(task_id,call_id) DO UPDATE SET attempt=excluded.attempt,step=excluded.step,name=excluded.name,
|
|
156
|
+
effect=excluded.effect,args_sha256=excluded.args_sha256,args_json=excluded.args_json,idempotency_key=excluded.idempotency_key,state=excluded.state,
|
|
157
|
+
result_json=excluded.result_json,dispatched_ms=excluded.dispatched_ms,settled_ms=excluded.settled_ms`)
|
|
158
|
+
.run(taskId, call.callId, call.attempt, call.step, call.name, call.effect, argumentsDigest(call.fullArgs), JSON.stringify(call.compactArgs ?? null), call.idempotencyKey, state, result === null ? null : JSON.stringify(result), dispatched, settled);
|
|
159
|
+
}
|
|
160
|
+
/** Settle a call with its outcome. */
|
|
161
|
+
settle(taskId, callId, state, result) {
|
|
162
|
+
this.db.prepare('UPDATE tool_invocations SET state=?,result_json=?,settled_ms=? WHERE task_id=? AND call_id=?')
|
|
163
|
+
.run(state, JSON.stringify(result), Date.now(), taskId, callId);
|
|
164
|
+
}
|
|
165
|
+
/** Copy a row to another task (a continuation), optionally settled differently. Keeps the idempotency key. */
|
|
166
|
+
copy(from, toTaskId, override) {
|
|
167
|
+
const state = override?.state ?? from.state;
|
|
168
|
+
const result = override ? override.result : from.result;
|
|
169
|
+
this.db.prepare(`INSERT INTO tool_invocations(task_id,call_id,attempt,step,name,effect,args_sha256,args_json,idempotency_key,state,result_json,dispatched_ms,settled_ms)
|
|
170
|
+
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(toTaskId, from.call_id, from.attempt, from.step, from.name, from.effect, from.args_sha256, JSON.stringify(from.args ?? null), from.idempotency_key, state, result === null ? null : JSON.stringify(result), from.dispatched_ms, override ? state === 'not_dispatched' ? null : Date.now() : from.settled_ms);
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Whether the task has an effect that may have happened without a recorded
|
|
174
|
+
* outcome: an unsettled non-read call, a call settled with an unknown
|
|
175
|
+
* effect, or (from a database older than these tables) a non-read
|
|
176
|
+
* `tool_attempt` with no invocation row.
|
|
177
|
+
*/
|
|
178
|
+
uncertain(taskId) {
|
|
179
|
+
if (this.db.prepare(`SELECT 1 FROM tool_invocations WHERE task_id=? AND ((state='dispatched' AND effect!='read') OR state='failed_unknown') LIMIT 1`).get(taskId))
|
|
180
|
+
return true;
|
|
181
|
+
return this.legacyAttempts(taskId).some(attempt => attempt.effect !== 'read');
|
|
182
|
+
}
|
|
183
|
+
/** `tool_attempt` events with no invocation row: calls journaled before execution checkpoints existed. */
|
|
184
|
+
legacyAttempts(taskId) {
|
|
185
|
+
const rows = this.db.prepare(`SELECT e.sequence, json_extract(e.detail_json,'$.id') AS call_id, json_extract(e.detail_json,'$.name') AS name,
|
|
186
|
+
json_extract(e.detail_json,'$.effect') AS effect FROM events e WHERE e.task_id=? AND e.kind='tool_attempt'
|
|
187
|
+
AND NOT EXISTS (SELECT 1 FROM tool_invocations i WHERE i.task_id=e.task_id AND i.call_id=json_extract(e.detail_json,'$.id'))`).all(taskId);
|
|
188
|
+
return rows.map(raw => {
|
|
189
|
+
const row = z.object({ sequence: z.number().int(), call_id: z.string().nullable(), name: z.string().nullable(), effect: z.string().nullable() }).parse(raw);
|
|
190
|
+
const settled = row.call_id !== null && this.db.prepare(`SELECT 1 FROM events WHERE task_id=? AND sequence>? AND kind='tool_result'
|
|
191
|
+
AND json_extract(detail_json,'$.id')=? AND json_extract(detail_json,'$.result.ok')=0 AND json_extract(detail_json,'$.result.effect')='none' LIMIT 1`)
|
|
192
|
+
.get(taskId, row.sequence, row.call_id) !== undefined;
|
|
193
|
+
return { call_id: row.call_id, name: row.name ?? 'unknown', effect: settled ? 'read' : row.effect, settled };
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
recovery(taskId) {
|
|
197
|
+
const raw = this.db.prepare('SELECT * FROM task_recovery WHERE task_id=?').get(taskId);
|
|
198
|
+
return raw ? this.#recovery(raw) : undefined;
|
|
199
|
+
}
|
|
200
|
+
/** Recovery rows for several tasks (task lists). */
|
|
201
|
+
recoveries(taskIds) {
|
|
202
|
+
const found = new Map();
|
|
203
|
+
if (!taskIds.length)
|
|
204
|
+
return found;
|
|
205
|
+
for (const raw of this.db.prepare(`SELECT * FROM task_recovery WHERE task_id IN (${taskIds.map(() => '?').join(',')})`).all(...taskIds)) {
|
|
206
|
+
const row = this.#recovery(raw);
|
|
207
|
+
found.set(row.task_id, row);
|
|
208
|
+
}
|
|
209
|
+
return found;
|
|
210
|
+
}
|
|
211
|
+
#recovery(raw) {
|
|
212
|
+
const row = RecoveryRow.parse(raw);
|
|
213
|
+
return { task_id: row.task_id, status: row.status, reason: RecoveryReason.parse(JSON.parse(row.reason_json)), attempt: row.attempt,
|
|
214
|
+
checkpoint: row.checkpoint_json === null ? null : RecoveryCheckpoint.parse(JSON.parse(row.checkpoint_json)),
|
|
215
|
+
continuation_task_id: row.continuation_task_id, decided: row.decided_json === null ? null : RecoveryDecision.parse(JSON.parse(row.decided_json)),
|
|
216
|
+
updated_ms: row.updated_ms };
|
|
217
|
+
}
|
|
218
|
+
setRecovery(taskId, value) {
|
|
219
|
+
const prior = this.recovery(taskId);
|
|
220
|
+
const checkpoint = value.checkpoint === undefined ? prior?.checkpoint ?? null : value.checkpoint;
|
|
221
|
+
const continuation = value.continuationTaskId === undefined ? prior?.continuation_task_id ?? null : value.continuationTaskId;
|
|
222
|
+
const decided = value.decided === undefined ? prior?.decided ?? null : value.decided;
|
|
223
|
+
this.db.prepare(`INSERT INTO task_recovery(task_id,status,reason_json,attempt,checkpoint_json,continuation_task_id,decided_json,updated_ms)
|
|
224
|
+
VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(task_id) DO UPDATE SET status=excluded.status,reason_json=excluded.reason_json,attempt=excluded.attempt,
|
|
225
|
+
checkpoint_json=excluded.checkpoint_json,continuation_task_id=excluded.continuation_task_id,decided_json=excluded.decided_json,updated_ms=excluded.updated_ms`)
|
|
226
|
+
.run(taskId, RecoveryStatus.parse(value.status), JSON.stringify(RecoveryReason.parse(value.reason)), value.attempt, checkpoint === null ? null : JSON.stringify(RecoveryCheckpoint.parse(checkpoint)), continuation, decided === null ? null : JSON.stringify(RecoveryDecision.parse(decided)), Date.now());
|
|
227
|
+
}
|
|
228
|
+
/** Tasks currently in each open recovery status (for `GET /api/v1/status`). */
|
|
229
|
+
counts() {
|
|
230
|
+
const rows = z.array(z.object({ status: z.string(), count: z.number().int() })).parse(this.db.prepare(`SELECT r.status, count(*) AS count FROM task_recovery r
|
|
231
|
+
JOIN tasks t ON t.id=r.task_id WHERE (r.status IN ('ready','reconciling') AND t.state='running') OR r.status IN ('awaiting_decision','unsupported')
|
|
232
|
+
GROUP BY r.status`).all());
|
|
233
|
+
const count = (status) => rows.find(row => row.status === status)?.count ?? 0;
|
|
234
|
+
return { ready: count('ready'), reconciling: count('reconciling'), awaiting_decision: count('awaiting_decision'), unsupported: count('unsupported') };
|
|
235
|
+
}
|
|
236
|
+
}
|