@hivemagnus/ardent 3.3.0 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +10 -973
  2. package/dist/a2a-client.js +3 -2
  3. package/dist/a2a-peers.d.ts +26 -0
  4. package/dist/a2a-peers.js +60 -18
  5. package/dist/a2a-push.d.ts +3 -1
  6. package/dist/a2a-push.js +5 -1
  7. package/dist/a2a-rate-limit.d.ts +3 -3
  8. package/dist/a2a-rate-limit.js +6 -3
  9. package/dist/a2a-server.d.ts +13 -1
  10. package/dist/a2a-server.js +20 -11
  11. package/dist/api.d.ts +10 -0
  12. package/dist/api.js +296 -127
  13. package/dist/artifact-transfer.js +3 -2
  14. package/dist/channel-catchup.d.ts +2 -2
  15. package/dist/channels.d.ts +6 -6
  16. package/dist/channels.js +4 -1
  17. package/dist/cli.js +55 -3
  18. package/dist/config.d.ts +9 -1
  19. package/dist/config.js +15 -6
  20. package/dist/development.d.ts +3 -3
  21. package/dist/development.js +2 -1
  22. package/dist/errors.d.ts +54 -0
  23. package/dist/errors.js +76 -0
  24. package/dist/identity.js +11 -6
  25. package/dist/job-engine.d.ts +3 -0
  26. package/dist/job-engine.js +5 -0
  27. package/dist/journal.d.ts +17 -2
  28. package/dist/journal.js +48 -4
  29. package/dist/log.d.ts +5 -1
  30. package/dist/log.js +6 -2
  31. package/dist/mattermost.js +7 -2
  32. package/dist/memory.js +3 -2
  33. package/dist/metrics.d.ts +34 -0
  34. package/dist/metrics.js +73 -0
  35. package/dist/missions.js +2 -1
  36. package/dist/plugin-http.js +10 -1
  37. package/dist/plugin-sdk.d.ts +2 -0
  38. package/dist/plugin-sdk.js +2 -0
  39. package/dist/retention.d.ts +64 -0
  40. package/dist/retention.js +239 -0
  41. package/dist/runtime.d.ts +17 -1
  42. package/dist/runtime.js +52 -15
  43. package/dist/skills.js +5 -4
  44. package/dist/store.d.ts +28 -0
  45. package/dist/store.js +97 -14
  46. package/dist/telegram.js +5 -1
  47. package/package.json +2 -2
  48. package/profiles/assistant/config.yaml +1 -1
package/dist/api.js CHANGED
@@ -1,6 +1,10 @@
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';
6
10
  import { ardentLogger } from './log.js';
@@ -13,11 +17,12 @@ import { assertCodexProtocol, CodexAppServer } from './codex.js';
13
17
  import { toJsonSchema } from './json-schema.js';
14
18
  import { readIdentity, writeIdentity, identityHistory, restoreIdentity } from './identity.js';
15
19
  import { inboundTokenEnv, listPeers, outboundTokenEnv, parsePeersConfig, readPeersConfig, savePeersConfig } from './a2a-peers.js';
20
+ import { OPENMETRICS_CONTENT_TYPE, renderMetrics } from './metrics.js';
16
21
  import { ArdentA2AClient } from './a2a-client.js';
17
22
  import { TelegramAdapter } from './telegram.js';
18
23
  import { MattermostAdapter } from './mattermost.js';
19
24
  import { CatchupStatusSchema } from './channel-catchup.js';
20
- import { EventSchema, SessionMessageSchema, SessionSchema, TaskSchema, TaskState } from './store.js';
25
+ import { EventSchema, SessionMessageSchema, SessionSchema, TaskContext, TaskSchema, TaskState } from './store.js';
21
26
  import { mountPluginHttp } from './plugin-http.js';
22
27
  import { pluginContext } from './plugins.js';
23
28
  import { MissionSubmit } from './missions.js';
@@ -31,7 +36,7 @@ import { ExecutionContextSchema, ExecutionInput } from './execution.js';
31
36
  import { TaskLineageSchema, taskLineage } from './lineage.js';
32
37
  import { readExecutionHeader } from '@hivemagnus/hive-common/execution';
