@agentropy/runtime 0.0.0-stage → 0.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/LICENSE +202 -0
- package/README.md +39 -2
- package/dist/a2a-client.d.ts +111 -0
- package/dist/a2a-client.js +386 -0
- package/dist/a2a-history.d.ts +27 -0
- package/dist/a2a-history.js +67 -0
- package/dist/a2a-http.d.ts +46 -0
- package/dist/a2a-http.js +183 -0
- package/dist/a2a-protocol.d.ts +77 -0
- package/dist/a2a-protocol.js +148 -0
- package/dist/a2a-push-receiver.d.ts +24 -0
- package/dist/a2a-push-receiver.js +161 -0
- package/dist/a2a-push.d.ts +85 -0
- package/dist/a2a-push.js +385 -0
- package/dist/a2a-server.d.ts +82 -0
- package/dist/a2a-server.js +523 -0
- package/dist/a2a-sse.d.ts +5 -0
- package/dist/a2a-sse.js +36 -0
- package/dist/a2a.d.ts +41 -0
- package/dist/a2a.js +40 -0
- package/dist/app.d.ts +256 -0
- package/dist/app.js +541 -0
- package/dist/audit.d.ts +229 -0
- package/dist/audit.js +718 -0
- package/dist/bounded-body.d.ts +32 -0
- package/dist/bounded-body.js +124 -0
- package/dist/communication.d.ts +62 -0
- package/dist/communication.js +142 -0
- package/dist/compaction.d.ts +24 -0
- package/dist/compaction.js +202 -0
- package/dist/federation.d.ts +108 -0
- package/dist/federation.js +241 -0
- package/dist/http-path.d.ts +7 -0
- package/dist/http-path.js +14 -0
- package/dist/human-actions.d.ts +62 -0
- package/dist/human-actions.js +359 -0
- package/dist/implementation.d.ts +47 -0
- package/dist/implementation.js +138 -0
- package/dist/inbox.d.ts +101 -0
- package/dist/inbox.js +389 -0
- package/dist/index.d.ts +32 -0
- package/dist/index.js +32 -0
- package/dist/ingress.d.ts +35 -0
- package/dist/ingress.js +86 -0
- package/dist/lifecycle.d.ts +45 -0
- package/dist/lifecycle.js +57 -0
- package/dist/limits.d.ts +43 -0
- package/dist/limits.js +71 -0
- package/dist/mcp.d.ts +111 -0
- package/dist/mcp.js +308 -0
- package/dist/memory.d.ts +25 -0
- package/dist/memory.js +134 -0
- package/dist/model-routing.d.ts +66 -0
- package/dist/model-routing.js +80 -0
- package/dist/otel.d.ts +60 -0
- package/dist/otel.js +72 -0
- package/dist/outbox.d.ts +116 -0
- package/dist/outbox.js +327 -0
- package/dist/policy-cache.d.ts +69 -0
- package/dist/policy-cache.js +178 -0
- package/dist/priority.d.ts +27 -0
- package/dist/priority.js +28 -0
- package/dist/quotas.d.ts +19 -0
- package/dist/quotas.js +47 -0
- package/dist/reasoning.d.ts +54 -0
- package/dist/reasoning.js +307 -0
- package/dist/registry.d.ts +101 -0
- package/dist/registry.js +369 -0
- package/dist/remote.d.ts +130 -0
- package/dist/remote.js +473 -0
- package/dist/runtime.d.ts +167 -0
- package/dist/runtime.js +1035 -0
- package/dist/skills.d.ts +86 -0
- package/dist/skills.js +376 -0
- package/dist/task-service.d.ts +239 -0
- package/dist/task-service.js +790 -0
- package/dist/tools.d.ts +140 -0
- package/dist/tools.js +476 -0
- package/dist/wake-index.d.ts +9 -0
- package/dist/wake-index.js +11 -0
- package/dist/wakeups.d.ts +142 -0
- package/dist/wakeups.js +501 -0
- package/dist/workflow.d.ts +36 -0
- package/dist/workflow.js +101 -0
- package/package.json +48 -3
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reads a peer's reply body with a cap and a deadline (TASK-068). A reply from a peer (an MCP server, an A2A peer, a
|
|
3
|
+
* federation card, a model endpoint) is untrusted input: it is refused as soon as it passes the cap, without being
|
|
4
|
+
* buffered whole, and a body that stalls ends with the caller's abort signal instead of waiting for ever.
|
|
5
|
+
*/
|
|
6
|
+
/** The part of a fetch `Response` a reader uses. Test doubles may offer only `text()` or `json()`. */
|
|
7
|
+
export interface ReplyBody {
|
|
8
|
+
body?: unknown;
|
|
9
|
+
headers?: {
|
|
10
|
+
get(name: string): string | null;
|
|
11
|
+
};
|
|
12
|
+
text?(): Promise<string>;
|
|
13
|
+
json?(): Promise<unknown>;
|
|
14
|
+
}
|
|
15
|
+
/** The reply passed the cap. */
|
|
16
|
+
export declare class ReplyTooLarge extends Error {
|
|
17
|
+
readonly maxBytes: number;
|
|
18
|
+
constructor(maxBytes: number);
|
|
19
|
+
}
|
|
20
|
+
/** The reply arrived but is not JSON. */
|
|
21
|
+
export declare class ReplyNotJson extends Error {
|
|
22
|
+
constructor();
|
|
23
|
+
}
|
|
24
|
+
/** Cancels a reply body that will not be read, so its connection is released now rather than at garbage collection. */
|
|
25
|
+
export declare const release: (body: unknown) => void;
|
|
26
|
+
/**
|
|
27
|
+
* The body as text, at most `maxBytes` long. A declared `content-length` over the cap is refused before a byte is
|
|
28
|
+
* read; a streamed body is cut off, and its connection released, at the first chunk that passes the cap.
|
|
29
|
+
*/
|
|
30
|
+
export declare function readBoundedText(res: ReplyBody, maxBytes: number, signal?: AbortSignal): Promise<string>;
|
|
31
|
+
/** The body parsed as JSON under the same cap; a body that is not JSON is `ReplyNotJson`. */
|
|
32
|
+
export declare function readBoundedJson(res: ReplyBody, maxBytes: number, signal?: AbortSignal): Promise<unknown>;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reads a peer's reply body with a cap and a deadline (TASK-068). A reply from a peer (an MCP server, an A2A peer, a
|
|
3
|
+
* federation card, a model endpoint) is untrusted input: it is refused as soon as it passes the cap, without being
|
|
4
|
+
* buffered whole, and a body that stalls ends with the caller's abort signal instead of waiting for ever.
|
|
5
|
+
*/
|
|
6
|
+
/** The reply passed the cap. */
|
|
7
|
+
export class ReplyTooLarge extends Error {
|
|
8
|
+
maxBytes;
|
|
9
|
+
constructor(maxBytes) {
|
|
10
|
+
super(`Reply exceeds ${maxBytes} bytes`);
|
|
11
|
+
this.maxBytes = maxBytes;
|
|
12
|
+
this.name = 'ReplyTooLarge';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/** The reply arrived but is not JSON. */
|
|
16
|
+
export class ReplyNotJson extends Error {
|
|
17
|
+
constructor() {
|
|
18
|
+
super('Reply is not JSON');
|
|
19
|
+
this.name = 'ReplyNotJson';
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const sizeOf = (chunk) => typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.byteLength;
|
|
23
|
+
/** Rejects when `signal` aborts; resolves with `p` otherwise. */
|
|
24
|
+
function until(p, signal) {
|
|
25
|
+
if (!signal)
|
|
26
|
+
return p;
|
|
27
|
+
if (signal.aborted)
|
|
28
|
+
return Promise.reject(signal.reason ?? new Error('aborted'));
|
|
29
|
+
return new Promise((resolve, reject) => {
|
|
30
|
+
const onAbort = () => reject(signal.reason ?? new Error('aborted'));
|
|
31
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
32
|
+
p.then((v) => {
|
|
33
|
+
signal.removeEventListener('abort', onAbort);
|
|
34
|
+
resolve(v);
|
|
35
|
+
}, (e) => {
|
|
36
|
+
signal.removeEventListener('abort', onAbort);
|
|
37
|
+
reject(e instanceof Error ? e : new Error(String(e)));
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
/** Cancels a reply body that will not be read, so its connection is released now rather than at garbage collection. */
|
|
42
|
+
export const release = (body) => {
|
|
43
|
+
const b = body;
|
|
44
|
+
void Promise.resolve(b?.cancel?.()).catch(() => undefined);
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* The body as text, at most `maxBytes` long. A declared `content-length` over the cap is refused before a byte is
|
|
48
|
+
* read; a streamed body is cut off, and its connection released, at the first chunk that passes the cap.
|
|
49
|
+
*/
|
|
50
|
+
export async function readBoundedText(res, maxBytes, signal) {
|
|
51
|
+
const declared = Number(res.headers?.get('content-length'));
|
|
52
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
53
|
+
release(res.body);
|
|
54
|
+
throw new ReplyTooLarge(maxBytes);
|
|
55
|
+
}
|
|
56
|
+
const body = res.body;
|
|
57
|
+
const chunks = [];
|
|
58
|
+
let total = 0;
|
|
59
|
+
const take = (chunk) => {
|
|
60
|
+
total += sizeOf(chunk);
|
|
61
|
+
if (total > maxBytes)
|
|
62
|
+
throw new ReplyTooLarge(maxBytes);
|
|
63
|
+
chunks.push(chunk);
|
|
64
|
+
};
|
|
65
|
+
if (body &&
|
|
66
|
+
typeof body.getReader === 'function') {
|
|
67
|
+
const reader = body.getReader();
|
|
68
|
+
try {
|
|
69
|
+
for (;;) {
|
|
70
|
+
const next = await until(reader.read(), signal);
|
|
71
|
+
if (next.done)
|
|
72
|
+
break;
|
|
73
|
+
take(next.value);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
catch (err) {
|
|
77
|
+
void reader.cancel().catch(() => undefined);
|
|
78
|
+
throw err;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
else if (body && Symbol.asyncIterator in body) {
|
|
82
|
+
const it = body[Symbol.asyncIterator]();
|
|
83
|
+
try {
|
|
84
|
+
for (;;) {
|
|
85
|
+
const next = await until(it.next(), signal);
|
|
86
|
+
if (next.done)
|
|
87
|
+
break;
|
|
88
|
+
take(next.value);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
catch (err) {
|
|
92
|
+
void Promise.resolve(it.return?.()).catch(() => undefined);
|
|
93
|
+
throw err;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
else if (typeof res.text === 'function') {
|
|
97
|
+
const text = await until(res.text(), signal);
|
|
98
|
+
if (Buffer.byteLength(text) > maxBytes)
|
|
99
|
+
throw new ReplyTooLarge(maxBytes);
|
|
100
|
+
return text;
|
|
101
|
+
}
|
|
102
|
+
else if (typeof res.json === 'function') {
|
|
103
|
+
const text = JSON.stringify(await until(res.json(), signal));
|
|
104
|
+
if (Buffer.byteLength(text) > maxBytes)
|
|
105
|
+
throw new ReplyTooLarge(maxBytes);
|
|
106
|
+
return text;
|
|
107
|
+
}
|
|
108
|
+
else
|
|
109
|
+
return '';
|
|
110
|
+
const decoder = new TextDecoder();
|
|
111
|
+
return (chunks
|
|
112
|
+
.map((c) => typeof c === 'string' ? c : decoder.decode(c, { stream: true }))
|
|
113
|
+
.join('') + decoder.decode());
|
|
114
|
+
}
|
|
115
|
+
/** The body parsed as JSON under the same cap; a body that is not JSON is `ReplyNotJson`. */
|
|
116
|
+
export async function readBoundedJson(res, maxBytes, signal) {
|
|
117
|
+
const text = await readBoundedText(res, maxBytes, signal);
|
|
118
|
+
try {
|
|
119
|
+
return JSON.parse(text);
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
throw new ReplyNotJson();
|
|
123
|
+
}
|
|
124
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/** Communication v1 revision 4: router and the internal direct provider (M1-11, R-31). */
|
|
2
|
+
import { type AgentCommunicationProvider, type AgentEvent, type AgentMessage, type AgentRef, type CallContext, type CommunicationFeatures, type CommunicationOperation, type CommunicationRouter, type DelegationRequest, type DurabilityLevel, type MessageReceipt, type PolicyDecisionPoint, type RemoteTaskRef, type RemoteTaskState, type RouteBinding, type RouteRequirements, type TaskSnapshot, type TrustedPrincipal } from '@agentropy/core';
|
|
3
|
+
export declare class DefaultCommunicationRouter implements CommunicationRouter {
|
|
4
|
+
private readonly pdp?;
|
|
5
|
+
private readonly providers;
|
|
6
|
+
/** An optional PDP adds a `communication:<operation>` check on the target agent before route selection. */
|
|
7
|
+
constructor(pdp?: PolicyDecisionPoint | undefined);
|
|
8
|
+
register(provider: AgentCommunicationProvider): void;
|
|
9
|
+
selectRoute(target: AgentRef, operation: CommunicationOperation, ctx: CallContext, requirements?: RouteRequirements): Promise<RouteBinding>;
|
|
10
|
+
/** Routes are pinned on the task; a later call never re-selects. */
|
|
11
|
+
provider(route: RouteBinding): AgentCommunicationProvider;
|
|
12
|
+
}
|
|
13
|
+
/** The co-located runtime side of the direct provider; the TaskService implements it. */
|
|
14
|
+
export interface DirectTarget {
|
|
15
|
+
delegate<I>(request: DelegationRequest<I>, caller: TrustedPrincipal): Promise<{
|
|
16
|
+
taskId: string;
|
|
17
|
+
}>;
|
|
18
|
+
getTask(taskId: string, caller: TrustedPrincipal): Promise<TaskSnapshot>;
|
|
19
|
+
cancel(taskId: string, caller: TrustedPrincipal): Promise<TaskSnapshot>;
|
|
20
|
+
/** Ends after the terminal event, or when `options.signal` aborts. */
|
|
21
|
+
subscribe(taskId: string, caller: TrustedPrincipal, options?: {
|
|
22
|
+
signal?: AbortSignal;
|
|
23
|
+
}): AsyncIterable<AgentEvent>;
|
|
24
|
+
receive(message: AgentMessage, caller: TrustedPrincipal): Promise<{
|
|
25
|
+
accepted: boolean;
|
|
26
|
+
}>;
|
|
27
|
+
/**
|
|
28
|
+
* Tasks the caller may see with an opaque cursor, oldest first or, with `newestFirst`, newest first (A2A
|
|
29
|
+
* `ListTasks`, FEAT-034.4, FIX-062). `cursors[i]` resumes right after `tasks[i]`.
|
|
30
|
+
*/
|
|
31
|
+
listTasks?(query: {
|
|
32
|
+
instanceId?: string;
|
|
33
|
+
cursor?: string;
|
|
34
|
+
limit?: number;
|
|
35
|
+
newestFirst?: boolean;
|
|
36
|
+
}, caller: TrustedPrincipal): Promise<{
|
|
37
|
+
tasks: TaskSnapshot[];
|
|
38
|
+
cursor: string;
|
|
39
|
+
cursors: string[];
|
|
40
|
+
}>;
|
|
41
|
+
/** Hands a follow-up message to a task waiting for input (A2A `message.taskId`, FEAT-034.4). */
|
|
42
|
+
continueTask?(taskId: string, input: unknown, messageId: string, caller: TrustedPrincipal): Promise<void>;
|
|
43
|
+
}
|
|
44
|
+
export declare class DirectCommunicationProvider implements AgentCommunicationProvider {
|
|
45
|
+
private readonly target;
|
|
46
|
+
private readonly tenantId?;
|
|
47
|
+
private readonly now;
|
|
48
|
+
readonly id = "direct";
|
|
49
|
+
readonly features: CommunicationFeatures;
|
|
50
|
+
constructor(target: DirectTarget,
|
|
51
|
+
/** Declare durable-acceptance only when the target persists before acknowledging. */
|
|
52
|
+
durability: DurabilityLevel, tenantId?: string | undefined, now?: () => string);
|
|
53
|
+
/** Only co-located agents (no endpoint) in this provider's tenant, if bound to one. */
|
|
54
|
+
supports(target: AgentRef, operation: CommunicationOperation): boolean;
|
|
55
|
+
delegate<I>(route: RouteBinding, request: DelegationRequest<I>, ctx: CallContext): Promise<RemoteTaskRef>;
|
|
56
|
+
/** The actor of a forwarded message is always the verified caller, never the envelope's claim. */
|
|
57
|
+
send(route: RouteBinding, message: AgentMessage, ctx: CallContext): Promise<MessageReceipt>;
|
|
58
|
+
getTask(ref: RemoteTaskRef, ctx: CallContext): Promise<RemoteTaskState>;
|
|
59
|
+
cancel(ref: RemoteTaskRef, ctx: CallContext): Promise<RemoteTaskState>;
|
|
60
|
+
subscribe(ref: RemoteTaskRef, ctx: CallContext): AsyncIterable<AgentEvent>;
|
|
61
|
+
private state;
|
|
62
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/** Communication v1 revision 4: router and the internal direct provider (M1-11, R-31). */
|
|
2
|
+
import { validateAgentMessage, AgentropyError, DURABILITY_LEVELS, enforcePolicy, } from '@agentropy/core';
|
|
3
|
+
const rank = (d) => d === 'provider-dependent' ? 0 : DURABILITY_LEVELS.indexOf(d);
|
|
4
|
+
export class DefaultCommunicationRouter {
|
|
5
|
+
pdp;
|
|
6
|
+
providers = new Map();
|
|
7
|
+
/** An optional PDP adds a `communication:<operation>` check on the target agent before route selection. */
|
|
8
|
+
constructor(pdp) {
|
|
9
|
+
this.pdp = pdp;
|
|
10
|
+
}
|
|
11
|
+
register(provider) {
|
|
12
|
+
if (this.providers.has(provider.id) &&
|
|
13
|
+
this.providers.get(provider.id) !== provider) {
|
|
14
|
+
throw new AgentropyError('InvalidConfiguration', `Communication provider ${provider.id} already registered`, { details: { reason: 'duplicate' } });
|
|
15
|
+
}
|
|
16
|
+
this.providers.set(provider.id, provider);
|
|
17
|
+
}
|
|
18
|
+
async selectRoute(target, operation, ctx, requirements = {}) {
|
|
19
|
+
// Tenant and authorization come before any route is considered (no provider is told about a forbidden target).
|
|
20
|
+
if (target.tenantId !== ctx.caller.tenantId)
|
|
21
|
+
throw new AgentropyError('TenantMismatch', 'Cross-tenant route denied', {
|
|
22
|
+
details: { operation },
|
|
23
|
+
});
|
|
24
|
+
if (this.pdp) {
|
|
25
|
+
await enforcePolicy(this.pdp, {
|
|
26
|
+
principal: ctx.caller,
|
|
27
|
+
action: `communication:${operation}`,
|
|
28
|
+
resource: {
|
|
29
|
+
type: 'agent',
|
|
30
|
+
id: target.definitionId,
|
|
31
|
+
tenantId: target.tenantId,
|
|
32
|
+
},
|
|
33
|
+
}, ctx.signal);
|
|
34
|
+
}
|
|
35
|
+
const ops = new Set([operation, ...(requirements.operations ?? [])]);
|
|
36
|
+
const all = [...this.providers.values()].sort((a, b) => a.id.localeCompare(b.id));
|
|
37
|
+
const reachable = all.filter((p) => p.supports(target, operation));
|
|
38
|
+
if (reachable.length === 0)
|
|
39
|
+
throw new AgentropyError('NoCompatibleRoute', 'No provider can reach the target', { details: { operation } });
|
|
40
|
+
const withOps = reachable.filter((p) => [...ops].every((o) => p.features.operations.includes(o)));
|
|
41
|
+
if (withOps.length === 0)
|
|
42
|
+
throw new AgentropyError('UnsupportedOperation', `No provider declares ${[...ops].join(', ')}`, { details: { operation } });
|
|
43
|
+
const withExt = withOps.filter((p) => (requirements.extensions ?? []).every((id) => p.features.extensions?.some((e) => e.id === id)));
|
|
44
|
+
if (withExt.length === 0)
|
|
45
|
+
throw new AgentropyError('UnsupportedOperation', 'Required extension not declared', { details: { reason: 'extension' } });
|
|
46
|
+
const wanted = requirements.durability;
|
|
47
|
+
const durable = wanted
|
|
48
|
+
? withExt.filter((p) => rank(p.features.durability) >= rank(wanted))
|
|
49
|
+
: withExt;
|
|
50
|
+
if (durable.length === 0)
|
|
51
|
+
throw new AgentropyError('GuaranteeUnavailable', `No route offers ${wanted}`, { details: { requested: wanted } });
|
|
52
|
+
// Prefer A2A-style providers for independently addressable agents, direct for co-located ones.
|
|
53
|
+
const preferRemote = Boolean(target.endpoint);
|
|
54
|
+
const chosen = [...durable].sort((a, b) => Number(preferRemote ? a.id === 'direct' : a.id !== 'direct') -
|
|
55
|
+
Number(preferRemote ? b.id === 'direct' : b.id !== 'direct'))[0];
|
|
56
|
+
return {
|
|
57
|
+
providerId: chosen.id,
|
|
58
|
+
protocol: chosen.features.protocol,
|
|
59
|
+
protocolVersion: chosen.features.protocolVersion,
|
|
60
|
+
target: { ...target },
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/** Routes are pinned on the task; a later call never re-selects. */
|
|
64
|
+
provider(route) {
|
|
65
|
+
const p = this.providers.get(route.providerId);
|
|
66
|
+
if (!p ||
|
|
67
|
+
p.features.protocol !== route.protocol ||
|
|
68
|
+
p.features.protocolVersion !== route.protocolVersion) {
|
|
69
|
+
throw new AgentropyError('NoCompatibleRoute', `Pinned route ${route.providerId} is not available`, { details: { providerId: route.providerId } });
|
|
70
|
+
}
|
|
71
|
+
return p;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
export class DirectCommunicationProvider {
|
|
75
|
+
target;
|
|
76
|
+
tenantId;
|
|
77
|
+
now;
|
|
78
|
+
id = 'direct';
|
|
79
|
+
features;
|
|
80
|
+
constructor(target,
|
|
81
|
+
/** Declare durable-acceptance only when the target persists before acknowledging. */
|
|
82
|
+
durability, tenantId, now = () => new Date().toISOString()) {
|
|
83
|
+
this.target = target;
|
|
84
|
+
this.tenantId = tenantId;
|
|
85
|
+
this.now = now;
|
|
86
|
+
this.features = {
|
|
87
|
+
operations: ['delegate', 'send', 'getTask', 'cancel', 'subscribe'],
|
|
88
|
+
streaming: true,
|
|
89
|
+
pushNotifications: false,
|
|
90
|
+
durability,
|
|
91
|
+
protocol: 'direct',
|
|
92
|
+
protocolVersion: '1',
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
/** Only co-located agents (no endpoint) in this provider's tenant, if bound to one. */
|
|
96
|
+
supports(target, operation) {
|
|
97
|
+
return (!target.endpoint &&
|
|
98
|
+
(this.tenantId === undefined || this.tenantId === target.tenantId) &&
|
|
99
|
+
this.features.operations.includes(operation));
|
|
100
|
+
}
|
|
101
|
+
async delegate(route, request, ctx) {
|
|
102
|
+
const { taskId } = await this.target.delegate({
|
|
103
|
+
...request,
|
|
104
|
+
target: {
|
|
105
|
+
...request.target,
|
|
106
|
+
...(route.target.instanceId
|
|
107
|
+
? { instanceId: route.target.instanceId }
|
|
108
|
+
: {}),
|
|
109
|
+
},
|
|
110
|
+
}, ctx.caller);
|
|
111
|
+
// Direct targets share the local runtime, so the local projection and the remote task carry the same ID.
|
|
112
|
+
return { localTaskId: taskId, route, remoteTaskId: taskId };
|
|
113
|
+
}
|
|
114
|
+
/** The actor of a forwarded message is always the verified caller, never the envelope's claim. */
|
|
115
|
+
async send(route, message, ctx) {
|
|
116
|
+
void route;
|
|
117
|
+
validateAgentMessage(message);
|
|
118
|
+
const trusted = {
|
|
119
|
+
...message,
|
|
120
|
+
tenantId: ctx.caller.tenantId,
|
|
121
|
+
actor: { principalId: ctx.caller.id, principalType: ctx.caller.type },
|
|
122
|
+
};
|
|
123
|
+
const { accepted } = await this.target.receive(trusted, ctx.caller);
|
|
124
|
+
return { messageId: message.messageId, accepted };
|
|
125
|
+
}
|
|
126
|
+
async getTask(ref, ctx) {
|
|
127
|
+
return this.state(await this.target.getTask(ref.remoteTaskId, ctx.caller));
|
|
128
|
+
}
|
|
129
|
+
async cancel(ref, ctx) {
|
|
130
|
+
return this.state(await this.target.cancel(ref.remoteTaskId, ctx.caller));
|
|
131
|
+
}
|
|
132
|
+
subscribe(ref, ctx) {
|
|
133
|
+
return this.target.subscribe(ref.remoteTaskId, ctx.caller, ctx.signal ? { signal: ctx.signal } : undefined);
|
|
134
|
+
}
|
|
135
|
+
state(s) {
|
|
136
|
+
return {
|
|
137
|
+
remoteState: s.status,
|
|
138
|
+
normalized: s.status,
|
|
139
|
+
observedAt: this.now(),
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { TaskService } from './task-service.js';
|
|
2
|
+
export interface CompactionResult {
|
|
3
|
+
mailbox: number;
|
|
4
|
+
inboundEvents: number;
|
|
5
|
+
outbox: number;
|
|
6
|
+
wakeups: number;
|
|
7
|
+
subscriptions: number;
|
|
8
|
+
effects: number;
|
|
9
|
+
checkpoints: number;
|
|
10
|
+
usage: number;
|
|
11
|
+
humanActions: number;
|
|
12
|
+
executions: number;
|
|
13
|
+
pushConfigs: number;
|
|
14
|
+
/** A2A message history rows (FEAT-044.2). */
|
|
15
|
+
a2aHistory: number;
|
|
16
|
+
/** Expired memory entries (FEAT-045). */
|
|
17
|
+
memories: number;
|
|
18
|
+
idempotency: number;
|
|
19
|
+
remoteTasks: number;
|
|
20
|
+
inbox: number;
|
|
21
|
+
/** Tasks whose standing state was removed in this run. */
|
|
22
|
+
tasks: number;
|
|
23
|
+
}
|
|
24
|
+
export declare function compactStore(tasks: TaskService, retainMs: number): Promise<CompactionResult>;
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compaction (M2-01, R-37; every collection since FEAT-040.1): removes the standing state of work that is over, so a
|
|
3
|
+
* long-running deployment's store stops growing with its history.
|
|
4
|
+
*
|
|
5
|
+
* - Consumed mailbox rows and inbound-event dedupe records older than the window (duplicates are only detected
|
|
6
|
+
* inside it).
|
|
7
|
+
* - For every task that ended before the window and has not been compacted: its published outbox rows, wake-ups,
|
|
8
|
+
* subscriptions and mailbox, effects journal, checkpoint, usage, human actions, executions, push configs and
|
|
9
|
+
* idempotency record. The task row itself stays (it is what `getTask` answers from) and is marked
|
|
10
|
+
* `compactedAt`, so later runs skip it.
|
|
11
|
+
* - Terminal remote task projections last observed before the window, and inbox entries resolved or acknowledged
|
|
12
|
+
* before it.
|
|
13
|
+
*
|
|
14
|
+
* Work is done in short transactions (a batch of tasks each), never one transaction for the whole store.
|
|
15
|
+
*/
|
|
16
|
+
import { AgentropyError, } from '@agentropy/core';
|
|
17
|
+
/** Rows handled per transaction. */
|
|
18
|
+
const BATCH = 100;
|
|
19
|
+
const add = (out, c) => {
|
|
20
|
+
for (const [k, n] of Object.entries(c))
|
|
21
|
+
out[k] += n;
|
|
22
|
+
};
|
|
23
|
+
export async function compactStore(tasks, retainMs) {
|
|
24
|
+
if (typeof retainMs !== 'number' ||
|
|
25
|
+
!Number.isFinite(retainMs) ||
|
|
26
|
+
retainMs < 0)
|
|
27
|
+
throw new AgentropyError('SchemaViolation', 'retainMs must be a non-negative number of milliseconds');
|
|
28
|
+
const store = tasks.o.store;
|
|
29
|
+
const cutoff = new Date(Date.parse(tasks.o.now()) - retainMs).toISOString();
|
|
30
|
+
const nowIso = tasks.o.now();
|
|
31
|
+
const out = {
|
|
32
|
+
mailbox: 0,
|
|
33
|
+
inboundEvents: 0,
|
|
34
|
+
outbox: 0,
|
|
35
|
+
wakeups: 0,
|
|
36
|
+
subscriptions: 0,
|
|
37
|
+
effects: 0,
|
|
38
|
+
checkpoints: 0,
|
|
39
|
+
usage: 0,
|
|
40
|
+
humanActions: 0,
|
|
41
|
+
executions: 0,
|
|
42
|
+
pushConfigs: 0,
|
|
43
|
+
a2aHistory: 0,
|
|
44
|
+
memories: 0,
|
|
45
|
+
idempotency: 0,
|
|
46
|
+
remoteTasks: 0,
|
|
47
|
+
inbox: 0,
|
|
48
|
+
tasks: 0,
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Walks one indexed read in pages of `BATCH`, each page handled in its own transaction. A transaction callback may
|
|
52
|
+
* run again after a serialization conflict, so it counts into a fresh object and the counts are added here, once
|
|
53
|
+
* the transaction has committed (TASK-066).
|
|
54
|
+
*/
|
|
55
|
+
const sweep = async (collection, options, handle) => {
|
|
56
|
+
let afterSeq = 0;
|
|
57
|
+
for (;;) {
|
|
58
|
+
const { counts, last, size } = await store.transaction(async (tx) => {
|
|
59
|
+
const rows = await tx.find(collection, {
|
|
60
|
+
...options,
|
|
61
|
+
orderBy: 'seq',
|
|
62
|
+
afterSeq,
|
|
63
|
+
limit: BATCH,
|
|
64
|
+
});
|
|
65
|
+
return {
|
|
66
|
+
counts: await handle(tx, rows),
|
|
67
|
+
last: rows.at(-1)?.seq,
|
|
68
|
+
size: rows.length,
|
|
69
|
+
};
|
|
70
|
+
});
|
|
71
|
+
add(out, counts);
|
|
72
|
+
if (size < BATCH || last === undefined)
|
|
73
|
+
return;
|
|
74
|
+
afterSeq = last;
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
// Consumed mailbox rows, in batches (removing them moves the next page up, so no cursor).
|
|
78
|
+
for (;;) {
|
|
79
|
+
const n = await store.transaction(async (tx) => {
|
|
80
|
+
const rows = await tx.find('mailbox', {
|
|
81
|
+
where: { consumed: 1 },
|
|
82
|
+
limit: BATCH * 5,
|
|
83
|
+
});
|
|
84
|
+
for (const m of rows)
|
|
85
|
+
await tx.remove('mailbox', m.id, m.revision);
|
|
86
|
+
return rows.length;
|
|
87
|
+
});
|
|
88
|
+
out.mailbox += n;
|
|
89
|
+
if (n < BATCH * 5)
|
|
90
|
+
break;
|
|
91
|
+
}
|
|
92
|
+
// Dedupe records that fell out of the window: only those, by the `at` index.
|
|
93
|
+
await sweep('inboundEvents', { range: { field: 'at', lte: cutoff } }, async (tx, rows) => {
|
|
94
|
+
let n = 0;
|
|
95
|
+
for (const e of rows)
|
|
96
|
+
if (e.value.at < cutoff) {
|
|
97
|
+
await tx.remove('inboundEvents', e.id, e.revision);
|
|
98
|
+
n++;
|
|
99
|
+
}
|
|
100
|
+
return { inboundEvents: n };
|
|
101
|
+
});
|
|
102
|
+
// Tasks that ended before the window and are not compacted yet (the `compactedAt` index skips the others). The
|
|
103
|
+
// ones still inside the window are read again by the next run, which is what retention means.
|
|
104
|
+
for (const status of ['completed', 'failed', 'cancelled'])
|
|
105
|
+
await sweep('tasks', { where: { status, compactedAt: null } }, async (tx, rows) => {
|
|
106
|
+
const c = {};
|
|
107
|
+
const bump = (k, n = 1) => (c[k] = (c[k] ?? 0) + n);
|
|
108
|
+
for (const row of rows) {
|
|
109
|
+
if (row.value.updatedAt >= cutoff)
|
|
110
|
+
continue;
|
|
111
|
+
for (const [k, n] of Object.entries(await compactTask(tx, row.id)))
|
|
112
|
+
bump(k, n);
|
|
113
|
+
await tx.update('tasks', row.id, row.revision, {
|
|
114
|
+
...row.value,
|
|
115
|
+
compactedAt: nowIso,
|
|
116
|
+
});
|
|
117
|
+
bump('tasks');
|
|
118
|
+
}
|
|
119
|
+
return c;
|
|
120
|
+
});
|
|
121
|
+
for (const status of ['completed', 'failed', 'cancelled'])
|
|
122
|
+
await sweep('remoteTasks', { where: { status }, range: { field: 'observedAt', lte: cutoff } }, async (tx, rows) => {
|
|
123
|
+
let n = 0;
|
|
124
|
+
for (const r of rows)
|
|
125
|
+
if (r.value.observedAt < cutoff) {
|
|
126
|
+
await tx.remove('remoteTasks', r.id, r.revision);
|
|
127
|
+
n++;
|
|
128
|
+
}
|
|
129
|
+
return { remoteTasks: n };
|
|
130
|
+
});
|
|
131
|
+
// Inbox entries resolved, or acknowledged, before the window: the resolved ones by status, the open ones that are
|
|
132
|
+
// neither new nor changed since they were shown (`pending: 0`) for an acknowledgement. Open entries written before
|
|
133
|
+
// `pending` existed have none (null in the index; FIX-083): for them it is worked out from the markers as the inbox
|
|
134
|
+
// does on every write, so an acknowledged one goes and one the briefing would still show stays.
|
|
135
|
+
for (const where of [
|
|
136
|
+
{ status: 'resolved' },
|
|
137
|
+
{ status: 'open', pending: 0 },
|
|
138
|
+
{ status: 'open', pending: null },
|
|
139
|
+
])
|
|
140
|
+
await sweep('inbox', { where }, async (tx, rows) => {
|
|
141
|
+
let n = 0;
|
|
142
|
+
for (const e of rows) {
|
|
143
|
+
const { markers, revision } = e.value;
|
|
144
|
+
const pending = !markers.acknowledgedAt && markers.presentedRevision !== revision;
|
|
145
|
+
if ('pending' in where && where.pending === null && pending)
|
|
146
|
+
continue;
|
|
147
|
+
const done = markers.resolvedAt ?? markers.acknowledgedAt;
|
|
148
|
+
if (done !== undefined && done < cutoff) {
|
|
149
|
+
await tx.remove('inbox', e.id, e.revision);
|
|
150
|
+
n++;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return { inbox: n };
|
|
154
|
+
});
|
|
155
|
+
// Memory entries past their expiry (FEAT-045), whatever the retention window: expiry is the entry's own.
|
|
156
|
+
await sweep('memories', { range: { field: 'expiresAt', lte: nowIso } }, async (tx, rows) => {
|
|
157
|
+
let n = 0;
|
|
158
|
+
for (const m of rows)
|
|
159
|
+
if (m.value.expiresAt !== undefined && m.value.expiresAt <= nowIso) {
|
|
160
|
+
await tx.remove('memories', m.id, m.revision);
|
|
161
|
+
n++;
|
|
162
|
+
}
|
|
163
|
+
return { memories: n };
|
|
164
|
+
});
|
|
165
|
+
return out;
|
|
166
|
+
}
|
|
167
|
+
/** Removes everything that belongs to one ended task and returns what it removed. */
|
|
168
|
+
async function compactTask(tx, taskId) {
|
|
169
|
+
const c = {};
|
|
170
|
+
const bump = (k) => (c[k] = (c[k] ?? 0) + 1);
|
|
171
|
+
const drop = async (collection, count) => {
|
|
172
|
+
for (const d of await tx.find(collection, {
|
|
173
|
+
where: { taskId },
|
|
174
|
+
})) {
|
|
175
|
+
await tx.remove(collection, d.id, d.revision);
|
|
176
|
+
bump(count);
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
for (const r of await tx.find('outbox', {
|
|
180
|
+
where: { aggregateId: taskId },
|
|
181
|
+
}))
|
|
182
|
+
if (r.value.published === 1) {
|
|
183
|
+
await tx.remove('outbox', r.id, r.revision);
|
|
184
|
+
bump('outbox');
|
|
185
|
+
}
|
|
186
|
+
await drop('wakeups', 'wakeups');
|
|
187
|
+
await drop('subscriptions', 'subscriptions');
|
|
188
|
+
await drop('mailbox', 'mailbox');
|
|
189
|
+
await drop('effects', 'effects');
|
|
190
|
+
await drop('usage', 'usage');
|
|
191
|
+
await drop('humanActions', 'humanActions');
|
|
192
|
+
await drop('executions', 'executions');
|
|
193
|
+
await drop('pushConfigs', 'pushConfigs');
|
|
194
|
+
await drop('a2aHistory', 'a2aHistory');
|
|
195
|
+
await drop('idempotency', 'idempotency');
|
|
196
|
+
const cp = await tx.get('checkpoints', taskId);
|
|
197
|
+
if (cp) {
|
|
198
|
+
await tx.remove('checkpoints', taskId, cp.revision);
|
|
199
|
+
bump('checkpoints');
|
|
200
|
+
}
|
|
201
|
+
return c;
|
|
202
|
+
}
|