@fatelabs/pi-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 +44 -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/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 +38 -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/runtime/move.mjs
ADDED
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
// `/estelle handoff` and `/estelle cloud`: collect this session's state and call the one server door, POST /sessions/move.
|
|
2
|
+
// The server picks the harness and writes the words. This file never reads an auth file or a credential: the conversation
|
|
3
|
+
// file comes from the host's own hook, one named file, and nothing else under the home directory is touched.
|
|
4
|
+
import { execFileSync } from 'node:child_process';
|
|
5
|
+
import { lstat, mkdtemp, opendir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
6
|
+
import { randomUUID } from 'node:crypto';
|
|
7
|
+
import { homedir, tmpdir } from 'node:os';
|
|
8
|
+
import { dirname, join } from 'node:path';
|
|
9
|
+
import { apiClient, git, hash, readJson, repository, stateDirectory, writeJson } from './io.mjs';
|
|
10
|
+
import { captureNativeTranscript, checkNativeRelativePath } from './native-export.mjs';
|
|
11
|
+
import { checkpointSession } from './checkpoint.mjs';
|
|
12
|
+
import { canonicalHost, cloudExecutionIdentity, timelineIdentity } from './identity.mjs';
|
|
13
|
+
import { isOpaque, textHasCredential } from './credential.mjs';
|
|
14
|
+
|
|
15
|
+
export const MOVING = 'moving this session to the cloud';
|
|
16
|
+
export const MOVE_LIMITS = Object.freeze({
|
|
17
|
+
snapshotFiles: 200, snapshotFileBytes: 2_000_000, pushMs: 45_000, requestMs: 60_000,
|
|
18
|
+
wordsChars: 8_000, noteChars: 600, rolloutScan: 20_000, pendingMs: 86_400_000,
|
|
19
|
+
unpushedDiffBytes: 8_000_000, visibilityMs: 5_000, gitMs: 20_000, untrackedSent: 64 });
|
|
20
|
+
// Paths that hold credentials by their nature, whatever is in them: a scan cannot see inside an encrypted or binary key.
|
|
21
|
+
const PRIVATE_PATH = /(?:^|\/)(?:\.env(?:\.[^/]*)?|\.npmrc|\.netrc|\.pypirc|\.git-credentials|\.dockercfg|\.docker\/config\.json|\.aws\/credentials|\.ssh\/[^/]+|id_(?:rsa|dsa|ecdsa|ed25519)|master\.key|credentials\.yml\.enc|secrets?\.(?:ya?ml|json|toml|env)|credentials\.json|service[-_]account[^/]*\.json|[^/]+\.(?:pem|key|p12|pfx|jks|keystore|ppk|kdbx))$/i;
|
|
22
|
+
// A lockfile is full of opaque digests under prefixes, and publishing it is normal.
|
|
23
|
+
const LOCKFILE = /(?:^|\/)(?:package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|[^/]+\.lock)$/;
|
|
24
|
+
// credential.mjs reads labels and known vendors, and a vendor it has never heard of has neither. So a short prefix on an
|
|
25
|
+
// opaque value counts by itself, in either case. A value with no prefix is not flagged: that is every hash in a repository.
|
|
26
|
+
// The leading `+` or `-` is a diff's, because an unpushed commit is scanned as its diff.
|
|
27
|
+
const prefixedOpaque = text => text.split(/[\s"'`,;:=()[\]{}<>]+/).some(word => /^[+-]?[A-Za-z]{2,10}[_-]/.test(word) && isOpaque(word));
|
|
28
|
+
export const secretShaped = text => textHasCredential(text) || prefixedOpaque(text);
|
|
29
|
+
const HARNESSES = { codex: 'codex', claude: 'claude-code', 'claude-code': 'claude-code', cursor: 'cursor', kimi: 'kimi-code',
|
|
30
|
+
'kimi-code': 'kimi-code', grok: 'grok', dsh: 'deepseek-harness', 'deepseek-harness': 'deepseek-harness' };
|
|
31
|
+
const NATIVE_HOSTS = new Set(['claude-code', 'codex']);
|
|
32
|
+
const UUID = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;
|
|
33
|
+
|
|
34
|
+
const hasServerAccess = env => Boolean(env.ESTELLE_API_KEY);
|
|
35
|
+
|
|
36
|
+
export function refusal(reason, needed = '') {
|
|
37
|
+
const error = new Error('move_refused');
|
|
38
|
+
error.reason = reason; error.needed = needed;
|
|
39
|
+
return error;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// `[harness] [words]`. The first word names a harness only when it is one, so `/estelle cloud fix codex` is a prompt.
|
|
43
|
+
export function parseWords(mode, raw) {
|
|
44
|
+
const text = String(raw ?? '').trim();
|
|
45
|
+
if (text.length > MOVE_LIMITS.wordsChars) throw refusal(`That is ${text.length} characters and a request holds ${MOVE_LIMITS.wordsChars}.`, 'Shorten it. Nothing was started.');
|
|
46
|
+
const [first = '', ...rest] = text.split(/\s+/);
|
|
47
|
+
const harness = HARNESSES[first.toLowerCase()] || '';
|
|
48
|
+
const words = harness ? text.slice(first.length).trim() : text;
|
|
49
|
+
if (mode === 'cloud' && !words) throw refusal('/estelle cloud needs a prompt.', 'Say what the cloud session should do.');
|
|
50
|
+
if (mode === 'handoff' && words.length > MOVE_LIMITS.noteChars) {
|
|
51
|
+
throw refusal(`That note is ${words.length} characters and a handoff holds ${MOVE_LIMITS.noteChars}.`, 'Shorten it. Nothing was started.');
|
|
52
|
+
}
|
|
53
|
+
return mode === 'cloud' ? { harness, prompt: words } : { harness, note: words };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const sessionPath = (stateDir, root) => join(stateDir, 'current', `${hash(root)}.json`);
|
|
57
|
+
|
|
58
|
+
// Called from every hook, so the commands know which session and file they are in. Names and a path, never content.
|
|
59
|
+
export async function noteCurrentSession(stateDir, { host, sessionId, transcriptPath, cwd }) {
|
|
60
|
+
const repo = repository(cwd);
|
|
61
|
+
if (!repo) return;
|
|
62
|
+
await writeJson(sessionPath(stateDir, repo.root), { host, sessionId, transcriptPath: transcriptPath || '',
|
|
63
|
+
at: new Date().toISOString() });
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Codex runs hooks only once a person trusts them, and never in `exec`, so a hook may never have named this session. It
|
|
67
|
+
// names its own thread to every process it starts, so a bounded walk of its own sessions folder finds that one file.
|
|
68
|
+
async function findRollout(root, thread) {
|
|
69
|
+
const pending = [root];
|
|
70
|
+
let seen = 0;
|
|
71
|
+
while (pending.length && seen < MOVE_LIMITS.rolloutScan) {
|
|
72
|
+
const directory = await opendir(pending.pop()).catch(() => null);
|
|
73
|
+
if (!directory) continue;
|
|
74
|
+
for await (const entry of directory) {
|
|
75
|
+
if (++seen >= MOVE_LIMITS.rolloutScan) break;
|
|
76
|
+
if (entry.isDirectory()) pending.push(join(entry.parentPath, entry.name));
|
|
77
|
+
else if (entry.isFile() && entry.name.endsWith(`${thread}.jsonl`)) return join(entry.parentPath, entry.name);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return '';
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function currentSession(stateDir, root, env, home) {
|
|
84
|
+
const noted = await readJson(sessionPath(stateDir, root), 16_000).catch(() => null);
|
|
85
|
+
const thread = env.CODEX_THREAD_ID;
|
|
86
|
+
if (!UUID.test(thread || '')) return noted;
|
|
87
|
+
if (noted?.sessionId === thread) return noted;
|
|
88
|
+
const sessions = join(env.CODEX_HOME || join(home || homedir(), '.codex'), 'sessions');
|
|
89
|
+
return { host: 'codex', sessionId: thread, transcriptPath: await findRollout(sessions, thread) };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function gitWrite(root, args, { env = {}, timeout = 10_000 } = {}) {
|
|
93
|
+
const clean = { ...process.env, GIT_TERMINAL_PROMPT: '0', ...env };
|
|
94
|
+
for (const name of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_PREFIX']) delete clean[name];
|
|
95
|
+
return execFileSync('git', ['-C', root, ...args], { env: clean, encoding: 'utf8', timeout, maxBuffer: 8_000_000,
|
|
96
|
+
stdio: ['ignore', 'pipe', 'pipe'] }).trim();
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// 🔴 THE FOUNDER'S RULING: "Handoff just push untrack continue." So a file is carried or it is named, and neither stops the handoff.
|
|
100
|
+
// Credential paths never go, and neither does a file the scan flags or one too large to scan.
|
|
101
|
+
async function sortForPush(root, paths, scan) {
|
|
102
|
+
const safe = [];
|
|
103
|
+
const skipped = [];
|
|
104
|
+
for (const path of paths) {
|
|
105
|
+
let held = false;
|
|
106
|
+
try { checkNativeRelativePath(path); } catch { held = true; }
|
|
107
|
+
if (held || PRIVATE_PATH.test(path)) { skipped.push(path); continue; }
|
|
108
|
+
const full = join(root, path);
|
|
109
|
+
const info = await lstat(full).catch(() => null);
|
|
110
|
+
if (!info || !info.isFile() || LOCKFILE.test(path)) { safe.push(path); continue; } // A deletion or a symlink carries no text to scan.
|
|
111
|
+
if (info.size > MOVE_LIMITS.snapshotFileBytes || scan(await readFile(full, 'latin1'))) { skipped.push(path); continue; }
|
|
112
|
+
safe.push(path);
|
|
113
|
+
}
|
|
114
|
+
return { safe: safe.slice(0, MOVE_LIMITS.snapshotFiles), skipped: [...skipped, ...safe.slice(MOVE_LIMITS.snapshotFiles)] };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// The commits this push would carry that origin has not seen, because a value deleted in a later commit is still history.
|
|
118
|
+
function unpushedHistory(root, scan) {
|
|
119
|
+
let diff;
|
|
120
|
+
let names;
|
|
121
|
+
try {
|
|
122
|
+
// By name, separately: a binary key has no `+++` line in a diff, so the diff alone never sees it.
|
|
123
|
+
names = execFileSync('git', ['-C', root, 'log', '--name-only', '--no-renames', '-z', '--format=', 'HEAD', '--not', '--remotes'],
|
|
124
|
+
{ encoding: 'utf8', timeout: 20_000, maxBuffer: MOVE_LIMITS.unpushedDiffBytes, stdio: ['ignore', 'pipe', 'ignore'] })
|
|
125
|
+
.split('\0').map(name => name.trim()).filter(Boolean);
|
|
126
|
+
diff = execFileSync('git', ['-C', root, 'log', '-p', '--no-color', '--no-ext-diff', 'HEAD', '--not', '--remotes', '--', '.',
|
|
127
|
+
':(exclude,glob)**/*.lock', ':(exclude,glob)**/package-lock.json', ':(exclude,glob)**/pnpm-lock.yaml'],
|
|
128
|
+
{ encoding: 'latin1', timeout: 20_000, maxBuffer: MOVE_LIMITS.unpushedDiffBytes, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
129
|
+
} catch { return ['your unpushed commits: too large to scan, so they could not be cleared']; }
|
|
130
|
+
const named = names.filter(name => PRIVATE_PATH.test(name)).map(name => `${name}: in an unpushed commit, and holds credentials by its nature`);
|
|
131
|
+
const added = diff.split('\n').filter(line => line.startsWith('+') && !line.startsWith('+++')).join('\n');
|
|
132
|
+
return [...new Set(named), ...(scan(added) ? ['your unpushed commits: something shaped like a credential is in their history'] : [])];
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// A commit cannot lose one file, so history is the one thing that still refuses the whole handoff.
|
|
136
|
+
function assertSafeHistory(root, scan) {
|
|
137
|
+
const problems = unpushedHistory(root, scan);
|
|
138
|
+
if (problems.length) {
|
|
139
|
+
throw refusal(`Nothing was pushed, because your unpushed commits would carry credentials to your remote: ${problems.join('; ')}.`,
|
|
140
|
+
'Remove them from those commits, then run this again.');
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// A snapshot lands on origin, so a public repo publishes it. Asked anonymously: an answer of 200 means anyone can read it.
|
|
145
|
+
export async function isPublicRepo(name, fetchImpl = fetch) {
|
|
146
|
+
try {
|
|
147
|
+
const answer = await fetchImpl(`https://api.github.com/repos/${name}`, { signal: AbortSignal.timeout(MOVE_LIMITS.visibilityMs),
|
|
148
|
+
headers: { Accept: 'application/vnd.github+json', 'User-Agent': 'estelle-plugin' } });
|
|
149
|
+
return answer.status === 200 ? true : answer.status === 404 ? false : null;
|
|
150
|
+
} catch { return null; }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// A commit built on a temporary index and pushed to its own branch. HEAD, the index and the working tree are never touched,
|
|
154
|
+
// and the push counts only once the remote reads back the same commit. Only the files named go, literally, so a skipped one cannot.
|
|
155
|
+
async function pushSnapshot(root, session, safe) {
|
|
156
|
+
const directory = await mkdtemp(join(tmpdir(), 'estelle-snapshot-'));
|
|
157
|
+
try {
|
|
158
|
+
const env = { GIT_INDEX_FILE: join(directory, 'index'), GIT_LITERAL_PATHSPECS: '1' };
|
|
159
|
+
gitWrite(root, ['read-tree', 'HEAD'], { env });
|
|
160
|
+
if (safe.length) {
|
|
161
|
+
const list = join(directory, 'paths');
|
|
162
|
+
await writeFile(list, safe.join('\0'));
|
|
163
|
+
gitWrite(root, ['add', '-A', `--pathspec-from-file=${list}`, '--pathspec-file-nul'], { env, timeout: 30_000 });
|
|
164
|
+
}
|
|
165
|
+
const tree = gitWrite(root, ['write-tree'], { env });
|
|
166
|
+
// Dated from HEAD, so the same tree is the same commit: a rerun pushes nothing new and names the same intent.
|
|
167
|
+
const when = git(root, ['log', '-1', '--format=%cI', 'HEAD'], { strict: true, timeout: MOVE_LIMITS.gitMs });
|
|
168
|
+
const commit = gitWrite(root, ['commit-tree', tree, '-p', 'HEAD', '-m', 'Estelle snapshot of uncommitted work'],
|
|
169
|
+
{ env: { GIT_AUTHOR_NAME: 'Estelle', GIT_AUTHOR_EMAIL: 'noreply@fatelabs.ca', GIT_COMMITTER_NAME: 'Estelle',
|
|
170
|
+
GIT_COMMITTER_EMAIL: 'noreply@fatelabs.ca', GIT_AUTHOR_DATE: when, GIT_COMMITTER_DATE: when } });
|
|
171
|
+
const branch = `estelle/snapshot/${session.slice(0, 40).replace(/[^A-Za-z0-9_-]/g, '-')}-${commit.slice(0, 8)}`;
|
|
172
|
+
try { gitWrite(root, ['push', '--quiet', 'origin', `${commit}:refs/heads/${branch}`], { timeout: MOVE_LIMITS.pushMs }); }
|
|
173
|
+
catch { throw refusal('Your uncommitted work could not be pushed to a snapshot branch.', 'Check that you can push to origin, then run this again.'); }
|
|
174
|
+
const seen = gitWrite(root, ['ls-remote', 'origin', `refs/heads/${branch}`], { timeout: 20_000 }).split(/\s+/)[0];
|
|
175
|
+
if (seen !== commit) throw refusal('The snapshot branch did not read back from origin.', 'Check origin, then run this again.');
|
|
176
|
+
return { branch, commit };
|
|
177
|
+
} finally { await rm(directory, { recursive: true, force: true }); }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// `--porcelain -z`: a rename or copy is followed by its old path as a bare entry, which is no row of its own.
|
|
181
|
+
function changedFiles(root) {
|
|
182
|
+
const rows = git(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all'], { raw: true, strict: true, timeout: MOVE_LIMITS.gitMs }).split('\0');
|
|
183
|
+
const tracked = [];
|
|
184
|
+
const untracked = [];
|
|
185
|
+
for (let at = 0; at < rows.length; at += 1) {
|
|
186
|
+
const row = rows[at];
|
|
187
|
+
if (!row) continue;
|
|
188
|
+
(row.startsWith('??') ? untracked : tracked).push(row.slice(3));
|
|
189
|
+
if (/^[RC]/.test(row)) at += 1;
|
|
190
|
+
}
|
|
191
|
+
return { tracked, untracked };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// 🔴 UNKNOWN IS NOT CLEAN OR PUSHED. A slow `git status` used to answer empty, and that read as nothing to carry.
|
|
195
|
+
function isPushed(root, commit) {
|
|
196
|
+
const upstream = git(root, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']);
|
|
197
|
+
if (upstream && !git(root, ['rev-list', '--max-count=1', `${upstream}..${commit}`], { strict: true, timeout: MOVE_LIMITS.gitMs })) return true;
|
|
198
|
+
return git(root, ['ls-remote', 'origin', 'HEAD'], { timeout: MOVE_LIMITS.gitMs }).startsWith(commit);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function readingGit(work) {
|
|
202
|
+
try { return work(); }
|
|
203
|
+
catch (error) {
|
|
204
|
+
if (error?.message !== 'git_failed') throw error;
|
|
205
|
+
throw refusal('Estelle could not read this repository in time, and it will not guess that nothing changed.', 'Nothing was pushed. Run this again.');
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// What the box starts from. `pushed` work goes by commit, and changed files go through a snapshot branch.
|
|
210
|
+
// 🔴 A PUBLIC REPOSITORY CARRIES NOTHING FROM THIS MACHINE. Files sent to the box still reached the public remote: the box's own
|
|
211
|
+
// snapshot and its agent's saves both push what they find, and no rule typed at an agent can promise otherwise. So the work stays here,
|
|
212
|
+
// is named, and the handoff goes on from what origin already has. Unknown visibility is treated as public.
|
|
213
|
+
export async function gitState(root, session, scan = secretShaped, isOpen = async () => false) {
|
|
214
|
+
const { commit, branch, changed, pushed } = readingGit(() => {
|
|
215
|
+
const head = git(root, ['rev-parse', 'HEAD'], { strict: true, timeout: MOVE_LIMITS.gitMs });
|
|
216
|
+
const { tracked, untracked } = changedFiles(root);
|
|
217
|
+
return { commit: head, branch: git(root, ['branch', '--show-current']), changed: [...tracked, ...untracked], pushed: isPushed(root, head) };
|
|
218
|
+
});
|
|
219
|
+
if (!/^[a-f0-9]{40}$/.test(commit)) throw refusal('This repository has no commit to start from.', 'Commit something first.');
|
|
220
|
+
const { safe, skipped } = await sortForPush(root, changed, scan);
|
|
221
|
+
if (!safe.length && pushed) return { state: { branch, commit, dirty: false }, snapshot: null, carried: 0, skipped };
|
|
222
|
+
if (await isOpen() !== false) return readingGit(() => stayingHere(root, commit, branch, changed));
|
|
223
|
+
assertSafeHistory(root, scan);
|
|
224
|
+
const snapshot = await pushSnapshot(root, session, safe);
|
|
225
|
+
return { state: { branch, commit: snapshot.commit, dirty: true, snapshot_branch: snapshot.branch }, snapshot, carried: safe.length, skipped };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function stayingHere(root, head, branch, changed) {
|
|
229
|
+
const start = startingPoint(root, head, branch);
|
|
230
|
+
const commits = start.unpushed ? [plural(start.unpushed, 'unpushed commit')] : [];
|
|
231
|
+
return { state: start.commit ? { ...(start.branch ? { branch: start.branch } : {}), commit: start.commit, dirty: false } : {}, snapshot: null, carried: 0,
|
|
232
|
+
skipped: [...commits, ...changed], publicRepo: true };
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const plural = (count, word) => `${count} ${word}${count === 1 ? '' : 's'}`;
|
|
236
|
+
|
|
237
|
+
// A new session starts from a prompt, so it pushes nothing, and it says so before the machine starts: its task may be a question,
|
|
238
|
+
// and a conversation is no reason to publish work. It starts from what origin already has.
|
|
239
|
+
function cloudState(repo) {
|
|
240
|
+
if (!repo) return { state: {}, snapshot: null, startsFrom: '' };
|
|
241
|
+
return readingGit(() => {
|
|
242
|
+
const head = git(repo.root, ['rev-parse', 'HEAD'], { strict: true, timeout: MOVE_LIMITS.gitMs });
|
|
243
|
+
const branch = git(repo.root, ['branch', '--show-current']);
|
|
244
|
+
const { tracked, untracked } = changedFiles(repo.root);
|
|
245
|
+
const left = tracked.length + untracked.length;
|
|
246
|
+
const start = startingPoint(repo.root, head, branch);
|
|
247
|
+
const notes = [left ? `Your ${plural(left, 'uncommitted file')} aren't included.`.replace(/1 uncommitted file aren't/, "1 uncommitted file isn't") : '',
|
|
248
|
+
start.unpushed ? `Your ${plural(start.unpushed, 'unpushed commit')} aren't included.`.replace(/1 unpushed commit aren't/, "1 unpushed commit isn't") : ''].filter(Boolean);
|
|
249
|
+
const named = start.commit ? `${start.label} at ${start.commit.slice(0, 7)}` : 'the default branch';
|
|
250
|
+
return { state: start.commit ? { ...(start.branch ? { branch: start.branch } : {}), commit: start.commit, dirty: false } : {}, snapshot: null,
|
|
251
|
+
startsFrom: notes.length ? `Starts from ${named}. ${notes.join(' ')}` : '' };
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function startingPoint(root, head, branch) {
|
|
256
|
+
if (/^[a-f0-9]{40}$/.test(head) && isPushed(root, head)) return { commit: head, branch, label: branch || 'this commit', unpushed: 0 };
|
|
257
|
+
const upstream = git(root, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']);
|
|
258
|
+
if (upstream) {
|
|
259
|
+
const name = upstream.replace(/^origin\//, '');
|
|
260
|
+
const unpushed = Number(git(root, ['rev-list', '--count', `${upstream}..HEAD`], { strict: true, timeout: MOVE_LIMITS.gitMs }));
|
|
261
|
+
return { commit: git(root, ['rev-parse', upstream], { strict: true, timeout: MOVE_LIMITS.gitMs }), branch: name, label: name, unpushed };
|
|
262
|
+
}
|
|
263
|
+
const remote = git(root, ['ls-remote', 'origin', 'HEAD'], { timeout: MOVE_LIMITS.gitMs }).split(/\s+/)[0];
|
|
264
|
+
const known = /^[a-f0-9]{40}$/.test(remote) ? Number(git(root, ['rev-list', '--count', 'HEAD', '--not', '--remotes'], { timeout: MOVE_LIMITS.gitMs }) || 0) : 0;
|
|
265
|
+
return { commit: /^[a-f0-9]{40}$/.test(remote) ? remote : '', branch: '', label: 'the default branch', unpushed: known };
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// captureNativeTranscript takes a home and appends the host's folder, so a relocated config folder needs its parent.
|
|
269
|
+
const homeFor = (host, env) => (host === 'codex' && env.CODEX_HOME ? dirname(env.CODEX_HOME)
|
|
270
|
+
: host === 'claude-code' && env.CLAUDE_CONFIG_DIR ? dirname(env.CLAUDE_CONFIG_DIR) : undefined);
|
|
271
|
+
|
|
272
|
+
async function conversation(host, nativeSession, transcriptPath, home, env) {
|
|
273
|
+
if (!NATIVE_HOSTS.has(host)) return { unavailable: `${host} has no proven way to reopen a conversation in another machine` };
|
|
274
|
+
if (!UUID.test(nativeSession || '') || !transcriptPath) return { unavailable: 'this host did not name its conversation file' };
|
|
275
|
+
try {
|
|
276
|
+
const transcript = await captureNativeTranscript({ harness: host, sessionId: nativeSession, transcriptPath, home: home || homeFor(host, env) || homedir() });
|
|
277
|
+
return { native: { session_id: nativeSession, transcript, files: [] } };
|
|
278
|
+
} catch (error) {
|
|
279
|
+
const reasons = { native_artifact_bound: 'the conversation is over the 512 KiB bound', native_credential_field: 'the conversation holds a credential field' };
|
|
280
|
+
return { unavailable: reasons[error?.message] || 'the conversation file could not be read safely' };
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// One intent keeps one key until its outcome is known, so a rerun after a timeout cannot buy a second machine. The key is
|
|
285
|
+
// written before the request goes out: the request may reach the server and its answer may not reach us.
|
|
286
|
+
const intentPath = (stateDir, root, sessionId, mode, words) => join(stateDir, 'moves',
|
|
287
|
+
`${hash([root, sessionId, mode, String(words ?? '').trim()].join('\x1f'))}.json`);
|
|
288
|
+
|
|
289
|
+
async function readIntent(path, now) {
|
|
290
|
+
const held = await readJson(path, 4_000).catch(() => null);
|
|
291
|
+
return held?.key && now - Number(held.at || 0) < MOVE_LIMITS.pendingMs ? held : null;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function uncertain(sessionId, env, cause) {
|
|
295
|
+
const site = String(env.ESTELLE_SITE_URL || 'https://fatelabs.ca').replace(/\/$/, '');
|
|
296
|
+
const link = `${site}/dashboard/sessions${sessionId ? `?session=${encodeURIComponent(sessionId)}` : ''}`;
|
|
297
|
+
const error = refusal(`Estelle could not confirm whether this started (${cause}), so do not start it another way.`,
|
|
298
|
+
`Run this same command again: it only checks, and it will not start a second machine. Watch it here: ${link}`);
|
|
299
|
+
error.uncertain = true;
|
|
300
|
+
return error;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const causeOf = error => (error?.status ? `HTTP ${error.status}` : 'no answer from the server');
|
|
304
|
+
|
|
305
|
+
// A new session's key is its intent, so the same ask from the same place asks the server about the same machine: still running says
|
|
306
|
+
// so with its link, and over means a new one. A folder is part of the intent, so one prompt from two folders is two sessions.
|
|
307
|
+
const cloudKey = (repo, cwd, sessionId, ask, commit) => `plugin-${hash([repo?.name || cwd, sessionId, 'cloud', ask.harness, ask.prompt, commit].join('\x1f')).slice(0, 40)}`;
|
|
308
|
+
|
|
309
|
+
// One remote the box can clone. Any other host's `owner/name` is a different repository on GitHub, or none.
|
|
310
|
+
function refuseOtherHost(repo, env) {
|
|
311
|
+
if (!repo || env.ESTELLE_REPO) return;
|
|
312
|
+
const remote = git(repo.root, ['remote', 'get-url', 'origin']);
|
|
313
|
+
const host = /^(?:[a-z+]+:\/\/)?(?:[^@/]+@)?([^/:]+)[:/]/i.exec(remote)?.[1]?.toLowerCase();
|
|
314
|
+
if (host !== 'github.com') {
|
|
315
|
+
throw refusal(`Estelle can only start from GitHub, and this repository's origin is ${host || 'not one it can read'}, so nothing was started.`);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// One move. `say` receives each line a person reads, so a host that can stream shows the first line before the wait.
|
|
320
|
+
export async function runMove({ mode, words, env = process.env, cwd = process.cwd(), stateDir = stateDirectory(env), home,
|
|
321
|
+
request = hasServerAccess(env) ? apiClient({ env, timeoutMs: MOVE_LIMITS.requestMs, deadline: Date.now() + MOVE_LIMITS.requestMs }) : null,
|
|
322
|
+
say = () => {}, now = Date.now, scan = secretShaped, isPublic = isPublicRepo }) {
|
|
323
|
+
// ⚠️ A box's own plugin stops here. A caller that skips the plugin is bounded by the account's Silo cap and its credits, not by depth.
|
|
324
|
+
if (cloudExecutionIdentity(env)) throw refusal('This session is already running in the cloud, so nothing new was started.');
|
|
325
|
+
const repo = repository(cwd, env);
|
|
326
|
+
refuseOtherHost(repo, env);
|
|
327
|
+
if (!repo && mode === 'handoff') throw refusal('This folder is not a Git repository with an origin on GitHub.', 'Run this from your repository.');
|
|
328
|
+
const ask = parseWords(mode, words);
|
|
329
|
+
const current = repo ? await currentSession(stateDir, repo.root, env, home) : null;
|
|
330
|
+
if (mode === 'handoff' && !current?.sessionId) {
|
|
331
|
+
throw refusal('Estelle has not seen this session, so it does not know what to continue.', 'Check the plugin is enabled with `doctor`, send one message here, then run this again.');
|
|
332
|
+
}
|
|
333
|
+
const host = current?.host ? canonicalHost(current.host) : '';
|
|
334
|
+
const nativeSession = current?.sessionId || '';
|
|
335
|
+
const sessionId = nativeSession ? timelineIdentity(host, nativeSession, env) : '';
|
|
336
|
+
if (mode === 'handoff') say(MOVING);
|
|
337
|
+
const isOpen = () => isPublic(repo.name);
|
|
338
|
+
if (!request) return viaMcp({ mode, ask, repo, cwd, host, sessionId, nativeSession, scan, isOpen, say });
|
|
339
|
+
if (mode === 'cloud') return cloudViaKey({ ask, repo, cwd, host, sessionId, request, say, env });
|
|
340
|
+
const path = intentPath(stateDir, repo.root, sessionId, mode, words);
|
|
341
|
+
const held = await readIntent(path, now());
|
|
342
|
+
if (held) {
|
|
343
|
+
// An earlier run never learned how this ended. Ask first; a record means it began, and nothing launches over it.
|
|
344
|
+
let seen;
|
|
345
|
+
try { seen = await request('/sessions/move', { action: 'status', move_key: held.key, ...(mode === 'handoff' ? { session_id: sessionId } : {}) }); }
|
|
346
|
+
catch (error) { throw uncertain(sessionId, env, causeOf(error)); }
|
|
347
|
+
if (seen.found === true) return finish(seen, { path, snapshot: null, checkpoint: null });
|
|
348
|
+
}
|
|
349
|
+
const key = held?.key || randomUUID();
|
|
350
|
+
await writeJson(path, { key, at: now() });
|
|
351
|
+
const { state, snapshot, carried: went, skipped, publicRepo } = await gitState(repo.root, sessionId || key, scan, isOpen);
|
|
352
|
+
if (publicRepo) say(PUBLIC_LINE);
|
|
353
|
+
const carried = await conversation(host, nativeSession, current?.transcriptPath, home, env);
|
|
354
|
+
const saved = await saveCheckpoint(current, repo, stateDir, request);
|
|
355
|
+
const body = { mode, repo: repo.name, git: state, from_host: host || undefined, confirm: true, origin: 'plugin', move_key: key,
|
|
356
|
+
...(sessionId ? { session_id: sessionId } : {}), ...contextOf(mode, nativeSession, sessionId),
|
|
357
|
+
...(ask.harness ? { harness: ask.harness } : {}), ...whatWent(went, skipped),
|
|
358
|
+
...(ask.note ? { note: ask.note } : {}), ...(carried.native ? { native: carried.native } : {}),
|
|
359
|
+
...(carried.unavailable ? { native_unavailable: carried.unavailable } : {}) };
|
|
360
|
+
let answer;
|
|
361
|
+
try { answer = await request('/sessions/move', body); }
|
|
362
|
+
catch (error) {
|
|
363
|
+
// A 4xx means the server refused the ask and started nothing. Anything else may have landed on either side.
|
|
364
|
+
if (error?.status >= 400 && error?.status < 500) { await rm(path, { force: true }); throw error; }
|
|
365
|
+
throw uncertain(sessionId, env, causeOf(error));
|
|
366
|
+
}
|
|
367
|
+
return finish(answer, { path, snapshot, checkpoint: saved });
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
const PUBLIC_LINE = 'This repository is public or unreadable, so your changes stay on this machine and the handoff goes on without them.';
|
|
371
|
+
const whatWent = (went, skipped) => ({ ...(went ? { files_carried: went } : {}),
|
|
372
|
+
...(skipped?.length ? { left_behind: skipped.slice(0, MOVE_LIMITS.untrackedSent) } : {}),
|
|
373
|
+
...(skipped?.length > MOVE_LIMITS.untrackedSent ? { left_behind_more: skipped.length - MOVE_LIMITS.untrackedSent } : {}) });
|
|
374
|
+
|
|
375
|
+
async function cloudViaKey({ ask, repo, cwd, host, sessionId, request, say, env }) {
|
|
376
|
+
const { state, startsFrom } = cloudState(repo);
|
|
377
|
+
if (startsFrom) say(startsFrom);
|
|
378
|
+
const body = { mode: 'cloud', ...(repo ? { repo: repo.name } : {}), git: state, from_host: host || undefined, confirm: true, origin: 'plugin',
|
|
379
|
+
move_key: cloudKey(repo, cwd, sessionId, ask, state.commit), ...(ask.harness ? { harness: ask.harness } : {}), prompt: ask.prompt };
|
|
380
|
+
let answer;
|
|
381
|
+
try { answer = await request('/sessions/move', body); }
|
|
382
|
+
catch (error) {
|
|
383
|
+
if (error?.status >= 400 && error?.status < 500) throw error;
|
|
384
|
+
throw uncertain(sessionId, env, causeOf(error));
|
|
385
|
+
}
|
|
386
|
+
return finish(answer, { snapshot: null, checkpoint: null });
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// A host's hooks checkpoint under its own id, and a move names the timeline id, so the server is told both.
|
|
390
|
+
const contextOf = (mode, nativeSession, sessionId) => (mode === 'handoff' && nativeSession && nativeSession !== sessionId
|
|
391
|
+
? { context_session_id: nativeSession } : {});
|
|
392
|
+
|
|
393
|
+
// 🔴 THE USUAL PATH: Claude Code signs in to Estelle with OAuth, and that sign-in belongs to the host, so this process
|
|
394
|
+
// holds no key and cannot reach the server. It does the part only it can (the git state and the snapshot) and hands the
|
|
395
|
+
// model one MCP call. A tool call cannot carry a conversation file, and this process cannot save a checkpoint either, so
|
|
396
|
+
// the server's last message says what actually travelled.
|
|
397
|
+
// The key is derived, not stored: this process never learns the answer, and the same tree and words are the same intent.
|
|
398
|
+
async function viaMcp({ mode, ask, repo, cwd, host, sessionId, nativeSession, scan, isOpen, say }) {
|
|
399
|
+
const cloud = mode === 'cloud';
|
|
400
|
+
const { state, snapshot, carried, skipped, startsFrom, publicRepo } = cloud ? cloudState(repo) : await gitState(repo.root, sessionId || repo.name, scan, isOpen);
|
|
401
|
+
if (startsFrom) say(startsFrom);
|
|
402
|
+
if (publicRepo) say(PUBLIC_LINE);
|
|
403
|
+
const intent = cloud ? cloudKey(repo, cwd, sessionId, ask, state.commit)
|
|
404
|
+
: `plugin-${hash([repo.name, sessionId, mode, ask.harness, ask.note, state.commit].join('\x1f')).slice(0, 40)}`;
|
|
405
|
+
const args = { mode, ...(repo ? { repo: repo.name } : {}), move_key: intent, confirm: true, ...(state.commit ? { commit: state.commit } : {}),
|
|
406
|
+
...(state.branch ? { branch: state.branch } : {}), ...(state.snapshot_branch ? { snapshot_branch: state.snapshot_branch } : {}),
|
|
407
|
+
...(host ? { from_host: host } : {}), ...(sessionId && !cloud ? { session_id: sessionId } : {}), ...contextOf(mode, nativeSession, sessionId),
|
|
408
|
+
...(ask.harness ? { harness: ask.harness } : {}), ...whatWent(carried, skipped),
|
|
409
|
+
...(ask.prompt ? { prompt: ask.prompt } : {}), ...(ask.note ? { note: ask.note } : {}) };
|
|
410
|
+
return { answer: { moved: undefined }, snapshot, mcp: args, final: `ESTELLE_MCP_CALL\n${JSON.stringify(args)}` };
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// 🔴 THE COMMAND ENDS HERE, AT THE LINK. It used to poll until the work landed, so a host's 120 s shell timeout killed it holding a
|
|
414
|
+
// billing machine and no link. Status is a separate read, on the page. An outcome nobody knows keeps its key, so a rerun only asks.
|
|
415
|
+
async function finish(answer, { path, snapshot, checkpoint }) {
|
|
416
|
+
if (path && answer.moved !== null && answer.state !== 'unknown') await rm(path, { force: true });
|
|
417
|
+
return { answer, snapshot, checkpoint, final: answer.last_message || answer.message };
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
async function saveCheckpoint(current, repo, stateDir, request) {
|
|
421
|
+
if (!current?.sessionId || !current.transcriptPath) return { saved: false, reason: 'this host did not name its conversation file' };
|
|
422
|
+
try {
|
|
423
|
+
return await checkpointSession({ payload: { session_id: current.sessionId, transcript_path: current.transcriptPath,
|
|
424
|
+
hook_event_name: 'PreCompact', cwd: repo.root }, host: current.host, repo: repo.name, stateDir, request });
|
|
425
|
+
} catch { return { saved: false, reason: 'the checkpoint could not be saved' }; }
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// Every last line carries a link. The refusal that could not tell already holds its session's.
|
|
429
|
+
const sessionsLink = env => `${String(env.ESTELLE_SITE_URL || 'https://fatelabs.ca').replace(/\/$/, '')}/dashboard/sessions`;
|
|
430
|
+
export function messageOf(error, env = process.env) {
|
|
431
|
+
if (error?.message === 'move_refused') return error.uncertain ? `${error.reason} ${error.needed}`.trim() : `${error.reason} ${error.needed} ${sessionsLink(env)}`.replace(/\s+/g, ' ').trim();
|
|
432
|
+
return `Estelle could not start this (${error?.status ? `HTTP ${error.status}: ${error.message}` : 'network error'}). Nothing was confirmed as started. ${sessionsLink(env)}`;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// The CLI door: `move <handoff|cloud>` with the person's words on stdin, so no shell ever parses them.
|
|
436
|
+
export async function moveCommand(mode, input, { stdout = console.log, setExit = code => { process.exitCode = code; } } = {}) {
|
|
437
|
+
if (mode !== 'handoff' && mode !== 'cloud') { stdout('Use `move handoff` or `move cloud`.'); setExit(2); return; }
|
|
438
|
+
try {
|
|
439
|
+
const result = await runMove({ mode, words: input, say: stdout });
|
|
440
|
+
stdout(result.final);
|
|
441
|
+
if ((result.answer.moved === false && result.answer.already_running !== true) || result.answer.moved === null) setExit(1);
|
|
442
|
+
} catch (error) { stdout(messageOf(error)); setExit(1); }
|
|
443
|
+
}
|