@kirkchinese/harness-forge 0.0.0-stage → 0.4.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 (246) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +42 -2
  3. package/assets/icon.svg +12 -0
  4. package/cordis.patch.yml +28 -0
  5. package/lib/agents/presets.d.ts +91 -0
  6. package/lib/agents/presets.js +282 -0
  7. package/lib/agents/profiles.d.ts +58 -0
  8. package/lib/agents/profiles.js +278 -0
  9. package/lib/agents/row.d.ts +17 -0
  10. package/lib/agents/row.js +146 -0
  11. package/lib/client/styles.d.ts +8 -0
  12. package/lib/client/styles.js +89 -0
  13. package/lib/client/typert.d.ts +14 -0
  14. package/lib/client/typert.js +110 -0
  15. package/lib/client.js +22500 -0
  16. package/lib/commands/definition.d.ts +40 -0
  17. package/lib/commands/definition.js +113 -0
  18. package/lib/commands/output-styles.d.ts +42 -0
  19. package/lib/commands/output-styles.js +152 -0
  20. package/lib/commands/row.d.ts +9 -0
  21. package/lib/commands/row.js +157 -0
  22. package/lib/context/instructions.d.ts +32 -0
  23. package/lib/context/instructions.js +88 -0
  24. package/lib/context/row.d.ts +16 -0
  25. package/lib/context/row.js +17 -0
  26. package/lib/dsh/commands.d.ts +30 -0
  27. package/lib/dsh/commands.js +61 -0
  28. package/lib/dsh/host.d.ts +107 -0
  29. package/lib/dsh/host.js +214 -0
  30. package/lib/dsh/model-route.d.ts +21 -0
  31. package/lib/dsh/model-route.js +37 -0
  32. package/lib/dsh/session-records.d.ts +78 -0
  33. package/lib/dsh/session-records.js +36 -0
  34. package/lib/dsh/subagents.d.ts +46 -0
  35. package/lib/dsh/subagents.js +14 -0
  36. package/lib/forge/contract.d.ts +231 -0
  37. package/lib/forge/contract.js +43 -0
  38. package/lib/forge/ledger.d.ts +143 -0
  39. package/lib/forge/ledger.js +733 -0
  40. package/lib/forge/live-mounts.d.ts +45 -0
  41. package/lib/forge/live-mounts.js +78 -0
  42. package/lib/forge/marketplace-install.d.ts +3 -0
  43. package/lib/forge/marketplace-install.js +64 -0
  44. package/lib/forge/npm.d.ts +31 -0
  45. package/lib/forge/npm.js +60 -0
  46. package/lib/forge/projects.d.ts +94 -0
  47. package/lib/forge/projects.js +336 -0
  48. package/lib/forge/receipts.d.ts +5 -0
  49. package/lib/forge/receipts.js +31 -0
  50. package/lib/forge/row.d.ts +32 -0
  51. package/lib/forge/row.js +59 -0
  52. package/lib/forge/service.d.ts +105 -0
  53. package/lib/forge/service.js +274 -0
  54. package/lib/forge/settings.d.ts +41 -0
  55. package/lib/forge/settings.js +115 -0
  56. package/lib/forge/state.d.ts +69 -0
  57. package/lib/forge/state.js +150 -0
  58. package/lib/forge/trust.d.ts +48 -0
  59. package/lib/forge/trust.js +107 -0
  60. package/lib/forge/turns.d.ts +13 -0
  61. package/lib/forge/turns.js +56 -0
  62. package/lib/hooks/broker/engine.d.ts +112 -0
  63. package/lib/hooks/broker/engine.js +728 -0
  64. package/lib/hooks/broker/helpers.d.ts +10 -0
  65. package/lib/hooks/broker/helpers.js +22 -0
  66. package/lib/hooks/broker/lifecycle.d.ts +65 -0
  67. package/lib/hooks/broker/lifecycle.js +342 -0
  68. package/lib/hooks/broker/session-events.d.ts +22 -0
  69. package/lib/hooks/broker/session-events.js +196 -0
  70. package/lib/hooks/broker/tools.d.ts +52 -0
  71. package/lib/hooks/broker/tools.js +424 -0
  72. package/lib/hooks/broker/types.d.ts +262 -0
  73. package/lib/hooks/broker/types.js +1 -0
  74. package/lib/hooks/broker.d.ts +80 -0
  75. package/lib/hooks/broker.js +95 -0
  76. package/lib/hooks/codex-user.d.ts +5 -0
  77. package/lib/hooks/codex-user.js +109 -0
  78. package/lib/hooks/condition.d.ts +11 -0
  79. package/lib/hooks/condition.js +181 -0
  80. package/lib/hooks/config.d.ts +85 -0
  81. package/lib/hooks/config.js +150 -0
  82. package/lib/hooks/matcher.d.ts +20 -0
  83. package/lib/hooks/matcher.js +39 -0
  84. package/lib/hooks/notice.d.ts +17 -0
  85. package/lib/hooks/notice.js +39 -0
  86. package/lib/hooks/output.d.ts +56 -0
  87. package/lib/hooks/output.js +214 -0
  88. package/lib/hooks/permissions.d.ts +14 -0
  89. package/lib/hooks/permissions.js +109 -0
  90. package/lib/hooks/process.d.ts +47 -0
  91. package/lib/hooks/process.js +134 -0
  92. package/lib/hooks/row.d.ts +17 -0
  93. package/lib/hooks/row.js +94 -0
  94. package/lib/hooks/runner.d.ts +85 -0
  95. package/lib/hooks/runner.js +293 -0
  96. package/lib/hooks/shell-commands.d.ts +19 -0
  97. package/lib/hooks/shell-commands.js +177 -0
  98. package/lib/hooks/shell.d.ts +43 -0
  99. package/lib/hooks/shell.js +126 -0
  100. package/lib/hooks/transcript.d.ts +28 -0
  101. package/lib/hooks/transcript.js +141 -0
  102. package/lib/hooks/vocabulary.d.ts +57 -0
  103. package/lib/hooks/vocabulary.js +364 -0
  104. package/lib/index.d.ts +31 -0
  105. package/lib/index.js +287 -0
  106. package/lib/mcp/auth.d.ts +35 -0
  107. package/lib/mcp/auth.js +178 -0
  108. package/lib/mcp/catalog.d.ts +36 -0
  109. package/lib/mcp/catalog.js +61 -0
  110. package/lib/mcp/mount.d.ts +75 -0
  111. package/lib/mcp/mount.js +217 -0
  112. package/lib/mcp/remote.d.ts +45 -0
  113. package/lib/mcp/remote.js +143 -0
  114. package/lib/mcp/row.d.ts +9 -0
  115. package/lib/mcp/row.js +131 -0
  116. package/lib/mods/bundler.d.ts +38 -0
  117. package/lib/mods/bundler.js +157 -0
  118. package/lib/mods/chain.d.ts +103 -0
  119. package/lib/mods/chain.js +436 -0
  120. package/lib/mods/claude.d.ts +27 -0
  121. package/lib/mods/claude.js +56 -0
  122. package/lib/mods/engine.d.ts +160 -0
  123. package/lib/mods/engine.js +701 -0
  124. package/lib/mods/expect.d.ts +8 -0
  125. package/lib/mods/expect.js +248 -0
  126. package/lib/mods/host.d.ts +105 -0
  127. package/lib/mods/host.js +462 -0
  128. package/lib/mods/loader.d.ts +53 -0
  129. package/lib/mods/loader.js +227 -0
  130. package/lib/mods/ops.d.ts +13 -0
  131. package/lib/mods/ops.js +117 -0
  132. package/lib/mods/row.d.ts +9 -0
  133. package/lib/mods/row.js +77 -0
  134. package/lib/mods/runtime.d.ts +60 -0
  135. package/lib/mods/runtime.js +133 -0
  136. package/lib/mods/service/commands.d.ts +17 -0
  137. package/lib/mods/service/commands.js +121 -0
  138. package/lib/mods/service/drawings.d.ts +36 -0
  139. package/lib/mods/service/drawings.js +64 -0
  140. package/lib/mods/service/sessions.d.ts +63 -0
  141. package/lib/mods/service/sessions.js +345 -0
  142. package/lib/mods/service/tools.d.ts +32 -0
  143. package/lib/mods/service/tools.js +253 -0
  144. package/lib/mods/service/turns.d.ts +32 -0
  145. package/lib/mods/service/turns.js +161 -0
  146. package/lib/mods/service/types.d.ts +151 -0
  147. package/lib/mods/service/types.js +1 -0
  148. package/lib/mods/service.d.ts +72 -0
  149. package/lib/mods/service.js +104 -0
  150. package/lib/mods/surfaces.d.ts +93 -0
  151. package/lib/mods/surfaces.js +309 -0
  152. package/lib/mods/values.d.ts +30 -0
  153. package/lib/mods/values.js +95 -0
  154. package/lib/opencode/bun.d.ts +40 -0
  155. package/lib/opencode/bun.js +156 -0
  156. package/lib/opencode/convert.d.ts +53 -0
  157. package/lib/opencode/convert.js +255 -0
  158. package/lib/opencode/row.d.ts +9 -0
  159. package/lib/opencode/row.js +86 -0
  160. package/lib/opencode/runtime/core.d.ts +74 -0
  161. package/lib/opencode/runtime/core.js +249 -0
  162. package/lib/opencode/runtime/events.d.ts +80 -0
  163. package/lib/opencode/runtime/events.js +281 -0
  164. package/lib/opencode/runtime/mount.d.ts +27 -0
  165. package/lib/opencode/runtime/mount.js +283 -0
  166. package/lib/opencode/runtime/server.d.ts +27 -0
  167. package/lib/opencode/runtime/server.js +353 -0
  168. package/lib/opencode/runtime/types.d.ts +109 -0
  169. package/lib/opencode/runtime/types.js +1 -0
  170. package/lib/opencode/runtime.d.ts +55 -0
  171. package/lib/opencode/runtime.js +79 -0
  172. package/lib/porting/port-gap.d.ts +30 -0
  173. package/lib/porting/port-gap.js +122 -0
  174. package/lib/porting/port-sessions.d.ts +41 -0
  175. package/lib/porting/port-sessions.js +98 -0
  176. package/lib/porting/prompt.d.ts +23 -0
  177. package/lib/porting/prompt.js +49 -0
  178. package/lib/porting/row.d.ts +16 -0
  179. package/lib/porting/row.js +25 -0
  180. package/lib/porting/verify-port.d.ts +53 -0
  181. package/lib/porting/verify-port.js +104 -0
  182. package/lib/presets/fs-search.d.ts +25 -0
  183. package/lib/presets/fs-search.js +17 -0
  184. package/lib/presets/tool-filter.d.ts +35 -0
  185. package/lib/presets/tool-filter.js +91 -0
  186. package/lib/sessions/claude.d.ts +29 -0
  187. package/lib/sessions/claude.js +83 -0
  188. package/lib/sessions/codex.d.ts +30 -0
  189. package/lib/sessions/codex.js +303 -0
  190. package/lib/sessions/opencode.d.ts +32 -0
  191. package/lib/sessions/opencode.js +320 -0
  192. package/lib/sessions/row.d.ts +14 -0
  193. package/lib/sessions/row.js +35 -0
  194. package/lib/shared/invocation.d.ts +169 -0
  195. package/lib/shared/invocation.js +325 -0
  196. package/lib/shared/render.d.ts +72 -0
  197. package/lib/shared/render.js +588 -0
  198. package/lib/shared/util.d.ts +21 -0
  199. package/lib/shared/util.js +32 -0
  200. package/lib/skills/bundled.d.ts +3 -0
  201. package/lib/skills/bundled.js +42 -0
  202. package/lib/skills/provider.d.ts +72 -0
  203. package/lib/skills/provider.js +340 -0
  204. package/lib/skills/row.d.ts +22 -0
  205. package/lib/skills/row.js +204 -0
  206. package/lib/workbench/adapter-coverage.d.ts +47 -0
  207. package/lib/workbench/adapter-coverage.js +102 -0
  208. package/lib/workbench/model-tools.d.ts +10 -0
  209. package/lib/workbench/model-tools.js +122 -0
  210. package/lib/workbench/overview.d.ts +103 -0
  211. package/lib/workbench/overview.js +159 -0
  212. package/lib/workbench/remote.d.ts +118 -0
  213. package/lib/workbench/remote.js +422 -0
  214. package/lib/workbench/row.d.ts +15 -0
  215. package/lib/workbench/row.js +16 -0
  216. package/lib/workbench/settings.d.ts +15 -0
  217. package/lib/workbench/settings.js +56 -0
  218. package/lib/workbench/workbench.d.ts +100 -0
  219. package/lib/workbench/workbench.js +260 -0
  220. package/locale/agents/en.json +6 -0
  221. package/locale/agents/zh.json +6 -0
  222. package/locale/commands/en.json +6 -0
  223. package/locale/commands/zh.json +6 -0
  224. package/locale/context/en.json +6 -0
  225. package/locale/context/zh.json +6 -0
  226. package/locale/en.json +6 -0
  227. package/locale/hooks/en.json +6 -0
  228. package/locale/hooks/zh.json +6 -0
  229. package/locale/mcp/en.json +6 -0
  230. package/locale/mcp/zh.json +6 -0
  231. package/locale/mods/en.json +6 -0
  232. package/locale/mods/zh.json +6 -0
  233. package/locale/opencode/en.json +6 -0
  234. package/locale/opencode/zh.json +6 -0
  235. package/locale/porter/en.json +6 -0
  236. package/locale/porter/zh.json +6 -0
  237. package/locale/sessions/en.json +6 -0
  238. package/locale/sessions/zh.json +6 -0
  239. package/locale/skills/en.json +6 -0
  240. package/locale/skills/zh.json +6 -0
  241. package/locale/workbench/en.json +6 -0
  242. package/locale/workbench/zh.json +6 -0
  243. package/locale/zh.json +6 -0
  244. package/package.json +246 -3
  245. package/runtime/opencode-host.mjs +270 -0
  246. package/skills/harness-forge/SKILL.md +47 -0
