feat: line-based process logs
This commit is contained in:
@@ -28,6 +28,7 @@
|
|||||||
- Streamed `<think>` segments are stripped before partial replies are emitted.
|
- Streamed `<think>` segments are stripped before partial replies are emitted.
|
||||||
- System prompt now tags allowlisted owner numbers as the user identity to avoid mistaken “friend” assumptions.
|
- System prompt now tags allowlisted owner numbers as the user identity to avoid mistaken “friend” assumptions.
|
||||||
- LM Studio/Ollama replies now require <final> tags; streaming ignores content until <final> begins.
|
- LM Studio/Ollama replies now require <final> tags; streaming ignores content until <final> begins.
|
||||||
|
- `process log` pagination is now line-based (omit `offset` to grab the last N lines).
|
||||||
- UI perf: pause repeat animations when scenes are inactive (typing dots, onboarding glow, iOS status pulse), throttle voice overlay level updates, and reduce overlay focus churn.
|
- UI perf: pause repeat animations when scenes are inactive (typing dots, onboarding glow, iOS status pulse), throttle voice overlay level updates, and reduce overlay focus churn.
|
||||||
- Canvas defaults/A2UI auto-nav aligned; debug status overlay centered; redundant await removed in `CanvasManager`.
|
- Canvas defaults/A2UI auto-nav aligned; debug status overlay centered; redundant await removed in `CanvasManager`.
|
||||||
- Gateway launchd loop fixed by removing redundant `kickstart -k`.
|
- Gateway launchd loop fixed by removing redundant `kickstart -k`.
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ Key parameters:
|
|||||||
- `command` (required)
|
- `command` (required)
|
||||||
- `yieldMs` (default 20000): auto‑background after this delay
|
- `yieldMs` (default 20000): auto‑background after this delay
|
||||||
- `background` (bool): background immediately
|
- `background` (bool): background immediately
|
||||||
- `timeout` (seconds): kill the process after this timeout
|
- `timeout` (seconds, default 1800): kill the process after this timeout
|
||||||
- `workdir`, `env`
|
- `workdir`, `env`
|
||||||
|
|
||||||
Behavior:
|
Behavior:
|
||||||
@@ -28,6 +28,11 @@ Environment overrides:
|
|||||||
- `PI_BASH_MAX_OUTPUT_CHARS`: in‑memory output cap (chars)
|
- `PI_BASH_MAX_OUTPUT_CHARS`: in‑memory output cap (chars)
|
||||||
- `PI_BASH_JOB_TTL_MS`: TTL for finished sessions (ms, bounded to 1m–3h)
|
- `PI_BASH_JOB_TTL_MS`: TTL for finished sessions (ms, bounded to 1m–3h)
|
||||||
|
|
||||||
|
Config (preferred):
|
||||||
|
- `agent.bash.backgroundMs` (default 20000)
|
||||||
|
- `agent.bash.timeoutSec` (default 1800)
|
||||||
|
- `agent.bash.cleanupMs` (default 1800000)
|
||||||
|
|
||||||
## process tool
|
## process tool
|
||||||
|
|
||||||
Actions:
|
Actions:
|
||||||
@@ -43,6 +48,8 @@ Notes:
|
|||||||
- Only backgrounded sessions are listed/persisted in memory.
|
- Only backgrounded sessions are listed/persisted in memory.
|
||||||
- Sessions are lost on process restart (no disk persistence).
|
- Sessions are lost on process restart (no disk persistence).
|
||||||
- Session logs are only saved to chat history if you run `process poll/log` and the tool result is recorded.
|
- Session logs are only saved to chat history if you run `process poll/log` and the tool result is recorded.
|
||||||
|
- `process list` includes a derived `name` (command verb + target) for quick scans.
|
||||||
|
- `process log` uses line-based `offset`/`limit` (omit `offset` to grab the last N lines).
|
||||||
|
|
||||||
## Examples
|
## Examples
|
||||||
|
|
||||||
|
|||||||
@@ -131,11 +131,21 @@ Controls the embedded agent runtime (provider/model/thinking/verbose/timeouts).
|
|||||||
timeoutSeconds: 600,
|
timeoutSeconds: 600,
|
||||||
mediaMaxMb: 5,
|
mediaMaxMb: 5,
|
||||||
heartbeatMinutes: 30,
|
heartbeatMinutes: 30,
|
||||||
|
bash: {
|
||||||
|
backgroundMs: 20000,
|
||||||
|
timeoutSec: 1800,
|
||||||
|
cleanupMs: 1800000
|
||||||
|
},
|
||||||
contextTokens: 200000
|
contextTokens: 200000
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`agent.bash` configures background bash defaults:
|
||||||
|
- `backgroundMs`: time before auto-background (ms, default 20000)
|
||||||
|
- `timeoutSec`: auto-kill after this runtime (seconds, default 1800)
|
||||||
|
- `cleanupMs`: how long to keep finished sessions in memory (ms, default 1800000)
|
||||||
|
|
||||||
### `models` (custom providers + base URLs)
|
### `models` (custom providers + base URLs)
|
||||||
|
|
||||||
Clawdis uses the **pi-coding-agent** model catalog. You can add custom providers
|
Clawdis uses the **pi-coding-agent** model catalog. You can add custom providers
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ Core parameters:
|
|||||||
- `command` (required)
|
- `command` (required)
|
||||||
- `yieldMs` (auto-background after timeout, default 20000)
|
- `yieldMs` (auto-background after timeout, default 20000)
|
||||||
- `background` (immediate background)
|
- `background` (immediate background)
|
||||||
- `timeout` (seconds; kills the process if exceeded)
|
- `timeout` (seconds; kills the process if exceeded, default 1800)
|
||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
- Returns `status: "running"` with a `sessionId` when backgrounded.
|
- Returns `status: "running"` with a `sessionId` when backgrounded.
|
||||||
@@ -34,7 +34,7 @@ Core actions:
|
|||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
- `poll` returns new output and exit status when complete.
|
- `poll` returns new output and exit status when complete.
|
||||||
- `log` supports `offset`/`limit` to page through output.
|
- `log` supports line-based `offset`/`limit` (omit `offset` to grab the last N lines).
|
||||||
|
|
||||||
### `clawdis_browser`
|
### `clawdis_browser`
|
||||||
Control the dedicated clawd browser.
|
Control the dedicated clawd browser.
|
||||||
@@ -90,6 +90,15 @@ Notes:
|
|||||||
- `add` expects a full cron job object (same schema as `cron.add` RPC).
|
- `add` expects a full cron job object (same schema as `cron.add` RPC).
|
||||||
- `update` uses `{ jobId, patch }`.
|
- `update` uses `{ jobId, patch }`.
|
||||||
|
|
||||||
|
### `clawdis_gateway`
|
||||||
|
Restart the running Gateway process (in-place).
|
||||||
|
|
||||||
|
Core actions:
|
||||||
|
- `restart` (sends `SIGUSR1` to the current process; `clawdis gateway`/`gateway-daemon` restart in-place)
|
||||||
|
|
||||||
|
Notes:
|
||||||
|
- Use `delayMs` (defaults to 2000) to avoid interrupting an in-flight reply.
|
||||||
|
|
||||||
## Parameters (common)
|
## Parameters (common)
|
||||||
|
|
||||||
Gateway-backed tools (`clawdis_canvas`, `clawdis_nodes`, `clawdis_cron`):
|
Gateway-backed tools (`clawdis_canvas`, `clawdis_nodes`, `clawdis_cron`):
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ function clampTtl(value: number | undefined) {
|
|||||||
return Math.min(Math.max(value, MIN_JOB_TTL_MS), MAX_JOB_TTL_MS);
|
return Math.min(Math.max(value, MIN_JOB_TTL_MS), MAX_JOB_TTL_MS);
|
||||||
}
|
}
|
||||||
|
|
||||||
const JOB_TTL_MS = clampTtl(
|
let jobTtlMs = clampTtl(
|
||||||
Number.parseInt(process.env.PI_BASH_JOB_TTL_MS ?? "", 10),
|
Number.parseInt(process.env.PI_BASH_JOB_TTL_MS ?? "", 10),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -163,14 +163,18 @@ export function clearFinished() {
|
|||||||
export function resetProcessRegistryForTests() {
|
export function resetProcessRegistryForTests() {
|
||||||
runningSessions.clear();
|
runningSessions.clear();
|
||||||
finishedSessions.clear();
|
finishedSessions.clear();
|
||||||
if (sweeper) {
|
stopSweeper();
|
||||||
clearInterval(sweeper);
|
|
||||||
sweeper = null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function setJobTtlMs(value?: number) {
|
||||||
|
if (value === undefined || Number.isNaN(value)) return;
|
||||||
|
jobTtlMs = clampTtl(value);
|
||||||
|
stopSweeper();
|
||||||
|
startSweeper();
|
||||||
}
|
}
|
||||||
|
|
||||||
function pruneFinishedSessions() {
|
function pruneFinishedSessions() {
|
||||||
const cutoff = Date.now() - JOB_TTL_MS;
|
const cutoff = Date.now() - jobTtlMs;
|
||||||
for (const [id, session] of finishedSessions.entries()) {
|
for (const [id, session] of finishedSessions.entries()) {
|
||||||
if (session.endedAt < cutoff) {
|
if (session.endedAt < cutoff) {
|
||||||
finishedSessions.delete(id);
|
finishedSessions.delete(id);
|
||||||
@@ -180,9 +184,12 @@ function pruneFinishedSessions() {
|
|||||||
|
|
||||||
function startSweeper() {
|
function startSweeper() {
|
||||||
if (sweeper) return;
|
if (sweeper) return;
|
||||||
sweeper = setInterval(
|
sweeper = setInterval(pruneFinishedSessions, Math.max(30_000, jobTtlMs / 6));
|
||||||
pruneFinishedSessions,
|
|
||||||
Math.max(30_000, JOB_TTL_MS / 6),
|
|
||||||
);
|
|
||||||
sweeper.unref?.();
|
sweeper.unref?.();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function stopSweeper() {
|
||||||
|
if (!sweeper) return;
|
||||||
|
clearInterval(sweeper);
|
||||||
|
sweeper = null;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,9 +1,30 @@
|
|||||||
import { beforeEach, describe, expect, it } from "vitest";
|
import { beforeEach, describe, expect, it } from "vitest";
|
||||||
|
import {
|
||||||
|
bashTool,
|
||||||
|
createBashTool,
|
||||||
|
createProcessTool,
|
||||||
|
processTool,
|
||||||
|
} from "./bash-tools.js";
|
||||||
import { resetProcessRegistryForTests } from "./bash-process-registry.js";
|
import { resetProcessRegistryForTests } from "./bash-process-registry.js";
|
||||||
import { bashTool, processTool } from "./bash-tools.js";
|
|
||||||
|
|
||||||
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
|
||||||
|
async function waitForCompletion(sessionId: string) {
|
||||||
|
let status = "running";
|
||||||
|
const deadline = Date.now() + 2000;
|
||||||
|
while (Date.now() < deadline && status === "running") {
|
||||||
|
const poll = await processTool.execute("call-wait", {
|
||||||
|
action: "poll",
|
||||||
|
sessionId,
|
||||||
|
});
|
||||||
|
status = (poll.details as { status: string }).status;
|
||||||
|
if (status === "running") {
|
||||||
|
await sleep(20);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
resetProcessRegistryForTests();
|
resetProcessRegistryForTests();
|
||||||
});
|
});
|
||||||
@@ -54,4 +75,87 @@ describe("bash tool backgrounding", () => {
|
|||||||
).sessions;
|
).sessions;
|
||||||
expect(sessions.some((s) => s.sessionId === sessionId)).toBe(true);
|
expect(sessions.some((s) => s.sessionId === sessionId)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("derives a session name from the command", async () => {
|
||||||
|
const result = await bashTool.execute("call1", {
|
||||||
|
command: "echo hello",
|
||||||
|
background: true,
|
||||||
|
});
|
||||||
|
const sessionId = (result.details as { sessionId: string }).sessionId;
|
||||||
|
await sleep(25);
|
||||||
|
|
||||||
|
const list = await processTool.execute("call2", { action: "list" });
|
||||||
|
const sessions = (
|
||||||
|
list.details as { sessions: Array<{ sessionId: string; name?: string }> }
|
||||||
|
).sessions;
|
||||||
|
const entry = sessions.find((s) => s.sessionId === sessionId);
|
||||||
|
expect(entry?.name).toBe("echo hello");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses default timeout when timeout is omitted", async () => {
|
||||||
|
const customBash = createBashTool({ timeoutSec: 1, backgroundMs: 10 });
|
||||||
|
const customProcess = createProcessTool();
|
||||||
|
|
||||||
|
const result = await customBash.execute("call1", {
|
||||||
|
command: "node -e \"setInterval(() => {}, 1000)\"",
|
||||||
|
background: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const sessionId = (result.details as { sessionId: string }).sessionId;
|
||||||
|
let status = "running";
|
||||||
|
const deadline = Date.now() + 5000;
|
||||||
|
|
||||||
|
while (Date.now() < deadline && status === "running") {
|
||||||
|
const poll = await customProcess.execute("call2", {
|
||||||
|
action: "poll",
|
||||||
|
sessionId,
|
||||||
|
});
|
||||||
|
status = (poll.details as { status: string }).status;
|
||||||
|
if (status === "running") {
|
||||||
|
await sleep(50);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(status).toBe("failed");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("logs line-based slices and defaults to last lines", async () => {
|
||||||
|
const result = await bashTool.execute("call1", {
|
||||||
|
command:
|
||||||
|
"node -e \"console.log('one'); console.log('two'); console.log('three');\"",
|
||||||
|
background: true,
|
||||||
|
});
|
||||||
|
const sessionId = (result.details as { sessionId: string }).sessionId;
|
||||||
|
|
||||||
|
const status = await waitForCompletion(sessionId);
|
||||||
|
|
||||||
|
const log = await processTool.execute("call3", {
|
||||||
|
action: "log",
|
||||||
|
sessionId,
|
||||||
|
limit: 2,
|
||||||
|
});
|
||||||
|
const textBlock = log.content.find((c) => c.type === "text");
|
||||||
|
expect(textBlock?.text).toBe("two\nthree");
|
||||||
|
expect((log.details as { totalLines?: number }).totalLines).toBe(3);
|
||||||
|
expect(status).toBe("completed");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("supports line offsets for log slices", async () => {
|
||||||
|
const result = await bashTool.execute("call1", {
|
||||||
|
command:
|
||||||
|
"node -e \"console.log('alpha'); console.log('beta'); console.log('gamma');\"",
|
||||||
|
background: true,
|
||||||
|
});
|
||||||
|
const sessionId = (result.details as { sessionId: string }).sessionId;
|
||||||
|
await waitForCompletion(sessionId);
|
||||||
|
|
||||||
|
const log = await processTool.execute("call2", {
|
||||||
|
action: "log",
|
||||||
|
sessionId,
|
||||||
|
offset: 1,
|
||||||
|
limit: 1,
|
||||||
|
});
|
||||||
|
const textBlock = log.content.find((c) => c.type === "text");
|
||||||
|
expect(textBlock?.text).toBe("beta");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
|
|
||||||
import { randomUUID } from "node:crypto";
|
|
||||||
import type { AgentTool, AgentToolResult } from "@mariozechner/pi-ai";
|
import type { AgentTool, AgentToolResult } from "@mariozechner/pi-ai";
|
||||||
import { StringEnum } from "@mariozechner/pi-ai";
|
import { StringEnum } from "@mariozechner/pi-ai";
|
||||||
import { Type } from "@sinclair/typebox";
|
import { Type } from "@sinclair/typebox";
|
||||||
|
import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
|
||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
addSession,
|
addSession,
|
||||||
@@ -15,20 +15,11 @@ import {
|
|||||||
listRunningSessions,
|
listRunningSessions,
|
||||||
markBackgrounded,
|
markBackgrounded,
|
||||||
markExited,
|
markExited,
|
||||||
|
setJobTtlMs,
|
||||||
} from "./bash-process-registry.js";
|
} from "./bash-process-registry.js";
|
||||||
import {
|
import { getShellConfig, killProcessTree, sanitizeBinaryOutput } from "./shell-utils.js";
|
||||||
getShellConfig,
|
|
||||||
killProcessTree,
|
|
||||||
sanitizeBinaryOutput,
|
|
||||||
} from "./shell-utils.js";
|
|
||||||
|
|
||||||
const CHUNK_LIMIT = 8 * 1024;
|
const CHUNK_LIMIT = 8 * 1024;
|
||||||
const DEFAULT_YIELD_MS = clampNumber(
|
|
||||||
readEnvInt("PI_BASH_YIELD_MS"),
|
|
||||||
20_000,
|
|
||||||
10,
|
|
||||||
120_000,
|
|
||||||
);
|
|
||||||
const DEFAULT_MAX_OUTPUT = clampNumber(
|
const DEFAULT_MAX_OUTPUT = clampNumber(
|
||||||
readEnvInt("PI_BASH_MAX_OUTPUT_CHARS"),
|
readEnvInt("PI_BASH_MAX_OUTPUT_CHARS"),
|
||||||
30_000,
|
30_000,
|
||||||
@@ -36,6 +27,15 @@ const DEFAULT_MAX_OUTPUT = clampNumber(
|
|||||||
150_000,
|
150_000,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
export type BashToolDefaults = {
|
||||||
|
backgroundMs?: number;
|
||||||
|
timeoutSec?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ProcessToolDefaults = {
|
||||||
|
cleanupMs?: number;
|
||||||
|
};
|
||||||
|
|
||||||
const bashSchema = Type.Object({
|
const bashSchema = Type.Object({
|
||||||
command: Type.String({ description: "Bash command to execute" }),
|
command: Type.String({ description: "Bash command to execute" }),
|
||||||
workdir: Type.Optional(
|
workdir: Type.Optional(
|
||||||
@@ -77,13 +77,27 @@ export type BashToolDetails =
|
|||||||
aggregated: string;
|
aggregated: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const bashTool: AgentTool<typeof bashSchema, BashToolDetails> = {
|
export function createBashTool(
|
||||||
|
defaults?: BashToolDefaults,
|
||||||
|
): AgentTool<typeof bashSchema, BashToolDetails> {
|
||||||
|
const defaultBackgroundMs = clampNumber(
|
||||||
|
defaults?.backgroundMs ?? readEnvInt("PI_BASH_YIELD_MS"),
|
||||||
|
20_000,
|
||||||
|
10,
|
||||||
|
120_000,
|
||||||
|
);
|
||||||
|
const defaultTimeoutSec =
|
||||||
|
typeof defaults?.timeoutSec === "number" && defaults.timeoutSec > 0
|
||||||
|
? defaults.timeoutSec
|
||||||
|
: 1800;
|
||||||
|
|
||||||
|
return {
|
||||||
name: "bash",
|
name: "bash",
|
||||||
label: "bash",
|
label: "bash",
|
||||||
description:
|
description:
|
||||||
"Execute bash with background continuation. Use yieldMs/background to continue later via process tool.",
|
"Execute bash with background continuation. Use yieldMs/background to continue later via process tool.",
|
||||||
parameters: bashSchema,
|
parameters: bashSchema,
|
||||||
execute: async (_toolCallId, args, signal, onUpdate) => {
|
execute: async (toolCallId, args, signal, onUpdate) => {
|
||||||
const params = args as {
|
const params = args as {
|
||||||
command: string;
|
command: string;
|
||||||
workdir?: string;
|
workdir?: string;
|
||||||
@@ -103,20 +117,24 @@ export const bashTool: AgentTool<typeof bashSchema, BashToolDetails> = {
|
|||||||
|
|
||||||
const yieldWindow = params.background
|
const yieldWindow = params.background
|
||||||
? 0
|
? 0
|
||||||
: clampNumber(params.yieldMs, DEFAULT_YIELD_MS, 10, 120_000);
|
: clampNumber(
|
||||||
|
params.yieldMs ?? defaultBackgroundMs,
|
||||||
|
defaultBackgroundMs,
|
||||||
|
10,
|
||||||
|
120_000,
|
||||||
|
);
|
||||||
const maxOutput = DEFAULT_MAX_OUTPUT;
|
const maxOutput = DEFAULT_MAX_OUTPUT;
|
||||||
const startedAt = Date.now();
|
const startedAt = Date.now();
|
||||||
const sessionId = randomUUID();
|
const sessionId = randomUUID();
|
||||||
const workdir = params.workdir?.trim() || process.cwd();
|
const workdir = params.workdir?.trim() || process.cwd();
|
||||||
|
|
||||||
const { shell, args: shellArgs } = getShellConfig();
|
const { shell, args: shellArgs } = getShellConfig();
|
||||||
const env = params.env ?? {};
|
|
||||||
const child: ChildProcessWithoutNullStreams = spawn(
|
const child: ChildProcessWithoutNullStreams = spawn(
|
||||||
shell,
|
shell,
|
||||||
[...shellArgs, params.command],
|
[...shellArgs, params.command],
|
||||||
{
|
{
|
||||||
cwd: workdir,
|
cwd: workdir,
|
||||||
env: { ...process.env, ...env },
|
env: { ...process.env, ...(params.env ?? {}) },
|
||||||
detached: true,
|
detached: true,
|
||||||
stdio: ["pipe", "pipe", "pipe"],
|
stdio: ["pipe", "pipe", "pipe"],
|
||||||
},
|
},
|
||||||
@@ -163,11 +181,13 @@ export const bashTool: AgentTool<typeof bashSchema, BashToolDetails> = {
|
|||||||
if (signal?.aborted) onAbort();
|
if (signal?.aborted) onAbort();
|
||||||
else if (signal) signal.addEventListener("abort", onAbort, { once: true });
|
else if (signal) signal.addEventListener("abort", onAbort, { once: true });
|
||||||
|
|
||||||
if (typeof params.timeout === "number" && params.timeout > 0) {
|
const effectiveTimeout =
|
||||||
|
typeof params.timeout === "number" ? params.timeout : defaultTimeoutSec;
|
||||||
|
if (effectiveTimeout > 0) {
|
||||||
timeoutTimer = setTimeout(() => {
|
timeoutTimer = setTimeout(() => {
|
||||||
timedOut = true;
|
timedOut = true;
|
||||||
onAbort();
|
onAbort();
|
||||||
}, params.timeout * 1000);
|
}, effectiveTimeout * 1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
const emitUpdate = () => {
|
const emitUpdate = () => {
|
||||||
@@ -201,7 +221,8 @@ export const bashTool: AgentTool<typeof bashSchema, BashToolDetails> = {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return new Promise<AgentToolResult<BashToolDetails>>((resolve, reject) => {
|
return new Promise<AgentToolResult<BashToolDetails>>(
|
||||||
|
(resolve, reject) => {
|
||||||
const resolveRunning = () => {
|
const resolveRunning = () => {
|
||||||
settle(() =>
|
settle(() =>
|
||||||
resolve({
|
resolve({
|
||||||
@@ -210,7 +231,7 @@ export const bashTool: AgentTool<typeof bashSchema, BashToolDetails> = {
|
|||||||
type: "text",
|
type: "text",
|
||||||
text:
|
text:
|
||||||
`Command still running (session ${sessionId}, pid ${child.pid ?? "n/a"}). ` +
|
`Command still running (session ${sessionId}, pid ${child.pid ?? "n/a"}). ` +
|
||||||
"Use process (list/poll/log/write/kill/clear) for follow-up.",
|
"Use process (list/poll/log/write/kill/clear/remove) for follow-up.",
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
details: {
|
details: {
|
||||||
@@ -260,7 +281,7 @@ export const bashTool: AgentTool<typeof bashSchema, BashToolDetails> = {
|
|||||||
const aggregated = session.aggregated.trim();
|
const aggregated = session.aggregated.trim();
|
||||||
if (!isSuccess) {
|
if (!isSuccess) {
|
||||||
const reason = timedOut
|
const reason = timedOut
|
||||||
? `Command timed out after ${params.timeout} seconds`
|
? `Command timed out after ${effectiveTimeout} seconds`
|
||||||
: wasSignal && exitSignal
|
: wasSignal && exitSignal
|
||||||
? `Command aborted by signal ${exitSignal}`
|
? `Command aborted by signal ${exitSignal}`
|
||||||
: code === null
|
: code === null
|
||||||
@@ -290,9 +311,13 @@ export const bashTool: AgentTool<typeof bashSchema, BashToolDetails> = {
|
|||||||
markExited(session, null, null, "failed");
|
markExited(session, null, null, "failed");
|
||||||
settle(() => reject(err));
|
settle(() => reject(err));
|
||||||
});
|
});
|
||||||
});
|
},
|
||||||
|
);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const bashTool = createBashTool();
|
||||||
|
|
||||||
const processSchema = Type.Object({
|
const processSchema = Type.Object({
|
||||||
action: StringEnum(
|
action: StringEnum(
|
||||||
@@ -310,7 +335,14 @@ const processSchema = Type.Object({
|
|||||||
limit: Type.Optional(Type.Number({ description: "Log length" })),
|
limit: Type.Optional(Type.Number({ description: "Log length" })),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const processTool: AgentTool<typeof processSchema> = {
|
export function createProcessTool(
|
||||||
|
defaults?: ProcessToolDefaults,
|
||||||
|
): AgentTool<typeof processSchema> {
|
||||||
|
if (defaults?.cleanupMs !== undefined) {
|
||||||
|
setJobTtlMs(defaults.cleanupMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
name: "process",
|
name: "process",
|
||||||
label: "process",
|
label: "process",
|
||||||
description: "Manage running bash sessions: list, poll, log, write, kill.",
|
description: "Manage running bash sessions: list, poll, log, write, kill.",
|
||||||
@@ -334,6 +366,7 @@ export const processTool: AgentTool<typeof processSchema> = {
|
|||||||
runtimeMs: Date.now() - s.startedAt,
|
runtimeMs: Date.now() - s.startedAt,
|
||||||
cwd: s.cwd,
|
cwd: s.cwd,
|
||||||
command: s.command,
|
command: s.command,
|
||||||
|
name: deriveSessionName(s.command),
|
||||||
tail: s.tail,
|
tail: s.tail,
|
||||||
truncated: s.truncated,
|
truncated: s.truncated,
|
||||||
}));
|
}));
|
||||||
@@ -345,6 +378,7 @@ export const processTool: AgentTool<typeof processSchema> = {
|
|||||||
runtimeMs: s.endedAt - s.startedAt,
|
runtimeMs: s.endedAt - s.startedAt,
|
||||||
cwd: s.cwd,
|
cwd: s.cwd,
|
||||||
command: s.command,
|
command: s.command,
|
||||||
|
name: deriveSessionName(s.command),
|
||||||
tail: s.tail,
|
tail: s.tail,
|
||||||
truncated: s.truncated,
|
truncated: s.truncated,
|
||||||
exitCode: s.exitCode ?? undefined,
|
exitCode: s.exitCode ?? undefined,
|
||||||
@@ -352,12 +386,15 @@ export const processTool: AgentTool<typeof processSchema> = {
|
|||||||
}));
|
}));
|
||||||
const lines = [...running, ...finished]
|
const lines = [...running, ...finished]
|
||||||
.sort((a, b) => b.startedAt - a.startedAt)
|
.sort((a, b) => b.startedAt - a.startedAt)
|
||||||
.map(
|
.map((s) => {
|
||||||
(s) =>
|
const label = s.name
|
||||||
`${s.sessionId.slice(0, 8)} ${pad(s.status, 9)} ${formatDuration(
|
? truncateMiddle(s.name, 80)
|
||||||
s.runtimeMs,
|
: truncateMiddle(s.command, 120);
|
||||||
)} :: ${truncateMiddle(s.command, 120)}`,
|
return `${s.sessionId.slice(0, 8)} ${pad(
|
||||||
);
|
s.status,
|
||||||
|
9,
|
||||||
|
)} ${formatDuration(s.runtimeMs)} :: ${label}`;
|
||||||
|
});
|
||||||
return {
|
return {
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
@@ -407,6 +444,7 @@ export const processTool: AgentTool<typeof processSchema> = {
|
|||||||
sessionId: params.sessionId,
|
sessionId: params.sessionId,
|
||||||
exitCode: finished.exitCode ?? undefined,
|
exitCode: finished.exitCode ?? undefined,
|
||||||
aggregated: finished.aggregated,
|
aggregated: finished.aggregated,
|
||||||
|
name: deriveSessionName(finished.command),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -472,6 +510,7 @@ export const processTool: AgentTool<typeof processSchema> = {
|
|||||||
sessionId: params.sessionId,
|
sessionId: params.sessionId,
|
||||||
exitCode: exited ? exitCode : undefined,
|
exitCode: exited ? exitCode : undefined,
|
||||||
aggregated: session.aggregated,
|
aggregated: session.aggregated,
|
||||||
|
name: deriveSessionName(session.command),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -489,38 +528,45 @@ export const processTool: AgentTool<typeof processSchema> = {
|
|||||||
details: { status: "failed" },
|
details: { status: "failed" },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const total = session.aggregated.length;
|
const { slice, totalLines, totalChars } = sliceLogLines(
|
||||||
const slice = session.aggregated.slice(
|
session.aggregated,
|
||||||
params.offset ?? 0,
|
params.offset,
|
||||||
params.limit ? (params.offset ?? 0) + params.limit : undefined,
|
params.limit,
|
||||||
);
|
);
|
||||||
return {
|
return {
|
||||||
content: [{ type: "text", text: slice || "(no output yet)" }],
|
content: [{ type: "text", text: slice || "(no output yet)" }],
|
||||||
details: {
|
details: {
|
||||||
status: session.exited ? "completed" : "running",
|
status: session.exited ? "completed" : "running",
|
||||||
sessionId: params.sessionId,
|
sessionId: params.sessionId,
|
||||||
total,
|
total: totalLines,
|
||||||
|
totalLines,
|
||||||
|
totalChars,
|
||||||
truncated: session.truncated,
|
truncated: session.truncated,
|
||||||
|
name: deriveSessionName(session.command),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (finished) {
|
if (finished) {
|
||||||
const total = finished.aggregated.length;
|
const { slice, totalLines, totalChars } = sliceLogLines(
|
||||||
const slice = finished.aggregated.slice(
|
finished.aggregated,
|
||||||
params.offset ?? 0,
|
params.offset,
|
||||||
params.limit ? (params.offset ?? 0) + params.limit : undefined,
|
params.limit,
|
||||||
);
|
);
|
||||||
const status =
|
const status = finished.status === "completed" ? "completed" : "failed";
|
||||||
finished.status === "completed" ? "completed" : "failed";
|
|
||||||
return {
|
return {
|
||||||
content: [{ type: "text", text: slice || "(no output recorded)" }],
|
content: [
|
||||||
|
{ type: "text", text: slice || "(no output recorded)" },
|
||||||
|
],
|
||||||
details: {
|
details: {
|
||||||
status,
|
status,
|
||||||
sessionId: params.sessionId,
|
sessionId: params.sessionId,
|
||||||
total,
|
total: totalLines,
|
||||||
|
totalLines,
|
||||||
|
totalChars,
|
||||||
truncated: finished.truncated,
|
truncated: finished.truncated,
|
||||||
exitCode: finished.exitCode ?? undefined,
|
exitCode: finished.exitCode ?? undefined,
|
||||||
exitSignal: finished.exitSignal ?? undefined,
|
exitSignal: finished.exitSignal ?? undefined,
|
||||||
|
name: deriveSessionName(finished.command),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -536,10 +582,7 @@ export const processTool: AgentTool<typeof processSchema> = {
|
|||||||
if (!session) {
|
if (!session) {
|
||||||
return {
|
return {
|
||||||
content: [
|
content: [
|
||||||
{
|
{ type: "text", text: `No active session found for ${params.sessionId}` },
|
||||||
type: "text",
|
|
||||||
text: `No active session found for ${params.sessionId}`,
|
|
||||||
},
|
|
||||||
],
|
],
|
||||||
details: { status: "failed" },
|
details: { status: "failed" },
|
||||||
};
|
};
|
||||||
@@ -584,7 +627,11 @@ export const processTool: AgentTool<typeof processSchema> = {
|
|||||||
}${params.eof ? " (stdin closed)" : ""}.`,
|
}${params.eof ? " (stdin closed)" : ""}.`,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
details: { status: "running", sessionId: params.sessionId },
|
details: {
|
||||||
|
status: "running",
|
||||||
|
sessionId: params.sessionId,
|
||||||
|
name: session ? deriveSessionName(session.command) : undefined,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -592,10 +639,7 @@ export const processTool: AgentTool<typeof processSchema> = {
|
|||||||
if (!session) {
|
if (!session) {
|
||||||
return {
|
return {
|
||||||
content: [
|
content: [
|
||||||
{
|
{ type: "text", text: `No active session found for ${params.sessionId}` },
|
||||||
type: "text",
|
|
||||||
text: `No active session found for ${params.sessionId}`,
|
|
||||||
},
|
|
||||||
],
|
],
|
||||||
details: { status: "failed" },
|
details: { status: "failed" },
|
||||||
};
|
};
|
||||||
@@ -619,7 +663,10 @@ export const processTool: AgentTool<typeof processSchema> = {
|
|||||||
content: [
|
content: [
|
||||||
{ type: "text", text: `Killed session ${params.sessionId}.` },
|
{ type: "text", text: `Killed session ${params.sessionId}.` },
|
||||||
],
|
],
|
||||||
details: { status: "failed" },
|
details: {
|
||||||
|
status: "failed",
|
||||||
|
name: session ? deriveSessionName(session.command) : undefined,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -654,7 +701,10 @@ export const processTool: AgentTool<typeof processSchema> = {
|
|||||||
content: [
|
content: [
|
||||||
{ type: "text", text: `Removed session ${params.sessionId}.` },
|
{ type: "text", text: `Removed session ${params.sessionId}.` },
|
||||||
],
|
],
|
||||||
details: { status: "failed" },
|
details: {
|
||||||
|
status: "failed",
|
||||||
|
name: session ? deriveSessionName(session.command) : undefined,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (finished) {
|
if (finished) {
|
||||||
@@ -683,6 +733,9 @@ export const processTool: AgentTool<typeof processSchema> = {
|
|||||||
};
|
};
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const processTool = createProcessTool();
|
||||||
|
|
||||||
function clampNumber(
|
function clampNumber(
|
||||||
value: number | undefined,
|
value: number | undefined,
|
||||||
@@ -715,6 +768,62 @@ function truncateMiddle(str: string, max: number) {
|
|||||||
return `${str.slice(0, half)}...${str.slice(str.length - half)}`;
|
return `${str.slice(0, half)}...${str.slice(str.length - half)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function sliceLogLines(
|
||||||
|
text: string,
|
||||||
|
offset?: number,
|
||||||
|
limit?: number,
|
||||||
|
): { slice: string; totalLines: number; totalChars: number } {
|
||||||
|
if (!text) return { slice: "", totalLines: 0, totalChars: 0 };
|
||||||
|
const normalized = text.replace(/\r\n/g, "\n");
|
||||||
|
const lines = normalized.split("\n");
|
||||||
|
if (lines.length > 0 && lines[lines.length - 1] === "") {
|
||||||
|
lines.pop();
|
||||||
|
}
|
||||||
|
const totalLines = lines.length;
|
||||||
|
const totalChars = text.length;
|
||||||
|
let start =
|
||||||
|
typeof offset === "number" && Number.isFinite(offset)
|
||||||
|
? Math.max(0, Math.floor(offset))
|
||||||
|
: 0;
|
||||||
|
if (limit !== undefined && offset === undefined) {
|
||||||
|
const tailCount = Math.max(0, Math.floor(limit));
|
||||||
|
start = Math.max(totalLines - tailCount, 0);
|
||||||
|
}
|
||||||
|
const end =
|
||||||
|
typeof limit === "number" && Number.isFinite(limit)
|
||||||
|
? start + Math.max(0, Math.floor(limit))
|
||||||
|
: undefined;
|
||||||
|
return { slice: lines.slice(start, end).join("\n"), totalLines, totalChars };
|
||||||
|
}
|
||||||
|
|
||||||
|
function deriveSessionName(command: string): string | undefined {
|
||||||
|
const tokens = tokenizeCommand(command);
|
||||||
|
if (tokens.length === 0) return undefined;
|
||||||
|
const verb = tokens[0];
|
||||||
|
let target = tokens.slice(1).find((t) => !t.startsWith("-"));
|
||||||
|
if (!target) target = tokens[1];
|
||||||
|
if (!target) return verb;
|
||||||
|
const cleaned = truncateMiddle(stripQuotes(target), 48);
|
||||||
|
return `${stripQuotes(verb)} ${cleaned}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tokenizeCommand(command: string): string[] {
|
||||||
|
const matches =
|
||||||
|
command.match(/(?:[^\s"']+|"(?:\\.|[^"])*"|'(?:\\.|[^'])*')+/g) ?? [];
|
||||||
|
return matches.map((token) => stripQuotes(token)).filter(Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
function stripQuotes(value: string): string {
|
||||||
|
const trimmed = value.trim();
|
||||||
|
if (
|
||||||
|
(trimmed.startsWith("\"") && trimmed.endsWith("\"")) ||
|
||||||
|
(trimmed.startsWith("'") && trimmed.endsWith("'"))
|
||||||
|
) {
|
||||||
|
return trimmed.slice(1, -1);
|
||||||
|
}
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
function formatDuration(ms: number) {
|
function formatDuration(ms: number) {
|
||||||
if (ms < 1000) return `${ms}ms`;
|
if (ms < 1000) return `${ms}ms`;
|
||||||
const seconds = Math.floor(ms / 1000);
|
const seconds = Math.floor(ms / 1000);
|
||||||
|
|||||||
@@ -325,7 +325,9 @@ export async function runEmbeddedPiAgent(params: {
|
|||||||
await loadWorkspaceBootstrapFiles(resolvedWorkspace);
|
await loadWorkspaceBootstrapFiles(resolvedWorkspace);
|
||||||
const contextFiles = buildBootstrapContextFiles(bootstrapFiles);
|
const contextFiles = buildBootstrapContextFiles(bootstrapFiles);
|
||||||
const promptSkills = resolvePromptSkills(skillsSnapshot, skillEntries);
|
const promptSkills = resolvePromptSkills(skillsSnapshot, skillEntries);
|
||||||
const tools = createClawdisCodingTools();
|
const tools = createClawdisCodingTools({
|
||||||
|
bash: params.config?.agent?.bash,
|
||||||
|
});
|
||||||
const machineName = await getMachineDisplayName();
|
const machineName = await getMachineDisplayName();
|
||||||
const runtimeInfo = {
|
const runtimeInfo = {
|
||||||
host: machineName,
|
host: machineName,
|
||||||
|
|||||||
@@ -32,6 +32,9 @@ describe("createClawdisCodingTools", () => {
|
|||||||
anyOf?: Array<{ properties?: Record<string, unknown> }>;
|
anyOf?: Array<{ properties?: Record<string, unknown> }>;
|
||||||
properties?: Record<string, unknown>;
|
properties?: Record<string, unknown>;
|
||||||
};
|
};
|
||||||
|
if (!Array.isArray(parameters.anyOf) || parameters.anyOf.length === 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
const actionValues = new Set<string>();
|
const actionValues = new Set<string>();
|
||||||
for (const variant of parameters.anyOf ?? []) {
|
for (const variant of parameters.anyOf ?? []) {
|
||||||
const action = variant?.properties?.action as
|
const action = variant?.properties?.action as
|
||||||
@@ -45,6 +48,9 @@ describe("createClawdisCodingTools", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (actionValues.size <= 1) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
const mergedAction = parameters.properties?.action as
|
const mergedAction = parameters.properties?.action as
|
||||||
| { const?: unknown; enum?: unknown[] }
|
| { const?: unknown; enum?: unknown[] }
|
||||||
| undefined;
|
| undefined;
|
||||||
|
|||||||
@@ -4,7 +4,12 @@ import { type TSchema, Type } from "@sinclair/typebox";
|
|||||||
|
|
||||||
import { detectMime } from "../media/mime.js";
|
import { detectMime } from "../media/mime.js";
|
||||||
import { startWebLoginWithQr, waitForWebLogin } from "../web/login-qr.js";
|
import { startWebLoginWithQr, waitForWebLogin } from "../web/login-qr.js";
|
||||||
import { bashTool, processTool } from "./bash-tools.js";
|
import {
|
||||||
|
type BashToolDefaults,
|
||||||
|
type ProcessToolDefaults,
|
||||||
|
createBashTool,
|
||||||
|
createProcessTool,
|
||||||
|
} from "./bash-tools.js";
|
||||||
import { createClawdisTools } from "./clawdis-tools.js";
|
import { createClawdisTools } from "./clawdis-tools.js";
|
||||||
import { sanitizeToolResultImages } from "./tool-images.js";
|
import { sanitizeToolResultImages } from "./tool-images.js";
|
||||||
|
|
||||||
@@ -288,18 +293,24 @@ function createClawdisReadTool(base: AnyAgentTool): AnyAgentTool {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createClawdisCodingTools(): AnyAgentTool[] {
|
export function createClawdisCodingTools(options?: {
|
||||||
|
bash?: BashToolDefaults & ProcessToolDefaults;
|
||||||
|
}): AnyAgentTool[] {
|
||||||
|
const bashToolName = "bash";
|
||||||
const base = (codingTools as unknown as AnyAgentTool[]).flatMap((tool) => {
|
const base = (codingTools as unknown as AnyAgentTool[]).flatMap((tool) => {
|
||||||
if (tool.name === readTool.name) return [createClawdisReadTool(tool)];
|
if (tool.name === readTool.name) return [createClawdisReadTool(tool)];
|
||||||
if (tool.name === bashTool.name) return [];
|
if (tool.name === bashToolName) return [];
|
||||||
return [tool as AnyAgentTool];
|
return [tool as AnyAgentTool];
|
||||||
});
|
});
|
||||||
const tools: AnyAgentTool[] = [
|
const bashTool = createBashTool(options?.bash);
|
||||||
|
const processTool = createProcessTool({
|
||||||
|
cleanupMs: options?.bash?.cleanupMs,
|
||||||
|
});
|
||||||
|
return [
|
||||||
...base,
|
...base,
|
||||||
bashTool as unknown as AnyAgentTool,
|
bashTool,
|
||||||
processTool as unknown as AnyAgentTool,
|
processTool,
|
||||||
createWhatsAppLoginTool(),
|
createWhatsAppLoginTool(),
|
||||||
...createClawdisTools(),
|
...createClawdisTools(),
|
||||||
];
|
].map(normalizeToolParameters);
|
||||||
return tools.map(normalizeToolParameters);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -325,6 +325,15 @@ export type ClawdisConfig = {
|
|||||||
typingIntervalSeconds?: number;
|
typingIntervalSeconds?: number;
|
||||||
/** Periodic background heartbeat runs (minutes). 0 disables. */
|
/** Periodic background heartbeat runs (minutes). 0 disables. */
|
||||||
heartbeatMinutes?: number;
|
heartbeatMinutes?: number;
|
||||||
|
/** Bash tool defaults. */
|
||||||
|
bash?: {
|
||||||
|
/** Default time (ms) before a bash command auto-backgrounds. */
|
||||||
|
backgroundMs?: number;
|
||||||
|
/** Default timeout (seconds) before auto-killing bash commands. */
|
||||||
|
timeoutSec?: number;
|
||||||
|
/** How long to keep finished sessions in memory (ms). */
|
||||||
|
cleanupMs?: number;
|
||||||
|
};
|
||||||
};
|
};
|
||||||
routing?: RoutingConfig;
|
routing?: RoutingConfig;
|
||||||
messages?: MessagesConfig;
|
messages?: MessagesConfig;
|
||||||
@@ -573,6 +582,13 @@ const ClawdisSchema = z.object({
|
|||||||
mediaMaxMb: z.number().positive().optional(),
|
mediaMaxMb: z.number().positive().optional(),
|
||||||
typingIntervalSeconds: z.number().int().positive().optional(),
|
typingIntervalSeconds: z.number().int().positive().optional(),
|
||||||
heartbeatMinutes: z.number().nonnegative().optional(),
|
heartbeatMinutes: z.number().nonnegative().optional(),
|
||||||
|
bash: z
|
||||||
|
.object({
|
||||||
|
backgroundMs: z.number().int().positive().optional(),
|
||||||
|
timeoutSec: z.number().int().positive().optional(),
|
||||||
|
cleanupMs: z.number().int().positive().optional(),
|
||||||
|
})
|
||||||
|
.optional(),
|
||||||
})
|
})
|
||||||
.optional(),
|
.optional(),
|
||||||
routing: RoutingSchema,
|
routing: RoutingSchema,
|
||||||
|
|||||||
Reference in New Issue
Block a user