pi-better-subagents 0.25.0 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/batch.mjs +12 -3
- package/catalog-runtime.ts +6 -2
- package/child-codemode.ts +17 -0
- package/cleanup.ts +118 -26
- package/config.json +1 -1
- package/config.ts +1 -1
- package/continuation.ts +43 -11
- package/docs/usage.md +83 -63
- package/extensions.mjs +2 -1
- package/index.ts +278 -188
- package/list.mjs +19 -3
- package/list.ts +1 -0
- package/package.json +1 -1
- package/registry.ts +133 -17
- package/session-selection.ts +35 -0
- package/session-store.ts +410 -0
- package/task-guard.ts +5 -2
- package/tools.ts +22 -23
- package/workspace-scope.ts +50 -0
package/list.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { describeTiming } from "./timing.ts";
|
|
2
2
|
import { fmtElapsed } from "./widget.mjs";
|
|
3
3
|
import { formatListHealthSuffix } from "./health-surface.mjs";
|
|
4
|
+
import { isWithinWorkspace, normalizeWorkspacePath } from "./workspace-scope.ts";
|
|
4
5
|
|
|
5
6
|
export const SUBAGENT_LIST_DEFAULT_LIMIT = 10;
|
|
6
7
|
export const SUBAGENT_LIST_MAX_LIMIT = 100;
|
|
@@ -66,6 +67,19 @@ export function normalizeSubagentListOptions(params = {}) {
|
|
|
66
67
|
};
|
|
67
68
|
}
|
|
68
69
|
|
|
70
|
+
/**
|
|
71
|
+
* Cursor scope for one list call.
|
|
72
|
+
*
|
|
73
|
+
* Machine-global lists keep the existing `all` key. Folder lists use the
|
|
74
|
+
* canonical folder path, so a cursor cannot replay another folder's page while
|
|
75
|
+
* two foreground sessions in the same folder intentionally share one scope.
|
|
76
|
+
*/
|
|
77
|
+
export function listFolderScopeKey(all, cwd) {
|
|
78
|
+
if (all) return "all";
|
|
79
|
+
const folder = typeof cwd === "string" && cwd !== "" ? cwd : process.cwd();
|
|
80
|
+
return `folder:${normalizeWorkspacePath(folder)}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
69
83
|
function bounded(value, max) {
|
|
70
84
|
const single = String(value ?? "").replace(/\s+/g, " ").trim();
|
|
71
85
|
return single.length <= max ? single : `${single.slice(0, Math.max(0, max - 1))}…`;
|
|
@@ -87,17 +101,19 @@ export function formatSubagentListRow(meta, p) {
|
|
|
87
101
|
const batch = meta.batchId
|
|
88
102
|
? ` [batch: ${meta.batchName ? `${bounded(meta.batchName, 40)} ` : ""}${bounded(meta.batchId, 60)}]`
|
|
89
103
|
: "";
|
|
90
|
-
return `• ${name}${meta.id} [${status}] ${bounded(meta.model ?? "?", 60)} ${elapsed}${health}${timing}${batch}${failure}\n ${promptPreview(meta)}`;
|
|
104
|
+
return `• ${name}${meta.id} [${status}] session_id=${meta.sessionId ?? "unavailable"} ${bounded(meta.model ?? "?", 60)} ${elapsed}${health}${timing}${batch}${failure}\n ${promptPreview(meta)}`;
|
|
91
105
|
}
|
|
92
106
|
|
|
93
107
|
export function collectSubagentList(p) {
|
|
94
108
|
const options = normalizeSubagentListOptions(p.params ?? {});
|
|
95
109
|
const now = p.now ?? Date.now();
|
|
96
|
-
|
|
110
|
+
// Folder scope, not spawn ownership: every foreground session working in
|
|
111
|
+
// this folder (or one of its descendants) contributes to the default list.
|
|
112
|
+
const cwd = typeof p.cwd === "string" && p.cwd !== "" ? p.cwd : process.cwd();
|
|
97
113
|
const statusOf = p.statusOf ?? ((meta) => meta.status);
|
|
98
114
|
const healthById = p.healthById ?? (() => undefined);
|
|
99
115
|
const failureById = p.failureById ?? (() => "");
|
|
100
|
-
const inScope = p.inScope ?? ((meta) => options.all || meta.
|
|
116
|
+
const inScope = p.inScope ?? ((meta) => options.all || isWithinWorkspace(meta.cwd, cwd));
|
|
101
117
|
const offset = Math.max(0, Math.floor(Number(p.offset) || 0));
|
|
102
118
|
|
|
103
119
|
const scoped = (p.metas ?? [])
|
package/list.ts
CHANGED
package/package.json
CHANGED
package/registry.ts
CHANGED
|
@@ -21,6 +21,14 @@ import { tmpdir } from "node:os";
|
|
|
21
21
|
import { basename, dirname, join } from "node:path";
|
|
22
22
|
import { processExists } from "./spawn.ts";
|
|
23
23
|
import type { LifecycleClassification } from "./lifecycle.ts";
|
|
24
|
+
import {
|
|
25
|
+
archiveCompletedAttempt,
|
|
26
|
+
durableSessionsDir,
|
|
27
|
+
listArchivedAttempts,
|
|
28
|
+
readArchivedAttempt,
|
|
29
|
+
recordArchiveStatusTombstone,
|
|
30
|
+
} from "./session-store.ts";
|
|
31
|
+
import { failureIdentity, observeFailures, readFailureState } from "./shared-failure-observations.ts";
|
|
24
32
|
|
|
25
33
|
/**
|
|
26
34
|
* Terminal + live statuses as recorded on disk. `orphaned` is durable and
|
|
@@ -246,12 +254,19 @@ export interface RunMeta {
|
|
|
246
254
|
timing?: RunTiming;
|
|
247
255
|
}
|
|
248
256
|
|
|
249
|
-
/** Root runtime
|
|
257
|
+
/** Root of the VOLATILE runtime registry, deliberately OUTSIDE any repo. */
|
|
250
258
|
export function baseDir(): string {
|
|
251
259
|
return join(realpathSync(tmpdir()), "pi-better-subagents");
|
|
252
260
|
}
|
|
261
|
+
/**
|
|
262
|
+
* `--session-dir` for NEW child launches: the durable Pi agent directory
|
|
263
|
+
* (`<agent dir>/subagents/sessions`), not the volatile registry. Saved
|
|
264
|
+
* conversations are ordinary Pi session files, so changing TMPDIR or a restart
|
|
265
|
+
* must not move them. Recipes recorded before this layout keep pointing at the
|
|
266
|
+
* old temporary directory and are read exactly as recorded.
|
|
267
|
+
*/
|
|
253
268
|
export function sessionsDir(): string {
|
|
254
|
-
return
|
|
269
|
+
return durableSessionsDir();
|
|
255
270
|
}
|
|
256
271
|
export function taskWorkspaceDir(id: string): string {
|
|
257
272
|
if (!/^sa_[a-z0-9]+_[a-z0-9]+$/i.test(id)) throw new Error("Invalid task workspace run ID.");
|
|
@@ -942,6 +957,54 @@ export function nextRunId(): string {
|
|
|
942
957
|
return `sa_${Date.now().toString(36)}_${seq}`;
|
|
943
958
|
}
|
|
944
959
|
|
|
960
|
+
/** Failure-journal operation for durable archive publication. */
|
|
961
|
+
const ARCHIVE_OPERATION = "durable-archive";
|
|
962
|
+
|
|
963
|
+
/**
|
|
964
|
+
* Journal the outcome of publishing one attempt's compact durable record in the
|
|
965
|
+
* run's existing failures journal (`failures.jsonl`, read by the output and
|
|
966
|
+
* result payloads). `undefined` reports a verified recovery.
|
|
967
|
+
*
|
|
968
|
+
* While publication keeps failing, the volatile run directory still holds the
|
|
969
|
+
* only copy of the recipe, so both sweeps retain it; this incident is what makes
|
|
970
|
+
* that state visible instead of silent. Best-effort: journaling never throws
|
|
971
|
+
* into finalization or a sweep, and an untouched run keeps no journal.
|
|
972
|
+
*/
|
|
973
|
+
export function observeArchivePublication(id: string, error?: unknown): void {
|
|
974
|
+
try {
|
|
975
|
+
if (!/^[A-Za-z0-9_-]+$/.test(id)) return;
|
|
976
|
+
const path = join(runDir(id), "failures.jsonl");
|
|
977
|
+
const key = failureIdentity(ARCHIVE_OPERATION);
|
|
978
|
+
const open = readFailureState(path).observations[key];
|
|
979
|
+
const at = Date.now();
|
|
980
|
+
if (error === undefined) {
|
|
981
|
+
if (!open || open.status !== "unresolved") return;
|
|
982
|
+
observeFailures(path, [{
|
|
983
|
+
id: `archive-published:${id}:${at}`,
|
|
984
|
+
operation: ARCHIVE_OPERATION,
|
|
985
|
+
kind: "recovered",
|
|
986
|
+
at,
|
|
987
|
+
incidents: [open.id],
|
|
988
|
+
summary: "the compact durable continuation record was published",
|
|
989
|
+
}]);
|
|
990
|
+
return;
|
|
991
|
+
}
|
|
992
|
+
// One open incident per run: repeated sweeps retry the same publication and
|
|
993
|
+
// must not fill the journal with the same failure.
|
|
994
|
+
if (open && open.status === "unresolved") return;
|
|
995
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
996
|
+
observeFailures(path, [{
|
|
997
|
+
id: `archive-failed:${id}:${at}`,
|
|
998
|
+
operation: ARCHIVE_OPERATION,
|
|
999
|
+
kind: "failure",
|
|
1000
|
+
at,
|
|
1001
|
+
category: "storage",
|
|
1002
|
+
summary: `durable continuation record could not be published (${detail}); this attempt's log and recipe are retained until it is`,
|
|
1003
|
+
evidence: `compact record for ${id}`,
|
|
1004
|
+
}]);
|
|
1005
|
+
} catch { /* the journal is best-effort; retaining the run is the safety net */ }
|
|
1006
|
+
}
|
|
1007
|
+
|
|
945
1008
|
export function writeMeta(meta: RunMeta): void {
|
|
946
1009
|
mkdirSync(runDir(meta.id), { recursive: true });
|
|
947
1010
|
withRunMetaLock(meta.id, (owns) => {
|
|
@@ -950,6 +1013,18 @@ export function writeMeta(meta: RunMeta): void {
|
|
|
950
1013
|
writeMetaFile(meta);
|
|
951
1014
|
metaCache.set(meta.id, meta);
|
|
952
1015
|
indexMeta(meta);
|
|
1016
|
+
// Publish the compact durable continuation record in the same critical
|
|
1017
|
+
// section, so a completed attempt is never visible only in volatile
|
|
1018
|
+
// storage. Best-effort: a durable write failure must not break a launch
|
|
1019
|
+
// or finalization (the volatile record still exists). It is journaled
|
|
1020
|
+
// instead, and both sweeps retain the run until publication succeeds.
|
|
1021
|
+
if (meta.status === "completed") {
|
|
1022
|
+
try {
|
|
1023
|
+
if (archiveCompletedAttempt(meta)) observeArchivePublication(meta.id);
|
|
1024
|
+
} catch (error) {
|
|
1025
|
+
observeArchivePublication(meta.id, error);
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
953
1028
|
owns();
|
|
954
1029
|
});
|
|
955
1030
|
for (const listener of metaChangedListeners) {
|
|
@@ -968,9 +1043,15 @@ export function readMeta(id: string): RunMeta | undefined {
|
|
|
968
1043
|
const meta = JSON.parse(readFileSync(metaPathFor(id), "utf-8")) as RunMeta;
|
|
969
1044
|
metaCache.set(id, meta);
|
|
970
1045
|
return meta;
|
|
971
|
-
} catch {
|
|
1046
|
+
} catch (error) {
|
|
972
1047
|
metaCache.delete(id);
|
|
973
|
-
|
|
1048
|
+
// Only a MISSING volatile record falls back to the durable copy. An
|
|
1049
|
+
// unreadable or corrupt `meta.json` stays authoritative and is reported
|
|
1050
|
+
// as absent: a possibly stale archive must never replace it.
|
|
1051
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") return undefined;
|
|
1052
|
+
const archived = readArchivedAttempt(id);
|
|
1053
|
+
if (archived) metaCache.set(id, archived);
|
|
1054
|
+
return archived;
|
|
974
1055
|
}
|
|
975
1056
|
}
|
|
976
1057
|
|
|
@@ -982,10 +1063,27 @@ export function readMeta(id: string): RunMeta | undefined {
|
|
|
982
1063
|
* in place, so a purged run does not free its display label for reuse.
|
|
983
1064
|
* Deleting the whole registry root is what clears them.
|
|
984
1065
|
*/
|
|
985
|
-
export
|
|
1066
|
+
export interface RemoveMetaArtifactsOptions {
|
|
1067
|
+
/**
|
|
1068
|
+
* Keep the run's owned clone workspace. A conversation whose saved session
|
|
1069
|
+
* and recipe are durable still needs the workspace later attempts run in;
|
|
1070
|
+
* only its volatile log, metadata, and task scratch are reclaimed.
|
|
1071
|
+
*/
|
|
1072
|
+
keepWorkspace?: boolean;
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
export function removeMetaArtifacts(meta: RunMeta, options: RemoveMetaArtifactsOptions = {}): boolean {
|
|
986
1076
|
try {
|
|
1077
|
+
// A newer failed/killed attempt's volatile record is about to be the only
|
|
1078
|
+
// evidence that the conversation's newest attempt did not complete. Leave
|
|
1079
|
+
// a durable marker first, or an older completed archive would become the
|
|
1080
|
+
// conversation's visible last word and could be continued as if this
|
|
1081
|
+
// attempt had never happened. A marker that cannot be published retains
|
|
1082
|
+
// the run (the throw below): the unsafe direction is deleting both.
|
|
1083
|
+
recordArchiveStatusTombstone(meta);
|
|
987
1084
|
removeRunDirectory(meta.id);
|
|
988
|
-
if (
|
|
1085
|
+
if (!options.keepWorkspace
|
|
1086
|
+
&& meta.taskRuntime && /^sa_[a-z0-9]+_[a-z0-9]+$/i.test(meta.id) && meta.cwd === taskWorkspaceDir(meta.id)) {
|
|
989
1087
|
rmSync(taskWorkspaceDir(meta.id), { recursive: true, force: true });
|
|
990
1088
|
}
|
|
991
1089
|
if (meta.taskRuntime && meta.taskScratch && dirname(meta.taskScratch) === realpathSync(tmpdir()) && /^pi-task-scratch-[a-z0-9]{6}$/i.test(basename(meta.taskScratch))) {
|
|
@@ -1004,19 +1102,33 @@ export function removeMetaArtifacts(meta: RunMeta): boolean {
|
|
|
1004
1102
|
}
|
|
1005
1103
|
}
|
|
1006
1104
|
|
|
1007
|
-
/**
|
|
1105
|
+
/**
|
|
1106
|
+
* All runs, newest first: the volatile registry plus durable archived attempts
|
|
1107
|
+
* whose raw log/run directory was already reclaimed. The volatile record wins
|
|
1108
|
+
* whenever both exist, so a reclaimed log never hides the live one.
|
|
1109
|
+
*/
|
|
1008
1110
|
export function listMetas(): RunMeta[] {
|
|
1009
|
-
let ids: string[];
|
|
1111
|
+
let ids: string[] = [];
|
|
1010
1112
|
try {
|
|
1011
1113
|
registryIo.fullDirectoryReads += 1;
|
|
1012
1114
|
ids = readdirSync(join(baseDir(), "runs"));
|
|
1013
1115
|
} catch {
|
|
1014
|
-
|
|
1116
|
+
ids = [];
|
|
1015
1117
|
}
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
.
|
|
1118
|
+
const seen = new Set<string>();
|
|
1119
|
+
const metas: RunMeta[] = [];
|
|
1120
|
+
for (const id of ids) {
|
|
1121
|
+
seen.add(id); // A corrupt volatile record must not be hidden by an older archive.
|
|
1122
|
+
const meta = readMetaForSweep(id);
|
|
1123
|
+
if (!meta) continue;
|
|
1124
|
+
metas.push(meta);
|
|
1125
|
+
}
|
|
1126
|
+
for (const meta of listArchivedAttempts()) {
|
|
1127
|
+
if (seen.has(meta.id)) continue;
|
|
1128
|
+
seen.add(meta.id);
|
|
1129
|
+
metas.push(meta);
|
|
1130
|
+
}
|
|
1131
|
+
return metas.sort((a, b) => b.startedAt - a.startedAt);
|
|
1020
1132
|
}
|
|
1021
1133
|
|
|
1022
1134
|
export interface RunRecordIndex {
|
|
@@ -1054,7 +1166,8 @@ export function inspectRunMeta(id: string): { kind: "ok"; meta: RunMeta } | { ki
|
|
|
1054
1166
|
statSync(runDir(id));
|
|
1055
1167
|
return { kind: "unreadable", detail: "metadata file is missing; the run directory and its evidence are retained" };
|
|
1056
1168
|
} catch {
|
|
1057
|
-
|
|
1169
|
+
const archived = readArchivedAttempt(id);
|
|
1170
|
+
return archived ? { kind: "ok", meta: archived } : { kind: "missing" };
|
|
1058
1171
|
}
|
|
1059
1172
|
}
|
|
1060
1173
|
return { kind: "unreadable", detail: error instanceof Error ? error.message : String(error) };
|
|
@@ -1077,14 +1190,13 @@ export function inspectRunMeta(id: string): { kind: "ok"; meta: RunMeta } | { ki
|
|
|
1077
1190
|
|
|
1078
1191
|
/** Every run directory, counting unreadable records instead of dropping them. */
|
|
1079
1192
|
export function listRunRecords(): RunRecordIndex {
|
|
1080
|
-
let ids: string[];
|
|
1193
|
+
let ids: string[] = [];
|
|
1081
1194
|
try {
|
|
1082
1195
|
registryIo.fullDirectoryReads += 1;
|
|
1083
1196
|
ids = readdirSync(join(baseDir(), "runs"));
|
|
1084
1197
|
} catch (error) {
|
|
1085
1198
|
const code = (error as NodeJS.ErrnoException).code;
|
|
1086
|
-
if (code
|
|
1087
|
-
return { metas: [], unreadable: [], indexError: error instanceof Error ? error.message : String(error) };
|
|
1199
|
+
if (code !== "ENOENT") return { metas: [], unreadable: [], indexError: error instanceof Error ? error.message : String(error) };
|
|
1088
1200
|
}
|
|
1089
1201
|
const metas: RunMeta[] = [];
|
|
1090
1202
|
const unreadable: Array<{ id: string; detail: string }> = [];
|
|
@@ -1098,6 +1210,10 @@ export function listRunRecords(): RunRecordIndex {
|
|
|
1098
1210
|
if (inspected.kind === "ok") metas.push(inspected.meta);
|
|
1099
1211
|
else if (inspected.kind === "unreadable") unreadable.push({ id, detail: inspected.detail });
|
|
1100
1212
|
}
|
|
1213
|
+
const volatileIds = new Set(ids);
|
|
1214
|
+
for (const archived of listArchivedAttempts()) {
|
|
1215
|
+
if (!volatileIds.has(archived.id)) metas.push(archived);
|
|
1216
|
+
}
|
|
1101
1217
|
metas.sort((a, b) => b.startedAt - a.startedAt);
|
|
1102
1218
|
return { metas, unreadable };
|
|
1103
1219
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** Exact-name selection of saved conversations; attempt IDs never become session IDs. */
|
|
2
|
+
import type { RunMeta } from "./registry.ts";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Select a single conversation in the caller's workspace scope. Several attempts
|
|
6
|
+
* of one conversation count once; distinct conversations with the same display
|
|
7
|
+
* name must be disambiguated by session_id. Admission/status/lease checks remain
|
|
8
|
+
* the launcher's responsibility, including refusal of an active conversation.
|
|
9
|
+
*/
|
|
10
|
+
export function selectSessionByName(
|
|
11
|
+
metas: readonly RunMeta[],
|
|
12
|
+
name: string,
|
|
13
|
+
inWorkspace: (cwd: string) => boolean,
|
|
14
|
+
): string {
|
|
15
|
+
const requested = name.trim();
|
|
16
|
+
if (!requested) throw new Error("session_name is empty.");
|
|
17
|
+
const latest = new Map<string, RunMeta>();
|
|
18
|
+
for (const meta of metas) {
|
|
19
|
+
if (!meta.sessionId) continue;
|
|
20
|
+
const previous = latest.get(meta.sessionId);
|
|
21
|
+
if (!previous || meta.startedAt > previous.startedAt) latest.set(meta.sessionId, meta);
|
|
22
|
+
}
|
|
23
|
+
const matches = [...latest.values()]
|
|
24
|
+
.filter((meta) => meta.name === requested && inWorkspace(meta.cwd))
|
|
25
|
+
.sort((a, b) => a.sessionId.localeCompare(b.sessionId));
|
|
26
|
+
if (matches.length === 0) {
|
|
27
|
+
throw new Error(`No saved subagent conversation named ${JSON.stringify(requested)} in the current folder. Use subagent_list({all:true}) to find its session_id.`);
|
|
28
|
+
}
|
|
29
|
+
if (matches.length > 1) {
|
|
30
|
+
const shown = matches.slice(0, 10).map((meta) => `session_id=${meta.sessionId} (${meta.cwd})`).join("; ");
|
|
31
|
+
const remaining = matches.length > 10 ? `; ${matches.length - 10} more` : "";
|
|
32
|
+
throw new Error(`Ambiguous session_name ${JSON.stringify(requested)}: ${shown}${remaining}. Pass session_id to choose the conversation.`);
|
|
33
|
+
}
|
|
34
|
+
return matches[0]!.sessionId;
|
|
35
|
+
}
|