@kirkchinese/harness-forge 0.0.0-stage → 0.5.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.
- package/LICENSE +21 -0
- package/README.md +46 -2
- package/assets/icon.svg +12 -0
- package/cordis.patch.yml +28 -0
- package/docs/DETAIL.zh.md +47 -0
- package/lib/agents/presets.d.ts +98 -0
- package/lib/agents/presets.js +292 -0
- package/lib/agents/profiles.d.ts +58 -0
- package/lib/agents/profiles.js +279 -0
- package/lib/agents/row.d.ts +17 -0
- package/lib/agents/row.js +148 -0
- package/lib/client/paths.d.ts +12 -0
- package/lib/client/paths.js +68 -0
- package/lib/client/styles.d.ts +8 -0
- package/lib/client/styles.js +89 -0
- package/lib/client/typert.d.ts +25 -0
- package/lib/client/typert.js +158 -0
- package/lib/client.js +23823 -0
- package/lib/commands/definition.d.ts +40 -0
- package/lib/commands/definition.js +113 -0
- package/lib/commands/output-styles.d.ts +42 -0
- package/lib/commands/output-styles.js +152 -0
- package/lib/commands/row.d.ts +9 -0
- package/lib/commands/row.js +157 -0
- package/lib/context/instructions.d.ts +32 -0
- package/lib/context/instructions.js +88 -0
- package/lib/context/row.d.ts +16 -0
- package/lib/context/row.js +17 -0
- package/lib/dsh/commands.d.ts +30 -0
- package/lib/dsh/commands.js +61 -0
- package/lib/dsh/host.d.ts +110 -0
- package/lib/dsh/host.js +217 -0
- package/lib/dsh/model-route.d.ts +21 -0
- package/lib/dsh/model-route.js +37 -0
- package/lib/dsh/session-records.d.ts +78 -0
- package/lib/dsh/session-records.js +36 -0
- package/lib/dsh/subagents.d.ts +46 -0
- package/lib/dsh/subagents.js +14 -0
- package/lib/forge/contract.d.ts +271 -0
- package/lib/forge/contract.js +45 -0
- package/lib/forge/follow.d.ts +30 -0
- package/lib/forge/follow.js +73 -0
- package/lib/forge/ledger.d.ts +206 -0
- package/lib/forge/ledger.js +1005 -0
- package/lib/forge/live-mounts.d.ts +45 -0
- package/lib/forge/live-mounts.js +78 -0
- package/lib/forge/npm.d.ts +31 -0
- package/lib/forge/npm.js +60 -0
- package/lib/forge/projects.d.ts +97 -0
- package/lib/forge/projects.js +343 -0
- package/lib/forge/receipts.d.ts +5 -0
- package/lib/forge/receipts.js +31 -0
- package/lib/forge/remote/archive.d.ts +65 -0
- package/lib/forge/remote/archive.js +565 -0
- package/lib/forge/remote/code-parts.d.ts +18 -0
- package/lib/forge/remote/code-parts.js +76 -0
- package/lib/forge/remote/fetch.d.ts +265 -0
- package/lib/forge/remote/fetch.js +1133 -0
- package/lib/forge/remote/service.d.ts +256 -0
- package/lib/forge/remote/service.js +868 -0
- package/lib/forge/row.d.ts +32 -0
- package/lib/forge/row.js +59 -0
- package/lib/forge/service.d.ts +115 -0
- package/lib/forge/service.js +290 -0
- package/lib/forge/settings.d.ts +43 -0
- package/lib/forge/settings.js +122 -0
- package/lib/forge/state.d.ts +129 -0
- package/lib/forge/state.js +266 -0
- package/lib/forge/trust.d.ts +48 -0
- package/lib/forge/trust.js +107 -0
- package/lib/forge/turns.d.ts +13 -0
- package/lib/forge/turns.js +56 -0
- package/lib/hooks/broker/engine.d.ts +112 -0
- package/lib/hooks/broker/engine.js +722 -0
- package/lib/hooks/broker/helpers.d.ts +10 -0
- package/lib/hooks/broker/helpers.js +22 -0
- package/lib/hooks/broker/lifecycle.d.ts +65 -0
- package/lib/hooks/broker/lifecycle.js +342 -0
- package/lib/hooks/broker/session-events.d.ts +27 -0
- package/lib/hooks/broker/session-events.js +205 -0
- package/lib/hooks/broker/tools.d.ts +52 -0
- package/lib/hooks/broker/tools.js +424 -0
- package/lib/hooks/broker/types.d.ts +264 -0
- package/lib/hooks/broker/types.js +1 -0
- package/lib/hooks/broker.d.ts +80 -0
- package/lib/hooks/broker.js +95 -0
- package/lib/hooks/codex-user.d.ts +5 -0
- package/lib/hooks/codex-user.js +109 -0
- package/lib/hooks/condition.d.ts +87 -0
- package/lib/hooks/condition.js +602 -0
- package/lib/hooks/config.d.ts +85 -0
- package/lib/hooks/config.js +154 -0
- package/lib/hooks/glob.d.ts +41 -0
- package/lib/hooks/glob.js +114 -0
- package/lib/hooks/matcher.d.ts +20 -0
- package/lib/hooks/matcher.js +39 -0
- package/lib/hooks/notice.d.ts +17 -0
- package/lib/hooks/notice.js +39 -0
- package/lib/hooks/output.d.ts +56 -0
- package/lib/hooks/output.js +214 -0
- package/lib/hooks/permissions.d.ts +19 -0
- package/lib/hooks/permissions.js +202 -0
- package/lib/hooks/powershell-aliases.d.ts +19 -0
- package/lib/hooks/powershell-aliases.js +58 -0
- package/lib/hooks/process.d.ts +64 -0
- package/lib/hooks/process.js +289 -0
- package/lib/hooks/row.d.ts +17 -0
- package/lib/hooks/row.js +96 -0
- package/lib/hooks/runner.d.ts +98 -0
- package/lib/hooks/runner.js +322 -0
- package/lib/hooks/shell-commands.d.ts +28 -0
- package/lib/hooks/shell-commands.js +241 -0
- package/lib/hooks/shell.d.ts +44 -0
- package/lib/hooks/shell.js +129 -0
- package/lib/hooks/transcript.d.ts +28 -0
- package/lib/hooks/transcript.js +141 -0
- package/lib/hooks/vocabulary.d.ts +57 -0
- package/lib/hooks/vocabulary.js +366 -0
- package/lib/index.d.ts +31 -0
- package/lib/index.js +287 -0
- package/lib/mcp/auth.d.ts +35 -0
- package/lib/mcp/auth.js +178 -0
- package/lib/mcp/catalog.d.ts +39 -0
- package/lib/mcp/catalog.js +69 -0
- package/lib/mcp/mount.d.ts +113 -0
- package/lib/mcp/mount.js +317 -0
- package/lib/mcp/policy.d.ts +42 -0
- package/lib/mcp/policy.js +43 -0
- package/lib/mcp/remote.d.ts +45 -0
- package/lib/mcp/remote.js +133 -0
- package/lib/mcp/row.d.ts +9 -0
- package/lib/mcp/row.js +225 -0
- package/lib/mods/bundler.d.ts +38 -0
- package/lib/mods/bundler.js +157 -0
- package/lib/mods/chain.d.ts +103 -0
- package/lib/mods/chain.js +436 -0
- package/lib/mods/claude.d.ts +27 -0
- package/lib/mods/claude.js +56 -0
- package/lib/mods/engine.d.ts +160 -0
- package/lib/mods/engine.js +701 -0
- package/lib/mods/expect.d.ts +8 -0
- package/lib/mods/expect.js +248 -0
- package/lib/mods/host.d.ts +105 -0
- package/lib/mods/host.js +462 -0
- package/lib/mods/loader.d.ts +53 -0
- package/lib/mods/loader.js +231 -0
- package/lib/mods/ops.d.ts +13 -0
- package/lib/mods/ops.js +117 -0
- package/lib/mods/row.d.ts +9 -0
- package/lib/mods/row.js +77 -0
- package/lib/mods/runtime.d.ts +60 -0
- package/lib/mods/runtime.js +133 -0
- package/lib/mods/service/commands.d.ts +17 -0
- package/lib/mods/service/commands.js +121 -0
- package/lib/mods/service/drawings.d.ts +36 -0
- package/lib/mods/service/drawings.js +64 -0
- package/lib/mods/service/sessions.d.ts +63 -0
- package/lib/mods/service/sessions.js +345 -0
- package/lib/mods/service/tools.d.ts +32 -0
- package/lib/mods/service/tools.js +253 -0
- package/lib/mods/service/turns.d.ts +33 -0
- package/lib/mods/service/turns.js +136 -0
- package/lib/mods/service/types.d.ts +151 -0
- package/lib/mods/service/types.js +1 -0
- package/lib/mods/service.d.ts +72 -0
- package/lib/mods/service.js +104 -0
- package/lib/mods/surfaces.d.ts +93 -0
- package/lib/mods/surfaces.js +309 -0
- package/lib/mods/values.d.ts +30 -0
- package/lib/mods/values.js +95 -0
- package/lib/opencode/bun.d.ts +40 -0
- package/lib/opencode/bun.js +168 -0
- package/lib/opencode/convert.d.ts +53 -0
- package/lib/opencode/convert.js +255 -0
- package/lib/opencode/row.d.ts +22 -0
- package/lib/opencode/row.js +104 -0
- package/lib/opencode/runtime/core.d.ts +74 -0
- package/lib/opencode/runtime/core.js +249 -0
- package/lib/opencode/runtime/events.d.ts +80 -0
- package/lib/opencode/runtime/events.js +281 -0
- package/lib/opencode/runtime/mount.d.ts +27 -0
- package/lib/opencode/runtime/mount.js +283 -0
- package/lib/opencode/runtime/server.d.ts +27 -0
- package/lib/opencode/runtime/server.js +354 -0
- package/lib/opencode/runtime/types.d.ts +109 -0
- package/lib/opencode/runtime/types.js +1 -0
- package/lib/opencode/runtime.d.ts +55 -0
- package/lib/opencode/runtime.js +79 -0
- package/lib/porting/adapter-paths.d.ts +13 -0
- package/lib/porting/adapter-paths.js +120 -0
- package/lib/porting/port-gap.d.ts +36 -0
- package/lib/porting/port-gap.js +158 -0
- package/lib/porting/port-sessions.d.ts +41 -0
- package/lib/porting/port-sessions.js +98 -0
- package/lib/porting/prompt.d.ts +23 -0
- package/lib/porting/prompt.js +51 -0
- package/lib/porting/row.d.ts +16 -0
- package/lib/porting/row.js +27 -0
- package/lib/porting/verify-port.d.ts +46 -0
- package/lib/porting/verify-port.js +82 -0
- package/lib/presets/fs-search.d.ts +25 -0
- package/lib/presets/fs-search.js +17 -0
- package/lib/presets/tool-filter.d.ts +35 -0
- package/lib/presets/tool-filter.js +91 -0
- package/lib/sessions/chat-import.d.ts +48 -0
- package/lib/sessions/chat-import.js +44 -0
- package/lib/sessions/claude.d.ts +35 -0
- package/lib/sessions/claude.js +104 -0
- package/lib/sessions/codex-discover.d.ts +34 -0
- package/lib/sessions/codex-discover.js +205 -0
- package/lib/sessions/codex-meta.d.ts +63 -0
- package/lib/sessions/codex-meta.js +148 -0
- package/lib/sessions/codex-text.d.ts +9 -0
- package/lib/sessions/codex-text.js +44 -0
- package/lib/sessions/codex.d.ts +42 -0
- package/lib/sessions/codex.js +270 -0
- package/lib/sessions/opencode.d.ts +38 -0
- package/lib/sessions/opencode.js +339 -0
- package/lib/sessions/persist.d.ts +162 -0
- package/lib/sessions/persist.js +377 -0
- package/lib/sessions/row.d.ts +15 -0
- package/lib/sessions/row.js +101 -0
- package/lib/sessions/turns.d.ts +31 -0
- package/lib/sessions/turns.js +63 -0
- package/lib/sessions/zstd.d.ts +15 -0
- package/lib/sessions/zstd.js +152 -0
- package/lib/shared/invocation.d.ts +169 -0
- package/lib/shared/invocation.js +325 -0
- package/lib/shared/render.d.ts +101 -0
- package/lib/shared/render.js +1353 -0
- package/lib/shared/util.d.ts +21 -0
- package/lib/shared/util.js +32 -0
- package/lib/skills/bundled.d.ts +3 -0
- package/lib/skills/bundled.js +42 -0
- package/lib/skills/provider.d.ts +74 -0
- package/lib/skills/provider.js +346 -0
- package/lib/skills/row.d.ts +22 -0
- package/lib/skills/row.js +204 -0
- package/lib/workbench/adapter-coverage.d.ts +65 -0
- package/lib/workbench/adapter-coverage.js +141 -0
- package/lib/workbench/model-tools.d.ts +10 -0
- package/lib/workbench/model-tools.js +122 -0
- package/lib/workbench/overview.d.ts +153 -0
- package/lib/workbench/overview.js +246 -0
- package/lib/workbench/remote.d.ts +161 -0
- package/lib/workbench/remote.js +561 -0
- package/lib/workbench/row.d.ts +15 -0
- package/lib/workbench/row.js +16 -0
- package/lib/workbench/settings.d.ts +19 -0
- package/lib/workbench/settings.js +60 -0
- package/lib/workbench/workbench.d.ts +130 -0
- package/lib/workbench/workbench.js +361 -0
- package/locale/agents/en.json +6 -0
- package/locale/agents/zh.json +6 -0
- package/locale/commands/en.json +6 -0
- package/locale/commands/zh.json +6 -0
- package/locale/context/en.json +6 -0
- package/locale/context/zh.json +6 -0
- package/locale/en.json +6 -0
- package/locale/hooks/en.json +6 -0
- package/locale/hooks/zh.json +6 -0
- package/locale/mcp/en.json +6 -0
- package/locale/mcp/zh.json +6 -0
- package/locale/mods/en.json +6 -0
- package/locale/mods/zh.json +6 -0
- package/locale/opencode/en.json +6 -0
- package/locale/opencode/zh.json +6 -0
- package/locale/porter/en.json +6 -0
- package/locale/porter/zh.json +6 -0
- package/locale/sessions/en.json +6 -0
- package/locale/sessions/zh.json +6 -0
- package/locale/skills/en.json +6 -0
- package/locale/skills/zh.json +6 -0
- package/locale/workbench/en.json +6 -0
- package/locale/workbench/zh.json +6 -0
- package/locale/zh.json +7 -0
- package/package.json +247 -3
- package/runtime/opencode-host.mjs +270 -0
- package/skills/harness-forge/SKILL.md +47 -0
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The OpenCode row: OpenCode code plugins, each in its own Bun host, their
|
|
3
|
+
* hooks raised where DSH does the same work. It adds `shell.env` to the hooks
|
|
4
|
+
* row and `command.execute.before` to the commands row while those run, and
|
|
5
|
+
* its plugins' added commands through the commands row while both the plugin
|
|
6
|
+
* and that row run.
|
|
7
|
+
* @module @kirkchinese/harness-forge/opencode
|
|
8
|
+
*/
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { HarnessError } from '@kirkchinese/harness-forge-core';
|
|
11
|
+
import { onDsh } from '../dsh/host.js';
|
|
12
|
+
import { FORGE_SERVICE } from '../forge/service.js';
|
|
13
|
+
import { OpenCodeRuntime } from './runtime.js';
|
|
14
|
+
import { mounted, Parts, rowEffect } from '../forge/row.js';
|
|
15
|
+
export const name = 'harness-forge-opencode';
|
|
16
|
+
export const inject = [FORGE_SERVICE];
|
|
17
|
+
/** The OpenCode row. */
|
|
18
|
+
export function apply(ctx) {
|
|
19
|
+
rowEffect(ctx, 'opencode', forge => startOpenCode(ctx, forge));
|
|
20
|
+
}
|
|
21
|
+
/** Start the OpenCode row on the shared service. Returns its teardown. */
|
|
22
|
+
export function startOpenCode(ctx, forge) {
|
|
23
|
+
const opencode = new OpenCodeRuntime(ctx, {
|
|
24
|
+
dataRoot: join(forge.dataRoot, 'opencode'),
|
|
25
|
+
observe: (componentId, signal, ok, detail) => { forge.observe(componentId, signal, ok, detail); },
|
|
26
|
+
directory: (agent, signal) => forge.directory(agent, signal),
|
|
27
|
+
rewrite: (callId, args) => { forge.lookup('hooks')?.rewrite(callId, args); },
|
|
28
|
+
agentName: presetId => forge.lookup('agents')?.foreignName(presetId),
|
|
29
|
+
});
|
|
30
|
+
/** The component of each tool a plugin registered, for its call evidence. */
|
|
31
|
+
const tools = new Map();
|
|
32
|
+
const parts = new Parts(ctx, forge, 'opencode');
|
|
33
|
+
parts.add('runtime', () => opencode.install());
|
|
34
|
+
parts.add('tool evidence', () => onDsh(ctx, 'tools/post-execute', ((exec, result, next) => {
|
|
35
|
+
const componentId = tools.get(exec.name);
|
|
36
|
+
if (componentId !== undefined)
|
|
37
|
+
forge.observe(componentId, `tool:${exec.name}`, !result.isError, result.isError ? result.error?.message ?? 'tool call failed' : 'tool call returned');
|
|
38
|
+
return next();
|
|
39
|
+
}), { owner: 'opencode' }));
|
|
40
|
+
parts.add('shell.env', () => forge.watch('hooks', hooks => hooks.addShellEnv(exec => opencode.shellEnv(exec))));
|
|
41
|
+
parts.add('command.execute.before', () => forge.watch('commands', commands => commands.setBeforeSubmit((agent, command, prompt) => opencode.beforeCommand(agent, command, prompt))));
|
|
42
|
+
parts.add('plugin mounter', () => forge.registerMounter('opencode-plugin', {
|
|
43
|
+
mount: async ({ component, plugin, dataDir, scope, takenNames }) => {
|
|
44
|
+
if (component.kind !== 'code')
|
|
45
|
+
throw new HarnessError('component-failed', `action expects code: ${component.id}`);
|
|
46
|
+
const mount = await opencode.mount(component, plugin);
|
|
47
|
+
for (const tool of mount.tools)
|
|
48
|
+
tools.set(tool, component.id);
|
|
49
|
+
// Commands the plugin's `config` hook added run like the project's own OpenCode commands, while the commands row runs.
|
|
50
|
+
let commandNames = [];
|
|
51
|
+
const unbind = bindAddedCommands(forge, mount.commands, { pluginId: plugin.id, pluginRoot: plugin.root, dataDir, scope, takenNames }, (names) => {
|
|
52
|
+
commandNames = names;
|
|
53
|
+
opencode.recordAddedCommands(component.id, mount.commands.map((command, index) => ({ name: names[index] || command.name, foreignName: command.name, template: command.component.body })));
|
|
54
|
+
});
|
|
55
|
+
const summary = [
|
|
56
|
+
`opencode-plugin hooks [${mount.hooks.join(', ')}]`,
|
|
57
|
+
`tools [${mount.tools.join(', ')}]`,
|
|
58
|
+
// The names they are typed under in DSH.
|
|
59
|
+
...(commandNames.some(name => name.length > 0) ? [`commands [${commandNames.filter(name => name.length > 0).join(', ')}]`] : []),
|
|
60
|
+
// What its config hook changed: only `command` is applied in DSH.
|
|
61
|
+
...(mount.configChanged.length > 0 ? [`config [${mount.configChanged.join(', ')}]`] : []),
|
|
62
|
+
].join('; ');
|
|
63
|
+
return {
|
|
64
|
+
outcome: mounted(component, 'L1b', summary),
|
|
65
|
+
disposer: async () => {
|
|
66
|
+
for (const tool of mount.tools)
|
|
67
|
+
if (tools.get(tool) === component.id)
|
|
68
|
+
tools.delete(tool);
|
|
69
|
+
unbind();
|
|
70
|
+
await mount.dispose();
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
},
|
|
74
|
+
}));
|
|
75
|
+
return () => parts.dispose();
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Register a mounted plugin's added commands for as long as both the plugin and the commands row run: again each
|
|
79
|
+
* time the commands row starts, withdrawn when it stops or `dispose` runs. `record` gets, at each registration, the
|
|
80
|
+
* DSH name of each command in order (empty where none was given).
|
|
81
|
+
*/
|
|
82
|
+
export function bindAddedCommands(forge, commands, owner, record) {
|
|
83
|
+
if (commands.length === 0)
|
|
84
|
+
return () => undefined;
|
|
85
|
+
const unwatch = forge.watch('commands', (api) => {
|
|
86
|
+
const taken = owner.takenNames();
|
|
87
|
+
const names = [];
|
|
88
|
+
const withdraw = [];
|
|
89
|
+
for (const command of commands) {
|
|
90
|
+
const added = api.registerAdded({ component: command.component, name: command.name, foreignName: command.name, pluginId: owner.pluginId, pluginRoot: owner.pluginRoot, dataDir: owner.dataDir }, owner.scope, taken);
|
|
91
|
+
names.push(added?.name ?? '');
|
|
92
|
+
if (added === undefined)
|
|
93
|
+
continue;
|
|
94
|
+
taken.add(added.name);
|
|
95
|
+
withdraw.push(added.dispose);
|
|
96
|
+
}
|
|
97
|
+
record(names);
|
|
98
|
+
return () => {
|
|
99
|
+
for (const dispose of withdraw)
|
|
100
|
+
dispose();
|
|
101
|
+
};
|
|
102
|
+
});
|
|
103
|
+
return unwatch;
|
|
104
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { ServerResponse } from 'node:http';
|
|
2
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
3
|
+
import { type LoggedEvent, type SessionFacts } from '../convert.js';
|
|
4
|
+
import type { Agent, Agents, Message, OpenCodeRuntimeHost, PluginHost } from './types.js';
|
|
5
|
+
/** How long a plugin gets to answer a hook or an event before it counts as failed. */
|
|
6
|
+
export declare const RPC_DEADLINE_MS = 30000;
|
|
7
|
+
/** What a call to a plugin host may be given besides its body. */
|
|
8
|
+
export interface PostOptions {
|
|
9
|
+
/** The deadline in milliseconds; `null` for none (a tool call runs as long as the tool does). */
|
|
10
|
+
readonly timeoutMs?: number | null;
|
|
11
|
+
readonly signal?: AbortSignal;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* What every part of the OpenCode runtime shares: the running plugins, how
|
|
15
|
+
* their hooks are raised and events published, and DSH's facts in OpenCode's
|
|
16
|
+
* terms.
|
|
17
|
+
*/
|
|
18
|
+
export declare class OpenCodeCore {
|
|
19
|
+
readonly ctx: Context;
|
|
20
|
+
readonly host: OpenCodeRuntimeHost;
|
|
21
|
+
readonly deadlineMs: number;
|
|
22
|
+
readonly hosts: Map<string, PluginHost>;
|
|
23
|
+
readonly waiting: Map<string, {
|
|
24
|
+
resolve(body: Record<string, unknown>): void;
|
|
25
|
+
reject(error: Error): void;
|
|
26
|
+
}>;
|
|
27
|
+
readonly streams: Set<ServerResponse<import("http").IncomingMessage>>;
|
|
28
|
+
/** Prompts plugins sent while a `chat.message` of that session ran: they enter before its message. */
|
|
29
|
+
readonly admitting: Map<string, Message[]>;
|
|
30
|
+
/** Sessions a plugin created, which it may delete. */
|
|
31
|
+
readonly created: Map<string, {
|
|
32
|
+
dispose(): Promise<void>;
|
|
33
|
+
parentId?: string;
|
|
34
|
+
}>;
|
|
35
|
+
private readonly projects;
|
|
36
|
+
constructor(ctx: Context, host: OpenCodeRuntimeHost, deadlineMs?: number);
|
|
37
|
+
/** Whether any running plugin has a hook. */
|
|
38
|
+
has(hook: string): boolean;
|
|
39
|
+
/**
|
|
40
|
+
* Run one hook of every plugin that has it, in load order, on one output.
|
|
41
|
+
* A plugin refuses by throwing from a `.before` hook (`error`, which ends the
|
|
42
|
+
* chain); a plugin that crashes, does not answer in time or cannot be reached
|
|
43
|
+
* has failed, not refused: the fault is recorded, that plugin is skipped and
|
|
44
|
+
* the chain goes on.
|
|
45
|
+
* @returns the output after them all, the refusal if there was one, and the faults met.
|
|
46
|
+
*/
|
|
47
|
+
trigger(name: string, input: unknown, output: Record<string, unknown>): Promise<{
|
|
48
|
+
output: Record<string, unknown>;
|
|
49
|
+
error?: string;
|
|
50
|
+
faults: string[];
|
|
51
|
+
}>;
|
|
52
|
+
/** Publish one OpenCode event: to the event stream and every plugin's `event` hook. */
|
|
53
|
+
emit(event: Record<string, unknown>): void;
|
|
54
|
+
/** One call to a plugin's Bun host; it fails when the host does not answer within the deadline. */
|
|
55
|
+
post(plugin: PluginHost, path: string, body: unknown, options?: PostOptions): Promise<Record<string, unknown>>;
|
|
56
|
+
agents(): Agents | undefined;
|
|
57
|
+
agentOf(agent: Agent): string;
|
|
58
|
+
facts(agent: Agent): SessionFacts;
|
|
59
|
+
events(agent: Agent): LoggedEvent[];
|
|
60
|
+
/** OpenCode's project of a directory: the git worktree and its first commit, else `global`. */
|
|
61
|
+
projectOf(directory: string): {
|
|
62
|
+
id: string;
|
|
63
|
+
worktree: string;
|
|
64
|
+
created: number;
|
|
65
|
+
};
|
|
66
|
+
/** The OpenCode configuration in effect for a directory: global, then project files, later winning. */
|
|
67
|
+
configFor(directory: string): Record<string, unknown>;
|
|
68
|
+
/** OpenCode's stored provider credentials (`auth.json`). */
|
|
69
|
+
storedAuth(): Record<string, unknown>;
|
|
70
|
+
defaultModel(): {
|
|
71
|
+
provider: string;
|
|
72
|
+
model: string;
|
|
73
|
+
} | undefined;
|
|
74
|
+
}
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The OpenCode runtime's shared state: running plugins, hooks, events and DSH
|
|
3
|
+
* facts.
|
|
4
|
+
* @module @kirkchinese/harness-forge/opencode
|
|
5
|
+
*/
|
|
6
|
+
import { spawnSync } from 'node:child_process';
|
|
7
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
8
|
+
import { homedir } from 'node:os';
|
|
9
|
+
import { join, resolve } from 'node:path';
|
|
10
|
+
import { readOpenCodeConfig } from '@kirkchinese/harness-forge-core';
|
|
11
|
+
import { isRecord } from '../convert.js';
|
|
12
|
+
import { dshService, presetOfSession } from '../../dsh/host.js';
|
|
13
|
+
import { messageOf } from '../../shared/util.js';
|
|
14
|
+
/** Hooks whose throw stops the work they precede (OpenCode's documented way to refuse). */
|
|
15
|
+
const STOPPING_HOOKS = new Set(['tool.execute.before', 'command.execute.before']);
|
|
16
|
+
/** How long a plugin gets to answer a hook or an event before it counts as failed. */
|
|
17
|
+
export const RPC_DEADLINE_MS = 30_000;
|
|
18
|
+
/**
|
|
19
|
+
* What every part of the OpenCode runtime shares: the running plugins, how
|
|
20
|
+
* their hooks are raised and events published, and DSH's facts in OpenCode's
|
|
21
|
+
* terms.
|
|
22
|
+
*/
|
|
23
|
+
export class OpenCodeCore {
|
|
24
|
+
ctx;
|
|
25
|
+
host;
|
|
26
|
+
deadlineMs;
|
|
27
|
+
hosts = new Map();
|
|
28
|
+
waiting = new Map();
|
|
29
|
+
streams = new Set();
|
|
30
|
+
/** Prompts plugins sent while a `chat.message` of that session ran: they enter before its message. */
|
|
31
|
+
admitting = new Map();
|
|
32
|
+
/** Sessions a plugin created, which it may delete. */
|
|
33
|
+
created = new Map();
|
|
34
|
+
projects = new Map();
|
|
35
|
+
constructor(ctx, host, deadlineMs = RPC_DEADLINE_MS) {
|
|
36
|
+
this.ctx = ctx;
|
|
37
|
+
this.host = host;
|
|
38
|
+
this.deadlineMs = deadlineMs;
|
|
39
|
+
}
|
|
40
|
+
/** Whether any running plugin has a hook. */
|
|
41
|
+
has(hook) {
|
|
42
|
+
for (const plugin of this.hosts.values())
|
|
43
|
+
if (plugin.hooks.has(hook))
|
|
44
|
+
return true;
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
// ---------------------------------------------------------------------------
|
|
48
|
+
// Hooks and events
|
|
49
|
+
// ---------------------------------------------------------------------------
|
|
50
|
+
/**
|
|
51
|
+
* Run one hook of every plugin that has it, in load order, on one output.
|
|
52
|
+
* A plugin refuses by throwing from a `.before` hook (`error`, which ends the
|
|
53
|
+
* chain); a plugin that crashes, does not answer in time or cannot be reached
|
|
54
|
+
* has failed, not refused: the fault is recorded, that plugin is skipped and
|
|
55
|
+
* the chain goes on.
|
|
56
|
+
* @returns the output after them all, the refusal if there was one, and the faults met.
|
|
57
|
+
*/
|
|
58
|
+
async trigger(name, input, output) {
|
|
59
|
+
let current = output;
|
|
60
|
+
const faults = [];
|
|
61
|
+
for (const plugin of [...this.hosts.values()]) {
|
|
62
|
+
if (!plugin.hooks.has(name))
|
|
63
|
+
continue;
|
|
64
|
+
let answer;
|
|
65
|
+
try {
|
|
66
|
+
answer = await this.post(plugin, '/hook', { name, input, output: current });
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
// The host is unreachable or too slow: a runtime failure, never a refusal.
|
|
70
|
+
const detail = messageOf(error);
|
|
71
|
+
faults.push(detail);
|
|
72
|
+
if (plugin.stopping !== true) {
|
|
73
|
+
this.host.observe(plugin.componentId, `opencode:${name}`, false, detail);
|
|
74
|
+
this.host.observe(plugin.componentId, `opencode:${name}:failed`, false, detail);
|
|
75
|
+
}
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
current = isRecord(answer['output']) ? answer['output'] : current;
|
|
79
|
+
const thrown = typeof answer['error'] === 'string' ? answer['error'] : undefined;
|
|
80
|
+
// Throwing is how a `.before` hook stops the call or command: the hook did its job.
|
|
81
|
+
const refused = thrown !== undefined && STOPPING_HOOKS.has(name) && answer['errorKind'] !== 'crash';
|
|
82
|
+
if (Number(answer['ran'] ?? 0) > 0) {
|
|
83
|
+
const failed = thrown !== undefined && !refused;
|
|
84
|
+
this.host.observe(plugin.componentId, `opencode:${name}`, !failed, refused ? `stopped it: ${String(thrown)}` : failed ? String(thrown) : `${name} ran`);
|
|
85
|
+
// A failure stays on record: a later success under the same signal would replace it.
|
|
86
|
+
if (failed)
|
|
87
|
+
this.host.observe(plugin.componentId, `opencode:${name}:failed`, false, String(thrown));
|
|
88
|
+
}
|
|
89
|
+
if (thrown === undefined)
|
|
90
|
+
continue;
|
|
91
|
+
if (refused)
|
|
92
|
+
return { output: current, error: thrown, faults };
|
|
93
|
+
faults.push(thrown);
|
|
94
|
+
}
|
|
95
|
+
return { output: current, faults };
|
|
96
|
+
}
|
|
97
|
+
/** Publish one OpenCode event: to the event stream and every plugin's `event` hook. */
|
|
98
|
+
emit(event) {
|
|
99
|
+
const frame = `data: ${JSON.stringify(event)}\n\n`;
|
|
100
|
+
for (const stream of this.streams)
|
|
101
|
+
stream.write(frame);
|
|
102
|
+
for (const plugin of this.hosts.values()) {
|
|
103
|
+
if (!plugin.hooks.has('event'))
|
|
104
|
+
continue;
|
|
105
|
+
plugin.events = plugin.events.then(async () => {
|
|
106
|
+
const answer = await this.post(plugin, '/event', { event }).catch((error) => ({ ok: false, error: messageOf(error), unreached: true }));
|
|
107
|
+
const ok = answer['ok'] === true;
|
|
108
|
+
// An event the stopping host could no longer take is not something the plugin did wrong (an answer it gave is).
|
|
109
|
+
if (answer['unreached'] === true && plugin.stopping === true)
|
|
110
|
+
return;
|
|
111
|
+
this.host.observe(plugin.componentId, 'opencode:event', ok, ok ? `received ${String(event['type'])}` : `${String(event['type'])}: ${String(answer['error'] ?? 'failed')}`);
|
|
112
|
+
if (!ok)
|
|
113
|
+
this.host.observe(plugin.componentId, 'opencode:event:failed', false, `${String(event['type'])}: ${String(answer['error'] ?? 'failed')}`);
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/** One call to a plugin's Bun host; it fails when the host does not answer within the deadline. */
|
|
118
|
+
async post(plugin, path, body, options = {}) {
|
|
119
|
+
const timeoutMs = options.timeoutMs === undefined ? this.deadlineMs : options.timeoutMs;
|
|
120
|
+
const signals = [...(timeoutMs === null ? [] : [AbortSignal.timeout(timeoutMs)]), ...(options.signal === undefined ? [] : [options.signal])];
|
|
121
|
+
try {
|
|
122
|
+
const response = await fetch(`${plugin.url}${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), ...(signals.length > 0 ? { signal: AbortSignal.any(signals) } : {}) });
|
|
123
|
+
const parsed = await response.json();
|
|
124
|
+
return isRecord(parsed) ? parsed : {};
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
if (timeoutMs !== null && signals[0]?.aborted === true && options.signal?.aborted !== true)
|
|
128
|
+
throw new Error(`the plugin did not answer ${path} in ${String(Math.round(timeoutMs / 1000))}s`);
|
|
129
|
+
throw error;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
// ---------------------------------------------------------------------------
|
|
133
|
+
// DSH facts
|
|
134
|
+
// ---------------------------------------------------------------------------
|
|
135
|
+
agents() {
|
|
136
|
+
return dshService(this.ctx, 'agents');
|
|
137
|
+
}
|
|
138
|
+
agentOf(agent) {
|
|
139
|
+
const id = presetOfSession(this.ctx, agent.session);
|
|
140
|
+
if (id !== undefined)
|
|
141
|
+
return this.host.agentName(id) ?? id;
|
|
142
|
+
return (agent.session.header.delegationDepth ?? 0) > 0 ? 'general' : 'build';
|
|
143
|
+
}
|
|
144
|
+
facts(agent) {
|
|
145
|
+
const header = agent.session.header;
|
|
146
|
+
const cwd = header.cwd ?? process.cwd();
|
|
147
|
+
const project = this.projectOf(cwd);
|
|
148
|
+
const created = typeof header.createdAt === 'number' ? header.createdAt : typeof header.createdAt === 'string' ? Date.parse(header.createdAt) : Date.now();
|
|
149
|
+
const titles = dshService(this.ctx, 'sessionTitle');
|
|
150
|
+
let title = '';
|
|
151
|
+
try {
|
|
152
|
+
title = titles?.get(agent.session)?.title ?? '';
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
title = '';
|
|
156
|
+
}
|
|
157
|
+
const parentId = header.parentSession ?? this.created.get(header.id)?.parentId;
|
|
158
|
+
return {
|
|
159
|
+
id: header.id,
|
|
160
|
+
cwd,
|
|
161
|
+
projectId: project.id,
|
|
162
|
+
worktree: project.worktree,
|
|
163
|
+
...(parentId !== undefined ? { parentId } : {}),
|
|
164
|
+
title,
|
|
165
|
+
created,
|
|
166
|
+
updated: Date.now(),
|
|
167
|
+
provider: agent.options?.provider ?? '',
|
|
168
|
+
model: agent.options?.model ?? '',
|
|
169
|
+
agent: this.agentOf(agent),
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
events(agent) {
|
|
173
|
+
const events = [];
|
|
174
|
+
for (let seq = 0; seq < agent.session.seq; seq++) {
|
|
175
|
+
const event = agent.session.eventAt(seq);
|
|
176
|
+
if (event !== undefined)
|
|
177
|
+
events.push(event);
|
|
178
|
+
}
|
|
179
|
+
return events;
|
|
180
|
+
}
|
|
181
|
+
/** OpenCode's project of a directory: the git worktree and its first commit, else `global`. */
|
|
182
|
+
projectOf(directory) {
|
|
183
|
+
const cached = this.projects.get(directory);
|
|
184
|
+
if (cached !== undefined)
|
|
185
|
+
return cached;
|
|
186
|
+
const git = (...args) => {
|
|
187
|
+
const result = spawnSync('git', args, { cwd: directory, encoding: 'utf8', windowsHide: true, timeout: 10_000 });
|
|
188
|
+
return result.status === 0 ? result.stdout.trim() : undefined;
|
|
189
|
+
};
|
|
190
|
+
const worktree = git('rev-parse', '--show-toplevel');
|
|
191
|
+
const first = worktree === undefined ? undefined : git('rev-list', '--max-parents=0', '--all')?.split(/\r?\n/u).filter(Boolean).sort()[0];
|
|
192
|
+
const project = { id: first ?? 'global', worktree: worktree === undefined ? directory : resolve(worktree), created: Date.now() };
|
|
193
|
+
this.projects.set(directory, project);
|
|
194
|
+
return project;
|
|
195
|
+
}
|
|
196
|
+
/** The OpenCode configuration in effect for a directory: global, then project files, later winning. */
|
|
197
|
+
configFor(directory) {
|
|
198
|
+
const configHome = process.env['XDG_CONFIG_HOME'] ?? join(homedir(), '.config');
|
|
199
|
+
const merged = {};
|
|
200
|
+
for (const root of [join(configHome, 'opencode'), this.projectOf(directory).worktree, join(this.projectOf(directory).worktree, '.opencode'), directory, join(directory, '.opencode')]) {
|
|
201
|
+
const config = readOpenCodeConfig(root);
|
|
202
|
+
if (config !== undefined)
|
|
203
|
+
mergeConfig(merged, config);
|
|
204
|
+
}
|
|
205
|
+
const selection = this.defaultModel();
|
|
206
|
+
if (merged['model'] === undefined && selection !== undefined)
|
|
207
|
+
merged['model'] = `${selection.provider}/${selection.model}`;
|
|
208
|
+
return merged;
|
|
209
|
+
}
|
|
210
|
+
/** OpenCode's stored provider credentials (`auth.json`). */
|
|
211
|
+
storedAuth() {
|
|
212
|
+
const dataHome = process.env['XDG_DATA_HOME'] ?? join(homedir(), '.local', 'share');
|
|
213
|
+
const path = join(dataHome, 'opencode', 'auth.json');
|
|
214
|
+
if (!existsSync(path))
|
|
215
|
+
return {};
|
|
216
|
+
try {
|
|
217
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
218
|
+
return isRecord(parsed) ? parsed : {};
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
return {};
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
defaultModel() {
|
|
225
|
+
const service = dshService(this.ctx, 'agentDefaultModel');
|
|
226
|
+
try {
|
|
227
|
+
const selected = service?.currentSelection();
|
|
228
|
+
if (selected !== undefined)
|
|
229
|
+
return selected;
|
|
230
|
+
}
|
|
231
|
+
catch {
|
|
232
|
+
// No default model yet.
|
|
233
|
+
}
|
|
234
|
+
const root = this.agents()?.roots()[0];
|
|
235
|
+
return root?.options?.provider !== undefined && root.options.model !== undefined ? { provider: root.options.provider, model: root.options.model } : undefined;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
/** Deep-merge OpenCode configuration: objects merge, `plugin`/`plugins`/`instructions` concatenate, the rest is replaced. */
|
|
239
|
+
function mergeConfig(into, from) {
|
|
240
|
+
for (const [key, value] of Object.entries(from)) {
|
|
241
|
+
const current = into[key];
|
|
242
|
+
if ((key === 'plugin' || key === 'plugins' || key === 'instructions') && Array.isArray(value))
|
|
243
|
+
into[key] = [...(Array.isArray(current) ? current : []), ...value];
|
|
244
|
+
else if (isRecord(value) && isRecord(current))
|
|
245
|
+
mergeConfig(current, value);
|
|
246
|
+
else
|
|
247
|
+
into[key] = isRecord(value) ? structuredClone(value) : value;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { type LoggedEvent } from '../convert.js';
|
|
2
|
+
import type { OpenCodeCore } from './core.js';
|
|
3
|
+
import type { Agent, Message, ToolExec } from './types.js';
|
|
4
|
+
/**
|
|
5
|
+
* DSH's events raised as OpenCode hooks and events: session events,
|
|
6
|
+
* `chat.message`, `chat.params`, `tool.execute.before` / `.after`,
|
|
7
|
+
* `permission.ask`, the prompt and tool transforms, `shell.env` and
|
|
8
|
+
* `command.execute.before`.
|
|
9
|
+
*/
|
|
10
|
+
export declare class EventBridge {
|
|
11
|
+
private readonly core;
|
|
12
|
+
/** Calls whose arguments the `tool.execute.before` hooks saw, by call id. */
|
|
13
|
+
private readonly calls;
|
|
14
|
+
constructor(core: OpenCodeCore);
|
|
15
|
+
sessionCreated(agent: Agent): void;
|
|
16
|
+
/** The session log, as OpenCode's events. */
|
|
17
|
+
sessionEvent(sessionId: string, event: LoggedEvent): void;
|
|
18
|
+
/**
|
|
19
|
+
* `chat.message` for each prompt about to enter: the plugin sees the
|
|
20
|
+
* message and its parts before the session holds it, may change or add
|
|
21
|
+
* parts, and the prompts it sends meanwhile (`noReply`) enter before it.
|
|
22
|
+
*/
|
|
23
|
+
preStep(payload: {
|
|
24
|
+
agent: Agent;
|
|
25
|
+
messages: Message[];
|
|
26
|
+
signal: AbortSignal;
|
|
27
|
+
}, next: () => Promise<{
|
|
28
|
+
kind: string;
|
|
29
|
+
messages?: Message[];
|
|
30
|
+
}>): Promise<unknown>;
|
|
31
|
+
/** `chat.params`: the temperature and output tokens a plugin sets reach the request. */
|
|
32
|
+
request(payload: {
|
|
33
|
+
agent: Agent;
|
|
34
|
+
}, next: () => Promise<Record<string, unknown>>): Promise<Record<string, unknown>>;
|
|
35
|
+
/** `tool.execute.before`: OpenCode's view of the call; a throw refuses it, changed arguments run. */
|
|
36
|
+
preExecute(exec: ToolExec, next: () => Promise<unknown>): Promise<unknown>;
|
|
37
|
+
/** `tool.execute.after`: the plugin may rewrite the output the model reads. */
|
|
38
|
+
postExecute(exec: ToolExec, result: {
|
|
39
|
+
isError: boolean;
|
|
40
|
+
content?: Array<{
|
|
41
|
+
type: string;
|
|
42
|
+
text?: string;
|
|
43
|
+
}>;
|
|
44
|
+
}, next: () => Promise<{
|
|
45
|
+
kind: string;
|
|
46
|
+
content?: unknown[];
|
|
47
|
+
}>): Promise<unknown>;
|
|
48
|
+
toolResult(exec: ToolExec, result: {
|
|
49
|
+
isError: boolean;
|
|
50
|
+
}): void;
|
|
51
|
+
/** `permission.ask` before DSH asks the person: `allow` and `deny` answer for them. */
|
|
52
|
+
approval(request: {
|
|
53
|
+
agent: Agent;
|
|
54
|
+
toolName: string;
|
|
55
|
+
callId?: string;
|
|
56
|
+
reason?: string;
|
|
57
|
+
}, next: () => Promise<string>): Promise<string>;
|
|
58
|
+
/**
|
|
59
|
+
* `experimental.chat.system.transform` on the assembled prompt. (`tool.definition` has no seam: DSH collects the
|
|
60
|
+
* offered tools outside the assembly a listener sees.)
|
|
61
|
+
*/
|
|
62
|
+
assemble(next: () => Promise<{
|
|
63
|
+
sections: Array<{
|
|
64
|
+
name: string;
|
|
65
|
+
text: string;
|
|
66
|
+
}>;
|
|
67
|
+
}>): Promise<unknown>;
|
|
68
|
+
/** `shell.env`: the variables plugins add to a shell call's environment. */
|
|
69
|
+
shellEnv(exec: ToolExec): Promise<Record<string, string>>;
|
|
70
|
+
/**
|
|
71
|
+
* `command.execute.before` for an OpenCode command about to be submitted:
|
|
72
|
+
* the plugin sees the command and the parts of its prompt, and may change them.
|
|
73
|
+
*/
|
|
74
|
+
beforeCommand(agent: Agent, command: {
|
|
75
|
+
name: string;
|
|
76
|
+
args: string;
|
|
77
|
+
}, prompt: string): Promise<string[] | {
|
|
78
|
+
stopped: string;
|
|
79
|
+
}>;
|
|
80
|
+
}
|