@oyasmi/pipiclaw 0.7.0 → 0.7.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.md +1 -0
- package/dist/agent/channel-runner.d.ts +21 -4
- package/dist/agent/channel-runner.js +134 -18
- package/dist/agent/model-fallback.d.ts +64 -0
- package/dist/agent/model-fallback.js +125 -0
- package/dist/agent/run-queue.d.ts +2 -2
- package/dist/agent/runner-factory.d.ts +7 -2
- package/dist/agent/runner-factory.js +18 -6
- package/dist/agent/session-events.d.ts +2 -2
- package/dist/agent/status-render.d.ts +22 -0
- package/dist/agent/status-render.js +61 -0
- package/dist/agent/types.d.ts +9 -4
- package/dist/index.d.ts +2 -1
- package/dist/log.d.ts +7 -0
- package/dist/log.js +46 -24
- package/dist/main.js +15 -2
- package/dist/runtime/bootstrap.d.ts +17 -0
- package/dist/runtime/bootstrap.js +46 -76
- package/dist/runtime/channel-context.d.ts +44 -0
- package/dist/runtime/channel-context.js +15 -0
- package/dist/runtime/delivery.d.ts +3 -2
- package/dist/runtime/dingtalk.d.ts +1 -25
- 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 +20 -0
- package/dist/settings.js +18 -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/dist/tui/app.d.ts +18 -0
- package/dist/tui/app.js +104 -0
- package/dist/tui/cli.d.ts +22 -0
- package/dist/tui/cli.js +116 -0
- package/dist/tui/colors.d.ts +9 -0
- package/dist/tui/colors.js +20 -0
- package/dist/tui/commands.d.ts +47 -0
- package/dist/tui/commands.js +64 -0
- package/dist/tui/pitui-frontend.d.ts +47 -0
- package/dist/tui/pitui-frontend.js +154 -0
- package/dist/tui/plain-frontend.d.ts +23 -0
- package/dist/tui/plain-frontend.js +56 -0
- package/dist/tui/renderer.d.ts +62 -0
- package/dist/tui/renderer.js +13 -0
- package/dist/tui/terminal-context.d.ts +27 -0
- package/dist/tui/terminal-context.js +84 -0
- package/dist/tui/turn-controller.d.ts +68 -0
- package/dist/tui/turn-controller.js +266 -0
- package/package.json +2 -1
- package/dist/security/platform.d.ts +0 -1
- package/dist/security/platform.js +0 -3
package/README.md
CHANGED
|
@@ -16,6 +16,7 @@ npm package: [`@oyasmi/pipiclaw`](https://www.npmjs.com/package/@oyasmi/pipiclaw
|
|
|
16
16
|
## 功能特性(Features)
|
|
17
17
|
|
|
18
18
|
- 原生支持钉钉 Stream Mode,不需要消息中转服务,不需要公网IP
|
|
19
|
+
- 支持终端 TUI:`pipiclaw tui` 直接在命令行对话,复用同一套配置、记忆与会话(见[配置手册](docs/configuration.md)的「终端 TUI」)
|
|
19
20
|
- 支持 AI Card 过程展示,思考、工具执行和状态更新可以持续流式呈现
|
|
20
21
|
- 支持 `/help`、`/new`、`/compact`、`/session`、`/model`
|
|
21
22
|
- 忙碌时可继续接收 `/steer`、`/followup`、`/stop`、`/events`
|
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
|
|
2
|
-
import type {
|
|
2
|
+
import type { ChannelContext } from "../runtime/channel-context.js";
|
|
3
3
|
import type { ChannelStore } from "../runtime/store.js";
|
|
4
4
|
import { type SandboxConfig } from "../sandbox.js";
|
|
5
5
|
import { type BuiltInCommand } from "./commands.js";
|
|
6
|
+
import type { RunnerFactoryPaths } from "./runner-factory.js";
|
|
6
7
|
import { type AgentRunner, type RunnerStatusSnapshot } from "./types.js";
|
|
7
8
|
export declare class ChannelRunner implements AgentRunner {
|
|
8
9
|
private readonly executor;
|
|
9
10
|
private readonly sandboxConfig;
|
|
10
11
|
private readonly channelId;
|
|
11
12
|
private readonly channelDir;
|
|
13
|
+
private readonly appHomeDir;
|
|
14
|
+
private readonly authConfigPath;
|
|
15
|
+
private readonly modelsConfigPath;
|
|
12
16
|
private readonly workspacePath;
|
|
13
17
|
private readonly workspaceDir;
|
|
14
18
|
private session;
|
|
@@ -30,13 +34,15 @@ export declare class ChannelRunner implements AgentRunner {
|
|
|
30
34
|
private firstTurnMemoryBootstrapPending;
|
|
31
35
|
private acceptingBusyMessages;
|
|
32
36
|
private agentLoopStarted;
|
|
37
|
+
/** When the primary model last failed and we switched to the backup. null = on primary. */
|
|
38
|
+
private primaryFailedAt;
|
|
33
39
|
private runState;
|
|
34
|
-
constructor(sandboxConfig: SandboxConfig, channelId: string, channelDir: string);
|
|
35
|
-
run(ctx:
|
|
40
|
+
constructor(sandboxConfig: SandboxConfig, channelId: string, channelDir: string, paths: RunnerFactoryPaths);
|
|
41
|
+
run(ctx: ChannelContext, store: ChannelStore): Promise<{
|
|
36
42
|
stopReason: string;
|
|
37
43
|
errorMessage?: string;
|
|
38
44
|
}>;
|
|
39
|
-
handleBuiltinCommand(ctx:
|
|
45
|
+
handleBuiltinCommand(ctx: ChannelContext, command: BuiltInCommand): Promise<void>;
|
|
40
46
|
queueSteer(text: string, userName?: string): Promise<void>;
|
|
41
47
|
flushMemoryForShutdown(): Promise<void>;
|
|
42
48
|
getMemoryMaintenanceContext(): Promise<MemoryMaintenanceRuntimeContext>;
|
|
@@ -50,6 +56,17 @@ export declare class ChannelRunner implements AgentRunner {
|
|
|
50
56
|
private queueBusyMessage;
|
|
51
57
|
private resetRunState;
|
|
52
58
|
private refreshSessionResources;
|
|
59
|
+
/**
|
|
60
|
+
* At turn start, if a fallback is active and the primary's cooldown has elapsed,
|
|
61
|
+
* switch back to the preferred model. Silent — no user notice on recovery.
|
|
62
|
+
*/
|
|
63
|
+
private maybeRestorePrimaryModel;
|
|
64
|
+
/**
|
|
65
|
+
* Resolve the configured backup model reference against available models.
|
|
66
|
+
* Returns null when unset, unresolvable/ambiguous, or missing an API key —
|
|
67
|
+
* each case logs a warning and disables fallback for this turn.
|
|
68
|
+
*/
|
|
69
|
+
private resolveFallbackModel;
|
|
53
70
|
private initializeSession;
|
|
54
71
|
private reloadSessionResources;
|
|
55
72
|
private bindSessionExtensions;
|
|
@@ -10,8 +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";
|
|
14
|
-
import { APP_HOME_DIR, AUTH_CONFIG_PATH, MODELS_CONFIG_PATH } from "../paths.js";
|
|
13
|
+
import { findExactModelReferenceMatch, formatModelReference, resolveInitialModel } from "../models/utils.js";
|
|
15
14
|
import { createExecutor } from "../sandbox.js";
|
|
16
15
|
import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
|
|
17
16
|
import { PipiclawSettingsManager } from "../settings.js";
|
|
@@ -26,7 +25,8 @@ import { getUsageLedger } from "../usage/ledger.js";
|
|
|
26
25
|
import { createCommandExtension } from "./command-extension.js";
|
|
27
26
|
import { renderBuiltInHelp } from "./commands.js";
|
|
28
27
|
import { estimateIncomingMessageTokens, getPreventiveCompactionDecision } from "./context-budget.js";
|
|
29
|
-
import {
|
|
28
|
+
import { PRIMARY_COOLDOWN_MS, runPromptWithFallback, shouldRestorePrimary, } from "./model-fallback.js";
|
|
29
|
+
import { clipUserInput, formatProgressEntry } from "./progress-formatter.js";
|
|
30
30
|
import { buildAppendSystemPrompt } from "./prompt-builder.js";
|
|
31
31
|
import { createRunQueue } from "./run-queue.js";
|
|
32
32
|
import { handleSessionEvent } from "./session-events.js";
|
|
@@ -53,17 +53,22 @@ function asSdkSettingsManager(manager) {
|
|
|
53
53
|
return manager;
|
|
54
54
|
}
|
|
55
55
|
export class ChannelRunner {
|
|
56
|
-
constructor(sandboxConfig, channelId, channelDir) {
|
|
56
|
+
constructor(sandboxConfig, channelId, channelDir, paths) {
|
|
57
57
|
this.ledger = getUsageLedger();
|
|
58
58
|
this.currentTools = [];
|
|
59
59
|
this.firstTurnMemoryBootstrapPending = true;
|
|
60
60
|
this.acceptingBusyMessages = false;
|
|
61
61
|
this.agentLoopStarted = false;
|
|
62
|
+
/** When the primary model last failed and we switched to the backup. null = on primary. */
|
|
63
|
+
this.primaryFailedAt = null;
|
|
62
64
|
// --- Per run ---
|
|
63
65
|
this.runState = createEmptyRunState();
|
|
64
66
|
this.sandboxConfig = sandboxConfig;
|
|
65
67
|
this.channelId = channelId;
|
|
66
68
|
this.channelDir = channelDir;
|
|
69
|
+
this.appHomeDir = paths.appHomeDir;
|
|
70
|
+
this.authConfigPath = paths.authConfigPath;
|
|
71
|
+
this.modelsConfigPath = paths.modelsConfigPath;
|
|
67
72
|
const executor = createExecutor(sandboxConfig);
|
|
68
73
|
this.executor = executor;
|
|
69
74
|
this.workspaceDir = resolve(dirname(channelDir));
|
|
@@ -74,12 +79,12 @@ export class ChannelRunner {
|
|
|
74
79
|
// Create session manager
|
|
75
80
|
const contextFile = join(channelDir, "context.jsonl");
|
|
76
81
|
this.sessionManager = SessionManager.open(contextFile, channelDir);
|
|
77
|
-
this.settingsManager = new PipiclawSettingsManager(
|
|
82
|
+
this.settingsManager = new PipiclawSettingsManager(this.appHomeDir);
|
|
78
83
|
this.reportSettingsDiagnostics();
|
|
79
84
|
this.memoryCandidateStore = createMemoryCandidateStore();
|
|
80
85
|
// Create AuthStorage and ModelRegistry
|
|
81
|
-
const authStorage = AuthStorage.create(
|
|
82
|
-
this.modelRegistry = createModelRegistry(authStorage,
|
|
86
|
+
const authStorage = AuthStorage.create(this.authConfigPath);
|
|
87
|
+
this.modelRegistry = createModelRegistry(authStorage, this.modelsConfigPath);
|
|
83
88
|
// Resolve model: prefer saved global default, fall back to first available model
|
|
84
89
|
this.activeModel = resolveInitialModel(this.modelRegistry, this.settingsManager);
|
|
85
90
|
log.logInfo(`Using model: ${this.activeModel.provider}/${this.activeModel.id} (${this.activeModel.name})`);
|
|
@@ -150,8 +155,11 @@ export class ChannelRunner {
|
|
|
150
155
|
const runQueue = createRunQueue(ctx);
|
|
151
156
|
this.runState.queue = runQueue.queue;
|
|
152
157
|
let promptSubmitted = false;
|
|
158
|
+
let fallbackAttempted = false;
|
|
159
|
+
let fallbackTargetRef;
|
|
153
160
|
try {
|
|
154
161
|
await this.ensureSessionReady();
|
|
162
|
+
await this.maybeRestorePrimaryModel();
|
|
155
163
|
this.memoryLifecycle.noteUserTurnStarted();
|
|
156
164
|
const normalizedInputLength = ctx.message.text.replace(/\r/g, "").trim().length;
|
|
157
165
|
if (normalizedInputLength > MAX_USER_MESSAGE_CHARS) {
|
|
@@ -207,10 +215,58 @@ export class ChannelRunner {
|
|
|
207
215
|
};
|
|
208
216
|
await writeFile(join(this.channelDir, "last_prompt.json"), JSON.stringify(debugContext, null, 2));
|
|
209
217
|
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
218
|
+
const fallbackDeps = {
|
|
219
|
+
prompt: async (text) => {
|
|
220
|
+
try {
|
|
221
|
+
await this.sessionResourceGate.runPrompt(async () => {
|
|
222
|
+
await this.session.prompt(text);
|
|
223
|
+
promptSubmitted = true;
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
catch (err) {
|
|
227
|
+
this.runState.stopReason = "error";
|
|
228
|
+
this.runState.errorMessage = err instanceof Error ? err.message : String(err);
|
|
229
|
+
log.logWarning(`[${this.channelId}] Runner failed`, this.runState.errorMessage);
|
|
230
|
+
}
|
|
231
|
+
},
|
|
232
|
+
getRunError: () => ({
|
|
233
|
+
stopReason: this.runState.stopReason,
|
|
234
|
+
errorMessage: this.runState.errorMessage,
|
|
235
|
+
}),
|
|
236
|
+
resetRunError: () => {
|
|
237
|
+
this.runState.stopReason = "stop";
|
|
238
|
+
this.runState.errorMessage = undefined;
|
|
239
|
+
this.runState.finalOutcome = { kind: "none" };
|
|
240
|
+
this.runState.lastCompactionError = undefined;
|
|
241
|
+
},
|
|
242
|
+
getMessages: () => this.agent.state.messages,
|
|
243
|
+
setMessages: (messages) => {
|
|
244
|
+
this.agent.state.messages = messages;
|
|
245
|
+
},
|
|
246
|
+
promptWasSubmitted: () => promptSubmitted,
|
|
247
|
+
getCurrentModelRef: () => formatModelReference(this.session.model ?? this.activeModel),
|
|
248
|
+
resolveFallbackModel: () => this.resolveFallbackModel(),
|
|
249
|
+
setModel: async (model) => {
|
|
250
|
+
await this.session.setModel(model);
|
|
251
|
+
},
|
|
252
|
+
notifySwitch: (from, to, errorSummary) => {
|
|
253
|
+
fallbackTargetRef = to;
|
|
254
|
+
if (this.runState.logCtx) {
|
|
255
|
+
log.logModelFallback(this.runState.logCtx, from, to, errorSummary);
|
|
256
|
+
}
|
|
257
|
+
const text = `⚠️ 模型 ${from} 出错(${errorSummary}),切换到 ${to} 重试…`;
|
|
258
|
+
if (ctx.progressStyle !== "none") {
|
|
259
|
+
runQueue.queue.enqueue(() => ctx.respond(formatProgressEntry("error", text), false), "fallback switch");
|
|
260
|
+
}
|
|
261
|
+
else {
|
|
262
|
+
runQueue.queue.enqueue(() => ctx.respondInThread(text), "fallback switch");
|
|
263
|
+
}
|
|
264
|
+
},
|
|
265
|
+
markPrimaryFailed: () => {
|
|
266
|
+
this.primaryFailedAt = Date.now();
|
|
267
|
+
},
|
|
268
|
+
};
|
|
269
|
+
fallbackAttempted = await runPromptWithFallback(promptText, fallbackDeps);
|
|
214
270
|
}
|
|
215
271
|
catch (err) {
|
|
216
272
|
this.runState.stopReason = "error";
|
|
@@ -248,6 +304,9 @@ export class ChannelRunner {
|
|
|
248
304
|
if (compactionSummary) {
|
|
249
305
|
detailLines.push(`Recovery: \`${compactionSummary}\``);
|
|
250
306
|
}
|
|
307
|
+
if (fallbackAttempted && fallbackTargetRef) {
|
|
308
|
+
detailLines.push(`已切换备用模型 \`${fallbackTargetRef}\` 重试,仍失败。`);
|
|
309
|
+
}
|
|
251
310
|
await ctx.replaceMessage(`_Sorry, something went wrong._\n\n${detailLines.join("\n\n")}`);
|
|
252
311
|
}
|
|
253
312
|
catch (err) {
|
|
@@ -390,11 +449,18 @@ export class ChannelRunner {
|
|
|
390
449
|
getStatusSnapshot() {
|
|
391
450
|
const model = this.session.model ?? this.activeModel;
|
|
392
451
|
const contextTokens = this.session.getContextUsage()?.tokens;
|
|
452
|
+
const fallbackActive = formatModelReference(model) !== formatModelReference(this.activeModel);
|
|
393
453
|
return {
|
|
394
454
|
model: formatModelReference(model),
|
|
395
455
|
contextTokens: typeof contextTokens === "number" ? contextTokens : undefined,
|
|
396
456
|
contextWindow: model.contextWindow || 200000,
|
|
397
457
|
thinkingLevel: this.session.thinkingLevel,
|
|
458
|
+
fallback: fallbackActive
|
|
459
|
+
? {
|
|
460
|
+
primary: formatModelReference(this.activeModel),
|
|
461
|
+
cooldownUntilMs: (this.primaryFailedAt ?? Date.now()) + PRIMARY_COOLDOWN_MS,
|
|
462
|
+
}
|
|
463
|
+
: undefined,
|
|
398
464
|
};
|
|
399
465
|
}
|
|
400
466
|
async abort() {
|
|
@@ -415,7 +481,7 @@ export class ChannelRunner {
|
|
|
415
481
|
? new Date(eventTime + Math.max(0, maintenanceSettings.minIdleMinutesBeforeLlmWork) * 60_000).toISOString()
|
|
416
482
|
: undefined;
|
|
417
483
|
try {
|
|
418
|
-
await updateMemoryMaintenanceState(
|
|
484
|
+
await updateMemoryMaintenanceState(this.appHomeDir, this.channelId, (state) => applyMemoryActivityToState(state, {
|
|
419
485
|
...event,
|
|
420
486
|
eligibleAfter,
|
|
421
487
|
}));
|
|
@@ -486,6 +552,54 @@ export class ChannelRunner {
|
|
|
486
552
|
await this.ensureSessionReady();
|
|
487
553
|
await this.sessionResourceGate.requestRefresh();
|
|
488
554
|
}
|
|
555
|
+
/**
|
|
556
|
+
* At turn start, if a fallback is active and the primary's cooldown has elapsed,
|
|
557
|
+
* switch back to the preferred model. Silent — no user notice on recovery.
|
|
558
|
+
*/
|
|
559
|
+
async maybeRestorePrimaryModel() {
|
|
560
|
+
const current = this.session.model;
|
|
561
|
+
if (!current || formatModelReference(current) === formatModelReference(this.activeModel)) {
|
|
562
|
+
this.primaryFailedAt = null;
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
if (!shouldRestorePrimary(this.primaryFailedAt, Date.now())) {
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
try {
|
|
569
|
+
await this.session.setModel(this.activeModel);
|
|
570
|
+
this.primaryFailedAt = null;
|
|
571
|
+
log.logInfo(`[${this.channelId}] Restored primary model ${formatModelReference(this.activeModel)}`);
|
|
572
|
+
}
|
|
573
|
+
catch (err) {
|
|
574
|
+
log.logWarning(`[${this.channelId}] Failed to restore primary model`, err instanceof Error ? err.message : String(err));
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
/**
|
|
578
|
+
* Resolve the configured backup model reference against available models.
|
|
579
|
+
* Returns null when unset, unresolvable/ambiguous, or missing an API key —
|
|
580
|
+
* each case logs a warning and disables fallback for this turn.
|
|
581
|
+
*/
|
|
582
|
+
async resolveFallbackModel() {
|
|
583
|
+
const reference = this.settingsManager.getFallbackModelReference();
|
|
584
|
+
if (!reference) {
|
|
585
|
+
return null;
|
|
586
|
+
}
|
|
587
|
+
this.modelRegistry.refresh();
|
|
588
|
+
const available = await this.modelRegistry.getAvailable();
|
|
589
|
+
const { match, ambiguous } = findExactModelReferenceMatch(reference, available);
|
|
590
|
+
if (!match) {
|
|
591
|
+
log.logWarning(`[${this.channelId}] fallbackModel "${reference}" ${ambiguous ? "is ambiguous" : "not found"}; skipping fallback`);
|
|
592
|
+
return null;
|
|
593
|
+
}
|
|
594
|
+
try {
|
|
595
|
+
await getApiKeyForModel(this.modelRegistry, match);
|
|
596
|
+
}
|
|
597
|
+
catch {
|
|
598
|
+
log.logWarning(`[${this.channelId}] fallbackModel "${reference}" has no API key; skipping fallback`);
|
|
599
|
+
return null;
|
|
600
|
+
}
|
|
601
|
+
return match;
|
|
602
|
+
}
|
|
489
603
|
async initializeSession() {
|
|
490
604
|
await this.reloadSessionResources();
|
|
491
605
|
await this.bindSessionExtensions();
|
|
@@ -557,7 +671,7 @@ export class ChannelRunner {
|
|
|
557
671
|
}
|
|
558
672
|
reportSettingsDiagnostics() {
|
|
559
673
|
for (const { scope, error } of this.settingsManager.drainErrors()) {
|
|
560
|
-
log.logWarning(`[${this.channelId}] Failed to load ${scope} settings`, `${error.message}\n${join(
|
|
674
|
+
log.logWarning(`[${this.channelId}] Failed to load ${scope} settings`, `${error.message}\n${join(this.appHomeDir, "settings.json")}`);
|
|
561
675
|
}
|
|
562
676
|
}
|
|
563
677
|
reportConfigDiagnostics(diagnostics) {
|
|
@@ -568,7 +682,7 @@ export class ChannelRunner {
|
|
|
568
682
|
createResourceLoader() {
|
|
569
683
|
return new DefaultResourceLoader({
|
|
570
684
|
cwd: process.cwd(),
|
|
571
|
-
agentDir:
|
|
685
|
+
agentDir: this.appHomeDir,
|
|
572
686
|
settingsManager: asSdkSettingsManager(this.settingsManager),
|
|
573
687
|
extensionFactories: [
|
|
574
688
|
this.memoryLifecycle.createExtensionFactory(),
|
|
@@ -584,6 +698,8 @@ export class ChannelRunner {
|
|
|
584
698
|
switchModel: async (model) => {
|
|
585
699
|
await this.session.setModel(model);
|
|
586
700
|
this.activeModel = model;
|
|
701
|
+
// Manual /model switch redefines the preferred model and clears fallback state.
|
|
702
|
+
this.primaryFailedAt = null;
|
|
587
703
|
},
|
|
588
704
|
refreshSessionResources: async () => {
|
|
589
705
|
await this.refreshSessionResources();
|
|
@@ -621,8 +737,8 @@ export class ChannelRunner {
|
|
|
621
737
|
createAgentSessionServices(resourceLoader) {
|
|
622
738
|
return {
|
|
623
739
|
cwd: process.cwd(),
|
|
624
|
-
agentDir:
|
|
625
|
-
authStorage: AuthStorage.create(
|
|
740
|
+
agentDir: this.appHomeDir,
|
|
741
|
+
authStorage: AuthStorage.create(this.authConfigPath),
|
|
626
742
|
settingsManager: asSdkSettingsManager(this.settingsManager),
|
|
627
743
|
modelRegistry: this.modelRegistry,
|
|
628
744
|
resourceLoader,
|
|
@@ -662,8 +778,8 @@ export class ChannelRunner {
|
|
|
662
778
|
return { agent, session, resourceLoader };
|
|
663
779
|
}
|
|
664
780
|
buildRuntimeTools() {
|
|
665
|
-
const securityLoad = loadSecurityConfigWithDiagnostics(
|
|
666
|
-
const toolsLoad = loadToolsConfigWithDiagnostics(
|
|
781
|
+
const securityLoad = loadSecurityConfigWithDiagnostics(this.appHomeDir);
|
|
782
|
+
const toolsLoad = loadToolsConfigWithDiagnostics(this.appHomeDir);
|
|
667
783
|
this.reportConfigDiagnostics([...securityLoad.diagnostics, ...toolsLoad.diagnostics]);
|
|
668
784
|
const tools = createPipiclawTools({
|
|
669
785
|
executor: this.executor,
|
|
@@ -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
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { ChannelContext } from "../runtime/channel-context.js";
|
|
2
2
|
import type { RunQueue } from "./types.js";
|
|
3
3
|
export interface CreatedRunQueue {
|
|
4
4
|
queue: RunQueue;
|
|
5
5
|
drain: () => Promise<void>;
|
|
6
6
|
}
|
|
7
|
-
export declare function createRunQueue(ctx:
|
|
7
|
+
export declare function createRunQueue(ctx: ChannelContext): CreatedRunQueue;
|
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
import type { SandboxConfig } from "../sandbox.js";
|
|
2
2
|
import type { AgentRunner } from "./types.js";
|
|
3
|
-
export
|
|
4
|
-
|
|
3
|
+
export interface RunnerFactoryPaths {
|
|
4
|
+
appHomeDir: string;
|
|
5
|
+
authConfigPath: string;
|
|
6
|
+
modelsConfigPath: string;
|
|
7
|
+
}
|
|
8
|
+
export declare function getOrCreateRunner(sandboxConfig: SandboxConfig, channelId: string, channelDir: string, paths: RunnerFactoryPaths): AgentRunner;
|
|
9
|
+
export declare function resetRunner(channelId: string, paths?: RunnerFactoryPaths, channelDir?: string): void;
|
|
@@ -1,13 +1,25 @@
|
|
|
1
1
|
import { ChannelRunner } from "./channel-runner.js";
|
|
2
2
|
const channelRunners = new Map();
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
function runnerKey(paths, channelId, channelDir) {
|
|
4
|
+
return `${paths.appHomeDir}\0${channelDir}\0${channelId}`;
|
|
5
|
+
}
|
|
6
|
+
export function getOrCreateRunner(sandboxConfig, channelId, channelDir, paths) {
|
|
7
|
+
const key = runnerKey(paths, channelId, channelDir);
|
|
8
|
+
const existing = channelRunners.get(key);
|
|
5
9
|
if (existing)
|
|
6
10
|
return existing;
|
|
7
|
-
const runner = new ChannelRunner(sandboxConfig, channelId, channelDir);
|
|
8
|
-
channelRunners.set(
|
|
11
|
+
const runner = new ChannelRunner(sandboxConfig, channelId, channelDir, paths);
|
|
12
|
+
channelRunners.set(key, runner);
|
|
9
13
|
return runner;
|
|
10
14
|
}
|
|
11
|
-
export function resetRunner(channelId) {
|
|
12
|
-
|
|
15
|
+
export function resetRunner(channelId, paths, channelDir) {
|
|
16
|
+
if (paths && channelDir) {
|
|
17
|
+
channelRunners.delete(runnerKey(paths, channelId, channelDir));
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
for (const key of channelRunners.keys()) {
|
|
21
|
+
if (key.endsWith(`\0${channelId}`)) {
|
|
22
|
+
channelRunners.delete(key);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
13
25
|
}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import type { MemoryLifecycle } from "../memory/lifecycle.js";
|
|
2
|
-
import type {
|
|
2
|
+
import type { ChannelContext } from "../runtime/channel-context.js";
|
|
3
3
|
import type { ChannelStore } from "../runtime/store.js";
|
|
4
4
|
import type { UsageLedger } from "../usage/ledger.js";
|
|
5
5
|
import type { PendingTool, RunLogContext, RunQueue, RunState } from "./types.js";
|
|
6
6
|
export interface SessionEventHandlerContext {
|
|
7
|
-
ctx:
|
|
7
|
+
ctx: ChannelContext;
|
|
8
8
|
logCtx: RunLogContext;
|
|
9
9
|
queue: RunQueue;
|
|
10
10
|
pendingTools: Map<string, PendingTool>;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/status` rendering. Extracted verbatim from `runtime/bootstrap.ts` so both
|
|
3
|
+
* the DingTalk runtime and the terminal TUI can render the same status block
|
|
4
|
+
* from an `AgentRunner` status snapshot. Pure functions, no side effects.
|
|
5
|
+
*/
|
|
6
|
+
import type { SandboxConfig } from "../sandbox.js";
|
|
7
|
+
import type { AgentRunner } from "./types.js";
|
|
8
|
+
/** Minimal per-channel run state the status renderer needs. */
|
|
9
|
+
export interface StatusRenderState {
|
|
10
|
+
running: boolean;
|
|
11
|
+
currentTaskText?: string;
|
|
12
|
+
runner: Pick<AgentRunner, "getStatusSnapshot">;
|
|
13
|
+
}
|
|
14
|
+
export interface RenderStatusOptions {
|
|
15
|
+
state: StatusRenderState | undefined;
|
|
16
|
+
version: string;
|
|
17
|
+
uptimeMs: number;
|
|
18
|
+
sandbox: SandboxConfig;
|
|
19
|
+
}
|
|
20
|
+
export declare function formatTokenCount(count: number): string;
|
|
21
|
+
export declare function formatUptime(ms: number): string;
|
|
22
|
+
export declare function renderStatus(options: RenderStatusOptions): string;
|