@namzu/sdk 69.3.0 → 70.0.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 (131) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/dist/authorization/protected-paths.d.ts +24 -6
  3. package/dist/authorization/protected-paths.d.ts.map +1 -1
  4. package/dist/authorization/protected-paths.js +37 -9
  5. package/dist/authorization/protected-paths.js.map +1 -1
  6. package/dist/authorization/readonly-commands.d.ts.map +1 -1
  7. package/dist/authorization/readonly-commands.js +30 -2
  8. package/dist/authorization/readonly-commands.js.map +1 -1
  9. package/dist/authorization/shell-lexer.d.ts.map +1 -1
  10. package/dist/authorization/shell-lexer.js +263 -0
  11. package/dist/authorization/shell-lexer.js.map +1 -1
  12. package/dist/connector/web/guarded-fetch.d.ts +30 -0
  13. package/dist/connector/web/guarded-fetch.d.ts.map +1 -1
  14. package/dist/connector/web/guarded-fetch.js +85 -0
  15. package/dist/connector/web/guarded-fetch.js.map +1 -1
  16. package/dist/connector/web/index.d.ts +1 -1
  17. package/dist/connector/web/index.d.ts.map +1 -1
  18. package/dist/connector/web/index.js +1 -1
  19. package/dist/connector/web/index.js.map +1 -1
  20. package/dist/plugin/common-layout/read.js +2 -2
  21. package/dist/plugin/common-layout/read.js.map +1 -1
  22. package/dist/plugin/hook-module/capabilities.d.ts +12 -0
  23. package/dist/plugin/hook-module/capabilities.d.ts.map +1 -1
  24. package/dist/plugin/hook-module/capabilities.js +82 -10
  25. package/dist/plugin/hook-module/capabilities.js.map +1 -1
  26. package/dist/plugin/hook-module/consent.d.ts +11 -0
  27. package/dist/plugin/hook-module/consent.d.ts.map +1 -1
  28. package/dist/plugin/hook-module/consent.js +31 -0
  29. package/dist/plugin/hook-module/consent.js.map +1 -1
  30. package/dist/plugin/hook-module/host.d.ts.map +1 -1
  31. package/dist/plugin/hook-module/host.js +69 -23
  32. package/dist/plugin/hook-module/host.js.map +1 -1
  33. package/dist/plugin/hook-module/index.d.ts +1 -1
  34. package/dist/plugin/hook-module/index.d.ts.map +1 -1
  35. package/dist/plugin/hook-module/index.js +1 -1
  36. package/dist/plugin/hook-module/index.js.map +1 -1
  37. package/dist/plugin/hook-module/scan.js +1 -1
  38. package/dist/plugin/hook-module/scan.js.map +1 -1
  39. package/dist/plugin/hook-module/worker-source.d.ts +5 -4
  40. package/dist/plugin/hook-module/worker-source.d.ts.map +1 -1
  41. package/dist/plugin/hook-module/worker-source.js +198 -28
  42. package/dist/plugin/hook-module/worker-source.js.map +1 -1
  43. package/dist/prompt/coding-agent-doctrine.d.ts +1 -1
  44. package/dist/prompt/coding-agent-doctrine.d.ts.map +1 -1
  45. package/dist/prompt/coding-agent-doctrine.js +1 -1
  46. package/dist/provider/side-request-reasoning.d.ts.map +1 -1
  47. package/dist/provider/side-request-reasoning.js +5 -1
  48. package/dist/provider/side-request-reasoning.js.map +1 -1
  49. package/dist/public-runtime.d.ts +3 -3
  50. package/dist/public-runtime.d.ts.map +1 -1
  51. package/dist/public-runtime.js +3 -3
  52. package/dist/public-runtime.js.map +1 -1
  53. package/dist/public-tools.d.ts +1 -1
  54. package/dist/public-tools.d.ts.map +1 -1
  55. package/dist/public-tools.js +1 -1
  56. package/dist/public-tools.js.map +1 -1
  57. package/dist/runtime/query/auto-review/classifier.d.ts.map +1 -1
  58. package/dist/runtime/query/auto-review/classifier.js +13 -2
  59. package/dist/runtime/query/auto-review/classifier.js.map +1 -1
  60. package/dist/runtime/query/auto-review/failure.d.ts +12 -5
  61. package/dist/runtime/query/auto-review/failure.d.ts.map +1 -1
  62. package/dist/runtime/query/auto-review/failure.js +42 -7
  63. package/dist/runtime/query/auto-review/failure.js.map +1 -1
  64. package/dist/runtime/query/executor.d.ts.map +1 -1
  65. package/dist/runtime/query/executor.js +75 -10
  66. package/dist/runtime/query/executor.js.map +1 -1
  67. package/dist/runtime/query/review-policy.d.ts +21 -3
  68. package/dist/runtime/query/review-policy.d.ts.map +1 -1
  69. package/dist/runtime/query/review-policy.js +57 -25
  70. package/dist/runtime/query/review-policy.js.map +1 -1
  71. package/dist/runtime/query/turn/check-scope.d.ts +18 -0
  72. package/dist/runtime/query/turn/check-scope.d.ts.map +1 -0
  73. package/dist/runtime/query/turn/check-scope.js +90 -0
  74. package/dist/runtime/query/turn/check-scope.js.map +1 -0
  75. package/dist/runtime/query/turn/outcome-ledger.d.ts.map +1 -1
  76. package/dist/runtime/query/turn/outcome-ledger.js +13 -0
  77. package/dist/runtime/query/turn/outcome-ledger.js.map +1 -1
  78. package/dist/skills/inline-shell-host.d.ts +6 -0
  79. package/dist/skills/inline-shell-host.d.ts.map +1 -1
  80. package/dist/skills/inline-shell-host.js +8 -0
  81. package/dist/skills/inline-shell-host.js.map +1 -1
  82. package/dist/skills/inline-shell.d.ts +9 -1
  83. package/dist/skills/inline-shell.d.ts.map +1 -1
  84. package/dist/skills/inline-shell.js +78 -10
  85. package/dist/skills/inline-shell.js.map +1 -1
  86. package/dist/tools/builtins/job.d.ts.map +1 -1
  87. package/dist/tools/builtins/job.js +4 -1
  88. package/dist/tools/builtins/job.js.map +1 -1
  89. package/dist/tools/builtins/skill.d.ts.map +1 -1
  90. package/dist/tools/builtins/skill.js +2 -0
  91. package/dist/tools/builtins/skill.js.map +1 -1
  92. package/dist/tools/builtins/wait-for-job.d.ts.map +1 -1
  93. package/dist/tools/builtins/wait-for-job.js +2 -1
  94. package/dist/tools/builtins/wait-for-job.js.map +1 -1
  95. package/dist/types/permission/index.d.ts +11 -2
  96. package/dist/types/permission/index.d.ts.map +1 -1
  97. package/dist/types/permission/index.js +12 -2
  98. package/dist/types/permission/index.js.map +1 -1
  99. package/dist/types/tool/index.d.ts +7 -0
  100. package/dist/types/tool/index.d.ts.map +1 -1
  101. package/dist/types/tool/index.js.map +1 -1
  102. package/package.json +1 -1
  103. package/src/authorization/protected-paths.ts +44 -9
  104. package/src/authorization/readonly-commands.ts +30 -2
  105. package/src/authorization/shell-lexer.ts +242 -0
  106. package/src/connector/web/guarded-fetch.ts +92 -0
  107. package/src/connector/web/index.ts +6 -1
  108. package/src/plugin/common-layout/read.ts +2 -2
  109. package/src/plugin/hook-module/capabilities.ts +94 -10
  110. package/src/plugin/hook-module/consent.ts +36 -0
  111. package/src/plugin/hook-module/host.ts +72 -21
  112. package/src/plugin/hook-module/index.ts +2 -0
  113. package/src/plugin/hook-module/scan.ts +2 -2
  114. package/src/plugin/hook-module/worker-source.ts +199 -28
  115. package/src/prompt/coding-agent-doctrine.ts +1 -1
  116. package/src/provider/side-request-reasoning.ts +5 -1
  117. package/src/public-runtime.ts +6 -0
  118. package/src/public-tools.ts +4 -1
  119. package/src/runtime/query/auto-review/classifier.ts +14 -2
  120. package/src/runtime/query/auto-review/failure.ts +52 -7
  121. package/src/runtime/query/executor.ts +74 -7
  122. package/src/runtime/query/review-policy.ts +72 -19
  123. package/src/runtime/query/turn/check-scope.ts +90 -0
  124. package/src/runtime/query/turn/outcome-ledger.ts +11 -0
  125. package/src/skills/inline-shell-host.ts +16 -0
  126. package/src/skills/inline-shell.ts +90 -8
  127. package/src/tools/builtins/job.ts +4 -1
  128. package/src/tools/builtins/skill.ts +2 -0
  129. package/src/tools/builtins/wait-for-job.ts +3 -1
  130. package/src/types/permission/index.ts +20 -3
  131. package/src/types/tool/index.ts +7 -0
