@oyasmi/pipiclaw 0.7.4 → 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.
Files changed (59) hide show
  1. package/README.md +5 -1
  2. package/dist/agent/channel-runner.js +14 -0
  3. package/dist/agent/commands.d.ts +1 -1
  4. package/dist/agent/commands.js +6 -0
  5. package/dist/agent/job-manager.d.ts +79 -0
  6. package/dist/agent/job-manager.js +241 -0
  7. package/dist/agent/prompt-builder.js +13 -4
  8. package/dist/memory/review-log.d.ts +1 -1
  9. package/dist/memory/task-digest.d.ts +21 -0
  10. package/dist/memory/task-digest.js +66 -0
  11. package/dist/runtime/bootstrap.js +13 -1
  12. package/dist/runtime/dingtalk.d.ts +1 -0
  13. package/dist/runtime/dingtalk.js +6 -2
  14. package/dist/runtime/event-commands.d.ts +5 -0
  15. package/dist/runtime/event-commands.js +2 -2
  16. package/dist/runtime/task-commands.d.ts +6 -0
  17. package/dist/runtime/task-commands.js +133 -0
  18. package/dist/settings.d.ts +7 -0
  19. package/dist/settings.js +13 -0
  20. package/dist/shared/task-ledger.d.ts +53 -0
  21. package/dist/shared/task-ledger.js +149 -0
  22. package/dist/tools/bash.d.ts +12 -0
  23. package/dist/tools/bash.js +67 -1
  24. package/dist/tools/config.d.ts +15 -0
  25. package/dist/tools/config.js +37 -0
  26. package/dist/tools/edit.js +0 -0
  27. package/dist/tools/event-manage.d.ts +35 -0
  28. package/dist/tools/event-manage.js +238 -0
  29. package/dist/tools/grep.d.ts +19 -0
  30. package/dist/tools/grep.js +262 -0
  31. package/dist/tools/index.js +5 -0
  32. package/dist/tools/job.d.ts +13 -0
  33. package/dist/tools/job.js +92 -0
  34. package/dist/tools/memory-manage.d.ts +24 -0
  35. package/dist/tools/memory-manage.js +150 -0
  36. package/dist/tools/read.js +103 -16
  37. package/dist/tools/registry.d.ts +7 -1
  38. package/dist/tools/registry.js +54 -17
  39. package/dist/tools/session-search.js +4 -1
  40. package/dist/tools/skill-manage.d.ts +12 -5
  41. package/dist/tools/skill-manage.js +113 -15
  42. package/dist/tools/task-manage.d.ts +43 -0
  43. package/dist/tools/task-manage.js +226 -0
  44. package/dist/tools/web-cache.d.ts +11 -0
  45. package/dist/tools/web-cache.js +62 -0
  46. package/dist/tools/web-fetch.d.ts +3 -0
  47. package/dist/tools/web-fetch.js +70 -5
  48. package/dist/tui/app.js +2 -0
  49. package/dist/tui/commands.d.ts +1 -0
  50. package/dist/tui/commands.js +3 -0
  51. package/dist/tui/turn-controller.d.ts +1 -0
  52. package/dist/tui/turn-controller.js +1 -0
  53. package/package.json +1 -1
  54. package/dist/tools/memory-save.d.ts +0 -16
  55. package/dist/tools/memory-save.js +0 -42
  56. package/dist/tools/skill-list.d.ts +0 -18
  57. package/dist/tools/skill-list.js +0 -86
  58. package/dist/tools/skill-view.d.ts +0 -13
  59. package/dist/tools/skill-view.js +0 -44
