pi-better-server 0.2.4 → 0.4.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/package.json +6 -3
- package/scripts/measure-shared-reads/daemon.mjs +7 -0
- package/scripts/measure-shared-reads/probe.mjs +10 -0
- package/scripts/measure-shared-reads.mjs +165 -0
- package/scripts/test-on-pi.sh +21 -3
- package/src/cli.ts +39 -2
- package/src/client.ts +9 -4
- package/src/daemon-owner.ts +48 -6
- package/src/handshake.ts +8 -7
- package/src/lifecycle-config.ts +4 -0
- package/src/paths.ts +1 -11
- package/src/protocol.ts +7 -0
- package/src/registry.ts +2 -1
- package/src/runtime/background-history.ts +241 -0
- package/src/runtime/background.ts +182 -0
- package/src/runtime/cancellation.ts +99 -0
- package/src/runtime/catalog-admission.ts +50 -0
- package/src/runtime/catalog.ts +133 -0
- package/src/runtime/client.ts +111 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -0
- package/src/runtime/domain/assignment-observation.mjs +120 -0
- package/src/runtime/domain/assignment-projection.d.mts +1 -0
- package/src/runtime/domain/assignment-projection.mjs +245 -0
- package/src/runtime/domain/background/conditions.mjs +93 -0
- package/src/runtime/domain/background/process-identity.mjs +110 -0
- package/src/runtime/domain/background/process.mjs +511 -0
- package/src/runtime/domain/background/registry.mjs +374 -0
- package/src/runtime/domain/background/snapshot.mjs +73 -0
- package/src/runtime/domain/background/supervisor/identity.mjs +92 -0
- package/src/runtime/domain/background/supervisor/invocation.mjs +29 -0
- package/src/runtime/domain/background/supervisor/store.mjs +604 -0
- package/src/runtime/domain/background/supervisor/supervisor.mjs +720 -0
- package/src/runtime/domain/background/supervisor/types.mjs +47 -0
- package/src/runtime/domain/background/terminal-publication.mjs +58 -0
- package/src/runtime/domain/background/types.mjs +3 -0
- package/src/runtime/domain/catalog/agent-session-settings.d.mts +30 -0
- package/src/runtime/domain/catalog/agent-session-settings.mjs +112 -0
- package/src/runtime/domain/catalog/catalog-overlay.d.mts +3 -0
- package/src/runtime/domain/catalog/catalog-overlay.mjs +9 -0
- package/src/runtime/domain/catalog/catalog-preferences.d.mts +17 -0
- package/src/runtime/domain/catalog/catalog-preferences.mjs +164 -0
- package/src/runtime/domain/catalog/catalog-schema.d.mts +265 -0
- package/src/runtime/domain/catalog/catalog-schema.mjs +1331 -0
- package/src/runtime/domain/catalog/catalog-skill-edits.d.mts +42 -0
- package/src/runtime/domain/catalog/catalog-skill-edits.mjs +95 -0
- package/src/runtime/domain/catalog/catalog-store.d.mts +126 -0
- package/src/runtime/domain/catalog/catalog-store.mjs +810 -0
- package/src/runtime/domain/catalog/roles/role.architect.md +13 -0
- package/src/runtime/domain/catalog/roles/role.developer.md +16 -0
- package/src/runtime/domain/catalog/roles/role.explorer.md +13 -0
- package/src/runtime/domain/catalog/roles/role.product-manager.md +13 -0
- package/src/runtime/domain/catalog/roles/role.researcher.md +13 -0
- package/src/runtime/domain/catalog/roles/role.reviewer.md +13 -0
- package/src/runtime/domain/catalog/roles/role.writer.md +12 -0
- package/src/runtime/domain/catalog/thinking.d.mts +8 -0
- package/src/runtime/domain/catalog/thinking.mjs +22 -0
- package/src/runtime/domain/coordinator/index.mjs +50 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
- package/src/runtime/domain/coordinator/src/discovery.mjs +94 -0
- package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
- package/src/runtime/domain/coordinator/src/operations.mjs +301 -0
- package/src/runtime/domain/coordinator/src/outbox.mjs +282 -0
- package/src/runtime/domain/coordinator/src/recovery.mjs +51 -0
- package/src/runtime/domain/coordinator/src/result-supervision.mjs +101 -0
- package/src/runtime/domain/coordinator/src/rows.mjs +277 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +367 -0
- package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
- package/src/runtime/domain/coordinator/src/store.mjs +245 -0
- package/src/runtime/domain/coordinator/src/task-cancellation.mjs +187 -0
- package/src/runtime/domain/coordinator/src/types.mjs +24 -0
- package/src/runtime/domain/coordinator/src/validate.mjs +233 -0
- package/src/runtime/domain/coordinator/src/waits.mjs +850 -0
- package/src/runtime/domain/health-observation.d.mts +3 -0
- package/src/runtime/domain/health-observation.mjs +613 -0
- package/src/runtime/domain/health-surface.mjs +279 -0
- package/src/runtime/domain/log-cursor.mjs +148 -0
- package/src/runtime/domain/log-paths.mjs +13 -0
- package/src/runtime/domain/parse.d.mts +2 -0
- package/src/runtime/domain/parse.mjs +1173 -0
- package/src/runtime/domain/process-status.d.mts +1 -0
- package/src/runtime/domain/process-status.mjs +25 -0
- package/src/runtime/domain/session-store.d.mts +2 -0
- package/src/runtime/domain/session-store.mjs +489 -0
- package/src/runtime/domain/shared-harness-settings.d.mts +1 -0
- package/src/runtime/domain/shared-harness-settings.mjs +126 -0
- package/src/runtime/domain/shared-log-utils.mjs +1223 -0
- package/src/runtime/domain/shared-stall-detector.mjs +37 -0
- package/src/runtime/domain/widget.d.mts +1 -0
- package/src/runtime/domain/widget.mjs +250 -0
- package/src/runtime/guardian.ts +189 -0
- package/src/runtime/health-config.ts +27 -0
- package/src/runtime/local-client.ts +34 -0
- package/src/runtime/mutation-store.ts +34 -0
- package/src/runtime/queries.ts +76 -0
- package/src/runtime/query-executor.ts +277 -0
- package/src/runtime/query-worker.mjs +119 -0
- package/src/runtime/read-model.ts +409 -0
- package/src/runtime/result-supervision.ts +63 -0
- package/src/runtime/root.ts +29 -0
- package/src/runtime/socket.ts +10 -0
- package/src/runtime/status-cli.ts +11 -0
- package/src/runtime/work-client.d.mts +14 -0
- package/src/runtime/work-client.mjs +102 -0
- package/src/server.ts +199 -14
- package/src/session-activity.ts +22 -2
- package/src/startup/activation.ts +32 -5
- package/src/startup/ensure.ts +13 -1
- package/src/startup/install.ts +2 -0
- package/src/version.ts +4 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function effectiveStatus(meta: any): string;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Generated canonical read-only process observation.
|
|
2
|
+
/** Cheap liveness probe via signal 0. */
|
|
3
|
+
export function processExists(pid) {
|
|
4
|
+
if (typeof pid !== "number" || pid <= 0)
|
|
5
|
+
return false;
|
|
6
|
+
try {
|
|
7
|
+
process.kill(pid, 0);
|
|
8
|
+
return true;
|
|
9
|
+
}
|
|
10
|
+
catch (err) {
|
|
11
|
+
return err.code === "EPERM";
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Reconcile the recorded status with reality for display. A run marked
|
|
16
|
+
* "running" whose PID is no longer alive exited without our handler firing
|
|
17
|
+
* (foreground pi was closed / restarted) — surface that as "exited".
|
|
18
|
+
*/
|
|
19
|
+
export function effectiveStatus(meta) {
|
|
20
|
+
if (meta.status !== "running")
|
|
21
|
+
return meta.status;
|
|
22
|
+
if (processExists(meta.pid))
|
|
23
|
+
return "running";
|
|
24
|
+
return "exited";
|
|
25
|
+
}
|
|
@@ -0,0 +1,489 @@
|
|
|
1
|
+
// Generated from packages/pi-better-subagents/session-store.ts. Do not edit directly.
|
|
2
|
+
/**
|
|
3
|
+
* Durable native-session storage for subagents.
|
|
4
|
+
*
|
|
5
|
+
* A subagent conversation is an ordinary Pi session file. Its history and the
|
|
6
|
+
* launch recipe needed to continue it therefore belong with the user's Pi agent
|
|
7
|
+
* state, not in the volatile runtime registry under `os.tmpdir()`: changing
|
|
8
|
+
* TMPDIR, a restart, or the age/size sweeps must not strand a completed
|
|
9
|
+
* attempt's saved conversation. This module owns the two durable locations and
|
|
10
|
+
* nothing else:
|
|
11
|
+
*
|
|
12
|
+
* - `<agent dir>/subagents/sessions` — the `--session-dir` of NEW child
|
|
13
|
+
* launches. Pi's own SessionManager writes there, so no copy or mirror exists.
|
|
14
|
+
* - `<agent dir>/subagents/attempts/<run id>.json` — a compact continuation
|
|
15
|
+
* record (metadata + frozen launch recipe) published atomically when an
|
|
16
|
+
* attempt completes. Raw logs, results, timing and callback markers stay in
|
|
17
|
+
* the volatile registry and are reclaimed by the existing sweeps.
|
|
18
|
+
*
|
|
19
|
+
* The durable store deliberately has no expiry, size cap, or recovery design:
|
|
20
|
+
* cleanup never removes a durable conversation's saved history or attempt
|
|
21
|
+
* record, and a missing saved conversation refuses continuation instead of being
|
|
22
|
+
* recreated. Deleting them is an explicit operator action. Recipes written by
|
|
23
|
+
* older versions that point at the old temporary session directory are legacy:
|
|
24
|
+
* they are read as recorded and never migrated or guessed at.
|
|
25
|
+
*/
|
|
26
|
+
import { randomBytes } from "node:crypto";
|
|
27
|
+
import { mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
28
|
+
import { homedir } from "node:os";
|
|
29
|
+
import { isAbsolute, join, sep } from "node:path";
|
|
30
|
+
import { isDeepStrictEqual } from "node:util";
|
|
31
|
+
/**
|
|
32
|
+
* Test-isolation override for the whole durable root. Production resolves the
|
|
33
|
+
* Pi agent directory; the package's tests point this at a private directory so
|
|
34
|
+
* they never touch the machine's real `~/.pi/agent/subagents`.
|
|
35
|
+
*/
|
|
36
|
+
const DURABLE_ROOT_ENV = "PI_SUBAGENT_DURABLE_DIR";
|
|
37
|
+
const ARCHIVE_VERSION = 1;
|
|
38
|
+
/**
|
|
39
|
+
* Durable "the conversation's newest attempt did not complete" marker. It is
|
|
40
|
+
* published before that attempt's volatile metadata is reclaimed, so an older
|
|
41
|
+
* completed archive can no longer speak for the conversation.
|
|
42
|
+
*/
|
|
43
|
+
const ARCHIVE_STATUS_VERSION = 1;
|
|
44
|
+
/** Terminal statuses that leave a conversation unavailable for continuation. */
|
|
45
|
+
const NON_RESUMABLE_STATUSES = new Set(["failed", "killed", "lost"]);
|
|
46
|
+
/** Fields copied into the compact record: what discovery, display, and continuation read. */
|
|
47
|
+
const ARCHIVE_META_KEYS = [
|
|
48
|
+
"id", "name", "status", "pid", "startedAt", "endedAt", "exitCode", "failureReason",
|
|
49
|
+
"lifecycleClassification", "cwd", "promptPreview", "logPath", "sessionId",
|
|
50
|
+
"rootRunId", "resumedFrom", "recipe", "sandbox", "taskRuntime", "callback",
|
|
51
|
+
"batchId", "batchName", "model", "effort", "spawnPid", "spawnPidStartTime",
|
|
52
|
+
"dismissedAt",
|
|
53
|
+
// A parked attempt's disposition and operation binding outlive the volatile
|
|
54
|
+
// run directory: the resume path and cleanup protection read this record.
|
|
55
|
+
"park", "operations", "assignment", "pidStartTime",
|
|
56
|
+
];
|
|
57
|
+
function isSafeRunId(id) {
|
|
58
|
+
return typeof id === "string" && /^[A-Za-z0-9_-]+$/.test(id);
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Root of durable subagent state: `<agent dir>/subagents`, honoring
|
|
62
|
+
* `PI_CODING_AGENT_DIR`. Resolved per call so a foreground that changes its
|
|
63
|
+
* agent directory (and every test) sees the same value the launcher used.
|
|
64
|
+
*/
|
|
65
|
+
export function durableSubagentRoot(env = process.env, home = homedir()) {
|
|
66
|
+
const override = env[DURABLE_ROOT_ENV]?.trim();
|
|
67
|
+
if (override) {
|
|
68
|
+
if (!isAbsolute(override))
|
|
69
|
+
throw new Error(`${DURABLE_ROOT_ENV} must be an absolute path.`);
|
|
70
|
+
return override;
|
|
71
|
+
}
|
|
72
|
+
const agentDir = env.PI_CODING_AGENT_DIR?.trim();
|
|
73
|
+
return join(agentDir || join(home, ".pi", "agent"), "subagents");
|
|
74
|
+
}
|
|
75
|
+
/** Durable `--session-dir` for new child launches. */
|
|
76
|
+
export function durableSessionsDir() {
|
|
77
|
+
return join(durableSubagentRoot(), "sessions");
|
|
78
|
+
}
|
|
79
|
+
/** Durable compact continuation records for completed attempts. */
|
|
80
|
+
export function durableAttemptsDir() {
|
|
81
|
+
return join(durableSubagentRoot(), "attempts");
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Durable per-conversation markers for the newest attempt that ended WITHOUT a
|
|
85
|
+
* completion (see `recordArchiveStatusTombstone`).
|
|
86
|
+
*/
|
|
87
|
+
export function durableSessionStateDir() {
|
|
88
|
+
return join(durableSubagentRoot(), "session-state");
|
|
89
|
+
}
|
|
90
|
+
/** True when `path` is the durable session root or lies beneath it. */
|
|
91
|
+
export function isDurableSessionsPath(path) {
|
|
92
|
+
const root = durableSessionsDir();
|
|
93
|
+
return path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
|
|
94
|
+
}
|
|
95
|
+
function attemptPath(id) {
|
|
96
|
+
if (!isSafeRunId(id))
|
|
97
|
+
throw new Error("Invalid run ID.");
|
|
98
|
+
return join(durableAttemptsDir(), `${id}.json`);
|
|
99
|
+
}
|
|
100
|
+
/** Copy the compact fields of one attempt; the raw log and volatile markers stay behind. */
|
|
101
|
+
function compactAttempt(meta) {
|
|
102
|
+
const compact = {};
|
|
103
|
+
for (const key of ARCHIVE_META_KEYS) {
|
|
104
|
+
const value = meta[key];
|
|
105
|
+
if (value !== undefined)
|
|
106
|
+
compact[key] = value;
|
|
107
|
+
}
|
|
108
|
+
return compact;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Whether this record is the compact durable record of a completed attempt of a
|
|
112
|
+
* durable-layout conversation. Only a completed attempt is archived: a legacy
|
|
113
|
+
* attempt whose recipe points at the old temporary session directory, or a
|
|
114
|
+
* fixture without a recipe, keeps the pre-existing reclaimable behavior, and a
|
|
115
|
+
* failed/killed attempt is not resumable, so archiving it would only pin its
|
|
116
|
+
* clone. The recipe and the attempt must agree about the conversation identity,
|
|
117
|
+
* so a record can never become a second, contradicting source of truth.
|
|
118
|
+
*/
|
|
119
|
+
function durableCompletion(meta) {
|
|
120
|
+
if (meta.status !== "completed")
|
|
121
|
+
return false;
|
|
122
|
+
const recipe = meta.recipe;
|
|
123
|
+
if (!recipe || recipe.version !== 1)
|
|
124
|
+
return false;
|
|
125
|
+
if (recipe.sessionId !== meta.sessionId)
|
|
126
|
+
return false;
|
|
127
|
+
return isDurableSessionsPath(recipe.sessionDir);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Whether a completed durable-layout attempt still has no published compact
|
|
131
|
+
* record. Its volatile run directory then holds the ONLY copy of the recipe, so
|
|
132
|
+
* the age and size bounds must retain the whole run rather than reclaim it.
|
|
133
|
+
*/
|
|
134
|
+
export function archivePublicationPending(meta) {
|
|
135
|
+
return durableCompletion(meta) && isSafeRunId(meta.id) && !publishedAttemptIds().has(meta.id);
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Publish the compact record for a completed attempt, atomically.
|
|
139
|
+
*
|
|
140
|
+
* Returns true when this call published or verified an identical record and
|
|
141
|
+
* false when the attempt is not archivable at all. Missing, corrupt or changed
|
|
142
|
+
* records are atomically replaced; redundant retries preserve source identity.
|
|
143
|
+
* IO failures throw:
|
|
144
|
+
* the caller decides whether the volatile record is retained.
|
|
145
|
+
*/
|
|
146
|
+
export function archiveCompletedAttempt(meta) {
|
|
147
|
+
if (!durableCompletion(meta))
|
|
148
|
+
return false;
|
|
149
|
+
if (!isSafeRunId(meta.id))
|
|
150
|
+
throw new Error("Invalid run ID.");
|
|
151
|
+
const directory = durableAttemptsDir();
|
|
152
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
153
|
+
const path = attemptPath(meta.id);
|
|
154
|
+
const record = { version: ARCHIVE_VERSION, meta: compactAttempt(meta) };
|
|
155
|
+
const payload = JSON.stringify(record);
|
|
156
|
+
let previous;
|
|
157
|
+
try {
|
|
158
|
+
previous = readFileSync(path, "utf8");
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
if (error.code !== "ENOENT")
|
|
162
|
+
throw error;
|
|
163
|
+
}
|
|
164
|
+
let identical = false;
|
|
165
|
+
if (previous !== undefined) {
|
|
166
|
+
try {
|
|
167
|
+
identical = isDeepStrictEqual(JSON.parse(previous), JSON.parse(payload));
|
|
168
|
+
}
|
|
169
|
+
catch { /* A corrupt record must be repaired by the real writer. */ }
|
|
170
|
+
}
|
|
171
|
+
if (!identical) {
|
|
172
|
+
const temp = join(directory, `.${randomBytes(8).toString("hex")}.tmp`);
|
|
173
|
+
try {
|
|
174
|
+
writeFileSync(temp, payload, { mode: 0o600, flag: "wx" });
|
|
175
|
+
renameSync(temp, path);
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
try {
|
|
179
|
+
unlinkSync(temp);
|
|
180
|
+
}
|
|
181
|
+
catch { /* best effort */ }
|
|
182
|
+
throw error;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
// The published record now speaks for this conversation, so a marker left by
|
|
186
|
+
// an older non-completing attempt no longer applies.
|
|
187
|
+
clearSupersededArchiveStatus(meta);
|
|
188
|
+
return true;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Validate one archived record against the run id it was asked for. Anything
|
|
192
|
+
* that does not match is treated as absent: guessing a conversation identity
|
|
193
|
+
* from a damaged or foreign record would continue the wrong history.
|
|
194
|
+
*/
|
|
195
|
+
export function parseArchivedAttempt(raw, id, sessionRoot = durableSessionsDir()) {
|
|
196
|
+
let parsed;
|
|
197
|
+
try {
|
|
198
|
+
parsed = JSON.parse(raw);
|
|
199
|
+
}
|
|
200
|
+
catch {
|
|
201
|
+
return undefined;
|
|
202
|
+
}
|
|
203
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
204
|
+
return undefined;
|
|
205
|
+
const record = parsed;
|
|
206
|
+
if (record.version !== ARCHIVE_VERSION)
|
|
207
|
+
return undefined;
|
|
208
|
+
const meta = record.meta;
|
|
209
|
+
if (!meta || typeof meta !== "object" || Array.isArray(meta))
|
|
210
|
+
return undefined;
|
|
211
|
+
if (meta.id !== id)
|
|
212
|
+
return undefined;
|
|
213
|
+
// Only a completed attempt is ever archived; a record that claims otherwise
|
|
214
|
+
// cannot speak for the conversation.
|
|
215
|
+
if (meta.status !== "completed")
|
|
216
|
+
return undefined;
|
|
217
|
+
if (typeof meta.startedAt !== "number" || !Number.isFinite(meta.startedAt))
|
|
218
|
+
return undefined;
|
|
219
|
+
if (typeof meta.sessionId !== "string" || !isSafeRunId(meta.sessionId))
|
|
220
|
+
return undefined;
|
|
221
|
+
if (typeof meta.cwd !== "string" || meta.cwd === "")
|
|
222
|
+
return undefined;
|
|
223
|
+
const recipe = meta.recipe;
|
|
224
|
+
if (!recipe || typeof recipe !== "object" || recipe.version !== 1)
|
|
225
|
+
return undefined;
|
|
226
|
+
if (recipe.sessionId !== meta.sessionId)
|
|
227
|
+
return undefined;
|
|
228
|
+
if (typeof recipe.sessionDir !== "string" || !(recipe.sessionDir === sessionRoot || recipe.sessionDir.startsWith(sessionRoot.endsWith(sep) ? sessionRoot : `${sessionRoot}${sep}`)))
|
|
229
|
+
return undefined;
|
|
230
|
+
if (typeof recipe.cwd !== "string" || recipe.cwd === "")
|
|
231
|
+
return undefined;
|
|
232
|
+
return meta;
|
|
233
|
+
}
|
|
234
|
+
/** One published archived completed attempt, ignoring staleness. */
|
|
235
|
+
function readPublishedAttempt(id, requireReadable = false) {
|
|
236
|
+
if (!isSafeRunId(id))
|
|
237
|
+
return undefined;
|
|
238
|
+
let raw;
|
|
239
|
+
try {
|
|
240
|
+
raw = readFileSync(attemptPath(id), "utf-8");
|
|
241
|
+
}
|
|
242
|
+
catch (error) {
|
|
243
|
+
// A direct lookup can refuse continuation as absent. A list also
|
|
244
|
+
// authorizes tombstone/cleanup decisions, so partial history is unsafe.
|
|
245
|
+
if (requireReadable)
|
|
246
|
+
throw error;
|
|
247
|
+
return undefined;
|
|
248
|
+
}
|
|
249
|
+
return parseArchivedAttempt(raw, id);
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* One archived completed attempt that may still speak for its conversation, or
|
|
253
|
+
* undefined. A conversation whose newest attempt ended without completing is not
|
|
254
|
+
* resumable, and this record must not offer an older completion as one.
|
|
255
|
+
*/
|
|
256
|
+
export function readArchivedAttempt(id) {
|
|
257
|
+
const meta = readPublishedAttempt(id);
|
|
258
|
+
return meta && !archiveSuperseded(meta) ? meta : undefined;
|
|
259
|
+
}
|
|
260
|
+
let archiveListCache;
|
|
261
|
+
let archiveFiles = new Map();
|
|
262
|
+
function attemptsSignature() {
|
|
263
|
+
try {
|
|
264
|
+
const stat = statSync(durableAttemptsDir());
|
|
265
|
+
return `${durableAttemptsDir()}:${stat.dev}:${stat.ino}:${stat.mtimeMs}:${stat.ctimeMs}`;
|
|
266
|
+
}
|
|
267
|
+
catch (error) {
|
|
268
|
+
if (error.code !== "ENOENT")
|
|
269
|
+
throw error;
|
|
270
|
+
return `${durableAttemptsDir()}:missing`;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Every published compact record, staleness not applied. The directory
|
|
275
|
+
* signature (which changes when a record is atomically replaced) keeps repeated
|
|
276
|
+
* `listMetas` calls cheap. After a publication, reuse unchanged file identities
|
|
277
|
+
* rather than parsing the entire history again. Markers have their own boundary.
|
|
278
|
+
*/
|
|
279
|
+
function archivedAttempts() {
|
|
280
|
+
const signature = attemptsSignature();
|
|
281
|
+
if (archiveListCache?.signature === signature)
|
|
282
|
+
return archiveListCache.metas;
|
|
283
|
+
let names = [];
|
|
284
|
+
try {
|
|
285
|
+
names = readdirSync(durableAttemptsDir());
|
|
286
|
+
}
|
|
287
|
+
catch (error) {
|
|
288
|
+
const code = error.code;
|
|
289
|
+
// A missing directory (or a file at that path) contains no archives.
|
|
290
|
+
// Permission and I/O refusals cannot establish that same absence.
|
|
291
|
+
if (code !== "ENOENT" && code !== "ENOTDIR")
|
|
292
|
+
throw error;
|
|
293
|
+
names = [];
|
|
294
|
+
}
|
|
295
|
+
const metas = [];
|
|
296
|
+
const files = new Map();
|
|
297
|
+
for (const name of names) {
|
|
298
|
+
if (!name.endsWith(".json"))
|
|
299
|
+
continue;
|
|
300
|
+
const path = join(durableAttemptsDir(), name);
|
|
301
|
+
const fileSignature = stateSignature(path);
|
|
302
|
+
const cached = archiveFiles.get(path);
|
|
303
|
+
const entry = cached?.signature === fileSignature ? cached : {
|
|
304
|
+
signature: fileSignature,
|
|
305
|
+
meta: readPublishedAttempt(name.slice(0, -".json".length), true),
|
|
306
|
+
};
|
|
307
|
+
// Retain successful observations even if a later file refuses a read.
|
|
308
|
+
// The list signature is committed only after the entire scan succeeds.
|
|
309
|
+
archiveFiles.set(path, entry);
|
|
310
|
+
files.set(path, entry);
|
|
311
|
+
if (entry.meta)
|
|
312
|
+
metas.push(entry.meta);
|
|
313
|
+
}
|
|
314
|
+
archiveFiles = files;
|
|
315
|
+
archiveListCache = { signature, metas, ids: new Set(metas.map((meta) => meta.id)) };
|
|
316
|
+
return metas;
|
|
317
|
+
}
|
|
318
|
+
function publishedAttemptIds() {
|
|
319
|
+
archivedAttempts();
|
|
320
|
+
return archiveListCache.ids;
|
|
321
|
+
}
|
|
322
|
+
let visibleArchiveCache;
|
|
323
|
+
/** Every archived completed attempt that may still speak for its conversation. */
|
|
324
|
+
export function listArchivedAttempts() {
|
|
325
|
+
const metas = archivedAttempts();
|
|
326
|
+
const directory = durableSessionStateDir();
|
|
327
|
+
const signature = `${directory}:${stateSignature(directory)}`;
|
|
328
|
+
if (visibleArchiveCache?.metas === metas && visibleArchiveCache.signature === signature) {
|
|
329
|
+
return visibleArchiveCache.visible;
|
|
330
|
+
}
|
|
331
|
+
// Atomic marker add/replace/delete changes the directory identity. Enumerate
|
|
332
|
+
// published markers once; missing markers never need one stat per archive.
|
|
333
|
+
let names;
|
|
334
|
+
try {
|
|
335
|
+
names = readdirSync(directory);
|
|
336
|
+
}
|
|
337
|
+
catch (error) {
|
|
338
|
+
if (error.code !== "ENOENT")
|
|
339
|
+
throw error;
|
|
340
|
+
names = [];
|
|
341
|
+
}
|
|
342
|
+
const sessions = new Set(names.filter((name) => name.endsWith(".json")).map((name) => name.slice(0, -5)));
|
|
343
|
+
const visible = metas.filter((meta) => !sessions.has(meta.sessionId) || !archiveSuperseded(meta));
|
|
344
|
+
visibleArchiveCache = { metas, signature, visible };
|
|
345
|
+
return visible;
|
|
346
|
+
}
|
|
347
|
+
/** Whether this conversation has any published compact record at all. */
|
|
348
|
+
export function hasArchivedAttemptForSession(sessionId) {
|
|
349
|
+
return archivedAttempts().some((meta) => meta.sessionId === sessionId);
|
|
350
|
+
}
|
|
351
|
+
function statePath(sessionId) {
|
|
352
|
+
if (!isSafeRunId(sessionId))
|
|
353
|
+
throw new Error("Invalid session ID.");
|
|
354
|
+
return join(durableSessionStateDir(), `${sessionId}.json`);
|
|
355
|
+
}
|
|
356
|
+
function stateSignature(path) {
|
|
357
|
+
try {
|
|
358
|
+
const stat = statSync(path);
|
|
359
|
+
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`;
|
|
360
|
+
}
|
|
361
|
+
catch (error) {
|
|
362
|
+
if (error.code !== "ENOENT")
|
|
363
|
+
throw error;
|
|
364
|
+
return "missing";
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
/** Anything that does not match the requested conversation is treated as absent. */
|
|
368
|
+
export function parseArchivedSessionState(raw, sessionId) {
|
|
369
|
+
let parsed;
|
|
370
|
+
try {
|
|
371
|
+
parsed = JSON.parse(raw);
|
|
372
|
+
}
|
|
373
|
+
catch {
|
|
374
|
+
return undefined;
|
|
375
|
+
}
|
|
376
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
377
|
+
return undefined;
|
|
378
|
+
const record = parsed;
|
|
379
|
+
if (record.version !== ARCHIVE_STATUS_VERSION)
|
|
380
|
+
return undefined;
|
|
381
|
+
if (record.sessionId !== sessionId)
|
|
382
|
+
return undefined;
|
|
383
|
+
if (!isSafeRunId(record.attemptId))
|
|
384
|
+
return undefined;
|
|
385
|
+
if (typeof record.status !== "string" || !NON_RESUMABLE_STATUSES.has(record.status))
|
|
386
|
+
return undefined;
|
|
387
|
+
if (typeof record.startedAt !== "number" || !Number.isFinite(record.startedAt))
|
|
388
|
+
return undefined;
|
|
389
|
+
return record;
|
|
390
|
+
}
|
|
391
|
+
/** One marker file, re-read only when its inode, size, or timestamps change. */
|
|
392
|
+
const stateCache = new Map();
|
|
393
|
+
function readArchivedSessionState(sessionId) {
|
|
394
|
+
if (!isSafeRunId(sessionId))
|
|
395
|
+
return undefined;
|
|
396
|
+
const path = statePath(sessionId);
|
|
397
|
+
const signature = stateSignature(path);
|
|
398
|
+
const cached = stateCache.get(path);
|
|
399
|
+
if (cached && cached.signature === signature)
|
|
400
|
+
return cached.state;
|
|
401
|
+
let state;
|
|
402
|
+
try {
|
|
403
|
+
state = parseArchivedSessionState(readFileSync(path, "utf-8"), sessionId);
|
|
404
|
+
}
|
|
405
|
+
catch (error) {
|
|
406
|
+
if (error.code !== "ENOENT")
|
|
407
|
+
throw error;
|
|
408
|
+
state = undefined;
|
|
409
|
+
}
|
|
410
|
+
stateCache.set(path, { signature, state });
|
|
411
|
+
return state;
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Whether a marker for a strictly later attempt of this conversation hides this
|
|
415
|
+
* archive. A record at least as new as the marker is unaffected, so the newest
|
|
416
|
+
* completed attempt is always resumable.
|
|
417
|
+
*/
|
|
418
|
+
function archiveSuperseded(meta) {
|
|
419
|
+
const state = readArchivedSessionState(meta.sessionId);
|
|
420
|
+
if (!state)
|
|
421
|
+
return false;
|
|
422
|
+
return state.attemptId !== meta.id && state.startedAt >= meta.startedAt;
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Publish the "newest attempt did not complete" marker for one conversation,
|
|
426
|
+
* before that attempt's volatile metadata is reclaimed.
|
|
427
|
+
*
|
|
428
|
+
* Without it, reclaiming a failed/killed attempt's record would let an older
|
|
429
|
+
* completed archive look like the conversation's last word and be offered for
|
|
430
|
+
* continuation again. The marker never makes an attempt resumable.
|
|
431
|
+
*
|
|
432
|
+
* Returns false when the record needs no marker (not a non-completing attempt,
|
|
433
|
+
* or the conversation has no published completion to invalidate). IO failures
|
|
434
|
+
* throw so the caller retains the volatile record instead of losing the fact.
|
|
435
|
+
*/
|
|
436
|
+
export function recordArchiveStatusTombstone(meta) {
|
|
437
|
+
if (!NON_RESUMABLE_STATUSES.has(meta.status))
|
|
438
|
+
return false;
|
|
439
|
+
if (!isSafeRunId(meta.sessionId) || !isSafeRunId(meta.id))
|
|
440
|
+
return false;
|
|
441
|
+
if (typeof meta.startedAt !== "number" || !Number.isFinite(meta.startedAt))
|
|
442
|
+
return false;
|
|
443
|
+
if (!hasArchivedAttemptForSession(meta.sessionId))
|
|
444
|
+
return false;
|
|
445
|
+
const existing = readArchivedSessionState(meta.sessionId);
|
|
446
|
+
// A newer attempt is already marked; its marker is the stronger evidence.
|
|
447
|
+
if (existing && existing.startedAt >= meta.startedAt)
|
|
448
|
+
return true;
|
|
449
|
+
const directory = durableSessionStateDir();
|
|
450
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
451
|
+
const path = statePath(meta.sessionId);
|
|
452
|
+
const temp = join(directory, `.${randomBytes(8).toString("hex")}.tmp`);
|
|
453
|
+
const record = {
|
|
454
|
+
version: ARCHIVE_STATUS_VERSION,
|
|
455
|
+
sessionId: meta.sessionId,
|
|
456
|
+
attemptId: meta.id,
|
|
457
|
+
status: meta.status,
|
|
458
|
+
startedAt: meta.startedAt,
|
|
459
|
+
at: Date.now(),
|
|
460
|
+
};
|
|
461
|
+
try {
|
|
462
|
+
writeFileSync(temp, JSON.stringify(record), { mode: 0o600, flag: "wx" });
|
|
463
|
+
renameSync(temp, path);
|
|
464
|
+
}
|
|
465
|
+
catch (error) {
|
|
466
|
+
try {
|
|
467
|
+
unlinkSync(temp);
|
|
468
|
+
}
|
|
469
|
+
catch { /* best effort */ }
|
|
470
|
+
throw error;
|
|
471
|
+
}
|
|
472
|
+
return true;
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* Drop a marker the published record supersedes: a completion at least as new as
|
|
476
|
+
* the marker is the conversation's newest attempt, so the marker's claim is no
|
|
477
|
+
* longer true. Best effort — a marker left behind only hides older records.
|
|
478
|
+
*/
|
|
479
|
+
function clearSupersededArchiveStatus(meta) {
|
|
480
|
+
const state = readArchivedSessionState(meta.sessionId);
|
|
481
|
+
if (!state)
|
|
482
|
+
return;
|
|
483
|
+
if (state.attemptId !== meta.id && state.startedAt > meta.startedAt)
|
|
484
|
+
return;
|
|
485
|
+
try {
|
|
486
|
+
unlinkSync(statePath(meta.sessionId));
|
|
487
|
+
}
|
|
488
|
+
catch { /* already gone */ }
|
|
489
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function readHarnessSetting(key: string, seams?: { agentDir?: () => string }): any;
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// Generated from packages/pi-better-subagents/shared-harness-settings.ts. Do not edit directly.
|
|
2
|
+
// Generated from packages/harness-settings/index.ts. Do not edit directly.
|
|
3
|
+
import { existsSync, lstatSync, realpathSync, readFileSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { createRequire } from "node:module";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
// Match Pi's settings lock without depending on a private SDK import.
|
|
9
|
+
const lockfile = createRequire(import.meta.url)("proper-lockfile");
|
|
10
|
+
const NAMESPACE = "piBetterHarness";
|
|
11
|
+
export function harnessSettingsPath(seams = {}) {
|
|
12
|
+
return join((seams.agentDir ?? getAgentDir)(), "settings.json");
|
|
13
|
+
}
|
|
14
|
+
function object(value, label) {
|
|
15
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
16
|
+
throw new Error(`${label} must be a JSON object.`);
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
function readSettings(path) {
|
|
20
|
+
try {
|
|
21
|
+
return object(JSON.parse(readFileSync(path, "utf8")), `Settings at ${path}`);
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
if (error.code === "ENOENT")
|
|
25
|
+
return {};
|
|
26
|
+
throw error;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function section(settings) {
|
|
30
|
+
return Object.hasOwn(settings, NAMESPACE) ? object(settings[NAMESPACE], NAMESPACE) : {};
|
|
31
|
+
}
|
|
32
|
+
function acquire(path) {
|
|
33
|
+
// A live writer can be briefly descheduled; allow contention without stealing its lock.
|
|
34
|
+
const maxAttempts = 100;
|
|
35
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
36
|
+
try {
|
|
37
|
+
return lockfile.lockSync(path, { realpath: false });
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
if (error.code !== "ELOCKED" || attempt === maxAttempts - 1)
|
|
41
|
+
throw error;
|
|
42
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
throw new Error(`Cannot lock settings at ${path}`);
|
|
46
|
+
}
|
|
47
|
+
function lockedRead(path) {
|
|
48
|
+
if (!existsSync(path))
|
|
49
|
+
return {};
|
|
50
|
+
const release = acquire(path);
|
|
51
|
+
try {
|
|
52
|
+
return readSettings(path);
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
release();
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function writeDestination(path) {
|
|
59
|
+
let stat;
|
|
60
|
+
try {
|
|
61
|
+
stat = lstatSync(path);
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
if (error.code === "ENOENT")
|
|
65
|
+
return path;
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
// Keep managed dotfiles links intact. A dangling link fails rather than being replaced.
|
|
69
|
+
return stat.isSymbolicLink() ? realpathSync(path) : path;
|
|
70
|
+
}
|
|
71
|
+
function mutate(seams, change) {
|
|
72
|
+
const path = harnessSettingsPath(seams);
|
|
73
|
+
mkdirSync((seams.agentDir ?? getAgentDir)(), { recursive: true });
|
|
74
|
+
const release = acquire(path);
|
|
75
|
+
let pending;
|
|
76
|
+
try {
|
|
77
|
+
// Read inside the lock so another session's settings are never replaced by a stale snapshot.
|
|
78
|
+
const settings = readSettings(path);
|
|
79
|
+
const values = section(settings);
|
|
80
|
+
const result = change(values);
|
|
81
|
+
settings[NAMESPACE] = values;
|
|
82
|
+
const destination = writeDestination(path);
|
|
83
|
+
pending = `${destination}.${randomUUID()}.tmp`;
|
|
84
|
+
writeFileSync(pending, `${JSON.stringify(settings, null, 2)}\n`, { mode: 0o600, flag: "wx" });
|
|
85
|
+
renameSync(pending, destination);
|
|
86
|
+
return result;
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
try {
|
|
90
|
+
if (pending)
|
|
91
|
+
rmSync(pending, { force: true });
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
release();
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
export function readHarnessSetting(key, seams = {}, legacy) {
|
|
99
|
+
const values = section(lockedRead(harnessSettingsPath(seams)));
|
|
100
|
+
if (Object.hasOwn(values, key))
|
|
101
|
+
return values[key];
|
|
102
|
+
if (!legacy)
|
|
103
|
+
return undefined;
|
|
104
|
+
let raw;
|
|
105
|
+
try {
|
|
106
|
+
raw = readFileSync(legacy.path, "utf8");
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
if (error.code === "ENOENT")
|
|
110
|
+
return undefined;
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
const migrated = legacy.parse(JSON.parse(raw));
|
|
114
|
+
return mutate(seams, current => {
|
|
115
|
+
if (!Object.hasOwn(current, key))
|
|
116
|
+
current[key] = migrated;
|
|
117
|
+
return current[key];
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
export function updateHarnessSetting(key, update, seams = {}) {
|
|
121
|
+
return mutate(seams, values => {
|
|
122
|
+
const next = update(values[key]);
|
|
123
|
+
values[key] = next;
|
|
124
|
+
return next;
|
|
125
|
+
});
|
|
126
|
+
}
|