typeclaw 0.45.1 → 0.46.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) 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 +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 +161 -39
  9. package/src/agent/network/response-body.ts +26 -0
  10. package/src/agent/network/safe-http.ts +207 -0
  11. package/src/agent/plugin-tools.ts +377 -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 +1310 -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 +163 -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 +30 -0
  30. package/src/agent/turn-runner.ts +86 -6
  31. package/src/bundled-plugins/backup/README.md +23 -10
  32. package/src/bundled-plugins/backup/git-auth.ts +6 -4
  33. package/src/bundled-plugins/backup/index.ts +85 -44
  34. package/src/bundled-plugins/backup/runner.ts +85 -1
  35. package/src/bundled-plugins/doc-render/render.ts +93 -12
  36. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  37. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  38. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  39. package/src/bundled-plugins/github-cli-auth/git-askpass.ts +74 -26
  40. package/src/bundled-plugins/github-cli-auth/git-command.ts +224 -36
  41. package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +9 -9
  42. package/src/bundled-plugins/github-cli-auth/index.ts +207 -132
  43. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  44. package/src/bundled-plugins/github-cli-auth/token-class.ts +4 -6
  45. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  46. package/src/bundled-plugins/memory/README.md +32 -11
  47. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  48. package/src/bundled-plugins/memory/citations.ts +22 -9
  49. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  50. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  51. package/src/bundled-plugins/memory/index.ts +0 -4
  52. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  53. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  54. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  55. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  56. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  57. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  58. package/src/bundled-plugins/memory/vector/embed-threads.ts +36 -0
  59. package/src/bundled-plugins/memory/vector/embedder.ts +19 -1
  60. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  61. package/src/bundled-plugins/researcher/write-report.ts +8 -5
  62. package/src/bundled-plugins/reviewer/index.ts +2 -2
  63. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  64. package/src/bundled-plugins/reviewer/skills/code-review.ts +19 -9
  65. package/src/bundled-plugins/scout/scout.ts +8 -0
  66. package/src/bundled-plugins/security/index.ts +4 -4
  67. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  68. package/src/bundled-plugins/security/policies/private-surface-read.ts +787 -36
  69. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  70. package/src/bundled-plugins/security/policies/ssrf.ts +147 -42
  71. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  72. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  73. package/src/channels/adapters/discord-bot.ts +66 -6
  74. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  75. package/src/channels/adapters/discord-id.ts +4 -0
  76. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  77. package/src/channels/adapters/discord.ts +57 -7
  78. package/src/channels/adapters/github/auth-app.ts +41 -12
  79. package/src/channels/adapters/github/inbound.ts +11 -0
  80. package/src/channels/adapters/github/index.ts +71 -65
  81. package/src/channels/adapters/github/reconcile-cooldown-store.ts +178 -0
  82. package/src/channels/adapters/github/reconcile-open-prs.ts +31 -0
  83. package/src/channels/adapters/github/review-submitter.ts +302 -0
  84. package/src/channels/adapters/kakaotalk-channel-resolver.ts +5 -3
  85. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  86. package/src/channels/adapters/kakaotalk-typing.ts +17 -15
  87. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  88. package/src/channels/adapters/slack-bot-edit.ts +85 -20
  89. package/src/channels/adapters/slack-bot.ts +26 -10
  90. package/src/channels/adapters/slack-classify.ts +21 -2
  91. package/src/channels/adapters/slack-format.ts +245 -0
  92. package/src/channels/adapters/slack.ts +59 -7
  93. package/src/channels/adapters/telegram-bot.ts +18 -5
  94. package/src/channels/adapters/webex-bot.ts +8 -3
  95. package/src/channels/adapters/webex.ts +8 -3
  96. package/src/channels/fetch-attachment.ts +43 -0
  97. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  98. package/src/channels/github-token-bridge.ts +12 -6
  99. package/src/channels/manager.ts +9 -0
  100. package/src/channels/router.ts +248 -6
  101. package/src/channels/types.ts +28 -1
  102. package/src/cli/channel.ts +1 -1
  103. package/src/cli/init.ts +1 -1
  104. package/src/cli/model.ts +57 -7
  105. package/src/compose/stop.ts +17 -5
  106. package/src/config/config.ts +6 -6
  107. package/src/config/models-mutation.ts +13 -1
  108. package/src/config/providers.ts +176 -0
  109. package/src/container/docker-app.ts +42 -13
  110. package/src/container/start.ts +62 -10
  111. package/src/cron/bridge.ts +9 -2
  112. package/src/doctor/checks.ts +8 -3
  113. package/src/doctor/commit.ts +2 -1
  114. package/src/doctor/file-ownership.ts +52 -0
  115. package/src/dreams/git.ts +2 -1
  116. package/src/git/bound-gc-config.ts +82 -0
  117. package/src/git/hookless.ts +5 -0
  118. package/src/git/reconcile-ignored.ts +18 -5
  119. package/src/git/system-commit.ts +12 -6
  120. package/src/hostd/spawn.ts +133 -47
  121. package/src/init/dockerfile.ts +99 -5
  122. package/src/init/index.ts +17 -5
  123. package/src/init/models-dev.ts +4 -0
  124. package/src/init/validate-api-key.ts +2 -0
  125. package/src/inspect/replay.ts +21 -9
  126. package/src/inspect/session-list.ts +71 -33
  127. package/src/mcp/tools.ts +17 -3
  128. package/src/network/internal-destinations.ts +267 -0
  129. package/src/permissions/builtins.ts +3 -1
  130. package/src/plugin/context.ts +2 -0
  131. package/src/plugin/index.ts +1 -0
  132. package/src/plugin/manager.ts +4 -0
  133. package/src/plugin/types.ts +22 -0
  134. package/src/run/index.ts +40 -0
  135. package/src/run/llm-fetch-observer.ts +41 -4
  136. package/src/sandbox/build.ts +37 -15
  137. package/src/sandbox/canonical-secrets.ts +18 -0
  138. package/src/sandbox/env-exposure.ts +83 -0
  139. package/src/sandbox/errors.ts +13 -6
  140. package/src/sandbox/hidden-paths.ts +102 -44
  141. package/src/sandbox/index.ts +22 -4
  142. package/src/sandbox/package-install.ts +3 -27
  143. package/src/sandbox/policy.ts +16 -28
  144. package/src/sandbox/privileged-runtime.ts +256 -0
  145. package/src/sandbox/session-tmp.ts +8 -2
  146. package/src/sandbox/writable-zones.ts +204 -140
  147. package/src/secrets/index.ts +8 -0
  148. package/src/secrets/refresh-provider-oauth.ts +128 -0
  149. package/src/server/command-runner.ts +48 -4
  150. package/src/server/index.ts +4 -0
  151. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  152. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  153. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  154. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  155. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  156. package/src/skills/typeclaw-config/SKILL.md +27 -11
  157. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  158. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  159. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  160. package/src/skills/typeclaw-permissions/SKILL.md +36 -19
  161. package/src/skills/typeclaw-plugins/SKILL.md +37 -0
  162. package/src/usage/scan.ts +11 -2
  163. package/typeclaw.schema.json +25 -0
