@oyasmi/pipiclaw 0.9.2-beta.3 → 0.9.2-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- package/dist/agent/channel-runner.d.ts +13 -18
- package/dist/agent/channel-runner.js +44 -90
- package/dist/agent/command-extension.js +1 -1
- package/dist/agent/context-budget.d.ts +8 -0
- package/dist/agent/context-budget.js +10 -2
- package/dist/agent/job-manager.d.ts +1 -1
- package/dist/agent/job-manager.js +6 -1
- package/dist/agent/prompt/builder.d.ts +0 -1
- package/dist/agent/prompt/builder.js +1 -14
- package/dist/agent/prompt/manifest.js +2 -1
- package/dist/agent/prompt/sections.js +1 -1
- package/dist/agent/runner-factory.d.ts +19 -1
- package/dist/agent/runner-factory.js +8 -1
- package/dist/agent/session-events.d.ts +2 -2
- package/dist/agent/turn-prompt.d.ts +35 -0
- package/dist/agent/turn-prompt.js +37 -0
- package/dist/agent/turn-recovery.js +1 -1
- package/dist/agent/turn-state.d.ts +60 -0
- package/dist/agent/turn-state.js +95 -0
- package/dist/agent/types.d.ts +3 -3
- package/dist/{runtime → channel}/channel-context.d.ts +6 -2
- package/dist/{runtime → channel}/channel-context.js +6 -2
- package/dist/channel/channel-paths.d.ts +16 -0
- package/dist/{runtime → channel}/channel-paths.js +20 -0
- package/dist/{agent/commands.d.ts → commands/catalog.d.ts} +16 -1
- package/dist/{agent/commands.js → commands/catalog.js} +30 -0
- package/dist/index.d.ts +1 -1
- package/dist/log.js +14 -5
- package/dist/main.js +29 -0
- package/dist/memory/commands.js +2 -2
- package/dist/memory/maintenance-state.d.ts +8 -0
- package/dist/memory/maintenance-state.js +47 -4
- package/dist/memory/scheduler.d.ts +6 -0
- package/dist/memory/scheduler.js +19 -16
- package/dist/playbooks/agent-delegation.md +2 -2
- package/dist/runtime/bootstrap.d.ts +2 -2
- package/dist/runtime/bootstrap.js +14 -6
- package/dist/runtime/delivery.d.ts +3 -3
- package/dist/runtime/dingtalk.d.ts +4 -4
- package/dist/runtime/dingtalk.js +2 -2
- package/dist/runtime/durable-dispatch.d.ts +7 -1
- package/dist/runtime/durable-dispatch.js +12 -2
- package/dist/runtime/event-commands.js +2 -2
- package/dist/runtime/events.d.ts +8 -1
- package/dist/runtime/events.js +15 -3
- package/dist/runtime/project-commands.js +2 -2
- package/dist/runtime/skill-commands.d.ts +27 -0
- package/dist/runtime/skill-commands.js +72 -0
- package/dist/runtime/subagent-commands.js +1 -1
- package/dist/runtime/task-commands.js +2 -2
- package/dist/runtime/task-driver.d.ts +5 -1
- package/dist/runtime/task-driver.js +13 -12
- package/dist/runtime/task-migration.js +3 -2
- package/dist/runtime/task-wake.d.ts +1 -1
- package/dist/runtime/task-wake.js +1 -1
- package/dist/settings.d.ts +1 -0
- package/dist/settings.js +69 -0
- package/dist/shared/token-estimate.d.ts +1 -0
- package/dist/shared/token-estimate.js +19 -0
- package/dist/subagents/runs.d.ts +9 -4
- package/dist/subagents/runs.js +107 -11
- package/dist/subagents/tool.js +4 -3
- package/dist/tools/glob-match.d.ts +25 -4
- package/dist/tools/glob-match.js +175 -53
- package/dist/tools/glob.js +5 -2
- package/dist/tools/index.d.ts +1 -1
- package/dist/tools/registry.d.ts +1 -1
- package/dist/tools/send-media.d.ts +1 -1
- package/dist/tools/skill.d.ts +15 -0
- package/dist/tools/skill.js +16 -8
- package/dist/tui/app.js +5 -3
- package/dist/tui/commands.d.ts +1 -0
- package/dist/tui/commands.js +3 -1
- package/dist/tui/terminal-context.d.ts +2 -2
- package/dist/tui/terminal-media-sender.d.ts +1 -1
- package/dist/tui/turn-controller.d.ts +2 -1
- package/dist/tui/turn-controller.js +2 -1
- package/examples/sub-agents/README.md +2 -2
- package/examples/sub-agents/explorer.md +4 -4
- package/examples/sub-agents/git-committer.md +3 -2
- package/examples/sub-agents/log-sifter.md +2 -2
- package/examples/sub-agents/verifier.md +1 -1
- package/examples/sub-agents/worker.md +3 -3
- package/package.json +1 -1
- package/dist/runtime/channel-paths.d.ts +0 -4
- /package/dist/{runtime → channel}/active-session-store.d.ts +0 -0
- /package/dist/{runtime → channel}/active-session-store.js +0 -0
- /package/dist/{runtime → channel}/channel-event.d.ts +0 -0
- /package/dist/{runtime → channel}/channel-event.js +0 -0
- /package/dist/{runtime → channel}/channel-index.d.ts +0 -0
- /package/dist/{runtime → channel}/channel-index.js +0 -0
- /package/dist/{runtime → channel}/project-scope-store.d.ts +0 -0
- /package/dist/{runtime → channel}/project-scope-store.js +0 -0
- /package/dist/{runtime → channel}/store.d.ts +0 -0
- /package/dist/{runtime → channel}/store.js +0 -0
- /package/dist/{agent → commands}/reply-limits.d.ts +0 -0
- /package/dist/{agent → commands}/reply-limits.js +0 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rough token estimate, shared by everything that has to reason about context size without
|
|
3
|
+
* calling a tokenizer. CJK runs about one token per character, Latin text about four characters
|
|
4
|
+
* per token; the provider's real tokenizer is the authority, and the usage ledger records what
|
|
5
|
+
* it billed.
|
|
6
|
+
*
|
|
7
|
+
* The script split matters wherever the estimate gates behavior rather than just reporting: a
|
|
8
|
+
* flat characters-per-token ratio tuned for Latin text underestimates Chinese input roughly
|
|
9
|
+
* threefold, so a budget check would clear a message that in fact does not fit.
|
|
10
|
+
*/
|
|
11
|
+
const CJK_REGEX = /\p{Script=Han}|\p{Script=Hiragana}|\p{Script=Katakana}|\p{Script=Hangul}/u;
|
|
12
|
+
export function estimateTokens(text) {
|
|
13
|
+
let cjk = 0;
|
|
14
|
+
for (const char of text) {
|
|
15
|
+
if (CJK_REGEX.test(char))
|
|
16
|
+
cjk++;
|
|
17
|
+
}
|
|
18
|
+
return Math.ceil(cjk + (text.length - cjk) / 4);
|
|
19
|
+
}
|
package/dist/subagents/runs.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { ChannelEvent } from "../
|
|
2
|
-
import type { ChannelStore } from "../
|
|
1
|
+
import type { ChannelEvent } from "../channel/channel-event.js";
|
|
2
|
+
import type { ChannelStore } from "../channel/store.js";
|
|
3
3
|
import { type UsageTotals } from "../shared/types.js";
|
|
4
4
|
import type { UsageLedger } from "../usage/ledger.js";
|
|
5
5
|
/**
|
|
@@ -216,7 +216,10 @@ export interface RunNotice {
|
|
|
216
216
|
}
|
|
217
217
|
export type RunNotifier = (channelId: string, notice: RunNotice) => void | Promise<void>;
|
|
218
218
|
export interface RunManagerOptions {
|
|
219
|
-
/**
|
|
219
|
+
/**
|
|
220
|
+
* Root of the per-channel record directories (`<stateDir>/<escaped channelId>/`, escaped by
|
|
221
|
+
* `getChannelDir`). Omit to skip persistence.
|
|
222
|
+
*/
|
|
220
223
|
stateDir?: string;
|
|
221
224
|
dispatch?: (event: ChannelEvent) => boolean | Promise<boolean>;
|
|
222
225
|
/** Best-effort out-of-band notice sink (see `RunNotice`). Never awaited by settlement or the
|
|
@@ -251,6 +254,7 @@ export declare class SubAgentRunManager {
|
|
|
251
254
|
private readonly externalProgressTails;
|
|
252
255
|
private readonly queue;
|
|
253
256
|
constructor(channelId: string, options: RunManagerOptions);
|
|
257
|
+
private recordDir;
|
|
254
258
|
private recordPath;
|
|
255
259
|
private persist;
|
|
256
260
|
/**
|
|
@@ -408,7 +412,8 @@ export declare function channelDelegationTaskIds(channelId: string): Set<string>
|
|
|
408
412
|
/**
|
|
409
413
|
* Re-adopt every channel's persisted runs at startup, settling any internal run still marked
|
|
410
414
|
* `running` as `lost` (D10.3). Channels are discovered from the state directory itself, exactly
|
|
411
|
-
* like `restoreChannelJobs
|
|
415
|
+
* like `restoreChannelJobs` — but by reading the records rather than trusting directory names,
|
|
416
|
+
* so a channel is adopted under the id the rest of the runtime can act on.
|
|
412
417
|
*/
|
|
413
418
|
export declare function restoreAllSubAgentRuns(): Promise<number>;
|
|
414
419
|
export {};
|
package/dist/subagents/runs.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { mkdir, readdir, readFile, rmdir, stat, unlink } from "node:fs/promises";
|
|
2
|
-
import { join } from "node:path";
|
|
1
|
+
import { mkdir, readdir, readFile, rename, rmdir, stat, unlink } from "node:fs/promises";
|
|
2
|
+
import { dirname, join, relative, sep } from "node:path";
|
|
3
|
+
import { getChannelDir, isChannelId } from "../channel/channel-paths.js";
|
|
3
4
|
import * as log from "../log.js";
|
|
4
5
|
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
5
6
|
import { formatDuration } from "../shared/duration.js";
|
|
@@ -151,8 +152,15 @@ export class SubAgentRunManager {
|
|
|
151
152
|
this.externalProgressTails = new Map();
|
|
152
153
|
this.queue = createSerialQueue();
|
|
153
154
|
}
|
|
155
|
+
recordDir() {
|
|
156
|
+
// `getChannelDir`, not a raw join: a DingTalk group id routinely contains `/`, which used
|
|
157
|
+
// to nest the records one directory deeper than the startup scan ever looked — so a
|
|
158
|
+
// restart silently abandoned every delegation run of every such channel.
|
|
159
|
+
return this.options.stateDir ? getChannelDir(this.options.stateDir, this.channelId) : undefined;
|
|
160
|
+
}
|
|
154
161
|
recordPath(runId) {
|
|
155
|
-
|
|
162
|
+
const dir = this.recordDir();
|
|
163
|
+
return dir ? join(dir, `${runId}.json`) : undefined;
|
|
156
164
|
}
|
|
157
165
|
async persist(record, required = false) {
|
|
158
166
|
const path = this.recordPath(record.runId);
|
|
@@ -719,10 +727,9 @@ export class SubAgentRunManager {
|
|
|
719
727
|
* without mutual exclusion.
|
|
720
728
|
*/
|
|
721
729
|
async restore() {
|
|
722
|
-
const
|
|
723
|
-
if (!
|
|
730
|
+
const dir = this.recordDir();
|
|
731
|
+
if (!dir)
|
|
724
732
|
return 0;
|
|
725
|
-
const dir = join(stateDir, this.channelId);
|
|
726
733
|
let filenames;
|
|
727
734
|
try {
|
|
728
735
|
filenames = (await readdir(dir)).filter((name) => name.endsWith(".json"));
|
|
@@ -1098,26 +1105,115 @@ export function getSubAgentRunManager(channelId) {
|
|
|
1098
1105
|
export function channelDelegationTaskIds(channelId) {
|
|
1099
1106
|
return managers.get(channelId)?.runningTaskIds() ?? new Set();
|
|
1100
1107
|
}
|
|
1108
|
+
/**
|
|
1109
|
+
* How deep the scan below looks for record files.
|
|
1110
|
+
*
|
|
1111
|
+
* Canonical records sit one level under the state root. Records written before the id was
|
|
1112
|
+
* escaped sit one level deeper per `/` in the channel id, and a base64 conversation id carries
|
|
1113
|
+
* very few; three is generous, and the bound keeps a corrupted or hand-made tree from turning
|
|
1114
|
+
* startup into an unbounded walk.
|
|
1115
|
+
*/
|
|
1116
|
+
const MAX_RECORD_SCAN_DEPTH = 3;
|
|
1117
|
+
/** Every directory under `root` that directly holds run records, canonical or not. */
|
|
1118
|
+
async function findRecordDirectories(root, dir = root, depth = 0) {
|
|
1119
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
1120
|
+
const found = entries.some((entry) => entry.isFile() && entry.name.endsWith(".json")) ? [dir] : [];
|
|
1121
|
+
if (depth >= MAX_RECORD_SCAN_DEPTH)
|
|
1122
|
+
return found;
|
|
1123
|
+
for (const entry of entries) {
|
|
1124
|
+
if (!entry.isDirectory())
|
|
1125
|
+
continue;
|
|
1126
|
+
try {
|
|
1127
|
+
found.push(...(await findRecordDirectories(root, join(dir, entry.name), depth + 1)));
|
|
1128
|
+
}
|
|
1129
|
+
catch (error) {
|
|
1130
|
+
// One unreadable subtree must not hide every other channel's runs.
|
|
1131
|
+
log.logWarning(`Failed to scan sub-agent run directory ${entry.name}`, errorMessage(error));
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
return found;
|
|
1135
|
+
}
|
|
1136
|
+
/**
|
|
1137
|
+
* The channel a directory of records belongs to, and the records that are not where they belong.
|
|
1138
|
+
*
|
|
1139
|
+
* The id is read out of the records themselves — the one lossless source, since a directory name
|
|
1140
|
+
* is the *escaped* id and `__` cannot be turned back into `/`. Records written before escaping
|
|
1141
|
+
* are moved to the canonical directory here, so a run started by an older build is adopted
|
|
1142
|
+
* rather than abandoned; without the move it would stay invisible to `restore()` forever, and an
|
|
1143
|
+
* external process would keep running with nothing supervising, settling or billing it.
|
|
1144
|
+
*/
|
|
1145
|
+
async function adoptRecordDirectory(stateDir, dir) {
|
|
1146
|
+
const filenames = (await readdir(dir)).filter((name) => name.endsWith(".json"));
|
|
1147
|
+
const channelIds = new Set();
|
|
1148
|
+
let moved = 0;
|
|
1149
|
+
for (const filename of filenames) {
|
|
1150
|
+
const path = join(dir, filename);
|
|
1151
|
+
let channelId;
|
|
1152
|
+
try {
|
|
1153
|
+
channelId = parseRunRecord(await readFile(path, "utf-8"))?.channelId;
|
|
1154
|
+
}
|
|
1155
|
+
catch {
|
|
1156
|
+
channelId = undefined;
|
|
1157
|
+
}
|
|
1158
|
+
// A record is only trusted to name its own directory if it is a well-formed id; anything
|
|
1159
|
+
// else keeps the path-derived fallback, which cannot escape the state root.
|
|
1160
|
+
if (!channelId || !isChannelId(channelId)) {
|
|
1161
|
+
channelIds.add(relative(stateDir, dir).split(sep).join("/"));
|
|
1162
|
+
continue;
|
|
1163
|
+
}
|
|
1164
|
+
channelIds.add(channelId);
|
|
1165
|
+
const canonicalDir = getChannelDir(stateDir, channelId);
|
|
1166
|
+
if (canonicalDir === dir)
|
|
1167
|
+
continue;
|
|
1168
|
+
try {
|
|
1169
|
+
await mkdir(canonicalDir, { recursive: true });
|
|
1170
|
+
await rename(path, join(canonicalDir, filename));
|
|
1171
|
+
moved++;
|
|
1172
|
+
}
|
|
1173
|
+
catch (error) {
|
|
1174
|
+
log.logWarning(`Failed to relocate sub-agent run record ${filename}`, errorMessage(error));
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
if (moved > 0) {
|
|
1178
|
+
log.logInfo(`Relocated ${moved} sub-agent run record(s) from ${relative(stateDir, dir)}`);
|
|
1179
|
+
// Tidy the directory the unescaped id created. `rmdir` refuses a non-empty one, which is
|
|
1180
|
+
// exactly the guard wanted: records that could not be moved keep their home.
|
|
1181
|
+
await rmdir(dir).catch(() => undefined);
|
|
1182
|
+
const parent = dirname(dir);
|
|
1183
|
+
if (parent !== stateDir)
|
|
1184
|
+
await rmdir(parent).catch(() => undefined);
|
|
1185
|
+
}
|
|
1186
|
+
return Array.from(channelIds);
|
|
1187
|
+
}
|
|
1101
1188
|
/**
|
|
1102
1189
|
* Re-adopt every channel's persisted runs at startup, settling any internal run still marked
|
|
1103
1190
|
* `running` as `lost` (D10.3). Channels are discovered from the state directory itself, exactly
|
|
1104
|
-
* like `restoreChannelJobs
|
|
1191
|
+
* like `restoreChannelJobs` — but by reading the records rather than trusting directory names,
|
|
1192
|
+
* so a channel is adopted under the id the rest of the runtime can act on.
|
|
1105
1193
|
*/
|
|
1106
1194
|
export async function restoreAllSubAgentRuns() {
|
|
1107
1195
|
const stateDir = runtimeConfig.stateDir;
|
|
1108
1196
|
if (!stateDir)
|
|
1109
1197
|
return 0;
|
|
1110
|
-
|
|
1198
|
+
const channelIds = new Set();
|
|
1199
|
+
let recordDirs;
|
|
1111
1200
|
try {
|
|
1112
1201
|
await mkdir(stateDir, { recursive: true });
|
|
1113
|
-
|
|
1114
|
-
.filter((entry) => entry.isDirectory())
|
|
1115
|
-
.map((entry) => entry.name);
|
|
1202
|
+
recordDirs = await findRecordDirectories(stateDir);
|
|
1116
1203
|
}
|
|
1117
1204
|
catch (error) {
|
|
1118
1205
|
log.logWarning("Failed to scan persisted sub-agent runs", errorMessage(error));
|
|
1119
1206
|
return 0;
|
|
1120
1207
|
}
|
|
1208
|
+
for (const dir of recordDirs) {
|
|
1209
|
+
try {
|
|
1210
|
+
for (const channelId of await adoptRecordDirectory(stateDir, dir))
|
|
1211
|
+
channelIds.add(channelId);
|
|
1212
|
+
}
|
|
1213
|
+
catch (error) {
|
|
1214
|
+
log.logWarning(`Failed to adopt sub-agent run records in ${relative(stateDir, dir)}`, errorMessage(error));
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1121
1217
|
let restored = 0;
|
|
1122
1218
|
for (const channelId of channelIds) {
|
|
1123
1219
|
restored += await getSubAgentRunManager(channelId).restore();
|
package/dist/subagents/tool.js
CHANGED
|
@@ -5,6 +5,7 @@ import { Agent } from "@earendil-works/pi-agent-core";
|
|
|
5
5
|
import { clampThinkingLevel, streamSimple } from "@earendil-works/pi-ai/compat";
|
|
6
6
|
import { convertToLlm } from "@earendil-works/pi-coding-agent";
|
|
7
7
|
import { Type } from "typebox";
|
|
8
|
+
import { getChannelDir } from "../channel/channel-paths.js";
|
|
8
9
|
import * as log from "../log.js";
|
|
9
10
|
import { getChannelHistoryPath, getChannelMemoryPath, getChannelSessionPath, readChannelSession, } from "../memory/files.js";
|
|
10
11
|
import { recallRelevantMemory } from "../memory/recall.js";
|
|
@@ -358,7 +359,7 @@ export function buildSubAgentTask(task, config, runtimeContext, contextBlocks, r
|
|
|
358
359
|
`Runtime context:`,
|
|
359
360
|
`- Workspace root: ${runtimeContext.workspaceDir}`,
|
|
360
361
|
`- Channel id: ${runtimeContext.channelId}`,
|
|
361
|
-
`- Channel directory: ${runtimeContext.workspaceDir
|
|
362
|
+
`- Channel directory: ${getChannelDir(runtimeContext.workspaceDir, runtimeContext.channelId)}`,
|
|
362
363
|
`- Working directory: ${runContext.workingDirectory}`,
|
|
363
364
|
`- Artifact directory: ${runContext.artifactDir}`,
|
|
364
365
|
`- Your configured role: ${config.name}`,
|
|
@@ -371,7 +372,7 @@ export function buildSubAgentTask(task, config, runtimeContext, contextBlocks, r
|
|
|
371
372
|
}
|
|
372
373
|
lines.push("", `Task:`, taskText);
|
|
373
374
|
if (runContext.purpose === "verify") {
|
|
374
|
-
const taskPath = join(runtimeContext.workspaceDir, runtimeContext.channelId, "tasks", `${runContext.taskId}.md`);
|
|
375
|
+
const taskPath = join(getChannelDir(runtimeContext.workspaceDir, runtimeContext.channelId), "tasks", `${runContext.taskId}.md`);
|
|
375
376
|
lines.push("", buildVerificationProtocol(taskPath));
|
|
376
377
|
}
|
|
377
378
|
return lines.join("\n");
|
|
@@ -1044,7 +1045,7 @@ export function createSubAgentInlineTool(options) {
|
|
|
1044
1045
|
return {
|
|
1045
1046
|
name: "subagent_inline",
|
|
1046
1047
|
label: "subagent_inline",
|
|
1047
|
-
description: "
|
|
1048
|
+
description: "Advanced fallback only, not the default: use `subagent` first whenever any configured role in the workspace `sub-agents/` can do the work. `subagent` is the normal role-based path: pass its `agent` and complete `task`; the role file supplies the tools, model, budget and context policy. Use `subagent_inline` only when no configured role is suitable. It is a raw one-shot meta-executor, not a shorthand for `subagent`: there is no role file to supply those settings. Build a complete valid inline call yourself — `task` and `systemPrompt` are required; choose valid values for any needed `tools`, `model`, `effort`, `context`, `thinkingLevel`, `mutates`, `workingDirectory`, `purpose` and `taskId` fields. Do not send a partial role-style payload or choose this tool just because it is available. Sub-agents never receive the subagent tool, so they cannot create nested agents.",
|
|
1048
1049
|
parameters: subagentInlineSchema,
|
|
1049
1050
|
execute: async (_toolCallId, params, signal, onUpdate) => {
|
|
1050
1051
|
if (signal?.aborted) {
|
|
@@ -1,11 +1,32 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Compile a shell-style glob pattern into a
|
|
2
|
+
* Compile a shell-style glob pattern into a matcher for POSIX-relative file paths.
|
|
3
3
|
*
|
|
4
4
|
* Semantics follow the convention the model already knows from `find`/`fd`/Claude Code's own glob
|
|
5
5
|
* tool: a pattern with no `/` matches the *basename* at any depth (so `*.ts` searches the whole
|
|
6
6
|
* tree, not just its top level); `**` matches any number of path segments, including zero, when it
|
|
7
|
-
* sits between (or at the start/end of) path separators; `{a,b}` is brace-expanded into
|
|
8
|
-
*
|
|
7
|
+
* sits between (or at the start/end of) path separators; `{a,b}` is brace-expanded into
|
|
8
|
+
* alternatives. Matching is always case-sensitive and always against `/`-joined relative paths —
|
|
9
9
|
* callers never see platform separators.
|
|
10
|
+
*
|
|
11
|
+
* ## Why this is not a regular expression
|
|
12
|
+
*
|
|
13
|
+
* The obvious implementation compiles the whole pattern into one `RegExp` — and that regex is a
|
|
14
|
+
* denial-of-service primitive, because the pattern is a model-supplied argument and the matcher
|
|
15
|
+
* runs once per walked file on the event loop. Nested unbounded quantifiers backtrack
|
|
16
|
+
* exponentially on a *near* miss: `**/` repeated ten times took ~2s per path, `{*,*}` repeated
|
|
17
|
+
* five times ~145ms and rising by ~17x per group, and `*a*a*a*a*a*a*a*azzz` — nineteen
|
|
18
|
+
* characters, no `**`, no braces — took **32 seconds** against a sixty-character name. Folding
|
|
19
|
+
* `**/` or capping the pattern length only removes particular spellings; the blow-up belongs to
|
|
20
|
+
* the whole class of "several stars separated by literals", which no length bound can exclude.
|
|
21
|
+
*
|
|
22
|
+
* So the pattern is matched structurally instead: braces expand to a bounded set of variants,
|
|
23
|
+
* each variant is split into path segments, and both the segment sequence and each segment's
|
|
24
|
+
* characters are matched by the classic single-backtrack-point wildcard algorithm. That is
|
|
25
|
+
* O(n·m) in the worst case with no nested quantifiers, so every shape above matches in
|
|
26
|
+
* microseconds and no pattern can stall the walk.
|
|
10
27
|
*/
|
|
11
|
-
export
|
|
28
|
+
export interface GlobMatcher {
|
|
29
|
+
/** True when `path` — a `/`-joined path relative to the walk root — matches the pattern. */
|
|
30
|
+
test(path: string): boolean;
|
|
31
|
+
}
|
|
32
|
+
export declare function compileGlobPattern(pattern: string): GlobMatcher;
|
package/dist/tools/glob-match.js
CHANGED
|
@@ -1,75 +1,197 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Compile a shell-style glob pattern into a
|
|
2
|
+
* Compile a shell-style glob pattern into a matcher for POSIX-relative file paths.
|
|
3
3
|
*
|
|
4
4
|
* Semantics follow the convention the model already knows from `find`/`fd`/Claude Code's own glob
|
|
5
5
|
* tool: a pattern with no `/` matches the *basename* at any depth (so `*.ts` searches the whole
|
|
6
6
|
* tree, not just its top level); `**` matches any number of path segments, including zero, when it
|
|
7
|
-
* sits between (or at the start/end of) path separators; `{a,b}` is brace-expanded into
|
|
8
|
-
*
|
|
7
|
+
* sits between (or at the start/end of) path separators; `{a,b}` is brace-expanded into
|
|
8
|
+
* alternatives. Matching is always case-sensitive and always against `/`-joined relative paths —
|
|
9
9
|
* callers never see platform separators.
|
|
10
|
+
*
|
|
11
|
+
* ## Why this is not a regular expression
|
|
12
|
+
*
|
|
13
|
+
* The obvious implementation compiles the whole pattern into one `RegExp` — and that regex is a
|
|
14
|
+
* denial-of-service primitive, because the pattern is a model-supplied argument and the matcher
|
|
15
|
+
* runs once per walked file on the event loop. Nested unbounded quantifiers backtrack
|
|
16
|
+
* exponentially on a *near* miss: `**/` repeated ten times took ~2s per path, `{*,*}` repeated
|
|
17
|
+
* five times ~145ms and rising by ~17x per group, and `*a*a*a*a*a*a*a*azzz` — nineteen
|
|
18
|
+
* characters, no `**`, no braces — took **32 seconds** against a sixty-character name. Folding
|
|
19
|
+
* `**/` or capping the pattern length only removes particular spellings; the blow-up belongs to
|
|
20
|
+
* the whole class of "several stars separated by literals", which no length bound can exclude.
|
|
21
|
+
*
|
|
22
|
+
* So the pattern is matched structurally instead: braces expand to a bounded set of variants,
|
|
23
|
+
* each variant is split into path segments, and both the segment sequence and each segment's
|
|
24
|
+
* characters are matched by the classic single-backtrack-point wildcard algorithm. That is
|
|
25
|
+
* O(n·m) in the worst case with no nested quantifiers, so every shape above matches in
|
|
26
|
+
* microseconds and no pattern can stall the walk.
|
|
10
27
|
*/
|
|
28
|
+
/** A pattern longer than this is a mistake or an attack; neither deserves a match attempt. */
|
|
29
|
+
const MAX_PATTERN_LENGTH = 512;
|
|
30
|
+
/** Brace expansion multiplies: `{a,b}` ten times over is 1024 variants of the same walk. */
|
|
31
|
+
const MAX_BRACE_VARIANTS = 64;
|
|
32
|
+
/** A path segment that is exactly `**`: any number of segments, including none. */
|
|
33
|
+
const GLOBSTAR = Symbol("globstar");
|
|
34
|
+
/** `*` inside a segment: any run of characters, not crossing a separator. */
|
|
35
|
+
const STAR = Symbol("star");
|
|
36
|
+
/** `?` inside a segment: exactly one character. */
|
|
37
|
+
const ANY = Symbol("any");
|
|
11
38
|
export function compileGlobPattern(pattern) {
|
|
12
|
-
|
|
13
|
-
|
|
39
|
+
if (pattern.length > MAX_PATTERN_LENGTH) {
|
|
40
|
+
throw new Error(`pattern is longer than ${MAX_PATTERN_LENGTH} characters`);
|
|
41
|
+
}
|
|
42
|
+
// The anchoring decision is made on the pattern as written, before expansion: `{src/a,b}`
|
|
43
|
+
// carries a separator and is therefore path-anchored for *both* of its alternatives.
|
|
44
|
+
const matchBasenameOnly = !pattern.includes("/");
|
|
45
|
+
const variants = expandBraces(pattern).map(compileVariant);
|
|
46
|
+
return {
|
|
47
|
+
test(path) {
|
|
48
|
+
const segments = matchBasenameOnly ? [path.slice(path.lastIndexOf("/") + 1)] : path.split("/");
|
|
49
|
+
return variants.some((variant) => matchVariant(variant, segments));
|
|
50
|
+
},
|
|
51
|
+
};
|
|
14
52
|
}
|
|
15
|
-
/**
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
53
|
+
/**
|
|
54
|
+
* Expand `{a,b}` alternations into concrete patterns, innermost group last so nesting works.
|
|
55
|
+
*
|
|
56
|
+
* Braces are located by depth-counted scanning rather than the first `}` found, so `{a,{b,c}}`
|
|
57
|
+
* and a comma inside a nested group are read the way the writer meant. An unmatched `{` stays a
|
|
58
|
+
* literal character, as it did before.
|
|
59
|
+
*/
|
|
60
|
+
function expandBraces(pattern) {
|
|
61
|
+
const open = findBraceGroup(pattern);
|
|
62
|
+
if (!open)
|
|
63
|
+
return [pattern];
|
|
64
|
+
const results = [];
|
|
65
|
+
for (const alternative of open.alternatives) {
|
|
66
|
+
for (const expanded of expandBraces(`${open.prefix}${alternative}${open.suffix}`)) {
|
|
67
|
+
results.push(expanded);
|
|
68
|
+
if (results.length > MAX_BRACE_VARIANTS) {
|
|
69
|
+
throw new Error(`brace expansion produces more than ${MAX_BRACE_VARIANTS} patterns`);
|
|
31
70
|
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return results;
|
|
74
|
+
}
|
|
75
|
+
function findBraceGroup(pattern) {
|
|
76
|
+
const start = pattern.indexOf("{");
|
|
77
|
+
if (start === -1)
|
|
78
|
+
return undefined;
|
|
79
|
+
let depth = 0;
|
|
80
|
+
const alternatives = [];
|
|
81
|
+
let current = "";
|
|
82
|
+
for (let i = start; i < pattern.length; i++) {
|
|
83
|
+
const char = pattern[i];
|
|
84
|
+
if (char === "{") {
|
|
85
|
+
depth++;
|
|
86
|
+
if (depth === 1)
|
|
87
|
+
continue; // the group's own opening brace is not content
|
|
88
|
+
}
|
|
89
|
+
else if (char === "}") {
|
|
90
|
+
depth--;
|
|
91
|
+
if (depth === 0) {
|
|
92
|
+
alternatives.push(current);
|
|
93
|
+
return { prefix: pattern.slice(0, start), alternatives, suffix: pattern.slice(i + 1) };
|
|
37
94
|
}
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
95
|
+
}
|
|
96
|
+
else if (char === "," && depth === 1) {
|
|
97
|
+
alternatives.push(current);
|
|
98
|
+
current = "";
|
|
41
99
|
continue;
|
|
42
100
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
101
|
+
current += char;
|
|
102
|
+
}
|
|
103
|
+
return undefined; // unbalanced `{` — leave it as a literal
|
|
104
|
+
}
|
|
105
|
+
function compileVariant(pattern) {
|
|
106
|
+
const rawSegments = pattern.split("/");
|
|
107
|
+
const segments = rawSegments.map((segment) => segment === "**" ? GLOBSTAR : compileSegment(segment));
|
|
108
|
+
const trailingGlobstar = segments.length > 1 && segments[segments.length - 1] === GLOBSTAR;
|
|
109
|
+
return { segments, trailingGlobstar };
|
|
110
|
+
}
|
|
111
|
+
function compileSegment(segment) {
|
|
112
|
+
const tokens = [];
|
|
113
|
+
for (const char of segment) {
|
|
114
|
+
if (char === "*") {
|
|
115
|
+
// Adjacent stars are the same star. A `**` that is not a whole segment (`a**b`) has
|
|
116
|
+
// always meant single-segment `*`, and collapsing keeps that without a second token.
|
|
117
|
+
if (tokens[tokens.length - 1] !== STAR)
|
|
118
|
+
tokens.push(STAR);
|
|
46
119
|
continue;
|
|
47
120
|
}
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
121
|
+
tokens.push(char === "?" ? ANY : char);
|
|
122
|
+
}
|
|
123
|
+
return tokens;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Match a segment sequence, with `**` as the only construct that can span segments.
|
|
127
|
+
*
|
|
128
|
+
* The single backtrack point (`starIndex`/`starSegment`) is what keeps this linear-ish: on a
|
|
129
|
+
* mismatch the matcher advances the most recent globstar by one segment instead of exploring
|
|
130
|
+
* every combination of every globstar, which is the search space a regex engine would walk.
|
|
131
|
+
*/
|
|
132
|
+
function matchVariant(variant, path) {
|
|
133
|
+
const { segments, trailingGlobstar } = variant;
|
|
134
|
+
// The trailing `**` is handled after the loop, so drop it here and require a remainder there.
|
|
135
|
+
const patternLength = trailingGlobstar ? segments.length - 1 : segments.length;
|
|
136
|
+
let patternIndex = 0;
|
|
137
|
+
let pathIndex = 0;
|
|
138
|
+
let starIndex = -1;
|
|
139
|
+
let starPathIndex = 0;
|
|
140
|
+
while (pathIndex < path.length) {
|
|
141
|
+
const segment = patternIndex < patternLength ? segments[patternIndex] : undefined;
|
|
142
|
+
// Pattern spent with path left over: a trailing `**` takes the whole remainder.
|
|
143
|
+
if (segment === undefined && trailingGlobstar)
|
|
144
|
+
break;
|
|
145
|
+
if (segment === GLOBSTAR) {
|
|
146
|
+
starIndex = patternIndex;
|
|
147
|
+
starPathIndex = pathIndex;
|
|
148
|
+
patternIndex++;
|
|
51
149
|
continue;
|
|
52
150
|
}
|
|
53
|
-
if (
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
out += escapeRegExpChar(ch);
|
|
57
|
-
i += 1;
|
|
58
|
-
continue;
|
|
59
|
-
}
|
|
60
|
-
const alternatives = pattern
|
|
61
|
-
.slice(i + 1, close)
|
|
62
|
-
.split(",")
|
|
63
|
-
.map((alt) => globToRegExpSource(alt));
|
|
64
|
-
out += `(?:${alternatives.join("|")})`;
|
|
65
|
-
i = close + 1;
|
|
151
|
+
if (segment !== undefined && matchSegment(segment, path[pathIndex])) {
|
|
152
|
+
patternIndex++;
|
|
153
|
+
pathIndex++;
|
|
66
154
|
continue;
|
|
67
155
|
}
|
|
68
|
-
|
|
69
|
-
|
|
156
|
+
if (starIndex === -1)
|
|
157
|
+
return false;
|
|
158
|
+
// Let the last globstar swallow one more segment and retry from just after it.
|
|
159
|
+
starPathIndex++;
|
|
160
|
+
pathIndex = starPathIndex;
|
|
161
|
+
patternIndex = starIndex + 1;
|
|
70
162
|
}
|
|
71
|
-
|
|
163
|
+
while (patternIndex < patternLength && segments[patternIndex] === GLOBSTAR)
|
|
164
|
+
patternIndex++;
|
|
165
|
+
if (patternIndex !== patternLength)
|
|
166
|
+
return false;
|
|
167
|
+
return trailingGlobstar ? pathIndex < path.length : pathIndex === path.length;
|
|
72
168
|
}
|
|
73
|
-
|
|
74
|
-
|
|
169
|
+
/** The same algorithm one level down: `*` is the backtrack point, `?` and literals advance. */
|
|
170
|
+
function matchSegment(tokens, text) {
|
|
171
|
+
let tokenIndex = 0;
|
|
172
|
+
let textIndex = 0;
|
|
173
|
+
let starIndex = -1;
|
|
174
|
+
let starTextIndex = 0;
|
|
175
|
+
while (textIndex < text.length) {
|
|
176
|
+
const token = tokenIndex < tokens.length ? tokens[tokenIndex] : undefined;
|
|
177
|
+
if (token === STAR) {
|
|
178
|
+
starIndex = tokenIndex;
|
|
179
|
+
starTextIndex = textIndex;
|
|
180
|
+
tokenIndex++;
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
if (token === ANY || (typeof token === "string" && token === text[textIndex])) {
|
|
184
|
+
tokenIndex++;
|
|
185
|
+
textIndex++;
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
if (starIndex === -1)
|
|
189
|
+
return false;
|
|
190
|
+
starTextIndex++;
|
|
191
|
+
textIndex = starTextIndex;
|
|
192
|
+
tokenIndex = starIndex + 1;
|
|
193
|
+
}
|
|
194
|
+
while (tokenIndex < tokens.length && tokens[tokenIndex] === STAR)
|
|
195
|
+
tokenIndex++;
|
|
196
|
+
return tokenIndex === tokens.length;
|
|
75
197
|
}
|
package/dist/tools/glob.js
CHANGED
|
@@ -3,6 +3,7 @@ import { Type } from "typebox";
|
|
|
3
3
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
4
4
|
import { checkPathGuard } from "../security/path-guard-check.js";
|
|
5
5
|
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
6
|
+
import { errorMessage } from "../shared/text-utils.js";
|
|
6
7
|
import { compileGlobPattern } from "./glob-match.js";
|
|
7
8
|
import { IGNORED_DIR_SEGMENTS } from "./ignore-dirs.js";
|
|
8
9
|
import { DEFAULT_MAX_BYTES, formatSize, truncateHead } from "./truncate.js";
|
|
@@ -52,8 +53,10 @@ export function createGlobTool(fileStore, options = {}) {
|
|
|
52
53
|
try {
|
|
53
54
|
matcher = compileGlobPattern(pattern);
|
|
54
55
|
}
|
|
55
|
-
catch {
|
|
56
|
-
|
|
56
|
+
catch (error) {
|
|
57
|
+
// The reason is part of the message: a pattern rejected for complexity is fixed by
|
|
58
|
+
// simplifying it, which "invalid pattern" alone does not tell the model.
|
|
59
|
+
throw new RecoverableToolError(`Invalid glob pattern: ${pattern} (${errorMessage(error)})`);
|
|
57
60
|
}
|
|
58
61
|
const walk = await fileStore.walkFiles(target, {
|
|
59
62
|
maxEntries: MAX_SCAN_ENTRIES,
|
package/dist/tools/index.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
|
2
2
|
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
3
|
+
import type { MediaSender } from "../channel/channel-context.js";
|
|
3
4
|
import type { Executor } from "../executor.js";
|
|
4
5
|
import type { FileStore } from "../file-store.js";
|
|
5
6
|
import type { MemoryCandidateStore } from "../memory/candidates.js";
|
|
6
|
-
import type { MediaSender } from "../runtime/channel-context.js";
|
|
7
7
|
import type { ProjectScope } from "../security/project-scope.js";
|
|
8
8
|
import type { SecurityConfig } from "../security/types.js";
|
|
9
9
|
import type { PipiclawMemoryRecallSettings, PipiclawSessionSearchSettings } from "../settings.js";
|
package/dist/tools/registry.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
|
2
2
|
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
3
3
|
import type { ChannelJobManager } from "../agent/job-manager.js";
|
|
4
|
+
import type { MediaSender } from "../channel/channel-context.js";
|
|
4
5
|
import type { Executor } from "../executor.js";
|
|
5
6
|
import type { FileStore } from "../file-store.js";
|
|
6
7
|
import type { MemoryCandidateStore } from "../memory/candidates.js";
|
|
7
|
-
import type { MediaSender } from "../runtime/channel-context.js";
|
|
8
8
|
import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
|
|
9
9
|
import type { PipiclawSessionSearchSettings } from "../settings.js";
|
|
10
10
|
import type { PipiclawToolsConfig, PipiclawWebToolsConfig } from "./config.js";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
|
2
2
|
import { Type } from "typebox";
|
|
3
|
+
import type { MediaSender } from "../channel/channel-context.js";
|
|
3
4
|
import type { FileStore } from "../file-store.js";
|
|
4
|
-
import type { MediaSender } from "../runtime/channel-context.js";
|
|
5
5
|
import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
|
|
6
6
|
declare const sendMediaSchema: Type.TObject<{
|
|
7
7
|
path: Type.TString;
|
package/dist/tools/skill.d.ts
CHANGED
|
@@ -27,5 +27,20 @@ export interface SkillToolOptions {
|
|
|
27
27
|
export declare function listWorkspaceSkills(options: {
|
|
28
28
|
workspaceDir: string;
|
|
29
29
|
}): Promise<WorkspaceSkillSummary[]>;
|
|
30
|
+
export interface WorkspaceSkillFile {
|
|
31
|
+
name: string;
|
|
32
|
+
/** The guard-resolved path actually opened — never the raw pre-guard path. */
|
|
33
|
+
path: string;
|
|
34
|
+
content: string;
|
|
35
|
+
truncated: boolean;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Load one skill's `SKILL.md` bytes through the same path-guard every other file read goes
|
|
39
|
+
* through. Shared by the `skill` tool's `read` action and the `/skills show` runtime command
|
|
40
|
+
* (`src/runtime/skill-commands.ts`) — a `SKILL.md` that is itself a symlink pointing outside
|
|
41
|
+
* `workspace/skills/` (planted via `bash ln -s`, not via `name` -- `resolveSkillPath` already
|
|
42
|
+
* confines that) is caught here in both callers instead of being read verbatim.
|
|
43
|
+
*/
|
|
44
|
+
export declare function loadWorkspaceSkillFile(options: SkillToolOptions, name: string): Promise<WorkspaceSkillFile>;
|
|
30
45
|
export declare function createSkillTool(options: SkillToolOptions): AgentTool<typeof skillSchema>;
|
|
31
46
|
export {};
|