@hivemagnus/ardent 2.1.2 → 2.2.1

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.
package/README.md CHANGED
@@ -12,7 +12,8 @@ What you get:
12
12
  per-task event journal in SQLite. Interrupted work is marked `unknown`,
13
13
  never silently replayed.
14
14
  - **Management API** (Hono, bearer-token protected) for tasks, sessions,
15
- config, identity, skills, peers, channels, and live event streams. The
15
+ config, identity, skills, peers, channels, and live event streams, including
16
+ the reply text as the model writes it. The
16
17
  OpenAPI document is served at `/openapi.json` and pinned in
17
18
  [`openapi/ardent.json`](openapi/ardent.json).
18
19
  - **A2A protocol 1.0** server and client over JSON-RPC, HTTP+JSON, and gRPC,
@@ -68,6 +69,7 @@ ARDENT_LLAMA_MODEL=your-model-name
68
69
  EOF
69
70
  ardent chat # interactive session
70
71
  ardent run --prompt "Summarize RFC 9110 in three bullets"
72
+ ardent mission submit --mission-file mission.json # a team mission, see below
71
73
  ardent gateway run # management API, A2A, channels, jobs
72
74
  ```
73
75
 
@@ -127,6 +129,7 @@ only the *names* of the environment variables that hold them.
127
129
  | `a2a` | disabled | See [A2A](#a2a). |
128
130
  | `channels.telegram`, `channels.mattermost` | disabled | See [Chat channels](#chat-channels). |
129
131
  | `integrations.magnus_control` | disabled | See [Magnus Control tools](#magnus-control-tools). |
132
+ | `artifacts.max_bytes` | `2097152` (2 MiB) | Largest artifact a task may store, up to 64 MiB. See [Team missions](#team-missions). |
130
133
  | `plugins` | `[]` | See [Plugins](#plugins). |
131
134
  | `api` | `127.0.0.1:9910`, `ARDENT_API_TOKEN` | Management listener and the env var holding its bearer token. A non-loopback host is refused; put a TLS proxy in front instead. |
132
135
 
@@ -152,6 +155,15 @@ Direct conversations then get `hivemem_status`, `hivemem_search`,
152
155
  validated team mission may grant read access to one shared `project:<id>`
153
156
  scope.
154
157
 
158
+ To rotate the HiveMem credential without a restart, write the new token into the
159
+ profile environment file (`.env`, or the `--env-file` the gateway started with)
160
+ and call `POST /api/v1/memory/credential/reload` with no body or `{}`. The
161
+ gateway re-reads only the `token_env` variable, checks that it is a well-formed
162
+ JWT, and uses it for every later HiveMem request; requests in flight finish
163
+ with the previous token. It answers `{"reloaded": true, "token_env": "...",
164
+ "changed": true|false}`, `409` when memory is not `hivemem`, and `422` (the old
165
+ token stays in use) when the new value is missing or malformed.
166
+
155
167
  ### Chat channels
156
168
 
157
169
  ```yaml
@@ -258,6 +270,122 @@ Codex model and reasoning effort and configures context compaction for all
258
270
  profiles under that home. [`model-policy.default.json`](model-policy.default.json)
259
271
  is a starting point; compaction is disabled until you enable it.
260
272
 
