@oyasmi/pipiclaw 0.7.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/channel-runner.d.ts +13 -0
- package/dist/agent/channel-runner.js +120 -6
- package/dist/agent/model-fallback.d.ts +64 -0
- package/dist/agent/model-fallback.js +125 -0
- package/dist/agent/types.d.ts +5 -0
- package/dist/log.d.ts +1 -0
- package/dist/log.js +9 -0
- package/dist/runtime/bootstrap.js +8 -3
- package/dist/sandbox.js +7 -77
- package/dist/security/command-guard.js +0 -4
- package/dist/security/path-guard.js +0 -4
- package/dist/settings.d.ts +7 -0
- package/dist/settings.js +12 -0
- package/dist/shared/shell-escape.d.ts +0 -7
- package/dist/shared/shell-escape.js +0 -11
- package/dist/tools/bash.js +2 -2
- package/dist/tools/edit.js +2 -2
- package/dist/tools/read.js +6 -6
- package/dist/tools/write-content.js +3 -3
- package/package.json +1 -1
- package/dist/security/platform.d.ts +0 -1
- package/dist/security/platform.js +0 -3
|
@@ -30,6 +30,8 @@ export declare class ChannelRunner implements AgentRunner {
|
|
|
30
30
|
private firstTurnMemoryBootstrapPending;
|
|
31
31
|
private acceptingBusyMessages;
|
|
32
32
|
private agentLoopStarted;
|
|
33
|
+
/** When the primary model last failed and we switched to the backup. null = on primary. */
|
|
34
|
+
private primaryFailedAt;
|
|
33
35
|
private runState;
|
|
34
36
|
constructor(sandboxConfig: SandboxConfig, channelId: string, channelDir: string);
|
|
35
37
|
run(ctx: DingTalkContext, store: ChannelStore): Promise<{
|
|
@@ -50,6 +52,17 @@ export declare class ChannelRunner implements AgentRunner {
|
|
|
50
52
|
private queueBusyMessage;
|
|
51
53
|
private resetRunState;
|
|
52
54
|
private refreshSessionResources;
|
|
55
|
+
/**
|
|
56
|
+
* At turn start, if a fallback is active and the primary's cooldown has elapsed,
|
|
57
|
+
* switch back to the preferred model. Silent — no user notice on recovery.
|
|
58
|
+
*/
|
|
59
|
+
private maybeRestorePrimaryModel;
|
|
60
|
+
/**
|
|
61
|
+
* Resolve the configured backup model reference against available models.
|
|
62
|
+
* Returns null when unset, unresolvable/ambiguous, or missing an API key —
|
|
63
|
+
* each case logs a warning and disables fallback for this turn.
|
|
64
|
+
*/
|
|
65
|
+
private resolveFallbackModel;
|
|
53
66
|
private initializeSession;
|
|
54
67
|
private reloadSessionResources;
|
|
55
68
|
private bindSessionExtensions;
|
|
@@ -10,7 +10,7 @@ import { MemoryLifecycle } from "../memory/lifecycle.js";
|
|
|
10
10
|
import { applyMemoryActivityToState, updateMemoryMaintenanceState, } from "../memory/maintenance-state.js";
|
|
11
11
|
import { recallRelevantMemory } from "../memory/recall.js";
|
|
12
12
|
import { getApiKeyForModel } from "../models/api-keys.js";
|
|
13
|
-
import { formatModelReference, resolveInitialModel } from "../models/utils.js";
|
|
13
|
+
import { findExactModelReferenceMatch, formatModelReference, resolveInitialModel } from "../models/utils.js";
|
|
14
14
|
import { APP_HOME_DIR, AUTH_CONFIG_PATH, MODELS_CONFIG_PATH } from "../paths.js";
|
|
15
15
|
import { createExecutor } from "../sandbox.js";
|
|
16
16
|
import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
|
|
@@ -26,7 +26,8 @@ import { getUsageLedger } from "../usage/ledger.js";
|
|
|
26
26
|
import { createCommandExtension } from "./command-extension.js";
|
|
27
27
|
import { renderBuiltInHelp } from "./commands.js";
|
|
28
28
|
import { estimateIncomingMessageTokens, getPreventiveCompactionDecision } from "./context-budget.js";
|
|
29
|
-
import {
|
|
29
|
+
import { PRIMARY_COOLDOWN_MS, runPromptWithFallback, shouldRestorePrimary, } from "./model-fallback.js";
|
|
30
|
+
import { clipUserInput, formatProgressEntry } from "./progress-formatter.js";
|
|
30
31
|
import { buildAppendSystemPrompt } from "./prompt-builder.js";
|
|
31
32
|
import { createRunQueue } from "./run-queue.js";
|
|
32
33
|
import { handleSessionEvent } from "./session-events.js";
|
|
@@ -59,6 +60,8 @@ export class ChannelRunner {
|
|
|
59
60
|
this.firstTurnMemoryBootstrapPending = true;
|
|
60
61
|
this.acceptingBusyMessages = false;
|
|
61
62
|
this.agentLoopStarted = false;
|
|
63
|
+
/** When the primary model last failed and we switched to the backup. null = on primary. */
|
|
64
|
+
this.primaryFailedAt = null;
|
|
62
65
|
// --- Per run ---
|
|
63
66
|
this.runState = createEmptyRunState();
|
|
64
67
|
this.sandboxConfig = sandboxConfig;
|
|
@@ -150,8 +153,11 @@ export class ChannelRunner {
|
|
|
150
153
|
const runQueue = createRunQueue(ctx);
|
|
151
154
|
this.runState.queue = runQueue.queue;
|
|
152
155
|
let promptSubmitted = false;
|
|
156
|
+
let fallbackAttempted = false;
|
|
157
|
+
let fallbackTargetRef;
|
|
153
158
|
try {
|
|
154
159
|
await this.ensureSessionReady();
|
|
160
|
+
await this.maybeRestorePrimaryModel();
|
|
155
161
|
this.memoryLifecycle.noteUserTurnStarted();
|
|
156
162
|
const normalizedInputLength = ctx.message.text.replace(/\r/g, "").trim().length;
|
|
157
163
|
if (normalizedInputLength > MAX_USER_MESSAGE_CHARS) {
|
|
@@ -207,10 +213,58 @@ export class ChannelRunner {
|
|
|
207
213
|
};
|
|
208
214
|
await writeFile(join(this.channelDir, "last_prompt.json"), JSON.stringify(debugContext, null, 2));
|
|
209
215
|
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
216
|
+
const fallbackDeps = {
|
|
217
|
+
prompt: async (text) => {
|
|
218
|
+
try {
|
|
219
|
+
await this.sessionResourceGate.runPrompt(async () => {
|
|
220
|
+
await this.session.prompt(text);
|
|
221
|
+
promptSubmitted = true;
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
catch (err) {
|
|
225
|
+
this.runState.stopReason = "error";
|
|
226
|
+
this.runState.errorMessage = err instanceof Error ? err.message : String(err);
|
|
227
|
+
log.logWarning(`[${this.channelId}] Runner failed`, this.runState.errorMessage);
|
|
228
|
+
}
|
|
229
|
+
},
|
|
230
|
+
getRunError: () => ({
|
|
231
|
+
stopReason: this.runState.stopReason,
|
|
232
|
+
errorMessage: this.runState.errorMessage,
|
|
233
|
+
}),
|
|
234
|
+
resetRunError: () => {
|
|
235
|
+
this.runState.stopReason = "stop";
|
|
236
|
+
this.runState.errorMessage = undefined;
|
|
237
|
+
this.runState.finalOutcome = { kind: "none" };
|
|
238
|
+
this.runState.lastCompactionError = undefined;
|
|
239
|
+
},
|
|
240
|
+
getMessages: () => this.agent.state.messages,
|
|
241
|
+
setMessages: (messages) => {
|
|
242
|
+
this.agent.state.messages = messages;
|
|
243
|
+
},
|
|
244
|
+
promptWasSubmitted: () => promptSubmitted,
|
|
245
|
+
getCurrentModelRef: () => formatModelReference(this.session.model ?? this.activeModel),
|
|
246
|
+
resolveFallbackModel: () => this.resolveFallbackModel(),
|
|
247
|
+
setModel: async (model) => {
|
|
248
|
+
await this.session.setModel(model);
|
|
249
|
+
},
|
|
250
|
+
notifySwitch: (from, to, errorSummary) => {
|
|
251
|
+
fallbackTargetRef = to;
|
|
252
|
+
if (this.runState.logCtx) {
|
|
253
|
+
log.logModelFallback(this.runState.logCtx, from, to, errorSummary);
|
|
254
|
+
}
|
|
255
|
+
const text = `⚠️ 模型 ${from} 出错(${errorSummary}),切换到 ${to} 重试…`;
|
|
256
|
+
if (ctx.progressStyle !== "none") {
|
|
257
|
+
runQueue.queue.enqueue(() => ctx.respond(formatProgressEntry("error", text), false), "fallback switch");
|
|
258
|
+
}
|
|
259
|
+
else {
|
|
260
|
+
runQueue.queue.enqueue(() => ctx.respondInThread(text), "fallback switch");
|
|
261
|
+
}
|
|
262
|
+
},
|
|
263
|
+
markPrimaryFailed: () => {
|
|
264
|
+
this.primaryFailedAt = Date.now();
|
|
265
|
+
},
|
|
266
|
+
};
|
|
267
|
+
fallbackAttempted = await runPromptWithFallback(promptText, fallbackDeps);
|
|
214
268
|
}
|
|
215
269
|
catch (err) {
|
|
216
270
|
this.runState.stopReason = "error";
|
|
@@ -248,6 +302,9 @@ export class ChannelRunner {
|
|
|
248
302
|
if (compactionSummary) {
|
|
249
303
|
detailLines.push(`Recovery: \`${compactionSummary}\``);
|
|
250
304
|
}
|
|
305
|
+
if (fallbackAttempted && fallbackTargetRef) {
|
|
306
|
+
detailLines.push(`已切换备用模型 \`${fallbackTargetRef}\` 重试,仍失败。`);
|
|
307
|
+
}
|
|
251
308
|
await ctx.replaceMessage(`_Sorry, something went wrong._\n\n${detailLines.join("\n\n")}`);
|
|
252
309
|
}
|
|
253
310
|
catch (err) {
|
|
@@ -390,11 +447,18 @@ export class ChannelRunner {
|
|
|
390
447
|
getStatusSnapshot() {
|
|
391
448
|
const model = this.session.model ?? this.activeModel;
|
|
392
449
|
const contextTokens = this.session.getContextUsage()?.tokens;
|
|
450
|
+
const fallbackActive = formatModelReference(model) !== formatModelReference(this.activeModel);
|
|
393
451
|
return {
|
|
394
452
|
model: formatModelReference(model),
|
|
395
453
|
contextTokens: typeof contextTokens === "number" ? contextTokens : undefined,
|
|
396
454
|
contextWindow: model.contextWindow || 200000,
|
|
397
455
|
thinkingLevel: this.session.thinkingLevel,
|
|
456
|
+
fallback: fallbackActive
|
|
457
|
+
? {
|
|
458
|
+
primary: formatModelReference(this.activeModel),
|
|
459
|
+
cooldownUntilMs: (this.primaryFailedAt ?? Date.now()) + PRIMARY_COOLDOWN_MS,
|
|
460
|
+
}
|
|
461
|
+
: undefined,
|
|
398
462
|
};
|
|
399
463
|
}
|
|
400
464
|
async abort() {
|
|
@@ -486,6 +550,54 @@ export class ChannelRunner {
|
|
|
486
550
|
await this.ensureSessionReady();
|
|
487
551
|
await this.sessionResourceGate.requestRefresh();
|
|
488
552
|
}
|
|
553
|
+
/**
|
|
554
|
+
* At turn start, if a fallback is active and the primary's cooldown has elapsed,
|
|
555
|
+
* switch back to the preferred model. Silent — no user notice on recovery.
|
|
556
|
+
*/
|
|
557
|
+
async maybeRestorePrimaryModel() {
|
|
558
|
+
const current = this.session.model;
|
|
559
|
+
if (!current || formatModelReference(current) === formatModelReference(this.activeModel)) {
|
|
560
|
+
this.primaryFailedAt = null;
|
|
561
|
+
return;
|
|
562
|
+
}
|
|
563
|
+
if (!shouldRestorePrimary(this.primaryFailedAt, Date.now())) {
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
try {
|
|
567
|
+
await this.session.setModel(this.activeModel);
|
|
568
|
+
this.primaryFailedAt = null;
|
|
569
|
+
log.logInfo(`[${this.channelId}] Restored primary model ${formatModelReference(this.activeModel)}`);
|
|
570
|
+
}
|
|
571
|
+
catch (err) {
|
|
572
|
+
log.logWarning(`[${this.channelId}] Failed to restore primary model`, err instanceof Error ? err.message : String(err));
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* Resolve the configured backup model reference against available models.
|
|
577
|
+
* Returns null when unset, unresolvable/ambiguous, or missing an API key —
|
|
578
|
+
* each case logs a warning and disables fallback for this turn.
|
|
579
|
+
*/
|
|
580
|
+
async resolveFallbackModel() {
|
|
581
|
+
const reference = this.settingsManager.getFallbackModelReference();
|
|
582
|
+
if (!reference) {
|
|
583
|
+
return null;
|
|
584
|
+
}
|
|
585
|
+
this.modelRegistry.refresh();
|
|
586
|
+
const available = await this.modelRegistry.getAvailable();
|
|
587
|
+
const { match, ambiguous } = findExactModelReferenceMatch(reference, available);
|
|
588
|
+
if (!match) {
|
|
589
|
+
log.logWarning(`[${this.channelId}] fallbackModel "${reference}" ${ambiguous ? "is ambiguous" : "not found"}; skipping fallback`);
|
|
590
|
+
return null;
|
|
591
|
+
}
|
|
592
|
+
try {
|
|
593
|
+
await getApiKeyForModel(this.modelRegistry, match);
|
|
594
|
+
}
|
|
595
|
+
catch {
|
|
596
|
+
log.logWarning(`[${this.channelId}] fallbackModel "${reference}" has no API key; skipping fallback`);
|
|
597
|
+
return null;
|
|
598
|
+
}
|
|
599
|
+
return match;
|
|
600
|
+
}
|
|
489
601
|
async initializeSession() {
|
|
490
602
|
await this.reloadSessionResources();
|
|
491
603
|
await this.bindSessionExtensions();
|
|
@@ -584,6 +696,8 @@ export class ChannelRunner {
|
|
|
584
696
|
switchModel: async (model) => {
|
|
585
697
|
await this.session.setModel(model);
|
|
586
698
|
this.activeModel = model;
|
|
699
|
+
// Manual /model switch redefines the preferred model and clears fallback state.
|
|
700
|
+
this.primaryFailedAt = null;
|
|
587
701
|
},
|
|
588
702
|
refreshSessionResources: async () => {
|
|
589
703
|
await this.refreshSessionResources();
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
2
|
+
/**
|
|
3
|
+
* Backup-model fallback (spec 017).
|
|
4
|
+
*
|
|
5
|
+
* When the primary model's turn ends in error, switch to a single configured
|
|
6
|
+
* backup model and re-run the turn once. Pure decision helpers live here so the
|
|
7
|
+
* orchestration is fully testable without a real SDK session.
|
|
8
|
+
*/
|
|
9
|
+
/** How long the primary model stays "cooling down" after a fallback before we retry it. */
|
|
10
|
+
export declare const PRIMARY_COOLDOWN_MS: number;
|
|
11
|
+
/**
|
|
12
|
+
* A turn ended with `stopReason: "error"`. Decide whether switching to the backup
|
|
13
|
+
* model is worth trying. Blacklist, not classifier: everything is worth a retry on a
|
|
14
|
+
* different provider EXCEPT context overflow (that is compaction's job — a bigger
|
|
15
|
+
* transcript fails the same way on any model). 429 / 5xx / quota / auth / even 400 all
|
|
16
|
+
* return true; the cost of a wasted extra attempt buys a one-sentence rule.
|
|
17
|
+
*/
|
|
18
|
+
export declare function shouldFallback(errorMessage: string | undefined): boolean;
|
|
19
|
+
/**
|
|
20
|
+
* State surgery. The failed single-shot turn leaves the transcript tail as
|
|
21
|
+
* `[user, assistant(stopReason "error")]` — the shape of the common 429 / quota / auth
|
|
22
|
+
* case where the very first API call fails before any tool runs. Return the transcript
|
|
23
|
+
* with those two messages removed, ready to be re-prompted on the backup model.
|
|
24
|
+
*
|
|
25
|
+
* Returns `null` if the tail is any other shape (multi-step failure, unexpected state).
|
|
26
|
+
* The caller MUST then skip fallback — better to surface the error than corrupt context.
|
|
27
|
+
* This is the single coupling point to the SDK's `agent.state.messages` layout.
|
|
28
|
+
*/
|
|
29
|
+
export declare function takeFailedTurn(messages: readonly unknown[]): unknown[] | null;
|
|
30
|
+
/** At turn start, may we leave the backup model and try the primary again? */
|
|
31
|
+
export declare function shouldRestorePrimary(primaryFailedAt: number | null, now: number): boolean;
|
|
32
|
+
/** Short one-line error summary for the user-facing switch notice. */
|
|
33
|
+
export declare function summarizeFallbackError(errorMessage: string | undefined): string;
|
|
34
|
+
export interface FallbackRunDeps {
|
|
35
|
+
/** Submit a prompt. Must catch transport/prompt errors and record them into run error state. */
|
|
36
|
+
prompt(text: string): Promise<void>;
|
|
37
|
+
/** Read the current turn's terminal error state (populated by prompt + session events). */
|
|
38
|
+
getRunError(): {
|
|
39
|
+
stopReason: string;
|
|
40
|
+
errorMessage?: string;
|
|
41
|
+
};
|
|
42
|
+
/** Clear stopReason/errorMessage/finalOutcome so the re-run starts clean. */
|
|
43
|
+
resetRunError(): void;
|
|
44
|
+
/** Live `agent.state.messages` reference for surgery. */
|
|
45
|
+
getMessages(): readonly unknown[];
|
|
46
|
+
/** Assign the truncated transcript back (SDK setter copies the array). */
|
|
47
|
+
setMessages(messages: unknown[]): void;
|
|
48
|
+
/** Whether the first prompt actually enqueued its user message (false = pre-flight throw, e.g. no API key). */
|
|
49
|
+
promptWasSubmitted(): boolean;
|
|
50
|
+
getCurrentModelRef(): string;
|
|
51
|
+
/** Resolve the configured backup model, or null (unset / unresolvable / no API key). */
|
|
52
|
+
resolveFallbackModel(): Promise<Model<Api> | null>;
|
|
53
|
+
setModel(model: Model<Api>): Promise<void>;
|
|
54
|
+
/** Notify the user a switch happened. */
|
|
55
|
+
notifySwitch(from: string, to: string, errorSummary: string): void;
|
|
56
|
+
/** Record `primaryFailedAt = now` so cooldown/restore logic engages. */
|
|
57
|
+
markPrimaryFailed(): void;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Run the prompt with at most one backup-model retry. Returns whether a fallback
|
|
61
|
+
* re-run was attempted (for error-message wording / logging). When no backup is
|
|
62
|
+
* configured, this is a single `prompt()` — behaviorally identical to the status quo.
|
|
63
|
+
*/
|
|
64
|
+
export declare function runPromptWithFallback(promptText: string, deps: FallbackRunDeps): Promise<boolean>;
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { isContextOverflow } from "@earendil-works/pi-ai";
|
|
2
|
+
import * as log from "../log.js";
|
|
3
|
+
import { formatModelReference } from "../models/utils.js";
|
|
4
|
+
import { isRecord } from "../shared/type-guards.js";
|
|
5
|
+
/**
|
|
6
|
+
* Backup-model fallback (spec 017).
|
|
7
|
+
*
|
|
8
|
+
* When the primary model's turn ends in error, switch to a single configured
|
|
9
|
+
* backup model and re-run the turn once. Pure decision helpers live here so the
|
|
10
|
+
* orchestration is fully testable without a real SDK session.
|
|
11
|
+
*/
|
|
12
|
+
/** How long the primary model stays "cooling down" after a fallback before we retry it. */
|
|
13
|
+
export const PRIMARY_COOLDOWN_MS = 5 * 60_000;
|
|
14
|
+
/**
|
|
15
|
+
* A turn ended with `stopReason: "error"`. Decide whether switching to the backup
|
|
16
|
+
* model is worth trying. Blacklist, not classifier: everything is worth a retry on a
|
|
17
|
+
* different provider EXCEPT context overflow (that is compaction's job — a bigger
|
|
18
|
+
* transcript fails the same way on any model). 429 / 5xx / quota / auth / even 400 all
|
|
19
|
+
* return true; the cost of a wasted extra attempt buys a one-sentence rule.
|
|
20
|
+
*/
|
|
21
|
+
export function shouldFallback(errorMessage) {
|
|
22
|
+
if (!errorMessage) {
|
|
23
|
+
return true;
|
|
24
|
+
}
|
|
25
|
+
// Only the error-message branch of isContextOverflow matters here (we already know
|
|
26
|
+
// stopReason === "error"); usage/contextWindow paths are irrelevant, so a minimal
|
|
27
|
+
// message is enough. NON_OVERFLOW_PATTERNS inside keeps rate-limit (429) → fallback.
|
|
28
|
+
const overflow = isContextOverflow({
|
|
29
|
+
role: "assistant",
|
|
30
|
+
stopReason: "error",
|
|
31
|
+
errorMessage,
|
|
32
|
+
content: [],
|
|
33
|
+
usage: {
|
|
34
|
+
input: 0,
|
|
35
|
+
output: 0,
|
|
36
|
+
cacheRead: 0,
|
|
37
|
+
cacheWrite: 0,
|
|
38
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
return !overflow;
|
|
42
|
+
}
|
|
43
|
+
function isAssistantErrorMessage(value) {
|
|
44
|
+
return isRecord(value) && value.role === "assistant" && value.stopReason === "error";
|
|
45
|
+
}
|
|
46
|
+
function isUserMessage(value) {
|
|
47
|
+
return isRecord(value) && value.role === "user";
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* State surgery. The failed single-shot turn leaves the transcript tail as
|
|
51
|
+
* `[user, assistant(stopReason "error")]` — the shape of the common 429 / quota / auth
|
|
52
|
+
* case where the very first API call fails before any tool runs. Return the transcript
|
|
53
|
+
* with those two messages removed, ready to be re-prompted on the backup model.
|
|
54
|
+
*
|
|
55
|
+
* Returns `null` if the tail is any other shape (multi-step failure, unexpected state).
|
|
56
|
+
* The caller MUST then skip fallback — better to surface the error than corrupt context.
|
|
57
|
+
* This is the single coupling point to the SDK's `agent.state.messages` layout.
|
|
58
|
+
*/
|
|
59
|
+
export function takeFailedTurn(messages) {
|
|
60
|
+
if (messages.length < 2) {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
const last = messages[messages.length - 1];
|
|
64
|
+
const prev = messages[messages.length - 2];
|
|
65
|
+
if (!isAssistantErrorMessage(last) || !isUserMessage(prev)) {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
return messages.slice(0, -2);
|
|
69
|
+
}
|
|
70
|
+
/** At turn start, may we leave the backup model and try the primary again? */
|
|
71
|
+
export function shouldRestorePrimary(primaryFailedAt, now) {
|
|
72
|
+
if (primaryFailedAt === null) {
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
return now - primaryFailedAt > PRIMARY_COOLDOWN_MS;
|
|
76
|
+
}
|
|
77
|
+
/** Short one-line error summary for the user-facing switch notice. */
|
|
78
|
+
export function summarizeFallbackError(errorMessage) {
|
|
79
|
+
if (!errorMessage) {
|
|
80
|
+
return "未知错误";
|
|
81
|
+
}
|
|
82
|
+
const firstLine = errorMessage.split("\n")[0]?.trim() ?? "";
|
|
83
|
+
if (!firstLine) {
|
|
84
|
+
return "未知错误";
|
|
85
|
+
}
|
|
86
|
+
return firstLine.length > 120 ? `${firstLine.slice(0, 117)}...` : firstLine;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Run the prompt with at most one backup-model retry. Returns whether a fallback
|
|
90
|
+
* re-run was attempted (for error-message wording / logging). When no backup is
|
|
91
|
+
* configured, this is a single `prompt()` — behaviorally identical to the status quo.
|
|
92
|
+
*/
|
|
93
|
+
export async function runPromptWithFallback(promptText, deps) {
|
|
94
|
+
await deps.prompt(promptText);
|
|
95
|
+
const firstError = deps.getRunError();
|
|
96
|
+
if (firstError.stopReason !== "error" || !shouldFallback(firstError.errorMessage)) {
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
const candidate = await deps.resolveFallbackModel();
|
|
100
|
+
if (!candidate) {
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
const fromRef = deps.getCurrentModelRef();
|
|
104
|
+
const toRef = formatModelReference(candidate);
|
|
105
|
+
if (fromRef === toRef) {
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
// Surgery only when the failed turn was actually enqueued. A pre-flight throw
|
|
109
|
+
// (no API key on the primary) submits nothing, so there is nothing to remove —
|
|
110
|
+
// switch straight to the backup, which covers a mis-configured primary key.
|
|
111
|
+
if (deps.promptWasSubmitted()) {
|
|
112
|
+
const truncated = takeFailedTurn(deps.getMessages());
|
|
113
|
+
if (!truncated) {
|
|
114
|
+
log.logWarning("[fallback] transcript tail is not [user, assistant(error)]; skipping fallback to avoid corrupting context");
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
deps.setMessages(truncated);
|
|
118
|
+
}
|
|
119
|
+
deps.markPrimaryFailed();
|
|
120
|
+
await deps.setModel(candidate);
|
|
121
|
+
deps.notifySwitch(fromRef, toRef, summarizeFallbackError(firstError.errorMessage));
|
|
122
|
+
deps.resetRunError();
|
|
123
|
+
await deps.prompt(promptText);
|
|
124
|
+
return true;
|
|
125
|
+
}
|
package/dist/agent/types.d.ts
CHANGED
|
@@ -8,6 +8,11 @@ export interface RunnerStatusSnapshot {
|
|
|
8
8
|
contextTokens?: number;
|
|
9
9
|
contextWindow: number;
|
|
10
10
|
thinkingLevel: string;
|
|
11
|
+
/** Present only while running on the backup model (spec 017). */
|
|
12
|
+
fallback?: {
|
|
13
|
+
primary: string;
|
|
14
|
+
cooldownUntilMs: number;
|
|
15
|
+
};
|
|
11
16
|
}
|
|
12
17
|
export interface AgentRunner {
|
|
13
18
|
run(ctx: DingTalkContext, store: ChannelStore): Promise<{
|
package/dist/log.d.ts
CHANGED
|
@@ -37,6 +37,7 @@ export declare function logResponse(ctx: LogContext, text: string): void;
|
|
|
37
37
|
export declare function logInfo(message: string): void;
|
|
38
38
|
export declare function logWarning(message: string, details?: string): void;
|
|
39
39
|
export declare function logAgentError(ctx: LogContext | "system", error: string): void;
|
|
40
|
+
export declare function logModelFallback(ctx: LogContext, from: string, to: string, error: string): void;
|
|
40
41
|
export declare function logUsageSummary(ctx: LogContext, usage: {
|
|
41
42
|
input: number;
|
|
42
43
|
output: number;
|
package/dist/log.js
CHANGED
|
@@ -217,6 +217,15 @@ export function logAgentError(ctx, error) {
|
|
|
217
217
|
details: error,
|
|
218
218
|
});
|
|
219
219
|
}
|
|
220
|
+
// Model fallback (spec 017)
|
|
221
|
+
export function logModelFallback(ctx, from, to, error) {
|
|
222
|
+
console.log(color("yellow", `${timestamp()} ${formatContext(ctx)} ⤳ Fallback ${from} → ${to}`));
|
|
223
|
+
emit("warn", "model_fallback", `Fallback ${from} → ${to}`, {
|
|
224
|
+
ctx,
|
|
225
|
+
details: error,
|
|
226
|
+
fields: { from, to, error },
|
|
227
|
+
});
|
|
228
|
+
}
|
|
220
229
|
// Usage summary
|
|
221
230
|
export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
|
|
222
231
|
const formatTokens = (count) => {
|
|
@@ -190,11 +190,10 @@ function writeJsonFileIfMissing(path, value, label, created, mode) {
|
|
|
190
190
|
}
|
|
191
191
|
// App-level config files that may hold secrets (DingTalk client secret, provider
|
|
192
192
|
// API keys, Brave key). They are created owner-only, and any pre-existing file with
|
|
193
|
-
// looser bits is tightened on startup.
|
|
194
|
-
// not apply.
|
|
193
|
+
// looser bits is tightened on startup.
|
|
195
194
|
const SECRET_FILE_MODE = 0o600;
|
|
196
195
|
function hardenExistingSecretFile(path) {
|
|
197
|
-
if (
|
|
196
|
+
if (!existsSync(path)) {
|
|
198
197
|
return;
|
|
199
198
|
}
|
|
200
199
|
try {
|
|
@@ -433,6 +432,12 @@ function renderStatus(options) {
|
|
|
433
432
|
try {
|
|
434
433
|
const snapshot = state.runner.getStatusSnapshot();
|
|
435
434
|
lines.push(`- Model: ${snapshot.model}`);
|
|
435
|
+
if (snapshot.fallback) {
|
|
436
|
+
const until = new Date(snapshot.fallback.cooldownUntilMs);
|
|
437
|
+
const hh = String(until.getHours()).padStart(2, "0");
|
|
438
|
+
const mm = String(until.getMinutes()).padStart(2, "0");
|
|
439
|
+
lines.push(`- Fallback: active(primary ${snapshot.fallback.primary} 冷却至 ${hh}:${mm})`);
|
|
440
|
+
}
|
|
436
441
|
if (snapshot.thinkingLevel && snapshot.thinkingLevel !== "off") {
|
|
437
442
|
lines.push(`- Thinking: ${snapshot.thinkingLevel}`);
|
|
438
443
|
}
|
package/dist/sandbox.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { spawn
|
|
1
|
+
import { spawn } from "child_process";
|
|
2
2
|
import { shellEscape } from "./shared/shell-escape.js";
|
|
3
3
|
/**
|
|
4
4
|
* Error raised when sandbox configuration is invalid or the target sandbox is not
|
|
@@ -26,14 +26,6 @@ export function parseSandboxArg(value) {
|
|
|
26
26
|
}
|
|
27
27
|
export async function validateSandbox(config) {
|
|
28
28
|
if (config.type === "host") {
|
|
29
|
-
if (process.platform === "win32") {
|
|
30
|
-
try {
|
|
31
|
-
resolveWindowsHostShell();
|
|
32
|
-
}
|
|
33
|
-
catch (error) {
|
|
34
|
-
throw new SandboxConfigError(error instanceof Error ? error.message : String(error));
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
29
|
return;
|
|
38
30
|
}
|
|
39
31
|
// Check if Docker is available
|
|
@@ -60,7 +52,6 @@ function execSimple(cmd, args) {
|
|
|
60
52
|
return new Promise((resolve, reject) => {
|
|
61
53
|
const child = spawn(cmd, args, {
|
|
62
54
|
stdio: ["ignore", "pipe", "pipe"],
|
|
63
|
-
windowsHide: true,
|
|
64
55
|
});
|
|
65
56
|
let stdout = "";
|
|
66
57
|
let stderr = "";
|
|
@@ -78,51 +69,6 @@ function execSimple(cmd, args) {
|
|
|
78
69
|
});
|
|
79
70
|
});
|
|
80
71
|
}
|
|
81
|
-
const WINDOWS_POSIX_SHELL_CANDIDATES = [
|
|
82
|
-
"bash",
|
|
83
|
-
"sh",
|
|
84
|
-
"C:\\Program Files\\Git\\bin\\bash.exe",
|
|
85
|
-
"C:\\Program Files\\Git\\usr\\bin\\bash.exe",
|
|
86
|
-
"C:\\Program Files (x86)\\Git\\bin\\bash.exe",
|
|
87
|
-
"C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe",
|
|
88
|
-
];
|
|
89
|
-
let cachedWindowsHostShell;
|
|
90
|
-
function looksLikeUnixShellPath(shell) {
|
|
91
|
-
return shell.endsWith("/bash") || shell.endsWith("/sh");
|
|
92
|
-
}
|
|
93
|
-
function isUsablePosixShell(command) {
|
|
94
|
-
const result = spawnSync(command, ["-lc", "printf pipiclaw"], {
|
|
95
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
96
|
-
encoding: "utf-8",
|
|
97
|
-
windowsHide: true,
|
|
98
|
-
});
|
|
99
|
-
return !result.error && result.status === 0 && result.stdout === "pipiclaw";
|
|
100
|
-
}
|
|
101
|
-
function resolveWindowsHostShell() {
|
|
102
|
-
if (cachedWindowsHostShell) {
|
|
103
|
-
return cachedWindowsHostShell;
|
|
104
|
-
}
|
|
105
|
-
const configuredShell = process.env.PIPICLAW_SHELL?.trim();
|
|
106
|
-
const inheritedShell = process.env.SHELL?.trim();
|
|
107
|
-
const shellCandidates = [
|
|
108
|
-
configuredShell,
|
|
109
|
-
inheritedShell && looksLikeUnixShellPath(inheritedShell) ? inheritedShell.split("/").pop() : undefined,
|
|
110
|
-
...WINDOWS_POSIX_SHELL_CANDIDATES,
|
|
111
|
-
].filter((value) => Boolean(value));
|
|
112
|
-
for (const command of shellCandidates) {
|
|
113
|
-
if (isUsablePosixShell(command)) {
|
|
114
|
-
cachedWindowsHostShell = { command, args: ["-lc"] };
|
|
115
|
-
return cachedWindowsHostShell;
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
throw new Error("Windows host sandbox requires a POSIX shell. Install Git Bash and ensure `bash` is on PATH, set `PIPICLAW_SHELL`, or use the Docker sandbox.");
|
|
119
|
-
}
|
|
120
|
-
function resolveHostShell() {
|
|
121
|
-
if (process.platform === "win32") {
|
|
122
|
-
return resolveWindowsHostShell();
|
|
123
|
-
}
|
|
124
|
-
return { command: "sh", args: ["-c"] };
|
|
125
|
-
}
|
|
126
72
|
/**
|
|
127
73
|
* Create an executor that runs commands either on host or in Docker container
|
|
128
74
|
*/
|
|
@@ -135,13 +81,11 @@ export function createExecutor(config) {
|
|
|
135
81
|
class HostExecutor {
|
|
136
82
|
async exec(command, options) {
|
|
137
83
|
return new Promise((resolve, reject) => {
|
|
138
|
-
const shell = resolveHostShell();
|
|
139
84
|
const child = (() => {
|
|
140
85
|
try {
|
|
141
|
-
return spawn(
|
|
86
|
+
return spawn("sh", ["-c", command], {
|
|
142
87
|
detached: true,
|
|
143
88
|
stdio: ["pipe", "pipe", "pipe"],
|
|
144
|
-
windowsHide: true,
|
|
145
89
|
});
|
|
146
90
|
}
|
|
147
91
|
catch (err) {
|
|
@@ -255,29 +199,15 @@ class DockerExecutor {
|
|
|
255
199
|
}
|
|
256
200
|
}
|
|
257
201
|
function killProcessTree(pid) {
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
spawn("taskkill", ["/F", "/T", "/PID", String(pid)], {
|
|
261
|
-
stdio: "ignore",
|
|
262
|
-
detached: true,
|
|
263
|
-
windowsHide: true,
|
|
264
|
-
});
|
|
265
|
-
}
|
|
266
|
-
catch {
|
|
267
|
-
// Ignore errors
|
|
268
|
-
}
|
|
202
|
+
try {
|
|
203
|
+
process.kill(-pid, "SIGKILL");
|
|
269
204
|
}
|
|
270
|
-
|
|
205
|
+
catch {
|
|
271
206
|
try {
|
|
272
|
-
process.kill(
|
|
207
|
+
process.kill(pid, "SIGKILL");
|
|
273
208
|
}
|
|
274
209
|
catch {
|
|
275
|
-
|
|
276
|
-
process.kill(pid, "SIGKILL");
|
|
277
|
-
}
|
|
278
|
-
catch {
|
|
279
|
-
// Process already dead
|
|
280
|
-
}
|
|
210
|
+
// Process already dead
|
|
281
211
|
}
|
|
282
212
|
}
|
|
283
213
|
}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { basename } from "node:path";
|
|
2
|
-
import { isWindowsPlatform } from "./platform.js";
|
|
3
2
|
const WHITESPACE = /\s+/;
|
|
4
3
|
function stripNullAndNormalize(text) {
|
|
5
4
|
return text.replace(/\0/g, "").normalize("NFKC");
|
|
@@ -549,9 +548,6 @@ export function guardCommand(command, config) {
|
|
|
549
548
|
if (!config.enabled) {
|
|
550
549
|
return { allowed: true };
|
|
551
550
|
}
|
|
552
|
-
if (isWindowsPlatform()) {
|
|
553
|
-
return { allowed: true };
|
|
554
|
-
}
|
|
555
551
|
const match = evaluateCommand(command, config, 0);
|
|
556
552
|
if (match) {
|
|
557
553
|
return {
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { existsSync, lstatSync, realpathSync } from "node:fs";
|
|
2
2
|
import { homedir, tmpdir } from "node:os";
|
|
3
3
|
import { basename, dirname, isAbsolute, normalize, resolve } from "node:path";
|
|
4
|
-
import { isWindowsPlatform } from "./platform.js";
|
|
5
4
|
const PRIVATE_KEY_EXTENSIONS = new Set([".pem", ".key", ".p12", ".pfx"]);
|
|
6
5
|
const PRIVATE_KEY_NAME_HINTS = /(id_rsa|id_ed25519|private|secret|credentials)/i;
|
|
7
6
|
const PROC_MEM_PATH = /^\/proc\/\d+\/mem(?:\/|$)/;
|
|
@@ -198,9 +197,6 @@ export function guardPath(rawPath, operation, ctx) {
|
|
|
198
197
|
if (!ctx.config.enabled) {
|
|
199
198
|
return { allowed: true, operation, rawPath };
|
|
200
199
|
}
|
|
201
|
-
if (isWindowsPlatform()) {
|
|
202
|
-
return { allowed: true, operation, rawPath };
|
|
203
|
-
}
|
|
204
200
|
const homeDir = ctx.homeDir ?? homedir();
|
|
205
201
|
const effectiveCtx = {
|
|
206
202
|
...ctx,
|
package/dist/settings.d.ts
CHANGED
|
@@ -112,6 +112,8 @@ export interface PipiclawSettings {
|
|
|
112
112
|
defaultProvider?: string;
|
|
113
113
|
defaultModel?: string;
|
|
114
114
|
defaultThinkingLevel?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
|
|
115
|
+
/** Single backup model reference (`provider/model`) used when the primary model's turn fails. */
|
|
116
|
+
fallbackModel?: string | null;
|
|
115
117
|
compaction?: Partial<PipiclawCompactionSettings>;
|
|
116
118
|
retry?: Partial<PipiclawRetrySettings>;
|
|
117
119
|
memoryRecall?: Partial<PipiclawMemoryRecallSettings>;
|
|
@@ -149,6 +151,11 @@ export declare class PipiclawSettingsManager {
|
|
|
149
151
|
getLoggingSettings(): PipiclawLoggingSettings;
|
|
150
152
|
getRetryEnabled(): boolean;
|
|
151
153
|
setRetryEnabled(enabled: boolean): void;
|
|
154
|
+
/**
|
|
155
|
+
* Backup model reference (`provider/model`) for fallback, or null when unset.
|
|
156
|
+
* Empty / whitespace-only values are treated as unset (fallback disabled).
|
|
157
|
+
*/
|
|
158
|
+
getFallbackModelReference(): string | null;
|
|
152
159
|
getDefaultModel(): string | undefined;
|
|
153
160
|
getDefaultProvider(): string | undefined;
|
|
154
161
|
setDefaultModelAndProvider(provider: string, modelId: string): void;
|
package/dist/settings.js
CHANGED
|
@@ -212,6 +212,18 @@ export class PipiclawSettingsManager {
|
|
|
212
212
|
this.settings.retry = { ...this.settings.retry, enabled };
|
|
213
213
|
this.save();
|
|
214
214
|
}
|
|
215
|
+
/**
|
|
216
|
+
* Backup model reference (`provider/model`) for fallback, or null when unset.
|
|
217
|
+
* Empty / whitespace-only values are treated as unset (fallback disabled).
|
|
218
|
+
*/
|
|
219
|
+
getFallbackModelReference() {
|
|
220
|
+
const raw = this.settings.fallbackModel;
|
|
221
|
+
if (typeof raw !== "string") {
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
const trimmed = raw.trim();
|
|
225
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
226
|
+
}
|
|
215
227
|
getDefaultModel() {
|
|
216
228
|
return this.settings.defaultModel;
|
|
217
229
|
}
|
|
@@ -3,10 +3,3 @@
|
|
|
3
3
|
* Wraps in single quotes and escapes internal single quotes.
|
|
4
4
|
*/
|
|
5
5
|
export declare function shellEscape(s: string): string;
|
|
6
|
-
/**
|
|
7
|
-
* Normalize filesystem paths for POSIX-style shells.
|
|
8
|
-
* On Windows we convert backslashes to forward slashes so Git Bash/MSYS tools
|
|
9
|
-
* can consume the path consistently.
|
|
10
|
-
*/
|
|
11
|
-
export declare function toShellPath(path: string): string;
|
|
12
|
-
export declare function shellEscapePath(path: string): string;
|
|
@@ -5,14 +5,3 @@
|
|
|
5
5
|
export function shellEscape(s) {
|
|
6
6
|
return `'${s.replace(/'/g, "'\\''")}'`;
|
|
7
7
|
}
|
|
8
|
-
/**
|
|
9
|
-
* Normalize filesystem paths for POSIX-style shells.
|
|
10
|
-
* On Windows we convert backslashes to forward slashes so Git Bash/MSYS tools
|
|
11
|
-
* can consume the path consistently.
|
|
12
|
-
*/
|
|
13
|
-
export function toShellPath(path) {
|
|
14
|
-
return process.platform === "win32" ? path.replace(/\\/g, "/") : path;
|
|
15
|
-
}
|
|
16
|
-
export function shellEscapePath(path) {
|
|
17
|
-
return shellEscape(toShellPath(path));
|
|
18
|
-
}
|
package/dist/tools/bash.js
CHANGED
|
@@ -3,7 +3,7 @@ import { Type } from "typebox";
|
|
|
3
3
|
import { guardCommand } from "../security/command-guard.js";
|
|
4
4
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
5
5
|
import { logSecurityEvent } from "../security/logger.js";
|
|
6
|
-
import {
|
|
6
|
+
import { shellEscape } from "../shared/shell-escape.js";
|
|
7
7
|
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail } from "./truncate.js";
|
|
8
8
|
/**
|
|
9
9
|
* Default wall-clock timeout for bash commands when the caller supplies neither a
|
|
@@ -90,7 +90,7 @@ export function createBashTool(executor, options = {}) {
|
|
|
90
90
|
if (totalBytes > DEFAULT_MAX_BYTES) {
|
|
91
91
|
const candidatePath = getSpillFilePath();
|
|
92
92
|
try {
|
|
93
|
-
const spillResult = await executor.exec(`cat > ${
|
|
93
|
+
const spillResult = await executor.exec(`cat > ${shellEscape(candidatePath)}`, {
|
|
94
94
|
signal,
|
|
95
95
|
stdin: output,
|
|
96
96
|
});
|
package/dist/tools/edit.js
CHANGED
|
@@ -3,7 +3,7 @@ import { Type } from "typebox";
|
|
|
3
3
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
4
4
|
import { logSecurityEvent } from "../security/logger.js";
|
|
5
5
|
import { guardPath } from "../security/path-guard.js";
|
|
6
|
-
import {
|
|
6
|
+
import { shellEscape } from "../shared/shell-escape.js";
|
|
7
7
|
import { writeContent } from "./write-content.js";
|
|
8
8
|
/**
|
|
9
9
|
* Generate a unified diff string with line numbers and context
|
|
@@ -126,7 +126,7 @@ export function createEditTool(executor, options = {}) {
|
|
|
126
126
|
}
|
|
127
127
|
}
|
|
128
128
|
// Read the file
|
|
129
|
-
const readResult = await executor.exec(`cat ${
|
|
129
|
+
const readResult = await executor.exec(`cat ${shellEscape(path)}`, { signal });
|
|
130
130
|
if (readResult.code !== 0) {
|
|
131
131
|
throw new Error(readResult.stderr || `File not found: ${path}`);
|
|
132
132
|
}
|
package/dist/tools/read.js
CHANGED
|
@@ -3,7 +3,7 @@ import { Type } from "typebox";
|
|
|
3
3
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
4
4
|
import { logSecurityEvent } from "../security/logger.js";
|
|
5
5
|
import { guardPath } from "../security/path-guard.js";
|
|
6
|
-
import {
|
|
6
|
+
import { shellEscape } from "../shared/shell-escape.js";
|
|
7
7
|
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateHead } from "./truncate.js";
|
|
8
8
|
/**
|
|
9
9
|
* Map of file extensions to MIME types for common image formats
|
|
@@ -76,7 +76,7 @@ export function createReadTool(executor, options = {}) {
|
|
|
76
76
|
const mimeType = isImageFile(path);
|
|
77
77
|
if (mimeType) {
|
|
78
78
|
// Read as image (binary) - use base64
|
|
79
|
-
const result = await executor.exec(`base64 < ${
|
|
79
|
+
const result = await executor.exec(`base64 < ${shellEscape(path)}`, { signal });
|
|
80
80
|
if (result.code !== 0) {
|
|
81
81
|
throw new Error(result.stderr || `Failed to read file: ${path}`);
|
|
82
82
|
}
|
|
@@ -90,7 +90,7 @@ export function createReadTool(executor, options = {}) {
|
|
|
90
90
|
};
|
|
91
91
|
}
|
|
92
92
|
// Get total line count first
|
|
93
|
-
const countResult = await executor.exec(`awk 'END { print NR }' ${
|
|
93
|
+
const countResult = await executor.exec(`awk 'END { print NR }' ${shellEscape(path)}`, { signal });
|
|
94
94
|
if (countResult.code !== 0) {
|
|
95
95
|
throw new Error(countResult.stderr || `Failed to read file: ${path}`);
|
|
96
96
|
}
|
|
@@ -106,10 +106,10 @@ export function createReadTool(executor, options = {}) {
|
|
|
106
106
|
// Read content with offset
|
|
107
107
|
let cmd;
|
|
108
108
|
if (startLine === 1) {
|
|
109
|
-
cmd = `cat ${
|
|
109
|
+
cmd = `cat ${shellEscape(path)}`;
|
|
110
110
|
}
|
|
111
111
|
else {
|
|
112
|
-
cmd = `tail -n +${startLine} ${
|
|
112
|
+
cmd = `tail -n +${startLine} ${shellEscape(path)}`;
|
|
113
113
|
}
|
|
114
114
|
const result = await executor.exec(cmd, { signal });
|
|
115
115
|
if (result.code !== 0) {
|
|
@@ -131,7 +131,7 @@ export function createReadTool(executor, options = {}) {
|
|
|
131
131
|
if (truncation.firstLineExceedsLimit) {
|
|
132
132
|
// First line at offset exceeds 50KB - tell model to use bash
|
|
133
133
|
const firstLineSize = formatSize(Buffer.byteLength(selectedContent.split("\n")[0], "utf-8"));
|
|
134
|
-
outputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${
|
|
134
|
+
outputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${path} | head -c ${DEFAULT_MAX_BYTES}]`;
|
|
135
135
|
details = { truncation };
|
|
136
136
|
}
|
|
137
137
|
else if (truncation.truncated) {
|
|
@@ -2,7 +2,7 @@ import { dirname } from "node:path";
|
|
|
2
2
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
3
3
|
import { logSecurityEvent } from "../security/logger.js";
|
|
4
4
|
import { guardPath } from "../security/path-guard.js";
|
|
5
|
-
import {
|
|
5
|
+
import { shellEscape } from "../shared/shell-escape.js";
|
|
6
6
|
function getDir(path) {
|
|
7
7
|
return dirname(path);
|
|
8
8
|
}
|
|
@@ -42,8 +42,8 @@ export async function writeContent(executor, path, content, signal, options) {
|
|
|
42
42
|
throw new Error(lines.join("\n"));
|
|
43
43
|
}
|
|
44
44
|
}
|
|
45
|
-
const dirPrefix = createParentDir ? `mkdir -p ${
|
|
46
|
-
const result = await executor.exec(`${dirPrefix}cat > ${
|
|
45
|
+
const dirPrefix = createParentDir ? `mkdir -p ${shellEscape(getDir(path))} && ` : "";
|
|
46
|
+
const result = await executor.exec(`${dirPrefix}cat > ${shellEscape(path)}`, {
|
|
47
47
|
signal,
|
|
48
48
|
stdin: content,
|
|
49
49
|
});
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare function isWindowsPlatform(): boolean;
|