@namzu/sdk 71.1.0 → 72.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 (198) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/agents/QueryAgent.d.ts.map +1 -1
  3. package/dist/agents/QueryAgent.js +1 -0
  4. package/dist/agents/QueryAgent.js.map +1 -1
  5. package/dist/compaction/index.d.ts +1 -1
  6. package/dist/compaction/index.d.ts.map +1 -1
  7. package/dist/compaction/index.js +1 -1
  8. package/dist/compaction/index.js.map +1 -1
  9. package/dist/compaction/manual.d.ts +8 -0
  10. package/dist/compaction/manual.d.ts.map +1 -1
  11. package/dist/compaction/manual.js +18 -14
  12. package/dist/compaction/manual.js.map +1 -1
  13. package/dist/compaction/model-summary.d.ts +24 -6
  14. package/dist/compaction/model-summary.d.ts.map +1 -1
  15. package/dist/compaction/model-summary.js +108 -23
  16. package/dist/compaction/model-summary.js.map +1 -1
  17. package/dist/compaction/restore.d.ts +23 -0
  18. package/dist/compaction/restore.d.ts.map +1 -1
  19. package/dist/compaction/restore.js +59 -1
  20. package/dist/compaction/restore.js.map +1 -1
  21. package/dist/compaction/summary.d.ts +37 -2
  22. package/dist/compaction/summary.d.ts.map +1 -1
  23. package/dist/compaction/summary.js +46 -6
  24. package/dist/compaction/summary.js.map +1 -1
  25. package/dist/config/runtime.js +3 -3
  26. package/dist/config/runtime.js.map +1 -1
  27. package/dist/connector/index.d.ts +2 -2
  28. package/dist/connector/index.d.ts.map +1 -1
  29. package/dist/connector/index.js +1 -1
  30. package/dist/connector/index.js.map +1 -1
  31. package/dist/connector/mcp/client.d.ts +26 -6
  32. package/dist/connector/mcp/client.d.ts.map +1 -1
  33. package/dist/connector/mcp/client.js +49 -7
  34. package/dist/connector/mcp/client.js.map +1 -1
  35. package/dist/connector/mcp/index.d.ts +2 -0
  36. package/dist/connector/mcp/index.d.ts.map +1 -1
  37. package/dist/connector/mcp/index.js +1 -0
  38. package/dist/connector/mcp/index.js.map +1 -1
  39. package/dist/connector/mcp/sandbox-stdio.d.ts +67 -0
  40. package/dist/connector/mcp/sandbox-stdio.d.ts.map +1 -0
  41. package/dist/connector/mcp/sandbox-stdio.js +178 -0
  42. package/dist/connector/mcp/sandbox-stdio.js.map +1 -0
  43. package/dist/connector/mcp/stdio-program.d.ts +34 -0
  44. package/dist/connector/mcp/stdio-program.d.ts.map +1 -0
  45. package/dist/connector/mcp/stdio-program.js +47 -0
  46. package/dist/connector/mcp/stdio-program.js.map +1 -0
  47. package/dist/connector/mcp/stdio.d.ts.map +1 -1
  48. package/dist/connector/mcp/stdio.js +5 -2
  49. package/dist/connector/mcp/stdio.js.map +1 -1
  50. package/dist/connector/web/guarded-fetch.d.ts +51 -2
  51. package/dist/connector/web/guarded-fetch.d.ts.map +1 -1
  52. package/dist/connector/web/guarded-fetch.js +140 -19
  53. package/dist/connector/web/guarded-fetch.js.map +1 -1
  54. package/dist/connector/web/index.d.ts +2 -2
  55. package/dist/connector/web/index.d.ts.map +1 -1
  56. package/dist/connector/web/index.js +1 -1
  57. package/dist/connector/web/index.js.map +1 -1
  58. package/dist/manager/agent/lifecycle.js +1 -1
  59. package/dist/manager/agent/lifecycle.js.map +1 -1
  60. package/dist/plugin/hook-module/capabilities.d.ts.map +1 -1
  61. package/dist/plugin/hook-module/capabilities.js +24 -13
  62. package/dist/plugin/hook-module/capabilities.js.map +1 -1
  63. package/dist/plugin/hook-module/host.d.ts +31 -0
  64. package/dist/plugin/hook-module/host.d.ts.map +1 -1
  65. package/dist/plugin/hook-module/host.js +56 -13
  66. package/dist/plugin/hook-module/host.js.map +1 -1
  67. package/dist/plugin/hook-module/index.d.ts +3 -2
  68. package/dist/plugin/hook-module/index.d.ts.map +1 -1
  69. package/dist/plugin/hook-module/index.js +2 -1
  70. package/dist/plugin/hook-module/index.js.map +1 -1
  71. package/dist/plugin/index.d.ts +1 -0
  72. package/dist/plugin/index.d.ts.map +1 -1
  73. package/dist/plugin/index.js +1 -0
  74. package/dist/plugin/index.js.map +1 -1
  75. package/dist/plugin/shell-hook-execute.d.ts +55 -0
  76. package/dist/plugin/shell-hook-execute.d.ts.map +1 -0
  77. package/dist/plugin/shell-hook-execute.js +73 -0
  78. package/dist/plugin/shell-hook-execute.js.map +1 -0
  79. package/dist/plugin/shell-hook-restrict.d.ts +31 -0
  80. package/dist/plugin/shell-hook-restrict.d.ts.map +1 -0
  81. package/dist/plugin/shell-hook-restrict.js +69 -0
  82. package/dist/plugin/shell-hook-restrict.js.map +1 -0
  83. package/dist/plugin/shell-hook.d.ts +29 -2
  84. package/dist/plugin/shell-hook.d.ts.map +1 -1
  85. package/dist/plugin/shell-hook.js +44 -12
  86. package/dist/plugin/shell-hook.js.map +1 -1
  87. package/dist/public-runtime.d.ts +7 -5
  88. package/dist/public-runtime.d.ts.map +1 -1
  89. package/dist/public-runtime.js +5 -4
  90. package/dist/public-runtime.js.map +1 -1
  91. package/dist/public-types.d.ts +2 -0
  92. package/dist/public-types.d.ts.map +1 -1
  93. package/dist/runtime/jobs/websocket-source.d.ts +2 -22
  94. package/dist/runtime/jobs/websocket-source.d.ts.map +1 -1
  95. package/dist/runtime/jobs/websocket-source.js +2 -33
  96. package/dist/runtime/jobs/websocket-source.js.map +1 -1
  97. package/dist/runtime/query/compact-session.d.ts.map +1 -1
  98. package/dist/runtime/query/compact-session.js +5 -0
  99. package/dist/runtime/query/compact-session.js.map +1 -1
  100. package/dist/runtime/query/events.d.ts +7 -0
  101. package/dist/runtime/query/events.d.ts.map +1 -1
  102. package/dist/runtime/query/events.js +29 -11
  103. package/dist/runtime/query/events.js.map +1 -1
  104. package/dist/runtime/query/executor/tool-call-admission.d.ts.map +1 -1
  105. package/dist/runtime/query/executor/tool-call-admission.js +51 -10
  106. package/dist/runtime/query/executor/tool-call-admission.js.map +1 -1
  107. package/dist/runtime/query/index.d.ts +6 -0
  108. package/dist/runtime/query/index.d.ts.map +1 -1
  109. package/dist/runtime/query/index.js +3 -0
  110. package/dist/runtime/query/index.js.map +1 -1
  111. package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
  112. package/dist/runtime/query/iteration/phases/compaction.js +21 -3
  113. package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
  114. package/dist/runtime/query/iteration/phases/context.d.ts +4 -0
  115. package/dist/runtime/query/iteration/phases/context.d.ts.map +1 -1
  116. package/dist/runtime/query/iteration/phases/context.js.map +1 -1
  117. package/dist/scheduler/completion-inbox.d.ts.map +1 -1
  118. package/dist/scheduler/completion-inbox.js +15 -0
  119. package/dist/scheduler/completion-inbox.js.map +1 -1
  120. package/dist/store/session-index/index.d.ts +13 -0
  121. package/dist/store/session-index/index.d.ts.map +1 -1
  122. package/dist/store/session-index/index.js +1 -0
  123. package/dist/store/session-index/index.js.map +1 -1
  124. package/dist/store/session-index/rebuild.d.ts +12 -0
  125. package/dist/store/session-index/rebuild.d.ts.map +1 -1
  126. package/dist/store/session-index/rebuild.js +20 -4
  127. package/dist/store/session-index/rebuild.js.map +1 -1
  128. package/dist/store/session-index/sqlite.d.ts +20 -0
  129. package/dist/store/session-index/sqlite.d.ts.map +1 -1
  130. package/dist/store/session-index/sqlite.js +50 -12
  131. package/dist/store/session-index/sqlite.js.map +1 -1
  132. package/dist/tools/admit-facts.d.ts.map +1 -1
  133. package/dist/tools/admit-facts.js +59 -0
  134. package/dist/tools/admit-facts.js.map +1 -1
  135. package/dist/tools/coordinator/ask-user-question.d.ts.map +1 -1
  136. package/dist/tools/coordinator/ask-user-question.js +67 -3
  137. package/dist/tools/coordinator/ask-user-question.js.map +1 -1
  138. package/dist/turn/memory-promoter.d.ts.map +1 -1
  139. package/dist/turn/memory-promoter.js +20 -4
  140. package/dist/turn/memory-promoter.js.map +1 -1
  141. package/dist/types/agent/base.d.ts +6 -0
  142. package/dist/types/agent/base.d.ts.map +1 -1
  143. package/dist/types/agent/task.d.ts +5 -0
  144. package/dist/types/agent/task.d.ts.map +1 -1
  145. package/dist/types/agent/task.js.map +1 -1
  146. package/dist/types/hitl/index.d.ts +8 -0
  147. package/dist/types/hitl/index.d.ts.map +1 -1
  148. package/dist/types/hitl/index.js.map +1 -1
  149. package/dist/types/message/index.d.ts +7 -0
  150. package/dist/types/message/index.d.ts.map +1 -1
  151. package/dist/types/message/index.js.map +1 -1
  152. package/dist/types/tool/presentation.d.ts +21 -0
  153. package/dist/types/tool/presentation.d.ts.map +1 -1
  154. package/package.json +6 -6
  155. package/src/agents/QueryAgent.ts +1 -0
  156. package/src/compaction/index.ts +1 -0
  157. package/src/compaction/manual.ts +48 -12
  158. package/src/compaction/model-summary.ts +118 -23
  159. package/src/compaction/restore.ts +74 -1
  160. package/src/compaction/summary.ts +69 -3
  161. package/src/config/runtime.ts +3 -3
  162. package/src/connector/index.ts +3 -0
  163. package/src/connector/mcp/client.ts +49 -7
  164. package/src/connector/mcp/index.ts +5 -0
  165. package/src/connector/mcp/sandbox-stdio.ts +214 -0
  166. package/src/connector/mcp/stdio-program.ts +68 -0
  167. package/src/connector/mcp/stdio.ts +5 -2
  168. package/src/connector/web/guarded-fetch.ts +197 -30
  169. package/src/connector/web/index.ts +4 -1
  170. package/src/manager/agent/lifecycle.ts +1 -1
  171. package/src/plugin/hook-module/capabilities.ts +36 -14
  172. package/src/plugin/hook-module/host.ts +86 -13
  173. package/src/plugin/hook-module/index.ts +3 -0
  174. package/src/plugin/index.ts +1 -0
  175. package/src/plugin/shell-hook-execute.ts +126 -0
  176. package/src/plugin/shell-hook-restrict.ts +66 -0
  177. package/src/plugin/shell-hook.ts +78 -10
  178. package/src/public-runtime.ts +14 -0
  179. package/src/public-types.ts +13 -0
  180. package/src/runtime/jobs/websocket-source.ts +2 -46
  181. package/src/runtime/query/compact-session.ts +5 -0
  182. package/src/runtime/query/events.ts +29 -11
  183. package/src/runtime/query/executor/tool-call-admission.ts +62 -17
  184. package/src/runtime/query/index.ts +10 -0
  185. package/src/runtime/query/iteration/phases/compaction.ts +26 -2
  186. package/src/runtime/query/iteration/phases/context.ts +6 -0
  187. package/src/scheduler/completion-inbox.ts +14 -0
  188. package/src/store/session-index/index.ts +14 -0
  189. package/src/store/session-index/rebuild.ts +22 -4
  190. package/src/store/session-index/sqlite.ts +63 -14
  191. package/src/tools/admit-facts.ts +64 -0
  192. package/src/tools/coordinator/ask-user-question.ts +88 -4
  193. package/src/turn/memory-promoter.ts +24 -3
  194. package/src/types/agent/base.ts +7 -0
  195. package/src/types/agent/task.ts +5 -0
  196. package/src/types/hitl/index.ts +8 -0
  197. package/src/types/message/index.ts +7 -0
  198. package/src/types/tool/presentation.ts +22 -0
