@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.
Files changed (83) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +6 -0
  3. package/README.md +46 -2
  4. package/adapters/claude.mjs +17 -0
  5. package/adapters/codex.mjs +85 -0
  6. package/adapters/cursor.mjs +66 -0
  7. package/adapters/dsh-host.mjs +181 -0
  8. package/adapters/dsh-plugin.mjs +11 -0
  9. package/adapters/dsh.mjs +54 -0
  10. package/adapters/grok.mjs +63 -0
  11. package/adapters/host-bridge.mjs +85 -0
  12. package/adapters/kimi.mjs +135 -0
  13. package/adapters/opencode-mirror.mjs +103 -0
  14. package/adapters/opencode-plugin.mjs +143 -0
  15. package/adapters/opencode.mjs +15 -0
  16. package/adapters/pi-extension.mjs +107 -0
  17. package/adapters/pi.mjs +13 -0
  18. package/adapters/plugin-envelope.mjs +56 -0
  19. package/agents/estelle-grounder.md +34 -0
  20. package/agents/estelle-historian.md +28 -0
  21. package/agents/estelle-repair.md +29 -0
  22. package/agents/estelle-reviewer.md +32 -0
  23. package/commands/cloud.md +28 -0
  24. package/commands/code.md +6 -0
  25. package/commands/handoff.md +25 -0
  26. package/commands/monitor.md +6 -0
  27. package/commands/resume.md +6 -0
  28. package/commands/review.md +6 -0
  29. package/commands/rooms.md +7 -0
  30. package/instructions.md +19 -0
  31. package/package.json +34 -4
  32. package/runtime/auth.mjs +27 -0
  33. package/runtime/checkpoint.mjs +208 -0
  34. package/runtime/claude-setup.mjs +130 -0
  35. package/runtime/cli.mjs +112 -0
  36. package/runtime/codex-trust.mjs +68 -0
  37. package/runtime/credential.mjs +341 -0
  38. package/runtime/dsh-session.mjs +91 -0
  39. package/runtime/dsh-telemetry.mjs +31 -0
  40. package/runtime/hooks.mjs +234 -0
  41. package/runtime/identity.mjs +20 -0
  42. package/runtime/io.mjs +155 -0
  43. package/runtime/key-check.mjs +51 -0
  44. package/runtime/kimi-history.mjs +163 -0
  45. package/runtime/mailbox.mjs +46 -0
  46. package/runtime/migration.mjs +118 -0
  47. package/runtime/move.mjs +443 -0
  48. package/runtime/native-export.mjs +204 -0
  49. package/runtime/native-index.mjs +77 -0
  50. package/runtime/native-tree.mjs +117 -0
  51. package/runtime/queued-context.mjs +152 -0
  52. package/runtime/redact.mjs +74 -0
  53. package/runtime/reindex.mjs +259 -0
  54. package/runtime/setup.mjs +174 -0
  55. package/runtime/stream.mjs +755 -0
  56. package/runtime/version.mjs +2 -0
  57. package/runtime/write-warning.mjs +67 -0
  58. package/skills/abstain-right/SKILL.md +19 -0
  59. package/skills/api-call-ground/SKILL.md +19 -0
  60. package/skills/bug-hunt/SKILL.md +20 -0
  61. package/skills/chain-of-verification/SKILL.md +19 -0
  62. package/skills/change-impact/SKILL.md +19 -0
  63. package/skills/coding-workflow/SKILL.md +20 -0
  64. package/skills/commit-guard/SKILL.md +20 -0
  65. package/skills/context-checkpoint/SKILL.md +19 -0
  66. package/skills/continuity-brief/SKILL.md +19 -0
  67. package/skills/dead-code-sweep/SKILL.md +19 -0
  68. package/skills/deep-search/SKILL.md +19 -0
  69. package/skills/diff-review/SKILL.md +19 -0
  70. package/skills/estelle/SKILL.md +119 -0
  71. package/skills/estelle-loop/SKILL.md +19 -0
  72. package/skills/estelle-monitor-install/SKILL.md +20 -0
  73. package/skills/evidence-traceability-audit/SKILL.md +19 -0
  74. package/skills/grounded-generate/SKILL.md +19 -0
  75. package/skills/incident-rca/SKILL.md +20 -0
  76. package/skills/mutation-test/SKILL.md +19 -0
  77. package/skills/program-repair/SKILL.md +20 -0
  78. package/skills/prompt-injection-defense/SKILL.md +19 -0
  79. package/skills/property-based-test/SKILL.md +19 -0
  80. package/skills/refactor-rfc/SKILL.md +19 -0
  81. package/skills/root-cause-loop/SKILL.md +19 -0
  82. package/skills/test-first/SKILL.md +19 -0
  83. package/skills/threat-model-stride/SKILL.md +19 -0
