@hivemagnus/ardent 3.3.0 → 3.4.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 (48) hide show
  1. package/README.md +10 -973
  2. package/dist/a2a-client.js +3 -2
  3. package/dist/a2a-peers.d.ts +26 -0
  4. package/dist/a2a-peers.js +60 -18
  5. package/dist/a2a-push.d.ts +3 -1
  6. package/dist/a2a-push.js +5 -1
  7. package/dist/a2a-rate-limit.d.ts +3 -3
  8. package/dist/a2a-rate-limit.js +6 -3
  9. package/dist/a2a-server.d.ts +13 -1
  10. package/dist/a2a-server.js +20 -11
  11. package/dist/api.d.ts +10 -0
  12. package/dist/api.js +296 -127
  13. package/dist/artifact-transfer.js +3 -2
  14. package/dist/channel-catchup.d.ts +2 -2
  15. package/dist/channels.d.ts +6 -6
  16. package/dist/channels.js +4 -1
  17. package/dist/cli.js +55 -3
  18. package/dist/config.d.ts +9 -1
  19. package/dist/config.js +15 -6
  20. package/dist/development.d.ts +3 -3
  21. package/dist/development.js +2 -1
  22. package/dist/errors.d.ts +54 -0
  23. package/dist/errors.js +76 -0
  24. package/dist/identity.js +11 -6
  25. package/dist/job-engine.d.ts +3 -0
  26. package/dist/job-engine.js +5 -0
  27. package/dist/journal.d.ts +17 -2
  28. package/dist/journal.js +48 -4
  29. package/dist/log.d.ts +5 -1
  30. package/dist/log.js +6 -2
  31. package/dist/mattermost.js +7 -2
  32. package/dist/memory.js +3 -2
  33. package/dist/metrics.d.ts +34 -0
  34. package/dist/metrics.js +73 -0
  35. package/dist/missions.js +2 -1
  36. package/dist/plugin-http.js +10 -1
  37. package/dist/plugin-sdk.d.ts +2 -0
  38. package/dist/plugin-sdk.js +2 -0
  39. package/dist/retention.d.ts +64 -0
  40. package/dist/retention.js +239 -0
  41. package/dist/runtime.d.ts +17 -1
  42. package/dist/runtime.js +52 -15
  43. package/dist/skills.js +5 -4
  44. package/dist/store.d.ts +28 -0
  45. package/dist/store.js +97 -14
  46. package/dist/telegram.js +5 -1
  47. package/package.json +2 -2
  48. package/profiles/assistant/config.yaml +1 -1
package/dist/journal.js CHANGED
@@ -25,6 +25,13 @@ import Database from './sqlite.js';
25
25
  * when a consumer would need to read the policy or status differently; adding
26
26
  * a table or a state value does not change it.
27
27
  */
28
+ /**
29
+ * Mattermost history claimed on a channel's first sight, never to be answered (it has no channel
30
+ * type: live and catch-up posts always record one). Such a row is finished, not admitted work.
31
+ */
32
+ /** task_recovery statuses: `active` ones count only while their task is running. */
33
+ export const TASK_RECOVERY_STATUSES = Object.freeze({ active: ['ready', 'reconciling'], uncertain: ['awaiting_decision', 'unsupported', 'unknown'], terminal: ['resumed', 'resolved'] });
34
+ export const SEEDED_INBOUND = "(inbound.platform='mattermost' AND inbound.channel_type='unknown')";
28
35
  export const JOURNAL_POLICY_VERSION = 1;
29
36
  const state = (column, active, uncertain, terminal, description) => ({ kind: 'state', column, active, uncertain, terminal, description });
30
37
  const passive = (description) => ({ kind: 'passive', description });
