@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.
Files changed (85) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +39 -2
  3. package/dist/a2a-client.d.ts +111 -0
  4. package/dist/a2a-client.js +386 -0
  5. package/dist/a2a-history.d.ts +27 -0
  6. package/dist/a2a-history.js +67 -0
  7. package/dist/a2a-http.d.ts +46 -0
  8. package/dist/a2a-http.js +183 -0
  9. package/dist/a2a-protocol.d.ts +77 -0
  10. package/dist/a2a-protocol.js +148 -0
  11. package/dist/a2a-push-receiver.d.ts +24 -0
  12. package/dist/a2a-push-receiver.js +161 -0
  13. package/dist/a2a-push.d.ts +85 -0
  14. package/dist/a2a-push.js +385 -0
  15. package/dist/a2a-server.d.ts +82 -0
  16. package/dist/a2a-server.js +523 -0
  17. package/dist/a2a-sse.d.ts +5 -0
  18. package/dist/a2a-sse.js +36 -0
  19. package/dist/a2a.d.ts +41 -0
  20. package/dist/a2a.js +40 -0
  21. package/dist/app.d.ts +256 -0
  22. package/dist/app.js +541 -0
  23. package/dist/audit.d.ts +229 -0
  24. package/dist/audit.js +718 -0
  25. package/dist/bounded-body.d.ts +32 -0
  26. package/dist/bounded-body.js +124 -0
  27. package/dist/communication.d.ts +62 -0
  28. package/dist/communication.js +142 -0
  29. package/dist/compaction.d.ts +24 -0
  30. package/dist/compaction.js +202 -0
  31. package/dist/federation.d.ts +108 -0
  32. package/dist/federation.js +241 -0
  33. package/dist/http-path.d.ts +7 -0
  34. package/dist/http-path.js +14 -0
  35. package/dist/human-actions.d.ts +62 -0
  36. package/dist/human-actions.js +359 -0
  37. package/dist/implementation.d.ts +47 -0
  38. package/dist/implementation.js +138 -0
  39. package/dist/inbox.d.ts +101 -0
  40. package/dist/inbox.js +389 -0
  41. package/dist/index.d.ts +32 -0
  42. package/dist/index.js +32 -0
  43. package/dist/ingress.d.ts +35 -0
  44. package/dist/ingress.js +86 -0
  45. package/dist/lifecycle.d.ts +45 -0
  46. package/dist/lifecycle.js +57 -0
  47. package/dist/limits.d.ts +43 -0
  48. package/dist/limits.js +71 -0
  49. package/dist/mcp.d.ts +111 -0
  50. package/dist/mcp.js +308 -0
  51. package/dist/memory.d.ts +25 -0
  52. package/dist/memory.js +134 -0
  53. package/dist/model-routing.d.ts +66 -0
  54. package/dist/model-routing.js +80 -0
  55. package/dist/otel.d.ts +60 -0
  56. package/dist/otel.js +72 -0
  57. package/dist/outbox.d.ts +116 -0
  58. package/dist/outbox.js +327 -0
  59. package/dist/policy-cache.d.ts +69 -0
  60. package/dist/policy-cache.js +178 -0
  61. package/dist/priority.d.ts +27 -0
  62. package/dist/priority.js +28 -0
  63. package/dist/quotas.d.ts +19 -0
  64. package/dist/quotas.js +47 -0
  65. package/dist/reasoning.d.ts +54 -0
  66. package/dist/reasoning.js +307 -0
  67. package/dist/registry.d.ts +101 -0
  68. package/dist/registry.js +369 -0
  69. package/dist/remote.d.ts +130 -0
  70. package/dist/remote.js +473 -0
  71. package/dist/runtime.d.ts +167 -0
  72. package/dist/runtime.js +1035 -0
  73. package/dist/skills.d.ts +86 -0
  74. package/dist/skills.js +376 -0
  75. package/dist/task-service.d.ts +239 -0
  76. package/dist/task-service.js +790 -0
  77. package/dist/tools.d.ts +140 -0
  78. package/dist/tools.js +476 -0
  79. package/dist/wake-index.d.ts +9 -0
  80. package/dist/wake-index.js +11 -0
  81. package/dist/wakeups.d.ts +142 -0
  82. package/dist/wakeups.js +501 -0
  83. package/dist/workflow.d.ts +36 -0
  84. package/dist/workflow.js +101 -0
  85. package/package.json +48 -3
