pi-better-server 0.6.0 → 0.7.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.
Files changed (120) hide show
  1. package/package.json +4 -3
  2. package/scripts/measure-full-runtime/frontend.ts +10 -2
  3. package/scripts/measure-full-runtime.mjs +2 -0
  4. package/src/runtime/background-tools.ts +54 -8
  5. package/src/runtime/background.ts +16 -4
  6. package/src/runtime/domain/background/process.mjs +49 -11
  7. package/src/runtime/domain/background/supervisor/store.mjs +3 -3
  8. package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
  9. package/src/runtime/domain/background-service/index.domain.mjs +19 -0
  10. package/src/runtime/domain/background-service/index.ts +19 -0
  11. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +87 -5
  12. package/src/runtime/domain/background-service/managed-frontend.ts +76 -5
  13. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +5 -0
  14. package/src/runtime/domain/background-service/navigator-provider.ts +4 -0
  15. package/src/runtime/domain/background-service/observed-waits.domain.mjs +203 -31
  16. package/src/runtime/domain/background-service/observed-waits.ts +168 -24
  17. package/src/runtime/domain/background-service/process.domain.mjs +49 -11
  18. package/src/runtime/domain/background-service/process.ts +45 -11
  19. package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
  20. package/src/runtime/domain/background-service/review-settings.ts +18 -0
  21. package/src/runtime/domain/background-service/runtime.domain.mjs +8 -70
  22. package/src/runtime/domain/background-service/runtime.ts +8 -73
  23. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +55 -28
  24. package/src/runtime/domain/background-service/shared-navigator.ts +47 -26
  25. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  26. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
  27. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +5 -1
  28. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +6 -0
  29. package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
  30. package/src/runtime/domain/background-service/stall.ts +7 -4
  31. package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
  32. package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
  33. package/src/runtime/domain/background-service/supervisor/README.md +1 -4
  34. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
  35. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +49 -11
  36. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
  37. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
  38. package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
  39. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
  40. package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
  41. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
  42. package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
  43. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
  44. package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
  45. package/src/runtime/domain/background-service/tools.domain.mjs +22 -16
  46. package/src/runtime/domain/background-service/tools.ts +26 -16
  47. package/src/runtime/domain/background-service/types.ts +4 -2
  48. package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
  49. package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
  50. package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
  51. package/src/runtime/domain/coordinator/src/store.mjs +5 -1
  52. package/src/runtime/domain/log-paths.mjs +8 -1
  53. package/src/runtime/domain/parse.mjs +9 -5
  54. package/src/runtime/domain/sandbox-policy/README.md +3 -3
  55. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  56. package/src/runtime/domain/session-store.mjs +7 -0
  57. package/src/runtime/domain/subagents/README.md +12 -10
  58. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +2 -5
  59. package/src/runtime/domain/subagents/assignment-outcomes.ts +2 -5
  60. package/src/runtime/domain/subagents/assignment-report.domain.mjs +22 -0
  61. package/src/runtime/domain/subagents/assignment-report.ts +20 -0
  62. package/src/runtime/domain/subagents/batch.mjs +13 -5
  63. package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
  64. package/src/runtime/domain/subagents/cleanup.ts +10 -2
  65. package/src/runtime/domain/subagents/config.domain.mjs +5 -0
  66. package/src/runtime/domain/subagents/config.ts +7 -1
  67. package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
  68. package/src/runtime/domain/subagents/continuation.ts +4 -2
  69. package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
  70. package/src/runtime/domain/subagents/failures.ts +10 -2
  71. package/src/runtime/domain/subagents/finalization.domain.mjs +5 -2
  72. package/src/runtime/domain/subagents/finalization.ts +7 -2
  73. package/src/runtime/domain/subagents/index.domain.mjs +163 -61
  74. package/src/runtime/domain/subagents/index.ts +163 -60
  75. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +515 -0
  76. package/src/runtime/domain/subagents/isolated-workspace.ts +557 -0
  77. package/src/runtime/domain/subagents/list.mjs +2 -2
  78. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +22 -5
  79. package/src/runtime/domain/subagents/managed-launch-client.ts +23 -6
  80. package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
  81. package/src/runtime/domain/subagents/output-payload.ts +26 -12
  82. package/src/runtime/domain/subagents/package.json +4 -2
  83. package/src/runtime/domain/subagents/parse.domain.mjs +9 -5
  84. package/src/runtime/domain/subagents/parse.ts +10 -5
  85. package/src/runtime/domain/subagents/registry.domain.mjs +24 -18
  86. package/src/runtime/domain/subagents/registry.ts +23 -5
  87. package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
  88. package/src/runtime/domain/subagents/retained-result.ts +65 -0
  89. package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
  90. package/src/runtime/domain/subagents/session-selection.ts +2 -1
  91. package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
  92. package/src/runtime/domain/subagents/session-store.ts +9 -0
  93. package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
  94. package/src/runtime/domain/subagents/settings-page.ts +147 -108
  95. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +23 -7
  96. package/src/runtime/domain/subagents/shared-catalog.ts +23 -7
  97. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +55 -28
  98. package/src/runtime/domain/subagents/shared-navigator.ts +47 -26
  99. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  100. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
  101. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +5 -1
  102. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +6 -0
  103. package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
  104. package/src/runtime/domain/subagents/task-guard.ts +13 -1
  105. package/src/runtime/domain/subagents/task-policy.domain.mjs +2 -1
  106. package/src/runtime/domain/subagents/task-policy.ts +5 -1
  107. package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
  108. package/src/runtime/domain/subagents/tools.ts +4 -7
  109. package/src/runtime/domain/subagents/work-observation.domain.mjs +25 -1
  110. package/src/runtime/domain/subagents/work-observation.ts +20 -1
  111. package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
  112. package/src/runtime/domain/subagents/workspace-files.ts +114 -0
  113. package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
  114. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
  115. package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
  116. package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
  117. package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
  118. package/src/runtime/read-model.ts +4 -2
  119. package/src/runtime/root.ts +5 -2
  120. package/src/version.ts +1 -1
