@hivemagnus/ardent 3.1.4 → 3.2.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 (79) hide show
  1. package/README.md +475 -4
  2. package/dist/a2a-client.d.ts +26 -4
  3. package/dist/a2a-client.js +91 -23
  4. package/dist/a2a-push-inbox.d.ts +2 -0
  5. package/dist/a2a-push-inbox.js +7 -0
  6. package/dist/a2a-push.d.ts +1 -1
  7. package/dist/a2a-push.js +26 -18
  8. package/dist/a2a-server.d.ts +17 -0
  9. package/dist/a2a-server.js +91 -14
  10. package/dist/a2a.d.ts +19 -1
  11. package/dist/a2a.js +197 -27
  12. package/dist/api.d.ts +2 -0
  13. package/dist/api.js +160 -22
  14. package/dist/artifact-manifests.d.ts +344 -5
  15. package/dist/artifact-manifests.js +413 -20
  16. package/dist/artifact-transfer.d.ts +113 -0
  17. package/dist/artifact-transfer.js +517 -0
  18. package/dist/artifacts.d.ts +86 -0
  19. package/dist/artifacts.js +249 -1
  20. package/dist/backend-events.d.ts +2 -1
  21. package/dist/backend-events.js +1 -1
  22. package/dist/channel-catchup.d.ts +67 -0
  23. package/dist/channel-catchup.js +108 -0
  24. package/dist/channels.d.ts +35 -0
  25. package/dist/channels.js +152 -4
  26. package/dist/cli.js +28 -3
  27. package/dist/codex-protocol.d.ts +22 -0
  28. package/dist/codex-protocol.js +19 -0
  29. package/dist/codex.d.ts +32 -3
  30. package/dist/codex.js +91 -17
  31. package/dist/config.d.ts +25 -2
  32. package/dist/config.js +41 -4
  33. package/dist/development.d.ts +6 -6
  34. package/dist/execution-state.d.ts +245 -0
  35. package/dist/execution-state.js +236 -0
  36. package/dist/execution.d.ts +135 -0
  37. package/dist/execution.js +178 -0
  38. package/dist/index.d.ts +7 -4
  39. package/dist/index.js +5 -3
  40. package/dist/job-engine.d.ts +2 -1
  41. package/dist/job-engine.js +33 -4
  42. package/dist/lineage.d.ts +106 -0
  43. package/dist/lineage.js +145 -0
  44. package/dist/llamacpp.d.ts +32 -2
  45. package/dist/llamacpp.js +69 -33
  46. package/dist/mattermost.d.ts +8 -0
  47. package/dist/mattermost.js +250 -36
  48. package/dist/mission-tools.js +41 -5
  49. package/dist/missions.d.ts +5 -1
  50. package/dist/missions.js +10 -5
  51. package/dist/plugin-evidence.js +2 -1
  52. package/dist/plugin-sdk.d.ts +3 -0
  53. package/dist/plugin-sdk.js +3 -0
  54. package/dist/plugins.d.ts +108 -2
  55. package/dist/plugins.js +131 -1
  56. package/dist/preview.d.ts +1 -0
  57. package/dist/preview.js +4 -1
  58. package/dist/recovery.d.ts +155 -0
  59. package/dist/recovery.js +216 -0
  60. package/dist/research.d.ts +1 -1
  61. package/dist/retry.d.ts +143 -0
  62. package/dist/retry.js +127 -0
  63. package/dist/runtime.d.ts +56 -4
  64. package/dist/runtime.js +727 -125
  65. package/dist/store.d.ts +62 -7
  66. package/dist/store.js +86 -15
  67. package/dist/team-artifacts.d.ts +130 -112
  68. package/dist/team-artifacts.js +123 -151
  69. package/dist/team-child.d.ts +4 -1
  70. package/dist/team-child.js +21 -2
  71. package/dist/team-contract.d.ts +1 -1
  72. package/dist/telegram.d.ts +2 -0
  73. package/dist/telegram.js +83 -47
  74. package/dist/tool-scheduler.d.ts +84 -0
  75. package/dist/tool-scheduler.js +226 -0
  76. package/dist/tools.d.ts +78 -4
  77. package/dist/tools.js +34 -7
  78. package/package.json +15 -8
  79. package/profiles/assistant/config.yaml +2 -1
