@1agents/acp-service 0.8.3 → 0.9.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 (75) hide show
  1. package/README.md +6 -0
  2. package/dist/bin/a2a.js +10 -2
  3. package/dist/bin/acp-service.js +6 -0
  4. package/dist/bin/roles.d.ts +1 -0
  5. package/dist/bin/roles.js +24 -0
  6. package/dist/src/a2a/executor.d.ts +16 -1
  7. package/dist/src/a2a/executor.js +205 -19
  8. package/dist/src/a2a/gateway.d.ts +77 -0
  9. package/dist/src/a2a/gateway.js +349 -27
  10. package/dist/src/a2a/index.d.ts +7 -1
  11. package/dist/src/a2a/index.js +4 -0
  12. package/dist/src/a2a/result-metadata.d.ts +3 -0
  13. package/dist/src/a2a/result-metadata.js +2 -1
  14. package/dist/src/a2a/server.js +2 -1
  15. package/dist/src/a2a/store.js +7 -1
  16. package/dist/src/a2a/types.d.ts +32 -1
  17. package/dist/src/a2a/types.js +11 -1
  18. package/dist/src/acp-connection.js +93 -12
  19. package/dist/src/bridge.js +127 -4
  20. package/dist/src/capacity-lifecycle.d.ts +5 -0
  21. package/dist/src/capacity-lifecycle.js +57 -0
  22. package/dist/src/capacity-queue.d.ts +23 -0
  23. package/dist/src/capacity-queue.js +251 -0
  24. package/dist/src/capacity.d.ts +76 -0
  25. package/dist/src/capacity.js +377 -0
  26. package/dist/src/execution/human-review.d.ts +103 -0
  27. package/dist/src/execution/human-review.js +87 -0
  28. package/dist/src/execution/ledger.d.ts +5 -0
  29. package/dist/src/execution/ledger.js +39 -8
  30. package/dist/src/execution/ppt-delivery.d.ts +36 -3
  31. package/dist/src/execution/ppt-delivery.js +243 -53
  32. package/dist/src/execution/project-discovery.d.ts +56 -0
  33. package/dist/src/execution/project-discovery.js +429 -0
  34. package/dist/src/execution/report-review.d.ts +60 -0
  35. package/dist/src/execution/report-review.js +173 -0
  36. package/dist/src/execution/targets.d.ts +5 -0
  37. package/dist/src/execution/targets.js +1 -0
  38. package/dist/src/execution/workbench.d.ts +131 -0
  39. package/dist/src/execution/workbench.js +265 -0
  40. package/dist/src/index.d.ts +4 -0
  41. package/dist/src/index.js +3 -0
  42. package/dist/src/roles/index.d.ts +1 -0
  43. package/dist/src/roles/index.js +1 -0
  44. package/dist/src/roles/skills.d.ts +71 -0
  45. package/dist/src/roles/skills.js +427 -0
  46. package/package.json +5 -1
  47. package/skills/acp-service/SKILL.md +21 -7
  48. package/skills/acp-service/references/a2a.md +9 -5
  49. package/skills/acp-service/references/async-caller.md +48 -0
  50. package/skills/acp-service/references/roles-and-tasks.md +120 -0
  51. package/skills/acp-service/scripts/a2a-caller.py +242 -0
  52. package/vendor/dsh/README.md +2 -0
  53. package/vendor/dsh/a2a-executor.d.ts +4 -1
  54. package/vendor/dsh/a2a-executor.js +46 -2
  55. package/vendor/dsh/adapter.d.ts +10 -0
  56. package/vendor/dsh/adapter.js +67 -3
  57. package/vendor/dsh/index.js +2 -1
  58. package/vendor/runtime/dist/{cli-DeOpE2Xz.js → cli-DXmYwv3U.js} +4 -4
  59. package/vendor/runtime/dist/{cli-DeOpE2Xz.js.map → cli-DXmYwv3U.js.map} +1 -1
  60. package/vendor/runtime/dist/cli.js +7 -7
  61. package/vendor/runtime/dist/client-VQsqcIOJ.d.ts.map +1 -1
  62. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +1 -0
  63. package/vendor/runtime/dist/{flows-oaBGn31w.js → flows-DJ17ajbw.js} +3 -3
  64. package/vendor/runtime/dist/{flows-oaBGn31w.js.map → flows-DJ17ajbw.js.map} +1 -1
  65. package/vendor/runtime/dist/flows.js +1 -1
  66. package/vendor/runtime/dist/{invocation-options-CUDEE8vW.js → invocation-options-PBfCgrdi.js} +3 -3
  67. package/vendor/runtime/dist/{invocation-options-CUDEE8vW.js.map → invocation-options-PBfCgrdi.js.map} +1 -1
  68. package/vendor/runtime/dist/{output-CFv3jcOQ.js → output-B3MDn7kv.js} +2 -2
  69. package/vendor/runtime/dist/{output-CFv3jcOQ.js.map → output-B3MDn7kv.js.map} +1 -1
  70. package/vendor/runtime/dist/{queue-owner-runtime-DvMJiGbP.js → queue-owner-runtime-DXCVngwU.js} +15 -8
  71. package/vendor/runtime/dist/queue-owner-runtime-DXCVngwU.js.map +1 -0
  72. package/vendor/runtime/dist/runtime.js +1 -1
  73. package/vendor/runtime/dist/{session-watch-Di-wIdCH.js → session-watch-DURyCw31.js} +2 -2
  74. package/vendor/runtime/dist/{session-watch-Di-wIdCH.js.map → session-watch-DURyCw31.js.map} +1 -1
  75. package/vendor/runtime/dist/queue-owner-runtime-DvMJiGbP.js.map +0 -1
