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
@@ -1,4 +1,4 @@
1
- import { definePlugin } from '@/plugin'
1
+ import { definePlugin, type PluginLogger } from '@/plugin'
2
2
  import { resolveHiddenPaths } from '@/sandbox'
3
3
 
4
4
  import { HIGH_TIER_PER_GUARD_PERMISSIONS, SECURITY_PERMISSIONS, SEVERITY_PERMISSION } from './permissions'
@@ -87,6 +87,15 @@ function withPermissionHint(
87
87
  }
88
88
  }
89
89
 
90
+ const INTERNAL_SECURITY_GUARD_REASON =
91
+ 'The tool call was blocked because an internal security guard error prevented safe evaluation.'
92
+
93
+ function reportInternalGuardError(logger: PluginLogger, guard: string, error: unknown): void {
94
+ const detail = error instanceof Error ? (error.stack ?? error.message) : String(error)
95
+ const code = error instanceof Error && 'code' in error && typeof error.code === 'string' ? ` code=${error.code}` : ''
96
+ logger.error(`internal security guard error guard=${guard}${code}: ${detail}`)
97
+ }
98
+
90
99
  export default definePlugin({
91
100
  permissions: Object.values(SECURITY_PERMISSIONS),
92
101
  // No wildcard exclusions: owner bypasses every security tier by default
@@ -102,148 +111,189 @@ export default definePlugin({
102
111
  applyPromptInjectionDefense(event)
103
112
  },
104
113
  'tool.before': async (event) => {
105
- const can = (perm: string) => ctx.permissions.has(event.origin, perm)
106
- const canBypass = (severity: SecuritySeverity, perGuardPerm: string): boolean =>
107
- can(SEVERITY_PERMISSION[severity]) || can(perGuardPerm)
108
-
109
- // The cron guard blocks deferred work that fires as a role granting
110
- // permissions the caller lacks. Capability dominance — target's
111
- // permission set must be a SUBSET of the caller's — not the coarse
112
- // `compareRoleSeverity` tower: every configured custom role ranks
113
- // equal there, so rank `>= 0` would let one custom role schedule as a
114
- // different custom role (or `trusted` schedule as a custom role with
115
- // an extra grant), laundering permissions the caller never had. Unknown
116
- // caller/target role => undefined permissions => fail closed.
117
- const callerRole = ctx.permissions.resolveRole(event.origin)
118
- const canScheduleAs = (targetRole: string | undefined): boolean => {
119
- if (targetRole === undefined) return false
120
- const callerPermissions = ctx.permissions.permissionsForRole(callerRole)
121
- const targetPermissions = ctx.permissions.permissionsForRole(targetRole)
122
- if (callerPermissions === undefined || targetPermissions === undefined) return false
123
- const callerSet = new Set(callerPermissions)
124
- return targetPermissions.every((permission) => callerSet.has(permission))
125
- }
114
+ try {
115
+ const can = (perm: string) => ctx.permissions.has(event.origin, perm)
116
+ const canBypass = (severity: SecuritySeverity, perGuardPerm: string): boolean =>
117
+ can(SEVERITY_PERMISSION[severity]) || can(perGuardPerm)
118
+
119
+ // The cron guard blocks deferred work that fires as a role granting
120
+ // permissions the caller lacks. Capability dominance — target's
121
+ // permission set must be a SUBSET of the caller's — not the coarse
122
+ // `compareRoleSeverity` tower: every configured custom role ranks
123
+ // equal there, so rank `>= 0` would let one custom role schedule as a
124
+ // different custom role (or `trusted` schedule as a custom role with
125
+ // an extra grant), laundering permissions the caller never had. Unknown
126
+ // caller/target role => undefined permissions => fail closed.
127
+ const callerRole = ctx.permissions.resolveRole(event.origin)
128
+ const canScheduleAs = (targetRole: string | undefined): boolean => {
129
+ if (targetRole === undefined) return false
130
+ const callerPermissions = ctx.permissions.permissionsForRole(callerRole)
131
+ const targetPermissions = ctx.permissions.permissionsForRole(targetRole)
132
+ if (callerPermissions === undefined || targetPermissions === undefined) return false
133
+ const callerSet = new Set(callerPermissions)
134
+ return targetPermissions.every((permission) => callerSet.has(permission))
135
+ }
136
+
137
+ const rolePromotionResult = canBypass(GUARD_ROLE_PROMOTION_SEVERITY, SECURITY_PERMISSIONS.bypassRolePromotion)
138
+ ? undefined
139
+ : withPermissionHint(
140
+ await checkRolePromotionGuard({ tool: event.tool, args: event.args, agentDir: ctx.agentDir }),
141
+ SECURITY_PERMISSIONS.bypassRolePromotion,
142
+ GUARD_ROLE_PROMOTION_SEVERITY,
143
+ )
144
+ if (rolePromotionResult) return rolePromotionResult
145
+
146
+ const cronPromotionResult = canBypass(GUARD_CRON_PROMOTION_SEVERITY, SECURITY_PERMISSIONS.bypassCronPromotion)
147
+ ? undefined
148
+ : withPermissionHint(
149
+ await checkCronPromotionGuard({
150
+ tool: event.tool,
151
+ args: event.args,
152
+ agentDir: ctx.agentDir,
153
+ canScheduleAs,
154
+ }),
155
+ SECURITY_PERMISSIONS.bypassCronPromotion,
156
+ GUARD_CRON_PROMOTION_SEVERITY,
157
+ )
158
+ if (cronPromotionResult) return cronPromotionResult
159
+
160
+ const pluginAdditionResult = canBypass(
161
+ GUARD_PLUGIN_ADDITION_SEVERITY,
162
+ SECURITY_PERMISSIONS.bypassPluginAddition,
163
+ )
164
+ ? undefined
165
+ : withPermissionHint(
166
+ await checkPluginAdditionGuard({ tool: event.tool, args: event.args, agentDir: ctx.agentDir }),
167
+ SECURITY_PERMISSIONS.bypassPluginAddition,
168
+ GUARD_PLUGIN_ADDITION_SEVERITY,
169
+ )
170
+ if (pluginAdditionResult) return pluginAdditionResult
126
171
 
127
- const rolePromotionResult = canBypass(GUARD_ROLE_PROMOTION_SEVERITY, SECURITY_PERMISSIONS.bypassRolePromotion)
128
- ? undefined
129
- : withPermissionHint(
130
- await checkRolePromotionGuard({ tool: event.tool, args: event.args, agentDir: ctx.agentDir }),
131
- SECURITY_PERMISSIONS.bypassRolePromotion,
132
- GUARD_ROLE_PROMOTION_SEVERITY,
133
- )
134
- if (rolePromotionResult) return rolePromotionResult
135
-
136
- const cronPromotionResult = canBypass(GUARD_CRON_PROMOTION_SEVERITY, SECURITY_PERMISSIONS.bypassCronPromotion)
137
- ? undefined
138
- : withPermissionHint(
139
- await checkCronPromotionGuard({
140
- tool: event.tool,
141
- args: event.args,
142
- agentDir: ctx.agentDir,
143
- canScheduleAs,
144
- }),
145
- SECURITY_PERMISSIONS.bypassCronPromotion,
146
- GUARD_CRON_PROMOTION_SEVERITY,
147
- )
148
- if (cronPromotionResult) return cronPromotionResult
149
-
150
- const pluginAdditionResult = canBypass(
151
- GUARD_PLUGIN_ADDITION_SEVERITY,
152
- SECURITY_PERMISSIONS.bypassPluginAddition,
153
- )
154
- ? undefined
155
- : withPermissionHint(
156
- await checkPluginAdditionGuard({ tool: event.tool, args: event.args, agentDir: ctx.agentDir }),
157
- SECURITY_PERMISSIONS.bypassPluginAddition,
158
- GUARD_PLUGIN_ADDITION_SEVERITY,
159
- )
160
- if (pluginAdditionResult) return pluginAdditionResult
161
-
162
- // Taint-recording runs FIRST, independently of the gitExfil guard.
163
- // The gitRemoteTainted defense depends on it. We pass through
164
- // `permittedBypass` for actors who can skip gitExfil (via either the
165
- // per-guard permission or the medium-tier permission) so the
166
- // recorder still fires for them — an acked or permission-bypassed
167
- // command will actually run, so its remote change must be remembered.
168
- recordGitRemoteTaintIfAny({
169
- tool: event.tool,
170
- args: event.args,
171
- sessionId: event.sessionId,
172
- permittedBypass: canBypass(GUARD_GIT_EXFIL_SEVERITY, SECURITY_PERMISSIONS.bypassGitExfil),
173
- })
174
-
175
- const checks: (SecurityBlock | undefined)[] = [
176
- canBypass(GUARD_GIT_REMOTE_TAINTED_SEVERITY, SECURITY_PERMISSIONS.bypassGitRemoteTainted)
172
+ // Taint-recording runs FIRST, independently of the gitExfil guard.
173
+ // The gitRemoteTainted defense depends on it. We pass through
174
+ // `permittedBypass` for actors who can skip gitExfil (via either the
175
+ // per-guard permission or the medium-tier permission) so the
176
+ // recorder still fires for them — an acked or permission-bypassed
177
+ // command will actually run, so its remote change must be remembered.
178
+ recordGitRemoteTaintIfAny({
179
+ tool: event.tool,
180
+ args: event.args,
181
+ sessionId: event.sessionId,
182
+ permittedBypass: canBypass(GUARD_GIT_EXFIL_SEVERITY, SECURITY_PERMISSIONS.bypassGitExfil),
183
+ })
184
+
185
+ const gitRemoteTaintedResult = canBypass(
186
+ GUARD_GIT_REMOTE_TAINTED_SEVERITY,
187
+ SECURITY_PERMISSIONS.bypassGitRemoteTainted,
188
+ )
177
189
  ? undefined
178
190
  : withPermissionHint(
179
191
  checkGitRemoteTaintedGuard({ tool: event.tool, args: event.args, sessionId: event.sessionId }),
180
192
  SECURITY_PERMISSIONS.bypassGitRemoteTainted,
181
193
  GUARD_GIT_REMOTE_TAINTED_SEVERITY,
182
- ),
183
- canBypass(GUARD_SECRET_EXFIL_BASH_SEVERITY, SECURITY_PERMISSIONS.bypassSecretExfilBash)
194
+ )
195
+ if (gitRemoteTaintedResult) return gitRemoteTaintedResult
196
+
197
+ const secretExfilBashResult = canBypass(
198
+ GUARD_SECRET_EXFIL_BASH_SEVERITY,
199
+ SECURITY_PERMISSIONS.bypassSecretExfilBash,
200
+ )
184
201
  ? undefined
185
202
  : withPermissionHint(
186
203
  checkSecretExfilBashGuard({ tool: event.tool, args: event.args }),
187
204
  SECURITY_PERMISSIONS.bypassSecretExfilBash,
188
205
  GUARD_SECRET_EXFIL_BASH_SEVERITY,
189
- ),
190
- canBypass(GUARD_GIT_EXFIL_SEVERITY, SECURITY_PERMISSIONS.bypassGitExfil)
206
+ )
207
+ if (secretExfilBashResult) return secretExfilBashResult
208
+
209
+ const gitExfilResult = canBypass(GUARD_GIT_EXFIL_SEVERITY, SECURITY_PERMISSIONS.bypassGitExfil)
191
210
  ? undefined
192
211
  : withPermissionHint(
193
212
  checkGitExfilGuard({ tool: event.tool, args: event.args, sessionId: event.sessionId }),
194
213
  SECURITY_PERMISSIONS.bypassGitExfil,
195
214
  GUARD_GIT_EXFIL_SEVERITY,
196
- ),
197
- canBypass(GUARD_SECRET_EXFIL_READ_SEVERITY, SECURITY_PERMISSIONS.bypassSecretExfilRead)
215
+ )
216
+ if (gitExfilResult) return gitExfilResult
217
+
218
+ const secretExfilReadResult = canBypass(
219
+ GUARD_SECRET_EXFIL_READ_SEVERITY,
220
+ SECURITY_PERMISSIONS.bypassSecretExfilRead,
221
+ )
198
222
  ? undefined
199
223
  : withPermissionHint(
200
224
  checkSecretExfilReadGuard({ tool: event.tool, args: event.args }),
201
225
  SECURITY_PERMISSIONS.bypassSecretExfilRead,
202
226
  GUARD_SECRET_EXFIL_READ_SEVERITY,
203
- ),
227
+ )
228
+ if (secretExfilReadResult) return secretExfilReadResult
229
+
204
230
  // Not severity-bypassed: private directories remain role-derived,
205
231
  // while canonical credential-store denial is unconditional. Mirrors
206
232
  // the bash masks onto every non-bash path-bearing tool.
207
- checkPrivateSurfaceReadGuard({
208
- tool: event.tool,
209
- args: event.args,
210
- agentDir: ctx.agentDir,
211
- hidden: resolveHiddenPaths(ctx.permissions, event.origin, ctx.agentDir),
212
- ...(event.fileOperands !== undefined ? { fileOperands: event.fileOperands } : {}),
213
- }),
214
- canBypass(GUARD_SSRF_SEVERITY, SECURITY_PERMISSIONS.bypassSsrf)
233
+ const privateSurfaceReadResult = checkPrivateSurfaceReadGuard(
234
+ {
235
+ tool: event.tool,
236
+ args: event.args,
237
+ agentDir: ctx.agentDir,
238
+ hidden: resolveHiddenPaths(ctx.permissions, event.origin, ctx.agentDir),
239
+ ...(event.fileOperands !== undefined ? { fileOperands: event.fileOperands } : {}),
240
+ },
241
+ {
242
+ onInternalError: (error) => reportInternalGuardError(ctx.logger, 'privateSurfaceRead', error),
243
+ },
244
+ )
245
+ if (privateSurfaceReadResult) return privateSurfaceReadResult
246
+
247
+ const ssrfResult = canBypass(GUARD_SSRF_SEVERITY, SECURITY_PERMISSIONS.bypassSsrf)
215
248
  ? undefined
216
249
  : withPermissionHint(
217
250
  checkSsrfGuard({ tool: event.tool, args: event.args }),
218
251
  SECURITY_PERMISSIONS.bypassSsrf,
219
252
  GUARD_SSRF_SEVERITY,
220
- ),
221
- canBypass(GUARD_SESSION_SEARCH_SECRETS_SEVERITY, SECURITY_PERMISSIONS.bypassSessionSearchSecrets)
253
+ )
254
+ if (ssrfResult) return ssrfResult
255
+
256
+ const sessionSearchSecretsResult = canBypass(
257
+ GUARD_SESSION_SEARCH_SECRETS_SEVERITY,
258
+ SECURITY_PERMISSIONS.bypassSessionSearchSecrets,
259
+ )
222
260
  ? undefined
223
261
  : withPermissionHint(
224
262
  checkSessionSearchSecretsGuard({ tool: event.tool, args: event.args }),
225
263
  SECURITY_PERMISSIONS.bypassSessionSearchSecrets,
226
264
  GUARD_SESSION_SEARCH_SECRETS_SEVERITY,
227
- ),
228
- canBypass(GUARD_SYSTEM_PROMPT_LEAK_SEVERITY, SECURITY_PERMISSIONS.bypassSystemPromptLeak)
265
+ )
266
+ if (sessionSearchSecretsResult) return sessionSearchSecretsResult
267
+
268
+ const systemPromptLeakResult = canBypass(
269
+ GUARD_SYSTEM_PROMPT_LEAK_SEVERITY,
270
+ SECURITY_PERMISSIONS.bypassSystemPromptLeak,
271
+ )
229
272
  ? undefined
