@namzu/sdk 71.0.1 → 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 (268) hide show
  1. package/CHANGELOG.md +126 -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/authorization/readonly-commands.d.ts +9 -1
  6. package/dist/authorization/readonly-commands.d.ts.map +1 -1
  7. package/dist/authorization/readonly-commands.js +70 -4
  8. package/dist/authorization/readonly-commands.js.map +1 -1
  9. package/dist/authorization/shell-paths.d.ts.map +1 -1
  10. package/dist/authorization/shell-paths.js +68 -16
  11. package/dist/authorization/shell-paths.js.map +1 -1
  12. package/dist/compaction/index.d.ts +1 -1
  13. package/dist/compaction/index.d.ts.map +1 -1
  14. package/dist/compaction/index.js +1 -1
  15. package/dist/compaction/index.js.map +1 -1
  16. package/dist/compaction/manual.d.ts +8 -0
  17. package/dist/compaction/manual.d.ts.map +1 -1
  18. package/dist/compaction/manual.js +18 -14
  19. package/dist/compaction/manual.js.map +1 -1
  20. package/dist/compaction/model-summary.d.ts +24 -6
  21. package/dist/compaction/model-summary.d.ts.map +1 -1
  22. package/dist/compaction/model-summary.js +152 -28
  23. package/dist/compaction/model-summary.js.map +1 -1
  24. package/dist/compaction/restore.d.ts +23 -0
  25. package/dist/compaction/restore.d.ts.map +1 -1
  26. package/dist/compaction/restore.js +59 -1
  27. package/dist/compaction/restore.js.map +1 -1
  28. package/dist/compaction/summary.d.ts +37 -2
  29. package/dist/compaction/summary.d.ts.map +1 -1
  30. package/dist/compaction/summary.js +46 -6
  31. package/dist/compaction/summary.js.map +1 -1
  32. package/dist/config/registry.d.ts +2 -0
  33. package/dist/config/registry.d.ts.map +1 -1
  34. package/dist/config/registry.js +76 -5
  35. package/dist/config/registry.js.map +1 -1
  36. package/dist/config/runtime.js +3 -3
  37. package/dist/config/runtime.js.map +1 -1
  38. package/dist/connector/index.d.ts +2 -2
  39. package/dist/connector/index.d.ts.map +1 -1
  40. package/dist/connector/index.js +1 -1
  41. package/dist/connector/index.js.map +1 -1
  42. package/dist/connector/mcp/adapter.d.ts +8 -0
  43. package/dist/connector/mcp/adapter.d.ts.map +1 -1
  44. package/dist/connector/mcp/adapter.js +131 -1
  45. package/dist/connector/mcp/adapter.js.map +1 -1
  46. package/dist/connector/mcp/client.d.ts +26 -6
  47. package/dist/connector/mcp/client.d.ts.map +1 -1
  48. package/dist/connector/mcp/client.js +49 -7
  49. package/dist/connector/mcp/client.js.map +1 -1
  50. package/dist/connector/mcp/index.d.ts +2 -0
  51. package/dist/connector/mcp/index.d.ts.map +1 -1
  52. package/dist/connector/mcp/index.js +1 -0
  53. package/dist/connector/mcp/index.js.map +1 -1
  54. package/dist/connector/mcp/sandbox-stdio.d.ts +67 -0
  55. package/dist/connector/mcp/sandbox-stdio.d.ts.map +1 -0
  56. package/dist/connector/mcp/sandbox-stdio.js +178 -0
  57. package/dist/connector/mcp/sandbox-stdio.js.map +1 -0
  58. package/dist/connector/mcp/stdio-program.d.ts +34 -0
  59. package/dist/connector/mcp/stdio-program.d.ts.map +1 -0
  60. package/dist/connector/mcp/stdio-program.js +47 -0
  61. package/dist/connector/mcp/stdio-program.js.map +1 -0
  62. package/dist/connector/mcp/stdio.d.ts +12 -0
  63. package/dist/connector/mcp/stdio.d.ts.map +1 -1
  64. package/dist/connector/mcp/stdio.js +54 -7
  65. package/dist/connector/mcp/stdio.js.map +1 -1
  66. package/dist/connector/web/guarded-fetch.d.ts +51 -2
  67. package/dist/connector/web/guarded-fetch.d.ts.map +1 -1
  68. package/dist/connector/web/guarded-fetch.js +140 -19
  69. package/dist/connector/web/guarded-fetch.js.map +1 -1
  70. package/dist/connector/web/index.d.ts +2 -2
  71. package/dist/connector/web/index.d.ts.map +1 -1
  72. package/dist/connector/web/index.js +1 -1
  73. package/dist/connector/web/index.js.map +1 -1
  74. package/dist/constants/mcp/index.d.ts +29 -0
  75. package/dist/constants/mcp/index.d.ts.map +1 -1
  76. package/dist/constants/mcp/index.js +29 -0
  77. package/dist/constants/mcp/index.js.map +1 -1
  78. package/dist/manager/agent/lifecycle.d.ts +18 -1
  79. package/dist/manager/agent/lifecycle.d.ts.map +1 -1
  80. package/dist/manager/agent/lifecycle.js +53 -8
  81. package/dist/manager/agent/lifecycle.js.map +1 -1
  82. package/dist/plugin/hook-module/capabilities.d.ts.map +1 -1
  83. package/dist/plugin/hook-module/capabilities.js +24 -13
  84. package/dist/plugin/hook-module/capabilities.js.map +1 -1
  85. package/dist/plugin/hook-module/host.d.ts +31 -0
  86. package/dist/plugin/hook-module/host.d.ts.map +1 -1
  87. package/dist/plugin/hook-module/host.js +56 -13
  88. package/dist/plugin/hook-module/host.js.map +1 -1
  89. package/dist/plugin/hook-module/index.d.ts +3 -2
  90. package/dist/plugin/hook-module/index.d.ts.map +1 -1
  91. package/dist/plugin/hook-module/index.js +2 -1
  92. package/dist/plugin/hook-module/index.js.map +1 -1
  93. package/dist/plugin/index.d.ts +2 -1
  94. package/dist/plugin/index.d.ts.map +1 -1
  95. package/dist/plugin/index.js +1 -0
  96. package/dist/plugin/index.js.map +1 -1
  97. package/dist/plugin/shell-hook-execute.d.ts +55 -0
  98. package/dist/plugin/shell-hook-execute.d.ts.map +1 -0
  99. package/dist/plugin/shell-hook-execute.js +73 -0
  100. package/dist/plugin/shell-hook-execute.js.map +1 -0
  101. package/dist/plugin/shell-hook-restrict.d.ts +31 -0
  102. package/dist/plugin/shell-hook-restrict.d.ts.map +1 -0
  103. package/dist/plugin/shell-hook-restrict.js +69 -0
  104. package/dist/plugin/shell-hook-restrict.js.map +1 -0
  105. package/dist/plugin/shell-hook.d.ts +73 -4
  106. package/dist/plugin/shell-hook.d.ts.map +1 -1
  107. package/dist/plugin/shell-hook.js +118 -17
  108. package/dist/plugin/shell-hook.js.map +1 -1
  109. package/dist/public-runtime.d.ts +9 -7
  110. package/dist/public-runtime.d.ts.map +1 -1
  111. package/dist/public-runtime.js +6 -5
  112. package/dist/public-runtime.js.map +1 -1
  113. package/dist/public-types.d.ts +4 -2
  114. package/dist/public-types.d.ts.map +1 -1
  115. package/dist/runtime/jobs/websocket-source.d.ts +2 -22
  116. package/dist/runtime/jobs/websocket-source.d.ts.map +1 -1
  117. package/dist/runtime/jobs/websocket-source.js +2 -33
  118. package/dist/runtime/jobs/websocket-source.js.map +1 -1
  119. package/dist/runtime/query/compact-session.d.ts.map +1 -1
  120. package/dist/runtime/query/compact-session.js +5 -0
  121. package/dist/runtime/query/compact-session.js.map +1 -1
  122. package/dist/runtime/query/events.d.ts +7 -0
  123. package/dist/runtime/query/events.d.ts.map +1 -1
  124. package/dist/runtime/query/events.js +29 -11
  125. package/dist/runtime/query/events.js.map +1 -1
  126. package/dist/runtime/query/executor/tool-call-admission.d.ts.map +1 -1
  127. package/dist/runtime/query/executor/tool-call-admission.js +51 -10
  128. package/dist/runtime/query/executor/tool-call-admission.js.map +1 -1
  129. package/dist/runtime/query/index.d.ts +6 -0
  130. package/dist/runtime/query/index.d.ts.map +1 -1
  131. package/dist/runtime/query/index.js +3 -0
  132. package/dist/runtime/query/index.js.map +1 -1
  133. package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
  134. package/dist/runtime/query/iteration/phases/compaction.js +21 -3
  135. package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
  136. package/dist/runtime/query/iteration/phases/context.d.ts +4 -0
  137. package/dist/runtime/query/iteration/phases/context.d.ts.map +1 -1
  138. package/dist/runtime/query/iteration/phases/context.js.map +1 -1
  139. package/dist/runtime/query/path-escalation.d.ts.map +1 -1
  140. package/dist/runtime/query/path-escalation.js +90 -17
  141. package/dist/runtime/query/path-escalation.js.map +1 -1
  142. package/dist/runtime/query/steering.d.ts +15 -0
  143. package/dist/runtime/query/steering.d.ts.map +1 -1
  144. package/dist/runtime/query/steering.js +27 -3
  145. package/dist/runtime/query/steering.js.map +1 -1
  146. package/dist/scheduler/completion-inbox.d.ts.map +1 -1
  147. package/dist/scheduler/completion-inbox.js +15 -0
  148. package/dist/scheduler/completion-inbox.js.map +1 -1
  149. package/dist/session/workspace/driver.d.ts +12 -0
  150. package/dist/session/workspace/driver.d.ts.map +1 -1
  151. package/dist/session/workspace/git-worktree.d.ts +16 -0
  152. package/dist/session/workspace/git-worktree.d.ts.map +1 -1
  153. package/dist/session/workspace/git-worktree.js +35 -0
  154. package/dist/session/workspace/git-worktree.js.map +1 -1
  155. package/dist/session/workspace/holds.d.ts +78 -0
  156. package/dist/session/workspace/holds.d.ts.map +1 -0
  157. package/dist/session/workspace/holds.js +150 -0
  158. package/dist/session/workspace/holds.js.map +1 -0
  159. package/dist/session/workspace/index.d.ts +3 -1
  160. package/dist/session/workspace/index.d.ts.map +1 -1
  161. package/dist/session/workspace/index.js +2 -1
  162. package/dist/session/workspace/index.js.map +1 -1
  163. package/dist/store/config/index.d.ts +3 -0
  164. package/dist/store/config/index.d.ts.map +1 -1
  165. package/dist/store/config/index.js +3 -0
  166. package/dist/store/config/index.js.map +1 -1
  167. package/dist/store/session-index/index.d.ts +13 -0
  168. package/dist/store/session-index/index.d.ts.map +1 -1
  169. package/dist/store/session-index/index.js +1 -0
  170. package/dist/store/session-index/index.js.map +1 -1
  171. package/dist/store/session-index/rebuild.d.ts +12 -0
  172. package/dist/store/session-index/rebuild.d.ts.map +1 -1
  173. package/dist/store/session-index/rebuild.js +20 -4
  174. package/dist/store/session-index/rebuild.js.map +1 -1
  175. package/dist/store/session-index/sqlite.d.ts +20 -0
  176. package/dist/store/session-index/sqlite.d.ts.map +1 -1
  177. package/dist/store/session-index/sqlite.js +50 -12
  178. package/dist/store/session-index/sqlite.js.map +1 -1
  179. package/dist/tools/admit-facts.d.ts.map +1 -1
  180. package/dist/tools/admit-facts.js +59 -0
  181. package/dist/tools/admit-facts.js.map +1 -1
  182. package/dist/tools/builtins/grep.d.ts.map +1 -1
  183. package/dist/tools/builtins/grep.js +57 -0
  184. package/dist/tools/builtins/grep.js.map +1 -1
  185. package/dist/tools/builtins/lsp.d.ts.map +1 -1
  186. package/dist/tools/builtins/lsp.js +41 -4
  187. package/dist/tools/builtins/lsp.js.map +1 -1
  188. package/dist/tools/coordinator/ask-user-question.d.ts.map +1 -1
  189. package/dist/tools/coordinator/ask-user-question.js +67 -3
  190. package/dist/tools/coordinator/ask-user-question.js.map +1 -1
  191. package/dist/turn/memory-promoter.d.ts.map +1 -1
  192. package/dist/turn/memory-promoter.js +20 -4
  193. package/dist/turn/memory-promoter.js.map +1 -1
  194. package/dist/types/agent/base.d.ts +6 -0
  195. package/dist/types/agent/base.d.ts.map +1 -1
  196. package/dist/types/agent/task.d.ts +5 -0
  197. package/dist/types/agent/task.d.ts.map +1 -1
  198. package/dist/types/agent/task.js.map +1 -1
  199. package/dist/types/code-navigation/index.d.ts +34 -4
  200. package/dist/types/code-navigation/index.d.ts.map +1 -1
  201. package/dist/types/hitl/index.d.ts +8 -0
  202. package/dist/types/hitl/index.d.ts.map +1 -1
  203. package/dist/types/hitl/index.js.map +1 -1
  204. package/dist/types/message/index.d.ts +7 -0
  205. package/dist/types/message/index.d.ts.map +1 -1
  206. package/dist/types/message/index.js.map +1 -1
  207. package/dist/types/tool/presentation.d.ts +21 -0
  208. package/dist/types/tool/presentation.d.ts.map +1 -1
  209. package/package.json +6 -6
  210. package/src/agents/QueryAgent.ts +1 -0
  211. package/src/authorization/readonly-commands.ts +72 -4
  212. package/src/authorization/shell-paths.ts +75 -18
  213. package/src/compaction/index.ts +1 -0
  214. package/src/compaction/manual.ts +48 -12
  215. package/src/compaction/model-summary.ts +163 -28
  216. package/src/compaction/restore.ts +74 -1
  217. package/src/compaction/summary.ts +69 -3
  218. package/src/config/registry.ts +87 -5
  219. package/src/config/runtime.ts +3 -3
  220. package/src/connector/index.ts +3 -0
  221. package/src/connector/mcp/adapter.ts +137 -1
  222. package/src/connector/mcp/client.ts +49 -7
  223. package/src/connector/mcp/index.ts +5 -0
  224. package/src/connector/mcp/sandbox-stdio.ts +214 -0
  225. package/src/connector/mcp/stdio-program.ts +68 -0
  226. package/src/connector/mcp/stdio.ts +61 -7
  227. package/src/connector/web/guarded-fetch.ts +197 -30
  228. package/src/connector/web/index.ts +4 -1
  229. package/src/constants/mcp/index.ts +31 -0
  230. package/src/manager/agent/lifecycle.ts +58 -13
  231. package/src/plugin/hook-module/capabilities.ts +36 -14
  232. package/src/plugin/hook-module/host.ts +86 -13
  233. package/src/plugin/hook-module/index.ts +3 -0
  234. package/src/plugin/index.ts +4 -0
  235. package/src/plugin/shell-hook-execute.ts +126 -0
  236. package/src/plugin/shell-hook-restrict.ts +66 -0
  237. package/src/plugin/shell-hook.ts +209 -16
  238. package/src/public-runtime.ts +19 -0
  239. package/src/public-types.ts +20 -0
  240. package/src/runtime/jobs/websocket-source.ts +2 -46
  241. package/src/runtime/query/compact-session.ts +5 -0
  242. package/src/runtime/query/events.ts +29 -11
  243. package/src/runtime/query/executor/tool-call-admission.ts +62 -17
  244. package/src/runtime/query/index.ts +10 -0
  245. package/src/runtime/query/iteration/phases/compaction.ts +26 -2
  246. package/src/runtime/query/iteration/phases/context.ts +6 -0
  247. package/src/runtime/query/path-escalation.ts +102 -16
  248. package/src/runtime/query/steering.ts +38 -3
  249. package/src/scheduler/completion-inbox.ts +14 -0
  250. package/src/session/workspace/driver.ts +12 -0
  251. package/src/session/workspace/git-worktree.ts +49 -0
  252. package/src/session/workspace/holds.ts +201 -0
  253. package/src/session/workspace/index.ts +13 -1
  254. package/src/store/config/index.ts +6 -0
  255. package/src/store/session-index/index.ts +14 -0
  256. package/src/store/session-index/rebuild.ts +22 -4
  257. package/src/store/session-index/sqlite.ts +63 -14
  258. package/src/tools/admit-facts.ts +64 -0
  259. package/src/tools/builtins/grep.ts +52 -0
  260. package/src/tools/builtins/lsp.ts +47 -4
  261. package/src/tools/coordinator/ask-user-question.ts +88 -4
  262. package/src/turn/memory-promoter.ts +24 -3
  263. package/src/types/agent/base.ts +7 -0
  264. package/src/types/agent/task.ts +5 -0
  265. package/src/types/code-navigation/index.ts +48 -4
  266. package/src/types/hitl/index.ts +8 -0
  267. package/src/types/message/index.ts +7 -0
  268. 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,
@@ -68,11 +69,14 @@ export {
68
69
  } from './shell-hook-tool-names.js'
69
70
  export type {
70
71
  HttpHookEntry,
72
+ McpToolHookEntry,
71
73
  PromptHookEntry,
72
74
  ShellHookEntry,
73
75
  ShellHookEvent,
74
76
  ShellHookHandler,
75
77
  ShellHookJudge,
78
+ ShellHookMcpToolAnswer,
79
+ ShellHookMcpToolCaller,
76
80
  ShellHookOnFailure,
77
81
  ShellHookCall,
78
82
  ShellHookInput,
@@ -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
+ }