@hivemagnus/ardent 3.0.0 → 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.
- package/README.md +71 -0
- package/dist/a2a-server.js +1 -1
- package/dist/a2a.js +19 -11
- package/dist/api.js +2 -0
- package/dist/cli.js +45 -19
- package/dist/development.d.ts +1 -1
- package/dist/hermes-compat.d.ts +1 -1
- package/dist/hermes-compat.js +19 -2
- package/dist/index.d.ts +1 -1
- package/dist/job-engine.d.ts +6 -27
- package/dist/job-engine.js +4 -3
- package/dist/missions.d.ts +7 -6
- package/dist/missions.js +2 -2
- package/dist/plugin-evidence.d.ts +16 -0
- package/dist/plugin-evidence.js +44 -0
- package/dist/plugin-http.d.ts +4 -0
- package/dist/plugin-http.js +43 -0
- package/dist/plugin-inputs.d.ts +3 -0
- package/dist/plugin-inputs.js +40 -0
- package/dist/plugin-sdk.d.ts +25 -0
- package/dist/plugin-sdk.js +24 -0
- package/dist/plugins.d.ts +118 -7
- package/dist/plugins.js +93 -6
- package/dist/runtime.d.ts +20 -1
- package/dist/runtime.js +162 -23
- package/dist/sqlite.d.ts +0 -1
- package/dist/sqlite.js +11 -3
- package/dist/store.d.ts +3 -1
- package/dist/store.js +5 -5
- package/dist/team-artifacts.js +5 -5
- package/dist/team-contract.d.ts +20 -7
- package/dist/team-contract.js +11 -5
- package/dist/team-control.js +1 -2
- package/package.json +5 -1
|
@@ -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,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 {
|
|
6
|
-
import
|
|
7
|
-
import type {
|
|
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
|
-
/**
|
|
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;
|
package/dist/plugins.js
CHANGED
|
@@ -1,28 +1,33 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
2
|
import { isAbsolute, join } from 'node:path';
|
|
3
3
|
import { pathToFileURL } from 'node:url';
|
|
4
|
-
import {
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { defineTool, ToolRegistry } from './tools.js';
|
|
6
|
+
import { TeamEnvelope, TeamMissionShape } from './team-contract.js';
|
|
5
7
|
const pluginName = /^[a-z][a-z0-9-]{0,63}$/;
|
|
6
8
|
const registered = [];
|
|
7
9
|
/** Identity helper that type-checks a plugin definition. */
|
|
8
10
|
export function definePlugin(plugin) {
|
|
9
11
|
return plugin;
|
|
10
12
|
}
|
|
13
|
+
function isPluginFactory(value) { return typeof value === 'function'; }
|
|
11
14
|
function isRecord(value) {
|
|
12
15
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
13
16
|
}
|
|
14
17
|
function assertPlugin(plugin, source) {
|
|
15
18
|
if (!isRecord(plugin) || typeof plugin.name !== 'string' || !pluginName.test(plugin.name))
|
|
16
19
|
throw new Error(`Plugin ${source} must export an object with a lowercase name`);
|
|
17
|
-
for (const hook of ['registerTools', 'routes', 'jobHandlers', 'jobOwnership', 'peerTool'])
|
|
20
|
+
for (const hook of ['registerTools', 'routes', 'jobHandlers', 'jobOwnership', 'peerTool', 'taskTools', 'filterTool', 'teamEnvelope', 'admitTeamEnvelope', 'channelAdapter', 'httpRoutes', 'systemPrompt', 'allowMemory', 'observeToolResult', 'beforeFinish', 'taskSettled', 'taskExecutor', 'inputImages', 'teamEvidence', 'teamCard', 'prepareGateway', 'start', 'drain', 'close'])
|
|
18
21
|
if (plugin[hook] !== undefined && typeof plugin[hook] !== 'function')
|
|
19
22
|
throw new Error(`Plugin ${plugin.name} hook ${hook} must be a function`);
|
|
20
23
|
if (plugin.cliCommands !== undefined) {
|
|
21
24
|
if (!isRecord(plugin.cliCommands))
|
|
22
25
|
throw new Error(`Plugin ${plugin.name} cliCommands must be an object`);
|
|
23
26
|
for (const [name, command] of Object.entries(plugin.cliCommands))
|
|
24
|
-
if (!pluginName.test(name) || !isRecord(command) || typeof command.run !== 'function')
|
|
27
|
+
if (!pluginName.test(name) || !isRecord(command) || typeof command.run !== 'function' || command.matches !== undefined && typeof command.matches !== 'function')
|
|
25
28
|
throw new Error(`Plugin ${plugin.name} CLI command ${name} is invalid`);
|
|
29
|
+
else if (command.valueOptions !== undefined && (!Array.isArray(command.valueOptions) || command.valueOptions.length > 64 || command.valueOptions.some((value) => typeof value !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/.test(value))))
|
|
30
|
+
throw new Error(`Plugin ${plugin.name} CLI command ${name} has invalid value options`);
|
|
26
31
|
}
|
|
27
32
|
}
|
|
28
33
|
function validate(plugin, source) {
|
|
@@ -62,14 +67,16 @@ async function importSpecifier(specifier, profileDir) {
|
|
|
62
67
|
* programmatically. A module's default export (or named `plugin` export) may
|
|
63
68
|
* be one plugin or an array of plugins.
|
|
64
69
|
*/
|
|
65
|
-
export async function loadPlugins(config, profileDir) {
|
|
70
|
+
export async function loadPlugins(config, profileDir, env = process.env) {
|
|
66
71
|
const plugins = [...registered];
|
|
67
72
|
for (const specifier of config.plugins) {
|
|
68
73
|
const module = await importSpecifier(specifier, profileDir);
|
|
69
74
|
if (!isRecord(module))
|
|
70
75
|
throw new Error(`Plugin ${specifier} did not load as a module`);
|
|
71
76
|
const exported = module.default ?? module.plugin;
|
|
72
|
-
|
|
77
|
+
const configured = isPluginFactory(exported)
|
|
78
|
+
? await exported({ config, profileDir, env }) : exported;
|
|
79
|
+
for (const item of Array.isArray(configured) ? configured : [configured]) {
|
|
73
80
|
const plugin = validate(item, specifier);
|
|
74
81
|
if (plugins.some(existing => existing.name === plugin.name))
|
|
75
82
|
throw new Error(`Duplicate plugin: ${plugin.name}`);
|
|
@@ -87,6 +94,7 @@ class ValidationContext {
|
|
|
87
94
|
config;
|
|
88
95
|
profileDir;
|
|
89
96
|
env;
|
|
97
|
+
runtimeAvailable = false;
|
|
90
98
|
defineTool = defineTool;
|
|
91
99
|
constructor(config, profileDir, env) {
|
|
92
100
|
this.config = config;
|
|
@@ -100,7 +108,40 @@ export function validationContext(config, profileDir, env) {
|
|
|
100
108
|
return new ValidationContext(config, profileDir, env);
|
|
101
109
|
}
|
|
102
110
|
export function pluginContext(runtime, env) {
|
|
103
|
-
return { runtime, config: runtime.config, profileDir: runtime.profileDir, env, tools: runtime.tools, defineTool };
|
|
111
|
+
return { runtimeAvailable: true, runtime, config: runtime.config, profileDir: runtime.profileDir, env, tools: runtime.tools, defineTool };
|
|
112
|
+
}
|
|
113
|
+
/** A codec cannot change authenticated identity, constraints, resources, or core actions. */
|
|
114
|
+
export function pluginTeamEnvelope(plugins, value) {
|
|
115
|
+
const raw = TeamEnvelope.extend({ mission: TeamMissionShape.extend({ allowed_actions: z.array(z.string()).min(1).max(8) }).passthrough() }).parse(value);
|
|
116
|
+
const candidates = plugins.flatMap(plugin => {
|
|
117
|
+
// Each codec gets a separate copy; neither the bindings nor another codec's
|
|
118
|
+
// input may change when a plugin normalizes its private wire vocabulary.
|
|
119
|
+
const envelope = plugin.teamEnvelope?.(structuredClone(raw));
|
|
120
|
+
return envelope === undefined ? [] : [{ plugin, envelope: TeamEnvelope.parse(envelope) }];
|
|
121
|
+
});
|
|
122
|
+
if (candidates.length > 1)
|
|
123
|
+
throw new Error('Multiple plugins claimed the team envelope');
|
|
124
|
+
const selected = candidates[0];
|
|
125
|
+
if (!selected) {
|
|
126
|
+
const envelope = TeamEnvelope.parse(raw);
|
|
127
|
+
if (envelope.mission.extensions && Object.keys(envelope.mission.extensions).length ||
|
|
128
|
+
envelope.mission.allowed_actions.some(action => action.startsWith('extension:')))
|
|
129
|
+
throw new Error('Team extension has no configured validator');
|
|
130
|
+
return envelope;
|
|
131
|
+
}
|
|
132
|
+
const canonical = selected.envelope;
|
|
133
|
+
const { allowed_actions: rawActions, extensions: _rawExtensions, ...rawMission } = raw.mission;
|
|
134
|
+
const { allowed_actions: actions, extensions, ...mission } = canonical.mission;
|
|
135
|
+
const bindings = ['id', 'revision', 'parent_task', 'constraints', 'resources', 'deadline', 'acceptance_criteria', 'expected_artifacts'];
|
|
136
|
+
if (canonical.version !== raw.version || canonical.caller !== raw.caller || canonical.task_id !== raw.task_id || canonical.objective !== raw.objective ||
|
|
137
|
+
bindings.some(key => JSON.stringify(mission[key]) !== JSON.stringify(rawMission[key])))
|
|
138
|
+
throw new Error('Plugin changed a team envelope binding');
|
|
139
|
+
if (extensions && Object.keys(extensions).some(key => key !== selected.plugin.name))
|
|
140
|
+
throw new Error('Plugin claimed another extension namespace');
|
|
141
|
+
if (actions.length !== rawActions.length || actions.some((action, index) => action.startsWith('extension:') && !action.startsWith(`extension:${selected.plugin.name}:`) ||
|
|
142
|
+
action !== rawActions[index] && action !== `extension:${selected.plugin.name}:${rawActions[index]}`))
|
|
143
|
+
throw new Error('Plugin changed a team action grant');
|
|
144
|
+
return canonical;
|
|
104
145
|
}
|
|
105
146
|
/** Merge plugin job handlers into a base registry; a duplicate handler ID is an error. */
|
|
106
147
|
export function pluginJobHandlers(plugins, ctx, base = {}) {
|
|
@@ -113,3 +154,49 @@ export function pluginJobHandlers(plugins, ctx, base = {}) {
|
|
|
113
154
|
}
|
|
114
155
|
return registry;
|
|
115
156
|
}
|
|
157
|
+
export function pluginChannelAdapter(plugins, ctx, channel, jobs) {
|
|
158
|
+
const adapters = plugins.flatMap(plugin => {
|
|
159
|
+
const adapter = plugin.channelAdapter?.(ctx, channel, jobs);
|
|
160
|
+
if (adapter !== undefined && typeof adapter.run !== 'function')
|
|
161
|
+
throw new Error(`Plugin ${plugin.name} returned an invalid channel adapter`);
|
|
162
|
+
return adapter ? [adapter] : [];
|
|
163
|
+
});
|
|
164
|
+
if (adapters.length > 1)
|
|
165
|
+
throw new Error(`Multiple plugins own the ${channel} consumer`);
|
|
166
|
+
return adapters[0];
|
|
167
|
+
}
|
|
168
|
+
/** Task additions cannot bypass context, preview effect, peer grant or restrictive filters. */
|
|
169
|
+
export function pluginTaskTools(plugins, ctx) {
|
|
170
|
+
if (ctx.task.context === 'mission' && !ctx.envelope)
|
|
171
|
+
throw new Error('Mission task has no recorded mission');
|
|
172
|
+
const tools = new Map(ctx.baseTools.map(tool => [tool.name, tool]));
|
|
173
|
+
for (const plugin of plugins) {
|
|
174
|
+
const additions = plugin.taskTools?.(ctx) ?? [];
|
|
175
|
+
const raw = additions;
|
|
176
|
+
if (!Array.isArray(raw))
|
|
177
|
+
throw new Error(`Plugin ${plugin.name} taskTools must return an array`);
|
|
178
|
+
for (const tool of additions) {
|
|
179
|
+
if (!tool || typeof tool.name !== 'string' || !/^[A-Za-z0-9_-]{1,100}$/.test(tool.name) ||
|
|
180
|
+
!['read', 'artifact-write', 'memory-write', 'external-write'].includes(tool.effect) ||
|
|
181
|
+
!Array.isArray(tool.contexts) || !tool.contexts.every((context) => typeof context === 'string' && ['direct', 'peer', 'scheduled', 'mission', 'preview'].includes(context)) ||
|
|
182
|
+
!Number.isSafeInteger(tool.timeoutMs) || tool.timeoutMs < 1 || typeof tool.invoke !== 'function' ||
|
|
183
|
+
typeof tool.input?.safeParse !== 'function' || typeof tool.output?.parse !== 'function')
|
|
184
|
+
throw new Error(`Plugin ${plugin.name} returned an invalid task tool`);
|
|
185
|
+
if (!tool.contexts.includes(ctx.task.context) || (ctx.task.context === 'preview' && tool.effect !== 'read'))
|
|
186
|
+
continue;
|
|
187
|
+
if (ctx.task.context === 'peer' || ctx.task.context === 'mission') {
|
|
188
|
+
if (!ctx.envelope?.mission.resources.includes(`tool:${tool.name}`) && plugin.peerTool?.(tool, ctx.task, ctx.envelope) !== true)
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
const prior = tools.get(tool.name);
|
|
192
|
+
if (prior && prior !== tool)
|
|
193
|
+
throw new Error(`Duplicate task tool: ${tool.name}`);
|
|
194
|
+
tools.set(tool.name, tool);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
const registry = new ToolRegistry();
|
|
198
|
+
for (const tool of tools.values())
|
|
199
|
+
if (plugins.every(plugin => plugin.filterTool?.(ctx, tool) !== false))
|
|
200
|
+
registry.register(tool);
|
|
201
|
+
return registry;
|
|
202
|
+
}
|
package/dist/runtime.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { ArtifactStore } from './artifacts.js';
|
|
|
3
3
|
import { type ResearchBrief } from './research.js';
|
|
4
4
|
import { TaskStore, type Task, type TaskContext } from './store.js';
|
|
5
5
|
import { ToolRegistry } from './tools.js';
|
|
6
|
-
import { TeamResult } from './team-contract.js';
|
|
6
|
+
import { TeamEnvelope, TeamResult } from './team-contract.js';
|
|
7
7
|
import { type ArdentPlugin } from './plugins.js';
|
|
8
8
|
import { LiveTextHub } from './live-text.js';
|
|
9
9
|
import { ArtifactManifests } from './artifact-manifests.js';
|
|
@@ -17,6 +17,20 @@ export type RunResult = {
|
|
|
17
17
|
brief?: ResearchBrief;
|
|
18
18
|
team_result?: TeamResult;
|
|
19
19
|
};
|
|
20
|
+
type SourceEvidence = {
|
|
21
|
+
url: string;
|
|
22
|
+
extracted: boolean;
|
|
23
|
+
title: string;
|
|
24
|
+
published_at: string | null;
|
|
25
|
+
retrieved_at: string | null;
|
|
26
|
+
content_sha256: string | null;
|
|
27
|
+
};
|
|
28
|
+
export type TaskEvidence = {
|
|
29
|
+
sourceIds: Set<string>;
|
|
30
|
+
sources: Map<string, SourceEvidence>;
|
|
31
|
+
artifactIds: Set<string>;
|
|
32
|
+
researchAttempted: boolean;
|
|
33
|
+
};
|
|
20
34
|
export declare class ArdentRuntime {
|
|
21
35
|
#private;
|
|
22
36
|
readonly profileDir: string;
|
|
@@ -39,6 +53,8 @@ export declare class ArdentRuntime {
|
|
|
39
53
|
constructor(profileDir: string, config: ArdentConfig, env?: NodeJS.ProcessEnv);
|
|
40
54
|
/** Install plugins once, before the runtime accepts work. Plugin tools join the shared registry. */
|
|
41
55
|
usePlugins(plugins: readonly ArdentPlugin[], env?: NodeJS.ProcessEnv): Promise<void>;
|
|
56
|
+
prepareGateway(env?: NodeJS.ProcessEnv): Promise<void>;
|
|
57
|
+
startPlugins(env?: NodeJS.ProcessEnv): Promise<void>;
|
|
42
58
|
close(): void;
|
|
43
59
|
drain(timeoutMs?: number): Promise<boolean>;
|
|
44
60
|
accept(prompt: string, caller?: string, context?: TaskContext, idempotencyKey?: string, sessionId?: string, originalDeadlineMs?: number, backendOverride?: 'llamacpp' | 'codex'): Task;
|
|
@@ -66,4 +82,7 @@ export declare class ArdentRuntime {
|
|
|
66
82
|
admission: 'open' | 'paused';
|
|
67
83
|
};
|
|
68
84
|
run(taskId: string, env?: NodeJS.ProcessEnv, onText?: (chunk: string, step: number) => void): Promise<RunResult>;
|
|
85
|
+
decodeTeamEnvelope(value: unknown): TeamEnvelope;
|
|
86
|
+
assertTeamEnvelopeAdmission(envelope: TeamEnvelope, wire: unknown, env: NodeJS.ProcessEnv): void;
|
|
69
87
|
}
|
|
88
|
+
export {};
|