@oyasmi/pipiclaw 0.9.3 → 0.9.4-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/builtin-commands.d.ts +19 -0
- package/dist/agent/builtin-commands.js +80 -0
- package/dist/agent/channel-runner.d.ts +20 -208
- package/dist/agent/channel-runner.js +167 -1188
- package/dist/agent/maintenance-context.d.ts +1 -1
- package/dist/agent/maintenance-context.js +1 -1
- package/dist/agent/prompt/manifest.d.ts +6 -1
- package/dist/agent/prompt/manifest.js +45 -64
- package/dist/agent/prompt/resources.d.ts +3 -0
- package/dist/agent/prompt/resources.js +11 -2
- package/dist/agent/runner-factory.d.ts +1 -43
- package/dist/agent/{command-extension.d.ts → session/command-extension.d.ts} +4 -0
- package/dist/agent/{command-extension.js → session/command-extension.js} +48 -35
- package/dist/agent/{type-guards.d.ts → session/event-guards.d.ts} +2 -2
- package/dist/agent/{type-guards.js → session/event-guards.js} +5 -1
- package/dist/agent/session/model-selection.d.ts +47 -0
- package/dist/agent/session/model-selection.js +99 -0
- package/dist/agent/{session-adapter.d.ts → session/session-adapter.d.ts} +21 -1
- package/dist/agent/session/session-adapter.js +159 -0
- package/dist/agent/{session-events.d.ts → session/session-events.d.ts} +9 -5
- package/dist/agent/{session-events.js → session/session-events.js} +24 -13
- package/dist/agent/session/session-host.d.ts +200 -0
- package/dist/agent/session/session-host.js +621 -0
- package/dist/agent/{session-resource-gate.js → session/session-resource-gate.js} +5 -3
- package/dist/agent/status-render.d.ts +0 -1
- package/dist/agent/status-render.js +4 -16
- package/dist/agent/{context-budget.js → turn/context-budget.js} +5 -1
- package/dist/agent/{progress-formatter.d.ts → turn/progress-formatter.d.ts} +4 -1
- package/dist/agent/{run-queue.d.ts → turn/run-queue.d.ts} +1 -1
- package/dist/agent/{run-queue.js → turn/run-queue.js} +10 -5
- package/dist/{memory → agent/turn}/task-digest.js +4 -4
- package/dist/agent/turn/turn-context.d.ts +14 -0
- package/dist/agent/turn/turn-context.js +64 -0
- package/dist/agent/turn/turn-error.d.ts +31 -0
- package/dist/agent/turn/turn-error.js +68 -0
- package/dist/agent/turn/turn-finish.d.ts +50 -0
- package/dist/agent/turn/turn-finish.js +188 -0
- package/dist/agent/turn/turn-input.d.ts +43 -0
- package/dist/agent/turn/turn-input.js +79 -0
- package/dist/agent/turn/turn-pipeline.d.ts +68 -0
- package/dist/agent/turn/turn-pipeline.js +257 -0
- package/dist/agent/{turn-prompt.d.ts → turn/turn-prompt.d.ts} +2 -2
- package/dist/agent/{turn-prompt.js → turn/turn-prompt.js} +6 -2
- package/dist/agent/{turn-recovery.js → turn/turn-recovery.js} +1 -1
- package/dist/agent/{turn-state.d.ts → turn/turn-state.d.ts} +1 -1
- package/dist/agent/types.d.ts +43 -2
- package/dist/agent/types.js +1 -1
- package/dist/{models/auth-cli.d.ts → app/auth-command.d.ts} +1 -1
- package/dist/{models/auth-cli.js → app/auth-command.js} +14 -10
- package/dist/{runtime/app-home.d.ts → app/home.d.ts} +6 -2
- package/dist/{runtime/app-home.js → app/home.js} +22 -75
- package/dist/{runtime → app}/proxy.js +4 -2
- package/dist/{app-services.d.ts → app/services.d.ts} +5 -5
- package/dist/{app-services.js → app/services.js} +17 -14
- package/dist/channel/channel-context.d.ts +12 -2
- package/dist/channel/channel-context.js +29 -2
- package/dist/channel/channel-event.d.ts +10 -2
- package/dist/channel/channel-event.js +1 -1
- package/dist/channel/channel-index.js +4 -1
- package/dist/{runtime/project-commands.d.ts → channel/commands.d.ts} +1 -1
- package/dist/{runtime/project-commands.js → channel/commands.js} +17 -16
- package/dist/channel/project-scope-store.js +1 -1
- package/dist/channel/store.js +4 -0
- package/dist/commands/catalog.d.ts +24 -7
- package/dist/commands/catalog.js +91 -44
- package/dist/commands/reply-limits.d.ts +6 -0
- package/dist/commands/reply-limits.js +24 -0
- package/dist/{runtime/report-commands.d.ts → commands/router.d.ts} +10 -3
- package/dist/{runtime/report-commands.js → commands/router.js} +6 -6
- package/dist/{settings.d.ts → config/settings.d.ts} +10 -10
- package/dist/{settings.js → config/settings.js} +11 -11
- package/dist/{tools/config.d.ts → config/tools.d.ts} +1 -2
- package/dist/{tools/config.js → config/tools.js} +5 -2
- package/dist/dingtalk/access-token.d.ts +12 -0
- package/dist/dingtalk/access-token.js +51 -0
- package/dist/dingtalk/api.d.ts +19 -0
- package/dist/dingtalk/api.js +67 -0
- package/dist/dingtalk/bot.d.ts +97 -0
- package/dist/dingtalk/bot.js +389 -0
- package/dist/dingtalk/cards.d.ts +56 -0
- package/dist/dingtalk/cards.js +318 -0
- package/dist/{runtime → dingtalk}/channel-queue.js +4 -1
- package/dist/dingtalk/config.d.ts +19 -0
- package/dist/dingtalk/config.js +95 -0
- package/dist/dingtalk/connection.d.ts +57 -0
- package/dist/dingtalk/connection.js +356 -0
- package/dist/dingtalk/conversation-meta.d.ts +16 -0
- package/dist/dingtalk/conversation-meta.js +77 -0
- package/dist/{runtime → dingtalk}/delivery.d.ts +6 -2
- package/dist/{runtime → dingtalk}/delivery.js +29 -15
- package/dist/dingtalk/handler.d.ts +90 -0
- package/dist/dingtalk/handler.js +1 -0
- package/dist/dingtalk/inbound.d.ts +66 -0
- package/dist/dingtalk/inbound.js +137 -0
- package/dist/dingtalk/media.d.ts +66 -0
- package/dist/dingtalk/media.js +214 -0
- package/dist/events/{event-commands.js → commands.js} +99 -45
- package/dist/events/parse.d.ts +14 -0
- package/dist/events/parse.js +114 -0
- package/dist/events/types.d.ts +93 -0
- package/dist/events/types.js +1 -0
- package/dist/events/{event-validation.d.ts → validation.d.ts} +14 -3
- package/dist/events/{event-validation.js → validation.js} +17 -9
- package/dist/events/watcher.d.ts +67 -0
- package/dist/events/{events.js → watcher.js} +63 -121
- package/dist/executor.js +2 -2
- package/dist/index.d.ts +6 -4
- package/dist/index.js +2 -2
- package/dist/jobs/launch.d.ts +42 -0
- package/dist/jobs/launch.js +118 -0
- package/dist/{agent/job-manager.d.ts → jobs/manager.d.ts} +1 -67
- package/dist/{agent/job-manager.js → jobs/manager.js} +34 -157
- package/dist/jobs/record.d.ts +55 -0
- package/dist/jobs/record.js +36 -0
- package/dist/log.d.ts +12 -2
- package/dist/log.js +26 -34
- package/dist/main.js +3 -3
- package/dist/memory/commands.js +29 -23
- package/dist/memory/lifecycle.js +26 -5
- package/dist/memory/maintenance-gates.d.ts +2 -2
- package/dist/memory/maintenance-state.js +4 -1
- package/dist/memory/maintenance-tuning.d.ts +15 -0
- package/dist/memory/maintenance-tuning.js +3 -0
- package/dist/memory/reflect-job.d.ts +2 -2
- package/dist/memory/reflect-job.js +4 -2
- package/dist/memory/scheduler.d.ts +3 -3
- package/dist/memory/scheduler.js +5 -2
- package/dist/memory/sidecar-worker.js +1 -1
- package/dist/memory/transcript.js +1 -1
- package/dist/{agent/model-fallback.d.ts → models/fallback.d.ts} +6 -6
- package/dist/{agent/model-fallback.js → models/fallback.js} +15 -28
- package/dist/models/login-identity.d.ts +2 -0
- package/dist/models/login-identity.js +83 -0
- package/dist/models/provider-login.d.ts +3 -1
- package/dist/models/provider-login.js +8 -2
- package/dist/models/reference.d.ts +20 -0
- package/dist/models/{utils.js → reference.js} +0 -48
- package/dist/models/{utils.d.ts → runtime.d.ts} +1 -16
- package/dist/models/runtime.js +52 -0
- package/dist/paths.d.ts +2 -0
- package/dist/paths.js +9 -0
- package/dist/playbooks/agent-delegation.md +2 -2
- package/dist/playbooks/catalog.d.ts +6 -2
- package/dist/playbooks/catalog.js +9 -6
- package/dist/runtime/bootstrap.d.ts +7 -17
- package/dist/runtime/bootstrap.js +70 -659
- package/dist/runtime/durable-dispatch.d.ts +43 -4
- package/dist/runtime/durable-dispatch.js +153 -3
- package/dist/runtime/inbound-images.d.ts +18 -0
- package/dist/runtime/inbound-images.js +51 -0
- package/dist/runtime/shutdown.d.ts +39 -0
- package/dist/runtime/shutdown.js +120 -0
- package/dist/runtime/stop-watchdog.d.ts +16 -0
- package/dist/runtime/stop-watchdog.js +32 -0
- package/dist/runtime/task-driver.d.ts +6 -4
- package/dist/runtime/task-driver.js +58 -23
- package/dist/runtime/task-migration.js +25 -8
- package/dist/runtime/task-spawn.d.ts +1 -1
- package/dist/runtime/task-spawn.js +13 -6
- package/dist/runtime/turn-handler.d.ts +47 -0
- package/dist/runtime/turn-handler.js +318 -0
- package/dist/runtime/turn-run.d.ts +52 -0
- package/dist/runtime/turn-run.js +318 -0
- package/dist/runtime/wake-coalescing.d.ts +18 -0
- package/dist/runtime/wake-coalescing.js +29 -0
- package/dist/security/block-message.d.ts +22 -1
- package/dist/security/block-message.js +66 -1
- package/dist/security/command-guard.js +4 -0
- package/dist/security/network.d.ts +2 -1
- package/dist/security/network.js +7 -2
- package/dist/security/path-guard-check.js +2 -2
- package/dist/security/path-guard.js +4 -0
- package/dist/security/types.d.ts +1 -2
- package/dist/security/types.js +1 -2
- package/dist/shared/exact-keys.d.ts +1 -1
- package/dist/shared/format.d.ts +12 -0
- package/dist/shared/format.js +37 -0
- package/dist/shared/host-process.js +16 -4
- package/dist/shared/wake-claim.d.ts +1 -1
- package/dist/shared/with-timeout.d.ts +3 -2
- package/dist/shared/with-timeout.js +14 -3
- package/dist/{runtime/skill-commands.d.ts → skills/commands.d.ts} +2 -2
- package/dist/{runtime/skill-commands.js → skills/commands.js} +18 -11
- package/dist/{agent/workspace-resources.js → skills/loader.js} +1 -1
- package/dist/{tools/skill-security.js → skills/validation.js} +4 -0
- package/dist/skills/workspace.d.ts +33 -0
- package/dist/skills/workspace.js +116 -0
- package/dist/{runtime/subagent-commands.d.ts → subagents/commands.d.ts} +9 -7
- package/dist/{runtime/subagent-commands.js → subagents/commands.js} +116 -77
- package/dist/subagents/completion-wake.d.ts +17 -0
- package/dist/subagents/completion-wake.js +76 -0
- package/dist/subagents/detached-discovery.js +1 -1
- package/dist/subagents/discovery.d.ts +1 -1
- package/dist/subagents/discovery.js +2 -2
- package/dist/subagents/dispatch.d.ts +33 -0
- package/dist/subagents/dispatch.js +190 -0
- package/dist/subagents/external/claude-code.js +23 -1
- package/dist/subagents/external/dispatch.d.ts +25 -0
- package/dist/subagents/external/dispatch.js +90 -0
- package/dist/subagents/external/harness.d.ts +1 -1
- package/dist/subagents/external/progress-tail.d.ts +18 -1
- package/dist/subagents/external/progress-tail.js +64 -17
- package/dist/subagents/external/run.d.ts +5 -1
- package/dist/subagents/external/run.js +23 -9
- package/dist/subagents/external/settlement.d.ts +4 -1
- package/dist/subagents/external/settlement.js +1 -1
- package/dist/subagents/format.d.ts +1 -1
- package/dist/subagents/grace.d.ts +24 -0
- package/dist/subagents/grace.js +57 -0
- package/dist/subagents/internal/outcome.d.ts +24 -0
- package/dist/subagents/internal/outcome.js +149 -0
- package/dist/subagents/internal/provider-retry.d.ts +19 -0
- package/dist/subagents/internal/provider-retry.js +83 -0
- package/dist/subagents/internal/run.d.ts +31 -0
- package/dist/subagents/internal/run.js +240 -0
- package/dist/subagents/internal/state.d.ts +43 -0
- package/dist/subagents/internal/state.js +48 -0
- package/dist/subagents/internal/worker.d.ts +51 -0
- package/dist/subagents/internal/worker.js +167 -0
- package/dist/subagents/result.d.ts +62 -0
- package/dist/subagents/result.js +103 -0
- package/dist/subagents/run-record.d.ts +222 -0
- package/dist/subagents/run-record.js +101 -0
- package/dist/subagents/run-registry.d.ts +9 -0
- package/dist/subagents/run-registry.js +125 -0
- package/dist/subagents/runs.d.ts +16 -232
- package/dist/subagents/runs.js +132 -310
- package/dist/subagents/task-envelope.d.ts +36 -0
- package/dist/subagents/task-envelope.js +168 -0
- package/dist/subagents/types.d.ts +154 -0
- package/dist/subagents/types.js +1 -0
- package/dist/subagents/verification-outcome.d.ts +1 -1
- package/dist/subagents/workspace-summary.d.ts +16 -4
- package/dist/subagents/workspace-summary.js +74 -18
- package/dist/tasks/board.d.ts +10 -3
- package/dist/tasks/board.js +38 -3
- package/dist/tasks/{work-log.d.ts → bound-work.d.ts} +1 -1
- package/dist/tasks/{work-log.js → bound-work.js} +1 -1
- package/dist/tasks/brief.js +1 -1
- package/dist/{runtime/task-commands.d.ts → tasks/commands.d.ts} +1 -1
- package/dist/{runtime/task-commands.js → tasks/commands.js} +117 -67
- package/dist/tasks/contract-input.d.ts +1 -1
- package/dist/tasks/contract-input.js +1 -1
- package/dist/tasks/create.js +1 -1
- package/dist/tasks/frontmatter.d.ts +5 -0
- package/dist/tasks/frontmatter.js +8 -0
- package/dist/tasks/{log.d.ts → loop-log.d.ts} +11 -1
- package/dist/tasks/{log.js → loop-log.js} +59 -3
- package/dist/tasks/mutation-lock.js +1 -1
- package/dist/tasks/session-path.js +1 -1
- package/dist/tasks/steer.js +1 -1
- package/dist/tasks/store.js +6 -4
- package/dist/tasks/ticket.d.ts +3 -1
- package/dist/tasks/ticket.js +19 -1
- package/dist/tools/bash.d.ts +1 -1
- package/dist/tools/bash.js +2 -2
- package/dist/tools/{tool-details.d.ts → contract/details.d.ts} +11 -3
- package/dist/tools/{tool-details.js → contract/details.js} +42 -5
- package/dist/tools/{presentation.js → contract/presentation.js} +3 -3
- package/dist/tools/event-manage.d.ts +1 -1
- package/dist/tools/event-manage.js +4 -4
- package/dist/tools/index.d.ts +5 -3
- package/dist/tools/index.js +8 -6
- package/dist/tools/job.d.ts +1 -1
- package/dist/tools/memory-manage.js +4 -1
- package/dist/tools/registry.d.ts +7 -7
- package/dist/tools/registry.js +6 -6
- package/dist/tools/session-search.d.ts +1 -1
- package/dist/tools/skill.d.ts +2 -34
- package/dist/tools/skill.js +8 -116
- package/dist/tools/subagent-manage.d.ts +1 -1
- package/dist/tools/subagent-manage.js +19 -13
- package/dist/tools/subagent.d.ts +46 -0
- package/dist/tools/subagent.js +127 -0
- package/dist/tools/{task-manage.d.ts → task-manage/factory.d.ts} +7 -3
- package/dist/tools/{task-manage.js → task-manage/factory.js} +7 -7
- package/dist/tools/task-manage/lifecycle.js +2 -2
- package/dist/tools/task-manage/log-view.js +2 -2
- package/dist/tools/task-manage/shared.js +3 -3
- package/dist/tools/task-manage/step-end.js +7 -4
- package/dist/tools/task-manage/types.d.ts +1 -1
- package/dist/tools/web-fetch.d.ts +1 -1
- package/dist/tools/web-search.d.ts +1 -1
- package/dist/tui/app.d.ts +1 -1
- package/dist/tui/app.js +6 -6
- package/dist/tui/cli.d.ts +1 -1
- package/dist/tui/cli.js +3 -3
- package/dist/tui/commands.js +4 -4
- package/dist/tui/frontend.d.ts +44 -0
- package/dist/tui/frontend.js +13 -0
- package/dist/tui/pitui-frontend.d.ts +1 -1
- package/dist/tui/pitui-frontend.js +1 -1
- package/dist/tui/plain-frontend.d.ts +1 -1
- package/dist/tui/renderer.d.ts +3 -42
- package/dist/tui/renderer.js +3 -2
- package/dist/tui/terminal-context.d.ts +2 -2
- package/dist/tui/terminal-media-sender.d.ts +1 -1
- package/dist/tui/turn-controller.d.ts +3 -1
- package/dist/tui/turn-controller.js +36 -21
- package/dist/usage/ledger.js +7 -1
- package/dist/usage/render.js +3 -1
- package/dist/{shared/types.d.ts → usage/totals.d.ts} +3 -0
- package/dist/web/client.d.ts +5 -1
- package/dist/web/client.js +4 -0
- package/dist/web/config.d.ts +1 -1
- package/dist/web/fetch.d.ts +1 -1
- package/dist/web/search-providers.d.ts +1 -1
- package/dist/web/search.d.ts +1 -1
- package/package.json +9 -7
- package/dist/agent/session-adapter.js +0 -77
- package/dist/events/events.d.ts +0 -159
- package/dist/runtime/dingtalk.d.ts +0 -272
- package/dist/runtime/dingtalk.js +0 -1416
- package/dist/subagents/tool.d.ts +0 -206
- package/dist/subagents/tool.js +0 -1088
- /package/dist/{runtime → agent/prompt}/workspace-templates.d.ts +0 -0
- /package/dist/{runtime → agent/prompt}/workspace-templates.js +0 -0
- /package/dist/agent/{session-resource-gate.d.ts → session/session-resource-gate.d.ts} +0 -0
- /package/dist/agent/{context-budget.d.ts → turn/context-budget.d.ts} +0 -0
- /package/dist/agent/{progress-formatter.js → turn/progress-formatter.js} +0 -0
- /package/dist/{memory → agent/turn}/task-digest.d.ts +0 -0
- /package/dist/agent/{turn-recovery.d.ts → turn/turn-recovery.d.ts} +0 -0
- /package/dist/agent/{turn-state.js → turn/turn-state.js} +0 -0
- /package/dist/{runtime → app}/proxy.d.ts +0 -0
- /package/dist/{runtime → dingtalk}/channel-queue.d.ts +0 -0
- /package/dist/{runtime → dingtalk}/inbound-media.d.ts +0 -0
- /package/dist/{runtime → dingtalk}/inbound-media.js +0 -0
- /package/dist/events/{event-commands.d.ts → commands.d.ts} +0 -0
- /package/dist/{agent/workspace-resources.d.ts → skills/loader.d.ts} +0 -0
- /package/dist/{tools/skill-security.d.ts → skills/validation.d.ts} +0 -0
- /package/dist/tasks/{ledger.d.ts → contract.d.ts} +0 -0
- /package/dist/tasks/{ledger.js → contract.js} +0 -0
- /package/dist/tools/{subagent-tool-names.d.ts → contract/names.d.ts} +0 -0
- /package/dist/tools/{subagent-tool-names.js → contract/names.js} +0 -0
- /package/dist/tools/{presentation.d.ts → contract/presentation.d.ts} +0 -0
- /package/dist/{shared/types.js → usage/totals.js} +0 -0
|
@@ -1,65 +1,39 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
/**
|
|
2
|
+
* The daemon's composition root: loads config and builds the bot, durable dispatch, jobs, delegation
|
|
3
|
+
* runs, the events, memory and task services, then wires the per-channel handler (`turn-handler.ts`)
|
|
4
|
+
* and the ordered shutdown (`shutdown.ts`).
|
|
5
|
+
*/
|
|
6
|
+
import { join } from "path";
|
|
4
7
|
import { loadDetachedMaintenanceContext } from "../agent/maintenance-context.js";
|
|
5
8
|
import { createRunner } from "../agent/runner-factory.js";
|
|
6
|
-
import { scanWorkspaceForInterruptedTurns } from "../agent/turn-recovery.js";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import { muteChannelContext } from "../channel/channel-context.js";
|
|
9
|
+
import { scanWorkspaceForInterruptedTurns } from "../agent/turn/turn-recovery.js";
|
|
10
|
+
import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, parseArgs, printBootstrapSummary, printFirstRunGuide, readCliVersion, } from "../app/home.js";
|
|
11
|
+
import { prepareAppServices } from "../app/services.js";
|
|
10
12
|
import { createChannelIndex } from "../channel/channel-index.js";
|
|
11
13
|
import { ensureChannelDir, getChannelDir } from "../channel/channel-paths.js";
|
|
12
|
-
import { resolveProjectScope } from "../channel/project-scope-store.js";
|
|
13
14
|
import { ChannelStore } from "../channel/store.js";
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
15
|
+
import { PipiclawSettingsManager } from "../config/settings.js";
|
|
16
|
+
import { getToolsConfigPath, loadToolsConfig } from "../config/tools.js";
|
|
17
|
+
import { DingTalkBot } from "../dingtalk/bot.js";
|
|
18
|
+
import { loadConfig } from "../dingtalk/config.js";
|
|
19
|
+
import { createEventsWatcher } from "../events/watcher.js";
|
|
16
20
|
import { createExecutor } from "../executor.js";
|
|
21
|
+
import { createJobRuntime } from "../jobs/manager.js";
|
|
17
22
|
import * as log from "../log.js";
|
|
18
23
|
import { MemoryMaintenanceScheduler } from "../memory/scheduler.js";
|
|
19
|
-
import { defaultModel } from "../models/
|
|
24
|
+
import { defaultModel } from "../models/runtime.js";
|
|
20
25
|
import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
|
|
21
|
-
import { flushSecurityLogs } from "../security/logger.js";
|
|
22
|
-
import { resolveProjectAccessPolicy } from "../security/project-scope.js";
|
|
23
|
-
import { PipiclawSettingsManager } from "../settings.js";
|
|
24
26
|
import { fileStamp } from "../shared/format.js";
|
|
25
|
-
import { localStampForFilename } from "../shared/local-time.js";
|
|
26
27
|
import { errorMessage } from "../shared/text-utils.js";
|
|
27
|
-
import {
|
|
28
|
-
import { createSubAgentRuntime } from "../subagents/
|
|
29
|
-
import { buildTaskStepBrief } from "../tasks/brief.js";
|
|
30
|
-
import { readActiveTasks } from "../tasks/ledger.js";
|
|
31
|
-
import { consumeTaskNotice } from "../tasks/steer.js";
|
|
32
|
-
import { pauseTask as pauseStoredTask } from "../tasks/store.js";
|
|
33
|
-
import { getToolsConfigPath, loadToolsConfig } from "../tools/config.js";
|
|
28
|
+
import { renderRunNotice } from "../subagents/commands.js";
|
|
29
|
+
import { createSubAgentRuntime } from "../subagents/run-registry.js";
|
|
34
30
|
import { getUsageLedger } from "../usage/ledger.js";
|
|
35
|
-
import {
|
|
36
|
-
import {
|
|
37
|
-
import {
|
|
38
|
-
import { DurableDispatchService } from "./durable-dispatch.js";
|
|
39
|
-
import { extensionForMimeType } from "./inbound-media.js";
|
|
40
|
-
import { runReportCommand } from "./report-commands.js";
|
|
41
|
-
import { renderRunNotice } from "./subagent-commands.js";
|
|
42
|
-
import { createTaskDriverEvent, parseDriverTaskId, TaskDriver } from "./task-driver.js";
|
|
31
|
+
import { DurableDispatchService, renderDispatchExhaustedNotice } from "./durable-dispatch.js";
|
|
32
|
+
import { createShutdown } from "./shutdown.js";
|
|
33
|
+
import { TaskDriver } from "./task-driver.js";
|
|
43
34
|
import { migrateTasksToV5 } from "./task-migration.js";
|
|
44
35
|
import { createTaskSpawner } from "./task-spawn.js";
|
|
45
|
-
import {
|
|
46
|
-
const SHUTDOWN_WAIT_MS = 15000;
|
|
47
|
-
const SHUTDOWN_FLUSH_WAIT_MS = 45000;
|
|
48
|
-
const SHUTDOWN_ABORT_WAIT_MS = 5000;
|
|
49
|
-
const SHUTDOWN_LOG_FLUSH_WAIT_MS = 10_000;
|
|
50
|
-
function waitForTasks(tasks, timeoutMs) {
|
|
51
|
-
if (tasks.length === 0) {
|
|
52
|
-
return Promise.resolve(true);
|
|
53
|
-
}
|
|
54
|
-
return new Promise((resolve) => {
|
|
55
|
-
const timer = setTimeout(() => resolve(false), timeoutMs);
|
|
56
|
-
timer.unref?.();
|
|
57
|
-
void Promise.allSettled(tasks).then(() => {
|
|
58
|
-
clearTimeout(timer);
|
|
59
|
-
resolve(true);
|
|
60
|
-
});
|
|
61
|
-
});
|
|
62
|
-
}
|
|
36
|
+
import { createTurnHandler } from "./turn-handler.js";
|
|
63
37
|
/**
|
|
64
38
|
* Ceiling on cached runners per daemon process. A long-lived daemon otherwise accumulates one
|
|
65
39
|
* `ChannelRunner` (session, subscriptions, memory state) per distinct channel it has ever heard
|
|
@@ -83,531 +57,13 @@ async function evictIdleRunnersOverCap(channelRunners) {
|
|
|
83
57
|
continue;
|
|
84
58
|
channelRunners.delete(channelId);
|
|
85
59
|
await runner.dispose().catch((err) => {
|
|
86
|
-
log.
|
|
60
|
+
log.logWarn("runtime.runner.evict_dispose_failed", "Evicted runner dispose failed", {
|
|
61
|
+
channelId: channelId,
|
|
62
|
+
reason: errorMessage(err),
|
|
63
|
+
});
|
|
87
64
|
});
|
|
88
65
|
}
|
|
89
66
|
}
|
|
90
|
-
function isNoRunningTaskQueueError(err) {
|
|
91
|
-
return err instanceof Error && err.message === "No task is currently running.";
|
|
92
|
-
}
|
|
93
|
-
/**
|
|
94
|
-
* Absolute `InboundImage.path`s → paths relative to the channel directory, for
|
|
95
|
-
* `LoggedMessage.images` (spec 049). `log.jsonl` already stores everything else channel-relative
|
|
96
|
-
* (it lives inside the channel directory itself); an absolute path there would be dead on any
|
|
97
|
-
* machine other than the one that wrote it, and `~/.pipiclaw` itself can move between backup and
|
|
98
|
-
* restore.
|
|
99
|
-
*/
|
|
100
|
-
function relativeImagePaths(workspaceDir, channelId, images) {
|
|
101
|
-
if (!images || images.length === 0)
|
|
102
|
-
return [];
|
|
103
|
-
const channelDir = getChannelDir(workspaceDir, channelId);
|
|
104
|
-
return images.map((image) => relative(channelDir, image.path));
|
|
105
|
-
}
|
|
106
|
-
/**
|
|
107
|
-
* The `runRuntimeCommand` names usable on the idle-turn path — every `BUILT_IN_COMMANDS` entry
|
|
108
|
-
* *not* marked `runnerHandled`, i.e. every stateless report. `context` is the one deliberate
|
|
109
|
-
* exception even though it isn't runner-handled while busy (see the busy-path switch in
|
|
110
|
-
* `dingtalk.ts`): idle answers it through the runner's ChannelContext-aware command path
|
|
111
|
-
* (thread-reply, delete semantics) instead, so it is routed like the runner-handled built-ins
|
|
112
|
-
* here and excluded from this stateless-report set.
|
|
113
|
-
*/
|
|
114
|
-
const IDLE_RUNTIME_COMMAND_NAMES = new Set(BUILT_IN_COMMANDS.filter((command) => !command.runnerHandled).map((command) => command.name));
|
|
115
|
-
function isIdleRuntimeCommandName(name) {
|
|
116
|
-
return IDLE_RUNTIME_COMMAND_NAMES.has(name);
|
|
117
|
-
}
|
|
118
|
-
/**
|
|
119
|
-
* How long `/stop` waits for the turn to actually end before force-releasing it.
|
|
120
|
-
* `requestStop` + `abort` only reach the agent loop; a turn wedged in its
|
|
121
|
-
* epilogue (delivery drain, session-resource reload, memory flush) ignores both
|
|
122
|
-
* and would otherwise keep the channel reporting "已有回合在运行" indefinitely.
|
|
123
|
-
*/
|
|
124
|
-
const STOP_FORCE_END_GRACE_MS = 15_000;
|
|
125
|
-
const STOP_FORCE_END_POLL_MS = 250;
|
|
126
|
-
/**
|
|
127
|
-
* Watchdog for `/stop`: release the channel if the stopped turn has not ended
|
|
128
|
-
* once the grace window elapses. Returns true when it had to force the release.
|
|
129
|
-
*/
|
|
130
|
-
export async function forceEndStuckTurnAfterStop(input) {
|
|
131
|
-
const graceMs = input.graceMs ?? STOP_FORCE_END_GRACE_MS;
|
|
132
|
-
const pollMs = input.pollMs ?? STOP_FORCE_END_POLL_MS;
|
|
133
|
-
const deadline = Date.now() + graceMs;
|
|
134
|
-
while (input.runner.isBusy() && Date.now() < deadline) {
|
|
135
|
-
await sleepUnref(Math.min(pollMs, Math.max(1, deadline - Date.now())));
|
|
136
|
-
}
|
|
137
|
-
if (!input.runner.forceEndTurn(`/stop did not take effect within ${graceMs}ms`)) {
|
|
138
|
-
return false;
|
|
139
|
-
}
|
|
140
|
-
await input
|
|
141
|
-
.notify?.(`⚠️ 上一个回合的收尾卡住了,已强制结束以释放会话(后台清理仍在继续)。现在可以正常发消息或使用 \`/new\`、\`/model\`。`)
|
|
142
|
-
.catch(() => undefined);
|
|
143
|
-
return true;
|
|
144
|
-
}
|
|
145
|
-
function createDingTalkHandler(deps) {
|
|
146
|
-
const { options, store, channelRunners, sessionResetChains, activeTasks, stopWatchdogs, channelIndex, archiveIncomingMessage, getRunner, cliVersion, startedAt, isShuttingDown, getDurableDispatch, getJobs, getRuns, getTaskDriver, } = deps;
|
|
147
|
-
/**
|
|
148
|
-
* Turn a `[TASK_DRIVER:<id>]` dispatch into a task loop step: bind the runner to the task
|
|
149
|
-
* cycle's own session and replace the wake text with the step brief. Returns `undefined` for
|
|
150
|
-
* every other event, which then follows the unchanged chat path.
|
|
151
|
-
*
|
|
152
|
-
* Binding failures fall back to the chat path rather than dropping the wake — a task that
|
|
153
|
-
* cannot open its session should still be visible, not silently skipped.
|
|
154
|
-
*/
|
|
155
|
-
const prepareTaskStep = async (event, runner) => {
|
|
156
|
-
const taskId = parseDriverTaskId(event.text) ?? event.internalWake?.taskId;
|
|
157
|
-
if (!taskId)
|
|
158
|
-
return undefined;
|
|
159
|
-
const channelDir = ensureChannelDir(options.paths.workspaceDir, event.channelId);
|
|
160
|
-
try {
|
|
161
|
-
const brief = await buildTaskStepBrief({ channelDir, taskId });
|
|
162
|
-
if (!brief)
|
|
163
|
-
return undefined;
|
|
164
|
-
await runner.bindTaskSession(taskId);
|
|
165
|
-
return { taskId, brief };
|
|
166
|
-
}
|
|
167
|
-
catch (error) {
|
|
168
|
-
log.logWarning(`[${event.channelId}] Could not start task step for ${taskId}`, errorMessage(error));
|
|
169
|
-
return undefined;
|
|
170
|
-
}
|
|
171
|
-
};
|
|
172
|
-
/** Deliver whatever the step asked to say, then hand the runner back to the chat session. */
|
|
173
|
-
const finishTaskStep = async (channelId, taskId, bot) => {
|
|
174
|
-
const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
|
|
175
|
-
try {
|
|
176
|
-
const notice = await consumeTaskNotice(channelDir, taskId);
|
|
177
|
-
if (notice) {
|
|
178
|
-
// runner.run closes its per-turn delivery context before returning. Sending through that
|
|
179
|
-
// closed context silently dropped successful task_step_end notifications (T-run-01).
|
|
180
|
-
const delivered = await bot.sendPlain(channelId, notice);
|
|
181
|
-
if (delivered)
|
|
182
|
-
await store.logBotResponse(channelId, notice, Date.now().toString());
|
|
183
|
-
else
|
|
184
|
-
log.logWarning(`[${channelId}] Failed to deliver task notice for ${taskId}`);
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
catch (error) {
|
|
188
|
-
log.logWarning(`[${channelId}] Could not deliver task notice for ${taskId}`, errorMessage(error));
|
|
189
|
-
}
|
|
190
|
-
await getRunner(channelId).bindChatSession();
|
|
191
|
-
};
|
|
192
|
-
const handler = {
|
|
193
|
-
isRunning(channelId) {
|
|
194
|
-
return channelRunners.get(channelId)?.isBusy() ?? false;
|
|
195
|
-
},
|
|
196
|
-
noteChannelActivity(observation) {
|
|
197
|
-
if (isShuttingDown())
|
|
198
|
-
return;
|
|
199
|
-
channelIndex.note(observation);
|
|
200
|
-
},
|
|
201
|
-
async handleStop(channelId, _bot) {
|
|
202
|
-
const runner = channelRunners.get(channelId);
|
|
203
|
-
let pausedTaskId;
|
|
204
|
-
if (runner?.isBusy()) {
|
|
205
|
-
runner.requestStop();
|
|
206
|
-
// Stopping a task step stops the task: otherwise the driver would queue the next step
|
|
207
|
-
// straight away. The step may not be bound to its session yet, so fall back to the text.
|
|
208
|
-
const taskId = runner.getTaskLoop()?.taskId ?? parseDriverTaskId(runner.getTurnStatus().taskText);
|
|
209
|
-
if (taskId) {
|
|
210
|
-
await pauseStoredTask(getChannelDir(options.paths.workspaceDir, channelId), taskId, {
|
|
211
|
-
by: "user",
|
|
212
|
-
reason: "用户 /stop 中止了该任务的当前步骤。",
|
|
213
|
-
});
|
|
214
|
-
pausedTaskId = taskId;
|
|
215
|
-
log.logInfo(`[${channelId}] Paused task ${taskId} on /stop`);
|
|
216
|
-
}
|
|
217
|
-
_bot.discardCard(channelId);
|
|
218
|
-
// Drop queued-but-not-started messages so a burst does not keep
|
|
219
|
-
// running after the user asked to halt; abort the in-flight one.
|
|
220
|
-
const dropped = _bot.clearPendingMessages(channelId);
|
|
221
|
-
if (dropped > 0) {
|
|
222
|
-
log.logInfo(`[${channelId}] Dropped ${dropped} queued message(s) on stop`);
|
|
223
|
-
}
|
|
224
|
-
void runner.abort().catch((err) => {
|
|
225
|
-
log.logWarning(`[${channelId}] Failed to abort run`, errorMessage(err));
|
|
226
|
-
});
|
|
227
|
-
void getDurableDispatch()
|
|
228
|
-
?.cancelChannel(channelId)
|
|
229
|
-
.then((canceled) => {
|
|
230
|
-
if (canceled)
|
|
231
|
-
log.logInfo(`[${channelId}] Reset ${canceled} durable-dispatch lease(s) on stop`);
|
|
232
|
-
})
|
|
233
|
-
.catch((err) => {
|
|
234
|
-
log.logWarning(`[${channelId}] Failed to reset durable-dispatch leases on stop`, errorMessage(err));
|
|
235
|
-
});
|
|
236
|
-
log.logInfo(`[${channelId}] Stop requested`);
|
|
237
|
-
if (!stopWatchdogs.has(channelId)) {
|
|
238
|
-
stopWatchdogs.add(channelId);
|
|
239
|
-
void forceEndStuckTurnAfterStop({
|
|
240
|
-
channelId,
|
|
241
|
-
runner,
|
|
242
|
-
graceMs: options.stopForceEndGraceMs,
|
|
243
|
-
notify: (text) => _bot.sendPlain(channelId, text),
|
|
244
|
-
})
|
|
245
|
-
.catch((err) => {
|
|
246
|
-
log.logWarning(`[${channelId}] Stop watchdog failed`, errorMessage(err));
|
|
247
|
-
})
|
|
248
|
-
.finally(() => {
|
|
249
|
-
stopWatchdogs.delete(channelId);
|
|
250
|
-
});
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
return { pausedTaskId };
|
|
254
|
-
},
|
|
255
|
-
async handleNewSession(event, _bot) {
|
|
256
|
-
if (isShuttingDown())
|
|
257
|
-
return;
|
|
258
|
-
const previous = sessionResetChains.get(event.channelId) ?? Promise.resolve();
|
|
259
|
-
const reset = previous
|
|
260
|
-
.catch(() => undefined)
|
|
261
|
-
.then(async () => {
|
|
262
|
-
try {
|
|
263
|
-
const channelDir = ensureChannelDir(options.paths.workspaceDir, event.channelId);
|
|
264
|
-
const access = resolveProjectAccessPolicy(loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config, process.cwd());
|
|
265
|
-
const scope = resolveProjectScope(channelDir, access);
|
|
266
|
-
if (scope.kind === "blocked") {
|
|
267
|
-
throw new Error(scope.reason);
|
|
268
|
-
}
|
|
269
|
-
// The empty session file and active pointer are committed before the old
|
|
270
|
-
// generation is touched. A filesystem failure therefore leaves the live
|
|
271
|
-
// session authoritative and retryable.
|
|
272
|
-
const result = await createFreshActiveSession(channelDir, scope.scope.projectRoot);
|
|
273
|
-
const oldRunner = channelRunners.get(event.channelId);
|
|
274
|
-
if (oldRunner) {
|
|
275
|
-
channelRunners.delete(event.channelId);
|
|
276
|
-
try {
|
|
277
|
-
oldRunner.retireForNewSession();
|
|
278
|
-
}
|
|
279
|
-
catch (error) {
|
|
280
|
-
// The active pointer already names the new session. Retirement is
|
|
281
|
-
// best-effort cleanup and must not misreport the committed reset as failed.
|
|
282
|
-
log.logWarning(`[${event.channelId}] Old runner retirement failed after /new`, errorMessage(error));
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
const dropped = _bot.resetChannelQueue(event.channelId);
|
|
286
|
-
if (dropped > 0) {
|
|
287
|
-
log.logInfo(`[${event.channelId}] /new discarded ${dropped} queued old-session message(s)`);
|
|
288
|
-
}
|
|
289
|
-
await _bot.sendPlain(event.channelId, `已开启新会话。\n\nSession ID: \`${result.sessionId}\``);
|
|
290
|
-
void archiveIncomingMessage(event.channelId, {
|
|
291
|
-
date: new Date().toISOString(),
|
|
292
|
-
ts: event.ts,
|
|
293
|
-
user: event.user,
|
|
294
|
-
userName: event.userName,
|
|
295
|
-
text: event.text,
|
|
296
|
-
isBot: false,
|
|
297
|
-
images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
|
|
298
|
-
}, "/new command");
|
|
299
|
-
}
|
|
300
|
-
catch (error) {
|
|
301
|
-
const message = errorMessage(error);
|
|
302
|
-
log.logWarning(`[${event.channelId}] Failed to create a fresh session`, message);
|
|
303
|
-
await _bot.sendPlain(event.channelId, `新会话创建失败:${message}\n\n旧会话仍保持不变;请重试 \`/new\`。`);
|
|
304
|
-
}
|
|
305
|
-
});
|
|
306
|
-
sessionResetChains.set(event.channelId, reset);
|
|
307
|
-
activeTasks.add(reset);
|
|
308
|
-
try {
|
|
309
|
-
await reset;
|
|
310
|
-
}
|
|
311
|
-
finally {
|
|
312
|
-
activeTasks.delete(reset);
|
|
313
|
-
if (sessionResetChains.get(event.channelId) === reset) {
|
|
314
|
-
sessionResetChains.delete(event.channelId);
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
},
|
|
318
|
-
async runRuntimeCommand(event, name, args) {
|
|
319
|
-
const { channelId } = event;
|
|
320
|
-
return runReportCommand({
|
|
321
|
-
channelId,
|
|
322
|
-
paths: options.paths,
|
|
323
|
-
actor: "dingtalk-command",
|
|
324
|
-
version: cliVersion,
|
|
325
|
-
startedAt,
|
|
326
|
-
peekRunner: () => channelRunners.get(channelId),
|
|
327
|
-
getRunner: () => getRunner(channelId),
|
|
328
|
-
runManager: getRuns().get(channelId),
|
|
329
|
-
runningJobLines: () => getJobs().runningLines(channelId),
|
|
330
|
-
// D4.2: dispose the cached runner so the next access rebuilds it under the new scope.
|
|
331
|
-
// The active-session ref is untouched — same session, new project root.
|
|
332
|
-
onScopeChanged: async () => {
|
|
333
|
-
const runner = channelRunners.get(channelId);
|
|
334
|
-
channelRunners.delete(channelId);
|
|
335
|
-
await runner?.dispose().catch((err) => {
|
|
336
|
-
log.logWarning(`[${channelId}] Failed to dispose runner after /project`, errorMessage(err));
|
|
337
|
-
});
|
|
338
|
-
},
|
|
339
|
-
dispatchTask: async (id) => {
|
|
340
|
-
const channelDir = getChannelDir(options.paths.workspaceDir, channelId);
|
|
341
|
-
const entry = (await readActiveTasks(join(channelDir, "tasks"))).find((candidate) => candidate.id === id);
|
|
342
|
-
if (!entry)
|
|
343
|
-
return false;
|
|
344
|
-
// A human asking to run a task twice means twice, so this key is deliberately
|
|
345
|
-
// unique per invocation rather than sharing the driver's occurrence key (D1).
|
|
346
|
-
const now = Date.now();
|
|
347
|
-
return ((await getDurableDispatch()?.dispatch({
|
|
348
|
-
...createTaskDriverEvent(channelId, entry, now),
|
|
349
|
-
dispatchId: `task:${channelId}:${entry.id}:manual:${new Date(now).toISOString()}`,
|
|
350
|
-
})) ?? false);
|
|
351
|
-
},
|
|
352
|
-
}, name, args);
|
|
353
|
-
},
|
|
354
|
-
async handleBusyMessage(event, bot, mode, queueText) {
|
|
355
|
-
if (isShuttingDown()) {
|
|
356
|
-
return { kind: "handled" };
|
|
357
|
-
}
|
|
358
|
-
const runner = getRunner(event.channelId);
|
|
359
|
-
const trimmedQueueText = queueText.trim();
|
|
360
|
-
if (!trimmedQueueText) {
|
|
361
|
-
const commandName = mode === "followUp" ? "followup" : "steer";
|
|
362
|
-
await bot.sendPlain(event.channelId, `无法排队:/${commandName} 需要带上消息内容。`);
|
|
363
|
-
return { kind: "handled" };
|
|
364
|
-
}
|
|
365
|
-
// Compaction is maintenance, not user work. A new message cancels it and is
|
|
366
|
-
// kept as a normal queued turn instead of trying to steer an agent loop that
|
|
367
|
-
// is currently disconnected for summarization.
|
|
368
|
-
if (runner.interruptCompaction()) {
|
|
369
|
-
log.logInfo(`[${event.channelId}] Interrupted compaction for a new user message`);
|
|
370
|
-
return { kind: "requeue", text: trimmedQueueText };
|
|
371
|
-
}
|
|
372
|
-
// A task step runs in the task's own session and is muted: a steer here would land in
|
|
373
|
-
// the background task's context and its answer would never reach the user, while the
|
|
374
|
-
// message itself is kept out of the chat session. Run it as the next chat turn instead.
|
|
375
|
-
const taskLoop = runner.getTaskLoop();
|
|
376
|
-
if (taskLoop) {
|
|
377
|
-
await bot.sendPlain(event.channelId, `后台任务 \`${taskLoop.taskId}\` 正在执行一步,你的消息会在这一步结束后处理;要给该任务补充指示,用 \`/tasks steer ${taskLoop.taskId} <内容>\`。`);
|
|
378
|
-
log.logEvent("info", "agent.turn.followup_queued", "Message deferred past a task step", {
|
|
379
|
-
ctx: { channelId: event.channelId, userName: event.userName },
|
|
380
|
-
fields: { messageLength: trimmedQueueText.length, taskId: taskLoop.taskId },
|
|
381
|
-
});
|
|
382
|
-
return { kind: "requeue", text: trimmedQueueText };
|
|
383
|
-
}
|
|
384
|
-
if (mode === "followUp") {
|
|
385
|
-
log.logEvent("info", "agent.turn.followup_queued", "Follow-up queued", {
|
|
386
|
-
ctx: { channelId: event.channelId, userName: event.userName },
|
|
387
|
-
fields: { messageLength: trimmedQueueText.length },
|
|
388
|
-
});
|
|
389
|
-
return { kind: "requeue", text: trimmedQueueText };
|
|
390
|
-
}
|
|
391
|
-
try {
|
|
392
|
-
await runner.queueSteer(trimmedQueueText, event.userName, event.images);
|
|
393
|
-
await archiveIncomingMessage(event.channelId, {
|
|
394
|
-
date: new Date().toISOString(),
|
|
395
|
-
ts: event.ts,
|
|
396
|
-
user: event.user,
|
|
397
|
-
userName: event.userName,
|
|
398
|
-
text: event.text,
|
|
399
|
-
isBot: false,
|
|
400
|
-
deliveryMode: mode,
|
|
401
|
-
skipContextSync: true,
|
|
402
|
-
images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
|
|
403
|
-
}, `${mode} message`);
|
|
404
|
-
const confirmation = event.text.trim().startsWith("/")
|
|
405
|
-
? "已作为 steer 排队,当前工具步骤结束后生效。"
|
|
406
|
-
: "已作为 steer 排队,当前工具步骤结束后生效。想等整个回合结束再执行,用 `/followup <消息>`。";
|
|
407
|
-
await bot.sendPlain(event.channelId, confirmation);
|
|
408
|
-
log.logEvent("info", "agent.turn.steer_queued", "Steer queued", {
|
|
409
|
-
ctx: { channelId: event.channelId, userName: event.userName },
|
|
410
|
-
fields: { messageLength: trimmedQueueText.length },
|
|
411
|
-
});
|
|
412
|
-
return { kind: "handled" };
|
|
413
|
-
}
|
|
414
|
-
catch (err) {
|
|
415
|
-
const errMsg = errorMessage(err);
|
|
416
|
-
if (isNoRunningTaskQueueError(err)) {
|
|
417
|
-
log.logInfo(`[${event.channelId}] Busy ${mode} window closed; requeueing as a normal message`);
|
|
418
|
-
return { kind: "requeue", text: trimmedQueueText };
|
|
419
|
-
}
|
|
420
|
-
log.logWarning(`[${event.channelId}] Failed to queue ${mode}`, errMsg);
|
|
421
|
-
await bot.sendPlain(event.channelId, `无法排队这条消息:${errMsg}`);
|
|
422
|
-
return { kind: "handled" };
|
|
423
|
-
}
|
|
424
|
-
},
|
|
425
|
-
/**
|
|
426
|
-
* Persist one downloaded inbound image under the channel's `inbox/` (spec 049). Bootstrap
|
|
427
|
-
* owns this, not the transport, because it holds the workspace root; see the doc comment
|
|
428
|
-
* on `DingTalkHandler.persistInboundImage` for the full contract (`mimeType: null` case
|
|
429
|
-
* included).
|
|
430
|
-
*/
|
|
431
|
-
async persistInboundImage(channelId, image) {
|
|
432
|
-
try {
|
|
433
|
-
const dir = join(getChannelDir(options.paths.workspaceDir, channelId), "inbox");
|
|
434
|
-
await mkdir(dir, { recursive: true });
|
|
435
|
-
const extension = extensionForMimeType(image.mimeType);
|
|
436
|
-
const path = join(dir, `image-${localStampForFilename()}-${Math.random().toString(36).slice(2, 8)}.${extension}`);
|
|
437
|
-
await writeFile(path, image.data, { mode: 0o600 });
|
|
438
|
-
return {
|
|
439
|
-
path,
|
|
440
|
-
mimeType: image.mimeType ?? "application/octet-stream",
|
|
441
|
-
byteSize: image.data.byteLength,
|
|
442
|
-
...(image.mimeType === null ? { unsupportedFormat: true } : {}),
|
|
443
|
-
};
|
|
444
|
-
}
|
|
445
|
-
catch (err) {
|
|
446
|
-
log.logWarning(`[${channelId}] Failed to persist inbound image`, errorMessage(err));
|
|
447
|
-
return null;
|
|
448
|
-
}
|
|
449
|
-
},
|
|
450
|
-
reserveEvent(event) {
|
|
451
|
-
// This must remain synchronous. DingTalkBot calls it before awaiting the queued
|
|
452
|
-
// handler, making the busy state observable to another message in the same tick.
|
|
453
|
-
getRunner(event.channelId).beginTurn(event.text);
|
|
454
|
-
},
|
|
455
|
-
async handleEvent(inboundEvent, bot, _isEvent) {
|
|
456
|
-
let event = inboundEvent;
|
|
457
|
-
if (isShuttingDown()) {
|
|
458
|
-
log.logInfo(`[${event.channelId}] Ignoring event during shutdown`);
|
|
459
|
-
return;
|
|
460
|
-
}
|
|
461
|
-
const runner = getRunner(event.channelId);
|
|
462
|
-
await getDurableDispatch()?.markStarted(event.dispatchId);
|
|
463
|
-
let structuredWakeFinalized = event.internalWake === undefined;
|
|
464
|
-
const task = (async () => {
|
|
465
|
-
let baseCtx;
|
|
466
|
-
try {
|
|
467
|
-
// Computed before archiving so a command's own text can be excluded from
|
|
468
|
-
// memory-extraction input (review 2026-08-24 §1.2): it is control-plane
|
|
469
|
-
// traffic, not conversation, and the history stays queryable via session_search.
|
|
470
|
-
const builtInCommand = parseBuiltInCommand(event.text);
|
|
471
|
-
await archiveIncomingMessage(event.channelId, {
|
|
472
|
-
date: new Date().toISOString(),
|
|
473
|
-
ts: event.ts,
|
|
474
|
-
user: event.user,
|
|
475
|
-
userName: event.userName,
|
|
476
|
-
text: event.text,
|
|
477
|
-
isBot: false,
|
|
478
|
-
skipContextSync: Boolean(builtInCommand),
|
|
479
|
-
images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
|
|
480
|
-
}, "user message");
|
|
481
|
-
// Background wakes deliver their result, not their process: no progress card, no
|
|
482
|
-
// thinking stream, nothing to clean up when a check-in ends `[SILENT]`.
|
|
483
|
-
// Awaited completions deliver their result too, without opening another progress card.
|
|
484
|
-
const backgroundOnly = Boolean(_isEvent);
|
|
485
|
-
// Spec 051, D3: a task-driver dispatch runs as a *task step* — in the task cycle's
|
|
486
|
-
// own session, with a brief instead of the wake text, and silent unless the step
|
|
487
|
-
// asked for a notify. Everything below (busy state, /stop, delivery) is unchanged;
|
|
488
|
-
// only which session the turn is bound to, and what reaches the channel, differ.
|
|
489
|
-
let taskStep;
|
|
490
|
-
baseCtx = createDingTalkContext(event, bot, store, backgroundOnly ? "none" : undefined);
|
|
491
|
-
let ctx = baseCtx;
|
|
492
|
-
if (builtInCommand) {
|
|
493
|
-
const commandStartedAt = Date.now();
|
|
494
|
-
const logCtx = { channelId: event.channelId, userName: event.userName };
|
|
495
|
-
log.logEvent("info", "runtime.command.started", "Executing command", {
|
|
496
|
-
ctx: logCtx,
|
|
497
|
-
fields: { command: builtInCommand.name },
|
|
498
|
-
});
|
|
499
|
-
try {
|
|
500
|
-
if (isIdleRuntimeCommandName(builtInCommand.name)) {
|
|
501
|
-
const response = await handler.runRuntimeCommand(event, builtInCommand.name, builtInCommand.args);
|
|
502
|
-
const delivered = await bot.sendPlain(event.channelId, response, {
|
|
503
|
-
title: `/${builtInCommand.name}`,
|
|
504
|
-
markdown: true,
|
|
505
|
-
});
|
|
506
|
-
if (!delivered) {
|
|
507
|
-
log.logWarning(`[${event.channelId}] Failed to deliver /${builtInCommand.name} reply`, `${response.length} chars`);
|
|
508
|
-
}
|
|
509
|
-
}
|
|
510
|
-
else if (isRunnerBuiltInCommand(builtInCommand)) {
|
|
511
|
-
await runner.handleBuiltinCommand(ctx, builtInCommand);
|
|
512
|
-
}
|
|
513
|
-
log.logEvent("info", "runtime.command.completed", "Command completed", {
|
|
514
|
-
ctx: logCtx,
|
|
515
|
-
fields: { command: builtInCommand.name, durationMs: Date.now() - commandStartedAt },
|
|
516
|
-
});
|
|
517
|
-
}
|
|
518
|
-
catch (err) {
|
|
519
|
-
log.logEvent("warn", "runtime.command.failed", "Command failed", {
|
|
520
|
-
ctx: logCtx,
|
|
521
|
-
fields: {
|
|
522
|
-
command: builtInCommand.name,
|
|
523
|
-
durationMs: Date.now() - commandStartedAt,
|
|
524
|
-
error: errorMessage(err),
|
|
525
|
-
},
|
|
526
|
-
});
|
|
527
|
-
throw err;
|
|
528
|
-
}
|
|
529
|
-
return;
|
|
530
|
-
}
|
|
531
|
-
// Reject an unknown slash command instead of spending a full LLM turn
|
|
532
|
-
// letting the model guess what `/modle` meant. Session commands,
|
|
533
|
-
// skills, and prompt templates are recognized by isKnownSlashCommand.
|
|
534
|
-
if (event.text.trim().startsWith("/") && !runner.isKnownSlashCommand(event.text)) {
|
|
535
|
-
const name = slashCommandName(event.text) ?? "";
|
|
536
|
-
await bot.sendPlain(event.channelId, formatUnknownCommandMessage(name));
|
|
537
|
-
return;
|
|
538
|
-
}
|
|
539
|
-
log.logEvent("info", "agent.turn.started", "Starting turn", {
|
|
540
|
-
ctx: { channelId: event.channelId, userName: event.userName },
|
|
541
|
-
fields: { messageLength: event.text.length, source: _isEvent ? "event" : "message" },
|
|
542
|
-
});
|
|
543
|
-
// A completion wake for a task's job or delegation: verified against the resource's own
|
|
544
|
-
// record before it may reopen the task (see `claimVerifiedWake`). Plain "belongs to task"
|
|
545
|
-
// text in a message never counts — only the producer-created `internalWake` envelope.
|
|
546
|
-
if (event.internalWake) {
|
|
547
|
-
const { kind, resourceId, taskId: wakeTaskId } = event.internalWake;
|
|
548
|
-
const claimed = await claimVerifiedWake(event, options.paths.workspaceDir, kind === "job" ? getJobs().get(event.channelId) : getRuns().get(event.channelId), options.wakeTransitionHooks?.[kind]);
|
|
549
|
-
if (!claimed) {
|
|
550
|
-
log.logWarning(`[${event.channelId}] Ignored an unverifiable ${kind} wake for ${resourceId} claiming task ${wakeTaskId}`);
|
|
551
|
-
structuredWakeFinalized = true;
|
|
552
|
-
return;
|
|
553
|
-
}
|
|
554
|
-
await claimed.finish();
|
|
555
|
-
structuredWakeFinalized = true;
|
|
556
|
-
// Drop without a turn only when something else is still driving this task (a sibling
|
|
557
|
-
// wake in the same fan-out already reopened it); in every other case nobody else will
|
|
558
|
-
// look at this result, so it still reaches a normal turn.
|
|
559
|
-
if (!claimed.activated && claimed.taskStillDriven)
|
|
560
|
-
return;
|
|
561
|
-
}
|
|
562
|
-
// Verified job/run wakes that activate a task are task steps too. Verification must happen
|
|
563
|
-
// first: routing directly from user-controlled wake text would grant task-only tools.
|
|
564
|
-
taskStep = await prepareTaskStep(event, runner);
|
|
565
|
-
if (taskStep) {
|
|
566
|
-
await baseCtx.close();
|
|
567
|
-
event = { ...event, text: taskStep.brief };
|
|
568
|
-
baseCtx = createDingTalkContext(event, bot, store, "none");
|
|
569
|
-
ctx = muteChannelContext(baseCtx);
|
|
570
|
-
}
|
|
571
|
-
if (!backgroundOnly && !taskStep)
|
|
572
|
-
ctx.primeCard(1500);
|
|
573
|
-
const result = await runner.run(ctx, store);
|
|
574
|
-
if (taskStep)
|
|
575
|
-
await finishTaskStep(event.channelId, taskStep.taskId, bot);
|
|
576
|
-
if (result.stopReason === "aborted" && runner.getTurnStatus().stopRequested) {
|
|
577
|
-
log.logInfo(`[${event.channelId}] Stopped`);
|
|
578
|
-
}
|
|
579
|
-
}
|
|
580
|
-
catch (err) {
|
|
581
|
-
log.logEvent("error", "agent.turn.failed", "Turn failed", {
|
|
582
|
-
ctx: { channelId: event.channelId, userName: event.userName },
|
|
583
|
-
fields: { error: errorMessage(err) },
|
|
584
|
-
});
|
|
585
|
-
}
|
|
586
|
-
finally {
|
|
587
|
-
await baseCtx?.close().catch((error) => {
|
|
588
|
-
log.logWarning(`[${event.channelId}] Failed to close delivery`, errorMessage(error));
|
|
589
|
-
});
|
|
590
|
-
if (structuredWakeFinalized)
|
|
591
|
-
await getDurableDispatch()?.markCompleted(event.dispatchId);
|
|
592
|
-
else
|
|
593
|
-
await getDurableDispatch()?.markRetryable(event.dispatchId);
|
|
594
|
-
runner.endTurn();
|
|
595
|
-
// A finished turn may have written task files; rescan now so `outcome: continue`
|
|
596
|
-
// queues the next step immediately instead of waiting out the current sleep.
|
|
597
|
-
getTaskDriver().nudge?.();
|
|
598
|
-
}
|
|
599
|
-
})();
|
|
600
|
-
activeTasks.add(task);
|
|
601
|
-
try {
|
|
602
|
-
await task;
|
|
603
|
-
}
|
|
604
|
-
finally {
|
|
605
|
-
activeTasks.delete(task);
|
|
606
|
-
}
|
|
607
|
-
},
|
|
608
|
-
};
|
|
609
|
-
return handler;
|
|
610
|
-
}
|
|
611
67
|
export async function createRuntimeContext(options) {
|
|
612
68
|
const startServices = options.startServices ?? true;
|
|
613
69
|
const registerSignalHandlers = options.registerSignalHandlers ?? true;
|
|
@@ -626,13 +82,16 @@ export async function createRuntimeContext(options) {
|
|
|
626
82
|
const channelIndex = createChannelIndex({ workspaceDir: options.paths.workspaceDir });
|
|
627
83
|
let durableDispatch;
|
|
628
84
|
let shuttingDown = false;
|
|
629
|
-
let shutdownPromise = null;
|
|
630
85
|
const archiveIncomingMessage = async (channelId, message, contextLabel) => {
|
|
631
86
|
try {
|
|
632
87
|
await store.logMessage(channelId, message);
|
|
633
88
|
}
|
|
634
89
|
catch (err) {
|
|
635
|
-
log.
|
|
90
|
+
log.logWarn("channel.archive.write_failed", "Message archive failed", {
|
|
91
|
+
channelId: channelId,
|
|
92
|
+
reason: errorMessage(err),
|
|
93
|
+
fields: { label: contextLabel },
|
|
94
|
+
});
|
|
636
95
|
}
|
|
637
96
|
};
|
|
638
97
|
const getRunner = (channelId) => {
|
|
@@ -671,7 +130,7 @@ export async function createRuntimeContext(options) {
|
|
|
671
130
|
const getJobs = () => jobs;
|
|
672
131
|
const getRuns = () => runs;
|
|
673
132
|
const getTaskDriver = () => taskDriver;
|
|
674
|
-
const handler =
|
|
133
|
+
const handler = createTurnHandler({
|
|
675
134
|
options,
|
|
676
135
|
store,
|
|
677
136
|
channelRunners,
|
|
@@ -692,18 +151,21 @@ export async function createRuntimeContext(options) {
|
|
|
692
151
|
const bot = options.createBot
|
|
693
152
|
? options.createBot(handler, options.dingtalkConfig)
|
|
694
153
|
: new DingTalkBot(handler, options.dingtalkConfig);
|
|
154
|
+
const dispatchStateDir = join(options.paths.appHomeDir, "state", "dispatch");
|
|
695
155
|
durableDispatch = new DurableDispatchService({
|
|
696
|
-
stateDir:
|
|
156
|
+
stateDir: dispatchStateDir,
|
|
697
157
|
bot,
|
|
698
158
|
// A structured wake (job/subagent completion, task-driver) that keeps failing before it can
|
|
699
159
|
// ever mark itself complete would otherwise redeliver forever (30s tick, no backoff prior to
|
|
700
160
|
// this notice). Surface it once instead of looping silently; the record stays on disk for
|
|
701
161
|
// inspection until a human clears it.
|
|
702
162
|
onExhausted: async (record) => {
|
|
703
|
-
log.
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
163
|
+
log.logEvent("warn", "dispatch.exhausted", "Dispatch exhausted", {
|
|
164
|
+
ctx: { channelId: record.event.channelId },
|
|
165
|
+
details: record.event.text.slice(0, 500),
|
|
166
|
+
fields: { dispatchId: record.id, deliveries: record.deliveries, producer: record.event.user },
|
|
167
|
+
});
|
|
168
|
+
await bot.sendPlain(record.event.channelId, renderDispatchExhaustedNotice(record, dispatchStateDir));
|
|
707
169
|
},
|
|
708
170
|
});
|
|
709
171
|
const executor = options.executor ?? createExecutor();
|
|
@@ -727,7 +189,7 @@ export async function createRuntimeContext(options) {
|
|
|
727
189
|
const level = runtimeSettingsManager.getDelegationSettings().notices;
|
|
728
190
|
if (level === "off")
|
|
729
191
|
return;
|
|
730
|
-
if (level === "settled" && notice.kind
|
|
192
|
+
if (level === "settled" && notice.kind === "progress")
|
|
731
193
|
return;
|
|
732
194
|
const text = renderRunNotice(notice);
|
|
733
195
|
if (text)
|
|
@@ -755,12 +217,18 @@ export async function createRuntimeContext(options) {
|
|
|
755
217
|
model: defaultModel.id,
|
|
756
218
|
});
|
|
757
219
|
if (recoveryReport.repaired.length > 0) {
|
|
758
|
-
log.
|
|
759
|
-
|
|
760
|
-
|
|
220
|
+
log.logWarn("runtime.recovery.repaired", "Interrupted turns repaired on restart", {
|
|
221
|
+
fields: {
|
|
222
|
+
repaired: recoveryReport.repaired.length,
|
|
223
|
+
scanned: recoveryReport.scanned,
|
|
224
|
+
channels: recoveryReport.repaired.map((r) => r.channelDir),
|
|
225
|
+
},
|
|
226
|
+
});
|
|
761
227
|
}
|
|
762
228
|
if (recoveryReport.blocked.length > 0) {
|
|
763
|
-
log.
|
|
229
|
+
log.logWarn("runtime.recovery.blocked", "Channels with an unrecoverable session will refuse new turns", {
|
|
230
|
+
reason: recoveryReport.blocked.map((b) => `${b.channelDir}: ${b.reason}`).join("; "),
|
|
231
|
+
});
|
|
764
232
|
}
|
|
765
233
|
const eventsWatcher = options.createEventsWatcher
|
|
766
234
|
? options.createEventsWatcher(options.paths.workspaceDir, bot, executor, options.paths.eventHistoryPath)
|
|
@@ -822,81 +290,22 @@ export async function createRuntimeContext(options) {
|
|
|
822
290
|
notify: (receipt) => bot.sendPlain(receipt.channelId, receipt.text),
|
|
823
291
|
isEnabled: tasksToolEnabled,
|
|
824
292
|
});
|
|
825
|
-
const shutdownWithReason =
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
293
|
+
const shutdownWithReason = createShutdown({
|
|
294
|
+
taskDriver,
|
|
295
|
+
getDurableDispatch,
|
|
296
|
+
memoryMaintenanceScheduler,
|
|
297
|
+
eventsWatcher,
|
|
298
|
+
runs,
|
|
299
|
+
jobs,
|
|
300
|
+
bot,
|
|
301
|
+
store,
|
|
302
|
+
channelIndex,
|
|
303
|
+
channelRunners,
|
|
304
|
+
activeTasks,
|
|
305
|
+
markShuttingDown: () => {
|
|
830
306
|
shuttingDown = true;
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
durableDispatch?.stop();
|
|
834
|
-
memoryMaintenanceScheduler.stop();
|
|
835
|
-
eventsWatcher.stop();
|
|
836
|
-
runs.stop();
|
|
837
|
-
jobs.stop();
|
|
838
|
-
await bot.stop();
|
|
839
|
-
const runningTasks = Array.from(activeTasks);
|
|
840
|
-
if (runningTasks.length > 0) {
|
|
841
|
-
log.logInfo(`Waiting for ${runningTasks.length} active task(s) to finish`);
|
|
842
|
-
const completed = await waitForTasks(runningTasks, SHUTDOWN_WAIT_MS);
|
|
843
|
-
if (!completed) {
|
|
844
|
-
log.logWarning(`Shutdown grace period exceeded ${SHUTDOWN_WAIT_MS}ms, aborting active runs`);
|
|
845
|
-
const aborts = [];
|
|
846
|
-
for (const [channelId, runner] of channelRunners) {
|
|
847
|
-
if (!runner.isBusy())
|
|
848
|
-
continue;
|
|
849
|
-
runner.requestStop();
|
|
850
|
-
log.logInfo(`[${channelId}] Aborting active run for shutdown`);
|
|
851
|
-
aborts.push(runner.abort().catch((err) => {
|
|
852
|
-
log.logWarning(`[${channelId}] Failed to abort run during shutdown`, errorMessage(err));
|
|
853
|
-
}));
|
|
854
|
-
}
|
|
855
|
-
await Promise.allSettled(aborts);
|
|
856
|
-
const remainingTasks = Array.from(activeTasks);
|
|
857
|
-
if (remainingTasks.length > 0) {
|
|
858
|
-
const abortedCompleted = await waitForTasks(remainingTasks, SHUTDOWN_ABORT_WAIT_MS);
|
|
859
|
-
if (!abortedCompleted) {
|
|
860
|
-
log.logWarning(`Shutdown forced exit with ${remainingTasks.length} task(s) still active`);
|
|
861
|
-
}
|
|
862
|
-
}
|
|
863
|
-
}
|
|
864
|
-
}
|
|
865
|
-
// Idle runners are disposed (flush memory, unsubscribe, release the SDK session); a
|
|
866
|
-
// still-busy one — its turn already aborted above — is just dropped from the cache and
|
|
867
|
-
// left to unwind on its own as the process exits.
|
|
868
|
-
const disposals = [];
|
|
869
|
-
for (const [channelId, runner] of channelRunners) {
|
|
870
|
-
if (runner.isBusy())
|
|
871
|
-
continue;
|
|
872
|
-
disposals.push(runner.dispose().catch((err) => {
|
|
873
|
-
log.logWarning(`[${channelId}] Failed to dispose runner during shutdown`, errorMessage(err));
|
|
874
|
-
}));
|
|
875
|
-
}
|
|
876
|
-
if (disposals.length > 0) {
|
|
877
|
-
log.logInfo(`Disposing ${disposals.length} idle channel runner(s) before shutdown`);
|
|
878
|
-
const disposed = await waitForTasks(disposals, SHUTDOWN_FLUSH_WAIT_MS);
|
|
879
|
-
if (!disposed) {
|
|
880
|
-
log.logWarning(`Shutdown runner disposal exceeded ${SHUTDOWN_FLUSH_WAIT_MS}ms`);
|
|
881
|
-
}
|
|
882
|
-
}
|
|
883
|
-
channelRunners.clear();
|
|
884
|
-
const storageFlushes = [
|
|
885
|
-
store.close(),
|
|
886
|
-
// Cancels the debounce timer and lands the last activity times.
|
|
887
|
-
channelIndex.close(),
|
|
888
|
-
getUsageLedger().flush?.() ?? Promise.resolve(),
|
|
889
|
-
flushSecurityLogs(),
|
|
890
|
-
...(eventsWatcher.flush ? [eventsWatcher.flush()] : []),
|
|
891
|
-
];
|
|
892
|
-
const storageFlushed = await waitForTasks(storageFlushes, SHUTDOWN_LOG_FLUSH_WAIT_MS);
|
|
893
|
-
if (!storageFlushed) {
|
|
894
|
-
log.logWarning(`Shutdown log flush exceeded ${SHUTDOWN_LOG_FLUSH_WAIT_MS}ms`);
|
|
895
|
-
}
|
|
896
|
-
await waitForTasks([log.flushLogging()], SHUTDOWN_LOG_FLUSH_WAIT_MS);
|
|
897
|
-
})();
|
|
898
|
-
return shutdownPromise;
|
|
899
|
-
};
|
|
307
|
+
},
|
|
308
|
+
});
|
|
900
309
|
if (registerSignalHandlers) {
|
|
901
310
|
process.once("SIGINT", () => {
|
|
902
311
|
void shutdownWithReason("SIGINT").finally(() => {
|
|
@@ -940,9 +349,11 @@ export async function bootstrap(argv, options = {}) {
|
|
|
940
349
|
parseArgs(argv, paths, io);
|
|
941
350
|
const bootstrapResult = bootstrapAppHome(paths);
|
|
942
351
|
printBootstrapSummary(bootstrapResult, io, paths);
|
|
352
|
+
// A freshly written template is the expected first-run outcome, not a failure: guide and exit 0.
|
|
353
|
+
// A template that exists but is still unfilled is caught by `loadConfig` below and exits 1.
|
|
943
354
|
if (bootstrapResult.channelTemplateCreated) {
|
|
944
|
-
io
|
|
945
|
-
throw new BootstrapExitError(
|
|
355
|
+
printFirstRunGuide(io, paths);
|
|
356
|
+
throw new BootstrapExitError(0);
|
|
946
357
|
}
|
|
947
358
|
const dingtalkConfig = loadConfig(paths, io);
|
|
948
359
|
dingtalkConfig.stateDir = paths.workspaceDir;
|