@1agents/acp-service 0.8.2 → 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 (76) 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/client.js +84 -24
  58. package/vendor/dsh/index.js +2 -1
  59. package/vendor/runtime/dist/{cli-DeOpE2Xz.js → cli-DXmYwv3U.js} +4 -4
  60. package/vendor/runtime/dist/{cli-DeOpE2Xz.js.map → cli-DXmYwv3U.js.map} +1 -1
  61. package/vendor/runtime/dist/cli.js +7 -7
  62. package/vendor/runtime/dist/client-VQsqcIOJ.d.ts.map +1 -1
  63. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +1 -0
  64. package/vendor/runtime/dist/{flows-oaBGn31w.js → flows-DJ17ajbw.js} +3 -3
  65. package/vendor/runtime/dist/{flows-oaBGn31w.js.map → flows-DJ17ajbw.js.map} +1 -1
  66. package/vendor/runtime/dist/flows.js +1 -1
  67. package/vendor/runtime/dist/{invocation-options-CUDEE8vW.js → invocation-options-PBfCgrdi.js} +3 -3
  68. package/vendor/runtime/dist/{invocation-options-CUDEE8vW.js.map → invocation-options-PBfCgrdi.js.map} +1 -1
  69. package/vendor/runtime/dist/{output-CFv3jcOQ.js → output-B3MDn7kv.js} +2 -2
  70. package/vendor/runtime/dist/{output-CFv3jcOQ.js.map → output-B3MDn7kv.js.map} +1 -1
  71. package/vendor/runtime/dist/{queue-owner-runtime-DvMJiGbP.js → queue-owner-runtime-DXCVngwU.js} +15 -8
  72. package/vendor/runtime/dist/queue-owner-runtime-DXCVngwU.js.map +1 -0
  73. package/vendor/runtime/dist/runtime.js +1 -1
  74. package/vendor/runtime/dist/{session-watch-Di-wIdCH.js → session-watch-DURyCw31.js} +2 -2
  75. package/vendor/runtime/dist/{session-watch-Di-wIdCH.js.map → session-watch-DURyCw31.js.map} +1 -1
  76. package/vendor/runtime/dist/queue-owner-runtime-DvMJiGbP.js.map +0 -1