package/dist/api.js CHANGED
@@ -4,7 +4,7 @@ import { streamSSE } from 'hono/streaming';
4
4
  import { z } from 'zod';
5
5
  import { ARDENT_VERSION } from './version.js';
6
6
  import { ConfigSchema } from './config.js';
7
- import { runtimeProblems, saveConfig, loadConfig, resolveReference, parseConfig } from './config.js';
7
+ import { isConfigNotice, runtimeProblems, saveConfig, loadConfig, resolveReference, parseConfig } from './config.js';
8
8
  import { listSkills, setSkillEnabled } from './skills.js';
9
9
  import { HiveMemClient } from './memory.js';
10
10
  import { llamaEndpoint, LlamaCppBackend } from './llamacpp.js';
@@ -15,15 +15,30 @@ import { inboundTokenEnv, listPeers, outboundTokenEnv, parsePeersConfig, readPee
15
15
  import { ArdentA2AClient } from './a2a-client.js';
16
16
  import { TelegramAdapter } from './telegram.js';
17
17
  import { MattermostAdapter } from './mattermost.js';
18
+ import { CatchupStatusSchema } from './channel-catchup.js';
18
19
  import { EventSchema, SessionMessageSchema, SessionSchema, TaskSchema, TaskState } from './store.js';
19
20
  import { mountPluginHttp } from './plugin-http.js';
20
21
  import { pluginContext } from './plugins.js';
21
22
  import { MissionSubmit } from './missions.js';
22
- import { ArtifactRecordSchema } from './artifact-manifests.js';
23
+ import { ArtifactRecordSchema, ArtifactRecordV2Schema, ArtifactRenditionSchema } from './artifact-manifests.js';
24
+ import { ArtifactImportRequestSchema, ArtifactImportSchema, ArtifactTransfers } from './artifact-transfer.js';
25
+ import { formatReprDigest, parseByteRange } from '@hivemagnus/hive-common/artifact';
23
26
  import { PreviewSubmit } from './preview.js';
24
27
  import { developmentPage, DevelopmentKind, DevelopmentNoteInput, DevelopmentRecordSchema, recordSkillChange } from './development.js';
25
28
  import { readProfileEnv } from './profile-env.js';
26
- 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() }).strict();
29
+ import { ExecutionContextSchema, ExecutionInput } from './execution.js';
30
+ import { TaskLineageSchema, taskLineage } from './lineage.js';
31
+ import { readExecutionHeader } from '@hivemagnus/hive-common/execution';
32
+ import { RecoveryDecisionInput, RecoveryViewSchema, recoveryView } from './recovery.js';
33
+ import { RecoveryConflictError } from './runtime.js';
34
+ 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
+ execution: ExecutionInput.optional() }).strict();
36
+ /** A task as the management API reports it: the stored row plus its execution context and recovery, when it has them. */
37
+ const TaskView = TaskSchema.extend({ execution: ExecutionContextSchema.optional(), recovery: RecoveryViewSchema.optional() });
38
+ const RecoveryCounts = z.object({ ready: z.number().int(), reconciling: z.number().int(), awaiting_decision: z.number().int(), unsupported: z.number().int() })
39
+ .describe('Tasks in each open execution recovery status');
40
+ /** Request bodies as documented: `execution` is an execution context v1, accepted leniently. */
41
+ const documented = (schema) => schema.extend({ execution: ExecutionContextSchema.optional() });
27
42
  /** Contexts a management caller may open a session in. A session serves tasks of its own context only. */
28
43
  const SessionContext = z.enum(['direct', 'mission', 'preview']);
29
44
  const Admission = z.object({ task_id: z.string().guid(), state: TaskState, admission: z.enum(['open', 'paused']) });
