@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/runtime.d.ts CHANGED
@@ -12,6 +12,9 @@ import { DevelopmentRecords } from './development.js';
12
12
  import { type PreviewSubmit } from './preview.js';
13
13
  import { type MissionSubmit } from './missions.js';
14
14
  import { type ExecutionAcceptance, type ExecutionContext } from './execution.js';
15
+ import { HiveError } from './errors.js';
16
+ import { type Logger } from './log.js';
17
+ import { RuntimeCounters } from './metrics.js';
15
18
  /** A finished task. A mission also carries its validated TeamResult, which is the task's stored result. */
16
19
  export type RunResult = {
17
20
  task: Task;
@@ -37,7 +40,10 @@ export type TaskEvidence = {
37
40
  export declare class RecoveryHeldError extends Error {
38
41
  }
39
42
  /** A recovery decision that is not valid now (HTTP 409). */
40
- export declare class RecoveryConflictError extends Error {
43
+ /** No recovery decision, or not this one, is valid now (HTTP 409 CONFLICT). */
44
+ export declare class RecoveryConflictError extends HiveError {
45
+ readonly name: string;
46
+ constructor(message: string);
41
47
  }
42
48
  export declare class ArdentRuntime {
43
49
  #private;
@@ -60,6 +66,16 @@ export declare class ArdentRuntime {
60
66
  held: string[];
61
67
  };
62
68
  get draining(): boolean;
69
+ /**
70
+ * Operational log lines of this runtime and the components it owns (channels,
71
+ * A2A push, plugin hooks). Silent unless the host sets one; the gateway sets
72
+ * `ardentLogger({ requestContext: false })`.
73
+ */
74
+ logger: Logger;
75
+ /** In-process counters for GET /api/v1/metrics (A2A rate-limit refusals). */
76
+ readonly counters: RuntimeCounters;
77
+ /** When this runtime was created. */
78
+ readonly startedMs: number;
63
79
  get plugins(): readonly ArdentPlugin[];
64
80
  /** The instance part of this runtime's qualified references (`ARDENT_INSTANCE_REF`, else `local.<profile>`). */
65
81
  readonly instanceRef: string;
package/dist/runtime.js CHANGED
@@ -32,12 +32,18 @@ import { acceptPreview, previewOverrides, PREVIEW_ARTIFACT_TTL_SECONDS } from '.
32
32
  import { acceptMission, contextItemMessages, missionEnvelope, missionRecord, missionTeamResult } from './missions.js';
33
33
  import { compactToolArguments } from './tool-arguments.js';
34
34
  import { buildTaskExecution, executionInstance, taskRef, TaskPropagation } from './execution.js';
35
+ import { ErrorCode, HiveError, invalidRequest, notAcceptingWork, notFound } from './errors.js';
36
+ import { silentLogger } from './log.js';
37
+ import { RuntimeCounters } from './metrics.js';
35
38
  const SHUTDOWN_DEADLINE = 'gateway shutdown deadline';
36
39
  /** A resuming task was held as `unknown`; its recovery status says why. */
37
40
  export class RecoveryHeldError extends Error {
38
41
  }
39
42
  /** A recovery decision that is not valid now (HTTP 409). */
40
- export class RecoveryConflictError extends Error {
43
+ /** No recovery decision, or not this one, is valid now (HTTP 409 CONFLICT). */
44
+ export class RecoveryConflictError extends HiveError {
45
+ name = 'RecoveryConflictError';
46
+ constructor(message) { super(ErrorCode.conflict, message, { status: 409 }); }
41
47
  }
42
48
  function addSources(value, evidence, extracted = false, retrievedAt) {
43
49
  if (!Array.isArray(value))
@@ -104,6 +110,16 @@ export class ArdentRuntime {
104
110
  #pluginsStarted = false;
105
111
  #taskContexts = new Map();
106
112
  #settledListeners = new Set();
113
+ /**
114
+ * Operational log lines of this runtime and the components it owns (channels,
115
+ * A2A push, plugin hooks). Silent unless the host sets one; the gateway sets
116
+ * `ardentLogger({ requestContext: false })`.
117
+ */
118
+ logger = silentLogger;
119
+ /** In-process counters for GET /api/v1/metrics (A2A rate-limit refusals). */
120
+ counters = new RuntimeCounters();
121
+ /** When this runtime was created. */
122
+ startedMs = Date.now();
107
123
  #pluginEnvironment = {};
108
124
  #closing = false;
109
125
  #closed = false;
@@ -244,7 +260,7 @@ export class ArdentRuntime {
244
260
  */
245
261
  accept(prompt, caller = 'local', context = 'direct', idempotencyKey, sessionId, originalDeadlineMs, backendOverride, execution = {}) {
246
262
  if (this.#draining)
247
- throw new Error('Gateway is draining and cannot accept new work');
263
+ throw notAcceptingWork('Gateway is draining and cannot accept new work');
248
264
  const deadlineMs = Math.min(Date.now() + this.config.execution.deadline_seconds * 1000, originalDeadlineMs ?? Number.POSITIVE_INFINITY);
249
265
  return this.store.accept({ caller, context, prompt, ...(idempotencyKey ? { idempotencyKey } : {}), ...(sessionId ? { sessionId } : {}), backend: backendOverride ?? this.config.execution.backend, deadlineMs,
250
266
  execution: this.#execution(execution) });
@@ -260,7 +276,7 @@ export class ArdentRuntime {
260
276
  */
261
277
  acceptMission(input, caller = 'management', execution = { context: input.execution }) {
262
278
  if (this.#draining)
263
- throw new Error('Gateway is draining and cannot accept new work');
279
+ throw notAcceptingWork('Gateway is draining and cannot accept new work');
264
280
  return acceptMission(request => this.store.accept({ caller, context: 'mission', prompt: request.prompt, idempotencyKey: request.idempotencyKey,
265
281
  ...(request.sessionId ? { sessionId: request.sessionId } : {}), backend: this.config.execution.backend,
266
282
  deadlineMs: Math.min(Date.now() + this.config.execution.deadline_seconds * 1000, request.deadlineMs),
@@ -273,7 +289,7 @@ export class ArdentRuntime {
273
289
  */
274
290
  acceptPreview(input, caller = 'management', execution = { context: input.execution }) {
275
291
  if (this.#draining)
276
- throw new Error('Gateway is draining and cannot accept new work');
292
+ throw notAcceptingWork('Gateway is draining and cannot accept new work');
277
293
  void this.artifactManifests.sweepExpired().catch(() => { });
278
294
  return acceptPreview(request => this.store.accept({ caller, context: 'preview', prompt: request.prompt,
279
295
  ...(request.idempotencyKey ? { idempotencyKey: request.idempotencyKey } : {}), ...(request.sessionId ? { sessionId: request.sessionId } : {}),
@@ -290,6 +306,7 @@ export class ArdentRuntime {
290
306
  return () => { this.#settledListeners.delete(listener); };
291
307
  }
292
308
  #notifySettled(taskId) {
309
+ this.#logSettled(taskId);
293
310
  for (const listener of [...this.#settledListeners]) {
294
311
  try {
295
312
  listener(taskId);
@@ -297,6 +314,24 @@ export class ArdentRuntime {
297
314
  catch { /* a listener failure never affects the task */ }
298
315
  }
299
316
  }
317
+ #logSettled(taskId) {
318
+ try {
319
+ const task = this.store.get(taskId);
320
+ if (!task)
321
+ return;
322
+ const execution = this.store.executions.get(taskId);
323
+ const requestId = execution?.context.request_id;
324
+ const traceId = execution?.traceparent.split('-')[1];
325
+ const fields = { task_id: task.id, state: task.state, caller: task.caller, context: task.context, backend: task.backend, duration_ms: task.updated_ms - task.created_ms,
326
+ ...(requestId ? { request_id: requestId } : {}), ...(traceId ? { trace_id: traceId } : {}),
327
+ ...(task.error ? { error: task.error.slice(0, 300) } : {}) };
328
+ if (['failed', 'unknown'].includes(task.state))
329
+ this.logger.warn('Task settled', fields);
330
+ else
331
+ this.logger.info('Task settled', fields);
332
+ }
333
+ catch { /* logging never affects the task */ }
334
+ }
300
335
  /** The recovery object (C3) of a task interrupted by a crash or restart; undefined for one never interrupted. */
301
336
  recoveryFor(taskId) {
302
337
  const task = this.store.get(taskId);
@@ -314,7 +349,7 @@ export class ArdentRuntime {
314
349
  async decideRecovery(taskId, input, env = this.#pluginEnvironment, by = 'operator') {
315
350
  const task = this.store.get(taskId);
316
351
  if (!task)
317
- throw new Error('Task not found');
352
+ throw notFound('Task not found');
318
353
  const states = this.store.executionState;
319
354
  const row = states.recovery(taskId);
320
355
  if (!row)
@@ -333,18 +368,18 @@ export class ArdentRuntime {
333
368
  if (!actions.includes(input.action))
334
369
  throw new RecoveryConflictError(`${input.action} is not valid now; valid actions: ${actions.join(', ') || 'none'}`);
335
370
  if (input.result !== undefined && input.action !== 'mark_applied')
336
- throw new Error('Invalid request: result is valid only with mark_applied');
371
+ throw invalidRequest('Invalid request: result is valid only with mark_applied');
337
372
  if (input.deadline_seconds !== undefined && input.action !== 'retry_with_new_deadline')
338
- throw new Error('Invalid request: deadline_seconds is valid only with retry_with_new_deadline');
373
+ throw invalidRequest('Invalid request: deadline_seconds is valid only with retry_with_new_deadline');
339
374
  const pending = states.invocations(taskId).filter(item => item.state === 'dispatched');
340
375
  if (input.call_id && !pending.some(item => item.call_id === input.call_id))
341
- throw new Error('Invalid request: call_id does not name a pending call');
376
+ throw invalidRequest('Invalid request: call_id does not name a pending call');
342
377
  const target = input.call_id ? pending.find(item => item.call_id === input.call_id) : pending.length === 1 ? pending[0] : undefined;
343
378
  if (input.result !== undefined) {
344
379
  if (!target)
345
- throw new Error('Invalid request: result needs call_id when several calls are pending');
380
+ throw invalidRequest('Invalid request: result needs call_id when several calls are pending');
346
381
  if (Buffer.byteLength(JSON.stringify(input.result) ?? 'null') > MAX_OPERATOR_RESULT_BYTES)
347
- throw new Error('Invalid request: result exceeds 64 KiB');
382
+ throw invalidRequest('Invalid request: result exceeds 64 KiB');
348
383
  let tool;
349
384
  try {
350
385
  tool = (await this.#taskScope(task, env)).taskTools.get(target.name, task.context);
@@ -353,7 +388,7 @@ export class ArdentRuntime {
353
388
  tool = undefined;
354
389
  }
355
390
  if (tool && !tool.output.safeParse(input.result).success)
356
- throw new Error(`Invalid request: result does not match the ${tool.name} output schema`);
391
+ throw invalidRequest(`Invalid request: result does not match the ${tool.name} output schema`);
357
392
  }
358
393
  const decided = { action: input.action, by, at: new Date().toISOString(), ...(input.note ? { note: input.note } : {}) };
359
394
  if (input.action === 'abandon' || row.reason.code === 'CANCELLED_WITH_UNSETTLED_EFFECT') {
@@ -370,11 +405,11 @@ export class ArdentRuntime {
370
405
  if (input.action === 'retry_with_new_deadline') {
371
406
  const seconds = input.deadline_seconds ?? Math.min(this.config.execution.deadline_seconds, max);
372
407
  if (seconds > max)
373
- throw new Error(`Invalid request: deadline_seconds exceeds execution.recovery_max_new_deadline_seconds (${max})`);
408
+ throw invalidRequest(`Invalid request: deadline_seconds exceeds execution.recovery_max_new_deadline_seconds (${max})`);
374
409
  deadlineMs = Date.now() + seconds * 1000;
375
410
  }
376
411
  if (this.#draining)
377
- throw new Error('Gateway is draining and cannot accept new work');
412
+ throw notAcceptingWork('Gateway is draining and cannot accept new work');
378
413
  const continuation = this.#acceptContinuation(task, row.attempt, row.reason, input.action, decided, deadlineMs, target, input.result);
379
414
  this.#notifySettled(taskId);
380
415
  return { recovery: view(), continuation };
@@ -425,7 +460,7 @@ export class ArdentRuntime {
425
460
  cancel(id) {
426
461
  const task = this.store.get(id);
427
462
  if (!task)
428
- throw new Error('Task not found');
463
+ throw notFound('Task not found');
429
464
  const active = this.#active.get(id);
430
465
  const waitingResume = this.#waiting.get(id)?.resume === true ? this.#waiting.get(id) : undefined;
431
466
  if (active) {
@@ -579,7 +614,7 @@ export class ArdentRuntime {
579
614
  this.#waiting.set(pending.task.id, pending);
580
615
  }
581
616
  #pump() {
582
- const limit = Math.max(1, Math.min(maxParallelTasks(this.config), 4));
617
+ const limit = Math.max(1, maxParallelTasks(this.config));
583
618
  while (this.#runningCount < limit && this.#roundRobin.length) {
584
619
  let caller;
585
620
  for (let inspected = 0, count = this.#roundRobin.length; inspected < count; inspected++) {
@@ -827,6 +862,8 @@ export class ArdentRuntime {
827
862
  /** Journal a scheduler event with its boundary write, in one transaction. */
828
863
  const journal = (kind, detail, boundary) => this.store.db.transaction(() => {
829
864
  this.store.append(task.id, kind, detail);
865
+ if (kind === 'plugin_hook_failed' || kind === 'tool_denied_by_plugin')
866
+ this.logger.warn(kind === 'plugin_hook_failed' ? 'Plugin hook failed' : 'Plugin denied a tool call', { task_id: task.id, detail });
830
867
  if (!boundary)
831
868
  return;
832
869
  const row = { callId: boundary.call.id, attempt, step: backendName === 'llamacpp' ? currentStep : null, name: boundary.call.name, effect: boundary.effect ?? 'read',
package/dist/skills.js CHANGED
@@ -5,6 +5,7 @@ import YAML from 'yaml';
5
5
  import { loadConfig, saveConfig } from './config.js';
6
6
  import { defineTool } from './tools.js';
7
7
  import { z } from 'zod';
8
+ import { conflict, invalidRequest, notFound } from './errors.js';
8
9
  const safeName = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
9
10
  async function inside(root, target) {
10
11
  const realRoot = await realpath(root);
@@ -54,7 +55,7 @@ export async function readSkill(profileDir, config, name) {
54
55
  throw new Error('Skill is not enabled');
55
56
  const skill = (await listSkills(profileDir, config)).find(item => item.name === name);
56
57
  if (!skill)
57
- throw new Error('Skill not found');
58
+ throw notFound('Skill not found');
58
59
  return readFile(skill.path, 'utf8');
59
60
  }
60
61
  export async function registerSkillTool(registry, profileDir, config) {
@@ -69,13 +70,13 @@ export async function registerSkillTool(registry, profileDir, config) {
69
70
  }
70
71
  export async function setSkillEnabled(profileDir, name, enabled, expectedRevision) {
71
72
  if (!safeName.test(name))
72
- throw new Error('Invalid skill name');
73
+ throw invalidRequest('Invalid skill name');
73
74
  const loaded = await loadConfig(profileDir);
74
75
  if (loaded.revision !== expectedRevision)
75
- throw new Error('Configuration revision conflict');
76
+ throw conflict('Configuration revision conflict');
76
77
  const available = await listSkills(profileDir, loaded.config);
77
78
  if (!available.some(item => item.name === name))
78
- throw new Error('Skill not found');
79
+ throw notFound('Skill not found');
79
80
  const selected = new Set(loaded.config.skills.enabled);
80
81
  if (enabled)
81
82
  selected.add(name);
package/dist/store.d.ts CHANGED
@@ -97,8 +97,20 @@ export type TaskEvent = z.infer<typeof EventSchema>;
97
97
  /** Historical transport labels remain distinct; adapters must retain their original identity. */
98
98
  export type InboundChannelType = 'unknown' | 'telegram_private' | 'telegram_group' | 'telegram_supergroup' | 'mattermost_dm' | 'mattermost_channel' | 'chattermost_dm' | 'chattermost_channel';
99
99
  /** How a claimed inbound post was settled: admitted to the normal channel path, or claimed by catch-up as too old to answer. */
100
+ /** `skipped_stale`: claimed but never answered (a post too old on catch-up, or history seeded on a channel's first sight). */
100
101
  export type InboundDisposition = 'admitted' | 'skipped_stale';
102
+ /** Filters and cursor of `TaskStore.page()`. `since` and `until` bound `created_ms` (since inclusive, until exclusive). */
103
+ export type TaskPageQuery = {
104
+ limit?: number;
105
+ after?: string;
106
+ states?: readonly TaskState[];
107
+ context?: TaskContext;
108
+ caller?: string;
109
+ since?: number;
110
+ until?: number;
111
+ };
101
112
  export declare class TaskStore {
113
+ #private;
102
114
  readonly db: Database;
103
115
  readonly catchup: CatchupJournal;
104
116
  /** Execution ancestry (attribution only; never read for tool, memory or mission scope). */
@@ -198,7 +210,17 @@ export declare class TaskStore {
198
210
  };
199
211
  /** The last scheduler tick failure the gateway recorded (cursor `jobs:last_error`), with when it happened. */
200
212
  jobTickError(): JobTickError | null;
213
+ /** Forget the recorded job tick failure: a later tick succeeded. */
214
+ clearJobTickError(): void;
201
215
  list(limit?: number): Task[];
216
+ /**
217
+ * One page of tasks, newest first, with optional filters. `next` is an opaque
218
+ * cursor for the following page (pass it as `after`), or null on the last one.
219
+ */
220
+ page(query?: TaskPageQuery): {
221
+ tasks: Task[];
222
+ next: string | null;
223
+ };
202
224
  listByCaller(caller: string, limit?: number): Task[];
203
225
  setState(id: string, state: TaskState, result?: string | null, error?: string | null): void;
204
226
  startQueued(id: string): void;
@@ -219,6 +241,12 @@ export declare class TaskStore {
219
241
  hook: string;
220
242
  }[];
221
243
  append(id: string, kind: string, detail: unknown): void;
244
+ /**
245
+ * Call `listener` after each journal event this store appends for the task.
246
+ * Events written by another process (or another store on the same file) do
247
+ * not notify; poll for those. Returns the unsubscribe function.
248
+ */
249
+ onAppend(taskId: string, listener: () => void): () => void;
222
250
  events(id: string, after?: number, limit?: number): TaskEvent[];
223
251
  /**
224
252
  * Startup recovery, before any queued work is admitted. Each `running` task
package/dist/store.js CHANGED
@@ -7,6 +7,8 @@ import { CatchupJournal } from './channel-catchup.js';
7
7
  import { TaskExecutions } from './execution.js';
8
8
  import { ExecutionStates } from './execution-state.js';
9
9
  import { planRecovery } from './recovery.js';
10
+ import { SessionMismatchError, TaskTerminalError, conflict, invalidRequest, notAcceptingWork, notFound } from './errors.js';
11
+ import { SEEDED_INBOUND } from './journal.js';
10
12
  export const TaskState = z.enum(['queued', 'running', 'input_required', 'completed', 'partial', 'failed', 'cancelled', 'unknown']);
11
13
  /** Execution scope of a task. It selects tools and memory; a session belongs to exactly one context. */
12
14
  export const TaskContext = z.enum(['direct', 'peer', 'scheduled', 'mission', 'preview']);
@@ -14,7 +16,21 @@ export const TaskSchema = z.object({ id: z.string().guid(), caller: z.string(),
14
16
  export const SessionSchema = z.object({ id: z.string().guid(), caller: z.string(), context: TaskContext, key: z.string(), created_ms: z.number().int(), updated_ms: z.number().int() });
15
17
  export const SessionMessageSchema = z.object({ sequence: z.number().int(), session_id: z.string().guid(), task_id: z.string().guid(), role: z.enum(['user', 'assistant']), content: z.string(), created_ms: z.number().int() });
16
18
  export const EventSchema = z.object({ sequence: z.number().int(), task_id: z.string(), kind: z.string(), detail: z.unknown().optional(), created_ms: z.number().int() });
19
+ const TaskCursor = z.object({ created_ms: z.number().int().min(0), id: z.string().min(1).max(128) });
20
+ function encodeTaskCursor(task) {
21
+ return Buffer.from(JSON.stringify([task.created_ms, task.id])).toString('base64url');
22
+ }
23
+ function decodeTaskCursor(cursor) {
24
+ try {
25
+ const value = z.tuple([z.unknown(), z.unknown()]).safeParse(JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')));
26
+ if (value.success)
27
+ return TaskCursor.parse({ created_ms: value.data[0], id: value.data[1] });
28
+ }
29
+ catch { /* reported below */ }
30
+ throw invalidRequest('Invalid task cursor');
31
+ }
17
32
  export class TaskStore {
33
+ #appendListeners = new Map();
18
34
  db;
19
35
  catchup;
20
36
  /** Execution ancestry (attribution only; never read for tool, memory or mission scope). */
@@ -93,7 +109,8 @@ export class TaskStore {
93
109
  // Created after the column migration so an older database gains session_id first.
94
110
  this.db.exec(`CREATE INDEX IF NOT EXISTS tasks_caller_created ON tasks(caller, created_ms);
95
111
  CREATE INDEX IF NOT EXISTS tasks_session_created ON tasks(session_id, created_ms);
96
- CREATE INDEX IF NOT EXISTS tasks_state ON tasks(state);`);
112
+ CREATE INDEX IF NOT EXISTS tasks_state ON tasks(state);
113
+ CREATE INDEX IF NOT EXISTS tasks_created_id ON tasks(created_ms, id);`);
97
114
  const deliveryColumns = z.array(z.object({ name: z.string() })).parse(this.db.pragma('table_info(channel_deliveries)'));
98
115
  if (!deliveryColumns.some(column => column.name === 'attempts'))
99
116
  this.db.exec('ALTER TABLE channel_deliveries ADD COLUMN attempts INTEGER');
@@ -106,6 +123,11 @@ export class TaskStore {
106
123
  if (!inboundColumns.some(column => column.name === 'disposition'))
107
124
  this.db.exec(`ALTER TABLE channel_inbound ADD COLUMN
108
125
  disposition TEXT NOT NULL DEFAULT 'admitted' CHECK(disposition IN ('admitted','skipped_stale'))`);
126
+ // Mattermost history seeded on a channel's first sight (before 3.4 it was recorded as admitted):
127
+ // claimed so it is never answered, which is what skipped_stale means.
128
+ this.db.prepare(`UPDATE channel_inbound SET disposition='skipped_stale' WHERE disposition='admitted' AND task_id IS NULL
129
+ AND platform='mattermost' AND channel_type='unknown' AND NOT EXISTS (SELECT 1 FROM channel_deliveries d
130
+ WHERE d.platform=channel_inbound.platform AND d.account=channel_inbound.account AND d.update_id=channel_inbound.update_id)`).run();
109
131
  // Where a reply goes (conversation, thread, the message replied to), so a
110
132
  // task that execution recovery resumes or continues can still answer it.
111
133
  if (!inboundColumns.some(column => column.name === 'reply_target_json'))
@@ -135,7 +157,7 @@ export class TaskStore {
135
157
  return this.db.transaction(() => {
136
158
  const prior = this.admissionFence();
137
159
  if (prior && prior.release_id !== releaseId)
138
- throw new Error('Admission is already fenced by another release');
160
+ throw conflict('Admission is already fenced by another release');
139
161
  if (!prior)
140
162
  this.db.prepare('INSERT INTO admission_fence(singleton,release_id,closed_ms) VALUES (1,?,?)').run(releaseId, Date.now());
141
163
  const state = this.admissionFence();
@@ -148,12 +170,12 @@ export class TaskStore {
148
170
  inbound_unbound: count(`SELECT count(*) AS count FROM channel_inbound AS inbound
149
171
  LEFT JOIN channel_deliveries AS delivery ON delivery.platform=inbound.platform
150
172
  AND delivery.account=inbound.account AND delivery.update_id=inbound.update_id
151
- WHERE inbound.task_id IS NULL AND inbound.disposition='admitted' AND (delivery.id IS NULL OR delivery.state IN ('queued','unknown'))`) };
173
+ WHERE inbound.task_id IS NULL AND inbound.disposition='admitted' AND NOT ${SEEDED_INBOUND} AND (delivery.id IS NULL OR delivery.state IN ('queued','unknown'))`) };
152
174
  })();
153
175
  }
154
176
  session(caller, context, key) {
155
177
  if (!caller || caller.length > 128 || !key || key.length > 256)
156
- throw new Error('Invalid session identity');
178
+ throw invalidRequest('Invalid session identity');
157
179
  return this.db.transaction(() => {
158
180
  const previous = this.db.prepare('SELECT * FROM sessions WHERE caller=? AND context=? AND key=?').get(caller, context, key);
159
181
  if (previous)
@@ -178,7 +200,7 @@ export class TaskStore {
178
200
  sessionMessages(sessionId, caller, limit = 100) {
179
201
  const session = this.db.prepare('SELECT * FROM sessions WHERE id=?').get(sessionId);
180
202
  if (!session || SessionSchema.parse(session).caller !== caller)
181
- throw new Error('Session not found');
203
+ throw notFound('Session not found');
182
204
  return this.db.prepare('SELECT * FROM (SELECT * FROM session_messages WHERE session_id=? ORDER BY sequence DESC LIMIT ?) ORDER BY sequence').all(sessionId, Math.max(1, Math.min(limit, 500))).map(row => SessionMessageSchema.parse(row));
183
205
  }
184
206
  /**
@@ -192,25 +214,25 @@ export class TaskStore {
192
214
  */
193
215
  accept(input) {
194
216
  if (!input.caller || input.caller.length > 128 || !input.prompt.trim() || input.prompt.length > 16000 || (input.idempotencyKey && input.idempotencyKey.length > 128))
195
- throw new Error('Invalid task input');
217
+ throw invalidRequest('Invalid task input');
196
218
  const hash = createHash('sha256').update(JSON.stringify(input.content === undefined ? [input.prompt, input.backend] : [input.prompt, input.backend, input.content])).digest('hex');
197
219
  return this.db.transaction(() => {
198
220
  if (this.admissionFence())
199
- throw new Error('Profile admission is fenced for rollback');
221
+ throw notAcceptingWork('Profile admission is fenced for rollback');
200
222
  if (input.sessionId) {
201
223
  const session = this.db.prepare('SELECT * FROM sessions WHERE id=?').get(input.sessionId);
202
224
  if (!session)
203
- throw new Error('Session not found');
225
+ throw notFound('Session not found');
204
226
  const scoped = SessionSchema.parse(session);
205
227
  if (scoped.caller !== input.caller || scoped.context !== input.context)
206
- throw new Error('Session caller or context mismatch');
228
+ throw new SessionMismatchError();
207
229
  }
208
230
  if (input.idempotencyKey) {
209
231
  const previous = this.db.prepare('SELECT * FROM tasks WHERE caller=? AND context=? AND idempotency_key=?').get(input.caller, input.context, input.idempotencyKey);
210
232
  if (previous) {
211
233
  const task = TaskSchema.parse(previous);
212
234
  if (task.content_hash !== hash)
213
- throw new Error('Idempotency key reused with different task content');
235
+ throw conflict('Idempotency key reused with different task content');
214
236
  return task;
215
237
  }
216
238
  }
@@ -270,7 +292,7 @@ export class TaskStore {
270
292
  throw new Error('Inbound channel type differs from platform');
271
293
  return this.db.transaction(() => {
272
294
  if (this.admissionFence())
273
- throw new Error('Profile admission is fenced for rollback');
295
+ throw notAcceptingWork('Profile admission is fenced for rollback');
274
296
  const row = this.db.prepare('SELECT task_id,channel_type FROM channel_inbound WHERE platform=? AND account=? AND update_id=?').get(platform, account, updateId);
275
297
  if (row) {
276
298
  const prior = z.object({ task_id: z.string().nullable(), channel_type: z.string() }).parse(row);
@@ -339,14 +361,14 @@ export class TaskStore {
339
361
  return this.db.transaction(() => {
340
362
  const task = this.get(id);
341
363
  if (!task)
342
- throw new Error('Task not found');
364
+ throw notFound('Task not found');
343
365
  const prior = this.taskAdmission(id);
344
366
  if (prior === admission)
345
367
  return { task, admission, changed: false };
346
368
  if (!['queued', 'running'].includes(task.state)) {
347
369
  if (admission === 'open')
348
370
  return { task, admission: prior, changed: false };
349
- throw Object.assign(new Error(`Task is ${task.state}; only queued or running tasks can be paused`), { code: 'TASK_TERMINAL' });
371
+ throw new TaskTerminalError(`Task is ${task.state}; only queued or running tasks can be paused`);
350
372
  }
351
373
  this.db.prepare(`INSERT INTO task_admission(task_id,admission,updated_ms) VALUES (?,?,?)
352
374
  ON CONFLICT(task_id) DO UPDATE SET admission=excluded.admission,updated_ms=excluded.updated_ms`).run(id, admission, Date.now());
@@ -365,9 +387,50 @@ export class TaskStore {
365
387
  }
366
388
  /** The last scheduler tick failure the gateway recorded (cursor `jobs:last_error`), with when it happened. */
367
389
  jobTickError() { return readJobTickError(this.db); }
390
+ /** Forget the recorded job tick failure: a later tick succeeded. */
391
+ clearJobTickError() { this.db.prepare('DELETE FROM channel_cursors WHERE key=?').run(JOB_TICK_ERROR_CURSOR); }
368
392
  list(limit = 50) {
369
393
  return this.db.prepare('SELECT * FROM tasks ORDER BY created_ms DESC LIMIT ?').all(Math.max(1, Math.min(limit, 100))).map(row => TaskSchema.parse(row));
370
394
  }
395
+ /**
396
+ * One page of tasks, newest first, with optional filters. `next` is an opaque
397
+ * cursor for the following page (pass it as `after`), or null on the last one.
398
+ */
399
+ page(query = {}) {
400
+ const limit = Math.max(1, Math.min(query.limit ?? 50, 100));
401
+ const where = [];
402
+ const values = [];
403
+ if (query.after !== undefined) {
404
+ const cursor = decodeTaskCursor(query.after);
405
+ where.push('(created_ms < ? OR (created_ms = ? AND id < ?))');
406
+ values.push(cursor.created_ms, cursor.created_ms, cursor.id);
407
+ }
408
+ if (query.states?.length) {
409
+ where.push(`state IN (${query.states.map(() => '?').join(',')})`);
410
+ values.push(...query.states);
411
+ }
412
+ if (query.context !== undefined) {
413
+ where.push('context = ?');
414
+ values.push(query.context);
415
+ }
416
+ if (query.caller !== undefined) {
417
+ where.push('caller = ?');
418
+ values.push(query.caller);
419
+ }
420
+ if (query.since !== undefined) {
421
+ where.push('created_ms >= ?');
422
+ values.push(query.since);
423
+ }
424
+ if (query.until !== undefined) {
425
+ where.push('created_ms < ?');
426
+ values.push(query.until);
427
+ }
428
+ const sql = `SELECT * FROM tasks ${where.length ? `WHERE ${where.join(' AND ')}` : ''} ORDER BY created_ms DESC, id DESC LIMIT ?`;
429
+ const rows = this.db.prepare(sql).all(...values, limit + 1).map(row => TaskSchema.parse(row));
430
+ const tasks = rows.slice(0, limit);
431
+ const last = tasks.at(-1);
432
+ return { tasks, next: rows.length > limit && last ? encodeTaskCursor(last) : null };
433
+ }
371
434
  listByCaller(caller, limit = 50) {
372
435
  return this.db.prepare('SELECT * FROM tasks WHERE caller=? ORDER BY created_ms DESC LIMIT ?').all(caller, Math.max(1, Math.min(limit, 100))).map(row => TaskSchema.parse(row));
373
436
  }
@@ -386,7 +449,7 @@ export class TaskStore {
386
449
  startQueued(id) {
387
450
  this.db.transaction(() => {
388
451
  if (this.admissionFence())
389
- throw new Error('Profile admission is fenced for rollback');
452
+ throw notAcceptingWork('Profile admission is fenced for rollback');
390
453
  const task = this.get(id);
391
454
  if (!task || task.state !== 'queued')
392
455
  throw new Error('Task is no longer queued');
@@ -413,6 +476,26 @@ export class TaskStore {
413
476
  }
414
477
  append(id, kind, detail) {
415
478
  this.db.prepare('INSERT INTO events(task_id,kind,detail_json,created_ms) VALUES (?,?,?,?)').run(id, kind, JSON.stringify(detail), Date.now());
479
+ const listeners = this.#appendListeners.get(id);
480
+ // After the current synchronous work, so a transaction that appended has committed.
481
+ if (listeners?.size)
482
+ queueMicrotask(() => { for (const listener of listeners)
483
+ listener(); });
484
+ }
485
+ /**
486
+ * Call `listener` after each journal event this store appends for the task.
487
+ * Events written by another process (or another store on the same file) do
488
+ * not notify; poll for those. Returns the unsubscribe function.
489
+ */
490
+ onAppend(taskId, listener) {
491
+ const listeners = this.#appendListeners.get(taskId) ?? new Set();
492
+ listeners.add(listener);
493
+ this.#appendListeners.set(taskId, listeners);
494
+ return () => {
495
+ listeners.delete(listener);
496
+ if (!listeners.size && this.#appendListeners.get(taskId) === listeners)
497
+ this.#appendListeners.delete(taskId);
498
+ };
416
499
  }
417
500
  events(id, after = 0, limit = 100) {
418
501
  const rows = this.db.prepare('SELECT * FROM events WHERE task_id=? AND sequence>? ORDER BY sequence LIMIT ?').all(id, after, Math.max(1, Math.min(limit, 500)));
package/dist/telegram.js CHANGED
@@ -148,6 +148,7 @@ export class TelegramAdapter {
148
148
  const ready = new Promise((resolve, reject) => { readyResolve = () => { entry.accepted = true; resolve(); }; readyReject = reject; });
149
149
  const operation = this.#handleUpdate(update, readyResolve, deliverySignal).catch(error => {
150
150
  readyReject(error);
151
+ this.runtime.logger.warn('Telegram update failed', { account, update_id: update.update_id, err: error });
151
152
  this.runtime.store.setCursor(`telegram:${account}:last_error`, error instanceof Error ? error.message.slice(0, 500) : 'unknown');
152
153
  }).finally(() => {
153
154
  if (!entry.accepted) {
@@ -190,9 +191,12 @@ export class TelegramAdapter {
190
191
  catch (error) {
191
192
  if (signal.aborted)
192
193
  break;
193
- if (error instanceof TelegramConflictError)
194
+ if (error instanceof TelegramConflictError) {
195
+ this.runtime.logger.error('Telegram polling stopped', { err: error });
194
196
  throw error;
197
+ }
195
198
  failures++;
199
+ this.runtime.logger.warn('Telegram poll failed; retrying', { failures, err: error });
196
200
  // Abort-aware so shutdown does not wait out the reconnect backoff.
197
201
  await sleep(Math.min(30_000, 1000 * 2 ** Math.min(failures, 5)), undefined, { signal }).catch(() => { });
198
202
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hivemagnus/ardent",
3
- "version": "3.3.0",
3
+ "version": "3.4.0",
4
4
  "description": "Headless TypeScript agent runtime with A2A, scheduled jobs, skills, chat channels, and a plugin API",
5
5
  "keywords": [
6
6
  "agent",
@@ -88,7 +88,7 @@
88
88
  "@bufbuild/protobuf": "2.16.0",
89
89
  "@grpc/grpc-js": "1.14.7",
90
90
  "@hivemagnus/canvas-word-codec": "1.1.0",
91
- "@hivemagnus/emberfold": "0.1.0",
91
+ "@hivemagnus/emberfold": "0.4.0",
92
92
  "@hivemagnus/hive-common": "0.6.0",
93
93
  "@hono/node-server": "^2.1.11",
94
94
  "@photostructure/sqlite": "3.3.1",
@@ -14,7 +14,7 @@ execution:
14
14
  backend: llamacpp # llamacpp | codex
15
15
  max_model_steps: 40
16
16
  max_tool_calls: 80
17
- max_parallel_tasks: 3 # tasks running at once (the runtime runs at most 4)
17
+ max_parallel_tasks: 3 # tasks running at once (1-16)
18
18
  max_parallel_tool_calls: 4 # independent read calls overlapping in one model turn
19
19
  deadline_seconds: 3600
20
20
  max_delegation_depth: 2