@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,113 +1,45 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
/**
|
|
2
|
+
* The per-channel agent runner: the public API the transports drive (turn lifecycle, steering, status,
|
|
3
|
+
* retire/dispose), delegating the SDK session to `session/session-host.ts` and the steps of a turn to
|
|
4
|
+
* `turn/`. Owns the turn state machine.
|
|
5
|
+
*/
|
|
6
|
+
import { SessionManager } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { mkdir } from "fs/promises";
|
|
5
8
|
import { dirname, join, resolve } from "path";
|
|
6
|
-
import {
|
|
7
|
-
import { MAX_INBOUND_IMAGE_BYTES } from "../channel/channel-event.js";
|
|
9
|
+
import { resolveActiveSessionFile } from "../channel/active-session-store.js";
|
|
8
10
|
import { resolveProjectScope } from "../channel/project-scope-store.js";
|
|
9
|
-
import { isKnownCommandName,
|
|
11
|
+
import { isKnownCommandName, slashCommandName } from "../commands/catalog.js";
|
|
10
12
|
import * as log from "../log.js";
|
|
11
|
-
import { handleMemoryCommand } from "../memory/commands.js";
|
|
12
|
-
import { buildChannelIndexForBootstrap, clipJournalTailForBootstrap, clipWorkspaceMemoryForBootstrap, } from "../memory/index-budget.js";
|
|
13
|
-
import { readJournalDay } from "../memory/journal.js";
|
|
14
13
|
import { MemoryLifecycle } from "../memory/lifecycle.js";
|
|
15
14
|
import { createMemoryActivityRecorder, } from "../memory/maintenance-state.js";
|
|
16
|
-
import {
|
|
17
|
-
import { listMemoryEntries } from "../memory/store.js";
|
|
18
|
-
import { buildTaskDigest, TASK_AGENDA_MAX_UNITS } from "../memory/task-digest.js";
|
|
15
|
+
import { getMemoryMaintenanceTuning } from "../memory/maintenance-tuning.js";
|
|
19
16
|
import { getApiKeyForModel } from "../models/api-keys.js";
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
17
|
+
import { runPromptWithFallback } from "../models/fallback.js";
|
|
18
|
+
import { formatModelReference } from "../models/reference.js";
|
|
19
|
+
import { defaultModel } from "../models/runtime.js";
|
|
22
20
|
import { resolveProjectAccessPolicy } from "../security/project-scope.js";
|
|
23
|
-
import {
|
|
24
|
-
import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
|
|
25
|
-
import { formatLocalTime, localDayKey, localStampForFilename, parseLocalTime } from "../shared/local-time.js";
|
|
21
|
+
import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
|
|
26
22
|
import { errorMessage } from "../shared/text-utils.js";
|
|
27
|
-
import {
|
|
28
|
-
import { withTimeout } from "../shared/with-timeout.js";
|
|
29
|
-
import { discoverSubAgents } from "../subagents/discovery.js";
|
|
30
|
-
import { TASK_SESSIONS_DIRNAME, taskSessionPath } from "../tasks/session-path.js";
|
|
31
|
-
import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
|
|
32
|
-
import { createPipiclawTools } from "../tools/index.js";
|
|
33
|
-
import { formatSize } from "../tools/truncate.js";
|
|
23
|
+
import { loadPipiclawSkills } from "../skills/loader.js";
|
|
34
24
|
import { getUsageLedger } from "../usage/ledger.js";
|
|
35
|
-
import {
|
|
36
|
-
import {
|
|
37
|
-
import {
|
|
38
|
-
import {
|
|
39
|
-
import {
|
|
40
|
-
import {
|
|
41
|
-
import {
|
|
42
|
-
import {
|
|
43
|
-
import {
|
|
44
|
-
import {
|
|
45
|
-
import {
|
|
46
|
-
import { SessionResourceGate } from "./session-resource-gate.js";
|
|
47
|
-
import { assembleTurnPrompt } from "./turn-prompt.js";
|
|
48
|
-
import { recoverInterruptedTurn } from "./turn-recovery.js";
|
|
49
|
-
import { TurnStateMachine } from "./turn-state.js";
|
|
50
|
-
import { getLastAssistantUsage, isAutoCompactionEndEvent } from "./type-guards.js";
|
|
51
|
-
import { createEmptyRunState, MAX_USER_MESSAGE_CHARS, } from "./types.js";
|
|
52
|
-
import { loadPipiclawSkills, resolvePipiclawSkills } from "./workspace-resources.js";
|
|
53
|
-
function isSilentOutcome(outcome) {
|
|
54
|
-
return outcome.kind === "silent";
|
|
55
|
-
}
|
|
56
|
-
function isFinalOutcome(outcome) {
|
|
57
|
-
return outcome.kind === "final";
|
|
58
|
-
}
|
|
59
|
-
function getFinalOutcomeText(outcome) {
|
|
60
|
-
return isFinalOutcome(outcome) ? outcome.text : null;
|
|
61
|
-
}
|
|
62
|
-
/**
|
|
63
|
-
* Ceilings for the two awaited steps of a session-resource reload. Both reach
|
|
64
|
-
* the network (model/auth re-resolution; the SDK session's own reload) and
|
|
65
|
-
* neither carries a timeout of its own, so a stalled provider used to freeze a
|
|
66
|
-
* reload — and, before the gate detached it, the turn that triggered it. On
|
|
67
|
-
* timeout the reload keeps the resources it already had and logs.
|
|
68
|
-
*/
|
|
69
|
-
const MODEL_REGISTRY_REFRESH_TIMEOUT_MS = 15_000;
|
|
70
|
-
const SESSION_RELOAD_TIMEOUT_MS = 30_000;
|
|
71
|
-
/** The text of a message's `content`, whether it is a bare string or a multimodal part array. */
|
|
72
|
-
function plainTextOf(content) {
|
|
73
|
-
if (typeof content === "string")
|
|
74
|
-
return content;
|
|
75
|
-
if (!Array.isArray(content))
|
|
76
|
-
return "";
|
|
77
|
-
return content
|
|
78
|
-
.map((part) => (isRecord(part) && part.type === "text" && typeof part.text === "string" ? part.text : ""))
|
|
79
|
-
.join("\n");
|
|
80
|
-
}
|
|
81
|
-
/** Task sessions live under `<channelDir>/tasks/.sessions/`; nothing else may be mistaken for one. */
|
|
82
|
-
function isTaskSessionPath(sessionFile) {
|
|
83
|
-
return sessionFile?.replace(/\\/g, "/").includes(`/${TASK_SESSIONS_DIRNAME}/`) === true;
|
|
84
|
-
}
|
|
25
|
+
import { handleBuiltinCommand, requireQueuedMessage } from "./builtin-commands.js";
|
|
26
|
+
import { measureToolSchemas, renderContextReport } from "./prompt/manifest.js";
|
|
27
|
+
import { ModelSelection } from "./session/model-selection.js";
|
|
28
|
+
import { reportSettingsDiagnostics, SessionHost } from "./session/session-host.js";
|
|
29
|
+
import { createRunQueue } from "./turn/run-queue.js";
|
|
30
|
+
import { TurnFinisher } from "./turn/turn-finish.js";
|
|
31
|
+
import { createTurnProgress, TurnPipeline } from "./turn/turn-pipeline.js";
|
|
32
|
+
import { assembleTurnPrompt } from "./turn/turn-prompt.js";
|
|
33
|
+
import { recoverInterruptedTurn } from "./turn/turn-recovery.js";
|
|
34
|
+
import { TurnStateMachine } from "./turn/turn-state.js";
|
|
35
|
+
import { createEmptyRunState, } from "./types.js";
|
|
85
36
|
export class ChannelRunner {
|
|
86
|
-
get agent() {
|
|
87
|
-
return this.session.agent;
|
|
88
|
-
}
|
|
89
|
-
get sessionManager() {
|
|
90
|
-
return this.session.sessionManager;
|
|
91
|
-
}
|
|
92
37
|
constructor(channelId, channelDir, paths, deps) {
|
|
93
38
|
this.ledger = getUsageLedger();
|
|
94
|
-
/**
|
|
95
|
-
* Flips true only once `initializeSession` has fully assigned `this.session`
|
|
96
|
-
* and loaded its resources. Synchronous dispatch-path callers (`isKnownSlashCommand`)
|
|
97
|
-
* must not touch `this.session` before this — the model runtime takes hundreds
|
|
98
|
-
* of ms to build and the first message can arrive first (spec 048 F2).
|
|
99
|
-
*/
|
|
100
|
-
this.sessionInitialized = false;
|
|
101
|
-
this.currentTools = [];
|
|
102
|
-
this.firstTurnMemoryBootstrapPending = true;
|
|
103
|
-
/** Mirror of `tools.tasks.enabled` from the last tools-config load (see buildRuntimeTools). */
|
|
104
|
-
this.tasksEnabled = true;
|
|
105
39
|
/** Single owner of turn state; see TurnPhase in types.ts and TurnStateMachine in turn-state.ts. */
|
|
106
|
-
this.turnState = new TurnStateMachine((message, detail) => log.
|
|
40
|
+
this.turnState = new TurnStateMachine((message, detail) => log.logWarn("agent.session.warning", message, { channelId: this.channelId, reason: detail }));
|
|
107
41
|
/** Set once transport-level `/new` replaces this generation. A retired runner is never reused. */
|
|
108
42
|
this.retired = false;
|
|
109
|
-
/** When the primary model last failed and we switched to the backup. null = on primary. */
|
|
110
|
-
this.primaryFailedAt = null;
|
|
111
43
|
// --- Per run ---
|
|
112
44
|
this.runState = createEmptyRunState();
|
|
113
45
|
this.channelId = channelId;
|
|
@@ -138,7 +70,6 @@ export class ChannelRunner {
|
|
|
138
70
|
this.projectScope = scopeOutcome.scope;
|
|
139
71
|
// Initial skill summaries
|
|
140
72
|
const initialSkills = loadPipiclawSkills(channelDir);
|
|
141
|
-
this.currentSkills = initialSkills;
|
|
142
73
|
// Create session manager, opening whichever session this channel's active-session ref
|
|
143
74
|
// (or the context.jsonl default, for a channel that has never run a topology op) names
|
|
144
75
|
// (spec 043, D1).
|
|
@@ -160,15 +91,30 @@ export class ChannelRunner {
|
|
|
160
91
|
`Back up ${join(channelDir, activeSessionFile)} on the host, move it aside, then use /new to start a fresh session.`);
|
|
161
92
|
}
|
|
162
93
|
if (recoveryOutcome.kind === "repaired") {
|
|
163
|
-
log.
|
|
94
|
+
log.logWarn("agent.turn.repaired", "Interrupted turn repaired on restart", {
|
|
95
|
+
channelId: channelId,
|
|
96
|
+
fields: {
|
|
97
|
+
toolResults: recoveryOutcome.appendedToolResults,
|
|
98
|
+
abortedAssistant: recoveryOutcome.appendedAbortedAssistant,
|
|
99
|
+
},
|
|
100
|
+
});
|
|
164
101
|
}
|
|
165
102
|
this.settingsManager = paths.settingsManager;
|
|
166
|
-
this.
|
|
103
|
+
reportSettingsDiagnostics(this.settingsManager, this.channelId, this.appHomeDir);
|
|
167
104
|
this.memoryActivityRecorder = createMemoryActivityRecorder({
|
|
168
105
|
appHomeDir: this.appHomeDir,
|
|
169
|
-
onError: (channelId, error) => log.
|
|
106
|
+
onError: (channelId, error) => log.logWarn("memory.state.record_failed", "Memory maintenance state record failed", {
|
|
107
|
+
channelId: channelId,
|
|
108
|
+
reason: errorMessage(error),
|
|
109
|
+
}),
|
|
110
|
+
});
|
|
111
|
+
this.models = new ModelSelection({
|
|
112
|
+
channelId: this.channelId,
|
|
113
|
+
settingsManager: this.settingsManager,
|
|
114
|
+
getSession: () => this.session,
|
|
115
|
+
getSessionSettingsManager: () => this.host.sessionSettingsManager,
|
|
116
|
+
getModelRegistry: () => this.host.modelRegistry,
|
|
170
117
|
});
|
|
171
|
-
this.activeModel = defaultModel;
|
|
172
118
|
this.memoryLifecycle = new MemoryLifecycle({
|
|
173
119
|
channelId: this.channelId,
|
|
174
120
|
channelDir: this.channelDir,
|
|
@@ -176,14 +122,61 @@ export class ChannelRunner {
|
|
|
176
122
|
appHomeDir: this.appHomeDir,
|
|
177
123
|
getMessages: () => this.session.messages,
|
|
178
124
|
getSessionEntries: () => this.sessionManager.getBranch(),
|
|
179
|
-
getModel: () => this.session.model ?? this.activeModel,
|
|
180
|
-
resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
|
|
125
|
+
getModel: () => this.session.model ?? this.models.activeModel,
|
|
126
|
+
resolveApiKey: async (model) => getApiKeyForModel(this.host.modelRegistry, model),
|
|
181
127
|
recordMemoryActivity: (event) => this.recordMemoryActivity(event),
|
|
182
128
|
});
|
|
183
|
-
this.
|
|
184
|
-
|
|
129
|
+
this.host = new SessionHost({
|
|
130
|
+
channelId,
|
|
131
|
+
channelDir,
|
|
132
|
+
workspaceDir: this.workspaceDir,
|
|
133
|
+
appHomeDir: this.appHomeDir,
|
|
134
|
+
authConfigPath: this.authConfigPath,
|
|
135
|
+
modelsConfigPath: this.modelsConfigPath,
|
|
136
|
+
onSessionEvent: this.onSessionEvent,
|
|
137
|
+
mediaSender: this.mediaSender,
|
|
138
|
+
projectScope: this.projectScope,
|
|
139
|
+
settingsManager: this.settingsManager,
|
|
140
|
+
loadSecurityConfig: this.loadSecurityConfig,
|
|
141
|
+
executor: this.executor,
|
|
142
|
+
fileStore: this.fileStore,
|
|
143
|
+
jobManager: this.jobManager,
|
|
144
|
+
runManager: this.runManager,
|
|
145
|
+
memoryLifecycle: this.memoryLifecycle,
|
|
146
|
+
models: this.models,
|
|
147
|
+
ledger: this.ledger,
|
|
148
|
+
initialSkills,
|
|
149
|
+
getRunState: () => this.runState,
|
|
150
|
+
markStreaming: () => this.turnState.markStreaming(),
|
|
151
|
+
});
|
|
152
|
+
this.pipeline = new TurnPipeline({
|
|
153
|
+
channelId,
|
|
154
|
+
channelDir,
|
|
155
|
+
workspaceDir: this.workspaceDir,
|
|
156
|
+
host: this.host,
|
|
157
|
+
models: this.models,
|
|
158
|
+
turnState: this.turnState,
|
|
159
|
+
isRetired: () => this.retired,
|
|
160
|
+
getRunState: () => this.runState,
|
|
161
|
+
});
|
|
162
|
+
this.turnFinisher = new TurnFinisher({
|
|
163
|
+
channelId,
|
|
164
|
+
channelDir,
|
|
165
|
+
host: this.host,
|
|
166
|
+
models: this.models,
|
|
167
|
+
ledger: this.ledger,
|
|
168
|
+
turnState: this.turnState,
|
|
169
|
+
getRunState: () => this.runState,
|
|
170
|
+
flushMemoryActivity: () => this.flushMemoryActivity(),
|
|
171
|
+
endTurn: () => this.endTurn(),
|
|
185
172
|
});
|
|
186
|
-
this.
|
|
173
|
+
this.host.start(sessionManager);
|
|
174
|
+
}
|
|
175
|
+
get session() {
|
|
176
|
+
return this.host.session;
|
|
177
|
+
}
|
|
178
|
+
get sessionManager() {
|
|
179
|
+
return this.host.sessionManager;
|
|
187
180
|
}
|
|
188
181
|
// === Public API ===
|
|
189
182
|
beginTurn(taskText) {
|
|
@@ -219,146 +212,39 @@ export class ChannelRunner {
|
|
|
219
212
|
this.turnState.setPhase(ownTurn, "preparing");
|
|
220
213
|
const runQueue = createRunQueue();
|
|
221
214
|
this.runState.queue = runQueue.queue;
|
|
222
|
-
|
|
223
|
-
let fallbackAttempted = false;
|
|
224
|
-
let fallbackTargetRef;
|
|
225
|
-
// Hoisted so the debug dump in `finally` can report the turn as it was actually sent.
|
|
226
|
-
let promptText = "";
|
|
227
|
-
let taskDigestText = "";
|
|
228
|
-
let durableMemoryBootstrapText = "";
|
|
229
|
-
let channelCapsuleText = "";
|
|
230
|
-
let bootstrapPrepared = false;
|
|
215
|
+
const turn = createTurnProgress();
|
|
231
216
|
try {
|
|
232
|
-
await this.ensureSessionReady();
|
|
233
|
-
|
|
217
|
+
await this.host.ensureSessionReady();
|
|
218
|
+
this.host.assertContextHealthy();
|
|
219
|
+
await this.models.maybeRestorePrimaryModel();
|
|
234
220
|
this.memoryLifecycle.noteUserTurnStarted();
|
|
235
|
-
const
|
|
236
|
-
let oversizedInputPath;
|
|
237
|
-
if (normalizedInputLength > MAX_USER_MESSAGE_CHARS) {
|
|
238
|
-
oversizedInputPath = await this.persistOversizedInput(ctx.message.text);
|
|
239
|
-
await ctx.respondInThread(oversizedInputPath
|
|
240
|
-
? `⚠️ 消息过长(${normalizedInputLength} 字符),已截断至约 ${MAX_USER_MESSAGE_CHARS} 字符后处理;完整内容已存到 \`${oversizedInputPath}\`,可以让我 read 该文件查看被省略的部分。`
|
|
241
|
-
: `⚠️ 消息过长(${normalizedInputLength} 字符),已截断至约 ${MAX_USER_MESSAGE_CHARS} 字符后处理。`);
|
|
242
|
-
}
|
|
243
|
-
const clippedInput = clipUserInput(ctx.message.text, MAX_USER_MESSAGE_CHARS, oversizedInputPath);
|
|
244
|
-
const userMessage = this.formatUserMessage(clippedInput, ctx.message.userName);
|
|
245
|
-
const preserveRawInput = this.shouldPreserveRawInput(ctx.message.text);
|
|
221
|
+
const input = await this.pipeline.prepareUserInput(ctx);
|
|
246
222
|
// Ensure channel directory exists
|
|
247
223
|
await mkdir(this.channelDir, { recursive: true });
|
|
248
|
-
|
|
249
|
-
// Channel facts are turn-dynamic by design (spec 025 §7.3): keeping them out of the
|
|
250
|
-
// system prompt is what lets every channel in a workspace share one cached prefix.
|
|
251
|
-
channelCapsuleText = this.renderChannelTurnContext();
|
|
252
|
-
// The task digest reads the whole tasks/ directory and depends on nothing the memory
|
|
253
|
-
// bootstrap below produces, so it runs alongside it rather than queuing behind it.
|
|
254
|
-
// Settled into a result object rather than left as a bare promise: if the bootstrap
|
|
255
|
-
// throws first we would otherwise leave a rejection unobserved, which Node's default
|
|
256
|
-
// policy turns into a process exit. Rethrown at the await, so a digest failure still
|
|
257
|
-
// fails the turn exactly as it did when this ran inline. A task step gets none: its brief
|
|
258
|
-
// already carries its own task, and the channel's other tasks are noise there.
|
|
259
|
-
const taskDigestPromise = (this.tasksEnabled && !this.taskLoop ? this.buildTaskDigestForTurn() : Promise.resolve("")).then((text) => ({ text }), (error) => ({ error }));
|
|
260
|
-
// Spec 050, D1: the memory index is injected in full on the first turn of a session
|
|
261
|
-
// (and the first turn after compaction — see `subscribeToSessionEvents`), never per
|
|
262
|
-
// turn. Mid-session, the model uses `memory_search` to look things up.
|
|
263
|
-
if (this.firstTurnMemoryBootstrapPending) {
|
|
264
|
-
durableMemoryBootstrapText = await this.buildFirstTurnMemoryBootstrap();
|
|
265
|
-
bootstrapPrepared = true;
|
|
266
|
-
}
|
|
267
|
-
const taskDigestResult = await taskDigestPromise;
|
|
268
|
-
if (taskDigestResult.error !== undefined) {
|
|
269
|
-
throw taskDigestResult.error;
|
|
270
|
-
}
|
|
271
|
-
taskDigestText = taskDigestResult.text ?? "";
|
|
272
|
-
}
|
|
224
|
+
const channelCapsule = await this.pipeline.gatherTurnContext(input.preserveRawInput, turn);
|
|
273
225
|
const assembled = assembleTurnPrompt({
|
|
274
|
-
clippedInput,
|
|
275
|
-
userMessage,
|
|
276
|
-
preserveRawInput,
|
|
277
|
-
channelCapsule
|
|
278
|
-
durableMemoryBootstrap: durableMemoryBootstrapText,
|
|
279
|
-
taskDigest: taskDigestText,
|
|
226
|
+
clippedInput: input.clippedInput,
|
|
227
|
+
userMessage: input.userMessage,
|
|
228
|
+
preserveRawInput: input.preserveRawInput,
|
|
229
|
+
channelCapsule,
|
|
230
|
+
durableMemoryBootstrap: turn.durableMemoryBootstrapText,
|
|
231
|
+
taskDigest: turn.taskDigestText,
|
|
280
232
|
});
|
|
281
|
-
promptText = assembled.text;
|
|
233
|
+
turn.promptText = assembled.text;
|
|
282
234
|
// Resolved before the compaction estimate below (which needs the image count) and
|
|
283
235
|
// refreshed inside `setModel` further down if a fallback switches models mid-turn
|
|
284
236
|
// (spec 049 D7) — a model's image support is looked up here explicitly because the
|
|
285
237
|
// SDK's own handling of an unsupported model is to silently replace each image block
|
|
286
238
|
// with a text placeholder.
|
|
287
|
-
|
|
288
|
-
for (const notice of preparedImages.notices) {
|
|
289
|
-
await ctx.respondInThread(notice);
|
|
290
|
-
}
|
|
239
|
+
turn.images = await this.pipeline.prepareTurnImages(ctx);
|
|
291
240
|
// Estimated against the fully assembled prompt (recall + task digest + bootstrap all
|
|
292
241
|
// included above), not just the bare user message — those pieces can add thousands of
|
|
293
242
|
// characters and must count against the projected context usage this guard is checking.
|
|
294
243
|
// Each image adds a fixed per-image estimate on top of the text: three attached photos
|
|
295
244
|
// can by themselves push a turn over the threshold that would trigger this guard.
|
|
296
|
-
await this.maybeRunPreventiveCompactionForIncomingText(promptText,
|
|
245
|
+
await this.pipeline.maybeRunPreventiveCompactionForIncomingText(turn.promptText, turn.images.images.length);
|
|
297
246
|
this.lastTurnContextStats = assembled.stats;
|
|
298
|
-
|
|
299
|
-
prompt: async (text) => {
|
|
300
|
-
try {
|
|
301
|
-
await this.sessionResourceGate.runPrompt(async () => {
|
|
302
|
-
await this.session.prompt(text, preparedImages.images.length > 0 ? { images: preparedImages.images } : undefined);
|
|
303
|
-
promptSubmitted = true;
|
|
304
|
-
if (bootstrapPrepared)
|
|
305
|
-
this.firstTurnMemoryBootstrapPending = false;
|
|
306
|
-
});
|
|
307
|
-
}
|
|
308
|
-
catch (err) {
|
|
309
|
-
this.runState.stopReason = "error";
|
|
310
|
-
this.runState.errorMessage = errorMessage(err);
|
|
311
|
-
log.logEvent("error", "agent.turn.failed", "Runner failed", {
|
|
312
|
-
ctx: this.runState.logCtx ?? { channelId: this.channelId },
|
|
313
|
-
fields: { error: this.runState.errorMessage },
|
|
314
|
-
});
|
|
315
|
-
}
|
|
316
|
-
},
|
|
317
|
-
getRunError: () => ({
|
|
318
|
-
stopReason: this.runState.stopReason,
|
|
319
|
-
errorMessage: this.runState.errorMessage,
|
|
320
|
-
}),
|
|
321
|
-
resetRunError: () => {
|
|
322
|
-
this.runState.stopReason = "stop";
|
|
323
|
-
this.runState.errorMessage = undefined;
|
|
324
|
-
this.runState.finalOutcome = { kind: "none" };
|
|
325
|
-
this.runState.lastCompactionError = undefined;
|
|
326
|
-
},
|
|
327
|
-
getMessages: () => this.agent.state.messages,
|
|
328
|
-
setMessages: (messages) => {
|
|
329
|
-
this.agent.state.messages = messages;
|
|
330
|
-
},
|
|
331
|
-
promptWasSubmitted: () => promptSubmitted,
|
|
332
|
-
getCurrentModelRef: () => formatModelReference(this.session.model ?? this.activeModel),
|
|
333
|
-
resolveFallbackModel: () => this.resolveFallbackModel(),
|
|
334
|
-
setModel: async (model) => {
|
|
335
|
-
await this.setModelWithThinkingPreservation(model);
|
|
336
|
-
// The fallback model's vision support can differ from the one this turn started
|
|
337
|
-
// on; re-resolve against it rather than resend whatever was prepared for the
|
|
338
|
-
// model that just failed.
|
|
339
|
-
preparedImages = await this.prepareInboundImages(ctx.message.images);
|
|
340
|
-
for (const notice of preparedImages.notices) {
|
|
341
|
-
await ctx.respondInThread(notice);
|
|
342
|
-
}
|
|
343
|
-
},
|
|
344
|
-
notifySwitch: (from, to, errorSummary) => {
|
|
345
|
-
fallbackTargetRef = to;
|
|
346
|
-
if (this.runState.logCtx) {
|
|
347
|
-
log.logModelFallback(this.runState.logCtx, from, to, errorSummary);
|
|
348
|
-
}
|
|
349
|
-
const text = `⚠️ 模型 ${from} 出错(${errorSummary}),切换到 ${to} 重试…`;
|
|
350
|
-
if (ctx.progressStyle !== "none") {
|
|
351
|
-
runQueue.queue.enqueue(() => ctx.respond(formatProgressEntry("error", text), false), "fallback switch");
|
|
352
|
-
}
|
|
353
|
-
else {
|
|
354
|
-
runQueue.queue.enqueue(() => ctx.respondInThread(text), "fallback switch");
|
|
355
|
-
}
|
|
356
|
-
},
|
|
357
|
-
markPrimaryFailed: () => {
|
|
358
|
-
this.primaryFailedAt = Date.now();
|
|
359
|
-
},
|
|
360
|
-
};
|
|
361
|
-
fallbackAttempted = await runPromptWithFallback(promptText, fallbackDeps);
|
|
247
|
+
turn.fallbackAttempted = await runPromptWithFallback(turn.promptText, this.pipeline.buildFallbackDeps(ctx, runQueue, turn, ownTurn));
|
|
362
248
|
}
|
|
363
249
|
catch (err) {
|
|
364
250
|
this.runState.stopReason = "error";
|
|
@@ -369,17 +255,17 @@ export class ChannelRunner {
|
|
|
369
255
|
});
|
|
370
256
|
}
|
|
371
257
|
finally {
|
|
372
|
-
await this.
|
|
258
|
+
await this.turnFinisher.finish({
|
|
373
259
|
ctx,
|
|
374
260
|
ownTurn,
|
|
375
261
|
implicitTurn,
|
|
376
|
-
promptSubmitted,
|
|
262
|
+
promptSubmitted: turn.promptSubmitted,
|
|
377
263
|
runQueue,
|
|
378
|
-
fallbackAttempted,
|
|
379
|
-
fallbackTargetRef,
|
|
380
|
-
promptText,
|
|
381
|
-
durableMemoryBootstrapText,
|
|
382
|
-
taskDigestText,
|
|
264
|
+
fallbackAttempted: turn.fallbackAttempted,
|
|
265
|
+
fallbackTargetRef: turn.fallbackTargetRef,
|
|
266
|
+
promptText: turn.promptText,
|
|
267
|
+
durableMemoryBootstrapText: turn.durableMemoryBootstrapText,
|
|
268
|
+
taskDigestText: turn.taskDigestText,
|
|
383
269
|
});
|
|
384
270
|
}
|
|
385
271
|
return {
|
|
@@ -391,189 +277,13 @@ export class ChannelRunner {
|
|
|
391
277
|
silent: this.runState.finalOutcome.kind === "silent",
|
|
392
278
|
};
|
|
393
279
|
}
|
|
394
|
-
/**
|
|
395
|
-
* The epilogue shared by every exit path out of `run()`'s try/catch: debug dump, delivery of
|
|
396
|
-
* whatever final message the turn settled on, usage/ledger accounting, the end-of-turn memory
|
|
397
|
-
* flush, and clearing run state. Pulled out of `run()` itself only to keep that method's main
|
|
398
|
-
* line (prepare → prompt with fallback) readable; every input here is `run()`-local, not
|
|
399
|
-
* instance state, so it is threaded through explicitly rather than promoted to a field.
|
|
400
|
-
*/
|
|
401
|
-
async finishTurn(input) {
|
|
402
|
-
const { ctx, ownTurn, implicitTurn, promptSubmitted, runQueue, fallbackAttempted, fallbackTargetRef } = input;
|
|
403
|
-
this.turnState.setPhase(ownTurn, "finishing");
|
|
404
|
-
// Debug dump (PIPICLAW_DEBUG=1). Written after the run so `systemPrompt` is the
|
|
405
|
-
// string the provider actually received — base sections, pi's tail, and the boundary
|
|
406
|
-
// footer the prompt extension appends at before_agent_start.
|
|
407
|
-
if (process.env.PIPICLAW_DEBUG) {
|
|
408
|
-
const debugContext = {
|
|
409
|
-
systemPrompt: this.lastFinalPrompt ?? this.agent.state.systemPrompt,
|
|
410
|
-
promptManifest: this.lastPromptBuild
|
|
411
|
-
? buildPromptManifest(this.lastPromptBuild, this.lastFinalPrompt)
|
|
412
|
-
: undefined,
|
|
413
|
-
messages: this.session.messages,
|
|
414
|
-
durableMemoryBootstrap: input.durableMemoryBootstrapText || undefined,
|
|
415
|
-
taskDigest: input.taskDigestText || undefined,
|
|
416
|
-
newUserMessage: input.promptText,
|
|
417
|
-
};
|
|
418
|
-
await writeFile(join(this.channelDir, "last_prompt.json"), JSON.stringify(debugContext, null, 2)).catch((error) => log.logWarning(`[${this.channelId}] Failed to write last_prompt.json`, errorMessage(error)));
|
|
419
|
-
}
|
|
420
|
-
if (!promptSubmitted) {
|
|
421
|
-
const discarded = this.session.clearQueue();
|
|
422
|
-
const discardedCount = discarded.steering.length + discarded.followUp.length;
|
|
423
|
-
if (discardedCount > 0) {
|
|
424
|
-
log.logWarning(`[${this.channelId}] Discarded ${discardedCount} queued busy message(s) after run setup failed`);
|
|
425
|
-
}
|
|
426
|
-
}
|
|
427
|
-
await runQueue.drain();
|
|
428
|
-
const finalOutcome = this.runState.finalOutcome;
|
|
429
|
-
const finalOutcomeText = getFinalOutcomeText(finalOutcome);
|
|
430
|
-
try {
|
|
431
|
-
if (this.runState.stopReason === "error" &&
|
|
432
|
-
this.runState.errorMessage &&
|
|
433
|
-
!this.runState.finalResponseDelivered) {
|
|
434
|
-
try {
|
|
435
|
-
const baseErrorSummary = this.runState.errorMessage.length > 240
|
|
436
|
-
? `${this.runState.errorMessage.slice(0, 237)}...`
|
|
437
|
-
: this.runState.errorMessage;
|
|
438
|
-
const compactionSummary = this.runState.lastCompactionError && this.runState.lastCompactionError !== this.runState.errorMessage
|
|
439
|
-
? this.runState.lastCompactionError.length > 240
|
|
440
|
-
? `${this.runState.lastCompactionError.slice(0, 237)}...`
|
|
441
|
-
: this.runState.lastCompactionError
|
|
442
|
-
: undefined;
|
|
443
|
-
const detailLines = [`\`${baseErrorSummary}\``];
|
|
444
|
-
if (compactionSummary) {
|
|
445
|
-
detailLines.push(`恢复尝试:\`${compactionSummary}\``);
|
|
446
|
-
}
|
|
447
|
-
if (fallbackAttempted && fallbackTargetRef) {
|
|
448
|
-
detailLines.push(`已切换备用模型 \`${fallbackTargetRef}\` 重试,仍失败。`);
|
|
449
|
-
}
|
|
450
|
-
await ctx.replaceMessage(`_抱歉,出错了。_\n\n${detailLines.join("\n\n")}`);
|
|
451
|
-
}
|
|
452
|
-
catch (err) {
|
|
453
|
-
const errMsg = errorMessage(err);
|
|
454
|
-
log.logWarning("Failed to post error message", errMsg);
|
|
455
|
-
}
|
|
456
|
-
}
|
|
457
|
-
else if (isSilentOutcome(finalOutcome)) {
|
|
458
|
-
try {
|
|
459
|
-
await ctx.deleteMessage();
|
|
460
|
-
log.logInfo("Silent response - ended progress delivery");
|
|
461
|
-
}
|
|
462
|
-
catch (err) {
|
|
463
|
-
const errMsg = errorMessage(err);
|
|
464
|
-
log.logWarning("Failed to delete message for silent response", errMsg);
|
|
465
|
-
}
|
|
466
|
-
}
|
|
467
|
-
else if (this.runState.stopReason === "aborted" && !this.runState.finalResponseDelivered) {
|
|
468
|
-
try {
|
|
469
|
-
await ctx.deleteMessage();
|
|
470
|
-
log.logInfo("Aborted response - discarded active delivery state");
|
|
471
|
-
}
|
|
472
|
-
catch (err) {
|
|
473
|
-
const errMsg = errorMessage(err);
|
|
474
|
-
log.logWarning("Failed to discard active delivery state after abort", errMsg);
|
|
475
|
-
}
|
|
476
|
-
}
|
|
477
|
-
else if (finalOutcomeText && !this.runState.finalResponseDelivered) {
|
|
478
|
-
try {
|
|
479
|
-
await ctx.replaceMessage(finalOutcomeText);
|
|
480
|
-
}
|
|
481
|
-
catch (err) {
|
|
482
|
-
const errMsg = errorMessage(err);
|
|
483
|
-
log.logWarning("Failed to replace message with final text", errMsg);
|
|
484
|
-
}
|
|
485
|
-
}
|
|
486
|
-
await ctx.flush();
|
|
487
|
-
}
|
|
488
|
-
finally {
|
|
489
|
-
await ctx.close();
|
|
490
|
-
}
|
|
491
|
-
// Log usage summary. Gated on tokens as well as cost: a local (or pricing-less) model
|
|
492
|
-
// bills nothing, and skipping it here left both the log and the ledger empty.
|
|
493
|
-
if (this.runState.totalUsage.cost.total > 0 || this.runState.totalUsage.total > 0) {
|
|
494
|
-
const lastAssistantMessage = getLastAssistantUsage(this.session.messages);
|
|
495
|
-
const contextTokens = lastAssistantMessage
|
|
496
|
-
? lastAssistantMessage.usage.input +
|
|
497
|
-
lastAssistantMessage.usage.output +
|
|
498
|
-
lastAssistantMessage.usage.cacheRead +
|
|
499
|
-
lastAssistantMessage.usage.cacheWrite
|
|
500
|
-
: 0;
|
|
501
|
-
const currentRunModel = this.session.model ?? this.activeModel;
|
|
502
|
-
const contextWindow = currentRunModel.contextWindow || 200000;
|
|
503
|
-
log.logUsageSummary(this.runState.logCtx, this.runState.totalUsage, contextTokens, contextWindow);
|
|
504
|
-
const responseModel = lastAssistantMessage?.responseModel;
|
|
505
|
-
// Ledger turn entry: assistant-only usage (sub-agents recorded separately),
|
|
506
|
-
// keeping Σ(entries) == real spend with no double counting.
|
|
507
|
-
this.ledger.record({
|
|
508
|
-
channelId: this.channelId,
|
|
509
|
-
kind: "turn",
|
|
510
|
-
model: responseModel ?? formatModelReference(currentRunModel),
|
|
511
|
-
usage: {
|
|
512
|
-
input: this.runState.assistantUsage.input,
|
|
513
|
-
output: this.runState.assistantUsage.output,
|
|
514
|
-
cacheRead: this.runState.assistantUsage.cacheRead,
|
|
515
|
-
cacheWrite: this.runState.assistantUsage.cacheWrite,
|
|
516
|
-
total: this.runState.assistantUsage.total,
|
|
517
|
-
},
|
|
518
|
-
cost: { ...this.runState.assistantUsage.cost },
|
|
519
|
-
});
|
|
520
|
-
if (responseModel &&
|
|
521
|
-
responseModel !== formatModelReference(currentRunModel) &&
|
|
522
|
-
responseModel !== currentRunModel.id) {
|
|
523
|
-
log.logInfo(`[${this.channelId}] Actual model: ${responseModel} (configured: ${formatModelReference(currentRunModel)})`);
|
|
524
|
-
}
|
|
525
|
-
}
|
|
526
|
-
// The turn is over, so the channel is about to look idle to the maintenance gates —
|
|
527
|
-
// which is exactly when this state has to be on disk. Everything buffered during the
|
|
528
|
-
// turn lands here in one write.
|
|
529
|
-
await this.flushMemoryActivity();
|
|
530
|
-
// Clear run state
|
|
531
|
-
this.runState.ctx = null;
|
|
532
|
-
this.runState.logCtx = null;
|
|
533
|
-
this.runState.queue = null;
|
|
534
|
-
if (implicitTurn) {
|
|
535
|
-
this.endTurn();
|
|
536
|
-
}
|
|
537
|
-
}
|
|
538
280
|
async handleBuiltinCommand(ctx, command) {
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
case "help":
|
|
546
|
-
await this.sendCommandReply(ctx, this.renderHelpWithDiscovery(command.args), "help");
|
|
547
|
-
return;
|
|
548
|
-
case "context":
|
|
549
|
-
await this.sendCommandReply(ctx, this.renderContextReport(command.args), "context");
|
|
550
|
-
return;
|
|
551
|
-
case "stop":
|
|
552
|
-
await this.sendCommandReply(ctx, "当前没有运行中的回合,`/stop` 只在回合进行中有意义。", "stop");
|
|
553
|
-
return;
|
|
554
|
-
case "steer":
|
|
555
|
-
this.requireQueuedMessage(command.args, "steer");
|
|
556
|
-
await this.sendCommandReply(ctx, "当前没有运行中的回合,直接发消息即可,不用 `/steer`。", "steer");
|
|
557
|
-
return;
|
|
558
|
-
case "followup":
|
|
559
|
-
this.requireQueuedMessage(command.args, "followup");
|
|
560
|
-
await this.sendCommandReply(ctx, "当前没有运行中的回合,直接发消息即可;`/followup` 用于回合进行中排队。", "followup");
|
|
561
|
-
return;
|
|
562
|
-
default: {
|
|
563
|
-
// The stateless report commands (events/tasks/status/usage/subagents/project — see
|
|
564
|
-
// `BUILT_IN_COMMANDS`'s `runnerHandled: false` entries) are routed to their own
|
|
565
|
-
// handlers upstream and never reach here; the narrowed parameter type makes that a
|
|
566
|
-
// compile-time guarantee.
|
|
567
|
-
const _exhaustive = command.name;
|
|
568
|
-
throw new Error(`Unhandled built-in command: ${String(_exhaustive)}`);
|
|
569
|
-
}
|
|
570
|
-
}
|
|
571
|
-
}
|
|
572
|
-
catch (err) {
|
|
573
|
-
const errMsg = errorMessage(err);
|
|
574
|
-
log.logWarning(`[${this.channelId}] Built-in command failed`, errMsg);
|
|
575
|
-
await this.sendCommandReply(ctx, `命令执行失败:${errMsg}`, command.name);
|
|
576
|
-
}
|
|
281
|
+
await handleBuiltinCommand({
|
|
282
|
+
channelId: this.channelId,
|
|
283
|
+
ensureSessionReady: () => this.host.ensureSessionReady(),
|
|
284
|
+
promptTemplates: () => this.session.promptTemplates,
|
|
285
|
+
renderContextReport: (args) => this.renderContextReport(args),
|
|
286
|
+
}, ctx, command);
|
|
577
287
|
}
|
|
578
288
|
/**
|
|
579
289
|
* True if `text` is a slash command the runtime or session layer can handle:
|
|
@@ -587,20 +297,20 @@ export class ChannelRunner {
|
|
|
587
297
|
if (!name) {
|
|
588
298
|
return false;
|
|
589
299
|
}
|
|
590
|
-
if (isKnownCommandName(name, this.currentSkills.skills.map((skill) => skill.name.toLowerCase()))) {
|
|
300
|
+
if (isKnownCommandName(name, this.host.currentSkills.skills.map((skill) => skill.name.toLowerCase()))) {
|
|
591
301
|
return true;
|
|
592
302
|
}
|
|
593
303
|
// Synchronous dispatch-path call: before the session runtime finishes building,
|
|
594
304
|
// fall back to the static catalog + skills only. Misclassifying a prompt template
|
|
595
305
|
// as "unknown" for the first few hundred ms after a runner is created is far
|
|
596
306
|
// cheaper than throwing on the dispatch main path (spec 048 F2/D7).
|
|
597
|
-
if (!this.sessionInitialized) {
|
|
307
|
+
if (!this.host.sessionInitialized) {
|
|
598
308
|
return false;
|
|
599
309
|
}
|
|
600
310
|
return this.session.promptTemplates.some((template) => template.name.toLowerCase() === name);
|
|
601
311
|
}
|
|
602
312
|
async queueSteer(text, userName, images) {
|
|
603
|
-
await this.queueBusyMessage(
|
|
313
|
+
await this.pipeline.queueBusyMessage(requireQueuedMessage(text, "steer"), userName, images);
|
|
604
314
|
}
|
|
605
315
|
async flushMemoryForShutdown() {
|
|
606
316
|
await this.flushMemoryActivity();
|
|
@@ -611,23 +321,15 @@ export class ChannelRunner {
|
|
|
611
321
|
if (this.isBusy()) {
|
|
612
322
|
// `session.dispose()` aborts in-flight work; a busy runner keeps its session and
|
|
613
323
|
// subscription until whoever holds it calls dispose() again once idle.
|
|
614
|
-
log.
|
|
324
|
+
log.logWarn("agent.session.dispose_skipped", "Dispose skipped while busy; session left intact", {
|
|
325
|
+
channelId: this.channelId,
|
|
326
|
+
});
|
|
615
327
|
return;
|
|
616
328
|
}
|
|
617
|
-
|
|
618
|
-
// asynchronously, so a runner disposed the instant after creation may not have one yet.
|
|
619
|
-
await this.sessionReady;
|
|
620
|
-
this.sessionUnsubscribe?.();
|
|
621
|
-
this.sessionUnsubscribe = undefined;
|
|
622
|
-
try {
|
|
623
|
-
this.session.dispose();
|
|
624
|
-
}
|
|
625
|
-
catch (error) {
|
|
626
|
-
log.logWarning(`[${this.channelId}] Session dispose failed`, errorMessage(error));
|
|
627
|
-
}
|
|
329
|
+
await this.host.disposeSession();
|
|
628
330
|
}
|
|
629
331
|
async getMemoryMaintenanceContext() {
|
|
630
|
-
await this.ensureSessionReady();
|
|
332
|
+
await this.host.ensureSessionReady();
|
|
631
333
|
this.settingsManager.reload();
|
|
632
334
|
return {
|
|
633
335
|
channelId: this.channelId,
|
|
@@ -637,26 +339,20 @@ export class ChannelRunner {
|
|
|
637
339
|
// stop at a schedule gate and never call these.
|
|
638
340
|
messages: () => [...this.session.messages],
|
|
639
341
|
sessionEntries: () => [...this.sessionManager.getBranch()],
|
|
640
|
-
model: this.session.model ?? this.activeModel,
|
|
641
|
-
resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
|
|
342
|
+
model: this.session.model ?? this.models.activeModel,
|
|
343
|
+
resolveApiKey: async (model) => getApiKeyForModel(this.host.modelRegistry, model),
|
|
642
344
|
settings: { memoryMaintenance: this.settingsManager.getMemoryMaintenanceSettings() },
|
|
643
345
|
};
|
|
644
346
|
}
|
|
645
347
|
getStatusSnapshot() {
|
|
646
|
-
const model = this.session.model ?? this.activeModel;
|
|
348
|
+
const model = this.session.model ?? this.models.activeModel;
|
|
647
349
|
const contextTokens = this.session.getContextUsage()?.tokens;
|
|
648
|
-
const fallbackActive = formatModelReference(model) !== formatModelReference(this.activeModel);
|
|
649
350
|
return {
|
|
650
351
|
model: formatModelReference(model),
|
|
651
352
|
contextTokens: typeof contextTokens === "number" ? contextTokens : undefined,
|
|
652
353
|
contextWindow: model.contextWindow || 200000,
|
|
653
354
|
thinkingLevel: this.session.thinkingLevel,
|
|
654
|
-
fallback:
|
|
655
|
-
? {
|
|
656
|
-
primary: formatModelReference(this.activeModel),
|
|
657
|
-
cooldownUntilMs: (this.primaryFailedAt ?? Date.now()) + PRIMARY_COOLDOWN_MS,
|
|
658
|
-
}
|
|
659
|
-
: undefined,
|
|
355
|
+
fallback: this.models.fallbackStatus(model),
|
|
660
356
|
};
|
|
661
357
|
}
|
|
662
358
|
async abort() {
|
|
@@ -682,18 +378,14 @@ export class ChannelRunner {
|
|
|
682
378
|
// so late events from the old provider cannot overwrite the new session's response.
|
|
683
379
|
void this.runState.ctx?.close().catch(() => undefined);
|
|
684
380
|
this.forceEndTurn("superseded by /new");
|
|
685
|
-
const retireLiveSession = () =>
|
|
686
|
-
this.sessionUnsubscribe?.();
|
|
687
|
-
this.sessionUnsubscribe = undefined;
|
|
688
|
-
this.session.dispose();
|
|
689
|
-
};
|
|
381
|
+
const retireLiveSession = () => this.host.retireLiveSession();
|
|
690
382
|
if (this.session) {
|
|
691
383
|
retireLiveSession();
|
|
692
384
|
}
|
|
693
385
|
else {
|
|
694
386
|
// A second message can issue `/new` while this generation is still initializing.
|
|
695
387
|
// Let construction settle in the background, then immediately tear it down.
|
|
696
|
-
void this.sessionReady.then(retireLiveSession, () => undefined);
|
|
388
|
+
void this.host.sessionReady.then(retireLiveSession, () => undefined);
|
|
697
389
|
}
|
|
698
390
|
}
|
|
699
391
|
/**
|
|
@@ -702,77 +394,49 @@ export class ChannelRunner {
|
|
|
702
394
|
* often the larger half), and the last turn's dynamic context.
|
|
703
395
|
*/
|
|
704
396
|
renderContextReport(args = "") {
|
|
705
|
-
const build = this.lastPromptBuild ?? this.buildSystemPrompt();
|
|
397
|
+
const build = this.host.lastPromptBuild ?? this.host.buildSystemPrompt();
|
|
706
398
|
return renderContextReport({
|
|
707
399
|
build,
|
|
708
|
-
skills: this.currentSkills.skills.map((skill) => ({ name: skill.name, description: skill.description })),
|
|
709
|
-
finalPrompt: this.lastFinalPrompt,
|
|
710
|
-
toolNames: this.currentTools.map((tool) => tool.name),
|
|
711
|
-
toolSchemas: measureToolSchemas(this.currentTools),
|
|
712
|
-
soul: this.lastWorkspaceResources?.soul,
|
|
713
|
-
agents: this.lastWorkspaceResources?.agents,
|
|
400
|
+
skills: this.host.currentSkills.skills.map((skill) => ({ name: skill.name, description: skill.description })),
|
|
401
|
+
finalPrompt: this.host.lastFinalPrompt,
|
|
402
|
+
toolNames: this.host.currentTools.map((tool) => tool.name),
|
|
403
|
+
toolSchemas: measureToolSchemas(this.host.currentTools),
|
|
404
|
+
soul: this.host.lastWorkspaceResources?.soul,
|
|
405
|
+
agents: this.host.lastWorkspaceResources?.agents,
|
|
714
406
|
lastTurn: this.lastTurnContextStats,
|
|
715
407
|
detail: args.trim().toLowerCase() === "detail",
|
|
716
408
|
});
|
|
717
409
|
}
|
|
718
|
-
/**
|
|
719
|
-
* `/help` — the static per-command listing from `commands.ts`, plus (top-level only) the
|
|
720
|
-
* prompt templates this session can actually invoke via `/<template-name>`. Workspace skills
|
|
721
|
-
* have their own dedicated command (`/skills`) and are deliberately not duplicated here.
|
|
722
|
-
* Prompt templates aren't knowable to `renderBuiltInHelp` itself (it is a pure function with
|
|
723
|
-
* no session state), so the runner appends them here (review 2026-08-24 §1.9).
|
|
724
|
-
*/
|
|
725
|
-
renderHelpWithDiscovery(args) {
|
|
726
|
-
const help = renderBuiltInHelp(args);
|
|
727
|
-
if (args.trim()) {
|
|
728
|
-
return help;
|
|
729
|
-
}
|
|
730
|
-
const sections = [help];
|
|
731
|
-
if (this.session.promptTemplates.length > 0) {
|
|
732
|
-
sections.push(`**Prompt templates**\n\n${this.session.promptTemplates
|
|
733
|
-
.map((template) => `- \`/${template.name}\``)
|
|
734
|
-
.join("\n")}`);
|
|
735
|
-
}
|
|
736
|
-
return sections.join("\n\n");
|
|
737
|
-
}
|
|
738
410
|
/** `/subagents list`'s role-directory health tail — whatever this runner already discovered. */
|
|
739
411
|
getSubAgentDiscoverySnapshot() {
|
|
740
|
-
return this.subAgentDiscovery;
|
|
412
|
+
return this.host.subAgentDiscovery;
|
|
741
413
|
}
|
|
742
|
-
// === Private helpers ===
|
|
743
414
|
/**
|
|
744
|
-
*
|
|
745
|
-
* the
|
|
746
|
-
*
|
|
415
|
+
* Bind this runner to a task cycle's own session (spec 051, D3/INV-5): task work must not
|
|
416
|
+
* accumulate in the channel's chat transcript, so each task turn runs in its own bounded session
|
|
417
|
+
* while turn state, `/stop` and delivery stay exactly where they already are.
|
|
747
418
|
*/
|
|
748
|
-
|
|
749
|
-
return
|
|
750
|
-
"<runtime_turn_context>",
|
|
751
|
-
`Channel directory: ${this.channelDir}`,
|
|
752
|
-
"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.",
|
|
753
|
-
"</runtime_turn_context>",
|
|
754
|
-
].join("\n");
|
|
419
|
+
bindTaskSession(taskId) {
|
|
420
|
+
return this.host.bindTaskSession(taskId);
|
|
755
421
|
}
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
await ctx.flush();
|
|
764
|
-
}
|
|
422
|
+
/** Return to the channel's chat session after a task step. Safe to call when already bound. */
|
|
423
|
+
bindChatSession() {
|
|
424
|
+
return this.host.bindChatSession();
|
|
425
|
+
}
|
|
426
|
+
/** Which task loop this runner is currently bound to, if any. */
|
|
427
|
+
getTaskLoop() {
|
|
428
|
+
return this.host.taskLoop;
|
|
765
429
|
}
|
|
430
|
+
// === Private helpers ===
|
|
766
431
|
/**
|
|
767
432
|
* Buffer one activity event. The write itself is batched by the recorder (see
|
|
768
433
|
* `createMemoryActivityRecorder`); `run()` flushes at the end of every turn, which is the
|
|
769
434
|
* point the maintenance gates actually start looking at this state.
|
|
770
435
|
*/
|
|
771
436
|
recordMemoryActivity(event) {
|
|
772
|
-
const maintenanceSettings = this.settingsManager.getMemoryMaintenanceSettings();
|
|
773
437
|
const eventTime = parseLocalTime(event.timestamp);
|
|
774
438
|
const eligibleAfter = eventTime !== undefined
|
|
775
|
-
? formatLocalTime(new Date(eventTime + Math.max(0,
|
|
439
|
+
? formatLocalTime(new Date(eventTime + Math.max(0, getMemoryMaintenanceTuning().minIdleMinutesBeforeLlmWork) * 60_000))
|
|
776
440
|
: undefined;
|
|
777
441
|
this.memoryActivityRecorder.record({ ...event, eligibleAfter });
|
|
778
442
|
}
|
|
@@ -782,139 +446,11 @@ export class ChannelRunner {
|
|
|
782
446
|
await this.memoryActivityRecorder.flush(this.channelId);
|
|
783
447
|
}
|
|
784
448
|
catch (error) {
|
|
785
|
-
log.
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
const trimmedText = text.trim();
|
|
790
|
-
if (!trimmedText) {
|
|
791
|
-
throw new Error(`/${commandName} requires a message.`);
|
|
792
|
-
}
|
|
793
|
-
return trimmedText;
|
|
794
|
-
}
|
|
795
|
-
shouldPreserveRawInput(text) {
|
|
796
|
-
return text.trim().startsWith("/");
|
|
797
|
-
}
|
|
798
|
-
/**
|
|
799
|
-
* Save a message that exceeds the per-turn input budget so its clipped middle stays reachable.
|
|
800
|
-
*
|
|
801
|
-
* Pasting a long build log or diff is a normal way to start driving work here, and the clip
|
|
802
|
-
* keeps head and tail — which is where the failing frames usually are *not*. Landing the
|
|
803
|
-
* original under the channel directory puts it inside the paths `read` already allows, so
|
|
804
|
-
* recovery is the ordinary paging path rather than a special case.
|
|
805
|
-
*
|
|
806
|
-
* Best-effort: if the write fails the turn still runs on the clipped text, just without a
|
|
807
|
-
* pointer.
|
|
808
|
-
*/
|
|
809
|
-
async persistOversizedInput(text) {
|
|
810
|
-
try {
|
|
811
|
-
const dir = join(this.channelDir, "inbox");
|
|
812
|
-
await mkdir(dir, { recursive: true });
|
|
813
|
-
const path = join(dir, `message-${localStampForFilename()}.txt`);
|
|
814
|
-
await writeFile(path, text.replace(/\r/g, ""), { mode: 0o600 });
|
|
815
|
-
return path;
|
|
816
|
-
}
|
|
817
|
-
catch (error) {
|
|
818
|
-
log.logWarning("Could not persist oversized user message", errorMessage(error));
|
|
819
|
-
return undefined;
|
|
820
|
-
}
|
|
821
|
-
}
|
|
822
|
-
formatUserMessage(text, userName, now = new Date()) {
|
|
823
|
-
return `[${formatLocalTime(now)}] [${userName || "unknown"}]: ${text}`;
|
|
824
|
-
}
|
|
825
|
-
/**
|
|
826
|
-
* Turn `InboundImage`s (already downloaded and persisted by the transport, spec 049) into the
|
|
827
|
-
* `ImageContent[]` `AgentSession.prompt`/`steer` accept, plus any notices to surface to the
|
|
828
|
-
* user about images that did not make it into this turn.
|
|
829
|
-
*
|
|
830
|
-
* Two gates apply, both fail *open* toward "still deliver the message" rather than dropping
|
|
831
|
-
* the whole turn over one bad attachment:
|
|
832
|
-
*
|
|
833
|
-
* - The current model's `input` capability (spec 049 D7). A model that does not declare
|
|
834
|
-
* `"image"` support has its image blocks silently replaced with a text placeholder by the
|
|
835
|
-
* SDK's provider layer — exactly the failure this spec exists to fix, so it is checked
|
|
836
|
-
* explicitly here rather than trusted to fail loudly on its own. Re-checked on every call
|
|
837
|
-
* (including a mid-turn steer after a model fallback), since a fallback model's capability
|
|
838
|
-
* can differ from the one the turn started with.
|
|
839
|
-
* - A defense-in-depth size re-check against `MAX_INBOUND_IMAGE_BYTES`. The transport already
|
|
840
|
-
* enforces this at download time, but the check is cheap and free of assumptions about how
|
|
841
|
-
* an `InboundImage` reached this method.
|
|
842
|
-
*
|
|
843
|
-
* An image already marked `unsupportedFormat` (sniffing failed at download time) is skipped
|
|
844
|
-
* without its own notice — the `[图片N:格式不支持,已保存]` marker already in the message text
|
|
845
|
-
* covers it.
|
|
846
|
-
*/
|
|
847
|
-
async prepareInboundImages(images) {
|
|
848
|
-
if (!images || images.length === 0) {
|
|
849
|
-
return { images: [], notices: [] };
|
|
850
|
-
}
|
|
851
|
-
const model = this.session.model ?? this.activeModel;
|
|
852
|
-
if (!model.input.includes("image")) {
|
|
853
|
-
const modelRef = formatModelReference(model);
|
|
854
|
-
return {
|
|
855
|
-
images: [],
|
|
856
|
-
notices: [
|
|
857
|
-
`⚠️ 当前模型 ${modelRef} 不支持图片输入,收到的图片已保存但未加入本轮上下文:\n` +
|
|
858
|
-
images.map((image) => `- \`${image.path}\``).join("\n") +
|
|
859
|
-
"\n可以切换到支持视觉的模型后让我 read 该文件。",
|
|
860
|
-
],
|
|
861
|
-
};
|
|
862
|
-
}
|
|
863
|
-
const contents = [];
|
|
864
|
-
const notices = [];
|
|
865
|
-
for (const image of images) {
|
|
866
|
-
if (image.unsupportedFormat)
|
|
867
|
-
continue;
|
|
868
|
-
if (image.byteSize > MAX_INBOUND_IMAGE_BYTES) {
|
|
869
|
-
notices.push(`⚠️ 图片 \`${image.path}\`(${formatSize(image.byteSize)})超过 ${formatSize(MAX_INBOUND_IMAGE_BYTES)} 上限,未加入本轮上下文,可以让我 read 该文件查看。`);
|
|
870
|
-
continue;
|
|
871
|
-
}
|
|
872
|
-
try {
|
|
873
|
-
const data = await readFile(image.path);
|
|
874
|
-
contents.push({ type: "image", data: data.toString("base64"), mimeType: image.mimeType });
|
|
875
|
-
}
|
|
876
|
-
catch (error) {
|
|
877
|
-
notices.push(`⚠️ 图片 \`${image.path}\` 读取失败:${errorMessage(error)}`);
|
|
878
|
-
}
|
|
879
|
-
}
|
|
880
|
-
return { images: contents, notices };
|
|
881
|
-
}
|
|
882
|
-
/**
|
|
883
|
-
* Single source of truth for the busy-message window: steer is accepted while
|
|
884
|
-
* the prompt is being assembled ("preparing") or while the agent loop is
|
|
885
|
-
* actually streaming. Re-asserted after every await because the turn can end
|
|
886
|
-
* while this call was suspended.
|
|
887
|
-
*/
|
|
888
|
-
assertBusyWindowOpen() {
|
|
889
|
-
if (this.turnState.phase() === "preparing") {
|
|
890
|
-
return;
|
|
891
|
-
}
|
|
892
|
-
if (this.turnState.phase() === "streaming" && this.session.isStreaming) {
|
|
893
|
-
return;
|
|
894
|
-
}
|
|
895
|
-
throw new Error("No task is currently running.");
|
|
896
|
-
}
|
|
897
|
-
async queueBusyMessage(text, userName, images) {
|
|
898
|
-
this.assertBusyWindowOpen();
|
|
899
|
-
await this.ensureSessionReady();
|
|
900
|
-
const oversized = text.replace(/\r/g, "").trim().length > MAX_USER_MESSAGE_CHARS;
|
|
901
|
-
const oversizedPath = oversized ? await this.persistOversizedInput(text) : undefined;
|
|
902
|
-
const clippedText = clipUserInput(text, MAX_USER_MESSAGE_CHARS, oversizedPath);
|
|
903
|
-
if (oversized) {
|
|
904
|
-
log.logWarning(`[${this.channelId}] Queued message exceeded ${MAX_USER_MESSAGE_CHARS} chars and was clipped`);
|
|
905
|
-
}
|
|
906
|
-
const queuedMessage = this.formatUserMessage(clippedText, userName);
|
|
907
|
-
const preparedImages = await this.prepareInboundImages(images);
|
|
908
|
-
for (const notice of preparedImages.notices) {
|
|
909
|
-
await this.runState.ctx?.respondInThread(notice);
|
|
449
|
+
log.logWarn("memory.state.flush_failed", "Memory maintenance state flush failed", {
|
|
450
|
+
channelId: this.channelId,
|
|
451
|
+
reason: errorMessage(error),
|
|
452
|
+
});
|
|
910
453
|
}
|
|
911
|
-
await this.maybeRunPreventiveCompactionForIncomingText(queuedMessage, preparedImages.images.length);
|
|
912
|
-
this.assertBusyWindowOpen();
|
|
913
|
-
const queueMessage = async () => {
|
|
914
|
-
this.assertBusyWindowOpen();
|
|
915
|
-
await this.session.steer(queuedMessage, preparedImages.images.length > 0 ? preparedImages.images : undefined);
|
|
916
|
-
};
|
|
917
|
-
await this.sessionResourceGate.runPrompt(queueMessage);
|
|
918
454
|
}
|
|
919
455
|
resetRunState(ctx, store) {
|
|
920
456
|
this.runState = createEmptyRunState();
|
|
@@ -926,561 +462,4 @@ export class ChannelRunner {
|
|
|
926
462
|
};
|
|
927
463
|
this.runState.store = store;
|
|
928
464
|
}
|
|
929
|
-
async refreshSessionResources() {
|
|
930
|
-
await this.ensureSessionReady();
|
|
931
|
-
await this.sessionResourceGate.requestRefresh();
|
|
932
|
-
}
|
|
933
|
-
/**
|
|
934
|
-
* At turn start, if a fallback is active and the primary's cooldown has elapsed,
|
|
935
|
-
* switch back to the preferred model. Silent — no user notice on recovery.
|
|
936
|
-
*/
|
|
937
|
-
async maybeRestorePrimaryModel() {
|
|
938
|
-
const current = this.session.model;
|
|
939
|
-
if (!current || formatModelReference(current) === formatModelReference(this.activeModel)) {
|
|
940
|
-
this.primaryFailedAt = null;
|
|
941
|
-
return;
|
|
942
|
-
}
|
|
943
|
-
if (!shouldRestorePrimary(this.primaryFailedAt, Date.now())) {
|
|
944
|
-
return;
|
|
945
|
-
}
|
|
946
|
-
try {
|
|
947
|
-
await this.setModelWithThinkingPreservation(this.activeModel);
|
|
948
|
-
this.primaryFailedAt = null;
|
|
949
|
-
log.logInfo(`[${this.channelId}] Restored primary model ${formatModelReference(this.activeModel)}`);
|
|
950
|
-
}
|
|
951
|
-
catch (err) {
|
|
952
|
-
log.logWarning(`[${this.channelId}] Failed to restore primary model`, errorMessage(err));
|
|
953
|
-
}
|
|
954
|
-
}
|
|
955
|
-
async setModelWithThinkingPreservation(model) {
|
|
956
|
-
await setModelWithThinkingPreservation(this.session, this.sessionSettingsManager, model);
|
|
957
|
-
}
|
|
958
|
-
setThinkingLevelCompat(level) {
|
|
959
|
-
setThinkingLevelWithConditionalPersist(this.session, level);
|
|
960
|
-
}
|
|
961
|
-
cycleThinkingLevelCompat() {
|
|
962
|
-
return cycleThinkingLevelWithConditionalPersist(this.session);
|
|
963
|
-
}
|
|
964
|
-
/**
|
|
965
|
-
* Resolve the configured backup model reference against available models.
|
|
966
|
-
* Returns null when unset, unresolvable/ambiguous, or missing an API key —
|
|
967
|
-
* each case logs a warning and disables fallback for this turn.
|
|
968
|
-
*/
|
|
969
|
-
async resolveFallbackModel() {
|
|
970
|
-
const reference = this.settingsManager.getFallbackModelReference();
|
|
971
|
-
if (!reference) {
|
|
972
|
-
return null;
|
|
973
|
-
}
|
|
974
|
-
await this.modelRegistry.refresh();
|
|
975
|
-
const available = this.modelRegistry.getAvailable();
|
|
976
|
-
const { match, ambiguous } = findExactModelReferenceMatch(reference, available);
|
|
977
|
-
if (!match) {
|
|
978
|
-
log.logWarning(`[${this.channelId}] fallbackModel "${reference}" ${ambiguous ? "is ambiguous" : "not found"}; skipping fallback`);
|
|
979
|
-
return null;
|
|
980
|
-
}
|
|
981
|
-
try {
|
|
982
|
-
await getApiKeyForModel(this.modelRegistry, match);
|
|
983
|
-
}
|
|
984
|
-
catch {
|
|
985
|
-
log.logWarning(`[${this.channelId}] fallbackModel "${reference}" has no API key; skipping fallback`);
|
|
986
|
-
return null;
|
|
987
|
-
}
|
|
988
|
-
return match;
|
|
989
|
-
}
|
|
990
|
-
async initializeSession(sessionManager) {
|
|
991
|
-
// Build the canonical async model/auth runtime and its synchronous read shell.
|
|
992
|
-
this.modelRuntime = await createModelRuntime({
|
|
993
|
-
authConfigPath: this.authConfigPath,
|
|
994
|
-
modelsConfigPath: this.modelsConfigPath,
|
|
995
|
-
});
|
|
996
|
-
this.modelRegistry = wrapModelRegistry(this.modelRuntime);
|
|
997
|
-
// Resolve model: prefer saved global default, fall back to first available model.
|
|
998
|
-
this.activeModel = resolveInitialModel(this.modelRegistry, this.settingsManager);
|
|
999
|
-
log.logInfo(`Using model: ${this.activeModel.provider}/${this.activeModel.id} (${this.activeModel.name})`);
|
|
1000
|
-
this.subAgentDiscovery = await this.refreshSubAgentDiscovery();
|
|
1001
|
-
const initial = await this.createSessionRuntime(sessionManager);
|
|
1002
|
-
this.session = initial.session;
|
|
1003
|
-
this.sessionRuntime = new AgentSessionRuntime(this.session, this.createAgentSessionServices(initial.resourceLoader), async ({ sessionManager, sessionStartEvent }) => {
|
|
1004
|
-
// `/new`, fork, and switch already wrote the target session's durable header by
|
|
1005
|
-
// this point (the SDK does it synchronously before invoking this callback); commit
|
|
1006
|
-
// the pointer before we rebuild and rebind to it, so a crash between "SDK created
|
|
1007
|
-
// session" and "we finished rebinding" leaves the old ref (and old session)
|
|
1008
|
-
// authoritative rather than an orphaned new file (spec 043, D1.3).
|
|
1009
|
-
// A task session is not the channel's chat session: never repoint the active-session
|
|
1010
|
-
// ref at it, or `/new` and restart recovery would adopt a task's transcript as the
|
|
1011
|
-
// conversation (spec 051, D3).
|
|
1012
|
-
if (!isTaskSessionPath(sessionManager.getSessionFile())) {
|
|
1013
|
-
await commitActiveSessionRef(this.channelDir, sessionManager);
|
|
1014
|
-
}
|
|
1015
|
-
const next = await this.createSessionRuntime(sessionManager, sessionStartEvent);
|
|
1016
|
-
return {
|
|
1017
|
-
session: next.session,
|
|
1018
|
-
extensionsResult: next.resourceLoader.getExtensions(),
|
|
1019
|
-
services: this.createAgentSessionServices(next.resourceLoader),
|
|
1020
|
-
diagnostics: [],
|
|
1021
|
-
};
|
|
1022
|
-
});
|
|
1023
|
-
this.sessionRuntime.setRebindSession(async (session) => {
|
|
1024
|
-
this.session = session;
|
|
1025
|
-
await this.bindSessionExtensions();
|
|
1026
|
-
this.subscribeToSessionEvents();
|
|
1027
|
-
});
|
|
1028
|
-
// Subscribe to session events
|
|
1029
|
-
this.subscribeToSessionEvents();
|
|
1030
|
-
await this.bindSessionExtensions();
|
|
1031
|
-
// A restart resumes an existing transcript: if that session was already handed its
|
|
1032
|
-
// bootstrap before the daemon went down, the first turn after recovery must not inject a
|
|
1033
|
-
// second copy just because a process-local field starts out `true`.
|
|
1034
|
-
this.syncMemoryBootstrapPendingFromSession();
|
|
1035
|
-
this.sessionInitialized = true;
|
|
1036
|
-
}
|
|
1037
|
-
async reloadSessionResources() {
|
|
1038
|
-
this.settingsManager.reload();
|
|
1039
|
-
this.reportSettingsDiagnostics();
|
|
1040
|
-
const skills = loadPipiclawSkills(this.channelDir);
|
|
1041
|
-
this.currentSkills = skills;
|
|
1042
|
-
this.subAgentDiscovery = await this.refreshSubAgentDiscovery();
|
|
1043
|
-
this.rebuildSessionTools();
|
|
1044
|
-
try {
|
|
1045
|
-
await withTimeout(`[${this.channelId}] session reload`, SESSION_RELOAD_TIMEOUT_MS, () => this.session.reload());
|
|
1046
|
-
}
|
|
1047
|
-
catch (error) {
|
|
1048
|
-
log.logWarning(`[${this.channelId}] Session reload did not settle`, errorMessage(error));
|
|
1049
|
-
}
|
|
1050
|
-
}
|
|
1051
|
-
async bindSessionExtensions() {
|
|
1052
|
-
await this.session.bindExtensions({
|
|
1053
|
-
commandContextActions: {
|
|
1054
|
-
waitForIdle: () => this.session.agent.waitForIdle(),
|
|
1055
|
-
newSession: async (options) => {
|
|
1056
|
-
return await this.sessionRuntime.newSession(options);
|
|
1057
|
-
},
|
|
1058
|
-
fork: async (entryId, options) => {
|
|
1059
|
-
const result = await this.sessionRuntime.fork(entryId, options);
|
|
1060
|
-
this.syncMemoryBootstrapPendingFromSession();
|
|
1061
|
-
return { cancelled: result.cancelled };
|
|
1062
|
-
},
|
|
1063
|
-
navigateTree: async (targetId, options) => {
|
|
1064
|
-
const result = await this.session.navigateTree(targetId, options);
|
|
1065
|
-
this.syncMemoryBootstrapPendingFromSession();
|
|
1066
|
-
return { cancelled: result.cancelled };
|
|
1067
|
-
},
|
|
1068
|
-
switchSession: async (sessionPath, options) => {
|
|
1069
|
-
const result = await this.sessionRuntime.switchSession(sessionPath, options);
|
|
1070
|
-
this.syncMemoryBootstrapPendingFromSession();
|
|
1071
|
-
return result;
|
|
1072
|
-
},
|
|
1073
|
-
reload: async () => {
|
|
1074
|
-
await this.refreshSessionResources();
|
|
1075
|
-
},
|
|
1076
|
-
},
|
|
1077
|
-
});
|
|
1078
|
-
}
|
|
1079
|
-
async ensureSessionReady() {
|
|
1080
|
-
await this.sessionReady;
|
|
1081
|
-
}
|
|
1082
|
-
async maybeRunPreventiveCompactionForIncomingText(incomingText, imageCount = 0) {
|
|
1083
|
-
const currentModel = this.session.model ?? this.activeModel;
|
|
1084
|
-
const contextUsage = this.session.getContextUsage();
|
|
1085
|
-
const contextTokens = contextUsage?.tokens;
|
|
1086
|
-
const incomingTokens = estimateIncomingMessageTokens(incomingText, imageCount);
|
|
1087
|
-
const decision = getPreventiveCompactionDecision(contextTokens, incomingTokens, currentModel.contextWindow);
|
|
1088
|
-
if (!decision.shouldCompact) {
|
|
1089
|
-
return;
|
|
1090
|
-
}
|
|
1091
|
-
const currentTokens = contextTokens ?? 0;
|
|
1092
|
-
const startedAt = Date.now();
|
|
1093
|
-
log.logInfo(`[${this.channelId}] Preventive compaction triggered: projected ${decision.projectedTokens}/${currentModel.contextWindow} tokens (current=${currentTokens}, incoming≈${incomingTokens}), threshold=${decision.thresholdTokens}`);
|
|
1094
|
-
try {
|
|
1095
|
-
await this.session.compact();
|
|
1096
|
-
log.logInfo(`[${this.channelId}] Preventive compaction complete in ${Date.now() - startedAt}ms`);
|
|
1097
|
-
}
|
|
1098
|
-
catch (error) {
|
|
1099
|
-
const message = errorMessage(error);
|
|
1100
|
-
log.logWarning(`[${this.channelId}] Preventive compaction failed`, message);
|
|
1101
|
-
}
|
|
1102
|
-
}
|
|
1103
|
-
async refreshSubAgentDiscovery() {
|
|
1104
|
-
// Re-resolves models.json *and* every provider's auth, which for an OAuth
|
|
1105
|
-
// provider is a network call. Failing open keeps the last known model
|
|
1106
|
-
// snapshot — stale availability is a far smaller problem than a reload
|
|
1107
|
-
// (and, through it, a `/new` turn) that never returns.
|
|
1108
|
-
try {
|
|
1109
|
-
await withTimeout(`[${this.channelId}] model registry refresh`, MODEL_REGISTRY_REFRESH_TIMEOUT_MS, () => this.modelRegistry.refresh());
|
|
1110
|
-
}
|
|
1111
|
-
catch (error) {
|
|
1112
|
-
log.logWarning(`[${this.channelId}] Model registry refresh did not settle; using the previous model snapshot`, errorMessage(error));
|
|
1113
|
-
}
|
|
1114
|
-
const discovery = discoverSubAgents(this.workspaceDir, this.modelRegistry.getAvailable());
|
|
1115
|
-
for (const warning of discovery.warnings) {
|
|
1116
|
-
log.logWarning(`Sub-agent config warning (${this.channelId})`, warning);
|
|
1117
|
-
}
|
|
1118
|
-
return discovery;
|
|
1119
|
-
}
|
|
1120
|
-
reportSettingsDiagnostics() {
|
|
1121
|
-
for (const { scope, error } of this.settingsManager.drainErrors()) {
|
|
1122
|
-
log.logWarning(`[${this.channelId}] Failed to load ${scope} settings`, `${error.message}\n${join(this.appHomeDir, "settings.json")}`);
|
|
1123
|
-
}
|
|
1124
|
-
}
|
|
1125
|
-
reportConfigDiagnostics(diagnostics) {
|
|
1126
|
-
for (const diagnostic of diagnostics) {
|
|
1127
|
-
log.logWarning(`[${this.channelId}] ${formatConfigDiagnostic(diagnostic)}`, diagnostic.path);
|
|
1128
|
-
}
|
|
1129
|
-
}
|
|
1130
|
-
/**
|
|
1131
|
-
* Build the Pipiclaw-owned system prompt (spec 025). This replaces pi's default
|
|
1132
|
-
* base prompt entirely: identity, execution contract, hard invariants, the tool
|
|
1133
|
-
* catalog and the workspace files are ours. pi still appends its tail (skills,
|
|
1134
|
-
* date, cwd), and the boundary footer is appended after that by the prompt
|
|
1135
|
-
* extension.
|
|
1136
|
-
*
|
|
1137
|
-
* Nothing channel-specific enters this text — that is what lets two channels in
|
|
1138
|
-
* one workspace share a cached prompt prefix. Channel facts ride the turn.
|
|
1139
|
-
*/
|
|
1140
|
-
buildSystemPrompt() {
|
|
1141
|
-
const toolNames = this.currentTools.map((tool) => tool.name);
|
|
1142
|
-
const resources = loadWorkspacePromptResources(this.workspaceDir);
|
|
1143
|
-
this.lastWorkspaceResources = resources;
|
|
1144
|
-
const build = buildPipiclawSystemPrompt({
|
|
1145
|
-
tools: this.currentTools.map((tool) => ({
|
|
1146
|
-
name: tool.name,
|
|
1147
|
-
description: tool.description,
|
|
1148
|
-
})),
|
|
1149
|
-
soul: resources.soul,
|
|
1150
|
-
agents: resources.agents,
|
|
1151
|
-
playbooks: selectRuntimePlaybooks(loadRuntimePlaybookCatalog(), toolNames),
|
|
1152
|
-
subAgents: this.subAgentDiscovery.agents.map((agent) => ({
|
|
1153
|
-
name: agent.name,
|
|
1154
|
-
description: agent.description,
|
|
1155
|
-
runtime: agent.runtime,
|
|
1156
|
-
harness: agent.harness,
|
|
1157
|
-
workload: agent.workload ?? (agent.runtime === "external" ? "heavy" : "light"),
|
|
1158
|
-
mutates: agent.mutates,
|
|
1159
|
-
unavailable: agent.unavailable,
|
|
1160
|
-
})),
|
|
1161
|
-
});
|
|
1162
|
-
for (const diagnostic of [...resources.diagnostics, ...build.diagnostics]) {
|
|
1163
|
-
if (diagnostic.level === "info")
|
|
1164
|
-
continue;
|
|
1165
|
-
log.logWarning(`[${this.channelId}] Prompt ${diagnostic.level} (${diagnostic.sectionId})`, diagnostic.message);
|
|
1166
|
-
}
|
|
1167
|
-
// Only a real change is worth a line: a reload that produced the same bytes is noise.
|
|
1168
|
-
if (this.lastPromptBuild?.fingerprint !== build.fingerprint) {
|
|
1169
|
-
log.logInfo(`[${this.channelId}] System prompt rebuilt: ${build.totalChars} chars, ~${build.estimatedTokens} tokens, sha256:${build.fingerprint.slice(0, 12)} (was ${this.lastPromptBuild ? `sha256:${this.lastPromptBuild.fingerprint.slice(0, 12)}` : "none"})`);
|
|
1170
|
-
}
|
|
1171
|
-
this.lastPromptBuild = build;
|
|
1172
|
-
return build;
|
|
1173
|
-
}
|
|
1174
|
-
createResourceLoader() {
|
|
1175
|
-
return new DefaultResourceLoader({
|
|
1176
|
-
cwd: this.projectScope.projectRoot,
|
|
1177
|
-
agentDir: this.appHomeDir,
|
|
1178
|
-
settingsManager: asSdkSettingsManager(this.settingsManager),
|
|
1179
|
-
extensionFactories: [
|
|
1180
|
-
this.memoryLifecycle.createExtensionFactory(),
|
|
1181
|
-
createPromptBoundaryExtension({
|
|
1182
|
-
getFooter: () => this.lastPromptBuild?.footer ?? "",
|
|
1183
|
-
onFinalPrompt: (systemPrompt) => {
|
|
1184
|
-
this.lastFinalPrompt = systemPrompt;
|
|
1185
|
-
},
|
|
1186
|
-
}),
|
|
1187
|
-
createCommandExtension({
|
|
1188
|
-
getCurrentModel: () => this.session.model ?? this.activeModel,
|
|
1189
|
-
getAvailableModels: async () => {
|
|
1190
|
-
await this.modelRegistry.refresh();
|
|
1191
|
-
return this.modelRegistry.getAvailable();
|
|
1192
|
-
},
|
|
1193
|
-
getSessionStats: () => this.session.getSessionStats(),
|
|
1194
|
-
getThinkingLevel: () => this.session.thinkingLevel,
|
|
1195
|
-
getAvailableThinkingLevels: () => this.session.getAvailableThinkingLevels(),
|
|
1196
|
-
setThinkingLevel: (level) => this.setThinkingLevelCompat(level),
|
|
1197
|
-
cycleThinkingLevel: () => this.cycleThinkingLevelCompat(),
|
|
1198
|
-
getLastResponseModel: () => getLastAssistantUsage(this.session.messages)?.responseModel,
|
|
1199
|
-
switchModel: async (model) => {
|
|
1200
|
-
await this.setModelWithThinkingPreservation(model);
|
|
1201
|
-
this.activeModel = model;
|
|
1202
|
-
// Manual /model switch redefines the preferred model and clears fallback state.
|
|
1203
|
-
this.primaryFailedAt = null;
|
|
1204
|
-
},
|
|
1205
|
-
refreshSessionResources: async () => {
|
|
1206
|
-
await this.refreshSessionResources();
|
|
1207
|
-
},
|
|
1208
|
-
runMemoryCommand: async (args) => handleMemoryCommand({
|
|
1209
|
-
channelId: this.channelId,
|
|
1210
|
-
channelDir: this.channelDir,
|
|
1211
|
-
appHomeDir: this.appHomeDir,
|
|
1212
|
-
args,
|
|
1213
|
-
}),
|
|
1214
|
-
}),
|
|
1215
|
-
],
|
|
1216
|
-
// Pipiclaw owns the base prompt: with a custom prompt present, pi emits no
|
|
1217
|
-
// default identity, no pi docs index and no `Available tools: (none)` block.
|
|
1218
|
-
systemPromptOverride: () => this.buildSystemPrompt().text,
|
|
1219
|
-
// Nothing may slip in behind the section pipeline — not pi's app-level
|
|
1220
|
-
// APPEND_SYSTEM.md, not a base append. SOUL/AGENTS are rendered as sections.
|
|
1221
|
-
appendSystemPromptOverride: () => [],
|
|
1222
|
-
agentsFilesOverride: () => ({ agentsFiles: [] }),
|
|
1223
|
-
// Skills stay in the ResourceLoader: they drive `/skill:name` and pi's
|
|
1224
|
-
// `<available_skills>` index together. Only the merge policy is ours.
|
|
1225
|
-
skillsOverride: (base) => {
|
|
1226
|
-
const merged = resolvePipiclawSkills(base, this.currentSkills);
|
|
1227
|
-
for (const diagnostic of merged.diagnostics) {
|
|
1228
|
-
log.logWarning(`[${this.channelId}] Skill ${diagnostic.type}`, `${diagnostic.message}${diagnostic.path ? ` (${diagnostic.path})` : ""}`);
|
|
1229
|
-
}
|
|
1230
|
-
return merged;
|
|
1231
|
-
},
|
|
1232
|
-
});
|
|
1233
|
-
}
|
|
1234
|
-
createAgentSessionServices(resourceLoader) {
|
|
1235
|
-
return {
|
|
1236
|
-
cwd: this.projectScope.projectRoot,
|
|
1237
|
-
agentDir: this.appHomeDir,
|
|
1238
|
-
settingsManager: asSdkSettingsManager(this.settingsManager),
|
|
1239
|
-
modelRuntime: this.modelRuntime,
|
|
1240
|
-
resourceLoader,
|
|
1241
|
-
diagnostics: [],
|
|
1242
|
-
};
|
|
1243
|
-
}
|
|
1244
|
-
/**
|
|
1245
|
-
* Load a freshly constructed ResourceLoader before an `AgentSession` is built on top of it.
|
|
1246
|
-
*
|
|
1247
|
-
* `AgentSession` reads `resourceLoader.getExtensions()` in its constructor, and a loader that
|
|
1248
|
-
* has never been loaded answers with an *empty* set. Skipping this leaves a replacement session
|
|
1249
|
-
* with no extensions at all — no command extension (so `/model`, `/thinking`, `/session`,
|
|
1250
|
-
* `/compact` and `/memory` fall through to the model as plain text), no memory lifecycle, no
|
|
1251
|
-
* prompt-boundary footer, and no prompt templates. Tolerated on failure the same way
|
|
1252
|
-
* `reloadSessionResources` tolerates a stuck reload: a degraded session still answers chat.
|
|
1253
|
-
*/
|
|
1254
|
-
async loadSessionResources(resourceLoader) {
|
|
1255
|
-
try {
|
|
1256
|
-
await withTimeout(`[${this.channelId}] session resource load`, SESSION_RELOAD_TIMEOUT_MS, () => resourceLoader.reload());
|
|
1257
|
-
}
|
|
1258
|
-
catch (error) {
|
|
1259
|
-
log.logWarning(`[${this.channelId}] Session resources did not load`, errorMessage(error));
|
|
1260
|
-
}
|
|
1261
|
-
}
|
|
1262
|
-
/**
|
|
1263
|
-
* Resolve the initial thinking level using the same precedence as pi's SDK:
|
|
1264
|
-
* session history, configured default, then medium. The effective value is
|
|
1265
|
-
* clamped to the selected model before the session starts.
|
|
1266
|
-
*/
|
|
1267
|
-
initializeThinkingLevel(agent, model, sessionManager) {
|
|
1268
|
-
initializeThinkingLevelCompat(agent, model, sessionManager, this.settingsManager.getDefaultThinkingLevel());
|
|
1269
|
-
}
|
|
1270
|
-
async createSessionRuntime(sessionManager, sessionStartEvent) {
|
|
1271
|
-
const tools = this.buildRuntimeTools();
|
|
1272
|
-
const agent = new Agent({
|
|
1273
|
-
initialState: {
|
|
1274
|
-
systemPrompt: "",
|
|
1275
|
-
model: this.activeModel,
|
|
1276
|
-
thinkingLevel: DEFAULT_MAIN_THINKING_LEVEL,
|
|
1277
|
-
tools,
|
|
1278
|
-
},
|
|
1279
|
-
convertToLlm,
|
|
1280
|
-
getApiKey: async () => getApiKeyForModel(this.modelRegistry, this.activeModel),
|
|
1281
|
-
streamFn: streamSimple,
|
|
1282
|
-
});
|
|
1283
|
-
this.initializeThinkingLevel(agent, this.activeModel, sessionManager);
|
|
1284
|
-
const resourceLoader = this.createResourceLoader();
|
|
1285
|
-
// Must precede `new AgentSession`: the session snapshots the loader's extensions in its
|
|
1286
|
-
// constructor (see `loadSessionResources`).
|
|
1287
|
-
await this.loadSessionResources(resourceLoader);
|
|
1288
|
-
const sessionSettingsManager = asSdkSettingsManager(this.settingsManager);
|
|
1289
|
-
const session = new AgentSession({
|
|
1290
|
-
agent,
|
|
1291
|
-
sessionManager,
|
|
1292
|
-
settingsManager: sessionSettingsManager,
|
|
1293
|
-
cwd: this.projectScope.projectRoot,
|
|
1294
|
-
modelRuntime: this.modelRuntime,
|
|
1295
|
-
resourceLoader,
|
|
1296
|
-
baseToolsOverride: Object.fromEntries(tools.map((tool) => [tool.name, tool])),
|
|
1297
|
-
sessionStartEvent,
|
|
1298
|
-
});
|
|
1299
|
-
this.sessionSettingsManager = sessionSettingsManager;
|
|
1300
|
-
return { session, resourceLoader };
|
|
1301
|
-
}
|
|
1302
|
-
/**
|
|
1303
|
-
* Bind this runner to a task cycle's own session (spec 051, D3/INV-5).
|
|
1304
|
-
*
|
|
1305
|
-
* Task work must not accumulate in the channel's chat transcript: the one real channel on the
|
|
1306
|
-
* author's machine had grown to 7.4 MB and been compacted six times because chat and two daily
|
|
1307
|
-
* tasks shared it, so every compaction damaged all three at once. Swapping the bound session
|
|
1308
|
-
* per turn gives each task its own bounded context while leaving turn state, `/stop`, and
|
|
1309
|
-
* delivery exactly where they already are.
|
|
1310
|
-
*/
|
|
1311
|
-
async bindTaskSession(taskId) {
|
|
1312
|
-
await this.sessionReady;
|
|
1313
|
-
const path = taskSessionPath(this.channelDir, taskId);
|
|
1314
|
-
await mkdir(dirname(path), { recursive: true });
|
|
1315
|
-
this.taskLoop = { taskId };
|
|
1316
|
-
await this.sessionRuntime.switchSession(path);
|
|
1317
|
-
this.syncMemoryBootstrapPendingFromSession();
|
|
1318
|
-
}
|
|
1319
|
-
/** Return to the channel's chat session after a task step. Safe to call when already bound. */
|
|
1320
|
-
async bindChatSession() {
|
|
1321
|
-
if (!this.taskLoop)
|
|
1322
|
-
return;
|
|
1323
|
-
this.taskLoop = undefined;
|
|
1324
|
-
await this.sessionRuntime.switchSession(join(this.channelDir, resolveActiveSessionFile(this.channelDir)));
|
|
1325
|
-
this.syncMemoryBootstrapPendingFromSession();
|
|
1326
|
-
}
|
|
1327
|
-
/**
|
|
1328
|
-
* Re-derive "does this session still owe a memory bootstrap" from the session now bound.
|
|
1329
|
-
*
|
|
1330
|
-
* The pending flag used to be set to `true` on every bind, which is right for a fresh task
|
|
1331
|
-
* session and wrong for the return trip: a chat session that already carries the block would
|
|
1332
|
-
* be handed a second copy on its next turn, and one interleaved task step could therefore cost
|
|
1333
|
-
* the whole index again. It was also wrong across a restart, where the field simply starts
|
|
1334
|
-
* `true` and the resumed session's own history says otherwise.
|
|
1335
|
-
*
|
|
1336
|
-
* So the answer comes from the transcript that will actually be sent, not from a boolean that
|
|
1337
|
-
* has to be kept in step with every binding. The `/new` and post-compaction resets in
|
|
1338
|
-
* `subscribeToSessionEvents` stay as they are: those are the SDK telling us the context
|
|
1339
|
-
* generation changed, which is a fact about the session that its message list alone —
|
|
1340
|
-
* compaction having rewritten it into a summary — cannot be scanned for reliably.
|
|
1341
|
-
*/
|
|
1342
|
-
syncMemoryBootstrapPendingFromSession() {
|
|
1343
|
-
// `session.messages` is empty until the session actually runs a turn, so the answer comes
|
|
1344
|
-
// from the persisted branch — which is also what makes this correct across a restart.
|
|
1345
|
-
const injected = this.sessionManager.getBranch().some((entry) => {
|
|
1346
|
-
if (!isRecord(entry) || entry.type !== "message" || !isRecord(entry.message))
|
|
1347
|
-
return false;
|
|
1348
|
-
return entry.message.role === "user" && hasMemoryBootstrapBlock(plainTextOf(entry.message.content));
|
|
1349
|
-
});
|
|
1350
|
-
this.firstTurnMemoryBootstrapPending = !injected;
|
|
1351
|
-
}
|
|
1352
|
-
/** Which task loop this runner is currently bound to, if any. */
|
|
1353
|
-
getTaskLoop() {
|
|
1354
|
-
return this.taskLoop;
|
|
1355
|
-
}
|
|
1356
|
-
buildRuntimeTools() {
|
|
1357
|
-
const securityLoad = this.loadSecurityConfig();
|
|
1358
|
-
const toolsLoad = loadToolsConfigWithDiagnostics(this.appHomeDir);
|
|
1359
|
-
this.reportConfigDiagnostics([...securityLoad.diagnostics, ...toolsLoad.diagnostics]);
|
|
1360
|
-
this.tasksEnabled = toolsLoad.config.tools.tasks.enabled;
|
|
1361
|
-
const tools = createPipiclawTools({
|
|
1362
|
-
jobManager: this.jobManager,
|
|
1363
|
-
runManager: this.runManager,
|
|
1364
|
-
executor: this.executor,
|
|
1365
|
-
fileStore: this.fileStore,
|
|
1366
|
-
getCurrentModel: () => this.activeModel,
|
|
1367
|
-
getAvailableModels: () => this.modelRegistry.getAvailable(),
|
|
1368
|
-
resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
|
|
1369
|
-
workspaceDir: this.workspaceDir,
|
|
1370
|
-
projectScope: this.projectScope,
|
|
1371
|
-
channelDir: this.channelDir,
|
|
1372
|
-
channelId: this.channelId,
|
|
1373
|
-
getSubAgentDiscovery: () => this.subAgentDiscovery,
|
|
1374
|
-
getSubAgentModelReference: () => this.settingsManager.getSubAgentModelReference(),
|
|
1375
|
-
getSessionSearchSettings: () => this.settingsManager.getSessionSearchSettings(),
|
|
1376
|
-
securityConfig: securityLoad.config,
|
|
1377
|
-
toolsConfig: toolsLoad.config,
|
|
1378
|
-
mediaSender: this.mediaSender,
|
|
1379
|
-
taskLoop: this.taskLoop,
|
|
1380
|
-
getToolsUsed: () => this.runState.toolsUsed,
|
|
1381
|
-
// Assistant usage only: an internal sub-agent's cost is also in `totalUsage`, and a bound
|
|
1382
|
-
// one is already credited to the task when it settles.
|
|
1383
|
-
getStepCost: () => ({ usd: this.runState.assistantUsage.cost.total, estimated: !this.runState.costKnown }),
|
|
1384
|
-
});
|
|
1385
|
-
this.currentTools = tools;
|
|
1386
|
-
// Tool schemas are billed with the system prompt and, unlike it, nothing trims them.
|
|
1387
|
-
// Warn where the prompt's own budget diagnostics are reported, once per tool rebuild.
|
|
1388
|
-
const schemas = measureToolSchemas(tools);
|
|
1389
|
-
if (schemas.units > TOOL_SCHEMA_TARGET_UNITS) {
|
|
1390
|
-
log.logWarning(`[${this.channelId}] Tool schema budget`, toolSchemaBudgetWarning(schemas));
|
|
1391
|
-
}
|
|
1392
|
-
return tools;
|
|
1393
|
-
}
|
|
1394
|
-
rebuildSessionTools() {
|
|
1395
|
-
const tools = this.buildRuntimeTools();
|
|
1396
|
-
setSessionBaseToolsOverride(this.session, tools, this.channelId);
|
|
1397
|
-
this.agent.state.tools = tools;
|
|
1398
|
-
this.session.setActiveToolsByName(tools.map((tool) => tool.name));
|
|
1399
|
-
}
|
|
1400
|
-
// === Session event subscription ===
|
|
1401
|
-
subscribeToSessionEvents() {
|
|
1402
|
-
this.sessionUnsubscribe?.();
|
|
1403
|
-
this.sessionUnsubscribe = this.session.subscribe((event) => {
|
|
1404
|
-
// Observation is deliberately before our consumer and must never alter a turn.
|
|
1405
|
-
try {
|
|
1406
|
-
this.onSessionEvent?.(event, this.channelId);
|
|
1407
|
-
}
|
|
1408
|
-
catch (err) {
|
|
1409
|
-
log.logWarning(`[${this.channelId}] session observer failed`, errorMessage(err));
|
|
1410
|
-
}
|
|
1411
|
-
if (isRecord(event) && event.type === "message_start") {
|
|
1412
|
-
this.turnState.markStreaming();
|
|
1413
|
-
}
|
|
1414
|
-
if (isRecord(event) && "reason" in event && event.reason === "new") {
|
|
1415
|
-
this.firstTurnMemoryBootstrapPending = true;
|
|
1416
|
-
}
|
|
1417
|
-
// Spec 050, D1: compaction rewrites the first-turn bootstrap into a summary; re-inject
|
|
1418
|
-
// the authoritative index on the next turn so memory does not decay with the transcript.
|
|
1419
|
-
if (isAutoCompactionEndEvent(event) && !event.aborted && !event.errorMessage) {
|
|
1420
|
-
this.firstTurnMemoryBootstrapPending = true;
|
|
1421
|
-
}
|
|
1422
|
-
if (!this.runState.ctx || !this.runState.logCtx || !this.runState.queue)
|
|
1423
|
-
return;
|
|
1424
|
-
// The SDK listener signature is `(event) => void`, so the promise below is fire-and-forget.
|
|
1425
|
-
// Without this catch, a rejection inside handleSessionEvent becomes an unhandled rejection
|
|
1426
|
-
// that terminates the daemon under Node's default policy.
|
|
1427
|
-
handleSessionEvent(event, {
|
|
1428
|
-
ctx: this.runState.ctx,
|
|
1429
|
-
logCtx: this.runState.logCtx,
|
|
1430
|
-
queue: this.runState.queue,
|
|
1431
|
-
pendingTools: this.runState.pendingTools,
|
|
1432
|
-
store: this.runState.store,
|
|
1433
|
-
runState: this.runState,
|
|
1434
|
-
memoryLifecycle: this.memoryLifecycle,
|
|
1435
|
-
ledger: this.ledger,
|
|
1436
|
-
isModelCostKnown: (reference) => {
|
|
1437
|
-
const model = findExactModelReferenceMatch(reference, this.modelRegistry.getAvailable()).match;
|
|
1438
|
-
return model ? hasKnownModelPricing(model) : false;
|
|
1439
|
-
},
|
|
1440
|
-
refreshSessionResources: async () => {
|
|
1441
|
-
await this.refreshSessionResources();
|
|
1442
|
-
},
|
|
1443
|
-
skillsDir: join(this.workspaceDir, "skills"),
|
|
1444
|
-
}).catch((err) => {
|
|
1445
|
-
log.logWarning(`[${this.channelId}] session event handler failed`, errorMessage(err));
|
|
1446
|
-
});
|
|
1447
|
-
});
|
|
1448
|
-
}
|
|
1449
|
-
/** Gated by the same master autonomy switch as the task_* tools and the TaskDriver. */
|
|
1450
|
-
buildTaskDigestForTurn() {
|
|
1451
|
-
return buildTaskDigest({
|
|
1452
|
-
channelDir: this.channelDir,
|
|
1453
|
-
maxTasks: TASK_DIGEST_SETTINGS.maxTasks,
|
|
1454
|
-
maxChars: TASK_DIGEST_SETTINGS.maxChars,
|
|
1455
|
-
maxUnits: TASK_AGENDA_MAX_UNITS,
|
|
1456
|
-
});
|
|
1457
|
-
}
|
|
1458
|
-
/**
|
|
1459
|
-
* Spec 050, D1: assemble `<memory_bootstrap>` for the first turn of a session — workspace
|
|
1460
|
-
* MEMORY.md (whole H2 sections, budgeted) + the channel index (full, or budget-tiered) +
|
|
1461
|
-
* today's journal tail.
|
|
1462
|
-
*/
|
|
1463
|
-
async buildFirstTurnMemoryBootstrap() {
|
|
1464
|
-
const readOptionalFile = async (path) => {
|
|
1465
|
-
try {
|
|
1466
|
-
return await readFile(path, "utf-8");
|
|
1467
|
-
}
|
|
1468
|
-
catch {
|
|
1469
|
-
return "";
|
|
1470
|
-
}
|
|
1471
|
-
};
|
|
1472
|
-
const today = localDayKey();
|
|
1473
|
-
const [entries, workspaceMemory, journalToday] = await Promise.all([
|
|
1474
|
-
listMemoryEntries(this.channelDir).catch(() => []),
|
|
1475
|
-
readOptionalFile(join(this.workspaceDir, "MEMORY.md")),
|
|
1476
|
-
readJournalDay(this.channelDir, today).catch(() => ""),
|
|
1477
|
-
]);
|
|
1478
|
-
const index = buildChannelIndexForBootstrap(entries);
|
|
1479
|
-
const journalTail = clipJournalTailForBootstrap(journalToday);
|
|
1480
|
-
return renderMemoryBootstrap({
|
|
1481
|
-
workspaceMemory: clipWorkspaceMemoryForBootstrap(workspaceMemory),
|
|
1482
|
-
channelIndex: entries.length > 0 ? index.text : "",
|
|
1483
|
-
journal: journalTail ? { date: today, text: journalTail } : undefined,
|
|
1484
|
-
});
|
|
1485
|
-
}
|
|
1486
465
|
}
|