@namzu/sdk 71.0.0 → 71.1.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 (115) hide show
  1. package/CHANGELOG.md +100 -0
  2. package/dist/authorization/readonly-commands.d.ts +9 -1
  3. package/dist/authorization/readonly-commands.d.ts.map +1 -1
  4. package/dist/authorization/readonly-commands.js +70 -4
  5. package/dist/authorization/readonly-commands.js.map +1 -1
  6. package/dist/authorization/shell-paths.d.ts.map +1 -1
  7. package/dist/authorization/shell-paths.js +68 -16
  8. package/dist/authorization/shell-paths.js.map +1 -1
  9. package/dist/compaction/model-summary.d.ts.map +1 -1
  10. package/dist/compaction/model-summary.js +44 -5
  11. package/dist/compaction/model-summary.js.map +1 -1
  12. package/dist/config/registry.d.ts +2 -0
  13. package/dist/config/registry.d.ts.map +1 -1
  14. package/dist/config/registry.js +76 -5
  15. package/dist/config/registry.js.map +1 -1
  16. package/dist/connector/mcp/adapter.d.ts +8 -0
  17. package/dist/connector/mcp/adapter.d.ts.map +1 -1
  18. package/dist/connector/mcp/adapter.js +131 -1
  19. package/dist/connector/mcp/adapter.js.map +1 -1
  20. package/dist/connector/mcp/stdio.d.ts +12 -0
  21. package/dist/connector/mcp/stdio.d.ts.map +1 -1
  22. package/dist/connector/mcp/stdio.js +49 -5
  23. package/dist/connector/mcp/stdio.js.map +1 -1
  24. package/dist/constants/mcp/index.d.ts +29 -0
  25. package/dist/constants/mcp/index.d.ts.map +1 -1
  26. package/dist/constants/mcp/index.js +29 -0
  27. package/dist/constants/mcp/index.js.map +1 -1
  28. package/dist/manager/agent/lifecycle.d.ts +18 -1
  29. package/dist/manager/agent/lifecycle.d.ts.map +1 -1
  30. package/dist/manager/agent/lifecycle.js +52 -7
  31. package/dist/manager/agent/lifecycle.js.map +1 -1
  32. package/dist/plugin/index.d.ts +1 -1
  33. package/dist/plugin/index.d.ts.map +1 -1
  34. package/dist/plugin/index.js.map +1 -1
  35. package/dist/plugin/shell-hook.d.ts +44 -2
  36. package/dist/plugin/shell-hook.d.ts.map +1 -1
  37. package/dist/plugin/shell-hook.js +74 -5
  38. package/dist/plugin/shell-hook.js.map +1 -1
  39. package/dist/public-runtime.d.ts +2 -2
  40. package/dist/public-runtime.d.ts.map +1 -1
  41. package/dist/public-runtime.js +1 -1
  42. package/dist/public-runtime.js.map +1 -1
  43. package/dist/public-types.d.ts +2 -2
  44. package/dist/public-types.d.ts.map +1 -1
  45. package/dist/runtime/query/path-escalation.d.ts.map +1 -1
  46. package/dist/runtime/query/path-escalation.js +90 -17
  47. package/dist/runtime/query/path-escalation.js.map +1 -1
  48. package/dist/runtime/query/steering.d.ts +15 -0
  49. package/dist/runtime/query/steering.d.ts.map +1 -1
  50. package/dist/runtime/query/steering.js +27 -3
  51. package/dist/runtime/query/steering.js.map +1 -1
  52. package/dist/session/workspace/driver.d.ts +12 -0
  53. package/dist/session/workspace/driver.d.ts.map +1 -1
  54. package/dist/session/workspace/git-worktree.d.ts +16 -0
  55. package/dist/session/workspace/git-worktree.d.ts.map +1 -1
  56. package/dist/session/workspace/git-worktree.js +35 -0
  57. package/dist/session/workspace/git-worktree.js.map +1 -1
  58. package/dist/session/workspace/holds.d.ts +78 -0
  59. package/dist/session/workspace/holds.d.ts.map +1 -0
  60. package/dist/session/workspace/holds.js +150 -0
  61. package/dist/session/workspace/holds.js.map +1 -0
  62. package/dist/session/workspace/index.d.ts +3 -1
  63. package/dist/session/workspace/index.d.ts.map +1 -1
  64. package/dist/session/workspace/index.js +2 -1
  65. package/dist/session/workspace/index.js.map +1 -1
  66. package/dist/store/config/index.d.ts +3 -0
  67. package/dist/store/config/index.d.ts.map +1 -1
  68. package/dist/store/config/index.js +3 -0
  69. package/dist/store/config/index.js.map +1 -1
  70. package/dist/store/session-index/index.d.ts +5 -0
  71. package/dist/store/session-index/index.d.ts.map +1 -1
  72. package/dist/store/session-index/index.js +5 -1
  73. package/dist/store/session-index/index.js.map +1 -1
  74. package/dist/store/session-index/rebuild.d.ts +18 -0
  75. package/dist/store/session-index/rebuild.d.ts.map +1 -1
  76. package/dist/store/session-index/rebuild.js +79 -5
  77. package/dist/store/session-index/rebuild.js.map +1 -1
  78. package/dist/store/session-index/sqlite.d.ts +8 -0
  79. package/dist/store/session-index/sqlite.d.ts.map +1 -1
  80. package/dist/store/session-index/sqlite.js +23 -1
  81. package/dist/store/session-index/sqlite.js.map +1 -1
  82. package/dist/tools/builtins/grep.d.ts.map +1 -1
  83. package/dist/tools/builtins/grep.js +57 -0
  84. package/dist/tools/builtins/grep.js.map +1 -1
  85. package/dist/tools/builtins/lsp.d.ts.map +1 -1
  86. package/dist/tools/builtins/lsp.js +41 -4
  87. package/dist/tools/builtins/lsp.js.map +1 -1
  88. package/dist/types/code-navigation/index.d.ts +34 -4
  89. package/dist/types/code-navigation/index.d.ts.map +1 -1
  90. package/package.json +1 -1
  91. package/src/authorization/readonly-commands.ts +72 -4
  92. package/src/authorization/shell-paths.ts +75 -18
  93. package/src/compaction/model-summary.ts +45 -5
  94. package/src/config/registry.ts +87 -5
  95. package/src/connector/mcp/adapter.ts +137 -1
  96. package/src/connector/mcp/stdio.ts +56 -5
  97. package/src/constants/mcp/index.ts +31 -0
  98. package/src/manager/agent/lifecycle.ts +57 -12
  99. package/src/plugin/index.ts +3 -0
  100. package/src/plugin/shell-hook.ts +131 -6
  101. package/src/public-runtime.ts +5 -0
  102. package/src/public-types.ts +7 -0
  103. package/src/runtime/query/path-escalation.ts +102 -16
  104. package/src/runtime/query/steering.ts +38 -3
  105. package/src/session/workspace/driver.ts +12 -0
  106. package/src/session/workspace/git-worktree.ts +49 -0
  107. package/src/session/workspace/holds.ts +201 -0
  108. package/src/session/workspace/index.ts +13 -1
  109. package/src/store/config/index.ts +6 -0
  110. package/src/store/session-index/index.ts +10 -1
  111. package/src/store/session-index/rebuild.ts +81 -5
  112. package/src/store/session-index/sqlite.ts +30 -1
  113. package/src/tools/builtins/grep.ts +52 -0
  114. package/src/tools/builtins/lsp.ts +47 -4
  115. package/src/types/code-navigation/index.ts +48 -4
