@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
package/dist/memory.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reference `memory` capability provider (FEAT-045; Capability v1 revision 14, "Memory provider"): `remember` and
|
|
3
|
+
* `recall` on the Store port.
|
|
4
|
+
*
|
|
5
|
+
* - **Scoped.** An entry belongs to a tenant and to the acting principal of the invocation (an agent's instance
|
|
6
|
+
* identity), so another tenant, or another agent in the same tenant, never reads or overwrites it.
|
|
7
|
+
* - **Bounded.** Key, text (8 KiB), tags, TTL and the number of live entries per scope (`maxEntries`, default 1,000)
|
|
8
|
+
* are validated; recall returns at most 20 entries.
|
|
9
|
+
* - **Retained.** An entry expires after its TTL (or the provider's `defaultTtlMs`); it is invisible at once and
|
|
10
|
+
* `compact()` removes it. There is no `forget` operation in v1.
|
|
11
|
+
* - **Plain matching.** Key, tag and a case-insensitive substring of the text: deterministic, newest first. A semantic
|
|
12
|
+
* provider is a different provider of the same capability. Recalled text is data written by earlier tasks and may
|
|
13
|
+
* carry instructions aimed at a model: callers treat it as untrusted.
|
|
14
|
+
*/
|
|
15
|
+
import { AgentropyError, } from '@agentropy/core';
|
|
16
|
+
const KEY = /^[A-Za-z0-9._:/-]{1,128}$/;
|
|
17
|
+
const TAG = /^[a-z0-9._:-]{1,64}$/;
|
|
18
|
+
const MAX_TEXT_BYTES = 8 * 1024;
|
|
19
|
+
const MAX_TAGS = 8;
|
|
20
|
+
const MAX_QUERY = 256;
|
|
21
|
+
const DEFAULT_MAX_ENTRIES = 1_000;
|
|
22
|
+
const RECALL_DEFAULT = 5;
|
|
23
|
+
const RECALL_MAX = 20;
|
|
24
|
+
const bad = (message) => new AgentropyError('SchemaViolation', message);
|
|
25
|
+
const isLive = (r, now) => r.expiresAt === undefined || r.expiresAt > now;
|
|
26
|
+
const rowId = (tenantId, ownerId, key) => JSON.stringify([tenantId, ownerId, key]);
|
|
27
|
+
export function memoryOperationHandlers(o) {
|
|
28
|
+
const maxEntries = o.maxEntries ?? DEFAULT_MAX_ENTRIES;
|
|
29
|
+
if (!Number.isInteger(maxEntries) || maxEntries < 1)
|
|
30
|
+
throw new AgentropyError('InvalidConfiguration', 'memory.maxEntries must be a positive integer');
|
|
31
|
+
if (o.defaultTtlMs !== undefined &&
|
|
32
|
+
(!Number.isSafeInteger(o.defaultTtlMs) || o.defaultTtlMs < 1))
|
|
33
|
+
throw new AgentropyError('InvalidConfiguration', 'memory.defaultTtlMs must be a positive integer');
|
|
34
|
+
return {
|
|
35
|
+
remember: async (raw, ctx) => {
|
|
36
|
+
const i = (raw ?? {});
|
|
37
|
+
const key = i['key'] ?? (ctx.stepKey ? `step:${ctx.stepKey}` : undefined);
|
|
38
|
+
if (typeof key !== 'string' || !KEY.test(key))
|
|
39
|
+
throw bad(i['key'] === undefined
|
|
40
|
+
? 'memory.remember needs a key or a step key'
|
|
41
|
+
: 'key must be 1 to 128 characters of A-Z a-z 0-9 . _ : / -');
|
|
42
|
+
const text = i['text'];
|
|
43
|
+
if (typeof text !== 'string' ||
|
|
44
|
+
!text ||
|
|
45
|
+
Buffer.byteLength(text, 'utf8') > MAX_TEXT_BYTES)
|
|
46
|
+
throw bad(`text must be a non-empty string of at most ${MAX_TEXT_BYTES} bytes`);
|
|
47
|
+
const tagsIn = i['tags'] ?? [];
|
|
48
|
+
if (!Array.isArray(tagsIn) ||
|
|
49
|
+
tagsIn.length > MAX_TAGS ||
|
|
50
|
+
tagsIn.some((t) => typeof t !== 'string' || !TAG.test(t)))
|
|
51
|
+
throw bad(`tags must be at most ${MAX_TAGS} strings of 1 to 64 characters of a-z 0-9 . _ : -`);
|
|
52
|
+
const tags = [...new Set(tagsIn)];
|
|
53
|
+
const ttl = i['ttlMs'] ?? o.defaultTtlMs;
|
|
54
|
+
if (ttl !== undefined &&
|
|
55
|
+
(!Number.isSafeInteger(ttl) || ttl < 1))
|
|
56
|
+
throw bad('ttlMs must be a positive integer');
|
|
57
|
+
const now = o.now();
|
|
58
|
+
let expiresAt;
|
|
59
|
+
if (ttl !== undefined) {
|
|
60
|
+
const at = new Date(Date.parse(now) + ttl);
|
|
61
|
+
if (Number.isNaN(at.getTime()))
|
|
62
|
+
throw bad('ttlMs is too large');
|
|
63
|
+
expiresAt = at.toISOString();
|
|
64
|
+
}
|
|
65
|
+
const id = rowId(ctx.tenantId, ctx.principalId, key);
|
|
66
|
+
return o.store.transaction(async (tx) => {
|
|
67
|
+
const existing = await tx.get('memories', id);
|
|
68
|
+
const replaced = !!existing && isLive(existing.value, now);
|
|
69
|
+
if (!replaced) {
|
|
70
|
+
const live = (await tx.find('memories', {
|
|
71
|
+
where: { tenantId: ctx.tenantId, ownerId: ctx.principalId },
|
|
72
|
+
})).filter((d) => isLive(d.value, now)).length;
|
|
73
|
+
if (live >= maxEntries)
|
|
74
|
+
throw new AgentropyError('QuotaExceeded', 'The memory of this agent is full', { details: { maxEntries } });
|
|
75
|
+
}
|
|
76
|
+
const value = {
|
|
77
|
+
tenantId: ctx.tenantId,
|
|
78
|
+
ownerId: ctx.principalId,
|
|
79
|
+
key,
|
|
80
|
+
text,
|
|
81
|
+
tags,
|
|
82
|
+
rememberedAt: now,
|
|
83
|
+
...(expiresAt ? { expiresAt } : {}),
|
|
84
|
+
};
|
|
85
|
+
if (existing)
|
|
86
|
+
await tx.update('memories', id, existing.revision, value);
|
|
87
|
+
else
|
|
88
|
+
await tx.insert('memories', id, value);
|
|
89
|
+
return { key, replaced };
|
|
90
|
+
});
|
|
91
|
+
},
|
|
92
|
+
recall: async (raw, ctx) => {
|
|
93
|
+
const i = (raw ?? {});
|
|
94
|
+
const limit = i['limit'] ?? RECALL_DEFAULT;
|
|
95
|
+
if (!Number.isInteger(limit) ||
|
|
96
|
+
limit < 1 ||
|
|
97
|
+
limit > RECALL_MAX)
|
|
98
|
+
throw bad(`limit must be an integer from 1 to ${RECALL_MAX}`);
|
|
99
|
+
for (const f of ['key', 'tag', 'query'])
|
|
100
|
+
if (i[f] !== undefined && typeof i[f] !== 'string')
|
|
101
|
+
throw bad(`${f} must be a string`);
|
|
102
|
+
const query = i['query'];
|
|
103
|
+
if (query !== undefined && (!query || query.length > MAX_QUERY))
|
|
104
|
+
throw bad(`query must be 1 to ${MAX_QUERY} characters`);
|
|
105
|
+
const needle = query?.toLowerCase();
|
|
106
|
+
const now = o.now();
|
|
107
|
+
const rows = await o.store.transaction((tx) => tx.find('memories', {
|
|
108
|
+
where: { tenantId: ctx.tenantId, ownerId: ctx.principalId },
|
|
109
|
+
}));
|
|
110
|
+
const entries = rows
|
|
111
|
+
.map((d) => d.value)
|
|
112
|
+
.filter((r) => isLive(r, now) &&
|
|
113
|
+
(i['key'] === undefined || r.key === i['key']) &&
|
|
114
|
+
(i['tag'] === undefined || r.tags.includes(i['tag'])) &&
|
|
115
|
+
(needle === undefined || r.text.toLowerCase().includes(needle)))
|
|
116
|
+
.sort((a, b) => a.rememberedAt !== b.rememberedAt
|
|
117
|
+
? a.rememberedAt < b.rememberedAt
|
|
118
|
+
? 1
|
|
119
|
+
: -1
|
|
120
|
+
: a.key < b.key
|
|
121
|
+
? -1
|
|
122
|
+
: 1)
|
|
123
|
+
.slice(0, limit)
|
|
124
|
+
.map((r) => ({
|
|
125
|
+
key: r.key,
|
|
126
|
+
text: r.text,
|
|
127
|
+
tags: r.tags,
|
|
128
|
+
rememberedAt: r.rememberedAt,
|
|
129
|
+
...(r.expiresAt ? { expiresAt: r.expiresAt } : {}),
|
|
130
|
+
}));
|
|
131
|
+
return { entries };
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rule-based model routing (FEAT-035.3, N-03 option B): a `ReasoningProvider` that picks among configured endpoints,
|
|
3
|
+
* outside the core runtime and without a new contract surface beyond the endpoint descriptors.
|
|
4
|
+
*
|
|
5
|
+
* Security floors (see the model routing evaluation):
|
|
6
|
+
* 1. **Residency and data class are hard constraints.** The endpoints considered are those declared for the required
|
|
7
|
+
* zone and data class; with none available the call fails `ProviderUnavailable` — it is never sent elsewhere.
|
|
8
|
+
* Constraints come from the deployment's `floors` (trusted: tenant, task) and the caller's `route` hints; a floor
|
|
9
|
+
* always wins over a hint, and routing never reads prompts or any model-generated text.
|
|
10
|
+
* 2. **Fallback only within the same floor set.** Rules order candidates; candidates are filtered by the floors first,
|
|
11
|
+
* so a fallback can never be an endpoint the primary was not allowed to be.
|
|
12
|
+
* 3. **Budget.** The reasoning capability reserves the call's tokens before this provider runs and settles after, so
|
|
13
|
+
* attempts (including failed ones) cannot exceed `budget.maxCostUnits`; every attempt is asked for no more
|
|
14
|
+
* than the request's `maxTokens`.
|
|
15
|
+
* 4. **Auditable choice.** `onChoice` receives the rule, endpoint and outcome of every attempt (identifiers only, never
|
|
16
|
+
* prompts or keys) for spans and the audit trail.
|
|
17
|
+
* 5. **Credentials per endpoint.** Each endpoint is its own provider with its own credential reference; the router
|
|
18
|
+
* shares nothing between them.
|
|
19
|
+
* 6. **Deterministic.** The same request and floors always give the same candidate order.
|
|
20
|
+
*/
|
|
21
|
+
import { type ReasoningProvider } from '@agentropy/core';
|
|
22
|
+
/** Where a request may go and how it prefers to be served. All fields are identifiers, never free text from a model. */
|
|
23
|
+
export interface ModelRoute {
|
|
24
|
+
/** Residency zone the data must stay in. */
|
|
25
|
+
zone?: string;
|
|
26
|
+
/** Data class the endpoint must be cleared for. */
|
|
27
|
+
dataClass?: string;
|
|
28
|
+
/** Capability tier the caller wants (matched by rules). */
|
|
29
|
+
tier?: string;
|
|
30
|
+
latency?: 'low' | 'normal';
|
|
31
|
+
}
|
|
32
|
+
export interface ModelEndpoint {
|
|
33
|
+
id: string;
|
|
34
|
+
provider: ReasoningProvider;
|
|
35
|
+
/** The zone this endpoint runs in. */
|
|
36
|
+
zone: string;
|
|
37
|
+
/** Data classes it is cleared for. */
|
|
38
|
+
dataClasses: readonly string[];
|
|
39
|
+
}
|
|
40
|
+
export interface RoutingRule {
|
|
41
|
+
id: string;
|
|
42
|
+
/** The rule applies when every given attribute equals the request's `route` hint. */
|
|
43
|
+
when?: Pick<ModelRoute, 'tier' | 'latency'>;
|
|
44
|
+
/** Candidate endpoint IDs in order of preference. */
|
|
45
|
+
endpoints: readonly string[];
|
|
46
|
+
}
|
|
47
|
+
export interface RoutingChoice {
|
|
48
|
+
ruleId: string;
|
|
49
|
+
endpointId: string;
|
|
50
|
+
attempt: number;
|
|
51
|
+
outcome: 'ok' | 'failed';
|
|
52
|
+
/** Errors v1 code of a failed attempt. */
|
|
53
|
+
code?: string;
|
|
54
|
+
}
|
|
55
|
+
export declare function routedReasoning(o: {
|
|
56
|
+
id?: string;
|
|
57
|
+
endpoints: readonly ModelEndpoint[];
|
|
58
|
+
/** Ordered; the first rule that matches decides. A rule without `when` is the default. */
|
|
59
|
+
rules: readonly RoutingRule[];
|
|
60
|
+
/** Trusted constraints for a call (from the tenant or task); they override the caller's hints. */
|
|
61
|
+
floors?: (ctx: {
|
|
62
|
+
tenantId: string;
|
|
63
|
+
taskId: string;
|
|
64
|
+
}) => Pick<ModelRoute, 'zone' | 'dataClass'> | Promise<Pick<ModelRoute, 'zone' | 'dataClass'>>;
|
|
65
|
+
onChoice?: (choice: RoutingChoice) => void;
|
|
66
|
+
}): ReasoningProvider;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rule-based model routing (FEAT-035.3, N-03 option B): a `ReasoningProvider` that picks among configured endpoints,
|
|
3
|
+
* outside the core runtime and without a new contract surface beyond the endpoint descriptors.
|
|
4
|
+
*
|
|
5
|
+
* Security floors (see the model routing evaluation):
|
|
6
|
+
* 1. **Residency and data class are hard constraints.** The endpoints considered are those declared for the required
|
|
7
|
+
* zone and data class; with none available the call fails `ProviderUnavailable` — it is never sent elsewhere.
|
|
8
|
+
* Constraints come from the deployment's `floors` (trusted: tenant, task) and the caller's `route` hints; a floor
|
|
9
|
+
* always wins over a hint, and routing never reads prompts or any model-generated text.
|
|
10
|
+
* 2. **Fallback only within the same floor set.** Rules order candidates; candidates are filtered by the floors first,
|
|
11
|
+
* so a fallback can never be an endpoint the primary was not allowed to be.
|
|
12
|
+
* 3. **Budget.** The reasoning capability reserves the call's tokens before this provider runs and settles after, so
|
|
13
|
+
* attempts (including failed ones) cannot exceed `budget.maxCostUnits`; every attempt is asked for no more
|
|
14
|
+
* than the request's `maxTokens`.
|
|
15
|
+
* 4. **Auditable choice.** `onChoice` receives the rule, endpoint and outcome of every attempt (identifiers only, never
|
|
16
|
+
* prompts or keys) for spans and the audit trail.
|
|
17
|
+
* 5. **Credentials per endpoint.** Each endpoint is its own provider with its own credential reference; the router
|
|
18
|
+
* shares nothing between them.
|
|
19
|
+
* 6. **Deterministic.** The same request and floors always give the same candidate order.
|
|
20
|
+
*/
|
|
21
|
+
import { AgentropyError, isAgentropyError, } from '@agentropy/core';
|
|
22
|
+
const FAILOVER = new Set(['ProviderUnavailable', 'Timeout', 'QuotaExceeded']);
|
|
23
|
+
export function routedReasoning(o) {
|
|
24
|
+
const byId = new Map(o.endpoints.map((e) => [e.id, e]));
|
|
25
|
+
if (byId.size !== o.endpoints.length)
|
|
26
|
+
throw new AgentropyError('InvalidConfiguration', 'Duplicate endpoint IDs');
|
|
27
|
+
for (const r of o.rules)
|
|
28
|
+
for (const id of r.endpoints)
|
|
29
|
+
if (!byId.has(id))
|
|
30
|
+
throw new AgentropyError('InvalidConfiguration', `Rule ${r.id} names unknown endpoint ${id}`);
|
|
31
|
+
const noRoute = () => new AgentropyError('ProviderUnavailable', 'No model endpoint satisfies the required residency and data class', { details: { kind: 'reasoning', reason: 'routing' } });
|
|
32
|
+
return {
|
|
33
|
+
id: o.id ?? 'routed',
|
|
34
|
+
async complete(request, ctx) {
|
|
35
|
+
const hint = request.route ?? {};
|
|
36
|
+
const floors = (await o.floors?.(ctx)) ?? {};
|
|
37
|
+
const zone = floors.zone ?? hint.zone;
|
|
38
|
+
const dataClass = floors.dataClass ?? hint.dataClass;
|
|
39
|
+
const rule = o.rules.find((r) => (r.when?.tier === undefined || r.when.tier === hint.tier) &&
|
|
40
|
+
(r.when?.latency === undefined || r.when.latency === hint.latency));
|
|
41
|
+
if (!rule)
|
|
42
|
+
throw noRoute();
|
|
43
|
+
// The floors filter first: nothing outside them is ever a candidate, primary or fallback.
|
|
44
|
+
const candidates = rule.endpoints
|
|
45
|
+
.map((id) => byId.get(id))
|
|
46
|
+
.filter((e) => (zone === undefined || e.zone === zone) &&
|
|
47
|
+
(dataClass === undefined || e.dataClasses.includes(dataClass)));
|
|
48
|
+
if (!candidates.length)
|
|
49
|
+
throw noRoute();
|
|
50
|
+
let last;
|
|
51
|
+
for (const [i, e] of candidates.entries()) {
|
|
52
|
+
try {
|
|
53
|
+
const result = await e.provider.complete(request, ctx);
|
|
54
|
+
o.onChoice?.({
|
|
55
|
+
ruleId: rule.id,
|
|
56
|
+
endpointId: e.id,
|
|
57
|
+
attempt: i + 1,
|
|
58
|
+
outcome: 'ok',
|
|
59
|
+
});
|
|
60
|
+
return result;
|
|
61
|
+
}
|
|
62
|
+
catch (err) {
|
|
63
|
+
const code = isAgentropyError(err) ? err.code : 'Internal';
|
|
64
|
+
o.onChoice?.({
|
|
65
|
+
ruleId: rule.id,
|
|
66
|
+
endpointId: e.id,
|
|
67
|
+
attempt: i + 1,
|
|
68
|
+
outcome: 'failed',
|
|
69
|
+
code,
|
|
70
|
+
});
|
|
71
|
+
// Only an outage, a timeout or a rate limit moves on to the next endpoint; anything else is the answer.
|
|
72
|
+
if (!FAILOVER.has(code))
|
|
73
|
+
throw err;
|
|
74
|
+
last = err;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
throw last;
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
package/dist/otel.d.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenTelemetry adapter for the observability port (observability contract, M2-10).
|
|
3
|
+
*
|
|
4
|
+
* Structural: pass the `@opentelemetry/api` module plus a Tracer and Meter from your SDK; Agentropy itself does not
|
|
5
|
+
* depend on OpenTelemetry packages. Remote parents and links are rebuilt from sanitized W3C traceparents.
|
|
6
|
+
*/
|
|
7
|
+
import { type Attributes, type Telemetry } from '@agentropy/core';
|
|
8
|
+
interface OtelSpanContext {
|
|
9
|
+
traceId: string;
|
|
10
|
+
spanId: string;
|
|
11
|
+
traceFlags: number;
|
|
12
|
+
isRemote?: boolean;
|
|
13
|
+
}
|
|
14
|
+
interface OtelSpan {
|
|
15
|
+
spanContext(): OtelSpanContext;
|
|
16
|
+
setAttributes(a: Attributes): unknown;
|
|
17
|
+
setStatus(s: {
|
|
18
|
+
code: number;
|
|
19
|
+
message?: string;
|
|
20
|
+
}): unknown;
|
|
21
|
+
end(): void;
|
|
22
|
+
}
|
|
23
|
+
interface OtelTracer {
|
|
24
|
+
startSpan(name: string, options: {
|
|
25
|
+
kind?: number;
|
|
26
|
+
attributes?: Attributes;
|
|
27
|
+
links?: {
|
|
28
|
+
context: OtelSpanContext;
|
|
29
|
+
}[];
|
|
30
|
+
}, context?: unknown): OtelSpan;
|
|
31
|
+
}
|
|
32
|
+
interface OtelMeter {
|
|
33
|
+
createCounter(name: string, o?: {
|
|
34
|
+
unit?: string;
|
|
35
|
+
}): {
|
|
36
|
+
add(v: number, a?: Attributes): void;
|
|
37
|
+
};
|
|
38
|
+
createHistogram(name: string, o?: {
|
|
39
|
+
unit?: string;
|
|
40
|
+
}): {
|
|
41
|
+
record(v: number, a?: Attributes): void;
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/** The parts of `@opentelemetry/api` the adapter uses. */
|
|
45
|
+
export interface OtelApi {
|
|
46
|
+
ROOT_CONTEXT: unknown;
|
|
47
|
+
trace: {
|
|
48
|
+
setSpanContext(context: unknown, spanContext: OtelSpanContext): unknown;
|
|
49
|
+
};
|
|
50
|
+
SpanKind: Record<'INTERNAL' | 'SERVER' | 'CLIENT' | 'PRODUCER' | 'CONSUMER', number>;
|
|
51
|
+
SpanStatusCode: {
|
|
52
|
+
ERROR: number;
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
export declare function openTelemetry(o: {
|
|
56
|
+
api: OtelApi;
|
|
57
|
+
tracer: OtelTracer;
|
|
58
|
+
meter?: OtelMeter;
|
|
59
|
+
}): Telemetry;
|
|
60
|
+
export {};
|
package/dist/otel.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenTelemetry adapter for the observability port (observability contract, M2-10).
|
|
3
|
+
*
|
|
4
|
+
* Structural: pass the `@opentelemetry/api` module plus a Tracer and Meter from your SDK; Agentropy itself does not
|
|
5
|
+
* depend on OpenTelemetry packages. Remote parents and links are rebuilt from sanitized W3C traceparents.
|
|
6
|
+
*/
|
|
7
|
+
import { formatTraceparent, parseTraceparent, } from '@agentropy/core';
|
|
8
|
+
const remote = (traceparent) => {
|
|
9
|
+
const p = parseTraceparent(traceparent);
|
|
10
|
+
return p
|
|
11
|
+
? {
|
|
12
|
+
traceId: p.traceId,
|
|
13
|
+
spanId: p.spanId,
|
|
14
|
+
traceFlags: p.sampled ? 1 : 0,
|
|
15
|
+
isRemote: true,
|
|
16
|
+
}
|
|
17
|
+
: undefined;
|
|
18
|
+
};
|
|
19
|
+
export function openTelemetry(o) {
|
|
20
|
+
const counters = new Map();
|
|
21
|
+
const histograms = new Map();
|
|
22
|
+
const kinds = {
|
|
23
|
+
internal: o.api.SpanKind.INTERNAL,
|
|
24
|
+
server: o.api.SpanKind.SERVER,
|
|
25
|
+
client: o.api.SpanKind.CLIENT,
|
|
26
|
+
producer: o.api.SpanKind.PRODUCER,
|
|
27
|
+
consumer: o.api.SpanKind.CONSUMER,
|
|
28
|
+
};
|
|
29
|
+
return {
|
|
30
|
+
startSpan(name, options = {}) {
|
|
31
|
+
const parent = options.parent ? remote(options.parent) : undefined;
|
|
32
|
+
const ctx = parent
|
|
33
|
+
? o.api.trace.setSpanContext(o.api.ROOT_CONTEXT, parent)
|
|
34
|
+
: o.api.ROOT_CONTEXT;
|
|
35
|
+
const links = (options.links ?? [])
|
|
36
|
+
.map(remote)
|
|
37
|
+
.filter((c) => !!c)
|
|
38
|
+
.map((context) => ({ context }));
|
|
39
|
+
const span = o.tracer.startSpan(name, {
|
|
40
|
+
kind: kinds[options.kind ?? 'internal'],
|
|
41
|
+
...(options.attributes ? { attributes: options.attributes } : {}),
|
|
42
|
+
...(links.length ? { links } : {}),
|
|
43
|
+
}, ctx);
|
|
44
|
+
const sc = span.spanContext();
|
|
45
|
+
return {
|
|
46
|
+
traceparent: /^0+$/.test(sc.traceId)
|
|
47
|
+
? undefined
|
|
48
|
+
: formatTraceparent(sc.traceId, sc.spanId, (sc.traceFlags & 1) === 1),
|
|
49
|
+
setAttributes: (a) => void span.setAttributes(a),
|
|
50
|
+
fail: (code) => void (span.setAttributes({ 'agentropy.error.code': code }),
|
|
51
|
+
span.setStatus({ code: o.api.SpanStatusCode.ERROR, message: code })),
|
|
52
|
+
end: () => span.end(),
|
|
53
|
+
};
|
|
54
|
+
},
|
|
55
|
+
count(name, value, attributes) {
|
|
56
|
+
if (!o.meter)
|
|
57
|
+
return;
|
|
58
|
+
let c = counters.get(name);
|
|
59
|
+
if (!c)
|
|
60
|
+
counters.set(name, (c = o.meter.createCounter(name)));
|
|
61
|
+
c.add(value, attributes);
|
|
62
|
+
},
|
|
63
|
+
record(name, value, attributes) {
|
|
64
|
+
if (!o.meter)
|
|
65
|
+
return;
|
|
66
|
+
let h = histograms.get(name);
|
|
67
|
+
if (!h)
|
|
68
|
+
histograms.set(name, (h = o.meter.createHistogram(name, { unit: 'ms' })));
|
|
69
|
+
h.record(value, attributes);
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
}
|
package/dist/outbox.d.ts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Outbox relay and TaskEvent streams (messaging contract "Publication and inbox reconciliation", R-29, AC-19).
|
|
3
|
+
*
|
|
4
|
+
* Transitions and their outbox rows commit together (TaskService). The relay leases nothing: it reads unpublished
|
|
5
|
+
* rows in commit order, hands each to every consumer and only then marks it published. A crash anywhere before
|
|
6
|
+
* the mark re-delivers the row after restart, so delivery is at-least-once and consumers deduplicate by event ID
|
|
7
|
+
* (or by the `(revision, sequence)` pair). No external exactly-once is claimed.
|
|
8
|
+
*
|
|
9
|
+
* With a leader lease (`relayId`, several workers on one store) only the leader delivers to `consumers` and marks
|
|
10
|
+
* rows published. `localConsumers` (in-process signals such as subscription wake-ups) are fed by every relay,
|
|
11
|
+
* leader or not, by following the outbox in seq order after a cursor; seq order is commit order, so the cursor
|
|
12
|
+
* never skips a row (FEAT-032.5).
|
|
13
|
+
*/
|
|
14
|
+
import { type Store, type TaskEvent, type TrustedPrincipal, type Telemetry } from '@agentropy/core';
|
|
15
|
+
import type { OutboxRecord, TaskService } from './task-service.js';
|
|
16
|
+
/** A published TaskEvent with routing context for consumers. */
|
|
17
|
+
export interface PublishedEvent extends TaskEvent {
|
|
18
|
+
tenantId: string;
|
|
19
|
+
correlationId: string;
|
|
20
|
+
}
|
|
21
|
+
export interface EventConsumer {
|
|
22
|
+
readonly id: string;
|
|
23
|
+
/** Must be idempotent per `eventId`: the relay re-delivers after a crash before the published mark. */
|
|
24
|
+
handle(event: PublishedEvent): Promise<void>;
|
|
25
|
+
}
|
|
26
|
+
/** Structural fault hook (the testkit FaultInjector satisfies it); production passes nothing. */
|
|
27
|
+
export interface FaultHook {
|
|
28
|
+
checkpoint(operation: string): void;
|
|
29
|
+
}
|
|
30
|
+
export declare function toTaskEvent(r: OutboxRecord): PublishedEvent;
|
|
31
|
+
export interface OutboxRelayOptions {
|
|
32
|
+
store: Store;
|
|
33
|
+
consumers?: EventConsumer[];
|
|
34
|
+
/** Rows read per batch. */
|
|
35
|
+
batchSize?: number;
|
|
36
|
+
/**
|
|
37
|
+
* Longest a drain call keeps delivering (default 5000 ms, measured with `now`): a backlog after an outage is spread
|
|
38
|
+
* over several calls, in order, instead of one long tick. At least one row is delivered per call. Keep it well
|
|
39
|
+
* under `leaseMs`.
|
|
40
|
+
*/
|
|
41
|
+
drainBudgetMs?: number;
|
|
42
|
+
faults?: FaultHook;
|
|
43
|
+
/**
|
|
44
|
+
* Relay identity for the leader lease (M2-06): with several relays on one store only the lease holder
|
|
45
|
+
* delivers, so per-task order holds; a crashed holder's lease expires and another relay replays its rows.
|
|
46
|
+
*/
|
|
47
|
+
relayId?: string;
|
|
48
|
+
/**
|
|
49
|
+
* Consumers every relay feeds, leader or not (in-process signals; must not have shared side effects). Without
|
|
50
|
+
* `relayId` they are fed together with `consumers`.
|
|
51
|
+
*/
|
|
52
|
+
localConsumers?: EventConsumer[];
|
|
53
|
+
/** Leader lease length (default 30 s). */
|
|
54
|
+
leaseMs?: number;
|
|
55
|
+
/**
|
|
56
|
+
* Off by default: a row that keeps failing holds back every later row (ordering is kept). With a number, a row
|
|
57
|
+
* whose delivery failed that many times is given up on: marked published and `poisoned` (counted as
|
|
58
|
+
* `agentropy.outbox.poisoned`) so delivery goes on. A consumer that missed it is repaired by reconciliation
|
|
59
|
+
* (`rebuildInbox` for the inbox); other consumers must be able to tolerate a gap.
|
|
60
|
+
*/
|
|
61
|
+
poisonAfter?: number;
|
|
62
|
+
/** Delivery lag and terminal-outcome metrics, recorded once per published row. */
|
|
63
|
+
telemetry?: Telemetry;
|
|
64
|
+
now?: () => string;
|
|
65
|
+
}
|
|
66
|
+
export declare class OutboxRelay {
|
|
67
|
+
private readonly o;
|
|
68
|
+
private readonly consumers;
|
|
69
|
+
private readonly local;
|
|
70
|
+
private draining?;
|
|
71
|
+
/** Seq of the last row handed to local consumers (lease mode); `undefined` until the first follow. */
|
|
72
|
+
private cursor;
|
|
73
|
+
constructor(o: OutboxRelayOptions);
|
|
74
|
+
register(consumer: EventConsumer): void;
|
|
75
|
+
private observe;
|
|
76
|
+
/**
|
|
77
|
+
* Rows that consumers keep failing on (`attempts` at or above `minAttempts`). Delivery is in order, so the oldest
|
|
78
|
+
* of them holds back every later row: this is what an operator or a readiness probe looks at (FEAT-039.4).
|
|
79
|
+
*/
|
|
80
|
+
stuck(minAttempts?: number): Promise<{
|
|
81
|
+
eventId: string;
|
|
82
|
+
attempts: number;
|
|
83
|
+
occurredAt: string;
|
|
84
|
+
lastError?: string;
|
|
85
|
+
}[]>;
|
|
86
|
+
/** Publish pending rows in commit order; stops at the first failing row so order is preserved. Returns rows published. */
|
|
87
|
+
drain(): Promise<number>;
|
|
88
|
+
/** Acquire or renew the relay leader lease; false while another relay holds a live lease. */
|
|
89
|
+
private lead;
|
|
90
|
+
private drainOnce;
|
|
91
|
+
/** Hands every committed row after the cursor to the local consumers, published or not. */
|
|
92
|
+
private follow;
|
|
93
|
+
private publish;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Live TaskEvent fan-out for `AgentService.subscribe`: replays committed events from the outbox, then follows
|
|
97
|
+
* relay deliveries. Duplicates and replays at or below the last seen `(revision, sequence)` are dropped (AC-17).
|
|
98
|
+
*/
|
|
99
|
+
export declare class TaskEventStream implements EventConsumer {
|
|
100
|
+
private readonly tasks;
|
|
101
|
+
readonly id = "task-event-stream";
|
|
102
|
+
private readonly listeners;
|
|
103
|
+
constructor(tasks: TaskService);
|
|
104
|
+
handle(event: PublishedEvent): Promise<void>;
|
|
105
|
+
/**
|
|
106
|
+
* Events of one visible task after `from`, ending after its terminal event, or as soon as `abort` fires (the
|
|
107
|
+
* subscription is released at once, not at the task's next event).
|
|
108
|
+
*/
|
|
109
|
+
subscribe(taskId: string, caller: TrustedPrincipal, from?: {
|
|
110
|
+
revision: number;
|
|
111
|
+
sequence: number;
|
|
112
|
+
}, abort?: AbortSignal): AsyncIterable<TaskEvent>;
|
|
113
|
+
/** Drops one listener, and the task's entry with the last one: the map must not grow with every task ever followed. */
|
|
114
|
+
private release;
|
|
115
|
+
private signal;
|
|
116
|
+
}
|