@@ -67,14 +82,37 @@ const a2aConfigId = { in: 'path', name: 'configId', required: true, schema: { ty
67
82
  const a2aBody = { required: true, content: { 'application/json': { schema: { type: 'object', additionalProperties: true }, example: { message: { messageId: 'request-1', role: 'user', parts: [{ kind: 'text', text: 'Research the current update' }] } } } } };
68
83
  const a2aResult = { '200': { description: 'A2A v1 task or message; see the pinned A2A protocol contract', content: { 'application/json': { schema: { type: 'object', additionalProperties: true } } } }, '400': { description: 'Invalid A2A request' }, '401': { description: 'Peer authentication failed' }, '404': { description: 'Task or configuration absent' } };
69
84
  const taskExample = { id: '11111111-1111-4111-8111-111111111111', caller: 'management', context: 'direct', session_id: null, prompt: 'Research the current update', content_hash: '0'.repeat(64), idempotency_key: 'research-1', backend: 'llamacpp', state: 'queued', result: null, error: null, deadline_ms: 1790438400000, created_ms: 1790431200000, updated_ms: 1790431200000 };
85
+ const artifactDigest = { in: 'path', name: 'sha256', required: true, schema: { type: 'string', pattern: '^[a-f0-9]{64}$' } };
86
+ const artifactBytes = (description) => ({ description, headers: Object.fromEntries(['Accept-Ranges', 'ETag', 'Repr-Digest', 'X-Content-SHA256', 'Content-Disposition', 'Content-Range']
87
+ .map(name => [name, { schema: { type: 'string' } }])), content: { '*/*': { schema: { type: 'string', format: 'binary' } } } });
70
88
  const eventExample = { sequence: 1, task_id: taskExample.id, kind: 'task_accepted', detail: { backend: 'llamacpp' }, created_ms: 1790431200000 };
71
89
  const sseExample = `event: task.event\nid: 1\ndata: ${JSON.stringify(eventExample)}\n\nevent: task.text\ndata: ${JSON.stringify({ step: 0, text: 'The bridge' })}\n\nevent: task.delta\ndata: ${JSON.stringify({ step: 0, text: ' holds.' })}\n\n`;
90
+ /** Send a file stream with backpressure; a HEAD request closes it unread. */
91
+ function streamed(c, stream, status, headers) {
92
+ if (c.req.method === 'HEAD') {
93
+ stream.destroy();
94
+ return new Response(null, { status, headers });
95
+ }
96
+ const chunks = stream[Symbol.asyncIterator]();
97
+ // Pull-based: the next file chunk is read only when the client has taken the last one.
98
+ const body = new ReadableStream({
99
+ async pull(controller) {
100
+ const next = await chunks.next();
101
+ if (next.done)
102
+ controller.close();
103
+ else
104
+ controller.enqueue(z.instanceof(Uint8Array).parse(next.value));
105
+ },
106
+ cancel() { stream.destroy(); }
107
+ });
108
+ return new Response(body, { status, headers });
109
+ }
72
110
  export function ardentOpenApi() {
73
111
  return {
74
112
  openapi: '3.1.0', info: { title: 'Magnus Ardent API', version: ARDENT_VERSION },
75
113
  servers: [{ url: '/' }],
76
114
  components: { securitySchemes: { bearerAuth: { type: 'http', scheme: 'bearer' } }, schemas: {
77
- Task: jsonSchema(TaskSchema), TaskEvent: jsonSchema(EventSchema),
115
+ Task: jsonSchema(TaskView), TaskEvent: jsonSchema(EventSchema),
78
116
  Error: { type: 'object', required: ['error'], properties: { error: { type: 'object', required: ['code', 'message'], properties: { code: { type: 'string' }, message: { type: 'string' } } } } }
79
117
  } },
80
118
  paths: {
@@ -90,16 +128,21 @@ export function ardentOpenApi() {
90
128
  '/a2a/rest/tasks/{taskId}/pushNotificationConfigs': { post: { operationId: 'a2aSetPushConfig', servers: a2aServer, security: [{ bearerAuth: [] }], parameters: [a2aVersion, a2aTaskId], requestBody: { required: true, content: { 'application/json': { schema: { type: 'object', additionalProperties: true } } } }, responses: { '201': { description: 'Created push configuration', content: { 'application/json': { schema: { type: 'object', additionalProperties: true } } } }, '400': { description: 'Invalid configuration' }, '401': { description: 'Peer authentication failed' }, '404': { description: 'Task absent' } } }, get: { operationId: 'a2aListPushConfigs', servers: a2aServer, security: [{ bearerAuth: [] }], parameters: [a2aVersion, a2aTaskId], responses: a2aResult } },
91
129
  '/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' } } } },
92
130
  '/api/v1/tasks': {
93
- post: { operationId: 'submitTask', security: [{ bearerAuth: [] }], requestBody: { required: true, content: { 'application/json': { schema: jsonSchema(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' } } },
131
+ 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' } } },
94
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] } } } } } }
95
133
  },
