pi-better-server 0.5.0 → 0.6.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 (278) hide show
  1. package/package.json +4 -1
  2. package/scripts/copy-pi-test-providers.mjs +10 -0
  3. package/scripts/event-publication/README.md +26 -0
  4. package/scripts/event-publication/commit.mjs +21 -0
  5. package/scripts/event-publication/measure.mjs +37 -5
  6. package/scripts/event-publication/writer.mjs +3 -8
  7. package/scripts/measure-full-runtime/probe.mjs +4 -2
  8. package/scripts/measure-full-runtime/recovery-trace-loader.mjs +51 -0
  9. package/scripts/measure-full-runtime/recovery-trace.mjs +16 -0
  10. package/scripts/measure-shared-reads.mjs +2 -1
  11. package/scripts/private-runtime/package-lock.json +18 -0
  12. package/scripts/private-runtime/package.json +4 -1
  13. package/scripts/source-provenance.mjs +2 -2
  14. package/scripts/test-on-pi.sh +2 -9
  15. package/src/handshake.ts +1 -1
  16. package/src/hosted-session.ts +32 -4
  17. package/src/maintenance.ts +35 -7
  18. package/src/registry.ts +28 -4
  19. package/src/runtime/attempt-invalidation.ts +54 -0
  20. package/src/runtime/background-history.ts +151 -45
  21. package/src/runtime/background-policy.ts +9 -4
  22. package/src/runtime/background-tools.ts +131 -23
  23. package/src/runtime/background.ts +351 -68
  24. package/src/runtime/cancellation.ts +28 -7
  25. package/src/runtime/catalog-sources.ts +199 -0
  26. package/src/runtime/catalog.ts +53 -21
  27. package/src/runtime/client.ts +22 -2
  28. package/src/runtime/domain/assignment-inbox.mjs +119 -0
  29. package/src/runtime/domain/assignment-observation.d.mts +1 -1
  30. package/src/runtime/domain/assignment-observation.mjs +43 -35
  31. package/src/runtime/domain/background/process-identity.mjs +20 -2
  32. package/src/runtime/domain/background/process.mjs +3 -3
  33. package/src/runtime/domain/background/registry.mjs +61 -3
  34. package/src/runtime/domain/background/types.mjs +1 -0
  35. package/src/runtime/domain/background-service/adapter-contract.domain.mjs +1 -1
  36. package/src/runtime/domain/background-service/adapter-contract.ts +1 -1
  37. package/src/runtime/domain/background-service/goal-provider.domain.mjs +35 -16
  38. package/src/runtime/domain/background-service/goal-provider.ts +31 -16
  39. package/src/runtime/domain/background-service/index.domain.mjs +6 -9
  40. package/src/runtime/domain/background-service/index.ts +6 -9
  41. package/src/runtime/domain/background-service/managed-authority.domain.mjs +6 -3
  42. package/src/runtime/domain/background-service/managed-authority.ts +5 -3
  43. package/src/runtime/domain/background-service/managed-client.domain.mjs +21 -7
  44. package/src/runtime/domain/background-service/managed-client.ts +20 -7
  45. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +75 -17
  46. package/src/runtime/domain/background-service/managed-frontend.ts +62 -17
  47. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +16 -5
  48. package/src/runtime/domain/background-service/navigator-provider.ts +15 -5
  49. package/src/runtime/domain/background-service/observed-wait-client.domain.mjs +6 -0
  50. package/src/runtime/domain/background-service/observed-wait-client.ts +10 -0
  51. package/src/runtime/domain/background-service/observed-waits.domain.mjs +170 -27
  52. package/src/runtime/domain/background-service/observed-waits.ts +154 -30
  53. package/src/runtime/domain/background-service/process-identity.domain.mjs +20 -2
  54. package/src/runtime/domain/background-service/process-identity.ts +18 -2
  55. package/src/runtime/domain/background-service/process.domain.mjs +3 -3
  56. package/src/runtime/domain/background-service/process.ts +3 -3
  57. package/src/runtime/domain/background-service/registry.domain.mjs +61 -3
  58. package/src/runtime/domain/background-service/registry.ts +53 -5
  59. package/src/runtime/domain/background-service/runtime.domain.mjs +32 -16
  60. package/src/runtime/domain/background-service/runtime.ts +19 -9
  61. package/src/runtime/domain/background-service/sandbox.domain.mjs +14 -15
  62. package/src/runtime/domain/background-service/sandbox.ts +14 -11
  63. package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +8 -1
  64. package/src/runtime/domain/background-service/shared-callback-batcher.ts +11 -2
  65. package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +24 -2
  66. package/src/runtime/domain/background-service/shared-navigator-panels.ts +26 -4
  67. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +218 -13
  68. package/src/runtime/domain/background-service/shared-navigator.ts +197 -14
  69. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  70. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +53 -41
  71. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  72. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  73. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  74. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  75. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  76. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +14 -3
  77. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  78. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +5 -3
  79. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  80. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +50 -2
  81. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  82. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +12 -0
  83. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  84. package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +2 -0
  85. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  86. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +40 -24
  87. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +21 -3
  88. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +34 -8
  89. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  90. package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  91. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +1 -1
  92. package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +5 -1
  93. package/src/runtime/domain/background-service/shared-sandbox-core.ts +1 -1
  94. package/src/runtime/domain/background-service/shared-work-client.mjs +174 -7
  95. package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +20 -2
  96. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +3 -3
  97. package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +1 -1
  98. package/src/runtime/domain/background-service/task-diagnostics.ts +1 -1
  99. package/src/runtime/domain/background-service/tools.domain.mjs +31 -24
  100. package/src/runtime/domain/background-service/tools.ts +41 -38
  101. package/src/runtime/domain/background-service/types.domain.mjs +1 -0
  102. package/src/runtime/domain/background-service/types.ts +3 -1
  103. package/src/runtime/domain/background-service/work-observation.domain.mjs +46 -20
  104. package/src/runtime/domain/background-service/work-observation.ts +46 -19
  105. package/src/runtime/domain/catalog/catalog-store.d.mts +9 -1
  106. package/src/runtime/domain/catalog/catalog-store.mjs +20 -22
  107. package/src/runtime/domain/coordinator/src/assignment-changes.mjs +75 -0
  108. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +2 -0
  109. package/src/runtime/domain/coordinator/src/background-requests.mjs +11 -2
  110. package/src/runtime/domain/coordinator/src/discovery.mjs +4 -2
  111. package/src/runtime/domain/coordinator/src/operations.mjs +44 -4
  112. package/src/runtime/domain/coordinator/src/result-supervision.mjs +12 -0
  113. package/src/runtime/domain/coordinator/src/rows.mjs +2 -0
  114. package/src/runtime/domain/coordinator/src/schema.mjs +42 -21
  115. package/src/runtime/domain/coordinator/src/store.mjs +21 -3
  116. package/src/runtime/domain/coordinator/src/subagent-launch.mjs +23 -1
  117. package/src/runtime/domain/coordinator/src/types.mjs +1 -1
  118. package/src/runtime/domain/health-observation.d.mts +3 -1
  119. package/src/runtime/domain/health-observation.mjs +189 -190
  120. package/src/runtime/domain/log-cursor.d.mts +2 -0
  121. package/src/runtime/domain/log-cursor.mjs +85 -16
  122. package/src/runtime/domain/parse.d.mts +4 -1
  123. package/src/runtime/domain/parse.mjs +50 -5
  124. package/src/runtime/domain/sandbox-policy/README.md +61 -63
  125. package/src/runtime/domain/sandbox-policy/commands.domain.mjs +11 -8
  126. package/src/runtime/domain/sandbox-policy/commands.ts +12 -7
  127. package/src/runtime/domain/sandbox-policy/index.domain.mjs +53 -9
  128. package/src/runtime/domain/sandbox-policy/index.ts +52 -9
  129. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  130. package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +5 -2
  131. package/src/runtime/domain/sandbox-policy/permission-settings.ts +9 -2
  132. package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +56 -137
  133. package/src/runtime/domain/sandbox-policy/permissions-page.ts +52 -130
  134. package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +1 -6
  135. package/src/runtime/domain/sandbox-policy/permissions.ts +1 -6
  136. package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1 -1
  137. package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +14 -1
  138. package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +12 -1
  139. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.domain.mjs +140 -0
  140. package/src/runtime/domain/sandbox-policy/shared-task-process-identity.ts +126 -0
  141. package/src/runtime/domain/sandbox-policy/shared-task-process-list.domain.mjs +3 -2
  142. package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +8 -2
  143. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +4 -3
  144. package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +5 -3
  145. package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +8 -5
  146. package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +8 -5
  147. package/src/runtime/domain/subagents/README.md +1 -1
  148. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +12 -6
  149. package/src/runtime/domain/subagents/assignment-outcomes.ts +11 -5
  150. package/src/runtime/domain/subagents/assignment-report.domain.mjs +87 -24
  151. package/src/runtime/domain/subagents/assignment-report.ts +83 -19
  152. package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +21 -3
  153. package/src/runtime/domain/subagents/catalog-host-admission.ts +19 -3
  154. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -1
  155. package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +35 -1
  156. package/src/runtime/domain/subagents/catalog-resolver.ts +35 -1
  157. package/src/runtime/domain/subagents/catalog-store.domain.mjs +20 -22
  158. package/src/runtime/domain/subagents/catalog-store.ts +27 -20
  159. package/src/runtime/domain/subagents/child-apply-patch.domain.mjs +13 -0
  160. package/src/runtime/domain/subagents/child-apply-patch.ts +13 -0
  161. package/src/runtime/domain/subagents/child-dependencies.mjs +27 -15
  162. package/src/runtime/domain/subagents/child-operations.domain.mjs +80 -2
  163. package/src/runtime/domain/subagents/child-operations.ts +80 -1
  164. package/src/runtime/domain/subagents/child-preflight.mjs +9 -2
  165. package/src/runtime/domain/subagents/child-process-list.domain.mjs +7 -0
  166. package/src/runtime/domain/subagents/child-process-list.ts +8 -0
  167. package/src/runtime/domain/subagents/config.domain.mjs +49 -2
  168. package/src/runtime/domain/subagents/config.ts +46 -2
  169. package/src/runtime/domain/subagents/continuation-authority.domain.mjs +5 -1
  170. package/src/runtime/domain/subagents/continuation-authority.ts +3 -1
  171. package/src/runtime/domain/subagents/continuation-runtime.domain.mjs +89 -0
  172. package/src/runtime/domain/subagents/continuation-runtime.ts +88 -0
  173. package/src/runtime/domain/subagents/extensions.mjs +11 -13
  174. package/src/runtime/domain/subagents/finalization.domain.mjs +12 -0
  175. package/src/runtime/domain/subagents/finalization.ts +15 -0
  176. package/src/runtime/domain/subagents/goal-provider.domain.mjs +44 -2
  177. package/src/runtime/domain/subagents/goal-provider.ts +44 -2
  178. package/src/runtime/domain/subagents/health-observation.domain.mjs +189 -190
  179. package/src/runtime/domain/subagents/health-observation.ts +43 -48
  180. package/src/runtime/domain/subagents/index.domain.mjs +296 -123
  181. package/src/runtime/domain/subagents/index.ts +257 -98
  182. package/src/runtime/domain/subagents/launch-context.domain.mjs +24 -0
  183. package/src/runtime/domain/subagents/launch-context.ts +23 -0
  184. package/src/runtime/domain/subagents/launch-digest.mjs +6 -0
  185. package/src/runtime/domain/subagents/log-cursor.domain.mjs +85 -16
  186. package/src/runtime/domain/subagents/log-cursor.ts +91 -15
  187. package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +2 -2
  188. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +6 -3
  189. package/src/runtime/domain/subagents/managed-launch-client.ts +6 -3
  190. package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +222 -14
  191. package/src/runtime/domain/subagents/managed-launch-host.ts +168 -15
  192. package/src/runtime/domain/subagents/managed-launch-journal.mjs +1 -5
  193. package/src/runtime/domain/subagents/managed-launch-port.ts +4 -0
  194. package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +27 -2
  195. package/src/runtime/domain/subagents/operation-bridge-types.ts +27 -2
  196. package/src/runtime/domain/subagents/owned-exit.domain.mjs +12 -0
  197. package/src/runtime/domain/subagents/owned-exit.ts +12 -0
  198. package/src/runtime/domain/subagents/package.json +1 -1
  199. package/src/runtime/domain/subagents/parse.domain.mjs +50 -5
  200. package/src/runtime/domain/subagents/parse.ts +48 -6
  201. package/src/runtime/domain/subagents/permission-policy.domain.mjs +32 -8
  202. package/src/runtime/domain/subagents/permission-policy.ts +41 -8
  203. package/src/runtime/domain/subagents/process-identity.mjs +33 -0
  204. package/src/runtime/domain/subagents/registry.domain.mjs +47 -33
  205. package/src/runtime/domain/subagents/registry.ts +54 -33
  206. package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +8 -1
  207. package/src/runtime/domain/subagents/shared-callback-batcher.ts +11 -2
  208. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +6 -23
  209. package/src/runtime/domain/subagents/shared-catalog.ts +6 -14
  210. package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +24 -2
  211. package/src/runtime/domain/subagents/shared-navigator-panels.ts +26 -4
  212. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +218 -13
  213. package/src/runtime/domain/subagents/shared-navigator.ts +197 -14
  214. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
  215. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +53 -41
  216. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
  217. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  218. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
  219. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  220. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
  221. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +14 -3
  222. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
  223. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +5 -3
  224. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +44 -4
  225. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +50 -2
  226. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
  227. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +12 -0
  228. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +2 -0
  229. package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +2 -0
  230. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +42 -21
  231. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +40 -24
  232. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +21 -3
  233. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +34 -8
  234. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
  235. package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  236. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +1 -1
  237. package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +5 -1
  238. package/src/runtime/domain/subagents/shared-sandbox-core.ts +1 -1
  239. package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +14 -1
  240. package/src/runtime/domain/subagents/shared-task-exec.ts +12 -1
  241. package/src/runtime/domain/subagents/shared-task-process-identity.domain.mjs +140 -0
  242. package/src/runtime/domain/subagents/shared-task-process-identity.ts +126 -0
  243. package/src/runtime/domain/subagents/shared-task-process-list.domain.mjs +3 -2
  244. package/src/runtime/domain/subagents/shared-task-process-list.ts +8 -2
  245. package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +4 -3
  246. package/src/runtime/domain/subagents/shared-task-sandbox.ts +5 -3
  247. package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +8 -5
  248. package/src/runtime/domain/subagents/shared-task-tools.ts +8 -5
  249. package/src/runtime/domain/subagents/shared-work-client.mjs +174 -7
  250. package/src/runtime/domain/subagents/subagent-tools.domain.mjs +22 -38
  251. package/src/runtime/domain/subagents/subagent-tools.ts +28 -34
  252. package/src/runtime/domain/subagents/task-policy.domain.mjs +1 -1
  253. package/src/runtime/domain/subagents/task-policy.ts +3 -1
  254. package/src/runtime/domain/subagents/timing.domain.mjs +10 -1
  255. package/src/runtime/domain/subagents/timing.ts +10 -1
  256. package/src/runtime/domain/subagents/work-observation.domain.mjs +77 -16
  257. package/src/runtime/domain/subagents/work-observation.ts +71 -16
  258. package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +9 -4
  259. package/src/runtime/domain/subagents/worker-operations-host.ts +12 -4
  260. package/src/runtime/domain/subagents/worker-waits.domain.mjs +89 -35
  261. package/src/runtime/domain/subagents/worker-waits.ts +93 -34
  262. package/src/runtime/health-config.ts +27 -11
  263. package/src/runtime/log-checkpoints.ts +117 -0
  264. package/src/runtime/mutation-store.ts +5 -4
  265. package/src/runtime/queries.ts +25 -2
  266. package/src/runtime/query-executor.ts +149 -28
  267. package/src/runtime/query-worker.mjs +106 -21
  268. package/src/runtime/read-model.ts +846 -120
  269. package/src/runtime/read-watchdog-probe.ts +4 -0
  270. package/src/runtime/result-supervision.ts +188 -16
  271. package/src/runtime/source-watch.ts +175 -0
  272. package/src/runtime/subagent-launch.ts +11 -4
  273. package/src/runtime/work-budget.ts +130 -0
  274. package/src/runtime/work-client.d.mts +8 -0
  275. package/src/runtime/work-client.mjs +150 -7
  276. package/src/server.ts +104 -23
  277. package/src/session-activity.ts +26 -4
  278. package/src/version.ts +1 -1
