@oyasmi/pipiclaw 0.9.1 → 0.9.2-beta.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 +2 -1
- package/dist/agent/channel-runner.js +9 -5
- package/dist/agent/effect-ledger.js +9 -2
- package/dist/agent/job-manager.d.ts +4 -0
- package/dist/agent/job-manager.js +17 -2
- package/dist/agent/prompt/manifest.d.ts +1 -1
- package/dist/agent/prompt/manifest.js +1 -1
- package/dist/agent/prompt/sections.js +8 -5
- package/dist/agent/session-events.d.ts +2 -0
- package/dist/agent/session-events.js +29 -14
- package/dist/agent/turn-recovery.js +2 -2
- package/dist/agent/type-guards.js +5 -1
- package/dist/agent/workspace-resources.d.ts +2 -2
- package/dist/agent/workspace-resources.js +41 -3
- package/dist/executor.d.ts +14 -0
- package/dist/executor.js +96 -24
- package/dist/file-store.d.ts +96 -0
- package/dist/file-store.js +189 -0
- package/dist/memory/consolidation.js +2 -26
- package/dist/memory/files.js +7 -7
- package/dist/memory/maintenance-jobs.js +2 -34
- package/dist/memory/maintenance-state.js +2 -1
- package/dist/memory/recall.d.ts +10 -0
- package/dist/memory/recall.js +15 -7
- package/dist/memory/session-search.js +6 -22
- package/dist/memory/transcript.d.ts +10 -0
- package/dist/memory/transcript.js +39 -0
- package/dist/playbooks/agent-delegation.md +6 -4
- package/dist/playbooks/background-jobs.md +1 -1
- package/dist/playbooks/catalog.d.ts +1 -1
- package/dist/playbooks/catalog.js +1 -1
- package/dist/playbooks/event-scheduling.md +2 -0
- package/dist/playbooks/memory-and-learning.md +11 -11
- package/dist/playbooks/runtime-orientation.md +3 -3
- package/dist/playbooks/task-driving.md +5 -5
- package/dist/playbooks/task-planning.md +5 -5
- package/dist/runtime/app-home.js +1 -1
- package/dist/runtime/bootstrap.js +10 -0
- package/dist/runtime/dingtalk.js +3 -2
- package/dist/runtime/durable-dispatch.d.ts +26 -1
- package/dist/runtime/durable-dispatch.js +51 -5
- package/dist/runtime/event-commands.js +7 -16
- package/dist/runtime/events.d.ts +4 -2
- package/dist/runtime/events.js +15 -20
- package/dist/runtime/subagent-commands.js +1 -1
- package/dist/runtime/task-commands.d.ts +1 -1
- package/dist/runtime/task-commands.js +10 -10
- package/dist/runtime/task-driver.js +2 -2
- package/dist/security/block-message.d.ts +11 -0
- package/dist/security/block-message.js +12 -0
- package/dist/security/path-guard-check.d.ts +13 -0
- package/dist/security/path-guard-check.js +39 -0
- package/dist/security/path-guard.js +32 -14
- package/dist/settings.js +3 -2
- package/dist/shared/atomic-file.d.ts +17 -1
- package/dist/shared/atomic-file.js +50 -3
- package/dist/shared/duration.d.ts +2 -0
- package/dist/shared/duration.js +7 -0
- package/dist/shared/safe-id.d.ts +19 -0
- package/dist/shared/safe-id.js +24 -0
- package/dist/shared/text-utils.d.ts +1 -1
- package/dist/shared/text-utils.js +3 -8
- package/dist/shared/type-guards.d.ts +2 -0
- package/dist/shared/type-guards.js +4 -0
- package/dist/subagents/discovery.d.ts +44 -17
- package/dist/subagents/discovery.js +82 -111
- package/dist/subagents/external/claude-code.js +1 -3
- package/dist/subagents/external/harness.d.ts +1 -1
- package/dist/subagents/format.d.ts +3 -2
- package/dist/subagents/format.js +3 -7
- package/dist/subagents/runs.d.ts +1 -1
- package/dist/subagents/runs.js +4 -9
- package/dist/subagents/tool.d.ts +31 -19
- package/dist/subagents/tool.js +582 -561
- package/dist/subagents/workspace-lease.js +1 -1
- package/dist/tasks/control.js +7 -9
- package/dist/tasks/ledger.d.ts +2 -2
- package/dist/tasks/ledger.js +3 -7
- package/dist/tasks/transitions.d.ts +5 -1
- package/dist/tasks/transitions.js +2 -2
- package/dist/tools/bash.d.ts +0 -1
- package/dist/tools/bash.js +45 -40
- package/dist/tools/config.d.ts +6 -1
- package/dist/tools/config.js +9 -0
- package/dist/tools/edit.d.ts +2 -3
- package/dist/tools/edit.js +274 -86
- package/dist/tools/event-manage.d.ts +13 -7
- package/dist/tools/event-manage.js +52 -14
- package/dist/tools/glob-match.d.ts +11 -0
- package/dist/tools/glob-match.js +75 -0
- package/dist/tools/glob.d.ts +15 -0
- package/dist/tools/glob.js +113 -0
- package/dist/tools/grep.d.ts +0 -1
- package/dist/tools/grep.js +57 -42
- package/dist/tools/ignore-dirs.d.ts +6 -0
- package/dist/tools/ignore-dirs.js +15 -0
- package/dist/tools/index.d.ts +3 -0
- package/dist/tools/index.js +50 -40
- package/dist/tools/job.d.ts +0 -1
- package/dist/tools/job.js +1 -8
- package/dist/tools/line-index.d.ts +16 -0
- package/dist/tools/line-index.js +76 -0
- package/dist/tools/memory-manage.d.ts +20 -8
- package/dist/tools/memory-manage.js +65 -92
- package/dist/tools/presentation.d.ts +2 -0
- package/dist/tools/presentation.js +109 -0
- package/dist/tools/read.d.ts +2 -2
- package/dist/tools/read.js +97 -133
- package/dist/tools/registry.d.ts +4 -1
- package/dist/tools/registry.js +89 -22
- package/dist/tools/send-media.d.ts +6 -6
- package/dist/tools/send-media.js +16 -49
- package/dist/tools/session-search.d.ts +0 -1
- package/dist/tools/session-search.js +0 -1
- package/dist/tools/skill-security.d.ts +0 -2
- package/dist/tools/skill-security.js +0 -24
- package/dist/tools/skill.d.ts +31 -0
- package/dist/tools/skill.js +153 -0
- package/dist/tools/subagent-manage.d.ts +6 -5
- package/dist/tools/subagent-manage.js +47 -47
- package/dist/tools/task-manage/create.d.ts +2 -2
- package/dist/tools/task-manage/create.js +1 -3
- package/dist/tools/task-manage/lifecycle.d.ts +9 -6
- package/dist/tools/task-manage/lifecycle.js +49 -56
- package/dist/tools/task-manage/schema.d.ts +27 -15
- package/dist/tools/task-manage/schema.js +58 -74
- package/dist/tools/task-manage/shared.d.ts +11 -6
- package/dist/tools/task-manage/shared.js +30 -21
- package/dist/tools/task-manage/types.d.ts +14 -15
- package/dist/tools/task-manage/verification.d.ts +4 -4
- package/dist/tools/task-manage/verification.js +6 -8
- package/dist/tools/task-manage.d.ts +8 -11
- package/dist/tools/task-manage.js +63 -50
- package/dist/tools/tool-details.d.ts +17 -1
- package/dist/tools/tool-details.js +24 -0
- package/dist/tools/truncate.d.ts +5 -5
- package/dist/tools/truncate.js +5 -5
- package/dist/tools/web-fetch.d.ts +0 -1
- package/dist/tools/web-fetch.js +0 -1
- package/dist/tools/web-search.d.ts +0 -1
- package/dist/tools/web-search.js +0 -1
- package/dist/tools/write-content.d.ts +3 -3
- package/dist/tools/write-content.js +12 -51
- package/dist/tools/write.d.ts +2 -3
- package/dist/tools/write.js +3 -4
- package/dist/usage/ledger.js +7 -4
- package/package.json +1 -1
- package/dist/tools/skill-manage.d.ts +0 -41
- package/dist/tools/skill-manage.js +0 -232
package/dist/tools/edit.js
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
import * as Diff from "diff";
|
|
2
2
|
import { Type } from "typebox";
|
|
3
|
+
import { fingerprintOf, fingerprintsEqual } from "../file-store.js";
|
|
3
4
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
4
|
-
import {
|
|
5
|
-
import { guardPath } from "../security/path-guard.js";
|
|
5
|
+
import { checkPathGuard } from "../security/path-guard-check.js";
|
|
6
6
|
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
7
|
-
import { shellEscape } from "../shared/shell-escape.js";
|
|
8
|
-
import { writeContent } from "./write-content.js";
|
|
9
7
|
/**
|
|
10
|
-
* Generate a unified diff string with line numbers and context
|
|
8
|
+
* Generate a unified diff string with line numbers and context. `startLineOld`/`startLineNew` let
|
|
9
|
+
* a caller render a *window* of a larger file (spec 044, D2.3) while still printing the file's real
|
|
10
|
+
* absolute line numbers instead of restarting at 1.
|
|
11
11
|
*/
|
|
12
|
-
function generateDiffString(oldContent, newContent, contextLines = 4) {
|
|
12
|
+
function generateDiffString(oldContent, newContent, contextLines = 4, startLineOld = 1, startLineNew = 1) {
|
|
13
13
|
const parts = Diff.diffLines(oldContent, newContent);
|
|
14
14
|
const output = [];
|
|
15
15
|
const oldLines = oldContent.split("\n");
|
|
16
16
|
const newLines = newContent.split("\n");
|
|
17
|
-
const maxLineNum = Math.max(oldLines.length, newLines.length);
|
|
17
|
+
const maxLineNum = Math.max(startLineOld + oldLines.length, startLineNew + newLines.length);
|
|
18
18
|
const lineNumWidth = String(maxLineNum).length;
|
|
19
|
-
let oldLineNum =
|
|
20
|
-
let newLineNum =
|
|
19
|
+
let oldLineNum = startLineOld;
|
|
20
|
+
let newLineNum = startLineNew;
|
|
21
21
|
let lastWasChange = false;
|
|
22
22
|
for (let i = 0; i < parts.length; i++) {
|
|
23
23
|
const part = parts[i];
|
|
@@ -79,7 +79,6 @@ function generateDiffString(oldContent, newContent, contextLines = 4) {
|
|
|
79
79
|
return output.join("\n");
|
|
80
80
|
}
|
|
81
81
|
const editSchema = Type.Object({
|
|
82
|
-
label: Type.String({ description: "Brief description of the edit you're making (shown to user)" }),
|
|
83
82
|
path: Type.String({ description: "Path to the file to edit (relative or absolute)" }),
|
|
84
83
|
oldText: Type.String({ description: "Exact text to find and replace (must match exactly)" }),
|
|
85
84
|
newText: Type.String({ description: "New text to replace the old text with" }),
|
|
@@ -87,20 +86,26 @@ const editSchema = Type.Object({
|
|
|
87
86
|
description: "Replace every occurrence instead of requiring a unique match. Defaults to false (the match must be unique).",
|
|
88
87
|
})),
|
|
89
88
|
});
|
|
90
|
-
function formatPathBlockMessage(resolvedPath, category, reason) {
|
|
91
|
-
const lines = [`Path blocked${category ? ` [${category}]` : ""}`];
|
|
92
|
-
if (reason) {
|
|
93
|
-
lines.push(`Reason: ${reason}`);
|
|
94
|
-
}
|
|
95
|
-
if (resolvedPath) {
|
|
96
|
-
lines.push(`Resolved path: ${resolvedPath}`);
|
|
97
|
-
}
|
|
98
|
-
return lines.join("\n");
|
|
99
|
-
}
|
|
100
89
|
/** Max diff lines echoed back to the model in the success result before eliding the rest. */
|
|
101
90
|
const DIFF_ECHO_MAX_LINES = 40;
|
|
102
91
|
/** Consecutive byte-identical no-ops of the same payload before the soft error escalates to a hard stop. */
|
|
103
92
|
const NOOP_HARD_LIMIT = 3;
|
|
93
|
+
/** Above this, `edit` switches from "read whole file into memory" to the streaming two-pass path (D2.2). */
|
|
94
|
+
const EDIT_INLINE_MAX_BYTES = 8 * 1024 * 1024;
|
|
95
|
+
/** Bytes scanned from the head of the file for the binary guard (D2.5). */
|
|
96
|
+
const BINARY_SNIFF_BYTES = 8 * 1024;
|
|
97
|
+
/**
|
|
98
|
+
* Hard cap on how many `replaceAll` match offsets the streaming path records in memory (D2.2). A
|
|
99
|
+
* file with more occurrences than this is almost certainly the wrong target for a text edit (e.g.
|
|
100
|
+
* a needle that matches on every line of a huge generated file); failing loudly with a narrowing
|
|
101
|
+
* suggestion is one of the sanctioned "bounded" outcomes (spec 044, design principle P2), not a
|
|
102
|
+
* silent truncation.
|
|
103
|
+
*/
|
|
104
|
+
const MAX_REPLACE_ALL_OFFSETS = 200_000;
|
|
105
|
+
/** Bytes of file context shown around each match in the streaming path's local diff (D2.3). */
|
|
106
|
+
const DIFF_WINDOW_BYTES = 2000;
|
|
107
|
+
/** How many of a `replaceAll` match's diffs get rendered on the streaming path. */
|
|
108
|
+
const MAX_DIFF_WINDOWS = 5;
|
|
104
109
|
function clampDiffForEcho(diff) {
|
|
105
110
|
const lines = diff.split("\n");
|
|
106
111
|
if (lines.length <= DIFF_ECHO_MAX_LINES) {
|
|
@@ -109,7 +114,131 @@ function clampDiffForEcho(diff) {
|
|
|
109
114
|
const shown = lines.slice(0, DIFF_ECHO_MAX_LINES).join("\n");
|
|
110
115
|
return `${shown}\n[diff truncated, ${lines.length - DIFF_ECHO_MAX_LINES} more lines]`;
|
|
111
116
|
}
|
|
112
|
-
|
|
117
|
+
/** All non-overlapping byte offsets of `needle` in `haystack`, left to right (mirrors `String.split`). */
|
|
118
|
+
function findAllOffsets(haystack, needle) {
|
|
119
|
+
const offsets = [];
|
|
120
|
+
let from = 0;
|
|
121
|
+
while (true) {
|
|
122
|
+
const idx = haystack.indexOf(needle, from);
|
|
123
|
+
if (idx === -1)
|
|
124
|
+
break;
|
|
125
|
+
offsets.push(idx);
|
|
126
|
+
from = idx + needle.length;
|
|
127
|
+
}
|
|
128
|
+
return offsets;
|
|
129
|
+
}
|
|
130
|
+
/** Byte-level splice: replace `needle` at every offset in `offsets` (ascending) with `replacement`. */
|
|
131
|
+
function spliceBuffer(source, needle, replacement, offsets) {
|
|
132
|
+
const parts = [];
|
|
133
|
+
let cursor = 0;
|
|
134
|
+
for (const offset of offsets) {
|
|
135
|
+
parts.push(source.subarray(cursor, offset));
|
|
136
|
+
parts.push(replacement);
|
|
137
|
+
cursor = offset + needle.length;
|
|
138
|
+
}
|
|
139
|
+
parts.push(source.subarray(cursor));
|
|
140
|
+
return Buffer.concat(parts);
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* A streaming scan for every non-overlapping occurrence of `needle`, safe against a match that
|
|
144
|
+
* straddles a chunk boundary (D2.2). Carries the last `needle.length - 1` bytes of each window into
|
|
145
|
+
* the next iteration so a split match is still found, without ever holding more than one window in
|
|
146
|
+
* memory. Also tracks the 1-indexed line number of each match (from a running newline count) and
|
|
147
|
+
* sniffs the first `BINARY_SNIFF_BYTES` for a NUL byte (D2.5).
|
|
148
|
+
*/
|
|
149
|
+
async function scanOccurrences(stream, needle, maxOffsets) {
|
|
150
|
+
const overlapLen = needle.length - 1;
|
|
151
|
+
let carry = Buffer.alloc(0);
|
|
152
|
+
let windowBaseOffset = 0;
|
|
153
|
+
let newlinesBeforeWindow = 0;
|
|
154
|
+
let count = 0;
|
|
155
|
+
let offsets = [];
|
|
156
|
+
const lineNumbers = new Map();
|
|
157
|
+
let looksBinary = false;
|
|
158
|
+
let sniffed = 0;
|
|
159
|
+
let totalBytes = 0;
|
|
160
|
+
for await (const chunk of stream) {
|
|
161
|
+
totalBytes += chunk.length;
|
|
162
|
+
if (sniffed < BINARY_SNIFF_BYTES) {
|
|
163
|
+
const take = chunk.subarray(0, BINARY_SNIFF_BYTES - sniffed);
|
|
164
|
+
if (take.includes(0))
|
|
165
|
+
looksBinary = true;
|
|
166
|
+
sniffed += take.length;
|
|
167
|
+
}
|
|
168
|
+
const window = carry.length > 0 ? Buffer.concat([carry, chunk]) : chunk;
|
|
169
|
+
let from = 0;
|
|
170
|
+
while (true) {
|
|
171
|
+
const idx = window.indexOf(needle, from);
|
|
172
|
+
if (idx === -1)
|
|
173
|
+
break;
|
|
174
|
+
count++;
|
|
175
|
+
if (offsets && offsets.length < maxOffsets) {
|
|
176
|
+
const absoluteOffset = windowBaseOffset + idx;
|
|
177
|
+
offsets.push(absoluteOffset);
|
|
178
|
+
const lineNumber = newlinesBeforeWindow + countNewlines(window, 0, idx) + 1;
|
|
179
|
+
lineNumbers.set(absoluteOffset, lineNumber);
|
|
180
|
+
}
|
|
181
|
+
else if (offsets) {
|
|
182
|
+
offsets = undefined; // Overflowed: stop tracking, caller must fail closed if it needed them.
|
|
183
|
+
}
|
|
184
|
+
from = idx + needle.length;
|
|
185
|
+
}
|
|
186
|
+
const retiredLen = Math.max(0, window.length - overlapLen);
|
|
187
|
+
newlinesBeforeWindow += countNewlines(window, 0, retiredLen);
|
|
188
|
+
windowBaseOffset += retiredLen;
|
|
189
|
+
carry = window.subarray(retiredLen);
|
|
190
|
+
}
|
|
191
|
+
return { count, offsets, lineNumbers, looksBinary, totalBytes };
|
|
192
|
+
}
|
|
193
|
+
function countNewlines(buf, start, end) {
|
|
194
|
+
let n = 0;
|
|
195
|
+
for (let i = start; i < end; i++) {
|
|
196
|
+
if (buf[i] === 0x0a)
|
|
197
|
+
n++;
|
|
198
|
+
}
|
|
199
|
+
return n;
|
|
200
|
+
}
|
|
201
|
+
async function* readStreamChunks(store, path, signal) {
|
|
202
|
+
for await (const chunk of store.openRead(path)) {
|
|
203
|
+
if (signal?.aborted)
|
|
204
|
+
throw new Error("Aborted");
|
|
205
|
+
yield chunk;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
/** Copy `[start, end)` of `path` onto `out`, with simple backpressure handling. */
|
|
209
|
+
function copyRange(store, path, start, end, out) {
|
|
210
|
+
if (end <= start)
|
|
211
|
+
return Promise.resolve();
|
|
212
|
+
return new Promise((resolveCopy, reject) => {
|
|
213
|
+
const src = store.openRead(path, { start, end: end - 1 });
|
|
214
|
+
src.on("data", (chunk) => {
|
|
215
|
+
if (!out.write(chunk)) {
|
|
216
|
+
src.pause();
|
|
217
|
+
out.once("drain", () => src.resume());
|
|
218
|
+
}
|
|
219
|
+
});
|
|
220
|
+
src.on("end", () => resolveCopy());
|
|
221
|
+
src.on("error", reject);
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
/** Expand a byte window to the nearest line boundaries so the rendered diff never starts/ends mid-line. */
|
|
225
|
+
function expandToLineBoundaries(bytes, start, end, fileSize) {
|
|
226
|
+
let s = start;
|
|
227
|
+
while (s > 0 && bytes[s - 1] !== undefined && bytes[s - 1] !== 0x0a)
|
|
228
|
+
s--;
|
|
229
|
+
let e = end;
|
|
230
|
+
while (e < fileSize && bytes[e] !== undefined && bytes[e] !== 0x0a)
|
|
231
|
+
e++;
|
|
232
|
+
return { start: s, end: e };
|
|
233
|
+
}
|
|
234
|
+
async function checkFingerprintUnchanged(fileStore, target, path, before) {
|
|
235
|
+
const after = await fileStore.stat(target);
|
|
236
|
+
if (!after || !fingerprintsEqual(fingerprintOf(before), fingerprintOf(after))) {
|
|
237
|
+
throw new RecoverableToolError(`${path} changed during this edit (likely a background job or another agent writing concurrently). ` +
|
|
238
|
+
"Re-read the file and re-apply the edit against its current content.");
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
export function createEditTool(fileStore, options = {}) {
|
|
113
242
|
const securityConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
|
|
114
243
|
const securityContext = options.securityContext ?? {
|
|
115
244
|
agentWorkspaceDir: process.cwd(),
|
|
@@ -126,47 +255,21 @@ export function createEditTool(executor, options = {}) {
|
|
|
126
255
|
description: "Edit a file by replacing exact text. The oldText must match exactly (including whitespace). Use this for precise, surgical edits.",
|
|
127
256
|
parameters: editSchema,
|
|
128
257
|
execute: async (_toolCallId, { path, oldText, newText, replaceAll, }, signal) => {
|
|
129
|
-
if (
|
|
130
|
-
|
|
131
|
-
if (!readGuard.allowed) {
|
|
132
|
-
await logSecurityEvent(securityContext.agentWorkspaceDir, securityConfig, {
|
|
133
|
-
type: "path",
|
|
134
|
-
tool: "edit",
|
|
135
|
-
channelId: options.channelId,
|
|
136
|
-
rawPath: path,
|
|
137
|
-
operation: "read",
|
|
138
|
-
resolvedPath: readGuard.resolvedPath,
|
|
139
|
-
category: readGuard.category,
|
|
140
|
-
reason: readGuard.reason,
|
|
141
|
-
});
|
|
142
|
-
throw new Error(formatPathBlockMessage(readGuard.resolvedPath, readGuard.category, readGuard.reason));
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
// Read the file
|
|
146
|
-
const readResult = await executor.exec(`cat ${shellEscape(path)}`, { signal });
|
|
147
|
-
if (readResult.code !== 0) {
|
|
148
|
-
throw new RecoverableToolError(readResult.stderr || `File not found: ${path}`);
|
|
258
|
+
if (oldText.length === 0) {
|
|
259
|
+
throw new RecoverableToolError("oldText must not be empty.");
|
|
149
260
|
}
|
|
150
|
-
const
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
if (occurrences > 1 && !replaceAll) {
|
|
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.`);
|
|
159
|
-
}
|
|
160
|
-
// Perform replacement
|
|
161
|
-
let newContent;
|
|
162
|
-
if (replaceAll) {
|
|
163
|
-
newContent = content.split(oldText).join(newText);
|
|
164
|
-
}
|
|
165
|
-
else {
|
|
166
|
-
const index = content.indexOf(oldText);
|
|
167
|
-
newContent = content.substring(0, index) + newText + content.substring(index + oldText.length);
|
|
261
|
+
const target = await checkPathGuard(path, "read", securityConfig, securityContext, {
|
|
262
|
+
tool: "edit",
|
|
263
|
+
channelId: options.channelId,
|
|
264
|
+
});
|
|
265
|
+
const before = await fileStore.stat(target);
|
|
266
|
+
if (!before || !before.isFile) {
|
|
267
|
+
throw new RecoverableToolError(`File not found: ${path}`);
|
|
168
268
|
}
|
|
169
|
-
|
|
269
|
+
const needle = Buffer.from(oldText, "utf-8");
|
|
270
|
+
const replacement = Buffer.from(newText, "utf-8");
|
|
271
|
+
const isNoopPayload = needle.equals(replacement);
|
|
272
|
+
const applyNoop = () => {
|
|
170
273
|
const noopKey = `${path}\x00${oldText}\x00${newText}`;
|
|
171
274
|
const streak = (noopCounts.get(noopKey) ?? 0) + 1;
|
|
172
275
|
noopCounts.set(noopKey, streak);
|
|
@@ -177,42 +280,127 @@ export function createEditTool(executor, options = {}) {
|
|
|
177
280
|
}
|
|
178
281
|
throw new RecoverableToolError(`No changes made to ${path}: oldText and newText are byte-identical at the match, so the replacement produced no change. ` +
|
|
179
282
|
`Re-read the file to confirm what actually needs changing before editing again.`);
|
|
283
|
+
};
|
|
284
|
+
let result;
|
|
285
|
+
if (before.size <= EDIT_INLINE_MAX_BYTES) {
|
|
286
|
+
result = await editInline(fileStore, target, path, before, needle, replacement, replaceAll === true, signal);
|
|
287
|
+
}
|
|
288
|
+
else {
|
|
289
|
+
result = await editStreaming(fileStore, target, path, before, needle, replacement, replaceAll === true, isNoopPayload, signal);
|
|
290
|
+
}
|
|
291
|
+
if (isNoopPayload) {
|
|
292
|
+
applyNoop();
|
|
180
293
|
}
|
|
181
294
|
// A real edit breaks any no-op streak.
|
|
182
295
|
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
|
-
}
|
|
195
|
-
// Write the file back
|
|
196
|
-
await writeContent(executor, path, newContent, signal, {
|
|
197
|
-
securityConfig,
|
|
198
|
-
securityContext,
|
|
199
|
-
channelId: options.channelId,
|
|
200
|
-
toolName: "edit",
|
|
201
|
-
});
|
|
202
296
|
const replacementSummary = replaceAll
|
|
203
|
-
? `Replaced ${occurrences} occurrence${occurrences === 1 ? "" : "s"} in ${path}.`
|
|
297
|
+
? `Replaced ${result.occurrences} occurrence${result.occurrences === 1 ? "" : "s"} in ${path}.`
|
|
204
298
|
: `Successfully replaced text in ${path}. Changed ${oldText.length} characters to ${newText.length} characters.`;
|
|
205
|
-
const
|
|
206
|
-
// Echo the diff into the model-visible text so it can confirm the change landed where it
|
|
207
|
-
// intended without a follow-up read; `details.diff` stays the full diff for the UI.
|
|
208
|
-
const echoedDiff = diff.trim() ? `\n\n${clampDiffForEcho(diff)}` : "";
|
|
299
|
+
const echoedDiff = result.diff.trim() ? `\n\n${clampDiffForEcho(result.diff)}` : "";
|
|
209
300
|
return {
|
|
210
301
|
content: [{ type: "text", text: `${replacementSummary}${echoedDiff}` }],
|
|
211
302
|
details: {
|
|
212
|
-
|
|
213
|
-
|
|
303
|
+
path: target,
|
|
304
|
+
diff: result.diff,
|
|
305
|
+
patch: result.patch,
|
|
214
306
|
},
|
|
215
307
|
};
|
|
216
308
|
},
|
|
217
309
|
};
|
|
218
310
|
}
|
|
311
|
+
/** D2.1: small file path -- read whole, splice in memory, write atomically. */
|
|
312
|
+
async function editInline(fileStore, target, path, before, needle, replacement, replaceAll, signal) {
|
|
313
|
+
const { data } = await fileStore.readBytes(target, { signal });
|
|
314
|
+
if (data.subarray(0, BINARY_SNIFF_BYTES).includes(0)) {
|
|
315
|
+
throw new RecoverableToolError(`${path} looks like a binary file (a NUL byte appears in the first ${BINARY_SNIFF_BYTES} bytes). ` +
|
|
316
|
+
"Use bash for binary edits — edit is for text.");
|
|
317
|
+
}
|
|
318
|
+
const offsets = findAllOffsets(data, needle);
|
|
319
|
+
if (offsets.length === 0) {
|
|
320
|
+
throw new RecoverableToolError(`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`);
|
|
321
|
+
}
|
|
322
|
+
if (offsets.length > 1 && !replaceAll) {
|
|
323
|
+
throw new RecoverableToolError(`Found ${offsets.length} 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.`);
|
|
324
|
+
}
|
|
325
|
+
const useOffsets = replaceAll ? offsets : [offsets[0]];
|
|
326
|
+
const newData = spliceBuffer(data, needle, replacement, useOffsets);
|
|
327
|
+
if (newData.equals(data)) {
|
|
328
|
+
// Byte-identical payload -- caller (createEditTool) turns this into the no-op error/hard-stop.
|
|
329
|
+
return { text: "", diff: "", patch: "", occurrences: useOffsets.length };
|
|
330
|
+
}
|
|
331
|
+
await checkFingerprintUnchanged(fileStore, target, path, before);
|
|
332
|
+
await fileStore.writeAtomic(target, newData, { preserveMode: true, signal });
|
|
333
|
+
const oldText = data.toString("utf-8");
|
|
334
|
+
const newText = newData.toString("utf-8");
|
|
335
|
+
const diff = generateDiffString(oldText, newText);
|
|
336
|
+
const patch = Diff.createPatch(path, oldText, newText);
|
|
337
|
+
return { text: "", diff, patch, occurrences: useOffsets.length };
|
|
338
|
+
}
|
|
339
|
+
/** D2.2: streaming two-pass path for files over EDIT_INLINE_MAX_BYTES. */
|
|
340
|
+
async function editStreaming(fileStore, target, path, before, needle, replacement, replaceAll, isNoopPayload, signal) {
|
|
341
|
+
// Pass 1: scan for occurrences, line numbers, and a binary sniff -- no writes yet, so the
|
|
342
|
+
// uniqueness/existence judgment is made before anything touches disk.
|
|
343
|
+
const scan = await scanOccurrences(readStreamChunks(fileStore, target, signal), needle, MAX_REPLACE_ALL_OFFSETS);
|
|
344
|
+
if (scan.looksBinary) {
|
|
345
|
+
throw new RecoverableToolError(`${path} looks like a binary file (a NUL byte appears in the first ${BINARY_SNIFF_BYTES} bytes). ` +
|
|
346
|
+
"Use bash for binary edits — edit is for text.");
|
|
347
|
+
}
|
|
348
|
+
if (scan.count === 0) {
|
|
349
|
+
throw new RecoverableToolError(`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`);
|
|
350
|
+
}
|
|
351
|
+
if (scan.count > 1 && !replaceAll) {
|
|
352
|
+
throw new RecoverableToolError(`Found ${scan.count} 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.`);
|
|
353
|
+
}
|
|
354
|
+
if (!scan.offsets) {
|
|
355
|
+
throw new RecoverableToolError(`${path} has more than ${MAX_REPLACE_ALL_OFFSETS} occurrences of the text -- too many to replace in one call on a file this large. ` +
|
|
356
|
+
"Narrow the pattern (add more context) so it matches far fewer places.");
|
|
357
|
+
}
|
|
358
|
+
const matchOffsets = replaceAll ? scan.offsets : [scan.offsets[0]];
|
|
359
|
+
const occurrences = matchOffsets.length;
|
|
360
|
+
if (isNoopPayload) {
|
|
361
|
+
// The caller turns this into the no-op error/hard-stop; no point writing an identical file.
|
|
362
|
+
return { text: "", diff: "", patch: "", occurrences };
|
|
363
|
+
}
|
|
364
|
+
// Local diff windows, read from the *original* file before pass 2 rewrites it.
|
|
365
|
+
const diffParts = [];
|
|
366
|
+
const patchParts = [];
|
|
367
|
+
const shown = Math.min(matchOffsets.length, MAX_DIFF_WINDOWS);
|
|
368
|
+
for (let i = 0; i < shown; i++) {
|
|
369
|
+
const offset = matchOffsets[i];
|
|
370
|
+
const rawStart = Math.max(0, offset - DIFF_WINDOW_BYTES);
|
|
371
|
+
const rawEnd = Math.min(before.size, offset + needle.length + DIFF_WINDOW_BYTES);
|
|
372
|
+
const { data: windowBytes } = await fileStore.readBytes(target, {
|
|
373
|
+
start: rawStart,
|
|
374
|
+
maxBytes: rawEnd - rawStart,
|
|
375
|
+
signal,
|
|
376
|
+
});
|
|
377
|
+
const { start, end } = expandToLineBoundaries(windowBytes, offset - rawStart, offset - rawStart + needle.length, windowBytes.length);
|
|
378
|
+
const oldWindow = windowBytes.subarray(start, end).toString("utf-8");
|
|
379
|
+
const newWindow = windowBytes.subarray(start, offset - rawStart).toString("utf-8") +
|
|
380
|
+
replacement.toString("utf-8") +
|
|
381
|
+
windowBytes.subarray(offset - rawStart + needle.length, end).toString("utf-8");
|
|
382
|
+
const startLine = scan.lineNumbers.get(offset) ?? 1;
|
|
383
|
+
// The window itself may start mid-file above `offset`'s line, so back up the printed line
|
|
384
|
+
// number by however many newlines are in the window before the expanded start.
|
|
385
|
+
const linesBeforeWindowStart = countNewlines(windowBytes, 0, start);
|
|
386
|
+
const linesBeforeMatch = countNewlines(windowBytes, 0, offset - rawStart);
|
|
387
|
+
const windowStartLine = startLine - (linesBeforeMatch - linesBeforeWindowStart);
|
|
388
|
+
diffParts.push(generateDiffString(oldWindow, newWindow, 4, windowStartLine, windowStartLine));
|
|
389
|
+
patchParts.push(Diff.createPatch(path, oldWindow, newWindow));
|
|
390
|
+
}
|
|
391
|
+
if (matchOffsets.length > shown) {
|
|
392
|
+
diffParts.push(`[+${matchOffsets.length - shown} more occurrence(s) replaced, diff not shown]`);
|
|
393
|
+
}
|
|
394
|
+
// Pass 2: apply. Stream-copy the file, splicing in `replacement` at each recorded offset.
|
|
395
|
+
await checkFingerprintUnchanged(fileStore, target, path, before);
|
|
396
|
+
await fileStore.replaceViaTemp(target, async (out) => {
|
|
397
|
+
let cursor = 0;
|
|
398
|
+
for (const offset of matchOffsets) {
|
|
399
|
+
await copyRange(fileStore, target, cursor, offset, out);
|
|
400
|
+
out.write(replacement);
|
|
401
|
+
cursor = offset + needle.length;
|
|
402
|
+
}
|
|
403
|
+
await copyRange(fileStore, target, cursor, before.size, out);
|
|
404
|
+
}, { preserveMode: true, signal });
|
|
405
|
+
return { text: "", diff: diffParts.join("\n\n"), patch: patchParts.join("\n"), occurrences };
|
|
406
|
+
}
|
|
@@ -3,25 +3,31 @@ import { Type } from "typebox";
|
|
|
3
3
|
import { type ScheduledEvent } from "../runtime/events.js";
|
|
4
4
|
import type { SecurityConfig } from "../security/types.js";
|
|
5
5
|
declare const eventManageSchema: Type.TObject<{
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
name: Type.TString;
|
|
6
|
+
action: Type.TUnion<[Type.TLiteral<"list">, Type.TLiteral<"create">, Type.TLiteral<"update">, Type.TLiteral<"delete">]>;
|
|
7
|
+
name: Type.TOptional<Type.TString>;
|
|
9
8
|
definition: Type.TOptional<Type.TString>;
|
|
10
9
|
}>;
|
|
11
|
-
export type EventManageAction = "create" | "update" | "delete";
|
|
10
|
+
export type EventManageAction = "list" | "create" | "update" | "delete";
|
|
11
|
+
export interface EventManageListEntry {
|
|
12
|
+
name: string;
|
|
13
|
+
line: string;
|
|
14
|
+
parsed: boolean;
|
|
15
|
+
}
|
|
12
16
|
export interface EventManageResult {
|
|
13
17
|
action: EventManageAction;
|
|
14
|
-
name
|
|
15
|
-
path
|
|
18
|
+
name?: string;
|
|
19
|
+
path?: string;
|
|
16
20
|
eventType?: ScheduledEvent["type"];
|
|
17
21
|
channelId?: string;
|
|
18
22
|
bytesWritten?: number;
|
|
19
23
|
deleted?: boolean;
|
|
24
|
+
count?: number;
|
|
25
|
+
names?: string[];
|
|
20
26
|
notice: string;
|
|
21
27
|
}
|
|
22
28
|
export interface EventManageRequest {
|
|
23
29
|
action: EventManageAction;
|
|
24
|
-
name
|
|
30
|
+
name?: string;
|
|
25
31
|
definition?: string;
|
|
26
32
|
}
|
|
27
33
|
export interface EventManageToolOptions {
|
|
@@ -7,25 +7,50 @@ import { EventValidationError, MAX_EVENT_FILES, validateScheduledEvent } from ".
|
|
|
7
7
|
import { parseScheduledEventContent } from "../runtime/events.js";
|
|
8
8
|
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
9
9
|
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
10
|
-
import { errorMessage } from "../shared/text-utils.js";
|
|
10
|
+
import { clipText, errorMessage } from "../shared/text-utils.js";
|
|
11
11
|
import { isRecord } from "../shared/type-guards.js";
|
|
12
12
|
const eventManageSchema = Type.Object({
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
description: 'The event management action to perform: "create", "update", or "delete".',
|
|
16
|
-
}),
|
|
17
|
-
name: Type.String({
|
|
18
|
-
description: "Event name (filename without .json). For task-owned events use `task.<channelId>.<taskId>.<use>`, e.g. `task.dm_123.weekly-report.checkin`.",
|
|
13
|
+
action: Type.Union([Type.Literal("list"), Type.Literal("create"), Type.Literal("update"), Type.Literal("delete")], {
|
|
14
|
+
description: '"list" this channel\'s events, or "create" / "update" / "delete" one by name.',
|
|
19
15
|
}),
|
|
16
|
+
name: Type.Optional(Type.String({
|
|
17
|
+
description: "Event name (filename without .json); required for create/update/delete, ignored for list. Task-owned events: `task.<channelId>.<taskId>.<use>`.",
|
|
18
|
+
})),
|
|
20
19
|
definition: Type.Optional(Type.String({
|
|
21
|
-
description: "Full event JSON (required for create/update). one-shot / periodic only; one-shots
|
|
20
|
+
description: "Full event JSON (required for create/update). one-shot / periodic only; one-shots 2 minutes to about 24.8 days out. channelId defaults to the current channel.",
|
|
22
21
|
})),
|
|
23
22
|
});
|
|
24
23
|
function parseAction(action) {
|
|
25
|
-
if (action === "create" || action === "update" || action === "delete") {
|
|
24
|
+
if (action === "list" || action === "create" || action === "update" || action === "delete") {
|
|
26
25
|
return action;
|
|
27
26
|
}
|
|
28
|
-
throw new RecoverableToolError('Unsupported event action. Use "create", "update", or "delete".');
|
|
27
|
+
throw new RecoverableToolError('Unsupported event action. Use "list", "create", "update", or "delete".');
|
|
28
|
+
}
|
|
29
|
+
/** One line per event; unparseable files are listed and flagged so the model can still clean them up. */
|
|
30
|
+
async function listOwnedEvents(options) {
|
|
31
|
+
const dir = join(options.workspaceDir, "events");
|
|
32
|
+
if (!existsSync(dir))
|
|
33
|
+
return [];
|
|
34
|
+
const filenames = (await readdir(dir)).filter((filename) => filename.endsWith(".json")).sort();
|
|
35
|
+
const entries = [];
|
|
36
|
+
for (const filename of filenames) {
|
|
37
|
+
const name = filename.slice(0, -".json".length);
|
|
38
|
+
let event;
|
|
39
|
+
try {
|
|
40
|
+
event = parseScheduledEventContent(await readFile(join(dir, filename), "utf-8"), filename);
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
entries.push({ name, parsed: false, line: `- ${name} ⚠ 无法解析:${errorMessage(error)}` });
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
if (event.channelId !== options.channelId)
|
|
47
|
+
continue;
|
|
48
|
+
const when = event.type === "one-shot" ? `at ${event.at}` : event.schedule;
|
|
49
|
+
const pre = event.preAction ? " (preAction)" : "";
|
|
50
|
+
const text = clipText(event.text, 80, { collapseWhitespace: true });
|
|
51
|
+
entries.push({ name, parsed: true, line: `- ${name} [${event.type}] ${when}${pre} — ${text}` });
|
|
52
|
+
}
|
|
53
|
+
return entries;
|
|
29
54
|
}
|
|
30
55
|
/**
|
|
31
56
|
* Validate an agent-supplied event definition and return the normalized, typed event.
|
|
@@ -93,6 +118,19 @@ async function countEventFiles(dir) {
|
|
|
93
118
|
return filenames.filter((filename) => filename.endsWith(".json")).length;
|
|
94
119
|
}
|
|
95
120
|
export async function manageEvent(options, request) {
|
|
121
|
+
if (request.action === "list") {
|
|
122
|
+
const entries = await listOwnedEvents(options);
|
|
123
|
+
const notice = entries.length === 0 ? "本频道暂无定时事件。" : entries.map((entry) => entry.line).join("\n");
|
|
124
|
+
return {
|
|
125
|
+
action: "list",
|
|
126
|
+
count: entries.length,
|
|
127
|
+
names: entries.map((entry) => entry.name),
|
|
128
|
+
notice,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
if (!request.name || request.name.trim().length === 0) {
|
|
132
|
+
throw new RecoverableToolError(`${request.action} requires a non-empty event name.`);
|
|
133
|
+
}
|
|
96
134
|
const { eventName, eventPath } = resolveEventPath(options.workspaceDir, request.name);
|
|
97
135
|
const eventsDir = join(options.workspaceDir, "events");
|
|
98
136
|
if (request.action === "delete") {
|
|
@@ -158,9 +196,8 @@ export function createEventManageTool(options) {
|
|
|
158
196
|
return {
|
|
159
197
|
name: "event_manage",
|
|
160
198
|
label: "event_manage",
|
|
161
|
-
description: "
|
|
162
|
-
"
|
|
163
|
-
"blocked, clean up on close. immediate events are rejected; do that work in the current turn.",
|
|
199
|
+
description: "List, create, update, or delete scheduled events that wake this channel later (one-shot check-ins and periodic " +
|
|
200
|
+
"cadences). List to recover real event names before a reschedule or close-out. immediate events are rejected.",
|
|
164
201
|
parameters: eventManageSchema,
|
|
165
202
|
execute: async (_toolCallId, args) => {
|
|
166
203
|
const result = await manageEvent(options, {
|
|
@@ -168,8 +205,9 @@ export function createEventManageTool(options) {
|
|
|
168
205
|
name: args.name,
|
|
169
206
|
definition: args.definition,
|
|
170
207
|
});
|
|
208
|
+
const text = result.action === "list" ? result.notice : JSON.stringify(result, null, 2);
|
|
171
209
|
return {
|
|
172
|
-
content: [{ type: "text", text
|
|
210
|
+
content: [{ type: "text", text }],
|
|
173
211
|
details: { ...result },
|
|
174
212
|
};
|
|
175
213
|
},
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compile a shell-style glob pattern into a `RegExp` matched against a POSIX-relative file path.
|
|
3
|
+
*
|
|
4
|
+
* Semantics follow the convention the model already knows from `find`/`fd`/Claude Code's own glob
|
|
5
|
+
* tool: a pattern with no `/` matches the *basename* at any depth (so `*.ts` searches the whole
|
|
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 an
|
|
8
|
+
* alternation. Matching is always case-sensitive and always against `/`-joined relative paths —
|
|
9
|
+
* callers never see platform separators.
|
|
10
|
+
*/
|
|
11
|
+
export declare function compileGlobPattern(pattern: string): RegExp;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compile a shell-style glob pattern into a `RegExp` matched against a POSIX-relative file path.
|
|
3
|
+
*
|
|
4
|
+
* Semantics follow the convention the model already knows from `find`/`fd`/Claude Code's own glob
|
|
5
|
+
* tool: a pattern with no `/` matches the *basename* at any depth (so `*.ts` searches the whole
|
|
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 an
|
|
8
|
+
* alternation. Matching is always case-sensitive and always against `/`-joined relative paths —
|
|
9
|
+
* callers never see platform separators.
|
|
10
|
+
*/
|
|
11
|
+
export function compileGlobPattern(pattern) {
|
|
12
|
+
const body = globToRegExpSource(pattern);
|
|
13
|
+
return pattern.includes("/") ? new RegExp(`^${body}$`) : new RegExp(`(?:^|/)${body}$`);
|
|
14
|
+
}
|
|
15
|
+
/** Single-pass translation so `**` can see the literal `/` characters on either side of it. */
|
|
16
|
+
function globToRegExpSource(pattern) {
|
|
17
|
+
let out = "";
|
|
18
|
+
let i = 0;
|
|
19
|
+
const n = pattern.length;
|
|
20
|
+
while (i < n) {
|
|
21
|
+
const ch = pattern[i];
|
|
22
|
+
if (ch === "*" && pattern[i + 1] === "*") {
|
|
23
|
+
const precededByBoundary = i === 0 || pattern[i - 1] === "/";
|
|
24
|
+
const followedBySlash = pattern[i + 2] === "/";
|
|
25
|
+
const followedByEnd = i + 2 === n;
|
|
26
|
+
if (precededByBoundary && followedBySlash) {
|
|
27
|
+
// `**/`: zero or more complete path segments.
|
|
28
|
+
out += "(?:.*/)?";
|
|
29
|
+
i += 3;
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
if (precededByBoundary && followedByEnd) {
|
|
33
|
+
// trailing `**`: everything under this point.
|
|
34
|
+
out += ".*";
|
|
35
|
+
i += 2;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
// `**` not cleanly bounded by separators — fall back to single-segment `*` semantics.
|
|
39
|
+
out += "[^/]*";
|
|
40
|
+
i += 2;
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
if (ch === "*") {
|
|
44
|
+
out += "[^/]*";
|
|
45
|
+
i += 1;
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (ch === "?") {
|
|
49
|
+
out += "[^/]";
|
|
50
|
+
i += 1;
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (ch === "{") {
|
|
54
|
+
const close = pattern.indexOf("}", i);
|
|
55
|
+
if (close === -1) {
|
|
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;
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
out += escapeRegExpChar(ch);
|
|
69
|
+
i += 1;
|
|
70
|
+
}
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
function escapeRegExpChar(ch) {
|
|
74
|
+
return /[.+^${}()|[\]\\]/.test(ch) ? `\\${ch}` : ch;
|
|
75
|
+
}
|