@@ -104,6 +104,14 @@ const ENV_CODEX_OVERALL_MS = 'TYPECLAW_CODEX_OVERALL_MS'
104
104
  const DEFAULT_TTFB_MS = 15_000
105
105
  const DEFAULT_IDLE_MS = 120_000
106
106
  const DEFAULT_OVERALL_MS = 300_000
107
+ // Codex is healthy-FAST but silently hangs: observed header latency p50~1s /
108
+ // p99~8s / max~10.8s, yet hung requests wait out the generic 15s floor. Pinning
109
+ // 13s detects hangs ~2s sooner with ~2.2s margin over the healthy max. Pinned,
110
+ // not adaptive: codex's p95 (~5.6s) never crosses the floor so widening is a
111
+ // no-op, and a longer deadline only makes each silent hang costlier to recover.
112
+ // A concrete per-endpoint `ttfbMs` also disables adaptive eligibility for codex
113
+ // (see `usesAdaptiveTtfb`). Operator-set TYPECLAW_CODEX_TTFB_MS still overrides.
114
+ const DEFAULT_CODEX_TTFB_MS = 13_000
107
115
  const LOG_PREFIX = '[llm-fetch]'
108
116
 
109
117
  // Adaptive TTFB: give a provider that is OBSERVED to be slow-but-healthy more
