@oyasmi/pipiclaw 0.7.5 → 0.7.6

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/README.md CHANGED
@@ -24,7 +24,11 @@ npm package: [`@oyasmi/pipiclaw`](https://www.npmjs.com/package/@oyasmi/pipiclaw
24
24
  - 支持预定义子代理(sub-agent)和临时内联子代理(inline sub-agent)
25
25
  - 支持立即、单次、周期三类事件调度
26
26
  - 支持自定义模型提供方(provider)和模型(model)配置
27
- - 内建 `web_search` / `web_fetch`,支持联网搜索与网页抓取
27
+ - 内建 `web_search` / `web_fetch`,支持联网搜索与网页抓取;`web_fetch` 支持结果缓存与分页续读,长网页被截断后可直接续读、不重抓
28
+ - 内建 `grep` 结构化搜索工具:按文件分组、分页、token 有界的内容检索,优于裸 `bash grep`
29
+ - 支持后台作业:`bash async` + `job` 工具,长命令后台运行、不阻塞频道,可 poll / cancel
30
+ - 内建 `memory_manage` 记忆管理:按需保存 / 检索 / 忘记稳定记忆,写操作串行化,避免与后台整理竞态
31
+ - `read` 支持读取目录树与 PDF 文档(`pdftotext`)
28
32
  - 内建 `session_search`,可按需检索当前会话通道的冷存储历史
29
33
  - 内建 workspace skill 管理工具,可查看、创建和维护 `workspace/skills/`
30
34
  - 内置工具层安全防护:`bash` 命令守卫、文件路径守卫、敏感路径拒绝、阻断审计日志
@@ -0,0 +1,79 @@
1
+ import type { Executor } from "../sandbox.js";
2
+ /**
3
+ * Per-channel manager for background bash jobs. A long command that ran synchronously would hold
4
+ * the channel's run queue for its whole duration, blocking `/steer`, `/followup`, and every other
5
+ * message. A background job instead returns immediately; the model can end its turn (freeing the
6
+ * queue) and check back later — typically by scheduling a check-in with `event_manage`, or by
7
+ * calling the `job` tool to poll.
8
+ *
9
+ * Jobs live entirely in the executor's world (host or Docker), managed through shell commands
10
+ * (`nohup` to launch, `kill -0` to probe, `kill` to cancel), so this works identically in both
11
+ * sandboxes with no in-process child handles. Manager state is in-memory and not persisted: after a
12
+ * process restart, prior jobs surface as `lost` rather than being falsely resurrected.
13
+ */
14
+ export type JobStatus = "running" | "completed" | "failed" | "cancelled" | "lost";
15
+ export interface JobSnapshot {
16
+ id: string;
17
+ label: string;
18
+ command: string;
19
+ status: JobStatus;
20
+ startedAt: number;
21
+ durationMs: number;
22
+ exitCode?: number;
23
+ }
24
+ /** Cap on concurrently running jobs per channel, so a runaway model can't spawn unbounded processes. */
25
+ export declare const MAX_RUNNING_JOBS = 5;
26
+ /** Longest a single `poll` call blocks before returning a snapshot; the model can poll again. */
27
+ export declare const POLL_WAIT_MS = 30000;
28
+ /**
29
+ * How often the internal sweeper refreshes running jobs while any are alive. Without it, a job that
30
+ * finishes (or overruns its timeout) is only reaped when the model happens to call list/poll/cancel —
31
+ * so a never-polled job would hold a `MAX_RUNNING_JOBS` slot forever, eventually blocking all `async`.
32
+ * The sweep only reconciles in-memory state (and enforces the hard timeout); it never wakes the
33
+ * channel, so it stays within the design's "no automatic completion delivery" decision.
34
+ */
35
+ export declare const SWEEP_INTERVAL_MS = 10000;
36
+ export declare class ChannelJobManager {
37
+ private readonly channelId;
38
+ private readonly executor;
39
+ private readonly sweepIntervalMs;
40
+ private readonly jobs;
41
+ private sweepTimer?;
42
+ private sweeping;
43
+ constructor(channelId: string, executor: Executor, sweepIntervalMs?: number);
44
+ get channel(): string;
45
+ runningCount(): number;
46
+ /**
47
+ * Launch a command in the background and return its job id. The wrapper writes merged
48
+ * stdout/stderr to a spill file and the command's exit code to a sibling `.exit` file, then
49
+ * `echo $!` hands back the nohup PID for later probing/cancellation.
50
+ */
51
+ start(command: string, label: string, timeoutSeconds: number, signal?: AbortSignal): Promise<JobSnapshot>;
52
+ /**
53
+ * Start the low-frequency sweeper if it is not already running. It reaps finished/timed-out jobs
54
+ * so their slots free up even when the model never polls, and stops itself once nothing is running.
55
+ */
56
+ private ensureSweeper;
57
+ private stopSweeper;
58
+ private sweep;
59
+ /** Refresh the status of a single running job by consulting its `.exit` file and liveness. */
60
+ private refresh;
61
+ private kill;
62
+ list(signal?: AbortSignal): Promise<JobSnapshot[]>;
63
+ cancel(ids: string[], signal?: AbortSignal): Promise<Array<{
64
+ id: string;
65
+ status: JobStatus | "not_found";
66
+ }>>;
67
+ /**
68
+ * Wait until at least one watched job finishes or the wait window elapses, then return a
69
+ * snapshot. Returns immediately if a watched job is already finished. `ids` omitted watches all
70
+ * running jobs.
71
+ */
72
+ poll(ids: string[] | undefined, signal?: AbortSignal): Promise<JobSnapshot[]>;
73
+ /** Read the (possibly truncated) captured output of a finished or running job. */
74
+ readOutput(id: string, signal?: AbortSignal): Promise<{
75
+ spillFile: string;
76
+ text: string;
77
+ } | undefined>;
78
+ }
79
+ export declare function getChannelJobManager(channelId: string, executor: Executor): ChannelJobManager;
@@ -0,0 +1,241 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { shellEscape } from "../shared/shell-escape.js";
3
+ /** Cap on concurrently running jobs per channel, so a runaway model can't spawn unbounded processes. */
4
+ export const MAX_RUNNING_JOBS = 5;
5
+ /** Longest a single `poll` call blocks before returning a snapshot; the model can poll again. */
6
+ export const POLL_WAIT_MS = 30_000;
7
+ const POLL_CHECK_INTERVAL_MS = 3_000;
8
+ /**
9
+ * How often the internal sweeper refreshes running jobs while any are alive. Without it, a job that
10
+ * finishes (or overruns its timeout) is only reaped when the model happens to call list/poll/cancel —
11
+ * so a never-polled job would hold a `MAX_RUNNING_JOBS` slot forever, eventually blocking all `async`.
12
+ * The sweep only reconciles in-memory state (and enforces the hard timeout); it never wakes the
13
+ * channel, so it stays within the design's "no automatic completion delivery" decision.
14
+ */
15
+ export const SWEEP_INTERVAL_MS = 10_000;
16
+ function jobSpillPath(id) {
17
+ return `/tmp/pipiclaw-job-${id}.log`;
18
+ }
19
+ function sleep(ms, signal) {
20
+ return new Promise((resolve) => {
21
+ const timer = setTimeout(resolve, ms);
22
+ signal?.addEventListener("abort", () => {
23
+ clearTimeout(timer);
24
+ resolve();
25
+ }, { once: true });
26
+ });
27
+ }
28
+ function toSnapshot(record) {
29
+ return {
30
+ id: record.id,
31
+ label: record.label,
32
+ command: record.command,
33
+ status: record.status,
34
+ startedAt: record.startedAt,
35
+ durationMs: record.status === "running" ? Date.now() - record.startedAt : record.durationMs,
36
+ exitCode: record.exitCode,
37
+ };
38
+ }
39
+ export class ChannelJobManager {
40
+ constructor(channelId, executor, sweepIntervalMs = SWEEP_INTERVAL_MS) {
41
+ this.channelId = channelId;
42
+ this.executor = executor;
43
+ this.sweepIntervalMs = sweepIntervalMs;
44
+ this.jobs = new Map();
45
+ this.sweeping = false;
46
+ }
47
+ get channel() {
48
+ return this.channelId;
49
+ }
50
+ runningCount() {
51
+ return Array.from(this.jobs.values()).filter((job) => job.status === "running").length;
52
+ }
53
+ /**
54
+ * Launch a command in the background and return its job id. The wrapper writes merged
55
+ * stdout/stderr to a spill file and the command's exit code to a sibling `.exit` file, then
56
+ * `echo $!` hands back the nohup PID for later probing/cancellation.
57
+ */
58
+ async start(command, label, timeoutSeconds, signal) {
59
+ if (this.runningCount() >= MAX_RUNNING_JOBS) {
60
+ throw new Error(`Too many background jobs already running (>= ${MAX_RUNNING_JOBS}). Poll or cancel some with the job tool first.`);
61
+ }
62
+ const id = randomBytes(6).toString("hex");
63
+ const spillFile = jobSpillPath(id);
64
+ const exitFile = `${spillFile}.exit`;
65
+ // Run the user command inside a subshell so its own `exit` only leaves the subshell and the
66
+ // exit-capture line still runs; otherwise a command ending in `exit N` would skip it and the
67
+ // job would look `lost` instead of finished.
68
+ const inner = `( ${command} )\n__pc_rc=$?; echo "$__pc_rc" > ${shellEscape(exitFile)}`;
69
+ const launch = `rm -f ${shellEscape(exitFile)}; nohup sh -c ${shellEscape(inner)} > ${shellEscape(spillFile)} 2>&1 & echo $!`;
70
+ const result = await this.executor.exec(launch, { signal });
71
+ const pid = Number.parseInt(result.stdout.trim(), 10);
72
+ if (!Number.isFinite(pid) || pid <= 0) {
73
+ throw new Error(`Failed to start background job: ${result.stderr.trim() || "no PID returned"}`);
74
+ }
75
+ const now = Date.now();
76
+ const record = {
77
+ id,
78
+ label,
79
+ command,
80
+ status: "running",
81
+ startedAt: now,
82
+ durationMs: 0,
83
+ pid,
84
+ spillFile,
85
+ exitFile,
86
+ timeoutSeconds,
87
+ };
88
+ this.jobs.set(id, record);
89
+ this.ensureSweeper();
90
+ return toSnapshot(record);
91
+ }
92
+ /**
93
+ * Start the low-frequency sweeper if it is not already running. It reaps finished/timed-out jobs
94
+ * so their slots free up even when the model never polls, and stops itself once nothing is running.
95
+ */
96
+ ensureSweeper() {
97
+ if (this.sweepTimer || this.runningCount() === 0) {
98
+ return;
99
+ }
100
+ this.sweepTimer = setInterval(() => {
101
+ void this.sweep();
102
+ }, this.sweepIntervalMs);
103
+ // Do not keep the process alive just for the sweeper.
104
+ this.sweepTimer.unref?.();
105
+ }
106
+ stopSweeper() {
107
+ if (this.sweepTimer) {
108
+ clearInterval(this.sweepTimer);
109
+ this.sweepTimer = undefined;
110
+ }
111
+ }
112
+ async sweep() {
113
+ if (this.sweeping) {
114
+ return; // A prior sweep is still awaiting the executor; skip this tick.
115
+ }
116
+ this.sweeping = true;
117
+ try {
118
+ for (const record of this.jobs.values()) {
119
+ if (record.status === "running") {
120
+ await this.refresh(record).catch(() => { });
121
+ }
122
+ }
123
+ }
124
+ finally {
125
+ this.sweeping = false;
126
+ if (this.runningCount() === 0) {
127
+ this.stopSweeper();
128
+ }
129
+ }
130
+ }
131
+ /** Refresh the status of a single running job by consulting its `.exit` file and liveness. */
132
+ async refresh(record, signal) {
133
+ if (record.status !== "running") {
134
+ return;
135
+ }
136
+ // Read the exit-code file if present, and separately check whether the PID is still alive.
137
+ const probe = await this.executor.exec(`if [ -f ${shellEscape(record.exitFile)} ]; then echo "EXIT:$(cat ${shellEscape(record.exitFile)})"; ` +
138
+ `elif kill -0 ${record.pid} 2>/dev/null; then echo ALIVE; else echo GONE; fi`, { signal });
139
+ const out = probe.stdout.trim();
140
+ if (out.startsWith("EXIT:")) {
141
+ const code = Number.parseInt(out.slice("EXIT:".length).trim(), 10);
142
+ record.exitCode = Number.isFinite(code) ? code : undefined;
143
+ record.status = code === 0 ? "completed" : "failed";
144
+ record.durationMs = Date.now() - record.startedAt;
145
+ return;
146
+ }
147
+ if (out === "GONE") {
148
+ // Process vanished without writing an exit code (killed externally, or manager restarted).
149
+ record.status = "lost";
150
+ record.durationMs = Date.now() - record.startedAt;
151
+ return;
152
+ }
153
+ // Still alive: enforce the wall-clock budget from JS so we do not depend on a `timeout` binary.
154
+ if (Date.now() - record.startedAt > record.timeoutSeconds * 1000) {
155
+ await this.kill(record, signal);
156
+ record.status = "failed";
157
+ record.exitCode = 124;
158
+ record.durationMs = Date.now() - record.startedAt;
159
+ }
160
+ }
161
+ async kill(record, signal) {
162
+ await this.executor
163
+ .exec(`kill ${record.pid} 2>/dev/null; sleep 0.2; kill -9 ${record.pid} 2>/dev/null; true`, { signal })
164
+ .catch(() => { });
165
+ }
166
+ async list(signal) {
167
+ for (const record of this.jobs.values()) {
168
+ await this.refresh(record, signal);
169
+ }
170
+ return Array.from(this.jobs.values()).map(toSnapshot);
171
+ }
172
+ async cancel(ids, signal) {
173
+ const results = [];
174
+ for (const id of ids) {
175
+ const record = this.jobs.get(id);
176
+ if (!record) {
177
+ results.push({ id, status: "not_found" });
178
+ continue;
179
+ }
180
+ await this.refresh(record, signal);
181
+ if (record.status !== "running") {
182
+ results.push({ id, status: record.status });
183
+ continue;
184
+ }
185
+ await this.kill(record, signal);
186
+ record.status = "cancelled";
187
+ record.durationMs = Date.now() - record.startedAt;
188
+ results.push({ id, status: "cancelled" });
189
+ }
190
+ return results;
191
+ }
192
+ /**
193
+ * Wait until at least one watched job finishes or the wait window elapses, then return a
194
+ * snapshot. Returns immediately if a watched job is already finished. `ids` omitted watches all
195
+ * running jobs.
196
+ */
197
+ async poll(ids, signal) {
198
+ const deadline = Date.now() + POLL_WAIT_MS;
199
+ const watchIds = () => ids && ids.length > 0
200
+ ? ids.filter((id) => this.jobs.has(id))
201
+ : Array.from(this.jobs.values())
202
+ .filter((job) => job.status === "running")
203
+ .map((job) => job.id);
204
+ while (true) {
205
+ for (const id of watchIds()) {
206
+ const record = this.jobs.get(id);
207
+ if (record) {
208
+ await this.refresh(record, signal);
209
+ }
210
+ }
211
+ const watched = watchIds()
212
+ .map((id) => this.jobs.get(id))
213
+ .filter((record) => record !== undefined);
214
+ const anyDone = watched.some((record) => record.status !== "running");
215
+ if (watched.length === 0 || anyDone || Date.now() >= deadline || signal?.aborted) {
216
+ return watched.map(toSnapshot);
217
+ }
218
+ await sleep(POLL_CHECK_INTERVAL_MS, signal);
219
+ }
220
+ }
221
+ /** Read the (possibly truncated) captured output of a finished or running job. */
222
+ async readOutput(id, signal) {
223
+ const record = this.jobs.get(id);
224
+ if (!record) {
225
+ return undefined;
226
+ }
227
+ const result = await this.executor.exec(`cat ${shellEscape(record.spillFile)} 2>/dev/null || true`, { signal });
228
+ return { spillFile: record.spillFile, text: result.stdout };
229
+ }
230
+ }
231
+ // One manager per channel, shared across tool rebuilds so job records survive a resource reload —
232
+ // mirrors the shared singletons used elsewhere in the runtime (e.g. the channel memory queue).
233
+ const managers = new Map();
234
+ export function getChannelJobManager(channelId, executor) {
235
+ let manager = managers.get(channelId);
236
+ if (!manager) {
237
+ manager = new ChannelJobManager(channelId, executor);
238
+ managers.set(channelId, manager);
239
+ }
240
+ return manager;
241
+ }
@@ -81,7 +81,16 @@ You can schedule events that wake you up at specific times or when external thin
81
81
  ### Cron Format
82
82
  \`minute hour day-of-month month day-of-week\`
83
83
 
84
- ### Creating Events
84
+ ${hasTool("event_manage")
85
+ ? `### Creating Events
86
+ Prefer the event_manage tool to create, update, or delete your own scheduled events: it validates the payload on write (an invalid event would otherwise be silently dropped) and enforces the scheduling guards below. Editing the JSON files directly with the file tools still works but skips that validation.
87
+
88
+ ### Silent Completion
89
+ For periodic events where there's nothing to report, respond with just \`[SILENT]\`. This deletes the status message. Use this to avoid spam when periodic checks find nothing.
90
+
91
+ ### Limits
92
+ event_manage rejects self-triggering loops: no immediate events (do that work in the current turn), one-shot at least 2 minutes out, periodic no more often than every 30 minutes (5 minutes when it carries a preAction gate), and at most 50 event files. Name task-owned events \`task.<channelId>.<taskId>.<use>\` so they clean up together.`
93
+ : `### Creating Events
85
94
  Create a JSON file under \`${workspacePath}/events/\` with the appropriate event payload.
86
95
  Prefer the file tools for creating or editing the event file. Use shell commands only when they are the clearest option.
87
96
 
@@ -89,14 +98,14 @@ Prefer the file tools for creating or editing the event file. Use shell commands
89
98
  For periodic events where there's nothing to report, respond with just \`[SILENT]\`. This deletes the status message. Use this to avoid spam when periodic checks find nothing.
90
99
 
91
100
  ### Limits
92
- Maximum 5 events can be queued.`);
101
+ The scheduler ignores invalid files and de-duplicates by filename; keep the events directory tidy.`}`);
93
102
  const runtimeBehaviorLines = [
94
103
  "- The runtime may inject a small amount of relevant memory context from SESSION.md / MEMORY.md / HISTORY.md into a turn when it is clearly useful.",
95
104
  "- SESSION.md is the primary runtime-managed working-state artifact for current active work.",
96
105
  "- The runtime automatically consolidates channel MEMORY.md and HISTORY.md before compaction or session trimming, and sweeps durable facts into MEMORY.md in the background.",
97
106
  ];
