@hivemagnus/ardent 3.0.0 → 3.1.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/dist/runtime.js CHANGED
@@ -14,12 +14,13 @@ import { TaskStore } from './store.js';
14
14
  import { ToolRegistry } from './tools.js';
15
15
  import { MAGNUS_OWNER_READ_TOOLS, MAGNUS_NODE_OWNER_READ_TOOLS } from './magnus-owner-reads.js';
16
16
  import { z } from 'zod';
17
- import { TeamEnvelope, TeamResult } from './team-contract.js';
17
+ import { TeamResult } from './team-contract.js';
18
18
  import { fitModelMessages } from './context.js';
19
19
  import { ContextCheckpoints, tokenEstimate } from './context-checkpoints.js';
20
20
  import { loadModelPolicy } from './model-policy.js';
21
21
  import { BackendEventSchema } from './backend-events.js';
22
- import { pluginContext } from './plugins.js';
22
+ import { pluginContext, pluginTaskTools, pluginTeamEnvelope } from './plugins.js';
23
+ import { pluginInputImages } from './plugin-inputs.js';
23
24
  import { LiveTextHub } from './live-text.js';
24
25
  import { ArtifactManifests } from './artifact-manifests.js';
25
26
  import { DevelopmentRecords } from './development.js';
@@ -86,6 +87,14 @@ export class ArdentRuntime {
86
87
  get draining() { return this.#draining; }
87
88
  #skillsPromise;
88
89
  #plugins = [];
90
+ #pluginsInstalled = false;
91
+ #gatewayPrepared = false;
92
+ #pluginsStarted = false;
93
+ #taskContexts = new Map();
94
+ #pluginEnvironment = {};
95
+ #closing = false;
96
+ #closed = false;
97
+ #pluginsDrained = true;
89
98
  get plugins() { return this.#plugins; }
90
99
  constructor(profileDir, config, env = process.env) {
91
100
  this.profileDir = profileDir;
@@ -102,20 +111,71 @@ export class ArdentRuntime {
102
111
  }
103
112
  /** Install plugins once, before the runtime accepts work. Plugin tools join the shared registry. */
104
113
  async usePlugins(plugins, env = process.env) {
105
- if (this.#plugins.length)
114
+ if (this.#pluginsInstalled)
106
115
  throw new Error('Plugins are already installed');
116
+ this.#pluginsInstalled = true;
117
+ this.#pluginEnvironment = env;
107
118
  const ctx = pluginContext(this, env);
108
- for (const plugin of plugins)
119
+ for (const plugin of plugins) {
120
+ // Include a partially initialized plugin in cleanup, without retrying its setup.
121
+ this.#plugins = [...this.#plugins, plugin];
122
+ if (plugin.drain)
123
+ this.#pluginsDrained = false;
109
124
  await plugin.registerTools?.(ctx);
110
- this.#plugins = [...plugins];
125
+ }
126
+ }
127
+ async prepareGateway(env = this.#pluginEnvironment) {
128
+ if (!this.#pluginsInstalled || this.#gatewayPrepared || this.#draining)
129
+ throw new Error('Gateway preparation is unavailable');
130
+ for (const plugin of this.#plugins)
131
+ await plugin.prepareGateway?.(pluginContext(this, env));
132
+ this.#gatewayPrepared = true;
133
+ }
134
+ async startPlugins(env = this.#pluginEnvironment) {
135
+ if (!this.#gatewayPrepared || this.#pluginsStarted || this.#draining)
136
+ throw new Error('Plugin consumers are unavailable');
137
+ this.#pluginsStarted = true;
138
+ for (const plugin of this.#plugins)
139
+ await plugin.start?.(pluginContext(this, env));
111
140
  }
112
141
  close() {
142
+ if (this.#closed)
143
+ return;
144
+ if (this.#closing)
145
+ throw new Error('Plugin cleanup remains unsettled');
146
+ if (!this.#pluginsDrained)
147
+ throw new Error('Drain private services before closing their shared journal');
113
148
  if (this.#jobs.size)
114
149
  throw new Error('Cannot close Ardent state while tasks are active');
150
+ this.#closing = true;
151
+ const ctx = pluginContext(this, this.#pluginEnvironment);
152
+ for (const plugin of [...this.#plugins].reverse()) {
153
+ const result = plugin.close?.(ctx);
154
+ if (result && typeof result.then === 'function')
155
+ throw new Error('Plugin close must be synchronous; await owned work in drain');
156
+ }
115
157
  this.store.close();
158
+ this.#closed = true;
116
159
  }
117
160
  async drain(timeoutMs = 30_000) {
118
161
  this.#draining = true;
162
+ const deadline = Date.now() + timeoutMs;
163
+ const ctx = pluginContext(this, this.#pluginEnvironment);
164
+ for (const plugin of [...this.#plugins].reverse()) {
165
+ if (!plugin.drain)
166
+ continue;
167
+ const remaining = Math.max(0, deadline - Date.now());
168
+ let timer;
169
+ try {
170
+ const quiet = await Promise.race([plugin.drain(ctx, remaining), new Promise(resolve => { timer = setTimeout(() => resolve(false), remaining); })]);
171
+ if (!quiet)
172
+ return false;
173
+ }
174
+ finally {
175
+ if (timer)
176
+ clearTimeout(timer);
177
+ }
178
+ }
119
179
  const settle = async (milliseconds) => {
120
180
  if (!this.#jobs.size)
121
181
  return true;
@@ -138,13 +198,17 @@ export class ArdentRuntime {
138
198
  this.#jobs.delete(id);
139
199
  pending.reject(new Error('Gateway stopped while the task was paused'));
140
200
  }
141
- if (await settle(timeoutMs))
201
+ if (await settle(Math.max(0, deadline - Date.now()))) {
202
+ this.#pluginsDrained = true;
142
203
  return true;
204
+ }
143
205
  for (const id of [...this.#waiting.keys()])
144
206
  this.cancel(id);
145
207
  for (const controller of this.#active.values())
146
208
  controller.abort('gateway shutdown deadline');
147
- return settle(5_000);
209
+ const settled = await settle(5_000);
210
+ this.#pluginsDrained = settled;
211
+ return settled;
148
212
  }
149
213
  accept(prompt, caller = 'local', context = 'direct', idempotencyKey, sessionId, originalDeadlineMs, backendOverride) {
150
214
  if (this.#draining)
@@ -326,10 +390,56 @@ export class ArdentRuntime {
326
390
  this.#skillsPromise ??= registerSkillTool(this.tools, this.profileDir, this.config);
327
391
  const preview = task.context === 'preview' ? previewOverrides(this.store, task.id) : undefined;
328
392
  const skills = (await this.#skillsPromise).map(item => preview?.skills_enabled ? { ...item, enabled: preview.skills_enabled.includes(item.name) } : item);
329
- const taskTools = preview ? await this.#previewTools(preview) : this.#toolsForTask(task, env);
393
+ const baseTools = preview ? await this.#previewTools(preview) : this.#toolsForTask(task, env);
394
+ const selectedMission = task.context === 'mission' ? missionRecord(this.store, task.id) : undefined;
395
+ if (task.context === 'mission' && !selectedMission)
396
+ throw new Error('Mission task has no recorded mission');
397
+ const taskEnvelope = selectedMission ? missionEnvelope(task, selectedMission.mission)
398
+ : task.context === 'peer' ? this.#peerEnvelope(task) : undefined;
399
+ const taskContext = { ...pluginContext(this, env), task,
400
+ baseTools: baseTools.list(task.context), ...(taskEnvelope ? { envelope: taskEnvelope } : {}) };
401
+ this.#taskContexts.set(task.id, taskContext);
402
+ const taskTools = pluginTaskTools(this.#plugins, taskContext);
403
+ const observe = (name, result, evidence) => {
404
+ this.#recordEvidence(name, result, evidence);
405
+ for (const plugin of this.#plugins)
406
+ plugin.observeToolResult?.(taskContext, name, result, evidence);
407
+ };
408
+ const executors = this.#plugins.flatMap(plugin => {
409
+ const executor = plugin.taskExecutor?.(taskContext);
410
+ return executor === undefined ? [] : [{ plugin: plugin.name, executor }];
411
+ });
412
+ if (executors.length > 1)
413
+ throw new Error('Multiple plugins claimed task execution');
414
+ const selected = executors[0];
415
+ if (selected) {
416
+ if (task.context === 'preview' || task.context === 'mission')
417
+ throw new Error('Extensions cannot replace preview or mission execution');
418
+ const { executor, plugin } = selected;
419
+ if (!/^[a-z][a-z0-9_-]{0,63}$/.test(executor.id) || !['none', 'possible'].includes(executor.effect) || typeof executor.run !== 'function')
420
+ throw new Error('Invalid plugin task executor');
421
+ await this.#awaitTeamAdmission(task.id, abort.signal);
422
+ if (abort.signal.aborted)
423
+ throw new Error('Task cancelled before extension execution');
424
+ this.store.append(task.id, 'extension_execution_attempt', { plugin, id: executor.id, effect: executor.effect });
425
+ const result = z.object({ answer: z.string().trim().min(1).max(262_144), effect_status: z.enum(['none', 'confirmed', 'unknown']) }).strict().parse(await executor.run(abort.signal));
426
+ if (executor.effect === 'none' && result.effect_status !== 'none')
427
+ throw new Error('Read-only extension returned an external effect receipt');
428
+ this.store.append(task.id, 'extension_execution_result', { plugin, id: executor.id, effect_status: result.effect_status });
429
+ if (result.effect_status === 'unknown')
430
+ throw new Error('Extension effect outcome is unknown');
431
+ onText?.(result.answer, 0);
432
+ return await this.#finish(task, result.answer, { sourceIds: new Set(), sources: new Map(), artifactIds: new Set(), researchAttempted: false }, abort.signal);
433
+ }
330
434
  this.store.append(task.id, 'skills_selected', { skills: skills.filter(item => item.enabled).map(item => ({ name: item.name, hash: item.hash })) });
331
- const memory = await this.#memoryContext(task, env);
435
+ const memory = await this.#memoryContext(task, env, taskContext);
332
436
  let system = await this.#systemPrompt(task, memory.text, skills, taskTools, preview);
437
+ for (const plugin of this.#plugins)
438
+ if (plugin.systemPrompt) {
439
+ system = await plugin.systemPrompt(taskContext, { prompt: system, memory: memory.text, skills, tools: taskTools });
440
+ if (typeof system !== 'string' || !system.trim() || Buffer.byteLength(system) > 1_048_576)
441
+ throw new Error(`Plugin ${plugin.name} returned an invalid system prompt`);
442
+ }
333
443
  const modelPolicy = await loadModelPolicy(this.profileDir, env);
334
444
  const policyLlama = modelPolicy?.policy.primary.llamacpp.mode === 'policy'
335
445
  ? { ...this.config.providers.llamacpp, model: modelPolicy.policy.primary.llamacpp.model }
@@ -366,6 +476,7 @@ export class ArdentRuntime {
366
476
  if (normalized.kind !== 'text_delta')
367
477
  this.store.append(task.id, 'backend_event', normalized);
368
478
  };
479
+ const inputImages = await pluginInputImages(this.#plugins, taskContext);
369
480
  if (task.backend === 'codex') {
370
481
  this.store.append(task.id, 'model_started', { backend: 'codex' });
371
482
  const policyCodex = modelPolicy ? { ...this.config.providers.codex, model: modelPolicy.policy.primary.codex.model } : this.config.providers.codex;
@@ -379,8 +490,8 @@ export class ArdentRuntime {
379
490
  if (!current || ['completed', 'partial', 'failed', 'cancelled', 'unknown'].includes(current.state))
380
491
  return;
381
492
  this.store.append(task.id, 'tool_result', { name, result: toolResult });
382
- this.#recordEvidence(name, toolResult, evidence);
383
- }, () => this.#awaitTeamAdmission(task.id, abort.signal), onBackendEvent, modelPolicy?.policy.primary.codex.reasoning_effort, [], {
493
+ observe(name, toolResult, evidence);
494
+ }, () => this.#awaitTeamAdmission(task.id, abort.signal), onBackendEvent, modelPolicy?.policy.primary.codex.reasoning_effort, inputImages, {
384
495
  // Same journal shape as the llama.cpp loop: an attempt makes cancellation effect-uncertain.
385
496
  onToolAttempt: attempt => this.store.append(task.id, 'tool_attempt', { id: attempt.callId, name: attempt.tool, args: compactToolArguments(attempt.tool, attempt.arguments) })
386
497
  });
@@ -464,7 +575,7 @@ export class ArdentRuntime {
464
575
  const compacted = compactToolArguments(call.function.name, args, result);
465
576
  if (compacted !== args)
466
577
  call.function.arguments = JSON.stringify(compacted);
467
- this.#recordEvidence(call.function.name, result, evidence);
578
+ observe(call.function.name, result, evidence);
468
579
  messages.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(result) });
469
580
  if (call.function.name === 'team_ask_user' && result.ok)
470
581
  question = z.object({ question: z.string() }).safeParse(args).data?.question;
@@ -480,7 +591,8 @@ export class ArdentRuntime {
480
591
  // A cancelled model request has no application side effect. Once a tool
481
592
  // invocation begins, its external outcome may be uncertain on abort.
482
593
  const effectMayBeUncertain = Boolean(this.store.db.prepare("SELECT 1 FROM events WHERE task_id=? AND kind='tool_attempt' LIMIT 1").get(task.id));
483
- const state = abort.signal.aborted
594
+ const extensionEffect = Boolean(this.store.db.prepare("SELECT 1 FROM events WHERE task_id=? AND kind='extension_execution_attempt' AND json_extract(detail_json,'$.effect')='possible' LIMIT 1").get(task.id));
595
+ const state = extensionEffect ? 'unknown' : abort.signal.aborted
484
596
  ? abort.signal.reason === 'cancelled' && !effectMayBeUncertain ? 'cancelled' : 'unknown'
485
597
  : 'failed';
486
598
  this.store.setState(task.id, state, null, message);
@@ -489,6 +601,17 @@ export class ArdentRuntime {
489
601
  finally {
490
602
  clearTimeout(timer);
491
603
  this.#active.delete(task.id);
604
+ const ctx = this.#taskContexts.get(task.id);
605
+ this.#taskContexts.delete(task.id);
606
+ if (ctx)
607
+ for (const plugin of [...this.#plugins].reverse()) {
608
+ try {
609
+ plugin.taskSettled?.(ctx);
610
+ }
611
+ catch {
612
+ this.store.append(task.id, 'plugin_cleanup_failed', { plugin: plugin.name });
613
+ }
614
+ }
492
615
  }
493
616
  }
494
617
  #missionToolDeps(task) {
@@ -531,10 +654,18 @@ export class ArdentRuntime {
531
654
  }
532
655
  if (task.context !== 'peer')
533
656
  return this.tools;
534
- const row = this.store.db.prepare("SELECT detail_json FROM events WHERE task_id=? AND kind='team_envelope' ORDER BY sequence DESC LIMIT 1").get(task.id);
535
- const envelope = row ? TeamEnvelope.parse(JSON.parse(z.object({ detail_json: z.string() }).parse(row).detail_json)) : undefined;
657
+ const envelope = this.#peerEnvelope(task);
536
658
  return envelope ? this.#missionScopedTools(task, env, envelope) : this.#standardPeerTools(task);
537
659
  }
660
+ decodeTeamEnvelope(value) { return pluginTeamEnvelope(this.#plugins, value); }
661
+ assertTeamEnvelopeAdmission(envelope, wire, env) {
662
+ for (const plugin of this.#plugins)
663
+ plugin.admitTeamEnvelope?.(pluginContext(this, env), envelope, wire);
664
+ }
665
+ #peerEnvelope(task) {
666
+ const row = this.store.db.prepare("SELECT detail_json FROM events WHERE task_id=? AND kind='team_envelope' ORDER BY sequence DESC LIMIT 1").get(task.id);
667
+ return row ? this.decodeTeamEnvelope(JSON.parse(z.object({ detail_json: z.string() }).parse(row).detail_json)) : undefined;
668
+ }
538
669
  #standardPeerTools(task) {
539
670
  // Standard A2A callers get the documented bounded public-news scope.
540
671
  // A model cannot promote their request to a team mission or to operator tools.
@@ -739,6 +870,10 @@ export class ArdentRuntime {
739
870
  }
740
871
  this.store.append(task.id, 'evidence_register', { source_ids: [...evidence.sourceIds], artifact_ids: [report.id, markdown.id, ...evidence.artifactIds] });
741
872
  }
873
+ const ctx = this.#taskContexts.get(task.id);
874
+ if (ctx)
875
+ for (const plugin of this.#plugins)
876
+ await plugin.beforeFinish?.(ctx, { answer, ...(brief ? { brief } : {}), partial: partialResearchFallback, evidence });
742
877
  await this.#awaitTeamAdmission(task.id, signal);
743
878
  if (signal.aborted)
744
879
  throw new Error('Task cancelled or deadline elapsed before completion');
@@ -780,7 +915,7 @@ export class ArdentRuntime {
780
915
  throw new Error('Task disappeared');
781
916
  return { task: finished, answer, ...(brief ? { brief } : {}) };
782
917
  }
783
- async #memoryContext(task, env) {
918
+ async #memoryContext(task, env, ctx) {
784
919
  if (task.context === 'scheduled') {
785
920
  this.store.append(task.id, 'memory_context', { status: 'ok', scope: 'none', count: 0 });
786
921
  return { text: '' };
@@ -791,14 +926,14 @@ export class ArdentRuntime {
791
926
  }
792
927
  let projectId;
793
928
  if (task.context === 'mission')
794
- return this.#missionMemory(task, env);
929
+ return this.#missionMemory(task, env, ctx);
795
930
  if (task.context === 'peer') {
796
931
  // Peers never read private memory. A validated team mission may grant
797
932
  // read access to exactly one shared project scope.
798
933
  const row = this.store.db.prepare("SELECT detail_json FROM events WHERE task_id=? AND kind='team_envelope' ORDER BY sequence DESC LIMIT 1").get(task.id);
799
934
  if (row) {
800
935
  const encoded = z.object({ detail_json: z.string() }).parse(row).detail_json;
801
- const envelope = TeamEnvelope.parse(JSON.parse(encoded));
936
+ const envelope = this.decodeTeamEnvelope(JSON.parse(encoded));
802
937
  const grants = envelope.mission.resources.flatMap(value => /^project:([a-z][a-z0-9._-]{0,63})$/.exec(value)?.[1] ?? []);
803
938
  if ((envelope.mission.allowed_actions.includes('observe') || envelope.mission.allowed_actions.includes('analyze'))
804
939
  && grants.length === 1)
@@ -809,10 +944,14 @@ export class ArdentRuntime {
809
944
  return { text: '' };
810
945
  }
811
946
  }
947
+ const scope = task.context === 'peer' ? 'shared' : 'private';
948
+ if (this.#plugins.some(plugin => plugin.allowMemory?.(ctx, scope, projectId) === false)) {
949
+ this.store.append(task.id, 'memory_context', { status: 'ok', scope: 'none', count: 0, reason: 'Plugin policy denied memory read' });
950
+ return { text: '' };
951
+ }
812
952
  try {
813
953
  const client = new HiveMemClient(this.config.memory, env);
814
954
  await client.capabilities();
815
- const scope = task.context === 'peer' ? 'shared' : 'private';
816
955
  const memories = await client.search(task.prompt, scope, 5, undefined, projectId);
817
956
  this.store.append(task.id, 'memory_context', { status: 'ok', scope, count: memories.length, ...(projectId ? { project_id: projectId } : {}) });
818
957
  return { client, text: memories.map(item => `[memory:${item.id}] ${item.content.slice(0, 1200)}`).join('\n') };
@@ -823,15 +962,15 @@ export class ArdentRuntime {
823
962
  }
824
963
  }
825
964
  /** A mission reads private memory plus, with exactly one `project:<id>` grant, that shared project scope. It never writes memory. */
826
- async #missionMemory(task, env) {
965
+ async #missionMemory(task, env, ctx) {
827
966
  const mission = missionRecord(this.store, task.id)?.mission;
828
967
  const grants = mission?.resources.flatMap(value => /^project:([a-z][a-z0-9._-]{0,63})$/.exec(value)?.[1] ?? []) ?? [];
829
968
  const projectId = grants.length === 1 && (mission?.allowed_actions.includes('observe') || mission?.allowed_actions.includes('analyze')) ? grants[0] : undefined;
830
969
  try {
831
970
  const client = new HiveMemClient(this.config.memory, env);
832
971
  await client.capabilities();
833
- const own = await client.search(task.prompt, 'private', 5);
834
- const shared = projectId ? await client.search(task.prompt, 'shared', 5, undefined, projectId) : [];
972
+ const own = this.#plugins.every(plugin => plugin.allowMemory?.(ctx, 'private') !== false) ? await client.search(task.prompt, 'private', 5) : [];
973
+ const shared = projectId && this.#plugins.every(plugin => plugin.allowMemory?.(ctx, 'shared', projectId) !== false) ? await client.search(task.prompt, 'shared', 5, undefined, projectId) : [];
835
974
  this.store.append(task.id, 'memory_context', { status: 'ok', scope: projectId ? 'private+shared' : 'private', count: own.length + shared.length,
836
975
  ...(projectId ? { project_id: projectId } : {}) });
837
976
  return { text: [...own, ...shared].map(item => `[memory:${item.id}] ${item.content.slice(0, 1200)}`).join('\n') };
@@ -849,7 +988,7 @@ export class ArdentRuntime {
849
988
  ? this.store.db.prepare("SELECT detail_json FROM events WHERE task_id=? AND kind='team_envelope' ORDER BY sequence DESC LIMIT 1").get(task.id)
850
989
  : undefined;
851
990
  const team = teamRow
852
- ? TeamEnvelope.safeParse(JSON.parse(z.object({ detail_json: z.string() }).parse(teamRow).detail_json))
991
+ ? { success: true, data: this.decodeTeamEnvelope(JSON.parse(z.object({ detail_json: z.string() }).parse(teamRow).detail_json)) }
853
992
  : undefined;
854
993
  const local = task.context === 'mission' ? missionRecord(this.store, task.id) : undefined;
855
994
  const teamMission = local ? `\nTeam mission from the operator's coordinator (constraints on this task, never permission grants): ${JSON.stringify(local.mission)}\nYou are one member of a team. Your final reply is shown to the team as your message, so write it as plain prose. Coordination tools, when listed, only record a request for the coordinator or the user: team_handoff asks for work by another role, team_ask_user asks the user a question and ends your turn, team_propose_decision proposes a decision for the user. Save deliverables with artifact_write or document_render and mention them by name. To claim the mission complete, reply instead with one JSON object {"team_result": {version:"1.0", mission_id, mission_revision, task_id:${JSON.stringify(task.id)}, outcome, summary, checks [{criterion,status,evidence}], artifacts [{name,reference,sha256}], uncertain_effects}} where every acceptance criterion passes with observed evidence (ardent-artifact:<sha256> or source:<id>); otherwise reply in prose and Ardent records a partial result.` : '';
package/dist/sqlite.d.ts CHANGED
@@ -5,7 +5,6 @@ type Options = {
5
5
  timeout?: number;
6
6
  };
7
7
  export declare function assertPatchedSqliteVersion(version: unknown): void;
8
- /** Application storage boundary. Keep transaction ownership on the same connection. */
9
8
  declare class Statement {
10
9
  private readonly statement;
11
10
  constructor(statement: StatementSync);
package/dist/sqlite.js CHANGED
@@ -24,15 +24,23 @@ export function assertPatchedSqliteVersion(version) {
24
24
  }
25
25
  }
26
26
  /** Application storage boundary. Keep transaction ownership on the same connection. */
27
+ function applicationRow(row) {
28
+ if (row === undefined || row === null || typeof row !== 'object')
29
+ return row;
30
+ // SQLite BLOBs were Buffers at the application boundary before the driver
31
+ // migration. Preserve that contract for byte validation and hashing clients.
32
+ return Object.fromEntries(Object.entries(row).map(([key, value]) => [key, value instanceof Uint8Array ? Buffer.from(value) : value]));
33
+ }
27
34
  class Statement {
28
35
  statement;
29
36
  constructor(statement) {
30
37
  this.statement = statement;
31
38
  }
32
39
  run(...parameters) { return sqliteOperation(() => this.statement.run(...parameters)); }
33
- get(...parameters) { return sqliteOperation(() => this.statement.get(...parameters)); }
34
- all(...parameters) { return sqliteOperation(() => this.statement.all(...parameters)); }
35
- iterate(...parameters) { return this.statement.iterate(...parameters); }
40
+ get(...parameters) { return applicationRow(sqliteOperation(() => this.statement.get(...parameters))); }
41
+ all(...parameters) { return sqliteOperation(() => this.statement.all(...parameters)).map(applicationRow); }
42
+ *iterate(...parameters) { for (const row of this.statement.iterate(...parameters))
43
+ yield applicationRow(row); }
36
44
  }
37
45
  export class Database {
38
46
  #database;
package/dist/store.d.ts CHANGED
@@ -90,6 +90,8 @@ export declare const EventSchema: z.ZodObject<{
90
90
  created_ms: z.ZodNumber;
91
91
  }, z.core.$strip>;
92
92
  export type TaskEvent = z.infer<typeof EventSchema>;
93
+ /** Historical transport labels remain distinct; adapters must retain their original identity. */
94
+ export type InboundChannelType = 'unknown' | 'telegram_private' | 'telegram_group' | 'telegram_supergroup' | 'mattermost_dm' | 'mattermost_channel' | 'chattermost_dm' | 'chattermost_channel';
93
95
  export declare class TaskStore {
94
96
  readonly db: Database;
95
97
  constructor(path: string);
@@ -132,7 +134,7 @@ export declare class TaskStore {
132
134
  finishWithAssistant(id: string, state: 'completed' | 'partial', content: string, sessionContent?: string): void;
133
135
  latestSessionTask(sessionId: string, caller: string): Task | undefined;
134
136
  hasInbound(platform: string, account: string, updateId: string): boolean;
135
- claimInbound(platform: string, account: string, updateId: string, channelType?: 'unknown' | 'telegram_private' | 'telegram_group' | 'telegram_supergroup' | 'mattermost_dm' | 'mattermost_channel'): {
137
+ claimInbound(platform: string, account: string, updateId: string, channelType?: InboundChannelType): {
136
138
  claimed: boolean;
137
139
  taskId: string | null;
138
140
  };
package/dist/store.js CHANGED
@@ -34,7 +34,7 @@ export class TaskStore {
34
34
  task_id TEXT REFERENCES tasks(id), created_ms INTEGER NOT NULL,
35
35
  channel_type TEXT NOT NULL DEFAULT 'unknown' CHECK(channel_type IN
36
36
  ('unknown','telegram_private','telegram_group','telegram_supergroup',
37
- 'mattermost_dm','mattermost_channel')),
37
+ 'mattermost_dm','mattermost_channel','chattermost_dm','chattermost_channel')),
38
38
  PRIMARY KEY(platform, account, update_id));
39
39
  CREATE TABLE IF NOT EXISTS channel_cursors (
40
40
  key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_ms INTEGER NOT NULL);
@@ -87,7 +87,7 @@ export class TaskStore {
87
87
  this.db.exec(`ALTER TABLE channel_inbound ADD COLUMN
88
88
  channel_type TEXT NOT NULL DEFAULT 'unknown' CHECK(channel_type IN
89
89
  ('unknown','telegram_private','telegram_group','telegram_supergroup',
90
- 'mattermost_dm','mattermost_channel'))`);
90
+ 'mattermost_dm','mattermost_channel','chattermost_dm','chattermost_channel'))`);
91
91
  this.db.exec(`CREATE TRIGGER IF NOT EXISTS channel_inbound_type_immutable
92
92
  BEFORE UPDATE OF channel_type ON channel_inbound
93
93
  WHEN OLD.channel_type != NEW.channel_type
@@ -228,10 +228,10 @@ export class TaskStore {
228
228
  claimInbound(platform, account, updateId, channelType = 'unknown') {
229
229
  if (!platform || !account || !updateId || updateId.length > 256)
230
230
  throw new Error('Invalid channel update identity');
231
- if ((platform === 'telegram' && channelType.startsWith('mattermost_')) ||
232
- (platform === 'mattermost' && channelType.startsWith('telegram_')) ||
231
+ if ((platform === 'telegram' && (channelType.startsWith('mattermost_') || channelType.startsWith('chattermost_'))) ||
232
+ (['mattermost', 'chattermost'].includes(platform) && channelType.startsWith('telegram_')) ||
233
233
  !['unknown', 'telegram_private', 'telegram_group', 'telegram_supergroup',
234
- 'mattermost_dm', 'mattermost_channel'].includes(channelType))
234
+ 'mattermost_dm', 'mattermost_channel', 'chattermost_dm', 'chattermost_channel'].includes(channelType))
235
235
  throw new Error('Inbound channel type differs from platform');
236
236
  return this.db.transaction(() => {
237
237
  if (this.admissionFence())
@@ -2,7 +2,7 @@ import { createHash, randomBytes } from 'node:crypto';
2
2
  import { z } from 'zod';
3
3
  import { TaskState } from '@a2a-js/sdk';
4
4
  import { ArdentA2AClient } from './a2a-client.js';
5
- import { TeamEnvelope } from './team-contract.js';
5
+ import { collectPluginTeamEvidence } from './plugin-evidence.js';
6
6
  const digest = z.string().regex(/^[a-f0-9]{64}$/);
7
7
  const identifier = z.string().regex(/^[a-f0-9]{32}$/);
8
8
  const safeName = z.string().regex(/^[A-Za-z0-9._-]{1,128}$/);
@@ -62,16 +62,16 @@ export class TeamArtifacts {
62
62
  if (operation?.state !== 'completed' || operation.context !== 'peer' ||
63
63
  operation.caller !== `a2a:${bound.tenant}:${bound.caller}`)
64
64
  return [];
65
- const envelope = TeamEnvelope.parse(JSON.parse(bound.envelope_json));
66
- if (!envelope.mission.allowed_actions.includes('create_artifact'))
67
- return [];
65
+ const envelope = this.runtime.decodeTeamEnvelope(JSON.parse(bound.envelope_json));
66
+ const extensions = await collectPluginTeamEvidence(this.runtime, operation, envelope, this.env);
68
67
  const events = this.runtime.store.events(bound.operation_id, 0, 500);
69
68
  const event = events.find(item => item.kind === 'research_artifacts');
70
69
  const actual = z.object({ report: z.object({ id: digest }), markdown: z.object({ id: digest }) }).safeParse(event?.detail);
71
- const entries = actual.success ? [
70
+ const entries = envelope.mission.allowed_actions.includes('create_artifact') && actual.success ? [
72
71
  { name: 'research-brief.json', mime: 'application/json', digest: actual.data.report.id, producer: 'ardent-research', sourceId: '' },
73
72
  { name: 'research-brief.md', mime: 'text/markdown', digest: actual.data.markdown.id, producer: 'ardent-research', sourceId: '' }
74
73
  ] : [];
74
+ entries.push(...extensions.artifacts.map(item => ({ name: item.name, mime: item.mime, digest: item.sha256, producer: item.producer, sourceId: item.source })));
75
75
  const result = [];
76
76
  for (const entry of entries) {
77
77
  const bytes = await this.runtime.artifacts.get(entry.digest);
@@ -2,13 +2,23 @@ import { z } from 'zod';
2
2
  export declare const TEAM_VERSION = "1.0";
3
3
  export declare const TEAM_TASK_METADATA_KEY = "hermesTeamTask";
4
4
  export declare const TEAM_CLARIFICATION_METADATA_KEY = "hermesTeamClarification";
5
+ export declare const CoreTeamAction: z.ZodEnum<{
6
+ observe: "observe";
7
+ analyze: "analyze";
8
+ create_artifact: "create_artifact";
9
+ create_draft: "create_draft";
10
+ reversible_change: "reversible_change";
11
+ deploy: "deploy";
12
+ external_publish: "external_publish";
13
+ destructive_response: "destructive_response";
14
+ }>;
5
15
  /** The mission shape without its cross-field rules (Zod 4 cannot omit fields from a refined object). */
6
16
  export declare const TeamMissionShape: z.ZodObject<{
7
17
  id: z.ZodString;
8
18
  revision: z.ZodNumber;
9
19
  parent_task: z.ZodNullable<z.ZodString>;
10
20
  constraints: z.ZodArray<z.ZodString>;
11
- allowed_actions: z.ZodArray<z.ZodEnum<{
21
+ allowed_actions: z.ZodArray<z.ZodUnion<readonly [z.ZodEnum<{
12
22
  observe: "observe";
13
23
  analyze: "analyze";
14
24
  create_artifact: "create_artifact";
@@ -17,18 +27,19 @@ export declare const TeamMissionShape: z.ZodObject<{
17
27
  deploy: "deploy";
18
28
  external_publish: "external_publish";
19
29
  destructive_response: "destructive_response";
20
- }>>;
30
+ }>, z.ZodString]>>;
21
31
  resources: z.ZodArray<z.ZodString>;
22
32
  deadline: z.ZodNumber;
23
33
  acceptance_criteria: z.ZodArray<z.ZodString>;
24
34
  expected_artifacts: z.ZodArray<z.ZodString>;
35
+ extensions: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodJSONSchema>>;
25
36
  }, z.core.$strict>;
26
37
  export declare const TeamMission: z.ZodObject<{
27
38
  id: z.ZodString;
28
39
  revision: z.ZodNumber;
29
40
  parent_task: z.ZodNullable<z.ZodString>;
30
41
  constraints: z.ZodArray<z.ZodString>;
31
- allowed_actions: z.ZodArray<z.ZodEnum<{
42
+ allowed_actions: z.ZodArray<z.ZodUnion<readonly [z.ZodEnum<{
32
43
  observe: "observe";
33
44
  analyze: "analyze";
34
45
  create_artifact: "create_artifact";
@@ -37,11 +48,12 @@ export declare const TeamMission: z.ZodObject<{
37
48
  deploy: "deploy";
38
49
  external_publish: "external_publish";
39
50
  destructive_response: "destructive_response";
40
- }>>;
51
+ }>, z.ZodString]>>;
41
52
  resources: z.ZodArray<z.ZodString>;
42
53
  deadline: z.ZodNumber;
43
54
  acceptance_criteria: z.ZodArray<z.ZodString>;
44
55
  expected_artifacts: z.ZodArray<z.ZodString>;
56
+ extensions: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodJSONSchema>>;
45
57
  }, z.core.$strict>;
46
58
  export type TeamMission = z.infer<typeof TeamMission>;
47
59
  export declare const TeamEnvelope: z.ZodObject<{
@@ -54,7 +66,7 @@ export declare const TeamEnvelope: z.ZodObject<{
54
66
  revision: z.ZodNumber;
55
67
  parent_task: z.ZodNullable<z.ZodString>;
56
68
  constraints: z.ZodArray<z.ZodString>;
57
- allowed_actions: z.ZodArray<z.ZodEnum<{
69
+ allowed_actions: z.ZodArray<z.ZodUnion<readonly [z.ZodEnum<{
58
70
  observe: "observe";
59
71
  analyze: "analyze";
60
72
  create_artifact: "create_artifact";
@@ -63,11 +75,12 @@ export declare const TeamEnvelope: z.ZodObject<{
63
75
  deploy: "deploy";
64
76
  external_publish: "external_publish";
65
77
  destructive_response: "destructive_response";
66
- }>>;
78
+ }>, z.ZodString]>>;
67
79
  resources: z.ZodArray<z.ZodString>;
68
80
  deadline: z.ZodNumber;
69
81
  acceptance_criteria: z.ZodArray<z.ZodString>;
70
82
  expected_artifacts: z.ZodArray<z.ZodString>;
83
+ extensions: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodJSONSchema>>;
71
84
  }, z.core.$strict>;
72
85
  }, z.core.$strict>;
73
86
  export type TeamEnvelope = z.infer<typeof TeamEnvelope>;
@@ -112,5 +125,5 @@ export declare const TeamResult: z.ZodObject<{
112
125
  }, z.core.$strict>>;
113
126
  }, z.core.$strict>;
114
127
  export type TeamResult = z.infer<typeof TeamResult>;
115
- export declare function validateTeamEnvelope(value: unknown, authenticatedPeer: string, messageId: string, objective: string, nowSeconds?: number, child?: boolean): TeamEnvelope;
128
+ export declare function validateTeamEnvelope(value: unknown, authenticatedPeer: string, messageId: string, objective: string, nowSeconds?: number, child?: boolean, decode?: (value: unknown) => TeamEnvelope): TeamEnvelope;
116
129
  export declare function validateTeamResult(raw: string, envelope: TeamEnvelope, knownReferences?: ReadonlySet<string>): TeamResult;
@@ -7,7 +7,11 @@ const role = z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/);
7
7
  const boundedId = z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/);
8
8
  const text = (bytes) => z.string().trim().min(1).refine(value => Buffer.byteLength(value, 'utf8') <= bytes, `Exceeds ${bytes} bytes`);
9
9
  const texts = (minimum = 0) => z.array(text(1000)).min(minimum).max(32).refine(value => new Set(value).size === value.length, 'Duplicate entries');
10
- const Action = z.enum(['observe', 'analyze', 'create_artifact', 'create_draft', 'reversible_change', 'deploy', 'external_publish', 'destructive_response']);
10
+ export const CoreTeamAction = z.enum(['observe', 'analyze', 'create_artifact', 'create_draft', 'reversible_change', 'deploy', 'external_publish', 'destructive_response']);
11
+ const Action = z.union([
12
+ CoreTeamAction,
13
+ z.string().regex(/^extension:[a-z][a-z0-9-]{0,63}:[a-z][a-z0-9_]{0,63}$/)
14
+ ]);
11
15
  /** The mission shape without its cross-field rules (Zod 4 cannot omit fields from a refined object). */
12
16
  export const TeamMissionShape = z.object({
13
17
  id: boundedId,
@@ -18,7 +22,9 @@ export const TeamMissionShape = z.object({
18
22
  resources: texts(1),
19
23
  deadline: z.number().int().min(1).max(253402300799),
20
24
  acceptance_criteria: texts(1),
21
- expected_artifacts: texts()
25
+ expected_artifacts: texts(),
26
+ /** Validated only by the explicitly configured extension that owns the key. */
27
+ extensions: z.record(z.string().regex(/^[a-z][a-z0-9-]{0,63}$/), z.json()).optional()
22
28
  }).strict();
23
29
  export const TeamMission = TeamMissionShape;
24
30
  export const TeamEnvelope = z.object({ version: z.literal(TEAM_VERSION), caller: role, task_id: boundedId, objective: text(16000), mission: TeamMission }).strict();
@@ -31,15 +37,15 @@ export const TeamResult = z.object({
31
37
  summary: text(16000), checks: z.array(Check).max(32), artifacts: z.array(Artifact).max(32), uncertain_effects: texts(),
32
38
  clarification: Clarification.optional()
33
39
  }).strict();
34
- export function validateTeamEnvelope(value, authenticatedPeer, messageId, objective, nowSeconds = Date.now() / 1000, child = false) {
35
- const envelope = TeamEnvelope.parse(value);
40
+ export function validateTeamEnvelope(value, authenticatedPeer, messageId, objective, nowSeconds = Date.now() / 1000, child = false, decode = value => TeamEnvelope.parse(value)) {
41
+ const envelope = TeamEnvelope.parse(decode(value));
36
42
  if (envelope.caller !== authenticatedPeer || envelope.task_id !== messageId || envelope.objective !== objective)
37
43
  throw new Error('Team envelope does not match authenticated message');
38
44
  if (child ? envelope.mission.parent_task === null : envelope.mission.parent_task !== null)
39
45
  throw new Error('Child mission requires an exact retained root reservation');
40
46
  if (envelope.mission.deadline <= nowSeconds)
41
47
  throw new Error('Team mission deadline expired');
42
- if (Buffer.byteLength(JSON.stringify(envelope), 'utf8') > 48_000)
48
+ if (Buffer.byteLength(JSON.stringify(value), 'utf8') > 48_000 || Buffer.byteLength(JSON.stringify(envelope), 'utf8') > 48_000)
43
49
  throw new Error('Team envelope exceeds 48 KiB');
44
50
  return envelope;
45
51
  }
@@ -1,6 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { z } from 'zod';
3
- import { TeamEnvelope } from './team-contract.js';
4
3
  const id = z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/);
5
4
  const EventsPayload = z.object({ native_task_id: id, after_cursor: z.number().int().min(0), limit: z.number().int().min(1).max(100) }).strict();
6
5
  const ControlPayload = z.object({ native_task_id: id, task_id: id, mission_revision: z.number().int().min(1), control_id: id, control_version: z.number().int().min(1), action: z.enum(['pause', 'resume', 'cancel']) }).strict();
@@ -54,7 +53,7 @@ export class TeamControlService {
54
53
  if (bound.tenant !== tenant || bound.caller !== caller)
55
54
  throw new Error('Team task owner differs');
56
55
  const raw = JSON.parse(bound.envelope_json);
57
- return { envelope: TeamEnvelope.parse(raw), operationId: bound.operation_id };
56
+ return { envelope: this.runtime.decodeTeamEnvelope(raw), operationId: bound.operation_id };
58
57
  }
59
58
  #events(payload, tenant, caller) {
60
59
  const { envelope } = this.#mission(payload.native_task_id, tenant, caller);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hivemagnus/ardent",
3
- "version": "3.0.0",
3
+ "version": "3.1.1",
4
4
  "description": "Headless TypeScript agent runtime with A2A, scheduled jobs, skills, chat channels, and a plugin API",
5
5
  "keywords": [
6
6
  "agent",
@@ -29,6 +29,10 @@
29
29
  "ardent": "dist/cli.js"
30
30
  },
31
31
  "exports": {
32
+ "./plugin-sdk": {
33
+ "types": "./dist/plugin-sdk.d.ts",
34
+ "default": "./dist/plugin-sdk.js"
35
+ },
32
36
  ".": {
33
37
  "types": "./dist/index.d.ts",
34
38
  "default": "./dist/index.js"