@@ -8,7 +8,11 @@
8
8
  * - every command of the line is on the list, the line parses completely, and
9
9
  * nothing in it is read at run time: no `$var` outside single quotes, no
10
10
  * substitution, no subshell or group, no background `&`, no here-document,
11
- * no unquoted glob except for a short set of commands that only list or show;
11
+ * no unquoted glob except for a short set of commands that only list or show.
12
+ * `$PWD` and `${PWD}` are the one expansion the line may carry, because the
13
+ * directory the line starts in is fixed before it runs: they are read as the
14
+ * start directory spelled out, so `grep -r foo "$PWD/src"` is decided like
15
+ * `grep -r foo /the/start/dir/src`;
12
16
  * - a redirection is allowed only to `/dev/null`, as a descriptor copy, or as
13
17
  * an input from a plain file; a `~user` path and a UNC path are refused;
14
18
  * - a leading assignment is allowed only for a variable that cannot change
@@ -32,6 +36,10 @@
32
36
  * are in no table, so they are refused; a repository argument naming a
33
37
  * host, a URL or `user@host` is refused.
34
38
  *
39
+ * The expansion may not name another variable: `$PWDfoo` is a variable of its
40
+ * own, `${PWD:-.}` decides its value at run time, and a `~` or a brace list
41
+ * beside it is refused with every other expansion.
42
+ *
35
43
  * Not ported, and so never read-only here: `ps`, `lsof`, `ss`, `date`,
36
44
  * `man`, `xargs`, `fd`, `docker logs|inspect`, `printf`, `[[`, `test`
37
45
  * and the shell builtins other than `cd`.
@@ -280,6 +288,62 @@ function hasDynamicSyntax(line: string): boolean {
280
288
  return false
281
289
  }
282
290
 
