introsio 0.1.0 → 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/agents/vscode.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  // VS Code (GitHub Copilot agent mode): MCP in the user mcp.json and a /introsio-execute prompt file. No hooks.
2
- import { join, editJson, executeText, existsDir, existsFile, SERVER_NAME, COMMAND_NAME, DESCRIPTION } from './common.mjs';
2
+ import { join, editJson, commandText, writeCommands, removeCommands, commandsStatus, existsDir, SERVER_NAME, COMMAND_NAME } from './common.mjs';
3
3
  import { readJsonSafe } from '../lib/jsonFile.mjs';
4
4
 
5
5
  function userDir(ctx) {
@@ -9,9 +9,11 @@ function userDir(ctx) {
9
9
  return join(ctx.home, '.config', 'Code', 'User');
10
10
  }
11
11
 
12
- const paths = (ctx) => (ctx.scope === 'project'
13
- ? { mcp: join(ctx.root, '.vscode', 'mcp.json'), command: join(ctx.root, '.github', 'prompts', `${COMMAND_NAME}.prompt.md`) }
14
- : { mcp: join(userDir(ctx), 'mcp.json'), command: join(userDir(ctx), 'prompts', `${COMMAND_NAME}.prompt.md`) });
12
+ const paths = (ctx) => {
13
+ const prompts = ctx.scope === 'project' ? join(ctx.root, '.github', 'prompts') : join(userDir(ctx), 'prompts');
14
+ const commandFile = (name) => join(prompts, `${name}.prompt.md`);
15
+ return { mcp: ctx.scope === 'project' ? join(ctx.root, '.vscode', 'mcp.json') : join(userDir(ctx), 'mcp.json'), command: commandFile(COMMAND_NAME), commandFile };
16
+ };
15
17
 
16
18
  export default {
17
19
  id: 'vscode',
@@ -30,16 +32,16 @@ export default {
30
32
  });
31
33
  report.connect = mcp.error ?? (mcp.manual ? `manual — add "${SERVER_NAME}": { "type": "http", "url": "${ctx.url}" } under "servers" in ${p.mcp}` : mcp.changed ? 'added' : 'already connected');
32
34
  report.next.push('In VS Code: open mcp.json and click Start above "introsio" to sign in. Then in Copilot Chat (Agent mode): /introsio-execute <project>');
33
- writer.writeText(p.command, `---\nmode: agent\ndescription: ${DESCRIPTION}\n---\n\n${executeText(ctx, '${input:project:Project name or id}')}\n`);
35
+ writeCommands(writer, p.commandFile, (command) => `---\nmode: agent\ndescription: ${command.description}\n---\n\n${commandText(ctx, command, `\${input:args:${command.inputLabel}}`)}\n`);
34
36
  return report;
35
37
  },
36
38
  uninstall(ctx, writer) {
37
39
  const p = paths(ctx);
38
40
  editJson(writer, p.mcp, (config) => (config.servers?.[SERVER_NAME] ? (delete config.servers[SERVER_NAME], true) : false));
39
- writer.remove(p.command);
41
+ removeCommands(writer, p.commandFile);
40
42
  },
41
43
  status(ctx) {
42
44
  const p = paths(ctx);
43
- return { connect: readJsonSafe(p.mcp, {}).servers?.[SERVER_NAME] ? 'yes' : 'no', command: existsFile(p.command), hooks: 'none' };
45
+ return { connect: readJsonSafe(p.mcp, {}).servers?.[SERVER_NAME] ? 'yes' : 'no', command: commandsStatus(p.commandFile), hooks: 'none' };
44
46
  },
45
47
  };
@@ -20,7 +20,7 @@ export default {
20
20
  return true;
21
21
  });
22
22
  report.connect = mcp.error ?? (mcp.manual ? `manual — add "${SERVER_NAME}": { "serverUrl": "${ctx.url}" } to ${file}` : mcp.changed ? 'added' : 'already connected');