230
273
  : withPermissionHint(
231
274
  checkSystemPromptLeakGuard({ tool: event.tool, args: event.args }),
232
275
  SECURITY_PERMISSIONS.bypassSystemPromptLeak,
233
276
  GUARD_SYSTEM_PROMPT_LEAK_SEVERITY,
234
- ),
235
- canBypass(GUARD_OUTBOUND_SECRET_SEVERITY, SECURITY_PERMISSIONS.bypassOutboundSecret)
277
+ )
278
+ if (systemPromptLeakResult) return systemPromptLeakResult
279
+
280
+ const outboundSecretResult = canBypass(
281
+ GUARD_OUTBOUND_SECRET_SEVERITY,
282
+ SECURITY_PERMISSIONS.bypassOutboundSecret,
283
+ )
236
284
  ? undefined
237
285
  : withPermissionHint(
238
286
  checkOutboundSecretGuard({ tool: event.tool, args: event.args }),
239
287
  SECURITY_PERMISSIONS.bypassOutboundSecret,
240
288
  GUARD_OUTBOUND_SECRET_SEVERITY,
241
- ),
242
- ]
243
- for (const result of checks) {
244
- if (result) return result
289
+ )
290
+ if (outboundSecretResult) return outboundSecretResult
291
+
292
+ return undefined
293
+ } catch (error) {
294
+ reportInternalGuardError(ctx.logger, 'tool.before', error)
295
+ return { block: true, reason: INTERNAL_SECURITY_GUARD_REASON }
245
296
  }
