typeclaw 0.45.0 → 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 (147) hide show
  1. package/README.md +1 -1
  2. package/package.json +3 -2
  3. package/src/agent/git-nudge.ts +2 -1
  4. package/src/agent/index.ts +67 -25
  5. package/src/agent/live-subagents.ts +18 -0
  6. package/src/agent/loop-guard.ts +208 -10
  7. package/src/agent/multimodal/index.ts +1 -1
  8. package/src/agent/multimodal/look-at.ts +78 -44
  9. package/src/agent/multimodal/looker.ts +151 -39
  10. package/src/agent/network/response-body.ts +26 -0
  11. package/src/agent/network/safe-http.ts +198 -0
  12. package/src/agent/plugin-tools.ts +438 -162
  13. package/src/agent/provider-error.ts +62 -4
  14. package/src/agent/restart/index.ts +61 -40
  15. package/src/agent/restart-handoff/index.ts +73 -4
  16. package/src/agent/retry-same-ref.ts +66 -0
  17. package/src/agent/reviewer-bash-policy.ts +42 -1
  18. package/src/agent/session-origin.ts +2 -0
  19. package/src/agent/subagent-drain.ts +117 -7
  20. package/src/agent/subagents.ts +77 -18
  21. package/src/agent/throttle-circuit.ts +25 -5
  22. package/src/agent/tool-error-remediation.ts +72 -0
  23. package/src/agent/tool-file-safety.ts +1050 -0
  24. package/src/agent/tools/channel-fetch-attachment.ts +10 -3
  25. package/src/agent/tools/channel-reply.ts +15 -1
  26. package/src/agent/tools/channel-send.ts +17 -1
  27. package/src/agent/tools/ddg.ts +16 -2
  28. package/src/agent/tools/post-github-review.ts +199 -0
  29. package/src/agent/tools/spawn-subagent.ts +21 -18
  30. package/src/agent/tools/webfetch/fetch.ts +143 -183
  31. package/src/agent/tools/webfetch/tool.ts +2 -3
  32. package/src/agent/tools/websearch.ts +23 -2
  33. package/src/agent/tools-without-local-file-operands.ts +27 -0
  34. package/src/agent/turn-runner.ts +109 -15
  35. package/src/bundled-plugins/backup/index.ts +2 -1
  36. package/src/bundled-plugins/backup/runner.ts +2 -1
  37. package/src/bundled-plugins/doc-render/render.ts +93 -12
  38. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  39. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  40. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  41. package/src/bundled-plugins/github-cli-auth/index.ts +131 -135
  42. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  43. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  44. package/src/bundled-plugins/memory/README.md +23 -11
  45. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  46. package/src/bundled-plugins/memory/citations.ts +22 -9
  47. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  48. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  49. package/src/bundled-plugins/memory/index.ts +0 -4
  50. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  51. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  52. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  53. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  54. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  55. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  56. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  57. package/src/bundled-plugins/researcher/write-report.ts +6 -3
  58. package/src/bundled-plugins/reviewer/index.ts +2 -2
  59. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  60. package/src/bundled-plugins/reviewer/skills/code-review.ts +24 -9
  61. package/src/bundled-plugins/scout/scout.ts +8 -0
  62. package/src/bundled-plugins/security/index.ts +4 -4
  63. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  64. package/src/bundled-plugins/security/policies/private-surface-read.ts +220 -29
  65. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  66. package/src/bundled-plugins/security/policies/ssrf.ts +29 -9
  67. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  68. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  69. package/src/channels/adapters/discord-bot.ts +91 -10
  70. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  71. package/src/channels/adapters/discord-id.ts +4 -0
  72. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  73. package/src/channels/adapters/discord.ts +57 -7
  74. package/src/channels/adapters/github/auth-app.ts +41 -12
  75. package/src/channels/adapters/github/index.ts +23 -11
  76. package/src/channels/adapters/github/review-submitter.ts +302 -0
  77. package/src/channels/adapters/kakaotalk-channel-resolver.ts +12 -1
  78. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  79. package/src/channels/adapters/kakaotalk-typing.ts +127 -0
  80. package/src/channels/adapters/kakaotalk.ts +19 -0
  81. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  82. package/src/channels/adapters/slack-bot.ts +19 -8
  83. package/src/channels/adapters/slack-classify.ts +21 -2
  84. package/src/channels/adapters/slack.ts +59 -7
  85. package/src/channels/adapters/telegram-bot.ts +18 -5
  86. package/src/channels/adapters/webex-bot.ts +8 -3
  87. package/src/channels/adapters/webex.ts +8 -3
  88. package/src/channels/fetch-attachment.ts +43 -0
  89. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  90. package/src/channels/github-token-bridge.ts +10 -3
  91. package/src/channels/manager.ts +9 -0
  92. package/src/channels/router.ts +568 -12
  93. package/src/channels/types.ts +28 -1
  94. package/src/cli/channel.ts +1 -1
  95. package/src/cli/init.ts +1 -1
  96. package/src/cli/model.ts +57 -7
  97. package/src/compose/stop.ts +17 -5
  98. package/src/config/config.ts +6 -6
  99. package/src/config/models-mutation.ts +13 -1
  100. package/src/config/providers.ts +176 -0
  101. package/src/container/start.ts +49 -10
  102. package/src/doctor/checks.ts +3 -1
  103. package/src/doctor/commit.ts +2 -1
  104. package/src/doctor/file-ownership.ts +52 -0
  105. package/src/dreams/git.ts +2 -1
  106. package/src/git/hookless.ts +5 -0
  107. package/src/git/reconcile-ignored.ts +18 -5
  108. package/src/git/secret-history.ts +371 -0
  109. package/src/git/system-commit.ts +12 -6
  110. package/src/init/dockerfile.ts +86 -5
  111. package/src/init/index.ts +17 -5
  112. package/src/init/models-dev.ts +4 -0
  113. package/src/init/validate-api-key.ts +2 -0
  114. package/src/mcp/tools.ts +16 -3
  115. package/src/permissions/builtins.ts +3 -1
  116. package/src/plugin/context.ts +2 -0
  117. package/src/plugin/index.ts +1 -0
  118. package/src/plugin/manager.ts +4 -0
  119. package/src/plugin/types.ts +21 -0
  120. package/src/run/index.ts +40 -0
  121. package/src/run/llm-fetch-observer.ts +188 -13
  122. package/src/sandbox/build.ts +37 -15
  123. package/src/sandbox/canonical-secrets.ts +18 -0
  124. package/src/sandbox/env-exposure.ts +80 -0
  125. package/src/sandbox/errors.ts +13 -6
  126. package/src/sandbox/hidden-paths.ts +102 -44
  127. package/src/sandbox/index.ts +22 -4
  128. package/src/sandbox/package-install.ts +3 -27
  129. package/src/sandbox/policy.ts +11 -25
  130. package/src/sandbox/privileged-runtime.ts +255 -0
  131. package/src/sandbox/session-tmp.ts +8 -2
  132. package/src/sandbox/writable-zones.ts +204 -140
  133. package/src/secrets/index.ts +8 -0
  134. package/src/secrets/refresh-provider-oauth.ts +128 -0
  135. package/src/server/command-runner.ts +48 -4
  136. package/src/server/index.ts +4 -0
  137. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  138. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  139. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  140. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  141. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  142. package/src/skills/typeclaw-config/SKILL.md +5 -5
  143. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  144. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  145. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  146. package/src/skills/typeclaw-permissions/SKILL.md +19 -15
  147. package/typeclaw.schema.json +20 -0
