@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,47 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import { DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS, runFileSystemOperationWithRetry, waitForFileSystemRetry } from "./file-system-retry.ts";
|
|
3
|
+
|
|
4
|
+
type AccessibleDirFs = Pick<typeof fs, "accessSync" | "mkdirSync">;
|
|
5
|
+
|
|
6
|
+
type AccessibleDirOptions = {
|
|
7
|
+
fs?: AccessibleDirFs;
|
|
8
|
+
retryDirectoryErrors?: boolean;
|
|
9
|
+
retryDelaysMs?: readonly number[];
|
|
10
|
+
wait?: (delayMs: number) => void;
|
|
11
|
+
pid?: number;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export function ensureAccessibleDir(dirPath: string, options: AccessibleDirOptions = {}): string {
|
|
15
|
+
const fsImpl = options.fs ?? fs;
|
|
16
|
+
const pid = options.pid ?? process.pid;
|
|
17
|
+
const retryDirectoryErrors = options.retryDirectoryErrors ?? process.platform === "win32";
|
|
18
|
+
const retryDelaysMs = retryDirectoryErrors ? options.retryDelaysMs ?? DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS : [];
|
|
19
|
+
const wait = options.wait ?? waitForFileSystemRetry;
|
|
20
|
+
|
|
21
|
+
const mkdirWithRetry = (target: string): void => {
|
|
22
|
+
runFileSystemOperationWithRetry(() => {
|
|
23
|
+
fsImpl.mkdirSync(target, { recursive: true });
|
|
24
|
+
}, { retryDelaysMs, wait });
|
|
25
|
+
};
|
|
26
|
+
const accessWithRetry = (target: string): void => {
|
|
27
|
+
runFileSystemOperationWithRetry(() => {
|
|
28
|
+
fsImpl.accessSync(target, fs.constants.R_OK | fs.constants.W_OK);
|
|
29
|
+
}, { retryDelaysMs, wait });
|
|
30
|
+
};
|
|
31
|
+
const fallbackPath = (): string => {
|
|
32
|
+
const fallback = `${dirPath}-${pid}`;
|
|
33
|
+
mkdirWithRetry(fallback);
|
|
34
|
+
accessWithRetry(fallback);
|
|
35
|
+
return fallback;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
try {
|
|
39
|
+
mkdirWithRetry(dirPath);
|
|
40
|
+
accessWithRetry(dirPath);
|
|
41
|
+
return dirPath;
|
|
42
|
+
} catch (error) {
|
|
43
|
+
const code = (error as NodeJS.ErrnoException | undefined)?.code;
|
|
44
|
+
if (code !== "EPERM" && code !== "EACCES") throw error;
|
|
45
|
+
return fallbackPath();
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { CHAIN_RUNS_DIR, TEMP_ARTIFACTS_DIR, type ArtifactPaths, type ArtifactDirPreference } from "./types.ts";
|
|
4
|
+
import { getAgentDir } from "./utils.ts";
|
|
5
|
+
const CLEANUP_MARKER_FILE = ".last-cleanup";
|
|
6
|
+
const PROJECT_ARTIFACT_ROOT = ".pi-subagents";
|
|
7
|
+
|
|
8
|
+
const PROJECT_ARTIFACT_PATHS = [
|
|
9
|
+
`${PROJECT_ARTIFACT_ROOT}/artifacts/output.md`,
|
|
10
|
+
`${PROJECT_ARTIFACT_ROOT}/artifacts/run_worker_input.md`,
|
|
11
|
+
`${PROJECT_ARTIFACT_ROOT}/artifacts/run_worker_output.md`,
|
|
12
|
+
`${PROJECT_ARTIFACT_ROOT}/artifacts/run_worker.jsonl`,
|
|
13
|
+
`${PROJECT_ARTIFACT_ROOT}/artifacts/run_worker_transcript.jsonl`,
|
|
14
|
+
`${PROJECT_ARTIFACT_ROOT}/artifacts/run_worker_meta.json`,
|
|
15
|
+
`${PROJECT_ARTIFACT_ROOT}/artifacts/progress/run/progress.md`,
|
|
16
|
+
`${PROJECT_ARTIFACT_ROOT}/artifacts/outputs/output.md`,
|
|
17
|
+
`${PROJECT_ARTIFACT_ROOT}/artifacts/outputs/run/output.md`,
|
|
18
|
+
`${PROJECT_ARTIFACT_ROOT}/chain-runs/run.json`,
|
|
19
|
+
];
|
|
20
|
+
|
|
21
|
+
function globMatchesPath(pattern: string, filePath: string): boolean {
|
|
22
|
+
let expression = "^";
|
|
23
|
+
for (let index = 0; index < pattern.length; index += 1) {
|
|
24
|
+
const character = pattern[index];
|
|
25
|
+
if (character === undefined) break;
|
|
26
|
+
if (character === "*" && pattern[index + 1] === "*") {
|
|
27
|
+
index += 1;
|
|
28
|
+
if (pattern[index + 1] === "/") {
|
|
29
|
+
index += 1;
|
|
30
|
+
expression += "(?:.*/)?";
|
|
31
|
+
} else {
|
|
32
|
+
expression += ".*";
|
|
33
|
+
}
|
|
34
|
+
} else if (character === "*") {
|
|
35
|
+
expression += "[^/]*";
|
|
36
|
+
} else if (character === "?") {
|
|
37
|
+
expression += "[^/]";
|
|
38
|
+
} else if (character === "[") {
|
|
39
|
+
const end = pattern.indexOf("]", index + 1);
|
|
40
|
+
if (end === -1) expression += "\\[";
|
|
41
|
+
else {
|
|
42
|
+
expression += pattern.slice(index, end + 1);
|
|
43
|
+
index = end;
|
|
44
|
+
}
|
|
45
|
+
} else {
|
|
46
|
+
expression += character.replace(/[|\\{}()[\]^$+?.]/g, "\\$&");
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
return new RegExp(`${expression}$`).test(filePath);
|
|
51
|
+
} catch {
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function normalizePattern(pattern: string): string {
|
|
57
|
+
return pattern.replace(/^\.\//, "").replace(/^\//, "").replace(/\/+$/, "");
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function patternMatchesArtifactPath(pattern: string, artifactPath: string): boolean {
|
|
61
|
+
const normalized = normalizePattern(pattern);
|
|
62
|
+
return normalized === PROJECT_ARTIFACT_ROOT
|
|
63
|
+
|| normalized === "*"
|
|
64
|
+
|| artifactPath.startsWith(`${normalized}/`)
|
|
65
|
+
|| globMatchesPath(normalized, artifactPath);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function patternMatchesProjectArtifacts(pattern: string): boolean {
|
|
69
|
+
return PROJECT_ARTIFACT_PATHS.some((artifactPath) => patternMatchesArtifactPath(pattern, artifactPath));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function ignoreFileExcludesProjectArtifacts(filePath: string): boolean {
|
|
73
|
+
if (!fs.existsSync(filePath)) return false;
|
|
74
|
+
try {
|
|
75
|
+
const excluded = new Set<string>();
|
|
76
|
+
for (const rawLine of fs.readFileSync(filePath, "utf-8").split(/\r?\n/)) {
|
|
77
|
+
const line = rawLine.trim();
|
|
78
|
+
if (!line || line.startsWith("#")) continue;
|
|
79
|
+
const negated = line.startsWith("!");
|
|
80
|
+
const pattern = negated ? line.slice(1) : line;
|
|
81
|
+
for (const artifactPath of PROJECT_ARTIFACT_PATHS) {
|
|
82
|
+
if (!patternMatchesArtifactPath(pattern, artifactPath)) continue;
|
|
83
|
+
if (negated) excluded.delete(artifactPath);
|
|
84
|
+
else excluded.add(artifactPath);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return excluded.size === PROJECT_ARTIFACT_PATHS.length;
|
|
88
|
+
} catch {
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function filesIncludeProjectArtifacts(files: unknown): boolean | undefined {
|
|
94
|
+
if (!Array.isArray(files)) return undefined;
|
|
95
|
+
const included = new Set<string>();
|
|
96
|
+
for (const entry of files) {
|
|
97
|
+
if (typeof entry !== "string") continue;
|
|
98
|
+
const negated = entry.startsWith("!");
|
|
99
|
+
const pattern = negated ? entry.slice(1) : entry;
|
|
100
|
+
for (const artifactPath of PROJECT_ARTIFACT_PATHS) {
|
|
101
|
+
if (!patternMatchesArtifactPath(pattern, artifactPath)) continue;
|
|
102
|
+
if (negated) included.delete(artifactPath);
|
|
103
|
+
else included.add(artifactPath);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return included.size > 0;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Returns a package-publishing warning when project artifacts can enter npm packages. */
|
|
110
|
+
export function getProjectArtifactPackagingWarning(cwd: string): string | undefined {
|
|
111
|
+
const packagePath = path.join(cwd, "package.json");
|
|
112
|
+
if (!fs.existsSync(packagePath)) return undefined;
|
|
113
|
+
|
|
114
|
+
let packageJson: Record<string, unknown>;
|
|
115
|
+
try {
|
|
116
|
+
const parsed: unknown = JSON.parse(fs.readFileSync(packagePath, "utf-8"));
|
|
117
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
|
|
118
|
+
packageJson = parsed as Record<string, unknown>;
|
|
119
|
+
} catch {
|
|
120
|
+
return undefined;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const filesIncludeArtifacts = filesIncludeProjectArtifacts(packageJson.files);
|
|
124
|
+
if (filesIncludeArtifacts === false) return undefined;
|
|
125
|
+
|
|
126
|
+
const npmIgnorePath = path.join(cwd, ".npmignore");
|
|
127
|
+
const ignorePath = fs.existsSync(npmIgnorePath) ? npmIgnorePath : path.join(cwd, ".gitignore");
|
|
128
|
+
if (filesIncludeArtifacts === undefined && ignoreFileExcludesProjectArtifacts(ignorePath)) return undefined;
|
|
129
|
+
|
|
130
|
+
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
|
+
}
|
|
132
|
+
|
|
133
|
+
export function getProjectSubagentsDir(cwd: string): string {
|
|
134
|
+
return path.join(cwd, PROJECT_ARTIFACT_ROOT);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function getProjectArtifactsDir(cwd: string): string {
|
|
138
|
+
return path.join(getProjectSubagentsDir(cwd), "artifacts");
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function getProjectChainRunsDir(cwd: string): string {
|
|
142
|
+
return path.join(getProjectSubagentsDir(cwd), "chain-runs");
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function getChainRunsDir(
|
|
146
|
+
projectCwd: string,
|
|
147
|
+
dirPreference: ArtifactDirPreference = "project",
|
|
148
|
+
): string {
|
|
149
|
+
switch (dirPreference) {
|
|
150
|
+
case "project":
|
|
151
|
+
return getProjectChainRunsDir(projectCwd);
|
|
152
|
+
case "session":
|
|
153
|
+
case "temp":
|
|
154
|
+
return CHAIN_RUNS_DIR;
|
|
155
|
+
default:
|
|
156
|
+
throw new Error(`Unsupported artifactDir ${JSON.stringify(dirPreference)}; expected "project", "session", or "temp".`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function getArtifactsDir(
|
|
161
|
+
sessionFile: string | null,
|
|
162
|
+
projectCwd?: string,
|
|
163
|
+
dirPreference: ArtifactDirPreference = "project",
|
|
164
|
+
): string {
|
|
165
|
+
switch (dirPreference) {
|
|
166
|
+
case "session":
|
|
167
|
+
if (sessionFile) {
|
|
168
|
+
const sessionDir = path.dirname(sessionFile);
|
|
169
|
+
return path.join(sessionDir, "subagent-artifacts");
|
|
170
|
+
}
|
|
171
|
+
return TEMP_ARTIFACTS_DIR;
|
|
172
|
+
case "temp":
|
|
173
|
+
return TEMP_ARTIFACTS_DIR;
|
|
174
|
+
case "project":
|
|
175
|
+
if (projectCwd) return getProjectArtifactsDir(projectCwd);
|
|
176
|
+
if (sessionFile) {
|
|
177
|
+
const sessionDir = path.dirname(sessionFile);
|
|
178
|
+
return path.join(sessionDir, "subagent-artifacts");
|
|
179
|
+
}
|
|
180
|
+
return TEMP_ARTIFACTS_DIR;
|
|
181
|
+
default:
|
|
182
|
+
throw new Error(`Unsupported artifactDir ${JSON.stringify(dirPreference)}; expected "project", "session", or "temp".`);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export function getArtifactPaths(artifactsDir: string, runId: string, agent: string, index?: number): ArtifactPaths {
|
|
187
|
+
const suffix = index !== undefined ? `_${index}` : "";
|
|
188
|
+
const safeAgent = agent.replace(/[^\w.-]/g, "_");
|
|
189
|
+
const base = `${runId}_${safeAgent}${suffix}`;
|
|
190
|
+
return {
|
|
191
|
+
inputPath: path.join(artifactsDir, `${base}_input.md`),
|
|
192
|
+
outputPath: path.join(artifactsDir, `${base}_output.md`),
|
|
193
|
+
jsonlPath: path.join(artifactsDir, `${base}.jsonl`),
|
|
194
|
+
transcriptPath: path.join(artifactsDir, `${base}_transcript.jsonl`),
|
|
195
|
+
metadataPath: path.join(artifactsDir, `${base}_meta.json`),
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export function ensureArtifactsDir(dir: string): void {
|
|
200
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export function writeArtifact(filePath: string, content: string): void {
|
|
204
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
205
|
+
fs.writeFileSync(filePath, content, "utf-8");
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export function formatOutputArtifactContent(input: {
|
|
209
|
+
output: string;
|
|
210
|
+
error?: string;
|
|
211
|
+
transcriptPath?: string;
|
|
212
|
+
metadataPath?: string;
|
|
213
|
+
}): string {
|
|
214
|
+
if (input.output.trim() || !input.error) return input.output;
|
|
215
|
+
const lines = ["Subagent run failed before producing output.", "", "Error:", input.error];
|
|
216
|
+
if (input.transcriptPath) lines.push("", `Transcript: ${input.transcriptPath}`);
|
|
217
|
+
if (input.metadataPath) lines.push(`Metadata: ${input.metadataPath}`);
|
|
218
|
+
return lines.join("\n");
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export function writeMetadata(filePath: string, metadata: object): void {
|
|
222
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
223
|
+
fs.writeFileSync(filePath, JSON.stringify(metadata, null, 2), "utf-8");
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export function appendJsonl(filePath: string, line: string): void {
|
|
227
|
+
fs.appendFileSync(filePath, `${line}\n`);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export function cleanupOldArtifacts(dir: string, maxAgeDays: number): void {
|
|
231
|
+
if (!fs.existsSync(dir)) return;
|
|
232
|
+
|
|
233
|
+
const markerPath = path.join(dir, CLEANUP_MARKER_FILE);
|
|
234
|
+
const now = Date.now();
|
|
235
|
+
|
|
236
|
+
if (fs.existsSync(markerPath)) {
|
|
237
|
+
const stat = fs.statSync(markerPath);
|
|
238
|
+
if (now - stat.mtimeMs < 24 * 60 * 60 * 1000) return;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1000;
|
|
242
|
+
const cutoff = now - maxAgeMs;
|
|
243
|
+
|
|
244
|
+
for (const file of fs.readdirSync(dir)) {
|
|
245
|
+
if (file === CLEANUP_MARKER_FILE) continue;
|
|
246
|
+
const filePath = path.join(dir, file);
|
|
247
|
+
try {
|
|
248
|
+
const stat = fs.statSync(filePath);
|
|
249
|
+
if (stat.mtimeMs < cutoff) {
|
|
250
|
+
fs.unlinkSync(filePath);
|
|
251
|
+
}
|
|
252
|
+
} catch {
|
|
253
|
+
// Artifact cleanup is best-effort housekeeping. Skip files that disappear
|
|
254
|
+
// or become unreadable while scanning so one bad entry does not block the rest.
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
fs.writeFileSync(markerPath, String(now));
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export function cleanupAllArtifactDirs(maxAgeDays: number): void {
|
|
262
|
+
cleanupOldArtifacts(TEMP_ARTIFACTS_DIR, maxAgeDays);
|
|
263
|
+
|
|
264
|
+
const sessionsBase = path.join(getAgentDir(), "sessions");
|
|
265
|
+
if (!fs.existsSync(sessionsBase)) return;
|
|
266
|
+
|
|
267
|
+
let dirs: string[];
|
|
268
|
+
try {
|
|
269
|
+
dirs = fs.readdirSync(sessionsBase);
|
|
270
|
+
} catch {
|
|
271
|
+
// Session artifact cleanup is best-effort. If the sessions root cannot be read,
|
|
272
|
+
// skip cleanup instead of failing extension startup.
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
for (const dir of dirs) {
|
|
277
|
+
const artifactsDir = path.join(sessionsBase, dir, "subagent-artifacts");
|
|
278
|
+
try {
|
|
279
|
+
cleanupOldArtifacts(artifactsDir, maxAgeDays);
|
|
280
|
+
} catch {
|
|
281
|
+
// Session cleanup is best-effort. Keep going so one unreadable session dir
|
|
282
|
+
// does not block cleanup for the rest.
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS, runFileSystemOperationWithRetry, waitForFileSystemRetry } from "./file-system-retry.ts";
|
|
4
|
+
|
|
5
|
+
type AtomicJsonFs = Pick<typeof fs, "mkdirSync" | "writeFileSync" | "renameSync" | "rmSync">;
|
|
6
|
+
|
|
7
|
+
type AtomicJsonWriterOptions = {
|
|
8
|
+
fs?: AtomicJsonFs;
|
|
9
|
+
now?: () => number;
|
|
10
|
+
pid?: number;
|
|
11
|
+
random?: () => number;
|
|
12
|
+
mode?: number;
|
|
13
|
+
retryRenameErrors?: boolean;
|
|
14
|
+
retryDirectoryErrors?: boolean;
|
|
15
|
+
retryDelaysMs?: readonly number[];
|
|
16
|
+
wait?: (delayMs: number) => void;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
function renameWithRetry(
|
|
20
|
+
fsImpl: AtomicJsonFs,
|
|
21
|
+
sourcePath: string,
|
|
22
|
+
targetPath: string,
|
|
23
|
+
retryDelaysMs: readonly number[],
|
|
24
|
+
wait: (delayMs: number) => void,
|
|
25
|
+
): void {
|
|
26
|
+
runFileSystemOperationWithRetry(() => {
|
|
27
|
+
fsImpl.renameSync(sourcePath, targetPath);
|
|
28
|
+
}, { retryDelaysMs, wait });
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function createAtomicJsonWriter(options: AtomicJsonWriterOptions = {}): (filePath: string, payload: object) => void {
|
|
32
|
+
const fsImpl = options.fs ?? fs;
|
|
33
|
+
const now = options.now ?? Date.now;
|
|
34
|
+
const pid = options.pid ?? process.pid;
|
|
35
|
+
const random = options.random ?? Math.random;
|
|
36
|
+
const mode = options.mode;
|
|
37
|
+
const retryRenameErrors = options.retryRenameErrors ?? process.platform === "win32";
|
|
38
|
+
const retryDirectoryErrors = options.retryDirectoryErrors ?? retryRenameErrors;
|
|
39
|
+
const retryDelaysMs = options.retryDelaysMs ?? DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS;
|
|
40
|
+
const renameRetryDelaysMs = retryRenameErrors ? retryDelaysMs : [];
|
|
41
|
+
const directoryRetryDelaysMs = retryDirectoryErrors ? retryDelaysMs : [];
|
|
42
|
+
const wait = options.wait ?? waitForFileSystemRetry;
|
|
43
|
+
return (filePath: string, payload: object): void => {
|
|
44
|
+
runFileSystemOperationWithRetry(() => {
|
|
45
|
+
fsImpl.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
46
|
+
}, { retryDelaysMs: directoryRetryDelaysMs, wait });
|
|
47
|
+
const tempPath = path.join(
|
|
48
|
+
path.dirname(filePath),
|
|
49
|
+
`.${path.basename(filePath)}.${pid}.${now()}.${random().toString(36).slice(2)}.tmp`,
|
|
50
|
+
);
|
|
51
|
+
try {
|
|
52
|
+
fsImpl.writeFileSync(tempPath, JSON.stringify(payload, null, 2), mode === undefined ? "utf-8" : { encoding: "utf-8", mode });
|
|
53
|
+
renameWithRetry(fsImpl, tempPath, filePath, renameRetryDelaysMs, wait);
|
|
54
|
+
} finally {
|
|
55
|
+
fsImpl.rmSync(tempPath, { force: true });
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export const writeAtomicJson = createAtomicJsonWriter();
|
|
61
|
+
export const writePrivateAtomicJson = createAtomicJsonWriter({ mode: 0o600 });
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import type { Message } from "@earendil-works/pi-ai";
|
|
4
|
+
import { extractTextFromContent, extractToolArgsPreview } from "./utils.ts";
|
|
5
|
+
|
|
6
|
+
const MAX_TOOL_PAYLOAD_BYTES = 32 * 1024;
|
|
7
|
+
const TOOL_PAYLOAD_TRUNCATION_MARKER = "\n\n… payload truncated";
|
|
8
|
+
|
|
9
|
+
function boundedPayload(value: unknown, maxBytes = MAX_TOOL_PAYLOAD_BYTES): string | undefined {
|
|
10
|
+
let text: string;
|
|
11
|
+
if (typeof value === "string") text = value;
|
|
12
|
+
else {
|
|
13
|
+
try {
|
|
14
|
+
const serialized = JSON.stringify(value, null, 2);
|
|
15
|
+
if (serialized === undefined) return undefined;
|
|
16
|
+
text = serialized;
|
|
17
|
+
} catch {
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
if (!text.trim()) return undefined;
|
|
22
|
+
const payload = Buffer.from(text, "utf-8");
|
|
23
|
+
if (payload.length <= maxBytes) return text;
|
|
24
|
+
const markerBytes = Buffer.byteLength(TOOL_PAYLOAD_TRUNCATION_MARKER, "utf-8");
|
|
25
|
+
let end = Math.max(0, maxBytes - markerBytes);
|
|
26
|
+
while (end > 0 && (payload[end]! & 0xc0) === 0x80) end--;
|
|
27
|
+
return `${payload.subarray(0, end).toString("utf-8")}${TOOL_PAYLOAD_TRUNCATION_MARKER}`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export const CHILD_TRANSCRIPT_ARTIFACT_VERSION = 1;
|
|
31
|
+
const DEFAULT_MAX_CHILD_TRANSCRIPT_BYTES = 50 * 1024 * 1024;
|
|
32
|
+
|
|
33
|
+
type ChildTranscriptSource = "foreground" | "async";
|
|
34
|
+
type ChildTranscriptRecordType = "message" | "tool_start" | "tool_end" | "stdout" | "stderr" | "truncated";
|
|
35
|
+
|
|
36
|
+
type ChildTranscriptMessage = Message & {
|
|
37
|
+
model?: string;
|
|
38
|
+
errorMessage?: string;
|
|
39
|
+
stopReason?: string;
|
|
40
|
+
usage?: unknown;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
interface ChildTranscriptEvent {
|
|
44
|
+
type?: string;
|
|
45
|
+
message?: ChildTranscriptMessage;
|
|
46
|
+
toolCallId?: string;
|
|
47
|
+
toolName?: string;
|
|
48
|
+
args?: unknown;
|
|
49
|
+
isError?: boolean;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
interface ChildTranscriptWriterInput {
|
|
53
|
+
transcriptPath: string;
|
|
54
|
+
source: ChildTranscriptSource;
|
|
55
|
+
runId: string;
|
|
56
|
+
agent: string;
|
|
57
|
+
childIndex?: number;
|
|
58
|
+
cwd: string;
|
|
59
|
+
maxBytes?: number;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface ChildTranscriptWriter {
|
|
63
|
+
path: string;
|
|
64
|
+
writeInitialUserMessage(prompt: string): void;
|
|
65
|
+
writeChildEvent(event: ChildTranscriptEvent): void;
|
|
66
|
+
writeStdoutLine(line: string): void;
|
|
67
|
+
writeStderrLine(line: string): void;
|
|
68
|
+
writeStderrText(text: string): void;
|
|
69
|
+
getError(): string | undefined;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function errorMessage(error: unknown): string {
|
|
73
|
+
return error instanceof Error ? error.message : String(error);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function finiteNumber(value: unknown): number | undefined {
|
|
77
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function normalizeUsage(value: unknown): { input: number; output: number; cacheRead: number; cacheWrite: number; cost: number } | undefined {
|
|
81
|
+
if (!value || typeof value !== "object") return undefined;
|
|
82
|
+
const raw = value as Record<string, unknown>;
|
|
83
|
+
const rawCost = raw.cost;
|
|
84
|
+
const cost = rawCost && typeof rawCost === "object"
|
|
85
|
+
? finiteNumber((rawCost as { total?: unknown }).total) ?? 0
|
|
86
|
+
: finiteNumber(rawCost) ?? 0;
|
|
87
|
+
return {
|
|
88
|
+
input: finiteNumber(raw.input) ?? finiteNumber(raw.inputTokens) ?? 0,
|
|
89
|
+
output: finiteNumber(raw.output) ?? finiteNumber(raw.outputTokens) ?? 0,
|
|
90
|
+
cacheRead: finiteNumber(raw.cacheRead) ?? 0,
|
|
91
|
+
cacheWrite: finiteNumber(raw.cacheWrite) ?? 0,
|
|
92
|
+
cost,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function eventArgs(event: ChildTranscriptEvent): Record<string, unknown> {
|
|
97
|
+
return event.args && typeof event.args === "object" && !Array.isArray(event.args)
|
|
98
|
+
? event.args as Record<string, unknown>
|
|
99
|
+
: {};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function createChildTranscriptWriter(input: ChildTranscriptWriterInput): ChildTranscriptWriter {
|
|
103
|
+
let bytesWritten = 0;
|
|
104
|
+
let writeError: string | undefined;
|
|
105
|
+
let truncated = false;
|
|
106
|
+
const maxBytes = input.maxBytes ?? DEFAULT_MAX_CHILD_TRANSCRIPT_BYTES;
|
|
107
|
+
|
|
108
|
+
const baseRecord = (recordType: ChildTranscriptRecordType) => {
|
|
109
|
+
const ts = Date.now();
|
|
110
|
+
return {
|
|
111
|
+
version: CHILD_TRANSCRIPT_ARTIFACT_VERSION,
|
|
112
|
+
recordType,
|
|
113
|
+
source: input.source,
|
|
114
|
+
runId: input.runId,
|
|
115
|
+
agent: input.agent,
|
|
116
|
+
...(input.childIndex !== undefined ? { childIndex: input.childIndex } : {}),
|
|
117
|
+
cwd: input.cwd,
|
|
118
|
+
ts,
|
|
119
|
+
timestamp: new Date(ts).toISOString(),
|
|
120
|
+
};
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
const writeTruncatedMarker = () => {
|
|
124
|
+
truncated = true;
|
|
125
|
+
const marker = `${JSON.stringify({
|
|
126
|
+
...baseRecord("truncated"),
|
|
127
|
+
maxBytes,
|
|
128
|
+
message: `Child transcript exceeded ${maxBytes} bytes; further records were omitted.`,
|
|
129
|
+
})}\n`;
|
|
130
|
+
const markerBytes = Buffer.byteLength(marker, "utf-8");
|
|
131
|
+
if (bytesWritten + markerBytes > maxBytes) return false;
|
|
132
|
+
try {
|
|
133
|
+
fs.appendFileSync(input.transcriptPath, marker, "utf-8");
|
|
134
|
+
bytesWritten += markerBytes;
|
|
135
|
+
return true;
|
|
136
|
+
} catch (error) {
|
|
137
|
+
writeError = `Failed to write child transcript '${input.transcriptPath}': ${errorMessage(error)}`;
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
const writeRecord = (record: Record<string, unknown>) => {
|
|
143
|
+
if (writeError || truncated) return;
|
|
144
|
+
const line = `${JSON.stringify(record)}\n`;
|
|
145
|
+
const bytes = Buffer.byteLength(line, "utf-8");
|
|
146
|
+
if (bytesWritten + bytes > maxBytes) {
|
|
147
|
+
writeTruncatedMarker();
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
const markerProbe = `${JSON.stringify({
|
|
151
|
+
...baseRecord("truncated"),
|
|
152
|
+
maxBytes,
|
|
153
|
+
message: `Child transcript exceeded ${maxBytes} bytes; further records were omitted.`,
|
|
154
|
+
})}\n`;
|
|
155
|
+
if (bytesWritten + bytes + Buffer.byteLength(markerProbe, "utf-8") > maxBytes) {
|
|
156
|
+
writeTruncatedMarker();
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
try {
|
|
160
|
+
fs.appendFileSync(input.transcriptPath, line, "utf-8");
|
|
161
|
+
bytesWritten += bytes;
|
|
162
|
+
} catch (error) {
|
|
163
|
+
writeError = `Failed to write child transcript '${input.transcriptPath}': ${errorMessage(error)}`;
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
try {
|
|
168
|
+
fs.mkdirSync(path.dirname(input.transcriptPath), { recursive: true });
|
|
169
|
+
fs.writeFileSync(input.transcriptPath, "", "utf-8");
|
|
170
|
+
} catch (error) {
|
|
171
|
+
writeError = `Failed to initialize child transcript '${input.transcriptPath}': ${errorMessage(error)}`;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const writeMessage = (sourceEventType: string, message: ChildTranscriptMessage) => {
|
|
175
|
+
const text = extractTextFromContent(message.content);
|
|
176
|
+
if (message.role === "toolResult") {
|
|
177
|
+
const output = boundedPayload(text);
|
|
178
|
+
writeRecord({
|
|
179
|
+
...baseRecord("message"),
|
|
180
|
+
sourceEventType,
|
|
181
|
+
role: message.role,
|
|
182
|
+
toolCallId: message.toolCallId,
|
|
183
|
+
toolName: message.toolName,
|
|
184
|
+
isError: message.isError,
|
|
185
|
+
...(output ? { text: output, outputTruncated: output.includes("… payload truncated") } : {}),
|
|
186
|
+
message: {
|
|
187
|
+
role: message.role,
|
|
188
|
+
toolCallId: message.toolCallId,
|
|
189
|
+
toolName: message.toolName,
|
|
190
|
+
isError: message.isError,
|
|
191
|
+
content: output ? [{ type: "text", text: output }] : [],
|
|
192
|
+
...(message.timestamp !== undefined ? { timestamp: message.timestamp } : {}),
|
|
193
|
+
},
|
|
194
|
+
});
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
writeRecord({
|
|
198
|
+
...baseRecord("message"),
|
|
199
|
+
sourceEventType,
|
|
200
|
+
role: message.role,
|
|
201
|
+
...(text ? { text } : {}),
|
|
202
|
+
...(message.model ? { model: message.model } : {}),
|
|
203
|
+
...(message.stopReason ? { stopReason: message.stopReason } : {}),
|
|
204
|
+
...(message.errorMessage ? { errorMessage: message.errorMessage } : {}),
|
|
205
|
+
...(message.usage ? { usage: normalizeUsage(message.usage) } : {}),
|
|
206
|
+
message,
|
|
207
|
+
});
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
return {
|
|
211
|
+
path: input.transcriptPath,
|
|
212
|
+
writeInitialUserMessage(prompt: string) {
|
|
213
|
+
writeRecord({
|
|
214
|
+
...baseRecord("message"),
|
|
215
|
+
sourceEventType: "initial_prompt",
|
|
216
|
+
role: "user",
|
|
217
|
+
text: prompt,
|
|
218
|
+
message: { role: "user", content: [{ type: "text", text: prompt }] },
|
|
219
|
+
});
|
|
220
|
+
},
|
|
221
|
+
writeChildEvent(event: ChildTranscriptEvent) {
|
|
222
|
+
if ((event.type === "message_end" || event.type === "tool_result_end") && event.message) {
|
|
223
|
+
writeMessage(event.type, event.message);
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
if (event.type === "tool_execution_start" && event.toolName) {
|
|
227
|
+
const args = eventArgs(event);
|
|
228
|
+
const argsPayload = boundedPayload(args);
|
|
229
|
+
writeRecord({
|
|
230
|
+
...baseRecord("tool_start"),
|
|
231
|
+
sourceEventType: event.type,
|
|
232
|
+
...(event.toolCallId ? { toolCallId: event.toolCallId } : {}),
|
|
233
|
+
toolName: event.toolName,
|
|
234
|
+
...(Object.keys(args).length > 0 ? { argsPreview: extractToolArgsPreview(args) } : {}),
|
|
235
|
+
...(argsPayload ? { argsPayload } : {}),
|
|
236
|
+
});
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
if (event.type === "tool_execution_end") {
|
|
240
|
+
writeRecord({
|
|
241
|
+
...baseRecord("tool_end"),
|
|
242
|
+
sourceEventType: event.type,
|
|
243
|
+
...(event.toolCallId ? { toolCallId: event.toolCallId } : {}),
|
|
244
|
+
...(event.toolName ? { toolName: event.toolName } : {}),
|
|
245
|
+
...(typeof event.isError === "boolean" ? { isError: event.isError } : {}),
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
},
|
|
249
|
+
writeStdoutLine(line: string) {
|
|
250
|
+
if (!line.trim()) return;
|
|
251
|
+
writeRecord({ ...baseRecord("stdout"), text: line });
|
|
252
|
+
},
|
|
253
|
+
writeStderrLine(line: string) {
|
|
254
|
+
if (!line.trim()) return;
|
|
255
|
+
writeRecord({ ...baseRecord("stderr"), text: line });
|
|
256
|
+
},
|
|
257
|
+
writeStderrText(text: string) {
|
|
258
|
+
for (const line of text.split(/\r?\n/)) this.writeStderrLine(line);
|
|
259
|
+
},
|
|
260
|
+
getError() {
|
|
261
|
+
return writeError;
|
|
262
|
+
},
|
|
263
|
+
};
|
|
264
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
interface TimerApi {
|
|
2
|
+
setTimeout(handler: () => void, delayMs: number): unknown;
|
|
3
|
+
clearTimeout(handle: unknown): void;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
interface FileCoalescer {
|
|
7
|
+
schedule(file: string, delayMs?: number): boolean;
|
|
8
|
+
clear(): void;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const defaultTimerApi: TimerApi = {
|
|
12
|
+
setTimeout: (handler, delayMs) => setTimeout(handler, delayMs),
|
|
13
|
+
clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export function createFileCoalescer(
|
|
17
|
+
handler: (file: string) => void,
|
|
18
|
+
defaultDelayMs: number,
|
|
19
|
+
timerApi: TimerApi = defaultTimerApi,
|
|
20
|
+
): FileCoalescer {
|
|
21
|
+
const pending = new Map<string, unknown>();
|
|
22
|
+
|
|
23
|
+
return {
|
|
24
|
+
schedule(file: string, delayMs = defaultDelayMs): boolean {
|
|
25
|
+
if (pending.has(file)) return false;
|
|
26
|
+
const timer = timerApi.setTimeout(() => {
|
|
27
|
+
pending.delete(file);
|
|
28
|
+
handler(file);
|
|
29
|
+
}, delayMs);
|
|
30
|
+
pending.set(file, timer);
|
|
31
|
+
return true;
|
|
32
|
+
},
|
|
33
|
+
clear(): void {
|
|
34
|
+
for (const timer of pending.values()) {
|
|
35
|
+
timerApi.clearTimeout(timer);
|
|
36
|
+
}
|
|
37
|
+
pending.clear();
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
}
|