@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.
Files changed (79) hide show
  1. package/README.md +504 -16
  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 +16 -9
  79. package/profiles/assistant/config.yaml +2 -1
@@ -0,0 +1,216 @@
1
+ import { z } from 'zod';
2
+ import { codexThreadRecoveryLocked, codexThreadRecoveryProblem } from './codex-protocol.js';
3
+ import { InvalidCheckpointError, NO_EFFECT_STATES, RecoveryAction, RecoveryCheckpoint, RecoveryDecision, RecoveryReason, RecoveryStatus, SETTLED_STATES } from './execution-state.js';
4
+ export const RecoveryViewSchema = z.object({
5
+ status: RecoveryStatus, reason: RecoveryReason, attempt: z.number().int().min(1), checkpoint: RecoveryCheckpoint.optional(),
6
+ actions: z.array(RecoveryAction).describe('Only the actions valid now'),
7
+ continuation_task_id: z.string().optional(), decided: RecoveryDecision.optional()
8
+ }).describe('Execution recovery of a task interrupted by a crash or restart. Absent for a task that was never interrupted.');
9
+ /** `POST /api/v1/tasks/{id}/recovery`. */
10
+ export const RecoveryDecisionInput = z.object({
11
+ action: RecoveryAction,
12
+ /** The pending call the decision (and `result`) is about; defaults to every pending call. */
13
+ call_id: z.string().min(1).max(256).optional(),
14
+ /** `mark_applied` only: the call's result, at most 64 KiB, checked against the tool's output schema. */
15
+ result: z.unknown().optional(),
16
+ note: z.string().trim().min(1).max(2000).optional(),
17
+ /** `retry_with_new_deadline` only: the continuation's deadline from now, at most `execution.recovery_max_new_deadline_seconds`. */
18
+ deadline_seconds: z.number().int().min(1).max(86400).optional()
19
+ }).strict();
20
+ export const MAX_OPERATOR_RESULT_BYTES = 64 * 1024;
21
+ export const RECOVERY_REASONS = {
22
+ CANCELLED_DURING_OUTAGE: 'Cancellation was requested before the restart and no effect was uncertain, so the task was cancelled.',
23
+ CANCELLED_WITH_UNSETTLED_EFFECT: 'Cancellation was requested, but a tool call with a possible external effect had not settled. Confirm whether it applied.',
24
+ DEADLINE_ELAPSED_DURING_OUTAGE: 'The task deadline passed while the runtime was stopped. It is never extended automatically.',
25
+ RECOVERY_DISABLED: 'Execution recovery is disabled (execution.recovery.enabled: false); interrupted tasks are held as unknown.',
26
+ EXTENSION_EXECUTION_NOT_RESUMABLE: 'An extension task executor with a possible external effect was running; extension execution is not resumable.',
27
+ PREVIEW_NOT_RESUMABLE: 'Preview tasks are not resumed; submit the preview again.',
28
+ RESTART_NO_EFFECT: 'The task stopped before any effectful tool was dispatched; it restarts from the beginning.',
29
+ NO_EXECUTION_CHECKPOINT: 'The task has no execution checkpoint (it started before checkpoints were recorded, or stopped before the first one) and dispatched an effectful tool.',
30
+ CHECKPOINT_INVALID: 'The execution checkpoint failed verification and is not used.',
31
+ RESUME_FROM_CHECKPOINT: 'Every interrupted tool call is settled, a read or idempotent; the task resumes at its next step.',
32
+ TOOL_CHECK_PENDING: 'An interrupted tool call is checked against its tool (idempotency or reconciliation) before the task resumes.',
33
+ RECONCILE_INTERRUPTED_CALL: 'An interrupted tool call can be reconciled with its service before the task resumes.',
34
+ UNSETTLED_EXTERNAL_WRITE: 'A tool call with a possible external effect was dispatched but its outcome was not recorded, and the tool cannot prove it. Confirm whether it applied.',
35
+ RECONCILIATION_INCONCLUSIVE: 'Reconciliation could not prove whether an interrupted tool call applied. Confirm whether it applied.',
36
+ CODEX_THREAD_RESUME: 'The durable Codex thread is resumed after thread/read verifies every tool call in it.',
37
+ CODEX_RESTART_NO_EFFECT: 'The Codex task never dispatched an effectful tool; it restarts on a fresh thread.',
38
+ CODEX_THREAD_NOT_VERIFIABLE: 'The Codex task dispatched an effectful tool and its thread cannot be verified for resumption.'
39
+ };
40
+ export function reason(code, detail) {
41
+ return { code, message: detail ? `${RECOVERY_REASONS[code]} ${detail}`.slice(0, 1000) : RECOVERY_REASONS[code] };
42
+ }
43
+ /** Classify an unsettled call. Read and idempotent calls are re-dispatched; reconcilable ones are asked; the rest are held. */
44
+ export function classifyPending(invocation, tool) {
45
+ if (invocation.effect === 'read')
46
+ return 'redispatch';
47
+ if (!tool)
48
+ return 'hold';
49
+ if (tool.effect === 'read' || tool.idempotent === true)
50
+ return 'redispatch';
51
+ return typeof tool.reconcile === 'function' ? 'reconcile' : 'hold';
52
+ }
53
+ function pendingCalls(invocations, legacy, reconcilable) {
54
+ return [
55
+ ...invocations.filter(item => item.state === 'dispatched').map(item => ({ call_id: item.call_id, tool: item.name, effect: item.effect,
56
+ dispatched_at: item.dispatched_ms === null ? null : new Date(item.dispatched_ms).toISOString(), reconcilable: reconcilable(item) })),
57
+ ...legacy.filter(item => !item.settled).map(item => ({ call_id: item.call_id ?? 'unknown', tool: item.name, effect: item.effect ?? 'unknown', dispatched_at: null, reconcilable: false }))
58
+ ];
59
+ }
60
+ /** The attempt that was interrupted. */
61
+ export function interruptedAttempt(state, recovery) {
62
+ return Math.max(state?.attempt ?? 1, recovery?.status === 'resumed' ? recovery.attempt : 1);
63
+ }
64
+ function planTask(store, task, options, now) {
65
+ const states = store.executionState;
66
+ let state;
67
+ let invalid = false;
68
+ try {
69
+ state = states.get(task.id);
70
+ }
71
+ catch (error) {
72
+ if (error instanceof InvalidCheckpointError)
73
+ invalid = true;
74
+ else
75
+ throw error;
76
+ }
77
+ const invocations = states.invocations(task.id);
78
+ const legacy = states.legacyAttempts(task.id);
79
+ const unsettled = invocations.filter(item => item.state === 'dispatched');
80
+ const uncertain = states.uncertain(task.id);
81
+ const effectfulDispatched = invocations.some(item => item.effect !== 'read' && !NO_EFFECT_STATES.has(item.state)) || legacy.some(item => item.effect !== 'read');
82
+ const verdicts = new Map(unsettled.map(item => [item.call_id, options.toolFor ? classifyPending(item, options.toolFor(task, item.name)) : item.effect === 'read' ? 'redispatch' : undefined]));
83
+ const checkpoint = { step: state?.step ?? 0, completed_calls: invocations.filter(item => SETTLED_STATES.has(item.state)).length,
84
+ pending_calls: pendingCalls(invocations, legacy, item => verdicts.get(item.call_id) === 'reconcile') };
85
+ const held = (status, value) => ({ outcome: 'held', status, reason: value, checkpoint });
86
+ const events = (kind) => store.db.prepare('SELECT 1 FROM events WHERE task_id=? AND kind=? LIMIT 1').get(task.id, kind) !== undefined;
87
+ if (events('cancel_requested'))
88
+ return uncertain ? held('awaiting_decision', reason('CANCELLED_WITH_UNSETTLED_EFFECT')) : { outcome: 'cancelled', reason: reason('CANCELLED_DURING_OUTAGE') };
89
+ if (task.deadline_ms <= now)
90
+ return uncertain ? held('awaiting_decision', reason('DEADLINE_ELAPSED_DURING_OUTAGE')) : { outcome: 'failed', reason: reason('DEADLINE_ELAPSED_DURING_OUTAGE') };
91
+ if (options.enabled === false)
92
+ return held('unsupported', reason('RECOVERY_DISABLED'));
93
+ const extension = store.db.prepare("SELECT 1 FROM events WHERE task_id=? AND kind='extension_execution_attempt' AND json_extract(detail_json,'$.effect')='possible' LIMIT 1").get(task.id);
94
+ if (extension)
95
+ return held('unsupported', reason('EXTENSION_EXECUTION_NOT_RESUMABLE'));
96
+ if (task.context === 'preview')
97
+ return held('unsupported', reason('PREVIEW_NOT_RESUMABLE'));
98
+ if (invalid)
99
+ return held('unsupported', reason('CHECKPOINT_INVALID'));
100
+ if (task.backend === 'codex') {
101
+ const effectfulUnsettled = unsettled.some(item => item.effect !== 'read') || legacy.some(item => !item.settled && item.effect !== 'read');
102
+ const thread = state?.codex;
103
+ if (!effectfulUnsettled && thread?.durable && codexThreadRecoveryLocked())
104
+ return { outcome: 'ready', reason: reason('CODEX_THREAD_RESUME'), checkpoint };
105
+ if (!effectfulDispatched)
106
+ return { outcome: 'ready', reason: reason('CODEX_RESTART_NO_EFFECT'), checkpoint };
107
+ const why = effectfulUnsettled ? 'An effectful tool call is unsettled.' : !thread ? 'No thread was recorded.' : !thread.durable ? 'The thread was ephemeral (providers.codex.durable_threads: false).'
108
+ : codexThreadRecoveryProblem(undefined) ?? 'The thread could not be verified.';
109
+ return held('unsupported', reason('CODEX_THREAD_NOT_VERIFIABLE', why));
110
+ }
111
+ if (!state)
112
+ return effectfulDispatched ? held('unsupported', reason('NO_EXECUTION_CHECKPOINT')) : { outcome: 'ready', reason: reason('RESTART_NO_EFFECT'), checkpoint };
113
+ if (legacy.some(item => !item.settled && item.effect !== 'read'))
114
+ return held('unsupported', reason('NO_EXECUTION_CHECKPOINT'));
115
+ const values = [...verdicts.values()];
116
+ if (values.every(value => value === 'redispatch'))
117
+ return { outcome: 'ready', reason: reason('RESUME_FROM_CHECKPOINT'), checkpoint };
118
+ if (values.some(value => value === 'hold')) {
119
+ const missing = unsettled.find(item => verdicts.get(item.call_id) === 'hold' && !options.toolFor?.(task, item.name));
120
+ return held('awaiting_decision', reason('UNSETTLED_EXTERNAL_WRITE', missing ? `Tool ${missing.name} is no longer available.` : undefined));
121
+ }
122
+ if (values.some(value => value === undefined))
123
+ return { outcome: 'reconciling', reason: reason('TOOL_CHECK_PENDING'), checkpoint };
124
+ return { outcome: 'reconciling', reason: reason('RECONCILE_INTERRUPTED_CALL'), checkpoint };
125
+ }
126
+ /** Record one plan. Ready and reconciling tasks stay `running` under the same id. */
127
+ function applyPlan(store, task, plan, attempt) {
128
+ const states = store.executionState;
129
+ store.db.transaction(() => {
130
+ if (plan.outcome === 'cancelled' || plan.outcome === 'failed') {
131
+ store.setState(task.id, plan.outcome, null, plan.reason.message);
132
+ states.setRecovery(task.id, { status: 'resolved', reason: plan.reason, attempt });
133
+ }
134
+ else if (plan.outcome === 'held') {
135
+ store.setState(task.id, 'unknown', null, `Interrupted during execution: ${plan.reason.message}`.slice(0, 1000));
136
+ states.setRecovery(task.id, { status: plan.status, reason: plan.reason, attempt, checkpoint: plan.checkpoint });
137
+ }
138
+ else if (plan.outcome === 'ready' || plan.outcome === 'reconciling')
139
+ states.setRecovery(task.id, { status: plan.outcome, reason: plan.reason, attempt, checkpoint: plan.checkpoint });
140
+ store.append(task.id, 'recovery_planned', { status: plan.outcome === 'held' ? plan.status : plan.outcome === 'ready' || plan.outcome === 'reconciling' ? plan.outcome : 'resolved',
141
+ outcome: plan.outcome === 'held' ? 'unknown' : plan.outcome === 'ready' || plan.outcome === 'reconciling' ? 'running' : plan.outcome, reason: plan.reason, attempt });
142
+ })();
143
+ }
144
+ /**
145
+ * Plan every task that was `running`. Returns the ids left running for
146
+ * resumption and the ids held as `unknown`.
147
+ */
148
+ export function planRecovery(store, options = {}) {
149
+ const now = options.now ?? Date.now();
150
+ const running = store.db.prepare("SELECT * FROM tasks WHERE state='running' ORDER BY created_ms").all().map(row => store.parseTask(row));
151
+ const outcome = { resumed: [], held: [] };
152
+ for (const task of running) {
153
+ let state;
154
+ try {
155
+ state = store.executionState.get(task.id);
156
+ }
157
+ catch {
158
+ state = undefined;
159
+ }
160
+ const plan = planTask(store, task, options, now);
161
+ applyPlan(store, task, plan, interruptedAttempt(state, store.executionState.recovery(task.id)));
162
+ if (plan.outcome === 'ready' || plan.outcome === 'reconciling')
163
+ outcome.resumed.push(task.id);
164
+ else if (plan.outcome === 'held')
165
+ outcome.held.push(task.id);
166
+ }
167
+ return outcome;
168
+ }
169
+ /**
170
+ * Re-check a `reconciling` task whose calls still need a tool check, now that
171
+ * its tools are known. Holds it when a call cannot be proven.
172
+ */
173
+ export function refinePlan(store, task, toolFor, enabled) {
174
+ const row = store.executionState.recovery(task.id);
175
+ if (task.state !== 'running' || !row || row.reason.code !== 'TOOL_CHECK_PENDING')
176
+ return 'unchanged';
177
+ let state;
178
+ try {
179
+ state = store.executionState.get(task.id);
180
+ }
181
+ catch {
182
+ state = undefined;
183
+ }
184
+ const plan = planTask(store, task, { enabled, toolFor: (_task, name) => toolFor(name) }, Date.now());
185
+ applyPlan(store, task, plan, interruptedAttempt(state, row));
186
+ return plan.outcome === 'held' ? 'held' : plan.outcome === 'ready' || plan.outcome === 'reconciling' ? plan.outcome : 'held';
187
+ }
188
+ /** Whether a continuation can be seeded from the task's checkpoint. */
189
+ export function continuable(store, task) {
190
+ if (task.backend !== 'llamacpp' || task.context === 'preview')
191
+ return false;
192
+ try {
193
+ return store.executionState.get(task.id) !== undefined;
194
+ }
195
+ catch {
196
+ return false;
197
+ }
198
+ }
199
+ /** The decisions valid now for a recovery. Only `awaiting_decision` takes a decision. */
200
+ export function validActions(store, task, row, now = Date.now()) {
201
+ if (row.status !== 'awaiting_decision' || task.state !== 'unknown')
202
+ return [];
203
+ if (row.reason.code === 'CANCELLED_WITH_UNSETTLED_EFFECT')
204
+ return ['mark_applied', 'mark_not_applied', 'abandon'];
205
+ if (!continuable(store, task))
206
+ return ['abandon'];
207
+ return [...(task.deadline_ms > now ? ['mark_applied', 'mark_not_applied'] : []), 'retry_with_new_deadline', 'abandon'];
208
+ }
209
+ /** The C3 recovery object of a task, when it was ever interrupted. */
210
+ export function recoveryView(store, task, row = store.executionState.recovery(task.id), now = Date.now()) {
211
+ if (!row)
212
+ return undefined;
213
+ return { status: row.status, reason: row.reason, attempt: row.attempt, ...(row.checkpoint ? { checkpoint: row.checkpoint } : {}),
214
+ actions: validActions(store, task, row, now), ...(row.continuation_task_id ? { continuation_task_id: row.continuation_task_id } : {}),
215
+ ...(row.decided ? { decided: row.decided } : {}) };
216
+ }
@@ -66,9 +66,9 @@ export declare const ResearchBriefSchema: z.ZodObject<{
66
66
  unknown: "unknown";
67
67
  failed: "failed";
68
68
  completed: "completed";
69
+ cancelled: "cancelled";
69
70
  input_required: "input_required";
70
71
  partial: "partial";
71
- cancelled: "cancelled";
72
72
  blocked: "blocked";
73
73
  }>;