@@ -0,0 +1,140 @@
1
+ import { type AuditEvent, type AuditIntentWriter, type CredentialProvider, type PolicyDecisionPoint, type Store, type ToolBinding, type ToolDescriptor, type ToolExecutor, type ToolInvocationContext, type ToolPin, type ToolProvenance, type ToolProvider, type ToolRecord, type ToolRegistry, type TrustedPrincipal, type VersionedRef } from '@agentropy/core';
2
+ export interface SecurityServices {
3
+ pdp: PolicyDecisionPoint;
4
+ audit: AuditIntentWriter;
5
+ now: () => string;
6
+ }
7
+ /** Writes mandatory audit intent; any failure is AuditCommitUnavailable and the protected operation must not proceed. */
8
+ export declare function recordAudit(audit: AuditIntentWriter, event: AuditEvent): Promise<void>;
9
+ export declare class InMemoryToolRegistry implements ToolRegistry {
10
+ private readonly security;
11
+ /** Decides whether provenance is trusted (signature/allow-list check). Never derived from the manifest itself. */
12
+ private readonly verify;
13
+ /**
14
+ * With a `store`, the status an operator sets (activate, suspend, revoke) is kept there (FEAT-074): another worker
15
+ * on the store refuses a revoked tool at once, and a restart does not bring it back, because `register` adopts the
16
+ * stored status and `revoked` is final.
17
+ */
18
+ private readonly options;
19
+ private readonly records;
20
+ constructor(security: SecurityServices,
21
+ /** Decides whether provenance is trusted (signature/allow-list check). Never derived from the manifest itself. */
22
+ verify: (descriptor: ToolDescriptor, provenance: Omit<ToolProvenance, 'digest' | 'verified'>) => boolean,
23
+ /**
24
+ * With a `store`, the status an operator sets (activate, suspend, revoke) is kept there (FEAT-074): another worker
25
+ * on the store refuses a revoked tool at once, and a restart does not bring it back, because `register` adopts the
26
+ * stored status and `revoked` is final.
27
+ */
28
+ options?: {
29
+ store?: Store;
30
+ });
31
+ private guard;
32
+ register(descriptor: ToolDescriptor, bindings: ToolBinding[], provenance: Omit<ToolProvenance, 'digest' | 'verified'>, admin: TrustedPrincipal): Promise<ToolRecord>;
33
+ /** The record with the status the store has (this process's own when it has no store). */
34
+ refreshed(ref: VersionedRef): Promise<ToolRecord | undefined>;
35
+ activate(ref: VersionedRef, admin: TrustedPrincipal): Promise<ToolRecord>;
36
+ suspend(ref: VersionedRef, admin: TrustedPrincipal): Promise<ToolRecord>;
37
+ revoke(ref: VersionedRef, admin: TrustedPrincipal): Promise<ToolRecord>;
38
+ get(ref: VersionedRef): ToolRecord | undefined;
39
+ /**
40
+ * Every version of a tool with this process's own status, which only moves when this process acts on it or calls
41
+ * `refreshed`. What must agree with other workers on the store (task acceptance) uses `refreshedVersions`.
42
+ */
43
+ versions(id: string): ToolRecord[];
44
+ /**
45
+ * Every version of a tool with the status the store has (FIX-084): an activation or revoke on another worker counts.
46
+ * Task acceptance resolves against this. Without a store it answers as `versions` does.
47
+ */
48
+ refreshedVersions(id: string): Promise<ToolRecord[]>;
49
+ /** Metadata only. Discovery never implies invocation permission. */
50
+ discover(query: {
51
+ text?: string;
52
+ }, caller: TrustedPrincipal): Promise<ToolDescriptor[]>;
53
+ private require;
54
+ private move;
55
+ }
56
+ export declare class ToolProviderRegistry {
57
+ private readonly providers;
58
+ register(provider: ToolProvider): void;
59
+ has(id: string, version: string): boolean;
60
+ get(id: string, version: string): ToolProvider;
61
+ }
62
+ /** Derived idempotency key: hash(tenantId, taskId, capabilityId, operation, stepKey) — Agent v1 "Idempotent side effects". */
63
+ export declare function deriveIdempotencyKey(tenantId: string, taskId: string, capabilityId: string, operation: string, stepKey: string): string;
64
+ export interface ToolExecutorOptions extends SecurityServices {
65
+ registry: InMemoryToolRegistry;
66
+ providers: ToolProviderRegistry;
67
+ credentials?: CredentialProvider;
68
+ /** Default per-invocation timeout; a binding may set config.timeoutMs. */
69
+ defaultTimeoutMs?: number;
70
+ }
71
+ export declare class DefaultToolExecutor implements ToolExecutor {
72
+ private readonly o;
73
+ constructor(o: ToolExecutorOptions);
74
+ invoke(pin: ToolPin, input: unknown, ctx: ToolInvocationContext & {
75
+ stepKey?: string;
76
+ }): Promise<unknown>;
77
+ private resolveCredential;
78
+ private dispatch;
79
+ }
80
+ export type ToolFunction = (input: unknown, ctx: ToolInvocationContext) => Promise<unknown> | unknown;
81
+ /** Direct adapter: calls an in-process function selected by `config.function`. */
82
+ export declare class DirectToolProvider implements ToolProvider {
83
+ private readonly functions;
84
+ readonly id = "direct";
85
+ readonly version = "1.0.0";
86
+ readonly features: {
87
+ protocol: string;
88
+ protocolVersion: string;
89
+ cancellation: boolean;
90
+ idempotencyKeys: boolean;
91
+ streaming: boolean;
92
+ };
93
+ constructor(functions: Record<string, ToolFunction>);
94
+ invoke(binding: ToolBinding, _d: ToolDescriptor, input: unknown, ctx: ToolInvocationContext): Promise<unknown>;
95
+ }
96
+ /** A JSON-RPC-shaped request as it would cross a protocol boundary; payloads are serialized, never shared by reference. */
97
+ export interface LoopbackRequest {
98
+ jsonrpc: '2.0';
99
+ id: string;
100
+ method: string;
101
+ params: {
102
+ arguments: unknown;
103
+ idempotencyKey?: string;
104
+ };
105
+ }
106
+ export type LoopbackTransport = (request: string) => Promise<string>;
107
+ /** Second adapter: serializes calls into a JSON-RPC envelope over an injected transport (protocol-shaped, offline). */
108
+ export declare class LoopbackJsonRpcToolProvider implements ToolProvider {
109
+ private readonly transport;
110
+ readonly id = "loopback";
111
+ readonly version = "1.0.0";
112
+ readonly features: {
113
+ protocol: string;
114
+ protocolVersion: string;
115
+ cancellation: boolean;
116
+ idempotencyKeys: boolean;
117
+ streaming: boolean;
118
+ };
119
+ private seq;
120
+ constructor(transport: LoopbackTransport);
121
+ invoke(binding: ToolBinding, d: ToolDescriptor, input: unknown, ctx: ToolInvocationContext): Promise<unknown>;
122
+ }
123
+ /** The handler-facing `tool-use` capability over a task's pinned tools (Capability v1 operation I/O). */
124
+ export declare class ToolUseCapability {
125
+ private readonly executor;
126
+ private readonly registry;
127
+ private readonly pins;
128
+ constructor(executor: ToolExecutor, registry: InMemoryToolRegistry, pins: readonly ToolPin[]);
129
+ listTools(): {
130
+ tools: ToolDescriptor[];
131
+ };
132
+ call(input: {
133
+ toolId: string;
134
+ input: unknown;
135
+ }, ctx: ToolInvocationContext & {
136
+ stepKey?: string;
137
+ }): Promise<{
138
+ output: unknown;
139
+ }>;
140
+ }
package/dist/tools.js ADDED
@@ -0,0 +1,476 @@
1
+ /** Tool v1: registry with governed lifecycle, provider registry, executor (PEP + audit) and two direct adapters. */
2
+ import { createHash } from 'node:crypto';
3
+ import { AgentropyError, digestOf, enforcePolicy, isAgentropyError, validateAgainst, validateToolBinding, validateToolDescriptor, } from '@agentropy/core';
4
+ import { conflicts, effectiveStatus, lifecycleKey, moveLifecycle, readLifecycle, readLifecycles, } from './lifecycle.js';
5
+ /** Writes mandatory audit intent; any failure is AuditCommitUnavailable and the protected operation must not proceed. */
6
+ export async function recordAudit(audit, event) {
7
+ try {
8
+ await audit.record(event);
9
+ }
10
+ catch (cause) {
11
+ throw new AgentropyError('AuditCommitUnavailable', 'Mandatory audit intent could not be committed', { details: { action: event.action }, cause });
12
+ }
13
+ }
14
+ const refKey = (id, version) => `${id}@${version}`;
15
+ export class InMemoryToolRegistry {
16
+ security;
17
+ verify;
18
+ options;
19
+ records = new Map();
20
+ constructor(security,
21
+ /** Decides whether provenance is trusted (signature/allow-list check). Never derived from the manifest itself. */
22
+ verify,
23
+ /**
24
+ * With a `store`, the status an operator sets (activate, suspend, revoke) is kept there (FEAT-074): another worker
25
+ * on the store refuses a revoked tool at once, and a restart does not bring it back, because `register` adopts the
26
+ * stored status and `revoked` is final.
27
+ */
28
+ options = {}) {
29
+ this.security = security;
30
+ this.verify = verify;
31
+ this.options = options;
32
+ }
33
+ async guard(admin, operation, toolId) {
34
+ await enforcePolicy(this.security.pdp, {
35
+ principal: admin,
36
+ action: `tool-admin:${operation}`,
37
+ resource: { type: 'tool', id: toolId, tenantId: admin.tenantId },
38
+ });
39
+ await recordAudit(this.security.audit, {
40
+ type: `tool.${operation}`,
41
+ tenantId: admin.tenantId,
42
+ principalId: admin.id,
43
+ action: `tool-admin:${operation}`,
44
+ resource: { type: 'tool', id: toolId },
45
+ decision: 'allow',
46
+ at: this.security.now(),
47
+ });
48
+ }
49
+ async register(descriptor, bindings, provenance, admin) {
50
+ const d = validateToolDescriptor(structuredClone(descriptor));
51
+ const bs = bindings.map((b) => validateToolBinding(structuredClone(b)));
52
+ if (bs.length === 0 ||
53
+ bs.some((b) => b.toolId !== d.id || b.toolVersion !== d.version)) {
54
+ throw new AgentropyError('InvalidConfiguration', 'Bindings must target the registered tool version', { details: { reason: 'binding', id: d.id } });
55
+ }
56
+ if (new Set(bs.map((b) => b.bindingId)).size !== bs.length)
57
+ throw new AgentropyError('InvalidConfiguration', 'Duplicate binding IDs', { details: { reason: 'binding' } });
58
+ const digest = digestOf(d);
59
+ const existing = this.records.get(refKey(d.id, d.version));
60
+ if (existing) {
61
+ if (existing.provenance.digest === digest)
62
+ return (await this.refreshed(d)) ?? structuredClone(existing);
63
+ throw new AgentropyError('InvalidConfiguration', `${d.id}@${d.version} is already registered with different content`, { details: { reason: 'immutable', id: d.id } });
64
+ }
65
+ const row = this.options.store
66
+ ? (await readLifecycle(this.options.store, 'tool', d))?.value
67
+ : undefined;
68
+ if (conflicts(row, digest))
69
+ throw new AgentropyError('InvalidConfiguration', `${d.id}@${d.version} is already registered with different content`, { details: { reason: 'immutable', id: d.id } });
70
+ await this.guard(admin, 'register', d.id);
71
+ const record = {
72
+ descriptor: d,
73
+ provenance: {
74
+ publisher: provenance.publisher,
75
+ source: provenance.source,
76
+ digest,
77
+ verified: this.verify(d, provenance),
78
+ },
79
+ bindings: bs,
80
+ status: 'registered',
81
+ revision: 1,
82
+ };
83
+ // A restart finds the tool as an operator left it: suspended and revoked stay so.
84
+ record.status = effectiveStatus('registered', row, digest, record.provenance.verified);
85
+ this.records.set(refKey(d.id, d.version), record);
86
+ return structuredClone(record);
87
+ }
88
+ /** The record with the status the store has (this process's own when it has no store). */
89
+ async refreshed(ref) {
90
+ const r = this.records.get(refKey(ref.id, ref.version));
91
+ if (!r)
92
+ return undefined;
93
+ if (this.options.store) {
94
+ const row = (await readLifecycle(this.options.store, 'tool', ref))?.value;
95
+ const status = effectiveStatus(r.status, row, r.provenance.digest, r.provenance.verified);
96
+ if (status !== r.status) {
97
+ r.status = status;
98
+ r.revision += 1;
99
+ }
100
+ }
101
+ return structuredClone(r);
102
+ }
103
+ async activate(ref, admin) {
104
+ const r = this.require(ref);
105
+ if (!r.provenance.verified)
106
+ throw new AgentropyError('PermissionDenied', 'Unverified tools cannot be activated', { details: { reason: 'unverified', id: ref.id } });
107
+ return this.move(r, admin, 'activate', ['registered', 'suspended'], 'active');
108
+ }
109
+ async suspend(ref, admin) {
110
+ return this.move(this.require(ref), admin, 'suspend', ['active'], 'suspended');
111
+ }
112
+ async revoke(ref, admin) {
113
+ return this.move(this.require(ref), admin, 'revoke', ['registered', 'active', 'suspended'], 'revoked');
114
+ }
115
+ get(ref) {
116
+ const r = this.records.get(refKey(ref.id, ref.version));
117
+ return r ? structuredClone(r) : undefined;
118
+ }
119
+ /**
120
+ * Every version of a tool with this process's own status, which only moves when this process acts on it or calls
121
+ * `refreshed`. What must agree with other workers on the store (task acceptance) uses `refreshedVersions`.
122
+ */
123
+ versions(id) {
124
+ return [...this.records.values()]
125
+ .filter((r) => r.descriptor.id === id)
126
+ .map((r) => structuredClone(r));
127
+ }
128
+ /**
129
+ * Every version of a tool with the status the store has (FIX-084): an activation or revoke on another worker counts.
130
+ * Task acceptance resolves against this. Without a store it answers as `versions` does.
131
+ */
132
+ async refreshedVersions(id) {
133
+ const mine = [...this.records.values()].filter((r) => r.descriptor.id === id);
134
+ if (this.options.store && mine.length > 0) {
135
+ const rows = await readLifecycles(this.options.store, 'tool');
136
+ for (const r of mine) {
137
+ const status = effectiveStatus(r.status, rows.get(lifecycleKey('tool', r.descriptor)), r.provenance.digest, r.provenance.verified);
138
+ if (status !== r.status) {
139
+ r.status = status;
140
+ r.revision += 1;
141
+ }
142
+ }
143
+ }
144
+ return mine.map((r) => structuredClone(r));
145
+ }
146
+ /** Metadata only. Discovery never implies invocation permission. */
147
+ async discover(query, caller) {
148
+ void caller;
149
+ const text = query.text?.toLowerCase();
150
+ const rows = this.options.store
151
+ ? await readLifecycles(this.options.store, 'tool')
152
+ : new Map();
153
+ return [...this.records.values()]
154
+ .filter((r) => effectiveStatus(r.status, rows.get(lifecycleKey('tool', r.descriptor)), r.provenance.digest, r.provenance.verified) !== 'revoked')
155
+ .filter((r) => text
156
+ ? `${r.descriptor.id} ${r.descriptor.description}`
157
+ .toLowerCase()
158
+ .includes(text)
159
+ : true)
160
+ .sort((a, b) => a.descriptor.id.localeCompare(b.descriptor.id) ||
161
+ a.descriptor.version.localeCompare(b.descriptor.version))
162
+ .map((r) => structuredClone(r.descriptor));
163
+ }
164
+ require(ref) {
165
+ const r = this.records.get(refKey(ref.id, ref.version));
166
+ if (!r)
167
+ throw new AgentropyError('NotFound', `Tool ${ref.id}@${ref.version} not found`, { details: { kind: 'tool' } });
168
+ return r;
169
+ }
170
+ async move(r, admin, operation, from, to) {
171
+ // What other workers did counts: a tool revoked elsewhere cannot be activated here.
172
+ const known = (await this.refreshed(r.descriptor)).status;
173
+ if (!from.includes(known))
174
+ throw new AgentropyError('InvalidState', `Cannot ${operation} a ${known} tool`, { details: { status: known } });
175
+ await this.guard(admin, operation, r.descriptor.id);
176
+ if (this.options.store)
177
+ await moveLifecycle(this.options.store, 'tool', r.descriptor, {
178
+ from,
179
+ to,
180
+ local: r.status,
181
+ digest: r.provenance.digest,
182
+ by: admin.id,
183
+ at: this.security.now(),
184
+ });
185
+ r.status = to;
186
+ r.revision += 1;
187
+ return structuredClone(r);
188
+ }
189
+ }
190
+ export class ToolProviderRegistry {
191
+ providers = new Map();
192
+ register(provider) {
193
+ this.providers.set(refKey(provider.id, provider.version), provider);
194
+ }
195
+ has(id, version) {
196
+ return this.providers.has(refKey(id, version));
197
+ }
198
+ get(id, version) {
199
+ const p = this.providers.get(refKey(id, version));
200
+ if (!p)
201
+ throw new AgentropyError('ProviderUnavailable', `Tool provider ${id}@${version} is not registered`, { details: { kind: 'tool-provider' } });
202
+ return p;
203
+ }
204
+ }
205
+ /** Derived idempotency key: hash(tenantId, taskId, capabilityId, operation, stepKey) — Agent v1 "Idempotent side effects". */
206
+ export function deriveIdempotencyKey(tenantId, taskId, capabilityId, operation, stepKey) {
207
+ return createHash('sha256')
208
+ .update(JSON.stringify([tenantId, taskId, capabilityId, operation, stepKey]))
209
+ .digest('hex');
210
+ }
211
+ const TRANSPORT_CODES = new Set([
212
+ 'ProviderUnavailable',
213
+ 'Timeout',
214
+ 'UnknownAcceptance',
215
+ 'RemoteUnavailable',
216
+ 'QuotaExceeded',
217
+ ]);
218
+ export class DefaultToolExecutor {
219
+ o;
220
+ constructor(o) {
221
+ this.o = o;
222
+ }
223
+ async invoke(pin, input, ctx) {
224
+ // 1. The pinned record must still exist unchanged.
225
+ // The status comes from the store, not from this process's memory: a revoke can have come from another worker.
226
+ const record = await this.o.registry.refreshed({
227
+ id: pin.toolId,
228
+ version: pin.toolVersion,
229
+ });
230
+ if (!record || record.provenance.digest !== pin.digest) {
231
+ throw new AgentropyError('IncompatibleVersion', `Pinned tool ${pin.toolId}@${pin.toolVersion} is no longer available unchanged`, { details: { kind: 'tool' } });
232
+ }
233
+ // 2. Lifecycle status.
234
+ if (record.status !== 'active')
235
+ throw new AgentropyError('PermissionDenied', `Tool ${pin.toolId} is ${record.status}`, { details: { status: record.status } });
236
+ const d = record.descriptor;
237
+ // 3–4. Tenant, then a fresh PDP decision (never an acceptance-time Allow).
238
+ await enforcePolicy(this.o.pdp, {
239
+ principal: ctx.principal,
240
+ action: d.permission,
241
+ resource: { type: 'tool', id: d.id, tenantId: ctx.tenantId },
242
+ }, ctx.signal);
243
+ // 5. Step key for external effects.
244
+ if (d.effect === 'external' && !ctx.stepKey)
245
+ throw new AgentropyError('SchemaViolation', `Tool ${d.id} has an external effect and requires a stepKey`, { details: { reason: 'missingStepKey' } });
246
+ // 6. Input schema.
247
+ validateAgainst(d.inputSchema, input, `${d.id} input`);
248
+ // 7a. Binding and provider; a provider that cannot honor idempotency keys may only serve an external tool
249
+ // that explicitly declares at-least-once semantics (Tool v1 step 8, R-34, AC-07).
250
+ const binding = record.bindings.find((b) => b.bindingId === pin.bindingId);
251
+ if (!binding)
252
+ throw new AgentropyError('IncompatibleVersion', `Binding ${pin.bindingId} no longer exists`, { details: { kind: 'tool-binding' } });
253
+ const provider = this.o.providers.get(binding.providerId, binding.providerVersion);
254
+ if (d.effect === 'external' &&
255
+ d.idempotency !== 'at-least-once' &&
256
+ !provider.features.idempotencyKeys)
257
+ throw new AgentropyError('InvalidConfiguration', `Provider ${provider.id} cannot honor idempotency keys; ${d.id} must declare idempotency "at-least-once"`, { details: { kind: 'tool-binding', bindingId: binding.bindingId } });
258
+ // 7b. Audit intent before dispatch.
259
+ await recordAudit(this.o.audit, {
260
+ type: 'tool.invoke',
261
+ tenantId: ctx.tenantId,
262
+ principalId: ctx.principal.id,
263
+ action: d.permission,
264
+ resource: { type: 'tool', id: d.id },
265
+ decision: 'allow',
266
+ taskId: ctx.taskId,
267
+ details: {
268
+ toolVersion: d.version,
269
+ bindingId: pin.bindingId,
270
+ providerId: pin.providerId,
271
+ },
272
+ at: this.o.now(),
273
+ });
274
+ // 8. Dispatch.
275
+ const idempotencyKey = ctx.idempotencyKey ??
276
+ (ctx.stepKey
277
+ ? deriveIdempotencyKey(ctx.tenantId, ctx.taskId, 'tool-use', `call:${d.id}`, ctx.stepKey)
278
+ : undefined);
279
+ const attempt = async (b, p) => {
280
+ const credential = b.credentialRef
281
+ ? await this.resolveCredential(b.credentialRef, ctx)
282
+ : undefined;
283
+ const timeoutMs = typeof b.config.timeoutMs === 'number'
284
+ ? b.config.timeoutMs
285
+ : (this.o.defaultTimeoutMs ?? 30_000);
286
+ return this.dispatch(p, b, d, input, { ...ctx, idempotencyKey, credential }, timeoutMs);
287
+ };
288
+ let output;
289
+ try {
290
+ output = await attempt(binding, provider);
291
+ }
292
+ catch (err) {
293
+ // D-04 failover (opt-in): a read-only tool may move to the bindings its pinned binding lists in
294
+ // `config.fallbackBindings`, in that order, after an outage or timeout. Tools with effects never fail over
295
+ // (a second provider could not deduplicate the first one's effect); the task-level retry handles them.
296
+ const fallbacks = Array.isArray(binding.config.fallbackBindings)
297
+ ? binding.config.fallbackBindings.filter((x) => typeof x === 'string')
298
+ : [];
299
+ if (d.effect !== 'read' ||
300
+ !(isAgentropyError(err, 'ProviderUnavailable') ||
301
+ isAgentropyError(err, 'Timeout')))
302
+ throw err;
303
+ let last = err;
304
+ let recovered = false;
305
+ for (const id of fallbacks) {
306
+ const alt = record.bindings.find((b) => b.bindingId === id);
307
+ if (!alt || alt.bindingId === binding.bindingId)
308
+ continue;
309
+ if (!this.o.providers.has(alt.providerId, alt.providerVersion))
310
+ continue;
311
+ try {
312
+ output = await attempt(alt, this.o.providers.get(alt.providerId, alt.providerVersion));
313
+ recovered = true;
314
+ break;
315
+ }
316
+ catch (e) {
317
+ last = e;
318
+ }
319
+ }
320
+ if (!recovered)
321
+ throw last;
322
+ }
323
+ // 9. Output schema.
324
+ if (d.outputSchema !== undefined)
325
+ validateAgainst(d.outputSchema, output, `${d.id} output`);
326
+ return output;
327
+ }
328
+ async resolveCredential(ref, ctx) {
329
+ if (!this.o.credentials)
330
+ throw new AgentropyError('InvalidConfiguration', 'Binding needs a credential but no CredentialProvider is configured', { details: { reason: 'credential' } });
331
+ try {
332
+ return await this.o.credentials.resolve(ref, {
333
+ tenantId: ctx.tenantId,
334
+ principal: ctx.principal,
335
+ purpose: 'tool-invocation',
336
+ });
337
+ }
338
+ catch (err) {
339
+ if (isAgentropyError(err))
340
+ throw err;
341
+ throw new AgentropyError('ProviderUnavailable', 'Credential could not be resolved', { details: { kind: 'credential' } });
342
+ }
343
+ }
344
+ async dispatch(provider, binding, d, input, ctx, timeoutMs) {
345
+ const controller = new AbortController();
346
+ const onAbort = () => controller.abort(ctx.signal.reason);
347
+ ctx.signal.addEventListener('abort', onAbort, { once: true });
348
+ let timer;
349
+ const timeout = new Promise((_, reject) => {
350
+ timer = setTimeout(() => {
351
+ controller.abort(new Error('timeout'));
352
+ // For a read the effect is known not to have happened; for anything else the outcome is unknown.
353
+ reject(d.effect === 'read'
354
+ ? new AgentropyError('Timeout', `Tool ${d.id} timed out`, {
355
+ details: { kind: 'tool' },
356
+ })
357
+ : new AgentropyError('UnknownAcceptance', `Tool ${d.id} outcome unknown after timeout`, { details: { kind: 'tool' } }));
358
+ }, timeoutMs);
359
+ });
360
+ try {
361
+ return await Promise.race([
362
+ provider.invoke(binding, d, input, {
363
+ ...ctx,
364
+ signal: controller.signal,
365
+ }),
366
+ timeout,
367
+ ]);
368
+ }
369
+ catch (err) {
370
+ if (isAgentropyError(err) &&
371
+ (TRANSPORT_CODES.has(err.code) || err.code === 'SchemaViolation'))
372
+ throw err;
373
+ // An unclassified failure of a non-read call may have had an effect.
374
+ throw d.effect === 'read'
375
+ ? new AgentropyError('ProviderUnavailable', `Tool ${d.id} failed`, {
376
+ details: { kind: 'tool' },
377
+ cause: err,
378
+ })
379
+ : new AgentropyError('UnknownAcceptance', `Tool ${d.id} outcome unknown`, { details: { kind: 'tool' }, cause: err });
380
+ }
381
+ finally {
382
+ clearTimeout(timer);
383
+ ctx.signal.removeEventListener('abort', onAbort);
384
+ }
385
+ }
386
+ }
387
+ /** Direct adapter: calls an in-process function selected by `config.function`. */
388
+ export class DirectToolProvider {
389
+ functions;
390
+ id = 'direct';
391
+ version = '1.0.0';
392
+ features = {
393
+ protocol: 'direct',
394
+ protocolVersion: '1',
395
+ cancellation: true,
396
+ idempotencyKeys: true,
397
+ streaming: false,
398
+ };
399
+ constructor(functions) {
400
+ this.functions = functions;
401
+ }
402
+ async invoke(binding, _d, input, ctx) {
403
+ const fn = this.functions[String(binding.config.function)];
404
+ if (!fn)
405
+ throw new AgentropyError('ProviderUnavailable', 'Direct tool function not found', { details: { kind: 'tool-function' } });
406
+ return fn(input, ctx);
407
+ }
408
+ }
409
+ /** Second adapter: serializes calls into a JSON-RPC envelope over an injected transport (protocol-shaped, offline). */
410
+ export class LoopbackJsonRpcToolProvider {
411
+ transport;
412
+ id = 'loopback';
413
+ version = '1.0.0';
414
+ features = {
415
+ protocol: 'jsonrpc-loopback',
416
+ protocolVersion: '2.0',
417
+ cancellation: false,
418
+ idempotencyKeys: true,
419
+ streaming: false,
420
+ };
421
+ seq = 0;
422
+ constructor(transport) {
423
+ this.transport = transport;
424
+ }
425
+ async invoke(binding, d, input, ctx) {
426
+ const request = {
427
+ jsonrpc: '2.0',
428
+ id: String(++this.seq),
429
+ method: String(binding.config.method ?? d.id),
430
+ params: {
431
+ arguments: input,
432
+ ...(ctx.idempotencyKey ? { idempotencyKey: ctx.idempotencyKey } : {}),
433
+ },
434
+ };
435
+ const raw = await this.transport(JSON.stringify(request));
436
+ let response;
437
+ try {
438
+ response = JSON.parse(raw);
439
+ }
440
+ catch {
441
+ throw new AgentropyError('ProviderUnavailable', 'Malformed tool response', { details: { kind: 'tool' } });
442
+ }
443
+ if (response.error) {
444
+ // Remote error text is untrusted: keep only its numeric code.
445
+ throw new AgentropyError('ProviderUnavailable', 'Remote tool error', {
446
+ details: { kind: 'tool', remoteCode: response.error.code },
447
+ });
448
+ }
449
+ return response.result;
450
+ }
451
+ }
452
+ /** The handler-facing `tool-use` capability over a task's pinned tools (Capability v1 operation I/O). */
453
+ export class ToolUseCapability {
454
+ executor;
455
+ registry;
456
+ pins;
457
+ constructor(executor, registry, pins) {
458
+ this.executor = executor;
459
+ this.registry = registry;
460
+ this.pins = pins;
461
+ }
462
+ listTools() {
463
+ return {
464
+ tools: this.pins
465
+ .map((p) => this.registry.get({ id: p.toolId, version: p.toolVersion })
466
+ ?.descriptor)
467
+ .filter((d) => d !== undefined),
468
+ };
469
+ }
470
+ async call(input, ctx) {
471
+ const pin = this.pins.find((p) => p.toolId === input.toolId);
472
+ if (!pin)
473
+ throw new AgentropyError('CapabilityNotDeclared', `Tool ${input.toolId} is not pinned for this task`, { details: { kind: 'tool' } });
474
+ return { output: await this.executor.invoke(pin, input.input, ctx) };
475
+ }
476
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Wake-up evaluation index (FEAT-033.2, R-06). Each armed registration carries `checkAt`: the time from which the
3
+ * scheduler evaluates it. Timers and schedules set it to their due time; event, human-action and child-task
4
+ * conditions set it to "now" through `pokeWakeups` when what they wait for happens, in the same transaction.
5
+ * The poll reads only registrations with `checkAt <= now`, plus a periodic full scan as a backstop.
6
+ */
7
+ import type { StoreTx } from '@agentropy/core';
8
+ /** Marks a task's armed wake-ups for evaluation by the next poll. */
9
+ export declare function pokeWakeups(tx: StoreTx, taskId: string, now: string): Promise<void>;
@@ -0,0 +1,11 @@
1
+ /** Marks a task's armed wake-ups for evaluation by the next poll. */
2
+ export async function pokeWakeups(tx, taskId, now) {
3
+ for (const w of await tx.find('wakeups', {
4
+ where: { taskId, status: 'armed' },
5
+ }))
6
+ if (w.value.checkAt == null || w.value.checkAt > now)
7
+ await tx.update('wakeups', w.id, w.revision, {
8
+ ...w.value,
9
+ checkAt: now,
10
+ });
11
+ }