@@ -30,9 +30,10 @@
30
30
 
31
31
  import { spawn } from "node:child_process";
32
32
  import { closeSync, openSync, realpathSync } from "node:fs";
33
- import { resolve } from "node:path";
33
+ import { join, resolve } from "node:path";
34
34
  import { setTimeout as delay } from "node:timers/promises";
35
35
  import { fileURLToPath } from "node:url";
36
+ import { watchOutcomeFingerprint } from "../watch-fingerprint.ts";
36
37
  import { evaluateCondition, validateCondition } from "../conditions.ts";
37
38
  import { completeUtf8Length, stopProcessGroup, utf8PrefixLength } from "../process.ts";
38
39
  import { readProcessStartToken } from "../process-identity.ts";
@@ -47,6 +48,7 @@ import {
47
48
  supervisorPaths,
48
49
  writeCommandRecord,
49
50
  writeTerminalRecord,
51
+ writeTextAtomic,
50
52
  } from "./store.ts";
51
53
  import {
52
54
  DEFAULT_TERMINAL_TAIL_BYTES,
@@ -88,6 +90,7 @@ interface RunnerContext {
88
90
  checks: number;
89
91
  stdout: StreamSink;
90
92
  stderr: StreamSink;
93
+ progress: (observedAt: number, fingerprint?: string) => void;
91
94
  stopRequested: boolean;
92
95
  finalized: boolean;
93
96
  command?: { pid: number; pgid?: number; pidStartTime?: string; startedAt: number; attempt: number };
@@ -212,6 +215,29 @@ function streamChunk(sink: StreamSink, chunk: Buffer, maxBytes: number): void {
212
215
  }
213
216
  }
214
217
 
218
+ /** Coalesce stream bursts while retaining the timestamp of the last byte, including discarded output. */
219
+ function progressRecorder(directory: string) {
220
+ const path = join(directory, "progress.json");
221
+ let pending: { observedAt: number; fingerprint?: string } | undefined;
222
+ let timer: NodeJS.Timeout | undefined;
223
+ let lastWrite = 0;
224
+ const flush = () => {
225
+ timer = undefined;
226
+ if (!pending) return;
227
+ try { writeTextAtomic(path, JSON.stringify(pending)); }
228
+ catch (error) { process.stderr.write(`Could not record Background progress: ${String(error)}\n`); }
229
+ lastWrite = Date.now();
230
+ };
231
+ return (observedAt: number, fingerprint?: string) => {
232
+ if (fingerprint !== undefined && pending?.fingerprint === fingerprint) return;
233
+ pending = { observedAt, fingerprint };
234
+ if (timer) return;
235
+ const remaining = lastWrite + 1000 - Date.now();
236
+ if (remaining <= 0) flush();
237
+ else { timer = setTimeout(flush, remaining); timer.unref(); }
238
+ };
239
+ }
240
+
215
241
  function startToken(pid: number | undefined): string | undefined {
216
242
  return pid === undefined ? undefined : readProcessStartToken(pid);
217
243
  }
@@ -482,12 +508,18 @@ function runChild(ctx: RunnerContext, plan: ChildPlan): Promise<ChildOutcome> {
482
508
 
483
509
  child.stdout?.on("data", (chunk: Buffer | string) => {
484
510
  const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
485
- if (plan.mode === "stream") streamChunk(ctx.stdout, buffer, plan.maxBytes);
511
+ if (plan.mode === "stream") {
512
+ streamChunk(ctx.stdout, buffer, plan.maxBytes);
513
+ if (buffer.length) ctx.progress(Date.now());
514
+ }
486
515
  else captureChunk(stdoutCapture, buffer, plan.maxBytes);
487
516
  });
488
517
  child.stderr?.on("data", (chunk: Buffer | string) => {
489
518
  const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
490
- if (plan.mode === "stream") streamChunk(ctx.stderr, buffer, plan.maxBytes);
519
+ if (plan.mode === "stream") {
520
+ streamChunk(ctx.stderr, buffer, plan.maxBytes);
521
+ if (buffer.length) ctx.progress(Date.now());
522
+ }
491
523
  else captureChunk(stderrCapture, buffer, plan.maxBytes);
492
524
  });
493
525
  child.on("error", (error) => {
@@ -704,6 +736,7 @@ async function runWatch(ctx: RunnerContext): Promise<void> {
704
736
  });
705
737
  if (ctx.finalized) return;
706
738
  ctx.checks += 1;
739
+ ctx.progress(outcome.endedAt, watchOutcomeFingerprint({ ...asCommandResult(outcome), ...(outcome.spawnError ? { error: outcome.spawnError } : {}) }));
707
740
  // Per-check output keeps the streams apart: stdout bytes in stdout.log, stderr in stderr.log.
708
741
  streamChunk(ctx.stdout, Buffer.from(outcome.stdout), ctx.launch.maxLogBytes);
709
742
  streamChunk(ctx.stderr, Buffer.from(outcome.stderr), ctx.launch.maxLogBytes);
@@ -936,9 +969,11 @@ function main(): number {
936
969
  checks: 0,
937
970
  stdout,
938
971
  stderr,
972
+ progress: progressRecorder(paths.dir),
939
973
  stopRequested: false,
940
974
  finalized: false,
941
975
  };
976
+ ctx.progress(ctx.startedAt);
942
977
  appendEvent(paths.events, `claimed runner_pid=${process.pid} runner_version=${SUPERVISOR_RUNNER_VERSION} kind=${launch.kind} cwd=${launch.command.cwd}`);
943
978
 
944
979
  const onSignal = (signal: NodeJS.Signals): void => {
@@ -326,13 +326,13 @@ function readText(path) {
326
326
  catch (error) {
327
327
  if (error.code === "ENOENT")
328
328
  return { missing: true };
329
- return { missing: true, error: error instanceof Error ? error.message : String(error) };
329
+ return { missing: false, error: error instanceof Error ? error.message : String(error) };
330
330
  }
331
331
  }
332
332
  function readJsonRecord(path, problem) {
333
333
  const read = readText(path);
334
- if (read.missing)
335
- return { missing: true, error: read.error };
334
+ if (read.value === undefined)
335
+ return { missing: read.missing, error: read.error };
336
336
  let parsed;
337
337
  try {
338
338
  parsed = JSON.parse(read.value);
@@ -397,16 +397,16 @@ function readText(path: string): RecordRead<string> {
397
397
  return { value: readFileSync(path, "utf8"), missing: false };
398
398
  } catch (error) {
399
399
  if ((error as NodeJS.ErrnoException).code === "ENOENT") return { missing: true };
400
- return { missing: true, error: error instanceof Error ? error.message : String(error) };
400
+ return { missing: false, error: error instanceof Error ? error.message : String(error) };
401
401
  }
402
402
  }
403
403
 
404
404
  function readJsonRecord<T>(path: string, problem: (value: unknown) => string | undefined): RecordRead<T> {
405
405
  const read = readText(path);
406
- if (read.missing) return { missing: true, error: read.error };
406
+ if (read.value === undefined) return { missing: read.missing, error: read.error };
407
407
  let parsed: unknown;
408
408
  try {
409
- parsed = JSON.parse(read.value!);
409
+ parsed = JSON.parse(read.value);
410
410
  } catch (error) {
411
411
  return { missing: false, error: `invalid JSON: ${error instanceof Error ? error.message : String(error)}` };
412
412
  }
@@ -464,13 +464,19 @@ class Supervisor {
464
464
  }
465
465
  applyReconciliation(launch, options) {
466
466
  return withStateFence(this.directory, launch.taskId, () => {
467
- const result = readTerminalRecord(this.directory, launch.taskId).value;
467
+ const { value: result, error: resultError } = readTerminalRecord(this.directory, launch.taskId);
468
+ if (resultError)
469
+ throw new Error(`Unreadable supervisor result record for ${launch.taskId}: ${resultError}`);
468
470
  if (result)
469
471
  return { status: result.status, terminal: true, result };
470
- const existingLost = readLostRecord(this.directory, launch.taskId).value;
472
+ const { value: existingLost, error: lostError } = readLostRecord(this.directory, launch.taskId);
473
+ if (lostError)
474
+ throw new Error(`Unreadable supervisor loss record for ${launch.taskId}: ${lostError}`);
471
475
  if (existingLost)
472
476
  return { status: "lost", terminal: true, lost: existingLost };
473
- const claim = readClaimRecord(this.directory, launch.taskId).value;
477
+ const { value: claim, error: claimError } = readClaimRecord(this.directory, launch.taskId);
478
+ if (claimError)
479
+ throw new Error(`Unreadable supervisor claim record for ${launch.taskId}: ${claimError}`);
474
480
  if (claim) {
475
481
  if (identityAlive(claim.pid, claim.pidStartTime, claim.claimedAt, this.readToken)) {
476
482
  return { status: "running", terminal: false };
@@ -527,13 +527,16 @@ class Supervisor implements LocalSupervisor {
527
527
  options: SupervisorInspectOptions,
528
528
  ): { status: SupervisorTaskStatus; terminal: boolean; result?: SupervisorTerminalRecord; lost?: SupervisorLostRecord } {
529
529
  return withStateFence(this.directory, launch.taskId, () => {
530
- const result = readTerminalRecord(this.directory, launch.taskId).value;
530
+ const { value: result, error: resultError } = readTerminalRecord(this.directory, launch.taskId);
531
+ if (resultError) throw new Error(`Unreadable supervisor result record for ${launch.taskId}: ${resultError}`);
531
532
  if (result) return { status: result.status as SupervisorTaskStatus, terminal: true, result };
532
533
 
533
- const existingLost = readLostRecord(this.directory, launch.taskId).value;
534
+ const { value: existingLost, error: lostError } = readLostRecord(this.directory, launch.taskId);
535
+ if (lostError) throw new Error(`Unreadable supervisor loss record for ${launch.taskId}: ${lostError}`);
534
536
  if (existingLost) return { status: "lost" as const, terminal: true, lost: existingLost };
535
537
 
536
- const claim = readClaimRecord(this.directory, launch.taskId).value;
538
+ const { value: claim, error: claimError } = readClaimRecord(this.directory, launch.taskId);
539
+ if (claimError) throw new Error(`Unreadable supervisor claim record for ${launch.taskId}: ${claimError}`);
537
540
  if (claim) {
538
541
  if (identityAlive(claim.pid, claim.pidStartTime, claim.claimedAt, this.readToken)) {
539
542
  return { status: "running" as const, terminal: false };
@@ -1,5 +1,6 @@
1
1
  // Generated fixed launch domain from packages/pi-better-background-tasks/src/tools.ts. Do not edit directly.
2
2
  import { Type } from "typebox";
3
+ import { truncateToWidth as piTruncateToWidth, visibleWidth as piVisibleWidth, wrapTextWithAnsi as piWrapTextWithAnsi, } from "@earendil-works/pi-tui";
3
4
  import { advertiseBackgroundAdapter } from "./adapter-contract.domain.mjs";
4
5
  import { refreshBackgroundTasksNavigator } from "./navigator-provider.domain.mjs";
5
6
  import { classifyOwnership, formatLaunch, formatList, formatLog, formatMissingTask, formatMutationRefusal, formatStatus, formatDurableStatusMetadata, formatStopResult, } from "./output.domain.mjs";
@@ -951,29 +952,34 @@ function renderLines(lines, mode = "truncate") {
951
952
  invalidate() { },
952
953
  };
953
954
  }
955
+ /**
956
+ * Split one display line into rows of at most `width` terminal columns.
957
+ *
958
+ * Measures columns rather than characters: a CJK grapheme or emoji occupies two,
959
+ * so counting characters emitted rows wider than the width Pi asked for. Pi
960
+ * asserts every rendered line fits the terminal and exits the process when one
961
+ * does not, which turned any log holding double-width text into a crash that
962
+ * replayed on resume, because the tool result stays in session history.
963
+ */
954
964
  function wrapLineToVisibleWidth(line, width) {
955
965
  const str = String(line ?? "");
956
966
  const max = Math.max(1, Number(width) || 80);
957
- if (truncateToVisibleWidth(str, max) === str)
967
+ if (piVisibleWidth(str) <= max)
958
968
  return [str];
959
- const out = [];
960
- let current = "";
961
- let visible = 0;
962
- for (const char of str) {
963
- if (visible >= max) {
964
- out.push(current);
965
- current = "";
966
- visible = 0;
967
- }
968
- current += char;
969
- visible += 1;
970
- }
971
- out.push(current);
972
- return out;
969
+ const wrapped = piWrapTextWithAnsi(str, max);
970
+ return (wrapped.length > 0 ? wrapped : [str]).map((row) => fitToVisibleWidth(row, max));
973
971
  }
974
972
  function truncateToVisibleWidth(value, width) {
975
973
  const max = Math.max(0, Math.floor(width || 0));
976
- return String(value ?? "").slice(0, max);
974
+ return fitToVisibleWidth(String(value ?? ""), max);
975
+ }
976
+ /** Last resort for anything a wrap missed: never return a line wider than `max`. */
977
+ function fitToVisibleWidth(value, max) {
978
+ const str = String(value ?? "");
979
+ const limit = Math.max(0, Math.floor(max || 0));
980
+ if (piVisibleWidth(str) <= limit)
981
+ return str;
982
+ return piTruncateToWidth(str, limit, "");
977
983
  }
978
984
  async function formatStop(pi, id, _ctx, getActiveSession, options = {}, runtime) {
979
985
  const { stopTask } = runtime ?? await import("./runtime.domain.mjs");
@@ -1,5 +1,10 @@
1
1
  import { Type } from "typebox";
2
2
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import {
4
+ truncateToWidth as piTruncateToWidth,
5
+ visibleWidth as piVisibleWidth,
6
+ wrapTextWithAnsi as piWrapTextWithAnsi,
7
+ } from "@earendil-works/pi-tui";
3
8
  import { advertiseBackgroundAdapter } from "./adapter-contract.js";
4
9
  import { refreshBackgroundTasksNavigator } from "./navigator-provider.js";
5
10
  import {
@@ -1045,29 +1050,34 @@ function renderLines(lines: string[], mode: "truncate" | "wrap" = "truncate") {
1045
1050
  };
1046
1051
  }
1047
1052
 
1053
+ /**
1054
+ * Split one display line into rows of at most `width` terminal columns.
1055
+ *
1056
+ * Measures columns rather than characters: a CJK grapheme or emoji occupies two,
1057
+ * so counting characters emitted rows wider than the width Pi asked for. Pi
1058
+ * asserts every rendered line fits the terminal and exits the process when one
1059
+ * does not, which turned any log holding double-width text into a crash that
1060
+ * replayed on resume, because the tool result stays in session history.
1061
+ */
1048
1062
  function wrapLineToVisibleWidth(line: string, width: number): string[] {
1049
1063
  const str = String(line ?? "");
1050
1064
  const max = Math.max(1, Number(width) || 80);
1051
- if (truncateToVisibleWidth(str, max) === str) return [str];
1052
- const out: string[] = [];
1053
- let current = "";
1054
- let visible = 0;
1055
- for (const char of str) {
1056
- if (visible >= max) {
1057
- out.push(current);
1058
- current = "";
1059
- visible = 0;
1060
- }
1061
- current += char;
1062
- visible += 1;
1063
- }
1064
- out.push(current);
1065
- return out;
1065
+ if (piVisibleWidth(str) <= max) return [str];
1066
+ const wrapped = piWrapTextWithAnsi(str, max);
1067
+ return (wrapped.length > 0 ? wrapped : [str]).map((row) => fitToVisibleWidth(row, max));
1066
1068
  }
1067
1069
 
1068
1070
  function truncateToVisibleWidth(value: string, width: number): string {
1069
1071
  const max = Math.max(0, Math.floor(width || 0));
1070
- return String(value ?? "").slice(0, max);
1072
+ return fitToVisibleWidth(String(value ?? ""), max);
1073
+ }
1074
+
1075
+ /** Last resort for anything a wrap missed: never return a line wider than `max`. */
1076
+ function fitToVisibleWidth(value: string, max: number): string {
1077
+ const str = String(value ?? "");
1078
+ const limit = Math.max(0, Math.floor(max || 0));
1079
+ if (piVisibleWidth(str) <= limit) return str;
1080
+ return piTruncateToWidth(str, limit, "");
1071
1081
  }
1072
1082
 
1073
1083
  async function formatStop(
@@ -24,6 +24,8 @@ export interface CommandSpec {
24
24
  shell?: boolean;
25
25
  /** Run the shell as a login shell (`bash -lc`, the default). False runs `bash -c`, skipping profile sourcing. */
26
26
  loginShell?: boolean;
27
+ /** Internal executable selected by the host for a Windows shell or log trampoline. */
28
+ resolvedWindowsShell?: string;
27
29
  cwd?: string;
28
30
  env?: Record<string, string>;
29
31
  }
@@ -160,8 +162,8 @@ export interface BackgroundTaskMeta {
160
162
  env?: Record<string, string>;
161
163
  /**
162
164
  * The executable and argv this task was actually launched with, when that
163
- * differs from `command`/`argv` above — today, an OS write-sandbox wrapper
164
- * captured from the foreground policy at launch. Re-running a watch poll uses
165
+ * differs from `command`/`argv` above, such as an OS write-sandbox wrapper
166
+ * or a Windows watch shell selected at launch. Re-running a watch poll uses
165
167
  * it verbatim, which is how a running task keeps the policy it started under
166
168
  * even after the foreground policy changes. `command`/`argv` stay the operator's
167
169
  * own request, so status, navigator, and goal surfaces read unchanged.
@@ -0,0 +1,67 @@
1
+ // Generated fixed launch domain from packages/pi-better-background-tasks/src/watch-fingerprint.ts. Do not edit directly.
2
+ import { createHash } from "node:crypto";
3
+ /** Version tag of the watch outcome fingerprint. A value from another version is adopted, never compared. */
4
+ export const WATCH_FINGERPRINT_VERSION = "v1";
5
+ /** OSC and CSI control sequences are display markup, not content. */
6
+ const TERMINAL_ESCAPE = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b\[[0-?]*[ -/]*[@-~]/g;
7
+ /**
8
+ * Text as the terminal would settle it. Redraw frames and control sequences are
9
+ * display churn: repainting the same visible line is not a new observation.
10
+ */
11
+ function settledTerminalText(text) {
12
+ return text
13
+ .replace(TERMINAL_ESCAPE, "")
14
+ .split("\n")
15
+ .map((line) => {
16
+ // A CR immediately before LF ends the line; any other CR overwrites it in place.
17
+ const body = line.endsWith("\r") ? line.slice(0, -1) : line;
18
+ return (body.split("\r").at(-1) ?? "").replace(/[ \t]+$/, "");
19
+ })
20
+ .join("\n")
21
+ .replace(/\n+$/, "");
22
+ }
23
+ /** Objects compare by content regardless of key order, so reordered keys are not progress. */
24
+ function canonicalJsonText(value) {
25
+ if (Array.isArray(value))
26
+ return `[${value.map(canonicalJsonText).join(",")}]`;
27
+ if (value && typeof value === "object") {
28
+ const record = value;
29
+ const entries = Object.keys(record).sort()
30
+ .map((key) => `${JSON.stringify(key)}:${canonicalJsonText(record[key])}`);
31
+ return `{${entries.join(",")}}`;
32
+ }
33
+ return JSON.stringify(value) ?? "null";
34
+ }
35
+ /** stdout compares as JSON content when it parses, and as settled text otherwise. */
36
+ function canonicalWatchStdout(stdout) {
37
+ const settled = settledTerminalText(stdout);
38
+ try {
39
+ return `json:${canonicalJsonText(JSON.parse(settled))}`;
40
+ }
41
+ catch {
42
+ return `text:${settled}`;
43
+ }
44
+ }
45
+ /**
46
+ * What a poll observed, independent of when it ran. Exit status, signal, error,
47
+ * stdout content, and stderr content are included; poll metadata (start time,
48
+ * end time, duration, check count) is deliberately not, so it can never hide a
49
+ * watch that reports the same outcome forever. Watch stdout may carry its own
50
+ * timestamps: projecting meaningful fields is the caller's job, not this
51
+ * fingerprint's guess.
52
+ */
53
+ export function watchOutcomeFingerprint(result) {
54
+ // A runner may report why the check itself could not run; that is part of the
55
+ // observed outcome, not poll metadata.
56
+ const reported = result.error;
57
+ const error = typeof reported === "string" ? settledTerminalText(reported) : null;
58
+ const payload = JSON.stringify([
59
+ result.exitCode,
60
+ result.signal ?? null,
61
+ result.timedOut === true,
62
+ error,
63
+ canonicalWatchStdout(result.stdout),
64
+ settledTerminalText(result.stderr),
65
+ ]);
66
+ return `${WATCH_FINGERPRINT_VERSION}:${createHash("sha256").update(payload).digest("hex")}`;
67
+ }
@@ -0,0 +1,70 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { CommandResult } from "./types.js";
3
+
4
+ /** Version tag of the watch outcome fingerprint. A value from another version is adopted, never compared. */
5
+ export const WATCH_FINGERPRINT_VERSION = "v1";
6
+ /** OSC and CSI control sequences are display markup, not content. */
7
+ const TERMINAL_ESCAPE = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b\[[0-?]*[ -/]*[@-~]/g;
8
+
9
+ /**
10
+ * Text as the terminal would settle it. Redraw frames and control sequences are
11
+ * display churn: repainting the same visible line is not a new observation.
12
+ */
13
+ function settledTerminalText(text: string): string {
14
+ return text
15
+ .replace(TERMINAL_ESCAPE, "")
16
+ .split("\n")
17
+ .map((line) => {
18
+ // A CR immediately before LF ends the line; any other CR overwrites it in place.
19
+ const body = line.endsWith("\r") ? line.slice(0, -1) : line;
20
+ return (body.split("\r").at(-1) ?? "").replace(/[ \t]+$/, "");
21
+ })
22
+ .join("\n")
23
+ .replace(/\n+$/, "");
24
+ }
25
+
26
+ /** Objects compare by content regardless of key order, so reordered keys are not progress. */
27
+ function canonicalJsonText(value: unknown): string {
28
+ if (Array.isArray(value)) return `[${value.map(canonicalJsonText).join(",")}]`;
29
+ if (value && typeof value === "object") {
30
+ const record = value as Record<string, unknown>;
31
+ const entries = Object.keys(record).sort()
32
+ .map((key) => `${JSON.stringify(key)}:${canonicalJsonText(record[key])}`);
33
+ return `{${entries.join(",")}}`;
34
+ }
35
+ return JSON.stringify(value) ?? "null";
36
+ }
37
+
38
+ /** stdout compares as JSON content when it parses, and as settled text otherwise. */
39
+ function canonicalWatchStdout(stdout: string): string {
40
+ const settled = settledTerminalText(stdout);
41
+ try {
42
+ return `json:${canonicalJsonText(JSON.parse(settled))}`;
43
+ } catch {
44
+ return `text:${settled}`;
45
+ }
46
+ }
47
+
48
+ /**
49
+ * What a poll observed, independent of when it ran. Exit status, signal, error,
50
+ * stdout content, and stderr content are included; poll metadata (start time,
51
+ * end time, duration, check count) is deliberately not, so it can never hide a
52
+ * watch that reports the same outcome forever. Watch stdout may carry its own
53
+ * timestamps: projecting meaningful fields is the caller's job, not this
54
+ * fingerprint's guess.
55
+ */
56
+ export function watchOutcomeFingerprint(result: CommandResult): string {
57
+ // A runner may report why the check itself could not run; that is part of the
58
+ // observed outcome, not poll metadata.
59
+ const reported = (result as CommandResult & { error?: unknown }).error;
60
+ const error = typeof reported === "string" ? settledTerminalText(reported) : null;
61
+ const payload = JSON.stringify([
62
+ result.exitCode,
63
+ result.signal ?? null,
64
+ result.timedOut === true,
65
+ error,
66
+ canonicalWatchStdout(result.stdout),
67
+ settledTerminalText(result.stderr),
68
+ ]);
69
+ return `${WATCH_FINGERPRINT_VERSION}:${createHash("sha256").update(payload).digest("hex")}`;
70
+ }
@@ -155,6 +155,13 @@ export function listOutbox(ctx, filter = {}) {
155
155
  const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
156
156
  return getRows(ctx, `SELECT * FROM outbox_events ${where} ORDER BY created_at, event_id`, ...params).map((row) => mapOutbox(ctx, row));
157
157
  }
158
+ /** Check a wait handoff without loading the retained evidence for its generations. */
159
+ export function hasDeliveredWaitDependency(ctx, operationId, terminalRevision, recipient) {
160
+ const owner = ownerClause("recipient", recipient);
161
+ return getRows(ctx, `SELECT 1 FROM outbox_events
162
+ WHERE operation_id = ? AND terminal_revision = ? AND event_type = 'dependency-ready'
163
+ AND delivered_at IS NOT NULL AND ${owner.sql} LIMIT 1`, requireId("operationId", operationId), requireCounter("terminalRevision", terminalRevision), ...owner.params).length > 0;
164
+ }
158
165
  /** Find recipients with deliverable dependencies without loading each event's evidence. */
159
166
  export function listDispatchableOutboxRecipients(ctx) {
160
167
  return getRows(ctx, `SELECT recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id,
@@ -23,7 +23,7 @@ import { createContext, openDatabase, run } from "./sqlite.mjs";
23
23
  import { getOperation as readOperationRecord, listAssignmentCleanupOperations as readAssignmentCleanupOperations, listOperations as readOperationRecords, listRunningSupervisedBy as readRunningSupervisedBy, releaseSupervision as writeSupervisionRelease, recordSupervision as writeSupervision, recordTerminalOutcome as writeTerminalOutcome, registerOperation as writeOperation, } from "./operations.mjs";
24
24
  import { getChangeRevision as readChangeRevision, readDiscoveryClaim as readClaim, readDiscoveryState, releaseDiscoveryClaim as deleteDiscoveryClaim, tryClaimDiscovery as writeDiscoveryClaim, } from "./discovery.mjs";
25
25
  import { acknowledgeResult as writeAcknowledgement, cancelWait as writeCancellation, claimResume as writeClaim, findPendingWaitForOwner, getWait as readWait, listDependencies as readDependencies, listEvidencePins as readPins, listEvidenceReads as readReads, listResumeClaims as readClaims, listUnreconciledClaims, listWaits as readWaits, publishResumeAttempt as writeAttemptPublication, recordEvidencePin as writePin, recordEvidenceRead as writeRead, registerWait as writeWait, releaseEvidencePins as writePinRelease, holdFailedResume as writeHoldFailedResume, releaseResumeClaim as writeClaimRelease, transitionWaitPhase as writePhase, } from "./waits.mjs";
26
- import { claimOutbox as writeOutboxClaim, listDispatchableOutboxRecipients as readDispatchableOutboxRecipients, listOutbox as readOutbox, markOutboxDelivered as writeOutboxDelivery, releaseOutbox as writeOutboxRelease, } from "./outbox.mjs";
26
+ import { claimOutbox as writeOutboxClaim, hasDeliveredWaitDependency as readDeliveredWaitDependency, listDispatchableOutboxRecipients as readDispatchableOutboxRecipients, listOutbox as readOutbox, markOutboxDelivered as writeOutboxDelivery, releaseOutbox as writeOutboxRelease, } from "./outbox.mjs";
27
27
  import { readOperationEvidence } from "./rows.mjs";
28
28
  import { SCHEMA_VERSION, } from "./types.mjs";
29
29
  export function openStore(options) {
@@ -249,6 +249,10 @@ export function openStore(options) {
249
249
  alive();
250
250
  return readOutbox(ctx, filter);
251
251
  },
252
+ hasDeliveredWaitDependency(operationId, terminalRevision, recipient) {
253
+ alive();
254
+ return readDeliveredWaitDependency(ctx, operationId, terminalRevision, recipient);
255
+ },
252
256
  listDispatchableOutboxRecipients() {
253
257
  alive();
254
258
  return readDispatchableOutboxRecipients(ctx);
@@ -1,4 +1,5 @@
1
- import { realpathSync } from "node:fs";
1
+ import { retainedLogPath } from "./session-store.mjs";
2
+ import { existsSync, realpathSync } from "node:fs";
2
3
  import { tmpdir } from "node:os";
3
4
  import { join } from "node:path";
4
5
  /** Root of the VOLATILE runtime registry, deliberately OUTSIDE any repo. */
@@ -11,3 +12,9 @@ export function runDir(id) {
11
12
  export function logPathFor(id) {
12
13
  return join(runDir(id), "output.log");
13
14
  }
15
+ export function evidenceLogPath(id) {
16
+ const live = logPathFor(id);
17
+ if (existsSync(live) || existsSync(runDir(id)))
18
+ return live;
19
+ return retainedLogPath(id) ?? live;
20
+ }
@@ -23,7 +23,7 @@
23
23
  import { closeSync, openSync, readSync, statSync, } from "node:fs";
24
24
  import { readBoundedTail, tailTerminalDisplay } from "./shared-log-utils.mjs";
25
25
  import { readAppendedLines, parseLogEvent, logReadMetrics } from "./log-cursor.mjs";
26
- import { logPathFor } from "./log-paths.mjs";
26
+ import { evidenceLogPath } from "./log-paths.mjs";
27
27
  const DEFAULT_PARSE_TAIL_BYTES = 32 * 1024 * 1024; // 32 MiB
28
28
  const DEFAULT_RAW_TAIL_BYTES = 256 * 1024; // 256 KiB
29
29
  function envBytes(name, fallback) {
@@ -58,7 +58,7 @@ function fmtBytes(n) {
58
58
  const readTail = readBoundedTail;
59
59
  /** Last `n` terminal display rows of a run's log, or a placeholder if empty/unreadable. */
60
60
  export function tailLog(id, n, maxBytes = maxRawTailBytes()) {
61
- const tail = readTail(logPathFor(id), maxBytes);
61
+ const tail = readTail(evidenceLogPath(id), maxBytes);
62
62
  if (tail.error || tail.text.trim() === "")
63
63
  return "(no output yet)";
64
64
  const out = tailTerminalDisplay(tail.text, n).trim();
@@ -97,7 +97,7 @@ function transcriptContent(msg) {
97
97
  export function readRunTranscript(id, options = {}) {
98
98
  const maxBytes = Math.max(1024, options.maxBytes ?? DEFAULT_TRANSCRIPT_TAIL_BYTES);
99
99
  const maxEntries = Math.max(1, options.maxEntries ?? DEFAULT_TRANSCRIPT_ENTRIES);
100
- const tail = readTail(options.logPath ?? logPathFor(id), maxBytes);
100
+ const tail = readTail(options.logPath ?? evidenceLogPath(id), maxBytes);
101
101
  if (tail.error)
102
102
  return { entries: [], truncated: false, diagnostic: `Log unreadable: ${tail.error}` };
103
103
  const lines = tail.text.split(/\r?\n/);
@@ -724,7 +724,7 @@ function feedStructuralRecordChar(scan, ch) {
724
724
  * only after a record is grammar-valid; unfinished/malformed records fail closed.
725
725
  */
726
726
  export function scanLifecycleEvidence(id) {
727
- const path = logPathFor(id);
727
+ const path = evidenceLogPath(id);
728
728
  let totalBytes = 0;
729
729
  try {
730
730
  totalBytes = statSync(path).size;
@@ -1083,6 +1083,9 @@ function foldParseEvent(state, e) {
1083
1083
  state.openToolCalls.set(toolCallId ?? `anonymous:${state.anonymousToolCall++}`, { id: toolCallId, toolName });
1084
1084
  }
1085
1085
  if (type === "tool_execution_end") {
1086
+ const operation = e.result?.details?.deniedWorktreeGitOperation;
1087
+ if (e.isError && typeof operation === "string" && /^[a-z-]{1,24}$/.test(operation))
1088
+ state.deniedWorktreeGitOperation = operation;
1086
1089
  if (toolCallId) {
1087
1090
  state.openToolCalls.delete(toolCallId);
1088
1091
  }
@@ -1105,7 +1108,7 @@ export function parseRun(id, options = {}) {
1105
1108
  const key = options.logPath ?? id;
1106
1109
  const states = options.states ?? parseStates;
1107
1110
  const previous = states.get(key);
1108
- const path = options.logPath ?? logPathFor(id);
1111
+ const path = options.logPath ?? evidenceLogPath(id);
1109
1112
  let catchUp = false;
1110
1113
  if (options.summaryOnly) {
1111
1114
  try {
@@ -1172,6 +1175,7 @@ export function parseRun(id, options = {}) {
1172
1175
  return {
1173
1176
  finalText: view.finalText,
1174
1177
  lastActivity: view.lastActivity,
1178
+ ...(view.deniedWorktreeGitOperation ? { deniedWorktreeGitOperation: view.deniedWorktreeGitOperation } : {}),
1175
1179
  toolCalls: [...view.toolCalls],
1176
1180
  toolCallCount: view.toolCallCount,
1177
1181
  unmatchedToolCalls: [...view.openToolCalls.values()],
@@ -1,6 +1,6 @@
1
1
  # pi-better-sandbox
2
2
 
3
- Sandbox permissions for Pi's foreground tools, detached subagents, and local background tasks. See the [sandbox tool-loading and permission contract](../../docs/adr/0027-sandbox-tools-and-permissions.md).
3
+ Sandbox permissions for Pi's foreground tools, detached subagents, and local background tasks. See the [sandbox tool-loading and permission contract](https://github.com/1aboveio/pi-better-harness/blob/main/docs/adr/0027-sandbox-tools-and-permissions.md).
4
4
 
5
5
  ![Pi Better Sandbox package preview](https://raw.githubusercontent.com/1aboveio/pi-better-harness/main/docs/images/package-gallery/pi-better-sandbox.png)
6
6
 
@@ -164,7 +164,7 @@ Linux could separate removal from writing with Landlock (5.19+), but nothing
164
164
  here can apply it: Node has no binding and `bwrap` does not expose it. Windows
165
165
  could use NTFS `DELETE` rights with a restricted token or AppContainer, which
166
166
  would need a native launcher. Both are tracked as follow-ups; see
167
- [ADR 0008](../../docs/adr/0008-write-without-delete.md).
167
+ [ADR 0008](https://github.com/1aboveio/pi-better-harness/blob/main/docs/adr/0008-write-without-delete.md).
168
168
 
169
169
  ### Recovery snapshot (macOS)
170
170
 
@@ -309,7 +309,7 @@ schema identity before admitting local spawn/watch and explicit registry
309
309
  operations. Background's column controls the executable, independently of
310
310
  Main's commands switch. Missing or incompatible adapters fail closed when
311
311
  Background confinement is enabled, even with Main Off. Remote stop receives no
312
- local-adapter exemption under Main confinement. See [ADR 0017](../../docs/adr/0017-background-adapter-admission.md).
312
+ local-adapter exemption under Main confinement. See [ADR 0017](https://github.com/1aboveio/pi-better-harness/blob/main/docs/adr/0017-background-adapter-admission.md).
313
313
 
314
314
  Overriding `write` and `edit` changes nothing you can see: the parameter
315
315
  schemas, prompt guidance, call rendering, write previews, edit diffs, result
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-sandbox",
3
- "version": "0.15.0",
3
+ "version": "0.15.1",
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",
@@ -72,6 +72,13 @@ export function durableSubagentRoot(env = process.env, home = homedir()) {
72
72
  const agentDir = env.PI_CODING_AGENT_DIR?.trim();
73
73
  return join(agentDir || join(home, ".pi", "agent"), "subagents");
74
74
  }
75
+ export function resultDir(id) {
76
+ return /^sa_[a-z0-9]+_[a-z0-9]+$/i.test(id) ? join(durableSubagentRoot(), "results", id) : undefined;
77
+ }
78
+ export function retainedLogPath(id) {
79
+ const dir = resultDir(id);
80
+ return dir && join(dir, "output.log");
81
+ }
75
82
  /** Durable `--session-dir` for new child launches. */
76
83
  export function durableSessionsDir() {
77
84
  return join(durableSubagentRoot(), "sessions");