harnery 0.41.0 → 0.42.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 (212) hide show
  1. package/dist/commander.js +3 -0
  2. package/dist/commands/agents.d.ts.map +1 -1
  3. package/dist/commands/agents.js +9 -1
  4. package/dist/commands/artifacts.d.ts.map +1 -1
  5. package/dist/commands/artifacts.js +113 -12
  6. package/dist/commands/browse.d.ts +164 -0
  7. package/dist/commands/browse.d.ts.map +1 -1
  8. package/dist/commands/browse.js +263 -51
  9. package/dist/commands/claude-desktop.d.ts.map +1 -1
  10. package/dist/commands/claude-desktop.js +52 -0
  11. package/dist/commands/disk.d.ts +6 -0
  12. package/dist/commands/disk.d.ts.map +1 -0
  13. package/dist/commands/disk.js +80 -0
  14. package/dist/commands/doctor.d.ts +8 -0
  15. package/dist/commands/doctor.d.ts.map +1 -1
  16. package/dist/commands/doctor.js +48 -1
  17. package/dist/commands/files.d.ts +16 -0
  18. package/dist/commands/files.d.ts.map +1 -1
  19. package/dist/commands/files.js +54 -2
  20. package/dist/commands/init.d.ts +2 -2
  21. package/dist/commands/init.d.ts.map +1 -1
  22. package/dist/commands/init.js +43 -9
  23. package/dist/commands/rm.d.ts +4 -0
  24. package/dist/commands/rm.d.ts.map +1 -0
  25. package/dist/commands/rm.js +87 -0
  26. package/dist/commands/servers.d.ts +7 -0
  27. package/dist/commands/servers.d.ts.map +1 -0
  28. package/dist/commands/servers.js +394 -0
  29. package/dist/commands/tunnel.d.ts.map +1 -1
  30. package/dist/commands/tunnel.js +82 -2
  31. package/dist/core/adapters/profiles.d.ts +9 -0
  32. package/dist/core/adapters/profiles.d.ts.map +1 -1
  33. package/dist/core/adapters/profiles.js +22 -1
  34. package/dist/core/adapters/types.d.ts +9 -0
  35. package/dist/core/adapters/types.d.ts.map +1 -1
  36. package/dist/core/agents/cli.js +13 -6
  37. package/dist/core/agents/render/session-context.d.ts.map +1 -1
  38. package/dist/core/agents/render/session-context.js +2 -0
  39. package/dist/core/agents/state/live-coordination-view.d.ts +20 -0
  40. package/dist/core/agents/state/live-coordination-view.d.ts.map +1 -1
  41. package/dist/core/agents/state/live-coordination-view.js +60 -0
  42. package/dist/core/artifacts/delivery-card.js +9 -2
  43. package/dist/core/artifacts/index.d.ts +140 -4
  44. package/dist/core/artifacts/index.d.ts.map +1 -1
  45. package/dist/core/artifacts/index.js +522 -49
  46. package/dist/core/config.d.ts +68 -11
  47. package/dist/core/config.d.ts.map +1 -1
  48. package/dist/core/config.js +128 -3
  49. package/dist/core/diagnostics/bundle.d.ts.map +1 -1
  50. package/dist/core/diagnostics/bundle.js +2 -2
  51. package/dist/core/events/v3/producers/recorder.d.ts.map +1 -1
  52. package/dist/core/events/v3/producers/recorder.js +16 -0
  53. package/dist/core/events/v3/projection.js +9 -1
  54. package/dist/core/hooks/adapter/events.d.ts +17 -0
  55. package/dist/core/hooks/adapter/events.d.ts.map +1 -1
  56. package/dist/core/hooks/adapter/events.js +5 -0
  57. package/dist/core/hooks/adapter/runtime-telemetry.js +3 -1
  58. package/dist/core/hooks/adapter/wiring.d.ts +37 -7
  59. package/dist/core/hooks/adapter/wiring.d.ts.map +1 -1
  60. package/dist/core/hooks/adapter/wiring.js +62 -4
  61. package/dist/core/hooks/cli.js +45 -6
  62. package/dist/core/hooks/run-markers.d.ts +37 -0
  63. package/dist/core/hooks/run-markers.d.ts.map +1 -0
  64. package/dist/core/hooks/run-markers.js +109 -0
  65. package/dist/core/servers/index.d.ts +211 -0
  66. package/dist/core/servers/index.d.ts.map +1 -0
  67. package/dist/core/servers/index.js +560 -0
  68. package/dist/core/servers/net.d.ts +58 -0
  69. package/dist/core/servers/net.d.ts.map +1 -0
  70. package/dist/core/servers/net.js +270 -0
  71. package/dist/core/servers/tunnels.d.ts +14 -0
  72. package/dist/core/servers/tunnels.d.ts.map +1 -0
  73. package/dist/core/servers/tunnels.js +33 -0
  74. package/dist/core/storage/builtins.js +1 -0
  75. package/dist/core/workflow/engine.d.ts.map +1 -1
  76. package/dist/core/workflow/engine.js +30 -1
  77. package/dist/core/workflow/sandbox-projection.d.ts +13 -2
  78. package/dist/core/workflow/sandbox-projection.d.ts.map +1 -1
  79. package/dist/core/workflow/sandbox-projection.js +23 -0
  80. package/dist/core/workflow/spawn-claude.d.ts.map +1 -1
  81. package/dist/core/workflow/spawn-claude.js +6 -1
  82. package/dist/core/workflow/spawn-codex.d.ts +2 -0
  83. package/dist/core/workflow/spawn-codex.d.ts.map +1 -1
  84. package/dist/core/workflow/spawn-codex.js +20 -1
  85. package/dist/core/workflow/spawn-cursor.d.ts.map +1 -1
  86. package/dist/core/workflow/spawn-cursor.js +6 -1
  87. package/dist/core/workflow/spawn-opencode.d.ts.map +1 -1
  88. package/dist/core/workflow/spawn-opencode.js +4 -1
  89. package/dist/core/workflow/types.d.ts +47 -2
  90. package/dist/core/workflow/types.d.ts.map +1 -1
  91. package/dist/core/workflow/worker-access.d.ts +92 -0
  92. package/dist/core/workflow/worker-access.d.ts.map +1 -0
  93. package/dist/core/workflow/worker-access.js +450 -0
  94. package/dist/lib/browser/batch-steps.d.ts +18 -0
  95. package/dist/lib/browser/batch-steps.d.ts.map +1 -0
  96. package/dist/lib/browser/batch-steps.js +82 -0
  97. package/dist/lib/browser/collect/collector.d.ts +99 -0
  98. package/dist/lib/browser/collect/collector.d.ts.map +1 -0
  99. package/dist/lib/browser/collect/collector.js +202 -0
  100. package/dist/lib/browser/collect/fields.d.ts +31 -0
  101. package/dist/lib/browser/collect/fields.d.ts.map +1 -0
  102. package/dist/lib/browser/collect/fields.js +75 -0
  103. package/dist/lib/browser/collect/index.d.ts +6 -0
  104. package/dist/lib/browser/collect/index.d.ts.map +1 -0
  105. package/dist/lib/browser/collect/index.js +5 -0
  106. package/dist/lib/browser/collect/page-driver.d.ts +14 -0
  107. package/dist/lib/browser/collect/page-driver.d.ts.map +1 -0
  108. package/dist/lib/browser/collect/page-driver.js +306 -0
  109. package/dist/lib/browser/collect/presets.d.ts +52 -0
  110. package/dist/lib/browser/collect/presets.d.ts.map +1 -0
  111. package/dist/lib/browser/collect/presets.js +176 -0
  112. package/dist/lib/browser/collect/scroll-plan.d.ts +85 -0
  113. package/dist/lib/browser/collect/scroll-plan.d.ts.map +1 -0
  114. package/dist/lib/browser/collect/scroll-plan.js +118 -0
  115. package/dist/lib/browser/index.d.ts +1 -1
  116. package/dist/lib/browser/index.d.ts.map +1 -1
  117. package/dist/lib/browser/page-review-judge.d.ts +2 -0
  118. package/dist/lib/browser/page-review-judge.d.ts.map +1 -1
  119. package/dist/lib/browser/page-review-judge.js +13 -0
  120. package/dist/lib/browser/qa-run-contracts.d.ts +10 -0
  121. package/dist/lib/browser/qa-run-contracts.d.ts.map +1 -1
  122. package/dist/lib/browser/qa-run.d.ts.map +1 -1
  123. package/dist/lib/browser/qa-run.js +1 -0
  124. package/dist/lib/browser/windows-chrome.d.ts +59 -0
  125. package/dist/lib/browser/windows-chrome.d.ts.map +1 -0
  126. package/dist/lib/browser/windows-chrome.js +179 -0
  127. package/dist/lib/claude-desktop-share.d.ts +136 -0
  128. package/dist/lib/claude-desktop-share.d.ts.map +1 -0
  129. package/dist/lib/claude-desktop-share.js +394 -0
  130. package/dist/lib/disk-usage.d.ts +50 -0
  131. package/dist/lib/disk-usage.d.ts.map +1 -0
  132. package/dist/lib/disk-usage.js +303 -0
  133. package/dist/lib/docs-lint.d.ts +6 -0
  134. package/dist/lib/docs-lint.d.ts.map +1 -1
  135. package/dist/lib/docs-lint.js +8 -3
  136. package/dist/lib/guarded-remove.d.ts +34 -0
  137. package/dist/lib/guarded-remove.d.ts.map +1 -0
  138. package/dist/lib/guarded-remove.js +310 -0
  139. package/dist/lib/instructions/templates.js +8 -8
  140. package/dist/lib/tunnel/error-page.d.ts +1 -1
  141. package/dist/lib/tunnel/error-page.d.ts.map +1 -1
  142. package/dist/lib/tunnel/error-page.js +19 -8
  143. package/dist/lib/tunnel/gate.js +20 -1
  144. package/dist/lib/tunnel/path-scope.d.ts +22 -0
  145. package/dist/lib/tunnel/path-scope.d.ts.map +1 -0
  146. package/dist/lib/tunnel/path-scope.js +62 -0
  147. package/dist/lib/tunnel/state.d.ts +5 -0
  148. package/dist/lib/tunnel/state.d.ts.map +1 -1
  149. package/dist/lib/tunnel/state.js +17 -3
  150. package/package.json +6 -1
  151. package/schemas/config.schema.json +91 -0
  152. package/src/commander.ts +19 -0
  153. package/src/commands/agents.ts +14 -0
  154. package/src/commands/artifacts.ts +171 -19
  155. package/src/commands/browse.ts +400 -57
  156. package/src/commands/claude-desktop.ts +61 -0
  157. package/src/commands/disk.ts +114 -0
  158. package/src/commands/doctor.ts +52 -1
  159. package/src/commands/files.ts +93 -2
  160. package/src/commands/init.ts +55 -5
  161. package/src/commands/rm.ts +115 -0
  162. package/src/commands/servers.ts +506 -0
  163. package/src/commands/tunnel.ts +102 -2
  164. package/src/core/adapters/profiles.ts +22 -1
  165. package/src/core/adapters/types.ts +10 -0
  166. package/src/core/agents/cli.ts +14 -6
  167. package/src/core/agents/render/session-context.ts +1 -0
  168. package/src/core/agents/state/live-coordination-view.ts +73 -0
  169. package/src/core/artifacts/delivery-card.ts +10 -2
  170. package/src/core/artifacts/index.ts +697 -44
  171. package/src/core/config.ts +183 -4
  172. package/src/core/diagnostics/bundle.ts +2 -1
  173. package/src/core/events/v3/producers/recorder.ts +16 -0
  174. package/src/core/events/v3/projection.ts +11 -1
  175. package/src/core/hooks/adapter/events.ts +19 -0
  176. package/src/core/hooks/adapter/runtime-telemetry.ts +3 -1
  177. package/src/core/hooks/adapter/wiring.ts +116 -8
  178. package/src/core/hooks/cli.ts +47 -6
  179. package/src/core/hooks/run-markers.ts +132 -0
  180. package/src/core/servers/index.ts +712 -0
  181. package/src/core/servers/net.ts +283 -0
  182. package/src/core/servers/tunnels.ts +39 -0
  183. package/src/core/storage/builtins.ts +1 -0
  184. package/src/core/workflow/engine.ts +38 -1
  185. package/src/core/workflow/sandbox-projection.ts +38 -2
  186. package/src/core/workflow/spawn-claude.ts +5 -1
  187. package/src/core/workflow/spawn-codex.ts +18 -1
  188. package/src/core/workflow/spawn-cursor.ts +5 -1
  189. package/src/core/workflow/spawn-opencode.ts +4 -1
  190. package/src/core/workflow/types.ts +62 -2
  191. package/src/core/workflow/worker-access.ts +525 -0
  192. package/src/lib/browser/batch-steps.ts +79 -0
  193. package/src/lib/browser/collect/collector.ts +306 -0
  194. package/src/lib/browser/collect/fields.ts +87 -0
  195. package/src/lib/browser/collect/index.ts +47 -0
  196. package/src/lib/browser/collect/page-driver.ts +327 -0
  197. package/src/lib/browser/collect/presets.ts +237 -0
  198. package/src/lib/browser/collect/scroll-plan.ts +179 -0
  199. package/src/lib/browser/index.ts +1 -0
  200. package/src/lib/browser/page-review-judge.ts +16 -0
  201. package/src/lib/browser/qa-run-contracts.ts +11 -0
  202. package/src/lib/browser/qa-run.ts +1 -0
  203. package/src/lib/browser/windows-chrome.ts +227 -0
  204. package/src/lib/claude-desktop-share.ts +511 -0
  205. package/src/lib/disk-usage.ts +347 -0
  206. package/src/lib/docs-lint.ts +8 -3
  207. package/src/lib/guarded-remove.ts +376 -0
  208. package/src/lib/instructions/templates.ts +8 -8
  209. package/src/lib/tunnel/error-page.ts +25 -9
  210. package/src/lib/tunnel/gate.ts +22 -1
  211. package/src/lib/tunnel/path-scope.ts +73 -0
  212. package/src/lib/tunnel/state.ts +20 -3
