@hivemagnus/ardent 3.2.1 → 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 (52) hide show
  1. package/README.md +15 -923
  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 +12 -0
  12. package/dist/api.js +312 -131
  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 +106 -8
  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/index.d.ts +1 -0
  26. package/dist/index.js +1 -0
  27. package/dist/job-engine.d.ts +3 -0
  28. package/dist/job-engine.js +5 -0
  29. package/dist/journal.d.ts +90 -0
  30. package/dist/journal.js +395 -0
  31. package/dist/log.d.ts +11 -0
  32. package/dist/log.js +12 -0
  33. package/dist/mattermost.js +7 -2
  34. package/dist/memory.js +3 -2
  35. package/dist/metrics.d.ts +34 -0
  36. package/dist/metrics.js +73 -0
  37. package/dist/missions.js +2 -1
  38. package/dist/plugin-http.js +10 -1
  39. package/dist/plugin-sdk.d.ts +2 -0
  40. package/dist/plugin-sdk.js +2 -0
  41. package/dist/retention.d.ts +64 -0
  42. package/dist/retention.js +239 -0
  43. package/dist/runtime.d.ts +17 -1
  44. package/dist/runtime.js +52 -15
  45. package/dist/skills.js +5 -4
  46. package/dist/store.d.ts +42 -0
  47. package/dist/store.js +114 -14
  48. package/dist/telegram.js +5 -1
  49. package/package.json +8 -4
  50. package/profiles/assistant/config.yaml +1 -1
  51. package/dist/codex-output-budget.test.d.ts +0 -1
  52. package/dist/codex-output-budget.test.js +0 -29
@@ -12,6 +12,7 @@ import { ArtifactStoreError, hashFileRange } from './artifacts.js';
12
12
  import { buildTaskExecution } from './execution.js';
13
13
  import { TeamArtifactDescriptorSchema, TeamArtifactDescriptorV2Schema, TeamArtifactRequiresV2Schema } from './team-artifacts.js';
14
14
  import { ProvenNoEffectError } from './tools.js';
15
+ import { notFound } from './errors.js';
15
16
  const digest = z.string().regex(/^[a-f0-9]{64}$/);
16
17
  const identifier = z.string().regex(/^[a-f0-9]{32}$/);
17
18
  export const ArtifactImportStateSchema = z.enum(['queued', 'transferring', 'verifying', 'completed', 'failed']);
