@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.
Files changed (79) hide show
  1. package/README.md +479 -6
  2. package/dist/a2a-client.d.ts +26 -4
  3. package/dist/a2a-client.js +91 -23
  4. package/dist/a2a-push-inbox.d.ts +2 -0
  5. package/dist/a2a-push-inbox.js +7 -0
  6. package/dist/a2a-push.d.ts +1 -1
  7. package/dist/a2a-push.js +26 -18
  8. package/dist/a2a-server.d.ts +17 -0
  9. package/dist/a2a-server.js +91 -14
  10. package/dist/a2a.d.ts +19 -1
  11. package/dist/a2a.js +197 -27
  12. package/dist/api.d.ts +2 -0
  13. package/dist/api.js +160 -22
  14. package/dist/artifact-manifests.d.ts +344 -5
  15. package/dist/artifact-manifests.js +413 -20
  16. package/dist/artifact-transfer.d.ts +113 -0
  17. package/dist/artifact-transfer.js +517 -0
  18. package/dist/artifacts.d.ts +86 -0
  19. package/dist/artifacts.js +249 -1
  20. package/dist/backend-events.d.ts +2 -1
  21. package/dist/backend-events.js +1 -1
  22. package/dist/channel-catchup.d.ts +67 -0
  23. package/dist/channel-catchup.js +108 -0
  24. package/dist/channels.d.ts +35 -0
  25. package/dist/channels.js +152 -4
  26. package/dist/cli.js +28 -3
  27. package/dist/codex-protocol.d.ts +22 -0
  28. package/dist/codex-protocol.js +19 -0
  29. package/dist/codex.d.ts +32 -3
  30. package/dist/codex.js +91 -17
  31. package/dist/config.d.ts +25 -2
  32. package/dist/config.js +41 -4
  33. package/dist/development.d.ts +6 -6
  34. package/dist/execution-state.d.ts +245 -0
  35. package/dist/execution-state.js +236 -0
  36. package/dist/execution.d.ts +135 -0
  37. package/dist/execution.js +178 -0
  38. package/dist/index.d.ts +7 -4
  39. package/dist/index.js +5 -3
  40. package/dist/job-engine.d.ts +2 -1
  41. package/dist/job-engine.js +33 -4
  42. package/dist/lineage.d.ts +106 -0
  43. package/dist/lineage.js +145 -0
  44. package/dist/llamacpp.d.ts +32 -2
  45. package/dist/llamacpp.js +69 -33
  46. package/dist/mattermost.d.ts +8 -0
  47. package/dist/mattermost.js +250 -36
  48. package/dist/mission-tools.js +41 -5
  49. package/dist/missions.d.ts +5 -1
  50. package/dist/missions.js +10 -5
  51. package/dist/plugin-evidence.js +2 -1
  52. package/dist/plugin-sdk.d.ts +3 -0
  53. package/dist/plugin-sdk.js +3 -0
  54. package/dist/plugins.d.ts +108 -2
  55. package/dist/plugins.js +131 -1
  56. package/dist/preview.d.ts +1 -0
  57. package/dist/preview.js +4 -1
  58. package/dist/recovery.d.ts +155 -0
  59. package/dist/recovery.js +216 -0
  60. package/dist/research.d.ts +1 -1
  61. package/dist/retry.d.ts +143 -0
  62. package/dist/retry.js +127 -0
  63. package/dist/runtime.d.ts +56 -4
  64. package/dist/runtime.js +727 -125
  65. package/dist/store.d.ts +62 -7
  66. package/dist/store.js +86 -15
  67. package/dist/team-artifacts.d.ts +130 -112
  68. package/dist/team-artifacts.js +123 -151
  69. package/dist/team-child.d.ts +4 -1
  70. package/dist/team-child.js +21 -2
  71. package/dist/team-contract.d.ts +1 -1
  72. package/dist/telegram.d.ts +2 -0
  73. package/dist/telegram.js +83 -47
  74. package/dist/tool-scheduler.d.ts +84 -0
  75. package/dist/tool-scheduler.js +226 -0
  76. package/dist/tools.d.ts +78 -4
  77. package/dist/tools.js +34 -7
  78. package/package.json +15 -8
  79. package/profiles/assistant/config.yaml +2 -1
