@abelxiaoxing/cadence 2.0.23 → 2.0.24
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.
- package/docs/conversation-mode.md +19 -0
- package/package.json +2 -1
- package/src/cadence-mode.ts +283 -165
- package/src/coordinator-tools.mjs +9 -0
- package/src/native-build.ts +1 -1
- package/src/native-workflow-history.ts +3 -1
- package/src/research-tools.mjs +365 -0
- package/src/sdk-worker.mjs +59 -9
- package/src/service/contracts/workflow.ts +132 -1
- package/src/service-cli.mjs +15 -2
- package/src/service-host.mjs +217 -29
- package/src/worker-public.mjs +16 -1
- package/web/dist/assets/cadence.js +15 -14
- package/web/dist/manifest.json +5 -5
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
/** Deterministic workflow inspection, independent of model availability and mode. */
|
|
2
|
+
|
|
2
3
|
import { type NativeViews, pretty, value } from "./native-history.ts";
|
|
3
4
|
import type { WorkbenchResult } from "./service/contracts/workbench.ts";
|
|
5
|
+
import { workflowDiagnostics } from "./service/contracts/workflow.ts";
|
|
4
6
|
import type { ServiceClient } from "./service-client.ts";
|
|
5
7
|
import { ContractError } from "./service-contract.ts";
|
|
6
8
|
|
|
@@ -22,7 +24,7 @@ export async function workflowDetails(
|
|
|
22
24
|
throw new ContractError("invalid");
|
|
23
25
|
const run = view.response.run;
|
|
24
26
|
await ui.show(
|
|
25
|
-
`${run.goal}\n${run.id} • ${run.status} / ${run.phase}\n${run.notice}\nMerged commit: ${run.mergedCommit ?? "none"}\nAutomatic Agent review is not human review. Step summaries are previews; select a step for its retained result.\n${pretty(run.steps)}`,
|
|
27
|
+
`${run.goal}\n${run.id} • ${run.status} / ${run.phase}\n${run.notice}\n${workflowDiagnostics(run)}\nMerged commit: ${run.mergedCommit ?? "none"}\nAutomatic Agent review is not human review. Step summaries are previews; select a step for its retained result.\n${pretty(run.steps)}`,
|
|
26
28
|
);
|
|
27
29
|
const labels = run.steps.map(
|
|
28
30
|
(s, i) => `${i + 1}. ${s.kind} • ${s.id} • ${s.status}`,
|
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
/** Cooperative, bounded readonly investigation. No shell, downloads, raw spill,
|
|
2
|
+
* or abandoned Promise.race: every original filesystem operation is joined.
|
|
3
|
+
* Not a sandbox. The parent process deadline remains the hard stop for stuck I/O. */
|
|
4
|
+
import { constants } from "node:fs";
|
|
5
|
+
import { open, opendir, realpath, stat } from "node:fs/promises";
|
|
6
|
+
import {
|
|
7
|
+
basename,
|
|
8
|
+
isAbsolute,
|
|
9
|
+
join,
|
|
10
|
+
matchesGlob,
|
|
11
|
+
relative,
|
|
12
|
+
resolve,
|
|
13
|
+
sep,
|
|
14
|
+
} from "node:path";
|
|
15
|
+
import { Type } from "typebox";
|
|
16
|
+
|
|
17
|
+
export const RESEARCH_LIMITS = {
|
|
18
|
+
calls: 64,
|
|
19
|
+
toolMs: 30_000,
|
|
20
|
+
finishReserveMs: 120_000,
|
|
21
|
+
entries: 2000,
|
|
22
|
+
depth: 8,
|
|
23
|
+
results: 100,
|
|
24
|
+
fileBytes: 1024 * 1024,
|
|
25
|
+
scanBytes: 8 * 1024 * 1024,
|
|
26
|
+
outputBytes: 32 * 1024,
|
|
27
|
+
};
|
|
28
|
+
const within = (root, path) => {
|
|
29
|
+
const p = relative(root, path);
|
|
30
|
+
return (
|
|
31
|
+
p === "" || (!isAbsolute(p) && p !== ".." && !p.startsWith(`..${sep}`))
|
|
32
|
+
);
|
|
33
|
+
};
|
|
34
|
+
class Bound extends Error {}
|
|
35
|
+
const STOP =
|
|
36
|
+
"Investigation budget reached. Do not retry the same search. Summarize retained evidence, missing coverage and a narrower follow-up for the user.";
|
|
37
|
+
|
|
38
|
+
/** Node's same-host monotonic clock, not a child-local performance origin. */
|
|
39
|
+
export const researchClock = () => Number(process.hrtime.bigint() / 1_000_000n);
|
|
40
|
+
|
|
41
|
+
export function researchTools(cwd, roots, budget, now = researchClock) {
|
|
42
|
+
const finishAt =
|
|
43
|
+
budget.deadlineMs -
|
|
44
|
+
Math.min(RESEARCH_LIMITS.finishReserveMs, budget.timeoutMs / 10);
|
|
45
|
+
let calls = 0;
|
|
46
|
+
// Resolve only when explicitly used, never during resource discovery.
|
|
47
|
+
let selected;
|
|
48
|
+
const scope = async () => {
|
|
49
|
+
selected ??= (async () => {
|
|
50
|
+
const paths = [];
|
|
51
|
+
// Sequential originals: a rejected root cannot abandon sibling realpaths.
|
|
52
|
+
for (const p of roots.length ? roots : [cwd])
|
|
53
|
+
paths.push(await realpath(resolve(cwd, p)));
|
|
54
|
+
return paths;
|
|
55
|
+
})();
|
|
56
|
+
return selected;
|
|
57
|
+
};
|
|
58
|
+
const pathSchema = Type.Optional(
|
|
59
|
+
Type.String({
|
|
60
|
+
description:
|
|
61
|
+
"Path inside the supplied investigation roots; omitted and relative paths use the first root. Never start at / or a parent directory.",
|
|
62
|
+
}),
|
|
63
|
+
);
|
|
64
|
+
const limitSchema = Type.Optional(
|
|
65
|
+
Type.Integer({ minimum: 1, maximum: RESEARCH_LIMITS.results }),
|
|
66
|
+
);
|
|
67
|
+
const tools = [
|
|
68
|
+
{
|
|
69
|
+
name: "ls",
|
|
70
|
+
description:
|
|
71
|
+
"List one directory without per-entry stat calls. Filesystem order, at most 100 entries; use a specific subdirectory to narrow. No recursive listing.",
|
|
72
|
+
parameters: Type.Object({ path: pathSchema, limit: limitSchema }),
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
name: "find",
|
|
76
|
+
description:
|
|
77
|
+
"Bounded simple filename glob search (*, **, ?, brackets; no braces/extglobs) inside an investigation root. At most 2000 entries, depth 8, 100 results and 30s cooperative work. Does not follow symlinks; skips .git/node_modules, not backup trees. Does not interpret .gitignore. Partial coverage is explicit; narrow the path rather than repeating.",
|
|
78
|
+
parameters: Type.Object({
|
|
79
|
+
pattern: Type.String({ minLength: 1, maxLength: 256 }),
|
|
80
|
+
path: pathSchema,
|
|
81
|
+
limit: limitSchema,
|
|
82
|
+
depth: Type.Optional(
|
|
83
|
+
Type.Integer({ minimum: 0, maximum: RESEARCH_LIMITS.depth }),
|
|
84
|
+
),
|
|
85
|
+
}),
|
|
86
|
+
},
|
|
87
|
+
{
|
|
88
|
+
name: "grep",
|
|
89
|
+
description:
|
|
90
|
+
"Bounded literal text search (not regex). Search a specific file or narrow directory; optional simple filename glob (no braces/extglobs). At most 1MiB per file, 8MiB total, 2000 entries, depth 8, 100 matching lines. Binary files, symlinks and .git/node_modules are not searched; .gitignore is not interpreted. Reports incomplete coverage.",
|
|
91
|
+
parameters: Type.Object({
|
|
92
|
+
pattern: Type.String({ minLength: 1, maxLength: 256 }),
|
|
93
|
+
path: pathSchema,
|
|
94
|
+
glob: Type.Optional(Type.String({ maxLength: 256 })),
|
|
95
|
+
ignoreCase: Type.Optional(Type.Boolean()),
|
|
96
|
+
literal: Type.Optional(Type.Boolean()),
|
|
97
|
+
limit: limitSchema,
|
|
98
|
+
depth: Type.Optional(
|
|
99
|
+
Type.Integer({ minimum: 0, maximum: RESEARCH_LIMITS.depth }),
|
|
100
|
+
),
|
|
101
|
+
}),
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
name: "read",
|
|
105
|
+
description:
|
|
106
|
+
"Read a bounded UTF-8 text file within the investigation roots. At most the first 1MiB, 100 requested lines and 32KiB output. Binary/media are not decoded; partial coverage is explicit.",
|
|
107
|
+
parameters: Type.Object({
|
|
108
|
+
path: Type.String(),
|
|
109
|
+
offset: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
110
|
+
limit: limitSchema,
|
|
111
|
+
}),
|
|
112
|
+
},
|
|
113
|
+
];
|
|
114
|
+
return tools.map((tool) => ({
|
|
115
|
+
...tool,
|
|
116
|
+
label: tool.name,
|
|
117
|
+
async execute(_id, args, signal) {
|
|
118
|
+
if (++calls > RESEARCH_LIMITS.calls || now() >= finishAt)
|
|
119
|
+
throw new Error(STOP);
|
|
120
|
+
const startedAt = now();
|
|
121
|
+
const deadline = Math.min(finishAt, now() + RESEARCH_LIMITS.toolMs);
|
|
122
|
+
const check = () => {
|
|
123
|
+
if (signal?.aborted) throw new Error("Investigation canceled");
|
|
124
|
+
if (now() >= deadline) throw new Bound("cooperative time limit");
|
|
125
|
+
};
|
|
126
|
+
const limits = new Set();
|
|
127
|
+
const lines = [];
|
|
128
|
+
let entries = 0,
|
|
129
|
+
bytes = 0,
|
|
130
|
+
outputBytes = 0;
|
|
131
|
+
const limit = args.limit ?? RESEARCH_LIMITS.results;
|
|
132
|
+
if (
|
|
133
|
+
!Number.isSafeInteger(limit) ||
|
|
134
|
+
limit < 1 ||
|
|
135
|
+
limit > RESEARCH_LIMITS.results
|
|
136
|
+
)
|
|
137
|
+
throw new Error("Invalid result limit");
|
|
138
|
+
const depth = args.depth ?? RESEARCH_LIMITS.depth;
|
|
139
|
+
if (
|
|
140
|
+
!Number.isSafeInteger(depth) ||
|
|
141
|
+
depth < 0 ||
|
|
142
|
+
depth > RESEARCH_LIMITS.depth
|
|
143
|
+
)
|
|
144
|
+
throw new Error("Invalid search depth");
|
|
145
|
+
const add = (line) => {
|
|
146
|
+
if (lines.length >= limit) throw new Bound("result limit");
|
|
147
|
+
if (
|
|
148
|
+
outputBytes + Buffer.byteLength(line) + 1 >
|
|
149
|
+
RESEARCH_LIMITS.outputBytes
|
|
150
|
+
)
|
|
151
|
+
throw new Bound("output limit");
|
|
152
|
+
outputBytes += Buffer.byteLength(line) + 1;
|
|
153
|
+
lines.push(line);
|
|
154
|
+
};
|
|
155
|
+
const read = async (path) => {
|
|
156
|
+
check();
|
|
157
|
+
const file = await open(
|
|
158
|
+
path,
|
|
159
|
+
constants.O_RDONLY |
|
|
160
|
+
constants.O_NONBLOCK |
|
|
161
|
+
(constants.O_NOFOLLOW ?? 0),
|
|
162
|
+
);
|
|
163
|
+
try {
|
|
164
|
+
check();
|
|
165
|
+
const info = await file.stat();
|
|
166
|
+
if (!info.isFile())
|
|
167
|
+
throw new Error("Only regular text files can be read");
|
|
168
|
+
const size = Math.min(
|
|
169
|
+
RESEARCH_LIMITS.fileBytes,
|
|
170
|
+
RESEARCH_LIMITS.scanBytes - bytes,
|
|
171
|
+
);
|
|
172
|
+
if (!size) throw new Bound("aggregate byte limit");
|
|
173
|
+
const buffer = Buffer.alloc(size);
|
|
174
|
+
let offset = 0;
|
|
175
|
+
while (offset < size) {
|
|
176
|
+
check();
|
|
177
|
+
const result = await file.read(
|
|
178
|
+
buffer,
|
|
179
|
+
offset,
|
|
180
|
+
Math.min(65536, size - offset),
|
|
181
|
+
offset,
|
|
182
|
+
);
|
|
183
|
+
bytes += result.bytesRead;
|
|
184
|
+
if (!result.bytesRead) break;
|
|
185
|
+
offset += result.bytesRead;
|
|
186
|
+
}
|
|
187
|
+
check();
|
|
188
|
+
// Read actual EOF, not stat.size (virtual/growing files can report zero).
|
|
189
|
+
if (offset === size) limits.add("file/aggregate byte limit");
|
|
190
|
+
const content = buffer.subarray(0, offset);
|
|
191
|
+
if (content.includes(0)) {
|
|
192
|
+
limits.add("binary file omitted");
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
try {
|
|
196
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(content);
|
|
197
|
+
} catch {
|
|
198
|
+
limits.add("non-UTF-8 or cut UTF-8 file omitted");
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
} finally {
|
|
202
|
+
await file.close();
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
const walk = async function* (path, remaining, root) {
|
|
206
|
+
check();
|
|
207
|
+
const dir = await opendir(path);
|
|
208
|
+
try {
|
|
209
|
+
for (;;) {
|
|
210
|
+
check();
|
|
211
|
+
const e = await dir.read();
|
|
212
|
+
check();
|
|
213
|
+
if (!e) break;
|
|
214
|
+
if (++entries > RESEARCH_LIMITS.entries)
|
|
215
|
+
throw new Bound("entry limit");
|
|
216
|
+
const full = join(path, e.name);
|
|
217
|
+
if (e.isSymbolicLink()) {
|
|
218
|
+
limits.add("symlink omitted");
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
if (e.isDirectory()) {
|
|
222
|
+
if (e.name === ".git" || e.name === "node_modules") {
|
|
223
|
+
limits.add(".git/node_modules omitted");
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
if (remaining === 0) {
|
|
227
|
+
limits.add("depth limit");
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
try {
|
|
231
|
+
yield* walk(full, remaining - 1, root);
|
|
232
|
+
} catch (error) {
|
|
233
|
+
if (error instanceof Bound || signal?.aborted) throw error;
|
|
234
|
+
limits.add("unreadable directory omitted");
|
|
235
|
+
}
|
|
236
|
+
} else if (e.isFile())
|
|
237
|
+
yield {
|
|
238
|
+
path: full,
|
|
239
|
+
name: relative(root, full).split(sep).join("/"),
|
|
240
|
+
};
|
|
241
|
+
else limits.add("special file omitted");
|
|
242
|
+
}
|
|
243
|
+
} finally {
|
|
244
|
+
await dir.close();
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
try {
|
|
248
|
+
check();
|
|
249
|
+
const allowed = await scope();
|
|
250
|
+
check();
|
|
251
|
+
const target = await realpath(
|
|
252
|
+
args.path === undefined ? allowed[0] : resolve(allowed[0], args.path),
|
|
253
|
+
);
|
|
254
|
+
check();
|
|
255
|
+
if (!allowed.some((p) => within(p, target)))
|
|
256
|
+
throw new Error(
|
|
257
|
+
"Path outside investigation roots. Ask the coordinator to select the specific intended root; do not enumerate parent directories.",
|
|
258
|
+
);
|
|
259
|
+
const info = await stat(target);
|
|
260
|
+
check();
|
|
261
|
+
if (tool.name === "ls") {
|
|
262
|
+
if (!info.isDirectory()) throw new Error("Select a directory");
|
|
263
|
+
const dir = await opendir(target);
|
|
264
|
+
try {
|
|
265
|
+
for (;;) {
|
|
266
|
+
check();
|
|
267
|
+
const e = await dir.read();
|
|
268
|
+
check();
|
|
269
|
+
if (!e) break;
|
|
270
|
+
entries++;
|
|
271
|
+
add(
|
|
272
|
+
`${e.name}${e.isDirectory() ? "/" : e.isSymbolicLink() ? " [symlink; not followed]" : ""}`,
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
} finally {
|
|
276
|
+
await dir.close();
|
|
277
|
+
}
|
|
278
|
+
} else if (tool.name === "read") {
|
|
279
|
+
const content = await read(target);
|
|
280
|
+
const offset = args.offset ?? 1;
|
|
281
|
+
if (!Number.isSafeInteger(offset) || offset < 1)
|
|
282
|
+
throw new Error("Invalid line offset");
|
|
283
|
+
if (content !== null)
|
|
284
|
+
for (const line of content.split("\n").slice(offset - 1)) {
|
|
285
|
+
check();
|
|
286
|
+
add(line);
|
|
287
|
+
}
|
|
288
|
+
} else {
|
|
289
|
+
if (tool.name === "grep" && args.literal === false)
|
|
290
|
+
throw new Error(
|
|
291
|
+
"Research grep supports literal text only. Supply a literal pattern, not a regex.",
|
|
292
|
+
);
|
|
293
|
+
const glob = tool.name === "find" ? args.pattern : args.glob;
|
|
294
|
+
if (
|
|
295
|
+
glob !== undefined &&
|
|
296
|
+
(typeof glob !== "string" ||
|
|
297
|
+
!glob ||
|
|
298
|
+
glob.length > 256 ||
|
|
299
|
+
/[{}()]/u.test(glob))
|
|
300
|
+
)
|
|
301
|
+
throw new Error("Use a simple glob without braces or extglobs");
|
|
302
|
+
const pattern = args.ignoreCase
|
|
303
|
+
? args.pattern.toLowerCase()
|
|
304
|
+
: args.pattern;
|
|
305
|
+
const files = info.isDirectory()
|
|
306
|
+
? walk(target, depth, target)
|
|
307
|
+
: [{ path: target, name: basename(target) }];
|
|
308
|
+
for await (const file of files) {
|
|
309
|
+
check();
|
|
310
|
+
if (
|
|
311
|
+
glob &&
|
|
312
|
+
!matchesGlob(
|
|
313
|
+
glob.includes("/") ? file.name : basename(file.name),
|
|
314
|
+
glob,
|
|
315
|
+
)
|
|
316
|
+
)
|
|
317
|
+
continue;
|
|
318
|
+
if (tool.name === "find") add(file.name);
|
|
319
|
+
else {
|
|
320
|
+
let content;
|
|
321
|
+
try {
|
|
322
|
+
content = await read(file.path);
|
|
323
|
+
} catch (e) {
|
|
324
|
+
if (e instanceof Bound || signal?.aborted) throw e;
|
|
325
|
+
limits.add("unreadable file omitted");
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
if (content === null) continue;
|
|
329
|
+
let n = 0;
|
|
330
|
+
for (const line of content.split("\n")) {
|
|
331
|
+
check();
|
|
332
|
+
n++;
|
|
333
|
+
if (
|
|
334
|
+
(args.ignoreCase ? line.toLowerCase() : line).includes(
|
|
335
|
+
pattern,
|
|
336
|
+
)
|
|
337
|
+
)
|
|
338
|
+
add(`${file.name}:${n}: ${line}`);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
} catch (e) {
|
|
344
|
+
if (!(e instanceof Bound)) throw e;
|
|
345
|
+
limits.add(e.message);
|
|
346
|
+
}
|
|
347
|
+
// A bounded prefix is evidence, never proof that the unsearched tree has no match.
|
|
348
|
+
const partial = limits.size > 0;
|
|
349
|
+
return {
|
|
350
|
+
content: [
|
|
351
|
+
{
|
|
352
|
+
type: "text",
|
|
353
|
+
text: `${lines.join("\n") || (partial ? "No results in the inspected portion." : "No results in the requested scope.")}\n\n${partial ? `[Partial coverage: ${[...limits].join(", ")}. Narrow the path; do not infer absence.]` : "[Requested scope inspected.]"}${now() >= finishAt || calls >= RESEARCH_LIMITS.calls ? `\n${STOP}` : ""}`,
|
|
354
|
+
},
|
|
355
|
+
],
|
|
356
|
+
details: {
|
|
357
|
+
elapsedMs: Math.max(0, now() - startedAt),
|
|
358
|
+
inspectedEntries: entries,
|
|
359
|
+
readBytes: bytes,
|
|
360
|
+
...(partial ? { truncation: { reason: [...limits] } } : {}),
|
|
361
|
+
},
|
|
362
|
+
};
|
|
363
|
+
},
|
|
364
|
+
}));
|
|
365
|
+
}
|
package/src/sdk-worker.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Isolated SDK child, not Pi CLI startup. Task discovery stays disabled;
|
|
2
2
|
// ordinary conversations explicitly load only context/skills, never extensions.
|
|
3
|
-
import {
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
4
5
|
import {
|
|
5
6
|
createProvider,
|
|
6
7
|
InMemoryCredentialStore,
|
|
@@ -13,6 +14,7 @@ import {
|
|
|
13
14
|
ModelRuntime,
|
|
14
15
|
SessionManager,
|
|
15
16
|
SettingsManager,
|
|
17
|
+
VERSION,
|
|
16
18
|
} from "@earendil-works/pi-coding-agent";
|
|
17
19
|
import {
|
|
18
20
|
encodeConversationContext,
|
|
@@ -20,6 +22,7 @@ import {
|
|
|
20
22
|
} from "./conversation-context.mjs";
|
|
21
23
|
import { conversationResources } from "./conversation-resources.mjs";
|
|
22
24
|
import { coordinatorTools } from "./coordinator-tools.mjs";
|
|
25
|
+
import { researchClock, researchTools } from "./research-tools.mjs";
|
|
23
26
|
import { CaptureEmitter, SdkCapture } from "./worker-capture.mjs";
|
|
24
27
|
import {
|
|
25
28
|
closed,
|
|
@@ -198,12 +201,14 @@ try {
|
|
|
198
201
|
new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)),
|
|
199
202
|
LIMITS.workerRequestBytes,
|
|
200
203
|
);
|
|
201
|
-
const envelope = closed(
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
204
|
+
const envelope = closed(parsed, [
|
|
205
|
+
"request",
|
|
206
|
+
"cwd",
|
|
207
|
+
"model",
|
|
208
|
+
"auth",
|
|
209
|
+
...(Object.hasOwn(parsed ?? {}, "conversation") ? ["conversation"] : []),
|
|
210
|
+
...(Object.hasOwn(parsed ?? {}, "investigation") ? ["investigation"] : []),
|
|
211
|
+
]);
|
|
207
212
|
const conversation =
|
|
208
213
|
envelope.conversation === undefined
|
|
209
214
|
? null
|
|
@@ -221,6 +226,25 @@ try {
|
|
|
221
226
|
typeof conversation.agentDir !== "string")
|
|
222
227
|
)
|
|
223
228
|
refuse("parse", "invalid-conversation");
|
|
229
|
+
const investigation =
|
|
230
|
+
envelope.investigation === undefined
|
|
231
|
+
? null
|
|
232
|
+
: closed(envelope.investigation, ["roots", "timeoutMs", "deadlineMs"]);
|
|
233
|
+
if (
|
|
234
|
+
investigation &&
|
|
235
|
+
(!Array.isArray(investigation.roots) ||
|
|
236
|
+
investigation.roots.length < 1 ||
|
|
237
|
+
investigation.roots.length > 8 ||
|
|
238
|
+
investigation.roots.some(
|
|
239
|
+
(p) => typeof p !== "string" || !p || p.length > 4096,
|
|
240
|
+
) ||
|
|
241
|
+
!Number.isSafeInteger(investigation.timeoutMs) ||
|
|
242
|
+
investigation.timeoutMs < 100 ||
|
|
243
|
+
investigation.timeoutMs > LIMITS.workerMs ||
|
|
244
|
+
!Number.isSafeInteger(investigation.deadlineMs) ||
|
|
245
|
+
investigation.deadlineMs < 0)
|
|
246
|
+
)
|
|
247
|
+
refuse("parse", "invalid-investigation");
|
|
224
248
|
const publicRequest = decodeWorkerPublicRequest(envelope.request);
|
|
225
249
|
const coordinator = conversation?.coordinator === true;
|
|
226
250
|
if (
|
|
@@ -393,7 +417,19 @@ try {
|
|
|
393
417
|
emitter.queue,
|
|
394
418
|
),
|
|
395
419
|
]
|
|
396
|
-
:
|
|
420
|
+
: conversation
|
|
421
|
+
? []
|
|
422
|
+
: researchTools(
|
|
423
|
+
cwd,
|
|
424
|
+
investigation?.roots ?? [cwd],
|
|
425
|
+
investigation ?? {
|
|
426
|
+
timeoutMs: LIMITS.workerMs,
|
|
427
|
+
// Standalone protocol callers without a launcher policy still
|
|
428
|
+
// start at process birth, never at tool construction.
|
|
429
|
+
deadlineMs:
|
|
430
|
+
researchClock() + LIMITS.workerMs - process.uptime() * 1000,
|
|
431
|
+
},
|
|
432
|
+
),
|
|
397
433
|
resourceLoader:
|
|
398
434
|
conversation && !coordinator
|
|
399
435
|
? conversationResources(resourceLoader, cwd, conversation.agentDir)
|
|
@@ -506,11 +542,25 @@ try {
|
|
|
506
542
|
}
|
|
507
543
|
});
|
|
508
544
|
stage = "ready";
|
|
509
|
-
await emitter.emit({
|
|
545
|
+
await emitter.emit({
|
|
546
|
+
kind: "ready",
|
|
547
|
+
requestProtocol: 2,
|
|
548
|
+
runtime: {
|
|
549
|
+
sdkVersion: VERSION,
|
|
550
|
+
workerHash: createHash("sha256")
|
|
551
|
+
.update(readFileSync(new URL(import.meta.url)))
|
|
552
|
+
.digest("hex"),
|
|
553
|
+
},
|
|
554
|
+
});
|
|
510
555
|
await capture.context(publicRequest, session.systemPrompt);
|
|
511
556
|
stage = "prompt";
|
|
512
557
|
const suppliedPrompt = [
|
|
513
558
|
publicRequest.context,
|
|
559
|
+
...(!conversation && kind !== "code"
|
|
560
|
+
? [
|
|
561
|
+
`Investigation roots: ${JSON.stringify(investigation?.roots ?? [cwd])}. Start at these specific paths, not / or their parents. Tools use bounded cooperative reads; no shell is available. Search filenames and shallow directories before content. Do not repeat broad scans or silently exclude backup trees. Total worker deadline: ${investigation?.timeoutMs ?? LIMITS.workerMs}ms, including model and tool time; activity never extends it. Reserve the last portion for a concise final report. On any budget/coverage limit, summarize partial evidence and unresolved questions; never claim exhaustive absence.`,
|
|
562
|
+
]
|
|
563
|
+
: []),
|
|
514
564
|
...publicRequest.handoff.inputs.map(
|
|
515
565
|
(input) =>
|
|
516
566
|
`Dependency ${input.assignmentId} (recorded input):\n${input.text}`,
|
|
@@ -61,7 +61,33 @@ export interface WorkflowProposal {
|
|
|
61
61
|
cwd: string;
|
|
62
62
|
display?: { model: string; branch: string; baseCommit: string };
|
|
63
63
|
}
|
|
64
|
+
export interface WorkflowTiming {
|
|
65
|
+
createdAt: number;
|
|
66
|
+
preparedAt: number | null;
|
|
67
|
+
startedAt: number | null;
|
|
68
|
+
stopRequestedAt: number | null;
|
|
69
|
+
closedAt: number | null;
|
|
70
|
+
settledAt: number | null;
|
|
71
|
+
timeoutMs: number;
|
|
72
|
+
stopReason: string | null;
|
|
73
|
+
}
|
|
74
|
+
export interface WorkflowDiagnostics {
|
|
75
|
+
acceptedAt: number;
|
|
76
|
+
acquiredAt: number | null;
|
|
77
|
+
settledAt: number | null;
|
|
78
|
+
owner: {
|
|
79
|
+
version: string;
|
|
80
|
+
build: string;
|
|
81
|
+
entry: string;
|
|
82
|
+
pid: number;
|
|
83
|
+
node: string;
|
|
84
|
+
platform: string;
|
|
85
|
+
startedAt: number;
|
|
86
|
+
};
|
|
87
|
+
}
|
|
64
88
|
export interface WorkflowStep {
|
|
89
|
+
timing?: WorkflowTiming;
|
|
90
|
+
runtime?: { sdkVersion: string; workerHash: string };
|
|
65
91
|
id: string;
|
|
66
92
|
childRunId?: string;
|
|
67
93
|
kind: "research" | "implementation" | "review" | "check" | "git";
|
|
@@ -77,6 +103,7 @@ export interface WorkflowStep {
|
|
|
77
103
|
truncated: boolean;
|
|
78
104
|
}
|
|
79
105
|
export interface WorkflowRun {
|
|
106
|
+
diagnostics?: WorkflowDiagnostics;
|
|
80
107
|
id: string;
|
|
81
108
|
epoch: string;
|
|
82
109
|
goal: string;
|
|
@@ -105,6 +132,7 @@ export type WorkflowRequest =
|
|
|
105
132
|
action: "research";
|
|
106
133
|
goal: string;
|
|
107
134
|
questions: string[];
|
|
135
|
+
roots?: string[];
|
|
108
136
|
model: ChoiceVersion;
|
|
109
137
|
}
|
|
110
138
|
| { action: "propose"; plan: WorkflowPlan; model: ChoiceVersion }
|
|
@@ -354,15 +382,28 @@ export function decodeWorkflowProposal(v: unknown): WorkflowProposal {
|
|
|
354
382
|
export function decodeWorkflowRequest(v: unknown): WorkflowRequest {
|
|
355
383
|
const action = Object.getOwnPropertyDescriptor(v ?? {}, "action")?.value;
|
|
356
384
|
if (action === "research") {
|
|
357
|
-
const o = closed(v, [
|
|
385
|
+
const o = closed(v, [
|
|
386
|
+
"action",
|
|
387
|
+
"goal",
|
|
388
|
+
"questions",
|
|
389
|
+
"model",
|
|
390
|
+
...(Object.hasOwn(v ?? {}, "roots") ? ["roots"] : []),
|
|
391
|
+
]);
|
|
358
392
|
const questions = list(o.questions, WORKFLOW_LIMITS.parallel, (q) =>
|
|
359
393
|
text(q, 8192, true),
|
|
360
394
|
);
|
|
361
395
|
if (!questions.length) throw new Error("Research needs a question");
|
|
396
|
+
const roots =
|
|
397
|
+
o.roots === undefined
|
|
398
|
+
? undefined
|
|
399
|
+
: list(o.roots, 8, (p) => text(p, 4096, true));
|
|
400
|
+
if (roots && !roots.length)
|
|
401
|
+
throw new Error("Research needs a specific root");
|
|
362
402
|
return {
|
|
363
403
|
action,
|
|
364
404
|
goal: text(o.goal, 8192, true),
|
|
365
405
|
questions,
|
|
406
|
+
...(roots ? { roots } : {}),
|
|
366
407
|
model: decodeChoiceVersion(o.model),
|
|
367
408
|
};
|
|
368
409
|
}
|
|
@@ -403,6 +444,7 @@ export function decodeWorkflowRun(v: unknown): WorkflowRun {
|
|
|
403
444
|
"notice",
|
|
404
445
|
"mergedCommit",
|
|
405
446
|
"humanReviewed",
|
|
447
|
+
...(Object.hasOwn(v ?? {}, "diagnostics") ? ["diagnostics"] : []),
|
|
406
448
|
]);
|
|
407
449
|
const status = (x: unknown) =>
|
|
408
450
|
oneOf(x, [
|
|
@@ -416,6 +458,9 @@ export function decodeWorkflowRun(v: unknown): WorkflowRun {
|
|
|
416
458
|
if (o.humanReviewed !== false)
|
|
417
459
|
throw new Error("Automatic execution is not human review");
|
|
418
460
|
return {
|
|
461
|
+
...(o.diagnostics === undefined
|
|
462
|
+
? {}
|
|
463
|
+
: { diagnostics: decodeWorkflowDiagnostics(o.diagnostics) }),
|
|
419
464
|
id: decodeId(o.id),
|
|
420
465
|
epoch: decodeId(o.epoch),
|
|
421
466
|
goal: text(o.goal, 8192),
|
|
@@ -441,9 +486,25 @@ export function decodeWorkflowRun(v: unknown): WorkflowRun {
|
|
|
441
486
|
"text",
|
|
442
487
|
"exitCode",
|
|
443
488
|
"truncated",
|
|
489
|
+
...(Object.hasOwn(v ?? {}, "timing") ? ["timing"] : []),
|
|
490
|
+
...(Object.hasOwn(v ?? {}, "runtime") ? ["runtime"] : []),
|
|
444
491
|
...(linked ? ["childRunId"] : []),
|
|
445
492
|
]);
|
|
446
493
|
return {
|
|
494
|
+
...(s.timing === undefined
|
|
495
|
+
? {}
|
|
496
|
+
: { timing: decodeWorkflowTiming(s.timing) }),
|
|
497
|
+
...(s.runtime === undefined
|
|
498
|
+
? {}
|
|
499
|
+
: {
|
|
500
|
+
runtime: (() => {
|
|
501
|
+
const r = closed(s.runtime, ["sdkVersion", "workerHash"]);
|
|
502
|
+
return {
|
|
503
|
+
sdkVersion: text(r.sdkVersion, 128, true),
|
|
504
|
+
workerHash: decodeHash(r.workerHash),
|
|
505
|
+
};
|
|
506
|
+
})(),
|
|
507
|
+
}),
|
|
447
508
|
id: text(s.id, 160, true),
|
|
448
509
|
...(linked ? { childRunId: decodeId(s.childRunId) } : {}),
|
|
449
510
|
kind: oneOf(s.kind, [
|
|
@@ -493,3 +554,73 @@ export function readableWorkflowPlan(p: WorkflowPlan): string {
|
|
|
493
554
|
"\n\n",
|
|
494
555
|
)}\n\n## Setup (explicitly authorized commands)\n${p.setup.map((c) => `${c.name}: ${c.command} (${c.timeoutMs}ms)`).join("\n") || "None; no dependency installation or copying."}\n\n## Baseline verification\n${p.baselineChecks.map((c) => `${c.name}: ${c.command} (${c.timeoutMs}ms)`).join("\n") || "No separate baseline checks declared."}\n\n## Verification\n${p.checks.map((c) => `${c.name}: ${c.command} (${c.timeoutMs}ms)`).join("\n")}\n\n## Automation boundary\nAt most ${p.repairAttempts} repair rounds. ${p.delivery === "local-merge" ? "Authorize isolated task worktrees, local task commits and fast-forward integration into the current branch." : "Direct working-copy edits; failures leave actual edits for inspection. No Git commit or merge."} No push, publication, deployment, unplanned installation or recursive delegation. Generated project context and workflow Markdown are included. Worktrees/tools are not a sandbox.\n\n## Project context\n${p.projectContext}\n`;
|
|
495
556
|
}
|
|
557
|
+
|
|
558
|
+
const timestamp = (v: unknown) => integer(v, 0, 8640000000000000);
|
|
559
|
+
function decodeWorkflowTiming(v: unknown): WorkflowTiming {
|
|
560
|
+
const o = closed(v, [
|
|
561
|
+
"createdAt",
|
|
562
|
+
"preparedAt",
|
|
563
|
+
"startedAt",
|
|
564
|
+
"stopRequestedAt",
|
|
565
|
+
"closedAt",
|
|
566
|
+
"settledAt",
|
|
567
|
+
"timeoutMs",
|
|
568
|
+
"stopReason",
|
|
569
|
+
]);
|
|
570
|
+
return {
|
|
571
|
+
createdAt: timestamp(o.createdAt),
|
|
572
|
+
preparedAt: nullable(o.preparedAt, timestamp),
|
|
573
|
+
startedAt: nullable(o.startedAt, timestamp),
|
|
574
|
+
stopRequestedAt: nullable(o.stopRequestedAt, timestamp),
|
|
575
|
+
closedAt: nullable(o.closedAt, timestamp),
|
|
576
|
+
settledAt: nullable(o.settledAt, timestamp),
|
|
577
|
+
timeoutMs: integer(o.timeoutMs, 100, 1200000),
|
|
578
|
+
stopReason: nullable(o.stopReason, (v) => text(v, 32, true)),
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
function decodeWorkflowDiagnostics(v: unknown): WorkflowDiagnostics {
|
|
582
|
+
const o = closed(v, ["acceptedAt", "acquiredAt", "settledAt", "owner"]);
|
|
583
|
+
const r = closed(o.owner, [
|
|
584
|
+
"version",
|
|
585
|
+
"build",
|
|
586
|
+
"entry",
|
|
587
|
+
"pid",
|
|
588
|
+
"node",
|
|
589
|
+
"platform",
|
|
590
|
+
"startedAt",
|
|
591
|
+
]);
|
|
592
|
+
return {
|
|
593
|
+
acceptedAt: timestamp(o.acceptedAt),
|
|
594
|
+
acquiredAt: nullable(o.acquiredAt, timestamp),
|
|
595
|
+
settledAt: nullable(o.settledAt, timestamp),
|
|
596
|
+
owner: {
|
|
597
|
+
version: text(r.version, 128, true),
|
|
598
|
+
build: text(r.build, 64, true),
|
|
599
|
+
entry: text(r.entry, 4096, true),
|
|
600
|
+
pid: integer(r.pid, 1),
|
|
601
|
+
node: text(r.node, 128, true),
|
|
602
|
+
platform: text(r.platform, 32, true),
|
|
603
|
+
startedAt: timestamp(r.startedAt),
|
|
604
|
+
},
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
/** Owner observations, never inferred from a parent's batched tool-result timestamp. */
|
|
608
|
+
export function workflowDiagnostics(run: WorkflowRun): string {
|
|
609
|
+
const d = run.diagnostics;
|
|
610
|
+
if (!d) return "Owner timing/runtime observations not recorded.";
|
|
611
|
+
const at = (v: number | null) =>
|
|
612
|
+
v === null ? "not observed" : new Date(v).toISOString();
|
|
613
|
+
return [
|
|
614
|
+
`Owner: Cadence ${d.owner.version} · ${d.owner.platform} · Node ${d.owner.node} · PID ${d.owner.pid} · epoch ${run.epoch}`,
|
|
615
|
+
`Build: ${d.owner.build} · entry: ${d.owner.entry} · owner started: ${at(d.owner.startedAt)}`,
|
|
616
|
+
`Accepted: ${at(d.acceptedAt)} · checkout acquired: ${at(d.acquiredAt)} · settled: ${at(d.settledAt)}`,
|
|
617
|
+
`Checkout wait: ${d.acquiredAt === null ? "still waiting or not acquired" : `${Math.max(0, d.acquiredAt - d.acceptedAt)}ms`}. Runs share an exclusive checkout; questions within one research run may overlap.`,
|
|
618
|
+
...run.steps.flatMap((s) =>
|
|
619
|
+
s.timing
|
|
620
|
+
? [
|
|
621
|
+
`${s.id}: preparing ${at(s.timing.createdAt)} · prepared ${at(s.timing.preparedAt)} · spawned ${at(s.timing.startedAt)} · stop ${at(s.timing.stopRequestedAt)} (${s.timing.stopReason ?? "none"}) · direct child closed ${at(s.timing.closedAt)} · settled ${at(s.timing.settledAt)} · total process budget ${s.timing.timeoutMs}ms${s.runtime ? ` · worker SDK ${s.runtime.sdkVersion} · worker hash ${s.runtime.workerHash}` : ""}`,
|
|
622
|
+
]
|
|
623
|
+
: [],
|
|
624
|
+
),
|
|
625
|
+
].join("\n");
|
|
626
|
+
}
|