@@ -14,7 +14,12 @@ import {
14
14
  } from 'node:fs'
15
15
  import { isAbsolute, join, relative, resolve } from 'node:path'
16
16
 
17
- import { privateAddressProblem, proxyConfigured } from '../../connector/web/guarded-fetch.js'
17
+ import {
18
+ checkedAddresses,
19
+ pinnedFetch,
20
+ proxyConfigured,
21
+ } from '../../connector/web/guarded-fetch.js'
22
+ import { temporaryPathFor } from '../../utils/atomic-write.js'
18
23
  import type { Logger } from '../../utils/logger.js'
19
24
 
20
25
  /** The most one read, one output stream or one answer body may hold. */
@@ -278,7 +283,7 @@ export function createCapabilityBridge(options: CapabilityBridgeOptions): Capabi
278
283
  }
279
284
  const path = storePath()
280
285
  mkdirSync(options.dataDir as string, { recursive: true, mode: 0o700 })
281
- const temporary = `${path}.${process.pid}.tmp`
286
+ const temporary = temporaryPathFor(path)
282
287
  writeFileSync(temporary, text, { mode: 0o600 })
283
288
  renameSync(temporary, path)
284
289
  }
@@ -457,14 +462,25 @@ export function createCapabilityBridge(options: CapabilityBridgeOptions): Capabi
457
462
  // not be followed there.
