@hivemagnus/ardent 2.3.1 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,8 @@
1
- import type Database from 'better-sqlite3';
1
+ 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<{
@@ -175,14 +154,14 @@ export declare function validateJobDefinitions(raw: unknown, registry: JobRegist
175
154
  /** A profile-local SQLite scheduler. No work is admitted without a fresh ownership check. */
176
155
  export declare class JobEngine {
177
156
  #private;
178
- readonly db: Database.Database;
157
+ readonly db: Database;
179
158
  readonly profileDir: string;
180
159
  readonly profile: string;
181
160
  readonly registry: JobRegistry;
182
161
  readonly ownershipCheck: OwnershipCheck;
183
162
  readonly clock: () => number;
184
163
  /** `clock` measures elapsed time within a tick; the injected tick time stays the timeline origin. */
185
- constructor(db: Database.Database, profileDir: string, profile: string, registry: JobRegistry, ownershipCheck: OwnershipCheck, clock?: () => number);
164
+ constructor(db: Database, profileDir: string, profile: string, registry: JobRegistry, ownershipCheck: OwnershipCheck, clock?: () => number);
186
165
  load(): Promise<{
187
166
  definitions: JobDefinitions;
188
167
  sha256: string;
@@ -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
+ }>;
@@ -0,0 +1,44 @@
1
+ import { z } from 'zod';
2
+ import { pluginContext } from './plugins.js';
3
+ const Reference = z.string().min(8).max(1000).regex(/^source:\S+$/);
4
+ const Evidence = z.object({
5
+ references: z.array(Reference).max(100),
6
+ artifacts: z.array(z.object({ name: z.string().regex(/^[A-Za-z0-9._-]{1,128}$/), sha256: z.string().regex(/^[a-f0-9]{64}$/), mime: z.string().min(1).max(128), source: z.string().max(1000).optional() }).strict()).max(32),
7
+ citationAliases: z.record(Reference, Reference).optional()
8
+ }).strict();
9
+ /** Core verifies artifact bytes and grants; a configured plugin validates its own receipt schema. */
10
+ export async function collectPluginTeamEvidence(runtime, task, envelope, env) {
11
+ const references = new Set(), aliases = new Map(), ambiguous = new Set();
12
+ const artifacts = [];
13
+ const events = runtime.store.events(task.id, 0, 500);
14
+ for (const plugin of runtime.plugins) {
15
+ const raw = plugin.teamEvidence?.(pluginContext(runtime, env), task, envelope, events);
16
+ if (raw === undefined)
17
+ continue;
18
+ const evidence = Evidence.parse(raw);
19
+ for (const reference of evidence.references)
20
+ references.add(reference);
21
+ if (evidence.artifacts.length && !envelope.mission.allowed_actions.includes('create_artifact') &&
22
+ !envelope.mission.allowed_actions.some(action => action.startsWith(`extension:${plugin.name}:`)))
23
+ throw new Error('Plugin artifact lacks an exact mission grant');
24
+ for (const artifact of evidence.artifacts) {
25
+ await runtime.artifacts.get(artifact.sha256);
26
+ const prior = artifacts.find(item => item.name === artifact.name);
27
+ if (prior && prior.sha256 !== artifact.sha256)
28
+ throw new Error('Conflicting plugin artifact name');
29
+ if (!prior)
30
+ artifacts.push({ ...artifact, reference: `ardent-artifact:${artifact.sha256}`, producer: `ardent-plugin:${plugin.name}`, source: artifact.source ?? '' });
31
+ }
32
+ for (const [from, to] of Object.entries(evidence.citationAliases ?? {})) {
33
+ if (!evidence.references.includes(to))
34
+ throw new Error('Citation alias has no observed target');
35
+ if (aliases.has(from) && aliases.get(from) !== to)
36
+ ambiguous.add(from);
37
+ else
38
+ aliases.set(from, to);
39
+ }
40
+ }
41
+ for (const alias of ambiguous)
42
+ aliases.delete(alias);
43
+ return { references, artifacts, aliases };
44
+ }
@@ -0,0 +1,4 @@
1
+ import type { Hono } from 'hono';
2
+ import type { JobEngine } from './job-engine.js';
3
+ import type { ArdentRuntime } from './runtime.js';
4
+ export declare function mountPluginHttp(app: Hono, runtime: ArdentRuntime, env: NodeJS.ProcessEnv, jobs?: JobEngine): void;
@@ -0,0 +1,43 @@
1
+ import { bodyLimit } from 'hono/body-limit';
2
+ import { pluginContext } from './plugins.js';
3
+ import { TokenBucketLimiter } from './a2a-rate-limit.js';
4
+ /** Hono's route precedence must never let an extension shadow an existing handler. */
5
+ function overlaps(a, b) {
6
+ const left = a.split('/'), right = b.split('/');
7
+ return left.length === right.length && left.every((part, index) => part === right[index] || part.startsWith(':') || right[index]?.startsWith(':'));
8
+ }
9
+ export function mountPluginHttp(app, runtime, env, jobs) {
10
+ const claimed = app.routes.filter(route => route.method !== 'ALL').map(route => ({ method: route.method, path: route.path, owner: '' }));
11
+ const planned = [];
12
+ const ctx = pluginContext(runtime, env);
13
+ for (const plugin of runtime.plugins)
14
+ for (const mount of plugin.httpRoutes?.(ctx, jobs) ?? []) {
15
+ if (!['management', 'independent'].includes(mount.security))
16
+ throw new Error('Plugin HTTP security declaration is required');
17
+ for (const route of mount.app.routes) {
18
+ const path = route.path;
19
+ if (!['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'].includes(route.method) ||
20
+ !/^\/(?:[a-zA-Z0-9_-]+|:[a-zA-Z][a-zA-Z0-9_]*)(?:\/(?:[a-zA-Z0-9_-]+|:[a-zA-Z][a-zA-Z0-9_]*))*$/.test(path))
21
+ throw new Error('Plugin HTTP routes require explicit methods and bounded paths');
22
+ const management = path.startsWith('/api/v1/');
23
+ if (mount.security === 'management' ? !management : /^\/(?:api|health|a2a)(?:\/|$)/.test(path) || path === '/openapi.json')
24
+ throw new Error('Plugin HTTP route uses a reserved authentication boundary');
25
+ if (claimed.some(prior => (prior.method === route.method || [prior.method, route.method].every(method => ['GET', 'HEAD'].includes(method))) && overlaps(prior.path, path) && (prior.owner !== plugin.name || prior.path.replace(/:[^/]+/g, ':') === path.replace(/:[^/]+/g, ':'))))
26
+ throw new Error(`Plugin ${plugin.name} HTTP route ${route.method} ${path} overlaps an existing route`);
27
+ claimed.push({ method: route.method, path, owner: plugin.name });
28
+ planned.push({ route, plugin: plugin.name });
29
+ }
30
+ }
31
+ // One bounded bucket per configured plugin, before handler authentication and body processing.
32
+ const limits = new Map();
33
+ for (const { route, plugin } of planned) {
34
+ const limiter = limits.get(plugin) ?? new TokenBucketLimiter({ perMinute: 600, burst: 120 });
35
+ limits.set(plugin, limiter);
36
+ app.on(route.method, route.path, async (c, next) => {
37
+ const result = limiter.take('ingress');
38
+ if (!result.allowed)
39
+ return c.json({ error: { code: 'RATE_LIMITED' } }, 429, { 'Retry-After': String(result.retryAfterSeconds), 'Cache-Control': 'no-store' });
40
+ return next();
41
+ }, bodyLimit({ maxSize: 1_048_576, onError: c => c.json({ error: { code: 'BODY_TOO_LARGE' } }, 413) }), route.handler);
42
+ }
43
+ }
@@ -0,0 +1,3 @@
1
+ import type { ArdentPlugin, ArdentTaskPluginContext } from './plugins.js';
2
+ /** Validate retained bytes, never accepting a client-supplied path or a peer image grant. */
3
+ export declare function pluginInputImages(plugins: readonly ArdentPlugin[], ctx: ArdentTaskPluginContext): Promise<string[]>;
@@ -0,0 +1,40 @@
1
+ import { constants } from 'node:fs';
2
+ import { lstat, open, realpath } from 'node:fs/promises';
3
+ import { createHash } from 'node:crypto';
4
+ import { join, sep } from 'node:path';
5
+ import { z } from 'zod';
6
+ const Image = z.object({ path: z.string().min(1).max(2048), sha256: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
7
+ /** Validate retained bytes, never accepting a client-supplied path or a peer image grant. */
8
+ export async function pluginInputImages(plugins, ctx) {
9
+ const images = z.array(Image).max(5).parse((await Promise.all(plugins.map(plugin => plugin.inputImages?.(ctx) ?? []))).flat());
10
+ if (!images.length)
11
+ return [];
12
+ if (ctx.task.context !== 'direct' || ctx.task.backend !== 'codex')
13
+ throw new Error('Extension images require a direct Codex task');
14
+ const root = join(await realpath(ctx.profileDir), 'artifacts');
15
+ const directory = await lstat(root);
16
+ if (!directory.isDirectory() || directory.isSymbolicLink() || directory.uid !== process.getuid?.() || await realpath(root) !== root)
17
+ throw new Error('Extension image directory is not an owned profile artifact directory');
18
+ const seen = new Set();
19
+ for (const image of images) {
20
+ const path = await realpath(image.path);
21
+ if (path !== image.path || !path.startsWith(root + sep) || seen.has(path))
22
+ throw new Error('Extension image path is not a unique retained artifact');
23
+ seen.add(path);
24
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
25
+ try {
26
+ const stat = await file.stat();
27
+ if (!stat.isFile() || stat.nlink !== 1 || stat.uid !== process.getuid?.() || (stat.mode & 0o077) !== 0 || stat.size < 8 || stat.size > 8 * 1024 * 1024)
28
+ throw new Error('Extension image ownership or size differs');
29
+ const bytes = await file.readFile();
30
+ if (bytes.length !== stat.size || createHash('sha256').update(bytes).digest('hex') !== image.sha256)
31
+ throw new Error('Extension image digest differs');
32
+ if (!bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) && !bytes.subarray(0, 3).equals(Buffer.from([255, 216, 255])))
33
+ throw new Error('Extension input is not a supported image');
34
+ }
35
+ finally {
36
+ await file.close();
37
+ }
38
+ }
39
+ return images.map(image => image.path);
40
+ }
@@ -0,0 +1,25 @@
1
+ /** Supported primitives for profile extensions. No deployment-specific policy lives here. */
2
+ export { ArdentRuntime, type RunResult, type TaskEvidence } from './runtime.js';
3
+ export * from './plugins.js';
4
+ export * from './config.js';
5
+ export * from './store.js';
6
+ export * from './tools.js';
7
+ export * from './artifacts.js';
8
+ export * from './a2a-peers.js';
9
+ export * from './codex.js';
10
+ export * from './context.js';
11
+ export * from './context-checkpoints.js';
12
+ export * from './backend-events.js';
13
+ export * from './identity.js';
14
+ export * from './json-schema.js';
15
+ export * from './llamacpp.js';
16
+ export * from './memory.js';
17
+ export * from './memory-tools.js';
18
+ export * from './model-policy.js';
19
+ export * from './owner-read.js';
20
+ export * from './skills.js';
21
+ export * from './job-engine.js';
22
+ export { Database as SqliteDatabase } from './sqlite.js';
23
+ export type SqliteStatement = ReturnType<import('./sqlite.js').Database['prepare']>;
24
+ export * from './team-contract.js';
25
+ export { ARDENT_VERSION } from './version.js';
@@ -0,0 +1,24 @@
1
+ /** Supported primitives for profile extensions. No deployment-specific policy lives here. */
2
+ export { ArdentRuntime } from './runtime.js';
3
+ export * from './plugins.js';
4
+ export * from './config.js';
5
+ export * from './store.js';
6
+ export * from './tools.js';
7
+ export * from './artifacts.js';
8
+ export * from './a2a-peers.js';
9
+ export * from './codex.js';
10
+ export * from './context.js';
11
+ export * from './context-checkpoints.js';
12
+ export * from './backend-events.js';
13
+ export * from './identity.js';
14
+ export * from './json-schema.js';
15
+ export * from './llamacpp.js';
16
+ export * from './memory.js';
17
+ export * from './memory-tools.js';
18
+ export * from './model-policy.js';
19
+ export * from './owner-read.js';
20
+ export * from './skills.js';
21
+ export * from './job-engine.js';
22
+ export { Database as SqliteDatabase } from './sqlite.js';
23
+ export * from './team-contract.js';
24
+ export { ARDENT_VERSION } from './version.js';
package/dist/plugins.d.ts CHANGED
@@ -1,12 +1,17 @@
1
1
  import type { Hono } from 'hono';
2
2
  import type { ArdentConfig } from './config.js';
3
- import type { JobRegistry, OwnershipCheck } from './job-engine.js';
4
- import type { ArdentRuntime } from './runtime.js';
5
- import type { Task } from './store.js';
6
- import { defineTool, type Tool, type ToolRegistry } from './tools.js';
7
- import type { TeamEnvelope } from './team-contract.js';
3
+ import type { JobEngine, JobRegistry, OwnershipCheck } from './job-engine.js';
4
+ import type { ArdentRuntime, TaskEvidence } from './runtime.js';
5
+ import type { ResearchBrief } from './research.js';
6
+ import type { SkillInfo } from './skills.js';
7
+ import type { Task, TaskEvent } from './store.js';
8
+ import { defineTool, ToolRegistry, type Tool, type ToolResult } from './tools.js';
9
+ import { TeamEnvelope } from './team-contract.js';
10
+ import type { HermesTeamCard } from './hermes-compat.js';
8
11
  /** Everything a plugin may use. Plugins receive no authority beyond the profile's own runtime. */
9
12
  export type ArdentPluginContext = {
13
+ /** False for offline validation; runtime and tools are unavailable there. */
14
+ runtimeAvailable: boolean;
10
15
  runtime: ArdentRuntime;
11
16
  config: ArdentConfig;
12
17
  profileDir: string;
@@ -19,6 +24,8 @@ export type ArdentPluginContext = {
19
24
  export type ArdentCliInvocation = {
20
25
  /** Positional words after the command name. */
21
26
  words: string[];
27
+ /** Original CLI arguments for a plugin with its own bounded option grammar. */
28
+ rawArgs?: readonly string[];
22
29
  options: ReadonlyMap<string, string | true>;
23
30
  profileDir: string;
24
31
  config: ArdentConfig;
@@ -28,8 +35,69 @@ export type ArdentCliInvocation = {
28
35
  };
29
36
  export type ArdentCliCommand = {
30
37
  description: string;
38
+ /** Named options that consume one value, including when placed before the command. */
39
+ valueOptions?: readonly string[];
40
+ /** Select an extension subcommand without taking over other core subcommands. */
41
+ matches?(invocation: ArdentCliInvocation): boolean;
31
42
  run(invocation: ArdentCliInvocation): Promise<void>;
32
43
  };
44
+ /** Factory-time configuration is available before a runtime or its consumers exist. */
45
+ export type ArdentPluginFactoryContext = {
46
+ config: ArdentConfig;
47
+ profileDir: string;
48
+ env: NodeJS.ProcessEnv;
49
+ };
50
+ export type ArdentPluginFactory = (context: ArdentPluginFactoryContext) => ArdentPlugin | readonly ArdentPlugin[] | Promise<ArdentPlugin | readonly ArdentPlugin[]>;
51
+ /** An exact persisted task and its already scoped built-in tools. */
52
+ export type ArdentTaskPluginContext = ArdentPluginContext & {
53
+ task: Task;
54
+ envelope?: TeamEnvelope;
55
+ baseTools: readonly Tool[];
56
+ };
57
+ export type ArdentPromptInput = {
58
+ prompt: string;
59
+ memory: string;
60
+ skills: readonly SkillInfo[];
61
+ tools: ToolRegistry;
62
+ };
63
+ export type ArdentCompletionInput = {
64
+ answer: string;
65
+ brief?: ResearchBrief;
66
+ partial: boolean;
67
+ evidence: TaskEvidence;
68
+ };
69
+ export type ArdentChannelAdapter = {
70
+ run(intake: AbortSignal, delivery: AbortSignal): Promise<void>;
71
+ };
72
+ export type ArdentTaskExecutor = {
73
+ id: string;
74
+ /** Any provider call or possible external write requires `possible`. */
75
+ effect: 'none' | 'possible';
76
+ run(signal: AbortSignal): Promise<{
77
+ answer: string;
78
+ effect_status: 'none' | 'confirmed' | 'unknown';
79
+ }>;
80
+ };
81
+ export type ArdentInputImage = {
82
+ path: string;
83
+ sha256: string;
84
+ };
85
+ export type ArdentTeamEvidence = {
86
+ references: readonly string[];
87
+ artifacts: readonly {
88
+ name: string;
89
+ sha256: string;
90
+ mime: string;
91
+ source?: string;
92
+ }[];
93
+ /** Format-only aliases to observed references, used for one read-only check. */
94
+ citationAliases?: Readonly<Record<string, string>>;
95
+ };
96
+ export type ArdentHttpRoutes = {
97
+ /** Management aliases keep bearer auth. Independent ingress must authenticate inside every handler. */
98
+ security: 'management' | 'independent';
99
+ app: Hono;
100
+ };
33
101
  /**
34
102
  * An Ardent extension. Every hook is optional.
35
103
  *
@@ -46,13 +114,51 @@ export type ArdentCliCommand = {
46
114
  export interface ArdentPlugin {
47
115
  name: string;
48
116
  registerTools?(ctx: ArdentPluginContext): void | Promise<void>;
49
- /** Called with a validation context (no runtime) by `ardent jobs definitions validate`; use `ctx.runtime` only inside `run`. */
117
+ /** Management routes mounted under the plugin namespace, behind bearer authentication. */
50
118
  routes?(app: Hono, ctx: ArdentPluginContext): void;
51
119
  cliCommands?: Record<string, ArdentCliCommand>;
52
120
  /** Also called with a runtime-less validation context by `ardent jobs definitions validate`; touch `ctx.runtime` only inside `run`. */
53
121
  jobHandlers?(ctx: ArdentPluginContext): JobRegistry;
54
122
  jobOwnership?(ctx: ArdentPluginContext): OwnershipCheck;
55
123
  peerTool?(tool: Tool, task: Task, envelope: TeamEnvelope | undefined): boolean;
124
+ /** Add tools bound to this task. Peer and mission grants are still checked. */
125
+ taskTools?(ctx: ArdentTaskPluginContext): readonly Tool[];
126
+ /** Restrict the final tool set. This hook can remove authority, never add it. */
127
+ filterTool?(ctx: ArdentTaskPluginContext, tool: Tool): boolean;
128
+ /** Validate a legacy wire envelope and translate only owned extension fields/actions. */
129
+ teamEnvelope?(value: unknown): TeamEnvelope | undefined;
130
+ /** Additional admission restrictions, after authenticated message/deadline validation. */
131
+ admitTeamEnvelope?(ctx: ArdentPluginContext, envelope: TeamEnvelope, wire: unknown): void;
132
+ /** Replace one enabled built-in consumer, retaining its original receipt identity. */
133
+ channelAdapter?(ctx: ArdentPluginContext, channel: 'telegram' | 'mattermost', jobs?: JobEngine): ArdentChannelAdapter | undefined;
134
+ /** Explicit compatibility routes. Core paths and overlapping registrations are refused. */
135
+ httpRoutes?(ctx: ArdentPluginContext, jobs?: JobEngine): readonly ArdentHttpRoutes[];
136
+ /** Trusted policy text, still subject to the complete model input budget. */
137
+ systemPrompt?(ctx: ArdentTaskPluginContext, input: ArdentPromptInput): Promise<string> | string;
138
+ /** Restrict an already admitted memory read; this cannot grant another scope. */
139
+ allowMemory?(ctx: ArdentTaskPluginContext, scope: 'private' | 'shared', projectId?: string): boolean;
140
+ /** Observe an actual tool result, retaining evidence within this task only. */
141
+ observeToolResult?(ctx: ArdentTaskPluginContext, name: string, result: ToolResult, evidence: TaskEvidence): void;
142
+ /** Additional validation before terminal success; throwing prevents completion. */
143
+ beforeFinish?(ctx: ArdentTaskPluginContext, input: ArdentCompletionInput): Promise<void> | void;
144
+ /** Release per-task resources after execution, including failed/cancelled tasks. */
145
+ taskSettled?(ctx: ArdentTaskPluginContext): void;
146
+ /** Deterministic owned workflow; attempts are journaled before invocation and never replayed. */
147
+ taskExecutor?(ctx: ArdentTaskPluginContext): ArdentTaskExecutor | undefined;
148
+ /** Owner-authenticated retained images, confined to this profile's artifact directory. */
149
+ inputImages?(ctx: ArdentTaskPluginContext): Promise<readonly ArdentInputImage[]> | readonly ArdentInputImage[];
150
+ /** Build evidence from retained receipts, never from the model's completion claim. */
151
+ teamEvidence?(ctx: ArdentPluginContext, task: Task, envelope: TeamEnvelope, events: readonly TaskEvent[]): ArdentTeamEvidence;
152
+ /** Describe private role capabilities; discovery remains information, never authorization. */
153
+ teamCard?(ctx: ArdentPluginContext, card: HermesTeamCard): Promise<HermesTeamCard> | HermesTeamCard;
154
+ /** Verify external consumer ownership before any gateway intake resumes. */
155
+ prepareGateway?(ctx: ArdentPluginContext): Promise<void> | void;
156
+ /** Start owned background consumers only in gateway mode. */
157
+ start?(ctx: ArdentPluginContext): Promise<void> | void;
158
+ /** Stop private intake and await owned work; false retains unsettled ownership. */
159
+ drain?(ctx: ArdentPluginContext, timeoutMs: number): Promise<boolean>;
160
+ /** Synchronous cleanup after drain, before the shared journal closes. */
161
+ close?(ctx: ArdentPluginContext): void;
56
162
  }
57
163
  /** Identity helper that type-checks a plugin definition. */
58
164
  export declare function definePlugin(plugin: ArdentPlugin): ArdentPlugin;
@@ -67,8 +173,13 @@ export declare function clearRegisteredPlugins(): void;
67
173
  * programmatically. A module's default export (or named `plugin` export) may
68
174
  * be one plugin or an array of plugins.
69
175
  */
70
- export declare function loadPlugins(config: ArdentConfig, profileDir: string): Promise<ArdentPlugin[]>;
176
+ export declare function loadPlugins(config: ArdentConfig, profileDir: string, env?: NodeJS.ProcessEnv): Promise<ArdentPlugin[]>;
71
177
  export declare function validationContext(config: ArdentConfig, profileDir: string, env: NodeJS.ProcessEnv): ArdentPluginContext;
72
178
  export declare function pluginContext(runtime: ArdentRuntime, env: NodeJS.ProcessEnv): ArdentPluginContext;
179
+ /** A codec cannot change authenticated identity, constraints, resources, or core actions. */
180
+ export declare function pluginTeamEnvelope(plugins: readonly ArdentPlugin[], value: unknown): TeamEnvelope;
73
181
  /** Merge plugin job handlers into a base registry; a duplicate handler ID is an error. */
74
182
  export declare function pluginJobHandlers(plugins: readonly ArdentPlugin[], ctx: ArdentPluginContext, base?: JobRegistry): JobRegistry;
183
+ export declare function pluginChannelAdapter(plugins: readonly ArdentPlugin[], ctx: ArdentPluginContext, channel: 'telegram' | 'mattermost', jobs?: JobEngine): ArdentChannelAdapter | undefined;
184
+ /** Task additions cannot bypass context, preview effect, peer grant or restrictive filters. */
185
+ export declare function pluginTaskTools(plugins: readonly ArdentPlugin[], ctx: ArdentTaskPluginContext): ToolRegistry;