micro-models-agent 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Heuristic detection of long-running (server/watch) commands.
3
+ *
4
+ * The explicit `background: true` bash parameter always wins; this list is a
5
+ * convenience so dev servers don't block the agent. It only inspects the raw
6
+ * shell command (a technical process-type decision, not task classification).
7
+ */
8
+ const LONG_RUNNING_PATTERNS = [
9
+ /\b(npm|pnpm|yarn|bun|npx)\s+(run\s+)?(dev|start|serve|preview|watch|server)\b/i,
10
+ /\b(deno|node)\s+.*\b(run\s+)?(dev|serve|watch|server)\b/i,
11
+ /(^|\s)--watch\b/i,
12
+ /(^|\s)-w\b/i,
13
+ /\bnodemon\b/i,
14
+ /\btsx watch\b/i,
15
+ /\b(ts-node|tsc)\s+.*--watch\b/i,
16
+ /\bvite(?!\s+(build|create))\b/i,
17
+ /\bwebpack(-dev-server|\s+serve)\b/i,
18
+ /\bastro dev\b/i,
19
+ /\bnext (dev|start)\b/i,
20
+ /\bnuxt (dev|start)\b/i,
21
+ /\bsvelte-kit (dev|preview)\b/i,
22
+ /\bgatsby develop\b/i,
23
+ /\bdocker(-compose)?\s+.*\bup\b/i,
24
+ /\buvicorn\b|\bgunicorn\b/i,
25
+ /\bpython\s+-m\s+http\.server\b/i,
26
+ /\bflask run\b/i,
27
+ /\bphp artisan serve\b/i,
28
+ /\brails (server|s)\b/i,
29
+ /\bvitest watch\b/i,
30
+ /\bjest --watch\b/i,
31
+ ];
32
+ export function isLongRunningCommand(command) {
33
+ return LONG_RUNNING_PATTERNS.some((pattern) => pattern.test(command));
34
+ }
@@ -0,0 +1,3 @@
1
+ export { runCommand, killByCallId } from "./runner";
2
+ export { processRegistry } from "./registry";
3
+ export { isLongRunningCommand } from "./detect";
@@ -0,0 +1,142 @@
1
+ import { spawn } from "child_process";
2
+ import { platform } from "os";
3
+ const MAX_LOG_LINES = 300;
4
+ const MAX_KEPT_PROCESSES = 20;
5
+ let seq = 0;
6
+ function killTree(child) {
7
+ const pid = child.pid;
8
+ if (!pid)
9
+ return;
10
+ if (platform() === "win32") {
11
+ spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
12
+ windowsHide: true,
13
+ stdio: "ignore",
14
+ });
15
+ return;
16
+ }
17
+ try {
18
+ process.kill(-pid, "SIGTERM");
19
+ }
20
+ catch {
21
+ try {
22
+ child.kill("SIGKILL");
23
+ }
24
+ catch {
25
+ /* already dead */
26
+ }
27
+ }
28
+ }
29
+ class ProcessRegistry {
30
+ procs = new Map();
31
+ children = new Map();
32
+ /**
33
+ * Start a background process. Returns immediately with the entry; output is
34
+ * buffered into `entry.log` as it arrives.
35
+ */
36
+ start(command, cwd, sessionId) {
37
+ const id = `proc_${Date.now()}_${++seq}`;
38
+ const entry = {
39
+ id,
40
+ pid: 0,
41
+ command,
42
+ cwd,
43
+ sessionId,
44
+ status: "running",
45
+ exitCode: null,
46
+ startedAt: new Date().toISOString(),
47
+ log: [],
48
+ };
49
+ this.trimOldEntries();
50
+ this.procs.set(id, entry);
51
+ const child = spawn(command, {
52
+ cwd,
53
+ shell: true,
54
+ windowsHide: true,
55
+ detached: platform() !== "win32",
56
+ stdio: ["ignore", "pipe", "pipe"],
57
+ });
58
+ this.children.set(id, child);
59
+ entry.pid = child.pid ?? 0;
60
+ let partial = "";
61
+ const append = (chunk) => {
62
+ const text = partial + chunk.toString();
63
+ const lines = text.split(/\r?\n/);
64
+ partial = lines.pop() ?? "";
65
+ for (const line of lines) {
66
+ if (entry.log.length >= MAX_LOG_LINES) {
67
+ entry.log.shift();
68
+ }
69
+ entry.log.push(line);
70
+ }
71
+ };
72
+ child.stdout?.on("data", append);
73
+ child.stderr?.on("data", append);
74
+ child.on("error", (err) => {
75
+ if (entry.status === "running") {
76
+ entry.status = "killed";
77
+ }
78
+ append(Buffer.from(`[process error] ${err.message}`));
79
+ });
80
+ child.on("close", (code) => {
81
+ if (entry.status === "running") {
82
+ entry.status = "exited";
83
+ }
84
+ entry.exitCode = code;
85
+ this.children.delete(id);
86
+ if (partial) {
87
+ entry.log.push(partial);
88
+ partial = "";
89
+ }
90
+ });
91
+ return entry;
92
+ }
93
+ list(sessionId) {
94
+ const all = Array.from(this.procs.values());
95
+ if (!sessionId)
96
+ return all;
97
+ return all.filter((p) => p.sessionId === sessionId);
98
+ }
99
+ get(id) {
100
+ return this.procs.get(id);
101
+ }
102
+ getLog(id, tail) {
103
+ const entry = this.procs.get(id);
104
+ if (!entry)
105
+ return "";
106
+ const lines = tail && tail > 0 ? entry.log.slice(-tail) : entry.log;
107
+ return lines.join("\n");
108
+ }
109
+ /** Kill a background process tree. Returns false when not found. */
110
+ kill(id) {
111
+ const entry = this.procs.get(id);
112
+ if (!entry)
113
+ return false;
114
+ if (entry.status === "running") {
115
+ entry.status = "killed";
116
+ const child = this.children.get(id);
117
+ if (child) {
118
+ killTree(child);
119
+ }
120
+ }
121
+ return true;
122
+ }
123
+ /** Kill every managed background process (used on agent shutdown). */
124
+ killAll(sessionId) {
125
+ const targets = this.list(sessionId);
126
+ for (const entry of targets) {
127
+ this.kill(entry.id);
128
+ }
129
+ return targets.length;
130
+ }
131
+ trimOldEntries() {
132
+ if (this.procs.size < MAX_KEPT_PROCESSES)
133
+ return;
134
+ const sorted = Array.from(this.procs.values()).sort((a, b) => a.startedAt.localeCompare(b.startedAt));
135
+ const toRemove = sorted.slice(0, sorted.length - MAX_KEPT_PROCESSES + 1);
136
+ for (const entry of toRemove) {
137
+ this.procs.delete(entry.id);
138
+ this.children.delete(entry.id);
139
+ }
140
+ }
141
+ }
142
+ export const processRegistry = new ProcessRegistry();
@@ -0,0 +1,109 @@
1
+ import { spawn } from "child_process";
2
+ import { platform } from "os";
3
+ const activeChildren = new Map();
4
+ /**
5
+ * Kill a foreground command previously registered by `callId` (used by the
6
+ * tool executor when the execution timeout fires). Returns true when a child
7
+ * was found and killed.
8
+ */
9
+ export function killByCallId(callId) {
10
+ const entry = activeChildren.get(callId);
11
+ if (!entry)
12
+ return false;
13
+ activeChildren.delete(callId);
14
+ try {
15
+ entry.kill();
16
+ }
17
+ catch {
18
+ /* already dead */
19
+ }
20
+ return true;
21
+ }
22
+ function killTree(child) {
23
+ const pid = child.pid;
24
+ if (!pid)
25
+ return;
26
+ if (platform() === "win32") {
27
+ spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
28
+ windowsHide: true,
29
+ stdio: "ignore",
30
+ });
31
+ return;
32
+ }
33
+ try {
34
+ // `detached: true` makes the child a process-group leader on POSIX,
35
+ // so killing -pid terminates the whole tree.
36
+ process.kill(-pid, "SIGTERM");
37
+ }
38
+ catch {
39
+ try {
40
+ child.kill("SIGKILL");
41
+ }
42
+ catch {
43
+ /* already dead */
44
+ }
45
+ }
46
+ }
47
+ /**
48
+ * Run a shell command asynchronously (non-blocking event loop) and collect
49
+ * stdout/stderr. The child is killed on timeout and can be killed externally
50
+ * via `killByCallId` (used by the tool executor timeout).
51
+ */
52
+ export function runCommand(command, options = {}) {
53
+ const { cwd, callId, timeoutMs = 120_000, maxBuffer = 10 * 1024 * 1024, } = options;
54
+ return new Promise((resolve) => {
55
+ let timedOut = false;
56
+ let stdout = "";
57
+ let stderr = "";
58
+ const child = spawn(command, {
59
+ cwd,
60
+ shell: true,
61
+ windowsHide: true,
62
+ detached: platform() !== "win32",
63
+ stdio: ["ignore", "pipe", "pipe"],
64
+ });
65
+ const append = (ref, chunk) => {
66
+ const text = chunk.toString();
67
+ const next = ref.value.length + text.length;
68
+ if (next > maxBuffer) {
69
+ ref.value =
70
+ ref.value.slice(ref.value.length + text.length - maxBuffer) + text;
71
+ }
72
+ else {
73
+ ref.value = ref.value + text;
74
+ }
75
+ };
76
+ const stdoutRef = { value: stdout };
77
+ const stderrRef = { value: stderr };
78
+ child.stdout?.on("data", (chunk) => append(stdoutRef, chunk));
79
+ child.stderr?.on("data", (chunk) => append(stderrRef, chunk));
80
+ const entry = {
81
+ kill: () => killTree(child),
82
+ };
83
+ if (callId) {
84
+ activeChildren.set(callId, entry);
85
+ }
86
+ const timer = setTimeout(() => {
87
+ timedOut = true;
88
+ killTree(child);
89
+ }, timeoutMs);
90
+ child.on("error", () => {
91
+ clearTimeout(timer);
92
+ if (callId)
93
+ activeChildren.delete(callId);
94
+ resolve({
95
+ stdout: stdoutRef.value,
96
+ stderr: stderrRef.value,
97
+ code: null,
98
+ signal: null,
99
+ timedOut,
100
+ });
101
+ });
102
+ child.on("close", (code, signal) => {
103
+ clearTimeout(timer);
104
+ if (callId)
105
+ activeChildren.delete(callId);
106
+ resolve({ stdout: stdoutRef.value, stderr: stderrRef.value, code, signal, timedOut });
107
+ });
108
+ });
109
+ }
@@ -1,9 +1,11 @@
1
- import { execSync } from 'child_process';
2
- import { platform } from 'os';
3
1
  import { isCommandAllowed, sanitizeCommandForLog } from '../modules/security/command-validator';
