@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
package/dist/api.js CHANGED
@@ -1,8 +1,13 @@
1
1
  import { timingSafeEqual } from 'node:crypto';
2
2
  import { Hono } from 'hono';
3
+ import { bodyLimit } from 'hono/body-limit';
3
4
  import { streamSSE } from 'hono/streaming';
5
+ import { readBearerToken } from '@hivemagnus/hive-common/secrets';
6
+ import { liveness, readiness } from '@hivemagnus/hive-common/health';
7
+ import { requestContext } from '@hivemagnus/hive-common/hono';
4
8
  import { z } from 'zod';
5
9
  import { ARDENT_VERSION } from './version.js';
10
+ import { ardentLogger } from './log.js';
6
11
  import { ConfigSchema } from './config.js';
7
12
  import { isConfigNotice, runtimeProblems, saveConfig, loadConfig, resolveReference, parseConfig } from './config.js';
8
13
  import { listSkills, setSkillEnabled } from './skills.js';
@@ -12,11 +17,12 @@ import { assertCodexProtocol, CodexAppServer } from './codex.js';
12
17
  import { toJsonSchema } from './json-schema.js';
13
18
  import { readIdentity, writeIdentity, identityHistory, restoreIdentity } from './identity.js';
14
19
  import { inboundTokenEnv, listPeers, outboundTokenEnv, parsePeersConfig, readPeersConfig, savePeersConfig } from './a2a-peers.js';
20
+ import { OPENMETRICS_CONTENT_TYPE, renderMetrics } from './metrics.js';
15
21
  import { ArdentA2AClient } from './a2a-client.js';
16
22
  import { TelegramAdapter } from './telegram.js';
17
23
  import { MattermostAdapter } from './mattermost.js';
18
24
  import { CatchupStatusSchema } from './channel-catchup.js';
19
- import { EventSchema, SessionMessageSchema, SessionSchema, TaskSchema, TaskState } from './store.js';
25
+ import { EventSchema, SessionMessageSchema, SessionSchema, TaskContext, TaskSchema, TaskState } from './store.js';
20
26
  import { mountPluginHttp } from './plugin-http.js';
21
27
  import { pluginContext } from './plugins.js';
22
28
  import { MissionSubmit } from './missions.js';
@@ -30,7 +36,7 @@ import { ExecutionContextSchema, ExecutionInput } from './execution.js';
30
36
  import { TaskLineageSchema, taskLineage } from './lineage.js';
31
37
  import { readExecutionHeader } from '@hivemagnus/hive-common/execution';
32
38
  import { RecoveryDecisionInput, RecoveryViewSchema, recoveryView } from './recovery.js';
33
- import { RecoveryConflictError } from './runtime.js';
39
+ import { dependency, dependencyUnavailable, ErrorCode, invalidRequest, isHiveError, legacyPluginError, SessionMismatchError, TaskTerminalError } from './errors.js';
34
40
  const Submit = z.object({ prompt: z.string().trim().min(1).max(16000), session_id: z.string().guid().optional(), idempotency_key: z.string().min(1).max(128).optional(),
35
41
  execution: ExecutionInput.optional() }).strict();
36
42
  /** A task as the management API reports it: the stored row plus its execution context and recovery, when it has them. */
