@xzzpig/pi-subagents 0.1.0 → 0.3.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.
- package/CHANGELOG.md +135 -0
- package/README.md +4 -0
- package/agents/reviewer.md +3 -4
- package/docs/agents.md +343 -0
- package/docs/configuration.md +395 -0
- package/docs/extension-api.md +308 -0
- package/docs/missions.md +121 -0
- package/docs/models.md +192 -0
- package/docs/observability.md +198 -0
- package/docs/tool-reference.md +343 -0
- package/docs/watchdog.md +176 -0
- package/docs/workflows.md +163 -0
- package/package.json +13 -11
- package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
- package/skills/pi-subagents/references/execution-controls.md +7 -7
- package/skills/pi-subagents/references/management-authoring-rpc.md +1 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +1 -1
- package/src/agents/agents.ts +53 -23
- package/src/agents/frontmatter.ts +7 -3
- package/src/agents/skills.ts +2 -9
- package/src/api/preflight.ts +1 -1
- package/src/api/project-panes.ts +30 -0
- package/src/extension/config.ts +54 -1
- package/src/extension/doctor.ts +40 -0
- package/src/extension/fanout-child.ts +5 -4
- package/src/extension/index.ts +114 -38
- package/src/extension/public-execution.ts +35 -4
- package/src/extension/rpc.ts +10 -15
- package/src/extension/schemas.ts +33 -11
- package/src/extension/subagent-guide.ts +39 -0
- package/src/extension/tool-description.ts +38 -18
- package/src/inspectors/herdr/actions.ts +11 -2
- package/src/inspectors/herdr/inspector-runner.ts +16 -3
- package/src/inspectors/herdr/project-panes.ts +459 -63
- package/src/intercom/intercom-bridge.ts +7 -2
- package/src/intercom/native-supervisor-channel.ts +102 -4
- package/src/missions/actions.ts +25 -2
- package/src/missions/lifecycle.ts +25 -9
- package/src/missions/store.ts +89 -7
- package/src/missions/types.ts +33 -0
- package/src/missions/workflow-state.ts +25 -15
- package/src/runs/background/active-async-capacity.ts +431 -0
- package/src/runs/background/active-run-index.ts +46 -0
- package/src/runs/background/async-execution.ts +158 -71
- package/src/runs/background/async-job-tracker.ts +297 -133
- package/src/runs/background/async-resume.ts +37 -5
- package/src/runs/background/async-status.ts +39 -5
- package/src/runs/background/chain-append.ts +33 -15
- package/src/runs/background/completion-replay.ts +267 -0
- package/src/runs/background/control-channel.ts +95 -54
- package/src/runs/background/fleet-view.ts +18 -5
- package/src/runs/background/owned-process-tree.ts +104 -0
- package/src/runs/background/process-terminal.ts +17 -3
- package/src/runs/background/result-watcher.ts +113 -10
- package/src/runs/background/resume-guidance.ts +53 -0
- package/src/runs/background/retained-children.ts +14 -6
- package/src/runs/background/run-status.ts +119 -5
- package/src/runs/background/scheduled-runs.ts +25 -1
- package/src/runs/background/stale-run-reconciler.ts +12 -24
- package/src/runs/background/subagent-runner.ts +127 -41
- package/src/runs/background/subagent-wait.ts +5 -2
- package/src/runs/background/wait-completions.ts +39 -5
- package/src/runs/background/wait-subscriptions.ts +21 -5
- package/src/runs/foreground/async-dismiss-action.ts +85 -0
- package/src/runs/foreground/async-steering-action.ts +7 -8
- package/src/runs/foreground/chain-execution.ts +40 -2
- package/src/runs/foreground/execution.ts +97 -19
- package/src/runs/foreground/foreground-control.ts +12 -0
- package/src/runs/foreground/foreground-history.ts +137 -0
- package/src/runs/foreground/prompt-audit.ts +172 -0
- package/src/runs/foreground/subagent-executor.ts +1274 -243
- package/src/runs/foreground/workflow-foreground-steering.ts +187 -0
- package/src/runs/shared/acceptance.ts +13 -4
- package/src/runs/shared/completion-guard.ts +17 -1
- package/src/runs/shared/dynamic-fanout.ts +1 -1
- package/src/runs/shared/llm-intent-arbiter.ts +302 -0
- package/src/runs/shared/model-fallback.ts +8 -4
- package/src/runs/shared/model-scope.ts +12 -2
- package/src/runs/shared/parallel-utils.ts +3 -0
- package/src/runs/shared/pi-args.ts +44 -1
- package/src/runs/shared/run-fanout-budget.ts +280 -0
- package/src/runs/shared/single-output.ts +4 -2
- package/src/runs/shared/subagent-prompt-runtime.ts +94 -9
- package/src/runs/shared/task-intent.ts +19 -3
- package/src/runs/shared/worktree.ts +20 -7
- package/src/shared/agent-stream-options.ts +5 -0
- package/src/shared/artifacts.ts +17 -21
- package/src/shared/display-text.ts +150 -0
- package/src/shared/file-coalescer.ts +9 -0
- package/src/shared/fork-context.ts +13 -0
- package/src/shared/formatters.ts +4 -6
- package/src/shared/node-executable.ts +21 -0
- package/src/shared/prompt-resources.ts +51 -0
- package/src/shared/settings.ts +15 -2
- package/src/shared/types.ts +158 -4
- package/src/shared/utf8.ts +11 -0
- package/src/shared/utils.ts +46 -34
- package/src/slash/prompt-workflows.ts +2 -15
- package/src/slash/slash-commands.ts +22 -2
- package/src/tui/fleet-status.ts +29 -17
- package/src/tui/fleet-transcript.ts +1 -48
- package/src/tui/fleet.ts +362 -37
- package/src/tui/render.ts +235 -71
- package/src/watchdog/change-signature.ts +4 -3
- package/src/watchdog/permission-arbiter.ts +2 -1
- package/src/watchdog/review.ts +4 -3
- package/src/workflows/chat-progress.ts +8 -2
- package/src/workflows/scripted-workflow.ts +273 -20
|
@@ -3,6 +3,8 @@ import * as fs from "node:fs";
|
|
|
3
3
|
import * as os from "node:os";
|
|
4
4
|
import * as path from "node:path";
|
|
5
5
|
import { resolveAuthorityDecision, type AuthorityPolicyConfig } from "../../policy/authority.ts";
|
|
6
|
+
import { PROJECT_SUBAGENTS_RELATIVE_DIR } from "../../shared/artifacts.ts";
|
|
7
|
+
import { getAgentDir } from "../../shared/utils.ts";
|
|
6
8
|
|
|
7
9
|
export interface WorktreeSetup {
|
|
8
10
|
cwd: string;
|
|
@@ -135,9 +137,9 @@ function resolveRepoState(cwd: string): RepoState {
|
|
|
135
137
|
const cwdRelative = resolveRepoCwdRelative(cwd);
|
|
136
138
|
const toplevel = runGitChecked(cwd, ["rev-parse", "--show-toplevel"]).trim();
|
|
137
139
|
|
|
138
|
-
// pi-subagents writes durable runtime state under .pi
|
|
140
|
+
// pi-subagents writes durable runtime state under .pi/subagents/ by default;
|
|
139
141
|
// that state must not make managed isolation unusable for later runs.
|
|
140
|
-
const status = runGitChecked(toplevel, ["status", "--porcelain", "--",
|
|
142
|
+
const status = runGitChecked(toplevel, ["status", "--porcelain", "--", `:!${PROJECT_SUBAGENTS_RELATIVE_DIR}`]);
|
|
141
143
|
if (status.trim().length > 0) {
|
|
142
144
|
throw new Error("worktree isolation requires a clean git working tree. Commit or stash changes first.");
|
|
143
145
|
}
|
|
@@ -148,11 +150,17 @@ function resolveRepoState(cwd: string): RepoState {
|
|
|
148
150
|
|
|
149
151
|
function normalizeComparableCwd(cwd: string): string {
|
|
150
152
|
const resolved = path.resolve(cwd);
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
153
|
+
let existing = resolved;
|
|
154
|
+
const missingSegments: string[] = [];
|
|
155
|
+
while (true) {
|
|
156
|
+
try {
|
|
157
|
+
return path.join(fs.realpathSync(existing), ...missingSegments.reverse());
|
|
158
|
+
} catch {
|
|
159
|
+
const parent = path.dirname(existing);
|
|
160
|
+
if (parent === existing) return resolved;
|
|
161
|
+
missingSegments.push(path.basename(existing));
|
|
162
|
+
existing = parent;
|
|
163
|
+
}
|
|
156
164
|
}
|
|
157
165
|
}
|
|
158
166
|
|
|
@@ -195,6 +203,11 @@ function resolveWorktreeBaseDir(configuredBaseDir: string | undefined, repoRoot:
|
|
|
195
203
|
|
|
196
204
|
const expanded = trimmed.startsWith("~/") ? path.join(os.homedir(), trimmed.slice(2)) : trimmed;
|
|
197
205
|
const resolved = path.isAbsolute(expanded) ? expanded : path.resolve(repoRoot, expanded);
|
|
206
|
+
const extensionsDir = normalizeComparableCwd(path.join(getAgentDir(), "extensions"));
|
|
207
|
+
const relativeToExtensions = path.relative(extensionsDir, normalizeComparableCwd(resolved));
|
|
208
|
+
if (!relativeToExtensions || (!relativeToExtensions.startsWith(`..${path.sep}`) && relativeToExtensions !== ".." && !path.isAbsolute(relativeToExtensions))) {
|
|
209
|
+
throw new Error(`worktree base directory cannot be inside Pi extensions directory: ${extensionsDir}. Choose a directory outside it.`);
|
|
210
|
+
}
|
|
198
211
|
try {
|
|
199
212
|
fs.mkdirSync(resolved, { recursive: true });
|
|
200
213
|
} catch (error) {
|
package/src/shared/artifacts.ts
CHANGED
|
@@ -3,19 +3,19 @@ import * as path from "node:path";
|
|
|
3
3
|
import { CHAIN_RUNS_DIR, TEMP_ARTIFACTS_DIR, type ArtifactPaths, type ArtifactDirPreference } from "./types.ts";
|
|
4
4
|
import { getAgentDir } from "./utils.ts";
|
|
5
5
|
const CLEANUP_MARKER_FILE = ".last-cleanup";
|
|
6
|
-
const
|
|
6
|
+
export const PROJECT_SUBAGENTS_RELATIVE_DIR = ".pi/subagents";
|
|
7
7
|
|
|
8
8
|
const PROJECT_ARTIFACT_PATHS = [
|
|
9
|
-
`${
|
|
10
|
-
`${
|
|
11
|
-
`${
|
|
12
|
-
`${
|
|
13
|
-
`${
|
|
14
|
-
`${
|
|
15
|
-
`${
|
|
16
|
-
`${
|
|
17
|
-
`${
|
|
18
|
-
`${
|
|
9
|
+
`${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/output.md`,
|
|
10
|
+
`${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/run_worker_input.md`,
|
|
11
|
+
`${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/run_worker_output.md`,
|
|
12
|
+
`${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/run_worker.jsonl`,
|
|
13
|
+
`${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/run_worker_transcript.jsonl`,
|
|
14
|
+
`${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/run_worker_meta.json`,
|
|
15
|
+
`${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/progress/run/progress.md`,
|
|
16
|
+
`${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/outputs/output.md`,
|
|
17
|
+
`${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/outputs/run/output.md`,
|
|
18
|
+
`${PROJECT_SUBAGENTS_RELATIVE_DIR}/chain-runs/run.json`,
|
|
19
19
|
];
|
|
20
20
|
|
|
21
21
|
function globMatchesPath(pattern: string, filePath: string): boolean {
|
|
@@ -59,16 +59,12 @@ function normalizePattern(pattern: string): string {
|
|
|
59
59
|
|
|
60
60
|
function patternMatchesArtifactPath(pattern: string, artifactPath: string): boolean {
|
|
61
61
|
const normalized = normalizePattern(pattern);
|
|
62
|
-
return normalized ===
|
|
62
|
+
return normalized === PROJECT_SUBAGENTS_RELATIVE_DIR
|
|
63
63
|
|| normalized === "*"
|
|
64
64
|
|| artifactPath.startsWith(`${normalized}/`)
|
|
65
65
|
|| globMatchesPath(normalized, artifactPath);
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
-
function patternMatchesProjectArtifacts(pattern: string): boolean {
|
|
69
|
-
return PROJECT_ARTIFACT_PATHS.some((artifactPath) => patternMatchesArtifactPath(pattern, artifactPath));
|
|
70
|
-
}
|
|
71
|
-
|
|
72
68
|
function ignoreFileExcludesProjectArtifacts(filePath: string): boolean {
|
|
73
69
|
if (!fs.existsSync(filePath)) return false;
|
|
74
70
|
try {
|
|
@@ -127,11 +123,11 @@ export function getProjectArtifactPackagingWarning(cwd: string): string | undefi
|
|
|
127
123
|
const ignorePath = fs.existsSync(npmIgnorePath) ? npmIgnorePath : path.join(cwd, ".gitignore");
|
|
128
124
|
if (filesIncludeArtifacts === undefined && ignoreFileExcludesProjectArtifacts(ignorePath)) return undefined;
|
|
129
125
|
|
|
130
|
-
return "Project-scoped subagent artifacts can be included when this package is published. Add '.pi
|
|
126
|
+
return "Project-scoped subagent artifacts can be included when this package is published. Add '.pi/subagents/' to .npmignore, restrict package.json files, or set artifactDir to 'session' or 'temp'.";
|
|
131
127
|
}
|
|
132
128
|
|
|
133
129
|
export function getProjectSubagentsDir(cwd: string): string {
|
|
134
|
-
return path.join(cwd,
|
|
130
|
+
return path.join(cwd, PROJECT_SUBAGENTS_RELATIVE_DIR);
|
|
135
131
|
}
|
|
136
132
|
|
|
137
133
|
export function getProjectArtifactsDir(cwd: string): string {
|
|
@@ -144,7 +140,7 @@ export function getProjectChainRunsDir(cwd: string): string {
|
|
|
144
140
|
|
|
145
141
|
export function getChainRunsDir(
|
|
146
142
|
projectCwd: string,
|
|
147
|
-
dirPreference: ArtifactDirPreference = "
|
|
143
|
+
dirPreference: ArtifactDirPreference = "session",
|
|
148
144
|
): string {
|
|
149
145
|
switch (dirPreference) {
|
|
150
146
|
case "project":
|
|
@@ -160,7 +156,7 @@ export function getChainRunsDir(
|
|
|
160
156
|
export function getArtifactsDir(
|
|
161
157
|
sessionFile: string | null,
|
|
162
158
|
projectCwd?: string,
|
|
163
|
-
dirPreference: ArtifactDirPreference = "
|
|
159
|
+
dirPreference: ArtifactDirPreference = "session",
|
|
164
160
|
): string {
|
|
165
161
|
switch (dirPreference) {
|
|
166
162
|
case "session":
|
|
@@ -228,7 +224,7 @@ export function appendJsonl(filePath: string, line: string): void {
|
|
|
228
224
|
}
|
|
229
225
|
|
|
230
226
|
export function cleanupOldArtifacts(dir: string, maxAgeDays: number): void {
|
|
231
|
-
if (!fs.existsSync(dir)) return;
|
|
227
|
+
if (maxAgeDays <= 0 || !fs.existsSync(dir)) return;
|
|
232
228
|
|
|
233
229
|
const markerPath = path.join(dir, CLEANUP_MARKER_FILE);
|
|
234
230
|
const now = Date.now();
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
function codePointWidth(codePoint: number): 1 | 2 {
|
|
2
|
+
return codePoint > 0xffff ? 2 : 1;
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
function isWhitespaceOrControl(codePoint: number): boolean {
|
|
6
|
+
if (codePoint <= 0x20 || (codePoint >= 0x7f && codePoint <= 0x9f)) return true;
|
|
7
|
+
if (codePoint >= 0xd800 && codePoint <= 0xdfff) return true;
|
|
8
|
+
return String.fromCodePoint(codePoint).trim().length === 0;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function consumeControlString(value: string, index: number, osc: boolean): number {
|
|
12
|
+
while (index < value.length) {
|
|
13
|
+
const codePoint = value.codePointAt(index)!;
|
|
14
|
+
const width = codePointWidth(codePoint);
|
|
15
|
+
if (osc && codePoint === 0x07) return index + width;
|
|
16
|
+
if (codePoint === 0x9c) return index + width;
|
|
17
|
+
if (codePoint === 0x1b && value.charCodeAt(index + 1) === 0x5c) return index + 2;
|
|
18
|
+
index += width;
|
|
19
|
+
}
|
|
20
|
+
return value.length;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function consumeCsi(value: string, index: number): number {
|
|
24
|
+
while (index < value.length) {
|
|
25
|
+
const codePoint = value.codePointAt(index)!;
|
|
26
|
+
const width = codePointWidth(codePoint);
|
|
27
|
+
if (codePoint >= 0x40 && codePoint <= 0x7e) return index + width;
|
|
28
|
+
index += width;
|
|
29
|
+
}
|
|
30
|
+
return value.length;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function sanitizeDisplayText(value: string): string {
|
|
34
|
+
const output: string[] = [];
|
|
35
|
+
let pendingSpace = false;
|
|
36
|
+
|
|
37
|
+
const appendSpace = (): void => {
|
|
38
|
+
if (output.length > 0) pendingSpace = true;
|
|
39
|
+
};
|
|
40
|
+
const appendText = (text: string): void => {
|
|
41
|
+
if (pendingSpace) output.push(" ");
|
|
42
|
+
output.push(text);
|
|
43
|
+
pendingSpace = false;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
for (let index = 0; index < value.length;) {
|
|
47
|
+
const codePoint = value.codePointAt(index)!;
|
|
48
|
+
const width = codePointWidth(codePoint);
|
|
49
|
+
|
|
50
|
+
if (codePoint === 0x1b) {
|
|
51
|
+
const next = value.charCodeAt(index + 1);
|
|
52
|
+
appendSpace();
|
|
53
|
+
if (next === 0x5b) {
|
|
54
|
+
index = consumeCsi(value, index + 2);
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (next === 0x5d || next === 0x50 || next === 0x58 || next === 0x5e || next === 0x5f) {
|
|
58
|
+
index = consumeControlString(value, index + 2, next === 0x5d);
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
index += next ? 2 : 1;
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (codePoint === 0x9b) {
|
|
66
|
+
appendSpace();
|
|
67
|
+
index = consumeCsi(value, index + width);
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (codePoint === 0x90 || codePoint === 0x98 || codePoint === 0x9d || codePoint === 0x9e || codePoint === 0x9f) {
|
|
71
|
+
appendSpace();
|
|
72
|
+
index = consumeControlString(value, index + width, codePoint === 0x9d);
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (isWhitespaceOrControl(codePoint)) appendSpace();
|
|
77
|
+
else appendText(String.fromCodePoint(codePoint));
|
|
78
|
+
index += width;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return output.join("");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function truncateDisplayText(value: string, maxLength: number): string {
|
|
85
|
+
if (maxLength <= 0) return "";
|
|
86
|
+
if (value.length <= maxLength) return value;
|
|
87
|
+
let output = "";
|
|
88
|
+
for (const char of value) {
|
|
89
|
+
if (output.length + char.length > maxLength) break;
|
|
90
|
+
output += char;
|
|
91
|
+
}
|
|
92
|
+
return output;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function previewDisplayText(value: string, maxLength: number): string {
|
|
96
|
+
const normalized = sanitizeDisplayText(value);
|
|
97
|
+
if (normalized.length <= maxLength) return normalized;
|
|
98
|
+
if (maxLength <= 3) return truncateDisplayText(normalized, maxLength);
|
|
99
|
+
return `${truncateDisplayText(normalized, maxLength - 3)}...`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const BINARY_CONTENT_PLACEHOLDER = "[binary content omitted for safe display]";
|
|
103
|
+
|
|
104
|
+
function isUnsafeTerminalCodePoint(codePoint: number): boolean {
|
|
105
|
+
const terminalControl = (codePoint <= 0x1f && codePoint !== 0x09 && codePoint !== 0x0a)
|
|
106
|
+
|| (codePoint >= 0x7f && codePoint <= 0x9f);
|
|
107
|
+
const bidiControl = codePoint === 0x061c
|
|
108
|
+
|| codePoint === 0x200e
|
|
109
|
+
|| codePoint === 0x200f
|
|
110
|
+
|| (codePoint >= 0x202a && codePoint <= 0x202e)
|
|
111
|
+
|| (codePoint >= 0x2066 && codePoint <= 0x2069);
|
|
112
|
+
const privateUse = (codePoint >= 0xe000 && codePoint <= 0xf8ff)
|
|
113
|
+
|| (codePoint >= 0xf0000 && codePoint <= 0xffffd)
|
|
114
|
+
|| (codePoint >= 0x100000 && codePoint <= 0x10fffd);
|
|
115
|
+
const invalidScalar = codePoint >= 0xd800 && codePoint <= 0xdfff;
|
|
116
|
+
const nonCharacter = (codePoint >= 0xfdd0 && codePoint <= 0xfdef)
|
|
117
|
+
|| (codePoint & 0xffff) === 0xfffe
|
|
118
|
+
|| (codePoint & 0xffff) === 0xffff;
|
|
119
|
+
return terminalControl || bidiControl || privateUse || invalidScalar || nonCharacter;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function looksLikeBinaryContent(text: string): boolean {
|
|
123
|
+
if (text.includes("\0")) return true;
|
|
124
|
+
let suspiciousControls = 0;
|
|
125
|
+
let replacementCharacters = 0;
|
|
126
|
+
let codePoints = 0;
|
|
127
|
+
for (const character of text) {
|
|
128
|
+
codePoints++;
|
|
129
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
130
|
+
if ((codePoint <= 0x08) || (codePoint >= 0x0e && codePoint <= 0x1f)) suspiciousControls++;
|
|
131
|
+
if (codePoint === 0xfffd) replacementCharacters++;
|
|
132
|
+
}
|
|
133
|
+
if (codePoints === 0) return false;
|
|
134
|
+
return (suspiciousControls >= 4 && suspiciousControls / codePoints >= 0.1)
|
|
135
|
+
|| (replacementCharacters >= 3 && replacementCharacters / codePoints >= 0.1);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Escapes untrusted text before rendering it in a terminal while preserving safe newlines and tabs. */
|
|
139
|
+
export function safeTerminalText(value: string): string {
|
|
140
|
+
const normalized = value.replace(/\r\n/g, "\n");
|
|
141
|
+
if (looksLikeBinaryContent(normalized)) return BINARY_CONTENT_PLACEHOLDER;
|
|
142
|
+
let safe = "";
|
|
143
|
+
for (const character of normalized) {
|
|
144
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
145
|
+
safe += isUnsafeTerminalCodePoint(codePoint)
|
|
146
|
+
? `[U+${codePoint.toString(16).toUpperCase().padStart(4, "0")}]`
|
|
147
|
+
: character;
|
|
148
|
+
}
|
|
149
|
+
return safe;
|
|
150
|
+
}
|
|
@@ -5,6 +5,7 @@ interface TimerApi {
|
|
|
5
5
|
|
|
6
6
|
interface FileCoalescer {
|
|
7
7
|
schedule(file: string, delayMs?: number): boolean;
|
|
8
|
+
flush(file: string): boolean;
|
|
8
9
|
clear(): void;
|
|
9
10
|
}
|
|
10
11
|
|
|
@@ -30,6 +31,14 @@ export function createFileCoalescer(
|
|
|
30
31
|
pending.set(file, timer);
|
|
31
32
|
return true;
|
|
32
33
|
},
|
|
34
|
+
flush(file: string): boolean {
|
|
35
|
+
const timer = pending.get(file);
|
|
36
|
+
if (timer === undefined) return false;
|
|
37
|
+
timerApi.clearTimeout(timer);
|
|
38
|
+
pending.delete(file);
|
|
39
|
+
handler(file);
|
|
40
|
+
return true;
|
|
41
|
+
},
|
|
33
42
|
clear(): void {
|
|
34
43
|
for (const timer of pending.values()) {
|
|
35
44
|
timerApi.clearTimeout(timer);
|
|
@@ -9,6 +9,7 @@ type SubagentExecutionContext = "fresh" | "fork";
|
|
|
9
9
|
interface BranchSessionEntry {
|
|
10
10
|
type: string;
|
|
11
11
|
id?: string;
|
|
12
|
+
cwd?: string;
|
|
12
13
|
parentId?: string | null;
|
|
13
14
|
timestamp?: string;
|
|
14
15
|
message?: {
|
|
@@ -128,6 +129,18 @@ function readSessionEntries(sessionFile: string): BranchSessionEntry[] {
|
|
|
128
129
|
});
|
|
129
130
|
}
|
|
130
131
|
|
|
132
|
+
/** Keep Pi from restoring a forked session into the parent's cwd instead of the child launch cwd. */
|
|
133
|
+
export function alignForkedSessionCwd(sessionFile: string, cwd: string): void {
|
|
134
|
+
const entries = readSessionEntries(sessionFile);
|
|
135
|
+
const header = entries[0];
|
|
136
|
+
if (header?.type !== "session") throw new Error(`Forked session ${sessionFile} does not start with a session header.`);
|
|
137
|
+
const resolvedCwd = path.resolve(cwd);
|
|
138
|
+
const effectiveCwd = fs.realpathSync.native(resolvedCwd);
|
|
139
|
+
if (header.cwd === effectiveCwd) return;
|
|
140
|
+
header.cwd = effectiveCwd;
|
|
141
|
+
fs.writeFileSync(sessionFile, `${entries.map((entry) => JSON.stringify(entry)).join("\n")}\n`, "utf-8");
|
|
142
|
+
}
|
|
143
|
+
|
|
131
144
|
export function createForkContextResolver(
|
|
132
145
|
sessionManager: ForkableSessionManager,
|
|
133
146
|
requestedContext: unknown,
|
package/src/shared/formatters.ts
CHANGED
|
@@ -7,6 +7,7 @@ import * as path from "node:path";
|
|
|
7
7
|
import type { Usage, SingleResult } from "./types.ts";
|
|
8
8
|
import type { ChainStep } from "./settings.ts";
|
|
9
9
|
import { isDynamicParallelStep, isParallelStep } from "./settings.ts";
|
|
10
|
+
import { previewDisplayText, sanitizeDisplayText } from "./display-text.ts";
|
|
10
11
|
import { splitKnownThinkingSuffix, THINKING_LEVELS } from "./model-info.ts";
|
|
11
12
|
|
|
12
13
|
/**
|
|
@@ -100,8 +101,7 @@ export function formatToolCall(name: string, args: Record<string, unknown>, expa
|
|
|
100
101
|
switch (name) {
|
|
101
102
|
case "bash": {
|
|
102
103
|
const command = typeof args.command === "string" ? args.command : "";
|
|
103
|
-
|
|
104
|
-
return `$ ${command.slice(0, maxLength)}${command.length > maxLength ? "..." : ""}`;
|
|
104
|
+
return `$ ${previewDisplayText(command, expanded ? 240 : 60)}`;
|
|
105
105
|
}
|
|
106
106
|
case "read":
|
|
107
107
|
case "write":
|
|
@@ -111,12 +111,10 @@ export function formatToolCall(name: string, args: Record<string, unknown>, expa
|
|
|
111
111
|
: typeof args.file_path === "string"
|
|
112
112
|
? args.file_path
|
|
113
113
|
: "";
|
|
114
|
-
return `${name} ${shortenPath(target)}`;
|
|
114
|
+
return `${name} ${sanitizeDisplayText(shortenPath(target))}`;
|
|
115
115
|
}
|
|
116
116
|
default: {
|
|
117
|
-
|
|
118
|
-
const maxLength = expanded ? 160 : 40;
|
|
119
|
-
return `${name} ${s.slice(0, maxLength)}${s.length > maxLength ? "..." : ""}`;
|
|
117
|
+
return `${name} ${previewDisplayText(JSON.stringify(args), expanded ? 160 : 40)}`;
|
|
120
118
|
}
|
|
121
119
|
}
|
|
122
120
|
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
|
|
4
|
+
function isNodeExecutableName(execPath: string): boolean {
|
|
5
|
+
const basename = path.basename(execPath).toLowerCase();
|
|
6
|
+
return basename === "node" || basename === "node.exe" || basename === "nodejs" || basename === "nodejs.exe";
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function canUseNodeExecutable(execPath: string): boolean {
|
|
10
|
+
try {
|
|
11
|
+
fs.accessSync(execPath, process.platform === "win32" ? fs.constants.F_OK : fs.constants.X_OK);
|
|
12
|
+
return true;
|
|
13
|
+
} catch {
|
|
14
|
+
return false;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function resolveNodeExecutable(execPath = process.execPath): string {
|
|
19
|
+
if (isNodeExecutableName(execPath) && canUseNodeExecutable(execPath)) return execPath;
|
|
20
|
+
return process.platform === "win32" ? "node.exe" : "node";
|
|
21
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { parseFrontmatter } from "../agents/frontmatter.ts";
|
|
5
|
+
import { getAgentDir, getProjectConfigDir } from "./utils.ts";
|
|
6
|
+
|
|
7
|
+
const PROMPT_REF_PATTERN = /^(package|user|project):([A-Za-z0-9][A-Za-z0-9._-]{0,127})$/;
|
|
8
|
+
const PROMPT_VARIABLE_PATTERN = /\{\{(\w+)\}\}/g;
|
|
9
|
+
|
|
10
|
+
type PromptVariable = string | number | boolean;
|
|
11
|
+
|
|
12
|
+
export function getPromptDirectories(cwd: string) {
|
|
13
|
+
return {
|
|
14
|
+
package: path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "prompts"),
|
|
15
|
+
user: path.join(getAgentDir(), "prompts"),
|
|
16
|
+
project: path.join(getProjectConfigDir(cwd), "prompts"),
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function promptVariables(vars: unknown): Record<string, PromptVariable> {
|
|
21
|
+
if (vars === undefined) return {};
|
|
22
|
+
if (!vars || typeof vars !== "object" || Array.isArray(vars)) throw new Error("prompts.render vars must be a plain object.");
|
|
23
|
+
const prototype = Object.getPrototypeOf(vars);
|
|
24
|
+
if (prototype !== null && prototype !== Object.prototype) throw new Error("prompts.render vars must be a plain object.");
|
|
25
|
+
for (const [name, value] of Object.entries(vars)) {
|
|
26
|
+
if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") {
|
|
27
|
+
throw new Error(`prompts.render variable '${name}' must be a string, number, or boolean.`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return vars as Record<string, PromptVariable>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function renderWorkflowPrompt(ref: string, vars: unknown, cwd: string): string {
|
|
34
|
+
const match = ref.match(PROMPT_REF_PATTERN);
|
|
35
|
+
if (!match) throw new Error("prompts.render ref must use package:<name>, user:<name>, or project:<name>.");
|
|
36
|
+
const scope = match[1] as keyof ReturnType<typeof getPromptDirectories>;
|
|
37
|
+
const name = match[2]!;
|
|
38
|
+
const filePath = path.join(getPromptDirectories(cwd)[scope], `${name}.md`);
|
|
39
|
+
let content: string;
|
|
40
|
+
try {
|
|
41
|
+
if (!fs.lstatSync(filePath).isFile()) throw new Error("not a regular file");
|
|
42
|
+
content = fs.readFileSync(filePath, "utf-8");
|
|
43
|
+
} catch (error) {
|
|
44
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
45
|
+
throw new Error(`Could not read prompt fragment '${ref}': ${detail}`);
|
|
46
|
+
}
|
|
47
|
+
const variables = promptVariables(vars);
|
|
48
|
+
return parseFrontmatter(content).body.trim().replace(PROMPT_VARIABLE_PATTERN, (placeholder, variable: string) => {
|
|
49
|
+
return Object.hasOwn(variables, variable) ? String(variables[variable]) : placeholder;
|
|
50
|
+
});
|
|
51
|
+
}
|
package/src/shared/settings.ts
CHANGED
|
@@ -353,6 +353,18 @@ export function resolveChainPath(filePath: string, chainDir: string): string {
|
|
|
353
353
|
return path.isAbsolute(expanded) ? expanded : path.join(chainDir, expanded);
|
|
354
354
|
}
|
|
355
355
|
|
|
356
|
+
export function resolveExistingReadInstructionPaths(reads: readonly string[], instructionCwd: string, existenceCwd = instructionCwd): string[] {
|
|
357
|
+
return reads.flatMap((filePath) => {
|
|
358
|
+
const instructionPath = resolveChainPath(filePath, instructionCwd);
|
|
359
|
+
const existencePath = resolveChainPath(filePath, existenceCwd);
|
|
360
|
+
return fs.existsSync(existencePath) ? [instructionPath] : [];
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
export function resolveExistingReadPaths(reads: readonly string[], cwd: string): string[] {
|
|
365
|
+
return resolveExistingReadInstructionPaths(reads, cwd);
|
|
366
|
+
}
|
|
367
|
+
|
|
356
368
|
/**
|
|
357
369
|
* Build chain instructions from resolved behavior.
|
|
358
370
|
* These are appended to the task to tell the agent what to read/write.
|
|
@@ -367,14 +379,15 @@ export function buildChainInstructions(
|
|
|
367
379
|
chainDir: string,
|
|
368
380
|
isFirstProgressAgent: boolean,
|
|
369
381
|
previousSummary?: string,
|
|
382
|
+
readExistenceDir = chainDir,
|
|
370
383
|
): { prefix: string; suffix: string } {
|
|
371
384
|
const prefixParts: string[] = [];
|
|
372
385
|
const suffixParts: string[] = [];
|
|
373
386
|
|
|
374
387
|
// READS - prepend to override any hardcoded filenames in task text
|
|
375
388
|
if (behavior.reads && behavior.reads.length > 0) {
|
|
376
|
-
const files = behavior.reads
|
|
377
|
-
prefixParts.push(`[Read from: ${files.join(", ")}]`);
|
|
389
|
+
const files = resolveExistingReadInstructionPaths(behavior.reads, chainDir, readExistenceDir);
|
|
390
|
+
if (files.length > 0) prefixParts.push(`[Read from: ${files.join(", ")}]`);
|
|
378
391
|
}
|
|
379
392
|
|
|
380
393
|
// OUTPUT - prepend so agent knows where to write
|