@@ -119,7 +120,7 @@ export class ArtifactTransfers {
119
120
  request(input, caller = 'management') {
120
121
  const request = ArtifactImportRequestSchema.parse(input);
121
122
  if (request.task_id && !this.runtime.store.get(request.task_id))
122
- throw new Error('Local task not found');
123
+ throw notFound('Local task not found');
123
124
  const db = this.runtime.store.db;
124
125
  return db.transaction(() => {
125
126
  const existing = db.prepare('SELECT * FROM artifact_transfers WHERE peer_id=? AND a2a_task_id=? AND artifact_id=?')
@@ -484,7 +485,7 @@ export class ArtifactTransfers {
484
485
  #row(id) {
485
486
  const raw = this.runtime.store.db.prepare('SELECT * FROM artifact_transfers WHERE id=?').get(id);
486
487
  if (!raw)
487
- throw new Error('Artifact import not found');
488
+ throw notFound('Artifact import not found');
488
489
  return Row.parse(raw);
489
490
  }
490
491
  #resolvedRow(row) {
@@ -29,8 +29,8 @@ export declare const CatchupStatusSchema: z.ZodObject<{
29
29
  from_ms: z.ZodNumber;
30
30
  to_ms: z.ZodNumber;
31
31
  reason: z.ZodEnum<{
32
- walk_bound: "walk_bound";
33
32
  retention: "retention";
33
+ walk_bound: "walk_bound";
34
34
  }>;
35
35
  detected_ms: z.ZodNumber;
36
36
  }, z.core.$strip>>;
@@ -40,8 +40,8 @@ declare const GapRow: z.ZodObject<{
40
40
  from_ms: z.ZodNumber;
41
41
  to_ms: z.ZodNumber;
42
42
  reason: z.ZodEnum<{
43
- walk_bound: "walk_bound";
44
43
  retention: "retention";
44
+ walk_bound: "walk_bound";
45
45
  }>;
46
46
  detected_ms: z.ZodNumber;
47
47
  }, z.core.$strip>;
@@ -3,8 +3,8 @@ import type { ArdentRuntime } from './runtime.js';
3
3
  import type { JobEngine } from './job-engine.js';
4
4
  export declare const ChannelEvent: z.ZodObject<{
5
5
  platform: z.ZodEnum<{
6
- telegram: "telegram";
7
6
  mattermost: "mattermost";
7
+ telegram: "telegram";
8
8
  }>;
9
9
  account: z.ZodString;
10
10
  channel_type: z.ZodOptional<z.ZodEnum<{
@@ -35,6 +35,11 @@ export declare const ReplyTarget: z.ZodObject<{
35
35
  thread: z.ZodNullable<z.ZodString>;
36
36
  account: z.ZodString;
37
37
  user: z.ZodString;
38
+ platform: z.ZodEnum<{
39
+ mattermost: "mattermost";
40
+ telegram: "telegram";
41
+ }>;
42
+ update_id: z.ZodString;
38
43
  channel_type: z.ZodOptional<z.ZodEnum<{
39
44
  telegram_private: "telegram_private";
40
45
  telegram_group: "telegram_group";
@@ -43,11 +48,6 @@ export declare const ReplyTarget: z.ZodObject<{
43
48
  mattermost_channel: "mattermost_channel";
44
49
  }>>;
45
50
  conversation: z.ZodString;
46
- platform: z.ZodEnum<{
47
- telegram: "telegram";
48
- mattermost: "mattermost";
49
- }>;
50
- update_id: z.ZodString;
51
51
  reply_to: z.ZodNullable<z.ZodString>;
52
52
  }, z.core.$strict>;
53
53
  export type ReplyTarget = z.infer<typeof ReplyTarget>;
package/dist/channels.js CHANGED
@@ -63,7 +63,10 @@ export class ChannelCore {
63
63
  }
64
64
  #pluginContext() { return pluginContext(this.runtime, this.env); }
65
65
  #hookFailure(event, taskId) {
66
- return (plugin, hook) => this.runtime.store.recordPluginHookFailure(plugin, hook, taskId ? { taskId } : { platform: event.platform, account: event.account, updateId: event.update_id });
66
+ return (plugin, hook) => {
67
+ this.runtime.logger.warn('Plugin hook failed', { plugin, hook, platform: event.platform, ...(taskId ? { task_id: taskId } : { update_id: event.update_id }) });
68
+ this.runtime.store.recordPluginHookFailure(plugin, hook, taskId ? { taskId } : { platform: event.platform, account: event.account, updateId: event.update_id });
69
+ };
67
70
  }
68
71
  async #send(event, reply, deliver, duplicate) {
69
72
  const plugins = this.runtime.plugins;
package/dist/cli.js CHANGED
@@ -7,7 +7,8 @@ import { stdin, stdout, stderr } from 'node:process';
7
7
  import { z } from 'zod';
8
8
  import { ardentHome, ConfigSchema, DEFAULT_PROFILE, initProfile, loadConfig, profilePath, redactedConfig, resolveReference, runtimeProblems } from './config.js';
9
9
  import { ArdentRuntime } from './runtime.js';
10
- import { TaskStore } from './store.js';
10
+ import { JOB_TICK_ERROR_CURSOR, readJobTickError, TaskStore } from './store.js';
11
+ import { ardentLogger } from './log.js';
11
12
  import { ardentOpenApi, createArdentApi } from './api.js';
12
13
  import { serve } from '@hono/node-server';
13
14
  import { listSkills, readSkill, setSkillEnabled } from './skills.js';
@@ -35,10 +36,13 @@ import { PlainTextFilter } from './live-text.js';
35
36
  import { developmentQuery, missionSubmitInput, previewInput } from './cli-commands.js';
36
37
  import { developmentPage, DevelopmentRecords, recordSkillChange } from './development.js';
37
38
  import { ArtifactTransfers } from './artifact-transfer.js';
39
+ import { inspectJournal, journalPolicy } from './journal.js';
40
+ import { backupProfile, parseDuration, pruneJournal } from './retention.js';
41
+ import { ArtifactStore } from './artifacts.js';
38
42
  function args(argv, extraValues = []) {
39
43
  const words = [];
40
44
  const options = new Map();
41
- const valued = new Set([...extraValues, 'env-file', 'profile', 'profile-path', 'api-port', 'template', 'prompt', 'prompt-file', 'idempotency-key', 'session-id', 'login-id', 'source', 'schedule-id', 'window-key', 'release-id', 'caller', 'context', 'expected-head', 'expected-policy-revision', 'mission-file', 'after', 'limit', 'kind', 'soul-file', 'identity-file', 'skills', 'model', 'peer', 'task', 'artifact', 'local-task']);
45
+ const valued = new Set([...extraValues, 'env-file', 'profile', 'profile-path', 'api-port', 'template', 'prompt', 'prompt-file', 'idempotency-key', 'session-id', 'login-id', 'source', 'schedule-id', 'window-key', 'release-id', 'caller', 'context', 'expected-head', 'expected-policy-revision', 'mission-file', 'after', 'limit', 'kind', 'soul-file', 'identity-file', 'skills', 'model', 'peer', 'task', 'artifact', 'local-task', 'db', 'older-than']);
42
46
  for (let i = 0; i < argv.length; i++) {
43
47
  const arg = argv[i];
44
48
  if (!arg)
@@ -75,6 +79,25 @@ async function environment(dir, explicitFile) {
75
79
  env[name] = val;
76
80
  return env;
77
81
  }
82
+ /** Read-only. A profile that has never run has no journal; doctor never fails on a journal it cannot open. */
83
+ async function profileJobTickError(dir) {
84
+ const path = join(dir, 'state', 'ardent.sqlite');
85
+ const stat = await lstat(path).catch(() => undefined);
86
+ if (!stat?.isFile() || stat.isSymbolicLink())
87
+ return null;
88
+ try {
89
+ const database = new Database(path, { readonly: true, fileMustExist: true });
90
+ try {
91
+ return readJobTickError(database);
92
+ }
93
+ finally {
94
+ database.close();
95
+ }
96
+ }
97
+ catch {
98
+ return null;
99
+ }
100
+ }
78
101
  function print(value) { stdout.write(`${JSON.stringify(value, null, 2)}\n`); }
79
102
  async function assertNoGateway(dir) {
80
103
  const lock = await readFile(join(dir, 'state', 'gateway.lock'), 'utf8').catch((error) => {
@@ -114,6 +137,10 @@ Commands:
114
137
  jobs definitions status Show installed job definitions
115
138
  context status | compact Inspect or compact a session context
116
139
  admission status | close --release-id ID Inspect or close the admission fence
140
+ journal status [--db FILE] [--json] Report whether the journal holds active, unknown or unsupported work (read-only)
141
+ journal policy Print the journal table classification
142
+ backup <dir> [--artifacts] Copy the journal (online, consistent) and optionally the artifacts
143
+ prune --older-than 90d [--dry-run] Delete finished tasks older than that and what belongs only to them
117
144
  a2a discover <peer> | call <peer> Talk to a configured A2A peer
118
145
  a2a team-card Print the Hermes team card (a2a.hermes_compat)
119
146
  openapi export Print the management OpenAPI document
@@ -155,6 +182,42 @@ async function main() {
155
182
  print(entries.filter(entry => entry.isDirectory()).map(entry => ({ name: entry.name })));
156
183
  return;
157
184
  }
185
+ if (command === 'journal') {
186
+ // Read-only and independent of config and plugins, so it also answers for a profile that cannot start.
187
+ // Output is always JSON; --json is accepted for scripts that ask for it explicitly.
188
+ if (subcommand === 'policy') {
189
+ print(journalPolicy());
190
+ return;
191
+ }
192
+ if (subcommand === 'status') {
193
+ const db = value(parsed.options, 'db');
194
+ const path = db ? resolvePath(db) : join(dir, 'state', 'ardent.sqlite');
195
+ print({ ardent_version: ARDENT_VERSION, ...(db ? {} : { profile }), ...await inspectJournal(path) });
196
+ return;
197
+ }
198
+ throw new Error('Use journal status [--db FILE] or journal policy');
199
+ }
200
+ if (command === 'backup') {
201
+ // Needs no valid configuration: a backup is taken before risky changes too.
202
+ if (!subcommand)
203
+ throw new Error('Use backup <new directory> [--artifacts]');
204
+ print(await backupProfile(dir, subcommand, { artifacts: parsed.options.has('artifacts') }));
205
+ return;
206
+ }
207
+ if (command === 'prune') {
208
+ const olderThan = value(parsed.options, 'older-than');
209
+ if (!olderThan)
210
+ throw new Error('Use prune --older-than 90d [--dry-run]');
211
+ const loadedForPrune = await loadConfig(dir);
212
+ const store = new TaskStore(join(dir, 'state', 'ardent.sqlite'));
213
+ try {
214
+ print(await pruneJournal(store, new ArtifactStore(join(dir, 'artifacts'), loadedForPrune.config.artifacts.max_bytes), { olderThanMs: parseDuration(olderThan), dryRun: parsed.options.has('dry-run') }));
215
+ }
216
+ finally {
217
+ store.close();
218
+ }
219
+ return;
220
+ }
158
221
  const loaded = await loadConfig(dir);
159
222
  const env = await environment(dir, value(parsed.options, 'env-file'));
160
223
  if (command === 'acceptance') {
@@ -260,6 +323,7 @@ async function main() {
260
323
  if (action === 'status') {
261
324
  let activeJobs = 0;
262
325
  let unknownJobs = 0;
326
+ let lastTickError = null;
263
327
  const dbPath = join(dir, 'state', 'ardent.sqlite');
264
328
  const dbStat = await lstat(dbPath);
265
329
  if (!dbStat.isFile() || dbStat.isSymbolicLink())
@@ -272,12 +336,13 @@ async function main() {
272
336
  activeJobs = count.parse(database.prepare("SELECT count(*) AS n FROM job_windows WHERE state IN ('queued','running','retry')").get()).n;
273
337
  unknownJobs = count.parse(database.prepare("SELECT count(*) AS n FROM job_windows WHERE state='unknown'").get()).n;
274
338
  }
339
+ lastTickError = readJobTickError(database);
275
340
  }
276
341
  finally {
277
342
  database.close();
278
343
  }
279
344
  print({ profile, revision: validated.definitions.revision, sha256, job_count: validated.job_count,
280
- active_jobs: activeJobs, unknown_jobs: unknownJobs, last_validation_error: null });
345
+ active_jobs: activeJobs, unknown_jobs: unknownJobs, last_validation_error: null, last_tick_error: lastTickError });
281
346
  return;
282
347
  }
283
348
  throw new Error('Use jobs definitions validate or jobs definitions status');
@@ -319,7 +384,8 @@ async function main() {
319
384
  return;
320
385
  }
321
386
  if (command === 'doctor') {
322
- print({ profile: loaded.config.profile, config_valid: true, runtime_problems: runtimeProblems(loaded.config, env), checked_at: new Date().toISOString() });
387
+ print({ profile: loaded.config.profile, config_valid: true, runtime_problems: runtimeProblems(loaded.config, env),
388
+ last_job_tick_error: await profileJobTickError(dir), checked_at: new Date().toISOString() });
323
389
  return;
324
390
  }
325
391
  if (command === 'a2a' && subcommand === 'team-card') {
@@ -500,10 +566,12 @@ async function main() {
500
566
  }
501
567
  const lockPath = join(dir, 'state', 'gateway.lock');
502
568
  const lock = await acquireGatewayLock(lockPath);
569
+ const logger = ardentLogger().child({ profile: loaded.config.profile });
503
570
  let runtime;
504
571
  let shutdownUnsettled = false;
505
572
  try {
506
573
  runtime = new ArdentRuntime(dir, loaded.config, env);
574
+ runtime.logger = ardentLogger({ requestContext: false }).child({ profile: loaded.config.profile });
507
575
  await runtime.usePlugins(plugins, env);
508
576
  await runtime.prepareGateway(env);
509
577
  // Interrupted tasks that recovery left running resume first, ahead of queued work.
@@ -518,6 +586,22 @@ async function main() {
518
586
  sweepArtifacts();
519
587
  const artifactSweep = setInterval(sweepArtifacts, 3_600_000);
520
588
  artifactSweep.unref();
589
+ // Scheduled retention (retention.enabled): once a day, first after ten minutes.
590
+ const retention = loaded.config.retention;
591
+ let retentionRun;
592
+ const prune = () => {
593
+ if (!runtime || retentionRun)
594
+ return;
595
+ retentionRun = pruneJournal(runtime.store, runtime.artifacts, { olderThanMs: retention.older_than_days * 86_400_000 })
596
+ .then(result => { if (result.tasks)
597
+ logger.info('Journal retention pruned tasks', { tasks: result.tasks, rows: result.rows, artifacts: result.artifacts, cutoff: result.cutoff }); })
598
+ .catch((error) => { logger.error('Journal retention failed', { err: error }); })
599
+ .finally(() => { retentionRun = undefined; });
600
+ };
601
+ const retentionStart = retention.enabled ? setTimeout(prune, 600_000) : undefined;
602
+ const retentionTimer = retention.enabled ? setInterval(prune, 86_400_000) : undefined;
603
+ retentionStart?.unref();
604
+ retentionTimer?.unref();
521
605
  const jobPath = join(dir, 'jobs', 'active.json');
522
606
  const hasJobs = await lstat(jobPath).then(stat => {
523
607
  if (!stat.isFile() || stat.isSymbolicLink())
@@ -532,6 +616,8 @@ async function main() {
532
616
  const jobRegistry = pluginJobHandlers(plugins, ctx, builtinJobHandlers(runtime, env));
533
617
  const ownership = composeOwnershipChecks(plugins.flatMap((plugin) => plugin.jobOwnership ? [plugin.jobOwnership(ctx)] : []));
534
618
  const jobEngine = hasJobs ? new JobEngine(runtime.store.db, dir, loaded.config.profile, jobRegistry, ownership) : undefined;
619
+ if (jobEngine)
620
+ jobEngine.logger = runtime.logger;
535
621
  if (jobEngine)
536
622
  await jobEngine.load();
537
623
  if (jobEngine)
@@ -539,14 +625,15 @@ async function main() {
539
625
  // The API reloads rotated credentials from the same file the gateway started from.
540
626
  const envFile = value(parsed.options, 'env-file');
541
627
  const artifactTransfers = new ArtifactTransfers(runtime, env);
542
- const api = createArdentApi(runtime, loaded, env, jobEngine, { ...(envFile ? { envFile: resolvePath(envFile) } : {}), artifactTransfers });
628
+ let a2aSurface;
629
+ const api = createArdentApi(runtime, loaded, env, jobEngine, { ...(envFile ? { envFile: resolvePath(envFile) } : {}), artifactTransfers, logger,
630
+ peerAuthenticator: () => a2aSurface?.peerAuthenticator, serviceEnv: new Set(Object.keys(process.env)) });
543
631
  const server = serve({ fetch: api.fetch, hostname: loaded.config.api.host, port: loaded.config.api.port });
544
632
  await new Promise((resolve, reject) => { server.once('listening', resolve); server.once('error', reject); });
545
633
  // Imports a previous process left unfinished resume from their retained bytes.
546
634
  artifactTransfers.resumePending();
547
635
  let a2aHttp;
548
636
  let a2aGrpc;
549
- let a2aSurface;
550
637
  // Shutdown first stops intake (polling, listening, new job windows and
551
638
  // outbox claims), then drains, and only then aborts in-flight delivery.
552
639
  const channelAbort = new AbortController();
@@ -559,7 +646,13 @@ async function main() {
559
646
  if (jobEngine) {
560
647
  const tickJobs = () => {
561
648
  const operation = jobEngine.tick(new Date(), deliveryAbort.signal, channelAbort.signal)
562
- .catch(error => runtime?.store.setCursor('jobs:last_error', error instanceof Error ? error.message.slice(0, 500) : 'unknown'));
649
+ // A successful tick clears the reported failure, so status shows only a current one.
650
+ .then(() => { runtime?.store.clearJobTickError(); })
651
+ .catch((error) => {
652
+ // Reported by /api/v1/status, /api/v1/jobs/definitions/status and `ardent doctor`.
653
+ runtime?.store.setCursor(JOB_TICK_ERROR_CURSOR, error instanceof Error ? error.message.slice(0, 500) : 'unknown');
654
+ logger.error('Job engine tick failed', { err: error });
655
+ });
563
656
  noticeRuns.add(operation);
564
657
  void operation.finally(() => noticeRuns.delete(operation));
565
658
  };
@@ -613,6 +706,11 @@ async function main() {
613
706
  if (jobTimer)
614
707
  clearInterval(jobTimer);
615
708
  clearInterval(artifactSweep);
709
+ if (retentionStart)
710
+ clearTimeout(retentionStart);
711
+ if (retentionTimer)
712
+ clearInterval(retentionTimer);
713
+ await retentionRun;
616
714
  channelAbort.abort();
617
715
  shutdownUnsettled = !(await runtime.drain(30_000));
618
716
  // Replies and notices admitted before shutdown may still be sending.
@@ -657,7 +755,7 @@ async function main() {
657
755
  await lock.release();
658
756
  }
659
757
  if (shutdownUnsettled) {
660
- stderr.write('Gateway shutdown left unresolved work; interrupted tasks will be marked unknown on restart.\n');
758
+ stderr.write('Gateway shutdown left unresolved work; on restart execution recovery resumes or holds interrupted tasks (they are marked unknown when execution.recovery.enabled is false).\n');
661
759
  process.exit(1);
662
760
  }
663
761
  return;
package/dist/config.d.ts CHANGED
@@ -117,6 +117,10 @@ export declare const ConfigSchema: z.ZodObject<{
117
117
  max_concurrent_tasks_per_peer: z.ZodDefault<z.ZodNumber>;
118
118
  trusted_proxies: z.ZodDefault<z.ZodArray<z.ZodString>>;
119
119
  }, z.core.$strict>>;
120
+ provider: z.ZodOptional<z.ZodObject<{
121
+ organization: z.ZodString;
122
+ url: z.ZodString;
123
+ }, z.core.$strict>>;
120
124
  skill: z.ZodOptional<z.ZodObject<{
121
125
  id: z.ZodString;
122
126
  name: z.ZodString;
@@ -160,6 +164,10 @@ export declare const ConfigSchema: z.ZodObject<{
160
164
  artifacts: z.ZodDefault<z.ZodObject<{
161
165
  max_bytes: z.ZodDefault<z.ZodNumber>;
162
166
  }, z.core.$strict>>;
167
+ retention: z.ZodDefault<z.ZodObject<{
168
+ enabled: z.ZodDefault<z.ZodBoolean>;
169
+ older_than_days: z.ZodDefault<z.ZodNumber>;
170
+ }, z.core.$strict>>;
163
171
  plugins: z.ZodDefault<z.ZodArray<z.ZodString>>;
164
172
  api: z.ZodDefault<z.ZodObject<{
165
173
  host: z.ZodDefault<z.ZodString>;
@@ -185,7 +193,7 @@ export declare function revision(text: string): string;
185
193
  export declare function parseConfig(text: string): ArdentConfig;
186
194
  export declare function loadConfig(dir: string): Promise<LoadedConfig>;
187
195
  export declare function resolveReference(value: string, env?: NodeJS.ProcessEnv): string | undefined;
188
- /** The configured task concurrency, before the runtime's cap of 4. */
196
+ /** The configured task concurrency: how many tasks the runtime runs at once. */
189
197
  export declare function maxParallelTasks(config: ArdentConfig): number;
190
198
  /** Advisory notices, prefixed `notice:`. They never make a profile unready. */
191
199
  export declare function configNotices(config: ArdentConfig): string[];
package/dist/config.js CHANGED
@@ -6,6 +6,7 @@ import { fileURLToPath } from 'node:url';
6
6
  import YAML from 'yaml';
7
7
  import { z } from 'zod';
8
8
  import { instanceRefProblem } from './execution.js';
9
+ import { conflict, invalidRequest } from './errors.js';
9
10
  const envName = /^[A-Z][A-Z0-9_]*$/;
10
11
  const pathName = /^[A-Za-z0-9._-]+\.md$/;
11
12
  function safeUrl(value) {
@@ -64,7 +65,7 @@ export const ConfigSchema = z.object({
64
65
  timezone: ianaTimezone.default(systemTimezone),
65
66
  identity: z.object({ soul_file: z.string().regex(pathName).default('SOUL.md'), identity_file: z.string().regex(pathName).default('IDENTITY.md') }).strict().default({ soul_file: 'SOUL.md', identity_file: 'IDENTITY.md' }),
66
67
  execution: z.object({ backend: z.enum(['llamacpp', 'codex']), max_model_steps: z.number().int().min(1).max(200), max_tool_calls: z.number().int().min(0).max(500),
67
- /** Tasks running at once (the runtime caps it at 4). */
68
+ /** Tasks running at once. */
68
69
  max_parallel_tasks: z.number().int().min(1).max(16).optional(),
69
70
  /** Parallel-eligible tool calls in flight at once within one model turn. */
70
71
  max_parallel_tool_calls: z.number().int().min(1).max(16).default(DEFAULT_MAX_PARALLEL_TOOL_CALLS),
@@ -87,6 +88,8 @@ export const ConfigSchema = z.object({
87
88
  hermes_compat: z.boolean().default(false),
88
89
  /** Request and task limits. `trusted_proxies` lists the reverse proxies whose X-Forwarded-For is believed; by default none is. */
89
90
  rate_limit: z.object({ enabled: z.boolean().default(true), ip_requests_per_minute: z.number().int().min(1).max(1_000_000).default(600), ip_burst: z.number().int().min(1).max(1_000_000).default(120), peer_requests_per_minute: z.number().int().min(1).max(1_000_000).default(300), peer_burst: z.number().int().min(1).max(1_000_000).default(60), max_concurrent_tasks_per_peer: z.number().int().min(1).max(100_000).default(16), trusted_proxies: z.array(z.string().min(1).max(64)).max(64).default([]) }).strict().default(a2aRateLimitDefault),
91
+ /** Agent Card provider: the organization that runs this agent. Defaults to Ardent and its repository. */
92
+ provider: z.object({ organization: z.string().trim().min(1).max(100), url: z.string().url().max(500).refine(value => /^https?:\/\//.test(value), 'must be an http(s) URL') }).strict().optional(),
90
93
  /** Agent Card skill advertised to peers. */
91
94
  skill: z.object({ id: z.string().regex(/^[a-z][a-z0-9-]{0,63}$/), name: z.string().min(1).max(100), description: z.string().min(1).max(500), tags: z.array(z.string().min(1).max(40)).max(10).default([]), example: z.string().min(1).max(300).optional() }).strict().optional() }).strict().default(a2aDefault),
92
95
  channels: z.object({ telegram: TelegramChannel.default(TelegramChannel.parse({})), mattermost: MattermostChannel.default(MattermostChannel.parse({})) }).strict().default({ telegram: TelegramChannel.parse({}), mattermost: MattermostChannel.parse({}) }),
@@ -96,6 +99,12 @@ export const ConfigSchema = z.object({
96
99
  }).strict().default({ magnus_control: magnusControlDefault }),
97
100
  /** Artifact store limits. `max_bytes` bounds each stored artifact (default 2 MiB, at most 64 MiB). */
98
101
  artifacts: z.object({ max_bytes: z.number().int().min(1024).max(64 * 1024 * 1024).default(2 * 1024 * 1024) }).strict().default({ max_bytes: 2 * 1024 * 1024 }),
102
+ /**
103
+ * Scheduled journal retention, off unless enabled: the gateway runs `ardent prune` once a day for
104
+ * finished tasks older than `older_than_days`.
105
+ */
106
+ retention: z.object({ enabled: z.boolean().default(false), older_than_days: z.number().int().min(1).max(3650).default(90) }).strict()
107
+ .default({ enabled: false, older_than_days: 90 }),
99
108
  /** Plugin modules loaded by the gateway (npm package names, absolute paths, or file:// URLs). */
100
109
  plugins: z.array(pluginSpecifier).max(32).default([]),
101
110
  api: z.object({ host: z.string().min(1).default('127.0.0.1'), port: z.number().int().min(1).max(65535).default(9910), token_env: z.string().regex(envName).default('ARDENT_API_TOKEN') }).strict().default({ host: '127.0.0.1', port: 9910, token_env: 'ARDENT_API_TOKEN' })
@@ -118,11 +127,11 @@ export function revision(text) { return createHash('sha256').update(text).digest
118
127
  export function parseConfig(text) {
119
128
  const doc = YAML.parseDocument(text, { uniqueKeys: true });
120
129
  if (doc.errors.length)
121
- throw new Error(`Invalid YAML: ${doc.errors[0]?.message ?? 'unknown error'}`);
130
+ throw invalidRequest(`Invalid YAML: ${doc.errors[0]?.message ?? 'unknown error'}`);
122
131
  const value = doc.toJS();
123
132
  const parsed = ConfigSchema.safeParse(value);
124
133
  if (!parsed.success)
125
- throw new Error(`Invalid Ardent config: ${parsed.error.issues.map(i => `${i.path.join('.')}: ${i.message}`).join('; ')}`);
134
+ throw invalidRequest(`Invalid Ardent config: ${parsed.error.issues.map(i => `${i.path.join('.')}: ${i.message}`).join('; ')}`);
126
135
  return parsed.data;
127
136
  }
128
137
  export async function loadConfig(dir) {
@@ -136,7 +145,7 @@ export function resolveReference(value, env = process.env) {
136
145
  return value;
137
146
  return env[match[1] ?? ''];
138
147
  }
139
- /** The configured task concurrency, before the runtime's cap of 4. */
148
+ /** The configured task concurrency: how many tasks the runtime runs at once. */
140
149
  export function maxParallelTasks(config) {
141
150
  return config.execution.max_parallel_tasks ?? config.execution.max_parallel_tools ?? DEFAULT_MAX_PARALLEL_TASKS;
142
151
  }
@@ -262,14 +271,14 @@ export async function saveConfig(dir, nextText, expectedRevision) {
262
271
  const lockPath = join(dir, '.config.write.lock');
263
272
  const lock = await open(lockPath, 'wx', 0o600).catch((error) => {
264
273
  if (error && typeof error === 'object' && 'code' in error && error.code === 'EEXIST')
265
- throw new Error('Configuration edit is already in progress');
274
+ throw conflict('Configuration edit is already in progress');
266
275
  throw error;
267
276
  });
268
277
  let tmp;
269
278
  try {
270
279
  const current = await loadConfig(dir);
271
280
  if (current.revision !== expectedRevision)
272
- throw new Error('Configuration revision conflict');
281
+ throw conflict('Configuration revision conflict');
273
282
  parseConfig(nextText);
274
283
  tmp = join(dirname(path), `.config.${randomUUID()}.tmp`);
275
284
  await writeFile(tmp, nextText, { mode: 0o600, flag: 'wx' });
@@ -9,8 +9,8 @@ export declare const DevelopmentSource: z.ZodObject<{
9
9
  artifact: "artifact";
10
10
  identity: "identity";
11
11
  memory: "memory";
12
- skill: "skill";
13
12
  url: "url";
13
+ skill: "skill";
14
14
  note: "note";
15
15
  }>;
16
16
  ref: z.ZodString;
@@ -43,8 +43,8 @@ export declare const DevelopmentRecordSchema: z.ZodObject<{
43
43
  artifact: "artifact";
44
44
  identity: "identity";
45
45
  memory: "memory";
46
- skill: "skill";
47
46
  url: "url";
47
+ skill: "skill";
48
48
  note: "note";
49
49
  }>;
50
50
  ref: z.ZodString;
@@ -63,8 +63,8 @@ export declare const DevelopmentNoteInput: z.ZodObject<{
63
63
  artifact: "artifact";
64
64
  identity: "identity";
65
65
  memory: "memory";
66
- skill: "skill";
67
66
  url: "url";
67
+ skill: "skill";
68
68
  note: "note";
69
69
  }>;
70
70
  ref: z.ZodString;
@@ -1,6 +1,7 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { z } from 'zod';
3
3
  import { identityHistory, readIdentity } from './identity.js';
4
+ import { invalidRequest } from './errors.js';
4
5
  const digest = z.string().regex(/^[a-f0-9]{64}$/);
5
6
  /** A short machine-readable category, such as `self_understanding`, `method`, `lesson` or `skill_change`. */
6
7
  export const DevelopmentKind = z.string().regex(/^[a-z][a-z0-9_]{0,63}$/);
@@ -76,7 +77,7 @@ export function decodeDevelopmentCursor(value) {
76
77
  return { ms, id };
77
78
  }
78
79
  catch {
79
- throw new Error('Invalid development cursor');
80
+ throw invalidRequest('Invalid development cursor');
80
81
  }
81
82
  }
82
83
  const historyName = /^(\d+)-([a-f0-9]{12})-([a-f0-9]{64})\.md$/;
@@ -0,0 +1,54 @@
1
+ import { HiveError, type HiveErrorOptions } from '@hivemagnus/hive-common/errors';
2
+ export { HiveError, isHiveError } from '@hivemagnus/hive-common/errors';
3
+ /**
4
+ * Typed errors of the management API. Each one carries its HTTP status and a
5
+ * stable code, so the API maps it explicitly instead of reading the message.
6
+ * The messages are unchanged from the plain errors they replace, so the CLI,
7
+ * which prints `error.message`, reads the same.
8
+ */
9
+ export declare const ErrorCode: {
10
+ readonly invalid: "INVALID_REQUEST";
11
+ readonly notFound: "NOT_FOUND";
12
+ readonly conflict: "CONFLICT";
13
+ readonly unavailable: "DEPENDENCY_UNAVAILABLE";
14
+ /** The profile refuses new work: it is draining for shutdown or its admission is fenced for a rollback. */
15
+ readonly notAccepting: "NOT_ACCEPTING_WORK";
16
+ readonly tooLarge: "BODY_TOO_LARGE";
17
+ readonly internal: "INTERNAL_ERROR";
18
+ };
19
+ /** 400: the request is malformed or names something it may not. */
20
+ export declare const invalidRequest: (message: string, options?: Omit<HiveErrorOptions, "status">) => HiveError;
21
+ /** 404: the task, session, skill, peer or record does not exist. */
22
+ export declare const notFound: (message: string, options?: Omit<HiveErrorOptions, "status">) => HiveError;
23
+ /** 409: the request conflicts with the current state (a revision, an idempotency key, an edit in progress). */
24
+ export declare const conflict: (message: string, options?: Omit<HiveErrorOptions, "status">) => HiveError;
25
+ /** 503: a configured dependency (a provider, channel, peer or HiveMem) is missing, unconfigured or not answering. */
26
+ export declare const dependencyUnavailable: (message: string, options?: Omit<HiveErrorOptions, "status">) => HiveError;
27
+ /** 503: the profile does not accept new work right now. */
28
+ export declare const notAcceptingWork: (message: string, options?: Omit<HiveErrorOptions, "status">) => HiveError;
29
+ /** The session exists, but for another caller or context. */
30
+ export declare class SessionMismatchError extends HiveError {
31
+ readonly name: string;
32
+ constructor(message?: string);
33
+ }
34
+ /** A finished task cannot be paused. `code` stays `TASK_TERMINAL` for code that checked it; the API answers 409 CONFLICT. */
35
+ export declare class TaskTerminalError extends HiveError {
36
+ readonly name: string;
37
+ constructor(message: string);
38
+ }
39
+ /** The error's message, or a fallback for a thrown non-error. */
40
+ export declare const messageOf: (error: unknown, fallback: string) => string;
41
+ /**
42
+ * Run a probe of an external dependency: a failure that is not already typed
43
+ * is reported as the dependency being unavailable (503), with its message.
44
+ */
45
+ export declare function dependency<T>(probe: () => Promise<T>, fallback?: string): Promise<T>;
46
+ /**
47
+ * How Ardent before 3.4 classified an error by its message. Kept only for
48
+ * errors that plugin routes throw without a status, so a plugin written for
49
+ * an earlier release answers as it did; a plugin should throw a `HiveError`
50
+ * (for example `invalidRequest()`), which keeps its status and code.
51
+ */
52
+ export declare function legacyStatus(message: string): 400 | 404 | 409 | 500 | 503;
53
+ /** A plugin route's untyped error as the typed error Ardent before 3.4 would have answered with (a 500 stays untyped). */
54
+ export declare function legacyPluginError(error: unknown): unknown;
package/dist/errors.js ADDED
@@ -0,0 +1,76 @@
1
+ import { HiveError, isHiveError } from '@hivemagnus/hive-common/errors';
2
+ import { z } from 'zod';
3
+ export { HiveError, isHiveError } from '@hivemagnus/hive-common/errors';
4
+ /**
5
+ * Typed errors of the management API. Each one carries its HTTP status and a
6
+ * stable code, so the API maps it explicitly instead of reading the message.
7
+ * The messages are unchanged from the plain errors they replace, so the CLI,
8
+ * which prints `error.message`, reads the same.
9
+ */
10
+ export const ErrorCode = {
11
+ invalid: 'INVALID_REQUEST',
12
+ notFound: 'NOT_FOUND',
13
+ conflict: 'CONFLICT',
14
+ unavailable: 'DEPENDENCY_UNAVAILABLE',
15
+ /** The profile refuses new work: it is draining for shutdown or its admission is fenced for a rollback. */
16
+ notAccepting: 'NOT_ACCEPTING_WORK',
17
+ tooLarge: 'BODY_TOO_LARGE',
18
+ internal: 'INTERNAL_ERROR',
19
+ };
20
+ const make = (code, status) => (message, options = {}) => new HiveError(code, message, { ...options, status });
21
+ /** 400: the request is malformed or names something it may not. */
22
+ export const invalidRequest = make(ErrorCode.invalid, 400);
23
+ /** 404: the task, session, skill, peer or record does not exist. */
24
+ export const notFound = make(ErrorCode.notFound, 404);
25
+ /** 409: the request conflicts with the current state (a revision, an idempotency key, an edit in progress). */
26
+ export const conflict = make(ErrorCode.conflict, 409);
27
+ /** 503: a configured dependency (a provider, channel, peer or HiveMem) is missing, unconfigured or not answering. */
28
+ export const dependencyUnavailable = make(ErrorCode.unavailable, 503);
29
+ /** 503: the profile does not accept new work right now. */
30
+ export const notAcceptingWork = make(ErrorCode.notAccepting, 503);
31
+ /** The session exists, but for another caller or context. */
32
+ export class SessionMismatchError extends HiveError {
33
+ name = 'SessionMismatchError';
34
+ constructor(message = 'Session caller or context mismatch') { super(ErrorCode.invalid, message, { status: 400 }); }
35
+ }
36
+ /** A finished task cannot be paused. `code` stays `TASK_TERMINAL` for code that checked it; the API answers 409 CONFLICT. */
37
+ export class TaskTerminalError extends HiveError {
38
+ name = 'TaskTerminalError';
39
+ constructor(message) { super('TASK_TERMINAL', message, { status: 409 }); }
40
+ }
41
+ /** The error's message, or a fallback for a thrown non-error. */
42
+ export const messageOf = (error, fallback) => error instanceof Error && error.message ? error.message : fallback;
43
+ /**
44
+ * Run a probe of an external dependency: a failure that is not already typed
45
+ * is reported as the dependency being unavailable (503), with its message.
46
+ */
47
+ export async function dependency(probe, fallback = 'Dependency unavailable') {
48
+ try {
49
+ return await probe();
50
+ }
51
+ catch (error) {
52
+ if (isHiveError(error))
53
+ throw error;
54
+ throw dependencyUnavailable(messageOf(error, fallback), { cause: error });
55
+ }
56
+ }
57
+ /**
58
+ * How Ardent before 3.4 classified an error by its message. Kept only for
59
+ * errors that plugin routes throw without a status, so a plugin written for
60
+ * an earlier release answers as it did; a plugin should throw a `HiveError`
61
+ * (for example `invalidRequest()`), which keeps its status and code.
62
+ */
63
+ export function legacyStatus(message) {
64
+ return /revision conflict|Idempotency key reused|already in progress/i.test(message) ? 409
65
+ : /not found|absent/i.test(message) ? 404
66
+ : /unavailable|stale|unconfigured|missing|login required|wrong auth mode|CODEX_LOGIN_REQUIRED|CODEX_WRONG_AUTH_MODE|fetch failed|ECONNREFUSED|ETIMEDOUT|timeout/i.test(message) ? 503
67
+ : /invalid|must be|exceeds|requires/i.test(message) ? 400 : 500;
68
+ }
69
+ const LEGACY_CODE = { 400: ErrorCode.invalid, 404: ErrorCode.notFound, 409: ErrorCode.conflict, 503: ErrorCode.unavailable };
70
+ /** A plugin route's untyped error as the typed error Ardent before 3.4 would have answered with (a 500 stays untyped). */
71
+ export function legacyPluginError(error) {
72
+ if (isHiveError(error) || !(error instanceof Error))
73
+ return error;
74
+ const status = error instanceof z.ZodError || error instanceof SyntaxError ? 400 : legacyStatus(error.message);
75
+ return status === 500 ? error : new HiveError(LEGACY_CODE[status], error.message, { status, cause: error });
76
+ }