@oyasmi/pipiclaw 0.9.5 → 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 +300 -142
- package/README.md +295 -140
- package/dist/agent/builtin-commands.d.ts +1 -1
- package/dist/agent/builtin-commands.js +1 -1
- package/dist/agent/channel-runner.d.ts +4 -3
- package/dist/agent/channel-runner.js +17 -28
- 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 +3 -2
- 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/compaction.d.ts +2 -0
- package/dist/agent/session/compaction.js +22 -14
- 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 +5 -3
- package/dist/agent/session/session-host.js +20 -16
- package/dist/agent/status-render.js +3 -0
- package/dist/agent/stop-watchdog.js +5 -1
- 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/turn/turn-state.d.ts +2 -0
- package/dist/agent/turn/turn-state.js +2 -1
- package/dist/agent/types.d.ts +23 -3
- 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/attachments.d.ts +4 -0
- package/dist/channel/attachments.js +4 -0
- 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/channel/store.d.ts +1 -1
- package/dist/commands/catalog.js +42 -10
- package/dist/commands/router.js +5 -1
- package/dist/desk/commands.d.ts +44 -5
- package/dist/desk/commands.js +162 -28
- package/dist/desk/paths.d.ts +6 -0
- package/dist/desk/paths.js +21 -1
- package/dist/desk/registry.d.ts +17 -2
- package/dist/desk/registry.js +122 -12
- package/dist/desk/types.d.ts +83 -1
- package/dist/dingtalk/bot.d.ts +1 -1
- package/dist/dingtalk/bot.js +4 -3
- package/dist/dingtalk/config.js +10 -10
- package/dist/dingtalk/delivery.js +15 -8
- package/dist/dingtalk/inbound-media.d.ts +36 -14
- package/dist/dingtalk/inbound-media.js +71 -12
- package/dist/dingtalk/inbound.d.ts +9 -2
- package/dist/dingtalk/inbound.js +17 -2
- package/dist/dingtalk/media.d.ts +4 -10
- package/dist/dingtalk/media.js +58 -32
- package/dist/events/commands.d.ts +2 -0
- package/dist/events/commands.js +13 -8
- package/dist/events/history.d.ts +9 -0
- package/dist/events/history.js +66 -0
- package/dist/events/parse.js +7 -3
- package/dist/events/types.d.ts +3 -0
- package/dist/events/watcher.d.ts +4 -8
- package/dist/events/watcher.js +53 -58
- package/dist/jobs/kill.d.ts +23 -0
- package/dist/jobs/kill.js +65 -0
- package/dist/jobs/manager.d.ts +19 -18
- package/dist/jobs/manager.js +36 -103
- 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 +25 -4
- package/dist/memory/scheduler.d.ts +2 -1
- package/dist/memory/scheduler.js +1 -1
- package/dist/memory/session-corpus.d.ts +1 -1
- package/dist/memory/session-corpus.js +76 -1
- package/dist/memory/session-search.d.ts +2 -1
- package/dist/memory/session-search.js +14 -12
- package/dist/memory/sidecar-worker.d.ts +2 -1
- package/dist/memory/sidecar-worker.js +2 -4
- package/dist/memory/store.d.ts +2 -0
- package/dist/memory/store.js +19 -9
- 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 +20 -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 +10 -0
- package/dist/runtime/bootstrap.js +93 -29
- package/dist/runtime/daemon-lock.js +3 -3
- package/dist/runtime/desk-runtime.d.ts +40 -7
- package/dist/runtime/desk-runtime.js +330 -44
- package/dist/runtime/durable-dispatch.d.ts +14 -2
- package/dist/runtime/durable-dispatch.js +207 -65
- package/dist/runtime/ingress-busy.js +17 -8
- package/dist/runtime/ingress-commands.js +24 -4
- package/dist/runtime/ingress-deps.d.ts +4 -1
- package/dist/runtime/ingress.js +6 -1
- package/dist/runtime/request-execution.js +7 -6
- package/dist/runtime/shutdown.d.ts +4 -1
- package/dist/runtime/shutdown.js +88 -35
- package/dist/runtime/task-close.d.ts +1 -1
- package/dist/runtime/task-close.js +6 -3
- package/dist/runtime/task-control.d.ts +2 -3
- package/dist/runtime/task-control.js +38 -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 +2 -0
- package/dist/runtime/task-lane.js +38 -20
- package/dist/runtime/task-step.d.ts +3 -3
- package/dist/runtime/task-step.js +34 -16
- package/dist/runtime/transports.js +6 -5
- package/dist/runtime/turn-run.js +103 -66
- package/dist/security/command-guard.d.ts +1 -1
- package/dist/security/command-guard.js +259 -314
- package/dist/security/path-guard.js +48 -7
- package/dist/security/shell-parse.d.ts +10 -0
- package/dist/security/shell-parse.js +224 -0
- package/dist/security/types.d.ts +2 -0
- package/dist/subagents/commands.d.ts +1 -1
- package/dist/subagents/commands.js +14 -5
- package/dist/subagents/completion-wake.js +6 -0
- package/dist/subagents/detached-discovery.d.ts +1 -1
- package/dist/subagents/discovery.d.ts +18 -199
- package/dist/subagents/discovery.js +35 -289
- package/dist/subagents/dispatch.d.ts +1 -2
- package/dist/subagents/dispatch.js +50 -29
- package/dist/subagents/external/antigravity-cli.d.ts +2 -0
- package/dist/subagents/external/antigravity-cli.js +517 -0
- package/dist/subagents/external/claude-code.js +8 -17
- package/dist/subagents/external/codex-cli.js +8 -18
- package/dist/subagents/external/cursor-cli.js +34 -31
- package/dist/subagents/external/dispatch.d.ts +21 -7
- package/dist/subagents/external/dispatch.js +146 -12
- package/dist/subagents/external/exec.js +3 -0
- package/dist/subagents/external/harness.d.ts +57 -33
- package/dist/subagents/external/harness.js +69 -40
- package/dist/subagents/external/reconciliation.js +1 -0
- package/dist/subagents/external/registry.js +4 -1
- package/dist/subagents/external/role-warnings.d.ts +4 -13
- package/dist/subagents/external/role-warnings.js +4 -28
- package/dist/subagents/external/run.d.ts +1 -2
- package/dist/subagents/external/run.js +16 -26
- package/dist/subagents/external/settlement.d.ts +2 -0
- package/dist/subagents/external/settlement.js +13 -3
- package/dist/subagents/format.d.ts +1 -1
- package/dist/subagents/format.js +1 -1
- package/dist/subagents/internal/outcome.d.ts +1 -2
- package/dist/subagents/internal/outcome.js +19 -12
- package/dist/subagents/internal/provider-retry.d.ts +1 -2
- package/dist/subagents/internal/provider-retry.js +2 -4
- package/dist/subagents/internal/run.d.ts +2 -3
- package/dist/subagents/internal/run.js +27 -4
- package/dist/subagents/internal/state.d.ts +2 -5
- package/dist/subagents/internal/state.js +1 -2
- package/dist/subagents/internal/worker.d.ts +1 -2
- package/dist/subagents/internal/worker.js +20 -10
- package/dist/subagents/resolve.d.ts +56 -0
- package/dist/subagents/resolve.js +202 -0
- package/dist/subagents/result.d.ts +6 -4
- package/dist/subagents/result.js +39 -6
- package/dist/subagents/run-record.d.ts +54 -2
- package/dist/subagents/run-record.js +7 -0
- package/dist/subagents/runs.d.ts +6 -31
- package/dist/subagents/runs.js +26 -31
- package/dist/subagents/task-envelope.d.ts +1 -2
- package/dist/subagents/task-envelope.js +13 -4
- package/dist/subagents/task-settlement.js +1 -0
- package/dist/subagents/types.d.ts +105 -6
- package/dist/subagents/types.js +16 -1
- package/dist/subagents/workspace-lease.d.ts +41 -24
- package/dist/subagents/workspace-lease.js +159 -24
- package/dist/subagents/worktree.d.ts +52 -0
- package/dist/subagents/worktree.js +363 -0
- package/dist/tasks/archive.js +4 -0
- package/dist/tasks/brief.d.ts +5 -1
- package/dist/tasks/brief.js +19 -5
- package/dist/tasks/commands.d.ts +6 -1
- package/dist/tasks/commands.js +32 -7
- package/dist/tasks/control.d.ts +11 -0
- package/dist/tasks/delivery.d.ts +2 -0
- package/dist/tasks/delivery.js +141 -21
- package/dist/tasks/loop-log.d.ts +12 -0
- package/dist/tasks/loop-log.js +10 -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 +29 -15
- package/dist/tools/contract/presentation.js +7 -5
- 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 +2 -1
- package/dist/tools/event-manage.js +46 -39
- 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 +6 -2
- package/dist/tools/index.js +9 -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 +32 -12
- package/dist/tools/send-media.js +9 -5
- package/dist/tools/session-search.d.ts +2 -1
- package/dist/tools/session-search.js +15 -5
- package/dist/tools/skill.js +13 -12
- package/dist/tools/subagent-manage.d.ts +1 -1
- package/dist/tools/subagent-manage.js +25 -152
- package/dist/tools/subagent.d.ts +24 -2
- package/dist/tools/subagent.js +24 -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 +40 -4
- package/dist/tools/task-manage/lifecycle.d.ts +3 -3
- package/dist/tools/task-manage/lifecycle.js +56 -13
- package/dist/tools/task-manage/schema.d.ts +4 -1
- package/dist/tools/task-manage/schema.js +4 -1
- package/dist/tools/task-manage/shared.d.ts +1 -1
- package/dist/tools/task-manage/types.d.ts +5 -1
- 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 +6 -6
- package/dist/tui/cli.js +120 -28
- package/dist/tui/client.d.ts +7 -0
- package/dist/tui/client.js +67 -16
- 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/usage/ledger.d.ts +1 -1
- package/dist/usage/render.js +1 -1
- 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 +43 -75
- 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 +11 -12
- 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/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/examples/sub-agents/agents/scout.md +0 -30
- package/examples/sub-agents/roles/builder-hard.md +0 -34
- package/examples/sub-agents/roles/builder.md +0 -34
- package/examples/sub-agents/roles/explorer.md +0 -39
- package/examples/sub-agents/roles/git-committer.md +0 -43
- package/examples/sub-agents/roles/planner.md +0 -33
- package/examples/sub-agents/roles/reviewer.md +0 -33
- package/examples/sub-agents/roles/verifier.md +0 -35
- package/examples/sub-agents/roles/worker.md +0 -34
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.");
|
|
@@ -209,6 +219,7 @@ export function createBashTool(executor, options = {}) {
|
|
|
209
219
|
const jobLabel = clipText(effectiveCommand, 60, { collapseWhitespace: true });
|
|
210
220
|
const job = await options.jobManager.start(effectiveCommand, jobLabel, effectiveTimeout, {
|
|
211
221
|
channelId: options.channelId,
|
|
222
|
+
...(options.securityContext?.cwd ? { cwd: options.securityContext.cwd } : {}),
|
|
212
223
|
signal,
|
|
213
224
|
notify: willNotify,
|
|
214
225
|
...(effectiveTaskId ? { taskId: effectiveTaskId } : {}),
|
|
@@ -239,6 +250,7 @@ export function createBashTool(executor, options = {}) {
|
|
|
239
250
|
// output" for a command whose real output exceeds that cap. It is deleted below when it
|
|
240
251
|
// turns out not to be needed.
|
|
241
252
|
const buildOutputText = async (stdout, stderr, spillPath, captureTruncated) => {
|
|
253
|
+
const fullOutputHint = formatFullOutputHint(spillPath);
|
|
242
254
|
let output = "";
|
|
243
255
|
if (stdout)
|
|
244
256
|
output += stdout;
|
|
@@ -253,38 +265,39 @@ export function createBashTool(executor, options = {}) {
|
|
|
253
265
|
// spill file — the one uncapped copy — and never quote a total line count we never saw.
|
|
254
266
|
if (captureTruncated) {
|
|
255
267
|
let tailSource = output;
|
|
268
|
+
let hasFullTail = false;
|
|
256
269
|
try {
|
|
257
270
|
tailSource = await readFileTail(spillPath, TAIL_FROM_SPILL_BYTES);
|
|
271
|
+
hasFullTail = true;
|
|
258
272
|
}
|
|
259
273
|
catch {
|
|
260
274
|
// Spill unreadable: fall back to the capped head's tail; still bounded.
|
|
261
275
|
}
|
|
262
|
-
const tailTrunc = truncateTail(tailSource);
|
|
276
|
+
const tailTrunc = truncateTail(tailSource, outputLimits);
|
|
263
277
|
const shownBytes = Buffer.byteLength(tailTrunc.content, "utf-8");
|
|
264
278
|
const text = `${tailTrunc.content || "(no output)"}\n\n` +
|
|
265
|
-
`[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}]`;
|
|
266
280
|
return {
|
|
267
281
|
text,
|
|
268
282
|
details: { truncation: tailTrunc, fullOutputPath: spillPath, producedOutput: true },
|
|
269
283
|
};
|
|
270
284
|
}
|
|
271
|
-
const truncation = truncateTail(output);
|
|
285
|
+
const truncation = truncateTail(output, outputLimits);
|
|
272
286
|
let text = truncation.content || "(no output)";
|
|
273
287
|
let details;
|
|
274
288
|
if (truncation.truncated) {
|
|
275
289
|
details = { truncation, fullOutputPath: spillPath };
|
|
276
290
|
const startLine = truncation.totalLines - truncation.outputLines + 1;
|
|
277
291
|
const endLine = truncation.totalLines;
|
|
278
|
-
const fullOutputHint = ` Full output: ${spillPath}`;
|
|
279
292
|
if (truncation.lastLinePartial) {
|
|
280
293
|
const lastLineSize = formatSize(Buffer.byteLength(output.split("\n").pop() || "", "utf-8"));
|
|
281
|
-
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}]`;
|
|
282
295
|
}
|
|
283
296
|
else if (truncation.truncatedBy === "lines") {
|
|
284
|
-
text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}
|
|
297
|
+
text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. ${fullOutputHint}]`;
|
|
285
298
|
}
|
|
286
299
|
else {
|
|
287
|
-
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}]`;
|
|
288
301
|
}
|
|
289
302
|
}
|
|
290
303
|
else {
|
|
@@ -301,6 +314,7 @@ export function createBashTool(executor, options = {}) {
|
|
|
301
314
|
}
|
|
302
315
|
try {
|
|
303
316
|
const result = await executor.exec(effectiveCommand, {
|
|
317
|
+
...(options.securityContext?.cwd ? { cwd: options.securityContext.cwd } : {}),
|
|
304
318
|
timeout: effectiveTimeout,
|
|
305
319
|
signal,
|
|
306
320
|
spillTo: spillPath,
|
|
@@ -325,7 +339,7 @@ export function createBashTool(executor, options = {}) {
|
|
|
325
339
|
}
|
|
326
340
|
const built = await buildOutputText(error.stdout, error.stderr, spillPath, error.captureTruncated);
|
|
327
341
|
const nextStep = error.reason === "timeout"
|
|
328
|
-
? `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"}.`
|
|
329
343
|
: "The command was stopped (e.g. by /stop or a run cancellation); partial output above.";
|
|
330
344
|
const outputText = `${built.text}\n\n[${error.message}; partial output above. ${nextStep}]`;
|
|
331
345
|
const details = { ...built.details, timedOut: true };
|
|
@@ -10,9 +10,8 @@ import { isRecord } from "../../shared/type-guards.js";
|
|
|
10
10
|
* One function per tool name, keyed in a table rather than spread across each tool's own file:
|
|
11
11
|
* `session-events.ts` has only `toolName` + raw `args`, never the tool instance, so there is no
|
|
12
12
|
* natural per-file seam to hang this on without importing all sixteen modules into the session
|
|
13
|
-
* event handler.
|
|
14
|
-
*
|
|
15
|
-
* model's args are not guaranteed well-formed at the moment a call starts.
|
|
13
|
+
* event handler. Each entry survives empty/missing args, since the model's args are not guaranteed
|
|
14
|
+
* well-formed at the moment a call starts.
|
|
16
15
|
*/
|
|
17
16
|
function str(args, key) {
|
|
18
17
|
if (!isRecord(args))
|
|
@@ -53,7 +52,10 @@ const DESCRIBERS = {
|
|
|
53
52
|
const path = str(args, "path");
|
|
54
53
|
return `搜索 "${clipText(pattern, 40, { collapseWhitespace: true })}"${path ? ` · ${path}` : ""}`;
|
|
55
54
|
},
|
|
56
|
-
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
|
+
},
|
|
57
59
|
write: (args) => `写入 ${str(args, "path") ?? "?"}`,
|
|
58
60
|
bash: (args) => {
|
|
59
61
|
const command = clipText(str(args, "command") ?? "?", 60, { collapseWhitespace: true });
|
|
@@ -70,7 +72,7 @@ const DESCRIBERS = {
|
|
|
70
72
|
session_search: (args) => `检索历史 "${clipText(str(args, "query") ?? "?", 40, { collapseWhitespace: true })}"`,
|
|
71
73
|
memory_save: (args) => `记忆保存${str(args, "content") ? `:${firstLine(str(args, "content") ?? "", 30)}` : ""}`,
|
|
72
74
|
memory_search: (args) => `记忆检索 "${clipText(str(args, "query") ?? "?", 40, { collapseWhitespace: true })}"`,
|
|
73
|
-
memory_forget: (args) => `记忆删除 "${clipText(str(args, "
|
|
75
|
+
memory_forget: (args) => `记忆删除 "${clipText(str(args, "name") ?? "?", 40, { collapseWhitespace: true })}"`,
|
|
74
76
|
skill: (args) => {
|
|
75
77
|
const action = str(args, "action") ?? "?";
|
|
76
78
|
const name = str(args, "name");
|
|
@@ -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
|
+
}
|
package/dist/tools/edit.d.ts
CHANGED
|
@@ -2,17 +2,25 @@ import type { AgentTool } from "@earendil-works/pi-agent-core";
|
|
|
2
2
|
import { Type } from "typebox";
|
|
3
3
|
import { type FileStore } from "../file-store.js";
|
|
4
4
|
import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
|
|
5
|
+
import { type FileObservations } from "./file-observations.js";
|
|
5
6
|
declare const editSchema: Type.TObject<{
|
|
6
7
|
path: Type.TString;
|
|
7
|
-
oldText: Type.TString
|
|
8
|
-
newText: Type.TString
|
|
8
|
+
oldText: Type.TOptional<Type.TString>;
|
|
9
|
+
newText: Type.TOptional<Type.TString>;
|
|
9
10
|
replaceAll: Type.TOptional<Type.TBoolean>;
|
|
11
|
+
edits: Type.TOptional<Type.TArray<Type.TObject<{
|
|
12
|
+
oldText: Type.TString;
|
|
13
|
+
newText: Type.TString;
|
|
14
|
+
replaceAll: Type.TOptional<Type.TBoolean>;
|
|
15
|
+
}>>>;
|
|
10
16
|
}>;
|
|
11
17
|
export interface EditToolOptions {
|
|
12
18
|
deskDir?: string;
|
|
13
19
|
securityConfig?: SecurityConfig;
|
|
14
20
|
securityContext?: SecurityRuntimeContext;
|
|
15
21
|
channelId?: string;
|
|
22
|
+
leaseOwnerRunId?: string;
|
|
23
|
+
observations?: FileObservations;
|
|
16
24
|
}
|
|
17
25
|
export declare function createEditTool(fileStore: FileStore, options?: EditToolOptions): AgentTool<typeof editSchema>;
|
|
18
26
|
export {};
|