458
463
  let response: Response
459
464
  for (let hop = 0; ; hop++) {
460
- await assertReachable(parsed, deadline)
461
- response = await fetchImpl(parsed, {
462
- method,
463
- headers,
464
- ...(body !== undefined ? { body } : {}),
465
- redirect: 'manual',
466
- signal: deadline,
467
- })
465
+ const pinned = await assertReachable(parsed, deadline)
466
+ // The connection goes to the addresses that were checked, with the name kept for
467
+ // `Host` and TLS, so a name that answers differently the second time has no second
468
+ // answer to give. A host that supplies its own `fetch` is handed them as `pinnedAddresses`.
469
+ response =
470
+ pinned !== undefined && options.fetch === undefined
471
+ ? await pinnedFetch(
472
+ parsed,
473
+ { method, headers, ...(body !== undefined ? { body } : {}), signal: deadline },
474
+ pinned,
475
+ )
476
+ : await fetchImpl(parsed, {
477
+ method,
478
+ headers,
479
+ ...(body !== undefined ? { body } : {}),
480
+ redirect: 'manual',
481
+ signal: deadline,
482
+ ...(pinned !== undefined ? { pinnedAddresses: pinned } : {}),
483
+ } as RequestInit)
468
484
  const location = response.headers.get('location')
469
485
  if (response.status < 300 || response.status >= 400 || location === null) break
470
486
  await response.body?.cancel().catch(() => undefined)
@@ -504,7 +520,10 @@ export function createCapabilityBridge(options: CapabilityBridgeOptions): Capabi
504
520
  }
505
521
 
506
522
  /** Refuse an address a module may not reach: not https, or inside this machine's own network. */
