@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/README.md CHANGED
@@ -443,6 +443,10 @@ export default definePlugin({
443
443
  jobHandlers: ctx => ({ /* 'weather.daily': JobHandler */ }),
444
444
  jobOwnership: ctx => async (job, now) => { /* throw to refuse a job window */ },
445
445
  peerTool: (tool, task, envelope) => false, // allow a peer to call one of your tools
446
+ taskTools: ctx => [], // additions bound to the exact persisted task
447
+ filterTool: (ctx, tool) => true, // restrictive final filter
448
+ drain: async (ctx, timeoutMs) => true, // stop intake and await owned work
449
+ close: ctx => {}, // synchronous cleanup after a successful drain
446
450
  });
447
451
  ```
448
452
 
@@ -461,6 +465,73 @@ peer still needs an explicit mission grant (`tool:<name>`) or `peerTool`.
461
465
  Plugin routes sit behind the same bearer-token check as the rest of the
462
466
  management API.
463
467
 
468
+ A module may also export an asynchronous factory receiving `{ config, profileDir,
469
+ env }`. It returns a plugin or an array of plugins. This allows profile-specific
470
+ configuration and offline validation without constructing a runtime, claiming jobs,
471
+ or starting channel consumers. The CLI supplies the selected profile environment;
472
+ embedders can pass it as the third argument of `loadPlugins`.
473
+
474
+ Import supported extension primitives from `@hivemagnus/ardent/plugin-sdk` rather
475
+ than reaching into `dist`. This entry point includes the runtime, tool and job
476
+ contracts, profile/configuration helpers, provider clients, artifact and identity
477
+ helpers, and the application SQLite boundary (`SqliteDatabase`). Task additions retain their declared contexts and peer/mission grants. Preview
478
+ additions must be read-only. Restrictive filters apply to built-in and extension
479
+ tools; duplicate names cannot replace a tool silently. Stateful plugins must stop
480
+ intake and await their owned work in `drain`. A false or timed-out drain keeps the
481
+ journal open and ownership unsettled; `close` cannot bypass it. Cleanup runs in
482
+ reverse registration order, including partially initialized plugins.
483
+
484
+ Additional hooks support extensions that retain an existing workflow contract:
485
+
486
+ | Hook | Boundary |
487
+ | --- | --- |
488
+ | `systemPrompt` | Supplies trusted policy text; the full model input is still budgeted. |
489
+ | `allowMemory` | Can deny an admitted read; cannot grant a different scope. |
490
+ | `observeToolResult`, `beforeFinish`, `taskSettled` | Track actual task evidence, validate before success, and release task-local resources. |
491
+ | `teamEnvelope`, `admitTeamEnvelope` | Validate a legacy wire shape and apply extra admission restrictions. Identity, deadlines, parent reservations, constraints and resources remain core-validated. |
492
+ | `taskExecutor` | Runs one owned deterministic workflow. Attempts precede invocation in the journal; lost or unknown effects stay held across restart. Preview and mission execution cannot be replaced. |
493
+ | `inputImages` | Supplies at most five owned, digest-verified PNG/JPEG artifacts to a direct Codex task. Paths outside the selected profile's artifacts are rejected. |
494
+ | `teamEvidence` | Validates retained extension receipts. Artifacts require an exact mission grant and verified bytes; format-only citation aliases must target observed references. |
495
+ | `teamCard` | Describes private role capabilities without granting permissions or claiming backend readiness. |
496
+ | `prepareGateway`, `start` | Verify prior consumer ownership, then start background intake only in gateway mode. CLI inspection does not start consumers. |
497
+ | `channelAdapter` | Replaces one enabled built-in channel consumer. Multiple owners are refused. Intake and delivery receive separate abort signals. |
498
+ | `httpRoutes` | Adds explicit compatibility paths; overlapping core routes and authentication-boundary changes are refused. |
499
+
500
+ An envelope extension uses `mission.extensions[plugin.name]` and action names
501
+ `extension:<plugin-name>:<action>`. No extension is accepted without its configured
502
+ validator. A codec may retain an old wire action while translating it into its
503
+ own namespace; it cannot add a resource or substitute a core action grant.
504
+ Ardent retains the original wire envelope in its journal and revalidates it
505
+ when reading lifecycle controls or export receipts.
506
+
507
+ Normal plugin `routes` remain under `/api/v1/plugins/<name>/` and require the
508
+ management bearer token. `httpRoutes` declares each mount as `management` or
509
+ `independent`. Management aliases must remain under `/api/v1/` and inherit its
510
+ authentication. Independent device/webhook ingress must authenticate every
511
+ handler with its own credential and replay protection; it cannot use API,
512
+ health or A2A paths. All compatibility handlers receive a 1 MiB body bound and
513
+ share a bounded per-plugin rate bucket (600/minute, burst 120), applied before
514
+ handler authentication and parsing. Wildcard routes and middleware mounts are
515
+ refused so an extension cannot intercept unrelated core requests.
516
+
517
+ Offline job-validation contexts expose `runtimeAvailable: false`; their runtime
518
+ and tool registry getters throw. CLI extensions receive `rawArgs` for their own
519
+ option grammar, declare `valueOptions` to recognize values before the command, and can use `matches(invocation)` to select one subcommand while
520
+ leaving other core subcommands available. Plugin code has the profile owner's
521
+ process privileges: install only reviewed, pinned artifacts. These hooks preserve
522
+ authority boundaries between tasks; they do not sandbox an untrusted plugin.
523
+
524
+ Job owner labels other than `ardent` remain external references and never admit
525
+ work. A custom delivery kind requires its registered handler to validate the exact
526
+ descriptor. Existing definition bytes, revisions and receipts need not be rewritten
527
+ to rename an external scheduler. Historical channel labels also remain distinct;
528
+ a compatibility adapter must retain its original platform, account and receipt
529
+ identity instead of creating a second consumer under a renamed transport.
530
+
531
+ Extensions should
532
+ use `ctx.runtime.store` for the active journal and must not introduce a second
533
+ SQLite driver or rewrite another extension's state.
534
+
464
535
  ## Security model
465
536
 
466
537
  - The model never gets a shell, deployment, or credential tool from Ardent
@@ -508,3 +579,10 @@ Hermes team plugin or require a sibling Magnus checkout. The compatibility probe
508
579
  explicitly enables `hermes_compat` and allows its combined functional workload
509
580
  through the fixture's rate buckets. Default throttling remains covered by the
510
581
  separate rate-limit tests.
582
+
583
+ HTTP mounts may set `rateLimit: { perMinute, burst }` for their authentication
584
+ boundary. Defaults are 600 requests per minute and a burst of 120. Limits must be
585
+ positive integers no greater than 6000 and 1200 respectively. All mounts from one
586
+ plugin in the same boundary must agree; management and independent ingress retain
587
+ separate buckets. This capacity is trusted plugin policy and grants no authentication
588
+ or task authority. The one MiB body limit remains in force.
@@ -41,7 +41,7 @@ export async function createA2ASurface(runtime, config, env = process.env) {
41
41
  if (!['http:', 'https:'].includes(publicUrl.protocol) || publicUrl.username || publicUrl.password)
42
42
  throw new Error('Invalid A2A public URL');
43
43
  const { authenticate, peers } = await loadPeers(runtime.profileDir, config, env);
44
- const teamCard = config.a2a.hermes_compat ? await hermesTeamCard(runtime, config) : undefined;
44
+ const teamCard = config.a2a.hermes_compat ? await hermesTeamCard(runtime, config, env) : undefined;
45
45
  const grpcPort = Number(publicUrl.port || (publicUrl.protocol === 'https:' ? 443 : 80)) + 1;
46
46
  if (grpcPort > 65535)
47
47
  throw new Error('A2A gRPC port is unavailable');
package/dist/a2a.js CHANGED
@@ -1,8 +1,9 @@
1
+ import { collectPluginTeamEvidence } from './plugin-evidence.js';
1
2
  import { createHash, randomUUID } from 'node:crypto';
2
3
  import { Role, TaskState } from '@a2a-js/sdk';
3
4
  import { AgentEvent } from '@a2a-js/sdk/server';
4
5
  import { z } from 'zod';
5
- import { TEAM_TASK_METADATA_KEY, TEAM_CLARIFICATION_METADATA_KEY, TeamEnvelope as TeamEnvelopeSchema, TeamResult as TeamResultSchema, validateTeamEnvelope, validateTeamResult } from './team-contract.js';
6
+ import { TEAM_TASK_METADATA_KEY, TEAM_CLARIFICATION_METADATA_KEY, TeamResult as TeamResultSchema, validateTeamEnvelope, validateTeamResult } from './team-contract.js';
6
7
  import { TeamControlService } from './team-control.js';
7
8
  import { TeamChildService } from './team-child.js';
8
9
  import { TeamArtifacts } from './team-artifacts.js';
@@ -137,6 +138,7 @@ export class ArdentA2AExecutor {
137
138
  const rawEnvelope = metadata[TEAM_TASK_METADATA_KEY];
138
139
  let envelope;
139
140
  let childReference;
141
+ let wireEnvelope = rawEnvelope;
140
142
  try {
141
143
  const tenant = request.context.tenant ?? '';
142
144
  const existing = this.runtime.store.db.prepare('SELECT tenant,caller,envelope_json FROM a2a_team_missions WHERE a2a_task_id=?').get(taskId);
@@ -149,19 +151,21 @@ export class ArdentA2AExecutor {
149
151
  throw new Error('Cancelled team task cannot continue');
150
152
  }
151
153
  if (rawEnvelope !== undefined) {
152
- envelope = validateTeamEnvelope(rawEnvelope, caller.userName, request.userMessage.messageId, prompt, Date.now() / 1000, 'hermesTeamChild' in metadata);
154
+ envelope = validateTeamEnvelope(rawEnvelope, caller.userName, request.userMessage.messageId, prompt, Date.now() / 1000, 'hermesTeamChild' in metadata, value => this.runtime.decodeTeamEnvelope(value));
155
+ this.runtime.assertTeamEnvelopeAdmission(envelope, rawEnvelope, this.env);
153
156
  if ('hermesTeamChild' in metadata)
154
157
  childReference = await this.#children.claim(metadata.hermesTeamChild, envelope, taskId, contextId, caller.userName, JSON.stringify(request.userMessage));
155
- if (stored && stored.envelope_json !== JSON.stringify(envelope))
158
+ if (stored && stored.envelope_json !== JSON.stringify(rawEnvelope))
156
159
  throw new Error('Team mission changed during continuation');
157
160
  if (!stored)
158
- this.runtime.store.db.prepare('INSERT INTO a2a_team_missions(a2a_task_id,tenant,caller,envelope_json) VALUES (?,?,?,?)').run(taskId, tenant, caller.userName, JSON.stringify(envelope));
161
+ this.runtime.store.db.prepare('INSERT INTO a2a_team_missions(a2a_task_id,tenant,caller,envelope_json) VALUES (?,?,?,?)').run(taskId, tenant, caller.userName, JSON.stringify(rawEnvelope));
159
162
  }
160
163
  else if (stored) {
161
164
  if (request.task?.status?.state !== TaskState.TASK_STATE_INPUT_REQUIRED)
162
165
  throw new Error('Team continuation requires an input-required task');
163
166
  const parsed = JSON.parse(stored.envelope_json);
164
- envelope = TeamEnvelopeSchema.parse(parsed);
167
+ wireEnvelope = parsed;
168
+ envelope = this.runtime.decodeTeamEnvelope(parsed);
165
169
  }
166
170
  }
167
171
  catch {
@@ -180,7 +184,7 @@ export class ArdentA2AExecutor {
180
184
  const existedBefore = Boolean(request.userMessage.messageId && this.runtime.store.db.prepare("SELECT 1 FROM tasks WHERE caller=? AND context='peer' AND idempotency_key=?").get(owner, request.userMessage.messageId));
181
185
  const operation = this.runtime.accept(prompt, owner, 'peer', request.userMessage.messageId, session.id, deadline ? deadline * 1000 : undefined);
182
186
  if (envelope && operation.state === 'queued')
183
- this.runtime.store.append(operation.id, 'team_envelope', envelope);
187
+ this.runtime.store.append(operation.id, 'team_envelope', wireEnvelope);
184
188
  try {
185
189
  this.runtime.store.db.transaction(() => {
186
190
  this.runtime.store.db.prepare(`INSERT INTO a2a_operation_map(a2a_task_id,operation_id,tenant,caller) VALUES (?,?,?,?)