@@ -15,6 +15,13 @@ const { dirname } = posix
15
15
  export type SandboxedCommand = {
16
16
  argv: string[]
17
17
  commandString: string
18
+ // Exact environment the bwrap PARENT process must run with. bwrap only drops
19
+ // --clearenv when there are inherited names and then --unsetenv's the keys
20
+ // present in process.env AT BUILD TIME — a secret added to the live env between
21
+ // build and spawn would otherwise be inherited. The spawn must therefore start
22
+ // from THIS snapshot (defaults + resolved set + snapshotted inherited values),
23
+ // never the live process.env, so late-added keys can't reach the sandbox.
24
+ spawnEnv: Record<string, string>
18
25
  }
19
26
 
20
27
  // Fixed fd the rendered commandString opens to /dev/null for --ro-bind-data
@@ -35,7 +42,7 @@ export function buildSandboxedCommand(command: string, policy: SandboxPolicy = {
35
42
  const argv = buildArgv(command, policy)
36
43
  const needsMaskFd = (policy.masks?.files?.length ?? 0) > 0
37
44
  const commandString = needsMaskFd ? `${formatCommand(argv)} ${MASK_DATA_FD}</dev/null` : formatCommand(argv)
38
- return { argv, commandString }
45
+ return { argv, commandString, spawnEnv: resolveSpawnEnv(policy.env) }
39
46
  }
40
47
 
41
48
  function buildArgv(command: string, policy: SandboxPolicy): string[] {
@@ -84,8 +91,21 @@ function buildArgv(command: string, policy: SandboxPolicy): string[] {
84
91
  argv.push('--die-with-parent')
85
92
  }
86
93
 
87
- argv.push('--clearenv')
94
+ const inheritedNames = new Set(policy.env?.inherit ?? [])
95
+ if (inheritedNames.size === 0) {
96
+ argv.push('--clearenv')
97
+ } else {
98
+ const retained = new Set([
99
+ ...inheritedNames,
100
+ ...Object.keys(DEFAULT_SANDBOX_ENV),
101
+ ...Object.keys(policy.env?.set ?? {}),
102
+ ])
103
+ for (const key of Object.keys(process.env).sort()) {
104
+ if (!retained.has(key)) argv.push('--unsetenv', key)
105
+ }
106
+ }
88
107
  for (const [key, value] of Object.entries(resolveEnv(policy.env))) {
108
+ if (inheritedNames.has(key)) continue
89
109
  argv.push('--setenv', key, value)
90
110
  }
91
111
 
@@ -168,10 +188,9 @@ function buildArgv(command: string, policy: SandboxPolicy): string[] {
168
188
  }
169
189
 
170
190
  appendWritableRoot(argv, policy)
171
- appendMasks(argv, policy)
172
191
  appendWritable(argv, policy)
192
+ appendMasks(argv, policy)
173
193
  appendProtected(argv, policy)
174
- appendBlockedCreation(argv, policy)
175
194
  appendSymlinks(argv, policy)
176
195
 
177
196
  if (policy.cwd !== undefined) {
@@ -218,17 +237,6 @@ function appendProtected(argv: string[], policy: SandboxPolicy): void {
218
237
  }
219
238
  }
220
239
 
221
- // Occupies each path with an empty read-only object so a writable-root install
222
- // script cannot CREATE a real file there. /dev/null always exists (bwrap mounts
223
- // --dev), so unlike --ro-bind-data this needs no manufactured placeholder on the
224
- // host FS. Renders after appendProtected: both are RO carve-outs of the RW root,
225
- // last-op-wins.
226
- function appendBlockedCreation(argv: string[], policy: SandboxPolicy): void {
227
- for (const file of policy.blockedCreation?.files ?? []) {
228
- argv.push('--ro-bind', '/dev/null', file)
229
- }
230
- }
231
-
232
240
  // Rendered after every bind (incl. the /tmp session bind in policy.mounts) so
233
241
  // last-op-wins keeps the symlink: a `/tmp/.foo` dest emitted before the /tmp
234
242
  // bind would be erased by it. `--dir` ensures the symlink's parent exists inside
@@ -267,6 +275,20 @@ function resolveEnv(env: SandboxEnvPolicy | undefined): Record<string, string> {
267
275
  return resolved
268
276
  }
269
277
 
278
+ // The exact env for the bwrap parent process: the --setenv/passthrough values
279
+ // PLUS a one-shot snapshot of each inherited name's current value. Because the
280
+ // parent starts from exactly this map (and nothing else), a key added to the
281
+ // live process.env after this point cannot be inherited — closing the
282
+ // build-to-spawn TOCTOU on the --unsetenv enumeration.
283
+ function resolveSpawnEnv(env: SandboxEnvPolicy | undefined): Record<string, string> {
284
+ const resolved = resolveEnv(env)
285
+ for (const name of env?.inherit ?? []) {
286
+ const value = process.env[name]
287
+ if (value !== undefined) resolved[name] = value
288
+ }
289
+ return resolved
290
+ }
291
+
270
292
  // Token-boundary match: the normalized command must equal a prefix exactly or
271
293
  // start with `prefix + ' '`. Substring matching would let `git-evil ...` slip
272
294
  // past a `git` prefix; this does not.
@@ -0,0 +1,18 @@
1
+ export const CANONICAL_AGENT_SECRET_DIRS = [
2
+ 'workspace/.config/gws',
3
+ 'workspace/.agent-messenger',
4
+ '.typeclaw/home',
5
+ ] as const
6
+
7
+ export const CANONICAL_AGENT_SECRET_FILES = ['.env', 'secrets.json', 'auth.json'] as const
8
+
9
+ export const CANONICAL_HOME_SECRET_DIRS = [
10
+ '.ssh',
11
+ '.config/gh',
12
+ '.config/gws',
13
+ '.agent-messenger',
14
+ '.codex',
15
+ '.claude',
16
+ ] as const
17
+
18
+ export const CANONICAL_HOME_SECRET_FILES = ['.gitconfig', '.claude.json', '.netrc'] as const
@@ -0,0 +1,80 @@
1
+ import { DEFAULT_SANDBOX_ENV } from './policy'
2
+
3
+ // DEFAULT_SANDBOX_ENV names are sandbox-OWNED: build.ts renders them via
4
+ // --setenv, but an inherited name skips that --setenv (inherit keeps the parent
5
+ // value), so letting `.env` PATH/HOME/BUN_* through would REPLACE the sandbox's
6
+ // safe fixed values — a PATH/loader hijack of the sandbox mechanism itself.
7
+ const RESERVED_SANDBOX_ENV_NAMES = new Set(Object.keys(DEFAULT_SANDBOX_ENV))
8
+
9
+ // Names TypeClaw's own runtime/broker OWNS: github-cli-auth gates GH_TOKEN /
10
+ // GITHUB_TOKEN behind a capability + command-scoped overlay (only a validated
11
+ // `gh` call gets the token, out of argv), and the TYPECLAW_* tokens are
12
+ // host/container-injected auth. Ambient inheritance would bypass the broker and
13
+ // hand a reusable credential to arbitrary bash — so these are withheld even when
14
+ // declared in `.env`. Not a credential-name registry: these five names are ones
15
+ // the runtime CLAIMS, distinct from operator credentials (which belong in
16
+ // secrets.json). A matching `.env` line would otherwise make the runtime value
17
+ // eligible; the parsed-value gate (below) also blocks the empty-declaration case.
18
+ const RUNTIME_OWNED_ENV_NAMES = new Set<string>([
19
+ 'GH_TOKEN',
20
+ 'GITHUB_TOKEN',
21
+ 'TYPECLAW_TUI_TOKEN',
22
+ 'TYPECLAW_HOSTD_TOKEN',
23
+ 'TYPECLAW_HOSTD_BROKER_TOKEN',
24
+ ])
25
+
26
+ // Process-hijack vectors: an inherited value here changes how the shell, loader,
27
+ // or a runtime INTERPRETS later commands (arbitrary code load, config override,
28
+ // credential-socket handoff). SHELLOPTS/BASHOPTS/PS4/BASH_XTRACEFD and the
29
+ // BASH_FUNC_ prefix are OUTER-shell controls that execute in the `bash -c` that
30
+ // launches bwrap — before confinement begins (e.g. SHELLOPTS=xtrace + a
31
+ // command-substituting PS4, or an exported `BASH_FUNC_bwrap%%` replacing the
32
+ // bwrap command). These subvert the sandbox rather than expose a value.
33
+ const EXECUTION_CONTROL_ENV_NAMES = new Set<string>([
34
+ 'BASH_ENV',
35
+ 'ENV',
36
+ 'SHELLOPTS',
37
+ 'BASHOPTS',
38
+ 'PS4',
39
+ 'BASH_XTRACEFD',
40
+ 'LD_PRELOAD',
41
+ 'LD_LIBRARY_PATH',
42
+ 'LD_AUDIT',
43
+ 'NODE_OPTIONS',
44
+ 'BUN_OPTIONS',
45
+ 'PYTHONPATH',
46
+ 'PYTHONSTARTUP',
47
+ 'RUBYOPT',
48
+ 'PERL5OPT',
49
+ 'SSH_AUTH_SOCK',
50
+ 'KUBECONFIG',
51
+ ])
52
+
53
+ const EXECUTION_CONTROL_ENV_PREFIXES = ['GIT_CONFIG', 'BASH_FUNC_'] as const
54
+
55
+ // Withheld ONLY when the name would compromise sandbox integrity or the runtime
56
+ // credential broker — not for being credential-shaped. `.env` is the operator's
57
+ // expose-to-the-agent surface: every value they declare there reaches model bash
58
+ // by design. Credentials that must stay hidden belong in secrets.json.
59
+ function isWithheldEnvName(name: string): boolean {
60
+ if (RESERVED_SANDBOX_ENV_NAMES.has(name)) return true
61
+ if (RUNTIME_OWNED_ENV_NAMES.has(name)) return true
62
+ if (EXECUTION_CONTROL_ENV_NAMES.has(name)) return true
63
+ return EXECUTION_CONTROL_ENV_PREFIXES.some((prefix) => name === prefix || name.startsWith(prefix))
64
+ }
65
+
66
+ // Every name an operator declared in the `.env` FILE with a non-empty value,
67
+ // minus the sandbox-integrity/broker withholds. Eligibility is decided from the
68
+ // PARSED `.env` value, never process.env: an empty `.env` line (`X=`) is not an
69
+ // operator expose-choice even if hydrateChannelEnvFromSecrets later fills
70
+ // process.env[X] from secrets.json. The inherited VALUE is still snapshotted
71
+ // from process.env at spawn time.
72
+ export function resolveExposableEnvNames(declaredEnv: ReadonlyMap<string, string>): string[] {
73
+ const out: string[] = []
74
+ for (const [name, fileValue] of declaredEnv) {
75
+ if (fileValue.length === 0) continue
76
+ if (isWithheldEnvName(name)) continue
77
+ out.push(name)
78
+ }
79
+ return out
80
+ }
@@ -7,6 +7,13 @@ export class SandboxUnavailableError extends Error {
7
7
  }
8
8
  }
9
9
 
10
+ export class SandboxMaskTargetError extends Error {
11
+ override readonly name = 'SandboxMaskTargetError'
12
+ constructor(target: string, reason: string) {
13
+ super(`sandbox canonical mask target is unsafe: ${target} (${reason}). Refusing to run model-driven bash.`)
14
+ }
15
+ }
16
+
10
17
  // Raised by the optional command-filter knobs (allowPrefixes,
11
18
  // rejectShellMetacharacters). These are consumer-opt-in restrictions layered
12
19
  // ABOVE the always-on kernel containment, so a rejection here is a policy
@@ -20,9 +27,9 @@ export class SandboxPolicyError extends Error {
20
27
  }
21
28
 
22
29
  // Raised when the /proc strategy degraded to the empty `tmpfs` fallback AND the
23
- // command needs a real /proc (a bun install / bunx / bun run that reads the
30
+ // command needs a real /proc (bunx / bun run that reads the
24
31
  // kernel-backed /proc/self/{fd,maps}). Without this pre-check Bun aborts deep in
25
- // its install pipeline with the opaque "NotDir" (ENOTDIR) error, which the model
32
+ // its runner pipeline with the opaque "NotDir" (ENOTDIR) error, which the model
26
33
  // misreads as a bad package or a transient hiccup and retries forever. Surfacing
27
34
  // it here, before the command runs, turns the failure into one the operator (or
28
35
  // the model) can act on: it is an environment/runtime limitation, not the
@@ -31,8 +38,8 @@ export class SandboxDegradedProcError extends Error {
31
38
  override readonly name = 'SandboxDegradedProcError'
32
39
  constructor() {
33
40
  super(
34
- 'sandbox /proc is in degraded tmpfs mode, so bun package commands ' +
35
- '(bun install / bun add / bunx / bun run) cannot run: Bun needs a real ' +
41
+ 'sandbox /proc is in degraded tmpfs mode, so bun package runners ' +
42
+ '(bunx / bun x / bun create / bun run) cannot run: Bun needs a real ' +
36
43
  '/proc/self/fd, which this strategy cannot provide, and would otherwise ' +
37
44
  'fail with an opaque "NotDir" error. This is a container/runtime limitation ' +
38
45
  '(no usable user namespaces for the cap-free proc-bind strategy), not a ' +
@@ -59,8 +66,8 @@ export class SandboxProcProbeUnverifiedError extends Error {
59
66
  super(
60
67
  'sandbox /proc strategy could not be verified right now: the cap-free ' +
61
68
  'proc-bind safety probe stayed inconclusive (usually transient load on the ' +
62
- 'host while the container was starting up), so this bun package command ' +
63
- '(bun install / bun add / bunx / bun run) was held back rather than run ' +
69
+ 'host while the container was starting up), so this bun package runner ' +
70
+ '(bunx / bun x / bun create / bun run) was held back rather than run ' +
64
71
  'under a broken /proc. This is almost certainly temporary and NOT a problem ' +
65
72
  'with the command or the package: retry the SAME command in a few seconds — ' +
66
73
  'the next attempt re-probes and normally succeeds.',
@@ -1,44 +1,65 @@
1
- import { lstat, mkdir, writeFile } from 'node:fs/promises'
2
- import { join } from 'node:path'
1
+ import { lstat, mkdir, opendir, writeFile } from 'node:fs/promises'
2
+ import { join, sep } from 'node:path'
3
3
 
4
4
  import type { SessionOrigin } from '@/agent/session-origin'
5
5
  import { CORE_PERMISSIONS } from '@/permissions/builtins'
6
6
  import type { PermissionService } from '@/permissions/permissions'
7
7
 
8
+ import { CANONICAL_AGENT_SECRET_DIRS, CANONICAL_AGENT_SECRET_FILES } from './canonical-secrets'
9
+ import { SandboxMaskTargetError } from './errors'
10
+
8
11
  export type HiddenPaths = {
9
12
  dirs: string[]
10
13
  files: string[]
11
14
  }
12
15
 
13
16
  const PRIVATE_DIRS = ['workspace', 'memory', 'sessions'] as const
14
- const SECRET_FILES = ['.env', 'secrets.json'] as const
17
+ const MAX_CANONICAL_SECRET_SCAN_ENTRIES = 4096
15
18
 
16
- // The agent's private working surface and credential files are masked from
17
- // sandboxed bash unless the resolved role carries the matching fs.see.* grant.
19
+ // The ordinary private working surface is role-scoped, but canonical credential
20
+ // files and runtime-owned credential directories are always masked.
18
21
  // `permissions.has` resolves the role from the live origin and fails safe to
19
22
  // guest (empty permissions) for an unclear/undefined origin, so a missing
20
23
  // grant — whether from a low tier or an unresolvable author — hides the path.
21
24
  //
22
- // The security.bypass.* fallback keeps custom roles (which may never name the
23
- // fs.see.* strings) working by capability: a role trusted enough to bypass
24
- // medium-severity guards is treated as trusted for filesystem visibility, and
25
- // bypass.low maps to the private-surface tier. fs.see.* always wins when
26
- // present; the fallback only fires when it is absent.
25
+ // The security.bypass.* fallback keeps custom roles (which may never name
26
+ // fs.see.private) working by capability. fs.see.secrets remains useful for
27
+ // runtime-owned credential injection, but it deliberately cannot make raw
28
+ // .env, secrets.json, or historical auth.json bytes available to an LLM.
29
+ // Privileged diagnostics must
30
+ // use host-side commands that report presence/status without returning values.
27
31
  export function resolveHiddenPaths(
28
32
  permissions: PermissionService,
29
33
  origin: SessionOrigin | undefined,
30
34
  agentDir: string,
31
35
  ): HiddenPaths {
32
- const seesPrivate =
33
- permissions.has(origin, CORE_PERMISSIONS.fsSeePrivate) ||
34
- permissions.has(origin, 'security.bypass.low') ||
35
- permissions.has(origin, 'security.bypass.medium')
36
+ const seesPrivate = canSeePrivateSurface(permissions, origin)
37
+ const dirs = [
38
+ ...CANONICAL_AGENT_SECRET_DIRS.map((dir) => join(agentDir, dir)),
39
+ ...(seesPrivate ? [] : PRIVATE_DIRS.map((dir) => join(agentDir, dir))),
40
+ ]
41
+ const files = CANONICAL_AGENT_SECRET_FILES.map((f) => join(agentDir, f))
42
+ return { dirs, files }
43
+ }
44
+
45
+ // Before canonical secret masking became unconditional, roles carrying both
46
+ // visibility capabilities ran bash unsandboxed and therefore had full write
47
+ // access to the agent root. They now enter bwrap so canonical credential paths
48
+ // can be masked, but must retain ordinary root-write capability. The policy
49
+ // overlays the secret masks after the RW root bind, so this does not restore raw
50
+ // credential access.
51
+ export function canWriteAgentRootInSandbox(permissions: PermissionService, origin: SessionOrigin | undefined): boolean {
36
52
  const seesSecrets =
37
53
  permissions.has(origin, CORE_PERMISSIONS.fsSeeSecrets) || permissions.has(origin, 'security.bypass.medium')
54
+ return canSeePrivateSurface(permissions, origin) && seesSecrets
55
+ }
38
56
 
39
- const dirs = seesPrivate ? [] : PRIVATE_DIRS.map((d) => join(agentDir, d))
40
- const files = seesSecrets ? [] : SECRET_FILES.map((f) => join(agentDir, f))
41
- return { dirs, files }
57
+ function canSeePrivateSurface(permissions: PermissionService, origin: SessionOrigin | undefined): boolean {
58
+ return (
59
+ permissions.has(origin, CORE_PERMISSIONS.fsSeePrivate) ||
60
+ permissions.has(origin, 'security.bypass.low') ||
61
+ permissions.has(origin, 'security.bypass.medium')
62
+ )
42
63
  }
43
64
 
44
65
  // SECURITY / bwrap contract: the mask ops REQUIRE a pre-existing target.
@@ -51,31 +72,78 @@ export function resolveHiddenPaths(
51
72
  // here (only sandboxed bash sees it RO), so an empty placeholder is harmless and
52
73
  // the mask binds over a real empty file, leaking nothing.
53
74
  //
54
- // ENSURE, not FILTER: package-install mode makes the jail root RW
75
+ // ENSURE, not FILTER: privileged modes make the jail root RW
55
76
  // (`writableRoot: agentDir`), so dropping an absent secret would let sandboxed
56
- // code CREATE `.env`/`secrets.json` for real (planting) or expose one created
77
+ // code CREATE a canonical credential path for real (planting) or expose one created
57
78
  // mid-session (TOCTOU). A guaranteed target keeps the mask always rendered over
58
- // it (last-op-wins), closing that hole for both jail modes. A symlink squatting
59
- // a target is refused and dropped (a bind would follow it out), and each target
60
- // is best-effort so one bad entry degrades that mask, never aborts sandboxing.
79
+ // it (last-op-wins), closing that hole for every mode. Required masks are
80
+ // fail-closed: symlinks, wrong entry kinds, hardlinked files, materialization
81
+ // failures, or a late identity change abort bash.
61
82
  export async function ensureHiddenMaskTargets(hidden: HiddenPaths): Promise<HiddenPaths> {
62
- const dirs = await ensureMaskTargets(hidden.dirs, 'dir')
63
- const files = await ensureMaskTargets(hidden.files, 'file')
83
+ const dirs = await Promise.all(hidden.dirs.map((target) => ensureRequiredDirMaskTarget(target)))
84
+ const files = await Promise.all(hidden.files.map((target) => ensureRequiredFileMaskTarget(target)))
64
85
  return { dirs, files }
65
86
  }
66
87
 
67
- async function ensureMaskTargets(targets: string[], kind: 'dir' | 'file'): Promise<string[]> {
68
- const results = await Promise.all(targets.map((target) => ensureMaskTarget(target, kind)))
69
- return targets.filter((_, i) => results[i])
88
+ export async function verifyHiddenMaskTargets(hidden: HiddenPaths): Promise<void> {
89
+ await Promise.all(hidden.dirs.map((target) => verifyRequiredMaskTarget(target, 'dir')))
90
+ await Promise.all(hidden.files.map((target) => verifyRequiredMaskTarget(target, 'file')))
70
91
  }
71
92
 
72
- async function ensureMaskTarget(target: string, kind: 'dir' | 'file'): Promise<boolean> {
73
- try {
74
- if (kind === 'dir') await mkdir(target, { recursive: true })
75
- else await ensureEmptyFile(target)
76
- return await isRealEntry(target, kind)
77
- } catch {
78
- return false
93
+ async function ensureRequiredDirMaskTarget(target: string): Promise<string> {
94
+ await mkdir(target, { recursive: true }).catch(() => {})
95
+ await verifyRequiredMaskTarget(target, 'dir')
96
+ return target
97
+ }
98
+
99
+ async function ensureRequiredFileMaskTarget(target: string): Promise<string> {
100
+ await ensureEmptyFile(target)
101
+ await verifyRequiredMaskTarget(target, 'file')
102
+ return target
103
+ }
104
+
105
+ async function verifyRequiredMaskTarget(target: string, kind: 'dir' | 'file'): Promise<void> {
106
+ const stats = await lstat(target).catch(() => {
107
+ throw new SandboxMaskTargetError(target, `could not materialize or inspect a ${kind}`)
108
+ })
109
+ if (stats.isSymbolicLink()) throw new SandboxMaskTargetError(target, 'symlinks are not maskable safely')
110
+ if (kind === 'dir' && !stats.isDirectory()) throw new SandboxMaskTargetError(target, 'target is not a directory')
111
+ if (kind === 'file' && !stats.isFile()) throw new SandboxMaskTargetError(target, 'target is not a regular file')
112
+ if (kind === 'file' && stats.nlink !== 1) throw new SandboxMaskTargetError(target, 'target has hardlink aliases')
113
+ if (kind === 'dir' && isCanonicalSecretDir(target)) await rejectHardlinksUnderCanonicalDir(target)
114
+ }
115
+
116
+ function isCanonicalSecretDir(target: string): boolean {
117
+ return CANONICAL_AGENT_SECRET_DIRS.some((dir) => target.endsWith(`${sep}${dir.split('/').join(sep)}`))
118
+ }
119
+
120
+ async function rejectHardlinksUnderCanonicalDir(root: string): Promise<void> {
121
+ const pending = [root]
122
+ let visited = 0
123
+ while (pending.length > 0) {
124
+ const current = pending.pop() as string
125
+ const dir = await opendir(current).catch(() => {
126
+ throw new SandboxMaskTargetError(root, 'canonical secret directory could not be scanned safely')
127
+ })
128
+ try {
129
+ for await (const entry of dir) {
130
+ visited += 1
131
+ if (visited > MAX_CANONICAL_SECRET_SCAN_ENTRIES) {
132
+ throw new SandboxMaskTargetError(root, 'canonical secret directory exceeds bounded hardlink scan')
133
+ }
134
+ const child = join(current, entry.name)
135
+ const stats = await lstat(child)
136
+ if (stats.isSymbolicLink()) continue
137
+ if (stats.isDirectory()) pending.push(child)
138
+ if (stats.isFile() && stats.nlink !== 1) {
139
+ throw new SandboxMaskTargetError(root, `file under canonical secret directory has hardlink aliases: ${child}`)
140
+ }
141
+ }
142
+ } finally {
143
+ try {
144
+ await dir.close()
145
+ } catch {}
146
+ }
79
147
  }
80
148
  }
81
149
 
@@ -88,13 +156,3 @@ async function ensureEmptyFile(target: string): Promise<void> {
88
156
  // else is dropped from the mask.
89
157
  }
90
158
  }
91
-
92
- async function isRealEntry(target: string, kind: 'dir' | 'file'): Promise<boolean> {
93
- try {
94
- const stats = await lstat(target)
95
- if (stats.isSymbolicLink()) return false
96
- return kind === 'dir' ? stats.isDirectory() : stats.isFile()
97
- } catch {
98
- return false
99
- }
100
- }
@@ -1,4 +1,10 @@
1
1
  export { buildSandboxedCommand, type SandboxedCommand } from './build'
2
+ export {
3
+ CANONICAL_AGENT_SECRET_DIRS,
4
+ CANONICAL_AGENT_SECRET_FILES,
5
+ CANONICAL_HOME_SECRET_DIRS,
6
+ CANONICAL_HOME_SECRET_FILES,
7
+ } from './canonical-secrets'
2
8
  export {
3
9
  buildProcBindProbeScript,
4
10
  canBindProcSafely,
@@ -13,22 +19,34 @@ export {
13
19
  _resetProcBindProbeCacheForTests,
14
20
  _resetRealProcProbeCacheForTests,
15
21
  } from './availability'
16
- export { ensureHiddenMaskTargets, resolveHiddenPaths, type HiddenPaths } from './hidden-paths'
17
22
  export {
18
- resolvePackageInstallZones,
23
+ canWriteAgentRootInSandbox,
24
+ ensureHiddenMaskTargets,
25
+ resolveHiddenPaths,
26
+ verifyHiddenMaskTargets,
27
+ type HiddenPaths,
28
+ } from './hidden-paths'
29
+ export {
19
30
  resolveProtectedZones,
20
31
  resolveWritableZones,
32
+ isGitControlPath,
21
33
  subtractMasked,
22
- type PackageInstallZones,
23
34
  type ProtectedZones,
24
35
  type WritableZones,
25
36
  } from './writable-zones'
26
37
  export { resolveSandboxSymlinks, type SandboxSymlinkSpec } from './symlinks'
27
- export { commandNeedsRealProc, isPackageInstallCommand } from './package-install'
38
+ export { commandNeedsRealProc } from './package-install'
39
+ export {
40
+ cleanupPrivilegedSandboxRuntime,
41
+ resolvePrivilegedSandboxRuntime,
42
+ verifyPrivilegedSandboxRuntime,
43
+ type PrivilegedSandboxRuntime,
44
+ } from './privileged-runtime'
28
45
  export { ensureSessionTmpDir, isUnderTmp, mapVirtualTmpPath, SESSION_TMP_ROOT, sessionTmpDir } from './session-tmp'
29
46
  export { formatCommand, shellQuote } from './quote'
30
47
  export {
31
48
  SandboxDegradedProcError,
49
+ SandboxMaskTargetError,
32
50
  SandboxPolicyError,
33
51
  SandboxProcProbeUnverifiedError,
34
52
  SandboxUnavailableError,
@@ -1,27 +1,3 @@
1
- // Recognizes the narrow command class that earns the package-install sandbox
2
- // mode (RW project root). Deliberately conservative: a single standalone local
3
- // `bun add` / `bun install` / `bun i` with NO shell metacharacters, chaining,
4
- // redirects, or substitution. Anything fancier (`bun add x && rm -rf …`,
5
- // `bun add x; curl …`, a subshell, a pipe) falls back to the default ro-root
6
- // jail so the broad RW root can never be piggybacked onto an attacker-controlled
7
- // second command. Global installs (`-g` / `--global`) are excluded — the
8
- // bun-hygiene guard already blocks them and they write outside the jail anyway.
9
- const SHELL_METACHARACTERS = /[;&|`$()<>\\\n\r{}!*?[\]"']/
10
-
11
- const GLOBAL_FLAG = /^(-g|--global)$/
12
-
13
- export function isPackageInstallCommand(command: string): boolean {
14
- if (SHELL_METACHARACTERS.test(command)) return false
15
-
16
- const words = command.trim().split(/\s+/)
17
- if (words[0] !== 'bun') return false
18
-
19
- const subcommand = words[1]
20
- if (subcommand !== 'add' && subcommand !== 'install' && subcommand !== 'i') return false
21
-
22
- return !words.some((word) => GLOBAL_FLAG.test(word))
23
- }
24
-
25
1
  // The bun subcommands whose work (or whose spawned child) reads the kernel-backed
26
2
  // /proc/self/{fd,maps} magic symlinks: package installs (add/install/i), the
27
3
  // package runners (x/create), and `run` (which can exec a package bin). Under the
@@ -41,11 +17,11 @@ const SHELL_COMMAND_SEPARATOR = /(?:&&|\|\||[;|&\n()])+/
41
17
 
42
18
  // Whether a command will exercise the real /proc, so a caller can turn the
43
19
  // degraded-mode `tmpfs` fallback into an actionable diagnostic instead of letting
44
- // Bun surface its opaque "NotDir". UNLIKE isPackageInstallCommand this is a
45
- // DIAGNOSTIC heuristic, not a privilege gate — it deliberately fires through shell
20
+ // Bun surface its opaque "NotDir". This is a DIAGNOSTIC heuristic, not a
21
+ // privilege gate — it deliberately fires through shell
46
22
  // metacharacters and chained preludes (a `cd app && bunx foo` still runs bunx) and
47
23
  // never widens the sandbox surface, so erring toward catching more only improves
48
- // the error message.
24
+ // the error message. It is not an authorization boundary.
49
25
  export function commandNeedsRealProc(command: string): boolean {
50
26
  return command.split(SHELL_COMMAND_SEPARATOR).some((segment) => segmentInvokesRealProcBun(segment.trim()))
51
27
  }
@@ -9,7 +9,7 @@ export type SandboxNetwork = 'none' | 'inherit'
9
9
  // 'proc-bind' (the runtime default): --ro-bind /proc /proc binds the container's
10
10
  // ALREADY-REAL procfs straight into the sandbox — no `unshare --mount-proc`, no
11
11
  // CAP_SYS_ADMIN. A JS package runner's child gets a real /proc/self/{fd,maps,exe}
12
- // so `bunx`/`bun add`/`bun run <pkg-bin>` stop aborting with Bun's ENOTDIR. The
12
+ // so allowed `bunx`/`bun run <pkg-bin>` calls stop aborting with Bun's ENOTDIR. The
13
13
  // agent runtime's /proc/<agent>/environ (OPENAI_API_KEY, GH_TOKEN) is NOT
14
14
  // leaked: build.ts always emits --unshare-user, so the sandboxed bash runs as
15
15
  // mapped-root in a CHILD user namespace that is not an ancestor of the agent
@@ -37,6 +37,11 @@ export type SandboxProcStrategy = 'tmpfs' | 'none' | 'real-proc' | 'proc-bind'
37
37
  export type SandboxEnvPolicy = {
38
38
  set?: Record<string, string>
39
39
  passthrough?: string[]
40
+ // Preserve these names from bwrap's parent environment without rendering
41
+ // their values in argv. The builder switches from --clearenv to explicit
42
+ // --unsetenv for every other inherited name. Reserved for command-scoped
43
+ // secrets whose parent process is protected by the child-userns boundary.
44
+ inherit?: string[]
40
45
  }
41
46
 
42
47
  export type SandboxCommandFilter = {
@@ -94,36 +99,18 @@ export type SandboxSymlinkOp = {
94
99
  dest: string
95
100
  }
96
101
 
97
- // A single RW bind of the project root, used ONLY by the package-install path
98
- // (recognized standalone `bun add`/`bun install` commands). `bun add` writes
99
- // node_modules/ AND a temp lockfile (`bun.lock.NNN.tmp`, atomically renamed)
100
- // directly under the root, so a file-level RW bind of `bun.lock` alone is
101
- // insufficient — Bun needs DIRECTORY write to create its temp file. The default
102
- // ro-root + narrow carve-out model can't express that, so this widens the root
103
- // to RW for that command class only.
102
+ // A single RW bind that preserves ordinary agent-root writes for trusted/owner
103
+ // callers. Masks and protected zones overlay it; writableRoot provides no
104
+ // package-install isolation.
104
105
  //
105
106
  // CRITICAL ordering: unlike `writable` (rendered AFTER masks), `writableRoot`
106
107
  // renders BEFORE masks so the broad RW root does not re-expose secrets. With
107
108
  // last-op-wins the chain is: ro-bind root → writableRoot (RW root) → masks
108
- // (re-hide .env/secrets.json/private dirs) → protected (re-RO node_modules/typeclaw,
109
- // packages, .agents/skills, .git/hooks, .git/config). Everything stays hidden or
110
- // EROFS except the dirs a dependency install legitimately needs to write.
109
+ // (re-hide .env/secrets.json/private dirs) → protected (.git/hooks/.git/config).
111
110
  export type SandboxWritableRootPolicy = {
112
111
  dir: string
113
112
  }
114
113
 
115
- // Paths whose CREATION must be blocked under a writable root, rendered as
116
- // `--ro-bind /dev/null <path>`. Used by the package-install path for the
117
- // semantically-guarded managed files (cron.json / typeclaw.json) when they are
118
- // ABSENT: the RW root would otherwise let a postinstall lifecycle script create
119
- // them, bypassing the write/edit-tool guards. Binding /dev/null occupies the
120
- // path with an empty read-only object (blocking creation) WITHOUT manufacturing
121
- // a real invalid file on the host FS. Renders after writableRoot, with the
122
- // protected binds, so last-op-wins keeps the path occupied.
123
- export type SandboxBlockedCreationPolicy = {
124
- files?: string[]
125
- }
126
-
127
114
  export type SandboxPolicy = {
128
115
  bwrapPath?: string
129
116
  cwd?: string
@@ -140,7 +127,6 @@ export type SandboxPolicy = {
140
127
  masks?: SandboxMaskPolicy
141
128
  writable?: SandboxWritablePolicy
142
129
  protected?: SandboxProtectedPolicy
143
- blockedCreation?: SandboxBlockedCreationPolicy
144
130
  symlinks?: SandboxSymlinkOp[]
145
131
  network?: SandboxNetwork
146
132
  env?: SandboxEnvPolicy
@@ -158,7 +144,7 @@ export type SandboxPolicy = {
158
144
  //
159
145
  // BUN_TMPDIR / BUN_INSTALL both point under /tmp because `--clearenv` strips
160
146
  // the host's TMPDIR, and bun refuses to run without a writable scratch dir it
161
- // can discover: `bunx`, `bun add`, and `bun run <pkg-bin>` abort with
147
+ // can discover: `bunx` and `bun run <pkg-bin>` abort with
162
148
  // "Unexpected accessing temporary directory. Please set $BUN_TMPDIR or
163
149
  // $BUN_INSTALL". /tmp is always writable inside the sandbox (fresh tmpfs, or
164
150
  // the per-session bind that overrides it), so both are safe targets. Without