@@ -248,10 +256,12 @@ export function defaultLlmFetchEndpoints(env: NodeJS.ProcessEnv = process.env):
248
256
  // GETs to the same host (auth probes, etc.) are deliberately ignored.
249
257
  match: (url, method) =>
250
258
  method === 'POST' && url.hostname === 'chatgpt.com' && url.pathname.includes('/codex/responses'),
251
- // Only pin a per-endpoint value when the operator explicitly set the
252
- // Codex-specific var; unset falls through to the generic TYPECLAW_LLM_*
253
- // (or built-in default) so it isn't masked. See readEnvMsOptional.
254
- ttfbMs: readEnvMsOptional(env, ENV_CODEX_TTFB_MS),
259
+ // TTFB is pinned to the codex-specific default (not the generic 15s) so a
260
+ // silent hang is caught fast and adaptation is bypassed for this endpoint;
261
+ // an operator-set TYPECLAW_CODEX_TTFB_MS still wins. Idle/overall keep the
262
+ // fall-through shape (unset → generic TYPECLAW_LLM_* / built-in default) so
263
+ // they aren't masked. See readEnvMsOptional and DEFAULT_CODEX_TTFB_MS.
264
+ ttfbMs: readEnvMsOptional(env, ENV_CODEX_TTFB_MS) ?? DEFAULT_CODEX_TTFB_MS,
255
265
  idleMs: readEnvMsOptional(env, ENV_CODEX_IDLE_MS),
256
266
  overallMs: readEnvMsOptional(env, ENV_CODEX_OVERALL_MS),
257
267
  },