96
- '/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(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' } } } },
97
- '/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(PreviewSubmit) } } }, responses: { '202': jsonResponse('Accepted preview task', Accepted), '400': { description: 'Invalid request' }, '401': { description: 'Unauthorized' }, '409': { description: 'Conflicting idempotency key' } } } },
134
+ '/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
+ '/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' } } } },
98
136
  '/api/v1/development': { get: { operationId: 'listDevelopment', description: 'The agent\'s development history in creation order: its development notes, operator notes, skill changes, identity edits and method reflections.', security: [{ bearerAuth: [] }], parameters: [{ in: 'query', name: 'after', description: 'Cursor from a previous page (next)', schema: { type: 'string' } }, { in: 'query', name: 'limit', schema: { type: 'integer', minimum: 1, maximum: 200, default: 50 } }, { in: 'query', name: 'kind', schema: { type: 'string', pattern: '^[a-z][a-z0-9_]{0,63}$' } }], responses: { '200': jsonResponse('One page of development records; next is null on the last page', DevelopmentPage), '400': { description: 'Invalid cursor or kind' } } },
99
137
  post: { operationId: 'addDevelopmentNote', description: 'Record an operator note (default) or an agent note relayed by a coordinator.', security: [{ bearerAuth: [] }], requestBody: { required: true, content: { 'application/json': { schema: jsonSchema(DevelopmentPost) } } }, responses: { '201': jsonResponse('Stored development record', DevelopmentRecordSchema), '400': { description: 'Invalid note' } } } },
100
138
  '/api/v1/sessions': { get: { operationId: 'listSessions', security: [{ bearerAuth: [] }], parameters: [{ in: 'query', name: 'context', description: 'Session context (default direct)', schema: { type: 'string', enum: ['direct', 'mission', 'preview'] } }], responses: { '200': jsonResponse('Caller sessions', z.object({ sessions: z.array(SessionSchema) })) } }, post: { operationId: 'openSession', security: [{ bearerAuth: [] }], requestBody: { required: true, content: { 'application/json': { schema: jsonSchema(SessionOpen) } } }, responses: { '200': jsonResponse('Existing or new session', SessionSchema) } } },
101
139
  '/api/v1/sessions/{id}/messages': { get: { operationId: 'getSessionMessages', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'id', required: true, schema: { type: 'string', format: 'uuid' } }], responses: { '200': jsonResponse('Recent caller session messages', z.object({ messages: z.array(SessionMessageSchema) })), '404': { description: 'Session absent' } } } },
102
140
  '/api/v1/tasks/{id}': { get: { operationId: 'getTask', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'id', required: true, schema: { type: 'string' } }], responses: { '200': { description: 'Task status', content: { 'application/json': { schema: { $ref: '#/components/schemas/Task' }, example: taskExample } } }, '404': { description: 'Task absent' } } } },