98
- if (hasTool("memory_save")) {
99
- runtimeBehaviorLines.push("- When the user explicitly asks you to remember, prefer, default to, or stop doing something durable, call memory_save right away instead of waiting for background consolidation. Use it only for durable facts/preferences/decisions/constraints, not transient task state.");
107
+ if (hasTool("memory_manage")) {
108
+ runtimeBehaviorLines.push("- When the user explicitly asks you to remember, prefer, default to, or stop doing something durable, call memory_manage (op: save) right away instead of waiting for background consolidation. Use it only for durable facts/preferences/decisions/constraints, not transient task state.", "- When the user asks you to forget or drop something durable, use memory_manage (op: forget) rather than editing MEMORY.md directly, so the change serializes with background consolidation. To look something up mid-task, use memory_manage (op: search).", "- Do not use edit or write to change channel MEMORY.md or HISTORY.md directly; those files are runtime-managed and must go through memory_manage, which serializes with background consolidation.");
100
109
  }
101
110
  runtimeBehaviorLines.push("- Workspace MEMORY.md is not updated by normal runtime consolidation.", "- ENVIRONMENT.md is not normal conversational memory. Read it only when environment history or machine state matters.");
102
111
  const coldStorageLines = [
@@ -1,4 +1,4 @@
1
- export type MemoryReviewReason = "idle" | "compaction" | "new-session" | "shutdown" | "post-turn" | "session-refresh-job" | "durable-consolidation-job" | "growth-review-job" | "structural-maintenance-job";
1
+ export type MemoryReviewReason = "idle" | "compaction" | "new-session" | "shutdown" | "post-turn" | "session-refresh-job" | "durable-consolidation-job" | "growth-review-job" | "structural-maintenance-job" | "user-forget";
2
2
  export interface MemoryReviewLogEntry {
3
3
  timestamp: string;
4
4
  channelId: string;
@@ -1,5 +1,6 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { Type } from "typebox";
3
+ import type { ChannelJobManager } from "../agent/job-manager.js";
3
4
  import type { Executor } from "../sandbox.js";
4
5
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
5
6
  /**
@@ -13,6 +14,7 @@ declare const bashSchema: Type.TObject<{
13
14
  label: Type.TString;
14
15
  command: Type.TString;
15
16
  timeout: Type.TOptional<Type.TInteger>;
17
+ async: Type.TOptional<Type.TBoolean>;
16
18
  }>;
17
19
  export interface BashToolOptions {
18
20
  defaultTimeoutSeconds?: number;
@@ -25,6 +27,16 @@ export interface BashToolOptions {
25
27
  * Gated by `tools.rtk.enabled` in tools.json.
26
28
  */
27
29
  rtkEnabled?: boolean;
30
+ /**
31
+ * Present only on the main path when `tools.jobs.enabled` is on. Enables `async: true`
32
+ * background execution. Absent on the sub-agent path, so sub-agents cannot background jobs.
33
+ */
34
+ jobManager?: ChannelJobManager;
35
+ /**
36
+ * When true (`tools.bashInterceptor.enabled`), block a few bare shell patterns that have a
37
+ * better dedicated tool and steer the model to it. Off by default; main path only.
38
+ */
39
+ interceptorEnabled?: boolean;
28
40
  }
29
41
  export declare function createBashTool(executor: Executor, options?: BashToolOptions): AgentTool<typeof bashSchema>;
30
42
  export {};
@@ -30,7 +30,44 @@ const bashSchema = Type.Object({
30
30
  minimum: 1,
31
31
  description: `Timeout in seconds. Defaults to ${DEFAULT_BASH_TIMEOUT_SECONDS}s; pass a larger value for long-running commands.`,
32
32
  })),
33
+ async: Type.Optional(Type.Boolean({
34
+ description: "Run in the background and return immediately with a job id instead of blocking. Use for long commands so the channel stays responsive; check it later with the job tool or a scheduled event_manage check-in.",
35
+ })),
33
36
  });
