@fatelabs/opencode-estelle 0.0.0-stage → 0.0.18
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 +201 -0
- package/NOTICE +6 -0
- package/README.md +46 -2
- package/adapters/claude.mjs +17 -0
- package/adapters/codex.mjs +85 -0
- package/adapters/cursor.mjs +66 -0
- package/adapters/dsh-host.mjs +181 -0
- package/adapters/dsh-plugin.mjs +11 -0
- package/adapters/dsh.mjs +54 -0
- package/adapters/grok.mjs +63 -0
- package/adapters/host-bridge.mjs +85 -0
- package/adapters/kimi.mjs +135 -0
- package/adapters/opencode-mirror.mjs +103 -0
- package/adapters/opencode-plugin.mjs +143 -0
- package/adapters/opencode.mjs +15 -0
- package/adapters/pi-extension.mjs +107 -0
- package/adapters/pi.mjs +13 -0
- package/adapters/plugin-envelope.mjs +56 -0
- package/agents/estelle-grounder.md +34 -0
- package/agents/estelle-historian.md +28 -0
- package/agents/estelle-repair.md +29 -0
- package/agents/estelle-reviewer.md +32 -0
- package/commands/cloud.md +28 -0
- package/commands/code.md +6 -0
- package/commands/handoff.md +25 -0
- package/commands/monitor.md +6 -0
- package/commands/resume.md +6 -0
- package/commands/review.md +6 -0
- package/commands/rooms.md +7 -0
- package/instructions.md +19 -0
- package/package.json +34 -4
- package/runtime/auth.mjs +27 -0
- package/runtime/checkpoint.mjs +208 -0
- package/runtime/claude-setup.mjs +130 -0
- package/runtime/cli.mjs +112 -0
- package/runtime/codex-trust.mjs +68 -0
- package/runtime/credential.mjs +341 -0
- package/runtime/dsh-session.mjs +91 -0
- package/runtime/dsh-telemetry.mjs +31 -0
- package/runtime/hooks.mjs +234 -0
- package/runtime/identity.mjs +20 -0
- package/runtime/io.mjs +155 -0
- package/runtime/key-check.mjs +51 -0
- package/runtime/kimi-history.mjs +163 -0
- package/runtime/mailbox.mjs +46 -0
- package/runtime/migration.mjs +118 -0
- package/runtime/move.mjs +443 -0
- package/runtime/native-export.mjs +204 -0
- package/runtime/native-index.mjs +77 -0
- package/runtime/native-tree.mjs +117 -0
- package/runtime/queued-context.mjs +152 -0
- package/runtime/redact.mjs +74 -0
- package/runtime/reindex.mjs +259 -0
- package/runtime/setup.mjs +174 -0
- package/runtime/stream.mjs +755 -0
- package/runtime/version.mjs +2 -0
- package/runtime/write-warning.mjs +67 -0
- package/skills/abstain-right/SKILL.md +19 -0
- package/skills/api-call-ground/SKILL.md +19 -0
- package/skills/bug-hunt/SKILL.md +20 -0
- package/skills/chain-of-verification/SKILL.md +19 -0
- package/skills/change-impact/SKILL.md +19 -0
- package/skills/coding-workflow/SKILL.md +20 -0
- package/skills/commit-guard/SKILL.md +20 -0
- package/skills/context-checkpoint/SKILL.md +19 -0
- package/skills/continuity-brief/SKILL.md +19 -0
- package/skills/dead-code-sweep/SKILL.md +19 -0
- package/skills/deep-search/SKILL.md +19 -0
- package/skills/diff-review/SKILL.md +19 -0
- package/skills/estelle/SKILL.md +119 -0
- package/skills/estelle-loop/SKILL.md +19 -0
- package/skills/estelle-monitor-install/SKILL.md +20 -0
- package/skills/evidence-traceability-audit/SKILL.md +19 -0
- package/skills/grounded-generate/SKILL.md +19 -0
- package/skills/incident-rca/SKILL.md +20 -0
- package/skills/mutation-test/SKILL.md +19 -0
- package/skills/program-repair/SKILL.md +20 -0
- package/skills/prompt-injection-defense/SKILL.md +19 -0
- package/skills/property-based-test/SKILL.md +19 -0
- package/skills/refactor-rfc/SKILL.md +19 -0
- package/skills/root-cause-loop/SKILL.md +19 -0
- package/skills/test-first/SKILL.md +19 -0
- package/skills/threat-model-stride/SKILL.md +19 -0
package/adapters/dsh.mjs
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
|
|
3
|
+
// DeepSeek Harness has no hook protocol of its own: a hook is a Cordis listener. adapters/dsh-plugin.mjs is that
|
|
4
|
+
// listener and writes this envelope, so every field here is ours and was read from dsh's own events, not guessed.
|
|
5
|
+
export const HOOK_EVENTS = Object.freeze(['SessionStart', 'UserPromptSubmit', 'PreToolUse', 'PostToolUse', 'Stop', 'SessionEnd']);
|
|
6
|
+
const EVENTS = new Set(HOOK_EVENTS);
|
|
7
|
+
const TOOL_EVENTS = new Set(['PreToolUse', 'PostToolUse']);
|
|
8
|
+
// The events whose context dsh-plugin.mjs can place in front of the model: agent.inject and the pre-step decision.
|
|
9
|
+
const CONTEXT_EVENTS = new Set(['SessionStart', 'UserPromptSubmit']);
|
|
10
|
+
// Measured from @deepseek-ai/dsh-tool-fs: lower-case names with Claude-shaped file_path/old_string/new_string fields.
|
|
11
|
+
const SHARED_TOOL_NAMES = new Map([['write', 'Write'], ['edit', 'Edit'], ['str_replace_editor', 'Edit']]);
|
|
12
|
+
/** The tools worth a process before they run. Anything else cannot write a file, so it gets no write check. */
|
|
13
|
+
export const WRITE_TOOLS = Object.freeze(['write', 'edit', 'str_replace_editor', 'apply_patch']);
|
|
14
|
+
|
|
15
|
+
const text = (value, name) => {
|
|
16
|
+
if (value != null && typeof value !== 'string') throw new TypeError(`dsh ${name} must be text`);
|
|
17
|
+
return value ?? null;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
function toolArguments(value) {
|
|
21
|
+
if (typeof value !== 'string') return value ?? {};
|
|
22
|
+
// The session log stores arguments as the model's raw JSON text; text that is not JSON is still scanned as text.
|
|
23
|
+
try { return JSON.parse(value); } catch { return { arguments: value }; }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function normalize(payload) {
|
|
27
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw new TypeError('dsh hook input must be an object');
|
|
28
|
+
const event = payload.hook_event_name;
|
|
29
|
+
if (!EVENTS.has(event)) throw new TypeError('Unsupported dsh hook event');
|
|
30
|
+
if (typeof payload.session_id !== 'string' || !/^[A-Za-z0-9_-]{1,200}$/.test(payload.session_id)) {
|
|
31
|
+
throw new TypeError('Invalid dsh session identity');
|
|
32
|
+
}
|
|
33
|
+
if (typeof payload.cwd !== 'string' || payload.cwd.includes('\0') || !path.isAbsolute(payload.cwd)) {
|
|
34
|
+
throw new TypeError('dsh hook cwd must be an absolute local path');
|
|
35
|
+
}
|
|
36
|
+
const toolName = text(payload.tool_name, 'tool_name');
|
|
37
|
+
if (TOOL_EVENTS.has(event) && !toolName) throw new TypeError('dsh tool_name is required for tool events');
|
|
38
|
+
return {
|
|
39
|
+
host: 'dsh', event, sessionId: payload.session_id, cwd: payload.cwd,
|
|
40
|
+
transcriptPath: text(payload.transcript_path, 'transcript_path'),
|
|
41
|
+
prompt: text(payload.prompt, 'prompt'),
|
|
42
|
+
toolName: toolName ? SHARED_TOOL_NAMES.get(toolName) ?? toolName : null,
|
|
43
|
+
toolInput: toolArguments(payload.tool_input),
|
|
44
|
+
toolCallId: text(payload.tool_use_id, 'tool_use_id'),
|
|
45
|
+
source: text(payload.source, 'source'),
|
|
46
|
+
raw: payload,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** dsh-plugin.mjs reads `context` and turns it into one user-role message with the plugin's own source. */
|
|
51
|
+
export function formatContext(value, event) {
|
|
52
|
+
if (typeof value !== 'string') throw new TypeError('dsh hook context must be text');
|
|
53
|
+
return CONTEXT_EVENTS.has(event) && value.trim() ? { context: value } : null;
|
|
54
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Native Grok Build lifecycle envelope; camelCase is authoritative.
|
|
2
|
+
export const HOOK_EVENTS = Object.freeze([
|
|
3
|
+
'SessionStart', 'UserPromptSubmit', 'PreToolUse', 'PostToolUse', 'PostToolUseFailure',
|
|
4
|
+
'PermissionDenied', 'Stop', 'StopFailure', 'StopCancelled', 'Notification',
|
|
5
|
+
'SubagentStart', 'SubagentStop', 'PreCompact', 'PostCompact', 'SessionEnd',
|
|
6
|
+
]);
|
|
7
|
+
const EVENT_NAMES = new Map(HOOK_EVENTS.flatMap(event => [
|
|
8
|
+
[event, event], [event.replace(/[A-Z]/g, (letter, index) => `${index ? '_' : ''}${letter.toLowerCase()}`), event],
|
|
9
|
+
]));
|
|
10
|
+
EVENT_NAMES.set('SubagentEnd', 'SubagentStop');
|
|
11
|
+
EVENT_NAMES.set('subagent_end', 'SubagentStop');
|
|
12
|
+
const CONTEXT_EVENTS = new Set(['PreToolUse', 'PostToolUse', 'Stop', 'SubagentStop']);
|
|
13
|
+
const own = (value, key) => Object.hasOwn(value, key);
|
|
14
|
+
const field = (payload, camel, snake) => own(payload, camel) ? payload[camel] : payload[snake];
|
|
15
|
+
const optionalText = (value, name) => {
|
|
16
|
+
if (value != null && typeof value !== 'string') throw new TypeError(`Grok ${name} must be text`);
|
|
17
|
+
return value ?? null;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/** CamelCase is authoritative; current Grok adds snake_case compatibility aliases. */
|
|
21
|
+
export function normalize(payload) {
|
|
22
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw new TypeError('Grok hook input must be an object');
|
|
23
|
+
const event = EVENT_NAMES.get(field(payload, 'hookEventName', 'hook_event_name'));
|
|
24
|
+
if (!event) throw new TypeError('Unsupported Grok hook event');
|
|
25
|
+
const sessionId = field(payload, 'sessionId', 'session_id');
|
|
26
|
+
if (typeof sessionId !== 'string' || !sessionId) throw new TypeError('Grok session identity is required');
|
|
27
|
+
if (typeof payload.cwd !== 'string' || !payload.cwd) throw new TypeError('Grok cwd is required');
|
|
28
|
+
const transcriptPath = optionalText(field(payload, 'transcriptPath', 'transcript_path'), 'transcriptPath');
|
|
29
|
+
const toolName = optionalText(field(payload, 'toolName', 'tool_name'), 'toolName');
|
|
30
|
+
if (['PreToolUse', 'PostToolUse', 'PostToolUseFailure', 'PermissionDenied'].includes(event)) {
|
|
31
|
+
if (!toolName) throw new TypeError('Grok toolName is required for tool events');
|
|
32
|
+
if (!own(payload, 'toolInput') && !own(payload, 'tool_input')) throw new TypeError('Grok toolInput is required for tool events');
|
|
33
|
+
}
|
|
34
|
+
return {
|
|
35
|
+
host: 'grok', event, sessionId, cwd: payload.cwd, transcriptPath,
|
|
36
|
+
turnId: optionalText(payload.promptId, 'promptId'),
|
|
37
|
+
workspaceRoot: optionalText(payload.workspaceRoot, 'workspaceRoot'),
|
|
38
|
+
timestamp: optionalText(payload.timestamp, 'timestamp'),
|
|
39
|
+
prompt: optionalText(payload.prompt, 'prompt'), toolName,
|
|
40
|
+
toolInput: field(payload, 'toolInput', 'tool_input') ?? null,
|
|
41
|
+
toolResponse: field(payload, 'toolResult', 'tool_response') ?? null,
|
|
42
|
+
toolUseId: optionalText(field(payload, 'toolUseId', 'tool_use_id'), 'toolUseId'),
|
|
43
|
+
agentId: optionalText(payload.subagentId, 'subagentId'),
|
|
44
|
+
agentType: optionalText(payload.subagentType ?? payload.agentType, 'subagentType'),
|
|
45
|
+
lastAssistantMessage: optionalText(payload.lastAssistantMessage, 'lastAssistantMessage'),
|
|
46
|
+
source: optionalText(payload.source, 'source'), trigger: null,
|
|
47
|
+
permissionMode: optionalText(field(payload, 'permissionMode', 'permission_mode'), 'permissionMode'),
|
|
48
|
+
model: optionalText(payload.modelId, 'modelId'), phase: optionalText(payload.phase, 'phase'), raw: payload,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Passive lifecycle and prompt hooks cannot inject. Stop context may continue the model. */
|
|
53
|
+
export function formatContext(text, event, options = {}) {
|
|
54
|
+
if (typeof text !== 'string') throw new TypeError('Grok hook context must be text');
|
|
55
|
+
if (!HOOK_EVENTS.includes(event)) throw new TypeError('Unsupported Grok context event');
|
|
56
|
+
const replacement = own(options, 'updatedMCPToolOutput');
|
|
57
|
+
if (replacement && event !== 'PostToolUse') throw new TypeError('updatedMCPToolOutput requires PostToolUse');
|
|
58
|
+
if (!CONTEXT_EVENTS.has(event) || (!text.trim() && !replacement)) return null;
|
|
59
|
+
return { hookSpecificOutput: {
|
|
60
|
+
...(text.trim() ? { additionalContext: text } : {}),
|
|
61
|
+
...(replacement ? { updatedMCPToolOutput: options.updatedMCPToolOutput } : {}),
|
|
62
|
+
} };
|
|
63
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// The in-process side shared by Estelle's OpenCode plugin and Pi extension. Both hosts run plugins inside their own
|
|
2
|
+
// process, so each event is handed to the same `runtime/cli.mjs hook <host>` runner every other host uses, in a child
|
|
3
|
+
// Node process: one runner, one key from the environment, and a failure there can never take the host down.
|
|
4
|
+
import { spawn } from 'node:child_process';
|
|
5
|
+
import { readdir, readFile } from 'node:fs/promises';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
|
|
9
|
+
export const PLUGIN_ROOT = fileURLToPath(new URL('..', import.meta.url));
|
|
10
|
+
export const SERVER_URL = 'https://api.fatelabs.ca/mcp';
|
|
11
|
+
export const SERVER_NAME = 'Estelle';
|
|
12
|
+
// The runner's own deadline is 12 s for network work (runtime/io.mjs); this is the outer bound, as on the other hosts.
|
|
13
|
+
export const HOOK_TIMEOUT_MS = 20_000;
|
|
14
|
+
export const END_TIMEOUT_MS = 3_000;
|
|
15
|
+
const MAX_OUTPUT_BYTES = 1_000_000;
|
|
16
|
+
const MAX_ASSET_FILES = 64;
|
|
17
|
+
|
|
18
|
+
/** The runner's JSON answer, or null. Never rejects: a hook that fails leaves its own status for `doctor`. */
|
|
19
|
+
export function runHook(host, payload, { root = PLUGIN_ROOT, env = process.env, timeoutMs = HOOK_TIMEOUT_MS } = {}) {
|
|
20
|
+
return new Promise(resolve => {
|
|
21
|
+
let child;
|
|
22
|
+
try {
|
|
23
|
+
child = spawn(env.ESTELLE_NODE || 'node', [join(root, 'runtime', 'cli.mjs'), 'hook', host],
|
|
24
|
+
{ env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
|
|
25
|
+
} catch { resolve(null); return; }
|
|
26
|
+
const chunks = [];
|
|
27
|
+
let bytes = 0;
|
|
28
|
+
let stderr = '';
|
|
29
|
+
const timer = setTimeout(() => child.kill('SIGKILL'), timeoutMs);
|
|
30
|
+
child.stdout.on('data', chunk => {
|
|
31
|
+
bytes += chunk.length;
|
|
32
|
+
if (bytes <= MAX_OUTPUT_BYTES) chunks.push(chunk);
|
|
33
|
+
});
|
|
34
|
+
// Stderr carries the write warning on every host; it is kept short and never parsed as an answer.
|
|
35
|
+
child.stderr.on('data', chunk => { if (stderr.length < 4_000) stderr += chunk.toString('utf8'); });
|
|
36
|
+
child.on('error', () => { clearTimeout(timer); resolve(null); });
|
|
37
|
+
child.on('close', () => {
|
|
38
|
+
clearTimeout(timer);
|
|
39
|
+
const line = Buffer.concat(chunks).toString('utf8').trim().split('\n').filter(Boolean).at(-1);
|
|
40
|
+
try { resolve(line ? JSON.parse(line) : null); } catch { resolve(null); }
|
|
41
|
+
});
|
|
42
|
+
child.stdin.on('error', () => {});
|
|
43
|
+
child.stdin.end(JSON.stringify(payload));
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Text the runner asked this host to place in front of the model, or ''. */
|
|
48
|
+
export const contextOf = output => (typeof output?.additionalContext === 'string' ? output.additionalContext : '');
|
|
49
|
+
/** The write warning the runner attached, or ''. It never blocks the tool. */
|
|
50
|
+
export const warningOf = output => (typeof output?.warning === 'string' ? output.warning : '');
|
|
51
|
+
|
|
52
|
+
async function markdownFiles(directory) {
|
|
53
|
+
const names = (await readdir(directory).catch(() => [])).filter(name => name.endsWith('.md')).sort();
|
|
54
|
+
return names.slice(0, MAX_ASSET_FILES);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The shared Estelle commands (commands/*.md), with the runner path these hosts can name exactly. */
|
|
58
|
+
export async function readCommands(root = PLUGIN_ROOT) {
|
|
59
|
+
const cli = join(root, 'runtime', 'cli.mjs');
|
|
60
|
+
const out = [];
|
|
61
|
+
for (const file of await markdownFiles(join(root, 'commands'))) {
|
|
62
|
+
const source = await readFile(join(root, 'commands', file), 'utf8');
|
|
63
|
+
const [, description, body] = /^---\ndescription: (.+)\n---\n([\s\S]+)$/.exec(source) ?? [];
|
|
64
|
+
if (!description) continue;
|
|
65
|
+
out.push({ name: file.replace(/\.md$/, ''), description,
|
|
66
|
+
template: body.replaceAll('<Estelle cli.mjs>', cli.replaceAll('"', '\\"')) });
|
|
67
|
+
}
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The shared Estelle agents (agents/*.md): name, description and the prompt body. Their tool lists name Claude
|
|
72
|
+
* Code's tools, so they are not carried; each host gives the agent its own tools. */
|
|
73
|
+
export async function readAgents(root = PLUGIN_ROOT) {
|
|
74
|
+
const out = [];
|
|
75
|
+
for (const file of await markdownFiles(join(root, 'agents'))) {
|
|
76
|
+
const source = await readFile(join(root, 'agents', file), 'utf8');
|
|
77
|
+
const match = /^---\n([\s\S]*?)\n---\n([\s\S]+)$/.exec(source);
|
|
78
|
+
if (!match) continue;
|
|
79
|
+
const field = key => new RegExp(`^${key}: (.+)$`, 'm').exec(match[1])?.[1]?.trim() ?? '';
|
|
80
|
+
if (field('name') && field('description')) out.push({ name: field('name'), description: field('description'), prompt: match[2].trim() });
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export const readInstructions = (root = PLUGIN_ROOT) => readFile(join(root, 'instructions.md'), 'utf8');
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { open, realpath, stat } from 'node:fs/promises';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
// MoonshotAI/kimi-code a2afdbc7: features/externalHooks/internal/types.ts.
|
|
6
|
+
const EVENTS = new Set([
|
|
7
|
+
'PreToolUse', 'PostToolUse', 'PostToolUseFailure', 'PermissionRequest',
|
|
8
|
+
'PermissionResult', 'UserPromptSubmit', 'UserPromptQueued', 'TurnStarted',
|
|
9
|
+
'Stop', 'StopFailure', 'Interrupt', 'SessionStart', 'SessionEnd',
|
|
10
|
+
'SessionHeartbeat', 'SubagentStart', 'SubagentStop', 'TaskStarted',
|
|
11
|
+
'PreCompact', 'PostCompact', 'Notification',
|
|
12
|
+
]);
|
|
13
|
+
const MAX_PROMPT_PARTS = 256;
|
|
14
|
+
const MAX_PROMPT_CHARS = 200_000;
|
|
15
|
+
const MAX_INDEX_BYTES = 2_000_000;
|
|
16
|
+
const MAX_INDEX_LINES = 10_000;
|
|
17
|
+
|
|
18
|
+
function record(value) {
|
|
19
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function optionalString(value) {
|
|
23
|
+
return typeof value === 'string' ? value : undefined;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function promptText(value) {
|
|
27
|
+
if (value === undefined) return '';
|
|
28
|
+
if (typeof value === 'string') {
|
|
29
|
+
if (value.length > MAX_PROMPT_CHARS) throw new RangeError('Kimi prompt exceeds capture bound');
|
|
30
|
+
return value;
|
|
31
|
+
}
|
|
32
|
+
if (!Array.isArray(value)) throw new TypeError('Kimi prompt must be text or content parts');
|
|
33
|
+
if (value.length > MAX_PROMPT_PARTS) throw new RangeError('Kimi prompt exceeds part bound');
|
|
34
|
+
const text = value.filter(part => record(part) && part.type === 'text')
|
|
35
|
+
.map(part => optionalString(part.text) ?? '').join('\n');
|
|
36
|
+
if (text.length > MAX_PROMPT_CHARS) throw new RangeError('Kimi prompt exceeds capture bound');
|
|
37
|
+
return text;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function normalize(payload) {
|
|
41
|
+
if (!record(payload)) throw new TypeError('Kimi hook payload must be an object');
|
|
42
|
+
const event = payload.hook_event_name;
|
|
43
|
+
if (!EVENTS.has(event)) throw new TypeError('Unsupported Kimi hook event');
|
|
44
|
+
const sessionId = payload.session_id;
|
|
45
|
+
if (typeof sessionId !== 'string' || !/^[a-zA-Z0-9_-]{1,200}$/.test(sessionId)) {
|
|
46
|
+
throw new TypeError('Invalid Kimi session identity');
|
|
47
|
+
}
|
|
48
|
+
const cwd = payload.cwd;
|
|
49
|
+
if (typeof cwd !== 'string' || cwd.includes('\0') || !path.isAbsolute(cwd)) {
|
|
50
|
+
throw new TypeError('Kimi hook cwd must be an absolute local path');
|
|
51
|
+
}
|
|
52
|
+
const input = record(payload.tool_input) ? payload.tool_input : {};
|
|
53
|
+
// Kimi uses path; shared Claude-oriented file handling expects file_path.
|
|
54
|
+
const toolInput = typeof input.path === 'string' ? { ...input, file_path: input.path } : { ...input };
|
|
55
|
+
return {
|
|
56
|
+
host: 'kimi', event, sessionId, cwd,
|
|
57
|
+
toolName: optionalString(payload.tool_name) ?? '',
|
|
58
|
+
toolInput, prompt: promptText(payload.prompt),
|
|
59
|
+
// Kimi does not supply a transcript path. Never trust a made-up input field.
|
|
60
|
+
transcriptPath: undefined,
|
|
61
|
+
title: optionalString(payload.session_title),
|
|
62
|
+
toolCallId: optionalString(payload.tool_call_id),
|
|
63
|
+
toolOutput: optionalString(payload.tool_output),
|
|
64
|
+
agentName: optionalString(payload.agent_name),
|
|
65
|
+
response: optionalString(payload.response),
|
|
66
|
+
source: optionalString(payload.source),
|
|
67
|
+
trigger: optionalString(payload.trigger),
|
|
68
|
+
reason: optionalString(payload.reason),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function formatContext(text, event) {
|
|
73
|
+
if (typeof text !== 'string') throw new TypeError('Kimi hook context must be text');
|
|
74
|
+
// Only this event appends hook stdout to context. Other events cannot inject it.
|
|
75
|
+
if (event !== 'UserPromptSubmit' || text.trim() === '') return null;
|
|
76
|
+
return { message: text };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function within(child, parent) {
|
|
80
|
+
const relative = path.relative(parent, child);
|
|
81
|
+
return relative !== '' && !relative.startsWith(`..${path.sep}`)
|
|
82
|
+
&& relative !== '..' && !path.isAbsolute(relative);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function readIndex(file) {
|
|
86
|
+
const handle = await open(file, 'r');
|
|
87
|
+
try {
|
|
88
|
+
const metadata = await handle.stat();
|
|
89
|
+
if (!metadata.isFile() || metadata.size > MAX_INDEX_BYTES) return undefined;
|
|
90
|
+
const buffer = Buffer.alloc(metadata.size + 1);
|
|
91
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
|
|
92
|
+
if (bytesRead > metadata.size) return undefined; // Registry grew past the measured bound.
|
|
93
|
+
const lines = buffer.subarray(0, bytesRead).toString('utf8').split('\n');
|
|
94
|
+
return lines.length > MAX_INDEX_LINES ? undefined : lines;
|
|
95
|
+
} finally {
|
|
96
|
+
await handle.close();
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function registryMatch(lines, sessionId, cwd) {
|
|
101
|
+
let match;
|
|
102
|
+
for (const line of lines) {
|
|
103
|
+
let entry;
|
|
104
|
+
try { entry = JSON.parse(line); } catch { continue; }
|
|
105
|
+
if (!record(entry) || entry.sessionId !== sessionId || entry.workDir !== cwd) continue;
|
|
106
|
+
if (typeof entry.sessionDir !== 'string' || !path.isAbsolute(entry.sessionDir)) continue;
|
|
107
|
+
if (match !== undefined && match !== entry.sessionDir) return undefined;
|
|
108
|
+
match = entry.sessionDir;
|
|
109
|
+
}
|
|
110
|
+
return match;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Resolve only this session's registered legacy wire file. No history-directory walk. */
|
|
114
|
+
export async function getTranscriptPath(normalized, options = {}) {
|
|
115
|
+
if (!record(normalized) || normalized.host !== 'kimi') throw new TypeError('Expected normalized Kimi payload');
|
|
116
|
+
const home = options.home ?? process.env.KIMI_CODE_HOME ?? path.join(homedir(), '.kimi-code');
|
|
117
|
+
if (typeof home !== 'string' || !path.isAbsolute(home)) throw new TypeError('Kimi home must be absolute');
|
|
118
|
+
try {
|
|
119
|
+
const root = await realpath(home);
|
|
120
|
+
const index = await realpath(path.join(root, 'session_index.jsonl'));
|
|
121
|
+
if (!within(index, root)) return undefined;
|
|
122
|
+
const lines = await readIndex(index);
|
|
123
|
+
if (lines === undefined) return undefined;
|
|
124
|
+
const directory = await registryMatch(lines, normalized.sessionId, normalized.cwd);
|
|
125
|
+
if (directory === undefined) return undefined;
|
|
126
|
+
const session = await realpath(directory);
|
|
127
|
+
if (!within(session, path.join(root, 'sessions'))) return undefined;
|
|
128
|
+
const wire = await realpath(path.join(session, 'agents', 'main', 'wire.jsonl'));
|
|
129
|
+
if (!within(wire, session) || !(await stat(wire)).isFile()) return undefined;
|
|
130
|
+
return wire;
|
|
131
|
+
} catch (error) {
|
|
132
|
+
if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return undefined;
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// OpenCode keeps its sessions in its own database and names no transcript file to a plugin, so Estelle's plugin writes
|
|
2
|
+
// one: after each turn it reads the session's messages through OpenCode's own client and appends the parts it has not
|
|
3
|
+
// written yet, in Claude Code's line shape, which runtime/stream.mjs and runtime/checkpoint.mjs already read.
|
|
4
|
+
// Append-only, because the stream's cursor is a byte offset into this file.
|
|
5
|
+
import { appendFile, mkdir, open } from 'node:fs/promises';
|
|
6
|
+
import { dirname, join } from 'node:path';
|
|
7
|
+
|
|
8
|
+
const MAX_MESSAGES = 2_000;
|
|
9
|
+
const MAX_PARTS = 200;
|
|
10
|
+
const SEED_BYTES = 8_000_000;
|
|
11
|
+
const SESSION_FILE = /^[A-Za-z0-9_-]{1,200}$/;
|
|
12
|
+
|
|
13
|
+
export const mirrorPath = (stateDir, sessionID) => {
|
|
14
|
+
if (!SESSION_FILE.test(sessionID)) throw new Error('session_missing');
|
|
15
|
+
return join(stateDir, 'transcripts', `opencode-${sessionID}.jsonl`);
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const iso = value => (Number.isFinite(value) ? new Date(value).toISOString() : null);
|
|
19
|
+
const line = (type, uuid, timestamp, message, extra = {}) => ({ type, uuid, timestamp, message, ...extra });
|
|
20
|
+
|
|
21
|
+
/** The lines one finished OpenCode message contributes. Pure: `{info, parts}` in, lines out. */
|
|
22
|
+
export function linesFor({ info, parts }) {
|
|
23
|
+
if (!info || !['user', 'assistant'].includes(info.role) || !Array.isArray(parts)) return [];
|
|
24
|
+
const at = iso(info.time?.created);
|
|
25
|
+
if (!at) return [];
|
|
26
|
+
const out = [];
|
|
27
|
+
if (info.role === 'user') {
|
|
28
|
+
for (const part of parts.slice(0, MAX_PARTS)) {
|
|
29
|
+
// Synthetic parts are what plugins (Estelle's recall among them) added, not what the person typed.
|
|
30
|
+
if (part?.type === 'text' && !part.synthetic && !part.ignored && part.text?.trim()) {
|
|
31
|
+
out.push(line('user', part.id, at, { role: 'user', content: [{ type: 'text', text: part.text }] }));
|
|
32
|
+
} else if (part?.type === 'file' && /^image\//.test(part.mime ?? '')) {
|
|
33
|
+
out.push(line('user', part.id, at, { role: 'user', content: [{ type: 'image' }] }));
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
// An assistant message is written once it has finished; a compaction summary is not the conversation.
|
|
39
|
+
if (!info.time?.completed && !info.error) return [];
|
|
40
|
+
const extra = info.summary === true ? { isCompactSummary: true } : {};
|
|
41
|
+
for (const part of parts.slice(0, MAX_PARTS)) {
|
|
42
|
+
const partAt = iso(part?.time?.start) ?? at;
|
|
43
|
+
if (part?.type === 'text' && !part.synthetic && part.text?.trim()) {
|
|
44
|
+
out.push(line('assistant', part.id, partAt, { role: 'assistant', content: [{ type: 'text', text: part.text }] }, extra));
|
|
45
|
+
} else if (part?.type === 'reasoning' && part.text?.trim()) {
|
|
46
|
+
out.push(line('assistant', part.id, partAt, { role: 'assistant', content: [{ type: 'thinking', thinking: part.text }] }, extra));
|
|
47
|
+
} else if (part?.type === 'tool' && ['completed', 'error'].includes(part.state?.status)) {
|
|
48
|
+
const end = iso(part.state.time?.end) ?? partAt;
|
|
49
|
+
out.push(line('assistant', `${part.id}:call`, iso(part.state.time?.start) ?? partAt, { role: 'assistant',
|
|
50
|
+
content: [{ type: 'tool_use', id: part.callID, name: part.tool, input: part.state.input ?? {} }] }, extra));
|
|
51
|
+
out.push(line('user', `${part.id}:result`, end, { role: 'user', content: [{ type: 'tool_result', tool_use_id: part.callID,
|
|
52
|
+
is_error: part.state.status === 'error', content: String(part.state.status === 'error' ? part.state.error ?? '' : part.state.output ?? '') }] }, extra));
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const first = out.find(item => item.type === 'assistant');
|
|
56
|
+
if (first && info.tokens) {
|
|
57
|
+
first.message.model = info.modelID ?? null;
|
|
58
|
+
first.message.usage = { input_tokens: info.tokens.input ?? 0, output_tokens: info.tokens.output ?? 0,
|
|
59
|
+
cache_read_input_tokens: info.tokens.cache?.read ?? 0, cache_creation_input_tokens: info.tokens.cache?.write ?? 0 };
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function seed(path) {
|
|
65
|
+
const ids = new Set();
|
|
66
|
+
let handle;
|
|
67
|
+
try { handle = await open(path, 'r'); }
|
|
68
|
+
catch (error) { if (error.code === 'ENOENT') return ids; throw error; }
|
|
69
|
+
try {
|
|
70
|
+
const size = (await handle.stat()).size;
|
|
71
|
+
const start = Math.max(0, size - SEED_BYTES);
|
|
72
|
+
const buffer = Buffer.alloc(size - start);
|
|
73
|
+
await handle.read(buffer, 0, buffer.length, start);
|
|
74
|
+
for (const text of buffer.toString('utf8').split('\n')) {
|
|
75
|
+
try { const uuid = JSON.parse(text).uuid; if (typeof uuid === 'string') ids.add(uuid); } catch { /* a partial first line */ }
|
|
76
|
+
}
|
|
77
|
+
} finally { await handle.close(); }
|
|
78
|
+
return ids;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Append what is new for this session; `written` is the caller's per-session set, seeded from the file once.
|
|
82
|
+
* `idle` marks the end of a turn, written once per finished assistant message. Returns the lines appended. */
|
|
83
|
+
export async function syncMirror({ messages, path, written, idle = false }) {
|
|
84
|
+
if (!written.seeded) {
|
|
85
|
+
for (const id of await seed(path)) written.add(id);
|
|
86
|
+
written.seeded = true;
|
|
87
|
+
}
|
|
88
|
+
const fresh = [];
|
|
89
|
+
const list = Array.isArray(messages) ? messages.slice(-MAX_MESSAGES) : [];
|
|
90
|
+
for (const message of list) for (const item of linesFor(message)) {
|
|
91
|
+
if (!written.has(item.uuid)) { written.add(item.uuid); fresh.push(item); }
|
|
92
|
+
}
|
|
93
|
+
const last = list.findLast(message => message?.info?.role === 'assistant');
|
|
94
|
+
const done = last?.info?.time?.completed;
|
|
95
|
+
if (idle && done && !written.has(`${last.info.id}:turn-end`)) {
|
|
96
|
+
written.add(`${last.info.id}:turn-end`);
|
|
97
|
+
fresh.push({ type: 'system', subtype: 'turn_duration', uuid: `${last.info.id}:turn-end`, timestamp: iso(done) });
|
|
98
|
+
}
|
|
99
|
+
// The file exists from the session's first hook on, so a stream read before the first finished part finds it empty.
|
|
100
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
101
|
+
await appendFile(path, fresh.length ? fresh.map(item => JSON.stringify(item)).join('\n') + '\n' : '', { mode: 0o600 });
|
|
102
|
+
return fresh.length;
|
|
103
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// Estelle for OpenCode: one plugin module. It adds the Estelle MCP server, commands, agents, skills and instructions
|
|
2
|
+
// through OpenCode's `config` hook, and hands OpenCode's own events to the shared hook runner (adapters/host-bridge.mjs).
|
|
3
|
+
// Written against @opencode-ai/plugin 1.19.6 (`PluginModule = { id, server }`, `Hooks`).
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { contextOf, END_TIMEOUT_MS, PLUGIN_ROOT, readAgents, readCommands, runHook, SERVER_NAME, SERVER_URL, warningOf }
|
|
6
|
+
from './host-bridge.mjs';
|
|
7
|
+
import { mirrorPath, syncMirror } from './opencode-mirror.mjs';
|
|
8
|
+
import { stateDirectory } from '../runtime/io.mjs';
|
|
9
|
+
|
|
10
|
+
const HOST = 'opencode';
|
|
11
|
+
// Sessions one OpenCode process keeps state for; the oldest is forgotten past this.
|
|
12
|
+
const MAX_SESSIONS = 256;
|
|
13
|
+
const MAX_TOOL_WARNINGS = 64;
|
|
14
|
+
|
|
15
|
+
/** The config this plugin adds. Pure, so the test reads exactly what OpenCode is given. Nothing the person configured
|
|
16
|
+
* is replaced: their own `Estelle` server, command or agent of the same name wins. */
|
|
17
|
+
export function estelleConfig(config, { commands, agents, root = PLUGIN_ROOT, env = process.env }) {
|
|
18
|
+
const key = env.ESTELLE_API_KEY;
|
|
19
|
+
// No key: OpenCode's own MCP OAuth signs in (`opencode mcp auth Estelle`). A header with an empty key would disable that.
|
|
20
|
+
const server = { type: 'remote', url: SERVER_URL, enabled: true,
|
|
21
|
+
...(key && !/[\r\n]/.test(key) ? { headers: { Authorization: `Bearer ${key}` } } : {}) };
|
|
22
|
+
const command = { ...config.command };
|
|
23
|
+
for (const item of commands) command[`estelle:${item.name}`] ??= { description: item.description, template: item.template };
|
|
24
|
+
const agent = { ...config.agent };
|
|
25
|
+
for (const item of agents) agent[item.name] ??= { description: item.description, prompt: item.prompt, mode: 'subagent' };
|
|
26
|
+
const instructions = [...(config.instructions ?? [])];
|
|
27
|
+
const own = join(root, 'instructions.md');
|
|
28
|
+
if (!instructions.includes(own)) instructions.push(own);
|
|
29
|
+
const paths = [...(config.skills?.paths ?? [])];
|
|
30
|
+
if (!paths.includes(join(root, 'skills'))) paths.push(join(root, 'skills'));
|
|
31
|
+
return { ...config, mcp: { [SERVER_NAME]: server, ...config.mcp }, command, agent, instructions,
|
|
32
|
+
skills: { ...config.skills, paths } };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function remember(map, key, value) {
|
|
36
|
+
map.delete(key);
|
|
37
|
+
map.set(key, value);
|
|
38
|
+
if (map.size > MAX_SESSIONS) map.delete(map.keys().next().value);
|
|
39
|
+
return value;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The plugin's hooks for one OpenCode instance. `run` and `messages` are injectable so tests drive the real wiring. */
|
|
43
|
+
export function createHooks({ directory, client, env = process.env, run = runHook, stateDir = stateDirectory(env),
|
|
44
|
+
messagesOf } = {}) {
|
|
45
|
+
const sessions = new Map(); // sessionID -> { parent, context, started, written, pending, stopping }
|
|
46
|
+
const warnings = new Map(); // callID -> warning text for the tool result
|
|
47
|
+
const read = messagesOf ?? (async id => (await client.session.messages({ path: { id } }))?.data ?? []);
|
|
48
|
+
const cwd = directory;
|
|
49
|
+
const envelope = (event, sessionID, extra = {}) => {
|
|
50
|
+
const session = sessions.get(sessionID);
|
|
51
|
+
return { hook_event_name: event, session_id: sessionID, cwd, transcript_path: mirrorPath(stateDir, sessionID),
|
|
52
|
+
...(session?.parent ? { parent_session_id: session.parent } : {}), ...extra };
|
|
53
|
+
};
|
|
54
|
+
const state = sessionID => sessions.get(sessionID) ?? remember(sessions, sessionID, { parent: null, context: '', written: new Set() });
|
|
55
|
+
|
|
56
|
+
/** SessionStart once per session this process meets: created here, or resumed from before it loaded. */
|
|
57
|
+
function start(sessionID, event = 'session.seen', parent = null) {
|
|
58
|
+
const session = state(sessionID);
|
|
59
|
+
if (parent) session.parent = parent;
|
|
60
|
+
session.started ??= run(HOST, envelope(event, sessionID), { env }).then(output => { session.context = contextOf(output); });
|
|
61
|
+
return session.started;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** `current` is the person's message from chat.message, which OpenCode has not stored yet. */
|
|
65
|
+
async function mirror(sessionID, idle, current) {
|
|
66
|
+
const session = state(sessionID);
|
|
67
|
+
try {
|
|
68
|
+
const messages = [...await read(sessionID), ...(current ? [current] : [])];
|
|
69
|
+
await syncMirror({ messages, path: mirrorPath(stateDir, sessionID), written: session.written, idle });
|
|
70
|
+
} catch { /* The runner reports a missing or stale transcript itself. */ }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Stop once per turn. `opencode run` can dispose the instance while session.idle's work is in flight, so dispose
|
|
74
|
+
* waits for it and saves any turn that never reached idle. */
|
|
75
|
+
function stop(sessionID) {
|
|
76
|
+
const session = state(sessionID);
|
|
77
|
+
session.pending = false;
|
|
78
|
+
session.stopping = (async () => {
|
|
79
|
+
await mirror(sessionID, true);
|
|
80
|
+
await run(HOST, envelope('session.idle', sessionID), { env });
|
|
81
|
+
})();
|
|
82
|
+
return session.stopping;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return {
|
|
86
|
+
config: async config => { Object.assign(config, estelleConfig(config, { commands: await readCommands(), agents: await readAgents(), env })); },
|
|
87
|
+
event: async ({ event }) => {
|
|
88
|
+
const info = event?.properties?.info;
|
|
89
|
+
if (event?.type === 'session.created' && info?.id) await start(info.id, 'session.created', info.parentID ?? null);
|
|
90
|
+
else if (event?.type === 'session.idle' && event.properties?.sessionID) await stop(event.properties.sessionID);
|
|
91
|
+
else if (event?.type === 'session.deleted' && info?.id) {
|
|
92
|
+
await run(HOST, envelope('session.deleted', info.id), { env, timeoutMs: END_TIMEOUT_MS });
|
|
93
|
+
sessions.delete(info.id);
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
// The start text is part of the system prompt on every model call, so a compaction never drops this session's identity.
|
|
97
|
+
'experimental.chat.system.transform': async (input, output) => {
|
|
98
|
+
if (!input?.sessionID) return;
|
|
99
|
+
await start(input.sessionID);
|
|
100
|
+
const text = sessions.get(input.sessionID)?.context;
|
|
101
|
+
if (text) output.system.push(text);
|
|
102
|
+
},
|
|
103
|
+
'chat.message': async (input, output) => {
|
|
104
|
+
const sessionID = input?.sessionID;
|
|
105
|
+
if (!sessionID) return;
|
|
106
|
+
await start(sessionID);
|
|
107
|
+
state(sessionID).pending = true;
|
|
108
|
+
await mirror(sessionID, false, { info: { role: 'user', ...output.message }, parts: output.parts ?? [] });
|
|
109
|
+
const prompt = (output.parts ?? []).filter(part => part?.type === 'text' && !part.synthetic).map(part => part.text).join('\n');
|
|
110
|
+
const text = contextOf(await run(HOST, envelope('chat.message', sessionID, { prompt, model: input.model?.modelID ?? null }), { env }));
|
|
111
|
+
// Recall goes into the person's message as a synthetic part: the model reads it, the mirror and capture skip it.
|
|
112
|
+
if (text) output.parts.push({ id: `${output.message.id.replace(/^msg/, 'prt')}estelle`, sessionID,
|
|
113
|
+
messageID: output.message.id, type: 'text', text, synthetic: true });
|
|
114
|
+
},
|
|
115
|
+
'tool.execute.before': async (input, output) => {
|
|
116
|
+
const warning = warningOf(await run(HOST, envelope('tool.execute.before', input.sessionID,
|
|
117
|
+
{ tool_name: input.tool, tool_input: output.args ?? {}, tool_use_id: input.callID }), { env }));
|
|
118
|
+
if (warning) remember(warnings, input.callID, warning);
|
|
119
|
+
if (warnings.size > MAX_TOOL_WARNINGS) warnings.delete(warnings.keys().next().value);
|
|
120
|
+
},
|
|
121
|
+
// Mail and room entries for this session arrive with the tool result the model is about to read.
|
|
122
|
+
'tool.execute.after': async (input, output) => {
|
|
123
|
+
const text = contextOf(await run(HOST, envelope('tool.execute.after', input.sessionID, { tool_name: input.tool,
|
|
124
|
+
tool_input: input.args ?? {}, tool_use_id: input.callID, tool_response: { output: String(output.output ?? '').slice(0, 4_000) } }), { env }));
|
|
125
|
+
const warning = warnings.get(input.callID);
|
|
126
|
+
warnings.delete(input.callID);
|
|
127
|
+
const extra = [warning, text].filter(Boolean).join('\n\n');
|
|
128
|
+
if (extra) output.output = `${output.output ?? ''}\n\n${extra}`;
|
|
129
|
+
},
|
|
130
|
+
dispose: async () => {
|
|
131
|
+
await Promise.allSettled([...sessions.values()].map(session => session.stopping));
|
|
132
|
+
await Promise.allSettled([...sessions.entries()].filter(([, session]) => session.pending).map(([id]) => stop(id)));
|
|
133
|
+
},
|
|
134
|
+
'experimental.session.compacting': async input => {
|
|
135
|
+
if (!input?.sessionID) return;
|
|
136
|
+
await mirror(input.sessionID, false);
|
|
137
|
+
await run(HOST, envelope('experimental.session.compacting', input.sessionID), { env });
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export const server = async input => createHooks({ directory: input.directory, client: input.client });
|
|
143
|
+
export default { id: 'estelle', server };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// OpenCode's native plugin hooks (@opencode-ai/plugin 1.19.6 `Hooks`, and bus events through its `event` hook), as
|
|
2
|
+
// adapters/opencode-plugin.mjs names them in the envelope. `session.seen` is ours: the first time the plugin meets a
|
|
3
|
+
// session it did not see created (a resumed one, or one created before the plugin loaded).
|
|
4
|
+
import { envelopeAdapter } from './plugin-envelope.mjs';
|
|
5
|
+
|
|
6
|
+
export const { HOOK_EVENTS, normalize, formatContext } = envelopeAdapter({
|
|
7
|
+
host: 'opencode',
|
|
8
|
+
events: Object.freeze({
|
|
9
|
+
'session.created': 'SessionStart', 'session.seen': 'SessionStart', 'chat.message': 'UserPromptSubmit',
|
|
10
|
+
'tool.execute.before': 'PreToolUse', 'tool.execute.after': 'PostToolUse', 'session.idle': 'Stop',
|
|
11
|
+
'experimental.session.compacting': 'PreCompact', 'session.deleted': 'SessionEnd',
|
|
12
|
+
}),
|
|
13
|
+
// OpenCode's built-in file tools: write {filePath, content}, edit {filePath, oldString, newString}, apply_patch {patchText}.
|
|
14
|
+
tools: Object.freeze({ write: 'Write', edit: 'Edit', multiedit: 'MultiEdit', patch: 'apply_patch', apply_patch: 'apply_patch' }),
|
|
15
|
+
});
|