typeclaw 0.45.1 → 0.46.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 (142) hide show
  1. package/README.md +1 -1
  2. package/package.json +2 -1
  3. package/src/agent/git-nudge.ts +2 -1
  4. package/src/agent/index.ts +44 -30
  5. package/src/agent/live-subagents.ts +18 -0
  6. package/src/agent/multimodal/index.ts +1 -1
  7. package/src/agent/multimodal/look-at.ts +78 -44
  8. package/src/agent/multimodal/looker.ts +151 -39
  9. package/src/agent/network/response-body.ts +26 -0
  10. package/src/agent/network/safe-http.ts +198 -0
  11. package/src/agent/plugin-tools.ts +379 -157
  12. package/src/agent/provider-error.ts +52 -1
  13. package/src/agent/restart/index.ts +61 -40
  14. package/src/agent/restart-handoff/index.ts +73 -4
  15. package/src/agent/reviewer-bash-policy.ts +42 -1
  16. package/src/agent/session-origin.ts +2 -0
  17. package/src/agent/subagent-drain.ts +117 -7
  18. package/src/agent/subagents.ts +49 -16
  19. package/src/agent/throttle-circuit.ts +25 -5
  20. package/src/agent/tool-error-remediation.ts +72 -0
  21. package/src/agent/tool-file-safety.ts +1050 -0
  22. package/src/agent/tools/channel-fetch-attachment.ts +10 -3
  23. package/src/agent/tools/ddg.ts +16 -2
  24. package/src/agent/tools/post-github-review.ts +199 -0
  25. package/src/agent/tools/spawn-subagent.ts +21 -18
  26. package/src/agent/tools/webfetch/fetch.ts +143 -183
  27. package/src/agent/tools/webfetch/tool.ts +2 -3
  28. package/src/agent/tools/websearch.ts +23 -2
  29. package/src/agent/tools-without-local-file-operands.ts +27 -0
  30. package/src/agent/turn-runner.ts +86 -6
  31. package/src/bundled-plugins/backup/index.ts +2 -1
  32. package/src/bundled-plugins/backup/runner.ts +2 -1
  33. package/src/bundled-plugins/doc-render/render.ts +93 -12
  34. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  35. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  36. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  37. package/src/bundled-plugins/github-cli-auth/index.ts +131 -135
  38. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  39. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  40. package/src/bundled-plugins/memory/README.md +23 -11
  41. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  42. package/src/bundled-plugins/memory/citations.ts +22 -9
  43. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  44. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  45. package/src/bundled-plugins/memory/index.ts +0 -4
  46. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  47. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  48. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  49. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  50. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  51. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  52. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  53. package/src/bundled-plugins/researcher/write-report.ts +6 -3
  54. package/src/bundled-plugins/reviewer/index.ts +2 -2
  55. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  56. package/src/bundled-plugins/reviewer/skills/code-review.ts +19 -9
  57. package/src/bundled-plugins/scout/scout.ts +8 -0
  58. package/src/bundled-plugins/security/index.ts +4 -4
  59. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  60. package/src/bundled-plugins/security/policies/private-surface-read.ts +220 -29
  61. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  62. package/src/bundled-plugins/security/policies/ssrf.ts +29 -9
  63. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  64. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  65. package/src/channels/adapters/discord-bot.ts +66 -6
  66. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  67. package/src/channels/adapters/discord-id.ts +4 -0
  68. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  69. package/src/channels/adapters/discord.ts +57 -7
  70. package/src/channels/adapters/github/auth-app.ts +41 -12
  71. package/src/channels/adapters/github/index.ts +23 -11
  72. package/src/channels/adapters/github/review-submitter.ts +302 -0
  73. package/src/channels/adapters/kakaotalk-channel-resolver.ts +5 -3
  74. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  75. package/src/channels/adapters/kakaotalk-typing.ts +17 -15
  76. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  77. package/src/channels/adapters/slack-bot.ts +19 -8
  78. package/src/channels/adapters/slack-classify.ts +21 -2
  79. package/src/channels/adapters/slack.ts +59 -7
  80. package/src/channels/adapters/telegram-bot.ts +18 -5
  81. package/src/channels/adapters/webex-bot.ts +8 -3
  82. package/src/channels/adapters/webex.ts +8 -3
  83. package/src/channels/fetch-attachment.ts +43 -0
  84. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  85. package/src/channels/github-token-bridge.ts +10 -3
  86. package/src/channels/manager.ts +9 -0
  87. package/src/channels/router.ts +248 -6
  88. package/src/channels/types.ts +28 -1
  89. package/src/cli/channel.ts +1 -1
  90. package/src/cli/init.ts +1 -1
  91. package/src/cli/model.ts +57 -7
  92. package/src/compose/stop.ts +17 -5
  93. package/src/config/config.ts +6 -6
  94. package/src/config/models-mutation.ts +13 -1
  95. package/src/config/providers.ts +176 -0
  96. package/src/container/start.ts +49 -10
  97. package/src/doctor/checks.ts +3 -1
  98. package/src/doctor/commit.ts +2 -1
  99. package/src/doctor/file-ownership.ts +52 -0
  100. package/src/dreams/git.ts +2 -1
  101. package/src/git/hookless.ts +5 -0
  102. package/src/git/reconcile-ignored.ts +18 -5
  103. package/src/git/secret-history.ts +371 -0
  104. package/src/git/system-commit.ts +12 -6
  105. package/src/init/dockerfile.ts +86 -5
  106. package/src/init/index.ts +17 -5
  107. package/src/init/models-dev.ts +4 -0
  108. package/src/init/validate-api-key.ts +2 -0
  109. package/src/mcp/tools.ts +16 -3
  110. package/src/permissions/builtins.ts +3 -1
  111. package/src/plugin/context.ts +2 -0
  112. package/src/plugin/index.ts +1 -0
  113. package/src/plugin/manager.ts +4 -0
  114. package/src/plugin/types.ts +21 -0
  115. package/src/run/index.ts +40 -0
  116. package/src/run/llm-fetch-observer.ts +41 -4
  117. package/src/sandbox/build.ts +37 -15
  118. package/src/sandbox/canonical-secrets.ts +18 -0
  119. package/src/sandbox/env-exposure.ts +80 -0
  120. package/src/sandbox/errors.ts +13 -6
  121. package/src/sandbox/hidden-paths.ts +102 -44
  122. package/src/sandbox/index.ts +22 -4
  123. package/src/sandbox/package-install.ts +3 -27
  124. package/src/sandbox/policy.ts +11 -25
  125. package/src/sandbox/privileged-runtime.ts +255 -0
  126. package/src/sandbox/session-tmp.ts +8 -2
  127. package/src/sandbox/writable-zones.ts +204 -140
  128. package/src/secrets/index.ts +8 -0
  129. package/src/secrets/refresh-provider-oauth.ts +128 -0
  130. package/src/server/command-runner.ts +48 -4
  131. package/src/server/index.ts +4 -0
  132. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  133. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  134. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  135. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  136. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  137. package/src/skills/typeclaw-config/SKILL.md +5 -5
  138. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  139. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  140. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  141. package/src/skills/typeclaw-permissions/SKILL.md +19 -15
  142. package/typeclaw.schema.json +20 -0
