pi-better-server 0.6.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 (142) 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/codex/return.ts +3 -2
  5. package/src/detach/extension.ts +20 -3
  6. package/src/event-log.ts +40 -12
  7. package/src/hosted-session.ts +11 -5
  8. package/src/remote-client/packages.ts +1 -4
  9. package/src/runtime/background-tools.ts +54 -8
  10. package/src/runtime/background.ts +16 -4
  11. package/src/runtime/domain/background/process.mjs +49 -11
  12. package/src/runtime/domain/background/supervisor/store.mjs +3 -3
  13. package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
  14. package/src/runtime/domain/background-service/index.domain.mjs +19 -0
  15. package/src/runtime/domain/background-service/index.ts +19 -0
  16. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +87 -5
  17. package/src/runtime/domain/background-service/managed-frontend.ts +76 -5
  18. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +5 -0
  19. package/src/runtime/domain/background-service/navigator-provider.ts +4 -0
  20. package/src/runtime/domain/background-service/observed-waits.domain.mjs +203 -31
  21. package/src/runtime/domain/background-service/observed-waits.ts +168 -24
  22. package/src/runtime/domain/background-service/process.domain.mjs +49 -11
  23. package/src/runtime/domain/background-service/process.ts +45 -11
  24. package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
  25. package/src/runtime/domain/background-service/review-settings.ts +18 -0
  26. package/src/runtime/domain/background-service/runtime.domain.mjs +8 -70
  27. package/src/runtime/domain/background-service/runtime.ts +8 -73
  28. package/src/runtime/domain/background-service/shared-harness-settings.domain.mjs +2 -3
  29. package/src/runtime/domain/background-service/shared-harness-settings.ts +2 -5
  30. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +55 -28
  31. package/src/runtime/domain/background-service/shared-navigator.ts +47 -26
  32. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  33. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
  34. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +5 -1
  35. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +6 -0
  36. package/src/runtime/domain/background-service/shared-ssh-core/index.domain.mjs +1 -1
  37. package/src/runtime/domain/background-service/shared-ssh-core/index.ts +1 -1
  38. package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
  39. package/src/runtime/domain/background-service/stall.ts +7 -4
  40. package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
  41. package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
  42. package/src/runtime/domain/background-service/supervisor/README.md +1 -4
  43. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
  44. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +49 -11
  45. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
  46. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
  47. package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
  48. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
  49. package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
  50. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
  51. package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
  52. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
  53. package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
  54. package/src/runtime/domain/background-service/tools.domain.mjs +22 -16
  55. package/src/runtime/domain/background-service/tools.ts +26 -16
  56. package/src/runtime/domain/background-service/types.ts +4 -2
  57. package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
  58. package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
  59. package/src/runtime/domain/catalog/catalog-preferences.mjs +1 -3
  60. package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
  61. package/src/runtime/domain/coordinator/src/store.mjs +5 -1
  62. package/src/runtime/domain/log-paths.mjs +8 -1
  63. package/src/runtime/domain/parse.mjs +9 -5
  64. package/src/runtime/domain/sandbox-policy/README.md +3 -3
  65. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  66. package/src/runtime/domain/sandbox-policy/shared-harness-settings.domain.mjs +2 -3
  67. package/src/runtime/domain/sandbox-policy/shared-harness-settings.ts +2 -5
  68. package/src/runtime/domain/session-store.mjs +7 -0
  69. package/src/runtime/domain/shared-harness-settings.mjs +2 -3
  70. package/src/runtime/domain/subagents/README.md +12 -10
  71. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +2 -5
  72. package/src/runtime/domain/subagents/assignment-outcomes.ts +2 -5
  73. package/src/runtime/domain/subagents/assignment-report.domain.mjs +22 -0
  74. package/src/runtime/domain/subagents/assignment-report.ts +20 -0
  75. package/src/runtime/domain/subagents/batch.mjs +13 -5
  76. package/src/runtime/domain/subagents/catalog-preferences.domain.mjs +1 -3
  77. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -5
  78. package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
  79. package/src/runtime/domain/subagents/cleanup.ts +10 -2
  80. package/src/runtime/domain/subagents/config.domain.mjs +5 -0
  81. package/src/runtime/domain/subagents/config.ts +8 -2
  82. package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
  83. package/src/runtime/domain/subagents/continuation.ts +4 -2
  84. package/src/runtime/domain/subagents/extensions.mjs +1 -0
  85. package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
  86. package/src/runtime/domain/subagents/failures.ts +10 -2
  87. package/src/runtime/domain/subagents/finalization.domain.mjs +39 -32
  88. package/src/runtime/domain/subagents/finalization.ts +37 -30
  89. package/src/runtime/domain/subagents/git-workspace.domain.mjs +51 -6
  90. package/src/runtime/domain/subagents/git-workspace.ts +48 -6
  91. package/src/runtime/domain/subagents/index.domain.mjs +208 -75
  92. package/src/runtime/domain/subagents/index.ts +213 -75
  93. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +508 -0
  94. package/src/runtime/domain/subagents/isolated-workspace.ts +551 -0
  95. package/src/runtime/domain/subagents/list.mjs +2 -2
  96. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +22 -5
  97. package/src/runtime/domain/subagents/managed-launch-client.ts +23 -6
  98. package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
  99. package/src/runtime/domain/subagents/output-payload.ts +26 -12
  100. package/src/runtime/domain/subagents/package.json +4 -2
  101. package/src/runtime/domain/subagents/parse.domain.mjs +9 -5
  102. package/src/runtime/domain/subagents/parse.ts +10 -5
  103. package/src/runtime/domain/subagents/registry.domain.mjs +31 -25
  104. package/src/runtime/domain/subagents/registry.ts +31 -13
  105. package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
  106. package/src/runtime/domain/subagents/retained-result.ts +65 -0
  107. package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
  108. package/src/runtime/domain/subagents/session-selection.ts +2 -1
  109. package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
  110. package/src/runtime/domain/subagents/session-store.ts +9 -0
  111. package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
  112. package/src/runtime/domain/subagents/settings-page.ts +147 -108
  113. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +23 -7
  114. package/src/runtime/domain/subagents/shared-catalog.ts +23 -7
  115. package/src/runtime/domain/subagents/shared-harness-settings.domain.mjs +2 -3
  116. package/src/runtime/domain/subagents/shared-harness-settings.ts +2 -5
  117. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +55 -28
  118. package/src/runtime/domain/subagents/shared-navigator.ts +47 -26
  119. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  120. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
  121. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +5 -1
  122. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +6 -0
  123. package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
  124. package/src/runtime/domain/subagents/task-guard.ts +13 -1
  125. package/src/runtime/domain/subagents/task-policy.domain.mjs +2 -1
  126. package/src/runtime/domain/subagents/task-policy.ts +5 -1
  127. package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
  128. package/src/runtime/domain/subagents/tools.ts +4 -7
  129. package/src/runtime/domain/subagents/work-observation.domain.mjs +25 -1
  130. package/src/runtime/domain/subagents/work-observation.ts +20 -1
  131. package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
  132. package/src/runtime/domain/subagents/workspace-files.ts +114 -0
  133. package/src/runtime/domain/subagents/workspace-prepare-worker.mjs +12 -0
  134. package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
  135. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
  136. package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
  137. package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
  138. package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
  139. package/src/runtime/read-model.ts +4 -2
  140. package/src/runtime/root.ts +5 -2
  141. package/src/shared-ssh-core/index.ts +1 -1
  142. package/src/version.ts +1 -1