@@ -0,0 +1,135 @@
1
+ import { EXECUTION_METADATA_KEY, type ExecutionContext } from '@hivemagnus/hive-common/execution';
2
+ import { z } from 'zod';
3
+ import type Database from './sqlite.js';
4
+ /**
5
+ * Durable execution ancestry (execution context v1, `@hivemagnus/hive-common/execution`).
6
+ *
7
+ * Ancestry is attribution only. Tool, memory, mission, team-child and artifact
8
+ * selection never read `task_execution`; they re-derive scope from their owning
9
+ * stores. A context a caller supplies is never rejected: an invalid or absent one
10
+ * is replaced by a root minted for the task.
11
+ */
12
+ export { EXECUTION_METADATA_KEY, type ExecutionContext };
13
+ /** The environment variable naming this runtime instance in qualified references. */
14
+ export declare const INSTANCE_REF_ENV = "ARDENT_INSTANCE_REF";
15
+ /** Where a task's execution context came from. */
16
+ export declare const ExecutionSource: z.ZodEnum<{
17
+ caller: "caller";
18
+ a2a: "a2a";
19
+ minted: "minted";
20
+ continuation: "continuation";
21
+ }>;
22
+ export type ExecutionSource = z.infer<typeof ExecutionSource>;
23
+ /** Execution context v1 as Ardent reports it. Parsing always goes through hive-common, which never throws. */
24
+ export declare const ExecutionContextSchema: z.ZodObject<{
25
+ v: z.ZodLiteral<1>;
26
+ request_id: z.ZodOptional<z.ZodString>;
27
+ root: z.ZodString;
28
+ parent: z.ZodOptional<z.ZodString>;
29
+ self: z.ZodOptional<z.ZodString>;
30
+ inputs: z.ZodOptional<z.ZodReadonly<z.ZodArray<z.ZodString>>>;
31
+ attempt: z.ZodOptional<z.ZodNumber>;
32
+ deadline_ms: z.ZodOptional<z.ZodNumber>;
33
+ }, z.core.$strip>;
34
+ /** A request-body `execution` field: documented as a context, accepted as anything. */
35
+ export declare const ExecutionInput: z.ZodUnknown;
36
+ /**
37
+ * The instance part of this runtime's references: `ARDENT_INSTANCE_REF`
38
+ * (`<magnus node>.<profile>` under Magnus), else `local.<profile>`.
39
+ */
40
+ export declare function executionInstance(profile: string, env?: NodeJS.ProcessEnv): string;
41
+ /** The problem with `ARDENT_INSTANCE_REF`, if any. */
42
+ export declare function instanceRefProblem(env: NodeJS.ProcessEnv): string | undefined;
43
+ export declare function taskRef(instance: string, taskId: string): string;
44
+ /** One model call: `hx1:ardent:<instance>:attempt:<task>/<step>/<n>`. */
45
+ export declare function attemptRef(instance: string, taskId: string, step: number, attempt: number): string;
46
+ /** The local task id a reference names, when it is a task of this instance. */
47
+ export declare function localTaskId(instance: string, ref: string | null | undefined): string | undefined;
48
+ /**
49
+ * What an accept path knows about the work's ancestry. `context` is the raw
50
+ * supplied value (a body field, A2A metadata or a decoded header); anything
51
+ * invalid is treated as absent. `continuation` is for a task that continues
52
+ * another one (execution recovery): pass the original's context and the next attempt.
53
+ */
54
+ export type ExecutionAcceptance = {
55
+ context?: unknown;
56
+ source?: Exclude<ExecutionSource, 'minted'>;
57
+ /** The inbound `x-request-id`, used when the context carries none. */
58
+ requestId?: string | undefined;
59
+ /** The inbound `traceparent`; the task trace becomes its child. */
60
+ traceparent?: string | undefined;
61
+ attempt?: number;
62
+ inputs?: readonly string[];
63
+ };
64
+ /** The row `task_execution` keeps for a task. */
65
+ export type TaskExecution = {
66
+ task_id: string;
67
+ self_ref: string;
68
+ root_ref: string;
69
+ parent_ref: string | null;
70
+ inputs: string[];
71
+ context: ExecutionContext;
72
+ /** The task trace (W3C `traceparent`); model calls are its child spans. */
73
+ traceparent: string;
74
+ source: ExecutionSource;
75
+ created_ms: number;
76
+ };
77
+ /** Build the execution context of a newly accepted task. Self is always this task. */
78
+ export declare function buildTaskExecution(instance: string, task: {
79
+ id: string;
80
+ deadline_ms: number;
81
+ created_ms: number;
82
+ }, acceptance?: ExecutionAcceptance): TaskExecution;
83
+ /**
84
+ * The `task_execution` table: one row per task accepted since ancestry was
85
+ * added. Tasks accepted before have no row and report no `execution`.
86
+ */
87
+ export declare class TaskExecutions {
88
+ #private;
89
+ readonly db: Database;
90
+ constructor(db: Database);
91
+ /** Record a task's context. Call inside the accept transaction. */
92
+ insert(value: TaskExecution): void;
93
+ get(taskId: string): TaskExecution | undefined;
94
+ /** Contexts for several tasks at once (task lists). */
95
+ many(taskIds: readonly string[]): Map<string, TaskExecution>;
96
+ /** Local tasks whose causal parent is `ref`, oldest first. */
97
+ children(ref: string, limit?: number): TaskExecution[];
98
+ }
99
+ /** What one model call sends and journals. */
100
+ export type ModelAttempt = {
101
+ ref: string;
102
+ attempt: number;
103
+ request_id: string;
104
+ traceparent: string;
105
+ headers: Record<string, string>;
106
+ };
107
+ /**
108
+ * Outbound propagation for one running task: llama.cpp request headers
109
+ * (`x-request-id`, `traceparent`, `x-hive-execution`) and A2A metadata.
110
+ */
111
+ export declare class TaskPropagation {
112
+ #private;
113
+ readonly instance: string;
114
+ readonly task: {
115
+ id: string;
116
+ deadline_ms: number;
117
+ };
118
+ readonly context: ExecutionContext;
119
+ constructor(instance: string, task: {
120
+ id: string;
121
+ deadline_ms: number;
122
+ }, context: ExecutionContext, traceparent?: string);
123
+ /**
124
+ * A task without a stored row (accepted before ancestry was added) still
125
+ * propagates, as a root at its own reference that is not persisted.
126
+ */
127
+ static forTask(instance: string, task: {
128
+ id: string;
129
+ deadline_ms: number;
130
+ }, record: TaskExecution | undefined): TaskPropagation;
131
+ /** Headers for a model call that is not a completion (token counting): the task context. */
132
+ headers(): Record<string, string>;
133
+ /** One model completion: its attempt reference, a new request id and a child span. */
134
+ modelAttempt(step: number, attempt: number): ModelAttempt;
135
+ }
@@ -0,0 +1,178 @@
1
+ import { childExecution, EXECUTION_METADATA_KEY, executionHeaders, formatExecutionRef, parseExecutionContext, parseExecutionRef } from '@hivemagnus/hive-common/execution';
2
+ import { childTraceparent, formatTraceparent, generateRequestId, generateTraceparent, isValidRequestId, parseTraceparent } from '@hivemagnus/hive-common/context';
3
+ import { z } from 'zod';
4
+ /**
5
+ * Durable execution ancestry (execution context v1, `@hivemagnus/hive-common/execution`).
6
+ *
7
+ * Ancestry is attribution only. Tool, memory, mission, team-child and artifact
8
+ * selection never read `task_execution`; they re-derive scope from their owning
9
+ * stores. A context a caller supplies is never rejected: an invalid or absent one
10
+ * is replaced by a root minted for the task.
11
+ */
12
+ export { EXECUTION_METADATA_KEY };
13
+ /** The environment variable naming this runtime instance in qualified references. */
14
+ export const INSTANCE_REF_ENV = 'ARDENT_INSTANCE_REF';
15
+ const INSTANCE = /^[A-Za-z0-9._-]{1,96}$/;
16
+ const REF = /^hx1:[a-z][a-z0-9-]{1,31}:[A-Za-z0-9._-]{1,96}:[a-z]+:[A-Za-z0-9._:/-]{1,128}$/;
17
+ /** Where a task's execution context came from. */
18
+ export const ExecutionSource = z.enum(['caller', 'a2a', 'minted', 'continuation']);
19
+ const QualifiedRef = z.string().max(256).regex(REF).describe('Qualified reference hx1:<product>:<instance>:<kind>:<id>');
20
+ /** Execution context v1 as Ardent reports it. Parsing always goes through hive-common, which never throws. */
21
+ export const ExecutionContextSchema = z.object({
22
+ v: z.literal(1),
23
+ request_id: z.string().max(128).optional(),
24
+ root: QualifiedRef,
25
+ parent: QualifiedRef.optional(),
26
+ self: QualifiedRef.optional(),
27
+ inputs: z.array(QualifiedRef).max(16).readonly().optional(),
28
+ attempt: z.number().int().min(1).optional(),
29
+ deadline_ms: z.number().int().min(0).optional()
30
+ }).describe('Execution context v1. Attribution only: it never grants a tool, memory scope or artifact. An invalid value is treated as absent and never rejected.');
31
+ /** A request-body `execution` field: documented as a context, accepted as anything. */
32
+ export const ExecutionInput = z.unknown();
33
+ /**
34
+ * The instance part of this runtime's references: `ARDENT_INSTANCE_REF`
35
+ * (`<magnus node>.<profile>` under Magnus), else `local.<profile>`.
36
+ */
37
+ export function executionInstance(profile, env = process.env) {
38
+ const value = env[INSTANCE_REF_ENV];
39
+ if (value === undefined || value === '')
40
+ return `local.${profile}`;
41
+ if (!INSTANCE.test(value))
42
+ throw new Error(`${INSTANCE_REF_ENV} must be 1 to 96 characters of A-Z, a-z, 0-9, '.', '_' or '-'`);
43
+ return value;
44
+ }
45
+ /** The problem with `ARDENT_INSTANCE_REF`, if any. */
46
+ export function instanceRefProblem(env) {
47
+ try {
48
+ executionInstance('profile', env);
49
+ return undefined;
50
+ }
51
+ catch (error) {
52
+ return error instanceof Error ? error.message : `${INSTANCE_REF_ENV} is invalid`;
53
+ }
54
+ }
55
+ export function taskRef(instance, taskId) {
56
+ return formatExecutionRef({ product: 'ardent', instance, kind: 'task', id: taskId });
57
+ }
58
+ /** One model call: `hx1:ardent:<instance>:attempt:<task>/<step>/<n>`. */
59
+ export function attemptRef(instance, taskId, step, attempt) {
60
+ return formatExecutionRef({ product: 'ardent', instance, kind: 'attempt', id: `${taskId}/${step}/${attempt}` });
61
+ }
62
+ /** The local task id a reference names, when it is a task of this instance. */
63
+ export function localTaskId(instance, ref) {
64
+ const parts = parseExecutionRef(ref);
65
+ return parts && parts.product === 'ardent' && parts.instance === instance && parts.kind === 'task' ? parts.id : undefined;
66
+ }
67
+ /** Build the execution context of a newly accepted task. Self is always this task. */
68
+ export function buildTaskExecution(instance, task, acceptance = {}) {
69
+ const supplied = parseExecutionContext(acceptance.context);
70
+ const self = taskRef(instance, task.id);
71
+ const inbound = isValidRequestId(acceptance.requestId) ? acceptance.requestId : undefined;
72
+ const requestId = supplied?.request_id ?? inbound ?? generateRequestId();
73
+ const context = childExecution(supplied, self, { requestId, deadlineMs: task.deadline_ms,
74
+ ...(acceptance.attempt !== undefined ? { attempt: acceptance.attempt } : {}),
75
+ ...(acceptance.inputs?.length ? { inputs: acceptance.inputs } : supplied?.inputs?.length ? { inputs: supplied.inputs } : {}) });
76
+ const parentTrace = parseTraceparent(acceptance.traceparent);
77
+ const trace = parentTrace ? childTraceparent(parentTrace) : generateTraceparent();
78
+ return { task_id: task.id, self_ref: self, root_ref: context.root, parent_ref: context.parent ?? null, inputs: [...(context.inputs ?? [])],
79
+ context, traceparent: formatTraceparent(trace), source: supplied ? acceptance.source ?? 'caller' : 'minted', created_ms: task.created_ms };
80
+ }
81
+ const Row = z.object({ task_id: z.string(), self_ref: z.string(), root_ref: z.string(), parent_ref: z.string().nullable(),
82
+ inputs_json: z.string(), context_json: z.string(), source: ExecutionSource, created_ms: z.number().int() });
83
+ const StoredContext = z.object({ execution: z.unknown(), traceparent: z.string() });
84
+ /**
85
+ * The `task_execution` table: one row per task accepted since ancestry was
86
+ * added. Tasks accepted before have no row and report no `execution`.
87
+ */
88
+ export class TaskExecutions {
89
+ db;
90
+ constructor(db) {
91
+ this.db = db;
92
+ db.exec(`CREATE TABLE IF NOT EXISTS task_execution (
93
+ task_id TEXT PRIMARY KEY REFERENCES tasks(id), self_ref TEXT NOT NULL, root_ref TEXT NOT NULL, parent_ref TEXT,
94
+ inputs_json TEXT NOT NULL, context_json TEXT NOT NULL,
95
+ source TEXT NOT NULL CHECK(source IN ('caller','a2a','minted','continuation')), created_ms INTEGER NOT NULL);
96
+ CREATE INDEX IF NOT EXISTS task_execution_root ON task_execution(root_ref, created_ms);
97
+ CREATE INDEX IF NOT EXISTS task_execution_parent ON task_execution(parent_ref, created_ms);`);
98
+ }
99
+ /** Record a task's context. Call inside the accept transaction. */
100
+ insert(value) {
101
+ this.db.prepare(`INSERT INTO task_execution(task_id,self_ref,root_ref,parent_ref,inputs_json,context_json,source,created_ms)
102
+ VALUES (?,?,?,?,?,?,?,?)`).run(value.task_id, value.self_ref, value.root_ref, value.parent_ref, JSON.stringify(value.inputs), JSON.stringify({ execution: value.context, traceparent: value.traceparent }), value.source, value.created_ms);
103
+ }
104
+ get(taskId) {
105
+ const raw = this.db.prepare('SELECT * FROM task_execution WHERE task_id=?').get(taskId);
106
+ return raw ? this.#record(raw) : undefined;
107
+ }
108
+ /** Contexts for several tasks at once (task lists). */
109
+ many(taskIds) {
110
+ const found = new Map();
111
+ if (!taskIds.length)
112
+ return found;
113
+ const rows = this.db.prepare(`SELECT * FROM task_execution WHERE task_id IN (${taskIds.map(() => '?').join(',')})`).all(...taskIds);
114
+ for (const raw of rows) {
115
+ const record = this.#record(raw);
116
+ if (record)
117
+ found.set(record.task_id, record);
118
+ }
119
+ return found;
120
+ }
121
+ /** Local tasks whose causal parent is `ref`, oldest first. */
122
+ children(ref, limit = 200) {
123
+ return this.db.prepare('SELECT * FROM task_execution WHERE parent_ref=? ORDER BY created_ms, task_id LIMIT ?')
124
+ .all(ref, Math.max(1, Math.min(limit, 500))).flatMap(raw => this.#record(raw) ?? []);
125
+ }
126
+ #record(raw) {
127
+ const row = Row.parse(raw);
128
+ let stored;
129
+ let inputs;
130
+ try {
131
+ stored = StoredContext.parse(JSON.parse(row.context_json));
132
+ inputs = z.array(z.string()).parse(JSON.parse(row.inputs_json));
133
+ }
134
+ catch {
135
+ return undefined;
136
+ }
137
+ const context = parseExecutionContext(stored.execution);
138
+ if (!context)
139
+ return undefined;
140
+ return { task_id: row.task_id, self_ref: row.self_ref, root_ref: row.root_ref, parent_ref: row.parent_ref, inputs, context,
141
+ traceparent: stored.traceparent, source: row.source, created_ms: row.created_ms };
142
+ }
143
+ }
144
+ /**
145
+ * Outbound propagation for one running task: llama.cpp request headers
146
+ * (`x-request-id`, `traceparent`, `x-hive-execution`) and A2A metadata.
147
+ */
148
+ export class TaskPropagation {
149
+ instance;
150
+ task;
151
+ context;
152
+ #trace;
153
+ constructor(instance, task, context, traceparent) {
154
+ this.instance = instance;
155
+ this.task = task;
156
+ this.context = context;
157
+ this.#trace = parseTraceparent(traceparent) ?? generateTraceparent();
158
+ }
159
+ /**
160
+ * A task without a stored row (accepted before ancestry was added) still
161
+ * propagates, as a root at its own reference that is not persisted.
162
+ */
163
+ static forTask(instance, task, record) {
164
+ return new TaskPropagation(instance, task, record?.context ?? childExecution(undefined, taskRef(instance, task.id), { deadlineMs: task.deadline_ms }), record?.traceparent);
165
+ }
166
+ /** Headers for a model call that is not a completion (token counting): the task context. */
167
+ headers() {
168
+ return { 'x-request-id': generateRequestId(), traceparent: formatTraceparent(childTraceparent(this.#trace)), ...executionHeaders(this.context) };
169
+ }
170
+ /** One model completion: its attempt reference, a new request id and a child span. */
171
+ modelAttempt(step, attempt) {
172
+ const ref = attemptRef(this.instance, this.task.id, step, attempt);
173
+ const requestId = generateRequestId();
174
+ const traceparent = formatTraceparent(childTraceparent(this.#trace));
175
+ const context = childExecution(this.context, ref, { attempt, deadlineMs: this.task.deadline_ms });
176
+ return { ref, attempt, request_id: requestId, traceparent, headers: { 'x-request-id': requestId, traceparent, ...executionHeaders(context) } };
177
+ }
178
+ }
package/dist/index.d.ts CHANGED
@@ -1,9 +1,12 @@
1
- export { ArdentRuntime, type RunResult } from './runtime.js';
2
- export { ConfigSchema, loadConfig, initProfile, saveConfig, profilePath, parseConfig, runtimeProblems, type ArdentConfig, type LoadedConfig } from './config.js';
1
+ export { ArdentRuntime, RecoveryConflictError, RecoveryHeldError, type RunResult } from './runtime.js';
2
+ export { RecoveryDecisionInput, RecoveryViewSchema, RECOVERY_REASONS, type RecoveryView, type RecoveryReasonCode } from './recovery.js';
3
+ export type { InvocationState, RecoveryStatus, RecoveryAction, RecoveryReason, RecoveryCheckpoint, RecoveryDecision } from './execution-state.js';
4
+ export { ConfigSchema, loadConfig, initProfile, saveConfig, profilePath, parseConfig, runtimeProblems, maxParallelTasks, isConfigNotice, type ArdentConfig, type LoadedConfig } from './config.js';
3
5
  export { ResearchBriefSchema } from './research.js';
4
6
  export { TaskStore, type Task } from './store.js';
5
- export { defineTool, ToolRegistry, ProvenNoEffectError, type Tool, type ToolContext, type ToolEffect, type ToolResult } from './tools.js';
7
+ export { defineTool, ToolRegistry, ProvenNoEffectError, ToolCallLimitError, toolRunsInParallel, type Tool, type ToolContext, type ToolEffect, type ToolResult, type ToolConcurrency, type ToolInvocationContext, type ToolReconcileContext, type ToolReconcileResult, type PreparedToolCall, type ExecutionContext } from './tools.js';
8
+ export { toolIdempotencyKey } from './tool-scheduler.js';
6
9
  export { createArdentApi, ardentOpenApi } from './api.js';
7
10
  export { JobEngine, validateJobDefinitions, type JobContext, type JobDefinition, type JobHandler, type JobRegistry, type JobResult, type OwnershipCheck } from './job-engine.js';
8
- export { definePlugin, registerPlugin, registeredPlugins, clearRegisteredPlugins, loadPlugins, type ArdentPlugin, type ArdentPluginContext, type ArdentCliCommand, type ArdentCliInvocation, type ArdentPluginFactory, type ArdentPluginFactoryContext, type ArdentTaskPluginContext } from './plugins.js';
11
+ export { definePlugin, registerPlugin, registeredPlugins, clearRegisteredPlugins, loadPlugins, type ArdentPlugin, type ArdentPluginContext, type ArdentCliCommand, type ArdentCliInvocation, type ArdentPluginFactory, type ArdentPluginFactoryContext, type ArdentTaskPluginContext, type ArdentChannelMessage, type ArdentChannelDelivery, type ArdentDeliveryOutcome, type ArdentToolCall, type ArdentToolDenial, type ArdentToolCancellation } from './plugins.js';
9
12
  export type { TeamEnvelope, TeamMission, TeamResult } from './team-contract.js';
package/dist/index.js CHANGED
@@ -1,8 +1,10 @@
1
- export { ArdentRuntime } from './runtime.js';
2
- export { ConfigSchema, loadConfig, initProfile, saveConfig, profilePath, parseConfig, runtimeProblems } from './config.js';
1
+ export { ArdentRuntime, RecoveryConflictError, RecoveryHeldError } from './runtime.js';
2
+ export { RecoveryDecisionInput, RecoveryViewSchema, RECOVERY_REASONS } from './recovery.js';
3
+ export { ConfigSchema, loadConfig, initProfile, saveConfig, profilePath, parseConfig, runtimeProblems, maxParallelTasks, isConfigNotice } from './config.js';
3
4
  export { ResearchBriefSchema } from './research.js';
4
5
  export { TaskStore } from './store.js';
5
- export { defineTool, ToolRegistry, ProvenNoEffectError } from './tools.js';
6
+ export { defineTool, ToolRegistry, ProvenNoEffectError, ToolCallLimitError, toolRunsInParallel } from './tools.js';
7
+ export { toolIdempotencyKey } from './tool-scheduler.js';
6
8
  export { createArdentApi, ardentOpenApi } from './api.js';
7
9
  export { JobEngine, validateJobDefinitions } from './job-engine.js';
8
10
  export { definePlugin, registerPlugin, registeredPlugins, clearRegisteredPlugins, loadPlugins } from './plugins.js';
@@ -160,8 +160,9 @@ export declare class JobEngine {
160
160
  readonly registry: JobRegistry;
161
161
  readonly ownershipCheck: OwnershipCheck;
162
162
  readonly clock: () => number;
163
+ readonly random: () => number;
163
164
  /** `clock` measures elapsed time within a tick; the injected tick time stays the timeline origin. */
164
- constructor(db: Database, profileDir: string, profile: string, registry: JobRegistry, ownershipCheck: OwnershipCheck, clock?: () => number);
165
+ constructor(db: Database, profileDir: string, profile: string, registry: JobRegistry, ownershipCheck: OwnershipCheck, clock?: () => number, random?: () => number);
165
166
  load(): Promise<{
166
167
  definitions: JobDefinitions;
167
168
  sha256: string;
@@ -3,6 +3,7 @@ import { constants, existsSync, mkdirSync } from 'node:fs';
3
3
  import { open, readFile, unlink } from 'node:fs/promises';
4
4
  import { join } from 'node:path';
5
5
  import { z } from 'zod';
6
+ import { backoffDelay } from '@hivemagnus/hive-common/retry';
6
7
  const identifier = z.string().regex(/^[a-z][a-z0-9._-]{0,79}$/);
7
8
  const jobId = z.string().regex(/^[a-z0-9][a-z0-9._-]{0,79}$/);
8
9
  const timezone = z.string().min(1).max(80).refine(value => {
@@ -45,6 +46,11 @@ const rowSchema = z.object({ window_key: z.string(), job_id: z.string(), local_k
45
46
  state: z.enum(['queued', 'running', 'retry', 'completed', 'failed', 'unknown', 'superseded']),
46
47
  attempts: z.number().int(), next_attempt_ms: z.number().int(), receipt_json: z.string().nullable(),
47
48
  receipt_sha256: z.string().nullable(), error: z.string().nullable(), updated_ms: z.number().int() });
49
+ /** A job's retry policy: `retry_backoff_seconds · 2^(n-1)`, uncapped as before, with equal jitter. */
50
+ function jobRetryPolicy(job) {
51
+ const baseMs = job.policy.retry_backoff_seconds * 1000;
52
+ return { maxAttempts: job.policy.max_attempts, baseMs, maxMs: baseMs * 2 ** Math.max(0, job.policy.max_attempts - 1), jitter: 'equal' };
53
+ }
48
54
  function sha256(value) { return createHash('sha256').update(value).digest('hex'); }
49
55
  function encode(value) {
50
56
  const encoded = JSON.stringify(value);
@@ -146,17 +152,19 @@ export class JobEngine {
146
152
  registry;
147
153
  ownershipCheck;
148
154
  clock;
155
+ random;
149
156
  #lastValidationError = null;
150
157
  #lastActive = null;
151
158
  #busy = false;
152
159
  /** `clock` measures elapsed time within a tick; the injected tick time stays the timeline origin. */
153
- constructor(db, profileDir, profile, registry, ownershipCheck, clock = () => Date.now()) {
160
+ constructor(db, profileDir, profile, registry, ownershipCheck, clock = () => Date.now(), random = Math.random) {
154
161
  this.db = db;
155
162
  this.profileDir = profileDir;
156
163
  this.profile = profile;
157
164
  this.registry = registry;
158
165
  this.ownershipCheck = ownershipCheck;
159
166
  this.clock = clock;
167
+ this.random = random;
160
168
  identifier.parse(profile);
161
169
  mkdirSync(join(profileDir, 'state', 'job-definition-releases'), { recursive: true, mode: 0o700 });
162
170
  db.exec(`CREATE TABLE IF NOT EXISTS job_windows (
@@ -420,14 +428,19 @@ export class JobEngine {
420
428
  const settledMs = result.state === 'completed' ? claimedAt.getTime() : finishedMs;
421
429
  const receiptJson = encode(result.receipt);
422
430
  const receiptSha = sha256(receiptJson);
423
- const canRetry = result.state === 'retry' && result.receipt.effect_status === 'none' && attempt < job.policy.max_attempts;
431
+ // The existing formula (retry_backoff_seconds · 2^(n-1)) with equal jitter, and never past
432
+ // the window deadline: the next attempt must start before the job's next window is due.
433
+ const delay = result.state === 'retry' && result.receipt.effect_status === 'none'
434
+ ? backoffDelay(attempt, jobRetryPolicy(job), { deadlineMs: this.#windowDeadline(job, window, finishedMs), now: () => finishedMs, random: this.random }) : null;
435
+ const canRetry = delay !== null;
436
+ const pastDeadline = !canRetry && result.state === 'retry' && result.receipt.effect_status === 'none' && attempt < job.policy.max_attempts;
424
437
  const state = result.state === 'retry' ? canRetry ? 'retry' : result.receipt.effect_status === 'none' ? 'failed' : 'unknown' : result.state;
425
- const delay = job.policy.retry_backoff_seconds * 1000 * Math.pow(2, attempt - 1);
426
438
  this.db.transaction(() => {
427
439
  this.db.prepare('INSERT INTO job_attempts(window_key,attempt,state,receipt_json,receipt_sha256,recorded_ms) VALUES (?,?,?,?,?,?)')
428
440
  .run(window.window_key, attempt, state, receiptJson, receiptSha, finishedMs);
429
441
  this.db.prepare('UPDATE job_windows SET state=?,next_attempt_ms=?,receipt_json=?,receipt_sha256=?,error=?,updated_ms=? WHERE window_key=? AND state=\'running\'')
430
- .run(state, canRetry ? finishedMs + delay : settledMs, receiptJson, receiptSha, state === 'failed' ? 'handler failed or retry budget exhausted' : state === 'unknown' ? 'effect outcome unknown' : null, settledMs, window.window_key);
442
+ .run(state, canRetry ? finishedMs + delay : settledMs, receiptJson, receiptSha, state === 'failed' ? pastDeadline ? 'RETRY_DEADLINE: the next attempt would start after the window deadline' : 'handler failed or retry budget exhausted'
443
+ : state === 'unknown' ? 'effect outcome unknown' : null, settledMs, window.window_key);
431
444
  })();
432
445
  if (state === 'completed')
433
446
  completed++;
@@ -457,6 +470,22 @@ export class JobEngine {
457
470
  }
458
471
  }
459
472
  }
473
+ /**
474
+ * When a window's retries must stop: the job's next window. For an interval that is one period
475
+ * after the window; for cron, the next matching minute, searched only up to `horizonMs` plus the
476
+ * longest backoff (undefined when none falls inside, so no deadline applies).
477
+ */
478
+ #windowDeadline(job, window, fromMs) {
479
+ if ('kind' in job.schedule)
480
+ return window.scheduled_ms + job.schedule.every_minutes * 60_000;
481
+ const cron = parseCron(job.schedule.cron);
482
+ const policy = jobRetryPolicy(job);
483
+ const limit = Math.max(fromMs, window.scheduled_ms) + policy.maxMs;
484
+ for (let minuteMs = Math.floor(window.scheduled_ms / 60_000) * 60_000 + 60_000; minuteMs <= limit; minuteMs += 60_000)
485
+ if (matches(cron, localParts(new Date(minuteMs), job.schedule.timezone)))
486
+ return minuteMs;
487
+ return undefined;
488
+ }
460
489
  #admissionFenced() {
461
490
  try {
462
491
  return Boolean(this.db.prepare('SELECT 1 FROM admission_fence WHERE singleton=1').get());
@@ -0,0 +1,106 @@
1
+ import { z } from 'zod';
2
+ import type { TaskStore } from './store.js';
3
+ export declare const ToolLineageState: z.ZodEnum<{
4
+ failed: "failed";
5
+ succeeded: "succeeded";
6
+ not_dispatched: "not_dispatched";
7
+ attempted: "attempted";
8
+ denied: "denied";
9
+ }>;
10
+ /** What Ardent knows locally about a task's place in its causal tree, rebuilt from SQLite. */
11
+ export declare const TaskLineageSchema: z.ZodObject<{
12
+ task_id: z.ZodString;
13
+ execution: z.ZodOptional<z.ZodObject<{
14
+ v: z.ZodLiteral<1>;
15
+ request_id: z.ZodOptional<z.ZodString>;
16
+ root: z.ZodString;
17
+ parent: z.ZodOptional<z.ZodString>;
18
+ self: z.ZodOptional<z.ZodString>;
19
+ inputs: z.ZodOptional<z.ZodReadonly<z.ZodArray<z.ZodString>>>;
20
+ attempt: z.ZodOptional<z.ZodNumber>;
21
+ deadline_ms: z.ZodOptional<z.ZodNumber>;
22
+ }, z.core.$strip>>;
23
+ source: z.ZodOptional<z.ZodEnum<{
24
+ caller: "caller";
25
+ a2a: "a2a";
26
+ minted: "minted";
27
+ continuation: "continuation";
28
+ }>>;
29
+ traceparent: z.ZodOptional<z.ZodString>;
30
+ parent: z.ZodOptional<z.ZodObject<{
31
+ ref: z.ZodString;
32
+ local_task_id: z.ZodOptional<z.ZodString>;
33
+ }, z.core.$strip>>;
34
+ children: z.ZodArray<z.ZodObject<{
35
+ ref: z.ZodString;
36
+ local_task_id: z.ZodString;
37
+ source: z.ZodEnum<{
38
+ caller: "caller";
39
+ a2a: "a2a";
40
+ minted: "minted";
41
+ continuation: "continuation";
42
+ }>;
43
+ created_ms: z.ZodNumber;
44
+ }, z.core.$strip>>;
45
+ continuations: z.ZodArray<z.ZodObject<{
46
+ ref: z.ZodString;
47
+ local_task_id: z.ZodString;
48
+ source: z.ZodEnum<{
49
+ caller: "caller";
50
+ a2a: "a2a";
51
+ minted: "minted";
52
+ continuation: "continuation";
53
+ }>;
54
+ created_ms: z.ZodNumber;
55
+ }, z.core.$strip>>;
56
+ model_attempts: z.ZodArray<z.ZodObject<{
57
+ step: z.ZodNumber;
58
+ attempt: z.ZodNumber;
59
+ backend: z.ZodNullable<z.ZodString>;
60
+ request_id: z.ZodNullable<z.ZodString>;
61
+ ref: z.ZodNullable<z.ZodString>;
62
+ started_ms: z.ZodNumber;
63
+ usage: z.ZodNullable<z.ZodUnknown>;
64
+ repair: z.ZodOptional<z.ZodBoolean>;
65
+ }, z.core.$strip>>;
66
+ tools: z.ZodArray<z.ZodObject<{
67
+ call_id: z.ZodString;
68
+ name: z.ZodString;
69
+ effect: z.ZodNullable<z.ZodString>;
70
+ state: z.ZodEnum<{
71
+ failed: "failed";
72
+ succeeded: "succeeded";
73
+ not_dispatched: "not_dispatched";
74
+ attempted: "attempted";
75
+ denied: "denied";
76
+ }>;
77
+ }, z.core.$strip>>;
78
+ artifacts: z.ZodArray<z.ZodObject<{
79
+ sha256: z.ZodString;
80
+ name: z.ZodString;
81
+ mime: z.ZodNullable<z.ZodString>;
82
+ size: z.ZodNullable<z.ZodNumber>;
83
+ artifact_id: z.ZodNullable<z.ZodString>;
84
+ source: z.ZodEnum<{
85
+ manifest: "manifest";
86
+ artifact_registered: "artifact_registered";
87
+ research_artifacts: "research_artifacts";
88
+ }>;
89
+ created_ms: z.ZodNumber;
90
+ schema_version: z.ZodOptional<z.ZodString>;
91
+ execution: z.ZodOptional<z.ZodObject<{
92
+ root: z.ZodString;
93
+ task: z.ZodOptional<z.ZodString>;
94
+ step: z.ZodOptional<z.ZodString>;
95
+ }, z.core.$strip>>;
96
+ rendition_of: z.ZodOptional<z.ZodString>;
97
+ }, z.core.$strip>>;
98
+ }, z.core.$strip>;
99
+ export type TaskLineage = z.infer<typeof TaskLineageSchema>;
100
+ /**
101
+ * The lineage of a local task: its execution context and parent, local children
102
+ * and continuations, model attempts with their request ids, tool calls and
103
+ * artifacts. Model attempts, tools and artifacts come from the task journal, so
104
+ * tasks accepted before ancestry was recorded still list them.
105
+ */
106
+ export declare function taskLineage(store: TaskStore, instance: string, taskId: string): TaskLineage | undefined;