33
38
  import { RecoveryDecisionInput, RecoveryViewSchema, recoveryView } from './recovery.js';
34
- import { RecoveryConflictError } from './runtime.js';
39
+ import { dependency, dependencyUnavailable, ErrorCode, invalidRequest, isHiveError, legacyPluginError, SessionMismatchError, TaskTerminalError } from './errors.js';
35
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(),
36
41
  execution: ExecutionInput.optional() }).strict();
37
42
  /** A task as the management API reports it: the stored row plus its execution context and recovery, when it has them. */
@@ -51,29 +56,67 @@ const ConfigEdit = z.object({ text: z.string().min(1).max(200000), revision: z.s
51
56
  const SkillEdit = z.object({ enabled: z.boolean(), revision: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
52
57
  const IdentityEdit = z.object({ text: z.string().min(1).max(128 * 1024), revision: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
53
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;
54
61
  const PageLimit = z.coerce.number().int().min(1).max(100);
55
62
  /** A HiveMem agent credential is a JWT: three base64url segments. */
56
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') });
57
77
  const CredentialReload = z.object({ reloaded: z.literal(true), token_env: z.string(), changed: z.boolean() });
58
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();
59
90
  function authEqual(actual, expected) {
60
91
  const a = Buffer.from(actual);
61
92
  const b = Buffer.from(expected);
62
93
  return a.length === b.length && timingSafeEqual(a, b);
63
94
  }
64
- /** 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. */
65
99
  function parseInput(body, schema) {
66
100
  const result = schema.safeParse(body);
67
101
  if (!result.success)
68
- throw new Error(`Invalid request: ${result.error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`).join('; ')}`);
102
+ throw invalidRequest(`Invalid request: ${issues(result.error)}`);
69
103
  return result.data;
70
104
  }
71
105
  function parseJson(body, schema) {
72
106
  const result = schema.safeParse(body);
73
107
  if (!result.success)
74
- throw new Error(result.error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`).join('; '));
108
+ throw invalidRequest(issues(result.error));
75
109
  return result.data;
76
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
+ }
77
120
  const jsonSchema = (schema) => toJsonSchema(schema, 'openapi-3.0');
78
121
  const jsonResponse = (description, schema) => ({ description, content: { 'application/json': { schema: jsonSchema(schema) } } });
79
122
  const a2aServer = [{ url: 'http://localhost:9901', description: 'Example A2A listener. Use the HTTP+JSON interface URL advertised by the Agent Card.' }];
@@ -117,8 +160,8 @@ export function ardentOpenApi() {
117
160
  Error: { type: 'object', required: ['error'], properties: { error: { type: 'object', required: ['code', 'message'], properties: { code: { type: 'string' }, message: { type: 'string' } } } } }
118
161
  } },
119
162
  paths: {
120
- '/health/live': { get: { operationId: 'getLiveness', responses: { '200': { description: 'Process is running' } } } },
121
- '/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) } } },
122
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 } },
123
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 } },
124
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' } } } } } } },
@@ -130,7 +173,16 @@ export function ardentOpenApi() {
130
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' } } } },
131
174
  '/api/v1/tasks': {
132
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' } } },
133
- 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' } } }
134
186
  },
135
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' } } } },
136
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' } } } },
@@ -145,7 +197,7 @@ export function ardentOpenApi() {
145
197
  },
146
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' } } } },
147
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] } } } } } } },
148
- '/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' } } } },
149
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' } } } },
150
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' } } } },
151
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' } } } },
@@ -171,7 +223,7 @@ export function ardentOpenApi() {
171
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' } } } },
172
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' } } } },
173
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' } } } },
174
- '/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' } } } },
175
227
  '/api/v1/providers/test': { post: { operationId: 'testProvider', security: [{ bearerAuth: [] }], responses: { '200': { description: 'Selected provider probe' }, '503': { description: 'Provider unavailable' } } } },
176
228
  '/api/v1/channels': { get: { operationId: 'getChannels', security: [{ bearerAuth: [] }], responses: { '200': { description: 'Channel configuration and credential presence' } } } },
177
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' } } } },
@@ -184,6 +236,9 @@ export function ardentOpenApi() {
184
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' } } } },
185
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' } } } },
186
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' } } } },
187
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' } } } }
188
243
  }