141
+ '/api/v1/tasks/{id}/recovery': {
142
+ get: { operationId: 'getTaskRecovery', description: 'Execution recovery of a task interrupted by a crash or restart: its status, actionable reason, checkpoint with pending tool calls, and the operator actions valid now. A resumed task stays running under the same id; a held task is unknown.', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'id', required: true, schema: { type: 'string' } }], responses: { '200': jsonResponse('Task recovery', RecoveryViewSchema), '404': { description: 'Task absent, or never interrupted' } } },
143
+ post: { operationId: 'decideTaskRecovery', description: 'Resolve a task held awaiting_decision. mark_applied (optional result, at most 64 KiB, checked against the tool output schema), mark_not_applied and retry_with_new_deadline (the pending call is dispatched again under its idempotency key; deadline_seconds at most execution.recovery_max_new_deadline_seconds) continue the work as a linked continuation task; abandon only records the decision. A held task stays unknown. Idempotent per task, attempt and action.', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'id', required: true, schema: { type: 'string' } }], requestBody: { required: true, content: { 'application/json': { schema: jsonSchema(RecoveryDecisionInput) } } }, responses: { '200': jsonResponse('Recovery after the decision; continuation_task_id names the continuation task', RecoveryViewSchema), '400': { description: 'Invalid decision' }, '404': { description: 'Task absent' }, '409': { description: 'No decision, or not this one, is valid now' } } }
144
+ },
145
+ '/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' } } } },
103
146
  '/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] } } } } } } },
104
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' } } } },
105
148
  '/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' } } } },
@@ -107,8 +150,16 @@ export function ardentOpenApi() {
107
150
  '/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' } } } },
108
151
  '/api/v1/tasks/{id}/artifacts': { get: { operationId: 'listTaskArtifacts', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'id', required: true, schema: { type: 'string' } }], responses: { '200': jsonResponse('Current manifests of artifacts the task registered, oldest first', z.object({ artifacts: z.array(ArtifactRecordSchema) })), '404': { description: 'Task absent' } } } },
109
152
  '/api/v1/artifacts/{sha256}/manifest': { get: { operationId: 'getArtifactManifest', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'sha256', required: true, schema: { type: 'string', pattern: '^[a-f0-9]{64}$' } }], responses: { '200': jsonResponse('Newest current manifest registered for the digest', ArtifactRecordSchema), '404': { description: 'No current manifest' } } } },
110
- '/api/v1/artifacts/{id}': { get: { operationId: 'getArtifact', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'id', required: true, schema: { type: 'string' } }], responses: { '200': { description: 'Artifact bytes' }, '404': { description: 'Artifact absent' } } } },
111
- '/api/v1/status': { get: { operationId: 'getOperationalStatus', security: [{ bearerAuth: [] }], responses: { '200': jsonResponse('Active profile summary', z.object({ version: z.string(), profile: z.string(), backend: z.enum(['llamacpp', 'codex']), tasks: z.number().int() })) } } },
153
+ '/api/v1/artifacts/{id}': { get: { operationId: 'getArtifact', description: 'Artifact bytes as application/octet-stream, streamed and verified against the digest as they are sent (a mismatch ends the response before its last chunk). Use /content for the media type, ranges and digest headers.', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'id', required: true, schema: { type: 'string' } }], responses: { '200': { description: 'Artifact bytes' }, '404': { description: 'Artifact absent' } } } },
154
+ '/api/v1/artifacts/{sha256}/content': { get: { operationId: 'getArtifactContent', description: 'Artifact transfer v2 content. Without Range (or with an If-Range that is not the ETag) the whole artifact is returned with 200 and verified as it streams; a single Range returns 206 with Content-Range, an unsatisfiable one 416. Every response carries Accept-Ranges: bytes, ETag "<sha256>", Repr-Digest (RFC 9530 sha-256), X-Content-SHA256, the manifest media type and Content-Disposition: attachment with the manifest name. A rendition has its own digest and is fetched the same way.', security: [{ bearerAuth: [] }], parameters: [artifactDigest, { in: 'header', name: 'Range', required: false, schema: { type: 'string', example: 'bytes=0-1048575' } }, { in: 'header', name: 'If-Range', required: false, schema: { type: 'string' } }], responses: { '200': artifactBytes('Whole artifact'), '206': artifactBytes('One byte range'), '404': { description: 'Artifact absent' }, '416': { description: 'Range not satisfiable; Content-Range: bytes */<size>' } } } },
155
+ '/api/v1/artifacts/{sha256}/renditions': { get: { operationId: 'listArtifactRenditions', description: 'Every current form of an artifact, the original first (role original, purpose download). Given an original or any of its renditions, the list is the same. Select with HiveCommon selectRendition; download always means the original.', security: [{ bearerAuth: [] }], parameters: [artifactDigest], responses: { '200': jsonResponse('Original and renditions', z.object({ renditions: z.array(ArtifactRenditionSchema) })), '404': { description: 'No current manifest' } } } },
156
+ '/api/v1/artifacts/{sha256}/manifest/v2': { get: { operationId: 'getArtifactManifestV2', description: 'Newest current manifest for the digest as manifest 1.1 (a strict superset of 1.0 with optional rendition and provenance.execution).', security: [{ bearerAuth: [] }], parameters: [artifactDigest], responses: { '200': jsonResponse('Manifest 1.1 record', ArtifactRecordV2Schema), '404': { description: 'No current manifest' } } } },
157
+ '/api/v1/artifacts/imports': {
158
+ post: { operationId: 'importArtifact', description: 'Pull one artifact a configured A2A peer exported from one of its completed tasks, with transfer v2 (Range resume, SHA-256 verification) or, for an older peer, the v1 path up to 2 MiB. Idempotent per peer, task and artifact: a repeat returns the same import, and a failed import is queued again from its retained bytes. The import runs in the background and resumes after a restart.', security: [{ bearerAuth: [] }], requestBody: { required: true, content: { 'application/json': { schema: jsonSchema(ArtifactImportRequestSchema) } } }, responses: { '202': jsonResponse('Accepted import', z.object({ import_id: z.string() })), '400': { description: 'Invalid request' }, '404': { description: 'Local task absent' } } },
159
+ 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
+ },
161
+ '/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() })) } } },
112
163
  '/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' } } } },