291
+ /**
292
+ * The working-directory variable: `$PWD`, or `${PWD}` written out. It is the
293
+ * directory the line starts in, which the shell fixes before the line runs,
294
+ * so a word carrying it is as literal as the same word with the path typed
295
+ * out. Only this exact spelling matches: `$PWDfoo` is another variable and
296
+ * `${PWD:-x}` decides its own value.
297
+ */
298
+ const WORKING_DIRECTORY_VARIABLE = /^(?:\$PWD(?![A-Za-z0-9_])|\$\{PWD\})/
299
+
300
+ /** The directory a `$PWD` word is read as, so that both spellings match. */
301
+ const WORKING_DIRECTORY_PATH = '/namzu-start-directory'
302
+
303
+ /**
304
+ * The line with every `$PWD`/`${PWD}` the shell would expand replaced by the
305
+ * literal start directory, so the rest of the check sees the spelling with the
306
+ * path typed out. A `$` inside single quotes is text the shell passes on, and
307
+ * an escaped `\$PWD` is likewise passed on, so neither is touched.
308
+ */
309
+ function spellOutWorkingDirectory(line: string): string {
310
+ let out = ''
311
+ let single = false
312
+ let double = false
313
+ for (let i = 0; i < line.length; i += 1) {
314
+ const c = line[i] as string
315
+ if (c === '\\' && !single) {
316
+ out += c
317
+ const escaped = line[i + 1]
318
+ if (escaped !== undefined) {
319
+ out += escaped
320
+ i += 1
321
+ }
322
+ continue
323
+ }
324
+ if (c === "'" && !double) {
325
+ single = !single
326
+ out += c
327
+ continue
328
+ }
329
+ if (c === '"' && !single) {
330
+ double = !double
331
+ out += c
332
+ continue
333
+ }
334
+ if (!single && c === '$') {
335
+ const match = WORKING_DIRECTORY_VARIABLE.exec(line.slice(i))
336
+ if (match !== null) {
337
+ out += WORKING_DIRECTORY_PATH
338
+ i += match[0].length - 1
339
+ continue
340
+ }
341
+ }
342
+ out += c
343
+ }
344
+ return out
345
+ }
346
+
283
347
  /** An unquoted `*`, `?` or `[` in a word's source text. */