246
- return undefined
247
297
  },
248
298
  'session.end': async (event) => {
249
299
  clearSessionTaints(event.sessionId)
@@ -81,24 +81,33 @@ export function checkPrivateSurfaceReadGuard(
81
81
  ): SecurityBlock | undefined {
82
82
  const { tool, args, agentDir, hidden, fileOperands } = options
83
83
  if (UNSCANNED_TOOLS.has(tool)) return undefined
84
- const { deniedDirs, deniedFiles } = deniedSurface(agentDir, hidden)
85
- if (deniedDirs.length === 0 && deniedFiles.length === 0) return undefined
86
- const identityScanner = createHardlinkIdentityScanner(agentDir, deniedDirs, deniedFiles, hooks)
87
-
88
- const nonFile = fileOperands?.nonFile === undefined ? undefined : new Set(fileOperands.nonFile)
89
- for (const candidate of collectPathCandidates(args, tool, nonFile)) {
90
- const hit = matchHidden(candidate, agentDir, deniedDirs, deniedFiles, identityScanner)
91
- if (hit !== undefined) {
92
- return {
93
- block: true,
94
- reason: [
95
- `Guard \`${GUARD_PRIVATE_SURFACE_READ}\` blocked ${tool}: argument \`${candidate}\` resolves to ${hit}, which is not available to LLM tools.`,
96
- 'The bash sandbox masks the same path. Privileged roles cannot bypass canonical agent credential files; use host-side redacted diagnostics such as `typeclaw doctor`, `typeclaw provider list`, or `typeclaw channel list` instead.',
97
- ].join(' '),
84
+ try {
85
+ const { deniedDirs, deniedFiles } = deniedSurface(agentDir, hidden)
86
+ if (deniedDirs.length === 0 && deniedFiles.length === 0) return undefined
87
+ const identityScanner = createHardlinkIdentityScanner(agentDir, deniedDirs, deniedFiles, hooks)
88
+ const realpath = hooks.realpathNative ?? realpathSync.native
89
+
90
+ const nonFile = fileOperands?.nonFile === undefined ? undefined : new Set(fileOperands.nonFile)
91
+ for (const candidate of collectPathCandidates(args, tool, nonFile)) {
92
+ const hit = matchHidden(candidate, agentDir, deniedDirs, deniedFiles, identityScanner, realpath)
93
+ if (hit !== undefined) {
94
+ return {
95
+ block: true,
96
+ reason: [
97
+ `Guard \`${GUARD_PRIVATE_SURFACE_READ}\` blocked ${tool}: argument \`${candidate}\` resolves to ${hit}, which is not available to LLM tools.`,
98
+ 'The bash sandbox masks the same path. Privileged roles cannot bypass canonical agent credential files; use host-side redacted diagnostics such as `typeclaw doctor`, `typeclaw provider list`, or `typeclaw channel list` instead.',
99
+ ].join(' '),
100
+ }
98
101
  }
99
102
  }
103
+ return undefined
104
+ } catch (error) {
105
+ hooks.onInternalError?.(error)
106
+ return {
107
+ block: true,
108
+ reason: `Guard \`${GUARD_PRIVATE_SURFACE_READ}\` blocked ${tool}: an internal guard error prevented safe path validation.`,
109
+ }
100
110
  }
101
- return undefined
102
111
  }
103
112
 
104
113
  type PrivateSurfaceIdentityOptions = {
@@ -111,6 +120,8 @@ export type PrivateSurfaceIdentityScanHooks = {
111
120
  maxEntries?: number
112
121
  openDirectory?(directory: string): Pick<Dir, 'readSync' | 'closeSync'>
113
122
  lstat?(candidate: string): Stats
123
+ realpathNative?(candidate: string): string
124
+ onInternalError?(error: unknown): void
114
125
  afterEntryLstat?(candidate: string, stats: Stats): void
115
126
  }
116
127
 
@@ -157,6 +168,7 @@ function createHardlinkIdentityScanner(
157
168
  ? openDescriptorAnchoredDirectory
158
169
  : createPathDirectoryOpener(hooks.openDirectory, lstat),
159
170
  lstat,
171
+ realpath: hooks.realpathNative ?? realpathSync.native,
160
172
  afterEntryLstat: hooks.afterEntryLstat,
161
173
  })
162
174
  }
@@ -341,18 +353,19 @@ function matchHidden(
341
353
  deniedDirs: string[],
342
354
  deniedFiles: string[],
343
355
  identityScanner: HardlinkIdentityScanner,
356
+ realpath: (candidate: string) => string,
344
357
  ): string | undefined {
345
358
  const lexicalHit = matchLexicallyDenied(candidate, agentDir, deniedDirs, deniedFiles)
346
359
  if (lexicalHit !== undefined) return lexicalHit
347
360
  const lexical = path.resolve(agentDir, candidate)
348
- const resolved = realpathRealIntendedPath(lexical)
361
+ const resolved = realpathRealIntendedPath(lexical, realpath)
349
362
  const virtualRoot = virtualFilesystemRoot(lexical) ?? virtualFilesystemRoot(resolved)
350
363
  if (virtualRoot !== undefined) return `${virtualRoot}, a virtual or process-backed filesystem`
351
364
  for (const file of deniedFiles) {
352
- if (resolved === realpathRealIntendedPath(file) || hasSameFileIdentity(resolved, file)) return file
365
+ if (resolved === realpathRealIntendedPath(file, realpath) || hasSameFileIdentity(resolved, file)) return file
353
366
  }
354
367
  for (const dir of deniedDirs) {
355
- const realDir = realpathRealIntendedPath(dir)
368
+ const realDir = realpathRealIntendedPath(dir, realpath)
356
369
  // realpathRealIntendedPath joins with the platform separator, so the
357
370
  // under-dir test must use path.sep too — a hardcoded "/" never matches the
358
371
  // "\"-joined paths a win32 test runner produces.
@@ -510,6 +523,7 @@ type HardlinkIdentityScannerOptions = {
510
523
  maxEntries: number
511
524
  openDirectory(directory: string): HardlinkDirectory
512
525
  lstat(candidate: string): Stats
526
+ realpath(candidate: string): string
513
527
  afterEntryLstat?(candidate: string, stats: Stats): void
514
528
  }
515
529
 
@@ -565,9 +579,11 @@ class HardlinkIdentityScanner {
565
579
  private scanVisibleTree(): void {
566
580
  if (this.visibleScanned) return
567
581
  this.visibleScanned = true
568
- const root = realpathRealIntendedPath(this.options.agentDir)
569
- const deniedRoots = this.options.deniedDirs.map(realpathRealIntendedPath)
570
- const deniedFiles = new Set(this.options.deniedFiles.map(realpathRealIntendedPath))
582
+ const root = realpathRealIntendedPath(this.options.agentDir, this.options.realpath)
583
+ const deniedRoots = this.options.deniedDirs.map((dir) => realpathRealIntendedPath(dir, this.options.realpath))
584
+ const deniedFiles = new Set(
585
+ this.options.deniedFiles.map((file) => realpathRealIntendedPath(file, this.options.realpath)),
586
+ )
571
587
  const rootStats = this.readRootStats(root, 'visible')
572
588
  if (rootStats === undefined) return
573
589
  const rootDirectory = this.openVerifiedDirectory(root, rootStats, 'visible')
@@ -619,7 +635,7 @@ class HardlinkIdentityScanner {
619
635
  let rootStats: Stats
620
636
  let root: string
621
637
  try {
622
- root = realpathRealIntendedPath(deniedDir)
638
+ root = realpathRealIntendedPath(deniedDir, this.options.realpath)
623
639
  rootStats = this.options.lstat(root)
624
640
  } catch (error) {
625
641
  if (isNotFoundError(error)) continue
@@ -950,16 +966,15 @@ function hasSameFileIdentity(candidate: string, deniedFile: string): boolean {
950
966
  // symlinked component including a planted symlink), and rejoin the remainder.
951
967
  // This catches `public/leak/x` where `public/leak` is a symlink into a hidden
952
968
  // dir even though `public/leak/x` itself does not exist. Sync (realpathSync)
953
- // keeps the guard synchronous so the security tool.before check array stays
954
- // non-async; the cost is one syscall per existing component, negligible at the
955
- // tool-call boundary. Sync mirror of resolveRealIntendedPath in the guard
956
- // plugin's non-workspace-write policy.
957
- function realpathRealIntendedPath(absolutePath: string): string {
969
+ // keeps the guard synchronous; the cost is one syscall per existing component,
970
+ // negligible at the tool-call boundary. Sync mirror of resolveRealIntendedPath
971
+ // in the guard plugin's non-workspace-write policy.
972
+ function realpathRealIntendedPath(absolutePath: string, realpath: (candidate: string) => string): string {
958
973
  const pending: string[] = []
959
974
  let current = absolutePath
960
975
  while (true) {
961
976
  try {
962
- return path.join(realpathSync.native(current), ...pending.reverse())
977
+ return path.join(realpath(current), ...pending.reverse())
963
978
  } catch (err) {
964
979
  if (!isNotFoundError(err)) throw err
965
980
  }
@@ -2,6 +2,8 @@ import type { DiscordBotClient } from 'agent-messenger/discordbot'
2
2
 
3
3
  import type { EditMessageCallback, EditMessageResult } from '@/channels/types'
4
4
 
5
+ import { describeError } from '../describe-error'
6
+
5
7
  export function createDiscordEditMessageCallback(deps: {
6
8
  client: Pick<DiscordBotClient, 'editMessage'>
7
9
  }): EditMessageCallback {
@@ -17,7 +19,7 @@ export function createDiscordEditMessageCallback(deps: {
17
19
  try {
18
20
  await deps.client.editMessage(channelId, req.messageId, req.text)
19
21
  } catch (err) {
20
- return { ok: false, error: describe(err), code: classifyEditError(err) }
22
+ return { ok: false, error: describeError(err), code: classifyEditError(err) }
21
23
  }
22
24
  return { ok: true }
23
25
  }
@@ -43,7 +45,3 @@ function classifyEditError(err: unknown): NonNullable<(EditMessageResult & { ok:
43
45
  return 'not-found'
44
46
  }
45
47
  }
46
-
47
- function describe(err: unknown): string {
48
- return err instanceof Error ? err.message : String(err)
49
- }
@@ -8,6 +8,8 @@ import type {
8
8
  RemoveReactionCallback,
9
9
  } from '@/channels/types'
10
10
 
11
+ import { describeError } from '../describe-error'
12
+
11
13
  // The reactable target on Discord: a message is addressed by its channel id
12
14
  // plus the message id. The classifier stamps this because both values are on
13
15
  // the gateway event but `chat`/`externalMessageId` are the only ones that
@@ -99,7 +101,7 @@ export function createDiscordReactionCallback(deps: {
99
101
  try {
100
102
  await deps.client.addReaction(target.channel, target.message, unicode)
101
103
  } catch (err) {
102
- return { ok: false, error: describe(err), code: classifyDiscordError(err) }
104
+ return { ok: false, error: describeError(err), code: classifyDiscordError(err) }
103
105
  }
104
106
  return { ok: true, reactionRef: encodeDiscordRemovalRef({ ...target, emoji: unicode }) }
105
107
  }
@@ -117,7 +119,7 @@ export function createDiscordRemoveReactionCallback(deps: {
117
119
  try {
118
120
  await deps.client.removeReaction(target.channel, target.message, target.emoji)
119
121
  } catch (err) {
120
- return { ok: false, error: describe(err), code: classifyDiscordError(err) }
122
+ return { ok: false, error: describeError(err), code: classifyDiscordError(err) }
121
123
  }
122
124
  return { ok: true }
123
125
  }
@@ -159,7 +161,3 @@ function parseRecord(value: string): Record<string, unknown> | null {
159
161
  ? (parsed as Record<string, unknown>)
160
162
  : null
161
163
  }
162
-
163
- function describe(err: unknown): string {
164
- return err instanceof Error ? err.message : String(err)
165
- }
@@ -2,6 +2,8 @@ import type { DiscordGatewayInteractionEvent } from 'agent-messenger/discordbot'
2
2
 
3
3
  import type { ChannelKey } from '@/channels/types'
4
4
 
5
+ import { describeError } from '../describe-error'
6
+
5
7
  const DISCORD_API_BASE = 'https://discord.com/api/v10'
6
8
 
7
9
  // CHAT_INPUT is the only Discord application-command type that maps to the
@@ -63,7 +65,7 @@ export async function registerCommands(args: RegisterCommandsArgs): Promise<Regi
63
65
  }
64
66
  return { ok: true }
65
67
  } catch (err) {
66
- return { ok: false, error: err instanceof Error ? err.message : String(err) }
68
+ return { ok: false, error: describeError(err) }
67
69
  }
68
70
  }
69
71