@oyasmi/pipiclaw 0.9.6-beta.1 → 0.9.6-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +279 -215
- package/README.md +274 -213
- package/dist/agent/builtin-commands.d.ts +1 -1
- package/dist/agent/builtin-commands.js +1 -1
- package/dist/agent/channel-runner.d.ts +3 -2
- package/dist/agent/channel-runner.js +16 -27
- package/dist/agent/maintenance-context.js +2 -2
- package/dist/agent/prompt/builder.d.ts +1 -1
- package/dist/agent/prompt/builder.js +1 -1
- package/dist/agent/prompt/extension.d.ts +1 -1
- package/dist/agent/prompt/extension.js +1 -1
- package/dist/agent/prompt/manifest.d.ts +6 -1
- package/dist/agent/prompt/manifest.js +12 -5
- package/dist/agent/prompt/resources.d.ts +0 -3
- package/dist/agent/prompt/resources.js +0 -6
- package/dist/agent/prompt/sections.d.ts +2 -2
- package/dist/agent/prompt/sections.js +36 -26
- package/dist/agent/prompt/types.d.ts +1 -1
- package/dist/agent/runner-factory.js +1 -1
- package/dist/agent/session/command-extension.js +3 -1
- package/dist/agent/session/compaction-summary.js +3 -6
- package/dist/agent/session/event-guards.d.ts +2 -1
- package/dist/agent/session/event-guards.js +6 -0
- package/dist/agent/session/model-selection.d.ts +2 -1
- package/dist/agent/session/model-selection.js +5 -5
- package/dist/agent/session/session-events.js +31 -4
- package/dist/agent/session/session-host.d.ts +4 -2
- package/dist/agent/session/session-host.js +17 -15
- package/dist/agent/status-render.js +3 -0
- package/dist/agent/turn/task-digest.d.ts +2 -5
- package/dist/agent/turn/task-digest.js +25 -45
- package/dist/agent/turn/turn-context.js +4 -6
- package/dist/agent/turn/turn-error.d.ts +1 -1
- package/dist/agent/turn/turn-error.js +9 -0
- package/dist/agent/turn/turn-pipeline.d.ts +10 -5
- package/dist/agent/turn/turn-pipeline.js +36 -7
- package/dist/agent/turn/turn-prompt.d.ts +2 -0
- package/dist/agent/turn/turn-prompt.js +2 -1
- package/dist/agent/turn/turn-recovery.js +4 -1
- package/dist/agent/types.d.ts +20 -2
- package/dist/agent/types.js +2 -0
- package/dist/app/auth-command.d.ts +25 -0
- package/dist/app/auth-command.js +200 -67
- package/dist/app/home.d.ts +7 -8
- package/dist/app/home.js +143 -56
- package/dist/channel/channel-context.d.ts +6 -0
- package/dist/channel/config.d.ts +3 -0
- package/dist/channel/config.js +11 -5
- package/dist/commands/catalog.js +22 -6
- package/dist/desk/commands.d.ts +31 -4
- package/dist/desk/commands.js +101 -15
- package/dist/desk/paths.d.ts +6 -0
- package/dist/desk/paths.js +21 -1
- package/dist/desk/registry.d.ts +11 -0
- package/dist/desk/registry.js +53 -9
- package/dist/desk/types.d.ts +66 -1
- package/dist/dingtalk/config.js +10 -10
- package/dist/dingtalk/delivery.js +2 -0
- package/dist/dingtalk/inbound.js +2 -3
- package/dist/events/watcher.d.ts +1 -1
- package/dist/events/watcher.js +2 -2
- package/dist/main.js +15 -3
- package/dist/memory/boundary-work.d.ts +2 -1
- package/dist/memory/boundary-work.js +1 -1
- package/dist/memory/lifecycle.d.ts +2 -1
- package/dist/memory/lifecycle.js +2 -2
- package/dist/memory/reflect-job.d.ts +2 -1
- package/dist/memory/reflect-job.js +1 -1
- package/dist/memory/reflect.d.ts +2 -1
- package/dist/memory/reflect.js +2 -1
- package/dist/memory/scheduler.d.ts +2 -1
- package/dist/memory/scheduler.js +1 -1
- package/dist/memory/session-corpus.js +7 -1
- package/dist/memory/session-search.d.ts +2 -1
- package/dist/memory/session-search.js +1 -1
- package/dist/memory/sidecar-worker.d.ts +2 -1
- package/dist/memory/sidecar-worker.js +2 -4
- package/dist/models/credential-work.d.ts +7 -0
- package/dist/models/credential-work.js +36 -0
- package/dist/models/login-ui.js +4 -4
- package/dist/models/provider-login.js +7 -6
- package/dist/models/requests.d.ts +8 -0
- package/dist/models/requests.js +69 -0
- package/dist/models/runtime.d.ts +3 -1
- package/dist/models/runtime.js +9 -2
- package/dist/playbooks/agent-delegation.md +19 -45
- package/dist/playbooks/background-jobs.md +1 -1
- package/dist/playbooks/catalog.js +1 -1
- package/dist/playbooks/delegation-inline.md +25 -0
- package/dist/playbooks/delegation-recovery.md +28 -0
- package/dist/playbooks/event-scheduling.md +18 -37
- package/dist/playbooks/event-sensors.md +26 -0
- package/dist/playbooks/event-task-template.md +22 -0
- package/dist/playbooks/learning-and-skills.md +26 -0
- package/dist/playbooks/memory-operations.md +36 -0
- package/dist/playbooks/outbound-media.md +2 -2
- package/dist/playbooks/runtime-files.md +29 -0
- package/dist/playbooks/runtime-operations.md +25 -0
- package/dist/playbooks/runtime-orientation.md +18 -53
- package/dist/playbooks/task-lead.md +22 -68
- package/dist/playbooks/task-manage.md +38 -0
- package/dist/playbooks/task-recovery.md +24 -0
- package/dist/playbooks/task-verify.md +22 -0
- package/dist/runtime/bootstrap.d.ts +4 -0
- package/dist/runtime/bootstrap.js +82 -22
- package/dist/runtime/daemon-lock.js +3 -3
- package/dist/runtime/desk-runtime.d.ts +33 -6
- package/dist/runtime/desk-runtime.js +302 -47
- package/dist/runtime/ingress-commands.js +24 -4
- package/dist/runtime/shutdown.d.ts +3 -1
- package/dist/runtime/shutdown.js +1 -0
- package/dist/runtime/task-close.d.ts +1 -1
- package/dist/runtime/task-close.js +6 -3
- package/dist/runtime/task-control.d.ts +1 -3
- package/dist/runtime/task-control.js +15 -11
- package/dist/runtime/task-input.js +1 -1
- package/dist/runtime/task-lane-types.d.ts +12 -2
- package/dist/runtime/task-lane-types.js +9 -0
- package/dist/runtime/task-lane.d.ts +1 -0
- package/dist/runtime/task-lane.js +17 -14
- package/dist/runtime/task-step.d.ts +3 -3
- package/dist/runtime/task-step.js +23 -14
- package/dist/runtime/transports.js +6 -5
- package/dist/security/command-guard.js +23 -1
- package/dist/subagents/commands.js +14 -5
- package/dist/subagents/completion-wake.js +6 -0
- package/dist/subagents/dispatch.js +20 -18
- package/dist/subagents/external/dispatch.js +20 -14
- package/dist/subagents/external/run.js +10 -20
- package/dist/subagents/external/settlement.js +5 -1
- package/dist/subagents/internal/outcome.js +19 -12
- package/dist/subagents/internal/provider-retry.js +1 -3
- package/dist/subagents/internal/run.d.ts +1 -1
- package/dist/subagents/internal/run.js +27 -4
- package/dist/subagents/internal/state.d.ts +1 -3
- package/dist/subagents/internal/state.js +1 -2
- package/dist/subagents/internal/worker.js +17 -9
- package/dist/subagents/result.d.ts +5 -2
- package/dist/subagents/result.js +35 -6
- package/dist/subagents/run-record.d.ts +21 -0
- package/dist/subagents/run-record.js +5 -0
- package/dist/subagents/runs.d.ts +4 -7
- package/dist/subagents/runs.js +24 -35
- package/dist/subagents/task-envelope.js +5 -0
- package/dist/subagents/task-settlement.js +1 -0
- package/dist/subagents/types.d.ts +14 -4
- package/dist/subagents/workspace-lease.d.ts +37 -10
- package/dist/subagents/workspace-lease.js +121 -13
- package/dist/subagents/worktree.d.ts +47 -5
- package/dist/subagents/worktree.js +316 -30
- package/dist/tasks/brief.d.ts +5 -1
- package/dist/tasks/brief.js +19 -5
- package/dist/tasks/commands.d.ts +3 -1
- package/dist/tasks/commands.js +17 -6
- package/dist/tasks/control.d.ts +9 -0
- package/dist/tasks/loop-log.d.ts +10 -0
- package/dist/tasks/loop-log.js +1 -1
- package/dist/tasks/receipts.d.ts +7 -3
- package/dist/tasks/receipts.js +34 -5
- package/dist/tools/bash.d.ts +3 -0
- package/dist/tools/bash.js +27 -15
- package/dist/tools/contract/presentation.js +4 -1
- package/dist/tools/edit-diff.d.ts +11 -0
- package/dist/tools/edit-diff.js +148 -0
- package/dist/tools/edit-match.d.ts +18 -0
- package/dist/tools/edit-match.js +242 -0
- package/dist/tools/edit.d.ts +10 -2
- package/dist/tools/edit.js +91 -361
- package/dist/tools/event-manage.d.ts +1 -2
- package/dist/tools/event-manage.js +27 -38
- package/dist/tools/file-observations.d.ts +9 -0
- package/dist/tools/file-observations.js +50 -0
- package/dist/tools/glob-match.d.ts +3 -1
- package/dist/tools/glob-match.js +40 -17
- package/dist/tools/glob.d.ts +1 -0
- package/dist/tools/glob.js +39 -19
- package/dist/tools/grep-command.d.ts +13 -0
- package/dist/tools/grep-command.js +77 -0
- package/dist/tools/grep.js +96 -201
- package/dist/tools/index.d.ts +4 -1
- package/dist/tools/index.js +7 -4
- package/dist/tools/job.js +12 -11
- package/dist/tools/read.d.ts +2 -0
- package/dist/tools/read.js +10 -2
- package/dist/tools/registry.d.ts +16 -11
- package/dist/tools/registry.js +29 -11
- package/dist/tools/session-search.d.ts +2 -1
- package/dist/tools/session-search.js +14 -4
- package/dist/tools/skill.js +13 -12
- package/dist/tools/subagent-manage.js +10 -3
- package/dist/tools/subagent.d.ts +22 -2
- package/dist/tools/subagent.js +19 -18
- package/dist/tools/task-manage/control-tools.js +1 -1
- package/dist/tools/task-manage/factory.d.ts +2 -2
- package/dist/tools/task-manage/factory.js +39 -3
- package/dist/tools/task-manage/lifecycle.d.ts +2 -2
- package/dist/tools/task-manage/lifecycle.js +7 -4
- package/dist/tools/task-manage/shared.d.ts +1 -1
- package/dist/tools/task-manage/types.d.ts +1 -0
- package/dist/tools/write-content.d.ts +7 -1
- package/dist/tools/write-content.js +18 -6
- package/dist/tools/write.d.ts +3 -0
- package/dist/tools/write.js +6 -2
- package/dist/tui/cli.d.ts +5 -0
- package/dist/tui/cli.js +97 -31
- package/dist/tui/client.d.ts +5 -0
- package/dist/tui/client.js +63 -21
- package/dist/tui/frontend.d.ts +2 -0
- package/dist/tui/pitui-frontend.d.ts +4 -0
- package/dist/tui/pitui-frontend.js +27 -0
- package/dist/tui/render.d.ts +1 -0
- package/dist/tui/render.js +5 -0
- package/dist/tui/session.js +6 -0
- package/dist/web/client.d.ts +1 -0
- package/dist/web/client.js +11 -0
- package/dist/web/fetch.js +6 -3
- package/dist/webapi/auth.d.ts +0 -3
- package/dist/webapi/auth.js +3 -7
- package/dist/webapi/config.js +17 -14
- package/dist/webapi/key-command.js +41 -41
- package/dist/webapi/response-state.d.ts +7 -1
- package/dist/webapi/response-state.js +166 -3
- package/dist/webapi/routes/websocket.js +24 -1
- package/dist/webapi/server.d.ts +3 -1
- package/dist/webapi/server.js +32 -1
- package/dist/webapi/service.js +8 -0
- package/dist/webapi/transport.d.ts +2 -0
- package/dist/webapi/transport.js +11 -1
- package/examples/sub-agents/README.md +9 -7
- package/examples/sub-agents/agy-main.md +21 -0
- package/examples/sub-agents/claude-high.md +21 -0
- package/examples/sub-agents/claude-main.md +21 -0
- package/examples/sub-agents/codex-flash.md +21 -0
- package/examples/sub-agents/codex-high.md +21 -0
- package/examples/sub-agents/codex-main.md +21 -0
- package/examples/sub-agents/codex-review.md +20 -0
- package/examples/sub-agents/cursor-high.md +20 -0
- package/examples/sub-agents/cursor-main.md +20 -0
- package/examples/sub-agents/glm-flash.md +21 -0
- package/examples/sub-agents/glm-high.md +21 -0
- package/examples/sub-agents/pi-scout.md +20 -0
- package/package.json +8 -9
- package/dist/agent/session/request-tools.d.ts +0 -3
- package/dist/agent/session/request-tools.js +0 -20
- package/dist/models/api-keys.d.ts +0 -11
- package/dist/models/api-keys.js +0 -22
- package/dist/playbooks/memory-and-learning.md +0 -55
- package/examples/sub-agents/agents/agy-main.md +0 -23
- package/examples/sub-agents/agents/claude-high.md +0 -23
- package/examples/sub-agents/agents/claude-main.md +0 -23
- package/examples/sub-agents/agents/codex-flash.md +0 -23
- package/examples/sub-agents/agents/codex-high.md +0 -23
- package/examples/sub-agents/agents/codex-main.md +0 -23
- package/examples/sub-agents/agents/codex-review.md +0 -23
- package/examples/sub-agents/agents/cursor-high.md +0 -22
- package/examples/sub-agents/agents/cursor-main.md +0 -22
- package/examples/sub-agents/agents/glm-flash.md +0 -23
- package/examples/sub-agents/agents/glm-high.md +0 -23
package/dist/tasks/receipts.js
CHANGED
|
@@ -9,6 +9,12 @@ import { parseTaskItems } from "./contract.js";
|
|
|
9
9
|
* User copy under spec 053: Chinese, the four markers, no tool names or internal tags, and every
|
|
10
10
|
* next step is something the user can type.
|
|
11
11
|
*/
|
|
12
|
+
/** A `task_report` message, tagged with its task id when the leader did not already name it. */
|
|
13
|
+
export function reportReceipt(id, text) {
|
|
14
|
+
if (text.includes(id))
|
|
15
|
+
return text;
|
|
16
|
+
return `**任务 \`${id}\` 汇报**\n${text}`;
|
|
17
|
+
}
|
|
12
18
|
/** A `task_ask` question, delivered once the step ends. */
|
|
13
19
|
export function askReceipt(id, question) {
|
|
14
20
|
return `⚠️ 任务 \`${id}\` 需要你的决定:${question}\n直接回复我,或用 \`/tasks msg ${id} <内容>\` 回答。`;
|
|
@@ -21,7 +27,25 @@ export function pausedReceipt(id, title, reason, breach) {
|
|
|
21
27
|
`查看:\`/tasks show ${id}\`;${resume}:\`/tasks resume ${id}${grant}\`\n` +
|
|
22
28
|
`不再需要:\`/tasks cancel ${id}\``);
|
|
23
29
|
}
|
|
24
|
-
export function
|
|
30
|
+
export function formatRetainedWorktreeLines(retained) {
|
|
31
|
+
if (!retained || retained.length === 0)
|
|
32
|
+
return [];
|
|
33
|
+
const lines = retained.slice(0, 3).map((item) => {
|
|
34
|
+
const ref = item.branch ? `分支 \`${item.branch}\`` : `提交 \`${item.headSha.slice(0, 12)}\``;
|
|
35
|
+
const why = {
|
|
36
|
+
dirty: "含未提交改动",
|
|
37
|
+
unmerged: "含未合并提交",
|
|
38
|
+
busy: "仍有委派正在使用",
|
|
39
|
+
unavailable: "暂时无法确认状态",
|
|
40
|
+
}[item.reason];
|
|
41
|
+
return `- ⚠️ 保留工作树:\`${item.path}\`(委派 \`${item.runId}\`,${ref},${why})`;
|
|
42
|
+
});
|
|
43
|
+
if (retained.length > 3) {
|
|
44
|
+
lines.push(`- ⚠️ 另有 ${retained.length - 3} 个工作树已保留在本地仓库`);
|
|
45
|
+
}
|
|
46
|
+
return lines;
|
|
47
|
+
}
|
|
48
|
+
export function completedReceipt(id, title, document, closedAt, retainedWorktrees) {
|
|
25
49
|
const usage = document.fields.usage;
|
|
26
50
|
const since = usage ? parseLocalTime(usage.startedAt) : undefined;
|
|
27
51
|
const end = parseLocalTime(closedAt);
|
|
@@ -36,13 +60,18 @@ export function completedReceipt(id, title, document, closedAt) {
|
|
|
36
60
|
...(items
|
|
37
61
|
? [`- 工作项:${items.done}/${items.total}${dropped.length > 0 ? `;已放弃:${dropped.join("、")}` : ""}`]
|
|
38
62
|
: []),
|
|
63
|
+
...formatRetainedWorktreeLines(retainedWorktrees),
|
|
39
64
|
].join("\n"), { nextStepHint: `用 \`/tasks show ${id}\` 查看详情` }).text;
|
|
40
65
|
}
|
|
41
66
|
/** The leader cancelled its own task. */
|
|
42
|
-
export function cancelledByLeaderReceipt(id, title, note) {
|
|
43
|
-
|
|
67
|
+
export function cancelledByLeaderReceipt(id, title, note, retainedWorktrees) {
|
|
68
|
+
const retained = formatRetainedWorktreeLines(retainedWorktrees);
|
|
69
|
+
return capReply([`🛑 任务 \`${id}\`(${title})已取消:${truncate(note.replace(/\s+/g, " "), 160)}`, ...retained].join("\n"), { nextStepHint: `用 \`/tasks log ${id}\` 查看记录` }).text;
|
|
44
70
|
}
|
|
45
71
|
/** The user cancelled from another channel of the desk; the report channel should not be left wondering. */
|
|
46
|
-
export function cancelledByUserReceipt(id, title) {
|
|
47
|
-
|
|
72
|
+
export function cancelledByUserReceipt(id, title, retainedWorktrees) {
|
|
73
|
+
const retained = formatRetainedWorktreeLines(retainedWorktrees);
|
|
74
|
+
return capReply([`🛑 任务 \`${id}\`(${title})已被取消。`, ...retained].join("\n"), {
|
|
75
|
+
nextStepHint: `用 \`/tasks log ${id}\` 查看记录`,
|
|
76
|
+
}).text;
|
|
48
77
|
}
|
package/dist/tools/bash.d.ts
CHANGED
|
@@ -10,6 +10,9 @@ import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.j
|
|
|
10
10
|
* Callers that legitimately need longer must pass an explicit `timeout`.
|
|
11
11
|
*/
|
|
12
12
|
export declare const DEFAULT_BASH_TIMEOUT_SECONDS = 300;
|
|
13
|
+
export declare const BASH_MAX_OUTPUT_BYTES: number;
|
|
14
|
+
export declare const BASH_MAX_OUTPUT_LINES = 1000;
|
|
15
|
+
export declare function formatFullOutputHint(path: string): string;
|
|
13
16
|
declare const bashSchema: Type.TObject<{
|
|
14
17
|
command: Type.TString;
|
|
15
18
|
timeout: Type.TOptional<Type.TInteger>;
|
package/dist/tools/bash.js
CHANGED
|
@@ -12,7 +12,7 @@ import { logSecurityEvent } from "../security/logger.js";
|
|
|
12
12
|
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
13
13
|
import { clipText } from "../shared/text-utils.js";
|
|
14
14
|
import { maybeOptimizeCommand } from "./command-optimizer.js";
|
|
15
|
-
import {
|
|
15
|
+
import { formatSize, truncateTail } from "./truncate.js";
|
|
16
16
|
/**
|
|
17
17
|
* Default wall-clock timeout for bash commands when the caller supplies neither a
|
|
18
18
|
* per-call `timeout` nor a tool-level default. Without this, a hung command (a stray
|
|
@@ -20,10 +20,16 @@ import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail } from "
|
|
|
20
20
|
* Callers that legitimately need longer must pass an explicit `timeout`.
|
|
21
21
|
*/
|
|
22
22
|
export const DEFAULT_BASH_TIMEOUT_SECONDS = 300;
|
|
23
|
+
export const BASH_MAX_OUTPUT_BYTES = 30 * 1024;
|
|
24
|
+
export const BASH_MAX_OUTPUT_LINES = 1000;
|
|
25
|
+
const outputLimits = { maxBytes: BASH_MAX_OUTPUT_BYTES, maxLines: BASH_MAX_OUTPUT_LINES };
|
|
26
|
+
export function formatFullOutputHint(path) {
|
|
27
|
+
return `Full output: ${path} — use grep on this path to locate errors, or read with offset/limit.`;
|
|
28
|
+
}
|
|
23
29
|
/** Spill files kept per desk before the oldest are pruned on the next tool build. */
|
|
24
30
|
const BASH_LOG_RETENTION = 40;
|
|
25
31
|
/** Bytes read back from the spill file when the in-memory capture was truncated (D2.3). */
|
|
26
|
-
const TAIL_FROM_SPILL_BYTES =
|
|
32
|
+
const TAIL_FROM_SPILL_BYTES = BASH_MAX_OUTPUT_BYTES * 4;
|
|
27
33
|
/**
|
|
28
34
|
* Where the "full output" spill file for a command goes: under `<deskDir>/logs/` on the main
|
|
29
35
|
* path, next to the rest of the agent's files (fix plan §2.2). Sub-agents get no channel dir, so
|
|
@@ -71,13 +77,13 @@ const bashSchema = Type.Object({
|
|
|
71
77
|
description: `Timeout in seconds. Defaults to ${DEFAULT_BASH_TIMEOUT_SECONDS}s; pass a larger value for long-running commands.`,
|
|
72
78
|
})),
|
|
73
79
|
async: Type.Optional(Type.Boolean({
|
|
74
|
-
description: "Run in the background
|
|
80
|
+
description: "Run in the background; returns a job id immediately and wakes this session on completion.",
|
|
75
81
|
})),
|
|
76
82
|
notify: Type.Optional(Type.Boolean({
|
|
77
|
-
description: "
|
|
83
|
+
description: "Wake this session when the async job finishes (default true). False is fire-and-forget.",
|
|
78
84
|
})),
|
|
79
85
|
});
|
|
80
|
-
/** Schema
|
|
86
|
+
/** Schema for sessions without background execution: the async fields are
|
|
81
87
|
* dropped so the model is never offered a parameter its context cannot honor (fix plan §3.2). */
|
|
82
88
|
const bashSchemaNoJobs = Type.Omit(bashSchema, ["async", "notify"]);
|
|
83
89
|
/**
|
|
@@ -160,12 +166,16 @@ export function createBashTool(executor, options = {}) {
|
|
|
160
166
|
// is a process-local measure only: external sub-agents are separate host processes and are
|
|
161
167
|
// not serialized by it. The SDK serializes the whole batch if *any* tool in it is sequential.
|
|
162
168
|
executionMode: "sequential",
|
|
163
|
-
description: `
|
|
169
|
+
description: `Run a ${EXECUTOR_SHELL_IS_BASH ? "bash" : "POSIX sh"} command in the current directory. Returns output and exit code. Output beyond ${BASH_MAX_OUTPUT_LINES} lines or ${BASH_MAX_OUTPUT_BYTES / 1024}KB spills to a file. Default timeout: ${options.defaultTimeoutSeconds ?? DEFAULT_BASH_TIMEOUT_SECONDS}s.`,
|
|
164
170
|
parameters: (options.jobManager ? bashSchema : bashSchemaNoJobs),
|
|
165
171
|
execute: async (_toolCallId, { command, timeout, async: runAsync, notify, }, signal) => {
|
|
166
172
|
if (securityConfig.enabled && securityConfig.commandGuard.enabled) {
|
|
167
173
|
const guardResult = guardCommand(command, securityConfig.commandGuard);
|
|
168
174
|
if (!guardResult.allowed) {
|
|
175
|
+
if (guardResult.category === "unsupported-shell") {
|
|
176
|
+
throw new RecoverableToolError(`Command rejected by static shell parser (${guardResult.reason ?? "unsupported syntax"}). ` +
|
|
177
|
+
"Rewrite using simple commands without shell expansions, globs, or heredocs, or use the dedicated read, write, edit, glob, or grep tools instead.");
|
|
178
|
+
}
|
|
169
179
|
await logSecurityEvent(securityContext.agentWorkspaceDir, securityConfig, {
|
|
170
180
|
type: "command",
|
|
171
181
|
tool: "bash",
|
|
@@ -201,7 +211,7 @@ export function createBashTool(executor, options = {}) {
|
|
|
201
211
|
throw new RecoverableToolError("Task-owned jobs must notify their task when they finish. Keep notify=true (the default); only use notify=false for fire-and-forget work outside a task.");
|
|
202
212
|
}
|
|
203
213
|
if (!options.jobManager) {
|
|
204
|
-
throw new RecoverableToolError("This context does not support background execution (
|
|
214
|
+
throw new RecoverableToolError("This context does not support background execution (async=true requires a persistent chat or task session). Run the command in the foreground without async.");
|
|
205
215
|
}
|
|
206
216
|
if (!options.channelId)
|
|
207
217
|
throw new Error("Background execution has no delivery channel; run without async and have the deployer restore this context.");
|
|
@@ -240,6 +250,7 @@ export function createBashTool(executor, options = {}) {
|
|
|
240
250
|
// output" for a command whose real output exceeds that cap. It is deleted below when it
|
|
241
251
|
// turns out not to be needed.
|
|
242
252
|
const buildOutputText = async (stdout, stderr, spillPath, captureTruncated) => {
|
|
253
|
+
const fullOutputHint = formatFullOutputHint(spillPath);
|
|
243
254
|
let output = "";
|
|
244
255
|
if (stdout)
|
|
245
256
|
output += stdout;
|
|
@@ -254,38 +265,39 @@ export function createBashTool(executor, options = {}) {
|
|
|
254
265
|
// spill file — the one uncapped copy — and never quote a total line count we never saw.
|
|
255
266
|
if (captureTruncated) {
|
|
256
267
|
let tailSource = output;
|
|
268
|
+
let hasFullTail = false;
|
|
257
269
|
try {
|
|
258
270
|
tailSource = await readFileTail(spillPath, TAIL_FROM_SPILL_BYTES);
|
|
271
|
+
hasFullTail = true;
|
|
259
272
|
}
|
|
260
273
|
catch {
|
|
261
274
|
// Spill unreadable: fall back to the capped head's tail; still bounded.
|
|
262
275
|
}
|
|
263
|
-
const tailTrunc = truncateTail(tailSource);
|
|
276
|
+
const tailTrunc = truncateTail(tailSource, outputLimits);
|
|
264
277
|
const shownBytes = Buffer.byteLength(tailTrunc.content, "utf-8");
|
|
265
278
|
const text = `${tailTrunc.content || "(no output)"}\n\n` +
|
|
266
|
-
`[Output capture was cut off
|
|
279
|
+
`[Output capture was cut off; showing the last ${formatSize(shownBytes)} of ${hasFullTail ? "the full output" : "the captured output"}. ${fullOutputHint}]`;
|
|
267
280
|
return {
|
|
268
281
|
text,
|
|
269
282
|
details: { truncation: tailTrunc, fullOutputPath: spillPath, producedOutput: true },
|
|
270
283
|
};
|
|
271
284
|
}
|
|
272
|
-
const truncation = truncateTail(output);
|
|
285
|
+
const truncation = truncateTail(output, outputLimits);
|
|
273
286
|
let text = truncation.content || "(no output)";
|
|
274
287
|
let details;
|
|
275
288
|
if (truncation.truncated) {
|
|
276
289
|
details = { truncation, fullOutputPath: spillPath };
|
|
277
290
|
const startLine = truncation.totalLines - truncation.outputLines + 1;
|
|
278
291
|
const endLine = truncation.totalLines;
|
|
279
|
-
const fullOutputHint = ` Full output: ${spillPath}`;
|
|
280
292
|
if (truncation.lastLinePartial) {
|
|
281
293
|
const lastLineSize = formatSize(Buffer.byteLength(output.split("\n").pop() || "", "utf-8"));
|
|
282
|
-
text += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize})
|
|
294
|
+
text += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). ${fullOutputHint}]`;
|
|
283
295
|
}
|
|
284
296
|
else if (truncation.truncatedBy === "lines") {
|
|
285
|
-
text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}
|
|
297
|
+
text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. ${fullOutputHint}]`;
|
|
286
298
|
}
|
|
287
299
|
else {
|
|
288
|
-
text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(
|
|
300
|
+
text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(BASH_MAX_OUTPUT_BYTES)} limit). ${fullOutputHint}]`;
|
|
289
301
|
}
|
|
290
302
|
}
|
|
291
303
|
else {
|
|
@@ -327,7 +339,7 @@ export function createBashTool(executor, options = {}) {
|
|
|
327
339
|
}
|
|
328
340
|
const built = await buildOutputText(error.stdout, error.stderr, spillPath, error.captureTruncated);
|
|
329
341
|
const nextStep = error.reason === "timeout"
|
|
330
|
-
? `Retry with a larger \`timeout\` (currently ${error.timeoutSeconds}s)
|
|
342
|
+
? `Retry with a larger \`timeout\` (currently ${error.timeoutSeconds}s)${options.jobManager ? " or pass `async: true` to get a completion wake" : " or split the command into shorter steps"}.`
|
|
331
343
|
: "The command was stopped (e.g. by /stop or a run cancellation); partial output above.";
|
|
332
344
|
const outputText = `${built.text}\n\n[${error.message}; partial output above. ${nextStep}]`;
|
|
333
345
|
const details = { ...built.details, timedOut: true };
|
|
@@ -52,7 +52,10 @@ const DESCRIBERS = {
|
|
|
52
52
|
const path = str(args, "path");
|
|
53
53
|
return `搜索 "${clipText(pattern, 40, { collapseWhitespace: true })}"${path ? ` · ${path}` : ""}`;
|
|
54
54
|
},
|
|
55
|
-
edit: (args) =>
|
|
55
|
+
edit: (args) => {
|
|
56
|
+
const count = isRecord(args) && Array.isArray(args.edits) ? args.edits.length : 0;
|
|
57
|
+
return `编辑 ${str(args, "path") ?? "?"}${count > 1 ? ` (${count} 处)` : ""}`;
|
|
58
|
+
},
|
|
56
59
|
write: (args) => `写入 ${str(args, "path") ?? "?"}`,
|
|
57
60
|
bash: (args) => {
|
|
58
61
|
const command = clipText(str(args, "command") ?? "?", 60, { collapseWhitespace: true });
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { FileStore } from "../file-store.js";
|
|
2
|
+
export declare function renderEditDiff(path: string, before: Buffer, after: Buffer): {
|
|
3
|
+
diff: string;
|
|
4
|
+
patch: string;
|
|
5
|
+
};
|
|
6
|
+
export declare function clampDiffForEcho(diff: string): string;
|
|
7
|
+
/** Show a few local windows without loading the full file. */
|
|
8
|
+
export declare function renderStreamingEditDiff(fileStore: FileStore, target: string, path: string, fileSize: number, needle: Buffer, replacement: Buffer, matchOffsets: number[], lineNumbers: Map<number, number>, signal?: AbortSignal): Promise<{
|
|
9
|
+
diff: string;
|
|
10
|
+
patch: string;
|
|
11
|
+
}>;
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import * as Diff from "diff";
|
|
2
|
+
import { countNewlines } from "./edit-match.js";
|
|
3
|
+
const DIFF_ECHO_MAX_LINES = 40;
|
|
4
|
+
const DIFF_ECHO_MAX_BYTES = 8 * 1024;
|
|
5
|
+
const DIFF_WINDOW_BYTES = 2000;
|
|
6
|
+
const MAX_DIFF_WINDOWS = 5;
|
|
7
|
+
export function renderEditDiff(path, before, after) {
|
|
8
|
+
const oldText = before.toString("utf-8");
|
|
9
|
+
const newText = after.toString("utf-8");
|
|
10
|
+
return { diff: generateDiffString(oldText, newText), patch: Diff.createPatch(path, oldText, newText) };
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Generate a unified diff string with line numbers and context. `startLineOld`/`startLineNew` let
|
|
14
|
+
* a caller render a *window* of a larger file (spec 044, D2.3) while still printing the file's real
|
|
15
|
+
* absolute line numbers instead of restarting at 1.
|
|
16
|
+
*/
|
|
17
|
+
function generateDiffString(oldContent, newContent, contextLines = 4, startLineOld = 1, startLineNew = 1) {
|
|
18
|
+
const parts = Diff.diffLines(oldContent, newContent);
|
|
19
|
+
const output = [];
|
|
20
|
+
const oldLines = oldContent.split("\n");
|
|
21
|
+
const newLines = newContent.split("\n");
|
|
22
|
+
const maxLineNum = Math.max(startLineOld + oldLines.length, startLineNew + newLines.length);
|
|
23
|
+
const lineNumWidth = String(maxLineNum).length;
|
|
24
|
+
let oldLineNum = startLineOld;
|
|
25
|
+
let newLineNum = startLineNew;
|
|
26
|
+
let lastWasChange = false;
|
|
27
|
+
for (let i = 0; i < parts.length; i++) {
|
|
28
|
+
const part = parts[i];
|
|
29
|
+
const raw = part.value.split("\n");
|
|
30
|
+
if (raw[raw.length - 1] === "") {
|
|
31
|
+
raw.pop();
|
|
32
|
+
}
|
|
33
|
+
if (part.added || part.removed) {
|
|
34
|
+
for (const line of raw) {
|
|
35
|
+
if (part.added) {
|
|
36
|
+
const lineNum = String(newLineNum).padStart(lineNumWidth, " ");
|
|
37
|
+
output.push(`+${lineNum} ${line}`);
|
|
38
|
+
newLineNum++;
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
const lineNum = String(oldLineNum).padStart(lineNumWidth, " ");
|
|
42
|
+
output.push(`-${lineNum} ${line}`);
|
|
43
|
+
oldLineNum++;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
lastWasChange = true;
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
const nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed);
|
|
50
|
+
if (lastWasChange || nextPartIsChange) {
|
|
51
|
+
let linesToShow = raw;
|
|
52
|
+
let skipStart = 0;
|
|
53
|
+
let skipEnd = 0;
|
|
54
|
+
if (!lastWasChange) {
|
|
55
|
+
skipStart = Math.max(0, raw.length - contextLines);
|
|
56
|
+
linesToShow = raw.slice(skipStart);
|
|
57
|
+
}
|
|
58
|
+
if (!nextPartIsChange && linesToShow.length > contextLines) {
|
|
59
|
+
skipEnd = linesToShow.length - contextLines;
|
|
60
|
+
linesToShow = linesToShow.slice(0, contextLines);
|
|
61
|
+
}
|
|
62
|
+
if (skipStart > 0) {
|
|
63
|
+
oldLineNum += skipStart;
|
|
64
|
+
newLineNum += skipStart;
|
|
65
|
+
output.push(` ${"".padStart(lineNumWidth, " ")} ...`);
|
|
66
|
+
}
|
|
67
|
+
for (const line of linesToShow) {
|
|
68
|
+
const lineNum = String(oldLineNum).padStart(lineNumWidth, " ");
|
|
69
|
+
output.push(` ${lineNum} ${line}`);
|
|
70
|
+
oldLineNum++;
|
|
71
|
+
newLineNum++;
|
|
72
|
+
}
|
|
73
|
+
if (skipEnd > 0) {
|
|
74
|
+
output.push(` ${"".padStart(lineNumWidth, " ")} ...`);
|
|
75
|
+
}
|
|
76
|
+
oldLineNum += skipEnd;
|
|
77
|
+
newLineNum += skipEnd;
|
|
78
|
+
}
|
|
79
|
+
else {
|
|
80
|
+
oldLineNum += raw.length;
|
|
81
|
+
newLineNum += raw.length;
|
|
82
|
+
}
|
|
83
|
+
lastWasChange = false;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return output.join("\n");
|
|
87
|
+
}
|
|
88
|
+
export function clampDiffForEcho(diff) {
|
|
89
|
+
const lines = diff.split("\n");
|
|
90
|
+
if (lines.length <= DIFF_ECHO_MAX_LINES && Buffer.byteLength(diff, "utf-8") <= DIFF_ECHO_MAX_BYTES) {
|
|
91
|
+
return diff;
|
|
92
|
+
}
|
|
93
|
+
let kept = lines.slice(0, DIFF_ECHO_MAX_LINES);
|
|
94
|
+
while (kept.length > 1 && Buffer.byteLength(kept.join("\n"), "utf-8") > DIFF_ECHO_MAX_BYTES) {
|
|
95
|
+
kept = kept.slice(0, -1);
|
|
96
|
+
}
|
|
97
|
+
let shown = kept.join("\n");
|
|
98
|
+
if (Buffer.byteLength(shown, "utf-8") > DIFF_ECHO_MAX_BYTES) {
|
|
99
|
+
// A single line still over budget: hard-cut on a UTF-8 boundary.
|
|
100
|
+
shown = Buffer.from(shown, "utf-8").subarray(0, DIFF_ECHO_MAX_BYTES).toString("utf-8");
|
|
101
|
+
}
|
|
102
|
+
const omitted = lines.length - kept.length;
|
|
103
|
+
return `${shown}\n[diff truncated${omitted > 0 ? `, ${omitted} more line(s)` : ""}; the full diff is in the tool result details]`;
|
|
104
|
+
}
|
|
105
|
+
/** Expand a byte window to the nearest line boundaries so the rendered diff never starts/ends mid-line. */
|
|
106
|
+
function expandToLineBoundaries(bytes, start, end, fileSize) {
|
|
107
|
+
let s = start;
|
|
108
|
+
while (s > 0 && bytes[s - 1] !== undefined && bytes[s - 1] !== 0x0a)
|
|
109
|
+
s--;
|
|
110
|
+
let e = end;
|
|
111
|
+
while (e < fileSize && bytes[e] !== undefined && bytes[e] !== 0x0a)
|
|
112
|
+
e++;
|
|
113
|
+
return { start: s, end: e };
|
|
114
|
+
}
|
|
115
|
+
/** Show a few local windows without loading the full file. */
|
|
116
|
+
export async function renderStreamingEditDiff(fileStore, target, path, fileSize, needle, replacement, matchOffsets, lineNumbers, signal) {
|
|
117
|
+
// Local diff windows, read from the *original* file before pass 2 rewrites it.
|
|
118
|
+
const diffParts = [];
|
|
119
|
+
const patchParts = [];
|
|
120
|
+
const shown = Math.min(matchOffsets.length, MAX_DIFF_WINDOWS);
|
|
121
|
+
for (let i = 0; i < shown; i++) {
|
|
122
|
+
const offset = matchOffsets[i];
|
|
123
|
+
const rawStart = Math.max(0, offset - DIFF_WINDOW_BYTES);
|
|
124
|
+
const rawEnd = Math.min(fileSize, offset + needle.length + DIFF_WINDOW_BYTES);
|
|
125
|
+
const { data: windowBytes } = await fileStore.readBytes(target, {
|
|
126
|
+
start: rawStart,
|
|
127
|
+
maxBytes: rawEnd - rawStart,
|
|
128
|
+
signal,
|
|
129
|
+
});
|
|
130
|
+
const { start, end } = expandToLineBoundaries(windowBytes, offset - rawStart, offset - rawStart + needle.length, windowBytes.length);
|
|
131
|
+
const oldWindow = windowBytes.subarray(start, end).toString("utf-8");
|
|
132
|
+
const newWindow = windowBytes.subarray(start, offset - rawStart).toString("utf-8") +
|
|
133
|
+
replacement.toString("utf-8") +
|
|
134
|
+
windowBytes.subarray(offset - rawStart + needle.length, end).toString("utf-8");
|
|
135
|
+
const startLine = lineNumbers.get(offset) ?? 1;
|
|
136
|
+
// The window itself may start mid-file above `offset`'s line, so back up the printed line
|
|
137
|
+
// number by however many newlines are in the window before the expanded start.
|
|
138
|
+
const linesBeforeWindowStart = countNewlines(windowBytes, 0, start);
|
|
139
|
+
const linesBeforeMatch = countNewlines(windowBytes, 0, offset - rawStart);
|
|
140
|
+
const windowStartLine = startLine - (linesBeforeMatch - linesBeforeWindowStart);
|
|
141
|
+
diffParts.push(generateDiffString(oldWindow, newWindow, 4, windowStartLine, windowStartLine));
|
|
142
|
+
patchParts.push(Diff.createPatch(path, oldWindow, newWindow));
|
|
143
|
+
}
|
|
144
|
+
if (matchOffsets.length > shown) {
|
|
145
|
+
diffParts.push(`[+${matchOffsets.length - shown} more occurrence(s) replaced, diff not shown]`);
|
|
146
|
+
}
|
|
147
|
+
return { diff: diffParts.join("\n\n"), patch: patchParts.join("\n") };
|
|
148
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { FileStore } from "../file-store.js";
|
|
2
|
+
export interface EditHunk {
|
|
3
|
+
oldText: string;
|
|
4
|
+
newText: string;
|
|
5
|
+
replaceAll?: boolean;
|
|
6
|
+
}
|
|
7
|
+
/** Resolve every edit against the original bytes before assembling any replacement. */
|
|
8
|
+
export declare function planInlineEdit(data: Buffer, path: string, hunks: EditHunk[]): {
|
|
9
|
+
newData: Buffer<ArrayBufferLike>;
|
|
10
|
+
occurrences: number;
|
|
11
|
+
};
|
|
12
|
+
export declare function planStreamingEdit(fileStore: FileStore, target: string, path: string, { oldText, newText, replaceAll }: EditHunk, signal?: AbortSignal): Promise<{
|
|
13
|
+
needle: Buffer<ArrayBuffer>;
|
|
14
|
+
replacement: Buffer<ArrayBuffer>;
|
|
15
|
+
matchOffsets: number[];
|
|
16
|
+
lineNumbers: Map<number, number>;
|
|
17
|
+
}>;
|
|
18
|
+
export declare function countNewlines(buf: Buffer, start: number, end: number): number;
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
2
|
+
const MAX_DIAGNOSTIC_LINES = 10;
|
|
3
|
+
const BINARY_SNIFF_BYTES = 8 * 1024;
|
|
4
|
+
const MAX_REPLACE_ALL_OFFSETS = 200_000;
|
|
5
|
+
const CRLF = Buffer.from("\r\n");
|
|
6
|
+
const BARE_LF = /(?<!\r)\n/g;
|
|
7
|
+
function toCrlf(text) {
|
|
8
|
+
return Buffer.from(text.replace(BARE_LF, "\r\n"));
|
|
9
|
+
}
|
|
10
|
+
function canRetryWithCrlf(text) {
|
|
11
|
+
return text.includes("\n") && !text.includes("\r\n");
|
|
12
|
+
}
|
|
13
|
+
function usesCrlfForReplacement(firstNewlineIsCrlf, oldText) {
|
|
14
|
+
return firstNewlineIsCrlf && (!oldText.includes("\n") || oldText.includes("\r\n"));
|
|
15
|
+
}
|
|
16
|
+
function binaryFileError(path) {
|
|
17
|
+
return new RecoverableToolError(`${path} looks like a binary file (a NUL byte appears in the first ${BINARY_SNIFF_BYTES} bytes). Use bash for binary edits.`);
|
|
18
|
+
}
|
|
19
|
+
function duplicateError(path, count, lines) {
|
|
20
|
+
const more = count > lines.length ? ` +${count - lines.length} more` : "";
|
|
21
|
+
return new RecoverableToolError(`Found ${count} occurrences of oldText in ${path} (at lines ${lines.join(", ")}${more}). Include more surrounding lines to uniquely identify the target, or set replaceAll: true.`);
|
|
22
|
+
}
|
|
23
|
+
function missingError(path, nearLines = []) {
|
|
24
|
+
return new RecoverableToolError(`Could not find exact oldText in ${path}. ` +
|
|
25
|
+
(nearLines.length
|
|
26
|
+
? `Near-matches with different whitespace/indentation appear around lines ${nearLines.join(", ")} — read that range to copy exact whitespace.`
|
|
27
|
+
: `Re-read ${path} around the target section to verify current content.`));
|
|
28
|
+
}
|
|
29
|
+
/** All non-overlapping byte offsets of `needle` in `haystack`, left to right (mirrors `String.split`). */
|
|
30
|
+
function findAllOffsets(haystack, needle) {
|
|
31
|
+
const offsets = [];
|
|
32
|
+
let from = 0;
|
|
33
|
+
while (true) {
|
|
34
|
+
const idx = haystack.indexOf(needle, from);
|
|
35
|
+
if (idx === -1)
|
|
36
|
+
break;
|
|
37
|
+
offsets.push(idx);
|
|
38
|
+
from = idx + needle.length;
|
|
39
|
+
}
|
|
40
|
+
return offsets;
|
|
41
|
+
}
|
|
42
|
+
function linesAtOffsets(data, offsets) {
|
|
43
|
+
let cursor = 0;
|
|
44
|
+
let line = 1;
|
|
45
|
+
return offsets.slice(0, MAX_DIAGNOSTIC_LINES).map((offset) => {
|
|
46
|
+
line += countNewlines(data, cursor, offset);
|
|
47
|
+
cursor = offset;
|
|
48
|
+
return line;
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
function findNearWhitespaceLines(data, text) {
|
|
52
|
+
const anchor = text.split("\n").find((line) => line.trim());
|
|
53
|
+
if (!anchor)
|
|
54
|
+
return [];
|
|
55
|
+
const trimmed = anchor.trim();
|
|
56
|
+
const lines = [];
|
|
57
|
+
let start = 0;
|
|
58
|
+
for (let line = 1; start < data.length && lines.length < 5; line++) {
|
|
59
|
+
const newline = data.indexOf(0x0a, start);
|
|
60
|
+
const end = newline < 0 ? data.length : newline;
|
|
61
|
+
const candidate = data.toString("utf-8", start, end).replace(/\r$/, "");
|
|
62
|
+
if (candidate !== anchor.replace(/\r$/, "") && candidate.trim() === trimmed)
|
|
63
|
+
lines.push(line);
|
|
64
|
+
start = end + 1;
|
|
65
|
+
}
|
|
66
|
+
return lines;
|
|
67
|
+
}
|
|
68
|
+
function spliceIntervals(data, intervals) {
|
|
69
|
+
const size = intervals.reduce((length, entry) => length + entry.replacement.length - (entry.end - entry.start), data.length);
|
|
70
|
+
const result = Buffer.allocUnsafe(size);
|
|
71
|
+
let cursor = 0;
|
|
72
|
+
let written = 0;
|
|
73
|
+
for (const { start, end, replacement } of intervals) {
|
|
74
|
+
written += data.copy(result, written, cursor, start);
|
|
75
|
+
written += replacement.copy(result, written);
|
|
76
|
+
cursor = end;
|
|
77
|
+
}
|
|
78
|
+
data.copy(result, written, cursor);
|
|
79
|
+
return result;
|
|
80
|
+
}
|
|
81
|
+
/** Resolve every edit against the original bytes before assembling any replacement. */
|
|
82
|
+
export function planInlineEdit(data, path, hunks) {
|
|
83
|
+
if (data.subarray(0, BINARY_SNIFF_BYTES).includes(0))
|
|
84
|
+
throw binaryFileError(path);
|
|
85
|
+
const firstLf = data.indexOf(0x0a);
|
|
86
|
+
const firstNewlineIsCrlf = firstLf > 0 && data[firstLf - 1] === 0x0d;
|
|
87
|
+
const containsCrlf = firstNewlineIsCrlf || data.includes(CRLF);
|
|
88
|
+
const intervals = [];
|
|
89
|
+
for (const [index, { oldText, newText, replaceAll }] of hunks.entries()) {
|
|
90
|
+
let needle = Buffer.from(oldText);
|
|
91
|
+
let offsets = findAllOffsets(data, needle);
|
|
92
|
+
let useCrlf = usesCrlfForReplacement(firstNewlineIsCrlf, oldText);
|
|
93
|
+
if (offsets.length === 0 && containsCrlf && canRetryWithCrlf(oldText)) {
|
|
94
|
+
needle = toCrlf(oldText);
|
|
95
|
+
offsets = findAllOffsets(data, needle);
|
|
96
|
+
useCrlf = true;
|
|
97
|
+
}
|
|
98
|
+
const location = hunks.length > 1 ? `${path} (edit #${index + 1})` : path;
|
|
99
|
+
if (offsets.length === 0)
|
|
100
|
+
throw missingError(location, findNearWhitespaceLines(data, oldText));
|
|
101
|
+
if (offsets.length > 1 && !replaceAll)
|
|
102
|
+
throw duplicateError(location, offsets.length, linesAtOffsets(data, offsets));
|
|
103
|
+
const replacement = useCrlf ? toCrlf(newText) : Buffer.from(newText);
|
|
104
|
+
for (const start of offsets)
|
|
105
|
+
intervals.push({ start, end: start + needle.length, replacement, hunk: index + 1 });
|
|
106
|
+
}
|
|
107
|
+
intervals.sort((a, b) => a.start - b.start);
|
|
108
|
+
for (let i = 1; i < intervals.length; i++) {
|
|
109
|
+
const previous = intervals[i - 1];
|
|
110
|
+
const current = intervals[i];
|
|
111
|
+
if (previous.end > current.start) {
|
|
112
|
+
const line = linesAtOffsets(data, [current.start])[0];
|
|
113
|
+
throw new RecoverableToolError(`Edits #${previous.hunk} and #${current.hunk} overlap around line ${line}; merge them into one edit hunk.`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return { newData: spliceIntervals(data, intervals), occurrences: intervals.length };
|
|
117
|
+
}
|
|
118
|
+
export async function planStreamingEdit(fileStore, target, path, { oldText, newText, replaceAll }, signal) {
|
|
119
|
+
let needle = Buffer.from(oldText);
|
|
120
|
+
const scanFor = (text) => scanOccurrences(readStreamChunks(fileStore, target, signal), text, replaceAll ? MAX_REPLACE_ALL_OFFSETS : MAX_DIAGNOSTIC_LINES);
|
|
121
|
+
let scan = await scanFor(needle);
|
|
122
|
+
let useCrlf = usesCrlfForReplacement(scan.firstNewlineIsCrlf, oldText);
|
|
123
|
+
if (scan.looksBinary)
|
|
124
|
+
throw binaryFileError(path);
|
|
125
|
+
if (scan.count === 0 && scan.headContainsCrlf && canRetryWithCrlf(oldText)) {
|
|
126
|
+
needle = toCrlf(oldText);
|
|
127
|
+
scan = await scanFor(needle);
|
|
128
|
+
useCrlf = true;
|
|
129
|
+
if (scan.looksBinary)
|
|
130
|
+
throw binaryFileError(path);
|
|
131
|
+
}
|
|
132
|
+
if (scan.count === 0)
|
|
133
|
+
throw missingError(path);
|
|
134
|
+
if (scan.count > 1 && !replaceAll)
|
|
135
|
+
throw duplicateError(path, scan.count, [...scan.lineNumbers.values()]);
|
|
136
|
+
if (!scan.offsets) {
|
|
137
|
+
throw new RecoverableToolError(`${path} has more than ${MAX_REPLACE_ALL_OFFSETS} matches. Add context to oldText to match fewer places.`);
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
needle,
|
|
141
|
+
replacement: useCrlf ? toCrlf(newText) : Buffer.from(newText),
|
|
142
|
+
matchOffsets: scan.offsets,
|
|
143
|
+
lineNumbers: scan.lineNumbers,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* A streaming scan for every non-overlapping occurrence of `needle`, safe against a match that
|
|
148
|
+
* straddles a chunk boundary (D2.2). Carries the last `needle.length - 1` bytes of each window into
|
|
149
|
+
* the next iteration so a split match is still found, without ever holding more than one window in
|
|
150
|
+
* memory. Also tracks the 1-indexed line number of each match (from a running newline count) and
|
|
151
|
+
* sniffs the first `BINARY_SNIFF_BYTES` for a NUL byte (D2.5).
|
|
152
|
+
*/
|
|
153
|
+
async function scanOccurrences(stream, needle, maxOffsets) {
|
|
154
|
+
const overlapLen = needle.length - 1;
|
|
155
|
+
let carry = Buffer.alloc(0);
|
|
156
|
+
let windowBaseOffset = 0;
|
|
157
|
+
let newlinesBeforeWindow = 0;
|
|
158
|
+
let count = 0;
|
|
159
|
+
// Absolute byte position just past the last accepted match. A window carries the last
|
|
160
|
+
// `overlapLen` bytes of its predecessor, so without this guard a match that ended inside the
|
|
161
|
+
// carry region would be re-found (from a fresh `from = 0`) and reported as a second, overlapping
|
|
162
|
+
// offset -- which `spliceBuffer` then turns into a corrupt file. Verified against a non-overlapping
|
|
163
|
+
// `Buffer.indexOf` reference over 165 boundary combinations.
|
|
164
|
+
let nextAllowed = 0;
|
|
165
|
+
let offsets = [];
|
|
166
|
+
const lineNumbers = new Map();
|
|
167
|
+
let looksBinary = false;
|
|
168
|
+
let sniffed = 0;
|
|
169
|
+
let headContainsCrlf = false;
|
|
170
|
+
let previousSniffedByte;
|
|
171
|
+
let firstNewlineIsCrlf;
|
|
172
|
+
let previousByte;
|
|
173
|
+
const CR = 0x0d;
|
|
174
|
+
for await (const chunk of stream) {
|
|
175
|
+
if (firstNewlineIsCrlf === undefined) {
|
|
176
|
+
const newline = chunk.indexOf(0x0a);
|
|
177
|
+
if (newline >= 0)
|
|
178
|
+
firstNewlineIsCrlf = (newline === 0 ? previousByte : chunk[newline - 1]) === CR;
|
|
179
|
+
previousByte = chunk.at(-1) ?? previousByte;
|
|
180
|
+
}
|
|
181
|
+
if (sniffed < BINARY_SNIFF_BYTES) {
|
|
182
|
+
const take = chunk.subarray(0, BINARY_SNIFF_BYTES - sniffed);
|
|
183
|
+
if (take.includes(0))
|
|
184
|
+
looksBinary = true;
|
|
185
|
+
headContainsCrlf ||= (previousSniffedByte === CR && take[0] === 0x0a) || take.includes(CRLF);
|
|
186
|
+
previousSniffedByte = take.at(-1) ?? previousSniffedByte;
|
|
187
|
+
sniffed += take.length;
|
|
188
|
+
}
|
|
189
|
+
const window = carry.length > 0 ? Buffer.concat([carry, chunk]) : chunk;
|
|
190
|
+
let from = Math.max(0, nextAllowed - windowBaseOffset);
|
|
191
|
+
let lineFrom = 0;
|
|
192
|
+
let line = newlinesBeforeWindow + 1;
|
|
193
|
+
while (true) {
|
|
194
|
+
const idx = window.indexOf(needle, from);
|
|
195
|
+
if (idx === -1)
|
|
196
|
+
break;
|
|
197
|
+
const absoluteOffset = windowBaseOffset + idx;
|
|
198
|
+
count++;
|
|
199
|
+
nextAllowed = absoluteOffset + needle.length;
|
|
200
|
+
if (offsets && offsets.length < maxOffsets) {
|
|
201
|
+
offsets.push(absoluteOffset);
|
|
202
|
+
// Only the first few matches need line numbers for diagnostics or diff windows.
|
|
203
|
+
if (lineNumbers.size < MAX_DIAGNOSTIC_LINES) {
|
|
204
|
+
line += countNewlines(window, lineFrom, idx);
|
|
205
|
+
lineFrom = idx;
|
|
206
|
+
lineNumbers.set(absoluteOffset, line);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
else if (offsets) {
|
|
210
|
+
offsets = undefined; // Overflowed: stop tracking, caller must fail closed if it needed them.
|
|
211
|
+
}
|
|
212
|
+
from = idx + needle.length;
|
|
213
|
+
}
|
|
214
|
+
const retiredLen = Math.max(0, window.length - overlapLen);
|
|
215
|
+
newlinesBeforeWindow += countNewlines(window, 0, retiredLen);
|
|
216
|
+
windowBaseOffset += retiredLen;
|
|
217
|
+
carry = window.subarray(retiredLen);
|
|
218
|
+
}
|
|
219
|
+
return {
|
|
220
|
+
count,
|
|
221
|
+
offsets,
|
|
222
|
+
lineNumbers,
|
|
223
|
+
looksBinary,
|
|
224
|
+
firstNewlineIsCrlf: firstNewlineIsCrlf === true,
|
|
225
|
+
headContainsCrlf,
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
export function countNewlines(buf, start, end) {
|
|
229
|
+
let n = 0;
|
|
230
|
+
for (let i = start; i < end; i++) {
|
|
231
|
+
if (buf[i] === 0x0a)
|
|
232
|
+
n++;
|
|
233
|
+
}
|
|
234
|
+
return n;
|
|
235
|
+
}
|
|
236
|
+
async function* readStreamChunks(store, path, signal) {
|
|
237
|
+
for await (const chunk of store.openRead(path)) {
|
|
238
|
+
if (signal?.aborted)
|
|
239
|
+
throw new Error("Aborted");
|
|
240
|
+
yield chunk;
|
|
241
|
+
}
|
|
242
|
+
}
|