pi-better-server 0.7.0 → 0.7.1

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.
Files changed (35) hide show
  1. package/package.json +1 -1
  2. package/src/codex/return.ts +3 -2
  3. package/src/detach/extension.ts +20 -3
  4. package/src/event-log.ts +40 -12
  5. package/src/hosted-session.ts +11 -5
  6. package/src/remote-client/packages.ts +1 -4
  7. package/src/runtime/domain/background-service/shared-harness-settings.domain.mjs +2 -3
  8. package/src/runtime/domain/background-service/shared-harness-settings.ts +2 -5
  9. package/src/runtime/domain/background-service/shared-ssh-core/index.domain.mjs +1 -1
  10. package/src/runtime/domain/background-service/shared-ssh-core/index.ts +1 -1
  11. package/src/runtime/domain/catalog/catalog-preferences.mjs +1 -3
  12. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  13. package/src/runtime/domain/sandbox-policy/shared-harness-settings.domain.mjs +2 -3
  14. package/src/runtime/domain/sandbox-policy/shared-harness-settings.ts +2 -5
  15. package/src/runtime/domain/shared-harness-settings.mjs +2 -3
  16. package/src/runtime/domain/subagents/catalog-preferences.domain.mjs +1 -3
  17. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -5
  18. package/src/runtime/domain/subagents/config.ts +1 -1
  19. package/src/runtime/domain/subagents/extensions.mjs +1 -0
  20. package/src/runtime/domain/subagents/finalization.domain.mjs +34 -30
  21. package/src/runtime/domain/subagents/finalization.ts +30 -28
  22. package/src/runtime/domain/subagents/git-workspace.domain.mjs +51 -6
  23. package/src/runtime/domain/subagents/git-workspace.ts +48 -6
  24. package/src/runtime/domain/subagents/index.domain.mjs +58 -27
  25. package/src/runtime/domain/subagents/index.ts +61 -26
  26. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +7 -14
  27. package/src/runtime/domain/subagents/isolated-workspace.ts +6 -12
  28. package/src/runtime/domain/subagents/package.json +1 -1
  29. package/src/runtime/domain/subagents/registry.domain.mjs +7 -7
  30. package/src/runtime/domain/subagents/registry.ts +8 -8
  31. package/src/runtime/domain/subagents/shared-harness-settings.domain.mjs +2 -3
  32. package/src/runtime/domain/subagents/shared-harness-settings.ts +2 -5
  33. package/src/runtime/domain/subagents/workspace-prepare-worker.mjs +12 -0
  34. package/src/shared-ssh-core/index.ts +1 -1
  35. package/src/version.ts +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-server",
3
- "version": "0.7.0",
3
+ "version": "0.7.1",
4
4
  "description": "Daemon that hosts Pi agent sessions behind a local Unix socket with session-addressed Pi RPC.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -11,6 +11,7 @@ import { DaemonClient } from "../client.ts";
11
11
  import { moveSession, type MoveResult } from "../move/orchestrate.ts";
12
12
  import { defaultServerDir, socketPathFor } from "../paths.ts";
13
13
  import { resolveSession } from "../remote/sessions.ts";
14
+ import { shellQuote } from "../startup/runtime.ts";
14
15
  import { preflightCodexProvider } from "./preflight.ts";
15
16
  import { readRolloutMeta } from "./rollout.ts";
16
17
  import { startCodexDaemon, type CodexDaemon } from "./daemon.ts";