507
- const assertReachable = async (target: URL, signal: AbortSignal): Promise<void> => {
523
+ const assertReachable = async (
524
+ target: URL,
525
+ signal: AbortSignal,
526
+ ): Promise<readonly string[] | undefined> => {
508
527
  if (target.protocol !== 'https:' && target.protocol !== 'http:') {
509
528
  throw new Error(`${target.protocol} is not http or https`)
510
529
  }
@@ -512,13 +531,16 @@ export function createCapabilityBridge(options: CapabilityBridgeOptions): Capabi
512
531
  if (target.protocol === 'http:' && !(options.allowLoopbackHttp === true && loopback)) {
513
532
  throw new Error(`${target.hostname}: only https addresses are fetched`)
514
533
  }
515
- if (options.allowLoopbackHttp === true && loopback) return
516
- const problem = await privateAddressProblem(target.hostname, {
534
+ if (options.allowLoopbackHttp === true && loopback) return undefined
535
+ const proxied = options.proxied ?? proxyConfigured(process.env, target.hostname)
536
+ const { problem, addresses } = await checkedAddresses(target.hostname, {
517
537
  ...(options.resolve !== undefined ? { resolve: options.resolve } : {}),
518
- proxied: options.proxied ?? proxyConfigured(process.env, target.hostname),
538
+ proxied,
519
539
  signal,
520
540
  })
521
541
  if (problem !== undefined) throw new Error(`${target.hostname} was not fetched: ${problem}`)
542
+ // Behind a proxy the proxy resolves the name and there is nothing to pin.
543
+ return proxied || addresses.length === 0 ? undefined : addresses
522
544
  }
523
545
  const allowedCalls =
524
546
  options.allowedCalls === undefined ? undefined : new Set(options.allowedCalls)
@@ -7,6 +7,7 @@ import type {
7
7
  } from '../../types/plugin/index.js'
8
8
  import { toErrorMessage } from '../../utils/error.js'
9
9
  import type { Logger } from '../../utils/logger.js'
10
+ import { restrictHookVerdict } from '../shell-hook-restrict.js'
10
11
  import {
11
12
  type ShellHookCall,
12
13
  type ShellHookEvent,
@@ -97,6 +98,27 @@ export const workerTransport: HookModuleTransportFactory = () => {
97
98
  }
98
99
  }
99
100
 
101
+ /**
102
+ * The nouns a module reaches the host through on `$`. A host that does not
103
+ * want a module to touch its files, processes or network names them in
104
+ * {@link StartHookModuleOptions.refuseCapabilities}.
105
+ */
106
+ export type HookModuleCapability = 'process' | 'fs' | 'http' | 'store' | 'env'
107
+
108
+ /**
109
+ * Every capability that reaches the machine the host runs on: programs
110
+ * (`process`), files (`fs`, and `store`, which is a file in the plugin's data
111
+ * folder), the network (`http`) and the host's variables (`env`). Leaves a
112
+ * module that computes and logs.
113
+ */
114
+ export const HOST_REACHING_CAPABILITIES: readonly HookModuleCapability[] = Object.freeze([
115
+ 'process',
116
+ 'fs',
117
+ 'http',
118
+ 'store',
119
+ 'env',
120
+ ])
121
+
100
122
  export interface StartHookModuleOptions {
101
123
  readonly plugin: {
102
124
  readonly name: string
@@ -119,6 +141,23 @@ export interface StartHookModuleOptions {
119
141
  readonly catchMs?: number
120
142
  readonly clock?: HookModuleClock
121
143
  readonly transport?: HookModuleTransportFactory
144
+ /**
145
+ * Refuse a module whose scan declares a call on any of these nouns of `$`
146
+ * (`$.process.run`, `$.fs.read`, `$.http.fetch`, ...). The module is not
147
+ * loaded, its guards answer as a failed guard does, and `message` says which
148
+ * call and where. The bridge also refuses a call on these nouns whatever a
149
+ * worker sends, so a call the scan did not see still goes nowhere. Absent,
150
+ * nothing is refused. When `shell.execute` is set and no `bridge` is given,
151
+ * `process` is refused too, since the bridge would start the program on the host.
152
+ */
153
+ readonly refuseCapabilities?: readonly HookModuleCapability[]
154
+ /**
155
+ * Answers the calls on `$` instead of the bridge made on this host, so a
156
+ * host that runs the worker (see {@link HOOK_WORKER_SOURCE} and
157
+ * `transport`) and its calls elsewhere owns both. Only the calls the
158
+ * module's scan declared, and `refuseCapabilities` does not name, reach it.
159
+ */
160
+ readonly bridge?: CapabilityBridge
122
161
  readonly environment?: Readonly<Record<string, string | undefined>>
123
162
  readonly fetch?: typeof fetch
124
163
  /** Called once, with the reason, when the module stops running for any cause but being disposed. */
@@ -358,18 +397,49 @@ export async function startHookModule(options: StartHookModuleOptions): Promise<
358
397
  )
359
398
  }
360
399
 
361
- const bridge: CapabilityBridge = createCapabilityBridge({
362
- root: plugin.root,
363
- ...(plugin.dataDir !== undefined ? { dataDir: plugin.dataDir } : {}),
364
- projectDir: options.projectDir,
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),
368
- ...(options.environment !== undefined ? { environment: options.environment } : {}),
369
- ...(options.fetch !== undefined ? { fetch: options.fetch } : {}),
370
- log,
371
- pluginName: plugin.name,
372
- })
400
+ // What the host will not let a module reach: named by the host, and a program on the host when
401
+ // the host's own hooks are run elsewhere and no bridge of its own was given.
402
+ const refused = new Set<string>(options.refuseCapabilities ?? [])
403
+ if (options.shell.execute !== undefined && options.bridge === undefined) refused.add('process')
404
+ const refusedCalls = scan.calls.filter((call) => refused.has(call.call.split('.')[1] ?? ''))
405
+ if (refusedCalls.length > 0) {
406
+ const first = refusedCalls[0]
407
+ const more = refusedCalls.length > 1 ? ` (and ${refusedCalls.length - 1} more)` : ''
408
+ return unloaded(
409
+ withRecovery(
410
+ `hooks module ${label} not loaded: ${first?.file}:${first?.line}: ${first?.call} is a call this host does not allow a module${more}`,
411
+ ),
412
+ guards,
413
+ )
414
+ }
415
+ const declaredCalls = scan.calls
416
+ .filter((call) => call.supported && !refused.has(call.call.split('.')[1] ?? ''))
417
+ .map((call) => call.call)
418
+ const own: CapabilityBridge | undefined = options.bridge
419
+ const bridge: CapabilityBridge =
420
+ own !== undefined
421
+ ? {
422
+ call: async (noun, method, args) => {
423
+ // What the module's own scan declared is all its calls reach, whatever the worker sends.
424
+ if (!declaredCalls.includes(`$.${noun}.${method}`)) {
425
+ throw new Error(`$.${noun}.${method} is not among the calls this module declares`)
426
+ }
427
+ return own.call(noun, method, args)
428
+ },
429
+ endProcesses: () => own.endProcesses(),
430
+ }
431
+ : createCapabilityBridge({
432
+ root: plugin.root,
433
+ ...(plugin.dataDir !== undefined ? { dataDir: plugin.dataDir } : {}),
434
+ projectDir: options.projectDir,
435
+ envNames: scan.envNames,
436
+ // What the module's own scan declared is all its calls reach, whatever the worker sends.
437
+ allowedCalls: declaredCalls,
438
+ ...(options.environment !== undefined ? { environment: options.environment } : {}),
439
+ ...(options.fetch !== undefined ? { fetch: options.fetch } : {}),
440
+ log,
441
+ pluginName: plugin.name,
442
+ })
373
443
 
374
444
  // --- the worker --------------------------------------------------------
375
445
  let transport: HookModuleTransport | undefined
@@ -671,13 +741,16 @@ export async function startHookModule(options: StartHookModuleOptions): Promise<
671
741
  ...(context.toolName !== undefined ? { toolName: context.toolName } : {}),
672
742
  ...(context.toolInput !== undefined ? { toolInput: context.toolInput } : {}),
673
743
  }
674
- return shellHookVerdict(
744
+ const verdict = shellHookVerdict(
675
745
  event,
676
746
  { type: 'command', command: commandLabel },
677
747
  { exitCode: 0, timedOut: false, stdout: JSON.stringify(json.json), stderr: '' },
678
748
  log,
679
749
  call,
680
750
  )
751
+ return options.shell.restrictVerdicts === true
752
+ ? restrictHookVerdict(verdict, log, { event, command: commandLabel })
753
+ : verdict
681
754
  },
682
755
  } as PluginHookDefinition)