@@ -1,4 +1,5 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks'
2
+ import { mkdir } from 'node:fs/promises'
2
3
  import { join } from 'node:path'
3
4
 
4
5
  import {
@@ -23,6 +24,8 @@ import {
23
24
  checkSkillAuthoringGuard,
24
25
  } from '@/bundled-plugins/guard/policy'
25
26
  import { config, getSandboxWritablePathSpecs } from '@/config/config'
27
+ import { assertNoCanonicalSecretsInGit } from '@/git/secret-history'
28
+ import { readEnvFile } from '@/init/env-file'
26
29
  import type { PermissionService } from '@/permissions/permissions'
27
30
  import type {
28
31
  BuiltinToolRef,
@@ -36,31 +39,39 @@ import type {
36
39
  } from '@/plugin'
37
40
  import {
38
41
  buildSandboxedCommand,
42
+ canWriteAgentRootInSandbox,
39
43
  canMountRealProc,
44
+ cleanupPrivilegedSandboxRuntime,
40
45
  commandNeedsRealProc,
41
46
  DEFAULT_SANDBOX_ENV,
42
47
  ensureBwrapAvailable,
43
48
  ensureHiddenMaskTargets,
44
49
  ensureSessionTmpDir,
45
50
  getProcBindSafetyVerdict,
46
- isPackageInstallCommand,
51
+ isGitControlPath,
47
52
  mapVirtualTmpPath,
48
53
  resolveHiddenPaths,
49
- resolvePackageInstallZones,
54
+ resolvePrivilegedSandboxRuntime,
50
55
  resolveProcBindSafetyWithRetry,
51
56
  resolveProcSelfExe,
52
57
  resolveProtectedZones,
53
58
  resolveSandboxSymlinks,
54
59
  resolveWritableZones,
60
+ SandboxPolicyError,
55
61
  SandboxDegradedProcError,
56
62
  SandboxProcProbeUnverifiedError,
57
63
  subtractMasked,
64
+ verifyHiddenMaskTargets,
65
+ verifyPrivilegedSandboxRuntime,
58
66
  } from '@/sandbox'
67
+ import { resolveExposableEnvNames } from '@/sandbox/env-exposure'
59
68
 
60
69
  import { createLoopGuard, type LoopGuard, type LoopGuardDecision } from './loop-guard'
61
70
  import { checkImageReadRedirect } from './multimodal/read-redirect'
62
71
  import { enforceSubagentBashPolicy, type SubagentBashPolicy } from './reviewer-bash-policy'
63
72
  import type { SessionOrigin } from './session-origin'
73
+ import { remediateToolErrorMessage } from './tool-error-remediation'
74
+ import { enforceAndPinToolFiles, writeToolOutputNoFollow } from './tool-file-safety'
64
75
  import { SUBAGENT_OUTPUT_TOOL_NAME, type SubagentOutputToolDetails } from './tools/subagent-output'
65
76
  import { webFetchTool } from './tools/webfetch'
66
77
  import { webSearchTool } from './tools/websearch'
@@ -76,15 +87,36 @@ let sharedLoopGuard: LoopGuard = createLoopGuard()
76
87
  // a bash call's args to inject env vars into the spawned process WITHOUT
77
88
  // putting them in the command string (where they would leak through logs and
78
89
  // later hooks). The wrapper extracts and deletes it before the bash tool runs,
79
- // then threads it to the spawn (non-sandboxed) and to bwrap --setenv
80
- // (sandboxed). Used by github-cli-auth to inject a per-repo GH_TOKEN. The key
90
+ // then threads it to the spawn. Sandboxed secret values stay in bwrap's parent
91
+ // environment and are inherited by name rather than rendered into argv. Used
92
+ // by github-cli-auth to inject a per-repo GH_TOKEN. The key
81
93
  // is stripped from client-supplied args before tool.before so only trusted
82
94
  // hooks can set it.
83
95
  export const TYPECLAW_INTERNAL_BASH_ENV = '__typeclawBashEnv'
84
96
 
85
97
  type BashEnvOverlay = Record<string, string>
98
+ const SECRET_BASH_ENV_NAMES = new Set(['GH_TOKEN', 'GITHUB_TOKEN'])
99
+
100
+ // Transport classifier for the TRUSTED hook-injected overlay only (e.g.
101
+ // github-cli-auth's per-repo GH_TOKEN). Token/secret-shaped names use `inherit`
102
+ // so their value never renders into the bwrap argv; plain names (GH_REPO) go
103
+ // via `set`. This is NOT a .env exposure filter — the overlay is populated by
104
+ // trusted runtime hooks, not operator .env.
105
+ const OVERLAY_SECRET_NAME_PATTERN = /(?:^|_)(?:TOKEN|SECRET|PASSWORD|API_KEY|PRIVATE_KEY|AUTH)$/i
106
+ function isOverlaySecretName(name: string): boolean {
107
+ return SECRET_BASH_ENV_NAMES.has(name) || OVERLAY_SECRET_NAME_PATTERN.test(name)
108
+ }
109
+
110
+ type BashSpawnEnvContext = {
111
+ overlay?: BashEnvOverlay
112
+ // Exact env for the outer bwrap process on a sandboxed call. When present, the
113
+ // spawn hook uses it verbatim rather than the live inherited env, so a secret
114
+ // that appears in process.env between policy build and spawn stays out of the
115
+ // sandbox (closes the inherit TOCTOU).
116
+ sandboxSpawnEnv?: Record<string, string>
117
+ }
86
118
 
87
- const bashEnvStore = new AsyncLocalStorage<BashEnvOverlay | undefined>()
119
+ const bashEnvStore = new AsyncLocalStorage<BashSpawnEnvContext | undefined>()
88
120
 
89
121
  function readBashEnvOverlay(args: Record<string, unknown>): BashEnvOverlay | undefined {
90
122
  const raw = args[TYPECLAW_INTERNAL_BASH_ENV]
@@ -97,9 +129,19 @@ function readBashEnvOverlay(args: Record<string, unknown>): BashEnvOverlay | und
97
129
  }
98
130
 
99
131
  function bashSpawnHookWithOverlay(context: BashSpawnContext): BashSpawnContext {
100
- const overlay = bashEnvStore.getStore()
101
- if (overlay === undefined) return context
102
- return { ...context, env: { ...context.env, ...overlay } }
132
+ const store = bashEnvStore.getStore()
133
+ if (store?.sandboxSpawnEnv !== undefined) return { ...context, env: { ...store.sandboxSpawnEnv } }
134
+ return { ...context, env: sanitizeBashSpawnEnvironment(context.env, store?.overlay) }
135
+ }
136
+
137
+ export function sanitizeBashSpawnEnvironment(
138
+ inherited: NodeJS.ProcessEnv | undefined,
139
+ overlay: BashEnvOverlay | undefined,
140
+ ): NodeJS.ProcessEnv {
141
+ const env = { ...inherited }
142
+ for (const name of SECRET_BASH_ENV_NAMES) delete env[name]
143
+ if (overlay !== undefined) Object.assign(env, overlay)
144
+ return env
103
145
  }
104
146
 
105
147
  const ACKNOWLEDGE_GUARDS_SCHEMA = Type.Optional(
@@ -149,7 +191,14 @@ function createPiBuiltinToolDefinition(name: PiBuiltinToolName, cwd: string): To
149
191
  case 'edit':
150
192
  return piCreateEditToolDefinition(cwd)
151
193
  case 'write':
152
- return piCreateWriteToolDefinition(cwd)
194
+ return piCreateWriteToolDefinition(cwd, {
195
+ operations: {
196
+ mkdir: async (dir) => {
197
+ await mkdir(dir, { recursive: true })
198
+ },
199
+ writeFile: writeToolOutputNoFollow,
200
+ },
201
+ })
153
202
  case 'grep':
154
203
  return piCreateGrepToolDefinition(cwd)
155
204
  case 'find':
@@ -196,6 +245,7 @@ export type WrapToolOptions = {
196
245
  // origin mutates per turn surface the current-turn `lastInboundAuthorId`
197
246
  // to `tool.before`. Sessions with a fixed origin can pass `() => origin`.
198
247
  getOrigin?: () => SessionOrigin | undefined
248
+ permissions?: PermissionService
199
249
  // Resolves the current turn's abort handle. Resolved lazily (not at wrap
200
250
  // time) because tools are wrapped BEFORE `createAgentSession` returns the
201
251
  // session whose `agent.abort` this points at. See `fireLoopAbort`.
@@ -203,6 +253,19 @@ export type WrapToolOptions = {
203
253
  getLoopGuardTurn?: () => number | undefined
204
254
  }
205
255
 
256
+ export type BashSandboxBoundary = {
257
+ ensureAvailable: () => Promise<void>
258
+ buildCommand: typeof buildSandboxedCommand
259
+ resolveRuntime?: typeof resolvePrivilegedSandboxRuntime
260
+ verifyRuntime?: typeof verifyPrivilegedSandboxRuntime
261
+ cleanupRuntime?: typeof cleanupPrivilegedSandboxRuntime
262
+ }
263
+
264
+ const DEFAULT_BASH_SANDBOX_BOUNDARY: BashSandboxBoundary = {
265
+ ensureAvailable: ensureBwrapAvailable,
266
+ buildCommand: buildSandboxedCommand,
267
+ }
268
+
206
269
  export type WrapSystemToolOptions = {
207
270
  agentDir: string
208
271
  sessionId: string
@@ -211,15 +274,17 @@ export type WrapSystemToolOptions = {
211
274
  getAbort?: () => ((reason?: string) => void) | undefined
212
275
  getLoopGuardTurn?: () => number | undefined
213
276
  // When present, the bash builtin is rewritten through the per-tool bwrap
214
- // sandbox with role-derived path masks. Absent (or no masks for the role)
215
- // runs bash unchanged — preserving today's behavior for trusted+ and for
216
- // sessions wired without a permission service (e.g. tests).
277
+ // sandbox. Private-directory masks remain role-derived; canonical agent
278
+ // secret-file masks apply to every role. Only sessions wired without a
279
+ // permission service fail closed before execution. Production session setup
280
+ // always supplies either the live service or the deny-all service.
217
281
  permissions?: PermissionService
218
282
  // Per-subagent bash capability policy, enforced as a hard pre-check BEFORE
219
- // the role-derived sandbox (which returns early for trusted/owner). Lets a
220
- // read-only subagent keep its bash read-only no matter who spawned it. See
283
+ // the role-derived sandbox. Lets a read-only subagent keep its bash read-only
284
+ // no matter who spawned it. See
221
285
  // `src/agent/reviewer-bash-policy.ts`.
222
286
  bashPolicy?: SubagentBashPolicy
287
+ bashSandboxBoundary?: BashSandboxBoundary
223
288
  }
224
289
 
225
290
  // Zod 4 emits a top-level `"$schema": "https://json-schema.org/draft/2020-12/schema"`
@@ -265,6 +330,7 @@ export function wrapPluginTool(tool: Tool<any>, opts: WrapToolOptions): ToolDefi
265
330
  callId: toolCallId,
266
331
  args: mutableArgs,
267
332
  ...(liveOrigin !== undefined ? { origin: liveOrigin } : {}),
333
+ ...(tool.fileOperands !== undefined ? { fileOperands: tool.fileOperands } : {}),
268
334
  }
269
335
  const blockResult = await opts.hooks.runToolBefore(before)
270
336
  if (blockResult !== undefined) {
@@ -290,13 +356,37 @@ export function wrapPluginTool(tool: Tool<any>, opts: WrapToolOptions): ToolDefi
290
356
  logger: opts.logger,
291
357
  }
292
358
 
293
- let result: ToolResult
359
+ let result: ToolResult | undefined
360
+ let executionError: unknown
361
+ let cleanupError: unknown
362
+ const pinnedFiles = await enforceAndPinToolFiles({
363
+ tool: opts.toolName,
364
+ args: before.args,
365
+ agentDir: opts.agentDir,
366
+ genericInputs: true,
367
+ fileOperands: tool.fileOperands,
368
+ signal,
369
+ })
294
370
  try {
295
371
  result = await tool.execute(before.args, toolCtx)
296
372
  } catch (err) {
297
- const message = err instanceof Error ? err.message : String(err)
298
- return errorResult(message)
373
+ executionError = err
374
+ } finally {
375
+ try {
376
+ await pinnedFiles.cleanup()
377
+ } catch (error) {
378
+ cleanupError = error
379
+ }
380
+ }
381
+ const finalError = executionError ?? cleanupError
382
+ if (finalError !== undefined) {
383
+ const failure = errorResult(finalError instanceof Error ? finalError.message : String(finalError))
384
+ await runToolAfterSafely(opts, opts.toolName, toolCallId, failure)
385
+ if (cleanupError !== undefined) throw finalError
386
+ return failure
299
387
  }
388
+ if (result === undefined) throw new Error('plugin tool execution returned no result')
389
+ result = pinnedFiles.restoreResult(result)
300
390
 
301
391
  const resolved = loopGate.resolve(result)
302
392
  if ('deferredBlock' in resolved) {
@@ -329,6 +419,7 @@ export function wrapSystemTool<TParams extends TSchema, TDetails = unknown, TSta
329
419
  parameters: withGuardAcknowledgements(tool.name, tool.parameters),
330
420
  async execute(toolCallId, params, signal, onUpdate, ctx) {
331
421
  const mutableArgs = params as Record<string, unknown>
422
+ normalizeDefaultTreeRoot(tool.name, mutableArgs)
332
423
  const liveOrigin = opts.getOrigin?.()
333
424
  const blockResult = await opts.hooks.runToolBefore({
334
425
  tool: tool.name,
@@ -359,8 +450,41 @@ export function wrapSystemTool<TParams extends TSchema, TDetails = unknown, TSta
359
450
  }
360
451
  stripGuardAcknowledgements(mutableArgs)
361
452
 
362
- const result = await tool.execute(toolCallId, mutableArgs as Static<TParams>, signal, onUpdate, ctx)
363
- const resolved = loopGate.resolve({ content: result.content as ContentPart[], details: result.details })
453
+ const pinnedFiles = await enforceAndPinToolFiles({
454
+ tool: tool.name,
455
+ args: mutableArgs,
456
+ agentDir: opts.agentDir,
457
+ genericInputs: tool.name !== 'mcp_call',
458
+ ...(opts.permissions !== undefined
459
+ ? { hidden: resolveHiddenPaths(opts.permissions, liveOrigin, opts.agentDir) }
460
+ : {}),
461
+ signal,
462
+ })
463
+ let result: Awaited<ReturnType<typeof tool.execute>> | undefined
464
+ let executionError: unknown
465
+ let cleanupError: unknown
466
+ try {
467
+ result = await tool.execute(toolCallId, mutableArgs as Static<TParams>, signal, onUpdate, ctx)
468
+ } catch (error) {
469
+ executionError = error
470
+ } finally {
471
+ try {
472
+ await pinnedFiles.cleanup()
473
+ } catch (error) {
474
+ cleanupError = error
475
+ }
476
+ }
477
+ const finalError = executionError ?? cleanupError
478
+ if (finalError !== undefined) {
479
+ await runToolAfterSafely(opts, tool.name, toolCallId, toErrorResult(finalError))
480
+ throw finalError
481
+ }
482
+ if (result === undefined) throw new Error('system tool execution returned no result')
483
+ const restoredResult = pinnedFiles.restoreResult({
484
+ content: result.content as ContentPart[],
485
+ details: result.details,
486
+ })
487
+ const resolved = loopGate.resolve(restoredResult)
364
488
  if ('deferredBlock' in resolved) {
365
489
  fireLoopAbort(opts.getAbort, 'loop_guard:deferred_block')
366
490
  throw new Error(resolved.deferredBlock)
@@ -395,6 +519,7 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
395
519
  parameters: withGuardAcknowledgements(tool.name, tool.parameters),
396
520
  async execute(toolCallId, params, signal, onUpdate, ctx) {
397
521
  const mutableArgs = params as Record<string, unknown>
522
+ normalizeDefaultTreeRoot(tool.name, mutableArgs)
398
523
  const liveOrigin = opts.getOrigin?.()
399
524
  // Defense-in-depth: strip any pre-existing internal env-overlay key
400
525
  // before hooks run so only trusted tool.before hooks can set it.
@@ -435,36 +560,91 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
435
560
 
436
561
  // Per-subagent capability fence: runs BEFORE the role-derived sandbox so
437
562
  // a read-only subagent's bash stays read-only even for a trusted/owner
438
- // caller (for whom applyBashSandbox returns early with no masks). Throws
439
- // SubagentBashPolicyError on a disallowed command, surfaced to the model
440
- // as a tool error.
563
+ // caller whose sandbox otherwise preserves full agent-root writes. Throws
564
+ // SubagentBashPolicyError on a disallowed command, surfaced to the model as
565
+ // a tool error.
441
566
  if (tool.name === 'bash' && opts.bashPolicy !== undefined) {
442
567
  const command = mutableArgs.command
443
568
  if (typeof command === 'string') enforceSubagentBashPolicy(opts.bashPolicy, command)
444
569
  }
445
570
 
446
- if (tool.name === 'bash' && opts.permissions !== undefined) {
447
- await applyBashSandbox(mutableArgs, opts.permissions, liveOrigin, opts.agentDir, opts.sessionId, bashEnvOverlay)
448
- }
449
-
450
- const tmpRedirect =
451
- TMP_REDIRECT_TOOLS.has(tool.name) && opts.permissions !== undefined
452
- ? await applyTmpPathRedirect(mutableArgs, opts.permissions, liveOrigin, opts.agentDir, opts.sessionId)
453
- : undefined
454
-
455
- let rawResult: ToolResult
571
+ let preparedSandboxRuntime: PreparedBashSandbox | undefined
572
+ let pinnedFiles: Awaited<ReturnType<typeof enforceAndPinToolFiles>> | undefined
573
+ let tmpRedirect: TmpRedirect | undefined
574
+ let rawResult: ToolResult | undefined
575
+ let executionError: unknown
576
+ let cleanupError: unknown
577
+ const sandboxBoundary = opts.bashSandboxBoundary ?? DEFAULT_BASH_SANDBOX_BOUNDARY
456
578
  try {
457
- rawResult = await bashEnvStore.run(bashEnvOverlay, () =>
579
+ if (tool.name === 'bash') {
580
+ if (opts.permissions === undefined) {
581
+ throw new SandboxPolicyError('model-driven bash has no permission service; refusing unsandboxed execution')
582
+ }
583
+ preparedSandboxRuntime = await applyBashSandbox(
584
+ mutableArgs,
585
+ opts.permissions,
586
+ liveOrigin,
587
+ opts.agentDir,
588
+ opts.sessionId,
589
+ bashEnvOverlay,
590
+ sandboxBoundary,
591
+ )
592
+ }
593
+
594
+ tmpRedirect =
595
+ TMP_REDIRECT_TOOLS.has(tool.name) && opts.permissions !== undefined
596
+ ? await applyTmpPathRedirect(mutableArgs, opts.permissions, liveOrigin, opts.agentDir, opts.sessionId)
597
+ : undefined
598
+ pinnedFiles = await enforceAndPinToolFiles({
599
+ tool: tool.name,
600
+ args: mutableArgs,
601
+ agentDir: opts.agentDir,
602
+ ...(opts.permissions !== undefined
603
+ ? { hidden: resolveHiddenPaths(opts.permissions, liveOrigin, opts.agentDir) }
604
+ : {}),
605
+ signal,
606
+ })
607
+ await preparedSandboxRuntime?.verify()
608
+ const spawnEnvContext: BashSpawnEnvContext | undefined =
609
+ bashEnvOverlay !== undefined || preparedSandboxRuntime?.spawnEnv !== undefined
610
+ ? {
611
+ ...(bashEnvOverlay !== undefined ? { overlay: bashEnvOverlay } : {}),
612
+ ...(preparedSandboxRuntime?.spawnEnv !== undefined
613
+ ? { sandboxSpawnEnv: preparedSandboxRuntime.spawnEnv }
614
+ : {}),
615
+ }
616
+ : undefined
617
+ rawResult = await bashEnvStore.run(spawnEnvContext, () =>
458
618
  tool.execute(toolCallId, mutableArgs as Static<TParams>, signal, onUpdate, ctx),
459
619
  )
460
620
  } catch (error) {
461
- // A throwing tool (pi's bash rejects on non-zero exit) must still run
462
- // tool.after so cleanup hooks fire — e.g. the github approve guard's
463
- // release, whose absence stranded a PR as "already approved" (PR #672).
464
- await runToolAfterSafely(opts, tool.name, toolCallId, toErrorResult(error))
465
- throw error
621
+ executionError = error
622
+ } finally {
623
+ const cleanup = [pinnedFiles?.cleanup(), preparedSandboxRuntime?.cleanup()].filter(
624
+ (task): task is Promise<void> => task !== undefined,
625
+ )
626
+ const outcomes = await Promise.allSettled(cleanup)
627
+ const failed = outcomes.find((outcome) => outcome.status === 'rejected')
628
+ if (failed?.status === 'rejected') cleanupError = failed.reason
629
+ }
630
+ // Decorate genuine, user-correctable builtin file-tool failures with a
631
+ // recovery hint so weaker models retry correctly. Only executionError (not
632
+ // cleanupError) and only non-aborted Error instances; remediation is a
633
+ // no-op for every message/tool outside the allowlist, so abort, sandbox,
634
+ // and policy errors pass through untouched. Mutating the message in place
635
+ // preserves the error's subclass and stack for the rethrow.
636
+ if (executionError instanceof Error && signal?.aborted !== true) {
637
+ executionError.message = remediateToolErrorMessage(tool.name, executionError.message)
466
638
  }
467
- const result = tmpRedirect !== undefined ? restoreTmpPathInResult(rawResult, tmpRedirect) : rawResult
639
+ const finalError = executionError ?? cleanupError
640
+ if (finalError !== undefined) {
641
+ await runToolAfterSafely(opts, tool.name, toolCallId, toErrorResult(finalError))
642
+ throw finalError
643
+ }
644
+ if (pinnedFiles === undefined) throw new Error('tool file boundary was not initialized')
645
+ if (rawResult === undefined) throw new Error('tool execution returned no result')
646
+ const pinnedResult = pinnedFiles.restoreResult(rawResult)
647
+ const result = tmpRedirect !== undefined ? restoreTmpPathInResult(pinnedResult, tmpRedirect) : pinnedResult
468
648
  const resolved = loopGate.resolve({ content: result.content as ContentPart[], details: result.details })
469
649
  if ('deferredBlock' in resolved) {
470
650
  fireLoopAbort(opts.getAbort, 'loop_guard:deferred_block')
@@ -513,9 +693,31 @@ export function buildBuiltinPiToolOverrides(opts: WrapSystemToolOptions): ToolDe
513
693
  return defaultBuiltinPiToolDefinitions(opts.agentDir).map((tool) => wrapBuiltinToolDefinition(tool, opts))
514
694
  }
515
695
 
696
+ type BashFilesystemPolicyOptions = {
697
+ agentDir: string
698
+ canWriteAgentRoot: boolean
699
+ masks: { dirs: string[]; files: string[] }
700
+ writable: { dirs: string[]; files: string[] }
701
+ protected: { dirs: string[]; files: string[] }
702
+ }
703
+
704
+ type PreparedBashSandbox = {
705
+ verify: () => Promise<void>
706
+ cleanup: () => Promise<void>
707
+ spawnEnv?: Record<string, string>
708
+ }
709
+
710
+ export function buildBashFilesystemPolicy(options: BashFilesystemPolicyOptions) {
711
+ const { agentDir, canWriteAgentRoot, masks, writable, protected: protectedZones } = options
712
+ if (canWriteAgentRoot) {
713
+ return { writableRoot: { dir: agentDir }, masks, protected: protectedZones }
714
+ }
715
+ return { masks, writable, protected: protectedZones }
716
+ }
717
+
516
718
  // Rewrites mutableArgs.command in place so the bash builtin runs inside bwrap
517
- // with role-derived path masks. A role that sees everything (trusted+) yields
518
- // no masks and runs unchanged. When masks ARE needed but bwrap is unavailable
719
+ // with role-derived private-directory masks and unconditional canonical-secret
720
+ // file masks. When masks are needed but bwrap is unavailable
519
721
  // we throw rather than run unsandboxed — fail closed, never leak the masked
520
722
  // surface. Runs after the tool.before guards have inspected the raw command.
521
723
  async function applyBashSandbox(
@@ -525,123 +727,128 @@ async function applyBashSandbox(
525
727
  agentDir: string,
526
728
  sessionId: string,
527
729
  envOverlay: BashEnvOverlay | undefined,
528
- ): Promise<void> {
730
+ boundary: BashSandboxBoundary,
731
+ ): Promise<PreparedBashSandbox> {
529
732
  const command = mutableArgs.command
530
- if (typeof command !== 'string') return
733
+ if (typeof command !== 'string') return { verify: async () => {}, cleanup: async () => {} }
531
734
 
532
- const { dirs, files } = resolveHiddenPaths(permissions, origin, agentDir)
533
- if (dirs.length === 0 && files.length === 0) return
735
+ await assertNoCanonicalSecretsInGit(agentDir)
534
736
 
737
+ const { dirs, files } = resolveHiddenPaths(permissions, origin, agentDir)
535
738
  const sandboxEnvOverlay = buildRoleScopedConfigEnv(agentDir, dirs, envOverlay)
536
-
537
- await ensureBwrapAvailable()
538
- // bwrap's --ro-bind-data/--tmpfs mask ops abort when the target does not exist
539
- // on the (read-only, virtiofs/OrbStack) agent-folder bind. Materialize the mask
540
- // targets on the real host FS first; the full {dirs, files} still feeds
541
- // subtractMasked below so a masked path is never re-exposed by a later RW bind.
542
739
  const maskTargets = await ensureHiddenMaskTargets({ dirs, files })
543
- // Per-session /tmp: bind this session's scratch dir over the default
544
- // --tmpfs /tmp so writes survive across the role's sandboxed bash calls AND
545
- // match what the write/edit wrapper redirected a /tmp path to. The bind is
546
- // emitted via policy.mounts (after the hardcoded --tmpfs /tmp), so last-op-
547
- // wins makes it the live /tmp. Unsandboxed roles (empty masks, returned
548
- // above) keep sharing the real container /tmp between write and bash.
740
+ await boundary.ensureAvailable()
549
741
  const sessionTmp = await ensureSessionTmpDir(sessionId)
550
- // Write-confined jail for low-trust roles: bind the whole project read-only,
551
- // hide private/secret paths, then re-expose only the free-write scratch zones
552
- // (workspace + root allowlist + .git) RW. The WORKING TREE outside those zones
553
- // (node_modules/, agentDir root, non-allowlisted tracked files) stays EROFS, so
554
- // bash cannot sidestep the non-workspace-write guard — and `git checkout` of a
555
- // protected worktree path fails at the kernel. .git is RW so members can
556
- // commit; .git/hooks + .git/config (and any writable core.hooksPath target)
557
- // are re-protected RO (protected, rendered after writable, ensured to exist so
558
- // an absent path can't be created+executed) so a hook-plant / core.hooksPath
559
- // never becomes code execution in the unsandboxed runtime git ops. Trusted/owner never reach here
560
- // (their masks are empty) and keep full unsandboxed access. subtractMasked
561
- // drops any writable zone masked for this role so an RW bind never re-exposes a
562
- // hidden path (e.g. a guest's masked workspace/).
563
- // config.sandbox.* is read from the BOOT-TIME snapshot, not getConfig():
564
- // sandbox is restart-required, so the writable surface AND the in-jail symlinks
565
- // must stay coherent with the boot-time bwrap/capability decisions and with the
566
- // entrypoint shim's symlink creation (same contract as resolveProcStrategy's
567
- // read of config.sandbox.realProc below). getSandboxWritablePathSpecs folds
568
- // every sandbox.symlinks[].to into the writable set so the symlink target is
569
- // writable without the operator also listing it under writablePaths.
570
742
  const writable = subtractMasked(await resolveWritableZones(agentDir, getSandboxWritablePathSpecs(config)), {
571
743
  dirs,
572
744
  files,
573
745
  })
574
- // subtractMasked again on the protected set: a protected RO bind renders after
575
- // the masks (last-op-wins), so an unfiltered protected path nested under a
576
- // masked dir (e.g. a guest's workspace/ when core.hooksPath=workspace/hooks)
577
- // would re-expose the hidden real dir. A masked path is already non-writable
578
- // for this role, so it needs no protection anyway.
579
- const protectedZones = writable.dirs.includes(join(agentDir, '.git'))
580
- ? subtractMasked(await resolveProtectedZones(agentDir), { dirs, files })
581
- : { dirs: [], files: [] }
582
- // A recognized standalone `bun add`/`bun install` needs DIRECTORY write at the
583
- // root (node_modules/ + temp lockfile), which the narrow carve-out model can't
584
- // grant. Widen to an RW root for that command class only, then re-hide secrets
585
- // (masks) and re-RO the executable surfaces (resolvePackageInstallZones) on top
586
- // — subtractMasked drops any protected path a mask already hides so the RW root
587
- // never re-exposes it. The default jail's `writable`/`protected` are skipped
588
- // here: writableRoot supersedes them for this command, and the same masks +
589
- // package-install protected set cover the confidentiality and escalation
590
- // boundaries.
591
- const packageInstall = isPackageInstallCommand(command)
592
- ? subtractMaskedProtected(await resolvePackageInstallZones(agentDir), { dirs, files })
593
- : undefined
594
-
595
- // Only emit an in-jail symlink for a target that actually survived as a
596
- // writable dir: a symlink to a target that was dropped (missing, masked for
597
- // this role, or filtered by the writable-zone guardrails) would dangle onto an
598
- // EROFS/hidden path. Resolve `from` against the SANDBOX HOME (/tmp), where the
599
- // per-session tmp dir is bound — NOT the container's real /root, which the jail
600
- // never sees. The entrypoint shim handles the real-/root symlink for the
601
- // unsandboxed (trusted/owner) path.
746
+ const writableRoot = canWriteAgentRootInSandbox(permissions, origin)
747
+ const protectedZones =
748
+ writableRoot || writable.dirs.includes(join(agentDir, '.git'))
749
+ ? subtractMasked(await resolveProtectedZones(agentDir), { dirs, files })
750
+ : { dirs: [], files: [] }
602
751
  const writableDirSet = new Set(writable.dirs)
603
752
  const sandboxHome = DEFAULT_SANDBOX_ENV.HOME ?? '/tmp'
604
753
  const symlinks = resolveSandboxSymlinks(agentDir, config.sandbox.symlinks, sandboxHome).filter((op) =>
605
754
  writableDirSet.has(op.target),
606
755
  )
607
- // bwrap does --clearenv, so the overlay must be re-introduced via env.set or
608
- // it would never reach the sandboxed process (the non-sandboxed spawnHook
609
- // path does not run when the command is rewritten to a bwrap invocation).
610
756
  const { strategy: proc, degradeReason } = await resolveProcStrategy()
611
- // Fail fast with an actionable error when /proc degraded to tmpfs AND the
612
- // command needs a real /proc: under tmpfs Bun would otherwise abort deep in its
613
- // pipeline with the opaque "NotDir", which the model retries forever. Which
614
- // error depends on WHY it degraded: a 'definitive' degrade (a real leak / an
615
- // incapable host) is permanent → SandboxDegradedProcError ("retrying won't
616
- // help"); an 'unverified' degrade (the safety probe stayed inconclusive through
617
- // its retry budget, e.g. a boot-time load spike) is transient and re-probes on
618
- // the next call → SandboxProcProbeUnverifiedError ("retry the same command").
619
- // Guarded on the command so non-bun bash still runs in the degraded mode (it
620
- // does not touch /proc/self/{fd,maps}).
621
757
  if (proc === 'tmpfs' && commandNeedsRealProc(command)) {
622
758
  throw degradeReason === 'unverified' ? new SandboxProcProbeUnverifiedError() : new SandboxDegradedProcError()
623
759
  }
624
- const { commandString } = buildSandboxedCommand(command, {
625
- mounts: [
626
- { type: 'ro-bind', source: agentDir, dest: agentDir },
627
- { type: 'bind', source: sessionTmp, dest: '/tmp' },
628
- ],
629
- ...(packageInstall !== undefined
630
- ? {
631
- writableRoot: { dir: packageInstall.root },
632
- masks: maskTargets,
633
- protected: packageInstall.protected,
634
- blockedCreation: { files: packageInstall.blockedCreation },
635
- }
636
- : { masks: maskTargets, writable, protected: protectedZones }),
637
- symlinks,
638
- network: 'inherit',
639
- cwd: agentDir,
640
- proc,
641
- procSelfExe: resolveProcSelfExe(),
642
- ...(sandboxEnvOverlay !== undefined ? { env: { set: sandboxEnvOverlay } } : {}),
760
+ const privilegedRuntime = await (boundary.resolveRuntime ?? resolvePrivilegedSandboxRuntime)({
761
+ agentDir,
762
+ command,
763
+ env: sandboxEnvOverlay,
643
764
  })
644
- mutableArgs.command = commandString
765
+ const cleanup = async (): Promise<void> =>
766
+ (boundary.cleanupRuntime ?? cleanupPrivilegedSandboxRuntime)(privilegedRuntime)
767
+ try {
768
+ await verifyHiddenMaskTargets(maskTargets)
769
+ const { commandString, spawnEnv } = boundary.buildCommand(command, {
770
+ mounts: [
771
+ { type: 'ro-bind', source: agentDir, dest: agentDir },
772
+ { type: 'bind', source: sessionTmp, dest: '/tmp' },
773
+ ...(privilegedRuntime?.mounts ?? []),
774
+ ],
775
+ ...(writableRoot
776
+ ? { writableRoot: { dir: agentDir }, masks: maskTargets, protected: protectedZones }
777
+ : { masks: maskTargets, writable, protected: protectedZones }),
778
+ symlinks,
779
+ network: 'inherit',
780
+ cwd: agentDir,
781
+ proc,
782
+ procSelfExe: resolveProcSelfExe(),
783
+ ...spreadSandboxEnv(
784
+ buildSandboxEnvPolicy(sandboxEnvOverlay, privilegedRuntime?.env, resolveExposableBashEnvNames(agentDir)),
785
+ ),
786
+ })
787
+ mutableArgs.command = commandString
788
+ // The overlay carries command-scoped secret VALUES (e.g. a per-repo GH_TOKEN)
789
+ // that live in neither process.env nor argv; resolveSpawnEnv snapshots
790
+ // inherited names from process.env only, so merge the overlay values in here
791
+ // to complete the exact bwrap-parent env.
792
+ const mergedSpawnEnv =
793
+ spawnEnv !== undefined && sandboxEnvOverlay !== undefined ? { ...spawnEnv, ...sandboxEnvOverlay } : spawnEnv
794
+ return {
795
+ verify: async () => (boundary.verifyRuntime ?? verifyPrivilegedSandboxRuntime)(privilegedRuntime),
796
+ cleanup,
797
+ spawnEnv: mergedSpawnEnv,
798
+ }
799
+ } catch (error) {
800
+ await cleanup()
801
+ throw error
802
+ }
803
+ }
804
+
805
+ export function buildSandboxEnvPolicy(
806
+ overlay: BashEnvOverlay | undefined,
807
+ runtimeEnv: Record<string, string> | undefined,
808
+ exposableEnvNames: readonly string[] = [],
809
+ ): { inherit?: string[]; set?: Record<string, string> } {
810
+ const set = { ...runtimeEnv }
811
+ const inherit: string[] = []
812
+ const inheritSeen = new Set<string>()
813
+ const pushInherit = (key: string): void => {
814
+ if (Object.hasOwn(set, key) || inheritSeen.has(key)) return
815
+ inheritSeen.add(key)
816
+ inherit.push(key)
817
+ }
818
+ for (const [key, value] of Object.entries(overlay ?? {})) {
819
+ if (Object.hasOwn(set, key)) continue
820
+ if (isOverlaySecretName(key)) pushInherit(key)
821
+ else set[key] = value
822
+ }
823
+ // Operator-declared .env vars pass through by NAME (inherit), keeping values
824
+ // out of the rendered bwrap argv. Sandbox-integrity names were already dropped
825
+ // in resolveExposableEnvNames — these are the survivors.
826
+ for (const key of exposableEnvNames) pushInherit(key)
827
+ // Pass the entrypoint-exported Xvfb display (start_xvfb: `export DISPLAY=:99`)
828
+ // through --clearenv, else sandboxed `agent-browser --headed` dies with
829
+ // "Missing X server or $DISPLAY". Passing the runtime's OWN value (not a fixed
830
+ // ":99") keeps `docker.file.xvfb=false` advertising no display. Rendered via
831
+ // `set` (a display number is neither a credential nor shell-injectable), and no
832
+ // /tmp/.X11-unix bind is needed: Chrome reaches Xvfb over the netns-scoped
833
+ // abstract X11 socket while bash keeps network:'inherit'.
834
+ const display = process.env['DISPLAY']
835
+ if (display !== undefined && display !== '' && !Object.hasOwn(set, 'DISPLAY') && !inheritSeen.has('DISPLAY')) {
836
+ set['DISPLAY'] = display
837
+ }
838
+ return {
839
+ ...(inherit.length > 0 ? { inherit } : {}),
840
+ ...(Object.keys(set).length > 0 ? { set } : {}),
841
+ }
842
+ }
843
+
844
+ function spreadSandboxEnv(policy: ReturnType<typeof buildSandboxEnvPolicy>): {
845
+ env?: ReturnType<typeof buildSandboxEnvPolicy>
846
+ } {
847
+ return Object.keys(policy).length > 0 ? { env: policy } : {}
848
+ }
849
+
850
+ function resolveExposableBashEnvNames(agentDir: string): string[] {
851
+ return resolveExposableEnvNames(readEnvFile(agentDir))
645
852
  }
646
853
 
647
854
  function buildRoleScopedConfigEnv(
@@ -652,8 +859,8 @@ function buildRoleScopedConfigEnv(
652
859
  // Low-trust roles have workspace/ masked. Do not let container-global config
653
860
  // env vars point CLIs back at that private surface: apps that honor XDG should
654
861
  // still run, but their config must land in the sandbox's per-session /tmp.
655
- // Trusted/owner never get here (no hidden dirs), so their Dockerfile-level
656
- // persistent GWS_CONFIG_HOME remains /agent/workspace/.config/gws.
862
+ // Trusted/owner have only the unconditional credential-dir masks, not the
863
+ // workspace root mask, so their command broker decides whether to set GWS.
657
864
  const workspaceHidden = hiddenDirs.includes(join(agentDir, 'workspace'))
658
865
  if (!workspaceHidden) return envOverlay
659
866
 
@@ -664,14 +871,6 @@ function buildRoleScopedConfigEnv(
664
871
  }
665
872
  }
666
873
 
667
- function subtractMaskedProtected(
668
- zones: { root: string; protected: { dirs: string[]; files: string[] }; blockedCreation: string[] },
669
- masked: { dirs: string[]; files: string[] },
670
- ): { root: string; protected: { dirs: string[]; files: string[] }; blockedCreation: string[] } {
671
- const filtered = subtractMasked(zones.protected, masked)
672
- return { root: zones.root, protected: filtered, blockedCreation: zones.blockedCreation }
673
- }
674
-
675
874
  // Picks the /proc strategy for a sandboxed bash call. The branch order is:
676
875
  // 'real-proc' ONLY when the operator explicitly opted in (sandbox.realProc) AND
677
876
  // the kernel permits the mount (canMountRealProc) — it adds PID isolation but
@@ -717,7 +916,7 @@ async function resolveProcStrategy(): Promise<ProcStrategyResolution> {
717
916
  )
718
917
  if (verdict === 'safe') return { strategy: 'proc-bind' }
719
918
  // Degraded last resort: no working /proc strategy. External package runners
720
- // (bunx/bun add/bun run <pkg-bin>) will fail with Bun's opaque "NotDir" because
919
+ // (bunx/bun run <pkg-bin>) will fail with Bun's opaque "NotDir" because
721
920
  // /proc/self/{fd,maps} are absent. Only a proven 'unsafe' (a real cross-userns
722
921
  // leak) is DEFINITIVE — warn once (a real operator-facing limit). An
723
922
  // 'inconclusive' is reported as retryable upstream and NOT warned (it would cry
@@ -736,25 +935,26 @@ function warnTmpfsProcFallbackOnce(): void {
736
935
  tmpfsProcFallbackWarned = true
737
936
  console.warn(
738
937
  '[sandbox] degraded /proc mode: neither real-proc nor proc-bind is available on this host, ' +
739
- 'so sandboxed external package runners (bunx / bun add / bun run <pkg-bin>) will fail. ' +
938
+ 'so sandboxed external package runners (bunx / bun run <pkg-bin>) will fail. ' +
740
939
  'This needs a runtime with working user namespaces.',
741
940
  )
742
941
  }
743
942
 
744
- // The builtin file tools that take a single filesystem `path` arg. For a
745
- // sandboxed role they all run UNSANDBOXED in the main process (only bash is
746
- // bwrap-wrapped), so each must apply the same /tmp -> session-dir mapping that
943
+ // The builtin file tools that take a single filesystem `path` arg. They run in
944
+ // the main process rather than bwrap, so each must apply the same
945
+ // /tmp -> session-dir mapping that
747
946
  // applyBashSandbox binds for bash — otherwise a `read` of /tmp/foo hits the
748
947
  // real container /tmp while sandboxed bash wrote the session backing dir.
749
948
  const TMP_REDIRECT_TOOLS = new Set(['read', 'write', 'edit', 'grep', 'find', 'ls'])
750
949
 
751
- // Sandboxed roles read /tmp through bwrap's per-session bind (applyBashSandbox),
752
- // but the path-based file tools run unsandboxed against the real container /tmp.
950
+ // Model-driven bash reads /tmp through bwrap's per-session bind
951
+ // (applyBashSandbox), but the path-based file tools run in the main process
952
+ // against the real container /tmp.
753
953
  // Without this redirect a guest/member that touches /tmp/foo through bash (bound
754
954
  // to the session dir) and through a file tool (real /tmp) would see two
755
955
  // different files. Rewriting the file tool's on-disk path to the same session
756
- // backing dir makes every layer resolve /tmp/foo to one file. Unsandboxed roles
757
- // (empty masks) are left untouched: their bash already shares the real /tmp.
956
+ // backing dir makes every layer resolve /tmp/foo to one file. Bare harnesses
957
+ // without the production permission wiring are left untouched.
758
958
  type TmpRedirect = { original: string; backing: string }
759
959
 
760
960
  async function applyTmpPathRedirect(
@@ -798,6 +998,12 @@ function isRecord(value: unknown): value is Record<string, unknown> {
798
998
  return typeof value === 'object' && value !== null
799
999
  }
800
1000
 
1001
+ function normalizeDefaultTreeRoot(toolName: string, args: Record<string, unknown>): void {
1002
+ if ((toolName === 'grep' || toolName === 'find' || toolName === 'ls') && typeof args.path !== 'string') {
1003
+ args.path = '.'
1004
+ }
1005
+ }
1006
+
801
1007
  function appendLoopWarning(result: ToolResult, message: string): ToolResult {
802
1008
  const content: ContentPart[] = [...(result.content as ContentPart[]), { type: 'text', text: message }]
803
1009
  return { content, details: result.details }
@@ -955,12 +1161,28 @@ function errorResult(message: string) {
955
1161
 
956
1162
  async function runFinalWriteGuards(options: { tool: string; args: Record<string, unknown>; agentDir: string }) {
957
1163
  return (
1164
+ (await checkGitControlWriteGuard(options)) ??
958
1165
  (await checkManagedConfigGuard(options)) ??
959
1166
  (await checkSkillAuthoringGuard(options)) ??
960
1167
  checkNonWorkspaceWriteGuard(options)
961
1168
  )
962
1169
  }
963
1170
 
1171
+ async function checkGitControlWriteGuard(options: {
1172
+ tool: string
1173
+ args: Record<string, unknown>
1174
+ agentDir: string
1175
+ }): Promise<{ block: true; reason: string } | undefined> {
1176
+ if (options.tool !== 'write' && options.tool !== 'edit') return undefined
1177
+ const candidate = options.args.path
1178
+ if (typeof candidate !== 'string') return undefined
1179
+ if (!(await isGitControlPath(options.agentDir, candidate))) return undefined
1180
+ return {
1181
+ block: true,
1182
+ reason: `Git control path is runtime-protected and cannot be modified with ${options.tool}: ${candidate}`,
1183
+ }
1184
+ }
1185
+
964
1186
  function runFinalReadGuards(options: { tool: string; args: Record<string, unknown> }) {
965
1187
  return checkImageReadRedirect(options)
966
1188
  }