74
74
  summary: z.ZodString;
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Ardent's retry policy model, built on the shared HiveCommon retry helpers.
3
+ *
4
+ * Every retry site names one policy below. A failed attempt is repeated only when the failure
5
+ * is transient (a transport error, or 408/425/429/5xx), no response byte was consumed, the
6
+ * caller states the operation has no effect or is idempotent by contract, the peer did not say
7
+ * it already retried (`x-hive-retry: exhausted`), the next attempt starts before the deadline,
8
+ * and the caller has not cancelled. Codex turns and tools with a possible external effect are
9
+ * never retried: their policy is `never`, and an unknown effect is refused before any wait.
10
+ */
11
+ import { RetryExhaustedError, type RetryPolicy, type RetrySignal } from '@hivemagnus/hive-common/retry';
12
+ export { RETRY_HEADER } from '@hivemagnus/hive-common/retry';
13
+ /** Named policies. Delays are before jitter; `equal` jitter waits a random time in [d/2, d]. */
14
+ export declare const RETRY_POLICIES: {
15
+ /** llama.cpp `complete` and `countInputTokens`: before any response byte is consumed. */
16
+ readonly llamacpp: {
17
+ readonly maxAttempts: 3;
18
+ readonly baseMs: 250;
19
+ readonly maxMs: 4000;
20
+ readonly jitter: "equal";
21
+ readonly maxRetryAfterMs: 10000;
22
+ };
23
+ /** A2A reads: Agent Card, Hermes team card, `getTask`, `listTasks`, extended card. */
24
+ readonly a2a_read: {
25
+ readonly maxAttempts: 3;
26
+ readonly baseMs: 500;
27
+ readonly maxMs: 5000;
28
+ readonly jitter: "equal";
29
+ readonly maxRetryAfterMs: 10000;
30
+ };
31
+ /** A2A `SendMessage`, repeated only with the same `messageId` (the peer deduplicates on it). */
32
+ readonly a2a_send: {
33
+ readonly maxAttempts: 3;
34
+ readonly baseMs: 500;
35
+ readonly maxMs: 5000;
36
+ readonly jitter: "equal";
37
+ readonly maxRetryAfterMs: 10000;
38
+ };
39
+ /** A2A push delivery: the site clamps `Retry-After` to 1–5 s, the existing bound. */
40
+ readonly a2a_push: {
41
+ readonly maxAttempts: 3;
42
+ readonly baseMs: 1000;
43
+ readonly maxMs: 1000;
44
+ readonly jitter: "none";
45
+ readonly maxRetryAfterMs: 5000;
46
+ };
47
+ /** Telegram Bot API: 429 with `retry_after`, which the site caps at 60 s, the existing bound. */
48
+ readonly telegram: {
49
+ readonly maxAttempts: 4;
50
+ readonly baseMs: 1000;
51
+ readonly maxMs: 1000;
52
+ readonly jitter: "none";
53
+ readonly maxRetryAfterMs: 60000;
54
+ };
55
+ /** Mattermost/ChatterMost REST: only 429 (the request was not processed), `Retry-After` up to 60 s. */
56
+ readonly mattermost: {
57
+ readonly maxAttempts: 3;
58
+ readonly baseMs: 1000;
59
+ readonly maxMs: 1000;
60
+ readonly jitter: "none";
61
+ readonly maxRetryAfterMs: 60000;
62
+ };
63
+ /**
64
+ * Artifact transfer pulls. Each attempt resumes from the bytes already retained (Range and
65
+ * If-Range against the declared digest), so a stream that failed mid-way is continued, not replayed.
66
+ */
67
+ readonly artifact_transfer: {
68
+ readonly maxAttempts: 5;
69
+ readonly baseMs: 500;
70
+ readonly maxMs: 8000;
71
+ readonly jitter: "equal";
72
+ readonly maxRetryAfterMs: 30000;
73
+ };
74
+ /** Codex turns, tools with a possible effect, partially consumed streams. */
75
+ readonly never: {
76
+ readonly maxAttempts: 1;
77
+ readonly baseMs: 0;
78
+ readonly maxMs: 0;
79
+ readonly jitter: "none";
80
+ };
81
+ };
82
+ export type RetryPolicyName = keyof typeof RETRY_POLICIES;
83
+ /** What a site knows about one failed attempt. */
84
+ export type AttemptFailure = {
85
+ /** The HTTP status, when a response arrived. */
86
+ status?: number | undefined;
87
+ /** The request failed before any response (connection refused, reset, DNS). */
88
+ network?: boolean | undefined;
89
+ /** Response bytes already consumed or forwarded. Any consumed byte ends retrying. */
90
+ bytesConsumed?: number | undefined;
91
+ /** A wait the peer asked for, in milliseconds. */
92
+ retryAfterMs?: number | undefined;
93
+ /** The peer's `x-hive-retry` signal. `exhausted` ends retrying: the lower layer already retried. */
94
+ signal?: RetrySignal | undefined;
95
+ };
96
+ /** Thrown by an attempt to describe its failure to `retryWithPolicy`. */
97
+ export declare class AttemptError extends Error {
98
+ readonly failure: AttemptFailure;
99
+ constructor(message: string, failure: AttemptFailure, options?: ErrorOptions);
100
+ }
101
+ export type RetryStopCode = 'RETRY_EXHAUSTED' | 'RETRY_DEADLINE' | 'RETRY_AFTER_TOO_LONG';
102
+ /** Thrown when retrying stops on a retryable failure. The last attempt's error is the `cause`. */
103
+ export declare class RetryStoppedError extends RetryExhaustedError {
104
+ readonly code: RetryStopCode;
105
+ constructor(attempts: number, code: RetryStopCode, cause: unknown);
106
+ }
107
+ /** The last attempt's error, for sites that keep their established error types. */
108
+ export declare function lastAttemptError(error: unknown): unknown;
109
+ /** One failed attempt, reported through `onAttempt`. */
110
+ export type RetryAttemptRecord = {
111
+ attempt: number;
112
+ /** `http_<status>`, `network`, `peer_exhausted`, `unknown_effect`, `bytes_consumed` or `permanent`. */
113
+ reason: string;
114
+ /** The wait before the next attempt, or null when this attempt was the last. */
115
+ delayMs: number | null;
116
+ /** Why retrying stopped on a retryable failure. */
117
+ stop?: RetryStopCode;
118
+ };
119
+ export type RetryWithPolicyOptions = {
120
+ signal?: AbortSignal | undefined;
121
+ /** Absolute epoch-ms deadline. No attempt starts at or after it. */
122
+ deadlineMs?: number | undefined;
123
+ /** `none` (no effect, or a read), `idempotent` (safe to repeat by contract) or `unknown` (never repeated). */
124
+ effect: 'none' | 'idempotent' | 'unknown';
125
+ onAttempt?: ((record: RetryAttemptRecord) => void) | undefined;
126
+ /** Describe a thrown error that is not an `AttemptError`. Undefined: permanent. */
127
+ classify?: ((error: unknown) => AttemptFailure | undefined) | undefined;
128
+ now?: (() => number) | undefined;
129
+ random?: (() => number) | undefined;
130
+ };
131
+ /**
132
+ * Run `operation` under the named policy. A permanent failure rethrows its own error; stopping on
133
+ * a retryable one throws `RetryStoppedError` (`RETRY_EXHAUSTED`, `RETRY_DEADLINE` or
134
+ * `RETRY_AFTER_TOO_LONG`). Cancellation, including during a backoff wait, ends at once.
135
+ */
136
+ export declare function retryWithPolicy<T>(name: RetryPolicyName | RetryPolicy, operation: (attempt: number) => Promise<T>, options: RetryWithPolicyOptions): Promise<T>;
137
+ /** A failure from a non-2xx response: status, `Retry-After` (seconds or HTTP date) and `x-hive-retry`. */
138
+ export declare function responseFailure(response: Pick<Response, 'status' | 'headers'>, now?: () => number): AttemptFailure;
139
+ /**
140
+ * Whether a rejected `fetch` failed in transport (undici reports `TypeError: fetch failed`).
141
+ * Timeouts and aborts are not transport failures: a timed-out request is not repeated.
142
+ */
143
+ export declare function isTransportError(error: unknown): boolean;
package/dist/retry.js ADDED
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Ardent's retry policy model, built on the shared HiveCommon retry helpers.
3
+ *
4
+ * Every retry site names one policy below. A failed attempt is repeated only when the failure
5
+ * is transient (a transport error, or 408/425/429/5xx), no response byte was consumed, the
6
+ * caller states the operation has no effect or is idempotent by contract, the peer did not say
7
+ * it already retried (`x-hive-retry: exhausted`), the next attempt starts before the deadline,
8
+ * and the caller has not cancelled. Codex turns and tools with a possible external effect are
9
+ * never retried: their policy is `never`, and an unknown effect is refused before any wait.
10
+ */
11
+ import { backoffDelay, classifyRetry, readRetrySignal, retryAfterFromHeaders, RetryExhaustedError, sleepAbortable, } from '@hivemagnus/hive-common/retry';
12
+ export { RETRY_HEADER } from '@hivemagnus/hive-common/retry';
13
+ /** Named policies. Delays are before jitter; `equal` jitter waits a random time in [d/2, d]. */
14
+ export const RETRY_POLICIES = {
15
+ /** llama.cpp `complete` and `countInputTokens`: before any response byte is consumed. */
16
+ llamacpp: { maxAttempts: 3, baseMs: 250, maxMs: 4000, jitter: 'equal', maxRetryAfterMs: 10_000 },
17
+ /** A2A reads: Agent Card, Hermes team card, `getTask`, `listTasks`, extended card. */
18
+ a2a_read: { maxAttempts: 3, baseMs: 500, maxMs: 5000, jitter: 'equal', maxRetryAfterMs: 10_000 },
19
+ /** A2A `SendMessage`, repeated only with the same `messageId` (the peer deduplicates on it). */
20
+ a2a_send: { maxAttempts: 3, baseMs: 500, maxMs: 5000, jitter: 'equal', maxRetryAfterMs: 10_000 },
21
+ /** A2A push delivery: the site clamps `Retry-After` to 1–5 s, the existing bound. */
22
+ a2a_push: { maxAttempts: 3, baseMs: 1000, maxMs: 1000, jitter: 'none', maxRetryAfterMs: 5000 },
23
+ /** Telegram Bot API: 429 with `retry_after`, which the site caps at 60 s, the existing bound. */
24
+ telegram: { maxAttempts: 4, baseMs: 1000, maxMs: 1000, jitter: 'none', maxRetryAfterMs: 60_000 },
25
+ /** Mattermost/ChatterMost REST: only 429 (the request was not processed), `Retry-After` up to 60 s. */
26
+ mattermost: { maxAttempts: 3, baseMs: 1000, maxMs: 1000, jitter: 'none', maxRetryAfterMs: 60_000 },
27
+ /**
28
+ * Artifact transfer pulls. Each attempt resumes from the bytes already retained (Range and
29
+ * If-Range against the declared digest), so a stream that failed mid-way is continued, not replayed.
30
+ */
31
+ artifact_transfer: { maxAttempts: 5, baseMs: 500, maxMs: 8000, jitter: 'equal', maxRetryAfterMs: 30_000 },
32
+ /** Codex turns, tools with a possible effect, partially consumed streams. */
33
+ never: { maxAttempts: 1, baseMs: 0, maxMs: 0, jitter: 'none' },
34
+ };
35
+ /** Thrown by an attempt to describe its failure to `retryWithPolicy`. */
36
+ export class AttemptError extends Error {
37
+ failure;
38
+ constructor(message, failure, options) {
39
+ super(message, options);
40
+ this.failure = failure;
41
+ }
42
+ }
43
+ /** Thrown when retrying stops on a retryable failure. The last attempt's error is the `cause`. */
44
+ export class RetryStoppedError extends RetryExhaustedError {
45
+ code;
46
+ constructor(attempts, code, cause) {
47
+ super(attempts, code, cause);
48
+ this.code = code;
49
+ this.message = `${cause instanceof Error ? cause.message : 'Attempt failed'} (${code} after ${attempts} attempt${attempts === 1 ? '' : 's'})`;
50
+ }
51
+ }
52
+ /** The last attempt's error, for sites that keep their established error types. */
53
+ export function lastAttemptError(error) {
54
+ return error instanceof RetryStoppedError ? error.cause : error;
55
+ }
56
+ function reasonOf(failure) {
57
+ if (failure.signal === 'exhausted')
58
+ return 'peer_exhausted';
59
+ if ((failure.bytesConsumed ?? 0) > 0)
60
+ return 'bytes_consumed';
61
+ if (failure.network)
62
+ return 'network';
63
+ return failure.status === undefined ? 'permanent' : `http_${failure.status}`;
64
+ }
65
+ /**
66
+ * Run `operation` under the named policy. A permanent failure rethrows its own error; stopping on
67
+ * a retryable one throws `RetryStoppedError` (`RETRY_EXHAUSTED`, `RETRY_DEADLINE` or
68
+ * `RETRY_AFTER_TOO_LONG`). Cancellation, including during a backoff wait, ends at once.
69
+ */
70
+ export async function retryWithPolicy(name, operation, options) {
71
+ const policy = typeof name === 'string' ? RETRY_POLICIES[name] : name;
72
+ const now = options.now ?? Date.now;
73
+ for (let attempt = 1;; attempt++) {
74
+ // An aborted signal rejects at once with its reason.
75
+ if (options.signal?.aborted)
76
+ await sleepAbortable(0, options.signal);
77
+ try {
78
+ return await operation(attempt);
79
+ }
80
+ catch (error) {
81
+ if (options.signal?.aborted)
82
+ throw error;
83
+ const failure = error instanceof AttemptError ? error.failure : options.classify?.(error);
84
+ if (!failure) {
85
+ options.onAttempt?.({ attempt, reason: 'permanent', delayMs: null });
86
+ throw error;
87
+ }
88
+ const category = failure.signal === 'exhausted' ? 'permanent' : classifyRetry({ ...failure, effect: options.effect });
89
+ const reason = category === 'unknown_effect' ? 'unknown_effect' : reasonOf(failure);
90
+ if (category !== 'retryable') {
91
+ options.onAttempt?.({ attempt, reason, delayMs: null });
92
+ throw error;
93
+ }
94
+ let stop;
95
+ let delay = null;
96
+ if (attempt >= policy.maxAttempts)
97
+ stop = 'RETRY_EXHAUSTED';
98
+ else if (failure.retryAfterMs !== undefined && failure.retryAfterMs > (policy.maxRetryAfterMs ?? Number.POSITIVE_INFINITY))
99
+ stop = 'RETRY_AFTER_TOO_LONG';
100
+ else {
101
+ delay = backoffDelay(attempt, policy, { retryAfterMs: failure.retryAfterMs, deadlineMs: options.deadlineMs, now,
102
+ ...(options.random ? { random: options.random } : {}) });
103
+ if (delay === null)
104
+ stop = 'RETRY_DEADLINE';
105
+ }
106
+ options.onAttempt?.({ attempt, reason, delayMs: delay, ...(stop ? { stop } : {}) });
107
+ if (stop || delay === null)
108
+ throw new RetryStoppedError(attempt, stop ?? 'RETRY_DEADLINE', error);
109
+ await sleepAbortable(delay, options.signal);
110
+ }
111
+ }
112
+ }
113
+ /** A failure from a non-2xx response: status, `Retry-After` (seconds or HTTP date) and `x-hive-retry`. */
114
+ export function responseFailure(response, now) {
115
+ return { status: response.status, retryAfterMs: retryAfterFromHeaders(response.headers, now), signal: readRetrySignal(response.headers) };
116
+ }
117
+ /**
118
+ * Whether a rejected `fetch` failed in transport (undici reports `TypeError: fetch failed`).
119
+ * Timeouts and aborts are not transport failures: a timed-out request is not repeated.
120
+ */
121
+ export function isTransportError(error) {
122
+ if (!(error instanceof Error))
123
+ return false;
124
+ if (error.name === 'AbortError' || error.name === 'TimeoutError')
125
+ return false;
126
+ return error instanceof TypeError;
127
+ }
package/dist/runtime.d.ts CHANGED
@@ -3,6 +3,7 @@ import { ArtifactStore } from './artifacts.js';
3
3
  import { type ResearchBrief } from './research.js';