@@ -1,30 +1,18 @@
1
1
  import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
2
2
  import { Key, matchesKey, truncateToWidth, visibleWidth, type Component } from "@earendil-works/pi-tui";
3
3
 
4
- import { isNetworkTool, packageLabel, type DiscoveredTool } from "./shared-task-tools.ts";
5
4
  import { defaultSandboxPermissions, type CredentialAccess, type FileAccess, type SandboxPermissionProfile as PermissionProfile, type SandboxPermissionSettings as PermissionSettings } from "./permissions.ts";
6
5
  export type { PermissionProfile, PermissionSettings };
7
6
 
8
7
  export interface PermissionPageHandlers {
9
8
  getConfig(): PermissionSettings;
9
+ toolLoading?(): { main: { name: string; provider: string }[]; subagents?: { name: string; provider: string }[] };
10
10
  change(settings: PermissionSettings): void | Promise<void>;
11
11
  save(settings: PermissionSettings): void | Promise<void>;
12
12
  /** What saving `settings` would loosen versus the saved defaults. Reported after the save. */
13
13
  loosening?(settings: PermissionSettings): string[];
14
- /** Trusted-tool candidates registered in Pi (core builtins and non-SSH harness tools excluded). */
15
- discoverTools?(): readonly Pick<DiscoveredTool, "name" | "package" | "source">[];
16
14
  }
