@xzzpig/pi-subagents 0.1.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 +1621 -0
- package/LICENSE +21 -0
- package/README.md +118 -0
- package/agents/delegate.md +14 -0
- package/agents/oracle.md +74 -0
- package/agents/researcher.md +52 -0
- package/agents/reviewer.md +79 -0
- package/agents/scout.md +50 -0
- package/agents/worker.md +58 -0
- package/index.ts +1 -0
- package/inspector-runner.mjs +11 -0
- package/install.mjs +93 -0
- package/package.json +105 -0
- package/prompts/gather-context-and-clarify.md +13 -0
- package/prompts/parallel-cleanup.md +59 -0
- package/prompts/parallel-research.md +50 -0
- package/prompts/parallel-review.md +54 -0
- package/prompts/review-loop.md +43 -0
- package/skills/pi-subagents/SKILL.md +41 -0
- package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
- package/skills/pi-subagents/references/execution-controls.md +428 -0
- package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
- package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
- package/src/agents/agent-management.ts +1256 -0
- package/src/agents/agent-memory.ts +254 -0
- package/src/agents/agent-refinements.ts +624 -0
- package/src/agents/agent-scope.ts +6 -0
- package/src/agents/agent-selection.ts +25 -0
- package/src/agents/agent-serializer.ts +163 -0
- package/src/agents/agents.ts +1889 -0
- package/src/agents/chain-serializer.ts +280 -0
- package/src/agents/frontmatter.ts +149 -0
- package/src/agents/identity.ts +30 -0
- package/src/agents/proactive-skills.ts +194 -0
- package/src/agents/skills.ts +761 -0
- package/src/api/background-work.ts +197 -0
- package/src/api/capability-ceiling.ts +17 -0
- package/src/api/control-channel.ts +4 -0
- package/src/api/delegation.ts +119 -0
- package/src/api/external-runs.ts +129 -0
- package/src/api/intercom-bridge.ts +3 -0
- package/src/api/pi-args.ts +5 -0
- package/src/api/preflight.ts +403 -0
- package/src/api/shared-types.ts +19 -0
- package/src/extension/config.ts +76 -0
- package/src/extension/control-notices.ts +58 -0
- package/src/extension/doctor.ts +230 -0
- package/src/extension/fanout-child.ts +201 -0
- package/src/extension/index.ts +805 -0
- package/src/extension/public-execution.ts +71 -0
- package/src/extension/rpc.ts +653 -0
- package/src/extension/schemas.ts +375 -0
- package/src/extension/steering-notices.ts +35 -0
- package/src/extension/tool-description.ts +164 -0
- package/src/inspectors/herdr/actions.ts +229 -0
- package/src/inspectors/herdr/client.ts +130 -0
- package/src/inspectors/herdr/inspector-runner.ts +141 -0
- package/src/inspectors/herdr/project-panes.ts +154 -0
- package/src/integrations/herdr-status.ts +330 -0
- package/src/intercom/intercom-bridge.ts +187 -0
- package/src/intercom/native-supervisor-channel.ts +715 -0
- package/src/intercom/result-intercom.ts +421 -0
- package/src/missions/actions.ts +410 -0
- package/src/missions/goal-driver.ts +162 -0
- package/src/missions/lifecycle.ts +346 -0
- package/src/missions/store.ts +507 -0
- package/src/missions/types.ts +157 -0
- package/src/missions/workflow-state.ts +250 -0
- package/src/policy/authority.ts +46 -0
- package/src/profiles/profiles.ts +661 -0
- package/src/runs/background/async-execution.ts +1574 -0
- package/src/runs/background/async-job-tracker.ts +511 -0
- package/src/runs/background/async-resume.ts +539 -0
- package/src/runs/background/async-status.ts +542 -0
- package/src/runs/background/auto-drain.ts +67 -0
- package/src/runs/background/chain-append.ts +328 -0
- package/src/runs/background/chain-root-attachment.ts +199 -0
- package/src/runs/background/completion-batcher.ts +168 -0
- package/src/runs/background/completion-dedupe.ts +54 -0
- package/src/runs/background/control-channel.ts +692 -0
- package/src/runs/background/fleet-view.ts +540 -0
- package/src/runs/background/notify.ts +332 -0
- package/src/runs/background/parallel-groups.ts +45 -0
- package/src/runs/background/process-terminal.ts +280 -0
- package/src/runs/background/result-watcher.ts +414 -0
- package/src/runs/background/retained-children.ts +68 -0
- package/src/runs/background/run-id-resolver.ts +167 -0
- package/src/runs/background/run-status.ts +504 -0
- package/src/runs/background/scheduled-runs.ts +753 -0
- package/src/runs/background/stale-run-reconciler.ts +396 -0
- package/src/runs/background/steering.ts +239 -0
- package/src/runs/background/subagent-runner.ts +4718 -0
- package/src/runs/background/subagent-wait.ts +661 -0
- package/src/runs/background/top-level-async.ts +14 -0
- package/src/runs/background/wait-completions.ts +112 -0
- package/src/runs/background/wait-config.ts +36 -0
- package/src/runs/background/wait-subscriptions.ts +253 -0
- package/src/runs/background/wait-tool.ts +34 -0
- package/src/runs/foreground/async-steering-action.ts +256 -0
- package/src/runs/foreground/async-stop-action.ts +65 -0
- package/src/runs/foreground/chain-clarify.ts +1354 -0
- package/src/runs/foreground/chain-execution.ts +1527 -0
- package/src/runs/foreground/execution.ts +1868 -0
- package/src/runs/foreground/foreground-control.ts +132 -0
- package/src/runs/foreground/subagent-executor.ts +5532 -0
- package/src/runs/shared/acceptance.ts +1365 -0
- package/src/runs/shared/agent-contract.ts +38 -0
- package/src/runs/shared/capability-ceiling.ts +209 -0
- package/src/runs/shared/chain-outputs.ts +118 -0
- package/src/runs/shared/child-protocol.ts +401 -0
- package/src/runs/shared/completion-guard.ts +95 -0
- package/src/runs/shared/context-mode.ts +44 -0
- package/src/runs/shared/dynamic-fanout.ts +297 -0
- package/src/runs/shared/external-cli-runner.ts +130 -0
- package/src/runs/shared/long-running-guard.ts +220 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
- package/src/runs/shared/model-fallback.ts +336 -0
- package/src/runs/shared/model-scope.ts +128 -0
- package/src/runs/shared/nested-events.ts +1076 -0
- package/src/runs/shared/nested-path.ts +52 -0
- package/src/runs/shared/nested-render.ts +123 -0
- package/src/runs/shared/parallel-handoff.ts +238 -0
- package/src/runs/shared/parallel-utils.ts +256 -0
- package/src/runs/shared/permissions.ts +95 -0
- package/src/runs/shared/pi-args.ts +808 -0
- package/src/runs/shared/pi-spawn.ts +163 -0
- package/src/runs/shared/process-signal.ts +19 -0
- package/src/runs/shared/run-history.ts +181 -0
- package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
- package/src/runs/shared/session-lease.ts +299 -0
- package/src/runs/shared/single-output.ts +235 -0
- package/src/runs/shared/spawn-budget.ts +128 -0
- package/src/runs/shared/structured-output.ts +182 -0
- package/src/runs/shared/subagent-control.ts +231 -0
- package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
- package/src/runs/shared/subagent-startup-retry.ts +104 -0
- package/src/runs/shared/task-intent.ts +181 -0
- package/src/runs/shared/tool-availability.ts +83 -0
- package/src/runs/shared/tool-budget.ts +80 -0
- package/src/runs/shared/turn-budget.ts +98 -0
- package/src/runs/shared/usage-budget.ts +65 -0
- package/src/runs/shared/workflow-graph.ts +231 -0
- package/src/runs/shared/worktree.ts +759 -0
- package/src/shared/accessible-dir.ts +47 -0
- package/src/shared/artifacts.ts +285 -0
- package/src/shared/atomic-json.ts +61 -0
- package/src/shared/child-transcript.ts +264 -0
- package/src/shared/file-coalescer.ts +40 -0
- package/src/shared/file-system-retry.ts +47 -0
- package/src/shared/fork-context.ts +213 -0
- package/src/shared/formatters.ts +133 -0
- package/src/shared/jsonl-writer.ts +81 -0
- package/src/shared/launch-contract.ts +124 -0
- package/src/shared/model-info.ts +81 -0
- package/src/shared/post-exit-stdio-guard.ts +85 -0
- package/src/shared/session-identity.ts +10 -0
- package/src/shared/session-tokens.ts +44 -0
- package/src/shared/settings.ts +501 -0
- package/src/shared/status-format.ts +55 -0
- package/src/shared/types.ts +2069 -0
- package/src/shared/utils.ts +613 -0
- package/src/slash/delegation-adapters.ts +434 -0
- package/src/slash/delegation-json.ts +108 -0
- package/src/slash/delegation-request.ts +166 -0
- package/src/slash/prompt-template-bridge.ts +383 -0
- package/src/slash/prompt-workflows.ts +300 -0
- package/src/slash/selector.ts +147 -0
- package/src/slash/slash-bridge.ts +192 -0
- package/src/slash/slash-commands.ts +994 -0
- package/src/slash/slash-live-state.ts +296 -0
- package/src/slash/subagents-admin.ts +432 -0
- package/src/tui/fleet-status.ts +564 -0
- package/src/tui/fleet-transcript.ts +577 -0
- package/src/tui/fleet.ts +879 -0
- package/src/tui/render-helpers.ts +80 -0
- package/src/tui/render.ts +2029 -0
- package/src/types/pi-runtime-compat.d.ts +8 -0
- package/src/watchdog/change-signature.ts +220 -0
- package/src/watchdog/child-status.ts +205 -0
- package/src/watchdog/emission-guard.ts +123 -0
- package/src/watchdog/lsp-diagnostics.ts +537 -0
- package/src/watchdog/model-selection.ts +167 -0
- package/src/watchdog/permission-arbiter.ts +145 -0
- package/src/watchdog/register-child.ts +117 -0
- package/src/watchdog/register-main.ts +440 -0
- package/src/watchdog/render.ts +54 -0
- package/src/watchdog/review.ts +302 -0
- package/src/watchdog/runtime.ts +868 -0
- package/src/watchdog/scope.ts +62 -0
- package/src/watchdog/settings.ts +568 -0
- package/src/watchdog/tool-actions.ts +155 -0
- package/src/watchdog/turn-delta.ts +161 -0
- package/src/watchdog/types.ts +198 -0
- package/src/watchdog/warning-format.ts +73 -0
- package/src/workflows/chat-progress.ts +140 -0
- package/src/workflows/scripted-workflow.ts +506 -0
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
|
|
5
|
+
export const PI_CODING_AGENT_PACKAGE = "@earendil-works/pi-coding-agent";
|
|
6
|
+
export const PI_SUBAGENT_PI_BINARY_ENV = "PI_SUBAGENT_PI_BINARY";
|
|
7
|
+
|
|
8
|
+
export function findPiPackageRootFromEntry(
|
|
9
|
+
entryPoint: string,
|
|
10
|
+
): string | undefined {
|
|
11
|
+
let dir = path.dirname(entryPoint);
|
|
12
|
+
while (dir !== path.dirname(dir)) {
|
|
13
|
+
const packageJsonPath = path.join(dir, "package.json");
|
|
14
|
+
if (fs.existsSync(packageJsonPath)) {
|
|
15
|
+
const pkg = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8")) as {
|
|
16
|
+
name?: unknown;
|
|
17
|
+
};
|
|
18
|
+
if (pkg.name === PI_CODING_AGENT_PACKAGE) return dir;
|
|
19
|
+
}
|
|
20
|
+
dir = path.dirname(dir);
|
|
21
|
+
}
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function resolveInstalledPiPackageRoot(): string | undefined {
|
|
26
|
+
return findPiPackageRootFromEntry(
|
|
27
|
+
fileURLToPath(import.meta.resolve(PI_CODING_AGENT_PACKAGE)),
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function resolvePiPackageRoot(): string | undefined {
|
|
32
|
+
try {
|
|
33
|
+
const entry = process.argv[1];
|
|
34
|
+
return entry
|
|
35
|
+
? findPiPackageRootFromEntry(fs.realpathSync(entry))
|
|
36
|
+
: undefined;
|
|
37
|
+
} catch {
|
|
38
|
+
// process.argv[1] probing is best-effort; callers can fall back to PATH/package resolution.
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface PiSpawnDeps {
|
|
44
|
+
platform?: NodeJS.Platform;
|
|
45
|
+
execPath?: string;
|
|
46
|
+
argv1?: string;
|
|
47
|
+
existsSync?: (filePath: string) => boolean;
|
|
48
|
+
realpathSync?: (filePath: string) => string;
|
|
49
|
+
readFileSync?: (filePath: string, encoding: "utf-8") => string;
|
|
50
|
+
resolvePackageJson?: () => string;
|
|
51
|
+
resolvePackageEntry?: () => string;
|
|
52
|
+
piPackageRoot?: string;
|
|
53
|
+
env?: NodeJS.ProcessEnv;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
interface PiSpawnCommand {
|
|
57
|
+
command: string;
|
|
58
|
+
args: string[];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function isRunnableNodeScript(
|
|
62
|
+
filePath: string,
|
|
63
|
+
existsSync: (filePath: string) => boolean,
|
|
64
|
+
): boolean {
|
|
65
|
+
if (!existsSync(filePath)) return false;
|
|
66
|
+
return /\.(?:mjs|cjs|js)$/i.test(filePath);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function normalizePath(filePath: string): string {
|
|
70
|
+
return path.isAbsolute(filePath) ? filePath : path.resolve(filePath);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function isStandalonePiExecutable(execPath: string): boolean {
|
|
74
|
+
const executableName = execPath.split(/[\\/]/).pop();
|
|
75
|
+
return /^pi(?:\.exe)?$/i.test(executableName ?? "");
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function resolvePiCliScript(
|
|
79
|
+
deps: PiSpawnDeps = {},
|
|
80
|
+
): string | undefined {
|
|
81
|
+
const existsSync = deps.existsSync ?? fs.existsSync;
|
|
82
|
+
const realpathSync = deps.realpathSync ?? fs.realpathSync;
|
|
83
|
+
const readFileSync =
|
|
84
|
+
deps.readFileSync ??
|
|
85
|
+
((filePath, encoding) => fs.readFileSync(filePath, encoding));
|
|
86
|
+
const argv1 = deps.argv1 ?? process.argv[1];
|
|
87
|
+
|
|
88
|
+
if (argv1) {
|
|
89
|
+
const argvPath = normalizePath(argv1);
|
|
90
|
+
if (isRunnableNodeScript(argvPath, existsSync)) {
|
|
91
|
+
try {
|
|
92
|
+
const canonicalArgvPath = realpathSync(argvPath);
|
|
93
|
+
if (isRunnableNodeScript(canonicalArgvPath, existsSync) && findPiPackageRootFromEntry(canonicalArgvPath)) {
|
|
94
|
+
return canonicalArgvPath;
|
|
95
|
+
}
|
|
96
|
+
} catch {
|
|
97
|
+
// Host package metadata is untrusted here; keep resolving the installed Pi CLI.
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
try {
|
|
103
|
+
const resolvePackageJson =
|
|
104
|
+
deps.resolvePackageJson ??
|
|
105
|
+
(() => {
|
|
106
|
+
const root = deps.piPackageRoot ?? resolvePiPackageRoot();
|
|
107
|
+
if (root) return path.join(root, "package.json");
|
|
108
|
+
const packageRoot = deps.resolvePackageEntry
|
|
109
|
+
? findPiPackageRootFromEntry(deps.resolvePackageEntry())
|
|
110
|
+
: resolveInstalledPiPackageRoot();
|
|
111
|
+
if (!packageRoot)
|
|
112
|
+
throw new Error(
|
|
113
|
+
`Could not resolve ${PI_CODING_AGENT_PACKAGE} package root`,
|
|
114
|
+
);
|
|
115
|
+
return path.join(packageRoot, "package.json");
|
|
116
|
+
});
|
|
117
|
+
const packageJsonPath = resolvePackageJson();
|
|
118
|
+
const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8")) as {
|
|
119
|
+
bin?: string | Record<string, string>;
|
|
120
|
+
};
|
|
121
|
+
const binField = packageJson.bin;
|
|
122
|
+
const binPath =
|
|
123
|
+
typeof binField === "string"
|
|
124
|
+
? binField
|
|
125
|
+
: (binField?.pi ?? Object.values(binField ?? {})[0]);
|
|
126
|
+
if (!binPath) return undefined;
|
|
127
|
+
const candidate = path.resolve(path.dirname(packageJsonPath), binPath);
|
|
128
|
+
if (isRunnableNodeScript(candidate, existsSync)) {
|
|
129
|
+
return candidate;
|
|
130
|
+
}
|
|
131
|
+
} catch {
|
|
132
|
+
// Verified CLI resolution is optional; falling back to `pi` lets PATH handle execution.
|
|
133
|
+
return undefined;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return undefined;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function getPiSpawnCommand(
|
|
140
|
+
args: string[],
|
|
141
|
+
deps: PiSpawnDeps = {},
|
|
142
|
+
): PiSpawnCommand {
|
|
143
|
+
const env = deps.env ?? process.env;
|
|
144
|
+
const piBinary = env[PI_SUBAGENT_PI_BINARY_ENV]?.trim();
|
|
145
|
+
if (piBinary) {
|
|
146
|
+
return { command: piBinary, args };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const execPath = deps.execPath ?? process.execPath;
|
|
150
|
+
if (isStandalonePiExecutable(execPath)) {
|
|
151
|
+
return { command: execPath, args };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const piCliPath = resolvePiCliScript(deps);
|
|
155
|
+
if (piCliPath) {
|
|
156
|
+
return {
|
|
157
|
+
command: execPath,
|
|
158
|
+
args: [piCliPath, ...args],
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return { command: "pi", args };
|
|
163
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export function formatProcessSignalError(signal: string): string {
|
|
2
|
+
return `Subagent process terminated by signal ${signal}.`;
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
export function isUnexplainedProcessSignal(input: {
|
|
6
|
+
processSignal?: string | null;
|
|
7
|
+
interrupted?: boolean;
|
|
8
|
+
timedOut?: boolean;
|
|
9
|
+
stopped?: boolean;
|
|
10
|
+
turnBudgetExceeded?: boolean;
|
|
11
|
+
forcedDrainAfterFinalSuccess?: boolean;
|
|
12
|
+
}): boolean {
|
|
13
|
+
return Boolean(input.processSignal)
|
|
14
|
+
&& input.interrupted !== true
|
|
15
|
+
&& input.timedOut !== true
|
|
16
|
+
&& input.stopped !== true
|
|
17
|
+
&& input.turnBudgetExceeded !== true
|
|
18
|
+
&& input.forcedDrainAfterFinalSuccess !== true;
|
|
19
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import { getAgentDir } from "../../shared/utils.ts";
|
|
5
|
+
|
|
6
|
+
export interface RunEntry {
|
|
7
|
+
agent: string;
|
|
8
|
+
task: string;
|
|
9
|
+
taskHash?: string;
|
|
10
|
+
ts: number;
|
|
11
|
+
status: "ok" | "error";
|
|
12
|
+
duration: number;
|
|
13
|
+
exit?: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const ROTATE_READ_THRESHOLD = 1200;
|
|
17
|
+
const ROTATE_KEEP = 1000;
|
|
18
|
+
const PRIVATE_DIR_MODE = 0o700;
|
|
19
|
+
const PRIVATE_FILE_MODE = 0o600;
|
|
20
|
+
const REDACTED_TASK = "[redacted]";
|
|
21
|
+
const historyFileStates = new Map<string, { mtimeMs: number; ctimeMs: number; size: number; ino: number; lineCount: number }>();
|
|
22
|
+
|
|
23
|
+
function getHistoryPath(): string {
|
|
24
|
+
return path.join(getAgentDir(), "run-history.jsonl");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function hashTask(task: string): string {
|
|
28
|
+
return createHash("sha256").update(task).digest("hex");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function hardenHistoryStorage(historyPath: string): void {
|
|
32
|
+
const historyDir = path.dirname(historyPath);
|
|
33
|
+
fs.mkdirSync(historyDir, { recursive: true, mode: PRIVATE_DIR_MODE });
|
|
34
|
+
try {
|
|
35
|
+
if ((fs.statSync(historyDir).mode & 0o777) !== PRIVATE_DIR_MODE) fs.chmodSync(historyDir, PRIVATE_DIR_MODE);
|
|
36
|
+
} catch {}
|
|
37
|
+
try {
|
|
38
|
+
if ((fs.statSync(historyPath).mode & 0o777) !== PRIVATE_FILE_MODE) fs.chmodSync(historyPath, PRIVATE_FILE_MODE);
|
|
39
|
+
} catch {}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function sanitizeHistoryLine(line: string): string | undefined {
|
|
43
|
+
let value: unknown;
|
|
44
|
+
try {
|
|
45
|
+
value = JSON.parse(line);
|
|
46
|
+
} catch {
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
if (!value || typeof value !== "object") return undefined;
|
|
50
|
+
|
|
51
|
+
const record = value as Record<string, unknown>;
|
|
52
|
+
const task = typeof record.task === "string" ? record.task : "";
|
|
53
|
+
const taskHash = typeof record.taskHash === "string" && record.taskHash
|
|
54
|
+
? record.taskHash
|
|
55
|
+
: task && task !== REDACTED_TASK
|
|
56
|
+
? hashTask(task)
|
|
57
|
+
: undefined;
|
|
58
|
+
|
|
59
|
+
return JSON.stringify({
|
|
60
|
+
...record,
|
|
61
|
+
task: REDACTED_TASK,
|
|
62
|
+
...(taskHash ? { taskHash } : {}),
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function sanitizeHistoryLines(raw: string): { lines: string[]; changed: boolean } {
|
|
67
|
+
const lines: string[] = [];
|
|
68
|
+
let changed = false;
|
|
69
|
+
for (const line of raw.split("\n")) {
|
|
70
|
+
const trimmed = line.trim();
|
|
71
|
+
if (!trimmed) continue;
|
|
72
|
+
const sanitized = sanitizeHistoryLine(trimmed);
|
|
73
|
+
if (!sanitized) {
|
|
74
|
+
changed = true;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (sanitized !== trimmed) changed = true;
|
|
78
|
+
lines.push(sanitized);
|
|
79
|
+
}
|
|
80
|
+
return { lines, changed };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function writePrivateHistory(historyPath: string, lines: string[]): void {
|
|
84
|
+
fs.writeFileSync(historyPath, lines.length ? `${lines.join("\n")}\n` : "", { encoding: "utf-8", mode: PRIVATE_FILE_MODE });
|
|
85
|
+
try { fs.chmodSync(historyPath, PRIVATE_FILE_MODE); } catch {}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function rememberHistoryFile(historyPath: string, lineCount: number): void {
|
|
89
|
+
const stat = fs.statSync(historyPath);
|
|
90
|
+
historyFileStates.set(historyPath, {
|
|
91
|
+
mtimeMs: stat.mtimeMs,
|
|
92
|
+
ctimeMs: stat.ctimeMs,
|
|
93
|
+
size: stat.size,
|
|
94
|
+
ino: stat.ino,
|
|
95
|
+
lineCount,
|
|
96
|
+
});
|
|
97
|
+
if (historyFileStates.size > 8) historyFileStates.delete(historyFileStates.keys().next().value!);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function sanitizeHistoryFile(historyPath: string): number {
|
|
101
|
+
let stat: fs.Stats;
|
|
102
|
+
try {
|
|
103
|
+
stat = fs.statSync(historyPath);
|
|
104
|
+
} catch (error) {
|
|
105
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return 0;
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
const cached = historyFileStates.get(historyPath);
|
|
109
|
+
if (cached
|
|
110
|
+
&& cached.mtimeMs === stat.mtimeMs
|
|
111
|
+
&& cached.ctimeMs === stat.ctimeMs
|
|
112
|
+
&& cached.size === stat.size
|
|
113
|
+
&& cached.ino === stat.ino) {
|
|
114
|
+
return cached.lineCount;
|
|
115
|
+
}
|
|
116
|
+
const raw = fs.readFileSync(historyPath, "utf-8");
|
|
117
|
+
const { lines, changed } = sanitizeHistoryLines(raw);
|
|
118
|
+
if (changed) writePrivateHistory(historyPath, lines);
|
|
119
|
+
rememberHistoryFile(historyPath, lines.length);
|
|
120
|
+
return lines.length;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function appendPrivateHistoryLine(historyPath: string, line: string): void {
|
|
124
|
+
const fd = fs.openSync(historyPath, fs.constants.O_APPEND | fs.constants.O_CREAT | fs.constants.O_WRONLY, PRIVATE_FILE_MODE);
|
|
125
|
+
try {
|
|
126
|
+
fs.writeSync(fd, `${line}\n`);
|
|
127
|
+
} finally {
|
|
128
|
+
fs.closeSync(fd);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function recordRun(agent: string, task: string, exitCode: number, durationMs: number): void {
|
|
133
|
+
try {
|
|
134
|
+
const entry: RunEntry = {
|
|
135
|
+
agent,
|
|
136
|
+
task: REDACTED_TASK,
|
|
137
|
+
taskHash: hashTask(task),
|
|
138
|
+
ts: Math.floor(Date.now() / 1000),
|
|
139
|
+
status: exitCode === 0 ? "ok" : "error",
|
|
140
|
+
duration: durationMs,
|
|
141
|
+
...(exitCode !== 0 ? { exit: exitCode } : {}),
|
|
142
|
+
};
|
|
143
|
+
const historyPath = getHistoryPath();
|
|
144
|
+
hardenHistoryStorage(historyPath);
|
|
145
|
+
let lineCount: number | undefined;
|
|
146
|
+
try { lineCount = sanitizeHistoryFile(historyPath); } catch {}
|
|
147
|
+
appendPrivateHistoryLine(historyPath, JSON.stringify(entry));
|
|
148
|
+
if (lineCount === undefined) historyFileStates.delete(historyPath);
|
|
149
|
+
else rememberHistoryFile(historyPath, lineCount + 1);
|
|
150
|
+
} catch {
|
|
151
|
+
// Best-effort — never crash the execution flow for history recording
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function loadRunsForAgent(agent: string): RunEntry[] {
|
|
156
|
+
const historyPath = getHistoryPath();
|
|
157
|
+
try { hardenHistoryStorage(historyPath); } catch {}
|
|
158
|
+
if (!fs.existsSync(historyPath)) return [];
|
|
159
|
+
let raw: string;
|
|
160
|
+
try {
|
|
161
|
+
raw = fs.readFileSync(historyPath, "utf-8");
|
|
162
|
+
} catch {
|
|
163
|
+
return [];
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
let { lines, changed } = sanitizeHistoryLines(raw);
|
|
167
|
+
|
|
168
|
+
if (lines.length > ROTATE_READ_THRESHOLD) {
|
|
169
|
+
lines = lines.slice(-ROTATE_KEEP);
|
|
170
|
+
changed = true;
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
if (changed) writePrivateHistory(historyPath, lines);
|
|
174
|
+
rememberHistoryFile(historyPath, lines.length);
|
|
175
|
+
} catch {}
|
|
176
|
+
|
|
177
|
+
return lines
|
|
178
|
+
.map((line) => { try { return JSON.parse(line) as RunEntry; } catch { return undefined; } })
|
|
179
|
+
.filter((entry): entry is RunEntry => entry !== undefined && entry.agent === agent)
|
|
180
|
+
.reverse();
|
|
181
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import type { RuntimeAcknowledgedChildExtensionsV1 } from "../../shared/types.ts";
|
|
4
|
+
|
|
5
|
+
export const RUNTIME_EXTENSION_ACK_EVENT = "subagent:acknowledge-extension";
|
|
6
|
+
export const RUNTIME_EXTENSION_ACK_PATH_ENV = "PI_SUBAGENT_RUNTIME_ACKNOWLEDGED_EXTENSIONS";
|
|
7
|
+
export const MAX_RUNTIME_ACKNOWLEDGED_EXTENSION_IDS = 32;
|
|
8
|
+
export const MAX_RUNTIME_ACKNOWLEDGED_EXTENSION_ID_LENGTH = 128;
|
|
9
|
+
// Generous bound for a valid capture (32 ids x 128 chars plus envelope); larger files are child misbehavior.
|
|
10
|
+
export const MAX_RUNTIME_ACKNOWLEDGED_EXTENSION_FILE_BYTES = 64 * 1024;
|
|
11
|
+
|
|
12
|
+
export function isRuntimeAcknowledgedExtensionId(value: unknown): value is string {
|
|
13
|
+
return typeof value === "string"
|
|
14
|
+
&& value.length > 0
|
|
15
|
+
&& value.length <= MAX_RUNTIME_ACKNOWLEDGED_EXTENSION_ID_LENGTH
|
|
16
|
+
&& /^[A-Za-z0-9._:@+-]+$/.test(value)
|
|
17
|
+
&& !value.includes("..")
|
|
18
|
+
&& !value.includes("/")
|
|
19
|
+
&& !value.includes("\\");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function projectRuntimeAcknowledgedExtensions(ids: Iterable<unknown>): RuntimeAcknowledgedChildExtensionsV1 | undefined {
|
|
23
|
+
const unique: string[] = [];
|
|
24
|
+
const seen = new Set<string>();
|
|
25
|
+
for (const id of ids) {
|
|
26
|
+
if (!isRuntimeAcknowledgedExtensionId(id) || seen.has(id)) continue;
|
|
27
|
+
seen.add(id);
|
|
28
|
+
unique.push(id);
|
|
29
|
+
}
|
|
30
|
+
if (unique.length === 0) return undefined;
|
|
31
|
+
return {
|
|
32
|
+
version: 1,
|
|
33
|
+
source: "child-runtime",
|
|
34
|
+
ids: unique.slice(0, MAX_RUNTIME_ACKNOWLEDGED_EXTENSION_IDS),
|
|
35
|
+
omitted: Math.max(0, unique.length - MAX_RUNTIME_ACKNOWLEDGED_EXTENSION_IDS),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function sanitizeRuntimeAcknowledgedExtensions(value: unknown): RuntimeAcknowledgedChildExtensionsV1 | undefined {
|
|
40
|
+
if (!value || typeof value !== "object") return undefined;
|
|
41
|
+
const raw = value as Record<string, unknown>;
|
|
42
|
+
if (raw.version !== 1 || raw.source !== "child-runtime" || !Array.isArray(raw.ids)) return undefined;
|
|
43
|
+
const projected = projectRuntimeAcknowledgedExtensions(raw.ids);
|
|
44
|
+
if (!projected) return undefined;
|
|
45
|
+
const omitted = typeof raw.omitted === "number" && Number.isFinite(raw.omitted)
|
|
46
|
+
? Math.max(0, Math.floor(raw.omitted))
|
|
47
|
+
: 0;
|
|
48
|
+
return { ...projected, omitted: projected.omitted + omitted };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function readRuntimeAcknowledgedExtensions(filePath: string | undefined): RuntimeAcknowledgedChildExtensionsV1 | undefined {
|
|
52
|
+
if (!filePath) return undefined;
|
|
53
|
+
try {
|
|
54
|
+
if (fs.statSync(filePath).size > MAX_RUNTIME_ACKNOWLEDGED_EXTENSION_FILE_BYTES) return undefined;
|
|
55
|
+
const parsed = JSON.parse(fs.readFileSync(filePath, "utf-8")) as unknown;
|
|
56
|
+
return sanitizeRuntimeAcknowledgedExtensions(parsed);
|
|
57
|
+
} catch {
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function writeRuntimeAcknowledgedExtensions(filePath: string, ids: Iterable<unknown>): void {
|
|
63
|
+
const projection = projectRuntimeAcknowledgedExtensions(ids);
|
|
64
|
+
try {
|
|
65
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
66
|
+
if (projection) fs.writeFileSync(filePath, JSON.stringify(projection), { mode: 0o600 });
|
|
67
|
+
else fs.rmSync(filePath, { force: true });
|
|
68
|
+
} catch {
|
|
69
|
+
// Runtime acknowledgement is best-effort observability only.
|
|
70
|
+
}
|
|
71
|
+
}
|