@@ -0,0 +1,133 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readdir, readFile } from "node:fs/promises";
3
+ import { join, resolve, sep } from "node:path";
4
+ import { extractTaskTitle, normalizeTaskId, readActiveTasks } from "../shared/task-ledger.js";
5
+ function usage() {
6
+ return `# Tasks
7
+
8
+ Usage:
9
+
10
+ - \`/tasks\` — list active tasks in this channel
11
+ - \`/tasks show <id>\` — show a single task file (active or archived)
12
+ - \`/tasks archive\` — list archived (closed) tasks`;
13
+ }
14
+ function parseTasksCommand(args) {
15
+ const parts = args.trim().split(/\s+/).filter(Boolean);
16
+ const action = parts[0];
17
+ if (!action || action === "list") {
18
+ if (parts.length > 1)
19
+ throw new Error("Usage: /tasks list");
20
+ return { action: "list" };
21
+ }
22
+ if (action === "show") {
23
+ const id = parts[1];
24
+ if (!id || parts.length > 2)
25
+ throw new Error("Usage: /tasks show <id>");
26
+ return { action: "show", id };
27
+ }
28
+ if (action === "archive") {
29
+ if (parts.length > 1)
30
+ throw new Error("Usage: /tasks archive");
31
+ return { action: "archive" };
32
+ }
33
+ throw new Error(`Unknown /tasks action: ${action}`);
34
+ }
35
+ function tasksDir(channelDir) {
36
+ return join(channelDir, "tasks");
37
+ }
38
+ /** Resolve `<tasksDir>/[archive/]<id>.md`, rejecting any path that escapes the tasks dir. */
39
+ function resolveTaskPath(dir, id, subdir) {
40
+ const base = resolve(dir);
41
+ const target = resolve(base, subdir ?? "", `${id}.md`);
42
+ const expected = subdir ? join(base, subdir, `${id}.md`) : join(base, `${id}.md`);
43
+ if (target !== expected || !target.startsWith(`${base}${sep}`)) {
44
+ throw new Error(`Invalid task id: ${id}`);
45
+ }
46
+ return target;
47
+ }
48
+ function relativeWake(wakeMs, now) {
49
+ if (wakeMs === undefined)
50
+ return "—";
51
+ const iso = new Date(wakeMs).toISOString();
52
+ const diffMs = wakeMs - now;
53
+ if (diffMs <= 0)
54
+ return `${iso} (due)`;
55
+ const minutes = Math.round(diffMs / 60000);
56
+ const rel = minutes < 60 ? `${minutes}m` : minutes < 1440 ? `${Math.round(minutes / 60)}h` : `${Math.round(minutes / 1440)}d`;
57
+ return `${iso} (${rel})`;
58
+ }
59
+ async function listTasks(channelDir) {
60
+ const dir = tasksDir(channelDir);
61
+ const now = Date.now();
62
+ const entries = await readActiveTasks(dir, now);
63
+ if (entries.length === 0) {
64
+ return "# Tasks\n\nNo active tasks.";
65
+ }
66
+ const blocks = entries.map((entry) => {
67
+ const status = entry.frontmatter.readable ? (entry.frontmatter.status ?? "open") : "⚠ unreadable frontmatter";
68
+ const detail = [` status: ${status}`, `wake: ${relativeWake(entry.wakeMs, now)}`];
69
+ if (entry.frontmatter.recurrence)
70
+ detail.push(`recurrence: ${entry.frontmatter.recurrence}`);
71
+ return `- ${entry.id} — ${entry.title}\n${detail.join(" ")}`;
72
+ });
73
+ return `# Tasks: ${entries.length} active\n\n${blocks.join("\n")}`;
74
+ }
75
+ async function showTask(channelDir, id) {
76
+ const dir = tasksDir(channelDir);
77
+ const taskId = normalizeTaskId(id);
78
+ const activePath = resolveTaskPath(dir, taskId);
79
+ const archivePath = resolveTaskPath(dir, taskId, "archive");
80
+ const path = existsSync(activePath) ? activePath : existsSync(archivePath) ? archivePath : undefined;
81
+ if (!path) {
82
+ return `Task not found: ${taskId}`;
83
+ }
84
+ const location = path === archivePath ? " (archived)" : "";
85
+ const content = await readFile(path, "utf-8");
86
+ return `# Task: ${taskId}${location}\n\n\`\`\`markdown\n${content}\n\`\`\``;
87
+ }
88
+ async function listArchive(channelDir) {
89
+ const dir = join(tasksDir(channelDir), "archive");
90
+ if (!existsSync(dir)) {
91
+ return "# Archived Tasks\n\nNo archived tasks.";
92
+ }
93
+ const filenames = (await readdir(dir)).filter((filename) => filename.endsWith(".md")).sort();
94
+ if (filenames.length === 0) {
95
+ return "# Archived Tasks\n\nNo archived tasks.";
96
+ }
97
+ const blocks = [];
98
+ for (const filename of filenames) {
99
+ const id = filename.slice(0, -".md".length);
100
+ try {
101
+ const content = await readFile(join(dir, filename), "utf-8");
102
+ blocks.push(`- ${id} — ${extractTaskTitle(content, id)}`);
103
+ }
104
+ catch {
105
+ blocks.push(`- ${id}`);
106
+ }
107
+ }
108
+ return `# Archived Tasks: ${blocks.length}\n\n${blocks.join("\n")}`;
109
+ }
110
+ export async function handleTasksCommand(options) {
111
+ let command;
112
+ try {
113
+ command = parseTasksCommand(options.args);
114
+ }
115
+ catch (error) {
116
+ const message = error instanceof Error ? error.message : String(error);
117
+ return `${message}\n\n${usage()}`;
118
+ }
119
+ try {
120
+ switch (command.action) {
121
+ case "list":
122
+ return await listTasks(options.channelDir);
123
+ case "show":
124
+ return await showTask(options.channelDir, command.id);
125
+ case "archive":
126
+ return await listArchive(options.channelDir);
127
+ }
128
+ }
129
+ catch (error) {
130
+ const message = error instanceof Error ? error.message : String(error);
131
+ return `Could not ${command.action} tasks: ${message}`;
132
+ }
133
+ }
@@ -60,6 +60,11 @@ export interface PipiclawMemoryRecallSettings {
60
60
  maxChars: number;
61
61
  rerankWithModel: boolean | "auto";
62
62
  }