189
244
  };
@@ -201,8 +256,9 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
201
256
  // A saved configuration requires activation; it must not rotate the live
202
257
  // management credential before the gateway restarts with it.
203
258
  const apiTokenEnv = loaded.config.api.token_env;
204
- // Readiness spawns Codex. Cache one result briefly and share an in-flight probe.
205
- 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;
206
262
  let codexProbe;
207
263
  const probeCodex = async () => {
208
264
  try {
@@ -210,69 +266,97 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
210
266
  const server = new CodexAppServer(runtime.config.providers.codex.command, runtime.profileDir, env);
211
267
  try {
212
268
  await server.initialize();
213
- const auth = await server.accountStatus();
214
- 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 };
215
270
  }
216
271
  finally {
217
272
  server.close();
218
273
  }
219
274
  }
220
275
  catch (error) {
221
- return error instanceof Error ? error.message : 'Codex App Server unavailable';
276
+ return { auth: null, error: error instanceof Error ? error.message : 'Codex App Server unavailable' };
222
277
  }
223
278
  };
224
- const codexReadinessProblem = async () => {
225
- if (codexReadiness && Date.now() - codexReadiness.at < 30_000)
226
- return codexReadiness.problem;
227
- 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; })
228
283
  .finally(() => { codexProbe = undefined; });
229
284
  return codexProbe;
230
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.
231
295
  app.onError((error, c) => {
232
- const message = error instanceof Error ? error.message : 'Request failed';
233
- const status = /revision conflict|Idempotency key reused|already in progress/i.test(message) ? 409
234
- : /not found|absent/i.test(message) ? 404
235
- : /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
236
- : error instanceof z.ZodError || error instanceof SyntaxError || /invalid|must be|exceeds|requires/i.test(message) ? 400 : 500;
237
- const code = status === 409 ? 'CONFLICT' : status === 404 ? 'NOT_FOUND' : status === 503 ? 'DEPENDENCY_UNAVAILABLE' : status === 400 ? 'INVALID_REQUEST' : 'INTERNAL_ERROR';
238
- // The caller sees only a generic message; record what failed so the operator can find it.
239
- if (status === 500)
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.
240
299
  logger.error('Unhandled management API error', { method: c.req.method, path: c.req.path, err: error });
241
- return c.json({ error: { code, message: status === 500 ? 'Internal request error' : message.slice(0, 500) } }, status);
242
- });
243
- app.get('/health/live', c => c.json({ status: 'live' }));
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));
244
311
  app.get('/health/ready', async (c) => {
245
312
  // Advisory notices (such as a deprecated key) never make a profile unready.
246
313
  const problems = runtimeProblems(runtime.config, env).filter(problem => !isConfigNotice(problem));
247
- if (!problems.length && runtime.config.execution.backend === 'codex') {
248
- const problem = await codexReadinessProblem();
249
- if (problem)
250
- problems.push(problem);
251
- }
252
- if (!problems.length && runtime.config.execution.backend === 'llamacpp') {
253
- const base = resolveReference(runtime.config.providers.llamacpp.base_url, env);
254
- if (base) {
255
- try {
256
- const token = env[runtime.config.providers.llamacpp.api_key_env];
257
- const response = await fetch(llamaEndpoint(base, 'models'), { headers: token ? { Authorization: `Bearer ${token}` } : {}, signal: AbortSignal.timeout(2000), redirect: 'manual' });
258
- if (!response.ok)
259
- problems.push(`llama.cpp model discovery HTTP ${response.status}`);
260
- }
261
- catch {
262
- problems.push('llama.cpp model endpoint is unavailable');
263
- }
264
- }
265
- }
266
- 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);
267
344
  });
268
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;
269
348
  app.use('/api/v1/*', async (c, next) => {
270
349
  const expected = env[apiTokenEnv];
271
- const supplied = c.req.header('Authorization')?.replace(/^Bearer /, '') ?? '';
272
- 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))))
273
354
  return c.json({ error: { code: 'UNAUTHORIZED', message: 'Bearer token required' } }, 401);
274
355
  return next();
