@agentropy/runtime 0.0.0-bootstrap.0 → 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 +38 -1
- 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 +41 -5
package/dist/quotas.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-tenant quotas (M2-11, R-16): limits evaluated inside the accepting transaction, so concurrent requests cannot
|
|
3
|
+
* overshoot. A quota refusal is `QuotaExceeded` (retryable, `limit` category) and only affects the tenant that hit
|
|
4
|
+
* it. Idempotent replays of already accepted requests are answered before quotas are checked.
|
|
5
|
+
*/
|
|
6
|
+
import { AgentropyError } from '@agentropy/core';
|
|
7
|
+
/** Statuses of a task that has not ended. */
|
|
8
|
+
const LIVE = ['created', 'assigned', 'running', 'waiting'];
|
|
9
|
+
const exceeded = (quota, limit) => new AgentropyError('QuotaExceeded', `Tenant quota ${quota} (${limit}) reached`, {
|
|
10
|
+
details: { quota, limit },
|
|
11
|
+
});
|
|
12
|
+
export async function checkTaskQuota(tx, tenantId, quota, now) {
|
|
13
|
+
if (quota?.maxActiveTasks === undefined &&
|
|
14
|
+
quota?.maxAcceptsPerMinute === undefined)
|
|
15
|
+
return;
|
|
16
|
+
// Counted through the `status` and `createdAt` indexes, each read stopping at the limit: a tenant's history of
|
|
17
|
+
// finished tasks costs nothing here (FEAT-039.3).
|
|
18
|
+
if (quota.maxActiveTasks !== undefined) {
|
|
19
|
+
let active = 0;
|
|
20
|
+
for (const status of LIVE) {
|
|
21
|
+
active += (await tx.find('tasks', {
|
|
22
|
+
where: { tenantId, status },
|
|
23
|
+
limit: quota.maxActiveTasks - active,
|
|
24
|
+
})).length;
|
|
25
|
+
if (active >= quota.maxActiveTasks)
|
|
26
|
+
throw exceeded('maxActiveTasks', quota.maxActiveTasks);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
if (quota.maxAcceptsPerMinute !== undefined) {
|
|
30
|
+
const since = new Date(Date.parse(now) - 60_000).toISOString();
|
|
31
|
+
// `createdAt > since`: the range is inclusive, so the boundary row is excluded after the read.
|
|
32
|
+
const recent = (await tx.find('tasks', {
|
|
33
|
+
where: { tenantId },
|
|
34
|
+
range: { field: 'createdAt', gte: since },
|
|
35
|
+
limit: quota.maxAcceptsPerMinute + 1,
|
|
36
|
+
})).filter((t) => t.value.createdAt > since);
|
|
37
|
+
if (recent.length >= quota.maxAcceptsPerMinute)
|
|
38
|
+
throw exceeded('maxAcceptsPerMinute', quota.maxAcceptsPerMinute);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export async function checkInstanceQuota(tx, tenantId, quota) {
|
|
42
|
+
if (quota?.maxInstances === undefined)
|
|
43
|
+
return;
|
|
44
|
+
const live = (await tx.find('instances', { where: { tenantId } })).filter((i) => i.value.state !== 'retired').length;
|
|
45
|
+
if (live >= quota.maxInstances)
|
|
46
|
+
throw exceeded('maxInstances', quota.maxInstances);
|
|
47
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `reasoning.complete` backed by a ReasoningProvider (M2-08, R-35), with two runtime-enforced bounds:
|
|
3
|
+
*
|
|
4
|
+
* - **Bounded tools:** a request may offer the model only tools pinned in the task's acceptance snapshot; the model
|
|
5
|
+
* can *propose* calls (`toolCalls`) but never execute them — execution goes through `tool-use.call`, which applies
|
|
6
|
+
* pins, policy, audit and idempotency.
|
|
7
|
+
* - **Budget:** with `budget.maxCostUnits` on the task, cost units are model tokens. A call is refused with
|
|
8
|
+
* `BudgetExceeded` once the budget is spent, and `maxTokens` is capped to what remains. Usage is stored per task.
|
|
9
|
+
*
|
|
10
|
+
* `openAICompatibleReasoning` speaks the widely implemented Chat Completions wire format (OpenAI, gateways and
|
|
11
|
+
* proxies such as LiteLLM or agentgateway, vLLM, Ollama). The API key is resolved per call through a
|
|
12
|
+
* CredentialProvider and never stored.
|
|
13
|
+
*/
|
|
14
|
+
import { type CapabilityInvocationContext, type CredentialProvider, type ReasoningProvider } from '@agentropy/core';
|
|
15
|
+
import type { TaskService } from './task-service.js';
|
|
16
|
+
import type { InMemoryToolRegistry } from './tools.js';
|
|
17
|
+
export declare function reasoningOperationHandlers(o: {
|
|
18
|
+
tasks: TaskService;
|
|
19
|
+
provider: ReasoningProvider;
|
|
20
|
+
tools?: InMemoryToolRegistry;
|
|
21
|
+
/** Default and maximum `maxTokens` per call (default 1,024 / 8,192). */
|
|
22
|
+
defaultMaxTokens?: number;
|
|
23
|
+
maxTokensCap?: number;
|
|
24
|
+
}): Record<string, (input: unknown, ctx: CapabilityInvocationContext) => Promise<unknown>>;
|
|
25
|
+
type FetchLike = (url: string, init: {
|
|
26
|
+
method: string;
|
|
27
|
+
headers: Record<string, string>;
|
|
28
|
+
body: string;
|
|
29
|
+
signal: AbortSignal;
|
|
30
|
+
}) => Promise<{
|
|
31
|
+
status: number;
|
|
32
|
+
json(): Promise<unknown>;
|
|
33
|
+
text?(): Promise<string>;
|
|
34
|
+
headers?: {
|
|
35
|
+
get(name: string): string | null;
|
|
36
|
+
};
|
|
37
|
+
body?: {
|
|
38
|
+
cancel(): Promise<unknown>;
|
|
39
|
+
} | null;
|
|
40
|
+
}>;
|
|
41
|
+
/** Chat Completions client (OpenAI-compatible wire format). */
|
|
42
|
+
export declare function openAICompatibleReasoning(o: {
|
|
43
|
+
baseUrl: string;
|
|
44
|
+
model: string;
|
|
45
|
+
/** Opaque credential reference resolved per call (e.g. `openai-api-key`); omit for keyless local servers. */
|
|
46
|
+
credentialRef?: string;
|
|
47
|
+
credentials?: CredentialProvider;
|
|
48
|
+
fetch?: FetchLike;
|
|
49
|
+
/** One deadline for the call, headers and body (default 60 s). */
|
|
50
|
+
timeoutMs?: number;
|
|
51
|
+
/** Largest reply body read (default 4 MiB); a larger one is `ProviderUnavailable`. */
|
|
52
|
+
maxResponseBytes?: number;
|
|
53
|
+
}): ReasoningProvider;
|
|
54
|
+
export {};
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `reasoning.complete` backed by a ReasoningProvider (M2-08, R-35), with two runtime-enforced bounds:
|
|
3
|
+
*
|
|
4
|
+
* - **Bounded tools:** a request may offer the model only tools pinned in the task's acceptance snapshot; the model
|
|
5
|
+
* can *propose* calls (`toolCalls`) but never execute them — execution goes through `tool-use.call`, which applies
|
|
6
|
+
* pins, policy, audit and idempotency.
|
|
7
|
+
* - **Budget:** with `budget.maxCostUnits` on the task, cost units are model tokens. A call is refused with
|
|
8
|
+
* `BudgetExceeded` once the budget is spent, and `maxTokens` is capped to what remains. Usage is stored per task.
|
|
9
|
+
*
|
|
10
|
+
* `openAICompatibleReasoning` speaks the widely implemented Chat Completions wire format (OpenAI, gateways and
|
|
11
|
+
* proxies such as LiteLLM or agentgateway, vLLM, Ollama). The API key is resolved per call through a
|
|
12
|
+
* CredentialProvider and never stored.
|
|
13
|
+
*/
|
|
14
|
+
import { AgentropyError, isAgentropyError, } from '@agentropy/core';
|
|
15
|
+
import { ReplyTooLarge, readBoundedJson } from './bounded-body.js';
|
|
16
|
+
/** Routing hints are plain identifiers; anything else is dropped rather than passed on. */
|
|
17
|
+
function routeHint(r) {
|
|
18
|
+
if (!r || typeof r !== 'object')
|
|
19
|
+
return undefined;
|
|
20
|
+
const out = {};
|
|
21
|
+
const v = r;
|
|
22
|
+
for (const k of ['zone', 'dataClass', 'tier'])
|
|
23
|
+
if (typeof v[k] === 'string' && /^[\w.-]{1,64}$/.test(v[k]))
|
|
24
|
+
out[k] = v[k];
|
|
25
|
+
if (v['latency'] === 'low' || v['latency'] === 'normal')
|
|
26
|
+
out.latency = v['latency'];
|
|
27
|
+
return Object.keys(out).length ? out : undefined;
|
|
28
|
+
}
|
|
29
|
+
/** Tool IDs → provider-safe names and back (`finance.payout` → `finance_payout`). */
|
|
30
|
+
const toolName = (id) => id.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 64);
|
|
31
|
+
export function reasoningOperationHandlers(o) {
|
|
32
|
+
return {
|
|
33
|
+
complete: async (raw, ctx) => {
|
|
34
|
+
const input = (raw ?? {});
|
|
35
|
+
const messages = input.messages ?? [
|
|
36
|
+
...(input.system
|
|
37
|
+
? [{ role: 'system', content: input.system }]
|
|
38
|
+
: []),
|
|
39
|
+
...(typeof input.prompt === 'string'
|
|
40
|
+
? [{ role: 'user', content: input.prompt }]
|
|
41
|
+
: []),
|
|
42
|
+
];
|
|
43
|
+
if (!messages.length ||
|
|
44
|
+
messages.some((m) => !['system', 'user', 'assistant'].includes(m?.role) ||
|
|
45
|
+
typeof m.content !== 'string'))
|
|
46
|
+
throw new AgentropyError('SchemaViolation', 'reasoning.complete needs a prompt or messages');
|
|
47
|
+
const task = await o.tasks.o.store.transaction((tx) => tx.get('tasks', ctx.taskId));
|
|
48
|
+
if (!task || task.value.tenantId !== ctx.tenantId)
|
|
49
|
+
throw new AgentropyError('NotFound', 'Task not found');
|
|
50
|
+
// Bounded tools: only pins from the acceptance snapshot.
|
|
51
|
+
const byName = new Map();
|
|
52
|
+
const tools = [];
|
|
53
|
+
for (const id of input.tools ?? []) {
|
|
54
|
+
const pin = task.value.snapshot.tools?.find((p) => p.toolId === id);
|
|
55
|
+
// The stored status (FIX-084): a tool suspended or revoked on another worker since acceptance is not offered.
|
|
56
|
+
const record = pin
|
|
57
|
+
? await o.tools?.refreshed({
|
|
58
|
+
id: pin.toolId,
|
|
59
|
+
version: pin.toolVersion,
|
|
60
|
+
})
|
|
61
|
+
: undefined;
|
|
62
|
+
if (!pin || !record)
|
|
63
|
+
throw new AgentropyError('CapabilityNotDeclared', `Tool ${id} is not pinned for this task`, { details: { id } });
|
|
64
|
+
if (record.status !== 'active')
|
|
65
|
+
throw new AgentropyError('PermissionDenied', `Tool ${id} is ${record.status}`, { details: { status: record.status } });
|
|
66
|
+
const name = toolName(id);
|
|
67
|
+
// Two tool IDs that map to one function name would hand the handler the wrong tool back.
|
|
68
|
+
if (byName.has(name) && byName.get(name) !== id)
|
|
69
|
+
throw new AgentropyError('InvalidConfiguration', `Tools ${byName.get(name)} and ${id} map to the same function name`, { details: { reason: 'toolName' } });
|
|
70
|
+
byName.set(name, id);
|
|
71
|
+
tools.push({
|
|
72
|
+
name,
|
|
73
|
+
description: record.descriptor.description,
|
|
74
|
+
inputSchema: record.descriptor.inputSchema,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
// Budget: tokens spent so far (and reserved by this activation's calls in flight) against maxCostUnits. The
|
|
78
|
+
// check and the reservation are one transaction, so concurrent calls cannot overspend together.
|
|
79
|
+
const budget = task.value.budget?.maxCostUnits;
|
|
80
|
+
const cap = o.maxTokensCap ?? 8_192;
|
|
81
|
+
const wanted = Math.min(input.maxTokens ?? o.defaultMaxTokens ?? 1_024, cap);
|
|
82
|
+
const maxTokens = await o.tasks.o.store.transaction(async (tx) => {
|
|
83
|
+
const usage = await tx.get('usage', ctx.taskId);
|
|
84
|
+
const spent = usage
|
|
85
|
+
? usage.value.inputTokens + usage.value.outputTokens
|
|
86
|
+
: 0;
|
|
87
|
+
const mine = usage?.value.reserved?.executionId === ctx.executionId
|
|
88
|
+
? usage.value.reserved.tokens
|
|
89
|
+
: 0;
|
|
90
|
+
if (budget !== undefined && spent + mine >= budget)
|
|
91
|
+
throw new AgentropyError('BudgetExceeded', 'The task has spent its reasoning budget', { details: { budget, spent: spent + mine } });
|
|
92
|
+
const grant = budget === undefined
|
|
93
|
+
? wanted
|
|
94
|
+
: Math.min(wanted, budget - spent - mine);
|
|
95
|
+
const next = {
|
|
96
|
+
taskId: ctx.taskId,
|
|
97
|
+
inputTokens: usage?.value.inputTokens ?? 0,
|
|
98
|
+
outputTokens: usage?.value.outputTokens ?? 0,
|
|
99
|
+
calls: usage?.value.calls ?? 0,
|
|
100
|
+
reserved: { executionId: ctx.executionId, tokens: mine + grant },
|
|
101
|
+
};
|
|
102
|
+
if (usage)
|
|
103
|
+
await tx.update('usage', usage.id, usage.revision, next);
|
|
104
|
+
else
|
|
105
|
+
await tx.insert('usage', ctx.taskId, next);
|
|
106
|
+
return grant;
|
|
107
|
+
});
|
|
108
|
+
const release = (used) => o.tasks.o.store.transaction(async (tx) => {
|
|
109
|
+
const cur = await tx.get('usage', ctx.taskId);
|
|
110
|
+
if (!cur)
|
|
111
|
+
return;
|
|
112
|
+
const held = cur.value.reserved?.executionId === ctx.executionId
|
|
113
|
+
? cur.value.reserved.tokens
|
|
114
|
+
: 0;
|
|
115
|
+
const { reserved: _old, ...rest } = cur.value;
|
|
116
|
+
void _old;
|
|
117
|
+
const left = Math.max(0, held - maxTokens);
|
|
118
|
+
await tx.update('usage', cur.id, cur.revision, {
|
|
119
|
+
...rest,
|
|
120
|
+
inputTokens: rest.inputTokens + (used?.input ?? 0),
|
|
121
|
+
outputTokens: rest.outputTokens + (used?.output ?? 0),
|
|
122
|
+
calls: rest.calls + (used ? 1 : 0),
|
|
123
|
+
...(left > 0
|
|
124
|
+
? { reserved: { executionId: ctx.executionId, tokens: left } }
|
|
125
|
+
: {}),
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
let result;
|
|
129
|
+
try {
|
|
130
|
+
result = await o.provider.complete({
|
|
131
|
+
messages,
|
|
132
|
+
maxTokens,
|
|
133
|
+
...(input.temperature !== undefined
|
|
134
|
+
? { temperature: input.temperature }
|
|
135
|
+
: {}),
|
|
136
|
+
...(tools.length ? { tools } : {}),
|
|
137
|
+
...(routeHint(input.route)
|
|
138
|
+
? { route: routeHint(input.route) }
|
|
139
|
+
: {}),
|
|
140
|
+
}, { tenantId: ctx.tenantId, taskId: ctx.taskId, signal: ctx.signal });
|
|
141
|
+
}
|
|
142
|
+
catch (err) {
|
|
143
|
+
// A call that failed spent nothing we know of: give its reservation back.
|
|
144
|
+
await release(undefined).catch(() => undefined);
|
|
145
|
+
throw err;
|
|
146
|
+
}
|
|
147
|
+
await release({
|
|
148
|
+
input: result.usage.inputTokens,
|
|
149
|
+
output: result.usage.outputTokens,
|
|
150
|
+
});
|
|
151
|
+
const toolCalls = (result.toolCalls ?? []).map((c) => {
|
|
152
|
+
const id = byName.get(c.name);
|
|
153
|
+
if (!id)
|
|
154
|
+
throw new AgentropyError('SchemaViolation', 'Model proposed a tool that was not offered', { details: { reason: 'unofferedTool' } });
|
|
155
|
+
return { toolId: id, input: c.input };
|
|
156
|
+
});
|
|
157
|
+
return {
|
|
158
|
+
text: result.text,
|
|
159
|
+
...(toolCalls.length ? { toolCalls } : {}),
|
|
160
|
+
usage: result.usage,
|
|
161
|
+
model: result.model,
|
|
162
|
+
};
|
|
163
|
+
},
|
|
164
|
+
plan: async () => {
|
|
165
|
+
throw new AgentropyError('UnsupportedOperation', 'reasoning.plan is not offered by this provider; use complete');
|
|
166
|
+
},
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
/** Chat Completions client (OpenAI-compatible wire format). */
|
|
170
|
+
export function openAICompatibleReasoning(o) {
|
|
171
|
+
const doFetch = o.fetch ?? ((url, init) => fetch(url, init));
|
|
172
|
+
const url = `${o.baseUrl.replace(/\/+$/, '')}/chat/completions`;
|
|
173
|
+
return {
|
|
174
|
+
id: 'openai-compatible',
|
|
175
|
+
async complete(req, ctx) {
|
|
176
|
+
const headers = {
|
|
177
|
+
'content-type': 'application/json',
|
|
178
|
+
};
|
|
179
|
+
if (o.credentialRef) {
|
|
180
|
+
if (!o.credentials)
|
|
181
|
+
throw new AgentropyError('InvalidConfiguration', 'credentialRef needs a CredentialProvider');
|
|
182
|
+
const cred = (await o.credentials.resolve(o.credentialRef, {
|
|
183
|
+
tenantId: ctx.tenantId,
|
|
184
|
+
principal: { id: 'runtime', type: 'service', tenantId: ctx.tenantId },
|
|
185
|
+
purpose: 'reasoning',
|
|
186
|
+
}));
|
|
187
|
+
if (!cred?.apiKey)
|
|
188
|
+
throw new AgentropyError('AuthorityExpired', 'Model credential unavailable', {
|
|
189
|
+
details: { kind: 'credential', status: 'expired' },
|
|
190
|
+
});
|
|
191
|
+
headers.authorization = `Bearer ${cred.apiKey}`;
|
|
192
|
+
}
|
|
193
|
+
const body = {
|
|
194
|
+
model: o.model,
|
|
195
|
+
messages: req.messages,
|
|
196
|
+
max_tokens: req.maxTokens,
|
|
197
|
+
...(req.temperature !== undefined
|
|
198
|
+
? { temperature: req.temperature }
|
|
199
|
+
: {}),
|
|
200
|
+
...(req.tools?.length
|
|
201
|
+
? {
|
|
202
|
+
tools: req.tools.map((t) => ({
|
|
203
|
+
type: 'function',
|
|
204
|
+
function: {
|
|
205
|
+
name: t.name,
|
|
206
|
+
description: t.description,
|
|
207
|
+
parameters: t.inputSchema === true ? { type: 'object' } : t.inputSchema,
|
|
208
|
+
},
|
|
209
|
+
})),
|
|
210
|
+
}
|
|
211
|
+
: {}),
|
|
212
|
+
};
|
|
213
|
+
const controller = new AbortController();
|
|
214
|
+
const onAbort = () => controller.abort(ctx.signal.reason);
|
|
215
|
+
ctx.signal.addEventListener('abort', onAbort, { once: true });
|
|
216
|
+
const timer = setTimeout(() => controller.abort(new Error('timeout')), o.timeoutMs ?? 60_000);
|
|
217
|
+
let res;
|
|
218
|
+
try {
|
|
219
|
+
res = await doFetch(url, {
|
|
220
|
+
method: 'POST',
|
|
221
|
+
headers,
|
|
222
|
+
body: JSON.stringify(body),
|
|
223
|
+
signal: controller.signal,
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
catch (err) {
|
|
227
|
+
clearTimeout(timer);
|
|
228
|
+
ctx.signal.removeEventListener('abort', onAbort);
|
|
229
|
+
if (isAgentropyError(err))
|
|
230
|
+
throw err;
|
|
231
|
+
throw controller.signal.aborted && !ctx.signal.aborted
|
|
232
|
+
? new AgentropyError('Timeout', 'Model call timed out', {
|
|
233
|
+
details: { kind: 'reasoning' },
|
|
234
|
+
})
|
|
235
|
+
: new AgentropyError('ProviderUnavailable', 'Model endpoint unreachable', {
|
|
236
|
+
details: { kind: 'reasoning' },
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
// The deadline and the caller's abort stay in force until the body has been read: a stalled body is a timeout.
|
|
240
|
+
try {
|
|
241
|
+
// Provider error bodies are not passed through (they can echo prompts or keys) and not read: release them.
|
|
242
|
+
if (res.status >= 400)
|
|
243
|
+
void res.body?.cancel().catch(() => undefined);
|
|
244
|
+
if (res.status === 401 || res.status === 403)
|
|
245
|
+
throw new AgentropyError('AuthorityExpired', 'Model provider rejected the credential', {
|
|
246
|
+
details: { kind: 'credential', status: 'expired' },
|
|
247
|
+
});
|
|
248
|
+
if (res.status === 429)
|
|
249
|
+
throw new AgentropyError('QuotaExceeded', 'Model provider rate limit', {
|
|
250
|
+
details: { kind: 'reasoning' },
|
|
251
|
+
});
|
|
252
|
+
if (res.status >= 500)
|
|
253
|
+
throw new AgentropyError('ProviderUnavailable', 'Model provider error', {
|
|
254
|
+
details: { kind: 'reasoning', status: res.status },
|
|
255
|
+
});
|
|
256
|
+
if (res.status >= 400)
|
|
257
|
+
throw new AgentropyError('SchemaViolation', 'Model provider refused the request', {
|
|
258
|
+
details: { kind: 'reasoning', status: res.status },
|
|
259
|
+
});
|
|
260
|
+
let parsed;
|
|
261
|
+
try {
|
|
262
|
+
parsed = await readBoundedJson(res, o.maxResponseBytes ?? 4 * 1024 * 1024, controller.signal);
|
|
263
|
+
}
|
|
264
|
+
catch (err) {
|
|
265
|
+
if (controller.signal.aborted && !ctx.signal.aborted)
|
|
266
|
+
throw new AgentropyError('Timeout', 'Model call timed out', {
|
|
267
|
+
details: { kind: 'reasoning' },
|
|
268
|
+
});
|
|
269
|
+
throw new AgentropyError('ProviderUnavailable', err instanceof ReplyTooLarge
|
|
270
|
+
? 'Model response too large'
|
|
271
|
+
: 'Malformed model response', { details: { kind: 'reasoning' } });
|
|
272
|
+
}
|
|
273
|
+
const json = (parsed ?? {});
|
|
274
|
+
const msg = json.choices?.[0]?.message;
|
|
275
|
+
if (!msg)
|
|
276
|
+
throw new AgentropyError('ProviderUnavailable', 'Malformed model response', {
|
|
277
|
+
details: { kind: 'reasoning' },
|
|
278
|
+
});
|
|
279
|
+
const toolCalls = (msg.tool_calls ?? []).map((c) => {
|
|
280
|
+
let parsed;
|
|
281
|
+
try {
|
|
282
|
+
parsed = JSON.parse(c.function?.arguments ?? '{}');
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
throw new AgentropyError('SchemaViolation', 'Model returned invalid tool arguments', {
|
|
286
|
+
details: { reason: 'toolArguments' },
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
return { name: c.function?.name ?? '', input: parsed };
|
|
290
|
+
});
|
|
291
|
+
return {
|
|
292
|
+
text: msg.content ?? '',
|
|
293
|
+
...(toolCalls.length ? { toolCalls } : {}),
|
|
294
|
+
usage: {
|
|
295
|
+
inputTokens: json.usage?.prompt_tokens ?? 0,
|
|
296
|
+
outputTokens: json.usage?.completion_tokens ?? 0,
|
|
297
|
+
},
|
|
298
|
+
model: json.model ?? o.model,
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
finally {
|
|
302
|
+
clearTimeout(timer);
|
|
303
|
+
ctx.signal.removeEventListener('abort', onAbort);
|
|
304
|
+
}
|
|
305
|
+
},
|
|
306
|
+
};
|
|
307
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/** Definition registry, instance directory and discovery (M1-03, R-01, R-06, AC-15). In-memory for M1. */
|
|
2
|
+
import { type AgentDefinition, type AgentInstance, type AgentProfile, type PolicyDecisionPoint, type Store, type StoreTx, type TrustedPrincipal, type VersionedRef } from '@agentropy/core';
|
|
3
|
+
import { type QuotaResolver } from './quotas.js';
|
|
4
|
+
export interface DiscoveryQuery {
|
|
5
|
+
id?: string;
|
|
6
|
+
capability?: string;
|
|
7
|
+
profile?: string;
|
|
8
|
+
text?: string;
|
|
9
|
+
}
|
|
10
|
+
export declare class DefinitionRegistry {
|
|
11
|
+
private readonly profiles;
|
|
12
|
+
private readonly byKey;
|
|
13
|
+
constructor(profiles: readonly AgentProfile[]);
|
|
14
|
+
/** Immutable registration: identical content is a no-op, different content for the same id@version is rejected. */
|
|
15
|
+
register(definition: AgentDefinition): AgentDefinition;
|
|
16
|
+
get(ref: VersionedRef): AgentDefinition | undefined;
|
|
17
|
+
require(ref: VersionedRef): AgentDefinition;
|
|
18
|
+
versions(id: string): string[];
|
|
19
|
+
/** Capability IDs a definition declares (profile required/defaults plus additions, minus removals). */
|
|
20
|
+
declaredCapabilities(def: AgentDefinition): string[];
|
|
21
|
+
/**
|
|
22
|
+
* Deterministic discovery: same query and same policy → same order (id asc, version desc).
|
|
23
|
+
* Definitions the caller may not see are omitted without disclosure; a PDP outage fails closed.
|
|
24
|
+
*/
|
|
25
|
+
discover(query: DiscoveryQuery, caller: TrustedPrincipal, pdp: PolicyDecisionPoint): Promise<VersionedRef[]>;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Written in the transaction of a lifecycle change (Security v1 revision 9): the facade turns it into the audit
|
|
29
|
+
* intent, so the change and its audit record commit together or not at all.
|
|
30
|
+
*/
|
|
31
|
+
export type InstanceAudit = (tx: StoreTx, change: {
|
|
32
|
+
instanceId: string;
|
|
33
|
+
from?: AgentInstance['state'];
|
|
34
|
+
to?: AgentInstance['state'];
|
|
35
|
+
ownerId?: string;
|
|
36
|
+
sharedWith?: number;
|
|
37
|
+
}) => Promise<void>;
|
|
38
|
+
export interface CreateInstanceRequest {
|
|
39
|
+
definition: VersionedRef;
|
|
40
|
+
ownerId: string;
|
|
41
|
+
idempotencyKey: string;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Logical agent identities, owner- and tenant-scoped (Agent v1; runtime contract §3). Every change is
|
|
45
|
+
* committed to the Store before it is acknowledged, so instances survive a restart (R-08).
|
|
46
|
+
*/
|
|
47
|
+
export declare class InstanceDirectory {
|
|
48
|
+
private readonly definitions;
|
|
49
|
+
private readonly store;
|
|
50
|
+
private readonly newId;
|
|
51
|
+
private readonly quotas?;
|
|
52
|
+
private seq;
|
|
53
|
+
constructor(definitions: DefinitionRegistry, store?: Store, newId?: () => string, quotas?: QuotaResolver | undefined);
|
|
54
|
+
create(req: CreateInstanceRequest, caller: TrustedPrincipal, audit?: InstanceAudit): Promise<AgentInstance>;
|
|
55
|
+
/**
|
|
56
|
+
* The instance `create` would make for this request, without storing it (FIX-063): a delegation by definition
|
|
57
|
+
* plans the instance, runs every refusal that can still happen, and stores it in the transaction that accepts the
|
|
58
|
+
* task (`insertPlanned`), so a refused delegation leaves nothing behind. The ID of an instance that already exists
|
|
59
|
+
* for the key is returned as it is (`stored`), so a retry gets the same instance.
|
|
60
|
+
*/
|
|
61
|
+
plan(req: CreateInstanceRequest, caller: TrustedPrincipal): Promise<{
|
|
62
|
+
instance: AgentInstance;
|
|
63
|
+
stored: boolean;
|
|
64
|
+
}>;
|
|
65
|
+
/** Stores an instance from `plan` in the caller's transaction, under the instance quota. */
|
|
66
|
+
insertPlanned(tx: StoreTx, req: CreateInstanceRequest, caller: TrustedPrincipal, instance: AgentInstance): Promise<void>;
|
|
67
|
+
private createKey;
|
|
68
|
+
/** Tenant-scoped lookup: another tenant's instance is indistinguishable from a missing one. */
|
|
69
|
+
get(instanceId: string, caller: TrustedPrincipal): Promise<AgentInstance>;
|
|
70
|
+
/** Tenant of an instance, for distinguishing cross-tenant targets (AC-09) from missing ones. */
|
|
71
|
+
tenantOf(instanceId: string): Promise<string | undefined>;
|
|
72
|
+
/** Internal (trusted) read used by the runtime, e.g. to defer wake-ups of suspended instances. */
|
|
73
|
+
stateOf(instanceId: string): Promise<AgentInstance['state'] | undefined>;
|
|
74
|
+
list(caller: TrustedPrincipal, ownerId?: string): Promise<AgentInstance[]>;
|
|
75
|
+
suspend(instanceId: string, caller: TrustedPrincipal, audit?: InstanceAudit): Promise<AgentInstance>;
|
|
76
|
+
resume(instanceId: string, caller: TrustedPrincipal, audit?: InstanceAudit): Promise<AgentInstance>;
|
|
77
|
+
/** Without force, retiring fails InvalidState while non-terminal tasks exist (checked by the caller-supplied guard). */
|
|
78
|
+
retire(instanceId: string, caller: TrustedPrincipal, opts?: {
|
|
79
|
+
force?: boolean;
|
|
80
|
+
hasActiveTasks?: () => boolean | Promise<boolean>;
|
|
81
|
+
audit?: InstanceAudit;
|
|
82
|
+
}): Promise<AgentInstance>;
|
|
83
|
+
/**
|
|
84
|
+
* Drain: stop accepting new tasks while existing tasks run to completion; the runtime retires the instance
|
|
85
|
+
* when its last non-terminal task ends (TaskService.terminate). Retires at once when nothing is active.
|
|
86
|
+
*/
|
|
87
|
+
drain(instanceId: string, caller: TrustedPrincipal, audit?: InstanceAudit): Promise<AgentInstance>;
|
|
88
|
+
/** Owner-only: replace who may delegate to the instance (D-08). Shares never cross the tenant boundary. */
|
|
89
|
+
share(instanceId: string, principalIds: string[], caller: TrustedPrincipal, audit?: InstanceAudit): Promise<AgentInstance>;
|
|
90
|
+
/**
|
|
91
|
+
* Audited definition upgrade or rollback (FEAT-028.3, D-07): the instance uses `version` for **future** tasks only;
|
|
92
|
+
* accepted tasks keep their acceptance snapshot. The target must be registered and of the same definition; the
|
|
93
|
+
* caller passes the instance revision it saw (compare-and-swap). Owner or trusted service only.
|
|
94
|
+
*/
|
|
95
|
+
upgrade(instanceId: string, change: {
|
|
96
|
+
version: string;
|
|
97
|
+
expectedRevision: number;
|
|
98
|
+
}, caller: TrustedPrincipal, audit: (tx: StoreTx, from: VersionedRef, to: VersionedRef) => Promise<void>): Promise<AgentInstance>;
|
|
99
|
+
private owned;
|
|
100
|
+
private move;
|
|
101
|
+
}
|