@@ -0,0 +1,728 @@
1
+ /**
2
+ * The hook broker's engine: every matching handler of one occurrence run in
3
+ * its own dialect, the combined outcome, notices and environment files.
4
+ * @module @kirkchinese/harness-forge
5
+ */
6
+ import { randomUUID } from 'node:crypto';
7
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
8
+ import { dirname, join } from 'node:path';
9
+ import { createUserMessage } from '@deepseek-ai/dsh-llm';
10
+ import { conditionMatches } from '../condition.js';
11
+ import { matcherSelects } from '../matcher.js';
12
+ import { appendNotice, terminalNotification } from '../notice.js';
13
+ import { contextsOf, decodeAsyncRun, decodeRun, specific } from '../output.js';
14
+ import { HandlerRunner } from '../runner.js';
15
+ import { TranscriptMirror } from '../transcript.js';
16
+ import { foreignResponse, foreignTool } from '../vocabulary.js';
17
+ import { dshService, lastTurnOf, planModeActive, presetOfSession } from '../../dsh/host.js';
18
+ import { appendRecord, recordHookInvoked, recordHookResult } from '../../dsh/session-records.js';
19
+ import { isRecord } from './helpers.js';
20
+ export const CONTEXT_SOURCE = { kind: 'harness-forge' };
21
+ const TOOL_EVENTS = new Set(['PreToolUse', 'PostToolUse', 'PostToolUseFailure', 'PermissionRequest', 'PermissionDenied']);
22
+ const MODEL_HANDLER_EVENTS = new Set(['PermissionDenied', 'PostToolBatch', 'PostToolUse', 'PostToolUseFailure', 'PreToolUse', 'Stop', 'SubagentStop', 'TaskCompleted', 'TaskCreated', 'TeammateIdle', 'UserPromptExpansion', 'UserPromptSubmit']);
23
+ const NO_FAILURE_BLOCK = new Set(['Stop', 'SubagentStop', 'TaskCompleted', 'TeammateIdle']);
24
+ const ENV_FILE_EVENTS = new Set(['SessionStart', 'Setup', 'CwdChanged', 'FileChanged']);
25
+ const CONTEXT_LIMIT = 10_000;
26
+ const PREVIEW_LIMIT = 2_000;
27
+ const DEFAULT_TIMEOUT_MS = 600_000;
28
+ const MAX_PARALLEL_MODEL_HANDLERS = 12;
29
+ /**
30
+ * The broker's shared engine: the registered sources, per-session state, the
31
+ * handler runs and how their outcomes combine, notices, environment files and
32
+ * the host facts every part of the broker reads.
33
+ */
34
+ export class HookEngine {
35
+ ctx;
36
+ host;
37
+ sources = new Map();
38
+ sessions = new Map();
39
+ runner;
40
+ transcripts;
41
+ detached = new Set();
42
+ ending = new Set();
43
+ lifetime = new AbortController();
44
+ onceDone = new Set();
45
+ notifyTimers = new Map();
46
+ idleTimers = new Map();
47
+ constructor(ctx, host) {
48
+ this.ctx = ctx;
49
+ this.host = host;
50
+ this.runner = new HandlerRunner(ctx, host.shell, agent => host.environment?.(agent?.session.header) ?? {});
51
+ this.transcripts = new TranscriptMirror(join(host.dataRoot, 'transcripts'), {
52
+ agentName: id => host.agentName(id),
53
+ });
54
+ }
55
+ /** Register one source; the returned disposer removes it. */
56
+ add(source) {
57
+ const key = source.sessionId !== undefined || source.agentSessionId !== undefined
58
+ ? `${source.componentId}@${source.sessionId ?? source.agentSessionId ?? ''}`
59
+ : source.componentId;
60
+ this.sources.set(key, source);
61
+ return () => { this.sources.delete(key); };
62
+ }
63
+ // -------------------------------------------------------------------------
64
+ // Running handlers
65
+ // -------------------------------------------------------------------------
66
+ has(event) {
67
+ // `disableAllHooks: true` in global settings turns every hook off; a project's is checked per run.
68
+ if (this.host.hooksDisabled?.() === true)
69
+ return false;
70
+ for (const source of this.sources.values()) {
71
+ if (source.table.has(event))
72
+ return true;
73
+ if (event === 'SubagentStop' && source.agentSessionId !== undefined && source.table.has('Stop'))
74
+ return true;
75
+ }
76
+ return false;
77
+ }
78
+ hasAgentStop(agent) {
79
+ for (const source of this.sources.values())
80
+ if (source.agentSessionId === agent.session.header.id && source.table.has('Stop'))
81
+ return true;
82
+ return false;
83
+ }
84
+ /**
85
+ * Run every matching handler of one occurrence in parallel and decode the
86
+ * synchronous ones. Background handlers deliver their output later.
87
+ */
88
+ async run(occurrence, extra = {}) {
89
+ if (this.host.hooksDisabled?.(occurrence.agent?.session.header) === true)
90
+ return [];
91
+ const agent = occurrence.agent;
92
+ const cwd = occurrence.cwd ?? (agent !== undefined ? await this.directory(agent, occurrence.signal) : process.cwd());
93
+ const jobs = [];
94
+ const settingsSeen = new Set();
95
+ let modelHandlers = 0;
96
+ for (const source of [...this.sources.values()]) {
97
+ if (!this.sourceApplies(source, agent))
98
+ continue;
99
+ const groups = [
100
+ ...source.table.get(occurrence.event) ?? [],
101
+ ...(occurrence.event === 'SubagentStop' && source.agentSessionId !== undefined ? source.table.get('Stop') ?? [] : []),
102
+ ];
103
+ if (groups.length === 0)
104
+ continue;
105
+ const tool = occurrence.tool === undefined ? undefined : foreignTool(source.dialect, occurrence.tool.dshName, occurrence.tool.args, this.toolContext(agent, cwd));
106
+ for (const [groupIndex, group] of groups.entries()) {
107
+ const subjects = tool?.aliases ?? occurrence.subjects ?? [occurrence.subject ?? ''];
108
+ if (!matcherSelects(source.dialect, occurrence.event, group.matcher, subjects))
109
+ continue;
110
+ // The tool name the hook sees: the alias its matcher selected, else the canonical name.
111
+ const toolName = tool === undefined ? undefined : (group.matcher === undefined || group.matcher === '' || group.matcher === '*'
112
+ ? tool.name
113
+ : tool.aliases.find(alias => matcherSelects(source.dialect, occurrence.event, group.matcher, [alias])) ?? tool.name);
114
+ for (const [handlerIndex, handler] of group.handlers.entries()) {
115
+ if (handler.type === 'invalid') {
116
+ this.host.observe({ componentId: source.componentId, event: occurrence.event, ok: false, detail: handler.reason });
117
+ continue;
118
+ }
119
+ if (!handlerSupported(occurrence.event, handler.type, source.dialect))
120
+ continue;
121
+ if (handler.condition !== undefined) {
122
+ if (!TOOL_EVENTS.has(occurrence.event) || tool === undefined)
123
+ continue;
124
+ if (!conditionMatches(handler.condition, tool, cwd))
125
+ continue;
126
+ }
127
+ const onceKey = `${source.componentId}\0${occurrence.event}\0${JSON.stringify(handler)}\0${source.sessionId ?? ''}`;
128
+ if (handler.once === true && source.origin === 'skill' && this.onceDone.has(onceKey))
129
+ continue;
130
+ if (source.origin === 'settings') {
131
+ const key = `${occurrence.event}\0${JSON.stringify(handler)}`;
132
+ if (settingsSeen.has(key))
133
+ continue;
134
+ settingsSeen.add(key);
135
+ }
136
+ if (handler.type === 'prompt' || handler.type === 'agent')
137
+ modelHandlers++;
138
+ const view = tool === undefined ? undefined : { ...tool, name: toolName ?? tool.name };
139
+ const slot = { id: `g${String(groupIndex)}h${String(handlerIndex)}`, ...(group.matcher !== undefined ? { matcher: group.matcher } : {}) };
140
+ const job = () => this.runHandler(source, handler, occurrence, view, cwd, extra.envFile, slot).then((ran) => {
141
+ if (ran !== undefined && handler.once === true && source.origin === 'skill' && ran.decoded.error === undefined && ran.decoded.block === undefined)
142
+ this.onceDone.add(onceKey);
143
+ return ran;
144
+ });
145
+ jobs.push(job);
146
+ }
147
+ }
148
+ }
149
+ const results = modelHandlers > MAX_PARALLEL_MODEL_HANDLERS ? await limited(jobs, MAX_PARALLEL_MODEL_HANDLERS) : await Promise.all(jobs.map(job => job()));
150
+ return results.filter((ran) => ran !== undefined);
151
+ }
152
+ async runHandler(source, handler, occurrence, tool, cwd, envFile, slot = { id: 'g0h0' }) {
153
+ const agent = occurrence.agent;
154
+ const background = handler.type === 'command' && (handler.async === true || handler.asyncRewake === true) && !(source.dialect === 'codex' && occurrence.event === 'SessionEnd');
155
+ const payload = this.payload(source, occurrence, tool, cwd);
156
+ const places = {
157
+ pluginRoot: source.pluginRoot,
158
+ dataDir: source.dataDir,
159
+ projectDir: (agent?.session.header.cwd ?? cwd),
160
+ cwd: existingDirectory(cwd, agent?.session.header.cwd),
161
+ options: source.options ?? {},
162
+ ...(envFile !== undefined && ENV_FILE_EVENTS.has(occurrence.event) ? { envFile } : {}),
163
+ };
164
+ const timeoutMs = this.timeoutFor(occurrence, handler, source.dialect);
165
+ const label = handlerLabel(handler);
166
+ const turn = agent === undefined ? 0 : this.lastTurn(agent) ?? 0;
167
+ // Which group and handler of the event's table ran (`g<group>h<handler>`): evidence per handler, not per event.
168
+ const handlerId = `${source.componentId}:${occurrence.event}:${slot.id}:${randomUUID().slice(0, 8)}`;
169
+ if (agent !== undefined) {
170
+ try {
171
+ recordHookInvoked(agent.session, { turn, point: occurrence.event, dialect: source.dialect, handlerId, ...(slot.matcher !== undefined ? { matcher: slot.matcher } : {}) });
172
+ }
173
+ catch {
174
+ // A closed session still runs the hook.
175
+ }
176
+ }
177
+ const request = {
178
+ event: occurrence.event,
179
+ dialect: source.dialect,
180
+ payload,
181
+ places,
182
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
183
+ signal: background ? this.lifetime.signal : occurrence.signal,
184
+ ...(agent !== undefined ? { agent } : {}),
185
+ };
186
+ const execute = () => {
187
+ switch (handler.type) {
188
+ case 'command': return this.runner.command(handler, request);
189
+ case 'http': return this.runner.http(handler, request);
190
+ case 'mcp_tool': return this.runner.mcpTool(handler, request, mcpToolName(handler.server, handler.tool));
191
+ case 'prompt': return this.runner.prompt(handler, request);
192
+ case 'agent': return this.runner.agent(handler, request);
193
+ }
194
+ };
195
+ const record = (outcome, decoded) => {
196
+ const ok = decoded.error === undefined;
197
+ this.host.observe({ componentId: source.componentId, event: occurrence.event, ok, detail: ok ? `exit ${String(outcome.exitCode ?? 0)}` : decoded.error ?? 'failed' });
198
+ // SessionEnd runs as the session (or DSH) closes, when its log may no longer take records: kept beside it too.
199
+ if (occurrence.event === 'SessionEnd' && agent !== undefined) {
200
+ try {
201
+ mkdirSync(this.host.dataRoot, { recursive: true });
202
+ appendFileSync(join(this.host.dataRoot, 'session-ends.jsonl'), `${JSON.stringify({ sessionId: agent.session.header.id, handlerId, exitCode: outcome.exitCode ?? null, ok, at: new Date().toISOString() })}\n`);
203
+ }
204
+ catch {
205
+ // Evidence only.
206
+ }
207
+ }
208
+ if (agent === undefined)
209
+ return;
210
+ try {
211
+ recordHookResult(agent.session, {
212
+ turn,
213
+ point: occurrence.event,
214
+ handlerId,
215
+ output: { exitCode: outcome.exitCode, stderr: outcome.stderr || (decoded.error ?? (decoded.cancelled === true ? 'cancelled' : '')), stdout: outcome.stdout, ...(decoded.block !== undefined ? { decision: 'block' } : {}) },
216
+ stderrSummaryMaxChars: 2000,
217
+ durationMs: outcome.durationMs,
218
+ });
219
+ // What the handler answered, so its effect can be checked against what the session then did.
220
+ if (decoded.json !== undefined || decoded.block !== undefined || (decoded.plain !== undefined && decoded.plain.trim().length > 0)) {
221
+ appendRecord(agent.session, 'plugin:harness-forge/hook-output', {
222
+ handlerId,
223
+ event: occurrence.event,
224
+ ...(occurrence.tool?.callId !== undefined ? { callId: occurrence.tool.callId } : {}),
225
+ ...(decoded.block !== undefined ? { block: decoded.block.slice(0, 2000) } : {}),
226
+ ...(decoded.json !== undefined ? { json: JSON.parse(JSON.stringify(decoded.json)) } : {}),
227
+ ...(decoded.plain !== undefined && decoded.plain.trim().length > 0 ? { plain: decoded.plain.slice(0, 2000) } : {}),
228
+ });
229
+ }
230
+ }
231
+ catch {
232
+ // The session no longer accepts records.
233
+ }
234
+ };
235
+ if (background) {
236
+ this.track(execute().then((outcome) => {
237
+ const decoded = decodeAsyncRun(occurrence.event, source.dialect, outcome);
238
+ record(outcome, decoded);
239
+ if (agent !== undefined)
240
+ this.deliverAsync(agent, source, handler, occurrence.event, decoded, outcome);
241
+ }));
242
+ return undefined;
243
+ }
244
+ const outcome = await execute();
245
+ const decoded = decodeRun(occurrence.event, source.dialect, outcome);
246
+ record(outcome, decoded);
247
+ if (decoded.cancelled === true)
248
+ return undefined;
249
+ let failureBlock;
250
+ if (decoded.failed && !NO_FAILURE_BLOCK.has(occurrence.event) && this.blocksOnFailure(handler, occurrence.event)) {
251
+ const verb = outcome.failure?.kind === 'timeout' ? 'timed out' : 'failed';
252
+ const why = handler.type === 'command' && handler.onFailure === undefined
253
+ ? "blocking because Git Bash wasn't found, so only exit code 0 or 2 counts as this hook's verdict."
254
+ : 'blocking because onFailure is "block"';
255
+ failureBlock = `${occurrence.event}${tool !== undefined ? `:${tool.name}` : ''} hook error: [${label}]: ${verb}; ${why}\n${decoded.error ?? ''}`.trim();
256
+ }
257
+ if (outcome.suspectCapture === true && this.allows(occurrence.event, decoded)) {
258
+ failureBlock = `${occurrence.event} hook error: [${label}]: refusing to honor the suspect capture (a background process kept the hook's output open after it printed an allow)`;
259
+ }
260
+ const blocked = failureBlock !== undefined && decoded.block === undefined ? { ...decoded, block: failureBlock } : decoded;
261
+ return {
262
+ source,
263
+ handler,
264
+ decoded: blocked,
265
+ ...(outcome.verdict !== undefined ? { verdict: outcome.verdict } : {}),
266
+ ...(failureBlock !== undefined ? { failureBlock } : {}),
267
+ label,
268
+ ...(tool !== undefined ? { toolName: tool.name } : {}),
269
+ };
270
+ }
271
+ /** Whether a failed run of this handler blocks the action. */
272
+ blocksOnFailure(handler, event) {
273
+ if (handler.type !== 'command' && handler.type !== 'http')
274
+ return false;
275
+ if (handler.onFailure === 'block')
276
+ return true;
277
+ if (handler.onFailure === 'continue' || handler.type !== 'command')
278
+ return false;
279
+ // Windows without Git Bash: a shell-form PreToolUse/PermissionRequest hook only passes on 0 or 2.
280
+ return process.platform === 'win32' && this.host.shell.bash === undefined && handler.args === undefined && handler.shell === undefined
281
+ && (event === 'PreToolUse' || event === 'PermissionRequest');
282
+ }
283
+ /** Whether a decoded output allows the action outright. */
284
+ allows(event, decoded) {
285
+ const hso = specific(decoded);
286
+ if (event === 'PreToolUse')
287
+ return hso?.['permissionDecision'] === 'allow' || decoded.json?.['decision'] === 'approve';
288
+ if (event === 'PermissionRequest')
289
+ return isRecord(hso?.['decision']) && hso['decision']['behavior'] === 'allow';
290
+ return false;
291
+ }
292
+ /** Deliver a background run: context and system message on the next model request; asyncRewake wakes the agent on exit 2. */
293
+ deliverAsync(agent, source, handler, event, decoded, outcome) {
294
+ if (decoded.error !== undefined)
295
+ this.notice(agent, { kind: 'hook-error', event, plugin: source.pluginId, text: decoded.error });
296
+ if (handler.asyncRewake === true && outcome.exitCode === 2) {
297
+ const findings = outcome.stderr.trim() || outcome.stdout.trim();
298
+ const text = `${handler.rewakeMessage ?? `${event} hook (background) reported:`}\n${findings}`;
299
+ agent.steer(createUserMessage({ content: [{ type: 'text', text: this.reminder(agent, event, text) }], source: { ...CONTEXT_SOURCE, event } }));
300
+ return;
301
+ }
302
+ const texts = [];
303
+ const additional = specific(decoded)?.['additionalContext'];
304
+ if (typeof additional === 'string' && additional.length > 0)
305
+ texts.push(additional);
306
+ const system = decoded.json?.['systemMessage'];
307
+ if (typeof system === 'string' && system.length > 0)
308
+ texts.push(system);
309
+ if (texts.length === 0)
310
+ return;
311
+ if (event === 'SessionStart') {
312
+ const state = this.state(agent.session);
313
+ const key = `${source.componentId}\0${handlerLabel(handler)}`;
314
+ const joined = texts.join('\n');
315
+ if (state.asyncSessionStart.get(key) === joined)
316
+ return;
317
+ state.asyncSessionStart.set(key, joined);
318
+ }
319
+ for (const text of texts)
320
+ agent.inject(this.contextMessage(agent, event, text));
321
+ }
322
+ /** The stdin payload / POST body of one handler. */
323
+ payload(source, occurrence, tool, cwd) {
324
+ const agent = occurrence.agent;
325
+ const child = agent !== undefined && (agent.session.header.delegationDepth ?? 0) > 0;
326
+ const parent = child ? this.agentOf(agent.session.header.parentSession ?? '') : undefined;
327
+ // Subagent events and tool events inside a subagent name the main session and its transcript.
328
+ const sessionAgent = parent ?? agent;
329
+ const state = sessionAgent === undefined ? undefined : this.state(sessionAgent.session);
330
+ const effort = agent?.options?.reasoningEffort;
331
+ const out = {
332
+ session_id: sessionAgent?.session.header.id ?? '',
333
+ transcript_path: sessionAgent === undefined ? null : this.transcripts.path(sessionAgent.session, cwd),
334
+ cwd,
335
+ ...(sessionAgent !== undefined ? { permission_mode: this.permissionMode(sessionAgent, source.dialect) } : {}),
336
+ hook_event_name: occurrence.event,
337
+ ...(state?.promptId !== undefined && source.dialect === 'claude-code' ? { prompt_id: state.promptId } : {}),
338
+ ...(effort !== undefined && ['low', 'medium', 'high', 'xhigh', 'max'].includes(effort) ? { effort: { level: effort } } : {}),
339
+ ...(child && occurrence.event !== 'SubagentStart' && occurrence.event !== 'SubagentStop' ? { agent_id: agent.session.header.id, agent_type: this.agentTypeOf(agent) } : {}),
340
+ ...(source.dialect === 'codex' ? { model: agent?.options?.model ?? null, ...(agent !== undefined ? { turn_id: String(this.lastTurn(agent) ?? 0) } : {}) } : {}),
341
+ };
342
+ if (tool !== undefined) {
343
+ out['tool_name'] = tool.name;
344
+ out['tool_input'] = tool.input;
345
+ if (tool.dshName.startsWith('mcp__'))
346
+ out['mcp_server'] = { name: tool.dshName.split('__')[1] ?? '', source: 'plugin' };
347
+ if (occurrence.response !== undefined) {
348
+ out['tool_response'] = foreignResponse(source.dialect, tool.dshName, occurrence.tool?.args, occurrence.response.value, occurrence.response.text);
349
+ }
350
+ }
351
+ for (const [key, value] of Object.entries(occurrence.fields ?? {}))
352
+ if (value !== undefined)
353
+ out[key] = value;
354
+ if (occurrence.event === 'PermissionRequest')
355
+ delete out['tool_use_id'];
356
+ return out;
357
+ }
358
+ timeoutFor(occurrence, handler, dialect) {
359
+ if (handler.type === 'command' && handler.async === true && handler.asyncRewake !== true)
360
+ return undefined;
361
+ const codexShort = dialect === 'codex' && (occurrence.event === 'SessionEnd' || occurrence.event === 'Interrupt');
362
+ if (handler.timeoutSec !== undefined) {
363
+ const ms = handler.timeoutSec * 1000;
364
+ return codexShort ? Math.min(Math.max(ms, 1000), 3000) : ms;
365
+ }
366
+ if (handler.type === 'prompt')
367
+ return 30_000;
368
+ if (handler.type === 'agent')
369
+ return 60_000;
370
+ if (codexShort)
371
+ return 1000;
372
+ return occurrence.defaultTimeoutMs ?? (occurrence.event === 'MessageDisplay' ? 10_000 : DEFAULT_TIMEOUT_MS);
373
+ }
374
+ /** The SessionEnd budget: 1.5 s, raised by settings hooks' own timeouts up to 60 s, or the env override. */
375
+ sessionEndBudget() {
376
+ const override = Number(process.env['CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS']);
377
+ if (Number.isFinite(override) && override > 0)
378
+ return override;
379
+ let budget = 1500;
380
+ for (const source of this.sources.values()) {
381
+ if (source.origin !== 'settings')
382
+ continue;
383
+ for (const group of source.table.get('SessionEnd') ?? []) {
384
+ for (const handler of group.handlers)
385
+ if (handler.timeoutSec !== undefined)
386
+ budget = Math.max(budget, Math.min(handler.timeoutSec * 1000, 60_000));
387
+ }
388
+ }
389
+ return budget;
390
+ }
391
+ sessionEndDefault() {
392
+ const override = Number(process.env['CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS']);
393
+ return Number.isFinite(override) && override > 0 ? override : 1500;
394
+ }
395
+ // -------------------------------------------------------------------------
396
+ // Combining outcomes
397
+ // -------------------------------------------------------------------------
398
+ /** The first `continue: false`, as its stop reason. */
399
+ stopOf(results) {
400
+ const ran = results.find(item => item.decoded.json?.['continue'] === false);
401
+ if (ran === undefined)
402
+ return undefined;
403
+ const reason = ran.decoded.json?.['stopReason'];
404
+ return typeof reason === 'string' && reason.length > 0 ? reason : `stopped by a ${ran.handler.type} hook`;
405
+ }
406
+ /** A top-level `decision: "block"` or a blocking exit, as the block reason. */
407
+ blockOf(event, results) {
408
+ for (const ran of results) {
409
+ if (ran.decoded.block !== undefined)
410
+ return ran.decoded.block;
411
+ if (ran.decoded.json?.['decision'] === 'block')
412
+ return String(ran.decoded.json['reason'] ?? `blocked by a ${event} hook`);
413
+ }
414
+ return undefined;
415
+ }
416
+ /** A prompt/agent `ok: false`. */
417
+ modelBlock(results, continueOnBlock) {
418
+ for (const ran of results) {
419
+ if (ran.verdict === undefined || ran.verdict.ok)
420
+ continue;
421
+ if (continueOnBlock && ran.handler.type !== 'agent' && ran.handler.continueOnBlock !== true)
422
+ continue;
423
+ return ran.verdict.reason ?? 'blocked by a hook';
424
+ }
425
+ return undefined;
426
+ }
427
+ /** Every context string the runs add for the model. */
428
+ contexts(event, results) {
429
+ return results.flatMap(ran => contextsOf(event, ran.source.dialect, ran.decoded).map(text => this.bound(ran.source, text)));
430
+ }
431
+ /** Apply the 10,000-character cap (Codex: `additionalContextLimit` tokens): spill to a file with a preview. */
432
+ bound(source, text) {
433
+ const limit = source.dialect === 'codex' ? 2500 * 4 : CONTEXT_LIMIT;
434
+ if (text.length <= limit)
435
+ return text;
436
+ const dir = join(this.host.dataRoot, 'hook-output');
437
+ const path = join(dir, `${randomUUID()}.txt`);
438
+ try {
439
+ mkdirSync(dir, { recursive: true });
440
+ writeFileSync(path, text);
441
+ }
442
+ catch {
443
+ return text.slice(0, limit);
444
+ }
445
+ return `Output too large (${String(text.length)} characters). Full output saved to: ${path}\n\nPreview (first ${String(PREVIEW_LIMIT)} characters):\n${text.slice(0, PREVIEW_LIMIT)}`;
446
+ }
447
+ /** Notices for hook errors, system messages and terminal notifications of every run. */
448
+ noticeAll(agent, event, subject, results) {
449
+ for (const ran of results) {
450
+ const base = { event, ...(subject !== undefined ? { subject } : {}), plugin: ran.source.pluginId };
451
+ if (ran.decoded.error !== undefined)
452
+ this.notice(agent, { ...base, kind: 'hook-error', text: `${event}${subject !== undefined ? `:${subject}` : ''} hook error: [${ran.label}]: ${ran.decoded.error}` });
453
+ const system = ran.decoded.json?.['systemMessage'];
454
+ if (typeof system === 'string' && system.length > 0 && !DISCARDS_SYSTEM_MESSAGE.has(event))
455
+ this.notice(agent, { ...base, kind: 'system-message', text: system });
456
+ const sequence = ran.decoded.json?.['terminalSequence'];
457
+ if (typeof sequence === 'string') {
458
+ const notification = terminalNotification(sequence);
459
+ if (notification !== undefined)
460
+ this.notice(agent, { ...base, kind: 'terminal', text: JSON.stringify(notification) });
461
+ }
462
+ }
463
+ }
464
+ notice(agent, notice) {
465
+ if (agent !== undefined)
466
+ appendNotice(agent.session, notice);
467
+ }
468
+ /** `continue: false` or an ending block: stop the agent and tell the user why. */
469
+ halt(agent, event, reason, results) {
470
+ this.notice(agent, { kind: 'stopped', event, plugin: results[0]?.source.pluginId ?? '', text: reason });
471
+ queueMicrotask(() => { agent.cancel?.({ kind: 'hook', reason }); });
472
+ }
473
+ // -------------------------------------------------------------------------
474
+ // Messages
475
+ // -------------------------------------------------------------------------
476
+ /** Context for the model, as a system reminder naming the hook event. */
477
+ reminder(_agent, event, text) {
478
+ const escaped = text.replace(/<(\/?system-reminder)/gu, '&lt;$1');
479
+ return `<system-reminder>\n${event} hook additional context: ${escaped}\n</system-reminder>`;
480
+ }
481
+ contextMessage(agent, event, text) {
482
+ return createUserMessage({ content: [{ type: 'text', text: this.reminder(agent, event, text) }], source: { ...CONTEXT_SOURCE, event } });
483
+ }
484
+ // -------------------------------------------------------------------------
485
+ // Environment files (`CLAUDE_ENV_FILE`)
486
+ // -------------------------------------------------------------------------
487
+ /** The env file a session's SessionStart (`session`) or CwdChanged/FileChanged (`cwd`) hooks append to. */
488
+ envFile(session, scope) {
489
+ const path = join(this.host.dataRoot, 'env', `${session.header.id}.${scope}.sh`);
490
+ if (!existsSync(path)) {
491
+ mkdirSync(dirname(path), { recursive: true });
492
+ writeFileSync(path, '');
493
+ }
494
+ return path;
495
+ }
496
+ clearEnv(session, scope) {
497
+ const path = join(this.host.dataRoot, 'env', `${session.header.id}.${scope}.sh`);
498
+ if (existsSync(path))
499
+ writeFileSync(path, '');
500
+ }
501
+ /**
502
+ * The prefix that applies imported settings `env`, then the session's env
503
+ * files, to one shell tool command.
504
+ */
505
+ shellEnvPrefix(agent, dshName, extra = {}) {
506
+ const settings = Object.entries({ ...this.host.environment?.(agent.session.header), ...extra }).filter(([name]) => /^[A-Za-z_][A-Za-z0-9_]*$/u.test(name));
507
+ const files = ['session', 'cwd']
508
+ .map(scope => join(this.host.dataRoot, 'env', `${agent.session.header.id}.${scope}.sh`))
509
+ .filter(path => existsSync(path) && readFileSync(path, 'utf8').trim().length > 0);
510
+ if (files.length === 0 && settings.length === 0)
511
+ return undefined;
512
+ if (dshName === 'bash') {
513
+ const quote = (value) => `'${value.replace(/'/gu, "'\\''")}'`;
514
+ return [
515
+ ...settings.map(([name, value]) => `export ${name}=${quote(value)}\n`),
516
+ ...files.map(path => `. ${quote(path.replace(/\\/gu, '/'))}\n`),
517
+ ].join('');
518
+ }
519
+ // PowerShell never runs the file; plain assignments are copied into the environment.
520
+ const assignments = settings.map(([name, value]) => `$env:${name} = '${value.replace(/'/gu, "''")}'`);
521
+ const fromFiles = [];
522
+ let readable = true;
523
+ for (const path of files) {
524
+ for (const line of readFileSync(path, 'utf8').split(/\r?\n/u)) {
525
+ const trimmed = line.trim();
526
+ if (trimmed.length === 0 || trimmed.startsWith('#'))
527
+ continue;
528
+ const match = /^(?:export\s+|declare\s+-x\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/u.exec(trimmed);
529
+ const value = match === null ? undefined : plainValue(match[2] ?? '');
530
+ if (match === null || value === undefined) {
531
+ readable = false;
532
+ break;
533
+ }
534
+ if (process.platform === 'win32' && /[\\/]/u.test(value))
535
+ continue;
536
+ fromFiles.push(`$env:${match[1] ?? ''} = '${value.replace(/'/gu, "''")}'`);
537
+ }
538
+ }
539
+ if (readable)
540
+ assignments.push(...fromFiles);
541
+ return assignments.length === 0 ? undefined : `${assignments.join('; ')}\n`;
542
+ }
543
+ // -------------------------------------------------------------------------
544
+ // Host facts
545
+ // -------------------------------------------------------------------------
546
+ state(session) {
547
+ const id = session.header.id;
548
+ let state = this.sessions.get(id);
549
+ if (state === undefined) {
550
+ state = { stopActive: false, stopContinuations: 0, batch: [], expanded: new Set(), asyncSessionStart: new Map(), watchers: [], watchPaths: [] };
551
+ this.sessions.set(id, state);
552
+ }
553
+ return state;
554
+ }
555
+ sourceApplies(source, agent) {
556
+ if (source.sessionId !== undefined)
557
+ return agent !== undefined && (agent.session.header.id === source.sessionId || agent.session.header.parentSession === source.sessionId);
558
+ if (source.agentSessionId !== undefined)
559
+ return agent !== undefined && agent.session.header.id === source.agentSessionId;
560
+ return true;
561
+ }
562
+ toolContext(agent, cwd) {
563
+ const directory = cwd ?? (agent !== undefined ? this.committedDirectory(agent) ?? agent.session.header.cwd : undefined);
564
+ return {
565
+ ...(directory !== undefined ? { cwd: directory } : {}),
566
+ agentName: id => this.host.agentName(id),
567
+ presetOf: name => this.host.presetOf?.(name),
568
+ };
569
+ }
570
+ agentOf(sessionId) {
571
+ return dshService(this.ctx, 'agents')?.get(sessionId);
572
+ }
573
+ async directory(agent, signal) {
574
+ const service = dshService(this.ctx, 'workingDirectory');
575
+ if (service === undefined)
576
+ return agent.session.header.cwd ?? process.cwd();
577
+ try {
578
+ return await service.ensure(agent, signal);
579
+ }
580
+ catch {
581
+ return service.get(agent.session) ?? agent.session.header.cwd ?? process.cwd();
582
+ }
583
+ }
584
+ committedDirectory(agent) {
585
+ const service = dshService(this.ctx, 'workingDirectory');
586
+ try {
587
+ return service?.get(agent.session);
588
+ }
589
+ catch {
590
+ return undefined;
591
+ }
592
+ }
593
+ lastTurn(agent) {
594
+ return lastTurnOf(this.ctx, agent.session) ?? this.sessions.get(agent.session.header.id)?.lastTurn;
595
+ }
596
+ presetOf(agent) {
597
+ return presetOfSession(this.ctx, agent.session);
598
+ }
599
+ /** Claude's `agent_type`: the imported agent's own name, else `general-purpose`. */
600
+ agentTypeOf(child) {
601
+ const preset = this.presetOf(child);
602
+ return preset === undefined ? 'general-purpose' : this.host.agentName(preset) ?? 'general-purpose';
603
+ }
604
+ /** The foreign permission mode for the session's DSH permission preset and plan mode. */
605
+ permissionMode(agent, dialect) {
606
+ if (planModeActive(this.ctx, agent))
607
+ return 'plan';
608
+ const presets = dshService(this.ctx, 'permissionPresets');
609
+ let preset;
610
+ try {
611
+ preset = presets?.current(agent.session);
612
+ }
613
+ catch {
614
+ preset = undefined;
615
+ }
616
+ if (preset === 'auto')
617
+ return dialect === 'codex' ? 'default' : 'auto';
618
+ if (preset === 'danger-full-access')
619
+ return 'bypassPermissions';
620
+ if (preset === 'workspace-write')
621
+ return 'acceptEdits';
622
+ return 'default';
623
+ }
624
+ rename(agent, title) {
625
+ const titles = dshService(this.ctx, 'sessionTitle');
626
+ try {
627
+ titles?.rename(agent.session, title);
628
+ }
629
+ catch {
630
+ // A session whose title cannot change keeps its title.
631
+ }
632
+ }
633
+ track(promise) {
634
+ const tracked = promise.catch(() => undefined).finally(() => { this.detached.delete(tracked); });
635
+ this.detached.add(tracked);
636
+ }
637
+ }
638
+ /** Events whose `systemMessage` Claude Code discards. */
639
+ const DISCARDS_SYSTEM_MESSAGE = new Set(['Notification', 'SessionEnd', 'PostCompact', 'PreCompact', 'Setup', 'InstructionsLoaded', 'StopFailure']);
640
+ /** Which handler types run on which event (hook reference, "Prompt-based hooks"). */
641
+ function handlerSupported(event, type, dialect) {
642
+ if (dialect === 'codex')
643
+ return type === 'command' || type === 'mcp_tool';
644
+ if (type === 'command' || type === 'mcp_tool')
645
+ return true;
646
+ if (event === 'SessionStart' || event === 'Setup')
647
+ return false;
648
+ if (type === 'http')
649
+ return true;
650
+ if (event === 'PermissionRequest')
651
+ return type === 'prompt';
652
+ return MODEL_HANDLER_EVENTS.has(event);
653
+ }
654
+ /** A short description of what a handler runs, for messages. */
655
+ function handlerLabel(handler) {
656
+ switch (handler.type) {
657
+ case 'command': return handler.args === undefined ? handler.command : [handler.command, ...handler.args].join(' ');
658
+ case 'http': return handler.url;
659
+ case 'mcp_tool': return `${handler.server}/${handler.tool}`;
660
+ case 'prompt':
661
+ case 'agent': return `${handler.type}: ${handler.prompt.slice(0, 60)}`;
662
+ }
663
+ }
664
+ /** The DSH tool name of a hook's MCP `server`/`tool` (`plugin:<plugin>:<server>` is the scoped form). */
665
+ function mcpToolName(server, tool) {
666
+ const scoped = /^plugin:([^:]+):(.+)$/u.exec(server);
667
+ const name = scoped !== null ? `plugin_${scoped[1] ?? ''}_${scoped[2] ?? ''}` : server;
668
+ return `mcp__${name.replace(/[^A-Za-z0-9_-]+/gu, '_')}__${tool}`;
669
+ }
670
+ /** The first existing directory: the working directory, the session's start directory, home, temp. */
671
+ function existingDirectory(cwd, start) {
672
+ for (const candidate of [cwd, start, process.env['HOME'] ?? process.env['USERPROFILE'], process.env['TEMP'] ?? process.env['TMPDIR'] ?? '/tmp']) {
673
+ if (candidate !== undefined && candidate.length > 0 && existsSync(candidate))
674
+ return candidate;
675
+ }
676
+ return cwd;
677
+ }
678
+ /** A Bash value used exactly as written, or undefined when Bash would expand something. */
679
+ function plainValue(raw) {
680
+ let out = '';
681
+ let index = 0;
682
+ while (index < raw.length) {
683
+ const char = raw[index] ?? '';
684
+ if (char === "'") {
685
+ const end = raw.indexOf("'", index + 1);
686
+ if (end === -1)
687
+ return undefined;
688
+ out += raw.slice(index + 1, end);
689
+ index = end + 1;
690
+ }
691
+ else if (char === '"') {
692
+ let end = index + 1;
693
+ while (end < raw.length && raw[end] !== '"') {
694
+ if (raw[end] === '\\' && ['$', '`', '"', '\\'].includes(raw[end + 1] ?? '')) {
695
+ out += raw[end + 1];
696
+ end += 2;
697
+ continue;
698
+ }
699
+ if (raw[end] === '$' || raw[end] === '`')
700
+ return undefined;
701
+ out += raw[end];
702
+ end++;
703
+ }
704
+ if (end >= raw.length)
705
+ return undefined;
706
+ index = end + 1;
707
+ }
708
+ else if (/[A-Za-z0-9_@%+=:,./-]/u.test(char)) {
709
+ out += char;
710
+ index++;
711
+ }
712
+ else {
713
+ return undefined;
714
+ }
715
+ }
716
+ return out;
717
+ }
718
+ async function limited(jobs, size) {
719
+ const results = new Array(jobs.length);
720
+ let cursor = 0;
721
+ await Promise.all(Array.from({ length: Math.min(size, jobs.length) }, async () => {
722
+ while (cursor < jobs.length) {
723
+ const index = cursor++;
724
+ results[index] = await jobs[index]();
725
+ }
726
+ }));
727
+ return results;
728
+ }