typeclaw 0.45.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/README.md +1 -1
  2. package/package.json +3 -2
  3. package/src/agent/git-nudge.ts +2 -1
  4. package/src/agent/index.ts +67 -25
  5. package/src/agent/live-subagents.ts +18 -0
  6. package/src/agent/loop-guard.ts +208 -10
  7. package/src/agent/multimodal/index.ts +1 -1
  8. package/src/agent/multimodal/look-at.ts +78 -44
  9. package/src/agent/multimodal/looker.ts +151 -39
  10. package/src/agent/network/response-body.ts +26 -0
  11. package/src/agent/network/safe-http.ts +198 -0
  12. package/src/agent/plugin-tools.ts +438 -162
  13. package/src/agent/provider-error.ts +62 -4
  14. package/src/agent/restart/index.ts +61 -40
  15. package/src/agent/restart-handoff/index.ts +73 -4
  16. package/src/agent/retry-same-ref.ts +66 -0
  17. package/src/agent/reviewer-bash-policy.ts +42 -1
  18. package/src/agent/session-origin.ts +2 -0
  19. package/src/agent/subagent-drain.ts +117 -7
  20. package/src/agent/subagents.ts +77 -18
  21. package/src/agent/throttle-circuit.ts +25 -5
  22. package/src/agent/tool-error-remediation.ts +72 -0
  23. package/src/agent/tool-file-safety.ts +1050 -0
  24. package/src/agent/tools/channel-fetch-attachment.ts +10 -3
  25. package/src/agent/tools/channel-reply.ts +15 -1
  26. package/src/agent/tools/channel-send.ts +17 -1
  27. package/src/agent/tools/ddg.ts +16 -2
  28. package/src/agent/tools/post-github-review.ts +199 -0
  29. package/src/agent/tools/spawn-subagent.ts +21 -18
  30. package/src/agent/tools/webfetch/fetch.ts +143 -183
  31. package/src/agent/tools/webfetch/tool.ts +2 -3
  32. package/src/agent/tools/websearch.ts +23 -2
  33. package/src/agent/tools-without-local-file-operands.ts +27 -0
  34. package/src/agent/turn-runner.ts +109 -15
  35. package/src/bundled-plugins/backup/index.ts +2 -1
  36. package/src/bundled-plugins/backup/runner.ts +2 -1
  37. package/src/bundled-plugins/doc-render/render.ts +93 -12
  38. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  39. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  40. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  41. package/src/bundled-plugins/github-cli-auth/index.ts +131 -135
  42. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  43. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  44. package/src/bundled-plugins/memory/README.md +23 -11
  45. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  46. package/src/bundled-plugins/memory/citations.ts +22 -9
  47. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  48. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  49. package/src/bundled-plugins/memory/index.ts +0 -4
  50. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  51. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  52. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  53. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  54. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  55. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  56. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  57. package/src/bundled-plugins/researcher/write-report.ts +6 -3
  58. package/src/bundled-plugins/reviewer/index.ts +2 -2
  59. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  60. package/src/bundled-plugins/reviewer/skills/code-review.ts +24 -9
  61. package/src/bundled-plugins/scout/scout.ts +8 -0
  62. package/src/bundled-plugins/security/index.ts +4 -4
  63. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  64. package/src/bundled-plugins/security/policies/private-surface-read.ts +220 -29
  65. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  66. package/src/bundled-plugins/security/policies/ssrf.ts +29 -9
  67. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  68. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  69. package/src/channels/adapters/discord-bot.ts +91 -10
  70. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  71. package/src/channels/adapters/discord-id.ts +4 -0
  72. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  73. package/src/channels/adapters/discord.ts +57 -7
  74. package/src/channels/adapters/github/auth-app.ts +41 -12
  75. package/src/channels/adapters/github/index.ts +23 -11
  76. package/src/channels/adapters/github/review-submitter.ts +302 -0
  77. package/src/channels/adapters/kakaotalk-channel-resolver.ts +12 -1
  78. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  79. package/src/channels/adapters/kakaotalk-typing.ts +127 -0
  80. package/src/channels/adapters/kakaotalk.ts +19 -0
  81. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  82. package/src/channels/adapters/slack-bot.ts +19 -8
  83. package/src/channels/adapters/slack-classify.ts +21 -2
  84. package/src/channels/adapters/slack.ts +59 -7
  85. package/src/channels/adapters/telegram-bot.ts +18 -5
  86. package/src/channels/adapters/webex-bot.ts +8 -3
  87. package/src/channels/adapters/webex.ts +8 -3
  88. package/src/channels/fetch-attachment.ts +43 -0
  89. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  90. package/src/channels/github-token-bridge.ts +10 -3
  91. package/src/channels/manager.ts +9 -0
  92. package/src/channels/router.ts +568 -12
  93. package/src/channels/types.ts +28 -1
  94. package/src/cli/channel.ts +1 -1
  95. package/src/cli/init.ts +1 -1
  96. package/src/cli/model.ts +57 -7
  97. package/src/compose/stop.ts +17 -5
  98. package/src/config/config.ts +6 -6
  99. package/src/config/models-mutation.ts +13 -1
  100. package/src/config/providers.ts +176 -0
  101. package/src/container/start.ts +49 -10
  102. package/src/doctor/checks.ts +3 -1
  103. package/src/doctor/commit.ts +2 -1
  104. package/src/doctor/file-ownership.ts +52 -0
  105. package/src/dreams/git.ts +2 -1
  106. package/src/git/hookless.ts +5 -0
  107. package/src/git/reconcile-ignored.ts +18 -5
  108. package/src/git/secret-history.ts +371 -0
  109. package/src/git/system-commit.ts +12 -6
  110. package/src/init/dockerfile.ts +86 -5
  111. package/src/init/index.ts +17 -5
  112. package/src/init/models-dev.ts +4 -0
  113. package/src/init/validate-api-key.ts +2 -0
  114. package/src/mcp/tools.ts +16 -3
  115. package/src/permissions/builtins.ts +3 -1
  116. package/src/plugin/context.ts +2 -0
  117. package/src/plugin/index.ts +1 -0
  118. package/src/plugin/manager.ts +4 -0
  119. package/src/plugin/types.ts +21 -0
  120. package/src/run/index.ts +40 -0
  121. package/src/run/llm-fetch-observer.ts +188 -13
  122. package/src/sandbox/build.ts +37 -15
  123. package/src/sandbox/canonical-secrets.ts +18 -0
  124. package/src/sandbox/env-exposure.ts +80 -0
  125. package/src/sandbox/errors.ts +13 -6
  126. package/src/sandbox/hidden-paths.ts +102 -44
  127. package/src/sandbox/index.ts +22 -4
  128. package/src/sandbox/package-install.ts +3 -27
  129. package/src/sandbox/policy.ts +11 -25
  130. package/src/sandbox/privileged-runtime.ts +255 -0
  131. package/src/sandbox/session-tmp.ts +8 -2
  132. package/src/sandbox/writable-zones.ts +204 -140
  133. package/src/secrets/index.ts +8 -0
  134. package/src/secrets/refresh-provider-oauth.ts +128 -0
  135. package/src/server/command-runner.ts +48 -4
  136. package/src/server/index.ts +4 -0
  137. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  138. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  139. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  140. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  141. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  142. package/src/skills/typeclaw-config/SKILL.md +5 -5
  143. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  144. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  145. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  146. package/src/skills/typeclaw-permissions/SKILL.md +19 -15
  147. package/typeclaw.schema.json +20 -0
