typeclaw 0.47.1 → 0.48.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/package.json +1 -1
- package/src/agent/index.ts +1 -2
- package/src/agent/loop-guard.ts +71 -41
- package/src/agent/plugin-tools.ts +167 -50
- package/src/agent/retry-same-ref.ts +89 -9
- package/src/agent/subagents.ts +88 -15
- package/src/agent/system-prompt.ts +1 -1
- package/src/agent/turn-runner.ts +60 -5
- package/src/bundled-plugins/agent-browser/index.ts +0 -35
- package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +1 -1
- package/src/bundled-plugins/guard/policies/non-workspace-write.ts +16 -1
- package/src/bundled-plugins/memory/append-tool.ts +75 -2
- package/src/bundled-plugins/memory/frontmatter.ts +13 -2
- package/src/bundled-plugins/memory/load-memory.ts +1 -1
- package/src/bundled-plugins/memory/memory-logger.ts +5 -1
- package/src/bundled-plugins/memory/secret-detector.ts +7 -0
- package/src/bundled-plugins/memory/vector/hybrid.ts +3 -1
- package/src/bundled-plugins/memory/vector/passages.ts +5 -1
- package/src/bundled-plugins/operator/operator.ts +9 -2
- package/src/bundled-plugins/researcher/researcher.ts +4 -6
- package/src/bundled-plugins/security/index.ts +148 -98
- package/src/bundled-plugins/security/policies/private-surface-read.ts +43 -28
- package/src/channels/adapters/discord-bot-edit.ts +3 -5
- package/src/channels/adapters/discord-bot-reactions.ts +4 -6
- package/src/channels/adapters/discord-bot-slash-commands.ts +3 -1
- package/src/channels/adapters/discord-bot.ts +20 -23
- package/src/channels/adapters/discord-edit.ts +3 -5
- package/src/channels/adapters/discord-reactions.ts +4 -6
- package/src/channels/adapters/discord.ts +1 -1
- package/src/channels/adapters/github/decoy-reviewer.ts +2 -1
- package/src/channels/adapters/github/history.ts +2 -1
- package/src/channels/adapters/github/inbound.ts +4 -11
- package/src/channels/adapters/github/index.ts +6 -9
- package/src/channels/adapters/github/outbound.ts +3 -6
- package/src/channels/adapters/github/reactions.ts +3 -2
- package/src/channels/adapters/github/reconcile-cooldown-store.ts +4 -6
- package/src/channels/adapters/github/reconcile-open-prs.ts +5 -4
- package/src/channels/adapters/github/recover-failed-deliveries.ts +2 -5
- package/src/channels/adapters/github/review-state.ts +3 -2
- package/src/channels/adapters/github/review-thread-resolver.ts +3 -2
- package/src/channels/adapters/github/webhook-register.ts +5 -8
- package/src/channels/adapters/instagram-channel-resolver.ts +3 -5
- package/src/channels/adapters/instagram.ts +1 -1
- package/src/channels/adapters/kakaotalk-author-resolver.ts +2 -5
- package/src/channels/adapters/kakaotalk-channel-resolver.ts +3 -5
- package/src/channels/adapters/kakaotalk-fetch-attachment.ts +2 -1
- package/src/channels/adapters/kakaotalk-membership.ts +2 -5
- package/src/channels/adapters/kakaotalk-typing.ts +1 -1
- package/src/channels/adapters/kakaotalk.ts +1 -1
- package/src/channels/adapters/line-channel-resolver.ts +3 -5
- package/src/channels/adapters/line.ts +1 -1
- package/src/channels/adapters/slack-bot-edit.ts +1 -1
- package/src/channels/adapters/slack-bot-reactions.ts +4 -6
- package/src/channels/adapters/slack-bot.ts +8 -8
- package/src/channels/adapters/slack-edit.ts +3 -5
- package/src/channels/adapters/slack-reactions.ts +4 -6
- package/src/channels/adapters/slack.ts +1 -1
- package/src/channels/adapters/teams-edit.ts +2 -5
- package/src/channels/adapters/teams.ts +1 -1
- package/src/channels/adapters/telegram-bot-edit.ts +4 -7
- package/src/channels/adapters/telegram-bot.ts +1 -1
- package/src/channels/adapters/webex-bot.ts +1 -1
- package/src/channels/adapters/webex-edit.ts +3 -5
- package/src/channels/adapters/webex.ts +1 -1
- package/src/channels/github-review-claim.ts +89 -4
- package/src/channels/github-token-bridge.ts +2 -1
- package/src/channels/manager.ts +478 -64
- package/src/channels/membership-cache.ts +2 -5
- package/src/channels/persistence.ts +3 -6
- package/src/channels/reloadable.ts +23 -6
- package/src/channels/router.ts +134 -56
- package/src/channels/tunnel-bridge.ts +2 -1
- package/src/channels/types.ts +6 -3
- package/src/cli/hostd.ts +56 -28
- package/src/config/config.ts +10 -0
- package/src/config/providers.ts +179 -0
- package/src/dependencies/bin-resolver.ts +88 -0
- package/src/dependencies/bins.ts +227 -0
- package/src/dependencies/index.ts +17 -0
- package/src/doctor/checks.ts +2 -0
- package/src/doctor/operational-incidents.ts +32 -0
- package/src/hostd/credential-rotation-apply.ts +94 -0
- package/src/init/dockerfile.ts +36 -18
- package/src/init/index.ts +1 -1
- package/src/init/models-dev.ts +17 -3
- package/src/init/validate-api-key.ts +26 -4
- package/src/operations/classify-tool-outcome.ts +151 -0
- package/src/operations/incidents.ts +274 -0
- package/src/operations/index.ts +3 -0
- package/src/operations/remediations.ts +41 -0
- package/src/reload/client.ts +8 -2
- package/src/reload/docker-exec-client.ts +10 -2
- package/src/reload/index.ts +1 -1
- package/src/reload/recover.ts +5 -3
- package/src/reload/registry.ts +5 -5
- package/src/reload/types.ts +9 -1
- package/src/run/index.ts +5 -0
- package/src/sandbox/dependency-bins.ts +125 -0
- package/src/sandbox/errors.ts +32 -0
- package/src/sandbox/hidden-paths.ts +4 -1
- package/src/sandbox/index.ts +8 -0
- package/src/sandbox/policy.ts +1 -1
- package/src/sandbox/privileged-runtime.ts +88 -7
- package/src/sandbox/runtime-private.ts +4 -0
- package/src/sandbox/writable-zones.ts +4 -4
- package/src/server/index.ts +7 -5
- package/src/shared/protocol.ts +6 -1
- package/src/skills/typeclaw-monorepo/SKILL.md +1 -1
- package/src/skills/typeclaw-troubleshooting/SKILL.md +1 -1
- package/typeclaw.schema.json +35 -5
- package/src/bundled-plugins/agent-browser/shim-install.ts +0 -158
- package/src/bundled-plugins/agent-browser/shim.ts +0 -108
- /package/src/channels/{adapters/describe-error.ts → describe-error.ts} +0 -0
package/package.json
CHANGED
package/src/agent/index.ts
CHANGED
|
@@ -272,6 +272,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
|
|
|
272
272
|
// the chain when it recreates a session after the previous ref failed.
|
|
273
273
|
const activeRef: ModelRef = options.refOverride ?? resolved.ref
|
|
274
274
|
const { authStorage, modelRegistry } = getAuthFor(providerForModelRef(activeRef))
|
|
275
|
+
const sessionManager = options.sessionManager ?? SessionManager.inMemory()
|
|
275
276
|
|
|
276
277
|
const materializedSkills =
|
|
277
278
|
options.plugins && options.plugins.registry.skills.length > 0
|
|
@@ -357,8 +358,6 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
|
|
|
357
358
|
// session's stable identity (sessionManager.getSessionId()). Subscribers use
|
|
358
359
|
// that ID to distinguish the originating session from siblings on the
|
|
359
360
|
// container-restarting broadcast.
|
|
360
|
-
const sessionManager = options.sessionManager ?? SessionManager.inMemory()
|
|
361
|
-
|
|
362
361
|
// Stamp a one-shot custom entry naming the session's origin kind so
|
|
363
362
|
// `typeclaw usage` can bucket tokens by tui/cron/channel/subagent. Pi's
|
|
364
363
|
// `appendCustomEntry` is the blessed extension point: the entry persists
|
package/src/agent/loop-guard.ts
CHANGED
|
@@ -11,9 +11,10 @@ import { posix } from 'node:path'
|
|
|
11
11
|
// consecutive detector cannot see, e.g. read(a)→edit(b)→read(a)→edit(b)…, or
|
|
12
12
|
// re-reading one file with drifting offsets. Over a sliding window of the
|
|
13
13
|
// last WINDOW_SIZE calls, if one signature recurs WINDOW_SOFT_WARN times it
|
|
14
|
-
// warns and WINDOW_HARD_BLOCK times it blocks. Path-
|
|
15
|
-
//
|
|
16
|
-
//
|
|
14
|
+
// warns and WINDOW_HARD_BLOCK times it blocks. Path-only tools coarsen their
|
|
15
|
+
// signature to the path, while search tools retain the query as part of the
|
|
16
|
+
// target. Read and search calls additionally recognize one assistant tool
|
|
17
|
+
// batch, and reads recognize successfully-observed forward pagination, so
|
|
17
18
|
// productive inspection does not look like a reactive cycle.
|
|
18
19
|
//
|
|
19
20
|
// Both warn/block decisions carry the byte-identical or coarsened nudge text.
|
|
@@ -33,23 +34,25 @@ export const WINDOW_SIZE = 16
|
|
|
33
34
|
export const WINDOW_SOFT_WARN = 4
|
|
34
35
|
export const WINDOW_HARD_BLOCK = 6
|
|
35
36
|
|
|
36
|
-
//
|
|
37
|
-
//
|
|
38
|
-
// offset/limit collapses to a single signature. Two classes, because the
|
|
39
|
-
// builtins differ in whether the path is required:
|
|
37
|
+
// Path-bearing tools need coarser window signatures so presentation-only args
|
|
38
|
+
// cannot disguise repeated work. The target differs by tool class:
|
|
40
39
|
//
|
|
41
40
|
// - REQUIRED-path tools (read/write/edit): path is mandatory. Coarsen only
|
|
42
41
|
// when a path key is present; an absent path is malformed input, not a
|
|
43
42
|
// default, so we must NOT collapse such calls to a shared target.
|
|
44
|
-
// - DEFAULT-path tools (
|
|
45
|
-
//
|
|
46
|
-
//
|
|
47
|
-
//
|
|
43
|
+
// - DEFAULT-path tools (ls): path is OPTIONAL and defaults to the cwd (".").
|
|
44
|
+
// Omitting the path and varying only non-target args still hits the same
|
|
45
|
+
// directory, so an omitted/empty path coarsens to `${tool}#path:.` —
|
|
46
|
+
// otherwise those calls would evade the detector.
|
|
47
|
+
// - SEARCH-path tools (grep/find): path is also optional, but the pattern and
|
|
48
|
+
// matching controls are part of the research target. Different queries on
|
|
49
|
+
// one large file are legitimate fan-out, not repeated work.
|
|
48
50
|
//
|
|
49
51
|
// `glob` is intentionally absent: pi-coding-agent has no `glob` builtin (the
|
|
50
52
|
// glob-pattern arg lives inside grep/find), so listing it here matched nothing.
|
|
51
53
|
const REQUIRED_PATH_TOOLS = new Set(['read', 'write', 'edit'])
|
|
52
|
-
const DEFAULT_PATH_TOOLS = new Set(['
|
|
54
|
+
const DEFAULT_PATH_TOOLS = new Set(['ls'])
|
|
55
|
+
const SEARCH_PATH_TOOLS = new Set(['grep', 'find'])
|
|
53
56
|
const PATH_ARG_KEYS = ['path', 'file', 'filePath', 'filename']
|
|
54
57
|
const DEFAULT_PATH_TARGET = '.'
|
|
55
58
|
|
|
@@ -116,7 +119,7 @@ export type LoopGuard = {
|
|
|
116
119
|
// Undoes the one observation a prior `check` recorded, identified by its
|
|
117
120
|
// receipt. Pops that signature from the windowed history and, when the
|
|
118
121
|
// current consecutive streak is the call this receipt named, rewinds the
|
|
119
|
-
// streak by one. Suppressed same-batch
|
|
122
|
+
// streak by one. Suppressed same-batch target receipts are explicit no-ops so
|
|
120
123
|
// parallel sibling completion cannot retract the recorded observation. Used
|
|
121
124
|
// post-execution for a
|
|
122
125
|
// `subagent_output` poll that returned `status: 'running'` — a still-pending
|
|
@@ -147,11 +150,11 @@ type SessionState = {
|
|
|
147
150
|
// A block on such a signature is enforced pre-execute (not deferred), so a
|
|
148
151
|
// completed task is not re-polled forever just to re-learn it is done.
|
|
149
152
|
termKnown: Set<string>
|
|
150
|
-
//
|
|
151
|
-
//
|
|
152
|
-
//
|
|
153
|
-
|
|
154
|
-
|
|
153
|
+
// Parallel research siblings cannot react to one another's results. Counting
|
|
154
|
+
// a duplicated target within that batch toward a session-aborting threshold
|
|
155
|
+
// gives the model no chance to heed the warning and choose another approach.
|
|
156
|
+
targetTurnId: number | undefined
|
|
157
|
+
targetsThisTurn: Set<string>
|
|
155
158
|
// Observed contiguous line progress per recently-read canonical path.
|
|
156
159
|
// Suppressed siblings may wait here for earlier siblings to complete, but
|
|
157
160
|
// only exact adjacency advances the frontier.
|
|
@@ -263,20 +266,22 @@ export function createLoopGuard(options: CreateLoopGuardOptions = {}): LoopGuard
|
|
|
263
266
|
window: [],
|
|
264
267
|
windowWarned: new Set(),
|
|
265
268
|
termKnown: new Set(),
|
|
266
|
-
|
|
267
|
-
|
|
269
|
+
targetTurnId: undefined,
|
|
270
|
+
targetsThisTurn: new Set(),
|
|
268
271
|
readFrontiers: new Map(),
|
|
269
272
|
}
|
|
270
273
|
|
|
271
274
|
const readTarget = parseReadTarget(tool, args, context?.cwd)
|
|
272
275
|
const readPage = parseReadPage(tool, args, context?.cwd)
|
|
273
|
-
|
|
274
|
-
|
|
276
|
+
const turnTarget =
|
|
277
|
+
readTarget !== undefined ? readPathSignature(readTarget.path) : makeSearchTargetSignature(tool, args)
|
|
278
|
+
if (turnTarget !== undefined && context?.turnId !== undefined) {
|
|
279
|
+
if (targetSeenThisTurn(state, turnTarget, context.turnId, windowSize)) {
|
|
275
280
|
const receipt: LoopGuardReceipt = {
|
|
276
281
|
sessionId,
|
|
277
282
|
tool,
|
|
278
283
|
signature,
|
|
279
|
-
windowSignature:
|
|
284
|
+
windowSignature: turnTarget,
|
|
280
285
|
recorded: false,
|
|
281
286
|
...(readPage !== undefined ? { readPage } : {}),
|
|
282
287
|
}
|
|
@@ -348,11 +353,11 @@ export function createLoopGuard(options: CreateLoopGuardOptions = {}): LoopGuard
|
|
|
348
353
|
for (const sig of state.termKnown) {
|
|
349
354
|
if (signatureBelongsToTool(sig, tool)) state.termKnown.delete(sig)
|
|
350
355
|
}
|
|
351
|
-
|
|
352
|
-
state.
|
|
353
|
-
state.readPathsThisTurn.clear()
|
|
354
|
-
state.readFrontiers.clear()
|
|
356
|
+
for (const target of state.targetsThisTurn) {
|
|
357
|
+
if (signatureBelongsToTool(target, tool)) state.targetsThisTurn.delete(target)
|
|
355
358
|
}
|
|
359
|
+
if (state.targetsThisTurn.size === 0) state.targetTurnId = undefined
|
|
360
|
+
if (tool === 'read') state.readFrontiers.clear()
|
|
356
361
|
},
|
|
357
362
|
retract(receipt) {
|
|
358
363
|
if (!receipt.recorded) return
|
|
@@ -449,10 +454,10 @@ function makeCallSignature(tool: string, args: unknown): string {
|
|
|
449
454
|
}
|
|
450
455
|
}
|
|
451
456
|
|
|
452
|
-
// Coarsened signature for windowed detection: path-
|
|
453
|
-
// target path
|
|
454
|
-
//
|
|
455
|
-
// signature.
|
|
457
|
+
// Coarsened signature for windowed detection: path-only tools key on their
|
|
458
|
+
// target path, while searches keep semantic query arguments so parallel
|
|
459
|
+
// investigation of one large file does not look like repeated work. All other
|
|
460
|
+
// tools fall back to the exact signature.
|
|
456
461
|
function makeWindowSignature(tool: string, args: unknown, state: SessionState, cwd: string | undefined): string {
|
|
457
462
|
const readPage = parseReadPage(tool, args, cwd)
|
|
458
463
|
if (readPage !== undefined) {
|
|
@@ -463,6 +468,10 @@ function makeWindowSignature(tool: string, args: unknown, state: SessionState, c
|
|
|
463
468
|
: coarse
|
|
464
469
|
}
|
|
465
470
|
|
|
471
|
+
const searchTarget = makeSearchTargetSignature(tool, args)
|
|
472
|
+
if (searchTarget !== undefined) return searchTarget
|
|
473
|
+
if (SEARCH_PATH_TOOLS.has(tool)) return makeCallSignature(tool, args)
|
|
474
|
+
|
|
466
475
|
const isRequiredPath = REQUIRED_PATH_TOOLS.has(tool)
|
|
467
476
|
const isDefaultPath = DEFAULT_PATH_TOOLS.has(tool)
|
|
468
477
|
if ((isRequiredPath || isDefaultPath) && args !== null && typeof args === 'object') {
|
|
@@ -512,18 +521,39 @@ function readPathSignature(path: string): string {
|
|
|
512
521
|
return `read#path:${path}`
|
|
513
522
|
}
|
|
514
523
|
|
|
515
|
-
function
|
|
516
|
-
if (
|
|
517
|
-
|
|
518
|
-
|
|
524
|
+
function makeSearchTargetSignature(tool: string, args: unknown): string | undefined {
|
|
525
|
+
if (!SEARCH_PATH_TOOLS.has(tool) || args === null || typeof args !== 'object') return undefined
|
|
526
|
+
const record = args as Record<string, unknown>
|
|
527
|
+
const { pattern } = record
|
|
528
|
+
if (typeof pattern !== 'string') return undefined
|
|
529
|
+
|
|
530
|
+
const path = PATH_ARG_KEYS.map((key) => record[key]).find(
|
|
531
|
+
(value): value is string => typeof value === 'string' && value.length > 0,
|
|
532
|
+
)
|
|
533
|
+
const query =
|
|
534
|
+
tool === 'grep'
|
|
535
|
+
? {
|
|
536
|
+
pattern,
|
|
537
|
+
...(typeof record.glob === 'string' && record.glob.length > 0 ? { glob: record.glob } : {}),
|
|
538
|
+
...(record.ignoreCase === true ? { ignoreCase: true } : {}),
|
|
539
|
+
...(record.literal === true ? { literal: true } : {}),
|
|
540
|
+
}
|
|
541
|
+
: { pattern }
|
|
542
|
+
return `${tool}#search:${stableStringify({ path: path ?? DEFAULT_PATH_TARGET, query })}`
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
function targetSeenThisTurn(state: SessionState, target: string, turnId: number, maxTargets: number): boolean {
|
|
546
|
+
if (state.targetTurnId !== turnId) {
|
|
547
|
+
state.targetTurnId = turnId
|
|
548
|
+
state.targetsThisTurn.clear()
|
|
519
549
|
}
|
|
520
|
-
const seen = state.
|
|
521
|
-
if (seen) state.
|
|
522
|
-
state.
|
|
523
|
-
while (state.
|
|
524
|
-
const oldest = state.
|
|
550
|
+
const seen = state.targetsThisTurn.has(target)
|
|
551
|
+
if (seen) state.targetsThisTurn.delete(target)
|
|
552
|
+
state.targetsThisTurn.add(target)
|
|
553
|
+
while (state.targetsThisTurn.size > maxTargets) {
|
|
554
|
+
const oldest = state.targetsThisTurn.values().next().value
|
|
525
555
|
if (oldest === undefined) break
|
|
526
|
-
state.
|
|
556
|
+
state.targetsThisTurn.delete(oldest)
|
|
527
557
|
}
|
|
528
558
|
return seen
|
|
529
559
|
}
|
|
@@ -25,6 +25,16 @@ import {
|
|
|
25
25
|
} from '@/bundled-plugins/guard/policy'
|
|
26
26
|
import { config, getSandboxWritablePathSpecs } from '@/config/config'
|
|
27
27
|
import { readEnvFile } from '@/init/env-file'
|
|
28
|
+
import {
|
|
29
|
+
classifyToolOutcome,
|
|
30
|
+
deriveMechanicallyVerifiedIncidentFingerprints,
|
|
31
|
+
IncidentLedger,
|
|
32
|
+
operationalRemediations,
|
|
33
|
+
renderIncidentHint,
|
|
34
|
+
renderUntrackedIncidentHint,
|
|
35
|
+
repairAndRetryOnce,
|
|
36
|
+
} from '@/operations'
|
|
37
|
+
import type { RemediationRegistry } from '@/operations'
|
|
28
38
|
import type { PermissionService } from '@/permissions/permissions'
|
|
29
39
|
import type {
|
|
30
40
|
BuiltinToolRef,
|
|
@@ -43,12 +53,15 @@ import {
|
|
|
43
53
|
cleanupPrivilegedSandboxRuntime,
|
|
44
54
|
commandNeedsRealProc,
|
|
45
55
|
DEFAULT_SANDBOX_ENV,
|
|
56
|
+
DEPENDENCY_BIN_SANDBOX_DIR,
|
|
57
|
+
dependencyBinUnavailableHint,
|
|
46
58
|
ensureBwrapAvailable,
|
|
47
59
|
ensureHiddenMaskTargets,
|
|
48
60
|
ensureSessionTmpDir,
|
|
49
61
|
getProcBindSafetyVerdict,
|
|
50
62
|
isGitControlPath,
|
|
51
63
|
mapVirtualTmpPath,
|
|
64
|
+
reconcileDependencyBinWrappers,
|
|
52
65
|
resolveHiddenPaths,
|
|
53
66
|
resolvePrivilegedSandboxRuntime,
|
|
54
67
|
resolveProcBindSafetyWithRetry,
|
|
@@ -59,6 +72,7 @@ import {
|
|
|
59
72
|
SandboxPolicyError,
|
|
60
73
|
SandboxDegradedProcError,
|
|
61
74
|
SandboxProcProbeUnverifiedError,
|
|
75
|
+
type DependencyBinReconciliation,
|
|
62
76
|
subtractMasked,
|
|
63
77
|
verifyHiddenMaskTargets,
|
|
64
78
|
verifyPrivilegedSandboxRuntime,
|
|
@@ -284,6 +298,9 @@ export type WrapSystemToolOptions = {
|
|
|
284
298
|
// `src/agent/reviewer-bash-policy.ts`.
|
|
285
299
|
bashPolicy?: SubagentBashPolicy
|
|
286
300
|
bashSandboxBoundary?: BashSandboxBoundary
|
|
301
|
+
realProcDependencyCheck?: typeof commandNeedsRealProc
|
|
302
|
+
remediations?: RemediationRegistry
|
|
303
|
+
incidentLedger?: IncidentLedger
|
|
287
304
|
}
|
|
288
305
|
|
|
289
306
|
// Zod 4 emits a top-level `"$schema": "https://json-schema.org/draft/2020-12/schema"`
|
|
@@ -519,6 +536,8 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
|
|
|
519
536
|
parameters: withGuardAcknowledgements(tool.name, tool.parameters),
|
|
520
537
|
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
521
538
|
const mutableArgs = params as Record<string, unknown>
|
|
539
|
+
const originalBashCommand =
|
|
540
|
+
tool.name === 'bash' && typeof mutableArgs.command === 'string' ? mutableArgs.command : undefined
|
|
522
541
|
normalizeDefaultTreeRoot(tool.name, mutableArgs)
|
|
523
542
|
const liveOrigin = opts.getOrigin?.()
|
|
524
543
|
// Defense-in-depth: strip any pre-existing internal env-overlay key
|
|
@@ -574,59 +593,81 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
|
|
|
574
593
|
let rawResult: ToolResult | undefined
|
|
575
594
|
let executionError: unknown
|
|
576
595
|
let cleanupError: unknown
|
|
596
|
+
let sandboxedRealProcSucceeded = false
|
|
577
597
|
const sandboxBoundary = opts.bashSandboxBoundary ?? DEFAULT_BASH_SANDBOX_BOUNDARY
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
598
|
+
const incidentLedger = opts.incidentLedger ?? new IncidentLedger(opts.agentDir)
|
|
599
|
+
const originalArgs = { ...mutableArgs }
|
|
600
|
+
const executeAttempt = async (): Promise<void> => {
|
|
601
|
+
preparedSandboxRuntime = undefined
|
|
602
|
+
pinnedFiles = undefined
|
|
603
|
+
tmpRedirect = undefined
|
|
604
|
+
rawResult = undefined
|
|
605
|
+
executionError = undefined
|
|
606
|
+
cleanupError = undefined
|
|
607
|
+
sandboxedRealProcSucceeded = false
|
|
608
|
+
const attemptArgs = { ...originalArgs }
|
|
609
|
+
try {
|
|
610
|
+
if (tool.name === 'bash') {
|
|
611
|
+
if (opts.permissions === undefined) {
|
|
612
|
+
throw new SandboxPolicyError(
|
|
613
|
+
'model-driven bash has no permission service; refusing unsandboxed execution',
|
|
614
|
+
)
|
|
615
|
+
}
|
|
616
|
+
preparedSandboxRuntime = await applyBashSandbox(
|
|
617
|
+
attemptArgs,
|
|
618
|
+
opts.permissions,
|
|
619
|
+
liveOrigin,
|
|
620
|
+
opts.agentDir,
|
|
621
|
+
opts.sessionId,
|
|
622
|
+
bashEnvOverlay,
|
|
623
|
+
sandboxBoundary,
|
|
624
|
+
)
|
|
582
625
|
}
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
opts.permissions
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
626
|
+
|
|
627
|
+
tmpRedirect =
|
|
628
|
+
TMP_REDIRECT_TOOLS.has(tool.name) && opts.permissions !== undefined
|
|
629
|
+
? await applyTmpPathRedirect(attemptArgs, opts.permissions, liveOrigin, opts.agentDir, opts.sessionId)
|
|
630
|
+
: undefined
|
|
631
|
+
pinnedFiles = await enforceAndPinToolFiles({
|
|
632
|
+
tool: tool.name,
|
|
633
|
+
args: attemptArgs,
|
|
634
|
+
agentDir: opts.agentDir,
|
|
635
|
+
...(opts.permissions !== undefined
|
|
636
|
+
? { hidden: resolveHiddenPaths(opts.permissions, liveOrigin, opts.agentDir) }
|
|
637
|
+
: {}),
|
|
638
|
+
signal,
|
|
639
|
+
})
|
|
640
|
+
await preparedSandboxRuntime?.verify()
|
|
641
|
+
const spawnEnvContext: BashSpawnEnvContext | undefined =
|
|
642
|
+
bashEnvOverlay !== undefined || preparedSandboxRuntime?.spawnEnv !== undefined
|
|
643
|
+
? {
|
|
644
|
+
...(bashEnvOverlay !== undefined ? { overlay: bashEnvOverlay } : {}),
|
|
645
|
+
...(preparedSandboxRuntime?.spawnEnv !== undefined
|
|
646
|
+
? { sandboxSpawnEnv: preparedSandboxRuntime.spawnEnv }
|
|
647
|
+
: {}),
|
|
648
|
+
}
|
|
649
|
+
: undefined
|
|
650
|
+
rawResult = await bashEnvStore.run(spawnEnvContext, () =>
|
|
651
|
+
tool.execute(toolCallId, attemptArgs as Static<TParams>, signal, onUpdate, ctx),
|
|
652
|
+
)
|
|
653
|
+
const originalCommand = originalArgs.command
|
|
654
|
+
sandboxedRealProcSucceeded =
|
|
655
|
+
preparedSandboxRuntime !== undefined &&
|
|
656
|
+
typeof originalCommand === 'string' &&
|
|
657
|
+
(opts.realProcDependencyCheck ?? commandNeedsRealProc)(originalCommand)
|
|
658
|
+
} catch (error) {
|
|
659
|
+
executionError = error
|
|
660
|
+
} finally {
|
|
661
|
+
const cleanup = [pinnedFiles?.cleanup(), preparedSandboxRuntime?.cleanup()].filter(
|
|
662
|
+
(task): task is Promise<void> => task !== undefined,
|
|
591
663
|
)
|
|
664
|
+
const outcomes = await Promise.allSettled(cleanup)
|
|
665
|
+
const failed = outcomes.find((outcome) => outcome.status === 'rejected')
|
|
666
|
+
if (failed?.status === 'rejected') cleanupError = failed.reason
|
|
592
667
|
}
|
|
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, () =>
|
|
618
|
-
tool.execute(toolCallId, mutableArgs as Static<TParams>, signal, onUpdate, ctx),
|
|
619
|
-
)
|
|
620
|
-
} catch (error) {
|
|
621
|
-
executionError = error
|
|
622
|
-
} finally {
|
|
623
|
-
const cleanup = [pinnedFiles?.cleanup(), preparedSandboxRuntime?.cleanup()].filter(
|
|
624
|
-
(task): task is Promise<void> => task !== undefined,
|
|
625
|
-
)
|
|
626
|
-
const outcomes = await Promise.allSettled(cleanup)
|
|
627
|
-
const failed = outcomes.find((outcome) => outcome.status === 'rejected')
|
|
628
|
-
if (failed?.status === 'rejected') cleanupError = failed.reason
|
|
629
668
|
}
|
|
669
|
+
|
|
670
|
+
await executeAttempt()
|
|
630
671
|
// Decorate genuine, user-correctable builtin file-tool failures with a
|
|
631
672
|
// recovery hint so weaker models retry correctly. Only executionError (not
|
|
632
673
|
// cleanupError) and only non-aborted Error instances; remediation is a
|
|
@@ -635,6 +676,46 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
|
|
|
635
676
|
// preserves the error's subclass and stack for the rethrow.
|
|
636
677
|
if (executionError instanceof Error && signal?.aborted !== true) {
|
|
637
678
|
executionError.message = remediateToolErrorMessage(tool.name, executionError.message)
|
|
679
|
+
const incidentFact = classifyToolOutcome({ tool: tool.name, error: executionError })
|
|
680
|
+
if (incidentFact !== null) {
|
|
681
|
+
const initialError = executionError
|
|
682
|
+
let recordedFingerprint: string | undefined
|
|
683
|
+
let incidentHint = renderUntrackedIncidentHint(incidentFact)
|
|
684
|
+
try {
|
|
685
|
+
const incident = await incidentLedger.record(incidentFact, opts.sessionId)
|
|
686
|
+
recordedFingerprint = incident.fingerprint
|
|
687
|
+
incidentHint = renderIncidentHint(incident)
|
|
688
|
+
} catch {
|
|
689
|
+
// Incident persistence must never hide the originating tool failure.
|
|
690
|
+
}
|
|
691
|
+
const remediation = await repairAndRetryOnce(
|
|
692
|
+
opts.remediations ?? operationalRemediations,
|
|
693
|
+
incidentFact,
|
|
694
|
+
initialError,
|
|
695
|
+
async () => {
|
|
696
|
+
await executeAttempt()
|
|
697
|
+
const retryError = executionError ?? cleanupError
|
|
698
|
+
if (retryError !== undefined) throw retryError
|
|
699
|
+
},
|
|
700
|
+
)
|
|
701
|
+
if (remediation.outcome === 'retried') {
|
|
702
|
+
const retrySuccessFingerprints = deriveMechanicallyVerifiedIncidentFingerprints({
|
|
703
|
+
tool: tool.name,
|
|
704
|
+
args: originalArgs,
|
|
705
|
+
sandboxedRealProcSucceeded,
|
|
706
|
+
})
|
|
707
|
+
if (recordedFingerprint !== undefined && retrySuccessFingerprints.has(recordedFingerprint)) {
|
|
708
|
+
await incidentLedger.resolve(recordedFingerprint).catch(() => false)
|
|
709
|
+
}
|
|
710
|
+
} else {
|
|
711
|
+
const failedError = remediation.outcome === 'retry-failed' ? remediation.error : initialError
|
|
712
|
+
const finalIncidentError = failedError instanceof Error ? failedError : new Error(String(failedError))
|
|
713
|
+
finalIncidentError.message = remediateToolErrorMessage(tool.name, finalIncidentError.message)
|
|
714
|
+
finalIncidentError.message = `${finalIncidentError.message}\n\n${incidentHint}`
|
|
715
|
+
executionError = finalIncidentError
|
|
716
|
+
cleanupError = undefined
|
|
717
|
+
}
|
|
718
|
+
}
|
|
638
719
|
}
|
|
639
720
|
const finalError = executionError ?? cleanupError
|
|
640
721
|
if (finalError !== undefined) {
|
|
@@ -644,7 +725,15 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
|
|
|
644
725
|
if (pinnedFiles === undefined) throw new Error('tool file boundary was not initialized')
|
|
645
726
|
if (rawResult === undefined) throw new Error('tool execution returned no result')
|
|
646
727
|
const pinnedResult = pinnedFiles.restoreResult(rawResult)
|
|
647
|
-
|
|
728
|
+
let result = tmpRedirect !== undefined ? restoreTmpPathInResult(pinnedResult, tmpRedirect) : pinnedResult
|
|
729
|
+
if (
|
|
730
|
+
originalBashCommand !== undefined &&
|
|
731
|
+
preparedSandboxRuntime?.dependencyBins !== undefined &&
|
|
732
|
+
bashResultIsCommandNotFound(result)
|
|
733
|
+
) {
|
|
734
|
+
const hint = dependencyBinUnavailableHint(originalBashCommand, preparedSandboxRuntime.dependencyBins)
|
|
735
|
+
if (hint !== undefined) result = appendTextResult(result, hint)
|
|
736
|
+
}
|
|
648
737
|
const resolved = loopGate.resolve({ content: result.content as ContentPart[], details: result.details })
|
|
649
738
|
if ('deferredBlock' in resolved) {
|
|
650
739
|
fireLoopAbort(opts.getAbort, 'loop_guard:deferred_block')
|
|
@@ -657,6 +746,12 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
|
|
|
657
746
|
callId: toolCallId,
|
|
658
747
|
result: hookResult,
|
|
659
748
|
})
|
|
749
|
+
const successFingerprints = deriveMechanicallyVerifiedIncidentFingerprints({
|
|
750
|
+
tool: tool.name,
|
|
751
|
+
args: originalArgs,
|
|
752
|
+
sandboxedRealProcSucceeded,
|
|
753
|
+
})
|
|
754
|
+
await incidentLedger.resolveObservedSuccess(successFingerprints).catch(() => 0)
|
|
660
755
|
return {
|
|
661
756
|
content: hookResult.content as ContentPart[],
|
|
662
757
|
details: hookResult.details as TDetails,
|
|
@@ -705,6 +800,7 @@ type PreparedBashSandbox = {
|
|
|
705
800
|
verify: () => Promise<void>
|
|
706
801
|
cleanup: () => Promise<void>
|
|
707
802
|
spawnEnv?: Record<string, string>
|
|
803
|
+
dependencyBins?: DependencyBinReconciliation
|
|
708
804
|
}
|
|
709
805
|
|
|
710
806
|
export function buildBashFilesystemPolicy(options: BashFilesystemPolicyOptions) {
|
|
@@ -737,15 +833,20 @@ async function applyBashSandbox(
|
|
|
737
833
|
const maskTargets = await ensureHiddenMaskTargets({ dirs, files })
|
|
738
834
|
await boundary.ensureAvailable()
|
|
739
835
|
const sessionTmp = await ensureSessionTmpDir(sessionId)
|
|
836
|
+
const dependencyBins = await reconcileDependencyBinWrappers({ agentDir, sessionTmp })
|
|
740
837
|
const writable = subtractMasked(await resolveWritableZones(agentDir, getSandboxWritablePathSpecs(config)), {
|
|
741
838
|
dirs,
|
|
742
839
|
files,
|
|
743
840
|
})
|
|
744
841
|
const writableRoot = canWriteAgentRootInSandbox(permissions, origin)
|
|
745
|
-
const
|
|
842
|
+
const baseProtectedZones =
|
|
746
843
|
writableRoot || writable.dirs.includes(join(agentDir, '.git'))
|
|
747
844
|
? subtractMasked(await resolveProtectedZones(agentDir), { dirs, files })
|
|
748
845
|
: { dirs: [], files: [] }
|
|
846
|
+
const protectedZones = {
|
|
847
|
+
dirs: baseProtectedZones.dirs,
|
|
848
|
+
files: [...new Set([...baseProtectedZones.files, ...dependencyBins.protectedFiles])],
|
|
849
|
+
}
|
|
749
850
|
const writableDirSet = new Set(writable.dirs)
|
|
750
851
|
const sandboxHome = DEFAULT_SANDBOX_ENV.HOME ?? '/tmp'
|
|
751
852
|
const symlinks = resolveSandboxSymlinks(agentDir, config.sandbox.symlinks, sandboxHome).filter((op) =>
|
|
@@ -768,6 +869,10 @@ async function applyBashSandbox(
|
|
|
768
869
|
mounts: [
|
|
769
870
|
{ type: 'ro-bind', source: agentDir, dest: agentDir },
|
|
770
871
|
{ type: 'bind', source: sessionTmp, dest: '/tmp' },
|
|
872
|
+
// `/tmp` is writable, but PATH entries must remain runtime-owned for
|
|
873
|
+
// the lifetime of this command. Last-op-wins makes this narrow re-bind
|
|
874
|
+
// read-only without adding any broader filesystem exposure.
|
|
875
|
+
{ type: 'ro-bind', source: dependencyBins.wrapperDir, dest: DEPENDENCY_BIN_SANDBOX_DIR },
|
|
771
876
|
...(privilegedRuntime?.mounts ?? []),
|
|
772
877
|
],
|
|
773
878
|
...(writableRoot
|
|
@@ -793,6 +898,7 @@ async function applyBashSandbox(
|
|
|
793
898
|
verify: async () => (boundary.verifyRuntime ?? verifyPrivilegedSandboxRuntime)(privilegedRuntime),
|
|
794
899
|
cleanup,
|
|
795
900
|
spawnEnv: mergedSpawnEnv,
|
|
901
|
+
dependencyBins,
|
|
796
902
|
}
|
|
797
903
|
} catch (error) {
|
|
798
904
|
await cleanup()
|
|
@@ -800,6 +906,17 @@ async function applyBashSandbox(
|
|
|
800
906
|
}
|
|
801
907
|
}
|
|
802
908
|
|
|
909
|
+
function bashResultIsCommandNotFound(result: ToolResult): boolean {
|
|
910
|
+
if (isRecord(result.details) && result.details.exitCode === 127) return true
|
|
911
|
+
return (result.content as ContentPart[]).some(
|
|
912
|
+
(part) => part.type === 'text' && /command not found(?:\s|$)/i.test(part.text),
|
|
913
|
+
)
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
function appendTextResult(result: ToolResult, text: string): ToolResult {
|
|
917
|
+
return { ...result, content: [...(result.content as ContentPart[]), { type: 'text', text }] }
|
|
918
|
+
}
|
|
919
|
+
|
|
803
920
|
export function buildSandboxEnvPolicy(
|
|
804
921
|
overlay: BashEnvOverlay | undefined,
|
|
805
922
|
runtimeEnv: Record<string, string> | undefined,
|