@namzu/sdk 69.4.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 (93) hide show
  1. package/CHANGELOG.md +44 -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/shell-lexer.d.ts.map +1 -1
  7. package/dist/authorization/shell-lexer.js +263 -0
  8. package/dist/authorization/shell-lexer.js.map +1 -1
  9. package/dist/connector/web/guarded-fetch.d.ts +30 -0
  10. package/dist/connector/web/guarded-fetch.d.ts.map +1 -1
  11. package/dist/connector/web/guarded-fetch.js +85 -0
  12. package/dist/connector/web/guarded-fetch.js.map +1 -1
  13. package/dist/connector/web/index.d.ts +1 -1
  14. package/dist/connector/web/index.d.ts.map +1 -1
  15. package/dist/connector/web/index.js +1 -1
  16. package/dist/connector/web/index.js.map +1 -1
  17. package/dist/plugin/common-layout/read.js +2 -2
  18. package/dist/plugin/common-layout/read.js.map +1 -1
  19. package/dist/plugin/hook-module/capabilities.d.ts +12 -0
  20. package/dist/plugin/hook-module/capabilities.d.ts.map +1 -1
  21. package/dist/plugin/hook-module/capabilities.js +82 -10
  22. package/dist/plugin/hook-module/capabilities.js.map +1 -1
  23. package/dist/plugin/hook-module/consent.d.ts +11 -0
  24. package/dist/plugin/hook-module/consent.d.ts.map +1 -1
  25. package/dist/plugin/hook-module/consent.js +31 -0
  26. package/dist/plugin/hook-module/consent.js.map +1 -1
  27. package/dist/plugin/hook-module/host.d.ts.map +1 -1
  28. package/dist/plugin/hook-module/host.js +69 -23
  29. package/dist/plugin/hook-module/host.js.map +1 -1
  30. package/dist/plugin/hook-module/index.d.ts +1 -1
  31. package/dist/plugin/hook-module/index.d.ts.map +1 -1
  32. package/dist/plugin/hook-module/index.js +1 -1
  33. package/dist/plugin/hook-module/index.js.map +1 -1
  34. package/dist/plugin/hook-module/scan.js +1 -1
  35. package/dist/plugin/hook-module/scan.js.map +1 -1
  36. package/dist/plugin/hook-module/worker-source.d.ts +5 -4
  37. package/dist/plugin/hook-module/worker-source.d.ts.map +1 -1
  38. package/dist/plugin/hook-module/worker-source.js +198 -28
  39. package/dist/plugin/hook-module/worker-source.js.map +1 -1
  40. package/dist/public-runtime.d.ts +3 -3
  41. package/dist/public-runtime.d.ts.map +1 -1
  42. package/dist/public-runtime.js +3 -3
  43. package/dist/public-runtime.js.map +1 -1
  44. package/dist/public-tools.d.ts +1 -1
  45. package/dist/public-tools.d.ts.map +1 -1
  46. package/dist/public-tools.js +1 -1
  47. package/dist/public-tools.js.map +1 -1
  48. package/dist/runtime/query/executor.d.ts.map +1 -1
  49. package/dist/runtime/query/executor.js +75 -10
  50. package/dist/runtime/query/executor.js.map +1 -1
  51. package/dist/runtime/query/review-policy.d.ts +21 -3
  52. package/dist/runtime/query/review-policy.d.ts.map +1 -1
  53. package/dist/runtime/query/review-policy.js +35 -19
  54. package/dist/runtime/query/review-policy.js.map +1 -1
  55. package/dist/skills/inline-shell-host.d.ts +6 -0
  56. package/dist/skills/inline-shell-host.d.ts.map +1 -1
  57. package/dist/skills/inline-shell-host.js +8 -0
  58. package/dist/skills/inline-shell-host.js.map +1 -1
  59. package/dist/skills/inline-shell.d.ts +9 -1
  60. package/dist/skills/inline-shell.d.ts.map +1 -1
  61. package/dist/skills/inline-shell.js +78 -10
  62. package/dist/skills/inline-shell.js.map +1 -1
  63. package/dist/tools/builtins/skill.d.ts.map +1 -1
  64. package/dist/tools/builtins/skill.js +2 -0
  65. package/dist/tools/builtins/skill.js.map +1 -1
  66. package/dist/types/permission/index.d.ts +11 -2
  67. package/dist/types/permission/index.d.ts.map +1 -1
  68. package/dist/types/permission/index.js +12 -2
  69. package/dist/types/permission/index.js.map +1 -1
  70. package/dist/types/tool/index.d.ts +7 -0
  71. package/dist/types/tool/index.d.ts.map +1 -1
  72. package/dist/types/tool/index.js.map +1 -1
  73. package/package.json +1 -1
  74. package/src/authorization/protected-paths.ts +44 -9
  75. package/src/authorization/shell-lexer.ts +242 -0
  76. package/src/connector/web/guarded-fetch.ts +92 -0
  77. package/src/connector/web/index.ts +6 -1
  78. package/src/plugin/common-layout/read.ts +2 -2
  79. package/src/plugin/hook-module/capabilities.ts +94 -10
  80. package/src/plugin/hook-module/consent.ts +36 -0
  81. package/src/plugin/hook-module/host.ts +72 -21
  82. package/src/plugin/hook-module/index.ts +2 -0
  83. package/src/plugin/hook-module/scan.ts +2 -2
  84. package/src/plugin/hook-module/worker-source.ts +199 -28
  85. package/src/public-runtime.ts +6 -0
  86. package/src/public-tools.ts +4 -1
  87. package/src/runtime/query/executor.ts +74 -7
  88. package/src/runtime/query/review-policy.ts +42 -13
  89. package/src/skills/inline-shell-host.ts +16 -0
  90. package/src/skills/inline-shell.ts +90 -8
  91. package/src/tools/builtins/skill.ts +2 -0
  92. package/src/types/permission/index.ts +20 -3
  93. 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
  }
