introsio 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,169 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { setTimeout as delay } from 'node:timers/promises';
4
+ import { spawnSync } from 'node:child_process';
5
+ import { acquireLock } from '../lib/lock.mjs';
6
+
7
+ function git(cwd, args) {
8
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^GIT_/i.test(key)));
9
+ const result = spawnSync('git', ['--no-optional-locks', '--no-replace-objects', '-c', 'core.hooksPath=', '-c', 'core.fsmonitor=false', ...args], {
10
+ cwd, env: { ...env, GIT_TERMINAL_PROMPT: '0' }, encoding: 'utf8', windowsHide: true, timeout: 30000, maxBuffer: 8 * 1024 * 1024,
11
+ });
12
+ if (result.status !== 0) throw new Error('Cannot read workspace Git metadata.');
13
+ return result.stdout.trimEnd();
14
+ }
15
+
16
+ async function locked(file, work) {
17
+ const release = await acquireLock(file, { waitMs: 30000, staleMs: Infinity });
18
+ if (!release.acquired) throw new Error('Activity collector is busy.');
19
+ try { return await work(); } finally { release(); }
20
+ }
21
+
22
+ // Mirrored at the API boundary in backend-node/src/utils/agentActivity.js.
23
+ export function activityPath(value) {
24
+ if (typeof value !== 'string' || value.length > 240 || /[\x00-\x1f\x7f\\:]/.test(value) || value.startsWith('/')) return null;
25
+ const parts = value.split('/');
26
+ if (parts.some((part) => !part || part === '.' || part === '..')) return null;
27
+ if (parts.some((part) => /^(?:\.git|node_modules|dist|build|coverage|\.next|\.cache|vendor|\.aws|\.ssh)$/i.test(part))) return null;
28
+ if (parts.some((part) => /^(?:\.env(?:\..*)?|credentials(?:\..*)?|secrets?(?:\..*)?|id_rsa|id_ed25519)$/i.test(part)) || /\.(?:pem|p12|pfx|key|keystore)$/i.test(value)) return null;
29
+ if (/(?:gh[pousr]_|sk_live_|sk-proj-|AKIA)[a-zA-Z0-9_-]{8,}/.test(value) || /[\w.+-]+@[\w.-]+\.[a-z]{2,}/i.test(value)) return null;
30
+ return value;
31
+ }
32
+
33
+ export function parseStatus(porcelain, limit = 200) {
34
+ const entries = porcelain.split('\0');
35
+ const files = [];
36
+ let complete = true;
37
+ for (let i = 0; i < entries.length; i += 1) {
38
+ const row = entries[i];
39
+ if (!row) continue;
40
+ let file;
41
+ if (row.startsWith('? ')) file = { path: row.slice(2), index: '?', worktree: '?', kind: 'file' };
42
+ else if (/^[12u] /.test(row)) {
43
+ const fields = row.split(' ');
44
+ const type = fields[0];
45
+ const count = type === '1' ? 8 : type === '2' ? 9 : 10;
46
+ const modes = fields.slice(3, type === 'u' ? 7 : 6);
47
+ file = { path: fields.slice(count).join(' '), index: fields[1]?.[0], worktree: fields[1]?.[1],
48
+ kind: type === 'u' ? 'conflict' : fields[2]?.startsWith('S') ? 'submodule' : modes.includes('120000') ? 'symlink' : 'file' };
49
+ if (type === '2') file.previousPath = entries[++i];
50
+ } else { complete = false; continue; }
51
+ if (!activityPath(file.path) || (file.previousPath && !activityPath(file.previousPath))) continue;
52
+ if (files.length >= limit) { complete = false; continue; }
53
+ files.push(file);
54
+ }
55
+ return { files, complete };
56
+ }
57
+
58
+ export function collectSnapshot(directory) {
59
+ const { files, complete } = parseStatus(git(directory, ['status', '--porcelain=v2', '-z', '--untracked-files=all', '--ignore-submodules=none']));
60
+ return { head: git(directory, ['rev-parse', 'HEAD']), files, complete };
61
+ }
62
+
63
+ // Local metadata repairs missed watch events even while Git's XY status stays
64
+ // "modified" across several saves. These stat values never leave the runner.
65
+ export function snapshotFingerprint(directory, snapshot) {
66
+ const metadata = snapshot.files.map((file) => {
67
+ try {
68
+ const stat = fs.lstatSync(path.join(directory, file.path));
69
+ return [file.path, stat.mtimeMs, stat.size, stat.ino];
70
+ } catch { return [file.path, null]; }
71
+ });
72
+ return JSON.stringify([snapshot, metadata]);
73
+ }
74
+
75
+ export function activityClient({ baseUrl = 'https://api.introsio.app/api/v1', accessToken = () => process.env.INTROSIO_ACTIVITY_ACCESS_TOKEN, fetcher = fetch } = {}) {
76
+ const url = new URL(baseUrl);
77
+ if (url.username || url.password || url.search || url.hash || (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)))) throw new Error('Activity transport requires HTTPS or loopback HTTP.');
78
+ return async (method, route, body, token) => {
79
+ const access = await accessToken();
80
+ if (!access) throw new Error('Set INTROSIO_ACTIVITY_ACCESS_TOKEN outside model context to enable activity reporting.');
81
+ const controller = new AbortController();
82
+ const timer = setTimeout(() => controller.abort(), 10000);
83
+ try {
84
+ const response = await fetcher(`${baseUrl.replace(/\/$/, '')}/agent-activity${route}`, { method, redirect: 'error', signal: controller.signal,
85
+ headers: { Authorization: `Bearer ${access}`, 'Content-Type': 'application/json', ...(token ? { 'X-Agent-Session': token } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) });
86
+ if (!response.ok) throw Object.assign(new Error(`Activity request refused (${response.status}).`), { status: response.status });
87
+ return (await response.json()).data;
88
+ } finally { clearTimeout(timer); }
89
+ };
90
+ }
91
+
92
+ // One collector owns a workspace's sequence. Pending observations are journaled
93
+ // before sending, so response loss and restart resend the exact same payload.
94
+ export async function watchActivity(root, attemptId, { client, provider = 'manual', headless = false, signal, intervalMs = 15000, once = false, newSession = false, onError = () => {}, workspaceStore } = {}) {
95
+ if (typeof attemptId !== 'string' || !/^[a-f0-9-]{36}$/.test(attemptId)) throw new Error('Invalid attempt id.');
96
+ if (signal?.aborted) return { cancelled: true };
97
+ if (!workspaceStore || typeof client !== 'function') throw new Error('An authenticated activity client is required.');
98
+ return locked(path.join(root, `activity-${attemptId}`), async () => {
99
+ const state = await workspaceStore.read();
100
+ const workspace = state.workspaces.find((row) => row.attemptId === attemptId && row.state !== 'removed');
101
+ if (!workspace) throw new Error('Unknown active workspace.');
102
+ await workspaceStore.verify();
103
+ const prefix = `/projects/${encodeURIComponent(workspace.projectId)}/sessions`;
104
+ const update = (work) => workspaceStore.update(work);
105
+ let telemetry = workspace.telemetry;
106
+ if (newSession && telemetry) {
107
+ const retired = { sessionId: telemetry.sessionId, sequence: telemetry.sequence, pending: telemetry.pending, retiredAt: new Date().toISOString() };
108
+ await update((row) => { row.telemetryHistory = [...(row.telemetryHistory ?? []), retired].slice(-5); row.telemetry = null; });
109
+ telemetry = null;
110
+ }
111
+ if (!telemetry) {
112
+ const session = await client('POST', prefix, { runnerId: state.runnerId, attemptId, workspaceId: path.basename(workspace.directory), taskId: workspace.taskId,
113
+ provider, capabilities: { watch: true, rescan: true, headless } });
114
+ telemetry = { sessionId: session.sessionId, token: session.token, sequence: 0, pending: null };
115
+ await update((row) => { row.telemetry = telemetry; });
116
+ }
117
+ const route = `${prefix}/${encodeURIComponent(telemetry.sessionId)}`;
118
+ let changed = true;
119
+ let retryDelay = 500;
120
+ let watcher;
121
+ try {
122
+ try {
123
+ watcher = fs.watch(workspace.directory, { recursive: true }, (_event, filename) => {
124
+ if (!filename || activityPath(String(filename).split(path.sep).join('/'))) changed = true;
125
+ });
126
+ watcher.on('error', () => { changed = true; });
127
+ } catch { /* Periodic scans cover platforms without recursive watches. */ }
128
+ let previous = null;
129
+ let lastScan = 0;
130
+ let lastHeartbeat = 0;
131
+ do {
132
+ try {
133
+ if (!telemetry.pending && (changed || Date.now() - lastScan >= intervalMs || once)) {
134
+ await workspaceStore.verify();
135
+ const snapshot = collectSnapshot(workspace.directory);
136
+ const signature = snapshotFingerprint(workspace.directory, snapshot);
137
+ const observedEvent = changed && snapshot.files.length > 0;
138
+ changed = false;
139
+ lastScan = Date.now();
140
+ if (signature !== previous || observedEvent) {
141
+ telemetry.pending = { sequence: telemetry.sequence + 1, ...snapshot };
142
+ await update((row) => { row.telemetry = telemetry; });
143
+ previous = signature;
144
+ }
145
+ }
146
+ if (telemetry.pending) {
147
+ const reply = await client('POST', `${route}/observations`, telemetry.pending, telemetry.token);
148
+ telemetry.sequence = reply.sequence;
149
+ telemetry.pending = null;
150
+ if (reply.refresh) previous = null;
151
+ await update((row) => { row.telemetry = telemetry; });
152
+ }
153
+ if (Date.now() - lastHeartbeat >= intervalMs) {
154
+ const reply = await client('POST', `${route}/heartbeat`, null, telemetry.token);
155
+ if (!reply.active) return { ended: true };
156
+ lastHeartbeat = Date.now();
157
+ }
158
+ retryDelay = 500;
159
+ } catch (error) {
160
+ onError(error);
161
+ if (once || [400, 401, 403, 404, 409].includes(error.status)) throw error;
162
+ retryDelay = Math.min(30000, retryDelay * 2);
163
+ }
164
+ if (!once) await delay(retryDelay + Math.floor(Math.random() * retryDelay / 4), undefined, { signal }).catch((error) => { if (error.name !== 'AbortError') throw error; });
165
+ } while (!once && !signal?.aborted);
166
+ return { sessionId: telemetry.sessionId, sequence: telemetry.sequence };
167
+ } finally { watcher?.close(); }
168
+ });
169
+ }
@@ -0,0 +1,68 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { acquireLock } from '../lib/lock.mjs';
6
+ import { writeJson } from '../lib/jsonFile.mjs';
7
+ import { introsioDir } from '../lib/paths.mjs';
8
+
9
+ const VERSION = 1;
10
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
11
+ const runnerDir = (env) => path.join(introsioDir(env), 'runner');
12
+ const registryFile = (env) => path.join(runnerDir(env), 'registry.json');
13
+
14
+ function privateStat(target, isExpectedType) {
15
+ const stat = fs.lstatSync(target, { throwIfNoEntry: false });
16
+ if (!stat) return null;
17
+ if (!isExpectedType(stat) || (process.platform !== 'win32' && (stat.mode & 0o077) !== 0)) {
18
+ throw new Error(`Runner state requires a private local file or directory: ${target}`);
19
+ }
20
+ return stat;
21
+ }
22
+
23
+ /** Locally persisted runner identity. Unreadable or unknown state is left for recovery. */
24
+ export function readRunner(env = process.env) {
25
+ if (!privateStat(runnerDir(env), (stat) => stat.isDirectory())) return null;
26
+ const file = registryFile(env);
27
+ if (!privateStat(file, (stat) => stat.isFile())) return null;
28
+ let stored;
29
+ try {
30
+ stored = JSON.parse(fs.readFileSync(file, 'utf8'));
31
+ } catch (error) {
32
+ throw new Error('Runner registry could not be read. Restore it from a valid backup before initializing again.', { cause: error });
33
+ }
34
+ const { version, runnerId, hostname, platform, arch, registeredAt } = stored ?? {};
35
+ if (version !== VERSION || typeof runnerId !== 'string' || !UUID.test(runnerId)
36
+ || ![hostname, platform, arch, registeredAt].every((value) => typeof value === 'string' && value.length > 0)
37
+ || !Number.isFinite(Date.parse(registeredAt))) {
38
+ throw new Error('Runner registry is invalid or uses an unsupported version.');
39
+ }
40
+ return { version, runnerId, hostname, platform, arch, registeredAt };
41
+ }
42
+
43
+ /** Concurrent initialization always returns the identity written by the lock holder. */
44
+ export async function registerRunner(env = process.env) {
45
+ fs.mkdirSync(runnerDir(env), { recursive: true, mode: 0o700 });
46
+ const existing = readRunner(env);
47
+ if (existing) return existing;
48
+ const file = registryFile(env);
49
+ // Keep a live holder authoritative and recover only an abandoned lock.
50
+ const release = await acquireLock(file, { staleMs: Infinity });
51
+ if (!release.acquired) throw new Error('Runner registry is busy. Try initialization again.');
52
+ try {
53
+ const registered = readRunner(env);
54
+ if (registered) return registered;
55
+ const runner = {
56
+ version: VERSION,
57
+ runnerId: randomUUID(),
58
+ hostname: os.hostname(),
59
+ platform: process.platform,
60
+ arch: process.arch,
61
+ registeredAt: new Date().toISOString(),
62
+ };
63
+ writeJson(file, runner, { mode: 0o600, durable: true });
64
+ return runner;
65
+ } finally {
66
+ release();
67
+ }
68
+ }
@@ -0,0 +1,58 @@
1
+ import path from 'node:path';
2
+ import { listJournals, workspacePaths, readJournal, saveJournal } from './workspaceJournal.mjs';
3
+ import { inspectWorkspace } from './workspaceManager.mjs';
4
+ import { registerRunner } from './agentRegistry.mjs';
5
+ import { acquireLock } from '../lib/lock.mjs';
6
+ import { activityClient, watchActivity } from './activityCollector.mjs';
7
+
8
+ // Activity observes an already provisioned attempt. It grants no execution authority.
9
+ export async function managedActivityStore(attemptId, env = process.env) {
10
+ const record = listJournals(env).find(row => row.attemptId === attemptId);
11
+ if (!record || record.state !== 'ready') throw new Error('Unknown ready workspace attempt.');
12
+ const paths = workspacePaths(record, env);
13
+ const runner = await registerRunner(env);
14
+ const verify = () => {
15
+ const observed = inspectWorkspace(record, env);
16
+ if (observed.state !== 'ready' || !observed.exists) throw new Error('Workspace identity changed. Preserve it for recovery.');
17
+ };
18
+ const workspaceStore = {
19
+ verify,
20
+ read() {
21
+ verify();
22
+ return { runnerId: runner.runnerId, repositories: [], workspaces: [{ ...readJournal(paths.file), directory: paths.checkout }] };
23
+ },
24
+ async update(work) {
25
+ const release = await acquireLock(path.join(paths.dir, 'journal'), { staleMs: Infinity, waitMs: 30000 });
26
+ if (!release.acquired) throw new Error('Workspace journal is busy.');
27
+ try {
28
+ verify();
29
+ const latest = readJournal(paths.file);
30
+ work(latest);
31
+ saveJournal(paths.file, latest);
32
+ } finally { release(); }
33
+ },
34
+ };
35
+ return { workspaceStore, paths };
36
+ }
37
+
38
+ export async function watchManagedActivity(attemptId, flags = {}, env = process.env) {
39
+ const { workspaceStore, paths } = await managedActivityStore(attemptId, env);
40
+ const controller = new AbortController();
41
+ const stop = () => controller.abort();
42
+ process.once('SIGINT', stop);
43
+ process.once('SIGTERM', stop);
44
+ try {
45
+ return await watchActivity(paths.dir, attemptId, {
46
+ workspaceStore,
47
+ client: activityClient({ baseUrl: flags.api }),
48
+ provider: flags.provider ?? 'manual',
49
+ signal: controller.signal,
50
+ once: Boolean(flags.once),
51
+ newSession: Boolean(flags['new-session']),
52
+ onError: error => process.stderr.write(`${error.message}\n`),
53
+ });
54
+ } finally {
55
+ process.off('SIGINT', stop);
56
+ process.off('SIGTERM', stop);
57
+ }
58
+ }
@@ -0,0 +1,42 @@
1
+ // Never store PIDs or credentials. An unresolved launch record blocks automatic
2
+ // relaunch after a crash, even if the operating system reused the original PID.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { writeJson } from '../lib/jsonFile.mjs';
7
+ import { workspacePaths } from './workspaceJournal.mjs';
8
+
9
+ const STATES=new Set(['launching','exited','failed','launch-failed','cancelled','timed-out','authority-lost','termination-unconfirmed']);
10
+ const UUID=/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;
11
+ function fileFor(identity,env) {
12
+ const paths=workspacePaths(identity,env);
13
+ return paths?path.join(paths.dir,'process.json'):null;
14
+ }
15
+ export function readProcessRecord(identity,env=process.env) {
16
+ const file=fileFor(identity,env);
17
+ if(!file)return null;
18
+ const stat=fs.lstatSync(file,{throwIfNoEntry:false});
19
+ if(!stat)return null;
20
+ if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1||
21
+ (process.platform!=='win32'&&(stat.mode&0o077)))throw new Error('Unsafe process journal.');
22
+ let row;
23
+ try {row=JSON.parse(fs.readFileSync(file,'utf8'));}catch{throw new Error('Corrupt process journal; inspect manually.');}
24
+ if(row?.version!==1||!UUID.test(row.runId??'')||!STATES.has(row.state)||
25
+ !Number.isFinite(Date.parse(row.startedAt)))throw new Error('Invalid process journal.');
26
+ return row;
27
+ }
28
+ export function unresolvedProcess(row){return row?.state==='launching'||row?.state==='termination-unconfirmed';}
29
+ export function beginProcessRecord(identity,env=process.env) {
30
+ if(unresolvedProcess(readProcessRecord(identity,env)))throw new Error('Previous process termination is unverified; inspect manually before relaunch.');
31
+ const file=fileFor(identity,env);
32
+ if(!file)throw new Error('Workspace journal missing.');
33
+ const record={version:1,runId:randomUUID(),state:'launching',startedAt:new Date().toISOString()};
34
+ writeJson(file,record,{mode:0o600,durable:true});
35
+ return record;
36
+ }
37
+ export function finishProcessRecord(identity,record,result,env=process.env) {
38
+ const current=readProcessRecord(identity,env);
39
+ if(current?.runId!==record.runId||current.state!=='launching'||!STATES.has(result.status)||result.status==='launching')
40
+ throw new Error('Process journal changed; inspect manually.');
41
+ writeJson(fileFor(identity,env),{...record,state:result.status,finishedAt:new Date().toISOString(),code:Number.isInteger(result.code)?result.code:null},{mode:0o600,durable:true});
42
+ }
@@ -0,0 +1,118 @@
1
+ // Local, explicitly approved GitHub repository links. No network or checkout writes.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { spawnSync } from 'node:child_process';
5
+ import { introsioDir, canonicalPath } from '../lib/paths.mjs';
6
+ import { acquireLock } from '../lib/lock.mjs';
7
+ import { writeJson } from '../lib/jsonFile.mjs';
8
+ import { registerRunner } from './agentRegistry.mjs';
9
+
10
+ const ID = /^[a-f0-9]{24}$/;
11
+ const REPO = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9_.-]{1,100}$/;
12
+ const VERSION = 1;
13
+ const fail = (message) => { throw new Error(message); };
14
+ function projectId(value) {
15
+ if (typeof value !== 'string' || !ID.test(value)) fail('A lowercase 24-character project ID is required.');
16
+ return value;
17
+ }
18
+ function githubName(value) {
19
+ if (typeof value !== 'string' || !REPO.test(value) || ['.', '..'].includes(value.split('/')[1])) fail('Use the explicitly approved GitHub repository owner/name.');
20
+ return value.toLowerCase();
21
+ }
22
+ export function githubRemoteIdentity(url) {
23
+ if (typeof url !== 'string') fail('Unsupported GitHub remote.');
24
+ const match = /^(?:https:\/\/github\.com\/|ssh:\/\/git@github\.com\/|git@github\.com:)([A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9_.-]{1,104})$/i.exec(url);
25
+ if (!match) fail('Origin must use a credential-free github.com HTTPS or SSH URL.');
26
+ return githubName(match[1].replace(/\.git$/i, ''));
27
+ }
28
+ function git(cwd, args) {
29
+ // Do not let inherited Git overrides silently redirect operations to a
30
+ // different repository. No shell, no network, no credential prompt.
31
+ const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => !/^GIT_/i.test(name)));
32
+ const r = spawnSync('git', ['--no-optional-locks', ...args], {
33
+ cwd, env: { ...env, GIT_TERMINAL_PROMPT: '0' }, shell: false,
34
+ encoding: 'utf8', windowsHide: true, timeout: 15000, maxBuffer: 1024 * 1024,
35
+ });
36
+ if (r.error || r.status !== 0) fail('Git preflight failed. Check the local checkout and Git installation.');
37
+ return r.stdout.trimEnd();
38
+ }
39
+ const canonical = p => fs.realpathSync.native(p);
40
+ function privateDirectory(dir, create) {
41
+ if (create) fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
42
+ const stat = fs.lstatSync(dir, { throwIfNoEntry: false });
43
+ if (!stat) return false;
44
+ if (!stat.isDirectory() || stat.isSymbolicLink() || (process.platform !== 'win32' && (stat.mode & 0o077))) fail('Runner state directory is not private or is redirected.');
45
+ // Windows junctions and symbolic links are rejected by lstat; canonical
46
+ // comparison also refuses a directory redirected away from its parent.
47
+ if (canonical(dir) !== path.join(canonical(path.dirname(dir)), path.basename(dir))) fail('Runner state directory is redirected.');
48
+ return true;
49
+ }
50
+ function linkFile(id, env, create = false) {
51
+ projectId(id);
52
+ const home = path.resolve(introsioDir(env));
53
+ const runner = path.join(home, 'runner');
54
+ const links = path.join(runner, 'projects');
55
+ if (!privateDirectory(runner, create) || !privateDirectory(links, create)) return null;
56
+ return path.join(links, id + '.json');
57
+ }
58
+ export function inspectRepository(root, repository) {
59
+ const expected = githubName(repository);
60
+ if (typeof root !== 'string' || !root.trim()) fail('An explicit local repository root is required.');
61
+ const localRoot = canonical(path.resolve(root));
62
+ if (!fs.statSync(localRoot).isDirectory()) fail('Repository root must be a directory.');
63
+ const version = /^git version (\d+)\.(\d+)/.exec(git(localRoot, ['--version']));
64
+ if (!version || Number(version[1]) < 2 || (Number(version[1]) === 2 && Number(version[2]) < 31)) fail('Git 2.31 or newer is required.');
65
+ if (git(localRoot, ['rev-parse', '--is-inside-work-tree']) !== 'true' ||
66
+ canonical(git(localRoot, ['rev-parse', '--show-toplevel'])) !== localRoot) fail('Select the repository root, not a subdirectory.');
67
+ const commonDir = canonical(git(localRoot, ['rev-parse', '--path-format=absolute', '--git-common-dir']));
68
+ fs.accessSync(localRoot, fs.constants.W_OK);
69
+ fs.accessSync(commonDir, fs.constants.W_OK);
70
+ const fetch = git(localRoot, ['remote', 'get-url', '--all', 'origin']).split(/\r?\n/);
71
+ const push = git(localRoot, ['remote', 'get-url', '--push', '--all', 'origin']).split(/\r?\n/);
72
+ if (fetch.length !== 1 || push.length !== 1 ||
73
+ githubRemoteIdentity(fetch[0]) !== expected || githubRemoteIdentity(push[0]) !== expected) fail('Origin does not match the explicitly approved repository.');
74
+ return { repository: expected, localRoot, commonDir };
75
+ }
76
+ export function readProjectLink(id, env = process.env) {
77
+ const file = linkFile(id, env);
78
+ if (!file) return null;
79
+ const stat = fs.lstatSync(file, { throwIfNoEntry: false });
80
+ if (!stat) return null;
81
+ if (!stat.isFile() || stat.isSymbolicLink() || (process.platform !== 'win32' && (stat.mode & 0o077))) fail('Project link is not a private regular file.');
82
+ let record;
83
+ try { record = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { fail('Project link is corrupt; preserve it for recovery.'); }
84
+ if (record?.version !== VERSION || record.projectId !== id || !REPO.test(record.repository ?? '') ||
85
+ ![record.localRoot, record.commonDir].every(v => typeof v === 'string' && path.isAbsolute(v)) ||
86
+ !Number.isFinite(Date.parse(record.linkedAt))) fail('Project link is invalid or uses an unsupported version.');
87
+ const { version, projectId: pid, repository, localRoot, commonDir, linkedAt } = record;
88
+ return { version, projectId: pid, repository, localRoot, commonDir, linkedAt };
89
+ }
90
+ export async function linkProject({ id, root, repository }, env = process.env) {
91
+ projectId(id);
92
+ const repo = inspectRepository(root, repository);
93
+ const state = canonicalPath(introsioDir(env));
94
+ const inside = (p,c) => { const rel=path.relative(p,c); return rel==='' || (!path.isAbsolute(rel)&&rel!=='..'&&!rel.startsWith('..'+path.sep)); };
95
+ if(inside(repo.localRoot,state)||inside(repo.commonDir,state)) fail('Runner state must be outside the human checkout and Git metadata.');
96
+ await registerRunner(env);
97
+ const file = linkFile(id, env, true);
98
+ const release = await acquireLock(file, { staleMs: Infinity });
99
+ if (!release.acquired) fail('Project link is busy; retry.');
100
+ try {
101
+ const existing = readProjectLink(id, env);
102
+ if (existing) {
103
+ if (Object.keys(repo).every(key => existing[key] === repo[key])) return existing;
104
+ fail('Project already has a different local link. Explicit recovery or relinking is required.');
105
+ }
106
+ const record = { version: VERSION, projectId: id, ...repo, linkedAt: new Date().toISOString() };
107
+ writeJson(file, record, { mode: 0o600, durable: true });
108
+ return record;
109
+ } finally { release(); }
110
+ }
111
+ /** Recheck on every future provisioning action; a link is not remote authorization. */
112
+ export function verifyProjectLink(id, env = process.env) {
113
+ const record = readProjectLink(id, env);
114
+ if (!record) fail('Project has not been explicitly linked.');
115
+ const actual = inspectRepository(record.localRoot, record.repository);
116
+ if (actual.localRoot !== record.localRoot || actual.commonDir !== record.commonDir) fail('Local repository identity changed; recover the link first.');
117
+ return record;
118
+ }
@@ -0,0 +1,41 @@
1
+ // Conservative provider capabilities. Discovery never launches executables or reads credentials.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { inspectWorkspace, provisionWorkspace } from '../workspaceManager.mjs';
5
+
6
+ const PROVIDERS = Object.freeze({
7
+ codex: 'codex', claude: 'claude', gemini: 'gemini', cursor: 'cursor',
8
+ opencode: 'opencode', vscode: 'code', windsurf: 'windsurf',
9
+ });
10
+ function installed(command, env) {
11
+ const names = process.platform === 'win32' ? [command+'.exe',command+'.cmd',command+'.bat'] : [command];
12
+ return (env.PATH ?? env.Path ?? '').split(path.delimiter).filter(dir=>path.isAbsolute(dir)).some(dir=>names.some(name=>{
13
+ try {
14
+ const file=path.join(dir,name);
15
+ if(!fs.statSync(file).isFile()) return false;
16
+ fs.accessSync(file,process.platform==='win32'?fs.constants.F_OK:fs.constants.X_OK);
17
+ return true;
18
+ } catch { return false; }
19
+ }));
20
+ }
21
+ export function discoverProviders(env=process.env) {
22
+ return Object.entries(PROVIDERS).map(([id,command])=>({
23
+ id, installed:installed(command,env), mode:'manual',
24
+ capabilities:{ launch:false, checkpoint:true, stop:false, resume:true, health:true },
25
+ }));
26
+ }
27
+ export function manualProvider(id) {
28
+ if(!Object.hasOwn(PROVIDERS,id)) throw new Error('Unknown coding-agent provider.');
29
+ return Object.freeze({
30
+ id,
31
+ discover:env=>discoverProviders(env).find(p=>p.id===id),
32
+ async launch(packet,options) {
33
+ const workspace=await provisionWorkspace(packet,options);
34
+ return { mode:'manual', provider:id, workspace, instructions:'Open the verified workspace in your agent, connect Introsio, and use the authorized execution attempt. Automatic launch is not supported by this adapter.' };
35
+ },
36
+ checkpoint:(identity,env)=>inspectWorkspace(identity,env),
37
+ stop:()=>({mode:'manual',stopped:false,instructions:'Stop the agent in its own application. Preserve the workspace and report its checkpoint before releasing the lease.'}),
38
+ resume(packet,options){return this.launch(packet,options);},
39
+ health:(identity,env)=>inspectWorkspace(identity,env),
40
+ });
41
+ }
@@ -0,0 +1,61 @@
1
+ // Orchestration boundary. Only trusted host code may supply an executor.
2
+ // Never claim from a server-provided command or auto-complete based on exit 0.
3
+ import { provisionWorkspace, inspectWorkspace } from './workspaceManager.mjs';
4
+ import { attemptIdentity, workspacePaths, privateDir } from './workspaceJournal.mjs';
5
+ import { readProcessRecord, unresolvedProcess } from './processJournal.mjs';
6
+ import { acquireLock } from '../lib/lock.mjs';
7
+ import { writeJson } from '../lib/jsonFile.mjs';
8
+ import { randomUUID } from 'node:crypto';
9
+ import { captureWorkspaceArtifact } from './workspaceArtifacts.mjs';
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+
13
+ export async function checkpointWorkspace(identity, env=process.env) {
14
+ const id=attemptIdentity(identity);
15
+ const state=inspectWorkspace(id,env);
16
+ if(state.state!=='ready'||!state.exists)throw new Error('Cannot checkpoint an unverified workspace.');
17
+ const paths=workspacePaths(id,env);
18
+ const dir=path.join(paths.dir,'checkpoints');
19
+ privateDir(dir,true);
20
+ const checkpoint={version:1,...id,head:state.head,dirty:state.dirty,unpushed:state.unpushed,
21
+ createdAt:new Date().toISOString(),checkpointId:randomUUID()};
22
+ // Unique append-only metadata; not a backup of the actual working files.
23
+ writeJson(path.join(dir,checkpoint.checkpointId+'.json'),checkpoint,{mode:0o600,durable:true});
24
+ return checkpoint;
25
+ }
26
+
27
+ export async function runWorkerOnce({session,projectId,env=process.env,executor,signal,fetchCommit,claimOptions}={}) {
28
+ if(typeof executor!=='function'||typeof session?.claim!=='function'||session.projectId!==projectId)
29
+ throw new Error('A trusted executor and project-scoped runner session are required.');
30
+ if(signal?.aborted)return {status:'cancelled'};
31
+ const claim=await session.claim(claimOptions);
32
+ if(!claim.claimed)return {status:'idle',reason:claim.reason};
33
+ const id=attemptIdentity(claim.identity);
34
+ const authorizeAttempt=identity=>session.authorizeAttempt(identity);
35
+ const options={env,authorizeAttempt,fetchCommit};
36
+ const workspace=await provisionWorkspace(id,options);
37
+ const paths=workspacePaths(id,env);
38
+ const release=await acquireLock(path.join(paths.dir,'controller'),{staleMs:Infinity,waitMs:1000});
39
+ if(!release.acquired)throw new Error('Workspace controller busy.');
40
+ try{
41
+ if(unresolvedProcess(readProcessRecord(id,env)))throw new Error('Previous process termination requires review.');
42
+ await authorizeAttempt(id);
43
+ const captureArtifact = artifact => captureWorkspaceArtifact({
44
+ inputArtifactIds:claim.dependencySnapshot?.inputs.map(input=>input.artifactId)??[],...artifact,identity:id,session,env });
45
+ let completed=false;
46
+ const completeTask=async result=>{const receipt=await session.complete(result);completed=true;return receipt;};
47
+ const result=signal?.aborted?{status:'cancelled'}:await executor({
48
+ identity:id,workspace,task:claim.task,inputs:claim.inputs??[],signal,options,captureArtifact,completeTask,
49
+ });
50
+ // A provider may be unable to stop. Do not relinquish its authority
51
+ // automatically and never assume an exit code proves task correctness.
52
+ const checkpoint=await checkpointWorkspace(id,env);
53
+ if(unresolvedProcess(readProcessRecord(id,env))||result?.status==='termination-unconfirmed')
54
+ return {status:'review-required',checkpoint};
55
+ if(completed)return {status:'completed',checkpoint};
56
+ const note='Runner stopped; local work retained. Review checkpoint '+checkpoint.checkpointId+' before resuming.';
57
+ try{await authorizeAttempt(id);await session.pause({note});}
58
+ catch{return {status:'checkpoint-retained',checkpoint};}
59
+ return {status:'paused-for-review',checkpoint,processStatus:typeof result?.status==='string'?result.status:'unknown'};
60
+ }finally{release();}
61
+ }
@@ -0,0 +1,62 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ import { runWorkerOnce } from './runnerController.mjs';
3
+
4
+ const AUTH_ERRORS = new Set(['RUNNER_UNAUTHENTICATED', 'WORKER_SESSION_EXPIRED', 'WORKER_SCOPE_MISMATCH']);
5
+
6
+ /** The host waits and retries. The executor runs only after the server grants an exact attempt. */
7
+ export async function runWorkerLoop({ session, projectId, capabilities, executor, signal, env = process.env,
8
+ fetchCommit, maxIdleMs = 300000, maxRetries = 8, resumeTaskId,
9
+ runOnce = runWorkerOnce, sleep = delay, random = Math.random, onState = () => {} } = {}) {
10
+ if (!session || session.projectId !== projectId || typeof session.wait !== 'function' || typeof executor !== 'function' ||
11
+ !Number.isSafeInteger(maxIdleMs) || maxIdleMs < 1 || maxIdleMs > 3600000 ||
12
+ !Number.isSafeInteger(maxRetries) || maxRetries < 0 || maxRetries > 20) throw new Error('Invalid trusted runner loop configuration.');
13
+ if (!capabilities?.launch || (resumeTaskId && !capabilities.resume)) {
14
+ const state = { status: 'manual_action_required', message: 'Start or resume this agent in its application and use the verified workspace.' };
15
+ await onState(state);
16
+ return state;
17
+ }
18
+ let cursor = 0;
19
+ let failures = 0;
20
+ let idleSince = Date.now();
21
+ let resume = resumeTaskId;
22
+ for (;;) {
23
+ if (signal?.aborted) return { status: 'cancelled', cursor };
24
+ if (Date.now() - idleSince >= maxIdleMs) return { status: 'idle_timeout', cursor };
25
+ let claiming = false;
26
+ try {
27
+ await onState({ status: 'idle', cursor });
28
+ if (signal?.aborted) return { status: 'cancelled', cursor };
29
+ const wake = resume ? { reason: 'ready', cursor } : await session.wait(cursor, {
30
+ signal, timeoutSeconds: Math.min(20, Math.max(1, Math.ceil((maxIdleMs - (Date.now() - idleSince)) / 1000))),
31
+ });
32
+ cursor = Math.max(cursor, wake.cursor);
33
+ failures = 0;
34
+ if (signal?.aborted || wake.reason === 'cancelled') return { status: 'cancelled', cursor };
35
+ if (wake.reason === 'done') return { status: 'done', cursor };
36
+ if (wake.actionRequired || ['manual_action_required', 'busy'].includes(wake.reason)) return { status: wake.reason, cursor };
37
+ if (wake.reason !== 'ready') continue;
38
+ await onState({ status: 'claiming', cursor });
39
+ claiming = true;
40
+ const result = await runOnce({ session, projectId, executor, signal, env, fetchCommit,
41
+ ...(resume ? { claimOptions: { taskId: resume, resume: true } } : {}) });
42
+ resume = null;
43
+ claiming = false;
44
+ if (result.status === 'completed') { idleSince = Date.now(); await onState(result); continue; }
45
+ if (result.status !== 'idle') { await onState(result); return result; }
46
+ await sleep(250 + Math.floor(random() * 500), undefined, { signal });
47
+ } catch (error) {
48
+ if (signal?.aborted) return { status: 'cancelled', cursor };
49
+ if (AUTH_ERRORS.has(error.code)) return { status: 'auth', cursor };
50
+ if (claiming) return { status: 'review_required', cursor, reason: error.code ?? 'UNRESOLVED_ATTEMPT' };
51
+ if (['DEPENDENCY_REVALIDATION_REQUIRED', 'STALE_ATTEMPT', 'INTEGRATION_UNAVAILABLE'].includes(error.code)) {
52
+ return { status: 'review_required', cursor, reason: error.code };
53
+ }
54
+ failures++;
55
+ if (failures > maxRetries) return { status: 'offline', cursor, reason: error.code ?? 'RUNNER_UNAVAILABLE' };
56
+ const retryMs = Math.min(30000, 500 * 2 ** (failures - 1));
57
+ await onState({ status: 'retrying', cursor, attempt: failures });
58
+ try { await sleep(retryMs * (0.5 + random() * 0.5), undefined, { signal }); }
59
+ catch { if (signal?.aborted) return { status: 'cancelled', cursor }; throw error; }
60
+ }
61
+ }
62
+ }