113
164
  '/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() })) } } },
114
165
  '/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' } } } },
@@ -141,6 +192,7 @@ export function ardentOpenApi() {
141
192
  */
142
193
  export function createArdentApi(runtime, loaded, env = process.env, jobEngine, options = {}) {
143
194
  const app = new Hono();
195
+ const transfers = options.artifactTransfers ?? new ArtifactTransfers(runtime, env);
144
196
  let current = loaded;
145
197
  // A saved configuration requires activation; it must not rotate the live
146
198
  // management credential before the gateway restarts with it.
@@ -183,7 +235,8 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
183
235
  });
184
236
  app.get('/health/live', c => c.json({ status: 'live' }));
185
237
  app.get('/health/ready', async (c) => {
186
- const problems = runtimeProblems(runtime.config, env);
238
+ // Advisory notices (such as a deprecated key) never make a profile unready.
239
+ const problems = runtimeProblems(runtime.config, env).filter(problem => !isConfigNotice(problem));
187
240
  if (!problems.length && runtime.config.execution.backend === 'codex') {
188
241
  const problem = await codexReadinessProblem();
189
242
  if (problem)
@@ -213,7 +266,9 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
213
266
  return c.json({ error: { code: 'UNAUTHORIZED', message: 'Bearer token required' } }, 401);
214
267
  return next();
215
268
  });
216
- 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 }));
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() }));
217
272
  app.get('/api/v1/jobs/definitions/status', async (c) => {
218
273
  if (!jobEngine)
219
274
  throw new Error('Job engine is unavailable');
@@ -398,9 +453,15 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
398
453
  return c.json(input.reset ? runtime.store.resetSession('management', context, input.key) : runtime.store.session('management', context, input.key));
399
454
  });
400
455
  app.get('/api/v1/sessions/:id/messages', c => c.json({ messages: runtime.store.sessionMessages(c.req.param('id'), 'management') }));
