typeclaw 0.45.0 → 0.46.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +3 -2
- package/src/agent/git-nudge.ts +2 -1
- package/src/agent/index.ts +67 -25
- package/src/agent/live-subagents.ts +18 -0
- package/src/agent/loop-guard.ts +208 -10
- package/src/agent/multimodal/index.ts +1 -1
- package/src/agent/multimodal/look-at.ts +78 -44
- package/src/agent/multimodal/looker.ts +151 -39
- package/src/agent/network/response-body.ts +26 -0
- package/src/agent/network/safe-http.ts +198 -0
- package/src/agent/plugin-tools.ts +438 -162
- package/src/agent/provider-error.ts +62 -4
- package/src/agent/restart/index.ts +61 -40
- package/src/agent/restart-handoff/index.ts +73 -4
- package/src/agent/retry-same-ref.ts +66 -0
- 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 +77 -18
- package/src/agent/throttle-circuit.ts +25 -5
- package/src/agent/tool-error-remediation.ts +72 -0
- package/src/agent/tool-file-safety.ts +1050 -0
- package/src/agent/tools/channel-fetch-attachment.ts +10 -3
- package/src/agent/tools/channel-reply.ts +15 -1
- package/src/agent/tools/channel-send.ts +17 -1
- 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 +143 -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 +27 -0
- package/src/agent/turn-runner.ts +109 -15
- package/src/bundled-plugins/backup/index.ts +2 -1
- package/src/bundled-plugins/backup/runner.ts +2 -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/index.ts +131 -135
- package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
- package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
- package/src/bundled-plugins/memory/README.md +23 -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/hybrid.ts +126 -13
- package/src/bundled-plugins/researcher/write-report.ts +6 -3
- 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 +24 -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 +220 -29
- package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
- package/src/bundled-plugins/security/policies/ssrf.ts +29 -9
- 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 +91 -10
- 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/index.ts +23 -11
- package/src/channels/adapters/github/review-submitter.ts +302 -0
- package/src/channels/adapters/kakaotalk-channel-resolver.ts +12 -1
- package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
- package/src/channels/adapters/kakaotalk-typing.ts +127 -0
- package/src/channels/adapters/kakaotalk.ts +19 -0
- package/src/channels/adapters/slack-attachment-download.ts +71 -0
- package/src/channels/adapters/slack-bot.ts +19 -8
- package/src/channels/adapters/slack-classify.ts +21 -2
- 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 +10 -3
- package/src/channels/manager.ts +9 -0
- package/src/channels/router.ts +568 -12
- 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/start.ts +49 -10
- package/src/doctor/checks.ts +3 -1
- 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/hookless.ts +5 -0
- package/src/git/reconcile-ignored.ts +18 -5
- package/src/git/secret-history.ts +371 -0
- package/src/git/system-commit.ts +12 -6
- package/src/init/dockerfile.ts +86 -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/mcp/tools.ts +16 -3
- 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 +21 -0
- package/src/run/index.ts +40 -0
- package/src/run/llm-fetch-observer.ts +188 -13
- package/src/sandbox/build.ts +37 -15
- package/src/sandbox/canonical-secrets.ts +18 -0
- package/src/sandbox/env-exposure.ts +80 -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 +11 -25
- package/src/sandbox/privileged-runtime.ts +255 -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 +5 -5
- 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 +19 -15
- package/typeclaw.schema.json +20 -0
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
|
+
import { mkdir } from 'node:fs/promises'
|
|
2
3
|
import { join } from 'node:path'
|
|
3
4
|
|
|
4
5
|
import {
|
|
@@ -23,6 +24,8 @@ import {
|
|
|
23
24
|
checkSkillAuthoringGuard,
|
|
24
25
|
} from '@/bundled-plugins/guard/policy'
|
|
25
26
|
import { config, getSandboxWritablePathSpecs } from '@/config/config'
|
|
27
|
+
import { assertNoCanonicalSecretsInGit } from '@/git/secret-history'
|
|
28
|
+
import { readEnvFile } from '@/init/env-file'
|
|
26
29
|
import type { PermissionService } from '@/permissions/permissions'
|
|
27
30
|
import type {
|
|
28
31
|
BuiltinToolRef,
|
|
@@ -36,31 +39,39 @@ import type {
|
|
|
36
39
|
} from '@/plugin'
|
|
37
40
|
import {
|
|
38
41
|
buildSandboxedCommand,
|
|
42
|
+
canWriteAgentRootInSandbox,
|
|
39
43
|
canMountRealProc,
|
|
44
|
+
cleanupPrivilegedSandboxRuntime,
|
|
40
45
|
commandNeedsRealProc,
|
|
41
46
|
DEFAULT_SANDBOX_ENV,
|
|
42
47
|
ensureBwrapAvailable,
|
|
43
48
|
ensureHiddenMaskTargets,
|
|
44
49
|
ensureSessionTmpDir,
|
|
45
50
|
getProcBindSafetyVerdict,
|
|
46
|
-
|
|
51
|
+
isGitControlPath,
|
|
47
52
|
mapVirtualTmpPath,
|
|
48
53
|
resolveHiddenPaths,
|
|
49
|
-
|
|
54
|
+
resolvePrivilegedSandboxRuntime,
|
|
50
55
|
resolveProcBindSafetyWithRetry,
|
|
51
56
|
resolveProcSelfExe,
|
|
52
57
|
resolveProtectedZones,
|
|
53
58
|
resolveSandboxSymlinks,
|
|
54
59
|
resolveWritableZones,
|
|
60
|
+
SandboxPolicyError,
|
|
55
61
|
SandboxDegradedProcError,
|
|
56
62
|
SandboxProcProbeUnverifiedError,
|
|
57
63
|
subtractMasked,
|
|
64
|
+
verifyHiddenMaskTargets,
|
|
65
|
+
verifyPrivilegedSandboxRuntime,
|
|
58
66
|
} from '@/sandbox'
|
|
67
|
+
import { resolveExposableEnvNames } from '@/sandbox/env-exposure'
|
|
59
68
|
|
|
60
69
|
import { createLoopGuard, type LoopGuard, type LoopGuardDecision } from './loop-guard'
|
|
61
70
|
import { checkImageReadRedirect } from './multimodal/read-redirect'
|
|
62
71
|
import { enforceSubagentBashPolicy, type SubagentBashPolicy } from './reviewer-bash-policy'
|
|
63
72
|
import type { SessionOrigin } from './session-origin'
|
|
73
|
+
import { remediateToolErrorMessage } from './tool-error-remediation'
|
|
74
|
+
import { enforceAndPinToolFiles, writeToolOutputNoFollow } from './tool-file-safety'
|
|
64
75
|
import { SUBAGENT_OUTPUT_TOOL_NAME, type SubagentOutputToolDetails } from './tools/subagent-output'
|
|
65
76
|
import { webFetchTool } from './tools/webfetch'
|
|
66
77
|
import { webSearchTool } from './tools/websearch'
|
|
@@ -76,15 +87,36 @@ let sharedLoopGuard: LoopGuard = createLoopGuard()
|
|
|
76
87
|
// a bash call's args to inject env vars into the spawned process WITHOUT
|
|
77
88
|
// putting them in the command string (where they would leak through logs and
|
|
78
89
|
// later hooks). The wrapper extracts and deletes it before the bash tool runs,
|
|
79
|
-
// then threads it to the spawn
|
|
80
|
-
//
|
|
90
|
+
// then threads it to the spawn. Sandboxed secret values stay in bwrap's parent
|
|
91
|
+
// environment and are inherited by name rather than rendered into argv. Used
|
|
92
|
+
// by github-cli-auth to inject a per-repo GH_TOKEN. The key
|
|
81
93
|
// is stripped from client-supplied args before tool.before so only trusted
|
|
82
94
|
// hooks can set it.
|
|
83
95
|
export const TYPECLAW_INTERNAL_BASH_ENV = '__typeclawBashEnv'
|
|
84
96
|
|
|
85
97
|
type BashEnvOverlay = Record<string, string>
|
|
98
|
+
const SECRET_BASH_ENV_NAMES = new Set(['GH_TOKEN', 'GITHUB_TOKEN'])
|
|
99
|
+
|
|
100
|
+
// Transport classifier for the TRUSTED hook-injected overlay only (e.g.
|
|
101
|
+
// github-cli-auth's per-repo GH_TOKEN). Token/secret-shaped names use `inherit`
|
|
102
|
+
// so their value never renders into the bwrap argv; plain names (GH_REPO) go
|
|
103
|
+
// via `set`. This is NOT a .env exposure filter — the overlay is populated by
|
|
104
|
+
// trusted runtime hooks, not operator .env.
|
|
105
|
+
const OVERLAY_SECRET_NAME_PATTERN = /(?:^|_)(?:TOKEN|SECRET|PASSWORD|API_KEY|PRIVATE_KEY|AUTH)$/i
|
|
106
|
+
function isOverlaySecretName(name: string): boolean {
|
|
107
|
+
return SECRET_BASH_ENV_NAMES.has(name) || OVERLAY_SECRET_NAME_PATTERN.test(name)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
type BashSpawnEnvContext = {
|
|
111
|
+
overlay?: BashEnvOverlay
|
|
112
|
+
// Exact env for the outer bwrap process on a sandboxed call. When present, the
|
|
113
|
+
// spawn hook uses it verbatim rather than the live inherited env, so a secret
|
|
114
|
+
// that appears in process.env between policy build and spawn stays out of the
|
|
115
|
+
// sandbox (closes the inherit TOCTOU).
|
|
116
|
+
sandboxSpawnEnv?: Record<string, string>
|
|
117
|
+
}
|
|
86
118
|
|
|
87
|
-
const bashEnvStore = new AsyncLocalStorage<
|
|
119
|
+
const bashEnvStore = new AsyncLocalStorage<BashSpawnEnvContext | undefined>()
|
|
88
120
|
|
|
89
121
|
function readBashEnvOverlay(args: Record<string, unknown>): BashEnvOverlay | undefined {
|
|
90
122
|
const raw = args[TYPECLAW_INTERNAL_BASH_ENV]
|
|
@@ -97,9 +129,19 @@ function readBashEnvOverlay(args: Record<string, unknown>): BashEnvOverlay | und
|
|
|
97
129
|
}
|
|
98
130
|
|
|
99
131
|
function bashSpawnHookWithOverlay(context: BashSpawnContext): BashSpawnContext {
|
|
100
|
-
const
|
|
101
|
-
if (
|
|
102
|
-
return { ...context, env:
|
|
132
|
+
const store = bashEnvStore.getStore()
|
|
133
|
+
if (store?.sandboxSpawnEnv !== undefined) return { ...context, env: { ...store.sandboxSpawnEnv } }
|
|
134
|
+
return { ...context, env: sanitizeBashSpawnEnvironment(context.env, store?.overlay) }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function sanitizeBashSpawnEnvironment(
|
|
138
|
+
inherited: NodeJS.ProcessEnv | undefined,
|
|
139
|
+
overlay: BashEnvOverlay | undefined,
|
|
140
|
+
): NodeJS.ProcessEnv {
|
|
141
|
+
const env = { ...inherited }
|
|
142
|
+
for (const name of SECRET_BASH_ENV_NAMES) delete env[name]
|
|
143
|
+
if (overlay !== undefined) Object.assign(env, overlay)
|
|
144
|
+
return env
|
|
103
145
|
}
|
|
104
146
|
|
|
105
147
|
const ACKNOWLEDGE_GUARDS_SCHEMA = Type.Optional(
|
|
@@ -149,7 +191,14 @@ function createPiBuiltinToolDefinition(name: PiBuiltinToolName, cwd: string): To
|
|
|
149
191
|
case 'edit':
|
|
150
192
|
return piCreateEditToolDefinition(cwd)
|
|
151
193
|
case 'write':
|
|
152
|
-
return piCreateWriteToolDefinition(cwd
|
|
194
|
+
return piCreateWriteToolDefinition(cwd, {
|
|
195
|
+
operations: {
|
|
196
|
+
mkdir: async (dir) => {
|
|
197
|
+
await mkdir(dir, { recursive: true })
|
|
198
|
+
},
|
|
199
|
+
writeFile: writeToolOutputNoFollow,
|
|
200
|
+
},
|
|
201
|
+
})
|
|
153
202
|
case 'grep':
|
|
154
203
|
return piCreateGrepToolDefinition(cwd)
|
|
155
204
|
case 'find':
|
|
@@ -196,10 +245,25 @@ export type WrapToolOptions = {
|
|
|
196
245
|
// origin mutates per turn surface the current-turn `lastInboundAuthorId`
|
|
197
246
|
// to `tool.before`. Sessions with a fixed origin can pass `() => origin`.
|
|
198
247
|
getOrigin?: () => SessionOrigin | undefined
|
|
248
|
+
permissions?: PermissionService
|
|
199
249
|
// Resolves the current turn's abort handle. Resolved lazily (not at wrap
|
|
200
250
|
// time) because tools are wrapped BEFORE `createAgentSession` returns the
|
|
201
251
|
// session whose `agent.abort` this points at. See `fireLoopAbort`.
|
|
202
252
|
getAbort?: () => ((reason?: string) => void) | undefined
|
|
253
|
+
getLoopGuardTurn?: () => number | undefined
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export type BashSandboxBoundary = {
|
|
257
|
+
ensureAvailable: () => Promise<void>
|
|
258
|
+
buildCommand: typeof buildSandboxedCommand
|
|
259
|
+
resolveRuntime?: typeof resolvePrivilegedSandboxRuntime
|
|
260
|
+
verifyRuntime?: typeof verifyPrivilegedSandboxRuntime
|
|
261
|
+
cleanupRuntime?: typeof cleanupPrivilegedSandboxRuntime
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const DEFAULT_BASH_SANDBOX_BOUNDARY: BashSandboxBoundary = {
|
|
265
|
+
ensureAvailable: ensureBwrapAvailable,
|
|
266
|
+
buildCommand: buildSandboxedCommand,
|
|
203
267
|
}
|
|
204
268
|
|
|
205
269
|
export type WrapSystemToolOptions = {
|
|
@@ -208,16 +272,19 @@ export type WrapSystemToolOptions = {
|
|
|
208
272
|
hooks: HookBus
|
|
209
273
|
getOrigin?: () => SessionOrigin | undefined
|
|
210
274
|
getAbort?: () => ((reason?: string) => void) | undefined
|
|
275
|
+
getLoopGuardTurn?: () => number | undefined
|
|
211
276
|
// When present, the bash builtin is rewritten through the per-tool bwrap
|
|
212
|
-
// sandbox
|
|
213
|
-
//
|
|
214
|
-
//
|
|
277
|
+
// sandbox. Private-directory masks remain role-derived; canonical agent
|
|
278
|
+
// secret-file masks apply to every role. Only sessions wired without a
|
|
279
|
+
// permission service fail closed before execution. Production session setup
|
|
280
|
+
// always supplies either the live service or the deny-all service.
|
|
215
281
|
permissions?: PermissionService
|
|
216
282
|
// Per-subagent bash capability policy, enforced as a hard pre-check BEFORE
|
|
217
|
-
// the role-derived sandbox
|
|
218
|
-
//
|
|
283
|
+
// the role-derived sandbox. Lets a read-only subagent keep its bash read-only
|
|
284
|
+
// no matter who spawned it. See
|
|
219
285
|
// `src/agent/reviewer-bash-policy.ts`.
|
|
220
286
|
bashPolicy?: SubagentBashPolicy
|
|
287
|
+
bashSandboxBoundary?: BashSandboxBoundary
|
|
221
288
|
}
|
|
222
289
|
|
|
223
290
|
// Zod 4 emits a top-level `"$schema": "https://json-schema.org/draft/2020-12/schema"`
|
|
@@ -263,13 +330,20 @@ export function wrapPluginTool(tool: Tool<any>, opts: WrapToolOptions): ToolDefi
|
|
|
263
330
|
callId: toolCallId,
|
|
264
331
|
args: mutableArgs,
|
|
265
332
|
...(liveOrigin !== undefined ? { origin: liveOrigin } : {}),
|
|
333
|
+
...(tool.fileOperands !== undefined ? { fileOperands: tool.fileOperands } : {}),
|
|
266
334
|
}
|
|
267
335
|
const blockResult = await opts.hooks.runToolBefore(before)
|
|
268
336
|
if (blockResult !== undefined) {
|
|
269
337
|
return errorResult(`blocked: ${blockResult.reason}`)
|
|
270
338
|
}
|
|
271
339
|
|
|
272
|
-
const loopGate = gateLoopGuard(
|
|
340
|
+
const loopGate = gateLoopGuard(
|
|
341
|
+
opts.sessionId,
|
|
342
|
+
opts.toolName,
|
|
343
|
+
before.args,
|
|
344
|
+
opts.getLoopGuardTurn?.(),
|
|
345
|
+
opts.agentDir,
|
|
346
|
+
)
|
|
273
347
|
if (loopGate.blockNow) {
|
|
274
348
|
fireLoopAbort(opts.getAbort, 'loop_guard:block')
|
|
275
349
|
return errorResult(loopGate.message)
|
|
@@ -282,13 +356,37 @@ export function wrapPluginTool(tool: Tool<any>, opts: WrapToolOptions): ToolDefi
|
|
|
282
356
|
logger: opts.logger,
|
|
283
357
|
}
|
|
284
358
|
|
|
285
|
-
let result: ToolResult
|
|
359
|
+
let result: ToolResult | undefined
|
|
360
|
+
let executionError: unknown
|
|
361
|
+
let cleanupError: unknown
|
|
362
|
+
const pinnedFiles = await enforceAndPinToolFiles({
|
|
363
|
+
tool: opts.toolName,
|
|
364
|
+
args: before.args,
|
|
365
|
+
agentDir: opts.agentDir,
|
|
366
|
+
genericInputs: true,
|
|
367
|
+
fileOperands: tool.fileOperands,
|
|
368
|
+
signal,
|
|
369
|
+
})
|
|
286
370
|
try {
|
|
287
371
|
result = await tool.execute(before.args, toolCtx)
|
|
288
372
|
} catch (err) {
|
|
289
|
-
|
|
290
|
-
|
|
373
|
+
executionError = err
|
|
374
|
+
} finally {
|
|
375
|
+
try {
|
|
376
|
+
await pinnedFiles.cleanup()
|
|
377
|
+
} catch (error) {
|
|
378
|
+
cleanupError = error
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
const finalError = executionError ?? cleanupError
|
|
382
|
+
if (finalError !== undefined) {
|
|
383
|
+
const failure = errorResult(finalError instanceof Error ? finalError.message : String(finalError))
|
|
384
|
+
await runToolAfterSafely(opts, opts.toolName, toolCallId, failure)
|
|
385
|
+
if (cleanupError !== undefined) throw finalError
|
|
386
|
+
return failure
|
|
291
387
|
}
|
|
388
|
+
if (result === undefined) throw new Error('plugin tool execution returned no result')
|
|
389
|
+
result = pinnedFiles.restoreResult(result)
|
|
292
390
|
|
|
293
391
|
const resolved = loopGate.resolve(result)
|
|
294
392
|
if ('deferredBlock' in resolved) {
|
|
@@ -321,6 +419,7 @@ export function wrapSystemTool<TParams extends TSchema, TDetails = unknown, TSta
|
|
|
321
419
|
parameters: withGuardAcknowledgements(tool.name, tool.parameters),
|
|
322
420
|
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
323
421
|
const mutableArgs = params as Record<string, unknown>
|
|
422
|
+
normalizeDefaultTreeRoot(tool.name, mutableArgs)
|
|
324
423
|
const liveOrigin = opts.getOrigin?.()
|
|
325
424
|
const blockResult = await opts.hooks.runToolBefore({
|
|
326
425
|
tool: tool.name,
|
|
@@ -332,7 +431,7 @@ export function wrapSystemTool<TParams extends TSchema, TDetails = unknown, TSta
|
|
|
332
431
|
if (blockResult !== undefined) {
|
|
333
432
|
throw new Error(`blocked: ${blockResult.reason}`)
|
|
334
433
|
}
|
|
335
|
-
const loopGate = gateLoopGuard(opts.sessionId, tool.name, mutableArgs)
|
|
434
|
+
const loopGate = gateLoopGuard(opts.sessionId, tool.name, mutableArgs, opts.getLoopGuardTurn?.(), opts.agentDir)
|
|
336
435
|
if (loopGate.blockNow) {
|
|
337
436
|
fireLoopAbort(opts.getAbort, 'loop_guard:block')
|
|
338
437
|
throw new Error(loopGate.message)
|
|
@@ -351,8 +450,41 @@ export function wrapSystemTool<TParams extends TSchema, TDetails = unknown, TSta
|
|
|
351
450
|
}
|
|
352
451
|
stripGuardAcknowledgements(mutableArgs)
|
|
353
452
|
|
|
354
|
-
const
|
|
355
|
-
|
|
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)
|
|
356
488
|
if ('deferredBlock' in resolved) {
|
|
357
489
|
fireLoopAbort(opts.getAbort, 'loop_guard:deferred_block')
|
|
358
490
|
throw new Error(resolved.deferredBlock)
|
|
@@ -387,6 +519,7 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
|
|
|
387
519
|
parameters: withGuardAcknowledgements(tool.name, tool.parameters),
|
|
388
520
|
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
389
521
|
const mutableArgs = params as Record<string, unknown>
|
|
522
|
+
normalizeDefaultTreeRoot(tool.name, mutableArgs)
|
|
390
523
|
const liveOrigin = opts.getOrigin?.()
|
|
391
524
|
// Defense-in-depth: strip any pre-existing internal env-overlay key
|
|
392
525
|
// before hooks run so only trusted tool.before hooks can set it.
|
|
@@ -406,7 +539,7 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
|
|
|
406
539
|
// loop-detection state, or pi's execute.
|
|
407
540
|
const bashEnvOverlay = readBashEnvOverlay(mutableArgs)
|
|
408
541
|
delete mutableArgs[TYPECLAW_INTERNAL_BASH_ENV]
|
|
409
|
-
const loopGate = gateLoopGuard(opts.sessionId, tool.name, mutableArgs)
|
|
542
|
+
const loopGate = gateLoopGuard(opts.sessionId, tool.name, mutableArgs, opts.getLoopGuardTurn?.(), opts.agentDir)
|
|
410
543
|
if (loopGate.blockNow) {
|
|
411
544
|
fireLoopAbort(opts.getAbort, 'loop_guard:block')
|
|
412
545
|
throw new Error(loopGate.message)
|
|
@@ -427,36 +560,91 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
|
|
|
427
560
|
|
|
428
561
|
// Per-subagent capability fence: runs BEFORE the role-derived sandbox so
|
|
429
562
|
// a read-only subagent's bash stays read-only even for a trusted/owner
|
|
430
|
-
// caller
|
|
431
|
-
// SubagentBashPolicyError on a disallowed command, surfaced to the model
|
|
432
|
-
//
|
|
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.
|
|
433
566
|
if (tool.name === 'bash' && opts.bashPolicy !== undefined) {
|
|
434
567
|
const command = mutableArgs.command
|
|
435
568
|
if (typeof command === 'string') enforceSubagentBashPolicy(opts.bashPolicy, command)
|
|
436
569
|
}
|
|
437
570
|
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
: undefined
|
|
446
|
-
|
|
447
|
-
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
|
|
448
578
|
try {
|
|
449
|
-
|
|
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, () =>
|
|
450
618
|
tool.execute(toolCallId, mutableArgs as Static<TParams>, signal, onUpdate, ctx),
|
|
451
619
|
)
|
|
452
620
|
} catch (error) {
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
621
|
+
executionError = error
|
|
622
|
+
} finally {
|
|
623
|
+
const cleanup = [pinnedFiles?.cleanup(), preparedSandboxRuntime?.cleanup()].filter(
|
|
624
|
+
(task): task is Promise<void> => task !== undefined,
|
|
625
|
+
)
|
|
626
|
+
const outcomes = await Promise.allSettled(cleanup)
|
|
627
|
+
const failed = outcomes.find((outcome) => outcome.status === 'rejected')
|
|
628
|
+
if (failed?.status === 'rejected') cleanupError = failed.reason
|
|
629
|
+
}
|
|
630
|
+
// Decorate genuine, user-correctable builtin file-tool failures with a
|
|
631
|
+
// recovery hint so weaker models retry correctly. Only executionError (not
|
|
632
|
+
// cleanupError) and only non-aborted Error instances; remediation is a
|
|
633
|
+
// no-op for every message/tool outside the allowlist, so abort, sandbox,
|
|
634
|
+
// and policy errors pass through untouched. Mutating the message in place
|
|
635
|
+
// preserves the error's subclass and stack for the rethrow.
|
|
636
|
+
if (executionError instanceof Error && signal?.aborted !== true) {
|
|
637
|
+
executionError.message = remediateToolErrorMessage(tool.name, executionError.message)
|
|
458
638
|
}
|
|
459
|
-
const
|
|
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
|
|
460
648
|
const resolved = loopGate.resolve({ content: result.content as ContentPart[], details: result.details })
|
|
461
649
|
if ('deferredBlock' in resolved) {
|
|
462
650
|
fireLoopAbort(opts.getAbort, 'loop_guard:deferred_block')
|
|
@@ -505,9 +693,31 @@ export function buildBuiltinPiToolOverrides(opts: WrapSystemToolOptions): ToolDe
|
|
|
505
693
|
return defaultBuiltinPiToolDefinitions(opts.agentDir).map((tool) => wrapBuiltinToolDefinition(tool, opts))
|
|
506
694
|
}
|
|
507
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
|
+
|
|
508
718
|
// Rewrites mutableArgs.command in place so the bash builtin runs inside bwrap
|
|
509
|
-
// with role-derived
|
|
510
|
-
//
|
|
719
|
+
// with role-derived private-directory masks and unconditional canonical-secret
|
|
720
|
+
// file masks. When masks are needed but bwrap is unavailable
|
|
511
721
|
// we throw rather than run unsandboxed — fail closed, never leak the masked
|
|
512
722
|
// surface. Runs after the tool.before guards have inspected the raw command.
|
|
513
723
|
async function applyBashSandbox(
|
|
@@ -517,123 +727,128 @@ async function applyBashSandbox(
|
|
|
517
727
|
agentDir: string,
|
|
518
728
|
sessionId: string,
|
|
519
729
|
envOverlay: BashEnvOverlay | undefined,
|
|
520
|
-
|
|
730
|
+
boundary: BashSandboxBoundary,
|
|
731
|
+
): Promise<PreparedBashSandbox> {
|
|
521
732
|
const command = mutableArgs.command
|
|
522
|
-
if (typeof command !== 'string') return
|
|
733
|
+
if (typeof command !== 'string') return { verify: async () => {}, cleanup: async () => {} }
|
|
523
734
|
|
|
524
|
-
|
|
525
|
-
if (dirs.length === 0 && files.length === 0) return
|
|
735
|
+
await assertNoCanonicalSecretsInGit(agentDir)
|
|
526
736
|
|
|
737
|
+
const { dirs, files } = resolveHiddenPaths(permissions, origin, agentDir)
|
|
527
738
|
const sandboxEnvOverlay = buildRoleScopedConfigEnv(agentDir, dirs, envOverlay)
|
|
528
|
-
|
|
529
|
-
await ensureBwrapAvailable()
|
|
530
|
-
// bwrap's --ro-bind-data/--tmpfs mask ops abort when the target does not exist
|
|
531
|
-
// on the (read-only, virtiofs/OrbStack) agent-folder bind. Materialize the mask
|
|
532
|
-
// targets on the real host FS first; the full {dirs, files} still feeds
|
|
533
|
-
// subtractMasked below so a masked path is never re-exposed by a later RW bind.
|
|
534
739
|
const maskTargets = await ensureHiddenMaskTargets({ dirs, files })
|
|
535
|
-
|
|
536
|
-
// --tmpfs /tmp so writes survive across the role's sandboxed bash calls AND
|
|
537
|
-
// match what the write/edit wrapper redirected a /tmp path to. The bind is
|
|
538
|
-
// emitted via policy.mounts (after the hardcoded --tmpfs /tmp), so last-op-
|
|
539
|
-
// wins makes it the live /tmp. Unsandboxed roles (empty masks, returned
|
|
540
|
-
// above) keep sharing the real container /tmp between write and bash.
|
|
740
|
+
await boundary.ensureAvailable()
|
|
541
741
|
const sessionTmp = await ensureSessionTmpDir(sessionId)
|
|
542
|
-
// Write-confined jail for low-trust roles: bind the whole project read-only,
|
|
543
|
-
// hide private/secret paths, then re-expose only the free-write scratch zones
|
|
544
|
-
// (workspace + root allowlist + .git) RW. The WORKING TREE outside those zones
|
|
545
|
-
// (node_modules/, agentDir root, non-allowlisted tracked files) stays EROFS, so
|
|
546
|
-
// bash cannot sidestep the non-workspace-write guard — and `git checkout` of a
|
|
547
|
-
// protected worktree path fails at the kernel. .git is RW so members can
|
|
548
|
-
// commit; .git/hooks + .git/config (and any writable core.hooksPath target)
|
|
549
|
-
// are re-protected RO (protected, rendered after writable, ensured to exist so
|
|
550
|
-
// an absent path can't be created+executed) so a hook-plant / core.hooksPath
|
|
551
|
-
// never becomes code execution in the unsandboxed runtime git ops. Trusted/owner never reach here
|
|
552
|
-
// (their masks are empty) and keep full unsandboxed access. subtractMasked
|
|
553
|
-
// drops any writable zone masked for this role so an RW bind never re-exposes a
|
|
554
|
-
// hidden path (e.g. a guest's masked workspace/).
|
|
555
|
-
// config.sandbox.* is read from the BOOT-TIME snapshot, not getConfig():
|
|
556
|
-
// sandbox is restart-required, so the writable surface AND the in-jail symlinks
|
|
557
|
-
// must stay coherent with the boot-time bwrap/capability decisions and with the
|
|
558
|
-
// entrypoint shim's symlink creation (same contract as resolveProcStrategy's
|
|
559
|
-
// read of config.sandbox.realProc below). getSandboxWritablePathSpecs folds
|
|
560
|
-
// every sandbox.symlinks[].to into the writable set so the symlink target is
|
|
561
|
-
// writable without the operator also listing it under writablePaths.
|
|
562
742
|
const writable = subtractMasked(await resolveWritableZones(agentDir, getSandboxWritablePathSpecs(config)), {
|
|
563
743
|
dirs,
|
|
564
744
|
files,
|
|
565
745
|
})
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
const protectedZones = writable.dirs.includes(join(agentDir, '.git'))
|
|
572
|
-
? subtractMasked(await resolveProtectedZones(agentDir), { dirs, files })
|
|
573
|
-
: { dirs: [], files: [] }
|
|
574
|
-
// A recognized standalone `bun add`/`bun install` needs DIRECTORY write at the
|
|
575
|
-
// root (node_modules/ + temp lockfile), which the narrow carve-out model can't
|
|
576
|
-
// grant. Widen to an RW root for that command class only, then re-hide secrets
|
|
577
|
-
// (masks) and re-RO the executable surfaces (resolvePackageInstallZones) on top
|
|
578
|
-
// — subtractMasked drops any protected path a mask already hides so the RW root
|
|
579
|
-
// never re-exposes it. The default jail's `writable`/`protected` are skipped
|
|
580
|
-
// here: writableRoot supersedes them for this command, and the same masks +
|
|
581
|
-
// package-install protected set cover the confidentiality and escalation
|
|
582
|
-
// boundaries.
|
|
583
|
-
const packageInstall = isPackageInstallCommand(command)
|
|
584
|
-
? subtractMaskedProtected(await resolvePackageInstallZones(agentDir), { dirs, files })
|
|
585
|
-
: undefined
|
|
586
|
-
|
|
587
|
-
// Only emit an in-jail symlink for a target that actually survived as a
|
|
588
|
-
// writable dir: a symlink to a target that was dropped (missing, masked for
|
|
589
|
-
// this role, or filtered by the writable-zone guardrails) would dangle onto an
|
|
590
|
-
// EROFS/hidden path. Resolve `from` against the SANDBOX HOME (/tmp), where the
|
|
591
|
-
// per-session tmp dir is bound — NOT the container's real /root, which the jail
|
|
592
|
-
// never sees. The entrypoint shim handles the real-/root symlink for the
|
|
593
|
-
// unsandboxed (trusted/owner) path.
|
|
746
|
+
const writableRoot = canWriteAgentRootInSandbox(permissions, origin)
|
|
747
|
+
const protectedZones =
|
|
748
|
+
writableRoot || writable.dirs.includes(join(agentDir, '.git'))
|
|
749
|
+
? subtractMasked(await resolveProtectedZones(agentDir), { dirs, files })
|
|
750
|
+
: { dirs: [], files: [] }
|
|
594
751
|
const writableDirSet = new Set(writable.dirs)
|
|
595
752
|
const sandboxHome = DEFAULT_SANDBOX_ENV.HOME ?? '/tmp'
|
|
596
753
|
const symlinks = resolveSandboxSymlinks(agentDir, config.sandbox.symlinks, sandboxHome).filter((op) =>
|
|
597
754
|
writableDirSet.has(op.target),
|
|
598
755
|
)
|
|
599
|
-
// bwrap does --clearenv, so the overlay must be re-introduced via env.set or
|
|
600
|
-
// it would never reach the sandboxed process (the non-sandboxed spawnHook
|
|
601
|
-
// path does not run when the command is rewritten to a bwrap invocation).
|
|
602
756
|
const { strategy: proc, degradeReason } = await resolveProcStrategy()
|
|
603
|
-
// Fail fast with an actionable error when /proc degraded to tmpfs AND the
|
|
604
|
-
// command needs a real /proc: under tmpfs Bun would otherwise abort deep in its
|
|
605
|
-
// pipeline with the opaque "NotDir", which the model retries forever. Which
|
|
606
|
-
// error depends on WHY it degraded: a 'definitive' degrade (a real leak / an
|
|
607
|
-
// incapable host) is permanent → SandboxDegradedProcError ("retrying won't
|
|
608
|
-
// help"); an 'unverified' degrade (the safety probe stayed inconclusive through
|
|
609
|
-
// its retry budget, e.g. a boot-time load spike) is transient and re-probes on
|
|
610
|
-
// the next call → SandboxProcProbeUnverifiedError ("retry the same command").
|
|
611
|
-
// Guarded on the command so non-bun bash still runs in the degraded mode (it
|
|
612
|
-
// does not touch /proc/self/{fd,maps}).
|
|
613
757
|
if (proc === 'tmpfs' && commandNeedsRealProc(command)) {
|
|
614
758
|
throw degradeReason === 'unverified' ? new SandboxProcProbeUnverifiedError() : new SandboxDegradedProcError()
|
|
615
759
|
}
|
|
616
|
-
const
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
],
|
|
621
|
-
...(packageInstall !== undefined
|
|
622
|
-
? {
|
|
623
|
-
writableRoot: { dir: packageInstall.root },
|
|
624
|
-
masks: maskTargets,
|
|
625
|
-
protected: packageInstall.protected,
|
|
626
|
-
blockedCreation: { files: packageInstall.blockedCreation },
|
|
627
|
-
}
|
|
628
|
-
: { masks: maskTargets, writable, protected: protectedZones }),
|
|
629
|
-
symlinks,
|
|
630
|
-
network: 'inherit',
|
|
631
|
-
cwd: agentDir,
|
|
632
|
-
proc,
|
|
633
|
-
procSelfExe: resolveProcSelfExe(),
|
|
634
|
-
...(sandboxEnvOverlay !== undefined ? { env: { set: sandboxEnvOverlay } } : {}),
|
|
760
|
+
const privilegedRuntime = await (boundary.resolveRuntime ?? resolvePrivilegedSandboxRuntime)({
|
|
761
|
+
agentDir,
|
|
762
|
+
command,
|
|
763
|
+
env: sandboxEnvOverlay,
|
|
635
764
|
})
|
|
636
|
-
|
|
765
|
+
const cleanup = async (): Promise<void> =>
|
|
766
|
+
(boundary.cleanupRuntime ?? cleanupPrivilegedSandboxRuntime)(privilegedRuntime)
|
|
767
|
+
try {
|
|
768
|
+
await verifyHiddenMaskTargets(maskTargets)
|
|
769
|
+
const { commandString, spawnEnv } = boundary.buildCommand(command, {
|
|
770
|
+
mounts: [
|
|
771
|
+
{ type: 'ro-bind', source: agentDir, dest: agentDir },
|
|
772
|
+
{ type: 'bind', source: sessionTmp, dest: '/tmp' },
|
|
773
|
+
...(privilegedRuntime?.mounts ?? []),
|
|
774
|
+
],
|
|
775
|
+
...(writableRoot
|
|
776
|
+
? { writableRoot: { dir: agentDir }, masks: maskTargets, protected: protectedZones }
|
|
777
|
+
: { masks: maskTargets, writable, protected: protectedZones }),
|
|
778
|
+
symlinks,
|
|
779
|
+
network: 'inherit',
|
|
780
|
+
cwd: agentDir,
|
|
781
|
+
proc,
|
|
782
|
+
procSelfExe: resolveProcSelfExe(),
|
|
783
|
+
...spreadSandboxEnv(
|
|
784
|
+
buildSandboxEnvPolicy(sandboxEnvOverlay, privilegedRuntime?.env, resolveExposableBashEnvNames(agentDir)),
|
|
785
|
+
),
|
|
786
|
+
})
|
|
787
|
+
mutableArgs.command = commandString
|
|
788
|
+
// The overlay carries command-scoped secret VALUES (e.g. a per-repo GH_TOKEN)
|
|
789
|
+
// that live in neither process.env nor argv; resolveSpawnEnv snapshots
|
|
790
|
+
// inherited names from process.env only, so merge the overlay values in here
|
|
791
|
+
// to complete the exact bwrap-parent env.
|
|
792
|
+
const mergedSpawnEnv =
|
|
793
|
+
spawnEnv !== undefined && sandboxEnvOverlay !== undefined ? { ...spawnEnv, ...sandboxEnvOverlay } : spawnEnv
|
|
794
|
+
return {
|
|
795
|
+
verify: async () => (boundary.verifyRuntime ?? verifyPrivilegedSandboxRuntime)(privilegedRuntime),
|
|
796
|
+
cleanup,
|
|
797
|
+
spawnEnv: mergedSpawnEnv,
|
|
798
|
+
}
|
|
799
|
+
} catch (error) {
|
|
800
|
+
await cleanup()
|
|
801
|
+
throw error
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
export function buildSandboxEnvPolicy(
|
|
806
|
+
overlay: BashEnvOverlay | undefined,
|
|
807
|
+
runtimeEnv: Record<string, string> | undefined,
|
|
808
|
+
exposableEnvNames: readonly string[] = [],
|
|
809
|
+
): { inherit?: string[]; set?: Record<string, string> } {
|
|
810
|
+
const set = { ...runtimeEnv }
|
|
811
|
+
const inherit: string[] = []
|
|
812
|
+
const inheritSeen = new Set<string>()
|
|
813
|
+
const pushInherit = (key: string): void => {
|
|
814
|
+
if (Object.hasOwn(set, key) || inheritSeen.has(key)) return
|
|
815
|
+
inheritSeen.add(key)
|
|
816
|
+
inherit.push(key)
|
|
817
|
+
}
|
|
818
|
+
for (const [key, value] of Object.entries(overlay ?? {})) {
|
|
819
|
+
if (Object.hasOwn(set, key)) continue
|
|
820
|
+
if (isOverlaySecretName(key)) pushInherit(key)
|
|
821
|
+
else set[key] = value
|
|
822
|
+
}
|
|
823
|
+
// Operator-declared .env vars pass through by NAME (inherit), keeping values
|
|
824
|
+
// out of the rendered bwrap argv. Sandbox-integrity names were already dropped
|
|
825
|
+
// in resolveExposableEnvNames — these are the survivors.
|
|
826
|
+
for (const key of exposableEnvNames) pushInherit(key)
|
|
827
|
+
// Pass the entrypoint-exported Xvfb display (start_xvfb: `export DISPLAY=:99`)
|
|
828
|
+
// through --clearenv, else sandboxed `agent-browser --headed` dies with
|
|
829
|
+
// "Missing X server or $DISPLAY". Passing the runtime's OWN value (not a fixed
|
|
830
|
+
// ":99") keeps `docker.file.xvfb=false` advertising no display. Rendered via
|
|
831
|
+
// `set` (a display number is neither a credential nor shell-injectable), and no
|
|
832
|
+
// /tmp/.X11-unix bind is needed: Chrome reaches Xvfb over the netns-scoped
|
|
833
|
+
// abstract X11 socket while bash keeps network:'inherit'.
|
|
834
|
+
const display = process.env['DISPLAY']
|
|
835
|
+
if (display !== undefined && display !== '' && !Object.hasOwn(set, 'DISPLAY') && !inheritSeen.has('DISPLAY')) {
|
|
836
|
+
set['DISPLAY'] = display
|
|
837
|
+
}
|
|
838
|
+
return {
|
|
839
|
+
...(inherit.length > 0 ? { inherit } : {}),
|
|
840
|
+
...(Object.keys(set).length > 0 ? { set } : {}),
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
function spreadSandboxEnv(policy: ReturnType<typeof buildSandboxEnvPolicy>): {
|
|
845
|
+
env?: ReturnType<typeof buildSandboxEnvPolicy>
|
|
846
|
+
} {
|
|
847
|
+
return Object.keys(policy).length > 0 ? { env: policy } : {}
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
function resolveExposableBashEnvNames(agentDir: string): string[] {
|
|
851
|
+
return resolveExposableEnvNames(readEnvFile(agentDir))
|
|
637
852
|
}
|
|
638
853
|
|
|
639
854
|
function buildRoleScopedConfigEnv(
|
|
@@ -644,8 +859,8 @@ function buildRoleScopedConfigEnv(
|
|
|
644
859
|
// Low-trust roles have workspace/ masked. Do not let container-global config
|
|
645
860
|
// env vars point CLIs back at that private surface: apps that honor XDG should
|
|
646
861
|
// still run, but their config must land in the sandbox's per-session /tmp.
|
|
647
|
-
// Trusted/owner
|
|
648
|
-
//
|
|
862
|
+
// Trusted/owner have only the unconditional credential-dir masks, not the
|
|
863
|
+
// workspace root mask, so their command broker decides whether to set GWS.
|
|
649
864
|
const workspaceHidden = hiddenDirs.includes(join(agentDir, 'workspace'))
|
|
650
865
|
if (!workspaceHidden) return envOverlay
|
|
651
866
|
|
|
@@ -656,14 +871,6 @@ function buildRoleScopedConfigEnv(
|
|
|
656
871
|
}
|
|
657
872
|
}
|
|
658
873
|
|
|
659
|
-
function subtractMaskedProtected(
|
|
660
|
-
zones: { root: string; protected: { dirs: string[]; files: string[] }; blockedCreation: string[] },
|
|
661
|
-
masked: { dirs: string[]; files: string[] },
|
|
662
|
-
): { root: string; protected: { dirs: string[]; files: string[] }; blockedCreation: string[] } {
|
|
663
|
-
const filtered = subtractMasked(zones.protected, masked)
|
|
664
|
-
return { root: zones.root, protected: filtered, blockedCreation: zones.blockedCreation }
|
|
665
|
-
}
|
|
666
|
-
|
|
667
874
|
// Picks the /proc strategy for a sandboxed bash call. The branch order is:
|
|
668
875
|
// 'real-proc' ONLY when the operator explicitly opted in (sandbox.realProc) AND
|
|
669
876
|
// the kernel permits the mount (canMountRealProc) — it adds PID isolation but
|
|
@@ -709,7 +916,7 @@ async function resolveProcStrategy(): Promise<ProcStrategyResolution> {
|
|
|
709
916
|
)
|
|
710
917
|
if (verdict === 'safe') return { strategy: 'proc-bind' }
|
|
711
918
|
// Degraded last resort: no working /proc strategy. External package runners
|
|
712
|
-
// (bunx/bun
|
|
919
|
+
// (bunx/bun run <pkg-bin>) will fail with Bun's opaque "NotDir" because
|
|
713
920
|
// /proc/self/{fd,maps} are absent. Only a proven 'unsafe' (a real cross-userns
|
|
714
921
|
// leak) is DEFINITIVE — warn once (a real operator-facing limit). An
|
|
715
922
|
// 'inconclusive' is reported as retryable upstream and NOT warned (it would cry
|
|
@@ -728,25 +935,26 @@ function warnTmpfsProcFallbackOnce(): void {
|
|
|
728
935
|
tmpfsProcFallbackWarned = true
|
|
729
936
|
console.warn(
|
|
730
937
|
'[sandbox] degraded /proc mode: neither real-proc nor proc-bind is available on this host, ' +
|
|
731
|
-
'so sandboxed external package runners (bunx / bun
|
|
938
|
+
'so sandboxed external package runners (bunx / bun run <pkg-bin>) will fail. ' +
|
|
732
939
|
'This needs a runtime with working user namespaces.',
|
|
733
940
|
)
|
|
734
941
|
}
|
|
735
942
|
|
|
736
|
-
// The builtin file tools that take a single filesystem `path` arg.
|
|
737
|
-
//
|
|
738
|
-
//
|
|
943
|
+
// The builtin file tools that take a single filesystem `path` arg. They run in
|
|
944
|
+
// the main process rather than bwrap, so each must apply the same
|
|
945
|
+
// /tmp -> session-dir mapping that
|
|
739
946
|
// applyBashSandbox binds for bash — otherwise a `read` of /tmp/foo hits the
|
|
740
947
|
// real container /tmp while sandboxed bash wrote the session backing dir.
|
|
741
948
|
const TMP_REDIRECT_TOOLS = new Set(['read', 'write', 'edit', 'grep', 'find', 'ls'])
|
|
742
949
|
|
|
743
|
-
//
|
|
744
|
-
// but the path-based file tools run
|
|
950
|
+
// Model-driven bash reads /tmp through bwrap's per-session bind
|
|
951
|
+
// (applyBashSandbox), but the path-based file tools run in the main process
|
|
952
|
+
// against the real container /tmp.
|
|
745
953
|
// Without this redirect a guest/member that touches /tmp/foo through bash (bound
|
|
746
954
|
// to the session dir) and through a file tool (real /tmp) would see two
|
|
747
955
|
// different files. Rewriting the file tool's on-disk path to the same session
|
|
748
|
-
// backing dir makes every layer resolve /tmp/foo to one file.
|
|
749
|
-
//
|
|
956
|
+
// backing dir makes every layer resolve /tmp/foo to one file. Bare harnesses
|
|
957
|
+
// without the production permission wiring are left untouched.
|
|
750
958
|
type TmpRedirect = { original: string; backing: string }
|
|
751
959
|
|
|
752
960
|
async function applyTmpPathRedirect(
|
|
@@ -790,6 +998,12 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
|
|
790
998
|
return typeof value === 'object' && value !== null
|
|
791
999
|
}
|
|
792
1000
|
|
|
1001
|
+
function normalizeDefaultTreeRoot(toolName: string, args: Record<string, unknown>): void {
|
|
1002
|
+
if ((toolName === 'grep' || toolName === 'find' || toolName === 'ls') && typeof args.path !== 'string') {
|
|
1003
|
+
args.path = '.'
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
|
|
793
1007
|
function appendLoopWarning(result: ToolResult, message: string): ToolResult {
|
|
794
1008
|
const content: ContentPart[] = [...(result.content as ContentPart[]), { type: 'text', text: message }]
|
|
795
1009
|
return { content, details: result.details }
|
|
@@ -818,6 +1032,44 @@ function subagentPollStatus(toolName: string, result: ToolResult): 'running' | '
|
|
|
818
1032
|
return details.status === 'running' ? 'running' : 'terminal'
|
|
819
1033
|
}
|
|
820
1034
|
|
|
1035
|
+
function observedReadResult(
|
|
1036
|
+
toolName: string,
|
|
1037
|
+
result: ToolResult,
|
|
1038
|
+
): { nonEmpty: boolean; outputLines?: number; textual: boolean } | undefined {
|
|
1039
|
+
if (toolName !== 'read') return undefined
|
|
1040
|
+
const details = result.details as { truncation?: { outputLines?: unknown } } | undefined
|
|
1041
|
+
const outputLines = details?.truncation?.outputLines
|
|
1042
|
+
const hasImage = result.content.some((part) => part.type === 'image')
|
|
1043
|
+
const hasText = result.content.some(
|
|
1044
|
+
(part) => part.type === 'text' && typeof part.text === 'string' && part.text.trim().length > 0,
|
|
1045
|
+
)
|
|
1046
|
+
const imageFallback =
|
|
1047
|
+
!hasImage &&
|
|
1048
|
+
result.content.some(
|
|
1049
|
+
(part) => part.type === 'text' && typeof part.text === 'string' && /^Read image file \[[^\]]+\]/.test(part.text),
|
|
1050
|
+
)
|
|
1051
|
+
const observedOutputLines =
|
|
1052
|
+
typeof outputLines === 'number' && Number.isFinite(outputLines)
|
|
1053
|
+
? outputLines
|
|
1054
|
+
: !hasImage && !imageFallback
|
|
1055
|
+
? countReadOutputLines(result.content)
|
|
1056
|
+
: undefined
|
|
1057
|
+
return {
|
|
1058
|
+
nonEmpty: hasImage || hasText,
|
|
1059
|
+
textual: !hasImage && !imageFallback,
|
|
1060
|
+
...(observedOutputLines !== undefined ? { outputLines: observedOutputLines } : {}),
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
function countReadOutputLines(content: ContentPart[]): number | undefined {
|
|
1065
|
+
const textParts = content.filter(
|
|
1066
|
+
(part): part is Extract<ContentPart, { type: 'text' }> => part.type === 'text' && typeof part.text === 'string',
|
|
1067
|
+
)
|
|
1068
|
+
if (textParts.length !== 1) return undefined
|
|
1069
|
+
const fileText = textParts[0]!.text.replace(/\n\n\[\d+ more lines in file\. Use offset=\d+ to continue\.\]$/, '')
|
|
1070
|
+
return fileText.length === 0 ? 0 : fileText.split('\n').length
|
|
1071
|
+
}
|
|
1072
|
+
|
|
821
1073
|
type LoopGuardGate = {
|
|
822
1074
|
// True when the guard wants to block AND the block is enforced now (every tool
|
|
823
1075
|
// except a deferable `subagent_output` poll). The caller aborts + errors.
|
|
@@ -835,13 +1087,21 @@ type LoopGuardGate = {
|
|
|
835
1087
|
// semantics. `check` runs here (recording the observation); the returned
|
|
836
1088
|
// `resolve` is called after execute with the tool's result, feeding the poll's
|
|
837
1089
|
// running/terminal status back to the guard so future blocks stop deferring.
|
|
838
|
-
function gateLoopGuard(
|
|
839
|
-
|
|
1090
|
+
function gateLoopGuard(
|
|
1091
|
+
sessionId: string,
|
|
1092
|
+
toolName: string,
|
|
1093
|
+
args: unknown,
|
|
1094
|
+
turnId?: number,
|
|
1095
|
+
cwd?: string,
|
|
1096
|
+
): LoopGuardGate {
|
|
1097
|
+
const decision = sharedLoopGuard.check(sessionId, toolName, args, { turnId, cwd })
|
|
840
1098
|
const defer = shouldDeferLoopBlock(toolName, decision)
|
|
841
1099
|
return {
|
|
842
1100
|
blockNow: decision.kind === 'block' && !defer,
|
|
843
1101
|
message: decision.kind === 'ok' ? '' : decision.message,
|
|
844
1102
|
resolve(result) {
|
|
1103
|
+
const readResult = observedReadResult(toolName, result)
|
|
1104
|
+
if (readResult !== undefined) sharedLoopGuard.noteReadResult(decision.receipt, readResult)
|
|
845
1105
|
const pollStatus = subagentPollStatus(toolName, result)
|
|
846
1106
|
if (pollStatus !== undefined) {
|
|
847
1107
|
sharedLoopGuard.noteResult(decision.receipt, pollStatus)
|
|
@@ -901,12 +1161,28 @@ function errorResult(message: string) {
|
|
|
901
1161
|
|
|
902
1162
|
async function runFinalWriteGuards(options: { tool: string; args: Record<string, unknown>; agentDir: string }) {
|
|
903
1163
|
return (
|
|
1164
|
+
(await checkGitControlWriteGuard(options)) ??
|
|
904
1165
|
(await checkManagedConfigGuard(options)) ??
|
|
905
1166
|
(await checkSkillAuthoringGuard(options)) ??
|
|
906
1167
|
checkNonWorkspaceWriteGuard(options)
|
|
907
1168
|
)
|
|
908
1169
|
}
|
|
909
1170
|
|
|
1171
|
+
async function checkGitControlWriteGuard(options: {
|
|
1172
|
+
tool: string
|
|
1173
|
+
args: Record<string, unknown>
|
|
1174
|
+
agentDir: string
|
|
1175
|
+
}): Promise<{ block: true; reason: string } | undefined> {
|
|
1176
|
+
if (options.tool !== 'write' && options.tool !== 'edit') return undefined
|
|
1177
|
+
const candidate = options.args.path
|
|
1178
|
+
if (typeof candidate !== 'string') return undefined
|
|
1179
|
+
if (!(await isGitControlPath(options.agentDir, candidate))) return undefined
|
|
1180
|
+
return {
|
|
1181
|
+
block: true,
|
|
1182
|
+
reason: `Git control path is runtime-protected and cannot be modified with ${options.tool}: ${candidate}`,
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
|
|
910
1186
|
function runFinalReadGuards(options: { tool: string; args: Record<string, unknown> }) {
|
|
911
1187
|
return checkImageReadRedirect(options)
|
|
912
1188
|
}
|