4
4
  import { TaskStore, type Task, type TaskContext } from './store.js';
5
5
  import { ToolRegistry } from './tools.js';
6
+ import { type RecoveryDecisionInput, type RecoveryView } from './recovery.js';
6
7
  import { TeamEnvelope, TeamResult } from './team-contract.js';
7
8
  import { type ArdentPlugin } from './plugins.js';
8
9
  import { LiveTextHub } from './live-text.js';
@@ -10,6 +11,7 @@ import { ArtifactManifests } from './artifact-manifests.js';
10
11
  import { DevelopmentRecords } from './development.js';
11
12
  import { type PreviewSubmit } from './preview.js';
12
13
  import { type MissionSubmit } from './missions.js';
14
+ import { type ExecutionAcceptance, type ExecutionContext } from './execution.js';
13
15
  /** A finished task. A mission also carries its validated TeamResult, which is the task's stored result. */
14
16
  export type RunResult = {
15
17
  task: Task;
@@ -31,6 +33,12 @@ export type TaskEvidence = {
31
33
  artifactIds: Set<string>;
32
34
  researchAttempted: boolean;
33
35
  };
36
+ /** A resuming task was held as `unknown`; its recovery status says why. */
37
+ export declare class RecoveryHeldError extends Error {
38
+ }
39
+ /** A recovery decision that is not valid now (HTTP 409). */
40
+ export declare class RecoveryConflictError extends Error {
41
+ }
34
42
  export declare class ArdentRuntime {
35
43
  #private;
36
44
  readonly profileDir: string;
@@ -44,12 +52,17 @@ export declare class ArdentRuntime {
44
52
  readonly tools: ToolRegistry;
45
53
  /** Visible reply text of running tasks, for live clients. Never journaled. */
46
54
  readonly liveText: LiveTextHub;
55
+ /** Startup recovery: queued tasks, tasks interrupted while running, and of those the ids left running to resume or held as `unknown`. */
47
56
  readonly recovered: {
48
57
  queued: Task[];
49
58
  interrupted: number;
59
+ resumed: string[];
60
+ held: string[];
50
61
  };
51
62
  get draining(): boolean;
52
63
  get plugins(): readonly ArdentPlugin[];
64
+ /** The instance part of this runtime's qualified references (`ARDENT_INSTANCE_REF`, else `local.<profile>`). */
65
+ readonly instanceRef: string;
53
66
  constructor(profileDir: string, config: ArdentConfig, env?: NodeJS.ProcessEnv);
54
67
  /** Install plugins once, before the runtime accepts work. Plugin tools join the shared registry. */
55
68
  usePlugins(plugins: readonly ArdentPlugin[], env?: NodeJS.ProcessEnv): Promise<void>;
@@ -57,15 +70,46 @@ export declare class ArdentRuntime {
57
70
  startPlugins(env?: NodeJS.ProcessEnv): Promise<void>;
58
71
  close(): void;
59
72
  drain(timeoutMs?: number): Promise<boolean>;
60
- accept(prompt: string, caller?: string, context?: TaskContext, idempotencyKey?: string, sessionId?: string, originalDeadlineMs?: number, backendOverride?: 'llamacpp' | 'codex'): Task;
61
- /** Accept a team mission as a `mission` task. Its tools come from `mission.resources`. */
62
- acceptMission(input: MissionSubmit, caller?: string): Task;
73
+ /**
74
+ * Accept a task. `execution` carries the caller's execution context, if any;
75
+ * an invalid or absent one becomes a root minted for this task. It is
76
+ * attribution only and does not enter the idempotency digest.
77
+ */
78
+ accept(prompt: string, caller?: string, context?: TaskContext, idempotencyKey?: string, sessionId?: string, originalDeadlineMs?: number, backendOverride?: 'llamacpp' | 'codex', execution?: ExecutionAcceptance): Task;
79
+ /** The execution context a task was accepted with, if any. Attribution only; for provenance and lineage. */
80
+ executionFor(taskId: string): ExecutionContext | undefined;
81
+ /**
82
+ * Accept a team mission as a `mission` task. Its tools come from `mission.resources`.
83
+ * `execution` defaults to the submission's own `execution` field.
84
+ */
85
+ acceptMission(input: MissionSubmit, caller?: string, execution?: ExecutionAcceptance): Task;
63
86
  /**
64
87
  * Accept a preview task: a direct-style task that tries unsaved soul, identity,
65
88
  * skill or model changes. It never writes memory, development records or the
66
89
  * profile, has only read tools, and its artifacts expire after 24 hours.
67
90
  */
68
- acceptPreview(input: PreviewSubmit, caller?: string): Task;
91
+ acceptPreview(input: PreviewSubmit, caller?: string, execution?: ExecutionAcceptance): Task;
92
+ /**
93
+ * Be told when a task run by this runtime settles, or when an operator
94
+ * decides a held task. Channel adapters and the A2A surface use it to deliver
95
+ * the outcome of resumed and continued tasks. Returns an unsubscribe function.
96
+ */
97
+ onTaskSettled(listener: (taskId: string) => void): () => void;
98
+ /** The recovery object (C3) of a task interrupted by a crash or restart; undefined for one never interrupted. */
99
+ recoveryFor(taskId: string): RecoveryView | undefined;
100
+ /**
101
+ * Apply an operator decision to a task held `awaiting_decision`. A held task
102
+ * is `unknown`, which is terminal, so `mark_applied`, `mark_not_applied` and
103
+ * `retry_with_new_deadline` continue the work as a linked continuation task
104
+ * seeded from the checkpoint, with the pending call settled as the operator
105
+ * decided (or, for a retry, dispatched again under its idempotency key);
106
+ * `abandon` only records the decision. Idempotent per task, attempt and
107
+ * action: repeating a decision returns the same outcome.
108
+ */
109
+ decideRecovery(taskId: string, input: RecoveryDecisionInput, env?: NodeJS.ProcessEnv, by?: string): Promise<{
110
+ recovery: RecoveryView;
111
+ continuation?: Task;
112
+ }>;
69
113
  cancel(id: string): Task;
70
114
  /**
71
115
  * Pause a queued or running task. A queued task does not start; a running one
@@ -82,6 +126,14 @@ export declare class ArdentRuntime {
82
126
  admission: 'open' | 'paused';
83
127
  };
84
128
  run(taskId: string, env?: NodeJS.ProcessEnv, onText?: (chunk: string, step: number) => void): Promise<RunResult>;
129
+ /**
130
+ * Resume the tasks startup recovery left `running` (`ready` or
131
+ * `reconciling`), ahead of queued work and subject to per-caller fairness.
132
+ * Call it once plugins are installed and before queued tasks run: calls that
133
+ * still need a tool check are checked against the task's tools first, and a
134
+ * call that cannot be proven holds its task. Returns the ids resumed.
135
+ */
136
+ resumeRecovered(env?: NodeJS.ProcessEnv): Promise<string[]>;
85
137
  decodeTeamEnvelope(value: unknown): TeamEnvelope;
86
138
  assertTeamEnvelopeAdmission(envelope: TeamEnvelope, wire: unknown, env: NodeJS.ProcessEnv): void;
87
139
  }