typeclaw 0.48.6 → 0.48.8

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 (105) hide show
  1. package/auth.schema.json +15 -1
  2. package/package.json +1 -1
  3. package/secrets.schema.json +15 -1
  4. package/src/agent/guard-types.ts +25 -0
  5. package/src/agent/guards.ts +102 -0
  6. package/src/agent/index.ts +33 -3
  7. package/src/agent/live-subagents.ts +14 -0
  8. package/src/agent/multimodal/read-redirect.ts +8 -9
  9. package/src/agent/plugin-tools.ts +283 -148
  10. package/src/agent/provider-error.ts +6 -1
  11. package/src/agent/reload-tool.ts +12 -5
  12. package/src/agent/retry-same-ref.ts +95 -36
  13. package/src/agent/session-origin.ts +13 -1
  14. package/src/agent/system-prompt.ts +14 -3
  15. package/src/agent/todo/continuation-policy.ts +3 -4
  16. package/src/agent/tool-file-safety.ts +36 -13
  17. package/src/agent/tools/channel-reply.ts +39 -2
  18. package/src/agent/tools/channel-send.ts +45 -2
  19. package/src/agent/tools/post-github-review.ts +31 -13
  20. package/src/agent/tools/spawn-subagent.ts +15 -0
  21. package/src/agent/tools/webfetch/inline-style-visibility.ts +2 -2
  22. package/src/agent/tools/webfetch/strategies/readability.ts +109 -10
  23. package/src/agent/turn-runner.ts +23 -19
  24. package/src/bundled-plugins/backup/git-auth.ts +7 -4
  25. package/src/bundled-plugins/backup/subagents.ts +1 -1
  26. package/src/bundled-plugins/bun-hygiene/README.md +23 -20
  27. package/src/bundled-plugins/bun-hygiene/index.ts +1 -7
  28. package/src/bundled-plugins/bun-hygiene/policy.ts +111 -35
  29. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +44 -2
  30. package/src/bundled-plugins/github-cli-auth/gh-store.ts +733 -0
  31. package/src/bundled-plugins/github-cli-auth/git-askpass.ts +25 -0
  32. package/src/bundled-plugins/github-cli-auth/git-command.ts +231 -30
  33. package/src/bundled-plugins/github-cli-auth/git-credential-env.ts +151 -0
  34. package/src/bundled-plugins/github-cli-auth/index.ts +249 -42
  35. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +5 -0
  36. package/src/bundled-plugins/guard/index.ts +2 -25
  37. package/src/bundled-plugins/guard/keys.ts +8 -0
  38. package/src/bundled-plugins/guard/policies/non-workspace-write.ts +7 -8
  39. package/src/bundled-plugins/guard/policy.ts +1 -7
  40. package/src/bundled-plugins/security/policies/git-exfil.ts +22 -30
  41. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +2 -4
  42. package/src/bundled-plugins/security/policies/private-surface-read.ts +8 -6
  43. package/src/bundled-plugins/security/policies/secret-exfil-bash.ts +2 -5
  44. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +2 -4
  45. package/src/bundled-plugins/security/policies/session-search-secrets.ts +2 -4
  46. package/src/bundled-plugins/security/policies/system-prompt-leak.ts +2 -4
  47. package/src/bundled-plugins/security/policy.ts +0 -8
  48. package/src/channels/adapters/discord-bot-slash-commands.ts +22 -0
  49. package/src/channels/adapters/discord-bot.ts +2 -1
  50. package/src/channels/adapters/discord-classify.ts +16 -4
  51. package/src/channels/adapters/discord.ts +20 -8
  52. package/src/channels/adapters/github/dedup.ts +37 -8
  53. package/src/channels/adapters/github/inbound.ts +241 -46
  54. package/src/channels/adapters/github/review-state.ts +13 -9
  55. package/src/channels/adapters/github/review-thread-resolver.ts +52 -20
  56. package/src/channels/adapters/slack-classify.ts +40 -5
  57. package/src/channels/adapters/slack.ts +3 -9
  58. package/src/channels/adapters/webex-bot-classify.ts +4 -33
  59. package/src/channels/adapters/webex-bot.ts +2 -4
  60. package/src/channels/adapters/webex-classify.ts +4 -33
  61. package/src/channels/adapters/webex-format.ts +36 -0
  62. package/src/channels/adapters/webex.ts +2 -4
  63. package/src/channels/continuation-willingness.ts +64 -39
  64. package/src/channels/github-rereview-guard.ts +20 -0
  65. package/src/channels/github-review-turn-ledger.ts +11 -1
  66. package/src/channels/github-review-verdict-coordinator.ts +475 -41
  67. package/src/channels/github-verdict-activity.ts +14 -5
  68. package/src/channels/persistence.ts +89 -5
  69. package/src/channels/router.ts +1223 -225
  70. package/src/channels/types.ts +21 -5
  71. package/src/cli/compose-stats.ts +6 -7
  72. package/src/cli/compose-status.ts +6 -7
  73. package/src/cli/compose-usage.ts +6 -7
  74. package/src/cli/stats.ts +6 -7
  75. package/src/cli/status.ts +7 -8
  76. package/src/cli/ui.ts +4 -4
  77. package/src/container/start.ts +41 -1
  78. package/src/cron/consumer.ts +30 -9
  79. package/src/cron/scheduler.ts +24 -9
  80. package/src/doctor/channel-checks.ts +64 -0
  81. package/src/doctor/report.ts +8 -8
  82. package/src/dreams/render.ts +2 -2
  83. package/src/init/dockerfile.ts +8 -1
  84. package/src/inspect/render.ts +2 -2
  85. package/src/path-safety/real-intended-path.ts +14 -1
  86. package/src/permissions/permissions.ts +10 -2
  87. package/src/permissions/resolve.ts +8 -2
  88. package/src/plugin/core-tool-names.ts +15 -0
  89. package/src/plugin/hooks.ts +37 -3
  90. package/src/plugin/registry.ts +7 -3
  91. package/src/run/index.ts +35 -15
  92. package/src/sandbox/build.ts +19 -3
  93. package/src/sandbox/policy.ts +1 -0
  94. package/src/secrets/export-github-cli-store.ts +158 -0
  95. package/src/secrets/index.ts +19 -1
  96. package/src/secrets/provision-github-cli-store.ts +322 -0
  97. package/src/secrets/schema.ts +13 -7
  98. package/src/secrets/storage.ts +30 -0
  99. package/src/shared/index.ts +2 -0
  100. package/src/shared/style-text.ts +13 -0
  101. package/src/skills/typeclaw-channel-github/SKILL.md +24 -12
  102. package/src/skills/typeclaw-config/SKILL.md +3 -1
  103. package/src/skills/typeclaw-github-contributing/SKILL.md +6 -2
  104. package/src/skills/typeclaw-permissions/SKILL.md +11 -22
  105. package/src/usage/report.ts +3 -3