17
15
 
18
- type TrustedItem = Pick<DiscoveredTool, "name" | "package" | "source"> & { kind: "trusted"; loaded: boolean; group: string };
19
- type ToolGroup = { kind: "group"; id: string; label: string; tools: TrustedItem[] };
20
- type ToolItem =
21
- | { kind: "guarded"; name: "apply_patch" }
22
- | TrustedItem
23
- | ToolGroup;
24
-
25
- const GUARDED_HINT = "apply_patch goes through the guarded file operations: Project files and Outside project apply to it.";
26
- const TRUSTED_HINT = "Trusted tools run in the subagent's Pi process, outside the file rules. Tick only tools you trust.";
27
-
28
16
  export const DEFAULT_PERMISSION_SETTINGS = defaultSandboxPermissions();
29
17
 
30
18
  const rows = [
@@ -62,8 +50,8 @@ function cellHint(key: string, profile: PermissionProfile | undefined, column?:
62
50
  if (key === "shell") return "Shell scripts run inside the sandbox. Requires Run applications.";
63
51
  if (key === "commandTimeoutSeconds") return "Commands stop after this long. No limit lets them run until they finish.";
64
52
  if (key === "processAccess") return column === "background"
65
- ? "Task status diagnostics: requires Read here and in Main. No process control; shell access is unchanged."
66
- : "process_list: current-user PIDs and names. Main also gates task diagnostics. No process control.";
53
+ ? "Task status diagnostics: gated by this row when Background tasks is On. Unavailable under Main confinement."
54
+ : "Fixed process reads and macOS ps identity. This setting applies while the profile is On. No process control.";
67
55
  return undefined;
68
56
  }
69
57
  const columns = ["main", "subagents", "background"] as const;
@@ -83,7 +71,7 @@ function cell(text: string, width: number): string {
83
71
  return cut + " ".repeat(Math.max(0, width - visibleWidth(cut)));
84
72
  }
85
73
 
86
- /** Keyboard-driven profiles and a foldable package/provider tool tree. */
74
+ /** Keyboard-driven resource permissions and tool inventory. */
87
75
  export function createPermissionsPage(
88
76
  theme: Theme,
89
77
  handlers: PermissionPageHandlers,
@@ -91,6 +79,27 @@ export function createPermissionsPage(
91
79
  close: () => void,
92
80
  ): Component {
93
81
  let settings: PermissionSettings | undefined;
82
+ let section: "permissions" | "loading" = "permissions";
83
+ let loadingRows: string[] = [];
84
+ let loadingOffset = 0;
85
+ const loadingWindow = 14;
86
+ function readLoading(): string[] {
87
+ try {
88
+ const inventory = handlers.toolLoading?.();
89
+ const entries = (tools: { name: string; provider: string }[]) =>
90
+ tools.map(tool => ` ${tool.name} · ${tool.provider}`);
91
+ return [
92
+ "Ordinary subagent defaults",
93
+ ...(inventory?.subagents === undefined ? [" Subagents extension unavailable"]
94
+ : inventory.subagents.length ? entries(inventory.subagents) : [" No default tools selected"]),
95
+ "", "Local Background tasks run commands through the Background adapter.",
96
+ "", "Active Main tools",
97
+ ...(inventory ? entries(inventory.main) : [" Tool inventory unavailable"]),
98
+ ];
99
+ } catch (error) {
100
+ return [`Tool inventory unavailable: ${errorText(error)}`];
101
+ }
102
+ }
94
103
  let message = "";
95
104
  let isError = false;
96
105
  try {
@@ -99,47 +108,6 @@ export function createPermissionsPage(
99
108
  message = errorText(error);
100
109
  isError = true;
101
110
  }
102
- let discovered: readonly Pick<DiscoveredTool, "name" | "package" | "source">[] = [];
103
- try {
104
- discovered = handlers.discoverTools?.() ?? [];
105
- } catch (error) {
106
- message = `Tool discovery failed: ${errorText(error)}`;
107
- isError = true;
108
- }
109
- const isTicked = (item: { name: string; package: string }) =>
110
- !!settings?.subagentTools.trusted.some((tool) => tool.name === item.name && tool.package === item.package);
111
- const expanded = new Set<string>();
112
- function toolGroups(): ToolGroup[] {
113
- const trusted = new Map<string, TrustedItem>();
114
- const add = (tool: Pick<DiscoveredTool, "name" | "package" | "source">, loaded: boolean) => {
115
- const provider = /^mcp__(.+?)__/.exec(tool.name)?.[1];
116
- const group = JSON.stringify([tool.package, provider ?? "", tool.source ?? ""]);
117
- const key = JSON.stringify([tool.name, tool.package]);
118
- if (!trusted.has(key)) trusted.set(key, { ...tool, kind: "trusted", loaded, group });
119
- };
120
- for (const tool of discovered) add(tool, true);
121
- for (const tool of settings?.subagentTools.trusted ?? []) add(tool, false);
122
- const groups = new Map<string, ToolGroup>();
123
- for (const tool of trusted.values()) {
124
- if (!groups.has(tool.group)) {
125
- const provider = JSON.parse(tool.group)[1] as string;
126
- const label = tool.source === "builtin" ? "built-in" : packageLabel(tool.package);
127
- groups.set(tool.group, { kind: "group", id: tool.group,
128
- label: provider ? `${provider} (${label})` : label, tools: [] });
129
- }
130
- groups.get(tool.group)!.tools.push(tool);
131
- }
132
- for (const group of groups.values()) group.tools.sort((a, b) => a.name.localeCompare(b.name));
133
- return [...groups.values()].sort((a, b) => a.label.localeCompare(b.label) || a.id.localeCompare(b.id));
134
- }
135
- function toolItems(): ToolItem[] {
136
- return [{ kind: "guarded", name: "apply_patch" }, ...toolGroups().flatMap((group): ToolItem[] =>
137
- [group, ...(expanded.has(group.id) ? group.tools : [])])];
138
- }
139
- const itemKey = (item: ToolItem) => item.kind === "group" ? item.id
140
- : item.kind === "guarded" ? "apply_patch" : JSON.stringify([item.name, item.package]);
141
- let items = toolItems();
142
- const lastRow = () => rows.length + items.length - 1;
143
111
  let row = 0;
144
112
  let column = 0;
145
113
  let busy = false;
@@ -153,21 +121,6 @@ export function createPermissionsPage(
153
121
  async function change(): Promise<void> {
154
122
  if (!settings || busy) return;
155
123
  const next = snapshot(settings);
156
- if (row >= rows.length) {
157
- const item = items[row - rows.length]!;
158
- if (item.kind === "guarded") next.subagentTools.applyPatch = !next.subagentTools.applyPatch;
159
- else if (item.kind === "group") {
160
- const all = item.tools.every(isTicked);
161
- for (const tool of item.tools) {
162
- if (all) next.subagentTools.trusted = next.subagentTools.trusted.filter((entry) =>
163
- !(entry.name === tool.name && entry.package === tool.package));
164
- else if (!isTicked(tool)) next.subagentTools.trusted.push({ name: tool.name, package: tool.package });
165
- }
166
- } else if (isTicked(item)) {
167
- next.subagentTools.trusted = next.subagentTools.trusted.filter((tool) => !(tool.name === item.name && tool.package === item.package));
168
- } else next.subagentTools.trusted.push({ name: item.name, package: item.package });
169
- return apply(next);
170
- }
171
124
  const key = rows[row]!.key;
172
125
  const profile = columns[column]!;
173
126
  if (key !== "enabled" && !settings[profile].enabled) return;
@@ -198,14 +151,7 @@ export function createPermissionsPage(
198
151
  busy = true;
199
152
  try {
200
153
  await handlers.change(snapshot(next));
201
- const selected = row >= rows.length ? items[row - rows.length] : undefined;
202
- const successors = selected ? items.slice(row - rows.length + 1).map(itemKey) : [];
203
154
  settings = next;
204
- items = toolItems();
205
- const index = selected ? items.findIndex((item) => itemKey(item) === itemKey(selected)) : -1;
206
- const successor = successors.map((key) => items.findIndex((item) => itemKey(item) === key)).find((at) => at >= 0);
207
- row = index >= 0 ? rows.length + index
208
- : successor !== undefined ? rows.length + successor : Math.min(row, lastRow());
209
155
  message = "";
210
156
  isError = false;
211
157
  requestRender();
@@ -238,46 +184,52 @@ export function createPermissionsPage(
238
184
  }
239
185
  }
240
186
 
241
- function fold(open?: boolean): void {
242
- const item = row >= rows.length ? items[row - rows.length] : undefined;
243
- const id = item?.kind === "group" ? item.id : item?.kind === "trusted" && open === false ? item.group : undefined;
244
- if (!id) return;
245
- if (open ?? !expanded.has(id)) expanded.add(id);
246
- else expanded.delete(id);
247
- items = toolItems();
248
- row = rows.length + items.findIndex((entry) => entry.kind === "group" && entry.id === id);
249
- requestRender();
250
- }
251
-
252
187
  return {
253
188
  invalidate() {},
254
189
  handleInput(data: string) {
255
190
  if (matchesKey(data, Key.escape)) {
256
191
  close();
192
+ } else if (matchesKey(data, Key.tab) || matchesKey(data, Key.shift("tab"))) {
193
+ section = section === "permissions" ? "loading" : "permissions";
194
+ if (section === "loading") {
195
+ loadingRows = readLoading();
196
+ loadingOffset = 0;
197
+ }
198
+ requestRender();
199
+ } else if (section === "loading") {
200
+ if (matchesKey(data, Key.up)) loadingOffset = Math.max(0, loadingOffset - 1);
201
+ else if (matchesKey(data, Key.down)) loadingOffset = Math.min(Math.max(0, loadingRows.length - loadingWindow), loadingOffset + 1);
202
+ else return;
203
+ requestRender();
257
204
  } else if (matchesKey(data, Key.up)) {
258
205
  row = Math.max(0, row - 1);
259
206
  requestRender();
260
207
  } else if (matchesKey(data, Key.down)) {
261
- row = Math.min(lastRow(), row + 1);
208
+ row = Math.min(rows.length - 1, row + 1);
262
209
  requestRender();
263
210
  } else if (matchesKey(data, Key.left)) {
264
- if (row >= rows.length) fold(false);
265
- else column = Math.max(0, column - 1);
211
+ column = Math.max(0, column - 1);
266
212
  requestRender();
267
213
  } else if (matchesKey(data, Key.right)) {
268
- if (row >= rows.length) fold(true);
269
- else column = Math.min(columns.length - 1, column + 1);
214
+ column = Math.min(columns.length - 1, column + 1);
270
215
  requestRender();
271
216
  } else if (matchesKey(data, Key.space)) {
272
217
  void change();
273
218
  } else if (matchesKey(data, "ctrl+s")) {
274
219
  void save();
275
- } else if (matchesKey(data, Key.enter)) {
276
- fold();
277
220
  }
278
221
  },
279
222
  render(width: number): string[] {
280
223
  const w = Math.max(0, Math.floor(width));
224
+ const activeTitle = section === "loading" ? "Tool loading" : "Use permissions";
225
+ const tabs = ["Tool loading", "Use permissions"]
226
+ .map(title => title === activeTitle ? theme.inverse(` ${title} `) : ` ${title} `).join(" ");
227
+ const heading = truncateToWidth((visibleWidth(tabs) <= w ? tabs : theme.inverse(activeTitle)) + " Tab switch", w, "");
228
+ if (section === "loading") {
229
+ return [heading, "", ...loadingRows.slice(loadingOffset, loadingOffset + loadingWindow),
230
+ "", "Role, tool list and exclusions determine each worker's tools.",
231
+ "↑↓ Scroll · Tab Use permissions · Esc Back"].map(text => truncateToWidth(text, w, ""));
232
+ }
281
233
  const prefix = w >= 20 ? 2 : 0;
282
234
  const gap = w >= 8 ? 1 : 0;
283
235
  const minimumCell = Math.max(1, Math.min(16, Math.floor((w - prefix - gap) / 4)));
@@ -297,7 +249,7 @@ export function createPermissionsPage(
297
249
  return highlight(theme.fg(selected ? "accent" : "text", marker + labelPart) + " ".repeat(gap) +
298
250
  cells.join(""), selected);
299
251
  };
300
- const output = [line("Sandbox permissions", ["Main", "Subagents", "Background tasks"], false), ""];
252
+ const output = [heading, "", line("Sandbox permissions", ["Main", "Subagents", "Background tasks"], false), ""];
301
253
  for (let i = 0; i < rows.length; i++) {
302
254
  const entry = rows[i]!;
303
255
  const value = (profile: PermissionProfile): string => {
@@ -318,42 +270,12 @@ export function createPermissionsPage(
318
270
  ((entry.key === "shell" || entry.key === "commandTimeoutSeconds") && !settings[profile].commands))));
319
271
  if (i === 0) output.push("");
320
272
  }
321
- // Subagents · Tools: which extension tools a confined subagent may use.
322
- output.push("", theme.fg("text", truncateToWidth(`${prefix ? " " : ""}Subagents · Tools`, w, "")));
323
- const toolNames = items.flatMap((item) => item.kind === "group" ? [] : [visibleWidth(item.name)]);
324
- const nameWidth = Math.min(24, Math.max(...toolNames), Math.max(0, w - prefix - 10));
325
- items.forEach((item, index) => {
326
- if (index === 0) output.push(theme.fg("dim", truncateToWidth(`${prefix ? " " : ""} Guarded (follows the file rules)`, w, "")));
327
- if (index === 1) output.push(theme.fg("dim", truncateToWidth(`${prefix ? " " : ""} Trusted (runs outside the file rules)`, w, "")));
328
- const selected = row === rows.length + index;
329
- let text: string;
330
- if (item.kind === "group") {
331
- const count = item.tools.filter(isTicked).length;
332
- const tick = count === item.tools.length ? "x" : count ? "-" : " ";
333
- text = ` ${expanded.has(item.id) ? "v" : ">"} [${tick}] ${item.label} ${count}/${item.tools.length}`;
334
- } else {
335
- const ticked = item.kind === "guarded" ? !!settings?.subagentTools.applyPatch : isTicked(item);
336
- const detail = item.kind === "guarded" ? "harness adapter" : [
337
- ...(isNetworkTool(item.name) ? ["needs Network On"] : []), ...(item.loaded ? [] : ["not loaded"])].join(" · ");
338
- text = `${item.kind === "guarded" ? " " : " "}[${ticked ? "x" : " "}] ${cell(item.name, nameWidth)} ${detail}`;
339
- }
340
- output.push(highlight(theme.fg(selected ? "accent" : settings ? "text" : "dim",
341
- truncateToWidth(`${prefix ? (selected ? "> " : " ") : ""}${text}`, w, "")), selected));
342
- });
343
- if (items.length === 1) {
344
- output.push(theme.fg("dim", truncateToWidth(`${prefix ? " " : ""} Trusted (runs outside the file rules)`, w, "")),
345
- theme.fg("dim", truncateToWidth(`${prefix ? " " : ""} No other extension tools are installed.`, w, "")));
346
- }
347
273
  output.push("");
348
- const selected = row < rows.length ? rows[row]!.key : undefined;
349
- const tool = row >= rows.length ? items[row - rows.length] : undefined;
350
- const contextual = tool ? (tool.kind === "guarded" ? GUARDED_HINT : TRUSTED_HINT)
351
- : selected && settings ? cellHint(selected, settings[columns[column]!], columns[column]) : undefined;
274
+ const contextual = settings ? cellHint(rows[row]!.key, settings[columns[column]!], columns[column]) : undefined;
352
275
  for (const hint of [
353
- "↑↓ Select · ←→ Column/fold · Space Toggle · ctrl+s Save default · Enter Fold · Esc Back",
276
+ "↑↓ Select · ←→ Column · Space Toggle · ctrl+s Save default · Esc Back",
354
277
  "Changes apply to new launches.",
355
278
  "Stored credentials: known files only; excludes OS vaults and environment tokens.",
356
- "Trusted tools run outside the file rules.",
357
279
  ...(contextual ? [contextual] : []),
358
280
  ]) output.push(theme.fg("dim", truncateToWidth(hint, w, "")));
359
281
  if (message) {
@@ -1,6 +1,6 @@
1
1
  // Generated fixed launch domain from packages/pi-better-sandbox/permissions.ts. Do not edit directly.
2
2
  /** Permission values are intent; launch backends must validate support before enforcement. */
3
- import { defaultSubagentTools, packageLabel, parseSubagentTools } from "./shared-task-tools.domain.mjs";
3
+ import { defaultSubagentTools, parseSubagentTools } from "./shared-task-tools.domain.mjs";
4
4
  /**
5
5
  * Return fresh profiles so changing one column never changes another.
6
6
  * All sandbox switches default to Off. Subagents retain Outside project = Write
@@ -71,11 +71,6 @@ export function describeLoosening(previous, next) {
71
71
  changes.push(`${label}: processAccess off → read`);
72
72
  }
73
73
  // A trusted tool runs outside the file rules: ticking one loosens the profile.
74
- for (const tool of next.subagentTools.trusted) {
75
- if (!previous.subagentTools.trusted.some((t) => t.name === tool.name && t.package === tool.package)) {
76
- changes.push(`Subagents: trusted tool ${tool.name} (${packageLabel(tool.package)}) runs outside the file rules`);
77
- }
78
- }
79
74
  return changes;
80
75
  }
81
76
  /** Strict decoding: malformed policy must not silently broaden permissions. */
@@ -1,5 +1,5 @@
1
1
  /** Permission values are intent; launch backends must validate support before enforcement. */
2
- import { defaultSubagentTools, packageLabel, parseSubagentTools, type SubagentToolSettings } from "./shared-task-tools.ts";
2
+ import { defaultSubagentTools, parseSubagentTools, type SubagentToolSettings } from "./shared-task-tools.ts";
3
3
  export type { SubagentToolSettings } from "./shared-task-tools.ts";
4
4
  /**
5
5
  * Project files / Outside project levels: Off, Read, Write (read, create and
@@ -98,11 +98,6 @@ export function describeLoosening(previous: SandboxPermissionSettings, next: San
98
98
  if (a.processAccess !== "read" && b.processAccess === "read") changes.push(`${label}: processAccess off → read`);
99
99
  }
100
100
  // A trusted tool runs outside the file rules: ticking one loosens the profile.
101
- for (const tool of next.subagentTools.trusted) {
102
- if (!previous.subagentTools.trusted.some((t) => t.name === tool.name && t.package === tool.package)) {
103
- changes.push(`Subagents: trusted tool ${tool.name} (${packageLabel(tool.package)}) runs outside the file rules`);
104
- }
105
- }
106
101
  return changes;
107
102
  }
108
103
 
@@ -69,7 +69,7 @@ export type SandboxPermissions = {
69
69
  */
70
70
  commandTimeoutSeconds?: number | null;
71
71
  network: boolean;
72
- /** Fixed process_list adapter only; omitted legacy profiles keep it Off. */
72
+ /** Fixed process adapters (inventory and Darwin identity compatibility); omitted legacy profiles keep it Off. */
73
73
  processAccess?: "off" | "read";
74
74
  };
75
75
 
@@ -18,6 +18,7 @@ import { pathToFileURL } from "node:url";
18
18
  import * as PiCodingAgent from "@earendil-works/pi-coding-agent";
19
19
  const { createLocalBashOperations, getShellConfig } = PiCodingAgent;
20
20
  import { directApplicationTarget, maybeBuildSandboxCommand, SHELL_EXECUTABLE_NAMES } from "./shared-sandbox-core.domain.mjs";
21
+ import { processIdentityDirectory } from "./shared-task-process-identity.domain.mjs";
21
22
  export function taskExecutionEnvironment(input) {
22
23
  const environment = { ...input };
23
24
  // The authenticated worker transport belongs to trusted Pi, not to its task commands.
@@ -250,6 +251,18 @@ export function createTaskExecutor(controller, shellPath = () => undefined, diag
250
251
  // Git inventory otherwise creates optional locks in an outside gitdir it cannot unlink (#419).
251
252
  const taskEnv = { GIT_OPTIONAL_LOCKS: "0", ...process.env, ...options.env,
252
253
  ...(scratch ? { TMPDIR: scratch, TMP: scratch, TEMP: scratch } : {}) };
254
+ if (options.signal?.aborted)
255
+ throw new Error("aborted");
256
+ const identityDirectory = await processIdentityDirectory(plan);
257
+ if (identityDirectory && JSON.stringify(controller.requireLaunchPlan()) !== JSON.stringify(plan)) {
258
+ throw new Error("Sandbox permissions changed while preparing process identity; retry the command.");
259
+ }
260
+ const executionPolicy = identityDirectory ? { ...plan.policy,
261
+ runtimeWrite: [...(plan.policy.runtimeWrite ?? []), identityDirectory],
262
+ denyWrite: [...(plan.policy.denyWrite ?? []), identityDirectory],
263
+ } : plan.policy;
264
+ if (identityDirectory)
265
+ taskEnv.PATH = `${identityDirectory}:${taskEnv.PATH ?? "/usr/bin:/bin"}`;
253
266
  // Resolve against the launch cwd, not the trusted Pi process cwd.
254
267
  const executable = target.kind === "argv" ? findExecutable(target.execPath, taskEnv, cwd) : undefined;
255
268
  if (target.kind === "argv" && !executable) {
@@ -276,7 +289,7 @@ export function createTaskExecutor(controller, shellPath = () => undefined, diag
276
289
  ? [shell.shell, ...shell.args, target.command]
277
290
  : [executable, ...target.execArgs];
278
291
  const wrapped = maybeBuildSandboxCommand({
279
- policy: plan.policy, profilePath,
292
+ policy: executionPolicy, profilePath,
280
293
  ...(target.kind === "shell"
281
294
  ? { execPath: "/usr/bin/env", execArgs: ["-i", "--", ...envArgs, ...targetArgs] }
282
295
  : { ...directApplicationTarget(executable, target.execArgs, taskEnv, permissions?.shell !== false),
@@ -18,6 +18,7 @@ import * as PiCodingAgent from "@earendil-works/pi-coding-agent";
18
18
  const { createLocalBashOperations, getShellConfig } = PiCodingAgent;
19
19
  import { directApplicationTarget, maybeBuildSandboxCommand, SHELL_EXECUTABLE_NAMES, type SandboxPermissions } from "./shared-sandbox-core.ts";
20
20
  import type { SandboxDiagnostics } from "./shared-sandbox-diagnostics.ts";
21
+ import { processIdentityDirectory } from "./shared-task-process-identity.ts";
21
22
  import type { TaskFileController } from "./shared-task-files.ts";
22
23
 
23
24
  export type TaskExecTarget =
@@ -271,6 +272,16 @@ export function createTaskExecutor(
271
272
  // Git inventory otherwise creates optional locks in an outside gitdir it cannot unlink (#419).
272
273
  const taskEnv: NodeJS.ProcessEnv = { GIT_OPTIONAL_LOCKS: "0", ...process.env, ...options.env,
273
274
  ...(scratch ? { TMPDIR: scratch, TMP: scratch, TEMP: scratch } : {}) };
275
+ if (options.signal?.aborted) throw new Error("aborted");
276
+ const identityDirectory = await processIdentityDirectory(plan);
277
+ if (identityDirectory && JSON.stringify(controller.requireLaunchPlan()) !== JSON.stringify(plan)) {
278
+ throw new Error("Sandbox permissions changed while preparing process identity; retry the command.");
279
+ }
280
+ const executionPolicy = identityDirectory ? { ...plan.policy,
281
+ runtimeWrite: [...(plan.policy.runtimeWrite ?? []), identityDirectory],
282
+ denyWrite: [...(plan.policy.denyWrite ?? []), identityDirectory],
283
+ } : plan.policy;
284
+ if (identityDirectory) taskEnv.PATH = `${identityDirectory}:${taskEnv.PATH ?? "/usr/bin:/bin"}`;
274
285
  // Resolve against the launch cwd, not the trusted Pi process cwd.
275
286
  const executable = target.kind === "argv" ? findExecutable(target.execPath, taskEnv, cwd) : undefined;
276
287
  if (target.kind === "argv" && !executable) {
@@ -296,7 +307,7 @@ export function createTaskExecutor(
296
307
  ? [shell!.shell, ...shell!.args, target.command]
297
308
  : [executable!, ...target.execArgs];
298
309
  const wrapped = maybeBuildSandboxCommand({
299
- policy: plan.policy, profilePath,
310
+ policy: executionPolicy, profilePath,
300
311
  ...(target.kind === "shell"
301
312
  ? { execPath: "/usr/bin/env", execArgs: ["-i", "--", ...envArgs, ...targetArgs] }
302
313
  : { ...directApplicationTarget(executable!, target.execArgs, taskEnv, permissions?.shell !== false),
@@ -0,0 +1,140 @@
1
+ // Generated fixed launch domain from packages/pi-better-sandbox/shared-task-process-identity.ts. Do not edit directly.
2
+ // Generated from packages/task-sandbox/process-identity.ts. Do not edit directly.
3
+ /** Darwin-only, fixed ps identity compatibility for confined task descendants. */
4
+ import { spawn } from "node:child_process";
5
+ import { createHash } from "node:crypto";
6
+ import { chmod, lstat, mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises";
7
+ import { dirname, join } from "node:path";
8
+ import { compileWritePolicy } from "./shared-sandbox-core.domain.mjs";
9
+ // This is trusted implementation source, never interpolated with task input.
10
+ const SOURCE = String.raw `
11
+ #include <libproc.h>
12
+ #include <sys/proc_info.h>
13
+ #include <unistd.h>
14
+ #include <errno.h>
15
+ #include <limits.h>
16
+ #include <stdio.h>
17
+ #include <stdlib.h>
18
+ #include <string.h>
19
+ #include <time.h>
20
+ static int refuse(const char *reason) {
21
+ fprintf(stderr, "Sandbox process identity: %s (errno=%d). Supported: ps -p PID -o lstart= -o comm=\n", reason, errno);
22
+ return 1;
23
+ }
24
+ int main(int argc, char **argv) {
25
+ if (argc != 7 || strcmp(argv[1], "-p") || strcmp(argv[3], "-o") ||
26
+ strcmp(argv[4], "lstart=") || strcmp(argv[5], "-o") || strcmp(argv[6], "comm=")) return refuse("unsupported arguments");
27
+ for (const char *p = argv[2]; *p; p++) if (*p < '0' || *p > '9') return refuse("invalid PID");
28
+ char *end; errno = 0;
29
+ long pid = strtol(argv[2], &end, 10);
30
+ if (errno || end == argv[2] || *end || pid <= 0 || pid > INT_MAX) return refuse("invalid PID");
31
+ struct proc_bsdinfo a = {0}, b = {0};
32
+ if (proc_pidinfo((int)pid, PROC_PIDTBSDINFO, 0, &a, sizeof a) != sizeof a) return refuse("identity unavailable");
33
+ if (a.pbi_uid != getuid() || a.pbi_ruid != getuid()) return refuse("different user");
34
+ if (a.pbi_pid != (unsigned int)pid || !a.pbi_start_tvsec || a.pbi_start_tvusec >= 1000000) return refuse("invalid identity");
35
+ char path[PROC_PIDPATHINFO_MAXSIZE] = {0}, confirmed[PROC_PIDPATHINFO_MAXSIZE] = {0};
36
+ if (proc_pidpath((int)pid, path, sizeof path) <= 0 || path[0] != '/') return refuse("path unavailable");
37
+ for (const unsigned char *p = (unsigned char *)path; *p; p++) if (*p < 32 || *p == 127) return refuse("invalid path");
38
+ if (proc_pidinfo((int)pid, PROC_PIDTBSDINFO, 0, &b, sizeof b) != sizeof b) return refuse("identity unavailable");
39
+ if (a.pbi_pid != b.pbi_pid || a.pbi_uid != b.pbi_uid || a.pbi_ruid != b.pbi_ruid || a.pbi_ppid != b.pbi_ppid ||
40
+ a.pbi_start_tvsec != b.pbi_start_tvsec || a.pbi_start_tvusec != b.pbi_start_tvusec) return refuse("identity changed");
41
+ if (proc_pidpath((int)pid, confirmed, sizeof confirmed) <= 0 || strcmp(path, confirmed)) return refuse("executable changed");
42
+ time_t seconds = (time_t)a.pbi_start_tvsec;
43
+ struct tm started; char timestamp[64];
44
+ if (!localtime_r(&seconds, &started) || !strftime(timestamp, sizeof timestamp, "%a %b %e %H:%M:%S %Y", &started)) return refuse("invalid start time");
45
+ printf("%-28s %s\n", timestamp, path);
46
+ return 0;
47
+ }
48
+ `;
49
+ const UNAVAILABLE = '#!/bin/sh\nprintf "%s\\n" "Sandbox process identity unavailable: trusted helper build failed; check Xcode Command Line Tools and restart the session. No unconfined ps fallback was used." >&2\nexit 126\n';
50
+ const helpers = new Map();
51
+ const digest = (bytes) => createHash("sha256").update(bytes).digest("hex");
52
+ // The trusted host compiles fixed source, with fixed argv and a minimal env.
53
+ // The resulting helper, not the compiler, runs as the task under Seatbelt.
54
+ async function compile(source, output) {
55
+ return new Promise((resolve, reject) => {
56
+ const child = spawn("/usr/bin/clang", ["-Wall", "-Wextra", "-Werror", "-O2", source, "-o", output], {
57
+ detached: true, shell: false, stdio: ["ignore", "pipe", "pipe"],
58
+ env: { PATH: "/usr/bin:/bin", HOME: "/var/empty", LC_ALL: "C" },
59
+ });
60
+ let failure;
61
+ let size = 0;
62
+ const stop = (error) => {
63
+ if (failure)
64
+ return;
65
+ failure = error;
66
+ if (child.pid)
67
+ try {
68
+ process.kill(-child.pid, "SIGKILL");
69
+ }
70
+ catch {
71
+ child.kill("SIGKILL");
72
+ }
73
+ };
74
+ const timer = setTimeout(() => stop(new Error("Process identity compiler timed out")), 15000);
75
+ for (const pipe of [child.stdout, child.stderr])
76
+ pipe.on("data", (chunk) => {
77
+ size += chunk.length;
78
+ if (size > 65536)
79
+ stop(new Error("Process identity compiler output exceeded limit"));
80
+ });
81
+ child.on("error", error => { failure ??= error; });
82
+ child.on("close", code => {
83
+ clearTimeout(timer);
84
+ if (failure || code !== 0)
85
+ reject(failure ?? new Error("Process identity compiler failed"));
86
+ else
87
+ resolve();
88
+ });
89
+ });
90
+ }
91
+ async function build(parent) {
92
+ const directory = await mkdtemp(join(parent, "process-identity-"));
93
+ const source = join(directory, "identity.c"), binary = join(directory, "ps");
94
+ try {
95
+ await writeFile(source, SOURCE, { mode: 0o600, flag: "wx" });
96
+ try {
97
+ await compile(source, binary);
98
+ }
99
+ catch {
100
+ // Preserve all other commands when the optional compiler is absent.
101
+ // Identity requests still fail explicitly, never via a broader ps.
102
+ await rm(binary, { force: true });
103
+ await writeFile(binary, UNAVAILABLE, { mode: 0o700, flag: "wx" });
104
+ }
105
+ await chmod(binary, 0o700);
106
+ return { directory, digest: digest(await readFile(binary)) };
107
+ }
108
+ catch (error) {
109
+ await rm(directory, { recursive: true, force: true });
110
+ throw error;
111
+ }
112
+ finally {
113
+ await rm(source, { force: true });
114
+ }
115
+ }
116
+ export async function processIdentityDirectory(plan) {
117
+ if (process.platform !== "darwin" || plan.policy.permissions?.processAccess !== "read")
118
+ return undefined;
119
+ const parent = await realpath(dirname(plan.profilePath));
120
+ // The controller's control directory must be protected even with broad writes.
121
+ const policy = compileWritePolicy(plan.policy);
122
+ if (!policy.denyWrite.some(root => parent === root || parent.startsWith(`${root}/`))) {
123
+ throw new Error("Sandbox process identity requires a task-write-protected control directory.");
124
+ }
125
+ let pending = helpers.get(parent);
126
+ if (!pending) {
127
+ pending = build(parent);
128
+ helpers.set(parent, pending);
129
+ void pending.catch(() => { if (helpers.get(parent) === pending)
130
+ helpers.delete(parent); });
131
+ }
132
+ const helper = await pending;
133
+ const binary = join(helper.directory, "ps");
134
+ const info = await lstat(binary);
135
+ if (!info.isFile() || info.uid !== process.getuid() || (info.mode & 0o7777) !== 0o700 ||
136
+ await realpath(helper.directory) !== helper.directory || digest(await readFile(binary)) !== helper.digest) {
137
+ throw new Error("Sandbox process identity helper changed; restart the session.");
138
+ }
139
+ return helper.directory;
140
+ }