@@ -1,7 +1,17 @@
1
- import { realpathSync } from 'node:fs'
1
+ import { readdirSync, realpathSync, statSync } from 'node:fs'
2
+ import { homedir } from 'node:os'
2
3
  import path from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
3
5
 
4
- import type { HiddenPaths } from '@/sandbox'
6
+ import { TOOLS_WITHOUT_LOCAL_FILE_OPERANDS } from '@/agent/tools-without-local-file-operands'
7
+ import type { ToolFileOperands } from '@/plugin'
8
+ import {
9
+ CANONICAL_AGENT_SECRET_DIRS,
10
+ CANONICAL_AGENT_SECRET_FILES,
11
+ CANONICAL_HOME_SECRET_DIRS,
12
+ CANONICAL_HOME_SECRET_FILES,
13
+ type HiddenPaths,
14
+ } from '@/sandbox'
5
15
 
6
16
  import type { SecurityBlock } from '../policy'
7
17
 
@@ -12,10 +22,19 @@ export const GUARD_PRIVATE_SURFACE_READ = 'privateSurfaceRead'
12
22
  // scanned, so a new file-reading tool — bundled or third-party — is covered
13
23
  // the day it ships without a whitelist edit. web_search/web_fetch take URLs, not
14
24
  // local paths, and the path-plausibility filter keeps their args from matching.
15
- const UNSCANNED_TOOLS = new Set(['bash'])
25
+ //
26
+ // TOOLS_WITHOUT_LOCAL_FILE_OPERANDS is the SAME set the file-operand scanner
27
+ // skips: first-party tools whose args are only remote ids/control tokens
28
+ // (channel/stream/subagent/role reads). Without this, an id equal to a working
29
+ // dir — channel_read({ workspace: "memory" }) — would resolve to /agent/memory
30
+ // and be wrongly blocked here even after the scanner cleared it. Sharing one set
31
+ // keeps both enforcement points agreeing on which tools read no local path.
32
+ const UNSCANNED_TOOLS = new Set(['bash', ...TOOLS_WITHOUT_LOCAL_FILE_OPERANDS])
33
+ const VIRTUAL_FILESYSTEM_ROOTS = ['/proc', '/sys', '/dev', '/run'] as const
16
34
 
17
35
  // The bash sandbox hides the role's private surface — the working DIRECTORIES
18
- // (workspace/, memory/, sessions/) and the secret FILES (.env, secrets.json) —
36
+ // (workspace/, memory/, sessions/), unconditional credential directories, and
37
+ // secret FILES (.env, secrets.json, auth.json) —
19
38
  // via bwrap masks, but every non-bash tool runs in the main process, outside
20
39
  // any sandbox. find_entry, look_at, and the channel attachment tools all read
21
40
  // files by a caller-supplied path, so without a guard a restricted role could
@@ -26,11 +45,11 @@ const UNSCANNED_TOOLS = new Set(['bash'])
26
45
  // It covers the full deny-list rather than delegating secret files to the
27
46
  // secretExfilRead guard: that guard only inspects read/grep/find/ls (not
28
47
  // edit/write/look_at/channel_send) and is acknowledgement-bypassable, so