456
+ /** The caller's execution context: the body field, else the `x-hive-execution` header. Never rejected. */
457
+ const acceptance = (c, body) => ({
458
+ context: body ?? readExecutionHeader(name => c.req.header(name)), source: 'caller',
459
+ requestId: c.req.header('x-request-id'), traceparent: c.req.header('traceparent')
460
+ });
461
+ const view = (task, execution = runtime.store.executionFor(task.id), recovery = recoveryView(runtime.store, task)) => ({ ...task, ...(execution ? { execution } : {}), ...(recovery ? { recovery } : {}) });
401
462
  app.post('/api/v1/tasks', async (c) => {
402
463
  const input = parseJson(await c.req.json(), Submit);
403
- const task = runtime.accept(input.prompt, 'management', 'direct', input.idempotency_key, input.session_id);
464
+ const task = runtime.accept(input.prompt, 'management', 'direct', input.idempotency_key, input.session_id, undefined, undefined, acceptance(c, input.execution));
404
465
  if (task.state === 'queued')
405
466
  void runtime.run(task.id, env).catch(() => { });
406
467
  return c.json({ task_id: task.id, state: task.state }, 202);
@@ -409,7 +470,7 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
409
470
  const input = parseInput(await c.req.json(), MissionSubmit);
410
471
  let task;
411
472
  try {
412
- task = runtime.acceptMission(input, 'management');
473
+ task = runtime.acceptMission(input, 'management', acceptance(c, input.execution));
413
474
  }
414
475
  catch (error) {
415
476
  if (error instanceof Error && /Session caller or context mismatch/.test(error.message))
@@ -420,12 +481,50 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
420
481
  void runtime.run(task.id, env).catch(() => { });
421
482
  return c.json({ task_id: task.id, state: task.state }, 202);
422
483
  });
423
- app.get('/api/v1/tasks', c => c.json({ tasks: runtime.store.list(PageLimit.parse(c.req.query('limit') ?? 50)) }));
484
+ app.get('/api/v1/tasks', c => {
485
+ const tasks = runtime.store.list(PageLimit.parse(c.req.query('limit') ?? 50));
486
+ const executions = runtime.store.executions.many(tasks.map(task => task.id));
487
+ 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)))) });
489
+ });
424
490
  app.get('/api/v1/tasks/:id', c => {
425
491
  const task = runtime.store.get(c.req.param('id'));
426
492
  if (!task)
427
493
  return c.json({ error: { code: 'NOT_FOUND', message: 'Task not found' } }, 404);
428
- return c.json(task);
494
+ return c.json(view(task));
495
+ });
496
+ app.get('/api/v1/tasks/:id/recovery', c => {
497
+ const task = runtime.store.get(c.req.param('id'));
498
+ if (!task)
499
+ return c.json({ error: { code: 'NOT_FOUND', message: 'Task not found' } }, 404);
500
+ const recovery = recoveryView(runtime.store, task);
501
+ if (!recovery)
502
+ return c.json({ error: { code: 'NOT_FOUND', message: 'Task was never interrupted; it has no recovery' } }, 404);
503
+ return c.json(recovery);
504
+ });
505
+ app.post('/api/v1/tasks/:id/recovery', async (c) => {
506
+ const id = c.req.param('id');
507
+ if (!runtime.store.get(id))
508
+ 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
+ }
519
+ if (decided.continuation?.state === 'queued')
520
+ void runtime.run(decided.continuation.id, env).catch(() => { });
521
+ return c.json(decided.recovery);
522
+ });
523
+ app.get('/api/v1/tasks/:id/lineage', c => {
524
+ const lineage = taskLineage(runtime.store, runtime.instanceRef, c.req.param('id'));
525
+ if (!lineage)
526
+ return c.json({ error: { code: 'NOT_FOUND', message: 'Task not found' } }, 404);
527
+ return c.json(lineage);
429
528
  });
