@oyasmi/pipiclaw 0.9.3 → 0.9.4-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/builtin-commands.d.ts +19 -0
- package/dist/agent/builtin-commands.js +80 -0
- package/dist/agent/channel-runner.d.ts +20 -208
- package/dist/agent/channel-runner.js +167 -1188
- package/dist/agent/maintenance-context.d.ts +1 -1
- package/dist/agent/maintenance-context.js +1 -1
- package/dist/agent/prompt/manifest.d.ts +6 -1
- package/dist/agent/prompt/manifest.js +45 -64
- package/dist/agent/prompt/resources.d.ts +3 -0
- package/dist/agent/prompt/resources.js +11 -2
- package/dist/agent/runner-factory.d.ts +1 -43
- package/dist/agent/{command-extension.d.ts → session/command-extension.d.ts} +4 -0
- package/dist/agent/{command-extension.js → session/command-extension.js} +48 -35
- package/dist/agent/{type-guards.d.ts → session/event-guards.d.ts} +2 -2
- package/dist/agent/{type-guards.js → session/event-guards.js} +5 -1
- package/dist/agent/session/model-selection.d.ts +47 -0
- package/dist/agent/session/model-selection.js +99 -0
- package/dist/agent/{session-adapter.d.ts → session/session-adapter.d.ts} +21 -1
- package/dist/agent/session/session-adapter.js +159 -0
- package/dist/agent/{session-events.d.ts → session/session-events.d.ts} +9 -5
- package/dist/agent/{session-events.js → session/session-events.js} +24 -13
- package/dist/agent/session/session-host.d.ts +200 -0
- package/dist/agent/session/session-host.js +621 -0
- package/dist/agent/{session-resource-gate.js → session/session-resource-gate.js} +5 -3
- package/dist/agent/status-render.d.ts +0 -1
- package/dist/agent/status-render.js +4 -16
- package/dist/agent/{context-budget.js → turn/context-budget.js} +5 -1
- package/dist/agent/{progress-formatter.d.ts → turn/progress-formatter.d.ts} +4 -1
- package/dist/agent/{run-queue.d.ts → turn/run-queue.d.ts} +1 -1
- package/dist/agent/{run-queue.js → turn/run-queue.js} +10 -5
- package/dist/{memory → agent/turn}/task-digest.js +4 -4
- package/dist/agent/turn/turn-context.d.ts +14 -0
- package/dist/agent/turn/turn-context.js +64 -0
- package/dist/agent/turn/turn-error.d.ts +31 -0
- package/dist/agent/turn/turn-error.js +68 -0
- package/dist/agent/turn/turn-finish.d.ts +50 -0
- package/dist/agent/turn/turn-finish.js +188 -0
- package/dist/agent/turn/turn-input.d.ts +43 -0
- package/dist/agent/turn/turn-input.js +79 -0
- package/dist/agent/turn/turn-pipeline.d.ts +68 -0
- package/dist/agent/turn/turn-pipeline.js +257 -0
- package/dist/agent/{turn-prompt.d.ts → turn/turn-prompt.d.ts} +2 -2
- package/dist/agent/{turn-prompt.js → turn/turn-prompt.js} +6 -2
- package/dist/agent/{turn-recovery.js → turn/turn-recovery.js} +1 -1
- package/dist/agent/{turn-state.d.ts → turn/turn-state.d.ts} +1 -1
- package/dist/agent/types.d.ts +43 -2
- package/dist/agent/types.js +1 -1
- package/dist/{models/auth-cli.d.ts → app/auth-command.d.ts} +1 -1
- package/dist/{models/auth-cli.js → app/auth-command.js} +14 -10
- package/dist/{runtime/app-home.d.ts → app/home.d.ts} +6 -2
- package/dist/{runtime/app-home.js → app/home.js} +22 -75
- package/dist/{runtime → app}/proxy.js +4 -2
- package/dist/{app-services.d.ts → app/services.d.ts} +5 -5
- package/dist/{app-services.js → app/services.js} +17 -14
- package/dist/channel/channel-context.d.ts +12 -2
- package/dist/channel/channel-context.js +29 -2
- package/dist/channel/channel-event.d.ts +10 -2
- package/dist/channel/channel-event.js +1 -1
- package/dist/channel/channel-index.js +4 -1
- package/dist/{runtime/project-commands.d.ts → channel/commands.d.ts} +1 -1
- package/dist/{runtime/project-commands.js → channel/commands.js} +17 -16
- package/dist/channel/project-scope-store.js +1 -1
- package/dist/channel/store.js +4 -0
- package/dist/commands/catalog.d.ts +24 -7
- package/dist/commands/catalog.js +91 -44
- package/dist/commands/reply-limits.d.ts +6 -0
- package/dist/commands/reply-limits.js +24 -0
- package/dist/{runtime/report-commands.d.ts → commands/router.d.ts} +10 -3
- package/dist/{runtime/report-commands.js → commands/router.js} +6 -6
- package/dist/{settings.d.ts → config/settings.d.ts} +10 -10
- package/dist/{settings.js → config/settings.js} +11 -11
- package/dist/{tools/config.d.ts → config/tools.d.ts} +1 -2
- package/dist/{tools/config.js → config/tools.js} +5 -2
- package/dist/dingtalk/access-token.d.ts +12 -0
- package/dist/dingtalk/access-token.js +51 -0
- package/dist/dingtalk/api.d.ts +19 -0
- package/dist/dingtalk/api.js +67 -0
- package/dist/dingtalk/bot.d.ts +97 -0
- package/dist/dingtalk/bot.js +389 -0
- package/dist/dingtalk/cards.d.ts +56 -0
- package/dist/dingtalk/cards.js +318 -0
- package/dist/{runtime → dingtalk}/channel-queue.js +4 -1
- package/dist/dingtalk/config.d.ts +19 -0
- package/dist/dingtalk/config.js +95 -0
- package/dist/dingtalk/connection.d.ts +57 -0
- package/dist/dingtalk/connection.js +356 -0
- package/dist/dingtalk/conversation-meta.d.ts +16 -0
- package/dist/dingtalk/conversation-meta.js +77 -0
- package/dist/{runtime → dingtalk}/delivery.d.ts +6 -2
- package/dist/{runtime → dingtalk}/delivery.js +29 -15
- package/dist/dingtalk/handler.d.ts +90 -0
- package/dist/dingtalk/handler.js +1 -0
- package/dist/dingtalk/inbound.d.ts +66 -0
- package/dist/dingtalk/inbound.js +137 -0
- package/dist/dingtalk/media.d.ts +66 -0
- package/dist/dingtalk/media.js +214 -0
- package/dist/events/{event-commands.js → commands.js} +99 -45
- package/dist/events/parse.d.ts +14 -0
- package/dist/events/parse.js +114 -0
- package/dist/events/types.d.ts +93 -0
- package/dist/events/types.js +1 -0
- package/dist/events/{event-validation.d.ts → validation.d.ts} +14 -3
- package/dist/events/{event-validation.js → validation.js} +17 -9
- package/dist/events/watcher.d.ts +67 -0
- package/dist/events/{events.js → watcher.js} +63 -121
- package/dist/executor.js +2 -2
- package/dist/index.d.ts +6 -4
- package/dist/index.js +2 -2
- package/dist/jobs/launch.d.ts +42 -0
- package/dist/jobs/launch.js +118 -0
- package/dist/{agent/job-manager.d.ts → jobs/manager.d.ts} +1 -67
- package/dist/{agent/job-manager.js → jobs/manager.js} +34 -157
- package/dist/jobs/record.d.ts +55 -0
- package/dist/jobs/record.js +36 -0
- package/dist/log.d.ts +12 -2
- package/dist/log.js +26 -34
- package/dist/main.js +3 -3
- package/dist/memory/commands.js +29 -23
- package/dist/memory/lifecycle.js +26 -5
- package/dist/memory/maintenance-gates.d.ts +2 -2
- package/dist/memory/maintenance-state.js +4 -1
- package/dist/memory/maintenance-tuning.d.ts +15 -0
- package/dist/memory/maintenance-tuning.js +3 -0
- package/dist/memory/reflect-job.d.ts +2 -2
- package/dist/memory/reflect-job.js +4 -2
- package/dist/memory/scheduler.d.ts +3 -3
- package/dist/memory/scheduler.js +5 -2
- package/dist/memory/sidecar-worker.js +1 -1
- package/dist/memory/transcript.js +1 -1
- package/dist/{agent/model-fallback.d.ts → models/fallback.d.ts} +6 -6
- package/dist/{agent/model-fallback.js → models/fallback.js} +15 -28
- package/dist/models/login-identity.d.ts +2 -0
- package/dist/models/login-identity.js +83 -0
- package/dist/models/provider-login.d.ts +3 -1
- package/dist/models/provider-login.js +8 -2
- package/dist/models/reference.d.ts +20 -0
- package/dist/models/{utils.js → reference.js} +0 -48
- package/dist/models/{utils.d.ts → runtime.d.ts} +1 -16
- package/dist/models/runtime.js +52 -0
- package/dist/paths.d.ts +2 -0
- package/dist/paths.js +9 -0
- package/dist/playbooks/agent-delegation.md +2 -2
- package/dist/playbooks/catalog.d.ts +6 -2
- package/dist/playbooks/catalog.js +9 -6
- package/dist/runtime/bootstrap.d.ts +7 -17
- package/dist/runtime/bootstrap.js +70 -659
- package/dist/runtime/durable-dispatch.d.ts +43 -4
- package/dist/runtime/durable-dispatch.js +153 -3
- package/dist/runtime/inbound-images.d.ts +18 -0
- package/dist/runtime/inbound-images.js +51 -0
- package/dist/runtime/shutdown.d.ts +39 -0
- package/dist/runtime/shutdown.js +120 -0
- package/dist/runtime/stop-watchdog.d.ts +16 -0
- package/dist/runtime/stop-watchdog.js +32 -0
- package/dist/runtime/task-driver.d.ts +6 -4
- package/dist/runtime/task-driver.js +58 -23
- package/dist/runtime/task-migration.js +25 -8
- package/dist/runtime/task-spawn.d.ts +1 -1
- package/dist/runtime/task-spawn.js +13 -6
- package/dist/runtime/turn-handler.d.ts +47 -0
- package/dist/runtime/turn-handler.js +318 -0
- package/dist/runtime/turn-run.d.ts +52 -0
- package/dist/runtime/turn-run.js +318 -0
- package/dist/runtime/wake-coalescing.d.ts +18 -0
- package/dist/runtime/wake-coalescing.js +29 -0
- package/dist/security/block-message.d.ts +22 -1
- package/dist/security/block-message.js +66 -1
- package/dist/security/command-guard.js +4 -0
- package/dist/security/network.d.ts +2 -1
- package/dist/security/network.js +7 -2
- package/dist/security/path-guard-check.js +2 -2
- package/dist/security/path-guard.js +4 -0
- package/dist/security/types.d.ts +1 -2
- package/dist/security/types.js +1 -2
- package/dist/shared/exact-keys.d.ts +1 -1
- package/dist/shared/format.d.ts +12 -0
- package/dist/shared/format.js +37 -0
- package/dist/shared/host-process.js +16 -4
- package/dist/shared/wake-claim.d.ts +1 -1
- package/dist/shared/with-timeout.d.ts +3 -2
- package/dist/shared/with-timeout.js +14 -3
- package/dist/{runtime/skill-commands.d.ts → skills/commands.d.ts} +2 -2
- package/dist/{runtime/skill-commands.js → skills/commands.js} +18 -11
- package/dist/{agent/workspace-resources.js → skills/loader.js} +1 -1
- package/dist/{tools/skill-security.js → skills/validation.js} +4 -0
- package/dist/skills/workspace.d.ts +33 -0
- package/dist/skills/workspace.js +116 -0
- package/dist/{runtime/subagent-commands.d.ts → subagents/commands.d.ts} +9 -7
- package/dist/{runtime/subagent-commands.js → subagents/commands.js} +116 -77
- package/dist/subagents/completion-wake.d.ts +17 -0
- package/dist/subagents/completion-wake.js +76 -0
- package/dist/subagents/detached-discovery.js +1 -1
- package/dist/subagents/discovery.d.ts +1 -1
- package/dist/subagents/discovery.js +2 -2
- package/dist/subagents/dispatch.d.ts +33 -0
- package/dist/subagents/dispatch.js +190 -0
- package/dist/subagents/external/claude-code.js +23 -1
- package/dist/subagents/external/dispatch.d.ts +25 -0
- package/dist/subagents/external/dispatch.js +90 -0
- package/dist/subagents/external/harness.d.ts +1 -1
- package/dist/subagents/external/progress-tail.d.ts +18 -1
- package/dist/subagents/external/progress-tail.js +64 -17
- package/dist/subagents/external/run.d.ts +5 -1
- package/dist/subagents/external/run.js +23 -9
- package/dist/subagents/external/settlement.d.ts +4 -1
- package/dist/subagents/external/settlement.js +1 -1
- package/dist/subagents/format.d.ts +1 -1
- package/dist/subagents/grace.d.ts +24 -0
- package/dist/subagents/grace.js +57 -0
- package/dist/subagents/internal/outcome.d.ts +24 -0
- package/dist/subagents/internal/outcome.js +149 -0
- package/dist/subagents/internal/provider-retry.d.ts +19 -0
- package/dist/subagents/internal/provider-retry.js +83 -0
- package/dist/subagents/internal/run.d.ts +31 -0
- package/dist/subagents/internal/run.js +240 -0
- package/dist/subagents/internal/state.d.ts +43 -0
- package/dist/subagents/internal/state.js +48 -0
- package/dist/subagents/internal/worker.d.ts +51 -0
- package/dist/subagents/internal/worker.js +167 -0
- package/dist/subagents/result.d.ts +62 -0
- package/dist/subagents/result.js +103 -0
- package/dist/subagents/run-record.d.ts +222 -0
- package/dist/subagents/run-record.js +101 -0
- package/dist/subagents/run-registry.d.ts +9 -0
- package/dist/subagents/run-registry.js +125 -0
- package/dist/subagents/runs.d.ts +16 -232
- package/dist/subagents/runs.js +132 -310
- package/dist/subagents/task-envelope.d.ts +36 -0
- package/dist/subagents/task-envelope.js +168 -0
- package/dist/subagents/types.d.ts +154 -0
- package/dist/subagents/types.js +1 -0
- package/dist/subagents/verification-outcome.d.ts +1 -1
- package/dist/subagents/workspace-summary.d.ts +16 -4
- package/dist/subagents/workspace-summary.js +74 -18
- package/dist/tasks/board.d.ts +10 -3
- package/dist/tasks/board.js +38 -3
- package/dist/tasks/{work-log.d.ts → bound-work.d.ts} +1 -1
- package/dist/tasks/{work-log.js → bound-work.js} +1 -1
- package/dist/tasks/brief.js +1 -1
- package/dist/{runtime/task-commands.d.ts → tasks/commands.d.ts} +1 -1
- package/dist/{runtime/task-commands.js → tasks/commands.js} +117 -67
- package/dist/tasks/contract-input.d.ts +1 -1
- package/dist/tasks/contract-input.js +1 -1
- package/dist/tasks/create.js +1 -1
- package/dist/tasks/frontmatter.d.ts +5 -0
- package/dist/tasks/frontmatter.js +8 -0
- package/dist/tasks/{log.d.ts → loop-log.d.ts} +11 -1
- package/dist/tasks/{log.js → loop-log.js} +59 -3
- package/dist/tasks/mutation-lock.js +1 -1
- package/dist/tasks/session-path.js +1 -1
- package/dist/tasks/steer.js +1 -1
- package/dist/tasks/store.js +6 -4
- package/dist/tasks/ticket.d.ts +3 -1
- package/dist/tasks/ticket.js +19 -1
- package/dist/tools/bash.d.ts +1 -1
- package/dist/tools/bash.js +2 -2
- package/dist/tools/{tool-details.d.ts → contract/details.d.ts} +11 -3
- package/dist/tools/{tool-details.js → contract/details.js} +42 -5
- package/dist/tools/{presentation.js → contract/presentation.js} +3 -3
- package/dist/tools/event-manage.d.ts +1 -1
- package/dist/tools/event-manage.js +4 -4
- package/dist/tools/index.d.ts +5 -3
- package/dist/tools/index.js +8 -6
- package/dist/tools/job.d.ts +1 -1
- package/dist/tools/memory-manage.js +4 -1
- package/dist/tools/registry.d.ts +7 -7
- package/dist/tools/registry.js +6 -6
- package/dist/tools/session-search.d.ts +1 -1
- package/dist/tools/skill.d.ts +2 -34
- package/dist/tools/skill.js +8 -116
- package/dist/tools/subagent-manage.d.ts +1 -1
- package/dist/tools/subagent-manage.js +19 -13
- package/dist/tools/subagent.d.ts +46 -0
- package/dist/tools/subagent.js +127 -0
- package/dist/tools/{task-manage.d.ts → task-manage/factory.d.ts} +7 -3
- package/dist/tools/{task-manage.js → task-manage/factory.js} +7 -7
- package/dist/tools/task-manage/lifecycle.js +2 -2
- package/dist/tools/task-manage/log-view.js +2 -2
- package/dist/tools/task-manage/shared.js +3 -3
- package/dist/tools/task-manage/step-end.js +7 -4
- package/dist/tools/task-manage/types.d.ts +1 -1
- package/dist/tools/web-fetch.d.ts +1 -1
- package/dist/tools/web-search.d.ts +1 -1
- package/dist/tui/app.d.ts +1 -1
- package/dist/tui/app.js +6 -6
- package/dist/tui/cli.d.ts +1 -1
- package/dist/tui/cli.js +3 -3
- package/dist/tui/commands.js +4 -4
- package/dist/tui/frontend.d.ts +44 -0
- package/dist/tui/frontend.js +13 -0
- package/dist/tui/pitui-frontend.d.ts +1 -1
- package/dist/tui/pitui-frontend.js +1 -1
- package/dist/tui/plain-frontend.d.ts +1 -1
- package/dist/tui/renderer.d.ts +3 -42
- package/dist/tui/renderer.js +3 -2
- package/dist/tui/terminal-context.d.ts +2 -2
- package/dist/tui/terminal-media-sender.d.ts +1 -1
- package/dist/tui/turn-controller.d.ts +3 -1
- package/dist/tui/turn-controller.js +36 -21
- package/dist/usage/ledger.js +7 -1
- package/dist/usage/render.js +3 -1
- package/dist/{shared/types.d.ts → usage/totals.d.ts} +3 -0
- package/dist/web/client.d.ts +5 -1
- package/dist/web/client.js +4 -0
- package/dist/web/config.d.ts +1 -1
- package/dist/web/fetch.d.ts +1 -1
- package/dist/web/search-providers.d.ts +1 -1
- package/dist/web/search.d.ts +1 -1
- package/package.json +9 -7
- package/dist/agent/session-adapter.js +0 -77
- package/dist/events/events.d.ts +0 -159
- package/dist/runtime/dingtalk.d.ts +0 -272
- package/dist/runtime/dingtalk.js +0 -1416
- package/dist/subagents/tool.d.ts +0 -206
- package/dist/subagents/tool.js +0 -1088
- /package/dist/{runtime → agent/prompt}/workspace-templates.d.ts +0 -0
- /package/dist/{runtime → agent/prompt}/workspace-templates.js +0 -0
- /package/dist/agent/{session-resource-gate.d.ts → session/session-resource-gate.d.ts} +0 -0
- /package/dist/agent/{context-budget.d.ts → turn/context-budget.d.ts} +0 -0
- /package/dist/agent/{progress-formatter.js → turn/progress-formatter.js} +0 -0
- /package/dist/{memory → agent/turn}/task-digest.d.ts +0 -0
- /package/dist/agent/{turn-recovery.d.ts → turn/turn-recovery.d.ts} +0 -0
- /package/dist/agent/{turn-state.js → turn/turn-state.js} +0 -0
- /package/dist/{runtime → app}/proxy.d.ts +0 -0
- /package/dist/{runtime → dingtalk}/channel-queue.d.ts +0 -0
- /package/dist/{runtime → dingtalk}/inbound-media.d.ts +0 -0
- /package/dist/{runtime → dingtalk}/inbound-media.js +0 -0
- /package/dist/events/{event-commands.d.ts → commands.d.ts} +0 -0
- /package/dist/{agent/workspace-resources.d.ts → skills/loader.d.ts} +0 -0
- /package/dist/{tools/skill-security.d.ts → skills/validation.d.ts} +0 -0
- /package/dist/tasks/{ledger.d.ts → contract.d.ts} +0 -0
- /package/dist/tasks/{ledger.js → contract.js} +0 -0
- /package/dist/tools/{subagent-tool-names.d.ts → contract/names.d.ts} +0 -0
- /package/dist/tools/{subagent-tool-names.js → contract/names.js} +0 -0
- /package/dist/tools/{presentation.d.ts → contract/presentation.d.ts} +0 -0
- /package/dist/{shared/types.js → usage/totals.js} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import type { PipiclawSettingsManager } from "../config/settings.js";
|
|
1
2
|
import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
|
|
2
|
-
import type { PipiclawSettingsManager } from "../settings.js";
|
|
3
3
|
export interface DetachedMaintenanceContextOptions {
|
|
4
4
|
channelId: string;
|
|
5
5
|
channelDir: string;
|
|
@@ -2,7 +2,7 @@ import { statSync } from "node:fs";
|
|
|
2
2
|
import { dirname, join } from "node:path";
|
|
3
3
|
import { SessionManager } from "@earendil-works/pi-coding-agent";
|
|
4
4
|
import { getApiKeyForModel } from "../models/api-keys.js";
|
|
5
|
-
import { createModelRuntime, resolveInitialModel, wrapModelRegistry } from "../models/
|
|
5
|
+
import { createModelRuntime, resolveInitialModel, wrapModelRegistry } from "../models/runtime.js";
|
|
6
6
|
// The maintenance scheduler visits idle channels every tick; re-parsing an
|
|
7
7
|
// unchanged context.jsonl each time would be pure I/O waste for long-dead
|
|
8
8
|
// channels. Keyed by channelDir, replaced whenever the file changes.
|
|
@@ -32,7 +32,7 @@ export interface ToolSchemaMeasurement {
|
|
|
32
32
|
chars: number;
|
|
33
33
|
units: number;
|
|
34
34
|
}
|
|
35
|
-
/** The
|
|
35
|
+
/** The operator wording for "the tool set is over budget", for the rebuild log (`/context` says it in Chinese). */
|
|
36
36
|
export declare function toolSchemaBudgetWarning(measurement: ToolSchemaMeasurement): string;
|
|
37
37
|
/**
|
|
38
38
|
* What the tool set costs on top of the system prompt. Counts what the provider is actually sent
|
|
@@ -102,4 +102,9 @@ export declare function estimateSkillsPromptChars(skills: Array<{
|
|
|
102
102
|
}>): number;
|
|
103
103
|
/** Section metadata without any section body — safe to write next to a channel. */
|
|
104
104
|
export declare function buildPromptManifest(build: PromptBuildResult, finalPrompt?: string): PromptManifest;
|
|
105
|
+
/**
|
|
106
|
+
* `/context` (spec 053, D9): the default view is a summary a user can read on a phone; `detail`
|
|
107
|
+
* adds the per-section sources and the tool/skill inventory, still under the reply budget.
|
|
108
|
+
* "单位" is the prompt-unit measure the budgets are written in (`countPromptUnits`).
|
|
109
|
+
*/
|
|
105
110
|
export declare function renderContextReport(input: PromptContextReportInput): string;
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* owns the same list that backs `/skill:name`, so `estimateSkillsPromptChars` lives
|
|
10
10
|
* next to the report — not in the builder's budget path (spec 026 §9, §10.9).
|
|
11
11
|
*/
|
|
12
|
+
import { capReply } from "../../commands/reply-limits.js";
|
|
12
13
|
import { estimateTokens } from "../../shared/format.js";
|
|
13
14
|
import { countPromptUnits } from "../../shared/prompt-units.js";
|
|
14
15
|
import { RUNTIME_PROMPT_TARGET_UNITS, sha256 } from "./builder.js";
|
|
@@ -30,7 +31,7 @@ export const AUTOMATIC_TURN_CONTEXT_BUDGET_UNITS = 3_000;
|
|
|
30
31
|
* is exactly when someone should be looking.
|
|
31
32
|
*/
|
|
32
33
|
export const TOOL_SCHEMA_TARGET_UNITS = 3_000;
|
|
33
|
-
/** The
|
|
34
|
+
/** The operator wording for "the tool set is over budget", for the rebuild log (`/context` says it in Chinese). */
|
|
34
35
|
export function toolSchemaBudgetWarning(measurement) {
|
|
35
36
|
return `tool JSON schemas are ${measurement.units} units (${measurement.chars} chars), over the ${TOOL_SCHEMA_TARGET_UNITS} unit target. Shorten a tool description, move detail into a playbook, or unregister a tool; \`/context detail\` lists the set.`;
|
|
36
37
|
}
|
|
@@ -78,84 +79,64 @@ export function buildPromptManifest(build, finalPrompt) {
|
|
|
78
79
|
function formatNumber(value) {
|
|
79
80
|
return value.toLocaleString("en-US");
|
|
80
81
|
}
|
|
81
|
-
function
|
|
82
|
+
function renderWorkspaceResource(label, resource) {
|
|
82
83
|
if (!resource || resource.isDefaultTemplate)
|
|
83
84
|
return undefined;
|
|
84
|
-
const state = resource.truncated ? "
|
|
85
|
-
return
|
|
85
|
+
const state = resource.truncated ? ",已截断" : "";
|
|
86
|
+
return `${label} ${formatNumber(resource.injectedUnits)} / ${formatNumber(resource.budgetUnits)} 单位${state}`;
|
|
86
87
|
}
|
|
88
|
+
/**
|
|
89
|
+
* `/context` (spec 053, D9): the default view is a summary a user can read on a phone; `detail`
|
|
90
|
+
* adds the per-section sources and the tool/skill inventory, still under the reply budget.
|
|
91
|
+
* "单位" is the prompt-unit measure the budgets are written in (`countPromptUnits`).
|
|
92
|
+
*/
|
|
87
93
|
export function renderContextReport(input) {
|
|
88
94
|
const { build, finalPrompt, detail } = input;
|
|
89
|
-
const lines = ["
|
|
90
|
-
lines.push(
|
|
95
|
+
const lines = ["**上下文**", ""];
|
|
96
|
+
lines.push(`- 系统提示词(Pipiclaw 部分):${formatNumber(build.totalUnits)} 单位,约 ${formatNumber(build.estimatedTokens)} tokens;其中运行时自带 ${formatNumber(build.runtimeAuthoredUnits)} / 目标 ${formatNumber(RUNTIME_PROMPT_TARGET_UNITS)} 单位`);
|
|
91
97
|
if (finalPrompt) {
|
|
92
98
|
// The string the provider actually caches: our sections + pi's skills/date/cwd tail +
|
|
93
99
|
// the boundary footer. It is the fingerprint that matters for cache hits — the build
|
|
94
|
-
// fingerprint
|
|
95
|
-
//
|
|
96
|
-
lines.push(
|
|
97
|
-
}
|
|
98
|
-
lines.push(`Fingerprint (Pipiclaw sections): sha256:${build.fingerprint.slice(0, 16)}`);
|
|
99
|
-
lines.push("");
|
|
100
|
-
// Space-padded column alignment relies on a monospace font: DingTalk's proportional rendering
|
|
101
|
-
// collapses it back into unaligned runs, so each field is punctuation-delimited instead of
|
|
102
|
-
// column-aligned (review 2026-08-24 §1.3a).
|
|
103
|
-
for (const section of build.sections) {
|
|
104
|
-
const flags = [section.cacheClass];
|
|
105
|
-
if (section.truncated)
|
|
106
|
-
flags.push(`truncated from ${formatNumber(section.rawUnits)} units`);
|
|
107
|
-
lines.push(`- ${section.id}: ${formatNumber(section.injectedUnits)} units, ${formatNumber(section.injectedChars)} chars, ${flags.join(", ")}`);
|
|
100
|
+
// fingerprint only covers the part Pipiclaw owns, and stays stable across a date rollover
|
|
101
|
+
// that does invalidate the provider's cached prefix.
|
|
102
|
+
lines.push(`- 实际发送(含 skills、日期、工作目录):${formatNumber(finalPrompt.length)} 字,约 ${formatNumber(estimateTokens(finalPrompt))} tokens,指纹 \`${sha256(finalPrompt).slice(0, 16)}\``);
|
|
108
103
|
}
|
|
109
|
-
const soulLine = renderWorkspaceResourceLine("SOUL.md", input.soul);
|
|
110
|
-
const agentsLine = renderWorkspaceResourceLine("AGENTS.md", input.agents);
|
|
111
|
-
if (soulLine || agentsLine) {
|
|
112
|
-
lines.push("");
|
|
113
|
-
lines.push("Workspace resources (independent budgets, not competing with the runtime):");
|
|
114
|
-
if (soulLine)
|
|
115
|
-
lines.push(soulLine);
|
|
116
|
-
if (agentsLine)
|
|
117
|
-
lines.push(agentsLine);
|
|
118
|
-
}
|
|
119
|
-
lines.push("");
|
|
120
104
|
const overToolBudget = input.toolSchemas.units > TOOL_SCHEMA_TARGET_UNITS;
|
|
121
|
-
lines.push(
|
|
122
|
-
lines.push(
|
|
105
|
+
lines.push(`- 工具定义:${input.toolNames.length} 个,${formatNumber(input.toolSchemas.units)} / 目标 ${formatNumber(TOOL_SCHEMA_TARGET_UNITS)} 单位${overToolBudget ? "(超出目标)" : ""},在系统提示词之外另计`);
|
|
106
|
+
lines.push(`- Skills:${input.skills.length} 个可见,约 ${formatNumber(estimateSkillsPromptChars(input.skills))} 字(由 pi 渲染,不计入 Pipiclaw 预算)`);
|
|
107
|
+
const resources = [
|
|
108
|
+
renderWorkspaceResource("SOUL.md", input.soul),
|
|
109
|
+
renderWorkspaceResource("AGENTS.md", input.agents),
|
|
110
|
+
]
|
|
111
|
+
.filter(Boolean)
|
|
112
|
+
.join(";");
|
|
113
|
+
if (resources)
|
|
114
|
+
lines.push(`- 工作区文件(独立预算):${resources}`);
|
|
123
115
|
if (input.lastTurn) {
|
|
124
116
|
const turn = input.lastTurn;
|
|
125
117
|
const automaticUnits = turn.channelCapsuleUnits + turn.taskDigestUnits + turn.durableMemoryUnits;
|
|
126
|
-
lines.push(
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
lines.push(`-
|
|
130
|
-
lines.push(`- memory bootstrap: ${formatNumber(turn.durableMemoryUnits)} units / ${formatNumber(turn.durableMemoryChars)} chars (first turn only)`);
|
|
131
|
-
lines.push(`- user message: ${formatNumber(turn.userMessageChars)} chars (not automatic; not capped here)`);
|
|
118
|
+
lines.push(`- 上一回合自动附加:${formatNumber(automaticUnits)} / ${formatNumber(AUTOMATIC_TURN_CONTEXT_BUDGET_UNITS)} 单位(频道信息 ${formatNumber(turn.channelCapsuleUnits)},任务清单 ${formatNumber(turn.taskDigestUnits)},记忆 ${formatNumber(turn.durableMemoryUnits)},记忆只在首个回合附加);用户消息 ${formatNumber(turn.userMessageChars)} 字`);
|
|
119
|
+
}
|
|
120
|
+
for (const diagnostic of build.diagnostics) {
|
|
121
|
+
lines.push(`- ⚠️ ${diagnostic.sectionId}:${diagnostic.message}`);
|
|
132
122
|
}
|
|
133
|
-
if (
|
|
134
|
-
lines.push("");
|
|
135
|
-
lines.push("Diagnostics:");
|
|
136
|
-
for (const diagnostic of build.diagnostics) {
|
|
137
|
-
lines.push(`- [${diagnostic.level}] ${diagnostic.sectionId}: ${diagnostic.message}`);
|
|
138
|
-
}
|
|
139
|
-
if (overToolBudget) {
|
|
140
|
-
lines.push(`- [warning] tools: ${toolSchemaBudgetWarning(input.toolSchemas)}`);
|
|
141
|
-
}
|
|
123
|
+
if (overToolBudget) {
|
|
124
|
+
lines.push("- ⚠️ 工具定义超出目标:缩短某个工具的说明、把细节移到 playbook,或停用一个工具;`/context detail` 列出全部工具");
|
|
142
125
|
}
|
|
143
|
-
if (detail) {
|
|
144
|
-
lines.push("");
|
|
145
|
-
lines.
|
|
146
|
-
for (const section of build.sections) {
|
|
147
|
-
lines.push(`- ${section.id} (${section.authority}) ← ${section.source} · sha256:${section.sha256.slice(0, 12)}`);
|
|
148
|
-
}
|
|
149
|
-
if (input.toolNames.length > 0) {
|
|
150
|
-
lines.push(`- tools: ${input.toolNames.join(", ")}`);
|
|
151
|
-
}
|
|
152
|
-
if (input.skills.length > 0) {
|
|
153
|
-
lines.push(`- skills: ${input.skills.map((skill) => skill.name).join(", ")}`);
|
|
154
|
-
}
|
|
126
|
+
if (!detail) {
|
|
127
|
+
lines.push("", "用 `/context detail` 查看各分段的来源与工具、skill 清单。");
|
|
128
|
+
return lines.join("\n");
|
|
155
129
|
}
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
130
|
+
lines.push("", "**分段**");
|
|
131
|
+
for (const section of build.sections) {
|
|
132
|
+
const truncated = section.truncated ? `,已截断(原 ${formatNumber(section.rawUnits)} 单位)` : "";
|
|
133
|
+
lines.push(`- ${section.id}:${formatNumber(section.injectedUnits)} 单位,${formatNumber(section.injectedChars)} 字,${section.cacheClass}${truncated};来源 ${section.source}(${section.authority})`);
|
|
159
134
|
}
|
|
160
|
-
|
|
135
|
+
if (input.toolNames.length > 0)
|
|
136
|
+
lines.push("", `**工具**:${input.toolNames.join("、")}`);
|
|
137
|
+
if (input.skills.length > 0)
|
|
138
|
+
lines.push("", `**Skills**:${input.skills.map((skill) => skill.name).join("、")}`);
|
|
139
|
+
return capReply(lines.join("\n"), {
|
|
140
|
+
nextStepHint: "用 `/context` 只看汇总;完整提示词需部署者在服务器上设 `PIPICLAW_DEBUG=1`,之后查看频道目录的 `last_prompt.json`",
|
|
141
|
+
}).text;
|
|
161
142
|
}
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
* the runtime catalog, or with skills for space; only a genuinely oversized file is
|
|
12
12
|
* head/tail clipped.
|
|
13
13
|
*/
|
|
14
|
+
import { type RuntimePlaybookMetadata } from "../../playbooks/catalog.js";
|
|
14
15
|
import type { LoadedPromptResource, PromptDiagnostic } from "./types.js";
|
|
15
16
|
/** SOUL.md is identity and voice: normally short, so a tight independent budget (spec 026 §5.2). */
|
|
16
17
|
export declare const SOUL_BUDGET_UNITS = 3000;
|
|
@@ -23,5 +24,7 @@ export interface WorkspacePromptResources {
|
|
|
23
24
|
agents?: LoadedPromptResource;
|
|
24
25
|
diagnostics: PromptDiagnostic[];
|
|
25
26
|
}
|
|
27
|
+
/** The bundled runtime playbooks that apply to the tools this runner actually has. */
|
|
28
|
+
export declare function loadPlaybooks(toolNames: readonly string[]): RuntimePlaybookMetadata[];
|
|
26
29
|
/** Read SOUL.md and AGENTS.md from the workspace root, budgeted and template-aware. */
|
|
27
30
|
export declare function loadWorkspacePromptResources(workspaceDir: string): WorkspacePromptResources;
|
|
@@ -14,14 +14,20 @@
|
|
|
14
14
|
import { existsSync, readFileSync } from "node:fs";
|
|
15
15
|
import { join } from "node:path";
|
|
16
16
|
import * as log from "../../log.js";
|
|
17
|
-
import {
|
|
17
|
+
import { loadRuntimePlaybookCatalog, selectRuntimePlaybooks, } from "../../playbooks/catalog.js";
|
|
18
18
|
import { clipTextByPromptUnits, countPromptUnits } from "../../shared/prompt-units.js";
|
|
19
|
+
import { TOOL_NAMES } from "../../tools/registry.js";
|
|
20
|
+
import { DEFAULT_AGENTS, DEFAULT_SOUL, isDefaultWorkspaceTemplate } from "./workspace-templates.js";
|
|
19
21
|
/** SOUL.md is identity and voice: normally short, so a tight independent budget (spec 026 §5.2). */
|
|
20
22
|
export const SOUL_BUDGET_UNITS = 3_000;
|
|
21
23
|
export const SOUL_BUDGET_CHARS = 24_000;
|
|
22
24
|
/** AGENTS.md carries team procedure and is allowed to be larger (spec 026 §5.2). */
|
|
23
25
|
export const AGENTS_BUDGET_UNITS = 6_000;
|
|
24
26
|
export const AGENTS_BUDGET_CHARS = 48_000;
|
|
27
|
+
/** The bundled runtime playbooks that apply to the tools this runner actually has. */
|
|
28
|
+
export function loadPlaybooks(toolNames) {
|
|
29
|
+
return selectRuntimePlaybooks(loadRuntimePlaybookCatalog(TOOL_NAMES), toolNames);
|
|
30
|
+
}
|
|
25
31
|
function readWorkspaceFile(path) {
|
|
26
32
|
if (!existsSync(path)) {
|
|
27
33
|
return "";
|
|
@@ -30,7 +36,10 @@ function readWorkspaceFile(path) {
|
|
|
30
36
|
return readFileSync(path, "utf-8").replace(/\r/g, "").trim();
|
|
31
37
|
}
|
|
32
38
|
catch (error) {
|
|
33
|
-
log.
|
|
39
|
+
log.logWarn("agent.prompt.resource_read_failed", "Prompt resource read failed", {
|
|
40
|
+
reason: String(error),
|
|
41
|
+
fields: { path },
|
|
42
|
+
});
|
|
34
43
|
return "";
|
|
35
44
|
}
|
|
36
45
|
}
|
|
@@ -1,46 +1,4 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import { type Executor } from "../executor.js";
|
|
3
|
-
import { type FileStore } from "../file-store.js";
|
|
4
|
-
import { type LoadedSecurityConfig } from "../security/config.js";
|
|
5
|
-
import type { PipiclawSettingsManager } from "../settings.js";
|
|
6
|
-
import type { SubAgentRunManager } from "../subagents/runs.js";
|
|
7
|
-
import type { ChannelJobManager } from "./job-manager.js";
|
|
8
|
-
import type { AgentRunner } from "./types.js";
|
|
9
|
-
export interface RunnerFactoryPaths {
|
|
10
|
-
jobManager: ChannelJobManager;
|
|
11
|
-
runManager: SubAgentRunManager;
|
|
12
|
-
appHomeDir: string;
|
|
13
|
-
authConfigPath: string;
|
|
14
|
-
modelsConfigPath: string;
|
|
15
|
-
/**
|
|
16
|
-
* The single app-level settings manager (from `prepareAppServices`), shared across every
|
|
17
|
-
* channel's runner rather than each constructing its own. Keeps `drainErrors()`/diagnostics
|
|
18
|
-
* ordering and `reload()`'s file-stamp guard meaningful instead of racing N independent copies.
|
|
19
|
-
*/
|
|
20
|
-
settingsManager: PipiclawSettingsManager;
|
|
21
|
-
/** Optional, side-effect-free observer used by the behavior-eval harness. */
|
|
22
|
-
onSessionEvent?: (event: unknown, channelId: string) => void;
|
|
23
|
-
/**
|
|
24
|
-
* Transport that can deliver file attachments (the DingTalk bot, or the terminal).
|
|
25
|
-
* Present enables the `send_media` tool; absent, the tool is not built.
|
|
26
|
-
*/
|
|
27
|
-
mediaSender?: MediaSender;
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* The collaborators a runner uses but does not build. Composing them here rather than inside
|
|
31
|
-
* `ChannelRunner`'s constructor keeps the "which implementation" decision at the one place that
|
|
32
|
-
* already owns wiring, and is what makes `Executor`/`FileStore` real ports (a remote executor is
|
|
33
|
-
* a different value passed in, not a different branch inside the runner).
|
|
34
|
-
*/
|
|
35
|
-
export interface RunnerDeps {
|
|
36
|
-
executor: Executor;
|
|
37
|
-
fileStore: FileStore;
|
|
38
|
-
/**
|
|
39
|
-
* Called per use, not resolved once: the runner re-reads security policy on every tool rebuild
|
|
40
|
-
* so an edited `security.json` takes effect without restarting the daemon.
|
|
41
|
-
*/
|
|
42
|
-
loadSecurityConfig: () => LoadedSecurityConfig;
|
|
43
|
-
}
|
|
1
|
+
import type { AgentRunner, RunnerFactoryPaths } from "./types.js";
|
|
44
2
|
/**
|
|
45
3
|
* Stateless: always constructs a fresh runner. The daemon (`runtime/bootstrap.ts`) and the TUI
|
|
46
4
|
* (`tui/app.ts`) are the only two callers, and each already owns exactly one cache appropriate to
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The SDK extension that serves the session slash commands (`/model`, `/thinking`, `/session`,
|
|
3
|
+
* `/compact`, `/memory`, `/new`) inside the agent session, backed by callbacks from the session host.
|
|
4
|
+
*/
|
|
1
5
|
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
|
|
2
6
|
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
3
7
|
import type { ExtensionFactory, SessionStats } from "@earendil-works/pi-coding-agent";
|
|
@@ -1,24 +1,43 @@
|
|
|
1
1
|
import { basename } from "path";
|
|
2
|
-
import { sessionCommandDescription } from "
|
|
3
|
-
import {
|
|
2
|
+
import { formatNewSessionReply, sessionCommandDescription } from "../../commands/catalog.js";
|
|
3
|
+
import { capReply } from "../../commands/reply-limits.js";
|
|
4
|
+
import { findModelReferenceMatch, formatModelList, formatModelReference } from "../../models/reference.js";
|
|
5
|
+
import { estimateTokens } from "../../shared/format.js";
|
|
6
|
+
import { truncate } from "../../shared/text-utils.js";
|
|
4
7
|
export const COMMAND_RESULT_CUSTOM_TYPE = "pipiclaw.command_result";
|
|
5
8
|
function buildSessionText(stats, currentModel, thinkingLevel, lastResponseModel) {
|
|
6
9
|
const configuredRef = currentModel ? formatModelReference(currentModel) : null;
|
|
7
|
-
const modelText = configuredRef ? `\`${configuredRef}\`` : "
|
|
10
|
+
const modelText = configuredRef ? `\`${configuredRef}\`` : "(无)";
|
|
8
11
|
const actualText = lastResponseModel && configuredRef && lastResponseModel !== configuredRef
|
|
9
|
-
?
|
|
12
|
+
? `(实际响应:\`${lastResponseModel}\`)`
|
|
10
13
|
: "";
|
|
11
|
-
const sessionFile = stats.sessionFile ? `\`${basename(stats.sessionFile)}\`` : "
|
|
14
|
+
const sessionFile = stats.sessionFile ? `\`${basename(stats.sessionFile)}\`` : "(无)";
|
|
15
|
+
const tokens = stats.tokens;
|
|
12
16
|
return `**会话**
|
|
13
17
|
|
|
14
|
-
-
|
|
15
|
-
-
|
|
18
|
+
- 会话 ID:\`${stats.sessionId}\`
|
|
19
|
+
- 会话文件:${sessionFile}
|
|
16
20
|
- 模型:${modelText}${actualText}
|
|
17
|
-
-
|
|
21
|
+
- 思考档位(thinking):\`${thinkingLevel}\`
|
|
18
22
|
- 消息:用户 \`${stats.userMessages}\` · 助手 \`${stats.assistantMessages}\` · 共 \`${stats.totalMessages}\`
|
|
19
23
|
- 工具调用:\`${stats.toolCalls}\` · 工具结果:\`${stats.toolResults}\`
|
|
20
|
-
-
|
|
21
|
-
-
|
|
24
|
+
- token 用量:共 \`${tokens.total}\`(输入 \`${tokens.input}\`,输出 \`${tokens.output}\`,缓存读 \`${tokens.cacheRead}\`,缓存写 \`${tokens.cacheWrite}\`)
|
|
25
|
+
- 花费:\`$${stats.cost.toFixed(4)}\``;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The `/compact` confirmation: sizes and the summary's first line only — the summary itself is
|
|
29
|
+
* the model's working notes and can run to pages (spec 053, D9).
|
|
30
|
+
*/
|
|
31
|
+
function buildCompactText(result) {
|
|
32
|
+
const after = result.estimatedTokensAfter ?? estimateTokens(result.summary);
|
|
33
|
+
const firstLine = result.summary
|
|
34
|
+
.split("\n")
|
|
35
|
+
.map((line) => line.replace(/^#+\s*/, "").trim())
|
|
36
|
+
.find(Boolean) ?? "";
|
|
37
|
+
const lines = [`已压缩当前会话上下文:压缩前 \`${result.tokensBefore}\` tokens,压缩后约 \`${after}\` tokens。`];
|
|
38
|
+
if (firstLine)
|
|
39
|
+
lines.push(`摘要开头:${truncate(firstLine, 120)}`);
|
|
40
|
+
return lines.join("\n");
|
|
22
41
|
}
|
|
23
42
|
async function runCompact(ctx, customInstructions) {
|
|
24
43
|
return await new Promise((resolve, reject) => {
|
|
@@ -37,12 +56,12 @@ function sendCommandResult(sender, text) {
|
|
|
37
56
|
});
|
|
38
57
|
}
|
|
39
58
|
function buildThinkingText(current, available) {
|
|
40
|
-
return
|
|
59
|
+
return `**思考档位**
|
|
41
60
|
|
|
42
61
|
- 当前档位:\`${current}\`
|
|
43
|
-
- 可用档位:${available.map((level) => `\`${level}\``).join("
|
|
62
|
+
- 可用档位:${available.map((level) => `\`${level}\``).join("、")}
|
|
44
63
|
|
|
45
|
-
用 \`/thinking
|
|
64
|
+
用 \`/thinking <档位>\` 设置,或 \`/thinking cycle\` 切到下一个可用档位。`;
|
|
46
65
|
}
|
|
47
66
|
export function createCommandExtension(options) {
|
|
48
67
|
return (pi) => {
|
|
@@ -70,21 +89,21 @@ export function createCommandExtension(options) {
|
|
|
70
89
|
if (normalized === "cycle") {
|
|
71
90
|
const next = options.cycleThinkingLevel();
|
|
72
91
|
if (!next) {
|
|
73
|
-
sendCommandResult(pi, "
|
|
92
|
+
sendCommandResult(pi, "当前模型不支持思考档位。用 `/model` 换一个支持推理的模型。");
|
|
74
93
|
return;
|
|
75
94
|
}
|
|
76
|
-
sendCommandResult(pi,
|
|
95
|
+
sendCommandResult(pi, `思考档位已切换为 \`${next}\`。`);
|
|
77
96
|
return;
|
|
78
97
|
}
|
|
79
98
|
if (!available.includes(normalized)) {
|
|
80
|
-
sendCommandResult(pi,
|
|
99
|
+
sendCommandResult(pi, `当前模型不支持思考档位 \`${args.trim()}\`。可用档位:${available
|
|
81
100
|
.map((level) => `\`${level}\``)
|
|
82
|
-
.join("
|
|
101
|
+
.join("、")}。`);
|
|
83
102
|
return;
|
|
84
103
|
}
|
|
85
104
|
const level = normalized;
|
|
86
105
|
options.setThinkingLevel(level);
|
|
87
|
-
sendCommandResult(pi,
|
|
106
|
+
sendCommandResult(pi, `思考档位已设置为 \`${level}\`。`);
|
|
88
107
|
},
|
|
89
108
|
});
|
|
90
109
|
pi.registerCommand("model", {
|
|
@@ -93,23 +112,24 @@ export function createCommandExtension(options) {
|
|
|
93
112
|
const availableModels = await options.getAvailableModels();
|
|
94
113
|
const currentModel = options.getCurrentModel();
|
|
95
114
|
if (!args.trim()) {
|
|
96
|
-
const current = currentModel ? `\`${formatModelReference(currentModel)}\`` : "
|
|
97
|
-
const available = availableModels.length > 0 ? formatModelList(availableModels, currentModel) : "-
|
|
98
|
-
|
|
115
|
+
const current = currentModel ? `\`${formatModelReference(currentModel)}\`` : "(无)";
|
|
116
|
+
const available = availableModels.length > 0 ? formatModelList(availableModels, currentModel) : "- (无可用模型)";
|
|
117
|
+
const report = `**模型**
|
|
99
118
|
|
|
100
119
|
当前模型:${current}
|
|
101
120
|
|
|
102
|
-
用 \`/model <provider/modelId>\`、\`/model <modelId>\`
|
|
121
|
+
用 \`/model <provider/modelId>\`、\`/model <modelId>\` 或任意能唯一匹配的片段切换。
|
|
103
122
|
|
|
104
123
|
可用模型:
|
|
105
|
-
${available}
|
|
124
|
+
${available}`;
|
|
125
|
+
sendCommandResult(pi, capReply(report, { nextStepHint: "用 `/model <片段>` 按名称直接切换" }).text);
|
|
106
126
|
return;
|
|
107
127
|
}
|
|
108
128
|
const match = findModelReferenceMatch(args, availableModels);
|
|
109
|
-
const available = availableModels.length > 0 ? formatModelList(availableModels, currentModel, 10) : "-
|
|
129
|
+
const available = availableModels.length > 0 ? formatModelList(availableModels, currentModel, 10) : "- (无可用模型)";
|
|
110
130
|
if (match.match) {
|
|
111
131
|
await options.switchModel(match.match);
|
|
112
|
-
sendCommandResult(pi, `已切换模型到 \`${formatModelReference(match.match)}
|
|
132
|
+
sendCommandResult(pi, `已切换模型到 \`${formatModelReference(match.match)}\`。`);
|
|
113
133
|
return;
|
|
114
134
|
}
|
|
115
135
|
if (match.ambiguous) {
|
|
@@ -133,7 +153,7 @@ ${available}`);
|
|
|
133
153
|
withSession: async (nextCtx) => {
|
|
134
154
|
sentFromReplacement = true;
|
|
135
155
|
await options.refreshSessionResources();
|
|
136
|
-
await sendCommandResult(nextCtx,
|
|
156
|
+
await sendCommandResult(nextCtx, formatNewSessionReply(nextCtx.sessionManager.getSessionId()));
|
|
137
157
|
},
|
|
138
158
|
});
|
|
139
159
|
if (result.cancelled) {
|
|
@@ -141,7 +161,7 @@ ${available}`);
|
|
|
141
161
|
}
|
|
142
162
|
else if (!sentFromReplacement) {
|
|
143
163
|
await options.refreshSessionResources();
|
|
144
|
-
sendCommandResult(pi,
|
|
164
|
+
sendCommandResult(pi, formatNewSessionReply(ctx.sessionManager.getSessionId()));
|
|
145
165
|
}
|
|
146
166
|
},
|
|
147
167
|
});
|
|
@@ -150,14 +170,7 @@ ${available}`);
|
|
|
150
170
|
handler: async (args, ctx) => {
|
|
151
171
|
const customInstructions = args.trim() || undefined;
|
|
152
172
|
const result = await runCompact(ctx, customInstructions);
|
|
153
|
-
sendCommandResult(pi,
|
|
154
|
-
|
|
155
|
-
- 压缩前 tokens:\`${result.tokensBefore}\`
|
|
156
|
-
- 摘要:
|
|
157
|
-
|
|
158
|
-
\`\`\`text
|
|
159
|
-
${result.summary}
|
|
160
|
-
\`\`\``);
|
|
173
|
+
sendCommandResult(pi, buildCompactText(result));
|
|
161
174
|
},
|
|
162
175
|
});
|
|
163
176
|
};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { SubAgentToolDetails } from "
|
|
2
|
-
import type { AssistantContentPart, AssistantEventMessage, AssistantUsageMessage, AutoCompactionEndEvent, AutoCompactionStartEvent, AutoRetryStartEvent, MessageEndEvent, MessageStartEvent, ToolExecutionEndEvent, ToolExecutionStartEvent, ToolExecutionUpdateEvent, TurnEndEvent } from "
|
|
1
|
+
import type { SubAgentToolDetails } from "../../tools/subagent.js";
|
|
2
|
+
import type { AssistantContentPart, AssistantEventMessage, AssistantUsageMessage, AutoCompactionEndEvent, AutoCompactionStartEvent, AutoRetryStartEvent, MessageEndEvent, MessageStartEvent, ToolExecutionEndEvent, ToolExecutionStartEvent, ToolExecutionUpdateEvent, TurnEndEvent } from "../types.js";
|
|
3
3
|
export declare function isAssistantEventMessage(value: unknown): value is AssistantEventMessage;
|
|
4
4
|
export declare function isAssistantUsageMessage(value: unknown): value is AssistantUsageMessage;
|
|
5
5
|
export declare function getLastAssistantUsage(messages: readonly unknown[]): AssistantUsageMessage | null;
|
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Type guards for the SDK's loosely typed session and message events, so event handlers can narrow
|
|
3
|
+
* them without casts.
|
|
4
|
+
*/
|
|
5
|
+
import { isRecord } from "../../shared/type-guards.js";
|
|
2
6
|
import { COMMAND_RESULT_CUSTOM_TYPE } from "./command-extension.js";
|
|
3
7
|
function isMessageWithRole(value) {
|
|
4
8
|
return isRecord(value) && typeof value.role === "string";
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which model a channel is on: the preferred (active) model, the backup-model switch and its
|
|
3
|
+
* cooldown, resolving the configured backup, and the thinking-level handling that has to stay in
|
|
4
|
+
* step with a model change. Reads the live session through callbacks, since the session is rebuilt
|
|
5
|
+
* on `/new`, fork and task binding.
|
|
6
|
+
*/
|
|
7
|
+
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
|
|
8
|
+
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
9
|
+
import type { AgentSession, ModelRegistry, SettingsManager as SDKSettingsManager } from "@earendil-works/pi-coding-agent";
|
|
10
|
+
import type { PipiclawSettingsManager } from "../../config/settings.js";
|
|
11
|
+
export interface ModelSelectionDeps {
|
|
12
|
+
channelId: string;
|
|
13
|
+
settingsManager: PipiclawSettingsManager;
|
|
14
|
+
getSession: () => AgentSession;
|
|
15
|
+
getSessionSettingsManager: () => SDKSettingsManager;
|
|
16
|
+
getModelRegistry: () => ModelRegistry;
|
|
17
|
+
}
|
|
18
|
+
export declare class ModelSelection {
|
|
19
|
+
private deps;
|
|
20
|
+
/** The preferred model. Replaced from settings once the model registry exists, and by `/model`. */
|
|
21
|
+
activeModel: Model<Api>;
|
|
22
|
+
/** When the primary model last failed and we switched to the backup. null = on primary. */
|
|
23
|
+
private primaryFailedAt;
|
|
24
|
+
constructor(deps: ModelSelectionDeps);
|
|
25
|
+
markPrimaryFailed(): void;
|
|
26
|
+
/** A manual `/model` switch redefines the preferred model and clears fallback state. */
|
|
27
|
+
clearFallbackState(): void;
|
|
28
|
+
/** Set while running on the backup model: what the primary is and when it may be retried. */
|
|
29
|
+
fallbackStatus(current: Model<Api>): {
|
|
30
|
+
primary: string;
|
|
31
|
+
cooldownUntilMs: number;
|
|
32
|
+
} | undefined;
|
|
33
|
+
/**
|
|
34
|
+
* At turn start, if a fallback is active and the primary's cooldown has elapsed,
|
|
35
|
+
* switch back to the preferred model. Silent — no user notice on recovery.
|
|
36
|
+
*/
|
|
37
|
+
maybeRestorePrimaryModel(): Promise<void>;
|
|
38
|
+
setModelWithThinkingPreservation(model: Model<Api>): Promise<void>;
|
|
39
|
+
setThinkingLevelCompat(level: ThinkingLevel): void;
|
|
40
|
+
cycleThinkingLevelCompat(): ThinkingLevel | undefined;
|
|
41
|
+
/**
|
|
42
|
+
* Resolve the configured backup model reference against available models.
|
|
43
|
+
* Returns null when unset, unresolvable/ambiguous, or missing an API key —
|
|
44
|
+
* each case logs a warning and disables fallback for this turn.
|
|
45
|
+
*/
|
|
46
|
+
resolveFallbackModel(): Promise<Model<Api> | null>;
|
|
47
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import * as log from "../../log.js";
|
|
2
|
+
import { getApiKeyForModel } from "../../models/api-keys.js";
|
|
3
|
+
import { PRIMARY_COOLDOWN_MS, shouldRestorePrimary } from "../../models/fallback.js";
|
|
4
|
+
import { findExactModelReferenceMatch, formatModelReference } from "../../models/reference.js";
|
|
5
|
+
import { defaultModel } from "../../models/runtime.js";
|
|
6
|
+
import { errorMessage } from "../../shared/text-utils.js";
|
|
7
|
+
import { cycleThinkingLevelWithConditionalPersist, setModelWithThinkingPreservation, setThinkingLevelWithConditionalPersist, } from "./session-adapter.js";
|
|
8
|
+
export class ModelSelection {
|
|
9
|
+
constructor(deps) {
|
|
10
|
+
this.deps = deps;
|
|
11
|
+
/** The preferred model. Replaced from settings once the model registry exists, and by `/model`. */
|
|
12
|
+
this.activeModel = defaultModel;
|
|
13
|
+
/** When the primary model last failed and we switched to the backup. null = on primary. */
|
|
14
|
+
this.primaryFailedAt = null;
|
|
15
|
+
}
|
|
16
|
+
markPrimaryFailed() {
|
|
17
|
+
this.primaryFailedAt = Date.now();
|
|
18
|
+
}
|
|
19
|
+
/** A manual `/model` switch redefines the preferred model and clears fallback state. */
|
|
20
|
+
clearFallbackState() {
|
|
21
|
+
this.primaryFailedAt = null;
|
|
22
|
+
}
|
|
23
|
+
/** Set while running on the backup model: what the primary is and when it may be retried. */
|
|
24
|
+
fallbackStatus(current) {
|
|
25
|
+
if (formatModelReference(current) === formatModelReference(this.activeModel))
|
|
26
|
+
return undefined;
|
|
27
|
+
return {
|
|
28
|
+
primary: formatModelReference(this.activeModel),
|
|
29
|
+
cooldownUntilMs: (this.primaryFailedAt ?? Date.now()) + PRIMARY_COOLDOWN_MS,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* At turn start, if a fallback is active and the primary's cooldown has elapsed,
|
|
34
|
+
* switch back to the preferred model. Silent — no user notice on recovery.
|
|
35
|
+
*/
|
|
36
|
+
async maybeRestorePrimaryModel() {
|
|
37
|
+
const current = this.deps.getSession().model;
|
|
38
|
+
if (!current || formatModelReference(current) === formatModelReference(this.activeModel)) {
|
|
39
|
+
this.primaryFailedAt = null;
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (!shouldRestorePrimary(this.primaryFailedAt, Date.now())) {
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
try {
|
|
46
|
+
await this.setModelWithThinkingPreservation(this.activeModel);
|
|
47
|
+
this.primaryFailedAt = null;
|
|
48
|
+
log.logInfo(`[${this.deps.channelId}] Restored primary model ${formatModelReference(this.activeModel)}`);
|
|
49
|
+
}
|
|
50
|
+
catch (err) {
|
|
51
|
+
log.logWarn("agent.model.restore_failed", "Primary model restore failed", {
|
|
52
|
+
channelId: this.deps.channelId,
|
|
53
|
+
reason: errorMessage(err),
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
async setModelWithThinkingPreservation(model) {
|
|
58
|
+
await setModelWithThinkingPreservation(this.deps.getSession(), this.deps.getSessionSettingsManager(), model);
|
|
59
|
+
}
|
|
60
|
+
setThinkingLevelCompat(level) {
|
|
61
|
+
setThinkingLevelWithConditionalPersist(this.deps.getSession(), level);
|
|
62
|
+
}
|
|
63
|
+
cycleThinkingLevelCompat() {
|
|
64
|
+
return cycleThinkingLevelWithConditionalPersist(this.deps.getSession());
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Resolve the configured backup model reference against available models.
|
|
68
|
+
* Returns null when unset, unresolvable/ambiguous, or missing an API key —
|
|
69
|
+
* each case logs a warning and disables fallback for this turn.
|
|
70
|
+
*/
|
|
71
|
+
async resolveFallbackModel() {
|
|
72
|
+
const reference = this.deps.settingsManager.getFallbackModelReference();
|
|
73
|
+
if (!reference) {
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
const modelRegistry = this.deps.getModelRegistry();
|
|
77
|
+
await modelRegistry.refresh();
|
|
78
|
+
const available = modelRegistry.getAvailable();
|
|
79
|
+
const { match, ambiguous } = findExactModelReferenceMatch(reference, available);
|
|
80
|
+
if (!match) {
|
|
81
|
+
log.logWarn("agent.model.fallback_unresolved", "Fallback model skipped", {
|
|
82
|
+
channelId: this.deps.channelId,
|
|
83
|
+
fields: { reference, problem: ambiguous ? "ambiguous" : "not found" },
|
|
84
|
+
});
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
try {
|
|
88
|
+
await getApiKeyForModel(modelRegistry, match);
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
log.logWarn("agent.model.fallback_unresolved", "Fallback model skipped", {
|
|
92
|
+
channelId: this.deps.channelId,
|
|
93
|
+
fields: { reference, problem: "no API key" },
|
|
94
|
+
});
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
return match;
|
|
98
|
+
}
|
|
99
|
+
}
|