29
- // delegating would leave .env/secrets.json reachable through the uncovered
48
+ // delegating would leave canonical credential files reachable through uncovered
30
49
  // tools — exactly the gap the bash masks close. secretExfilRead remains as
31
50
  // independent defense in depth for the four tools it does cover.
32
51
  //
33
- // Posture is FAIL-CLOSED for restricted roles: it does not whitelist a known
52
+ // Posture is FAIL-CLOSED: it does not whitelist a known
34
53
  // set of tools (that fails open the moment a new reader is added). It scans
35
54
  // every arg of every non-bash tool — recursively, since paths hide in nested
36
55
  // shapes like look_at's images[].path and channel_send's attachments[].path —
@@ -41,21 +60,38 @@ export function checkPrivateSurfaceReadGuard(options: {
41
60
  args: Record<string, unknown>
42
61
  agentDir: string
43
62
  hidden: HiddenPaths
63
+ fileOperands?: ToolFileOperands
44
64
  }): SecurityBlock | undefined {
45
- const { tool, args, agentDir, hidden } = options
65
+ const { tool, args, agentDir, hidden, fileOperands } = options
46
66
  if (UNSCANNED_TOOLS.has(tool)) return undefined
47
- const deniedDirs = hidden.dirs
48
- const deniedFiles = hidden.files
67
+ const deniedDirs = [
68
+ ...new Set([
69
+ ...hidden.dirs,
70
+ ...CANONICAL_AGENT_SECRET_DIRS.map((dir) => path.join(agentDir, dir)),
71
+ ...CANONICAL_HOME_SECRET_DIRS.map((dir) => path.join(homedir(), dir)),
72
+ ]),
73
+ ]
74
+ // Keep these runtime-owned credential stores independent of role-derived
75
+ // visibility so a privileged role or partially-wired caller cannot turn raw
76
+ // credentials into model context.
77
+ const deniedFiles = [
78
+ ...new Set([
79
+ ...hidden.files,
80
+ ...CANONICAL_AGENT_SECRET_FILES.map((file) => path.join(agentDir, file)),
81
+ ...CANONICAL_HOME_SECRET_FILES.map((file) => path.join(homedir(), file)),
82
+ ]),
83
+ ]
49
84
  if (deniedDirs.length === 0 && deniedFiles.length === 0) return undefined
50
85
 
51
- for (const candidate of collectPathCandidates(args, tool)) {
86
+ const nonFile = fileOperands?.nonFile === undefined ? undefined : new Set(fileOperands.nonFile)
87
+ for (const candidate of collectPathCandidates(args, tool, nonFile)) {
52
88
  const hit = matchHidden(candidate, agentDir, deniedDirs, deniedFiles)
53
89
  if (hit !== undefined) {
54
90
  return {
55
91
  block: true,
56
92
  reason: [
57
- `Guard \`${GUARD_PRIVATE_SURFACE_READ}\` blocked ${tool}: argument \`${candidate}\` resolves to ${hit}, which is hidden from the current role.`,
58
- 'The bash sandbox masks the same path; reaching it through another tool is the same disclosure.',
93
+ `Guard \`${GUARD_PRIVATE_SURFACE_READ}\` blocked ${tool}: argument \`${candidate}\` resolves to ${hit}, which is not available to LLM tools.`,
94
+ '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.',
59
95
  ].join(' '),
60
96
  }
61
97
  }
@@ -95,13 +131,12 @@ const NON_PATH_KEYS = new Set([
95
131
  'newText',
96
132
  // memory append tool: fragment topic is free text.
97
133
  'topic',
98
- // channel_send/channel_reply attachments[].filename and
99
- // channel_fetch_attachment.filename: display-only metadata (defaults to the
100
- // basename of the real `path`), never the file location the guard cares
101
- // about — `attachments[].path` carries that and is NOT exempted.
102
- 'filename',
103
134
  ])
104
135
 
136
+ const PATH_KEYS = /(?:^|[_-])(path|filepath|file)$/i
137
+ const CAMEL_PATH_KEYS = /(?:Path|Filepath|File)$/
138
+ const MAX_HARDLINK_IDENTITY_ENTRIES = 4_096
139
+
105
140
  // Keys that are free text in SPECIFIC tools but path-bearing in others, so a
106
141
  // global denylist would either over-block or open a bypass. Scoped per tool:
107
142
  // - grep.pattern : a regex/search string (e.g. "sessions"), NOT a path.
@@ -117,37 +152,73 @@ const NON_PATH_KEYS = new Set([
117
152
  // (or grep gaining a new key) scans everything.
118
153
  const FREE_TEXT_KEYS_BY_TOOL: Record<string, ReadonlySet<string>> = {
119
154
  grep: new Set(['pattern']),
155
+ // These channel tools use filename only as attachment display metadata. The
156
+ // corresponding attachments[].path is scanned independently where present.
157
+ channel_send: new Set(['filename']),
158
+ channel_reply: new Set(['filename']),
159
+ channel_fetch_attachment: new Set(['filename']),
160
+ }
161
+
162
+ // Trim before the `file:` test: an exempt prose key otherwise lets a
163
+ // leading-whitespace `file: file://…/memory` URI slip past the scan (the value
164
+ // is not path-shaped and `isFileUrl` misses it), reaching a fetcher that trims
165
+ // before parsing. Returns the trimmed URI so callers scan the real target.
166
+ function trimmedFileUri(value: string): string | undefined {
167
+ const trimmed = value.trim()
168
+ return trimmed.toLocaleLowerCase().startsWith('file:') ? trimmed : undefined
120
169
  }
121
170
 
122
171
  // Recursively collects strings that could be paths, skipping values under a
123
- // universally-free-text key or a tool-scoped free-text key. matchHidden then
172
+ // universally-free-text key or a tool-scoped free-text key. Explicit path-like
173
+ // keys still win, and file:// values are normalized before matching. matchHidden then
124
174
  // realpath-resolves each candidate and fires only on one landing inside a
125
175
  // hidden directory. Fail-closed by design: a bare path-bearing value equal to a
126
176
  // hidden dir name (e.g. `path: "memory"`) is still blocked. `underExempt`
127
177
  // propagates so nested values under an exempt key (e.g. a structured pattern)
128
178
  // stay exempt; top-level strings and array elements carry no key and are always
129
179
  // scanned (so attachments[].path is collected).
130
- function collectPathCandidates(value: unknown, tool: string): string[] {
180
+ //
181
+ // `nonFile` holds the tool author's declared control-token operand PATHS
182
+ // (`fileOperands.nonFile`, trusted metadata). A string at exactly one of those
183
+ // operand paths is skipped, mirroring the file-operand scanner so the two
184
+ // enforcement points agree — an id like `{ tenant: "memory" }` on a tool that
185
+ // declared `nonFile: ['tenant']` is not blocked here. Scoped by EXACT operand
186
+ // path (not key name), so an undeclared key still fails closed; `input`/
187
+ // `output`/`destructive` are deliberately NOT honored (a declared real-file path
188
+ // that resolves under a hidden dir must still block).
189
+ function collectPathCandidates(value: unknown, tool: string, nonFile?: ReadonlySet<string>): string[] {
131
190
  const out: string[] = []
132
- walk(value, out, tool, false)
191
+ walk(value, out, tool, false, nonFile, '')
133
192
  return out
134
193
  }
135
194
 
136
- function walk(value: unknown, out: string[], tool: string, underExempt: boolean): void {
195
+ function walk(
196
+ value: unknown,
197
+ out: string[],
198
+ tool: string,
199
+ underExempt: boolean,
200
+ nonFile: ReadonlySet<string> | undefined,
201
+ operandPath: string,
202
+ key?: string,
203
+ ): void {
137
204
  if (typeof value === 'string') {
138
- if (underExempt) return
139
- out.push(value)
205
+ if (nonFile?.has(operandPath) === true) return
206
+ const isFileUrl = trimmedFileUri(value) !== undefined
207
+ if (underExempt && !isPathKey(key) && !isFileUrl) return
208
+ const normalized = normalizeCandidate(value)
209
+ if (normalized !== undefined) out.push(normalized)
140
210
  return
141
211
  }
142
212
  if (Array.isArray(value)) {
143
- for (const item of value) walk(item, out, tool, underExempt)
213
+ for (const item of value) walk(item, out, tool, underExempt, nonFile, operandPath, key)
144
214
  return
145
215
  }
146
216
  if (value !== null && typeof value === 'object') {
147
217
  const toolFreeText = FREE_TEXT_KEYS_BY_TOOL[tool]
148
- for (const [key, item] of Object.entries(value)) {
149
- const keyIsExempt = NON_PATH_KEYS.has(key) || (toolFreeText?.has(key) ?? false)
150
- walk(item, out, tool, underExempt || keyIsExempt)
218
+ for (const [childKey, item] of Object.entries(value)) {
219
+ const keyIsExempt = NON_PATH_KEYS.has(childKey) || (toolFreeText?.has(childKey) ?? false)
220
+ const childPath = operandPath === '' ? childKey : `${operandPath}.${childKey}`
221
+ walk(item, out, tool, underExempt || keyIsExempt, nonFile, childPath, childKey)
151
222
  }
152
223
  }
153
224
  }
@@ -172,9 +243,14 @@ function matchHidden(
172
243
  deniedDirs: string[],
173
244
  deniedFiles: string[],
174
245
  ): string | undefined {
175
- const resolved = realpathRealIntendedPath(path.resolve(agentDir, candidate))
246
+ const lexicalHit = matchLexicallyDenied(candidate, agentDir, deniedDirs, deniedFiles)
247
+ if (lexicalHit !== undefined) return lexicalHit
248
+ const lexical = path.resolve(agentDir, candidate)
249
+ const resolved = realpathRealIntendedPath(lexical)
250
+ const virtualRoot = virtualFilesystemRoot(lexical) ?? virtualFilesystemRoot(resolved)
251
+ if (virtualRoot !== undefined) return `${virtualRoot}, a virtual or process-backed filesystem`
176
252
  for (const file of deniedFiles) {
177
- if (resolved === realpathRealIntendedPath(file)) return file
253
+ if (resolved === realpathRealIntendedPath(file) || hasSameFileIdentity(resolved, file)) return file
178
254
  }
179
255
  for (const dir of deniedDirs) {
180
256
  const realDir = realpathRealIntendedPath(dir)
@@ -183,9 +259,124 @@ function matchHidden(
183
259
  // "\"-joined paths a win32 test runner produces.
184
260
  if (resolved === realDir || resolved.startsWith(`${realDir}${path.sep}`)) return dir
185
261
  }
262
+ if (hasMultipleLinks(resolved)) {
263
+ const alias = findDeniedHardlinkAlias(resolved, deniedDirs)
264
+ if (alias !== undefined) return alias
265
+ }
266
+ return undefined
267
+ }
268
+
269
+ function matchLexicallyDenied(
270
+ candidate: string,
271
+ agentDir: string,
272
+ deniedDirs: readonly string[],
273
+ deniedFiles: readonly string[],
274
+ ): string | undefined {
275
+ const absolute = portableAbsolute(agentDir, candidate)
276
+ const virtualRoot = virtualFilesystemRoot(absolute)
277
+ if (virtualRoot !== undefined) return `${virtualRoot}, a virtual or process-backed filesystem`
278
+ for (const file of deniedFiles) {
279
+ if (portableEqual(absolute, portableAbsolute(agentDir, file))) return file
280
+ }
281
+ for (const dir of deniedDirs) {
282
+ const root = portableAbsolute(agentDir, dir)
283
+ if (portableEqual(absolute, root) || portableInside(root, absolute)) return dir
284
+ }
285
+ return undefined
286
+ }
287
+
288
+ function portableAbsolute(agentDir: string, candidate: string): string {
289
+ const normalized = candidate.replaceAll('\\', '/')
290
+ if (/^[A-Za-z]:\//.test(normalized) || normalized.startsWith('//')) return path.posix.normalize(normalized)
291
+ if (normalized.startsWith('/')) return path.posix.normalize(normalized)
292
+ return path.posix.resolve(agentDir.replaceAll('\\', '/'), normalized)
293
+ }
294
+
295
+ function portableEqual(left: string, right: string): boolean {
296
+ const windows =
297
+ /^[A-Za-z]:\//.test(left) || left.startsWith('//') || /^[A-Za-z]:\//.test(right) || right.startsWith('//')
298
+ return windows ? left.toLocaleLowerCase() === right.toLocaleLowerCase() : left === right
299
+ }
300
+
301
+ function portableInside(parent: string, child: string): boolean {
302
+ const normalizedParent = parent.endsWith('/') ? parent : `${parent}/`
303
+ return portableEqual(child.slice(0, normalizedParent.length), normalizedParent)
304
+ }
305
+
306
+ function virtualFilesystemRoot(candidate: string): string | undefined {
307
+ const normalized = candidate.replaceAll('\\', '/')
308
+ for (const root of VIRTUAL_FILESYSTEM_ROOTS) {
309
+ if (normalized === root || normalized.startsWith(`${root}/`)) return root
310
+ }
311
+ return undefined
312
+ }
313
+
314
+ function hasMultipleLinks(candidate: string): boolean {
315
+ try {
316
+ const stats = statSync(candidate)
317
+ return stats.isFile() && stats.nlink > 1
318
+ } catch {
319
+ return false
320
+ }
321
+ }
322
+
323
+ function findDeniedHardlinkAlias(candidate: string, deniedDirs: readonly string[]): string | undefined {
324
+ let remaining = MAX_HARDLINK_IDENTITY_ENTRIES
325
+ for (const deniedDir of deniedDirs) {
326
+ const pending = [realpathRealIntendedPath(deniedDir)]
327
+ while (pending.length > 0) {
328
+ const current = pending.pop()
329
+ if (current === undefined) break
330
+ let entries
331
+ try {
332
+ entries = readdirSync(current, { withFileTypes: true })
333
+ } catch {
334
+ continue
335
+ }
336
+ for (const entry of entries) {
337
+ const entryPath = path.join(current, entry.name)
338
+ if (entry.isDirectory()) pending.push(entryPath)
339
+ else if (entry.isFile()) {
340
+ if (remaining-- <= 0) return undefined
341
+ if (hasSameFileIdentity(candidate, entryPath)) return deniedDir
342
+ }
343
+ }
344
+ }
345
+ }
186
346
  return undefined
187
347
  }
188
348
 
349
+ function isPathKey(key: string | undefined): boolean {
350
+ return key !== undefined && (PATH_KEYS.test(key) || CAMEL_PATH_KEYS.test(key))
351
+ }
352
+
353
+ function normalizeCandidate(value: string): string | undefined {
354
+ const uri = trimmedFileUri(value)
355
+ if (uri === undefined) return value
356
+ try {
357
+ const url = new URL(uri)
358
+ const pathname = decodeURIComponent(url.pathname)
359
+ if (url.hostname !== '') return `//${url.hostname}${pathname}`
360
+ if (/^\/[A-Za-z]:\//.test(pathname)) return pathname.slice(1)
361
+ // Keep synthetic POSIX container paths platform-independent. fileURLToPath
362
+ // would reinterpret file:///agent/... through the Windows host grammar.
363
+ if (pathname.startsWith('/agent/') || pathname === '/agent') return pathname
364
+ return fileURLToPath(uri)
365
+ } catch {
366
+ return value
367
+ }
368
+ }
369
+
370
+ function hasSameFileIdentity(candidate: string, deniedFile: string): boolean {
371
+ try {
372
+ const candidateStats = statSync(candidate)
373
+ const deniedStats = statSync(deniedFile)
374
+ return candidateStats.dev === deniedStats.dev && candidateStats.ino === deniedStats.ino
375
+ } catch {
376
+ return false
377
+ }
378
+ }
379
+
189
380
  // Resolves symlinks on the longest existing prefix of an absolute path, then
190
381
  // re-appends the non-existent tail. A bare realpathSync throws on a path that
191
382
  // does not exist yet (a write target, or a read of a not-yet-created file), so
@@ -22,6 +22,7 @@ const SENSITIVE_BASENAMES = new Set([
22
22
  'service-account.json',
23
23
  'gha-creds.json',
24
24
  'token.json',
25
+ 'secrets.json',
25
26
  ])
26
27
 
27
28
  const SENSITIVE_BASENAME_PATTERNS: ReadonlyArray<RegExp> = [
@@ -1,3 +1,5 @@
1
+ import { isIP } from 'node:net'
2
+
1
3
  import type { SecuritySeverity } from '../permissions'
2
4
  import { ACKNOWLEDGE_GUARDS, type SecurityBlock, isGuardAcknowledged } from '../policy'
3
5
 
@@ -84,20 +86,37 @@ export function classifyUrl(rawUrl: string): SsrfClassification {
84
86
  }
85
87
  }
86
88
 
89
+ const addressClassification = classifyIpAddress(decoded)
90
+ if (addressClassification.blocked) return addressClassification
91
+
92
+ return { blocked: false }
93
+ }
94
+
95
+ export function classifyIpAddress(address: string): SsrfClassification {
96
+ const decoded = decodeBracketedIpv6(address.toLowerCase().split('%')[0] ?? '')
87
97
  const ipv4 = parseIpv4Loose(decoded)
88
98
  if (ipv4) {
89
99
  const cls = classifyIpv4(ipv4)
90
100
  if (cls) return { blocked: true, category: cls.category, reason: cls.reason }
101
+ return { blocked: false }
91
102
  }
92
-
93
- if (looksLikeIpv6(decoded)) {
94
- const cls = classifyIpv6(decoded)
103
+ const normalizedIpv6 = normalizeIpv6(decoded)
104
+ if (normalizedIpv6 !== undefined) {
105
+ const cls = classifyIpv6(normalizedIpv6)
95
106
  if (cls) return { blocked: true, category: cls.category, reason: cls.reason }
96
107
  }
97
-
98
108
  return { blocked: false }
99
109
  }
100
110
 
111
+ function normalizeIpv6(address: string): string | undefined {
112
+ if (isIP(address) !== 6) return undefined
113
+ try {
114
+ return decodeBracketedIpv6(new URL(`http://[${address}]/`).hostname).toLowerCase()
115
+ } catch {
116
+ return undefined
117
+ }
118
+ }
119
+
101
120
  export function checkSsrfGuard(options: { tool: string; args: Record<string, unknown> }): SecurityBlock | undefined {
102
121
  const { tool, args } = options
103
122
  if (tool !== 'web_fetch') return undefined
@@ -162,21 +181,22 @@ function classifyIpv4(
162
181
  return { category: 'cloud_metadata', reason: `link-local / cloud metadata 169.254.0.0/16 (${ip.join('.')})` }
163
182
  if (a === 100 && b >= 64 && b <= 127)
164
183
  return { category: 'shared_cgnat', reason: `CGNAT 100.64.0.0/10 (${ip.join('.')})` }
184
+ if (a === 198 && (b === 18 || b === 19))
185
+ return { category: 'private_ipv4', reason: `benchmarking-only 198.18.0.0/15 (${ip.join('.')})` }
165
186
  if (a === 0) return { category: 'unspecified', reason: `unspecified 0.0.0.0/8 (${ip.join('.')})` }
166
187
  if (a >= 224) return { category: 'private_ipv4', reason: `multicast/reserved (${ip.join('.')})` }
167
188
  return undefined
168
189
  }
169
190
 
170
- function looksLikeIpv6(host: string): boolean {
171
- return host.includes(':') && /^[0-9a-f:]+$/i.test(host)
172
- }
173
-
174
191
  function classifyIpv6(host: string): { category: SsrfClassification['category']; reason: string } | undefined {
175
192
  const lower = host.toLowerCase()
176
193
  if (lower === '::1' || lower === '0:0:0:0:0:0:0:1') return { category: 'loopback', reason: 'IPv6 loopback ::1' }
177
194
  if (lower === '::' || lower === '0:0:0:0:0:0:0:0') return { category: 'unspecified', reason: 'IPv6 unspecified ::' }
178
- if (lower.startsWith('fe80:') || lower.startsWith('fe80::'))
195
+ const firstHextet = Number.parseInt(lower.split(':')[0] ?? '', 16)
196
+ if (Number.isFinite(firstHextet) && firstHextet >= 0xfe80 && firstHextet <= 0xfebf)
179
197
  return { category: 'link_local', reason: 'IPv6 link-local fe80::/10' }
198
+ if (Number.isFinite(firstHextet) && firstHextet >= 0xfec0 && firstHextet <= 0xfeff)
199
+ return { category: 'ipv6_internal', reason: 'IPv6 site-local fec0::/10' }
180
200
  if (lower.startsWith('fc') || lower.startsWith('fd'))
181
201
  return { category: 'ipv6_internal', reason: 'IPv6 unique-local fc00::/7' }
182
202
  if (lower.startsWith('ff')) return { category: 'ipv6_internal', reason: 'IPv6 multicast ff00::/8' }
@@ -1,5 +1,8 @@
1
1
  import type { ChannelKey, ChannelNameResolver, ResolvedChannelNames } from '@/channels/types'
2
2
 
3
+ import { isDiscordSnowflake } from './discord-id'
4
+ import { DiscordResolverCache } from './discord-resolver-cache'
5
+
3
6
  const DISCORD_API_BASE = 'https://discord.com/api/v10'
4
7
  const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000
5
8
 
@@ -7,29 +10,34 @@ export type DiscordChannelResolverOptions = {
7
10
  token: string
8
11
  now?: () => number
9
12
  ttlMs?: number
13
+ maxCacheEntries?: number
14
+ fetchImpl?: typeof fetch
10
15
  }
11
16
 
12
- type CacheEntry<T> = { value: T; expiresAt: number }
13
-
14
17
  type DiscordChannel = { id?: string; name?: string }
15
18
  type DiscordGuild = { id?: string; name?: string }
16
19
 
17
20
  export function createDiscordChannelResolver(options: DiscordChannelResolverOptions): ChannelNameResolver {
18
21
  const now = options.now ?? Date.now
19
22
  const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS
23
+ const fetchImpl = options.fetchImpl ?? fetch
20
24
 
21
- const channelCache = new Map<string, CacheEntry<string>>()
22
- const guildCache = new Map<string, CacheEntry<string>>()
25
+ const channelCache = new DiscordResolverCache<string>(options.maxCacheEntries)
26
+ const guildCache = new DiscordResolverCache<string>(options.maxCacheEntries)
23
27
 
24
28
  const fetchCached = async <T>(
25
- cache: Map<string, CacheEntry<T>>,
29
+ cache: DiscordResolverCache<T>,
26
30
  key: string,
27
31
  fetcher: () => Promise<T | null>,
28
32
  ): Promise<T | null> => {
29
- const cached = cache.get(key)
30
- if (cached && cached.expiresAt > now()) return cached.value
33
+ const currentTime = now()
34
+ const cached = cache.get(key, currentTime)
35
+ if (cached !== undefined) return cached
31
36
  const value = await fetcher()
32
- if (value !== null) cache.set(key, { value, expiresAt: now() + ttlMs })
37
+ if (value !== null) {
38
+ const fetchedAt = now()
39
+ cache.set(key, value, fetchedAt + ttlMs, fetchedAt)
40
+ }
33
41
  return value
34
42
  }
35
43
 
@@ -37,8 +45,12 @@ export function createDiscordChannelResolver(options: DiscordChannelResolverOpti
37
45
  if (key.workspace === '@dm') return {}
38
46
 
39
47
  const [chatName, workspaceName] = await Promise.all([
40
- fetchCached(channelCache, key.chat, () => fetchChannelName(key.chat, options.token)),
41
- fetchCached(guildCache, key.workspace, () => fetchGuildName(key.workspace, options.token)),
48
+ isDiscordSnowflake(key.chat)
49
+ ? fetchCached(channelCache, key.chat, () => fetchChannelName(key.chat, options.token, fetchImpl))
50
+ : Promise.resolve(null),
51
+ isDiscordSnowflake(key.workspace)
52
+ ? fetchCached(guildCache, key.workspace, () => fetchGuildName(key.workspace, options.token, fetchImpl))
53
+ : Promise.resolve(null),
42
54
  ])
43
55
 
44
56
  const result: ResolvedChannelNames = {}
@@ -48,9 +60,9 @@ export function createDiscordChannelResolver(options: DiscordChannelResolverOpti
48
60
  }
49
61
  }
50
62
 
51
- async function fetchChannelName(channelId: string, token: string): Promise<string | null> {
63
+ async function fetchChannelName(channelId: string, token: string, fetchImpl: typeof fetch): Promise<string | null> {
52
64
  try {
53
- const response = await fetch(`${DISCORD_API_BASE}/channels/${encodeURIComponent(channelId)}`, {
65
+ const response = await fetchImpl(`${DISCORD_API_BASE}/channels/${encodeURIComponent(channelId)}`, {
54
66
  headers: { Authorization: `Bot ${token}` },
55
67
  })
56
68
  if (!response.ok) return null
@@ -62,9 +74,9 @@ async function fetchChannelName(channelId: string, token: string): Promise<strin
62
74
  }
63
75
  }
64
76
 
65
- async function fetchGuildName(guildId: string, token: string): Promise<string | null> {
77
+ async function fetchGuildName(guildId: string, token: string, fetchImpl: typeof fetch): Promise<string | null> {
66
78
  try {
67
- const response = await fetch(`${DISCORD_API_BASE}/guilds/${encodeURIComponent(guildId)}`, {
79
+ const response = await fetchImpl(`${DISCORD_API_BASE}/guilds/${encodeURIComponent(guildId)}`, {
68
80
  headers: { Authorization: `Bot ${token}` },
69
81
  })
70
82
  if (!response.ok) return null
@@ -1,5 +1,8 @@
1
1
  import type { InboundMessage } from '@/channels/types'
2
2
 
3
+ import { isDiscordSnowflake } from './discord-id'
4
+ import { DiscordResolverCache } from './discord-resolver-cache'
5
+
3
6
  const DISCORD_API_BASE = 'https://discord.com/api/v10'
4
7
  const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000
5
8
 
@@ -11,7 +14,7 @@ const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000
11
14
  // carries no thread/parent signal.
12
15
  const DISCORD_THREAD_CHANNEL_TYPES: ReadonlySet<number> = new Set([10, 11, 12])
13
16
 
14
- export type DiscordChannelMeta = { type?: number; parent_id?: string }
17
+ export type DiscordChannelMeta = { type?: number; parent_id?: string | null }
15
18
 
16
19
  // The lookup has THREE outcomes, and the failure case must not be conflated
17
20
  // with a confirmed non-thread channel:
@@ -25,6 +28,12 @@ export type DiscordThreadRoomResolverOptions = {
25
28
  fetchImpl?: typeof fetch
26
29
  now?: () => number
27
30
  ttlMs?: number
31
+ maxCacheEntries?: number
32
+ }
33
+
34
+ export type DiscordThreadRoomStatus = { room: InboundMessage['room']; parentChecked: boolean }
35
+ export type DiscordThreadRoomResolver = ((channelId: string) => Promise<InboundMessage['room']>) & {
36
+ resolveStatus(channelId: string): Promise<DiscordThreadRoomStatus>
28
37
  }
29
38
 
30
39
  // Maps a lookup outcome to the room signal. A confirmed thread carries its
@@ -37,37 +46,60 @@ export type DiscordThreadRoomResolverOptions = {
37
46
  export function discordThreadRoom(meta: ChannelMetaLookup): InboundMessage['room'] {
38
47
  if (meta === 'unknown') return { kind: 'thread' }
39
48
  if (meta.type === undefined || !DISCORD_THREAD_CHANNEL_TYPES.has(meta.type)) return undefined
40
- return meta.parent_id !== undefined ? { kind: 'thread', parentChat: meta.parent_id } : { kind: 'thread' }
49
+ return meta.parent_id != null ? { kind: 'thread', parentChat: meta.parent_id } : { kind: 'thread' }
41
50
  }
42
51
 
43
- export function createDiscordThreadRoomResolver(
44
- options: DiscordThreadRoomResolverOptions,
45
- ): (channelId: string) => Promise<InboundMessage['room']> {
52
+ export function createDiscordThreadRoomResolver(options: DiscordThreadRoomResolverOptions): DiscordThreadRoomResolver {
46
53
  const fetchImpl = options.fetchImpl ?? fetch
47
54
  const now = options.now ?? Date.now
48
55
  const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS
49
- const cache = new Map<string, { value: DiscordChannelMeta; expiresAt: number }>()
56
+ const cache = new DiscordResolverCache<DiscordChannelMeta>(options.maxCacheEntries)
50
57
 
51
- return async (channelId: string): Promise<InboundMessage['room']> => {
52
- const cached = cache.get(channelId)
53
- if (cached !== undefined && cached.expiresAt > now()) return discordThreadRoom(cached.value)
58
+ const resolve = (async (channelId: string): Promise<InboundMessage['room']> =>
59
+ (await resolve.resolveStatus(channelId)).room) as DiscordThreadRoomResolver
60
+
61
+ resolve.resolveStatus = async (channelId: string): Promise<DiscordThreadRoomStatus> => {
62
+ if (!isDiscordSnowflake(channelId)) return { room: { kind: 'thread' }, parentChecked: false }
63
+ const currentTime = now()
64
+ const cached = cache.get(channelId, currentTime)
65
+ if (cached !== undefined) {
66
+ return { room: discordThreadRoom(cached), parentChecked: true }
67
+ }
54
68
  // Only CONFIRMED metadata is cached. A failed lookup ('unknown') is not
55
69
  // cached, so the next message on this channel retries rather than pinning
56
70
  // the fail-closed state for the whole TTL.
57
71
  const meta = await fetchChannelMeta(channelId)
58
- if (meta !== 'unknown') cache.set(channelId, { value: meta, expiresAt: now() + ttlMs })
59
- return discordThreadRoom(meta)
72
+ const room = discordThreadRoom(meta)
73
+ const parentChecked = meta !== 'unknown' && (room?.kind !== 'thread' || room.parentChat != null)
74
+ if (meta !== 'unknown' && parentChecked) {
75
+ const fetchedAt = now()
76
+ cache.set(channelId, meta, fetchedAt + ttlMs, fetchedAt)
77
+ }
78
+ return { room, parentChecked }
60
79
  }
61
80
 
81
+ return resolve
82
+
62
83
  async function fetchChannelMeta(channelId: string): Promise<ChannelMetaLookup> {
63
84
  try {
64
85
  const response = await fetchImpl(`${DISCORD_API_BASE}/channels/${encodeURIComponent(channelId)}`, {
65
86
  headers: { Authorization: `Bot ${options.token}` },
66
87
  })
67
88
  if (!response.ok) return 'unknown'
68
- return (await response.json()) as DiscordChannelMeta
89
+ const body: unknown = await response.json()
90
+ if (!validChannelMetadata(body)) return 'unknown'
91
+ return body
69
92
  } catch {
70
93
  return 'unknown'
71
94
  }
72
95
  }
73
96
  }
97
+
98
+ function validChannelMetadata(value: unknown): value is DiscordChannelMeta & { type: number } {
99
+ if (typeof value !== 'object' || value === null || !('type' in value)) return false
100
+ if (typeof value.type !== 'number' || !Number.isInteger(value.type) || value.type < 0) return false
101
+ if ('parent_id' in value && value.parent_id != null) {
102
+ if (typeof value.parent_id !== 'string' || !isDiscordSnowflake(value.parent_id)) return false
103
+ }
104
+ return true
105
+ }