273
+ ### Live task streams
274
+
275
+ `GET /api/v1/tasks/{id}/stream` is a server-sent event stream. It sends:
276
+
277
+ | Event | Data | Notes |
278
+ |---|---|---|
279
+ | `task.event` | A journal event | The event `id` is the journal sequence. Resume with `Last-Event-ID` or `?after=` |
280
+ | `task.text` | `{step, text}`: the visible reply text of the current model step | Sent on connect and when a new step starts showing text |
281
+ | `task.delta` | `{step, text}`: text to append | |
282
+ | `task.done` | The finished task | Its `result` is the authoritative answer |
283
+
284
+ The stream closes after 60 seconds; reconnect to continue.
285
+
286
+ Live text works the same for every backend and caller:
287
+ - It holds only what a user would see. Structured output, such as tool or research JSON, is never streamed.
288
+ - It is not journaled and has no event id. A reconnect receives a `task.text` snapshot instead of a replay.
289
+ - Codex sends its answer as one piece when the turn completes.
290
+
291
+ `ardent chat` uses the same rule to print replies as they arrive.
292
+
293
+ ### Team missions
294
+
295
+ `POST /api/v1/missions` runs a team mission locally, for a coordinator such as
296
+ a project studio. It is accepted like a task (`202 {task_id, state}`) and
297
+ streams on `/api/v1/tasks/{id}/stream` like any task.
298
+
299
+ ```json
300
+ {
301
+ "objective": "Draft the opening scene",
302
+ "mission": { "id": "scene-1", "revision": 1, "parent_task": null, "constraints": [],
303
+ "allowed_actions": ["observe", "analyze", "create_artifact"],
304
+ "resources": ["project:adventure", "tool:artifact_write", "tool:team_handoff"],
305
+ "deadline": 1893456000, "acceptance_criteria": ["The scene is saved"], "expected_artifacts": [] },
306
+ "context_items": [{ "title": "Brief", "mime": "text/markdown", "text": "..." }],
307
+ "labels": { "project": "adventure" },
308
+ "session_id": "<a session opened with context: mission>",
309
+ "idempotency_key": "scene-1-turn-1"
310
+ }
311
+ ```
312
+
313
+ - `mission` is the A2A team mission shape. The task runs in context `mission`,
314
+ and its tools follow the peer mission rule: `resources` grant tools, never
315
+ the model.
316
+ - The objective is at most 16,000 characters; `context_items` together at most
317
+ 64 KiB. Context items reach the model as tool data, so the context fitter can
318
+ shorten them; the full text stays in the task journal.
319
+ - Memory reads use the agent's private scope plus one `project:<id>` grant.
320
+ Missions never write memory.
321
+ - A session for a mission is opened with `POST /api/v1/sessions`
322
+ `{key, context: "mission"}`.
323
+ - The task result is a `TeamResult` JSON document. A prose reply becomes a
324
+ `partial` result with the reply as `summary`; a reply carrying a
325
+ `team_result` is checked against the mission and the observed artifacts.
326
+
327
+ Mission tools are granted with `tool:<name>` resources. The coordination
328
+ tools only record a journal event; Ardent never acts on them itself:
329
+
330
+ | Tool | Journal event | Notes |
331
+ |---|---|---|
332
+ | `team_handoff {to_role, objective, deliverables?, note?}` | `team_handoff` | Asks the coordinator to give work to another role |
333
+ | `team_ask_user {question, options?}` | `team_ask_user` | Ends the turn; the result is `input_required` with a clarification |
334
+ | `team_propose_decision {title, statement, rationale?}` | `team_propose_decision` | A proposal; only the user decides |
335
+ | `artifact_write {name, mime, text \| base64 \| workspace_path, revises_sha256?}` | `artifact_registered` | Markdown, text, JSON, CSV, SVG, PNG, JPEG, WebP, PDF or DOCX, up to `artifacts.max_bytes`. `workspace_path` reads a file inside the profile's `workspace` |
336
+ | `document_render {source_markdown, format: pdf \| docx, name}` | `artifact_registered` | Markdown (with ` ```svg ` figures) to PDF. DOCX is not available in this build |
337
+ | `development_note {kind, title, body, sources?}` | `development_note` | Also available in direct tasks; see below |
338
+
339
+ Every registered artifact has an immutable manifest (digest, size, media type,
340
+ revision, provenance and the artifact it supersedes). `revises_sha256` makes
341
+ a new artifact a revision of an earlier one. `GET /api/v1/tasks/{id}/artifacts`
342
+ lists a task's manifests and `GET /api/v1/artifacts/{sha256}/manifest` returns
343
+ the newest manifest for a digest; the bytes stay at `GET /api/v1/artifacts/{id}`.
344
+
345
+ `development_note` stores an append-only development record: the agent's own
346
+ note about how it works (`epistemic: agent_reported`).
347
+
348
+ ### Pause, preview and development history
349
+
350
+ **Pause and resume.** `POST /api/v1/tasks/{id}/pause` holds a queued or running
351
+ task: a queued task does not start (later tasks run instead), and a running
352
+ task stops at its next step boundary, before a model call, before a tool call
353
+ is journaled, or before it settles. The journal records `pause_requested`,
354
+ `paused` (with the boundary) and `resumed`. Both routes are idempotent, and the
355
+ deadline keeps running while a task is paused. `POST /api/v1/tasks/{id}/resume`
356
+ releases it. Locally, `ardent tasks pause <id>` holds a queued task and
357
+ `ardent tasks resume <id>` releases and runs it.
358
+
359
+ **Preview.** `POST /api/v1/preview/tasks` `{prompt, overrides: {soul?,
360
+ identity?, skills_enabled?, model?}, session_id?}` runs one task in context
361
+ `preview` with unsaved changes. A preview gets the read-only direct tools, no
362
+ mission tools and no memory tools. It never writes memory, development
363
+ records, identity or configuration, and any artifact it produces expires after
364
+ 24 hours. It streams like any task; a session for it is opened with
365
+ `context: "preview"`. `ardent preview --prompt TEXT [--soul-file FILE]
366
+ [--identity-file FILE] [--skills a,b | --no-skills] [--model NAME]` does the
367
+ same locally.
368
+
369
+ **Development history.** `GET /api/v1/development?after=&limit=&kind=` returns
370
+ the agent's development in one portable record shape, oldest first, with a
371
+ `next` cursor:
372
+
373
+ ```json
374
+ {"id": "dev_...", "agent_ref": "assistant", "kind": "self_understanding", "title": "...", "body": "...",
375
+ "author": "agent", "epistemic": "agent_reported", "before_sha256": null, "after_sha256": null,
376
+ "sources": [{"kind": "task", "ref": "..."}], "created_at": "2026-11-08T12:00:00.000Z"}
377
+ ```
378
+
379
+ It merges:
380
+ - the agent's `development_note` records (`agent_reported`);
381
+ - operator notes from `POST /api/v1/development` (`operator_reported`);
382
+ - skill selection changes, with the configuration revisions before and after (`observed`);
383
+ - soul and identity edits from the retained identity history (`observed`);
384
+ - research method reflections (`observed`).
385
+
386
+ `agent_ref` is the profile name. `ardent development list [--after CURSOR]
387
+ [--limit N] [--kind KIND]` prints the same pages.
388
+
261
389
  ## Plugins
262
390
 
263
391
  A plugin is an ES module whose default export (or named `plugin` export) is an
package/dist/api.d.ts CHANGED
@@ -3,4 +3,11 @@ import { type LoadedConfig } from './config.js';
3
3
  import type { ArdentRuntime } from './runtime.js';
4
4
  import type { JobEngine } from './job-engine.js';
5
5
  export declare function ardentOpenApi(): object;
6
- export declare function createArdentApi(runtime: ArdentRuntime, loaded: LoadedConfig, env?: NodeJS.ProcessEnv, jobEngine?: JobEngine): Hono;
6
+ /**
7
+ * `env` is the gateway's one shared environment: the runtime, tools, channels
8
+ * and plugins receive the same object. `envFile` is the explicit protected
9
+ * environment file the gateway started from, if any (default `<profile>/.env`).
10
+ */
11
+ export declare function createArdentApi(runtime: ArdentRuntime, loaded: LoadedConfig, env?: NodeJS.ProcessEnv, jobEngine?: JobEngine, options?: {
12
+ envFile?: string;
13
+ }): Hono;
package/dist/api.js CHANGED
@@ -17,19 +17,40 @@ import { TelegramAdapter } from './telegram.js';
17
17
  import { MattermostAdapter } from './mattermost.js';
18
18
  import { EventSchema, SessionMessageSchema, SessionSchema, TaskSchema, TaskState } from './store.js';
19
19
  import { pluginContext } from './plugins.js';
20
+ import { MissionSubmit } from './missions.js';
21
+ import { ArtifactRecordSchema } from './artifact-manifests.js';
22
+ import { PreviewSubmit } from './preview.js';
23
+ import { developmentPage, DevelopmentKind, DevelopmentNoteInput, DevelopmentRecordSchema, recordSkillChange } from './development.js';
24
+ import { readProfileEnv } from './profile-env.js';
20
25
  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();
21
- const SessionOpen = z.object({ key: z.string().trim().min(1).max(256), reset: z.boolean().optional() }).strict();
26
+ /** Contexts a management caller may open a session in. A session serves tasks of its own context only. */
27
+ const SessionContext = z.enum(['direct', 'mission', 'preview']);
28
+ const Admission = z.object({ task_id: z.string().guid(), state: TaskState, admission: z.enum(['open', 'paused']) });
29
+ const DevelopmentPost = DevelopmentNoteInput.extend({ author: z.enum(['operator', 'agent']).optional() }).strict();
30
+ const DevelopmentPage = z.object({ records: z.array(DevelopmentRecordSchema), next: z.string().nullable() });
31
+ const SessionOpen = z.object({ key: z.string().trim().min(1).max(256), reset: z.boolean().optional(), context: SessionContext.optional() }).strict();
32
+ const Accepted = z.object({ task_id: z.string().guid(), state: TaskState });
22
33
  const ConfigEdit = z.object({ text: z.string().min(1).max(200000), revision: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
23
34
  const SkillEdit = z.object({ enabled: z.boolean(), revision: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
24
35
  const IdentityEdit = z.object({ text: z.string().min(1).max(128 * 1024), revision: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
25
36
  const IdentityRestore = z.object({ history_name: z.string().min(1).max(128), revision: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
26
37
  const PageLimit = z.coerce.number().int().min(1).max(100);
38
+ /** A HiveMem agent credential is a JWT: three base64url segments. */
39
+ const HiveMemCredential = z.string().max(16384).regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/);
40
+ const CredentialReload = z.object({ reloaded: z.literal(true), token_env: z.string(), changed: z.boolean() });
27
41
  const EventCursor = z.coerce.number().int().min(0);
28
42
  function authEqual(actual, expected) {
29
43
  const a = Buffer.from(actual);
30
44
  const b = Buffer.from(expected);
31
45
  return a.length === b.length && timingSafeEqual(a, b);
32
46
  }
47
+ /** Like parseJson, but a validation failure always reads as an invalid request (HTTP 400). */
48
+ function parseInput(body, schema) {
49
+ const result = schema.safeParse(body);
50
+ if (!result.success)
51
+ throw new Error(`Invalid request: ${result.error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`).join('; ')}`);
52
+ return result.data;
53
+ }
33
54
  function parseJson(body, schema) {
34
55
  const result = schema.safeParse(body);
35
56
  if (!result.success)
@@ -46,7 +67,7 @@ const a2aBody = { required: true, content: { 'application/json': { schema: { typ
46
67
  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' } };
47
68
  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 };
48
69
  const eventExample = { sequence: 1, task_id: taskExample.id, kind: 'task_accepted', detail: { backend: 'llamacpp' }, created_ms: 1790431200000 };
49
- const sseExample = `event: task.event\nid: 1\ndata: ${JSON.stringify(eventExample)}\n\n`;
70
+ 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`;
50
71
  export function ardentOpenApi() {
51
72
  return {
52
73
  openapi: '3.1.0', info: { title: 'Magnus Ardent API', version: ARDENT_VERSION },
@@ -71,12 +92,20 @@ export function ardentOpenApi() {
71
92
  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' } } },
72
93
  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] } } } } } }
73
94
  },
74
- '/api/v1/sessions': { get: { operationId: 'listSessions', security: [{ bearerAuth: [] }], 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) } } },
95
+ '/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' } } } },
96
+ '/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' } } } },
97
+ '/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' } } },
98
+ 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' } } } },
99
+ '/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) } } },
75
100
  '/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' } } } },
76
101
  '/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' } } } },
77
102
  '/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] } } } } } } },
78
- '/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; task.done carries Task JSON', content: { 'text/event-stream': { schema: { type: 'string' }, example: sseExample } } }, '404': { description: 'Task absent' } } } },
103
+ '/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' } } } },
79
104
  '/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' } } } },
105
+ '/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' } } } },
106
+ '/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' } } } },
107
+ '/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' } } } },
108
+ '/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' } } } },
80
109
  '/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' } } } },
81
110
  '/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() })) } } },
82
111
  '/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' } } } },
@@ -99,11 +128,17 @@ export function ardentOpenApi() {
99
128
  '/api/v1/skills': { get: { operationId: 'listSkills', security: [{ bearerAuth: [] }], responses: { '200': { description: 'Profile skill index' } } } },
100
129
  '/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' } } } },
101
130
  '/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' } } } },
102
- '/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() })) } } }
131
+ '/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() })) } } },
132
+ '/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' } } } }
103
133
  }
104
134
  };
105
135
  }
106
- export function createArdentApi(runtime, loaded, env = process.env, jobEngine) {
136
+ /**
137
+ * `env` is the gateway's one shared environment: the runtime, tools, channels
138
+ * and plugins receive the same object. `envFile` is the explicit protected
139
+ * environment file the gateway started from, if any (default `<profile>/.env`).
140
+ */
141
+ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, options = {}) {
107
142
  const app = new Hono();
108
143
  let current = loaded;
109
144
  // A saved configuration requires activation; it must not rotate the live
@@ -284,6 +319,7 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine) {
284
319
  const edit = parseJson(await c.req.json(), SkillEdit);
285
320
  const revision = await setSkillEnabled(runtime.profileDir, c.req.param('name'), edit.enabled, edit.revision);
286
321
  current = await loadConfig(runtime.profileDir);
322
+ recordSkillChange(runtime.development, c.req.param('name'), edit.enabled, edit.revision, revision);
287
323
  return c.json({ revision, activation_required: true });
288
324
  });
289
325
  app.post('/api/v1/memory/search', async (c) => {
@@ -311,10 +347,54 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine) {
311
347
  reason: error instanceof Error ? error.message.slice(0, 200) : 'HiveMem unavailable' });
312
348
  }
313
349
  });
314
- app.get('/api/v1/sessions', c => c.json({ sessions: runtime.store.listSessions('management', 'direct') }));
350
+ // The fleet manager rotates the HiveMem agent credential in the profile
351
+ // environment file. A reload replaces only that key in the shared gateway
352
+ // environment, so every HiveMem client created afterwards uses it.
353
+ let credentialReloads = Promise.resolve();
354
+ const reloadCredential = async (name) => {
355
+ let value;
356
+ try {
357
+ value = (await readProfileEnv(runtime.profileDir, options.envFile))[name];
358
+ }
359
+ catch {
360
+ return { problem: 'Profile environment file is unreadable or not an owned private file' };
361
+ }
362
+ if (!value)
363
+ return { problem: `${name} is missing or empty in the profile environment file` };
364
+ if (!HiveMemCredential.safeParse(value).success)
365
+ return { problem: `${name} is not a well-formed agent credential` };
366
+ const changed = env[name] !== value;
367
+ env[name] = value;
368
+ return { changed };
369
+ };
370
+ app.post('/api/v1/memory/credential/reload', async (c) => {
371
+ const text = await c.req.text();
372
+ if (text.trim()) {
373
+ let body;
374
+ try {
375
+ body = JSON.parse(text);
376
+ }
377
+ catch {
378
+ throw new Error('Invalid request: body must be empty or an empty JSON object');
379
+ }
380
+ parseInput(body, z.object({}).strict());
381
+ }
382
+ const memory = runtime.config.memory;
383
+ if (memory.provider !== 'hivemem')
384
+ return c.json({ error: { code: 'CONFLICT', message: 'Memory provider is not hivemem' } }, 409);
385
+ // Serialize reloads so the last request to start decides the credential.
386
+ const outcome = credentialReloads.then(() => reloadCredential(memory.token_env));
387
+ credentialReloads = outcome.catch(() => { });
388
+ const result = await outcome;
389
+ if ('problem' in result)
390
+ return c.json({ error: { code: 'INVALID_CREDENTIAL', message: result.problem } }, 422);
391
+ return c.json({ reloaded: true, token_env: memory.token_env, changed: result.changed });
392
+ });
393
+ app.get('/api/v1/sessions', c => c.json({ sessions: runtime.store.listSessions('management', SessionContext.parse(c.req.query('context') ?? 'direct')) }));
315
394
  app.post('/api/v1/sessions', async (c) => {
316
395
  const input = parseJson(await c.req.json(), SessionOpen);
317
- return c.json(input.reset ? runtime.store.resetSession('management', 'direct', input.key) : runtime.store.session('management', 'direct', input.key));
396
+ const context = input.context ?? 'direct';
397
+ return c.json(input.reset ? runtime.store.resetSession('management', context, input.key) : runtime.store.session('management', context, input.key));
318
398
  });
319
399
  app.get('/api/v1/sessions/:id/messages', c => c.json({ messages: runtime.store.sessionMessages(c.req.param('id'), 'management') }));
320
400
  app.post('/api/v1/tasks', async (c) => {
@@ -324,6 +404,21 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine) {
324
404
  void runtime.run(task.id, env).catch(() => { });
325
405
  return c.json({ task_id: task.id, state: task.state }, 202);
326
406
  });
407
+ app.post('/api/v1/missions', async (c) => {
408
+ const input = parseInput(await c.req.json(), MissionSubmit);
409
+ let task;
410
+ try {
411
+ task = runtime.acceptMission(input, 'management');
412
+ }
413
+ catch (error) {
414
+ if (error instanceof Error && /Session caller or context mismatch/.test(error.message))
415
+ throw new Error('Invalid session: open it with context mission');
416
+ throw error;
417
+ }
418
+ if (task.state === 'queued')
419
+ void runtime.run(task.id, env).catch(() => { });
420
+ return c.json({ task_id: task.id, state: task.state }, 202);
421
+ });
327
422
  app.get('/api/v1/tasks', c => c.json({ tasks: runtime.store.list(PageLimit.parse(c.req.query('limit') ?? 50)) }));
328
423
  app.get('/api/v1/tasks/:id', c => {
329
424
  const task = runtime.store.get(c.req.param('id'));
@@ -343,23 +438,98 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine) {
343
438
  return c.json({ error: { code: 'NOT_FOUND', message: 'Task not found' } }, 404);
344
439
  let after = EventCursor.parse(c.req.query('after') ?? c.req.header('Last-Event-ID') ?? 0);
345
440
  return streamSSE(c, async (stream) => {
346
- const until = Date.now() + 60_000;
347
- while (!stream.aborted && Date.now() < until) {
348
- const events = runtime.store.events(id, after, 100);
349
- for (const event of events) {
350
- await stream.writeSSE({ event: 'task.event', id: String(event.sequence), data: JSON.stringify(event) });
351
- after = event.sequence;
352
- }
353
- const task = runtime.store.get(id);
354
- if (!task || ['completed', 'partial', 'failed', 'cancelled', 'unknown'].includes(task.state)) {
355
- await stream.writeSSE({ event: 'task.done', data: JSON.stringify(task ?? { id, state: 'missing' }) });
356
- break;
441
+ // Live reply text is not journaled, so its events carry no id and a reconnect
442
+ // starts from a task.text snapshot of the current step instead of a replay.
443
+ const live = [];
444
+ let wake;
445
+ const unsubscribe = runtime.liveText.subscribe(id, update => { live.push(update); wake?.(); });
446
+ const snapshot = runtime.liveText.snapshot(id);
447
+ if (snapshot)
448
+ live.push({ kind: 'text', ...snapshot });
449
+ try {
450
+ const until = Date.now() + 60_000;
451
+ while (!stream.aborted && Date.now() < until) {
452
+ for (const update of live.splice(0)) {
453
+ if (update.kind !== 'end')
454
+ await stream.writeSSE({ event: update.kind === 'text' ? 'task.text' : 'task.delta', data: JSON.stringify({ step: update.step, text: update.text }) });
455
+ }
456
+ const events = runtime.store.events(id, after, 100);
457
+ for (const event of events) {
458
+ await stream.writeSSE({ event: 'task.event', id: String(event.sequence), data: JSON.stringify(event) });
459
+ after = event.sequence;
460
+ }
461
+ const task = runtime.store.get(id);
462
+ if (!task || ['completed', 'partial', 'failed', 'cancelled', 'unknown'].includes(task.state)) {
463
+ await stream.writeSSE({ event: 'task.done', data: JSON.stringify(task ?? { id, state: 'missing' }) });
464
+ break;
465
+ }
466
+ if (events.length < 100 && !live.length) {
467
+ await new Promise(resolve => {
468
+ const timer = setTimeout(resolve, 250);
469
+ wake = () => { clearTimeout(timer); resolve(); };
470
+ });
471
+ wake = undefined;
472
+ }
357
473
  }
358
- await stream.sleep(250);
474
+ }
475
+ finally {
476
+ unsubscribe();
359
477
  }
360
478
  });
361
479
  });
362
480
  app.post('/api/v1/tasks/:id/cancel', c => c.json(runtime.cancel(c.req.param('id'))));
481
+ for (const action of ['pause', 'resume'])
482
+ app.post(`/api/v1/tasks/:id/${action}`, c => {
483
+ const id = c.req.param('id');
484
+ if (!runtime.store.get(id))
485
+ return c.json({ error: { code: 'NOT_FOUND', message: 'Task not found' } }, 404);
486
+ try {
487
+ const { task, admission } = action === 'pause' ? runtime.pause(id) : runtime.resume(id);
488
+ return c.json({ task_id: task.id, state: task.state, admission });
489
+ }
490
+ catch (error) {
491
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'TASK_TERMINAL')
492
+ return c.json({ error: { code: 'CONFLICT', message: error instanceof Error ? error.message : 'Task already finished' } }, 409);
493
+ throw error;
494
+ }
495
+ });
496
+ app.post('/api/v1/preview/tasks', async (c) => {
497
+ const input = parseInput(await c.req.json(), PreviewSubmit);
498
+ let task;
499
+ try {
500
+ task = runtime.acceptPreview(input, 'management');
501
+ }
502
+ catch (error) {
503
+ if (error instanceof Error && /Session caller or context mismatch/.test(error.message))
504
+ throw new Error('Invalid session: open it with context preview');
505
+ throw error;
506
+ }
507
+ if (task.state === 'queued')
508
+ void runtime.run(task.id, env).catch(() => { });
509
+ return c.json({ task_id: task.id, state: task.state }, 202);
510
+ });
511
+ app.get('/api/v1/development', async (c) => {
512
+ const limit = c.req.query('limit');
513
+ const kind = c.req.query('kind');
514
+ const query = parseInput({ after: c.req.query('after'), limit: limit === undefined ? undefined : Number(limit), kind }, z.object({ after: z.string().max(400).optional(), limit: z.number().int().min(1).max(200).optional(), kind: DevelopmentKind.optional() }));
515
+ return c.json(await developmentPage({ records: runtime.development, profileDir: runtime.profileDir, config: runtime.config }, query));
516
+ });
517
+ app.post('/api/v1/development', async (c) => {
518
+ const { author, ...note } = parseInput(await c.req.json(), DevelopmentPost);
519
+ return c.json(runtime.development.add({ ...note, author: author ?? 'operator', epistemic: author === 'agent' ? 'agent_reported' : 'operator_reported' }), 201);
520
+ });
521
+ app.get('/api/v1/tasks/:id/artifacts', c => {
522
+ const id = c.req.param('id');
523
+ if (!runtime.store.get(id))
524
+ return c.json({ error: { code: 'NOT_FOUND', message: 'Task not found' } }, 404);
525
+ return c.json({ artifacts: runtime.artifactManifests.forTask(id) });
526
+ });
527
+ app.get('/api/v1/artifacts/:sha256/manifest', c => {
528
+ const record = runtime.artifactManifests.manifest(c.req.param('sha256'));
529
+ if (!record)
530
+ return c.json({ error: { code: 'NOT_FOUND', message: 'Artifact manifest not found' } }, 404);
531
+ return c.json(record);
532
+ });
363
533
  app.get('/api/v1/artifacts/:id', async (c) => {
364
534
  try {
365
535
  return c.body(new Uint8Array(await runtime.artifacts.get(c.req.param('id'))), 200, { 'Content-Type': 'application/octet-stream', 'X-Content-Type-Options': 'nosniff' });