typeclaw 0.47.2 → 0.48.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/package.json +1 -1
  2. package/src/agent/index.ts +1 -2
  3. package/src/agent/loop-guard.ts +71 -41
  4. package/src/agent/plugin-tools.ts +234 -58
  5. package/src/agent/system-prompt.ts +1 -1
  6. package/src/agent/turn-runner.ts +12 -2
  7. package/src/agent-messenger/config-dir.ts +131 -0
  8. package/src/agent-messenger/host-config-dir.ts +121 -0
  9. package/src/bundled-plugins/agent-browser/index.ts +0 -38
  10. package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +1 -1
  11. package/src/bundled-plugins/guard/policies/non-workspace-write.ts +16 -1
  12. package/src/bundled-plugins/memory/append-tool.ts +75 -2
  13. package/src/bundled-plugins/memory/frontmatter.ts +13 -2
  14. package/src/bundled-plugins/memory/load-memory.ts +1 -1
  15. package/src/bundled-plugins/memory/memory-logger.ts +5 -1
  16. package/src/bundled-plugins/memory/secret-detector.ts +7 -0
  17. package/src/bundled-plugins/memory/vector/hybrid.ts +3 -1
  18. package/src/bundled-plugins/memory/vector/passages.ts +5 -1
  19. package/src/bundled-plugins/security/index.ts +148 -98
  20. package/src/bundled-plugins/security/policies/private-surface-read.ts +43 -28
  21. package/src/channels/adapters/discord-bot-edit.ts +3 -5
  22. package/src/channels/adapters/discord-bot-reactions.ts +4 -6
  23. package/src/channels/adapters/discord-bot-slash-commands.ts +3 -1
  24. package/src/channels/adapters/discord-bot.ts +20 -23
  25. package/src/channels/adapters/discord-edit.ts +3 -5
  26. package/src/channels/adapters/discord-reactions.ts +4 -6
  27. package/src/channels/adapters/discord.ts +1 -1
  28. package/src/channels/adapters/github/decoy-reviewer.ts +2 -1
  29. package/src/channels/adapters/github/history.ts +2 -1
  30. package/src/channels/adapters/github/inbound.ts +4 -11
  31. package/src/channels/adapters/github/index.ts +6 -9
  32. package/src/channels/adapters/github/outbound.ts +3 -6
  33. package/src/channels/adapters/github/reactions.ts +3 -2
  34. package/src/channels/adapters/github/reconcile-cooldown-store.ts +4 -6
  35. package/src/channels/adapters/github/reconcile-open-prs.ts +5 -4
  36. package/src/channels/adapters/github/recover-failed-deliveries.ts +2 -5
  37. package/src/channels/adapters/github/review-state.ts +3 -2
  38. package/src/channels/adapters/github/review-thread-resolver.ts +3 -2
  39. package/src/channels/adapters/github/webhook-register.ts +5 -8
  40. package/src/channels/adapters/instagram-channel-resolver.ts +3 -5
  41. package/src/channels/adapters/instagram.ts +1 -1
  42. package/src/channels/adapters/kakaotalk-author-resolver.ts +2 -5
  43. package/src/channels/adapters/kakaotalk-channel-resolver.ts +3 -5
  44. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +2 -1
  45. package/src/channels/adapters/kakaotalk-membership.ts +2 -5
  46. package/src/channels/adapters/kakaotalk-typing.ts +1 -1
  47. package/src/channels/adapters/kakaotalk.ts +1 -1
  48. package/src/channels/adapters/line-channel-resolver.ts +3 -5
  49. package/src/channels/adapters/line.ts +1 -1
  50. package/src/channels/adapters/slack-bot-edit.ts +1 -1
  51. package/src/channels/adapters/slack-bot-reactions.ts +4 -6
  52. package/src/channels/adapters/slack-bot.ts +8 -8
  53. package/src/channels/adapters/slack-edit.ts +3 -5
  54. package/src/channels/adapters/slack-reactions.ts +4 -6
  55. package/src/channels/adapters/slack.ts +1 -1
  56. package/src/channels/adapters/teams-edit.ts +2 -5
  57. package/src/channels/adapters/teams.ts +1 -1
  58. package/src/channels/adapters/telegram-bot-edit.ts +4 -7
  59. package/src/channels/adapters/telegram-bot.ts +1 -1
  60. package/src/channels/adapters/webex-bot.ts +1 -1
  61. package/src/channels/adapters/webex-edit.ts +3 -5
  62. package/src/channels/adapters/webex.ts +1 -1
  63. package/src/channels/github-review-claim.ts +89 -4
  64. package/src/channels/github-token-bridge.ts +2 -1
  65. package/src/channels/manager.ts +478 -64
  66. package/src/channels/membership-cache.ts +2 -5
  67. package/src/channels/persistence.ts +3 -6
  68. package/src/channels/reloadable.ts +23 -6
  69. package/src/channels/router.ts +134 -56
  70. package/src/channels/tunnel-bridge.ts +2 -1
  71. package/src/channels/types.ts +6 -3
  72. package/src/cli/channel.ts +15 -16
  73. package/src/cli/hostd.ts +61 -38
  74. package/src/cli/init.ts +21 -7
  75. package/src/cli/model.ts +6 -3
  76. package/src/cli/restart.ts +13 -15
  77. package/src/compose/restart.ts +14 -6
  78. package/src/config/config.ts +10 -0
  79. package/src/config/providers.ts +68 -0
  80. package/src/container/agent-operation-lock.ts +85 -0
  81. package/src/container/controller.ts +6 -0
  82. package/src/container/index.ts +8 -0
  83. package/src/container/restart.ts +55 -0
  84. package/src/container/shared.ts +5 -0
  85. package/src/container/start.ts +70 -4
  86. package/src/container/stop.ts +17 -1
  87. package/src/dependencies/bin-resolver.ts +88 -0
  88. package/src/dependencies/bins.ts +227 -0
  89. package/src/dependencies/index.ts +17 -0
  90. package/src/doctor/checks.ts +2 -0
  91. package/src/doctor/operational-incidents.ts +32 -0
  92. package/src/hostd/credential-rotation-apply.ts +94 -0
  93. package/src/hostd/daemon.ts +1 -1
  94. package/src/hostd/paths.ts +17 -0
  95. package/src/hostd/supervisor.ts +27 -10
  96. package/src/init/dockerfile.ts +6 -5
  97. package/src/init/env-file.ts +42 -18
  98. package/src/init/instagram-auth.ts +55 -31
  99. package/src/init/kakaotalk-auth.ts +1 -5
  100. package/src/init/line-auth.ts +45 -29
  101. package/src/init/models-dev.ts +131 -10
  102. package/src/init/opengateway-catalog.ts +120 -0
  103. package/src/init/validate-api-key.ts +26 -4
  104. package/src/operations/classify-tool-outcome.ts +151 -0
  105. package/src/operations/incidents.ts +274 -0
  106. package/src/operations/index.ts +3 -0
  107. package/src/operations/remediations.ts +41 -0
  108. package/src/reload/client.ts +8 -2
  109. package/src/reload/docker-exec-client.ts +10 -2
  110. package/src/reload/index.ts +1 -1
  111. package/src/reload/recover.ts +5 -3
  112. package/src/reload/registry.ts +5 -5
  113. package/src/reload/types.ts +9 -1
  114. package/src/run/index.ts +5 -0
  115. package/src/sandbox/canonical-secrets.ts +10 -1
  116. package/src/sandbox/dependency-bins.ts +125 -0
  117. package/src/sandbox/hidden-paths.ts +4 -1
  118. package/src/sandbox/index.ts +8 -0
  119. package/src/sandbox/policy.ts +1 -1
  120. package/src/sandbox/privileged-runtime.ts +7 -12
  121. package/src/sandbox/runtime-private.ts +4 -0
  122. package/src/sandbox/writable-zones.ts +4 -4
  123. package/src/server/index.ts +7 -5
  124. package/src/shared/protocol.ts +6 -1
  125. package/src/test-helpers/fake-agent-operation-lock.ts +66 -0
  126. package/typeclaw.schema.json +10 -5
  127. package/src/bundled-plugins/agent-browser/shim-install.ts +0 -179
  128. package/src/bundled-plugins/agent-browser/shim.ts +0 -108
  129. /package/src/channels/{adapters/describe-error.ts → describe-error.ts} +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typeclaw",