@@ -16,6 +16,12 @@ import {
16
16
  shellHookVerdict,
17
17
  } from '../shell-hook.js'
18
18
  import { type CapabilityBridge, createCapabilityBridge } from './capabilities.js'
19
+ import {
20
+ endedSentence,
21
+ hookFailureRecovery,
22
+ hookModuleRecovery,
23
+ withHookModuleRecovery,
24
+ } from './consent.js'
19
25
  import {
20
26
  MODULE_HOOK_EVENTS,
21
27
  classicEventName,
@@ -281,13 +287,65 @@ export async function startHookModule(options: StartHookModuleOptions): Promise<
281
287
  log.warn('Hooks module not loaded', { ...attrs, 'namzu.hook_module.reason': why })
282
288
  options.onUnload?.(why)
283
289
  }
284
- const unloaded = (why: string): HookModuleHandle => {
290
+ let disposed = false
291
+ const recovery = hookModuleRecovery(plugin.name)
292
+ /** A refusal says how to get past it; a message that already says so is not told twice. */
293
+ const withRecovery = (text: string): string => withHookModuleRecovery(text, plugin.name)
294
+ const commandLabel = `module ${label}`
295
+ const failurePolicy = (event: ShellHookEvent, why: string): PluginHookResult => {
296
+ log.warn('Hooks module hook failed', {
297
+ ...attrs,
298
+ 'namzu.hook.event': event,
299
+ 'namzu.hook_module.reason': why,
300
+ })
301
+ // A hook that failed leaves the module loaded, so its way out is not a new session; a message that
302
+ // is already an unload or refusal text carries its own recovery.
303
+ const closed = why.includes(recovery)
304
+ ? why
305
+ : `${endedSentence(why)} ${hookFailureRecovery(plugin.name)}`
306
+ const line = `${commandLabel}: ${closed}`
307
+ // A guard that failed does not wave the call through: the call is refused and the model is told why.
308
+ if (event === 'pre_tool_use') return { action: 'error', message: line }
309
+ if (event === 'pre_skill_shell_command') return { action: 'skip', reason: line }
310
+ // A permission request that gets no decision stays with the person: the prompt is still asked.
311
+ return { action: 'continue', notice: line }
312
+ }
313
+ /** The events whose hooks gate a call: a gate that did not load must not read as a gate that passed. */
314
+ const guards = new Set<ShellHookEvent>([
315
+ 'pre_tool_use',
316
+ 'pre_skill_shell_command',
317
+ 'permission_request',
318
+ ])
319
+
320
+ const unloaded = (why: string, refusedGuards?: ReadonlySet<ShellHookEvent>): HookModuleHandle => {
285
321
  unload(why)
286
- return { scan, status, message: why, hooks: [], dispose: async () => undefined }
322
+ // A refused module's guards never attached, which reads as a guard that passed. The events its
323
+ // scan saw it hook are still answered as a failed guard is, so a refusal does not wave calls through.
324
+ const hooks: PluginHookDefinition[] = []
325
+ for (const event of MODULE_HOOK_EVENTS) {
326
+ if (!refusedGuards?.has(event)) continue
327
+ hooks.push({
328
+ event,
329
+ handler: async (): Promise<PluginHookResult> =>
330
+ disposed ? { action: 'continue' } : failurePolicy(event, why),
331
+ } as PluginHookDefinition)
332
+ }
333
+ return {
334
+ scan,
335
+ status,
336
+ message: why,
337
+ hooks,
338
+ dispose: async () => {
339
+ disposed = true
340
+ },
341
+ }
287
342
  }
288
343
 
289
344
  if (scan.refusals.length > 0 || scan.program === undefined) {
290
- return unloaded(`hooks module ${label} not loaded: ${refusalLine(scan)}`)
345
+ // A refusal can come from a name the scan does not follow, so which events the module hooks is
346
+ // unknown, and unknown reads as guarding: every guarding event is answered as a failed guard.
347
+ const seen = guards
348
+ return unloaded(withRecovery(`hooks module ${label} not loaded: ${refusalLine(scan)}`), seen)
291
349
  }
292
350
  const program = scan.program
293
351
  const runnable = new Set<ShellHookEvent>()
@@ -305,6 +363,8 @@ export async function startHookModule(options: StartHookModuleOptions): Promise<
305
363
  ...(plugin.dataDir !== undefined ? { dataDir: plugin.dataDir } : {}),
306
364
  projectDir: options.projectDir,
307
365
  envNames: scan.envNames,
366
+ // What the module's own scan declared is all its calls reach, whatever the worker sends.
367
+ allowedCalls: scan.calls.filter((call) => call.supported).map((call) => call.call),
308
368
  ...(options.environment !== undefined ? { environment: options.environment } : {}),
309
369
  ...(options.fetch !== undefined ? { fetch: options.fetch } : {}),
310
370
  log,
@@ -526,7 +586,7 @@ export async function startHookModule(options: StartHookModuleOptions): Promise<
526
586
  try {
527
587
  await start()
528
588
  } catch (error) {
529
- const why = `hooks module ${label} failed to load: ${toErrorMessage(error)}`
589
+ const why = withRecovery(`hooks module ${label} failed to load: ${toErrorMessage(error)}`)
530
590
  unload(why)
531
591
  return { kind: 'failed', message: why }
532
592
  }
@@ -574,20 +634,6 @@ export async function startHookModule(options: StartHookModuleOptions): Promise<
574
634
  }
