@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.
- package/LICENSE +21 -0
- package/README.md +42 -2
- package/assets/icon.svg +12 -0
- package/cordis.patch.yml +28 -0
- package/lib/agents/presets.d.ts +91 -0
- package/lib/agents/presets.js +282 -0
- package/lib/agents/profiles.d.ts +58 -0
- package/lib/agents/profiles.js +278 -0
- package/lib/agents/row.d.ts +17 -0
- package/lib/agents/row.js +146 -0
- package/lib/client/styles.d.ts +8 -0
- package/lib/client/styles.js +89 -0
- package/lib/client/typert.d.ts +14 -0
- package/lib/client/typert.js +110 -0
- package/lib/client.js +22500 -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 +107 -0
- package/lib/dsh/host.js +214 -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 +231 -0
- package/lib/forge/contract.js +43 -0
- package/lib/forge/ledger.d.ts +143 -0
- package/lib/forge/ledger.js +733 -0
- package/lib/forge/live-mounts.d.ts +45 -0
- package/lib/forge/live-mounts.js +78 -0
- package/lib/forge/marketplace-install.d.ts +3 -0
- package/lib/forge/marketplace-install.js +64 -0
- package/lib/forge/npm.d.ts +31 -0
- package/lib/forge/npm.js +60 -0
- package/lib/forge/projects.d.ts +94 -0
- package/lib/forge/projects.js +336 -0
- package/lib/forge/receipts.d.ts +5 -0
- package/lib/forge/receipts.js +31 -0
- package/lib/forge/row.d.ts +32 -0
- package/lib/forge/row.js +59 -0
- package/lib/forge/service.d.ts +105 -0
- package/lib/forge/service.js +274 -0
- package/lib/forge/settings.d.ts +41 -0
- package/lib/forge/settings.js +115 -0
- package/lib/forge/state.d.ts +69 -0
- package/lib/forge/state.js +150 -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 +728 -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 +22 -0
- package/lib/hooks/broker/session-events.js +196 -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 +262 -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 +11 -0
- package/lib/hooks/condition.js +181 -0
- package/lib/hooks/config.d.ts +85 -0
- package/lib/hooks/config.js +150 -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 +14 -0
- package/lib/hooks/permissions.js +109 -0
- package/lib/hooks/process.d.ts +47 -0
- package/lib/hooks/process.js +134 -0
- package/lib/hooks/row.d.ts +17 -0
- package/lib/hooks/row.js +94 -0
- package/lib/hooks/runner.d.ts +85 -0
- package/lib/hooks/runner.js +293 -0
- package/lib/hooks/shell-commands.d.ts +19 -0
- package/lib/hooks/shell-commands.js +177 -0
- package/lib/hooks/shell.d.ts +43 -0
- package/lib/hooks/shell.js +126 -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 +364 -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 +36 -0
- package/lib/mcp/catalog.js +61 -0
- package/lib/mcp/mount.d.ts +75 -0
- package/lib/mcp/mount.js +217 -0
- package/lib/mcp/remote.d.ts +45 -0
- package/lib/mcp/remote.js +143 -0
- package/lib/mcp/row.d.ts +9 -0
- package/lib/mcp/row.js +131 -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 +227 -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 +32 -0
- package/lib/mods/service/turns.js +161 -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 +156 -0
- package/lib/opencode/convert.d.ts +53 -0
- package/lib/opencode/convert.js +255 -0
- package/lib/opencode/row.d.ts +9 -0
- package/lib/opencode/row.js +86 -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 +353 -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/port-gap.d.ts +30 -0
- package/lib/porting/port-gap.js +122 -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 +49 -0
- package/lib/porting/row.d.ts +16 -0
- package/lib/porting/row.js +25 -0
- package/lib/porting/verify-port.d.ts +53 -0
- package/lib/porting/verify-port.js +104 -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/claude.d.ts +29 -0
- package/lib/sessions/claude.js +83 -0
- package/lib/sessions/codex.d.ts +30 -0
- package/lib/sessions/codex.js +303 -0
- package/lib/sessions/opencode.d.ts +32 -0
- package/lib/sessions/opencode.js +320 -0
- package/lib/sessions/row.d.ts +14 -0
- package/lib/sessions/row.js +35 -0
- package/lib/shared/invocation.d.ts +169 -0
- package/lib/shared/invocation.js +325 -0
- package/lib/shared/render.d.ts +72 -0
- package/lib/shared/render.js +588 -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 +72 -0
- package/lib/skills/provider.js +340 -0
- package/lib/skills/row.d.ts +22 -0
- package/lib/skills/row.js +204 -0
- package/lib/workbench/adapter-coverage.d.ts +47 -0
- package/lib/workbench/adapter-coverage.js +102 -0
- package/lib/workbench/model-tools.d.ts +10 -0
- package/lib/workbench/model-tools.js +122 -0
- package/lib/workbench/overview.d.ts +103 -0
- package/lib/workbench/overview.js +159 -0
- package/lib/workbench/remote.d.ts +118 -0
- package/lib/workbench/remote.js +422 -0
- package/lib/workbench/row.d.ts +15 -0
- package/lib/workbench/row.js +16 -0
- package/lib/workbench/settings.d.ts +15 -0
- package/lib/workbench/settings.js +56 -0
- package/lib/workbench/workbench.d.ts +100 -0
- package/lib/workbench/workbench.js +260 -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 +6 -0
- package/package.json +246 -3
- package/runtime/opencode-host.mjs +270 -0
- package/skills/harness-forge/SKILL.md +47 -0
package/lib/mods/host.js
ADDED
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core of the mods engine inside a DSH session: what Claude Code itself does
|
|
3
|
+
* at each event a mod's `$` call or a DSH call site raises, served by the
|
|
4
|
+
* composed DSH services and Harness Forge's runtime.
|
|
5
|
+
* @module @kirkchinese/harness-forge/mods
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync, lstatSync, realpathSync } from 'node:fs';
|
|
8
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
9
|
+
import { createUserMessage } from '@deepseek-ai/dsh-llm';
|
|
10
|
+
import { appendNotice } from '../hooks/notice.js';
|
|
11
|
+
import { isRecord, jsonCopy, messageOf } from './values.js';
|
|
12
|
+
import { contextPressureOf, dshService, lastTurnOf } from '../dsh/host.js';
|
|
13
|
+
const STORE_MAX_BYTES = 4 * 1024 * 1024;
|
|
14
|
+
const FILE_MAX_BYTES = 4 * 1024 * 1024;
|
|
15
|
+
const OUTPUT_MAX_BYTES = 4 * 1024 * 1024;
|
|
16
|
+
/** The core of one session's mods engine. */
|
|
17
|
+
export class SessionHost {
|
|
18
|
+
services;
|
|
19
|
+
agent;
|
|
20
|
+
interactive;
|
|
21
|
+
/** Withdrawals of what the session's mods registered. */
|
|
22
|
+
registrations = [];
|
|
23
|
+
stores = new Map();
|
|
24
|
+
constructor(services, agent, interactive) {
|
|
25
|
+
this.services = services;
|
|
26
|
+
this.agent = agent;
|
|
27
|
+
this.interactive = interactive;
|
|
28
|
+
}
|
|
29
|
+
get ctx() {
|
|
30
|
+
return this.services.ctx;
|
|
31
|
+
}
|
|
32
|
+
/** Core at an op event: `{ value }` or `{ deny }`. */
|
|
33
|
+
async op(event, e, context) {
|
|
34
|
+
const plugin = context.mod?.ref.name ?? context.origin.plugin;
|
|
35
|
+
try {
|
|
36
|
+
const value = await this.serve(event, e, plugin, context);
|
|
37
|
+
return { value };
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
return { deny: messageOf(error) };
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
async cwd(signal) {
|
|
44
|
+
return this.services.directory(this.agent, signal).catch(() => this.agent.session.header.cwd ?? process.cwd());
|
|
45
|
+
}
|
|
46
|
+
async path(path, signal) {
|
|
47
|
+
if (typeof path !== 'string' || path.length === 0)
|
|
48
|
+
throw new Error('takes a path');
|
|
49
|
+
return isAbsolute(path) ? path : resolve(await this.cwd(signal), path);
|
|
50
|
+
}
|
|
51
|
+
async serve(event, e, plugin, context) {
|
|
52
|
+
const signal = context.signal;
|
|
53
|
+
switch (event) {
|
|
54
|
+
// ---- session facts -----------------------------------------------------
|
|
55
|
+
case 'session.id': return this.agent.session.header.id;
|
|
56
|
+
case 'session.cwd': return this.cwd(signal);
|
|
57
|
+
case 'session.root': return this.agent.session.header.cwd ?? this.cwd(signal);
|
|
58
|
+
case 'session.model': return this.agent.session.requestHeader?.()?.config?.model ?? this.agent.options?.model ?? '';
|
|
59
|
+
case 'session.turns': return this.turns();
|
|
60
|
+
case 'session.messages': return this.messages();
|
|
61
|
+
case 'session.surfaces': return this.interactive ? ['desktop'] : [];
|
|
62
|
+
case 'session.surface': return this.interactive ? 'desktop' : 'terminal';
|
|
63
|
+
case 'session.usage': return this.usage();
|
|
64
|
+
case 'session.version': return { version: 'harness-forge/dsh', base: '2.1.277' };
|
|
65
|
+
case 'session.repo': return this.repo(signal);
|
|
66
|
+
case 'session.identity': return this.identity();
|
|
67
|
+
case 'session.authorize': return null;
|
|
68
|
+
// ---- files -------------------------------------------------------------
|
|
69
|
+
case 'fs.read': {
|
|
70
|
+
const path = await this.path(e['path'], signal);
|
|
71
|
+
if (statSync(path).size > FILE_MAX_BYTES)
|
|
72
|
+
throw new Error(`${path} is over the 4194304-byte limit`);
|
|
73
|
+
return e['as'] === 'bytes' ? { base64: readFileSync(path).toString('base64') } : readFileSync(path, 'utf8');
|
|
74
|
+
}
|
|
75
|
+
case 'fs.write': {
|
|
76
|
+
const path = await this.path(e['path'], signal);
|
|
77
|
+
const text = String(e['text'] ?? '');
|
|
78
|
+
if (Buffer.byteLength(text) > FILE_MAX_BYTES)
|
|
79
|
+
throw new Error('the text is over the 4194304-byte limit');
|
|
80
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
81
|
+
writeFileSync(path, text);
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
case 'fs.list': {
|
|
85
|
+
const path = await this.path(e['path'] ?? '.', signal);
|
|
86
|
+
return readdirSync(path, { withFileTypes: true }).map((entry) => {
|
|
87
|
+
const full = join(path, entry.name);
|
|
88
|
+
const link = entry.isSymbolicLink();
|
|
89
|
+
let size = 0;
|
|
90
|
+
try {
|
|
91
|
+
size = statSync(full).size;
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
size = 0;
|
|
95
|
+
}
|
|
96
|
+
return { name: entry.name, kind: entry.isDirectory() ? 'dir' : entry.isFile() ? 'file' : link ? statKind(full) : 'other', size, isLink: link };
|
|
97
|
+
}).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
98
|
+
}
|
|
99
|
+
case 'fs.exists': return existsSync(await this.path(e['path'], signal));
|
|
100
|
+
case 'fs.stat': {
|
|
101
|
+
const path = await this.path(e['path'], signal);
|
|
102
|
+
const own = lstatSync(path);
|
|
103
|
+
const link = own.isSymbolicLink();
|
|
104
|
+
const info = link ? statSync(path) : own;
|
|
105
|
+
return {
|
|
106
|
+
kind: info.isDirectory() ? 'dir' : info.isFile() ? 'file' : 'other',
|
|
107
|
+
size: info.size,
|
|
108
|
+
mtimeMs: info.mtimeMs,
|
|
109
|
+
isLink: link,
|
|
110
|
+
...(e['resolve'] === true ? { realPath: realpathSync(path) } : {}),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
case 'fs.ancestors': return this.ancestors(e, signal);
|
|
114
|
+
// ---- store ------------------------------------------------------------
|
|
115
|
+
case 'store.get': return this.store(plugin)[String(e['key'])];
|
|
116
|
+
case 'store.set': {
|
|
117
|
+
const store = { ...this.store(plugin), [String(e['key'])]: jsonCopy(e['value']) };
|
|
118
|
+
this.saveStore(plugin, store);
|
|
119
|
+
return undefined;
|
|
120
|
+
}
|
|
121
|
+
case 'store.delete': {
|
|
122
|
+
const store = { ...this.store(plugin) };
|
|
123
|
+
delete store[String(e['key'])];
|
|
124
|
+
this.saveStore(plugin, store);
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
case 'store.keys': return Object.keys(this.store(plugin));
|
|
128
|
+
// ---- time --------------------------------------------------------------
|
|
129
|
+
case 'clock.now': return Date.now();
|
|
130
|
+
case 'clock.sleep':
|
|
131
|
+
case 'clock.after':
|
|
132
|
+
case 'clock.every':
|
|
133
|
+
await sleep(Number(e['ms']) || 0, signal);
|
|
134
|
+
return undefined;
|
|
135
|
+
// ---- processes, network, environment, settings -------------------------
|
|
136
|
+
case 'process.run': return this.run(e, signal);
|
|
137
|
+
case 'http.fetch': return this.fetch(e, signal);
|
|
138
|
+
case 'env.get': return process.env[String(e['name'])];
|
|
139
|
+
case 'env.set': {
|
|
140
|
+
const name = String(e['name']);
|
|
141
|
+
if (typeof e['value'] === 'string')
|
|
142
|
+
process.env[name] = e['value'];
|
|
143
|
+
else
|
|
144
|
+
delete process.env[name];
|
|
145
|
+
return undefined;
|
|
146
|
+
}
|
|
147
|
+
case 'settings.read': return this.services.settings(typeof e['source'] === 'string' ? e['source'] : undefined);
|
|
148
|
+
// ---- display -----------------------------------------------------------
|
|
149
|
+
case 'ui.log':
|
|
150
|
+
this.services.show(e['to'] === 'debug' ? 'debug' : 'transcript', plugin, String(e['text'] ?? ''));
|
|
151
|
+
return undefined;
|
|
152
|
+
case 'ui.toast':
|
|
153
|
+
this.services.show('toast', plugin, String(e['text'] ?? ''));
|
|
154
|
+
return undefined;
|
|
155
|
+
case 'ui.status':
|
|
156
|
+
this.services.show('status', plugin, typeof e['text'] === 'string' ? e['text'] : undefined);
|
|
157
|
+
return undefined;
|
|
158
|
+
case 'ui.notice': return undefined;
|
|
159
|
+
case 'ui.invalidate':
|
|
160
|
+
this.services.invalidate(plugin);
|
|
161
|
+
return undefined;
|
|
162
|
+
case 'ui.open': return this.services.pane(plugin, 'open', e);
|
|
163
|
+
case 'ui.close':
|
|
164
|
+
this.services.pane(plugin, 'close', e);
|
|
165
|
+
return undefined;
|
|
166
|
+
case 'ui.panes': return this.services.panes();
|
|
167
|
+
case 'ui.copy': return { isCopied: false, reason: 'no-clipboard: the copy reaches the client when it draws the button' };
|
|
168
|
+
case 'ui.notify': return { isSent: false, channel: 'none' };
|
|
169
|
+
// ---- commands and tools ------------------------------------------------
|
|
170
|
+
case 'command.register': {
|
|
171
|
+
const withdraw = this.services.registerCommand(plugin, e);
|
|
172
|
+
this.registrations.push(withdraw);
|
|
173
|
+
return { command: String(e['name']) };
|
|
174
|
+
}
|
|
175
|
+
case 'command.list': {
|
|
176
|
+
const commands = this.scoped('commands');
|
|
177
|
+
return (commands?.list(this.agent) ?? []).map(command => ({ name: command.name, description: command.description ?? '', source: 'builtin' }));
|
|
178
|
+
}
|
|
179
|
+
case 'tool.register': return this.registerTool(plugin, e);
|
|
180
|
+
case 'tool.list': {
|
|
181
|
+
const tools = this.scoped('tools');
|
|
182
|
+
return (tools?.schemas(this.agent) ?? []).map(tool => ({ name: tool.name, description: tool.description ?? '', mcp: tool.name.startsWith('mcp__') }));
|
|
183
|
+
}
|
|
184
|
+
case 'model.complete': return this.complete(e, signal);
|
|
185
|
+
case 'model.classify': return this.classify(e, signal);
|
|
186
|
+
case 'agent.list': return [];
|
|
187
|
+
case 'mcp.call': {
|
|
188
|
+
const tools = this.scoped('tools');
|
|
189
|
+
if (tools === undefined)
|
|
190
|
+
throw new Error('no tool runtime');
|
|
191
|
+
const result = await tools.execute({ callId: `mod-mcp-${crypto.randomUUID()}`, name: `mcp__${String(e['server'])}__${String(e['tool'])}`, arguments: e['args'] ?? {}, agent: this.agent, signal });
|
|
192
|
+
return { content: result.content ?? [], isError: result.isError };
|
|
193
|
+
}
|
|
194
|
+
case 'telemetry.log':
|
|
195
|
+
case 'telemetry.mark':
|
|
196
|
+
// Claude Code's collector is first-party analytics; DSH has none to send to.
|
|
197
|
+
return undefined;
|
|
198
|
+
// A plugin stopping the turn is a hook's cancel; what the person queued stays.
|
|
199
|
+
case 'turn.abort':
|
|
200
|
+
this.agent.cancel?.({ kind: 'hook', reason: 'a plugin aborted the turn' }, { keepInbox: true });
|
|
201
|
+
return undefined;
|
|
202
|
+
case 'prompt.read': return { text: '', cursor: 0 };
|
|
203
|
+
default:
|
|
204
|
+
throw new Error(`${event} is not served by this host`);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* The account the session is signed in as: DSH's DeepSeek account where one
|
|
209
|
+
* is signed in (its contact, when an email address), as Claude Code answers
|
|
210
|
+
* with its own login; an API-key or keyless session has none.
|
|
211
|
+
*/
|
|
212
|
+
async identity() {
|
|
213
|
+
const account = dshService(this.ctx, 'deepseekAccount');
|
|
214
|
+
if (account === undefined)
|
|
215
|
+
return { kind: 'none', isVerified: false };
|
|
216
|
+
const profile = await account.getProfile({ version: 'harness-forge', locale: Intl.DateTimeFormat().resolvedOptions().locale, timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60 }).catch(() => null);
|
|
217
|
+
if (profile?.status !== 'ready')
|
|
218
|
+
return { kind: 'none', isVerified: false };
|
|
219
|
+
const contact = profile.value?.contact ?? undefined;
|
|
220
|
+
return { kind: 'deepseek', isVerified: true, ...(typeof contact === 'string' && contact.includes('@') ? { email: contact } : {}) };
|
|
221
|
+
}
|
|
222
|
+
scoped(service) {
|
|
223
|
+
const agentCtx = this.agent.ctx;
|
|
224
|
+
return (dshService(agentCtx, service) ?? dshService(this.ctx, service));
|
|
225
|
+
}
|
|
226
|
+
turns() {
|
|
227
|
+
return lastTurnOf(this.ctx, this.agent.session) ?? 0;
|
|
228
|
+
}
|
|
229
|
+
messages() {
|
|
230
|
+
const rows = this.agent.session.deriveMessages?.() ?? [];
|
|
231
|
+
return rows.slice(-4096).map((row) => {
|
|
232
|
+
const blocks = Array.isArray(row.content) ? row.content : [];
|
|
233
|
+
return {
|
|
234
|
+
role: row.role === 'assistant' ? 'assistant' : 'user',
|
|
235
|
+
text: blocks.filter(block => block['type'] === 'text').map(block => String(block['text'] ?? '')).join(''),
|
|
236
|
+
toolUses: blocks.filter(block => block['type'] === 'tool-call' || block['type'] === 'tool_use').map(block => ({ name: String(block['name'] ?? block['toolName'] ?? ''), input: block['arguments'] ?? block['input'] ?? {} })),
|
|
237
|
+
};
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
usage() {
|
|
241
|
+
const created = this.agent.session.header.createdAt;
|
|
242
|
+
const startedAt = typeof created === 'number' ? created : typeof created === 'string' ? Date.parse(created) : Date.now();
|
|
243
|
+
const pressure = contextPressureOf(this.ctx, this.agent.session);
|
|
244
|
+
const tokens = pressure?.pressureTokens;
|
|
245
|
+
const window = pressure?.contextWindow ?? 0;
|
|
246
|
+
return {
|
|
247
|
+
startedAt,
|
|
248
|
+
context: { ...(tokens !== undefined ? { tokens } : {}), window, ...(tokens !== undefined && window > 0 ? { percent: Math.round(tokens / window * 100) } : {}) },
|
|
249
|
+
rateLimits: [],
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
async repo(signal) {
|
|
253
|
+
const cwd = await this.cwd(signal);
|
|
254
|
+
const top = await this.services.shell.runExec('git', ['rev-parse', '--show-toplevel'], { cwd, signal });
|
|
255
|
+
if (top.exitCode !== 0)
|
|
256
|
+
return null;
|
|
257
|
+
const root = top.stdout.trim();
|
|
258
|
+
const remote = await this.services.shell.runExec('git', ['remote', 'get-url', 'origin'], { cwd: root, signal });
|
|
259
|
+
const branch = await this.services.shell.runExec('git', ['branch', '--show-current'], { cwd: root, signal });
|
|
260
|
+
return {
|
|
261
|
+
root,
|
|
262
|
+
...(remote.exitCode === 0 && remote.stdout.trim().length > 0 ? { remote: remote.stdout.trim() } : {}),
|
|
263
|
+
...(branch.exitCode === 0 && branch.stdout.trim().length > 0 ? { branch: branch.stdout.trim() } : {}),
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
/** `$.fs.ancestors`: the named instruction files from the root down to `of`, with their `@` imports. */
|
|
267
|
+
async ancestors(e, signal) {
|
|
268
|
+
const names = Array.isArray(e['names']) ? e['names'].filter((name) => typeof name === 'string') : [];
|
|
269
|
+
const target = typeof e['of'] === 'string' ? dirname(await this.path(e['of'], signal)) : await this.cwd(signal);
|
|
270
|
+
const below = typeof e['below'] === 'string' ? await this.path(e['below'], signal) : undefined;
|
|
271
|
+
const dirs = [];
|
|
272
|
+
let current = resolve(target);
|
|
273
|
+
for (;;) {
|
|
274
|
+
dirs.unshift(current);
|
|
275
|
+
const parent = dirname(current);
|
|
276
|
+
if (parent === current)
|
|
277
|
+
break;
|
|
278
|
+
current = parent;
|
|
279
|
+
}
|
|
280
|
+
const within = (dir) => (below === undefined ? true : dir !== below && (dir + sep).startsWith(below + sep));
|
|
281
|
+
const out = [];
|
|
282
|
+
for (const dir of dirs.filter(within)) {
|
|
283
|
+
for (const name of names) {
|
|
284
|
+
const path = join(dir, name);
|
|
285
|
+
if (!existsSync(path) || !statSync(path).isFile())
|
|
286
|
+
continue;
|
|
287
|
+
const content = readFileSync(path, 'utf8');
|
|
288
|
+
out.push({ dir, name, content, parts: [{ path, content }] });
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
return out;
|
|
292
|
+
}
|
|
293
|
+
store(plugin) {
|
|
294
|
+
const cached = this.stores.get(plugin);
|
|
295
|
+
if (cached !== undefined)
|
|
296
|
+
return cached;
|
|
297
|
+
const path = join(this.services.storeRoot, `${plugin}.json`);
|
|
298
|
+
let value = {};
|
|
299
|
+
try {
|
|
300
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
301
|
+
if (isRecord(parsed))
|
|
302
|
+
value = parsed;
|
|
303
|
+
}
|
|
304
|
+
catch {
|
|
305
|
+
value = {};
|
|
306
|
+
}
|
|
307
|
+
this.stores.set(plugin, value);
|
|
308
|
+
return value;
|
|
309
|
+
}
|
|
310
|
+
saveStore(plugin, value) {
|
|
311
|
+
const text = JSON.stringify(value);
|
|
312
|
+
if (Buffer.byteLength(text) > STORE_MAX_BYTES)
|
|
313
|
+
throw new Error(`${plugin}'s store would be over 4 MiB of JSON`);
|
|
314
|
+
mkdirSync(this.services.storeRoot, { recursive: true });
|
|
315
|
+
writeFileSync(join(this.services.storeRoot, `${plugin}.json`), text);
|
|
316
|
+
this.stores.set(plugin, value);
|
|
317
|
+
}
|
|
318
|
+
async run(e, signal) {
|
|
319
|
+
const argv = Array.isArray(e['argv']) ? e['argv'].map(String) : [];
|
|
320
|
+
if (argv.length === 0)
|
|
321
|
+
throw new Error('takes an argv of at least the command');
|
|
322
|
+
const init = isRecord(e['init']) ? e['init'] : {};
|
|
323
|
+
const timeoutMs = Math.min(600_000, typeof init['timeoutMs'] === 'number' ? init['timeoutMs'] : 30_000);
|
|
324
|
+
const cwd = typeof init['cwd'] === 'string' ? await this.path(init['cwd'], signal) : await this.cwd(signal);
|
|
325
|
+
const env = isRecord(init['env']) ? Object.fromEntries(Object.entries(init['env']).filter((entry) => typeof entry[1] === 'string')) : undefined;
|
|
326
|
+
const outcome = await this.services.shell.runExec(argv[0], argv.slice(1), {
|
|
327
|
+
cwd,
|
|
328
|
+
timeoutMs,
|
|
329
|
+
signal,
|
|
330
|
+
...(env !== undefined ? { env } : {}),
|
|
331
|
+
...(typeof init['stdin'] === 'string' ? { stdin: init['stdin'] } : {}),
|
|
332
|
+
});
|
|
333
|
+
if (outcome.startError !== undefined)
|
|
334
|
+
throw new Error(`${argv[0]} did not start: ${outcome.startError}`);
|
|
335
|
+
if (outcome.timedOut)
|
|
336
|
+
throw new Error(`${argv[0]} was still running after ${String(timeoutMs)} ms`);
|
|
337
|
+
const stdout = outcome.stdout.length > OUTPUT_MAX_BYTES ? outcome.stdout.slice(0, OUTPUT_MAX_BYTES) : outcome.stdout;
|
|
338
|
+
const stderr = outcome.stderr.length > OUTPUT_MAX_BYTES ? outcome.stderr.slice(0, OUTPUT_MAX_BYTES) : outcome.stderr;
|
|
339
|
+
return {
|
|
340
|
+
exitCode: outcome.exitCode ?? -1,
|
|
341
|
+
stdout,
|
|
342
|
+
stderr,
|
|
343
|
+
...(stdout.length < outcome.stdout.length ? { isStdoutTruncated: true } : {}),
|
|
344
|
+
...(stderr.length < outcome.stderr.length ? { isStderrTruncated: true } : {}),
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
async fetch(e, signal) {
|
|
348
|
+
const url = String(e['url']);
|
|
349
|
+
const init = isRecord(e['init']) ? e['init'] : {};
|
|
350
|
+
const headers = isRecord(init['headers']) ? Object.fromEntries(Object.entries(init['headers']).map(([key, value]) => [key, String(value)])) : {};
|
|
351
|
+
const response = await fetch(url, {
|
|
352
|
+
method: typeof init['method'] === 'string' ? init['method'] : 'GET',
|
|
353
|
+
headers,
|
|
354
|
+
...(typeof init['body'] === 'string' ? { body: init['body'] } : {}),
|
|
355
|
+
redirect: 'follow',
|
|
356
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]),
|
|
357
|
+
});
|
|
358
|
+
const text = (await response.text()).slice(0, 4 * 1024 * 1024);
|
|
359
|
+
return { status: response.status, ok: response.ok, headers: Object.fromEntries(response.headers.entries()), text };
|
|
360
|
+
}
|
|
361
|
+
registerTool(plugin, e) {
|
|
362
|
+
const tools = dshService(this.ctx, 'tools');
|
|
363
|
+
if (tools === undefined)
|
|
364
|
+
throw new Error('no tool runtime');
|
|
365
|
+
const name = String(e['name']);
|
|
366
|
+
if (!/^[A-Za-z0-9_-]{1,64}$/u.test(name))
|
|
367
|
+
throw new Error('tool names are letters, digits, "_" and "-", up to 64 characters');
|
|
368
|
+
const full = `mcp__${plugin}__${name}`;
|
|
369
|
+
const withdraw = tools.register({
|
|
370
|
+
name: full,
|
|
371
|
+
description: String(e['description'] ?? ''),
|
|
372
|
+
parameters: isRecord(e['inputSchema']) ? e['inputSchema'] : { type: 'object', properties: {} },
|
|
373
|
+
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
|
|
374
|
+
execute: () => Promise.reject(new Error(`${plugin} registered ${full} but no tool.call hook answered it`)),
|
|
375
|
+
});
|
|
376
|
+
this.registrations.push(withdraw);
|
|
377
|
+
return { tool: full };
|
|
378
|
+
}
|
|
379
|
+
async complete(e, signal) {
|
|
380
|
+
const llm = dshService(this.ctx, 'llm');
|
|
381
|
+
if (llm === undefined)
|
|
382
|
+
throw new Error('no model is composed');
|
|
383
|
+
const provider = this.agent.options?.provider;
|
|
384
|
+
const model = this.agent.options?.model;
|
|
385
|
+
if (provider === undefined || model === undefined)
|
|
386
|
+
throw new Error('the session names no model');
|
|
387
|
+
const call = await llm.prepareCall({ provider, model, maxTokens: typeof e['maxTokens'] === 'number' ? e['maxTokens'] : 1024 }, signal);
|
|
388
|
+
let text = '';
|
|
389
|
+
for await (const chunk of call.stream({
|
|
390
|
+
...(typeof e['system'] === 'string' ? { system: e['system'] } : {}),
|
|
391
|
+
messages: [createUserMessage({ content: [{ type: 'text', text: String(e['prompt'] ?? '') }], source: { kind: 'user' } })],
|
|
392
|
+
signal,
|
|
393
|
+
})) {
|
|
394
|
+
if (isRecord(chunk) && chunk['type'] === 'text-delta' && typeof chunk['delta'] === 'string')
|
|
395
|
+
text += chunk['delta'];
|
|
396
|
+
if (isRecord(chunk) && chunk['type'] === 'text' && typeof chunk['text'] === 'string')
|
|
397
|
+
text += chunk['text'];
|
|
398
|
+
}
|
|
399
|
+
return { isAnswered: true, text, usage: { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 } };
|
|
400
|
+
}
|
|
401
|
+
async classify(e, signal) {
|
|
402
|
+
const labels = Array.isArray(e['labels']) ? e['labels'].map(String) : [];
|
|
403
|
+
const answer = await this.complete({ prompt: `${String(e['text'] ?? '')}\n\nAnswer with exactly one of: ${labels.join(', ')}`, maxTokens: 32 }, signal);
|
|
404
|
+
return labels.find(label => answer.text.toLowerCase().includes(label.toLowerCase())) ?? labels[0] ?? '';
|
|
405
|
+
}
|
|
406
|
+
/** Run a slash command line in the session (`$.command.run`). */
|
|
407
|
+
async runCommand(command, args, signal) {
|
|
408
|
+
const commands = this.scoped('commands');
|
|
409
|
+
if (commands === undefined)
|
|
410
|
+
throw new Error('no command registry');
|
|
411
|
+
const line = args.length > 0 ? `/${command} ${args}` : `/${command}`;
|
|
412
|
+
const execution = await commands.execute(this.agent, line, [], signal);
|
|
413
|
+
if (execution === undefined)
|
|
414
|
+
throw new Error(`/${command} is not a command`);
|
|
415
|
+
if (execution.result.kind === 'error')
|
|
416
|
+
throw new Error(execution.result.text ?? `/${command} failed`);
|
|
417
|
+
return execution.result.text === undefined ? {} : { text: execution.result.text };
|
|
418
|
+
}
|
|
419
|
+
/** A note a plugin appends (`$.session.append`): kept in the conversation. */
|
|
420
|
+
appendNote(plugin, e) {
|
|
421
|
+
const message = isRecord(e['message']) ? e['message'] : {};
|
|
422
|
+
const content = Array.isArray(message['content']) ? message['content'] : [];
|
|
423
|
+
const text = content.filter(isRecord).map(block => String(block['text'] ?? '')).join('\n');
|
|
424
|
+
if (message['type'] === 'system') {
|
|
425
|
+
appendNotice(this.agent.session, { kind: 'system-message', event: 'session.append', plugin, text });
|
|
426
|
+
}
|
|
427
|
+
else {
|
|
428
|
+
this.agent.inject(createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }));
|
|
429
|
+
}
|
|
430
|
+
return { message, uuid: e['uuid'] };
|
|
431
|
+
}
|
|
432
|
+
/** Relative path a mod sees for a file, from the session's root. */
|
|
433
|
+
relativePath(path) {
|
|
434
|
+
return relative(this.agent.session.header.cwd ?? process.cwd(), path);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
function statKind(path) {
|
|
438
|
+
try {
|
|
439
|
+
const info = statSync(path);
|
|
440
|
+
return info.isDirectory() ? 'dir' : info.isFile() ? 'file' : 'other';
|
|
441
|
+
}
|
|
442
|
+
catch {
|
|
443
|
+
return 'other';
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
function sleep(ms, signal) {
|
|
447
|
+
return new Promise((resolveSleep, reject) => {
|
|
448
|
+
if (signal.aborted) {
|
|
449
|
+
reject(signal.reason);
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
const timer = setTimeout(() => {
|
|
453
|
+
signal.removeEventListener('abort', abort);
|
|
454
|
+
resolveSleep();
|
|
455
|
+
}, Math.max(0, ms));
|
|
456
|
+
const abort = () => {
|
|
457
|
+
clearTimeout(timer);
|
|
458
|
+
reject(signal.reason);
|
|
459
|
+
};
|
|
460
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
461
|
+
});
|
|
462
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import vm from 'node:vm';
|
|
2
|
+
/** One bundled module: CommonJS text over the virtual `claude-code` imports. */
|
|
3
|
+
export interface Bundle {
|
|
4
|
+
readonly code: string;
|
|
5
|
+
readonly entry: string;
|
|
6
|
+
/** The plugin's own source files the bundle was built from. */
|
|
7
|
+
readonly files: readonly string[];
|
|
8
|
+
/** The bundle's identity, for caching. */
|
|
9
|
+
readonly digest: string;
|
|
10
|
+
}
|
|
11
|
+
/** What bundles and parses a module: rolldown's `build` and `parseAst` (see `bundler.ts`). */
|
|
12
|
+
export interface Bundler {
|
|
13
|
+
readonly build: (options: never) => Promise<unknown>;
|
|
14
|
+
readonly parseAst: (code: string, options?: {
|
|
15
|
+
lang?: string;
|
|
16
|
+
}) => unknown;
|
|
17
|
+
}
|
|
18
|
+
/** Bundle a module and everything it imports from its plugin. */
|
|
19
|
+
export declare function bundleModule(entry: string, bundler: Bundler): Promise<Bundle>;
|
|
20
|
+
/** A fresh environment for one load of a module. */
|
|
21
|
+
export declare function createEnvironment(extra?: Readonly<Record<string, unknown>>): vm.Context;
|
|
22
|
+
/**
|
|
23
|
+
* Run a bundle in an environment and return its exports.
|
|
24
|
+
* @param imports - the virtual modules it may import (`claude-code`, `claude-code/testing`).
|
|
25
|
+
*/
|
|
26
|
+
export declare function evaluateBundle(bundle: Bundle, context: vm.Context, imports?: Readonly<Record<string, unknown>>): Record<string, unknown>;
|
|
27
|
+
/**
|
|
28
|
+
* What a module hooks and calls, read off its source as `plugin.register`
|
|
29
|
+
* reports it: its `on(...)` patterns in order, the `$` calls it spells
|
|
30
|
+
* (sorted), and the variables its `$.env` calls name.
|
|
31
|
+
*/
|
|
32
|
+
export declare function scanUses(source: string): {
|
|
33
|
+
events: string[];
|
|
34
|
+
calls: string[];
|
|
35
|
+
env?: {
|
|
36
|
+
reads: string[];
|
|
37
|
+
writes: string[];
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Why the engine would refuse a module, read off its source as Claude Code's
|
|
42
|
+
* scan does: an `engine.create` step that keeps the table it is handed, to
|
|
43
|
+
* call later, outside the fold. Undefined when the module loads.
|
|
44
|
+
*/
|
|
45
|
+
export declare function scanRefusal(source: string, parseAst: Bundler['parseAst'], lang?: 'js' | 'jsx' | 'ts' | 'tsx'): string | undefined;
|
|
46
|
+
/** The scan over a bundle's own source files, as written (not as bundled). */
|
|
47
|
+
export declare function scanBundleRefusal(bundle: Bundle, parseAst: Bundler['parseAst']): string | undefined;
|
|
48
|
+
/** The `uses` of a bundle, read off its own source files. */
|
|
49
|
+
export declare function scanBundleUses(bundle: Bundle): ReturnType<typeof scanUses>;
|
|
50
|
+
/** The `Error` of an environment, for errors a module there receives. */
|
|
51
|
+
export declare function realmOf(context: vm.Context): {
|
|
52
|
+
readonly Error: ErrorConstructor;
|
|
53
|
+
};
|