@maheidem/pi-delegate 0.1.1 → 0.1.3
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/README.md +17 -0
- package/application.ts +69 -3
- package/commands.ts +46 -9
- package/config.ts +118 -0
- package/index.ts +31 -6
- package/package.json +1 -1
- package/run-store.ts +20 -7
- package/types.ts +18 -1
package/README.md
CHANGED
|
@@ -42,6 +42,23 @@ is performed by this package.
|
|
|
42
42
|
|
|
43
43
|
Any unrecognized first word is shorthand for `run general …`.
|
|
44
44
|
|
|
45
|
+
### Timeouts
|
|
46
|
+
|
|
47
|
+
Three levels, highest priority first:
|
|
48
|
+
|
|
49
|
+
1. **Per-invocation flag** — `--timeout <90s|10m|2h|1d|ms>` anywhere in the
|
|
50
|
+
task (e.g. `/delegate run general long migration --timeout 2h`). The
|
|
51
|
+
`delegate` tool exposes the same as its optional `timeout` parameter, so
|
|
52
|
+
the parent model can extend the budget when it expects a long subtask.
|
|
53
|
+
Clamped to the configured `hardTimeoutMs` bounds; the inactivity timeout
|
|
54
|
+
scales to at most half of it.
|
|
55
|
+
2. **Project-wide** — `<project>/.pi/delegate/config.json` overlays the user
|
|
56
|
+
config field-by-field (only listed keys override; e.g.
|
|
57
|
+
`{ "hardTimeoutMs": 7200000 }`). A missing or corrupt project file never
|
|
58
|
+
breaks delegations — user values win and corruption is diagnosed.
|
|
59
|
+
3. **User-wide** — `~/.pi/agent/delegate/config.json`
|
|
60
|
+
(`hardTimeoutMs` default 30 min, `inactivityTimeoutMs` default 5 min).
|
|
61
|
+
|
|
45
62
|
Tool (`delegate`) is available to models: same semantics, JSON result with
|
|
46
63
|
`ok`/`handoff`/`details` (usage, paths, state) or structured `error`.
|
|
47
64
|
|
package/application.ts
CHANGED
|
@@ -29,10 +29,14 @@ import type {
|
|
|
29
29
|
RunInspection,
|
|
30
30
|
RunMetadataV1,
|
|
31
31
|
RunnerOutcome,
|
|
32
|
+
TranscriptRecordV1,
|
|
32
33
|
SessionEntryLike,
|
|
33
34
|
} from "./types.ts";
|
|
34
|
-
import {
|
|
35
|
+
import { decodeTranscriptRecord } from "./types.ts";
|
|
36
|
+
import { applyProjectOverlay, clampTimeoutMs, normalizeConfig, saveConfig, type DelegateConfigV1 } from "./config.ts";
|
|
35
37
|
import { EMPTY_USAGE } from "./types.ts";
|
|
38
|
+
|
|
39
|
+
const MIN_INACTIVITY = 1_000;
|
|
36
40
|
import { isRoleName, resolveRole, rolePromptExists, DELEGATE_ROLES } from "./roles.ts";
|
|
37
41
|
import {
|
|
38
42
|
replayModeEntries,
|
|
@@ -180,8 +184,34 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
180
184
|
};
|
|
181
185
|
}
|
|
182
186
|
|
|
183
|
-
const cfg = this.liveConfig;
|
|
184
187
|
const agentDir = this.ports.agentDir;
|
|
188
|
+
// Config cascade: project .pi/delegate/config.json overlays the
|
|
189
|
+
// user-wide (live) config per run; missing file = live config.
|
|
190
|
+
let baseCfg: DelegateConfigV1 = this.liveConfig;
|
|
191
|
+
if (request.projectRoot) {
|
|
192
|
+
// Strip the overlay's diagnostic keys so only real config fields
|
|
193
|
+
// reach the runner (a spurious key would survive into metadata).
|
|
194
|
+
const overlay = applyProjectOverlay(this.liveConfig, request.projectRoot);
|
|
195
|
+
const { projectOverrides, projectCorrupt, ...rest } = overlay as unknown as DelegateConfigV1 & {
|
|
196
|
+
projectOverrides: string[];
|
|
197
|
+
projectCorrupt?: string;
|
|
198
|
+
};
|
|
199
|
+
baseCfg = { ...(rest as unknown as DelegateConfigV1) } as DelegateConfigV1;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// Per-invocation timeout overrides the config-cascade value, clamped
|
|
203
|
+
// to the configured bounds; inactivity scales to match. A per-run
|
|
204
|
+
// copy is used so the override never leaks into later runs.
|
|
205
|
+
const cfg: DelegateConfigV1 = request.timeoutMs !== undefined
|
|
206
|
+
? {
|
|
207
|
+
...baseCfg,
|
|
208
|
+
hardTimeoutMs: clampTimeoutMs(request.timeoutMs),
|
|
209
|
+
inactivityTimeoutMs: Math.min(
|
|
210
|
+
baseCfg.inactivityTimeoutMs,
|
|
211
|
+
Math.max(MIN_INACTIVITY, Math.floor(clampTimeoutMs(request.timeoutMs) / 2)),
|
|
212
|
+
),
|
|
213
|
+
}
|
|
214
|
+
: baseCfg;
|
|
185
215
|
|
|
186
216
|
// 2. Validate task (line endings, blank, byte limit).
|
|
187
217
|
const taskResult = validateTask(request.task, cfg.maxTaskBytes);
|
|
@@ -295,7 +325,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
295
325
|
if (!metadata) throw Object.assign(new Error(`Unknown run id '${id}'.`), { code: "E_RUN_NOT_FOUND" });
|
|
296
326
|
const inspection: RunInspection = { metadata };
|
|
297
327
|
if (includeTranscript) {
|
|
298
|
-
inspection.transcriptPreview =
|
|
328
|
+
inspection.transcriptPreview = transcriptPreview(metadata.transcriptPath, 12000);
|
|
299
329
|
inspection.stderrPreview = boundedPreview(metadata.stderrPath, 4000);
|
|
300
330
|
}
|
|
301
331
|
return inspection;
|
|
@@ -460,6 +490,42 @@ function isTerminal(state: string): boolean {
|
|
|
460
490
|
return ["succeeded", "failed", "cancelled", "timed_out_idle", "timed_out_hard", "crashed"].includes(state);
|
|
461
491
|
}
|
|
462
492
|
|
|
493
|
+
/**
|
|
494
|
+
* Read a transcript envelope back as readable text: decode each record
|
|
495
|
+
* (UTF-8 `raw`, or base64 fallback for non-UTF-8 evidence), bounded.
|
|
496
|
+
*/
|
|
497
|
+
function transcriptPreview(filePath: string, maxChars: number): string {
|
|
498
|
+
try {
|
|
499
|
+
const buf = fs.readFileSync(filePath);
|
|
500
|
+
if (buf.length > 200_000) {
|
|
501
|
+
// Bound the work on huge transcripts: decode the newest records.
|
|
502
|
+
const lines = buf.toString("utf8").split("\n");
|
|
503
|
+
const tail = lines.slice(-Math.max(1, Math.floor(200_000 / 200))).filter((l) => l.trim());
|
|
504
|
+
return decodeTranscriptLines(tail, maxChars, tail.length < lines.filter((l) => l.trim()).length);
|
|
505
|
+
}
|
|
506
|
+
const lines = buf.toString("utf8").split("\n").filter((l) => l.trim());
|
|
507
|
+
return decodeTranscriptLines(lines, maxChars, false);
|
|
508
|
+
} catch {
|
|
509
|
+
return "";
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
function decodeTranscriptLines(lines: string[], maxChars: number, hadMore: boolean): string {
|
|
514
|
+
const decoded = lines
|
|
515
|
+
.map((line) => {
|
|
516
|
+
try {
|
|
517
|
+
const rec = JSON.parse(line) as TranscriptRecordV1;
|
|
518
|
+
return decodeTranscriptRecord(rec);
|
|
519
|
+
} catch {
|
|
520
|
+
return line; // non-envelope line kept verbatim
|
|
521
|
+
}
|
|
522
|
+
})
|
|
523
|
+
.filter((t) => t.length > 0);
|
|
524
|
+
let text = decoded.join("\n");
|
|
525
|
+
if (text.length > maxChars) text = `${text.slice(0, maxChars)}\n… [truncated]`;
|
|
526
|
+
return hadMore ? `… [earlier records omitted]\n${text}` : text;
|
|
527
|
+
}
|
|
528
|
+
|
|
463
529
|
function boundedPreview(filePath: string, maxBytes: number): string {
|
|
464
530
|
try {
|
|
465
531
|
const buf = fs.readFileSync(filePath);
|
package/commands.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
import type { RoleName } from "./types.ts";
|
|
9
9
|
import { ROLE_NAMES } from "./types.ts";
|
|
10
|
+
import { parseDuration } from "./config.ts";
|
|
10
11
|
|
|
11
12
|
export type DelegateIntent =
|
|
12
13
|
| { kind: "dashboard" }
|
|
@@ -18,7 +19,7 @@ export type DelegateIntent =
|
|
|
18
19
|
| { kind: "help" }
|
|
19
20
|
| { kind: "cancel"; runId?: string }
|
|
20
21
|
| { kind: "inspect"; runId?: string }
|
|
21
|
-
| { kind: "run"; role: RoleName; task: string; explicit: boolean }
|
|
22
|
+
| { kind: "run"; role: RoleName; task: string; explicit: boolean; timeoutMs?: number }
|
|
22
23
|
| { kind: "invalid"; token: string; usage: string };
|
|
23
24
|
|
|
24
25
|
export const DELEGATE_USAGE = [
|
|
@@ -33,6 +34,8 @@ export const DELEGATE_USAGE = [
|
|
|
33
34
|
"/delegate run <general|research> <task...> run with an explicit role",
|
|
34
35
|
"/delegate research <task...> research-role shorthand",
|
|
35
36
|
"/delegate <task...> general-role shorthand",
|
|
37
|
+
"flags (run/research/<task>): --timeout <90s|10m|2h|1d|ms>",
|
|
38
|
+
"timeout priority: per-invocation > project .pi/delegate/config.json > user ~/.pi/agent/delegate/config.json",
|
|
36
39
|
"/delegate help this help",
|
|
37
40
|
].join("\n");
|
|
38
41
|
|
|
@@ -62,7 +65,9 @@ export function parseDelegateCommand(input: string, options: ParseOptions = {}):
|
|
|
62
65
|
if (!RESERVED_FIRST_TOKENS.has(first)) {
|
|
63
66
|
// General-role shorthand. `research` is reserved, so a general task
|
|
64
67
|
// that starts with that word must use `run general ...`.
|
|
65
|
-
|
|
68
|
+
const { task, timeoutMs } = extractFlags(trimmed);
|
|
69
|
+
if (!task) return invalid(first);
|
|
70
|
+
return { kind: "run", role: "general", task, explicit: false, timeoutMs };
|
|
66
71
|
}
|
|
67
72
|
|
|
68
73
|
switch (first) {
|
|
@@ -88,21 +93,24 @@ export function parseDelegateCommand(input: string, options: ParseOptions = {}):
|
|
|
88
93
|
}
|
|
89
94
|
case "run": {
|
|
90
95
|
const rest = trimmed.slice("run".length).trim();
|
|
91
|
-
const parts = rest.split(/\s+/);
|
|
92
96
|
if (!rest) return invalid("run");
|
|
97
|
+
const { task, timeoutMs } = extractFlags(rest);
|
|
98
|
+
const parts = task.split(/\s+/);
|
|
93
99
|
const roleToken = parts[0]!;
|
|
94
100
|
if (roleToken === "general" || roleToken === "research") {
|
|
95
|
-
const
|
|
96
|
-
if (!
|
|
97
|
-
return { kind: "run", role: roleToken, task, explicit: true };
|
|
101
|
+
const body = parts.slice(1).join(" ").trim();
|
|
102
|
+
if (!body) return invalid("run");
|
|
103
|
+
return { kind: "run", role: roleToken, task: body, explicit: true, timeoutMs };
|
|
98
104
|
}
|
|
99
105
|
// `run <task...>` — role defaults to general.
|
|
100
|
-
return { kind: "run", role: "general", task
|
|
106
|
+
return { kind: "run", role: "general", task, explicit: true, timeoutMs };
|
|
101
107
|
}
|
|
102
108
|
case "research": {
|
|
103
|
-
const
|
|
109
|
+
const rest = trimmed.slice("research".length).trim();
|
|
110
|
+
if (!rest) return invalid("research");
|
|
111
|
+
const { task, timeoutMs } = extractFlags(rest);
|
|
104
112
|
if (!task) return invalid("research");
|
|
105
|
-
return { kind: "run", role: "research", task, explicit: true };
|
|
113
|
+
return { kind: "run", role: "research", task, explicit: true, timeoutMs };
|
|
106
114
|
}
|
|
107
115
|
}
|
|
108
116
|
return invalid(first);
|
|
@@ -140,6 +148,35 @@ export function delegateCompletions(prefix: string, recentRunIds: string[] = [])
|
|
|
140
148
|
return [...new Set(matches)].slice(0, 10);
|
|
141
149
|
}
|
|
142
150
|
|
|
151
|
+
/**
|
|
152
|
+
* Pull `--timeout <duration>` flags out of a task string (any position).
|
|
153
|
+
* Unknown flags are kept in the task text; a malformed duration yields a
|
|
154
|
+
* stable error message.
|
|
155
|
+
*/
|
|
156
|
+
export function extractFlags(input: string): { task: string; timeoutMs?: number; error?: string } {
|
|
157
|
+
const tokens = input.split(/\s+/).filter(Boolean);
|
|
158
|
+
const kept: string[] = [];
|
|
159
|
+
let timeoutMs: number | undefined;
|
|
160
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
161
|
+
const t = tokens[i]!;
|
|
162
|
+
if (t === "--timeout") {
|
|
163
|
+
const value = tokens[i + 1];
|
|
164
|
+
if (!value) return { task: "", error: "--timeout needs a value (e.g. --timeout 30m)" };
|
|
165
|
+
try {
|
|
166
|
+
const parsed = parseDuration(value);
|
|
167
|
+
if (parsed === undefined) return { task: "", error: "--timeout needs a value (e.g. --timeout 30m)" };
|
|
168
|
+
timeoutMs = parsed;
|
|
169
|
+
i += 1;
|
|
170
|
+
} catch (e) {
|
|
171
|
+
return { task: "", error: (e as Error).message };
|
|
172
|
+
}
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
kept.push(t);
|
|
176
|
+
}
|
|
177
|
+
return { task: kept.join(" "), timeoutMs };
|
|
178
|
+
}
|
|
179
|
+
|
|
143
180
|
/**
|
|
144
181
|
* Validate a raw task: normalize line endings, reject blank input,
|
|
145
182
|
* enforce the UTF-8 byte limit. Returns the normalized task or a stable
|
package/config.ts
CHANGED
|
@@ -176,6 +176,124 @@ export function loadConfig(agentDir: string, configPath?: string): ConfigLoadRes
|
|
|
176
176
|
}
|
|
177
177
|
}
|
|
178
178
|
|
|
179
|
+
/** Clamp a per-invocation timeout into the configured hard-timeout bounds. */
|
|
180
|
+
export function clampTimeoutMs(value: number): number {
|
|
181
|
+
const min = MIN_VALUES.hardTimeoutMs ?? 1_000;
|
|
182
|
+
const max = MAX_VALUES.hardTimeoutMs ?? 604_800_000;
|
|
183
|
+
return Math.min(max, Math.max(min, Math.trunc(value)));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Parse a human duration into milliseconds: "90s", "10m", "2h", "1d",
|
|
188
|
+
* or a bare number (already ms). Returns undefined for empty input;
|
|
189
|
+
* throws for malformed values (callers surface a stable error).
|
|
190
|
+
*/
|
|
191
|
+
export function parseDuration(input: string): number | undefined {
|
|
192
|
+
const text = (input ?? "").trim().toLowerCase();
|
|
193
|
+
if (!text) return undefined;
|
|
194
|
+
const m = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/.exec(text);
|
|
195
|
+
if (m) {
|
|
196
|
+
const value = Number(m[1]);
|
|
197
|
+
const unit = m[2];
|
|
198
|
+
const factor = unit === "ms" ? 1 : unit === "s" ? 1_000 : unit === "m" ? 60_000 : unit === "h" ? 3_600_000 : 86_400_000;
|
|
199
|
+
return Math.round(value * factor);
|
|
200
|
+
}
|
|
201
|
+
if (/^\d+$/.test(text)) return Number(text);
|
|
202
|
+
throw new Error(`invalid duration '${input}' (use e.g. 90s, 10m, 2h, 1d, or bare ms)`);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Project-wide config path for a project root: `<root>/.pi/delegate/config.json`.
|
|
207
|
+
* The project file is an OPTIONAL overlay: only fields present in it override
|
|
208
|
+
* the user-wide config; it is never required to be schema-complete.
|
|
209
|
+
*/
|
|
210
|
+
export function projectConfigPath(projectRoot: string): string {
|
|
211
|
+
return path.join(projectRoot, ".pi", "delegate", "config.json");
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Overlay a project-wide config file onto a base config (the user-wide
|
|
216
|
+
* config in production; the app's live config for injected-config tests).
|
|
217
|
+
* Project file semantics:
|
|
218
|
+
* - missing file → base unchanged (the normal case);
|
|
219
|
+
* - corrupt file → diagnosed via `projectCorrupt`, base still wins
|
|
220
|
+
* (a broken project file must never break delegations);
|
|
221
|
+
* - only keys PRESENT in the project file override (no default backfill);
|
|
222
|
+
* - values are clamped by the same min/max bounds as the user config.
|
|
223
|
+
* Returns a NEW config object; the base is never mutated.
|
|
224
|
+
*/
|
|
225
|
+
export function applyProjectOverlay(
|
|
226
|
+
base: DelegateConfigV1,
|
|
227
|
+
projectRoot: string,
|
|
228
|
+
): DelegateConfigV1 & { projectOverrides: string[]; projectCorrupt?: string } {
|
|
229
|
+
const result: DelegateConfigV1 & { projectOverrides: string[]; projectCorrupt?: string } = {
|
|
230
|
+
...base,
|
|
231
|
+
projectOverrides: [],
|
|
232
|
+
};
|
|
233
|
+
const pPath = projectConfigPath(projectRoot);
|
|
234
|
+
let raw: unknown;
|
|
235
|
+
try {
|
|
236
|
+
raw = JSON.parse(fs.readFileSync(pPath, "utf8"));
|
|
237
|
+
} catch (error) {
|
|
238
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
|
|
239
|
+
result.projectCorrupt = pPath;
|
|
240
|
+
}
|
|
241
|
+
return result;
|
|
242
|
+
}
|
|
243
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return result;
|
|
244
|
+
const record = raw as Record<string, unknown>;
|
|
245
|
+
const known = new Set<string>(Object.keys(DEFAULT_DELEGATE_CONFIG));
|
|
246
|
+
const overrides: string[] = [];
|
|
247
|
+
for (const key of Object.keys(record)) {
|
|
248
|
+
if (key === "schemaVersion") continue;
|
|
249
|
+
if (!knownKey(key)) continue; // unknown keys in project overlay ignored
|
|
250
|
+
try {
|
|
251
|
+
const probe: DelegateConfigV1 = { ...DEFAULT_DELEGATE_CONFIG };
|
|
252
|
+
applyKnownField(probe, key, record[key]);
|
|
253
|
+
const next = probe[key as keyof DelegateConfigV1] as number;
|
|
254
|
+
if (next !== (base[key as keyof DelegateConfigV1] as number)) {
|
|
255
|
+
result[key as keyof DelegateConfigV1] = next as never;
|
|
256
|
+
overrides.push(key);
|
|
257
|
+
}
|
|
258
|
+
} catch {
|
|
259
|
+
// invalid value for one key: skip it, keep base value
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
result.projectOverrides = overrides;
|
|
263
|
+
return result;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function knownKey(key: string): boolean {
|
|
267
|
+
return (Object.keys(DEFAULT_DELEGATE_CONFIG) as string[]).includes(key);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Load the user-wide config, then overlay project-wide values on top.
|
|
272
|
+
* Convenience wrapper over loadConfig + applyProjectOverlay.
|
|
273
|
+
*/
|
|
274
|
+
export function loadConfigCascade(
|
|
275
|
+
agentDir: string,
|
|
276
|
+
projectRoot?: string,
|
|
277
|
+
configPath?: string,
|
|
278
|
+
): ConfigLoadResult & { projectOverrides: string[]; projectCorrupt?: string } {
|
|
279
|
+
const base = loadConfig(agentDir, configPath);
|
|
280
|
+
if (!projectRoot) {
|
|
281
|
+
return { ...base, projectOverrides: [] };
|
|
282
|
+
}
|
|
283
|
+
const overlay = applyProjectOverlay(base.config, projectRoot);
|
|
284
|
+
const { projectOverrides, projectCorrupt, ...rest } = overlay as unknown as DelegateConfigV1 & {
|
|
285
|
+
projectOverrides: string[];
|
|
286
|
+
projectCorrupt?: string;
|
|
287
|
+
};
|
|
288
|
+
const config: DelegateConfigV1 = { ...(rest as unknown as DelegateConfigV1) };
|
|
289
|
+
return {
|
|
290
|
+
...base,
|
|
291
|
+
config,
|
|
292
|
+
projectOverrides: overlay.projectOverrides,
|
|
293
|
+
projectCorrupt: overlay.projectCorrupt,
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
|
|
179
297
|
/**
|
|
180
298
|
* Persist config: temp file + fsync + close + rename inside the same
|
|
181
299
|
* directory, mode 0600. Unknown future keys carried in `extraKeys` are
|
package/index.ts
CHANGED
|
@@ -21,7 +21,7 @@ import {
|
|
|
21
21
|
} from "@earendil-works/pi-coding-agent";
|
|
22
22
|
import { Text } from "@earendil-works/pi-tui";
|
|
23
23
|
|
|
24
|
-
import { loadConfig, saveConfig } from "./config.ts";
|
|
24
|
+
import { loadConfig, parseDuration, saveConfig } from "./config.ts";
|
|
25
25
|
import { parseDelegateCommand, delegateCompletions, type DelegateIntent } from "./commands.ts";
|
|
26
26
|
import { DELEGATE_ROLES, isRoleName, resolveRole } from "./roles.ts";
|
|
27
27
|
import { STRICT_OVERLAY, syncStrictToolSet, resetBlockedCounters } from "./mode.ts";
|
|
@@ -162,7 +162,13 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
162
162
|
}
|
|
163
163
|
};
|
|
164
164
|
|
|
165
|
-
const buildRequest = (
|
|
165
|
+
const buildRequest = (
|
|
166
|
+
task: string,
|
|
167
|
+
role: "general" | "research",
|
|
168
|
+
source: "tool" | "command",
|
|
169
|
+
ctx: ExtensionContext,
|
|
170
|
+
timeoutMs?: number,
|
|
171
|
+
): DelegateRequest => ({
|
|
166
172
|
task,
|
|
167
173
|
role,
|
|
168
174
|
source,
|
|
@@ -170,6 +176,8 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
170
176
|
parentModel: modelString(ctx),
|
|
171
177
|
thinkingLevel: thinkingOf(ctx),
|
|
172
178
|
projectTrusted: ctx.isProjectTrusted(),
|
|
179
|
+
projectRoot: ctx.cwd ?? process.cwd(),
|
|
180
|
+
...(timeoutMs !== undefined ? { timeoutMs } : {}),
|
|
173
181
|
});
|
|
174
182
|
|
|
175
183
|
const refreshDoctor = (ctx: ExtensionContext) => {
|
|
@@ -257,6 +265,11 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
257
265
|
const DelegateParams = Type.Object({
|
|
258
266
|
task: Type.String({ minLength: 1 }),
|
|
259
267
|
role: Type.Optional(Type.Union([Type.Literal("general"), Type.Literal("research")])),
|
|
268
|
+
timeout: Type.Optional(Type.String({
|
|
269
|
+
description:
|
|
270
|
+
"Optional per-run hard timeout, e.g. '90s', '10m', '2h', '1d' or bare ms. " +
|
|
271
|
+
"Use it when the subtask is expected to run longer than the configured default; it overrides the project/user config base.",
|
|
272
|
+
})),
|
|
260
273
|
});
|
|
261
274
|
|
|
262
275
|
pi.registerTool({
|
|
@@ -276,7 +289,19 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
276
289
|
parameters: DelegateParams,
|
|
277
290
|
async execute(_toolCallId, params, signal, onUpdate, ctx) {
|
|
278
291
|
// Strict mode invariant also holds here: only delegate runs anyway.
|
|
279
|
-
|
|
292
|
+
let timeoutMs: number | undefined;
|
|
293
|
+
if (typeof params.timeout === "string" && params.timeout.trim()) {
|
|
294
|
+
try {
|
|
295
|
+
timeoutMs = parseDuration(params.timeout);
|
|
296
|
+
} catch (error) {
|
|
297
|
+
return {
|
|
298
|
+
content: [{ type: "text" as const, text: (error as Error).message }],
|
|
299
|
+
details: {} satisfies Record<string, unknown>,
|
|
300
|
+
isError: true,
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
const request = buildRequest(params.task, params.role ?? config.defaultRole, "tool", ctx, timeoutMs);
|
|
280
305
|
refreshDoctor(ctx);
|
|
281
306
|
const hooks = {
|
|
282
307
|
abortSignal: signal ?? undefined,
|
|
@@ -368,8 +393,8 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
368
393
|
}
|
|
369
394
|
};
|
|
370
395
|
|
|
371
|
-
const runCommandForeground = async (task: string, role: "general" | "research", ctx: ExtensionCommandContext): Promise<void> => {
|
|
372
|
-
const request = buildRequest(task, role, "command", ctx);
|
|
396
|
+
const runCommandForeground = async (task: string, role: "general" | "research", ctx: ExtensionCommandContext, timeoutMs?: number): Promise<void> => {
|
|
397
|
+
const request = buildRequest(task, role, "command", ctx, timeoutMs);
|
|
373
398
|
refreshDoctor(ctx);
|
|
374
399
|
let lastText = `[delegate] starting ${role} run…`;
|
|
375
400
|
const hooks = {
|
|
@@ -556,7 +581,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
556
581
|
say(ctx, `[delegate] invalid role '${intent.role}'. Use general or research.`, "error");
|
|
557
582
|
return;
|
|
558
583
|
}
|
|
559
|
-
await runCommandForeground(intent.task, intent.role, ctx);
|
|
584
|
+
await runCommandForeground(intent.task, intent.role, ctx, intent.timeoutMs);
|
|
560
585
|
return;
|
|
561
586
|
case "invalid":
|
|
562
587
|
say(ctx, `[delegate] unrecognized '${intent.token}'.\n${intent.usage}\n${helpText()}`, "error");
|
package/package.json
CHANGED
package/run-store.ts
CHANGED
|
@@ -128,13 +128,26 @@ export function appendTranscriptRecord(
|
|
|
128
128
|
receivedAt: string,
|
|
129
129
|
rawBytes: Buffer,
|
|
130
130
|
): void {
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
131
|
+
let record: TranscriptRecordV1;
|
|
132
|
+
try {
|
|
133
|
+
// Normal case: the child emits valid UTF-8 JSON — keep it readable.
|
|
134
|
+
record = {
|
|
135
|
+
schemaVersion: 1,
|
|
136
|
+
sequence,
|
|
137
|
+
receivedAt,
|
|
138
|
+
stream: "stdout",
|
|
139
|
+
raw: new TextDecoder("utf-8", { fatal: true }).decode(rawBytes),
|
|
140
|
+
};
|
|
141
|
+
} catch {
|
|
142
|
+
// Non-UTF-8 evidence is preserved verbatim, never dropped.
|
|
143
|
+
record = {
|
|
144
|
+
schemaVersion: 1,
|
|
145
|
+
sequence,
|
|
146
|
+
receivedAt,
|
|
147
|
+
stream: "stdout",
|
|
148
|
+
rawBase64: rawBytes.toString("base64"),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
138
151
|
const line = JSON.stringify(record) + "\n";
|
|
139
152
|
const fd = (stdoutStream as unknown as { fd: number | null }).fd;
|
|
140
153
|
if (typeof fd === "number") {
|
package/types.ts
CHANGED
|
@@ -94,6 +94,9 @@ export const EMPTY_USAGE: DelegateUsage = {
|
|
|
94
94
|
|
|
95
95
|
export type RunSource = "tool" | "command";
|
|
96
96
|
|
|
97
|
+
/** Project-wide config path: `<projectRoot>/.pi/delegate/config.json`. */
|
|
98
|
+
export const PROJECT_DELEGATE_CONFIG_REL = ".pi/delegate/config.json";
|
|
99
|
+
|
|
97
100
|
export interface DelegateRequest {
|
|
98
101
|
task: string;
|
|
99
102
|
role: RoleName;
|
|
@@ -105,6 +108,10 @@ export interface DelegateRequest {
|
|
|
105
108
|
/** Parent thinking level, when available. */
|
|
106
109
|
thinkingLevel?: string;
|
|
107
110
|
projectTrusted: boolean;
|
|
111
|
+
/** Per-invocation hard timeout (ms); overrides the config cascade. */
|
|
112
|
+
timeoutMs?: number;
|
|
113
|
+
/** Project root for the project-wide config overlay (optional). */
|
|
114
|
+
projectRoot?: string;
|
|
108
115
|
}
|
|
109
116
|
|
|
110
117
|
/** Bounded, parent-visible tool result details (schema v1). */
|
|
@@ -195,7 +202,17 @@ export interface TranscriptRecordV1 {
|
|
|
195
202
|
sequence: number;
|
|
196
203
|
receivedAt: string;
|
|
197
204
|
stream: "stdout";
|
|
198
|
-
|
|
205
|
+
/** UTF-8 text of the raw record (the normal case — readable). */
|
|
206
|
+
raw?: string;
|
|
207
|
+
/** Base64 fallback when the bytes are not valid UTF-8. */
|
|
208
|
+
rawBase64?: string;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Decode a captured transcript record back to its original text. */
|
|
212
|
+
export function decodeTranscriptRecord(record: TranscriptRecordV1): string {
|
|
213
|
+
if (typeof record.raw === "string") return record.raw;
|
|
214
|
+
if (typeof record.rawBase64 === "string") return Buffer.from(record.rawBase64, "base64").toString("utf8");
|
|
215
|
+
return "";
|
|
199
216
|
}
|
|
200
217
|
|
|
201
218
|
export interface DelegatePaths {
|