introsio 0.0.0-stage → 0.3.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.
- package/CHANGELOG.md +62 -0
- package/LICENSE +21 -0
- package/README.md +291 -3
- package/agents/claude.mjs +80 -0
- package/agents/codex.mjs +67 -0
- package/agents/common.mjs +200 -0
- package/agents/cursor.mjs +67 -0
- package/agents/gemini.mjs +63 -0
- package/agents/index.mjs +10 -0
- package/agents/opencode.mjs +65 -0
- package/agents/vscode.mjs +47 -0
- package/agents/windsurf.mjs +32 -0
- package/cli.mjs +536 -0
- package/hook/engine.mjs +286 -0
- package/hook/features/claims.mjs +265 -0
- package/hook/features/gates.mjs +134 -0
- package/hook/features/git.mjs +243 -0
- package/hook/features/log.mjs +70 -0
- package/hook/features/notes.mjs +88 -0
- package/hook/features/pause.mjs +340 -0
- package/hook/features/stopGuard.mjs +42 -0
- package/hook/features/workerId.mjs +55 -0
- package/hook/introsio-hook.mjs +95 -0
- package/hook/normalize.mjs +171 -0
- package/hook/respond.mjs +46 -0
- package/hook/state.mjs +136 -0
- package/lib/config.mjs +64 -0
- package/lib/git.mjs +120 -0
- package/lib/jsonFile.mjs +103 -0
- package/lib/lock.mjs +182 -0
- package/lib/managedBlock.mjs +19 -0
- package/lib/paths.mjs +59 -0
- package/lib/processTree.mjs +127 -0
- package/opencode/introsio.template.js +55 -0
- package/package.json +54 -6
- package/templates/execute.md +20 -0
- package/templates/pause.md +25 -0
- package/templates/resume.md +22 -0
package/lib/lock.mjs
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// A cross-process lock built on mkdir (atomic on every filesystem we target).
|
|
2
|
+
// Hooks for parallel tool calls run at the same time and must not overwrite each
|
|
3
|
+
// other's session state.
|
|
4
|
+
//
|
|
5
|
+
// The holder writes its pid into the lock, so a lock whose holder died is taken
|
|
6
|
+
// over within seconds (ABANDONED_STALE_MS); a lock whose holder is alive is taken over only after STALE_MS,
|
|
7
|
+
// which is longer than anything a hook does while holding it (the pause
|
|
8
|
+
// snapshot's git work is budgeted at 15 s). A waiter gives up after WAIT_MS and
|
|
9
|
+
// goes on unlocked (fail open — a hook must answer within the agent's timeout,
|
|
10
|
+
// 10–15 s for the after-tool / stop / session-start hooks); the release function
|
|
11
|
+
// then reports `acquired: false` so the caller merges instead of overwriting
|
|
12
|
+
// (hook/state.mjs saveSessionUnlocked, which locks again just for that write).
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
|
|
16
|
+
const STALE_MS = 60_000;
|
|
17
|
+
// Two waits fit in the agents' 10–15 s hook timeouts: the hook's own (WAIT_MS), and,
|
|
18
|
+
// when it ran unlocked, one more for its short merge-and-save (SAVE_WAIT_MS).
|
|
19
|
+
const WAIT_MS = 6_000;
|
|
20
|
+
export const SAVE_WAIT_MS = 3_000;
|
|
21
|
+
const OWNER = 'owner.json';
|
|
22
|
+
|
|
23
|
+
// On Windows, mkdir on a directory another process is deleting right now fails with
|
|
24
|
+
// EPERM / EACCES / EBUSY instead of EEXIST. That is contention, not a broken disk: wait and retry.
|
|
25
|
+
const isContention = (error) => error.code === 'EEXIST'
|
|
26
|
+
|| (process.platform === 'win32' && ['EPERM', 'EACCES', 'EBUSY'].includes(error.code));
|
|
27
|
+
|
|
28
|
+
const sleep = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });
|
|
29
|
+
|
|
30
|
+
function pidAlive(pid) {
|
|
31
|
+
if (!Number.isInteger(pid) || pid <= 0) return true; // unknown: let the age decide
|
|
32
|
+
try {
|
|
33
|
+
process.kill(pid, 0);
|
|
34
|
+
return true;
|
|
35
|
+
} catch (error) {
|
|
36
|
+
return error.code === 'EPERM';
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The lock's owner, or null when it has none. A momentarily unreadable owner file (Windows) is read again. */
|
|
41
|
+
function readOwner(dir) {
|
|
42
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
43
|
+
try {
|
|
44
|
+
return JSON.parse(fs.readFileSync(path.join(dir, OWNER), 'utf8'));
|
|
45
|
+
} catch (error) {
|
|
46
|
+
if (process.platform !== 'win32' || !TRANSIENT.has(error.code) || attempt >= 20) return null;
|
|
47
|
+
pauseSync(2);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function writeOwner(dir) {
|
|
53
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
54
|
+
try {
|
|
55
|
+
fs.writeFileSync(path.join(dir, OWNER), JSON.stringify({ pid: process.pid, at: Date.now() }));
|
|
56
|
+
return true;
|
|
57
|
+
} catch (error) {
|
|
58
|
+
if (process.platform !== 'win32' || !TRANSIENT.has(error.code) || attempt >= 20) return false;
|
|
59
|
+
pauseSync(2);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// A lock whose owner is gone (or that has no owner file) is broken only after this
|
|
65
|
+
// grace. On Windows a released lock lingers for a moment — a deleted file or folder
|
|
66
|
+
// another process still has open is only marked for deletion — still naming its
|
|
67
|
+
// owner, whose process may have exited already. Breaking such a lock at once let two
|
|
68
|
+
// hooks hold the lock together; a genuinely abandoned one simply waits 2 s longer.
|
|
69
|
+
const ABANDONED_STALE_MS = 2_000;
|
|
70
|
+
// The guard that serializes breaking a stale lock is held for milliseconds.
|
|
71
|
+
const GUARD_STALE_MS = 5_000;
|
|
72
|
+
const REMOVE_RETRY_MS = 1_000;
|
|
73
|
+
const TRANSIENT = new Set(['EPERM', 'EACCES', 'EBUSY', 'ENOTEMPTY']);
|
|
74
|
+
const pauseSync = (ms) => { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); };
|
|
75
|
+
|
|
76
|
+
/** Whether the lock at `dir` belongs to nobody any more. Throws when it is gone (released meanwhile). */
|
|
77
|
+
function isStale(dir, staleMs, now) {
|
|
78
|
+
const age = now - fs.statSync(dir).mtimeMs;
|
|
79
|
+
const owner = readOwner(dir);
|
|
80
|
+
const abandoned = !owner || (owner.pid !== process.pid && !pidAlive(owner.pid));
|
|
81
|
+
if (abandoned) return age > Math.min(ABANDONED_STALE_MS, staleMs);
|
|
82
|
+
return age > staleMs;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Removes a lock directory. On Windows a file or directory another process has
|
|
87
|
+
* open is only marked for deletion, so the removal is retried briefly.
|
|
88
|
+
*/
|
|
89
|
+
function removeLockDir(dir) {
|
|
90
|
+
const deadline = Date.now() + REMOVE_RETRY_MS;
|
|
91
|
+
let delay = 2;
|
|
92
|
+
for (;;) {
|
|
93
|
+
try {
|
|
94
|
+
fs.rmSync(path.join(dir, OWNER), { force: true });
|
|
95
|
+
fs.rmdirSync(dir);
|
|
96
|
+
return true;
|
|
97
|
+
} catch (error) {
|
|
98
|
+
if (error.code === 'ENOENT') return true;
|
|
99
|
+
if (process.platform !== 'win32' || !TRANSIENT.has(error.code) || Date.now() > deadline) return false;
|
|
100
|
+
pauseSync(delay);
|
|
101
|
+
delay = Math.min(delay * 2, 50);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Breaks a stale lock — under a guard, re-checking that it is still stale, so
|
|
108
|
+
* two waiters that both judged it stale cannot both break it: the second would
|
|
109
|
+
* otherwise remove the fresh lock the first had just taken, and both would hold it.
|
|
110
|
+
*/
|
|
111
|
+
function breakLock(dir, staleMs) {
|
|
112
|
+
const guard = `${dir}.break`;
|
|
113
|
+
try {
|
|
114
|
+
fs.mkdirSync(guard);
|
|
115
|
+
} catch {
|
|
116
|
+
// Another waiter is breaking it; clear a guard whose breaker died.
|
|
117
|
+
try { if (Date.now() - fs.statSync(guard).mtimeMs > GUARD_STALE_MS) removeLockDir(guard); } catch { /* gone */ }
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
if (isStale(dir, staleMs, Date.now())) removeLockDir(dir);
|
|
122
|
+
} catch {
|
|
123
|
+
// Released meanwhile: nothing to break.
|
|
124
|
+
} finally {
|
|
125
|
+
removeLockDir(guard);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const unlocked = () => {
|
|
130
|
+
const release = () => {};
|
|
131
|
+
release.acquired = false;
|
|
132
|
+
return release;
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Resolves to a release function (`release.acquired` says whether the lock was
|
|
137
|
+
* really taken); after `waitMs` it resolves unlocked rather than hang the hook.
|
|
138
|
+
*/
|
|
139
|
+
export async function acquireLock(file, { waitMs = WAIT_MS, staleMs = STALE_MS } = {}) {
|
|
140
|
+
const dir = `${file}.lock`;
|
|
141
|
+
fs.mkdirSync(path.dirname(dir), { recursive: true });
|
|
142
|
+
const deadline = Date.now() + waitMs;
|
|
143
|
+
let delay = 5;
|
|
144
|
+
for (;;) {
|
|
145
|
+
try {
|
|
146
|
+
fs.mkdirSync(dir);
|
|
147
|
+
if (!writeOwner(dir)) {
|
|
148
|
+
// A lock without an owner reads as stale within seconds: do not hold one.
|
|
149
|
+
removeLockDir(dir);
|
|
150
|
+
return unlocked();
|
|
151
|
+
}
|
|
152
|
+
let released = false;
|
|
153
|
+
const release = () => {
|
|
154
|
+
if (released) return;
|
|
155
|
+
released = true;
|
|
156
|
+
// Never remove a lock someone else took over after judging ours stale.
|
|
157
|
+
const owner = readOwner(dir);
|
|
158
|
+
if (owner && owner.pid !== process.pid) return;
|
|
159
|
+
removeLockDir(dir);
|
|
160
|
+
};
|
|
161
|
+
release.acquired = true;
|
|
162
|
+
return release;
|
|
163
|
+
} catch (error) {
|
|
164
|
+
if (!isContention(error)) return unlocked();
|
|
165
|
+
try {
|
|
166
|
+
if (isStale(dir, staleMs, Date.now())) {
|
|
167
|
+
breakLock(dir, staleMs);
|
|
168
|
+
await sleep(1 + Math.floor(Math.random() * 5));
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
} catch {
|
|
172
|
+
// The holder just released it (or it is mid-delete): try again after a short pause.
|
|
173
|
+
if (Date.now() > deadline) return unlocked();
|
|
174
|
+
await sleep(delay);
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
if (Date.now() > deadline) return unlocked();
|
|
178
|
+
await sleep(delay + Math.floor(Math.random() * delay)); // jitter: waiters do not retry in lockstep
|
|
179
|
+
delay = Math.min(delay * 2, 50);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// A delimited block the kit owns inside a text config (TOML): add, replace or remove it without touching the rest.
|
|
2
|
+
export const BEGIN = '# >>> introsio (managed by `introsio setup` — edit with the introsio command) >>>';
|
|
3
|
+
export const END = '# <<< introsio <<<';
|
|
4
|
+
|
|
5
|
+
export function withBlock(text, body) {
|
|
6
|
+
const without = withoutBlock(text ?? '');
|
|
7
|
+
const block = `${BEGIN}\n${body.trim()}\n${END}\n`;
|
|
8
|
+
return without.trim() ? `${without.trimEnd()}\n\n${block}` : block;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function withoutBlock(text) {
|
|
12
|
+
const start = text.indexOf(BEGIN);
|
|
13
|
+
if (start < 0) return text;
|
|
14
|
+
const end = text.indexOf(END, start);
|
|
15
|
+
if (end < 0) return text;
|
|
16
|
+
return `${text.slice(0, start).trimEnd()}\n${text.slice(end + END.length).replace(/^\n+/, '')}`.replace(/^\n+/, '');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export const hasBlock = (text) => (text ?? '').includes(BEGIN);
|
package/lib/paths.mjs
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Every path the kit reads or writes, resolved from one HOME so tests can point it at a scratch folder.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
|
|
6
|
+
export function homeDir(env = process.env) {
|
|
7
|
+
return env.INTROSIO_TEST_HOME || os.homedir();
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** ~/.introsio — the kit's own folder (installed hook code, settings, session state, log). */
|
|
11
|
+
export function introsioDir(env = process.env) {
|
|
12
|
+
return env.INTROSIO_HOME || path.join(homeDir(env), '.introsio');
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const kitDir = (env) => path.join(introsioDir(env), 'kit');
|
|
16
|
+
export const configPath = (env) => path.join(introsioDir(env), 'config.json');
|
|
17
|
+
export const sessionsDir = (env) => path.join(introsioDir(env), 'sessions');
|
|
18
|
+
export const gateCachePath = (env) => path.join(introsioDir(env), 'gate-cache.json');
|
|
19
|
+
export const logPath = (env) => path.join(introsioDir(env), 'log.jsonl');
|
|
20
|
+
export const installedHookScript = (env) => path.join(kitDir(env), 'hook', 'introsio-hook.mjs');
|
|
21
|
+
|
|
22
|
+
/** XDG-style config root (OpenCode, VS Code on Linux). */
|
|
23
|
+
export function xdgConfigHome(env = process.env) {
|
|
24
|
+
return env.XDG_CONFIG_HOME && !env.INTROSIO_TEST_HOME ? env.XDG_CONFIG_HOME : path.join(homeDir(env), '.config');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* One spelling for one location. Windows reports the same folder as
|
|
29
|
+
* `C:/Users/Jane_dev/x` (git), `C:\\Users\\Jane_dev\\x` (Node) and
|
|
30
|
+
* `C:\\Users\\JANE_D~1\\x` (8.3 short names in temp folders, subst drives);
|
|
31
|
+
* macOS has /tmp -> /private/tmp. Every comparison and every settings key goes
|
|
32
|
+
* through this, or settings saved by the CLI are never found by the hooks.
|
|
33
|
+
*/
|
|
34
|
+
export function canonicalPath(input) {
|
|
35
|
+
const absolute = path.resolve(String(input));
|
|
36
|
+
try {
|
|
37
|
+
return fs.realpathSync.native(absolute);
|
|
38
|
+
} catch {
|
|
39
|
+
// Not there (yet): canonicalize the nearest folder that is.
|
|
40
|
+
const parent = path.dirname(absolute);
|
|
41
|
+
return parent === absolute ? absolute : path.join(canonicalPath(parent), path.basename(absolute));
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The key a repository's settings are stored under. Case-insensitive on Windows. */
|
|
46
|
+
export function repoKey(root) {
|
|
47
|
+
const canonical = canonicalPath(root);
|
|
48
|
+
return process.platform === 'win32' ? canonical.toLowerCase() : canonical;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** `file` relative to `root` with forward slashes, or null when it is outside (or is the root itself). */
|
|
52
|
+
export function relativeInside(root, file) {
|
|
53
|
+
if (!root || !file) return null;
|
|
54
|
+
const base = canonicalPath(root);
|
|
55
|
+
const target = canonicalPath(path.isAbsolute(file) ? file : path.join(root, file));
|
|
56
|
+
const rel = path.relative(base, target);
|
|
57
|
+
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;
|
|
58
|
+
return rel.split(path.sep).join('/');
|
|
59
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// Running a command so that a timeout really stops it — the command and everything
|
|
2
|
+
// it started (test runners fork workers) — and keeping only the tail of its output.
|
|
3
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
|
|
6
|
+
const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'fish', 'ksh', 'cmd.exe', 'powershell.exe', 'pwsh', 'pwsh.exe']);
|
|
7
|
+
|
|
8
|
+
export function killTree(pid) {
|
|
9
|
+
if (!pid) return;
|
|
10
|
+
if (process.platform === 'win32') {
|
|
11
|
+
spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' });
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
try { process.kill(-pid, 'SIGKILL'); } catch { try { process.kill(pid, 'SIGKILL'); } catch { /* gone */ } }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Keeps the last `maxLines` lines, each cut to `maxLineChars`, at most `maxChars` in all. */
|
|
18
|
+
export function tailText(text, { maxLines = 40, maxLineChars = 300, maxChars = 3000 } = {}) {
|
|
19
|
+
const lines = String(text ?? '').replace(/\r/g, '').trimEnd().split('\n').slice(-maxLines)
|
|
20
|
+
.map((line) => (line.length > maxLineChars ? `${line.slice(0, maxLineChars)}…` : line));
|
|
21
|
+
let out = lines.join('\n');
|
|
22
|
+
if (out.length > maxChars) out = `…${out.slice(-maxChars)}`;
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Groups started by this process, killed if the process ends first.
|
|
27
|
+
const running = new Set();
|
|
28
|
+
const killAll = () => { for (const pid of running) killTree(pid); running.clear(); };
|
|
29
|
+
let exitHookInstalled = false;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* For the hook process only (never inside an agent like OpenCode, whose signals
|
|
33
|
+
* are its own): if the agent kills the hook — its timeout, or the person
|
|
34
|
+
* cancelling — the gate's processes go with it instead of running on unattended.
|
|
35
|
+
*/
|
|
36
|
+
export function killChildrenOnSignals() {
|
|
37
|
+
for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP']) {
|
|
38
|
+
process.once(signal, () => {
|
|
39
|
+
killAll();
|
|
40
|
+
process.exit(0);
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Runs `command` in a shell, in its own process group; on timeout the whole group is killed. */
|
|
46
|
+
export function runCommand(command, { cwd, timeoutSec, env = process.env, keepBytes = 64 * 1024 }) {
|
|
47
|
+
return new Promise((resolve) => {
|
|
48
|
+
const started = Date.now();
|
|
49
|
+
let output = '';
|
|
50
|
+
let timedOut = false;
|
|
51
|
+
const keep = (chunk) => {
|
|
52
|
+
output += chunk.toString('utf8');
|
|
53
|
+
if (output.length > keepBytes * 2) output = output.slice(-keepBytes);
|
|
54
|
+
};
|
|
55
|
+
let child;
|
|
56
|
+
try {
|
|
57
|
+
child = spawn(command, { cwd, shell: true, env, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
|
|
58
|
+
} catch (error) {
|
|
59
|
+
resolve({ ok: false, code: null, timedOut: false, output: String(error.message), ms: 0 });
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
if (!exitHookInstalled) {
|
|
63
|
+
exitHookInstalled = true;
|
|
64
|
+
process.on('exit', killAll);
|
|
65
|
+
}
|
|
66
|
+
running.add(child.pid);
|
|
67
|
+
child.stdout.on('data', keep);
|
|
68
|
+
child.stderr.on('data', keep);
|
|
69
|
+
const timer = setTimeout(() => {
|
|
70
|
+
timedOut = true;
|
|
71
|
+
killTree(child.pid);
|
|
72
|
+
}, timeoutSec * 1000);
|
|
73
|
+
let finished = false;
|
|
74
|
+
const finish = (code) => {
|
|
75
|
+
if (finished) return;
|
|
76
|
+
finished = true;
|
|
77
|
+
clearTimeout(timer);
|
|
78
|
+
running.delete(child.pid);
|
|
79
|
+
// Stray background processes the command left behind go too.
|
|
80
|
+
if (process.platform !== 'win32') { try { process.kill(-child.pid, 'SIGKILL'); } catch { /* none left */ } }
|
|
81
|
+
resolve({ ok: code === 0 && !timedOut, code, timedOut, output: tailText(output), ms: Date.now() - started });
|
|
82
|
+
};
|
|
83
|
+
child.on('error', (error) => { keep(String(error.message)); finish(null); });
|
|
84
|
+
// 'exit' rather than 'close': a forked worker holding the pipe must not keep us waiting.
|
|
85
|
+
child.on('exit', (code) => finish(code));
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* The agent process behind a hook. Agents start hooks through a shell, so the
|
|
91
|
+
* hook's parent is usually a short-lived `sh -c`; its parent is the agent.
|
|
92
|
+
*/
|
|
93
|
+
export function agentPid(ppid = process.ppid) {
|
|
94
|
+
try {
|
|
95
|
+
const parent = parentOf(ppid);
|
|
96
|
+
if (parent && SHELLS.has(parent.comm)) return parentOf(parent.ppid)?.pid ?? ppid;
|
|
97
|
+
return ppid;
|
|
98
|
+
} catch {
|
|
99
|
+
return ppid;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function parentOf(pid) {
|
|
104
|
+
if (!pid || pid <= 1) return null;
|
|
105
|
+
if (process.platform === 'linux') {
|
|
106
|
+
const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
|
|
107
|
+
const close = stat.lastIndexOf(')');
|
|
108
|
+
const comm = stat.slice(stat.indexOf('(') + 1, close);
|
|
109
|
+
const ppid = Number(stat.slice(close + 2).split(' ')[1]);
|
|
110
|
+
return { pid, comm, ppid };
|
|
111
|
+
}
|
|
112
|
+
if (process.platform === 'win32') return null;
|
|
113
|
+
const result = spawnSync('ps', ['-o', 'ppid=,comm=', '-p', String(pid)], { encoding: 'utf8', timeout: 2000 });
|
|
114
|
+
const match = result.stdout.trim().match(/^(\d+)\s+(.+)$/);
|
|
115
|
+
if (!match) return null;
|
|
116
|
+
return { pid, ppid: Number(match[1]), comm: match[2].split('/').pop().replace(/^-/, '') };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function isAlive(pid) {
|
|
120
|
+
if (!pid) return false;
|
|
121
|
+
try {
|
|
122
|
+
process.kill(pid, 0);
|
|
123
|
+
return true;
|
|
124
|
+
} catch (error) {
|
|
125
|
+
return error.code === 'EPERM';
|
|
126
|
+
}
|
|
127
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Introsio plugin for OpenCode — installed by `introsio setup`. Runs the same engine as the
|
|
2
|
+
// Claude Code / Codex / Gemini / Cursor hooks: tracks claimed tasks, guards completion and git,
|
|
3
|
+
// and on session.idle sends the agent back if a claimed task is still open in Introsio.
|
|
4
|
+
import { handleEvent } from '__ENGINE__';
|
|
5
|
+
// OpenCode runs this plugin inside its own process: every hook here is awaited, and
|
|
6
|
+
// nothing here may throw except a deliberate refusal in tool.execute.before.
|
|
7
|
+
import { classifyTool, parseToolResult } from '__NORMALIZE__';
|
|
8
|
+
|
|
9
|
+
const argsByCall = new Map();
|
|
10
|
+
|
|
11
|
+
export const IntrosioPlugin = async ({ client, directory, worktree }) => {
|
|
12
|
+
const cwd = worktree || directory || process.cwd();
|
|
13
|
+
const base = (sessionID, hookEvent, event) => ({
|
|
14
|
+
agent: 'opencode', hookEvent, event, sessionId: String(sessionID ?? 'unknown'), cwd,
|
|
15
|
+
transcriptPath: null, source: null, stopHookActive: false, loopCount: 0,
|
|
16
|
+
});
|
|
17
|
+
const safe = async (fn) => {
|
|
18
|
+
try {
|
|
19
|
+
return (await fn()) ?? { type: 'none' };
|
|
20
|
+
} catch {
|
|
21
|
+
return { type: 'none' };
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
return {
|
|
26
|
+
'tool.execute.before': async (input, output) => {
|
|
27
|
+
argsByCall.set(input.callID, output?.args ?? {});
|
|
28
|
+
const tool = classifyTool(input.tool, output?.args ?? {}, 'opencode');
|
|
29
|
+
const answer = await safe(() => handleEvent({ ...base(input.sessionID, 'tool.execute.before', 'before-tool'), tool, result: null }));
|
|
30
|
+
if (answer.type === 'deny') throw new Error(answer.message);
|
|
31
|
+
},
|
|
32
|
+
'tool.execute.after': async (input, output) => {
|
|
33
|
+
const args = argsByCall.get(input.callID) ?? {};
|
|
34
|
+
argsByCall.delete(input.callID);
|
|
35
|
+
const tool = classifyTool(input.tool, args, 'opencode');
|
|
36
|
+
const result = parseToolResult(output?.output ?? output?.metadata);
|
|
37
|
+
const answer = await safe(() => handleEvent({ ...base(input.sessionID, 'tool.execute.after', 'after-tool'), tool, result }));
|
|
38
|
+
if (answer.type === 'context' && output && typeof output.output === 'string') output.output += `\n\n${answer.message}`;
|
|
39
|
+
},
|
|
40
|
+
event: async ({ event }) => {
|
|
41
|
+
const sessionID = event?.properties?.sessionID ?? event?.properties?.info?.id;
|
|
42
|
+
if (!sessionID) return;
|
|
43
|
+
if (event.type === 'session.compacted') {
|
|
44
|
+
await safe(() => handleEvent({ ...base(sessionID, 'session.compacted', 'compact') }));
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
if (event.type !== 'session.idle') return;
|
|
48
|
+
const answer = await safe(() => handleEvent({ ...base(sessionID, 'session.idle', 'stop') }));
|
|
49
|
+
if (answer.type !== 'block') return;
|
|
50
|
+
client.session
|
|
51
|
+
.prompt({ path: { id: sessionID }, body: { parts: [{ type: 'text', text: answer.message }] } })
|
|
52
|
+
.catch(() => {});
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "introsio",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "introsio",
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Connect any coding agent to Introsio, run a Developer Mode project with /introsio-execute, and keep Introsio updated with hooks.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"int": "cli.mjs",
|
|
8
|
+
"introsio": "cli.mjs"
|
|
9
|
+
},
|
|
10
|
+
"engines": {
|
|
11
|
+
"node": ">=18"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"cli.mjs",
|
|
15
|
+
"lib",
|
|
16
|
+
"hook",
|
|
17
|
+
"agents",
|
|
18
|
+
"opencode",
|
|
19
|
+
"templates",
|
|
20
|
+
"README.md",
|
|
21
|
+
"LICENSE",
|
|
22
|
+
"CHANGELOG.md"
|
|
23
|
+
],
|
|
24
|
+
"scripts": {
|
|
25
|
+
"test": "node test/run.js",
|
|
26
|
+
"prepublishOnly": "node test/run.js"
|
|
27
|
+
},
|
|
28
|
+
"repository": {
|
|
29
|
+
"type": "git",
|
|
30
|
+
"url": "git+https://github.com/introsio/Introsio-cli.git"
|
|
31
|
+
},
|
|
32
|
+
"homepage": "https://github.com/introsio/Introsio-cli#readme",
|
|
33
|
+
"bugs": {
|
|
34
|
+
"url": "https://github.com/introsio/Introsio-cli/issues"
|
|
35
|
+
},
|
|
36
|
+
"keywords": [
|
|
37
|
+
"claude-code",
|
|
38
|
+
"cli",
|
|
39
|
+
"codex",
|
|
40
|
+
"coding-agent",
|
|
41
|
+
"cursor",
|
|
42
|
+
"gemini-cli",
|
|
43
|
+
"hooks",
|
|
44
|
+
"introsio",
|
|
45
|
+
"mcp",
|
|
46
|
+
"model-context-protocol",
|
|
47
|
+
"opencode"
|
|
48
|
+
],
|
|
49
|
+
"publishConfig": {
|
|
50
|
+
"access": "public"
|
|
51
|
+
},
|
|
52
|
+
"license": "MIT",
|
|
53
|
+
"author": "Mahesh Rasapalli"
|
|
54
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
Execute an Introsio Developer Mode project with the Introsio MCP tools, task by task, until it is done or nothing can start.
|
|
2
|
+
|
|
3
|
+
Project: $ARGUMENTS (a name or id — if empty, call getProjects and ask which Developer Mode project to run).
|
|
4
|
+
|
|
5
|
+
1. Start or resume: getProjectState { projectId } for the overview and the context revision, then getProjectContext { projectId } once. Work inside the context: use its tech stack, never cross a "must" constraint, follow its conventions, do not reopen accepted decisions (record a new one with recordProjectDecision).
|
|
6
|
+
2. Loop:
|
|
7
|
+
a. claimTask { projectId, workerId } — use the SAME workerId on every call (the one claimTask returns, or the one the Introsio hook gave you). It hands you the spec, subtask waves, inputs (what earlier tasks produced) and, when the project has one, the GitHub repository.
|
|
8
|
+
b. Do the work, one subtask at a time in the order of subtaskWaves, and report the steps you FINISH — never one you did not do:
|
|
9
|
+
- A task you will finish well inside the lease (leaseExpiresAt in the claim, 30 minutes by default): make no call per step. Name every finished subtask in step e: completeTask { …, completedSubtasks: [ids] }.
|
|
10
|
+
- A longer task: updateSubtask { taskId, subtaskId, workerId, completed: true } as each step finishes — one call, no in_progress first. It saves your progress if the session ends and renews the lease.
|
|
11
|
+
- Only when several workers share one task: mark a subtask in_progress before you start it, so they see it is taken.
|
|
12
|
+
c. Check it: run the tests or commands that prove it works.
|
|
13
|
+
d. Commit it. If the claim named a repository: work on your own branch off its defaultBranch, push it, and record outcome.branch. Otherwise keep it local — commit only, no push.
|
|
14
|
+
e. completeTask { taskId, workerId, completedSubtasks: [the subtasks you finished and have not reported], outcome: { summary: what you produced (names, shapes, commit id), verification: what you ran and its result, files: paths you changed } }. If it is refused, fix exactly what the error names and call it again.
|
|
15
|
+
Size the outcome to the task, not to a template: a small change is one line ("Renamed X to Y — abc1234"); a task that later tasks build on adds only the names and shapes they need (endpoints, exports, schema fields, decisions). Never narrate the steps you took, repeat the spec, or list what files already shows. verification is the command and its result in one line.
|
|
16
|
+
The outcome is the record — do not also write a recap in chat. Between tasks say at most one short line ("Done: <title>") and claim the next one; save the wrap-up for when the project is done or you stop.
|
|
17
|
+
f. The answer lists nowReady and openTasks — claim the next task. Do not re-read the schedule after every task.
|
|
18
|
+
3. If you cannot finish a task: updateTask { taskId, workerId, statusState: "blocked" } and tell the user why. Never leave a claimed task silently open.
|
|
19
|
+
4. When claimTask answers reason "complete": updateProjectState { projectId, handoff: true, execution: { description: where things stand, status: "done" } }. Reason "paused": the rest of the ready work is paused — tell the user (/introsio-resume takes a paused task back after checking the repository); never claim a paused task without resume: true.
|
|
20
|
+
5. If you have to stop before the project is done — out of usage, context or time, or the user asks — follow the /introsio-pause procedure: pauseTask each task you hold with a note, nextSteps, the subtask you were on and the git position, so the work resumes exactly.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
Pause the Introsio work in this session so it can be resumed EXACTLY later — by you in a new session, or by another agent — with the Introsio MCP tools. Use this when you are running out of usage, context or time, or the user asks you to stop.
|
|
2
|
+
|
|
3
|
+
What the user added: $ARGUMENTS (may be empty). "--release" means: hand the work to any worker (commit it first). Anything else is a note to pass on.
|
|
4
|
+
|
|
5
|
+
Be fast and do only this — no new work, no refactoring. If you are cut off part-way, what was already saved still counts.
|
|
6
|
+
|
|
7
|
+
1. Find what you hold: every task you claimed in this session and have not completed (the Introsio hook has also told you which). Hold none? Go to step 6.
|
|
8
|
+
2. For each task, settle its subtasks honestly: list the ids of the steps that are really finished and checked and that you have not reported yet — they go in completedSubtasks on the pauseTask call below, recorded with the pause (no call per step). The step you were in the middle of is NOT on that list: it stays open — remember its subtaskId for handoff.subtaskId.
|
|
9
|
+
3. Read the git position (skip outside a git repository):
|
|
10
|
+
- git rev-parse --abbrev-ref HEAD → branch
|
|
11
|
+
- git rev-parse HEAD → head
|
|
12
|
+
- git status --porcelain → dirtyFiles (the paths only)
|
|
13
|
+
Never commit, stash, reset or clean anything for a plain pause: the unfinished files stay exactly where they are.
|
|
14
|
+
4. Only with --release: commit the task's work on its own branch (create introsio/<taskId> first if you are on the default branch), push it if the project has a GitHub repository, and record it with updateTask { taskId, workerId, outcome: { branch } }. If you cannot commit cleanly, pause without release instead and say why.
|
|
15
|
+
5. For each task: pauseTask { taskId, workerId, agentName, release (only with --release), completedSubtasks: [the ids from step 2], handoff: {
|
|
16
|
+
reason: "usage_limit" | "context" | "user" | "other",
|
|
17
|
+
subtaskId: the subtask you were on,
|
|
18
|
+
note: written for someone who has NONE of your conversation — what is finished, what is half done and exactly how far (function, file:line, the failing test), what you were about to do, anything you tried that did not work, and the user's note if they gave one,
|
|
19
|
+
nextSteps: [ the next actions, in order ],
|
|
20
|
+
host: this computer's name (hostname),
|
|
21
|
+
git: { branch, head, dirtyFiles }
|
|
22
|
+
} }
|
|
23
|
+
If the Introsio hook refuses it with the exact git values to send, call pauseTask again with exactly those (they include the snapshot of your working tree).
|
|
24
|
+
6. If you hold no task: updateProjectState { projectId, handoff: true, execution: { description: where things stand, status: "paused" }, nextSteps } for the project you were working on.
|
|
25
|
+
7. Tell the user, in a few lines: what was paused, what is saved (the note, and that the working tree snapshot is kept locally and nothing was committed unless --release), and how to continue — `/introsio-resume <taskId>` in any agent connected to Introsio (`int paused` in a terminal lists every pause on this computer). Then stop.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
Resume paused or interrupted Introsio work exactly where it stopped, with the Introsio MCP tools — but only after checking that the repository still matches the pause.
|
|
2
|
+
|
|
3
|
+
What to resume: $ARGUMENTS (a task id, a project name or id, or empty).
|
|
4
|
+
|
|
5
|
+
1. Find the work:
|
|
6
|
+
- a task id → that task;
|
|
7
|
+
- a project → getProjectState { projectId }: ids.pausedTasks lists its paused tasks;
|
|
8
|
+
- empty → getProjects, then getProjectState for each Developer Mode project until you find paused tasks. (In a terminal, `int paused` lists the pauses made on this computer.)
|
|
9
|
+
Also count a task as interrupted if it is in progress with a claim whose worker is gone (the Introsio hook says so when it sees one). Several candidates → list them (title, paused when, by whom, where) and ask the user which. None → say so and stop.
|
|
10
|
+
2. Read it WITHOUT claiming it: getTaskById { taskId }. Its `pause` holds the note, nextSteps, the subtask and the git position. The Introsio hook answers with a resume check — EXACT, DRIFT or BLOCKED and the precise differences. If no check appears (your agent runs no hooks), check by hand:
|
|
11
|
+
a. same repository, no merge/rebase in progress (git status);
|
|
12
|
+
b. on pause.git.branch (git rev-parse --abbrev-ref HEAD) — else `git switch <branch>`;
|
|
13
|
+
c. HEAD is pause.git.head (git rev-parse HEAD); if not: `git log <head>..HEAD` (someone added commits), or HEAD is behind / the history was rewritten;
|
|
14
|
+
d. the files in pause.git.dirtyFiles still have their unfinished changes (git status, git diff);
|
|
15
|
+
e. the paused subtask is still open, and the task was not edited since (its updatedAt after pause.at).
|
|
16
|
+
3. Act on the verdict:
|
|
17
|
+
- EXACT → step 4.
|
|
18
|
+
- DRIFT → show the user each difference in plain words and ask how to go on: restore the snapshot (run the exact restore command the check gave, only after they agree), continue from the repository as it is, or leave it paused. Leaving it paused changes nothing.
|
|
19
|
+
- BLOCKED → do not resume. Explain what is wrong (e.g. the unfinished code is on another computer, another session is working it, a rebase is half done) and stop.
|
|
20
|
+
4. Take it back: claimTask { taskId, workerId, resume: true } — use your own workerId. For a task interrupted WITHOUT a pause, the hook names the dead session's workerId: claim with that one to take it over at once. If the claim is refused because someone else resumed it first, stop and tell the user.
|
|
21
|
+
The answer carries resumedPause and taskChangedSincePause: if the task changed, read its spec again before coding. If the context revision moved since the pause (pause.contextRevision), getProjectContext once.
|
|
22
|
+
5. Continue from the note and nextSteps, starting at the paused subtask (one updateSubtask { completed: true } when it is done). From here it is the normal loop: work → check → commit → completeTask { taskId, workerId, outcome } → claimTask { projectId, workerId } for the next task, as /introsio-execute does. If you must stop again, use /introsio-pause.
|