23
- report.next.push('In Windsurf: Cascade → MCP servers → refresh, sign in to introsio. For the execute procedure run `int print-execute` and save it as a Windsurf rule or workflow.');
23
+ report.next.push('In Windsurf: Cascade → MCP servers → refresh, sign in to introsio. For the procedures run `int print-execute`, `int print-pause` and `int print-resume` and save each as a Windsurf workflow.');
24
24
  return report;
25
25
  },
26
26
  uninstall(ctx, writer) {
package/cli.mjs CHANGED
@@ -1,4 +1,4 @@
1
- #!/usr/bin/env node
1
+ #!/usr/bin/env node
2
2
  // int — the Introsio agent kit: connect coding agents to Introsio, run projects with
3
3
  // /introsio-execute, and manage the hooks that keep Introsio updated.
4
4
  import fs from 'node:fs';
@@ -7,7 +7,7 @@ import path from 'node:path';
7
7
  import { spawnSync } from 'node:child_process';
8
8
  import { fileURLToPath } from 'node:url';
9
9
  import { AGENTS, agentById } from './agents/index.mjs';
10
- import { Writer, nodePathOf } from './agents/common.mjs';
10
+ import { Writer, nodePathOf, COMMANDS, commandText } from './agents/common.mjs';
11
11
  import { FEATURES, MODES, loadConfig, saveConfig, repoSettings, updateRepo, featureOn } from './lib/config.mjs';
12
12
  import { MAX_GATE_TIMEOUT_SEC } from './hook/features/gates.mjs';
13
13
  import { createGit } from './lib/git.mjs';
@@ -16,9 +16,31 @@ import { readText } from './lib/jsonFile.mjs';
16
16
  import { loadOtherSessions, clearSessions } from './hook/state.mjs';
17
17
  import { summarize } from './hook/features/log.mjs';
18
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';
19
21
 
20
22
  const KIT_SOURCE = path.dirname(fileURLToPath(import.meta.url));
21
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
+ }
22
44
  const KIT_DIRS = ['hook', 'lib'];
23
45
  const VERSION = JSON.parse(readText(path.join(KIT_SOURCE, 'package.json')) ?? '{"version":"0"}').version;
24
46
 
@@ -57,12 +79,13 @@ function context(flags, env = process.env) {
57
79
  scope,
58
80
  root,
59
81
  platform: process.platform,
60
- url: typeof flags.url === 'string' ? flags.url : (config.mcpUrl ?? DEFAULT_URL),
82
+ url: mcpUrlFor(flags, config),
61
83
  kitSource: KIT_SOURCE,
62
84
  kitInstallDir,
63
85
  hookScript: path.join(kitInstallDir, 'hook', 'introsio-hook.mjs'),
64
86
  nodePath: process.execPath,
65
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)) ?? ''])),
66
89
  };
67
90
  }
68
91
 
@@ -101,6 +124,7 @@ function suggestGate(dir) {
101
124
  }
102
125
 