275
356
  });
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) }));
276
360
  app.get('/api/v1/status', c => {
277
361
  const tasks = runtime.store.taskCounts();
278
362
  return c.json({ version: ARDENT_VERSION, profile: runtime.config.profile, backend: runtime.config.execution.backend,
@@ -282,7 +366,7 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
282
366
  });
283
367
  app.get('/api/v1/jobs/definitions/status', async (c) => {
284
368
  if (!jobEngine)
285
- throw new Error('Job engine is unavailable');
369
+ throw dependencyUnavailable('Job engine is unavailable');
286
370
  const status = await jobEngine.status();
287
371
  return c.json({ profile: runtime.config.profile, revision: status.active_revision,
288
372
  sha256: status.active_sha256, ...status, last_tick_error: runtime.store.jobTickError() });
@@ -291,12 +375,12 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
291
375
  app.get('/api/v1/config', c => c.json({ revision: current.revision, text: current.text }));
292
376
  app.get('/api/v1/config/schema', c => c.json(toJsonSchema(ConfigSchema)));
293
377
  app.post('/api/v1/config/validate', async (c) => {
294
- 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());
295
379
  const config = parseConfig(input.text);
296
380
  return c.json({ valid: true, profile: config.profile, runtime_problems: runtimeProblems(config, env) });
297
381
  });
298
382
  app.put('/api/v1/config', async (c) => {
299
- const edit = parseJson(await c.req.json(), ConfigEdit);
383
+ const edit = parseJson(await readBody(c), ConfigEdit);
300
384
  const revision = await saveConfig(runtime.profileDir, edit.text, edit.revision);
301
385
  current = await loadConfig(runtime.profileDir);
302
386
  return c.json({ revision, activation_required: true });
@@ -308,7 +392,7 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
308
392
  });
309
393
  app.put('/api/v1/identity/:kind', async (c) => {
310
394
  const kind = z.enum(['soul', 'identity']).parse(c.req.param('kind'));
311
- const edit = parseJson(await c.req.json(), IdentityEdit);
395
+ const edit = parseJson(await readBody(c), IdentityEdit);
312
396
  return c.json(await writeIdentity(runtime.profileDir, runtime.config, kind, edit.text, edit.revision));
313
397
  });
314
398
  app.get('/api/v1/identity/:kind/history', async (c) => {
@@ -317,28 +401,19 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
317
401
  });
318
402
  app.post('/api/v1/identity/:kind/restore', async (c) => {
319
403
  const kind = z.enum(['soul', 'identity']).parse(c.req.param('kind'));
320
- const input = parseJson(await c.req.json(), IdentityRestore);
404
+ const input = parseJson(await readBody(c), IdentityRestore);
321
405
  return c.json(await restoreIdentity(runtime.profileDir, runtime.config, kind, input.history_name, input.revision));
322
406
  });
323
407
  app.get('/api/v1/providers', async (c) => {
324
- let codex = 'unconfigured';
325
- try {
326
- await assertCodexProtocol(runtime.config.providers.codex.command, env);
327
- const server = new CodexAppServer(runtime.config.providers.codex.command, runtime.profileDir, env);
328
- try {
329
- await server.initialize();
330
- codex = await server.accountStatus();
331
- }
332
- finally {
333
- server.close();
334
- }
335
- }
336
- catch (error) {
337
- 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';
338
413
  }
339
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 } });
340
415
  });