575
635
 
576
636
  // --- the hooks ---------------------------------------------------------
577
- const commandLabel = `module ${label}`
578
- const failurePolicy = (event: ShellHookEvent, why: string): PluginHookResult => {
579
- log.warn('Hooks module hook failed', {
580
- ...attrs,
581
- 'namzu.hook.event': event,
582
- 'namzu.hook_module.reason': why,
583
- })
584
- const line = `${commandLabel}: ${why}`
585
- // A guard that failed does not wave the call through: the call is refused and the model is told why.
586
- if (event === 'pre_tool_use') return { action: 'error', message: line }
587
- if (event === 'pre_skill_shell_command') return { action: 'skip', reason: line }
588
- return { action: 'continue', notice: line }
589
- }
590
-
591
637
  const hooks: PluginHookDefinition[] = []
592
638
  for (const event of MODULE_HOOK_EVENTS) {
593
639
  if (!runnable.has(event)) continue
@@ -595,7 +641,11 @@ export async function startHookModule(options: StartHookModuleOptions): Promise<
595
641
  hooks.push({
596
642
  event,
597
643
  handler: async (context: PluginHookContext): Promise<PluginHookResult> => {
598
- if (status === 'unloaded') return { action: 'continue' }
644
+ if (status === 'unloaded') {
645
+ // A module that never loaded guards nothing, so a guarding event is answered as a failed guard is.
646
+ if (disposed || !guards.has(event)) return { action: 'continue' }
647
+ return failurePolicy(event, message ?? `hooks module ${label} is not loaded`)
648
+ }
599
649
  const input = shellHookInputFor(event, context, options.shell, { toolNames: 'written' })
600
650
  const payload = JSON.parse(shellHookPayload(input)) as Record<string, unknown>
601
651
  const e = event === 'pre_tool_use' ? toolEnvelope(payload) : payload
@@ -603,9 +653,9 @@ export async function startHookModule(options: StartHookModuleOptions): Promise<
603
653
  try {
604
654
  await start()
605
655
  } catch (error) {
606
- const why = `hooks module ${label} failed to load: ${toErrorMessage(error)}`
656
+ const why = withRecovery(`hooks module ${label} failed to load: ${toErrorMessage(error)}`)
607
657
  unload(why)
608
- return { action: 'continue', notice: why }
658
+ return guards.has(event) ? failurePolicy(event, why) : { action: 'continue', notice: why }
609
659
  }
610
660
  const registrations: number[] = []
611
661
  for (const [index, events] of registrationEvents.entries()) {
@@ -642,6 +692,7 @@ export async function startHookModule(options: StartHookModuleOptions): Promise<
642
692
  },
643
693
  hooks,
644
694
  dispose: async () => {
695
+ disposed = true
645
696
  status = 'unloaded'
646
697
  await endWorker('the hooks worker was stopped')
647
698
  },
@@ -47,6 +47,8 @@ export type { CapabilityBridge, CapabilityBridgeOptions } from './capabilities.j
47
47
  export {
48
48
  hookModuleConsentEntry,
49
49
  hookModuleConsentLines,
50
+ hookModuleRecovery,
50
51
  summarizeHookModule,
52
+ withHookModuleRecovery,
51
53
  } from './consent.js'
52
54
  export type { HookModuleConsentEntry, HookModuleSummary } from './consent.js'
@@ -271,9 +271,9 @@ function walk(
271
271
  parents.pop()
272
272
  }
273
273
 
274
- function isFunctionNode(node: AnyNode | undefined): boolean {
274
+ function isFunctionNode(node: AnyNode | null | undefined): boolean {
275
275
  return (
276
- node !== undefined &&
276
+ node != null &&
277
277
  (node.type === 'FunctionDeclaration' ||
278
278
  node.type === 'FunctionExpression' ||
279
279
  node.type === 'ArrowFunctionExpression')
@@ -19,10 +19,11 @@
19
19
  * is made from a sandbox with no prototype and with code generation from
20
20
  * strings off, and the worker's own function constructors are replaced by ones
21
21
  * that throw, so a reference that still leaked would not reach `process`. It is
22
- * a worker thread, not a process boundary, and a hostile module is not
23
- * contained against a flaw in V8 itself; a module runs only after the person
24
- * has been told what it does, and what it calls on `$` is checked before it
25
- * runs.
22
+ * a worker thread, not a process boundary, and it runs with the permissions of
23
+ * the user who runs Namzu: these are layers that make an escape hard, not a
24
+ * sandbox, and a hostile module is not contained against a flaw in V8 itself. A
25
+ * module runs only after the person has been told what it does, and what it
26
+ * calls on `$` is checked before it runs.
26
27
  *
27
28
  * Messages to the worker: `load`, `dispatch`, `overrun`, `grace-over`, `abort`,
28
29
  * `call-result`. Messages from it: `loaded`, `result`, `call`, `log`.
@@ -30,9 +31,75 @@
30
31
 
31
32
  /** Runs inside the module's context, and is the only code there besides the module. */
32
33
  const BOOTSTRAP_SOURCE = String.raw`
33
- (function (send, evaluate) {
34
+ (function (hostSend, hostEvaluate) {
34
35
  'use strict'
35
36
  const MAX_LOG = 4000
37
+ const freeze = Object.freeze
38
+ const setPrototypeOf = Object.setPrototypeOf
39
+ const getPrototypeOf = Object.getPrototypeOf
40
+ const objectPrototype = Object.prototype
41
+
42
+ // What reaches module code from outside this realm is a frozen object with no prototype, never the object
43
+ // itself: an error made in the worker's realm has that realm's Function behind its constructor, and a stack
44
+ // that names its frames.
45
+ const seal = (name, message) => {
46
+ const line = name + ': ' + message
47
+ const toStr = () => line
48
+ setPrototypeOf(toStr, null)
49
+ freeze(toStr)
50
+ return freeze({ __proto__: null, name, message, stack: line, toString: toStr })
51
+ }
52
+ const SENTINEL = seal('Error', 'a call to the host failed (details unavailable)')
53
+
54
+ // True only for an object whose prototype chain reaches this realm's Object.prototype within 64 hops: a
55
+ // foreign, null-terminated, throwing or over-long chain is not this realm's.
56
+ const ownRealm = (value) => {
57
+ let proto = value
58
+ for (let i = 0; i < 64; i++) {
59
+ proto = getPrototypeOf(proto)
60
+ if (proto === objectPrototype) return true
61
+ if (proto === null) return false
62
+ }
63
+ return false
64
+ }
65
+ const launder = (error) => {
66
+ if (error === null || (typeof error !== 'object' && typeof error !== 'function')) return error
67
+ try {
68
+ if (ownRealm(error)) return error
69
+ } catch (inner) {
70
+ // Not readable: sealed below.
71
+ }
72
+ let name = 'Error'
73
+ let message = ''
74
+ try {
75
+ if (typeof error.name === 'string') name = error.name
76
+ } catch (inner) {
77
+ // Keep the default.
78
+ }
79
+ try {
80
+ if (typeof error.message === 'string') message = error.message
81
+ } catch (inner) {
82
+ // Keep the default.
83
+ }
84
+ return seal(name, message)
85
+ }
86
+ // Every function the worker hands in is called through this: what it throws is laundered, and nothing is
87
+ // called or allocated between a failed launder and the throw.
88
+ const guarded = (hostFn) => (...args) => {
89
+ try {
90
+ return hostFn(...args)
91
+ } catch (error) {
92
+ let reason = SENTINEL
93
+ try {
94
+ reason = launder(error)
95
+ } catch (inner) {
96
+ // The sentinel stands.
97
+ }
98
+ throw reason
99
+ }
100
+ }
101
+ const send = guarded(hostSend)
102
+ const evaluate = guarded(hostEvaluate)
36
103
 
37
104
  const post = (message) => {
38
105
  try {
@@ -83,7 +150,7 @@ function call(noun, method, args) {
83
150
  pendingCalls.set(id, { resolve, reject })
84
151
  if (!post({ t: 'call', cid: id, noun, method, args })) {
85
152
  pendingCalls.delete(id)
86
- reject(new Error('the arguments of $.' + noun + '.' + method + ' are not plain data'))
153
+ reject(seal('TypeError', 'the arguments of $.' + noun + '.' + method + ' are not plain data'))
87
154
  }
88
155
  })
89
156
  }
@@ -218,7 +285,14 @@ function loadProgram(program) {
218
285
  cache.set(rel, exports)
219
286
  const source = program.files[rel]
220
287
  if (typeof source !== 'string') throw new Error('no such file in the module: ' + rel)
221
- const compiled = evaluate(rel, source)
288
+ // The worker's evaluate is outside this realm: whatever it throws (a RangeError from a stack that ran
289
+ // out is made in its realm) is turned into a message here, so no object of that realm is caught by a module.
290
+ let compiled
291
+ try {
292
+ compiled = evaluate(rel, source)
293
+ } catch (error) {
294
+ compiled = 'the module could not be compiled'
295
+ }
222
296
  if (typeof compiled === 'string') throw new Error(compiled)
223
297
  compiled(exports, load)
224
298
  return exports
@@ -385,7 +459,7 @@ function receive(json) {
385
459
  if (pending === undefined) return
386
460
  pendingCalls.delete(message.cid)
387
461
  if (message.ok) pending.resolve(message.value)
388
- else pending.reject(new Error(message.message))
462
+ else pending.reject(seal('Error', typeof message.message === 'string' ? message.message : 'the call failed'))
389
463
  return
390
464
  }
391
465
  }
@@ -395,13 +469,119 @@ return receive
395
469
  })
396
470
  `
397
471
 
472
+ // Run in the context before anything else is made there: the module's Error gets no way to read frames, and
473
+ // the globals a plain context should not have are gone.
474
+ const PREPARE_SOURCE = String.raw`(function () {
475
+ 'use strict'
476
+ Object.defineProperty(Error, 'prepareStackTrace', {
477
+ value: function () { return '' },
478
+ writable: false,
479
+ configurable: false,
480
+ })
481
+ // A stack that overflows is made by the engine, not by prepareStackTrace: with no frames kept it has none to read.
482
+ Object.defineProperty(Error, 'stackTraceLimit', { value: 0, writable: false, configurable: false })
483
+ for (const name of ['ShadowRealm', 'WebAssembly', 'FinalizationRegistry', 'WeakRef', 'Atomics',
484
+ 'SharedArrayBuffer', 'queueMicrotask', '$vm', 'gc', 'edenGC', 'fullGC', 'print', 'readFile', 'Loader']) {
485
+ delete globalThis[name]
486
+ }
487
+ })()`
488
+
489
+ // Run in the context once the bootstrap has made what the module is handed.
490
+ const FREEZE_SOURCE = String.raw`(function () {
491
+ 'use strict'
492
+ // A frozen prototype makes the data properties on it read-only, so "this.name = x" in an Error subclass
493
+ // would throw: those become accessors whose setter defines the property on the receiver instead.
494
+ function enableOverride(proto, key) {
495
+ const d = Object.getOwnPropertyDescriptor(proto, key)
496
+ if (!d || 'get' in d) return
497
+ const v = d.value
498
+ Object.defineProperty(proto, key, {
499
+ get() { return v },
500
+ set(nv) {
501
+ if (this === proto) return
502
+ Object.defineProperty(this, key, { value: nv, writable: true, enumerable: true, configurable: true })
503
+ },
504
+ enumerable: d.enumerable,
505
+ configurable: true,
506
+ })
507
+ }
508
+ const errorCtors = [Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError,
509
+ globalThis.AggregateError, globalThis.SuppressedError].filter(Boolean)
510
+ for (const [proto, keys] of [
511
+ [Object.prototype, Object.getOwnPropertyNames(Object.prototype)],
512
+ [Function.prototype, ['toString', 'constructor', 'name', 'length']],
513
+ [Array.prototype, ['toString', 'constructor']],
514
+ [Date.prototype, ['toString', 'toLocaleString', 'valueOf', 'constructor']],
515
+ ...errorCtors.map((C) => [C.prototype, ['name', 'message', 'toString', 'constructor']]),
516
+ ]) for (const key of keys) enableOverride(proto, key)
517
+ const freezeBoth = (C) => {
518
+ Object.freeze(C)
519
+ if (C.prototype) Object.freeze(C.prototype)
520
+ }
521
+ for (const C of [Promise, Object, Array, Function, globalThis.Iterator, Map, Set, WeakMap, WeakSet,
522
+ String, Number, Boolean, Symbol, BigInt, Date, RegExp, ArrayBuffer, DataView, ...errorCtors,
523
+ globalThis.DisposableStack, globalThis.AsyncDisposableStack, globalThis.Intl].filter(Boolean)) freezeBoth(C)
524
+ for (const C of [Object.getPrototypeOf(Int8Array), Int8Array, Uint8Array, Uint8ClampedArray, Int16Array,
525
+ Uint16Array, Int32Array, Uint32Array, globalThis.Float16Array, Float32Array, Float64Array,
526
+ BigInt64Array, BigUint64Array].filter(Boolean)) freezeBoth(C)
527
+ // The constructors of async, generator and async generator functions are reached only from an instance.
528
+ for (const f of [async () => {}, function* () {}, async function* () {}]) {
529
+ Object.freeze(f.constructor)
530
+ Object.freeze(f.constructor.prototype)
531
+ }
532
+ for (const namespace of [JSON, Math, Reflect, Proxy]) Object.freeze(namespace)
533
+ if (typeof Intl !== 'undefined') {
534
+ for (const key of Object.getOwnPropertyNames(Intl)) {
535
+ const C = Intl[key]
536
+ if (typeof C === 'function') freezeBoth(C)
537
+ }
538
+ }
539
+ const iterators = [
540
+ [][Symbol.iterator](), ''[Symbol.iterator](), new Map()[Symbol.iterator](), new Set()[Symbol.iterator](),
541
+ 'a'.matchAll(/a/g), (function* () {})(), (async function* () {})(),
542
+ ]
543
+ if (typeof Iterator !== 'undefined' && Iterator.from) {
544
+ iterators.push([].values().map((x) => x), Iterator.from({ next: () => ({ done: true }) }))
545
+ }
546
+ try {
547
+ if (typeof Intl !== 'undefined' && Intl.Segmenter) {
548
+ const segments = new Intl.Segmenter().segment('a')
549
+ iterators.push(segments, segments[Symbol.iterator]())
550
+ }
551
+ } catch (error) {
552
+ // No segmenter here: nothing to freeze.
553
+ }
554
+ for (const it of iterators) {
555
+ for (let p = Object.getPrototypeOf(it); p; p = Object.getPrototypeOf(p)) Object.freeze(p)
556
+ }
557
+ Object.defineProperty(globalThis, 'then', { value: undefined, writable: false, configurable: false })
558
+ for (const key of Reflect.ownKeys(globalThis)) {
559
+ const d = Object.getOwnPropertyDescriptor(globalThis, key)
560
+ if (d && d.configurable && 'value' in d) {
561
+ Object.defineProperty(globalThis, key, { value: d.value, writable: false, configurable: false, enumerable: d.enumerable })
562
+ }
563
+ }
564
+ })()`
565
+
398
566
  export const HOOK_WORKER_SOURCE =
399
- `const BOOTSTRAP = ${JSON.stringify('(' + BOOTSTRAP_SOURCE.trim() + ')')}\n` +
567
+ // 'use strict' is the first statement: a directive after any other statement is only an expression, so
568
+ // it must come before the BOOTSTRAP constant for the worker's own realm to be strict.
569
+ `'use strict'\nconst BOOTSTRAP = ${JSON.stringify('(' + BOOTSTRAP_SOURCE.trim() + ')')}\n` +
570
+ `const PREPARE_SOURCE = ${JSON.stringify(PREPARE_SOURCE)}\nconst FREEZE_SOURCE = ${JSON.stringify(FREEZE_SOURCE)}\n` +
400
571
  String.raw`
401
- 'use strict'
402
572
  const { parentPort } = require('node:worker_threads')
403
573
  const vm = require('node:vm')
404
574
 
575
+ // The worker's own realm gives a script nothing to read its stack with: a stack that overflows or throws
576
+ // is made of call sites, and a call site reaches the function that was running.
577
+ for (const key of ['prepareStackTrace', 'stackTraceLimit']) {
578
+ Object.defineProperty(Error, key, {
579
+ value: key === 'stackTraceLimit' ? 0 : undefined,
580
+ writable: false,
581
+ configurable: false,
582
+ })
583
+ }
584
+
405
585
  // Whatever of the worker's own realm might still be reached must not be able to make code: its
406
586
  // function constructors throw.
407
587
  {
@@ -449,34 +629,25 @@ const evaluate = (rel, source) => {
449
629
  }
450
630
  }
451
631
 
632
+ function prepareContext() {
633
+ // 'use strict' first, then the one Error the module has loses captureStackTrace.
634
+ vm.runInContext("'use strict'; delete Error.captureStackTrace", context)
635
+ vm.runInContext(PREPARE_SOURCE, context, { filename: 'plugin:prepare' })
636
+ }
637
+
452
638
  function freezeIntrinsics() {
453
- vm.runInContext(
454
- '(function () {' +
455
- 'const keep = new Set(["Object", "Error"]);' +
456
- 'for (const name of ["Object", "Array", "Function", "String", "Number", "Boolean", "Symbol", "Promise", "RegExp", "Date", "Map", "Set", "WeakMap", "WeakSet", "Error", "TypeError", "RangeError", "SyntaxError", "BigInt", "ArrayBuffer", "Uint8Array"]) {' +
457
- 'const ctor = globalThis[name];' +
458
- 'if (!ctor) continue;' +
459
- 'if (ctor.prototype && !keep.has(name)) Object.freeze(ctor.prototype);' +
460
- 'Object.freeze(ctor);' +
461
- '}' +
462
- 'for (const name of ["JSON", "Math", "Reflect"]) { if (globalThis[name]) Object.freeze(globalThis[name]); }' +
463
- 'for (const key of Reflect.ownKeys(globalThis)) {' +
464
- 'const d = Object.getOwnPropertyDescriptor(globalThis, key);' +
465
- 'if (d && d.configurable && "value" in d) Object.defineProperty(globalThis, key, { value: d.value, writable: false, configurable: false, enumerable: d.enumerable });' +
466
- '}' +
467
- '})()',
468
- context,
469
- )
639
+ vm.runInContext(FREEZE_SOURCE, context, { filename: 'plugin:freeze' })
470
640
  }
471
641
 
472
642
  let receive
473
643
 
474
644
  function start() {
475
- // No prototype on the sandbox, so nothing of the worker's realm is found through the global.
645
+ // No prototype on the context's global, so nothing of the worker's realm is found through the global.
476
646
  context = vm.createContext(Object.create(null), {
477
647
  name: 'plugin',
478
648
  codeGeneration: { strings: false, wasm: false },
479
649
  })
650
+ prepareContext()
480
651
  receive = vm.runInContext(BOOTSTRAP, context, { filename: 'plugin:bootstrap' })(send, evaluate)
481
652
  freezeIntrinsics()
482
653
  }
@@ -69,7 +69,7 @@ export const CODING_AGENT_WORKING_DOCTRINE = `## How you work
69
69
  This section applies only when you were asked to change something.
70
70
  - Begin editing once you know the first change; the requested scope is the deliverable, at the size asked. Match the surrounding idiom.
71
71
  - Prefer the dedicated tools over shell equivalents (\`read\` over \`cat\`, \`grep\` over a shell grep, \`glob\` over \`find\`, \`edit\` over \`sed -i\`, \`write\` over a redirect); use \`bash\` for the rest.
72
- - For a defect, reproduce it first with a small script or a failing test; a script stays in the scratch folder unless it becomes a test. After the change, rerun it. Run the project's tests and lint or format check, and add tests for behaviour you introduced. Claim only the checks you ran.
72
+ - For a defect, reproduce it first with a small script or a failing test; a script stays in the scratch folder unless it becomes a test. After the change, rerun it. Run the project's tests and lint or format check, and add tests for behaviour you introduced. Claim only the checks you ran; name what you skipped, and call a partial count partial.
73
73
  - Say where any throwaway file you made is, and which files outside the request you touched.
74
74
 
75
75
  ### Working with git
@@ -71,9 +71,13 @@ function refusesReasoningControls(error: unknown): boolean {
71
71
  // request nor switch the controls off for the model.
72
72
  if (/rate.?limit|too many requests|overloaded|timed? ?out|\b(429|5\d\d)\b/i.test(text))
73
73
  return false
74
+ // A driver that checks the request itself before sending it (the Codex
75
+ // subscription driver refuses `thinking: disabled` beside any effort but
76
+ // `none`) refuses with a plain error that says "requires" or "would not
77
+ // prove"; it is a refusal of the controls all the same.
74
78
  const names = /\b(thinking|reasoning|effort)\b/i.test(text)
75
79
  const rejects =
76
- /unsupported|not supported|unsupport|invalid|unknown|unrecogni[sz]ed|unexpected|not allowed|not permitted|does not (?:accept|support|allow)|not accept|extra inputs|bad request|\b400\b|\b422\b/i.test(
80
+ /unsupported|not supported|unsupport|invalid|unknown|unrecogni[sz]ed|unexpected|not allowed|not permitted|does not (?:accept|support|allow)|not accept|extra inputs|bad request|\b400\b|\b422\b|\brequires\b|would not prove/i.test(
77
81
  text,
78
82
  )
79
83
  return names && rejects
@@ -856,6 +856,8 @@ export {
856
856
  readCommonLayout,
857
857
  hookModuleConsentEntry,
858
858
  hookModuleConsentLines,
859
+ hookModuleRecovery,
860
+ withHookModuleRecovery,
859
861
  locateHookModule,
860
862
  scanHookModule,
861
863
  startHookModule,
@@ -1792,6 +1794,7 @@ export {
1792
1794
  ASK_RULE_UNATTENDED_REFUSAL,
1793
1795
  CLASSIFIER_SAFE_TOOLS,
1794
1796
  CLASSIFIER_TRANSCRIPT_TOO_LONG_FEEDBACK,
1797
+ CLASSIFY_NESTED_REFUSAL,
1795
1798
  OUTSIDE_ROOTS_UNATTENDED_REFUSAL,
1796
1799
  PLAN_MODE_REFUSAL,
1797
1800
  PLAN_MODE_REFUSAL_WITH_PLAN_FILE,
@@ -1802,6 +1805,7 @@ export {
1802
1805
  SCREEN_CONSENT_UNATTENDED_REFUSAL,
1803
1806
  STRICT_MODE_REFUSAL,
1804
1807
  UNFINISHED_CHECK_UNATTENDED_REFUSAL,
1808
+ allowedCallTooWide,
1805
1809
  batchNeedsReview,
1806
1810
  createReviewHandler,
1807
1811
  createReviewPolicy,
@@ -1868,6 +1872,8 @@ export {
1868
1872
  GuardedFetchProvider,
1869
1873
  WebFetchRefusedError,
1870
1874
  isPrivateAddress,
1875
+ privateAddressProblem,
1876
+ proxyConfigured,
1871
1877
  } from './connector/web/index.js'
1872
1878
 
1873
1879
  // Where an attachment's bytes live when the message does not carry them.
@@ -89,7 +89,10 @@ export {
89
89
  execHostShell,
90
90
  } from './tools/builtins/bash.js'
91
91
  // Authorization and execution must agree after a session carries its shell cwd.
92
- export { effectiveBashWorkingDirectory } from './tools/builtins/bash-cwd.js'
92
+ export {
93
+ effectiveBashWorkingDirectory,
94
+ pinBashWorkingDirectory,
95
+ } from './tools/builtins/bash-cwd.js'
93
96
  // The same reach questions the executor asks of a nested shell call, for a host that runs one without a turn.
94
97
  export {
95
98
  type ShellLineEscalationContext,
@@ -198,6 +198,12 @@ export {
198
198
  autoReviewUnavailableFeedback,
199
199
  } from './feedback.js'
200
200
 
201
+ /** The HTTP status the failure carried, as the one log attribute it is kept under. */
202
+ function statusOf(error: unknown): { 'namzu.auto_review.error_status'?: number } {
203
+ const status = classifyProviderError(error).status
204
+ return status !== undefined ? { 'namzu.auto_review.error_status': status } : {}
205
+ }
206
+
201
207
  class DeadlineError extends Error {
202
208
  readonly retryable = true
203
209
  constructor() {
@@ -430,11 +436,14 @@ export function createAutoReviewClassifier(
430
436
  if (request.signal?.aborted) {
431
437
  return blocked(started, 0, 'aborted', 'the review was cancelled before it finished')
432
438
  }
433
- const why = describeCheckFailure(error, options.quickDeadlineMs ?? 60_000)
439
+ const why = describeCheckFailure(error, options.quickDeadlineMs ?? 60_000, options.model)
434
440
  log.warn('auto review could not complete', {
435
441
  'namzu.auto_review.stage': 1,
436
442
  'namzu.auto_review.failure': why,
443
+ 'namzu.auto_review.model': options.model,
437
444
  'namzu.auto_review.error': error instanceof Error ? error.message : String(error),
445
+ 'namzu.auto_review.error_code': classifyProviderError(error).code,
446
+ ...statusOf(error),
438
447
  })
439
448
  return blocked(
440
449
  started,
@@ -457,11 +466,14 @@ export function createAutoReviewClassifier(
457
466
  if (request.signal?.aborted) {
458
467
  return blocked(started, 1, 'aborted', 'the review was cancelled before it finished')
459
468
  }
460
- const why = describeCheckFailure(error, options.reasonedDeadlineMs ?? 120_000)
469
+ const why = describeCheckFailure(error, options.reasonedDeadlineMs ?? 120_000, options.model)
461
470
  log.warn('auto review could not complete', {
462
471
  'namzu.auto_review.stage': 2,
463
472
  'namzu.auto_review.failure': why,
473
+ 'namzu.auto_review.model': options.model,
464
474
  'namzu.auto_review.error': error instanceof Error ? error.message : String(error),
475
+ 'namzu.auto_review.error_code': classifyProviderError(error).code,
476
+ ...statusOf(error),
465
477
  })
466
478
  return blocked(
467
479
  started,
@@ -1,16 +1,57 @@
1
+ import { LOG_SECRET_PATTERNS } from '../../../constants/secret-patterns.js'
1
2
  import { classifyProviderError } from '../../../types/provider/errors.js'
2
3
 
4
+ /** The most characters of the provider's own wording that are shown. */
5
+ const DETAIL_CHARS = 140
6
+
7
+ /** A query-parameter or field name that says its value is a credential. */
8
+ const SENSITIVE_NAME = String.raw`[A-Za-z0-9_.-]*(?:key|token|secret|passw(?:or)?d|pwd|sig|signature|auth|credential|cookie|session)[A-Za-z0-9_.-]*`
9
+
10
+ /**
11
+ * Credential shapes that carry no vendor prefix: URL userinfo, a query
12
+ * parameter or `name: value` / `name=value` pair whose name says secret, and
13
+ * an `x-api-key` style header.
14
+ */
15
+ function scrubCredentialShapes(input: string): string {
16
+ return input
17
+ .replace(/(\/\/)[^/@\s]+@/g, '$1[REDACTED:userinfo]@')
18
+ .replace(
19
+ new RegExp(
20
+ String.raw`(\b${SENSITIVE_NAME}\b)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s&;,"']+)`,
21
+ 'gi',
22
+ ),
23
+ '$1$2[REDACTED:secret]',
24
+ )
25
+ }
26
+
27
+ /**
28
+ * The provider's own wording, fit to show: one line, anything shaped like a
29
+ * credential replaced, and cut short. A refusal that says only "provider
30
+ * error" hides the one fact that tells a person what to change.
31
+ */
32
+ export function checkFailureDetail(error: unknown): string {
33
+ let text = error instanceof Error ? error.message : String(error)
34
+ for (const [label, pattern] of LOG_SECRET_PATTERNS) {
35
+ pattern.lastIndex = 0
36
+ text = text.replace(pattern, `[REDACTED:${label}]`)
37
+ }
38
+ text = scrubCredentialShapes(text)
39
+ text = text.replace(/\s+/g, ' ').trim()
40
+ return text.length > DETAIL_CHARS ? `${text.slice(0, DETAIL_CHARS - 1)}…` : text
41
+ }
42
+
3
43
  /**
4
44
  * The class of a failure to complete the safety check, in a few plain words:
5
- * `no credential for the check model`, `provider returned 400`,
6
- * `timed out after 60 s`. It is a class, never the provider's own text: that
7
- * text can carry a request body or a key fragment, so it goes to the log, not
8
- * to the person or the model.
45
+ * `no credential for the check model`, `timed out after 60 s`, or, when the
46
+ * class alone says nothing, the status, the model and a short, scrubbed piece
47
+ * of the provider's own wording: `provider returned 400 (gpt-6.2-sol): ...`.
48
+ * The text is cut to one short line with anything shaped like a credential
49
+ * replaced; the whole of it goes to the log.
9
50
  *
10
51
  * `deadlineMs` is the deadline the pass ran under, when the failure was the
11
52
  * deadline expiring.
12
53
  */
13
- export function describeCheckFailure(error: unknown, deadlineMs?: number): string {
54
+ export function describeCheckFailure(error: unknown, deadlineMs?: number, model?: string): string {
14
55
  if (error instanceof Error && error.name === 'DeadlineError') {
15
56
  return deadlineMs !== undefined
16
57
  ? `timed out after ${Math.round(deadlineMs / 1000)} s`
@@ -44,7 +85,11 @@ export function describeCheckFailure(error: unknown, deadlineMs?: number): strin
44
85
  return 'could not reach the provider'
45
86
  case 'not_found':
46
87
  return 'the check model was not found'
47
- default:
48
- return status !== undefined ? `provider returned ${status}` : 'provider error'
88
+ default: {
89
+ const head = status !== undefined ? `provider returned ${status}` : 'provider error'
90
+ const where = model !== undefined && model !== '' ? ` (${model})` : ''
91
+ const detail = checkFailureDetail(error)
92
+ return detail === '' ? `${head}${where}` : `${head}${where}: ${detail}`
93
+ }
49
94
  }
50
95
  }