37
+ /**
38
+ * Bare shell patterns that a dedicated tool handles better (with truncation, grouping, or a diff).
39
+ * Deliberately narrow — only unambiguous bare forms, never piped/compound commands — so a legitimate
40
+ * `cat x | jq` is untouched. Runs after the security guard (which must see the real command) and
41
+ * before rtk. Complements rtk: rtk makes output cheaper, this steers to the right tool.
42
+ */
43
+ const BASH_INTERCEPTOR_RULES = [
44
+ {
45
+ test: /^\s*cat\s+[^|&;<>`$()]+$/,
46
+ tool: "read",
47
+ why: "it truncates safely and tells you how to page through the rest",
48
+ },
49
+ {
50
+ // Anchored to end and free of pipe/redirect chars so only a *bare* recursive grep is caught;
51
+ // a piped/compound form like `grep -rn foo . | wc -l` is a legitimate use and must pass through.
52
+ test: /^\s*grep\b[^|&;<>]*\s-[A-Za-z]*r[A-Za-z]*\b[^|&;<>]*$/,
53
+ tool: "grep",
54
+ why: "it groups, paginates, and bounds output instead of flooding the context",
55
+ },
56
+ { test: /^\s*rg\b[^|&;]*$/, tool: "grep", why: "it groups, paginates, and bounds output" },
57
+ {
58
+ test: /\b(?:sed|perl)\b[^|&;]*\s-i\b/,
59
+ tool: "edit",
60
+ why: "it verifies a unique match and echoes a diff of the change",
61
+ },
62
+ ];
63
+ function checkBashInterception(command) {
64
+ for (const rule of BASH_INTERCEPTOR_RULES) {
65
+ if (rule.test.test(command)) {
66
+ return `Blocked: use the ${rule.tool} tool instead — ${rule.why}. Command: ${command}`;
67
+ }
68
+ }
69
+ return null;
70
+ }
34
71
  function formatCommandBlockMessage(command, category, reason, matchedText) {
35
72
  const lines = [`Command blocked${category ? ` [${category}]` : ""}`];
36
73
  if (reason) {
@@ -42,6 +79,7 @@ function formatCommandBlockMessage(command, category, reason, matchedText) {
42
79
  else {
43
80
  lines.push(`Command: ${command}`);
44
81
  }
82
+ lines.push("If this operation is genuinely needed, explain the intent to the user so they can adjust security.json.");
45
83
  return lines.join("\n");
46
84
  }
47
85
  export function createBashTool(executor, options = {}) {
@@ -56,7 +94,7 @@ export function createBashTool(executor, options = {}) {
56
94
  label: "bash",
57
95
  description: `Execute a bash command in the current working directory. Returns stdout, stderr, and the exit code (a non-zero exit code is reported in the output, not raised as an error). Output is truncated to the last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, the full output is saved to a temp file whose path is included. Commands time out after ${DEFAULT_BASH_TIMEOUT_SECONDS}s unless you pass a larger \`timeout\`.`,
58
96
  parameters: bashSchema,
59
- execute: async (_toolCallId, { command, timeout }, signal) => {
97
+ execute: async (_toolCallId, { label, command, timeout, async: runAsync, }, signal) => {
60
98
  if (securityConfig.enabled && securityConfig.commandGuard.enabled) {
61
99
  const guardResult = guardCommand(command, securityConfig.commandGuard);
62
100
  if (!guardResult.allowed) {
@@ -73,11 +111,39 @@ export function createBashTool(executor, options = {}) {
73
111
  throw new Error(formatCommandBlockMessage(command, guardResult.category, guardResult.reason, guardResult.matchedText));
74
112
  }
75
113
  }
114
+ // Steer a few bare shell patterns to their dedicated tool. After the guard (which must see
115
+ // the real command), before rtk (which would reshape it). Off by default.
116
+ if (options.interceptorEnabled) {
117
+ const intercepted = checkBashInterception(command);
118
+ if (intercepted) {
119
+ throw new Error(intercepted);
120
+ }
121
+ }
76
122
  // Optimize *after* the security guard: the guard must inspect the operator's real
77
123
  // intent (`command`), while rtk only reshapes a semantically-equivalent command for
78
124
  // compact output. Optimizing first would hide the true command from the guard.
79
125
  const effectiveCommand = options.rtkEnabled ? await maybeOptimizeCommand(command, executor, signal) : command;
80
126
  const effectiveTimeout = timeout ?? options.defaultTimeoutSeconds ?? DEFAULT_BASH_TIMEOUT_SECONDS;
127
+ // Background execution: hand off to the channel's job manager and return immediately so
128
+ // the run queue is not held for the command's duration. Gated by `tools.jobs.enabled`
129
+ // (the main path supplies a jobManager; the sub-agent path never does).
130
+ if (runAsync) {
131
+ if (!options.jobManager) {
132
+ throw new Error("Background execution is not available here (enable tools.jobs.enabled, and note it is off for sub-agents). Run the command without async, or shorten it.");
133
+ }
134
+ const job = await options.jobManager.start(effectiveCommand, label, effectiveTimeout, signal);
135
+ return {
136
+ content: [
137
+ {
138
+ type: "text",
139
+ text: `Background job ${job.id} started: ${label}\n` +
140
+ "It runs off-turn; you can end your turn now. Check it with the job tool (op:poll/list), " +
141
+ "or schedule an event_manage check-in to be woken when it is likely done.",
142
+ },
143
+ ],
144
+ details: { kind: "bash", async: { state: "running", jobId: job.id } },
145
+ };
146
+ }
81
147
  const result = await executor.exec(effectiveCommand, { timeout: effectiveTimeout, signal });
82
148
  let output = "";
83
149
  if (result.stdout)
@@ -44,6 +44,15 @@ export interface PipiclawToolsConfig {
44
44
  tasks: {
45
45
  enabled: boolean;
46
46
  };
47
+ grep: {
48
+ enabled: boolean;
49
+ };
50
+ jobs: {
51
+ enabled: boolean;
52
+ };
53
+ bashInterceptor: {
54
+ enabled: boolean;
55
+ };
47
56
  rtk: {
48
57
  enabled: boolean;
49
58
  };
@@ -44,6 +44,15 @@ export const DEFAULT_TOOLS_CONFIG = {
44
44
  tasks: {
45
45
  enabled: true,
46
46
  },
47
+ grep: {
48
+ enabled: true,
49
+ },
50
+ jobs: {
51
+ enabled: true,
52
+ },
53
+ bashInterceptor: {
54
+ enabled: true,
55
+ },
47
56
  rtk: {
48
57
  enabled: false,
49
58
  },
@@ -97,6 +106,9 @@ function mergeToolsConfig(source, configPath, diagnostics) {
97
106
  const manage = isRecord(skills.manage) ? skills.manage : {};
98
107
  const events = isRecord(tools.events) ? tools.events : {};
99
108
  const tasks = isRecord(tools.tasks) ? tools.tasks : {};
109
+ const grep = isRecord(tools.grep) ? tools.grep : {};
110
+ const jobs = isRecord(tools.jobs) ? tools.jobs : {};
111
+ const bashInterceptor = isRecord(tools.bashInterceptor) ? tools.bashInterceptor : {};
100
112
  const rtk = isRecord(tools.rtk) ? tools.rtk : {};
101
113
  const search = isRecord(web.search) ? web.search : {};
102
114
  const fetch = isRecord(web.fetch) ? web.fetch : {};
@@ -187,6 +199,17 @@ function mergeToolsConfig(source, configPath, diagnostics) {
187
199
  tasks: {
188
200
  enabled: typeof tasks.enabled === "boolean" ? tasks.enabled : DEFAULT_TOOLS_CONFIG.tools.tasks.enabled,
189
201
  },
202
+ grep: {
203
+ enabled: typeof grep.enabled === "boolean" ? grep.enabled : DEFAULT_TOOLS_CONFIG.tools.grep.enabled,
204
+ },
205
+ jobs: {
206
+ enabled: typeof jobs.enabled === "boolean" ? jobs.enabled : DEFAULT_TOOLS_CONFIG.tools.jobs.enabled,
207
+ },
208
+ bashInterceptor: {
209
+ enabled: typeof bashInterceptor.enabled === "boolean"
210
+ ? bashInterceptor.enabled
211
+ : DEFAULT_TOOLS_CONFIG.tools.bashInterceptor.enabled,
212
+ },
190
213
  rtk: {
191
214
  enabled: typeof rtk.enabled === "boolean" ? rtk.enabled : DEFAULT_TOOLS_CONFIG.tools.rtk.enabled,
192
215
  },
Binary file
@@ -0,0 +1,19 @@
1
+ import type { AgentTool } from "@earendil-works/pi-agent-core";
2
+ import { Type } from "typebox";
3
+ import type { Executor } from "../sandbox.js";
4
+ import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
5
+ declare const grepSchema: Type.TObject<{
6
+ label: Type.TString;
7
+ pattern: Type.TString;
8
+ path: Type.TOptional<Type.TString>;
9
+ glob: Type.TOptional<Type.TString>;
10
+ caseSensitive: Type.TOptional<Type.TBoolean>;
11
+ skip: Type.TOptional<Type.TInteger>;
12
+ }>;
13
+ export interface GrepToolOptions {
14
+ securityConfig?: SecurityConfig;
15
+ securityContext?: SecurityRuntimeContext;
16
+ channelId?: string;
17
+ }
18
+ export declare function createGrepTool(executor: Executor, options?: GrepToolOptions): AgentTool<typeof grepSchema>;
19
+ export {};