@@ -0,0 +1,56 @@
1
+ import { z } from 'zod';
2
+ export declare const projectDiscoveryConfigSchema: z.ZodObject<{
3
+ readerExecutable: z.ZodDefault<z.ZodString>;
4
+ allowedRoots: z.ZodArray<z.ZodString>;
5
+ explicitRoots: z.ZodDefault<z.ZodArray<z.ZodString>>;
6
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
7
+ maxProjects: z.ZodDefault<z.ZodNumber>;
8
+ }, z.core.$strict>;
9
+ export declare const DISCOVERY_METHODS: {
10
+ execution_project_scan: {
11
+ description: string;
12
+ parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{}, z.core.$strict>>;
13
+ };
14
+ execution_project_list: {
15
+ description: string;
16
+ parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{}, z.core.$strict>>;
17
+ };
18
+ execution_discovery_config_get: {
19
+ description: string;
20
+ parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{}, z.core.$strict>>;
21
+ };
22
+ execution_discovery_config_update: {
23
+ description: string;
24
+ parameters: z.core.ZodStandardJSONSchemaPayload<z.ZodObject<{
25
+ mode: z.ZodEnum<{
26
+ manual: "manual";
27
+ interval: "interval";
28
+ }>;
29
+ intervalMs: z.ZodOptional<z.ZodNumber>;
30
+ }, z.core.$strict>>;
31
+ };
32
+ };
33
+ export declare class ProjectRoleDiscovery {
34
+ private readonly file;
35
+ private readonly config;
36
+ private state;
37
+ private started;
38
+ private closed;
39
+ private timer?;
40
+ private active?;
41
+ private controller?;
42
+ constructor(options: {
43
+ stateDirectory: string;
44
+ config: z.input<typeof projectDiscoveryConfigSchema>;
45
+ });
46
+ private commit;
47
+ private view;
48
+ start(): void;
49
+ private schedule;
50
+ close(): Promise<void>;
51
+ invoke(method: string, params: unknown): Promise<unknown>;
52
+ private scan;
53
+ private reader;
54
+ private collect;
55
+ private readRoles;
56
+ }
@@ -0,0 +1,429 @@
1
+ /** Optional, metadata-only project role discovery. Never registers targets or starts agent work. */
2
+ import { execFile } from 'node:child_process';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { closeSync, constants, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
5
+ import { lstat, open, readdir, realpath } from 'node:fs/promises';
6
+ import path from 'node:path';
7
+ import { z } from 'zod';
8
+ import { roleSkillProfileSchema } from '../roles/skills.js';
9
+ const absolute = z.string().min(1).max(4096).refine(value => path.isAbsolute(value) && !value.includes('\0'), 'Expected an absolute local path');
10
+ export const projectDiscoveryConfigSchema = z.object({
11
+ readerExecutable: z.string().min(1).max(4096).refine(value => !value.includes('\0')).default('1session'),
12
+ allowedRoots: z.array(absolute).min(1).max(100), explicitRoots: z.array(absolute).max(1000).default([]),
13
+ timeoutMs: z.number().int().min(100).max(120_000).default(15_000),
14
+ maxProjects: z.number().int().min(1).max(1000).default(200),
15
+ }).strict();
16
+ const interval = z.number().int().min(60_000).max(86_400_000);
17
+ const settingsSchema = z.object({
18
+ mode: z.enum(['manual', 'interval']),
19
+ intervalMs: interval.optional(),
20
+ }).strict().superRefine((value, ctx) => {
21
+ if (value.mode === 'interval' && value.intervalMs === undefined) {
22
+ ctx.addIssue({ code: 'custom', message: 'intervalMs is required in interval mode', path: ['intervalMs'] });
23
+ }
24
+ });
25
+ const empty = z.object({}).strict();
26
+ export const DISCOVERY_METHODS = {
27
+ execution_project_scan: { description: '只读探查批准目录及可选 Session Reader 项目中的 .1agents 角色声明;不创建目标或任务。', parameters: z.toJSONSchema(empty) },
28
+ execution_project_list: { description: '读取项目角色候选缓存,不执行扫描或模型。', parameters: z.toJSONSchema(empty) },
29
+ execution_discovery_config_get: { description: '读取项目探查的手动/周期设置,不执行扫描。', parameters: z.toJSONSchema(empty) },
30
+ execution_discovery_config_update: { description: '更新手动/周期探查设置;周期模式需显式指定 intervalMs,不唤醒主会话。', parameters: z.toJSONSchema(settingsSchema) },
31
+ };
32
+ const candidateSchema = z.object({ key: z.string(), projectRoot: absolute, roleDirectory: absolute, profilePath: absolute,
33
+ roleId: z.string().optional(), roleVersion: z.string().optional(),
34
+ skillRefs: z.array(z.object({ key: z.string(), name: z.string() }).strict()).optional(),
35
+ status: z.enum(['candidate', 'invalid', 'missing', 'stale']), reasonCode: z.string().optional(), lastSeenAt: z.string().optional(),
36
+ }).strict();
37
+ const diagnosticSchema = z.object({ code: z.string(), path: z.string().optional() }).strict();
38
+ const snapshotSchema = z.object({ status: z.enum(['idle', 'complete', 'partial', 'error']), scannedAt: z.string().optional(),
39
+ candidates: z.array(candidateSchema).max(20_000), diagnostics: z.array(diagnosticSchema).max(2000),
40
+ }).strict();
41
+ const stateSchema = z.object({ version: z.literal(1), config: settingsSchema, snapshot: snapshotSchema }).strict();
42
+ const within = (root, value) => {
43
+ const relative = path.relative(root, value);
44
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
45
+ };
46
+ const candidateKey = (root, roleId) => createHash('sha256').update(JSON.stringify([root, roleId])).digest('hex');
47
+ const clone = (value) => structuredClone(value);
48
+ const readerPageSchema = z.object({ projects: z.array(z.object({ workspace: absolute,
49
+ workspaces: z.array(absolute).max(1000).optional(),
50
+ }).passthrough()).max(1000), hasMore: z.boolean(), nextPage: z.number().int().positive().optional() }).passthrough();
51
+ export class ProjectRoleDiscovery {
52
+ file;
53
+ config;
54
+ state;
55
+ started = false;
56
+ closed = false;
57
+ timer;
58
+ active;
59
+ controller;
60
+ constructor(options) {
61
+ if (!path.isAbsolute(options.stateDirectory))
62
+ throw new Error('Discovery stateDirectory must be absolute');
63
+ this.config = projectDiscoveryConfigSchema.parse(options.config);
64
+ mkdirSync(options.stateDirectory, { recursive: true, mode: 0o700 });
65
+ this.file = path.join(realpathSync(options.stateDirectory), 'discovery.json');
66
+ try {
67
+ const info = lstatSync(this.file);
68
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 16 * 1024 * 1024)
69
+ throw new Error('Invalid discovery state file');
70
+ this.state = stateSchema.parse(JSON.parse(readFileSync(this.file, 'utf8')));
71
+ }
72
+ catch (error) {
73
+ if (error.code !== 'ENOENT')
74
+ throw new Error('Cannot load discovery state');
75
+ this.state = { version: 1, config: { mode: 'manual' }, snapshot: { status: 'idle', candidates: [], diagnostics: [] } };
76
+ }
77
+ }
78
+ commit(next) {
79
+ stateSchema.parse(next);
80
+ const bytes = JSON.stringify(next);
81
+ if (Buffer.byteLength(bytes) > 16 * 1024 * 1024)
82
+ throw new Error('Discovery snapshot exceeds byte limit');
83
+ const temporary = `${this.file}.${randomUUID()}.tmp`, descriptor = openSync(temporary, 'wx', 0o600);
84
+ try {
85
+ try {
86
+ writeFileSync(descriptor, bytes);
87
+ fsyncSync(descriptor);
88
+ }
89
+ finally {
90
+ closeSync(descriptor);
91
+ }
92
+ renameSync(temporary, this.file);
93
+ const directory = openSync(path.dirname(this.file), 'r');
94
+ try {
95
+ fsyncSync(directory);
96
+ }
97
+ finally {
98
+ closeSync(directory);
99
+ }
100
+ this.state = next;
101
+ }
102
+ catch (error) {
103
+ try {
104
+ unlinkSync(temporary);
105
+ }
106
+ catch { }
107
+ throw error;
108
+ }
109
+ }
110
+ view() { return clone({ config: this.state.config, snapshot: this.state.snapshot }); }
111
+ start() { if (!this.closed) {
112
+ this.started = true;
113
+ this.schedule();
114
+ } }
115
+ schedule() {
116
+ if (this.timer)
117
+ clearTimeout(this.timer);
118
+ this.timer = undefined;
119
+ if (!this.started || this.closed || this.state.config.mode !== 'interval')
120
+ return;
121
+ this.timer = setTimeout(() => {
122
+ this.timer = undefined;
123
+ // Scans write their own diagnostic snapshot. Persistence failures must also stay contained.
124
+ void this.scan().catch(() => { }).finally(() => this.schedule());
125
+ }, this.state.config.intervalMs);
126
+ this.timer.unref();
127
+ }
128
+ async close() {
129
+ this.closed = true;
130
+ if (this.timer)
131
+ clearTimeout(this.timer);
132
+ this.timer = undefined;
133
+ this.controller?.abort();
134
+ await this.active?.catch(() => { });
135
+ }
136
+ async invoke(method, params) {
137
+ if (this.closed)
138
+ throw new Error('Project discovery is closed');
139
+ if (method === 'execution_discovery_config_update') {
140
+ const config = settingsSchema.parse(params);
141
+ this.commit({ ...this.state, config });
142
+ this.schedule();
143
+ return clone(config);
144
+ }
145
+ empty.parse(params);
146
+ if (method === 'execution_discovery_config_get')
147
+ return clone(this.state.config);
148
+ if (method === 'execution_project_list')
149
+ return this.view();
150
+ if (method === 'execution_project_scan')
151
+ return this.scan();
152
+ throw new Error('Unknown project discovery method');
153
+ }
154
+ scan() {
155
+ if (this.active)
156
+ return this.active;
157
+ if (this.closed)
158
+ return Promise.reject(new Error('Project discovery is closed'));
159
+ this.controller = new AbortController();
160
+ this.active = this.collect(this.controller.signal).finally(() => { this.active = undefined; this.controller = undefined; });
161
+ return this.active;
162
+ }
163
+ async reader(scope, page, limit, timeoutMs, signal) {
164
+ const stdout = await new Promise((resolve, reject) => {
165
+ // execFile forwards its timeout killSignal, but some Node versions use SIGTERM for AbortSignal.
166
+ // Explicitly kill the configured Reader on close, including Readers that ignore SIGTERM.
167
+ const abort = () => { child.kill('SIGKILL'); };
168
+ const child = execFile(this.config.readerExecutable, ['projects', '--scope', scope, '--page', String(page), '--limit', String(limit), '--json'], { encoding: 'utf8', timeout: timeoutMs, maxBuffer: 2 * 1024 * 1024, windowsHide: true, shell: false, killSignal: 'SIGKILL' }, (error, output) => {
169
+ signal.removeEventListener('abort', abort);
170
+ if (error)
171
+ reject(new Error(signal.aborted ? 'reader_cancelled' : 'reader_failed'));
172
+ else
173
+ resolve(output);
174
+ });
175
+ signal.addEventListener('abort', abort, { once: true });
176
+ if (signal.aborted)
177
+ abort();
178
+ });
179
+ try {
180
+ return readerPageSchema.parse(JSON.parse(stdout));
181
+ }
182
+ catch {
183
+ throw new Error('reader_invalid_output');
184
+ }
185
+ }
186
+ async collect(signal) {
187
+ const diagnostics = [], candidates = new Map(), now = new Date().toISOString();
188
+ let diagnosticBytes = 0;
189
+ const note = (code, value) => {
190
+ const item = { code, ...(value ? { path: value } : {}) }, bytes = Buffer.byteLength(JSON.stringify(item));
191
+ if (diagnostics.length < 2000 && diagnosticBytes + bytes < 64 * 1024) {
192
+ diagnostics.push(item);
193
+ diagnosticBytes += bytes;
194
+ }
195
+ };
196
+ const roots = [], paths = new Set();
197
+ let partial = false, readerSucceeded = false, projectCount = 0;
198
+ for (const configured of this.config.allowedRoots) {
199
+ try {
200
+ const root = await realpath(configured);
201
+ if (!(await lstat(root)).isDirectory())
202
+ throw new Error();
203
+ roots.push(root);
204
+ paths.add(root);
205
+ }
206
+ catch {
207
+ note('allowed_root_missing', configured);
208
+ partial = true;
209
+ }
210
+ }
211
+ const allowed = (value) => roots.some(root => within(root, value));
212
+ for (const explicit of this.config.explicitRoots)
213
+ paths.add(explicit);
214
+ const readerDeadline = Date.now() + this.config.timeoutMs;
215
+ const scopes = [...new Set(roots)];
216
+ for (const [scopeIndex, scope] of scopes.entries()) {
217
+ let page = 1;
218
+ while (!signal.aborted && projectCount < this.config.maxProjects) {
219
+ const remaining = readerDeadline - Date.now();
220
+ if (remaining <= 0) {
221
+ note('reader_timeout', scope);
222
+ partial = true;
223
+ break;
224
+ }
225
+ try {
226
+ const limit = Math.min(50, this.config.maxProjects - projectCount);
227
+ const result = await this.reader(scope, page, limit, remaining, signal);
228
+ if (result.projects.length > limit)
229
+ throw new Error('reader_invalid_output');
230
+ readerSucceeded = true;
231
+ projectCount += result.projects.length;
232
+ for (const project of result.projects)
233
+ for (const value of [project.workspace, ...project.workspaces ?? []]) {
234
+ if (paths.size < this.config.maxProjects * 10 + this.config.explicitRoots.length + roots.length)
235
+ paths.add(value);
236
+ else {
237
+ note('candidate_limit');
238
+ partial = true;
239
+ }
240
+ }
241
+ if (!result.hasMore)
242
+ break;
243
+ if (!result.projects.length || (result.nextPage !== undefined && result.nextPage !== page + 1))
244
+ throw new Error('reader_invalid_pagination');
245
+ if (projectCount >= this.config.maxProjects) {
246
+ note('project_limit');
247
+ partial = true;
248
+ break;
249
+ }
250
+ page++;
251
+ }
252
+ catch (error) {
253
+ note(error.message.startsWith('reader_') ? error.message : 'reader_failed', scope);
254
+ partial = true;
255
+ break;
256
+ }
257
+ }
258
+ if (projectCount >= this.config.maxProjects) {
259
+ if (scopeIndex < scopes.length - 1) {
260
+ note('project_limit');
261
+ partial = true;
262
+ }
263
+ break;
264
+ }
265
+ }
266
+ const visited = new Set(), roleBudget = { count: 0, bytes: 0, limited: false };
267
+ directories: for (const candidate of paths) {
268
+ if (signal.aborted)
269
+ break;
270
+ // Native sessions can start inside runtime jobs; never traverse role caches as projects.
271
+ const segments = path.resolve(candidate).split(path.sep), internal = segments.indexOf('.1agents');
272
+ const base = internal < 0 ? candidate : segments.slice(0, internal).join(path.sep) || path.sep;
273
+ let current;
274
+ try {
275
+ current = await realpath(base);
276
+ // A plain alias can resolve into a cache/job even when its lexical path has no .1agents.
277
+ const canonicalSegments = current.split(path.sep), canonicalInternal = canonicalSegments.indexOf('.1agents');
278
+ if (canonicalInternal >= 0)
279
+ current = canonicalSegments.slice(0, canonicalInternal).join(path.sep) || path.sep;
280
+ if (!(await lstat(current)).isDirectory())
281
+ throw new Error();
282
+ }
283
+ catch {
284
+ note('project_missing', base);
285
+ continue;
286
+ }
287
+ if (!allowed(current)) {
288
+ note('outside_allowed_roots', base);
289
+ continue;
290
+ }
291
+ for (let depth = 0; depth < 32 && allowed(current) && !signal.aborted; depth++) {
292
+ if (!visited.has(current)) {
293
+ if (visited.size >= 20_000) {
294
+ note('directory_limit');
295
+ partial = true;
296
+ break directories;
297
+ }
298
+ visited.add(current);
299
+ try {
300
+ await this.readRoles(current, candidates, now, signal, roleBudget);
301
+ }
302
+ catch (error) {
303
+ const code = error.message, exhausted = code === 'candidate_limit' || code === 'snapshot_limit';
304
+ note(exhausted ? code : 'role_directory_unreadable', current);
305
+ partial = true;
306
+ if (exhausted)
307
+ break directories;
308
+ }
309
+ }
310
+ const parent = path.dirname(current);
311
+ if (parent === current || !allowed(parent))
312
+ break;
313
+ if (depth === 31) {
314
+ note('ancestor_limit', current);
315
+ partial = true;
316
+ }
317
+ current = parent;
318
+ }
319
+ }
320
+ if (signal.aborted) {
321
+ note('scan_cancelled');
322
+ partial = true;
323
+ }
324
+ // Bound complete snapshots too: individually valid large profiles can exceed a safe cache size.
325
+ const retained = new Map();
326
+ const size = (candidate) => Buffer.byteLength(JSON.stringify(candidate)) + 1;
327
+ let candidateBytes = 0;
328
+ for (const old of this.state.snapshot.candidates) {
329
+ const value = { ...old, status: partial ? 'stale' : 'missing', reasonCode: partial ? 'scan_incomplete' : 'not_observed' };
330
+ retained.set(old.key, value);
331
+ candidateBytes += size(value);
332
+ }
333
+ let limited = roleBudget.limited || candidateBytes > 8 * 1024 * 1024;
334
+ for (const [key, value] of candidates) {
335
+ const old = retained.get(key), nextBytes = candidateBytes + size(value) - (old ? size(old) : 0);
336
+ if ((!old && retained.size >= 20_000) || nextBytes > 8 * 1024 * 1024) {
337
+ limited = true;
338
+ continue;
339
+ }
340
+ retained.set(key, value);
341
+ candidateBytes = nextBytes;
342
+ }
343
+ if (limited) {
344
+ note('snapshot_limit');
345
+ partial = true;
346
+ // On overflow keep the complete prior evidence, rather than evicting older candidates.
347
+ if (this.state.snapshot.candidates.length) {
348
+ retained.clear();
349
+ for (const old of this.state.snapshot.candidates)
350
+ retained.set(old.key, { ...old, status: 'stale' });
351
+ }
352
+ }
353
+ if (partial && !limited)
354
+ for (const [key, value] of retained)
355
+ if (!candidates.has(key))
356
+ retained.set(key, { ...value, status: 'stale', reasonCode: 'scan_incomplete' });
357
+ const snapshot = { scannedAt: now,
358
+ status: partial ? (readerSucceeded || retained.size || visited.size ? 'partial' : 'error') : 'complete',
359
+ candidates: [...retained.values()].sort((a, b) => a.projectRoot.localeCompare(b.projectRoot) || a.profilePath.localeCompare(b.profilePath)), diagnostics };
360
+ this.commit({ ...this.state, snapshot });
361
+ return this.view();
362
+ }
363
+ async readRoles(projectRoot, result, now, signal, budget) {
364
+ const agentDirectory = path.join(projectRoot, '.1agents'), roles = path.join(agentDirectory, 'roles');
365
+ for (const directory of [agentDirectory, roles]) {
366
+ let info;
367
+ try {
368
+ info = await lstat(directory);
369
+ }
370
+ catch (error) {
371
+ if (error.code === 'ENOENT')
372
+ return;
373
+ throw error;
374
+ }
375
+ if (info.isSymbolicLink() || !info.isDirectory() || !within(projectRoot, await realpath(directory)))
376
+ throw new Error('Unsafe role directory');
377
+ }
378
+ const entries = await readdir(roles, { withFileTypes: true });
379
+ if (entries.length > 1000) {
380
+ budget.limited = true;
381
+ throw new Error('candidate_limit');
382
+ }
383
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
384
+ if (signal.aborted)
385
+ return;
386
+ if (!entry.isDirectory() && !entry.isSymbolicLink())
387
+ continue;
388
+ if (budget.count >= 10_000) {
389
+ budget.limited = true;
390
+ throw new Error('candidate_limit');
391
+ }
392
+ budget.count++;
393
+ const roleDirectory = path.join(roles, entry.name), profilePath = path.join(roleDirectory, 'profile.json');
394
+ const base = { key: candidateKey(projectRoot, entry.name), projectRoot, roleDirectory, profilePath, status: 'invalid', lastSeenAt: now };
395
+ let candidate = base;
396
+ try {
397
+ if (entry.isSymbolicLink() || !(await lstat(roleDirectory)).isDirectory() || !within(projectRoot, await realpath(roleDirectory)))
398
+ throw new Error('unsafe_role_path');
399
+ const handle = await open(profilePath, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
400
+ let profile;
401
+ try {
402
+ const info = await handle.stat();
403
+ if (!info.isFile() || info.size > 256 * 1024 || !within(projectRoot, await realpath(profilePath)))
404
+ throw new Error('unsafe_profile');
405
+ profile = roleSkillProfileSchema.parse(JSON.parse(await handle.readFile('utf8')));
406
+ }
407
+ finally {
408
+ await handle.close();
409
+ }
410
+ candidate = { ...base, key: candidateKey(projectRoot, profile.id), roleId: profile.id, roleVersion: profile.version,
411
+ skillRefs: profile.skills.map(skill => ({ key: skill.key, name: skill.name })), status: 'candidate' };
412
+ }
413
+ catch (error) {
414
+ candidate = { ...base, status: error.code === 'ENOENT' ? 'missing' : 'invalid',
415
+ reasonCode: error.code === 'ENOENT' ? 'profile_missing' : 'profile_invalid_or_unsafe' };
416
+ }
417
+ const existing = result.get(candidate.key);
418
+ if (existing && existing.profilePath !== candidate.profilePath)
419
+ candidate = { ...existing, status: 'invalid', reasonCode: 'duplicate_role_id' };
420
+ const bytes = budget.bytes + Buffer.byteLength(JSON.stringify(candidate)) + 1 - (existing ? Buffer.byteLength(JSON.stringify(existing)) + 1 : 0);
421
+ if (bytes > 8 * 1024 * 1024) {
422
+ budget.limited = true;
423
+ throw new Error('snapshot_limit');
424
+ }
425
+ budget.bytes = bytes;
426
+ result.set(candidate.key, candidate);
427
+ }
428
+ }
429
+ }
@@ -0,0 +1,60 @@
1
+ import { z } from 'zod';
2
+ import { type HumanReviewRequest } from './human-review.js';
3
+ import type { LedgerAttempt } from './ledger.js';
4
+ export declare const reportReviewPolicySchema: z.ZodObject<{
5
+ workspaceRoot: z.ZodString;
6
+ allowedProjectRoots: z.ZodArray<z.ZodString>;
7
+ allowedRemotes: z.ZodArray<z.ZodString>;
8
+ }, z.core.$strict>;
9
+ export declare const reportReviewInputSchema: z.ZodObject<{
10
+ fileName: z.ZodDefault<z.ZodString>;
11
+ }, z.core.$strict>;
12
+ export type ReportReviewPolicy = z.infer<typeof reportReviewPolicySchema>;
13
+ export interface ReportReviewRun {
14
+ sourceId: string;
15
+ jobId: string;
16
+ attemptId: string;
17
+ originSessionId: string;
18
+ title: string;
19
+ targetId: string;
20
+ remote: string;
21
+ cwd: string;
22
+ authorInput: Record<string, unknown>;
23
+ directory: string;
24
+ reportPath: string;
25
+ revision: number;
26
+ reviewerId: string;
27
+ stage: 'research' | 'file_check' | 'human_review' | 'finished';
28
+ phase: string;
29
+ executionStatus: 'working' | 'input_required' | 'completed' | 'failed' | 'canceled';
30
+ child?: {
31
+ jobId: string;
32
+ attemptId: string;
33
+ };
34
+ humanReviews: HumanReviewRequest[];
35
+ digest?: string;
36
+ snapshotPath?: string;
37
+ fileCheck?: {
38
+ passed: boolean;
39
+ path: string;
40
+ checkedAt: string;
41
+ size?: number;
42
+ sha256?: string;
43
+ error?: string;
44
+ };
45
+ resultSummary?: string;
46
+ createdAt: string;
47
+ updatedAt: string;
48
+ }
49
+ export interface ReportReviewAdapter {
50
+ persist(run: ReportReviewRun): void;
51
+ submit(run: ReportReviewRun, prompt: string, previous?: ReportReviewRun['child']): Promise<ReportReviewRun['child']>;
52
+ child(attemptId: string): LedgerAttempt;
53
+ update(run: ReportReviewRun): void;
54
+ }
55
+ export declare const reportRevision: (run: ReportReviewRun) => string;
56
+ export declare function createReportReviewRun(input: Pick<ReportReviewRun, 'sourceId' | 'jobId' | 'attemptId' | 'originSessionId' | 'title' | 'targetId' | 'remote' | 'cwd' | 'authorInput' | 'reviewerId'>, policy: ReportReviewPolicy, report: z.input<typeof reportReviewInputSchema>): Promise<ReportReviewRun>;
57
+ /** Read bounded regular bytes without following symlinks or accepting linked aliases. */
58
+ export declare function readReportFile(file: string): Promise<Buffer>;
59
+ export declare function reportBindingDigest(run: ReportReviewRun): Promise<string>;
60
+ export declare function advanceReportReview(run: ReportReviewRun, adapter: ReportReviewAdapter): Promise<void>;