@oyasmi/pipiclaw 0.9.1-beta.2 → 0.9.1
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/dist/agent/channel-runner.d.ts +7 -0
- package/dist/agent/channel-runner.js +42 -13
- package/dist/agent/command-extension.js +24 -27
- package/dist/agent/commands.d.ts +51 -7
- package/dist/agent/commands.js +199 -59
- package/dist/agent/prompt/manifest.js +5 -6
- package/dist/agent/prompt/sections.js +1 -0
- package/dist/agent/reply-limits.d.ts +16 -0
- package/dist/agent/reply-limits.js +17 -0
- package/dist/agent/session-events.js +2 -2
- package/dist/agent/status-render.js +12 -12
- package/dist/executor.d.ts +14 -0
- package/dist/executor.js +36 -6
- package/dist/main.js +3 -4
- package/dist/memory/commands.js +79 -38
- package/dist/memory/consolidation.d.ts +5 -1
- package/dist/memory/consolidation.js +33 -12
- package/dist/memory/extraction.d.ts +8 -1
- package/dist/memory/extraction.js +47 -4
- package/dist/memory/files.d.ts +0 -1
- package/dist/memory/files.js +24 -5
- package/dist/memory/lifecycle.js +9 -2
- package/dist/memory/maintenance-jobs.js +14 -4
- package/dist/memory/metadata.d.ts +3 -0
- package/dist/memory/metadata.js +7 -0
- package/dist/memory/recall.d.ts +9 -0
- package/dist/memory/recall.js +101 -17
- package/dist/memory/review-log.d.ts +0 -2
- package/dist/memory/review-log.js +0 -0
- package/dist/memory/session-corpus.js +5 -0
- package/dist/memory/session-search.js +9 -0
- package/dist/memory/sidecar-worker.js +4 -0
- package/dist/memory/source-window.d.ts +0 -1
- package/dist/memory/source-window.js +0 -5
- package/dist/playbooks/agent-delegation.md +32 -25
- package/dist/playbooks/background-jobs.md +8 -16
- package/dist/playbooks/event-scheduling.md +13 -15
- package/dist/playbooks/memory-and-learning.md +29 -22
- package/dist/playbooks/outbound-media.md +15 -8
- package/dist/playbooks/runtime-orientation.md +40 -37
- package/dist/playbooks/task-driving.md +34 -36
- package/dist/playbooks/task-planning.md +18 -18
- package/dist/runtime/app-home.d.ts +6 -0
- package/dist/runtime/app-home.js +15 -6
- package/dist/runtime/bootstrap.js +44 -13
- package/dist/runtime/channel-context.d.ts +2 -1
- package/dist/runtime/delivery.js +3 -3
- package/dist/runtime/dingtalk.d.ts +9 -1
- package/dist/runtime/dingtalk.js +27 -13
- package/dist/runtime/event-commands.d.ts +15 -0
- package/dist/runtime/event-commands.js +48 -40
- package/dist/runtime/project-commands.d.ts +16 -0
- package/dist/runtime/project-commands.js +13 -17
- package/dist/runtime/subagent-commands.d.ts +20 -0
- package/dist/runtime/subagent-commands.js +61 -58
- package/dist/runtime/task-commands.d.ts +37 -0
- package/dist/runtime/task-commands.js +106 -64
- package/dist/security/path-guard.js +33 -2
- package/dist/security/types.d.ts +9 -0
- package/dist/subagents/discovery.d.ts +7 -2
- package/dist/subagents/discovery.js +31 -7
- package/dist/subagents/external/claude-code.js +42 -2
- package/dist/subagents/external/run.js +61 -8
- package/dist/subagents/runs.js +6 -0
- package/dist/subagents/tool.d.ts +1 -0
- package/dist/subagents/tool.js +62 -53
- package/dist/tasks/verification.d.ts +7 -5
- package/dist/tools/bash.d.ts +1 -1
- package/dist/tools/bash.js +77 -59
- package/dist/tools/edit.js +17 -4
- package/dist/tools/grep.js +3 -2
- package/dist/tools/index.js +4 -0
- package/dist/tools/job.js +2 -1
- package/dist/tools/memory-manage.d.ts +1 -0
- package/dist/tools/memory-manage.js +54 -16
- package/dist/tools/read.js +21 -5
- package/dist/tools/send-media.js +17 -6
- package/dist/tools/skill-manage.js +12 -11
- package/dist/tools/skill-security.js +1 -1
- package/dist/tools/task-manage.js +1 -1
- package/dist/tools/truncate.d.ts +8 -0
- package/dist/tools/truncate.js +8 -0
- package/dist/tools/web-fetch.js +9 -1
- package/dist/tools/write-content.js +11 -1
- package/dist/tui/app.js +1 -1
- package/dist/tui/commands.d.ts +1 -1
- package/dist/tui/commands.js +1 -1
- package/dist/tui/turn-controller.d.ts +1 -1
- package/dist/tui/turn-controller.js +14 -4
- package/dist/usage/render.js +10 -8
- package/examples/sub-agents/README.md +2 -0
- package/package.json +3 -2
package/dist/tools/grep.js
CHANGED
|
@@ -2,6 +2,7 @@ import { Type } from "typebox";
|
|
|
2
2
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
3
3
|
import { logSecurityEvent } from "../security/logger.js";
|
|
4
4
|
import { guardPath } from "../security/path-guard.js";
|
|
5
|
+
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
5
6
|
import { shellEscape } from "../shared/shell-escape.js";
|
|
6
7
|
import { DEFAULT_MAX_BYTES, truncateHead } from "./truncate.js";
|
|
7
8
|
/**
|
|
@@ -146,7 +147,7 @@ export function createGrepTool(executor, options = {}) {
|
|
|
146
147
|
parameters: grepSchema,
|
|
147
148
|
execute: async (_toolCallId, { pattern, path, glob, caseSensitive, skip, }, signal) => {
|
|
148
149
|
if (!pattern.trim()) {
|
|
149
|
-
throw new
|
|
150
|
+
throw new RecoverableToolError("Pattern must not be empty.");
|
|
150
151
|
}
|
|
151
152
|
const searchPath = path?.trim() || ".";
|
|
152
153
|
if (securityConfig.enabled && securityConfig.pathGuard.enabled) {
|
|
@@ -175,7 +176,7 @@ export function createGrepTool(executor, options = {}) {
|
|
|
175
176
|
// grep exit code 1 = no matches (normal), 0 = matches, >=2 = error.
|
|
176
177
|
if (result.code >= 2) {
|
|
177
178
|
const stderr = result.stderr.trim();
|
|
178
|
-
throw new
|
|
179
|
+
throw new RecoverableToolError(`grep failed: ${stderr || `exit code ${result.code}`}. Check the regex (ERE syntax) and that the path exists.`);
|
|
179
180
|
}
|
|
180
181
|
const globRegExp = glob ? globToRegExp(glob) : undefined;
|
|
181
182
|
const parsed = parseGrepOutput(result.stdout);
|
package/dist/tools/index.js
CHANGED
|
@@ -16,6 +16,10 @@ export function createPipiclawTools(options) {
|
|
|
16
16
|
agentWorkspaceDir: options.workspaceDir,
|
|
17
17
|
projectRoot: options.projectScope.projectRoot,
|
|
18
18
|
boundary: options.projectScope.boundary,
|
|
19
|
+
// The main agent is channel-bound, so its own SESSION/MEMORY/HISTORY/tasks stay reachable
|
|
20
|
+
// even when `boundary: "project"` puts the rest of the workspace out of bounds — a task wake
|
|
21
|
+
// names `tasks/<id>.md` and expects the model to be able to open it (spec 043, D5).
|
|
22
|
+
channelDir: options.channelDir,
|
|
19
23
|
};
|
|
20
24
|
// The leaf tools (files, web, memory, skills) come from the single declarative
|
|
21
25
|
// registry so this set, the sub-agent set, and the prompt hints share one source.
|
package/dist/tools/job.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Type } from "typebox";
|
|
2
|
+
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
2
3
|
import { truncateTail } from "./truncate.js";
|
|
3
4
|
const jobSchema = Type.Object({
|
|
4
5
|
label: Type.String({ description: "Brief description of what you're checking (shown to user)" }),
|
|
@@ -43,7 +44,7 @@ export function createJobTool(options) {
|
|
|
43
44
|
execute: async (_toolCallId, { op, ids }, signal) => {
|
|
44
45
|
if (op === "cancel") {
|
|
45
46
|
if (!ids || ids.length === 0) {
|
|
46
|
-
throw new
|
|
47
|
+
throw new RecoverableToolError("cancel requires at least one job id.");
|
|
47
48
|
}
|
|
48
49
|
const outcomes = await jobManager.cancel(ids, signal);
|
|
49
50
|
const text = outcomes.map((outcome) => `- [${outcome.id}] ${outcome.status}`).join("\n");
|
|
@@ -10,6 +10,7 @@ declare const memoryManageSchema: Type.TObject<{
|
|
|
10
10
|
query: Type.TOptional<Type.TString>;
|
|
11
11
|
target: Type.TOptional<Type.TString>;
|
|
12
12
|
kind: Type.TOptional<Type.TUnion<[Type.TLiteral<"preference">, Type.TLiteral<"fact">, Type.TLiteral<"decision">, Type.TLiteral<"constraint">, Type.TLiteral<"open-loop">, Type.TLiteral<"lesson">]>>;
|
|
13
|
+
supersedes: Type.TOptional<Type.TString>;
|
|
13
14
|
}>;
|
|
14
15
|
export interface MemoryManageToolOptions {
|
|
15
16
|
channelId: string;
|
|
@@ -29,7 +29,20 @@ const memoryManageSchema = Type.Object({
|
|
|
29
29
|
Type.Literal("open-loop"),
|
|
30
30
|
Type.Literal("lesson"),
|
|
31
31
|
], { description: "For save: what kind of durable memory this is." })),
|
|
32
|
+
supersedes: Type.Optional(Type.String({
|
|
33
|
+
description: "For save, only after this tool reported a similar existing entry: the entry id being replaced, " +
|
|
34
|
+
'or "none" to keep both.',
|
|
35
|
+
})),
|
|
32
36
|
});
|
|
37
|
+
/**
|
|
38
|
+
* Above this recall score, an existing entry is similar enough that saving alongside it — rather
|
|
39
|
+
* than superseding it — risks two contradictory durable facts competing at recall time. Set high
|
|
40
|
+
* on purpose: a false positive interrupts every plain save, a false negative just means the old
|
|
41
|
+
* conflict-resolution instruction ("say 'forget the old one'") still applies. Starts at the same
|
|
42
|
+
* value `recall.ts` uses to gate its own model rerank (`HIGH_CONFIDENCE_SCORE`) — a score that
|
|
43
|
+
* strong elsewhere in the pipeline is a reasonable place to start being strict here too.
|
|
44
|
+
*/
|
|
45
|
+
const SAVE_CONFLICT_SCORE = 8;
|
|
33
46
|
function normalizeMemoryKind(kind) {
|
|
34
47
|
return kind === "preference" ||
|
|
35
48
|
kind === "decision" ||
|
|
@@ -77,7 +90,7 @@ function rejectMissingArgument(op, parameter, args) {
|
|
|
77
90
|
export function createMemoryManageTool(options) {
|
|
78
91
|
const queue = options.channelMemoryQueue ?? getDefaultChannelMemoryQueue();
|
|
79
92
|
async function save(args) {
|
|
80
|
-
const { content, kind } = args;
|
|
93
|
+
const { content, kind, supersedes } = args;
|
|
81
94
|
const trimmed = (content ?? "").trim();
|
|
82
95
|
if (!trimmed) {
|
|
83
96
|
rejectMissingArgument("save", "content", args);
|
|
@@ -85,28 +98,53 @@ export function createMemoryManageTool(options) {
|
|
|
85
98
|
if (containsSecret(trimmed)) {
|
|
86
99
|
return textResult("This content looks like a credential or secret, so it was not saved. Store the secret in an approved secret manager and remember only its location.", { op: "save", saved: false, blockedReason: "secret" });
|
|
87
100
|
}
|
|
101
|
+
if (!supersedes) {
|
|
102
|
+
// Reuse the recall scoring pipeline (already the point-query path for `search`) as a
|
|
103
|
+
// deterministic, no-cost conflict check before writing a second fact that might
|
|
104
|
+
// contradict one already stored.
|
|
105
|
+
const model = options.getCurrentModel();
|
|
106
|
+
const { items } = await recallRelevantMemory({
|
|
107
|
+
query: trimmed,
|
|
108
|
+
channelId: options.channelId,
|
|
109
|
+
workspaceDir: options.workspaceDir,
|
|
110
|
+
channelDir: options.channelDir,
|
|
111
|
+
allowedSources: ["channel-memory"],
|
|
112
|
+
maxCandidates: 3,
|
|
113
|
+
maxInjected: 3,
|
|
114
|
+
maxChars: 1200,
|
|
115
|
+
rerankWithModel: false,
|
|
116
|
+
model,
|
|
117
|
+
resolveApiKey: options.resolveApiKey,
|
|
118
|
+
candidateStore: options.memoryCandidateStore,
|
|
119
|
+
});
|
|
120
|
+
const similar = items.filter((item) => item.entryId && item.score >= SAVE_CONFLICT_SCORE);
|
|
121
|
+
if (similar.length > 0) {
|
|
122
|
+
throw new RecoverableToolError(`Nothing was saved yet. This channel already stores ${similar.length} similar entr${similar.length === 1 ? "y" : "ies"}:\n` +
|
|
123
|
+
similar.map((item) => `- ${item.entryId}: ${item.content}`).join("\n") +
|
|
124
|
+
'\nRe-issue the save with "supersedes" set to the entry id this replaces, or to "none" if both facts are true at the same time.');
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const metadata = {
|
|
128
|
+
kind: normalizeMemoryKind(kind),
|
|
129
|
+
sourceType: "user",
|
|
130
|
+
probationUntil: null,
|
|
131
|
+
};
|
|
88
132
|
// Serialize through the shared channel memory queue so this never races with background
|
|
89
133
|
// consolidation/maintenance on the same channel's files.
|
|
90
134
|
const result = await queue.run(options.channelId, () => applyChannelMemoryOps(options.channelDir, [
|
|
91
|
-
|
|
92
|
-
op: "
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
metadata: {
|
|
97
|
-
kind: normalizeMemoryKind(kind),
|
|
98
|
-
sourceType: "user",
|
|
99
|
-
probationUntil: null,
|
|
100
|
-
},
|
|
101
|
-
},
|
|
135
|
+
supersedes && supersedes !== "none"
|
|
136
|
+
? { op: "supersede", targetId: supersedes, content: trimmed, metadata }
|
|
137
|
+
: // A user explicitly saying "remember this" is never probationary, and restating a
|
|
138
|
+
// fact the runtime had already put on probation promotes it (spec 037, D7).
|
|
139
|
+
{ op: "add", content: trimmed, metadata },
|
|
102
140
|
]));
|
|
103
141
|
options.memoryCandidateStore.invalidate(getChannelMemoryPath(options.channelDir));
|
|
104
|
-
const message = result.added > 0
|
|
142
|
+
const message = result.added > 0 || result.superseded > 0
|
|
105
143
|
? `Saved to channel memory${kind ? ` (${kind})` : ""}.`
|
|
106
144
|
: "That memory is already present; no duplicate was added.";
|
|
107
145
|
return textResult(message, {
|
|
108
146
|
op: "save",
|
|
109
|
-
saved: result.added > 0 || result.skippedDuplicate > 0,
|
|
147
|
+
saved: result.added > 0 || result.superseded > 0 || result.skippedDuplicate > 0,
|
|
110
148
|
});
|
|
111
149
|
}
|
|
112
150
|
async function search(args) {
|
|
@@ -162,7 +200,7 @@ export function createMemoryManageTool(options) {
|
|
|
162
200
|
if (matches.length > 1) {
|
|
163
201
|
// Never guess which entry to delete; make the model disambiguate.
|
|
164
202
|
const candidates = matches.map((entry, index) => `${index + 1}. ${entry.content}`).join("\n");
|
|
165
|
-
throw new
|
|
203
|
+
throw new RecoverableToolError(`"${trimmed}" matched ${matches.length} entries; be more specific so only one is removed:\n${candidates}`);
|
|
166
204
|
}
|
|
167
205
|
const removed = matches[0];
|
|
168
206
|
await queue.run(options.channelId, () => applyChannelMemoryOps(options.channelDir, [{ op: "forget", targetId: removed.id, reason: "user forget" }]));
|
|
@@ -195,7 +233,7 @@ export function createMemoryManageTool(options) {
|
|
|
195
233
|
case "forget":
|
|
196
234
|
return forget(args);
|
|
197
235
|
default:
|
|
198
|
-
throw new
|
|
236
|
+
throw new RecoverableToolError('Unsupported memory op. Use "save", "search", or "forget".');
|
|
199
237
|
}
|
|
200
238
|
},
|
|
201
239
|
};
|
package/dist/tools/read.js
CHANGED
|
@@ -3,8 +3,9 @@ import { Type } from "typebox";
|
|
|
3
3
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
4
4
|
import { logSecurityEvent } from "../security/logger.js";
|
|
5
5
|
import { guardPath } from "../security/path-guard.js";
|
|
6
|
+
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
6
7
|
import { shellEscape } from "../shared/shell-escape.js";
|
|
7
|
-
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateHead } from "./truncate.js";
|
|
8
|
+
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, MAX_INLINE_BINARY_BYTES, truncateHead, } from "./truncate.js";
|
|
8
9
|
/**
|
|
9
10
|
* Map of file extensions to MIME types for common image formats
|
|
10
11
|
*/
|
|
@@ -120,10 +121,23 @@ export function createReadTool(executor, options = {}) {
|
|
|
120
121
|
}
|
|
121
122
|
const mimeType = isImageFile(path);
|
|
122
123
|
if (mimeType) {
|
|
124
|
+
// Guard the file size before `base64`: base64 inflates to 4/3, and the executor caps
|
|
125
|
+
// captured stdout at 10MB, so a file above MAX_INLINE_BINARY_BYTES would be silently
|
|
126
|
+
// truncated mid-encoding into a buffer that still decodes -- a corrupt image handed to
|
|
127
|
+
// the model with no error (fix plan §2.3).
|
|
128
|
+
const sizeCheck = await executor.exec(`wc -c < ${shellEscape(path)} 2>&1 || echo __SIZE_FAILED__`, {
|
|
129
|
+
signal,
|
|
130
|
+
});
|
|
131
|
+
const sizeBytes = Number.parseInt(sizeCheck.stdout.trim(), 10);
|
|
132
|
+
if (Number.isFinite(sizeBytes) && sizeBytes > MAX_INLINE_BINARY_BYTES) {
|
|
133
|
+
throw new RecoverableToolError(`Image ${path} is ${formatSize(sizeBytes)}, over the ${formatSize(MAX_INLINE_BINARY_BYTES)} inline limit. ` +
|
|
134
|
+
"Compress or resize it first with bash (e.g. sips/convert/ffmpeg), or read it as text to inspect metadata only.");
|
|
135
|
+
}
|
|
123
136
|
// Read as image (binary) - use base64
|
|
124
137
|
const result = await executor.exec(`base64 < ${shellEscape(path)}`, { signal });
|
|
125
138
|
if (result.code !== 0) {
|
|
126
|
-
throw new
|
|
139
|
+
throw new RecoverableToolError(result.stderr ||
|
|
140
|
+
`Failed to read file: ${path}. Check the path — try \`read\` on its parent directory to confirm it exists.`);
|
|
127
141
|
}
|
|
128
142
|
const base64 = result.stdout.replace(/\s/g, ""); // Remove whitespace from base64
|
|
129
143
|
return {
|
|
@@ -159,7 +173,8 @@ export function createReadTool(executor, options = {}) {
|
|
|
159
173
|
else {
|
|
160
174
|
const countResult = await executor.exec(`if [ -d ${shellEscape(path)} ]; then echo __DIR__; else awk 'END { print NR }' ${shellEscape(path)}; fi`, { signal });
|
|
161
175
|
if (countResult.code !== 0) {
|
|
162
|
-
throw new
|
|
176
|
+
throw new RecoverableToolError(countResult.stderr ||
|
|
177
|
+
`Failed to read file: ${path}. Check the path — try \`read\` on its parent directory to confirm it exists.`);
|
|
163
178
|
}
|
|
164
179
|
if (countResult.stdout.trim() === "__DIR__") {
|
|
165
180
|
const listing = await executor.exec(`{ find ${shellEscape(path)} -maxdepth ${DIR_MAX_DEPTH} -type d | sed 's,$,/,'; ` +
|
|
@@ -185,7 +200,7 @@ export function createReadTool(executor, options = {}) {
|
|
|
185
200
|
const guidance = totalFileLines > 0
|
|
186
201
|
? `Use offset=${totalFileLines} to read the last line, or omit offset to read from the start.`
|
|
187
202
|
: "The file is empty; omit offset.";
|
|
188
|
-
throw new
|
|
203
|
+
throw new RecoverableToolError(`Offset ${offset} is beyond end of file (${totalFileLines} lines total). ${guidance}`);
|
|
189
204
|
}
|
|
190
205
|
// Read content from the offset. PDF text is already in memory; files stream from disk.
|
|
191
206
|
let selectedContent;
|
|
@@ -212,7 +227,8 @@ export function createReadTool(executor, options = {}) {
|
|
|
212
227
|
// the pipe early is the point, not a failure.
|
|
213
228
|
const result = await executor.exec(`${source} | head -c ${readWindowBytes}`, { signal });
|
|
214
229
|
if (result.code !== 0) {
|
|
215
|
-
throw new
|
|
230
|
+
throw new RecoverableToolError(result.stderr ||
|
|
231
|
+
`Failed to read file: ${path}. Check the path — try \`read\` on its parent directory to confirm it exists.`);
|
|
216
232
|
}
|
|
217
233
|
selectedContent = result.stdout;
|
|
218
234
|
}
|
package/dist/tools/send-media.js
CHANGED
|
@@ -3,7 +3,9 @@ import { Type } from "typebox";
|
|
|
3
3
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
4
4
|
import { logSecurityEvent } from "../security/logger.js";
|
|
5
5
|
import { guardPath } from "../security/path-guard.js";
|
|
6
|
+
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
6
7
|
import { shellEscape } from "../shared/shell-escape.js";
|
|
8
|
+
import { formatSize, MAX_INLINE_BINARY_BYTES } from "./truncate.js";
|
|
7
9
|
/** Extensions delivered as inline images; everything else goes as a file attachment. */
|
|
8
10
|
const IMAGE_EXTENSIONS = new Set([".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"]);
|
|
9
11
|
const sendMediaSchema = Type.Object({
|
|
@@ -54,11 +56,20 @@ export function createSendMediaTool(executor, options) {
|
|
|
54
56
|
throw new Error(formatPathBlockMessage(guardResult.resolvedPath, guardResult.category, guardResult.reason));
|
|
55
57
|
}
|
|
56
58
|
}
|
|
57
|
-
// Confirm the target is a readable regular file
|
|
58
|
-
//
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
59
|
+
// Confirm the target is a readable regular file and get its size before base64-encoding
|
|
60
|
+
// it, in one exec. Size matters because base64 inflates to 4/3 and the executor caps
|
|
61
|
+
// captured stdout at 10MB -- above the inline limit, base64 would be silently truncated
|
|
62
|
+
// mid-encoding into a buffer that still decodes: a corrupt file "successfully" sent to
|
|
63
|
+
// the user with no error at all (fix plan §2.3).
|
|
64
|
+
const stat = await executor.exec(`if [ -f ${shellEscape(path)} ]; then wc -c < ${shellEscape(path)}; else echo NO; fi`, { signal });
|
|
65
|
+
const statOutput = stat.stdout.trim();
|
|
66
|
+
if (statOutput === "NO") {
|
|
67
|
+
throw new RecoverableToolError(`Cannot send ${path}: not a regular file (does it exist?).`);
|
|
68
|
+
}
|
|
69
|
+
const sizeBytes = Number.parseInt(statOutput, 10);
|
|
70
|
+
if (Number.isFinite(sizeBytes) && sizeBytes > MAX_INLINE_BINARY_BYTES) {
|
|
71
|
+
throw new RecoverableToolError(`Cannot send ${path}: it is ${formatSize(sizeBytes)}, over the ${formatSize(MAX_INLINE_BINARY_BYTES)} send limit. ` +
|
|
72
|
+
"Compress it first, or provide the path so the user can be told where to find it.");
|
|
62
73
|
}
|
|
63
74
|
const encoded = await executor.exec(`base64 < ${shellEscape(path)}`, { signal });
|
|
64
75
|
if (encoded.code !== 0) {
|
|
@@ -66,7 +77,7 @@ export function createSendMediaTool(executor, options) {
|
|
|
66
77
|
}
|
|
67
78
|
const data = Buffer.from(encoded.stdout.replace(/\s/g, ""), "base64");
|
|
68
79
|
if (data.length === 0) {
|
|
69
|
-
throw new
|
|
80
|
+
throw new RecoverableToolError(`Cannot send ${path}: the file is empty.`);
|
|
70
81
|
}
|
|
71
82
|
const name = fileName?.trim() || basename(path);
|
|
72
83
|
const kind = IMAGE_EXTENSIONS.has(extname(name).toLowerCase()) ? "image" : "file";
|
|
@@ -3,6 +3,7 @@ import { readdir, readFile, stat } from "node:fs/promises";
|
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { Type } from "typebox";
|
|
5
5
|
import { createAtomicTempPath, writeFileAtomically } from "../shared/atomic-file.js";
|
|
6
|
+
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
6
7
|
import { resolveSkillPath, resolveSkillSupportingFile, scanSkillContent, validateSkillFrontmatter, validateSkillMarkdown, validateSkillName, } from "./skill-security.js";
|
|
7
8
|
import { DEFAULT_MAX_BYTES, formatSize, truncateHead } from "./truncate.js";
|
|
8
9
|
const skillManageSchema = Type.Object({
|
|
@@ -92,30 +93,30 @@ function parseWriteAction(action) {
|
|
|
92
93
|
if (action === "create" || action === "patch" || action === "write_file") {
|
|
93
94
|
return action;
|
|
94
95
|
}
|
|
95
|
-
throw new
|
|
96
|
+
throw new RecoverableToolError('Unsupported skill action. Use "list", "view", "create", "patch", or "write_file".');
|
|
96
97
|
}
|
|
97
98
|
function ensureSkillMarkdownSafe(content, name) {
|
|
98
99
|
const validation = validateSkillMarkdown(content, name);
|
|
99
100
|
if (!validation.ok) {
|
|
100
|
-
throw new
|
|
101
|
+
throw new RecoverableToolError(validation.error ?? "Skill content failed validation.");
|
|
101
102
|
}
|
|
102
103
|
}
|
|
103
104
|
function ensureSupportingFileSafe(content) {
|
|
104
105
|
const validation = scanSkillContent(content);
|
|
105
106
|
if (!validation.ok) {
|
|
106
|
-
throw new
|
|
107
|
+
throw new RecoverableToolError(validation.error ?? "Skill content failed validation.");
|
|
107
108
|
}
|
|
108
109
|
}
|
|
109
110
|
function applyUniquePatch(content, find, replace) {
|
|
110
111
|
if (!find) {
|
|
111
|
-
throw new
|
|
112
|
+
throw new RecoverableToolError("Patch requires a non-empty find string.");
|
|
112
113
|
}
|
|
113
114
|
const first = content.indexOf(find);
|
|
114
115
|
if (first < 0) {
|
|
115
|
-
throw new
|
|
116
|
+
throw new RecoverableToolError("Patch find string was not found.");
|
|
116
117
|
}
|
|
117
118
|
if (content.indexOf(find, first + find.length) >= 0) {
|
|
118
|
-
throw new
|
|
119
|
+
throw new RecoverableToolError("Patch find string matched multiple locations.");
|
|
119
120
|
}
|
|
120
121
|
return `${content.slice(0, first)}${replace}${content.slice(first + find.length)}`;
|
|
121
122
|
}
|
|
@@ -124,7 +125,7 @@ export async function manageWorkspaceSkill(options, request) {
|
|
|
124
125
|
const skillPath = join(skillDir, "SKILL.md");
|
|
125
126
|
if (request.action === "create") {
|
|
126
127
|
if (existsSync(skillPath)) {
|
|
127
|
-
throw new
|
|
128
|
+
throw new RecoverableToolError(`Workspace skill "${request.name}" already exists.`);
|
|
128
129
|
}
|
|
129
130
|
const content = request.content ?? "";
|
|
130
131
|
ensureSkillMarkdownSafe(content, request.name);
|
|
@@ -139,11 +140,11 @@ export async function manageWorkspaceSkill(options, request) {
|
|
|
139
140
|
};
|
|
140
141
|
}
|
|
141
142
|
if (!existsSync(skillPath)) {
|
|
142
|
-
throw new
|
|
143
|
+
throw new RecoverableToolError(`Workspace skill "${request.name}" does not exist.`);
|
|
143
144
|
}
|
|
144
145
|
if (request.action === "write_file") {
|
|
145
146
|
if (!request.filePath) {
|
|
146
|
-
throw new
|
|
147
|
+
throw new RecoverableToolError("write_file requires filePath.");
|
|
147
148
|
}
|
|
148
149
|
const content = request.content ?? "";
|
|
149
150
|
const targetPath = resolveSkillSupportingFile(skillDir, request.filePath);
|
|
@@ -209,7 +210,7 @@ export function createSkillManageTool(options) {
|
|
|
209
210
|
};
|
|
210
211
|
}
|
|
211
212
|
if (!args.name) {
|
|
212
|
-
throw new
|
|
213
|
+
throw new RecoverableToolError(`Action "${args.action}" requires a skill name.`);
|
|
213
214
|
}
|
|
214
215
|
if (args.action === "view") {
|
|
215
216
|
return viewWorkspaceSkill(options, args.name, args.filePath);
|
|
@@ -223,7 +224,7 @@ export function createSkillManageTool(options) {
|
|
|
223
224
|
replace: args.replace,
|
|
224
225
|
});
|
|
225
226
|
return {
|
|
226
|
-
content: [{ type: "text", text: JSON.stringify(result
|
|
227
|
+
content: [{ type: "text", text: JSON.stringify(result) }],
|
|
227
228
|
details: { ...result },
|
|
228
229
|
};
|
|
229
230
|
},
|
|
@@ -73,7 +73,7 @@ export function resolveSkillPath(workspaceDir, name) {
|
|
|
73
73
|
}
|
|
74
74
|
const skillsDir = resolve(workspaceDir, "skills");
|
|
75
75
|
const skillDir = resolve(skillsDir, name);
|
|
76
|
-
if (
|
|
76
|
+
if (!skillDir.startsWith(`${skillsDir}/`)) {
|
|
77
77
|
throw new Error("Resolved skill path escaped workspace skills directory.");
|
|
78
78
|
}
|
|
79
79
|
return skillDir;
|
|
@@ -55,7 +55,7 @@ export function createTaskManageTool(options) {
|
|
|
55
55
|
action: parseAction(request.action),
|
|
56
56
|
});
|
|
57
57
|
return {
|
|
58
|
-
content: [{ type: "text", text: JSON.stringify(result
|
|
58
|
+
content: [{ type: "text", text: JSON.stringify(result) }],
|
|
59
59
|
details: { ...result },
|
|
60
60
|
};
|
|
61
61
|
},
|
package/dist/tools/truncate.d.ts
CHANGED
|
@@ -9,6 +9,14 @@
|
|
|
9
9
|
*/
|
|
10
10
|
export declare const DEFAULT_MAX_LINES = 2000;
|
|
11
11
|
export declare const DEFAULT_MAX_BYTES: number;
|
|
12
|
+
/**
|
|
13
|
+
* Upper bound for a file read/sent as base64 in one `sh -c` (fix plan §2.3). `base64` inflates a
|
|
14
|
+
* file to 4/3 of its size, and the executor caps captured stdout at 10MB -- above this threshold
|
|
15
|
+
* the encoded output would be silently cut mid-stream, producing a buffer that still decodes (so
|
|
16
|
+
* failure is invisible) but is corrupt. 5MB leaves headroom for the 4/3 blow-up plus protocol
|
|
17
|
+
* overhead. A code constant, not a settings.json key, per CLAUDE.md's rule for numeric thresholds.
|
|
18
|
+
*/
|
|
19
|
+
export declare const MAX_INLINE_BINARY_BYTES: number;
|
|
12
20
|
export interface TruncationResult {
|
|
13
21
|
/** The truncated content */
|
|
14
22
|
content: string;
|
package/dist/tools/truncate.js
CHANGED
|
@@ -9,6 +9,14 @@
|
|
|
9
9
|
*/
|
|
10
10
|
export const DEFAULT_MAX_LINES = 2000;
|
|
11
11
|
export const DEFAULT_MAX_BYTES = 50 * 1024; // 50KB
|
|
12
|
+
/**
|
|
13
|
+
* Upper bound for a file read/sent as base64 in one `sh -c` (fix plan §2.3). `base64` inflates a
|
|
14
|
+
* file to 4/3 of its size, and the executor caps captured stdout at 10MB -- above this threshold
|
|
15
|
+
* the encoded output would be silently cut mid-stream, producing a buffer that still decodes (so
|
|
16
|
+
* failure is invisible) but is corrupt. 5MB leaves headroom for the 4/3 blow-up plus protocol
|
|
17
|
+
* overhead. A code constant, not a settings.json key, per CLAUDE.md's rule for numeric thresholds.
|
|
18
|
+
*/
|
|
19
|
+
export const MAX_INLINE_BINARY_BYTES = 5 * 1024 * 1024;
|
|
12
20
|
/**
|
|
13
21
|
* Format bytes as human-readable size.
|
|
14
22
|
*/
|
package/dist/tools/web-fetch.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Type } from "typebox";
|
|
2
|
+
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
2
3
|
import { resolveWebFetchRequest } from "../web/config.js";
|
|
3
4
|
import { runWebFetch } from "../web/fetch.js";
|
|
4
5
|
import { formatFetchedText, UNTRUSTED_WEB_CONTENT_BANNER } from "../web/format.js";
|
|
@@ -61,8 +62,15 @@ export function createWebFetchTool(options) {
|
|
|
61
62
|
const displayMaxChars = request.maxChars;
|
|
62
63
|
const startOffset = offset && offset > 0 ? offset : 0;
|
|
63
64
|
// Cache is per-channel; when no channelDir is available (e.g. sub-agent path) fall back to a
|
|
64
|
-
// plain single-shot fetch with the requested maxChars.
|
|
65
|
+
// plain single-shot fetch with the requested maxChars. An `offset` here would otherwise be
|
|
66
|
+
// silently dropped -- the caller gets the first screen back with no way to tell "reached
|
|
67
|
+
// the end" from "pagination just doesn't work here" (fix plan §4.5), and can spin retrying
|
|
68
|
+
// the same offset forever.
|
|
65
69
|
if (!options.channelDir) {
|
|
70
|
+
if (startOffset > 0) {
|
|
71
|
+
throw new RecoverableToolError("This context does not support web_fetch pagination (no per-channel cache available); " +
|
|
72
|
+
"offset is ignored here. Increase maxChars instead, or have the main agent fetch the page.");
|
|
73
|
+
}
|
|
66
74
|
return runWebFetch({
|
|
67
75
|
webConfig: options.webConfig,
|
|
68
76
|
securityConfig: options.securityConfig,
|
|
@@ -42,7 +42,17 @@ export async function writeContent(executor, path, content, signal, options) {
|
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
44
|
const dirPrefix = createParentDir ? `mkdir -p ${shellEscape(getDir(path))} && ` : "";
|
|
45
|
-
|
|
45
|
+
// Atomic write via a same-directory temp file + rename (fix plan §4.1): `cat > path` truncates
|
|
46
|
+
// before writing, so a process death or full disk mid-write leaves a corrupted file. `cp -p`
|
|
47
|
+
// copies the existing file's permission bits onto the temp file first -- `mv` onto an existing
|
|
48
|
+
// path otherwise keeps the *destination's* inode and mode, but a fresh temp file created by the
|
|
49
|
+
// shell has its own default mode, and simply overwriting via a new inode would silently strip
|
|
50
|
+
// an executable file's permission bit on its very next edit.
|
|
51
|
+
const tempPath = `${path}.pipiclaw-tmp`;
|
|
52
|
+
const script = `${dirPrefix}tmp=${shellEscape(tempPath)}; ` +
|
|
53
|
+
`[ -f ${shellEscape(path)} ] && cp -p ${shellEscape(path)} "$tmp" 2>/dev/null; ` +
|
|
54
|
+
`cat > "$tmp" && mv -f "$tmp" ${shellEscape(path)}`;
|
|
55
|
+
const result = await executor.exec(script, {
|
|
46
56
|
signal,
|
|
47
57
|
stdin: content,
|
|
48
58
|
});
|
package/dist/tui/app.js
CHANGED
|
@@ -131,7 +131,7 @@ export async function runTuiApp(options) {
|
|
|
131
131
|
traits,
|
|
132
132
|
channelId,
|
|
133
133
|
userName: safeUserName(),
|
|
134
|
-
renderHelp: () => renderBuiltInHelp(),
|
|
134
|
+
renderHelp: (args) => renderBuiltInHelp(args),
|
|
135
135
|
renderUsage: async (args) => renderUsageReport(getUsageLedger(), channelId, parseUsageMode(args), new Date()),
|
|
136
136
|
runEvents: (args) => handleEventsCommand({ args, workspaceDir: paths.workspaceDir, historyPath: paths.eventHistoryPath }),
|
|
137
137
|
runTasks: (args) => handleTasksCommand({
|
package/dist/tui/commands.d.ts
CHANGED
|
@@ -33,7 +33,7 @@ export type DispatchOutcome =
|
|
|
33
33
|
text?: string;
|
|
34
34
|
};
|
|
35
35
|
export interface DispatchDeps {
|
|
36
|
-
renderHelp(): string;
|
|
36
|
+
renderHelp(args?: string): string;
|
|
37
37
|
renderStatus(): string;
|
|
38
38
|
renderContext(args: string): string;
|
|
39
39
|
renderUsage(args: string): Promise<string>;
|
package/dist/tui/commands.js
CHANGED
|
@@ -28,7 +28,7 @@ export async function dispatch(input, deps) {
|
|
|
28
28
|
}
|
|
29
29
|
switch (command.name) {
|
|
30
30
|
case "help":
|
|
31
|
-
return { kind: "reply", text: deps.renderHelp() };
|
|
31
|
+
return { kind: "reply", text: deps.renderHelp(command.args) };
|
|
32
32
|
case "status":
|
|
33
33
|
return { kind: "reply", text: deps.renderStatus() };
|
|
34
34
|
case "context":
|
|
@@ -18,7 +18,7 @@ export interface TurnControllerDeps {
|
|
|
18
18
|
channelId: string;
|
|
19
19
|
userName: string;
|
|
20
20
|
/** Info commands that do not depend on run state. */
|
|
21
|
-
renderHelp: () => string;
|
|
21
|
+
renderHelp: (args?: string) => string;
|
|
22
22
|
renderUsage: (args: string) => Promise<string>;
|
|
23
23
|
runEvents: (args: string) => Promise<string>;
|
|
24
24
|
runTasks: (args: string) => Promise<string>;
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* Collaborators (runner, frontend, store) are injected so the machine can be
|
|
7
7
|
* unit-tested with fakes and a fake clock. `app.ts` builds the real ones.
|
|
8
8
|
*/
|
|
9
|
-
import { formatUnknownCommandMessage, slashCommandName } from "../agent/commands.js";
|
|
9
|
+
import { formatBusyCommandList, formatUnknownCommandMessage, isSessionCommandName, slashCommandName, } from "../agent/commands.js";
|
|
10
10
|
import { renderStatus } from "../agent/status-render.js";
|
|
11
11
|
import * as log from "../log.js";
|
|
12
12
|
import { formatLocalTime } from "../shared/local-time.js";
|
|
@@ -116,15 +116,25 @@ export class TurnController {
|
|
|
116
116
|
case "steer":
|
|
117
117
|
await this.applyText(outcome.text);
|
|
118
118
|
return;
|
|
119
|
-
case "run":
|
|
119
|
+
case "run": {
|
|
120
120
|
// Reject an unknown slash command rather than steering/running its raw
|
|
121
121
|
// text. Session commands, skills, and prompt templates pass through.
|
|
122
|
-
|
|
123
|
-
|
|
122
|
+
const name = outcome.text.trim().startsWith("/") ? slashCommandName(outcome.text) : null;
|
|
123
|
+
if (name && !this.deps.runner.isKnownSlashCommand(outcome.text)) {
|
|
124
|
+
this.deps.frontend.showFinal(formatUnknownCommandMessage(name));
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
// Session commands (`/model`, `/compact`, …) run inside the SDK command extension
|
|
128
|
+
// and need the idle session layer — mid-turn they must be rejected outright, not
|
|
129
|
+
// steered into the running turn as literal text (review 2026-08-24 §1.6; matches
|
|
130
|
+
// the DingTalk busy refusal in dingtalk.ts).
|
|
131
|
+
if (name && isSessionCommandName(name) && this.deps.runner.isBusy()) {
|
|
132
|
+
this.deps.frontend.showFinal(`当前已有回合在运行。运行中可用:${formatBusyCommandList()}。会话命令(\`/model\`、\`/compact\`、\`/session\`)需要等空闲后再用。`);
|
|
124
133
|
return;
|
|
125
134
|
}
|
|
126
135
|
await this.applyText(outcome.text);
|
|
127
136
|
return;
|
|
137
|
+
}
|
|
128
138
|
}
|
|
129
139
|
}
|
|
130
140
|
/** A plain message or /steer: steer the in-flight turn, else start a fresh one. */
|
package/dist/usage/render.js
CHANGED
|
@@ -65,36 +65,38 @@ async function renderWindow(window, ledger, channelId) {
|
|
|
65
65
|
ledger.summarize({ since: window.since, until: window.until }),
|
|
66
66
|
ledger.summarize({ since: window.since, until: window.until, channelId }),
|
|
67
67
|
]);
|
|
68
|
-
const lines = [
|
|
68
|
+
const lines = [`**${window.title}**`];
|
|
69
69
|
if (global.entryCount === 0) {
|
|
70
70
|
lines.push("暂无用量记录。");
|
|
71
71
|
return lines.join("\n");
|
|
72
72
|
}
|
|
73
73
|
// Tokens are reported next to cost because a local or pricing-less model bills nothing while
|
|
74
74
|
// still consuming context — "$0.0000" alone would read as "nothing happened".
|
|
75
|
-
|
|
75
|
+
let channelLine = `- 本频道:${money(channel.totalCost)} · ${tokens(channel.totalTokens)}`;
|
|
76
76
|
const channelKinds = renderKindBreakdown(channel);
|
|
77
77
|
if (channelKinds) {
|
|
78
|
-
|
|
78
|
+
channelLine += ` · ${channelKinds}`;
|
|
79
79
|
}
|
|
80
80
|
const channelUnknown = unknownNote(channel);
|
|
81
81
|
if (channelUnknown) {
|
|
82
|
-
|
|
82
|
+
channelLine += channelUnknown;
|
|
83
83
|
}
|
|
84
|
+
lines.push(channelLine);
|
|
84
85
|
const channelCount = Object.keys(global.byChannel).length;
|
|
85
|
-
|
|
86
|
+
let globalLine = `- 全局:${money(global.totalCost)} · ${tokens(global.totalTokens)},覆盖 ${channelCount} 个频道`;
|
|
86
87
|
const topModels = topEntries(global.byModel, 3);
|
|
87
88
|
if (topModels.length > 0) {
|
|
88
|
-
|
|
89
|
+
globalLine += ` · 用量最高:${topModels.map(([model, cost]) => `${model} ${money(cost)}`).join(",")}`;
|
|
89
90
|
}
|
|
90
91
|
const globalUnknown = unknownNote(global);
|
|
91
92
|
if (globalUnknown) {
|
|
92
|
-
|
|
93
|
+
globalLine += globalUnknown;
|
|
93
94
|
}
|
|
95
|
+
lines.push(globalLine);
|
|
94
96
|
return lines.join("\n");
|
|
95
97
|
}
|
|
96
98
|
export async function renderUsageReport(ledger, channelId, mode, now) {
|
|
97
99
|
const windows = usageWindows(mode, now);
|
|
98
100
|
const rendered = await Promise.all(windows.map((window) => renderWindow(window, ledger, channelId)));
|
|
99
|
-
return
|
|
101
|
+
return `**用量**\n\n${rendered.join("\n\n")}`;
|
|
100
102
|
}
|
|
@@ -64,6 +64,8 @@ reviewer 发现的问题回流给产出角色;verifier 失败回流给 builder
|
|
|
64
64
|
|
|
65
65
|
`builder` / `builder-hard` 仍用 Claude 的 `--dangerously-skip-permissions`,因为它们需要非交互地完成实现;这是本目录权限最高的默认配置。务必在可信 checkout、最小权限宿主账号中使用。角色文件只声明 `model` 和 `thinkingLevel`,具体的 `--model` / `--effort` 参数由 claude-code harness 自动拼接,不应重复写进 `command`。
|
|
66
66
|
|
|
67
|
+
**每个角色都应显式写 `thinkingLevel`**(本目录全部 11 个模板均已如此,见上表),不要依赖隐藏默认值——内置委派未声明时默认 `medium`,但外部 work 角色未声明时**不追加任何推理参数**,沿用该 CLI 自己的配置(`~/.claude/settings.json` / `~/.codex/config.toml` 等);只有 `purpose=verify` 的外部角色仍会兜底 `medium`。可复用的角色请显式写,让行为不随宿主机的本地配置漂移。
|
|
68
|
+
|
|
67
69
|
## 使用原则
|
|
68
70
|
|
|
69
71
|
- `description` 会进入主代理的子代理目录,必须写清楚「何时使用、何时不用、调用前提、是否修改状态、大概多重」。这是路由的主要依据。
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oyasmi/pipiclaw",
|
|
3
|
-
"version": "0.9.1
|
|
3
|
+
"version": "0.9.1",
|
|
4
4
|
"description": "An AI assistant runtime for coding and team workflows, with DingTalk AI Cards, sub-agents, memory, and scheduled events.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -38,7 +38,8 @@
|
|
|
38
38
|
"eval:promote": "npm run eval:build && node dist-evals/evals/harness/promote.js",
|
|
39
39
|
"test:coverage": "vitest --run --coverage",
|
|
40
40
|
"check": "npm run lint && npm run typecheck && npm run deadcode && npm run test",
|
|
41
|
-
"prepublishOnly": "npm run clean && npm run build && npm run check"
|
|
41
|
+
"prepublishOnly": "npm run clean && npm run build && npm run check",
|
|
42
|
+
"test:evals": "vitest --run --config vitest.config.evals.ts"
|
|
42
43
|
},
|
|
43
44
|
"dependencies": {
|
|
44
45
|
"@earendil-works/pi-agent-core": "0.83.0",
|