@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.
- package/README.md +5 -1
- package/dist/agent/channel-runner.js +14 -0
- package/dist/agent/commands.d.ts +1 -1
- package/dist/agent/commands.js +6 -0
- package/dist/agent/job-manager.d.ts +79 -0
- package/dist/agent/job-manager.js +241 -0
- package/dist/agent/prompt-builder.js +13 -4
- package/dist/memory/review-log.d.ts +1 -1
- package/dist/memory/task-digest.d.ts +21 -0
- package/dist/memory/task-digest.js +66 -0
- package/dist/runtime/bootstrap.js +13 -1
- package/dist/runtime/dingtalk.d.ts +1 -0
- package/dist/runtime/dingtalk.js +6 -2
- package/dist/runtime/event-commands.d.ts +5 -0
- package/dist/runtime/event-commands.js +2 -2
- package/dist/runtime/task-commands.d.ts +6 -0
- package/dist/runtime/task-commands.js +133 -0
- package/dist/settings.d.ts +7 -0
- package/dist/settings.js +13 -0
- package/dist/shared/task-ledger.d.ts +53 -0
- package/dist/shared/task-ledger.js +149 -0
- package/dist/tools/bash.d.ts +12 -0
- package/dist/tools/bash.js +67 -1
- package/dist/tools/config.d.ts +15 -0
- package/dist/tools/config.js +37 -0
- package/dist/tools/edit.js +0 -0
- package/dist/tools/event-manage.d.ts +35 -0
- package/dist/tools/event-manage.js +238 -0
- package/dist/tools/grep.d.ts +19 -0
- package/dist/tools/grep.js +262 -0
- package/dist/tools/index.js +5 -0
- package/dist/tools/job.d.ts +13 -0
- package/dist/tools/job.js +92 -0
- package/dist/tools/memory-manage.d.ts +24 -0
- package/dist/tools/memory-manage.js +150 -0
- package/dist/tools/read.js +103 -16
- package/dist/tools/registry.d.ts +7 -1
- package/dist/tools/registry.js +54 -17
- package/dist/tools/session-search.js +4 -1
- package/dist/tools/skill-manage.d.ts +12 -5
- package/dist/tools/skill-manage.js +113 -15
- package/dist/tools/task-manage.d.ts +43 -0
- package/dist/tools/task-manage.js +226 -0
- package/dist/tools/web-cache.d.ts +11 -0
- package/dist/tools/web-cache.js +62 -0
- package/dist/tools/web-fetch.d.ts +3 -0
- package/dist/tools/web-fetch.js +70 -5
- package/dist/tui/app.js +2 -0
- package/dist/tui/commands.d.ts +1 -0
- package/dist/tui/commands.js +3 -0
- package/dist/tui/turn-controller.d.ts +1 -0
- package/dist/tui/turn-controller.js +1 -0
- package/package.json +1 -1
- package/dist/tools/memory-save.d.ts +0 -16
- package/dist/tools/memory-save.js +0 -42
- package/dist/tools/skill-list.d.ts +0 -18
- package/dist/tools/skill-list.js +0 -86
- package/dist/tools/skill-view.d.ts +0 -13
- package/dist/tools/skill-view.js +0 -44
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { readdir, readFile, unlink } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { Cron } from "croner";
|
|
5
|
+
import { Type } from "typebox";
|
|
6
|
+
import { resolveEventPath } from "../runtime/event-commands.js";
|
|
7
|
+
import { parseScheduledEventContent } from "../runtime/events.js";
|
|
8
|
+
import { guardCommand } from "../security/command-guard.js";
|
|
9
|
+
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
10
|
+
import { isRecord } from "../shared/type-guards.js";
|
|
11
|
+
/** one-shot events must be scheduled at least this far out; anything sooner is effectively self-triggering. */
|
|
12
|
+
const MIN_ONE_SHOT_LEAD_MS = 2 * 60 * 1000;
|
|
13
|
+
/** periodic events without a preAction gate may fire no more often than this. */
|
|
14
|
+
const MIN_PERIODIC_INTERVAL_MS = 30 * 60 * 1000;
|
|
15
|
+
/**
|
|
16
|
+
* periodic events WITH a preAction gate may fire this often: the sensor is the token guard
|
|
17
|
+
* (it exits non-zero and stays silent when there is nothing to do), so a tighter cadence is
|
|
18
|
+
* safe and is exactly the design-endorsed posture for completion-driven checks (e.g. polling
|
|
19
|
+
* an agentmux instance until it goes idle). A hard sub-floor still applies so a bogus
|
|
20
|
+
* always-pass preAction cannot drive an arbitrarily hot loop.
|
|
21
|
+
*/
|
|
22
|
+
const MIN_PERIODIC_INTERVAL_WITH_PREACTION_MS = 5 * 60 * 1000;
|
|
23
|
+
/** sanity cap on total event files to keep the directory (and the scheduler) from being flooded. */
|
|
24
|
+
const MAX_EVENT_FILES = 50;
|
|
25
|
+
const eventManageSchema = Type.Object({
|
|
26
|
+
label: Type.String({ description: "Brief description of the scheduling change (shown to the user)" }),
|
|
27
|
+
action: Type.Union([Type.Literal("create"), Type.Literal("update"), Type.Literal("delete")], {
|
|
28
|
+
description: 'The event management action to perform: "create", "update", or "delete".',
|
|
29
|
+
}),
|
|
30
|
+
name: Type.String({
|
|
31
|
+
description: "Event name (filename without .json). For task-owned events use `task.<channelId>.<taskId>.<use>`, e.g. `task.dm_123.weekly-report.checkin`.",
|
|
32
|
+
}),
|
|
33
|
+
definition: Type.Optional(Type.String({
|
|
34
|
+
description: "Full event JSON (required for create/update). one-shot / periodic only; immediate is rejected. channelId defaults to the current channel.",
|
|
35
|
+
})),
|
|
36
|
+
});
|
|
37
|
+
function parseAction(action) {
|
|
38
|
+
if (action === "create" || action === "update" || action === "delete") {
|
|
39
|
+
return action;
|
|
40
|
+
}
|
|
41
|
+
throw new Error('Unsupported event action. Use "create", "update", or "delete".');
|
|
42
|
+
}
|
|
43
|
+
function toWorkspacePath(options, hostPath) {
|
|
44
|
+
if (hostPath.startsWith(options.workspaceDir)) {
|
|
45
|
+
return `${options.workspacePath}${hostPath.slice(options.workspaceDir.length)}`;
|
|
46
|
+
}
|
|
47
|
+
return hostPath;
|
|
48
|
+
}
|
|
49
|
+
function validateTimezone(timezone) {
|
|
50
|
+
try {
|
|
51
|
+
new Intl.DateTimeFormat(undefined, { timeZone: timezone });
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
throw new Error(`Invalid timezone: ${timezone}`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function validateOneShot(event) {
|
|
58
|
+
const atTime = new Date(event.at).getTime();
|
|
59
|
+
if (!Number.isFinite(atTime)) {
|
|
60
|
+
throw new Error(`one-shot 'at' is not a valid date: ${event.at}`);
|
|
61
|
+
}
|
|
62
|
+
if (atTime < Date.now() + MIN_ONE_SHOT_LEAD_MS) {
|
|
63
|
+
throw new Error("one-shot 'at' must be at least 2 minutes in the future (self-triggering guard).");
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function validatePeriodic(event) {
|
|
67
|
+
validateTimezone(event.timezone);
|
|
68
|
+
let runs;
|
|
69
|
+
try {
|
|
70
|
+
const cron = new Cron(event.schedule, { timezone: event.timezone });
|
|
71
|
+
runs = cron.nextRuns(3);
|
|
72
|
+
cron.stop();
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
76
|
+
throw new Error(`Invalid cron schedule "${event.schedule}": ${message}`);
|
|
77
|
+
}
|
|
78
|
+
// A preAction gate makes a tighter cadence safe (the sensor keeps most fires silent);
|
|
79
|
+
// without one, hold the 30-minute floor so a bare high-frequency cron can't burn tokens.
|
|
80
|
+
const floorMs = event.preAction ? MIN_PERIODIC_INTERVAL_WITH_PREACTION_MS : MIN_PERIODIC_INTERVAL_MS;
|
|
81
|
+
const floorMinutes = Math.round(floorMs / 60000);
|
|
82
|
+
// Fewer than two upcoming runs means no meaningful cadence to rate-limit (e.g. a one-off cron); allow it.
|
|
83
|
+
for (let i = 1; i < runs.length; i++) {
|
|
84
|
+
if (runs[i].getTime() - runs[i - 1].getTime() < floorMs) {
|
|
85
|
+
throw new Error(`periodic events must fire no more often than every ${floorMinutes} minutes` +
|
|
86
|
+
`${event.preAction ? " (even with a preAction gate)" : "; for tighter checks add a preAction gate (min 5 minutes) instead of a high-frequency cron"}.`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function validatePreAction(event, commandGuardConfig) {
|
|
91
|
+
if (!event.preAction)
|
|
92
|
+
return;
|
|
93
|
+
const result = guardCommand(event.preAction.command, commandGuardConfig);
|
|
94
|
+
if (!result.allowed) {
|
|
95
|
+
throw new Error(`preAction command blocked by guard: ${result.reason ?? "not allowed"}`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Validate an agent-supplied event definition and return the normalized, typed event.
|
|
100
|
+
* Rejects immediate events, near-term one-shots, high-frequency periodics, guard-blocked
|
|
101
|
+
* preActions, and cross-channel channelIds. The returned event is what gets persisted, so
|
|
102
|
+
* the file on disk is exactly what was validated.
|
|
103
|
+
*/
|
|
104
|
+
function validateDefinition(rawDefinition, name, options) {
|
|
105
|
+
let data;
|
|
106
|
+
try {
|
|
107
|
+
data = JSON.parse(rawDefinition);
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
111
|
+
throw new Error(`definition is not valid JSON: ${message}`);
|
|
112
|
+
}
|
|
113
|
+
if (!isRecord(data)) {
|
|
114
|
+
throw new Error("definition must be a JSON object.");
|
|
115
|
+
}
|
|
116
|
+
const providedChannelId = data.channelId;
|
|
117
|
+
if (providedChannelId === undefined || providedChannelId === null || providedChannelId === "") {
|
|
118
|
+
data.channelId = options.channelId;
|
|
119
|
+
}
|
|
120
|
+
else if (providedChannelId !== options.channelId) {
|
|
121
|
+
throw new Error(`definition channelId "${String(providedChannelId)}" does not match the current channel "${options.channelId}".`);
|
|
122
|
+
}
|
|
123
|
+
const event = parseScheduledEventContent(JSON.stringify(data), `${name}.json`);
|
|
124
|
+
if (event.type === "immediate") {
|
|
125
|
+
throw new Error("event_manage cannot create or update immediate events (self-triggering loop guard); " +
|
|
126
|
+
"do the work in the current turn instead.");
|
|
127
|
+
}
|
|
128
|
+
if (event.type === "one-shot") {
|
|
129
|
+
validateOneShot(event);
|
|
130
|
+
}
|
|
131
|
+
if (event.type === "periodic") {
|
|
132
|
+
validatePeriodic(event);
|
|
133
|
+
}
|
|
134
|
+
validatePreAction(event, options.commandGuardConfig);
|
|
135
|
+
return event;
|
|
136
|
+
}
|
|
137
|
+
async function readOwnedEvent(eventPath, name, options) {
|
|
138
|
+
let existing;
|
|
139
|
+
try {
|
|
140
|
+
existing = parseScheduledEventContent(await readFile(eventPath, "utf-8"), `${name}.json`);
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
144
|
+
throw new Error(`Existing event "${name}" could not be parsed (${message}); use /events to manage it directly.`);
|
|
145
|
+
}
|
|
146
|
+
if (existing.channelId !== options.channelId) {
|
|
147
|
+
throw new Error(`Event "${name}" belongs to another channel and cannot be modified from here.`);
|
|
148
|
+
}
|
|
149
|
+
return existing;
|
|
150
|
+
}
|
|
151
|
+
async function countEventFiles(dir) {
|
|
152
|
+
if (!existsSync(dir))
|
|
153
|
+
return 0;
|
|
154
|
+
const filenames = await readdir(dir);
|
|
155
|
+
return filenames.filter((filename) => filename.endsWith(".json")).length;
|
|
156
|
+
}
|
|
157
|
+
export async function manageEvent(options, request) {
|
|
158
|
+
const { eventName, eventPath } = resolveEventPath(options.workspaceDir, request.name);
|
|
159
|
+
const eventsDir = join(options.workspaceDir, "events");
|
|
160
|
+
if (request.action === "delete") {
|
|
161
|
+
if (!existsSync(eventPath)) {
|
|
162
|
+
return {
|
|
163
|
+
action: "delete",
|
|
164
|
+
name: eventName,
|
|
165
|
+
path: toWorkspacePath(options, eventPath),
|
|
166
|
+
deleted: false,
|
|
167
|
+
notice: `事件 \`${eventName}\` 不存在,无需删除。`,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
await readOwnedEvent(eventPath, eventName, options);
|
|
171
|
+
await unlink(eventPath);
|
|
172
|
+
return {
|
|
173
|
+
action: "delete",
|
|
174
|
+
name: eventName,
|
|
175
|
+
path: toWorkspacePath(options, eventPath),
|
|
176
|
+
deleted: true,
|
|
177
|
+
notice: `已删除事件 \`${eventName}\`。`,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
if (!request.definition || request.definition.trim().length === 0) {
|
|
181
|
+
throw new Error(`${request.action} requires a non-empty definition.`);
|
|
182
|
+
}
|
|
183
|
+
if (request.action === "create") {
|
|
184
|
+
if (existsSync(eventPath)) {
|
|
185
|
+
throw new Error(`Event "${eventName}" already exists; use action "update" to replace it.`);
|
|
186
|
+
}
|
|
187
|
+
if ((await countEventFiles(eventsDir)) >= MAX_EVENT_FILES) {
|
|
188
|
+
throw new Error(`Too many event files (>= ${MAX_EVENT_FILES}) in workspace/events; clean up stale events before creating more.`);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
if (!existsSync(eventPath)) {
|
|
193
|
+
throw new Error(`Event "${eventName}" does not exist; use action "create" to add it.`);
|
|
194
|
+
}
|
|
195
|
+
const existing = await readOwnedEvent(eventPath, eventName, options);
|
|
196
|
+
if (existing.type === "immediate") {
|
|
197
|
+
throw new Error(`Event "${eventName}" is an immediate event and cannot be updated via event_manage.`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
const event = validateDefinition(request.definition, eventName, options);
|
|
201
|
+
const content = `${JSON.stringify(event, null, 2)}\n`;
|
|
202
|
+
await writeFileAtomically(eventPath, content);
|
|
203
|
+
return {
|
|
204
|
+
action: request.action,
|
|
205
|
+
name: eventName,
|
|
206
|
+
path: toWorkspacePath(options, eventPath),
|
|
207
|
+
eventType: event.type,
|
|
208
|
+
channelId: event.channelId,
|
|
209
|
+
bytesWritten: Buffer.byteLength(content, "utf-8"),
|
|
210
|
+
notice: request.action === "create"
|
|
211
|
+
? `已创建 ${event.type} 事件 \`${eventName}\`。`
|
|
212
|
+
: `已更新 ${event.type} 事件 \`${eventName}\`。`,
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
export function createEventManageTool(options) {
|
|
216
|
+
return {
|
|
217
|
+
name: "event_manage",
|
|
218
|
+
label: "event_manage",
|
|
219
|
+
description: "Create, update, or delete scheduled events (one-shot check-ins and periodic cadences) that wake this " +
|
|
220
|
+
"channel later. Use for task self-scheduling: arrange a follow-up after delegating, reschedule while " +
|
|
221
|
+
"blocked, clean up on close. immediate events are rejected; do that work in the current turn.",
|
|
222
|
+
parameters: eventManageSchema,
|
|
223
|
+
execute: async (_toolCallId, args) => {
|
|
224
|
+
const result = await manageEvent(options, {
|
|
225
|
+
action: parseAction(args.action),
|
|
226
|
+
name: args.name,
|
|
227
|
+
definition: args.definition,
|
|
228
|
+
});
|
|
229
|
+
return {
|
|
230
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
231
|
+
details: {
|
|
232
|
+
kind: "event_manage",
|
|
233
|
+
...result,
|
|
234
|
+
},
|
|
235
|
+
};
|
|
236
|
+
},
|
|
237
|
+
};
|
|
238
|
+
}
|
|
@@ -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 {};
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { Type } from "typebox";
|
|
2
|
+
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
3
|
+
import { logSecurityEvent } from "../security/logger.js";
|
|
4
|
+
import { guardPath } from "../security/path-guard.js";
|
|
5
|
+
import { shellEscape } from "../shared/shell-escape.js";
|
|
6
|
+
import { DEFAULT_MAX_BYTES, truncateHead } from "./truncate.js";
|
|
7
|
+
/**
|
|
8
|
+
* Structured content search over the sandbox filesystem. The execution layer is deliberately thin
|
|
9
|
+
* — one `grep -rnH -B1 -A3` invocation through the shared Executor, so it works identically on the
|
|
10
|
+
* host and inside the Docker (busybox) sandbox with no native dependency. The value lives in the
|
|
11
|
+
* JS-side output shaping: per-file grouping, per-file and per-page caps, and a final byte bound, so
|
|
12
|
+
* a broad search can never flood the model's context the way raw `bash grep -rn` would.
|
|
13
|
+
*/
|
|
14
|
+
const CONTEXT_BEFORE = 1;
|
|
15
|
+
const CONTEXT_AFTER = 3;
|
|
16
|
+
const LINE_MAX_CHARS = 512;
|
|
17
|
+
/** Match cap per file: tight for multi-file scopes (anti-monopoly), generous for a single file. */
|
|
18
|
+
const MULTI_FILE_PER_FILE_MATCHES = 20;
|
|
19
|
+
const SINGLE_FILE_MATCHES = 200;
|
|
20
|
+
/** Files shown per page; `skip` pages through the rest. */
|
|
21
|
+
const FILE_PAGE_LIMIT = 20;
|
|
22
|
+
const SEARCH_TIMEOUT_SECONDS = 30;
|
|
23
|
+
/** Directories never worth scanning; filtered in JS since busybox grep lacks --exclude-dir. */
|
|
24
|
+
const IGNORED_DIR_SEGMENTS = new Set(["node_modules", ".git", ".hg", ".svn", "dist", "build", ".next", ".cache"]);
|
|
25
|
+
const grepSchema = Type.Object({
|
|
26
|
+
label: Type.String({ description: "Brief description of what you're searching for and why (shown to user)" }),
|
|
27
|
+
pattern: Type.String({ description: "Extended regular expression (ERE) to search for in file contents." }),
|
|
28
|
+
path: Type.Optional(Type.String({ description: "File or directory to search. Defaults to the workspace root." })),
|
|
29
|
+
glob: Type.Optional(Type.String({
|
|
30
|
+
description: 'Filename filter for directory searches, e.g. "*.ts". Matched against the basename.',
|
|
31
|
+
})),
|
|
32
|
+
caseSensitive: Type.Optional(Type.Boolean({ description: "Case-sensitive match. Defaults to true." })),
|
|
33
|
+
skip: Type.Optional(Type.Integer({ minimum: 0, description: "File-page offset for paging through many matching files." })),
|
|
34
|
+
});
|
|
35
|
+
function formatPathBlockMessage(resolvedPath, category, reason) {
|
|
36
|
+
const lines = [`Path blocked${category ? ` [${category}]` : ""}`];
|
|
37
|
+
if (reason) {
|
|
38
|
+
lines.push(`Reason: ${reason}`);
|
|
39
|
+
}
|
|
40
|
+
if (resolvedPath) {
|
|
41
|
+
lines.push(`Resolved path: ${resolvedPath}`);
|
|
42
|
+
}
|
|
43
|
+
return lines.join("\n");
|
|
44
|
+
}
|
|
45
|
+
/** Convert a simple `*`/`?` glob into an anchored regex matched against a basename. */
|
|
46
|
+
function globToRegExp(glob) {
|
|
47
|
+
const escaped = glob
|
|
48
|
+
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
|
|
49
|
+
.replace(/\*/g, ".*")
|
|
50
|
+
.replace(/\?/g, ".");
|
|
51
|
+
return new RegExp(`^${escaped}$`);
|
|
52
|
+
}
|
|
53
|
+
function truncateLine(text) {
|
|
54
|
+
return text.length > LINE_MAX_CHARS ? `${text.slice(0, LINE_MAX_CHARS)}…` : text;
|
|
55
|
+
}
|
|
56
|
+
function isIgnoredPath(relPath) {
|
|
57
|
+
return relPath.split("/").some((segment) => IGNORED_DIR_SEGMENTS.has(segment));
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Parse `grep -rnH -B -A` output into ordered per-file entries. Match lines are `path:N:text`;
|
|
61
|
+
* context lines are `path-N-text`. Context is attributed by anchoring on the current match file's
|
|
62
|
+
* exact path string, so a hyphen or colon inside a filename can never misattribute a line. Before
|
|
63
|
+
* context (which precedes a file's first match) is buffered until that match names the file.
|
|
64
|
+
*/
|
|
65
|
+
function parseGrepOutput(stdout) {
|
|
66
|
+
const files = new Map();
|
|
67
|
+
let currentFile;
|
|
68
|
+
const pendingContext = [];
|
|
69
|
+
const ensure = (file) => {
|
|
70
|
+
let entries = files.get(file);
|
|
71
|
+
if (!entries) {
|
|
72
|
+
entries = [];
|
|
73
|
+
files.set(file, entries);
|
|
74
|
+
}
|
|
75
|
+
return entries;
|
|
76
|
+
};
|
|
77
|
+
const attributeContext = (raw, file) => {
|
|
78
|
+
const prefix = `${file}-`;
|
|
79
|
+
if (!raw.startsWith(prefix)) {
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
const rest = raw.slice(prefix.length);
|
|
83
|
+
const sep = rest.indexOf("-");
|
|
84
|
+
if (sep < 0) {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
const lineNum = Number.parseInt(rest.slice(0, sep), 10);
|
|
88
|
+
if (!Number.isFinite(lineNum)) {
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
ensure(file).push({ line: lineNum, text: rest.slice(sep + 1), isMatch: false });
|
|
92
|
+
return true;
|
|
93
|
+
};
|
|
94
|
+
for (const raw of stdout.split("\n")) {
|
|
95
|
+
if (raw === "" || raw === "--") {
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
const matchDelim = raw.match(/^(.+?):(\d+):/);
|
|
99
|
+
if (matchDelim) {
|
|
100
|
+
const file = matchDelim[1];
|
|
101
|
+
const line = Number.parseInt(matchDelim[2], 10);
|
|
102
|
+
const text = raw.slice(matchDelim[0].length);
|
|
103
|
+
currentFile = file;
|
|
104
|
+
// Retro-attribute any before-context buffered ahead of this file's first match.
|
|
105
|
+
for (const buffered of pendingContext.splice(0)) {
|
|
106
|
+
attributeContext(buffered, file);
|
|
107
|
+
}
|
|
108
|
+
ensure(file).push({ line, text, isMatch: true });
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
// Context line: attribute to the current file, else buffer for the next match.
|
|
112
|
+
if (!currentFile || !attributeContext(raw, currentFile)) {
|
|
113
|
+
pendingContext.push(raw);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return files;
|
|
117
|
+
}
|
|
118
|
+
function renderFileGroup(file, entries, perFileMatchCap) {
|
|
119
|
+
const lines = [`== ${file} ==`];
|
|
120
|
+
let matchesShown = 0;
|
|
121
|
+
let capped = false;
|
|
122
|
+
for (const entry of entries) {
|
|
123
|
+
if (entry.isMatch && matchesShown >= perFileMatchCap) {
|
|
124
|
+
capped = true;
|
|
125
|
+
break;
|
|
126
|
+
}
|
|
127
|
+
const marker = entry.isMatch ? "*" : " ";
|
|
128
|
+
lines.push(`${marker}${entry.line}:${truncateLine(entry.text)}`);
|
|
129
|
+
if (entry.isMatch) {
|
|
130
|
+
matchesShown++;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return { text: lines.join("\n"), capped, matchesShown };
|
|
134
|
+
}
|
|
135
|
+
export function createGrepTool(executor, options = {}) {
|
|
136
|
+
const securityConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
|
|
137
|
+
const securityContext = options.securityContext ?? {
|
|
138
|
+
workspaceDir: process.cwd(),
|
|
139
|
+
workspacePath: process.cwd(),
|
|
140
|
+
cwd: process.cwd(),
|
|
141
|
+
};
|
|
142
|
+
return {
|
|
143
|
+
name: "grep",
|
|
144
|
+
label: "grep",
|
|
145
|
+
description: "Search file contents with an extended regular expression across a file or directory tree. Output is " +
|
|
146
|
+
"grouped by file, capped per file, paginated, and token-bounded — prefer this over `bash grep -rn`, which " +
|
|
147
|
+
"floods context. Match lines are marked with `*`, context lines with a space.",
|
|
148
|
+
parameters: grepSchema,
|
|
149
|
+
execute: async (_toolCallId, { pattern, path, glob, caseSensitive, skip, }, signal) => {
|
|
150
|
+
if (!pattern.trim()) {
|
|
151
|
+
throw new Error("Pattern must not be empty.");
|
|
152
|
+
}
|
|
153
|
+
const searchPath = path?.trim() || ".";
|
|
154
|
+
if (securityConfig.enabled && securityConfig.pathGuard.enabled) {
|
|
155
|
+
const guardResult = guardPath(searchPath, "read", { ...securityContext, config: securityConfig.pathGuard });
|
|
156
|
+
if (!guardResult.allowed) {
|
|
157
|
+
logSecurityEvent(securityContext.workspaceDir, securityConfig, {
|
|
158
|
+
type: "path",
|
|
159
|
+
tool: "grep",
|
|
160
|
+
channelId: options.channelId,
|
|
161
|
+
rawPath: searchPath,
|
|
162
|
+
operation: "read",
|
|
163
|
+
resolvedPath: guardResult.resolvedPath,
|
|
164
|
+
category: guardResult.category,
|
|
165
|
+
reason: guardResult.reason,
|
|
166
|
+
});
|
|
167
|
+
throw new Error(formatPathBlockMessage(guardResult.resolvedPath, guardResult.category, guardResult.reason));
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
const flags = ["-rnH", "-E", `-B${CONTEXT_BEFORE}`, `-A${CONTEXT_AFTER}`];
|
|
171
|
+
if (caseSensitive === false) {
|
|
172
|
+
flags.push("-i");
|
|
173
|
+
}
|
|
174
|
+
// `--` terminates flags so a pattern beginning with `-` is not read as one.
|
|
175
|
+
const command = `grep ${flags.join(" ")} -- ${shellEscape(pattern)} ${shellEscape(searchPath)}`;
|
|
176
|
+
const result = await executor.exec(command, { timeout: SEARCH_TIMEOUT_SECONDS, signal });
|
|
177
|
+
// grep exit code 1 = no matches (normal), 0 = matches, >=2 = error.
|
|
178
|
+
if (result.code >= 2) {
|
|
179
|
+
const stderr = result.stderr.trim();
|
|
180
|
+
throw new Error(`grep failed: ${stderr || `exit code ${result.code}`}. Check the regex (ERE syntax) and that the path exists.`);
|
|
181
|
+
}
|
|
182
|
+
const globRegExp = glob ? globToRegExp(glob) : undefined;
|
|
183
|
+
const parsed = parseGrepOutput(result.stdout);
|
|
184
|
+
// Filter ignored dirs and (for directory scopes) the optional glob, on the basename.
|
|
185
|
+
const files = [];
|
|
186
|
+
for (const [file, entries] of parsed) {
|
|
187
|
+
const normalized = file.replace(/^\.\//, "");
|
|
188
|
+
if (isIgnoredPath(normalized)) {
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
if (globRegExp) {
|
|
192
|
+
const base = normalized.split("/").pop() ?? normalized;
|
|
193
|
+
if (!globRegExp.test(base)) {
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
files.push([normalized, entries]);
|
|
198
|
+
}
|
|
199
|
+
if (files.length === 0) {
|
|
200
|
+
const scope = glob ? `${searchPath} (glob ${glob})` : searchPath;
|
|
201
|
+
return {
|
|
202
|
+
content: [
|
|
203
|
+
{
|
|
204
|
+
type: "text",
|
|
205
|
+
text: `No matches found in ${scope}. Try a broader pattern, drop the glob, or widen the path.`,
|
|
206
|
+
},
|
|
207
|
+
],
|
|
208
|
+
details: { kind: "grep", matchCount: 0, fileCount: 0 },
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
files.sort((a, b) => a[0].localeCompare(b[0]));
|
|
212
|
+
const isSingleFile = files.length === 1;
|
|
213
|
+
const perFileMatchCap = isSingleFile ? SINGLE_FILE_MATCHES : MULTI_FILE_PER_FILE_MATCHES;
|
|
214
|
+
const startOffset = skip && skip > 0 ? skip : 0;
|
|
215
|
+
const page = files.slice(startOffset, startOffset + FILE_PAGE_LIMIT);
|
|
216
|
+
if (page.length === 0) {
|
|
217
|
+
return {
|
|
218
|
+
content: [
|
|
219
|
+
{
|
|
220
|
+
type: "text",
|
|
221
|
+
text: `No more matching files (skip=${startOffset} is past the last of ${files.length}).`,
|
|
222
|
+
},
|
|
223
|
+
],
|
|
224
|
+
details: { kind: "grep", matchCount: 0, fileCount: files.length },
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
const blocks = [];
|
|
228
|
+
let shownMatchCount = 0;
|
|
229
|
+
let anyFileCapped = false;
|
|
230
|
+
for (const [file, entries] of page) {
|
|
231
|
+
const { text, capped, matchesShown } = renderFileGroup(file, entries, perFileMatchCap);
|
|
232
|
+
blocks.push(text);
|
|
233
|
+
shownMatchCount += matchesShown;
|
|
234
|
+
anyFileCapped = anyFileCapped || capped;
|
|
235
|
+
}
|
|
236
|
+
const footerLines = [];
|
|
237
|
+
if (anyFileCapped) {
|
|
238
|
+
footerLines.push(`[Some files were capped at ${perFileMatchCap} matches; narrow the pattern for the rest.]`);
|
|
239
|
+
}
|
|
240
|
+
const moreFiles = files.length - (startOffset + page.length);
|
|
241
|
+
if (moreFiles > 0) {
|
|
242
|
+
footerLines.push(`[${moreFiles} more matching file(s). Use skip=${startOffset + page.length} for the next page.]`);
|
|
243
|
+
}
|
|
244
|
+
const body = blocks.join("\n\n");
|
|
245
|
+
const footer = footerLines.length > 0 ? `\n\n${footerLines.join("\n")}` : "";
|
|
246
|
+
const truncation = truncateHead(body);
|
|
247
|
+
let outputText = truncation.content + footer;
|
|
248
|
+
if (truncation.truncated) {
|
|
249
|
+
outputText += `\n\n[Output truncated at ${DEFAULT_MAX_BYTES / 1024}KB; narrow the pattern or path to see the rest.]`;
|
|
250
|
+
}
|
|
251
|
+
return {
|
|
252
|
+
content: [{ type: "text", text: outputText }],
|
|
253
|
+
details: {
|
|
254
|
+
kind: "grep",
|
|
255
|
+
matchCount: shownMatchCount,
|
|
256
|
+
fileCount: files.length,
|
|
257
|
+
shownFileCount: page.length,
|
|
258
|
+
},
|
|
259
|
+
};
|
|
260
|
+
},
|
|
261
|
+
};
|
|
262
|
+
}
|
package/dist/tools/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { getChannelJobManager } from "../agent/job-manager.js";
|
|
1
2
|
import { APP_HOME_DIR } from "../paths.js";
|
|
2
3
|
import { loadSecurityConfig } from "../security/config.js";
|
|
3
4
|
import { createSubAgentTool } from "../subagents/tool.js";
|
|
@@ -26,6 +27,10 @@ export function createPipiclawTools(options) {
|
|
|
26
27
|
webConfig: toolsConfig.tools.web,
|
|
27
28
|
toolsConfig,
|
|
28
29
|
rtkEnabled: toolsConfig.tools.rtk.enabled,
|
|
30
|
+
// Background jobs are opt-in; when off, bash `async` errors and the job tool is not registered.
|
|
31
|
+
jobManager: toolsConfig.tools.jobs.enabled
|
|
32
|
+
? getChannelJobManager(options.channelId, options.executor)
|
|
33
|
+
: undefined,
|
|
29
34
|
getCurrentModel: options.getCurrentModel,
|
|
30
35
|
getAvailableModels: options.getAvailableModels,
|
|
31
36
|
resolveApiKey: options.resolveApiKey,
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import type { ChannelJobManager } from "../agent/job-manager.js";
|
|
4
|
+
declare const jobSchema: Type.TObject<{
|
|
5
|
+
label: Type.TString;
|
|
6
|
+
op: Type.TUnion<[Type.TLiteral<"list">, Type.TLiteral<"poll">, Type.TLiteral<"cancel">]>;
|
|
7
|
+
ids: Type.TOptional<Type.TArray<Type.TString>>;
|
|
8
|
+
}>;
|
|
9
|
+
export interface JobToolOptions {
|
|
10
|
+
jobManager: ChannelJobManager;
|
|
11
|
+
}
|
|
12
|
+
export declare function createJobTool(options: JobToolOptions): AgentTool<typeof jobSchema>;
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { Type } from "typebox";
|
|
2
|
+
import { truncateTail } from "./truncate.js";
|
|
3
|
+
const jobSchema = Type.Object({
|
|
4
|
+
label: Type.String({ description: "Brief description of what you're checking (shown to user)" }),
|
|
5
|
+
op: Type.Union([Type.Literal("list"), Type.Literal("poll"), Type.Literal("cancel")], {
|
|
6
|
+
description: '"list" a snapshot of background jobs, "poll" to wait (briefly) for one to finish, or "cancel" jobs by id.',
|
|
7
|
+
}),
|
|
8
|
+
ids: Type.Optional(Type.Array(Type.String(), {
|
|
9
|
+
description: "Job ids for poll/cancel. For poll, omit to watch all running jobs.",
|
|
10
|
+
})),
|
|
11
|
+
});
|
|
12
|
+
function formatDuration(ms) {
|
|
13
|
+
const seconds = Math.round(ms / 1000);
|
|
14
|
+
if (seconds < 60) {
|
|
15
|
+
return `${seconds}s`;
|
|
16
|
+
}
|
|
17
|
+
return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
|
|
18
|
+
}
|
|
19
|
+
function formatJobLine(job) {
|
|
20
|
+
const exit = job.exitCode !== undefined ? `, exit ${job.exitCode}` : "";
|
|
21
|
+
return `- [${job.id}] ${job.label} — ${job.status} (${formatDuration(job.durationMs)}${exit})`;
|
|
22
|
+
}
|
|
23
|
+
export function createJobTool(options) {
|
|
24
|
+
const { jobManager } = options;
|
|
25
|
+
async function completedDetail(jobs) {
|
|
26
|
+
const sections = [];
|
|
27
|
+
for (const job of jobs) {
|
|
28
|
+
const output = await jobManager.readOutput(job.id);
|
|
29
|
+
const tail = output ? truncateTail(output.text).content : "";
|
|
30
|
+
const body = tail.trim() ? tail : "(no output)";
|
|
31
|
+
const path = output ? `\nFull output: ${output.spillFile}` : "";
|
|
32
|
+
sections.push(`### [${job.id}] ${job.label} — ${job.status}${job.exitCode !== undefined ? `, exit ${job.exitCode}` : ""}\n${body}${path}`);
|
|
33
|
+
}
|
|
34
|
+
return sections;
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
name: "job",
|
|
38
|
+
label: "job",
|
|
39
|
+
description: "Inspect and control background bash jobs (started with bash async:true). op=list shows a snapshot; " +
|
|
40
|
+
"op=poll waits briefly for a running job to finish and returns its output; op=cancel stops jobs by id. " +
|
|
41
|
+
"To be woken when a long job is likely done, schedule a check-in with event_manage instead of blocking.",
|
|
42
|
+
parameters: jobSchema,
|
|
43
|
+
execute: async (_toolCallId, { op, ids }, signal) => {
|
|
44
|
+
if (op === "cancel") {
|
|
45
|
+
if (!ids || ids.length === 0) {
|
|
46
|
+
throw new Error("cancel requires at least one job id.");
|
|
47
|
+
}
|
|
48
|
+
const outcomes = await jobManager.cancel(ids, signal);
|
|
49
|
+
const text = outcomes.map((outcome) => `- [${outcome.id}] ${outcome.status}`).join("\n");
|
|
50
|
+
return {
|
|
51
|
+
content: [{ type: "text", text: `Cancel results:\n${text}` }],
|
|
52
|
+
details: { kind: "job", op: "cancel", outcomes },
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
if (op === "list") {
|
|
56
|
+
const jobs = await jobManager.list(signal);
|
|
57
|
+
if (jobs.length === 0) {
|
|
58
|
+
return {
|
|
59
|
+
content: [{ type: "text", text: "No background jobs." }],
|
|
60
|
+
details: { kind: "job", op: "list", jobs },
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
content: [{ type: "text", text: jobs.map(formatJobLine).join("\n") }],
|
|
65
|
+
details: { kind: "job", op: "list", jobs },
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
// poll
|
|
69
|
+
const jobs = await jobManager.poll(ids, signal);
|
|
70
|
+
if (jobs.length === 0) {
|
|
71
|
+
return {
|
|
72
|
+
content: [{ type: "text", text: "No matching running jobs to wait for." }],
|
|
73
|
+
details: { kind: "job", op: "poll", jobs },
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
const finished = jobs.filter((job) => job.status !== "running");
|
|
77
|
+
const running = jobs.filter((job) => job.status === "running");
|
|
78
|
+
const parts = [];
|
|
79
|
+
if (finished.length > 0) {
|
|
80
|
+
parts.push(`## Finished (${finished.length})`, ...(await completedDetail(finished)));
|
|
81
|
+
}
|
|
82
|
+
if (running.length > 0) {
|
|
83
|
+
parts.push(`## Still running (${running.length})`, ...running.map(formatJobLine));
|
|
84
|
+
parts.push("Poll again to keep waiting, or schedule a check-in with event_manage.");
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
content: [{ type: "text", text: parts.join("\n\n") }],
|
|
88
|
+
details: { kind: "job", op: "poll", jobs },
|
|
89
|
+
};
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
3
|
+
import { Type } from "typebox";
|
|
4
|
+
import type { MemoryCandidateStore } from "../memory/candidates.js";
|
|
5
|
+
import { type ChannelMemoryQueue } from "../memory/channel-maintenance-queue.js";
|
|
6
|
+
declare const memoryManageSchema: Type.TObject<{
|
|
7
|
+
label: Type.TString;
|
|
8
|
+
op: Type.TUnion<[Type.TLiteral<"save">, Type.TLiteral<"search">, Type.TLiteral<"forget">]>;
|
|
9
|
+
content: Type.TOptional<Type.TString>;
|
|
10
|
+
query: Type.TOptional<Type.TString>;
|
|
11
|
+
target: Type.TOptional<Type.TString>;
|
|
12
|
+
kind: Type.TOptional<Type.TUnion<[Type.TLiteral<"preference">, Type.TLiteral<"fact">, Type.TLiteral<"decision">, Type.TLiteral<"constraint">, Type.TLiteral<"open-loop">]>>;
|
|
13
|
+
}>;
|
|
14
|
+
export interface MemoryManageToolOptions {
|
|
15
|
+
channelId: string;
|
|
16
|
+
channelDir: string;
|
|
17
|
+
workspaceDir: string;
|
|
18
|
+
memoryCandidateStore: MemoryCandidateStore;
|
|
19
|
+
getCurrentModel: () => Model<Api>;
|
|
20
|
+
resolveApiKey: (model: Model<Api>) => Promise<string>;
|
|
21
|
+
channelMemoryQueue?: ChannelMemoryQueue;
|
|
22
|
+
}
|
|
23
|
+
export declare function createMemoryManageTool(options: MemoryManageToolOptions): AgentTool<typeof memoryManageSchema>;
|
|
24
|
+
export {};
|