@oyasmi/pipiclaw 0.9.1-beta.1 → 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 -1
- package/dist/agent/channel-runner.js +42 -15
- 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/runner-factory.d.ts +0 -2
- 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/memory/task-digest.js +0 -2
- package/dist/playbooks/agent-delegation.md +32 -24
- 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 -38
- package/dist/playbooks/task-planning.md +18 -20
- package/dist/runtime/app-home.d.ts +6 -0
- package/dist/runtime/app-home.js +15 -6
- package/dist/runtime/bootstrap.d.ts +1 -1
- package/dist/runtime/bootstrap.js +57 -62
- package/dist/runtime/channel-context.d.ts +2 -1
- package/dist/runtime/channel-event.d.ts +0 -6
- 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 +38 -1
- package/dist/runtime/task-commands.js +135 -234
- package/dist/runtime/task-driver.d.ts +1 -3
- package/dist/runtime/task-driver.js +34 -40
- package/dist/runtime/task-migration.d.ts +7 -6
- package/dist/runtime/task-migration.js +85 -19
- package/dist/runtime/task-wake.d.ts +3 -5
- package/dist/runtime/task-wake.js +7 -15
- 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 +72 -2
- package/dist/subagents/runs.js +28 -3
- package/dist/subagents/tool.d.ts +11 -0
- package/dist/subagents/tool.js +89 -55
- package/dist/subagents/verification-outcome.js +17 -10
- package/dist/tasks/control.d.ts +18 -67
- package/dist/tasks/control.js +44 -176
- package/dist/tasks/ledger.d.ts +7 -13
- package/dist/tasks/ledger.js +13 -49
- package/dist/tasks/store.d.ts +15 -48
- package/dist/tasks/store.js +22 -154
- package/dist/tasks/transitions.d.ts +3 -4
- package/dist/tasks/transitions.js +8 -27
- 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.d.ts +0 -2
- package/dist/tools/index.js +6 -1
- 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/registry.d.ts +0 -1
- package/dist/tools/registry.js +0 -1
- 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/subagent-manage.d.ts +8 -1
- package/dist/tools/subagent-manage.js +77 -7
- package/dist/tools/task-manage/lifecycle.js +19 -17
- package/dist/tools/task-manage/schema.d.ts +2 -6
- package/dist/tools/task-manage/schema.js +4 -17
- package/dist/tools/task-manage/shared.js +1 -6
- package/dist/tools/task-manage/types.d.ts +0 -3
- package/dist/tools/task-manage/verification.d.ts +9 -6
- package/dist/tools/task-manage/verification.js +19 -71
- package/dist/tools/task-manage.d.ts +1 -1
- package/dist/tools/task-manage.js +3 -5
- 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/ledger.d.ts +4 -0
- package/dist/usage/ledger.js +3 -0
- package/dist/usage/render.js +10 -8
- package/examples/sub-agents/README.md +2 -0
- package/package.json +3 -2
package/dist/tools/edit.js
CHANGED
|
@@ -3,6 +3,7 @@ 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
8
|
import { writeContent } from "./write-content.js";
|
|
8
9
|
/**
|
|
@@ -144,17 +145,17 @@ export function createEditTool(executor, options = {}) {
|
|
|
144
145
|
// Read the file
|
|
145
146
|
const readResult = await executor.exec(`cat ${shellEscape(path)}`, { signal });
|
|
146
147
|
if (readResult.code !== 0) {
|
|
147
|
-
throw new
|
|
148
|
+
throw new RecoverableToolError(readResult.stderr || `File not found: ${path}`);
|
|
148
149
|
}
|
|
149
150
|
const content = readResult.stdout;
|
|
150
151
|
// Check if old text exists
|
|
151
152
|
if (!content.includes(oldText)) {
|
|
152
|
-
throw new
|
|
153
|
+
throw new RecoverableToolError(`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`);
|
|
153
154
|
}
|
|
154
155
|
// Count occurrences
|
|
155
156
|
const occurrences = content.split(oldText).length - 1;
|
|
156
157
|
if (occurrences > 1 && !replaceAll) {
|
|
157
|
-
throw new
|
|
158
|
+
throw new RecoverableToolError(`Found ${occurrences} occurrences of the text in ${path}. The text must be unique, or pass replaceAll: true to replace all of them. Please provide more context to make it unique.`);
|
|
158
159
|
}
|
|
159
160
|
// Perform replacement
|
|
160
161
|
let newContent;
|
|
@@ -174,11 +175,23 @@ export function createEditTool(executor, options = {}) {
|
|
|
174
175
|
`The bug is somewhere else — re-read the file to verify the anchor text before editing again. ` +
|
|
175
176
|
`Do NOT widen oldText or add lines to force a match.`);
|
|
176
177
|
}
|
|
177
|
-
throw new
|
|
178
|
+
throw new RecoverableToolError(`No changes made to ${path}: oldText and newText are byte-identical at the match, so the replacement produced no change. ` +
|
|
178
179
|
`Re-read the file to confirm what actually needs changing before editing again.`);
|
|
179
180
|
}
|
|
180
181
|
// A real edit breaks any no-op streak.
|
|
181
182
|
noopCounts.clear();
|
|
183
|
+
// Re-read immediately before writing back and compare against what was read at the top of
|
|
184
|
+
// this call (fix plan §2.4/§4.2): a background job, an external agent, or a concurrent
|
|
185
|
+
// `bash`/`edit` call (none of which the workspace write lease protects for the caller's own
|
|
186
|
+
// tool calls -- only inter-delegation writes) can change the file in between. Without this,
|
|
187
|
+
// the write below would silently clobber whatever changed it, keeping only this call's
|
|
188
|
+
// edit and discarding the other writer's. This narrows the race to the read-compare-write
|
|
189
|
+
// gap itself rather than closing it -- cheap insurance, not a lock.
|
|
190
|
+
const recheck = await executor.exec(`cat ${shellEscape(path)}`, { signal });
|
|
191
|
+
if (recheck.code === 0 && recheck.stdout !== content) {
|
|
192
|
+
throw new RecoverableToolError(`${path} changed during this edit (likely a background job or another agent writing concurrently). ` +
|
|
193
|
+
"Re-read the file and re-apply the edit against its current content.");
|
|
194
|
+
}
|
|
182
195
|
// Write the file back
|
|
183
196
|
await writeContent(executor, path, newContent, signal, {
|
|
184
197
|
securityConfig,
|
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.d.ts
CHANGED
|
@@ -27,7 +27,5 @@ export interface CreatePipiclawToolsOptions {
|
|
|
27
27
|
toolsConfig?: PipiclawToolsConfig;
|
|
28
28
|
/** Transport-provided attachment port; when present, enables the `send_media` tool. */
|
|
29
29
|
mediaSender?: MediaSender;
|
|
30
|
-
/** Runtime-provided durable verifier dispatch. */
|
|
31
|
-
dispatchVerification?: (taskId: string) => Promise<boolean>;
|
|
32
30
|
}
|
|
33
31
|
export declare function createPipiclawTools(options: CreatePipiclawToolsOptions): AgentTool<any>[];
|
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.
|
|
@@ -38,7 +42,6 @@ export function createPipiclawTools(options) {
|
|
|
38
42
|
getSessionSearchSettings: options.getSessionSearchSettings,
|
|
39
43
|
memoryCandidateStore: options.memoryCandidateStore,
|
|
40
44
|
mediaSender: options.mediaSender,
|
|
41
|
-
dispatchVerification: options.dispatchVerification,
|
|
42
45
|
});
|
|
43
46
|
return [
|
|
44
47
|
...leafTools,
|
|
@@ -72,6 +75,8 @@ export function createPipiclawTools(options) {
|
|
|
72
75
|
channelDir: options.channelDir,
|
|
73
76
|
getSubAgentDiscovery: options.getSubAgentDiscovery,
|
|
74
77
|
workspaceDir: options.workspaceDir,
|
|
78
|
+
workingDirectory: options.projectScope.projectRoot,
|
|
79
|
+
projectBoundary: options.projectScope.boundary,
|
|
75
80
|
securityConfig,
|
|
76
81
|
// Spec 042 D7: follow_up builds its envelope through the same buildContextualBlocks
|
|
77
82
|
// the initial dispatch uses, which needs these to resolve a memory: relevant recall.
|
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/registry.d.ts
CHANGED
|
@@ -47,7 +47,6 @@ export interface ToolBuildContext {
|
|
|
47
47
|
* files. Gates the `send_media` tool; sub-agents never receive it.
|
|
48
48
|
*/
|
|
49
49
|
mediaSender?: MediaSender;
|
|
50
|
-
dispatchVerification?: (taskId: string) => Promise<boolean>;
|
|
51
50
|
}
|
|
52
51
|
export interface ToolRegistration {
|
|
53
52
|
/** Also the tool's `details.kind`: the name is the authoritative discriminator. */
|
package/dist/tools/registry.js
CHANGED
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;
|
|
@@ -7,7 +7,7 @@ import type { PipiclawMemoryRecallSettings } from "../settings.js";
|
|
|
7
7
|
import { type SubAgentDiscoveryResult } from "../subagents/discovery.js";
|
|
8
8
|
declare const subagentManageSchema: Type.TObject<{
|
|
9
9
|
label: Type.TString;
|
|
10
|
-
op: Type.TUnion<[Type.TLiteral<"list">, Type.TLiteral<"cancel">, Type.TLiteral<"follow_up">]>;
|
|
10
|
+
op: Type.TUnion<[Type.TLiteral<"list">, Type.TLiteral<"cancel">, Type.TLiteral<"follow_up">, Type.TLiteral<"show">]>;
|
|
11
11
|
runId: Type.TOptional<Type.TString>;
|
|
12
12
|
task: Type.TOptional<Type.TString>;
|
|
13
13
|
}>;
|
|
@@ -23,6 +23,13 @@ export interface SubAgentManageToolOptions {
|
|
|
23
23
|
*/
|
|
24
24
|
workspaceDir: string;
|
|
25
25
|
channelDir: string;
|
|
26
|
+
/**
|
|
27
|
+
* The current project scope, so `follow_up` can re-check a resumed run's `workingDirectory`
|
|
28
|
+
* against the boundary in effect *now* rather than trusting the one recorded at dispatch time
|
|
29
|
+
* (review 2026-08-23 §3.1) — `/project` can move `workingDirectory` between the two.
|
|
30
|
+
*/
|
|
31
|
+
workingDirectory?: string;
|
|
32
|
+
projectBoundary?: "project" | "unbounded";
|
|
26
33
|
/** Needed only for `follow_up`: re-resolves the role's current config by name. */
|
|
27
34
|
getSubAgentDiscovery?: () => SubAgentDiscoveryResult;
|
|
28
35
|
securityConfig?: SecurityConfig;
|