@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
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// Bounded conversation checkpoint client, ported from the public CLI contract.
|
|
2
|
+
import { open } from 'node:fs/promises';
|
|
3
|
+
import { redact, sanitize } from './redact.mjs';
|
|
4
|
+
import { cloudExecutionIdentity } from './identity.mjs';
|
|
5
|
+
import { safeSession, grokContentText } from './stream.mjs';
|
|
6
|
+
import { readKimiHistory } from './kimi-history.mjs';
|
|
7
|
+
|
|
8
|
+
export const CHECKPOINT_LIMITS = Object.freeze({
|
|
9
|
+
tailBytes: 32 * 1024 * 1024, headBytes: 64 * 1024,
|
|
10
|
+
records: 100_000, messages: 400, chars: 4_000, blocks: 1_000,
|
|
11
|
+
});
|
|
12
|
+
const HOSTS = { claude: 'claude-code', 'claude-code': 'claude-code', codex: 'codex', kimi: 'kimi-code', 'kimi-code': 'kimi-code',
|
|
13
|
+
grok: 'grok', cursor: 'cursor', dsh: 'deepseek-harness', 'deepseek-harness': 'deepseek-harness', opencode: 'opencode', pi: 'pi' };
|
|
14
|
+
const INJECTED = ['<environment_context', '<user_instructions', '# AGENTS.md instructions', '<skill', '<system-reminder', '<task-notification', '<command-', '<local-command', '<turn_aborted'];
|
|
15
|
+
const string = value => typeof value === 'string' ? value : '';
|
|
16
|
+
const shortened = text => Array.from(redact(text)).slice(0, CHECKPOINT_LIMITS.chars).join('');
|
|
17
|
+
|
|
18
|
+
async function readPart(file, start, bytes) {
|
|
19
|
+
const buffer = Buffer.alloc(bytes);
|
|
20
|
+
let used = 0;
|
|
21
|
+
const maxReads = 1024;
|
|
22
|
+
for (let attempt = 0; attempt < maxReads && used < bytes; attempt++) {
|
|
23
|
+
const { bytesRead } = await file.read(buffer, used, bytes - used, start + used);
|
|
24
|
+
if (!bytesRead) break;
|
|
25
|
+
used += bytesRead;
|
|
26
|
+
}
|
|
27
|
+
return buffer.subarray(0, used);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function transcriptWindows(path) {
|
|
31
|
+
const file = await open(path, 'r');
|
|
32
|
+
try {
|
|
33
|
+
const bytes = (await file.stat()).size;
|
|
34
|
+
if (bytes <= CHECKPOINT_LIMITS.tailBytes) {
|
|
35
|
+
const buffer = await readPart(file, 0, bytes);
|
|
36
|
+
return { windows: [buffer], bytes, read: buffer.length, partial: buffer.length < bytes };
|
|
37
|
+
}
|
|
38
|
+
const head = await readPart(file, 0, CHECKPOINT_LIMITS.headBytes);
|
|
39
|
+
const tailStart = Math.max(head.length, bytes - CHECKPOINT_LIMITS.tailBytes);
|
|
40
|
+
const tail = await readPart(file, tailStart, bytes - tailStart);
|
|
41
|
+
const first = tail.indexOf(10);
|
|
42
|
+
return { windows: [head.subarray(0, head.lastIndexOf(10) + 1), first < 0 ? Buffer.alloc(0) : tail.subarray(first + 1)],
|
|
43
|
+
bytes, read: head.length + tail.length, partial: true };
|
|
44
|
+
} finally { await file.close(); }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function blockText(block) {
|
|
48
|
+
if (['text', 'input_text', 'output_text'].includes(block?.type)) return string(block.text);
|
|
49
|
+
if (['image', 'input_image', 'image_url'].includes(block?.type)) return '[image attached; image bytes omitted]';
|
|
50
|
+
if (block?.type === 'tool_use') return `[tool: ${string(block.name) || '?'}]`;
|
|
51
|
+
return ''; // Tool output, encrypted content, and reasoning do not belong in conversation checkpoints.
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function messageOf(record, host, subagent) {
|
|
55
|
+
if (!record || typeof record !== 'object') return null;
|
|
56
|
+
// OpenCode's plugin mirror is written in Claude Code's line shape (adapters/opencode-mirror.mjs).
|
|
57
|
+
if (host === 'claude-code' || host === 'opencode') {
|
|
58
|
+
if (!['user', 'assistant'].includes(record.type) || record.isMeta || record.isCompactSummary || (record.isSidechain && !subagent)) return null;
|
|
59
|
+
return { role: record.type, ...record.message };
|
|
60
|
+
}
|
|
61
|
+
if (host === 'codex') {
|
|
62
|
+
const item = record.type === 'response_item' ? record.payload : record;
|
|
63
|
+
return item?.type === 'message' && ['user', 'assistant'].includes(item.role) ? item : null;
|
|
64
|
+
}
|
|
65
|
+
if (host === 'cursor') {
|
|
66
|
+
// Cursor lines: {"role":"user"|"assistant","message":{"content":[...]}}; role-less control lines carry no conversation.
|
|
67
|
+
return ['user', 'assistant'].includes(record.role) ? { role: record.role, content: record.message?.content ?? record.content } : null;
|
|
68
|
+
}
|
|
69
|
+
if (host === 'deepseek-harness') {
|
|
70
|
+
// The JSONL adapters/dsh-plugin.mjs writes from session/event. Only the person's own messages are "user":
|
|
71
|
+
// dsh also sends its runtime context and skill catalog as user-role messages with another source.
|
|
72
|
+
if (record.type === 'user/message') return record.data?.source?.kind === 'user' ? { role: 'user', content: record.data.content } : null;
|
|
73
|
+
return record.type === 'assistant/message' ? { role: 'assistant', content: record.data?.message?.content } : null;
|
|
74
|
+
}
|
|
75
|
+
if (host === 'pi') {
|
|
76
|
+
// Pi's session file: `message` entries. Extension messages (role `custom`) are not the conversation.
|
|
77
|
+
const message = record.type === 'message' ? record.message : null;
|
|
78
|
+
return ['user', 'assistant'].includes(message?.role) ? { role: message.role, content: message.content } : null;
|
|
79
|
+
}
|
|
80
|
+
if (host === 'grok') {
|
|
81
|
+
// Inferred dialect (not verified against a live session): ACP update lines become one message fragment
|
|
82
|
+
// per chunk; chat-history lines carry role/content directly. Tool output lines are not conversation.
|
|
83
|
+
const update = record.params?.update ?? record.update ?? (typeof record.sessionUpdate === 'string' ? record : null);
|
|
84
|
+
if (update && typeof update === 'object') {
|
|
85
|
+
const kind = update.sessionUpdate;
|
|
86
|
+
if (kind === 'user_message_chunk') return { role: 'user', content: grokContentText(update.content), chunk: true };
|
|
87
|
+
if (kind === 'agent_message_chunk') return { role: 'assistant', content: grokContentText(update.content), chunk: true };
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
return ['user', 'assistant'].includes(record.role) ? { role: record.role, content: record.content } : null;
|
|
91
|
+
}
|
|
92
|
+
return record.type === 'context.append_message' && ['user', 'assistant'].includes(record.message?.role) ? record.message : null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function contextOf(record, host, context) {
|
|
96
|
+
const meta = host === 'codex' && record.type === 'session_meta' ? record.payload : record;
|
|
97
|
+
for (const [key, value] of Object.entries({ cwd: meta?.cwd, branch: meta?.gitBranch ?? meta?.git?.branch,
|
|
98
|
+
client_version: meta?.version ?? meta?.cli_version, model: record.message?.model, entrypoint: meta?.entrypoint })) {
|
|
99
|
+
if (context[key] === undefined && typeof value === 'string' && value) context[key] = shortened(value);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function checkpointText(message, counters) {
|
|
104
|
+
const blocks = message.content;
|
|
105
|
+
if (Array.isArray(blocks) && blocks.length > CHECKPOINT_LIMITS.blocks) counters.blocks_truncated++;
|
|
106
|
+
const text = (typeof blocks === 'string' ? blocks : Array.isArray(blocks)
|
|
107
|
+
? blocks.slice(0, CHECKPOINT_LIMITS.blocks).map(blockText).filter(Boolean).join('\n') : '');
|
|
108
|
+
// ACP chunk fragments split mid-word; trimming each fragment would corrupt the merged turn.
|
|
109
|
+
if (!text.trim() || (message.role === 'user' && INJECTED.some(prefix => text.trim().startsWith(prefix)))) return null;
|
|
110
|
+
const clean = redact(message.chunk ? text : text.trim());
|
|
111
|
+
if (Array.from(clean).length > CHECKPOINT_LIMITS.chars) counters.messages_truncated++;
|
|
112
|
+
return { role: message.role, content: shortened(clean), ...(message.chunk ? { chunk: true } : {}) };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** ACP chunk updates split one host message over many lines; merge consecutive same-role fragments. */
|
|
116
|
+
function mergeChunks(messages) {
|
|
117
|
+
const merged = [];
|
|
118
|
+
for (const message of messages) {
|
|
119
|
+
const last = merged.at(-1);
|
|
120
|
+
const fits = last && Array.from(last.content).length + Array.from(message.content).length <= CHECKPOINT_LIMITS.chars;
|
|
121
|
+
if (fits && last.role === message.role && (last.chunk || message.chunk)) last.content += message.content;
|
|
122
|
+
else merged.push(message);
|
|
123
|
+
delete merged.at(-1).chunk;
|
|
124
|
+
}
|
|
125
|
+
return merged;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function parseWindow(buffer, host, subagent, messages, counters, context) {
|
|
129
|
+
let end = buffer.lastIndexOf(10);
|
|
130
|
+
if (end < buffer.length - 1) counters.partial_last_line = true;
|
|
131
|
+
for (; end >= 0 && counters.lines < CHECKPOINT_LIMITS.records;) {
|
|
132
|
+
const start = end === 0 ? 0 : buffer.lastIndexOf(10, end - 1) + 1;
|
|
133
|
+
const text = buffer.subarray(start, end).toString('utf8').trim();
|
|
134
|
+
end = start - 1;
|
|
135
|
+
if (!text) continue;
|
|
136
|
+
counters.lines++;
|
|
137
|
+
let record;
|
|
138
|
+
try { record = JSON.parse(text); } catch { counters.invalid_lines++; continue; }
|
|
139
|
+
if (!record || typeof record !== 'object' || Array.isArray(record)) { counters.unknown_lines++; continue; }
|
|
140
|
+
contextOf(record, host, context);
|
|
141
|
+
const message = messageOf(record, host, subagent);
|
|
142
|
+
if (!message) { counters.unknown_lines++; continue; }
|
|
143
|
+
counters.recognized_lines++;
|
|
144
|
+
const kept = checkpointText(message, counters);
|
|
145
|
+
if (!kept) continue;
|
|
146
|
+
if (messages.length < CHECKPOINT_LIMITS.messages) messages.push(kept);
|
|
147
|
+
else counters.turns_dropped++;
|
|
148
|
+
}
|
|
149
|
+
if (end >= 0) counters.record_limit_reached = true;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Read the most recent conversation, with a small head window for provenance, and disclose every cap. */
|
|
153
|
+
export async function readTranscriptMessages({ path, host, subagent = false }) {
|
|
154
|
+
const harness = HOSTS[host];
|
|
155
|
+
if (!harness) throw new Error('unsupported checkpoint host');
|
|
156
|
+
const bounded = await transcriptWindows(path);
|
|
157
|
+
const messages = [];
|
|
158
|
+
const counters = { lines: 0, recognized_lines: 0, unknown_lines: 0, invalid_lines: 0, turns_dropped: 0,
|
|
159
|
+
messages_truncated: 0, blocks_truncated: 0, record_limit_reached: false, partial_last_line: false };
|
|
160
|
+
const context = {};
|
|
161
|
+
// Reverse order makes message cap retain the most recent turns, while context keeps the latest fact.
|
|
162
|
+
for (const window of bounded.windows.toReversed()) parseWindow(window, harness, subagent, messages, counters, context);
|
|
163
|
+
messages.reverse();
|
|
164
|
+
const legacy = harness === 'kimi-code';
|
|
165
|
+
const inferred = harness === 'grok' || harness === 'cursor';
|
|
166
|
+
if (harness === 'grok') messages.splice(0, messages.length, ...mergeChunks(messages));
|
|
167
|
+
const partial = bounded.partial || legacy || inferred || counters.record_limit_reached || counters.partial_last_line || counters.turns_dropped > 0
|
|
168
|
+
|| counters.invalid_lines > 0 || counters.messages_truncated > 0 || counters.blocks_truncated > 0;
|
|
169
|
+
if (partial && messages.length) messages[0].content = shortened(
|
|
170
|
+
'[Estelle: this checkpoint is PARTIAL. Read bounds, omitted records, or text limits apply; this is not the complete session history.]\n' + messages[0].content);
|
|
171
|
+
return { messages, client: { name: harness, ...context, transcript_partial: partial, transcript_bytes: bounded.bytes,
|
|
172
|
+
transcript_read_bytes: bounded.read, ...(legacy ? { transcript_format: 'kimi-legacy-wire', newer_format_verified: false } : {}),
|
|
173
|
+
...(inferred ? { transcript_format: `${harness}-jsonl-inferred`, format_verified: false,
|
|
174
|
+
capture_note: 'Dialect inferred from third-party observations, not verified against a live host session.' } : {}),
|
|
175
|
+
...counters } };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** SessionEnd is deliberately delegated to the caller's durable reference queue, without filesystem/network work. */
|
|
179
|
+
export async function checkpointSession({ payload, host, repo, stateDir, request }) {
|
|
180
|
+
if (cloudExecutionIdentity()) return { saved: false, unsupported: true,
|
|
181
|
+
reason: 'Cloud transcript checkpoints require a private owner-bound storage door; visible event streaming remains separate.' };
|
|
182
|
+
if (payload.hook_event_name === 'SessionEnd') return { saved: false, deferred: true };
|
|
183
|
+
if (!safeSession(payload.session_id)) throw new Error('invalid host session identity');
|
|
184
|
+
const child = payload.hook_event_name === 'SubagentStop';
|
|
185
|
+
const path = child && string(payload.agent_transcript_path).trim() ? payload.agent_transcript_path : payload.transcript_path;
|
|
186
|
+
if (!string(path).trim()) return { saved: false, reason: 'host did not supply a transcript path' };
|
|
187
|
+
let messages, client;
|
|
188
|
+
if (host === 'kimi' || host === 'kimi-code') {
|
|
189
|
+
const history = await readKimiHistory({ sessionId: payload.session_id, cwd: payload.cwd });
|
|
190
|
+
if (!history.available) return { saved: false, reason: history.coverage.reason, client: history.coverage };
|
|
191
|
+
const selected = history.messages.slice(-CHECKPOINT_LIMITS.messages);
|
|
192
|
+
messages = selected.map(message => ({ ...message, content: shortened(message.content) }));
|
|
193
|
+
const capped = selected.length < history.messages.length || selected.some(message => Array.from(message.content).length > CHECKPOINT_LIMITS.chars);
|
|
194
|
+
client = { name: 'kimi-code', transcript_format: history.format,
|
|
195
|
+
transcript_partial: !history.coverage.complete || capped, capture_coverage: history.coverage };
|
|
196
|
+
if (client.transcript_partial && messages.length) messages[0].content = shortened('[Estelle: this checkpoint is PARTIAL; inspect capture_coverage.]\n' + messages[0].content);
|
|
197
|
+
} else ({ messages, client } = await readTranscriptMessages({ path, host, subagent: child }));
|
|
198
|
+
if (!messages.length) return { saved: false, reason: 'no verified user or assistant messages in transcript', client };
|
|
199
|
+
const id = string(payload.agent_id);
|
|
200
|
+
if (child && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(id)) {
|
|
201
|
+
const kind = string(payload.agent_type).replace(/[\[\]\r\n]/g, ' ').trim() || id;
|
|
202
|
+
for (const message of messages) message.content = shortened(`[subagent: ${kind.slice(0, 100)} ${id}] ${message.content}`);
|
|
203
|
+
}
|
|
204
|
+
const body = { session_id: payload.session_id, messages,
|
|
205
|
+
client: sanitize({ ...client, event: payload.hook_event_name, cwd: client.cwd || payload.cwd || undefined, repo }) };
|
|
206
|
+
await request('/checkpoint', body);
|
|
207
|
+
return { saved: true, messages: messages.length, client: body.client };
|
|
208
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/** Claude Code setup has one path: an old install migrates, and no old install is a fresh one. */
|
|
2
|
+
import { execFile } from 'node:child_process';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { open } from 'node:fs/promises';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { join, resolve } from 'node:path';
|
|
7
|
+
import { checkKey, KEY_MESSAGES } from './key-check.mjs';
|
|
8
|
+
import { commitHooks, inspectHooks, planHooks } from './migration.mjs';
|
|
9
|
+
import { VERSION } from './version.mjs';
|
|
10
|
+
|
|
11
|
+
export const OLD_PLUGIN = 'estelle@fatelabs', NEW_PLUGIN = 'estelle@estelle-plugins';
|
|
12
|
+
const LIST_BYTES = 262144, CALL_MS = 15000, RC_BYTES = 262144, MAX_LISTED_PLUGINS = 1024;
|
|
13
|
+
const COMMANDS = Object.freeze({ list: ['plugin', 'list', '--json'],
|
|
14
|
+
// --keep-data: the old plugin's saved data stays on disk, and `user` is the only scope setup may change.
|
|
15
|
+
uninstall: ['plugin', 'uninstall', OLD_PLUGIN, '--keep-data', '--json', '--scope', 'user'] });
|
|
16
|
+
const RC_FILES = Object.freeze(['.zshenv', '.zprofile', '.zshrc', '.zlogin', '.bash_profile', '.bashrc', '.profile']);
|
|
17
|
+
const EXPORT_LINE = /^[ \t]*(?:export[ \t]+)?ESTELLE_API_KEY=/gm;
|
|
18
|
+
|
|
19
|
+
function nativeClaude(operation) {
|
|
20
|
+
return new Promise(done => {
|
|
21
|
+
execFile('claude', COMMANDS[operation], { timeout: CALL_MS, maxBuffer: LIST_BYTES, windowsHide: true },
|
|
22
|
+
(error, stdout) => done(error ? { ok: false, text: stdout || '' } : { ok: true, text: stdout }));
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The plugins Claude Code reports. Throws on any row without an id: non-empty is not correctly parsed. */
|
|
27
|
+
function parseList(text) {
|
|
28
|
+
const items = JSON.parse(text);
|
|
29
|
+
if (!Array.isArray(items) || items.length > MAX_LISTED_PLUGINS) throw new Error('plugin_list_shape');
|
|
30
|
+
if (!items.every(item => typeof item?.id === 'string' && typeof item?.scope === 'string')) throw new Error('plugin_list_shape');
|
|
31
|
+
return items;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const scopesOf = (items, id) => items.filter(item => item.id === id).map(item => item.scope);
|
|
35
|
+
|
|
36
|
+
/** How many times shell startup files set the key. A count and file names only; the contents never leave this function.
|
|
37
|
+
* A warning, not a proof: a file past RC_BYTES is read in part, so null means none were found, not that none exist. */
|
|
38
|
+
export async function duplicateKeyExports(home) {
|
|
39
|
+
const found = [];
|
|
40
|
+
let count = 0;
|
|
41
|
+
for (const name of RC_FILES) {
|
|
42
|
+
const file = await open(join(home, name), 'r').catch(() => null);
|
|
43
|
+
if (!file) continue;
|
|
44
|
+
try {
|
|
45
|
+
const bytes = Buffer.alloc(RC_BYTES), { bytesRead } = await file.read(bytes, 0, RC_BYTES, 0);
|
|
46
|
+
const hits = (bytes.subarray(0, bytesRead).toString('utf8').match(EXPORT_LINE) || []).length;
|
|
47
|
+
if (hits) { count += hits; found.push(name); }
|
|
48
|
+
} catch { /* an unreadable file is not a duplicate */ } finally { await file.close(); }
|
|
49
|
+
}
|
|
50
|
+
if (count < 2) return null;
|
|
51
|
+
return { exports: count, files: found,
|
|
52
|
+
message: `ESTELLE_API_KEY is set ${count} times in ${found.join(', ')}. Your shell keeps the last one it reads, so hooks may use a different key or account than you expect. Keep one.` };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function accountFields(env, home, check) {
|
|
56
|
+
const duplicate = await duplicateKeyExports(home);
|
|
57
|
+
const key = env.ESTELLE_API_KEY;
|
|
58
|
+
const keyCheck = key ? await check(key) : null;
|
|
59
|
+
return { capture_auth: key ? 'environment_key' : 'off_no_key',
|
|
60
|
+
...(keyCheck ? { key_check: keyCheck, key_message: KEY_MESSAGES[keyCheck] } : {}),
|
|
61
|
+
...(duplicate ? { duplicate_key: duplicate } : {}) };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const report = (status, fields = {}) => ({ status, host: 'claude', version: VERSION, ...fields,
|
|
65
|
+
mcp_auth: 'oauth_in_claude_not_probed', accounts_match: 'not_proved', hook_execution: 'not_observed',
|
|
66
|
+
trust: 'not_changed_not_measured', reload: 'fresh_session_required' });
|
|
67
|
+
|
|
68
|
+
const next = capture => ['Restart Claude Code. In a session, run /mcp, choose Estelle, and sign in with your browser.',
|
|
69
|
+
...(capture === 'off_no_key' ? ['MCP works without a key. Session capture stays off until ESTELLE_API_KEY is set to a key from the same Estelle account.'] : [])];
|
|
70
|
+
|
|
71
|
+
async function uninstallOld(native) {
|
|
72
|
+
const removed = await native('uninstall');
|
|
73
|
+
let outcome = null;
|
|
74
|
+
try { outcome = JSON.parse(removed.text).outcome; } catch { /* unparsed is not removed; the read-back decides */ }
|
|
75
|
+
const after = await native('list');
|
|
76
|
+
if (after.ok !== true) return 'unknown';
|
|
77
|
+
const gone = !scopesOf(parseList(after.text), OLD_PLUGIN).includes('user');
|
|
78
|
+
return gone && outcome === 'ok' ? 'removed' : gone ? 'unknown' : 'not_removed';
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function applyMigration(file, snapshot, oldScopes, native, fields) {
|
|
82
|
+
let hooks = { status: 'unchanged', removed: 0 };
|
|
83
|
+
try {
|
|
84
|
+
if (snapshot) hooks = await commitHooks(file, snapshot);
|
|
85
|
+
} catch {
|
|
86
|
+
return report('pending_conflict', { ...fields, path: 'migrate', hooks: 'not_applied', old_plugin: 'not_removed' });
|
|
87
|
+
}
|
|
88
|
+
if (hooks.status === 'unknown') return report('unknown', { ...fields, path: 'migrate', hooks: 'unknown', old_plugin: 'not_removed' });
|
|
89
|
+
const plugin = oldScopes.includes('user') ? await uninstallOld(native) : 'absent';
|
|
90
|
+
const left = oldScopes.filter(scope => scope !== 'user');
|
|
91
|
+
const complete = plugin !== 'not_removed' && plugin !== 'unknown' && left.length === 0;
|
|
92
|
+
return report(complete ? 'applied' : plugin === 'unknown' ? 'unknown' : 'partial', { ...fields, path: 'migrate', hooks: hooks.status,
|
|
93
|
+
hook_removals: hooks.removed, old_plugin: plugin, old_plugin_left_in_scopes: left,
|
|
94
|
+
next: complete ? next(fields.capture_auth) : [`Run /plugin in Claude Code and remove ${OLD_PLUGIN} from the listed scope. Nothing else was changed.`] });
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export async function runClaudeSetup({ apply = false, expect, env = process.env, home = homedir(), base } = {}, ports = {}) {
|
|
98
|
+
if (apply && (ports.platform || process.platform) === 'win32') return report('pending_unsupported_platform');
|
|
99
|
+
const native = ports.native || nativeClaude;
|
|
100
|
+
const check = ports.checkKey || (key => checkKey(key, { base, version: VERSION }));
|
|
101
|
+
const listing = await native('list');
|
|
102
|
+
let items;
|
|
103
|
+
try {
|
|
104
|
+
if (listing.ok !== true) throw new Error('plugin_list');
|
|
105
|
+
items = parseList(listing.text);
|
|
106
|
+
} catch { return report('pending_host_cli', { message: 'The claude command could not list plugins, so nothing was changed.' }); }
|
|
107
|
+
if (!scopesOf(items, NEW_PLUGIN).length) {
|
|
108
|
+
return report('pending_package', { message: `Install ${NEW_PLUGIN} first. Nothing was changed, so any old install keeps working.` });
|
|
109
|
+
}
|
|
110
|
+
const file = join(env.CLAUDE_CONFIG_DIR ? resolve(env.CLAUDE_CONFIG_DIR) : join(home, '.claude'), 'settings.json');
|
|
111
|
+
let snapshot, removals;
|
|
112
|
+
try {
|
|
113
|
+
snapshot = await inspectHooks(file);
|
|
114
|
+
removals = snapshot ? planHooks(snapshot.bytes).removed : 0;
|
|
115
|
+
} catch { return report('pending_configuration', { message: 'settings.json could not be read safely, so nothing was changed.' }); }
|
|
116
|
+
const oldScopes = scopesOf(items, OLD_PLUGIN);
|
|
117
|
+
const path = oldScopes.length || removals ? 'migrate' : 'fresh';
|
|
118
|
+
const fields = await accountFields(env, home, check);
|
|
119
|
+
const planHash = createHash('sha256').update(JSON.stringify({ before: snapshot?.hash || null, removals, oldScopes, version: VERSION })).digest('hex');
|
|
120
|
+
if (expect !== undefined && expect !== planHash) return report('pending_conflict', { ...fields, path });
|
|
121
|
+
if (path === 'fresh') {
|
|
122
|
+
return report(apply ? 'unchanged' : 'planned', { ...fields, path, next: next(fields.capture_auth),
|
|
123
|
+
message: 'No old Estelle install was found, so there is nothing to migrate.' });
|
|
124
|
+
}
|
|
125
|
+
if (!apply) {
|
|
126
|
+
return report('planned', { ...fields, path, old_plugin_scopes: oldScopes, hook_removals: removals, plan_sha256: planHash,
|
|
127
|
+
message: `Found an old Estelle install: ${[oldScopes.length ? OLD_PLUGIN : '', removals ? `${removals} old hook command(s)` : ''].filter(Boolean).join(' and ')}. Run setup claude --apply to remove it. Sessions, saved memory and every other setting stay.` });
|
|
128
|
+
}
|
|
129
|
+
return applyMigration(file, snapshot, oldScopes, native, fields);
|
|
130
|
+
}
|
package/runtime/cli.mjs
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { opendir } from 'node:fs/promises';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { apiBase, apiClient, errorCode, MAX_JSON_BYTES, readJson, recordStatus, stateDirectory } from './io.mjs';
|
|
6
|
+
import { checkKey, KEY_MESSAGES } from './key-check.mjs';
|
|
7
|
+
import { VERSION } from './version.mjs';
|
|
8
|
+
|
|
9
|
+
async function readInput() {
|
|
10
|
+
const chunks = [];
|
|
11
|
+
let bytes = 0;
|
|
12
|
+
for await (const chunk of process.stdin) {
|
|
13
|
+
bytes += chunk.length;
|
|
14
|
+
if (bytes > MAX_JSON_BYTES) throw new Error('input_size');
|
|
15
|
+
chunks.push(chunk);
|
|
16
|
+
}
|
|
17
|
+
try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); }
|
|
18
|
+
catch { throw new Error('input_json'); }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function status(stateDir) {
|
|
22
|
+
let directory;
|
|
23
|
+
try { directory = await opendir(join(stateDir, 'status')); }
|
|
24
|
+
catch (error) { if (error.code === 'ENOENT') return []; throw error; }
|
|
25
|
+
const rows = [];
|
|
26
|
+
const MAX_STATUS_ROWS = 64;
|
|
27
|
+
for await (const entry of directory) {
|
|
28
|
+
if (rows.length >= MAX_STATUS_ROWS) break;
|
|
29
|
+
if (!entry.isFile() || !/^[a-z-]+\.json$/.test(entry.name)) continue;
|
|
30
|
+
rows.push(await readJson(join(stateDir, 'status', entry.name), 16_000));
|
|
31
|
+
}
|
|
32
|
+
return rows;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function doctor() {
|
|
36
|
+
const api = apiBase();
|
|
37
|
+
const keyPresent = Boolean(process.env.ESTELLE_API_KEY);
|
|
38
|
+
// Presence is not validity: a revoked key is present. Anything but `accepted` is not a pass.
|
|
39
|
+
const keyCheck = keyPresent ? await checkKey(process.env.ESTELLE_API_KEY, { base: api, version: VERSION }) : 'not_checked_no_key';
|
|
40
|
+
// Only the Codex package asks Codex: nothing else should start an app-server on this machine.
|
|
41
|
+
const codexHooks = existsSync(new URL('../.codex-plugin/plugin.json', import.meta.url))
|
|
42
|
+
? await (await import('./codex-trust.mjs')).codexHookTrust() : undefined;
|
|
43
|
+
console.log(JSON.stringify({ version: VERSION, node: process.version, api,
|
|
44
|
+
credential: keyPresent ? 'environment' : 'missing', key_check: keyCheck,
|
|
45
|
+
...(KEY_MESSAGES[keyCheck] ? { key_message: KEY_MESSAGES[keyCheck] } : {}),
|
|
46
|
+
...(codexHooks ? { codex_hooks: codexHooks } : {}),
|
|
47
|
+
status: await status(stateDirectory()) }, null, 2));
|
|
48
|
+
// As with the key: not being able to tell that hooks will run is not a pass.
|
|
49
|
+
if (keyCheck !== 'accepted' || (codexHooks && codexHooks.status !== 'trusted')) process.exitCode = 1;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const [command, host] = process.argv.slice(2);
|
|
53
|
+
if (command === 'doctor') {
|
|
54
|
+
doctor().catch(error => { console.error(errorCode(error)); process.exitCode = 1; });
|
|
55
|
+
} else if (command === 'hook') {
|
|
56
|
+
let payload;
|
|
57
|
+
// Optional integration failures must not abort a user's turn. They remain visible in doctor.
|
|
58
|
+
try {
|
|
59
|
+
payload = await readInput();
|
|
60
|
+
const { handleHook } = await import('./hooks.mjs');
|
|
61
|
+
const output = await handleHook({ host, payload, stateDir: stateDirectory(), request: apiClient() });
|
|
62
|
+
if (output) console.log(JSON.stringify(output));
|
|
63
|
+
} catch (error) {
|
|
64
|
+
if (host === 'cursor') {
|
|
65
|
+
const { defaultOutput } = await import('../adapters/cursor.mjs');
|
|
66
|
+
const output = defaultOutput(payload?.hook_event_name);
|
|
67
|
+
if (output) console.log(JSON.stringify(output));
|
|
68
|
+
}
|
|
69
|
+
try {
|
|
70
|
+
const directory = stateDirectory({ ...process.env, ESTELLE_PLUGIN_DATA: undefined });
|
|
71
|
+
await recordStatus(directory, { host: /^[a-z-]+$/.test(host || '') ? host : 'unknown',
|
|
72
|
+
event: 'unknown', mode: 'runner', status: 'failed', code: errorCode(error) });
|
|
73
|
+
} catch {
|
|
74
|
+
console.error('Estelle could not save hook diagnostics. Check the plugin data directory permissions.');
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
} else if (command === 'move') {
|
|
78
|
+
const chunks = [];
|
|
79
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
80
|
+
const { moveCommand } = await import('./move.mjs');
|
|
81
|
+
await moveCommand(host, Buffer.concat(chunks).toString('utf8'));
|
|
82
|
+
} else if (command === 'continue-cloud') {
|
|
83
|
+
try {
|
|
84
|
+
const { runNativeContinue } = await import('./native-export.mjs');
|
|
85
|
+
console.log(JSON.stringify(await runNativeContinue(process.argv.slice(3))));
|
|
86
|
+
} catch (error) {
|
|
87
|
+
const { nativeErrorCode } = await import('./native-export.mjs');
|
|
88
|
+
console.error(`Native continuation could not be completed (${nativeErrorCode(error)}). No safe-to-close acknowledgment was issued.`);
|
|
89
|
+
process.exitCode = 1;
|
|
90
|
+
}
|
|
91
|
+
} else if (command === 'dsh-telemetry') {
|
|
92
|
+
// `dsh --profile <name> --dump-config | node runtime/cli.mjs dsh-telemetry`: the Silo's check on what dsh will mount.
|
|
93
|
+
const chunks = [];
|
|
94
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
95
|
+
const { telemetryCheck, TELEMETRY_OFF } = await import('./dsh-telemetry.mjs');
|
|
96
|
+
const verdict = telemetryCheck(Buffer.concat(chunks).toString('utf8'));
|
|
97
|
+
console.log(verdict);
|
|
98
|
+
if (verdict !== TELEMETRY_OFF) process.exitCode = 1;
|
|
99
|
+
} else if (command === 'setup') {
|
|
100
|
+
try {
|
|
101
|
+
const { runSetupArgs } = await import('./setup.mjs');
|
|
102
|
+
const result = await runSetupArgs(process.argv.slice(3));
|
|
103
|
+
console.log(JSON.stringify(result));
|
|
104
|
+
if (!['planned', 'applied', 'unchanged'].includes(result.status)) process.exitCode = 1;
|
|
105
|
+
} catch {
|
|
106
|
+
console.log(JSON.stringify({ status: 'pending_setup_unavailable' }));
|
|
107
|
+
process.exitCode = 1;
|
|
108
|
+
}
|
|
109
|
+
} else {
|
|
110
|
+
console.error('Usage: node runtime/cli.mjs hook <claude-code|codex|kimi|grok|cursor|dsh|opencode|pi> | doctor | setup <host> [--apply] [--expect SHA256]');
|
|
111
|
+
process.exitCode = 1;
|
|
112
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/** Read whether Codex will run Estelle's hooks. Read-only: hook approval belongs to the person, in Codex. */
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
|
|
4
|
+
const PLUGIN_ID = 'estelle@estelle-plugins';
|
|
5
|
+
const DEADLINE_MS = 8_000;
|
|
6
|
+
const MAX_OUTPUT_BYTES = 1_000_000;
|
|
7
|
+
const MAX_HOOK_ROWS = 64;
|
|
8
|
+
|
|
9
|
+
export const REVIEW_STEP = 'Codex turned off Estelle\'s hooks because the plugin changed. Run /hooks in Codex and press t, '
|
|
10
|
+
+ 'or choose "Trust all and continue" the next time Codex starts. Until then Estelle captures nothing from this '
|
|
11
|
+
+ 'machine and does not check file writes for credentials.';
|
|
12
|
+
// Right after an update is when this read is most likely to fail, so a failed read still says what to do.
|
|
13
|
+
export const UNREADABLE = Object.freeze({ status: 'unavailable',
|
|
14
|
+
next_step: 'Estelle could not ask Codex whether its hooks will run. Run /hooks in Codex, and if an Estelle hook needs review, press t.' });
|
|
15
|
+
|
|
16
|
+
/** Counts by Codex's own trust status. A hook that is not trusted does not run. */
|
|
17
|
+
export function summarizeHooks(rows) {
|
|
18
|
+
if (!Array.isArray(rows) || rows.length > MAX_HOOK_ROWS) return UNREADABLE;
|
|
19
|
+
const ours = rows.filter(row => row?.pluginId === PLUGIN_ID);
|
|
20
|
+
if (!ours.length) return { status: 'not_installed' };
|
|
21
|
+
const needs = ours.filter(row => row.enabled !== false && !['trusted', 'managed'].includes(row.trustStatus)).length;
|
|
22
|
+
const result = { status: needs ? 'review_required' : 'trusted', hooks: ours.length, needs_review: needs };
|
|
23
|
+
return needs ? { ...result, next_step: REVIEW_STEP } : result;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Codex's documented hooks/list over a private app-server, closed before returning. Never approves. */
|
|
27
|
+
export function codexHookTrust(cwd = process.cwd(), { spawnImpl = spawn, deadlineMs = DEADLINE_MS, env = process.env } = {}) {
|
|
28
|
+
return new Promise(resolve => {
|
|
29
|
+
let child;
|
|
30
|
+
let bytes = 0;
|
|
31
|
+
let buffer = '';
|
|
32
|
+
let settled = false;
|
|
33
|
+
let timer;
|
|
34
|
+
const finish = value => {
|
|
35
|
+
if (settled) return;
|
|
36
|
+
settled = true;
|
|
37
|
+
clearTimeout(timer);
|
|
38
|
+
try { child?.kill(); } catch { /* already gone */ }
|
|
39
|
+
resolve(value);
|
|
40
|
+
};
|
|
41
|
+
const send = message => child.stdin.write(`${JSON.stringify(message)}\n`);
|
|
42
|
+
const receive = chunk => {
|
|
43
|
+
bytes += chunk.length;
|
|
44
|
+
if (bytes > MAX_OUTPUT_BYTES) return finish(UNREADABLE);
|
|
45
|
+
buffer += chunk.toString('utf8');
|
|
46
|
+
for (let at = buffer.indexOf('\n'); at >= 0; at = buffer.indexOf('\n')) {
|
|
47
|
+
const line = buffer.slice(0, at);
|
|
48
|
+
buffer = buffer.slice(at + 1);
|
|
49
|
+
let row;
|
|
50
|
+
try { row = JSON.parse(line); } catch { return finish(UNREADABLE); }
|
|
51
|
+
if (row.id === 1) {
|
|
52
|
+
send({ method: 'initialized', params: {} });
|
|
53
|
+
send({ id: 2, method: 'hooks/list', params: { cwds: [cwd] } });
|
|
54
|
+
} else if (row.id === 2) finish(summarizeHooks(row.result?.data?.[0]?.hooks));
|
|
55
|
+
}
|
|
56
|
+
return undefined;
|
|
57
|
+
};
|
|
58
|
+
timer = setTimeout(() => finish(UNREADABLE), deadlineMs);
|
|
59
|
+
try {
|
|
60
|
+
child = spawnImpl('codex', ['app-server', '--stdio'], { cwd, env, stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true });
|
|
61
|
+
child.on('error', () => finish(UNREADABLE));
|
|
62
|
+
child.on('exit', () => finish(UNREADABLE));
|
|
63
|
+
child.stdin.on('error', () => finish(UNREADABLE));
|
|
64
|
+
child.stdout.on('data', receive);
|
|
65
|
+
send({ id: 1, method: 'initialize', params: { clientInfo: { name: 'estelle-plugin-doctor', version: '1' } } });
|
|
66
|
+
} catch { finish(UNREADABLE); }
|
|
67
|
+
});
|
|
68
|
+
}
|