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/hook/engine.mjs
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
// The one decision point every agent's hooks go through: a normalized event in,
|
|
2
|
+
// an answer ({ type: none | deny | context | block | warn, message }) out.
|
|
3
|
+
//
|
|
4
|
+
// Concurrency: agents run the hooks of parallel tool calls at the same time, so
|
|
5
|
+
// every read-modify-write of a session happens under that session's lock. The
|
|
6
|
+
// test gate (minutes) runs after the lock is released.
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { loadConfig, featureOn, repoSettings } from '../lib/config.mjs';
|
|
10
|
+
import { createGit } from '../lib/git.mjs';
|
|
11
|
+
import { gateCachePath, sessionsDir, relativeInside } from '../lib/paths.mjs';
|
|
12
|
+
import { readJsonSafe, writeJson } from '../lib/jsonFile.mjs';
|
|
13
|
+
import { acquireLock } from '../lib/lock.mjs';
|
|
14
|
+
import { agentPid } from '../lib/processTree.mjs';
|
|
15
|
+
import { loadSession, saveSession, saveSessionUnlocked, loadOtherSessions, sessionExists, sessionFile } from './state.mjs';
|
|
16
|
+
import { applyIntrosioResult, updateClaimsFromTranscript, isCompletionCall } from './features/claims.mjs';
|
|
17
|
+
import { stopDecision } from './features/stopGuard.mjs';
|
|
18
|
+
import { makeWorkerId, workerIdDecision } from './features/workerId.mjs';
|
|
19
|
+
import { shippedDecision, planTestGate, runTestGate, resolveMode, workTreeKey } from './features/gates.mjs';
|
|
20
|
+
import { pushDecision, secretsDecision } from './features/git.mjs';
|
|
21
|
+
import { scopeNote, leaseNote, recoveryNote, rereadDecision } from './features/notes.mjs';
|
|
22
|
+
import { logRow, writeLog } from './features/log.mjs';
|
|
23
|
+
import { pauseDecision, recordPause, forgetPause, pauseInAnswer, resumeReport, formatReport, readLocalPause, interruptedNote } from './features/pause.mjs';
|
|
24
|
+
|
|
25
|
+
const NONE = Object.freeze({ type: 'none' });
|
|
26
|
+
const GIT_WRITE = /\bgit\b[^\n]*\b(push|commit)\b/;
|
|
27
|
+
// Agents whose after-tool hook may not see MCP calls: their stop check falls back to the transcript.
|
|
28
|
+
const TRANSCRIPT_FALLBACK = new Set(['codex', 'gemini']);
|
|
29
|
+
const MAX_EDITED_FILES = 500;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Whether an event can matter to a session that has never used Introsio. Most
|
|
33
|
+
* tool calls in most sessions are not Introsio's: those return at once, with no
|
|
34
|
+
* state file read or written.
|
|
35
|
+
*/
|
|
36
|
+
function relevantWithoutSession(evt) {
|
|
37
|
+
if (evt.tool?.kind === 'introsio') return true;
|
|
38
|
+
if (evt.tool?.kind === 'shell' && GIT_WRITE.test(evt.tool.command ?? '')) return true;
|
|
39
|
+
return evt.event === 'stop' && !!evt.transcriptPath && TRANSCRIPT_FALLBACK.has(evt.agent);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function gateCache(env) {
|
|
43
|
+
const file = gateCachePath(env);
|
|
44
|
+
return {
|
|
45
|
+
get: (root) => readJsonSafe(file, {})[root],
|
|
46
|
+
set: (root, value) => {
|
|
47
|
+
const data = readJsonSafe(file, {});
|
|
48
|
+
data[root] = value;
|
|
49
|
+
writeJson(file, data);
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function firstDeny(...decisions) {
|
|
55
|
+
for (const decide of decisions) {
|
|
56
|
+
const answer = decide();
|
|
57
|
+
if (answer?.type === 'deny') return answer;
|
|
58
|
+
}
|
|
59
|
+
return NONE;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const context = (notes) => {
|
|
63
|
+
const text = notes.filter(Boolean).join('\n');
|
|
64
|
+
return text ? { type: 'context', message: text } : NONE;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
export async function handleEvent(evt, deps = {}) {
|
|
68
|
+
const env = deps.env ?? process.env;
|
|
69
|
+
if (!evt || String(env.INTROSIO_HOOKS ?? '').toLowerCase() === 'off') return NONE;
|
|
70
|
+
const existed = sessionExists(evt.sessionId, env);
|
|
71
|
+
if (!existed && !relevantWithoutSession(evt)) return NONE;
|
|
72
|
+
|
|
73
|
+
fs.mkdirSync(sessionsDir(env), { recursive: true });
|
|
74
|
+
const release = await acquireLock(sessionFile(evt.sessionId, env));
|
|
75
|
+
let gatePlan = null;
|
|
76
|
+
let gateClaim = null;
|
|
77
|
+
let answer = NONE;
|
|
78
|
+
try {
|
|
79
|
+
const now = deps.now ?? Date.now();
|
|
80
|
+
const config = loadConfig(env);
|
|
81
|
+
const on = (feature) => featureOn(config, feature);
|
|
82
|
+
const session = loadSession(evt.sessionId, evt.agent, now, env);
|
|
83
|
+
// Without the lock (another hook held it too long), only this hook's own changes are saved.
|
|
84
|
+
const loaded = release.acquired === false ? structuredClone(session) : null;
|
|
85
|
+
session.lastSeenAt = now;
|
|
86
|
+
session.agent = evt.agent;
|
|
87
|
+
if (evt.cwd) session.cwd = evt.cwd;
|
|
88
|
+
if (!session.workerId) session.workerId = makeWorkerId(evt.agent, evt.sessionId, deps.hostname);
|
|
89
|
+
if (!session.agentPid && evt.agent !== 'opencode') session.agentPid = deps.agentPid ?? agentPid();
|
|
90
|
+
|
|
91
|
+
let gitHandle = null;
|
|
92
|
+
const git = () => (gitHandle ??= (deps.createGit ?? createGit)(evt.cwd ?? session.cwd ?? process.cwd()));
|
|
93
|
+
const settingsHere = () => repoSettings(config, git().root());
|
|
94
|
+
|
|
95
|
+
switch (evt.event) {
|
|
96
|
+
case 'session-start': {
|
|
97
|
+
if (evt.source === 'compact' || session.contextLost) {
|
|
98
|
+
session.contextLost = false;
|
|
99
|
+
if (on('compact-recovery')) answer = context([recoveryNote(session)]);
|
|
100
|
+
}
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
case 'compact': {
|
|
104
|
+
session.contextRead = {};
|
|
105
|
+
session.rereadDenied = {};
|
|
106
|
+
if (session.lastCompletion) session.lastCompletion.rereadDenied = true;
|
|
107
|
+
session.contextLost = true;
|
|
108
|
+
break;
|
|
109
|
+
}
|
|
110
|
+
case 'before-tool': {
|
|
111
|
+
const tool = evt.tool ?? {};
|
|
112
|
+
if (tool.kind === 'introsio') {
|
|
113
|
+
session.introsio = true;
|
|
114
|
+
session.pending[tool.name] = now;
|
|
115
|
+
const claim = session.claims[String(tool.args?.taskId ?? '')];
|
|
116
|
+
const completing = claim && isCompletionCall(tool.name, tool.args);
|
|
117
|
+
answer = firstDeny(
|
|
118
|
+
() => (on('worker-id') ? workerIdDecision(session, loadOtherSessions(session.sessionId, now, env), tool, now, deps.isAlive) : NONE),
|
|
119
|
+
() => (on('reread') ? rereadDecision(session, tool) : NONE),
|
|
120
|
+
() => (tool.name === 'pauseTask' && on('pause') ? pauseDecision({ git: git(), args: tool.args, session, now, budgetMs: deps.snapshotBudgetMs }) : NONE),
|
|
121
|
+
() => (completing && on('shipped-gate') ? shippedDecision({ git: git(), settings: settingsHere(), claim, args: tool.args, session }) : NONE),
|
|
122
|
+
);
|
|
123
|
+
if (answer.type !== 'deny' && completing && on('test-gate')) {
|
|
124
|
+
gatePlan = planTestGate({ git: git(), settings: settingsHere(), cache: gateCache(env) });
|
|
125
|
+
gateClaim = claim;
|
|
126
|
+
}
|
|
127
|
+
} else if (tool.kind === 'shell' && GIT_WRITE.test(tool.command ?? '')) {
|
|
128
|
+
const root = git().root();
|
|
129
|
+
const settings = repoSettings(config, root);
|
|
130
|
+
const claim = Object.values(session.claims)[0];
|
|
131
|
+
const active = session.introsio || settings.mode || settings.gate;
|
|
132
|
+
if (!root || !active) break;
|
|
133
|
+
const mode = resolveMode(settings, claim);
|
|
134
|
+
let note = null;
|
|
135
|
+
answer = firstDeny(
|
|
136
|
+
() => (on('push-guard') ? pushDecision({ command: tool.command, mode, git: git(), defaultBranch: claim?.repository?.defaultBranch }) : NONE),
|
|
137
|
+
() => {
|
|
138
|
+
if (!on('secrets')) return NONE;
|
|
139
|
+
const decision = secretsDecision({ command: tool.command, git: git(), readFile: (file) => readSmallFile(path.join(root, file)) });
|
|
140
|
+
note = decision.note ?? null;
|
|
141
|
+
return decision;
|
|
142
|
+
},
|
|
143
|
+
);
|
|
144
|
+
if (answer.type !== 'deny' && note) session.notes = [...(session.notes ?? []), note].slice(-3);
|
|
145
|
+
}
|
|
146
|
+
break;
|
|
147
|
+
}
|
|
148
|
+
case 'after-tool': {
|
|
149
|
+
const tool = evt.tool ?? {};
|
|
150
|
+
const notes = [];
|
|
151
|
+
if (tool.kind === 'introsio') {
|
|
152
|
+
session.sawIntrosioResult = true;
|
|
153
|
+
const hadClaims = Object.keys(session.claims).length;
|
|
154
|
+
const pausedClaim = tool.name === 'pauseTask' ? session.claims[String(tool.args?.taskId ?? '')] : null;
|
|
155
|
+
applyIntrosioResult(session, { name: tool.name, args: tool.args, result: evt.result }, now);
|
|
156
|
+
if (on('pause')) notes.push(...pauseNotes({ tool, result: evt.result, session, pausedClaim, git, config, env, now, deps }));
|
|
157
|
+
if (on('log')) writeLog(logRow(session, evt, { name: tool.name, args: tool.args, result: evt.result }, now), env);
|
|
158
|
+
if (tool.name === 'claimTask' && Object.keys(session.claims).length > hadClaims && !session.modeNoted && on('shipped-gate')) {
|
|
159
|
+
const claim = Object.values(session.claims).at(-1);
|
|
160
|
+
session.modeNoted = true;
|
|
161
|
+
if (resolveMode(settingsHere(), claim) === 'local' && git().root()) {
|
|
162
|
+
notes.push('Introsio (local mode): this repository stays on this computer. Commit your work locally (no push), then completeTask with the commit id in outcome.summary.');
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
} else if (tool.kind === 'edit') {
|
|
166
|
+
const root = git().root();
|
|
167
|
+
const edited = new Set(session.editedFiles ?? []);
|
|
168
|
+
for (const file of tool.files ?? []) {
|
|
169
|
+
const rel = relativeInside(root, file);
|
|
170
|
+
if (rel) edited.add(rel);
|
|
171
|
+
}
|
|
172
|
+
session.editedFiles = [...edited].slice(-MAX_EDITED_FILES);
|
|
173
|
+
if (on('scope')) notes.push(scopeNote(session, tool.files ?? [], root));
|
|
174
|
+
}
|
|
175
|
+
if (session.notes?.length) {
|
|
176
|
+
notes.push(...session.notes);
|
|
177
|
+
session.notes = [];
|
|
178
|
+
}
|
|
179
|
+
if (session.contextLost && on('compact-recovery')) {
|
|
180
|
+
session.contextLost = false;
|
|
181
|
+
notes.push(recoveryNote(session));
|
|
182
|
+
}
|
|
183
|
+
if (on('lease')) notes.push(leaseNote(session, now));
|
|
184
|
+
answer = context(notes);
|
|
185
|
+
break;
|
|
186
|
+
}
|
|
187
|
+
case 'stop': {
|
|
188
|
+
if (!on('stop-guard')) break;
|
|
189
|
+
if (!session.sawIntrosioResult && evt.transcriptPath && TRANSCRIPT_FALLBACK.has(evt.agent)) {
|
|
190
|
+
// This agent's after-tool hook never saw an Introsio call: read the transcript instead.
|
|
191
|
+
updateClaimsFromTranscript(session, evt.transcriptPath, now, fs);
|
|
192
|
+
}
|
|
193
|
+
answer = stopDecision(session, evt, now);
|
|
194
|
+
break;
|
|
195
|
+
}
|
|
196
|
+
default:
|
|
197
|
+
}
|
|
198
|
+
// A transcript offset is worth keeping even before any Introsio call: the next stop then reads only what is new.
|
|
199
|
+
if (existed || session.introsio || session.transcript) {
|
|
200
|
+
if (loaded) await saveSessionUnlocked(loaded, session, env);
|
|
201
|
+
else saveSession(session, env);
|
|
202
|
+
}
|
|
203
|
+
} finally {
|
|
204
|
+
release();
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
if (gatePlan) {
|
|
208
|
+
return runTestGate(gatePlan, { claim: gateClaim, cache: gateCache(env), runGate: deps.runGate, now: deps.now ?? Date.now() });
|
|
209
|
+
}
|
|
210
|
+
return answer;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Feature `pause`, after an Introsio answer: keep the snapshot of a pause that
|
|
215
|
+
* landed, drop it once the task is done, check the repository against any pause
|
|
216
|
+
* an answer carries, and say so when a task was left by a session that died.
|
|
217
|
+
*/
|
|
218
|
+
function pauseNotes({ tool, result, session, pausedClaim, git, config, env, now, deps }) {
|
|
219
|
+
const data = result?.data;
|
|
220
|
+
const notes = [];
|
|
221
|
+
const root = () => git().root();
|
|
222
|
+
const gatePassed = () => {
|
|
223
|
+
const settings = repoSettings(config, root());
|
|
224
|
+
if (!settings.gate) return null;
|
|
225
|
+
const key = workTreeKey(git(), settings.gate);
|
|
226
|
+
return !!key && readJsonSafe(gateCachePath(env), {})[root()]?.key === key;
|
|
227
|
+
};
|
|
228
|
+
if (tool.name === 'pauseTask' && result?.ok && data?.success !== false) {
|
|
229
|
+
if (pausedClaim) session.claims[String(tool.args?.taskId)] = pausedClaim; // recordPause reads the title / files once more
|
|
230
|
+
const record = recordPause({ git: root() ? git() : null, session, args: tool.args, data, now, env, gatePassed: root() ? gatePassed() : null });
|
|
231
|
+
delete session.claims[String(tool.args?.taskId)];
|
|
232
|
+
if (record) {
|
|
233
|
+
notes.push(`Introsio: paused "${record.title}".${record.snapshot ? ` The working tree is saved as ${record.ref} (local only, never pushed; your files are untouched).` : record.snapshotError ? ` No snapshot of the working tree (${record.snapshotError}) — resume will compare file lists only.` : ''}` +
|
|
234
|
+
` Resume later with /introsio-resume ${record.taskId}.`);
|
|
235
|
+
}
|
|
236
|
+
return notes;
|
|
237
|
+
}
|
|
238
|
+
if (tool.name === 'completeTask' && result?.ok && data?.task?.completed !== false && tool.args?.taskId) {
|
|
239
|
+
forgetPause({ git: root() ? git() : null, taskId: String(tool.args.taskId), env });
|
|
240
|
+
if (session.paused) delete session.paused[String(tool.args.taskId)];
|
|
241
|
+
return notes;
|
|
242
|
+
}
|
|
243
|
+
const found = result?.ok ? pauseInAnswer(tool.name, data) : null;
|
|
244
|
+
if (found?.resumed && session.paused) delete session.paused[found.taskId];
|
|
245
|
+
if (found) {
|
|
246
|
+
const key = `${found.taskId}:${found.pause?.at ?? ''}:${found.resumed ? 'r' : 'p'}`;
|
|
247
|
+
session.resumeChecked = session.resumeChecked ?? {};
|
|
248
|
+
if (session.resumeChecked[key]) return notes;
|
|
249
|
+
session.resumeChecked[key] = now;
|
|
250
|
+
const report = resumeReport({
|
|
251
|
+
git: root() ? git() : null,
|
|
252
|
+
taskId: found.taskId,
|
|
253
|
+
pause: found.pause,
|
|
254
|
+
local: readLocalPause(found.taskId, env),
|
|
255
|
+
others: loadOtherSessions(session.sessionId, now, env),
|
|
256
|
+
now,
|
|
257
|
+
alive: deps.isAlive,
|
|
258
|
+
taskChanged: found.changed === true,
|
|
259
|
+
gatePassedNow: root() ? gatePassed() : null,
|
|
260
|
+
});
|
|
261
|
+
const title = data.title ?? data.name ?? data.task?.title ?? found.taskId;
|
|
262
|
+
notes.push(formatReport(title, report, { resumed: found.resumed }));
|
|
263
|
+
return notes;
|
|
264
|
+
}
|
|
265
|
+
// Interrupted without a pause: the task is held by a session on this computer whose agent died.
|
|
266
|
+
const taskId = String(tool.args?.taskId ?? data?.id ?? '');
|
|
267
|
+
const claimWorkerId = tool.name === 'getTaskById' && result?.ok
|
|
268
|
+
? data?.claim?.workerId
|
|
269
|
+
: (!result?.ok && Number(data?.status) === 409 ? (data?.claimedBy?.workerId ?? data?.details?.claimedBy?.workerId) : null);
|
|
270
|
+
if (taskId && claimWorkerId && claimWorkerId !== session.workerId) {
|
|
271
|
+
const note = interruptedNote({ taskId, claimWorkerId, others: loadOtherSessions(session.sessionId, now, env), now, alive: deps.isAlive });
|
|
272
|
+
if (note) notes.push(note);
|
|
273
|
+
}
|
|
274
|
+
return notes;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function readSmallFile(file) {
|
|
278
|
+
try {
|
|
279
|
+
const stat = fs.statSync(file);
|
|
280
|
+
if (!stat.isFile() || stat.size > 1024 * 1024) return '';
|
|
281
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
282
|
+
return text.includes('\u0000') ? '' : text;
|
|
283
|
+
} catch {
|
|
284
|
+
return '';
|
|
285
|
+
}
|
|
286
|
+
}
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
// Tracks which Introsio tasks this session holds, from the tools' own answers.
|
|
2
|
+
// Only a successful answer changes anything: a refused call means the agent must fix what the error names.
|
|
3
|
+
|
|
4
|
+
const PATH_IN_BACKTICKS = /`([^`\s]+)`/g;
|
|
5
|
+
const BARE_PATH = /(?:^|[\s(])((?:[\w@.-]+\/)+[\w@.-]+\.[A-Za-z0-9]+)(?=$|[\s),:;]|\.(?:\s|$))/gm;
|
|
6
|
+
|
|
7
|
+
/** File and folder paths a task spec names (`src/a.js`, src/b/, …). */
|
|
8
|
+
export function extractPaths(text) {
|
|
9
|
+
const found = new Set();
|
|
10
|
+
const add = (candidate) => {
|
|
11
|
+
const value = candidate.replace(/^\.\//, '').replace(/[.,;:]+$/, '');
|
|
12
|
+
if (!value || /^[a-z]+:\/\//i.test(value) || value.startsWith('@') || value.includes('*')) return;
|
|
13
|
+
if (value.includes('/') || /\.[A-Za-z0-9]{1,6}$/.test(value)) found.add(value);
|
|
14
|
+
};
|
|
15
|
+
for (const match of String(text ?? '').matchAll(PATH_IN_BACKTICKS)) add(match[1]);
|
|
16
|
+
for (const match of String(text ?? '').matchAll(BARE_PATH)) add(match[1]);
|
|
17
|
+
return [...found].slice(0, 100);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const time = (value) => {
|
|
21
|
+
const parsed = Date.parse(value ?? '');
|
|
22
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const countSubtasks = (task) => {
|
|
26
|
+
const waves = Array.isArray(task?.subtaskWaves) ? task.subtaskWaves.flat() : [];
|
|
27
|
+
const done = Number(task?.completedSubtasks) || 0;
|
|
28
|
+
return { total: waves.length + done, done };
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
function rememberRevision(session, projectId, revision) {
|
|
32
|
+
if (projectId && Number.isFinite(Number(revision))) session.contextRevision[projectId] = Number(revision);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function isCompletionCall(name, args) {
|
|
36
|
+
return name === 'completeTask' || (name === 'updateTask' && args?.completed === true);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const RELEASING_STATES = new Set(['blocked', 'pending']);
|
|
40
|
+
|
|
41
|
+
/** The code the server answers when a project reset revoked this worker's claim (agentExecutionService). */
|
|
42
|
+
const REVOKED_BY_RESET = 'CLAIM_REVOKED_BY_RESET';
|
|
43
|
+
|
|
44
|
+
const TASK_TOOLS = new Set(['completeTask', 'updateTask', 'updateSubtask', 'undoTaskCompletion', 'claimTask', 'getTaskById', 'pauseTask']);
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* A refusal that proves this session no longer holds the task: the task is gone
|
|
48
|
+
* (404), or another worker holds it now (409 naming someone else). Keeping such
|
|
49
|
+
* a claim would refuse every stop for a task nobody here can finish.
|
|
50
|
+
*/
|
|
51
|
+
function lostClaim(session, { name, args = {}, result }) {
|
|
52
|
+
const id = String(args.taskId ?? '');
|
|
53
|
+
const claim = session.claims[id];
|
|
54
|
+
const data = result?.data;
|
|
55
|
+
if (!claim || !data || !TASK_TOOLS.has(name)) return false;
|
|
56
|
+
if (Number(data.status) === 404) return true;
|
|
57
|
+
// The person reset the project's execution while this session held the task (its work no longer counts).
|
|
58
|
+
if (data.code === REVOKED_BY_RESET) return true;
|
|
59
|
+
const holder = data.claimedBy?.workerId ?? data.details?.claimedBy?.workerId;
|
|
60
|
+
return Number(data.status) === 409 && !!holder && holder !== claim.workerId && holder !== args.workerId;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const lostReason = (data) => {
|
|
64
|
+
if (Number(data.status) === 404) return 'the task no longer exists';
|
|
65
|
+
if (data.code === REVOKED_BY_RESET) return "the project's execution was reset, so that work no longer counts";
|
|
66
|
+
return `worker ${data.claimedBy?.workerId ?? data.details?.claimedBy?.workerId} holds it now`;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/** The code the server answers when a plan limit refuses a call (backend services/billing, ADR-0016). */
|
|
70
|
+
const PLAN_LIMIT_REACHED = 'PLAN_LIMIT_REACHED';
|
|
71
|
+
/** The daily MCP budgets: once one is used up, every metered call is refused until it resets. */
|
|
72
|
+
const DAILY_BUDGETS = new Set(['mcpPersonalPerDay', 'mcpDeveloperPerDay']);
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The note for a call refused because the day's budget is used up. Nothing to
|
|
76
|
+
* release: a refused claimTask leaves no claim (so the agent may stop), and
|
|
77
|
+
* pausing or completing a held task is a reporting call the budget never refuses.
|
|
78
|
+
*/
|
|
79
|
+
function budgetNote(data) {
|
|
80
|
+
if (data?.code !== PLAN_LIMIT_REACHED || !DAILY_BUDGETS.has(data.key)) return null;
|
|
81
|
+
return `Introsio budget reached, resets ${data.resetsAt ?? 'at midnight (the user\'s time)'}; pause what you hold and tell the user.`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Applies one Introsio tool answer to the session. */
|
|
85
|
+
export function applyIntrosioResult(session, { name, args = {}, result }, now) {
|
|
86
|
+
session.introsio = true;
|
|
87
|
+
const data = result?.data;
|
|
88
|
+
const budget = result?.ok ? null : budgetNote(data);
|
|
89
|
+
if (budget && !(session.notes ?? []).includes(budget)) session.notes = [...(session.notes ?? []), budget].slice(-3);
|
|
90
|
+
if (!result?.ok && lostClaim(session, { name, args, result })) {
|
|
91
|
+
const claim = session.claims[String(args.taskId)];
|
|
92
|
+
delete session.claims[String(args.taskId)];
|
|
93
|
+
session.notes = [...(session.notes ?? []), `Introsio: you no longer hold "${claim.title}" (${lostReason(data)}). Leave it and claimTask the next one.`].slice(-3);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
if (!result?.ok || !data) return;
|
|
97
|
+
|
|
98
|
+
const projectId = data.project?.id ?? args.projectId ?? null;
|
|
99
|
+
if (data.context && typeof data.context === 'object') rememberRevision(session, projectId, data.context.revision);
|
|
100
|
+
|
|
101
|
+
switch (name) {
|
|
102
|
+
case 'claimTask': {
|
|
103
|
+
session.lastCompletion = null;
|
|
104
|
+
if (data.claimed !== true || !data.task?.id) return;
|
|
105
|
+
const id = String(data.task.id);
|
|
106
|
+
const previous = session.claims[id];
|
|
107
|
+
const expiresAt = time(data.leaseExpiresAt);
|
|
108
|
+
session.claims[id] = {
|
|
109
|
+
taskId: id,
|
|
110
|
+
title: data.task.title ?? previous?.title ?? id,
|
|
111
|
+
workerId: data.workerId ?? previous?.workerId ?? null,
|
|
112
|
+
projectId,
|
|
113
|
+
claimedAt: previous?.claimedAt ?? now,
|
|
114
|
+
lastWriteAt: now,
|
|
115
|
+
expiresAt,
|
|
116
|
+
leaseMs: expiresAt ? Math.max(60_000, expiresAt - now) : 30 * 60_000,
|
|
117
|
+
nudgedAt: null,
|
|
118
|
+
repository: data.repository ?? null,
|
|
119
|
+
branch: data.task.outcome?.branch ?? previous?.branch ?? null,
|
|
120
|
+
files: extractPaths(data.task.description),
|
|
121
|
+
subtasks: countSubtasks(data.task),
|
|
122
|
+
};
|
|
123
|
+
if (data.workerId) session.workerId = data.workerId;
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
case 'completeTask': {
|
|
127
|
+
const id = String(args.taskId ?? data.task?.id ?? '');
|
|
128
|
+
if (data.task && data.task.completed === false) return;
|
|
129
|
+
delete session.claims[id];
|
|
130
|
+
session.lastCompletion = {
|
|
131
|
+
taskId: id,
|
|
132
|
+
at: now,
|
|
133
|
+
nowReady: Array.isArray(data.nowReady) ? data.nowReady.map((task) => task.id).filter(Boolean) : [],
|
|
134
|
+
projectComplete: data.projectComplete === true,
|
|
135
|
+
rereadDenied: false,
|
|
136
|
+
};
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
case 'updateTask': {
|
|
140
|
+
const id = String(args.taskId ?? data.task?.id ?? '');
|
|
141
|
+
const claim = session.claims[id];
|
|
142
|
+
if (args.completed === true || (Object.hasOwn(args, 'statusState') && (args.statusState === null || RELEASING_STATES.has(args.statusState)))) {
|
|
143
|
+
delete session.claims[id];
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
if (args.statusState === 'in_progress' && !claim && data.task?.id) {
|
|
147
|
+
const expiresAt = time(data.task.claim?.expiresAt);
|
|
148
|
+
session.claims[id] = {
|
|
149
|
+
taskId: id, title: data.task.title ?? id, workerId: data.task.claim?.workerId ?? args.workerId ?? null,
|
|
150
|
+
projectId, claimedAt: now, lastWriteAt: now, expiresAt,
|
|
151
|
+
leaseMs: expiresAt ? Math.max(60_000, expiresAt - now) : 30 * 60_000,
|
|
152
|
+
nudgedAt: null, repository: null, branch: args.outcome?.branch ?? null, files: [], subtasks: { total: 0, done: 0 },
|
|
153
|
+
};
|
|
154
|
+
if (session.claims[id].workerId) session.workerId = session.workerId ?? session.claims[id].workerId;
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
if (claim) {
|
|
158
|
+
claim.lastWriteAt = now;
|
|
159
|
+
const expiresAt = time(data.task?.claim?.expiresAt);
|
|
160
|
+
if (expiresAt) claim.expiresAt = expiresAt;
|
|
161
|
+
if (args.outcome?.branch) claim.branch = args.outcome.branch;
|
|
162
|
+
}
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
case 'pauseTask': {
|
|
166
|
+
// Paused (ADR-0011): the task waits for a resume, so this session no longer holds it.
|
|
167
|
+
delete session.claims[String(args.taskId ?? data.task?.id ?? '')];
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
case 'updateSubtask': {
|
|
171
|
+
const claim = session.claims[String(args.taskId ?? '')];
|
|
172
|
+
if (!claim) return;
|
|
173
|
+
claim.lastWriteAt = now;
|
|
174
|
+
const expiresAt = time(data.task?.claim?.expiresAt);
|
|
175
|
+
if (expiresAt) claim.expiresAt = expiresAt;
|
|
176
|
+
const counts = data.task?.subtasks;
|
|
177
|
+
if (counts && Number.isFinite(counts.total)) claim.subtasks = { total: counts.total, done: counts.total - (Number(counts.open) || 0) };
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
case 'getProjectContext': {
|
|
181
|
+
const pid = args.projectId ?? null;
|
|
182
|
+
if (pid && Number.isFinite(Number(data.revision))) {
|
|
183
|
+
rememberRevision(session, pid, data.revision);
|
|
184
|
+
session.contextRead[pid] = Number(data.revision);
|
|
185
|
+
}
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
case 'getProjectState':
|
|
189
|
+
case 'getExecutionWaves': {
|
|
190
|
+
const pid = args.projectId ?? null;
|
|
191
|
+
rememberRevision(session, pid, data.context?.revision ?? data.contextRevision);
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
default:
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Fallback for agents whose after-tool hook does not see MCP calls: rebuild the
|
|
200
|
+
* open set from the transcript. Format-agnostic — it looks for the Introsio
|
|
201
|
+
* answers themselves (a claim's work packet, a completion receipt), which are
|
|
202
|
+
* distinctive JSON wherever the agent stores them.
|
|
203
|
+
*/
|
|
204
|
+
export function claimsFromTranscript(text, now, claims = {}) {
|
|
205
|
+
const visit = (value, depth) => {
|
|
206
|
+
if (depth > 8 || value === null || value === undefined) return;
|
|
207
|
+
if (typeof value === 'string') {
|
|
208
|
+
const trimmed = value.trim();
|
|
209
|
+
if (trimmed.startsWith('{') && (trimmed.includes('"claimed"') || trimmed.includes('"nowReady"'))) {
|
|
210
|
+
try { visit(JSON.parse(trimmed), depth + 1); } catch { /* not JSON */ }
|
|
211
|
+
}
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
if (Array.isArray(value)) { value.forEach((item) => visit(item, depth + 1)); return; }
|
|
215
|
+
if (typeof value !== 'object') return;
|
|
216
|
+
if (value.claimed === true && value.task?.id) {
|
|
217
|
+
claims[value.task.id] = { taskId: value.task.id, title: value.task.title ?? value.task.id, workerId: value.workerId ?? null, claimedAt: now, lastWriteAt: now, expiresAt: time(value.leaseExpiresAt), files: [], subtasks: countSubtasks(value.task) };
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
if (value.success === true && Array.isArray(value.nowReady) && value.task?.id && value.task.completed === true) {
|
|
221
|
+
delete claims[value.task.id];
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
Object.values(value).forEach((item) => visit(item, depth + 1));
|
|
225
|
+
};
|
|
226
|
+
for (const line of String(text ?? '').split('\n')) {
|
|
227
|
+
if (!line.includes('claimed') && !line.includes('nowReady')) continue;
|
|
228
|
+
try { visit(JSON.parse(line), 0); } catch { /* a partial line */ }
|
|
229
|
+
}
|
|
230
|
+
return claims;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const TRANSCRIPT_TAIL_LIMIT = 256 * 1024 * 1024;
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Reads only what the transcript gained since the last stop (offset kept in the
|
|
237
|
+
* session), so a long session is never re-parsed from the start. A transcript
|
|
238
|
+
* that shrank or was replaced is read again from the beginning.
|
|
239
|
+
*/
|
|
240
|
+
export function updateClaimsFromTranscript(session, file, now, fsImpl) {
|
|
241
|
+
let stat;
|
|
242
|
+
try { stat = fsImpl.statSync(file); } catch { return; }
|
|
243
|
+
const previous = session.transcript?.path === file ? session.transcript : null;
|
|
244
|
+
let offset = previous && previous.offset <= stat.size ? previous.offset : 0;
|
|
245
|
+
const claims = offset > 0 ? { ...(previous.claims ?? {}) } : {};
|
|
246
|
+
if (stat.size - offset > TRANSCRIPT_TAIL_LIMIT) offset = stat.size - TRANSCRIPT_TAIL_LIMIT;
|
|
247
|
+
if (stat.size > offset) {
|
|
248
|
+
const fd = fsImpl.openSync(file, 'r');
|
|
249
|
+
try {
|
|
250
|
+
const buffer = Buffer.alloc(stat.size - offset);
|
|
251
|
+
fsImpl.readSync(fd, buffer, 0, buffer.length, offset);
|
|
252
|
+
let text = buffer.toString('utf8');
|
|
253
|
+
// Keep a partial last line for next time.
|
|
254
|
+
const lastNewline = text.lastIndexOf('\n');
|
|
255
|
+
const complete = lastNewline >= 0 ? text.slice(0, lastNewline + 1) : '';
|
|
256
|
+
claimsFromTranscript(complete, now, claims);
|
|
257
|
+
offset += Buffer.byteLength(complete);
|
|
258
|
+
text = null;
|
|
259
|
+
} finally {
|
|
260
|
+
fsImpl.closeSync(fd);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
session.transcript = { path: file, offset, claims };
|
|
264
|
+
session.claims = { ...claims, ...Object.fromEntries(Object.entries(session.claims).filter(([id]) => claims[id])) };
|
|
265
|
+
}
|