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