@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/app.js
ADDED
|
@@ -0,0 +1,541 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local single-process composition (M1, ADR-0017): wires the Store, registries, TaskService, runtime pool,
|
|
3
|
+
* wake-ups, outbox relay, inbox, human actions, audit forwarding and the built-in capability provider, and
|
|
4
|
+
* exposes the Agent v1 `AgentService` operations as one facade. Examples and embedding applications use this
|
|
5
|
+
* instead of assembling the services by hand. Trusted principals are supplied by the embedding ingress.
|
|
6
|
+
*/
|
|
7
|
+
import { randomUUID } from 'node:crypto';
|
|
8
|
+
import { AgentropyError, digestOf, enforcePolicy, BUILTIN_PROFILES, CAPABILITY_CATALOG, METRICS, TASK_MACHINE, isTerminal, toAgentropyError, validateAgentDefinition, } from '@agentropy/core';
|
|
9
|
+
import { AuditForwarder, AuditService, } from './audit.js';
|
|
10
|
+
import { HumanActionService, humanActionOperationHandlers, } from './human-actions.js';
|
|
11
|
+
import { InMemoryHandlerRegistry, InMemoryImplementationProviderRegistry, NativeImplementationProvider, } from './implementation.js';
|
|
12
|
+
import { InboxProjector, InboxService, inboxOperationHandlers, } from './inbox.js';
|
|
13
|
+
import { OutboxRelay, TaskEventStream } from './outbox.js';
|
|
14
|
+
import { resolveLimits } from './limits.js';
|
|
15
|
+
import { CachingPolicyDecisionPoint, recordPolicyInvalidation, } from './policy-cache.js';
|
|
16
|
+
import { memoryOperationHandlers } from './memory.js';
|
|
17
|
+
import { reasoningOperationHandlers } from './reasoning.js';
|
|
18
|
+
import { RemoteDelegationService } from './remote.js';
|
|
19
|
+
import { bridgeWorkflowCompletions, workflowOperationHandlers, } from './workflow.js';
|
|
20
|
+
import { DefinitionRegistry, InstanceDirectory, } from './registry.js';
|
|
21
|
+
import { AgentRuntime } from './runtime.js';
|
|
22
|
+
import { TaskService, } from './task-service.js';
|
|
23
|
+
import { FileSystemSkillLoader, PinnedSkillAccess, } from './skills.js';
|
|
24
|
+
import { ToolUseCapability, } from './tools.js';
|
|
25
|
+
import { BuiltinCapabilityProvider, WakeupService, coreOperationHandlers, } from './wakeups.js';
|
|
26
|
+
/** The largest delay a Node.js timer keeps; a longer one is shortened to 1 ms (FIX-086). */
|
|
27
|
+
const MAX_TIMER_MS = 2_147_483_647;
|
|
28
|
+
export function createLocalApp(o) {
|
|
29
|
+
const { skills: _skills, ...runtimeLimitFields } = o.runtime ?? {};
|
|
30
|
+
void _skills;
|
|
31
|
+
const limits = resolveLimits({
|
|
32
|
+
...runtimeLimitFields,
|
|
33
|
+
...(o.mailboxLimit ? { mailboxLimit: o.mailboxLimit } : {}),
|
|
34
|
+
...o.limits,
|
|
35
|
+
});
|
|
36
|
+
const now = o.now ?? (() => new Date().toISOString());
|
|
37
|
+
const store = o.store;
|
|
38
|
+
const definitions = new DefinitionRegistry(o.profiles ?? BUILTIN_PROFILES);
|
|
39
|
+
const instances = new InstanceDirectory(definitions, store, () => `inst-${randomUUID()}`, o.quotas);
|
|
40
|
+
const handlers = new InMemoryHandlerRegistry();
|
|
41
|
+
const implementations = new InMemoryImplementationProviderRegistry();
|
|
42
|
+
implementations.register(new NativeImplementationProvider(handlers));
|
|
43
|
+
const builtinContracts = CAPABILITY_CATALOG.map((c) => ({
|
|
44
|
+
id: c.id,
|
|
45
|
+
version: c.version,
|
|
46
|
+
...(c.id === 'durability' ? { level: store.durability } : {}),
|
|
47
|
+
}));
|
|
48
|
+
const tasks = new TaskService({
|
|
49
|
+
store,
|
|
50
|
+
definitions,
|
|
51
|
+
instances,
|
|
52
|
+
pdp: o.pdp,
|
|
53
|
+
...(o.grants ? { grants: o.grants } : {}),
|
|
54
|
+
now,
|
|
55
|
+
limits: {
|
|
56
|
+
maxDepth: limits.maxDepth,
|
|
57
|
+
maxFanOut: limits.maxFanOut,
|
|
58
|
+
maxInputBytes: limits.maxInputBytes,
|
|
59
|
+
},
|
|
60
|
+
...(o.faults ? { faults: o.faults } : {}),
|
|
61
|
+
...(o.telemetry ? { telemetry: o.telemetry } : {}),
|
|
62
|
+
...(o.quotas ? { quotas: o.quotas } : {}),
|
|
63
|
+
acceptance: {
|
|
64
|
+
contracts: CAPABILITY_CATALOG,
|
|
65
|
+
profiles: o.profiles ?? BUILTIN_PROFILES,
|
|
66
|
+
providers: [
|
|
67
|
+
{ id: 'builtin', version: '1.0.0', contracts: builtinContracts },
|
|
68
|
+
],
|
|
69
|
+
runtimeDurability: store.durability,
|
|
70
|
+
implementationProvider: (id, v) => implementations.find(id, v),
|
|
71
|
+
// The stored lifecycle status, not this process's memory: another worker may have activated or revoked a
|
|
72
|
+
// version (FIX-084).
|
|
73
|
+
toolVersions: async (id) => (await o.tools?.registry.refreshedVersions(id)) ?? [],
|
|
74
|
+
toolProviderRegistered: (id, v) => o.tools?.providers.has(id, v) ?? false,
|
|
75
|
+
skillVersions: async (id) => (await o.skills?.registry.refreshedVersions(id)) ?? [],
|
|
76
|
+
pdp: o.pdp,
|
|
77
|
+
now,
|
|
78
|
+
},
|
|
79
|
+
});
|
|
80
|
+
const wakeups = new WakeupService(tasks, instances, {
|
|
81
|
+
mailboxLimit: limits.mailboxLimit,
|
|
82
|
+
maxEventBytes: limits.maxEventBytes,
|
|
83
|
+
// A failing sweep (workflow poll, remote sync, human-action expiry) goes to the same hook as other contained
|
|
84
|
+
// failures of the pool (FIX-052).
|
|
85
|
+
...(o.runtime?.onError ? { onError: o.runtime.onError } : {}),
|
|
86
|
+
});
|
|
87
|
+
const inbox = new InboxService(tasks, {
|
|
88
|
+
...(o.inbox?.policy ? { policy: o.inbox.policy } : {}),
|
|
89
|
+
...(o.inbox?.preferences ? { preferences: o.inbox.preferences } : {}),
|
|
90
|
+
});
|
|
91
|
+
const projector = new InboxProjector(tasks, {
|
|
92
|
+
...(o.inbox?.policy ? { policy: o.inbox.policy } : {}),
|
|
93
|
+
...(o.inbox?.push ? { push: o.inbox.push } : {}),
|
|
94
|
+
});
|
|
95
|
+
const human = new HumanActionService(tasks, {
|
|
96
|
+
maxPromptBytes: limits.maxPromptBytes,
|
|
97
|
+
});
|
|
98
|
+
wakeups.addSweep(() => human.sweep());
|
|
99
|
+
const remote = o.communication
|
|
100
|
+
? new RemoteDelegationService({
|
|
101
|
+
tasks,
|
|
102
|
+
router: o.communication.router,
|
|
103
|
+
...(o.communication.sync ? { sync: o.communication.sync } : {}),
|
|
104
|
+
...(o.communication.timeoutMs !== undefined
|
|
105
|
+
? { timeoutMs: o.communication.timeoutMs }
|
|
106
|
+
: {}),
|
|
107
|
+
maxOutputBytes: limits.maxOutputBytes,
|
|
108
|
+
})
|
|
109
|
+
: undefined;
|
|
110
|
+
// Remote projections refresh before wake-ups are evaluated, so a parent waiting on a remote child wakes promptly.
|
|
111
|
+
// A network sweep: the scheduler loop starts it without waiting, so a slow peer cannot hold the tick (FIX-053).
|
|
112
|
+
if (remote)
|
|
113
|
+
wakeups.addSweep(() => remote.sync(), { background: true });
|
|
114
|
+
const stream = new TaskEventStream(tasks);
|
|
115
|
+
const relay = new OutboxRelay({
|
|
116
|
+
store,
|
|
117
|
+
consumers: [projector],
|
|
118
|
+
// Subscription wake-ups are per process: with a relay lease every worker still wakes its own subscribers.
|
|
119
|
+
localConsumers: [stream],
|
|
120
|
+
...(o.relay
|
|
121
|
+
? {
|
|
122
|
+
relayId: o.relay.relayId,
|
|
123
|
+
now,
|
|
124
|
+
...(o.relay.leaseMs ? { leaseMs: o.relay.leaseMs } : {}),
|
|
125
|
+
}
|
|
126
|
+
: {}),
|
|
127
|
+
...(o.outboxPoisonAfter ? { poisonAfter: o.outboxPoisonAfter } : {}),
|
|
128
|
+
...(o.telemetry ? { telemetry: o.telemetry, now } : {}),
|
|
129
|
+
...(o.faults ? { faults: o.faults } : {}),
|
|
130
|
+
});
|
|
131
|
+
const forwarder = o.audit
|
|
132
|
+
? new AuditForwarder({
|
|
133
|
+
store,
|
|
134
|
+
sink: o.audit,
|
|
135
|
+
now,
|
|
136
|
+
...(o.telemetry ? { telemetry: o.telemetry } : {}),
|
|
137
|
+
...(o.faults ? { faults: o.faults } : {}),
|
|
138
|
+
})
|
|
139
|
+
: undefined;
|
|
140
|
+
const toolHandlers = o.tools
|
|
141
|
+
? {
|
|
142
|
+
listTools: async (_input, ctx) => new ToolUseCapability(o.tools.executor, o.tools.registry, (await taskOf(ctx.taskId)).snapshot.tools).listTools(),
|
|
143
|
+
call: async (input, ctx) => new ToolUseCapability(o.tools.executor, o.tools.registry, (await taskOf(ctx.taskId)).snapshot.tools).call(input, {
|
|
144
|
+
tenantId: ctx.tenantId,
|
|
145
|
+
taskId: ctx.taskId,
|
|
146
|
+
executionId: ctx.executionId,
|
|
147
|
+
principal: {
|
|
148
|
+
id: ctx.principalId,
|
|
149
|
+
type: 'agent',
|
|
150
|
+
tenantId: ctx.tenantId,
|
|
151
|
+
...(ctx.delegatedAuthorityRef
|
|
152
|
+
? { delegatedAuthorityRef: ctx.delegatedAuthorityRef }
|
|
153
|
+
: {}),
|
|
154
|
+
},
|
|
155
|
+
signal: ctx.signal,
|
|
156
|
+
...(ctx.idempotencyKey
|
|
157
|
+
? { idempotencyKey: ctx.idempotencyKey }
|
|
158
|
+
: {}),
|
|
159
|
+
...(ctx.stepKey ? { stepKey: ctx.stepKey } : {}),
|
|
160
|
+
}),
|
|
161
|
+
}
|
|
162
|
+
: {};
|
|
163
|
+
function isRemote(taskId) {
|
|
164
|
+
return !!remote && taskId.includes(':');
|
|
165
|
+
}
|
|
166
|
+
function remoteOrFail() {
|
|
167
|
+
if (!remote)
|
|
168
|
+
throw new AgentropyError('NoCompatibleRoute', 'No communication router is configured for remote targets');
|
|
169
|
+
return remote;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* An instance lifecycle call (Security v1 revision 9): the caller's grant and a policy decision come first, so a
|
|
173
|
+
* denied call changes nothing; the change then commits together with its audit intent (`instance.<verb>`).
|
|
174
|
+
*/
|
|
175
|
+
async function governInstance(caller, verb, resourceId, run, resourceType = 'agent-instance') {
|
|
176
|
+
const action = `agent:${verb}`;
|
|
177
|
+
await tasks.checkGrant(caller);
|
|
178
|
+
await enforcePolicy(o.pdp, {
|
|
179
|
+
principal: caller,
|
|
180
|
+
action,
|
|
181
|
+
resource: {
|
|
182
|
+
type: resourceType,
|
|
183
|
+
id: String(resourceId),
|
|
184
|
+
tenantId: caller?.tenantId,
|
|
185
|
+
},
|
|
186
|
+
});
|
|
187
|
+
return run((tx, change) => tasks.audit(tx, caller, {
|
|
188
|
+
type: `instance.${verb}`,
|
|
189
|
+
action,
|
|
190
|
+
resource: { type: 'agent-instance', id: change.instanceId },
|
|
191
|
+
decision: 'allow',
|
|
192
|
+
details: {
|
|
193
|
+
...(change.from ? { from: change.from } : {}),
|
|
194
|
+
...(change.to ? { to: change.to } : {}),
|
|
195
|
+
...(change.ownerId ? { ownerId: change.ownerId } : {}),
|
|
196
|
+
...(change.sharedWith !== undefined
|
|
197
|
+
? { sharedWith: change.sharedWith }
|
|
198
|
+
: {}),
|
|
199
|
+
},
|
|
200
|
+
}));
|
|
201
|
+
}
|
|
202
|
+
async function hasActiveTasks(instanceId) {
|
|
203
|
+
return (await store.transaction((tx) => tx.find('tasks', { where: { instanceId } }))).some((t) => !isTerminal(TASK_MACHINE, t.value.status));
|
|
204
|
+
}
|
|
205
|
+
async function taskOf(taskId) {
|
|
206
|
+
const doc = await store.transaction((tx) => tx.get('tasks', taskId));
|
|
207
|
+
if (!doc)
|
|
208
|
+
throw new AgentropyError('NotFound', 'Task not found');
|
|
209
|
+
return doc.value;
|
|
210
|
+
}
|
|
211
|
+
const builtin = new BuiltinCapabilityProvider({
|
|
212
|
+
...coreOperationHandlers(tasks, wakeups, remote),
|
|
213
|
+
...inboxOperationHandlers(tasks, inbox),
|
|
214
|
+
...humanActionOperationHandlers(human),
|
|
215
|
+
...toolHandlers,
|
|
216
|
+
...(o.reasoning
|
|
217
|
+
? reasoningOperationHandlers({
|
|
218
|
+
tasks,
|
|
219
|
+
provider: o.reasoning,
|
|
220
|
+
...(o.tools ? { tools: o.tools.registry } : {}),
|
|
221
|
+
})
|
|
222
|
+
: {}),
|
|
223
|
+
...(o.workflow
|
|
224
|
+
? workflowOperationHandlers(o.workflow, { store, now })
|
|
225
|
+
: {}),
|
|
226
|
+
...(o.memory ? memoryOperationHandlers({ store, now, ...o.memory }) : {}),
|
|
227
|
+
...o.operations,
|
|
228
|
+
});
|
|
229
|
+
const skillLoader = o.skills &&
|
|
230
|
+
(o.skills.loader ?? new FileSystemSkillLoader(o.skills.registry));
|
|
231
|
+
const runtime = new AgentRuntime({
|
|
232
|
+
...(o.skills && skillLoader
|
|
233
|
+
? {
|
|
234
|
+
skills: (task) => new PinnedSkillAccess(skillLoader, o.skills.registry, task.snapshot.skills),
|
|
235
|
+
}
|
|
236
|
+
: {}),
|
|
237
|
+
...o.runtime,
|
|
238
|
+
poolSize: limits.poolSize,
|
|
239
|
+
leaseMs: limits.leaseMs,
|
|
240
|
+
cancelGraceMs: limits.cancelGraceMs,
|
|
241
|
+
maxActivationMs: limits.maxActivationMs,
|
|
242
|
+
maxOutputBytes: limits.maxOutputBytes,
|
|
243
|
+
keepExecutions: limits.keepExecutions,
|
|
244
|
+
maxCheckpointBytes: limits.maxCheckpointBytes,
|
|
245
|
+
pdpTimeoutMs: limits.pdpTimeoutMs,
|
|
246
|
+
gateRetry: limits.gateRetry,
|
|
247
|
+
tasks,
|
|
248
|
+
implementations,
|
|
249
|
+
capabilityProviders: new Map([[builtin.id, builtin]]),
|
|
250
|
+
relay: {
|
|
251
|
+
drain: async () => (await relay.drain()) + ((await forwarder?.drain()) ?? 0),
|
|
252
|
+
},
|
|
253
|
+
});
|
|
254
|
+
if (o.workflow) {
|
|
255
|
+
bridgeWorkflowCompletions(o.workflow, (e) => wakeups.publish(e), {
|
|
256
|
+
onError: (err) => runtime.report(err),
|
|
257
|
+
});
|
|
258
|
+
// Engines that cannot push are polled as a scheduler sweep, at most every workflowPollMs (FEAT-038.2).
|
|
259
|
+
const engine = o.workflow;
|
|
260
|
+
let lastPoll = -Infinity;
|
|
261
|
+
if (engine.poll)
|
|
262
|
+
wakeups.addSweep(async () => {
|
|
263
|
+
const at = Date.parse(now());
|
|
264
|
+
if (at - lastPoll < (o.workflowPollMs ?? 5_000))
|
|
265
|
+
return;
|
|
266
|
+
lastPoll = at;
|
|
267
|
+
await engine.poll();
|
|
268
|
+
}, { background: true });
|
|
269
|
+
}
|
|
270
|
+
const scheduler = { running: false, consecutiveFailures: 0 };
|
|
271
|
+
const app = {
|
|
272
|
+
store,
|
|
273
|
+
definitions,
|
|
274
|
+
instances,
|
|
275
|
+
tasks,
|
|
276
|
+
runtime,
|
|
277
|
+
wakeups,
|
|
278
|
+
inbox,
|
|
279
|
+
human,
|
|
280
|
+
relay,
|
|
281
|
+
...(forwarder ? { auditForwarder: forwarder } : {}),
|
|
282
|
+
auditLog: new AuditService({
|
|
283
|
+
store,
|
|
284
|
+
pdp: o.pdp,
|
|
285
|
+
now,
|
|
286
|
+
newId: () => tasks.newId('audit'),
|
|
287
|
+
...(o.auditRetention ? { retention: o.auditRetention } : {}),
|
|
288
|
+
...(o.auditAnchors ? { anchorSink: o.auditAnchors } : {}),
|
|
289
|
+
}),
|
|
290
|
+
limits,
|
|
291
|
+
define(definition, handler) {
|
|
292
|
+
const def = validateAgentDefinition(definition);
|
|
293
|
+
if (def.implementation.providerId === 'native-ts') {
|
|
294
|
+
if (!handler)
|
|
295
|
+
throw new AgentropyError('InvalidConfiguration', `Definition ${def.id}@${def.version} needs a native handler`);
|
|
296
|
+
handlers.register(def.implementation.artifact, handler);
|
|
297
|
+
}
|
|
298
|
+
definitions.register(def);
|
|
299
|
+
},
|
|
300
|
+
delegate: async (r, c, trace) => r?.target?.remote
|
|
301
|
+
? remoteOrFail().delegate(r, c)
|
|
302
|
+
: tasks.delegate(r, c, trace),
|
|
303
|
+
getTask: async (id, c) => isRemote(id)
|
|
304
|
+
? remoteOrFail().snapshot(await remoteOrFail().get(id, c))
|
|
305
|
+
: tasks.getTask(id, c),
|
|
306
|
+
listTasks: (q, c) => tasks.listTasks(q, c),
|
|
307
|
+
listInstances: (c, ownerId) => instances.list(c, ownerId),
|
|
308
|
+
drainInstance: (id, c) => governInstance(c, 'drain', id, (audit) => instances.drain(id, c, audit)),
|
|
309
|
+
async upgradeInstance(id, change, c) {
|
|
310
|
+
await tasks.checkGrant(c);
|
|
311
|
+
await enforcePolicy(o.pdp, {
|
|
312
|
+
principal: c,
|
|
313
|
+
action: 'agent:upgrade',
|
|
314
|
+
resource: { type: 'agent-instance', id, tenantId: c?.tenantId },
|
|
315
|
+
});
|
|
316
|
+
return instances.upgrade(id, change, c, (tx, from, to) => tasks.audit(tx, c, {
|
|
317
|
+
type: 'instance.upgrade',
|
|
318
|
+
action: 'agent:upgrade',
|
|
319
|
+
resource: { type: 'agent-instance', id },
|
|
320
|
+
decision: 'allow',
|
|
321
|
+
details: { from: from.version, to: to.version, definition: to.id },
|
|
322
|
+
}));
|
|
323
|
+
},
|
|
324
|
+
async versionsInUse(definitionId, c) {
|
|
325
|
+
if (c?.type !== 'service')
|
|
326
|
+
throw new AgentropyError('PermissionDenied', 'Only trusted services can list version usage');
|
|
327
|
+
const usage = new Map();
|
|
328
|
+
const bump = (v, k) => {
|
|
329
|
+
const u = usage.get(v) ?? { instances: 0, activeTasks: 0 };
|
|
330
|
+
u[k]++;
|
|
331
|
+
usage.set(v, u);
|
|
332
|
+
};
|
|
333
|
+
await o.store.transaction(async (tx) => {
|
|
334
|
+
for (const i of await tx.find('instances', {
|
|
335
|
+
where: { tenantId: c.tenantId },
|
|
336
|
+
}))
|
|
337
|
+
if (i.value.definition.id === definitionId &&
|
|
338
|
+
i.value.state !== 'retired')
|
|
339
|
+
bump(i.value.definition.version, 'instances');
|
|
340
|
+
for (const t of await tx.find('tasks', {
|
|
341
|
+
where: { tenantId: c.tenantId },
|
|
342
|
+
}))
|
|
343
|
+
if (t.value.snapshot.definition.id === definitionId &&
|
|
344
|
+
!isTerminal(TASK_MACHINE, t.value.status))
|
|
345
|
+
bump(t.value.snapshot.definition.version, 'activeTasks');
|
|
346
|
+
});
|
|
347
|
+
return [...usage]
|
|
348
|
+
.map(([version, u]) => ({ version, ...u }))
|
|
349
|
+
.sort((a, b) => a.version.localeCompare(b.version));
|
|
350
|
+
},
|
|
351
|
+
shareInstance: (id, ids, c) => governInstance(c, 'share', id, (audit) => instances.share(id, ids, c, audit)),
|
|
352
|
+
getTaskByIdempotencyKey: (k, c) => tasks.getTaskByIdempotencyKey(k, c),
|
|
353
|
+
getResult: async (id, c) => {
|
|
354
|
+
if (!isRemote(id))
|
|
355
|
+
return tasks.getResult(id, c);
|
|
356
|
+
const r = await remoteOrFail().get(id, c);
|
|
357
|
+
if (r.status === 'completed')
|
|
358
|
+
return r.output;
|
|
359
|
+
if (r.status === 'failed')
|
|
360
|
+
throw new AgentropyError('TaskFailed', r.outcome?.message ?? 'Remote task failed');
|
|
361
|
+
if (r.status === 'cancelled')
|
|
362
|
+
throw new AgentropyError('TaskCancelled', 'Remote task cancelled');
|
|
363
|
+
throw new AgentropyError('NotReady', 'Remote task has not finished');
|
|
364
|
+
},
|
|
365
|
+
cancel: (id, c, reason) => isRemote(id) ? remoteOrFail().cancel(id, c) : tasks.cancel(id, c, reason),
|
|
366
|
+
subscribe: (id, c, from, options) => stream.subscribe(id, c, from, options?.signal),
|
|
367
|
+
submitTurn: (t, c) => tasks.submitTurn(t, c),
|
|
368
|
+
createInstance: (req, c) => governInstance(c, 'create', req?.definition?.id, (audit) => instances.create(req, c, audit), 'agent-definition'),
|
|
369
|
+
suspendInstance: (id, c) => governInstance(c, 'suspend', id, (audit) => instances.suspend(id, c, audit)),
|
|
370
|
+
resumeInstance: (id, c) => governInstance(c, 'resume', id, (audit) => instances.resume(id, c, audit)),
|
|
371
|
+
retireInstance: (id, c, opts = {}) => governInstance(c, 'retire', id, (audit) => instances.retire(id, c, {
|
|
372
|
+
...opts,
|
|
373
|
+
audit,
|
|
374
|
+
hasActiveTasks: () => hasActiveTasks(id),
|
|
375
|
+
})),
|
|
376
|
+
claimHumanAction: (id, c) => human.claim(id, c),
|
|
377
|
+
releaseHumanAction: (id, c) => human.release(id, c),
|
|
378
|
+
getHumanAction: (id, c) => human.get(id, c),
|
|
379
|
+
provideHumanInput: (d, c) => human.decide(d, c),
|
|
380
|
+
listInbox: (q, c) => inbox.list(q, c),
|
|
381
|
+
markInbox: (id, m, c, rev) => inbox.mark(id, m, c, rev),
|
|
382
|
+
reauthorize: (id, c) => tasks.reauthorize(id, c),
|
|
383
|
+
async revokeAuthority(grantRef, caller) {
|
|
384
|
+
if (caller?.type !== 'service')
|
|
385
|
+
throw new AgentropyError('PermissionDenied', 'Revoking authority is an operator action');
|
|
386
|
+
const signalled = await runtime.revokeAuthority(grantRef, caller.tenantId);
|
|
387
|
+
const invalidatedDecisions = o.pdp instanceof CachingPolicyDecisionPoint
|
|
388
|
+
? o.pdp.invalidate({ tenantId: caller.tenantId, grantRef })
|
|
389
|
+
: 0;
|
|
390
|
+
await store.transaction(async (tx) => {
|
|
391
|
+
// Other workers' shared decision caches drop the grant's decisions on their next sync (FEAT-033.1).
|
|
392
|
+
await recordPolicyInvalidation(tx, tasks.newId('invalidation'), { tenantId: caller.tenantId, grantRef }, now());
|
|
393
|
+
await tasks.audit(tx, caller, {
|
|
394
|
+
type: 'authority.revoke',
|
|
395
|
+
action: 'grant:revoke',
|
|
396
|
+
// The reference itself stays out of the audit trail; its digest identifies it.
|
|
397
|
+
resource: { type: 'grant', id: digestOf(grantRef) },
|
|
398
|
+
decision: 'allow',
|
|
399
|
+
details: { signalled: signalled.length, invalidatedDecisions },
|
|
400
|
+
});
|
|
401
|
+
});
|
|
402
|
+
return { signalled, invalidatedDecisions };
|
|
403
|
+
},
|
|
404
|
+
async listEffects(taskId, caller) {
|
|
405
|
+
await tasks.visible(taskId, caller);
|
|
406
|
+
const rows = await store.transaction((tx) => tx.find('effects', { where: { taskId }, orderBy: 'seq' }));
|
|
407
|
+
return rows.map((r) => ({
|
|
408
|
+
operation: r.value.operation,
|
|
409
|
+
...(r.value.stepKey ? { stepKey: r.value.stepKey } : {}),
|
|
410
|
+
at: r.value.at,
|
|
411
|
+
}));
|
|
412
|
+
},
|
|
413
|
+
refreshRemote: (taskId) => remoteOrFail().refresh(taskId),
|
|
414
|
+
async compact(retainMs, caller) {
|
|
415
|
+
if (caller?.type !== 'service')
|
|
416
|
+
throw new AgentropyError('PermissionDenied', 'Compaction is an operator action');
|
|
417
|
+
return wakeups.compact(retainMs);
|
|
418
|
+
},
|
|
419
|
+
async rebuildInbox(caller) {
|
|
420
|
+
if (caller?.type !== 'service')
|
|
421
|
+
throw new AgentropyError('PermissionDenied', 'Inbox rebuild is an operator action');
|
|
422
|
+
return { created: await projector.rebuild() };
|
|
423
|
+
},
|
|
424
|
+
publishEvent: (e) => wakeups.publish(e),
|
|
425
|
+
async runUntilIdle(maxRounds = 20) {
|
|
426
|
+
for (let i = 0; i < maxRounds; i++) {
|
|
427
|
+
const fired = await wakeups.poll();
|
|
428
|
+
await runtime.runUntilIdle();
|
|
429
|
+
if (fired === 0 && runtime.activeCount === 0) {
|
|
430
|
+
const again = await wakeups.poll();
|
|
431
|
+
if (again === 0)
|
|
432
|
+
return;
|
|
433
|
+
await runtime.runUntilIdle();
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
},
|
|
437
|
+
schedulerStatus: () => ({ ...scheduler }),
|
|
438
|
+
start(intervalMs = 250, options = {}) {
|
|
439
|
+
// A Node.js timer shortens a delay above 2^31-1 ms to 1 ms (FIX-086): refuse such an interval instead of
|
|
440
|
+
// running a busy loop.
|
|
441
|
+
if (!Number.isInteger(intervalMs) ||
|
|
442
|
+
intervalMs < 1 ||
|
|
443
|
+
intervalMs > MAX_TIMER_MS)
|
|
444
|
+
throw new AgentropyError('InvalidConfiguration', `intervalMs must be an integer in [1, ${MAX_TIMER_MS}]`, { details: { field: 'intervalMs', value: String(intervalMs) } });
|
|
445
|
+
const heartbeatMs = options.heartbeatMs ?? Math.max(1, Math.floor(limits.leaseMs / 3));
|
|
446
|
+
if (!Number.isInteger(heartbeatMs) ||
|
|
447
|
+
heartbeatMs < 1 ||
|
|
448
|
+
heartbeatMs >= limits.leaseMs)
|
|
449
|
+
throw new AgentropyError('InvalidConfiguration', `heartbeatMs must be an integer in [1, leaseMs=${limits.leaseMs})`, { details: { field: 'heartbeatMs', value: String(heartbeatMs) } });
|
|
450
|
+
let stopped = false;
|
|
451
|
+
// The tick in flight, if any. An interval that finds one skips its turn: a tick slower than the interval must
|
|
452
|
+
// not queue further ticks behind it (they would all run before `stop` settles) (FIX-050).
|
|
453
|
+
let inFlight;
|
|
454
|
+
scheduler.running = true;
|
|
455
|
+
scheduler.startedAt = now();
|
|
456
|
+
scheduler.intervalMs = intervalMs;
|
|
457
|
+
scheduler.consecutiveFailures = 0;
|
|
458
|
+
delete scheduler.lastError;
|
|
459
|
+
// One tick never rejects: a failing store or a bug in one tick is reported and the next interval starts a new
|
|
460
|
+
// one, instead of the rejection escaping as an unhandled rejection.
|
|
461
|
+
const failed = (err) => {
|
|
462
|
+
const error = toAgentropyError(err);
|
|
463
|
+
tasks.telemetry.count(METRICS.schedulerErrors, 1, {
|
|
464
|
+
'agentropy.error.code': error.code,
|
|
465
|
+
});
|
|
466
|
+
try {
|
|
467
|
+
options.onError?.(error);
|
|
468
|
+
}
|
|
469
|
+
catch {
|
|
470
|
+
// A failing error hook must not take the loop down either.
|
|
471
|
+
}
|
|
472
|
+
return error;
|
|
473
|
+
};
|
|
474
|
+
const tick = async () => {
|
|
475
|
+
try {
|
|
476
|
+
await wakeups.poll({ detach: true });
|
|
477
|
+
await runtime.tick();
|
|
478
|
+
scheduler.lastTickAt = now();
|
|
479
|
+
scheduler.consecutiveFailures = 0;
|
|
480
|
+
delete scheduler.lastError;
|
|
481
|
+
}
|
|
482
|
+
catch (err) {
|
|
483
|
+
scheduler.consecutiveFailures++;
|
|
484
|
+
scheduler.lastError = failed(err).code;
|
|
485
|
+
}
|
|
486
|
+
};
|
|
487
|
+
// The lease heartbeat has its own timer (FIX-051): a tick may take longer than a lease (a slow sweep, drain or
|
|
488
|
+
// policy decision), and after `stop` no tick runs at all while running executions are waited for. One renewal
|
|
489
|
+
// at a time; nothing to do while the pool is empty.
|
|
490
|
+
let beating;
|
|
491
|
+
const heartbeat = setInterval(() => {
|
|
492
|
+
if (beating || runtime.activeCount === 0)
|
|
493
|
+
return;
|
|
494
|
+
beating = runtime
|
|
495
|
+
.renewLeases()
|
|
496
|
+
.then(() => undefined, (err) => void failed(err))
|
|
497
|
+
.finally(() => {
|
|
498
|
+
beating = undefined;
|
|
499
|
+
});
|
|
500
|
+
}, heartbeatMs);
|
|
501
|
+
const timer = setInterval(() => {
|
|
502
|
+
if (stopped || inFlight)
|
|
503
|
+
return;
|
|
504
|
+
inFlight = tick().finally(() => {
|
|
505
|
+
inFlight = undefined;
|
|
506
|
+
});
|
|
507
|
+
}, intervalMs);
|
|
508
|
+
return async (stop = {}) => {
|
|
509
|
+
stopped = true;
|
|
510
|
+
clearInterval(timer);
|
|
511
|
+
await inFlight;
|
|
512
|
+
await wakeups.settle(); // background sweeps in flight (bounded by their own timeouts)
|
|
513
|
+
if (stop.drainMs === undefined)
|
|
514
|
+
await runtime.idle();
|
|
515
|
+
else {
|
|
516
|
+
// The heartbeat keeps the leases alive while the executions are given their time.
|
|
517
|
+
let bound;
|
|
518
|
+
const settled = await Promise.race([
|
|
519
|
+
runtime.idle().then(() => true),
|
|
520
|
+
new Promise((r) => {
|
|
521
|
+
// A longer drain than a timer keeps is the longest one it does keep, not 1 ms (FIX-086).
|
|
522
|
+
bound = setTimeout(() => r(false), Math.min(Math.max(0, stop.drainMs), MAX_TIMER_MS));
|
|
523
|
+
bound.unref?.();
|
|
524
|
+
}),
|
|
525
|
+
]);
|
|
526
|
+
clearTimeout(bound);
|
|
527
|
+
if (!settled) {
|
|
528
|
+
// No renewal may follow the expiry: stop the heartbeat first, then hand the executions over.
|
|
529
|
+
clearInterval(heartbeat);
|
|
530
|
+
await beating;
|
|
531
|
+
await runtime.handOver();
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
clearInterval(heartbeat);
|
|
535
|
+
await beating;
|
|
536
|
+
scheduler.running = false;
|
|
537
|
+
};
|
|
538
|
+
},
|
|
539
|
+
};
|
|
540
|
+
return app;
|
|
541
|
+
}
|