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.
- package/README.md +1 -1
- package/package.json +3 -2
- package/src/agent/git-nudge.ts +2 -1
- package/src/agent/index.ts +44 -30
- package/src/agent/live-subagents.ts +18 -0
- package/src/agent/multimodal/index.ts +1 -1
- package/src/agent/multimodal/look-at.ts +78 -44
- package/src/agent/multimodal/looker.ts +161 -39
- package/src/agent/network/response-body.ts +26 -0
- package/src/agent/network/safe-http.ts +207 -0
- package/src/agent/plugin-tools.ts +377 -157
- package/src/agent/provider-error.ts +52 -1
- package/src/agent/restart/index.ts +61 -40
- package/src/agent/restart-handoff/index.ts +73 -4
- package/src/agent/reviewer-bash-policy.ts +42 -1
- package/src/agent/session-origin.ts +2 -0
- package/src/agent/subagent-drain.ts +117 -7
- package/src/agent/subagents.ts +49 -16
- package/src/agent/throttle-circuit.ts +25 -5
- package/src/agent/tool-error-remediation.ts +72 -0
- package/src/agent/tool-file-safety.ts +1310 -0
- package/src/agent/tools/channel-fetch-attachment.ts +10 -3
- package/src/agent/tools/ddg.ts +16 -2
- package/src/agent/tools/post-github-review.ts +199 -0
- package/src/agent/tools/spawn-subagent.ts +21 -18
- package/src/agent/tools/webfetch/fetch.ts +163 -183
- package/src/agent/tools/webfetch/tool.ts +2 -3
- package/src/agent/tools/websearch.ts +23 -2
- package/src/agent/tools-without-local-file-operands.ts +30 -0
- package/src/agent/turn-runner.ts +86 -6
- package/src/bundled-plugins/backup/README.md +23 -10
- package/src/bundled-plugins/backup/git-auth.ts +6 -4
- package/src/bundled-plugins/backup/index.ts +85 -44
- package/src/bundled-plugins/backup/runner.ts +85 -1
- package/src/bundled-plugins/doc-render/render.ts +93 -12
- package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
- package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
- package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
- package/src/bundled-plugins/github-cli-auth/git-askpass.ts +74 -26
- package/src/bundled-plugins/github-cli-auth/git-command.ts +224 -36
- package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +9 -9
- package/src/bundled-plugins/github-cli-auth/index.ts +207 -132
- package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
- package/src/bundled-plugins/github-cli-auth/token-class.ts +4 -6
- package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
- package/src/bundled-plugins/memory/README.md +32 -11
- package/src/bundled-plugins/memory/append-tool.ts +15 -8
- package/src/bundled-plugins/memory/citations.ts +22 -9
- package/src/bundled-plugins/memory/dreaming.ts +13 -8
- package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
- package/src/bundled-plugins/memory/index.ts +0 -4
- package/src/bundled-plugins/memory/load-memory.ts +8 -3
- package/src/bundled-plugins/memory/provenance-index.ts +717 -0
- package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
- package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
- package/src/bundled-plugins/memory/search-tool.ts +163 -60
- package/src/bundled-plugins/memory/stream-events.ts +2 -0
- package/src/bundled-plugins/memory/vector/embed-threads.ts +36 -0
- package/src/bundled-plugins/memory/vector/embedder.ts +19 -1
- package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
- package/src/bundled-plugins/researcher/write-report.ts +8 -5
- package/src/bundled-plugins/reviewer/index.ts +2 -2
- package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
- package/src/bundled-plugins/reviewer/skills/code-review.ts +19 -9
- package/src/bundled-plugins/scout/scout.ts +8 -0
- package/src/bundled-plugins/security/index.ts +4 -4
- package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
- package/src/bundled-plugins/security/policies/private-surface-read.ts +787 -36
- package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
- package/src/bundled-plugins/security/policies/ssrf.ts +147 -42
- package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
- package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
- package/src/channels/adapters/discord-bot.ts +66 -6
- package/src/channels/adapters/discord-channel-resolver.ts +91 -23
- package/src/channels/adapters/discord-id.ts +4 -0
- package/src/channels/adapters/discord-resolver-cache.ts +41 -0
- package/src/channels/adapters/discord.ts +57 -7
- package/src/channels/adapters/github/auth-app.ts +41 -12
- package/src/channels/adapters/github/inbound.ts +11 -0
- package/src/channels/adapters/github/index.ts +71 -65
- package/src/channels/adapters/github/reconcile-cooldown-store.ts +178 -0
- package/src/channels/adapters/github/reconcile-open-prs.ts +31 -0
- package/src/channels/adapters/github/review-submitter.ts +302 -0
- package/src/channels/adapters/kakaotalk-channel-resolver.ts +5 -3
- package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
- package/src/channels/adapters/kakaotalk-typing.ts +17 -15
- package/src/channels/adapters/slack-attachment-download.ts +71 -0
- package/src/channels/adapters/slack-bot-edit.ts +85 -20
- package/src/channels/adapters/slack-bot.ts +26 -10
- package/src/channels/adapters/slack-classify.ts +21 -2
- package/src/channels/adapters/slack-format.ts +245 -0
- package/src/channels/adapters/slack.ts +59 -7
- package/src/channels/adapters/telegram-bot.ts +18 -5
- package/src/channels/adapters/webex-bot.ts +8 -3
- package/src/channels/adapters/webex.ts +8 -3
- package/src/channels/fetch-attachment.ts +43 -0
- package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
- package/src/channels/github-token-bridge.ts +12 -6
- package/src/channels/manager.ts +9 -0
- package/src/channels/router.ts +248 -6
- package/src/channels/types.ts +28 -1
- package/src/cli/channel.ts +1 -1
- package/src/cli/init.ts +1 -1
- package/src/cli/model.ts +57 -7
- package/src/compose/stop.ts +17 -5
- package/src/config/config.ts +6 -6
- package/src/config/models-mutation.ts +13 -1
- package/src/config/providers.ts +176 -0
- package/src/container/docker-app.ts +42 -13
- package/src/container/start.ts +62 -10
- package/src/cron/bridge.ts +9 -2
- package/src/doctor/checks.ts +8 -3
- package/src/doctor/commit.ts +2 -1
- package/src/doctor/file-ownership.ts +52 -0
- package/src/dreams/git.ts +2 -1
- package/src/git/bound-gc-config.ts +82 -0
- package/src/git/hookless.ts +5 -0
- package/src/git/reconcile-ignored.ts +18 -5
- package/src/git/system-commit.ts +12 -6
- package/src/hostd/spawn.ts +133 -47
- package/src/init/dockerfile.ts +99 -5
- package/src/init/index.ts +17 -5
- package/src/init/models-dev.ts +4 -0
- package/src/init/validate-api-key.ts +2 -0
- package/src/inspect/replay.ts +21 -9
- package/src/inspect/session-list.ts +71 -33
- package/src/mcp/tools.ts +17 -3
- package/src/network/internal-destinations.ts +267 -0
- package/src/permissions/builtins.ts +3 -1
- package/src/plugin/context.ts +2 -0
- package/src/plugin/index.ts +1 -0
- package/src/plugin/manager.ts +4 -0
- package/src/plugin/types.ts +22 -0
- package/src/run/index.ts +40 -0
- package/src/run/llm-fetch-observer.ts +41 -4
- package/src/sandbox/build.ts +37 -15
- package/src/sandbox/canonical-secrets.ts +18 -0
- package/src/sandbox/env-exposure.ts +83 -0
- package/src/sandbox/errors.ts +13 -6
- package/src/sandbox/hidden-paths.ts +102 -44
- package/src/sandbox/index.ts +22 -4
- package/src/sandbox/package-install.ts +3 -27
- package/src/sandbox/policy.ts +16 -28
- package/src/sandbox/privileged-runtime.ts +256 -0
- package/src/sandbox/session-tmp.ts +8 -2
- package/src/sandbox/writable-zones.ts +204 -140
- package/src/secrets/index.ts +8 -0
- package/src/secrets/refresh-provider-oauth.ts +128 -0
- package/src/server/command-runner.ts +48 -4
- package/src/server/index.ts +4 -0
- package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
- package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
- package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
- package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
- package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
- package/src/skills/typeclaw-config/SKILL.md +27 -11
- package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
- package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
- package/src/skills/typeclaw-memory/SKILL.md +9 -3
- package/src/skills/typeclaw-permissions/SKILL.md +36 -19
- package/src/skills/typeclaw-plugins/SKILL.md +37 -0
- package/src/usage/scan.ts +11 -2
- package/typeclaw.schema.json +25 -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,7 @@ import {
|
|
|
23
24
|
checkSkillAuthoringGuard,
|
|
24
25
|
} from '@/bundled-plugins/guard/policy'
|
|
25
26
|
import { config, getSandboxWritablePathSpecs } from '@/config/config'
|
|
27
|
+
import { readEnvFile } from '@/init/env-file'
|
|
26
28
|
import type { PermissionService } from '@/permissions/permissions'
|
|
27
29
|
import type {
|
|
28
30
|
BuiltinToolRef,
|
|
@@ -36,31 +38,39 @@ import type {
|
|
|
36
38
|
} from '@/plugin'
|
|
37
39
|
import {
|
|
38
40
|
buildSandboxedCommand,
|
|
41
|
+
canWriteAgentRootInSandbox,
|
|
39
42
|
canMountRealProc,
|
|
43
|
+
cleanupPrivilegedSandboxRuntime,
|
|
40
44
|
commandNeedsRealProc,
|
|
41
45
|
DEFAULT_SANDBOX_ENV,
|
|
42
46
|
ensureBwrapAvailable,
|
|
43
47
|
ensureHiddenMaskTargets,
|
|
44
48
|
ensureSessionTmpDir,
|
|
45
49
|
getProcBindSafetyVerdict,
|
|
46
|
-
|
|
50
|
+
isGitControlPath,
|
|
47
51
|
mapVirtualTmpPath,
|
|
48
52
|
resolveHiddenPaths,
|
|
49
|
-
|
|
53
|
+
resolvePrivilegedSandboxRuntime,
|
|
50
54
|
resolveProcBindSafetyWithRetry,
|
|
51
55
|
resolveProcSelfExe,
|
|
52
56
|
resolveProtectedZones,
|
|
53
57
|
resolveSandboxSymlinks,
|
|
54
58
|
resolveWritableZones,
|
|
59
|
+
SandboxPolicyError,
|
|
55
60
|
SandboxDegradedProcError,
|
|
56
61
|
SandboxProcProbeUnverifiedError,
|
|
57
62
|
subtractMasked,
|
|
63
|
+
verifyHiddenMaskTargets,
|
|
64
|
+
verifyPrivilegedSandboxRuntime,
|
|
58
65
|
} from '@/sandbox'
|
|
66
|
+
import { resolveExposableEnvNames } from '@/sandbox/env-exposure'
|
|
59
67
|
|
|
60
68
|
import { createLoopGuard, type LoopGuard, type LoopGuardDecision } from './loop-guard'
|
|
61
69
|
import { checkImageReadRedirect } from './multimodal/read-redirect'
|
|
62
70
|
import { enforceSubagentBashPolicy, type SubagentBashPolicy } from './reviewer-bash-policy'
|
|
63
71
|
import type { SessionOrigin } from './session-origin'
|
|
72
|
+
import { remediateToolErrorMessage } from './tool-error-remediation'
|
|
73
|
+
import { enforceAndPinToolFiles, writeToolOutputNoFollow } from './tool-file-safety'
|
|
64
74
|
import { SUBAGENT_OUTPUT_TOOL_NAME, type SubagentOutputToolDetails } from './tools/subagent-output'
|
|
65
75
|
import { webFetchTool } from './tools/webfetch'
|
|
66
76
|
import { webSearchTool } from './tools/websearch'
|
|
@@ -76,15 +86,36 @@ let sharedLoopGuard: LoopGuard = createLoopGuard()
|
|
|
76
86
|
// a bash call's args to inject env vars into the spawned process WITHOUT
|
|
77
87
|
// putting them in the command string (where they would leak through logs and
|
|
78
88
|
// later hooks). The wrapper extracts and deletes it before the bash tool runs,
|
|
79
|
-
// then threads it to the spawn
|
|
80
|
-
//
|
|
89
|
+
// then threads it to the spawn. Sandboxed secret values stay in bwrap's parent
|
|
90
|
+
// environment and are inherited by name rather than rendered into argv. Used
|
|
91
|
+
// by github-cli-auth to inject a per-repo GH_TOKEN. The key
|
|
81
92
|
// is stripped from client-supplied args before tool.before so only trusted
|
|
82
93
|
// hooks can set it.
|
|
83
94
|
export const TYPECLAW_INTERNAL_BASH_ENV = '__typeclawBashEnv'
|
|
84
95
|
|
|
85
96
|
type BashEnvOverlay = Record<string, string>
|
|
97
|
+
const SECRET_BASH_ENV_NAMES = new Set(['GH_TOKEN', 'GITHUB_TOKEN'])
|
|
98
|
+
|
|
99
|
+
// Transport classifier for the TRUSTED hook-injected overlay only (e.g.
|
|
100
|
+
// github-cli-auth's per-repo GH_TOKEN). Token/secret-shaped names use `inherit`
|
|
101
|
+
// so their value never renders into the bwrap argv; plain names (GH_REPO) go
|
|
102
|
+
// via `set`. This is NOT a .env exposure filter — the overlay is populated by
|
|
103
|
+
// trusted runtime hooks, not operator .env.
|
|
104
|
+
const OVERLAY_SECRET_NAME_PATTERN = /(?:^|_)(?:TOKEN|SECRET|PASSWORD|API_KEY|PRIVATE_KEY|AUTH)$/i
|
|
105
|
+
function isOverlaySecretName(name: string): boolean {
|
|
106
|
+
return SECRET_BASH_ENV_NAMES.has(name) || OVERLAY_SECRET_NAME_PATTERN.test(name)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
type BashSpawnEnvContext = {
|
|
110
|
+
overlay?: BashEnvOverlay
|
|
111
|
+
// Exact env for the outer bwrap process on a sandboxed call. When present, the
|
|
112
|
+
// spawn hook uses it verbatim rather than the live inherited env, so a secret
|
|
113
|
+
// that appears in process.env between policy build and spawn stays out of the
|
|
114
|
+
// sandbox (closes the inherit TOCTOU).
|
|
115
|
+
sandboxSpawnEnv?: Record<string, string>
|
|
116
|
+
}
|
|
86
117
|
|
|
87
|
-
const bashEnvStore = new AsyncLocalStorage<
|
|
118
|
+
const bashEnvStore = new AsyncLocalStorage<BashSpawnEnvContext | undefined>()
|
|
88
119
|
|
|
89
120
|
function readBashEnvOverlay(args: Record<string, unknown>): BashEnvOverlay | undefined {
|
|
90
121
|
const raw = args[TYPECLAW_INTERNAL_BASH_ENV]
|
|
@@ -97,9 +128,19 @@ function readBashEnvOverlay(args: Record<string, unknown>): BashEnvOverlay | und
|
|
|
97
128
|
}
|
|
98
129
|
|
|
99
130
|
function bashSpawnHookWithOverlay(context: BashSpawnContext): BashSpawnContext {
|
|
100
|
-
const
|
|
101
|
-
if (
|
|
102
|
-
return { ...context, env:
|
|
131
|
+
const store = bashEnvStore.getStore()
|
|
132
|
+
if (store?.sandboxSpawnEnv !== undefined) return { ...context, env: { ...store.sandboxSpawnEnv } }
|
|
133
|
+
return { ...context, env: sanitizeBashSpawnEnvironment(context.env, store?.overlay) }
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function sanitizeBashSpawnEnvironment(
|
|
137
|
+
inherited: NodeJS.ProcessEnv | undefined,
|
|
138
|
+
overlay: BashEnvOverlay | undefined,
|
|
139
|
+
): NodeJS.ProcessEnv {
|
|
140
|
+
const env = { ...inherited }
|
|
141
|
+
for (const name of SECRET_BASH_ENV_NAMES) delete env[name]
|
|
142
|
+
if (overlay !== undefined) Object.assign(env, overlay)
|
|
143
|
+
return env
|
|
103
144
|
}
|
|
104
145
|
|
|
105
146
|
const ACKNOWLEDGE_GUARDS_SCHEMA = Type.Optional(
|
|
@@ -149,7 +190,14 @@ function createPiBuiltinToolDefinition(name: PiBuiltinToolName, cwd: string): To
|
|
|
149
190
|
case 'edit':
|
|
150
191
|
return piCreateEditToolDefinition(cwd)
|
|
151
192
|
case 'write':
|
|
152
|
-
return piCreateWriteToolDefinition(cwd
|
|
193
|
+
return piCreateWriteToolDefinition(cwd, {
|
|
194
|
+
operations: {
|
|
195
|
+
mkdir: async (dir) => {
|
|
196
|
+
await mkdir(dir, { recursive: true })
|
|
197
|
+
},
|
|
198
|
+
writeFile: writeToolOutputNoFollow,
|
|
199
|
+
},
|
|
200
|
+
})
|
|
153
201
|
case 'grep':
|
|
154
202
|
return piCreateGrepToolDefinition(cwd)
|
|
155
203
|
case 'find':
|
|
@@ -196,6 +244,7 @@ export type WrapToolOptions = {
|
|
|
196
244
|
// origin mutates per turn surface the current-turn `lastInboundAuthorId`
|
|
197
245
|
// to `tool.before`. Sessions with a fixed origin can pass `() => origin`.
|
|
198
246
|
getOrigin?: () => SessionOrigin | undefined
|
|
247
|
+
permissions?: PermissionService
|
|
199
248
|
// Resolves the current turn's abort handle. Resolved lazily (not at wrap
|
|
200
249
|
// time) because tools are wrapped BEFORE `createAgentSession` returns the
|
|
201
250
|
// session whose `agent.abort` this points at. See `fireLoopAbort`.
|
|
@@ -203,6 +252,19 @@ export type WrapToolOptions = {
|
|
|
203
252
|
getLoopGuardTurn?: () => number | undefined
|
|
204
253
|
}
|
|
205
254
|
|
|
255
|
+
export type BashSandboxBoundary = {
|
|
256
|
+
ensureAvailable: () => Promise<void>
|
|
257
|
+
buildCommand: typeof buildSandboxedCommand
|
|
258
|
+
resolveRuntime?: typeof resolvePrivilegedSandboxRuntime
|
|
259
|
+
verifyRuntime?: typeof verifyPrivilegedSandboxRuntime
|
|
260
|
+
cleanupRuntime?: typeof cleanupPrivilegedSandboxRuntime
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const DEFAULT_BASH_SANDBOX_BOUNDARY: BashSandboxBoundary = {
|
|
264
|
+
ensureAvailable: ensureBwrapAvailable,
|
|
265
|
+
buildCommand: buildSandboxedCommand,
|
|
266
|
+
}
|
|
267
|
+
|
|
206
268
|
export type WrapSystemToolOptions = {
|
|
207
269
|
agentDir: string
|
|
208
270
|
sessionId: string
|
|
@@ -211,15 +273,17 @@ export type WrapSystemToolOptions = {
|
|
|
211
273
|
getAbort?: () => ((reason?: string) => void) | undefined
|
|
212
274
|
getLoopGuardTurn?: () => number | undefined
|
|
213
275
|
// When present, the bash builtin is rewritten through the per-tool bwrap
|
|
214
|
-
// sandbox
|
|
215
|
-
//
|
|
216
|
-
//
|
|
276
|
+
// sandbox. Private-directory masks remain role-derived; canonical agent
|
|
277
|
+
// secret-file masks apply to every role. Only sessions wired without a
|
|
278
|
+
// permission service fail closed before execution. Production session setup
|
|
279
|
+
// always supplies either the live service or the deny-all service.
|
|
217
280
|
permissions?: PermissionService
|
|
218
281
|
// Per-subagent bash capability policy, enforced as a hard pre-check BEFORE
|
|
219
|
-
// the role-derived sandbox
|
|
220
|
-
//
|
|
282
|
+
// the role-derived sandbox. Lets a read-only subagent keep its bash read-only
|
|
283
|
+
// no matter who spawned it. See
|
|
221
284
|
// `src/agent/reviewer-bash-policy.ts`.
|
|
222
285
|
bashPolicy?: SubagentBashPolicy
|
|
286
|
+
bashSandboxBoundary?: BashSandboxBoundary
|
|
223
287
|
}
|
|
224
288
|
|
|
225
289
|
// Zod 4 emits a top-level `"$schema": "https://json-schema.org/draft/2020-12/schema"`
|
|
@@ -265,6 +329,7 @@ export function wrapPluginTool(tool: Tool<any>, opts: WrapToolOptions): ToolDefi
|
|
|
265
329
|
callId: toolCallId,
|
|
266
330
|
args: mutableArgs,
|
|
267
331
|
...(liveOrigin !== undefined ? { origin: liveOrigin } : {}),
|
|
332
|
+
...(tool.fileOperands !== undefined ? { fileOperands: tool.fileOperands } : {}),
|
|
268
333
|
}
|
|
269
334
|
const blockResult = await opts.hooks.runToolBefore(before)
|
|
270
335
|
if (blockResult !== undefined) {
|
|
@@ -290,13 +355,38 @@ export function wrapPluginTool(tool: Tool<any>, opts: WrapToolOptions): ToolDefi
|
|
|
290
355
|
logger: opts.logger,
|
|
291
356
|
}
|
|
292
357
|
|
|
293
|
-
let result: ToolResult
|
|
358
|
+
let result: ToolResult | undefined
|
|
359
|
+
let executionError: unknown
|
|
360
|
+
let cleanupError: unknown
|
|
361
|
+
const pinnedFiles = await enforceAndPinToolFiles({
|
|
362
|
+
tool: opts.toolName,
|
|
363
|
+
args: before.args,
|
|
364
|
+
agentDir: opts.agentDir,
|
|
365
|
+
genericInputs: true,
|
|
366
|
+
fileOperands: tool.fileOperands,
|
|
367
|
+
logger: opts.logger,
|
|
368
|
+
signal,
|
|
369
|
+
})
|
|
294
370
|
try {
|
|
295
371
|
result = await tool.execute(before.args, toolCtx)
|
|
296
372
|
} catch (err) {
|
|
297
|
-
|
|
298
|
-
|
|
373
|
+
executionError = err
|
|
374
|
+
} finally {
|
|
375
|
+
try {
|
|
376
|
+
await pinnedFiles.cleanup()
|
|
377
|
+
} catch (error) {
|
|
378
|
+
cleanupError = error
|
|
379
|
+
}
|
|
299
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
|
|
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
|
|
363
|
-
|
|
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
|
|
439
|
-
// SubagentBashPolicyError on a disallowed command, surfaced to the model
|
|
440
|
-
//
|
|
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
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
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
|
-
|
|
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
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
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
|
|
466
629
|
}
|
|
467
|
-
|
|
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)
|
|
638
|
+
}
|
|
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
|
|
518
|
-
//
|
|
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,126 @@ async function applyBashSandbox(
|
|
|
525
727
|
agentDir: string,
|
|
526
728
|
sessionId: string,
|
|
527
729
|
envOverlay: BashEnvOverlay | undefined,
|
|
528
|
-
|
|
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
735
|
const { dirs, files } = resolveHiddenPaths(permissions, origin, agentDir)
|
|
533
|
-
if (dirs.length === 0 && files.length === 0) return
|
|
534
|
-
|
|
535
736
|
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
737
|
const maskTargets = await ensureHiddenMaskTargets({ dirs, files })
|
|
543
|
-
|
|
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.
|
|
738
|
+
await boundary.ensureAvailable()
|
|
549
739
|
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
740
|
const writable = subtractMasked(await resolveWritableZones(agentDir, getSandboxWritablePathSpecs(config)), {
|
|
571
741
|
dirs,
|
|
572
742
|
files,
|
|
573
743
|
})
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
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.
|
|
744
|
+
const writableRoot = canWriteAgentRootInSandbox(permissions, origin)
|
|
745
|
+
const protectedZones =
|
|
746
|
+
writableRoot || writable.dirs.includes(join(agentDir, '.git'))
|
|
747
|
+
? subtractMasked(await resolveProtectedZones(agentDir), { dirs, files })
|
|
748
|
+
: { dirs: [], files: [] }
|
|
602
749
|
const writableDirSet = new Set(writable.dirs)
|
|
603
750
|
const sandboxHome = DEFAULT_SANDBOX_ENV.HOME ?? '/tmp'
|
|
604
751
|
const symlinks = resolveSandboxSymlinks(agentDir, config.sandbox.symlinks, sandboxHome).filter((op) =>
|
|
605
752
|
writableDirSet.has(op.target),
|
|
606
753
|
)
|
|
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
754
|
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
755
|
if (proc === 'tmpfs' && commandNeedsRealProc(command)) {
|
|
622
756
|
throw degradeReason === 'unverified' ? new SandboxProcProbeUnverifiedError() : new SandboxDegradedProcError()
|
|
623
757
|
}
|
|
624
|
-
const
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
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 } } : {}),
|
|
758
|
+
const privilegedRuntime = await (boundary.resolveRuntime ?? resolvePrivilegedSandboxRuntime)({
|
|
759
|
+
agentDir,
|
|
760
|
+
command,
|
|
761
|
+
env: sandboxEnvOverlay,
|
|
643
762
|
})
|
|
644
|
-
|
|
763
|
+
const cleanup = async (): Promise<void> =>
|
|
764
|
+
(boundary.cleanupRuntime ?? cleanupPrivilegedSandboxRuntime)(privilegedRuntime)
|
|
765
|
+
try {
|
|
766
|
+
await verifyHiddenMaskTargets(maskTargets)
|
|
767
|
+
const { commandString, spawnEnv } = boundary.buildCommand(command, {
|
|
768
|
+
mounts: [
|
|
769
|
+
{ type: 'ro-bind', source: agentDir, dest: agentDir },
|
|
770
|
+
{ type: 'bind', source: sessionTmp, dest: '/tmp' },
|
|
771
|
+
...(privilegedRuntime?.mounts ?? []),
|
|
772
|
+
],
|
|
773
|
+
...(writableRoot
|
|
774
|
+
? { writableRoot: { dir: agentDir }, masks: maskTargets, protected: protectedZones }
|
|
775
|
+
: { masks: maskTargets, writable, protected: protectedZones }),
|
|
776
|
+
symlinks,
|
|
777
|
+
network: 'inherit',
|
|
778
|
+
cwd: agentDir,
|
|
779
|
+
proc,
|
|
780
|
+
procSelfExe: resolveProcSelfExe(),
|
|
781
|
+
...spreadSandboxEnv(
|
|
782
|
+
buildSandboxEnvPolicy(sandboxEnvOverlay, privilegedRuntime?.env, resolveExposableBashEnvNames(agentDir)),
|
|
783
|
+
),
|
|
784
|
+
})
|
|
785
|
+
mutableArgs.command = commandString
|
|
786
|
+
// The overlay carries command-scoped secret VALUES (e.g. a per-repo GH_TOKEN)
|
|
787
|
+
// that live in neither process.env nor argv; resolveSpawnEnv snapshots
|
|
788
|
+
// inherited names from process.env only, so merge the overlay values in here
|
|
789
|
+
// to complete the exact bwrap-parent env.
|
|
790
|
+
const mergedSpawnEnv =
|
|
791
|
+
spawnEnv !== undefined && sandboxEnvOverlay !== undefined ? { ...spawnEnv, ...sandboxEnvOverlay } : spawnEnv
|
|
792
|
+
return {
|
|
793
|
+
verify: async () => (boundary.verifyRuntime ?? verifyPrivilegedSandboxRuntime)(privilegedRuntime),
|
|
794
|
+
cleanup,
|
|
795
|
+
spawnEnv: mergedSpawnEnv,
|
|
796
|
+
}
|
|
797
|
+
} catch (error) {
|
|
798
|
+
await cleanup()
|
|
799
|
+
throw error
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
export function buildSandboxEnvPolicy(
|
|
804
|
+
overlay: BashEnvOverlay | undefined,
|
|
805
|
+
runtimeEnv: Record<string, string> | undefined,
|
|
806
|
+
exposableEnvNames: readonly string[] = [],
|
|
807
|
+
): { inherit?: string[]; set?: Record<string, string> } {
|
|
808
|
+
const set = { ...runtimeEnv }
|
|
809
|
+
const inherit: string[] = []
|
|
810
|
+
const inheritSeen = new Set<string>()
|
|
811
|
+
const pushInherit = (key: string): void => {
|
|
812
|
+
if (Object.hasOwn(set, key) || inheritSeen.has(key)) return
|
|
813
|
+
inheritSeen.add(key)
|
|
814
|
+
inherit.push(key)
|
|
815
|
+
}
|
|
816
|
+
for (const [key, value] of Object.entries(overlay ?? {})) {
|
|
817
|
+
if (Object.hasOwn(set, key)) continue
|
|
818
|
+
if (isOverlaySecretName(key)) pushInherit(key)
|
|
819
|
+
else set[key] = value
|
|
820
|
+
}
|
|
821
|
+
// Operator-declared .env vars pass through by NAME (inherit), keeping values
|
|
822
|
+
// out of the rendered bwrap argv. Sandbox-integrity names were already dropped
|
|
823
|
+
// in resolveExposableEnvNames — these are the survivors.
|
|
824
|
+
for (const key of exposableEnvNames) pushInherit(key)
|
|
825
|
+
// Pass the entrypoint-exported Xvfb display (start_xvfb: `export DISPLAY=:99`)
|
|
826
|
+
// through --clearenv, else sandboxed `agent-browser --headed` dies with
|
|
827
|
+
// "Missing X server or $DISPLAY". Passing the runtime's OWN value (not a fixed
|
|
828
|
+
// ":99") keeps `docker.file.xvfb=false` advertising no display. Rendered via
|
|
829
|
+
// `set` (a display number is neither a credential nor shell-injectable), and no
|
|
830
|
+
// /tmp/.X11-unix bind is needed: Chrome reaches Xvfb over the netns-scoped
|
|
831
|
+
// abstract X11 socket while bash keeps network:'inherit'.
|
|
832
|
+
const display = process.env['DISPLAY']
|
|
833
|
+
if (display !== undefined && display !== '' && !Object.hasOwn(set, 'DISPLAY') && !inheritSeen.has('DISPLAY')) {
|
|
834
|
+
set['DISPLAY'] = display
|
|
835
|
+
}
|
|
836
|
+
return {
|
|
837
|
+
...(inherit.length > 0 ? { inherit } : {}),
|
|
838
|
+
...(Object.keys(set).length > 0 ? { set } : {}),
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
function spreadSandboxEnv(policy: ReturnType<typeof buildSandboxEnvPolicy>): {
|
|
843
|
+
env?: ReturnType<typeof buildSandboxEnvPolicy>
|
|
844
|
+
} {
|
|
845
|
+
return Object.keys(policy).length > 0 ? { env: policy } : {}
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
function resolveExposableBashEnvNames(agentDir: string): string[] {
|
|
849
|
+
return resolveExposableEnvNames(readEnvFile(agentDir))
|
|
645
850
|
}
|
|
646
851
|
|
|
647
852
|
function buildRoleScopedConfigEnv(
|
|
@@ -652,8 +857,8 @@ function buildRoleScopedConfigEnv(
|
|
|
652
857
|
// Low-trust roles have workspace/ masked. Do not let container-global config
|
|
653
858
|
// env vars point CLIs back at that private surface: apps that honor XDG should
|
|
654
859
|
// still run, but their config must land in the sandbox's per-session /tmp.
|
|
655
|
-
// Trusted/owner
|
|
656
|
-
//
|
|
860
|
+
// Trusted/owner have only the unconditional credential-dir masks, not the
|
|
861
|
+
// workspace root mask, so their command broker decides whether to set GWS.
|
|
657
862
|
const workspaceHidden = hiddenDirs.includes(join(agentDir, 'workspace'))
|
|
658
863
|
if (!workspaceHidden) return envOverlay
|
|
659
864
|
|
|
@@ -664,14 +869,6 @@ function buildRoleScopedConfigEnv(
|
|
|
664
869
|
}
|
|
665
870
|
}
|
|
666
871
|
|
|
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
872
|
// Picks the /proc strategy for a sandboxed bash call. The branch order is:
|
|
676
873
|
// 'real-proc' ONLY when the operator explicitly opted in (sandbox.realProc) AND
|
|
677
874
|
// the kernel permits the mount (canMountRealProc) — it adds PID isolation but
|
|
@@ -717,7 +914,7 @@ async function resolveProcStrategy(): Promise<ProcStrategyResolution> {
|
|
|
717
914
|
)
|
|
718
915
|
if (verdict === 'safe') return { strategy: 'proc-bind' }
|
|
719
916
|
// Degraded last resort: no working /proc strategy. External package runners
|
|
720
|
-
// (bunx/bun
|
|
917
|
+
// (bunx/bun run <pkg-bin>) will fail with Bun's opaque "NotDir" because
|
|
721
918
|
// /proc/self/{fd,maps} are absent. Only a proven 'unsafe' (a real cross-userns
|
|
722
919
|
// leak) is DEFINITIVE — warn once (a real operator-facing limit). An
|
|
723
920
|
// 'inconclusive' is reported as retryable upstream and NOT warned (it would cry
|
|
@@ -736,25 +933,26 @@ function warnTmpfsProcFallbackOnce(): void {
|
|
|
736
933
|
tmpfsProcFallbackWarned = true
|
|
737
934
|
console.warn(
|
|
738
935
|
'[sandbox] degraded /proc mode: neither real-proc nor proc-bind is available on this host, ' +
|
|
739
|
-
'so sandboxed external package runners (bunx / bun
|
|
936
|
+
'so sandboxed external package runners (bunx / bun run <pkg-bin>) will fail. ' +
|
|
740
937
|
'This needs a runtime with working user namespaces.',
|
|
741
938
|
)
|
|
742
939
|
}
|
|
743
940
|
|
|
744
|
-
// The builtin file tools that take a single filesystem `path` arg.
|
|
745
|
-
//
|
|
746
|
-
//
|
|
941
|
+
// The builtin file tools that take a single filesystem `path` arg. They run in
|
|
942
|
+
// the main process rather than bwrap, so each must apply the same
|
|
943
|
+
// /tmp -> session-dir mapping that
|
|
747
944
|
// applyBashSandbox binds for bash — otherwise a `read` of /tmp/foo hits the
|
|
748
945
|
// real container /tmp while sandboxed bash wrote the session backing dir.
|
|
749
946
|
const TMP_REDIRECT_TOOLS = new Set(['read', 'write', 'edit', 'grep', 'find', 'ls'])
|
|
750
947
|
|
|
751
|
-
//
|
|
752
|
-
// but the path-based file tools run
|
|
948
|
+
// Model-driven bash reads /tmp through bwrap's per-session bind
|
|
949
|
+
// (applyBashSandbox), but the path-based file tools run in the main process
|
|
950
|
+
// against the real container /tmp.
|
|
753
951
|
// Without this redirect a guest/member that touches /tmp/foo through bash (bound
|
|
754
952
|
// to the session dir) and through a file tool (real /tmp) would see two
|
|
755
953
|
// 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.
|
|
757
|
-
//
|
|
954
|
+
// backing dir makes every layer resolve /tmp/foo to one file. Bare harnesses
|
|
955
|
+
// without the production permission wiring are left untouched.
|
|
758
956
|
type TmpRedirect = { original: string; backing: string }
|
|
759
957
|
|
|
760
958
|
async function applyTmpPathRedirect(
|
|
@@ -798,6 +996,12 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
|
|
798
996
|
return typeof value === 'object' && value !== null
|
|
799
997
|
}
|
|
800
998
|
|
|
999
|
+
function normalizeDefaultTreeRoot(toolName: string, args: Record<string, unknown>): void {
|
|
1000
|
+
if ((toolName === 'grep' || toolName === 'find' || toolName === 'ls') && typeof args.path !== 'string') {
|
|
1001
|
+
args.path = '.'
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
|
|
801
1005
|
function appendLoopWarning(result: ToolResult, message: string): ToolResult {
|
|
802
1006
|
const content: ContentPart[] = [...(result.content as ContentPart[]), { type: 'text', text: message }]
|
|
803
1007
|
return { content, details: result.details }
|
|
@@ -955,12 +1159,28 @@ function errorResult(message: string) {
|
|
|
955
1159
|
|
|
956
1160
|
async function runFinalWriteGuards(options: { tool: string; args: Record<string, unknown>; agentDir: string }) {
|
|
957
1161
|
return (
|
|
1162
|
+
(await checkGitControlWriteGuard(options)) ??
|
|
958
1163
|
(await checkManagedConfigGuard(options)) ??
|
|
959
1164
|
(await checkSkillAuthoringGuard(options)) ??
|
|
960
1165
|
checkNonWorkspaceWriteGuard(options)
|
|
961
1166
|
)
|
|
962
1167
|
}
|
|
963
1168
|
|
|
1169
|
+
async function checkGitControlWriteGuard(options: {
|
|
1170
|
+
tool: string
|
|
1171
|
+
args: Record<string, unknown>
|
|
1172
|
+
agentDir: string
|
|
1173
|
+
}): Promise<{ block: true; reason: string } | undefined> {
|
|
1174
|
+
if (options.tool !== 'write' && options.tool !== 'edit') return undefined
|
|
1175
|
+
const candidate = options.args.path
|
|
1176
|
+
if (typeof candidate !== 'string') return undefined
|
|
1177
|
+
if (!(await isGitControlPath(options.agentDir, candidate))) return undefined
|
|
1178
|
+
return {
|
|
1179
|
+
block: true,
|
|
1180
|
+
reason: `Git control path is runtime-protected and cannot be modified with ${options.tool}: ${candidate}`,
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
|
|
964
1184
|
function runFinalReadGuards(options: { tool: string; args: Record<string, unknown> }) {
|
|
965
1185
|
return checkImageReadRedirect(options)
|
|
966
1186
|
}
|