3
- "version": "0.47.2",
3
+ "version": "0.48.1",
4
4
  "homepage": "https://github.com/typeclaw/typeclaw#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/typeclaw/typeclaw/issues"
@@ -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
@@ -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-bearing tools coarsen
15
- // their signature to the path alone. Read calls additionally recognize one
16
- // assistant tool batch and successfully-observed forward pagination so
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
- // Tools whose first path-like argument identifies the target. Their windowed
37
- // signature keys on that path alone so paging one file with drifting
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 (grep/find/ls): path is OPTIONAL and defaults to the
45
- // cwd ("."). Omitting the path and varying only non-target args (pattern,
46
- // limit) still hits the same directory, so an omitted/empty path coarsens
47
- // to `${tool}#path:.` — otherwise those calls would evade the detector.
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(['grep', 'find', 'ls'])
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 read receipts are explicit no-ops so
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
- // A model turn may emit several tool calls in one assistant message. Those
151
- // calls cannot react to one another's results, so same-path reads in that
152
- // batch count as one loop observation rather than a reactive cycle.
153
- readTurnId: number | undefined
154
- readPathsThisTurn: Set<string>
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
- readTurnId: undefined,
267
- readPathsThisTurn: new Set(),
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
- if (readTarget !== undefined && context?.turnId !== undefined) {
274
- if (readPathSeenThisTurn(state, readTarget.path, context.turnId, windowSize)) {
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: readPathSignature(readTarget.path),
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
- if (tool === 'read') {
352
- state.readTurnId = undefined
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-bearing tools key on their
453
- // target path alone so re-reading one target with drifting non-path args
454
- // collapses to a single signature. All other tools fall back to the exact
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 readPathSeenThisTurn(state: SessionState, path: string, turnId: number, maxReadPaths: number): boolean {
516
- if (state.readTurnId !== turnId) {
517
- state.readTurnId = turnId
518
- state.readPathsThisTurn.clear()
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.readPathsThisTurn.has(path)
521
- if (seen) state.readPathsThisTurn.delete(path)
522
- state.readPathsThisTurn.add(path)
523
- while (state.readPathsThisTurn.size > maxReadPaths) {
524
- const oldest = state.readPathsThisTurn.values().next().value
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.readPathsThisTurn.delete(oldest)
556
+ state.targetsThisTurn.delete(oldest)
527
557
  }
528
558
  return seen
529
559
  }
@@ -1,6 +1,6 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks'
2
2
  import { mkdir } from 'node:fs/promises'
3
- import { join } from 'node:path'
3
+ import { join, relative, sep } from 'node:path'
4
4
 
5
5
  import {
6
6
  createBashToolDefinition as piCreateBashToolDefinition,
@@ -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,85 @@ 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
- try {
579
- if (tool.name === 'bash') {
580
- if (opts.permissions === undefined) {
581
- throw new SandboxPolicyError('model-driven bash has no permission service; refusing unsandboxed execution')
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
- preparedSandboxRuntime = await applyBashSandbox(
584
- mutableArgs,
585
- opts.permissions,
586
- liveOrigin,
587
- opts.agentDir,
588
- opts.sessionId,
589
- bashEnvOverlay,
590
- sandboxBoundary,
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
+ ? {
637
+ hidden:
638
+ preparedSandboxRuntime?.withheld.paths ??
639
+ resolveHiddenPaths(opts.permissions, liveOrigin, opts.agentDir),
640
+ }
641
+ : {}),
642
+ signal,
643
+ })
644
+ await preparedSandboxRuntime?.verify()
645
+ const spawnEnvContext: BashSpawnEnvContext | undefined =
646
+ bashEnvOverlay !== undefined || preparedSandboxRuntime?.spawnEnv !== undefined
647
+ ? {
648
+ ...(bashEnvOverlay !== undefined ? { overlay: bashEnvOverlay } : {}),
649
+ ...(preparedSandboxRuntime?.spawnEnv !== undefined
650
+ ? { sandboxSpawnEnv: preparedSandboxRuntime.spawnEnv }
651
+ : {}),
652
+ }
653
+ : undefined
654
+ rawResult = await bashEnvStore.run(spawnEnvContext, () =>
655
+ tool.execute(toolCallId, attemptArgs as Static<TParams>, signal, onUpdate, ctx),
656
+ )
657
+ const originalCommand = originalArgs.command
658
+ sandboxedRealProcSucceeded =
659
+ preparedSandboxRuntime !== undefined &&
660
+ typeof originalCommand === 'string' &&
661
+ (opts.realProcDependencyCheck ?? commandNeedsRealProc)(originalCommand)
662
+ } catch (error) {
663
+ executionError = error
664
+ } finally {
665
+ const cleanup = [pinnedFiles?.cleanup(), preparedSandboxRuntime?.cleanup()].filter(
666
+ (task): task is Promise<void> => task !== undefined,
591
667
  )
668
+ const outcomes = await Promise.allSettled(cleanup)
669
+ const failed = outcomes.find((outcome) => outcome.status === 'rejected')
670
+ if (failed?.status === 'rejected') cleanupError = failed.reason
592
671
  }
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
672
  }
673
+
674
+ await executeAttempt()
630
675
  // Decorate genuine, user-correctable builtin file-tool failures with a
631
676
  // recovery hint so weaker models retry correctly. Only executionError (not
632
677
  // cleanupError) and only non-aborted Error instances; remediation is a
@@ -635,16 +680,77 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
635
680
  // preserves the error's subclass and stack for the rethrow.
636
681
  if (executionError instanceof Error && signal?.aborted !== true) {
637
682
  executionError.message = remediateToolErrorMessage(tool.name, executionError.message)
683
+ const incidentFact = classifyToolOutcome({ tool: tool.name, error: executionError })
684
+ if (incidentFact !== null) {
685
+ const initialError = executionError
686
+ let recordedFingerprint: string | undefined
687
+ let incidentHint = renderUntrackedIncidentHint(incidentFact)
688
+ try {
689
+ const incident = await incidentLedger.record(incidentFact, opts.sessionId)
690
+ recordedFingerprint = incident.fingerprint
691
+ incidentHint = renderIncidentHint(incident)
692
+ } catch {
693
+ // Incident persistence must never hide the originating tool failure.
694
+ }
695
+ const remediation = await repairAndRetryOnce(
696
+ opts.remediations ?? operationalRemediations,
697
+ incidentFact,
698
+ initialError,
699
+ async () => {
700
+ await executeAttempt()
701
+ const retryError = executionError ?? cleanupError
702
+ if (retryError !== undefined) throw retryError
703
+ },
704
+ )
705
+ if (remediation.outcome === 'retried') {
706
+ const retrySuccessFingerprints = deriveMechanicallyVerifiedIncidentFingerprints({
707
+ tool: tool.name,
708
+ args: originalArgs,
709
+ sandboxedRealProcSucceeded,
710
+ })
711
+ if (recordedFingerprint !== undefined && retrySuccessFingerprints.has(recordedFingerprint)) {
712
+ await incidentLedger.resolve(recordedFingerprint).catch(() => false)
713
+ }
714
+ } else {
715
+ const failedError = remediation.outcome === 'retry-failed' ? remediation.error : initialError
716
+ const finalIncidentError = failedError instanceof Error ? failedError : new Error(String(failedError))
717
+ finalIncidentError.message = remediateToolErrorMessage(tool.name, finalIncidentError.message)
718
+ finalIncidentError.message = `${finalIncidentError.message}\n\n${incidentHint}`
719
+ executionError = finalIncidentError
720
+ cleanupError = undefined
721
+ }
722
+ }
638
723
  }
639
- const finalError = executionError ?? cleanupError
724
+ let finalError = executionError ?? cleanupError
640
725
  if (finalError !== undefined) {
726
+ // The builtin reports command failures as execution errors rather than
727
+ // result details. Once the sandbox was prepared, annotate every such
728
+ // error without parsing its arbitrary or localized text. Cleanup-only
729
+ // failures are not command failures and remain unchanged.
730
+ if (executionError !== undefined && preparedSandboxRuntime !== undefined) {
731
+ finalError = appendErrorText(
732
+ finalError,
733
+ renderSandboxPolicyNote(preparedSandboxRuntime.withheld, opts.agentDir),
734
+ )
735
+ }
641
736
  await runToolAfterSafely(opts, tool.name, toolCallId, toErrorResult(finalError))
642
737
  throw finalError
643
738
  }
644
739
  if (pinnedFiles === undefined) throw new Error('tool file boundary was not initialized')
645
740
  if (rawResult === undefined) throw new Error('tool execution returned no result')
646
741
  const pinnedResult = pinnedFiles.restoreResult(rawResult)
647
- const result = tmpRedirect !== undefined ? restoreTmpPathInResult(pinnedResult, tmpRedirect) : pinnedResult
742
+ let result = tmpRedirect !== undefined ? restoreTmpPathInResult(pinnedResult, tmpRedirect) : pinnedResult
743
+ if (
744
+ originalBashCommand !== undefined &&
745
+ preparedSandboxRuntime?.dependencyBins !== undefined &&
746
+ bashResultIsCommandNotFound(result)
747
+ ) {
748
+ const hint = dependencyBinUnavailableHint(originalBashCommand, preparedSandboxRuntime.dependencyBins)
749
+ if (hint !== undefined) result = appendTextResult(result, hint)
750
+ }
751
+ if (preparedSandboxRuntime !== undefined && bashResultHasNonzeroExit(result)) {
752
+ result = appendTextResult(result, renderSandboxPolicyNote(preparedSandboxRuntime.withheld, opts.agentDir))
753
+ }
648
754
  const resolved = loopGate.resolve({ content: result.content as ContentPart[], details: result.details })
649
755
  if ('deferredBlock' in resolved) {
650
756
  fireLoopAbort(opts.getAbort, 'loop_guard:deferred_block')
@@ -657,6 +763,12 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
657
763
  callId: toolCallId,
658
764
  result: hookResult,
659
765
  })
766
+ const successFingerprints = deriveMechanicallyVerifiedIncidentFingerprints({
767
+ tool: tool.name,
768
+ args: originalArgs,
769
+ sandboxedRealProcSucceeded,
770
+ })
771
+ await incidentLedger.resolveObservedSuccess(successFingerprints).catch(() => 0)
660
772
  return {
661
773
  content: hookResult.content as ContentPart[],
662
774
  details: hookResult.details as TDetails,
@@ -705,6 +817,11 @@ type PreparedBashSandbox = {
705
817
  verify: () => Promise<void>
706
818
  cleanup: () => Promise<void>
707
819
  spawnEnv?: Record<string, string>
820
+ dependencyBins?: DependencyBinReconciliation
821
+ withheld: {
822
+ paths: { dirs: string[]; files: string[] }
823
+ envNames: string[]
824
+ }
708
825
  }
709
826
 
710
827
  export function buildBashFilesystemPolicy(options: BashFilesystemPolicyOptions) {
@@ -730,22 +847,34 @@ async function applyBashSandbox(
730
847
  boundary: BashSandboxBoundary,
731
848
  ): Promise<PreparedBashSandbox> {
732
849
  const command = mutableArgs.command
733
- if (typeof command !== 'string') return { verify: async () => {}, cleanup: async () => {} }
850
+ if (typeof command !== 'string') {
851
+ return {
852
+ verify: async () => {},
853
+ cleanup: async () => {},
854
+ withheld: { paths: { dirs: [], files: [] }, envNames: [] },
855
+ }
856
+ }
734
857
 
735
858
  const { dirs, files } = resolveHiddenPaths(permissions, origin, agentDir)
859
+ const envNames = resolveExposableBashEnvNames(agentDir)
736
860
  const sandboxEnvOverlay = buildRoleScopedConfigEnv(agentDir, dirs, envOverlay)
737
861
  const maskTargets = await ensureHiddenMaskTargets({ dirs, files })
738
862
  await boundary.ensureAvailable()
739
863
  const sessionTmp = await ensureSessionTmpDir(sessionId)
864
+ const dependencyBins = await reconcileDependencyBinWrappers({ agentDir, sessionTmp })
740
865
  const writable = subtractMasked(await resolveWritableZones(agentDir, getSandboxWritablePathSpecs(config)), {
741
866
  dirs,
742
867
  files,
743
868
  })
744
869
  const writableRoot = canWriteAgentRootInSandbox(permissions, origin)
745
- const protectedZones =
870
+ const baseProtectedZones =
746
871
  writableRoot || writable.dirs.includes(join(agentDir, '.git'))
747
872
  ? subtractMasked(await resolveProtectedZones(agentDir), { dirs, files })
748
873
  : { dirs: [], files: [] }
874
+ const protectedZones = {
875
+ dirs: baseProtectedZones.dirs,
876
+ files: [...new Set([...baseProtectedZones.files, ...dependencyBins.protectedFiles])],
877
+ }
749
878
  const writableDirSet = new Set(writable.dirs)
750
879
  const sandboxHome = DEFAULT_SANDBOX_ENV.HOME ?? '/tmp'
751
880
  const symlinks = resolveSandboxSymlinks(agentDir, config.sandbox.symlinks, sandboxHome).filter((op) =>
@@ -768,6 +897,10 @@ async function applyBashSandbox(
768
897
  mounts: [
769
898
  { type: 'ro-bind', source: agentDir, dest: agentDir },
770
899
  { type: 'bind', source: sessionTmp, dest: '/tmp' },
900
+ // `/tmp` is writable, but PATH entries must remain runtime-owned for
901
+ // the lifetime of this command. Last-op-wins makes this narrow re-bind
902
+ // read-only without adding any broader filesystem exposure.
903
+ { type: 'ro-bind', source: dependencyBins.wrapperDir, dest: DEPENDENCY_BIN_SANDBOX_DIR },
771
904
  ...(privilegedRuntime?.mounts ?? []),
772
905
  ],
773
906
  ...(writableRoot
@@ -778,9 +911,7 @@ async function applyBashSandbox(
778
911
  cwd: agentDir,
779
912
  proc,
780
913
  procSelfExe: resolveProcSelfExe(),
781
- ...spreadSandboxEnv(
782
- buildSandboxEnvPolicy(sandboxEnvOverlay, privilegedRuntime?.env, resolveExposableBashEnvNames(agentDir)),
783
- ),
914
+ ...spreadSandboxEnv(buildSandboxEnvPolicy(sandboxEnvOverlay, privilegedRuntime?.env, envNames.exposable)),
784
915
  })
785
916
  mutableArgs.command = commandString
786
917
  // The overlay carries command-scoped secret VALUES (e.g. a per-repo GH_TOKEN)
@@ -793,6 +924,8 @@ async function applyBashSandbox(
793
924
  verify: async () => (boundary.verifyRuntime ?? verifyPrivilegedSandboxRuntime)(privilegedRuntime),
794
925
  cleanup,
795
926
  spawnEnv: mergedSpawnEnv,
927
+ dependencyBins,
928
+ withheld: { paths: maskTargets, envNames: envNames.withheld },
796
929
  }
797
930
  } catch (error) {
798
931
  await cleanup()
@@ -800,6 +933,43 @@ async function applyBashSandbox(
800
933
  }
801
934
  }
802
935
 
936
+ function bashResultIsCommandNotFound(result: ToolResult): boolean {
937
+ if (isRecord(result.details) && result.details.exitCode === 127) return true
938
+ return (result.content as ContentPart[]).some(
939
+ (part) => part.type === 'text' && /command not found(?:\s|$)/i.test(part.text),
940
+ )
941
+ }
942
+
943
+ function bashResultHasNonzeroExit(result: ToolResult): boolean {
944
+ // A numeric nonzero exit is the command's tool-agnostic failure signal. Do
945
+ // not infer failure from arbitrary or localized output text.
946
+ return isRecord(result.details) && typeof result.details.exitCode === 'number' && result.details.exitCode !== 0
947
+ }
948
+
949
+ function renderSandboxPolicyNote(withheld: PreparedBashSandbox['withheld'], agentDir: string): string {
950
+ const maskedPaths = [...withheld.paths.dirs, ...withheld.paths.files].map(
951
+ (target) => `agent/${relative(agentDir, target).split(sep).join('/')}`,
952
+ )
953
+ return (
954
+ `[TypeClaw sandbox policy (LOCAL): masked credential/private paths: ${maskedPaths.join(', ') || 'none'}; ` +
955
+ `withheld env names: ${withheld.envNames.join(', ') || 'none'}. This may be unrelated to this failure; ` +
956
+ 'it is NOT evidence about authentication of any account, workspace, or upstream service and must not be ' +
957
+ 'reported as such.]'
958
+ )
959
+ }
960
+
961
+ function appendErrorText(error: unknown, text: string): Error {
962
+ if (error instanceof Error) {
963
+ error.message = `${error.message}\n\n${text}`
964
+ return error
965
+ }
966
+ return new Error(`${String(error)}\n\n${text}`)
967
+ }
968
+
969
+ function appendTextResult(result: ToolResult, text: string): ToolResult {
970
+ return { ...result, content: [...(result.content as ContentPart[]), { type: 'text', text }] }
971
+ }
972
+
803
973
  export function buildSandboxEnvPolicy(
804
974
  overlay: BashEnvOverlay | undefined,
805
975
  runtimeEnv: Record<string, string> | undefined,
@@ -845,8 +1015,14 @@ function spreadSandboxEnv(policy: ReturnType<typeof buildSandboxEnvPolicy>): {
845
1015
  return Object.keys(policy).length > 0 ? { env: policy } : {}
846
1016
  }
847
1017
 
848
- function resolveExposableBashEnvNames(agentDir: string): string[] {
849
- return resolveExposableEnvNames(readEnvFile(agentDir))
1018
+ function resolveExposableBashEnvNames(agentDir: string): { exposable: string[]; withheld: string[] } {
1019
+ const declaredEnv = readEnvFile(agentDir)
1020
+ const exposable = resolveExposableEnvNames(declaredEnv)
1021
+ const exposableSet = new Set(exposable)
1022
+ const withheld = [...declaredEnv]
1023
+ .filter(([name, value]) => value.length > 0 && !exposableSet.has(name))
1024
+ .map(([name]) => name)
1025
+ return { exposable, withheld }
850
1026
  }
851
1027
 
852
1028
  function buildRoleScopedConfigEnv(
@@ -1,7 +1,7 @@
1
1
  import { formatLocalDateTime, formatLocalWeekday, resolveLocalTimezoneName } from '@/shared'
2
2
 
3
3
  const PACKAGE_JSON_INSTALL_RULE =
4
- "After editing `package.json` (adding, removing, or bumping dependencies/plugins), run the project's package manager to update the lockfile and installed dependency state — e.g. `bun install`, `npm install`, `pnpm install`, or `yarn install`, matching the existing lockfile. Commit the lockfile change alongside the `package.json` edit."
4
+ '`package.json` is operator-owned because direct dependencies define sandbox-visible commands. Do not edit it or install dependencies; tell the operator which package and command are needed.'
5
5
 
6
6
  // The orchestration roster (the `Briefly: ...` enumeration of public subagents)
7
7
  // is GENERATED from the registry by `renderPublicSubagentRoster` and threaded in