430
529
  app.get('/api/v1/tasks/:id/events', c => {
431
530
  const id = c.req.param('id');
@@ -498,7 +597,7 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
498
597
  const input = parseInput(await c.req.json(), PreviewSubmit);
499
598
  let task;
500
599
  try {
501
- task = runtime.acceptPreview(input, 'management');
600
+ task = runtime.acceptPreview(input, 'management', acceptance(c, input.execution));
502
601
  }
503
602
  catch (error) {
504
603
  if (error instanceof Error && /Session caller or context mismatch/.test(error.message))
@@ -531,13 +630,52 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
531
630
  return c.json({ error: { code: 'NOT_FOUND', message: 'Artifact manifest not found' } }, 404);
532
631
  return c.json(record);
533
632
  });
633
+ // Imports register before /artifacts/:id so their static segment is not read as a digest.
634
+ app.post('/api/v1/artifacts/imports', async (c) => {
635
+ const record = transfers.start(parseInput(await c.req.json(), ArtifactImportRequestSchema), 'management');
636
+ return c.json({ import_id: record.import_id }, 202);
637
+ });
638
+ app.get('/api/v1/artifacts/imports', c => c.json({ imports: transfers.list(PageLimit.parse(c.req.query('limit') ?? 50)) }));
639
+ app.get('/api/v1/artifacts/imports/:id', c => {
640
+ const record = transfers.get(c.req.param('id'));
641
+ return record ? c.json(record) : c.json({ error: { code: 'NOT_FOUND', message: 'Artifact import not found' } }, 404);
642
+ });
643
+ const artifactAbsent = (c) => c.json({ error: { code: 'NOT_FOUND', message: 'Artifact not found' } }, 404);
644
+ app.get('/api/v1/artifacts/:sha256/manifest/v2', c => {
645
+ const record = runtime.artifactManifests.manifestV2(c.req.param('sha256'));
646
+ return record ? c.json(record) : c.json({ error: { code: 'NOT_FOUND', message: 'Artifact manifest not found' } }, 404);
647
+ });
648
+ app.get('/api/v1/artifacts/:sha256/renditions', async (c) => {
649
+ const renditions = await runtime.artifactManifests.renditions(c.req.param('sha256'));
650
+ return renditions ? c.json({ renditions }) : c.json({ error: { code: 'NOT_FOUND', message: 'Artifact manifest not found' } }, 404);
651
+ });
652
+ app.get('/api/v1/artifacts/:sha256/content', async (c) => {
653
+ const sha = c.req.param('sha256');
654
+ if (!/^[a-f0-9]{64}$/.test(sha))
655
+ return artifactAbsent(c);
656
+ const stat = await runtime.artifacts.stat(sha).catch(() => undefined);
657
+ if (!stat)
658
+ return artifactAbsent(c);
659
+ const manifest = runtime.artifactManifests.manifestV2(sha)?.manifest;
660
+ const etag = `"${sha}"`;
661
+ const ifRange = c.req.header('If-Range');
662
+ const range = parseByteRange(ifRange === undefined || ifRange === etag ? c.req.header('Range') : undefined, stat.size);
663
+ const headers = { 'Accept-Ranges': 'bytes', ETag: etag, 'Repr-Digest': formatReprDigest(sha), 'X-Content-SHA256': sha,
664
+ 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'private, no-store' };
665
+ if (range === null)
666
+ return c.json({ error: { code: 'RANGE_NOT_SATISFIABLE', message: 'Requested range is not satisfiable' } }, 416, { ...headers, 'Content-Range': `bytes */${stat.size}` });
667
+ const read = await runtime.artifacts.openRead(sha, range ?? {}, { verify: !range }).catch(() => undefined);
668
+ if (!read)
669
+ return artifactAbsent(c);
670
+ Object.assign(headers, { 'Content-Type': manifest?.mime ?? 'application/octet-stream', 'Content-Length': String(read.end - read.start + 1),
671
+ 'Content-Disposition': `attachment; filename="${manifest?.name ?? sha}"`, ...(range ? { 'Content-Range': `bytes ${read.start}-${read.end}/${stat.size}` } : {}) });
672
+ return streamed(c, read.stream, range ? 206 : 200, headers);
673
+ });
534
674
  app.get('/api/v1/artifacts/:id', async (c) => {
535
- try {
536
- return c.body(new Uint8Array(await runtime.artifacts.get(c.req.param('id'))), 200, { 'Content-Type': 'application/octet-stream', 'X-Content-Type-Options': 'nosniff' });
537
- }
538
- catch {
539
- return c.json({ error: { code: 'NOT_FOUND', message: 'Artifact not found' } }, 404);
540
- }
675
+ const read = await runtime.artifacts.openRead(c.req.param('id'), {}, { verify: true }).catch(() => undefined);
676
+ if (!read)
677
+ return artifactAbsent(c);
678
+ return streamed(c, read.stream, 200, { 'Content-Type': 'application/octet-stream', 'Content-Length': String(read.size), 'X-Content-Type-Options': 'nosniff' });
541
679
  });
542
680
  // Plugin routes mount after the bearer-token middleware above.
543
681
  const ctx = pluginContext(runtime, env);