@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.
Files changed (85) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +38 -1
  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 +41 -5
package/dist/outbox.js ADDED
@@ -0,0 +1,327 @@
1
+ /**
2
+ * Outbox relay and TaskEvent streams (messaging contract "Publication and inbox reconciliation", R-29, AC-19).
3
+ *
4
+ * Transitions and their outbox rows commit together (TaskService). The relay leases nothing: it reads unpublished
5
+ * rows in commit order, hands each to every consumer and only then marks it published. A crash anywhere before
6
+ * the mark re-delivers the row after restart, so delivery is at-least-once and consumers deduplicate by event ID
7
+ * (or by the `(revision, sequence)` pair). No external exactly-once is claimed.
8
+ *
9
+ * With a leader lease (`relayId`, several workers on one store) only the leader delivers to `consumers` and marks
10
+ * rows published. `localConsumers` (in-process signals such as subscription wake-ups) are fed by every relay,
11
+ * leader or not, by following the outbox in seq order after a cursor; seq order is commit order, so the cursor
12
+ * never skips a row (FEAT-032.5).
13
+ */
14
+ import { isAfter, TASK_MACHINE, isTerminal, METRICS, } from '@agentropy/core';
15
+ export function toTaskEvent(r) {
16
+ return {
17
+ eventId: r.eventId,
18
+ taskId: r.aggregateId,
19
+ revision: r.revision,
20
+ sequence: r.sequence,
21
+ type: r.type,
22
+ status: r.status,
23
+ occurredAt: r.occurredAt,
24
+ ...(r.data !== undefined ? { data: r.data } : {}),
25
+ tenantId: r.tenantId,
26
+ correlationId: r.correlationId,
27
+ };
28
+ }
29
+ export class OutboxRelay {
30
+ o;
31
+ consumers;
32
+ local;
33
+ draining;
34
+ /** Seq of the last row handed to local consumers (lease mode); `undefined` until the first follow. */
35
+ cursor;
36
+ constructor(o) {
37
+ this.o = o;
38
+ this.local = [...(o.localConsumers ?? [])];
39
+ // Without a lease this relay is the only one: local consumers ride along with the shared ones.
40
+ this.consumers = [...(o.consumers ?? []), ...(o.relayId ? [] : this.local)];
41
+ }
42
+ register(consumer) {
43
+ if (this.consumers.some((c) => c.id === consumer.id))
44
+ throw new RangeError(`Consumer ${consumer.id} is already registered`);
45
+ this.consumers.push(consumer);
46
+ }
47
+ observe(r) {
48
+ const t = this.o.telemetry;
49
+ if (!t)
50
+ return;
51
+ if (this.o.now)
52
+ t.record(METRICS.outboxLag, Math.max(0, Date.parse(this.o.now()) - Date.parse(r.occurredAt)), { 'agentropy.event.type': r.type });
53
+ if (r.sequence === 0 && isTerminal(TASK_MACHINE, r.status))
54
+ t.count(METRICS.tasksFinished, 1, {
55
+ 'agentropy.task.status': r.status,
56
+ ...(r.payload.outcome
57
+ ? { 'agentropy.outcome.code': r.payload.outcome.code }
58
+ : {}),
59
+ });
60
+ }
61
+ /**
62
+ * Rows that consumers keep failing on (`attempts` at or above `minAttempts`). Delivery is in order, so the oldest
63
+ * of them holds back every later row: this is what an operator or a readiness probe looks at (FEAT-039.4).
64
+ */
65
+ async stuck(minAttempts = 5) {
66
+ const rows = await this.o.store.transaction((tx) => tx.find('outbox', {
67
+ where: { published: 0 },
68
+ orderBy: 'seq',
69
+ limit: 100,
70
+ }));
71
+ return rows
72
+ .filter((r) => r.value.attempts >= minAttempts)
73
+ .map((r) => ({
74
+ eventId: r.value.eventId,
75
+ attempts: r.value.attempts,
76
+ occurredAt: r.value.occurredAt,
77
+ ...(r.value.lastError ? { lastError: r.value.lastError } : {}),
78
+ }));
79
+ }
80
+ /** Publish pending rows in commit order; stops at the first failing row so order is preserved. Returns rows published. */
81
+ drain() {
82
+ // One drain at a time per relay keeps per-relay order; concurrent callers share the running drain.
83
+ this.draining ??= this.drainOnce().finally(() => (this.draining = undefined));
84
+ return this.draining;
85
+ }
86
+ /** Acquire or renew the relay leader lease; false while another relay holds a live lease. */
87
+ async lead() {
88
+ if (!this.o.relayId)
89
+ return true;
90
+ const now = this.o.now?.() ?? new Date().toISOString();
91
+ const until = new Date(Date.parse(now) + (this.o.leaseMs ?? 30_000)).toISOString();
92
+ return this.o.store.transaction(async (tx) => {
93
+ const cur = await tx.get('leases', 'outbox-relay');
94
+ if (!cur) {
95
+ await tx.insert('leases', 'outbox-relay', {
96
+ kind: 'relay',
97
+ holder: this.o.relayId,
98
+ expiresAt: until,
99
+ });
100
+ return true;
101
+ }
102
+ if (cur.value.holder !== this.o.relayId && cur.value.expiresAt > now)
103
+ return false;
104
+ await tx.update('leases', cur.id, cur.revision, {
105
+ kind: 'relay',
106
+ holder: this.o.relayId,
107
+ expiresAt: until,
108
+ });
109
+ return true;
110
+ });
111
+ }
112
+ async drainOnce() {
113
+ const published = (await this.lead()) ? await this.publish() : 0;
114
+ if (this.o.relayId && this.local.length)
115
+ await this.follow();
116
+ return published;
117
+ }
118
+ /** Hands every committed row after the cursor to the local consumers, published or not. */
119
+ async follow() {
120
+ const limit = this.o.batchSize ?? 100;
121
+ // A process that has just started has no subscribers yet: start at the newest row, not at the first one ever
122
+ // written (FEAT-039.4). Subscriptions replay from the outbox themselves.
123
+ this.cursor ??=
124
+ (await this.o.store.transaction((tx) => tx.find('outbox', {
125
+ orderBy: 'seq',
126
+ descending: true,
127
+ limit: 1,
128
+ })))[0]?.seq ?? 0;
129
+ for (;;) {
130
+ const rows = await this.o.store.transaction((tx) => tx.find('outbox', {
131
+ afterSeq: this.cursor,
132
+ orderBy: 'seq',
133
+ limit,
134
+ }));
135
+ for (const row of rows) {
136
+ const event = toTaskEvent(row.value);
137
+ for (const c of this.local)
138
+ await c.handle(event).catch(() => undefined);
139
+ this.cursor = row.seq;
140
+ }
141
+ if (rows.length < limit)
142
+ return;
143
+ }
144
+ }
145
+ async publish() {
146
+ let published = 0;
147
+ const at = () => Date.parse(this.o.now?.() ?? new Date().toISOString());
148
+ const started = at();
149
+ const budget = this.o.drainBudgetMs ?? 5_000;
150
+ const renewEvery = (this.o.leaseMs ?? 30_000) / 3;
151
+ let renewedAt = started;
152
+ // Between rows: stop when the budget is spent, and renew the leader lease while a long drain goes on (a drain
153
+ // that outlasts the lease would let another relay take over and deliver the same rows again). A relay that finds
154
+ // its lease taken stops.
155
+ const proceed = async () => {
156
+ const now = at();
157
+ if (now - started >= budget)
158
+ return false;
159
+ if (this.o.relayId && now - renewedAt >= renewEvery) {
160
+ if (!(await this.lead()))
161
+ return false;
162
+ renewedAt = now;
163
+ }
164
+ return true;
165
+ };
166
+ for (;;) {
167
+ const pending = await this.o.store.transaction((tx) => tx.find('outbox', {
168
+ where: { published: 0 },
169
+ orderBy: 'seq',
170
+ limit: this.o.batchSize ?? 100,
171
+ }));
172
+ if (!pending.length)
173
+ return published;
174
+ for (const row of pending) {
175
+ const event = toTaskEvent(row.value);
176
+ try {
177
+ this.o.faults?.checkpoint('relay.deliver');
178
+ for (const c of this.consumers)
179
+ await c.handle(event);
180
+ this.o.faults?.checkpoint('relay.markPublished');
181
+ this.observe(row.value);
182
+ }
183
+ catch (err) {
184
+ this.o.telemetry?.count(METRICS.outboxFailures, 1, {
185
+ 'agentropy.event.type': row.value.type,
186
+ });
187
+ const poisoned = await this.o.store.transaction(async (tx) => {
188
+ const cur = await tx.get('outbox', row.id);
189
+ if (!cur || cur.value.published !== 0)
190
+ return false;
191
+ const attempts = cur.value.attempts + 1;
192
+ const give = this.o.poisonAfter !== undefined &&
193
+ attempts >= this.o.poisonAfter;
194
+ await tx.update('outbox', cur.id, cur.revision, {
195
+ ...cur.value,
196
+ attempts,
197
+ lastError: err instanceof Error ? err.name : 'Error',
198
+ ...(give ? { published: 1, poisoned: true } : {}),
199
+ });
200
+ return give;
201
+ });
202
+ if (poisoned) {
203
+ this.o.telemetry?.count(METRICS.outboxPoisoned, 1, {
204
+ 'agentropy.event.type': row.value.type,
205
+ });
206
+ published++;
207
+ if (!(await proceed()))
208
+ return published;
209
+ continue; // given up on: the next row is delivered
210
+ }
211
+ return published;
212
+ }
213
+ await this.o.store.transaction(async (tx) => {
214
+ const cur = await tx.get('outbox', row.id);
215
+ if (cur && cur.value.published === 0)
216
+ await tx.update('outbox', cur.id, cur.revision, {
217
+ ...cur.value,
218
+ published: 1,
219
+ });
220
+ });
221
+ published++;
222
+ if (!(await proceed()))
223
+ return published;
224
+ }
225
+ }
226
+ }
227
+ }
228
+ /**
229
+ * Live TaskEvent fan-out for `AgentService.subscribe`: replays committed events from the outbox, then follows
230
+ * relay deliveries. Duplicates and replays at or below the last seen `(revision, sequence)` are dropped (AC-17).
231
+ */
232
+ export class TaskEventStream {
233
+ tasks;
234
+ id = 'task-event-stream';
235
+ listeners = new Map();
236
+ constructor(tasks) {
237
+ this.tasks = tasks;
238
+ }
239
+ async handle(event) {
240
+ for (const wake of this.listeners.get(event.taskId) ?? [])
241
+ wake();
242
+ }
243
+ /**
244
+ * Events of one visible task after `from`, ending after its terminal event, or as soon as `abort` fires (the
245
+ * subscription is released at once, not at the task's next event).
246
+ */
247
+ async *subscribe(taskId, caller, from, abort) {
248
+ await this.tasks.visible(taskId, caller);
249
+ const aborted = new Promise((r) => {
250
+ if (abort?.aborted)
251
+ r();
252
+ else
253
+ abort?.addEventListener('abort', () => r(), { once: true });
254
+ });
255
+ let last = from;
256
+ let signal = this.signal(taskId);
257
+ // Each pass reads only the rows committed since the previous one (by seq), not the task's whole history.
258
+ let afterSeq = 0;
259
+ let terminalRow;
260
+ try {
261
+ for (;;) {
262
+ const rows = await this.tasks.o.store.transaction((tx) => tx.find('outbox', {
263
+ where: { aggregateId: taskId },
264
+ orderBy: 'seq',
265
+ afterSeq,
266
+ }));
267
+ if (rows.length)
268
+ afterSeq = rows[rows.length - 1].seq;
269
+ terminalRow ??= rows.find((r) => r.value.sequence === 0 && isTerminal(TASK_MACHINE, r.value.status))?.value;
270
+ const fresh = rows
271
+ .map((r) => r.value)
272
+ .sort((a, b) => a.revision - b.revision || a.sequence - b.sequence)
273
+ .filter((r) => isAfter(r, last));
274
+ for (const r of fresh) {
275
+ const { tenantId: _t, correlationId: _c, ...event } = toTaskEvent(r);
276
+ void _t;
277
+ void _c;
278
+ last = { revision: r.revision, sequence: r.sequence };
279
+ yield event;
280
+ }
281
+ // Events committed with the terminal transition (same transaction) were in this read; nothing follows.
282
+ if (terminalRow && !isAfter(terminalRow, last))
283
+ return;
284
+ // Events of a long-finished task may have been compacted away: stop instead of waiting forever.
285
+ if (!terminalRow) {
286
+ const t = await this.tasks.o.store.transaction((tx) => tx.get('tasks', taskId));
287
+ if (t && isTerminal(TASK_MACHINE, t.value.status))
288
+ return;
289
+ }
290
+ if (abort?.aborted)
291
+ return;
292
+ await Promise.race([signal.promise, aborted]);
293
+ if (abort?.aborted)
294
+ return;
295
+ signal = this.signal(taskId);
296
+ }
297
+ }
298
+ finally {
299
+ this.release(taskId, signal.wake);
300
+ }
301
+ }
302
+ /** Drops one listener, and the task's entry with the last one: the map must not grow with every task ever followed. */
303
+ release(taskId, wake) {
304
+ const set = this.listeners.get(taskId);
305
+ if (!set)
306
+ return;
307
+ set.delete(wake);
308
+ if (set.size === 0)
309
+ this.listeners.delete(taskId);
310
+ }
311
+ signal(taskId) {
312
+ let wake;
313
+ const promise = new Promise((r) => (wake = r));
314
+ const set = this.listeners.get(taskId) ?? new Set();
315
+ set.add(wake);
316
+ this.listeners.set(taskId, set);
317
+ const entry = {
318
+ promise: promise.then(() => {
319
+ set.delete(wake);
320
+ if (set.size === 0 && this.listeners.get(taskId) === set)
321
+ this.listeners.delete(taskId);
322
+ }),
323
+ wake,
324
+ };
325
+ return entry;
326
+ }
327
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Policy decision cache (D-19, TASK-026.3): a PolicyDecisionPoint wrapper with explicit scope, expiry and
3
+ * revocation freshness.
4
+ *
5
+ * - Scope: one entry per (tenant, principal, principal type, delegated grant, action, resource). Entries never
6
+ * cross tenants or principals, and a different grant reference is a different entry.
7
+ * - Expiry: `ttlMs` bounds staleness (default 30 s). A decision is never served after it expires.
8
+ * - Freshness: `invalidate` drops entries for a tenant, principal or grant at once (call it from grant revocation
9
+ * or policy-change notifications); `policyVersion` changes do the same when the PDP reports one.
10
+ * - Across workers (FEAT-033.1): with `shared`, the cache reads invalidations other workers recorded in the store
11
+ * (`recordPolicyInvalidation`, written by `revokeAuthority`) before serving a hit, at most every `syncMs`. A
12
+ * revocation on one worker reaches every other within `syncMs`, not `ttlMs`. If the read fails, the cache drops
13
+ * everything and asks the PDP until a read succeeds.
14
+ * - Failures are never cached: an outage, timeout or malformed decision always reaches the caller (fail closed),
15
+ * and a later call asks the PDP again.
16
+ * - Grant validity itself is never cached: GrantVerifier checks stay per protected operation.
17
+ */
18
+ import { type PolicyDecision, type PolicyDecisionPoint, type PolicyRequest, type Store, type StoreTx } from '@agentropy/core';
19
+ /** Which cached decisions an invalidation drops; every given field must match. */
20
+ export interface PolicyInvalidationFilter {
21
+ tenantId?: string;
22
+ principalId?: string;
23
+ grantRef?: string;
24
+ }
25
+ /**
26
+ * How long invalidation rows are kept. A shared cache's `ttlMs` may not exceed it: an entry older than this has
27
+ * expired anyway, so a worker that missed a pruned row serves nothing stale.
28
+ */
29
+ export declare const POLICY_INVALIDATION_RETENTION_MS = 600000;
30
+ /**
31
+ * Records an invalidation for every worker's shared cache inside `tx` (commit it with the change it reflects,
32
+ * e.g. a revocation's audit event) and prunes rows past the retention.
33
+ */
34
+ export declare function recordPolicyInvalidation(tx: StoreTx, id: string, filter: PolicyInvalidationFilter, now: string): Promise<void>;
35
+ export interface PolicyCacheOptions {
36
+ ttlMs?: number;
37
+ /** Maximum entries; the oldest are evicted first (default 10,000). */
38
+ maxEntries?: number;
39
+ now?: () => string;
40
+ /** Cache only allows (default) or both allows and denies. */
41
+ cacheDenies?: boolean;
42
+ /** Apply invalidations recorded in this store by any worker; read at most every `syncMs` (default 1000). */
43
+ shared?: {
44
+ store: Store;
45
+ syncMs?: number;
46
+ };
47
+ }
48
+ export declare class CachingPolicyDecisionPoint implements PolicyDecisionPoint {
49
+ private readonly pdp;
50
+ private readonly o;
51
+ private readonly entries;
52
+ private lastPolicyVersion?;
53
+ /** Last applied invalidation row; undefined until the first successful read. */
54
+ private cursor?;
55
+ private syncedAt;
56
+ private syncing?;
57
+ hits: number;
58
+ misses: number;
59
+ constructor(pdp: PolicyDecisionPoint, o?: PolicyCacheOptions);
60
+ /** Applies invalidations recorded since the last read; on failure drops every entry (fail closed). */
61
+ private sync;
62
+ private now;
63
+ private key;
64
+ decide(request: PolicyRequest, signal?: AbortSignal): Promise<PolicyDecision>;
65
+ /** Drop cached decisions immediately (revocation freshness). With no filter, clears everything. */
66
+ invalidate(filter?: PolicyInvalidationFilter): number;
67
+ private drop;
68
+ get size(): number;
69
+ }
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Policy decision cache (D-19, TASK-026.3): a PolicyDecisionPoint wrapper with explicit scope, expiry and
3
+ * revocation freshness.
4
+ *
5
+ * - Scope: one entry per (tenant, principal, principal type, delegated grant, action, resource). Entries never
6
+ * cross tenants or principals, and a different grant reference is a different entry.
7
+ * - Expiry: `ttlMs` bounds staleness (default 30 s). A decision is never served after it expires.
8
+ * - Freshness: `invalidate` drops entries for a tenant, principal or grant at once (call it from grant revocation
9
+ * or policy-change notifications); `policyVersion` changes do the same when the PDP reports one.
10
+ * - Across workers (FEAT-033.1): with `shared`, the cache reads invalidations other workers recorded in the store
11
+ * (`recordPolicyInvalidation`, written by `revokeAuthority`) before serving a hit, at most every `syncMs`. A
12
+ * revocation on one worker reaches every other within `syncMs`, not `ttlMs`. If the read fails, the cache drops
13
+ * everything and asks the PDP until a read succeeds.
14
+ * - Failures are never cached: an outage, timeout or malformed decision always reaches the caller (fail closed),
15
+ * and a later call asks the PDP again.
16
+ * - Grant validity itself is never cached: GrantVerifier checks stay per protected operation.
17
+ */
18
+ import { AgentropyError, digestOf, } from '@agentropy/core';
19
+ /**
20
+ * How long invalidation rows are kept. A shared cache's `ttlMs` may not exceed it: an entry older than this has
21
+ * expired anyway, so a worker that missed a pruned row serves nothing stale.
22
+ */
23
+ export const POLICY_INVALIDATION_RETENTION_MS = 600_000;
24
+ /**
25
+ * Records an invalidation for every worker's shared cache inside `tx` (commit it with the change it reflects,
26
+ * e.g. a revocation's audit event) and prunes rows past the retention.
27
+ */
28
+ export async function recordPolicyInvalidation(tx, id, filter, now) {
29
+ const horizon = Date.parse(now) - POLICY_INVALIDATION_RETENTION_MS;
30
+ for (const old of await tx.find('policyInvalidations', {
31
+ orderBy: 'seq',
32
+ })) {
33
+ if (Date.parse(old.value.at) >= horizon)
34
+ break;
35
+ await tx.remove('policyInvalidations', old.id, old.revision);
36
+ }
37
+ await tx.insert('policyInvalidations', id, {
38
+ ...(filter.tenantId !== undefined ? { tenantId: filter.tenantId } : {}),
39
+ ...(filter.principalId !== undefined
40
+ ? { principalId: filter.principalId }
41
+ : {}),
42
+ ...(filter.grantRef !== undefined
43
+ ? { grantDigest: digestOf(filter.grantRef) }
44
+ : {}),
45
+ at: now,
46
+ });
47
+ }
48
+ export class CachingPolicyDecisionPoint {
49
+ pdp;
50
+ o;
51
+ entries = new Map();
52
+ lastPolicyVersion;
53
+ /** Last applied invalidation row; undefined until the first successful read. */
54
+ cursor;
55
+ syncedAt = -Infinity;
56
+ syncing;
57
+ hits = 0;
58
+ misses = 0;
59
+ constructor(pdp, o = {}) {
60
+ this.pdp = pdp;
61
+ this.o = o;
62
+ if (o.shared && (o.ttlMs ?? 30_000) > POLICY_INVALIDATION_RETENTION_MS)
63
+ throw new AgentropyError('InvalidConfiguration', `A shared policy cache's ttlMs may not exceed ${POLICY_INVALIDATION_RETENTION_MS} ms`);
64
+ }
65
+ /** Applies invalidations recorded since the last read; on failure drops every entry (fail closed). */
66
+ async sync(now) {
67
+ const shared = this.o.shared;
68
+ if (!shared || now - this.syncedAt < (shared.syncMs ?? 1_000))
69
+ return;
70
+ this.syncing ??= (async () => {
71
+ try {
72
+ const rows = await shared.store.transaction((tx) => tx.find('policyInvalidations', {
73
+ orderBy: 'seq',
74
+ ...(this.cursor !== undefined ? { afterSeq: this.cursor } : {}),
75
+ }));
76
+ // Before the first read the cache may hold entries decided before rows that are already stored.
77
+ for (const r of rows)
78
+ this.drop(r.value);
79
+ this.cursor = rows.at(-1)?.seq ?? this.cursor ?? 0;
80
+ this.syncedAt = now;
81
+ }
82
+ catch {
83
+ this.entries.clear();
84
+ }
85
+ finally {
86
+ this.syncing = undefined;
87
+ }
88
+ })();
89
+ await this.syncing;
90
+ }
91
+ now() {
92
+ return Date.parse(this.o.now?.() ?? new Date().toISOString());
93
+ }
94
+ key(r) {
95
+ return JSON.stringify([
96
+ r.resource.tenantId,
97
+ r.principal.tenantId,
98
+ r.principal.id,
99
+ r.principal.type,
100
+ r.principal.delegatedAuthorityRef ?? null,
101
+ r.action,
102
+ r.resource.type,
103
+ r.resource.id,
104
+ ]);
105
+ }
106
+ async decide(request, signal) {
107
+ // Requests with extra context are evaluated every time: the cache key cannot see that context.
108
+ const cacheable = request.context === undefined;
109
+ const key = this.key(request);
110
+ const now = this.now();
111
+ if (cacheable) {
112
+ await this.sync(now);
113
+ const hit = this.entries.get(key);
114
+ if (hit && hit.expiresAt > now) {
115
+ this.hits++;
116
+ return hit.decision;
117
+ }
118
+ if (hit)
119
+ this.entries.delete(key);
120
+ }
121
+ this.misses++;
122
+ const decision = await this.pdp.decide(request, signal);
123
+ const effect = decision?.effect;
124
+ if (effect !== 'allow' && effect !== 'deny')
125
+ return decision; // malformed: not cached, caller fails closed
126
+ if (decision.policyVersion !== undefined &&
127
+ this.lastPolicyVersion !== undefined &&
128
+ decision.policyVersion !== this.lastPolicyVersion)
129
+ this.entries.clear(); // a new policy version invalidates everything decided under the old one
130
+ if (decision.policyVersion !== undefined)
131
+ this.lastPolicyVersion = decision.policyVersion;
132
+ if (cacheable && (effect === 'allow' || this.o.cacheDenies)) {
133
+ if (this.entries.size >= (this.o.maxEntries ?? 10_000)) {
134
+ const oldest = this.entries.keys().next().value;
135
+ if (oldest !== undefined)
136
+ this.entries.delete(oldest);
137
+ }
138
+ this.entries.set(key, {
139
+ decision,
140
+ expiresAt: now + (this.o.ttlMs ?? 30_000),
141
+ tenantId: request.resource.tenantId,
142
+ principalId: request.principal.id,
143
+ ...(request.principal.delegatedAuthorityRef
144
+ ? { grantDigest: digestOf(request.principal.delegatedAuthorityRef) }
145
+ : {}),
146
+ });
147
+ }
148
+ return decision;
149
+ }
150
+ /** Drop cached decisions immediately (revocation freshness). With no filter, clears everything. */
151
+ invalidate(filter = {}) {
152
+ return this.drop({
153
+ ...(filter.tenantId !== undefined ? { tenantId: filter.tenantId } : {}),
154
+ ...(filter.principalId !== undefined
155
+ ? { principalId: filter.principalId }
156
+ : {}),
157
+ ...(filter.grantRef !== undefined
158
+ ? { grantDigest: digestOf(filter.grantRef) }
159
+ : {}),
160
+ });
161
+ }
162
+ drop(filter) {
163
+ let n = 0;
164
+ for (const [k, e] of this.entries)
165
+ if ((filter.tenantId === undefined || e.tenantId === filter.tenantId) &&
166
+ (filter.principalId === undefined ||
167
+ e.principalId === filter.principalId) &&
168
+ (filter.grantDigest === undefined ||
169
+ e.grantDigest === filter.grantDigest)) {
170
+ this.entries.delete(k);
171
+ n++;
172
+ }
173
+ return n;
174
+ }
175
+ get size() {
176
+ return this.entries.size;
177
+ }
178
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Briefing priority and delivery policy (docs/human-actions.md "Shared effective priority", M2-04, R-26).
3
+ *
4
+ * effectiveSeverity = max(entry severity, policy floor). The floor is set by policy (e.g. a pending approval is at
5
+ * least `high`); personal preferences may only decide how much *below the floor-free range* is mentioned and can
6
+ * never hide an entry that has a floor. Delivery: `critical` interrupts (push + top of briefing); entries at or
7
+ * above the user's briefing threshold, or with a floor, are mentioned; the rest wait for on-demand reading.
8
+ */
9
+ import type { InboxEntry, Severity } from '@agentropy/core';
10
+ export declare const SEVERITY_ORDER: readonly Severity[];
11
+ export type Delivery = 'interrupt' | 'mention' | 'on-demand';
12
+ export interface InboxPreferences {
13
+ /** Lowest severity mentioned in a briefing (default `normal`): lower entries are on-demand unless floored. */
14
+ briefFrom?: Severity;
15
+ }
16
+ export interface PriorityPolicy {
17
+ /** Minimum severity for an entry, or undefined when policy sets none. Never lowered by preferences. */
18
+ floor(entry: InboxEntry): Severity | undefined;
19
+ }
20
+ /** Default floors: approvals someone must act on and failed delegated work are at least `high`. */
21
+ export declare const DEFAULT_PRIORITY_POLICY: PriorityPolicy;
22
+ export interface DeliveryDecision {
23
+ severity: Severity;
24
+ delivery: Delivery;
25
+ floored: boolean;
26
+ }
27
+ export declare function resolveDelivery(entry: InboxEntry, preferences?: InboxPreferences, policy?: PriorityPolicy): DeliveryDecision;
@@ -0,0 +1,28 @@
1
+ export const SEVERITY_ORDER = [
2
+ 'critical',
3
+ 'high',
4
+ 'normal',
5
+ 'low',
6
+ ];
7
+ const rank = (s) => SEVERITY_ORDER.indexOf(s);
8
+ /** Default floors: approvals someone must act on and failed delegated work are at least `high`. */
9
+ export const DEFAULT_PRIORITY_POLICY = {
10
+ floor: (e) => e.actionRequestId && !e.markers.resolvedAt
11
+ ? 'high'
12
+ : e.source.type === 'taskFailed'
13
+ ? 'high'
14
+ : undefined,
15
+ };
16
+ export function resolveDelivery(entry, preferences = {}, policy = DEFAULT_PRIORITY_POLICY) {
17
+ const floor = policy.floor(entry);
18
+ const severity = floor !== undefined && rank(floor) < rank(entry.severity)
19
+ ? floor
20
+ : entry.severity;
21
+ const threshold = preferences.briefFrom ?? 'normal';
22
+ const delivery = severity === 'critical'
23
+ ? 'interrupt'
24
+ : floor !== undefined || rank(severity) <= rank(threshold)
25
+ ? 'mention'
26
+ : 'on-demand';
27
+ return { severity, delivery, floored: floor !== undefined };
28
+ }
@@ -0,0 +1,19 @@
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 { type StoreTx } from '@agentropy/core';
7
+ export interface TenantQuota {
8
+ /** Non-terminal tasks at once. */
9
+ maxActiveTasks?: number;
10
+ /** New tasks accepted in any rolling 60-second window. */
11
+ maxAcceptsPerMinute?: number;
12
+ /** Agent instances that are not retired. */
13
+ maxInstances?: number;
14
+ /** Executions running at once across every worker sharing the store (M3-02); excess work waits queued. */
15
+ maxConcurrentExecutions?: number;
16
+ }
17
+ export type QuotaResolver = (tenantId: string) => TenantQuota | undefined;
18
+ export declare function checkTaskQuota(tx: StoreTx, tenantId: string, quota: TenantQuota | undefined, now: string): Promise<void>;
19
+ export declare function checkInstanceQuota(tx: StoreTx, tenantId: string, quota: TenantQuota | undefined): Promise<void>;