683
756
  }
@@ -27,10 +27,12 @@ export type {
27
27
  export {
28
28
  HOOK_MODULE_BUDGET_MS,
29
29
  HOOK_MODULE_CATCH_MS,
30
+ HOST_REACHING_CAPABILITIES,
30
31
  startHookModule,
31
32
  workerTransport,
32
33
  } from './host.js'
33
34
  export type {
35
+ HookModuleCapability,
34
36
  HookModuleClock,
35
37
  HookModuleHandle,
36
38
  HookModuleTransport,
@@ -52,3 +54,4 @@ export {
52
54
  withHookModuleRecovery,
53
55
  } from './consent.js'
54
56
  export type { HookModuleConsentEntry, HookModuleSummary } from './consent.js'
57
+ export { HOOK_WORKER_SOURCE } from './worker-source.js'
@@ -50,6 +50,7 @@ export {
50
50
  shellHookMatches,
51
51
  shellHookVerdict,
52
52
  } from './shell-hook.js'
53
+ export { restrictHookVerdict } from './shell-hook-restrict.js'
53
54
  export {
54
55
  assignedWithin,
55
56
  isPluginFolderVariable,
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Running a hook command somewhere other than the host.
3
+ *
4
+ * A host that runs an agent's tools inside a sandbox cannot attach hooks that
5
+ * start as children of its own process: the hook would run outside the
6
+ * boundary the tools are held to. `ShellHookOptions.execute` is the seam. With
7
+ * it set, a command hook is handed to the caller's executor as a request, the
8
+ * executor runs it wherever the host keeps its tools, and what comes back
9
+ * becomes the hook's outcome. Nothing on this path starts a process in the host.
10
+ */
11
+
12
+ import type { ShellHookOutcome } from './shell-hook.js'
13
+
14
+ /** One command hook, as an executor receives it. */
15
+ export interface ShellHookExecRequest {
16
+ /**
17
+ * The exec form (`args` present): the program. The shell form (`args`
18
+ * absent): shell text to run with `sh -c`, which is the executor's to run.
19
+ */
20
+ readonly command: string
21
+ readonly args?: readonly string[]
22
+ /** The JSON object the hook reads on stdin. */
23
+ readonly stdin: string
24
+ /**
25
+ * The whole environment of the command. It is built from the hook's own
26
+ * variables and the host's `extraEnv`; the host process's environment is
27
+ * not in it.
28
+ */
29
+ readonly env: Readonly<Record<string, string>>
30
+ /** The folder the hook is run for, as the host names it; the executor maps it if its world differs. */
31
+ readonly cwd: string
32
+ /** The hook's deadline. */
33
+ readonly timeoutMs: number
34
+ /** Aborted at the deadline or when the turn is cancelled; the executor must end the command. */
35
+ readonly signal: AbortSignal
36
+ }
37
+
38
+ /** What an executor answers with once the command has ended. */
39
+ export interface ShellHookExecResult {
40
+ /** `null` when the command was ended by a signal. */
41
+ readonly exitCode: number | null
42
+ readonly stdout: string
43
+ readonly stderr: string
44
+ /** Set when the executor itself ended the command at the deadline. */
45
+ readonly timedOut?: boolean
46
+ }
47
+
48
+ /**
49
+ * Runs one command hook for a host. A rejection is the hook failing to start
50
+ * (reported as such), never a reason to run it on the host instead.
51
+ */
52
+ export type ShellHookExecutor = (request: ShellHookExecRequest) => Promise<ShellHookExecResult>
53
+
54
+ const messageOf = (error: unknown): string =>
55
+ error instanceof Error ? error.message : String(error)
56
+
57
+ /**
58
+ * Run `request` through `execute`, bounded by the request's deadline and the
59
+ * capture cap. The deadline is enforced here too: an executor that ignores the
60
+ * signal still does not hold the hook open past its time.
61
+ */
62
+ export function runThroughExecutor(
63
+ execute: ShellHookExecutor,
64
+ request: Omit<ShellHookExecRequest, 'signal'>,
65
+ cap: number,
66
+ signal: AbortSignal | undefined,
67
+ extra: Pick<ShellHookOutcome, 'unsetVariables'>,
68
+ ): Promise<ShellHookOutcome> {
69
+ return new Promise((resolve) => {
70
+ const controller = new AbortController()
71
+ let settled = false
72
+ const finish = (outcome: ShellHookOutcome): void => {
73
+ if (settled) return
74
+ settled = true
75
+ clearTimeout(timer)
76
+ signal?.removeEventListener('abort', onAbort)
77
+ controller.abort()
78
+ resolve({
79
+ ...outcome,
80
+ ...(extra.unsetVariables ? { unsetVariables: extra.unsetVariables } : {}),
81
+ })
82
+ }
83
+ const timer = setTimeout(
84
+ () => finish({ exitCode: null, timedOut: true, stdout: '', stderr: '' }),
85
+ request.timeoutMs,
86
+ )
87
+ const onAbort = (): void => controller.abort()
88
+ if (signal?.aborted) controller.abort()
89
+ else signal?.addEventListener('abort', onAbort, { once: true })
90
+ let running: Promise<ShellHookExecResult>
91
+ try {
92
+ running = execute({ ...request, signal: controller.signal })
93
+ } catch (error) {
94
+ finish({
95
+ exitCode: null,
96
+ timedOut: false,
97
+ stdout: '',
98
+ stderr: '',
99
+ spawnError: messageOf(error),
100
+ })
101
+ return
102
+ }
103
+ running.then(
104
+ (result) => {
105
+ const out = typeof result?.stdout === 'string' ? result.stdout : ''
106
+ const err = typeof result?.stderr === 'string' ? result.stderr : ''
107
+ const code = result?.exitCode
108
+ finish({
109
+ exitCode: typeof code === 'number' && Number.isInteger(code) ? code : null,
110
+ timedOut: result?.timedOut === true,
111
+ stdout: out.slice(0, cap),
112
+ stderr: err.slice(0, cap),
113
+ ...(out.length > cap ? { stdoutTruncated: true } : {}),
114
+ })
115
+ },
116
+ (error) =>
117
+ finish({
118
+ exitCode: null,
119
+ timedOut: false,
120
+ stdout: '',
121
+ stderr: '',
122
+ spawnError: messageOf(error),
123
+ }),
124
+ )
125
+ })
126
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Limiting what a hook's answer may do.
3
+ *
4
+ * A host that cannot vouch for the code behind a hook may still want its
5
+ * refusals and its notes to the model. `ShellHookOptions.restrictVerdicts`
6
+ * keeps those and drops every answer that widens what the session may do:
7
+ *
8
+ * - an `allow` (a hook's `permissionDecision: allow`, `decision: approve`, a
9
+ * module's `allow: true`) stands in for no one's yes; `ask` is kept, since it
10
+ * only sends the call to a person;
11
+ * - `updatedInput` does not rewrite the call;
12
+ * - `retry` does not run a call again;
13
+ * - an elicitation answer does not stand in for the person's;
14
+ * - a worktree folder, files to watch and a retryable mark are not taken.
15
+ *
16
+ * Kept: `deny`, `block`, `skip`, `error`, `halt`, `additionalContext`
17
+ * (`context`, `annotate`), notices, and a replacement of a tool's result
18
+ * (which only narrows what the model reads; a guard that failed closed
19
+ * answers with one).
20
+ */
21
+
22
+ import type { PluginHookResult } from '../types/plugin/index.js'
23
+ import type { Logger } from '../utils/logger.js'
24
+
25
+ /** What a restricted answer was stripped of, named for the log. */
26
+ function dropped(result: PluginHookResult): string[] {
27
+ const names: string[] = []
28
+ if (result.action === 'modify') names.push('updatedInput')
29
+ if (result.action === 'retry') names.push('retry')
30
+ if ('permission' in result && result.permission?.decision === 'allow') names.push('allow')
31
+ if ('elicitation' in result && result.elicitation !== undefined) names.push('elicitation')
32
+ if ('worktreePath' in result && result.worktreePath !== undefined) names.push('worktreePath')
33
+ if ('watchPaths' in result && result.watchPaths !== undefined) names.push('watchPaths')
34
+ if ('retryable' in result && result.retryable !== undefined) names.push('retryable')
35
+ return names
36
+ }
37
+
38
+ /**
39
+ * `result` as a restricted host accepts it. A verdict that only narrows is
40
+ * returned as it came; one that widens is returned without the widening part.
41
+ */
42
+ export function restrictHookVerdict(
43
+ result: PluginHookResult,
44
+ log: Logger,
45
+ where: { readonly event: string; readonly command: string },
46
+ ): PluginHookResult {
47
+ const names = dropped(result)
48
+ if (names.length === 0) return result
49
+ log.warn('a hook answer was narrowed by the host', {
50
+ 'namzu.hook.event': where.event,
51
+ 'namzu.hook.command': where.command,
52
+ 'namzu.hook.dropped': names.join(','),
53
+ })
54
+ if (result.action === 'retry') return { action: 'continue' }
55
+ const { elicitation, worktreePath, watchPaths, retryable, ...rest } = result as PluginHookResult &
56
+ Record<string, unknown>
57
+ const kept = rest as Record<string, unknown>
58
+ if (kept.action === 'modify') {
59
+ kept.action = 'continue'
60
+ kept.input = undefined
61
+ }
62
+ const permission = kept.permission as { decision: string } | undefined
63
+ if (permission?.decision === 'allow') kept.permission = undefined
64
+ for (const key of Object.keys(kept)) if (kept[key] === undefined) delete kept[key]
65
+ return kept as PluginHookResult
66
+ }
@@ -157,7 +157,9 @@ import {
157
157
  shellPathOutsideEnv,
158
158
  substituteMovedFolders,
159
159
  } from './shell-hook-env.js'
160
+ import { type ShellHookExecutor, runThroughExecutor } from './shell-hook-execute.js'
160
161
  import { postHookJson } from './shell-hook-http.js'
162
+ import { restrictHookVerdict } from './shell-hook-restrict.js'
161
163
  import { type ShellHookToolNames, shellHookToolName } from './shell-hook-tool-names.js'
162
164
  import { worktreeHookVerdict } from './worktree-hook-answer.js'
163
165
 
@@ -1004,11 +1006,18 @@ function isExecutableFile(path: string): boolean {
1004
1006
  }
1005
1007
  }
1006
1008
 
1007
- /** Run one hook command to completion, bounded by its deadline and capture. */
1009
+ /**
1010
+ * Run one hook command to completion, bounded by its deadline and capture.
1011
+ *
1012
+ * With `execute` the command goes to that executor and nothing is started in
1013
+ * this process: no fallback exists, and the host's own environment is not
1014
+ * handed over (the command gets the hook's variables and `extraEnv` only).
1015
+ */
1008
1016
  export function runShellHook(
1009
1017
  entry: ShellHookEntry,
1010
1018
  input: ShellHookInput,
1011
1019
  signal?: AbortSignal,
1020
+ execute?: ShellHookExecutor,
1012
1021
  ): Promise<ShellHookOutcome> {
1013
1022
  const timeoutMs = Math.min(
1014
1023
  MAX_SHELL_HOOK_TIMEOUT_MS,
@@ -1023,7 +1032,7 @@ export function runShellHook(
1023
1032
  NAMZU_TURN_ID: _inheritedTurnId,
1024
1033
  NAMZU_ENV_FILE: _inheritedEnvFile,
1025
1034
  ...inherited
1026
- } = process.env
1035
+ } = execute !== undefined ? ({} as NodeJS.ProcessEnv) : process.env
1027
1036
  const projectDir = input.projectDir ?? input.cwd
1028
1037
  const kernel = {
1029
1038
  NAMZU_HOOK_EVENT: input.event,
@@ -1074,6 +1083,27 @@ export function runShellHook(
1074
1083
  args: entry.args.map((arg) => substituteMovedFolders(arg, env)),
1075
1084
  }
1076
1085
  const unsetVariables = unset.length > 0 ? { unsetVariables: unset } : {}
1086
+ if (execute !== undefined) {
1087
+ // Nothing below this block runs: no host folder is made, no host process is started.
1088
+ const sent: Record<string, string> = {}
1089
+ for (const [name, value] of Object.entries(withSessionChildMarker(withSafeGitConfig(env)))) {
1090
+ if (typeof value === 'string') sent[name] = value
1091
+ }
1092
+ return runThroughExecutor(
1093
+ execute,
1094
+ {
1095
+ command: placed.command,
1096
+ ...(placed.args !== undefined ? { args: placed.args } : {}),
1097
+ stdin: payload,
1098
+ env: sent,
1099
+ cwd: input.cwd,
1100
+ timeoutMs,
1101
+ },
1102
+ MAX_CAPTURE_BYTES,
1103
+ signal,
1104
+ unsetVariables,
1105
+ )
1106
+ }
1077
1107
  if (pluginFolders !== undefined) {
1078
1108
  try {
1079
1109
  // Created when first needed; never inside the plugin's own folder.
@@ -2159,6 +2189,26 @@ export interface ShellHookOptions {
2159
2189
  * Without it no hook gets the variable and nothing is carried.
2160
2190
  */
2161
2191
  readonly hookEnv?: SessionHookEnv
2192
+ /**
2193
+ * Runs every command hook of this adapter somewhere other than this process
2194
+ * (a sandbox the host keeps its tools in). With it set, no hook command is
2195
+ * ever started as a child of the host, whatever the event: a request the
2196
+ * executor cannot serve fails the hook, it does not run on the host. The
2197
+ * command gets the hook's own variables and `extraEnv`, not the host's
2198
+ * environment, and the plugin's data folder is not made here. A hook that
2199
+ * writes variables for later commands (`NAMZU_ENV_FILE`) is not given the
2200
+ * file, which is a host path. `http`, `prompt` and `mcp_tool` hooks start no
2201
+ * process and are not routed through it.
2202
+ */
2203
+ readonly execute?: ShellHookExecutor
2204
+ /**
2205
+ * Accept only the answers that narrow: `deny`, `block`, `skip`, errors,
2206
+ * `additionalContext`, notices and `halt`. An `allow`, `permissionDecision:
2207
+ * allow`, `updatedInput`, `retry` and the other answers that widen what the
2208
+ * session may do are dropped, whichever hook gave them. Absent, every answer
2209
+ * is read as before.
2210
+ */
2211
+ readonly restrictVerdicts?: boolean
2162
2212
  /**
2163
2213
  * Called when a hook of this adapter ran out its deadline and was ended.
2164
2214
  * `hook` is the command, URL or prompt text the entry names.
@@ -2346,6 +2396,7 @@ async function runWorktreeHook(
2346
2396
  input: ShellHookInput,
2347
2397
  signal: AbortSignal | undefined,
2348
2398
  reportTimeout: (timedOut: boolean) => void,
2399
+ execute: ShellHookExecutor | undefined,
2349
2400
  ): Promise<PluginHookResult> {
2350
2401
  const label = describeShellHook(entry)
2351
2402
  if (entry.type === 'prompt' || entry.type === 'mcp_tool') {
@@ -2373,7 +2424,7 @@ async function runWorktreeHook(
2373
2424
  ...(response.error !== undefined ? { spawnError: response.error } : {}),
2374
2425
  })
2375
2426
  }
2376
- const outcome = await runShellHook(entry, input, signal)
2427
+ const outcome = await runShellHook(entry, input, signal, execute)
2377
2428
  reportTimeout(outcome.timedOut)
2378
2429
  return worktreeHookVerdict(event, label, outcome)
2379
2430
  }
@@ -2483,7 +2534,7 @@ export function createShellHook(
2483
2534
  let spent = false
2484
2535
  // The shell verdict branches on `event`, but TypeScript cannot retain that
2485
2536
  // correlation across the async handler closure and the union of events.
2486
- return {
2537
+ const definition = {
2487
2538
  event,
2488
2539
  ...(entry.statusMessage !== undefined ? { statusMessage: entry.statusMessage } : {}),
2489
2540
  // A file named by the matcher is watched for as long as the hook is attached.
@@ -2570,8 +2621,9 @@ export function createShellHook(
2570
2621
  ? event
2571
2622
  : undefined
2572
2623
  const runsACommand = entry.type === undefined || entry.type === 'command'
2624
+ // The variables file is a host path; a command run elsewhere is not given it.
2573
2625
  const envFile =
2574
- envEvent !== undefined && runsACommand
2626
+ envEvent !== undefined && runsACommand && options.execute === undefined
2575
2627
  ? options.hookEnv?.fileFor(envEvent, envSlot)
2576
2628
  : undefined
2577
2629
  const hookInput = shellHookInputFor(event, context, options, {
@@ -2583,7 +2635,14 @@ export function createShellHook(
2583
2635
  ...(context.toolInput !== undefined ? { toolInput: context.toolInput } : {}),
2584
2636
  }
2585
2637
  if (event === 'worktree_create' || event === 'worktree_remove') {
2586
- return runWorktreeHook(event, entry, hookInput, context.signal, reportTimeout)
2638
+ return runWorktreeHook(
2639
+ event,
2640
+ entry,
2641
+ hookInput,
2642
+ context.signal,
2643
+ reportTimeout,
2644
+ options.execute,
2645
+ )
2587
2646
  }
2588
2647
  if (entry.type === 'http') {
2589
2648
  const response = await postHookJson({
@@ -2627,9 +2686,10 @@ export function createShellHook(
2627
2686
  if (entry.async === true) {
2628
2687
  // Started and left running: it decides nothing, so nothing waits
2629
2688
  // for it and its own failure is only written down.
2630
- void runShellHook(entry, hookInput)
2689
+ void runShellHook(entry, hookInput, undefined, options.execute)
2631
2690
  .then((outcome) => {
2632
- if (envEvent !== undefined) options.hookEnv?.absorb(envEvent, envSlot)
2691
+ if (envEvent !== undefined && options.execute === undefined)
2692
+ options.hookEnv?.absorb(envEvent, envSlot)
2633
2693
  const verdict = shellHookVerdict(event, entry, outcome, log, verdictCall)
2634
2694
  if (verdict.action !== 'continue') {
2635
2695
  log.warn('an async hook answered, and its answer is not applied', {
@@ -2642,14 +2702,22 @@ export function createShellHook(
2642
2702
  .catch(() => undefined)
2643
2703
  return { action: 'continue' }
2644
2704
  }
2645
- const outcome = await runShellHook(entry, hookInput, context.signal)
2705
+ const outcome = await runShellHook(entry, hookInput, context.signal, options.execute)
2646
2706
  // What the hook appended counts even when it was ended or failed after
2647
2707
  // writing it: the lines are data it already gave.
2648
- if (envEvent !== undefined) options.hookEnv?.absorb(envEvent, envSlot)
2708
+ if (envEvent !== undefined && options.execute === undefined)
2709
+ options.hookEnv?.absorb(envEvent, envSlot)
2649
2710
  reportTimeout(outcome.timedOut)
2650
2711
  return shellHookVerdict(event, entry, outcome, log, verdictCall)
2651
2712
  },
2652
2713
  } as PluginHookDefinition
2714
+ if (options.restrictVerdicts !== true) return definition
2715
+ const where = { event, command: describeShellHook(entry) }
2716
+ return {
2717
+ ...definition,
2718
+ handler: async (context: PluginHookContext) =>
2719
+ restrictHookVerdict(await definition.handler(context as never), log, where),
2720
+ } as PluginHookDefinition
2653
2721
  }
2654
2722
 
2655
2723
  /**