@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,10 @@
1
+ /**
2
+ * Plain helpers the hook broker's parts share.
3
+ * @module @kirkchinese/harness-forge
4
+ */
5
+ import type { ContentBlock } from '@deepseek-ai/dsh-llm';
6
+ import type { SessionLike } from './types.js';
7
+ /** The text of the last assistant message in a session. */
8
+ export declare function lastAssistantText(session: SessionLike): string | null;
9
+ export declare function textOf(content: readonly ContentBlock[]): string;
10
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
@@ -0,0 +1,22 @@
1
+ /** The text of the last assistant message in a session. */
2
+ export function lastAssistantText(session) {
3
+ const events = session.snapshotEvents();
4
+ for (let index = events.length - 1; index >= 0; index--) {
5
+ const event = events[index];
6
+ if (event?.type !== 'assistant/message')
7
+ continue;
8
+ const message = isRecord(event.data) && isRecord(event.data['message']) ? event.data['message'] : {};
9
+ const text = Array.isArray(message['content'])
10
+ ? message['content'].filter(isRecord).filter(block => block['type'] === 'text').map(block => String(block['text'] ?? '')).join('')
11
+ : '';
12
+ if (text.length > 0)
13
+ return text;
14
+ }
15
+ return null;
16
+ }
17
+ export function textOf(content) {
18
+ return content.filter((block) => block.type === 'text').map(block => block.text).join('');
19
+ }
20
+ export function isRecord(value) {
21
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
22
+ }
@@ -0,0 +1,65 @@
1
+ import { type HookEngine } from './engine.js';
2
+ import type { SessionEvents } from './session-events.js';
3
+ import type { AgentLike, PreStepDecision, PreStepPayload } from './types.js';
4
+ /**
5
+ * Session lifecycle and turns: SessionStart, SubagentStart and SessionEnd as
6
+ * agents come and go; UserPromptSubmit, UserPromptExpansion, PostToolBatch,
7
+ * PreModelRequest and Stop / SubagentStop around each turn and step.
8
+ */
9
+ export declare class SessionLifecycle {
10
+ private readonly engine;
11
+ private readonly events;
12
+ constructor(engine: HookEngine, events: SessionEvents);
13
+ agentCreated({ agent, source, signal }: {
14
+ agent: AgentLike;
15
+ source: string;
16
+ signal?: AbortSignal;
17
+ }): Promise<void>;
18
+ private subagentStart;
19
+ /** Root agents whose session has not ended yet. */
20
+ private readonly live;
21
+ /** Sessions whose SessionEnd ran at shutdown: DSH disposing their agent afterwards does not end them again. */
22
+ private readonly endedAtShutdown;
23
+ /**
24
+ * DSH is shutting down: every session still open ends, and its SessionEnd hooks run, as Claude Code runs them
25
+ * when it exits. (DSH disposes Harness Forge before its agents, so agent/disposed would come too late.)
26
+ */
27
+ endLive(): void;
28
+ agentDisposed(agent: AgentLike): void;
29
+ /**
30
+ * An imported slash command was typed: `UserPromptSubmit` sees the typed
31
+ * line, then `UserPromptExpansion` sees the command. Returns the block
32
+ * message, or the context to send with the expanded prompt.
33
+ */
34
+ expandCommand(agent: AgentLike, command: {
35
+ readonly name: string;
36
+ readonly foreignName: string;
37
+ readonly args: string;
38
+ readonly expanded: string;
39
+ }, signal: AbortSignal): Promise<{
40
+ blocked?: string;
41
+ context: string[];
42
+ }>;
43
+ /**
44
+ * The user typed `/skill args`: `UserPromptExpansion` sees the skill (the
45
+ * typed line already went through `UserPromptSubmit`). Returns the block
46
+ * message, or the reminders to send with the skill content.
47
+ */
48
+ expandSkill(agent: AgentLike, skill: {
49
+ readonly name: string;
50
+ readonly foreignName: string;
51
+ readonly args: string;
52
+ readonly source: string;
53
+ }, signal: AbortSignal): Promise<{
54
+ blocked?: string;
55
+ context: string[];
56
+ }>;
57
+ preStep(payload: PreStepPayload, next: () => Promise<PreStepDecision>): Promise<PreStepDecision>;
58
+ /** Run UserPromptSubmit for one prompt; block messages become notices. */
59
+ private promptSubmitHooks;
60
+ turnStopping({ agent, signal }: {
61
+ agent: AgentLike;
62
+ turn: number;
63
+ signal: AbortSignal;
64
+ }): Promise<void>;
65
+ }
@@ -0,0 +1,342 @@
1
+ /**
2
+ * The hook broker's session lifecycle and turn events.
3
+ * @module @kirkchinese/harness-forge
4
+ */
5
+ import { randomUUID } from 'node:crypto';
6
+ import { createUserMessage } from '@deepseek-ai/dsh-llm';
7
+ import { contextsOf, specific } from '../output.js';
8
+ import { CONTEXT_SOURCE } from './engine.js';
9
+ import { lastAssistantText, textOf } from './helpers.js';
10
+ import { messageOf } from '../../shared/util.js';
11
+ /**
12
+ * Session lifecycle and turns: SessionStart, SubagentStart and SessionEnd as
13
+ * agents come and go; UserPromptSubmit, UserPromptExpansion, PostToolBatch,
14
+ * PreModelRequest and Stop / SubagentStop around each turn and step.
15
+ */
16
+ export class SessionLifecycle {
17
+ engine;
18
+ events;
19
+ constructor(engine, events) {
20
+ this.engine = engine;
21
+ this.events = events;
22
+ }
23
+ // -------------------------------------------------------------------------
24
+ // Session lifecycle
25
+ // -------------------------------------------------------------------------
26
+ async agentCreated({ agent, source, signal }) {
27
+ const depth = agent.session.header.delegationDepth ?? 0;
28
+ if (depth > 0) {
29
+ await this.subagentStart(agent, signal ?? this.engine.lifetime.signal);
30
+ return;
31
+ }
32
+ this.live.set(agent.session.header.id, agent);
33
+ if (this.engine.host.prepareSession !== undefined) {
34
+ try {
35
+ await this.engine.host.prepareSession(agent, await this.engine.directory(agent, signal ?? this.engine.lifetime.signal));
36
+ }
37
+ catch (error) {
38
+ this.engine.notice(agent, { kind: 'hook-error', event: 'SessionStart', plugin: 'harness-forge', text: `project assets not loaded: ${messageOf(error)}` });
39
+ }
40
+ }
41
+ if (!this.engine.has('SessionStart'))
42
+ return;
43
+ const envFile = this.engine.envFile(agent.session, 'session');
44
+ const results = await this.engine.run({
45
+ event: 'SessionStart',
46
+ agent,
47
+ signal: signal ?? this.engine.lifetime.signal,
48
+ subject: source,
49
+ fields: { source, model: agent.options?.model },
50
+ }, { envFile });
51
+ for (const ran of results) {
52
+ const hso = specific(ran.decoded);
53
+ const title = hso?.['sessionTitle'];
54
+ if (typeof title === 'string' && title.length > 0 && source !== 'clear' && source !== 'compact')
55
+ this.engine.rename(agent, title);
56
+ const watchPaths = hso?.['watchPaths'];
57
+ if (Array.isArray(watchPaths))
58
+ this.events.setWatchPaths(agent, watchPaths.map(String));
59
+ if (hso?.['reloadSkills'] === true)
60
+ this.engine.host.reloadSkills?.();
61
+ if (ran.decoded.block !== undefined)
62
+ this.engine.notice(agent, { kind: 'hook-error', event: 'SessionStart', subject: source, plugin: ran.source.pluginId, text: ran.decoded.block });
63
+ }
64
+ this.engine.noticeAll(agent, 'SessionStart', source, results);
65
+ const contexts = this.engine.contexts('SessionStart', results);
66
+ for (const text of contexts)
67
+ agent.inject(this.engine.contextMessage(agent, 'SessionStart', text));
68
+ this.events.startWatching(agent);
69
+ }
70
+ async subagentStart(child, signal) {
71
+ const preset = this.engine.presetOf(child);
72
+ const scoped = preset === undefined ? undefined : this.engine.host.agentHooks?.(preset);
73
+ if (scoped !== undefined)
74
+ this.engine.add({ ...scoped, origin: 'agent', agentSessionId: child.session.header.id });
75
+ if (!this.engine.has('SubagentStart'))
76
+ return;
77
+ const agentType = this.engine.agentTypeOf(child);
78
+ const results = await this.engine.run({
79
+ event: 'SubagentStart',
80
+ agent: child,
81
+ signal,
82
+ subject: agentType,
83
+ fields: { agent_id: child.session.header.id, agent_type: agentType },
84
+ });
85
+ this.engine.noticeAll(child, 'SubagentStart', agentType, results);
86
+ for (const ran of results) {
87
+ if (ran.decoded.block !== undefined)
88
+ this.engine.notice(child, { kind: 'hook-error', event: 'SubagentStart', subject: agentType, plugin: ran.source.pluginId, text: ran.decoded.block });
89
+ }
90
+ for (const text of this.engine.contexts('SubagentStart', results))
91
+ child.inject(this.engine.contextMessage(child, 'SubagentStart', text));
92
+ }
93
+ /** Root agents whose session has not ended yet. */
94
+ live = new Map();
95
+ /** Sessions whose SessionEnd ran at shutdown: DSH disposing their agent afterwards does not end them again. */
96
+ endedAtShutdown = new Set();
97
+ /**
98
+ * DSH is shutting down: every session still open ends, and its SessionEnd hooks run, as Claude Code runs them
99
+ * when it exits. (DSH disposes Harness Forge before its agents, so agent/disposed would come too late.)
100
+ */
101
+ endLive() {
102
+ for (const agent of [...this.live.values()]) {
103
+ this.agentDisposed(agent);
104
+ this.endedAtShutdown.add(agent.session.header.id);
105
+ }
106
+ }
107
+ agentDisposed(agent) {
108
+ const id = agent.session.header.id;
109
+ if (this.endedAtShutdown.has(id))
110
+ return;
111
+ this.live.delete(id);
112
+ const state = this.engine.sessions.get(id);
113
+ for (const watcher of state?.watchers ?? [])
114
+ watcher.close();
115
+ this.engine.sessions.delete(id);
116
+ clearTimeout(this.engine.idleTimers.get(id));
117
+ this.engine.idleTimers.delete(id);
118
+ for (const [key, source] of this.engine.sources) {
119
+ if (source.agentSessionId === id)
120
+ this.engine.sources.delete(key);
121
+ }
122
+ // A session's own sources (project hooks, invoked skills) still see its SessionEnd.
123
+ const forget = () => {
124
+ // SessionEnd's own run recreated the session's state (its payload reads it): drop it again.
125
+ this.engine.sessions.delete(id);
126
+ for (const [key, source] of this.engine.sources)
127
+ if (source.sessionId === id)
128
+ this.engine.sources.delete(key);
129
+ void this.engine.host.releaseSession?.(id);
130
+ };
131
+ if ((agent.session.header.delegationDepth ?? 0) > 0 || !this.engine.has('SessionEnd')) {
132
+ forget();
133
+ return;
134
+ }
135
+ const budget = this.engine.sessionEndBudget();
136
+ const ending = this.engine.run({
137
+ event: 'SessionEnd',
138
+ agent,
139
+ signal: AbortSignal.timeout(budget),
140
+ subject: 'other',
141
+ fields: { reason: 'other' },
142
+ cwd: this.engine.committedDirectory(agent) ?? agent.session.header.cwd ?? process.cwd(),
143
+ defaultTimeoutMs: this.engine.sessionEndDefault(),
144
+ }).then((results) => {
145
+ for (const ran of results) {
146
+ if (ran.decoded.block !== undefined)
147
+ this.engine.notice(agent, { kind: 'hook-error', event: 'SessionEnd', subject: 'other', plugin: ran.source.pluginId, text: ran.decoded.block });
148
+ }
149
+ }).catch(() => undefined).finally(() => {
150
+ this.engine.ending.delete(ending);
151
+ forget();
152
+ });
153
+ this.engine.ending.add(ending);
154
+ this.engine.track(ending);
155
+ }
156
+ // -------------------------------------------------------------------------
157
+ // Turns and steps
158
+ // -------------------------------------------------------------------------
159
+ /**
160
+ * An imported slash command was typed: `UserPromptSubmit` sees the typed
161
+ * line, then `UserPromptExpansion` sees the command. Returns the block
162
+ * message, or the context to send with the expanded prompt.
163
+ */
164
+ async expandCommand(agent, command, signal) {
165
+ const typed = `/${command.name}${command.args.length > 0 ? ` ${command.args}` : ''}`;
166
+ const context = [];
167
+ if (this.engine.has('UserPromptSubmit')) {
168
+ const submit = await this.promptSubmitHooks(agent, typed, signal);
169
+ if (submit.blocked !== undefined)
170
+ return { blocked: submit.blocked, context: [] };
171
+ context.push(...submit.context);
172
+ }
173
+ if (this.engine.has('UserPromptExpansion')) {
174
+ const results = await this.engine.run({
175
+ event: 'UserPromptExpansion',
176
+ agent,
177
+ signal,
178
+ subjects: [command.foreignName, command.name],
179
+ fields: { expansion_type: 'slash_command', command_name: command.foreignName, command_args: command.args, command_source: 'plugin', prompt: typed },
180
+ });
181
+ const blocked = this.engine.blockOf('UserPromptExpansion', results);
182
+ if (this.engine.stopOf(results) !== undefined || blocked !== undefined) {
183
+ this.engine.noticeAll(agent, 'UserPromptExpansion', command.foreignName, results);
184
+ return { blocked: blocked ?? this.engine.stopOf(results) ?? 'blocked by a UserPromptExpansion hook', context: [] };
185
+ }
186
+ this.engine.noticeAll(agent, 'UserPromptExpansion', command.foreignName, results);
187
+ context.push(...this.engine.contexts('UserPromptExpansion', results));
188
+ }
189
+ const reminders = context.map(text => this.engine.reminder(agent, 'UserPromptExpansion', text));
190
+ // The submitted message is the expanded prompt followed by these reminders; UserPromptSubmit already saw the typed line.
191
+ this.engine.state(agent.session).expanded.add(command.expanded + reminders.join(''));
192
+ return { context: reminders };
193
+ }
194
+ /**
195
+ * The user typed `/skill args`: `UserPromptExpansion` sees the skill (the
196
+ * typed line already went through `UserPromptSubmit`). Returns the block
197
+ * message, or the reminders to send with the skill content.
198
+ */
199
+ async expandSkill(agent, skill, signal) {
200
+ if (!this.engine.has('UserPromptExpansion'))
201
+ return { context: [] };
202
+ const typed = `/${skill.name}${skill.args.length > 0 ? ` ${skill.args}` : ''}`;
203
+ const results = await this.engine.run({
204
+ event: 'UserPromptExpansion',
205
+ agent,
206
+ signal,
207
+ subjects: [skill.foreignName, skill.name],
208
+ fields: { expansion_type: 'slash_command', command_name: skill.foreignName, command_args: skill.args, command_source: skill.source, prompt: typed },
209
+ });
210
+ this.engine.noticeAll(agent, 'UserPromptExpansion', skill.foreignName, results);
211
+ const blocked = this.engine.blockOf('UserPromptExpansion', results) ?? this.engine.stopOf(results);
212
+ if (blocked !== undefined)
213
+ return { blocked, context: [] };
214
+ return { context: this.engine.contexts('UserPromptExpansion', results).map(text => this.engine.reminder(agent, 'UserPromptExpansion', text)) };
215
+ }
216
+ async preStep(payload, next) {
217
+ const { agent } = payload;
218
+ const state = this.engine.state(agent.session);
219
+ const firstStep = state.lastTurn !== payload.turn;
220
+ const root = (agent.session.header.delegationDepth ?? 0) === 0;
221
+ if (firstStep) {
222
+ state.lastTurn = payload.turn;
223
+ state.promptId = randomUUID();
224
+ state.stopActive = false;
225
+ state.stopContinuations = 0;
226
+ state.batch = [];
227
+ clearTimeout(this.engine.idleTimers.get(agent.session.header.id));
228
+ this.engine.idleTimers.delete(agent.session.header.id);
229
+ }
230
+ let contexts = [];
231
+ if (firstStep && root && this.engine.has('UserPromptSubmit')) {
232
+ const prompt = textOf(payload.messages.filter(message => message.source?.kind !== 'harness-forge').flatMap(message => message.content));
233
+ if (prompt.length > 0 && !state.expanded.delete(prompt)) {
234
+ const submit = await this.promptSubmitHooks(agent, prompt, payload.signal);
235
+ if (submit.blocked !== undefined)
236
+ return { kind: 'reject' };
237
+ contexts = submit.context.map(text => this.engine.contextMessage(agent, 'UserPromptSubmit', text));
238
+ }
239
+ }
240
+ if (!firstStep && state.batch.length > 0 && this.engine.has('PostToolBatch')) {
241
+ const toolCalls = state.batch;
242
+ state.batch = [];
243
+ const results = await this.engine.run({ event: 'PostToolBatch', agent, signal: payload.signal, fields: { tool_calls: toolCalls } });
244
+ this.engine.noticeAll(agent, 'PostToolBatch', undefined, results);
245
+ const stop = this.engine.stopOf(results) ?? this.engine.blockOf('PostToolBatch', results) ?? this.engine.modelBlock(results, false);
246
+ if (stop !== undefined) {
247
+ this.engine.notice(agent, { kind: 'stopped', event: 'PostToolBatch', plugin: results[0]?.source.pluginId ?? '', text: stop });
248
+ return { kind: 'reject' };
249
+ }
250
+ contexts.push(...this.engine.contexts('PostToolBatch', results).map(text => this.engine.contextMessage(agent, 'PostToolBatch', text)));
251
+ }
252
+ if (this.engine.has('PreModelRequest')) {
253
+ this.engine.track(this.engine.run({ event: 'PreModelRequest', agent, signal: this.engine.lifetime.signal, fields: { model: agent.options?.model } }));
254
+ }
255
+ const downstream = await next();
256
+ if (contexts.length === 0 || downstream.kind !== 'enter')
257
+ return downstream;
258
+ return { ...downstream, messages: [...downstream.messages ?? [], ...contexts] };
259
+ }
260
+ /** Run UserPromptSubmit for one prompt; block messages become notices. */
261
+ async promptSubmitHooks(agent, prompt, signal) {
262
+ const results = await this.engine.run({ event: 'UserPromptSubmit', agent, signal, fields: { prompt }, defaultTimeoutMs: 30_000 });
263
+ for (const ran of results) {
264
+ const title = specific(ran.decoded)?.['sessionTitle'];
265
+ if (typeof title === 'string' && title.length > 0)
266
+ this.engine.rename(agent, title);
267
+ }
268
+ this.engine.noticeAll(agent, 'UserPromptSubmit', undefined, results);
269
+ const stop = this.engine.stopOf(results);
270
+ const blocked = stop ?? this.engine.blockOf('UserPromptSubmit', results) ?? this.engine.modelBlock(results, false);
271
+ if (blocked !== undefined) {
272
+ const suppress = results.some(ran => specific(ran.decoded)?.['suppressOriginalPrompt'] === true);
273
+ const text = suppress ? blocked : `${blocked}\n\nOriginal prompt: ${prompt}`;
274
+ this.engine.notice(agent, { kind: stop !== undefined ? 'stopped' : 'blocked', event: 'UserPromptSubmit', plugin: results[0]?.source.pluginId ?? '', text });
275
+ return { blocked: text, context: [] };
276
+ }
277
+ return { context: this.engine.contexts('UserPromptSubmit', results) };
278
+ }
279
+ async turnStopping({ agent, signal }) {
280
+ const child = (agent.session.header.delegationDepth ?? 0) > 0;
281
+ const event = child ? 'SubagentStop' : 'Stop';
282
+ if (!child)
283
+ this.events.armIdle(agent);
284
+ if (!this.engine.has(event) && !(child && this.engine.hasAgentStop(agent)))
285
+ return;
286
+ const state = this.engine.state(agent.session);
287
+ const agentType = child ? this.engine.agentTypeOf(agent) : undefined;
288
+ const results = await this.engine.run({
289
+ event,
290
+ agent,
291
+ signal,
292
+ ...(agentType !== undefined ? { subject: agentType } : {}),
293
+ fields: {
294
+ stop_hook_active: state.stopActive,
295
+ last_assistant_message: lastAssistantText(agent.session),
296
+ background_tasks: [],
297
+ session_crons: [],
298
+ ...(child ? {
299
+ agent_id: agent.session.header.id,
300
+ agent_type: agentType,
301
+ agent_transcript_path: this.engine.transcripts.path(agent.session, this.engine.committedDirectory(agent) ?? agent.session.header.cwd ?? process.cwd()),
302
+ } : {}),
303
+ },
304
+ });
305
+ this.engine.noticeAll(agent, event, agentType, results);
306
+ if (this.engine.stopOf(results) !== undefined) {
307
+ state.stopActive = false;
308
+ return;
309
+ }
310
+ const reasons = [];
311
+ for (const ran of results) {
312
+ const verdict = ran.verdict;
313
+ if (verdict !== undefined && !verdict.ok && verdict.impossible !== true)
314
+ reasons.push(verdict.reason ?? `${event} hook condition not met`);
315
+ if (ran.decoded.block !== undefined)
316
+ reasons.push(ran.decoded.block);
317
+ else if (ran.decoded.json?.['decision'] === 'block')
318
+ reasons.push(String(ran.decoded.json['reason'] ?? `${event} hook asked to continue`));
319
+ }
320
+ const feedback = results.flatMap(ran => contextsOf(event, ran.source.dialect, ran.decoded));
321
+ if (reasons.length === 0 && feedback.length === 0) {
322
+ state.stopActive = false;
323
+ state.stopContinuations = 0;
324
+ return;
325
+ }
326
+ const cap = Number(process.env['CLAUDE_CODE_STOP_HOOK_BLOCK_CAP'] ?? 8);
327
+ if (state.stopContinuations >= (Number.isFinite(cap) && cap > 0 ? cap : 8)) {
328
+ // The count resets on the next tool call or the next turn, not here.
329
+ this.engine.notice(agent, { kind: 'hook-error', event, plugin: results[0]?.source.pluginId ?? '', text: `${event} hooks continued the turn ${String(state.stopContinuations)} times in a row; ending the turn` });
330
+ state.stopActive = false;
331
+ return;
332
+ }
333
+ state.stopActive = true;
334
+ state.stopContinuations += 1;
335
+ const dialect = results[0]?.source.dialect ?? 'claude-code';
336
+ const text = [
337
+ ...reasons.map(reason => dialect === 'codex' ? reason : `${event} hook feedback:\n${reason}`),
338
+ ...feedback.map(item => `${event} hook feedback:\n${item}`),
339
+ ].join('\n\n');
340
+ agent.steer(createUserMessage({ content: [{ type: 'text', text }], source: { ...CONTEXT_SOURCE, event } }));
341
+ }
342
+ }
@@ -0,0 +1,22 @@
1
+ import type { HookEngine } from './engine.js';
2
+ import type { AgentLike, SessionLike } from './types.js';
3
+ /**
4
+ * Committed session events (compaction, turn ends, working-directory
5
+ * changes, approvals, model responses), the idle notification and the
6
+ * FileChanged watchers, each raised in the background.
7
+ */
8
+ export declare class SessionEvents {
9
+ private readonly engine;
10
+ constructor(engine: HookEngine);
11
+ sessionEvent(session: SessionLike, event: {
12
+ type: string;
13
+ data?: Record<string, unknown>;
14
+ }): void;
15
+ /** Arm the `idle_prompt` notification: 60 s after a root turn ends without new input. */
16
+ armIdle(agent: AgentLike): void;
17
+ setWatchPaths(agent: AgentLike, paths: readonly string[]): void;
18
+ /** Watch the FileChanged matcher filenames in the working directory plus the dynamic watch list. */
19
+ startWatching(agent: AgentLike): void;
20
+ /** Fire an observational event in the background. */
21
+ private detachedEvent;
22
+ }
@@ -0,0 +1,196 @@
1
+ /**
2
+ * The hook broker's observational events: committed session events and file
3
+ * watching.
4
+ * @module @kirkchinese/harness-forge
5
+ */
6
+ import { existsSync, watch } from 'node:fs';
7
+ import { basename, dirname, join, resolve } from 'node:path';
8
+ import { specific } from '../output.js';
9
+ import { foreignTool } from '../vocabulary.js';
10
+ import { isRecord, lastAssistantText, textOf } from './helpers.js';
11
+ /**
12
+ * Committed session events (compaction, turn ends, working-directory
13
+ * changes, approvals, model responses), the idle notification and the
14
+ * FileChanged watchers, each raised in the background.
15
+ */
16
+ export class SessionEvents {
17
+ engine;
18
+ constructor(engine) {
19
+ this.engine = engine;
20
+ }
21
+ // -------------------------------------------------------------------------
22
+ // Committed session events
23
+ // -------------------------------------------------------------------------
24
+ sessionEvent(session, event) {
25
+ const agent = this.engine.agentOf(session.header.id);
26
+ const data = event.data ?? {};
27
+ switch (event.type) {
28
+ case 'compaction/start': {
29
+ if (!this.engine.has('PreCompact'))
30
+ return;
31
+ const trigger = data['sourceCommandId'] !== undefined ? 'manual' : 'auto';
32
+ this.detachedEvent(agent, { event: 'PreCompact', subject: trigger, fields: { trigger, custom_instructions: null } });
33
+ return;
34
+ }
35
+ case 'compaction/summary':
36
+ this.engine.state(session).lastSummary = textOf(Array.isArray(data['summary']) ? data['summary'] : []);
37
+ return;
38
+ case 'compaction/end': {
39
+ if (!this.engine.has('PostCompact') || data['error'] !== undefined)
40
+ return;
41
+ const trigger = data['sourceCommandId'] !== undefined ? 'manual' : 'auto';
42
+ this.detachedEvent(agent, { event: 'PostCompact', subject: trigger, fields: { trigger, compact_summary: this.engine.state(session).lastSummary ?? '' } }, true);
43
+ return;
44
+ }
45
+ case 'turn/end': {
46
+ const reason = isRecord(data['reason']) ? data['reason'] : {};
47
+ if (reason['kind'] === 'error' && this.engine.has('StopFailure')) {
48
+ const failure = isRecord(reason['error']) ? reason['error'] : {};
49
+ const error = stopFailureType(String(failure['code'] ?? ''), String(failure['message'] ?? ''));
50
+ this.detachedEvent(agent, {
51
+ event: 'StopFailure',
52
+ subject: error,
53
+ fields: { error, error_details: String(failure['message'] ?? ''), last_assistant_message: `API Error: ${String(failure['message'] ?? 'unknown error')}` },
54
+ });
55
+ }
56
+ if (reason['kind'] === 'max-tokens' && this.engine.has('StopFailure')) {
57
+ this.detachedEvent(agent, { event: 'StopFailure', subject: 'max_output_tokens', fields: { error: 'max_output_tokens', last_assistant_message: lastAssistantText(session) } });
58
+ }
59
+ if (reason['kind'] === 'aborted' && isRecord(reason['reason']) && reason['reason']['kind'] === 'user' && this.engine.has('Interrupt')) {
60
+ this.detachedEvent(agent, { event: 'Interrupt', fields: { turn_id: String(data['turn'] ?? '') } });
61
+ }
62
+ return;
63
+ }
64
+ case 'working-directory/change': {
65
+ if (agent === undefined)
66
+ return;
67
+ const state = this.engine.state(session);
68
+ const oldCwd = state.cwd ?? session.header.cwd ?? '';
69
+ state.cwd = String(data['cwd'] ?? '');
70
+ this.engine.clearEnv(session, 'cwd');
71
+ if (this.engine.has('CwdChanged')) {
72
+ this.detachedEvent(agent, { event: 'CwdChanged', fields: { old_cwd: oldCwd, new_cwd: state.cwd }, cwd: state.cwd }, true, this.engine.envFile(session, 'cwd'));
73
+ }
74
+ this.startWatching(agent);
75
+ return;
76
+ }
77
+ case 'approval/asked': {
78
+ if (!this.engine.has('Notification') || agent === undefined)
79
+ return;
80
+ const id = String(data['id'] ?? '');
81
+ const tool = foreignTool('claude-code', String(data['toolName'] ?? ''), {}, this.engine.toolContext(agent)).name;
82
+ this.engine.notifyTimers.set(id, setTimeout(() => {
83
+ this.engine.notifyTimers.delete(id);
84
+ this.detachedEvent(agent, { event: 'Notification', subject: 'permission_prompt', fields: { notification_type: 'permission_prompt', title: 'Permission needed', message: `Claude needs your permission to use ${tool}` } });
85
+ }, 6_000));
86
+ return;
87
+ }
88
+ case 'approval/decided': {
89
+ const id = String(data['id'] ?? '');
90
+ clearTimeout(this.engine.notifyTimers.get(id));
91
+ this.engine.notifyTimers.delete(id);
92
+ return;
93
+ }
94
+ case 'assistant/message': {
95
+ if (!this.engine.has('PostModelRequest') || agent === undefined)
96
+ return;
97
+ const message = isRecord(data['message']) ? data['message'] : {};
98
+ this.detachedEvent(agent, { event: 'PostModelRequest', fields: { model: agent.options?.model, turn_id: String(data['turn'] ?? ''), status: 'completed', error: null, token_usage: message['usage'] ?? null } });
99
+ return;
100
+ }
101
+ default:
102
+ }
103
+ }
104
+ /** Arm the `idle_prompt` notification: 60 s after a root turn ends without new input. */
105
+ armIdle(agent) {
106
+ if (!this.engine.has('Notification'))
107
+ return;
108
+ const id = agent.session.header.id;
109
+ clearTimeout(this.engine.idleTimers.get(id));
110
+ this.engine.idleTimers.set(id, setTimeout(() => {
111
+ this.engine.idleTimers.delete(id);
112
+ this.detachedEvent(agent, { event: 'Notification', subject: 'idle_prompt', fields: { notification_type: 'idle_prompt', title: 'Waiting for input', message: 'Claude is waiting for your input' } });
113
+ }, 60_000));
114
+ }
115
+ // -------------------------------------------------------------------------
116
+ // FileChanged
117
+ // -------------------------------------------------------------------------
118
+ setWatchPaths(agent, paths) {
119
+ this.engine.state(agent.session).watchPaths = [...paths];
120
+ this.startWatching(agent);
121
+ }
122
+ /** Watch the FileChanged matcher filenames in the working directory plus the dynamic watch list. */
123
+ startWatching(agent) {
124
+ if (!this.engine.has('FileChanged'))
125
+ return;
126
+ const state = this.engine.state(agent.session);
127
+ for (const watcher of state.watchers)
128
+ watcher.close();
129
+ state.watchers = [];
130
+ const cwd = state.cwd ?? this.engine.committedDirectory(agent) ?? agent.session.header.cwd ?? process.cwd();
131
+ const files = new Set(state.watchPaths);
132
+ for (const source of this.engine.sources.values()) {
133
+ for (const group of source.table.get('FileChanged') ?? []) {
134
+ for (const name of (group.matcher ?? '').split('|').map(item => item.trim()).filter(item => item.length > 0))
135
+ files.add(resolve(cwd, name));
136
+ }
137
+ }
138
+ const byDir = new Map();
139
+ for (const file of files) {
140
+ const dir = dirname(file);
141
+ if (!existsSync(dir))
142
+ continue;
143
+ byDir.set(dir, (byDir.get(dir) ?? new Set()).add(basename(file)));
144
+ }
145
+ for (const [dir, names] of byDir) {
146
+ try {
147
+ const watcher = watch(dir, (_type, filename) => {
148
+ if (filename === null || !names.has(filename.toString()))
149
+ return;
150
+ const path = join(dir, filename.toString());
151
+ const kind = existsSync(path) ? 'change' : 'unlink';
152
+ this.detachedEvent(agent, { event: 'FileChanged', subject: basename(path), fields: { file_path: path, event: kind } }, true, this.engine.envFile(agent.session, 'cwd'));
153
+ });
154
+ watcher.unref();
155
+ state.watchers.push(watcher);
156
+ }
157
+ catch {
158
+ // A directory that cannot be watched is skipped.
159
+ }
160
+ }
161
+ }
162
+ /** Fire an observational event in the background. */
163
+ detachedEvent(agent, occurrence, userErrors = false, envFile) {
164
+ this.engine.track(this.engine.run({ ...occurrence, ...(agent !== undefined ? { agent } : {}), signal: this.engine.lifetime.signal }, envFile !== undefined ? { envFile } : {}).then((results) => {
165
+ if (agent === undefined)
166
+ return;
167
+ this.engine.noticeAll(agent, occurrence.event, occurrence.subject, results);
168
+ for (const ran of results) {
169
+ if (userErrors && ran.decoded.block !== undefined)
170
+ this.engine.notice(agent, { kind: 'hook-error', event: occurrence.event, ...(occurrence.subject !== undefined ? { subject: occurrence.subject } : {}), plugin: ran.source.pluginId, text: ran.decoded.block });
171
+ const watchPaths = specific(ran.decoded)?.['watchPaths'];
172
+ if ((occurrence.event === 'CwdChanged' || occurrence.event === 'FileChanged') && Array.isArray(watchPaths))
173
+ this.setWatchPaths(agent, watchPaths.map(String));
174
+ }
175
+ }));
176
+ }
177
+ }
178
+ /** Claude's StopFailure error type for a DSH LLM failure. */
179
+ function stopFailureType(code, message) {
180
+ const text = `${code} ${message}`.toLowerCase();
181
+ if (/rate.?limit|429/u.test(text))
182
+ return 'rate_limit';
183
+ if (/overload|529/u.test(text))
184
+ return 'overloaded';
185
+ if (/auth|401|403|api key/u.test(text))
186
+ return 'authentication_failed';
187
+ if (/billing|quota|payment|402/u.test(text))
188
+ return 'billing_error';
189
+ if (/model.*(not.?found|does not exist)/u.test(text))
190
+ return 'model_not_found';
191
+ if (/invalid|400/u.test(text))
192
+ return 'invalid_request';
193
+ if (/5\d\d|server/u.test(text))
194
+ return 'server_error';
195
+ return 'unknown';
196
+ }