@@ -42,7 +49,8 @@ export const JOURNAL_TABLES = Object.freeze({
42
49
  description: 'The one-way rollback fence. Any row is unsupported: a temporary snapshot must never clear it.' },
43
50
  // Ardent 3.2.0 execution recovery.
44
51
  tool_invocations: state('state', ['dispatched'], ['failed_unknown', 'unknown'], ['succeeded', 'failed_no_effect', 'reconciled_applied', 'reconciled_not_applied', 'operator_applied', 'operator_not_applied', 'not_dispatched'], 'Tool calls with a possible effect. A dispatched call is in flight; an uncertain one needs reconciliation.'),
45
- task_recovery: state('status', ['ready', 'reconciling'], ['awaiting_decision', 'unsupported', 'unknown'], ['resumed', 'resolved'], 'Execution recovery decisions for interrupted tasks.'),
52
+ task_recovery: { kind: 'special', rule: 'task_recovery',
53
+ description: 'Execution recovery decisions for interrupted tasks. A ready or reconciling row is active only while its task is running; awaiting_decision, unsupported and unknown rows are uncertain; resumed and resolved rows are finished.' },
46
54
  artifact_transfers: state('state', ['queued', 'transferring', 'verifying'], ['unknown'], ['completed', 'failed'], 'Resumable peer artifact imports.'),
47
55
  // A2A.
48
56
  a2a_tasks: { kind: 'special', rule: 'a2a_tasks',
@@ -50,7 +58,8 @@ export const JOURNAL_TABLES = Object.freeze({
50
58
  a2a_request_receipts: { kind: 'special', rule: 'a2a_request_receipts',
51
59
  description: 'A2A request idempotency receipts. A receipt not yet bound to a task is active.' },
52
60
  a2a_push_deliveries: state('state', ['queued'], ['unknown'], ['sent', 'failed'], 'A2A push notifications recorded before they are sent.'),
53
- a2a_outbound_calls: state('state', ['pending', 'bound'], ['unknown'], ['failed'], 'Outbound A2A calls awaiting the peer\'s push callbacks.'),
61
+ // A bound call was accepted by the peer; its push callbacks are received whenever they come.
62
+ a2a_outbound_calls: state('state', ['pending'], ['unknown'], ['bound', 'failed'], 'Outbound A2A calls. A pending call is being sent; a bound call has its peer task and only receives callbacks.'),
54
63
  a2a_team_artifacts: state('status', [], ['unknown'], ['available', 'revoked'], 'Artifacts this profile exports to team peers.'),
55
64
  a2a_team_artifact_transfers: state('status', [], ['unknown'], ['complete'], 'Team artifacts received from peers.'),
56
65
  a2a_team_child_claims: { kind: 'special', rule: 'a2a_team_child_claims',
@@ -263,7 +272,38 @@ function inspectOpen(db) {
263
272
  result.active += count(`SELECT count(*) AS count FROM channel_inbound AS inbound
264
273
  LEFT JOIN channel_deliveries AS delivery ON delivery.platform=inbound.platform
265
274
  AND delivery.account=inbound.account AND delivery.update_id=inbound.update_id
266
- WHERE inbound.task_id IS NULL${columns.has('disposition') ? " AND inbound.disposition='admitted'" : ''} AND (delivery.id IS NULL OR delivery.state IN ('queued','unknown'))`);
275
+ WHERE inbound.task_id IS NULL${columns.has('disposition') ? " AND inbound.disposition='admitted'" : ''}${columns.has('channel_type') ? ` AND NOT ${SEEDED_INBOUND}` : ''}
276
+ AND (delivery.id IS NULL OR delivery.state IN ('queued','unknown'))`);
277
+ break;
278
+ }
279
+ case 'task_recovery': {
280
+ if (columns.has('state')) {
281
+ unsupported('unexpected state column');
282
+ break;
283
+ }
284
+ if (missing('status', 'task_id'))
285
+ break;
286
+ if (!names.has('tasks')) {
287
+ unsupported('tasks table is missing');
288
+ break;
289
+ }
290
+ for (const entry of db.prepare(`SELECT r.status AS value, t.state AS task_state, count(*) AS count FROM task_recovery r
291
+ LEFT JOIN tasks t ON t.id=r.task_id GROUP BY r.status, t.state`).all()) {
292
+ const group = z.object({ value: z.unknown(), task_state: z.unknown(), count: z.number().int() }).parse(entry);
293
+ const value = typeof group.value === 'string' ? group.value : null;
294
+ const is = (list) => value !== null && list.includes(value);
295
+ if (is(TASK_RECOVERY_STATUSES.terminal))
296
+ continue;
297
+ if (is(TASK_RECOVERY_STATUSES.uncertain))
298
+ result.unknown += group.count;
299
+ // A ready or reconciling plan whose task no longer runs was settled another way: nothing resumes it.
300
+ else if (is(TASK_RECOVERY_STATUSES.active)) {
301
+ if (group.task_state === 'running')
302
+ result.active += group.count;
303
+ }
304
+ else
305
+ unsupported(`unrecognized status ${JSON.stringify(group.value)}`, group.count || 1);
306
+ }
267
307
  break;
268
308
  }
269
309
  }
@@ -317,7 +357,11 @@ async function regularFile(path, optional = false) {
317
357
  * of it. The database and its WAL are copied to a private directory, verified
318
358
  * by digest, and inspected there, so committed but uncheckpointed work in the
319
359
  * WAL is counted. Throws when the files change during inspection, which means
320
- * a gateway is writing: a running profile is never idle.
360
+ * a gateway is writing. It does not check the gateway lock: an idle gateway
361
+ * that writes nothing during the copy can be reported idle, so stop the
362
+ * profile (or hold its gateway lock) before relying on `idle` for a snapshot.
363
+ * Tables an extension created and this policy does not classify count as
364
+ * `unsupported`, so such a profile is never reported idle.
321
365
  */
322
366
  export async function inspectJournal(path) {
323
367
  await regularFile(path);
package/dist/log.d.ts CHANGED
@@ -4,4 +4,8 @@ export type { Logger } from '@hivemagnus/hive-common/log';
4
4
  * Operational log lines: JSON, secrets redacted, written to stderr so stdout
5
5
  * stays the CLI's machine-readable output. `LOG_LEVEL` sets the minimum level.
6
6
  */
7
- export declare function ardentLogger(): Logger;
7
+ export declare function ardentLogger(options?: {
8
+ requestContext?: boolean;
9
+ }): Logger;
10
+ /** A logger that writes nothing: the default of a runtime or component nobody gave a logger. */
11
+ export declare const silentLogger: Logger;
package/dist/log.js CHANGED
@@ -3,6 +3,10 @@ import { createLogger } from '@hivemagnus/hive-common/log';
3
3
  * Operational log lines: JSON, secrets redacted, written to stderr so stdout
4
4
  * stays the CLI's machine-readable output. `LOG_LEVEL` sets the minimum level.
5
5
  */
6
- export function ardentLogger() {
7
- return createLogger({ bindings: { service: 'ardent' }, write: line => { process.stderr.write(`${line}\n`); } });
6
+ export function ardentLogger(options = {}) {
7
+ return createLogger({ bindings: { service: 'ardent' }, write: line => { process.stderr.write(`${line}\n`); },
8
+ // Task work outlives the request that queued it: without the request context, its lines carry their own ids.
9
+ ...(options.requestContext === false ? { context: () => undefined } : {}) });
8
10
  }
11
+ /** A logger that writes nothing: the default of a runtime or component nobody gave a logger. */
12
+ export const silentLogger = createLogger({ level: 'silent' });
@@ -147,6 +147,7 @@ export class MattermostAdapter {
147
147
  const event = { platform: 'mattermost', channel_type: isDm ? 'mattermost_dm' : 'mattermost_channel',
148
148
  account: me.id, user: post.user_id, conversation: post.channel_id, thread: post.root_id || null, update_id: post.id, reply_to: post.id, text, attachments, authorized: true, bot_message: false };
149
149
  const operation = this.#core.handle(event, async (reply) => this.#deliver({ channel_id: post.channel_id, root_id: post.root_id, id: post.id }, channelType, reply)).catch(error => {
150
+ this.runtime.logger.warn('Mattermost post failed', { post_id: post.id, channel_id: post.channel_id, err: error });
150
151
  this.runtime.store.setCursor(`mattermost:${me.id}:last_error`, error instanceof Error ? error.message.slice(0, 500) : 'unknown');
151
152
  });
152
153
  // A live post never moves an existing boundary: posts missed before it are
@@ -284,8 +285,9 @@ export class MattermostAdapter {
284
285
  const posts = await this.#page(channelId, undefined, readSignal);
285
286
  if (signal?.aborted)
286
287
  return 0;
288
+ // Not admitted work: nothing will answer these posts.
287
289
  for (const post of posts)
288
- store.claimInbound('mattermost', me.id, post.id);
290
+ store.claimInbound('mattermost', me.id, post.id, 'unknown', 'skipped_stale');
289
291
  const newest = posts[0];
290
292
  // An empty channel starts at 0: every later post is new, whatever the clocks say.
291
293
  this.#saveBoundary(channelId, newest ? { last_ms: newest.create_at, last_post_id: newest.id } : { last_ms: 0, last_post_id: null });
@@ -515,8 +517,11 @@ export class MattermostAdapter {
515
517
  if (signal.aborted)
516
518
  break;
517
519
  failures++;
518
- if (failures >= 10)
520
+ if (failures >= 10) {
521
+ this.runtime.logger.error('Mattermost connection stopped after 10 failures', { err: error });
519
522
  throw error;
523
+ }
524
+ this.runtime.logger.warn('Mattermost connection failed; reconnecting', { failures, err: error });
520
525
  }
521
526
  if (!signal.aborted)
522
527
  await sleep(Math.min(30_000, 1000 * 2 ** Math.min(failures, 5)), undefined, { signal }).catch(() => { });
package/dist/memory.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { resolveReference } from './config.js';
3
+ import { dependencyUnavailable } from './errors.js';
3
4
  const Memory = z.object({ id: z.string(), agent_id: z.string(), content: z.string(), scope: z.enum(['private', 'shared']), workspace_id: z.string().optional(),
4
5
  created_at: z.string().optional(), metadata: z.object({ project_id: z.string().optional() }).passthrough().optional() }).passthrough();
5
6
  const Search = z.object({ results: z.array(z.object({ memory: Memory, score: z.number().optional(), citation: z.unknown().optional() }).passthrough()) }).passthrough();
@@ -12,12 +13,12 @@ export class HiveMemClient {
12
13
  agentId;
13
14
  constructor(config, env = process.env) {
14
15
  if (config.provider !== 'hivemem')
15
- throw new Error('Memory provider is not configured (memory.provider: none)');
16
+ throw dependencyUnavailable('Memory provider is not configured (memory.provider: none)');
16
17
  const base = resolveReference(config.base_url, env);
17
18
  const workspace = resolveReference(config.workspace_id, env);
18
19
  const token = env[config.token_env];
19
20
  if (!base || !workspace || !token)
20
- throw new Error('HiveMem URL, workspace, or scoped token is unconfigured');
21
+ throw dependencyUnavailable('HiveMem URL, workspace, or scoped token is unconfigured');
21
22
  const url = new URL(base);
22
23
  if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
23
24
  throw new Error('HiveMem URL is invalid');
@@ -0,0 +1,34 @@
1
+ import type { TaskStore } from './store.js';
2
+ /** The OpenMetrics text format's media type. */
3
+ export declare const OPENMETRICS_CONTENT_TYPE = "application/openmetrics-text; version=1.0.0; charset=utf-8";
4
+ type Labels = Readonly<Record<string, string>>;
5
+ /**
6
+ * In-process counters of things the journal does not record, such as A2A
7
+ * rate-limit refusals. They start at zero when the process starts.
8
+ */
9
+ export declare class RuntimeCounters {
10
+ #private;
11
+ increment(name: string, labels?: Labels, by?: number): void;
12
+ value(name: string, labels?: Labels): number;
13
+ series(name: string): Array<{
14
+ labels: Labels;
15
+ value: number;
16
+ }>;
17
+ }
18
+ /** A2A rate-limit refusal scopes: by client address, per peer, and the per-peer task cap. */
19
+ export declare const A2A_REFUSAL_SCOPES: readonly ["ip", "peer", "tasks"];
20
+ export interface MetricsSource {
21
+ readonly version: string;
22
+ readonly profile: string;
23
+ readonly backend: string;
24
+ readonly store: TaskStore;
25
+ readonly counters: RuntimeCounters;
26
+ readonly startedMs: number;
27
+ readonly now?: () => number;
28
+ }
29
+ /**
30
+ * The profile's metrics in the OpenMetrics text format. Gauges are read from
31
+ * the journal at scrape time; counters are this process's own.
32
+ */
33
+ export declare function renderMetrics(source: MetricsSource): string;
34
+ export {};
@@ -0,0 +1,73 @@
1
+ import { z } from 'zod';
2
+ /** The OpenMetrics text format's media type. */
3
+ export const OPENMETRICS_CONTENT_TYPE = 'application/openmetrics-text; version=1.0.0; charset=utf-8';
4
+ const labelKey = (labels) => JSON.stringify(Object.entries(labels).sort(([a], [b]) => a.localeCompare(b)));
5
+ /**
6
+ * In-process counters of things the journal does not record, such as A2A
7
+ * rate-limit refusals. They start at zero when the process starts.
8
+ */
9
+ export class RuntimeCounters {
10
+ #counts = new Map();
11
+ increment(name, labels = {}, by = 1) {
12
+ const series = this.#counts.get(name) ?? new Map();
13
+ const key = labelKey(labels);
14
+ const entry = series.get(key) ?? { labels, value: 0 };
15
+ entry.value += by;
16
+ series.set(key, entry);
17
+ this.#counts.set(name, series);
18
+ }
19
+ value(name, labels = {}) { return this.#counts.get(name)?.get(labelKey(labels))?.value ?? 0; }
20
+ series(name) { return [...this.#counts.get(name)?.values() ?? []]; }
21
+ }
22
+ const escapeLabel = (value) => value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
23
+ const sample = (name, labels, value) => {
24
+ const entries = Object.entries(labels);
25
+ return `${name}${entries.length ? `{${entries.map(([key, label]) => `${key}="${escapeLabel(label)}"`).join(',')}}` : ''} ${Number.isFinite(value) ? value : 0}`;
26
+ };
27
+ /** A2A rate-limit refusal scopes: by client address, per peer, and the per-peer task cap. */
28
+ export const A2A_REFUSAL_SCOPES = ['ip', 'peer', 'tasks'];
29
+ /**
30
+ * The profile's metrics in the OpenMetrics text format. Gauges are read from
31
+ * the journal at scrape time; counters are this process's own.
32
+ */
33
+ export function renderMetrics(source) {
34
+ const now = source.now?.() ?? Date.now();
35
+ const lines = [];
36
+ const family = (name, type, help, samples) => {
37
+ lines.push(`# TYPE ${name} ${type}`, `# HELP ${name} ${help}`);
38
+ for (const item of samples)
39
+ lines.push(sample(`${name}${item.suffix ?? ''}`, item.labels ?? {}, item.value));
40
+ };
41
+ const db = source.store.db;
42
+ const tables = new Set(z.array(z.object({ name: z.string() })).parse(db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all()).map(row => row.name));
43
+ /** Rows per state of a journal table; a table this profile never created (no jobs, no A2A) counts nothing. */
44
+ const counts = (table) => tables.has(table)
45
+ ? z.array(z.object({ key: z.string(), count: z.number().int() })).parse(db.prepare(`SELECT state AS key, count(*) AS count FROM ${table} GROUP BY state`).all()) : [];
46
+ family('ardent_build', 'info', 'Ardent version, profile and selected backend', [{ labels: { version: source.version, profile: source.profile, backend: source.backend }, value: 1, suffix: '_info' }]);
47
+ family('ardent_process_start_time_seconds', 'gauge', 'When this gateway process started (Unix time)', [{ value: source.startedMs / 1000 }]);
48
+ const tasks = source.store.taskCounts();
49
+ const states = ['queued', 'running', 'input_required', 'completed', 'partial', 'failed', 'cancelled', 'unknown'];
50
+ family('ardent_tasks', 'gauge', 'Tasks in the journal, by state', states.map(state => ({ labels: { state }, value: tasks.by_state[state] ?? 0 })));
51
+ const recovery = source.store.executionState.counts();
52
+ family('ardent_recovery_tasks', 'gauge', 'Tasks in each open execution recovery status', Object.entries(recovery).map(([status, value]) => ({ labels: { status }, value })));
53
+ const windows = counts('job_windows');
54
+ family('ardent_job_windows', 'gauge', 'Scheduled job windows in the journal, by state', ['queued', 'running', 'retry', 'completed', 'failed', 'unknown', 'superseded']
55
+ .map(state => ({ labels: { state }, value: windows.find(row => row.key === state)?.count ?? 0 })));
56
+ const deliveries = counts('channel_deliveries');
57
+ family('ardent_channel_deliveries', 'gauge', 'Channel replies in the journal, by delivery state', ['queued', 'sent', 'failed', 'unknown']
58
+ .map(state => ({ labels: { state }, value: deliveries.find(row => row.key === state)?.count ?? 0 })));
59
+ const push = counts('a2a_push_deliveries');
60
+ family('ardent_a2a_push_deliveries', 'gauge', 'A2A push notifications in the journal, by delivery state', ['queued', 'sent', 'failed', 'unknown']
61
+ .map(state => ({ labels: { state }, value: push.find(row => row.key === state)?.count ?? 0 })));
62
+ family('ardent_a2a_rate_limited', 'counter', 'A2A requests refused with 429 since the process started, by limit', A2A_REFUSAL_SCOPES
63
+ .map(scope => ({ labels: { scope }, value: source.counters.value('a2a_rate_limited', { scope }), suffix: '_total' })));
64
+ // Mattermost catch-up: how old each channel's settled boundary and its last finished walk are.
65
+ const catchup = source.store.catchup.status('mattermost');
66
+ const boundaries = new Map((tables.has('channel_cursors') ? z.array(z.object({ key: z.string(), value: z.string() })).parse(db.prepare("SELECT key,value FROM channel_cursors WHERE key LIKE 'mattermost:%:%:last_ms'").all()) : [])
67
+ .map(row => [row.key.split(':').slice(1, 3).join(':'), Number(row.value)]));
68
+ family('ardent_mattermost_catchup_boundary_age_seconds', 'gauge', 'Seconds since the newest Mattermost post up to which every older post is settled, per channel', catchup.flatMap(item => { const at = boundaries.get(`${item.account}:${item.channel}`); return at && Number.isFinite(at) ? [{ labels: { account: item.account, channel: item.channel }, value: Math.max(0, (now - at) / 1000) }] : []; }));
69
+ family('ardent_mattermost_catchup_walk_age_seconds', 'gauge', 'Seconds since the last finished Mattermost catch-up walk, per channel', catchup.flatMap(item => item.finished_ms === null ? [] : [{ labels: { account: item.account, channel: item.channel, state: item.state }, value: Math.max(0, (now - item.finished_ms) / 1000) }]));
70
+ family('ardent_mattermost_catchup_gaps', 'gauge', 'Recorded Mattermost history gaps catch-up could not walk, per channel', catchup.map(item => ({ labels: { account: item.account, channel: item.channel }, value: item.gaps })));
71
+ lines.push('# EOF');
72
+ return `${lines.join('\n')}\n`;
73
+ }
package/dist/missions.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { ExecutionInput } from './execution.js';
3
3
  import { TEAM_VERSION, CoreTeamAction, TeamMission, TeamResult, validateTeamResult } from './team-contract.js';
4
+ import { invalidRequest } from './errors.js';
4
5
  /** Bound on the combined text of a mission's context items. */
5
6
  export const MAX_CONTEXT_ITEM_BYTES = 64 * 1024;
6
7
  const MISSION_EVENT = 'mission';
@@ -24,7 +25,7 @@ export const MissionRecord = z.object({ mission: TeamMission, context_items: z.a
24
25
  /** Accept a mission as a durable `mission` task. The mission and its context are journaled atomically with the task. */
25
26
  export function acceptMission(accept, store, input, nowMs = Date.now()) {
26
27
  if (input.mission.deadline * 1000 <= nowMs)
27
- throw new Error('Mission deadline must be in the future');
28
+ throw invalidRequest('Mission deadline must be in the future');
28
29
  const record = { mission: input.mission, context_items: input.context_items ?? [], labels: input.labels ?? {} };
29
30
  return accept({ prompt: input.objective, ...(input.session_id ? { sessionId: input.session_id } : {}), idempotencyKey: input.idempotency_key,
30
31
  deadlineMs: input.mission.deadline * 1000, content: record, onAccepted: task => store.append(task.id, MISSION_EVENT, record) });
@@ -2,6 +2,7 @@ import { z } from 'zod';
2
2
  import { bodyLimit } from 'hono/body-limit';
3
3
  import { pluginContext } from './plugins.js';
4
4
  import { TokenBucketLimiter } from './a2a-rate-limit.js';
5
+ import { legacyPluginError } from './errors.js';
5
6
  const capacity = z.object({ perMinute: z.number().int().min(1).max(6000), burst: z.number().int().min(1).max(1200) }).strict();
6
7
  /** Hono's route precedence must never let an extension shadow an existing handler. */
7
8
  function overlaps(a, b) {
@@ -46,6 +47,14 @@ export function mountPluginHttp(app, runtime, env, jobs) {
46
47
  if (!result.allowed)
47
48
  return c.json({ error: { code: 'RATE_LIMITED' } }, 429, { 'Retry-After': String(result.retryAfterSeconds), 'Cache-Control': 'no-store' });
48
49
  return next();
49
- }, bodyLimit({ maxSize: 1_048_576, onError: c => c.json({ error: { code: 'BODY_TOO_LARGE' } }, 413) }), route.handler);
50
+ }, bodyLimit({ maxSize: 1_048_576, onError: c => c.json({ error: { code: 'BODY_TOO_LARGE' } }, 413) }), async (c, next) => {
51
+ // A plugin error without a type answers as it did before typed errors.
52
+ try {
53
+ return await route.handler(c, next);
54
+ }
55
+ catch (error) {
56
+ throw legacyPluginError(error);
57
+ }
58
+ });
50
59
  }
51
60
  }
@@ -26,3 +26,5 @@ export { Database as SqliteDatabase } from './sqlite.js';
26
26
  export type SqliteStatement = ReturnType<import('./sqlite.js').Database['prepare']>;
27
27
  export * from './team-contract.js';
28
28
  export { ARDENT_VERSION } from './version.js';
29
+ /** Typed errors: a plugin route that throws one answers with its status and code. */
30
+ export { HiveError, isHiveError, ErrorCode, invalidRequest, notFound, conflict, dependencyUnavailable, notAcceptingWork } from './errors.js';
@@ -25,3 +25,5 @@ export * from './job-engine.js';
25
25
  export { Database as SqliteDatabase } from './sqlite.js';
26
26
  export * from './team-contract.js';
27
27
  export { ARDENT_VERSION } from './version.js';
28
+ /** Typed errors: a plugin route that throws one answers with its status and code. */
29
+ export { HiveError, isHiveError, ErrorCode, invalidRequest, notFound, conflict, dependencyUnavailable, notAcceptingWork } from './errors.js';
@@ -0,0 +1,64 @@
1
+ import type { ArtifactStore } from './artifacts.js';
2
+ import type { TaskStore } from './store.js';
3
+ /** A task that ended this way can be pruned; queued, running, input_required and unknown tasks never are. */
4
+ export declare const PRUNABLE_STATES: readonly ["completed", "partial", "failed", "cancelled"];
5
+ /** The shortest retention: younger work stays, so channel replay protection outlives any catch-up window. */
6
+ export declare const MIN_RETENTION_MS: number;
7
+ export type PruneOptions = {
8
+ /** Prune tasks that last changed before now minus this. At least one day. */
9
+ olderThanMs: number;
10
+ dryRun?: boolean;
11
+ /** Tasks per pass; the prune runs passes until none is left. Default 500. */
12
+ batch?: number;
13
+ now?: number;
14
+ };
15
+ export type PruneResult = {
16
+ dry_run: boolean;
17
+ cutoff: string;
18
+ tasks: number;
19
+ rows: Record<string, number>;
20
+ artifacts: {
21
+ deleted: number;
22
+ retained: number;
23
+ };
24
+ };
25
+ /**
26
+ * Delete old finished tasks and everything that belongs only to them: events,
27
+ * execution state, settled tool invocations and recovery, settled channel
28
+ * deliveries and their inbound updates, and artifact manifests. Artifact bytes
29
+ * go when no manifest or kept task's journal still names them. Unknown, held,
30
+ * queued, running and paused work, tasks with (immutable) session messages,
31
+ * and any task another record refers to, are kept.
32
+ */
33
+ export declare function pruneJournal(store: TaskStore, artifacts: ArtifactStore, options: PruneOptions): Promise<PruneResult>;
34
+ /** `90d`, `36h` or `45m`. */
35
+ export declare function parseDuration(text: string): number;
36
+ export type BackupResult = {
37
+ format: 'ardent-backup';
38
+ version: 1;
39
+ ardent_version: string;
40
+ created_at: string;
41
+ directory: string;
42
+ journal: {
43
+ file: string;
44
+ bytes: number;
45
+ sha256: string;
46
+ integrity: 'ok';
47
+ idle: boolean;
48
+ };
49
+ artifacts: {
50
+ included: boolean;
51
+ files: number;
52
+ bytes: number;
53
+ };
54
+ };
55
+ /**
56
+ * Copy the profile journal with SQLite's online backup API: a consistent copy
57
+ * while the gateway keeps running. The directory must be new (or empty) and is
58
+ * private. With `artifacts`, the content-addressed artifact files are copied too.
59
+ * Configuration, identity and `.env` are not copied.
60
+ */
61
+ export declare function backupProfile(profileDir: string, target: string, options?: {
62
+ artifacts?: boolean;
63
+ now?: () => number;
64
+ }): Promise<BackupResult>;
@@ -0,0 +1,239 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createReadStream } from 'node:fs';
3
+ import { chmod, cp, mkdir, readdir, rm, stat, writeFile } from 'node:fs/promises';
4
+ import { join, resolve } from 'node:path';
5
+ import { z } from 'zod';
6
+ import { inspectJournal } from './journal.js';
7
+ import { Database } from './sqlite.js';
8
+ import { invalidRequest } from './errors.js';
9
+ import { ARDENT_VERSION } from './version.js';
10
+ /** A task that ended this way can be pruned; queued, running, input_required and unknown tasks never are. */
11
+ export const PRUNABLE_STATES = ['completed', 'partial', 'failed', 'cancelled'];
12
+ /** The shortest retention: younger work stays, so channel replay protection outlives any catch-up window. */
13
+ export const MIN_RETENTION_MS = 24 * 3_600_000;
14
+ /**
15
+ * Tables whose rows belong to one task and go with it. Any other table that
16
+ * names a task (a foreign key to tasks, or a `*task_id` / `operation_id`
17
+ * column) keeps the task: A2A, team, job and future records are never orphaned.
18
+ */
19
+ const OWNED = {
20
+ events: 'task_id', task_admission: 'task_id', task_execution: 'task_id', execution_state: 'task_id',
21
+ tool_invocations: 'task_id', task_recovery: 'task_id', artifact_manifests: 'task_id',
22
+ channel_deliveries: 'task_id', channel_inbound: 'task_id',
23
+ };
24
+ const ids = z.array(z.object({ id: z.string() }));
25
+ /** Columns of other tables that name a task, found from the schema so a new table is covered without a change here. */
26
+ function referencingColumns(db) {
27
+ const tables = z.array(z.object({ name: z.string() })).parse(db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").all()).map(row => row.name);
28
+ const result = [];
29
+ for (const table of tables) {
30
+ if (table === 'tasks' || table in OWNED)
31
+ continue;
32
+ const quoted = `"${table.replace(/"/g, '""')}"`;
33
+ const columns = z.array(z.object({ name: z.string() })).parse(db.prepare(`PRAGMA table_info(${quoted})`).all()).map(row => row.name);
34
+ const keys = z.array(z.object({ table: z.string(), from: z.string() })).parse(db.prepare(`PRAGMA foreign_key_list(${quoted})`).all())
35
+ .filter(key => key.table === 'tasks').map(key => key.from);
36
+ for (const column of new Set([...keys, ...columns.filter(name => /task_id$/.test(name) || name === 'operation_id')]))
37
+ result.push({ table: quoted, column: `"${column}"` });
38
+ }
39
+ return result;
40
+ }
41
+ /** One page of prunable tasks after `after` (oldest first), minus any another record still needs. */
42
+ function candidates(db, cutoff, limit, after) {
43
+ const has = (table) => db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(table) !== undefined;
44
+ const guards = [];
45
+ if (has('task_recovery'))
46
+ guards.push("NOT EXISTS (SELECT 1 FROM task_recovery r WHERE r.task_id=t.id AND r.status NOT IN ('resumed','resolved'))", 'NOT EXISTS (SELECT 1 FROM task_recovery r WHERE r.continuation_task_id=t.id)');
47
+ if (has('tool_invocations'))
48
+ guards.push("NOT EXISTS (SELECT 1 FROM tool_invocations i WHERE i.task_id=t.id AND i.state IN ('dispatched','failed_unknown','unknown'))");
49
+ if (has('channel_deliveries'))
50
+ guards.push("NOT EXISTS (SELECT 1 FROM channel_deliveries d WHERE d.task_id=t.id AND d.state NOT IN ('sent','failed'))");
51
+ // Session transcripts are immutable and context checkpoints rest on them: a task with session messages stays.
52
+ if (has('session_messages'))
53
+ guards.push('NOT EXISTS (SELECT 1 FROM session_messages m WHERE m.task_id=t.id)');
54
+ for (const { table, column } of referencingColumns(db))
55
+ guards.push(`NOT EXISTS (SELECT 1 FROM ${table} x WHERE x.${column}=t.id)`);
56
+ const page = z.array(z.object({ id: z.string(), updated_ms: z.number().int() })).parse(db.prepare(`SELECT t.id, t.updated_ms FROM tasks t
57
+ WHERE t.state IN (${PRUNABLE_STATES.map(() => '?').join(',')}) AND t.updated_ms < ?
58
+ ${after ? 'AND (t.updated_ms > ? OR (t.updated_ms = ? AND t.id > ?))' : ''} ORDER BY t.updated_ms, t.id LIMIT ?`)
59
+ .all(...PRUNABLE_STATES, cutoff, ...(after ? [after.updated_ms, after.updated_ms, after.id] : []), limit));
60
+ const tail = page.at(-1);
61
+ const last = tail ? { updated_ms: tail.updated_ms, id: tail.id } : undefined;
62
+ if (!page.length)
63
+ return { ids: [], last, scanned: 0 };
64
+ const placeholders = page.map(() => '?').join(',');
65
+ const rows = ids.parse(db.prepare(`SELECT t.id FROM tasks t WHERE t.id IN (${placeholders}) ${guards.map(guard => `AND ${guard}`).join(' ')}`).all(...page.map(row => row.id))).map(row => row.id);
66
+ if (!has('task_execution') || !rows.length)
67
+ return { ids: rows, last, scanned: page.length };
68
+ // A kept task's ancestry (parent or root) keeps the tasks it names.
69
+ const selected = new Set(rows);
70
+ for (let changed = true; changed;) {
71
+ changed = false;
72
+ for (const id of [...selected]) {
73
+ const placeholders = [...selected].map(() => '?').join(',');
74
+ const named = db.prepare(`SELECT 1 FROM task_execution WHERE task_id NOT IN (${placeholders}) AND (instr(coalesce(parent_ref,''), ?)>0 OR instr(root_ref, ?)>0) LIMIT 1`)
75
+ .get(...selected, id, id);
76
+ if (named) {
77
+ selected.delete(id);
78
+ changed = true;
79
+ }
80
+ }
81
+ }
82
+ return { ids: [...selected], last, scanned: page.length };
83
+ }
84
+ /**
85
+ * Delete old finished tasks and everything that belongs only to them: events,
86
+ * execution state, settled tool invocations and recovery, settled channel
87
+ * deliveries and their inbound updates, and artifact manifests. Artifact bytes
88
+ * go when no manifest or kept task's journal still names them. Unknown, held,
89
+ * queued, running and paused work, tasks with (immutable) session messages,
90
+ * and any task another record refers to, are kept.
91
+ */
92
+ export async function pruneJournal(store, artifacts, options) {
93
+ if (!Number.isSafeInteger(options.olderThanMs) || options.olderThanMs < MIN_RETENTION_MS)
94
+ throw invalidRequest('Retention must be at least one day');
95
+ const now = options.now ?? Date.now();
96
+ const cutoff = now - options.olderThanMs;
97
+ const db = store.db;
98
+ const rows = {};
99
+ const add = (table, count) => { rows[table] = (rows[table] ?? 0) + count; };
100
+ const freed = new Set();
101
+ let tasks = 0;
102
+ const batch = Math.max(1, Math.min(options.batch ?? 500, 5000));
103
+ // Pages move forward by (updated_ms, id), so a kept task is looked at once and deleted ones never come back.
104
+ for (let after, scanned = batch; scanned === batch;) {
105
+ const page = candidates(db, cutoff, batch, after);
106
+ ({ last: after, scanned } = page);
107
+ const ids = page.ids;
108
+ if (!ids.length)
109
+ continue;
110
+ tasks += ids.length;
111
+ if (options.dryRun) {
112
+ add('tasks', ids.length);
113
+ continue;
114
+ }
115
+ db.transaction(() => {
116
+ const placeholders = ids.map(() => '?').join(',');
117
+ const has = (table) => db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(table) !== undefined;
118
+ if (has('artifact_manifests')) {
119
+ for (const row of z.array(z.object({ sha256: z.string() })).parse(db.prepare(`SELECT DISTINCT sha256 FROM artifact_manifests WHERE task_id IN (${placeholders})`).all(...ids)))
120
+ freed.add(row.sha256);
121
+ if (has('artifact_renditions'))
122
+ add('artifact_renditions', Number(db.prepare(`DELETE FROM artifact_renditions WHERE rendition_artifact_id IN (SELECT artifact_id FROM artifact_manifests WHERE task_id IN (${placeholders}))`).run(...ids).changes));
123
+ }
124
+ for (const [table, column] of Object.entries(OWNED))
125
+ if (has(table))
126
+ add(table, Number(db.prepare(`DELETE FROM ${table} WHERE ${column} IN (${placeholders})`).run(...ids).changes));
127
+ add('tasks', Number(db.prepare(`DELETE FROM tasks WHERE id IN (${placeholders})`).run(...ids).changes));
128
+ })();
129
+ }
130
+ const result = { deleted: 0, retained: 0 };
131
+ for (const sha of freed) {
132
+ const manifest = db.prepare('SELECT 1 FROM artifact_manifests WHERE sha256=? LIMIT 1').get(sha);
133
+ const rendition = db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='artifact_renditions'").get() !== undefined
134
+ && db.prepare('SELECT 1 FROM artifact_renditions WHERE original_sha256=? OR rendition_sha256=? LIMIT 1').get(sha, sha) !== undefined;
135
+ const journaled = db.prepare('SELECT 1 FROM events WHERE instr(detail_json, ?)>0 LIMIT 1').get(sha);
136
+ if (manifest || rendition || journaled) {
137
+ result.retained++;
138
+ continue;
139
+ }
140
+ await artifacts.delete(sha).catch(() => undefined);
141
+ result.deleted++;
142
+ }
143
+ return { dry_run: options.dryRun ?? false, cutoff: new Date(cutoff).toISOString(), tasks, rows, artifacts: result };
144
+ }
145
+ /** `90d`, `36h` or `45m`. */
146
+ export function parseDuration(text) {
147
+ const match = /^(\d{1,6})([dhm])$/.exec(text.trim());
148
+ const unit = match?.[2] === 'd' ? 86_400_000 : match?.[2] === 'h' ? 3_600_000 : match?.[2] === 'm' ? 60_000 : undefined;
149
+ if (!match || unit === undefined)
150
+ throw invalidRequest('Use a duration such as 90d, 36h or 45m');
151
+ return Number(match[1]) * unit;
152
+ }
153
+ async function sha256File(path) {
154
+ const hash = createHash('sha256');
155
+ for await (const chunk of createReadStream(path))
156
+ hash.update(z.instanceof(Buffer).parse(chunk));
157
+ return hash.digest('hex');
158
+ }
159
+ async function tree(path) {
160
+ let files = 0, bytes = 0;
161
+ for (const entry of await readdir(path, { withFileTypes: true }).catch(() => [])) {
162
+ const child = join(path, entry.name);
163
+ if (entry.isDirectory()) {
164
+ const sub = await tree(child);
165
+ files += sub.files;
166
+ bytes += sub.bytes;
167
+ }
168
+ else if (entry.isFile()) {
169
+ files++;
170
+ bytes += (await stat(child)).size;
171
+ await chmod(child, 0o600);
172
+ }
173
+ }
174
+ return { files, bytes };
175
+ }
176
+ /**
177
+ * Copy the profile journal with SQLite's online backup API: a consistent copy
178
+ * while the gateway keeps running. The directory must be new (or empty) and is
179
+ * private. With `artifacts`, the content-addressed artifact files are copied too.
180
+ * Configuration, identity and `.env` are not copied.
181
+ */
182
+ export async function backupProfile(profileDir, target, options = {}) {
183
+ const directory = resolve(target);
184
+ const existing = await readdir(directory).catch((error) => {
185
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')
186
+ return undefined;
187
+ throw error;
188
+ });
189
+ if (existing && existing.length)
190
+ throw invalidRequest('The backup directory exists and is not empty');
191
+ const created = existing === undefined;
192
+ await mkdir(directory, { recursive: true, mode: 0o700 });
193
+ await chmod(directory, 0o700);
194
+ const source = join(profileDir, 'state', 'ardent.sqlite');
195
+ const file = join(directory, 'ardent.sqlite');
196
+ try {
197
+ const db = new Database(source, { fileMustExist: true });
198
+ try {
199
+ await db.backup(file);
200
+ }
201
+ finally {
202
+ db.close();
203
+ }
204
+ await chmod(file, 0o600);
205
+ const copy = new Database(file, { readonly: true, fileMustExist: true });
206
+ try {
207
+ const check = z.object({ integrity_check: z.string() }).parse(copy.prepare('PRAGMA integrity_check').get());
208
+ if (check.integrity_check !== 'ok')
209
+ throw new Error('The backup copy failed its integrity check');
210
+ }
211
+ finally {
212
+ copy.close();
213
+ }
214
+ const inspected = await inspectJournal(file);
215
+ let artifacts = { included: false, files: 0, bytes: 0 };
216
+ if (options.artifacts) {
217
+ // Artifact files are immutable and named by digest, so a plain copy is consistent.
218
+ await cp(join(profileDir, 'artifacts'), join(directory, 'artifacts'), { recursive: true, errorOnExist: true, force: false }).catch((error) => {
219
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')
220
+ return;
221
+ throw error;
222
+ });
223
+ artifacts = { included: true, ...await tree(join(directory, 'artifacts')) };
224
+ }
225
+ const result = { format: 'ardent-backup', version: 1, ardent_version: ARDENT_VERSION, created_at: new Date(options.now?.() ?? Date.now()).toISOString(), directory,
226
+ journal: { file: 'ardent.sqlite', bytes: (await stat(file)).size, sha256: await sha256File(file), integrity: 'ok', idle: inspected.idle }, artifacts };
227
+ await writeFile(join(directory, 'backup.json'), `${JSON.stringify(result, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
228
+ return result;
229
+ }
230
+ catch (error) {
231
+ // Never leave a partial backup that looks complete.
232
+ if (created)
233
+ await rm(directory, { recursive: true, force: true });
234
+ else
235
+ for (const entry of await readdir(directory).catch(() => []))
236
+ await rm(join(directory, entry), { recursive: true, force: true });
237
+ throw error;
238
+ }
239
+ }