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/cli.mjs
ADDED
|
@@ -0,0 +1,536 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// int — the Introsio agent kit: connect coding agents to Introsio, run projects with
|
|
3
|
+
// /introsio-execute, and manage the hooks that keep Introsio updated.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { spawnSync } from 'node:child_process';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { AGENTS, agentById } from './agents/index.mjs';
|
|
10
|
+
import { Writer, nodePathOf, COMMANDS, commandText } from './agents/common.mjs';
|
|
11
|
+
import { FEATURES, MODES, loadConfig, saveConfig, repoSettings, updateRepo, featureOn } from './lib/config.mjs';
|
|
12
|
+
import { MAX_GATE_TIMEOUT_SEC } from './hook/features/gates.mjs';
|
|
13
|
+
import { createGit } from './lib/git.mjs';
|
|
14
|
+
import { homeDir, introsioDir, kitDir, logPath, configPath } from './lib/paths.mjs';
|
|
15
|
+
import { readText } from './lib/jsonFile.mjs';
|
|
16
|
+
import { loadOtherSessions, clearSessions } from './hook/state.mjs';
|
|
17
|
+
import { summarize } from './hook/features/log.mjs';
|
|
18
|
+
import { runGateCommand } from './hook/features/gates.mjs';
|
|
19
|
+
import { listLocalPauses, removeLocalPause } from './hook/features/pause.mjs';
|
|
20
|
+
import { sessionIsLive } from './hook/features/workerId.mjs';
|
|
21
|
+
|
|
22
|
+
const KIT_SOURCE = path.dirname(fileURLToPath(import.meta.url));
|
|
23
|
+
const DEFAULT_URL = 'https://api.introsio.app/mcp?toolset=developer';
|
|
24
|
+
// Which tools the agents load: `developer` plans and executes; `execute` is the slim set for running a
|
|
25
|
+
// plan that already exists (about a third of the definitions, so every turn is cheaper).
|
|
26
|
+
const KIT_TOOLSETS = ['developer', 'execute', 'all'];
|
|
27
|
+
|
|
28
|
+
/** `url` with its toolset replaced; a URL that cannot be parsed is left alone. */
|
|
29
|
+
function withToolset(url, toolset) {
|
|
30
|
+
try {
|
|
31
|
+
const parsed = new URL(url);
|
|
32
|
+
parsed.searchParams.set('toolset', toolset);
|
|
33
|
+
return parsed.toString();
|
|
34
|
+
} catch {
|
|
35
|
+
return url;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The MCP URL a run of setup uses: --url, else the remembered one, else the default; --toolset switches its tools. */
|
|
40
|
+
function mcpUrlFor(flags, config) {
|
|
41
|
+
const base = typeof flags.url === 'string' ? flags.url : (config.mcpUrl ?? DEFAULT_URL);
|
|
42
|
+
return typeof flags.toolset === 'string' && KIT_TOOLSETS.includes(flags.toolset) ? withToolset(base, flags.toolset) : base;
|
|
43
|
+
}
|
|
44
|
+
const KIT_DIRS = ['hook', 'lib'];
|
|
45
|
+
const VERSION = JSON.parse(readText(path.join(KIT_SOURCE, 'package.json')) ?? '{"version":"0"}').version;
|
|
46
|
+
|
|
47
|
+
process.stdout.on('error', (error) => {
|
|
48
|
+
if (error.code === 'EPIPE') process.exit(0);
|
|
49
|
+
});
|
|
50
|
+
const out = (line = '') => process.stdout.write(`${line}\n`);
|
|
51
|
+
const fail = (message) => {
|
|
52
|
+
process.stderr.write(`introsio: ${message}\n`);
|
|
53
|
+
process.exitCode = 1;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
function parseArgs(argv) {
|
|
57
|
+
const positional = [];
|
|
58
|
+
const flags = {};
|
|
59
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
60
|
+
const arg = argv[i];
|
|
61
|
+
if (arg.startsWith('--')) {
|
|
62
|
+
const [key, inline] = arg.slice(2).split('=', 2);
|
|
63
|
+
if (inline !== undefined) flags[key] = inline;
|
|
64
|
+
else if (argv[i + 1] !== undefined && !argv[i + 1].startsWith('--')) flags[key] = argv[(i += 1)];
|
|
65
|
+
else flags[key] = true;
|
|
66
|
+
} else positional.push(arg);
|
|
67
|
+
}
|
|
68
|
+
return { positional, flags };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function context(flags, env = process.env) {
|
|
72
|
+
const scope = flags.project ? 'project' : 'user';
|
|
73
|
+
const root = scope === 'project' ? path.resolve(flags.project === true ? '.' : flags.project) : null;
|
|
74
|
+
const config = loadConfig(env, { strict: true });
|
|
75
|
+
const kitInstallDir = scope === 'project' ? path.join(root, '.introsio', 'kit') : kitDir(env);
|
|
76
|
+
return {
|
|
77
|
+
env,
|
|
78
|
+
home: homeDir(env),
|
|
79
|
+
scope,
|
|
80
|
+
root,
|
|
81
|
+
platform: process.platform,
|
|
82
|
+
url: mcpUrlFor(flags, config),
|
|
83
|
+
kitSource: KIT_SOURCE,
|
|
84
|
+
kitInstallDir,
|
|
85
|
+
hookScript: path.join(kitInstallDir, 'hook', 'introsio-hook.mjs'),
|
|
86
|
+
nodePath: process.execPath,
|
|
87
|
+
executeTemplate: readText(path.join(KIT_SOURCE, 'templates', 'execute.md')),
|
|
88
|
+
templates: Object.fromEntries(COMMANDS.map((command) => [command.name, readText(path.join(KIT_SOURCE, 'templates', command.template)) ?? ''])),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function selectedAgents(ctx, flags) {
|
|
93
|
+
if (typeof flags.agents === 'string') {
|
|
94
|
+
const ids = flags.agents.split(',').map((id) => id.trim()).filter(Boolean);
|
|
95
|
+
const unknown = ids.filter((id) => !agentById(id));
|
|
96
|
+
if (unknown.length) throw new Error(`unknown agent(s): ${unknown.join(', ')} — choose from ${AGENTS.map((a) => a.id).join(', ')}`);
|
|
97
|
+
return ids.map(agentById);
|
|
98
|
+
}
|
|
99
|
+
return AGENTS.filter((agent) => agent.detect(ctx));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Copies the hook engine to where the agents' configs point, so they never depend on this checkout. */
|
|
103
|
+
function installKit(ctx, writer) {
|
|
104
|
+
const copy = (from, to) => {
|
|
105
|
+
for (const entry of fs.readdirSync(from, { withFileTypes: true })) {
|
|
106
|
+
const source = path.join(from, entry.name);
|
|
107
|
+
const target = path.join(to, entry.name);
|
|
108
|
+
if (entry.isDirectory()) copy(source, target);
|
|
109
|
+
else if (/\.(mjs|js|json)$/.test(entry.name)) writer.writeText(target, fs.readFileSync(source, 'utf8'));
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
for (const dir of KIT_DIRS) copy(path.join(KIT_SOURCE, dir), path.join(ctx.kitInstallDir, dir));
|
|
113
|
+
writer.writeText(path.join(ctx.kitInstallDir, 'package.json'), `${JSON.stringify({ type: 'module', private: true, introsio: VERSION }, null, 2)}\n`);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function suggestGate(dir) {
|
|
117
|
+
const pkg = (() => { try { return JSON.parse(readText(path.join(dir, 'package.json')) ?? ''); } catch { return null; } })();
|
|
118
|
+
if (pkg?.scripts?.test && !/no test specified/.test(pkg.scripts.test)) return 'npm test';
|
|
119
|
+
if (fs.existsSync(path.join(dir, 'Makefile')) && /^test:/m.test(readText(path.join(dir, 'Makefile')) ?? '')) return 'make test';
|
|
120
|
+
if (fs.existsSync(path.join(dir, 'Cargo.toml'))) return 'cargo test';
|
|
121
|
+
if (fs.existsSync(path.join(dir, 'go.mod'))) return 'go test ./...';
|
|
122
|
+
if (fs.existsSync(path.join(dir, 'pyproject.toml')) || fs.existsSync(path.join(dir, 'pytest.ini'))) return 'pytest -q';
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function setup(flags) {
|
|
127
|
+
if (flags.toolset !== undefined && !KIT_TOOLSETS.includes(flags.toolset)) return fail(`--toolset takes one of: ${KIT_TOOLSETS.join(', ')}`);
|
|
128
|
+
const ctx = context(flags);
|
|
129
|
+
if (flags.print) {
|
|
130
|
+
const agent = agentById(String(flags.print));
|
|
131
|
+
if (!agent?.print) return fail(`nothing to print for ${flags.print}`);
|
|
132
|
+
out(JSON.stringify(agent.print(ctx), null, 2));
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
const agents = selectedAgents(ctx, flags).filter((agent) => !(ctx.scope === 'project' && agent.userOnly));
|
|
136
|
+
if (agents.length === 0) {
|
|
137
|
+
out('No coding agents found. Name them: int setup --agents claude,codex,gemini,cursor,opencode,vscode,windsurf');
|
|
138
|
+
process.exitCode = 1;
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
const writer = new Writer({ dryRun: !!flags['dry-run'] });
|
|
142
|
+
installKit(ctx, writer);
|
|
143
|
+
out(`${flags['dry-run'] ? 'Would install' : 'Installing'} Introsio for ${agents.map((a) => a.label).join(', ')} (${ctx.scope === 'project' ? `project ${ctx.root}` : 'every project — global'})`);
|
|
144
|
+
out(`MCP server: ${ctx.url}`);
|
|
145
|
+
out('');
|
|
146
|
+
const next = [];
|
|
147
|
+
for (const agent of agents) {
|
|
148
|
+
try {
|
|
149
|
+
const report = agent.install(ctx, writer);
|
|
150
|
+
out(`● ${agent.label}`);
|
|
151
|
+
out(` connect: ${report.connect}`);
|
|
152
|
+
if (report.command) out(` commands: /introsio-execute, /introsio-pause, /introsio-resume → ${path.dirname(report.command)}`);
|
|
153
|
+
out(` hooks: ${report.hooks}`);
|
|
154
|
+
for (const line of report.next) next.push(`${agent.label}: ${line}`);
|
|
155
|
+
} catch (error) {
|
|
156
|
+
out(`● ${agent.label}: failed — ${error.message}`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (!flags['dry-run'] && (typeof flags.url === 'string' || typeof flags.toolset === 'string')) {
|
|
160
|
+
const config = loadConfig(undefined, { strict: true });
|
|
161
|
+
config.mcpUrl = ctx.url;
|
|
162
|
+
saveConfig(config);
|
|
163
|
+
}
|
|
164
|
+
out('');
|
|
165
|
+
out('Next:');
|
|
166
|
+
for (const line of next) out(` - ${line}`);
|
|
167
|
+
const git = createGit(process.cwd());
|
|
168
|
+
const root = git.root();
|
|
169
|
+
if (root && !repoSettings(loadConfig(undefined, { strict: true }), root).gate) {
|
|
170
|
+
const suggestion = suggestGate(root);
|
|
171
|
+
if (suggestion) out(` - Test gate for this repo (tasks complete only when it passes): int gate set "${suggestion}"`);
|
|
172
|
+
}
|
|
173
|
+
out(' - Check everything: int doctor');
|
|
174
|
+
if (flags['dry-run']) {
|
|
175
|
+
out('');
|
|
176
|
+
out('Dry run — files that would change:');
|
|
177
|
+
for (const action of writer.actions) out(` ${action}`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function uninstall(flags) {
|
|
182
|
+
const ctx = context(flags);
|
|
183
|
+
const agents = typeof flags.agents === 'string' ? selectedAgents(ctx, flags) : AGENTS;
|
|
184
|
+
const writer = new Writer({ dryRun: !!flags['dry-run'] });
|
|
185
|
+
for (const agent of agents) {
|
|
186
|
+
if (ctx.scope === 'project' && agent.userOnly) continue;
|
|
187
|
+
try { agent.uninstall(ctx, writer); } catch (error) { out(`${agent.label}: ${error.message}`); }
|
|
188
|
+
}
|
|
189
|
+
if (typeof flags.agents !== 'string') writer.remove(ctx.kitInstallDir);
|
|
190
|
+
out(writer.actions.length ? `Removed Introsio from:\n${writer.actions.map((a) => ` ${a}`).join('\n')}` : 'Nothing to remove.');
|
|
191
|
+
out('Your settings and log in ~/.introsio stay; delete that folder to remove them too.');
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function repoRoot(flags) {
|
|
195
|
+
const root = createGit(path.resolve(typeof flags.repo === 'string' ? flags.repo : '.')).root();
|
|
196
|
+
if (!root) throw new Error('not inside a git repository (use --repo <dir>)');
|
|
197
|
+
return path.resolve(root);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function status(flags) {
|
|
201
|
+
const ctx = context(flags);
|
|
202
|
+
out(`int ${VERSION} — hook engine ${fs.existsSync(ctx.hookScript) ? `installed at ${ctx.kitInstallDir}` : 'NOT installed (run int setup)'}`);
|
|
203
|
+
out('');
|
|
204
|
+
for (const agent of AGENTS) {
|
|
205
|
+
if (!agent.detect(ctx)) continue;
|
|
206
|
+
const s = agent.status(ctx);
|
|
207
|
+
out(`● ${agent.label.padEnd(18)} connect: ${s.connect.padEnd(4)} commands: ${String(s.command).padEnd(4)} hooks: ${s.hooks}`);
|
|
208
|
+
}
|
|
209
|
+
const config = loadConfig(undefined, { strict: true });
|
|
210
|
+
out('');
|
|
211
|
+
out(`Features: ${Object.keys(FEATURES).map((name) => `${name}${featureOn(config, name) ? '' : ' (off)'}`).join(', ')}`);
|
|
212
|
+
const root = createGit(process.cwd()).root();
|
|
213
|
+
if (root) {
|
|
214
|
+
const settings = repoSettings(config, root);
|
|
215
|
+
out(`This repo (${root}): mode ${settings.mode ?? 'auto (github if the project is linked to GitHub, else local)'} · test gate ${settings.gate ? `"${settings.gate}" (${settings.gateTimeoutSec}s)` : 'off'}`);
|
|
216
|
+
}
|
|
217
|
+
if (String(process.env.INTROSIO_HOOKS ?? '').toLowerCase() === 'off') out('INTROSIO_HOOKS=off is set in this shell — hooks do nothing here.');
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function mode(positional, flags) {
|
|
221
|
+
const value = positional[1];
|
|
222
|
+
const root = repoRoot(flags);
|
|
223
|
+
const config = loadConfig(undefined, { strict: true });
|
|
224
|
+
if (!value) {
|
|
225
|
+
out(`${root}: ${repoSettings(config, root).mode ?? 'auto'}`);
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
if (value !== 'auto' && !MODES.includes(value)) return fail(`mode must be one of: ${MODES.join(', ')}, auto`);
|
|
229
|
+
saveConfig(updateRepo(config, root, { mode: value === 'auto' ? null : value }));
|
|
230
|
+
const explain = {
|
|
231
|
+
github: 'tasks complete only when the work is committed, pushed on its own branch and outcome.branch is recorded; pushes to the default branch and force pushes are blocked',
|
|
232
|
+
local: 'the code stays on this computer: tasks complete once the work is committed, and every git push is blocked',
|
|
233
|
+
off: 'no git checks before completing; push guard off',
|
|
234
|
+
auto: 'github when the Introsio project is linked to a GitHub repository, else local',
|
|
235
|
+
};
|
|
236
|
+
out(`${root}: mode ${value} — ${explain[value]}`);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async function gate(positional, flags) {
|
|
240
|
+
const action = positional[1];
|
|
241
|
+
const root = repoRoot(flags);
|
|
242
|
+
const config = loadConfig(undefined, { strict: true });
|
|
243
|
+
const settings = repoSettings(config, root);
|
|
244
|
+
if (action === 'set') {
|
|
245
|
+
const command = positional.slice(2).join(' ').trim();
|
|
246
|
+
if (!command) return fail('usage: int gate set "<command>" [--timeout <seconds>]');
|
|
247
|
+
const timeout = flags.timeout ? Number(flags.timeout) : null;
|
|
248
|
+
if (timeout !== null && !(timeout > 0)) return fail('--timeout must be a number of seconds');
|
|
249
|
+
if (timeout !== null && timeout > MAX_GATE_TIMEOUT_SEC) {
|
|
250
|
+
return fail(`--timeout can be at most ${MAX_GATE_TIMEOUT_SEC}s: agents stop a hook after 900s, and a gate cut off by the agent would let the completion through unchecked.`);
|
|
251
|
+
}
|
|
252
|
+
saveConfig(updateRepo(config, root, { gate: command, ...(timeout ? { gateTimeoutSec: timeout } : {}) }));
|
|
253
|
+
out(`${root}: claimed Introsio tasks complete only after "${command}" passes (${timeout ?? settings.gateTimeoutSec}s limit). Try it: int gate run`);
|
|
254
|
+
} else if (action === 'off') {
|
|
255
|
+
saveConfig(updateRepo(config, root, { gate: null, gateTimeoutSec: null }));
|
|
256
|
+
out(`${root}: test gate off`);
|
|
257
|
+
} else if (action === 'run') {
|
|
258
|
+
if (!settings.gate) return fail('no gate set — int gate set "<command>"');
|
|
259
|
+
out(`Running "${settings.gate}" in ${root} …`);
|
|
260
|
+
const result = await runGateCommand(settings.gate, root, settings.gateTimeoutSec);
|
|
261
|
+
out(result.output);
|
|
262
|
+
out(result.ok ? `✓ passed in ${Math.round(result.ms / 1000)}s` : result.timedOut ? `✗ timed out after ${settings.gateTimeoutSec}s` : `✗ failed (exit ${result.code})`);
|
|
263
|
+
if (!result.ok) process.exitCode = 1;
|
|
264
|
+
} else {
|
|
265
|
+
out(settings.gate ? `${root}: "${settings.gate}" (${settings.gateTimeoutSec}s)` : `${root}: no test gate — int gate set "<command>"`);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function features(positional) {
|
|
270
|
+
const [action, name] = positional;
|
|
271
|
+
const config = loadConfig(undefined, { strict: true });
|
|
272
|
+
if (action === 'enable' || action === 'disable') {
|
|
273
|
+
if (!FEATURES[name]) return fail(`unknown feature "${name}" — one of: ${Object.keys(FEATURES).join(', ')}`);
|
|
274
|
+
config.features[name] = action === 'enable';
|
|
275
|
+
saveConfig(config);
|
|
276
|
+
out(`${name}: ${action === 'enable' ? 'on' : 'off'}`);
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
for (const [feature, description] of Object.entries(FEATURES)) out(`${featureOn(config, feature) ? '✓' : '·'} ${feature.padEnd(17)} ${description}`);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function claims(positional) {
|
|
283
|
+
if (positional[1] === 'clear') {
|
|
284
|
+
out(`Cleared ${clearSessions()} session record(s) on this computer. Nothing changed in Introsio — a claim there ends when it is completed or its lease expires.`);
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
const now = Date.now();
|
|
288
|
+
const sessions = loadOtherSessions('', now).filter((session) => Object.keys(session.claims ?? {}).length);
|
|
289
|
+
if (sessions.length === 0) {
|
|
290
|
+
out('No open claims tracked on this computer.');
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
for (const session of sessions) {
|
|
294
|
+
out(`${session.agent} session ${session.sessionId} (workerId ${session.workerId ?? '?'}, ${session.cwd ?? ''})`);
|
|
295
|
+
for (const claim of Object.values(session.claims)) {
|
|
296
|
+
const lease = claim.expiresAt ? (claim.expiresAt > now ? `lease ${Math.round((claim.expiresAt - now) / 60000)} min left` : 'lease expired') : '';
|
|
297
|
+
out(` - "${claim.title}" taskId ${claim.taskId} ${lease}`);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* `int paused`: the pauses made on this computer, and tasks a session that is no
|
|
304
|
+
* longer running still holds (interrupted without a pause). Reads only local
|
|
305
|
+
* files and git — it works after the agent is gone, with no Introsio sign-in.
|
|
306
|
+
* `--prune` drops the records (and snapshot refs) of pauses older than --days (default 30).
|
|
307
|
+
*/
|
|
308
|
+
function paused(flags) {
|
|
309
|
+
const now = Date.now();
|
|
310
|
+
const pauses = listLocalPauses().sort((a, b) => Date.parse(b.at) - Date.parse(a.at));
|
|
311
|
+
if (flags.prune) {
|
|
312
|
+
const days = flags.days !== undefined && Number(flags.days) >= 0 ? Number(flags.days) : 30;
|
|
313
|
+
let pruned = 0;
|
|
314
|
+
for (const pause of pauses) {
|
|
315
|
+
if (now - Date.parse(pause.at) < days * 86_400_000) continue;
|
|
316
|
+
if (pause.ref && pause.root) createGit(pause.root).deleteRef(pause.ref);
|
|
317
|
+
removeLocalPause(pause.taskId);
|
|
318
|
+
pruned += 1;
|
|
319
|
+
}
|
|
320
|
+
out(`Removed ${pruned} pause record(s) older than ${days} days (and their snapshot refs). Nothing changed in Introsio.`);
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
const interrupted = loadOtherSessions('', now)
|
|
324
|
+
.filter((session) => Object.keys(session.claims ?? {}).length && !sessionIsLive(session, now));
|
|
325
|
+
if (pauses.length === 0 && interrupted.length === 0) {
|
|
326
|
+
out('Nothing paused or interrupted on this computer.');
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
const ago = (iso) => {
|
|
330
|
+
const minutes = Math.round((now - Date.parse(iso)) / 60_000);
|
|
331
|
+
return minutes < 90 ? `${minutes} min ago` : minutes < 2880 ? `${Math.round(minutes / 60)} h ago` : `${Math.round(minutes / 1440)} days ago`;
|
|
332
|
+
};
|
|
333
|
+
if (pauses.length) {
|
|
334
|
+
out('Paused:');
|
|
335
|
+
for (const pause of pauses) {
|
|
336
|
+
const snapshot = pause.ref && pause.root && createGit(pause.root).resolve(pause.ref) ? 'working tree saved' : (pause.dirtyFiles?.length ? 'no snapshot' : 'clean tree');
|
|
337
|
+
out(` - "${pause.title}" (taskId ${pause.taskId}) ${ago(pause.at)} by ${pause.agent ?? 'agent'}${pause.release ? ', released' : ''}`);
|
|
338
|
+
if (pause.root) out(` ${pause.root} · ${pause.branch ?? 'detached HEAD'} @ ${String(pause.head ?? '?').slice(0, 10)} · ${pause.dirtyFiles?.length ?? 0} unfinished file(s), ${snapshot}`);
|
|
339
|
+
if (pause.note) out(` ${pause.note.replace(/\s+/g, ' ').slice(0, 160)}`);
|
|
340
|
+
out(` resume: /introsio-resume ${pause.taskId}`);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
if (interrupted.length) {
|
|
344
|
+
if (pauses.length) out('');
|
|
345
|
+
out('Interrupted without a pause (the agent session is gone, its claim is still open):');
|
|
346
|
+
for (const session of interrupted) {
|
|
347
|
+
for (const claim of Object.values(session.claims)) {
|
|
348
|
+
out(` - "${claim.title}" (taskId ${claim.taskId}) — ${session.agent} session, workerId ${claim.workerId ?? session.workerId ?? '?'}${session.cwd ? `, in ${session.cwd}` : ''}`);
|
|
349
|
+
out(` resume: /introsio-resume ${claim.taskId} (it takes the task over with workerId ${claim.workerId ?? session.workerId ?? '?'})`);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function parseSince(value) {
|
|
356
|
+
const match = String(value ?? '').match(/^(\d+)([hdw])$/);
|
|
357
|
+
if (!match) return null;
|
|
358
|
+
return Date.now() - Number(match[1]) * { h: 3_600_000, d: 86_400_000, w: 604_800_000 }[match[2]];
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function stats(flags) {
|
|
362
|
+
const since = flags.since ? parseSince(flags.since) : null;
|
|
363
|
+
if (flags.since && since === null) return fail('--since takes e.g. 12h, 7d, 2w');
|
|
364
|
+
const rows = [`${logPath()}.1`, logPath()]
|
|
365
|
+
.flatMap((file) => (readText(file) ?? '').split('\n'))
|
|
366
|
+
.filter(Boolean)
|
|
367
|
+
.map((line) => { try { return JSON.parse(line); } catch { return null; } })
|
|
368
|
+
.filter(Boolean)
|
|
369
|
+
.filter((row) => (since === null || Date.parse(row.at) >= since) && (!flags.project || row.projectId === flags.project));
|
|
370
|
+
const summary = summarize(rows);
|
|
371
|
+
if (flags.json) {
|
|
372
|
+
out(JSON.stringify(summary, null, 2));
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
if (rows.length === 0) {
|
|
376
|
+
out('No Introsio calls logged yet.');
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
out(`${summary.calls} Introsio calls, ${summary.refused} refused (${Math.round((summary.refused / summary.calls) * 100)}%)`);
|
|
380
|
+
out('');
|
|
381
|
+
out('By tool:');
|
|
382
|
+
for (const tool of summary.tools) out(` ${tool.tool.padEnd(24)} ${String(tool.calls).padStart(5)} calls ${String(tool.refused).padStart(4)} refused ${tool.avgMs === null ? '' : `${tool.avgMs} ms avg`}`);
|
|
383
|
+
if (summary.topErrors.length) {
|
|
384
|
+
out('');
|
|
385
|
+
out('Most common refusals:');
|
|
386
|
+
for (const { error, count } of summary.topErrors) out(` ${String(count).padStart(4)}× ${error}`);
|
|
387
|
+
}
|
|
388
|
+
if (summary.retryLoops.length) {
|
|
389
|
+
out('');
|
|
390
|
+
out('Retry loops (same call refused 3+ times in a row):');
|
|
391
|
+
for (const loop of summary.retryLoops) out(` ${loop.tool} on ${loop.taskId}: ${loop.error ?? ''}`);
|
|
392
|
+
}
|
|
393
|
+
out('');
|
|
394
|
+
out('Tasks (most refusals first):');
|
|
395
|
+
for (const task of summary.tasks.slice(0, 15)) out(` ${task.taskId} ${task.completed ? 'done' : 'open'} ${task.calls} calls ${task.refused} refused ${task.minutes} min`);
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** Every hook command string in a parsed config. */
|
|
399
|
+
function hookCommandsIn(value, found = []) {
|
|
400
|
+
if (typeof value === 'string') {
|
|
401
|
+
if (value.includes('introsio-hook.mjs')) found.push(value);
|
|
402
|
+
} else if (value && typeof value === 'object') {
|
|
403
|
+
for (const item of Object.values(value)) hookCommandsIn(item, found);
|
|
404
|
+
}
|
|
405
|
+
return found;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function doctor(flags) {
|
|
409
|
+
let problems = 0;
|
|
410
|
+
const check = (ok, label, hint) => {
|
|
411
|
+
out(`${ok ? '✓' : '✗'} ${label}${ok || !hint ? '' : ` — ${hint}`}`);
|
|
412
|
+
if (!ok) problems += 1;
|
|
413
|
+
};
|
|
414
|
+
const major = Number(process.versions.node.split('.')[0]);
|
|
415
|
+
check(major >= 18, `Node ${process.versions.node}`, 'Node 18 or newer is required for the hooks');
|
|
416
|
+
let ctx;
|
|
417
|
+
try {
|
|
418
|
+
ctx = context(flags);
|
|
419
|
+
check(true, `settings ${configPath()}`);
|
|
420
|
+
} catch (error) {
|
|
421
|
+
check(false, `settings ${configPath()}`, `${error.message}`);
|
|
422
|
+
out('\n1 problem — fix the settings file first.');
|
|
423
|
+
process.exitCode = 1;
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
check(fs.existsSync(ctx.hookScript), `hook engine at ${ctx.kitInstallDir}`, 'run int setup');
|
|
427
|
+
const installed = (() => { try { return JSON.parse(readText(path.join(ctx.kitInstallDir, 'package.json'))).introsio; } catch { return null; } })();
|
|
428
|
+
if (installed) check(installed === VERSION, `hook engine version ${installed}`, `this int is ${VERSION} — run int setup to update the installed hooks`);
|
|
429
|
+
|
|
430
|
+
const hookFiles = ctx.scope === 'project'
|
|
431
|
+
? []
|
|
432
|
+
: [path.join(ctx.home, '.claude', 'settings.json'), path.join(ctx.home, '.codex', 'hooks.json'), path.join(ctx.home, '.gemini', 'settings.json'), path.join(ctx.home, '.cursor', 'hooks.json')];
|
|
433
|
+
const nodes = new Set();
|
|
434
|
+
for (const file of hookFiles) {
|
|
435
|
+
const text = readText(file);
|
|
436
|
+
if (!text) continue;
|
|
437
|
+
try { for (const command of hookCommandsIn(JSON.parse(text))) nodes.add(nodePathOf(command)); } catch { /* reported by the agent check */ }
|
|
438
|
+
}
|
|
439
|
+
nodes.delete('');
|
|
440
|
+
for (const node of nodes) {
|
|
441
|
+
check(fs.existsSync(node), `hooks run with ${node}`, 'that Node binary is gone (nvm / Homebrew upgrade?) — run int setup again to point the hooks at the current one');
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
for (const agent of AGENTS) {
|
|
445
|
+
if (!agent.detect(ctx)) continue;
|
|
446
|
+
const s = agent.status(ctx);
|
|
447
|
+
check(s.connect !== 'no', `${agent.label}: MCP server`, 'run int setup');
|
|
448
|
+
if (agent.hooks.startsWith('blocking')) check(s.hooks.startsWith('blocking'), `${agent.label}: hooks`, 'run int setup');
|
|
449
|
+
}
|
|
450
|
+
if (fs.existsSync(ctx.hookScript)) {
|
|
451
|
+
// Fire the installed hook, with the Node the hooks use, in a scratch state folder: a claim, then a stop — it must refuse the stop.
|
|
452
|
+
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'introsio-doctor-'));
|
|
453
|
+
const env = { ...process.env, INTROSIO_HOME: scratch, INTROSIO_HOOKS: '' };
|
|
454
|
+
const node = [...nodes].find((candidate) => fs.existsSync(candidate)) ?? process.execPath;
|
|
455
|
+
const fire = (event, payload) => spawnSync(node, [ctx.hookScript, 'claude', event], { input: JSON.stringify(payload), encoding: 'utf8', env, timeout: 20000 });
|
|
456
|
+
const started = Date.now();
|
|
457
|
+
fire('PostToolUse', {
|
|
458
|
+
session_id: 'doctor', cwd: scratch, tool_name: 'mcp__introsio__claimTask', tool_input: { projectId: 'p' },
|
|
459
|
+
tool_response: [{ type: 'text', text: JSON.stringify({ claimed: true, workerId: 'doctor', task: { id: 't1', title: 'Doctor check' } }) }],
|
|
460
|
+
});
|
|
461
|
+
const stop = fire('Stop', { session_id: 'doctor', cwd: scratch, stop_hook_active: false });
|
|
462
|
+
const ms = Date.now() - started;
|
|
463
|
+
let blocked = false;
|
|
464
|
+
try { blocked = JSON.parse(stop.stdout).decision === 'block'; } catch { /* no output */ }
|
|
465
|
+
check(blocked, `hook fires and refuses a stop with an open claim (2 calls in ${ms} ms)`, `unexpected output: ${stop.stdout || stop.stderr}`);
|
|
466
|
+
fs.rmSync(scratch, { recursive: true, force: true });
|
|
467
|
+
}
|
|
468
|
+
const errors = (readText(path.join(introsioDir(), 'errors.log')) ?? '').trim().split('\n').filter(Boolean);
|
|
469
|
+
const recent = errors.filter((line) => Date.now() - Date.parse(line.slice(0, 24)) < 7 * 86_400_000);
|
|
470
|
+
check(recent.length === 0, 'no hook errors in the last 7 days', `${recent.length} — latest: ${recent.at(-1)?.slice(0, 240)} (full log: ${path.join(introsioDir(), 'errors.log')})`);
|
|
471
|
+
out(problems ? `\n${problems} problem(s).` : '\nAll good.');
|
|
472
|
+
if (problems) process.exitCode = 1;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
function help() {
|
|
476
|
+
out(`int ${VERSION} — the Introsio agent kit: connect coding agents to Introsio and keep it updated while they execute
|
|
477
|
+
|
|
478
|
+
int setup [--agents claude,codex,gemini,cursor,opencode,vscode,windsurf] [--project <repo>] [--toolset developer|execute|all] [--url <mcp url>] [--dry-run]
|
|
479
|
+
int uninstall [--agents …] [--project <repo>]
|
|
480
|
+
int status what is installed, per agent and for this repo
|
|
481
|
+
int doctor check the install and fire a test hook
|
|
482
|
+
|
|
483
|
+
int mode github|local|off|auto this repo: push + branch required / commit only, no push / no checks
|
|
484
|
+
int gate set "<cmd>" [--timeout <sec>] | gate off | gate run | gate
|
|
485
|
+
int features | enable <name> | disable <name>
|
|
486
|
+
int claims | claims clear tasks your agents hold on this computer
|
|
487
|
+
int stats [--since 7d] [--project <id>] [--json]
|
|
488
|
+
int paused [--prune [--days 30]] work paused or interrupted on this computer, and how to resume it
|
|
489
|
+
int print-execute | print-pause | print-resume
|
|
490
|
+
a command's procedure, to paste where an agent has no commands
|
|
491
|
+
|
|
492
|
+
Inside an agent: /introsio-execute <project> · /introsio-pause [--release] · /introsio-resume [task]
|
|
493
|
+
One session without hooks: INTROSIO_HOOKS=off`);
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
async function main() {
|
|
497
|
+
const { positional, flags } = parseArgs(process.argv.slice(2));
|
|
498
|
+
const command = positional[0] ?? 'help';
|
|
499
|
+
try {
|
|
500
|
+
return await run(command, positional, flags);
|
|
501
|
+
} catch (error) {
|
|
502
|
+
return fail(error.message);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
async function run(command, positional, flags) {
|
|
507
|
+
{
|
|
508
|
+
switch (command) {
|
|
509
|
+
case 'setup': case 'install': return setup(flags);
|
|
510
|
+
case 'uninstall': case 'remove': return uninstall(flags);
|
|
511
|
+
case 'status': return status(flags);
|
|
512
|
+
case 'doctor': return doctor(flags);
|
|
513
|
+
case 'mode': return mode(positional, flags);
|
|
514
|
+
case 'gate': return gate(positional, flags);
|
|
515
|
+
case 'features': return features([]);
|
|
516
|
+
case 'enable': case 'disable': return features(positional);
|
|
517
|
+
case 'claims': return claims(positional);
|
|
518
|
+
case 'stats': return stats(flags);
|
|
519
|
+
case 'paused': return paused(flags);
|
|
520
|
+
case 'print-execute': case 'print-pause': case 'print-resume': {
|
|
521
|
+
const chosen = COMMANDS.find((item) => item.name === `introsio-${command.slice('print-'.length)}`);
|
|
522
|
+
return out(commandText(context(flags), chosen, chosen.name === 'introsio-execute' ? 'the project the user names' : 'what the user names'));
|
|
523
|
+
}
|
|
524
|
+
case 'hook': {
|
|
525
|
+
// `int hook <agent> <event>` — the same entry as introsio-hook.mjs, for package-manager installs.
|
|
526
|
+
process.argv = [process.argv[0], path.join(KIT_SOURCE, 'hook', 'introsio-hook.mjs'), ...positional.slice(1)];
|
|
527
|
+
await import('./hook/introsio-hook.mjs');
|
|
528
|
+
return undefined;
|
|
529
|
+
}
|
|
530
|
+
case 'version': case '--version': return out(VERSION);
|
|
531
|
+
default: return help();
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
main();
|