103
126
  function setup(flags) {
127
+ if (flags.toolset !== undefined && !KIT_TOOLSETS.includes(flags.toolset)) return fail(`--toolset takes one of: ${KIT_TOOLSETS.join(', ')}`);
104
128
  const ctx = context(flags);
105
129
  if (flags.print) {
106
130
  const agent = agentById(String(flags.print));
@@ -125,16 +149,16 @@ function setup(flags) {
125
149
  const report = agent.install(ctx, writer);
126
150
  out(`● ${agent.label}`);
127
151
  out(` connect: ${report.connect}`);
128
- if (report.command) out(` command: /introsio-execute → ${report.command}`);
152
+ if (report.command) out(` commands: /introsio-execute, /introsio-pause, /introsio-resume → ${path.dirname(report.command)}`);
129
153
  out(` hooks: ${report.hooks}`);
130
154
  for (const line of report.next) next.push(`${agent.label}: ${line}`);
131
155
  } catch (error) {
132
156
  out(`● ${agent.label}: failed — ${error.message}`);
133
157
  }
134
158
  }
135
- if (!flags['dry-run'] && typeof flags.url === 'string') {
159
+ if (!flags['dry-run'] && (typeof flags.url === 'string' || typeof flags.toolset === 'string')) {
136
160
  const config = loadConfig(undefined, { strict: true });
137
- config.mcpUrl = flags.url;
161
+ config.mcpUrl = ctx.url;
138
162
  saveConfig(config);
139
163
  }
140
164
  out('');
@@ -180,7 +204,7 @@ function status(flags) {
180
204
  for (const agent of AGENTS) {
181
205
  if (!agent.detect(ctx)) continue;
182
206
  const s = agent.status(ctx);
183
- out(`● ${agent.label.padEnd(18)} connect: ${s.connect.padEnd(4)} /introsio-execute: ${String(s.command).padEnd(4)} hooks: ${s.hooks}`);
207
+ out(`● ${agent.label.padEnd(18)} connect: ${s.connect.padEnd(4)} commands: ${String(s.command).padEnd(4)} hooks: ${s.hooks}`);
184
208
  }
185
209
  const config = loadConfig(undefined, { strict: true });
186
210
  out('');
@@ -275,6 +299,59 @@ function claims(positional) {
275
299
  }
276
300
  }
277
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
+
278
355
  function parseSince(value) {
279
356
  const match = String(value ?? '').match(/^(\d+)([hdw])$/);
280
357
  if (!match) return null;
@@ -398,7 +475,7 @@ function doctor(flags) {
398
475
  function help() {
399
476
  out(`int ${VERSION} — the Introsio agent kit: connect coding agents to Introsio and keep it updated while they execute
400
477
 
401
- int setup [--agents claude,codex,gemini,cursor,opencode,vscode,windsurf] [--project <repo>] [--url <mcp url>] [--dry-run]
478
+ int setup [--agents claude,codex,gemini,cursor,opencode,vscode,windsurf] [--project <repo>] [--toolset developer|execute|all] [--url <mcp url>] [--dry-run]
402
479
  int uninstall [--agents …] [--project <repo>]
403
480
  int status what is installed, per agent and for this repo
404
481
  int doctor check the install and fire a test hook
@@ -408,9 +485,12 @@ function help() {
408
485
  int features | enable <name> | disable <name>
409
486
  int claims | claims clear tasks your agents hold on this computer
410
487
  int stats [--since 7d] [--project <id>] [--json]
411
- int print-execute the /introsio-execute procedure, to paste where an agent has no commands
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
412
491
 
413
- Inside an agent: /introsio-execute <project> One session without hooks: INTROSIO_HOOKS=off`);
492
+ Inside an agent: /introsio-execute <project> · /introsio-pause [--release] · /introsio-resume [task]
493
+ One session without hooks: INTROSIO_HOOKS=off`);
414
494
  }
415
495
 
416
496
  async function main() {
@@ -436,7 +516,11 @@ async function run(command, positional, flags) {
436
516
  case 'enable': case 'disable': return features(positional);
437
517
  case 'claims': return claims(positional);
438
518
  case 'stats': return stats(flags);
439
- case 'print-execute': return out(context(flags).executeTemplate.replaceAll('$ARGUMENTS', 'the project the user names'));
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
+ }
440
524
  case 'hook': {
441
525
  // `int hook <agent> <event>` — the same entry as introsio-hook.mjs, for package-manager installs.
442
526
  process.argv = [process.argv[0], path.join(KIT_SOURCE, 'hook', 'introsio-hook.mjs'), ...positional.slice(1)];
package/hook/engine.mjs CHANGED
@@ -12,14 +12,15 @@ import { gateCachePath, sessionsDir, relativeInside } from '../lib/paths.mjs';
12
12
  import { readJsonSafe, writeJson } from '../lib/jsonFile.mjs';
13
13
  import { acquireLock } from '../lib/lock.mjs';
14
14
  import { agentPid } from '../lib/processTree.mjs';
15
- import { loadSession, saveSession, loadOtherSessions, sessionExists, sessionFile } from './state.mjs';
15
+ import { loadSession, saveSession, saveSessionUnlocked, loadOtherSessions, sessionExists, sessionFile } from './state.mjs';
16
16
  import { applyIntrosioResult, updateClaimsFromTranscript, isCompletionCall } from './features/claims.mjs';
17
17
  import { stopDecision } from './features/stopGuard.mjs';
18
18
  import { makeWorkerId, workerIdDecision } from './features/workerId.mjs';
19
- import { shippedDecision, planTestGate, runTestGate, resolveMode } from './features/gates.mjs';
19
+ import { shippedDecision, planTestGate, runTestGate, resolveMode, workTreeKey } from './features/gates.mjs';
20
20
  import { pushDecision, secretsDecision } from './features/git.mjs';
21
21
  import { scopeNote, leaseNote, recoveryNote, rereadDecision } from './features/notes.mjs';
22
22
  import { logRow, writeLog } from './features/log.mjs';
23
+ import { pauseDecision, recordPause, forgetPause, pauseInAnswer, resumeReport, formatReport, readLocalPause, interruptedNote } from './features/pause.mjs';
23
24
 
24
25
  const NONE = Object.freeze({ type: 'none' });
25
26
  const GIT_WRITE = /\bgit\b[^\n]*\b(push|commit)\b/;
@@ -79,6 +80,8 @@ export async function handleEvent(evt, deps = {}) {
79
80
  const config = loadConfig(env);
80
81
  const on = (feature) => featureOn(config, feature);
81
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;
82
85
  session.lastSeenAt = now;
83
86
  session.agent = evt.agent;
84
87
  if (evt.cwd) session.cwd = evt.cwd;
@@ -114,6 +117,7 @@ export async function handleEvent(evt, deps = {}) {
114
117
  answer = firstDeny(
115
118
  () => (on('worker-id') ? workerIdDecision(session, loadOtherSessions(session.sessionId, now, env), tool, now, deps.isAlive) : NONE),
116
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),
117
121
  () => (completing && on('shipped-gate') ? shippedDecision({ git: git(), settings: settingsHere(), claim, args: tool.args, session }) : NONE),
118
122
  );
119
123
  if (answer.type !== 'deny' && completing && on('test-gate')) {
@@ -147,7 +151,9 @@ export async function handleEvent(evt, deps = {}) {
147
151
  if (tool.kind === 'introsio') {
148
152
  session.sawIntrosioResult = true;
149
153
  const hadClaims = Object.keys(session.claims).length;
154
+ const pausedClaim = tool.name === 'pauseTask' ? session.claims[String(tool.args?.taskId ?? '')] : null;
150
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 }));
151
157
  if (on('log')) writeLog(logRow(session, evt, { name: tool.name, args: tool.args, result: evt.result }, now), env);
152
158
  if (tool.name === 'claimTask' && Object.keys(session.claims).length > hadClaims && !session.modeNoted && on('shipped-gate')) {
153
159
  const claim = Object.values(session.claims).at(-1);
@@ -190,7 +196,10 @@ export async function handleEvent(evt, deps = {}) {
190
196
  default:
191
197
  }
192
198
  // A transcript offset is worth keeping even before any Introsio call: the next stop then reads only what is new.
193
- if (existed || session.introsio || session.transcript) saveSession(session, env);
199
+ if (existed || session.introsio || session.transcript) {
200
+ if (loaded) await saveSessionUnlocked(loaded, session, env);
201
+ else saveSession(session, env);
202
+ }
194
203
  } finally {
195
204
  release();
196
205
  }
@@ -201,6 +210,70 @@ export async function handleEvent(evt, deps = {}) {
201
210
  return answer;
202
211
  }
203
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
+
204
277
  function readSmallFile(file) {
205
278
  try {
206
279
  const stat = fs.statSync(file);
@@ -38,7 +38,10 @@ export function isCompletionCall(name, args) {
38
38
 
39
39
  const RELEASING_STATES = new Set(['blocked', 'pending']);
40
40
 
41
- const TASK_TOOLS = new Set(['completeTask', 'updateTask', 'updateSubtask', 'undoTaskCompletion', 'claimTask', 'getTaskById']);
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']);
42
45
 
43
46
  /**
44
47
  * A refusal that proves this session no longer holds the task: the task is gone
@@ -51,18 +54,43 @@ function lostClaim(session, { name, args = {}, result }) {
51
54
  const data = result?.data;
52
55
  if (!claim || !data || !TASK_TOOLS.has(name)) return false;
53
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;
54
59
  const holder = data.claimedBy?.workerId ?? data.details?.claimedBy?.workerId;
55
60
  return Number(data.status) === 409 && !!holder && holder !== claim.workerId && holder !== args.workerId;
56
61
  }
57
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
+
58
84
  /** Applies one Introsio tool answer to the session. */
59
85
  export function applyIntrosioResult(session, { name, args = {}, result }, now) {
60
86
  session.introsio = true;
61
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);
62
90
  if (!result?.ok && lostClaim(session, { name, args, result })) {
63
91
  const claim = session.claims[String(args.taskId)];
64
92
  delete session.claims[String(args.taskId)];
65
- session.notes = [...(session.notes ?? []), `Introsio: you no longer hold "${claim.title}" (${Number(data.status) === 404 ? 'the task no longer exists' : `worker ${data.claimedBy?.workerId ?? data.details?.claimedBy?.workerId} holds it now`}). Leave it and claimTask the next one.`].slice(-3);
93
+ session.notes = [...(session.notes ?? []), `Introsio: you no longer hold "${claim.title}" (${lostReason(data)}). Leave it and claimTask the next one.`].slice(-3);
66
94
  return;
67
95
  }
68
96
  if (!result?.ok || !data) return;
@@ -134,6 +162,11 @@ export function applyIntrosioResult(session, { name, args = {}, result }, now) {
134
162
  }
135
163
  return;
136
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
+ }
137
170
  case 'updateSubtask': {
138
171
  const claim = session.claims[String(args.taskId ?? '')];
139
172
  if (!claim) return;
@@ -41,10 +41,41 @@ export function shellCommands(command) {
41
41
  return commands;
42
42
  }
43
43
 
44
+ const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh']);
45
+ /** Words that run the rest of the line as a command (`env A=1 git …`, `sudo git …`). */
46
+ const PREFIXES = new Set(['env', 'sudo', 'command', 'exec', 'nohup', 'time', 'nice']);
47
+ const MAX_WRAPPER_DEPTH = 3;
48
+
49
+ /**
50
+ * The script a wrapper runs, when the command is one: `bash -c "…"`, `sh -lc '…'`,
51
+ * `eval "…"` (also behind env/sudo prefixes). Its text is checked like a command
52
+ * line of its own, so `bash -c "git push origin main"` is guarded the same as the
53
+ * bare push. A guard-rail for agents, not a sandbox: a script file or another
54
+ * interpreter (`python -c`) is not looked into.
55
+ */
56
+ function wrappedScript(words) {
57
+ let i = 0;
58
+ while (i < words.length && (PREFIXES.has(words[i].split('/').pop()) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i]))) i += 1;
59
+ const head = words[i]?.split('/').pop();
60
+ if (head === 'eval') return words.slice(i + 1).join(' ');
61
+ if (!SHELLS.has(head)) return null;
62
+ for (let j = i + 1; j < words.length; j += 1) {
63
+ // `-c` alone or in a cluster (`-lc`, `-ec`); the script is the next word.
64
+ if (/^-[a-zA-Z]*c[a-zA-Z]*$/.test(words[j])) return words[j + 1] ?? null;
65
+ if (!words[j].startsWith('-')) return null;
66
+ }
67
+ return null;
68
+ }
69
+
44
70
  /** Every `git … <sub>` invocation in a shell command line, as argv arrays after `git`. */
45
- export function gitInvocations(command) {
71
+ export function gitInvocations(command, depth = 0) {
46
72
  const out = [];
47
73
  for (const words of shellCommands(command)) {
74
+ const script = depth < MAX_WRAPPER_DEPTH ? wrappedScript(words) : null;
75
+ if (script !== null) {
76
+ out.push(...gitInvocations(script, depth + 1));
77
+ continue;
78
+ }
48
79
  const gitAt = words.findIndex((token) => token === 'git' || token.endsWith('/git'));
49
80
  if (gitAt < 0) continue;
50
81
  const args = words.slice(gitAt + 1);
@@ -62,7 +93,12 @@ export function gitInvocations(command) {
62
93
  */
63
94
  export function pushDecision({ command, mode, git, defaultBranch }) {
64
95
  const pushes = gitInvocations(command).filter((call) => call.sub === 'push');
65
- if (pushes.length === 0 || mode === 'off') return { type: 'none' };
96
+ if (pushes.length === 0) return { type: 'none' };
97
+ // Pause snapshots (refs/introsio/paused/*) hold unfinished work and stay on this computer, whatever the mode.
98
+ if (pushes.some(({ args }) => args.some((arg) => /(^|:|\+)refs\/introsio\//.test(arg)))) {
99
+ return { type: 'deny', message: 'Introsio: refs/introsio/* are local pause snapshots of unfinished work — they are never pushed. To hand work over, commit it on a branch and push that (or /introsio-pause --release).' };
100
+ }
101
+ if (mode === 'off') return { type: 'none' };
66
102
  if (mode === 'local') {
67
103
  return { type: 'deny', message: 'Introsio (local mode): this repository stays on this computer — git push is blocked. Commit locally; switch with `int mode github` if it should go to GitHub.' };
68
104
  }
@@ -73,10 +109,14 @@ export function pushDecision({ command, mode, git, defaultBranch }) {
73
109
  return { type: 'deny', message: 'Introsio: force push is blocked. Use --force-with-lease on your own branch if you really must rewrite it.' };
74
110
  }
75
111
  if (args.includes('--mirror')) return { type: 'deny', message: 'Introsio: git push --mirror is blocked.' };
112
+ // Every local branch — the default one included — so it cannot be checked target by target.
113
+ if (args.includes('--all') || args.includes('--branches')) {
114
+ return { type: 'deny', message: `Introsio: git push --all is blocked — it pushes every local branch, "${main || 'the default branch'}" included. Push your own branch by name (git push -u origin <name>).` };
115
+ }
76
116
  const positional = args.filter((arg) => !arg.startsWith('-'));
77
117
  const deleting = args.includes('--delete') || args.includes('-d');
78
118
  const refspecs = positional.slice(1);
79
- if (args.includes('--all') || args.includes('--tags')) continue;
119
+ if (args.includes('--tags')) continue;
80
120
  // A bare push goes where push.default sends it — possibly main from a branch with another name.
81
121
  const bareTarget = () => {
82
122
  const push = git.pushTarget?.();
@@ -60,6 +60,8 @@ export function recoveryNote(session) {
60
60
  ].filter(Boolean);
61
61
  lines.push(`You hold "${claim.title}" (taskId ${claim.taskId}${claim.projectId ? `, project ${claim.projectId}` : ''})${parts.length ? ` — ${parts.join(', ')}` : ''}. Continue it (getReadySubtasks shows the next step), then completeTask with outcome.`);
62
62
  }
63
+ const paused = Object.entries(session.paused ?? {});
64
+ if (paused.length) lines.push(`You paused: ${paused.map(([id, item]) => `"${item.title}" (taskId ${id})`).join(', ')} — /introsio-resume takes them back after checking the repository.`);
63
65
  if (claims.length === 0) lines.push('You hold no task. claimTask { projectId, workerId } takes the next one.');
64
66
  return lines.join('\n');
65
67
  }