@oyasmi/pipiclaw 0.9.4-beta.1 → 0.9.4-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/builtin-commands.d.ts +19 -0
- package/dist/agent/builtin-commands.js +80 -0
- package/dist/agent/channel-runner.d.ts +20 -208
- package/dist/agent/channel-runner.js +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 +9 -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
|
@@ -0,0 +1,621 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The SDK session of one channel: building and rebuilding it (resource loader, tools, system prompt,
|
|
3
|
+
* extensions), subscribing to its events, binding it to a task's own session or back to the chat
|
|
4
|
+
* session, and tearing it down. Owns the session-side state — the session itself, the model
|
|
5
|
+
* runtime and registry, the current tools and skills, the last prompt build — and nothing about
|
|
6
|
+
* turns; `ChannelRunner` drives turns through it.
|
|
7
|
+
*/
|
|
8
|
+
import { Agent } from "@earendil-works/pi-agent-core";
|
|
9
|
+
import { streamSimple } from "@earendil-works/pi-ai/compat";
|
|
10
|
+
import { AgentSession, AgentSessionRuntime, convertToLlm, DefaultResourceLoader, } from "@earendil-works/pi-coding-agent";
|
|
11
|
+
import { mkdir } from "fs/promises";
|
|
12
|
+
import { dirname, join } from "path";
|
|
13
|
+
import { commitActiveSessionRef, resolveActiveSessionFile } from "../../channel/active-session-store.js";
|
|
14
|
+
import { loadToolsConfigWithDiagnostics } from "../../config/tools.js";
|
|
15
|
+
import * as log from "../../log.js";
|
|
16
|
+
import { handleMemoryCommand } from "../../memory/commands.js";
|
|
17
|
+
import { hasMemoryBootstrapBlock } from "../../memory/render.js";
|
|
18
|
+
import { getApiKeyForModel } from "../../models/api-keys.js";
|
|
19
|
+
import { findExactModelReferenceMatch, hasKnownModelPricing } from "../../models/reference.js";
|
|
20
|
+
import { createModelRuntime, resolveInitialModel, wrapModelRegistry } from "../../models/runtime.js";
|
|
21
|
+
import { formatConfigDiagnostic } from "../../shared/config-diagnostic.js";
|
|
22
|
+
import { errorMessage } from "../../shared/text-utils.js";
|
|
23
|
+
import { isRecord } from "../../shared/type-guards.js";
|
|
24
|
+
import { withTimeout } from "../../shared/with-timeout.js";
|
|
25
|
+
import { loadPipiclawSkills, resolvePipiclawSkills } from "../../skills/loader.js";
|
|
26
|
+
import { discoverSubAgents } from "../../subagents/discovery.js";
|
|
27
|
+
import { TASK_SESSIONS_DIRNAME, taskSessionPath } from "../../tasks/session-path.js";
|
|
28
|
+
import { createPipiclawTools } from "../../tools/index.js";
|
|
29
|
+
import { buildPipiclawSystemPrompt } from "../prompt/builder.js";
|
|
30
|
+
import { createPromptBoundaryExtension } from "../prompt/extension.js";
|
|
31
|
+
import { measureToolSchemas, TOOL_SCHEMA_TARGET_UNITS, toolSchemaBudgetWarning } from "../prompt/manifest.js";
|
|
32
|
+
import { loadPlaybooks, loadWorkspacePromptResources } from "../prompt/resources.js";
|
|
33
|
+
import { createCommandExtension } from "./command-extension.js";
|
|
34
|
+
import { getLastAssistantUsage, isAutoCompactionEndEvent } from "./event-guards.js";
|
|
35
|
+
import { asSdkSettingsManager, DEFAULT_MAIN_THINKING_LEVEL, initializeThinkingLevelCompat, setSessionBaseToolsOverride, } from "./session-adapter.js";
|
|
36
|
+
import { handleSessionEvent } from "./session-events.js";
|
|
37
|
+
import { SessionResourceGate } from "./session-resource-gate.js";
|
|
38
|
+
const MODEL_REGISTRY_REFRESH_TIMEOUT_MS = 15_000;
|
|
39
|
+
const SESSION_RELOAD_TIMEOUT_MS = 30_000;
|
|
40
|
+
const CONTEXT_FAULT_MESSAGE = "会话上下文保存失败。请让部署者检查服务器存储后发送 /new 重新开启会话。";
|
|
41
|
+
/** The text of a message's `content`, whether it is a bare string or a multimodal part array. */
|
|
42
|
+
function plainTextOf(content) {
|
|
43
|
+
if (typeof content === "string")
|
|
44
|
+
return content;
|
|
45
|
+
if (!Array.isArray(content))
|
|
46
|
+
return "";
|
|
47
|
+
return content
|
|
48
|
+
.map((part) => (isRecord(part) && part.type === "text" && typeof part.text === "string" ? part.text : ""))
|
|
49
|
+
.join("\n");
|
|
50
|
+
}
|
|
51
|
+
/** Task sessions live under `<channelDir>/tasks/.sessions/`; nothing else may be mistaken for one. */
|
|
52
|
+
function isTaskSessionPath(sessionFile) {
|
|
53
|
+
return sessionFile?.replace(/\\/g, "/").includes(`/${TASK_SESSIONS_DIRNAME}/`) === true;
|
|
54
|
+
}
|
|
55
|
+
/** Surface settings.json load errors (once drained) as warnings; shared by construction and reload. */
|
|
56
|
+
export function reportSettingsDiagnostics(settingsManager, channelId, appHomeDir) {
|
|
57
|
+
for (const { scope, error } of settingsManager.drainErrors()) {
|
|
58
|
+
log.logWarn("config.settings.load_failed", "Settings load failed", {
|
|
59
|
+
channelId,
|
|
60
|
+
reason: error.message,
|
|
61
|
+
fields: { scope, path: join(appHomeDir, "settings.json") },
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
export class SessionHost {
|
|
66
|
+
constructor(deps) {
|
|
67
|
+
this.deps = deps;
|
|
68
|
+
/**
|
|
69
|
+
* Flips true only once `initializeSession` has fully assigned `this.session`
|
|
70
|
+
* and loaded its resources. Synchronous dispatch-path callers (`isKnownSlashCommand`)
|
|
71
|
+
* must not touch `this.session` before this — the model runtime takes hundreds
|
|
72
|
+
* of ms to build and the first message can arrive first (spec 048 F2).
|
|
73
|
+
*/
|
|
74
|
+
this.sessionInitialized = false;
|
|
75
|
+
this.currentTools = [];
|
|
76
|
+
this.firstTurnMemoryBootstrapPending = true;
|
|
77
|
+
/** Mirror of `tools.tasks.enabled` from the last tools-config load (see buildRuntimeTools). */
|
|
78
|
+
this.tasksEnabled = true;
|
|
79
|
+
this.contextFaults = new WeakSet();
|
|
80
|
+
this.channelId = deps.channelId;
|
|
81
|
+
this.channelDir = deps.channelDir;
|
|
82
|
+
this.workspaceDir = deps.workspaceDir;
|
|
83
|
+
this.appHomeDir = deps.appHomeDir;
|
|
84
|
+
this.authConfigPath = deps.authConfigPath;
|
|
85
|
+
this.modelsConfigPath = deps.modelsConfigPath;
|
|
86
|
+
this.onSessionEvent = deps.onSessionEvent;
|
|
87
|
+
this.mediaSender = deps.mediaSender;
|
|
88
|
+
this.projectScope = deps.projectScope;
|
|
89
|
+
this.settingsManager = deps.settingsManager;
|
|
90
|
+
this.loadSecurityConfig = deps.loadSecurityConfig;
|
|
91
|
+
this.executor = deps.executor;
|
|
92
|
+
this.fileStore = deps.fileStore;
|
|
93
|
+
this.jobManager = deps.jobManager;
|
|
94
|
+
this.runManager = deps.runManager;
|
|
95
|
+
this.memoryLifecycle = deps.memoryLifecycle;
|
|
96
|
+
this.models = deps.models;
|
|
97
|
+
this.ledger = deps.ledger;
|
|
98
|
+
this.currentSkills = deps.initialSkills;
|
|
99
|
+
this.sessionResourceGate = new SessionResourceGate(async () => {
|
|
100
|
+
await this.reloadSessionResources();
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
get runState() {
|
|
104
|
+
return this.deps.getRunState();
|
|
105
|
+
}
|
|
106
|
+
get agent() {
|
|
107
|
+
return this.session.agent;
|
|
108
|
+
}
|
|
109
|
+
get sessionManager() {
|
|
110
|
+
return this.session.sessionManager;
|
|
111
|
+
}
|
|
112
|
+
/** Kick off asynchronous session construction. The first message can arrive before it settles. */
|
|
113
|
+
start(sessionManager) {
|
|
114
|
+
this.sessionReady = this.initializeSession(sessionManager);
|
|
115
|
+
}
|
|
116
|
+
markContextFault(session, error) {
|
|
117
|
+
this.contextFaults.add(session);
|
|
118
|
+
log.logWarn("agent.session.context_failed", "Session context persistence failed", {
|
|
119
|
+
channelId: this.channelId,
|
|
120
|
+
reason: errorMessage(error),
|
|
121
|
+
fields: { sessionId: session.sessionManager.getSessionId(), stage: "fallback-context-edit" },
|
|
122
|
+
});
|
|
123
|
+
return new Error(CONTEXT_FAULT_MESSAGE, { cause: error });
|
|
124
|
+
}
|
|
125
|
+
assertContextHealthy() {
|
|
126
|
+
if (this.contextFaults.has(this.session))
|
|
127
|
+
throw new Error(CONTEXT_FAULT_MESSAGE);
|
|
128
|
+
}
|
|
129
|
+
/** Run a prompt (or steer) with the resource gate and the context-fault guard. */
|
|
130
|
+
runPrompt(fn) {
|
|
131
|
+
return this.sessionResourceGate.runPrompt(async () => {
|
|
132
|
+
this.assertContextHealthy();
|
|
133
|
+
return fn();
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
/** Stop listening to the live session and dispose it (no-op error handling is the caller's). */
|
|
137
|
+
retireLiveSession() {
|
|
138
|
+
this.sessionUnsubscribe?.();
|
|
139
|
+
this.sessionUnsubscribe = undefined;
|
|
140
|
+
this.session.dispose();
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Release the session once idle. Guards a dispose() racing construction: initializeSession
|
|
144
|
+
* assigns `this.session` asynchronously, so a runner disposed the instant after creation may
|
|
145
|
+
* not have one yet.
|
|
146
|
+
*/
|
|
147
|
+
async disposeSession() {
|
|
148
|
+
await this.sessionReady;
|
|
149
|
+
this.sessionUnsubscribe?.();
|
|
150
|
+
this.sessionUnsubscribe = undefined;
|
|
151
|
+
try {
|
|
152
|
+
this.session.dispose();
|
|
153
|
+
}
|
|
154
|
+
catch (error) {
|
|
155
|
+
log.logWarn("agent.session.dispose_failed", "Session dispose failed", {
|
|
156
|
+
channelId: this.channelId,
|
|
157
|
+
reason: errorMessage(error),
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
async refreshSessionResources() {
|
|
162
|
+
await this.ensureSessionReady();
|
|
163
|
+
await this.sessionResourceGate.requestRefresh();
|
|
164
|
+
}
|
|
165
|
+
async initializeSession(sessionManager) {
|
|
166
|
+
// Build the canonical async model/auth runtime and its synchronous read shell.
|
|
167
|
+
this.modelRuntime = await createModelRuntime({
|
|
168
|
+
authConfigPath: this.authConfigPath,
|
|
169
|
+
modelsConfigPath: this.modelsConfigPath,
|
|
170
|
+
});
|
|
171
|
+
this.modelRegistry = wrapModelRegistry(this.modelRuntime);
|
|
172
|
+
// Resolve model: prefer saved global default, fall back to first available model.
|
|
173
|
+
this.models.activeModel = resolveInitialModel(this.modelRegistry, this.settingsManager);
|
|
174
|
+
log.logInfo(`Using model: ${this.models.activeModel.provider}/${this.models.activeModel.id} (${this.models.activeModel.name})`);
|
|
175
|
+
this.subAgentDiscovery = await this.refreshSubAgentDiscovery();
|
|
176
|
+
const initial = await this.createSessionRuntime(sessionManager);
|
|
177
|
+
this.session = initial.session;
|
|
178
|
+
this.sessionRuntime = new AgentSessionRuntime(this.session, this.createAgentSessionServices(initial.resourceLoader), async ({ sessionManager, sessionStartEvent }) => {
|
|
179
|
+
// `/new`, fork, and switch already wrote the target session's durable header by
|
|
180
|
+
// this point (the SDK does it synchronously before invoking this callback); commit
|
|
181
|
+
// the pointer before we rebuild and rebind to it, so a crash between "SDK created
|
|
182
|
+
// session" and "we finished rebinding" leaves the old ref (and old session)
|
|
183
|
+
// authoritative rather than an orphaned new file (spec 043, D1.3).
|
|
184
|
+
// A task session is not the channel's chat session: never repoint the active-session
|
|
185
|
+
// ref at it, or `/new` and restart recovery would adopt a task's transcript as the
|
|
186
|
+
// conversation (spec 051, D3).
|
|
187
|
+
if (!isTaskSessionPath(sessionManager.getSessionFile())) {
|
|
188
|
+
await commitActiveSessionRef(this.channelDir, sessionManager);
|
|
189
|
+
}
|
|
190
|
+
const next = await this.createSessionRuntime(sessionManager, sessionStartEvent);
|
|
191
|
+
return {
|
|
192
|
+
session: next.session,
|
|
193
|
+
extensionsResult: next.resourceLoader.getExtensions(),
|
|
194
|
+
services: this.createAgentSessionServices(next.resourceLoader),
|
|
195
|
+
diagnostics: [],
|
|
196
|
+
};
|
|
197
|
+
});
|
|
198
|
+
this.sessionRuntime.setRebindSession(async (session) => {
|
|
199
|
+
this.session = session;
|
|
200
|
+
await this.bindSessionExtensions();
|
|
201
|
+
this.subscribeToSessionEvents();
|
|
202
|
+
});
|
|
203
|
+
// Subscribe to session events
|
|
204
|
+
this.subscribeToSessionEvents();
|
|
205
|
+
await this.bindSessionExtensions();
|
|
206
|
+
// A restart resumes an existing transcript: if that session was already handed its
|
|
207
|
+
// bootstrap before the daemon went down, the first turn after recovery must not inject a
|
|
208
|
+
// second copy just because a process-local field starts out `true`.
|
|
209
|
+
this.syncMemoryBootstrapPendingFromSession();
|
|
210
|
+
this.sessionInitialized = true;
|
|
211
|
+
}
|
|
212
|
+
async reloadSessionResources() {
|
|
213
|
+
this.settingsManager.reload();
|
|
214
|
+
this.reportSettingsDiagnostics();
|
|
215
|
+
const skills = loadPipiclawSkills(this.channelDir);
|
|
216
|
+
this.currentSkills = skills;
|
|
217
|
+
this.subAgentDiscovery = await this.refreshSubAgentDiscovery();
|
|
218
|
+
this.rebuildSessionTools();
|
|
219
|
+
try {
|
|
220
|
+
await withTimeout(`[${this.channelId}] session reload`, SESSION_RELOAD_TIMEOUT_MS, () => this.session.reload());
|
|
221
|
+
}
|
|
222
|
+
catch (error) {
|
|
223
|
+
log.logWarn("agent.session.reload_unsettled", "Session reload did not settle", {
|
|
224
|
+
channelId: this.channelId,
|
|
225
|
+
reason: errorMessage(error),
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
async bindSessionExtensions() {
|
|
230
|
+
await this.session.bindExtensions({
|
|
231
|
+
commandContextActions: {
|
|
232
|
+
waitForIdle: () => this.session.agent.waitForIdle(),
|
|
233
|
+
newSession: async (options) => {
|
|
234
|
+
return await this.sessionRuntime.newSession(options);
|
|
235
|
+
},
|
|
236
|
+
fork: async (entryId, options) => {
|
|
237
|
+
const result = await this.sessionRuntime.fork(entryId, options);
|
|
238
|
+
this.syncMemoryBootstrapPendingFromSession();
|
|
239
|
+
return { cancelled: result.cancelled };
|
|
240
|
+
},
|
|
241
|
+
navigateTree: async (targetId, options) => {
|
|
242
|
+
const result = await this.session.navigateTree(targetId, options);
|
|
243
|
+
this.syncMemoryBootstrapPendingFromSession();
|
|
244
|
+
return { cancelled: result.cancelled };
|
|
245
|
+
},
|
|
246
|
+
switchSession: async (sessionPath, options) => {
|
|
247
|
+
const result = await this.sessionRuntime.switchSession(sessionPath, options);
|
|
248
|
+
this.syncMemoryBootstrapPendingFromSession();
|
|
249
|
+
return result;
|
|
250
|
+
},
|
|
251
|
+
reload: async () => {
|
|
252
|
+
await this.refreshSessionResources();
|
|
253
|
+
},
|
|
254
|
+
},
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
async ensureSessionReady() {
|
|
258
|
+
await this.sessionReady;
|
|
259
|
+
}
|
|
260
|
+
async refreshSubAgentDiscovery() {
|
|
261
|
+
// Re-resolves models.json *and* every provider's auth, which for an OAuth
|
|
262
|
+
// provider is a network call. Failing open keeps the last known model
|
|
263
|
+
// snapshot — stale availability is a far smaller problem than a reload
|
|
264
|
+
// (and, through it, a `/new` turn) that never returns.
|
|
265
|
+
try {
|
|
266
|
+
await withTimeout(`[${this.channelId}] model registry refresh`, MODEL_REGISTRY_REFRESH_TIMEOUT_MS, () => this.modelRegistry.refresh());
|
|
267
|
+
}
|
|
268
|
+
catch (error) {
|
|
269
|
+
log.logWarn("agent.models.refresh_unsettled", "Model registry refresh did not settle; using the previous snapshot", { channelId: this.channelId, reason: errorMessage(error) });
|
|
270
|
+
}
|
|
271
|
+
const discovery = discoverSubAgents(this.workspaceDir, this.modelRegistry.getAvailable());
|
|
272
|
+
for (const warning of discovery.warnings) {
|
|
273
|
+
log.logWarn("config.subagents.warning", "Sub-agent config warning", {
|
|
274
|
+
channelId: this.channelId,
|
|
275
|
+
reason: warning,
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
return discovery;
|
|
279
|
+
}
|
|
280
|
+
reportSettingsDiagnostics() {
|
|
281
|
+
reportSettingsDiagnostics(this.settingsManager, this.channelId, this.appHomeDir);
|
|
282
|
+
}
|
|
283
|
+
reportConfigDiagnostics(diagnostics) {
|
|
284
|
+
for (const diagnostic of diagnostics) {
|
|
285
|
+
log.logWarn("config.diagnostic", formatConfigDiagnostic(diagnostic), {
|
|
286
|
+
channelId: this.channelId,
|
|
287
|
+
fields: { path: diagnostic.path },
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Build the Pipiclaw-owned system prompt (spec 025). This replaces pi's default
|
|
293
|
+
* base prompt entirely: identity, execution contract, hard invariants, the tool
|
|
294
|
+
* catalog and the workspace files are ours. pi still appends its tail (skills,
|
|
295
|
+
* date, cwd), and the boundary footer is appended after that by the prompt
|
|
296
|
+
* extension.
|
|
297
|
+
*
|
|
298
|
+
* Nothing channel-specific enters this text — that is what lets two channels in
|
|
299
|
+
* one workspace share a cached prompt prefix. Channel facts ride the turn.
|
|
300
|
+
*/
|
|
301
|
+
buildSystemPrompt() {
|
|
302
|
+
const toolNames = this.currentTools.map((tool) => tool.name);
|
|
303
|
+
const resources = loadWorkspacePromptResources(this.workspaceDir);
|
|
304
|
+
this.lastWorkspaceResources = resources;
|
|
305
|
+
const build = buildPipiclawSystemPrompt({
|
|
306
|
+
tools: this.currentTools.map((tool) => ({
|
|
307
|
+
name: tool.name,
|
|
308
|
+
description: tool.description,
|
|
309
|
+
})),
|
|
310
|
+
soul: resources.soul,
|
|
311
|
+
agents: resources.agents,
|
|
312
|
+
playbooks: loadPlaybooks(toolNames),
|
|
313
|
+
subAgents: this.subAgentDiscovery.agents.map((agent) => ({
|
|
314
|
+
name: agent.name,
|
|
315
|
+
description: agent.description,
|
|
316
|
+
runtime: agent.runtime,
|
|
317
|
+
harness: agent.harness,
|
|
318
|
+
workload: agent.workload ?? (agent.runtime === "external" ? "heavy" : "light"),
|
|
319
|
+
mutates: agent.mutates,
|
|
320
|
+
unavailable: agent.unavailable,
|
|
321
|
+
})),
|
|
322
|
+
});
|
|
323
|
+
for (const diagnostic of [...resources.diagnostics, ...build.diagnostics]) {
|
|
324
|
+
if (diagnostic.level === "info")
|
|
325
|
+
continue;
|
|
326
|
+
log.logWarn("agent.prompt.diagnostic", "Prompt section diagnostic", {
|
|
327
|
+
channelId: this.channelId,
|
|
328
|
+
reason: diagnostic.message,
|
|
329
|
+
fields: { level: diagnostic.level, section: diagnostic.sectionId },
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
// Only a real change is worth a line: a reload that produced the same bytes is noise.
|
|
333
|
+
if (this.lastPromptBuild?.fingerprint !== build.fingerprint) {
|
|
334
|
+
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"})`);
|
|
335
|
+
}
|
|
336
|
+
this.lastPromptBuild = build;
|
|
337
|
+
return build;
|
|
338
|
+
}
|
|
339
|
+
createResourceLoader() {
|
|
340
|
+
return new DefaultResourceLoader({
|
|
341
|
+
cwd: this.projectScope.projectRoot,
|
|
342
|
+
agentDir: this.appHomeDir,
|
|
343
|
+
settingsManager: asSdkSettingsManager(this.settingsManager),
|
|
344
|
+
extensionFactories: [
|
|
345
|
+
this.memoryLifecycle.createExtensionFactory(),
|
|
346
|
+
createPromptBoundaryExtension({
|
|
347
|
+
getFooter: () => this.lastPromptBuild?.footer ?? "",
|
|
348
|
+
onFinalPrompt: (systemPrompt) => {
|
|
349
|
+
this.lastFinalPrompt = systemPrompt;
|
|
350
|
+
},
|
|
351
|
+
}),
|
|
352
|
+
createCommandExtension({
|
|
353
|
+
getCurrentModel: () => this.session.model ?? this.models.activeModel,
|
|
354
|
+
getAvailableModels: async () => {
|
|
355
|
+
await this.modelRegistry.refresh();
|
|
356
|
+
return this.modelRegistry.getAvailable();
|
|
357
|
+
},
|
|
358
|
+
getSessionStats: () => this.session.getSessionStats(),
|
|
359
|
+
getThinkingLevel: () => this.session.thinkingLevel,
|
|
360
|
+
getAvailableThinkingLevels: () => this.session.getAvailableThinkingLevels(),
|
|
361
|
+
setThinkingLevel: (level) => this.models.setThinkingLevelCompat(level),
|
|
362
|
+
cycleThinkingLevel: () => this.models.cycleThinkingLevelCompat(),
|
|
363
|
+
getLastResponseModel: () => getLastAssistantUsage(this.session.messages)?.responseModel,
|
|
364
|
+
switchModel: async (model) => {
|
|
365
|
+
await this.models.setModelWithThinkingPreservation(model);
|
|
366
|
+
this.models.activeModel = model;
|
|
367
|
+
// Manual /model switch redefines the preferred model and clears fallback state.
|
|
368
|
+
this.models.clearFallbackState();
|
|
369
|
+
},
|
|
370
|
+
refreshSessionResources: async () => {
|
|
371
|
+
await this.refreshSessionResources();
|
|
372
|
+
},
|
|
373
|
+
runMemoryCommand: async (args) => handleMemoryCommand({
|
|
374
|
+
channelId: this.channelId,
|
|
375
|
+
channelDir: this.channelDir,
|
|
376
|
+
appHomeDir: this.appHomeDir,
|
|
377
|
+
args,
|
|
378
|
+
}),
|
|
379
|
+
}),
|
|
380
|
+
],
|
|
381
|
+
// Pipiclaw owns the base prompt: with a custom prompt present, pi emits no
|
|
382
|
+
// default identity, no pi docs index and no `Available tools: (none)` block.
|
|
383
|
+
systemPromptOverride: () => this.buildSystemPrompt().text,
|
|
384
|
+
// Nothing may slip in behind the section pipeline — not pi's app-level
|
|
385
|
+
// APPEND_SYSTEM.md, not a base append. SOUL/AGENTS are rendered as sections.
|
|
386
|
+
appendSystemPromptOverride: () => [],
|
|
387
|
+
agentsFilesOverride: () => ({ agentsFiles: [] }),
|
|
388
|
+
// Skills stay in the ResourceLoader: they drive `/skill:name` and pi's
|
|
389
|
+
// `<available_skills>` index together. Only the merge policy is ours.
|
|
390
|
+
skillsOverride: (base) => {
|
|
391
|
+
const merged = resolvePipiclawSkills(base, this.currentSkills);
|
|
392
|
+
for (const diagnostic of merged.diagnostics) {
|
|
393
|
+
log.logWarn("agent.skills.diagnostic", "Skill diagnostic", {
|
|
394
|
+
channelId: this.channelId,
|
|
395
|
+
reason: diagnostic.message,
|
|
396
|
+
fields: { type: diagnostic.type, path: diagnostic.path },
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
return merged;
|
|
400
|
+
},
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
createAgentSessionServices(resourceLoader) {
|
|
404
|
+
return {
|
|
405
|
+
cwd: this.projectScope.projectRoot,
|
|
406
|
+
agentDir: this.appHomeDir,
|
|
407
|
+
settingsManager: asSdkSettingsManager(this.settingsManager),
|
|
408
|
+
modelRuntime: this.modelRuntime,
|
|
409
|
+
resourceLoader,
|
|
410
|
+
diagnostics: [],
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Load a freshly constructed ResourceLoader before an `AgentSession` is built on top of it.
|
|
415
|
+
*
|
|
416
|
+
* `AgentSession` reads `resourceLoader.getExtensions()` in its constructor, and a loader that
|
|
417
|
+
* has never been loaded answers with an *empty* set. Skipping this leaves a replacement session
|
|
418
|
+
* with no extensions at all — no command extension (so `/model`, `/thinking`, `/session`,
|
|
419
|
+
* `/compact` and `/memory` fall through to the model as plain text), no memory lifecycle, no
|
|
420
|
+
* prompt-boundary footer, and no prompt templates. Tolerated on failure the same way
|
|
421
|
+
* `reloadSessionResources` tolerates a stuck reload: a degraded session still answers chat.
|
|
422
|
+
*/
|
|
423
|
+
async loadSessionResources(resourceLoader) {
|
|
424
|
+
try {
|
|
425
|
+
await withTimeout(`[${this.channelId}] session resource load`, SESSION_RELOAD_TIMEOUT_MS, () => resourceLoader.reload());
|
|
426
|
+
}
|
|
427
|
+
catch (error) {
|
|
428
|
+
log.logWarn("agent.session.resources_failed", "Session resources did not load", {
|
|
429
|
+
channelId: this.channelId,
|
|
430
|
+
reason: errorMessage(error),
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* Resolve the initial thinking level using the same precedence as pi's SDK:
|
|
436
|
+
* session history, configured default, then medium. The effective value is
|
|
437
|
+
* clamped to the selected model before the session starts.
|
|
438
|
+
*/
|
|
439
|
+
initializeThinkingLevel(agent, model, sessionManager) {
|
|
440
|
+
initializeThinkingLevelCompat(agent, model, sessionManager, this.settingsManager.getDefaultThinkingLevel());
|
|
441
|
+
}
|
|
442
|
+
async createSessionRuntime(sessionManager, sessionStartEvent) {
|
|
443
|
+
const tools = this.buildRuntimeTools();
|
|
444
|
+
const agent = new Agent({
|
|
445
|
+
initialState: {
|
|
446
|
+
systemPrompt: "",
|
|
447
|
+
model: this.models.activeModel,
|
|
448
|
+
thinkingLevel: DEFAULT_MAIN_THINKING_LEVEL,
|
|
449
|
+
tools: [],
|
|
450
|
+
messages: sessionManager.buildSessionContext().messages,
|
|
451
|
+
},
|
|
452
|
+
convertToLlm,
|
|
453
|
+
getApiKey: async () => getApiKeyForModel(this.modelRegistry, this.models.activeModel),
|
|
454
|
+
streamFn: streamSimple,
|
|
455
|
+
});
|
|
456
|
+
this.initializeThinkingLevel(agent, this.models.activeModel, sessionManager);
|
|
457
|
+
const resourceLoader = this.createResourceLoader();
|
|
458
|
+
// Must precede `new AgentSession`: the session snapshots the loader's extensions in its
|
|
459
|
+
// constructor (see `loadSessionResources`).
|
|
460
|
+
await this.loadSessionResources(resourceLoader);
|
|
461
|
+
const sessionSettingsManager = asSdkSettingsManager(this.settingsManager);
|
|
462
|
+
const session = new AgentSession({
|
|
463
|
+
agent,
|
|
464
|
+
sessionManager,
|
|
465
|
+
settingsManager: sessionSettingsManager,
|
|
466
|
+
cwd: this.projectScope.projectRoot,
|
|
467
|
+
modelRuntime: this.modelRuntime,
|
|
468
|
+
resourceLoader,
|
|
469
|
+
baseToolsOverride: Object.fromEntries(tools.map((tool) => [tool.name, tool])),
|
|
470
|
+
initialActiveToolNames: tools.map((tool) => tool.name),
|
|
471
|
+
sessionStartEvent,
|
|
472
|
+
});
|
|
473
|
+
this.sessionSettingsManager = sessionSettingsManager;
|
|
474
|
+
return { session, resourceLoader };
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* Bind this runner to a task cycle's own session (spec 051, D3/INV-5).
|
|
478
|
+
*
|
|
479
|
+
* Task work must not accumulate in the channel's chat transcript: the one real channel on the
|
|
480
|
+
* author's machine had grown to 7.4 MB and been compacted six times because chat and two daily
|
|
481
|
+
* tasks shared it, so every compaction damaged all three at once. Swapping the bound session
|
|
482
|
+
* per turn gives each task its own bounded context while leaving turn state, `/stop`, and
|
|
483
|
+
* delivery exactly where they already are.
|
|
484
|
+
*/
|
|
485
|
+
async bindTaskSession(taskId) {
|
|
486
|
+
await this.sessionReady;
|
|
487
|
+
const path = taskSessionPath(this.channelDir, taskId);
|
|
488
|
+
await mkdir(dirname(path), { recursive: true });
|
|
489
|
+
this.taskLoop = { taskId };
|
|
490
|
+
await this.sessionRuntime.switchSession(path);
|
|
491
|
+
this.syncMemoryBootstrapPendingFromSession();
|
|
492
|
+
}
|
|
493
|
+
/** Return to the channel's chat session after a task step. Safe to call when already bound. */
|
|
494
|
+
async bindChatSession() {
|
|
495
|
+
if (!this.taskLoop)
|
|
496
|
+
return;
|
|
497
|
+
this.taskLoop = undefined;
|
|
498
|
+
await this.sessionRuntime.switchSession(join(this.channelDir, resolveActiveSessionFile(this.channelDir)));
|
|
499
|
+
this.syncMemoryBootstrapPendingFromSession();
|
|
500
|
+
}
|
|
501
|
+
/** Bootstrap presence follows canonical context, including omissions and compaction.
|
|
502
|
+
* Returning from a task or restarting must neither duplicate a visible bootstrap nor
|
|
503
|
+
* mistake an omitted failed input for one. Raw messages remain available to memory/recovery.
|
|
504
|
+
*/
|
|
505
|
+
syncMemoryBootstrapPendingFromSession() {
|
|
506
|
+
const injected = this.sessionManager.buildSessionContext().messages.some((value) => {
|
|
507
|
+
const message = value;
|
|
508
|
+
if (!isRecord(message))
|
|
509
|
+
return false;
|
|
510
|
+
return message.role === "user" && hasMemoryBootstrapBlock(plainTextOf(message.content));
|
|
511
|
+
});
|
|
512
|
+
this.firstTurnMemoryBootstrapPending = !injected;
|
|
513
|
+
}
|
|
514
|
+
/** Which task loop this runner is currently bound to, if any. */
|
|
515
|
+
getTaskLoop() {
|
|
516
|
+
return this.taskLoop;
|
|
517
|
+
}
|
|
518
|
+
buildRuntimeTools() {
|
|
519
|
+
const securityLoad = this.loadSecurityConfig();
|
|
520
|
+
const toolsLoad = loadToolsConfigWithDiagnostics(this.appHomeDir);
|
|
521
|
+
this.reportConfigDiagnostics([...securityLoad.diagnostics, ...toolsLoad.diagnostics]);
|
|
522
|
+
this.tasksEnabled = toolsLoad.config.tools.tasks.enabled;
|
|
523
|
+
const tools = createPipiclawTools({
|
|
524
|
+
jobManager: this.jobManager,
|
|
525
|
+
runManager: this.runManager,
|
|
526
|
+
executor: this.executor,
|
|
527
|
+
fileStore: this.fileStore,
|
|
528
|
+
getCurrentModel: () => this.models.activeModel,
|
|
529
|
+
getAvailableModels: () => this.modelRegistry.getAvailable(),
|
|
530
|
+
resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
|
|
531
|
+
workspaceDir: this.workspaceDir,
|
|
532
|
+
projectScope: this.projectScope,
|
|
533
|
+
channelDir: this.channelDir,
|
|
534
|
+
channelId: this.channelId,
|
|
535
|
+
getSubAgentDiscovery: () => this.subAgentDiscovery,
|
|
536
|
+
getSubAgentModelReference: () => this.settingsManager.getSubAgentModelReference(),
|
|
537
|
+
resolveFallbackModel: () => this.models.resolveFallbackModel(),
|
|
538
|
+
getSessionSearchSettings: () => this.settingsManager.getSessionSearchSettings(),
|
|
539
|
+
securityConfig: securityLoad.config,
|
|
540
|
+
toolsConfig: toolsLoad.config,
|
|
541
|
+
mediaSender: this.mediaSender,
|
|
542
|
+
taskLoop: this.taskLoop,
|
|
543
|
+
getToolsUsed: () => this.runState.toolsUsed,
|
|
544
|
+
// Assistant usage only: an internal sub-agent's cost is also in `totalUsage`, and a bound
|
|
545
|
+
// one is already credited to the task when it settles.
|
|
546
|
+
getStepCost: () => ({ usd: this.runState.assistantUsage.cost.total, estimated: !this.runState.costKnown }),
|
|
547
|
+
});
|
|
548
|
+
this.currentTools = tools;
|
|
549
|
+
// Tool schemas are billed with the system prompt and, unlike it, nothing trims them.
|
|
550
|
+
// Warn where the prompt's own budget diagnostics are reported, once per tool rebuild.
|
|
551
|
+
const schemas = measureToolSchemas(tools);
|
|
552
|
+
if (schemas.units > TOOL_SCHEMA_TARGET_UNITS) {
|
|
553
|
+
log.logWarn("agent.tools.schema_over_budget", "Tool schemas over budget", {
|
|
554
|
+
channelId: this.channelId,
|
|
555
|
+
reason: toolSchemaBudgetWarning(schemas),
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
return tools;
|
|
559
|
+
}
|
|
560
|
+
rebuildSessionTools() {
|
|
561
|
+
const tools = this.buildRuntimeTools();
|
|
562
|
+
setSessionBaseToolsOverride(this.session, tools, this.channelId);
|
|
563
|
+
this.agent.state.tools = tools;
|
|
564
|
+
this.session.setActiveToolsByName(tools.map((tool) => tool.name));
|
|
565
|
+
}
|
|
566
|
+
// === Session event subscription ===
|
|
567
|
+
subscribeToSessionEvents() {
|
|
568
|
+
this.sessionUnsubscribe?.();
|
|
569
|
+
this.sessionUnsubscribe = this.session.subscribe((event) => {
|
|
570
|
+
// Observation is deliberately before our consumer and must never alter a turn.
|
|
571
|
+
try {
|
|
572
|
+
this.onSessionEvent?.(event, this.channelId);
|
|
573
|
+
}
|
|
574
|
+
catch (err) {
|
|
575
|
+
log.logWarn("agent.session.observer_failed", "Session observer failed", {
|
|
576
|
+
channelId: this.channelId,
|
|
577
|
+
reason: errorMessage(err),
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
if (isRecord(event) && event.type === "message_start") {
|
|
581
|
+
this.deps.markStreaming();
|
|
582
|
+
}
|
|
583
|
+
if (isRecord(event) && "reason" in event && event.reason === "new") {
|
|
584
|
+
this.firstTurnMemoryBootstrapPending = true;
|
|
585
|
+
}
|
|
586
|
+
// Spec 050, D1: compaction rewrites the first-turn bootstrap into a summary; re-inject
|
|
587
|
+
// the authoritative index on the next turn so memory does not decay with the transcript.
|
|
588
|
+
if (isAutoCompactionEndEvent(event) && !event.aborted && !event.errorMessage) {
|
|
589
|
+
this.firstTurnMemoryBootstrapPending = true;
|
|
590
|
+
}
|
|
591
|
+
if (!this.runState.ctx || !this.runState.logCtx || !this.runState.queue)
|
|
592
|
+
return;
|
|
593
|
+
// The SDK listener signature is `(event) => void`, so the promise below is fire-and-forget.
|
|
594
|
+
// Without this catch, a rejection inside handleSessionEvent becomes an unhandled rejection
|
|
595
|
+
// that terminates the daemon under Node's default policy.
|
|
596
|
+
handleSessionEvent(event, {
|
|
597
|
+
ctx: this.runState.ctx,
|
|
598
|
+
logCtx: this.runState.logCtx,
|
|
599
|
+
queue: this.runState.queue,
|
|
600
|
+
pendingTools: this.runState.pendingTools,
|
|
601
|
+
store: this.runState.store,
|
|
602
|
+
runState: this.runState,
|
|
603
|
+
memoryLifecycle: this.memoryLifecycle,
|
|
604
|
+
ledger: this.ledger,
|
|
605
|
+
isModelCostKnown: (reference) => {
|
|
606
|
+
const model = findExactModelReferenceMatch(reference, this.modelRegistry.getAvailable()).match;
|
|
607
|
+
return model ? hasKnownModelPricing(model) : false;
|
|
608
|
+
},
|
|
609
|
+
refreshSessionResources: async () => {
|
|
610
|
+
await this.refreshSessionResources();
|
|
611
|
+
},
|
|
612
|
+
skillsDir: join(this.workspaceDir, "skills"),
|
|
613
|
+
}).catch((err) => {
|
|
614
|
+
log.logWarn("agent.session.handler_failed", "Session event handler failed", {
|
|
615
|
+
channelId: this.channelId,
|
|
616
|
+
reason: errorMessage(err),
|
|
617
|
+
});
|
|
618
|
+
});
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
}
|
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Preventive-compaction budget: estimate the tokens an incoming message adds and decide whether to
|
|
3
|
+
* compact before sending, instead of waiting for the provider to reject the request.
|
|
4
|
+
*/
|
|
5
|
+
import { estimateTokens } from "../../shared/format.js";
|
|
2
6
|
export const PREVENTIVE_COMPACTION_THRESHOLD_RATIO = 0.75;
|
|
3
7
|
/**
|
|
4
8
|
* Rough per-image token cost (spec 049), used only to keep the preventive-compaction projection
|
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Formatting helpers for turn progress entries and for clipping over-length user input.
|
|
3
|
+
*/
|
|
4
|
+
import type { ProgressEntryKind } from "../types.js";
|
|
2
5
|
/**
|
|
3
6
|
* Head + tail of an over-length message, with the middle replaced by a marker.
|
|
4
7
|
*
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import * as log from "
|
|
2
|
-
import { errorMessage } from "
|
|
3
|
-
import { withTimeout } from "
|
|
1
|
+
import * as log from "../../log.js";
|
|
2
|
+
import { errorMessage } from "../../shared/text-utils.js";
|
|
3
|
+
import { withTimeout } from "../../shared/with-timeout.js";
|
|
4
4
|
/**
|
|
5
5
|
* Ceiling on how long `drain()` blocks the caller. The queue carries outbound
|
|
6
6
|
* delivery calls plus whatever a session event enqueued (a resource refresh, a
|