@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
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* the DingTalk runtime and the terminal TUI can render the same status block
|
|
4
4
|
* from an `AgentRunner` status snapshot. Pure functions, no side effects.
|
|
5
5
|
*/
|
|
6
|
+
import { formatElapsedZh } from "../shared/format.js";
|
|
6
7
|
import { errorMessage } from "../shared/text-utils.js";
|
|
7
8
|
export function formatTokenCount(count) {
|
|
8
9
|
if (count < 1000)
|
|
@@ -11,19 +12,6 @@ export function formatTokenCount(count) {
|
|
|
11
12
|
return `${Math.round(count / 1000)}k`;
|
|
12
13
|
return `${(count / 1_000_000).toFixed(1)}M`;
|
|
13
14
|
}
|
|
14
|
-
export function formatUptime(ms) {
|
|
15
|
-
const totalSeconds = Math.floor(ms / 1000);
|
|
16
|
-
const days = Math.floor(totalSeconds / 86400);
|
|
17
|
-
const hours = Math.floor((totalSeconds % 86400) / 3600);
|
|
18
|
-
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
|
19
|
-
const parts = [];
|
|
20
|
-
if (days > 0)
|
|
21
|
-
parts.push(`${days}d`);
|
|
22
|
-
if (hours > 0)
|
|
23
|
-
parts.push(`${hours}h`);
|
|
24
|
-
parts.push(`${minutes}m`);
|
|
25
|
-
return parts.join(" ");
|
|
26
|
-
}
|
|
27
15
|
export function renderStatus(options) {
|
|
28
16
|
const { runner, version, uptimeMs } = options;
|
|
29
17
|
let runState;
|
|
@@ -39,12 +27,12 @@ export function renderStatus(options) {
|
|
|
39
27
|
if (runner) {
|
|
40
28
|
try {
|
|
41
29
|
const snapshot = runner.getStatusSnapshot();
|
|
42
|
-
let modelLine = `- 模型:\`${snapshot.model}
|
|
30
|
+
let modelLine = `- 模型:\`${snapshot.model}\`(思考档位 \`${snapshot.thinkingLevel}\`)`;
|
|
43
31
|
if (snapshot.fallback) {
|
|
44
32
|
const until = new Date(snapshot.fallback.cooldownUntilMs);
|
|
45
33
|
const hh = String(until.getHours()).padStart(2, "0");
|
|
46
34
|
const mm = String(until.getMinutes()).padStart(2, "0");
|
|
47
|
-
modelLine += ` ·
|
|
35
|
+
modelLine += ` · 正在使用备用模型(主模型 \`${snapshot.fallback.primary}\` 暂停到 ${hh}:${mm})`;
|
|
48
36
|
}
|
|
49
37
|
lines.push(modelLine);
|
|
50
38
|
if (snapshot.contextTokens !== undefined && snapshot.contextWindow > 0) {
|
|
@@ -59,6 +47,6 @@ export function renderStatus(options) {
|
|
|
59
47
|
else {
|
|
60
48
|
lines.push("- 模型:本频道尚未开始过会话");
|
|
61
49
|
}
|
|
62
|
-
lines.push(`- 已运行 ${
|
|
50
|
+
lines.push(`- 已运行 ${formatElapsedZh(uptimeMs)} · 版本 \`${version}\``);
|
|
63
51
|
return lines.join("\n");
|
|
64
52
|
}
|
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Preventive-compaction budget: estimate the tokens an incoming message adds and decide whether to
|
|
3
|
+
* compact before sending, instead of waiting for the provider to reject the request.
|
|
4
|
+
*/
|
|
5
|
+
import { estimateTokens } from "../../shared/format.js";
|
|
2
6
|
export const PREVENTIVE_COMPACTION_THRESHOLD_RATIO = 0.75;
|
|
3
7
|
/**
|
|
4
8
|
* Rough per-image token cost (spec 049), used only to keep the preventive-compaction projection
|
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Formatting helpers for turn progress entries and for clipping over-length user input.
|
|
3
|
+
*/
|
|
4
|
+
import type { ProgressEntryKind } from "../types.js";
|
|
2
5
|
/**
|
|
3
6
|
* Head + tail of an over-length message, with the middle replaced by a marker.
|
|
4
7
|
*
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import * as log from "
|
|
2
|
-
import { errorMessage } from "
|
|
3
|
-
import { withTimeout } from "
|
|
1
|
+
import * as log from "../../log.js";
|
|
2
|
+
import { errorMessage } from "../../shared/text-utils.js";
|
|
3
|
+
import { withTimeout } from "../../shared/with-timeout.js";
|
|
4
4
|
/**
|
|
5
5
|
* Ceiling on how long `drain()` blocks the caller. The queue carries outbound
|
|
6
6
|
* delivery calls plus whatever a session event enqueued (a resource refresh, a
|
|
@@ -20,7 +20,10 @@ export function createRunQueue() {
|
|
|
20
20
|
}
|
|
21
21
|
catch (err) {
|
|
22
22
|
const errMsg = errorMessage(err);
|
|
23
|
-
log.
|
|
23
|
+
log.logWarn("delivery.api.failed", "DingTalk API call failed", {
|
|
24
|
+
reason: errMsg,
|
|
25
|
+
fields: { context: errorContext },
|
|
26
|
+
});
|
|
24
27
|
}
|
|
25
28
|
});
|
|
26
29
|
},
|
|
@@ -34,7 +37,9 @@ export function createRunQueue() {
|
|
|
34
37
|
});
|
|
35
38
|
}
|
|
36
39
|
catch (err) {
|
|
37
|
-
log.
|
|
40
|
+
log.logWarn("delivery.queue.drain_timeout", "Run queue drain deadline exceeded; releasing the turn", {
|
|
41
|
+
reason: errorMessage(err),
|
|
42
|
+
});
|
|
38
43
|
}
|
|
39
44
|
},
|
|
40
45
|
};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { join } from "node:path";
|
|
2
|
-
import { parseLocalTime } from "
|
|
3
|
-
import { countPromptUnits } from "
|
|
4
|
-
import { readActiveTasks } from "
|
|
5
|
-
import { describeTicket } from "
|
|
2
|
+
import { parseLocalTime } from "../../shared/local-time.js";
|
|
3
|
+
import { countPromptUnits } from "../../shared/prompt-units.js";
|
|
4
|
+
import { readActiveTasks } from "../../tasks/contract.js";
|
|
5
|
+
import { describeTicket } from "../../tasks/ticket.js";
|
|
6
6
|
/** Automatic-context share for the in-flight task agenda (spec 026 §5.3). */
|
|
7
7
|
export const TASK_AGENDA_MAX_UNITS = 600;
|
|
8
8
|
/** Relative time to a ticket's due/backstop moment, for a compact agenda line. */
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The per-turn channel capsule. It replaces the channel paths that used to sit in
|
|
3
|
+
* the system prompt: memory/task/event tools are already bound to this channel, so
|
|
4
|
+
* the model only needs the directory when it wants to read a file directly.
|
|
5
|
+
*/
|
|
6
|
+
export declare function renderChannelTurnContext(channelDir: string): string;
|
|
7
|
+
/** Gated by the same master autonomy switch as the task_* tools and the TaskDriver. */
|
|
8
|
+
export declare function buildTaskDigestForTurn(channelDir: string): Promise<string>;
|
|
9
|
+
/**
|
|
10
|
+
* Spec 050, D1: assemble `<memory_bootstrap>` for the first turn of a session — workspace
|
|
11
|
+
* MEMORY.md (whole H2 sections, budgeted) + the channel index (full, or budget-tiered) +
|
|
12
|
+
* today's journal tail.
|
|
13
|
+
*/
|
|
14
|
+
export declare function buildFirstTurnMemoryBootstrap(channelDir: string, workspaceDir: string): Promise<string>;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The dynamic context that rides a turn rather than the system prompt (so every channel in a
|
|
3
|
+
* workspace shares one cached prompt prefix): the channel capsule, the task agenda digest, and the
|
|
4
|
+
* first-turn memory bootstrap.
|
|
5
|
+
*/
|
|
6
|
+
import { readFile } from "node:fs/promises";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { TASK_DIGEST_SETTINGS } from "../../config/settings.js";
|
|
9
|
+
import { buildChannelIndexForBootstrap, clipJournalTailForBootstrap, clipWorkspaceMemoryForBootstrap, } from "../../memory/index-budget.js";
|
|
10
|
+
import { readJournalDay } from "../../memory/journal.js";
|
|
11
|
+
import { renderMemoryBootstrap } from "../../memory/render.js";
|
|
12
|
+
import { listMemoryEntries } from "../../memory/store.js";
|
|
13
|
+
import { localDayKey } from "../../shared/local-time.js";
|
|
14
|
+
import { buildTaskDigest, TASK_AGENDA_MAX_UNITS } from "./task-digest.js";
|
|
15
|
+
/**
|
|
16
|
+
* The per-turn channel capsule. It replaces the channel paths that used to sit in
|
|
17
|
+
* the system prompt: memory/task/event tools are already bound to this channel, so
|
|
18
|
+
* the model only needs the directory when it wants to read a file directly.
|
|
19
|
+
*/
|
|
20
|
+
export function renderChannelTurnContext(channelDir) {
|
|
21
|
+
return [
|
|
22
|
+
"<runtime_turn_context>",
|
|
23
|
+
`Channel directory: ${channelDir}`,
|
|
24
|
+
"The channel `MEMORY.md` index, `memory/`, `journal/` and `tasks/` live there. Prefer the context supplied with this turn and the channel-bound tools; read those files directly only when you need detail they did not provide.",
|
|
25
|
+
"</runtime_turn_context>",
|
|
26
|
+
].join("\n");
|
|
27
|
+
}
|
|
28
|
+
/** Gated by the same master autonomy switch as the task_* tools and the TaskDriver. */
|
|
29
|
+
export function buildTaskDigestForTurn(channelDir) {
|
|
30
|
+
return buildTaskDigest({
|
|
31
|
+
channelDir,
|
|
32
|
+
maxTasks: TASK_DIGEST_SETTINGS.maxTasks,
|
|
33
|
+
maxChars: TASK_DIGEST_SETTINGS.maxChars,
|
|
34
|
+
maxUnits: TASK_AGENDA_MAX_UNITS,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Spec 050, D1: assemble `<memory_bootstrap>` for the first turn of a session — workspace
|
|
39
|
+
* MEMORY.md (whole H2 sections, budgeted) + the channel index (full, or budget-tiered) +
|
|
40
|
+
* today's journal tail.
|
|
41
|
+
*/
|
|
42
|
+
export async function buildFirstTurnMemoryBootstrap(channelDir, workspaceDir) {
|
|
43
|
+
const readOptionalFile = async (path) => {
|
|
44
|
+
try {
|
|
45
|
+
return await readFile(path, "utf-8");
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return "";
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
const today = localDayKey();
|
|
52
|
+
const [entries, workspaceMemory, journalToday] = await Promise.all([
|
|
53
|
+
listMemoryEntries(channelDir).catch(() => []),
|
|
54
|
+
readOptionalFile(join(workspaceDir, "MEMORY.md")),
|
|
55
|
+
readJournalDay(channelDir, today).catch(() => ""),
|
|
56
|
+
]);
|
|
57
|
+
const index = buildChannelIndexForBootstrap(entries);
|
|
58
|
+
const journalTail = clipJournalTailForBootstrap(journalToday);
|
|
59
|
+
return renderMemoryBootstrap({
|
|
60
|
+
workspaceMemory: clipWorkspaceMemoryForBootstrap(workspaceMemory),
|
|
61
|
+
channelIndex: entries.length > 0 ? index.text : "",
|
|
62
|
+
journal: journalTail ? { date: today, text: journalTail } : undefined,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turn-failure classification for the user's error bubble (spec 053, D5.1).
|
|
3
|
+
*
|
|
4
|
+
* A raw provider error ("401 invalid x-api-key", "429 rate_limit_error", "prompt is too long")
|
|
5
|
+
* tells the user nothing they can act on. The bubble now leads with a class and the one or two
|
|
6
|
+
* things the user (or the deployer, on the server) can actually do about it; the raw text is kept
|
|
7
|
+
* as a short quoted line for whoever has to debug it.
|
|
8
|
+
*
|
|
9
|
+
* Only stable features are matched — HTTP status codes and the phrases providers have used for
|
|
10
|
+
* years. Anything unrecognised is `other`, which still carries a next step.
|
|
11
|
+
*/
|
|
12
|
+
export type TurnErrorKind = "auth" | "rate_limit" | "context_overflow" | "network" | "other";
|
|
13
|
+
export declare function classifyTurnError(message: string): TurnErrorKind;
|
|
14
|
+
/** What the user is told for each class: a reason (absent for `other`) and what to do next. */
|
|
15
|
+
export declare function describeTurnError(kind: TurnErrorKind): {
|
|
16
|
+
reason?: string;
|
|
17
|
+
nextStep: string;
|
|
18
|
+
};
|
|
19
|
+
export interface TurnErrorReplyInput {
|
|
20
|
+
errorMessage: string;
|
|
21
|
+
/** A failed recovery compaction whose error differs from the turn's own. */
|
|
22
|
+
compactionError?: string;
|
|
23
|
+
/** The fallback model already tried, when the runner switched to one. */
|
|
24
|
+
fallbackRef?: string;
|
|
25
|
+
}
|
|
26
|
+
/** The error bubble: class + next step first, the raw provider text last (spec 053, D5.1). */
|
|
27
|
+
export declare function renderTurnErrorReply(input: TurnErrorReplyInput): string;
|
|
28
|
+
/** The progress line for a failed automatic compaction. */
|
|
29
|
+
export declare function renderCompactionFailure(errorMessage: string): string;
|
|
30
|
+
/** The line shown when the runner switches to the fallback model mid-turn; the raw error goes to the log. */
|
|
31
|
+
export declare function renderFallbackSwitch(from: string, to: string, errorMessage: string): string;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
const PATTERNS = [
|
|
2
|
+
[
|
|
3
|
+
"auth",
|
|
4
|
+
/\b40[13]\b|unauthori[sz]ed|forbidden|invalid[ _-]?(?:x-)?api[ _-]?key|incorrect api key|authentication[ _-]?(?:error|failed)|(?:token|credential)s? (?:has |have )?expired/i,
|
|
5
|
+
],
|
|
6
|
+
[
|
|
7
|
+
"context_overflow",
|
|
8
|
+
/context[ _-]?length|context window|too many tokens|prompt is too long|input is too long|maximum context|exceeds? the (?:model's )?(?:maximum|context)/i,
|
|
9
|
+
],
|
|
10
|
+
[
|
|
11
|
+
"rate_limit",
|
|
12
|
+
/\b429\b|\b529\b|rate[ _-]?limit|too many requests|quota|insufficient[ _-]?(?:quota|balance|credit|funds)|overloaded/i,
|
|
13
|
+
],
|
|
14
|
+
[
|
|
15
|
+
"network",
|
|
16
|
+
/ETIMEDOUT|ECONNRESET|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|EPIPE|socket hang up|fetch failed|network error|timed out|\b50[0234]\b|internal server error|bad gateway|service unavailable|gateway timeout/i,
|
|
17
|
+
],
|
|
18
|
+
];
|
|
19
|
+
export function classifyTurnError(message) {
|
|
20
|
+
for (const [kind, pattern] of PATTERNS) {
|
|
21
|
+
if (pattern.test(message))
|
|
22
|
+
return kind;
|
|
23
|
+
}
|
|
24
|
+
return "other";
|
|
25
|
+
}
|
|
26
|
+
/** What the user is told for each class: a reason (absent for `other`) and what to do next. */
|
|
27
|
+
export function describeTurnError(kind) {
|
|
28
|
+
switch (kind) {
|
|
29
|
+
case "auth":
|
|
30
|
+
return {
|
|
31
|
+
reason: "模型凭据无效或已过期。",
|
|
32
|
+
nextStep: "请部署者在服务器上执行 `pipiclaw auth login`,或用 `/model` 换一个模型。",
|
|
33
|
+
};
|
|
34
|
+
case "rate_limit":
|
|
35
|
+
return { reason: "模型暂时限流或额度不足。", nextStep: "稍后重发,或用 `/model` 换一个模型。" };
|
|
36
|
+
case "context_overflow":
|
|
37
|
+
return { reason: "会话上下文已满。", nextStep: "用 `/compact` 压缩,或用 `/new` 开新会话。" };
|
|
38
|
+
case "network":
|
|
39
|
+
return { reason: "连不上模型服务。", nextStep: "稍后重发;持续出现请检查服务器网络或代理。" };
|
|
40
|
+
case "other":
|
|
41
|
+
return { nextStep: "可以重发一次;持续出现请用 `/status` 查看模型状态。" };
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function quoteRaw(text) {
|
|
45
|
+
const flat = text.replace(/`/g, "'").replace(/\s+/g, " ").trim();
|
|
46
|
+
return `\`${flat.length > 240 ? `${flat.slice(0, 239)}…` : flat}\``;
|
|
47
|
+
}
|
|
48
|
+
/** The error bubble: class + next step first, the raw provider text last (spec 053, D5.1). */
|
|
49
|
+
export function renderTurnErrorReply(input) {
|
|
50
|
+
const { reason, nextStep } = describeTurnError(classifyTurnError(input.errorMessage));
|
|
51
|
+
const lines = [reason ? `处理失败:${reason}` : "处理失败。", nextStep];
|
|
52
|
+
if (input.fallbackRef)
|
|
53
|
+
lines.push(`已切换备用模型 \`${input.fallbackRef}\` 重试,仍失败。`);
|
|
54
|
+
lines.push(`原始错误:${quoteRaw(input.errorMessage)}`);
|
|
55
|
+
if (input.compactionError)
|
|
56
|
+
lines.push(`压缩重试的错误:${quoteRaw(input.compactionError)}`);
|
|
57
|
+
return lines.join("\n");
|
|
58
|
+
}
|
|
59
|
+
/** The progress line for a failed automatic compaction. */
|
|
60
|
+
export function renderCompactionFailure(errorMessage) {
|
|
61
|
+
const { reason } = describeTurnError(classifyTurnError(errorMessage));
|
|
62
|
+
return reason ? `上下文压缩失败:${reason}` : "上下文压缩失败。";
|
|
63
|
+
}
|
|
64
|
+
/** The line shown when the runner switches to the fallback model mid-turn; the raw error goes to the log. */
|
|
65
|
+
export function renderFallbackSwitch(from, to, errorMessage) {
|
|
66
|
+
const { reason } = describeTurnError(classifyTurnError(errorMessage));
|
|
67
|
+
return `模型 \`${from}\` 请求失败${reason ? `:${reason}` : "。"}改用 \`${to}\` 重试…`;
|
|
68
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { ChannelContext } from "../../channel/channel-context.js";
|
|
2
|
+
import type { UsageLedger } from "../../usage/ledger.js";
|
|
3
|
+
import type { ModelSelection } from "../session/model-selection.js";
|
|
4
|
+
import type { SessionHost } from "../session/session-host.js";
|
|
5
|
+
import type { RunState } from "../types.js";
|
|
6
|
+
import type { createRunQueue } from "./run-queue.js";
|
|
7
|
+
import type { TurnHandle, TurnStateMachine } from "./turn-state.js";
|
|
8
|
+
export interface TurnFinisherDeps {
|
|
9
|
+
channelId: string;
|
|
10
|
+
channelDir: string;
|
|
11
|
+
host: SessionHost;
|
|
12
|
+
models: ModelSelection;
|
|
13
|
+
ledger: UsageLedger;
|
|
14
|
+
turnState: TurnStateMachine;
|
|
15
|
+
/** The live run state: `ChannelRunner` replaces it at the start of every run. */
|
|
16
|
+
getRunState: () => RunState;
|
|
17
|
+
flushMemoryActivity: () => Promise<void>;
|
|
18
|
+
/** Release the turn, for a `run()` that owned the whole turn itself (no transport wrapper). */
|
|
19
|
+
endTurn: () => void;
|
|
20
|
+
}
|
|
21
|
+
export declare class TurnFinisher {
|
|
22
|
+
private readonly deps;
|
|
23
|
+
private readonly channelId;
|
|
24
|
+
private readonly channelDir;
|
|
25
|
+
private readonly host;
|
|
26
|
+
private readonly models;
|
|
27
|
+
private readonly ledger;
|
|
28
|
+
private readonly turnState;
|
|
29
|
+
constructor(deps: TurnFinisherDeps);
|
|
30
|
+
private get runState();
|
|
31
|
+
/**
|
|
32
|
+
* The epilogue shared by every exit path out of `run()`'s try/catch: debug dump, delivery of
|
|
33
|
+
* whatever final message the turn settled on, usage/ledger accounting, the end-of-turn memory
|
|
34
|
+
* flush, and clearing run state. Pulled out of `run()` itself only to keep that method's main
|
|
35
|
+
* line (prepare → prompt with fallback) readable; every input here is `run()`-local, not
|
|
36
|
+
* instance state, so it is threaded through explicitly rather than promoted to a field.
|
|
37
|
+
*/
|
|
38
|
+
finish(input: {
|
|
39
|
+
ctx: ChannelContext;
|
|
40
|
+
ownTurn: TurnHandle;
|
|
41
|
+
implicitTurn: boolean;
|
|
42
|
+
promptSubmitted: boolean;
|
|
43
|
+
runQueue: ReturnType<typeof createRunQueue>;
|
|
44
|
+
fallbackAttempted: boolean;
|
|
45
|
+
fallbackTargetRef: string | undefined;
|
|
46
|
+
promptText: string;
|
|
47
|
+
durableMemoryBootstrapText: string;
|
|
48
|
+
taskDigestText: string;
|
|
49
|
+
}): Promise<void>;
|
|
50
|
+
}
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The epilogue of a turn, shared by every exit path out of `ChannelRunner.run()`: the debug dump,
|
|
3
|
+
* delivery of whatever final message the turn settled on, usage and ledger accounting, the
|
|
4
|
+
* end-of-turn memory flush, and clearing run state.
|
|
5
|
+
*/
|
|
6
|
+
import { writeFile } from "fs/promises";
|
|
7
|
+
import { join } from "path";
|
|
8
|
+
import * as log from "../../log.js";
|
|
9
|
+
import { formatModelReference } from "../../models/reference.js";
|
|
10
|
+
import { errorMessage } from "../../shared/text-utils.js";
|
|
11
|
+
import { buildPromptManifest } from "../prompt/manifest.js";
|
|
12
|
+
import { getLastAssistantUsage } from "../session/event-guards.js";
|
|
13
|
+
import { renderTurnErrorReply } from "./turn-error.js";
|
|
14
|
+
function isSilentOutcome(outcome) {
|
|
15
|
+
return outcome.kind === "silent";
|
|
16
|
+
}
|
|
17
|
+
function isFinalOutcome(outcome) {
|
|
18
|
+
return outcome.kind === "final";
|
|
19
|
+
}
|
|
20
|
+
function getFinalOutcomeText(outcome) {
|
|
21
|
+
return isFinalOutcome(outcome) ? outcome.text : null;
|
|
22
|
+
}
|
|
23
|
+
export class TurnFinisher {
|
|
24
|
+
constructor(deps) {
|
|
25
|
+
this.deps = deps;
|
|
26
|
+
this.channelId = deps.channelId;
|
|
27
|
+
this.channelDir = deps.channelDir;
|
|
28
|
+
this.host = deps.host;
|
|
29
|
+
this.models = deps.models;
|
|
30
|
+
this.ledger = deps.ledger;
|
|
31
|
+
this.turnState = deps.turnState;
|
|
32
|
+
}
|
|
33
|
+
get runState() {
|
|
34
|
+
return this.deps.getRunState();
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The epilogue shared by every exit path out of `run()`'s try/catch: debug dump, delivery of
|
|
38
|
+
* whatever final message the turn settled on, usage/ledger accounting, the end-of-turn memory
|
|
39
|
+
* flush, and clearing run state. Pulled out of `run()` itself only to keep that method's main
|
|
40
|
+
* line (prepare → prompt with fallback) readable; every input here is `run()`-local, not
|
|
41
|
+
* instance state, so it is threaded through explicitly rather than promoted to a field.
|
|
42
|
+
*/
|
|
43
|
+
async finish(input) {
|
|
44
|
+
const { ctx, ownTurn, implicitTurn, promptSubmitted, runQueue, fallbackAttempted, fallbackTargetRef } = input;
|
|
45
|
+
this.turnState.setPhase(ownTurn, "finishing");
|
|
46
|
+
// Debug dump (PIPICLAW_DEBUG=1). Written after the run so `systemPrompt` is the
|
|
47
|
+
// string the provider actually received — base sections, pi's tail, and the boundary
|
|
48
|
+
// footer the prompt extension appends at before_agent_start.
|
|
49
|
+
if (process.env.PIPICLAW_DEBUG) {
|
|
50
|
+
const debugContext = {
|
|
51
|
+
systemPrompt: this.host.lastFinalPrompt ?? this.host.agent.state.systemPrompt,
|
|
52
|
+
promptManifest: this.host.lastPromptBuild
|
|
53
|
+
? buildPromptManifest(this.host.lastPromptBuild, this.host.lastFinalPrompt)
|
|
54
|
+
: undefined,
|
|
55
|
+
messages: this.host.session.messages,
|
|
56
|
+
durableMemoryBootstrap: input.durableMemoryBootstrapText || undefined,
|
|
57
|
+
taskDigest: input.taskDigestText || undefined,
|
|
58
|
+
newUserMessage: input.promptText,
|
|
59
|
+
};
|
|
60
|
+
await writeFile(join(this.channelDir, "last_prompt.json"), JSON.stringify(debugContext, null, 2)).catch((error) => log.logWarn("agent.debug.dump_failed", "last_prompt.json write failed", {
|
|
61
|
+
channelId: this.channelId,
|
|
62
|
+
reason: errorMessage(error),
|
|
63
|
+
}));
|
|
64
|
+
}
|
|
65
|
+
if (!promptSubmitted) {
|
|
66
|
+
const discarded = this.host.session.clearQueue();
|
|
67
|
+
const discardedCount = discarded.steering.length + discarded.followUp.length;
|
|
68
|
+
if (discardedCount > 0) {
|
|
69
|
+
log.logWarn("agent.turn.queue_discarded", "Queued busy messages discarded after run setup failed", {
|
|
70
|
+
channelId: this.channelId,
|
|
71
|
+
fields: { count: discardedCount },
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
await runQueue.drain();
|
|
76
|
+
const finalOutcome = this.runState.finalOutcome;
|
|
77
|
+
const finalOutcomeText = getFinalOutcomeText(finalOutcome);
|
|
78
|
+
try {
|
|
79
|
+
if (this.runState.stopReason === "error" &&
|
|
80
|
+
this.runState.errorMessage &&
|
|
81
|
+
!this.runState.finalResponseDelivered) {
|
|
82
|
+
try {
|
|
83
|
+
const compactionError = this.runState.lastCompactionError;
|
|
84
|
+
await ctx.replaceMessage(renderTurnErrorReply({
|
|
85
|
+
errorMessage: this.runState.errorMessage,
|
|
86
|
+
compactionError: compactionError && compactionError !== this.runState.errorMessage ? compactionError : undefined,
|
|
87
|
+
fallbackRef: fallbackAttempted ? fallbackTargetRef : undefined,
|
|
88
|
+
}));
|
|
89
|
+
}
|
|
90
|
+
catch (err) {
|
|
91
|
+
const errMsg = errorMessage(err);
|
|
92
|
+
log.logWarn("delivery.error_reply.failed", "Error reply failed", {
|
|
93
|
+
channelId: this.channelId,
|
|
94
|
+
reason: errMsg,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
else if (isSilentOutcome(finalOutcome)) {
|
|
99
|
+
try {
|
|
100
|
+
await ctx.deleteMessage();
|
|
101
|
+
log.logInfo(`[${this.channelId}] Silent response ended progress delivery`);
|
|
102
|
+
}
|
|
103
|
+
catch (err) {
|
|
104
|
+
const errMsg = errorMessage(err);
|
|
105
|
+
log.logWarn("delivery.silent_cleanup.failed", "Silent-response cleanup failed", {
|
|
106
|
+
channelId: this.channelId,
|
|
107
|
+
reason: errMsg,
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
else if (this.runState.stopReason === "aborted" && !this.runState.finalResponseDelivered) {
|
|
112
|
+
try {
|
|
113
|
+
await ctx.deleteMessage();
|
|
114
|
+
log.logInfo(`[${this.channelId}] Aborted response discarded active delivery state`);
|
|
115
|
+
}
|
|
116
|
+
catch (err) {
|
|
117
|
+
const errMsg = errorMessage(err);
|
|
118
|
+
log.logWarn("delivery.abort_cleanup.failed", "Aborted-response cleanup failed", {
|
|
119
|
+
channelId: this.channelId,
|
|
120
|
+
reason: errMsg,
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
else if (finalOutcomeText && !this.runState.finalResponseDelivered) {
|
|
125
|
+
try {
|
|
126
|
+
await ctx.replaceMessage(finalOutcomeText);
|
|
127
|
+
}
|
|
128
|
+
catch (err) {
|
|
129
|
+
const errMsg = errorMessage(err);
|
|
130
|
+
log.logWarn("delivery.final_reply.failed", "Final reply replacement failed", {
|
|
131
|
+
channelId: this.channelId,
|
|
132
|
+
reason: errMsg,
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
await ctx.flush();
|
|
137
|
+
}
|
|
138
|
+
finally {
|
|
139
|
+
await ctx.close();
|
|
140
|
+
}
|
|
141
|
+
// Log usage summary. Gated on tokens as well as cost: a local (or pricing-less) model
|
|
142
|
+
// bills nothing, and skipping it here left both the log and the ledger empty.
|
|
143
|
+
if (this.runState.totalUsage.cost.total > 0 || this.runState.totalUsage.total > 0) {
|
|
144
|
+
const lastAssistantMessage = getLastAssistantUsage(this.host.session.messages);
|
|
145
|
+
const contextTokens = lastAssistantMessage
|
|
146
|
+
? lastAssistantMessage.usage.input +
|
|
147
|
+
lastAssistantMessage.usage.output +
|
|
148
|
+
lastAssistantMessage.usage.cacheRead +
|
|
149
|
+
lastAssistantMessage.usage.cacheWrite
|
|
150
|
+
: 0;
|
|
151
|
+
const currentRunModel = this.host.session.model ?? this.models.activeModel;
|
|
152
|
+
const contextWindow = currentRunModel.contextWindow || 200000;
|
|
153
|
+
log.logUsageSummary(this.runState.logCtx, this.runState.totalUsage, contextTokens, contextWindow);
|
|
154
|
+
const responseModel = lastAssistantMessage?.responseModel;
|
|
155
|
+
// Ledger turn entry: assistant-only usage (sub-agents recorded separately),
|
|
156
|
+
// keeping Σ(entries) == real spend with no double counting.
|
|
157
|
+
this.ledger.record({
|
|
158
|
+
channelId: this.channelId,
|
|
159
|
+
kind: "turn",
|
|
160
|
+
model: responseModel ?? formatModelReference(currentRunModel),
|
|
161
|
+
usage: {
|
|
162
|
+
input: this.runState.assistantUsage.input,
|
|
163
|
+
output: this.runState.assistantUsage.output,
|
|
164
|
+
cacheRead: this.runState.assistantUsage.cacheRead,
|
|
165
|
+
cacheWrite: this.runState.assistantUsage.cacheWrite,
|
|
166
|
+
total: this.runState.assistantUsage.total,
|
|
167
|
+
},
|
|
168
|
+
cost: { ...this.runState.assistantUsage.cost },
|
|
169
|
+
});
|
|
170
|
+
if (responseModel &&
|
|
171
|
+
responseModel !== formatModelReference(currentRunModel) &&
|
|
172
|
+
responseModel !== currentRunModel.id) {
|
|
173
|
+
log.logInfo(`[${this.channelId}] Actual model: ${responseModel} (configured: ${formatModelReference(currentRunModel)})`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
// The turn is over, so the channel is about to look idle to the maintenance gates —
|
|
177
|
+
// which is exactly when this state has to be on disk. Everything buffered during the
|
|
178
|
+
// turn lands here in one write.
|
|
179
|
+
await this.deps.flushMemoryActivity();
|
|
180
|
+
// Clear run state
|
|
181
|
+
this.runState.ctx = null;
|
|
182
|
+
this.runState.logCtx = null;
|
|
183
|
+
this.runState.queue = null;
|
|
184
|
+
if (implicitTurn) {
|
|
185
|
+
this.deps.endTurn();
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { Api, ImageContent, Model } from "@earendil-works/pi-ai";
|
|
2
|
+
import { type InboundImage } from "../../channel/channel-event.js";
|
|
3
|
+
export declare function shouldPreserveRawInput(text: string): boolean;
|
|
4
|
+
/**
|
|
5
|
+
* Save a message that exceeds the per-turn input budget so its clipped middle stays reachable.
|
|
6
|
+
*
|
|
7
|
+
* Pasting a long build log or diff is a normal way to start driving work here, and the clip
|
|
8
|
+
* keeps head and tail — which is where the failing frames usually are *not*. Landing the
|
|
9
|
+
* original under the channel directory puts it inside the paths `read` already allows, so
|
|
10
|
+
* recovery is the ordinary paging path rather than a special case.
|
|
11
|
+
*
|
|
12
|
+
* Best-effort: if the write fails the turn still runs on the clipped text, just without a
|
|
13
|
+
* pointer.
|
|
14
|
+
*/
|
|
15
|
+
export declare function persistOversizedInput(channelDir: string, channelId: string, text: string): Promise<string | undefined>;
|
|
16
|
+
export declare function formatUserMessage(text: string, userName?: string, now?: Date): string;
|
|
17
|
+
/**
|
|
18
|
+
* Turn `InboundImage`s (already downloaded and persisted by the transport, spec 049) into the
|
|
19
|
+
* `ImageContent[]` `AgentSession.prompt`/`steer` accept, plus any notices to surface to the
|
|
20
|
+
* user about images that did not make it into this turn.
|
|
21
|
+
*
|
|
22
|
+
* Two gates apply, both fail *open* toward "still deliver the message" rather than dropping
|
|
23
|
+
* the whole turn over one bad attachment:
|
|
24
|
+
*
|
|
25
|
+
* - The current model's `input` capability (spec 049 D7). A model that does not declare
|
|
26
|
+
* `"image"` support has its image blocks silently replaced with a text placeholder by the
|
|
27
|
+
* SDK's provider layer — exactly the failure this spec exists to fix, so it is checked
|
|
28
|
+
* explicitly here rather than trusted to fail loudly on its own. Re-checked on every call
|
|
29
|
+
* (including a mid-turn steer after a model fallback), since a fallback model's capability
|
|
30
|
+
* can differ from the one the turn started with.
|
|
31
|
+
* - A defense-in-depth size re-check against `MAX_INBOUND_IMAGE_BYTES`. The transport already
|
|
32
|
+
* enforces this at download time, but the check is cheap and free of assumptions about how
|
|
33
|
+
* an `InboundImage` reached this method.
|
|
34
|
+
*
|
|
35
|
+
* An image already marked `unsupportedFormat` (sniffing failed at download time) is skipped
|
|
36
|
+
* without its own notice — the `[图片N:格式不支持,已保存]` marker already in the message text
|
|
37
|
+
* covers it.
|
|
38
|
+
*/
|
|
39
|
+
export interface PreparedInboundImages {
|
|
40
|
+
images: ImageContent[];
|
|
41
|
+
notices: string[];
|
|
42
|
+
}
|
|
43
|
+
export declare function prepareInboundImages(images: InboundImage[] | undefined, model: Model<Api>): Promise<PreparedInboundImages>;
|