@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
|
@@ -3,6 +3,7 @@ import { join } from "node:path";
|
|
|
3
3
|
import { Type } from "typebox";
|
|
4
4
|
import * as log from "../log.js";
|
|
5
5
|
import { getDefaultChannelMemoryQueue } from "../memory/channel-maintenance-queue.js";
|
|
6
|
+
import { readJournalForSearch } from "../memory/journal.js";
|
|
6
7
|
import { appendMemoryReviewLog } from "../memory/review-log.js";
|
|
7
8
|
import { findNearDuplicateEntries, searchMemory } from "../memory/search.js";
|
|
8
9
|
import { containsSecret } from "../memory/secret-redaction.js";
|
|
@@ -32,7 +33,7 @@ const memorySaveSchema = Type.Object({
|
|
|
32
33
|
});
|
|
33
34
|
const memorySearchSchema = Type.Object({
|
|
34
35
|
query: Type.String({
|
|
35
|
-
description: "What to look for across this channel's memory, journal, and workspace MEMORY.md.",
|
|
36
|
+
description: "What to look for across this channel's memory, recent journal files, and workspace MEMORY.md.",
|
|
36
37
|
}),
|
|
37
38
|
});
|
|
38
39
|
const memoryForgetSchema = Type.Object({
|
|
@@ -64,73 +65,111 @@ function buildMemoryClosures(options) {
|
|
|
64
65
|
if (args.name && !isValidMemoryName(args.name)) {
|
|
65
66
|
throw new RecoverableToolError(`"${args.name}" is not a valid memory name. Use lowercase letters, digits, and hyphens only (e.g. deploy-window-thursday).`);
|
|
66
67
|
}
|
|
67
|
-
const entries = await listMemoryEntries(options.channelDir);
|
|
68
|
-
if (!args.replaces) {
|
|
69
|
-
const similar = findNearDuplicateEntries(content, entries);
|
|
70
|
-
if (similar.length > 0) {
|
|
71
|
-
throw new RecoverableToolError(`Nothing was saved yet. This channel already stores ${similar.length} similar entr${similar.length === 1 ? "y" : "ies"}:\n` +
|
|
72
|
-
similar.map((entry) => `- ${entry.name}: ${entry.description}`).join("\n") +
|
|
73
|
-
'\nRe-issue the save with "replaces" set to the name this replaces, or to "none" if both facts are true at once.');
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
68
|
const replaces = args.replaces && args.replaces !== "none" ? args.replaces : undefined;
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
69
|
+
// The near-duplicate judgment ("read existing facts → decide → write") has to run inside the
|
|
70
|
+
// same per-channel critical section as the write, or two concurrent saves of the same fact
|
|
71
|
+
// each see "no duplicate" and both add it. A `null` return means "blocked by near-duplicates,
|
|
72
|
+
// nothing written".
|
|
73
|
+
let similar = [];
|
|
74
|
+
const result = await queue.run(options.channelId, async () => {
|
|
75
|
+
// `replaces: "none"` is an explicit "both facts are true, keep both" waiver, so it skips
|
|
76
|
+
// the near-duplicate gate just like naming a real target does.
|
|
77
|
+
if (!args.replaces) {
|
|
78
|
+
const existing = await listMemoryEntries(options.channelDir);
|
|
79
|
+
const near = findNearDuplicateEntries(content, existing);
|
|
80
|
+
if (near.length > 0) {
|
|
81
|
+
similar = near;
|
|
82
|
+
return null;
|
|
86
83
|
}
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
84
|
+
}
|
|
85
|
+
return applyMemoryOps(options.channelDir, [
|
|
86
|
+
replaces
|
|
87
|
+
? {
|
|
88
|
+
op: "update",
|
|
89
|
+
name: replaces,
|
|
90
|
+
description: content,
|
|
91
|
+
type: args.type,
|
|
92
|
+
details: args.details,
|
|
93
|
+
expires: null,
|
|
94
|
+
}
|
|
95
|
+
: {
|
|
96
|
+
op: "add",
|
|
97
|
+
description: content,
|
|
98
|
+
source: "user",
|
|
99
|
+
name: args.name,
|
|
100
|
+
type: args.type ?? "project",
|
|
101
|
+
details: args.details,
|
|
102
|
+
},
|
|
103
|
+
]);
|
|
104
|
+
});
|
|
105
|
+
if (result === null) {
|
|
106
|
+
throw new RecoverableToolError(`Nothing was saved yet. This channel already stores ${similar.length} similar entr${similar.length === 1 ? "y" : "ies"}:\n` +
|
|
107
|
+
similar.map((entry) => `- ${entry.name}: ${entry.description}`).join("\n") +
|
|
108
|
+
'\nRe-issue the save with "replaces" set to the name this replaces, or to "none" if both facts are true at once.');
|
|
109
|
+
}
|
|
96
110
|
if (replaces && result.updated.length === 0 && result.missingTarget > 0) {
|
|
97
111
|
throw new RecoverableToolError(`No memory named "${replaces}" exists in this channel. Check the name, or omit "replaces" to save a new entry.`);
|
|
98
112
|
}
|
|
99
|
-
|
|
113
|
+
// Report what actually landed on disk — never a name for an entry that was not written.
|
|
114
|
+
// The old code read `replaces ?? result.added[0]` unconditionally, so a skipped add
|
|
115
|
+
// rendered "Saved ... as `undefined`." and told the user a lie the model could not see.
|
|
116
|
+
if (replaces) {
|
|
117
|
+
await logMemorySave(options, replaces, "update");
|
|
118
|
+
return textResult(`Replaced channel memory \`${replaces}\`.`, { saved: true, name: replaces });
|
|
119
|
+
}
|
|
120
|
+
const addedName = result.added[0];
|
|
121
|
+
if (addedName) {
|
|
122
|
+
await logMemorySave(options, addedName, "add");
|
|
123
|
+
return textResult(`Saved to channel memory as \`${addedName}\`.`, { saved: true, name: addedName });
|
|
124
|
+
}
|
|
125
|
+
if (result.skippedSecret > 0) {
|
|
126
|
+
return textResult("Not saved: the content still reads as a credential or secret after the first check. Store the secret itself in an approved secret manager and save only a pointer to it here.", { saved: false, blockedReason: "secret" });
|
|
127
|
+
}
|
|
128
|
+
if (result.skippedTombstone > 0) {
|
|
129
|
+
return textResult(`Not saved: "${content}" was explicitly forgotten in this channel and is still tombstoned. ` +
|
|
130
|
+
"Confirm with the user that they want it back, then re-save (an explicit user save is allowed through), or reword it so it is not byte-for-byte the forgotten fact.", { saved: false, blockedReason: "tombstone" });
|
|
131
|
+
}
|
|
132
|
+
return textResult("Not saved, and the store reported no specific reason (it may already be stored under another entry). " +
|
|
133
|
+
"Run memory_search for this fact before trying again.", { saved: false, blockedReason: "unknown" });
|
|
134
|
+
}
|
|
135
|
+
async function logMemorySave(opts, name, op) {
|
|
136
|
+
await appendMemoryReviewLog(opts.channelDir, {
|
|
100
137
|
timestamp: new Date().toISOString(),
|
|
101
|
-
channelId:
|
|
138
|
+
channelId: opts.channelId,
|
|
102
139
|
reason: "memory-save",
|
|
103
|
-
actions: [{ op
|
|
140
|
+
actions: [{ op, name }],
|
|
104
141
|
}).catch(() => { });
|
|
105
|
-
const savedName = replaces ?? result.added[0];
|
|
106
|
-
return textResult(replaces ? `Replaced channel memory \`${savedName}\`.` : `Saved to channel memory as \`${savedName}\`.`, { saved: result.added.length > 0 || result.updated.length > 0, name: savedName });
|
|
107
142
|
}
|
|
108
143
|
async function search({ query }) {
|
|
109
144
|
const trimmed = query.trim();
|
|
110
145
|
if (!trimmed) {
|
|
111
146
|
throw new RecoverableToolError("memory_search requires a non-empty query.");
|
|
112
147
|
}
|
|
113
|
-
const [entries, workspaceMemory] = await Promise.all([
|
|
148
|
+
const [entries, workspaceMemory, journal] = await Promise.all([
|
|
114
149
|
listMemoryEntries(options.channelDir),
|
|
115
150
|
readWorkspaceMemory(options.workspaceDir),
|
|
151
|
+
readJournalForSearch(options.channelDir),
|
|
116
152
|
]);
|
|
117
|
-
const hits = searchMemory({ query: trimmed, entries, workspaceMemory });
|
|
153
|
+
const hits = searchMemory({ query: trimmed, entries, workspaceMemory, journal: journal.days });
|
|
154
|
+
const scopeHint = journal.omittedDays > 0 || journal.truncatedDates.length > 0
|
|
155
|
+
? `\nJournal search omitted ${journal.omittedDays} older day files and older text in ${journal.truncatedDates.length} large files. Use grep in ${join(options.channelDir, "journal")} or read a dated file to search the omitted history.`
|
|
156
|
+
: "";
|
|
118
157
|
if (hits.length === 0) {
|
|
119
|
-
return textResult(`No stored memory matched "${trimmed}". Try a broader query
|
|
158
|
+
return textResult(`No stored memory matched "${trimmed}". Try a broader query; no match does not prove the fact was never recorded.${scopeHint}`, {
|
|
120
159
|
resultCount: 0,
|
|
121
160
|
});
|
|
122
161
|
}
|
|
123
162
|
const rendered = hits
|
|
124
163
|
.map((hit) => {
|
|
125
164
|
const where = hit.kind === "memory"
|
|
126
|
-
? `memory/${hit.label}`
|
|
165
|
+
? `memory/${hit.label}.md`
|
|
127
166
|
: hit.kind === "journal"
|
|
128
|
-
? `journal
|
|
167
|
+
? `journal/${hit.date}.md`
|
|
129
168
|
: `workspace MEMORY.md › ${hit.label}`;
|
|
130
169
|
return `- [${where}] ${hit.line}`;
|
|
131
170
|
})
|
|
132
171
|
.join("\n");
|
|
133
|
-
return textResult(`Found ${hits.length} match${hits.length === 1 ? "" : "es"}:\n\n${rendered}
|
|
172
|
+
return textResult(`Found ${hits.length} match${hits.length === 1 ? "" : "es"}:\n\n${rendered}${scopeHint}\nResults are excerpts. Read a cited file for full context; narrow the query for more specific matches.`, {
|
|
134
173
|
resultCount: hits.length,
|
|
135
174
|
});
|
|
136
175
|
}
|
|
@@ -164,7 +203,7 @@ export function createMemorySaveTool(options) {
|
|
|
164
203
|
name: "memory_save",
|
|
165
204
|
label: "memory_save",
|
|
166
205
|
description: "Save a durable fact into this channel's memory when the user asks you to remember it. Not for transient task state — " +
|
|
167
|
-
"
|
|
206
|
+
"keep in-progress work in a task (task_log) instead; the journal is written only by the background reflect pass.",
|
|
168
207
|
parameters: memorySaveSchema,
|
|
169
208
|
execute: async (_toolCallId, args) => save(args),
|
|
170
209
|
};
|
|
@@ -174,7 +213,7 @@ export function createMemorySearchTool(options) {
|
|
|
174
213
|
return {
|
|
175
214
|
name: "memory_search",
|
|
176
215
|
label: "memory_search",
|
|
177
|
-
description: "Search this channel's stored memory, journal, and the workspace MEMORY.md on demand. The memory index is only " +
|
|
216
|
+
description: "Search this channel's stored memory, recent journal, and the workspace MEMORY.md on demand. The memory index is only " +
|
|
178
217
|
"injected at the start of a session, so use this when you suspect something was recorded since.",
|
|
179
218
|
parameters: memorySearchSchema,
|
|
180
219
|
execute: async (_toolCallId, args) => search(args),
|
package/dist/tools/read.js
CHANGED
|
@@ -26,6 +26,8 @@ function isImageFile(filePath) {
|
|
|
26
26
|
/** Directory tree caps, mirroring oh-my-pi's read: shallow and per-directory bounded. */
|
|
27
27
|
const DIR_MAX_DEPTH = 2;
|
|
28
28
|
const DIR_PER_DIR_LIMIT = 12;
|
|
29
|
+
/** Source cap on entries `listDirectory` collects before we ever start rendering (fix plan §2.4). */
|
|
30
|
+
const DIR_MAX_ENTRIES = 4_000;
|
|
29
31
|
/**
|
|
30
32
|
* Render a depth-2 directory tree from `FileStore.listDirectory` entries. Kept deliberately
|
|
31
33
|
* portable — no sizes or mtimes, since formats differ across platforms; the structure is the value.
|
|
@@ -39,23 +41,41 @@ function renderDirectoryTree(entries) {
|
|
|
39
41
|
const perParentCount = new Map();
|
|
40
42
|
const lines = [];
|
|
41
43
|
const elided = new Map();
|
|
44
|
+
// Parents whose own line was omitted (over the per-dir cap). Their descendants must be skipped
|
|
45
|
+
// too — otherwise the tree shows children of a directory it never listed.
|
|
46
|
+
const elidedParents = new Set();
|
|
42
47
|
for (const entry of sorted) {
|
|
43
48
|
const segments = entry.relativePath.split("/");
|
|
44
49
|
const depth = segments.length - 1;
|
|
45
50
|
const parent = depth === 0 ? "" : segments.slice(0, -1).join("/");
|
|
51
|
+
if (isUnderElidedParent(parent, elidedParents)) {
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
46
54
|
const count = (perParentCount.get(parent) ?? 0) + 1;
|
|
47
55
|
perParentCount.set(parent, count);
|
|
48
56
|
if (count > DIR_PER_DIR_LIMIT) {
|
|
49
57
|
elided.set(parent, (elided.get(parent) ?? 0) + 1);
|
|
58
|
+
if (entry.isDirectory) {
|
|
59
|
+
elidedParents.add(entry.relativePath);
|
|
60
|
+
}
|
|
50
61
|
continue;
|
|
51
62
|
}
|
|
52
63
|
lines.push(`${" ".repeat(depth)}${entry.name}${entry.isDirectory ? "/" : ""}`);
|
|
53
64
|
}
|
|
54
|
-
for (const [, count] of elided) {
|
|
55
|
-
|
|
65
|
+
for (const [parent, count] of elided) {
|
|
66
|
+
const indent = parent === "" ? "" : " ".repeat(parent.split("/").length);
|
|
67
|
+
lines.push(`${indent} [+${count} more]`);
|
|
56
68
|
}
|
|
57
69
|
return lines.join("\n");
|
|
58
70
|
}
|
|
71
|
+
function isUnderElidedParent(parent, elidedParents) {
|
|
72
|
+
for (const elided of elidedParents) {
|
|
73
|
+
if (parent === elided || parent.startsWith(`${elided}/`)) {
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
59
79
|
const readSchema = Type.Object({
|
|
60
80
|
path: Type.String({ description: "Path to the file to read (relative or absolute)" }),
|
|
61
81
|
offset: Type.Optional(Type.Integer({ minimum: 1, description: "Line number to start reading from (1-indexed)" })),
|
|
@@ -77,7 +97,7 @@ export function createReadTool(executor, fileStore, options = {}) {
|
|
|
77
97
|
return {
|
|
78
98
|
name: "read",
|
|
79
99
|
label: "read",
|
|
80
|
-
description: `Read
|
|
100
|
+
description: `Read a file, a PDF (converted to text), or a directory (rendered as a shallow tree). Also reads images (jpg, png, gif, webp), returned as attachments. Text/PDF output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first); use offset/limit to page a large file. A directory tree is depth-2, capped per directory, and points you to subdirectories for the rest.`,
|
|
81
101
|
parameters: readSchema,
|
|
82
102
|
execute: async (_toolCallId, { path, offset, limit }, signal) => {
|
|
83
103
|
const target = await checkPathGuard(path, "read", securityConfig, securityContext, {
|
|
@@ -121,15 +141,32 @@ export function createReadTool(executor, fileStore, options = {}) {
|
|
|
121
141
|
`The file may be scanned/image-based — ask the user for a text version or a screenshot.`);
|
|
122
142
|
}
|
|
123
143
|
pdfText = converted.stdout;
|
|
144
|
+
if (converted.stdoutTruncated) {
|
|
145
|
+
// The 10MB capture cap hit mid-conversion — the rest of the PDF's text is gone.
|
|
146
|
+
// Say so rather than presenting a partial extraction as the whole document.
|
|
147
|
+
pdfText += `\n\n[pdftotext output exceeded the command capture limit and was cut off here; this is not the complete document. Ask the user for a text version to read the rest.]`;
|
|
148
|
+
}
|
|
124
149
|
}
|
|
125
150
|
const stat = isPdf ? undefined : await fileStore.stat(target);
|
|
126
151
|
if (!isPdf && !stat) {
|
|
127
152
|
throw new RecoverableToolError(`Failed to read file: ${path}. Check the path — try \`read\` on its parent directory to confirm it exists.`);
|
|
128
153
|
}
|
|
129
154
|
if (stat?.isDirectory) {
|
|
130
|
-
const entries = await fileStore.listDirectory(target, {
|
|
155
|
+
const entries = await fileStore.listDirectory(target, {
|
|
156
|
+
maxDepth: DIR_MAX_DEPTH,
|
|
157
|
+
maxEntries: DIR_MAX_ENTRIES,
|
|
158
|
+
});
|
|
159
|
+
const tree = renderDirectoryTree(entries);
|
|
160
|
+
const clamped = truncateHead(tree);
|
|
161
|
+
let text = `Directory: ${path}\n\n${clamped.content}`;
|
|
162
|
+
if (entries.length >= DIR_MAX_ENTRIES) {
|
|
163
|
+
text += `\n\n[Listing stopped at ${DIR_MAX_ENTRIES} entries; this directory is large. read a specific subdirectory to see the rest.]`;
|
|
164
|
+
}
|
|
165
|
+
else if (clamped.truncated) {
|
|
166
|
+
text += `\n\n[Tree truncated at ${DEFAULT_MAX_BYTES / 1024}KB; read a specific subdirectory to see the rest.]`;
|
|
167
|
+
}
|
|
131
168
|
return {
|
|
132
|
-
content: [{ type: "text", text
|
|
169
|
+
content: [{ type: "text", text }],
|
|
133
170
|
details: undefined,
|
|
134
171
|
};
|
|
135
172
|
}
|
package/dist/tools/registry.d.ts
CHANGED
|
@@ -34,6 +34,12 @@ export interface ToolBuildContext {
|
|
|
34
34
|
bashDefaultTimeoutSeconds?: number;
|
|
35
35
|
/** Gates the bash tool's rtk command optimizer (`tools.rtk.enabled`). Threaded to both sets. */
|
|
36
36
|
rtkEnabled?: boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Set by `buildToolSet` from `BuildToolSetOptions.forSubagent`. A sub-agent's `securityContext`
|
|
39
|
+
* has no `channelDir` and may be project-bounded, so tools that would otherwise write into the
|
|
40
|
+
* channel directory (bash/job output spill) must fall back to a neutral location for it.
|
|
41
|
+
*/
|
|
42
|
+
forSubagent?: boolean;
|
|
37
43
|
/**
|
|
38
44
|
* Present only on the main path. Enables bash `async` and the `job` tool.
|
|
39
45
|
* The sub-agent set never supplies it, so sub-agents get neither.
|
package/dist/tools/registry.js
CHANGED
|
@@ -56,6 +56,9 @@ export const TOOL_REGISTRY = [
|
|
|
56
56
|
...fileToolOptions(ctx),
|
|
57
57
|
rtkEnabled: ctx.rtkEnabled === true,
|
|
58
58
|
interceptorEnabled: ctx.toolsConfig?.tools.bashInterceptor.enabled === true,
|
|
59
|
+
// Sub-agents get no channel dir (their guard context has none); their spill stays in tmpdir.
|
|
60
|
+
...(ctx.forSubagent ? {} : { channelDir: ctx.channelDir }),
|
|
61
|
+
...(ctx.taskLoop ? { boundTaskId: ctx.taskLoop.taskId } : {}),
|
|
59
62
|
...(ctx.jobManager ? { jobManager: ctx.jobManager } : {}),
|
|
60
63
|
...(ctx.bashDefaultTimeoutSeconds !== undefined
|
|
61
64
|
? { defaultTimeoutSeconds: ctx.bashDefaultTimeoutSeconds }
|
|
@@ -275,7 +278,7 @@ export function buildToolSet(ctx, options = {}) {
|
|
|
275
278
|
if (registration.enabledBy && !registration.enabledBy(ctx)) {
|
|
276
279
|
continue;
|
|
277
280
|
}
|
|
278
|
-
result.push(withToolDetails(registration.create(ctx), registration.name));
|
|
281
|
+
result.push(withToolDetails(registration.create({ ...ctx, forSubagent: options.forSubagent }), registration.name));
|
|
279
282
|
}
|
|
280
283
|
return result;
|
|
281
284
|
}
|
package/dist/tools/send-media.js
CHANGED
|
@@ -7,7 +7,7 @@ import { formatSize, MAX_INLINE_BINARY_BYTES } from "./truncate.js";
|
|
|
7
7
|
/** Extensions delivered as inline images; everything else goes as a file attachment. */
|
|
8
8
|
const IMAGE_EXTENSIONS = new Set([".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"]);
|
|
9
9
|
const sendMediaSchema = Type.Object({
|
|
10
|
-
path: Type.String({ description: "
|
|
10
|
+
path: Type.String({ description: "Local file path (relative to the current project root, or absolute)" }),
|
|
11
11
|
fileName: Type.Optional(Type.String({ description: "Display name for the recipient; defaults to the file's own name" })),
|
|
12
12
|
});
|
|
13
13
|
/**
|
|
@@ -36,18 +36,20 @@ export function createSendMediaTool(fileStore, options) {
|
|
|
36
36
|
});
|
|
37
37
|
const stat = await fileStore.stat(target);
|
|
38
38
|
if (!stat || !stat.isFile) {
|
|
39
|
-
throw new RecoverableToolError(`Cannot send ${path}: not a regular file
|
|
39
|
+
throw new RecoverableToolError(`Cannot send ${path}: not a regular file. Locate the generated file and retry with its path.`);
|
|
40
40
|
}
|
|
41
41
|
if (stat.size > MAX_INLINE_BINARY_BYTES) {
|
|
42
42
|
throw new RecoverableToolError(`Cannot send ${path}: it is ${formatSize(stat.size)}, over the ${formatSize(MAX_INLINE_BINARY_BYTES)} send limit. ` +
|
|
43
43
|
"Compress it first, or provide the path so the user can be told where to find it.");
|
|
44
44
|
}
|
|
45
45
|
if (stat.size === 0) {
|
|
46
|
-
throw new RecoverableToolError(`Cannot send ${path}: the file is empty.`);
|
|
46
|
+
throw new RecoverableToolError(`Cannot send ${path}: the file is empty. Generate the content before sending it.`);
|
|
47
47
|
}
|
|
48
48
|
const { data } = await fileStore.readBytes(target, { signal });
|
|
49
49
|
const name = fileName?.trim() || basename(path);
|
|
50
|
-
|
|
50
|
+
// Route by the *real file's* extension, not the display name: `fileName` is only a label,
|
|
51
|
+
// so a PNG sent with fileName "报告" must still be delivered as an image (fix plan §4).
|
|
52
|
+
const kind = IMAGE_EXTENSIONS.has(extname(path).toLowerCase()) ? "image" : "file";
|
|
51
53
|
const result = await options.mediaSender.sendMedia(options.channelId, { data, fileName: name, kind });
|
|
52
54
|
if (!result.ok) {
|
|
53
55
|
throw new Error(result.error ?? "Failed to send the file to the channel.");
|
|
@@ -42,8 +42,11 @@ export function createSessionSearchTool(options) {
|
|
|
42
42
|
model,
|
|
43
43
|
resolveApiKey: options.resolveApiKey,
|
|
44
44
|
});
|
|
45
|
+
const partialNote = response.partialDocuments > 0
|
|
46
|
+
? ` ${response.partialDocuments} scanned message(s) were themselves clipped at the scan cap, so a keyword past that point would not be found — this is not proof it was never said.`
|
|
47
|
+
: "";
|
|
45
48
|
const text = response.results.length === 0
|
|
46
|
-
? `${JSON.stringify(response)}\n\nNo matches in cold transcript storage. Try a broader query, drop roleFilter, or read the distilled memory directly (MEMORY.md / HISTORY.md in this channel)
|
|
49
|
+
? `${JSON.stringify(response)}\n\nNo matches in cold transcript storage. Try a broader query, drop roleFilter, or read the distilled memory directly (MEMORY.md / HISTORY.md in this channel).${partialNote}`
|
|
47
50
|
: JSON.stringify(response);
|
|
48
51
|
return {
|
|
49
52
|
content: [
|
package/dist/tools/skill.d.ts
CHANGED
|
@@ -26,6 +26,8 @@ export interface SkillToolOptions {
|
|
|
26
26
|
}
|
|
27
27
|
export declare function listWorkspaceSkills(options: {
|
|
28
28
|
workspaceDir: string;
|
|
29
|
+
securityConfig?: SecurityConfig;
|
|
30
|
+
securityContext?: SecurityRuntimeContext;
|
|
29
31
|
}): Promise<WorkspaceSkillSummary[]>;
|
|
30
32
|
export interface WorkspaceSkillFile {
|
|
31
33
|
name: string;
|
package/dist/tools/skill.js
CHANGED
|
@@ -4,6 +4,7 @@ import { dirname, join } from "node:path";
|
|
|
4
4
|
import { Type } from "typebox";
|
|
5
5
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
6
6
|
import { checkPathGuard } from "../security/path-guard-check.js";
|
|
7
|
+
import { readGuardAllows } from "../security/path-guard-filter.js";
|
|
7
8
|
import { isNodeError } from "../shared/fs-utils.js";
|
|
8
9
|
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
9
10
|
import { resolveSkillPath, scanSkillContent, validateSkillFrontmatter, validateSkillName } from "./skill-security.js";
|
|
@@ -36,6 +37,14 @@ function extractDescription(content) {
|
|
|
36
37
|
}
|
|
37
38
|
export async function listWorkspaceSkills(options) {
|
|
38
39
|
const skillsDir = join(options.workspaceDir, "skills");
|
|
40
|
+
// `skill read` runs each SKILL.md through the path guard (`loadWorkspaceSkillFile`); `list`
|
|
41
|
+
// must apply the same guard so a skill whose SKILL.md is a symlink out of `workspace/skills/`
|
|
42
|
+
// is silently omitted here too, rather than being advertised and then refused on read.
|
|
43
|
+
const guardConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
|
|
44
|
+
const guardContext = options.securityContext ?? {
|
|
45
|
+
agentWorkspaceDir: options.workspaceDir,
|
|
46
|
+
projectRoot: options.workspaceDir,
|
|
47
|
+
};
|
|
39
48
|
let names;
|
|
40
49
|
try {
|
|
41
50
|
names = await readdir(skillsDir);
|
|
@@ -58,6 +67,9 @@ export async function listWorkspaceSkills(options) {
|
|
|
58
67
|
continue;
|
|
59
68
|
}
|
|
60
69
|
const skillPath = join(skillDir, "SKILL.md");
|
|
70
|
+
if (!readGuardAllows(skillPath, guardConfig, guardContext)) {
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
61
73
|
let content;
|
|
62
74
|
try {
|
|
63
75
|
const skillFileStats = await stat(skillPath);
|
|
@@ -95,7 +95,7 @@ export function createSubAgentListTool(options) {
|
|
|
95
95
|
return {
|
|
96
96
|
name: "subagent_list",
|
|
97
97
|
label: "subagent_list",
|
|
98
|
-
description: "Snapshot of this channel's delegation runs.
|
|
98
|
+
description: "Snapshot of this channel's delegation runs. Completion wakes this channel; inspect when a decision needs current status, not in a polling loop.",
|
|
99
99
|
parameters: subagentListSchema,
|
|
100
100
|
execute: async () => {
|
|
101
101
|
// Spec 042 D9: this used to return every run on the channel, unbounded, in both the
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The single source of truth for which tools a sub-agent role may request.
|
|
3
|
+
*
|
|
4
|
+
* This is a leaf module with no imports so both ends can read it without pulling in a cycle:
|
|
5
|
+
* `registry.ts` stamps `availableToSubagents` from it when building the sub-agent tool set, and
|
|
6
|
+
* `subagents/discovery.ts` validates a role file's `tools:` list against it. They used to be two
|
|
7
|
+
* hand-maintained lists and had already drifted (`glob` was build-available but validation-rejected).
|
|
8
|
+
* A test asserts the two ends still agree.
|
|
9
|
+
*/
|
|
10
|
+
export declare const SUBAGENT_TOOL_NAMES: readonly ["read", "grep", "glob", "bash", "edit", "write", "web_search", "web_fetch"];
|
|
11
|
+
export type SubAgentToolName = (typeof SUBAGENT_TOOL_NAMES)[number];
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The single source of truth for which tools a sub-agent role may request.
|
|
3
|
+
*
|
|
4
|
+
* This is a leaf module with no imports so both ends can read it without pulling in a cycle:
|
|
5
|
+
* `registry.ts` stamps `availableToSubagents` from it when building the sub-agent tool set, and
|
|
6
|
+
* `subagents/discovery.ts` validates a role file's `tools:` list against it. They used to be two
|
|
7
|
+
* hand-maintained lists and had already drifted (`glob` was build-available but validation-rejected).
|
|
8
|
+
* A test asserts the two ends still agree.
|
|
9
|
+
*/
|
|
10
|
+
export const SUBAGENT_TOOL_NAMES = [
|
|
11
|
+
"read",
|
|
12
|
+
"grep",
|
|
13
|
+
"glob",
|
|
14
|
+
"bash",
|
|
15
|
+
"edit",
|
|
16
|
+
"write",
|
|
17
|
+
"web_search",
|
|
18
|
+
"web_fetch",
|
|
19
|
+
];
|
|
@@ -2,11 +2,10 @@ import { mkdir } from "node:fs/promises";
|
|
|
2
2
|
import { renderCloseSummary, writeLastResult } from "../../tasks/cycle.js";
|
|
3
3
|
import { applyTaskPlanPatch, normalizeTaskId, readActiveTasks, uncheckedTaskAcceptanceItems, } from "../../tasks/ledger.js";
|
|
4
4
|
import { appendTaskLog } from "../../tasks/log.js";
|
|
5
|
-
import { hasPassingRound } from "../../tasks/rounds.js";
|
|
6
5
|
import { archiveTask, readStoredTask, writeStoredTask } from "../../tasks/store.js";
|
|
7
6
|
import { describeTicket, resolveTicket } from "../../tasks/ticket.js";
|
|
8
7
|
import { RecoverableToolError } from "../tool-details.js";
|
|
9
|
-
import { buildTicketContext, cleanupTaskEvents, describeTaskState, normalizeBudget, normalizeSchedule, renderCloseEvidence, requiredField, tasksDir, } from "./shared.js";
|
|
8
|
+
import { assertVerificationHoldsForClose, buildTicketContext, cleanupTaskEvents, describeTaskState, normalizeBudget, normalizeSchedule, renderCloseEvidence, requiredField, tasksDir, } from "./shared.js";
|
|
10
9
|
async function requireTask(options, id) {
|
|
11
10
|
const document = await readStoredTask(options.channelDir, id);
|
|
12
11
|
if (!document) {
|
|
@@ -67,10 +66,7 @@ export async function closeTask(options, request) {
|
|
|
67
66
|
if (unchecked.length > 0) {
|
|
68
67
|
throw new RecoverableToolError(`Task "${id}" still has unmet acceptance items: ${unchecked.slice(0, 3).join("; ")}. Check them off with edit once the evidence holds.`);
|
|
69
68
|
}
|
|
70
|
-
|
|
71
|
-
!(await hasPassingRound(options.channelDir, id, document.fields.cycle?.id))) {
|
|
72
|
-
throw new RecoverableToolError(`Task "${id}" requires independent verification; dispatch a purpose=verify sub-agent with taskId=${id} and let its PASS land before completing.`);
|
|
73
|
-
}
|
|
69
|
+
await assertVerificationHoldsForClose(options, document, id);
|
|
74
70
|
const evidence = renderCloseEvidence(request);
|
|
75
71
|
document.body = writeLastResult(document.body, evidence);
|
|
76
72
|
await writeStoredTask(document);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { normalizeTaskId } from "../../tasks/ledger.js";
|
|
2
|
-
import { readTaskLog, renderTaskLogLine } from "../../tasks/log.js";
|
|
2
|
+
import { readTaskLog, renderTaskLogLine, taskLogIsArchived } from "../../tasks/log.js";
|
|
3
3
|
const DEFAULT_LIMIT = 20;
|
|
4
4
|
const MAX_LIMIT = 100;
|
|
5
5
|
/**
|
|
@@ -11,14 +11,17 @@ const MAX_LIMIT = 100;
|
|
|
11
11
|
export async function readTaskLogTool(options, request) {
|
|
12
12
|
const id = normalizeTaskId(request.id);
|
|
13
13
|
const limit = Math.min(Math.max(1, Math.trunc(request.limit ?? DEFAULT_LIMIT)), MAX_LIMIT);
|
|
14
|
+
const archived = taskLogIsArchived(options.channelDir, id);
|
|
14
15
|
const records = await readTaskLog(options.channelDir, id, { cycle: request.cycle, limit });
|
|
15
16
|
const entries = records.map(renderTaskLogLine);
|
|
17
|
+
const scope = request.cycle ? `(周期 ${request.cycle})` : "";
|
|
18
|
+
const archivedTag = archived ? "(已归档任务)" : "";
|
|
16
19
|
return {
|
|
17
20
|
action: "log",
|
|
18
21
|
id,
|
|
19
22
|
entries,
|
|
20
23
|
notice: entries.length === 0
|
|
21
|
-
? `任务 \`${id}\` 暂无循环日志${
|
|
22
|
-
: `任务 \`${id}\` 最近 ${entries.length} 条记录${
|
|
24
|
+
? `任务 \`${id}\` 暂无循环日志${scope}${archivedTag}。`
|
|
25
|
+
: `任务 \`${id}\` 最近 ${entries.length} 条记录${scope}${archivedTag}。`,
|
|
23
26
|
};
|
|
24
27
|
}
|
|
@@ -11,10 +11,10 @@ export declare const taskCreateSchema: Type.TObject<{
|
|
|
11
11
|
verificationRequired: Type.TOptional<Type.TBoolean>;
|
|
12
12
|
schedule: Type.TOptional<Type.TString>;
|
|
13
13
|
budget: Type.TOptional<Type.TObject<{
|
|
14
|
-
steps: Type.TOptional<Type.
|
|
14
|
+
steps: Type.TOptional<Type.TInteger>;
|
|
15
15
|
wallMin: Type.TOptional<Type.TNumber>;
|
|
16
16
|
usd: Type.TOptional<Type.TNumber>;
|
|
17
|
-
rounds: Type.TOptional<Type.
|
|
17
|
+
rounds: Type.TOptional<Type.TInteger>;
|
|
18
18
|
until: Type.TOptional<Type.TString>;
|
|
19
19
|
}>>;
|
|
20
20
|
}>;
|
|
@@ -27,10 +27,10 @@ export declare const taskUpdateSchema: Type.TObject<{
|
|
|
27
27
|
}>>>;
|
|
28
28
|
schedule: Type.TOptional<Type.TString>;
|
|
29
29
|
budget: Type.TOptional<Type.TObject<{
|
|
30
|
-
steps: Type.TOptional<Type.
|
|
30
|
+
steps: Type.TOptional<Type.TInteger>;
|
|
31
31
|
wallMin: Type.TOptional<Type.TNumber>;
|
|
32
32
|
usd: Type.TOptional<Type.TNumber>;
|
|
33
|
-
rounds: Type.TOptional<Type.
|
|
33
|
+
rounds: Type.TOptional<Type.TInteger>;
|
|
34
34
|
until: Type.TOptional<Type.TString>;
|
|
35
35
|
}>>;
|
|
36
36
|
verificationRequired: Type.TOptional<Type.TBoolean>;
|
|
@@ -46,7 +46,7 @@ export declare const taskCloseSchema: Type.TObject<{
|
|
|
46
46
|
export declare const taskLogSchema: Type.TObject<{
|
|
47
47
|
id: Type.TString;
|
|
48
48
|
cycle: Type.TOptional<Type.TString>;
|
|
49
|
-
limit: Type.TOptional<Type.
|
|
49
|
+
limit: Type.TOptional<Type.TInteger>;
|
|
50
50
|
}>;
|
|
51
51
|
export declare const taskStepEndSchema: Type.TObject<{
|
|
52
52
|
outcome: Type.TUnion<[Type.TLiteral<"continue">, Type.TLiteral<"park">, Type.TLiteral<"done">, Type.TLiteral<"blocked">]>;
|
|
@@ -57,7 +57,7 @@ export declare const taskStepEndSchema: Type.TObject<{
|
|
|
57
57
|
text: Type.TOptional<Type.TString>;
|
|
58
58
|
}>>>;
|
|
59
59
|
ticket: Type.TOptional<Type.TObject<{
|
|
60
|
-
kind: Type.TUnion<[Type.TLiteral<"time">, Type.TLiteral<"
|
|
60
|
+
kind: Type.TUnion<[Type.TLiteral<"time">, Type.TLiteral<"run">, Type.TLiteral<"job">, Type.TLiteral<"ask">, Type.TLiteral<"signal">]>;
|
|
61
61
|
at: Type.TOptional<Type.TString>;
|
|
62
62
|
id: Type.TOptional<Type.TString>;
|
|
63
63
|
asked: Type.TOptional<Type.TString>;
|
|
@@ -11,10 +11,10 @@ const scheduleField = Type.Optional(Type.String({
|
|
|
11
11
|
description: "Five-field cron cadence; makes this recurring. Empty string clears it. Min every 30 minutes.",
|
|
12
12
|
}));
|
|
13
13
|
const budgetField = Type.Optional(Type.Object({
|
|
14
|
-
steps: Type.Optional(Type.
|
|
15
|
-
wallMin: Type.Optional(Type.Number({ description: "Max
|
|
14
|
+
steps: Type.Optional(Type.Integer({ minimum: 1, description: "Max model steps in one cycle." })),
|
|
15
|
+
wallMin: Type.Optional(Type.Number({ description: "Max elapsed minutes in one cycle, including parked waits." })),
|
|
16
16
|
usd: Type.Optional(Type.Number({ description: "Max attributable cost in one cycle." })),
|
|
17
|
-
rounds: Type.Optional(Type.
|
|
17
|
+
rounds: Type.Optional(Type.Integer({ minimum: 1, description: "Max delegate→verify rework rounds in one cycle." })),
|
|
18
18
|
until: Type.Optional(Type.String({ description: "Hard local-time stop, e.g. 2026-09-06T18:00:00+08:00." })),
|
|
19
19
|
}, { description: "Per-task budget; omitted keys fall back to the runtime defaults." }));
|
|
20
20
|
/**
|
|
@@ -23,14 +23,7 @@ const budgetField = Type.Optional(Type.Object({
|
|
|
23
23
|
* the model can choose is a backstop it can choose not to have.
|
|
24
24
|
*/
|
|
25
25
|
const ticketField = Type.Object({
|
|
26
|
-
kind: Type.Union([
|
|
27
|
-
Type.Literal("time"),
|
|
28
|
-
Type.Literal("schedule"),
|
|
29
|
-
Type.Literal("run"),
|
|
30
|
-
Type.Literal("job"),
|
|
31
|
-
Type.Literal("ask"),
|
|
32
|
-
Type.Literal("signal"),
|
|
33
|
-
], { description: "What will wake this task." }),
|
|
26
|
+
kind: Type.Union([Type.Literal("time"), Type.Literal("run"), Type.Literal("job"), Type.Literal("ask"), Type.Literal("signal")], { description: "What will wake this task." }),
|
|
34
27
|
at: Type.Optional(Type.String({ description: 'kind=time: when, e.g. "+2h" or a local timestamp.' })),
|
|
35
28
|
id: Type.Optional(Type.String({ description: "kind=run/job: the run or job id this task is waiting on." })),
|
|
36
29
|
asked: Type.Optional(Type.String({ description: "kind=ask: the question the user must answer." })),
|
|
@@ -75,7 +68,7 @@ export const taskCloseSchema = Type.Object({
|
|
|
75
68
|
export const taskLogSchema = Type.Object({
|
|
76
69
|
id: idField,
|
|
77
70
|
cycle: Type.Optional(Type.String({ description: "Only this cycle's records, e.g. c-2026-09-05." })),
|
|
78
|
-
limit: Type.Optional(Type.
|
|
71
|
+
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 100, description: "Most recent N records; default 20." })),
|
|
79
72
|
});
|
|
80
73
|
export const taskStepEndSchema = Type.Object({
|
|
81
74
|
outcome: Type.Union([Type.Literal("continue"), Type.Literal("park"), Type.Literal("done"), Type.Literal("blocked")], {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { TaskBudget, TaskFrontmatterV4 } from "../../tasks/frontmatter.js";
|
|
2
|
+
import type { StoredTaskDocument } from "../../tasks/store.js";
|
|
2
3
|
import { type TicketContext } from "../../tasks/ticket.js";
|
|
3
4
|
import type { TaskCloseRequest, TaskCreateRequest, TaskManageToolOptions, TaskUpdateRequest } from "./types.js";
|
|
4
5
|
export declare function tasksDir(options: TaskManageToolOptions): string;
|
|
@@ -38,3 +39,13 @@ export declare function buildTicketContext(options: TaskManageToolOptions, taskI
|
|
|
38
39
|
export declare function cleanupTaskEvents(options: TaskManageToolOptions, id: string): Promise<{
|
|
39
40
|
deleted: string[];
|
|
40
41
|
}>;
|
|
42
|
+
/**
|
|
43
|
+
* The verification gate both close entry points share (`task_step_end outcome=done` and
|
|
44
|
+
* `task_close outcome=complete`).
|
|
45
|
+
*
|
|
46
|
+
* It exists as one function because the two used to ask the question separately and both asked
|
|
47
|
+
* the weaker one — "did a PASS ever land in this cycle" — which a contract edit or a further code
|
|
48
|
+
* change made *after* the PASS would still satisfy. The real check is re-run here, against the
|
|
49
|
+
* contract and the checkout as they stand at close time.
|
|
50
|
+
*/
|
|
51
|
+
export declare function assertVerificationHoldsForClose(options: TaskManageToolOptions, document: StoredTaskDocument, id: string): Promise<void>;
|