@@ -0,0 +1,234 @@
1
+ import { join } from 'node:path';
2
+ import { mkdir, opendir, unlink, rename } from 'node:fs/promises';
3
+ import { normalize as claude, formatContext as claudeContext } from '../adapters/claude.mjs';
4
+ import { normalize as codex, formatContext as codexContext } from '../adapters/codex.mjs';
5
+ import { safeSession, hash, repository, readJson, writeJson, errorCode, recordStatus } from './io.mjs';
6
+ import { streamSession } from './stream.mjs';
7
+ import { checkpointSession } from './checkpoint.mjs';
8
+ import { redact } from './redact.mjs';
9
+ import { queueReindex } from './reindex.mjs';
10
+ import { timelineIdentity } from './identity.mjs';
11
+ import { mutatingTool, writeWarning } from './write-warning.mjs';
12
+ import { beginContext, saveContext, takeContext } from './queued-context.mjs';
13
+ import { MAILBOX_HOSTS, pullAtBoundary, sessionIdentity } from './mailbox.mjs';
14
+
15
+ const CHECKPOINT_EVENTS = new Set(['Stop', 'SubagentStop', 'PreCompact', 'Interrupt']);
16
+ const STREAM_EVENTS = new Set(['UserPromptSubmit', 'PostToolUse', 'Stop', 'SubagentStop', 'PreCompact', 'Interrupt']);
17
+ const MAX_DEFERRED_SCAN = 512;
18
+
19
+ async function adapter(host) {
20
+ if (host === 'claude-code') return { normalize: claude, formatContext: claudeContext };
21
+ if (host === 'codex') return { normalize: codex, formatContext: codexContext };
22
+ if (host === 'kimi') return import('../adapters/kimi.mjs');
23
+ if (host === 'grok') return import('../adapters/grok.mjs');
24
+ if (host === 'cursor') return import('../adapters/cursor.mjs');
25
+ if (host === 'dsh') return import('../adapters/dsh.mjs');
26
+ if (host === 'opencode') return import('../adapters/opencode.mjs');
27
+ if (host === 'pi') return import('../adapters/pi.mjs');
28
+ throw new Error('unsupported_host');
29
+ }
30
+
31
+ export async function deferSession(normalized, stateDir) {
32
+ const { host, sessionId, cwd, transcriptPath, event } = normalized;
33
+ if (!safeSession(sessionId)) throw new Error('session_missing');
34
+ // Exit does no network or transcript read. Do not queue a prompt, tool result, or credential.
35
+ await writeJson(join(stateDir, 'deferred', `${hash(`${host}:${sessionId}`)}.json`), {
36
+ host, queuedAt: new Date().toISOString(),
37
+ payload: { session_id: sessionId, cwd, transcript_path: transcriptPath || null, hook_event_name: event },
38
+ });
39
+ }
40
+
41
+ export async function drainOne(stateDir, request) {
42
+ let directory;
43
+ try { directory = await opendir(join(stateDir, 'deferred')); }
44
+ catch (error) { if (error.code === 'ENOENT') return; throw error; }
45
+ let scanned = 0;
46
+ const candidates = [];
47
+ for await (const entry of directory) {
48
+ if (++scanned > MAX_DEFERRED_SCAN) break;
49
+ if (!entry.isFile() || !/^[a-f0-9]{64}\.json$/.test(entry.name)) continue;
50
+ candidates.push(entry.name);
51
+ }
52
+ candidates.sort();
53
+ const cursorPath = join(stateDir, 'deferred-cursor.json');
54
+ const cursor = await readJson(cursorPath).catch(error => {
55
+ if (error.code === 'ENOENT') return { last: '' };
56
+ throw error;
57
+ });
58
+ const pivot = candidates.findIndex(name => name > cursor.last);
59
+ const ordered = pivot < 0 ? candidates : [...candidates.slice(pivot), ...candidates.slice(0, pivot)];
60
+ for (const name of ordered) {
61
+ await writeJson(cursorPath, { last: name });
62
+ const path = join(stateDir, 'deferred', name);
63
+ const item = await readJson(path, 16_000);
64
+ if (!['claude-code', 'codex', 'kimi', 'grok', 'cursor', 'dsh', 'opencode', 'pi'].includes(item.host)) throw new Error('unsupported_host');
65
+ const repo = repository(item.payload.cwd);
66
+ const payload = { ...item.payload, hook_event_name: 'Stop' };
67
+ if (item.host === 'kimi') {
68
+ const port = await adapter(item.host);
69
+ payload.transcript_path = await port.getTranscriptPath({ host: 'kimi', sessionId: payload.session_id, cwd: payload.cwd });
70
+ }
71
+ if (!payload.transcript_path) {
72
+ // Preserve the reference for diagnosis without letting one unusable item starve the queue.
73
+ await mkdir(join(stateDir, 'unavailable'), { recursive: true, mode: 0o700 });
74
+ await rename(path, join(stateDir, 'unavailable', name));
75
+ continue;
76
+ }
77
+ const [result, stream] = await Promise.all([
78
+ checkpointSession({ payload, host: item.host, repo: repo?.name, stateDir, request }),
79
+ streamSession({ payload, host: item.host, repo: repo?.name, stateDir, request }),
80
+ ]);
81
+ if (result.saved && !stream.pending && !stream.backlog) {
82
+ if (stream.incomplete || stream.unsupported) {
83
+ await mkdir(join(stateDir, 'partial'), { recursive: true, mode: 0o700 });
84
+ await rename(path, join(stateDir, 'partial', name));
85
+ } else await unlink(path);
86
+ }
87
+ return stream.association_partial ? { association_partial: true } : undefined;
88
+ }
89
+ }
90
+
91
+ async function runAction(mode, normalized, stateDir, operation) {
92
+ let result;
93
+ let row;
94
+ try {
95
+ result = await operation();
96
+ const skipped = result?.unsupported || result?.incomplete || result?.saved === false;
97
+ row = result?.association_partial ? { status: 'partial', code: 'association_unverified' }
98
+ : result?.degraded ? { status: 'partial', code: 'recall_degraded' }
99
+ : { status: result?.pending ? 'pending' : result?.skipped ? 'skipped' : skipped ? 'partial' : 'ok' };
100
+ } catch (error) {
101
+ row = { status: 'failed', code: errorCode(error) };
102
+ result = { failed: true, code: row.code };
103
+ }
104
+ try {
105
+ await recordStatus(stateDir, { host: normalized.host, event: normalized.event, mode,
106
+ ...row });
107
+ } catch {
108
+ // Recording an optional integration failure must never create another rejected action.
109
+ console.error('Estelle could not save local hook status. Check the plugin data directory.');
110
+ return { ...result, diagnostics_failed: true };
111
+ }
112
+ return result;
113
+ }
114
+
115
+ async function recall(n, repo, request) {
116
+ const query = typeof n.prompt === 'string' ? n.prompt.trim().slice(0, 8_000) : '';
117
+ if (!query || !repo) return { text: '', skipped: true };
118
+ const body = { repo: repo.name, query: redact(query), code: false, host: n.host,
119
+ timeline_session: timelineIdentity(n.host, n.sessionId) };
120
+ const result = await request('/search', body);
121
+ if (typeof result.recall !== 'string') throw new Error('response_json');
122
+ const degraded = result.degraded === true;
123
+ const text = !result.recall.trim() && degraded
124
+ ? 'Estelle recall is temporarily unavailable. Retry with estelle_resume or memory_chat.' : result.recall;
125
+ return { text, degraded };
126
+ }
127
+
128
+ const START_TEXT = 'If Estelle MCP tools are available, call estelle_resume before planning and use their live schemas. '
129
+ + 'Use only this session’s verified Room identity; never invent or borrow a token. '
130
+ + 'Check capture coverage before claiming a complete handoff.';
131
+
132
+ /** One host event, one process. Network failures are recorded separately from successful empty results. */
133
+ export async function handleHook({ host, payload, stateDir, request }) {
134
+ const port = await adapter(host);
135
+ const n = port.normalize(payload);
136
+ if (!n.event) throw new Error('event_missing');
137
+ if (!safeSession(n.sessionId)) throw new Error('session_missing');
138
+ // `/estelle handoff` reads this to learn which session and conversation file it is in. Names and a path, no content.
139
+ if (n.cwd && ['SessionStart', 'UserPromptSubmit'].includes(n.event)) {
140
+ const { noteCurrentSession } = await import('./move.mjs');
141
+ await noteCurrentSession(stateDir, { host, sessionId: n.sessionId, transcriptPath: n.transcriptPath, cwd: n.cwd }).catch(() => {});
142
+ }
143
+ const found = writeWarning(n);
144
+ if (found?.unscanned) {
145
+ await recordStatus(stateDir, { host, event: n.event, mode: 'protect', status: 'partial', code: 'input_bound' });
146
+ return port.defaultOutput?.(payload.hook_event_name) ?? null;
147
+ }
148
+ const output = await answerEvent({ host, port, n, payload, stateDir, request });
149
+ return found ? withWarning(host, output, found.warning) : output;
150
+ }
151
+
152
+ /** The warning added to whatever this event already answers. ⛔ It adds words and never a decision: no host is told to stop.
153
+ * Each host's own field, because each shows a different one. Stderr too, the only place Kimi has at this event. */
154
+ function withWarning(host, output, warning) {
155
+ console.error(warning);
156
+ if (host === 'kimi') return output;
157
+ if (host === 'cursor') return { ...output, user_message: warning, agent_message: warning };
158
+ // dsh, OpenCode and Pi run Estelle from their own in-process plugin, which shows `warning` in the host's own way.
159
+ if (['dsh', 'opencode', 'pi'].includes(host)) return { ...output, warning };
160
+ const earlier = output?.hookSpecificOutput?.additionalContext;
161
+ const additionalContext = earlier ? `${earlier}\n\n${warning}` : warning;
162
+ if (host === 'grok') return { ...output, hookSpecificOutput: { ...output?.hookSpecificOutput, additionalContext } };
163
+ return { ...output, systemMessage: warning, hookSpecificOutput: { ...output?.hookSpecificOutput, hookEventName: 'PreToolUse', additionalContext } };
164
+ }
165
+
166
+ async function answerEvent({ host, port, n, payload, stateDir, request }) {
167
+ const defaultOutput = () => port.defaultOutput?.(payload.hook_event_name) ?? null;
168
+ const queuedContext = host === 'grok' || host === 'cursor';
169
+ const grokContextPath = join(stateDir, 'context', `${hash(`${host}:${n.sessionId}`)}.json`);
170
+ let contextRequest;
171
+ if (queuedContext && n.event === 'UserPromptSubmit') {
172
+ contextRequest = await beginContext(grokContextPath, n.turnId);
173
+ }
174
+ if (n.event === 'SessionEnd' || n.event === 'Interrupt') {
175
+ await deferSession(n, stateDir);
176
+ return null;
177
+ }
178
+ if (host === 'kimi' && port.getTranscriptPath) n.transcriptPath = await port.getTranscriptPath(n);
179
+ const streamPayload = { ...payload, session_id: n.sessionId, cwd: n.cwd,
180
+ hook_event_name: n.event, transcript_path: n.transcriptPath || null };
181
+ const repo = repository(n.cwd);
182
+ const actions = [];
183
+ const edited = n.event === 'PostToolUse' && mutatingTool(n.toolName)
184
+ && n.raw?.tool_response?.is_error !== true && n.raw?.tool_response?.success !== false;
185
+ if (repo && (edited || ['Stop', 'SessionStart'].includes(n.event))) {
186
+ actions.push(runAction('reindex', n, stateDir, () => queueReindex({ normalized: n, repo, stateDir, request })));
187
+ }
188
+ if (n.event === 'SessionStart') actions.push(runAction('deferred', n, stateDir, () => drainOne(stateDir, request)));
189
+ // Session capture belongs to the authenticated account even before a workspace has Git metadata.
190
+ if (STREAM_EVENTS.has(n.event)) actions.push(runAction('stream', n, stateDir,
191
+ () => streamSession({ payload: streamPayload, host, repo: repo?.name, stateDir, request })));
192
+ if (CHECKPOINT_EVENTS.has(n.event)) actions.push(runAction('checkpoint', n, stateDir,
193
+ () => checkpointSession({ payload: streamPayload, host, repo: repo?.name, stateDir, request })));
194
+ // This session's own identity (id + session_token) and its mail, for hosts the server can address.
195
+ const mailbox = MAILBOX_HOSTS.has(host);
196
+ const identity = mailbox && ['SessionStart', 'SubagentStart'].includes(n.event)
197
+ ? runAction('identity', n, stateDir, () => sessionIdentity(n, request)) : undefined;
198
+ const boundary = !mailbox ? '' : n.event === 'SessionStart' ? 'start'
199
+ : n.event === 'PostToolUse' && !n.agentId ? 'tool' : '';
200
+ const mail = boundary ? runAction('mailbox', n, stateDir, () => pullAtBoundary(n, stateDir, request, boundary)) : undefined;
201
+ // Attach handlers before awaiting recall: other operations can finish while it is in flight.
202
+ const completedActions = Promise.allSettled(actions);
203
+ let context;
204
+ if (n.event === 'UserPromptSubmit') {
205
+ context = await runAction('context', n, stateDir, () => recall(n, repo, request));
206
+ }
207
+ await completedActions;
208
+ const [own, delivered] = await Promise.all([identity, mail]);
209
+ const extra = [own?.text, delivered?.text].filter(text => typeof text === 'string' && text.trim()).join('\n\n');
210
+ if (context?.failed) return port.formatContext(`Estelle recall was not obtained (${context.code}). Use its MCP tools directly; this is not an empty search result.`, n.event) ?? defaultOutput();
211
+ if (context?.text && queuedContext) {
212
+ const saved = await saveContext(grokContextPath, n.turnId, contextRequest, context.text, context.degraded);
213
+ await recordStatus(stateDir, { host, event: n.event, mode: 'context',
214
+ ...(context.degraded ? { status: 'partial', code: 'recall_degraded', pending: saved }
215
+ : { status: saved ? 'pending' : 'skipped' }) });
216
+ return defaultOutput();
217
+ }
218
+ const contextBoundary = host === 'grok' && n.event === 'PreToolUse'
219
+ || host === 'cursor' && ['PostToolUse', 'PostToolUseFailure'].includes(n.event);
220
+ if (contextBoundary) {
221
+ const queued = await takeContext(grokContextPath, n.turnId);
222
+ if (queued) {
223
+ await recordStatus(stateDir, { host, event: n.event, mode: 'context',
224
+ ...(queued.degraded ? { status: 'partial', code: 'recall_degraded', pending: false } : { status: 'emitted' }) });
225
+ return port.formatContext(queued.text, n.event);
226
+ }
227
+ }
228
+ if (context?.text) return port.formatContext(context.text, n.event);
229
+ if (n.event === 'SessionStart' || n.event === 'SubagentStart') {
230
+ return port.formatContext(extra ? `${START_TEXT}\n\n${extra}` : START_TEXT, n.event) ?? defaultOutput();
231
+ }
232
+ if (extra) return port.formatContext(extra, n.event) ?? defaultOutput();
233
+ return defaultOutput();
234
+ }
@@ -0,0 +1,20 @@
1
+ // Shared public timeline identity. This is a name, never a Rooms write credential.
2
+ const HARNESSES = { claude: 'claude-code', 'claude-code': 'claude-code', codex: 'codex',
3
+ kimi: 'kimi-code', 'kimi-code': 'kimi-code', grok: 'grok', cursor: 'cursor',
4
+ dsh: 'deepseek-harness', 'deepseek-harness': 'deepseek-harness', opencode: 'opencode', pi: 'pi' };
5
+ export function canonicalHost(host) {
6
+ const value = HARNESSES[host];
7
+ if (!value) throw new Error('unsupported_host');
8
+ return value;
9
+ }
10
+ export function cloudExecutionIdentity(env = process.env) {
11
+ const value = env.ESTELLE_EXECUTION_SESSION_ID;
12
+ if (value === undefined || value === '') return '';
13
+ if (typeof value !== 'string' || !/^ade-launch-[a-f0-9]{16}$/.test(value)) throw new Error('cloud_execution_identity_invalid');
14
+ return value;
15
+ }
16
+ export function timelineIdentity(host, session, env = process.env) {
17
+ if (typeof session !== 'string' || !/^[A-Za-z0-9_-]{1,200}$/.test(session)) throw new Error('session_missing');
18
+ const canonical = canonicalHost(host);
19
+ return cloudExecutionIdentity(env) || `${canonical}-${session}`;
20
+ }
package/runtime/io.mjs ADDED
@@ -0,0 +1,155 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, join, resolve, relative, isAbsolute, sep } from 'node:path';
5
+ import { realpathSync } from 'node:fs';
6
+ import { mkdir, open, rename, stat, readFile, unlink } from 'node:fs/promises';
7
+ import { VERSION } from './version.mjs';
8
+
9
+ export const MAX_JSON_BYTES = 2_000_000;
10
+ export const MAX_RESPONSE_BYTES = 2_000_000;
11
+ export const REQUEST_TIMEOUT_MS = 8_000;
12
+ export const safeSession = value => typeof value === 'string' && /^[A-Za-z0-9_-]{1,200}$/.test(value);
13
+ export const hash = value => createHash('sha256').update(value).digest('hex');
14
+
15
+ export function stateDirectory(env = process.env) {
16
+ // Never write into a host's immutable, approved plugin bundle.
17
+ const base = resolve(env.ESTELLE_PLUGIN_DATA || join(homedir(), '.estelle-plugins'));
18
+ const bundle = realpathSync(resolve(import.meta.dirname, '..'));
19
+ let existing = base;
20
+ let resolved = false;
21
+ const MAX_PARENTS = 64;
22
+ for (let i = 0; i < MAX_PARENTS; i++) {
23
+ try { existing = realpathSync(existing); resolved = true; break; }
24
+ catch (error) { if (error.code !== 'ENOENT') throw error; existing = dirname(existing); }
25
+ }
26
+ if (!resolved) throw new Error('state_inside_bundle');
27
+ for (const candidate of [base, existing]) {
28
+ const child = relative(bundle, candidate);
29
+ if (child === '' || (child !== '..' && !child.startsWith(`..${sep}`) && !isAbsolute(child))) throw new Error('state_inside_bundle');
30
+ }
31
+ // A different account credential must never replay another account's saved transcript batches.
32
+ const key = env.ESTELLE_API_KEY;
33
+ return join(base, key ? hash(key).slice(0, 24) : 'unauthenticated');
34
+ }
35
+
36
+ export async function readJson(path, maxBytes = MAX_JSON_BYTES) {
37
+ const file = await open(path, 'r');
38
+ try {
39
+ const info = await file.stat();
40
+ if (!info.isFile() || info.size > maxBytes) throw new Error('state_size');
41
+ const buffer = Buffer.alloc(info.size + 1);
42
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
43
+ if (bytesRead > info.size) throw new Error('state_size');
44
+ return JSON.parse(buffer.subarray(0, bytesRead).toString('utf8'));
45
+ } finally { await file.close(); }
46
+ }
47
+
48
+ export async function writeJson(path, value) {
49
+ const content = JSON.stringify(value);
50
+ if (Buffer.byteLength(content) > MAX_JSON_BYTES) throw new Error('state_size');
51
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
52
+ const temporary = `${path}.${randomUUID()}.tmp`;
53
+ const file = await open(temporary, 'wx', 0o600);
54
+ try { await file.writeFile(content); await file.sync(); }
55
+ finally { await file.close(); }
56
+ try { await rename(temporary, path); }
57
+ catch (error) { await unlink(temporary).catch(() => {}); throw error; }
58
+ }
59
+
60
+ export function git(cwd, args, { strict = false, raw = false, bytes = false, timeout = 1500 } = {}) {
61
+ const env = { ...process.env, GIT_TERMINAL_PROMPT: '0' };
62
+ for (const name of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR',
63
+ 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_NAMESPACE', 'GIT_PREFIX']) delete env[name];
64
+ try {
65
+ const output = execFileSync('git', ['-C', cwd, ...args], {
66
+ env, encoding: bytes ? null : 'utf8', timeout, maxBuffer: MAX_JSON_BYTES, stdio: ['ignore', 'pipe', 'ignore'],
67
+ });
68
+ return bytes || raw ? output : output.trim();
69
+ } catch { if (strict) throw new Error('git_failed'); return ''; }
70
+ }
71
+
72
+ export function repository(cwd, env = process.env) {
73
+ const root = git(cwd, ['rev-parse', '--show-toplevel'], { raw: true }).replace(/\r?\n$/, '');
74
+ if (!root) return null;
75
+ const remote = git(root, ['remote', 'get-url', 'origin']);
76
+ const match = /(?:[:/])([^/:\s]+\/[^/\s]+?)(?:\.git)?$/.exec(remote);
77
+ const name = env.ESTELLE_REPO || match?.[1];
78
+ if (!name || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(name)) return null;
79
+ return { root, name };
80
+ }
81
+
82
+ export function apiBase(env = process.env) {
83
+ let url;
84
+ try { url = new URL(env.ESTELLE_API_URL || 'https://api.fatelabs.ca'); }
85
+ catch { throw new Error('invalid_api_url'); }
86
+ const local = ['127.0.0.1', '[::1]', 'localhost'].includes(url.hostname);
87
+ if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) ||
88
+ url.username || url.password || url.search || url.hash || !['', '/'].includes(url.pathname)) {
89
+ throw new Error('invalid_api_url');
90
+ }
91
+ return url.origin;
92
+ }
93
+
94
+ export function apiClient({ env = process.env, fetchImpl = fetch, timeoutMs = REQUEST_TIMEOUT_MS,
95
+ deadline = Date.now() + 12_000 } = {}) {
96
+ const base = apiBase(env);
97
+ const key = env.ESTELLE_API_KEY;
98
+ return async (path, body) => {
99
+ if (!key || /[\r\n]/.test(key)) throw new Error('credential_missing');
100
+ const remaining = deadline - Date.now();
101
+ if (remaining <= 0) throw new DOMException('hook deadline', 'TimeoutError');
102
+ if (!/^\/[a-z0-9/_-]+$/i.test(path)) throw new Error('invalid_route');
103
+ const encoded = JSON.stringify(body);
104
+ if (Buffer.byteLength(encoded) > MAX_JSON_BYTES) throw new Error('request_size');
105
+ const response = await fetchImpl(`${base}${path}`, {
106
+ method: 'POST', redirect: 'error', signal: AbortSignal.timeout(Math.min(remaining, timeoutMs)),
107
+ headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json',
108
+ 'X-Estelle-Client-Protocol': '1', 'X-Estelle-Hook-Contract': '1',
109
+ 'X-Estelle-Client-Version': `estelle-plugins/${VERSION}` },
110
+ body: encoded,
111
+ });
112
+ let bytes = 0;
113
+ const parts = [];
114
+ for await (const chunk of response.body || []) {
115
+ bytes += chunk.byteLength;
116
+ if (bytes > MAX_RESPONSE_BYTES) throw new Error('response_size');
117
+ parts.push(Buffer.from(chunk));
118
+ }
119
+ const text = Buffer.concat(parts).toString('utf8');
120
+ if (!response.ok) {
121
+ // Server text is used internally by stream poison-event isolation. Never log it.
122
+ const error = new Error('http_error');
123
+ error.status = response.status;
124
+ let detail;
125
+ try {
126
+ const parsed = JSON.parse(text);
127
+ detail = typeof parsed.error === 'string' ? parsed.error : parsed.error?.message;
128
+ } catch { /* A non-JSON refusal remains an HTTP error. */ }
129
+ error.message = typeof detail === 'string' ? detail.slice(0, 1000) : text.slice(0, 1000);
130
+ throw error;
131
+ }
132
+ try { return text ? JSON.parse(text) : {}; }
133
+ catch { throw new Error('response_json'); }
134
+ };
135
+ }
136
+
137
+ const ERROR_CODES = new Set(['credential_missing', 'invalid_api_url', 'invalid_route',
138
+ 'request_size', 'response_size', 'response_json', 'state_size', 'input_size', 'input_json',
139
+ 'event_missing', 'session_missing', 'transcript_missing', 'unsupported_host', 'state_inside_bundle', 'context_claim_locked']);
140
+
141
+ export function errorCode(error) {
142
+ if (Number.isInteger(error?.status)) return `http_${error.status}`;
143
+ if (error?.name === 'TimeoutError' || error?.name === 'AbortError') return 'timeout';
144
+ if (ERROR_CODES.has(error?.message)) return error.message;
145
+ if (['EACCES', 'EPERM', 'ENOENT', 'ENOSPC'].includes(error?.code)) return error.code.toLowerCase();
146
+ return 'operation_failed';
147
+ }
148
+
149
+ export async function recordStatus(stateDir, { host, event, mode, status, code, pending }) {
150
+ const row = { at: new Date().toISOString(), host, event, mode, status, ...(code ? { code } : {}),
151
+ ...(typeof pending === 'boolean' ? { pending } : {}) };
152
+ // One bounded record per host/mode; no prompts, paths, headers, tokens, or remote response text.
153
+ if (!/^[a-z-]+$/.test(host) || !/^[a-z-]+$/.test(mode)) throw new Error('unsupported_host');
154
+ await writeJson(join(stateDir, 'status', `${host}-${mode}.json`), row);
155
+ }
@@ -0,0 +1,51 @@
1
+ /** Ask the server whether a key works, with a method that spends nothing. Reports a word, never the key or a body. */
2
+ const CAP = 16384, TIMEOUT_MS = 8000;
3
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
4
+ const usable = value => typeof value === 'string' && /^[\x21-\x7e]{1,4096}$/.test(value);
5
+
6
+ async function boundedText(response) {
7
+ const reader = response.body?.getReader();
8
+ if (!reader) return '';
9
+ const chunks = [];
10
+ let bytes = 0;
11
+ for (let reads = 0; reads < CAP; reads++) {
12
+ const { done, value } = await reader.read();
13
+ if (done) return Buffer.concat(chunks).toString('utf8');
14
+ bytes += value.length;
15
+ if (bytes > CAP) { await reader.cancel(); throw new Error('response_bound'); }
16
+ chunks.push(value);
17
+ }
18
+ throw new Error('response_bound');
19
+ }
20
+
21
+ /** `accepted`, `rejected` (401), `account_refused` (a valid key the plan or balance stops), or a could-not-check word. */
22
+ export async function checkKey(key, { base = 'https://api.fatelabs.ca', fetchImpl = fetch, version = '0' } = {}) {
23
+ if (!usable(key)) return 'malformed';
24
+ const body = JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-11-25',
25
+ capabilities: {}, clientInfo: { name: 'estelle-plugin-doctor', version } } });
26
+ try {
27
+ const response = await fetchImpl(`${base}/mcp`, { method: 'POST', redirect: 'error', body,
28
+ signal: AbortSignal.timeout(TIMEOUT_MS),
29
+ headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json', Accept: 'application/json' } });
30
+ if (response.status === 401) return 'rejected';
31
+ if (response.status === 402) return 'account_refused';
32
+ if (response.status !== 200) return 'server_unavailable';
33
+ const reply = JSON.parse(await boundedText(response));
34
+ if (reply?.error?.code === -32001) return 'rejected';
35
+ if (reply?.error?.code === -32002) return 'account_refused';
36
+ return object(reply?.result?.capabilities) ? 'accepted' : 'unexpected_response';
37
+ } catch {
38
+ return 'unreachable';
39
+ }
40
+ }
41
+
42
+ export const KEY_MESSAGES = Object.freeze({
43
+ not_checked_no_key: 'ESTELLE_API_KEY is not set, so session capture is off. Claude Code MCP signs in through /mcp and does not need it; other hosts do.',
44
+ accepted: 'The server accepted ESTELLE_API_KEY.',
45
+ rejected: 'The server rejected ESTELLE_API_KEY (HTTP 401). It is wrong, revoked or from another environment. Create a new key in your Estelle account, replace the old one, then quit and reopen your host app.',
46
+ account_refused: 'The server knows this key, but the account behind it cannot use this right now. Check the plan and balance.',
47
+ malformed: 'ESTELLE_API_KEY is set but is not a usable key. It is empty or contains spaces or line breaks.',
48
+ server_unavailable: 'The key could not be checked because the server did not answer normally. This says nothing about the key.',
49
+ unexpected_response: 'The key could not be checked because the server sent an unexpected reply. This says nothing about the key.',
50
+ unreachable: 'The key could not be checked because the server could not be reached. This says nothing about the key.',
51
+ });
@@ -0,0 +1,163 @@
1
+ // Current Kimi wire 1.5 reader. The source contracts are pinned in docs/research/kimi-current-capture.md.
2
+ import { open } from 'node:fs/promises';
3
+ import { getTranscriptPath } from '../adapters/kimi.mjs';
4
+ import { cap, sanitize } from './redact.mjs';
5
+
6
+ export const KIMI_HISTORY_LIMITS = Object.freeze({ bytes: 32 * 1024 * 1024,
7
+ records: 100_000, branches: 256, parts: 1_000, calls: 1_000 });
8
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
9
+ const typeOf = value => typeof value?.type === 'string' ? value.type.replace(/^human\./, '') : '';
10
+ const timeOf = value => Number.isSafeInteger(value) && value >= 0 && Number.isFinite(new Date(value).getTime());
11
+ const string = value => typeof value === 'string' ? value : '';
12
+
13
+ function visibleMessage(value) {
14
+ if (!object(value) || !['user', 'assistant', 'tool'].includes(value.role)) return null;
15
+ const content = typeof value.content === 'string' ? [{ type: 'text', text: value.content }] : value.content;
16
+ if (!Array.isArray(content) || content.length > KIMI_HISTORY_LIMITS.parts) return null;
17
+ const parts = [];
18
+ let incomplete = false;
19
+ for (const part of content) {
20
+ if (part?.type === 'text' && typeof part.text === 'string') {
21
+ parts.push({ type: 'text', text: cap(part.text) });
22
+ if (Array.from(part.text).length > 20_000) incomplete = true;
23
+ }
24
+ if (['image_url', 'image', 'audio_url', 'video_url'].includes(part?.type)) {
25
+ parts.push({ type: 'text', text: '[media attachment; bytes and URL omitted]' });
26
+ }
27
+ // Do not recover or persist encrypted, hidden, or recorded reasoning through this reader.
28
+ if (!['text', 'think', 'image_url', 'image', 'audio_url', 'video_url'].includes(part?.type)) incomplete = true;
29
+ }
30
+ const calls = value.toolCalls ?? [];
31
+ if (!Array.isArray(calls) || calls.length > KIMI_HISTORY_LIMITS.calls) return null;
32
+ return { message: { role: value.role, content: parts,
33
+ ...(typeof value.toolCallId === 'string' ? { toolCallId: value.toolCallId } : {}),
34
+ ...(typeof value.isError === 'boolean' ? { isError: value.isError } : {}),
35
+ ...(value.role === 'assistant' ? { toolCalls: sanitize(calls) } : {}),
36
+ }, incomplete };
37
+ }
38
+
39
+ /** Normalize a single actual journal record without inventing its timestamp, session, or identity. */
40
+ export function normalizeKimiRecord(record) {
41
+ if (!object(record) || !timeOf(record.time)) return null;
42
+ const type = typeOf(record);
43
+ if (['agent.turn.ended', 'turn.ended'].includes(type)) return { type: 'turn.ended', time: record.time };
44
+ if (!['agent.message.appended', 'context.append_message'].includes(type)) return null;
45
+ const wrapper = record.message;
46
+ const raw = object(wrapper?.message) ? wrapper.message : wrapper;
47
+ const visible = visibleMessage(raw);
48
+ if (!visible) return null;
49
+ const { message } = visible;
50
+ // System injections and generated summaries are not things the person typed.
51
+ const source = wrapper?.meta?.source;
52
+ const origin = raw?.origin?.kind ?? wrapper?.meta?.origin?.kind;
53
+ if (message.role === 'user' && ((source && source !== 'input') || (origin && origin !== 'user'))) return null;
54
+ return { type: 'context.append_message', time: record.time, message,
55
+ ...(visible.incomplete ? { capture_incomplete: true } : {}) };
56
+ }
57
+
58
+ function switchEdge(record, line) {
59
+ if (typeOf(record) !== 'agent.switched') return null;
60
+ if (typeof record.branch !== 'string' || !/^[A-Za-z0-9_-]{1,200}$/.test(record.branch)) throw new Error('invalid_branch');
61
+ if (!object(record.base) || typeof record.base.branch !== 'string' ||
62
+ !/^[A-Za-z0-9_-]{1,200}$/.test(record.base.branch) || !Number.isSafeInteger(record.base.line) ||
63
+ record.base.line < 0 || record.base.line >= line) throw new Error('invalid_branch_base');
64
+ return { branch: record.branch, line, base: record.base };
65
+ }
66
+
67
+ /** Select the same branch ancestry as Kimi's wire activeChain, iteratively and with a fixed bound. */
68
+ export function activeKimiRecords(records) {
69
+ if (!Array.isArray(records) || records.length > KIMI_HISTORY_LIMITS.records) throw new Error('record_bound');
70
+ const segments = new Map();
71
+ let branch = 'main';
72
+ let from = 1;
73
+ let base;
74
+ for (const [index, record] of records.entries()) {
75
+ const line = index + 1;
76
+ const edge = switchEdge(record, line);
77
+ if (!edge) continue;
78
+ segments.set(branch, { from, to: line, base });
79
+ if (segments.has(edge.branch) || segments.size >= KIMI_HISTORY_LIMITS.branches) throw new Error('branch_bound_or_duplicate');
80
+ branch = edge.branch; from = line + 1; base = edge.base;
81
+ }
82
+ segments.set(branch, { from, to: records.length, base });
83
+ const chain = [];
84
+ const visited = new Set();
85
+ let ceiling = records.length;
86
+ for (let depth = 0; depth < KIMI_HISTORY_LIMITS.branches; depth++) {
87
+ if (visited.has(branch)) throw new Error('branch_cycle');
88
+ const segment = segments.get(branch);
89
+ if (!segment || ceiling > segment.to || ceiling < segment.from - 1) throw new Error('unknown_branch_base');
90
+ visited.add(branch); chain.push({ from: segment.from, to: ceiling });
91
+ if (!segment.base) break;
92
+ ceiling = segment.base.line; branch = segment.base.branch;
93
+ }
94
+ if (chain.length >= KIMI_HISTORY_LIMITS.branches) throw new Error('branch_bound');
95
+ return chain.reverse().flatMap(segment => records.slice(segment.from - 1, segment.to)
96
+ .filter(record => typeOf(record) !== 'agent.switched'));
97
+ }
98
+
99
+ async function readBounded(path) {
100
+ const file = await open(path, 'r');
101
+ try {
102
+ const info = await file.stat();
103
+ if (!info.isFile() || info.size > KIMI_HISTORY_LIMITS.bytes) return { incomplete: true, reason: 'byte_bound', fileBytes: info.size };
104
+ const buffer = Buffer.alloc(info.size + 1);
105
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
106
+ if (bytesRead > info.size) return { incomplete: true, reason: 'concurrent_growth', fileBytes: info.size };
107
+ const text = buffer.subarray(0, bytesRead).toString('utf8');
108
+ const end = text.lastIndexOf('\n');
109
+ const lines = text.slice(0, end + 1).split('\n').slice(0, -1);
110
+ if (lines.length > KIMI_HISTORY_LIMITS.records) return { incomplete: true, reason: 'record_bound', fileBytes: info.size };
111
+ return { lines, fileBytes: info.size, incomplete: end + 1 < text.length || bytesRead < info.size };
112
+ } finally { await file.close(); }
113
+ }
114
+
115
+ const OBSERVATION = new Set(['metadata', 'agent.turn.started', 'agent.turn.ended', 'turn.prompt', 'turn.ended',
116
+ 'turn.cancel', 'context.undo', 'context.undone', 'agent.switched', 'llm.request', 'llm.response',
117
+ 'tools.update_store', 'state.updated', 'agent.state.updated']);
118
+
119
+ /** Read this registered main agent only. It never scans other sessions, reads blobs, or writes Kimi state. */
120
+ export async function readKimiHistory({ sessionId, cwd, home }) {
121
+ if (typeof sessionId !== 'string' || !/^[A-Za-z0-9_-]{1,200}$/.test(sessionId)) throw new Error('invalid_session');
122
+ const sourcePath = await getTranscriptPath({ host: 'kimi', sessionId, cwd }, { home });
123
+ if (!sourcePath) return { available: false, coverage: { complete: false, reason: 'registered_wire_unavailable' } };
124
+ const bounded = await readBounded(sourcePath);
125
+ if (!bounded.lines) return { available: false, sourcePath, coverage: { complete: false, ...bounded } };
126
+ const records = [];
127
+ let invalid = 0;
128
+ for (const line of bounded.lines) {
129
+ try { const value = JSON.parse(line); if (!object(value) || typeof value.type !== 'string') invalid++; else records.push(value); }
130
+ catch { invalid++; }
131
+ }
132
+ const metadata = records[0]?.type === 'metadata' ? records[0] : null;
133
+ const version = metadata?.protocol_version ?? '1.4';
134
+ if (typeof version !== 'string' || !/^1\.[0-5]$/.test(version)) {
135
+ return { available: false, sourcePath, coverage: { complete: false, reason: 'unsupported_wire_version' } };
136
+ }
137
+ // Line numbers are part of branch identity; do not project through missing or malformed records.
138
+ if (invalid) return { available: false, sourcePath, coverage: { complete: false, reason: 'invalid_records', invalid } };
139
+ let active;
140
+ try { active = activeKimiRecords(records); }
141
+ catch { return { available: false, sourcePath, coverage: { complete: false, reason: 'invalid_branch_history' } }; }
142
+ const lineOf = new Map(records.map((record, index) => [record, index + 1]));
143
+ const pairedUndo = new Set(records.filter(record => typeOf(record) === 'agent.switched')
144
+ .map(record => record.legacyUndoLine).filter(Number.isSafeInteger));
145
+ if (active.some(record => ['context.apply_compaction', 'context.clear'].includes(typeOf(record)) ||
146
+ (typeOf(record) === 'context.undo' && !pairedUndo.has(lineOf.get(record))))) {
147
+ return { available: false, sourcePath, coverage: { complete: false, reason: 'unsupported_context_mutation' } };
148
+ }
149
+ const normalized = [];
150
+ let unsupported = 0;
151
+ for (const record of active) {
152
+ const item = normalizeKimiRecord(record);
153
+ if (item) { normalized.push(item); if (item.capture_incomplete) unsupported++; }
154
+ else if (!OBSERVATION.has(typeOf(record))) unsupported++;
155
+ }
156
+ const messages = normalized.filter(record => record.type === 'context.append_message' && ['user', 'assistant'].includes(record.message.role))
157
+ .map(record => ({ role: record.message.role, content: record.message.content.filter(part => part.type === 'text').map(part => part.text).join('\n') }))
158
+ .filter(message => message.content);
159
+ return { available: true, sourcePath, format: `kimi-wire-${version}`, records: normalized, messages,
160
+ coverage: { complete: !bounded.incomplete && unsupported === 0, partialLastLine: bounded.incomplete,
161
+ fileBytes: bounded.fileBytes, recordsRead: records.length, recordsSelected: active.length, unsupported,
162
+ scope: 'registered main-agent visible conversation and tool records; media bytes and reasoning omitted' } };
163
+ }