@ashx-j/lunr 0.2.27 → 0.2.28
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 +10 -1
- package/dist/builtin-extensions/narumiruna-pi-goal/src/accounting.d.ts.map +1 -1
- package/dist/builtin-extensions/narumiruna-pi-goal/src/accounting.js +5 -2
- package/dist/builtin-extensions/narumiruna-pi-goal/src/accounting.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/chain-root-attachment.d.ts +4 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/chain-root-attachment.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/chain-root-attachment.js +2 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/chain-root-attachment.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/notify.d.ts +5 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/notify.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/notify.js +2 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/notify.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.d.ts +5 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.js +68 -40
- package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.d.ts +0 -3
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js +28 -4
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js +1 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/session-tokens.d.ts +7 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/session-tokens.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/session-tokens.js +70 -38
- package/dist/builtin-extensions/pi-subagents/src/shared/session-tokens.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts +9 -0
- package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/types.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js +13 -62
- package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/tui/render.js +1 -1
- package/dist/builtin-extensions/pi-subagents/src/tui/render.js.map +1 -1
- package/dist/builtin-extensions/pi-tps.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-tps.js +10 -2
- package/dist/builtin-extensions/pi-tps.js.map +1 -1
- package/dist/catalog/models.json +1 -1
- package/dist/catalog/providers/google-vertex.json +1 -1
- package/dist/catalog/providers/google.json +1 -1
- package/dist/catalog/publication.json +3 -3
- package/dist/core/agent-session.d.ts +6 -15
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +35 -50
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/cache-stats.d.ts +1 -1
- package/dist/core/cache-stats.d.ts.map +1 -1
- package/dist/core/cache-stats.js +1 -1
- package/dist/core/cache-stats.js.map +1 -1
- package/dist/core/compaction/branch-summarization.d.ts +2 -1
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/core/compaction/branch-summarization.js +1 -0
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +5 -11
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +38 -92
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/context-breakdown.d.ts +2 -2
- package/dist/core/context-breakdown.d.ts.map +1 -1
- package/dist/core/context-breakdown.js +22 -20
- package/dist/core/context-breakdown.js.map +1 -1
- package/dist/core/extensions/types.d.ts +3 -1
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/session-manager.d.ts +5 -1
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +16 -1
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/usage-accounting.d.ts +47 -0
- package/dist/core/usage-accounting.d.ts.map +1 -0
- package/dist/core/usage-accounting.js +205 -0
- package/dist/core/usage-accounting.js.map +1 -0
- package/dist/core/usage-history.d.ts +1 -18
- package/dist/core/usage-history.d.ts.map +1 -1
- package/dist/core/usage-history.js +46 -114
- package/dist/core/usage-history.js.map +1 -1
- package/dist/gateway/mobile-commands.d.ts.map +1 -1
- package/dist/gateway/mobile-commands.js +13 -1
- package/dist/gateway/mobile-commands.js.map +1 -1
- package/dist/modes/interactive/components/context-view.d.ts.map +1 -1
- package/dist/modes/interactive/components/context-view.js +2 -2
- package/dist/modes/interactive/components/context-view.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +8 -12
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/usage-view.d.ts +5 -0
- package/dist/modes/interactive/components/usage-view.d.ts.map +1 -1
- package/dist/modes/interactive/components/usage-view.js +21 -6
- package/dist/modes/interactive/components/usage-view.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +1 -5
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +55 -22
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/node-runtime/{agent-session-services-KDMSPQDY.js → agent-session-services-RTUGP3XR.js} +5 -4
- package/dist/node-runtime/{builtin-extensions-OX6KELNX.js → builtin-extensions-N4EUD6SB.js} +1 -1
- package/dist/node-runtime/{chunk-A2WO6WIN.js → chunk-4QRUZ64T.js} +11 -5
- package/dist/node-runtime/{chunk-ZDJUR45D.js → chunk-BMRXLQWQ.js} +41 -38
- package/dist/node-runtime/{chunk-MQPKUHRN.js → chunk-DFMPRAQQ.js} +8 -8
- package/dist/node-runtime/{chunk-C3P6Q3B2.js → chunk-E5DQGNJI.js} +10 -10
- package/dist/node-runtime/{chunk-FIRA54AC.js → chunk-ICKGAKWX.js} +22 -55
- package/dist/node-runtime/{chunk-JWEVT363.js → chunk-JEK35V2M.js} +14 -8
- package/dist/node-runtime/{chunk-EPR2F3GU.js → chunk-PWHTSQC4.js} +15 -1
- package/dist/node-runtime/{chunk-AYHH7YSD.js → chunk-QT3F6UEV.js} +61 -30
- package/dist/node-runtime/{chunk-JQYNHAKX.js → chunk-RY3FJ6WI.js} +29 -27
- package/dist/node-runtime/{chunk-I2H5QMWW.js → chunk-STMX7W5I.js} +1 -1
- package/dist/node-runtime/chunk-SWWHZ2RI.js +158 -0
- package/dist/node-runtime/{chunk-QNVMKNNN.js → chunk-U3YVZ6UC.js} +4 -4
- package/dist/node-runtime/{command-3HMSY6W2.js → command-YRT7I2BW.js} +1 -1
- package/dist/node-runtime/{commands-OCSSEEWJ.js → commands-2ETOWWRA.js} +5 -5
- package/dist/node-runtime/{export-html-BRWF5AHI.js → export-html-DBQRRMAY.js} +1 -1
- package/dist/node-runtime/{gateway-6623C2U3.js → gateway-V6K2CDWN.js} +9 -9
- package/dist/node-runtime/{goal-AIHEDUYA.js → goal-J7TYMOBK.js} +9 -3
- package/dist/node-runtime/index.js +9 -8
- package/dist/node-runtime/{interactive-mode-FM5DNUSW.js → interactive-mode-ASZ7APYP.js} +7 -6
- package/dist/node-runtime/{lunr-cron-LKVA5CZZ.js → lunr-cron-WD3YH4CR.js} +4 -4
- package/dist/node-runtime/main.js +7 -6
- package/dist/node-runtime/{mobile-commands-XT3NQXLD.js → mobile-commands-ICUXFW5V.js} +2 -2
- package/dist/node-runtime/{pi-subagents-LT3CTO4E.js → pi-subagents-QPU3OXE4.js} +17 -62
- package/dist/node-runtime/rpc-entry.js +7 -6
- package/dist/node-runtime/{session-handoff-LNSPDTKY.js → session-handoff-LYH53ESV.js} +2 -2
- package/dist/node-runtime/{session-manager-YIFIAVGC.js → session-manager-ZJ3N5Q74.js} +1 -1
- package/dist/node-runtime/{subagent-executor-Q5F7DBVM.js → subagent-executor-UI6SHG3X.js} +294 -231
- package/docs/features.md +10 -0
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/install-lock/package-lock.json +24 -24
- package/install-lock/package.json +2 -2
- package/npm-shrinkwrap.json +21 -21
- package/package.json +7 -7
|
@@ -218,12 +218,16 @@ import "./chunk-RYRGL7P4.js";
|
|
|
218
218
|
import "./chunk-ES6PBSIE.js";
|
|
219
219
|
import {
|
|
220
220
|
SessionManager
|
|
221
|
-
} from "./chunk-
|
|
221
|
+
} from "./chunk-PWHTSQC4.js";
|
|
222
222
|
import "./chunk-FVDOXRUD.js";
|
|
223
223
|
import "./chunk-UJOCPOMX.js";
|
|
224
224
|
import "./chunk-IMLCWLPI.js";
|
|
225
225
|
import "./chunk-MNQXDFPV.js";
|
|
226
226
|
import "./chunk-RQ2Q5IYR.js";
|
|
227
|
+
import {
|
|
228
|
+
collectUsageRequests,
|
|
229
|
+
totalRequestUsage
|
|
230
|
+
} from "./chunk-SWWHZ2RI.js";
|
|
227
231
|
import "./chunk-RHCGYWO7.js";
|
|
228
232
|
import "./chunk-QW3AAHWN.js";
|
|
229
233
|
import "./chunk-JL4HYQXK.js";
|
|
@@ -233,8 +237,8 @@ import "./chunk-BRJX2PRC.js";
|
|
|
233
237
|
|
|
234
238
|
// packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js
|
|
235
239
|
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
236
|
-
import * as
|
|
237
|
-
import * as
|
|
240
|
+
import * as fs16 from "node:fs";
|
|
241
|
+
import * as path16 from "node:path";
|
|
238
242
|
|
|
239
243
|
// packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-clarify.js
|
|
240
244
|
import { matchesKey, visibleWidth, truncateToWidth } from "@ashx-j/lunr-tui";
|
|
@@ -918,16 +922,72 @@ var ChainClarifyComponent = class {
|
|
|
918
922
|
};
|
|
919
923
|
|
|
920
924
|
// packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.js
|
|
921
|
-
import * as
|
|
922
|
-
import * as
|
|
925
|
+
import * as fs8 from "node:fs";
|
|
926
|
+
import * as path7 from "node:path";
|
|
927
|
+
|
|
928
|
+
// packages/coding-agent/dist/builtin-extensions/pi-subagents/src/shared/session-tokens.js
|
|
929
|
+
import * as fs from "node:fs";
|
|
930
|
+
import * as path from "node:path";
|
|
931
|
+
function parseSessionRequests(sessionPath) {
|
|
932
|
+
if (!sessionPath)
|
|
933
|
+
return [];
|
|
934
|
+
try {
|
|
935
|
+
let files = fs.statSync(sessionPath).isDirectory() ? fs.readdirSync(sessionPath).filter((name) => name.endsWith(".jsonl")).map((name) => path.join(sessionPath, name)) : [sessionPath], requests = /* @__PURE__ */ new Map();
|
|
936
|
+
for (let file of files) {
|
|
937
|
+
let entries = [];
|
|
938
|
+
for (let line of fs.readFileSync(file, "utf-8").split(`
|
|
939
|
+
`))
|
|
940
|
+
try {
|
|
941
|
+
let entry = JSON.parse(line);
|
|
942
|
+
entry?.type && entries.push(entry);
|
|
943
|
+
} catch {
|
|
944
|
+
}
|
|
945
|
+
for (let request of collectUsageRequests(entries))
|
|
946
|
+
requests.set(request.id, request);
|
|
947
|
+
}
|
|
948
|
+
return [...requests.values()];
|
|
949
|
+
} catch {
|
|
950
|
+
return [];
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
function parseSessionUsage(sessionPath) {
|
|
954
|
+
let requests = parseSessionRequests(sessionPath);
|
|
955
|
+
if (requests.length === 0)
|
|
956
|
+
return null;
|
|
957
|
+
let total = totalRequestUsage(requests);
|
|
958
|
+
return {
|
|
959
|
+
input: total.input,
|
|
960
|
+
output: total.output,
|
|
961
|
+
cacheRead: total.cacheRead,
|
|
962
|
+
cacheWrite: total.cacheWrite,
|
|
963
|
+
cost: total.cost,
|
|
964
|
+
turns: requests.length,
|
|
965
|
+
unknownRequests: total.unknownRequests,
|
|
966
|
+
partialRequests: total.partialRequests,
|
|
967
|
+
unknownCosts: total.unknownCosts
|
|
968
|
+
};
|
|
969
|
+
}
|
|
970
|
+
function sessionUsageDelta(current, previous) {
|
|
971
|
+
return {
|
|
972
|
+
unknownRequests: Math.max(0, (current.unknownRequests ?? 0) - (previous?.unknownRequests ?? 0)),
|
|
973
|
+
partialRequests: Math.max(0, (current.partialRequests ?? 0) - (previous?.partialRequests ?? 0)),
|
|
974
|
+
unknownCosts: Math.max(0, (current.unknownCosts ?? 0) - (previous?.unknownCosts ?? 0)),
|
|
975
|
+
input: Math.max(0, current.input - (previous?.input ?? 0)),
|
|
976
|
+
output: Math.max(0, current.output - (previous?.output ?? 0)),
|
|
977
|
+
cacheRead: Math.max(0, current.cacheRead - (previous?.cacheRead ?? 0)),
|
|
978
|
+
cacheWrite: Math.max(0, current.cacheWrite - (previous?.cacheWrite ?? 0)),
|
|
979
|
+
cost: Math.max(0, current.cost - (previous?.cost ?? 0)),
|
|
980
|
+
turns: Math.max(0, current.turns - (previous?.turns ?? 0))
|
|
981
|
+
};
|
|
982
|
+
}
|
|
923
983
|
|
|
924
984
|
// packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js
|
|
925
985
|
import { spawn } from "node:child_process";
|
|
926
986
|
import { existsSync as existsSync2, unlinkSync } from "node:fs";
|
|
927
987
|
|
|
928
988
|
// packages/coding-agent/dist/builtin-extensions/pi-subagents/src/shared/child-transcript.js
|
|
929
|
-
import * as
|
|
930
|
-
import * as
|
|
989
|
+
import * as fs2 from "node:fs";
|
|
990
|
+
import * as path2 from "node:path";
|
|
931
991
|
var CHILD_TRANSCRIPT_ARTIFACT_VERSION = 1, DEFAULT_MAX_CHILD_TRANSCRIPT_BYTES = 50 * 1024 * 1024;
|
|
932
992
|
function errorMessage(error) {
|
|
933
993
|
return error instanceof Error ? error.message : String(error);
|
|
@@ -975,7 +1035,7 @@ function createChildTranscriptWriter(input) {
|
|
|
975
1035
|
if (bytesWritten + markerBytes > maxBytes)
|
|
976
1036
|
return !1;
|
|
977
1037
|
try {
|
|
978
|
-
return
|
|
1038
|
+
return fs2.appendFileSync(input.transcriptPath, marker, "utf-8"), bytesWritten += markerBytes, !0;
|
|
979
1039
|
} catch (error) {
|
|
980
1040
|
return writeError = `Failed to write child transcript '${input.transcriptPath}': ${errorMessage(error)}`, !1;
|
|
981
1041
|
}
|
|
@@ -999,13 +1059,13 @@ function createChildTranscriptWriter(input) {
|
|
|
999
1059
|
return;
|
|
1000
1060
|
}
|
|
1001
1061
|
try {
|
|
1002
|
-
|
|
1062
|
+
fs2.appendFileSync(input.transcriptPath, line, "utf-8"), bytesWritten += bytes;
|
|
1003
1063
|
} catch (error) {
|
|
1004
1064
|
writeError = `Failed to write child transcript '${input.transcriptPath}': ${errorMessage(error)}`;
|
|
1005
1065
|
}
|
|
1006
1066
|
};
|
|
1007
1067
|
try {
|
|
1008
|
-
|
|
1068
|
+
fs2.mkdirSync(path2.dirname(input.transcriptPath), { recursive: !0 }), fs2.writeFileSync(input.transcriptPath, "", "utf-8");
|
|
1009
1069
|
} catch (error) {
|
|
1010
1070
|
writeError = `Failed to initialize child transcript '${input.transcriptPath}': ${errorMessage(error)}`;
|
|
1011
1071
|
}
|
|
@@ -1227,17 +1287,17 @@ function evaluateCompletionMutationGuard(input) {
|
|
|
1227
1287
|
}
|
|
1228
1288
|
|
|
1229
1289
|
// packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-spawn.js
|
|
1230
|
-
import * as
|
|
1231
|
-
import * as
|
|
1290
|
+
import * as fs3 from "node:fs";
|
|
1291
|
+
import * as path3 from "node:path";
|
|
1232
1292
|
import { fileURLToPath } from "node:url";
|
|
1233
1293
|
var PI_CODING_AGENT_PACKAGE = "@ashx-j/lunr", PI_SUBAGENT_PI_BINARY_ENV = "PI_SUBAGENT_PI_BINARY";
|
|
1234
1294
|
function findPiPackageRootFromEntry(entryPoint) {
|
|
1235
|
-
let dir =
|
|
1236
|
-
for (; dir !==
|
|
1237
|
-
let packageJsonPath =
|
|
1238
|
-
if (
|
|
1295
|
+
let dir = path3.dirname(entryPoint);
|
|
1296
|
+
for (; dir !== path3.dirname(dir); ) {
|
|
1297
|
+
let packageJsonPath = path3.join(dir, "package.json");
|
|
1298
|
+
if (fs3.existsSync(packageJsonPath) && JSON.parse(fs3.readFileSync(packageJsonPath, "utf-8")).name === PI_CODING_AGENT_PACKAGE)
|
|
1239
1299
|
return dir;
|
|
1240
|
-
dir =
|
|
1300
|
+
dir = path3.dirname(dir);
|
|
1241
1301
|
}
|
|
1242
1302
|
}
|
|
1243
1303
|
function resolveInstalledPiPackageRoot() {
|
|
@@ -1246,7 +1306,7 @@ function resolveInstalledPiPackageRoot() {
|
|
|
1246
1306
|
function resolvePiPackageRoot() {
|
|
1247
1307
|
try {
|
|
1248
1308
|
let entry = process.argv[1];
|
|
1249
|
-
return entry ? findPiPackageRootFromEntry(
|
|
1309
|
+
return entry ? findPiPackageRootFromEntry(fs3.realpathSync(entry)) : void 0;
|
|
1250
1310
|
} catch {
|
|
1251
1311
|
return;
|
|
1252
1312
|
}
|
|
@@ -1255,10 +1315,10 @@ function isRunnableNodeScript(filePath, existsSync11) {
|
|
|
1255
1315
|
return existsSync11(filePath) ? /\.(?:mjs|cjs|js)$/i.test(filePath) : !1;
|
|
1256
1316
|
}
|
|
1257
1317
|
function normalizePath(filePath) {
|
|
1258
|
-
return
|
|
1318
|
+
return path3.isAbsolute(filePath) ? filePath : path3.resolve(filePath);
|
|
1259
1319
|
}
|
|
1260
1320
|
function resolvePiCliScript(deps = {}) {
|
|
1261
|
-
let existsSync11 = deps.existsSync ??
|
|
1321
|
+
let existsSync11 = deps.existsSync ?? fs3.existsSync, realpathSync5 = deps.realpathSync ?? fs3.realpathSync, readFileSync9 = deps.readFileSync ?? ((filePath, encoding) => fs3.readFileSync(filePath, encoding)), argv1 = deps.argv1 ?? process.argv[1];
|
|
1262
1322
|
if (argv1) {
|
|
1263
1323
|
let argvPath = normalizePath(argv1);
|
|
1264
1324
|
if (isRunnableNodeScript(argvPath, existsSync11))
|
|
@@ -1273,15 +1333,15 @@ function resolvePiCliScript(deps = {}) {
|
|
|
1273
1333
|
let packageJsonPath = (deps.resolvePackageJson ?? (() => {
|
|
1274
1334
|
let root = deps.piPackageRoot ?? resolvePiPackageRoot();
|
|
1275
1335
|
if (root)
|
|
1276
|
-
return
|
|
1336
|
+
return path3.join(root, "package.json");
|
|
1277
1337
|
let packageRoot = deps.resolvePackageEntry ? findPiPackageRootFromEntry(deps.resolvePackageEntry()) : resolveInstalledPiPackageRoot();
|
|
1278
1338
|
if (!packageRoot)
|
|
1279
1339
|
throw new Error(`Could not resolve ${PI_CODING_AGENT_PACKAGE} package root`);
|
|
1280
|
-
return
|
|
1281
|
-
}))(), binField = JSON.parse(
|
|
1340
|
+
return path3.join(packageRoot, "package.json");
|
|
1341
|
+
}))(), binField = JSON.parse(readFileSync9(packageJsonPath, "utf-8")).bin, binPath = typeof binField == "string" ? binField : binField?.pi ?? Object.values(binField ?? {})[0];
|
|
1282
1342
|
if (!binPath)
|
|
1283
1343
|
return;
|
|
1284
|
-
let candidate =
|
|
1344
|
+
let candidate = path3.resolve(path3.dirname(packageJsonPath), binPath);
|
|
1285
1345
|
if (isRunnableNodeScript(candidate, existsSync11))
|
|
1286
1346
|
return candidate;
|
|
1287
1347
|
} catch {
|
|
@@ -1300,7 +1360,7 @@ function getPiSpawnCommand(args, deps = {}) {
|
|
|
1300
1360
|
}
|
|
1301
1361
|
|
|
1302
1362
|
// packages/coding-agent/dist/builtin-extensions/pi-subagents/src/shared/jsonl-writer.js
|
|
1303
|
-
import * as
|
|
1363
|
+
import * as fs4 from "node:fs";
|
|
1304
1364
|
var DEFAULT_MAX_JSONL_BYTES = 50 * 1024 * 1024;
|
|
1305
1365
|
function createJsonlWriter(filePath, source, deps = {}) {
|
|
1306
1366
|
if (!filePath)
|
|
@@ -1310,7 +1370,7 @@ function createJsonlWriter(filePath, source, deps = {}) {
|
|
|
1310
1370
|
async close() {
|
|
1311
1371
|
}
|
|
1312
1372
|
};
|
|
1313
|
-
let createWriteStream2 = deps.createWriteStream ?? ((targetPath) =>
|
|
1373
|
+
let createWriteStream2 = deps.createWriteStream ?? ((targetPath) => fs4.createWriteStream(targetPath, { flags: "a" })), stream;
|
|
1314
1374
|
try {
|
|
1315
1375
|
stream = createWriteStream2(filePath);
|
|
1316
1376
|
} catch {
|
|
@@ -1375,12 +1435,12 @@ function attachPostExitStdioGuard(child, options) {
|
|
|
1375
1435
|
}
|
|
1376
1436
|
|
|
1377
1437
|
// packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/shared/single-output.js
|
|
1378
|
-
import * as
|
|
1379
|
-
import * as
|
|
1438
|
+
import * as fs5 from "node:fs";
|
|
1439
|
+
import * as path4 from "node:path";
|
|
1380
1440
|
function extractChildWrittenOutput(messages, outputPath, cwd) {
|
|
1381
1441
|
if (!messages?.length || !outputPath)
|
|
1382
1442
|
return;
|
|
1383
|
-
let resolvedTarget =
|
|
1443
|
+
let resolvedTarget = path4.resolve(cwd ?? ".", outputPath), comparableTarget = process.platform === "win32" ? resolvedTarget.toLowerCase() : resolvedTarget, successfulCallIds = /* @__PURE__ */ new Set();
|
|
1384
1444
|
for (let message of messages)
|
|
1385
1445
|
message.role === "toolResult" && message.isError === !1 && typeof message.toolCallId == "string" && successfulCallIds.add(message.toolCallId);
|
|
1386
1446
|
let content;
|
|
@@ -1392,7 +1452,7 @@ function extractChildWrittenOutput(messages, outputPath, cwd) {
|
|
|
1392
1452
|
let args = typeof part.arguments == "object" && part.arguments !== null && !Array.isArray(part.arguments) ? part.arguments : {};
|
|
1393
1453
|
if (typeof args.path != "string" || typeof args.content != "string")
|
|
1394
1454
|
continue;
|
|
1395
|
-
let resolvedWritePath =
|
|
1455
|
+
let resolvedWritePath = path4.resolve(cwd ?? ".", args.path);
|
|
1396
1456
|
(process.platform === "win32" ? resolvedWritePath.toLowerCase() : resolvedWritePath) === comparableTarget && (content = args.content);
|
|
1397
1457
|
}
|
|
1398
1458
|
return content;
|
|
@@ -1408,12 +1468,12 @@ function normalizeSingleOutputOverride(output, defaultOutput) {
|
|
|
1408
1468
|
function resolveSingleOutputPath(output, runtimeCwd, requestedCwd, relativeBaseDir) {
|
|
1409
1469
|
if (typeof output != "string" || !output || output === "false" || output === "true")
|
|
1410
1470
|
return;
|
|
1411
|
-
if (
|
|
1471
|
+
if (path4.isAbsolute(output))
|
|
1412
1472
|
return output;
|
|
1413
1473
|
if (relativeBaseDir)
|
|
1414
|
-
return
|
|
1415
|
-
let baseCwd = requestedCwd ?
|
|
1416
|
-
return
|
|
1474
|
+
return path4.resolve(relativeBaseDir, output);
|
|
1475
|
+
let baseCwd = requestedCwd ? path4.isAbsolute(requestedCwd) ? requestedCwd : path4.resolve(runtimeCwd, requestedCwd) : runtimeCwd;
|
|
1476
|
+
return path4.resolve(baseCwd, output);
|
|
1417
1477
|
}
|
|
1418
1478
|
function formatOutputPathInstruction(outputPath, capabilities) {
|
|
1419
1479
|
return [
|
|
@@ -1456,7 +1516,7 @@ function formatByteSize(bytes) {
|
|
|
1456
1516
|
return `${value.toFixed(1)} ${units[unitIndex]}`;
|
|
1457
1517
|
}
|
|
1458
1518
|
function formatSavedOutputReference(savedPath, fullOutput) {
|
|
1459
|
-
let absolutePath =
|
|
1519
|
+
let absolutePath = path4.resolve(savedPath), bytes = Buffer.byteLength(fullOutput, "utf-8"), lines = countLines(fullOutput);
|
|
1460
1520
|
return {
|
|
1461
1521
|
path: absolutePath,
|
|
1462
1522
|
bytes,
|
|
@@ -1471,7 +1531,7 @@ function validateFileOnlyOutputMode(outputMode, outputPath, context) {
|
|
|
1471
1531
|
function captureSingleOutputSnapshot(outputPath) {
|
|
1472
1532
|
if (outputPath)
|
|
1473
1533
|
try {
|
|
1474
|
-
let stat =
|
|
1534
|
+
let stat = fs5.statSync(outputPath);
|
|
1475
1535
|
return { exists: !0, mtimeMs: stat.mtimeMs, size: stat.size };
|
|
1476
1536
|
} catch {
|
|
1477
1537
|
return { exists: !1 };
|
|
@@ -1481,7 +1541,7 @@ function persistSingleOutput(outputPath, fullOutput) {
|
|
|
1481
1541
|
if (!outputPath)
|
|
1482
1542
|
return {};
|
|
1483
1543
|
try {
|
|
1484
|
-
return
|
|
1544
|
+
return fs5.mkdirSync(path4.dirname(outputPath), { recursive: !0 }), fs5.writeFileSync(outputPath, fullOutput, "utf-8"), { savedPath: outputPath };
|
|
1485
1545
|
} catch (err) {
|
|
1486
1546
|
return { error: err instanceof Error ? err.message : String(err) };
|
|
1487
1547
|
}
|
|
@@ -1491,7 +1551,7 @@ function resolveSingleOutput(outputPath, fallbackOutput, beforeRun) {
|
|
|
1491
1551
|
return { fullOutput: fallbackOutput };
|
|
1492
1552
|
let changedSinceStart = !1;
|
|
1493
1553
|
try {
|
|
1494
|
-
let stat =
|
|
1554
|
+
let stat = fs5.statSync(outputPath);
|
|
1495
1555
|
changedSinceStart = !beforeRun?.exists || stat.mtimeMs !== beforeRun.mtimeMs || stat.size !== beforeRun.size;
|
|
1496
1556
|
} catch (error) {
|
|
1497
1557
|
let code = error && typeof error == "object" && "code" in error ? error.code : void 0;
|
|
@@ -1503,7 +1563,7 @@ function resolveSingleOutput(outputPath, fallbackOutput, beforeRun) {
|
|
|
1503
1563
|
}
|
|
1504
1564
|
if (changedSinceStart)
|
|
1505
1565
|
try {
|
|
1506
|
-
return { fullOutput:
|
|
1566
|
+
return { fullOutput: fs5.readFileSync(outputPath, "utf-8"), savedPath: outputPath };
|
|
1507
1567
|
} catch (error) {
|
|
1508
1568
|
return {
|
|
1509
1569
|
fullOutput: fallbackOutput,
|
|
@@ -1603,10 +1663,10 @@ function projectChildLifecycle(event, terminalAssistantStop = !1) {
|
|
|
1603
1663
|
// packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js
|
|
1604
1664
|
var artifactOutputByResult = /* @__PURE__ */ new WeakMap(), acceptanceOutputByResult = /* @__PURE__ */ new WeakMap();
|
|
1605
1665
|
function emptyUsage() {
|
|
1606
|
-
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
|
|
1666
|
+
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0, unknownRequests: 0, partialRequests: 0, unknownCosts: 0 };
|
|
1607
1667
|
}
|
|
1608
1668
|
function sumUsage(target, source) {
|
|
1609
|
-
target.input += source.input, target.output += source.output, target.cacheRead += source.cacheRead, target.cacheWrite += source.cacheWrite, target.cost += source.cost, target.turns += source.turns;
|
|
1669
|
+
target.input += source.input, target.output += source.output, target.cacheRead += source.cacheRead, target.cacheWrite += source.cacheWrite, target.cost += source.cost, target.turns += source.turns, target.unknownRequests += source.unknownRequests ?? 0, target.partialRequests += source.partialRequests ?? 0, target.unknownCosts += source.unknownCosts ?? 0;
|
|
1610
1670
|
}
|
|
1611
1671
|
function formatTimeoutMessage(timeoutMs) {
|
|
1612
1672
|
return `Subagent timed out after ${timeoutMs}ms.`;
|
|
@@ -1677,7 +1737,7 @@ function snapshotResult(result2, progress) {
|
|
|
1677
1737
|
};
|
|
1678
1738
|
}
|
|
1679
1739
|
async function runSingleAttempt(runtimeCwd, spec, task, model, options, shared) {
|
|
1680
|
-
let effectiveThinking = options.thinkingOverride, modelArg = applyThinkingSuffix(model, effectiveThinking, options.thinkingOverride !== void 0), watchdogConfig = resolveWatchdogConfig(options.cwd ?? runtimeCwd), childWatchdog = watchdogConfig.ok ? resolveChildWatchdogConfig({
|
|
1740
|
+
let usageBeforeAttempt = parseSessionUsage(options.sessionFile ?? options.sessionDir), effectiveThinking = options.thinkingOverride, modelArg = applyThinkingSuffix(model, effectiveThinking, options.thinkingOverride !== void 0), watchdogConfig = resolveWatchdogConfig(options.cwd ?? runtimeCwd), childWatchdog = watchdogConfig.ok ? resolveChildWatchdogConfig({
|
|
1681
1741
|
config: watchdogConfig.config,
|
|
1682
1742
|
agent: spec.childId,
|
|
1683
1743
|
runId: options.runId,
|
|
@@ -2033,7 +2093,7 @@ async function runSingleAttempt(runtimeCwd, spec, task, model, options, shared)
|
|
|
2033
2093
|
let stopReason = evt.message.stopReason, hasToolCall = Array.isArray(evt.message.content) && evt.message.content.some((part) => part.type === "toolCall"), terminalAssistantStop = stopReason === "stop" && !hasToolCall;
|
|
2034
2094
|
updateTurnBudget(result2.usage.turns, terminalAssistantStop);
|
|
2035
2095
|
let u = evt.message.usage;
|
|
2036
|
-
if (u && (result2.usage.input += u.input || 0, result2.usage.output += u.output || 0, result2.usage.cacheRead += u.cacheRead || 0, result2.usage.cacheWrite += u.cacheWrite || 0, result2.usage.cost += u.cost?.total || 0, progress.tokens = result2.usage.input + result2.usage.output), !result2.model && evt.message.model) {
|
|
2096
|
+
if (u && (result2.usage.input += u.input || 0, result2.usage.output += u.output || 0, result2.usage.cacheRead += u.cacheRead || 0, result2.usage.cacheWrite += u.cacheWrite || 0, result2.usage.cost += u.cost?.total || 0, result2.usage.unknownRequests += +(u.measurement === "unknown"), result2.usage.partialRequests += +(u.measurement === "partial"), result2.usage.unknownCosts += +(u.costSource === "unknown"), progress.tokens = result2.usage.input + result2.usage.output + result2.usage.cacheRead + result2.usage.cacheWrite), !result2.model && evt.message.model) {
|
|
2037
2097
|
result2.model = evt.message.model;
|
|
2038
2098
|
let parsed = splitKnownThinkingSuffix(evt.message.model);
|
|
2039
2099
|
parsed.thinkingSuffix && (result2.thinking = parsed.thinkingSuffix.slice(1)), progress.model = result2.model, progress.thinking = result2.thinking;
|
|
@@ -2100,6 +2160,8 @@ async function runSingleAttempt(runtimeCwd, spec, task, model, options, shared)
|
|
|
2100
2160
|
});
|
|
2101
2161
|
let toolDiagnosticError = readChildToolDiagnosticError(toolDiagnosticPath);
|
|
2102
2162
|
cleanupTempDir(tempDir), stdoutReader.end(), stderrReader.end();
|
|
2163
|
+
let persistedUsage = parseSessionUsage(options.sessionFile ?? options.sessionDir ?? result2.sessionFile);
|
|
2164
|
+
persistedUsage && (result2.usageRequests = parseSessionRequests(options.sessionFile ?? options.sessionDir ?? result2.sessionFile), result2.usage = options.sessionFile ? persistedUsage : sessionUsageDelta(persistedUsage, usageBeforeAttempt), progress.tokens = result2.usage.input + result2.usage.output + result2.usage.cacheRead + result2.usage.cacheWrite);
|
|
2103
2165
|
let stderr = stderrTail.text(), closeError = result2.error ?? toolDiagnosticError ?? assistantError, forcedDrainAfterFinalSuccess = forcedTerminationSignal && (cleanTerminalAssistantStopReceived || agentSettledReceived) && !closeError;
|
|
2104
2166
|
code !== 0 && stderr.trim() && !closeError && !forcedDrainAfterFinalSuccess && (closeError = stderr.trim());
|
|
2105
2167
|
let finalCode = forcedDrainAfterFinalSuccess ? 0 : forcedTerminationSignal || signal ? code ?? 1 : code ?? 0;
|
|
@@ -2334,9 +2396,9 @@ ${acceptanceFailure2}` : acceptanceFailure2, recoveredResult.progress && (recove
|
|
|
2334
2396
|
Acceptance evaluation failed: ${message}` : `Acceptance evaluation failed: ${message}`, options.onDetachedExit?.(recoveredResult);
|
|
2335
2397
|
});
|
|
2336
2398
|
}
|
|
2337
|
-
} : options, lastResult, modelsToTry = candidates.length > 0 ? candidates : [void 0];
|
|
2399
|
+
} : options, priorRequestIds = new Set(parseSessionRequests(options.sessionFile ?? options.sessionDir).map((request) => request.id)), lastResult, modelsToTry = candidates.length > 0 ? candidates : [void 0];
|
|
2338
2400
|
for (let i = 0; i < modelsToTry.length; i++) {
|
|
2339
|
-
let candidate = modelsToTry[i], outputSnapshot = captureSingleOutputSnapshot(options.outputPath), result3 = await runSingleAttempt(runtimeCwd, spec, taskWithAcceptance, candidate, detachedAwareOptions, {
|
|
2401
|
+
let candidate = modelsToTry[i], outputSnapshot = captureSingleOutputSnapshot(options.outputPath), usageBeforeAttempt = parseSessionUsage(options.sessionFile ?? options.sessionDir), result3 = await runSingleAttempt(runtimeCwd, spec, taskWithAcceptance, candidate, detachedAwareOptions, {
|
|
2340
2402
|
sessionEnabled,
|
|
2341
2403
|
systemPrompt,
|
|
2342
2404
|
resolvedSkillNames: resolvedSkills.length > 0 ? resolvedSkills.map((skill) => skill.name) : void 0,
|
|
@@ -2347,8 +2409,8 @@ Acceptance evaluation failed: ${message}` : `Acceptance evaluation failed: ${mes
|
|
|
2347
2409
|
attemptNotes,
|
|
2348
2410
|
outputSnapshot,
|
|
2349
2411
|
originalTask: task
|
|
2350
|
-
});
|
|
2351
|
-
lastResult = result3, result3.model ? attemptedModels.push(result3.model) : candidate && attemptedModels.push(candidate), sumUsage(aggregateUsage, result3.usage), totalToolCount += result3.progressSummary?.toolCount ?? 0, totalDurationMs += result3.progressSummary?.durationMs ?? 0;
|
|
2412
|
+
}), persistedUsage = parseSessionUsage(options.sessionFile ?? options.sessionDir ?? result3.sessionFile);
|
|
2413
|
+
persistedUsage && (result3.usage = sessionUsageDelta(persistedUsage, usageBeforeAttempt)), lastResult = result3, result3.model ? attemptedModels.push(result3.model) : candidate && attemptedModels.push(candidate), sumUsage(aggregateUsage, result3.usage), totalToolCount += result3.progressSummary?.toolCount ?? 0, totalDurationMs += result3.progressSummary?.durationMs ?? 0;
|
|
2352
2414
|
let attemptSucceeded = result3.exitCode === 0 && !result3.error, attempt = {
|
|
2353
2415
|
model: result3.model ?? candidate ?? spec.model ?? "default",
|
|
2354
2416
|
success: attemptSucceeded,
|
|
@@ -2370,10 +2432,10 @@ Acceptance evaluation failed: ${message}` : `Acceptance evaluation failed: ${mes
|
|
|
2370
2432
|
messages: [],
|
|
2371
2433
|
usage: emptyUsage(),
|
|
2372
2434
|
error: "Subagent did not produce a result."
|
|
2373
|
-
};
|
|
2374
|
-
if (result2.usage = aggregateUsage, result2.attemptedModels = attemptedModels.length > 0 ? attemptedModels : void 0, result2.modelAttempts = modelAttempts.length > 0 ? modelAttempts : void 0, result2.progressSummary = {
|
|
2435
|
+
}, cumulativeResumeUsage = options.sessionFile ? parseSessionUsage(options.sessionFile) : null;
|
|
2436
|
+
if (result2.usage = cumulativeResumeUsage ?? aggregateUsage, result2.usageRequests = parseSessionRequests(options.sessionFile ?? options.sessionDir ?? result2.sessionFile).filter((request) => !!options.sessionFile || !priorRequestIds.has(request.id)), result2.usageRequests.length === 0 && (result2.usageRequests = void 0), result2.attemptedModels = attemptedModels.length > 0 ? attemptedModels : void 0, result2.modelAttempts = modelAttempts.length > 0 ? modelAttempts : void 0, result2.progressSummary = {
|
|
2375
2437
|
toolCount: totalToolCount,
|
|
2376
|
-
tokens:
|
|
2438
|
+
tokens: result2.usage.input + result2.usage.output + result2.usage.cacheRead + result2.usage.cacheWrite,
|
|
2377
2439
|
durationMs: totalDurationMs
|
|
2378
2440
|
}, attemptNotes.length > 0 && result2.progress && (result2.progress.recentOutput = [...attemptNotes, ...result2.progress.recentOutput], result2.progress.recentOutput.length > 50 && result2.progress.recentOutput.splice(50)), transcriptWriter && (result2.transcriptPath = artifactPathsResult?.transcriptPath), transcriptWriter?.getError() && (result2.transcriptError = transcriptWriter.getError()), artifactPathsResult && options.artifactConfig?.enabled !== !1) {
|
|
2379
2441
|
if (result2.artifactPaths = artifactPathsResult, options.artifactConfig?.includeOutput !== !1 && writeArtifact(artifactPathsResult.outputPath, artifactOutputByResult.get(result2) ?? result2.finalOutput ?? ""), options.maxOutput) {
|
|
@@ -2403,10 +2465,10 @@ ${acceptanceFailure}` : acceptanceFailure, result2.progress && (result2.progress
|
|
|
2403
2465
|
}
|
|
2404
2466
|
|
|
2405
2467
|
// packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/shared/run-history.js
|
|
2406
|
-
import * as
|
|
2407
|
-
import * as
|
|
2468
|
+
import * as fs6 from "node:fs";
|
|
2469
|
+
import * as path5 from "node:path";
|
|
2408
2470
|
function getHistoryPath() {
|
|
2409
|
-
return
|
|
2471
|
+
return path5.join(getAgentDir(), "run-history.jsonl");
|
|
2410
2472
|
}
|
|
2411
2473
|
function recordRun(agent, task, exitCode, durationMs) {
|
|
2412
2474
|
try {
|
|
@@ -2418,7 +2480,7 @@ function recordRun(agent, task, exitCode, durationMs) {
|
|
|
2418
2480
|
duration: durationMs,
|
|
2419
2481
|
...exitCode !== 0 ? { exit: exitCode } : {}
|
|
2420
2482
|
}, historyPath = getHistoryPath();
|
|
2421
|
-
|
|
2483
|
+
fs6.mkdirSync(path5.dirname(historyPath), { recursive: !0 }), fs6.appendFileSync(historyPath, `${JSON.stringify(entry)}
|
|
2422
2484
|
`);
|
|
2423
2485
|
} catch {
|
|
2424
2486
|
}
|
|
@@ -2426,9 +2488,9 @@ function recordRun(agent, task, exitCode, durationMs) {
|
|
|
2426
2488
|
|
|
2427
2489
|
// packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/shared/worktree.js
|
|
2428
2490
|
import { spawnSync } from "node:child_process";
|
|
2429
|
-
import * as
|
|
2491
|
+
import * as fs7 from "node:fs";
|
|
2430
2492
|
import * as os from "node:os";
|
|
2431
|
-
import * as
|
|
2493
|
+
import * as path6 from "node:path";
|
|
2432
2494
|
var DEFAULT_WORKTREE_SETUP_HOOK_TIMEOUT_MS = 3e4;
|
|
2433
2495
|
function runGit(cwd, args) {
|
|
2434
2496
|
let result2 = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf-8" });
|
|
@@ -2454,9 +2516,9 @@ function resolveRepoState(cwd) {
|
|
|
2454
2516
|
return { toplevel, cwdRelative, baseCommit };
|
|
2455
2517
|
}
|
|
2456
2518
|
function normalizeComparableCwd(cwd) {
|
|
2457
|
-
let resolved =
|
|
2519
|
+
let resolved = path6.resolve(cwd);
|
|
2458
2520
|
try {
|
|
2459
|
-
return
|
|
2521
|
+
return fs7.realpathSync(resolved);
|
|
2460
2522
|
} catch {
|
|
2461
2523
|
return resolved;
|
|
2462
2524
|
}
|
|
@@ -2467,7 +2529,7 @@ function findWorktreeTaskCwdConflict(tasks, sharedCwd) {
|
|
|
2467
2529
|
let task = tasks[index];
|
|
2468
2530
|
if (!task.cwd)
|
|
2469
2531
|
continue;
|
|
2470
|
-
let taskCwd =
|
|
2532
|
+
let taskCwd = path6.isAbsolute(task.cwd) ? task.cwd : path6.resolve(sharedCwd, task.cwd);
|
|
2471
2533
|
if (normalizeComparableCwd(taskCwd) !== normalizedSharedCwd)
|
|
2472
2534
|
return { index, agent: task.agent, cwd: task.cwd };
|
|
2473
2535
|
}
|
|
@@ -2488,9 +2550,9 @@ function resolveWorktreeBaseDir(configuredBaseDir, repoRoot) {
|
|
|
2488
2550
|
let trimmed = rawBaseDir.trim();
|
|
2489
2551
|
if (!trimmed)
|
|
2490
2552
|
throw new Error("worktree base directory cannot be empty");
|
|
2491
|
-
let expanded = trimmed.startsWith("~/") ?
|
|
2553
|
+
let expanded = trimmed.startsWith("~/") ? path6.join(os.homedir(), trimmed.slice(2)) : trimmed, resolved = path6.isAbsolute(expanded) ? expanded : path6.resolve(repoRoot, expanded);
|
|
2492
2554
|
try {
|
|
2493
|
-
|
|
2555
|
+
fs7.mkdirSync(resolved, { recursive: !0 });
|
|
2494
2556
|
} catch (error) {
|
|
2495
2557
|
let message = error instanceof Error ? error.message : String(error);
|
|
2496
2558
|
throw new Error(`failed to create worktree base directory ${resolved}: ${message}`);
|
|
@@ -2498,25 +2560,25 @@ function resolveWorktreeBaseDir(configuredBaseDir, repoRoot) {
|
|
|
2498
2560
|
return resolved;
|
|
2499
2561
|
}
|
|
2500
2562
|
function buildWorktreePath(baseDir, runId, index) {
|
|
2501
|
-
return
|
|
2563
|
+
return path6.join(baseDir, `pi-worktree-${runId}-${index}`);
|
|
2502
2564
|
}
|
|
2503
2565
|
function resolveRepoCwdRelative(cwd) {
|
|
2504
2566
|
let repoCheck = runGit(cwd, ["rev-parse", "--is-inside-work-tree"]);
|
|
2505
2567
|
if (repoCheck.status !== 0 || repoCheck.stdout.trim() !== "true")
|
|
2506
2568
|
throw new Error("worktree isolation requires a git repository");
|
|
2507
|
-
let rawPrefix = runGitChecked(cwd, ["rev-parse", "--show-prefix"]).trim(), normalizedPrefix = rawPrefix ?
|
|
2569
|
+
let rawPrefix = runGitChecked(cwd, ["rev-parse", "--show-prefix"]).trim(), normalizedPrefix = rawPrefix ? path6.normalize(rawPrefix.replace(/[\\/]+$/, "")) : "";
|
|
2508
2570
|
return normalizedPrefix === "." ? "" : normalizedPrefix;
|
|
2509
2571
|
}
|
|
2510
2572
|
function resolveExpectedWorktreeAgentCwd(cwd, runId, index, baseDir) {
|
|
2511
2573
|
let cwdRelative = resolveRepoCwdRelative(cwd), repoRoot = runGitChecked(cwd, ["rev-parse", "--show-toplevel"]).trim(), worktreePath = buildWorktreePath(resolveWorktreeBaseDir(baseDir, repoRoot), runId, index);
|
|
2512
|
-
return cwdRelative ?
|
|
2574
|
+
return cwdRelative ? path6.join(worktreePath, cwdRelative) : worktreePath;
|
|
2513
2575
|
}
|
|
2514
2576
|
function linkNodeModulesIfPresent(toplevel, worktreePath) {
|
|
2515
|
-
let nodeModulesPath =
|
|
2516
|
-
if (!
|
|
2577
|
+
let nodeModulesPath = path6.join(toplevel, "node_modules"), nodeModulesLinkPath = path6.join(worktreePath, "node_modules");
|
|
2578
|
+
if (!fs7.existsSync(nodeModulesPath) || fs7.existsSync(nodeModulesLinkPath))
|
|
2517
2579
|
return !1;
|
|
2518
2580
|
try {
|
|
2519
|
-
return
|
|
2581
|
+
return fs7.symlinkSync(nodeModulesPath, nodeModulesLinkPath), !0;
|
|
2520
2582
|
} catch {
|
|
2521
2583
|
return !1;
|
|
2522
2584
|
}
|
|
@@ -2534,16 +2596,16 @@ function resolveWorktreeSetupHook(repoRoot, config) {
|
|
|
2534
2596
|
let hookPath = config.hookPath.trim();
|
|
2535
2597
|
if (!hookPath)
|
|
2536
2598
|
throw new Error("worktree setup hook path cannot be empty");
|
|
2537
|
-
let expandedHookPath = hookPath.startsWith("~/") ?
|
|
2538
|
-
if (
|
|
2599
|
+
let expandedHookPath = hookPath.startsWith("~/") ? path6.join(os.homedir(), hookPath.slice(2)) : hookPath, resolvedPath;
|
|
2600
|
+
if (path6.isAbsolute(expandedHookPath))
|
|
2539
2601
|
resolvedPath = expandedHookPath;
|
|
2540
2602
|
else if (expandedHookPath.includes("/") || expandedHookPath.includes("\\"))
|
|
2541
|
-
resolvedPath =
|
|
2603
|
+
resolvedPath = path6.resolve(repoRoot, expandedHookPath);
|
|
2542
2604
|
else
|
|
2543
2605
|
throw new Error("worktree setup hook must be an absolute path or a repo-relative path");
|
|
2544
|
-
if (!
|
|
2606
|
+
if (!fs7.existsSync(resolvedPath))
|
|
2545
2607
|
throw new Error(`worktree setup hook not found: ${resolvedPath}`);
|
|
2546
|
-
if (
|
|
2608
|
+
if (fs7.statSync(resolvedPath).isDirectory())
|
|
2547
2609
|
throw new Error(`worktree setup hook must be a file, got directory: ${resolvedPath}`);
|
|
2548
2610
|
return {
|
|
2549
2611
|
hookPath: resolvedPath,
|
|
@@ -2554,14 +2616,14 @@ function normalizeSyntheticPath(worktreePath, rawPath) {
|
|
|
2554
2616
|
let trimmed = rawPath.trim();
|
|
2555
2617
|
if (!trimmed)
|
|
2556
2618
|
throw new Error("synthetic path cannot be empty");
|
|
2557
|
-
if (
|
|
2619
|
+
if (path6.isAbsolute(trimmed))
|
|
2558
2620
|
throw new Error(`synthetic path must be relative: ${rawPath}`);
|
|
2559
|
-
let resolved =
|
|
2621
|
+
let resolved = path6.resolve(worktreePath, trimmed), relative2 = path6.relative(worktreePath, resolved);
|
|
2560
2622
|
if (!relative2 || relative2 === ".")
|
|
2561
2623
|
throw new Error(`synthetic path cannot target the worktree root: ${rawPath}`);
|
|
2562
|
-
if (relative2 === ".." || relative2.startsWith(`..${
|
|
2624
|
+
if (relative2 === ".." || relative2.startsWith(`..${path6.sep}`) || path6.isAbsolute(relative2))
|
|
2563
2625
|
throw new Error(`synthetic path escapes the worktree root: ${rawPath}`);
|
|
2564
|
-
return
|
|
2626
|
+
return path6.normalize(relative2);
|
|
2565
2627
|
}
|
|
2566
2628
|
function hasTrackedEntries(worktreePath, relativePath) {
|
|
2567
2629
|
let result2 = runGit(worktreePath, ["ls-files", "--", relativePath]);
|
|
@@ -2618,7 +2680,7 @@ function createSingleWorktree(toplevel, cwdRelative, runId, index, baseCommit, s
|
|
|
2618
2680
|
let message = add.stderr.trim() || add.stdout.trim() || `failed to create worktree ${worktreePath}`;
|
|
2619
2681
|
throw new Error(message);
|
|
2620
2682
|
}
|
|
2621
|
-
let agentCwd = cwdRelative ?
|
|
2683
|
+
let agentCwd = cwdRelative ? path6.join(worktreePath, cwdRelative) : worktreePath;
|
|
2622
2684
|
try {
|
|
2623
2685
|
let nodeModulesLinked = linkNodeModulesIfPresent(toplevel, worktreePath), syntheticPaths = nodeModulesLinked ? ["node_modules"] : [];
|
|
2624
2686
|
if (setupHook) {
|
|
@@ -2656,26 +2718,26 @@ function createSingleWorktree(toplevel, cwdRelative, runId, index, baseCommit, s
|
|
|
2656
2718
|
}
|
|
2657
2719
|
}
|
|
2658
2720
|
function removeSyntheticPath(worktree, syntheticPath) {
|
|
2659
|
-
let resolved =
|
|
2660
|
-
if (!relative2 || relative2 === "." || relative2 === ".." || relative2.startsWith(`..${
|
|
2721
|
+
let resolved = path6.resolve(worktree.path, syntheticPath), relative2 = path6.relative(worktree.path, resolved);
|
|
2722
|
+
if (!relative2 || relative2 === "." || relative2 === ".." || relative2.startsWith(`..${path6.sep}`) || path6.isAbsolute(relative2))
|
|
2661
2723
|
return;
|
|
2662
2724
|
let stat;
|
|
2663
2725
|
try {
|
|
2664
|
-
stat =
|
|
2726
|
+
stat = fs7.lstatSync(resolved);
|
|
2665
2727
|
} catch (error) {
|
|
2666
2728
|
if ((error && typeof error == "object" && "code" in error ? error.code : void 0) === "ENOENT")
|
|
2667
2729
|
return;
|
|
2668
2730
|
throw error;
|
|
2669
2731
|
}
|
|
2670
2732
|
if (stat.isSymbolicLink()) {
|
|
2671
|
-
|
|
2733
|
+
fs7.unlinkSync(resolved);
|
|
2672
2734
|
return;
|
|
2673
2735
|
}
|
|
2674
2736
|
if (stat.isDirectory()) {
|
|
2675
|
-
|
|
2737
|
+
fs7.rmSync(resolved, { recursive: !0, force: !0 });
|
|
2676
2738
|
return;
|
|
2677
2739
|
}
|
|
2678
|
-
|
|
2740
|
+
fs7.rmSync(resolved, { force: !0 });
|
|
2679
2741
|
}
|
|
2680
2742
|
function removeSyntheticPathsBeforeDiff(worktree) {
|
|
2681
2743
|
if (worktree.syntheticPaths.length === 0)
|
|
@@ -2708,7 +2770,7 @@ function parseNumstat(numstat) {
|
|
|
2708
2770
|
function captureWorktreeDiff(setup, worktree, agent, patchPath) {
|
|
2709
2771
|
removeSyntheticPathsBeforeDiff(worktree), runGitChecked(worktree.path, ["add", "-A"]);
|
|
2710
2772
|
let diffStat = runGitChecked(worktree.path, ["diff", "--cached", "--stat", setup.baseCommit]).trim(), patch = runGitChecked(worktree.path, ["diff", "--cached", setup.baseCommit]), numstat = runGitChecked(worktree.path, ["diff", "--cached", "--numstat", setup.baseCommit]);
|
|
2711
|
-
if (
|
|
2773
|
+
if (fs7.writeFileSync(patchPath, patch, "utf-8"), !patch.trim())
|
|
2712
2774
|
return emptyDiff(worktree.index, agent, worktree.branch, patchPath);
|
|
2713
2775
|
let parsed = parseNumstat(numstat);
|
|
2714
2776
|
return {
|
|
@@ -2724,7 +2786,7 @@ function captureWorktreeDiff(setup, worktree, agent, patchPath) {
|
|
|
2724
2786
|
}
|
|
2725
2787
|
function writeEmptyPatch(patchPath) {
|
|
2726
2788
|
try {
|
|
2727
|
-
|
|
2789
|
+
fs7.writeFileSync(patchPath, "", "utf-8");
|
|
2728
2790
|
} catch {
|
|
2729
2791
|
}
|
|
2730
2792
|
}
|
|
@@ -2761,13 +2823,13 @@ function createWorktrees(cwd, runId, count, options) {
|
|
|
2761
2823
|
}
|
|
2762
2824
|
function diffWorktrees(setup, agents, diffsDir) {
|
|
2763
2825
|
try {
|
|
2764
|
-
|
|
2826
|
+
fs7.mkdirSync(diffsDir, { recursive: !0 });
|
|
2765
2827
|
} catch {
|
|
2766
2828
|
return [];
|
|
2767
2829
|
}
|
|
2768
2830
|
let diffs = [];
|
|
2769
2831
|
for (let index = 0; index < setup.worktrees.length; index++) {
|
|
2770
|
-
let worktree = setup.worktrees[index], agent = agents[index] ?? `task-${index + 1}`, patchPath =
|
|
2832
|
+
let worktree = setup.worktrees[index], agent = agents[index] ?? `task-${index + 1}`, patchPath = path6.join(diffsDir, `task-${index}-${safePatchAgentName(agent)}.patch`);
|
|
2771
2833
|
try {
|
|
2772
2834
|
diffs.push(captureWorktreeDiff(setup, worktree, agent, patchPath));
|
|
2773
2835
|
} catch {
|
|
@@ -2791,7 +2853,7 @@ function formatWorktreeDiffSummary(diffs) {
|
|
|
2791
2853
|
let lines = ["=== Worktree Changes ===", ""];
|
|
2792
2854
|
for (let diff of changed)
|
|
2793
2855
|
lines.push(`--- Task ${diff.index + 1} (${diff.agent}): ${diff.filesChanged} files changed, +${diff.insertions} -${diff.deletions} ---`), diff.diffStat.trim().length > 0 && lines.push(diff.diffStat), lines.push("");
|
|
2794
|
-
let patchesDir =
|
|
2856
|
+
let patchesDir = path6.dirname(changed[0].patchPath);
|
|
2795
2857
|
return lines.push(`Full patches: ${patchesDir}`), lines.join(`
|
|
2796
2858
|
`).trimEnd();
|
|
2797
2859
|
}
|
|
@@ -3356,11 +3418,11 @@ async function runParallelChainTasks(input) {
|
|
|
3356
3418
|
let effectiveModel = effectiveModels[taskIndex], maxSubagentDepth = resolveChildMaxSubagentDepth(input.maxSubagentDepth, taskChildConfig?.maxSubagentDepth), toolBudget = resolveChainToolBudget({ stepBudget: task.toolBudget, runBudget: input.toolBudget, agentBudget: taskChildConfig?.toolBudget, configBudget: input.configToolBudget });
|
|
3357
3419
|
if (toolBudget.error)
|
|
3358
3420
|
throw new Error(toolBudget.error);
|
|
3359
|
-
let taskCwd = input.worktreeSetup ? input.worktreeSetup.worktrees[taskIndex].agentCwd : resolveChildCwd(input.cwd ?? input.ctx.cwd, task.cwd), outputPath = typeof behavior.output == "string" ?
|
|
3421
|
+
let taskCwd = input.worktreeSetup ? input.worktreeSetup.worktrees[taskIndex].agentCwd : resolveChildCwd(input.cwd ?? input.ctx.cwd, task.cwd), outputPath = typeof behavior.output == "string" ? path7.isAbsolute(behavior.output) ? behavior.output : path7.join(input.chainDir, behavior.output) : void 0;
|
|
3360
3422
|
taskStr = withChainHandoff(injectSingleOutputInstruction(taskStr, outputPath, taskChildConfig), input.stepIndex < input.totalSteps - 1);
|
|
3361
3423
|
let interruptController = new AbortController();
|
|
3362
3424
|
input.foregroundControl && (input.foregroundControl.currentAgent = task.description || task.agent, input.foregroundControl.currentChildId = task.agent, input.foregroundControl.currentIndex = input.globalTaskIndex + taskIndex, input.foregroundControl.currentActivityState = void 0, input.foregroundControl.updatedAt = Date.now(), input.foregroundControl.interrupt = () => interruptController.signal.aborted ? !1 : (interruptController.abort(), input.foregroundControl.currentActivityState = void 0, input.foregroundControl.updatedAt = Date.now(), !0));
|
|
3363
|
-
let structuredRuntime = task.outputSchema ? createStructuredOutputRuntime(task.outputSchema,
|
|
3425
|
+
let structuredRuntime = task.outputSchema ? createStructuredOutputRuntime(task.outputSchema, path7.join(input.chainDir, "structured-output")) : void 0, result2 = await runSync(input.ctx.cwd, normalizeChildSpec({
|
|
3364
3426
|
task: taskStr,
|
|
3365
3427
|
description: task.description,
|
|
3366
3428
|
permissions: task.permissions,
|
|
@@ -3558,7 +3620,7 @@ async function executeChain(params) {
|
|
|
3558
3620
|
try {
|
|
3559
3621
|
let agentNames = step.parallel.map((task) => task.agent), parallelBehaviors = resolveParallelBehaviors(step.parallel, stepIndex, chainSkills).map((behavior, taskIndex) => suppressProgressForReadOnlyTask(behavior, parallelTemplates[taskIndex] ?? step.parallel[taskIndex]?.task, originalTask));
|
|
3560
3622
|
for (let taskIndex = 0; taskIndex < step.parallel.length; taskIndex++) {
|
|
3561
|
-
let behavior = parallelBehaviors[taskIndex], outputPath = typeof behavior.output == "string" ?
|
|
3623
|
+
let behavior = parallelBehaviors[taskIndex], outputPath = typeof behavior.output == "string" ? path7.isAbsolute(behavior.output) ? behavior.output : path7.join(chainDir, behavior.output) : void 0, validationError = validateFileOnlyOutputMode(behavior.outputMode, outputPath, `Parallel chain step ${stepIndex + 1} task ${taskIndex + 1} (${step.parallel[taskIndex].agent})`);
|
|
3562
3624
|
if (validationError)
|
|
3563
3625
|
return buildChainExecutionErrorResult(validationError, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex + taskIndex }));
|
|
3564
3626
|
}
|
|
@@ -3656,7 +3718,7 @@ ${failureSummary}`;
|
|
|
3656
3718
|
outputName && (outputs[outputName] = outputEntryFromResult(parallelResults[taskIndex], stepIndex));
|
|
3657
3719
|
}
|
|
3658
3720
|
let taskResults = parallelResults.map((result2, i) => {
|
|
3659
|
-
let outputTarget = parallelBehaviors[i]?.output, outputTargetPath = typeof outputTarget == "string" ?
|
|
3721
|
+
let outputTarget = parallelBehaviors[i]?.output, outputTargetPath = typeof outputTarget == "string" ? path7.isAbsolute(outputTarget) ? outputTarget : path7.join(chainDir, outputTarget) : void 0;
|
|
3660
3722
|
return {
|
|
3661
3723
|
agent: result2.agent,
|
|
3662
3724
|
taskIndex: i,
|
|
@@ -3665,10 +3727,10 @@ ${failureSummary}`;
|
|
|
3665
3727
|
error: result2.error,
|
|
3666
3728
|
timedOut: result2.timedOut,
|
|
3667
3729
|
outputTargetPath,
|
|
3668
|
-
outputTargetExists: outputTargetPath ?
|
|
3730
|
+
outputTargetExists: outputTargetPath ? fs8.existsSync(outputTargetPath) : void 0
|
|
3669
3731
|
};
|
|
3670
3732
|
});
|
|
3671
|
-
prev = aggregateParallelOutputs(taskResults), prev = appendParallelWorktreeSummary(prev, worktreeSetup,
|
|
3733
|
+
prev = aggregateParallelOutputs(taskResults), prev = appendParallelWorktreeSummary(prev, worktreeSetup, path7.join(chainDir, "worktree-diffs", `step-${stepIndex}`), agentNames);
|
|
3672
3734
|
} finally {
|
|
3673
3735
|
worktreeSetup && cleanupWorktrees(worktreeSetup);
|
|
3674
3736
|
}
|
|
@@ -3730,7 +3792,7 @@ ${failureSummary}`;
|
|
|
3730
3792
|
failFast: step.failFast
|
|
3731
3793
|
}, parallelTemplates = materialized.parallel.map((task) => task.task ?? "{previous}"), parallelBehaviors = resolveParallelBehaviors(dynamicParallelStep.parallel, stepIndex, chainSkills).map((behavior, taskIndex) => suppressProgressForReadOnlyTask(behavior, parallelTemplates[taskIndex] ?? dynamicParallelStep.parallel[taskIndex]?.task, originalTask));
|
|
3732
3794
|
for (let taskIndex = 0; taskIndex < dynamicParallelStep.parallel.length; taskIndex++) {
|
|
3733
|
-
let behavior = parallelBehaviors[taskIndex], outputPath = typeof behavior.output == "string" ?
|
|
3795
|
+
let behavior = parallelBehaviors[taskIndex], outputPath = typeof behavior.output == "string" ? path7.isAbsolute(behavior.output) ? behavior.output : path7.join(chainDir, behavior.output) : void 0, validationError = validateFileOnlyOutputMode(behavior.outputMode, outputPath, `Dynamic chain step ${stepIndex + 1} item ${taskIndex + 1} (${dynamicParallelStep.parallel[taskIndex].agent})`);
|
|
3734
3796
|
if (validationError)
|
|
3735
3797
|
return dynamicGroupStatuses[stepIndex] = { status: "failed", error: validationError }, buildChainExecutionErrorResult(validationError, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex + taskIndex }));
|
|
3736
3798
|
}
|
|
@@ -3891,14 +3953,14 @@ ${failureSummary}`;
|
|
|
3891
3953
|
thinking: seqStep.thinking,
|
|
3892
3954
|
availableModels,
|
|
3893
3955
|
preferredProvider: ctx.model?.provider
|
|
3894
|
-
}), outputPath = typeof behavior.output == "string" ?
|
|
3956
|
+
}), outputPath = typeof behavior.output == "string" ? path7.isAbsolute(behavior.output) ? behavior.output : path7.join(chainDir, behavior.output) : void 0;
|
|
3895
3957
|
stepTask = withChainHandoff(injectSingleOutputInstruction(stepTask, outputPath, agentConfig), stepIndex < totalSteps - 1);
|
|
3896
3958
|
let validationError = validateFileOnlyOutputMode(behavior.outputMode, outputPath, `Chain step ${stepIndex + 1} (${seqStep.agent})`);
|
|
3897
3959
|
if (validationError)
|
|
3898
3960
|
return buildChainExecutionErrorResult(validationError, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex }));
|
|
3899
3961
|
let maxSubagentDepth = resolveChildMaxSubagentDepth(params.maxSubagentDepth, agentConfig.maxSubagentDepth), childIndex = globalTaskIndex, interruptController = new AbortController();
|
|
3900
3962
|
foregroundControl && (foregroundControl.currentAgent = seqStep.description || seqStep.agent, foregroundControl.currentChildId = seqStep.agent, foregroundControl.currentIndex = childIndex, foregroundControl.currentActivityState = void 0, foregroundControl.updatedAt = Date.now(), foregroundControl.interrupt = () => interruptController.signal.aborted ? !1 : (interruptController.abort(), foregroundControl.currentActivityState = void 0, foregroundControl.updatedAt = Date.now(), !0));
|
|
3901
|
-
let structuredRuntime = seqStep.outputSchema ? createStructuredOutputRuntime(seqStep.outputSchema,
|
|
3963
|
+
let structuredRuntime = seqStep.outputSchema ? createStructuredOutputRuntime(seqStep.outputSchema, path7.join(chainDir, "structured-output")) : void 0, toolBudget = resolveChainToolBudget({ stepBudget: seqStep.toolBudget, runBudget: params.toolBudget, agentBudget: agentConfig?.toolBudget, configBudget: params.configToolBudget });
|
|
3902
3964
|
if (toolBudget.error)
|
|
3903
3965
|
return buildChainExecutionErrorResult(toolBudget.error, {
|
|
3904
3966
|
results,
|
|
@@ -4019,9 +4081,9 @@ ${failureSummary}`;
|
|
|
4019
4081
|
};
|
|
4020
4082
|
if (behavior.output)
|
|
4021
4083
|
try {
|
|
4022
|
-
let expectedPath =
|
|
4023
|
-
if (!
|
|
4024
|
-
let mdFiles =
|
|
4084
|
+
let expectedPath = path7.isAbsolute(behavior.output) ? behavior.output : path7.join(chainDir, behavior.output);
|
|
4085
|
+
if (!fs8.existsSync(expectedPath)) {
|
|
4086
|
+
let mdFiles = fs8.readdirSync(chainDir).filter((file) => file.endsWith(".md") && file !== "progress.md"), warning = mdFiles.length > 0 ? `Agent wrote to different file(s): ${mdFiles.join(", ")} instead of ${behavior.output}` : `Agent did not create expected output file: ${behavior.output}`;
|
|
4025
4087
|
r.error = r.error ? `${r.error}
|
|
4026
4088
|
${warning}` : warning;
|
|
4027
4089
|
}
|
|
@@ -4037,37 +4099,37 @@ ${warning}` : warning;
|
|
|
4037
4099
|
}
|
|
4038
4100
|
|
|
4039
4101
|
// packages/coding-agent/dist/builtin-extensions/pi-subagents/src/extension/doctor.js
|
|
4040
|
-
import * as
|
|
4041
|
-
import * as
|
|
4102
|
+
import * as fs10 from "node:fs";
|
|
4103
|
+
import * as path9 from "node:path";
|
|
4042
4104
|
|
|
4043
4105
|
// packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.js
|
|
4044
4106
|
import { spawn as spawn2 } from "node:child_process";
|
|
4045
|
-
import * as
|
|
4046
|
-
import * as
|
|
4107
|
+
import * as fs9 from "node:fs";
|
|
4108
|
+
import * as path8 from "node:path";
|
|
4047
4109
|
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
4048
4110
|
import { createRequire } from "node:module";
|
|
4049
4111
|
var require2 = createRequire(new URL("../builtin-extensions/pi-subagents/src/runs/background/async-execution.js", import.meta.url).href), piPackageRoot = resolvePiPackageRoot();
|
|
4050
4112
|
function resolveJitiCliFromPackageJson(packageJsonPath) {
|
|
4051
|
-
if (!
|
|
4113
|
+
if (!fs9.existsSync(packageJsonPath))
|
|
4052
4114
|
return;
|
|
4053
|
-
let packageRoot =
|
|
4115
|
+
let packageRoot = path8.dirname(packageJsonPath), binField = JSON.parse(fs9.readFileSync(packageJsonPath, "utf-8")).bin, candidates = [typeof binField == "string" ? binField : binField?.jiti ?? Object.values(binField ?? {})[0], "lib/jiti-cli.mjs"].filter((candidate) => !!candidate);
|
|
4054
4116
|
for (let candidate of candidates) {
|
|
4055
|
-
let cliPath =
|
|
4056
|
-
if (
|
|
4117
|
+
let cliPath = path8.resolve(packageRoot, candidate);
|
|
4118
|
+
if (fs9.existsSync(cliPath))
|
|
4057
4119
|
return cliPath;
|
|
4058
4120
|
}
|
|
4059
4121
|
}
|
|
4060
4122
|
function resolveJitiCliPath() {
|
|
4061
4123
|
let candidates = [
|
|
4062
4124
|
() => require2.resolve("jiti/package.json"),
|
|
4063
|
-
() => piPackageRoot ? createRequire(
|
|
4125
|
+
() => piPackageRoot ? createRequire(path8.join(piPackageRoot, "package.json")).resolve("jiti/package.json") : void 0,
|
|
4064
4126
|
() => {
|
|
4065
4127
|
if (!process.argv[1])
|
|
4066
4128
|
return;
|
|
4067
|
-
let piEntry =
|
|
4129
|
+
let piEntry = fs9.realpathSync(process.argv[1]);
|
|
4068
4130
|
return createRequire(piEntry).resolve("jiti/package.json");
|
|
4069
4131
|
},
|
|
4070
|
-
() => piPackageRoot ?
|
|
4132
|
+
() => piPackageRoot ? path8.join(piPackageRoot, "node_modules", "jiti", "package.json") : void 0
|
|
4071
4133
|
];
|
|
4072
4134
|
for (let candidate of candidates)
|
|
4073
4135
|
try {
|
|
@@ -4094,12 +4156,12 @@ function isAsyncAvailable() {
|
|
|
4094
4156
|
return jitiCliPath !== void 0;
|
|
4095
4157
|
}
|
|
4096
4158
|
function isNodeExecutableName(execPath) {
|
|
4097
|
-
let basename3 =
|
|
4159
|
+
let basename3 = path8.basename(execPath).toLowerCase();
|
|
4098
4160
|
return basename3 === "node" || basename3 === "node.exe" || basename3 === "nodejs" || basename3 === "nodejs.exe";
|
|
4099
4161
|
}
|
|
4100
4162
|
function canUseCurrentNodeExecutable(execPath) {
|
|
4101
4163
|
try {
|
|
4102
|
-
return
|
|
4164
|
+
return fs9.accessSync(execPath, process.platform === "win32" ? fs9.constants.F_OK : fs9.constants.X_OK), !0;
|
|
4103
4165
|
} catch {
|
|
4104
4166
|
return !1;
|
|
4105
4167
|
}
|
|
@@ -4111,14 +4173,14 @@ function resolveAsyncRunnerLogPaths(cfg) {
|
|
|
4111
4173
|
let asyncDir = typeof cfg.asyncDir == "string" ? cfg.asyncDir : void 0;
|
|
4112
4174
|
if (asyncDir)
|
|
4113
4175
|
return {
|
|
4114
|
-
stdoutPath:
|
|
4115
|
-
stderrPath:
|
|
4176
|
+
stdoutPath: path8.join(asyncDir, "runner.stdout.log"),
|
|
4177
|
+
stderrPath: path8.join(asyncDir, "runner.stderr.log")
|
|
4116
4178
|
};
|
|
4117
4179
|
}
|
|
4118
4180
|
function closeFd(fd) {
|
|
4119
4181
|
if (fd !== void 0)
|
|
4120
4182
|
try {
|
|
4121
|
-
|
|
4183
|
+
fs9.closeSync(fd);
|
|
4122
4184
|
} catch {
|
|
4123
4185
|
}
|
|
4124
4186
|
}
|
|
@@ -4133,9 +4195,9 @@ function waitForStartupInterval(delayMs = 20) {
|
|
|
4133
4195
|
;
|
|
4134
4196
|
}
|
|
4135
4197
|
function readRunnerStartup(startupPath, expectedState, expectedToken) {
|
|
4136
|
-
if (
|
|
4198
|
+
if (fs9.existsSync(startupPath))
|
|
4137
4199
|
try {
|
|
4138
|
-
let payload = JSON.parse(
|
|
4200
|
+
let payload = JSON.parse(fs9.readFileSync(startupPath, "utf-8"));
|
|
4139
4201
|
return payload.state === "error" && typeof payload.error == "string" ? { ok: !1, error: payload.error } : payload.state !== expectedState ? void 0 : typeof payload.token != "string" || expectedToken !== void 0 && payload.token !== expectedToken ? { ok: !1, error: `Async runner wrote an invalid ${expectedState} startup handshake: ${startupPath}` } : { ok: !0, token: payload.token };
|
|
4140
4202
|
} catch (error) {
|
|
4141
4203
|
return { ok: !1, error: `Failed to read async runner startup handshake '${startupPath}': ${error instanceof Error ? error.message : String(error)}` };
|
|
@@ -4157,10 +4219,10 @@ function waitForRunnerStartup(startupPath, expectedState, timeoutMs, expectedTok
|
|
|
4157
4219
|
function writeRunnerStartupControl(filePath, payload) {
|
|
4158
4220
|
let tempPath = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
4159
4221
|
try {
|
|
4160
|
-
|
|
4222
|
+
fs9.writeFileSync(tempPath, JSON.stringify(payload), { encoding: "utf-8", mode: 384 }), fs9.renameSync(tempPath, filePath);
|
|
4161
4223
|
} catch (error) {
|
|
4162
4224
|
try {
|
|
4163
|
-
|
|
4225
|
+
fs9.rmSync(tempPath, { force: !0 });
|
|
4164
4226
|
} catch {
|
|
4165
4227
|
}
|
|
4166
4228
|
throw error;
|
|
@@ -4192,19 +4254,19 @@ function spawnRunner(cfg, suffix, cwd) {
|
|
|
4192
4254
|
if (!jitiCliPath)
|
|
4193
4255
|
return { error: "upstream jiti for TypeScript execution could not be found; ensure package dependencies are installed" };
|
|
4194
4256
|
try {
|
|
4195
|
-
if (!
|
|
4257
|
+
if (!fs9.statSync(cwd).isDirectory())
|
|
4196
4258
|
return { error: `cwd is not a directory: ${cwd}` };
|
|
4197
4259
|
} catch {
|
|
4198
4260
|
return { error: `cwd does not exist: ${cwd}` };
|
|
4199
4261
|
}
|
|
4200
|
-
|
|
4262
|
+
fs9.mkdirSync(TEMP_ROOT_DIR, { recursive: !0 });
|
|
4201
4263
|
let cfgPath = getAsyncConfigPath(suffix);
|
|
4202
|
-
|
|
4203
|
-
let runnerTsPath =
|
|
4204
|
-
startupPath &&
|
|
4264
|
+
fs9.writeFileSync(cfgPath, JSON.stringify(cfg));
|
|
4265
|
+
let runnerTsPath = path8.join(path8.dirname(fileURLToPath2(new URL("../builtin-extensions/pi-subagents/src/runs/background/async-execution.js", import.meta.url).href)), "subagent-runner.ts"), runner = fs9.existsSync(runnerTsPath) ? runnerTsPath : runnerTsPath.replace(/\.ts$/, ".js"), nodeCommand = resolveAsyncRunnerNodeCommand(), startupPath = typeof cfg.revivalLease == "object" && typeof cfg.asyncDir == "string" ? path8.join(cfg.asyncDir, "runner-startup.json") : void 0, startupAckPath = startupPath ? path8.join(path8.dirname(startupPath), "runner-startup-ack.json") : void 0, startupProceedPath = startupPath ? path8.join(path8.dirname(startupPath), "runner-startup-proceed.json") : void 0;
|
|
4266
|
+
startupPath && fs9.rmSync(startupPath, { force: !0 }), startupAckPath && fs9.rmSync(startupAckPath, { force: !0 }), startupProceedPath && fs9.rmSync(startupProceedPath, { force: !0 });
|
|
4205
4267
|
let logPaths = resolveAsyncRunnerLogPaths(cfg), stdoutFd, stderrFd;
|
|
4206
4268
|
try {
|
|
4207
|
-
logPaths && (
|
|
4269
|
+
logPaths && (fs9.mkdirSync(path8.dirname(logPaths.stdoutPath), { recursive: !0 }), stdoutFd = fs9.openSync(logPaths.stdoutPath, "a"), stderrFd = fs9.openSync(logPaths.stderrPath, "a"));
|
|
4208
4270
|
let proc = spawn2(nodeCommand, [jitiCliPath, runner, cfgPath], {
|
|
4209
4271
|
cwd,
|
|
4210
4272
|
detached: !0,
|
|
@@ -4238,7 +4300,7 @@ function spawnRunner(cfg, suffix, cwd) {
|
|
|
4238
4300
|
return terminateRunnerBeforeProceed(proc.pid), { error: `Failed to authorize async runner startup: ${error instanceof Error ? error.message : String(error)}` };
|
|
4239
4301
|
}
|
|
4240
4302
|
try {
|
|
4241
|
-
|
|
4303
|
+
fs9.rmSync(startupPath, { force: !0 });
|
|
4242
4304
|
} catch {
|
|
4243
4305
|
}
|
|
4244
4306
|
}
|
|
@@ -4295,10 +4357,10 @@ function buildAsyncRunnerSteps(id, params) {
|
|
|
4295
4357
|
}), toolBudgetInput = spec.toolBudget ?? params.toolBudget ?? params.configToolBudget, resolvedToolBudget = validateToolBudgetConfig(toolBudgetInput, spec.toolBudget ? "toolBudget" : "config.toolBudget");
|
|
4296
4358
|
if (resolvedToolBudget.error)
|
|
4297
4359
|
throw new AsyncStartValidationError(resolvedToolBudget.error);
|
|
4298
|
-
let stepCwd = resolveChildCwd(runnerCwd, s.cwd), instructionCwd = behaviorCwd ?? stepCwd, behavior = suppressProgressForReadOnlyTask(resolvedBehavior ?? resolveStepBehavior(buildStepOverrides(s), chainSkills), s.task, originalTask), inheritedRelativeParallelOutput = parallelOutputNamespace && s.output === void 0 && typeof behavior.output == "string" && !
|
|
4360
|
+
let stepCwd = resolveChildCwd(runnerCwd, s.cwd), instructionCwd = behaviorCwd ?? stepCwd, behavior = suppressProgressForReadOnlyTask(resolvedBehavior ?? resolveStepBehavior(buildStepOverrides(s), chainSkills), s.task, originalTask), inheritedRelativeParallelOutput = parallelOutputNamespace && s.output === void 0 && typeof behavior.output == "string" && !path8.isAbsolute(behavior.output);
|
|
4299
4361
|
inheritedRelativeParallelOutput && parallelOutputNamespace.taskIndex !== void 0 && (behavior = {
|
|
4300
4362
|
...behavior,
|
|
4301
|
-
output:
|
|
4363
|
+
output: path8.join(`parallel-${parallelOutputNamespace.stepIndex}`, String(parallelOutputNamespace.taskIndex), behavior.output)
|
|
4302
4364
|
});
|
|
4303
4365
|
let namespaceOutputPath = !!(inheritedRelativeParallelOutput && parallelOutputNamespace.taskIndex === void 0), skillNames = behavior.skills === !1 ? [] : behavior.skills, { resolved: resolvedSkills, missing: missingSkills } = resolveSkillsWithFallback(skillNames, stepCwd, ctx.cwd, void 0, stepCwd);
|
|
4304
4366
|
if (missingSkills.includes("pi-subagents"))
|
|
@@ -4372,7 +4434,7 @@ ${injection}` : injection;
|
|
|
4372
4434
|
acceptanceInput: s.acceptance,
|
|
4373
4435
|
acceptanceRole: spec.effectivePermissions === "read-only" ? "read-only" : "writer",
|
|
4374
4436
|
...s.outputSchema ? { structuredOutputSchema: s.outputSchema } : {},
|
|
4375
|
-
...s.outputSchema ? { structuredOutput: createStructuredOutputRuntime(s.outputSchema,
|
|
4437
|
+
...s.outputSchema ? { structuredOutput: createStructuredOutputRuntime(s.outputSchema, path8.join(asyncDir, "structured-output")) } : {},
|
|
4376
4438
|
...resolvedToolBudget.budget ? { toolBudget: resolvedToolBudget.budget } : {}
|
|
4377
4439
|
};
|
|
4378
4440
|
}, flatStepIndex = 0, nextFlatStep = () => {
|
|
@@ -4469,9 +4531,9 @@ ${injection}` : injection;
|
|
|
4469
4531
|
}
|
|
4470
4532
|
}
|
|
4471
4533
|
function executeAsyncChain(id, params) {
|
|
4472
|
-
let { chain, ctx, cwd, maxOutput, artifactsDir, artifactConfig, shareEnabled, sessionRoot, sessionFilesByFlatIndex, thinkingOverridesByFlatIndex, maxSubagentDepth, worktreeSetupHook, worktreeSetupHookTimeoutMs, worktreeBaseDir, controlConfig, controlIntercomTarget, childIntercomTarget, nestedRoute } = params, resultMode = params.resultMode ?? "chain", inheritedNestedRoute = resolveInheritedNestedRouteFromEnv(), nestedAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : void 0, asyncDir = inheritedNestedRoute ?
|
|
4534
|
+
let { chain, ctx, cwd, maxOutput, artifactsDir, artifactConfig, shareEnabled, sessionRoot, sessionFilesByFlatIndex, thinkingOverridesByFlatIndex, maxSubagentDepth, worktreeSetupHook, worktreeSetupHookTimeoutMs, worktreeBaseDir, controlConfig, controlIntercomTarget, childIntercomTarget, nestedRoute } = params, resultMode = params.resultMode ?? "chain", inheritedNestedRoute = resolveInheritedNestedRouteFromEnv(), nestedAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : void 0, asyncDir = inheritedNestedRoute ? path8.join(TEMP_ROOT_DIR, "nested-subagent-runs", inheritedNestedRoute.rootRunId, id) : path8.join(ASYNC_DIR, id);
|
|
4473
4535
|
try {
|
|
4474
|
-
|
|
4536
|
+
fs9.mkdirSync(asyncDir, { recursive: !0 });
|
|
4475
4537
|
} catch (error) {
|
|
4476
4538
|
let message = error instanceof Error ? error.message : String(error);
|
|
4477
4539
|
return {
|
|
@@ -4491,8 +4553,8 @@ function executeAsyncChain(id, params) {
|
|
|
4491
4553
|
chainSkills: params.chainSkills,
|
|
4492
4554
|
sessionFilesByFlatIndex,
|
|
4493
4555
|
thinkingOverridesByFlatIndex,
|
|
4494
|
-
progressDir: params.progressDir ?? (artifactsDir ?
|
|
4495
|
-
outputBaseDir: artifactsDir ?
|
|
4556
|
+
progressDir: params.progressDir ?? (artifactsDir ? path8.join(artifactsDir, "progress", id) : resultMode === "parallel" ? path8.join(asyncDir, "progress") : void 0),
|
|
4557
|
+
outputBaseDir: artifactsDir ? path8.join(artifactsDir, "outputs", id) : void 0,
|
|
4496
4558
|
dynamicFanoutMaxItems: params.dynamicFanoutMaxItems,
|
|
4497
4559
|
maxSubagentDepth,
|
|
4498
4560
|
waitToolEnabled: params.waitToolEnabled,
|
|
@@ -4503,7 +4565,7 @@ function executeAsyncChain(id, params) {
|
|
|
4503
4565
|
});
|
|
4504
4566
|
if ("error" in built) {
|
|
4505
4567
|
try {
|
|
4506
|
-
|
|
4568
|
+
fs9.rmSync(asyncDir, { recursive: !0, force: !0 });
|
|
4507
4569
|
} catch {
|
|
4508
4570
|
}
|
|
4509
4571
|
return formatAsyncStartError(resultMode, built.error);
|
|
@@ -4513,14 +4575,14 @@ function executeAsyncChain(id, params) {
|
|
|
4513
4575
|
spawnResult = spawnRunner({
|
|
4514
4576
|
id,
|
|
4515
4577
|
steps,
|
|
4516
|
-
resultPath: inheritedNestedRoute ? nestedResultsPath(inheritedNestedRoute.rootRunId, id) :
|
|
4578
|
+
resultPath: inheritedNestedRoute ? nestedResultsPath(inheritedNestedRoute.rootRunId, id) : path8.join(RESULTS_DIR, `${id}.json`),
|
|
4517
4579
|
cwd: runnerCwd,
|
|
4518
4580
|
placeholder: "{previous}",
|
|
4519
4581
|
maxOutput,
|
|
4520
4582
|
artifactsDir: artifactConfig.enabled ? artifactsDir : void 0,
|
|
4521
4583
|
artifactConfig,
|
|
4522
4584
|
share: shareEnabled,
|
|
4523
|
-
sessionDir: sessionRoot ?
|
|
4585
|
+
sessionDir: sessionRoot ? path8.join(sessionRoot, `async-${id}`) : void 0,
|
|
4524
4586
|
asyncDir,
|
|
4525
4587
|
sessionId: ctx.currentSessionId,
|
|
4526
4588
|
piPackageRoot,
|
|
@@ -4644,9 +4706,9 @@ function executeAsyncSingle(id, params) {
|
|
|
4644
4706
|
|
|
4645
4707
|
${injection}` : injection;
|
|
4646
4708
|
}
|
|
4647
|
-
let inheritedNestedRoute = resolveInheritedNestedRouteFromEnv(), nestedAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : void 0, asyncDir = inheritedNestedRoute ?
|
|
4709
|
+
let inheritedNestedRoute = resolveInheritedNestedRouteFromEnv(), nestedAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : void 0, asyncDir = inheritedNestedRoute ? path8.join(TEMP_ROOT_DIR, "nested-subagent-runs", inheritedNestedRoute.rootRunId, id) : path8.join(ASYNC_DIR, id);
|
|
4648
4710
|
try {
|
|
4649
|
-
|
|
4711
|
+
fs9.mkdirSync(asyncDir, { recursive: !0 });
|
|
4650
4712
|
} catch (error) {
|
|
4651
4713
|
let message = error instanceof Error ? error.message : String(error);
|
|
4652
4714
|
return {
|
|
@@ -4655,7 +4717,7 @@ ${injection}` : injection;
|
|
|
4655
4717
|
details: { mode: "single", results: [] }
|
|
4656
4718
|
};
|
|
4657
4719
|
}
|
|
4658
|
-
let effectiveOutput = normalizeSingleOutputOverride(params.output ?? spec.output, typeof spec.output == "string" ? spec.output : void 0), outputPath = resolveSingleOutputPath(effectiveOutput, ctx.cwd, runnerCwd, params.outputBaseDir ?? (artifactsDir ?
|
|
4720
|
+
let effectiveOutput = normalizeSingleOutputOverride(params.output ?? spec.output, typeof spec.output == "string" ? spec.output : void 0), outputPath = resolveSingleOutputPath(effectiveOutput, ctx.cwd, runnerCwd, params.outputBaseDir ?? (artifactsDir ? path8.join(artifactsDir, "outputs", id) : void 0)), childToolShape = { tools: spec.effectivePermissions === "read-only" ? ["read", "grep", "find", "ls", "bash"] : void 0 };
|
|
4659
4721
|
systemPrompt = injectOutputPathSystemPrompt(systemPrompt, outputPath, childToolShape);
|
|
4660
4722
|
let outputMode = params.outputMode ?? spec.outputMode ?? "inline", validationError = validateFileOnlyOutputMode(outputMode, outputPath, `Async single run (${agent})`);
|
|
4661
4723
|
if (validationError)
|
|
@@ -4673,7 +4735,7 @@ ${injection}` : injection;
|
|
|
4673
4735
|
let deadlineAt = params.absoluteDeadlineAt ?? (params.timeoutMs !== void 0 ? Date.now() + params.timeoutMs : void 0), timeoutMs = params.absoluteDeadlineAt !== void 0 && deadlineAt !== void 0 ? deadlineAt - Date.now() : params.timeoutMs;
|
|
4674
4736
|
if (timeoutMs !== void 0 && timeoutMs <= 0)
|
|
4675
4737
|
return formatAsyncStartError("single", "The source run's absolute deadline expired before recovery could launch.");
|
|
4676
|
-
let initialTurnBudget = params.turnBudget ? initialTurnBudgetState(params.turnBudget) : void 0, resolvedSessionDir = params.sessionDir ?? (sessionRoot ?
|
|
4738
|
+
let initialTurnBudget = params.turnBudget ? initialTurnBudgetState(params.turnBudget) : void 0, resolvedSessionDir = params.sessionDir ?? (sessionRoot ? path8.join(sessionRoot, `async-${id}`) : void 0), resolvedAcceptance = resolveAsyncSingleAcceptance({
|
|
4677
4739
|
restoredAcceptance: params.restoredAcceptance,
|
|
4678
4740
|
launchAcceptance: params.acceptance ?? spec.acceptance,
|
|
4679
4741
|
agentName: agent,
|
|
@@ -4709,7 +4771,7 @@ ${injection}` : injection;
|
|
|
4709
4771
|
artifactConfig
|
|
4710
4772
|
};
|
|
4711
4773
|
try {
|
|
4712
|
-
writePrivateAtomicJson(
|
|
4774
|
+
writePrivateAtomicJson(path8.join(asyncDir, "recovery-descriptor.json"), recoveryDescriptor);
|
|
4713
4775
|
} catch (error) {
|
|
4714
4776
|
return formatAsyncStartError("single", `Failed to persist async recovery descriptor for '${id}': ${error instanceof Error ? error.message : String(error)}`);
|
|
4715
4777
|
}
|
|
@@ -4746,7 +4808,7 @@ ${injection}` : injection;
|
|
|
4746
4808
|
...resolvedToolBudget.budget ? { toolBudget: resolvedToolBudget.budget } : {}
|
|
4747
4809
|
}
|
|
4748
4810
|
],
|
|
4749
|
-
resultPath: inheritedNestedRoute ? nestedResultsPath(inheritedNestedRoute.rootRunId, id) :
|
|
4811
|
+
resultPath: inheritedNestedRoute ? nestedResultsPath(inheritedNestedRoute.rootRunId, id) : path8.join(RESULTS_DIR, `${id}.json`),
|
|
4750
4812
|
cwd: runnerCwd,
|
|
4751
4813
|
placeholder: "{previous}",
|
|
4752
4814
|
maxOutput,
|
|
@@ -4866,11 +4928,11 @@ function lineFromCheck(label, check) {
|
|
|
4866
4928
|
}
|
|
4867
4929
|
function formatExistingDirectory(label, dirPath) {
|
|
4868
4930
|
try {
|
|
4869
|
-
if (!
|
|
4931
|
+
if (!fs10.existsSync(dirPath))
|
|
4870
4932
|
return `- ${label}: missing (${dirPath})`;
|
|
4871
|
-
if (!
|
|
4933
|
+
if (!fs10.statSync(dirPath).isDirectory())
|
|
4872
4934
|
throw new Error(`not a directory: ${dirPath}`);
|
|
4873
|
-
return
|
|
4935
|
+
return fs10.accessSync(dirPath, fs10.constants.R_OK | fs10.constants.W_OK), `- ${label}: ok (${dirPath})`;
|
|
4874
4936
|
} catch (error) {
|
|
4875
4937
|
return `- ${label}: failed (${dirPath}) \u2014 ${errorText(error)}`;
|
|
4876
4938
|
}
|
|
@@ -4893,13 +4955,13 @@ function formatSkillSourceCounts(skills) {
|
|
|
4893
4955
|
return parts.length > 0 ? parts.join(", ") : "none";
|
|
4894
4956
|
}
|
|
4895
4957
|
function formatConfiguredSessionDir(input) {
|
|
4896
|
-
return input.requestedSessionDir ?
|
|
4958
|
+
return input.requestedSessionDir ? path9.resolve(input.expandTilde?.(input.requestedSessionDir) ?? input.requestedSessionDir) : input.config.defaultSessionDir ? path9.resolve(input.expandTilde?.(input.config.defaultSessionDir) ?? input.config.defaultSessionDir) : "not configured";
|
|
4897
4959
|
}
|
|
4898
4960
|
function formatSessionLines(input) {
|
|
4899
4961
|
let sessionFile = input.currentSessionFile ?? null, lines = [
|
|
4900
4962
|
lineFromCheck("configured session dir", () => `- configured session dir: ${formatConfiguredSessionDir(input)}`),
|
|
4901
4963
|
`- current session file: ${sessionFile ?? "not available"}`,
|
|
4902
|
-
`- current session dir: ${sessionFile ?
|
|
4964
|
+
`- current session dir: ${sessionFile ? path9.dirname(sessionFile) : "not available"}`,
|
|
4903
4965
|
`- current session id: ${input.currentSessionId ?? input.state.currentSessionId ?? "not available"}`
|
|
4904
4966
|
];
|
|
4905
4967
|
return input.sessionError && lines.push(`- session manager: failed \u2014 ${input.sessionError}`), lines;
|
|
@@ -5016,19 +5078,19 @@ var WATCHDOG_TOOL_ACTIONS = ["watchdog.status", "watchdog.check", "watchdog.reco
|
|
|
5016
5078
|
|
|
5017
5079
|
// packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/chain-append.js
|
|
5018
5080
|
import { randomUUID } from "node:crypto";
|
|
5019
|
-
import * as
|
|
5020
|
-
import * as
|
|
5081
|
+
import * as fs11 from "node:fs";
|
|
5082
|
+
import * as path10 from "node:path";
|
|
5021
5083
|
var APPEND_REQUESTS_DIR = "append-requests";
|
|
5022
5084
|
function appendDir(asyncDir) {
|
|
5023
|
-
return
|
|
5085
|
+
return path10.join(asyncDir, APPEND_REQUESTS_DIR);
|
|
5024
5086
|
}
|
|
5025
5087
|
function appendRequestPath(asyncDir, request) {
|
|
5026
|
-
return
|
|
5088
|
+
return path10.join(appendDir(asyncDir), `${request.createdAt}-${request.id}.json`);
|
|
5027
5089
|
}
|
|
5028
5090
|
function listAppendRequestFiles(asyncDir) {
|
|
5029
5091
|
let dir = appendDir(asyncDir);
|
|
5030
5092
|
try {
|
|
5031
|
-
return
|
|
5093
|
+
return fs11.readdirSync(dir).filter((entry) => entry.endsWith(".json")).map((entry) => path10.join(dir, entry)).sort();
|
|
5032
5094
|
} catch (error) {
|
|
5033
5095
|
if (error.code === "ENOENT")
|
|
5034
5096
|
return [];
|
|
@@ -5063,9 +5125,9 @@ function enqueueChainAppendRequest(input) {
|
|
|
5063
5125
|
createdAt: input.now ?? Date.now(),
|
|
5064
5126
|
steps: input.steps
|
|
5065
5127
|
};
|
|
5066
|
-
|
|
5067
|
-
let pendingCount = countPendingChainAppendRequests(input.asyncDir), statusPath =
|
|
5068
|
-
return writeAtomicJson(statusPath, updatedStatus), appendJsonl(
|
|
5128
|
+
fs11.mkdirSync(appendDir(input.asyncDir), { recursive: !0 }), writeAtomicJson(appendRequestPath(input.asyncDir, request), request);
|
|
5129
|
+
let pendingCount = countPendingChainAppendRequests(input.asyncDir), statusPath = path10.join(input.asyncDir, "status.json"), updatedStatus = { ...status, pendingAppends: pendingCount, lastUpdate: request.createdAt };
|
|
5130
|
+
return writeAtomicJson(statusPath, updatedStatus), appendJsonl(path10.join(input.asyncDir, "events.jsonl"), JSON.stringify({
|
|
5069
5131
|
type: "subagent.chain.append.requested",
|
|
5070
5132
|
ts: request.createdAt,
|
|
5071
5133
|
runId: input.runId,
|
|
@@ -5075,7 +5137,7 @@ function enqueueChainAppendRequest(input) {
|
|
|
5075
5137
|
})), { request, pendingCount };
|
|
5076
5138
|
}
|
|
5077
5139
|
function readAppendRequest(filePath) {
|
|
5078
|
-
let raw = JSON.parse(
|
|
5140
|
+
let raw = JSON.parse(fs11.readFileSync(filePath, "utf-8"));
|
|
5079
5141
|
if (!(!raw.id || typeof raw.id != "string") && Number.isFinite(raw.createdAt) && !(!Array.isArray(raw.steps) || raw.steps.length === 0))
|
|
5080
5142
|
return { id: raw.id, createdAt: raw.createdAt, steps: raw.steps };
|
|
5081
5143
|
}
|
|
@@ -5085,8 +5147,8 @@ function readPendingChainAppendRequests(asyncDir) {
|
|
|
5085
5147
|
|
|
5086
5148
|
// packages/coding-agent/dist/builtin-extensions/pi-subagents/src/shared/fork-context.js
|
|
5087
5149
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
5088
|
-
import * as
|
|
5089
|
-
import * as
|
|
5150
|
+
import * as fs12 from "node:fs";
|
|
5151
|
+
import * as path11 from "node:path";
|
|
5090
5152
|
function resolveSubagentContext(value) {
|
|
5091
5153
|
return value === "fork" ? "fork" : "fresh";
|
|
5092
5154
|
}
|
|
@@ -5140,7 +5202,7 @@ function sanitizeUnsafeThinkingBlocks(entries) {
|
|
|
5140
5202
|
return sanitized;
|
|
5141
5203
|
}
|
|
5142
5204
|
function readSessionEntries(sessionFile) {
|
|
5143
|
-
return
|
|
5205
|
+
return fs12.readFileSync(sessionFile, "utf-8").split(`
|
|
5144
5206
|
`).filter((line) => line.trim().length > 0).map((line, index) => {
|
|
5145
5207
|
try {
|
|
5146
5208
|
return JSON.parse(line);
|
|
@@ -5169,22 +5231,22 @@ function createForkContextResolver(sessionManager, requestedContext, options = {
|
|
|
5169
5231
|
if (cached)
|
|
5170
5232
|
return cached;
|
|
5171
5233
|
try {
|
|
5172
|
-
if (!
|
|
5234
|
+
if (!fs12.existsSync(parentSessionFile))
|
|
5173
5235
|
throw new Error(`Parent session file does not exist: ${parentSessionFile}. Pi has not persisted enough history to fork yet.`);
|
|
5174
5236
|
let sourceManager = openSession(parentSessionFile, sessionDir), sessionFile = sourceManager.createBranchedSession(leafId);
|
|
5175
5237
|
if (!sessionFile)
|
|
5176
5238
|
throw new Error("Session manager did not return a forked session file.");
|
|
5177
5239
|
let forceThinkingOff = (sanitized) => sanitized && (options.forceThinkingOffForIndex?.(index) ?? !0), thinkingOverride;
|
|
5178
|
-
if (
|
|
5240
|
+
if (fs12.existsSync(sessionFile)) {
|
|
5179
5241
|
let entries = readSessionEntries(sessionFile);
|
|
5180
|
-
sanitizeUnsafeThinkingBlocks(entries) && (forceThinkingOff(!0) && (appendThinkingOffEntry(entries), thinkingOverride = "off"),
|
|
5242
|
+
sanitizeUnsafeThinkingBlocks(entries) && (forceThinkingOff(!0) && (appendThinkingOffEntry(entries), thinkingOverride = "off"), fs12.writeFileSync(sessionFile, `${entries.map((entry) => JSON.stringify(entry)).join(`
|
|
5181
5243
|
`)}
|
|
5182
5244
|
`, "utf-8"));
|
|
5183
5245
|
} else {
|
|
5184
5246
|
let header = sourceManager.getHeader?.(), entries = sourceManager.getEntries?.();
|
|
5185
5247
|
if (!header || !entries)
|
|
5186
5248
|
throw new Error(`Session manager returned a forked session file that does not exist and cannot be persisted by fallback: ${sessionFile}`);
|
|
5187
|
-
forceThinkingOff(sanitizeUnsafeThinkingBlocks(entries)) && (appendThinkingOffEntry(entries), thinkingOverride = "off"),
|
|
5249
|
+
forceThinkingOff(sanitizeUnsafeThinkingBlocks(entries)) && (appendThinkingOffEntry(entries), thinkingOverride = "off"), fs12.mkdirSync(path11.dirname(sessionFile), { recursive: !0 }), fs12.writeFileSync(sessionFile, `${[header, ...entries].map((entry) => JSON.stringify(entry)).join(`
|
|
5188
5250
|
`)}
|
|
5189
5251
|
`, "utf-8");
|
|
5190
5252
|
}
|
|
@@ -5215,8 +5277,8 @@ function lunrContextPolicy(params) {
|
|
|
5215
5277
|
}
|
|
5216
5278
|
|
|
5217
5279
|
// packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/steering.js
|
|
5218
|
-
import * as
|
|
5219
|
-
import * as
|
|
5280
|
+
import * as fs13 from "node:fs";
|
|
5281
|
+
import * as path12 from "node:path";
|
|
5220
5282
|
function incrementStateCount(status, state) {
|
|
5221
5283
|
state === "scheduled" ? status.scheduled++ : state === "routed" ? status.pending++ : state === "delivered" || state === "late" ? status.delivered++ : state === "failed" ? status.failed++ : state === "recovered" && status.recovered++;
|
|
5222
5284
|
}
|
|
@@ -5248,29 +5310,29 @@ function steeringActionIsTerminal(result2) {
|
|
|
5248
5310
|
return result2?.state === "delivered" || result2?.state === "scheduled" || result2?.state === "partial" || result2?.state === "recovered" || result2?.state === "failed";
|
|
5249
5311
|
}
|
|
5250
5312
|
function claimSteeringRecovery(asyncDir, input) {
|
|
5251
|
-
let recoveryDir =
|
|
5252
|
-
|
|
5253
|
-
let claimPath =
|
|
5313
|
+
let recoveryDir = path12.join(asyncDir, "control", "steer-recovery");
|
|
5314
|
+
fs13.mkdirSync(recoveryDir, { recursive: !0, mode: 448 });
|
|
5315
|
+
let claimPath = path12.join(recoveryDir, "claim.json"), fd;
|
|
5254
5316
|
try {
|
|
5255
|
-
fd =
|
|
5317
|
+
fd = fs13.openSync(claimPath, "wx", 384);
|
|
5256
5318
|
} catch (error) {
|
|
5257
5319
|
throw error.code === "EEXIST" ? new Error("Another steering recovery is already committed for this source run.") : error;
|
|
5258
5320
|
}
|
|
5259
5321
|
let writeError;
|
|
5260
5322
|
try {
|
|
5261
|
-
|
|
5323
|
+
fs13.writeFileSync(fd, JSON.stringify({ version: 1, ...input }, null, 2), "utf-8"), fs13.fsyncSync(fd);
|
|
5262
5324
|
} catch (error) {
|
|
5263
5325
|
writeError = error;
|
|
5264
5326
|
} finally {
|
|
5265
|
-
|
|
5327
|
+
fs13.closeSync(fd);
|
|
5266
5328
|
}
|
|
5267
5329
|
if (writeError !== void 0)
|
|
5268
|
-
throw
|
|
5269
|
-
let markerPath =
|
|
5330
|
+
throw fs13.rmSync(claimPath, { force: !0 }), writeError;
|
|
5331
|
+
let markerPath = path12.join(recoveryDir, `${Buffer.from(input.requestId).toString("base64url")}.json`);
|
|
5270
5332
|
try {
|
|
5271
5333
|
writePrivateAtomicJson(markerPath, { version: 1, ...input });
|
|
5272
5334
|
} catch (error) {
|
|
5273
|
-
throw
|
|
5335
|
+
throw fs13.rmSync(claimPath, { force: !0 }), error;
|
|
5274
5336
|
}
|
|
5275
5337
|
return { claimPath, markerPath };
|
|
5276
5338
|
}
|
|
@@ -5321,8 +5383,8 @@ async function waitForSteeringAction(input) {
|
|
|
5321
5383
|
|
|
5322
5384
|
// packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/foreground/async-steering-action.js
|
|
5323
5385
|
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
5324
|
-
import * as
|
|
5325
|
-
import * as
|
|
5386
|
+
import * as fs14 from "node:fs";
|
|
5387
|
+
import * as path13 from "node:path";
|
|
5326
5388
|
async function steerAsyncRun(input) {
|
|
5327
5389
|
if (!input.location.asyncDir)
|
|
5328
5390
|
return {
|
|
@@ -5403,7 +5465,7 @@ async function steerAsyncRun(input) {
|
|
|
5403
5465
|
if (status.mode === "single" && status.isNested !== !0 && running.length === 1 && !!finalStatus?.steering && (input.index === void 0 || input.index === 0) && finalResult?.state !== "scheduled" && input.recover) {
|
|
5404
5466
|
let appendSteeringNotice = (state, message) => {
|
|
5405
5467
|
try {
|
|
5406
|
-
|
|
5468
|
+
fs14.appendFileSync(path13.join(asyncDir, "events.jsonl"), `${JSON.stringify({ type: "subagent.steering.notice", ts: Date.now(), runId: status.runId, requestId, state, message, ...status.sessionId ? { currentSessionId: status.sessionId } : {} })}
|
|
5407
5469
|
`);
|
|
5408
5470
|
} catch {
|
|
5409
5471
|
}
|
|
@@ -5416,11 +5478,11 @@ async function steerAsyncRun(input) {
|
|
|
5416
5478
|
input.onRecoveryCommitted?.(requestId, committedAt);
|
|
5417
5479
|
let preCommitStatus = readStatus(asyncDir), preCommitResult = preCommitStatus?.steering ? actionResultFromSteeringStatus(preCommitStatus.steering, status.runId, requestId) : void 0;
|
|
5418
5480
|
if (preCommitResult?.state === "delivered" && preCommitResult.targets.every((target) => target.deliveredAt !== void 0 && target.deliveredAt <= committedAt))
|
|
5419
|
-
return
|
|
5481
|
+
return fs14.rmSync(markerPath, { force: !0 }), fs14.rmSync(claimPath, { force: !0 }), { content: [{ type: "text", text: `Steering delivered for async run ${status.runId} (request ${requestId}).` }], details: { mode: "management", results: [], steering: preCommitResult } };
|
|
5420
5482
|
try {
|
|
5421
5483
|
deliverInterruptRequest({ asyncDir, pid: latest?.pid ?? status.pid, kill: input.kill, source: "steering-recovery" });
|
|
5422
5484
|
} catch (error) {
|
|
5423
|
-
throw
|
|
5485
|
+
throw fs14.rmSync(markerPath, { force: !0 }), fs14.rmSync(claimPath, { force: !0 }), new Error(`Failed to commit steering recovery interrupt: ${error instanceof Error ? error.message : String(error)}`);
|
|
5424
5486
|
}
|
|
5425
5487
|
let pauseDeadline = Date.now() + (input.recoveryTimeoutMs ?? 15e3), paused = null;
|
|
5426
5488
|
for (; Date.now() <= pauseDeadline && !input.signal?.aborted; ) {
|
|
@@ -5442,12 +5504,12 @@ async function steerAsyncRun(input) {
|
|
|
5442
5504
|
let stepSteering = paused.steps?.[ack.index]?.steering;
|
|
5443
5505
|
stepSteering && updateSteeringTarget(stepSteering, ack.requestId, ack.index, state, ack.ts, { reason }), lateAckRecorded = !0;
|
|
5444
5506
|
try {
|
|
5445
|
-
|
|
5507
|
+
fs14.appendFileSync(path13.join(asyncDir, "events.jsonl"), `${JSON.stringify({ type: ack.state === "delivered" ? "subagent.steer.delivered" : "subagent.steer.failed", ts: ack.ts, runId: status.runId, requestId: ack.requestId, index: ack.index, late: !0, message: ack.message })}
|
|
5446
5508
|
`);
|
|
5447
5509
|
} catch {
|
|
5448
5510
|
}
|
|
5449
5511
|
}
|
|
5450
|
-
lateAckRecorded && writeAtomicJson(
|
|
5512
|
+
lateAckRecorded && writeAtomicJson(path13.join(asyncDir, "status.json"), paused);
|
|
5451
5513
|
let recoveryTarget;
|
|
5452
5514
|
try {
|
|
5453
5515
|
recoveryTarget = resolveAsyncResumeTarget({ id: status.runId }, { kill: input.kill });
|
|
@@ -5465,7 +5527,7 @@ async function steerAsyncRun(input) {
|
|
|
5465
5527
|
if (sourceStatus?.state === "paused" && sourceStatus.steering && targetIndex >= 0) {
|
|
5466
5528
|
updateSteeringTarget(sourceStatus.steering, requestId, targetIndex, "recovered", Date.now(), { replacementRunId: revived.details.asyncId });
|
|
5467
5529
|
let stepSteering = sourceStatus.steps?.[targetIndex]?.steering;
|
|
5468
|
-
stepSteering && updateSteeringTarget(stepSteering, requestId, targetIndex, "recovered", Date.now(), { replacementRunId: revived.details.asyncId }), writeAtomicJson(
|
|
5530
|
+
stepSteering && updateSteeringTarget(stepSteering, requestId, targetIndex, "recovered", Date.now(), { replacementRunId: revived.details.asyncId }), writeAtomicJson(path13.join(asyncDir, "status.json"), sourceStatus);
|
|
5469
5531
|
}
|
|
5470
5532
|
let recovered = sourceStatus?.steering ? actionResultFromSteeringStatus(sourceStatus.steering, status.runId, requestId, revived.details.asyncId) : void 0;
|
|
5471
5533
|
return appendSteeringNotice("recovered", `Steering recovered for run ${status.runId}; replacement ${revived.details.asyncId} launched.`), { content: [{ type: "text", text: `Steering recovered for async run ${status.runId}; replacement ${revived.details.asyncId} launched after the source paused.` }], details: { mode: "management", results: [], steering: recovered ?? { requestId, state: "recovered", sourceRunId: status.runId, replacementRunId: revived.details.asyncId, targets: [{ index: input.index ?? 0, state: "recovered" }] } } };
|
|
@@ -5474,7 +5536,7 @@ async function steerAsyncRun(input) {
|
|
|
5474
5536
|
if (failedStatus && failedStatus.state !== "running" && failedStatus.state !== "queued" && failedStatus.steering && targetIndex >= 0) {
|
|
5475
5537
|
updateSteeringTarget(failedStatus.steering, requestId, targetIndex, "failed", Date.now(), { reason });
|
|
5476
5538
|
let stepSteering = failedStatus.steps?.[targetIndex]?.steering;
|
|
5477
|
-
stepSteering && updateSteeringTarget(stepSteering, requestId, targetIndex, "failed", Date.now(), { reason }), failedStatus.activityState = "needs_attention", writeAtomicJson(
|
|
5539
|
+
stepSteering && updateSteeringTarget(stepSteering, requestId, targetIndex, "failed", Date.now(), { reason }), failedStatus.activityState = "needs_attention", writeAtomicJson(path13.join(asyncDir, "status.json"), failedStatus);
|
|
5478
5540
|
}
|
|
5479
5541
|
let failed = failedStatus?.steering ? actionResultFromSteeringStatus(failedStatus.steering, status.runId, requestId) : void 0;
|
|
5480
5542
|
return appendSteeringNotice("failed", `Steering failed for run ${status.runId}: ${reason}`), { content: [{ type: "text", text: `Steering failed for async run ${status.runId} (request ${requestId}): ${reason}` }], isError: !0, details: { mode: "management", results: [], steering: failed ?? { requestId, state: "failed", sourceRunId: status.runId, targets: [{ index: input.index ?? 0, state: "failed", reason }] } } };
|
|
@@ -5489,16 +5551,16 @@ async function steerAsyncRun(input) {
|
|
|
5489
5551
|
}
|
|
5490
5552
|
|
|
5491
5553
|
// packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/chain-root-attachment.js
|
|
5492
|
-
import * as
|
|
5554
|
+
import * as path14 from "node:path";
|
|
5493
5555
|
function resolveAsyncRootResultPath(resultsDir, runId) {
|
|
5494
|
-
return
|
|
5556
|
+
return path14.join(resultsDir, `${runId}.json`);
|
|
5495
5557
|
}
|
|
5496
5558
|
|
|
5497
5559
|
// packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/run-status.js
|
|
5498
|
-
import * as
|
|
5499
|
-
import * as
|
|
5560
|
+
import * as fs15 from "node:fs";
|
|
5561
|
+
import * as path15 from "node:path";
|
|
5500
5562
|
function hasExistingSessionFile(value) {
|
|
5501
|
-
return typeof value == "string" &&
|
|
5563
|
+
return typeof value == "string" && fs15.existsSync(value);
|
|
5502
5564
|
}
|
|
5503
5565
|
function formatResumeGuidance(runId, children, fallbackSessionFile, options = {}) {
|
|
5504
5566
|
if (options.stopped)
|
|
@@ -5534,9 +5596,9 @@ function formatSteeringSummary(input) {
|
|
|
5534
5596
|
}
|
|
5535
5597
|
function rememberedForegroundChildOutput(child) {
|
|
5536
5598
|
let outputPath = child.artifactPaths?.outputPath ?? child.savedOutputPath;
|
|
5537
|
-
if (outputPath &&
|
|
5599
|
+
if (outputPath && fs15.existsSync(outputPath))
|
|
5538
5600
|
try {
|
|
5539
|
-
let artifactOutput =
|
|
5601
|
+
let artifactOutput = fs15.readFileSync(outputPath, "utf-8").trim();
|
|
5540
5602
|
if (artifactOutput)
|
|
5541
5603
|
return artifactOutput;
|
|
5542
5604
|
} catch {
|
|
@@ -5709,7 +5771,7 @@ function inspectSubagentStatus(params, deps = {}) {
|
|
|
5709
5771
|
details: { mode: "single", results: [] }
|
|
5710
5772
|
};
|
|
5711
5773
|
}
|
|
5712
|
-
let status = reconciliation.status, effectiveRunId = status?.runId ?? resolvedId ?? "unknown", logPath =
|
|
5774
|
+
let status = reconciliation.status, effectiveRunId = status?.runId ?? resolvedId ?? "unknown", logPath = path15.join(asyncDir, `subagent-log-${effectiveRunId}.md`), eventsPath = path15.join(asyncDir, "events.jsonl");
|
|
5713
5775
|
if (status) {
|
|
5714
5776
|
if (params.view === "transcript") {
|
|
5715
5777
|
if (currentSessionId && status.sessionId !== currentSessionId)
|
|
@@ -5753,22 +5815,22 @@ function inspectSubagentStatus(params, deps = {}) {
|
|
|
5753
5815
|
`Dir: ${asyncDir}`,
|
|
5754
5816
|
outputPath ? `Output: ${outputPath}` : void 0,
|
|
5755
5817
|
reconciliation.message ? `Diagnosis: ${reconciliation.message}` : void 0,
|
|
5756
|
-
reconciliation.resultPath &&
|
|
5818
|
+
reconciliation.resultPath && fs15.existsSync(reconciliation.resultPath) ? `Result: ${reconciliation.resultPath}` : void 0
|
|
5757
5819
|
].filter((line) => !!line);
|
|
5758
5820
|
for (let [index, step] of (status.steps ?? []).entries()) {
|
|
5759
5821
|
let stepActivityText = step.status === "running" ? formatActivityLabel(step.lastActivityAt, step.activityState) : void 0, modelThinking = formatModelSelection(step.modelSelection, step.model, step.thinking), modelText = modelThinking ? ` (${modelThinking})` : "", steeringText2 = formatSteeringSummary(step), steeringSuffix = steeringText2 ? `, steering: ${steeringText2}` : "", errorText2 = step.error ? `, error: ${step.error}` : "", acceptanceText = step.acceptance?.status ? `, acceptance: ${step.acceptance.status}` : "", budgetText = step.turnBudget ? `, turn budget: ${step.turnBudget.turnCount}/${step.turnBudget.maxTurns}+${step.turnBudget.graceTurns} (${step.turnBudget.outcome})` : "", display = step.label ? `${step.label} (${step.agent})` : step.agent, phase = step.phase ? `[${step.phase}] ` : "";
|
|
5760
5822
|
lines.push(`${stepLineLabel(status, index)}: ${phase}${display} ${step.status}${modelText}${stepActivityText ? `, ${stepActivityText}` : ""}${steeringSuffix}${acceptanceText}${budgetText}${errorText2}`), lines.push(...formatNestedRunStatusLines(step.children, { indent: " ", commandHints: !0, maxLines: 20 }));
|
|
5761
|
-
let stepOutputPath =
|
|
5762
|
-
stepOutputPath !== outputPath &&
|
|
5823
|
+
let stepOutputPath = path15.join(asyncDir, `output-${index}.log`);
|
|
5824
|
+
stepOutputPath !== outputPath && fs15.existsSync(stepOutputPath) && lines.push(` Output: ${stepOutputPath}`), step.status === "running" && (lines.push(` Intercom target: ${resolveSubagentIntercomTarget(status.runId, step.childId ?? step.agent, index)} (if registered)`), lines.push(` Steer: subagent({ action: "steer", id: "${status.runId}", index: ${index}, message: "..." })`));
|
|
5763
5825
|
}
|
|
5764
5826
|
let attached = new Set((status.steps ?? []).flatMap((step) => step.children?.map((child) => child.id) ?? [])), unattached = nestedChildren.filter((child) => !attached.has(child.id));
|
|
5765
|
-
return lines.push(...formatNestedRunStatusLines(unattached, { indent: "", commandHints: !0, maxLines: 20 })), nestedWarning && lines.push(`Warning: ${nestedWarning}`), status.sessionFile && lines.push(`Session: ${status.sessionFile}`), status.state === "running" && lines.push(`Steer running child: subagent({ action: "steer", id: "${status.runId}", message: "..." })`), status.state !== "running" && lines.push(formatResumeGuidance(status.runId, status.steps ?? [], status.sessionFile, { stopped: status.state === "stopped" || status.stopped === !0 })),
|
|
5827
|
+
return lines.push(...formatNestedRunStatusLines(unattached, { indent: "", commandHints: !0, maxLines: 20 })), nestedWarning && lines.push(`Warning: ${nestedWarning}`), status.sessionFile && lines.push(`Session: ${status.sessionFile}`), status.state === "running" && lines.push(`Steer running child: subagent({ action: "steer", id: "${status.runId}", message: "..." })`), status.state !== "running" && lines.push(formatResumeGuidance(status.runId, status.steps ?? [], status.sessionFile, { stopped: status.state === "stopped" || status.stopped === !0 })), fs15.existsSync(logPath) && lines.push(`Log: ${logPath}`), fs15.existsSync(eventsPath) && lines.push(`Events: ${eventsPath}`), { content: [{ type: "text", text: lines.join(`
|
|
5766
5828
|
`) }], details: { mode: "single", results: [] } };
|
|
5767
5829
|
}
|
|
5768
5830
|
}
|
|
5769
5831
|
if (resultPath)
|
|
5770
5832
|
try {
|
|
5771
|
-
let raw =
|
|
5833
|
+
let raw = fs15.readFileSync(resultPath, "utf-8"), data = JSON.parse(raw);
|
|
5772
5834
|
if (params.view === "transcript")
|
|
5773
5835
|
try {
|
|
5774
5836
|
return { content: [{ type: "text", text: formatAsyncResultTranscript(data, resultPath, { index: params.index, lines: params.lines }) }], details: { mode: "single", results: [] } };
|
|
@@ -5795,7 +5857,7 @@ function inspectSubagentStatus(params, deps = {}) {
|
|
|
5795
5857
|
// packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js
|
|
5796
5858
|
var MUTATING_MANAGEMENT_ACTIONS = /* @__PURE__ */ new Set(["create", "update", "delete", "eject", "disable", "enable", "reset"]);
|
|
5797
5859
|
function resolveRequestedCwd(runtimeCwd, requestedCwd) {
|
|
5798
|
-
return requestedCwd ?
|
|
5860
|
+
return requestedCwd ? path16.resolve(runtimeCwd, requestedCwd) : runtimeCwd;
|
|
5799
5861
|
}
|
|
5800
5862
|
function getForegroundControl(state, runId) {
|
|
5801
5863
|
if (runId)
|
|
@@ -5827,7 +5889,7 @@ function nestedResolutionScopeForExecutor(deps) {
|
|
|
5827
5889
|
};
|
|
5828
5890
|
}
|
|
5829
5891
|
function trustedSessionRootsForStatus(ctx, deps) {
|
|
5830
|
-
let roots = deps.config.defaultSessionDir ? [
|
|
5892
|
+
let roots = deps.config.defaultSessionDir ? [path16.resolve(deps.expandTilde(deps.config.defaultSessionDir))] : [], parentSessionFile = ctx.sessionManager.getSessionFile() ?? null;
|
|
5831
5893
|
return parentSessionFile && roots.push(deps.getSubagentSessionRoot(parentSessionFile)), [...new Set(roots)];
|
|
5832
5894
|
}
|
|
5833
5895
|
function reserveSubagentSpawns(input) {
|
|
@@ -5949,7 +6011,8 @@ ${output}` : ""}` : output || input.result.error || "Detached child exited witho
|
|
|
5949
6011
|
cwd: input.cwd,
|
|
5950
6012
|
sessionFile: input.result.sessionFile,
|
|
5951
6013
|
sessionId: input.sessionId,
|
|
5952
|
-
taskIndex: input.index
|
|
6014
|
+
taskIndex: input.index,
|
|
6015
|
+
results: [{ childId: input.result.childId, agent: input.result.agent, sessionFile: input.result.sessionFile, usage: input.result.usage, usageRequests: input.result.usageRequests, success, output: summary }]
|
|
5953
6016
|
});
|
|
5954
6017
|
}
|
|
5955
6018
|
function resolveForegroundResumeTarget(params, state) {
|
|
@@ -5974,10 +6037,10 @@ function resolveForegroundResumeTarget(params, state) {
|
|
|
5974
6037
|
let child = run.children[index];
|
|
5975
6038
|
if (!child.sessionFile)
|
|
5976
6039
|
throw new Error(`Foreground run '${run.runId}' child ${index} does not have a persisted session file to resume from.`);
|
|
5977
|
-
if (
|
|
6040
|
+
if (path16.extname(child.sessionFile) !== ".jsonl")
|
|
5978
6041
|
throw new Error(`Foreground run '${run.runId}' child ${index} session file must be a .jsonl file: ${child.sessionFile}`);
|
|
5979
|
-
let sessionFile =
|
|
5980
|
-
if (!
|
|
6042
|
+
let sessionFile = path16.resolve(child.sessionFile);
|
|
6043
|
+
if (!fs16.existsSync(sessionFile))
|
|
5981
6044
|
throw new Error(`Foreground run '${run.runId}' child ${index} session file does not exist: ${child.sessionFile}`);
|
|
5982
6045
|
return { runId: run.runId, mode: run.mode, state: "complete", agent: child.agent, index, intercomTarget: resolveSubagentIntercomTarget(run.runId, child.agent, index), cwd: run.cwd, sessionFile };
|
|
5983
6046
|
}
|
|
@@ -6032,7 +6095,7 @@ function resolveResumeTarget(params, state, options = {}) {
|
|
|
6032
6095
|
function getAsyncInterruptTarget(state, runId, location) {
|
|
6033
6096
|
if (location?.asyncDir)
|
|
6034
6097
|
return {
|
|
6035
|
-
asyncId: location.resolvedId ?? runId ??
|
|
6098
|
+
asyncId: location.resolvedId ?? runId ?? path16.basename(location.asyncDir),
|
|
6036
6099
|
asyncDir: location.asyncDir
|
|
6037
6100
|
};
|
|
6038
6101
|
if (runId) {
|
|
@@ -6300,27 +6363,27 @@ function nestedRunAgent(run) {
|
|
|
6300
6363
|
return run.agent ?? run.agents?.[0] ?? (run.steps?.length === 1 ? run.steps[0]?.agent : void 0);
|
|
6301
6364
|
}
|
|
6302
6365
|
function pathWithin(base, candidate) {
|
|
6303
|
-
let resolvedBase =
|
|
6304
|
-
return resolvedCandidate === resolvedBase || resolvedCandidate.startsWith(`${resolvedBase}${
|
|
6366
|
+
let resolvedBase = path16.resolve(base), resolvedCandidate = path16.resolve(candidate);
|
|
6367
|
+
return resolvedCandidate === resolvedBase || resolvedCandidate.startsWith(`${resolvedBase}${path16.sep}`);
|
|
6305
6368
|
}
|
|
6306
6369
|
function validateNestedSessionFile(run, trustedSessionRoots) {
|
|
6307
6370
|
let sessionFile = nestedRunSessionFile(run);
|
|
6308
6371
|
if (!sessionFile)
|
|
6309
6372
|
throw new Error(`Nested run '${run.id}' does not have a persisted session file to resume from.`);
|
|
6310
|
-
if (
|
|
6373
|
+
if (path16.extname(sessionFile) !== ".jsonl")
|
|
6311
6374
|
throw new Error(`Nested run '${run.id}' session file must be a .jsonl file: ${sessionFile}`);
|
|
6312
|
-
let resolved =
|
|
6313
|
-
if (!
|
|
6375
|
+
let resolved = path16.resolve(sessionFile);
|
|
6376
|
+
if (!path16.isAbsolute(sessionFile))
|
|
6314
6377
|
throw new Error(`Nested run '${run.id}' session file must be absolute: ${sessionFile}`);
|
|
6315
|
-
if (!
|
|
6378
|
+
if (!fs16.existsSync(resolved))
|
|
6316
6379
|
throw new Error(`Nested run '${run.id}' session file does not exist: ${sessionFile}`);
|
|
6317
|
-
let stat =
|
|
6380
|
+
let stat = fs16.lstatSync(resolved);
|
|
6318
6381
|
if (!stat.isFile() || stat.isSymbolicLink())
|
|
6319
6382
|
throw new Error(`Nested run '${run.id}' session file is not a regular file: ${sessionFile}`);
|
|
6320
|
-
let realSessionFile =
|
|
6321
|
-
if (!trustedSessionRoots.filter((root) =>
|
|
6383
|
+
let realSessionFile = fs16.realpathSync(resolved);
|
|
6384
|
+
if (!trustedSessionRoots.filter((root) => fs16.existsSync(root)).map((root) => fs16.realpathSync(root)).some((root) => pathWithin(root, realSessionFile)))
|
|
6322
6385
|
throw new Error(`Nested run '${run.id}' session file is outside trusted nested session roots: ${sessionFile}`);
|
|
6323
|
-
if (!realSessionFile.split(
|
|
6386
|
+
if (!realSessionFile.split(path16.sep).includes(run.id))
|
|
6324
6387
|
throw new Error(`Nested run '${run.id}' session file is not under that nested run's session directory: ${sessionFile}`);
|
|
6325
6388
|
return realSessionFile;
|
|
6326
6389
|
}
|
|
@@ -6340,7 +6403,7 @@ function resolveNestedResumeTarget(match, trustedSessionRoots) {
|
|
|
6340
6403
|
agent,
|
|
6341
6404
|
index: 0,
|
|
6342
6405
|
intercomTarget: resolveSubagentIntercomTarget(run.id, agent, 0),
|
|
6343
|
-
cwd: asyncDir ?
|
|
6406
|
+
cwd: asyncDir ? path16.dirname(asyncDir) : void 0,
|
|
6344
6407
|
sessionFile: validateNestedSessionFile(run, trustedSessionRoots)
|
|
6345
6408
|
};
|
|
6346
6409
|
}
|
|
@@ -6367,7 +6430,7 @@ function directNestedAsyncInterrupt(target) {
|
|
|
6367
6430
|
let run = target.match.run, asyncDir = resolveNestedAsyncDir(target.match.rootRunId, run);
|
|
6368
6431
|
if (!asyncDir)
|
|
6369
6432
|
return;
|
|
6370
|
-
let status = reconcileAsyncRun(asyncDir, { resultsDir:
|
|
6433
|
+
let status = reconcileAsyncRun(asyncDir, { resultsDir: path16.join(RESULTS_DIR, "nested", target.match.rootRunId) }).status, pid = typeof status?.pid == "number" && status.pid > 0 ? status.pid : run.pid;
|
|
6371
6434
|
if (!(!status || status.state !== "running" || typeof pid != "number" || pid <= 0))
|
|
6372
6435
|
try {
|
|
6373
6436
|
return deliverInterruptRequest({ asyncDir, pid, source: "nested-interrupt" }), { content: [{ type: "text", text: `Interrupt requested for nested async run ${run.id}.` }], details: { mode: "management", results: [] } };
|
|
@@ -6380,7 +6443,7 @@ async function directNestedAsyncSteer(input) {
|
|
|
6380
6443
|
let run = input.target.match.run, asyncDir = resolveNestedAsyncDir(input.target.match.rootRunId, run);
|
|
6381
6444
|
if (!asyncDir)
|
|
6382
6445
|
return;
|
|
6383
|
-
let status = reconcileAsyncRun(asyncDir, { resultsDir:
|
|
6446
|
+
let status = reconcileAsyncRun(asyncDir, { resultsDir: path16.join(RESULTS_DIR, "nested", input.target.match.rootRunId) }).status;
|
|
6384
6447
|
if (!status || status.state !== "running" && status.state !== "queued")
|
|
6385
6448
|
return;
|
|
6386
6449
|
let steps = status.steps ?? [];
|
|
@@ -6474,7 +6537,7 @@ async function resumeAsyncRun(input) {
|
|
|
6474
6537
|
if (resolved.match.run.state === "running" || resolved.match.run.state === "queued")
|
|
6475
6538
|
return resumeLiveNestedRun({ target: resolved, message: followUp });
|
|
6476
6539
|
let trustedSessionRoots = [
|
|
6477
|
-
...input.deps.config.defaultSessionDir ? [
|
|
6540
|
+
...input.deps.config.defaultSessionDir ? [path16.resolve(input.deps.expandTilde(input.deps.config.defaultSessionDir))] : [],
|
|
6478
6541
|
...parentSessionFile ? [input.deps.getSubagentSessionRoot(parentSessionFile)] : []
|
|
6479
6542
|
];
|
|
6480
6543
|
target = resolveNestedResumeTarget(resolved, trustedSessionRoots);
|
|
@@ -6540,7 +6603,7 @@ ${followUp}`, 500, { source: "async-resume", runId: target.runId, agent: target.
|
|
|
6540
6603
|
goal,
|
|
6541
6604
|
attachRoot: {
|
|
6542
6605
|
runId: target.runId,
|
|
6543
|
-
asyncDir: target.asyncDir ??
|
|
6606
|
+
asyncDir: target.asyncDir ?? path16.join(ASYNC_DIR, target.runId),
|
|
6544
6607
|
resultPath: resolveAsyncRootResultPath(RESULTS_DIR, target.runId),
|
|
6545
6608
|
index: target.index,
|
|
6546
6609
|
agent: target.agent,
|
|
@@ -7484,7 +7547,7 @@ function buildParallelWorktreeTaskCwdError(tasks, sharedCwd) {
|
|
|
7484
7547
|
return formatWorktreeTaskCwdConflict(conflict, sharedCwd);
|
|
7485
7548
|
}
|
|
7486
7549
|
function resolveSingleRunOutputBaseDir(deps, artifactsDir, runId) {
|
|
7487
|
-
return deps.config.singleRunOutputBaseDir ?
|
|
7550
|
+
return deps.config.singleRunOutputBaseDir ? path16.resolve(deps.expandTilde(deps.config.singleRunOutputBaseDir)) : path16.join(artifactsDir, "outputs", runId);
|
|
7488
7551
|
}
|
|
7489
7552
|
function buildChainWorktreeTaskCwdError(chain, sharedCwd) {
|
|
7490
7553
|
for (let stepIndex = 0; stepIndex < chain.length; stepIndex++) {
|
|
@@ -7504,7 +7567,7 @@ function resolveParallelTaskCwd(task, paramsCwd, worktreeSetup, index) {
|
|
|
7504
7567
|
function buildParallelWorktreeSuffix(worktreeSetup, artifactsDir, tasks) {
|
|
7505
7568
|
if (!worktreeSetup)
|
|
7506
7569
|
return "";
|
|
7507
|
-
let diffsDir =
|
|
7570
|
+
let diffsDir = path16.join(artifactsDir, "worktree-diffs"), diffs = diffWorktrees(worktreeSetup, tasks.map((task) => task.agent), diffsDir);
|
|
7508
7571
|
return formatWorktreeDiffSummary(diffs);
|
|
7509
7572
|
}
|
|
7510
7573
|
function findDuplicateParallelOutputPath(input) {
|
|
@@ -7738,7 +7801,7 @@ async function runParallelPath(data, deps) {
|
|
|
7738
7801
|
if (errorResult)
|
|
7739
7802
|
return errorResult;
|
|
7740
7803
|
try {
|
|
7741
|
-
let outputBaseDir =
|
|
7804
|
+
let outputBaseDir = path16.join(artifactsDir, "outputs", runId), duplicateOutputError = findDuplicateParallelOutputPath({
|
|
7742
7805
|
tasks,
|
|
7743
7806
|
behaviors,
|
|
7744
7807
|
paramsCwd: effectiveCwd,
|
|
@@ -7753,7 +7816,7 @@ async function runParallelPath(data, deps) {
|
|
|
7753
7816
|
if (validationError)
|
|
7754
7817
|
return buildParallelModeError(validationError);
|
|
7755
7818
|
}
|
|
7756
|
-
let parallelProgressPrecreated = firstProgressIndex !== -1, parallelProgressDir =
|
|
7819
|
+
let parallelProgressPrecreated = firstProgressIndex !== -1, parallelProgressDir = path16.join(artifactsDir, "progress", runId);
|
|
7757
7820
|
parallelProgressPrecreated && writeInitialProgressFile(parallelProgressDir);
|
|
7758
7821
|
for (let i = 0; i < taskTexts.length; i++)
|
|
7759
7822
|
shouldForkAgent(contextPolicy, tasks[i].agent) && (taskTexts[i] = wrapForkTask(taskTexts[i]));
|
|
@@ -8176,7 +8239,7 @@ function createSubagentExecutor(deps) {
|
|
|
8176
8239
|
let targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;
|
|
8177
8240
|
if (paramsWithResolvedCwd.dir)
|
|
8178
8241
|
try {
|
|
8179
|
-
let location = resolveAsyncRunLocation(paramsWithResolvedCwd, ASYNC_DIR, RESULTS_DIR), runId2 = location.resolvedId ?? targetRunId ??
|
|
8242
|
+
let location = resolveAsyncRunLocation(paramsWithResolvedCwd, ASYNC_DIR, RESULTS_DIR), runId2 = location.resolvedId ?? targetRunId ?? path16.basename(location.asyncDir ?? paramsWithResolvedCwd.dir);
|
|
8180
8243
|
return steerAsyncRun({ state: deps.state, runId: runId2, message, index: paramsWithResolvedCwd.index, kill: deps.kill, location, signal, recover: ({ absoluteDeadlineAt, ...limits }) => resumeAsyncRun({ params: { ...limits, action: "resume", id: runId2, message }, requestCwd, ctx, deps, absoluteDeadlineAt }) });
|
|
8181
8244
|
} catch (error) {
|
|
8182
8245
|
return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: !0, details: { mode: "management", results: [] } };
|
|
@@ -8204,7 +8267,7 @@ function createSubagentExecutor(deps) {
|
|
|
8204
8267
|
if (paramsWithResolvedCwd.dir)
|
|
8205
8268
|
try {
|
|
8206
8269
|
let location = resolveAsyncRunLocation(paramsWithResolvedCwd, ASYNC_DIR, RESULTS_DIR);
|
|
8207
|
-
return stopAsyncRun(deps.state, location.resolvedId ?? targetRunId ??
|
|
8270
|
+
return stopAsyncRun(deps.state, location.resolvedId ?? targetRunId ?? path16.basename(location.asyncDir ?? paramsWithResolvedCwd.dir), deps.kill, location);
|
|
8208
8271
|
} catch (error) {
|
|
8209
8272
|
return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: !0, details: { mode: "management", results: [] } };
|
|
8210
8273
|
}
|
|
@@ -8338,18 +8401,18 @@ function createSubagentExecutor(deps) {
|
|
|
8338
8401
|
enabled: effectiveParams.artifacts !== !1
|
|
8339
8402
|
}, artifactsDir = getArtifactsDir(parentSessionFile, effectiveCwd), sessionRoot;
|
|
8340
8403
|
if (effectiveParams.sessionDir)
|
|
8341
|
-
sessionRoot =
|
|
8404
|
+
sessionRoot = path16.resolve(deps.expandTilde(effectiveParams.sessionDir));
|
|
8342
8405
|
else {
|
|
8343
|
-
let baseSessionRoot = deps.config.defaultSessionDir ?
|
|
8344
|
-
sessionRoot =
|
|
8406
|
+
let baseSessionRoot = deps.config.defaultSessionDir ? path16.resolve(deps.expandTilde(deps.config.defaultSessionDir)) : deps.getSubagentSessionRoot(parentSessionFile);
|
|
8407
|
+
sessionRoot = path16.join(baseSessionRoot, runId);
|
|
8345
8408
|
}
|
|
8346
8409
|
try {
|
|
8347
|
-
|
|
8410
|
+
fs16.mkdirSync(sessionRoot, { recursive: !0 });
|
|
8348
8411
|
} catch (error) {
|
|
8349
8412
|
let message = error instanceof Error ? error.message : String(error);
|
|
8350
8413
|
return toExecutionErrorResult(effectiveParams, new Error(`Failed to create session directory '${sessionRoot}': ${message}`));
|
|
8351
8414
|
}
|
|
8352
|
-
let sessionDirForIndex = (idx) =>
|
|
8415
|
+
let sessionDirForIndex = (idx) => path16.join(sessionRoot, `run-${idx ?? 0}`), forkSessionFileForTask = (agentName, idx = 0, modelOverride) => {
|
|
8353
8416
|
if (shouldForkAgent(contextPolicy, agentName))
|
|
8354
8417
|
return prepareForkThinking(agentName, idx, modelOverride), forkSessionFileForIndex(idx);
|
|
8355
8418
|
}, forkThinkingOverrideForTask = (agentName, idx = 0, modelOverride) => {
|
|
@@ -8358,7 +8421,7 @@ function createSubagentExecutor(deps) {
|
|
|
8358
8421
|
prepareForkThinking(agentName, idx, modelOverride);
|
|
8359
8422
|
let override = forkThinkingOverrideForIndex(idx);
|
|
8360
8423
|
return override === "off" && forkThinkingDowngrades.set(idx, agentName), override;
|
|
8361
|
-
}, childSessionFileForTask = (agentName, idx, modelOverride) => forkSessionFileForTask(agentName, idx, modelOverride) ??
|
|
8424
|
+
}, childSessionFileForTask = (agentName, idx, modelOverride) => forkSessionFileForTask(agentName, idx, modelOverride) ?? path16.join(sessionDirForIndex(idx), "session.jsonl"), childSessionFileForIndex = (idx) => path16.join(sessionDirForIndex(idx), "session.jsonl");
|
|
8362
8425
|
try {
|
|
8363
8426
|
effectiveParams.clarify === !0 && ctx.hasUI || preflightForkSessionsForStaticTasks(effectiveParams, contextPolicy, forkSessionFileForTask, deps.config.chain?.dynamicFanout?.maxItems);
|
|
8364
8427
|
} catch (error) {
|