@@ -17,12 +17,7 @@ import type { Static, TSchema } from 'typebox'
17
17
  import { Type } from 'typebox'
18
18
  import { z } from 'zod'
19
19
 
20
- import {
21
- ACKNOWLEDGE_GUARDS,
22
- checkManagedConfigGuard,
23
- checkNonWorkspaceWriteGuard,
24
- checkSkillAuthoringGuard,
25
- } from '@/bundled-plugins/guard/policy'
20
+ import { ACKNOWLEDGE_GUARDS } from '@/bundled-plugins/guard/keys'
26
21
  import { config, getSandboxWritablePathSpecs } from '@/config/config'
27
22
  import { readEnvFile } from '@/init/env-file'
28
23
  import {
@@ -47,6 +42,7 @@ import type {
47
42
  ToolFileOperands,
48
43
  ToolResult,
49
44
  } from '@/plugin'
45
+ import { PI_BUILTIN_TOOL_NAMES, type PiBuiltinToolName } from '@/plugin/core-tool-names'
50
46
  import {
51
47
  buildSandboxedCommand,
52
48
  canWriteAgentRootInSandbox,
@@ -73,6 +69,7 @@ import {
73
69
  SandboxPolicyError,
74
70
  SandboxDegradedProcError,
75
71
  SandboxProcProbeUnverifiedError,
72
+ type SandboxMount,
76
73
  type DependencyBinReconciliation,
77
74
  subtractMasked,
78
75
  verifyHiddenMaskTargets,
@@ -80,8 +77,8 @@ import {
80
77
  } from '@/sandbox'
81
78
  import { resolveExposableEnvNames } from '@/sandbox/env-exposure'
82
79
 
80
+ import type { InternalGuard } from './guard-types'
83
81
  import { createLoopGuard, type LoopGuard, type LoopGuardDecision } from './loop-guard'
84
- import { checkImageReadRedirect } from './multimodal/read-redirect'
85
82
  import { enforceSubagentBashPolicy, type SubagentBashPolicy } from './reviewer-bash-policy'
86
83
  import type { SessionOrigin } from './session-origin'
87
84
  import { remediateToolErrorMessage } from './tool-error-remediation'
@@ -107,8 +104,18 @@ let sharedLoopGuard: LoopGuard = createLoopGuard()
107
104
  // is stripped from client-supplied args before tool.before so only trusted
108
105
  // hooks can set it.
109
106
  export const TYPECLAW_INTERNAL_BASH_ENV = '__typeclawBashEnv'
107
+ export const TYPECLAW_INTERNAL_BASH_WITHHOLD_ENV = '__typeclawBashWithholdEnv'
108
+ export const TYPECLAW_INTERNAL_BASH_PREPARE = '__typeclawBashPrepare'
110
109
 
111
110
  type BashEnvOverlay = Record<string, string>
111
+ type BashEnvWithhold = string[]
112
+ export type DeferredBashPreparationResult = {
113
+ command: string
114
+ env?: Record<string, string>
115
+ mount: Extract<SandboxMount, { type: 'ro-bind' }>
116
+ cleanup: () => Promise<void>
117
+ }
118
+ export type DeferredBashPreparation = () => Promise<DeferredBashPreparationResult>
112
119
  const SECRET_BASH_ENV_NAMES = new Set(['GH_TOKEN', 'GITHUB_TOKEN'])
113
120
 
114
121
  // Transport classifier for the TRUSTED hook-injected overlay only (e.g.
@@ -123,6 +130,7 @@ function isOverlaySecretName(name: string): boolean {
123
130
 
124
131
  type BashSpawnEnvContext = {
125
132
  overlay?: BashEnvOverlay
133
+ withhold?: BashEnvWithhold
126
134
  // Exact env for the outer bwrap process on a sandboxed call. When present, the
127
135
  // spawn hook uses it verbatim rather than the live inherited env, so a secret
128
136
  // that appears in process.env between policy build and spawn stays out of the
@@ -142,33 +150,38 @@ function readBashEnvOverlay(args: Record<string, unknown>): BashEnvOverlay | und
142
150
  return Object.keys(overlay).length > 0 ? overlay : undefined
143
151
  }
144
152
 
153
+ function readBashEnvWithhold(args: Record<string, unknown>): BashEnvWithhold | undefined {
154
+ const raw = args[TYPECLAW_INTERNAL_BASH_WITHHOLD_ENV]
155
+ if (!Array.isArray(raw) || !raw.every((name) => typeof name === 'string')) return undefined
156
+ const names = [...new Set(raw)]
157
+ return names.length > 0 ? names : undefined
158
+ }
159
+
160
+ function readBashPreparation(args: Record<string, unknown>): DeferredBashPreparation | undefined {
161
+ const raw = args[TYPECLAW_INTERNAL_BASH_PREPARE]
162
+ return typeof raw === 'function' ? (raw as DeferredBashPreparation) : undefined
163
+ }
164
+
145
165
  function bashSpawnHookWithOverlay(context: BashSpawnContext): BashSpawnContext {
146
166
  const store = bashEnvStore.getStore()
147
167
  if (store?.sandboxSpawnEnv !== undefined) return { ...context, env: { ...store.sandboxSpawnEnv } }
148
- return { ...context, env: sanitizeBashSpawnEnvironment(context.env, store?.overlay) }
168
+ return { ...context, env: sanitizeBashSpawnEnvironment(context.env, store?.overlay, store?.withhold) }
149
169
  }
150
170
 
151
171
  export function sanitizeBashSpawnEnvironment(
152
172
  inherited: NodeJS.ProcessEnv | undefined,
153
173
  overlay: BashEnvOverlay | undefined,
174
+ withhold: readonly string[] = [],
154
175
  ): NodeJS.ProcessEnv {
155
176
  const env = { ...inherited }
156
177
  for (const name of SECRET_BASH_ENV_NAMES) delete env[name]
178
+ for (const name of withhold) delete env[name]
179
+ // A trusted overlay deliberately replaces ambient state for this command, so
180
+ // it wins when the same name is also withheld.
157
181
  if (overlay !== undefined) Object.assign(env, overlay)
158
182
  return env
159
183
  }
160
184
 
161
- const ACKNOWLEDGE_GUARDS_SCHEMA = Type.Optional(
162
- Type.Object(
163
- {
164
- nonWorkspaceWrite: Type.Optional(Type.Boolean()),
165
- rolePromotion: Type.Optional(Type.Boolean()),
166
- cronPromotion: Type.Optional(Type.Boolean()),
167
- },
168
- { additionalProperties: false },
169
- ),
170
- )
171
-
172
185
  // pi-coding-agent 0.73 contract (load-bearing for hook coverage):
173
186
  // - `createAgentSession({ tools: string[] })` is a name allowlist: only the
174
187
  // listed names stay active, and that allowlist gates BOTH builtins and
@@ -185,11 +198,8 @@ const ACKNOWLEDGE_GUARDS_SCHEMA = Type.Optional(
185
198
  // guard + sandbox pipeline, and the call site routes them through `customTools`
186
199
  // while narrowing via `tools:` names. There is no longer an `AgentTool` vs
187
200
  // `ToolDefinition` split.
188
- type PiBuiltinToolName = 'read' | 'bash' | 'edit' | 'write' | 'grep' | 'find' | 'ls'
189
201
  type TypeclawToolName = 'web_search' | 'web_fetch'
190
202
 
191
- const PI_BUILTIN_TOOL_NAMES: readonly PiBuiltinToolName[] = ['read', 'bash', 'edit', 'write', 'grep', 'find', 'ls']
192
-
193
203
  // pi builtins resolve relative paths (and, for trusted/owner bash, the spawn
194
204
  // cwd) against the cwd baked in at factory time, so the definitions are built
195
205
  // per session from the session's agentDir rather than the module-load
@@ -255,6 +265,7 @@ export type WrapToolOptions = {
255
265
  sessionId: string
256
266
  logger: PluginLogger
257
267
  hooks: HookBus
268
+ guards?: readonly InternalGuard[]
258
269
  // Called at tool-execute time (not at wrap time) so channel sessions whose
259
270
  // origin mutates per turn surface the current-turn `lastInboundAuthorId`
260
271
  // to `tool.before`. Sessions with a fixed origin can pass `() => origin`.
@@ -270,6 +281,7 @@ export type WrapToolOptions = {
270
281
  export type BashSandboxBoundary = {
271
282
  ensureAvailable: () => Promise<void>
272
283
  buildCommand: typeof buildSandboxedCommand
284
+ resolveProcStrategy?: () => Promise<ProcStrategyResolution>
273
285
  resolveRuntime?: typeof resolvePrivilegedSandboxRuntime
274
286
  verifyRuntime?: typeof verifyPrivilegedSandboxRuntime
275
287
  cleanupRuntime?: typeof cleanupPrivilegedSandboxRuntime
@@ -284,6 +296,7 @@ export type WrapSystemToolOptions = {
284
296
  agentDir: string
285
297
  sessionId: string
286
298
  hooks: HookBus
299
+ guards?: readonly InternalGuard[]
287
300
  getOrigin?: () => SessionOrigin | undefined
288
301
  getAbort?: () => ((reason?: string) => void) | undefined
289
302
  getLoopGuardTurn?: () => number | undefined
@@ -334,7 +347,7 @@ export function zodToToolParameters(schema: z.ZodType<unknown>): TSchema {
334
347
  }
335
348
 
336
349
  export function wrapPluginTool(tool: Tool<any>, opts: WrapToolOptions): ToolDefinition {
337
- const parameters = zodToToolParameters(tool.parameters)
350
+ const parameters = withGuardAcknowledgements(opts.toolName, zodToToolParameters(tool.parameters), opts.guards ?? [])
338
351
 
339
352
  return piDefineTool({
340
353
  name: opts.toolName,
@@ -342,7 +355,10 @@ export function wrapPluginTool(tool: Tool<any>, opts: WrapToolOptions): ToolDefi
342
355
  description: tool.description,
343
356
  parameters,
344
357
  async execute(toolCallId, params, signal) {
345
- const validated = tool.parameters.safeParse(params)
358
+ const envelope = extractGuardAcknowledgements(params, opts.toolName, opts.guards ?? [])
359
+ if (!envelope.ok) return errorResult(`invalid arguments: ${envelope.error}`)
360
+
361
+ const validated = tool.parameters.safeParse(envelope.pluginArgs)
346
362
  if (!validated.success) {
347
363
  return errorResult(`invalid arguments: ${validated.error.message}`)
348
364
  }
@@ -359,7 +375,7 @@ export function wrapPluginTool(tool: Tool<any>, opts: WrapToolOptions): ToolDefi
359
375
  ...(liveOrigin !== undefined ? { origin: liveOrigin } : {}),
360
376
  ...(tool.fileOperands !== undefined ? { fileOperands: tool.fileOperands } : {}),
361
377
  }
362
- const blockResult = await opts.hooks.runToolBefore(before)
378
+ const blockResult = await opts.hooks.runToolBefore(before, opts.guards, envelope.acknowledgements)
363
379
  if (blockResult !== undefined) {
364
380
  return errorResult(`blocked: ${blockResult.reason}`)
365
381
  }
@@ -372,7 +388,7 @@ export function wrapPluginTool(tool: Tool<any>, opts: WrapToolOptions): ToolDefi
372
388
  opts.agentDir,
373
389
  )
374
390
  if (loopGate.blockNow) {
375
- fireLoopAbort(opts.getAbort, 'loop_guard:block')
391
+ fireLoopAbort(opts.getAbort, 'loop_guard:block', opts.sessionId)
376
392
  return errorResult(loopGate.message)
377
393
  }
378
394
 
@@ -419,7 +435,7 @@ export function wrapPluginTool(tool: Tool<any>, opts: WrapToolOptions): ToolDefi
419
435
 
420
436
  const resolved = loopGate.resolve(result)
421
437
  if ('deferredBlock' in resolved) {
422
- fireLoopAbort(opts.getAbort, 'loop_guard:deferred_block')
438
+ fireLoopAbort(opts.getAbort, 'loop_guard:deferred_block', opts.sessionId)
423
439
  return errorResult(resolved.deferredBlock)
424
440
  }
425
441
  result = resolved.result
@@ -445,43 +461,41 @@ export function wrapSystemTool<TParams extends TSchema, TDetails = unknown, TSta
445
461
  ): ToolDefinition<TParams, TDetails, TState> {
446
462
  return piDefineTool({
447
463
  ...tool,
448
- parameters: withGuardAcknowledgements(tool.name, tool.parameters),
464
+ parameters: withGuardAcknowledgements(tool.name, tool.parameters, opts.guards ?? []),
449
465
  async execute(toolCallId, params, signal, onUpdate, ctx) {
450
- const mutableArgs = params as Record<string, unknown>
466
+ const envelope = extractGuardAcknowledgements(params, tool.name, opts.guards ?? [])
467
+ if (!envelope.ok) throw new Error(`invalid arguments: ${envelope.error}`)
468
+ const mutableArgs = envelope.pluginArgs as Record<string, unknown>
451
469
  normalizeDefaultTreeRoot(tool.name, mutableArgs)
452
470
  const liveOrigin = opts.getOrigin?.()
453
471
  const preflightFileOperands = opts.resolvePreflightFileOperands?.(tool.name, mutableArgs)
454
- const blockResult = await opts.hooks.runToolBefore({
455
- tool: tool.name,
456
- sessionId: opts.sessionId,
457
- callId: toolCallId,
458
- args: mutableArgs,
459
- toolProvenance: 'first-party',
460
- ...(liveOrigin !== undefined ? { origin: liveOrigin } : {}),
461
- ...(preflightFileOperands !== undefined ? { fileOperands: preflightFileOperands } : {}),
462
- })
472
+ const blockResult = await opts.hooks.runToolBefore(
473
+ {
474
+ tool: tool.name,
475
+ sessionId: opts.sessionId,
476
+ callId: toolCallId,
477
+ args: mutableArgs,
478
+ toolProvenance: 'first-party',
479
+ ...(liveOrigin !== undefined ? { origin: liveOrigin } : {}),
480
+ ...(preflightFileOperands !== undefined ? { fileOperands: preflightFileOperands } : {}),
481
+ },
482
+ opts.guards,
483
+ envelope.acknowledgements,
484
+ )
463
485
  if (blockResult !== undefined) {
464
486
  throw new Error(`blocked: ${blockResult.reason}`)
465
487
  }
466
- const loopGate = gateLoopGuard(opts.sessionId, tool.name, mutableArgs, opts.getLoopGuardTurn?.(), opts.agentDir)
467
- if (loopGate.blockNow) {
468
- fireLoopAbort(opts.getAbort, 'loop_guard:block')
469
- throw new Error(loopGate.message)
470
- }
471
- const guardResult = await runFinalWriteGuards({
488
+ const gitControlResult = await checkGitControlWriteGuard({
472
489
  tool: tool.name,
473
490
  args: mutableArgs,
474
491
  agentDir: opts.agentDir,
475
492
  })
476
- if (guardResult !== undefined) {
477
- throw new Error(`blocked: ${guardResult.reason}`)
478
- }
479
- const readGuardResult = runFinalReadGuards({ tool: tool.name, args: mutableArgs })
480
- if (readGuardResult !== undefined) {
481
- throw new Error(`blocked: ${readGuardResult.reason}`)
493
+ if (gitControlResult !== undefined) throw new Error(`blocked: ${gitControlResult.reason}`)
494
+ const loopGate = gateLoopGuard(opts.sessionId, tool.name, mutableArgs, opts.getLoopGuardTurn?.(), opts.agentDir)
495
+ if (loopGate.blockNow) {
496
+ fireLoopAbort(opts.getAbort, 'loop_guard:block', opts.sessionId)
497
+ throw new Error(loopGate.message)
482
498
  }
483
- stripGuardAcknowledgements(mutableArgs)
484
-
485
499
  // `preflightFileOperands` is deliberately NOT forwarded: this boundary's
486
500
  // canonical credential denial must stay unconditional, so a target-declared
487
501
  // nonFile operand can never exempt `secrets.json`/`.env`/`~/.ssh` from it.
@@ -522,7 +536,7 @@ export function wrapSystemTool<TParams extends TSchema, TDetails = unknown, TSta
522
536
  })
523
537
  const resolved = loopGate.resolve(restoredResult)
524
538
  if ('deferredBlock' in resolved) {
525
- fireLoopAbort(opts.getAbort, 'loop_guard:deferred_block')
539
+ fireLoopAbort(opts.getAbort, 'loop_guard:deferred_block', opts.sessionId)
526
540
  throw new Error(resolved.deferredBlock)
527
541
  }
528
542
  const hookResult = resolved.result
@@ -552,51 +566,55 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
552
566
  ): ToolDefinition<TParams, TDetails, TState> {
553
567
  return piDefineTool({
554
568
  ...tool,
555
- parameters: withGuardAcknowledgements(tool.name, tool.parameters),
569
+ parameters: withGuardAcknowledgements(tool.name, tool.parameters, opts.guards ?? []),
556
570
  async execute(toolCallId, params, signal, onUpdate, ctx) {
557
- const mutableArgs = params as Record<string, unknown>
571
+ const envelope = extractGuardAcknowledgements(params, tool.name, opts.guards ?? [])
572
+ if (!envelope.ok) throw new Error(`invalid arguments: ${envelope.error}`)
573
+ const mutableArgs = envelope.pluginArgs as Record<string, unknown>
558
574
  const originalBashCommand =
559
575
  tool.name === 'bash' && typeof mutableArgs.command === 'string' ? mutableArgs.command : undefined
560
576
  normalizeDefaultTreeRoot(tool.name, mutableArgs)
561
577
  const liveOrigin = opts.getOrigin?.()
562
- // Defense-in-depth: strip any pre-existing internal env-overlay key
563
- // before hooks run so only trusted tool.before hooks can set it.
578
+ // Defense-in-depth: strip pre-existing internal env-control keys before
579
+ // hooks run so only trusted tool.before hooks can set them.
564
580
  delete mutableArgs[TYPECLAW_INTERNAL_BASH_ENV]
565
- const blockResult = await opts.hooks.runToolBefore({
566
- tool: tool.name,
567
- sessionId: opts.sessionId,
568
- callId: toolCallId,
569
- args: mutableArgs,
570
- toolProvenance: 'first-party',
571
- ...(liveOrigin !== undefined ? { origin: liveOrigin } : {}),
572
- })
581
+ delete mutableArgs[TYPECLAW_INTERNAL_BASH_WITHHOLD_ENV]
582
+ delete mutableArgs[TYPECLAW_INTERNAL_BASH_PREPARE]
583
+ const blockResult = await opts.hooks.runToolBefore(
584
+ {
585
+ tool: tool.name,
586
+ sessionId: opts.sessionId,
587
+ callId: toolCallId,
588
+ args: mutableArgs,
589
+ toolProvenance: 'first-party',
590
+ ...(liveOrigin !== undefined ? { origin: liveOrigin } : {}),
591
+ },
592
+ opts.guards,
593
+ envelope.acknowledgements,
594
+ )
573
595
  if (blockResult !== undefined) {
574
596
  throw new Error(`blocked: ${blockResult.reason}`)
575
597
  }
598
+ const gitControlResult = await checkGitControlWriteGuard({
599
+ tool: tool.name,
600
+ args: mutableArgs,
601
+ agentDir: opts.agentDir,
602
+ })
603
+ if (gitControlResult !== undefined) throw new Error(`blocked: ${gitControlResult.reason}`)
576
604
  // Extract and delete before the loop guard serializes args and before
577
605
  // the bash tool destructures them, so the overlay never reaches logs,
578
606
  // loop-detection state, or pi's execute.
579
607
  const bashEnvOverlay = readBashEnvOverlay(mutableArgs)
608
+ const bashEnvWithhold = readBashEnvWithhold(mutableArgs)
609
+ const bashPreparation = readBashPreparation(mutableArgs)
580
610
  delete mutableArgs[TYPECLAW_INTERNAL_BASH_ENV]
611
+ delete mutableArgs[TYPECLAW_INTERNAL_BASH_WITHHOLD_ENV]
612
+ delete mutableArgs[TYPECLAW_INTERNAL_BASH_PREPARE]
581
613
  const loopGate = gateLoopGuard(opts.sessionId, tool.name, mutableArgs, opts.getLoopGuardTurn?.(), opts.agentDir)
582
614
  if (loopGate.blockNow) {
583
- fireLoopAbort(opts.getAbort, 'loop_guard:block')
615
+ fireLoopAbort(opts.getAbort, 'loop_guard:block', opts.sessionId)
584
616
  throw new Error(loopGate.message)
585
617
  }
586
- const guardResult = await runFinalWriteGuards({
587
- tool: tool.name,
588
- args: mutableArgs,
589
- agentDir: opts.agentDir,
590
- })
591
- if (guardResult !== undefined) {
592
- throw new Error(`blocked: ${guardResult.reason}`)
593
- }
594
- const readGuardResult = runFinalReadGuards({ tool: tool.name, args: mutableArgs })
595
- if (readGuardResult !== undefined) {
596
- throw new Error(`blocked: ${readGuardResult.reason}`)
597
- }
598
- stripGuardAcknowledgements(mutableArgs)
599
-
600
618
  // Per-subagent capability fence: runs BEFORE the role-derived sandbox so
601
619
  // a read-only subagent's bash stays read-only even for a trusted/owner
602
620
  // caller whose sandbox otherwise preserves full agent-root writes. Throws
@@ -640,6 +658,8 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
640
658
  opts.agentDir,
641
659
  opts.sessionId,
642
660
  bashEnvOverlay,
661
+ bashEnvWithhold,
662
+ bashPreparation,
643
663
  sandboxBoundary,
644
664
  )
645
665
  }
@@ -664,9 +684,12 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
664
684
  })
665
685
  await preparedSandboxRuntime?.verify()
666
686
  const spawnEnvContext: BashSpawnEnvContext | undefined =
667
- bashEnvOverlay !== undefined || preparedSandboxRuntime?.spawnEnv !== undefined
687
+ bashEnvOverlay !== undefined ||
688
+ bashEnvWithhold !== undefined ||
689
+ preparedSandboxRuntime?.spawnEnv !== undefined
668
690
  ? {
669
691
  ...(bashEnvOverlay !== undefined ? { overlay: bashEnvOverlay } : {}),
692
+ ...(bashEnvWithhold !== undefined ? { withhold: bashEnvWithhold } : {}),
670
693
  ...(preparedSandboxRuntime?.spawnEnv !== undefined
671
694
  ? { sandboxSpawnEnv: preparedSandboxRuntime.spawnEnv }
672
695
  : {}),
@@ -699,7 +722,7 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
699
722
  // no-op for every message/tool outside the allowlist, so abort, sandbox,
700
723
  // and policy errors pass through untouched. Mutating the message in place
701
724
  // preserves the error's subclass and stack for the rethrow.
702
- if (executionError instanceof Error && signal?.aborted !== true) {
725
+ if (cleanupError === undefined && executionError instanceof Error && signal?.aborted !== true) {
703
726
  executionError.message = remediateToolErrorMessage(tool.name, executionError.message)
704
727
  const incidentFact = classifyToolOutcome({ tool: tool.name, error: executionError })
705
728
  if (incidentFact !== null) {
@@ -742,7 +765,13 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
742
765
  }
743
766
  }
744
767
  }
745
- let finalError = executionError ?? cleanupError
768
+ let finalError =
769
+ executionError !== undefined && cleanupError !== undefined
770
+ ? new Error(
771
+ `${executionError instanceof Error ? executionError.message : String(executionError)}\n\n` +
772
+ `Cleanup failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,
773
+ )
774
+ : (executionError ?? cleanupError)
746
775
  if (finalError !== undefined) {
747
776
  // The builtin reports command failures as execution errors rather than
748
777
  // result details. Once the sandbox was prepared, annotate every such
@@ -774,7 +803,7 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
774
803
  }
775
804
  const resolved = loopGate.resolve({ content: result.content as ContentPart[], details: result.details })
776
805
  if ('deferredBlock' in resolved) {
777
- fireLoopAbort(opts.getAbort, 'loop_guard:deferred_block')
806
+ fireLoopAbort(opts.getAbort, 'loop_guard:deferred_block', opts.sessionId)
778
807
  throw new Error(resolved.deferredBlock)
779
808
  }
780
809
  const hookResult = resolved.result
@@ -865,10 +894,12 @@ async function applyBashSandbox(
865
894
  agentDir: string,
866
895
  sessionId: string,
867
896
  envOverlay: BashEnvOverlay | undefined,
897
+ envWithhold: BashEnvWithhold | undefined,
898
+ deferredPreparation: DeferredBashPreparation | undefined,
868
899
  boundary: BashSandboxBoundary,
869
900
  ): Promise<PreparedBashSandbox> {
870
- const command = mutableArgs.command
871
- if (typeof command !== 'string') {
901
+ const originalCommand = mutableArgs.command
902
+ if (typeof originalCommand !== 'string') {
872
903
  return {
873
904
  verify: async () => {},
874
905
  cleanup: async () => {},
@@ -876,43 +907,57 @@ async function applyBashSandbox(
876
907
  }
877
908
  }
878
909
 
879
- const { dirs, files } = resolveHiddenPaths(permissions, origin, agentDir)
880
- const envNames = resolveExposableBashEnvNames(agentDir)
881
- const sandboxEnvOverlay = buildRoleScopedConfigEnv(agentDir, dirs, envOverlay)
882
- const maskTargets = await ensureHiddenMaskTargets({ dirs, files })
883
- await boundary.ensureAvailable()
884
- const sessionTmp = await ensureSessionTmpDir(sessionId)
885
- const dependencyBins = await reconcileDependencyBinWrappers({ agentDir, sessionTmp })
886
- const writable = subtractMasked(await resolveWritableZones(agentDir, getSandboxWritablePathSpecs(config)), {
887
- dirs,
888
- files,
889
- })
890
- const writableRoot = canWriteAgentRootInSandbox(permissions, origin)
891
- const baseProtectedZones =
892
- writableRoot || writable.dirs.includes(join(agentDir, '.git'))
893
- ? subtractMasked(await resolveProtectedZones(agentDir), { dirs, files })
894
- : { dirs: [], files: [] }
895
- const protectedZones = {
896
- dirs: baseProtectedZones.dirs,
897
- files: [...new Set([...baseProtectedZones.files, ...dependencyBins.protectedFiles])],
898
- }
899
- const writableDirSet = new Set(writable.dirs)
900
- const sandboxHome = DEFAULT_SANDBOX_ENV.HOME ?? '/tmp'
901
- const symlinks = resolveSandboxSymlinks(agentDir, config.sandbox.symlinks, sandboxHome).filter((op) =>
902
- writableDirSet.has(op.target),
903
- )
904
- const { strategy: proc, degradeReason } = await resolveProcStrategy()
905
- if (proc === 'tmpfs' && commandNeedsRealProc(command)) {
906
- throw degradeReason === 'unverified' ? new SandboxProcProbeUnverifiedError() : new SandboxDegradedProcError()
910
+ let preparation: DeferredBashPreparationResult | undefined
911
+ let privilegedRuntime: Awaited<ReturnType<typeof resolvePrivilegedSandboxRuntime>> | undefined
912
+ const cleanup = async (): Promise<void> => {
913
+ const tasks: Promise<void>[] = []
914
+ if (privilegedRuntime !== undefined) {
915
+ tasks.push((boundary.cleanupRuntime ?? cleanupPrivilegedSandboxRuntime)(privilegedRuntime))
916
+ }
917
+ if (preparation !== undefined) tasks.push(preparation.cleanup())
918
+ const outcomes = await Promise.allSettled(tasks)
919
+ const failure = outcomes.find((outcome) => outcome.status === 'rejected')
920
+ if (failure?.status === 'rejected') throw failure.reason
907
921
  }
908
- const privilegedRuntime = await (boundary.resolveRuntime ?? resolvePrivilegedSandboxRuntime)({
909
- agentDir,
910
- command,
911
- env: sandboxEnvOverlay,
912
- })
913
- const cleanup = async (): Promise<void> =>
914
- (boundary.cleanupRuntime ?? cleanupPrivilegedSandboxRuntime)(privilegedRuntime)
915
922
  try {
923
+ preparation = await deferredPreparation?.()
924
+ const command = preparation?.command ?? originalCommand
925
+ const preparedEnvOverlay = preparation?.env === undefined ? envOverlay : { ...envOverlay, ...preparation.env }
926
+ const { dirs, files } = resolveHiddenPaths(permissions, origin, agentDir)
927
+ const envNames = resolveExposableBashEnvNames(agentDir)
928
+ const sandboxEnvOverlay = buildRoleScopedConfigEnv(agentDir, dirs, preparedEnvOverlay)
929
+ const effectiveEnvWithhold = (envWithhold ?? []).filter((name) => !Object.hasOwn(sandboxEnvOverlay ?? {}, name))
930
+ const maskTargets = await ensureHiddenMaskTargets({ dirs, files })
931
+ await boundary.ensureAvailable()
932
+ const sessionTmp = await ensureSessionTmpDir(sessionId)
933
+ const dependencyBins = await reconcileDependencyBinWrappers({ agentDir, sessionTmp })
934
+ const writable = subtractMasked(await resolveWritableZones(agentDir, getSandboxWritablePathSpecs(config)), {
935
+ dirs,
936
+ files,
937
+ })
938
+ const writableRoot = canWriteAgentRootInSandbox(permissions, origin)
939
+ const baseProtectedZones =
940
+ writableRoot || writable.dirs.includes(join(agentDir, '.git'))
941
+ ? subtractMasked(await resolveProtectedZones(agentDir), { dirs, files })
942
+ : { dirs: [], files: [] }
943
+ const protectedZones = {
944
+ dirs: baseProtectedZones.dirs,
945
+ files: [...new Set([...baseProtectedZones.files, ...dependencyBins.protectedFiles])],
946
+ }
947
+ const writableDirSet = new Set(writable.dirs)
948
+ const sandboxHome = DEFAULT_SANDBOX_ENV.HOME ?? '/tmp'
949
+ const symlinks = resolveSandboxSymlinks(agentDir, config.sandbox.symlinks, sandboxHome).filter((op) =>
950
+ writableDirSet.has(op.target),
951
+ )
952
+ const { strategy: proc, degradeReason } = await (boundary.resolveProcStrategy ?? resolveProcStrategy)()
953
+ if (proc === 'tmpfs' && commandNeedsRealProc(command)) {
954
+ throw degradeReason === 'unverified' ? new SandboxProcProbeUnverifiedError() : new SandboxDegradedProcError()
955
+ }
956
+ privilegedRuntime = await (boundary.resolveRuntime ?? resolvePrivilegedSandboxRuntime)({
957
+ agentDir,
958
+ command,
959
+ env: sandboxEnvOverlay,
960
+ })
916
961
  await verifyHiddenMaskTargets(maskTargets)
917
962
  const { commandString, spawnEnv } = boundary.buildCommand(command, {
918
963
  mounts: [
@@ -923,6 +968,7 @@ async function applyBashSandbox(
923
968
  // read-only without adding any broader filesystem exposure.
924
969
  { type: 'ro-bind', source: dependencyBins.wrapperDir, dest: DEPENDENCY_BIN_SANDBOX_DIR },
925
970
  ...(privilegedRuntime?.mounts ?? []),
971
+ ...(preparation === undefined ? [] : [preparation.mount]),
926
972
  ],
927
973
  ...(writableRoot
928
974
  ? { writableRoot: { dir: agentDir }, masks: maskTargets, protected: protectedZones }
@@ -932,7 +978,9 @@ async function applyBashSandbox(
932
978
  cwd: agentDir,
933
979
  proc,
934
980
  procSelfExe: resolveProcSelfExe(),
935
- ...spreadSandboxEnv(buildSandboxEnvPolicy(sandboxEnvOverlay, privilegedRuntime?.env, envNames.exposable)),
981
+ ...spreadSandboxEnv(
982
+ buildSandboxEnvPolicy(sandboxEnvOverlay, privilegedRuntime?.env, envNames.exposable, envWithhold),
983
+ ),
936
984
  })
937
985
  mutableArgs.command = commandString
938
986
  // The overlay carries command-scoped secret VALUES (e.g. a per-repo GH_TOKEN)
@@ -941,12 +989,13 @@ async function applyBashSandbox(
941
989
  // to complete the exact bwrap-parent env.
942
990
  const mergedSpawnEnv =
943
991
  spawnEnv !== undefined && sandboxEnvOverlay !== undefined ? { ...spawnEnv, ...sandboxEnvOverlay } : spawnEnv
992
+ const runtimeForResult = privilegedRuntime
944
993
  return {
945
- verify: async () => (boundary.verifyRuntime ?? verifyPrivilegedSandboxRuntime)(privilegedRuntime),
994
+ verify: async () => (boundary.verifyRuntime ?? verifyPrivilegedSandboxRuntime)(runtimeForResult),
946
995
  cleanup,
947
996
  spawnEnv: mergedSpawnEnv,
948
997
  dependencyBins,
949
- withheld: { paths: maskTargets, envNames: envNames.withheld },
998
+ withheld: { paths: maskTargets, envNames: [...new Set([...envNames.withheld, ...effectiveEnvWithhold])] },
950
999
  }
951
1000
  } catch (error) {
952
1001
  await cleanup()
@@ -995,12 +1044,19 @@ export function buildSandboxEnvPolicy(
995
1044
  overlay: BashEnvOverlay | undefined,
996
1045
  runtimeEnv: Record<string, string> | undefined,
997
1046
  exposableEnvNames: readonly string[] = [],
998
- ): { inherit?: string[]; set?: Record<string, string> } {
999
- const set = { ...runtimeEnv }
1047
+ withhold: readonly string[] = [],
1048
+ ): { inherit?: string[]; set?: Record<string, string>; withhold?: string[] } {
1049
+ const requestedWithhold = new Set(withhold)
1050
+ const overlayNames = new Set(Object.keys(overlay ?? {}))
1051
+ // The overlay is a deliberate command-scoped replacement, while withholding
1052
+ // only removes ambient values; an overlay therefore wins for the same name.
1053
+ const effectiveWithhold = [...requestedWithhold].filter((name) => !overlayNames.has(name))
1054
+ const effectiveWithholdSet = new Set(effectiveWithhold)
1055
+ const set = Object.fromEntries(Object.entries(runtimeEnv ?? {}).filter(([key]) => !requestedWithhold.has(key)))
1000
1056
  const inherit: string[] = []
1001
1057
  const inheritSeen = new Set<string>()
1002
1058
  const pushInherit = (key: string): void => {
1003
- if (Object.hasOwn(set, key) || inheritSeen.has(key)) return
1059
+ if (effectiveWithholdSet.has(key) || Object.hasOwn(set, key) || inheritSeen.has(key)) return
1004
1060
  inheritSeen.add(key)
1005
1061
  inherit.push(key)
1006
1062
  }
@@ -1021,12 +1077,19 @@ export function buildSandboxEnvPolicy(
1021
1077
  // /tmp/.X11-unix bind is needed: Chrome reaches Xvfb over the netns-scoped
1022
1078
  // abstract X11 socket while bash keeps network:'inherit'.
1023
1079
  const display = process.env['DISPLAY']
1024
- if (display !== undefined && display !== '' && !Object.hasOwn(set, 'DISPLAY') && !inheritSeen.has('DISPLAY')) {
1080
+ if (
1081
+ display !== undefined &&
1082
+ display !== '' &&
1083
+ !effectiveWithholdSet.has('DISPLAY') &&
1084
+ !Object.hasOwn(set, 'DISPLAY') &&
1085
+ !inheritSeen.has('DISPLAY')
1086
+ ) {
1025
1087
  set['DISPLAY'] = display
1026
1088
  }
1027
1089
  return {
1028
1090
  ...(inherit.length > 0 ? { inherit } : {}),
1029
1091
  ...(Object.keys(set).length > 0 ? { set } : {}),
1092
+ ...(effectiveWithhold.length > 0 ? { withhold: effectiveWithhold } : {}),
1030
1093
  }
1031
1094
  }
1032
1095
 
@@ -1342,8 +1405,21 @@ export function __resetSharedLoopGuardForTests(): void {
1342
1405
  // 'aborted'). We use the signal-only `agent.abort`, never `session.abort`,
1343
1406
  // which would deadlock awaiting the very run this tool call belongs to. See
1344
1407
  // the matching pattern in src/channels/router.ts (policy-denied send cap).
1345
- function fireLoopAbort(getAbort: (() => ((reason?: string) => void) | undefined) | undefined, reason: string): void {
1346
- getAbort?.()?.(reason)
1408
+ //
1409
+ // A signal-only abort leaves no trace in the transcript itself (the turn just
1410
+ // ends with stopReason 'aborted' and no follow-up call), so this is the only
1411
+ // place an operator can learn WHY from `typeclaw logs` — log before invoking
1412
+ // the abort, not after, so a getAbort() that turns out to be undefined never
1413
+ // reports an abort that didn't actually happen.
1414
+ function fireLoopAbort(
1415
+ getAbort: (() => ((reason?: string) => void) | undefined) | undefined,
1416
+ reason: string,
1417
+ sessionId: string,
1418
+ ): void {
1419
+ const abort = getAbort?.()
1420
+ if (abort === undefined) return
1421
+ console.warn(`[agent] abort site=loop_guard session=${sessionId} reason=${reason}`)
1422
+ abort(reason)
1347
1423
  }
1348
1424
 
1349
1425
  function errorResult(message: string) {
@@ -1354,15 +1430,6 @@ function errorResult(message: string) {
1354
1430
  }
1355
1431
  }
1356
1432
 
1357
- async function runFinalWriteGuards(options: { tool: string; args: Record<string, unknown>; agentDir: string }) {
1358
- return (
1359
- (await checkGitControlWriteGuard(options)) ??
1360
- (await checkManagedConfigGuard(options)) ??
1361
- (await checkSkillAuthoringGuard(options)) ??
1362
- checkNonWorkspaceWriteGuard(options)
1363
- )
1364
- }
1365
-
1366
1433
  async function checkGitControlWriteGuard(options: {
1367
1434
  tool: string
1368
1435
  args: Record<string, unknown>
@@ -1378,26 +1445,94 @@ async function checkGitControlWriteGuard(options: {
1378
1445
  }
1379
1446
  }
1380
1447
 
1381
- function runFinalReadGuards(options: { tool: string; args: Record<string, unknown> }) {
1382
- return checkImageReadRedirect(options)
1383
- }
1384
-
1385
- function withGuardAcknowledgements<TParams extends TSchema>(toolName: string, parameters: TParams): TParams {
1386
- if (toolName !== 'write' && toolName !== 'edit') return parameters
1448
+ function withGuardAcknowledgements<TParams extends TSchema>(
1449
+ toolName: string,
1450
+ parameters: TParams,
1451
+ guards: readonly InternalGuard[],
1452
+ ): TParams {
1453
+ const matching = guards.filter((guard) => guard.tools.has(toolName))
1454
+ if (matching.length === 0) return parameters
1387
1455
 
1388
1456
  const schema = parameters as Record<string, unknown>
1389
1457
  const properties = schema.properties
1390
1458
  if (!properties || typeof properties !== 'object' || Array.isArray(properties)) return parameters
1459
+ if (ACKNOWLEDGE_GUARDS in properties) {
1460
+ throw new Error(`tool "${toolName}" declares reserved parameter "${ACKNOWLEDGE_GUARDS}"`)
1461
+ }
1462
+
1463
+ const acknowledgementProperties: Record<string, TSchema> = {}
1464
+ for (const guard of matching) {
1465
+ const plugin = acknowledgementProperties[guard.owner] as { properties?: Record<string, TSchema> } | undefined
1466
+ acknowledgementProperties[guard.owner] = Type.Optional(
1467
+ Type.Object(
1468
+ { ...plugin?.properties, [guard.key]: Type.Optional(Type.Boolean()) },
1469
+ { additionalProperties: false },
1470
+ ),
1471
+ )
1472
+ }
1391
1473
 
1392
1474
  return {
1393
1475
  ...schema,
1394
1476
  properties: {
1395
1477
  ...(properties as Record<string, unknown>),
1396
- [ACKNOWLEDGE_GUARDS]: ACKNOWLEDGE_GUARDS_SCHEMA,
1478
+ [ACKNOWLEDGE_GUARDS]: Type.Optional(Type.Object(acknowledgementProperties, { additionalProperties: false })),
1397
1479
  },
1398
1480
  } as unknown as TParams
1399
1481
  }
1400
1482
 
1401
- function stripGuardAcknowledgements(args: Record<string, unknown>): void {
1402
- delete args[ACKNOWLEDGE_GUARDS]
1483
+ function extractGuardAcknowledgements(
1484
+ params: unknown,
1485
+ toolName: string,
1486
+ guards: readonly InternalGuard[],
1487
+ ):
1488
+ | {
1489
+ ok: true
1490
+ pluginArgs: unknown
1491
+ acknowledgements?: Record<string, Record<string, boolean>>
1492
+ }
1493
+ | { ok: false; error: string } {
1494
+ if (params === null || typeof params !== 'object' || Array.isArray(params)) {
1495
+ return { ok: true, pluginArgs: params }
1496
+ }
1497
+
1498
+ const pluginArgs = params as Record<string, unknown>
1499
+ if (!Object.hasOwn(pluginArgs, ACKNOWLEDGE_GUARDS)) return { ok: true, pluginArgs }
1500
+
1501
+ const rawAcknowledgements = pluginArgs[ACKNOWLEDGE_GUARDS]
1502
+ delete pluginArgs[ACKNOWLEDGE_GUARDS]
1503
+ if (rawAcknowledgements === null || typeof rawAcknowledgements !== 'object' || Array.isArray(rawAcknowledgements)) {
1504
+ return { ok: false, error: `${ACKNOWLEDGE_GUARDS} must be an object` }
1505
+ }
1506
+
1507
+ const acknowledgements: Record<string, Record<string, boolean>> = {}
1508
+ for (const [pluginName, rawPluginAcknowledgements] of Object.entries(
1509
+ rawAcknowledgements as Record<string, unknown>,
1510
+ )) {
1511
+ if (
1512
+ rawPluginAcknowledgements === null ||
1513
+ typeof rawPluginAcknowledgements !== 'object' ||
1514
+ Array.isArray(rawPluginAcknowledgements)
1515
+ ) {
1516
+ return { ok: false, error: `${ACKNOWLEDGE_GUARDS}.${pluginName} must be an object` }
1517
+ }
1518
+ const pluginAcknowledgements: Record<string, boolean> = {}
1519
+ for (const [key, value] of Object.entries(rawPluginAcknowledgements as Record<string, unknown>)) {
1520
+ const allowed = guards.some(
1521
+ (guard) => guard.owner === pluginName && guard.key === key && guard.tools.has(toolName),
1522
+ )
1523
+ if (!allowed) {
1524
+ return {
1525
+ ok: false,
1526
+ error: `${ACKNOWLEDGE_GUARDS}.${pluginName}.${key} is not allowed for tool "${toolName}"`,
1527
+ }
1528
+ }
1529
+ if (typeof value !== 'boolean') {
1530
+ return { ok: false, error: `${ACKNOWLEDGE_GUARDS}.${pluginName}.${key} must be a boolean` }
1531
+ }
1532
+ pluginAcknowledgements[key] = value
1533
+ }
1534
+ acknowledgements[pluginName] = pluginAcknowledgements
1535
+ }
1536
+
1537
+ return { ok: true, pluginArgs, acknowledgements }
1403
1538
  }