@@ -10,6 +10,8 @@ let context;
10
10
  let connecting;
11
11
  let collecting;
12
12
  let collectingClient;
13
+ let collectionRetry;
14
+ let collectionFailures = 0;
13
15
  let dirty = false;
14
16
  let retry;
15
17
  let backoff = 100;
@@ -48,6 +50,9 @@ function reconnectLater(current) {
48
50
  }
49
51
  // Every page is bounded; a conversation anchor fences collection across filtered queries.
50
52
  async function collect(candidate, current) {
53
+ if (collectionRetry)
54
+ clearTimeout(collectionRetry);
55
+ collectionRetry = undefined;
51
56
  dirty = true;
52
57
  if (collecting && collectingClient === candidate)
53
58
  return collecting;
@@ -119,6 +124,7 @@ async function collect(candidate, current) {
119
124
  snapshot = { ...first, seq: anchor.seq, observedRevisionVector: anchor.observedRevisionVector, rows: allRows, nextCursor: undefined,
120
125
  observedAtLocal: Date.now(),
121
126
  totalMatching: first.totalMatching + history.totalMatching, activity: { active: rows.length } };
127
+ collectionFailures = 0;
122
128
  completed = true;
123
129
  refresh();
124
130
  }
@@ -127,8 +133,21 @@ async function collect(candidate, current) {
127
133
  return;
128
134
  if (attempt === 1 || candidate.closed) {
129
135
  degraded(error);
130
- if (candidate.closed)
136
+ if (current !== generation || candidate !== client || candidate.closed)
131
137
  return;
138
+ // Retry the outstanding notification after transient transport or
139
+ // consistency failures, even when the terminal source sends no more events.
140
+ const message = error instanceof Error ? error.message : String(error);
141
+ if (!dirty && /^(?:runtime-(?:timeout|overloaded|unhealthy)|resync_required):/.test(message) && collectionFailures < 3) {
142
+ const wait = 100 * 2 ** collectionFailures++;
143
+ collectionRetry = setTimeout(() => {
144
+ collectionRetry = undefined;
145
+ if (current === generation && candidate === client && !candidate.closed)
146
+ void collect(candidate, current).catch(error => { if (current === generation && candidate === client)
147
+ degraded(error); });
148
+ }, wait);
149
+ collectionRetry.unref?.();
150
+ }
132
151
  // A notification received during these page reads is
133
152
  // still owed a coherent collection. Drain only that
134
153
  // demand through the outer loop; do not start a poller.
@@ -179,6 +198,7 @@ async function connectObservation(current) {
179
198
  candidate.onChange(() => {
180
199
  if (current !== generation || candidate !== client)
181
200
  return;
201
+ collectionFailures = 0;
182
202
  if (candidate.closed) {
183
203
  details.clear();
184
204
  pendingDetails.clear();
@@ -275,6 +295,10 @@ export async function observedList(scope) { return query(scope); }
275
295
  export function stopWorkObservation() {
276
296
  generation++;
277
297
  context = undefined;
298
+ if (collectionRetry)
299
+ clearTimeout(collectionRetry);
300
+ collectionRetry = undefined;
301
+ collectionFailures = 0;
278
302
  connectionAbort.abort();
279
303
  connectionAbort = new AbortController();
280
304
  if (retry)
@@ -10,6 +10,8 @@ let context: { agentDir: string; origin: { cwd: string; sessionId?: string } } |
10
10
  let connecting: Promise<void> | undefined;
11
11
  let collecting: Promise<void> | undefined;
12
12
  let collectingClient: WorkClient | undefined;
13
+ let collectionRetry: ReturnType<typeof setTimeout> | undefined;
14
+ let collectionFailures = 0;
13
15
  let dirty = false;
14
16
  let retry: ReturnType<typeof setTimeout> | undefined;
15
17
  let backoff = 100;
@@ -48,6 +50,7 @@ function reconnectLater(current: number) {
48
50
 
49
51
  // Every page is bounded; a conversation anchor fences collection across filtered queries.
50
52
  async function collect(candidate: WorkClient, current: number) {
53
+ if (collectionRetry) clearTimeout(collectionRetry); collectionRetry = undefined;
51
54
  dirty = true;
52
55
  if (collecting && collectingClient === candidate) return collecting;
53
56
  collectingClient = candidate;
@@ -104,12 +107,25 @@ async function collect(candidate: WorkClient, current: number) {
104
107
  snapshot = { ...first, seq: anchor.seq, observedRevisionVector: anchor.observedRevisionVector, rows: allRows, nextCursor: undefined,
105
108
  observedAtLocal: Date.now(),
106
109
  totalMatching: first.totalMatching + history.totalMatching, activity: { active: rows.length } };
110
+ collectionFailures = 0;
107
111
  completed = true; refresh();
108
112
  } catch (error) {
109
113
  if (current !== generation || candidate !== client) return;
110
114
  if (attempt === 1 || candidate.closed) {
111
115
  degraded(error);
112
- if (candidate.closed) return;
116
+ if (current !== generation || candidate !== client || candidate.closed) return;
117
+ // Retry the outstanding notification after transient transport or
118
+ // consistency failures, even when the terminal source sends no more events.
119
+ const message = error instanceof Error ? error.message : String(error);
120
+ if (!dirty && /^(?:runtime-(?:timeout|overloaded|unhealthy)|resync_required):/.test(message) && collectionFailures < 3) {
121
+ const wait = 100 * 2 ** collectionFailures++;
122
+ collectionRetry = setTimeout(() => {
123
+ collectionRetry = undefined;
124
+ if (current === generation && candidate === client && !candidate.closed)
125
+ void collect(candidate, current).catch(error => { if (current === generation && candidate === client) degraded(error); });
126
+ }, wait);
127
+ collectionRetry.unref?.();
128
+ }
113
129
  // A notification received during these page reads is
114
130
  // still owed a coherent collection. Drain only that
115
131
  // demand through the outer loop; do not start a poller.
@@ -151,6 +167,7 @@ async function connectObservation(current: number) {
151
167
  client = candidate;
152
168
  candidate.onChange(() => {
153
169
  if (current !== generation || candidate !== client) return;
170
+ collectionFailures = 0;
154
171
  if (candidate.closed) {
155
172
  details.clear(); pendingDetails.clear();
156
173
  degraded(candidate.snapshot?.reason ?? "runtime-unavailable: disconnected; resync required");
@@ -221,6 +238,8 @@ export async function observedList(scope: object) { return query(scope); }
221
238
 
222
239
  export function stopWorkObservation() {
223
240
  generation++; context = undefined;
241
+ if (collectionRetry) clearTimeout(collectionRetry); collectionRetry = undefined;
242
+ collectionFailures = 0;
224
243
  connectionAbort.abort(); connectionAbort = new AbortController();
225
244
  if (retry) clearTimeout(retry); retry = undefined;
226
245
  client?.close(); client = undefined; snapshot = undefined;
@@ -0,0 +1,103 @@
1
+ // Generated fixed launch domain from packages/pi-better-subagents/workspace-files.ts. Do not edit directly.
2
+ // A private content store lets retained checkouts share identical Git objects and files.
3
+ // Source files are never hardlinked into storage. Restoring a file makes an independent copy.
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ import { chmodSync, closeSync, constants, copyFileSync, existsSync, lstatSync, mkdirSync, openSync, readSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, } from "node:fs";
6
+ import { dirname, join } from "node:path";
7
+ function fileHash(path) {
8
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
9
+ try {
10
+ const hash = createHash("sha256");
11
+ const buffer = Buffer.allocUnsafe(128 * 1024);
12
+ let bytes;
13
+ while ((bytes = readSync(fd, buffer, 0, buffer.length, null)) > 0)
14
+ hash.update(buffer.subarray(0, bytes));
15
+ return hash.digest("hex");
16
+ }
17
+ finally {
18
+ closeSync(fd);
19
+ }
20
+ }
21
+ function blobPath(store, hash) {
22
+ if (!/^[a-f0-9]{64}$/.test(hash))
23
+ throw new Error("Invalid saved file identity");
24
+ return join(store, hash.slice(0, 2), hash.slice(2));
25
+ }
26
+ function saveFile(path, store, hash) {
27
+ const dest = blobPath(store, hash);
28
+ if (existsSync(dest))
29
+ return;
30
+ mkdirSync(dirname(dest), { recursive: true, mode: 0o700 });
31
+ const temp = dest + "-" + randomUUID();
32
+ try {
33
+ copyFileSync(path, temp, constants.COPYFILE_FICLONE);
34
+ chmodSync(temp, 0o600);
35
+ if (fileHash(temp) !== hash)
36
+ throw new Error("File changed while saving " + path);
37
+ renameSync(temp, dest);
38
+ }
39
+ finally {
40
+ rmSync(temp, { force: true });
41
+ }
42
+ }
43
+ // Directories precede children. Symbolic links are captured as links, never traversed.
44
+ export function snapshotTree(root, store, omit = new Set()) {
45
+ if (!lstatSync(root).isDirectory())
46
+ throw new Error("Expected a directory at " + root);
47
+ const entries = [];
48
+ function walk(parent) {
49
+ for (const child of readdirSync(join(root, parent)).sort()) {
50
+ const name = join(parent, child);
51
+ if (omit.has(name))
52
+ continue;
53
+ const path = join(root, name), stat = lstatSync(path), mode = stat.mode & 0o7777;
54
+ if (stat.isDirectory()) {
55
+ entries.push({ name, mode, type: "directory" });
56
+ walk(name);
57
+ }
58
+ else if (stat.isSymbolicLink()) {
59
+ entries.push({ name, mode, type: "symlink", target: readlinkSync(path) });
60
+ }
61
+ else if (stat.isFile()) {
62
+ const blob = fileHash(path);
63
+ if (store)
64
+ saveFile(path, store, blob);
65
+ entries.push({ name, mode, type: "file", blob });
66
+ }
67
+ else
68
+ throw new Error("Cannot save special file " + path + ". The original is retained.");
69
+ }
70
+ }
71
+ walk("");
72
+ return entries;
73
+ }
74
+ export function restoreTree(root, store, entries) {
75
+ mkdirSync(root, { recursive: true, mode: 0o700 });
76
+ const directories = new Set(["."]);
77
+ for (const entry of entries) {
78
+ const parts = entry.name.split("/");
79
+ if (parts.some((p) => !p || p === "." || p === "..") || !directories.has(dirname(entry.name))) {
80
+ throw new Error("Invalid path in workspace manifest");
81
+ }
82
+ const dest = join(root, entry.name);
83
+ if (entry.type === "directory") {
84
+ mkdirSync(dest);
85
+ directories.add(entry.name);
86
+ }
87
+ else if (entry.type === "symlink")
88
+ symlinkSync(entry.target, dest);
89
+ else {
90
+ copyFileSync(blobPath(store, entry.blob), dest, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE);
91
+ chmodSync(dest, entry.mode);
92
+ }
93
+ }
94
+ for (const entry of entries.slice().reverse()) {
95
+ if (entry.type === "directory")
96
+ chmodSync(join(root, entry.name), entry.mode);
97
+ }
98
+ }
99
+ export function verifyTree(root, entries, omit) {
100
+ if (JSON.stringify(snapshotTree(root, undefined, omit)) !== JSON.stringify(entries)) {
101
+ throw new Error("Workspace contents changed or could not be recovered at " + root);
102
+ }
103
+ }
@@ -0,0 +1,114 @@
1
+ // A private content store lets retained checkouts share identical Git objects and files.
2
+ // Source files are never hardlinked into storage. Restoring a file makes an independent copy.
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import {
5
+ chmodSync,
6
+ closeSync,
7
+ constants,
8
+ copyFileSync,
9
+ existsSync,
10
+ lstatSync,
11
+ mkdirSync,
12
+ openSync,
13
+ readSync,
14
+ readdirSync,
15
+ readlinkSync,
16
+ renameSync,
17
+ rmSync,
18
+ symlinkSync,
19
+ } from "node:fs";
20
+ import { dirname, join } from "node:path";
21
+
22
+ export type SavedEntry =
23
+ | { name: string; mode: number; type: "directory" }
24
+ | { name: string; mode: number; type: "file"; blob: string }
25
+ | { name: string; mode: number; type: "symlink"; target: string };
26
+
27
+ function fileHash(path: string): string {
28
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
29
+ try {
30
+ const hash = createHash("sha256");
31
+ const buffer = Buffer.allocUnsafe(128 * 1024);
32
+ let bytes: number;
33
+ while ((bytes = readSync(fd, buffer, 0, buffer.length, null)) > 0) hash.update(buffer.subarray(0, bytes));
34
+ return hash.digest("hex");
35
+ } finally {
36
+ closeSync(fd);
37
+ }
38
+ }
39
+
40
+ function blobPath(store: string, hash: string): string {
41
+ if (!/^[a-f0-9]{64}$/.test(hash)) throw new Error("Invalid saved file identity");
42
+ return join(store, hash.slice(0, 2), hash.slice(2));
43
+ }
44
+
45
+ function saveFile(path: string, store: string, hash: string): void {
46
+ const dest = blobPath(store, hash);
47
+ if (existsSync(dest)) return;
48
+ mkdirSync(dirname(dest), { recursive: true, mode: 0o700 });
49
+ const temp = dest + "-" + randomUUID();
50
+ try {
51
+ copyFileSync(path, temp, constants.COPYFILE_FICLONE);
52
+ chmodSync(temp, 0o600);
53
+ if (fileHash(temp) !== hash) throw new Error("File changed while saving " + path);
54
+ renameSync(temp, dest);
55
+ } finally {
56
+ rmSync(temp, { force: true });
57
+ }
58
+ }
59
+
60
+ // Directories precede children. Symbolic links are captured as links, never traversed.
61
+ export function snapshotTree(root: string, store?: string, omit: ReadonlySet<string> = new Set()): SavedEntry[] {
62
+ if (!lstatSync(root).isDirectory()) throw new Error("Expected a directory at " + root);
63
+ const entries: SavedEntry[] = [];
64
+ function walk(parent: string): void {
65
+ for (const child of readdirSync(join(root, parent)).sort()) {
66
+ const name = join(parent, child);
67
+ if (omit.has(name)) continue;
68
+ const path = join(root, name),
69
+ stat = lstatSync(path),
70
+ mode = stat.mode & 0o7777;
71
+ if (stat.isDirectory()) {
72
+ entries.push({ name, mode, type: "directory" });
73
+ walk(name);
74
+ } else if (stat.isSymbolicLink()) {
75
+ entries.push({ name, mode, type: "symlink", target: readlinkSync(path) });
76
+ } else if (stat.isFile()) {
77
+ const blob = fileHash(path);
78
+ if (store) saveFile(path, store, blob);
79
+ entries.push({ name, mode, type: "file", blob });
80
+ } else throw new Error("Cannot save special file " + path + ". The original is retained.");
81
+ }
82
+ }
83
+ walk("");
84
+ return entries;
85
+ }
86
+
87
+ export function restoreTree(root: string, store: string, entries: SavedEntry[]): void {
88
+ mkdirSync(root, { recursive: true, mode: 0o700 });
89
+ const directories = new Set(["."]);
90
+ for (const entry of entries) {
91
+ const parts = entry.name.split("/");
92
+ if (parts.some((p) => !p || p === "." || p === "..") || !directories.has(dirname(entry.name))) {
93
+ throw new Error("Invalid path in workspace manifest");
94
+ }
95
+ const dest = join(root, entry.name);
96
+ if (entry.type === "directory") {
97
+ mkdirSync(dest);
98
+ directories.add(entry.name);
99
+ } else if (entry.type === "symlink") symlinkSync(entry.target, dest);
100
+ else {
101
+ copyFileSync(blobPath(store, entry.blob), dest, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE);
102
+ chmodSync(dest, entry.mode);
103
+ }
104
+ }
105
+ for (const entry of entries.slice().reverse()) {
106
+ if (entry.type === "directory") chmodSync(join(root, entry.name), entry.mode);
107
+ }
108
+ }
109
+
110
+ export function verifyTree(root: string, entries: SavedEntry[], omit?: ReadonlySet<string>): void {
111
+ if (JSON.stringify(snapshotTree(root, undefined, omit)) !== JSON.stringify(entries)) {
112
+ throw new Error("Workspace contents changed or could not be recovered at " + root);
113
+ }
114
+ }
@@ -0,0 +1,12 @@
1
+ // Generated fixed launch domain from packages/pi-better-subagents/workspace-prepare-worker.mjs. Do not edit directly.
2
+ import { parentPort, workerData } from "node:worker_threads";
3
+ import { resolveSubagentWorkspace } from "./git-workspace.domain.mjs";
4
+ import { createIsolatedWorkspace } from "./isolated-workspace.domain.mjs";
5
+ const { options, isolated } = workerData;
6
+ if (isolated) {
7
+ const cwd = createIsolatedWorkspace(isolated, true);
8
+ parentPort.postMessage({ cwd, requestedSandboxDir: options.sandboxEnabled ? cwd : undefined });
9
+ }
10
+ else {
11
+ parentPort.postMessage(resolveSubagentWorkspace(options));
12
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Workspace (folder) scope for cross-session discovery.
3
+ *
4
+ * `subagent_list` defaults to the caller's current folder and its descendants,
5
+ * not to the foreground session that spawned a run. A folder is identified by
6
+ * its canonical path: two foreground sessions in the same folder share one
7
+ * list scope, and a run in a sibling folder that merely shares a name prefix
8
+ * (`/repo-other` vs `/repo`) is a different workspace.
9
+ *
10
+ * Paths are compared with `node:path.relative`, never with string prefixes, so
11
+ * `..`, separators, and sibling names cannot be mistaken for descendants. An
12
+ * existing directory is resolved through `realpath` first (a symlinked
13
+ * workspace and its target are the same folder); a path that no longer exists
14
+ * falls back to `path.resolve` so a deleted run workspace still compares
15
+ * predictably.
16
+ *
17
+ * This helper is shared with the parent name resolver, so it owns no list-only
18
+ * state and performs no I/O beyond `realpath`.
19
+ */
20
+ /** Canonical absolute form of one workspace path (realpath when it exists). */
21
+ export declare function normalizeWorkspacePath(path: string): string;
22
+ /**
23
+ * True when `candidateCwd` is `scopeCwd` itself or lies beneath it.
24
+ *
25
+ * A missing or empty candidate is never inside a workspace: metadata that does
26
+ * not name a workspace cannot be placed in the caller's folder.
27
+ */
28
+ export declare function isWithinWorkspace(candidateCwd: string, scopeCwd: string): boolean;
29
+ /** Folder where the parent requested the work. The execution cwd stays on the run for delivery and authorization. */
30
+ export declare function discoveryWorkspace(meta: {
31
+ cwd: string;
32
+ recipe?: {
33
+ workspace?: {
34
+ source: string;
35
+ subdir: string;
36
+ };
37
+ };
38
+ }): string;
@@ -50,3 +50,8 @@ export function isWithinWorkspace(candidateCwd, scopeCwd) {
50
50
  return true;
51
51
  return rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
52
52
  }
53
+ /** Folder where the parent requested the work. The execution cwd stays on the run for delivery and authorization. */
54
+ export function discoveryWorkspace(meta) {
55
+ const workspace = meta.recipe?.workspace;
56
+ return workspace ? resolve(workspace.source, workspace.subdir) : meta.cwd;
57
+ }
@@ -48,3 +48,9 @@ export function isWithinWorkspace(candidateCwd: string, scopeCwd: string): boole
48
48
  if (rel === "") return true;
49
49
  return rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
50
50
  }
51
+
52
+ /** Folder where the parent requested the work. The execution cwd stays on the run for delivery and authorization. */
53
+ export function discoveryWorkspace(meta: { cwd: string; recipe?: { workspace?: { source: string; subdir: string } } }): string {
54
+ const workspace = meta.recipe?.workspace;
55
+ return workspace ? resolve(workspace.source, workspace.subdir) : meta.cwd;
56
+ }
@@ -0,0 +1,55 @@
1
+ // Generated fixed launch domain from packages/pi-better-subagents/worktree-feedback.ts. Do not edit directly.
2
+ import { join } from "node:path";
3
+ import { evaluateDeleteAccess, evaluateWriteAccess } from "./shared-sandbox-core.domain.mjs";
4
+ // Require all three observations: an actual failed Git call, Git naming the index
5
+ // and OS denial, and the captured policy refusing that specific filesystem operation.
6
+ export function deniedGitOperation(event, gitDir, policy) {
7
+ if (!event.isError)
8
+ return;
9
+ let operation;
10
+ if (event.toolName === "run_application" &&
11
+ typeof event.input.executable === "string" &&
12
+ /^(?:\/usr\/bin\/|\/bin\/)?git$/.test(event.input.executable) &&
13
+ Array.isArray(event.input.args)) {
14
+ operation = event.input.args[0];
15
+ }
16
+ else if (event.toolName === "bash" && typeof event.input.command === "string") {
17
+ // A compound shell command can print diagnostics from a different program.
18
+ const command = event.input.command.trim();
19
+ if (!/[;&|<>$`\n]/.test(command))
20
+ operation = /^(?:\/usr\/bin\/|\/bin\/)?git\s+([a-z-]+)(?:\s|$)/.exec(command)?.[1];
21
+ }
22
+ if (!operation ||
23
+ !/^(?:add|commit|checkout|switch|reset|merge|rebase|restore|stash|cherry-pick|update-index|rm|mv|apply)$/.test(operation))
24
+ return;
25
+ const index = join(gitDir, "index"), lock = index + ".lock";
26
+ for (const block of event.content) {
27
+ if (block.type !== "text" || !block.text)
28
+ continue;
29
+ for (const line of block.text.split("\n")) {
30
+ if (!/^(?:fatal|error): /i.test(line) ||
31
+ !/(?:permission denied|operation not permitted|read-only file system)\s*$/i.test(line))
32
+ continue;
33
+ if (line.includes("'" + lock + "'") && !evaluateWriteAccess(lock, policy).allowed)
34
+ return operation;
35
+ if ((line.includes("'" + lock + "'") || line.includes("'" + index + "'")) &&
36
+ /renam|unlink|remov/i.test(line) &&
37
+ !evaluateDeleteAccess(lock, policy).allowed)
38
+ return operation;
39
+ }
40
+ }
41
+ }
42
+ export function worktreePolicyNotice(gitDir, policy) {
43
+ const lock = join(gitDir, "index.lock");
44
+ if (!evaluateWriteAccess(lock, policy).allowed)
45
+ return "The current sandbox profile denies writes to the shared Git index.";
46
+ if (!evaluateDeleteAccess(lock, policy).allowed)
47
+ return "The current sandbox profile restricts renaming or removing the shared Git index lock.";
48
+ }
49
+ export function worktreeDenialText(operation, cwd) {
50
+ return ("The sandbox denied git " +
51
+ operation +
52
+ " access to linked worktree metadata. Review the changes in " +
53
+ cwd +
54
+ " or continue this conversation with recover_in_clone:true.");
55
+ }
@@ -0,0 +1,77 @@
1
+ import { join } from "node:path";
2
+ import { evaluateDeleteAccess, evaluateWriteAccess, type CompiledSandboxWritePolicy } from "./shared-sandbox-core.ts";
3
+
4
+ export interface WorktreeFailure {
5
+ toolName: string;
6
+ isError: boolean;
7
+ input: Record<string, unknown>;
8
+ content: readonly { type: string; text?: string }[];
9
+ }
10
+
11
+ // Require all three observations: an actual failed Git call, Git naming the index
12
+ // and OS denial, and the captured policy refusing that specific filesystem operation.
13
+ export function deniedGitOperation(
14
+ event: WorktreeFailure,
15
+ gitDir: string,
16
+ policy: CompiledSandboxWritePolicy,
17
+ ): string | undefined {
18
+ if (!event.isError) return;
19
+ let operation: string | undefined;
20
+ if (
21
+ event.toolName === "run_application" &&
22
+ typeof event.input.executable === "string" &&
23
+ /^(?:\/usr\/bin\/|\/bin\/)?git$/.test(event.input.executable) &&
24
+ Array.isArray(event.input.args)
25
+ ) {
26
+ operation = event.input.args[0];
27
+ } else if (event.toolName === "bash" && typeof event.input.command === "string") {
28
+ // A compound shell command can print diagnostics from a different program.
29
+ const command = event.input.command.trim();
30
+ if (!/[;&|<>$`\n]/.test(command))
31
+ operation = /^(?:\/usr\/bin\/|\/bin\/)?git\s+([a-z-]+)(?:\s|$)/.exec(command)?.[1];
32
+ }
33
+ if (
34
+ !operation ||
35
+ !/^(?:add|commit|checkout|switch|reset|merge|rebase|restore|stash|cherry-pick|update-index|rm|mv|apply)$/.test(
36
+ operation,
37
+ )
38
+ )
39
+ return;
40
+ const index = join(gitDir, "index"),
41
+ lock = index + ".lock";
42
+ for (const block of event.content) {
43
+ if (block.type !== "text" || !block.text) continue;
44
+ for (const line of block.text.split("\n")) {
45
+ if (
46
+ !/^(?:fatal|error): /i.test(line) ||
47
+ !/(?:permission denied|operation not permitted|read-only file system)\s*$/i.test(line)
48
+ )
49
+ continue;
50
+ if (line.includes("'" + lock + "'") && !evaluateWriteAccess(lock, policy).allowed) return operation;
51
+ if (
52
+ (line.includes("'" + lock + "'") || line.includes("'" + index + "'")) &&
53
+ /renam|unlink|remov/i.test(line) &&
54
+ !evaluateDeleteAccess(lock, policy).allowed
55
+ )
56
+ return operation;
57
+ }
58
+ }
59
+ }
60
+
61
+ export function worktreePolicyNotice(gitDir: string, policy: CompiledSandboxWritePolicy): string | undefined {
62
+ const lock = join(gitDir, "index.lock");
63
+ if (!evaluateWriteAccess(lock, policy).allowed)
64
+ return "The current sandbox profile denies writes to the shared Git index.";
65
+ if (!evaluateDeleteAccess(lock, policy).allowed)
66
+ return "The current sandbox profile restricts renaming or removing the shared Git index lock.";
67
+ }
68
+
69
+ export function worktreeDenialText(operation: string, cwd: string): string {
70
+ return (
71
+ "The sandbox denied git " +
72
+ operation +
73
+ " access to linked worktree metadata. Review the changes in " +
74
+ cwd +
75
+ " or continue this conversation with recover_in_clone:true."
76
+ );
77
+ }
@@ -1,3 +1,4 @@
1
+ import { discoveryWorkspace } from "./domain/subagents/workspace-scope.domain.mjs";
1
2
  import { affectedAttempts } from "./attempt-invalidation.ts";
2
3
  import { processMatchesStart } from "../daemon-owner.ts";
3
4
  import { createHash } from "node:crypto";
@@ -425,7 +426,8 @@ export class WorkReadModel {
425
426
  if (scope.sessionId !== m.callbackOrigin?.sessionId || scope.cwd !== (m.callbackOrigin?.cwd ?? m.cwd)) return false;
426
427
  } else if (scope.cwd) {
427
428
  const cwd = resolve(scope.cwd), prefix = cwd.endsWith(sep) ? cwd : cwd + sep;
428
- if (m.cwd !== cwd && !m.cwd.startsWith(prefix)) return false;
429
+ const folder = discoveryWorkspace(m);
430
+ if (folder !== cwd && !folder.startsWith(prefix)) return false;
429
431
  }
430
432
  const active = ["running", "waiting"].includes(row.assignment.state);
431
433
  if (activity) return active;
@@ -1057,7 +1059,7 @@ export class WorkReadModel {
1057
1059
  changedRows.push({ before: this.projected.get(row.meta.id), after: row });
1058
1060
  const m = row.meta;
1059
1061
  if (m.management?.root !== this.agentDir || m.status === "running") this.db.prepare("DELETE FROM terminal_log_folds WHERE id=?").run(m.id);
1060
- insert.run(m.id, m.cwd, m.callbackOrigin?.cwd ?? m.cwd, m.callbackOrigin?.sessionId ?? null,
1062
+ insert.run(m.id, discoveryWorkspace(m), m.callbackOrigin?.cwd ?? m.cwd, m.callbackOrigin?.sessionId ?? null,
1061
1063
  m.startedAt, row.assignment.state, ["running", "waiting"].includes(row.assignment.state) ? 1 : 0, m.endedAt ?? m.lostAt ?? null, row.recipientPending ? 1 : 0, JSON.stringify(row));
1062
1064
  this.db.prepare("DELETE FROM assignment_members WHERE id=?").run(m.id);
1063
1065
  const session = m.assignment?.owner?.sessionId ?? m.operations?.conversationId ?? m.sessionId;
@@ -1,6 +1,7 @@
1
1
  import { linkSync, mkdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { join, resolve } from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
+ import { socketPathFor } from "./socket.ts";
4
5
 
5
6
  /** Transport selection is durable and independent of installation or package version. */
6
7
  export function runtimeRoot(agentDir: string, requestedServerDir: string): { agentDir: string; serverDir: string } {
@@ -17,9 +18,11 @@ export function runtimeRoot(agentDir: string, requestedServerDir: string): { age
17
18
  };
18
19
  try { return read(); }
19
20
  catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
20
- const temporary = `${path}.${randomUUID()}`;
21
21
  mkdirSync(requestedServerDir, { recursive: true, mode: 0o700 });
22
- const proposed = { version: 1, agentDir, serverDir: realpathSync(requestedServerDir) };
22
+ const serverDir = realpathSync(requestedServerDir);
23
+ socketPathFor(serverDir);
24
+ const proposed = { version: 1, agentDir, serverDir };
25
+ const temporary = `${path}.${randomUUID()}`;
23
26
  writeFileSync(temporary, JSON.stringify(proposed), { mode: 0o600, flag: "wx" });
24
27
  try {
25
28
  try { linkSync(temporary, path); }
@@ -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"}`);
package/src/version.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  /** Kept equal to package.json `version`; a test pins that. */
2
- export const SERVER_VERSION = "0.6.0";
2
+ export const SERVER_VERSION = "0.7.1";
3
3
 
4
4
  export const SERVER_EXTENSION_VERSIONS: Readonly<Record<string, string>> = { "pi-better-server": SERVER_VERSION };