@hivemagnus/ardent 3.2.1 → 3.4.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 +15 -923
- package/dist/a2a-client.js +3 -2
- package/dist/a2a-peers.d.ts +26 -0
- package/dist/a2a-peers.js +60 -18
- package/dist/a2a-push.d.ts +3 -1
- package/dist/a2a-push.js +5 -1
- package/dist/a2a-rate-limit.d.ts +3 -3
- package/dist/a2a-rate-limit.js +6 -3
- package/dist/a2a-server.d.ts +13 -1
- package/dist/a2a-server.js +20 -11
- package/dist/api.d.ts +12 -0
- package/dist/api.js +312 -131
- package/dist/artifact-transfer.js +3 -2
- package/dist/channel-catchup.d.ts +2 -2
- package/dist/channels.d.ts +6 -6
- package/dist/channels.js +4 -1
- package/dist/cli.js +106 -8
- package/dist/config.d.ts +9 -1
- package/dist/config.js +15 -6
- package/dist/development.d.ts +3 -3
- package/dist/development.js +2 -1
- package/dist/errors.d.ts +54 -0
- package/dist/errors.js +76 -0
- package/dist/identity.js +11 -6
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/job-engine.d.ts +3 -0
- package/dist/job-engine.js +5 -0
- package/dist/journal.d.ts +90 -0
- package/dist/journal.js +395 -0
- package/dist/log.d.ts +11 -0
- package/dist/log.js +12 -0
- package/dist/mattermost.js +7 -2
- package/dist/memory.js +3 -2
- package/dist/metrics.d.ts +34 -0
- package/dist/metrics.js +73 -0
- package/dist/missions.js +2 -1
- package/dist/plugin-http.js +10 -1
- package/dist/plugin-sdk.d.ts +2 -0
- package/dist/plugin-sdk.js +2 -0
- package/dist/retention.d.ts +64 -0
- package/dist/retention.js +239 -0
- package/dist/runtime.d.ts +17 -1
- package/dist/runtime.js +52 -15
- package/dist/skills.js +5 -4
- package/dist/store.d.ts +42 -0
- package/dist/store.js +114 -14
- package/dist/telegram.js +5 -1
- package/package.json +8 -4
- package/profiles/assistant/config.yaml +1 -1
- package/dist/codex-output-budget.test.d.ts +0 -1
- package/dist/codex-output-budget.test.js +0 -29
package/dist/a2a-client.js
CHANGED
|
@@ -8,6 +8,7 @@ import { z } from 'zod';
|
|
|
8
8
|
import { parseExecutionContext } from '@hivemagnus/hive-common/execution';
|
|
9
9
|
import { EXECUTION_METADATA_KEY } from './execution.js';
|
|
10
10
|
import { isTransportError, lastAttemptError, responseFailure, retryWithPolicy } from './retry.js';
|
|
11
|
+
import { dependencyUnavailable, notFound } from './errors.js';
|
|
11
12
|
/**
|
|
12
13
|
* What the last HTTP exchange of one A2A call looked like. The SDK reports failures as plain
|
|
13
14
|
* errors, so the fetch wrapper records the status, `Retry-After` and `x-hive-retry` it saw.
|
|
@@ -80,10 +81,10 @@ export class ArdentA2AClient {
|
|
|
80
81
|
const { peers } = await loadPeers(this.profileDir, this.config, this.env);
|
|
81
82
|
const peer = peers.find(item => item.id === peerId && item.enabled);
|
|
82
83
|
if (!peer)
|
|
83
|
-
throw
|
|
84
|
+
throw notFound(`A2A peer is not configured: ${peerId}`);
|
|
84
85
|
const token = this.env[outboundTokenEnv(peer)];
|
|
85
86
|
if (!token)
|
|
86
|
-
throw
|
|
87
|
+
throw dependencyUnavailable(`A2A outbound credential is missing: ${outboundTokenEnv(peer)}`);
|
|
87
88
|
const base = new URL(peer.url);
|
|
88
89
|
const basePort = Number(base.port || (base.protocol === 'https:' ? 443 : 80));
|
|
89
90
|
const allowedPorts = new Set([basePort, ...peer.transport_ports]);
|
package/dist/a2a-peers.d.ts
CHANGED
|
@@ -21,8 +21,34 @@ export declare function readPeersConfig(profileDir: string, config: ArdentConfig
|
|
|
21
21
|
}>;
|
|
22
22
|
export declare function savePeersConfig(profileDir: string, config: ArdentConfig, text: string, expectedRevision: string): Promise<string>;
|
|
23
23
|
export declare function listPeers(profileDir: string, config: ArdentConfig): Promise<PeerConfig[]>;
|
|
24
|
+
type PeerCredential = {
|
|
25
|
+
id: string;
|
|
26
|
+
token: Buffer;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Inbound peer authentication whose credentials can be replaced while the
|
|
30
|
+
* gateway runs. After a reload a peer's previous inbound token is still
|
|
31
|
+
* accepted until its overlap window ends, so a peer can switch at its own pace.
|
|
32
|
+
*/
|
|
33
|
+
export declare class PeerAuthenticator {
|
|
34
|
+
#private;
|
|
35
|
+
readonly peers: readonly PeerConfig[];
|
|
36
|
+
readonly now: () => number;
|
|
37
|
+
constructor(peers: readonly PeerConfig[], credentials: PeerCredential[], now?: () => number);
|
|
38
|
+
/** The peer whose `Bearer` token this is (scheme case-insensitive), or undefined. */
|
|
39
|
+
authenticate(authorization: string | undefined): string | undefined;
|
|
40
|
+
/**
|
|
41
|
+
* Replace the credentials with those `env` holds for the same peers. Throws,
|
|
42
|
+
* changing nothing, when they are not valid. Returns the peers whose inbound
|
|
43
|
+
* token changed; their previous token stays valid for `overlapMs`.
|
|
44
|
+
*/
|
|
45
|
+
reload(env: NodeJS.ProcessEnv, overlapMs: number): {
|
|
46
|
+
changed: string[];
|
|
47
|
+
};
|
|
48
|
+
}
|
|
24
49
|
export declare function loadPeers(profileDir: string, config: ArdentConfig, env?: NodeJS.ProcessEnv): Promise<{
|
|
25
50
|
peers: PeerConfig[];
|
|
26
51
|
authenticate: (authorization: string | undefined) => string | undefined;
|
|
52
|
+
authenticator: PeerAuthenticator;
|
|
27
53
|
}>;
|
|
28
54
|
export {};
|
package/dist/a2a-peers.js
CHANGED
|
@@ -4,6 +4,8 @@ import { join } from 'node:path';
|
|
|
4
4
|
import YAML from 'yaml';
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
import { revision } from './config.js';
|
|
7
|
+
import { conflict, invalidRequest } from './errors.js';
|
|
8
|
+
import { readBearerToken } from '@hivemagnus/hive-common/secrets';
|
|
7
9
|
const envName = z.string().regex(/^[A-Z][A-Z0-9_]*$/);
|
|
8
10
|
const Peer = z.object({ id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/), url: z.string().url(),
|
|
9
11
|
token_env: envName.optional(), inbound_token_env: envName.optional(), outbound_token_env: envName.optional(),
|
|
@@ -23,14 +25,14 @@ export function outboundTokenEnv(peer) { return peer.outbound_token_env ?? peer.
|
|
|
23
25
|
export function parsePeersConfig(text) {
|
|
24
26
|
const document = YAML.parseDocument(text, { uniqueKeys: true });
|
|
25
27
|
if (document.errors.length)
|
|
26
|
-
throw
|
|
28
|
+
throw invalidRequest(`Invalid peer YAML: ${document.errors[0]?.message ?? 'unknown error'}`);
|
|
27
29
|
const peers = Peers.parse(document.toJS()).peers;
|
|
28
30
|
if (new Set(peers.map(peer => peer.id)).size !== peers.length)
|
|
29
|
-
throw
|
|
31
|
+
throw invalidRequest('Duplicate A2A peer ID');
|
|
30
32
|
for (const peer of peers) {
|
|
31
33
|
const url = new URL(peer.url);
|
|
32
34
|
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.hash || url.search)
|
|
33
|
-
throw
|
|
35
|
+
throw invalidRequest(`Invalid A2A peer URL: ${peer.id}`);
|
|
34
36
|
}
|
|
35
37
|
return peers;
|
|
36
38
|
}
|
|
@@ -41,19 +43,19 @@ export async function readPeersConfig(profileDir, config) {
|
|
|
41
43
|
}
|
|
42
44
|
export async function savePeersConfig(profileDir, config, text, expectedRevision) {
|
|
43
45
|
if (Buffer.byteLength(text) > 200_000)
|
|
44
|
-
throw
|
|
46
|
+
throw invalidRequest('Peer configuration exceeds size limit');
|
|
45
47
|
parsePeersConfig(text);
|
|
46
48
|
const lockPath = join(profileDir, '.peers.write.lock');
|
|
47
49
|
const lock = await open(lockPath, 'wx', 0o600).catch((error) => {
|
|
48
50
|
if (error && typeof error === 'object' && 'code' in error && error.code === 'EEXIST')
|
|
49
|
-
throw
|
|
51
|
+
throw conflict('Peer configuration edit is already in progress');
|
|
50
52
|
throw error;
|
|
51
53
|
});
|
|
52
54
|
let temporary;
|
|
53
55
|
try {
|
|
54
56
|
const current = await readPeersConfig(profileDir, config);
|
|
55
57
|
if (current.revision !== expectedRevision)
|
|
56
|
-
throw
|
|
58
|
+
throw conflict('Peer configuration revision conflict');
|
|
57
59
|
temporary = join(profileDir, `.peers.${randomUUID()}.tmp`);
|
|
58
60
|
await writeFile(temporary, text, { flag: 'wx', mode: 0o600 });
|
|
59
61
|
await rename(temporary, join(profileDir, config.a2a.peers_file));
|
|
@@ -70,8 +72,8 @@ export async function savePeersConfig(profileDir, config, text, expectedRevision
|
|
|
70
72
|
export async function listPeers(profileDir, config) {
|
|
71
73
|
return parsePeersConfig(await readFile(join(profileDir, config.a2a.peers_file), 'utf8'));
|
|
72
74
|
}
|
|
73
|
-
|
|
74
|
-
|
|
75
|
+
/** Validate every enabled peer's credentials in `env` and return their inbound tokens. */
|
|
76
|
+
function peerCredentials(peers, env) {
|
|
75
77
|
const seen = new Set();
|
|
76
78
|
const credentials = [];
|
|
77
79
|
for (const peer of peers) {
|
|
@@ -82,7 +84,7 @@ export async function loadPeers(profileDir, config, env = process.env) {
|
|
|
82
84
|
continue;
|
|
83
85
|
const url = new URL(peer.url);
|
|
84
86
|
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.hash)
|
|
85
|
-
throw
|
|
87
|
+
throw invalidRequest(`Invalid A2A peer URL: ${peer.id}`);
|
|
86
88
|
const inbound = env[inboundTokenEnv(peer)];
|
|
87
89
|
const outbound = env[outboundTokenEnv(peer)];
|
|
88
90
|
if (!inbound || inbound.length < 16)
|
|
@@ -95,14 +97,54 @@ export async function loadPeers(profileDir, config, env = process.env) {
|
|
|
95
97
|
throw new Error(`A2A inbound credential is assigned to multiple peers: ${peer.id}`);
|
|
96
98
|
credentials.push({ id: peer.id, token: Buffer.from(inbound) });
|
|
97
99
|
}
|
|
98
|
-
return
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
100
|
+
return credentials;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Inbound peer authentication whose credentials can be replaced while the
|
|
104
|
+
* gateway runs. After a reload a peer's previous inbound token is still
|
|
105
|
+
* accepted until its overlap window ends, so a peer can switch at its own pace.
|
|
106
|
+
*/
|
|
107
|
+
export class PeerAuthenticator {
|
|
108
|
+
peers;
|
|
109
|
+
now;
|
|
110
|
+
#current;
|
|
111
|
+
#previous = [];
|
|
112
|
+
constructor(peers, credentials, now = () => Date.now()) {
|
|
113
|
+
this.peers = peers;
|
|
114
|
+
this.now = now;
|
|
115
|
+
this.#current = credentials;
|
|
116
|
+
}
|
|
117
|
+
/** The peer whose `Bearer` token this is (scheme case-insensitive), or undefined. */
|
|
118
|
+
authenticate(authorization) {
|
|
119
|
+
const bearer = readBearerToken(authorization);
|
|
120
|
+
if (!bearer)
|
|
106
121
|
return undefined;
|
|
107
|
-
|
|
122
|
+
const candidate = Buffer.from(bearer);
|
|
123
|
+
const match = (entry) => entry.token.length === candidate.length && timingSafeEqual(entry.token, candidate);
|
|
124
|
+
const current = this.#current.find(match);
|
|
125
|
+
if (current)
|
|
126
|
+
return current.id;
|
|
127
|
+
const now = this.now();
|
|
128
|
+
this.#previous = this.#previous.filter(entry => entry.until > now);
|
|
129
|
+
return this.#previous.find(match)?.id;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Replace the credentials with those `env` holds for the same peers. Throws,
|
|
133
|
+
* changing nothing, when they are not valid. Returns the peers whose inbound
|
|
134
|
+
* token changed; their previous token stays valid for `overlapMs`.
|
|
135
|
+
*/
|
|
136
|
+
reload(env, overlapMs) {
|
|
137
|
+
const next = peerCredentials(this.peers, env);
|
|
138
|
+
const now = this.now();
|
|
139
|
+
const changed = next.filter(entry => { const prior = this.#current.find(item => item.id === entry.id); return !prior || !prior.token.equals(entry.token); }).map(entry => entry.id);
|
|
140
|
+
const retired = this.#current.filter(entry => !next.some(item => item.id === entry.id && item.token.equals(entry.token)));
|
|
141
|
+
this.#previous = [...this.#previous.filter(entry => entry.until > now), ...(overlapMs > 0 ? retired.map(entry => ({ ...entry, until: now + overlapMs })) : [])];
|
|
142
|
+
this.#current = next;
|
|
143
|
+
return { changed };
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
export async function loadPeers(profileDir, config, env = process.env) {
|
|
147
|
+
const peers = await listPeers(profileDir, config);
|
|
148
|
+
const authenticator = new PeerAuthenticator(peers, peerCredentials(peers, env));
|
|
149
|
+
return { peers, authenticate: authorization => authenticator.authenticate(authorization), authenticator };
|
|
108
150
|
}
|
package/dist/a2a-push.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type Database from './sqlite.js';
|
|
|
2
2
|
import { type StreamResponse, type Task, type TaskPushNotificationConfig } from '@a2a-js/sdk';
|
|
3
3
|
import type { PushNotificationSender, PushNotificationStore, ServerCallContext, StoredPushNotificationConfig } from '@a2a-js/sdk/server';
|
|
4
4
|
import type { PeerConfig } from './a2a-peers.js';
|
|
5
|
+
import { type Logger } from './log.js';
|
|
5
6
|
export declare class SqliteA2APushStore implements PushNotificationStore {
|
|
6
7
|
readonly db: Database;
|
|
7
8
|
readonly peers: PeerConfig[];
|
|
@@ -21,7 +22,8 @@ export declare class SafeA2APushSender implements PushNotificationSender {
|
|
|
21
22
|
#private;
|
|
22
23
|
readonly store: SqliteA2APushStore;
|
|
23
24
|
readonly beforeDelivery?: ((taskId: string) => void) | undefined;
|
|
24
|
-
|
|
25
|
+
readonly logger: Logger;
|
|
26
|
+
constructor(store: SqliteA2APushStore, beforeDelivery?: ((taskId: string) => void) | undefined, logger?: Logger);
|
|
25
27
|
drain(): Promise<void>;
|
|
26
28
|
send(event: StreamResponse, context: ServerCallContext, _task?: Task): Promise<void>;
|
|
27
29
|
}
|
package/dist/a2a-push.js
CHANGED
|
@@ -4,6 +4,7 @@ import { StreamResponse as StreamCodec, TaskPushNotificationConfig as PushCodec
|
|
|
4
4
|
import { RequestMalformedError } from '@a2a-js/sdk/errors';
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
import { AttemptError, lastAttemptError, responseFailure, retryWithPolicy } from './retry.js';
|
|
7
|
+
import { silentLogger } from './log.js';
|
|
7
8
|
const Row = z.object({ config_json: z.string(), wire_version: z.string() });
|
|
8
9
|
const Delivery = z.object({ state: z.enum(['queued', 'sent', 'failed', 'unknown']) });
|
|
9
10
|
function scope(context) {
|
|
@@ -119,10 +120,12 @@ export class DeliveryVetoError extends Error {
|
|
|
119
120
|
export class SafeA2APushSender {
|
|
120
121
|
store;
|
|
121
122
|
beforeDelivery;
|
|
123
|
+
logger;
|
|
122
124
|
#chains = new Map();
|
|
123
|
-
constructor(store, beforeDelivery) {
|
|
125
|
+
constructor(store, beforeDelivery, logger = silentLogger) {
|
|
124
126
|
this.store = store;
|
|
125
127
|
this.beforeDelivery = beforeDelivery;
|
|
128
|
+
this.logger = logger;
|
|
126
129
|
}
|
|
127
130
|
async drain() {
|
|
128
131
|
for (let pass = 0; pass < 3; pass++) {
|
|
@@ -177,6 +180,7 @@ export class SafeA2APushSender {
|
|
|
177
180
|
}
|
|
178
181
|
catch (raw) {
|
|
179
182
|
const error = lastAttemptError(raw);
|
|
183
|
+
this.logger.warn('A2A push delivery failed', { task_id: taskId, delivery_id: id, attempts, ...(error instanceof AttemptError && error.failure.status !== undefined ? { http_status: error.failure.status } : {}), err: error });
|
|
180
184
|
if (error instanceof AttemptError && error.failure.status !== undefined)
|
|
181
185
|
this.store.setDelivery(id, error.failure.status >= 500 ? 'unknown' : 'failed', error.failure.status, undefined, attempts);
|
|
182
186
|
else
|
package/dist/a2a-rate-limit.d.ts
CHANGED
|
@@ -21,7 +21,7 @@ export declare class TokenBucketLimiter {
|
|
|
21
21
|
/** One bucket per client: an IPv4-mapped address is its IPv4 address, and IPv6 clients share a /64. */
|
|
22
22
|
export declare function clientKey(address: string | undefined): string;
|
|
23
23
|
export declare function tooManyRequests(res: Response, retryAfterSeconds: number, error?: string): void;
|
|
24
|
-
export declare function limitRequests(limiter: TokenBucketLimiter, key: (req: Request, res: Response) => string): RequestHandler;
|
|
24
|
+
export declare function limitRequests(limiter: TokenBucketLimiter, key: (req: Request, res: Response) => string, onRefuse?: () => void): RequestHandler;
|
|
25
25
|
/** Admitted peer tasks, from before the SDK creates the task until the executor settles it. */
|
|
26
26
|
export declare class PeerTaskGate {
|
|
27
27
|
#private;
|
|
@@ -47,6 +47,6 @@ export declare const TASK_CAP_RETRY_SECONDS = 5;
|
|
|
47
47
|
* application error. The handler still enforces the cap atomically and for gRPC.
|
|
48
48
|
* Team control messages stay allowed so a peer at its cap can still cancel work.
|
|
49
49
|
*/
|
|
50
|
-
export declare function jsonRpcTaskCap(gate: PeerTaskGate, peerOf: (res: Response) => string): RequestHandler;
|
|
50
|
+
export declare function jsonRpcTaskCap(gate: PeerTaskGate, peerOf: (res: Response) => string, onRefuse?: () => void): RequestHandler;
|
|
51
51
|
/** The REST body is not parsed yet here; cancel has its own route and stays available. */
|
|
52
|
-
export declare function restTaskCap(gate: PeerTaskGate, peerOf: (res: Response) => string): RequestHandler;
|
|
52
|
+
export declare function restTaskCap(gate: PeerTaskGate, peerOf: (res: Response) => string, onRefuse?: () => void): RequestHandler;
|
package/dist/a2a-rate-limit.js
CHANGED
|
@@ -50,13 +50,14 @@ export function clientKey(address) {
|
|
|
50
50
|
export function tooManyRequests(res, retryAfterSeconds, error = 'Too many A2A requests') {
|
|
51
51
|
res.status(429).set({ 'Retry-After': String(retryAfterSeconds), 'Cache-Control': 'no-store' }).json({ error });
|
|
52
52
|
}
|
|
53
|
-
export function limitRequests(limiter, key) {
|
|
53
|
+
export function limitRequests(limiter, key, onRefuse) {
|
|
54
54
|
return (req, res, next) => {
|
|
55
55
|
const result = limiter.take(key(req, res));
|
|
56
56
|
if (result.allowed) {
|
|
57
57
|
next();
|
|
58
58
|
return;
|
|
59
59
|
}
|
|
60
|
+
onRefuse?.();
|
|
60
61
|
tooManyRequests(res, result.retryAfterSeconds);
|
|
61
62
|
};
|
|
62
63
|
}
|
|
@@ -114,10 +115,11 @@ export const TASK_CAP_RETRY_SECONDS = 5;
|
|
|
114
115
|
* application error. The handler still enforces the cap atomically and for gRPC.
|
|
115
116
|
* Team control messages stay allowed so a peer at its cap can still cancel work.
|
|
116
117
|
*/
|
|
117
|
-
export function jsonRpcTaskCap(gate, peerOf) {
|
|
118
|
+
export function jsonRpcTaskCap(gate, peerOf, onRefuse) {
|
|
118
119
|
return (req, res, next) => {
|
|
119
120
|
const rpc = SendRpc.safeParse(req.body);
|
|
120
121
|
if (rpc.success && SEND_METHODS.has(rpc.data.method) && !('hermesTeamControl' in (rpc.data.params?.message?.metadata ?? {})) && gate.isFull(peerOf(res))) {
|
|
122
|
+
onRefuse?.();
|
|
121
123
|
tooManyRequests(res, TASK_CAP_RETRY_SECONDS, 'Peer task limit reached');
|
|
122
124
|
return;
|
|
123
125
|
}
|
|
@@ -125,9 +127,10 @@ export function jsonRpcTaskCap(gate, peerOf) {
|
|
|
125
127
|
};
|
|
126
128
|
}
|
|
127
129
|
/** The REST body is not parsed yet here; cancel has its own route and stays available. */
|
|
128
|
-
export function restTaskCap(gate, peerOf) {
|
|
130
|
+
export function restTaskCap(gate, peerOf, onRefuse) {
|
|
129
131
|
return (req, res, next) => {
|
|
130
132
|
if (req.method === 'POST' && /\/message:(?:send|stream)$/.test(req.path) && gate.isFull(peerOf(res))) {
|
|
133
|
+
onRefuse?.();
|
|
131
134
|
tooManyRequests(res, TASK_CAP_RETRY_SECONDS, 'Peer task limit reached');
|
|
132
135
|
return;
|
|
133
136
|
}
|
package/dist/a2a-server.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { type Express } from 'express';
|
|
|
2
2
|
import { Server as GrpcServer } from '@grpc/grpc-js';
|
|
3
3
|
import { AgentCard } from '@a2a-js/sdk';
|
|
4
4
|
import type { ArdentConfig } from './config.js';
|
|
5
|
+
import { type PeerAuthenticator } from './a2a-peers.js';
|
|
5
6
|
import { SafeA2APushSender } from './a2a-push.js';
|
|
6
7
|
import { A2APushInbox } from './a2a-push-inbox.js';
|
|
7
8
|
import type { ArdentRuntime } from './runtime.js';
|
|
@@ -9,6 +10,15 @@ import { hermesTeamCard } from './hermes-compat.js';
|
|
|
9
10
|
import { IdempotentA2AHandler } from './a2a-idempotency.js';
|
|
10
11
|
import { PeerTaskGate, TokenBucketLimiter } from './a2a-rate-limit.js';
|
|
11
12
|
/** The transfer-v2 capability this runtime advertises on its Agent Card. */
|
|
13
|
+
/** The Agent Card provider: `a2a.provider`, else Ardent itself. */
|
|
14
|
+
export declare const DEFAULT_AGENT_CARD_PROVIDER: {
|
|
15
|
+
readonly organization: "Ardent";
|
|
16
|
+
readonly url: "https://github.com/ChefTaco/Ardent";
|
|
17
|
+
};
|
|
18
|
+
export declare function agentCardProvider(config: ArdentConfig): {
|
|
19
|
+
organization: string;
|
|
20
|
+
url: string;
|
|
21
|
+
};
|
|
12
22
|
export declare function artifactTransferExtension(maxBytes: number): {
|
|
13
23
|
uri: string;
|
|
14
24
|
description: string;
|
|
@@ -35,6 +45,8 @@ export type A2ASurface = {
|
|
|
35
45
|
handler: IdempotentA2AHandler;
|
|
36
46
|
taskGate: PeerTaskGate;
|
|
37
47
|
recovery: A2ARecoveryPublisher;
|
|
48
|
+
/** Inbound peer authentication; `POST /api/v1/credentials/peers/reload` replaces its credentials. */
|
|
49
|
+
peerAuthenticator: PeerAuthenticator;
|
|
38
50
|
};
|
|
39
51
|
/** Refresh only discovery freshness; the reviewed runtime identity and digests stay pinned to this process. */
|
|
40
52
|
export declare function freshHermesTeamCard(source: Awaited<ReturnType<typeof hermesTeamCard>>, now?: number): {
|
|
@@ -55,7 +67,7 @@ export declare function freshHermesTeamCard(source: Awaited<ReturnType<typeof he
|
|
|
55
67
|
}>;
|
|
56
68
|
};
|
|
57
69
|
/** gRPC bypasses Express, so its authenticated calls spend the same per-peer tokens here. */
|
|
58
|
-
export declare function limitedGrpcUser(peer: string | undefined, bucket: TokenBucketLimiter | undefined): {
|
|
70
|
+
export declare function limitedGrpcUser(peer: string | undefined, bucket: TokenBucketLimiter | undefined, onRefuse?: () => void): {
|
|
59
71
|
isAuthenticated: boolean;
|
|
60
72
|
userName: string;
|
|
61
73
|
};
|
package/dist/a2a-server.js
CHANGED
|
@@ -20,6 +20,11 @@ import { TeamArtifacts } from './team-artifacts.js';
|
|
|
20
20
|
import { pipeline } from 'node:stream/promises';
|
|
21
21
|
import { ARTIFACT_TRANSFER_V2_URN, formatReprDigest, parseByteRange } from '@hivemagnus/hive-common/artifact';
|
|
22
22
|
/** The transfer-v2 capability this runtime advertises on its Agent Card. */
|
|
23
|
+
/** The Agent Card provider: `a2a.provider`, else Ardent itself. */
|
|
24
|
+
export const DEFAULT_AGENT_CARD_PROVIDER = { organization: 'Ardent', url: 'https://github.com/ChefTaco/Ardent' };
|
|
25
|
+
export function agentCardProvider(config) {
|
|
26
|
+
return config.a2a.provider ?? { ...DEFAULT_AGENT_CARD_PROVIDER };
|
|
27
|
+
}
|
|
23
28
|
export function artifactTransferExtension(maxBytes) {
|
|
24
29
|
return { uri: ARTIFACT_TRANSFER_V2_URN, description: 'Resumable artifact transfer over HTTP Range with SHA-256 verification and renditions',
|
|
25
30
|
required: false, params: { max_bytes: maxBytes, range: true, renditions: true } };
|
|
@@ -35,9 +40,11 @@ export function freshHermesTeamCard(source, now = Date.now()) {
|
|
|
35
40
|
discovery: { ...team.discovery, observedAt, expiresAt: observedAt + 300 } } } };
|
|
36
41
|
}
|
|
37
42
|
/** gRPC bypasses Express, so its authenticated calls spend the same per-peer tokens here. */
|
|
38
|
-
export function limitedGrpcUser(peer, bucket) {
|
|
39
|
-
if (peer && bucket && !bucket.take(peer).allowed)
|
|
43
|
+
export function limitedGrpcUser(peer, bucket, onRefuse) {
|
|
44
|
+
if (peer && bucket && !bucket.take(peer).allowed) {
|
|
45
|
+
onRefuse?.();
|
|
40
46
|
throw new Error('Too many A2A requests');
|
|
47
|
+
}
|
|
41
48
|
return { isAuthenticated: Boolean(peer), userName: peer ?? '' };
|
|
42
49
|
}
|
|
43
50
|
export async function createA2ASurface(runtime, config, env = process.env) {
|
|
@@ -47,7 +54,7 @@ export async function createA2ASurface(runtime, config, env = process.env) {
|
|
|
47
54
|
const publicUrl = new URL(publicAddress);
|
|
48
55
|
if (!['http:', 'https:'].includes(publicUrl.protocol) || publicUrl.username || publicUrl.password)
|
|
49
56
|
throw new Error('Invalid A2A public URL');
|
|
50
|
-
const { authenticate, peers } = await loadPeers(runtime.profileDir, config, env);
|
|
57
|
+
const { authenticate, peers, authenticator: peerAuthenticator } = await loadPeers(runtime.profileDir, config, env);
|
|
51
58
|
const teamCard = config.a2a.hermes_compat ? await hermesTeamCard(runtime, config, env) : undefined;
|
|
52
59
|
const grpcPort = Number(publicUrl.port || (publicUrl.protocol === 'https:' ? 443 : 80)) + 1;
|
|
53
60
|
if (grpcPort > 65535)
|
|
@@ -76,7 +83,7 @@ export async function createA2ASurface(runtime, config, env = process.env) {
|
|
|
76
83
|
name: config.name,
|
|
77
84
|
description: teamCard?.description ?? skill.description,
|
|
78
85
|
supportedInterfaces: interfaces,
|
|
79
|
-
provider:
|
|
86
|
+
provider: agentCardProvider(config),
|
|
80
87
|
version: ARDENT_VERSION,
|
|
81
88
|
capabilities: { streaming: true, pushNotifications: true, extendedAgentCard: true, extensions: [artifactTransferExtension(config.artifacts.max_bytes)] },
|
|
82
89
|
securitySchemes: { Bearer: { scheme: { $case: 'httpAuthSecurityScheme', value: { description: 'Peer bearer token', scheme: 'bearer', bearerFormat: '' } } } },
|
|
@@ -87,7 +94,7 @@ export async function createA2ASurface(runtime, config, env = process.env) {
|
|
|
87
94
|
documentationUrl: '', signatures: []
|
|
88
95
|
};
|
|
89
96
|
const pushStore = new SqliteA2APushStore(runtime.store.db, peers);
|
|
90
|
-
const pushSender = new SafeA2APushSender(pushStore);
|
|
97
|
+
const pushSender = new SafeA2APushSender(pushStore, undefined, runtime.logger);
|
|
91
98
|
const pushInbox = new A2APushInbox(runtime.store.db, peers, publicAddress);
|
|
92
99
|
const artifactTransfers = new TeamArtifacts(runtime, config, env);
|
|
93
100
|
const taskStore = new SqliteA2ATaskStore(runtime.store.db);
|
|
@@ -134,7 +141,9 @@ export async function createA2ASurface(runtime, config, env = process.env) {
|
|
|
134
141
|
const pass = (_req, _res, next) => next();
|
|
135
142
|
const peerOf = (res) => String(res.locals.peer);
|
|
136
143
|
const peerBucket = new TokenBucketLimiter({ perMinute: limits.peer_requests_per_minute, burst: limits.peer_burst });
|
|
137
|
-
|
|
144
|
+
// Refusals are counted for GET /api/v1/metrics (ardent_a2a_rate_limited_total).
|
|
145
|
+
const refused = (scope) => () => runtime.counters.increment('a2a_rate_limited', { scope });
|
|
146
|
+
const peerLimit = limits.enabled ? limitRequests(peerBucket, (_req, res) => peerOf(res), refused('peer')) : pass;
|
|
138
147
|
const requirePeer = (message) => (req, res, next) => {
|
|
139
148
|
const peer = authenticate(req.header('Authorization'));
|
|
140
149
|
if (!peer) {
|
|
@@ -146,7 +155,7 @@ export async function createA2ASurface(runtime, config, env = process.env) {
|
|
|
146
155
|
};
|
|
147
156
|
// First in the chain: every route below, authenticated or not, is limited by client address.
|
|
148
157
|
if (limits.enabled)
|
|
149
|
-
app.use(limitRequests(new TokenBucketLimiter({ perMinute: limits.ip_requests_per_minute, burst: limits.ip_burst }), req => clientKey(req.ip)));
|
|
158
|
+
app.use(limitRequests(new TokenBucketLimiter({ perMinute: limits.ip_requests_per_minute, burst: limits.ip_burst }), req => clientKey(req.ip), refused('ip')));
|
|
150
159
|
const unavailable = (status) => ({ error: status === 410 ? 'Artifact export revoked or expired' : 'Artifact unavailable' });
|
|
151
160
|
/** Resolve the export for the authenticated peer, or answer the refusal. */
|
|
152
161
|
const exportFor = async (req, res) => {
|
|
@@ -255,7 +264,7 @@ export async function createA2ASurface(runtime, config, env = process.env) {
|
|
|
255
264
|
res.set('Cache-Control', 'private, no-store').json({ ...encoded, ...freshHermesTeamCard(teamCard) });
|
|
256
265
|
});
|
|
257
266
|
const auth = requirePeer('Authenticated A2A peer required');
|
|
258
|
-
const jsonRpcCap = jsonRpcTaskCap(taskGate, peerOf);
|
|
267
|
+
const jsonRpcCap = jsonRpcTaskCap(taskGate, peerOf, refused('tasks'));
|
|
259
268
|
const userBuilder = async (req) => {
|
|
260
269
|
const id = authenticate(req.header('Authorization'));
|
|
261
270
|
return { isAuthenticated: Boolean(id), userName: id ?? '' };
|
|
@@ -264,7 +273,7 @@ export async function createA2ASurface(runtime, config, env = process.env) {
|
|
|
264
273
|
if (config.a2a.bindings.includes('jsonrpc'))
|
|
265
274
|
app.use('/a2a/jsonrpc', auth, peerLimit, express.json({ limit: '1mb' }), aliases, jsonRpcCap, jsonRpcHandler({ requestHandler: handler, userBuilder, legacyCompat: { enabled: true } }));
|
|
266
275
|
if (config.a2a.bindings.includes('http-json'))
|
|
267
|
-
app.use('/a2a/rest', auth, peerLimit, restTaskCap(taskGate, peerOf), restHandler({ requestHandler: handler, userBuilder }));
|
|
276
|
+
app.use('/a2a/rest', auth, peerLimit, restTaskCap(taskGate, peerOf, refused('tasks')), restHandler({ requestHandler: handler, userBuilder }));
|
|
268
277
|
// Hermes Agent's team router posts to the peer origin itself. Keep that
|
|
269
278
|
// optional compatibility route separate from the advertised v1 interface.
|
|
270
279
|
if (config.a2a.hermes_compat && config.a2a.bindings.includes('jsonrpc')) {
|
|
@@ -278,10 +287,10 @@ export async function createA2ASurface(runtime, config, env = process.env) {
|
|
|
278
287
|
if (config.a2a.bindings.includes('grpc'))
|
|
279
288
|
grpcServer.addService(A2AService, grpcService({ requestHandler: handler, userBuilder: async (call) => {
|
|
280
289
|
const raw = call.metadata.get('authorization')[0];
|
|
281
|
-
return limitedGrpcUser(authenticate(typeof raw === 'string' ? raw : undefined), limits.enabled ? peerBucket : undefined);
|
|
290
|
+
return limitedGrpcUser(authenticate(typeof raw === 'string' ? raw : undefined), limits.enabled ? peerBucket : undefined, refused('peer'));
|
|
282
291
|
} }));
|
|
283
292
|
publish();
|
|
284
|
-
return { app, grpcServer, card, grpcAddress, grpcListenPort: listenPort + 1, pushSender, pushInbox, handler, taskGate, recovery };
|
|
293
|
+
return { app, grpcServer, card, grpcAddress, grpcListenPort: listenPort + 1, pushSender, pushInbox, handler, taskGate, recovery, peerAuthenticator };
|
|
285
294
|
}
|
|
286
295
|
export async function startA2AGrpc(surface, host = '127.0.0.1') {
|
|
287
296
|
await new Promise((resolve, reject) => {
|
package/dist/api.d.ts
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
import { Hono } from 'hono';
|
|
2
|
+
import { type Logger } from './log.js';
|
|
2
3
|
import { type LoadedConfig } from './config.js';
|
|
3
4
|
import type { ArdentRuntime } from './runtime.js';
|
|
5
|
+
import { type PeerAuthenticator } from './a2a-peers.js';
|
|
4
6
|
import type { JobEngine } from './job-engine.js';
|
|
5
7
|
import { ArtifactTransfers } from './artifact-transfer.js';
|
|
8
|
+
/** Request bodies of the core management routes, as for plugin routes. */
|
|
9
|
+
export declare const MANAGEMENT_BODY_LIMIT_BYTES = 1048576;
|
|
6
10
|
export declare function ardentOpenApi(): object;
|
|
7
11
|
/**
|
|
8
12
|
* `env` is the gateway's one shared environment: the runtime, tools, channels
|
|
@@ -12,4 +16,12 @@ export declare function ardentOpenApi(): object;
|
|
|
12
16
|
export declare function createArdentApi(runtime: ArdentRuntime, loaded: LoadedConfig, env?: NodeJS.ProcessEnv, jobEngine?: JobEngine, options?: {
|
|
13
17
|
envFile?: string;
|
|
14
18
|
artifactTransfers?: ArtifactTransfers;
|
|
19
|
+
logger?: Logger;
|
|
20
|
+
/** The running A2A surface's peer authentication, for POST /api/v1/credentials/peers/reload. */
|
|
21
|
+
peerAuthenticator?: () => PeerAuthenticator | undefined;
|
|
22
|
+
/**
|
|
23
|
+
* Variables the service environment set when the gateway started. They win over the profile
|
|
24
|
+
* environment file, so a credential reload never replaces them from the file.
|
|
25
|
+
*/
|
|
26
|
+
serviceEnv?: ReadonlySet<string>;
|
|
15
27
|
}): Hono;
|