@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
@@ -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
@@ -37,10 +37,12 @@ import { developmentQuery, missionSubmitInput, previewInput } from './cli-comman
37
37
  import { developmentPage, DevelopmentRecords, recordSkillChange } from './development.js';
38
38
  import { ArtifactTransfers } from './artifact-transfer.js';
39
39
  import { inspectJournal, journalPolicy } from './journal.js';
40
+ import { backupProfile, parseDuration, pruneJournal } from './retention.js';
41
+ import { ArtifactStore } from './artifacts.js';
40
42
  function args(argv, extraValues = []) {
41
43
  const words = [];
42
44
  const options = new Map();
43
- 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']);
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']);
44
46
  for (let i = 0; i < argv.length; i++) {
45
47
  const arg = argv[i];
46
48
  if (!arg)
@@ -137,6 +139,8 @@ Commands:
137
139
  admission status | close --release-id ID Inspect or close the admission fence
138
140
  journal status [--db FILE] [--json] Report whether the journal holds active, unknown or unsupported work (read-only)
139
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
140
144
  a2a discover <peer> | call <peer> Talk to a configured A2A peer
141
145
  a2a team-card Print the Hermes team card (a2a.hermes_compat)
142
146
  openapi export Print the management OpenAPI document
@@ -193,6 +197,27 @@ async function main() {
193
197
  }
194
198
  throw new Error('Use journal status [--db FILE] or journal policy');
195
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
+ }
196
221
  const loaded = await loadConfig(dir);
197
222
  const env = await environment(dir, value(parsed.options, 'env-file'));
198
223
  if (command === 'acceptance') {
@@ -546,6 +571,7 @@ async function main() {
546
571
  let shutdownUnsettled = false;
547
572
  try {
548
573
  runtime = new ArdentRuntime(dir, loaded.config, env);
574
+ runtime.logger = ardentLogger({ requestContext: false }).child({ profile: loaded.config.profile });
549
575
  await runtime.usePlugins(plugins, env);
550
576
  await runtime.prepareGateway(env);
551
577
  // Interrupted tasks that recovery left running resume first, ahead of queued work.
@@ -560,6 +586,22 @@ async function main() {
560
586
  sweepArtifacts();
561
587
  const artifactSweep = setInterval(sweepArtifacts, 3_600_000);
562
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();
563
605
  const jobPath = join(dir, 'jobs', 'active.json');
564
606
  const hasJobs = await lstat(jobPath).then(stat => {
565
607
  if (!stat.isFile() || stat.isSymbolicLink())
@@ -574,6 +616,8 @@ async function main() {
574
616
  const jobRegistry = pluginJobHandlers(plugins, ctx, builtinJobHandlers(runtime, env));
575
617
  const ownership = composeOwnershipChecks(plugins.flatMap((plugin) => plugin.jobOwnership ? [plugin.jobOwnership(ctx)] : []));
576
618
  const jobEngine = hasJobs ? new JobEngine(runtime.store.db, dir, loaded.config.profile, jobRegistry, ownership) : undefined;
619
+ if (jobEngine)
620
+ jobEngine.logger = runtime.logger;
577
621
  if (jobEngine)
578
622
  await jobEngine.load();
579
623
  if (jobEngine)
@@ -581,14 +625,15 @@ async function main() {
581
625
  // The API reloads rotated credentials from the same file the gateway started from.
582
626
  const envFile = value(parsed.options, 'env-file');
583
627
  const artifactTransfers = new ArtifactTransfers(runtime, env);
584
- const api = createArdentApi(runtime, loaded, env, jobEngine, { ...(envFile ? { envFile: resolvePath(envFile) } : {}), artifactTransfers, logger });
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)) });
585
631
  const server = serve({ fetch: api.fetch, hostname: loaded.config.api.host, port: loaded.config.api.port });
586
632
  await new Promise((resolve, reject) => { server.once('listening', resolve); server.once('error', reject); });
587
633
  // Imports a previous process left unfinished resume from their retained bytes.
588
634
  artifactTransfers.resumePending();
589
635
  let a2aHttp;
590
636
  let a2aGrpc;
591
- let a2aSurface;
592
637
  // Shutdown first stops intake (polling, listening, new job windows and
593
638
  // outbox claims), then drains, and only then aborts in-flight delivery.
594
639
  const channelAbort = new AbortController();
@@ -601,6 +646,8 @@ async function main() {
601
646
  if (jobEngine) {
602
647
  const tickJobs = () => {
603
648
  const operation = jobEngine.tick(new Date(), deliveryAbort.signal, channelAbort.signal)
649
+ // A successful tick clears the reported failure, so status shows only a current one.
650
+ .then(() => { runtime?.store.clearJobTickError(); })
604
651
  .catch((error) => {
605
652
  // Reported by /api/v1/status, /api/v1/jobs/definitions/status and `ardent doctor`.
606
653
  runtime?.store.setCursor(JOB_TICK_ERROR_CURSOR, error instanceof Error ? error.message.slice(0, 500) : 'unknown');
@@ -659,6 +706,11 @@ async function main() {
659
706
  if (jobTimer)
660
707
  clearInterval(jobTimer);
661
708
  clearInterval(artifactSweep);
709
+ if (retentionStart)
710
+ clearTimeout(retentionStart);
711
+ if (retentionTimer)
712
+ clearInterval(retentionTimer);
713
+ await retentionRun;
662
714
  channelAbort.abort();
663
715
  shutdownUnsettled = !(await runtime.drain(30_000));
664
716
  // Replies and notices admitted before shutdown may still be sending.
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
+ }
package/dist/identity.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { mkdir, open, readFile, readdir, rename, unlink, writeFile } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
+ import { conflict, invalidRequest, notFound } from './errors.js';
4
5
  function digest(text) { return createHash('sha256').update(text).digest('hex'); }
5
6
  function name(config, kind) { return kind === 'soul' ? config.identity.soul_file : config.identity.identity_file; }
6
7
  function historyDir(dir, kind) { return join(dir, 'state', 'identity-history', kind); }
@@ -9,20 +10,20 @@ export async function readIdentity(dir, config, kind) {
9
10
  const filename = name(config, kind);
10
11
  const text = await readFile(join(dir, filename), 'utf8');
11
12
  if (Buffer.byteLength(text) > 128 * 1024)
12
- throw new Error('Identity file exceeds 128 KiB');
13
+ throw invalidRequest('Identity file exceeds 128 KiB');
13
14
  return { kind, name: filename, text, revision: digest(text) };
14
15
  }
15
16
  export async function writeIdentity(dir, config, kind, nextText, expectedRevision) {
16
17
  if (!nextText.trim() || Buffer.byteLength(nextText) > 128 * 1024)
17
- throw new Error('Identity text must be 1 to 128 KiB');
18
+ throw invalidRequest('Identity text must be 1 to 128 KiB');
18
19
  const history = historyDir(dir, kind);
19
20
  await mkdir(history, { recursive: true, mode: 0o700 });
20
21
  const lockPath = join(history, '.write.lock');
21
- const lock = await open(lockPath, 'wx', 0o600).catch(() => { throw new Error('Identity edit is already in progress'); });
22
+ const lock = await open(lockPath, 'wx', 0o600).catch(() => { throw conflict('Identity edit is already in progress'); });
22
23
  try {
23
24
  const previous = await readIdentity(dir, config, kind);
24
25
  if (previous.revision !== expectedRevision)
25
- throw new Error('Identity revision conflict');
26
+ throw conflict('Identity revision conflict');
26
27
  await writeFile(join(history, `${Date.now()}-${randomUUID().replaceAll('-', '').slice(0, 12)}-${previous.revision}.md`), previous.text, { mode: 0o600, flag: 'wx' });
27
28
  const temporary = join(dir, `.${previous.name}.${randomUUID()}.tmp`);
28
29
  await writeFile(temporary, nextText, { mode: 0o600, flag: 'wx' });
@@ -44,8 +45,12 @@ export async function identityHistory(dir, kind) {
44
45
  export async function restoreIdentity(dir, config, kind, historyName, expectedRevision) {
45
46
  const revision = historyNamePattern.exec(historyName)?.[1];
46
47
  if (!revision)
47
- throw new Error('Invalid identity history entry');
48
- const text = await readFile(join(historyDir(dir, kind), historyName), 'utf8');
48
+ throw invalidRequest('Invalid identity history entry');
49
+ const text = await readFile(join(historyDir(dir, kind), historyName), 'utf8').catch((error) => {
50
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')
51
+ throw notFound('Identity history entry not found');
52
+ throw error;
53
+ });
49
54
  if (digest(text) !== revision)
50
55
  throw new Error('Identity history checksum mismatch');
51
56
  return writeIdentity(dir, config, kind, text, expectedRevision);
@@ -1,5 +1,6 @@
1
1
  import type Database from './sqlite.js';
2
2
  import { z } from 'zod';
3
+ import { type Logger } from './log.js';
3
4
  declare const definition: z.ZodObject<{
4
5
  id: z.ZodString;
5
6
  owner: z.ZodString;
@@ -161,6 +162,8 @@ export declare class JobEngine {
161
162
  readonly ownershipCheck: OwnershipCheck;
162
163
  readonly clock: () => number;
163
164
  readonly random: () => number;
165
+ /** Where failed, unknown and retried job windows are logged; the gateway sets it. */
166
+ logger: Logger;
164
167
  /** `clock` measures elapsed time within a tick; the injected tick time stays the timeline origin. */
165
168
  constructor(db: Database, profileDir: string, profile: string, registry: JobRegistry, ownershipCheck: OwnershipCheck, clock?: () => number, random?: () => number);
166
169
  load(): Promise<{
@@ -4,6 +4,7 @@ import { open, readFile, unlink } from 'node:fs/promises';
4
4
  import { join } from 'node:path';
5
5
  import { z } from 'zod';
6
6
  import { backoffDelay } from '@hivemagnus/hive-common/retry';
7
+ import { silentLogger } from './log.js';
7
8
  const identifier = z.string().regex(/^[a-z][a-z0-9._-]{0,79}$/);
8
9
  const jobId = z.string().regex(/^[a-z0-9][a-z0-9._-]{0,79}$/);
9
10
  const timezone = z.string().min(1).max(80).refine(value => {
@@ -153,6 +154,8 @@ export class JobEngine {
153
154
  ownershipCheck;
154
155
  clock;
155
156
  random;
157
+ /** Where failed, unknown and retried job windows are logged; the gateway sets it. */
158
+ logger = silentLogger;
156
159
  #lastValidationError = null;
157
160
  #lastActive = null;
158
161
  #busy = false;
@@ -448,6 +451,8 @@ export class JobEngine {
448
451
  retry++;
449
452
  else if (state === 'unknown')
450
453
  unknown++;
454
+ if (state !== 'completed')
455
+ this.logger[state === 'retry' ? 'info' : 'warn'](`Job window ${state}`, { job_id: job.id, window_key: window.window_key, attempt });
451
456
  }
452
457
  }
453
458
  return { scanned, claimed, completed, retry, unknown };
package/dist/journal.d.ts CHANGED
@@ -3,6 +3,17 @@
3
3
  * when a consumer would need to read the policy or status differently; adding
4
4
  * a table or a state value does not change it.
5
5
  */
6
+ /**
7
+ * Mattermost history claimed on a channel's first sight, never to be answered (it has no channel
8
+ * type: live and catch-up posts always record one). Such a row is finished, not admitted work.
9
+ */
10
+ /** task_recovery statuses: `active` ones count only while their task is running. */
11
+ export declare const TASK_RECOVERY_STATUSES: Readonly<{
12
+ readonly active: readonly ["ready", "reconciling"];
13
+ readonly uncertain: readonly ["awaiting_decision", "unsupported", "unknown"];
14
+ readonly terminal: readonly ["resumed", "resolved"];
15
+ }>;
16
+ export declare const SEEDED_INBOUND = "(inbound.platform='mattermost' AND inbound.channel_type='unknown')";
6
17
  export declare const JOURNAL_POLICY_VERSION = 1;
7
18
  /** A table whose `state` or `status` column says whether a row is still work. */
8
19
  export type JournalStateRule = {
@@ -26,7 +37,7 @@ export type JournalLedgerRule = {
26
37
  /** A table with its own rule, described in `description`. */
27
38
  export type JournalSpecialRule = {
28
39
  readonly kind: 'special';
29
- readonly rule: 'a2a_tasks' | 'a2a_team_child_claims' | 'a2a_request_receipts' | 'channel_inbound' | 'admission_fence';
40
+ readonly rule: 'a2a_tasks' | 'a2a_team_child_claims' | 'a2a_request_receipts' | 'channel_inbound' | 'admission_fence' | 'task_recovery';
30
41
  };
31
42
  export type JournalTableRule = (JournalStateRule | JournalPassiveRule | JournalLedgerRule | JournalSpecialRule) & {
32
43
  readonly description: string;
@@ -70,6 +81,10 @@ export declare function inspectJournalFile(path: string): JournalStatus;
70
81
  * of it. The database and its WAL are copied to a private directory, verified
71
82
  * by digest, and inspected there, so committed but uncheckpointed work in the
72
83
  * WAL is counted. Throws when the files change during inspection, which means
73
- * a gateway is writing: a running profile is never idle.
84
+ * a gateway is writing. It does not check the gateway lock: an idle gateway
85
+ * that writes nothing during the copy can be reported idle, so stop the
86
+ * profile (or hold its gateway lock) before relying on `idle` for a snapshot.
87
+ * Tables an extension created and this policy does not classify count as
88
+ * `unsupported`, so such a profile is never reported idle.
74
89
  */
75
90
  export declare function inspectJournal(path: string): Promise<JournalStatus>;