63
+ export interface PipiclawTaskDigestSettings {
64
+ enabled: boolean;
65
+ maxTasks: number;
66
+ maxChars: number;
67
+ }
63
68
  export interface PipiclawSessionMemorySettings {
64
69
  enabled: boolean;
65
70
  minTurnsBetweenUpdate: number;
@@ -118,6 +123,7 @@ export interface PipiclawSettings {
118
123
  compaction?: Partial<PipiclawCompactionSettings>;
119
124
  retry?: Partial<PipiclawRetrySettings>;
120
125
  memoryRecall?: Partial<PipiclawMemoryRecallSettings>;
126
+ taskDigest?: Partial<PipiclawTaskDigestSettings>;
121
127
  sessionMemory?: Partial<PipiclawSessionMemorySettings>;
122
128
  memoryGrowth?: Partial<PipiclawMemoryGrowthSettings>;
123
129
  memoryMaintenance?: Partial<PipiclawMemoryMaintenanceSettings>;
@@ -156,6 +162,7 @@ export declare class PipiclawSettingsManager {
156
162
  setCompactionEnabled(enabled: boolean): void;
157
163
  getRetrySettings(): PipiclawRetrySettings;
158
164
  getMemoryRecallSettings(): PipiclawMemoryRecallSettings;
165
+ getTaskDigestSettings(): PipiclawTaskDigestSettings;
159
166
  getSessionMemorySettings(): PipiclawSessionMemorySettings;
160
167
  getMemoryGrowthSettings(): PipiclawMemoryGrowthSettings;
161
168
  getMemoryMaintenanceSettings(): PipiclawMemoryMaintenanceSettings;
package/dist/settings.js CHANGED
@@ -29,6 +29,13 @@ const DEFAULT_MEMORY_RECALL = {
29
29
  maxChars: 5000,
30
30
  rerankWithModel: "auto",
31
31
  };
32
+ // Cheap and high-value: reading a handful of task frontmatters and always surfacing
33
+ // the in-flight agenda is worth more than the tokens it costs, so it defaults on.
34
+ const DEFAULT_TASK_DIGEST = {
35
+ enabled: true,
36
+ maxTasks: 8,
37
+ maxChars: 1000,
38
+ };
32
39
  const DEFAULT_SESSION_MEMORY = {
33
40
  enabled: true,
34
41
  minTurnsBetweenUpdate: 2,
@@ -167,6 +174,12 @@ export class PipiclawSettingsManager {
167
174
  ...this.settings.memoryRecall,
168
175
  };
169
176
  }
177
+ getTaskDigestSettings() {
178
+ return {
179
+ ...DEFAULT_TASK_DIGEST,
180
+ ...this.settings.taskDigest,
181
+ };
182
+ }
170
183
  getSessionMemorySettings() {
171
184
  return {
172
185
  ...DEFAULT_SESSION_MEMORY,
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Shared reader for the task ledger (`workspace/<channelId>/tasks/*.md`).
3
+ *
4
+ * This is the in-repo half of the frontmatter contract documented in `docs/tasks.md`
5
+ * ("Frontmatter 契约(单一事实源)"). The heartbeat sensor `tasks-pending.mjs` is the
6
+ * out-of-repo half (a dependency-free script in workspace/skills). Both MUST agree on
7
+ * `actionable`, so the parsing here is a deliberate, literal mirror of that script:
8
+ * three flat `key: value` fields, done-vs-not-done, wake gating, fail-open on unreadable
9
+ * frontmatter. `/tasks`, the task digest, and `task_manage list` all read through here.
10
+ */
11
+ export interface TaskFrontmatter {
12
+ /** false => frontmatter could not be read (fail-open: the task is treated as actionable). */
13
+ readable: boolean;
14
+ status?: string;
15
+ wake?: string;
16
+ recurrence?: string;
17
+ }
18
+ export interface TaskLedgerEntry {
19
+ /** Filename without `.md`; the task id. */
20
+ id: string;
21
+ /** First `# ` heading in the body, or the id when none. */
22
+ title: string;
23
+ frontmatter: TaskFrontmatter;
24
+ /** status ≠ done AND (no valid wake OR wake ≤ now). Matches the sensor exactly. */
25
+ actionable: boolean;
26
+ /** Milliseconds since epoch parsed from `wake`, or undefined when unset/unparseable. */
27
+ wakeMs?: number;
28
+ /** First bullet/line under a "当前周期"/"current cycle" heading, if any (digest only). */
29
+ latestNote?: string;
30
+ }
31
+ /** Validate/normalize a task id (filename without `.md`), rejecting path traversal. */
32
+ export declare function normalizeTaskId(id: string): string;
33
+ /** The document body after the leading frontmatter block, or the whole content when there is none. */
34
+ export declare function taskBody(content: string): string;
35
+ /** Parse the leading `---` frontmatter block into the three known fields. */
36
+ export declare function parseTaskFrontmatter(content: string): TaskFrontmatter;
37
+ /**
38
+ * The single shared judgement: is there work to do on this task right now?
39
+ * Unreadable frontmatter is fail-open (actionable) so a corrupt ledger surfaces
40
+ * rather than being silently skipped — identical to the sensor's behaviour.
41
+ */
42
+ export declare function isTaskActionable(frontmatter: TaskFrontmatter, now: number): boolean;
43
+ /** First `# ` heading after the frontmatter block, or the id when there is none. */
44
+ export declare function extractTaskTitle(content: string, fallbackId: string): string;
45
+ /** Actionable first; then earliest wake first (unset wake sorts as "ready now"); then id. */
46
+ export declare function compareTaskEntries(a: TaskLedgerEntry, b: TaskLedgerEntry): number;
47
+ /**
48
+ * Read every `.md` file in `tasks/` (root only — the `archive/` subdirectory is not
49
+ * scanned), returning entries sorted actionable-first. A file that cannot be read is
50
+ * still returned (fail-open: `readable: false`, `actionable: true`) so problems surface.
51
+ * Missing directory → empty list.
52
+ */
53
+ export declare function readActiveTasks(tasksDir: string, now?: number): Promise<TaskLedgerEntry[]>;
@@ -0,0 +1,149 @@
1
+ import { readdir, readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ const FRONTMATTER_FIELDS = ["status", "wake", "recurrence"];
4
+ const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
5
+ /** Validate/normalize a task id (filename without `.md`), rejecting path traversal. */
6
+ export function normalizeTaskId(id) {
7
+ const trimmed = id.trim();
8
+ const normalized = trimmed.endsWith(".md") ? trimmed.slice(0, -".md".length) : trimmed;
9
+ if (!normalized || normalized === "." || normalized === ".." || !TASK_ID_PATTERN.test(normalized)) {
10
+ throw new Error(`Invalid task id: ${id}`);
11
+ }
12
+ return normalized;
13
+ }
14
+ /** The document body after the leading frontmatter block, or the whole content when there is none. */
15
+ export function taskBody(content) {
16
+ if (!content.startsWith("---"))
17
+ return content;
18
+ const end = content.indexOf("\n---", 3);
19
+ if (end === -1)
20
+ return content;
21
+ const after = content.indexOf("\n", end + 1);
22
+ return after === -1 ? "" : content.slice(after + 1);
23
+ }
24
+ /** Parse the leading `---` frontmatter block into the three known fields. */
25
+ export function parseTaskFrontmatter(content) {
26
+ if (!content.startsWith("---"))
27
+ return { readable: false };
28
+ const end = content.indexOf("\n---", 3);
29
+ if (end === -1)
30
+ return { readable: false };
31
+ const block = content.slice(3, end);
32
+ const frontmatter = { readable: true };
33
+ for (const line of block.split("\n")) {
34
+ const idx = line.indexOf(":");
35
+ if (idx === -1)
36
+ continue;
37
+ const key = line.slice(0, idx).trim();
38
+ if (FRONTMATTER_FIELDS.includes(key)) {
39
+ const value = line.slice(idx + 1).trim();
40
+ frontmatter[key] = value || undefined;
41
+ }
42
+ }
43
+ return frontmatter;
44
+ }
45
+ /**
46
+ * The single shared judgement: is there work to do on this task right now?
47
+ * Unreadable frontmatter is fail-open (actionable) so a corrupt ledger surfaces
48
+ * rather than being silently skipped — identical to the sensor's behaviour.
49
+ */
50
+ export function isTaskActionable(frontmatter, now) {
51
+ if (!frontmatter.readable)
52
+ return true;
53
+ if (frontmatter.status === "done")
54
+ return false;
55
+ if (frontmatter.wake) {
56
+ const wakeAt = new Date(frontmatter.wake).getTime();
57
+ if (Number.isFinite(wakeAt) && wakeAt > now)
58
+ return false;
59
+ }
60
+ return true;
61
+ }
62
+ /** First `# ` heading after the frontmatter block, or the id when there is none. */
63
+ export function extractTaskTitle(content, fallbackId) {
64
+ for (const line of taskBody(content).split("\n")) {
65
+ const match = /^#\s+(.+?)\s*$/.exec(line);
66
+ if (match)
67
+ return match[1];
68
+ }
69
+ return fallbackId;
70
+ }
71
+ /** First non-empty bullet/line under a "当前周期"/"current cycle" heading. */
72
+ function extractLatestNote(content) {
73
+ const lines = content.split("\n");
74
+ let inSection = false;
75
+ for (const line of lines) {
76
+ if (/^#{1,6}\s/.test(line)) {
77
+ inSection = /当前周期|current cycle/i.test(line);
78
+ continue;
79
+ }
80
+ if (!inSection)
81
+ continue;
82
+ const trimmed = line.replace(/^\s*[-*]\s+/, "").trim();
83
+ if (trimmed)
84
+ return trimmed;
85
+ }
86
+ return undefined;
87
+ }
88
+ function wakeMsOf(frontmatter) {
89
+ if (!frontmatter.wake)
90
+ return undefined;
91
+ const at = new Date(frontmatter.wake).getTime();
92
+ return Number.isFinite(at) ? at : undefined;
93
+ }
94
+ /** Actionable first; then earliest wake first (unset wake sorts as "ready now"); then id. */
95
+ export function compareTaskEntries(a, b) {
96
+ if (a.actionable !== b.actionable)
97
+ return a.actionable ? -1 : 1;
98
+ const aw = a.wakeMs ?? Number.NEGATIVE_INFINITY;
99
+ const bw = b.wakeMs ?? Number.NEGATIVE_INFINITY;
100
+ if (aw !== bw)
101
+ return aw - bw;
102
+ return a.id.localeCompare(b.id);
103
+ }
104
+ function toEntry(id, content, now) {
105
+ const frontmatter = parseTaskFrontmatter(content);
106
+ return {
107
+ id,
108
+ title: extractTaskTitle(content, id),
109
+ frontmatter,
110
+ actionable: isTaskActionable(frontmatter, now),
111
+ wakeMs: wakeMsOf(frontmatter),
112
+ latestNote: extractLatestNote(content),
113
+ };
114
+ }
115
+ /**
116
+ * Read every `.md` file in `tasks/` (root only — the `archive/` subdirectory is not
117
+ * scanned), returning entries sorted actionable-first. A file that cannot be read is
118
+ * still returned (fail-open: `readable: false`, `actionable: true`) so problems surface.
119
+ * Missing directory → empty list.
120
+ */
121
+ export async function readActiveTasks(tasksDir, now = Date.now()) {
122
+ let dirents;
123
+ try {
124
+ dirents = await readdir(tasksDir, { withFileTypes: true });
125
+ }
126
+ catch {
127
+ return [];
128
+ }
129
+ const entries = [];
130
+ for (const dirent of dirents) {
131
+ if (!dirent.isFile() || !dirent.name.endsWith(".md"))
132
+ continue;
133
+ const id = dirent.name.slice(0, -".md".length);
134
+ try {
135
+ const content = await readFile(join(tasksDir, dirent.name), "utf-8");
136
+ entries.push(toEntry(id, content, now));
137
+ }
138
+ catch {
139
+ entries.push({
140
+ id,
141
+ title: id,
142
+ frontmatter: { readable: false },
143
+ actionable: true,
144
+ });
145
+ }
146
+ }
147
+ entries.sort(compareTaskEntries);
148
+ return entries;
149
+ }
@@ -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)
@@ -38,6 +38,21 @@ export interface PipiclawToolsConfig {
38
38
  enabled: boolean;
39
39
  };
40
40
  };
41
+ events: {
42
+ enabled: boolean;
43
+ };
44
+ tasks: {
45
+ enabled: boolean;
46
+ };
47
+ grep: {
48
+ enabled: boolean;
49
+ };
50
+ jobs: {
51
+ enabled: boolean;
52
+ };
53
+ bashInterceptor: {
54
+ enabled: boolean;
55
+ };
41
56
  rtk: {
42
57
  enabled: boolean;
43
58
  };
@@ -38,6 +38,21 @@ export const DEFAULT_TOOLS_CONFIG = {
38
38
  enabled: true,
39
39
  },
40
40
  },
41
+ events: {
42
+ enabled: true,
43
+ },
44
+ tasks: {
45
+ enabled: true,
46
+ },
47
+ grep: {
48
+ enabled: true,
49
+ },
50
+ jobs: {
51
+ enabled: true,
52
+ },
53
+ bashInterceptor: {
54
+ enabled: true,
55
+ },
41
56
  rtk: {
42
57
  enabled: false,
43
58
  },
@@ -89,6 +104,11 @@ function mergeToolsConfig(source, configPath, diagnostics) {
89
104
  const memorySave = isRecord(memory.save) ? memory.save : {};
90
105
  const skills = isRecord(tools.skills) ? tools.skills : {};
91
106
  const manage = isRecord(skills.manage) ? skills.manage : {};
107
+ const events = isRecord(tools.events) ? tools.events : {};
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 : {};
92
112
  const rtk = isRecord(tools.rtk) ? tools.rtk : {};
93
113
  const search = isRecord(web.search) ? web.search : {};
94
114
  const fetch = isRecord(web.fetch) ? web.fetch : {};
@@ -173,6 +193,23 @@ function mergeToolsConfig(source, configPath, diagnostics) {
173
193
  : DEFAULT_TOOLS_CONFIG.tools.skills.manage.enabled,
174
194
  },
175
195
  },
196
+ events: {
197
+ enabled: typeof events.enabled === "boolean" ? events.enabled : DEFAULT_TOOLS_CONFIG.tools.events.enabled,
198
+ },
199
+ tasks: {
200
+ enabled: typeof tasks.enabled === "boolean" ? tasks.enabled : DEFAULT_TOOLS_CONFIG.tools.tasks.enabled,
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
+ },
176
213
  rtk: {
177
214
  enabled: typeof rtk.enabled === "boolean" ? rtk.enabled : DEFAULT_TOOLS_CONFIG.tools.rtk.enabled,
178
215
  },
Binary file
@@ -0,0 +1,35 @@
1
+ import type { AgentTool } from "@earendil-works/pi-agent-core";
2
+ import { Type } from "typebox";
3
+ import { type ScheduledEvent } from "../runtime/events.js";
4
+ import type { SecurityConfig } from "../security/types.js";
5
+ declare const eventManageSchema: Type.TObject<{
6
+ label: Type.TString;
7
+ action: Type.TUnion<[Type.TLiteral<"create">, Type.TLiteral<"update">, Type.TLiteral<"delete">]>;
8
+ name: Type.TString;
9
+ definition: Type.TOptional<Type.TString>;
10
+ }>;
11
+ export type EventManageAction = "create" | "update" | "delete";
12
+ export interface EventManageResult {
13
+ action: EventManageAction;
14
+ name: string;
15
+ path: string;
16
+ eventType?: ScheduledEvent["type"];
17
+ channelId?: string;
18
+ bytesWritten?: number;
19
+ deleted?: boolean;
20
+ notice: string;
21
+ }
22
+ export interface EventManageRequest {
23
+ action: EventManageAction;
24
+ name: string;
25
+ definition?: string;
26
+ }
27
+ export interface EventManageToolOptions {
28
+ workspaceDir: string;
29
+ workspacePath: string;
30
+ channelId: string;
31
+ commandGuardConfig: SecurityConfig["commandGuard"];
32
+ }
33
+ export declare function manageEvent(options: EventManageToolOptions, request: EventManageRequest): Promise<EventManageResult>;
34
+ export declare function createEventManageTool(options: EventManageToolOptions): AgentTool<typeof eventManageSchema>;
35
+ export {};