@@ -74,8 +75,8 @@ async function localDaemon(serverDir: string, codex: CodexRuntimeOptions | undef
74
75
  * plain `codex resume` works.
75
76
  */
76
77
  export function resumeHint(cwd: string, sessionId: string, managed: boolean, serverDir: string): string {
77
- if (!managed) return `cd ${cwd} && codex resume ${sessionId}`;
78
- const env = serverDir === defaultServerDir() ? "" : `PI_SERVER_DIR=${serverDir} `;
78
+ if (!managed) return `cd ${shellQuote(cwd)} && codex resume ${sessionId}`;
79
+ const env = serverDir === defaultServerDir() ? "" : `PI_SERVER_DIR=${shellQuote(serverDir)} `;
79
80
  return `${env}pi-remote attach ${sessionId} --agent codex (or: ${env}pi-remote steer ${sessionId} --agent codex "<message>")`;
80
81
  }
81
82
 
@@ -60,6 +60,7 @@ export function assertLocalSessionTransferSafe(sessionManager: unknown): void {
60
60
  interface ManagerOwnershipGuard {
61
61
  departed: Set<string>;
62
62
  wrapped: boolean;
63
+ flushDropped?: () => boolean;
63
64
  }
64
65
 
65
66
  // Native replacement and separately loaded extension modules must share both gates and latches.
@@ -107,9 +108,15 @@ function createLocalOwnershipGuard() {
107
108
  if (state.wrapped) return;
108
109
  state.wrapped = true;
109
110
  const rewrite = typeof manager._rewriteFile === "function" ? manager._rewriteFile : undefined;
110
- // Dropped entries remain in memory. After a failed move unfences the source, rewrite them
111
- // before appending again so every on-disk parentId still points to an on-disk entry.
111
+ // Entries withheld by the fence remain in memory. Rewriting restores parent links
112
+ // on rollback, or on the next append if the fence was lifted outside this handler.
112
113
  let dropped = false;
114
+ state.flushDropped = () => {
115
+ if (!dropped || !rewrite || manager.flushed === false) return false;
116
+ rewrite.call(manager);
117
+ dropped = false;
118
+ return true;
119
+ };
113
120
  for (const method of GATED_METHODS) {
114
121
  const original = manager[method];
115
122
  if (typeof original !== "function") continue;
@@ -119,8 +126,8 @@ function createLocalOwnershipGuard() {
119
126
  return undefined;
120
127
  }
121
128
  if (dropped) {
129
+ if (state.flushDropped?.()) return undefined;
122
130
  dropped = false;
123
- if (rewrite && manager.flushed !== false) return rewrite.call(this);
124
131
  }
125
132
  return (original as (...a: unknown[]) => unknown).apply(this, args);
126
133
  };
@@ -180,6 +187,7 @@ export function markLocalSessionDeparted(pi: ExtensionAPI, sessionId: string, ma
180
187
 
181
188
  export interface DetachDeps {
182
189
  resolveTarget: typeof resolveTarget;
190
+ waitMs?: number;
183
191
  }
184
192
 
185
193
  export function registerDetach(pi: ExtensionAPI, deps: DetachDeps = { resolveTarget }): void {
@@ -223,6 +231,7 @@ export function registerDetach(pi: ExtensionAPI, deps: DetachDeps = { resolveTar
223
231
  return DaemonClient.connect(target.socketPath);
224
232
  },
225
233
  isBusy: () => !ctx.isIdle(),
234
+ ...(deps.waitMs === undefined ? {} : { waitMs: deps.waitMs }),
226
235
  ...(parsed.toCwd ? { toCwd: parsed.toCwd } : {}),
227
236
  onProgress: (message) => ctx.ui.notify(message, "info"),
228
237
  });
@@ -231,6 +240,14 @@ export function registerDetach(pi: ExtensionAPI, deps: DetachDeps = { resolveTar
231
240
  } catch (error) {
232
241
  const message = error instanceof Error ? error.message : String(error);
233
242
  const untouched = error instanceof PreflightError || (error instanceof MoveError && error.sourceUnfenced);
243
+ if (error instanceof MoveError && error.sourceUnfenced && manager.getSessionId() === sessionId) {
244
+ try {
245
+ if (!localOwnershipGuard(pi).blockedFor(manager)) managerOwnershipGuard(manager).flushDropped?.();
246
+ } catch (flushError) {
247
+ ctx.ui.notify(`${message}\nCould not persist entries buffered during the move: ${String(flushError)}`, "error");
248
+ return;
249
+ }
250
+ }
234
251
  ctx.ui.notify(untouched ? `${message}\nThis session is unchanged.` : message, "error");
235
252
  } finally {
236
253
  await target?.close();
package/src/event-log.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
- import { dirname } from "node:path";
1
+ import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, truncateSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
3
 
4
4
  export interface LoggedEvent {
5
5
  seq: number;
@@ -56,13 +56,14 @@ export class EventLog {
56
56
  private pending: string[] = [];
57
57
  private pendingBytes = 0;
58
58
  private timer: ReturnType<typeof setTimeout> | undefined;
59
+ private committed: ((entry: LoggedEvent) => void) | undefined;
59
60
 
60
61
  constructor(path: string, options: EventLogOptions = {}) {
61
62
  this.path = path;
62
63
  this.ringSize = options.ringSize ?? DEFAULT_RING;
63
64
  this.maxEvents = options.maxEvents ?? DEFAULT_MAX_EVENTS;
64
65
  mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
65
- const existing = this.readFile();
66
+ const existing = this.readFile(true);
66
67
  this.fileEvents = existing.length;
67
68
  this.lastSeq = existing.at(-1)?.seq ?? 0;
68
69
  this.maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
@@ -77,17 +78,21 @@ export class EventLog {
77
78
  return this.lastSeq;
78
79
  }
79
80
 
80
- append(event: unknown): LoggedEvent {
81
- const logged: LoggedEvent = { seq: ++this.lastSeq, event };
81
+ onCommitted(listener: (entry: LoggedEvent) => void): void {
82
+ this.committed = listener;
83
+ }
84
+
85
+ append(event: unknown, flushImmediately = false): LoggedEvent {
86
+ const logged: LoggedEvent = { seq: this.lastSeq + 1, event };
82
87
  const line = `${JSON.stringify(logged)}\n`;
88
+ this.lastSeq = logged.seq;
83
89
  const size = Buffer.byteLength(line);
84
- this.pushRing(logged, size);
85
90
  this.pending.push(line);
86
91
  this.pendingBytes += size;
87
92
  this.fileEvents++;
88
93
  this.fileBytes += size;
89
94
  // Small batches are written after a short delay; a big one (or a quiet gap in the stream) does not wait.
90
- if (this.pendingBytes >= 256 * 1024) this.flush();
95
+ if (flushImmediately || this.pendingBytes >= 256 * 1024) this.flush();
91
96
  else if (!this.timer) {
92
97
  this.timer = setTimeout(() => this.flush(), this.flushMs);
93
98
  this.timer.unref();
@@ -103,10 +108,18 @@ export class EventLog {
103
108
  this.timer = undefined;
104
109
  }
105
110
  if (this.pending.length === 0) return;
106
- const text = this.pending.join("");
111
+ const pending = this.pending;
112
+ appendFileSync(this.path, pending.join(""), { mode: 0o600 });
107
113
  this.pending = [];
108
114
  this.pendingBytes = 0;
109
- appendFileSync(this.path, text, { mode: 0o600 });
115
+ // Deliver the recorded values. Pi may mutate a streaming message between
116
+ // append and flush, and a replay must agree with the original delivery.
117
+ const committed = pending.map(line => {
118
+ const entry = JSON.parse(line) as LoggedEvent;
119
+ this.pushRing(entry, Buffer.byteLength(line));
120
+ return entry;
121
+ });
122
+ for (const entry of committed) this.committed?.(entry);
110
123
  }
111
124
 
112
125
  private pushRing(entry: LoggedEvent, size: number): void {
@@ -122,6 +135,7 @@ export class EventLog {
122
135
 
123
136
  /** Every retained event with `seq > sinceSeq`, in order. */
124
137
  since(sinceSeq: number): Replay {
138
+ this.flush();
125
139
  const ringFirst = this.ring[0]?.seq;
126
140
  const source = ringFirst !== undefined && sinceSeq + 1 >= ringFirst ? this.ring : this.readFile();
127
141
  const firstSeq = source[0]?.seq ?? 0;
@@ -141,16 +155,30 @@ export class EventLog {
141
155
  // Drop the oldest until the file is at half its byte bound (the newest event always stays).
142
156
  while (start < lines.length - 1 && bytes > this.maxBytes / 2) bytes -= Buffer.byteLength(lines[start++]!);
143
157
  keep = keep.slice(start);
144
- writeFileSync(this.path, lines.slice(start).join(""), { mode: 0o600 });
158
+ const staging = mkdtempSync(join(dirname(this.path), ".compact-events-"));
159
+ try {
160
+ const next = join(staging, "events.jsonl");
161
+ writeFileSync(next, lines.slice(start).join(""), { mode: 0o600 });
162
+ renameSync(next, this.path);
163
+ } finally {
164
+ rmSync(staging, { recursive: true, force: true });
165
+ }
145
166
  this.fileEvents = keep.length;
146
167
  this.fileBytes = bytes;
147
168
  }
148
169
 
149
- private readFile(): LoggedEvent[] {
170
+ private readFile(repairTail = false): LoggedEvent[] {
150
171
  this.flush();
151
172
  if (!existsSync(this.path)) return [];
152
173
  const entries: LoggedEvent[] = [];
153
- for (const line of readFileSync(this.path, "utf8").split("\n")) {
174
+ let text = readFileSync(this.path, "utf8");
175
+ if (repairTail && text && !text.endsWith("\n")) {
176
+ // A crash can leave a partial final line. Remove it before any new
177
+ // append, so a later committed event cannot land on the broken line.
178
+ text = text.slice(0, text.lastIndexOf("\n") + 1);
179
+ truncateSync(this.path, Buffer.byteLength(text));
180
+ }
181
+ for (const line of text.split("\n")) {
154
182
  if (!line) continue;
155
183
  try {
156
184
  entries.push(JSON.parse(line) as LoggedEvent);
@@ -104,6 +104,9 @@ export class HostedSession {
104
104
  constructor(session: AgentSession, log: EventLog, onActivity: (kind?: "work" | "metadata") => void, activity?: SessionActivity) {
105
105
  this.session = session;
106
106
  this.log = log;
107
+ this.log.onCommitted(entry => {
108
+ for (const listener of this.listeners) listener(entry);
109
+ });
107
110
  this.onActivity = onActivity;
108
111
  this.activity = activity;
109
112
  this.ui = new UiBridge((event) => {
@@ -125,7 +128,9 @@ export class HostedSession {
125
128
  if (event.type === "message_end") this.activeMessage = undefined;
126
129
  if (event.type === "tool_execution_start" || event.type === "tool_execution_update") this.activeTools.set(event.toolCallId, event);
127
130
  if (event.type === "tool_execution_end") this.activeTools.delete(event.toolCallId);
128
- this.publish(event);
131
+ // Clients use lifecycle events to decide when a turn is idle. Flush those
132
+ // boundaries together with any preceding token or tool updates.
133
+ this.publish(event, event.type !== "message_update" && event.type !== "tool_execution_update");
129
134
  if (event.type === "agent_start") this.runIdle = session.waitForIdle().catch(() => undefined);
130
135
  if (event.type === "agent_end") for (const release of [...this.releaseOnAgentEnd]) release();
131
136
  this.onActivity("work");
@@ -228,6 +233,7 @@ export class HostedSession {
228
233
  fence(): void { this.disposed = true; fenceHostedSession(this.session); this.activity?.revokeRuntime(); }
229
234
 
230
235
  get lastSeq(): number {
236
+ this.log.flush();
231
237
  return this.log.last;
232
238
  }
233
239
 
@@ -243,11 +249,10 @@ export class HostedSession {
243
249
  /** Activation notices share the normal sequence and replay log, including after commitStop. */
244
250
  publishRuntimeEvent(event: unknown): void { this.publish(event); }
245
251
 
246
- private publish(event: unknown): void {
252
+ private publish(event: unknown, flushImmediately = true): void {
247
253
  this.progressAt = Date.now();
248
254
  if (this.runtimeReleased) return;
249
- const logged = this.log.append(event);
250
- for (const listener of this.listeners) listener(logged);
255
+ this.log.append(event, flushImmediately);
251
256
  }
252
257
 
253
258
  /**
@@ -255,6 +260,7 @@ export class HostedSession {
255
260
  * The replay and the live registration happen in one synchronous step, so no event is lost or repeated.
256
261
  */
257
262
  subscribe(sinceSeq: number | undefined, listener: Listener): { replay: Replay; unsubscribe: () => void } {
263
+ this.log.flush();
258
264
  const replay = sinceSeq === undefined ? { events: [], firstSeq: 0, truncated: false } : this.log.since(sinceSeq);
259
265
  return { replay, unsubscribe: this.addListener(listener) };
260
266
  }
@@ -305,9 +311,9 @@ export class HostedSession {
305
311
  this.ui.cancelAll();
306
312
  await aborted;
307
313
  this.unsubscribe();
314
+ this.log.flush();
308
315
  this.listeners.clear();
309
316
  this.runtimeReleased = true;
310
- this.log.flush();
311
317
  this.session.dispose();
312
318
  }
313
319
 
@@ -6,6 +6,7 @@ import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
6
6
  import { promisify } from "node:util";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { getAgentDir, ProjectTrustStore, SettingsManager } from "@earendil-works/pi-coding-agent";
9
+ import lockfile from "proper-lockfile";
9
10
 
10
11
  export interface PackageSpec {
11
12
  source: string;
@@ -34,10 +35,6 @@ const semver = piRequire("semver") as {
34
35
  valid(value: string): string | null;
35
36
  validRange(value: string): string | null;
36
37
  };
37
- const lockfile = piRequire("proper-lockfile") as {
38
- lockSync(path: string, options: { realpath: boolean }): () => void;
39
- lock(path: string, options: { realpath: boolean; retries: { retries: number; minTimeout: number; maxTimeout: number } }): Promise<() => Promise<void>>;
40
- };
41
38
  const run = promisify(execFile);
42
39
  const resources = ["extensions", "skills", "prompts", "themes"] as const;
43
40
  const commitPattern = /^[a-f0-9]{40}$/;
@@ -2,11 +2,10 @@
2
2
  // Generated from packages/harness-settings/index.ts. Do not edit directly.
3
3
  import { existsSync, lstatSync, realpathSync, readFileSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
4
  import { randomUUID } from "node:crypto";
5
- import { createRequire } from "node:module";
6
5
  import { join } from "node:path";
7
6
  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");
7
+ // A static import lets the compiled Pi loader resolve dependencies of the settings lock.
8
+ import lockfile from "proper-lockfile";
10
9
  const NAMESPACE = "piBetterHarness";
11
10
  export function harnessSettingsPath(seams = {}) {
12
11
  return join((seams.agentDir ?? getAgentDir)(), "settings.json");
@@ -1,14 +1,11 @@
1
1
  // Generated from packages/harness-settings/index.ts. Do not edit directly.
2
2
  import { existsSync, lstatSync, realpathSync, readFileSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { randomUUID } from "node:crypto";
4
- import { createRequire } from "node:module";
5
4
  import { join } from "node:path";
6
5
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
+ // A static import lets the compiled Pi loader resolve dependencies of the settings lock.
7
+ import lockfile from "proper-lockfile";
7
8
 
8
- // Match Pi's settings lock without depending on a private SDK import.
9
- const lockfile = createRequire(import.meta.url)("proper-lockfile") as {
10
- lockSync(path: string, options: { realpath: boolean }): () => void;
11
- };
12
9
  const NAMESPACE = "piBetterHarness";
13
10
  export interface HarnessSettingsSeams { agentDir?: () => string }
14
11
 
@@ -122,7 +122,7 @@ export function wrapRemoteBashCommand(input) {
122
122
  }
123
123
  export function defaultSshControlPathRoot() {
124
124
  const agentDirectory = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
125
- const root = join(agentDirectory, "ssh-control");
125
+ const root = resolve(agentDirectory, "ssh-control");
126
126
  // A long agent directory would push the socket past the unix path limit; fall back to a short per-user root.
127
127
  if (Buffer.byteLength(join(root, MUX_CONTROL_PATH_NAME_TEMPLATE)) <= MAX_SSH_CONTROL_PATH_BYTES)
128
128
  return root;
@@ -328,7 +328,7 @@ export function wrapRemoteBashCommand(input: RemoteBashCommandInput): string {
328
328
 
329
329
  export function defaultSshControlPathRoot(): string {
330
330
  const agentDirectory = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
331
- const root = join(agentDirectory, "ssh-control");
331
+ const root = resolve(agentDirectory, "ssh-control");
332
332
  // A long agent directory would push the socket past the unix path limit; fall back to a short per-user root.
333
333
  if (Buffer.byteLength(join(root, MUX_CONTROL_PATH_NAME_TEMPLATE)) <= MAX_SSH_CONTROL_PATH_BYTES) return root;
334
334
  return join("/tmp", `pi-ssh-${process.getuid?.() ?? "user"}`);
@@ -1,7 +1,7 @@
1
1
  // Generated from packages/pi-better-subagents/catalog-preferences.ts. Do not edit directly.
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
- import { createRequire } from "node:module";
4
+ import lockfile from "proper-lockfile";
5
5
  import { join, resolve } from "node:path";
6
6
  import { THINKING_LEVELS } from "./thinking.mjs";
7
7
  const ID = /^(role|agent)\.[a-z0-9]+(?:[.-][a-z0-9]+)*$/;
@@ -92,8 +92,6 @@ export function readCatalogPreferences(root) {
92
92
  }
93
93
  }
94
94
  function acquire(path) {
95
- // Read-only catalog consumers (including the portable CLI) need no lock adapter.
96
- const lockfile = createRequire(import.meta.url)("proper-lockfile");
97
95
  for (let attempt = 0; attempt < 100; attempt++) {
98
96
  try {
99
97
  return lockfile.lockSync(path, { realpath: false });
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-sandbox",
3
- "version": "0.15.1",
3
+ "version": "0.15.2",
4
4
  "description": "Pi extension with independent Main and Subagents permission profiles, file guards, and OS sandbox enforcement.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -2,11 +2,10 @@
2
2
  // Generated from packages/harness-settings/index.ts. Do not edit directly.
3
3
  import { existsSync, lstatSync, realpathSync, readFileSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
4
  import { randomUUID } from "node:crypto";
5
- import { createRequire } from "node:module";
6
5
  import { join } from "node:path";
7
6
  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");
7
+ // A static import lets the compiled Pi loader resolve dependencies of the settings lock.
8
+ import lockfile from "proper-lockfile";
10
9
  const NAMESPACE = "piBetterHarness";
11
10
  export function harnessSettingsPath(seams = {}) {
12
11
  return join((seams.agentDir ?? getAgentDir)(), "settings.json");
@@ -1,14 +1,11 @@
1
1
  // Generated from packages/harness-settings/index.ts. Do not edit directly.
2
2
  import { existsSync, lstatSync, realpathSync, readFileSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { randomUUID } from "node:crypto";
4
- import { createRequire } from "node:module";
5
4
  import { join } from "node:path";
6
5
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
+ // A static import lets the compiled Pi loader resolve dependencies of the settings lock.
7
+ import lockfile from "proper-lockfile";
7
8
 
8
- // Match Pi's settings lock without depending on a private SDK import.
9
- const lockfile = createRequire(import.meta.url)("proper-lockfile") as {
10
- lockSync(path: string, options: { realpath: boolean }): () => void;
11
- };
12
9
  const NAMESPACE = "piBetterHarness";
13
10
  export interface HarnessSettingsSeams { agentDir?: () => string }
14
11
 
@@ -2,11 +2,10 @@
2
2
  // Generated from packages/harness-settings/index.ts. Do not edit directly.
3
3
  import { existsSync, lstatSync, realpathSync, readFileSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
4
  import { randomUUID } from "node:crypto";
5
- import { createRequire } from "node:module";
6
5
  import { join } from "node:path";
7
6
  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");
7
+ // A static import lets the compiled Pi loader resolve dependencies of the settings lock.
8
+ import lockfile from "proper-lockfile";
10
9
  const NAMESPACE = "piBetterHarness";
11
10
  export function harnessSettingsPath(seams = {}) {
12
11
  return join((seams.agentDir ?? getAgentDir)(), "settings.json");
@@ -1,7 +1,7 @@
1
1
  // Generated fixed launch domain from packages/pi-better-subagents/catalog-preferences.ts. Do not edit directly.
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
- import { createRequire } from "node:module";
4
+ import lockfile from "proper-lockfile";
5
5
  import { join, resolve } from "node:path";
6
6
  import { THINKING_LEVELS } from "./thinking.domain.mjs";
7
7
  const ID = /^(role|agent)\.[a-z0-9]+(?:[.-][a-z0-9]+)*$/;
@@ -92,8 +92,6 @@ export function readCatalogPreferences(root) {
92
92
  }
93
93
  }
94
94
  function acquire(path) {
95
- // Read-only catalog consumers (including the portable CLI) need no lock adapter.
96
- const lockfile = createRequire(import.meta.url)("proper-lockfile");
97
95
  for (let attempt = 0; attempt < 100; attempt++) {
98
96
  try {
99
97
  return lockfile.lockSync(path, { realpath: false });
@@ -1,6 +1,6 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
- import { createRequire } from "node:module";
3
+ import lockfile from "proper-lockfile";
4
4
  import { join, resolve } from "node:path";
5
5
  import { THINKING_LEVELS, type ThinkingLevel } from "./thinking.ts";
6
6
 
@@ -84,10 +84,6 @@ export function readCatalogPreferences(root: string): { settings: CatalogPrefere
84
84
  }
85
85
 
86
86
  function acquire(path: string): () => void {
87
- // Read-only catalog consumers (including the portable CLI) need no lock adapter.
88
- const lockfile = createRequire(import.meta.url)("proper-lockfile") as {
89
- lockSync(path: string, options: { realpath: boolean }): () => void;
90
- };
91
87
  for (let attempt = 0; attempt < 100; attempt++) {
92
88
  try { return lockfile.lockSync(path, { realpath: false }); }
93
89
  catch (error) {
@@ -45,7 +45,7 @@ export interface SubagentConfig extends TimingSettings {
45
45
  /**
46
46
  * Provider → extension package(s) that authenticate it. Model auth is not
47
47
  * tool-shaped: `xai/grok-4.5` needs pi-xai-oauth loaded whatever the tools.
48
- * A built-in entry covers `ollama-cloud`; an entry here replaces it.
48
+ * Entries here override built-in mappings, including Ollama Cloud and LiteLLM.
49
49
  */
50
50
  providerExtensions?: Record<string, string | string[]> | null;
51
51
  /**
@@ -47,6 +47,7 @@ export const SELF_SPEC = "self";
47
47
  export const BUILTIN_PROVIDER_EXTENSIONS = {
48
48
  "router": "npm:pi-better-model-router",
49
49
  "ollama-cloud": "npm:pi-ollama-cloud",
50
+ "litellm": "npm:pi-provider-litellm",
50
51
  };
51
52
  /** Split "xai/grok-4.5" -> "xai". Returns undefined when there is no provider. */
52
53
  export function providerOf(model) {
@@ -33,15 +33,15 @@ export function reconcileInterruptedRun(meta, probe, now, hooks = {}) {
33
33
  * and builds the completion callback delivery from real log evidence.
34
34
  */
35
35
  export function finalizeRun(id, code, hooks = {}) {
36
- const meta = readMeta(id);
36
+ const initial = readMeta(id);
37
37
  // Coherent child-exit evidence may supersede provisional orphaned/lost
38
38
  // reconciliation, but never overwrites a true terminal record.
39
- if (!meta || !canExitFinalize(meta.status))
39
+ if (!initial || !canExitFinalize(initial.status))
40
40
  return { applied: false };
41
41
  // Lifecycle authority streams the complete NDJSON log; result text stays bounded.
42
42
  const r = parseRunForLifecycle(id);
43
43
  const outcome = classifyChildExit(code, r);
44
- collectRunFailures(id, meta.cwd, true);
44
+ collectRunFailures(id, initial.cwd, true);
45
45
  // A run can now end exit 0 as failed (a final request the model could not
46
46
  // serve), so "not incomplete and has an exit code" no longer means success.
47
47
  const completed = outcome.status === "completed";
@@ -59,12 +59,6 @@ export function finalizeRun(id, code, hooks = {}) {
59
59
  operation: "child-exit", kind: outcome.incomplete ? "incomplete" : "failure",
60
60
  category: "exit", summary }]);
61
61
  }
62
- meta.status = outcome.status;
63
- meta.lifecycleClassification = outcome.classification;
64
- if (outcome.incomplete)
65
- meta.failureReason = "incomplete-stream";
66
- meta.exitCode = code;
67
- meta.endedAt = Date.now();
68
62
  // A clean park finishes this ATTEMPT, not the assignment. It is only accepted
69
63
  // with a durable park record whose saved-conversation checkpoint still
70
64
  // verifies; a failed, incoherent or unverifiable exit stays an ordinary exit
@@ -77,27 +71,37 @@ export function finalizeRun(id, code, hooks = {}) {
77
71
  && completed && !outcome.incomplete && !outcome.diagnostics.modelError,
78
72
  });
79
73
  const parked = park.parked && park.record !== undefined;
80
- if (parked && park.record) {
81
- meta.park = park.record;
82
- // The rest of the attempt is complete; the assignment is still waiting.
83
- meta.status = "completed";
84
- }
74
+ const endedAt = Date.now();
75
+ const meta = writeMeta(initial, { patch: current => {
76
+ if (!canExitFinalize(current.status))
77
+ return undefined;
78
+ const patch = {
79
+ status: outcome.status,
80
+ lifecycleClassification: outcome.classification,
81
+ ...(outcome.incomplete ? { failureReason: "incomplete-stream" } : {}),
82
+ exitCode: code,
83
+ endedAt,
84
+ };
85
+ if (parked && park.record)
86
+ patch.park = park.record;
87
+ if (current.callback !== false
88
+ && current.completionCallbackPendingAt === undefined
89
+ && current.completionCallbackSentAt === undefined
90
+ && current.completionCallbackSuppressedAt === undefined) {
91
+ if (parked) {
92
+ // The continuation reports the assignment's result.
93
+ patch.completionCallbackSuppressedAt = endedAt;
94
+ patch.completionCallbackSuppressedReason = `parked on wait ${park.record?.waitId} generation ${park.record?.generation}`;
95
+ }
96
+ else {
97
+ patch.completionCallbackPendingAt = endedAt;
98
+ }
99
+ }
100
+ return patch;
101
+ } });
102
+ if (!meta)
103
+ return { applied: false };
85
104
  const callback = meta.callback !== false;
86
- if (callback
87
- && meta.completionCallbackPendingAt === undefined
88
- && meta.completionCallbackSentAt === undefined
89
- && meta.completionCallbackSuppressedAt === undefined) {
90
- if (parked) {
91
- // A parked attempt owes no completion callback: the continuation
92
- // resumes the same conversation and reports the assignment's result.
93
- meta.completionCallbackSuppressedAt = meta.endedAt;
94
- meta.completionCallbackSuppressedReason = `parked on wait ${park.record?.waitId} generation ${park.record?.generation}`;
95
- }
96
- else {
97
- meta.completionCallbackPendingAt = meta.endedAt;
98
- }
99
- }
100
- writeMeta(meta);
101
105
  commitAssignmentTerminal(meta);
102
106
  if (!parked && park.record) {
103
107
  // A park disposition existed but could not be proven on exit. Hold it in
@@ -112,7 +116,7 @@ export function finalizeRun(id, code, hooks = {}) {
112
116
  const verdict = parked
113
117
  ? `parked · waiting for ${park.record?.waitId ?? "its dependency"}`
114
118
  : outcome.verdict;
115
- const el = fmtElapsed(meta.endedAt - meta.startedAt);
119
+ const el = fmtElapsed(endedAt - meta.startedAt);
116
120
  const spend = fmtSpend(r.usage);
117
121
  const humanStat = `${el}${spend ? ` · ${spend}` : ""}`;
118
122
  const stat = el;