@@ -0,0 +1,525 @@
1
+ /**
2
+ * Decide, per launch, whether a workflow worker runs without its vendor sandbox
3
+ * (ADR 0192).
4
+ *
5
+ * A worker gets full access only when three independent things agree:
6
+ *
7
+ * 1. The host project enabled it. Harnery ships it off.
8
+ * 2. The session that launched the run can itself be shown to have full
9
+ * access. A sandboxed parent never hands more access to a child than it
10
+ * holds, and a parent whose access cannot be established counts as
11
+ * sandboxed.
12
+ * 3. The worker's model and effort meet a floor the host configured for that
13
+ * adapter.
14
+ *
15
+ * Every other case keeps the ordinary sandboxed projection, byte for byte. The
16
+ * decision is recorded on every launch, so a run states what each worker was
17
+ * allowed to do and why.
18
+ */
19
+
20
+ import {
21
+ closeSync,
22
+ existsSync,
23
+ openSync,
24
+ readdirSync,
25
+ readFileSync,
26
+ readSync,
27
+ statSync,
28
+ } from "node:fs";
29
+ import { homedir } from "node:os";
30
+ import { join } from "node:path";
31
+ import { builtinAdapterProfile } from "../adapters/profiles.ts";
32
+ import type { ParentAccessEvidence, SpawnFilesystemPolicy, WorkerAccessDecision } from "./types.ts";
33
+
34
+ /** One model an adapter's worker may run unsandboxed on. `minEffort` is on the
35
+ * adapter's declared effort scale; it is required for an adapter that has one
36
+ * and refused for an adapter that does not (whose effort lives in the model id). */
37
+ export interface WorkerFullAccessFloor {
38
+ model: string;
39
+ minEffort?: string;
40
+ }
41
+
42
+ export interface WorkerFullAccessPolicy {
43
+ enabled: boolean;
44
+ floors: Readonly<Record<string, readonly WorkerFullAccessFloor[]>>;
45
+ /** Set when the configured value could not be validated. An invalid policy
46
+ * is disabled as a whole rather than partially honored. */
47
+ invalid?: string;
48
+ }
49
+
50
+ export const DISABLED_WORKER_FULL_ACCESS: WorkerFullAccessPolicy = Object.freeze({
51
+ enabled: false,
52
+ floors: Object.freeze({}),
53
+ });
54
+
55
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
56
+ return typeof value === "object" && value !== null && !Array.isArray(value);
57
+ }
58
+
59
+ function invalid(message: string): WorkerFullAccessPolicy {
60
+ return { enabled: false, floors: {}, invalid: message };
61
+ }
62
+
63
+ /**
64
+ * Validate the raw `workflow.workerFullAccess` config value.
65
+ *
66
+ * Absent means disabled. Anything malformed disables the whole policy and says
67
+ * why, because honoring the valid half of a half-valid trust grant would hand
68
+ * out access the host never cleanly stated.
69
+ */
70
+ export function parseWorkerFullAccessPolicy(raw: unknown): WorkerFullAccessPolicy {
71
+ if (raw === undefined || raw === null) return DISABLED_WORKER_FULL_ACCESS;
72
+ if (!isPlainObject(raw)) return invalid("workflow.workerFullAccess must be an object");
73
+ for (const key of Object.keys(raw)) {
74
+ if (key !== "enabled" && key !== "floors") {
75
+ return invalid(`workflow.workerFullAccess has unknown key ${JSON.stringify(key)}`);
76
+ }
77
+ }
78
+ if (raw.enabled !== undefined && typeof raw.enabled !== "boolean") {
79
+ return invalid("workflow.workerFullAccess.enabled must be a boolean");
80
+ }
81
+ const floorsRaw = raw.floors ?? {};
82
+ if (!isPlainObject(floorsRaw))
83
+ return invalid("workflow.workerFullAccess.floors must be an object");
84
+ const floors: Record<string, WorkerFullAccessFloor[]> = {};
85
+ for (const [adapter, entries] of Object.entries(floorsRaw)) {
86
+ const profile = builtinAdapterProfile(adapter);
87
+ if (!profile) {
88
+ return invalid(
89
+ `workflow.workerFullAccess.floors names unknown adapter ${JSON.stringify(adapter)}`,
90
+ );
91
+ }
92
+ if (!Array.isArray(entries)) {
93
+ return invalid(`workflow.workerFullAccess.floors.${adapter} must be an array`);
94
+ }
95
+ const parsed: WorkerFullAccessFloor[] = [];
96
+ for (const entry of entries) {
97
+ if (!isPlainObject(entry)) {
98
+ return invalid(`workflow.workerFullAccess.floors.${adapter} entries must be objects`);
99
+ }
100
+ for (const key of Object.keys(entry)) {
101
+ if (key !== "model" && key !== "minEffort") {
102
+ return invalid(
103
+ `workflow.workerFullAccess.floors.${adapter} entry has unknown key ${JSON.stringify(key)}`,
104
+ );
105
+ }
106
+ }
107
+ const model = typeof entry.model === "string" ? entry.model.trim() : "";
108
+ if (!model) {
109
+ return invalid(`workflow.workerFullAccess.floors.${adapter} entry needs a model id`);
110
+ }
111
+ const minEffort = entry.minEffort;
112
+ if (profile.effortValues.length > 0) {
113
+ if (typeof minEffort !== "string" || !profile.effortValues.includes(minEffort)) {
114
+ return invalid(
115
+ `workflow.workerFullAccess.floors.${adapter} entry for ${model} needs minEffort, one of: ${profile.effortValues.join(", ")}`,
116
+ );
117
+ }
118
+ parsed.push({ model, minEffort });
119
+ } else {
120
+ if (minEffort !== undefined) {
121
+ return invalid(
122
+ `workflow.workerFullAccess.floors.${adapter} has no effort scale; name the exact model id instead of minEffort`,
123
+ );
124
+ }
125
+ parsed.push({ model });
126
+ }
127
+ }
128
+ floors[adapter] = parsed;
129
+ }
130
+ return { enabled: raw.enabled === true, floors };
131
+ }
132
+
133
+ export interface WorkerAccessInput {
134
+ adapter: string;
135
+ model?: string;
136
+ effort?: string;
137
+ policy: WorkerFullAccessPolicy;
138
+ /** The run's filesystem policy, if the host requested one. */
139
+ filesystemPolicy?: SpawnFilesystemPolicy;
140
+ /** Called at most when every cheaper condition already allows full access. */
141
+ parent: () => ParentAccessEvidence;
142
+ }
143
+
144
+ const sandboxed = (
145
+ reason: WorkerAccessDecision["reason"],
146
+ detail: string,
147
+ ): WorkerAccessDecision => ({
148
+ mode: "sandboxed",
149
+ reason,
150
+ detail,
151
+ });
152
+
153
+ /**
154
+ * The access decision for one launch. Conditions are checked from the host's
155
+ * own configuration outward, so the recorded reason names the first thing that
156
+ * kept the sandbox in place.
157
+ */
158
+ export function decideWorkerAccess(input: WorkerAccessInput): WorkerAccessDecision {
159
+ const { adapter, policy } = input;
160
+ if (policy.invalid) {
161
+ return sandboxed("config_invalid", `worker full access is off: ${policy.invalid}`);
162
+ }
163
+ if (!policy.enabled) {
164
+ return sandboxed("disabled", "the host has not enabled worker full access");
165
+ }
166
+ if (!builtinAdapterProfile(adapter)?.fullAccess) {
167
+ return sandboxed("adapter_unrepresentable", `${adapter} declares no full-access mode`);
168
+ }
169
+ if (input.filesystemPolicy?.mode === "read-only") {
170
+ // A read-only policy is a deliberate constraint on this run's children, not
171
+ // a sandbox limitation to route around.
172
+ return sandboxed("policy_read_only", "the run requested a read-only filesystem policy");
173
+ }
174
+ const floors = policy.floors[adapter] ?? [];
175
+ if (floors.length === 0) {
176
+ return sandboxed("model_not_listed", `no full-access floor is configured for ${adapter}`);
177
+ }
178
+ if (!input.model) {
179
+ return sandboxed(
180
+ "model_unset",
181
+ "the worker names no model, so the adapter default cannot be checked against a floor",
182
+ );
183
+ }
184
+ const matching = floors.filter((floor) => floor.model === input.model);
185
+ if (matching.length === 0) {
186
+ return sandboxed(
187
+ "model_not_listed",
188
+ `${input.model} is not on the ${adapter} full-access list`,
189
+ );
190
+ }
191
+ const scale = builtinAdapterProfile(adapter)?.effortValues ?? [];
192
+ if (scale.length > 0) {
193
+ if (!input.effort) {
194
+ return sandboxed(
195
+ "effort_unset",
196
+ `the worker names no effort, so ${input.model} cannot be checked against its floor`,
197
+ );
198
+ }
199
+ const rank = scale.indexOf(input.effort);
200
+ const floor = matching.find(
201
+ (entry) => entry.minEffort !== undefined && rank >= scale.indexOf(entry.minEffort),
202
+ );
203
+ if (rank < 0 || !floor) {
204
+ const needed = matching.map((entry) => entry.minEffort).join(" or ");
205
+ return sandboxed(
206
+ "effort_below_floor",
207
+ `${input.model} at effort ${input.effort} is below the ${needed} floor`,
208
+ );
209
+ }
210
+ }
211
+ const parent = input.parent();
212
+ if (parent.state === "sandboxed") {
213
+ return sandboxed("parent_sandboxed", `the launching session is sandboxed: ${parent.detail}`);
214
+ }
215
+ if (parent.state !== "full-access") {
216
+ return sandboxed(
217
+ "parent_unknown",
218
+ `the launching session's access could not be established: ${parent.detail}`,
219
+ );
220
+ }
221
+ const effortPart = input.effort ? ` at effort ${input.effort}` : "";
222
+ return {
223
+ mode: "full-access",
224
+ reason: "qualified",
225
+ detail: `${input.model}${effortPart} meets the ${adapter} floor and ${parent.detail}`,
226
+ };
227
+ }
228
+
229
+ // ---------------------------------------------------------------------------
230
+ // Parent access detection
231
+ // ---------------------------------------------------------------------------
232
+
233
+ export interface ParentAccessDeps {
234
+ env: Readonly<Record<string, string | undefined>>;
235
+ platform: NodeJS.Platform;
236
+ homeDir: string;
237
+ /** Contents of /proc/self/status, or null when unreadable. */
238
+ procStatus: () => string | null;
239
+ /** Windows user profile roots visible from a WSL guest. */
240
+ windowsUserRoots: () => string[];
241
+ }
242
+
243
+ function defaultDeps(): ParentAccessDeps {
244
+ return {
245
+ env: process.env,
246
+ platform: process.platform,
247
+ homeDir: homedir(),
248
+ procStatus: () => {
249
+ try {
250
+ return readFileSync("/proc/self/status", "utf8");
251
+ } catch {
252
+ return null;
253
+ }
254
+ },
255
+ windowsUserRoots: () => {
256
+ try {
257
+ return readdirSync("/mnt/c/Users").map((name) => join("/mnt/c/Users", name));
258
+ } catch {
259
+ return [];
260
+ }
261
+ },
262
+ };
263
+ }
264
+
265
+ const nonEmpty = (value: string | undefined): string | undefined => {
266
+ const trimmed = value?.trim();
267
+ return trimmed ? trimmed : undefined;
268
+ };
269
+
270
+ type Verdict = { state: ParentAccessEvidence["state"]; detail: string };
271
+
272
+ /**
273
+ * Establish whether the session that launched this process runs without a
274
+ * sandbox. Only positive evidence counts.
275
+ *
276
+ * Every adapter session marker in the environment has to prove full access on
277
+ * its own. A nested launch (one agent CLI inside another) inherits both
278
+ * markers, and the outer session's sandbox would still bind the inner one, so
279
+ * one sandboxed or unprovable marker is enough to keep workers sandboxed.
280
+ *
281
+ * - Process confinement is checked first. On Linux, the Codex and Claude Code
282
+ * sandboxes both set `no_new_privs`, and Codex also exports
283
+ * `CODEX_SANDBOX*` variables. Either one means this process is confined.
284
+ * - Codex: the thread's rollout file must show the latest turn ran under the
285
+ * `danger-full-access` sandbox policy.
286
+ * - Claude Code: the session transcript's latest permission mode must be
287
+ * `bypassPermissions`. Claude Code's Bash sandbox is covered by the Linux
288
+ * confinement check; on other platforms it cannot be ruled out, so a Claude
289
+ * Code parent there is unknown.
290
+ * - Cursor and OpenCode record no readable access state, so they are unknown.
291
+ */
292
+ export function detectParentAccess(deps: ParentAccessDeps = defaultDeps()): ParentAccessEvidence {
293
+ const env = deps.env;
294
+ const markers: Array<{ adapter: string; id: string }> = [];
295
+ const claudeId = nonEmpty(env.CLAUDE_CODE_SESSION_ID);
296
+ if (claudeId) markers.push({ adapter: "claude-code", id: claudeId });
297
+ const codexId = nonEmpty(env.CODEX_THREAD_ID);
298
+ if (codexId) markers.push({ adapter: "codex", id: codexId });
299
+ const cursorId = nonEmpty(env.CURSOR_SESSION_ID) ?? nonEmpty(env.CURSOR_CONVERSATION_ID);
300
+ if (cursorId) markers.push({ adapter: "cursor", id: cursorId });
301
+ const openCodeId = nonEmpty(env.OPENCODE_SESSION_ID);
302
+ if (openCodeId) markers.push({ adapter: "opencode", id: openCodeId });
303
+ const adapters = markers.map((marker) => marker.adapter);
304
+ const result = (verdict: Verdict): ParentAccessEvidence => ({ ...verdict, adapters });
305
+
306
+ if (markers.length === 0) {
307
+ return result({ state: "unknown", detail: "no adapter session marker is present" });
308
+ }
309
+ const sandboxVars = Object.keys(env).filter(
310
+ (key) => key.startsWith("CODEX_SANDBOX") && nonEmpty(env[key]),
311
+ );
312
+ if (sandboxVars.length > 0) {
313
+ return result({ state: "sandboxed", detail: `${sandboxVars.join(", ")} is set` });
314
+ }
315
+ let confinement: Verdict;
316
+ if (deps.platform === "linux") {
317
+ const status = deps.procStatus();
318
+ const match = status?.match(/^NoNewPrivs:\s*(\d)/m);
319
+ if (!match) {
320
+ return result({ state: "unknown", detail: "process confinement could not be read" });
321
+ }
322
+ if (match[1] !== "0") {
323
+ return result({ state: "sandboxed", detail: "this process runs with no_new_privs set" });
324
+ }
325
+ confinement = { state: "full-access", detail: "no_new_privs is clear" };
326
+ } else {
327
+ confinement = { state: "unknown", detail: `no confinement probe on ${deps.platform}` };
328
+ }
329
+
330
+ const verdicts: Verdict[] = [];
331
+ for (const marker of markers) {
332
+ if (marker.adapter === "codex") {
333
+ verdicts.push(codexParentAccess(marker.id, deps));
334
+ } else if (marker.adapter === "claude-code") {
335
+ if (confinement.state !== "full-access") {
336
+ verdicts.push({
337
+ state: "unknown",
338
+ detail: `Claude Code's Bash sandbox cannot be ruled out (${confinement.detail})`,
339
+ });
340
+ } else {
341
+ verdicts.push(claudeParentAccess(marker.id, deps));
342
+ }
343
+ } else {
344
+ verdicts.push({
345
+ state: "unknown",
346
+ detail: `${marker.adapter} records no readable access state`,
347
+ });
348
+ }
349
+ }
350
+ const sandboxedVerdict = verdicts.find((verdict) => verdict.state === "sandboxed");
351
+ if (sandboxedVerdict) return result(sandboxedVerdict);
352
+ const unknownVerdict = verdicts.find((verdict) => verdict.state === "unknown");
353
+ if (unknownVerdict) return result(unknownVerdict);
354
+ const details = verdicts.map((verdict) => verdict.detail);
355
+ if (confinement.state === "full-access") details.push(confinement.detail);
356
+ return result({ state: "full-access", detail: details.join("; ") });
357
+ }
358
+
359
+ /** The last line of `path` containing `needle`, reading backwards so a large
360
+ * session log is not loaded whole. Null when absent or past `maxBytes`. */
361
+ export function lastLineContaining(
362
+ path: string,
363
+ needle: string,
364
+ maxBytes = 256 * 1024 * 1024,
365
+ ): string | null {
366
+ let fd: number;
367
+ try {
368
+ fd = openSync(path, "r");
369
+ } catch {
370
+ return null;
371
+ }
372
+ try {
373
+ const size = statSync(path).size;
374
+ const chunkSize = 1024 * 1024;
375
+ const needleBytes = Buffer.from(needle);
376
+ let position = size;
377
+ let tail = Buffer.alloc(0);
378
+ while (position > 0 && size - position < maxBytes) {
379
+ const length = Math.min(chunkSize, position);
380
+ position -= length;
381
+ const chunk = Buffer.alloc(length);
382
+ readSync(fd, chunk, 0, length, position);
383
+ tail = Buffer.concat([chunk, tail]);
384
+ const hit = tail.lastIndexOf(needleBytes);
385
+ if (hit < 0) continue;
386
+ const start = tail.lastIndexOf(0x0a, hit);
387
+ if (start < 0 && position > 0) continue; // the line starts in an unread chunk
388
+ const end = tail.indexOf(0x0a, hit);
389
+ return tail.subarray(start + 1, end < 0 ? tail.length : end).toString("utf8");
390
+ }
391
+ return null;
392
+ } catch {
393
+ return null;
394
+ } finally {
395
+ closeSync(fd);
396
+ }
397
+ }
398
+
399
+ /** Candidate UTC dates (YYYY/MM/DD) for a UUIDv7 thread id: its creation day
400
+ * and the days either side, since rollout folders use the creator's local date. */
401
+ function rolloutDays(threadId: string): string[] | null {
402
+ const hex = threadId.replace(/-/g, "");
403
+ if (!/^[0-9a-f]{32}$/i.test(hex) || hex[12] !== "7") return null;
404
+ const ms = Number.parseInt(hex.slice(0, 12), 16);
405
+ const days: string[] = [];
406
+ for (const offset of [0, -1, 1]) {
407
+ const date = new Date(ms + offset * 86_400_000);
408
+ const y = date.getUTCFullYear();
409
+ const m = String(date.getUTCMonth() + 1).padStart(2, "0");
410
+ const d = String(date.getUTCDate()).padStart(2, "0");
411
+ days.push(`${y}/${m}/${d}`);
412
+ }
413
+ return days;
414
+ }
415
+
416
+ function codexHomes(deps: ParentAccessDeps): string[] {
417
+ const homes: string[] = [];
418
+ const explicit = nonEmpty(deps.env.CODEX_HOME);
419
+ if (explicit) homes.push(explicit);
420
+ homes.push(join(deps.homeDir, ".codex"));
421
+ // A Windows Codex session driving a WSL checkout keeps its rollouts in the
422
+ // Windows profile, which the guest sees under /mnt/c/Users.
423
+ if (deps.platform === "linux" && nonEmpty(deps.env.WSL_DISTRO_NAME)) {
424
+ for (const root of deps.windowsUserRoots()) homes.push(join(root, ".codex"));
425
+ }
426
+ return [...new Set(homes)];
427
+ }
428
+
429
+ function findCodexRollout(threadId: string, deps: ParentAccessDeps): string | null {
430
+ const days = rolloutDays(threadId);
431
+ if (!days) return null;
432
+ const suffix = `-${threadId}.jsonl`;
433
+ for (const home of codexHomes(deps)) {
434
+ for (const day of days) {
435
+ const dir = join(home, "sessions", day);
436
+ let names: string[];
437
+ try {
438
+ names = readdirSync(dir);
439
+ } catch {
440
+ continue;
441
+ }
442
+ const name = names.find((entry) => entry.startsWith("rollout-") && entry.endsWith(suffix));
443
+ if (name) return join(dir, name);
444
+ }
445
+ }
446
+ return null;
447
+ }
448
+
449
+ function codexParentAccess(threadId: string, deps: ParentAccessDeps): Verdict {
450
+ const rollout = findCodexRollout(threadId, deps);
451
+ if (!rollout) {
452
+ return { state: "unknown", detail: `no Codex rollout was found for thread ${threadId}` };
453
+ }
454
+ const line = lastLineContaining(rollout, '"type":"turn_context"');
455
+ if (!line) return { state: "unknown", detail: "the Codex rollout records no turn context" };
456
+ let policyType: unknown;
457
+ try {
458
+ const record = JSON.parse(line) as {
459
+ type?: unknown;
460
+ payload?: { sandbox_policy?: { type?: unknown } };
461
+ };
462
+ if (record.type !== "turn_context") {
463
+ return { state: "unknown", detail: "the Codex rollout's latest turn context is unreadable" };
464
+ }
465
+ policyType = record.payload?.sandbox_policy?.type;
466
+ } catch {
467
+ return { state: "unknown", detail: "the Codex rollout's latest turn context is unreadable" };
468
+ }
469
+ if (typeof policyType !== "string") {
470
+ return { state: "unknown", detail: "the Codex turn context names no sandbox policy" };
471
+ }
472
+ if (policyType === "danger-full-access") {
473
+ return {
474
+ state: "full-access",
475
+ detail: "the Codex parent's latest turn ran danger-full-access",
476
+ };
477
+ }
478
+ return { state: "sandboxed", detail: `the Codex parent's latest turn ran ${policyType}` };
479
+ }
480
+
481
+ function findClaudeTranscript(sessionId: string, deps: ParentAccessDeps): string | null {
482
+ if (!/^[A-Za-z0-9._-]+$/.test(sessionId)) return null;
483
+ const configDir = nonEmpty(deps.env.CLAUDE_CONFIG_DIR) ?? join(deps.homeDir, ".claude");
484
+ const projects = join(configDir, "projects");
485
+ let dirs: string[];
486
+ try {
487
+ dirs = readdirSync(projects);
488
+ } catch {
489
+ return null;
490
+ }
491
+ for (const dir of dirs) {
492
+ const candidate = join(projects, dir, `${sessionId}.jsonl`);
493
+ if (existsSync(candidate)) return candidate;
494
+ }
495
+ return null;
496
+ }
497
+
498
+ function claudeParentAccess(sessionId: string, deps: ParentAccessDeps): Verdict {
499
+ const transcript = findClaudeTranscript(sessionId, deps);
500
+ if (!transcript) {
501
+ return {
502
+ state: "unknown",
503
+ detail: `no Claude Code transcript was found for session ${sessionId}`,
504
+ };
505
+ }
506
+ const line = lastLineContaining(transcript, '"permissionMode":"');
507
+ if (!line)
508
+ return { state: "unknown", detail: "the Claude Code transcript records no permission mode" };
509
+ let mode: unknown;
510
+ try {
511
+ mode = (JSON.parse(line) as { permissionMode?: unknown }).permissionMode;
512
+ } catch {
513
+ return {
514
+ state: "unknown",
515
+ detail: "the Claude Code transcript's latest permission mode is unreadable",
516
+ };
517
+ }
518
+ if (mode === "bypassPermissions") {
519
+ return { state: "full-access", detail: "the Claude Code parent runs bypassPermissions" };
520
+ }
521
+ return {
522
+ state: "sandboxed",
523
+ detail: `the Claude Code parent runs ${typeof mode === "string" ? mode : "an unrecognized"} permission mode`,
524
+ };
525
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Split a `browse --batch` string into steps.
3
+ *
4
+ * Steps are separated by `;`. Two rules keep JavaScript intact:
5
+ *
6
+ * 1. A step that starts with the `eval` verb ends only at a `;` that sits
7
+ * outside JavaScript quotes ('...', "...", `...`) and outside (), [] and {}.
8
+ * So `eval (() => { const a = 1; return a })(); wait 500` is two steps.
9
+ * 2. Every other step ends at the next `;`, exactly as before. Selectors and
10
+ * fill values may contain apostrophes or brackets that are not balanced
11
+ * JavaScript, so they get no quote or bracket tracking.
12
+ *
13
+ * `\;` always inserts a literal `;` without ending the step, in any verb.
14
+ * A top-level `;` inside an eval (two bare statements) still ends the step:
15
+ * wrap multiple statements in a block or an arrow function.
16
+ */
17
+ export function splitBatchSteps(input: string): string[] {
18
+ const steps: string[] = [];
19
+ let buf = "";
20
+ let stepStart = true;
21
+ let jsAware = false;
22
+ let quote: string | null = null;
23
+ let depth = 0;
24
+
25
+ const endStep = () => {
26
+ if (buf.trim()) steps.push(buf);
27
+ buf = "";
28
+ stepStart = true;
29
+ jsAware = false;
30
+ quote = null;
31
+ depth = 0;
32
+ };
33
+
34
+ for (let i = 0; i < input.length; i++) {
35
+ if (stepStart) {
36
+ // Decide the splitting rule once per step from its leading verb.
37
+ jsAware = /^\s*eval(\s|$)/i.test(input.slice(i));
38
+ stepStart = false;
39
+ }
40
+ const ch = input[i] as string;
41
+ if (ch === "\\" && input[i + 1] === ";") {
42
+ buf += ";";
43
+ i++;
44
+ continue;
45
+ }
46
+ if (jsAware) {
47
+ if (quote) {
48
+ buf += ch;
49
+ if (ch === "\\" && i + 1 < input.length) {
50
+ buf += input[i + 1];
51
+ i++;
52
+ } else if (ch === quote) {
53
+ quote = null;
54
+ }
55
+ continue;
56
+ }
57
+ if (ch === "'" || ch === '"' || ch === "`") {
58
+ quote = ch;
59
+ buf += ch;
60
+ continue;
61
+ }
62
+ if (ch === "(" || ch === "[" || ch === "{") depth++;
63
+ else if (ch === ")" || ch === "]" || ch === "}") depth = Math.max(0, depth - 1);
64
+ if (ch === ";" && depth === 0) {
65
+ endStep();
66
+ continue;
67
+ }
68
+ buf += ch;
69
+ continue;
70
+ }
71
+ if (ch === ";") {
72
+ endStep();
73
+ continue;
74
+ }
75
+ buf += ch;
76
+ }
77
+ if (buf.trim()) steps.push(buf);
78
+ return steps;
79
+ }