Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(agent): add exec/process tools
Jiayuan1097ef514482
diff --git a/package.json b/package.jsonindex e3e13a2843..4b5d2bf060 100644--- a/package.json+++ b/package.json@@ -30,6 +30,7 @@"@mariozechner/pi-agent-core": "^0.50.3","@mariozechner/pi-ai": "^0.50.3","@mariozechner/pi-coding-agent": "^0.50.3",+ "@sinclair/typebox": "^0.34.41","@nestjs/common": "^11.1.12","@nestjs/core": "^11.1.12","@nestjs/platform-express": "^11.1.12",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex ad2465f0b8..c662cc0a25 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -35,6 +35,9 @@ importers:'@nestjs/websockets':specifier: ^11.1.12version: 11.1.12(@nestjs/[email protected]([email protected])([email protected]))(@nestjs/[email protected])(@nestjs/[email protected])([email protected])([email protected])+ '@sinclair/typebox':+ specifier: ^0.34.41+ version: 0.34.48nestjs-pino:specifier: ^4.5.0version: 4.5.0(@nestjs/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])diff --git a/src/agent/tools/exec.ts b/src/agent/tools/exec.tsnew file mode 100644index 0000000000..f40aa00757--- /dev/null+++ b/src/agent/tools/exec.ts@@ -0,0 +1,94 @@+import { spawn } from "child_process";+import { Type } from "@sinclair/typebox";+import type { AgentTool } from "@mariozechner/pi-agent-core";++const ExecSchema = Type.Object({+ command: Type.String({ description: "Shell command to execute." }),+ cwd: Type.Optional(Type.String({ description: "Working directory." })),+ timeoutMs: Type.Optional(+ Type.Number({ description: "Timeout in milliseconds.", minimum: 0 }),+ ),+});++type ExecArgs = {+ command: string;+ cwd?: string;+ timeoutMs?: number;+};++export type ExecResult = {+ output: string;+ exitCode: number | null;+ truncated: boolean;+};++const MAX_OUTPUT_BYTES = 64 * 1024;++export function createExecTool(defaultCwd?: string): AgentTool<typeof ExecSchema, ExecResult> {+ return {+ name: "exec",+ label: "Exec",+ description: "Execute a shell command and return its output.",+ parameters: ExecSchema,+ execute: async (_toolCallId, args, signal) => {+ const { command, cwd, timeoutMs } = args as ExecArgs;+ return new Promise((resolve, reject) => {+ const child = spawn(command, {+ shell: true,+ cwd: cwd || defaultCwd,+ stdio: ["ignore", "pipe", "pipe"],+ });++ let timedOut = false;+ let timeout: NodeJS.Timeout | undefined;+ if (timeoutMs && timeoutMs > 0) {+ timeout = setTimeout(() => {+ timedOut = true;+ child.kill("SIGTERM");+ }, timeoutMs);+ }++ const chunks: Buffer[] = [];+ let size = 0;+ let truncated = false;++ const handleData = (data: Buffer) => {+ if (truncated) return;+ size += data.length;+ if (size > MAX_OUTPUT_BYTES) {+ truncated = true;+ const remaining = MAX_OUTPUT_BYTES - (size - data.length);+ if (remaining > 0) chunks.push(data.subarray(0, remaining));+ return;+ }+ chunks.push(data);+ };++ child.stdout?.on("data", handleData);+ child.stderr?.on("data", handleData);+ child.on("error", (err) => {+ if (timeout) clearTimeout(timeout);+ reject(err);+ });+ child.on("close", (code) => {+ if (timeout) clearTimeout(timeout);+ const output = Buffer.concat(chunks).toString("utf8");+ resolve({+ content: [{ type: "text", text: output || (timedOut ? "Process timed out." : "") }],+ details: {+ output,+ exitCode: code,+ truncated,+ },+ });+ });++ if (signal) {+ signal.addEventListener("abort", () => {+ child.kill("SIGTERM");+ });+ }+ });+ },+ };+}diff --git a/src/agent/tools/process.ts b/src/agent/tools/process.tsnew file mode 100644index 0000000000..42ab45e400--- /dev/null+++ b/src/agent/tools/process.ts@@ -0,0 +1,114 @@+import { spawn, type ChildProcess } from "child_process";+import { Type } from "@sinclair/typebox";+import type { AgentTool } from "@mariozechner/pi-agent-core";+import { v7 as uuidv7 } from "uuid";++const ProcessSchema = Type.Object({+ action: Type.String({ description: "Action: start | status | stop." }),+ id: Type.Optional(Type.String({ description: "Process id for status/stop." })),+ command: Type.Optional(Type.String({ description: "Command to run for start." })),+ cwd: Type.Optional(Type.String({ description: "Working directory." })),+});++type ProcessEntry = {+ id: string;+ command: string;+ cwd?: string;+ child: ChildProcess;+ exitCode: number | null;+ startedAt: number;+};++const PROCESS_REGISTRY = new Map<string, ProcessEntry>();++export type ProcessResult = {+ id?: string;+ running?: boolean;+ exitCode?: number | null;+ message?: string;+};++export function createProcessTool(defaultCwd?: string): AgentTool<typeof ProcessSchema, ProcessResult> {+ return {+ name: "process",+ label: "Process",+ description: "Manage background processes (start, status, stop).",+ parameters: ProcessSchema,+ execute: async (_toolCallId, params, signal) => {+ const action = String(params.action ?? "").toLowerCase();+ if (!action) {+ throw new Error("Missing action");+ }++ if (action === "start") {+ const command = String(params.command ?? "");+ if (!command) throw new Error("Missing command");+ const id = params.id ? String(params.id) : uuidv7();+ if (PROCESS_REGISTRY.has(id)) {+ throw new Error(`Process already exists: ${id}`);+ }+ const child = spawn(command, {+ shell: true,+ cwd: params.cwd || defaultCwd,+ stdio: ["ignore", "pipe", "pipe"],+ detached: true,+ });+ const entry: ProcessEntry = {+ id,+ command,+ cwd: params.cwd || defaultCwd,+ child,+ exitCode: null,+ startedAt: Date.now(),+ };+ PROCESS_REGISTRY.set(id, entry);+ child.on("close", (code) => {+ entry.exitCode = code;+ });+ if (signal) {+ signal.addEventListener("abort", () => {+ child.kill("SIGTERM");+ });+ }+ return {+ content: [{ type: "text", text: `Started process ${id}` }],+ details: { id, running: true },+ };+ }++ if (action === "status") {+ const id = String(params.id ?? "");+ const entry = PROCESS_REGISTRY.get(id);+ if (!entry) {+ return {+ content: [{ type: "text", text: `Process not found: ${id}` }],+ details: { id, running: false },+ };+ }+ const running = entry.exitCode === null;+ return {+ content: [{ type: "text", text: running ? `Process running: ${id}` : `Process exited: ${id}` }],+ details: { id, running, exitCode: entry.exitCode },+ };+ }++ if (action === "stop") {+ const id = String(params.id ?? "");+ const entry = PROCESS_REGISTRY.get(id);+ if (!entry) {+ return {+ content: [{ type: "text", text: `Process not found: ${id}` }],+ details: { id, running: false },+ };+ }+ entry.child.kill("SIGTERM");+ return {+ content: [{ type: "text", text: `Stopped process ${id}` }],+ details: { id, running: false },+ };+ }++ throw new Error(`Unknown action: ${action}`);+ },+ };+}