@@ -309,7 +313,9 @@ export class ArdentA2AExecutor {
309
313
  { name: 'research-brief.md', reference: `ardent-artifact:${detail.data.markdown.id}`, sha256: detail.data.markdown.id }
310
314
  ];
311
315
  });
312
- const knownReferences = new Set(artifacts.map(item => item.reference));
316
+ const extensions = await collectPluginTeamEvidence(this.runtime, result.task, envelope, this.env);
317
+ artifacts.push(...extensions.artifacts.map(({ name, reference, sha256 }) => ({ name, reference, sha256 })));
318
+ const knownReferences = new Set([...artifacts.map(item => item.reference), ...extensions.references]);
313
319
  for (const event of events.filter(item => item.kind === 'evidence_register')) {
314
320
  const register = z.object({ source_ids: z.array(z.string()), artifact_ids: z.array(z.string()) }).safeParse(event.detail);
315
321
  if (!register.success)
@@ -350,7 +356,7 @@ export class ArdentA2AExecutor {
350
356
  const reason = error instanceof Error ? error.message : 'Invalid team result';
351
357
  this.runtime.store.append(operationId, 'team_result_rejected', { reason: reason.slice(0, 1000) });
352
358
  if (envelope.mission.allowed_actions.every(action => action === 'observe' || action === 'analyze')) {
353
- const repaired = await this.#repairTeamResult(submitted, reason, envelope, result, operationId, artifacts, knownReferences, observedOwnerSources);
359
+ const repaired = await this.#repairTeamResult(submitted, reason, envelope, result, operationId, artifacts, knownReferences, observedOwnerSources, extensions.aliases);
354
360
  if (repaired)
355
361
  return repaired;
356
362
  }
@@ -366,7 +372,7 @@ export class ArdentA2AExecutor {
366
372
  }
367
373
  #validateSubmittedTeamResult(submitted, artifacts, envelope, knownReferences) {
368
374
  const parsed = TeamResultSchema.parse(submitted);
369
- if (!envelope.mission.allowed_actions.includes('create_artifact') && parsed.artifacts.length)
375
+ if (!envelope.mission.allowed_actions.includes('create_artifact') && parsed.artifacts.some(item => !artifacts.some(actual => actual.name === item.name && actual.sha256 === item.sha256 && actual.reference === item.reference)))
370
376
  throw new Error('Team result declares an artifact without create_artifact authority');
371
377
  for (const item of parsed.artifacts)
372
378
  if (!knownReferences.has(item.reference) || item.reference !== `ardent-artifact:${item.sha256}`)
@@ -374,7 +380,7 @@ export class ArdentA2AExecutor {
374
380
  return validateTeamResult(JSON.stringify({ ...parsed,
375
381
  artifacts: [...artifacts, ...parsed.artifacts.filter(item => !artifacts.some(real => real.name === item.name))] }), envelope, knownReferences);
376
382
  }
377
- async #repairTeamResult(submitted, reason, envelope, result, operationId, artifacts, knownReferences, observedOwnerSources) {
383
+ async #repairTeamResult(submitted, reason, envelope, result, operationId, artifacts, knownReferences, observedOwnerSources, citationAliases) {
378
384
  const shape = z.object({ version: z.unknown().optional(), mission_id: z.string(), mission_revision: z.number(), task_id: z.string(),
379
385
  outcome: z.string(), summary: z.string(), checks: z.array(z.object({ criterion: z.string(), status: z.string(),
380
386
  evidence: z.union([z.array(z.string()), z.string()]) }).strict()), artifacts: z.array(z.unknown()), uncertain_effects: z.array(z.string()) }).strict();
@@ -397,7 +403,9 @@ export class ArdentA2AExecutor {
397
403
  const originalEvidence = original.data.checks[0]?.evidence;
398
404
  const executionCitation = singleReadCheck && Array.isArray(originalEvidence) && originalEvidence.length === 1
399
405
  && /^source:exec-[A-Za-z0-9._:-]{1,128}$/.test(originalEvidence[0] ?? '') ? originalEvidence[0] : undefined;
400
- const citationCorrection = executionCitation && soleOwnerSource ? { from: executionCitation, to: soleOwnerSource } : undefined;
406
+ const alias = singleReadCheck && Array.isArray(originalEvidence) && originalEvidence.length === 1 ? citationAliases.get(originalEvidence[0] ?? '') : undefined;
407
+ const citationCorrection = executionCitation && soleOwnerSource ? { from: executionCitation, to: soleOwnerSource }
408
+ : alias && knownReferences.has(alias) ? { from: originalEvidence[0], to: alias } : undefined;
401
409
  const evidenceArrayCorrection = singleReadCheck && typeof originalEvidence === 'string' && knownReferences.has(originalEvidence)
402
410
  ? { from: originalEvidence, to: [originalEvidence] } : undefined;
403
411
  // These are format-only aliases for one observed, read-only owner check.
package/dist/api.js CHANGED
@@ -16,6 +16,7 @@ import { ArdentA2AClient } from './a2a-client.js';
16
16
  import { TelegramAdapter } from './telegram.js';
17
17
  import { MattermostAdapter } from './mattermost.js';
18
18
  import { EventSchema, SessionMessageSchema, SessionSchema, TaskSchema, TaskState } from './store.js';
19
+ import { mountPluginHttp } from './plugin-http.js';
19
20
  import { pluginContext } from './plugins.js';
20
21
  import { MissionSubmit } from './missions.js';
21
22
  import { ArtifactRecordSchema } from './artifact-manifests.js';
@@ -547,5 +548,6 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
547
548
  plugin.routes(sub, ctx);
548
549
  app.route(`/api/v1/plugins/${plugin.name}`, sub);
549
550
  }
551
+ mountPluginHttp(app, runtime, env, jobEngine);
550
552
  return app;
551
553
  }
package/dist/cli.js CHANGED
@@ -27,17 +27,17 @@ import { BUILTIN_JOB_VALIDATION_REGISTRY, builtinJobHandlers } from './job-news-
27
27
  import { acquireGatewayLock, createLockFile } from './gateway-lock.js';
28
28
  import { ContextCheckpoints } from './context-checkpoints.js';
29
29
  import { loadModelPolicy } from './model-policy.js';
30
- import { loadPlugins, pluginContext, pluginJobHandlers, validationContext } from './plugins.js';
30
+ import { loadPlugins, pluginContext, pluginChannelAdapter, pluginJobHandlers, validationContext } from './plugins.js';
31
31
  import { ARDENT_VERSION } from './version.js';
32
32
  import { acceptRuntime } from './acceptance.js';
33
33
  import { readProfileEnv } from './profile-env.js';
34
34
  import { PlainTextFilter } from './live-text.js';
35
35
  import { developmentQuery, missionSubmitInput, previewInput } from './cli-commands.js';
36
36
  import { developmentPage, DevelopmentRecords, recordSkillChange } from './development.js';
37
- function args(argv) {
37
+ function args(argv, extraValues = []) {
38
38
  const words = [];
39
39
  const options = new Map();
40
- const valued = new Set(['env-file', 'profile', 'profile-path', 'api-port', 'template', 'prompt', 'prompt-file', 'idempotency-key', 'session-id', 'login-id', 'source', 'schedule-id', 'window-key', 'release-id', 'caller', 'context', 'expected-head', 'expected-policy-revision', 'mission-file', 'after', 'limit', 'kind', 'soul-file', 'identity-file', 'skills', 'model']);
40
+ const valued = new Set([...extraValues, 'env-file', 'profile', 'profile-path', 'api-port', 'template', 'prompt', 'prompt-file', 'idempotency-key', 'session-id', 'login-id', 'source', 'schedule-id', 'window-key', 'release-id', 'caller', 'context', 'expected-head', 'expected-policy-revision', 'mission-file', 'after', 'limit', 'kind', 'soul-file', 'identity-file', 'skills', 'model']);
41
41
  for (let i = 0; i < argv.length; i++) {
42
42
  const arg = argv[i];
43
43
  if (!arg)
@@ -125,8 +125,8 @@ Commands:
125
125
  tasks pause | resume <id> Hold a queued task, or release and run it
126
126
  gateway run Serve the management API, A2A, channels and jobs`;
127
127
  async function main() {
128
- const parsed = args(process.argv.slice(2));
129
- const [command, subcommand, id] = parsed.words;
128
+ let parsed = args(process.argv.slice(2));
129
+ let [command, subcommand, id] = parsed.words;
130
130
  if (parsed.options.has('version')) {
131
131
  stdout.write(`${ARDENT_VERSION}\n`);
132
132
  return;
@@ -160,11 +160,16 @@ async function main() {
160
160
  process.exitCode = 1;
161
161
  return;
162
162
  }
163
- const plugins = await loadPlugins(loaded.config, dir);
163
+ const plugins = await loadPlugins(loaded.config, dir, env);
164
+ parsed = args(process.argv.slice(2), plugins.flatMap(plugin => Object.values(plugin.cliCommands ?? {}).flatMap(command => [...command.valueOptions ?? []])));
165
+ [command, subcommand, id] = parsed.words;
164
166
  for (const plugin of plugins) {
165
167
  const pluginCommand = command ? plugin.cliCommands?.[command] : undefined;
166
168
  if (pluginCommand) {
167
- await pluginCommand.run({ words: parsed.words.slice(1), options: parsed.options, profileDir: dir, config: loaded.config, env, print });
169
+ const invocation = { rawArgs: process.argv.slice(2), words: parsed.words.slice(1), options: parsed.options, profileDir: dir, config: loaded.config, env, print };
170
+ if (pluginCommand.matches?.(invocation) === false)
171
+ continue;
172
+ await pluginCommand.run(invocation);
168
173
  return;
169
174
  }
170
175
  }
@@ -316,13 +321,23 @@ async function main() {
316
321
  if (command === 'a2a' && subcommand === 'team-card') {
317
322
  if (!loaded.config.a2a.hermes_compat)
318
323
  throw new Error('Hermes team card requires a2a.hermes_compat: true');
319
- const runtime = new ArdentRuntime(dir, loaded.config, env);
324
+ const lock = await createLockFile(join(dir, 'state', 'gateway.lock'));
325
+ let runtime;
320
326
  try {
327
+ runtime = new ArdentRuntime(dir, loaded.config, env);
321
328
  await runtime.usePlugins(plugins, env);
322
- print(await hermesTeamCard(runtime, loaded.config));
329
+ print(await hermesTeamCard(runtime, loaded.config, env));
323
330
  }
324
331
  finally {
325
- runtime.close();
332
+ if (runtime) {
333
+ if (await runtime.drain(30_000))
334
+ runtime.close();
335
+ else {
336
+ stderr.write('Plugin work remains unsettled; retain the owner record.\n');
337
+ process.exit(1);
338
+ }
339
+ }
340
+ await lock.release();
326
341
  }
327
342
  return;
328
343
  }
@@ -486,6 +501,7 @@ async function main() {
486
501
  try {
487
502
  runtime = new ArdentRuntime(dir, loaded.config, env);
488
503
  await runtime.usePlugins(plugins, env);
504
+ await runtime.prepareGateway(env);
489
505
  // Legacy scheduled tasks are not replayed by a new gateway generation.
490
506
  // The job engine owns its own window recovery and never replays uncertain effects.
491
507
  for (const task of runtime.recovered.queued)
@@ -560,16 +576,18 @@ async function main() {
560
576
  a2aGrpc = surface.grpcServer;
561
577
  }
562
578
  }
579
+ await runtime.startPlugins(env);
563
580
  if (loaded.config.channels.telegram.enabled) {
564
581
  const fixtureBase = env.ARDENT_TELEGRAM_API_FIXTURE_URL;
565
582
  if (fixtureBase && (env.NODE_ENV !== 'test' || !/^http:\/\/(?:127\.0\.0\.1|localhost):\d+$/.test(fixtureBase)))
566
583
  throw new Error('Telegram API fixture URL is permitted only for loopback tests');
567
- const telegram = new TelegramAdapter(runtime, loaded.config.channels.telegram, env, fixtureBase ?? 'https://api.telegram.org', jobEngine);
584
+ const telegram = pluginChannelAdapter(plugins, ctx, 'telegram', jobEngine) ?? new TelegramAdapter(runtime, loaded.config.channels.telegram, env, fixtureBase ?? 'https://api.telegram.org', jobEngine);
568
585
  telegramRun = telegram.run(channelAbort.signal, deliveryAbort.signal);
569
586
  }
570
587
  if (loaded.config.channels.mattermost.enabled) {
571
- const mattermost = new MattermostAdapter(runtime, loaded.config.channels.mattermost, env, jobEngine);
572
- mattermostRun = mattermost.run(channelAbort.signal);
588
+ const replacement = pluginChannelAdapter(plugins, ctx, 'mattermost', jobEngine);
589
+ const mattermost = replacement ?? { run: (intake, _delivery) => new MattermostAdapter(runtime, loaded.config.channels.mattermost, env, jobEngine).run(intake) };
590
+ mattermostRun = mattermost.run(channelAbort.signal, deliveryAbort.signal);
573
591
  }
574
592
  print({ profile, host: loaded.config.api.host, port: loaded.config.api.port, a2a: a2aHttp ? 'listening' : 'disabled', status: 'listening' });
575
593
  await new Promise((resolve, reject) => {
@@ -625,7 +643,8 @@ async function main() {
625
643
  if (settled)
626
644
  runtime.close();
627
645
  }
628
- await lock.release();
646
+ if (!shutdownUnsettled)
647
+ await lock.release();
629
648
  }
630
649
  if (shutdownUnsettled) {
631
650
  stderr.write('Gateway shutdown left unresolved work; interrupted tasks will be marked unknown on restart.\n');
@@ -647,6 +666,13 @@ async function main() {
647
666
  await runtime.usePlugins(plugins, env);
648
667
  }
649
668
  catch (error) {
669
+ if (runtime) {
670
+ if (!await runtime.drain(30_000)) {
671
+ stderr.write('Plugin initialization left unresolved work; retain the owner record for recovery.\n');
672
+ process.exit(1);
673
+ }
674
+ runtime.close();
675
+ }
650
676
  await ownerLock.release();
651
677
  throw error;
652
678
  }
@@ -873,12 +899,12 @@ async function main() {
873
899
  }
874
900
  }
875
901
  finally {
876
- try {
877
- runtime.close();
878
- }
879
- finally {
880
- await ownerLock.release();
902
+ if (!await runtime.drain(30_000)) {
903
+ stderr.write('Command shutdown left unresolved work; retain the owner record for recovery.\n');
904
+ process.exit(1);
881
905
  }
906
+ runtime.close();
907
+ await ownerLock.release();
882
908
  }
883
909
  }
884
910
  main().catch((error) => {
@@ -27,8 +27,8 @@ export declare const DevelopmentRecordSchema: z.ZodObject<{
27
27
  body: z.ZodString;
28
28
  author: z.ZodEnum<{
29
29
  operator: "operator";
30
- agent: "agent";
31
30
  runtime: "runtime";
31
+ agent: "agent";
32
32
  }>;
33
33
  epistemic: z.ZodEnum<{
34
34
  observed: "observed";
@@ -12,4 +12,4 @@ export type HermesTeamCard = {
12
12
  tags: string[];
13
13
  }>;
14
14
  };
15
- export declare function hermesTeamCard(runtime: Pick<ArdentRuntime, 'tools'>, config: ArdentConfig): Promise<HermesTeamCard>;
15
+ export declare function hermesTeamCard(runtime: Pick<ArdentRuntime, 'tools'> & Partial<Pick<ArdentRuntime, 'plugins' | 'config' | 'profileDir'>>, config: ArdentConfig, env?: NodeJS.ProcessEnv): Promise<HermesTeamCard>;
@@ -1,6 +1,8 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { readFile, readdir } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
+ import { z } from 'zod';
5
+ import { pluginContext } from './plugins.js';
4
6
  /**
5
7
  * Optional Hermes Agent team-card compatibility (`a2a.hermes_compat: true`).
6
8
  * The card describes this profile's registered peer-callable tools so a Hermes
@@ -28,7 +30,8 @@ function toolset(name) {
28
30
  const prefix = /^([a-z][a-z0-9]*)_/.exec(name)?.[1];
29
31
  return prefix ?? 'tools';
30
32
  }
31
- export async function hermesTeamCard(runtime, config) {
33
+ function isRuntime(value) { return 'store' in value && 'profileDir' in value && 'plugins' in value; }
34
+ export async function hermesTeamCard(runtime, config, env = process.env) {
32
35
  const now = Math.floor(Date.now() / 1000);
33
36
  const description = config.a2a.skill?.description ?? `${config.name}: bounded tasks with this profile's registered tools`;
34
37
  const grouped = new Map();
@@ -49,7 +52,7 @@ export async function hermesTeamCard(runtime, config) {
49
52
  tags: [entry.id, 'task-conditional'] }));
50
53
  const sourceDigest = await digestRuntimeSource();
51
54
  const taskPolicyDigest = await digestModules(['a2a', 'a2a-client', 'a2a-idempotency', 'a2a-peers', 'runtime', 'team-contract', 'tools']);
52
- return { description, skills, metadata: { hermesTeam: {
55
+ const card = { description, skills, metadata: { hermesTeam: {
53
56
  schemaVersion: '1.0', missionContractVersions: ['1.0'], coordinationProtocolVersions: [],
54
57
  lifecycleProtocolVersions: ['1.0'], missionControlScopes: [], taskExecutionBoundaryVersion: '1.0',
55
58
  genericSurfacePolicyVersion: '1.0', sourceDigest, role: config.profile,
@@ -59,4 +62,18 @@ export async function hermesTeamCard(runtime, config) {
59
62
  taskPolicyDigest, runtimeKind: 'ardent', discovery: { schemaVersion: '1.0', observedAt: now, expiresAt: now + 300,
60
63
  registryStatus: 'observed', configurationStatus: 'observed', toolsets }
61
64
  } } };
65
+ const configured = runtime.plugins?.filter(plugin => plugin.teamCard) ?? [];
66
+ if (configured.length > 1)
67
+ throw new Error('Multiple plugins own the team card');
68
+ const plugin = configured[0];
69
+ if (!plugin?.teamCard)
70
+ return card;
71
+ // A real runtime supplies this context; tools-only callers retain the default card.
72
+ if (!isRuntime(runtime))
73
+ throw new Error('A plugin team card requires the selected runtime');
74
+ const custom = await plugin.teamCard(pluginContext(runtime, env), card);
75
+ if (Buffer.byteLength(JSON.stringify(custom)) > 64_000)
76
+ throw new Error('Plugin team card exceeds 64 KiB');
77
+ return z.object({ description: z.string().min(1).max(1000), metadata: z.object({ hermesTeam: z.record(z.string(), z.json()) }).strict(),
78
+ skills: z.array(z.object({ id: z.string().min(1).max(100), name: z.string().min(1).max(100), description: z.string().min(1).max(1000), tags: z.array(z.string().max(100)).max(32) }).strict()).max(64) }).strict().parse(custom);
62
79
  }
package/dist/index.d.ts CHANGED
@@ -5,5 +5,5 @@ export { TaskStore, type Task } from './store.js';
5
5
  export { defineTool, ToolRegistry, ProvenNoEffectError, type Tool, type ToolContext, type ToolEffect, type ToolResult } from './tools.js';
6
6
  export { createArdentApi, ardentOpenApi } from './api.js';
7
7
  export { JobEngine, validateJobDefinitions, type JobContext, type JobDefinition, type JobHandler, type JobRegistry, type JobResult, type OwnershipCheck } from './job-engine.js';
8
- export { definePlugin, registerPlugin, registeredPlugins, clearRegisteredPlugins, loadPlugins, type ArdentPlugin, type ArdentPluginContext, type ArdentCliCommand, type ArdentCliInvocation } from './plugins.js';
8
+ export { definePlugin, registerPlugin, registeredPlugins, clearRegisteredPlugins, loadPlugins, type ArdentPlugin, type ArdentPluginContext, type ArdentCliCommand, type ArdentCliInvocation, type ArdentPluginFactory, type ArdentPluginFactoryContext, type ArdentTaskPluginContext } from './plugins.js';
9
9
  export type { TeamEnvelope, TeamMission, TeamResult } from './team-contract.js';
@@ -2,10 +2,7 @@ import type Database from './sqlite.js';
2
2
  import { z } from 'zod';
3
3
  declare const definition: z.ZodObject<{
4
4
  id: z.ZodString;
5
- owner: z.ZodEnum<{
6
- external: "external";
7
- ardent: "ardent";
8
- }>;
5
+ owner: z.ZodString;
9
6
  enabled: z.ZodBoolean;
10
7
  handler: z.ZodString;
11
8
  schedule: z.ZodUnion<readonly [z.ZodObject<{
@@ -23,11 +20,7 @@ declare const definition: z.ZodObject<{
23
20
  }, z.core.$strict>]>;
24
21
  input: z.ZodOptional<z.ZodUnknown>;
25
22
  delivery: z.ZodObject<{
26
- kind: z.ZodEnum<{
27
- none: "none";
28
- telegram: "telegram";
29
- mattermost: "mattermost";
30
- }>;
23
+ kind: z.ZodString;
31
24
  target_ref: z.ZodOptional<z.ZodString>;
32
25
  }, z.core.$strict>;
33
26
  policy: z.ZodObject<{
@@ -37,10 +30,7 @@ declare const definition: z.ZodObject<{
37
30
  }, z.core.$strict>;
38
31
  export declare const JobDefinitionSchema: z.ZodObject<{
39
32
  id: z.ZodString;
40
- owner: z.ZodEnum<{
41
- external: "external";
42
- ardent: "ardent";
43
- }>;
33
+ owner: z.ZodString;
44
34
  enabled: z.ZodBoolean;
45
35
  handler: z.ZodString;
46
36
  schedule: z.ZodUnion<readonly [z.ZodObject<{
@@ -58,11 +48,7 @@ export declare const JobDefinitionSchema: z.ZodObject<{
58
48
  }, z.core.$strict>]>;
59
49
  input: z.ZodOptional<z.ZodUnknown>;
60
50
  delivery: z.ZodObject<{
61
- kind: z.ZodEnum<{
62
- none: "none";
63
- telegram: "telegram";
64
- mattermost: "mattermost";
65
- }>;
51
+ kind: z.ZodString;
66
52
  target_ref: z.ZodOptional<z.ZodString>;
67
53
  }, z.core.$strict>;
68
54
  policy: z.ZodObject<{
@@ -77,10 +63,7 @@ export declare const JobDefinitionsSchema: z.ZodObject<{
77
63
  revision: z.ZodNumber;
78
64
  jobs: z.ZodArray<z.ZodObject<{
79
65
  id: z.ZodString;
80
- owner: z.ZodEnum<{
81
- external: "external";
82
- ardent: "ardent";
83
- }>;
66
+ owner: z.ZodString;
84
67
  enabled: z.ZodBoolean;
85
68
  handler: z.ZodString;
86
69
  schedule: z.ZodUnion<readonly [z.ZodObject<{
@@ -98,11 +81,7 @@ export declare const JobDefinitionsSchema: z.ZodObject<{
98
81
  }, z.core.$strict>]>;
99
82
  input: z.ZodOptional<z.ZodUnknown>;
100
83
  delivery: z.ZodObject<{
101
- kind: z.ZodEnum<{
102
- none: "none";
103
- telegram: "telegram";
104
- mattermost: "mattermost";
105
- }>;
84
+ kind: z.ZodString;
106
85
  target_ref: z.ZodOptional<z.ZodString>;
107
86
  }, z.core.$strict>;
108
87
  policy: z.ZodObject<{
@@ -25,13 +25,14 @@ const intervalSchedule = z.object({
25
25
  }).strict();
26
26
  const definition = z.object({
27
27
  id: jobId,
28
- /** `external` marks a job retained for reference but owned by another scheduler. */
29
- owner: z.enum(['ardent', 'external']),
28
+ /** Only `ardent` admits work. Other bounded labels retain the original external owner. */
29
+ owner: identifier,
30
30
  enabled: z.boolean(),
31
31
  handler: identifier,
32
32
  schedule: z.union([cronSchedule, intervalSchedule]),
33
33
  input: z.unknown().optional(),
34
- delivery: z.object({ kind: z.enum(['none', 'telegram', 'mattermost']), target_ref: identifier.optional() }).strict(),
34
+ /** A handler must explicitly validate every delivery kind other than `none`. */
35
+ delivery: z.object({ kind: identifier, target_ref: identifier.optional() }).strict(),
35
36
  policy: z.object({ max_attempts: z.number().int().min(1).max(5), retry_backoff_seconds: z.number().int().min(1).max(3600) }).strict()
36
37
  }).strict();
37
38
  export const JobDefinitionSchema = definition;
@@ -19,6 +19,10 @@ export declare const MissionSubmit: z.ZodObject<{
19
19
  revision: z.ZodNumber;
20
20
  parent_task: z.ZodNullable<z.ZodString>;
21
21
  constraints: z.ZodArray<z.ZodString>;
22
+ resources: z.ZodArray<z.ZodString>;
23
+ deadline: z.ZodNumber;
24
+ acceptance_criteria: z.ZodArray<z.ZodString>;
25
+ expected_artifacts: z.ZodArray<z.ZodString>;
22
26
  allowed_actions: z.ZodArray<z.ZodEnum<{
23
27
  observe: "observe";
24
28
  analyze: "analyze";
@@ -29,10 +33,6 @@ export declare const MissionSubmit: z.ZodObject<{
29
33
  external_publish: "external_publish";
30
34
  destructive_response: "destructive_response";
31
35
  }>>;
32
- resources: z.ZodArray<z.ZodString>;
33
- deadline: z.ZodNumber;
34
- acceptance_criteria: z.ZodArray<z.ZodString>;
35
- expected_artifacts: z.ZodArray<z.ZodString>;
36
36
  }, z.core.$strict>;
37
37
  context_items: z.ZodOptional<z.ZodArray<z.ZodObject<{
38
38
  title: z.ZodString;
@@ -50,7 +50,7 @@ export declare const MissionRecord: z.ZodObject<{
50
50
  revision: z.ZodNumber;
51
51
  parent_task: z.ZodNullable<z.ZodString>;
52
52
  constraints: z.ZodArray<z.ZodString>;
53
- allowed_actions: z.ZodArray<z.ZodEnum<{
53
+ allowed_actions: z.ZodArray<z.ZodUnion<readonly [z.ZodEnum<{
54
54
  observe: "observe";
55
55
  analyze: "analyze";
56
56
  create_artifact: "create_artifact";
@@ -59,11 +59,12 @@ export declare const MissionRecord: z.ZodObject<{
59
59
  deploy: "deploy";
60
60
  external_publish: "external_publish";
61
61
  destructive_response: "destructive_response";
62
- }>>;
62
+ }>, z.ZodString]>>;
63
63
  resources: z.ZodArray<z.ZodString>;
64
64
  deadline: z.ZodNumber;
65
65
  acceptance_criteria: z.ZodArray<z.ZodString>;
66
66
  expected_artifacts: z.ZodArray<z.ZodString>;
67
+ extensions: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodJSONSchema>>;
67
68
  }, z.core.$strict>;
68
69
  context_items: z.ZodArray<z.ZodObject<{
69
70
  title: z.ZodString;
package/dist/missions.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import { TEAM_VERSION, TeamMission, TeamResult, validateTeamResult } from './team-contract.js';
2
+ import { TEAM_VERSION, CoreTeamAction, TeamMission, TeamResult, validateTeamResult } from './team-contract.js';
3
3
  /** Bound on the combined text of a mission's context items. */
4
4
  export const MAX_CONTEXT_ITEM_BYTES = 64 * 1024;
5
5
  const MISSION_EVENT = 'mission';
@@ -10,7 +10,7 @@ export const MissionLabels = z.record(z.string().regex(/^[a-z][a-z0-9._:-]{0,63}
10
10
  export const MissionSubmit = z.object({
11
11
  session_id: z.string().guid().optional(),
12
12
  objective: z.string().trim().min(1).max(16000),
13
- mission: TeamMission,
13
+ mission: TeamMission.omit({ extensions: true }).extend({ allowed_actions: z.array(CoreTeamAction).min(1).max(8).refine(actions => new Set(actions).size === actions.length, 'Duplicate action') }),
14
14
  context_items: z.array(ContextItem).max(64).optional()
15
15
  .refine(items => Buffer.byteLength((items ?? []).map(item => item.title + item.text).join(''), 'utf8') <= MAX_CONTEXT_ITEM_BYTES, `Context items exceed ${MAX_CONTEXT_ITEM_BYTES / 1024} KiB`),
16
16
  labels: MissionLabels.optional(),
@@ -0,0 +1,16 @@
1
+ import type { ArdentRuntime } from './runtime.js';
2
+ import type { Task } from './store.js';
3
+ import type { TeamEnvelope } from './team-contract.js';
4
+ /** Core verifies artifact bytes and grants; a configured plugin validates its own receipt schema. */
5
+ export declare function collectPluginTeamEvidence(runtime: ArdentRuntime, task: Task, envelope: TeamEnvelope, env: NodeJS.ProcessEnv): Promise<{
6
+ references: Set<string>;
7
+ artifacts: {
8
+ name: string;
9
+ sha256: string;
10
+ reference: string;
11
+ mime: string;
12
+ producer: string;
13
+ source: string;
14
+ }[];
15
+ aliases: Map<string, string>;
16
+ }>;