@@ -0,0 +1,377 @@
1
+ /** Device-wide admission control. These limits are conservative estimates, not measured hardware maxima. */
2
+ import { randomUUID } from 'node:crypto';
3
+ import { execFileSync } from 'node:child_process';
4
+ import { closeSync, constants, fstatSync, fsyncSync, lstatSync, openSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
5
+ import { availableParallelism, freemem, homedir, totalmem } from 'node:os';
6
+ import { join, resolve } from 'node:path';
7
+ import { setTimeout as delay } from 'node:timers/promises';
8
+ import { DirectoryLease } from './a2a/lease.js';
9
+ export class CapacityError extends Error {
10
+ code;
11
+ constructor(code) {
12
+ super(code === 'ACP_CAPACITY_MEMORY_LIMIT'
13
+ ? 'Available device memory is below the ACP startup reserve; retry after memory is freed.'
14
+ : code === 'ACP_CAPACITY_SOFT_LIMIT'
15
+ ? 'Automatic ACP capacity is full; retry after an active task or process finishes.'
16
+ : 'Device ACP capacity is full; retry after an active task or process finishes.');
17
+ this.code = code;
18
+ this.name = 'CapacityError';
19
+ }
20
+ }
21
+ const MiB = 1024 ** 2;
22
+ const startupWindowMs = 30_000;
23
+ const tokenPattern = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
24
+ const stateMessage = 'ACP capacity state is unavailable; check the local host capacity state before retrying.';
25
+ const pidIsValid = (value) => Number.isSafeInteger(value) && value > 0;
26
+ const validKind = (value) => value === 'process' || value === 'task';
27
+ const validSource = (value) => value === 'automatic' || value === 'interactive';
28
+ /** Allow roughly one automatic agent per two CPUs and 3 GiB, then keep at least one manual slot. */
29
+ export function estimateCapacityLimits() {
30
+ const cores = availableParallelism();
31
+ const memoryGiB = totalmem() / (1024 ** 3);
32
+ const soft = Math.max(1, Math.min(Math.floor(cores / 2), Math.floor(memoryGiB / 3)));
33
+ const hard = Math.max(soft + 1, Math.min(cores, Math.floor(memoryGiB / 2)));
34
+ return { soft, hard, basis: 'hardware-estimate' };
35
+ }
36
+ function limit(value, label) {
37
+ if (value === undefined)
38
+ return undefined;
39
+ const parsed = typeof value === 'string' && /^[1-9]\d*$/.test(value) ? Number(value) : value;
40
+ if (typeof parsed !== 'number' || !Number.isSafeInteger(parsed) || parsed <= 0) {
41
+ throw new Error(`${label} must be a positive safe integer`);
42
+ }
43
+ return parsed;
44
+ }
45
+ function bytes(value, environment, label, allowZero = false) {
46
+ let parsed = value;
47
+ if (parsed === undefined && environment !== undefined) {
48
+ if (!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(environment))
49
+ throw new Error(`${label} must be a valid memory size`);
50
+ parsed = Number(environment) * MiB;
51
+ }
52
+ if (parsed === undefined)
53
+ return undefined;
54
+ if (typeof parsed !== 'number' || !Number.isSafeInteger(parsed) || parsed < (allowZero ? 0 : 1)) {
55
+ throw new Error(`${label} must be a valid memory size`);
56
+ }
57
+ return parsed;
58
+ }
59
+ /** Darwin's raw free count excludes reclaimable inactive caches. Purgeable pages are not added twice. */
60
+ export function parseMacOSAvailableMemory(output, totalBytes) {
61
+ const pageSize = /page size of (\d+) bytes/.exec(output);
62
+ if (!pageSize || !Number.isSafeInteger(totalBytes) || totalBytes <= 0)
63
+ throw new Error(stateMessage);
64
+ const pageBytes = Number(pageSize[1]);
65
+ if (!Number.isSafeInteger(pageBytes) || pageBytes <= 0)
66
+ throw new Error(stateMessage);
67
+ let pages = 0;
68
+ for (const label of ['free', 'inactive', 'speculative']) {
69
+ const match = new RegExp(`^Pages ${label}:\\s+(\\d+)\\.?\\s*$`, 'm').exec(output);
70
+ if (!match || !Number.isSafeInteger(Number(match[1])))
71
+ throw new Error(stateMessage);
72
+ pages += Number(match[1]);
73
+ }
74
+ const available = pages * pageBytes;
75
+ if (!Number.isSafeInteger(available))
76
+ throw new Error(stateMessage);
77
+ return Math.min(totalBytes, available);
78
+ }
79
+ function currentMemory() {
80
+ const totalBytes = totalmem();
81
+ if (process.platform === 'darwin') {
82
+ try {
83
+ const output = execFileSync('/usr/bin/vm_stat', [], { encoding: 'utf8', timeout: 1000, maxBuffer: 65536, stdio: ['ignore', 'pipe', 'ignore'] });
84
+ return { totalBytes, availableBytes: parseMacOSAvailableMemory(output, totalBytes), source: 'macos-reclaimable-estimate' };
85
+ }
86
+ catch { /* Fall back conservatively when the host cannot read its reclaimable-page estimate. */ }
87
+ }
88
+ // availableMemory also respects the process/container allocation when the Node host exposes it.
89
+ const processAvailable = process.availableMemory?.();
90
+ return { totalBytes, availableBytes: Math.min(freemem(), processAvailable ?? Infinity), source: 'system-available' };
91
+ }
92
+ /** Only ESRCH proves death. Permission failures and PID reuse retain the reservation. */
93
+ function isDead(pid) {
94
+ try {
95
+ process.kill(pid, 0);
96
+ return false;
97
+ }
98
+ catch (error) {
99
+ return error.code === 'ESRCH';
100
+ }
101
+ }
102
+ export function resolveCapacityDirectory(options = {}) {
103
+ const directory = options.directory ?? process.env.ACP_CAPACITY_DIRECTORY ?? join(homedir(), '.1agents', 'state', 'acp-capacity');
104
+ if (typeof directory !== 'string' || !directory.trim())
105
+ throw new Error('ACP capacity directory must be a nonempty path');
106
+ return resolve(directory);
107
+ }
108
+ export class CapacityGovernor {
109
+ directory;
110
+ limits;
111
+ memoryProvider;
112
+ memoryReserveBytes;
113
+ estimatedInstanceBytes;
114
+ constructor(options = {}) {
115
+ this.directory = resolveCapacityDirectory(options);
116
+ const estimate = estimateCapacityLimits();
117
+ const soft = limit(options.softLimit ?? process.env.ACP_CAPACITY_SOFT_LIMIT, 'ACP capacity soft limit');
118
+ const hard = limit(options.hardLimit ?? process.env.ACP_CAPACITY_HARD_LIMIT, 'ACP capacity hard limit');
119
+ this.limits = {
120
+ soft: soft ?? (hard === undefined ? estimate.soft : Math.min(estimate.soft, hard - 1)),
121
+ hard: hard ?? Math.max(estimate.hard, (soft ?? estimate.soft) + 1),
122
+ basis: soft === undefined && hard === undefined ? 'hardware-estimate' : 'configured',
123
+ };
124
+ if (this.limits.soft < 1 || this.limits.hard <= this.limits.soft || !Number.isSafeInteger(this.limits.hard)) {
125
+ throw new Error('ACP capacity hard limit must exceed the soft limit and reserve at least one interactive slot');
126
+ }
127
+ this.memoryProvider = options.memoryProvider ?? currentMemory;
128
+ if (typeof this.memoryProvider !== 'function')
129
+ throw new Error('ACP capacity memory provider must be a function');
130
+ this.memoryReserveBytes = bytes(options.memoryReserveBytes, process.env.ACP_CAPACITY_MEMORY_RESERVE_MB, 'ACP capacity memory reserve', true) ?? Math.max(512 * MiB, Math.min(4 * 1024 * MiB, Math.floor(totalmem() * 0.1)));
131
+ this.estimatedInstanceBytes = bytes(options.estimatedInstanceBytes, process.env.ACP_CAPACITY_INSTANCE_MEMORY_MB, 'ACP estimated instance memory') ?? 1024 * MiB;
132
+ }
133
+ async acquire(request) {
134
+ if (!request || !validKind(request.kind) || !validSource(request.source) || typeof request.id !== 'string' ||
135
+ !request.id.trim() || request.id.length > 4096)
136
+ throw new Error('Invalid ACP capacity request');
137
+ const reservation = { version: 1, token: randomUUID(), ownerPid: process.pid, startupUntil: Date.now() + startupWindowMs,
138
+ kind: request.kind, source: request.source, id: request.id };
139
+ await this.transaction(() => {
140
+ const records = this.readReservations();
141
+ this.ensurePolicy(records);
142
+ const state = this.count(request.kind, records);
143
+ if (state.used >= this.limits.hard)
144
+ throw new CapacityError('ACP_CAPACITY_HARD_LIMIT');
145
+ if (request.source === 'automatic' && state.used >= this.limits.soft)
146
+ throw new CapacityError('ACP_CAPACITY_SOFT_LIMIT');
147
+ if (state.memory.availableSlots < 1)
148
+ throw new CapacityError('ACP_CAPACITY_MEMORY_LIMIT');
149
+ this.writeReservation({ ...reservation, startupUntil: Date.now() + startupWindowMs });
150
+ });
151
+ // Serialize methods on an individual lease so release can never be followed by resurrection.
152
+ let released = false;
153
+ let pending = Promise.resolve();
154
+ const queue = (operation) => {
155
+ const result = pending.then(operation);
156
+ pending = result.catch(() => undefined);
157
+ return result;
158
+ };
159
+ return {
160
+ recheck: () => queue(async () => {
161
+ if (released)
162
+ throw new Error('ACP capacity lease has already been released');
163
+ await this.transaction(() => {
164
+ const records = this.readReservations();
165
+ this.ensurePolicy(records);
166
+ if (!records.some(item => item.token === reservation.token && item.ownerPid === process.pid))
167
+ throw new Error(stateMessage);
168
+ const state = this.count(request.kind, records, reservation.token);
169
+ if (state.memory.availableSlots < 1)
170
+ throw new CapacityError('ACP_CAPACITY_MEMORY_LIMIT');
171
+ const own = records.find(item => item.token === reservation.token);
172
+ this.writeReservation({ ...own, startupUntil: Date.now() + startupWindowMs });
173
+ });
174
+ }),
175
+ spawned: pid => queue(async () => {
176
+ if (!pidIsValid(pid) || request.kind !== 'process')
177
+ throw new Error('Invalid ACP child process registration');
178
+ if (released)
179
+ throw new Error('ACP capacity lease has already been released');
180
+ await this.transaction(() => {
181
+ const current = this.readReservation(this.reservationPath(reservation.token));
182
+ if (current.ownerPid !== process.pid || current.token !== reservation.token ||
183
+ (current.childPid !== undefined && current.childPid !== pid))
184
+ throw new Error(stateMessage);
185
+ this.writeReservation({ ...current, childPid: pid, startupUntil: Date.now() + startupWindowMs });
186
+ });
187
+ }),
188
+ release: () => queue(async () => {
189
+ if (released)
190
+ return;
191
+ await this.transaction(() => {
192
+ try {
193
+ unlinkSync(this.reservationPath(reservation.token));
194
+ }
195
+ catch (error) {
196
+ if (error.code !== 'ENOENT')
197
+ throw error;
198
+ }
199
+ });
200
+ released = true;
201
+ }),
202
+ };
203
+ }
204
+ async snapshot(kind) {
205
+ if (!validKind(kind))
206
+ throw new Error('Invalid ACP capacity kind');
207
+ return this.transaction(() => {
208
+ const records = this.readReservations();
209
+ this.ensurePolicy(records);
210
+ return this.count(kind, records);
211
+ });
212
+ }
213
+ count(kind, reservations, excludeStartupToken) {
214
+ const matching = reservations.filter(item => item.kind === kind);
215
+ const automatic = matching.filter(item => item.source === 'automatic').length;
216
+ const used = matching.length;
217
+ const reading = this.memoryProvider();
218
+ if (!reading || !Number.isSafeInteger(reading.totalBytes) || reading.totalBytes <= 0 ||
219
+ !Number.isSafeInteger(reading.availableBytes) || reading.availableBytes < 0 || reading.availableBytes > reading.totalBytes) {
220
+ throw new Error(stateMessage);
221
+ }
222
+ // Pending processes retain their budget until spawn is registered. Stable leases stay counted
223
+ // for concurrency, but actual free memory carries their cost after the startup window expires.
224
+ // Share startup memory budget across kinds. Without an explicit task-to-child association,
225
+ // short-lived double counting is safer than letting unrelated starts spend the same bytes.
226
+ const starting = reservations.filter(item => item.token !== excludeStartupToken &&
227
+ ((item.kind === 'process' && item.childPid === undefined) || item.startupUntil > Date.now()));
228
+ const startupReservedBytes = starting.length * this.estimatedInstanceBytes;
229
+ const availableForStartupBytes = Math.max(0, reading.availableBytes - this.memoryReserveBytes - startupReservedBytes);
230
+ const availableSlots = Math.floor(availableForStartupBytes / this.estimatedInstanceBytes);
231
+ return { limits: { ...this.limits }, used, automatic, interactive: used - automatic,
232
+ availableAutomatic: Math.max(0, Math.min(this.limits.soft - used, this.limits.hard - used, availableSlots)),
233
+ availableInteractive: Math.max(0, Math.min(this.limits.hard - used, availableSlots)),
234
+ memory: { ...reading, source: reading.source ?? 'host-provider', reserveBytes: this.memoryReserveBytes, estimatedInstanceBytes: this.estimatedInstanceBytes,
235
+ startupReservedBytes, availableForStartupBytes, availableSlots, startupWindowMs } };
236
+ }
237
+ readReservations() {
238
+ const records = [];
239
+ for (const name of readdirSync(this.directory)) {
240
+ if (name === '.lock' || name === 'policy.json')
241
+ continue;
242
+ if (name === 'queue') {
243
+ const stat = lstatSync(join(this.directory, name));
244
+ if (!stat.isDirectory() || stat.isSymbolicLink())
245
+ throw new Error(stateMessage);
246
+ continue;
247
+ }
248
+ // A crash before an atomic rename leaves no admitted caller and therefore no spawned child.
249
+ if (/^pending-[a-f0-9-]{36}\.json$/.test(name)) {
250
+ unlinkSync(join(this.directory, name));
251
+ continue;
252
+ }
253
+ if (!/^lease-[a-f0-9-]{36}\.json$/.test(name))
254
+ throw new Error(stateMessage);
255
+ const path = join(this.directory, name);
256
+ const record = this.readReservation(path);
257
+ if (name !== `lease-${record.token}.json`)
258
+ throw new Error(stateMessage);
259
+ // An unregistered process may have spawned just before its owner crashed. Never guess it dead.
260
+ const reclaimable = isDead(record.ownerPid) &&
261
+ (record.kind === 'task' || (record.childPid !== undefined && isDead(record.childPid)));
262
+ if (reclaimable)
263
+ unlinkSync(path);
264
+ else
265
+ records.push(record);
266
+ }
267
+ return records;
268
+ }
269
+ reservationPath(token) { return join(this.directory, `lease-${token}.json`); }
270
+ ensurePolicy(records) {
271
+ const policy = { version: 1, softLimit: this.limits.soft, hardLimit: this.limits.hard,
272
+ memoryReserveBytes: this.memoryReserveBytes, estimatedInstanceBytes: this.estimatedInstanceBytes };
273
+ const path = join(this.directory, 'policy.json');
274
+ let current;
275
+ try {
276
+ current = this.readJson(path);
277
+ if (!current || current.version !== 1 || !Number.isSafeInteger(current.softLimit) || current.softLimit < 1 ||
278
+ !Number.isSafeInteger(current.hardLimit) || current.hardLimit <= current.softLimit ||
279
+ !Number.isSafeInteger(current.memoryReserveBytes) || current.memoryReserveBytes < 0 ||
280
+ !Number.isSafeInteger(current.estimatedInstanceBytes) || current.estimatedInstanceBytes <= 0)
281
+ throw new Error(stateMessage);
282
+ }
283
+ catch (error) {
284
+ if (error.code !== 'ENOENT')
285
+ throw error;
286
+ if (records.length)
287
+ throw new Error(stateMessage);
288
+ }
289
+ const matches = current && Object.entries(policy).every(([key, value]) => current[key] === value);
290
+ if (matches)
291
+ return;
292
+ // Hosts sharing a device cannot raise each other's active policy by choosing different options.
293
+ // Drain first; releases do not require a policy match, so active hosts can always finish.
294
+ if (records.length)
295
+ throw new Error(stateMessage);
296
+ this.writeJson(path, policy);
297
+ }
298
+ readJson(path) {
299
+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
300
+ try {
301
+ const stat = fstatSync(fd);
302
+ if (!stat.isFile() || stat.size > 64 * 1024)
303
+ throw new Error(stateMessage);
304
+ return JSON.parse(readFileSync(fd, 'utf8'));
305
+ }
306
+ finally {
307
+ closeSync(fd);
308
+ }
309
+ }
310
+ readReservation(path) {
311
+ const value = this.readJson(path);
312
+ if (!value || value.version !== 1 || typeof value.token !== 'string' || !tokenPattern.test(value.token) ||
313
+ !pidIsValid(value.ownerPid) || !validKind(value.kind) || !validSource(value.source) ||
314
+ typeof value.id !== 'string' || !value.id.trim() || value.id.length > 4096 ||
315
+ !Number.isSafeInteger(value.startupUntil) || value.startupUntil < 0 ||
316
+ (value.childPid !== undefined && (!pidIsValid(value.childPid) || value.kind !== 'process')))
317
+ throw new Error(stateMessage);
318
+ return value;
319
+ }
320
+ writeReservation(record) {
321
+ this.writeJson(this.reservationPath(record.token), record);
322
+ }
323
+ writeJson(path, value) {
324
+ const temporary = join(this.directory, `pending-${randomUUID()}.json`);
325
+ const fd = openSync(temporary, 'wx', 0o600);
326
+ try {
327
+ writeFileSync(fd, JSON.stringify(value));
328
+ fsyncSync(fd);
329
+ }
330
+ finally {
331
+ closeSync(fd);
332
+ }
333
+ try {
334
+ renameSync(temporary, path);
335
+ }
336
+ finally {
337
+ try {
338
+ unlinkSync(temporary);
339
+ }
340
+ catch (error) {
341
+ if (error.code !== 'ENOENT')
342
+ throw error;
343
+ }
344
+ }
345
+ }
346
+ async transaction(operation) {
347
+ let lease;
348
+ const deadline = performance.now() + 5000;
349
+ do {
350
+ try {
351
+ lease = new DirectoryLease(this.directory);
352
+ break;
353
+ }
354
+ catch {
355
+ if (performance.now() >= deadline)
356
+ throw new Error(stateMessage);
357
+ }
358
+ await delay(10 + Math.floor(Math.random() * 20));
359
+ } while (true);
360
+ try {
361
+ return operation();
362
+ }
363
+ catch (error) {
364
+ if (error instanceof CapacityError)
365
+ throw error;
366
+ throw new Error(stateMessage);
367
+ }
368
+ finally {
369
+ try {
370
+ lease.close();
371
+ }
372
+ catch {
373
+ throw new Error(stateMessage);
374
+ }
375
+ }
376
+ }
377
+ }
@@ -0,0 +1,103 @@
1
+ import { z } from 'zod';
2
+ export declare const humanReviewPreviewSchema: z.ZodObject<{
3
+ title: z.ZodString;
4
+ slides: z.ZodArray<z.ZodObject<{
5
+ title: z.ZodString;
6
+ message: z.ZodString;
7
+ body: z.ZodArray<z.ZodString>;
8
+ visual: z.ZodString;
9
+ sources: z.ZodArray<z.ZodString>;
10
+ facts: z.ZodArray<z.ZodString>;
11
+ notes: z.ZodString;
12
+ }, z.core.$strict>>;
13
+ }, z.core.$strict>;
14
+ declare const reviewPreviewSchema: z.ZodUnion<readonly [z.ZodObject<{
15
+ title: z.ZodString;
16
+ slides: z.ZodArray<z.ZodObject<{
17
+ title: z.ZodString;
18
+ message: z.ZodString;
19
+ body: z.ZodArray<z.ZodString>;
20
+ visual: z.ZodString;
21
+ sources: z.ZodArray<z.ZodString>;
22
+ facts: z.ZodArray<z.ZodString>;
23
+ notes: z.ZodString;
24
+ }, z.core.$strict>>;
25
+ }, z.core.$strict>, z.ZodObject<{
26
+ kind: z.ZodLiteral<"markdown">;
27
+ title: z.ZodString;
28
+ markdown: z.ZodString;
29
+ reportPath: z.ZodString;
30
+ slides: z.ZodArray<z.ZodNever>;
31
+ }, z.core.$strict>]>;
32
+ export type HumanReviewPreview = z.infer<typeof reviewPreviewSchema>;
33
+ export declare const humanReviewActorSchema: z.ZodObject<{
34
+ id: z.ZodString;
35
+ displayName: z.ZodOptional<z.ZodString>;
36
+ source: z.ZodLiteral<"1agents-web">;
37
+ }, z.core.$strict>;
38
+ export type HumanReviewActor = z.infer<typeof humanReviewActorSchema>;
39
+ export declare const humanReviewDecisionSchema: z.ZodObject<{
40
+ clientRequestId: z.ZodString;
41
+ action: z.ZodEnum<{
42
+ cancel: "cancel";
43
+ comment: "comment";
44
+ approve: "approve";
45
+ changes_requested: "changes_requested";
46
+ }>;
47
+ revision: z.ZodString;
48
+ digest: z.ZodString;
49
+ note: z.ZodOptional<z.ZodString>;
50
+ }, z.core.$strict>;
51
+ export type HumanReviewDecisionInput = z.infer<typeof humanReviewDecisionSchema>;
52
+ export type HumanReviewStatus = 'pending' | 'approved' | 'changes_requested' | 'superseded' | 'canceled';
53
+ export interface HumanReviewDecision extends HumanReviewDecisionInput {
54
+ decisionId: string;
55
+ actor: HumanReviewActor;
56
+ at: string;
57
+ }
58
+ export interface HumanReviewRequest {
59
+ reviewId: string;
60
+ jobId: string;
61
+ attemptId: string;
62
+ stage: 'summary' | 'report';
63
+ authorJobId: string;
64
+ authorAttemptId: string;
65
+ authorSessionId: string;
66
+ revision: string;
67
+ digest: string;
68
+ title: string;
69
+ preview: HumanReviewPreview;
70
+ reviewerId: string;
71
+ status: HumanReviewStatus;
72
+ createdAt: string;
73
+ updatedAt: string;
74
+ history: HumanReviewDecision[];
75
+ resume?: {
76
+ status: 'pending' | 'applied';
77
+ action: Exclude<HumanReviewDecisionInput['action'], 'comment'>;
78
+ decisionId: string;
79
+ appliedAt?: string;
80
+ };
81
+ }
82
+ export type HumanReviewCreateInput = Omit<HumanReviewRequest, 'reviewId' | 'status' | 'history' | 'resume' | 'createdAt' | 'updatedAt'> & {
83
+ reviewId?: string;
84
+ };
85
+ export interface HumanReviewBinding {
86
+ attemptId: string;
87
+ revision: string;
88
+ digest: string;
89
+ }
90
+ export declare class HumanReviewError extends Error {
91
+ readonly code: 'forbidden' | 'version_conflict' | 'already_decided' | 'idempotency_conflict';
92
+ constructor(code: 'forbidden' | 'version_conflict' | 'already_decided' | 'idempotency_conflict', message: string);
93
+ }
94
+ export declare function createHumanReview(input: HumanReviewCreateInput, at?: string): HumanReviewRequest;
95
+ /** A replay may acknowledge an old durable decision but cannot schedule it a second time. */
96
+ export declare function decideHumanReview(request: HumanReviewRequest, input: HumanReviewDecisionInput, actorInput: HumanReviewActor, current: HumanReviewBinding, at?: string): {
97
+ review: HumanReviewRequest;
98
+ decision: HumanReviewDecision;
99
+ idempotent: boolean;
100
+ };
101
+ export declare function markHumanReviewApplied(request: HumanReviewRequest, decisionId: string, at?: string): HumanReviewRequest;
102
+ export declare function supersedeHumanReview(request: HumanReviewRequest, at?: string): HumanReviewRequest;
103
+ export {};
@@ -0,0 +1,87 @@
1
+ /** Version-bound human decisions. Callers persist each returned value before scheduling work. */
2
+ import { randomUUID } from 'node:crypto';
3
+ import { z } from 'zod';
4
+ const id = z.string().trim().min(1).max(512);
5
+ const sha256 = z.string().regex(/^[a-f0-9]{64}$/);
6
+ export const humanReviewPreviewSchema = z.object({
7
+ title: z.string().min(1),
8
+ slides: z.array(z.object({ title: z.string().min(1), message: z.string(), body: z.array(z.string()),
9
+ visual: z.string(), sources: z.array(z.string()).min(1), facts: z.array(z.string()).min(1), notes: z.string() }).strict()).length(6),
10
+ }).strict();
11
+ const markdownReviewPreviewSchema = z.object({
12
+ kind: z.literal('markdown'), title: z.string().min(1), markdown: z.string().min(1).max(256 * 1024),
13
+ reportPath: z.string().min(1), slides: z.array(z.never()).length(0),
14
+ }).strict();
15
+ const reviewPreviewSchema = z.union([humanReviewPreviewSchema, markdownReviewPreviewSchema]);
16
+ export const humanReviewActorSchema = z.object({ id, displayName: z.string().trim().min(1).max(200).optional(), source: z.literal('1agents-web') }).strict();
17
+ export const humanReviewDecisionSchema = z.object({
18
+ clientRequestId: id, action: z.enum(['comment', 'approve', 'changes_requested', 'cancel']),
19
+ revision: id, digest: sha256, note: z.string().trim().max(16000).optional(),
20
+ }).strict().superRefine((input, ctx) => {
21
+ if (['comment', 'changes_requested'].includes(input.action) && !input.note) {
22
+ ctx.addIssue({ code: 'custom', path: ['note'], message: 'Comment and changes_requested require a note' });
23
+ }
24
+ });
25
+ export class HumanReviewError extends Error {
26
+ code;
27
+ constructor(code, message) {
28
+ super(message);
29
+ this.code = code;
30
+ }
31
+ }
32
+ const timestamp = () => new Date().toISOString();
33
+ export function createHumanReview(input, at = timestamp()) {
34
+ const parsed = z.object({ reviewId: id.optional(), jobId: id, attemptId: id, stage: z.enum(['summary', 'report']),
35
+ authorJobId: id, authorAttemptId: id, authorSessionId: id, revision: id, digest: sha256, title: z.string().min(1),
36
+ preview: reviewPreviewSchema, reviewerId: id }).strict().parse(input);
37
+ return { ...parsed, reviewId: parsed.reviewId ?? randomUUID(), status: 'pending', createdAt: at, updatedAt: at, history: [] };
38
+ }
39
+ /** A replay may acknowledge an old durable decision but cannot schedule it a second time. */
40
+ export function decideHumanReview(request, input, actorInput, current, at = timestamp()) {
41
+ const actor = humanReviewActorSchema.parse(actorInput), decisionInput = humanReviewDecisionSchema.parse(input);
42
+ if (actor.id !== request.reviewerId)
43
+ throw new HumanReviewError('forbidden', 'Review is assigned to another person');
44
+ if (decisionInput.revision !== request.revision || decisionInput.digest !== request.digest) {
45
+ throw new HumanReviewError('version_conflict', 'Decision does not match the displayed review version');
46
+ }
47
+ const replay = request.history.find(item => item.clientRequestId === decisionInput.clientRequestId);
48
+ if (replay) {
49
+ if (replay.actor.id !== actor.id || replay.actor.source !== actor.source || replay.action !== decisionInput.action
50
+ || replay.revision !== decisionInput.revision || replay.digest !== decisionInput.digest || replay.note !== decisionInput.note) {
51
+ throw new HumanReviewError('idempotency_conflict', 'clientRequestId conflicts with a recorded decision');
52
+ }
53
+ return { review: structuredClone(request), decision: structuredClone(replay), idempotent: true };
54
+ }
55
+ if (request.attemptId !== current.attemptId || request.revision !== current.revision || request.digest !== current.digest) {
56
+ throw new HumanReviewError('version_conflict', 'This review has been replaced by a newer execution or content version');
57
+ }
58
+ if (request.status !== 'pending')
59
+ throw new HumanReviewError('already_decided', 'This review is no longer pending');
60
+ const review = structuredClone(request), decision = { ...decisionInput, decisionId: randomUUID(), actor, at };
61
+ review.history.push(decision);
62
+ review.updatedAt = at;
63
+ if (decision.action !== 'comment') {
64
+ review.status = { approve: 'approved', changes_requested: 'changes_requested', cancel: 'canceled' }[decision.action];
65
+ review.resume = { status: 'pending', action: decision.action, decisionId: decision.decisionId };
66
+ }
67
+ return { review, decision, idempotent: false };
68
+ }
69
+ export function markHumanReviewApplied(request, decisionId, at = timestamp()) {
70
+ if (!request.resume || request.resume.decisionId !== decisionId)
71
+ throw new HumanReviewError('version_conflict', 'Continuation does not match the recorded decision');
72
+ const review = structuredClone(request);
73
+ if (review.resume.status === 'pending') {
74
+ review.resume.status = 'applied';
75
+ review.resume.appliedAt = at;
76
+ review.updatedAt = at;
77
+ }
78
+ return review;
79
+ }
80
+ export function supersedeHumanReview(request, at = timestamp()) {
81
+ const review = structuredClone(request);
82
+ if (review.status === 'pending') {
83
+ review.status = 'superseded';
84
+ review.updatedAt = at;
85
+ }
86
+ return review;
87
+ }
@@ -30,6 +30,8 @@ export interface LedgerResult {
30
30
  resultDigest?: string;
31
31
  resultRevision?: string;
32
32
  artifactLinks: unknown[];
33
+ /** Artifact byte receipts supplied by the execution host, when available. */
34
+ resultArtifacts?: unknown[];
33
35
  resultAvailable: boolean;
34
36
  observedAt: string;
35
37
  }
@@ -67,6 +69,7 @@ export interface LedgerAttempt {
67
69
  updatedAt: string;
68
70
  diagnostic?: string;
69
71
  result?: LedgerResult;
72
+ resultHistory?: LedgerResult[];
70
73
  }
71
74
  export interface LedgerJob {
72
75
  sourceId: string;
@@ -146,6 +149,7 @@ export interface LedgerObservation {
146
149
  resultDigest?: string;
147
150
  resultRevision?: string;
148
151
  artifactLinks?: unknown[];
152
+ resultArtifacts?: unknown[];
149
153
  resultAvailable?: boolean;
150
154
  diagnostic?: string;
151
155
  }
@@ -171,6 +175,7 @@ export interface LedgerJobView extends LedgerJob {
171
175
  attempts: LedgerAttempt[];
172
176
  children: LedgerJob[];
173
177
  result?: LedgerResult;
178
+ resultHistory: LedgerResult[];
174
179
  businessAcceptance?: BusinessAcceptance;
175
180
  acceptanceHistory: BusinessAcceptance[];
176
181
  }