@@ -316,6 +326,18 @@ function quote(value: string | null): string {
316
326
 
317
327
  function formatLine(fields: {
318
328
  provider: string
329
+ // The request origin (scheme+host, no path/query — non-sensitive) that scopes
330
+ // `seq`. `provider` alone is ambiguous: `openai-compatible` accepts arbitrary
331
+ // proxy origins and the observer is shared across agents, so two origins can
332
+ // each emit `provider=openai-compatible seq=1`. The origin disambiguates them
333
+ // so seq is attributable per stream.
334
+ origin: string
335
+ // Per-(provider,origin) monotonic fetch sequence. A tight run of increasing seq
336
+ // on one provider|origin is the observable signature of retry MULTIPLICATION (the
337
+ // pi-ai codex provider's internal loop stacked under typeclaw's own retries):
338
+ // it makes the physical-fetch count per logical turn countable from logs alone.
339
+ // Observability only — nothing reads this back to drive behavior.
340
+ seq: number
319
341
  status: number | null
320
342
  headersMs: number | null
321
343
  firstByteMs: number | null
@@ -329,6 +351,8 @@ function formatLine(fields: {
329
351
  return [
330
352
  LOG_PREFIX,
331
353
  `provider=${fields.provider}`,
354
+ `origin=${fields.origin}`,
355
+ `seq=${fields.seq}`,
332
356
  `status=${fields.status === null ? 'null' : fields.status}`,
333
357
  `headers_ms=${fields.headersMs === null ? 'null' : fields.headersMs}`,
334
358
  `first_byte_ms=${fields.firstByteMs === null ? 'null' : fields.firstByteMs}`,
@@ -367,6 +391,8 @@ type ResolvedTimeouts = {
367
391
 
368
392
  type BodyTapConfig = {
369
393
  provider: string
394
+ origin: string
395
+ seq: number
370
396
  idleMs: number
371
397
  overallMs: number
372
398
  scheduler: TimeoutScheduler
@@ -387,6 +413,8 @@ function attachBodyTimingTap(
387
413
  logger.info(
388
414
  formatLine({
389
415
  provider: config.provider,
416
+ origin: config.origin,
417
+ seq: config.seq,
390
418
  status,
391
419
  headersMs,
392
420
  firstByteMs: null,
@@ -412,6 +440,8 @@ function attachBodyTimingTap(
412
440
  logger.info(
413
441
  formatLine({
414
442
  provider: config.provider,
443
+ origin: config.origin,
444
+ seq: config.seq,
415
445
  status,
416
446
  headersMs,
417
447
  firstByteMs,
@@ -577,6 +607,7 @@ export function installLlmFetchObserver(opts: LlmFetchObserverOptions = {}): ()
577
607
  }
578
608
  const originalFetch = globalThis.fetch
579
609
  const adaptive = opts.adaptiveTracker ?? new AdaptiveTtfbTracker(now)
610
+ const fetchSeqByKey = new Map<string, number>()
580
611
  // Adaptation is a property of the built-in floor default only. Any explicit
581
612
  // static TTFB (observer opt, per-endpoint value, or a set TYPECLAW_*_TTFB_MS)
582
613
  // means the operator pinned a deadline — honour it verbatim, no widening.
@@ -616,6 +647,8 @@ export function installLlmFetchObserver(opts: LlmFetchObserverOptions = {}): ()
616
647
  const timeouts = resolveTimeouts(endpoint, perRequest)
617
648
  const provider = endpoint.label
618
649
  const adaptiveKey = `${provider}|${origin}`
650
+ const seq = (fetchSeqByKey.get(adaptiveKey) ?? 0) + 1
651
+ fetchSeqByKey.set(adaptiveKey, seq)
619
652
  const usesAdaptiveTtfb = adaptiveEligible && perRequest?.ttfbMs === undefined && endpoint.ttfbMs === undefined
620
653
  const effectiveTtfbMs = usesAdaptiveTtfb ? adaptive.resolve(adaptiveKey) : timeouts.ttfbMs
621
654
  const start = now()
@@ -653,6 +686,8 @@ export function installLlmFetchObserver(opts: LlmFetchObserverOptions = {}): ()
653
686
  logger.info(
654
687
  formatLine({
655
688
  provider,
689
+ origin,
690
+ seq,
656
691
  status: null,
657
692
  headersMs: null,
658
693
  firstByteMs: null,
@@ -673,6 +708,8 @@ export function installLlmFetchObserver(opts: LlmFetchObserverOptions = {}): ()
673
708
  const requestId = response.headers.get('x-request-id')
674
709
  return attachBodyTimingTap(response, start, headersMs, response.status, retryAfter, requestId, now, logger, {
675
710
  provider,
711
+ origin,
712
+ seq,
676
713
  idleMs: timeouts.idleMs,
677
714
  overallMs: timeouts.overallMs,
678
715
  scheduler,
@@ -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,83 @@
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 the runtime claims for its own control plane. The token values are
10
+ // injected at container start. The model-HTTP policy values are operator-authored
11
+ // in raw-masked `.env`, but are runtime controls rather than model inputs; exposing
12
+ // them to bash would let the model discover the private network exceptions. Not a
13
+ // credential-name registry: ordinary operator credentials still belong in
14
+ // secrets.json when they must stay hidden. GH_TOKEN / GITHUB_TOKEN are NOT here:
15
+ // `.env` is the operator's expose-to-the-agent surface, so an operator who
16
+ // declares a GitHub token there has chosen to hand it to model bash (e.g. so plain
17
+ // `gh` / `git` / `curl` work in agents with no GitHub channel). The github-cli-auth
18
+ // broker still injects a narrower per-repo token via a command-scoped overlay, and
19
+ // when both exist for the same name the overlay is deduplicated and its value wins.
20
+ const RUNTIME_OWNED_ENV_NAMES = new Set<string>([
21
+ 'TYPECLAW_TUI_TOKEN',
22
+ 'TYPECLAW_HOSTD_TOKEN',
23
+ 'TYPECLAW_HOSTD_BROKER_TOKEN',
24
+ 'TYPECLAW_MODEL_HTTP_ALLOW_INTERNAL_HOSTS',
25
+ 'TYPECLAW_MODEL_HTTP_ALLOW_INTERNAL_CIDRS',
26
+ ])
27
+
28
+ // Process-hijack vectors: an inherited value here changes how the shell, loader,
29
+ // or a runtime INTERPRETS later commands (arbitrary code load, config override,
30
+ // credential-socket handoff). SHELLOPTS/BASHOPTS/PS4/BASH_XTRACEFD and the
31
+ // BASH_FUNC_ prefix are OUTER-shell controls that execute in the `bash -c` that
32
+ // launches bwrap — before confinement begins (e.g. SHELLOPTS=xtrace + a
33
+ // command-substituting PS4, or an exported `BASH_FUNC_bwrap%%` replacing the
34
+ // bwrap command). These subvert the sandbox rather than expose a value.
35
+ const EXECUTION_CONTROL_ENV_NAMES = new Set<string>([
36
+ 'BASH_ENV',
37
+ 'ENV',
38
+ 'SHELLOPTS',
39
+ 'BASHOPTS',
40
+ 'PS4',
41
+ 'BASH_XTRACEFD',
42
+ 'LD_PRELOAD',
43
+ 'LD_LIBRARY_PATH',
44
+ 'LD_AUDIT',
45
+ 'NODE_OPTIONS',
46
+ 'BUN_OPTIONS',
47
+ 'PYTHONPATH',
48
+ 'PYTHONSTARTUP',
49
+ 'RUBYOPT',
50
+ 'PERL5OPT',
51
+ 'SSH_AUTH_SOCK',
52
+ 'KUBECONFIG',
53
+ ])
54
+
55
+ const EXECUTION_CONTROL_ENV_PREFIXES = ['GIT_CONFIG', 'BASH_FUNC_'] as const
56
+
57
+ // Withheld ONLY when the name would compromise sandbox integrity or claim a
58
+ // host/container-injected runtime token — not for being credential-shaped. `.env`
59
+ // is the operator's expose-to-the-agent surface: every value they declare there
60
+ // reaches model bash by design, INCLUDING GH_TOKEN / GITHUB_TOKEN. Credentials
61
+ // that must stay hidden belong in secrets.json.
62
+ function isWithheldEnvName(name: string): boolean {
63
+ if (RESERVED_SANDBOX_ENV_NAMES.has(name)) return true
64
+ if (RUNTIME_OWNED_ENV_NAMES.has(name)) return true
65
+ if (EXECUTION_CONTROL_ENV_NAMES.has(name)) return true
66
+ return EXECUTION_CONTROL_ENV_PREFIXES.some((prefix) => name === prefix || name.startsWith(prefix))
67
+ }
68
+
69
+ // Every name an operator declared in the `.env` FILE with a non-empty value,
70
+ // minus the sandbox-integrity/broker withholds. Eligibility is decided from the
71
+ // PARSED `.env` value, never process.env: an empty `.env` line (`X=`) is not an
72
+ // operator expose-choice even if hydrateChannelEnvFromSecrets later fills
73
+ // process.env[X] from secrets.json. The inherited VALUE is still snapshotted
74
+ // from process.env at spawn time.
75
+ export function resolveExposableEnvNames(declaredEnv: ReadonlyMap<string, string>): string[] {
76
+ const out: string[] = []
77
+ for (const [name, fileValue] of declaredEnv) {
78
+ if (fileValue.length === 0) continue
79
+ if (isWithheldEnvName(name)) continue
80
+ out.push(name)
81
+ }
82
+ return out
83
+ }
@@ -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
  }