@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/registry.js
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
/** Definition registry, instance directory and discovery (M1-03, R-01, R-06, AC-15). In-memory for M1. */
|
|
2
|
+
import { AgentropyError, MemoryStore, INSTANCE_MACHINE, assertTransition, digestOf, enforcePolicy, isAgentropyError, validateAgentDefinition, } from '@agentropy/core';
|
|
3
|
+
import semver from 'semver';
|
|
4
|
+
import { checkInstanceQuota } from './quotas.js';
|
|
5
|
+
export class DefinitionRegistry {
|
|
6
|
+
profiles;
|
|
7
|
+
byKey = new Map();
|
|
8
|
+
constructor(profiles) {
|
|
9
|
+
this.profiles = profiles;
|
|
10
|
+
}
|
|
11
|
+
/** Immutable registration: identical content is a no-op, different content for the same id@version is rejected. */
|
|
12
|
+
register(definition) {
|
|
13
|
+
const def = validateAgentDefinition(structuredClone(definition));
|
|
14
|
+
const key = `${def.id}@${def.version}`;
|
|
15
|
+
const digest = digestOf(def);
|
|
16
|
+
const existing = this.byKey.get(key);
|
|
17
|
+
if (existing) {
|
|
18
|
+
if (existing.digest === digest)
|
|
19
|
+
return structuredClone(existing.definition);
|
|
20
|
+
throw new AgentropyError('InvalidConfiguration', `${key} is already registered with different content`, { details: { reason: 'immutable', id: def.id } });
|
|
21
|
+
}
|
|
22
|
+
this.byKey.set(key, { definition: Object.freeze(def), digest });
|
|
23
|
+
return structuredClone(def);
|
|
24
|
+
}
|
|
25
|
+
get(ref) {
|
|
26
|
+
const hit = this.byKey.get(`${ref.id}@${ref.version}`);
|
|
27
|
+
return hit ? structuredClone(hit.definition) : undefined;
|
|
28
|
+
}
|
|
29
|
+
require(ref) {
|
|
30
|
+
const def = this.get(ref);
|
|
31
|
+
if (!def)
|
|
32
|
+
throw new AgentropyError('NotFound', `Definition ${ref.id}@${ref.version} not found`, { details: { kind: 'definition', id: ref.id } });
|
|
33
|
+
return def;
|
|
34
|
+
}
|
|
35
|
+
versions(id) {
|
|
36
|
+
return [...this.byKey.values()]
|
|
37
|
+
.filter((e) => e.definition.id === id)
|
|
38
|
+
.map((e) => e.definition.version)
|
|
39
|
+
.sort(semver.rcompare);
|
|
40
|
+
}
|
|
41
|
+
/** Capability IDs a definition declares (profile required/defaults plus additions, minus removals). */
|
|
42
|
+
declaredCapabilities(def) {
|
|
43
|
+
const profile = this.profiles.find((p) => p.id === def.profile.id && p.version === def.profile.version);
|
|
44
|
+
const ids = new Set([...(profile?.required ?? []), ...(profile?.defaults ?? [])].map((s) => s.id));
|
|
45
|
+
for (const s of [
|
|
46
|
+
...(def.capabilities ?? []),
|
|
47
|
+
...def.runtimeRequirements.guarantees,
|
|
48
|
+
]) {
|
|
49
|
+
if (s.remove)
|
|
50
|
+
ids.delete(s.id);
|
|
51
|
+
else
|
|
52
|
+
ids.add(s.id);
|
|
53
|
+
}
|
|
54
|
+
return [...ids].sort();
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Deterministic discovery: same query and same policy → same order (id asc, version desc).
|
|
58
|
+
* Definitions the caller may not see are omitted without disclosure; a PDP outage fails closed.
|
|
59
|
+
*/
|
|
60
|
+
async discover(query, caller, pdp) {
|
|
61
|
+
const text = query.text?.toLowerCase();
|
|
62
|
+
const candidates = [...this.byKey.values()]
|
|
63
|
+
.map((e) => e.definition)
|
|
64
|
+
.filter((d) => (query.id ? d.id === query.id : true))
|
|
65
|
+
.filter((d) => (query.profile ? d.profile.id === query.profile : true))
|
|
66
|
+
.filter((d) => query.capability
|
|
67
|
+
? this.declaredCapabilities(d).includes(query.capability)
|
|
68
|
+
: true)
|
|
69
|
+
.filter((d) => text
|
|
70
|
+
? `${d.displayName} ${d.description ?? ''}`
|
|
71
|
+
.toLowerCase()
|
|
72
|
+
.includes(text)
|
|
73
|
+
: true)
|
|
74
|
+
.sort((a, b) => a.id.localeCompare(b.id) || semver.rcompare(a.version, b.version));
|
|
75
|
+
const visible = [];
|
|
76
|
+
for (const d of candidates) {
|
|
77
|
+
try {
|
|
78
|
+
await enforcePolicy(pdp, {
|
|
79
|
+
principal: caller,
|
|
80
|
+
action: 'definition:discover',
|
|
81
|
+
resource: {
|
|
82
|
+
type: 'agent-definition',
|
|
83
|
+
id: d.id,
|
|
84
|
+
tenantId: caller.tenantId,
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
visible.push({ id: d.id, version: d.version });
|
|
88
|
+
}
|
|
89
|
+
catch (err) {
|
|
90
|
+
if (isAgentropyError(err, 'PermissionDenied'))
|
|
91
|
+
continue;
|
|
92
|
+
throw err;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return visible;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Logical agent identities, owner- and tenant-scoped (Agent v1; runtime contract §3). Every change is
|
|
100
|
+
* committed to the Store before it is acknowledged, so instances survive a restart (R-08).
|
|
101
|
+
*/
|
|
102
|
+
export class InstanceDirectory {
|
|
103
|
+
definitions;
|
|
104
|
+
store;
|
|
105
|
+
newId;
|
|
106
|
+
quotas;
|
|
107
|
+
seq = 0;
|
|
108
|
+
constructor(definitions, store = new MemoryStore(), newId = () => `inst-${Date.now().toString(36)}-${++this.seq}`, quotas) {
|
|
109
|
+
this.definitions = definitions;
|
|
110
|
+
this.store = store;
|
|
111
|
+
this.newId = newId;
|
|
112
|
+
this.quotas = quotas;
|
|
113
|
+
}
|
|
114
|
+
async create(req, caller, audit) {
|
|
115
|
+
const { key, fingerprint } = this.createKey(req, caller);
|
|
116
|
+
this.definitions.require(req.definition);
|
|
117
|
+
return this.store.transaction(async (tx) => {
|
|
118
|
+
const prior = await tx.get('idempotency', key);
|
|
119
|
+
if (prior) {
|
|
120
|
+
if (prior.value.fingerprint !== fingerprint)
|
|
121
|
+
throw new AgentropyError('IdempotencyConflict', 'Idempotency key reused with a different request');
|
|
122
|
+
return (await tx.get('instances', prior.value.instanceId)).value;
|
|
123
|
+
}
|
|
124
|
+
await checkInstanceQuota(tx, caller.tenantId, this.quotas?.(caller.tenantId));
|
|
125
|
+
assertTransition(INSTANCE_MACHINE, null, 'available');
|
|
126
|
+
const instance = {
|
|
127
|
+
id: this.newId(),
|
|
128
|
+
definition: { ...req.definition },
|
|
129
|
+
tenantId: caller.tenantId,
|
|
130
|
+
ownerId: req.ownerId,
|
|
131
|
+
state: 'available',
|
|
132
|
+
revision: 1,
|
|
133
|
+
};
|
|
134
|
+
await tx.insert('instances', instance.id, instance);
|
|
135
|
+
await tx.insert('idempotency', key, {
|
|
136
|
+
tenantId: caller.tenantId,
|
|
137
|
+
instanceId: instance.id,
|
|
138
|
+
fingerprint,
|
|
139
|
+
});
|
|
140
|
+
await audit?.(tx, {
|
|
141
|
+
instanceId: instance.id,
|
|
142
|
+
to: 'available',
|
|
143
|
+
ownerId: instance.ownerId,
|
|
144
|
+
});
|
|
145
|
+
return instance;
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* The instance `create` would make for this request, without storing it (FIX-063): a delegation by definition
|
|
150
|
+
* plans the instance, runs every refusal that can still happen, and stores it in the transaction that accepts the
|
|
151
|
+
* task (`insertPlanned`), so a refused delegation leaves nothing behind. The ID of an instance that already exists
|
|
152
|
+
* for the key is returned as it is (`stored`), so a retry gets the same instance.
|
|
153
|
+
*/
|
|
154
|
+
async plan(req, caller) {
|
|
155
|
+
const { key, fingerprint } = this.createKey(req, caller);
|
|
156
|
+
this.definitions.require(req.definition);
|
|
157
|
+
const prior = await this.store.transaction(async (tx) => {
|
|
158
|
+
const rec = await tx.get('idempotency', key);
|
|
159
|
+
return rec
|
|
160
|
+
? {
|
|
161
|
+
rec,
|
|
162
|
+
doc: await tx.get('instances', rec.value.instanceId),
|
|
163
|
+
}
|
|
164
|
+
: undefined;
|
|
165
|
+
});
|
|
166
|
+
if (prior) {
|
|
167
|
+
if (prior.rec.value.fingerprint !== fingerprint)
|
|
168
|
+
throw new AgentropyError('IdempotencyConflict', 'Idempotency key reused with a different request');
|
|
169
|
+
return { instance: prior.doc.value, stored: true };
|
|
170
|
+
}
|
|
171
|
+
return {
|
|
172
|
+
instance: {
|
|
173
|
+
id: this.newId(),
|
|
174
|
+
definition: { ...req.definition },
|
|
175
|
+
tenantId: caller.tenantId,
|
|
176
|
+
ownerId: req.ownerId,
|
|
177
|
+
state: 'available',
|
|
178
|
+
revision: 1,
|
|
179
|
+
},
|
|
180
|
+
stored: false,
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
/** Stores an instance from `plan` in the caller's transaction, under the instance quota. */
|
|
184
|
+
async insertPlanned(tx, req, caller, instance) {
|
|
185
|
+
const { key, fingerprint } = this.createKey(req, caller);
|
|
186
|
+
await checkInstanceQuota(tx, caller.tenantId, this.quotas?.(caller.tenantId));
|
|
187
|
+
await tx.insert('instances', instance.id, instance);
|
|
188
|
+
await tx.insert('idempotency', key, {
|
|
189
|
+
tenantId: caller.tenantId,
|
|
190
|
+
instanceId: instance.id,
|
|
191
|
+
fingerprint,
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
createKey(req, caller) {
|
|
195
|
+
// The owner is who the instance appears for in lists and the inbox: only a trusted service names another one.
|
|
196
|
+
if (req.ownerId !== caller.id && caller.type !== 'service')
|
|
197
|
+
throw new AgentropyError('PermissionDenied', 'Only a trusted service can create an instance for another owner');
|
|
198
|
+
return {
|
|
199
|
+
key: `instance:${caller.tenantId}|${caller.id}|${req.idempotencyKey}`,
|
|
200
|
+
fingerprint: digestOf({
|
|
201
|
+
definition: req.definition,
|
|
202
|
+
ownerId: req.ownerId,
|
|
203
|
+
}),
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
/** Tenant-scoped lookup: another tenant's instance is indistinguishable from a missing one. */
|
|
207
|
+
async get(instanceId, caller) {
|
|
208
|
+
const doc = await this.store.transaction((tx) => tx.get('instances', instanceId));
|
|
209
|
+
if (!doc || doc.value.tenantId !== caller.tenantId)
|
|
210
|
+
throw new AgentropyError('NotFound', 'Instance not found', {
|
|
211
|
+
details: { kind: 'instance' },
|
|
212
|
+
});
|
|
213
|
+
return doc.value;
|
|
214
|
+
}
|
|
215
|
+
/** Tenant of an instance, for distinguishing cross-tenant targets (AC-09) from missing ones. */
|
|
216
|
+
async tenantOf(instanceId) {
|
|
217
|
+
return (await this.store.transaction((tx) => tx.get('instances', instanceId)))?.value.tenantId;
|
|
218
|
+
}
|
|
219
|
+
/** Internal (trusted) read used by the runtime, e.g. to defer wake-ups of suspended instances. */
|
|
220
|
+
async stateOf(instanceId) {
|
|
221
|
+
return (await this.store.transaction((tx) => tx.get('instances', instanceId)))?.value.state;
|
|
222
|
+
}
|
|
223
|
+
async list(caller, ownerId = caller.id) {
|
|
224
|
+
// Owners list their own instances; only trusted services may list another owner's (R-13).
|
|
225
|
+
if (ownerId !== caller.id && caller.type !== 'service')
|
|
226
|
+
return [];
|
|
227
|
+
const docs = await this.store.transaction((tx) => tx.find('instances', {
|
|
228
|
+
where: { tenantId: caller.tenantId, ownerId },
|
|
229
|
+
}));
|
|
230
|
+
return docs.map((d) => d.value).sort((a, b) => a.id.localeCompare(b.id));
|
|
231
|
+
}
|
|
232
|
+
suspend(instanceId, caller, audit) {
|
|
233
|
+
return this.move(instanceId, caller, 'suspended', audit);
|
|
234
|
+
}
|
|
235
|
+
resume(instanceId, caller, audit) {
|
|
236
|
+
return this.move(instanceId, caller, 'available', audit);
|
|
237
|
+
}
|
|
238
|
+
/** Without force, retiring fails InvalidState while non-terminal tasks exist (checked by the caller-supplied guard). */
|
|
239
|
+
async retire(instanceId, caller, opts = {}) {
|
|
240
|
+
if (!opts.force && (await opts.hasActiveTasks?.()))
|
|
241
|
+
throw new AgentropyError('InvalidState', 'Instance has non-terminal tasks', { details: { kind: 'instance' } });
|
|
242
|
+
return this.move(instanceId, caller, 'retired', opts.audit);
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Drain: stop accepting new tasks while existing tasks run to completion; the runtime retires the instance
|
|
246
|
+
* when its last non-terminal task ends (TaskService.terminate). Retires at once when nothing is active.
|
|
247
|
+
*/
|
|
248
|
+
async drain(instanceId, caller, audit) {
|
|
249
|
+
return this.store.transaction(async (tx) => {
|
|
250
|
+
const doc = await this.owned(tx, instanceId, caller);
|
|
251
|
+
const inst = doc.value;
|
|
252
|
+
if (inst.state === 'retired')
|
|
253
|
+
throw new AgentropyError('InvalidState', 'Instance is retired', {
|
|
254
|
+
details: { kind: 'instance' },
|
|
255
|
+
});
|
|
256
|
+
// Checked in the same transaction as the update, so no task can slip in between.
|
|
257
|
+
const active = (await tx.find('tasks', { where: { instanceId } })).some((t) => !['completed', 'failed', 'cancelled'].includes(t.value.status));
|
|
258
|
+
if (!active)
|
|
259
|
+
assertTransition(INSTANCE_MACHINE, inst.state, 'retired');
|
|
260
|
+
const next = {
|
|
261
|
+
...inst,
|
|
262
|
+
draining: true,
|
|
263
|
+
...(active ? {} : { state: 'retired' }),
|
|
264
|
+
revision: inst.revision + 1,
|
|
265
|
+
};
|
|
266
|
+
const updated = (await tx.update('instances', instanceId, doc.revision, next)).value;
|
|
267
|
+
await audit?.(tx, {
|
|
268
|
+
instanceId,
|
|
269
|
+
from: inst.state,
|
|
270
|
+
to: updated.state,
|
|
271
|
+
});
|
|
272
|
+
return updated;
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
/** Owner-only: replace who may delegate to the instance (D-08). Shares never cross the tenant boundary. */
|
|
276
|
+
async share(instanceId, principalIds, caller, audit) {
|
|
277
|
+
if (!Array.isArray(principalIds) ||
|
|
278
|
+
principalIds.some((p) => typeof p !== 'string' || !p))
|
|
279
|
+
throw new AgentropyError('SchemaViolation', 'principalIds must be non-empty strings');
|
|
280
|
+
return this.store.transaction(async (tx) => {
|
|
281
|
+
const doc = await this.owned(tx, instanceId, caller);
|
|
282
|
+
if (doc.value.ownerId !== caller.id)
|
|
283
|
+
throw new AgentropyError('PermissionDenied', 'Only the owner can share an instance');
|
|
284
|
+
const next = {
|
|
285
|
+
...doc.value,
|
|
286
|
+
sharedWith: [...new Set(principalIds)].filter((p) => p !== doc.value.ownerId),
|
|
287
|
+
revision: doc.value.revision + 1,
|
|
288
|
+
};
|
|
289
|
+
const updated = (await tx.update('instances', instanceId, doc.revision, next)).value;
|
|
290
|
+
await audit?.(tx, {
|
|
291
|
+
instanceId,
|
|
292
|
+
sharedWith: updated.sharedWith?.length ?? 0,
|
|
293
|
+
});
|
|
294
|
+
return updated;
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Audited definition upgrade or rollback (FEAT-028.3, D-07): the instance uses `version` for **future** tasks only;
|
|
299
|
+
* accepted tasks keep their acceptance snapshot. The target must be registered and of the same definition; the
|
|
300
|
+
* caller passes the instance revision it saw (compare-and-swap). Owner or trusted service only.
|
|
301
|
+
*/
|
|
302
|
+
async upgrade(instanceId, change, caller, audit) {
|
|
303
|
+
if (typeof change?.version !== 'string' || !change.version)
|
|
304
|
+
throw new AgentropyError('SchemaViolation', 'version is required');
|
|
305
|
+
return this.store.transaction(async (tx) => {
|
|
306
|
+
const doc = await this.owned(tx, instanceId, caller);
|
|
307
|
+
const inst = doc.value;
|
|
308
|
+
if (inst.state === 'retired')
|
|
309
|
+
throw new AgentropyError('InvalidState', 'Instance is retired');
|
|
310
|
+
if (inst.revision !== change.expectedRevision)
|
|
311
|
+
throw new AgentropyError('StaleRevision', 'Instance changed since it was read', {
|
|
312
|
+
details: {
|
|
313
|
+
expected: change.expectedRevision,
|
|
314
|
+
actual: inst.revision,
|
|
315
|
+
},
|
|
316
|
+
});
|
|
317
|
+
const to = {
|
|
318
|
+
id: inst.definition.id,
|
|
319
|
+
version: change.version,
|
|
320
|
+
};
|
|
321
|
+
if (!this.definitions.get(to))
|
|
322
|
+
throw new AgentropyError('IncompatibleVersion', `Definition ${to.id}@${to.version} is not registered`, { details: { kind: 'definition' } });
|
|
323
|
+
if (to.version === inst.definition.version)
|
|
324
|
+
return inst;
|
|
325
|
+
await audit(tx, inst.definition, to);
|
|
326
|
+
return (await tx.update('instances', instanceId, doc.revision, {
|
|
327
|
+
...inst,
|
|
328
|
+
definition: to,
|
|
329
|
+
previousDefinition: { ...inst.definition },
|
|
330
|
+
revision: inst.revision + 1,
|
|
331
|
+
})).value;
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
async owned(tx, instanceId, caller) {
|
|
335
|
+
const doc = await tx.get('instances', instanceId);
|
|
336
|
+
const inst = doc?.value;
|
|
337
|
+
if (!doc ||
|
|
338
|
+
!inst ||
|
|
339
|
+
inst.tenantId !== caller.tenantId ||
|
|
340
|
+
(inst.ownerId !== caller.id && caller.type !== 'service'))
|
|
341
|
+
throw new AgentropyError('NotFound', 'Instance not found', {
|
|
342
|
+
details: { kind: 'instance' },
|
|
343
|
+
});
|
|
344
|
+
return doc;
|
|
345
|
+
}
|
|
346
|
+
move(instanceId, caller, to, audit) {
|
|
347
|
+
return this.store.transaction(async (tx) => {
|
|
348
|
+
const doc = await tx.get('instances', instanceId);
|
|
349
|
+
const inst = doc?.value;
|
|
350
|
+
// Non-owners (other than trusted services) and other tenants get NotFound, never a state-revealing error (R-13).
|
|
351
|
+
if (!doc ||
|
|
352
|
+
!inst ||
|
|
353
|
+
inst.tenantId !== caller.tenantId ||
|
|
354
|
+
(inst.ownerId !== caller.id && caller.type !== 'service')) {
|
|
355
|
+
throw new AgentropyError('NotFound', 'Instance not found', {
|
|
356
|
+
details: { kind: 'instance' },
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
assertTransition(INSTANCE_MACHINE, inst.state, to);
|
|
360
|
+
const updated = (await tx.update('instances', instanceId, doc.revision, {
|
|
361
|
+
...inst,
|
|
362
|
+
state: to,
|
|
363
|
+
revision: inst.revision + 1,
|
|
364
|
+
})).value;
|
|
365
|
+
await audit?.(tx, { instanceId, from: inst.state, to });
|
|
366
|
+
return updated;
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
}
|
package/dist/remote.d.ts
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Remote delegation (FEAT-027.9, Communication v1 "Only for remote targets … call the router"): a delegation whose
|
|
3
|
+
* target is `{ remote: { endpoint, definitionId } }` goes through the CommunicationRouter to the selected provider
|
|
4
|
+
* (A2A, a custom broker provider, …). Locally the runtime keeps a *projection* of the remote task — the remote side
|
|
5
|
+
* stays authoritative — and refreshes it on every scheduler poll, so a parent waiting on `child-tasks` wakes when
|
|
6
|
+
* the remote task finishes.
|
|
7
|
+
*
|
|
8
|
+
* Checks before anything leaves the process: authentication, delegated-authority status, the same
|
|
9
|
+
* `delegation:delegate` policy action as local delegation (resource type `remote-agent`), and route selection
|
|
10
|
+
* (tenant boundary, required guarantees). The remote call is idempotent by the delegation's idempotency key, so a
|
|
11
|
+
* crash between the remote acceptance and the local projection write is repaired by retrying the same step.
|
|
12
|
+
*
|
|
13
|
+
* Every call to the peer (delegate, getTask, cancel) is bounded by `timeoutMs` (FIX-053): the provider gets an
|
|
14
|
+
* AbortSignal that fires at the limit, and a provider that ignores it is given up on all the same, so a peer that
|
|
15
|
+
* accepts the connection and never answers costs one `RemoteUnavailable` and never holds the caller.
|
|
16
|
+
*/
|
|
17
|
+
import { type CommunicationRouter, type DelegationRequest, type RouteBinding, type TaskHandle, type TaskSnapshot, type TrustedPrincipal } from '@agentropy/core';
|
|
18
|
+
import { type TaskService } from './task-service.js';
|
|
19
|
+
export interface RemoteTaskRecord {
|
|
20
|
+
taskId: string;
|
|
21
|
+
tenantId: string;
|
|
22
|
+
callerId: string;
|
|
23
|
+
callerType: TrustedPrincipal['type'];
|
|
24
|
+
parentTaskId?: string;
|
|
25
|
+
correlationId: string;
|
|
26
|
+
idempotencyKey: string;
|
|
27
|
+
fingerprint: string;
|
|
28
|
+
definition: {
|
|
29
|
+
id: string;
|
|
30
|
+
version: string;
|
|
31
|
+
};
|
|
32
|
+
route: RouteBinding;
|
|
33
|
+
remoteTaskId: string;
|
|
34
|
+
status: TaskSnapshot['status'];
|
|
35
|
+
remoteState: string;
|
|
36
|
+
/** Local projection revision: bumps whenever the observed remote state changes. */
|
|
37
|
+
revision: number;
|
|
38
|
+
output?: unknown;
|
|
39
|
+
outcome?: {
|
|
40
|
+
code: string;
|
|
41
|
+
message: string;
|
|
42
|
+
};
|
|
43
|
+
observedAt: string;
|
|
44
|
+
createdAt: string;
|
|
45
|
+
lastError?: string;
|
|
46
|
+
/** The scheduler asks the peer again from this time on (FEAT-039.2); absent means now. */
|
|
47
|
+
nextSyncAt?: string;
|
|
48
|
+
/** Polls in a row that found nothing new or failed; the wait doubles with each. */
|
|
49
|
+
quiet?: number;
|
|
50
|
+
/**
|
|
51
|
+
* Set when the parent task was cancelled or failed (FEAT-070): the next sync asks the peer to cancel the remote task
|
|
52
|
+
* instead of asking for its state, and keeps asking, backing off, until the peer has answered. A refused cancel
|
|
53
|
+
* (`InvalidState`, `UnsupportedOperation`) is followed by `getTask` in the same sync; `NotFound` fails it (FIX-080).
|
|
54
|
+
*/
|
|
55
|
+
cancelRequestedAt?: string;
|
|
56
|
+
/**
|
|
57
|
+
* When the peer first answered `NotFound` to a status poll of this projection, in the current run of such answers
|
|
58
|
+
* (FIX-087). Cleared by any other answer; once `sync.notFoundMs` has passed since it, the projection fails `NotFound`.
|
|
59
|
+
*/
|
|
60
|
+
notFoundSince?: string;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* How often a projection is refreshed: `minMs` after a change, doubling per quiet poll up to `maxMs`. `notFoundMs` is
|
|
64
|
+
* how long a peer may keep answering `NotFound` to the status poll before the projection fails `NotFound` (FIX-087).
|
|
65
|
+
*/
|
|
66
|
+
export interface RemoteSyncOptions {
|
|
67
|
+
minMs?: number;
|
|
68
|
+
maxMs?: number;
|
|
69
|
+
notFoundMs?: number;
|
|
70
|
+
}
|
|
71
|
+
/** How long a peer may keep answering `NotFound` to the status poll of a remote task before it fails (FIX-087). */
|
|
72
|
+
export declare const DEFAULT_REMOTE_NOT_FOUND_MS: number;
|
|
73
|
+
/** Longest one call to a peer may take unless configured otherwise. */
|
|
74
|
+
export declare const DEFAULT_REMOTE_TIMEOUT_MS = 30000;
|
|
75
|
+
export declare class RemoteDelegationService {
|
|
76
|
+
private readonly o;
|
|
77
|
+
constructor(o: {
|
|
78
|
+
tasks: TaskService;
|
|
79
|
+
router: CommunicationRouter;
|
|
80
|
+
sync?: RemoteSyncOptions;
|
|
81
|
+
/** Longest one call to a peer may take (default 30 s); a longer one fails `RemoteUnavailable` (FIX-053). */
|
|
82
|
+
timeoutMs?: number;
|
|
83
|
+
/** Largest output a remote task may report (default `DEFAULT_LIMITS.maxOutputBytes`); a larger one fails it (TASK-068). */
|
|
84
|
+
maxOutputBytes?: number;
|
|
85
|
+
});
|
|
86
|
+
/**
|
|
87
|
+
* Runs one call to a peer within `timeoutMs`. The provider's context carries a signal that fires at the limit (and
|
|
88
|
+
* when the caller's own signal fires); the call is also raced against the limit, so a provider that ignores the
|
|
89
|
+
* signal cannot hold the caller. What the abandoned call does later is contained.
|
|
90
|
+
*/
|
|
91
|
+
private bounded;
|
|
92
|
+
/** Next refresh time after a poll that saw `quiet` quiet polls in a row (FEAT-039.2). */
|
|
93
|
+
private due;
|
|
94
|
+
private get store();
|
|
95
|
+
private now;
|
|
96
|
+
delegate(request: DelegationRequest, caller: TrustedPrincipal): Promise<TaskHandle>;
|
|
97
|
+
private replay;
|
|
98
|
+
private handle;
|
|
99
|
+
private find;
|
|
100
|
+
/**
|
|
101
|
+
* The projection, visible to its delegator, to whoever can see the parent task (owner or delegator of the
|
|
102
|
+
* parent), and to trusted services of the tenant — the same visibility a local child task has.
|
|
103
|
+
*/
|
|
104
|
+
get(taskId: string, caller: TrustedPrincipal): Promise<RemoteTaskRecord>;
|
|
105
|
+
snapshot(r: RemoteTaskRecord): TaskSnapshot;
|
|
106
|
+
cancel(taskId: string, caller: TrustedPrincipal): Promise<TaskSnapshot>;
|
|
107
|
+
/**
|
|
108
|
+
* Refresh the non-terminal projections that are due from their providers (called on each scheduler poll). A
|
|
109
|
+
* projection that keeps showing nothing new, or whose peer is down, is asked less and less often (doubling from
|
|
110
|
+
* `sync.minMs` up to `sync.maxMs`), so open remote tasks do not become a request every poll (FEAT-039.2).
|
|
111
|
+
*/
|
|
112
|
+
sync(): Promise<number>;
|
|
113
|
+
/** One poll of a projection: true when the peer's answer changed it; otherwise its next poll is pushed back. */
|
|
114
|
+
private poll;
|
|
115
|
+
private readonly refreshing;
|
|
116
|
+
/**
|
|
117
|
+
* Asks the peer for one open projection now, outside the poll schedule (FEAT-048.2: the A2A push notification
|
|
118
|
+
* receiver calls this). True when the projection changed; false when it did not, is terminal, does not exist or the
|
|
119
|
+
* peer could not be reached (recorded like a failed poll). Concurrent refreshes of one projection share one call.
|
|
120
|
+
* Trusted host code only: it takes no principal, and what it applies is whatever the peer, the authority for the
|
|
121
|
+
* task, answers.
|
|
122
|
+
*/
|
|
123
|
+
refresh(taskId: string): Promise<boolean>;
|
|
124
|
+
/** Records when the projection is asked next, and the error of a failed poll (cleared by a good one). */
|
|
125
|
+
private schedule;
|
|
126
|
+
/** Ends a run of NotFound answers: the peer answered something else (FIX-087). */
|
|
127
|
+
private forgetNotFound;
|
|
128
|
+
private ref;
|
|
129
|
+
private apply;
|
|
130
|
+
}
|