284
348
  function hasUnquotedGlob(text: string): boolean {
285
349
  let single = false
@@ -850,10 +914,11 @@ export function isReadOnlyCommandLine(
850
914
  ): boolean {
851
915
  if (dialect === 'cmd') return false
852
916
  if (line.trim() === '' || line.length > MAX_LINE_LENGTH) return false
853
- if (hasDynamicSyntax(line)) return false
854
- if (looksLikeNetworkPath(line.trim())) return false
917
+ const spelled = spellOutWorkingDirectory(line)
918
+ if (hasDynamicSyntax(spelled)) return false
919
+ if (looksLikeNetworkPath(spelled.trim())) return false
855
920
 
856
- const lexed = lexShellCommandLine(line, { dialect })
921
+ const lexed = lexShellCommandLine(spelled, { dialect })
857
922
  if (!lexed.complete || lexed.opaque || lexed.commands.length === 0) return false
858
923
  if (lexed.compoundWords.length > 0) return false
859
924
  if (!redirectionsAreHarmless(lexed.redirections)) return false
@@ -890,6 +955,9 @@ export function isReadOnlyCommandLine(
890
955
  if (head.value === 'cd') changesDirectory = true
891
956
  }
892
957
  if (runsGit && changesDirectory) return false
958
+ // `$PWD` is read as the directory the line starts in; after a `cd` the shell
959
+ // holds another one, so the two spellings no longer name the same path.
960
+ if (spelled !== line && changesDirectory) return false
893
961
  // Git trusts the folder it starts in. The directory of the session carries
894
962
  // over between calls, so `cd vendor/cache` and `git status` are two lines
895
963
  // that are only dangerous together. A folder that looks like a bare
@@ -176,20 +176,49 @@ function derived(from: ShellWord, value: string): ShellWord {
176
176
  return { ...from, text: value, value }
177
177
  }
178
178
 
179
+ /** An operand of `cp` or `mv`, and whether it is the destination. */
180
+ interface CopyOperand {
181
+ readonly word: ShellWord
182
+ readonly destination: boolean
183
+ }
184
+
179
185
  /**
180
- * Operands of `cp` and `mv`. GNU lets a flag follow an operand, and the
181
- * destination can be a flag's value: `--target-directory=D`, `--target-directory D`,
182
- * `-tD`, `-t D`, also inside a cluster (`-at D`, `-rtD`). Reading the operands
183
- * alone would miss the attached and the trailing forms.
186
+ * Operands of `cp` and `mv`, each marked with whether it is the destination.
187
+ * GNU lets a flag follow an operand, and the destination can be a flag's value:
188
+ * `--target-directory=D`, `--target-directory D`, `-tD`, `-t D`, also inside a
189
+ * cluster (`-at D`, `-rtD`). Reading the operands alone would miss the attached
190
+ * and the trailing forms. A target directory makes every other operand a
191
+ * source; without one the last operand is the destination. The callers differ
192
+ * on what a source costs: `mv` removes it, `cp` only reads it.
184
193
  */
185
- function copyOperands(args: Args): ShellWord[] {
186
- const out: ShellWord[] = []
194
+ function copyOperands(args: Args): CopyOperand[] {
195
+ return readCopyArguments(args).operands
196
+ }
197
+
198
+ /** True when `name` is a spelling GNU accepts for `full`: `minimum` or more of its leading characters. */
199
+ function isLongOption(name: string, full: string, minimum: number): boolean {
200
+ return name.length >= minimum && full.startsWith(name)
201
+ }
202
+
203
+ /**
204
+ * The operands of `cp`, `mv` or `install`, and whether the flags make the
205
+ * "copy" a link to its source (`cp -l`, `--link`, `-s`, `--symbolic-link`,
206
+ * alone or in a cluster such as `-al`, `-rs`): a later edit through the link
207
+ * changes the source. GNU takes any unique prefix of a long option, so the
208
+ * prefixes below are the shortest that no other option of `cp`, `mv` or
209
+ * `install` shares: `--t` for `--target-directory`, `--su` for `--suffix`,
210
+ * `--l` for `--link`, `--sy` for `--symbolic-link`. `--reflink` is a copy.
211
+ */
212
+ function readCopyArguments(args: Args): { operands: CopyOperand[]; links: boolean } {
213
+ const out: CopyOperand[] = []
214
+ let links = false
215
+ let target: ShellWord | undefined
187
216
  let afterDashes = false
188
217
  for (let i = 0; i < args.length; i += 1) {
189
218
  const arg = args[i] as ShellWord
190
219
  const text = arg.value
191
220
  if (afterDashes || text === '-' || !text.startsWith('-')) {
192
- out.push(arg)
221
+ out.push({ word: arg, destination: false })
193
222
  continue
194
223
  }
195
224
  if (text === '--') {
@@ -199,30 +228,39 @@ function copyOperands(args: Args): ShellWord[] {
199
228
  if (text.startsWith('--')) {
200
229
  const eq = text.indexOf('=')
201
230
  const name = eq >= 0 ? text.slice(0, eq) : text
202
- if (name === '--target-directory') {
203
- if (eq >= 0) out.push(derived(arg, text.slice(eq + 1)))
231
+ if (isLongOption(name, '--target-directory', 3)) {
232
+ if (eq >= 0) target = derived(arg, text.slice(eq + 1))
204
233
  else if (args[i + 1] !== undefined) {
205
- out.push(args[i + 1] as ShellWord)
234
+ target = args[i + 1] as ShellWord
206
235
  i += 1
207
236
  }
208
- } else if (name === '--suffix' && eq < 0) i += 1
237
+ } else if (isLongOption(name, '--suffix', 4) && eq < 0) i += 1
238
+ else if (isLongOption(name, '--link', 3) || isLongOption(name, '--symbolic-link', 4))
239
+ links = true
209
240
  continue
210
241
  }
211
242
  for (let j = 1; j < text.length; j += 1) {
212
243
  const letter = text[j] as string
244
+ if (letter === 'l' || letter === 's') links = true
213
245
  if (letter !== 't' && letter !== 'S') continue
214
246
  const rest = text.slice(j + 1)
215
247
  if (letter === 't') {
216
- if (rest !== '') out.push(derived(arg, rest))
248
+ if (rest !== '') target = derived(arg, rest)
217
249
  else if (args[i + 1] !== undefined) {
218
- out.push(args[i + 1] as ShellWord)
250
+ target = args[i + 1] as ShellWord
219
251
  i += 1
220
252
  }
221
253
  } else if (rest === '') i += 1
222
254
  break
223
255
  }
224
256
  }
225
- return out
257
+ if (target !== undefined) {
258
+ out.push({ word: target, destination: true })
259
+ return { operands: out, links }
260
+ }
261
+ const last = out[out.length - 1]
262
+ if (last !== undefined) out[out.length - 1] = { word: last.word, destination: true }
263
+ return { operands: out, links }
226
264
  }
227
265
 
228
266
  /**
@@ -804,8 +842,6 @@ const EXTRACTORS: Readonly<Record<string, (args: Args) => ShellWord[]>> = {
804
842
  touch: touchOperands,
805
843
  rm: operands,
806
844
  rmdir: operands,
807
- mv: copyOperands,
808
- cp: copyOperands,
809
845
  cat: operands,
810
846
  head: operands,
811
847
  tail: operands,
@@ -1175,7 +1211,10 @@ function outputTargets(program: string, args: Args): ShellWord[] {
1175
1211
  case 'dd':
1176
1212
  return args.filter((a) => a.value.startsWith('of=')).map((a) => derived(a, a.value.slice(3)))
1177
1213
  case 'install':
1178
- return [...copyOperands(args), ...(hasShort(args, 'd') ? operands(args) : [])]
1214
+ return [
1215
+ ...copyOperands(args).map((operand) => operand.word),
1216
+ ...(hasShort(args, 'd') ? operands(args) : []),
1217
+ ]
1179
1218
  case 'rsync': {
1180
1219
  const rest = operandsSkippingValues(args, RSYNC_VALUED, 'eTBMfgp'.replace(/[gp]/g, ''))
1181
1220
  return rest.length > 1 ? [rest[rest.length - 1] as ShellWord] : []
@@ -1374,7 +1413,7 @@ function outputTargets(program: string, args: Args): ShellWord[] {
1374
1413
  }
1375
1414
 
1376
1415
  /** Commands that create or change what their operands name. `sed` is added per call when it edits in place. */
1377
- const WRITERS = new Set(['mkdir', 'touch', 'rm', 'rmdir', 'mv', 'cp', 'tee'])
1416
+ const WRITERS = new Set(['mkdir', 'touch', 'rm', 'rmdir', 'tee'])
1378
1417
 
1379
1418
  const CD_PROGRAMS = new Set(['cd', 'pushd', 'popd', 'chdir'])
1380
1419
 
@@ -1449,6 +1488,24 @@ export function shellPathAccess(reading: ShellReading): ShellPathAccess {
1449
1488
  ...(directory !== undefined ? { directory } : {}),
1450
1489
  })
1451
1490
  }
1491
+ if (program === 'mv' || program === 'cp') {
1492
+ // `mv` removes its sources, so each is a write; `cp` leaves its sources
1493
+ // alone, so only the destination is, unless it links to them (`-l`,
1494
+ // `-s`): an edit through the link changes the source, so a source is
1495
+ // a write then as well.
1496
+ const copy = readCopyArguments(args)
1497
+ const sourcesChange = program === 'mv' || copy.links
1498
+ for (const operand of copy.operands) {
1499
+ if (operand.word.value === '' || isHarmlessTarget(operand.word.value)) continue
1500
+ uses.push({
1501
+ path: operand.word.value,
1502
+ access: sourcesChange || operand.destination ? 'write' : 'read',
1503
+ via: program,
1504
+ unresolved: expandsAtRuntime(operand.word),
1505
+ ...(directory !== undefined ? { directory } : {}),
1506
+ })
1507
+ }
1508
+ }
1452
1509
  if (program === 'touch') {
1453
1510
  for (const arg of touchReferences(args)) {
1454
1511
  if (arg.value === '' || isHarmlessTarget(arg.value)) continue
@@ -208,20 +208,60 @@ export function replaceableSummaries(systemMessages: readonly Message[]): string
208
208
  return bodies
209
209
  }
210
210
 
211
- const SUMMARY_TAG = /<summary>([\s\S]*?)<\/summary>/i
211
+ /**
212
+ * The summary runs from the first opening tag to the last closing tag, because
213
+ * the closing tag that ends the reply is the one that closes the summary: a
214
+ * summary body that quotes `</summary>` - the older conversation may well have
215
+ * shown that markup - must not end the summary at the quoted tag and lose
216
+ * everything after it. A reply cut off before its closing tag has no last one,
217
+ * and everything after the opening tag stands.
218
+ */
219
+ const SUMMARY_TAG = /<summary>([\s\S]*)<\/summary>/i
220
+ const SUMMARY_OPEN = /<summary>/i
221
+ const ANALYSIS_OPEN = /<analysis>/i
222
+ const ANALYSIS_CLOSE = '</analysis>'
223
+
224
+ /**
225
+ * A reasoning block a reply puts before its summary, removed. The block ends at
226
+ * the `</analysis>` that is followed straight away by the summary's opening tag,
227
+ * so neither a `</analysis>` nor a `<summary>` the block itself quotes leaves
228
+ * the rest of its reasoning in the reply. Without such a pair it runs to the
229
+ * last `</analysis>` that precedes the first `<summary>`. Text from the summary
230
+ * on is left alone: markup quoted inside a summary is its content, not a
231
+ * reasoning block.
232
+ */
233
+ function withoutAnalysis(reply: string): string {
234
+ const open = ANALYSIS_OPEN.exec(reply)
235
+ if (!open) return reply
236
+ const handover = /<\/analysis>\s*<summary>/i.exec(reply.slice(open.index))
237
+ if (handover) {
238
+ return (
239
+ reply.slice(0, open.index) + reply.slice(open.index + handover.index + ANALYSIS_CLOSE.length)
240
+ )
241
+ }
242
+ const summaryAt = reply.search(SUMMARY_OPEN)
243
+ const limit = summaryAt >= 0 ? summaryAt : reply.length
244
+ const closing = /<\/analysis>/gi
245
+ let last = -1
246
+ for (let match = closing.exec(reply); match && match.index < limit; match = closing.exec(reply)) {
247
+ last = match.index
248
+ }
249
+ if (last < 0) return reply
250
+ return reply.slice(0, open.index) + reply.slice(last + ANALYSIS_CLOSE.length)
251
+ }
212
252
 
213
253
  /** What lies between the summary tags of a reply, or `undefined` when it has none. */
214
254
  export function extractSummary(reply: string): string | undefined {
215
- const withoutAnalysis = reply.replace(/<analysis>[\s\S]*?<\/analysis>/gi, '')
216
- const found = SUMMARY_TAG.exec(withoutAnalysis)
255
+ const withoutReasoning = withoutAnalysis(reply)
256
+ const found = SUMMARY_TAG.exec(withoutReasoning)
217
257
  if (found) {
218
258
  const text = found[1]?.trim() ?? ''
219
259
  return text.length > 0 ? text : undefined
220
260
  }
221
261
  // A reply cut off before its closing tag still holds a usable summary.
222
- const open = withoutAnalysis.search(/<summary>/i)
262
+ const open = withoutReasoning.search(SUMMARY_OPEN)
223
263
  if (open >= 0) {
224
- const text = withoutAnalysis.slice(open + '<summary>'.length).trim()
264
+ const text = withoutReasoning.slice(open + '<summary>'.length).trim()
225
265
  return text.length > 0 ? text : undefined
226
266
  }
227
267
  return undefined
@@ -140,14 +140,17 @@ export class ConfigRegistry {
140
140
  const base = options.base ?? {}
141
141
  const override = asRecord(this.persisted[this.storeKey(namespace)])
142
142
  // Schema defaults, then the plugin's declared base, then the operator's
143
- // override — and the whole thing through the schema, so a persisted
144
- // override written against an older shape is refused at registration
145
- // rather than at the first read.
143
+ // override — and the whole thing through the schema. A persisted override
144
+ // is whatever an earlier or later version left on disk, so one invalid
145
+ // key is dropped (and said once) instead of failing the whole load; the
146
+ // valid keys beside it still apply. A base that is invalid is the
147
+ // plugin's own bug and still throws.
148
+ const resolved = this.resolvePersisted(namespace, schema, base, override)
146
149
  const entry: Entry<T> = {
147
150
  schema,
148
151
  base,
149
- override,
150
- resolved: schema.parse({ ...base, ...override }),
152
+ override: resolved.override,
153
+ resolved: resolved.value,
151
154
  watchers: new Set(),
152
155
  }
153
156
  this.entries.set(namespace, entry as Entry<unknown>)
@@ -179,6 +182,64 @@ export class ConfigRegistry {
179
182
  }
180
183
  }
181
184
 
185
+ private resolvePersisted<T>(
186
+ namespace: string,
187
+ schema: ConfigSchema<T>,
188
+ base: Record<string, unknown>,
189
+ persisted: Record<string, unknown>,
190
+ ): { value: T; override: Record<string, unknown> } {
191
+ let override = persisted
192
+ const dropped: string[] = []
193
+ for (;;) {
194
+ const result = schema.safeParse({ ...base, ...override })
195
+ if (result.success) {
196
+ for (const key of dropped) this.warnDropped(namespace, key, persisted[key], schema, base)
197
+ return { value: result.data, override }
198
+ }
199
+ const bad = new Set<string>()
200
+ for (const issue of result.error.issues) {
201
+ const head = issue.path[0]
202
+ if (typeof head === 'string' && Object.hasOwn(override, head)) bad.add(head)
203
+ }
204
+ if (bad.size === 0) {
205
+ // Not the override's doing, or the issue names no key: fall back to
206
+ // the base alone, and if even that fails the plugin's base is wrong.
207
+ if (Object.keys(override).length === 0) throw result.error
208
+ for (const key of Object.keys(override)) if (!dropped.includes(key)) dropped.push(key)
209
+ override = {}
210
+ continue
211
+ }
212
+ const next: Record<string, unknown> = {}
213
+ for (const [key, value] of Object.entries(override)) {
214
+ if (bad.has(key)) dropped.push(key)
215
+ else next[key] = value
216
+ }
217
+ override = next
218
+ }
219
+ }
220
+
221
+ private warnDropped<T>(
222
+ namespace: string,
223
+ key: string,
224
+ value: unknown,
225
+ schema: ConfigSchema<T>,
226
+ base: Record<string, unknown>,
227
+ ): void {
228
+ const where = this.store.location?.()
229
+ const probe = schema.safeParse({ ...base, [key]: value })
230
+ const expected = probe.success ? undefined : probe.error.issues.find((i) => i.path[0] === key)
231
+ this.log.warn(
232
+ 'Namzu ignored a saved setting that does not fit; the other settings still apply',
233
+ {
234
+ 'namzu.config.namespace': namespace,
235
+ 'namzu.config.key': key,
236
+ 'namzu.config.expected': describeExpected(expected),
237
+ ...(where ? { 'namzu.config.file': where } : {}),
238
+ 'namzu.config.sentence': `Namzu ignored the saved setting "${namespace}.${key}"${where ? ` in ${where}` : ''}: ${describeExpected(expected)} The other settings still apply.`,
239
+ },
240
+ )
241
+ }
242
+
182
243
  /** Namespaces registered on THIS scope. */
183
244
  namespaces(): readonly string[] {
184
245
  return [...this.entries.keys()].sort()
@@ -230,3 +291,24 @@ function asRecord(value: unknown): Record<string, unknown> {
230
291
  ? { ...(value as Record<string, unknown>) }
231
292
  : {}
232
293
  }
294
+
295
+ /** What a setting expected, in plain words, from the first issue zod raised for it. */
296
+ function describeExpected(
297
+ issue: { code?: string; message?: string; expected?: unknown; values?: unknown } | undefined,
298
+ ): string {
299
+ if (!issue) return 'its value is not one Namzu can use.'
300
+ if (issue.code === 'invalid_type' && typeof issue.expected === 'string') {
301
+ const kind: Record<string, string> = {
302
+ string: 'text',
303
+ number: 'a number',
304
+ boolean: 'true or false',
305
+ object: 'a group of settings',
306
+ array: 'a list',
307
+ }
308
+ const word = kind[issue.expected] ?? `a ${issue.expected}`
309
+ return `it should be ${word === 'text' ? 'text' : word}.`
310
+ }
311
+ if (issue.code === 'invalid_value' && Array.isArray(issue.values))
312
+ return `it should be one of ${issue.values.map((v) => `"${String(v)}"`).join(', ')}.`
313
+ return 'its value is not one Namzu can use.'
314
+ }
@@ -84,7 +84,24 @@ function objectToZod(rawSchema: Record<string, unknown>, depth: number): z.ZodTy
84
84
  const schema = Array.isArray(allOf) && allOf.length > 0 ? mergeAllOf(allOf, rawSchema) : rawSchema
85
85
 
86
86
  const properties = schema.properties as Record<string, unknown> | undefined
87
- if (!properties || Object.keys(properties).length === 0) {
87
+ const hasProperties = properties !== undefined && Object.keys(properties).length > 0
88
+
89
+ // A root union says "one of these argument shapes", and it used to
90
+ // vanish here for the same reason a root `allOf` did: `properties` is
91
+ // undefined on `{ anyOf: [...] }`, so the schema fell to the empty-object
92
+ // branch below and the tool was bridged to the model as taking no
93
+ // arguments at all. A server that spelled out two alternative payloads
94
+ // had every field of both dropped from the description, and its calls
95
+ // came back rejected for fields the model was never shown. Only taken
96
+ // when the root declares no properties of its own: `properties` beside a
97
+ // union is an intersection of the two, which the object reading below
98
+ // already covers.
99
+ const composite = (schema.anyOf ?? schema.oneOf) as unknown[] | undefined
100
+ if (!hasProperties && Array.isArray(composite) && composite.length > 0) {
101
+ return rootUnionToZod(composite, depth)
102
+ }
103
+
104
+ if (!hasProperties) {
88
105
  return closeOrOpen(z.object({}), schema, depth)
89
106
  }
90
107
  if (depth >= MAX_CONVERSION_DEPTH) return z.record(z.string(), z.unknown())
@@ -100,6 +117,47 @@ function objectToZod(rawSchema: Record<string, unknown>, depth: number): z.ZodTy
100
117
  return closeOrOpen(z.object(shape), schema, depth)
101
118
  }
102
119
 
120
+ /**
121
+ * Convert a root `anyOf`/`oneOf` into a union of the argument shapes it
122
+ * declares.
123
+ *
124
+ * The wire reads `anyOf` in both dialects namzu emits — `registry/tool/
125
+ * portable.ts` recommends it as the replacement for the `type: [...]` list
126
+ * some wires refuse — so the union survives the round trip and the members
127
+ * and their properties reach the model, instead of the empty object a root
128
+ * union used to collapse to.
129
+ *
130
+ * A single-member union is returned unwrapped, matching the property-level
131
+ * conversion in `baseTypeToZod`: an `anyOf` of one would only cost prompt
132
+ * bytes.
133
+ */
134
+ function rootUnionToZod(members: readonly unknown[], depth: number): z.ZodType {
135
+ if (depth >= MAX_CONVERSION_DEPTH) return z.record(z.string(), z.unknown())
136
+ const converted = members.map((member) => unionMemberToZod(member, depth + 1))
137
+ return converted.length === 1
138
+ ? (converted[0] as z.ZodType)
139
+ : z.union(converted as [z.ZodType, z.ZodType, ...z.ZodType[]])
140
+ }
141
+
142
+ /**
143
+ * Convert one member of a root union.
144
+ *
145
+ * The branches of a tool's root union are argument OBJECTS, and a server
146
+ * commonly writes each one without repeating `type: 'object'` — the
147
+ * `properties` and `required` keys alone carry the shape. Routing those
148
+ * through `jsonSchemaPropertyToZod` would read the missing type as
149
+ * "anything", so an object-shaped member is converted as an object; every
150
+ * other member (a bare `{ type: 'string' }`, say) takes the ordinary
151
+ * property path.
152
+ */
153
+ function unionMemberToZod(member: unknown, depth: number): z.ZodType {
154
+ if (typeof member !== 'object' || member === null) return z.unknown()
155
+ const schema = member as Record<string, unknown>
156
+ const objectShaped =
157
+ schema.type === 'object' || schema.properties !== undefined || Array.isArray(schema.allOf)
158
+ return objectShaped ? objectToZod(schema, depth) : jsonSchemaPropertyToZod(schema, depth)
159
+ }
160
+
103
161
  /**
104
162
  * Honor the server's `additionalProperties`, defaulting to closed.
105
163
  *
@@ -457,6 +515,79 @@ function mergeAllOf(members: readonly unknown[], parent: Record<string, unknown>
457
515
 
458
516
  type JsonRecord = Record<string, unknown>
459
517
 
518
+ /**
519
+ * The model-facing form of a root `anyOf`/`oneOf`: one object holding every
520
+ * member's properties, requiring only what every member requires. The union
521
+ * itself stays the validator. Returns undefined when the root is no union.
522
+ */
523
+ export function flattenRootUnion(schema: MCPJsonSchema): JsonRecord | undefined {
524
+ const inlined = inlineSchemaRefs(schema as unknown as Record<string, unknown>)
525
+ const own = inlined.properties as JsonRecord | undefined
526
+ if (own !== undefined && Object.keys(own).length > 0) return undefined
527
+ const members = (inlined.anyOf ?? inlined.oneOf) as unknown[] | undefined
528
+ if (!Array.isArray(members) || members.length === 0) return undefined
529
+
530
+ const seen = new Map<string, unknown[]>()
531
+ let required: string[] | undefined
532
+ for (const raw of members) {
533
+ if (typeof raw !== 'object' || raw === null) continue
534
+ const member = Array.isArray((raw as JsonRecord).allOf)
535
+ ? mergeAllOf((raw as JsonRecord).allOf as unknown[], raw as JsonRecord)
536
+ : (raw as JsonRecord)
537
+ for (const [key, value] of Object.entries(
538
+ (member.properties as JsonRecord | undefined) ?? {},
539
+ )) {
540
+ const definitions = seen.get(key) ?? []
541
+ if (!definitions.some((d) => JSON.stringify(d) === JSON.stringify(value)))
542
+ definitions.push(value)
543
+ seen.set(key, definitions)
544
+ }
545
+ const req = (member.required as string[] | undefined) ?? []
546
+ required = required === undefined ? [...req] : required.filter((key) => req.includes(key))
547
+ }
548
+ const properties: JsonRecord = {}
549
+ for (const [key, definitions] of seen) properties[key] = mergePropertyDefinitions(definitions)
550
+ return {
551
+ type: 'object',
552
+ properties,
553
+ ...(required && required.length > 0 ? { required } : {}),
554
+ }
555
+ }
556
+
557
+ /**
558
+ * One definition for a property that several members of a root union declare.
559
+ * The model must be able to pick any member, so a discriminator spelled as a
560
+ * `const` or an `enum` in each member becomes one `enum` of every value, and
561
+ * definitions that differ in any other way become an `anyOf` of them. The
562
+ * arguments are still checked against the original union.
563
+ */
564
+ function mergePropertyDefinitions(definitions: readonly unknown[]): unknown {
565
+ if (definitions.length === 1) return definitions[0]
566
+ const records = definitions.filter(
567
+ (d): d is JsonRecord => typeof d === 'object' && d !== null && !Array.isArray(d),
568
+ )
569
+ if (records.length === definitions.length) {
570
+ const valuesOf = (d: JsonRecord): unknown[] | undefined =>
571
+ 'const' in d ? [d.const] : Array.isArray(d.enum) ? (d.enum as unknown[]) : undefined
572
+ const sets = records.map(valuesOf)
573
+ const plain = (d: JsonRecord) =>
574
+ Object.keys(d).every((k) => ['const', 'enum', 'type', 'description', 'title'].includes(k))
575
+ const types = new Set(records.map((d) => JSON.stringify(d.type)))
576
+ if (sets.every((v) => v !== undefined) && records.every(plain) && types.size === 1) {
577
+ const values: unknown[] = []
578
+ for (const v of sets.flat())
579
+ if (!values.some((x) => JSON.stringify(x) === JSON.stringify(v))) values.push(v)
580
+ const first = records[0] as JsonRecord
581
+ return {
582
+ ...(first.type !== undefined ? { type: first.type } : {}),
583
+ ...(first.description !== undefined ? { description: first.description } : {}),
584
+ enum: values,
585
+ }
586
+ }
587
+ }
588
+ return { anyOf: [...definitions] }
589
+ }
590
+
460
591
  /** What `z.literal` takes. */
461
592
  type LiteralValue = string | number | bigint | boolean | null | undefined
462
593
 
@@ -505,6 +636,7 @@ export function mcpToolToToolDefinition(
505
636
  maxRetries?: number,
506
637
  ): ToolDefinition {
507
638
  const inputSchema = mcpJsonSchemaToZod(tool.inputSchema)
639
+ const flatModelSchema = flattenRootUnion(tool.inputSchema)
508
640
  // A call the client keeps alive on progress must not be cut by the
509
641
  // executor's own per-tool deadline (120 s unless the host says otherwise)
510
642
  // first. Only with `resetTimeoutOnProgress`; otherwise no `timeoutMs`, so
@@ -542,6 +674,10 @@ export function mcpToolToToolDefinition(
542
674
  ? `[MCP:${serverName}] ${tool.description}`
543
675
  : `[MCP:${serverName}] ${tool.name}`,
544
676
  inputSchema,
677
+ // A root union is validated through `inputSchema` (the union), but the
678
+ // model is shown one flat object: providers refuse a root without
679
+ // `type: "object"`, and one such tool would fail every turn.
680
+ ...(flatModelSchema ? { modelInputSchema: flatModelSchema } : {}),
545
681
  // Carried as the server wrote it. It is shown to the model, never
546
682
  // validated here, so rebuilding it would only lose fidelity.
547
683
  ...(tool.outputSchema