@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
@@ -0,0 +1,359 @@
1
+ /**
2
+ * Human actions (docs/human-actions.md, Agent v1 human-action operations, R-24, AC-08, SEC-07).
3
+ *
4
+ * The runtime is the only authority: `human-input.requestAction` creates the request and its
5
+ * `humanActionRequested` event in one journaled transaction; claim, release and decide are commands that
6
+ * re-check identity, tenant, assignment, delegated authority, policy, revision, deadline and input schema
7
+ * atomically. A decision commits a `humanActionResolved` event; the inbox projects it only after commit and
8
+ * the waiting task resumes through its `human-action` wake-up. Expiry uses the request's `dueAt` only.
9
+ */
10
+ import { AgentropyError, HUMAN_ACTION_MACHINE, assertTransition, digestOf, enforcePolicy, isTerminal, normalizeInstant, validateAgainst, } from '@agentropy/core';
11
+ import { journaled } from './inbox.js';
12
+ import { DEFAULT_LIMITS, assertMaxBytes } from './limits.js';
13
+ import { pokeWakeups } from './wake-index.js';
14
+ import { actionUsers, } from './task-service.js';
15
+ const view = (d) => {
16
+ const { decisionInput: _i, decidedBy: _b, decidedAt: _a, decisionFingerprint: _f, approvals: _p, ...rest } = d.value;
17
+ void _p;
18
+ void _i;
19
+ void _b;
20
+ void _a;
21
+ void _f;
22
+ return { ...rest, revision: d.revision };
23
+ };
24
+ const addMs = (iso, ms) => new Date(Date.parse(iso) + ms).toISOString();
25
+ const KINDS = ['approval', 'choice', 'text', 'form'];
26
+ function validateRequest(input) {
27
+ const r = input;
28
+ const bad = (why) => new AgentropyError('SchemaViolation', `human-input.requestAction: ${why}`);
29
+ if (!r || !KINDS.includes(r.kind))
30
+ throw bad('unknown kind');
31
+ if (typeof r.prompt !== 'string' || !r.prompt)
32
+ throw bad('prompt required');
33
+ if (r.inputSchema === undefined)
34
+ throw bad('inputSchema required');
35
+ if (!r.assignees ||
36
+ !(r.assignees.principalIds?.length || r.assignees.roles?.length))
37
+ throw bad('at least one assignee or role required');
38
+ if (r.onExpiry !== 'resume' && r.onExpiry !== 'fail-task')
39
+ throw bad('onExpiry must be "resume" or "fail-task"');
40
+ if (r.dueAt !== undefined)
41
+ normalizeInstant(r.dueAt, 'dueAt');
42
+ if (r.requiredApprovals !== undefined &&
43
+ (r.kind !== 'approval' ||
44
+ !Number.isInteger(r.requiredApprovals) ||
45
+ r.requiredApprovals < 1 ||
46
+ r.requiredApprovals > 5))
47
+ throw bad('requiredApprovals must be 1–5 and only on approvals');
48
+ if (r.allowSelfApproval !== undefined && r.kind !== 'approval')
49
+ throw bad('allowSelfApproval applies to approvals only');
50
+ return {
51
+ ...(r.requiredApprovals !== undefined
52
+ ? { requiredApprovals: r.requiredApprovals }
53
+ : {}),
54
+ ...(r.allowSelfApproval ? { allowSelfApproval: true } : {}),
55
+ kind: r.kind,
56
+ prompt: r.prompt,
57
+ inputSchema: r.inputSchema,
58
+ assignees: r.assignees,
59
+ ...(r.dueAt ? { dueAt: normalizeInstant(r.dueAt, 'dueAt') } : {}),
60
+ onExpiry: r.onExpiry,
61
+ };
62
+ }
63
+ export class HumanActionService {
64
+ tasks;
65
+ options;
66
+ constructor(tasks, options = {}) {
67
+ this.tasks = tasks;
68
+ this.options = options;
69
+ }
70
+ get store() {
71
+ return this.tasks.o.store;
72
+ }
73
+ now() {
74
+ return this.tasks.o.now();
75
+ }
76
+ /** Built-in `human-input.requestAction` (external effect with a step key; replay returns the original request). */
77
+ async request(input, ctx) {
78
+ const r = validateRequest(input);
79
+ assertMaxBytes(r.prompt, this.options.maxPromptBytes ?? DEFAULT_LIMITS.maxPromptBytes, 'prompt');
80
+ return journaled(this.tasks, ctx, 'human-input.requestAction', async (tx, task) => {
81
+ const requestId = this.tasks.newId('action');
82
+ assertTransition(HUMAN_ACTION_MACHINE, null, 'pending', 'H-create');
83
+ const doc = await tx.insert('humanActions', requestId, {
84
+ ...r,
85
+ requestId,
86
+ taskId: task.id,
87
+ agentInstanceId: task.value.instanceId,
88
+ tenantId: task.value.tenantId,
89
+ requestedBy: ctx.principalId,
90
+ status: 'pending',
91
+ });
92
+ await this.tasks.emit(tx, task.value, task.revision, 'humanActionRequested', {
93
+ requestId,
94
+ revision: doc.revision,
95
+ kind: r.kind,
96
+ prompt: r.prompt,
97
+ assignees: r.assignees,
98
+ ...(r.dueAt ? { dueAt: r.dueAt } : {}),
99
+ });
100
+ return { requestId, ...(r.dueAt ? { dueAt: r.dueAt } : {}) };
101
+ });
102
+ }
103
+ async get(requestId, caller) {
104
+ return this.store.transaction(async (tx) => view(await this.visible(tx, requestId, caller)));
105
+ }
106
+ async claim(requestId, caller) {
107
+ await this.authorize(requestId, caller);
108
+ return this.store.transaction(async (tx) => {
109
+ const doc = await this.actionable(tx, requestId, caller);
110
+ const a = doc.value;
111
+ if (a.status === 'claimed') {
112
+ if (a.claimedBy === caller.id)
113
+ return view(doc);
114
+ throw new AgentropyError('ActionConflict', 'Request is claimed by someone else');
115
+ }
116
+ assertTransition(HUMAN_ACTION_MACHINE, a.status, 'claimed', 'H-claim');
117
+ return view(await tx.update('humanActions', doc.id, doc.revision, {
118
+ ...a,
119
+ status: 'claimed',
120
+ claimedBy: caller.id,
121
+ claimExpiresAt: addMs(this.now(), this.options.claimMs ?? 15 * 60_000),
122
+ }));
123
+ });
124
+ }
125
+ async release(requestId, caller) {
126
+ await this.authorize(requestId, caller);
127
+ return this.store.transaction(async (tx) => {
128
+ const doc = await this.actionable(tx, requestId, caller);
129
+ if (doc.value.status === 'pending')
130
+ return view(doc);
131
+ if (doc.value.claimedBy !== caller.id)
132
+ throw new AgentropyError('NotAssignee', 'Only the claimant may release');
133
+ return view(await this.unclaim(tx, doc));
134
+ });
135
+ }
136
+ /** `AgentService.provideHumanInput`: the single command boundary for chat, UI and API decisions. */
137
+ async decide(decision, caller) {
138
+ if (!decision?.idempotencyKey)
139
+ throw new AgentropyError('SchemaViolation', 'A decision needs an idempotency key');
140
+ await this.authorize(decision.requestId, caller);
141
+ await this.store.transaction(async (tx) => {
142
+ const doc = await this.visible(tx, decision.requestId, caller);
143
+ const a = doc.value;
144
+ const fingerprint = digestOf({ by: caller.id, input: decision.input });
145
+ // Duplicate identical decision → no-op, even with the pre-decision revision; anything else after resolution conflicts.
146
+ if (a.status === 'resolved') {
147
+ if (a.decisionFingerprint === fingerprint)
148
+ return;
149
+ throw new AgentropyError('ActionConflict', 'Request was already decided differently');
150
+ }
151
+ await this.expireIfDue(tx, doc);
152
+ const live = await this.actionable(tx, decision.requestId, caller);
153
+ if (live.revision !== decision.expectedRevision)
154
+ throw new AgentropyError('StaleRevision', 'Request changed since it was presented', {
155
+ details: {
156
+ expected: decision.expectedRevision,
157
+ actual: live.revision,
158
+ },
159
+ });
160
+ if (live.value.status === 'claimed' && live.value.claimedBy !== caller.id)
161
+ throw new AgentropyError('NotAssignee', 'Request is claimed by someone else');
162
+ validateAgainst(live.value.inputSchema, decision.input, 'human decision input');
163
+ const task = (await tx.get('tasks', live.value.taskId));
164
+ // Separation of duties (FEAT-028.5): whoever delegated the work does not approve it.
165
+ if (live.value.kind === 'approval' &&
166
+ !live.value.allowSelfApproval &&
167
+ caller.id === task.value.callerId)
168
+ throw new AgentropyError('NotAssignee', 'The requester of the work cannot approve it', { details: { reason: 'selfApproval' } });
169
+ const needed = live.value.requiredApprovals ?? 1;
170
+ if (needed > 1) {
171
+ const inputDigest = digestOf(decision.input);
172
+ const prior = (live.value.approvals ?? []).filter((x) => x.by !== caller.id);
173
+ const approvals = [
174
+ ...prior,
175
+ { by: caller.id, inputDigest, at: this.now() },
176
+ ];
177
+ const agreeing = approvals.filter((x) => x.inputDigest === inputDigest).length;
178
+ if (agreeing < needed) {
179
+ await this.tasks.audit(tx, caller, {
180
+ type: 'human-action.approve-partial',
181
+ action: 'human-input:decide',
182
+ resource: { type: 'human-action', id: live.id },
183
+ decision: 'allow',
184
+ correlationId: task.value.correlationId,
185
+ taskId: task.id,
186
+ details: { agreeing, required: needed },
187
+ });
188
+ await tx.update('humanActions', live.id, live.revision, {
189
+ ...live.value,
190
+ // A partial approval releases the caller's claim so the next approver can act.
191
+ status: 'pending',
192
+ approvals,
193
+ ...(live.value.claimedBy === caller.id
194
+ ? { claimedBy: undefined, claimExpiresAt: undefined }
195
+ : {}),
196
+ });
197
+ return;
198
+ }
199
+ }
200
+ await this.tasks.audit(tx, caller, {
201
+ type: 'human-action.decide',
202
+ action: 'human-input:decide',
203
+ resource: { type: 'human-action', id: live.id },
204
+ decision: 'allow',
205
+ correlationId: task.value.correlationId,
206
+ taskId: task.id,
207
+ });
208
+ assertTransition(HUMAN_ACTION_MACHINE, live.value.status, 'resolved', 'H-resolve');
209
+ await pokeWakeups(tx, live.value.taskId, this.now());
210
+ const resolved = await tx.update('humanActions', live.id, live.revision, {
211
+ ...live.value,
212
+ status: 'resolved',
213
+ decisionInput: decision.input,
214
+ decidedBy: caller.id,
215
+ decidedAt: this.now(),
216
+ decisionFingerprint: fingerprint,
217
+ });
218
+ await this.tasks.emit(tx, task.value, task.revision, 'humanActionResolved', {
219
+ requestId: live.id,
220
+ revision: resolved.revision,
221
+ outcome: 'resolved',
222
+ decidedBy: caller.id,
223
+ assignees: actionUsers(live.value, task.value),
224
+ });
225
+ });
226
+ }
227
+ /** Expire requests past `dueAt` and return lapsed claims to `pending`. Safe to call repeatedly. */
228
+ async sweep() {
229
+ const now = this.now();
230
+ // Only what lapsed and is still open: the status index keeps the requests that were decided or expired (they
231
+ // stay in the `dueAt` and `claimExpiresAt` ranges until compaction) out of the read, and open requests that are
232
+ // not due cost nothing. A claim can lapse and so can a deadline, so a claimed request is looked up by both.
233
+ const lapsedRows = await this.store.transaction(async (tx) => [
234
+ ...(await tx.find('humanActions', {
235
+ where: { status: 'pending' },
236
+ range: { field: 'dueAt', lte: now },
237
+ })),
238
+ ...(await tx.find('humanActions', {
239
+ where: { status: 'claimed' },
240
+ range: { field: 'dueAt', lte: now },
241
+ })),
242
+ ...(await tx.find('humanActions', {
243
+ where: { status: 'claimed' },
244
+ range: { field: 'claimExpiresAt', lte: now },
245
+ })),
246
+ ]);
247
+ const open = [...new Map(lapsedRows.map((a) => [a.id, a])).values()];
248
+ let changed = 0;
249
+ for (const a of open) {
250
+ const due = a.value.dueAt && a.value.dueAt <= now;
251
+ const lapsed = a.value.status === 'claimed' &&
252
+ a.value.claimExpiresAt &&
253
+ a.value.claimExpiresAt <= now;
254
+ if (!due && !lapsed)
255
+ continue;
256
+ await this.store.transaction(async (tx) => {
257
+ const cur = await tx.get('humanActions', a.id);
258
+ if (!cur || cur.revision !== a.revision)
259
+ return;
260
+ if (due)
261
+ await this.expireIfDue(tx, cur);
262
+ else
263
+ await this.unclaim(tx, cur);
264
+ changed++;
265
+ });
266
+ }
267
+ return changed;
268
+ }
269
+ // --- guards ----------------------------------------------------------------------------------
270
+ /** Authentication, delegated authority and policy before any state is read (SEC-07). */
271
+ async authorize(requestId, caller) {
272
+ if (!caller?.id || !caller.tenantId)
273
+ throw new AgentropyError('Unauthenticated', 'No trusted principal');
274
+ await this.tasks.checkGrant(caller);
275
+ await enforcePolicy(this.tasks.o.pdp, {
276
+ principal: caller,
277
+ action: 'human-input:decide',
278
+ resource: {
279
+ type: 'human-action',
280
+ id: requestId,
281
+ tenantId: caller.tenantId,
282
+ },
283
+ });
284
+ }
285
+ /** Visible = same tenant and the caller is an assignee (by ID, or by a role the policy grants). */
286
+ async visible(tx, requestId, caller) {
287
+ if (!caller?.id || !caller.tenantId)
288
+ throw new AgentropyError('Unauthenticated', 'No trusted principal');
289
+ const doc = await tx.get('humanActions', requestId);
290
+ if (!doc || doc.value.tenantId !== caller.tenantId)
291
+ throw new AgentropyError('NotFound', 'Request not found');
292
+ if (!(await this.eligible(doc.value, caller)))
293
+ throw new AgentropyError('NotAssignee', 'Caller is not an assignee of this request');
294
+ return doc;
295
+ }
296
+ async eligible(a, caller) {
297
+ if (a.assignees.principalIds?.includes(caller.id))
298
+ return true;
299
+ for (const role of a.assignees.roles ?? []) {
300
+ const d = await this.tasks.o.pdp
301
+ .decide({
302
+ principal: caller,
303
+ action: 'human-input:act-as-role',
304
+ resource: { type: 'role', id: role, tenantId: a.tenantId },
305
+ })
306
+ .catch(() => ({ effect: 'deny' }));
307
+ if (d.effect === 'allow')
308
+ return true;
309
+ }
310
+ return false;
311
+ }
312
+ /** Visible and still open; terminal states map to their typed refusals. */
313
+ async actionable(tx, requestId, caller) {
314
+ const doc = await this.visible(tx, requestId, caller);
315
+ switch (doc.value.status) {
316
+ case 'expired':
317
+ throw new AgentropyError('ActionExpired', 'Request has expired');
318
+ case 'revoked':
319
+ throw new AgentropyError('ActionRevoked', 'Request was revoked');
320
+ case 'resolved':
321
+ throw new AgentropyError('ActionConflict', 'Request is already decided');
322
+ default:
323
+ return doc;
324
+ }
325
+ }
326
+ async unclaim(tx, doc) {
327
+ assertTransition(HUMAN_ACTION_MACHINE, doc.value.status, 'pending', 'H-release');
328
+ const { claimedBy: _c, claimExpiresAt: _e, ...rest } = doc.value;
329
+ void _c;
330
+ void _e;
331
+ return tx.update('humanActions', doc.id, doc.revision, {
332
+ ...rest,
333
+ status: 'pending',
334
+ });
335
+ }
336
+ /** Moves a past-due open request to `expired` with its event; the wake-up applies `onExpiry`. */
337
+ async expireIfDue(tx, doc) {
338
+ const a = doc.value;
339
+ if (!a.dueAt ||
340
+ a.dueAt > this.now() ||
341
+ isTerminal(HUMAN_ACTION_MACHINE, a.status))
342
+ return;
343
+ assertTransition(HUMAN_ACTION_MACHINE, a.status, 'expired', 'H-expire');
344
+ const expired = await tx.update('humanActions', doc.id, doc.revision, { ...a, status: 'expired' });
345
+ await pokeWakeups(tx, a.taskId, this.now());
346
+ const task = await tx.get('tasks', a.taskId);
347
+ if (task)
348
+ await this.tasks.emit(tx, task.value, task.revision, 'humanActionResolved', {
349
+ requestId: a.requestId,
350
+ revision: expired.revision,
351
+ outcome: 'expired',
352
+ assignees: actionUsers(a, task.value),
353
+ });
354
+ }
355
+ }
356
+ /** Built-in handler for `human-input.requestAction`. */
357
+ export function humanActionOperationHandlers(human) {
358
+ return { requestAction: (input, ctx) => human.request(input, ctx) };
359
+ }
@@ -0,0 +1,47 @@
1
+ /** Agent Implementation v1: provider registry, HandlerRegistry and the built-in native-ts provider. */
2
+ import { type Agent, type AgentDisposition, type WakeReason, type AgentImplementationProvider, type AgentImplementationRef, type HandlerRegistry, type ImplementationBinding, type ImplementationFeatures, type ImplementationProviderRegistry, type VersionedRef } from '@agentropy/core';
3
+ export declare class InMemoryHandlerRegistry implements HandlerRegistry {
4
+ private readonly handlers;
5
+ register(artifact: VersionedRef, handler: Agent): void;
6
+ unregister(artifact: VersionedRef): void;
7
+ get(artifact: VersionedRef): Agent | undefined;
8
+ }
9
+ export declare const NATIVE_TS_FEATURES: ImplementationFeatures;
10
+ /** Built-in provider for TypeScript handlers registered in a HandlerRegistry. */
11
+ export declare class NativeImplementationProvider implements AgentImplementationProvider {
12
+ readonly handlers: HandlerRegistry;
13
+ readonly id = "native-ts";
14
+ readonly version = "1.0.0";
15
+ readonly features: ImplementationFeatures;
16
+ constructor(handlers?: HandlerRegistry);
17
+ resolve(ref: AgentImplementationRef): Promise<ImplementationBinding>;
18
+ /** The handler is looked up per activation, so an unregistered artifact fails that activation with IncompatibleVersion (AC-10). */
19
+ createAgent(binding: ImplementationBinding): Agent;
20
+ }
21
+ export declare class InMemoryImplementationProviderRegistry implements ImplementationProviderRegistry {
22
+ private readonly providers;
23
+ register(provider: AgentImplementationProvider): void;
24
+ find(providerId: string, providerVersion: string): AgentImplementationProvider | undefined;
25
+ get(providerId: string, providerVersion: string): AgentImplementationProvider;
26
+ }
27
+ /** A deterministic step function: no context, no effects — the shape of a workflow-backed or rule-based agent. */
28
+ export type PureStep = (state: {
29
+ input: unknown;
30
+ checkpoint?: unknown;
31
+ wakeReason?: WakeReason;
32
+ attempt: number;
33
+ activation: number;
34
+ }) => AgentDisposition<unknown> | Promise<AgentDisposition<unknown>>;
35
+ /**
36
+ * Second implementation provider (A-02): artifacts are pure step functions registered by `id@version`.
37
+ * It declares no cooperative cancellation or progress reporting, so the runtime relies on grace-period fencing.
38
+ */
39
+ export declare class PureFunctionImplementationProvider implements AgentImplementationProvider {
40
+ readonly id = "pure-fn";
41
+ readonly version = "1.0.0";
42
+ readonly features: ImplementationFeatures;
43
+ private readonly steps;
44
+ register(artifact: VersionedRef, step: PureStep): void;
45
+ resolve(ref: AgentImplementationRef): Promise<ImplementationBinding>;
46
+ createAgent(binding: ImplementationBinding): Agent;
47
+ }
@@ -0,0 +1,138 @@
1
+ /** Agent Implementation v1: provider registry, HandlerRegistry and the built-in native-ts provider. */
2
+ import { AgentropyError, } from '@agentropy/core';
3
+ const key = (ref) => `${ref.id}@${ref.version}`;
4
+ export class InMemoryHandlerRegistry {
5
+ handlers = new Map();
6
+ register(artifact, handler) {
7
+ const existing = this.handlers.get(key(artifact));
8
+ if (existing && existing !== handler) {
9
+ throw new AgentropyError('InvalidConfiguration', `Artifact ${key(artifact)} already has a different handler`, { details: { reason: 'immutable' } });
10
+ }
11
+ this.handlers.set(key(artifact), handler);
12
+ }
13
+ unregister(artifact) {
14
+ this.handlers.delete(key(artifact));
15
+ }
16
+ get(artifact) {
17
+ return this.handlers.get(key(artifact));
18
+ }
19
+ }
20
+ export const NATIVE_TS_FEATURES = {
21
+ checkpointResume: true,
22
+ cooperativeCancellation: true,
23
+ progressReporting: true,
24
+ isolation: 'in-process',
25
+ remoteAuthority: false,
26
+ };
27
+ /** Built-in provider for TypeScript handlers registered in a HandlerRegistry. */
28
+ export class NativeImplementationProvider {
29
+ handlers;
30
+ id = 'native-ts';
31
+ version = '1.0.0';
32
+ features = NATIVE_TS_FEATURES;
33
+ constructor(handlers = new InMemoryHandlerRegistry()) {
34
+ this.handlers = handlers;
35
+ }
36
+ async resolve(ref) {
37
+ if (ref.providerId !== this.id || ref.providerVersion !== this.version) {
38
+ throw new AgentropyError('IncompatibleVersion', `native-ts cannot resolve ${ref.providerId}@${ref.providerVersion}`, { details: { kind: 'implementation-provider' } });
39
+ }
40
+ if (!this.handlers.get(ref.artifact)) {
41
+ throw new AgentropyError('NotFound', `No handler registered for ${key(ref.artifact)}`, { details: { kind: 'implementation-artifact' } });
42
+ }
43
+ return {
44
+ providerId: this.id,
45
+ providerVersion: this.version,
46
+ artifact: { ...ref.artifact },
47
+ features: { ...this.features },
48
+ };
49
+ }
50
+ /** The handler is looked up per activation, so an unregistered artifact fails that activation with IncompatibleVersion (AC-10). */
51
+ createAgent(binding) {
52
+ const codec = this.handlers.get(binding.artifact)?.checkpointCodec;
53
+ return {
54
+ ...(codec ? { checkpointCodec: codec } : {}),
55
+ handle: (invocation, context) => {
56
+ const handler = this.handlers.get(binding.artifact);
57
+ if (!handler) {
58
+ return Promise.reject(new AgentropyError('IncompatibleVersion', `Handler for ${key(binding.artifact)} is no longer registered`, { details: { kind: 'implementation-artifact' } }));
59
+ }
60
+ return handler.handle(invocation, context);
61
+ },
62
+ };
63
+ }
64
+ }
65
+ export class InMemoryImplementationProviderRegistry {
66
+ providers = new Map();
67
+ register(provider) {
68
+ const k = `${provider.id}@${provider.version}`;
69
+ const existing = this.providers.get(k);
70
+ if (existing &&
71
+ existing !== provider &&
72
+ JSON.stringify(existing.features) !== JSON.stringify(provider.features)) {
73
+ throw new AgentropyError('InvalidConfiguration', `Implementation provider ${k} already registered with different features`, { details: { reason: 'immutable' } });
74
+ }
75
+ this.providers.set(k, provider);
76
+ }
77
+ find(providerId, providerVersion) {
78
+ return this.providers.get(`${providerId}@${providerVersion}`);
79
+ }
80
+ get(providerId, providerVersion) {
81
+ const p = this.find(providerId, providerVersion);
82
+ if (!p)
83
+ throw new AgentropyError('NotFound', `Implementation provider ${providerId}@${providerVersion} not found`, { details: { kind: 'implementation-provider' } });
84
+ return p;
85
+ }
86
+ }
87
+ /**
88
+ * Second implementation provider (A-02): artifacts are pure step functions registered by `id@version`.
89
+ * It declares no cooperative cancellation or progress reporting, so the runtime relies on grace-period fencing.
90
+ */
91
+ export class PureFunctionImplementationProvider {
92
+ id = 'pure-fn';
93
+ version = '1.0.0';
94
+ features = {
95
+ checkpointResume: true,
96
+ cooperativeCancellation: false,
97
+ progressReporting: false,
98
+ isolation: 'in-process',
99
+ remoteAuthority: false,
100
+ };
101
+ steps = new Map();
102
+ register(artifact, step) {
103
+ if (this.steps.has(key(artifact)) &&
104
+ this.steps.get(key(artifact)) !== step) {
105
+ throw new AgentropyError('InvalidConfiguration', `Artifact ${key(artifact)} already registered`, { details: { reason: 'immutable' } });
106
+ }
107
+ this.steps.set(key(artifact), step);
108
+ }
109
+ async resolve(ref) {
110
+ if (!this.steps.has(key(ref.artifact))) {
111
+ throw new AgentropyError('NotFound', `No step function for ${key(ref.artifact)}`, { details: { kind: 'implementation-artifact' } });
112
+ }
113
+ return {
114
+ providerId: this.id,
115
+ providerVersion: this.version,
116
+ artifact: { ...ref.artifact },
117
+ features: { ...this.features },
118
+ };
119
+ }
120
+ createAgent(binding) {
121
+ return {
122
+ handle: async (inv) => {
123
+ const step = this.steps.get(key(binding.artifact));
124
+ if (!step)
125
+ throw new AgentropyError('IncompatibleVersion', `Step function ${key(binding.artifact)} is gone`, { details: { kind: 'implementation-artifact' } });
126
+ return step({
127
+ input: inv.input,
128
+ attempt: inv.attempt,
129
+ activation: inv.activation,
130
+ ...(inv.checkpoint !== undefined
131
+ ? { checkpoint: inv.checkpoint }
132
+ : {}),
133
+ ...(inv.wakeReason ? { wakeReason: inv.wakeReason } : {}),
134
+ });
135
+ },
136
+ };
137
+ }
138
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * User inbox as a projection of TaskEvents (docs/human-actions.md "User inbox as projection", R-12, R-25, R-36, AC-02).
3
+ *
4
+ * - `notification.notify` writes its journal entry and a `notificationCreated` outbox event in one transaction,
5
+ * so a replayed step returns the original `entryId` and never creates a second entry (AC-07 internal half).
6
+ * - `InboxProjector` turns published events into entries; it is idempotent per event ID and never changes task state.
7
+ * - `conversation.briefing` returns entries not yet presented at their current revision and marks them presented
8
+ * in the same transaction, so a later turn does not repeat an unchanged entry.
9
+ */
10
+ import { type CapabilityInvocationContext, type InboxEntry, type InboxMarker, type StoreTx, type TrustedPrincipal } from '@agentropy/core';
11
+ import { type EventConsumer, type PublishedEvent } from './outbox.js';
12
+ import { type InboxPreferences, type PriorityPolicy } from './priority.js';
13
+ import { type TaskRecord, type TaskService } from './task-service.js';
14
+ export interface StoredInboxEntry extends InboxEntry {
15
+ ownerId: string;
16
+ status: 'open' | 'resolved';
17
+ /** Recent source event IDs already applied (projection idempotency). */
18
+ applied: string[];
19
+ /**
20
+ * 1 while the entry is neither acknowledged nor presented at its current revision, i.e. the briefing may show it.
21
+ * Indexed; kept in step by `settle` on every write. Entries written before the field existed lack it.
22
+ */
23
+ pending?: 0 | 1;
24
+ }
25
+ export interface EffectRecord {
26
+ taskId: string;
27
+ operation: string;
28
+ stepKey?: string;
29
+ result: unknown;
30
+ at: string;
31
+ }
32
+ /** Public shape: storage bookkeeping removed. */
33
+ export declare function publicEntry(e: StoredInboxEntry): InboxEntry;
34
+ export interface InboxServiceOptions {
35
+ policy?: PriorityPolicy;
36
+ preferences?: (user: TrustedPrincipal) => InboxPreferences | Promise<InboxPreferences>;
37
+ }
38
+ export declare class InboxService {
39
+ private readonly tasks;
40
+ private readonly options;
41
+ constructor(tasks: TaskService, options?: InboxServiceOptions);
42
+ private get store();
43
+ list(query: {
44
+ cursor?: string;
45
+ limit?: number;
46
+ }, caller: TrustedPrincipal): Promise<{
47
+ entries: InboxEntry[];
48
+ cursor: string;
49
+ }>;
50
+ mark(entryId: string, marker: InboxMarker, caller: TrustedPrincipal, presentedRevision?: number): Promise<void>;
51
+ /**
52
+ * Turn-start briefing (R-36, R-26): entries not yet presented at their current revision, filtered and ordered by
53
+ * the delivery policy (interrupts first, then severity, then age), marked presented in the same transaction.
54
+ * On-demand entries are left unpresented and only counted.
55
+ */
56
+ briefing(user: TrustedPrincipal, limit?: number): Promise<{
57
+ entries: InboxEntry[];
58
+ onDemand: number;
59
+ }>;
60
+ }
61
+ /** Projects user-relevant TaskEvents into inbox entries. */
62
+ export declare class InboxProjector implements EventConsumer {
63
+ private readonly tasks;
64
+ readonly id = "inbox";
65
+ private readonly projectTerminal;
66
+ private touched;
67
+ constructor(tasks: TaskService, options?: {
68
+ /** Which terminal task events become entries; default: failures of delegated (child) tasks. */
69
+ projectTerminal?: (task: TaskRecord, type: 'taskCompleted' | 'taskFailed') => boolean;
70
+ /** Urgent push to active clients (e.g. SSE); `true` marks the entry delivered. Durable replay stays the briefing. */
71
+ push?: (entry: InboxEntry) => Promise<boolean>;
72
+ policy?: PriorityPolicy;
73
+ });
74
+ private readonly push?;
75
+ private readonly policy?;
76
+ /**
77
+ * Reconciliation (M2-03): re-apply every committed TaskEvent in commit order. Projection is idempotent per event,
78
+ * so existing entries and their markers are kept; missing entries are recreated. Task state is never changed.
79
+ * Returns how many entries were created.
80
+ */
81
+ rebuild(): Promise<number>;
82
+ handle(event: PublishedEvent, push?: boolean): Promise<void>;
83
+ private pushUrgent;
84
+ private project;
85
+ private notification;
86
+ private actionRequested;
87
+ private actionResolved;
88
+ private upsert;
89
+ }
90
+ export declare const actionEntryId: (requestId: string, user: string) => string;
91
+ /**
92
+ * Platform-internal effect journal: runs `effect` at most once per idempotency key, in the same transaction
93
+ * as the journal write, and returns the original result on replay.
94
+ */
95
+ export declare function journaled<T>(tasks: TaskService, ctx: CapabilityInvocationContext, operation: string, effect: (tx: StoreTx, task: {
96
+ id: string;
97
+ revision: number;
98
+ value: TaskRecord;
99
+ }) => Promise<T>): Promise<T>;
100
+ /** Built-in `notification.notify` and `conversation.briefing` handlers. */
101
+ export declare function inboxOperationHandlers(tasks: TaskService, inbox: InboxService): Record<string, (input: unknown, ctx: CapabilityInvocationContext) => Promise<unknown>>;