@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,32 @@
1
+ import type { CoreContext } from '../engine.js';
2
+ import { type SessionRegistry } from './sessions.js';
3
+ import type { ClaudeVerdict, PostDecision, SessionMods, ToolExec, ToolResult } from './types.js';
4
+ /** Tool calls and permission decisions in the sessions' mods. */
5
+ export declare class ModTools {
6
+ private readonly registry;
7
+ constructor(registry: SessionRegistry);
8
+ private toolContext;
9
+ preExecute(exec: ToolExec, next: () => Promise<unknown>): Promise<unknown>;
10
+ /** Core of `tool.call`: the rest of DSH's pipeline, which settles in post-execute. */
11
+ toolCore(session: SessionMods, e: Record<string, unknown>, context: CoreContext): Promise<unknown>;
12
+ /** A mod's `$.tool.call`: the tool through DSH's registry. */
13
+ private callTool;
14
+ private resultOf;
15
+ execute(exec: ToolExec, next: () => Promise<ToolResult>): Promise<ToolResult>;
16
+ /**
17
+ * `agent.spawn` as a delegated agent is about to start: a deny keeps it
18
+ * from starting; a model the hooks chose runs the child.
19
+ * @returns the refusal the model reads, when the spawn was denied.
20
+ */
21
+ private spawn;
22
+ postExecute(exec: ToolExec, result: ToolResult, next: () => Promise<PostDecision>): Promise<PostDecision>;
23
+ toolResult(exec: ToolExec, result: ToolResult): void;
24
+ /** Whether a call's session has mods hooking `tool.check`. */
25
+ checks(exec: ToolExec): boolean;
26
+ /**
27
+ * `tool.check` for one call the hooks broker decided: the mods' answer over
28
+ * Claude Code's own verdict (rules, PreToolUse hooks, the mode).
29
+ */
30
+ check(exec: ToolExec, verdict: ClaudeVerdict): Promise<ClaudeVerdict>;
31
+ checkCore(session: SessionMods, e: Record<string, unknown>): ClaudeVerdict;
32
+ }
@@ -0,0 +1,253 @@
1
+ /**
2
+ * The tool path: `tool.call` wrapped around DSH's pipeline, a mod's own
3
+ * `$.tool.call`, `agent.spawn` and `tool.check`.
4
+ * @module @kirkchinese/harness-forge/mods
5
+ */
6
+ import { createUserMessage } from '@deepseek-ai/dsh-llm';
7
+ import { appendNotice } from '../../hooks/notice.js';
8
+ import { dshInput, foreignResponse, foreignTool, shellFailure } from '../../hooks/vocabulary.js';
9
+ import { resolveRoute } from '../../shared/invocation.js';
10
+ import { isRecord, messageOf } from '../values.js';
11
+ import { dshService } from '../../dsh/host.js';
12
+ import { hasHooks } from './sessions.js';
13
+ function deferred() {
14
+ let resolve;
15
+ const promise = new Promise((done) => { resolve = done; });
16
+ return { promise, resolve };
17
+ }
18
+ /** Tool calls and permission decisions in the sessions' mods. */
19
+ export class ModTools {
20
+ registry;
21
+ constructor(registry) {
22
+ this.registry = registry;
23
+ }
24
+ // ---------------------------------------------------------------------------
25
+ // Tool calls
26
+ // ---------------------------------------------------------------------------
27
+ toolContext(cwd) {
28
+ return { ...(cwd !== undefined ? { cwd } : {}), agentName: id => this.registry.host.agentName(id), presetOf: name => this.registry.host.presetOf(name) };
29
+ }
30
+ async preExecute(exec, next) {
31
+ const found = this.registry.sessionOf(exec.agent);
32
+ if (found === undefined || exec.callId === undefined || !hasHooks(found.session.engine, 'tool.call'))
33
+ return next();
34
+ const { session, agentId } = found;
35
+ await session.ready;
36
+ const cwd = await this.registry.host.directory(exec.agent, exec.signal).catch(() => undefined);
37
+ const tool = foreignTool('claude-code', exec.name, exec.arguments, this.toolContext(cwd));
38
+ const input = { ...tool.input, tool: tool.name, tool_use_id: exec.callId, ...(agentId !== undefined ? { agentId } : {}) };
39
+ const pending = { input, reached: deferred(), beneath: deferred(), isBeneathSettled: false };
40
+ session.calls.set(exec.callId, pending);
41
+ pending.chain = session.engine.raise('tool.call', input, { signal: exec.signal });
42
+ const first = await Promise.race([
43
+ pending.reached.promise.then(e => ({ reached: e })),
44
+ pending.chain.then(result => ({ answered: result }), (error) => ({ failed: error })),
45
+ ]);
46
+ if ('failed' in first) {
47
+ appendNotice(exec.agent.session, { kind: 'hook-error', event: 'tool.call', plugin: 'mods', text: messageOf(first.failed) });
48
+ return next();
49
+ }
50
+ if ('answered' in first) {
51
+ if (typeof first.answered['deny'] === 'string')
52
+ return { kind: 'deny', reason: first.answered['deny'] };
53
+ pending.answered = first.answered;
54
+ return { kind: 'allow' };
55
+ }
56
+ // The hooks passed the call on: what they changed in its arguments is what runs.
57
+ const { tool: _tool, tool_use_id: _id, agentId: _agent, ...passed } = first.reached;
58
+ const { tool: _t, tool_use_id: _i, agentId: _a, ...original } = input;
59
+ if (JSON.stringify(passed) !== JSON.stringify(original))
60
+ this.registry.host.rewrite(exec.callId, dshInput('claude-code', exec.name, exec.arguments, passed, this.toolContext(cwd)));
61
+ return next();
62
+ }
63
+ /** Core of `tool.call`: the rest of DSH's pipeline, which settles in post-execute. */
64
+ toolCore(session, e, context) {
65
+ const pending = typeof e['tool_use_id'] === 'string' ? session.calls.get(e['tool_use_id']) : undefined;
66
+ if (pending !== undefined && context.mod === undefined) {
67
+ pending.reached.resolve(e);
68
+ return pending.beneath.promise;
69
+ }
70
+ return this.callTool(session, e, context);
71
+ }
72
+ /** A mod's `$.tool.call`: the tool through DSH's registry. */
73
+ async callTool(session, e, context) {
74
+ const tools = dshService(session.agent.ctx, 'tools');
75
+ if (tools === undefined)
76
+ throw new Error('no tool runtime');
77
+ const { tool, tool_use_id: _id, agentId: _agent, ...args } = e;
78
+ const name = dshToolName(String(tool));
79
+ const dshArgs = dshInput('claude-code', name, {}, args, this.toolContext(session.agent.session.header.cwd));
80
+ const result = await tools.execute({ callId: `mod-${crypto.randomUUID()}`, name, arguments: dshArgs, agent: session.agent, signal: context.signal });
81
+ return this.resultOf(name, dshArgs, result);
82
+ }
83
+ resultOf(name, args, result) {
84
+ const text = (result.content ?? []).filter(block => block.type === 'text').map(block => block.text ?? '').join('');
85
+ const failure = result.isError ? result.error?.message ?? text : shellFailure(name, result.value);
86
+ return {
87
+ ref: 0,
88
+ result: result.isError ? text : foreignResponse('claude-code', name, args, result.value, text),
89
+ text,
90
+ ...(failure !== undefined ? { isError: true } : {}),
91
+ };
92
+ }
93
+ async execute(exec, next) {
94
+ const found = this.registry.sessionOf(exec.agent);
95
+ const pending = exec.callId === undefined ? undefined : found?.session.calls.get(exec.callId);
96
+ if (pending?.answered === undefined) {
97
+ if (found !== undefined && DELEGATION_TOOLS.has(exec.name) && hasHooks(found.session.engine, 'agent.spawn')) {
98
+ const refusal = await this.spawn(found.session, found.agentId, exec);
99
+ if (refusal !== undefined)
100
+ return { isError: true, error: { message: refusal }, content: [{ type: 'text', text: refusal }] };
101
+ }
102
+ return next();
103
+ }
104
+ // A hook answered the call itself: its result is the tool's, and no tool runs.
105
+ const answer = pending.answered;
106
+ const text = typeof answer['result'] === 'string' ? answer['result'] : JSON.stringify(answer['result'] ?? '');
107
+ return answer['isError'] === true
108
+ ? { isError: true, error: { message: text }, content: [{ type: 'text', text }] }
109
+ : { isError: false, value: text, content: [{ type: 'text', text }] };
110
+ }
111
+ /**
112
+ * `agent.spawn` as a delegated agent is about to start: a deny keeps it
113
+ * from starting; a model the hooks chose runs the child.
114
+ * @returns the refusal the model reads, when the spawn was denied.
115
+ */
116
+ async spawn(session, agentId, exec) {
117
+ const args = isRecord(exec.arguments) ? exec.arguments : {};
118
+ const preset = typeof args['agent_preset'] === 'string' ? args['agent_preset'] : undefined;
119
+ const parentModel = exec.agent?.options?.model ?? '';
120
+ const input = {
121
+ tool_use_id: exec.callId ?? '',
122
+ prompt: String(args['prompt'] ?? ''),
123
+ description: String(args['description'] ?? ''),
124
+ subagentType: preset === undefined ? 'general-purpose' : this.registry.host.agentName(preset) ?? preset,
125
+ provider: { plugin: 'engine', tier: 'core' },
126
+ parentModel,
127
+ background: true,
128
+ fork: exec.name === 'subagent_fork',
129
+ permissionMode: 'default',
130
+ ...(agentId !== undefined ? { parentAgentId: agentId } : {}),
131
+ ...(typeof args['cwd'] === 'string' ? { cwd: args['cwd'] } : {}),
132
+ };
133
+ const result = await session.engine.raise('agent.spawn', input, { signal: exec.signal }).catch(() => undefined);
134
+ if (result === undefined)
135
+ return undefined;
136
+ if (typeof result['deny'] === 'string')
137
+ return `a plugin declined the spawn: ${result['deny']}`;
138
+ const model = typeof result['model'] === 'string' ? result['model'] : undefined;
139
+ if (model !== undefined && model !== parentModel && model.length > 0 && exec.agent !== undefined) {
140
+ const resolved = await resolveRoute(this.registry.ctx, exec.agent.options ?? {}, model, undefined, exec.signal);
141
+ if (resolved.route !== undefined) {
142
+ const queue = this.registry.spawnRoutes.get(exec.agent.session.header.id) ?? [];
143
+ queue.push(resolved.route);
144
+ this.registry.spawnRoutes.set(exec.agent.session.header.id, queue);
145
+ }
146
+ }
147
+ return undefined;
148
+ }
149
+ async postExecute(exec, result, next) {
150
+ const found = this.registry.sessionOf(exec.agent);
151
+ const pending = exec.callId === undefined ? undefined : found?.session.calls.get(exec.callId);
152
+ if (found === undefined || pending === undefined || pending.answered !== undefined || pending.chain === undefined)
153
+ return next();
154
+ const downstream = await next();
155
+ const content = downstream.kind === 'accept' && downstream.content !== undefined ? downstream.content : result.content;
156
+ const effective = { ...result, ...(content !== undefined ? { content } : {}) };
157
+ const beneath = downstream.kind === 'block'
158
+ ? { deny: downstream.reason ?? 'blocked by a PostToolUse hook' }
159
+ : this.resultOf(exec.name, exec.arguments, effective);
160
+ pending.isBeneathSettled = true;
161
+ pending.beneath.resolve(beneath);
162
+ const final = await pending.chain.catch(() => beneath);
163
+ found.session.calls.delete(exec.callId);
164
+ const contexts = Array.isArray(final['context']) ? final['context'].map(text => createUserMessage({ content: [{ type: 'text', text: String(text) }], source: { kind: 'user' } })) : [];
165
+ const additional = [...(downstream.additionalContexts ?? []), ...contexts];
166
+ if (typeof final['deny'] === 'string' && typeof beneath['deny'] !== 'string') {
167
+ const tool = String(pending.input['tool']);
168
+ const note = result.isError ? final['deny'] : `${tool} ran, and a plugin withheld its result: ${final['deny']}`;
169
+ return { kind: 'accept', content: [{ type: 'text', text: note }], ...(additional.length > 0 ? { additionalContexts: additional } : {}) };
170
+ }
171
+ const changed = final['result'] !== beneath['result'] && final['result'] !== undefined;
172
+ if (changed) {
173
+ const text = typeof final['result'] === 'string' ? final['result'] : JSON.stringify(final['result']);
174
+ return { kind: 'accept', content: [{ type: 'text', text }], ...(additional.length > 0 ? { additionalContexts: additional } : {}) };
175
+ }
176
+ if (contexts.length > 0)
177
+ return { ...downstream, additionalContexts: additional };
178
+ return downstream;
179
+ }
180
+ toolResult(exec, result) {
181
+ const found = this.registry.sessionOf(exec.agent);
182
+ found?.session.surfaces.invalidate();
183
+ const pending = exec.callId === undefined ? undefined : found?.session.calls.get(exec.callId);
184
+ if (found === undefined || pending === undefined)
185
+ return;
186
+ // A call refused before it ran settles here: beneath the hooks, the refusal.
187
+ if (!pending.isBeneathSettled) {
188
+ pending.isBeneathSettled = true;
189
+ pending.beneath.resolve({ deny: result.error?.message ?? 'the call did not run' });
190
+ }
191
+ found.session.calls.delete(exec.callId);
192
+ }
193
+ // ---------------------------------------------------------------------------
194
+ // Permission decisions
195
+ // ---------------------------------------------------------------------------
196
+ /** Whether a call's session has mods hooking `tool.check`. */
197
+ checks(exec) {
198
+ const found = this.registry.sessionOf(exec.agent);
199
+ return found !== undefined && hasHooks(found.session.engine, 'tool.check');
200
+ }
201
+ /**
202
+ * `tool.check` for one call the hooks broker decided: the mods' answer over
203
+ * Claude Code's own verdict (rules, PreToolUse hooks, the mode).
204
+ */
205
+ async check(exec, verdict) {
206
+ const found = this.registry.sessionOf(exec.agent);
207
+ if (found === undefined || exec.callId === undefined || !hasHooks(found.session.engine, 'tool.check'))
208
+ return verdict;
209
+ const { session, agentId } = found;
210
+ await session.ready;
211
+ const cwd = await this.registry.host.directory(exec.agent, exec.signal).catch(() => undefined);
212
+ const tool = foreignTool('claude-code', exec.name, exec.arguments, this.toolContext(cwd));
213
+ session.checks.set(exec.callId, verdict);
214
+ try {
215
+ const answer = await session.engine.raise('tool.check', {
216
+ tool: tool.name,
217
+ input: tool.input,
218
+ tool_use_id: exec.callId,
219
+ ...(agentId !== undefined ? { agentId } : {}),
220
+ ...(READ_ONLY_TOOLS.has(exec.name) ? { isReadOnly: true } : {}),
221
+ }, { signal: exec.signal });
222
+ if (isRecord(answer) && ['allow', 'ask', 'deny'].includes(String(answer['decision'])))
223
+ return answer;
224
+ return verdict;
225
+ }
226
+ finally {
227
+ session.checks.delete(exec.callId);
228
+ }
229
+ }
230
+ checkCore(session, e) {
231
+ const verdict = typeof e['tool_use_id'] === 'string' ? session.checks.get(e['tool_use_id']) : undefined;
232
+ return verdict ?? { decision: 'allow' };
233
+ }
234
+ }
235
+ const READ_ONLY_TOOLS = new Set(['read', 'read_image', 'glob', 'grep', 'web_search', 'web_fetch']);
236
+ const DELEGATION_TOOLS = new Set(['agent', 'subagent', 'subagent_fork']);
237
+ /** The DSH tool a Claude tool name runs on. */
238
+ function dshToolName(name) {
239
+ const table = {
240
+ Bash: process.platform === 'win32' ? 'pwsh' : 'bash',
241
+ PowerShell: 'pwsh',
242
+ Read: 'read',
243
+ Write: 'write',
244
+ Edit: 'edit',
245
+ Glob: 'glob',
246
+ Grep: 'grep',
247
+ WebFetch: 'web_fetch',
248
+ WebSearch: 'web_search',
249
+ TodoWrite: 'todo_write',
250
+ AskUserQuestion: 'ask_user_question',
251
+ };
252
+ return table[name] ?? name;
253
+ }
@@ -0,0 +1,32 @@
1
+ import { type SessionRegistry } from './sessions.js';
2
+ import type { PreStep, PreStepDecision } from './types.js';
3
+ /** The sessions' mods around each prompt and turn. */
4
+ export declare class ModTurns {
5
+ private readonly registry;
6
+ constructor(registry: SessionRegistry);
7
+ preStep(payload: PreStep, next: () => Promise<PreStepDecision>): Promise<PreStepDecision>;
8
+ /**
9
+ * `prompt.context` for the conversation's first prompt: the instruction
10
+ * files Claude Code itself would load (CLAUDE.md from the root down, the
11
+ * user's, the local ones) and the blocks they frame. Files a hook adds that
12
+ * DSH's own instructions did not load enter the conversation as context.
13
+ */
14
+ private promptContext;
15
+ sessionEvent(session: {
16
+ id: string;
17
+ }, event: {
18
+ type: string;
19
+ data: Record<string, unknown>;
20
+ }): void;
21
+ }
22
+ /**
23
+ * The instruction files Claude Code loads for a working directory: the
24
+ * user's (~/.claude/CLAUDE.md), then from the filesystem root down to the
25
+ * directory each CLAUDE.md and .claude/CLAUDE.md (project) and
26
+ * CLAUDE.local.md (local).
27
+ */
28
+ export declare function claudeInstructionFiles(cwd: string, home?: string): Array<{
29
+ path: string;
30
+ kind: string;
31
+ content: string;
32
+ }>;
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Prompts and turns: `prompt.submit`, `prompt.context`, `turn.start` and
3
+ * `turn.complete`.
4
+ * @module @kirkchinese/harness-forge/mods
5
+ */
6
+ import { existsSync, readFileSync } from 'node:fs';
7
+ import { homedir } from 'node:os';
8
+ import { dirname, join } from 'node:path';
9
+ import { createUserMessage } from '@deepseek-ai/dsh-llm';
10
+ import { appendNotice } from '../../hooks/notice.js';
11
+ import { claudeMdText } from '../engine.js';
12
+ import { isRecord } from '../values.js';
13
+ import { hasHooks } from './sessions.js';
14
+ /** The sessions' mods around each prompt and turn. */
15
+ export class ModTurns {
16
+ registry;
17
+ constructor(registry) {
18
+ this.registry = registry;
19
+ }
20
+ // ---------------------------------------------------------------------------
21
+ // Prompts and turns
22
+ // ---------------------------------------------------------------------------
23
+ async preStep(payload, next) {
24
+ const found = this.registry.sessionOf(payload.agent);
25
+ if (found === undefined || found.session.engine.mods.length === 0)
26
+ return next();
27
+ const { session, agentId } = found;
28
+ await session.ready;
29
+ const engine = session.engine;
30
+ const prompt = payload.messages.filter(message => message.source?.kind === 'user');
31
+ const text = prompt.flatMap(message => message.content).filter(block => block.type === 'text').map(block => block.text ?? '').join('');
32
+ let submitted = { text };
33
+ if (prompt.length > 0 && agentId === undefined && hasHooks(engine, 'prompt.submit')) {
34
+ const result = await engine.raise('prompt.submit', { text, wait: false, origin: { kind: 'composer' } }, { signal: payload.signal });
35
+ if (typeof result['drop'] === 'string') {
36
+ appendNotice(payload.agent.session, { kind: 'blocked', event: 'prompt.submit', plugin: 'mods', text: `Prompt dropped by a hook: ${result['drop']}` });
37
+ return { kind: 'reject' };
38
+ }
39
+ submitted = {
40
+ text: typeof result['text'] === 'string' ? result['text'] : text,
41
+ ...(Array.isArray(result['context']) ? { context: result['context'].map(String) } : {}),
42
+ };
43
+ }
44
+ const contextMessages = agentId === undefined && !session.isContextRaised && prompt.length > 0 && hasHooks(engine, 'prompt.context')
45
+ ? await this.promptContext(session, payload.signal)
46
+ : [];
47
+ const record = session.turns.get(payload.turn) ?? { startedAt: Date.now(), answer: '', started: false };
48
+ session.turns.set(payload.turn, record);
49
+ if (!record.started && agentId === undefined) {
50
+ record.started = true;
51
+ if (hasHooks(engine, 'turn.start'))
52
+ await engine.raise('turn.start', { text: submitted.text, turnId: String(payload.turn) }, { signal: payload.signal }).catch(() => undefined);
53
+ }
54
+ const entered = await next();
55
+ const decision = entered.kind === 'enter' && contextMessages.length > 0 ? { ...entered, messages: [...(entered.messages ?? []), ...contextMessages] } : entered;
56
+ if (decision.kind !== 'enter' || prompt.length === 0)
57
+ return decision;
58
+ const context = submitted.context ?? [];
59
+ if (submitted.text === text && context.length === 0)
60
+ return decision;
61
+ const rewritten = new Map();
62
+ prompt.forEach((message, index) => {
63
+ const content = index === 0 && submitted.text !== text ? [{ type: 'text', text: submitted.text }, ...message.content.filter(block => block.type !== 'text')] : index === 0 ? message.content : message.content.filter(block => block.type !== 'text');
64
+ const last = index === prompt.length - 1;
65
+ rewritten.set(message, { ...message, content: last ? [...content, ...context.map(line => ({ type: 'text', text: line }))] : content });
66
+ });
67
+ return { ...decision, messages: decision.messages?.map(message => rewritten.get(message) ?? message) };
68
+ }
69
+ /**
70
+ * `prompt.context` for the conversation's first prompt: the instruction
71
+ * files Claude Code itself would load (CLAUDE.md from the root down, the
72
+ * user's, the local ones) and the blocks they frame. Files a hook adds that
73
+ * DSH's own instructions did not load enter the conversation as context.
74
+ */
75
+ async promptContext(session, signal) {
76
+ session.isContextRaised = true;
77
+ const cwd = await this.registry.host.directory(session.agent, signal).catch(() => session.agent.session.header.cwd ?? process.cwd());
78
+ const files = claudeInstructionFiles(cwd);
79
+ const blocks = [
80
+ ...(files.length > 0 ? [{ name: 'claudeMd', text: claudeMdText(files) }] : []),
81
+ { name: 'currentDate', text: `Today's date is ${new Date().toISOString().slice(0, 10)}.` },
82
+ ];
83
+ const result = await session.engine.raise('prompt.context', { blocks, instructionFiles: files }, { signal }).catch(() => undefined);
84
+ const after = Array.isArray(result?.['instructionFiles']) ? result['instructionFiles'].filter(isRecord) : undefined;
85
+ if (after === undefined)
86
+ return [];
87
+ const dshLoads = new Set(['AGENTS.md', 'CLAUDE.md', 'AGENTS.local.md', 'CLAUDE.local.md']);
88
+ const added = after.filter(file => !files.some(known => known.path === file['path']) && !dshLoads.has(String(file['path']).split(/[\\/]/u).pop() ?? ''));
89
+ return added.map(file => createUserMessage({
90
+ content: [{ type: 'text', text: `Contents of ${String(file['path'])}:\n\n${String(file['content'] ?? '')}` }],
91
+ source: { kind: 'user' },
92
+ }));
93
+ }
94
+ sessionEvent(session, event) {
95
+ const mods = this.registry.sessions.get(session.id);
96
+ if (mods === undefined)
97
+ return;
98
+ const turn = typeof event.data['turn'] === 'number' ? event.data['turn'] : undefined;
99
+ if (event.type === 'assistant/message' && turn !== undefined) {
100
+ const record = mods.turns.get(turn);
101
+ const message = event.data['message'];
102
+ if (record !== undefined && Array.isArray(message?.content))
103
+ record.answer = message.content.filter(block => block.type === 'text').map(block => block.text ?? '').join('');
104
+ return;
105
+ }
106
+ if (event.type !== 'turn/end' || turn === undefined)
107
+ return;
108
+ const record = mods.turns.get(turn);
109
+ mods.turns.delete(turn);
110
+ mods.surfaces.invalidate();
111
+ if (!hasHooks(mods.engine, 'turn.complete'))
112
+ return;
113
+ const reason = event.data['reason'];
114
+ void mods.engine.raise('turn.complete', {
115
+ turnId: String(turn),
116
+ answer: record?.answer ?? '',
117
+ durationMs: record === undefined ? 0 : Date.now() - record.startedAt,
118
+ isAborted: reason?.kind === 'aborted',
119
+ reason: reason?.kind === 'aborted' ? 'aborted' : reason?.kind === 'error' ? 'error' : 'answer',
120
+ usage: null,
121
+ }).then((result) => {
122
+ const text = isRecord(result) ? result['text'] : undefined;
123
+ if (typeof text === 'string' && text.length > 0)
124
+ appendNotice(mods.agent.session, { kind: 'system-message', event: 'turn.complete', plugin: 'mods', text });
125
+ }, () => undefined);
126
+ }
127
+ }
128
+ /**
129
+ * The instruction files Claude Code loads for a working directory: the
130
+ * user's (~/.claude/CLAUDE.md), then from the filesystem root down to the
131
+ * directory each CLAUDE.md and .claude/CLAUDE.md (project) and
132
+ * CLAUDE.local.md (local).
133
+ */
134
+ export function claudeInstructionFiles(cwd, home = homedir()) {
135
+ const files = [];
136
+ const read = (path, kind) => {
137
+ if (!existsSync(path))
138
+ return;
139
+ try {
140
+ files.push({ path, kind, content: readFileSync(path, 'utf8') });
141
+ }
142
+ catch {
143
+ // An unreadable file is not loaded.
144
+ }
145
+ };
146
+ read(join(home, '.claude', 'CLAUDE.md'), 'user');
147
+ const dirs = [];
148
+ for (let current = cwd;; current = dirname(current)) {
149
+ dirs.unshift(current);
150
+ if (dirname(current) === current)
151
+ break;
152
+ }
153
+ for (const dir of dirs) {
154
+ if (dir === home)
155
+ continue;
156
+ read(join(dir, 'CLAUDE.md'), 'project');
157
+ read(join(dir, '.claude', 'CLAUDE.md'), 'project');
158
+ read(join(dir, 'CLAUDE.local.md'), 'local');
159
+ }
160
+ return files;
161
+ }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * The mods service's types: imported mods, the host it needs, one root
3
+ * session's mods and structural views of the DSH objects it touches.
4
+ * @module @kirkchinese/harness-forge/mods
5
+ */
6
+ import type { ForeignShell } from '../../hooks/shell.js';
7
+ import type { PluginTier } from '../chain.js';
8
+ import type { ModsEngine } from '../engine.js';
9
+ import type { SessionAgent, SessionHost } from '../host.js';
10
+ import type { Bundle } from '../loader.js';
11
+ import type { SessionSurfaces } from '../surfaces.js';
12
+ export type { ModEventRecord } from '../../dsh/session-records.js';
13
+ /** One imported mod, bundled once and loaded into each session. */
14
+ export interface ModSource {
15
+ /** The Harness Forge component the mod was installed as. */
16
+ readonly componentId: string;
17
+ readonly name: string;
18
+ readonly tier: PluginTier;
19
+ readonly root: string;
20
+ readonly bundle: Bundle;
21
+ readonly options: Readonly<Record<string, unknown>>;
22
+ readonly uses: Readonly<Record<string, unknown>>;
23
+ readonly provenance: string;
24
+ readonly version?: string;
25
+ readonly refusal?: string;
26
+ }
27
+ /** A Claude permission verdict, as `tool.check` answers it. */
28
+ export interface ClaudeVerdict {
29
+ readonly decision: 'allow' | 'ask' | 'deny';
30
+ readonly reason?: string;
31
+ readonly rule?: string;
32
+ readonly hook?: string;
33
+ readonly setting?: string;
34
+ }
35
+ /** What the service needs from Harness Forge's runtime. */
36
+ export interface ModsServiceHost {
37
+ readonly shell: ForeignShell;
38
+ readonly storeRoot: string;
39
+ /** Where each mod's unload is recorded, one JSON line each: the record of an uninstalled plugin is gone from the ledger. */
40
+ readonly disposedLog?: string;
41
+ directory(agent: unknown, signal: AbortSignal): Promise<string>;
42
+ settings(session: {
43
+ id: string;
44
+ parentSession?: string;
45
+ } | undefined, source: string | undefined): Record<string, unknown>;
46
+ /** Carry a rewrite of a call's arguments to the tool (the hooks broker applies it). */
47
+ rewrite(callId: string, args: Record<string, unknown>): void;
48
+ agentName(presetId: string): string | undefined;
49
+ presetOf(name: string): string | undefined;
50
+ /** A mod's hook ran for an event: runtime evidence of its component. */
51
+ observe(componentId: string, event: string): void;
52
+ }
53
+ export interface Deferred<T> {
54
+ readonly promise: Promise<T>;
55
+ resolve(value: T): void;
56
+ }
57
+ /** One DSH tool call the `tool.call` hooks are wrapped around. */
58
+ export interface PendingCall {
59
+ readonly input: Record<string, unknown>;
60
+ readonly reached: Deferred<Record<string, unknown>>;
61
+ readonly beneath: Deferred<Record<string, unknown>>;
62
+ chain?: Promise<Record<string, unknown>>;
63
+ answered?: Record<string, unknown>;
64
+ isBeneathSettled: boolean;
65
+ }
66
+ export interface ToolExec {
67
+ readonly name: string;
68
+ readonly arguments: unknown;
69
+ readonly callId?: string;
70
+ readonly agent?: SessionAgent & {
71
+ readonly session: SessionAgent['session'] & {
72
+ readonly header: {
73
+ readonly delegationDepth?: number;
74
+ };
75
+ };
76
+ };
77
+ readonly signal: AbortSignal;
78
+ }
79
+ export interface ToolResult {
80
+ readonly isError: boolean;
81
+ readonly value?: unknown;
82
+ readonly content?: ReadonlyArray<{
83
+ readonly type: string;
84
+ readonly text?: string;
85
+ }>;
86
+ readonly error?: {
87
+ readonly message?: string;
88
+ };
89
+ }
90
+ /** One root session's mods. */
91
+ export interface SessionMods {
92
+ readonly agent: SessionAgent;
93
+ readonly engine: ModsEngine;
94
+ readonly host: SessionHost;
95
+ readonly calls: Map<string, PendingCall>;
96
+ readonly checks: Map<string, ClaudeVerdict>;
97
+ readonly turns: Map<number, {
98
+ startedAt: number;
99
+ answer: string;
100
+ started: boolean;
101
+ }>;
102
+ readonly commands: Map<string, () => void>;
103
+ /** The mod that registered each command, so unloading a mod withdraws its commands. */
104
+ readonly commandOwners: Map<string, string>;
105
+ /** DSH's own run of the command a `command.run` dispatch is about, innermost last. */
106
+ readonly nativeCommands: Array<(command: string, args: string) => Promise<{
107
+ text?: string;
108
+ }>>;
109
+ /** The band and panes the session's mods draw. */
110
+ readonly surfaces: SessionSurfaces;
111
+ /** (mod, event) pairs already recorded in the session. */
112
+ readonly recorded: Set<string>;
113
+ /** Whether `prompt.context` has run for the conversation. */
114
+ isContextRaised: boolean;
115
+ ready: Promise<void>;
116
+ }
117
+ export type CommandsExecute = (agent: unknown, line: string, attachments: unknown[], signal: AbortSignal) => Promise<{
118
+ commandId: string;
119
+ result: {
120
+ kind: string;
121
+ text?: string;
122
+ };
123
+ } | undefined>;
124
+ export interface PreStep {
125
+ readonly agent: ToolExec['agent'];
126
+ readonly messages: ReadonlyArray<{
127
+ readonly source?: {
128
+ readonly kind?: string;
129
+ };
130
+ readonly content: ReadonlyArray<{
131
+ readonly type: string;
132
+ readonly text?: string;
133
+ }>;
134
+ }>;
135
+ readonly turn: number;
136
+ readonly step: number;
137
+ readonly signal: AbortSignal;
138
+ }
139
+ export interface PreStepDecision {
140
+ readonly kind: string;
141
+ readonly messages?: unknown[];
142
+ }
143
+ export interface PostDecision {
144
+ readonly kind: 'accept' | 'block';
145
+ readonly content?: ReadonlyArray<{
146
+ readonly type: string;
147
+ readonly text?: string;
148
+ }>;
149
+ readonly additionalContexts?: unknown[];
150
+ readonly reason?: string;
151
+ }
@@ -0,0 +1 @@
1
+ export {};