4
2
  import { logBashCommand, logSecurityBlock } from '../modules/security/audit-log';
5
3
  import { getSessionSecurityConfig } from '../modules/security/session-isolation';
6
4
  import { DEFAULT_SECURITY_CONFIG } from '../config/security';
5
+ import { runCommand, processRegistry, isLongRunningCommand } from '../modules/processes';
6
+ import { t } from '../i18n/index';
7
+ import { platform } from 'os';
8
+ const BASH_TIMEOUT_MS = 120_000;
7
9
  function adaptCommandForWindows(command) {
8
10
  if (platform() !== 'win32')
9
11
  return command;
@@ -19,13 +21,14 @@ function adaptCommandForWindows(command) {
19
21
  }
20
22
  export const bashTool = {
21
23
  name: 'bash',
22
- description: 'Execute a shell command and return its output. Use for running tests, build, git, and shell operations.',
24
+ description: 'Execute a shell command and return its output. Use for running tests, build, git, and shell operations. Long-running commands (dev servers, watchers) start in the background and return a process id immediately — manage them with process_list, process_log, process_kill. Set background=true to force background execution.',
23
25
  tags: ['shell', 'code'],
24
26
  parameters: {
25
27
  type: 'object',
26
28
  properties: {
27
29
  command: { type: 'string', description: 'Shell command to execute' },
28
30
  workdir: { type: 'string', description: 'Working directory (default: baseDir)' },
31
+ background: { type: 'boolean', description: 'Start the command in the background and return immediately with a process id (default: auto-detect long-running commands)' },
29
32
  },
30
33
  required: ['command'],
31
34
  },
@@ -53,28 +56,52 @@ export const bashTool = {
53
56
  logBashCommand(ctx.sessionId, sanitizeCommandForLog(command), false, // Will be updated after execution
54
57
  `Working directory: ${workdir}`);
55
58
  }
59
+ const background = args.background === true || isLongRunningCommand(command);
60
+ if (background) {
61
+ const entry = processRegistry.start(command, workdir, ctx.sessionId);
62
+ if (securityConfig?.logCommands) {
63
+ logBashCommand(ctx.sessionId, sanitizeCommandForLog(command), true, `Started in background: ${entry.id} (PID ${entry.pid})`);
64
+ }
65
+ const explicit = args.background === true;
66
+ return {
67
+ success: true,
68
+ output: `${t("proc.started", {
69
+ id: entry.id,
70
+ pid: entry.pid,
71
+ command,
72
+ })}${explicit ? "" : `\n${t("proc.detected_hint")}`}\n${t("proc.manage_hint", {
73
+ id: entry.id,
74
+ })}`,
75
+ };
76
+ }
56
77
  try {
57
- const output = execSync(command, {
78
+ const res = await runCommand(command, {
58
79
  cwd: workdir,
59
- encoding: 'utf-8',
60
- maxBuffer: 10 * 1024 * 1024,
61
- timeout: 120_000,
80
+ callId: ctx.activeCallId,
81
+ timeoutMs: BASH_TIMEOUT_MS,
62
82
  });
63
- // Update audit log with success
83
+ const parts = [res.stdout.trimEnd(), res.stderr.trimEnd()].filter(Boolean);
84
+ let output = parts.join("\n");
85
+ if (res.timedOut) {
86
+ output = `${output ? output + "\n" : ""}${t("proc.timed_out", {
87
+ ms: BASH_TIMEOUT_MS,
88
+ })}`;
89
+ }
90
+ else if (!output && res.code !== 0) {
91
+ output = `(exit code ${res.code})`;
92
+ }
93
+ // Update audit log with result
64
94
  if (securityConfig?.logCommands) {
65
- logBashCommand(ctx.sessionId, sanitizeCommandForLog(command), true, `Working directory: ${workdir}, Output length: ${output.length}`);
95
+ logBashCommand(ctx.sessionId, sanitizeCommandForLog(command), res.code === 0, `Working directory: ${workdir}, Output length: ${res.stdout.length}`);
66
96
  }
67
- return { success: true, output: output.trimEnd() };
97
+ return { success: res.code === 0, output };
68
98
  }
69
99
  catch (e) {
70
- const stderr = e.stderr?.toString() || '';
71
- const stdout = e.stdout?.toString() || '';
72
- const errorOutput = stderr || stdout || e.message;
73
100
  // Update audit log with failure
74
101
  if (securityConfig?.logCommands) {
75
- logBashCommand(ctx.sessionId, sanitizeCommandForLog(command), false, `Working directory: ${workdir}, Error: ${errorOutput.slice(0, 100)}`);
102
+ logBashCommand(ctx.sessionId, sanitizeCommandForLog(command), false, `Working directory: ${workdir}, Error: ${e.message?.slice(0, 100) || ""}`);
76
103
  }
77
- return { success: false, output: errorOutput };
104
+ return { success: false, output: e.message || String(e) };
78
105
  }
79
106
  },
80
107
  };
@@ -1,3 +1,4 @@
1
+ import { killByCallId } from "../modules/processes/runner";
1
2
  import { t } from "../i18n/index";
2
3
  const TOOL_EXECUTION_TIMEOUT_MS = 60000;
3
4
  export class ToolExecutor {
@@ -39,16 +40,21 @@ export class ToolExecutor {
39
40
  }
40
41
  let result;
41
42
  try {
43
+ this.ctx.activeCallId = call.id;
42
44
  if (tool.interactive) {
43
45
  // Interactive tools wait for user input — no timeout.
44
46
  result = await tool.handler(this.ctx, call.arguments);
45
47
  }
46
48
  else {
47
49
  const timeoutPromise = new Promise((_, reject) => {
48
- setTimeout(() => reject(new Error(t("tool.timeout", {
49
- name: call.name,
50
- seconds: TOOL_EXECUTION_TIMEOUT_MS / 1000,
51
- }))), TOOL_EXECUTION_TIMEOUT_MS);
50
+ setTimeout(() => {
51
+ // Kill any long-running child process registered for this call.
52
+ killByCallId(call.id);
53
+ reject(new Error(t("tool.timeout", {
54
+ name: call.name,
55
+ seconds: TOOL_EXECUTION_TIMEOUT_MS / 1000,
56
+ })));
57
+ }, TOOL_EXECUTION_TIMEOUT_MS);
52
58
  });
53
59
  result = await Promise.race([
54
60
  tool.handler(this.ctx, call.arguments),
@@ -11,6 +11,9 @@ import { deleteFileTool } from './delete-file';
11
11
  import { moveFileTool } from './move-file';
12
12
  import { fileInfoTool } from './file-info';
13
13
  import { bashTool } from './bash';
14
+ import { processListTool } from './process-list';
15
+ import { processLogTool } from './process-log';
16
+ import { processKillTool } from './process-kill';
14
17
  import { subagentTool } from './subagent';
15
18
  import { webSearchTool } from './web-search';
16
19
  import { webFetchTool } from './web-fetch';
@@ -24,13 +27,14 @@ import { searchHistoryTool } from './search-history';
24
27
  import { createBrowserTool } from './browser';
25
28
  export { ToolRegistry, ToolExecutor };
26
29
  export { filterToolsByTags } from './filter-tools';
27
- export { readFileTool, writeFileTool, editFileTool, globTool, grepTool, listDirTool, createDirTool, deleteFileTool, moveFileTool, fileInfoTool, bashTool, subagentTool, webSearchTool, webFetchTool, webBrowseTool, questionTool, approveTool, createLoadSkillTool, pipelineRunTool, mcpCallTool, searchHistoryTool, createBrowserTool, };
30
+ export { readFileTool, writeFileTool, editFileTool, globTool, grepTool, listDirTool, createDirTool, deleteFileTool, moveFileTool, fileInfoTool, bashTool, subagentTool, processListTool, processLogTool, processKillTool, webSearchTool, webFetchTool, webBrowseTool, questionTool, approveTool, createLoadSkillTool, pipelineRunTool, mcpCallTool, searchHistoryTool, createBrowserTool, };
28
31
  export function registerAllTools(registry, skillsModule) {
29
32
  const tools = [
30
33
  readFileTool, writeFileTool, editFileTool,
31
34
  globTool, grepTool, listDirTool, createDirTool,
32
35
  deleteFileTool, moveFileTool, fileInfoTool,
33
36
  bashTool, subagentTool,
37
+ processListTool, processLogTool, processKillTool,
34
38
  webSearchTool, webFetchTool, webBrowseTool,
35
39
  questionTool, approveTool,
36
40
  pipelineRunTool, mcpCallTool, searchHistoryTool,
@@ -0,0 +1,29 @@
1
+ import { processRegistry } from '../modules/processes';
2
+ import { t } from '../i18n/index';
3
+ export const processKillTool = {
4
+ name: 'process_kill',
5
+ description: 'Stop a background process started via bash (dev server, watcher). Kills the whole process tree (children included). Use the id returned by bash or process_list.',
6
+ tags: ['shell'],
7
+ parameters: {
8
+ type: 'object',
9
+ properties: {
10
+ id: { type: 'string', description: 'Process id from bash output or process_list' },
11
+ },
12
+ required: ['id'],
13
+ },
14
+ handler: async (ctx, args) => {
15
+ const id = String(args.id);
16
+ const entry = processRegistry.get(id);
17
+ if (!entry) {
18
+ return { success: false, output: t('proc.not_found', { id }) };
19
+ }
20
+ const killed = processRegistry.kill(id);
21
+ if (!killed) {
22
+ return { success: false, output: t('proc.kill_failed', { id }) };
23
+ }
24
+ return {
25
+ success: true,
26
+ output: t('proc.killed', { id, pid: entry.pid }),
27
+ };
28
+ },
29
+ };
@@ -0,0 +1,38 @@
1
+ import { processRegistry } from '../modules/processes';
2
+ import { t } from '../i18n/index';
3
+ export const processListTool = {
4
+ name: 'process_list',
5
+ description: 'List background processes started via the bash tool (dev servers, watchers, long-running commands). Shows id, pid, command, status, and recent output. Use with process_log and process_kill to inspect or stop them.',
6
+ tags: ['shell'],
7
+ parameters: {
8
+ type: 'object',
9
+ properties: {},
10
+ },
11
+ handler: async (ctx) => {
12
+ const list = processRegistry.list(ctx.sessionId);
13
+ if (list.length === 0) {
14
+ return { success: true, output: t('proc.none') };
15
+ }
16
+ const statusLabel = (status) => {
17
+ if (status === 'running')
18
+ return t('proc.status_running');
19
+ if (status === 'exited')
20
+ return t('proc.status_exited');
21
+ return t('proc.status_killed');
22
+ };
23
+ const lines = [`${t('proc.list_header')} (${list.length}):`];
24
+ for (const entry of list) {
25
+ const tail = entry.log.length > 0 ? entry.log[entry.log.length - 1] : '';
26
+ const detail = tail
27
+ ? ` — ${tail.slice(0, 80)}${tail.length > 80 ? '…' : ''}`
28
+ : '';
29
+ lines.push(` ${entry.id} PID ${entry.pid} ${statusLabel(entry.status)} ${entry.command}${detail}`);
30
+ }
31
+ lines.push(`\n${t('proc.hint', {
32
+ list: 'process_list',
33
+ log: 'process_log',
34
+ kill: 'process_kill',
35
+ })}`);
36
+ return { success: true, output: lines.join('\n') };
37
+ },
38
+ };
@@ -0,0 +1,39 @@
1
+ import { processRegistry } from '../modules/processes';
2
+ import { t } from '../i18n/index';
3
+ export const processLogTool = {
4
+ name: 'process_log',
5
+ description: 'Show the buffered output of a background process started via bash. Use after starting a dev server to verify it came up without errors, and while it runs to check its state.',
6
+ tags: ['shell'],
7
+ parameters: {
8
+ type: 'object',
9
+ properties: {
10
+ id: { type: 'string', description: 'Process id from bash output or process_list' },
11
+ tail: { type: 'number', description: 'Number of trailing lines to show (default: all buffered lines, max 300)' },
12
+ },
13
+ required: ['id'],
14
+ },
15
+ handler: async (ctx, args) => {
16
+ const id = String(args.id);
17
+ const entry = processRegistry.get(id);
18
+ if (!entry) {
19
+ return { success: false, output: t('proc.not_found', { id }) };
20
+ }
21
+ const status = entry.status === 'running'
22
+ ? t('proc.status_running')
23
+ : entry.status === 'exited'
24
+ ? t('proc.status_exited')
25
+ : t('proc.status_killed');
26
+ const tail = typeof args.tail === 'number' ? args.tail : undefined;
27
+ const log = processRegistry.getLog(id, tail);
28
+ if (!log) {
29
+ return {
30
+ success: true,
31
+ output: `${t('proc.log_header', { id, status })} ${t('proc.log_empty')}`,
32
+ };
33
+ }
34
+ return {
35
+ success: true,
36
+ output: `${t('proc.log_header', { id, status })}\n${log}`,
37
+ };
38
+ },
39
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "micro-models-agent",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Micro Models Agent (MMA) — LLM agent harness for small models (Qwen3.5-9B, 32K-64K context)",
5
5
  "type": "module",
6
6
  "bin": {