341
- app.post('/api/v1/providers/test', async (c) => {
416
+ app.post('/api/v1/providers/test', async (c) => dependency(async () => {
342
417
  if (runtime.config.execution.backend === 'codex') {
343
418
  await assertCodexProtocol(runtime.config.providers.codex.command, env);
344
419
  const server = new CodexAppServer(runtime.config.providers.codex.command, runtime.profileDir, env);
@@ -347,7 +422,7 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
347
422
  const auth = await server.accountStatus();
348
423
  // Match readiness: the account must use the configured auth mode (ChatGPT sign-in or API key).
349
424
  if (auth !== runtime.config.providers.codex.auth_mode)
350
- throw new Error(auth === 'login-required' ? 'Codex login required' : 'Codex account uses the wrong auth mode');
425
+ throw dependencyUnavailable(auth === 'login-required' ? 'Codex login required' : 'Codex account uses the wrong auth mode');
351
426
  return c.json({ backend: 'codex', auth_mode: auth });
352
427
  }
353
428
  finally {
@@ -356,46 +431,47 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
356
431
  }
357
432
  const result = await new LlamaCppBackend(runtime.config.providers.llamacpp, env).complete([{ role: 'user', content: 'Reply with READY.' }], [], AbortSignal.timeout(20000), false);
358
433
  return c.json({ backend: 'llamacpp', answer: result.content, usage: result.usage ?? null });
359
- });
434
+ }, 'Provider unavailable'));
360
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 } }));
361
436
  app.post('/api/v1/channels/:name/test', async (c) => {
362
437
  const name = z.enum(['telegram', 'mattermost']).parse(c.req.param('name'));
363
- if (name === 'telegram') {
364
- const result = await new TelegramAdapter(runtime, runtime.config.channels.telegram, env).initialize(AbortSignal.timeout(10000));
365
- return c.json({ name, status: 'reachable', bot: result, receive_mode: 'polling', polling_started: false });
366
- }
367
- const result = await new MattermostAdapter(runtime, runtime.config.channels.mattermost, env).initialize();
368
- 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');
369
446
  });
370
447
  app.get('/api/v1/peers', async (c) => c.json({ peers: (await listPeers(runtime.profileDir, runtime.config)).map(peer => ({ ...peer,
371
448
  inbound_credential_configured: Boolean(env[inboundTokenEnv(peer)]), outbound_credential_configured: Boolean(env[outboundTokenEnv(peer)]),
372
449
  credential_configured: Boolean(env[inboundTokenEnv(peer)] && env[outboundTokenEnv(peer)]) })) }));
373
450
  app.get('/api/v1/peers/config', async (c) => c.json(await readPeersConfig(runtime.profileDir, runtime.config)));
374
451
  app.post('/api/v1/peers/validate', async (c) => {
375
- 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());
376
453
  return c.json({ valid: true, peers: parsePeersConfig(input.text).length });
377
454
  });
378
455
  app.put('/api/v1/peers/config', async (c) => {
379
- const input = parseJson(await c.req.json(), ConfigEdit);
456
+ const input = parseJson(await readBody(c), ConfigEdit);
380
457
  return c.json({ revision: await savePeersConfig(runtime.profileDir, runtime.config, input.text, input.revision), activation_required: true });
381
458
  });
382
459
  app.post('/api/v1/peers/:id/test', async (c) => {
383
- 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');
384
461
  return c.json({ peer: c.req.param('id'), status: 'reachable', card });
385
462
  });
386
463
  app.put('/api/v1/skills/:name', async (c) => {
387
- const edit = parseJson(await c.req.json(), SkillEdit);
464
+ const edit = parseJson(await readBody(c), SkillEdit);
388
465
  const revision = await setSkillEnabled(runtime.profileDir, c.req.param('name'), edit.enabled, edit.revision);
389
466
  current = await loadConfig(runtime.profileDir);
390
467
  recordSkillChange(runtime.development, c.req.param('name'), edit.enabled, edit.revision, revision);
391
468
  return c.json({ revision, activation_required: true });
392
469
  });
393
470
  app.post('/api/v1/memory/search', async (c) => {
394
- 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());
395
472
  if (runtime.config.memory.provider !== 'hivemem')
396
- throw new Error('Memory provider is unconfigured');
397
- const client = new HiveMemClient(runtime.config.memory, env);
398
- 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') });
399
475
  });
400
476
  app.get('/api/v1/memory/status', async (c) => {
401
477
  const memory = runtime.config.memory;
@@ -443,7 +519,7 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
443
519
  body = JSON.parse(text);
444
520
  }
445
521
  catch {
446
- 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');
447
523
  }
448
524
  parseInput(body, z.object({}).strict());
449
525
  }
@@ -458,9 +534,94 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
458
534
  return c.json({ error: { code: 'INVALID_CREDENTIAL', message: result.problem } }, 422);
459
535
  return c.json({ reloaded: true, token_env: memory.token_env, changed: result.changed });