@@ -50,29 +56,67 @@ const ConfigEdit = z.object({ text: z.string().min(1).max(200000), revision: z.s
50
56
  const SkillEdit = z.object({ enabled: z.boolean(), revision: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
51
57
  const IdentityEdit = z.object({ text: z.string().min(1).max(128 * 1024), revision: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
52
58
  const IdentityRestore = z.object({ history_name: z.string().min(1).max(128), revision: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
59
+ /** How long a Codex account status stays fresh for readiness and GET /providers. */
60
+ const CODEX_PROBE_CACHE_MS = 30_000;
53
61
  const PageLimit = z.coerce.number().int().min(1).max(100);
54
62
  /** A HiveMem agent credential is a JWT: three base64url segments. */
55
63
  const HiveMemCredential = z.string().max(16384).regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/);
64
+ const HealthCheckReport = z.object({ status: z.enum(['up', 'down']), critical: z.boolean(), latencyMs: z.number(), error: z.string().optional(), details: z.record(z.string(), z.unknown()).optional() });
65
+ const LiveBody = z.object({ status: z.literal('live'), service: z.string(), version: z.string(), time: z.string() });
66
+ const ReadyBody = z.object({ status: z.enum(['ready', 'degraded']), service: z.string(), version: z.string(), time: z.string(),
67
+ checks: z.record(z.string(), HealthCheckReport).describe('configuration, and codex or llamacpp when probed'), problems: z.array(z.string()) });
68
+ /** How long a replaced inbound credential stays valid after a rotation, unless the request says otherwise. */
69
+ const DEFAULT_CREDENTIAL_OVERLAP_SECONDS = 300;
70
+ const CredentialRotation = z.object({ overlap_seconds: z.number().int().min(0).max(3600).optional() }).strict();
71
+ const ManagementToken = z.string().min(16).max(4096).regex(/^\S+$/);
72
+ const ManagementCredentialRotated = z.object({ reloaded: z.literal(true), token_env: z.string(), changed: z.boolean(),
73
+ previous_valid_until: z.string().datetime().nullable().describe('Until when the replaced token is still accepted, or null') });
74
+ const PeerCredentialsRotated = z.object({ reloaded: z.literal(true), peers: z.number().int().describe('Enabled peers'), changed: z.array(z.string()).describe('Peers whose inbound token changed'),
75
+ service_environment: z.array(z.string()).describe('Token variables the service environment sets; they are not read from the file'),
76
+ previous_valid_until: z.string().datetime().nullable().describe('Until when the replaced inbound tokens are still accepted, or null') });
56
77
  const CredentialReload = z.object({ reloaded: z.literal(true), token_env: z.string(), changed: z.boolean() });
57
78
  const EventCursor = z.coerce.number().int().min(0);
79
+ /** A task stream ends after this long; clients reconnect from their cursor. */
80
+ const STREAM_ROTATION_MS = 60_000;
81
+ /** An idle task stream sends a `: keepalive` comment this often. */
82
+ const STREAM_KEEPALIVE_MS = 15_000;
83
+ /** How often an idle stream looks for journal events written by another process. */
84
+ const STREAM_FALLBACK_POLL_MS = 1_000;
85
+ /** A time bound: epoch milliseconds or an ISO 8601 date-time. */
86
+ const TimeBound = z.union([z.string().regex(/^\d{1,15}$/).transform(Number), z.string().datetime({ offset: true }).transform(value => Date.parse(value))]);
87
+ const TaskListQuery = z.object({ limit: PageLimit.optional(), after: z.string().min(1).max(400).optional(),
88
+ state: z.string().max(200).transform(value => value.split(',')).pipe(z.array(TaskState).min(1)).optional(),
89
+ context: TaskContext.optional(), caller: z.string().min(1).max(128).optional(), since: TimeBound.optional(), until: TimeBound.optional() }).strict();
58
90
  function authEqual(actual, expected) {
59
91
  const a = Buffer.from(actual);
60
92
  const b = Buffer.from(expected);
61
93
  return a.length === b.length && timingSafeEqual(a, b);
62
94
  }
63
- /** Like parseJson, but a validation failure always reads as an invalid request (HTTP 400). */
95
+ /** Request bodies of the core management routes, as for plugin routes. */
96
+ export const MANAGEMENT_BODY_LIMIT_BYTES = 1_048_576;
97
+ const issues = (error) => error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`).join('; ');
98
+ /** Like parseJson, but the message starts with "Invalid request:". Both answer 400. */
64
99
  function parseInput(body, schema) {
65
100
  const result = schema.safeParse(body);
66
101
  if (!result.success)
67
- throw new Error(`Invalid request: ${result.error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`).join('; ')}`);
102
+ throw invalidRequest(`Invalid request: ${issues(result.error)}`);
68
103
  return result.data;
69
104
  }
70
105
  function parseJson(body, schema) {
71
106
  const result = schema.safeParse(body);
72
107
  if (!result.success)
73
- throw new Error(result.error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`).join('; '));
108
+ throw invalidRequest(issues(result.error));
74
109
  return result.data;
75
110
  }
111
+ /** The JSON request body; a body that is not JSON is an invalid request (400). */
112
+ async function readBody(c) {
113
+ try {
114
+ return await c.req.json();
115
+ }
116
+ catch {
117
+ throw invalidRequest('Invalid request: the body must be JSON');
118
+ }
119
+ }
76
120
  const jsonSchema = (schema) => toJsonSchema(schema, 'openapi-3.0');
77
121
  const jsonResponse = (description, schema) => ({ description, content: { 'application/json': { schema: jsonSchema(schema) } } });
78
122
  const a2aServer = [{ url: 'http://localhost:9901', description: 'Example A2A listener. Use the HTTP+JSON interface URL advertised by the Agent Card.' }];
@@ -116,8 +160,8 @@ export function ardentOpenApi() {
116
160
  Error: { type: 'object', required: ['error'], properties: { error: { type: 'object', required: ['code', 'message'], properties: { code: { type: 'string' }, message: { type: 'string' } } } } }
117
161
  } },
118
162
  paths: {
119
- '/health/live': { get: { operationId: 'getLiveness', responses: { '200': { description: 'Process is running' } } } },
120
- '/health/ready': { get: { operationId: 'getReadiness', responses: { '200': { description: 'Configured runtime ready' }, '503': { description: 'Runtime dependency unavailable' } } } },
163
+ '/health/live': { get: { operationId: 'getLiveness', responses: { '200': jsonResponse('Process is running (HiveCommon liveness body)', LiveBody) } } },
164
+ '/health/ready': { get: { operationId: 'getReadiness', description: 'HiveCommon readiness body plus problems. The configuration check runs first; the selected backend (codex or llamacpp) is probed only when the configuration is complete. A 503 keeps the status degraded.', responses: { '200': jsonResponse('Configured runtime ready', ReadyBody), '503': jsonResponse('Runtime dependency unavailable', ReadyBody) } } },
121
165
  '/a2a/rest/extendedAgentCard': { get: { operationId: 'a2aGetExtendedAgentCard', description: 'Authenticated A2A v1 extended Agent Card on the separate A2A listener.', servers: a2aServer, security: [{ bearerAuth: [] }], parameters: [a2aVersion], responses: a2aResult } },
122
166
  '/a2a/rest/message:send': { post: { operationId: 'a2aSendMessage', description: 'Canonical A2A v1 HTTP+JSON send operation on the separate A2A listener.', servers: a2aServer, security: [{ bearerAuth: [] }], parameters: [a2aVersion], requestBody: a2aBody, responses: a2aResult } },
123
167
  '/a2a/rest/message:stream': { post: { operationId: 'a2aStreamMessage', description: 'Canonical A2A v1 HTTP+JSON streaming send.', servers: a2aServer, security: [{ bearerAuth: [] }], parameters: [a2aVersion], requestBody: a2aBody, responses: { ...a2aResult, '200': { description: 'A2A task/status/artifact SSE events', content: { 'text/event-stream': { schema: { type: 'string' } } } } } } },
@@ -129,7 +173,16 @@ export function ardentOpenApi() {
129
173
  '/a2a/rest/tasks/{taskId}/pushNotificationConfigs/{configId}': { get: { operationId: 'a2aGetPushConfig', servers: a2aServer, security: [{ bearerAuth: [] }], parameters: [a2aVersion, a2aTaskId, a2aConfigId], responses: a2aResult }, delete: { operationId: 'a2aDeletePushConfig', servers: a2aServer, security: [{ bearerAuth: [] }], parameters: [a2aVersion, a2aTaskId, a2aConfigId], responses: { '204': { description: 'Push configuration deleted' }, '401': { description: 'Peer authentication failed' }, '404': { description: 'Configuration absent' } } } },
130
174
  '/api/v1/tasks': {
131
175
  post: { operationId: 'submitTask', security: [{ bearerAuth: [] }], requestBody: { required: true, content: { 'application/json': { schema: jsonSchema(documented(Submit)), example: { prompt: 'Research today\'s topic', idempotency_key: 'topic-2026-09-26' } } } }, responses: { '202': { ...jsonResponse('Accepted durable task', z.object({ task_id: z.string().guid(), state: TaskState })), content: { 'application/json': { schema: jsonSchema(z.object({ task_id: z.string().guid(), state: TaskState })), example: { task_id: taskExample.id, state: 'queued' } } } }, '400': { description: 'Invalid request' }, '401': { description: 'Unauthorized' }, '409': { description: 'Conflicting idempotency key' } } },
132
- get: { operationId: 'listTasks', security: [{ bearerAuth: [] }], parameters: [{ in: 'query', name: 'limit', description: 'Maximum number of recent tasks', schema: { type: 'integer', minimum: 1, maximum: 100, default: 50 } }], responses: { '200': { description: 'Recent tasks', content: { 'application/json': { schema: { type: 'object', required: ['tasks'], properties: { tasks: { type: 'array', items: { $ref: '#/components/schemas/Task' } } } }, example: { tasks: [taskExample] } } } } } }
176
+ get: { operationId: 'listTasks', description: 'Tasks newest first (by created_ms, then id), one page at a time. Pass next as after for the following page; filters combine with AND.', security: [{ bearerAuth: [] }], parameters: [
177
+ { in: 'query', name: 'limit', description: 'Maximum number of tasks in the page', schema: { type: 'integer', minimum: 1, maximum: 100, default: 50 } },
178
+ { in: 'query', name: 'after', description: 'Cursor from a previous page (next)', schema: { type: 'string', maxLength: 400 } },
179
+ { in: 'query', name: 'state', description: 'Comma-separated task states', schema: { type: 'string', example: 'queued,running' } },
180
+ { in: 'query', name: 'context', schema: { type: 'string', enum: TaskContext.options } },
181
+ { in: 'query', name: 'caller', description: 'Exact caller, for example management or a peer ID', schema: { type: 'string', maxLength: 128 } },
182
+ { in: 'query', name: 'since', description: 'Tasks created at or after this time: epoch milliseconds or ISO 8601', schema: { type: 'string' } },
183
+ { in: 'query', name: 'until', description: 'Tasks created before this time: epoch milliseconds or ISO 8601', schema: { type: 'string' } }
184
+ ],
185
+ responses: { '200': { description: 'One page of tasks; next is null on the last page', content: { 'application/json': { schema: { type: 'object', required: ['tasks', 'next'], properties: { tasks: { type: 'array', items: { $ref: '#/components/schemas/Task' } }, next: { type: ['string', 'null'] } } }, example: { tasks: [taskExample], next: null } } } }, '400': { description: 'Invalid filter or cursor' } } }
133
186
  },
134
187
  '/api/v1/missions': { post: { operationId: 'submitMission', description: 'Accept a team mission as a durable task in context mission. Tools come from mission.resources with the peer mission rule; mission tools (team_handoff, team_ask_user, team_propose_decision, artifact_write, development_note, document_render) need a tool:<name> resource. Memory reads use private scope plus one project:<id> grant. The task result is a TeamResult JSON document. The task streams on /api/v1/tasks/{id}/stream like any task.', security: [{ bearerAuth: [] }], requestBody: { required: true, content: { 'application/json': { schema: jsonSchema(documented(MissionSubmit)) } } }, responses: { '202': jsonResponse('Accepted durable mission task', Accepted), '400': { description: 'Invalid mission, context items over 64 KiB, or deadline passed' }, '401': { description: 'Unauthorized' }, '404': { description: 'Session absent' }, '409': { description: 'Conflicting idempotency key' } } } },
135
188
  '/api/v1/preview/tasks': { post: { operationId: 'submitPreviewTask', description: 'Run a prompt with unsaved soul, identity, skill selection or model overrides in context preview. A preview has read-only direct tools and no mission tools, never writes memory, development records, identity or configuration, and its artifacts expire after 24 hours. It streams on /api/v1/tasks/{id}/stream like any task.', security: [{ bearerAuth: [] }], requestBody: { required: true, content: { 'application/json': { schema: jsonSchema(documented(PreviewSubmit)) } } }, responses: { '202': jsonResponse('Accepted preview task', Accepted), '400': { description: 'Invalid request' }, '401': { description: 'Unauthorized' }, '409': { description: 'Conflicting idempotency key' } } } },
@@ -144,7 +197,7 @@ export function ardentOpenApi() {
144
197
  },
145
198
  '/api/v1/tasks/{id}/lineage': { get: { operationId: 'getTaskLineage', description: 'What this profile knows about the task\'s causal tree: its execution context and parent, local child and continuation tasks, model attempts with their request ids, tool calls and artifacts. Rebuilt from SQLite, so it survives a restart. Attribution only.', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'id', required: true, schema: { type: 'string' } }], responses: { '200': jsonResponse('Task lineage', TaskLineageSchema), '404': { description: 'Task absent' } } } },
146
199
  '/api/v1/tasks/{id}/events': { get: { operationId: 'getTaskEvents', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'id', required: true, schema: { type: 'string' } }, { in: 'query', name: 'after', description: 'Return events with sequence greater than this cursor', schema: { type: 'integer', minimum: 0, default: 0 } }], responses: { '200': { description: 'Journal events after the supplied sequence cursor', content: { 'application/json': { schema: { type: 'object', required: ['events'], properties: { events: { type: 'array', items: { $ref: '#/components/schemas/TaskEvent' } } } }, example: { events: [eventExample] } } } } } } },
147
- '/api/v1/tasks/{id}/stream': { get: { operationId: 'streamTaskEvents', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'id', required: true, schema: { type: 'string' } }, { in: 'query', name: 'after', schema: { type: 'integer', minimum: 0 } }, { in: 'header', name: 'Last-Event-ID', description: 'Resume after a journal sequence', schema: { type: 'integer', minimum: 0 } }], responses: { '200': { description: 'SSE task.event carries TaskEvent JSON with the journal sequence as its id; task.done carries Task JSON. While the task runs, task.text carries the visible reply text of the current model step ({step, text}, sent on connect and when a step starts) and task.delta appends to it. Live text has no event id, is not journaled and is not replayed; the completed task result is authoritative.', content: { 'text/event-stream': { schema: { type: 'string' }, example: sseExample } } }, '404': { description: 'Task absent' } } } },
200
+ '/api/v1/tasks/{id}/stream': { get: { operationId: 'streamTaskEvents', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'id', required: true, schema: { type: 'string' } }, { in: 'query', name: 'after', schema: { type: 'integer', minimum: 0 } }, { in: 'header', name: 'Last-Event-ID', description: 'Resume after a journal sequence', schema: { type: 'integer', minimum: 0 } }], responses: { '200': { description: 'SSE task.event carries TaskEvent JSON with the journal sequence as its id; task.done carries Task JSON. An idle stream sends a `: keepalive` comment every 15 seconds. While the task runs, task.text carries the visible reply text of the current model step ({step, text}, sent on connect and when a step starts) and task.delta appends to it. Live text has no event id, is not journaled and is not replayed; the completed task result is authoritative.', content: { 'text/event-stream': { schema: { type: 'string' }, example: sseExample } } }, '404': { description: 'Task absent' } } } },
148
201
  '/api/v1/tasks/{id}/cancel': { post: { operationId: 'cancelTask', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'id', required: true, schema: { type: 'string' } }], responses: { '200': { description: 'Cancellation requested' } } } },
149
202
  '/api/v1/tasks/{id}/pause': { post: { operationId: 'pauseTask', description: 'Pause a queued or running task. A queued task does not start; a running task waits at its next step boundary (before a model call, a tool call or settling) and journals paused. Its deadline keeps running. Idempotent.', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'id', required: true, schema: { type: 'string' } }], responses: { '200': jsonResponse('Task admission', Admission), '404': { description: 'Task absent' }, '409': { description: 'Task already finished' } } } },
150
203
  '/api/v1/tasks/{id}/resume': { post: { operationId: 'resumeTask', description: 'Resume a paused task. Idempotent; resuming a task that is not paused changes nothing.', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'id', required: true, schema: { type: 'string' } }], responses: { '200': jsonResponse('Task admission', Admission), '404': { description: 'Task absent' } } } },
@@ -159,7 +212,9 @@ export function ardentOpenApi() {
159
212
  get: { operationId: 'listArtifactImports', security: [{ bearerAuth: [] }], parameters: [{ in: 'query', name: 'limit', schema: { type: 'integer', minimum: 1, maximum: 100, default: 50 } }], responses: { '200': jsonResponse('Recent imports, newest first', z.object({ imports: z.array(ArtifactImportSchema) })) } }
160
213
  },
161
214
  '/api/v1/artifacts/imports/{id}': { get: { operationId: 'getArtifactImport', description: 'Import progress. error.code is TRANSFER_REQUIRES_V2 (peer lacks urn:hive:artifact-transfer:2 and the artifact is over 2 MiB), DIGEST_MISMATCH (bytes discarded; reissue to retry), TRANSFER_TOO_LARGE, TRANSFER_SOURCE_GONE, TRANSFER_INTERRUPTED (retries exhausted; reissue resumes) or another stable code.', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'id', required: true, schema: { type: 'string', pattern: '^[a-f0-9]{32}$' } }], responses: { '200': jsonResponse('Import state', ArtifactImportSchema), '404': { description: 'Import absent' } } } },
162
- '/api/v1/status': { get: { operationId: 'getOperationalStatus', security: [{ bearerAuth: [] }], responses: { '200': jsonResponse('Active profile summary; capabilities.artifact_transfer is the highest artifact transfer version served', z.object({ version: z.string(), profile: z.string(), backend: z.enum(['llamacpp', 'codex']), tasks: z.number().int(), channels: z.object({ mattermost: z.object({ catchup: z.array(CatchupStatusSchema).describe('Latest missed-post catch-up walk per Mattermost channel') }) }), capabilities: z.object({ artifact_transfer: z.literal(2) }), recovery: RecoveryCounts.optional() })) } } },
215
+ '/api/v1/status': { get: { operationId: 'getOperationalStatus', security: [{ bearerAuth: [] }], responses: { '200': jsonResponse('Active profile summary; capabilities.artifact_transfer is the highest artifact transfer version served', z.object({ version: z.string(), profile: z.string(), backend: z.enum(['llamacpp', 'codex']), tasks: z.number().int().describe('Number of tasks in the journal'),
216
+ task_states: z.record(z.string(), z.number().int()).optional().describe('Number of tasks in each state'), channels: z.object({ mattermost: z.object({ catchup: z.array(CatchupStatusSchema).describe('Latest missed-post catch-up walk per Mattermost channel') }) }), capabilities: z.object({ artifact_transfer: z.literal(2) }), recovery: RecoveryCounts.optional(),
217
+ jobs: z.object({ last_tick_error: z.object({ message: z.string(), at: z.string().datetime() }).nullable().describe('Last scheduler tick failure the gateway recorded, or null') }).optional() })) } } },
163
218
  '/api/v1/jobs/definitions/status': { get: { operationId: 'getJobDefinitionsStatus', security: [{ bearerAuth: [] }], responses: { '200': { description: 'Active profile job definition revision, digest, and redacted window status' }, '503': { description: 'Job engine unavailable' } } } },
164
219
  '/api/v1/profile': { get: { operationId: 'getProfile', security: [{ bearerAuth: [] }], responses: { '200': jsonResponse('Profile identity and path', z.object({ profile: z.string(), name: z.string(), product: z.string(), timezone: z.string(), path: z.string() })) } } },
165
220
  '/api/v1/config': { get: { operationId: 'getConfig', security: [{ bearerAuth: [] }], responses: { '200': jsonResponse('Raw YAML and revision; secrets remain references', z.object({ revision: z.string(), text: z.string() })) } }, put: { operationId: 'saveConfig', security: [{ bearerAuth: [] }], requestBody: { required: true, content: { 'application/json': { schema: jsonSchema(ConfigEdit) } } }, responses: { '200': jsonResponse('Saved; activation required', z.object({ revision: z.string(), activation_required: z.boolean() })), '409': { description: 'Revision conflict' } } } },
@@ -168,7 +223,7 @@ export function ardentOpenApi() {
168
223
  '/api/v1/identity/{kind}': { get: { operationId: 'getIdentity', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'kind', required: true, schema: { type: 'string', enum: ['soul', 'identity'] } }], responses: { '200': { description: 'Identity text and revision' } } }, put: { operationId: 'saveIdentity', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'kind', required: true, schema: { type: 'string', enum: ['soul', 'identity'] } }], requestBody: { required: true, content: { 'application/json': { schema: toJsonSchema(IdentityEdit, 'openapi-3.0') } } }, responses: { '200': { description: 'Saved identity revision' }, '409': { description: 'Revision conflict' } } } },
169
224
  '/api/v1/identity/{kind}/history': { get: { operationId: 'getIdentityHistory', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'kind', required: true, schema: { type: 'string', enum: ['soul', 'identity'] } }], responses: { '200': { description: 'Previous versions' } } } },
170
225
  '/api/v1/identity/{kind}/restore': { post: { operationId: 'restoreIdentity', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'kind', required: true, schema: { type: 'string', enum: ['soul', 'identity'] } }], requestBody: { required: true, content: { 'application/json': { schema: toJsonSchema(IdentityRestore, 'openapi-3.0') } } }, responses: { '200': { description: 'Restored identity revision' }, '409': { description: 'Revision conflict' } } } },
171
- '/api/v1/providers': { get: { operationId: 'getProviders', security: [{ bearerAuth: [] }], responses: { '200': { description: 'Configured providers and Codex account mode' } } } },
226
+ '/api/v1/providers': { get: { operationId: 'getProviders', description: 'Configured providers. codex.auth_mode is the Codex account status (or the probe error) for a Codex profile, and not_selected for a llama.cpp profile unless probe=codex is given. The Codex probe is shared with readiness and cached for 30 seconds.', security: [{ bearerAuth: [] }], parameters: [{ in: 'query', name: 'probe', required: false, description: 'codex: probe the Codex account although llama.cpp is selected', schema: { type: 'string', enum: ['codex'] } }], responses: { '200': { description: 'Configured providers and Codex account mode' } } } },
172
227
  '/api/v1/providers/test': { post: { operationId: 'testProvider', security: [{ bearerAuth: [] }], responses: { '200': { description: 'Selected provider probe' }, '503': { description: 'Provider unavailable' } } } },
173
228
  '/api/v1/channels': { get: { operationId: 'getChannels', security: [{ bearerAuth: [] }], responses: { '200': { description: 'Channel configuration and credential presence' } } } },
174
229
  '/api/v1/channels/{name}/test': { post: { operationId: 'testChannel', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'name', required: true, schema: { type: 'string', enum: ['telegram', 'mattermost'] } }], responses: { '200': { description: 'Read-only channel connection probe' }, '503': { description: 'Channel unavailable' } } } },
@@ -181,6 +236,9 @@ export function ardentOpenApi() {
181
236
  '/api/v1/skills/{name}': { put: { operationId: 'setSkillEnabled', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'name', required: true, schema: { type: 'string' } }], requestBody: { required: true, content: { 'application/json': { schema: toJsonSchema(SkillEdit, 'openapi-3.0') } } }, responses: { '200': { description: 'Saved skill selection revision' }, '409': { description: 'Revision conflict' } } } },
182
237
  '/api/v1/memory/search': { post: { operationId: 'searchMemory', security: [{ bearerAuth: [] }], requestBody: { required: true, content: { 'application/json': { schema: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'] } } } }, responses: { '200': { description: 'Permitted memories' }, '503': { description: 'HiveMem unavailable' } } } },
183
238
  '/api/v1/memory/status': { get: { operationId: 'getMemoryStatus', security: [{ bearerAuth: [] }], responses: { '200': jsonResponse('HiveMem readiness and capability summary', z.object({ status: z.enum(['ready', 'degraded']), agent_id: z.string(), workspace_id: z.string(), retrieval: z.string().nullable(), storage: z.string().nullable(), reason: z.string().nullable() })) } } },
239
+ '/api/v1/metrics': { get: { operationId: 'getMetrics', description: 'Profile metrics in the OpenMetrics text format: tasks by state, open recovery statuses, job windows, channel and A2A push deliveries by state, A2A rate-limit refusals since the process started (ardent_a2a_rate_limited_total by scope ip, peer or tasks) and Mattermost catch-up boundary and walk ages and gaps per channel. Gauges are read from the journal when scraped.', security: [{ bearerAuth: [] }], responses: { '200': { description: 'OpenMetrics text, ending with # EOF', content: { 'application/openmetrics-text': { schema: { type: 'string' } } } }, '401': { description: 'Unauthorized' } } } },
240
+ '/api/v1/credentials/management/reload': { post: { operationId: 'reloadManagementCredential', description: 'Re-read the management token named by api.token_env from the profile environment file the gateway started from and require it for every later request, without a restart. A token the service environment set cannot be rotated this way (409). The replaced token is still accepted for overlap_seconds (default 300, at most 3600; 0 ends it now), so a caller can switch over. Authenticate this request with the token in use. The token is never returned.', security: [{ bearerAuth: [] }], requestBody: { required: false, content: { 'application/json': { schema: jsonSchema(CredentialRotation) } } }, responses: { '200': jsonResponse('Credential reloaded; changed is false when the file holds the token already in use', ManagementCredentialRotated), '400': { description: 'Invalid request' }, '401': { description: 'Unauthorized' }, '409': { description: 'The service environment sets the token' }, '422': { description: 'Token missing, too short or malformed, or the environment file is unreadable; the token in use stays' } } } },
241
+ '/api/v1/credentials/peers/reload': { post: { operationId: 'reloadPeerCredentials', description: 'Re-read the inbound and outbound tokens of every configured A2A peer from the profile environment file and use them without a restart (the peer list itself still needs a restart). A replaced inbound token is still accepted for overlap_seconds (default 300, at most 3600). The new set is validated as at startup; when it is not valid nothing changes. Tokens are never returned.', security: [{ bearerAuth: [] }], requestBody: { required: false, content: { 'application/json': { schema: jsonSchema(CredentialRotation) } } }, responses: { '200': jsonResponse('Peer credentials reloaded', PeerCredentialsRotated), '400': { description: 'Invalid request' }, '401': { description: 'Unauthorized' }, '409': { description: 'The A2A surface is not running' }, '422': { description: 'A peer credential is missing, too short, reused or not directional, or the environment file is unreadable; the credentials in use stay' } } } },
184
242
  '/api/v1/memory/credential/reload': { post: { operationId: 'reloadMemoryCredential', description: 'Re-read the HiveMem agent credential named by memory.token_env from the profile environment file the gateway started from, and use it for every later HiveMem request without a restart. No other variable changes; requests in flight finish with the previous credential. The credential is never returned.', security: [{ bearerAuth: [] }], requestBody: { required: false, content: { 'application/json': { schema: jsonSchema(z.object({}).strict()) } } }, responses: { '200': jsonResponse('Credential reloaded; changed is false when the file holds the credential already in use', CredentialReload), '400': { description: 'Invalid request' }, '401': { description: 'Unauthorized' }, '409': { description: 'Memory provider is not hivemem' }, '422': { description: 'Credential missing, empty or malformed, or the environment file is unreadable; the previous credential stays in use' } } } }
185
243
  }
186
244
  };
@@ -192,13 +250,15 @@ export function ardentOpenApi() {
192
250
  */
193
251
  export function createArdentApi(runtime, loaded, env = process.env, jobEngine, options = {}) {
194
252
  const app = new Hono();
253
+ const logger = options.logger ?? ardentLogger();
195
254
  const transfers = options.artifactTransfers ?? new ArtifactTransfers(runtime, env);
196
255
  let current = loaded;
197
256
  // A saved configuration requires activation; it must not rotate the live
198
257
  // management credential before the gateway restarts with it.
199
258
  const apiTokenEnv = loaded.config.api.token_env;
200
- // Readiness spawns Codex. Cache one result briefly and share an in-flight probe.
201
- let codexReadiness;
259
+ // Readiness and GET /providers spawn a Codex App Server. Cache one account
260
+ // status briefly and share an in-flight probe between them.
261
+ let codexAccount;
202
262
  let codexProbe;
203
263
  const probeCodex = async () => {
204
264
  try {
@@ -206,86 +266,121 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
206
266
  const server = new CodexAppServer(runtime.config.providers.codex.command, runtime.profileDir, env);
207
267
  try {
208
268
  await server.initialize();
209
- const auth = await server.accountStatus();
210
- return auth === runtime.config.providers.codex.auth_mode ? null : auth === 'login-required' ? 'Codex login required' : 'Codex account uses the wrong auth mode';
269
+ return { auth: await server.accountStatus(), error: null };
211
270
  }
212
271
  finally {
213
272
  server.close();
214
273
  }
215
274
  }
216
275
  catch (error) {
217
- return error instanceof Error ? error.message : 'Codex App Server unavailable';
276
+ return { auth: null, error: error instanceof Error ? error.message : 'Codex App Server unavailable' };
218
277
  }
219
278
  };
220
- const codexReadinessProblem = async () => {
221
- if (codexReadiness && Date.now() - codexReadiness.at < 30_000)
222
- return codexReadiness.problem;
223
- codexProbe ??= probeCodex().then(problem => { codexReadiness = { at: Date.now(), problem }; return problem; })
279
+ const codexAccountStatus = async () => {
280
+ if (codexAccount && Date.now() - codexAccount.at < CODEX_PROBE_CACHE_MS)
281
+ return codexAccount;
282
+ codexProbe ??= probeCodex().then(result => { codexAccount = { at: Date.now(), ...result }; return result; })
224
283
  .finally(() => { codexProbe = undefined; });
225
284
  return codexProbe;
226
285
  };
286
+ const codexReadinessProblem = async () => {
287
+ const { auth, error } = await codexAccountStatus();
288
+ if (error !== null)
289
+ return error;
290
+ return auth === runtime.config.providers.codex.auth_mode ? null : auth === 'login-required' ? 'Codex login required' : 'Codex account uses the wrong auth mode';
291
+ };
292
+ // Errors map to a status by their type: a HiveError (src/errors.ts) keeps its
293
+ // status and code, a Zod validation error is a 400, and anything else is an
294
+ // internal error whose message the caller never sees.
227
295
  app.onError((error, c) => {
228
- const message = error instanceof Error ? error.message : 'Request failed';
229
- const status = /revision conflict|Idempotency key reused|already in progress/i.test(message) ? 409
230
- : /not found|absent/i.test(message) ? 404
231
- : /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
232
- : error instanceof z.ZodError || error instanceof SyntaxError || /invalid|must be|exceeds|requires/i.test(message) ? 400 : 500;
233
- const code = status === 409 ? 'CONFLICT' : status === 404 ? 'NOT_FOUND' : status === 503 ? 'DEPENDENCY_UNAVAILABLE' : status === 400 ? 'INVALID_REQUEST' : 'INTERNAL_ERROR';
234
- return c.json({ error: { code, message: status === 500 ? 'Internal request error' : message.slice(0, 500) } }, status);
235
- });
236
- app.get('/health/live', c => c.json({ status: 'live' }));
296
+ const typed = isHiveError(error) ? error : error instanceof z.ZodError ? invalidRequest(issues(error)) : undefined;
297
+ if (!typed || typed.status >= 500 && typed.status !== 503) {
298
+ // The caller sees only a generic message; record what failed so the operator can find it.
299
+ logger.error('Unhandled management API error', { method: c.req.method, path: c.req.path, err: error });
300
+ return c.json({ error: { code: ErrorCode.internal, message: 'Internal request error' } }, 500);
301
+ }
302
+ // A finished task's refusal kept its historical code on the wire.
303
+ const code = typed instanceof TaskTerminalError ? ErrorCode.conflict : typed.code;
304
+ return new Response(JSON.stringify({ error: { code, message: typed.message.slice(0, 500) } }), { status: typed.status, headers: { ...typed.headers, 'Content-Type': 'application/json' } });
305
+ });
306
+ // Every request runs in a HiveCommon request context: x-request-id is accepted or generated and
307
+ // echoed, traceparent is continued, and the API's log lines carry requestId and traceId.
308
+ app.use('*', requestContext());
309
+ const health = { service: 'ardent', version: ARDENT_VERSION };
310
+ app.get('/health/live', c => c.json(liveness(health).body));
237
311
  app.get('/health/ready', async (c) => {
238
312
  // Advisory notices (such as a deprecated key) never make a profile unready.
239
313
  const problems = runtimeProblems(runtime.config, env).filter(problem => !isConfigNotice(problem));
240
- if (!problems.length && runtime.config.execution.backend === 'codex') {
241
- const problem = await codexReadinessProblem();
242
- if (problem)
243
- problems.push(problem);
244
- }
245
- if (!problems.length && runtime.config.execution.backend === 'llamacpp') {
246
- const base = resolveReference(runtime.config.providers.llamacpp.base_url, env);
247
- if (base) {
248
- try {
249
- const token = env[runtime.config.providers.llamacpp.api_key_env];
250
- const response = await fetch(llamaEndpoint(base, 'models'), { headers: token ? { Authorization: `Bearer ${token}` } : {}, signal: AbortSignal.timeout(2000), redirect: 'manual' });
251
- if (!response.ok)
252
- problems.push(`llama.cpp model discovery HTTP ${response.status}`);
253
- }
254
- catch {
255
- problems.push('llama.cpp model endpoint is unavailable');
256
- }
257
- }
258
- }
259
- return c.json({ status: problems.length ? 'degraded' : 'ready', problems }, problems.length ? 503 : 200);
314
+ const checks = [{ name: 'configuration', check: () => problems.length === 0 }];
315
+ // A backend is probed only once its configuration is complete.
316
+ if (!problems.length && runtime.config.execution.backend === 'codex')
317
+ checks.push({ name: 'codex', timeoutMs: 30_000, check: async () => {
318
+ const problem = await codexReadinessProblem();
319
+ if (problem)
320
+ problems.push(problem);
321
+ return !problem;
322
+ } });
323
+ const base = runtime.config.execution.backend === 'llamacpp' ? resolveReference(runtime.config.providers.llamacpp.base_url, env) : undefined;
324
+ if (!problems.length && base)
325
+ checks.push({ name: 'llamacpp', timeoutMs: 3000, check: async (signal) => {
326
+ try {
327
+ const token = env[runtime.config.providers.llamacpp.api_key_env];
328
+ const response = await fetch(llamaEndpoint(base, 'models'), { headers: token ? { Authorization: `Bearer ${token}` } : {}, signal: AbortSignal.any([signal, AbortSignal.timeout(2000)]), redirect: 'manual' });
329
+ if (!response.ok)
330
+ problems.push(`llama.cpp model discovery HTTP ${response.status}`);
331
+ return response.ok;
332
+ }
333
+ catch {
334
+ problems.push('llama.cpp model endpoint is unavailable');
335
+ return false;
336
+ }
337
+ } });
338
+ const result = await readiness({ ...health, checks });
339
+ for (const [name, report] of Object.entries(result.body.checks))
340
+ if (report.status === 'down' && report.error === 'timeout' && name !== 'configuration')
341
+ problems.push(`${name} readiness check timed out`);
342
+ // The HiveCommon readiness body, plus `problems`; a 503 keeps the status `degraded` it always had.
343
+ return c.json({ ...result.body, status: problems.length ? 'degraded' : 'ready', problems }, problems.length ? 503 : 200);
260
344
  });
261
345
  app.get('/openapi.json', c => c.json(ardentOpenApi()));
346
+ // After POST /api/v1/credentials/management/reload the replaced token stays valid until its overlap ends.
347
+ let previousApiToken;
262
348
  app.use('/api/v1/*', async (c, next) => {
263
349
  const expected = env[apiTokenEnv];
264
- const supplied = c.req.header('Authorization')?.replace(/^Bearer /, '') ?? '';
265
- if (!expected || !authEqual(supplied, expected))
350
+ // Only `Authorization: Bearer <token>` (scheme case-insensitive) authenticates; a bare token does not.
351
+ const supplied = readBearerToken(c.req.header('Authorization')) ?? '';
352
+ const previous = previousApiToken && Date.now() < previousApiToken.until ? previousApiToken.value : undefined;
353
+ if (!((expected && authEqual(supplied, expected)) || (previous && supplied && authEqual(supplied, previous))))
266
354
  return c.json({ error: { code: 'UNAUTHORIZED', message: 'Bearer token required' } }, 401);
267
355
  return next();
268
356
  });
269
- app.get('/api/v1/status', c => c.json({ version: ARDENT_VERSION, profile: runtime.config.profile, backend: runtime.config.execution.backend, tasks: runtime.store.list(10).length,
270
- channels: { mattermost: { catchup: runtime.store.catchup.status('mattermost') } },
271
- capabilities: { artifact_transfer: 2 }, recovery: runtime.store.executionState.counts() }));
357
+ // Plugin routes have their own limit of the same size (src/plugin-http.ts).
358
+ app.use('/api/v1/*', bodyLimit({ maxSize: MANAGEMENT_BODY_LIMIT_BYTES,
359
+ onError: c => c.json({ error: { code: ErrorCode.tooLarge, message: `Request body exceeds ${MANAGEMENT_BODY_LIMIT_BYTES} bytes` } }, 413) }));
360
+ app.get('/api/v1/status', c => {
361
+ const tasks = runtime.store.taskCounts();
362
+ return c.json({ version: ARDENT_VERSION, profile: runtime.config.profile, backend: runtime.config.execution.backend,
363
+ tasks: tasks.total, task_states: tasks.by_state,
364
+ channels: { mattermost: { catchup: runtime.store.catchup.status('mattermost') } }, jobs: { last_tick_error: runtime.store.jobTickError() },
365
+ capabilities: { artifact_transfer: 2 }, recovery: runtime.store.executionState.counts() });
366
+ });
272
367
  app.get('/api/v1/jobs/definitions/status', async (c) => {
273
368
  if (!jobEngine)
274
- throw new Error('Job engine is unavailable');
369
+ throw dependencyUnavailable('Job engine is unavailable');
275
370
  const status = await jobEngine.status();
276
371
  return c.json({ profile: runtime.config.profile, revision: status.active_revision,
277
- sha256: status.active_sha256, ...status });
372
+ sha256: status.active_sha256, ...status, last_tick_error: runtime.store.jobTickError() });
278
373
  });
279
374
  app.get('/api/v1/profile', c => c.json({ profile: runtime.config.profile, name: runtime.config.name, product: runtime.config.product, timezone: runtime.config.timezone, path: runtime.profileDir }));
280
375
  app.get('/api/v1/config', c => c.json({ revision: current.revision, text: current.text }));
281
376
  app.get('/api/v1/config/schema', c => c.json(toJsonSchema(ConfigSchema)));
282
377
  app.post('/api/v1/config/validate', async (c) => {
283
- const input = parseJson(await c.req.json(), z.object({ text: z.string().min(1).max(200000) }).strict());
378
+ const input = parseJson(await readBody(c), z.object({ text: z.string().min(1).max(200000) }).strict());
284
379
  const config = parseConfig(input.text);
285
380
  return c.json({ valid: true, profile: config.profile, runtime_problems: runtimeProblems(config, env) });
286
381
  });
287
382
  app.put('/api/v1/config', async (c) => {
288
- const edit = parseJson(await c.req.json(), ConfigEdit);
383
+ const edit = parseJson(await readBody(c), ConfigEdit);
289
384
  const revision = await saveConfig(runtime.profileDir, edit.text, edit.revision);
290
385
  current = await loadConfig(runtime.profileDir);
291
386
  return c.json({ revision, activation_required: true });
@@ -297,7 +392,7 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
297
392
  });
298
393
  app.put('/api/v1/identity/:kind', async (c) => {
299
394
  const kind = z.enum(['soul', 'identity']).parse(c.req.param('kind'));
300
- const edit = parseJson(await c.req.json(), IdentityEdit);
395
+ const edit = parseJson(await readBody(c), IdentityEdit);
301
396
  return c.json(await writeIdentity(runtime.profileDir, runtime.config, kind, edit.text, edit.revision));
302
397
  });
303
398
  app.get('/api/v1/identity/:kind/history', async (c) => {
@@ -306,36 +401,28 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
306
401
  });
307
402
  app.post('/api/v1/identity/:kind/restore', async (c) => {
308
403
  const kind = z.enum(['soul', 'identity']).parse(c.req.param('kind'));
309
- const input = parseJson(await c.req.json(), IdentityRestore);
404
+ const input = parseJson(await readBody(c), IdentityRestore);
310
405
  return c.json(await restoreIdentity(runtime.profileDir, runtime.config, kind, input.history_name, input.revision));
311
406
  });
312
407
  app.get('/api/v1/providers', async (c) => {
313
- let codex = 'unconfigured';
314
- try {
315
- await assertCodexProtocol(runtime.config.providers.codex.command, env);
316
- const server = new CodexAppServer(runtime.config.providers.codex.command, runtime.profileDir, env);
317
- try {
318
- await server.initialize();
319
- codex = await server.accountStatus();
320
- }
321
- finally {
322
- server.close();
323
- }
324
- }
325
- catch (error) {
326
- codex = error instanceof Error ? error.message : 'unavailable';
408
+ // A llama.cpp profile does not start Codex; ?probe=codex asks for its account status anyway (cached like readiness).
409
+ let codex = 'not_selected';
410
+ if (runtime.config.execution.backend === 'codex' || c.req.query('probe') === 'codex') {
411
+ const { auth, error } = await codexAccountStatus();
412
+ codex = error ?? auth ?? 'unavailable';
327
413
  }
328
414
  return c.json({ selected: runtime.config.execution.backend, llamacpp: { base_url: runtime.config.providers.llamacpp.base_url, model: runtime.config.providers.llamacpp.model }, codex: { model: runtime.config.providers.codex.model, auth_mode: codex } });
329
415
  });
330
- app.post('/api/v1/providers/test', async (c) => {
416
+ app.post('/api/v1/providers/test', async (c) => dependency(async () => {
331
417
  if (runtime.config.execution.backend === 'codex') {
332
418
  await assertCodexProtocol(runtime.config.providers.codex.command, env);
333
419
  const server = new CodexAppServer(runtime.config.providers.codex.command, runtime.profileDir, env);
334
420
  try {
335
421
  await server.initialize();
336
422
  const auth = await server.accountStatus();
337
- if (auth !== 'chatgpt')
338
- throw new Error(auth === 'login-required' ? 'Codex ChatGPT login required' : 'Codex account uses the wrong auth mode');
423
+ // Match readiness: the account must use the configured auth mode (ChatGPT sign-in or API key).
424
+ if (auth !== runtime.config.providers.codex.auth_mode)
425
+ throw dependencyUnavailable(auth === 'login-required' ? 'Codex login required' : 'Codex account uses the wrong auth mode');
339
426
  return c.json({ backend: 'codex', auth_mode: auth });
340
427
  }
341
428
  finally {
@@ -344,46 +431,47 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
344
431
  }
345
432
  const result = await new LlamaCppBackend(runtime.config.providers.llamacpp, env).complete([{ role: 'user', content: 'Reply with READY.' }], [], AbortSignal.timeout(20000), false);
346
433
  return c.json({ backend: 'llamacpp', answer: result.content, usage: result.usage ?? null });
347
- });
434
+ }, 'Provider unavailable'));
348
435
  app.get('/api/v1/channels', c => c.json({ telegram: { enabled: runtime.config.channels.telegram.enabled, token_configured: Boolean(env[runtime.config.channels.telegram.token_env]), allowed_user_count: runtime.config.channels.telegram.allowed_user_ids.length, allowed_chat_count: runtime.config.channels.telegram.allowed_chat_ids.length }, mattermost: { enabled: runtime.config.channels.mattermost.enabled, token_configured: Boolean(env[runtime.config.channels.mattermost.token_env]), allowed_user_count: runtime.config.channels.mattermost.allowed_user_ids.length, allowed_channel_count: runtime.config.channels.mattermost.allowed_channel_ids.length } }));
349
436
  app.post('/api/v1/channels/:name/test', async (c) => {
350
437
  const name = z.enum(['telegram', 'mattermost']).parse(c.req.param('name'));
351
- if (name === 'telegram') {
352
- const result = await new TelegramAdapter(runtime, runtime.config.channels.telegram, env).initialize(AbortSignal.timeout(10000));
353
- return c.json({ name, status: 'reachable', bot: result, receive_mode: 'polling', polling_started: false });
354
- }
355
- const result = await new MattermostAdapter(runtime, runtime.config.channels.mattermost, env).initialize();
356
- return c.json({ name, status: 'reachable', bot: result, socket_started: false });
438
+ return dependency(async () => {
439
+ if (name === 'telegram') {
440
+ const result = await new TelegramAdapter(runtime, runtime.config.channels.telegram, env).initialize(AbortSignal.timeout(10000));
441
+ return c.json({ name, status: 'reachable', bot: result, receive_mode: 'polling', polling_started: false });
442
+ }
443
+ const result = await new MattermostAdapter(runtime, runtime.config.channels.mattermost, env).initialize();
444
+ return c.json({ name, status: 'reachable', bot: result, socket_started: false });
445
+ }, 'Channel unavailable');
357
446
  });
358
447
  app.get('/api/v1/peers', async (c) => c.json({ peers: (await listPeers(runtime.profileDir, runtime.config)).map(peer => ({ ...peer,
359
448
  inbound_credential_configured: Boolean(env[inboundTokenEnv(peer)]), outbound_credential_configured: Boolean(env[outboundTokenEnv(peer)]),
360
449
  credential_configured: Boolean(env[inboundTokenEnv(peer)] && env[outboundTokenEnv(peer)]) })) }));
361
450
  app.get('/api/v1/peers/config', async (c) => c.json(await readPeersConfig(runtime.profileDir, runtime.config)));
362
451
  app.post('/api/v1/peers/validate', async (c) => {
363
- const input = parseJson(await c.req.json(), z.object({ text: z.string().min(1).max(200000) }).strict());
452
+ const input = parseJson(await readBody(c), z.object({ text: z.string().min(1).max(200000) }).strict());
364
453
  return c.json({ valid: true, peers: parsePeersConfig(input.text).length });
365
454
  });
366
455
  app.put('/api/v1/peers/config', async (c) => {
367
- const input = parseJson(await c.req.json(), ConfigEdit);
456
+ const input = parseJson(await readBody(c), ConfigEdit);
368
457
  return c.json({ revision: await savePeersConfig(runtime.profileDir, runtime.config, input.text, input.revision), activation_required: true });
369
458
  });
370
459
  app.post('/api/v1/peers/:id/test', async (c) => {
371
- const { card } = await new ArdentA2AClient(runtime.profileDir, runtime.config, env).open(c.req.param('id'));
460
+ const { card } = await dependency(() => new ArdentA2AClient(runtime.profileDir, runtime.config, env).open(c.req.param('id')), 'Peer unavailable');
372
461
  return c.json({ peer: c.req.param('id'), status: 'reachable', card });
373
462
  });
374
463
  app.put('/api/v1/skills/:name', async (c) => {
375
- const edit = parseJson(await c.req.json(), SkillEdit);
464
+ const edit = parseJson(await readBody(c), SkillEdit);
376
465
  const revision = await setSkillEnabled(runtime.profileDir, c.req.param('name'), edit.enabled, edit.revision);
377
466
  current = await loadConfig(runtime.profileDir);
378
467
  recordSkillChange(runtime.development, c.req.param('name'), edit.enabled, edit.revision, revision);
379
468
  return c.json({ revision, activation_required: true });
380
469
  });
381
470
  app.post('/api/v1/memory/search', async (c) => {
382
- const input = parseJson(await c.req.json(), z.object({ query: z.string().trim().min(1).max(1000) }).strict());
471
+ const input = parseJson(await readBody(c), z.object({ query: z.string().trim().min(1).max(1000) }).strict());
383
472
  if (runtime.config.memory.provider !== 'hivemem')
384
- throw new Error('Memory provider is unconfigured');
385
- const client = new HiveMemClient(runtime.config.memory, env);
386
- return c.json({ results: await client.search(input.query, 'private') });
473
+ throw dependencyUnavailable('Memory provider is unconfigured');
474
+ return c.json({ results: await dependency(() => new HiveMemClient(runtime.config.memory, env).search(input.query, 'private'), 'HiveMem unavailable') });
387
475
  });
388
476
  app.get('/api/v1/memory/status', async (c) => {
389
477
  const memory = runtime.config.memory;
@@ -431,7 +519,7 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
431
519
  body = JSON.parse(text);
432
520
  }
433
521
  catch {
434
- throw new Error('Invalid request: body must be empty or an empty JSON object');
522
+ throw invalidRequest('Invalid request: body must be empty or an empty JSON object');
435
523
  }
436
524
  parseInput(body, z.object({}).strict());
437
525
  }
@@ -446,9 +534,94 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
446
534
  return c.json({ error: { code: 'INVALID_CREDENTIAL', message: result.problem } }, 422);
447
535
  return c.json({ reloaded: true, token_env: memory.token_env, changed: result.changed });
448
536
  });
537
+ app.get('/api/v1/metrics', c => c.body(renderMetrics({ version: ARDENT_VERSION, profile: runtime.config.profile, backend: runtime.config.execution.backend,
538
+ store: runtime.store, counters: runtime.counters, startedMs: runtime.startedMs }), 200, { 'Content-Type': OPENMETRICS_CONTENT_TYPE, 'Cache-Control': 'no-store' }));
539
+ // Management and peer credential rotation without a restart: re-read the profile environment
540
+ // file, switch to the new values, and keep accepting the replaced inbound ones for an overlap.
541
+ let rotations = Promise.resolve();
542
+ const serialized = (work) => { const run = rotations.then(work); rotations = run.catch(() => { }); return run; };
543
+ const overlapOf = async (c) => {
544
+ const text = await c.req.text();
545
+ if (!text.trim())
546
+ return DEFAULT_CREDENTIAL_OVERLAP_SECONDS;
547
+ let body;
548
+ try {
549
+ body = JSON.parse(text);
550
+ }
551
+ catch {
552
+ throw invalidRequest('Invalid request: body must be empty or a JSON object');
553
+ }
554
+ return parseInput(body, CredentialRotation).overlap_seconds ?? DEFAULT_CREDENTIAL_OVERLAP_SECONDS;
555
+ };
556
+ const profileEnv = async () => {
557
+ try {
558
+ return await readProfileEnv(runtime.profileDir, options.envFile);
559
+ }
560
+ catch {
561
+ return undefined;
562
+ }
563
+ };
564
+ const unreadable = (c) => c.json({ error: { code: 'INVALID_CREDENTIAL', message: 'Profile environment file is unreadable or not an owned private file' } }, 422);
565
+ app.post('/api/v1/credentials/management/reload', async (c) => {
566
+ const overlap = await overlapOf(c);
567
+ return serialized(async () => {
568
+ // The service environment wins over the file at startup; rotating from the file would end its token after the overlap.
569
+ if (options.serviceEnv?.has(apiTokenEnv))
570
+ return c.json({ error: { code: 'CONFLICT', message: `${apiTokenEnv} is set by the service environment; rotate it there and restart the gateway` } }, 409);
571
+ const file = await profileEnv();
572
+ if (!file)
573
+ return unreadable(c);
574
+ const value = file[apiTokenEnv];
575
+ if (!value || !ManagementToken.safeParse(value).success)
576
+ return c.json({ error: { code: 'INVALID_CREDENTIAL', message: `${apiTokenEnv} is missing, shorter than 16 characters or not a single token in the profile environment file` } }, 422);
577
+ const prior = env[apiTokenEnv];
578
+ const changed = prior !== value;
579
+ if (changed) {
580
+ previousApiToken = prior && overlap > 0 ? { value: prior, until: Date.now() + overlap * 1000 } : undefined;
581
+ env[apiTokenEnv] = value;
582
+ logger.info('Management credential rotated', { token_env: apiTokenEnv, overlap_seconds: overlap });
583
+ }
584
+ return c.json({ reloaded: true, token_env: apiTokenEnv, changed,
585
+ previous_valid_until: changed && previousApiToken ? new Date(previousApiToken.until).toISOString() : null });
586
+ });
587
+ });
588
+ app.post('/api/v1/credentials/peers/reload', async (c) => {
589
+ const overlap = await overlapOf(c);
590
+ const authenticator = options.peerAuthenticator?.();
591
+ if (!authenticator)
592
+ return c.json({ error: { code: 'CONFLICT', message: 'The A2A surface is not running' } }, 409);
593
+ return serialized(async () => {
594
+ const file = await profileEnv();
595
+ if (!file)
596
+ return unreadable(c);
597
+ const names = new Set(authenticator.peers.flatMap(peer => [inboundTokenEnv(peer), outboundTokenEnv(peer)]).filter(Boolean));
598
+ const candidate = { ...env };
599
+ // A token the service environment set stays: it won over the file at startup too.
600
+ const fixed = [...names].filter(name => options.serviceEnv?.has(name)).sort();
601
+ for (const name of names)
602
+ if (file[name] !== undefined && !options.serviceEnv?.has(name))
603
+ candidate[name] = file[name];
604
+ let changed;
605
+ try {
606
+ ({ changed } = authenticator.reload(candidate, overlap * 1000));
607
+ }
608
+ catch (error) {
609
+ // Nothing changed: the previous credentials stay in use.
610
+ return c.json({ error: { code: 'INVALID_CREDENTIAL', message: error instanceof Error ? error.message.slice(0, 300) : 'Peer credentials are invalid' } }, 422);
611
+ }
612
+ // Outbound tokens are read from the shared environment on every call.
613
+ for (const name of names)
614
+ if (candidate[name] !== undefined)
615
+ env[name] = candidate[name];
616
+ if (changed.length)
617
+ logger.info('Peer credentials rotated', { peers: changed, overlap_seconds: overlap });
618
+ return c.json({ reloaded: true, peers: authenticator.peers.filter(peer => peer.enabled).length, changed, service_environment: fixed,
619
+ previous_valid_until: changed.length && overlap > 0 ? new Date(Date.now() + overlap * 1000).toISOString() : null });
620
+ });
621
+ });
449
622
  app.get('/api/v1/sessions', c => c.json({ sessions: runtime.store.listSessions('management', SessionContext.parse(c.req.query('context') ?? 'direct')) }));
450
623
  app.post('/api/v1/sessions', async (c) => {
451
- const input = parseJson(await c.req.json(), SessionOpen);
624
+ const input = parseJson(await readBody(c), SessionOpen);
452
625
  const context = input.context ?? 'direct';
453
626
  return c.json(input.reset ? runtime.store.resetSession('management', context, input.key) : runtime.store.session('management', context, input.key));
454
627
  });
@@ -460,21 +633,21 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
460
633
  });
461
634
  const view = (task, execution = runtime.store.executionFor(task.id), recovery = recoveryView(runtime.store, task)) => ({ ...task, ...(execution ? { execution } : {}), ...(recovery ? { recovery } : {}) });
462
635
  app.post('/api/v1/tasks', async (c) => {
463
- const input = parseJson(await c.req.json(), Submit);
636
+ const input = parseJson(await readBody(c), Submit);
464
637
  const task = runtime.accept(input.prompt, 'management', 'direct', input.idempotency_key, input.session_id, undefined, undefined, acceptance(c, input.execution));
465
638
  if (task.state === 'queued')
466
639
  void runtime.run(task.id, env).catch(() => { });
467
640
  return c.json({ task_id: task.id, state: task.state }, 202);
468
641
  });
469
642
  app.post('/api/v1/missions', async (c) => {
470
- const input = parseInput(await c.req.json(), MissionSubmit);
643
+ const input = parseInput(await readBody(c), MissionSubmit);
471
644
  let task;
472
645
  try {
473
646
  task = runtime.acceptMission(input, 'management', acceptance(c, input.execution));
474
647
  }
475
648
  catch (error) {
476
- if (error instanceof Error && /Session caller or context mismatch/.test(error.message))
477
- throw new Error('Invalid session: open it with context mission');
649
+ if (error instanceof SessionMismatchError)
650
+ throw new SessionMismatchError('Invalid session: open it with context mission');
478
651
  throw error;
479
652
  }
480
653
  if (task.state === 'queued')
@@ -482,10 +655,14 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
482
655
  return c.json({ task_id: task.id, state: task.state }, 202);
483
656
  });
484
657
  app.get('/api/v1/tasks', c => {
485
- const tasks = runtime.store.list(PageLimit.parse(c.req.query('limit') ?? 50));
658
+ const query = parseInput(Object.fromEntries(['limit', 'after', 'state', 'context', 'caller', 'since', 'until']
659
+ .flatMap(name => { const value = c.req.query(name); return value === undefined ? [] : [[name, value]]; })), TaskListQuery);
660
+ const { tasks, next } = runtime.store.page({ limit: query.limit ?? 50, ...(query.after !== undefined ? { after: query.after } : {}),
661
+ ...(query.state ? { states: query.state } : {}), ...(query.context ? { context: query.context } : {}), ...(query.caller !== undefined ? { caller: query.caller } : {}),
662
+ ...(query.since !== undefined ? { since: query.since } : {}), ...(query.until !== undefined ? { until: query.until } : {}) });
486
663
  const executions = runtime.store.executions.many(tasks.map(task => task.id));
487
664
  const recoveries = runtime.store.executionState.recoveries(tasks.map(task => task.id));
488
- return c.json({ tasks: tasks.map(task => view(task, executions.get(task.id)?.context, recoveryView(runtime.store, task, recoveries.get(task.id)))) });
665
+ return c.json({ tasks: tasks.map(task => view(task, executions.get(task.id)?.context, recoveryView(runtime.store, task, recoveries.get(task.id)))), next });
489
666
  });
490
667
  app.get('/api/v1/tasks/:id', c => {
491
668
  const task = runtime.store.get(c.req.param('id'));
@@ -506,16 +683,9 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
506
683
  const id = c.req.param('id');
507
684
  if (!runtime.store.get(id))
508
685
  return c.json({ error: { code: 'NOT_FOUND', message: 'Task not found' } }, 404);
509
- const input = parseInput(await c.req.json(), RecoveryDecisionInput);
510
- let decided;
511
- try {
512
- decided = await runtime.decideRecovery(id, input, env, 'management');
513
- }
514
- catch (error) {
515
- if (error instanceof RecoveryConflictError)
516
- return c.json({ error: { code: 'CONFLICT', message: error.message.slice(0, 500) } }, 409);
517
- throw error;
518
- }
686
+ const input = parseInput(await readBody(c), RecoveryDecisionInput);
687
+ // A RecoveryConflictError answers 409 CONFLICT.
688
+ const decided = await runtime.decideRecovery(id, input, env, 'management');
519
689
  if (decided.continuation?.state === 'queued')
520
690
  void runtime.run(decided.continuation.id, env).catch(() => { });
521
691
  return c.json(decided.recovery);
@@ -541,31 +711,45 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
541
711
  // Live reply text is not journaled, so its events carry no id and a reconnect
542
712
  // starts from a task.text snapshot of the current step instead of a replay.
543
713
  const live = [];
714
+ // The stream wakes when this gateway appends to the task's journal or has
715
+ // live text; a slow poll still finds events another process wrote.
716
+ let dirty = false;
544
717
  let wake;
545
- const unsubscribe = runtime.liveText.subscribe(id, update => { live.push(update); wake?.(); });
718
+ const notify = () => { dirty = true; wake?.(); };
719
+ const unsubscribe = runtime.liveText.subscribe(id, update => { live.push(update); notify(); });
720
+ const unsubscribeJournal = runtime.store.onAppend(id, notify);
721
+ stream.onAbort(notify);
546
722
  const snapshot = runtime.liveText.snapshot(id);
547
723
  if (snapshot)
548
724
  live.push({ kind: 'text', ...snapshot });
725
+ let lastWrite = Date.now();
726
+ const write = async (message) => { await stream.writeSSE(message); lastWrite = Date.now(); };
549
727
  try {
550
- const until = Date.now() + 60_000;
728
+ const until = Date.now() + STREAM_ROTATION_MS;
551
729
  while (!stream.aborted && Date.now() < until) {
730
+ dirty = false;
552
731
  for (const update of live.splice(0)) {
553
732
  if (update.kind !== 'end')
554
- await stream.writeSSE({ event: update.kind === 'text' ? 'task.text' : 'task.delta', data: JSON.stringify({ step: update.step, text: update.text }) });
733
+ await write({ event: update.kind === 'text' ? 'task.text' : 'task.delta', data: JSON.stringify({ step: update.step, text: update.text }) });
555
734
  }
556
735
  const events = runtime.store.events(id, after, 100);
557
736
  for (const event of events) {
558
- await stream.writeSSE({ event: 'task.event', id: String(event.sequence), data: JSON.stringify(event) });
737
+ await write({ event: 'task.event', id: String(event.sequence), data: JSON.stringify(event) });
559
738
  after = event.sequence;
560
739
  }
561
740
  const task = runtime.store.get(id);
562
741
  if (!task || ['completed', 'partial', 'failed', 'cancelled', 'unknown'].includes(task.state)) {
563
- await stream.writeSSE({ event: 'task.done', data: JSON.stringify(task ?? { id, state: 'missing' }) });
742
+ await write({ event: 'task.done', data: JSON.stringify(task ?? { id, state: 'missing' }) });
564
743
  break;
565
744
  }
566
- if (events.length < 100 && !live.length) {
745
+ // A comment keeps idle proxies from closing the stream; clients ignore it.
746
+ if (Date.now() - lastWrite >= STREAM_KEEPALIVE_MS) {
747
+ await stream.write(': keepalive\n\n');
748
+ lastWrite = Date.now();
749
+ }
750
+ if (events.length < 100 && !live.length && !dirty) {
567
751
  await new Promise(resolve => {
568
- const timer = setTimeout(resolve, 250);
752
+ const timer = setTimeout(resolve, Math.min(STREAM_FALLBACK_POLL_MS, Math.max(0, until - Date.now()), Math.max(0, lastWrite + STREAM_KEEPALIVE_MS - Date.now())));
569
753
  wake = () => { clearTimeout(timer); resolve(); };
570
754
  });
571
755
  wake = undefined;
@@ -574,6 +758,7 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
574
758
  }
575
759
  finally {
576
760
  unsubscribe();
761
+ unsubscribeJournal();
577
762
  }
578
763
  });
579
764
  });
@@ -583,25 +768,19 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
583
768
  const id = c.req.param('id');
584
769
  if (!runtime.store.get(id))
585
770
  return c.json({ error: { code: 'NOT_FOUND', message: 'Task not found' } }, 404);
586
- try {
587
- const { task, admission } = action === 'pause' ? runtime.pause(id) : runtime.resume(id);
588
- return c.json({ task_id: task.id, state: task.state, admission });
589
- }
590
- catch (error) {
591
- if (error && typeof error === 'object' && 'code' in error && error.code === 'TASK_TERMINAL')
592
- return c.json({ error: { code: 'CONFLICT', message: error instanceof Error ? error.message : 'Task already finished' } }, 409);
593
- throw error;
594
- }
771
+ // A finished task throws TaskTerminalError: 409 CONFLICT.
772
+ const { task, admission } = action === 'pause' ? runtime.pause(id) : runtime.resume(id);
773
+ return c.json({ task_id: task.id, state: task.state, admission });
595
774
  });
596
775
  app.post('/api/v1/preview/tasks', async (c) => {
597
- const input = parseInput(await c.req.json(), PreviewSubmit);
776
+ const input = parseInput(await readBody(c), PreviewSubmit);
598
777
  let task;
599
778
  try {
600
779
  task = runtime.acceptPreview(input, 'management', acceptance(c, input.execution));
601
780
  }
602
781
  catch (error) {
603
- if (error instanceof Error && /Session caller or context mismatch/.test(error.message))
604
- throw new Error('Invalid session: open it with context preview');
782
+ if (error instanceof SessionMismatchError)
783
+ throw new SessionMismatchError('Invalid session: open it with context preview');
605
784
  throw error;
606
785
  }
607
786
  if (task.state === 'queued')
@@ -615,7 +794,7 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
615
794
  return c.json(await developmentPage({ records: runtime.development, profileDir: runtime.profileDir, config: runtime.config }, query));
616
795
  });
617
796
  app.post('/api/v1/development', async (c) => {
618
- const { author, ...note } = parseInput(await c.req.json(), DevelopmentPost);
797
+ const { author, ...note } = parseInput(await readBody(c), DevelopmentPost);
619
798
  return c.json(runtime.development.add({ ...note, author: author ?? 'operator', epistemic: author === 'agent' ? 'agent_reported' : 'operator_reported' }), 201);
620
799
  });
621
800
  app.get('/api/v1/tasks/:id/artifacts', c => {
@@ -632,7 +811,7 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
632
811
  });
633
812
  // Imports register before /artifacts/:id so their static segment is not read as a digest.
634
813
  app.post('/api/v1/artifacts/imports', async (c) => {
635
- const record = transfers.start(parseInput(await c.req.json(), ArtifactImportRequestSchema), 'management');
814
+ const record = transfers.start(parseInput(await readBody(c), ArtifactImportRequestSchema), 'management');
636
815
  return c.json({ import_id: record.import_id }, 202);
637
816
  });
638
817
  app.get('/api/v1/artifacts/imports', c => c.json({ imports: transfers.list(PageLimit.parse(c.req.query('limit') ?? 50)) }));
@@ -683,6 +862,8 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
683
862
  if (!plugin.routes)
684
863
  continue;
685
864
  const sub = new Hono();
865
+ // A plugin error without a type answers as it did before typed errors.
866
+ sub.onError(error => { throw legacyPluginError(error); });
686
867
  plugin.routes(sub, ctx);
687
868
  app.route(`/api/v1/plugins/${plugin.name}`, sub);
688
869
  }