@oyasmi/pipiclaw 0.9.3-beta.1 → 0.9.3-beta.3
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.en.md +1 -1
- package/README.md +1 -1
- package/dist/agent/channel-runner.d.ts +16 -0
- package/dist/agent/channel-runner.js +47 -6
- package/dist/agent/job-manager.d.ts +9 -0
- package/dist/agent/job-manager.js +20 -6
- package/dist/agent/prompt/builder.d.ts +1 -1
- package/dist/agent/prompt/builder.js +1 -1
- package/dist/agent/prompt/sections.js +3 -3
- package/dist/executor.d.ts +5 -1
- package/dist/executor.js +35 -5
- package/dist/file-store.d.ts +4 -1
- package/dist/file-store.js +5 -0
- package/dist/memory/journal.d.ts +13 -0
- package/dist/memory/journal.js +47 -4
- package/dist/memory/render.d.ts +5 -0
- package/dist/memory/render.js +9 -2
- package/dist/memory/search.js +13 -6
- package/dist/memory/session-corpus.d.ts +11 -0
- package/dist/memory/session-corpus.js +15 -4
- package/dist/memory/session-search.d.ts +3 -0
- package/dist/memory/session-search.js +45 -8
- package/dist/memory/store.d.ts +9 -0
- package/dist/memory/store.js +25 -2
- package/dist/memory/transcript.js +12 -5
- package/dist/playbooks/agent-delegation.md +35 -50
- package/dist/playbooks/background-jobs.md +14 -16
- package/dist/playbooks/event-scheduling.md +20 -25
- package/dist/playbooks/memory-and-learning.md +28 -44
- package/dist/playbooks/outbound-media.md +10 -12
- package/dist/playbooks/runtime-orientation.md +34 -53
- package/dist/playbooks/task-loop.md +50 -48
- package/dist/runtime/bootstrap.js +25 -11
- package/dist/security/path-guard-filter.d.ts +22 -0
- package/dist/security/path-guard-filter.js +35 -0
- package/dist/subagents/discovery.d.ts +2 -3
- package/dist/subagents/discovery.js +3 -1
- package/dist/subagents/tool.d.ts +6 -0
- package/dist/subagents/tool.js +10 -2
- package/dist/tasks/brief.d.ts +1 -1
- package/dist/tasks/brief.js +11 -2
- package/dist/tasks/log.d.ts +4 -0
- package/dist/tasks/log.js +13 -1
- package/dist/tasks/rounds.d.ts +0 -2
- package/dist/tasks/rounds.js +0 -4
- package/dist/tasks/verification.d.ts +31 -0
- package/dist/tasks/verification.js +20 -0
- package/dist/tools/bash.d.ts +13 -0
- package/dist/tools/bash.js +123 -20
- package/dist/tools/edit.js +36 -5
- package/dist/tools/event-manage.d.ts +25 -4
- package/dist/tools/event-manage.js +81 -33
- package/dist/tools/glob.js +57 -4
- package/dist/tools/grep.d.ts +2 -0
- package/dist/tools/grep.js +187 -14
- package/dist/tools/job.js +16 -4
- package/dist/tools/memory-manage.js +80 -41
- package/dist/tools/read.js +42 -5
- package/dist/tools/registry.d.ts +6 -0
- package/dist/tools/registry.js +4 -1
- package/dist/tools/send-media.js +6 -4
- package/dist/tools/session-search.js +4 -1
- package/dist/tools/skill.d.ts +2 -0
- package/dist/tools/skill.js +12 -0
- package/dist/tools/subagent-manage.js +1 -1
- package/dist/tools/subagent-tool-names.d.ts +11 -0
- package/dist/tools/subagent-tool-names.js +19 -0
- package/dist/tools/task-manage/lifecycle.js +2 -6
- package/dist/tools/task-manage/log-view.js +6 -3
- package/dist/tools/task-manage/schema.d.ts +6 -6
- package/dist/tools/task-manage/schema.js +5 -12
- package/dist/tools/task-manage/shared.d.ts +11 -0
- package/dist/tools/task-manage/shared.js +43 -2
- package/dist/tools/task-manage/step-end.js +28 -13
- package/dist/tools/task-manage.js +9 -1
- package/dist/tools/web-cache.d.ts +11 -3
- package/dist/tools/web-cache.js +26 -8
- package/dist/tools/web-fetch.d.ts +1 -0
- package/dist/tools/web-fetch.js +68 -15
- package/dist/tools/write.js +3 -0
- package/dist/web/fetch.d.ts +5 -0
- package/dist/web/fetch.js +36 -1
- package/examples/sub-agents/README.md +65 -39
- package/examples/sub-agents/builder-hard.md +12 -25
- package/examples/sub-agents/builder.md +12 -24
- package/examples/sub-agents/explorer.md +13 -17
- package/examples/sub-agents/git-committer.md +16 -19
- package/examples/sub-agents/planner.md +11 -20
- package/examples/sub-agents/reviewer.md +11 -30
- package/examples/sub-agents/verifier.md +13 -22
- package/examples/sub-agents/worker.md +12 -20
- package/package.json +7 -3
- package/examples/sub-agents/documenter.md +0 -50
- package/examples/sub-agents/log-sifter.md +0 -47
- package/examples/sub-agents/scout.md +0 -34
|
@@ -8,23 +8,41 @@ import { parseScheduledEventContent } from "../runtime/events.js";
|
|
|
8
8
|
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
9
9
|
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
10
10
|
import { clipText, errorMessage } from "../shared/text-utils.js";
|
|
11
|
-
|
|
11
|
+
const eventDefinitionSchema = Type.Object({
|
|
12
|
+
type: Type.Union([Type.Literal("one-shot"), Type.Literal("periodic"), Type.Literal("immediate")], {
|
|
13
|
+
description: '"one-shot" (needs `at`), "periodic" (needs cron `schedule`). "immediate" is always rejected.',
|
|
14
|
+
}),
|
|
15
|
+
text: Type.String({ description: "Message delivered to the channel when the event fires." }),
|
|
16
|
+
at: Type.Optional(Type.String({ description: "one-shot local time, e.g. 2026-07-27T07:30:00+08:00 (2 min to ~24.8 days out)." })),
|
|
17
|
+
schedule: Type.Optional(Type.String({ description: "periodic 5-field cron, in the host timezone." })),
|
|
18
|
+
preAction: Type.Optional(Type.Object({
|
|
19
|
+
type: Type.Literal("bash"),
|
|
20
|
+
command: Type.String({
|
|
21
|
+
description: "Command run just before delivery; exit 0 = fire, non-zero = skip.",
|
|
22
|
+
}),
|
|
23
|
+
timeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: "Timeout in milliseconds (not s)." })),
|
|
24
|
+
}, { description: "Optional gate/sensor command." })),
|
|
25
|
+
}, { description: "The event to create/update. Channel is bound automatically — do not pass channelId." });
|
|
12
26
|
const eventManageSchema = Type.Object({
|
|
13
|
-
action: Type.Union([
|
|
14
|
-
|
|
27
|
+
action: Type.Union([
|
|
28
|
+
Type.Literal("list"),
|
|
29
|
+
Type.Literal("show"),
|
|
30
|
+
Type.Literal("create"),
|
|
31
|
+
Type.Literal("update"),
|
|
32
|
+
Type.Literal("delete"),
|
|
33
|
+
], {
|
|
34
|
+
description: '"list" this channel\'s events, "show" one event\'s full definition (for a safe update), or "create" / "update" / "delete" one by name.',
|
|
15
35
|
}),
|
|
16
36
|
name: Type.Optional(Type.String({
|
|
17
|
-
description: "Event name (filename without .json); required for create/update/delete, ignored for list. Task-owned events: `task.<channelId>.<taskId>.<use>`.",
|
|
18
|
-
})),
|
|
19
|
-
definition: Type.Optional(Type.String({
|
|
20
|
-
description: "Full event JSON (required for create/update). one-shot / periodic only; one-shots 2 minutes to about 24.8 days out. channelId defaults to the current channel.",
|
|
37
|
+
description: "Event name (filename without .json); required for show/create/update/delete, ignored for list. Task-owned events: `task.<channelId>.<taskId>.<use>`.",
|
|
21
38
|
})),
|
|
39
|
+
definition: Type.Optional(eventDefinitionSchema),
|
|
22
40
|
});
|
|
23
41
|
function parseAction(action) {
|
|
24
|
-
if (action === "list" || action === "create" || action === "update" || action === "delete") {
|
|
42
|
+
if (action === "list" || action === "show" || action === "create" || action === "update" || action === "delete") {
|
|
25
43
|
return action;
|
|
26
44
|
}
|
|
27
|
-
throw new RecoverableToolError('Unsupported event action. Use "list", "create", "update", or "delete".');
|
|
45
|
+
throw new RecoverableToolError('Unsupported event action. Use "list", "show", "create", "update", or "delete".');
|
|
28
46
|
}
|
|
29
47
|
/** One line per event; unparseable files are listed and flagged so the model can still clean them up. */
|
|
30
48
|
async function listOwnedEvents(options) {
|
|
@@ -62,30 +80,45 @@ async function listOwnedEvents(options) {
|
|
|
62
80
|
* the watcher (spec 031, D4); this layer only adds tool-specific framing (channel ownership,
|
|
63
81
|
* and turning validation failures into recoverable tool errors the model can retry).
|
|
64
82
|
*/
|
|
65
|
-
function validateDefinition(
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
}
|
|
70
|
-
catch (error) {
|
|
71
|
-
const message = errorMessage(error);
|
|
72
|
-
throw new RecoverableToolError(`definition is not valid JSON: ${message}`);
|
|
83
|
+
function validateDefinition(definition, name, options) {
|
|
84
|
+
if (definition.type === "immediate") {
|
|
85
|
+
throw new RecoverableToolError("event_manage cannot create or update immediate events (self-triggering loop guard); " +
|
|
86
|
+
"do the work in the current turn instead.");
|
|
73
87
|
}
|
|
74
|
-
if (!
|
|
75
|
-
throw new RecoverableToolError(
|
|
88
|
+
if (definition.type === "one-shot" && !definition.at?.trim()) {
|
|
89
|
+
throw new RecoverableToolError('A one-shot event needs "at" (a local time 2 minutes to ~24.8 days out).');
|
|
76
90
|
}
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
data.channelId = options.channelId;
|
|
91
|
+
if (definition.type === "periodic" && !definition.schedule?.trim()) {
|
|
92
|
+
throw new RecoverableToolError('A periodic event needs "schedule" (a 5-field cron expression).');
|
|
80
93
|
}
|
|
81
|
-
|
|
82
|
-
|
|
94
|
+
// Assemble the on-disk shape. `channelId` is bound here, never taken from the model; the
|
|
95
|
+
// preAction timeout field is `timeout` (ms) on disk but `timeoutMs` in the schema so the unit
|
|
96
|
+
// is unambiguous (fix plan §3.6).
|
|
97
|
+
const onDisk = {
|
|
98
|
+
type: definition.type,
|
|
99
|
+
channelId: options.channelId,
|
|
100
|
+
text: definition.text,
|
|
101
|
+
...(definition.type === "one-shot" ? { at: definition.at } : { schedule: definition.schedule }),
|
|
102
|
+
...(definition.preAction
|
|
103
|
+
? {
|
|
104
|
+
preAction: {
|
|
105
|
+
type: "bash",
|
|
106
|
+
command: definition.preAction.command,
|
|
107
|
+
...(definition.preAction.timeoutMs !== undefined ? { timeout: definition.preAction.timeoutMs } : {}),
|
|
108
|
+
},
|
|
109
|
+
}
|
|
110
|
+
: {}),
|
|
111
|
+
};
|
|
112
|
+
// Both the parse and the schedule validation become recoverable: a missing/malformed field is
|
|
113
|
+
// something the model can fix itself, and `parseScheduledEventContent` used to throw a plain
|
|
114
|
+
// Error that bypassed the recoverable wrapper (fix plan §3.6).
|
|
115
|
+
let event;
|
|
116
|
+
try {
|
|
117
|
+
event = parseScheduledEventContent(JSON.stringify(onDisk), `${name}.json`);
|
|
83
118
|
}
|
|
84
|
-
|
|
85
|
-
throw new RecoverableToolError(
|
|
86
|
-
"do the work in the current turn instead.");
|
|
119
|
+
catch (error) {
|
|
120
|
+
throw new RecoverableToolError(`Invalid event definition: ${errorMessage(error)}`);
|
|
87
121
|
}
|
|
88
|
-
const event = parseScheduledEventContent(JSON.stringify(data), `${name}.json`);
|
|
89
122
|
try {
|
|
90
123
|
validateScheduledEvent(event, { commandGuardConfig: options.commandGuardConfig });
|
|
91
124
|
}
|
|
@@ -133,6 +166,20 @@ export async function manageEvent(options, request) {
|
|
|
133
166
|
}
|
|
134
167
|
const { eventName, eventPath } = resolveEventPath(options.workspaceDir, request.name);
|
|
135
168
|
const eventsDir = join(options.workspaceDir, "events");
|
|
169
|
+
if (request.action === "show") {
|
|
170
|
+
if (!existsSync(eventPath)) {
|
|
171
|
+
throw new RecoverableToolError(`Event "${eventName}" does not exist. Use action "list" to see what's here.`);
|
|
172
|
+
}
|
|
173
|
+
const existing = await readOwnedEvent(eventPath, eventName, options);
|
|
174
|
+
return {
|
|
175
|
+
action: "show",
|
|
176
|
+
name: eventName,
|
|
177
|
+
path: eventPath,
|
|
178
|
+
eventType: existing.type,
|
|
179
|
+
channelId: existing.channelId,
|
|
180
|
+
notice: JSON.stringify(existing, null, 2),
|
|
181
|
+
};
|
|
182
|
+
}
|
|
136
183
|
if (request.action === "delete") {
|
|
137
184
|
if (!existsSync(eventPath)) {
|
|
138
185
|
return {
|
|
@@ -153,8 +200,8 @@ export async function manageEvent(options, request) {
|
|
|
153
200
|
notice: `已删除事件 \`${eventName}\`。`,
|
|
154
201
|
};
|
|
155
202
|
}
|
|
156
|
-
if (!request.definition || request.definition.trim()
|
|
157
|
-
throw new RecoverableToolError(`${request.action} requires a
|
|
203
|
+
if (!request.definition || !request.definition.type || !request.definition.text?.trim()) {
|
|
204
|
+
throw new RecoverableToolError(`${request.action} requires a definition with at least "type" and "text".`);
|
|
158
205
|
}
|
|
159
206
|
if (request.action === "create") {
|
|
160
207
|
if (existsSync(eventPath)) {
|
|
@@ -196,8 +243,9 @@ export function createEventManageTool(options) {
|
|
|
196
243
|
return {
|
|
197
244
|
name: "event_manage",
|
|
198
245
|
label: "event_manage",
|
|
199
|
-
description: "List, create, update, or delete scheduled events that wake this channel later (one-shot check-ins and
|
|
200
|
-
"cadences).
|
|
246
|
+
description: "List, show, create, update, or delete scheduled events that wake this channel later (one-shot check-ins and " +
|
|
247
|
+
"periodic cadences). Use list to recover event names, and show to read an event's full definition before an " +
|
|
248
|
+
"update. immediate events are rejected.",
|
|
201
249
|
parameters: eventManageSchema,
|
|
202
250
|
execute: async (_toolCallId, args) => {
|
|
203
251
|
const result = await manageEvent(options, {
|
|
@@ -205,7 +253,7 @@ export function createEventManageTool(options) {
|
|
|
205
253
|
name: args.name,
|
|
206
254
|
definition: args.definition,
|
|
207
255
|
});
|
|
208
|
-
const text = result.action === "list" ? result.notice : JSON.stringify(result, null, 2);
|
|
256
|
+
const text = result.action === "list" || result.action === "show" ? result.notice : JSON.stringify(result, null, 2);
|
|
209
257
|
return {
|
|
210
258
|
content: [{ type: "text", text }],
|
|
211
259
|
details: { ...result },
|
package/dist/tools/glob.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { join } from "node:path";
|
|
1
|
+
import { isAbsolute, join, relative } from "node:path";
|
|
2
2
|
import { Type } from "typebox";
|
|
3
3
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
4
4
|
import { checkPathGuard } from "../security/path-guard-check.js";
|
|
5
|
+
import { partitionByReadGuard } from "../security/path-guard-filter.js";
|
|
5
6
|
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
6
7
|
import { errorMessage } from "../shared/text-utils.js";
|
|
7
8
|
import { compileGlobPattern } from "./glob-match.js";
|
|
@@ -26,6 +27,18 @@ const globSchema = Type.Object({
|
|
|
26
27
|
}),
|
|
27
28
|
path: Type.Optional(Type.String({ description: "Directory to search in. Defaults to the workspace/project root." })),
|
|
28
29
|
});
|
|
30
|
+
/** Turn a path relative to the search root into an address `read` accepts unchanged. */
|
|
31
|
+
function toReadableAddress(target, rel, securityContext) {
|
|
32
|
+
const abs = join(target, ...rel.split("/"));
|
|
33
|
+
const root = securityContext.projectRoot;
|
|
34
|
+
if (root) {
|
|
35
|
+
const fromRoot = relative(root, abs);
|
|
36
|
+
if (fromRoot && !fromRoot.startsWith("..") && !isAbsolute(fromRoot)) {
|
|
37
|
+
return fromRoot;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return abs;
|
|
41
|
+
}
|
|
29
42
|
export function createGlobTool(fileStore, options = {}) {
|
|
30
43
|
const securityConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
|
|
31
44
|
const securityContext = options.securityContext ?? {
|
|
@@ -58,13 +71,41 @@ export function createGlobTool(fileStore, options = {}) {
|
|
|
58
71
|
// simplifying it, which "invalid pattern" alone does not tell the model.
|
|
59
72
|
throw new RecoverableToolError(`Invalid glob pattern: ${pattern} (${errorMessage(error)})`);
|
|
60
73
|
}
|
|
74
|
+
// `walkFiles` swallows a failed top-level readdir and returns an empty tree, so an
|
|
75
|
+
// illegal root would read as "no matches" and send the model looking for a broader
|
|
76
|
+
// pattern. Distinguish the three cases up front.
|
|
77
|
+
const rootStat = await fileStore.stat(target);
|
|
78
|
+
if (!rootStat) {
|
|
79
|
+
throw new RecoverableToolError(`Search root not found: ${searchPath}. Pass an existing directory, or omit path to search the workspace root.`);
|
|
80
|
+
}
|
|
81
|
+
if (!rootStat.isDirectory) {
|
|
82
|
+
throw new RecoverableToolError(`Search root is not a directory: ${searchPath}. glob searches a directory tree; to match one file, read it directly.`);
|
|
83
|
+
}
|
|
61
84
|
const walk = await fileStore.walkFiles(target, {
|
|
62
85
|
maxEntries: MAX_SCAN_ENTRIES,
|
|
63
86
|
prune: (name) => IGNORED_DIR_SEGMENTS.has(name),
|
|
64
87
|
signal,
|
|
65
88
|
});
|
|
66
|
-
const
|
|
89
|
+
const matchedRaw = walk.files.filter((relativePath) => matcher.test(relativePath));
|
|
90
|
+
// Backstop: `walkFiles` descends into `readDeny`/sensitive subtrees the per-path guard
|
|
91
|
+
// would refuse for a direct `read`. Drop those paths so `glob` never leaks them (a path
|
|
92
|
+
// name is less than `grep`'s content leak, but it is still a leak).
|
|
93
|
+
const { allowed: allowedAbs, deniedCount: readDenyExcluded } = partitionByReadGuard(matchedRaw.map((rel) => join(target, ...rel.split("/"))), securityConfig, securityContext);
|
|
94
|
+
const allowedAbsSet = new Set(allowedAbs);
|
|
95
|
+
const matched = matchedRaw.filter((rel) => allowedAbsSet.has(join(target, ...rel.split("/"))));
|
|
67
96
|
if (matched.length === 0) {
|
|
97
|
+
if (readDenyExcluded > 0) {
|
|
98
|
+
return {
|
|
99
|
+
content: [
|
|
100
|
+
{
|
|
101
|
+
type: "text",
|
|
102
|
+
text: `All ${readDenyExcluded} path(s) matching "${pattern}" are excluded by the read policy. ` +
|
|
103
|
+
"Search a path you are allowed to read.",
|
|
104
|
+
},
|
|
105
|
+
],
|
|
106
|
+
details: { matchCount: 0, readDenyExcluded },
|
|
107
|
+
};
|
|
108
|
+
}
|
|
68
109
|
const scope = path ? `${searchPath}` : "the workspace";
|
|
69
110
|
const text = walk.truncated
|
|
70
111
|
? `Scan of ${scope} hit the ${MAX_SCAN_ENTRIES.toLocaleString()}-file limit before any path matched "${pattern}". ` +
|
|
@@ -86,7 +127,11 @@ export function createGlobTool(fileStore, options = {}) {
|
|
|
86
127
|
else {
|
|
87
128
|
ordered = matched;
|
|
88
129
|
}
|
|
89
|
-
|
|
130
|
+
// Render each hit as an address `read` can take verbatim: a path relative to
|
|
131
|
+
// `target` alone is ambiguous (read resolves relative paths against projectRoot, not
|
|
132
|
+
// the search root), so emit a projectRoot-relative path when the hit is inside it and
|
|
133
|
+
// an absolute path otherwise.
|
|
134
|
+
const page = ordered.slice(0, GLOB_MAX_RESULTS).map((rel) => toReadableAddress(target, rel, securityContext));
|
|
90
135
|
const footerParts = [];
|
|
91
136
|
if (ordered.length > page.length) {
|
|
92
137
|
footerParts.push(`Showing ${page.length} of ${ordered.length} matches${sortableByMtime ? ", newest first" : ""}. ` +
|
|
@@ -98,6 +143,9 @@ export function createGlobTool(fileStore, options = {}) {
|
|
|
98
143
|
if (walk.truncated) {
|
|
99
144
|
footerParts.push(`Scan stopped after ${MAX_SCAN_ENTRIES.toLocaleString()} files; results may be incomplete. Narrow path to search a smaller subtree.`);
|
|
100
145
|
}
|
|
146
|
+
if (readDenyExcluded > 0) {
|
|
147
|
+
footerParts.push(`${readDenyExcluded} matching path(s) excluded by the read policy.`);
|
|
148
|
+
}
|
|
101
149
|
const body = page.join("\n");
|
|
102
150
|
const truncation = truncateHead(body);
|
|
103
151
|
let outputText = truncation.content;
|
|
@@ -109,7 +157,12 @@ export function createGlobTool(fileStore, options = {}) {
|
|
|
109
157
|
}
|
|
110
158
|
return {
|
|
111
159
|
content: [{ type: "text", text: outputText }],
|
|
112
|
-
details: {
|
|
160
|
+
details: {
|
|
161
|
+
matchCount: ordered.length,
|
|
162
|
+
shownCount: page.length,
|
|
163
|
+
scanTruncated: walk.truncated,
|
|
164
|
+
...(readDenyExcluded > 0 ? { readDenyExcluded } : {}),
|
|
165
|
+
},
|
|
113
166
|
};
|
|
114
167
|
},
|
|
115
168
|
};
|
package/dist/tools/grep.d.ts
CHANGED
|
@@ -6,6 +6,8 @@ declare const grepSchema: Type.TObject<{
|
|
|
6
6
|
pattern: Type.TString;
|
|
7
7
|
path: Type.TOptional<Type.TString>;
|
|
8
8
|
glob: Type.TOptional<Type.TString>;
|
|
9
|
+
literal: Type.TOptional<Type.TBoolean>;
|
|
10
|
+
mode: Type.TOptional<Type.TUnion<[Type.TLiteral<"content">, Type.TLiteral<"files">, Type.TLiteral<"count">]>>;
|
|
9
11
|
caseSensitive: Type.TOptional<Type.TBoolean>;
|
|
10
12
|
skip: Type.TOptional<Type.TInteger>;
|
|
11
13
|
}>;
|
package/dist/tools/grep.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { basename } from "node:path";
|
|
1
2
|
import { Type } from "typebox";
|
|
2
3
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
3
4
|
import { checkPathGuard } from "../security/path-guard-check.js";
|
|
5
|
+
import { partitionByReadGuard, readGuardAllows } from "../security/path-guard-filter.js";
|
|
4
6
|
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
5
7
|
import { shellEscape } from "../shared/shell-escape.js";
|
|
6
8
|
import { IGNORED_DIR_SEGMENTS } from "./ignore-dirs.js";
|
|
@@ -29,21 +31,77 @@ const SEARCH_TIMEOUT_SECONDS = 30;
|
|
|
29
31
|
*/
|
|
30
32
|
const MAX_RAW_RESULT_BYTES = 768 * 1024;
|
|
31
33
|
const grepSchema = Type.Object({
|
|
32
|
-
pattern: Type.String({
|
|
34
|
+
pattern: Type.String({
|
|
35
|
+
description: "Text to search for. An extended regular expression (ERE) unless `literal` is set.",
|
|
36
|
+
}),
|
|
33
37
|
path: Type.Optional(Type.String({ description: "File or directory to search. Defaults to the workspace root." })),
|
|
34
38
|
glob: Type.Optional(Type.String({
|
|
35
|
-
description: 'Filename filter for directory searches, e.g. "*.ts".
|
|
39
|
+
description: 'Filename filter for directory searches, matched against the basename. Supports `*`, `?`, `[abc]`, and `{a,b}` — e.g. "*.{ts,tsx}".',
|
|
40
|
+
})),
|
|
41
|
+
literal: Type.Optional(Type.Boolean({ description: "Treat `pattern` as a literal string, not a regex (like `grep -F`)." })),
|
|
42
|
+
mode: Type.Optional(Type.Union([Type.Literal("content"), Type.Literal("files"), Type.Literal("count")], {
|
|
43
|
+
description: '"content" (default) = matching lines; "files" = matching paths only; "count" = per-file counts. files/count cost far fewer tokens when you only need to locate.',
|
|
36
44
|
})),
|
|
37
45
|
caseSensitive: Type.Optional(Type.Boolean({ description: "Case-sensitive match. Defaults to true." })),
|
|
38
46
|
skip: Type.Optional(Type.Integer({ minimum: 0, description: "File-page offset for paging through many matching files." })),
|
|
39
47
|
});
|
|
40
|
-
/**
|
|
48
|
+
/**
|
|
49
|
+
* Convert a basename glob into an anchored regex. Supports `*`, `?`, character classes `[...]`, and
|
|
50
|
+
* brace alternation `{a,b}` so the JS-side backstop filter is never *stricter* than the `--include`
|
|
51
|
+
* glob pushed to `grep` — a mismatch there produced silent "no results" (fix plan §3.5).
|
|
52
|
+
*/
|
|
41
53
|
function globToRegExp(glob) {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
54
|
+
let out = "";
|
|
55
|
+
for (let i = 0; i < glob.length; i++) {
|
|
56
|
+
const ch = glob[i];
|
|
57
|
+
if (ch === "*") {
|
|
58
|
+
out += ".*";
|
|
59
|
+
}
|
|
60
|
+
else if (ch === "?") {
|
|
61
|
+
out += ".";
|
|
62
|
+
}
|
|
63
|
+
else if (ch === "[") {
|
|
64
|
+
// Copy the class verbatim to the closing `]` (leading `!` -> `^` for negation).
|
|
65
|
+
let j = i + 1;
|
|
66
|
+
let cls = "";
|
|
67
|
+
if (glob[j] === "!" || glob[j] === "^") {
|
|
68
|
+
cls += "^";
|
|
69
|
+
j++;
|
|
70
|
+
}
|
|
71
|
+
while (j < glob.length && glob[j] !== "]") {
|
|
72
|
+
cls += glob[j];
|
|
73
|
+
j++;
|
|
74
|
+
}
|
|
75
|
+
if (j < glob.length) {
|
|
76
|
+
out += `[${cls}]`;
|
|
77
|
+
i = j;
|
|
78
|
+
}
|
|
79
|
+
else {
|
|
80
|
+
out += "\\[";
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
else if (ch === "{") {
|
|
84
|
+
const end = glob.indexOf("}", i);
|
|
85
|
+
if (end > i) {
|
|
86
|
+
const alts = glob
|
|
87
|
+
.slice(i + 1, end)
|
|
88
|
+
.split(",")
|
|
89
|
+
.map((alt) => alt.replace(/[.+^${}()|[\]\\]/g, "\\$&"));
|
|
90
|
+
out += `(?:${alts.join("|")})`;
|
|
91
|
+
i = end;
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
out += "\\{";
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
else if (/[.+^$()|\\]/.test(ch)) {
|
|
98
|
+
out += `\\${ch}`;
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
out += ch;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return new RegExp(`^${out}$`);
|
|
47
105
|
}
|
|
48
106
|
function truncateLine(text) {
|
|
49
107
|
return text.length > LINE_MAX_CHARS ? `${text.slice(0, LINE_MAX_CHARS)}…` : text;
|
|
@@ -136,14 +194,16 @@ export function createGrepTool(executor, options = {}) {
|
|
|
136
194
|
return {
|
|
137
195
|
name: "grep",
|
|
138
196
|
label: "grep",
|
|
139
|
-
description: "Search file contents
|
|
140
|
-
"grouped by file, capped per file, paginated, and token-bounded — prefer this over `bash grep -rn`,
|
|
141
|
-
|
|
197
|
+
description: "Search file contents across a file or directory tree — an ERE regex, or a literal string with `literal:true`. " +
|
|
198
|
+
"Output is grouped by file, capped per file, paginated, and token-bounded — prefer this over `bash grep -rn`, " +
|
|
199
|
+
'which floods context. `mode:"files"` returns just matching paths and `mode:"count"` per-file counts (both ' +
|
|
200
|
+
"much cheaper when you only need to locate). Match lines are marked with `*`, context lines with a space.",
|
|
142
201
|
parameters: grepSchema,
|
|
143
|
-
execute: async (_toolCallId, { pattern, path, glob, caseSensitive, skip, }, signal) => {
|
|
202
|
+
execute: async (_toolCallId, { pattern, path, glob, literal, mode, caseSensitive, skip, }, signal) => {
|
|
144
203
|
if (!pattern.trim()) {
|
|
145
204
|
throw new RecoverableToolError("Pattern must not be empty.");
|
|
146
205
|
}
|
|
206
|
+
const effectiveMode = mode ?? "content";
|
|
147
207
|
const searchPath = path?.trim() || ".";
|
|
148
208
|
// Resolved once, then used for both the guard's judgment and the actual `grep` target
|
|
149
209
|
// (spec 044, D1.1): no separate `cwd` needed on the executor call, so there is no chance of
|
|
@@ -153,7 +213,13 @@ export function createGrepTool(executor, options = {}) {
|
|
|
153
213
|
tool: "grep",
|
|
154
214
|
channelId: options.channelId,
|
|
155
215
|
});
|
|
156
|
-
|
|
216
|
+
// `-rnH` for content; `-rlH` (paths only) for `files`; `-rcH` (per-file counts) for `count`.
|
|
217
|
+
const flags = effectiveMode === "files"
|
|
218
|
+
? ["-rlH"]
|
|
219
|
+
: effectiveMode === "count"
|
|
220
|
+
? ["-rcH"]
|
|
221
|
+
: ["-rnH", `-B${CONTEXT_BEFORE}`, `-A${CONTEXT_AFTER}`];
|
|
222
|
+
flags.push(literal ? "-F" : "-E");
|
|
157
223
|
if (caseSensitive === false) {
|
|
158
224
|
flags.push("-i");
|
|
159
225
|
}
|
|
@@ -165,6 +231,22 @@ export function createGrepTool(executor, options = {}) {
|
|
|
165
231
|
for (const segment of IGNORED_DIR_SEGMENTS) {
|
|
166
232
|
flags.push(`--exclude-dir=${segment}`);
|
|
167
233
|
}
|
|
234
|
+
// Push `readDeny` down into `grep` so a denied subtree is never opened (D5.1). `grep`'s
|
|
235
|
+
// `--exclude`/`--exclude-dir` match a *basename* glob, so a plain (non-glob) deny entry
|
|
236
|
+
// becomes a basename exclude — coarser than the path guard (it also skips a same-named
|
|
237
|
+
// dir elsewhere), but only ever *more* restrictive, and the post-parse read-guard filter
|
|
238
|
+
// below is the actual guarantee that no denied content is returned.
|
|
239
|
+
const denyBasenames = new Set();
|
|
240
|
+
for (const entry of securityConfig.pathGuard.readDeny) {
|
|
241
|
+
if (!/[*?[\]{}]/.test(entry)) {
|
|
242
|
+
const base = basename(entry.replace(/\/+$/, ""));
|
|
243
|
+
if (base && base !== "." && base !== "..")
|
|
244
|
+
denyBasenames.add(base);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
for (const base of denyBasenames) {
|
|
248
|
+
flags.push(`--exclude-dir=${shellEscape(base)}`, `--exclude=${shellEscape(base)}`);
|
|
249
|
+
}
|
|
168
250
|
if (glob) {
|
|
169
251
|
// Model-controlled, so it must be shell-escaped like the pattern and path below -- the
|
|
170
252
|
// executor runs the command via `sh -c`, and an unescaped glob such as `*.ts; rm -rf x`
|
|
@@ -184,13 +266,75 @@ export function createGrepTool(executor, options = {}) {
|
|
|
184
266
|
// grep exit code 1 = no matches (normal), 0 = matches, >=2 = error.
|
|
185
267
|
if (result.code >= 2) {
|
|
186
268
|
const stderr = result.stderr.trim();
|
|
187
|
-
throw new RecoverableToolError(`grep failed: ${stderr || `exit code ${result.code}`}.
|
|
269
|
+
throw new RecoverableToolError(`grep failed: ${stderr || `exit code ${result.code}`}. ${literal
|
|
270
|
+
? "Check that the path exists."
|
|
271
|
+
: "Check the regex (ERE syntax) and that the path exists, or pass literal:true."}`);
|
|
188
272
|
}
|
|
189
273
|
const rawTruncated = result.stdoutTruncated === true;
|
|
190
274
|
// A truncated capture may end mid-line; drop that dangling partial line rather than feed
|
|
191
275
|
// it to the parser, which expects each line to be a complete match or context line.
|
|
192
276
|
const boundedStdout = rawTruncated ? result.stdout.slice(0, result.stdout.lastIndexOf("\n")) : result.stdout;
|
|
193
277
|
const globRegExp = glob ? globToRegExp(glob) : undefined;
|
|
278
|
+
const keepFile = (file) => {
|
|
279
|
+
const normalized = file.replace(/^\.\//, "");
|
|
280
|
+
if (isIgnoredPath(normalized))
|
|
281
|
+
return false;
|
|
282
|
+
if (globRegExp) {
|
|
283
|
+
const base = normalized.split("/").pop() ?? normalized;
|
|
284
|
+
if (!globRegExp.test(base))
|
|
285
|
+
return false;
|
|
286
|
+
}
|
|
287
|
+
return readGuardAllows(normalized, securityConfig, securityContext);
|
|
288
|
+
};
|
|
289
|
+
const truncationFooter = rawTruncated
|
|
290
|
+
? `\n\n[Search hit the ${formatSize(MAX_RAW_RESULT_BYTES)} raw result cap; narrow the path or pattern to see the rest.]`
|
|
291
|
+
: "";
|
|
292
|
+
// `mode: "files"` — just the paths that matched, one per line.
|
|
293
|
+
if (effectiveMode === "files") {
|
|
294
|
+
const paths = [
|
|
295
|
+
...new Set(boundedStdout
|
|
296
|
+
.split("\n")
|
|
297
|
+
.map((l) => l.trim())
|
|
298
|
+
.filter(Boolean)),
|
|
299
|
+
]
|
|
300
|
+
.filter(keepFile)
|
|
301
|
+
.sort((a, b) => a.localeCompare(b));
|
|
302
|
+
if (paths.length === 0) {
|
|
303
|
+
return {
|
|
304
|
+
content: [{ type: "text", text: `No files contain a match in ${searchPath}.${truncationFooter}` }],
|
|
305
|
+
details: { matchCount: 0, fileCount: 0 },
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
return {
|
|
309
|
+
content: [{ type: "text", text: truncateHead(paths.join("\n")).content + truncationFooter }],
|
|
310
|
+
details: { fileCount: paths.length, mode: "files" },
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
// `mode: "count"` — `path:N` per file that matched.
|
|
314
|
+
if (effectiveMode === "count") {
|
|
315
|
+
const rows = [];
|
|
316
|
+
for (const line of boundedStdout.split("\n")) {
|
|
317
|
+
const m = line.match(/^(.*):(\d+)$/);
|
|
318
|
+
if (!m)
|
|
319
|
+
continue;
|
|
320
|
+
const count = Number.parseInt(m[2], 10);
|
|
321
|
+
if (count > 0 && keepFile(m[1]))
|
|
322
|
+
rows.push([m[1].replace(/^\.\//, ""), count]);
|
|
323
|
+
}
|
|
324
|
+
rows.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
|
|
325
|
+
if (rows.length === 0) {
|
|
326
|
+
return {
|
|
327
|
+
content: [{ type: "text", text: `No matches in ${searchPath}.${truncationFooter}` }],
|
|
328
|
+
details: { matchCount: 0, fileCount: 0 },
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
const total = rows.reduce((sum, [, n]) => sum + n, 0);
|
|
332
|
+
const body = rows.map(([f, n]) => `${n}\t${f}`).join("\n");
|
|
333
|
+
return {
|
|
334
|
+
content: [{ type: "text", text: truncateHead(body).content + truncationFooter }],
|
|
335
|
+
details: { matchCount: total, fileCount: rows.length, mode: "count" },
|
|
336
|
+
};
|
|
337
|
+
}
|
|
194
338
|
const parsed = parseGrepOutput(boundedStdout);
|
|
195
339
|
// Filter ignored dirs and (for directory scopes) the optional glob, on the basename.
|
|
196
340
|
const files = [];
|
|
@@ -207,7 +351,32 @@ export function createGrepTool(executor, options = {}) {
|
|
|
207
351
|
}
|
|
208
352
|
files.push([normalized, entries]);
|
|
209
353
|
}
|
|
354
|
+
// Backstop: a recursive `grep` descends into `readDeny`/sensitive subtrees the per-path
|
|
355
|
+
// guard would refuse. Drop any hit file the read guard denies before it is rendered or
|
|
356
|
+
// counted (the residual risk — grep already read the bytes — is documented in
|
|
357
|
+
// path-guard-filter.ts).
|
|
358
|
+
let readDenyExcluded = 0;
|
|
359
|
+
if (files.length > 0) {
|
|
360
|
+
const { allowed } = partitionByReadGuard(files.map(([file]) => file), securityConfig, securityContext);
|
|
361
|
+
const allowedSet = new Set(allowed);
|
|
362
|
+
const kept = files.filter(([file]) => allowedSet.has(file));
|
|
363
|
+
readDenyExcluded = files.length - kept.length;
|
|
364
|
+
files.length = 0;
|
|
365
|
+
files.push(...kept);
|
|
366
|
+
}
|
|
210
367
|
if (files.length === 0) {
|
|
368
|
+
if (readDenyExcluded > 0) {
|
|
369
|
+
return {
|
|
370
|
+
content: [
|
|
371
|
+
{
|
|
372
|
+
type: "text",
|
|
373
|
+
text: `All ${readDenyExcluded} matching file(s) in ${searchPath} are excluded by the read policy. ` +
|
|
374
|
+
"Search a path you are allowed to read.",
|
|
375
|
+
},
|
|
376
|
+
],
|
|
377
|
+
details: { matchCount: 0, fileCount: 0, readDenyExcluded },
|
|
378
|
+
};
|
|
379
|
+
}
|
|
211
380
|
const scope = glob ? `${searchPath} (glob ${glob})` : searchPath;
|
|
212
381
|
// D5.3: a result set that hit the raw-line cap but still filtered down to nothing must
|
|
213
382
|
// not be reported as "no matches" -- that tells the model to try a *broader* search,
|
|
@@ -258,6 +427,9 @@ export function createGrepTool(executor, options = {}) {
|
|
|
258
427
|
if (rawTruncated) {
|
|
259
428
|
footerLines.push(`[Search hit the ${formatSize(MAX_RAW_RESULT_BYTES)} raw result cap; there may be matches beyond what's shown above. Narrow the path or pattern to see them.]`);
|
|
260
429
|
}
|
|
430
|
+
if (readDenyExcluded > 0) {
|
|
431
|
+
footerLines.push(`[${readDenyExcluded} matching file(s) were excluded by the read policy and are not shown.]`);
|
|
432
|
+
}
|
|
261
433
|
const body = blocks.join("\n\n");
|
|
262
434
|
const footer = footerLines.length > 0 ? `\n\n${footerLines.join("\n")}` : "";
|
|
263
435
|
const truncation = truncateHead(body);
|
|
@@ -271,6 +443,7 @@ export function createGrepTool(executor, options = {}) {
|
|
|
271
443
|
matchCount: shownMatchCount,
|
|
272
444
|
fileCount: files.length,
|
|
273
445
|
shownFileCount: page.length,
|
|
446
|
+
...(readDenyExcluded > 0 ? { readDenyExcluded } : {}),
|
|
274
447
|
},
|
|
275
448
|
};
|
|
276
449
|
},
|
package/dist/tools/job.js
CHANGED
|
@@ -7,9 +7,12 @@ const jobSchema = Type.Object({
|
|
|
7
7
|
description: '"list" a snapshot of background jobs, "poll" to wait (briefly) for one to finish, or "cancel" jobs by id.',
|
|
8
8
|
}),
|
|
9
9
|
ids: Type.Optional(Type.Array(Type.String(), {
|
|
10
|
-
description: "Job ids for poll/cancel. For poll, omit to watch
|
|
10
|
+
description: "Job ids for poll/cancel. For poll, omit to watch every job running when the call starts " +
|
|
11
|
+
"(a job started later is not folded into that same poll).",
|
|
11
12
|
})),
|
|
12
13
|
});
|
|
14
|
+
/** Total bytes of job output `op=poll` inlines across all finished jobs in one call. */
|
|
15
|
+
const COMPLETED_DETAIL_TOTAL_BUDGET = 96 * 1024;
|
|
13
16
|
function formatJobLine(job) {
|
|
14
17
|
const exit = job.exitCode !== undefined ? `, exit ${job.exitCode}` : "";
|
|
15
18
|
return `- [${job.id}] ${job.label} — ${job.status} (${formatDuration(job.durationMs)}${exit})`;
|
|
@@ -18,12 +21,21 @@ export function createJobTool(options) {
|
|
|
18
21
|
const { jobManager } = options;
|
|
19
22
|
async function completedDetail(jobs) {
|
|
20
23
|
const sections = [];
|
|
24
|
+
let spent = 0;
|
|
21
25
|
for (const job of jobs) {
|
|
26
|
+
const header = `### [${job.id}] ${job.label} — ${job.status}${job.exitCode !== undefined ? `, exit ${job.exitCode}` : ""}`;
|
|
22
27
|
const output = await jobManager.readOutput(job.id);
|
|
28
|
+
// Total budget across all finished jobs in one poll: 5 jobs × the 50KB per-job tail would
|
|
29
|
+
// otherwise be 250KB of context. Once spent, later jobs get a header + a pointer only.
|
|
30
|
+
if (spent >= COMPLETED_DETAIL_TOTAL_BUDGET) {
|
|
31
|
+
sections.push(`${header}\n(output omitted to stay within budget — run \`job op=poll ids=["${job.id}"]\` for it)${output ? `\nFull output: ${output.spillFile}` : ""}`);
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
23
34
|
const tail = output ? truncateTail(output.text).content : "";
|
|
24
35
|
const body = tail.trim() ? tail : "(no output)";
|
|
25
36
|
const path = output ? `\nFull output: ${output.spillFile}` : "";
|
|
26
|
-
|
|
37
|
+
spent += Buffer.byteLength(body, "utf-8");
|
|
38
|
+
sections.push(`${header}\n${body}${path}`);
|
|
27
39
|
}
|
|
28
40
|
return sections;
|
|
29
41
|
}
|
|
@@ -32,7 +44,7 @@ export function createJobTool(options) {
|
|
|
32
44
|
label: "job",
|
|
33
45
|
description: "Inspect and control background bash jobs (started with bash async:true). op=list shows a snapshot; " +
|
|
34
46
|
"op=poll waits briefly for a running job to finish and returns its output; op=cancel stops jobs by id. " +
|
|
35
|
-
"
|
|
47
|
+
"Completion wakes this channel; finish independent work, then end the turn when only waiting remains.",
|
|
36
48
|
parameters: jobSchema,
|
|
37
49
|
execute: async (_toolCallId, { op, ids }, signal) => {
|
|
38
50
|
if (op === "cancel") {
|
|
@@ -75,7 +87,7 @@ export function createJobTool(options) {
|
|
|
75
87
|
}
|
|
76
88
|
if (running.length > 0) {
|
|
77
89
|
parts.push(`## Still running (${running.length})`, ...running.map(formatJobLine));
|
|
78
|
-
parts.push("
|
|
90
|
+
parts.push("Finish independent work, then end the turn; completion wakes this channel. Do not loop on poll.");
|
|
79
91
|
}
|
|
80
92
|
return {
|
|
81
93
|
content: [{ type: "text", text: parts.join("\n\n") }],
|