460
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
+ });
461
622
  app.get('/api/v1/sessions', c => c.json({ sessions: runtime.store.listSessions('management', SessionContext.parse(c.req.query('context') ?? 'direct')) }));
462
623
  app.post('/api/v1/sessions', async (c) => {
463
- const input = parseJson(await c.req.json(), SessionOpen);
624
+ const input = parseJson(await readBody(c), SessionOpen);
464
625
  const context = input.context ?? 'direct';
465
626
  return c.json(input.reset ? runtime.store.resetSession('management', context, input.key) : runtime.store.session('management', context, input.key));
466
627
  });
@@ -472,21 +633,21 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
472
633
  });
473
634
  const view = (task, execution = runtime.store.executionFor(task.id), recovery = recoveryView(runtime.store, task)) => ({ ...task, ...(execution ? { execution } : {}), ...(recovery ? { recovery } : {}) });
474
635
  app.post('/api/v1/tasks', async (c) => {
475
- const input = parseJson(await c.req.json(), Submit);
636
+ const input = parseJson(await readBody(c), Submit);
476
637
  const task = runtime.accept(input.prompt, 'management', 'direct', input.idempotency_key, input.session_id, undefined, undefined, acceptance(c, input.execution));
477
638
  if (task.state === 'queued')
478
639
  void runtime.run(task.id, env).catch(() => { });
479
640
  return c.json({ task_id: task.id, state: task.state }, 202);
480
641
  });
481
642
  app.post('/api/v1/missions', async (c) => {
482
- const input = parseInput(await c.req.json(), MissionSubmit);
643
+ const input = parseInput(await readBody(c), MissionSubmit);
483
644
  let task;
484
645
  try {
485
646
  task = runtime.acceptMission(input, 'management', acceptance(c, input.execution));
486
647
  }
487
648
  catch (error) {
488
- if (error instanceof Error && /Session caller or context mismatch/.test(error.message))
489
- 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');
490
651
  throw error;
491
652
  }
492
653
  if (task.state === 'queued')
@@ -494,10 +655,14 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
494
655
  return c.json({ task_id: task.id, state: task.state }, 202);
495
656
  });
496
657
  app.get('/api/v1/tasks', c => {
497
- 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 } : {}) });
498
663
  const executions = runtime.store.executions.many(tasks.map(task => task.id));
499
664
  const recoveries = runtime.store.executionState.recoveries(tasks.map(task => task.id));
500
- 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 });
501
666
  });
502
667
  app.get('/api/v1/tasks/:id', c => {
503
668
  const task = runtime.store.get(c.req.param('id'));
@@ -518,16 +683,9 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
518
683
  const id = c.req.param('id');
519
684
  if (!runtime.store.get(id))
520
685
  return c.json({ error: { code: 'NOT_FOUND', message: 'Task not found' } }, 404);
521
- const input = parseInput(await c.req.json(), RecoveryDecisionInput);
522
- let decided;
523
- try {
524
- decided = await runtime.decideRecovery(id, input, env, 'management');
525
- }
526
- catch (error) {
527
- if (error instanceof RecoveryConflictError)
528
- return c.json({ error: { code: 'CONFLICT', message: error.message.slice(0, 500) } }, 409);
529
- throw error;
530
- }
686
+ const input = parseInput(await readBody(c), RecoveryDecisionInput);
687
+ // A RecoveryConflictError answers 409 CONFLICT.
688
+ const decided = await runtime.decideRecovery(id, input, env, 'management');
531
689
  if (decided.continuation?.state === 'queued')
532
690
  void runtime.run(decided.continuation.id, env).catch(() => { });
533
691
  return c.json(decided.recovery);
@@ -553,31 +711,45 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
553
711
  // Live reply text is not journaled, so its events carry no id and a reconnect
554
712
  // starts from a task.text snapshot of the current step instead of a replay.
555
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;
556
717
  let wake;
557
- 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);
558
722
  const snapshot = runtime.liveText.snapshot(id);
559
723
  if (snapshot)
560
724
  live.push({ kind: 'text', ...snapshot });
725
+ let lastWrite = Date.now();
726
+ const write = async (message) => { await stream.writeSSE(message); lastWrite = Date.now(); };
561
727
  try {
562
- const until = Date.now() + 60_000;
728
+ const until = Date.now() + STREAM_ROTATION_MS;
563
729
  while (!stream.aborted && Date.now() < until) {
730
+ dirty = false;
564
731
  for (const update of live.splice(0)) {
565
732
  if (update.kind !== 'end')
566
- 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 }) });
567
734
  }
