@oyasmi/pipiclaw 0.9.3-beta.2 → 0.9.3-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/channel-runner.d.ts +4 -18
- package/dist/agent/channel-runner.js +25 -120
- package/dist/agent/context-budget.js +1 -1
- package/dist/agent/job-manager.d.ts +20 -17
- package/dist/agent/job-manager.js +95 -70
- package/dist/agent/prompt/builder.d.ts +1 -1
- package/dist/agent/prompt/builder.js +2 -18
- package/dist/agent/prompt/manifest.d.ts +0 -1
- package/dist/agent/prompt/manifest.js +2 -2
- package/dist/agent/prompt/sections.js +3 -12
- package/dist/agent/prompt/types.d.ts +2 -18
- package/dist/agent/prompt/types.js +1 -1
- package/dist/agent/runner-factory.d.ts +4 -0
- package/dist/agent/session-adapter.d.ts +19 -0
- package/dist/agent/session-adapter.js +77 -0
- package/dist/app-services.d.ts +18 -0
- package/dist/app-services.js +43 -0
- package/dist/{runtime → events}/events.d.ts +1 -1
- package/dist/executor.d.ts +5 -1
- package/dist/executor.js +35 -5
- package/dist/file-store.d.ts +4 -1
- package/dist/file-store.js +5 -0
- package/dist/memory/journal.d.ts +13 -0
- package/dist/memory/journal.js +47 -4
- package/dist/memory/maintenance-gates.d.ts +0 -3
- package/dist/memory/maintenance-gates.js +2 -2
- package/dist/memory/maintenance-migration.d.ts +5 -0
- package/dist/memory/maintenance-migration.js +91 -0
- package/dist/memory/maintenance-state.js +5 -44
- package/dist/memory/migrate.js +1 -1
- package/dist/memory/reflect-job.d.ts +1 -9
- package/dist/memory/reflect-job.js +1 -3
- package/dist/memory/reflect.js +1 -1
- package/dist/memory/search.js +13 -6
- package/dist/memory/session-corpus.d.ts +11 -0
- package/dist/memory/session-corpus.js +16 -5
- package/dist/memory/session-search.d.ts +3 -0
- package/dist/memory/session-search.js +45 -8
- package/dist/memory/store.d.ts +9 -0
- package/dist/memory/store.js +26 -3
- package/dist/models/auth-cli.js +1 -1
- package/dist/playbooks/agent-delegation.md +35 -76
- package/dist/playbooks/background-jobs.md +14 -16
- package/dist/playbooks/event-scheduling.md +20 -25
- package/dist/playbooks/memory-and-learning.md +28 -61
- package/dist/playbooks/outbound-media.md +10 -12
- package/dist/playbooks/runtime-orientation.md +34 -53
- package/dist/playbooks/task-loop.md +49 -69
- package/dist/runtime/bootstrap.d.ts +5 -15
- package/dist/runtime/bootstrap.js +57 -67
- package/dist/runtime/subagent-commands.d.ts +2 -1
- package/dist/runtime/subagent-commands.js +10 -12
- package/dist/runtime/task-wake.d.ts +4 -5
- package/dist/runtime/task-wake.js +2 -12
- package/dist/security/path-guard-filter.d.ts +22 -0
- package/dist/security/path-guard-filter.js +35 -0
- package/dist/security/types.d.ts +7 -0
- package/dist/security/types.js +16 -1
- package/dist/settings.d.ts +8 -0
- package/dist/settings.js +24 -1
- package/dist/shared/exact-keys.d.ts +13 -0
- package/dist/shared/exact-keys.js +1 -0
- package/dist/shared/format.d.ts +20 -0
- package/dist/shared/format.js +64 -0
- package/dist/shared/{fs-utils.d.ts → os.d.ts} +6 -0
- package/dist/shared/{fs-utils.js → os.js} +8 -0
- package/dist/subagents/discovery.d.ts +18 -6
- package/dist/subagents/discovery.js +12 -8
- package/dist/subagents/external/run.d.ts +2 -1
- package/dist/subagents/external/run.js +1 -2
- package/dist/subagents/external/settlement.js +10 -5
- package/dist/subagents/format.d.ts +1 -1
- package/dist/subagents/format.js +1 -1
- package/dist/subagents/runs.d.ts +13 -12
- package/dist/subagents/runs.js +108 -89
- package/dist/subagents/tool.d.ts +13 -7
- package/dist/subagents/tool.js +21 -13
- package/dist/tasks/brief.d.ts +1 -1
- package/dist/tasks/brief.js +12 -2
- package/dist/tasks/log.d.ts +4 -0
- package/dist/tasks/log.js +13 -1
- package/dist/tools/bash.d.ts +13 -0
- package/dist/tools/bash.js +123 -20
- package/dist/tools/command-optimizer.js +1 -1
- package/dist/tools/config.d.ts +7 -0
- package/dist/tools/config.js +16 -1
- package/dist/tools/edit.js +36 -5
- package/dist/tools/event-manage.d.ts +26 -5
- package/dist/tools/event-manage.js +84 -36
- package/dist/tools/glob.js +57 -4
- package/dist/tools/grep.d.ts +2 -0
- package/dist/tools/grep.js +188 -15
- package/dist/tools/index.d.ts +4 -0
- package/dist/tools/index.js +4 -2
- package/dist/tools/job.js +17 -5
- package/dist/tools/memory-manage.js +80 -41
- package/dist/tools/read.js +43 -6
- package/dist/tools/registry.d.ts +9 -3
- package/dist/tools/registry.js +22 -57
- package/dist/tools/send-media.js +6 -4
- package/dist/tools/session-search.js +4 -1
- package/dist/tools/skill.d.ts +2 -0
- package/dist/tools/skill.js +13 -1
- package/dist/tools/subagent-manage.d.ts +2 -0
- package/dist/tools/subagent-manage.js +8 -8
- package/dist/tools/subagent-tool-names.d.ts +11 -0
- package/dist/tools/subagent-tool-names.js +19 -0
- package/dist/tools/task-manage/log-view.js +6 -3
- package/dist/tools/task-manage/schema.d.ts +6 -6
- package/dist/tools/task-manage/schema.js +5 -12
- package/dist/tools/task-manage/shared.js +20 -11
- package/dist/tools/task-manage/step-end.js +22 -5
- package/dist/tools/task-manage/types.d.ts +4 -0
- package/dist/tools/task-manage.js +9 -1
- package/dist/tools/web-cache.d.ts +11 -3
- package/dist/tools/web-cache.js +26 -8
- package/dist/tools/web-fetch.d.ts +1 -0
- package/dist/tools/web-fetch.js +68 -15
- package/dist/tools/write.js +3 -0
- package/dist/tui/app.js +22 -7
- package/dist/web/config.js +1 -1
- package/dist/web/fetch.d.ts +5 -0
- package/dist/web/fetch.js +36 -1
- package/examples/sub-agents/README.md +14 -4
- package/examples/sub-agents/builder-hard.md +12 -34
- package/examples/sub-agents/builder.md +11 -31
- package/examples/sub-agents/explorer.md +10 -16
- package/examples/sub-agents/git-committer.md +15 -20
- package/examples/sub-agents/planner.md +11 -21
- package/examples/sub-agents/reviewer.md +10 -31
- package/examples/sub-agents/verifier.md +12 -27
- package/examples/sub-agents/worker.md +11 -35
- package/package.json +8 -3
- package/dist/shared/duration.d.ts +0 -2
- package/dist/shared/duration.js +0 -7
- package/dist/shared/file-stamp.d.ts +0 -10
- package/dist/shared/file-stamp.js +0 -19
- package/dist/shared/numeric.d.ts +0 -7
- package/dist/shared/numeric.js +0 -19
- package/dist/shared/shell-escape.d.ts +0 -5
- package/dist/shared/shell-escape.js +0 -7
- package/dist/shared/token-estimate.d.ts +0 -1
- package/dist/shared/token-estimate.js +0 -19
- /package/dist/{runtime → events}/event-commands.d.ts +0 -0
- /package/dist/{runtime → events}/event-commands.js +0 -0
- /package/dist/{runtime → events}/event-validation.d.ts +0 -0
- /package/dist/{runtime → events}/event-validation.js +0 -0
- /package/dist/{runtime → events}/events.js +0 -0
package/dist/subagents/tool.js
CHANGED
|
@@ -26,7 +26,7 @@ import { describeToolCall } from "../tools/presentation.js";
|
|
|
26
26
|
import { buildToolSet } from "../tools/registry.js";
|
|
27
27
|
import { DEFAULT_THINKING_LEVEL, externalRoleFingerprint, formatSubAgentList, resolveConfiguredRole, resolveInlineAgent, validateSubAgentTask, withSubAgentsDirWriteDeny, } from "./discovery.js";
|
|
28
28
|
import { launchExternalRun } from "./external/run.js";
|
|
29
|
-
import {
|
|
29
|
+
import { resolveSyncGraceMs } from "./runs.js";
|
|
30
30
|
import { resolveVerificationOutcome } from "./verification-outcome.js";
|
|
31
31
|
import { acquireWorkspaceLease, findWorkspaceLeaseHolder, formatWorkspaceLeaseConflict, releaseWorkspaceLease, } from "./workspace-lease.js";
|
|
32
32
|
/** Shared by both invocation surfaces (spec 046, D2.1). */
|
|
@@ -91,6 +91,12 @@ const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
|
|
|
91
91
|
* only caps what gets echoed into the parent's context.
|
|
92
92
|
*/
|
|
93
93
|
export const MAX_SUBAGENT_RESULT_UNITS = 1_200;
|
|
94
|
+
/**
|
|
95
|
+
* Character ceiling paired with the unit ceiling. `prompt-units.ts` notes that a long
|
|
96
|
+
* separator-free run of letters/digits counts as a single unit, so a units-only budget can still
|
|
97
|
+
* pass through an unbounded blob — every budget must bound units *and* chars (fix plan §2.4).
|
|
98
|
+
*/
|
|
99
|
+
export const MAX_SUBAGENT_RESULT_CHARS = 12_000;
|
|
94
100
|
const RESULT_TRUNCATION_HEAD_RATIO = 1;
|
|
95
101
|
/**
|
|
96
102
|
* Spec 032 D6: when a turn/tool/wall-time budget is hit, the sub-agent gets one more,
|
|
@@ -224,7 +230,8 @@ function formatStatus(agentName, text) {
|
|
|
224
230
|
function buildDispatchedText(runId, agentName, runtimeLabel, workingDirectory) {
|
|
225
231
|
return (`[Dispatched] runId=${runId}, agent ${agentName} (${runtimeLabel}), working directory ${workingDirectory}.\n` +
|
|
226
232
|
"Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
|
|
227
|
-
"
|
|
233
|
+
"Finish independent work and dispatches, then end the turn when only waiting remains; do not re-dispatch or poll to wait. " +
|
|
234
|
+
"Inside a task step, use task_step_end outcome=park with this run id.");
|
|
228
235
|
}
|
|
229
236
|
/**
|
|
230
237
|
* `buildContextualBlocks` shared by the external dispatch path and `runToCompletion`'s internal
|
|
@@ -268,11 +275,12 @@ function buildStoppedText(config, reason, finalText) {
|
|
|
268
275
|
*/
|
|
269
276
|
function finalizeSubAgentOutput(runContext, finalText) {
|
|
270
277
|
const outputPath = join(runContext.artifactDir, "output.md");
|
|
271
|
-
if (countPromptUnits(finalText) <= MAX_SUBAGENT_RESULT_UNITS) {
|
|
278
|
+
if (countPromptUnits(finalText) <= MAX_SUBAGENT_RESULT_UNITS && finalText.length <= MAX_SUBAGENT_RESULT_CHARS) {
|
|
272
279
|
return { replyText: finalText, truncated: false };
|
|
273
280
|
}
|
|
274
281
|
const clipped = clipTextByPromptUnits(finalText, MAX_SUBAGENT_RESULT_UNITS, {
|
|
275
282
|
headRatio: RESULT_TRUNCATION_HEAD_RATIO,
|
|
283
|
+
maxChars: MAX_SUBAGENT_RESULT_CHARS,
|
|
276
284
|
marker: `\n\n[... truncated; full output saved at ${outputPath} ...]\n\n`,
|
|
277
285
|
});
|
|
278
286
|
return { replyText: clipped.text, truncated: true };
|
|
@@ -304,8 +312,8 @@ function withSubagentMemoryWriteDeny(securityConfig, channelDir, workspaceDir) {
|
|
|
304
312
|
}, workspaceDir);
|
|
305
313
|
}
|
|
306
314
|
/**
|
|
307
|
-
* Build a sub-agent's tool set from the shared tool registry, filtered
|
|
308
|
-
*
|
|
315
|
+
* Build a sub-agent's tool set from the shared tool registry, filtered by the shared
|
|
316
|
+
* sub-agent whitelist (files + web). Sub-agents run with their own security context
|
|
309
317
|
* (rooted at the sub-agent workspace) and their own per-invocation bash timeout.
|
|
310
318
|
*/
|
|
311
319
|
function buildSubagentTools(executor, bashTimeoutSec, options, runContext) {
|
|
@@ -444,7 +452,10 @@ function createDetails(input) {
|
|
|
444
452
|
return {
|
|
445
453
|
agent: input.config.name,
|
|
446
454
|
source: input.config.source,
|
|
447
|
-
model: input.modelOverride ??
|
|
455
|
+
model: input.modelOverride ??
|
|
456
|
+
(input.config.runtime === "external"
|
|
457
|
+
? (input.config.externalModelRef ?? "default")
|
|
458
|
+
: formatModelReference(input.config.model)),
|
|
448
459
|
tools: input.toolsOverride ?? [...input.config.tools],
|
|
449
460
|
turns: input.turns,
|
|
450
461
|
toolCalls: input.toolCalls,
|
|
@@ -484,7 +495,7 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
|
|
|
484
495
|
// Only ever set for an inline (internal) delegation with `bash` in `tools` and no explicit
|
|
485
496
|
// `mutates` — surfaced to the model, not just a log, since it has no role file to fix.
|
|
486
497
|
const mutatesNote = warning ? `Note: ${warning}\n\n` : "";
|
|
487
|
-
const runManager =
|
|
498
|
+
const runManager = options.getRunManager(options.runtimeContext.channelId);
|
|
488
499
|
// A short, human-typeable id (spec 041) — never the dispatching tool call's own id, which
|
|
489
500
|
// on some providers is a long `call_<id>|fc_<id>` composite unreadable in a chat UI.
|
|
490
501
|
const runContext = await prepareRunContext(runManager.mintRunId(), params, options);
|
|
@@ -508,7 +519,7 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
|
|
|
508
519
|
leaseKey = lease.leaseKey;
|
|
509
520
|
}
|
|
510
521
|
if (config.runtime === "external") {
|
|
511
|
-
return dispatchExternalRun({ options, currentModel, config, runLabel, runContext, leaseKey, params });
|
|
522
|
+
return dispatchExternalRun({ options, currentModel, config, runLabel, runContext, leaseKey, params, runManager });
|
|
512
523
|
}
|
|
513
524
|
return dispatchInternalRun({
|
|
514
525
|
options,
|
|
@@ -530,10 +541,6 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
|
|
|
530
541
|
*/
|
|
531
542
|
async function dispatchExternalRun(input) {
|
|
532
543
|
const { options, config, runLabel, runContext, leaseKey, params } = input;
|
|
533
|
-
if (!config.harness) {
|
|
534
|
-
releaseWorkspaceLease(leaseKey, runContext.runId);
|
|
535
|
-
throw new Error(`Sub-agent "${config.name}" has runtime: external but no harness configured.`);
|
|
536
|
-
}
|
|
537
544
|
let launchResult;
|
|
538
545
|
try {
|
|
539
546
|
// D9/T5: external roles get the same task envelope internal workers do — runtime
|
|
@@ -542,6 +549,7 @@ async function dispatchExternalRun(input) {
|
|
|
542
549
|
const contextualBlocks = await resolveContextualBlocks(config, options);
|
|
543
550
|
const envelopedTask = buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext);
|
|
544
551
|
launchResult = await launchExternalRun({
|
|
552
|
+
runManager: input.runManager,
|
|
545
553
|
runId: runContext.runId,
|
|
546
554
|
channelId: options.runtimeContext.channelId,
|
|
547
555
|
channelDir: options.channelDir,
|
|
@@ -549,7 +557,7 @@ async function dispatchExternalRun(input) {
|
|
|
549
557
|
agent: config.name,
|
|
550
558
|
source: config.source,
|
|
551
559
|
harness: config.harness,
|
|
552
|
-
command: config.command
|
|
560
|
+
command: config.command,
|
|
553
561
|
shell: config.shell,
|
|
554
562
|
env: config.env,
|
|
555
563
|
externalModelRef: config.externalModelRef,
|
package/dist/tasks/brief.d.ts
CHANGED
|
@@ -9,7 +9,7 @@ export interface TaskBriefInput {
|
|
|
9
9
|
/**
|
|
10
10
|
* The turn input for one task loop step (spec 051, D3).
|
|
11
11
|
*
|
|
12
|
-
* The contract is injected whole
|
|
12
|
+
* The authored contract is injected whole; authors must keep it short. The history
|
|
13
13
|
* is the last few log lines rather than the 24 KB of closed cycles v3 pasted into every wake. Any
|
|
14
14
|
* pending `/tasks steer` or `/tasks reply` is consumed here and put first — it is the one thing in
|
|
15
15
|
* the brief that is genuinely new since the previous step.
|
package/dist/tasks/brief.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { PLAYBOOKS_DIR } from "../paths.js";
|
|
1
3
|
import { effectiveBudget } from "./budget.js";
|
|
2
4
|
import { readTaskLog, renderTaskLogLine } from "./log.js";
|
|
3
5
|
import { consumeTaskSteer } from "./steer.js";
|
|
@@ -8,7 +10,7 @@ export const BRIEF_LOG_LINES = 8;
|
|
|
8
10
|
/**
|
|
9
11
|
* The turn input for one task loop step (spec 051, D3).
|
|
10
12
|
*
|
|
11
|
-
* The contract is injected whole
|
|
13
|
+
* The authored contract is injected whole; authors must keep it short. The history
|
|
12
14
|
* is the last few log lines rather than the 24 KB of closed cycles v3 pasted into every wake. Any
|
|
13
15
|
* pending `/tasks steer` or `/tasks reply` is consumed here and put first — it is the one thing in
|
|
14
16
|
* the brief that is genuinely new since the previous step.
|
|
@@ -25,8 +27,15 @@ export async function buildTaskStepBrief(input) {
|
|
|
25
27
|
const blocks = [`[TASK_STEP:${input.taskId}]`];
|
|
26
28
|
if (input.reason)
|
|
27
29
|
blocks.push(input.reason);
|
|
30
|
+
// Reuse durable history instead of a new pending-wake flag. An expiry remains relevant until
|
|
31
|
+
// a later step records what recovery did; a verifier round in between does not consume it.
|
|
32
|
+
const lastTransition = [...log].reverse().find((record) => record.kind === "expired" || record.kind === "step");
|
|
33
|
+
if (lastTransition?.kind === "expired") {
|
|
34
|
+
blocks.push(`<task_recovery kind="expired">\n等待票过期:${lastTransition.ticket}。先核对来源的真实状态,再决定继续、换票或请求用户决定。\n</task_recovery>`);
|
|
35
|
+
}
|
|
28
36
|
if (steer)
|
|
29
37
|
blocks.push(`<user_guidance>\n${steer}\n</user_guidance>`);
|
|
38
|
+
blocks.push(`契约文件:${document.path}\n首次执行前读取 ${join(PLAYBOOKS_DIR, "task-loop.md")};已在当前上下文中完整读过则复用。`);
|
|
30
39
|
blocks.push(`<task_contract id="${input.taskId}">\n${document.body.trim()}\n</task_contract>`);
|
|
31
40
|
if (log.length > 0) {
|
|
32
41
|
blocks.push(`<task_log recent="${log.length}">\n${log.map(renderTaskLogLine).join("\n")}\n</task_log>`);
|
|
@@ -34,7 +43,8 @@ export async function buildTaskStepBrief(input) {
|
|
|
34
43
|
blocks.push(`<task_state>\n${renderState(document.fields)}\n</task_state>`);
|
|
35
44
|
blocks.push("推进这个任务的下一个具体步骤,然后必须调用 task_step_end 收尾:" +
|
|
36
45
|
"continue(还能继续)/ park(等一个真实来源)/ done(本周期完成)/ blocked(需要用户决定)。" +
|
|
37
|
-
|
|
46
|
+
`派发 run/job 时,首个调用就必须带 taskId=${input.taskId};达成 DoD 后先用 edit 勾选对应验收项,再调用 done。` +
|
|
47
|
+
"默认不向用户发言;契约要求交付、告知、汇报或回复时,必须把实际内容放进 notify,note 不会发送给用户。");
|
|
38
48
|
return blocks.join("\n\n");
|
|
39
49
|
}
|
|
40
50
|
function renderState(fields) {
|
package/dist/tasks/log.d.ts
CHANGED
|
@@ -56,6 +56,10 @@ export interface TaskCloseRecord {
|
|
|
56
56
|
}
|
|
57
57
|
export type TaskLogRecord = TaskStepRecord | TaskRoundRecord | TaskExpiredRecord | TaskCloseRecord;
|
|
58
58
|
export declare function taskLogPath(channelDir: string, id: string): string;
|
|
59
|
+
/** Where `archiveTask` moves a closed task's `.jsonl`. */
|
|
60
|
+
export declare function taskArchiveLogPath(channelDir: string, id: string): string;
|
|
61
|
+
/** True when the loop log for `id` lives only in the archive (the task is closed). */
|
|
62
|
+
export declare function taskLogIsArchived(channelDir: string, id: string): boolean;
|
|
59
63
|
/** Test seam: drop cached appenders so a temp-dir fixture does not leak into the next case. */
|
|
60
64
|
export declare function resetTaskLogAppenders(): Promise<void>;
|
|
61
65
|
export type TaskLogInput = (Omit<TaskStepRecord, "ts"> & {
|
package/dist/tasks/log.js
CHANGED
|
@@ -12,6 +12,14 @@ const NOTE_MAX_CHARS = 4_000;
|
|
|
12
12
|
export function taskLogPath(channelDir, id) {
|
|
13
13
|
return join(channelDir, "tasks", `${normalizeTaskId(id)}.jsonl`);
|
|
14
14
|
}
|
|
15
|
+
/** Where `archiveTask` moves a closed task's `.jsonl`. */
|
|
16
|
+
export function taskArchiveLogPath(channelDir, id) {
|
|
17
|
+
return join(channelDir, "tasks", "archive", `${normalizeTaskId(id)}.jsonl`);
|
|
18
|
+
}
|
|
19
|
+
/** True when the loop log for `id` lives only in the archive (the task is closed). */
|
|
20
|
+
export function taskLogIsArchived(channelDir, id) {
|
|
21
|
+
return !existsSync(taskLogPath(channelDir, id)) && existsSync(taskArchiveLogPath(channelDir, id));
|
|
22
|
+
}
|
|
15
23
|
const appenders = new Map();
|
|
16
24
|
function appenderFor(path) {
|
|
17
25
|
const existing = appenders.get(path);
|
|
@@ -50,7 +58,11 @@ function toRecord(value) {
|
|
|
50
58
|
* hand-edited or half-written line must not make a task's whole history unreadable.
|
|
51
59
|
*/
|
|
52
60
|
export async function readTaskLog(channelDir, id, options = {}) {
|
|
53
|
-
|
|
61
|
+
// Fall back to the archived copy so `task_log` on a completed task returns its history rather
|
|
62
|
+
// than "暂无日志" — a task that finished still has a loop log worth reading.
|
|
63
|
+
const path = existsSync(taskLogPath(channelDir, id))
|
|
64
|
+
? taskLogPath(channelDir, id)
|
|
65
|
+
: taskArchiveLogPath(channelDir, id);
|
|
54
66
|
if (!existsSync(path))
|
|
55
67
|
return [];
|
|
56
68
|
let content;
|
package/dist/tools/bash.d.ts
CHANGED
|
@@ -22,6 +22,12 @@ export interface BashToolOptions {
|
|
|
22
22
|
securityConfig?: SecurityConfig;
|
|
23
23
|
securityContext?: SecurityRuntimeContext;
|
|
24
24
|
channelId?: string;
|
|
25
|
+
/**
|
|
26
|
+
* The channel directory. When set, the "full output" spill file lives under
|
|
27
|
+
* `<channelDir>/logs/` so the pointer the tool hands back is one the model's `read` can open
|
|
28
|
+
* under both path-guard boundaries. Absent on the sub-agent path (spill falls back to tmpdir).
|
|
29
|
+
*/
|
|
30
|
+
channelDir?: string;
|
|
25
31
|
/**
|
|
26
32
|
* When true, route each command through the `rtk` command optimizer before executing
|
|
27
33
|
* (best-effort; falls back to the raw command when rtk is unavailable or declines).
|
|
@@ -33,6 +39,13 @@ export interface BashToolOptions {
|
|
|
33
39
|
* background execution. Absent on the sub-agent path, so sub-agents cannot background jobs.
|
|
34
40
|
*/
|
|
35
41
|
jobManager?: ChannelJobManager;
|
|
42
|
+
/**
|
|
43
|
+
* Set inside a task cycle's session. A background job started here belongs to this task, so the
|
|
44
|
+
* runtime binds the id rather than asking the model to repeat it (and rejects a conflicting one
|
|
45
|
+
* before the job launches — the old "relaunch with taskId=…" told the model to re-run a command
|
|
46
|
+
* that may have side effects). Chat sessions leave this unset and keep the optional `taskId`.
|
|
47
|
+
*/
|
|
48
|
+
boundTaskId?: string;
|
|
36
49
|
/**
|
|
37
50
|
* When true (`tools.bashInterceptor.enabled`), block a few bare shell patterns that have a
|
|
38
51
|
* better dedicated tool and steer the model to it. Off by default; main path only.
|
package/dist/tools/bash.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { randomBytes } from "node:crypto";
|
|
2
|
-
import { unlink } from "node:fs/promises";
|
|
2
|
+
import { mkdir, open, readdir, stat, unlink } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
3
5
|
import { Type } from "typebox";
|
|
4
|
-
import { CommandTerminatedError } from "../executor.js";
|
|
6
|
+
import { CommandTerminatedError, EXECUTOR_SHELL_IS_BASH } from "../executor.js";
|
|
5
7
|
import { formatBlockMessage } from "../security/block-message.js";
|
|
6
8
|
import { guardCommand } from "../security/command-guard.js";
|
|
7
9
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
@@ -17,14 +19,52 @@ import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail } from "
|
|
|
17
19
|
* Callers that legitimately need longer must pass an explicit `timeout`.
|
|
18
20
|
*/
|
|
19
21
|
export const DEFAULT_BASH_TIMEOUT_SECONDS = 300;
|
|
22
|
+
/** Subdirectory of the channel dir where full bash/job output spills live. */
|
|
23
|
+
const BASH_LOG_DIR_NAME = "logs";
|
|
24
|
+
/** Spill files kept per channel before the oldest are pruned on the next tool build. */
|
|
25
|
+
const BASH_LOG_RETENTION = 40;
|
|
26
|
+
/** Bytes read back from the spill file when the in-memory capture was truncated (D2.3). */
|
|
27
|
+
const TAIL_FROM_SPILL_BYTES = DEFAULT_MAX_BYTES * 4;
|
|
20
28
|
/**
|
|
21
|
-
*
|
|
22
|
-
* path
|
|
23
|
-
*
|
|
29
|
+
* Where the "full output" spill file for a command goes. Under `<channelDir>/logs/` on the main
|
|
30
|
+
* path, which the model's `read` can open under both `boundary: "project"` and `unbounded` — a
|
|
31
|
+
* `/tmp/...` pointer is unreadable under `boundary: "project"` (fix plan §2.2). Sub-agents get no
|
|
32
|
+
* channel dir, so they fall back to the OS temp dir as before.
|
|
24
33
|
*/
|
|
25
|
-
function getSpillFilePath() {
|
|
34
|
+
function getSpillFilePath(channelDir) {
|
|
26
35
|
const id = randomBytes(8).toString("hex");
|
|
27
|
-
|
|
36
|
+
const dir = channelDir ? join(channelDir, BASH_LOG_DIR_NAME) : tmpdir();
|
|
37
|
+
return join(dir, `pipiclaw-bash-${id}.log`);
|
|
38
|
+
}
|
|
39
|
+
/** Best-effort: keep the channel's `logs/` dir from growing without bound. */
|
|
40
|
+
async function pruneBashLogs(channelDir) {
|
|
41
|
+
const dir = join(channelDir, BASH_LOG_DIR_NAME);
|
|
42
|
+
let names;
|
|
43
|
+
try {
|
|
44
|
+
names = (await readdir(dir)).filter((n) => n.startsWith("pipiclaw-bash-") && n.endsWith(".log"));
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
if (names.length <= BASH_LOG_RETENTION)
|
|
50
|
+
return;
|
|
51
|
+
const withMtime = await Promise.all(names.map(async (n) => ({ n, m: (await stat(join(dir, n)).catch(() => null))?.mtimeMs ?? 0 })));
|
|
52
|
+
withMtime.sort((a, b) => b.m - a.m);
|
|
53
|
+
await Promise.all(withMtime.slice(BASH_LOG_RETENTION).map(({ n }) => unlink(join(dir, n)).catch(() => undefined)));
|
|
54
|
+
}
|
|
55
|
+
/** Read the last `maxBytes` of a file as UTF-8 text (used when the in-memory capture is only a head). */
|
|
56
|
+
async function readFileTail(path, maxBytes) {
|
|
57
|
+
const size = (await stat(path)).size;
|
|
58
|
+
const start = Math.max(0, size - maxBytes);
|
|
59
|
+
const fh = await open(path, "r");
|
|
60
|
+
try {
|
|
61
|
+
const buf = Buffer.alloc(size - start);
|
|
62
|
+
await fh.read(buf, 0, buf.length, start);
|
|
63
|
+
return buf.toString("utf-8");
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
await fh.close();
|
|
67
|
+
}
|
|
28
68
|
}
|
|
29
69
|
const bashSchema = Type.Object({
|
|
30
70
|
command: Type.String({ description: "Bash command to execute" }),
|
|
@@ -42,6 +82,12 @@ const bashSchema = Type.Object({
|
|
|
42
82
|
description: "For async jobs: the task this job advances, so the completion wake lands in that context.",
|
|
43
83
|
})),
|
|
44
84
|
});
|
|
85
|
+
/** Schema shown when background execution is unavailable (sub-agent path): the async trio is
|
|
86
|
+
* dropped so the model is never offered a parameter its context cannot honor (fix plan §3.2). */
|
|
87
|
+
const bashSchemaNoJobs = Type.Omit(bashSchema, ["async", "notify", "taskId"]);
|
|
88
|
+
/** Schema shown inside a task session: `taskId` is bound by the runtime, so the model never
|
|
89
|
+
* supplies (or misfills) it (fix plan §3.3). */
|
|
90
|
+
const bashSchemaBoundTask = Type.Omit(bashSchema, ["taskId"]);
|
|
45
91
|
/**
|
|
46
92
|
* Bare shell patterns that a dedicated tool handles better (with truncation, grouping, or a diff).
|
|
47
93
|
* Deliberately narrow — only unambiguous bare forms, never piped/compound commands — so a legitimate
|
|
@@ -61,7 +107,15 @@ const BASH_INTERCEPTOR_RULES = [
|
|
|
61
107
|
tool: "grep",
|
|
62
108
|
why: "it groups, paginates, and bounds output instead of flooding the context",
|
|
63
109
|
},
|
|
64
|
-
{
|
|
110
|
+
{
|
|
111
|
+
// Only a *pure content* `rg` (no output-shape flag) has a `grep`-tool equivalent. Let
|
|
112
|
+
// `rg --files`, `rg -l`/`--files-with-matches`, `rg -c`/`--count`, `rg --type*` through —
|
|
113
|
+
// forms the grep tool cannot express (fix plan §3.5). Erring toward passing a command
|
|
114
|
+
// through is the safe direction.
|
|
115
|
+
test: /^\s*rg\b(?![^|&;]*\s-{1,2}\S*[lct])[^|&;]*$/,
|
|
116
|
+
tool: "grep",
|
|
117
|
+
why: "it groups, paginates, and bounds output",
|
|
118
|
+
},
|
|
65
119
|
{
|
|
66
120
|
test: /^\s*find\s+[^|&;<>`$()]*-name\b[^|&;<>`$()]*$/,
|
|
67
121
|
tool: "glob",
|
|
@@ -73,7 +127,10 @@ const BASH_INTERCEPTOR_RULES = [
|
|
|
73
127
|
why: "it discovers file paths without listing directories, and bounds/sorts the result",
|
|
74
128
|
},
|
|
75
129
|
{
|
|
76
|
-
|
|
130
|
+
// Only a *single-file* in-place `sed`/`perl` maps to what `edit` does: flags, `-i`, a script
|
|
131
|
+
// arg, then exactly one non-glob path. A multi-file batch replace (two paths, or a glob) is
|
|
132
|
+
// something `edit` cannot do, so let it through (fix plan §3.5).
|
|
133
|
+
test: /\b(?:sed|perl)\b(?:\s+-\S+)*\s+-i\S*\s+(?:'[^']*'|"[^"]*"|\S+)\s+[^\s|&;*?[\]]+\s*$/,
|
|
77
134
|
tool: "edit",
|
|
78
135
|
why: "it verifies a unique match and echoes a diff of the change",
|
|
79
136
|
},
|
|
@@ -99,11 +156,24 @@ export function createBashTool(executor, options = {}) {
|
|
|
99
156
|
agentWorkspaceDir: process.cwd(),
|
|
100
157
|
projectRoot: process.cwd(),
|
|
101
158
|
};
|
|
159
|
+
if (options.channelDir) {
|
|
160
|
+
void pruneBashLogs(options.channelDir);
|
|
161
|
+
}
|
|
102
162
|
return {
|
|
103
163
|
name: "bash",
|
|
104
164
|
label: "bash",
|
|
105
|
-
|
|
106
|
-
|
|
165
|
+
// A bash command can write any file, so running it alongside a concurrent `edit`/`write` in
|
|
166
|
+
// the same batch reopens the lost-update window that `checkFingerprintUnchanged` cannot close
|
|
167
|
+
// (both calls pass the pre-write fingerprint check, then each rewrites the whole file). This
|
|
168
|
+
// is a process-local measure only: external sub-agents are separate host processes and are
|
|
169
|
+
// not serialized by it. The SDK serializes the whole batch if *any* tool in it is sequential.
|
|
170
|
+
executionMode: "sequential",
|
|
171
|
+
description: `Execute a ${EXECUTOR_SHELL_IS_BASH ? "bash" : "POSIX sh (no bash on this host)"} command in the current working directory. Returns stdout, stderr, and the exit code (a non-zero exit code is reported in the output, not raised as an error). Output is truncated to the last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, the full output is saved to a file whose path is included. Commands time out after ${options.defaultTimeoutSeconds ?? DEFAULT_BASH_TIMEOUT_SECONDS}s unless you pass a larger \`timeout\`.`,
|
|
172
|
+
parameters: (options.jobManager
|
|
173
|
+
? options.boundTaskId
|
|
174
|
+
? bashSchemaBoundTask
|
|
175
|
+
: bashSchema
|
|
176
|
+
: bashSchemaNoJobs),
|
|
107
177
|
execute: async (_toolCallId, { command, timeout, async: runAsync, notify, taskId, }, signal) => {
|
|
108
178
|
if (securityConfig.enabled && securityConfig.commandGuard.enabled) {
|
|
109
179
|
const guardResult = guardCommand(command, securityConfig.commandGuard);
|
|
@@ -137,16 +207,25 @@ export function createBashTool(executor, options = {}) {
|
|
|
137
207
|
// Background execution: hand off to the channel's job manager and return immediately so
|
|
138
208
|
// the run queue is not held for the command's duration. Gated by `tools.jobs.enabled`
|
|
139
209
|
// (the main path supplies a jobManager; the sub-agent path never does).
|
|
210
|
+
// Inside a task session the runtime owns the task id; a conflicting one supplied through a
|
|
211
|
+
// non-schema path is rejected before anything launches (fix plan §3.3).
|
|
212
|
+
if (options.boundTaskId && taskId && taskId !== options.boundTaskId) {
|
|
213
|
+
throw new RecoverableToolError(`This is task ${options.boundTaskId}'s session — drop taskId (it is bound automatically); "${taskId}" does not belong here.`);
|
|
214
|
+
}
|
|
215
|
+
const effectiveTaskId = options.boundTaskId ?? taskId;
|
|
140
216
|
if (runAsync) {
|
|
217
|
+
if (effectiveTaskId && notify === false) {
|
|
218
|
+
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 with no taskId.");
|
|
219
|
+
}
|
|
141
220
|
if (!options.jobManager) {
|
|
142
|
-
throw new RecoverableToolError("
|
|
221
|
+
throw new RecoverableToolError("This context does not support background execution (sub-agents never get it). Run the command without async, or split it into shorter steps.");
|
|
143
222
|
}
|
|
144
223
|
const willNotify = notify ?? true;
|
|
145
224
|
const jobLabel = clipText(effectiveCommand, 60, { collapseWhitespace: true });
|
|
146
225
|
const job = await options.jobManager.start(effectiveCommand, jobLabel, effectiveTimeout, {
|
|
147
226
|
signal,
|
|
148
227
|
notify: willNotify,
|
|
149
|
-
...(
|
|
228
|
+
...(effectiveTaskId ? { taskId: effectiveTaskId } : {}),
|
|
150
229
|
});
|
|
151
230
|
return {
|
|
152
231
|
content: [
|
|
@@ -154,8 +233,8 @@ export function createBashTool(executor, options = {}) {
|
|
|
154
233
|
type: "text",
|
|
155
234
|
text: `Background job ${job.id} started: ${jobLabel}\n` +
|
|
156
235
|
(willNotify
|
|
157
|
-
? "
|
|
158
|
-
"
|
|
236
|
+
? "Complete any independent work, then end the turn when only waiting remains. Completion wakes this channel with the exit code and output; do not poll or schedule a check-in. " +
|
|
237
|
+
"Inside a task step, park with task_step_end on this job id."
|
|
159
238
|
: "It runs off-turn and will NOT wake you when it finishes; check it with the job tool (op:poll/list)."),
|
|
160
239
|
},
|
|
161
240
|
],
|
|
@@ -172,7 +251,7 @@ export function createBashTool(executor, options = {}) {
|
|
|
172
251
|
// the 10MB capture bound, so it is the one place that can honestly be called "full
|
|
173
252
|
// output" for a command whose real output exceeds that cap. It is deleted below when it
|
|
174
253
|
// turns out not to be needed.
|
|
175
|
-
const buildOutputText = async (stdout, stderr, spillPath) => {
|
|
254
|
+
const buildOutputText = async (stdout, stderr, spillPath, captureTruncated) => {
|
|
176
255
|
let output = "";
|
|
177
256
|
if (stdout)
|
|
178
257
|
output += stdout;
|
|
@@ -181,6 +260,27 @@ export function createBashTool(executor, options = {}) {
|
|
|
181
260
|
output += "\n";
|
|
182
261
|
output += stderr;
|
|
183
262
|
}
|
|
263
|
+
// When the executor's 10MB in-memory capture was itself truncated, `output` is only
|
|
264
|
+
// the *head* of the stream, so `truncateTail(output)` would return the middle of the
|
|
265
|
+
// command's output and label it the tail (fix plan §2.3). Read the real tail from the
|
|
266
|
+
// spill file — the one uncapped copy — and never quote a total line count we never saw.
|
|
267
|
+
if (captureTruncated) {
|
|
268
|
+
let tailSource = output;
|
|
269
|
+
try {
|
|
270
|
+
tailSource = await readFileTail(spillPath, TAIL_FROM_SPILL_BYTES);
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
// Spill unreadable: fall back to the capped head's tail; still bounded.
|
|
274
|
+
}
|
|
275
|
+
const tailTrunc = truncateTail(tailSource);
|
|
276
|
+
const shownBytes = Buffer.byteLength(tailTrunc.content, "utf-8");
|
|
277
|
+
const text = `${tailTrunc.content || "(no output)"}\n\n` +
|
|
278
|
+
`[Output capture was cut off at ${formatSize(DEFAULT_MAX_BYTES)}+; showing the last ${formatSize(shownBytes)} of the complete output. Full output: ${spillPath}]`;
|
|
279
|
+
return {
|
|
280
|
+
text,
|
|
281
|
+
details: { truncation: tailTrunc, fullOutputPath: spillPath, producedOutput: true },
|
|
282
|
+
};
|
|
283
|
+
}
|
|
184
284
|
const truncation = truncateTail(output);
|
|
185
285
|
let text = truncation.content || "(no output)";
|
|
186
286
|
let details;
|
|
@@ -203,19 +303,22 @@ export function createBashTool(executor, options = {}) {
|
|
|
203
303
|
else {
|
|
204
304
|
// No truncation happened after all -- the spill file was insurance against the
|
|
205
305
|
// in-memory capture cap, not a promised artifact; clean it up rather than leaving
|
|
206
|
-
//
|
|
306
|
+
// clutter behind on every single bash call.
|
|
207
307
|
await unlink(spillPath).catch(() => undefined);
|
|
208
308
|
}
|
|
209
309
|
return { text, details: { ...details, producedOutput: output.trim().length > 0 } };
|
|
210
310
|
};
|
|
211
|
-
const spillPath = getSpillFilePath();
|
|
311
|
+
const spillPath = getSpillFilePath(options.channelDir);
|
|
312
|
+
if (options.channelDir) {
|
|
313
|
+
await mkdir(join(options.channelDir, BASH_LOG_DIR_NAME), { recursive: true }).catch(() => undefined);
|
|
314
|
+
}
|
|
212
315
|
try {
|
|
213
316
|
const result = await executor.exec(effectiveCommand, {
|
|
214
317
|
timeout: effectiveTimeout,
|
|
215
318
|
signal,
|
|
216
319
|
spillTo: spillPath,
|
|
217
320
|
});
|
|
218
|
-
const built = await buildOutputText(result.stdout, result.stderr, spillPath);
|
|
321
|
+
const built = await buildOutputText(result.stdout, result.stderr, spillPath, result.stdoutTruncated === true || result.stderrTruncated === true);
|
|
219
322
|
let outputText = built.text;
|
|
220
323
|
// A non-zero exit code is a normal result, not a tool failure: commands like
|
|
221
324
|
// `grep` (no match), `diff` (differences), and `test` use exit codes as data.
|
|
@@ -233,7 +336,7 @@ export function createBashTool(executor, options = {}) {
|
|
|
233
336
|
if (!(error instanceof CommandTerminatedError)) {
|
|
234
337
|
throw error;
|
|
235
338
|
}
|
|
236
|
-
const built = await buildOutputText(error.stdout, error.stderr, spillPath);
|
|
339
|
+
const built = await buildOutputText(error.stdout, error.stderr, spillPath, error.captureTruncated);
|
|
237
340
|
const nextStep = error.reason === "timeout"
|
|
238
341
|
? `Retry with a larger \`timeout\` (currently ${error.timeoutSeconds}s), or pass \`async: true\` to run it in the background and be woken when it finishes.`
|
|
239
342
|
: "The command was stopped (e.g. by /stop or a run cancellation); partial output above.";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { shellEscape } from "../shared/
|
|
1
|
+
import { shellEscape } from "../shared/os.js";
|
|
2
2
|
/**
|
|
3
3
|
* Optional "outbound command transform" for the bash tool. When enabled, a command is
|
|
4
4
|
* handed to the `rtk` binary (https://github.com/rtk-ai/rtk) which rewrites known
|
package/dist/tools/config.d.ts
CHANGED
|
@@ -51,6 +51,13 @@ export interface LoadedToolsConfig {
|
|
|
51
51
|
config: PipiclawToolsConfig;
|
|
52
52
|
diagnostics: ConfigDiagnostic[];
|
|
53
53
|
}
|
|
54
|
+
/**
|
|
55
|
+
* Every `tools.<key>` section in `tools.json`, read by `test/config-reference-coverage.test.ts`
|
|
56
|
+
* to check that `docs/configuration-reference.md` still mentions each one. Kept in sync with
|
|
57
|
+
* `PipiclawToolsConfig["tools"]` by `satisfies` (rejects an extra/misspelled entry) and
|
|
58
|
+
* `AssertNoMissingKeys` (rejects a section with no entry here) — both at `npm run typecheck`.
|
|
59
|
+
*/
|
|
60
|
+
export declare const TOOLS_CONFIG_SECTION_KEYS: readonly ["web", "tasks", "bashInterceptor", "rtk", "subagentInline"];
|
|
54
61
|
export declare const DEFAULT_TOOLS_CONFIG: PipiclawToolsConfig;
|
|
55
62
|
export declare function getToolsConfigPath(appHomeDir?: string): string;
|
|
56
63
|
export declare function loadToolsConfigWithDiagnostics(appHomeDir?: string): LoadedToolsConfig;
|
package/dist/tools/config.js
CHANGED
|
@@ -1,8 +1,23 @@
|
|
|
1
1
|
import { join } from "node:path";
|
|
2
2
|
import { APP_HOME_DIR } from "../paths.js";
|
|
3
3
|
import { loadJsonConfig, pushConfigWarning } from "../shared/config-diagnostic.js";
|
|
4
|
-
import { clampInteger } from "../shared/
|
|
4
|
+
import { clampInteger } from "../shared/format.js";
|
|
5
5
|
import { isRecord } from "../shared/type-guards.js";
|
|
6
|
+
/**
|
|
7
|
+
* Every `tools.<key>` section in `tools.json`, read by `test/config-reference-coverage.test.ts`
|
|
8
|
+
* to check that `docs/configuration-reference.md` still mentions each one. Kept in sync with
|
|
9
|
+
* `PipiclawToolsConfig["tools"]` by `satisfies` (rejects an extra/misspelled entry) and
|
|
10
|
+
* `AssertNoMissingKeys` (rejects a section with no entry here) — both at `npm run typecheck`.
|
|
11
|
+
*/
|
|
12
|
+
export const TOOLS_CONFIG_SECTION_KEYS = [
|
|
13
|
+
"web",
|
|
14
|
+
"tasks",
|
|
15
|
+
"bashInterceptor",
|
|
16
|
+
"rtk",
|
|
17
|
+
"subagentInline",
|
|
18
|
+
];
|
|
19
|
+
const _toolsConfigKeysComplete = true;
|
|
20
|
+
void _toolsConfigKeysComplete;
|
|
6
21
|
const WEB_SEARCH_PROVIDERS = ["brave", "tavily", "jina", "searxng", "duckduckgo"];
|
|
7
22
|
export const DEFAULT_TOOLS_CONFIG = {
|
|
8
23
|
tools: {
|
package/dist/tools/edit.js
CHANGED
|
@@ -88,6 +88,8 @@ const editSchema = Type.Object({
|
|
|
88
88
|
});
|
|
89
89
|
/** Max diff lines echoed back to the model in the success result before eliding the rest. */
|
|
90
90
|
const DIFF_ECHO_MAX_LINES = 40;
|
|
91
|
+
/** Byte ceiling on the echoed diff — 40 lines of a minified single-line file can be hundreds of KB. */
|
|
92
|
+
const DIFF_ECHO_MAX_BYTES = 8 * 1024;
|
|
91
93
|
/** Consecutive byte-identical no-ops of the same payload before the soft error escalates to a hard stop. */
|
|
92
94
|
const NOOP_HARD_LIMIT = 3;
|
|
93
95
|
/** Above this, `edit` switches from "read whole file into memory" to the streaming two-pass path (D2.2). */
|
|
@@ -108,11 +110,20 @@ const DIFF_WINDOW_BYTES = 2000;
|
|
|
108
110
|
const MAX_DIFF_WINDOWS = 5;
|
|
109
111
|
function clampDiffForEcho(diff) {
|
|
110
112
|
const lines = diff.split("\n");
|
|
111
|
-
if (lines.length <= DIFF_ECHO_MAX_LINES) {
|
|
113
|
+
if (lines.length <= DIFF_ECHO_MAX_LINES && Buffer.byteLength(diff, "utf-8") <= DIFF_ECHO_MAX_BYTES) {
|
|
112
114
|
return diff;
|
|
113
115
|
}
|
|
114
|
-
|
|
115
|
-
|
|
116
|
+
let kept = lines.slice(0, DIFF_ECHO_MAX_LINES);
|
|
117
|
+
while (kept.length > 1 && Buffer.byteLength(kept.join("\n"), "utf-8") > DIFF_ECHO_MAX_BYTES) {
|
|
118
|
+
kept = kept.slice(0, -1);
|
|
119
|
+
}
|
|
120
|
+
let shown = kept.join("\n");
|
|
121
|
+
if (Buffer.byteLength(shown, "utf-8") > DIFF_ECHO_MAX_BYTES) {
|
|
122
|
+
// A single line still over budget: hard-cut on a UTF-8 boundary.
|
|
123
|
+
shown = Buffer.from(shown, "utf-8").subarray(0, DIFF_ECHO_MAX_BYTES).toString("utf-8");
|
|
124
|
+
}
|
|
125
|
+
const omitted = lines.length - kept.length;
|
|
126
|
+
return `${shown}\n[diff truncated${omitted > 0 ? `, ${omitted} more line(s)` : ""}; the full diff is in the tool result details]`;
|
|
116
127
|
}
|
|
117
128
|
/** All non-overlapping byte offsets of `needle` in `haystack`, left to right (mirrors `String.split`). */
|
|
118
129
|
function findAllOffsets(haystack, needle) {
|
|
@@ -152,6 +163,12 @@ async function scanOccurrences(stream, needle, maxOffsets) {
|
|
|
152
163
|
let windowBaseOffset = 0;
|
|
153
164
|
let newlinesBeforeWindow = 0;
|
|
154
165
|
let count = 0;
|
|
166
|
+
// Absolute byte position just past the last accepted match. A window carries the last
|
|
167
|
+
// `overlapLen` bytes of its predecessor, so without this guard a match that ended inside the
|
|
168
|
+
// carry region would be re-found (from a fresh `from = 0`) and reported as a second, overlapping
|
|
169
|
+
// offset -- which `spliceBuffer` then turns into a corrupt file. Verified against a non-overlapping
|
|
170
|
+
// `Buffer.indexOf` reference over 165 boundary combinations.
|
|
171
|
+
let nextAllowed = 0;
|
|
155
172
|
let offsets = [];
|
|
156
173
|
const lineNumbers = new Map();
|
|
157
174
|
let looksBinary = false;
|
|
@@ -166,14 +183,15 @@ async function scanOccurrences(stream, needle, maxOffsets) {
|
|
|
166
183
|
sniffed += take.length;
|
|
167
184
|
}
|
|
168
185
|
const window = carry.length > 0 ? Buffer.concat([carry, chunk]) : chunk;
|
|
169
|
-
let from = 0;
|
|
186
|
+
let from = Math.max(0, nextAllowed - windowBaseOffset);
|
|
170
187
|
while (true) {
|
|
171
188
|
const idx = window.indexOf(needle, from);
|
|
172
189
|
if (idx === -1)
|
|
173
190
|
break;
|
|
191
|
+
const absoluteOffset = windowBaseOffset + idx;
|
|
174
192
|
count++;
|
|
193
|
+
nextAllowed = absoluteOffset + needle.length;
|
|
175
194
|
if (offsets && offsets.length < maxOffsets) {
|
|
176
|
-
const absoluteOffset = windowBaseOffset + idx;
|
|
177
195
|
offsets.push(absoluteOffset);
|
|
178
196
|
const lineNumber = newlinesBeforeWindow + countNewlines(window, 0, idx) + 1;
|
|
179
197
|
lineNumbers.set(absoluteOffset, lineNumber);
|
|
@@ -252,6 +270,10 @@ export function createEditTool(fileStore, options = {}) {
|
|
|
252
270
|
return {
|
|
253
271
|
name: "edit",
|
|
254
272
|
label: "edit",
|
|
273
|
+
// Serialize with other mutating tools in the same batch. `checkFingerprintUnchanged` runs
|
|
274
|
+
// before the write, so two concurrent edits can both pass it and then overwrite each other's
|
|
275
|
+
// result; running the batch one tool at a time closes that window (spec: batch 1.3).
|
|
276
|
+
executionMode: "sequential",
|
|
255
277
|
description: "Edit a file by replacing exact text. The oldText must match exactly (including whitespace). Use this for precise, surgical edits.",
|
|
256
278
|
parameters: editSchema,
|
|
257
279
|
execute: async (_toolCallId, { path, oldText, newText, replaceAll, }, signal) => {
|
|
@@ -262,6 +284,15 @@ export function createEditTool(fileStore, options = {}) {
|
|
|
262
284
|
tool: "edit",
|
|
263
285
|
channelId: options.channelId,
|
|
264
286
|
});
|
|
287
|
+
// `edit` rewrites the file in place, so it must clear the *write* guard too (spec 044,
|
|
288
|
+
// D1.1). Pass the original `path`, never the realpath'd `target`: the guard's
|
|
289
|
+
// symlink-write check lstats the pre-symlink-resolution path, and handing it a resolved
|
|
290
|
+
// value would blind it to "the path itself is a symlink". Both calls return the same
|
|
291
|
+
// `resolvedPath` for read and write, so `target` stays the one value we open.
|
|
292
|
+
await checkPathGuard(path, "write", securityConfig, securityContext, {
|
|
293
|
+
tool: "edit",
|
|
294
|
+
channelId: options.channelId,
|
|
295
|
+
});
|
|
265
296
|
const before = await fileStore.stat(target);
|
|
266
297
|
if (!before || !before.isFile) {
|
|
267
298
|
throw new RecoverableToolError(`File not found: ${path}`);
|