@@ -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,
@@ -117,6 +117,7 @@ import { seedObservationLedger } from './file-evidence-seed.js'
117
117
  import { DEFAULT_TOOL_RESULT_GUARDRAILS } from './guardrail-presets.js'
118
118
  import { declaredWriteEscalation, shellEscalations } from './path-escalation.js'
119
119
  import type { ToolResultObservation } from './project-instructions.js'
120
+ import { CLASSIFY_NESTED_REFUSAL, allowedCallTooWide } from './review-policy.js'
120
121
  import { savedPresentation } from './saved-presentation.js'
121
122
  import { ToolCallBudget, assertMaxToolCalls } from './tool-call-budget.js'
122
123
  import {
@@ -2375,14 +2376,34 @@ export class ToolExecutor {
2375
2376
  // The mode the turn is decided under answers a nested call as it answers the same
2376
2377
  // call made directly: the tool that made this one reads, so the policy never saw it.
2377
2378
  // Asked only when there is a mode to answer to: with none, the call is decided as before.
2378
- const reviewMode = this.config.reviewMode?.()
2379
- const modeRefusal =
2380
- reviewMode === undefined
2379
+ // Asked again right before the call starts (below), because a hook or the person can
2380
+ // change the mode while the earlier steps wait.
2381
+ const askMode = (): string | undefined => {
2382
+ const mode = this.config.reviewMode?.()
2383
+ return mode === undefined
2381
2384
  ? undefined
2382
- : nestedCallModeRefusal(reviewMode, {
2385
+ : nestedCallModeRefusal(mode, {
2383
2386
  readOnly: isTrustedReadOnly(nestedTool, preparedInput, this.toolSource(name)),
2384
2387
  allowedByRule: gateResult?.decision === 'allow' && gateResult.matchedRule !== null,
2388
+ ruleTooWide:
2389
+ gateResult?.decision === 'allow' &&
2390
+ allowedCallTooWide({
2391
+ name,
2392
+ tool: nestedTool,
2393
+ input: preparedInput,
2394
+ allowRule: gateResult.matchedRule,
2395
+ }),
2385
2396
  })
2397
+ }
2398
+ const modeRefusal = askMode()
2399
+ // A model loaded the text that made this call, and auto mode would have sent the call
2400
+ // to its reviewer: it is not run and not a failure. The model is asked to make the call
2401
+ // itself (see `ToolDispatchOptions.handOff`), where the reviewer does see it. A rule's
2402
+ // deny still fails the load, and so does every other mode's refusal.
2403
+ const handedOff =
2404
+ options?.handOff === true &&
2405
+ modeRefusal === CLASSIFY_NESTED_REFUSAL &&
2406
+ gateResult?.decision !== 'deny'
2386
2407
  const runGranted =
2387
2408
  modeRefusal === undefined &&
2388
2409
  gateResult?.decision === 'review' &&
@@ -2394,8 +2415,20 @@ export class ToolExecutor {
2394
2415
  modeRefusal !== undefined ||
2395
2416
  (gateResult && gateResult.decision !== 'allow' && !runGranted)
2396
2417
  ) {
2418
+ // A hand-off still asks the caller's last word first: a guard that refuses the
2419
+ // command at load must not lose to the model's own call, which the classifier
2420
+ // decides without that guard. A refusal is the answer, and nothing is handed off.
2421
+ if (handedOff && options?.beforeRun) {
2422
+ const refusal = await options.beforeRun({ name, input: preparedInput, toolUseId: nestedId })
2423
+ signal.throwIfAborted()
2424
+ if (refusal !== undefined) {
2425
+ await progress.close()
2426
+ return { success: false, output: '', error: refusal }
2427
+ }
2428
+ }
2397
2429
  const reason =
2398
- modeRefusal !== undefined
2430
+ modeRefusal !== undefined &&
2431
+ !(modeRefusal === CLASSIFY_NESTED_REFUSAL && gateResult?.decision === 'deny')
2399
2432
  ? `Blocked: ${modeRefusal}.`
2400
2433
  : nestedEscalation
2401
2434
  ? 'Blocked: this nested call reaches a protected path, removal floor, outside-root boundary or another safety escalation. Call it directly so it can be reviewed.'
@@ -2403,7 +2436,9 @@ export class ToolExecutor {
2403
2436
  ? `Blocked: "${name}" requires the person's approval for every call, and an approval cannot be requested from inside another tool. Call it directly.`
2404
2437
  : gateResult?.decision === 'deny'
2405
2438
  ? `Blocked by the authorization gate: ${gateResult.reason}`
2406
- : `Blocked by the authorization gate: this nested call requires an explicit allow rule because an operator review cannot be opened from inside another tool. ${gateResult?.reason}`
2439
+ : gateResult?.matchedRule === null
2440
+ ? `Blocked by the authorization gate: this nested call requires an explicit allow rule because an operator review cannot be opened from inside another tool. ${gateResult.reason}`
2441
+ : `Blocked by the authorization gate: a rule or safety check asked for this call, an operator review cannot be opened from inside another tool, and no allow rule lifts that: call it directly so a person can review it. ${gateResult?.reason}`
2407
2442
  const output = deniedToolOutput(name, reason)
2408
2443
  // Same fail-closed durability rule as a direct gate denial: if the
2409
2444
  // configured session log cannot record the refusal, do not quietly carry
@@ -2438,7 +2473,12 @@ export class ToolExecutor {
2438
2473
  outputLength: output.length,
2439
2474
  ...(via ? { via } : {}),
2440
2475
  })
2441
- return { success: false, output: '', error: reason }
2476
+ return {
2477
+ success: false,
2478
+ output: '',
2479
+ error: reason,
2480
+ ...(handedOff ? { data: { handedOff: true } } : {}),
2481
+ }
2442
2482
  }
2443
2483
 
2444
2484
  // A review approved the PARENT's escalation, as the parent's input
@@ -2532,6 +2572,33 @@ export class ToolExecutor {
2532
2572
  return { success: false, output: '', error: message }
2533
2573
  }
2534
2574
 
2575
+ // The mode is read once more, after the hooks and the veto had their time: a switch
2576
+ // to a stricter one in that window must still stop this call before it starts.
2577
+ const lateRefusal = askMode()
2578
+ if (lateRefusal !== undefined) {
2579
+ const message = `Blocked: ${lateRefusal}.`
2580
+ if (this.config.recordAudit) {
2581
+ await this.config.recordAudit({
2582
+ what: { action: 'tool_call', tool: name },
2583
+ outcome: 'refused',
2584
+ reason: message,
2585
+ })
2586
+ }
2587
+ await progress.close()
2588
+ await this.emitEvent({
2589
+ type: 'tool_completed',
2590
+ turnId: this.config.turnId,
2591
+ toolUseId: nestedId,
2592
+ toolName: name,
2593
+ result: deniedToolOutput(name, message),
2594
+ isError: true,
2595
+ durationMs: Date.now() - startedAt,
2596
+ outputLength: message.length,
2597
+ ...(via ? { via } : {}),
2598
+ })
2599
+ return { success: false, output: '', error: message }
2600
+ }
2601
+
2535
2602
  let result: ToolResult
2536
2603
  try {
2537
2604
  // Use the same deadline layer as a model-issued call. Calling the