568
735
  const events = runtime.store.events(id, after, 100);
569
736
  for (const event of events) {
570
- 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) });
571
738
  after = event.sequence;
572
739
  }
573
740
  const task = runtime.store.get(id);
574
741
  if (!task || ['completed', 'partial', 'failed', 'cancelled', 'unknown'].includes(task.state)) {
575
- 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' }) });
576
743
  break;
577
744
  }
578
- 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) {
579
751
  await new Promise(resolve => {
580
- 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())));
581
753
  wake = () => { clearTimeout(timer); resolve(); };
582
754
  });
583
755
  wake = undefined;
@@ -586,6 +758,7 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
586
758
  }
587
759
  finally {
588
760
  unsubscribe();
761
+ unsubscribeJournal();
589
762
  }
590
763
  });
591
764
  });
@@ -595,25 +768,19 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
595
768
  const id = c.req.param('id');
596
769
  if (!runtime.store.get(id))
597
770
  return c.json({ error: { code: 'NOT_FOUND', message: 'Task not found' } }, 404);
598
- try {
599
- const { task, admission } = action === 'pause' ? runtime.pause(id) : runtime.resume(id);
600
- return c.json({ task_id: task.id, state: task.state, admission });
601
- }
602
- catch (error) {
603
- if (error && typeof error === 'object' && 'code' in error && error.code === 'TASK_TERMINAL')
604
- return c.json({ error: { code: 'CONFLICT', message: error instanceof Error ? error.message : 'Task already finished' } }, 409);
605
- throw error;
606
- }
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 });
607
774
  });
608
775
  app.post('/api/v1/preview/tasks', async (c) => {
609
- const input = parseInput(await c.req.json(), PreviewSubmit);
776
+ const input = parseInput(await readBody(c), PreviewSubmit);
610
777
  let task;
611
778
  try {
612
779
  task = runtime.acceptPreview(input, 'management', acceptance(c, input.execution));
613
780
  }
614
781
  catch (error) {
615
- if (error instanceof Error && /Session caller or context mismatch/.test(error.message))
616
- 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');
617
784
  throw error;
618
785
  }
619
786
  if (task.state === 'queued')
@@ -627,7 +794,7 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
627
794
  return c.json(await developmentPage({ records: runtime.development, profileDir: runtime.profileDir, config: runtime.config }, query));
628
795
  });
629
796
  app.post('/api/v1/development', async (c) => {
630
- const { author, ...note } = parseInput(await c.req.json(), DevelopmentPost);
797
+ const { author, ...note } = parseInput(await readBody(c), DevelopmentPost);
631
798
  return c.json(runtime.development.add({ ...note, author: author ?? 'operator', epistemic: author === 'agent' ? 'agent_reported' : 'operator_reported' }), 201);
632
799
  });
633
800
  app.get('/api/v1/tasks/:id/artifacts', c => {
@@ -644,7 +811,7 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
644
811
  });
645
812
  // Imports register before /artifacts/:id so their static segment is not read as a digest.
646
813
  app.post('/api/v1/artifacts/imports', async (c) => {
647
- const record = transfers.start(parseInput(await c.req.json(), ArtifactImportRequestSchema), 'management');
814
+ const record = transfers.start(parseInput(await readBody(c), ArtifactImportRequestSchema), 'management');
648
815
  return c.json({ import_id: record.import_id }, 202);
649
816
  });
650
817
  app.get('/api/v1/artifacts/imports', c => c.json({ imports: transfers.list(PageLimit.parse(c.req.query('limit') ?? 50)) }));
@@ -695,6 +862,8 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
695
862
  if (!plugin.routes)
696
863
  continue;
697
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); });
698
867
  plugin.routes(sub, ctx);
699
868
  app.route(`/api/v1/plugins/${plugin.name}`, sub);
700
869
  }