@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
|
@@ -1,66 +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 { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, loadConfig, parseArgs, printBootstrapSummary, printFirstRunGuide, readCliVersion, } from "./app-home.js";
|
|
36
|
-
import { createDingTalkContext } from "./delivery.js";
|
|
37
|
-
import { DingTalkBot, } from "./dingtalk.js";
|
|
38
31
|
import { DurableDispatchService, renderDispatchExhaustedNotice } from "./durable-dispatch.js";
|
|
39
|
-
import {
|
|
40
|
-
import {
|
|
41
|
-
import { renderRunNotice } from "./subagent-commands.js";
|
|
42
|
-
import { createTaskDriverEvent, parseDriverTaskId, TaskDriver } from "./task-driver.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
|
-
import { isCoalescableWake, MAX_COALESCED_WAKES, mergeCompletionWakes } from "./wake-coalescing.js";
|
|
47
|
-
const SHUTDOWN_WAIT_MS = 15000;
|
|
48
|
-
const SHUTDOWN_FLUSH_WAIT_MS = 45000;
|
|
49
|
-
const SHUTDOWN_ABORT_WAIT_MS = 5000;
|
|
50
|
-
const SHUTDOWN_LOG_FLUSH_WAIT_MS = 10_000;
|
|
51
|
-
function waitForTasks(tasks, timeoutMs) {
|
|
52
|
-
if (tasks.length === 0) {
|
|
53
|
-
return Promise.resolve(true);
|
|
54
|
-
}
|
|
55
|
-
return new Promise((resolve) => {
|
|
56
|
-
const timer = setTimeout(() => resolve(false), timeoutMs);
|
|
57
|
-
timer.unref?.();
|
|
58
|
-
void Promise.allSettled(tasks).then(() => {
|
|
59
|
-
clearTimeout(timer);
|
|
60
|
-
resolve(true);
|
|
61
|
-
});
|
|
62
|
-
});
|
|
63
|
-
}
|
|
36
|
+
import { createTurnHandler } from "./turn-handler.js";
|
|
64
37
|
/**
|
|
65
38
|
* Ceiling on cached runners per daemon process. A long-lived daemon otherwise accumulates one
|
|
66
39
|
* `ChannelRunner` (session, subscriptions, memory state) per distinct channel it has ever heard
|
|
@@ -91,617 +64,6 @@ async function evictIdleRunnersOverCap(channelRunners) {
|
|
|
91
64
|
});
|
|
92
65
|
}
|
|
93
66
|
}
|
|
94
|
-
function isNoRunningTaskQueueError(err) {
|
|
95
|
-
return err instanceof Error && err.message === "No task is currently running.";
|
|
96
|
-
}
|
|
97
|
-
/**
|
|
98
|
-
* Absolute `InboundImage.path`s → paths relative to the channel directory, for
|
|
99
|
-
* `LoggedMessage.images` (spec 049). `log.jsonl` already stores everything else channel-relative
|
|
100
|
-
* (it lives inside the channel directory itself); an absolute path there would be dead on any
|
|
101
|
-
* machine other than the one that wrote it, and `~/.pipiclaw` itself can move between backup and
|
|
102
|
-
* restore.
|
|
103
|
-
*/
|
|
104
|
-
function relativeImagePaths(workspaceDir, channelId, images) {
|
|
105
|
-
if (!images || images.length === 0)
|
|
106
|
-
return [];
|
|
107
|
-
const channelDir = getChannelDir(workspaceDir, channelId);
|
|
108
|
-
return images.map((image) => relative(channelDir, image.path));
|
|
109
|
-
}
|
|
110
|
-
/**
|
|
111
|
-
* The `runRuntimeCommand` names usable on the idle-turn path — every `BUILT_IN_COMMANDS` entry
|
|
112
|
-
* *not* marked `runnerHandled`, i.e. every stateless report. `context` is the one deliberate
|
|
113
|
-
* exception even though it isn't runner-handled while busy (see the busy-path switch in
|
|
114
|
-
* `dingtalk.ts`): idle answers it through the runner's ChannelContext-aware command path
|
|
115
|
-
* (thread-reply, delete semantics) instead, so it is routed like the runner-handled built-ins
|
|
116
|
-
* here and excluded from this stateless-report set.
|
|
117
|
-
*/
|
|
118
|
-
const IDLE_RUNTIME_COMMAND_NAMES = new Set(BUILT_IN_COMMANDS.filter((command) => !command.runnerHandled).map((command) => command.name));
|
|
119
|
-
function isIdleRuntimeCommandName(name) {
|
|
120
|
-
return IDLE_RUNTIME_COMMAND_NAMES.has(name);
|
|
121
|
-
}
|
|
122
|
-
/**
|
|
123
|
-
* How long `/stop` waits for the turn to actually end before force-releasing it.
|
|
124
|
-
* `requestStop` + `abort` only reach the agent loop; a turn wedged in its
|
|
125
|
-
* epilogue (delivery drain, session-resource reload, memory flush) ignores both
|
|
126
|
-
* and would otherwise keep the channel reporting "已有回合在运行" indefinitely.
|
|
127
|
-
*/
|
|
128
|
-
const STOP_FORCE_END_GRACE_MS = 15_000;
|
|
129
|
-
const STOP_FORCE_END_POLL_MS = 250;
|
|
130
|
-
/**
|
|
131
|
-
* Watchdog for `/stop`: release the channel if the stopped turn has not ended
|
|
132
|
-
* once the grace window elapses. Returns true when it had to force the release.
|
|
133
|
-
*/
|
|
134
|
-
export async function forceEndStuckTurnAfterStop(input) {
|
|
135
|
-
const graceMs = input.graceMs ?? STOP_FORCE_END_GRACE_MS;
|
|
136
|
-
const pollMs = input.pollMs ?? STOP_FORCE_END_POLL_MS;
|
|
137
|
-
const deadline = Date.now() + graceMs;
|
|
138
|
-
while (input.runner.isBusy() && Date.now() < deadline) {
|
|
139
|
-
await sleepUnref(Math.min(pollMs, Math.max(1, deadline - Date.now())));
|
|
140
|
-
}
|
|
141
|
-
if (!input.runner.forceEndTurn(`/stop did not take effect within ${graceMs}ms`)) {
|
|
142
|
-
return false;
|
|
143
|
-
}
|
|
144
|
-
await input
|
|
145
|
-
.notify?.(`⚠️ 上一个回合的收尾卡住了,已强制结束以释放会话(后台清理仍在继续)。现在可以正常发消息或使用 \`/new\`、\`/model\`。`)
|
|
146
|
-
.catch(() => undefined);
|
|
147
|
-
return true;
|
|
148
|
-
}
|
|
149
|
-
function createDingTalkHandler(deps) {
|
|
150
|
-
const { options, store, channelRunners, sessionResetChains, activeTasks, stopWatchdogs, channelIndex, archiveIncomingMessage, getRunner, cliVersion, startedAt, isShuttingDown, getDurableDispatch, getJobs, getRuns, getTaskDriver, } = deps;
|
|
151
|
-
/**
|
|
152
|
-
* Turn a `[TASK_DRIVER:<id>]` dispatch into a task loop step: bind the runner to the task
|
|
153
|
-
* cycle's own session and replace the wake text with the step brief. Returns `undefined` for
|
|
154
|
-
* every other event, which then follows the unchanged chat path.
|
|
155
|
-
*
|
|
156
|
-
* Binding failures fall back to the chat path rather than dropping the wake — a task that
|
|
157
|
-
* cannot open its session should still be visible, not silently skipped.
|
|
158
|
-
*/
|
|
159
|
-
const prepareTaskStep = async (event, runner) => {
|
|
160
|
-
const taskId = parseDriverTaskId(event.text) ?? event.internalWake?.taskId;
|
|
161
|
-
if (!taskId)
|
|
162
|
-
return undefined;
|
|
163
|
-
const channelDir = ensureChannelDir(options.paths.workspaceDir, event.channelId);
|
|
164
|
-
try {
|
|
165
|
-
const brief = await buildTaskStepBrief({ channelDir, taskId });
|
|
166
|
-
if (!brief)
|
|
167
|
-
return undefined;
|
|
168
|
-
await runner.bindTaskSession(taskId);
|
|
169
|
-
return { taskId, brief };
|
|
170
|
-
}
|
|
171
|
-
catch (error) {
|
|
172
|
-
log.logWarn("taskdriver.step.start_failed", "Task step start failed", {
|
|
173
|
-
channelId: event.channelId,
|
|
174
|
-
reason: errorMessage(error),
|
|
175
|
-
fields: { taskId },
|
|
176
|
-
});
|
|
177
|
-
return undefined;
|
|
178
|
-
}
|
|
179
|
-
};
|
|
180
|
-
/** Deliver whatever the step asked to say, then hand the runner back to the chat session. */
|
|
181
|
-
const finishTaskStep = async (channelId, taskId, bot) => {
|
|
182
|
-
const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
|
|
183
|
-
try {
|
|
184
|
-
const notice = await consumeTaskNotice(channelDir, taskId);
|
|
185
|
-
if (notice) {
|
|
186
|
-
// runner.run closes its per-turn delivery context before returning. Sending through that
|
|
187
|
-
// closed context silently dropped successful task_step_end notifications (T-run-01).
|
|
188
|
-
const delivered = await bot.sendPlain(channelId, notice);
|
|
189
|
-
if (delivered)
|
|
190
|
-
await store.logBotResponse(channelId, notice, Date.now().toString());
|
|
191
|
-
else
|
|
192
|
-
log.logWarn("taskdriver.notice.delivery_failed", "Task notice delivery failed", {
|
|
193
|
-
channelId: channelId,
|
|
194
|
-
fields: { taskId },
|
|
195
|
-
});
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
catch (error) {
|
|
199
|
-
log.logWarn("taskdriver.notice.delivery_failed", "Task notice delivery failed", {
|
|
200
|
-
channelId: channelId,
|
|
201
|
-
reason: errorMessage(error),
|
|
202
|
-
fields: { taskId },
|
|
203
|
-
});
|
|
204
|
-
}
|
|
205
|
-
await getRunner(channelId).bindChatSession();
|
|
206
|
-
};
|
|
207
|
-
const handler = {
|
|
208
|
-
isRunning(channelId) {
|
|
209
|
-
return channelRunners.get(channelId)?.isBusy() ?? false;
|
|
210
|
-
},
|
|
211
|
-
noteChannelActivity(observation) {
|
|
212
|
-
if (isShuttingDown())
|
|
213
|
-
return;
|
|
214
|
-
channelIndex.note(observation);
|
|
215
|
-
},
|
|
216
|
-
async handleStop(channelId, _bot) {
|
|
217
|
-
const runner = channelRunners.get(channelId);
|
|
218
|
-
let pausedTaskId;
|
|
219
|
-
if (runner?.isBusy()) {
|
|
220
|
-
runner.requestStop();
|
|
221
|
-
// Stopping a task step stops the task: otherwise the driver would queue the next step
|
|
222
|
-
// straight away. The step may not be bound to its session yet, so fall back to the text.
|
|
223
|
-
const taskId = runner.getTaskLoop()?.taskId ?? parseDriverTaskId(runner.getTurnStatus().taskText);
|
|
224
|
-
if (taskId) {
|
|
225
|
-
await pauseStoredTask(getChannelDir(options.paths.workspaceDir, channelId), taskId, {
|
|
226
|
-
by: "user",
|
|
227
|
-
reason: "用户 /stop 中止了该任务的当前步骤。",
|
|
228
|
-
});
|
|
229
|
-
pausedTaskId = taskId;
|
|
230
|
-
log.logInfoEvent("tasks.task.paused_on_stop", "Task paused on /stop", {
|
|
231
|
-
channelId: channelId,
|
|
232
|
-
fields: { taskId },
|
|
233
|
-
});
|
|
234
|
-
}
|
|
235
|
-
_bot.discardCard(channelId);
|
|
236
|
-
// Drop queued-but-not-started messages so a burst does not keep
|
|
237
|
-
// running after the user asked to halt; abort the in-flight one.
|
|
238
|
-
const dropped = _bot.clearPendingMessages(channelId);
|
|
239
|
-
if (dropped > 0) {
|
|
240
|
-
log.logInfoEvent("agent.turn.queue_dropped", "Queued messages dropped on /stop", {
|
|
241
|
-
channelId: channelId,
|
|
242
|
-
fields: { count: dropped },
|
|
243
|
-
});
|
|
244
|
-
}
|
|
245
|
-
void runner.abort().catch((err) => {
|
|
246
|
-
log.logWarn("agent.turn.abort_failed", "Turn abort failed", {
|
|
247
|
-
channelId: channelId,
|
|
248
|
-
reason: errorMessage(err),
|
|
249
|
-
});
|
|
250
|
-
});
|
|
251
|
-
void getDurableDispatch()
|
|
252
|
-
?.cancelChannel(channelId)
|
|
253
|
-
.then((canceled) => {
|
|
254
|
-
if (canceled)
|
|
255
|
-
log.logInfoEvent("dispatch.cancel.reset", "Durable dispatch leases reset on /stop", {
|
|
256
|
-
channelId: channelId,
|
|
257
|
-
fields: { count: canceled },
|
|
258
|
-
});
|
|
259
|
-
})
|
|
260
|
-
.catch((err) => {
|
|
261
|
-
log.logWarn("dispatch.cancel.failed", "Durable dispatch lease reset on stop failed", {
|
|
262
|
-
channelId: channelId,
|
|
263
|
-
reason: errorMessage(err),
|
|
264
|
-
});
|
|
265
|
-
});
|
|
266
|
-
log.logInfoEvent("agent.turn.stop_requested", "Stop requested", { channelId: channelId });
|
|
267
|
-
if (!stopWatchdogs.has(channelId)) {
|
|
268
|
-
stopWatchdogs.add(channelId);
|
|
269
|
-
void forceEndStuckTurnAfterStop({
|
|
270
|
-
channelId,
|
|
271
|
-
runner,
|
|
272
|
-
graceMs: options.stopForceEndGraceMs,
|
|
273
|
-
notify: (text) => _bot.sendPlain(channelId, text),
|
|
274
|
-
})
|
|
275
|
-
.catch((err) => {
|
|
276
|
-
log.logWarn("agent.turn.stop_watchdog_failed", "Stop watchdog failed", {
|
|
277
|
-
channelId: channelId,
|
|
278
|
-
reason: errorMessage(err),
|
|
279
|
-
});
|
|
280
|
-
})
|
|
281
|
-
.finally(() => {
|
|
282
|
-
stopWatchdogs.delete(channelId);
|
|
283
|
-
});
|
|
284
|
-
}
|
|
285
|
-
}
|
|
286
|
-
return { pausedTaskId };
|
|
287
|
-
},
|
|
288
|
-
async handleNewSession(event, _bot) {
|
|
289
|
-
if (isShuttingDown())
|
|
290
|
-
return;
|
|
291
|
-
const previous = sessionResetChains.get(event.channelId) ?? Promise.resolve();
|
|
292
|
-
const reset = previous
|
|
293
|
-
.catch(() => undefined)
|
|
294
|
-
.then(async () => {
|
|
295
|
-
try {
|
|
296
|
-
const channelDir = ensureChannelDir(options.paths.workspaceDir, event.channelId);
|
|
297
|
-
const access = resolveProjectAccessPolicy(loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config, process.cwd());
|
|
298
|
-
const scope = resolveProjectScope(channelDir, access);
|
|
299
|
-
if (scope.kind === "blocked") {
|
|
300
|
-
throw new Error(scope.reason);
|
|
301
|
-
}
|
|
302
|
-
// The empty session file and active pointer are committed before the old
|
|
303
|
-
// generation is touched. A filesystem failure therefore leaves the live
|
|
304
|
-
// session authoritative and retryable.
|
|
305
|
-
const result = await createFreshActiveSession(channelDir, scope.scope.projectRoot);
|
|
306
|
-
const oldRunner = channelRunners.get(event.channelId);
|
|
307
|
-
if (oldRunner) {
|
|
308
|
-
channelRunners.delete(event.channelId);
|
|
309
|
-
try {
|
|
310
|
-
oldRunner.retireForNewSession();
|
|
311
|
-
}
|
|
312
|
-
catch (error) {
|
|
313
|
-
// The active pointer already names the new session. Retirement is
|
|
314
|
-
// best-effort cleanup and must not misreport the committed reset as failed.
|
|
315
|
-
log.logWarn("agent.session.retire_failed", "Old runner retirement after /new failed", {
|
|
316
|
-
channelId: event.channelId,
|
|
317
|
-
reason: errorMessage(error),
|
|
318
|
-
});
|
|
319
|
-
}
|
|
320
|
-
}
|
|
321
|
-
const dropped = _bot.resetChannelQueue(event.channelId);
|
|
322
|
-
if (dropped > 0) {
|
|
323
|
-
log.logInfoEvent("agent.session.queue_dropped", "Old-session queued messages discarded by /new", {
|
|
324
|
-
channelId: event.channelId,
|
|
325
|
-
fields: { count: dropped },
|
|
326
|
-
});
|
|
327
|
-
}
|
|
328
|
-
await _bot.sendPlain(event.channelId, formatNewSessionReply(result.sessionId));
|
|
329
|
-
void archiveIncomingMessage(event.channelId, {
|
|
330
|
-
date: new Date().toISOString(),
|
|
331
|
-
ts: event.ts,
|
|
332
|
-
user: event.user,
|
|
333
|
-
userName: event.userName,
|
|
334
|
-
text: event.text,
|
|
335
|
-
isBot: false,
|
|
336
|
-
images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
|
|
337
|
-
}, "/new command");
|
|
338
|
-
}
|
|
339
|
-
catch (error) {
|
|
340
|
-
const message = errorMessage(error);
|
|
341
|
-
log.logWarn("agent.session.create_failed", "Fresh session creation failed", {
|
|
342
|
-
channelId: event.channelId,
|
|
343
|
-
reason: message,
|
|
344
|
-
});
|
|
345
|
-
await _bot.sendPlain(event.channelId, `新会话创建失败:${message}\n旧会话保持不变,可以重试 \`/new\`。`);
|
|
346
|
-
}
|
|
347
|
-
});
|
|
348
|
-
sessionResetChains.set(event.channelId, reset);
|
|
349
|
-
activeTasks.add(reset);
|
|
350
|
-
try {
|
|
351
|
-
await reset;
|
|
352
|
-
}
|
|
353
|
-
finally {
|
|
354
|
-
activeTasks.delete(reset);
|
|
355
|
-
if (sessionResetChains.get(event.channelId) === reset) {
|
|
356
|
-
sessionResetChains.delete(event.channelId);
|
|
357
|
-
}
|
|
358
|
-
}
|
|
359
|
-
},
|
|
360
|
-
async runRuntimeCommand(event, name, args) {
|
|
361
|
-
const { channelId } = event;
|
|
362
|
-
return runReportCommand({
|
|
363
|
-
channelId,
|
|
364
|
-
paths: options.paths,
|
|
365
|
-
actor: "dingtalk-command",
|
|
366
|
-
version: cliVersion,
|
|
367
|
-
startedAt,
|
|
368
|
-
peekRunner: () => channelRunners.get(channelId),
|
|
369
|
-
getRunner: () => getRunner(channelId),
|
|
370
|
-
runManager: getRuns().get(channelId),
|
|
371
|
-
runningJobLines: () => getJobs().runningLines(channelId),
|
|
372
|
-
// D4.2: dispose the cached runner so the next access rebuilds it under the new scope.
|
|
373
|
-
// The active-session ref is untouched — same session, new project root.
|
|
374
|
-
onScopeChanged: async () => {
|
|
375
|
-
const runner = channelRunners.get(channelId);
|
|
376
|
-
channelRunners.delete(channelId);
|
|
377
|
-
await runner?.dispose().catch((err) => {
|
|
378
|
-
log.logWarn("runtime.runner.dispose_failed", "Runner dispose after /project failed", {
|
|
379
|
-
channelId: channelId,
|
|
380
|
-
reason: errorMessage(err),
|
|
381
|
-
});
|
|
382
|
-
});
|
|
383
|
-
},
|
|
384
|
-
dispatchTask: async (id) => {
|
|
385
|
-
const channelDir = getChannelDir(options.paths.workspaceDir, channelId);
|
|
386
|
-
const entry = (await readActiveTasks(join(channelDir, "tasks"))).find((candidate) => candidate.id === id);
|
|
387
|
-
if (!entry)
|
|
388
|
-
return false;
|
|
389
|
-
// A human asking to run a task twice means twice, so this key is deliberately
|
|
390
|
-
// unique per invocation rather than sharing the driver's occurrence key (D1).
|
|
391
|
-
const now = Date.now();
|
|
392
|
-
return ((await getDurableDispatch()?.dispatch({
|
|
393
|
-
...createTaskDriverEvent(channelId, entry, now),
|
|
394
|
-
dispatchId: `task:${channelId}:${entry.id}:manual:${new Date(now).toISOString()}`,
|
|
395
|
-
})) ?? false);
|
|
396
|
-
},
|
|
397
|
-
}, name, args);
|
|
398
|
-
},
|
|
399
|
-
async handleBusyMessage(event, bot, mode, queueText) {
|
|
400
|
-
if (isShuttingDown()) {
|
|
401
|
-
return { kind: "handled" };
|
|
402
|
-
}
|
|
403
|
-
const runner = getRunner(event.channelId);
|
|
404
|
-
const trimmedQueueText = queueText.trim();
|
|
405
|
-
if (!trimmedQueueText) {
|
|
406
|
-
await bot.sendPlain(event.channelId, formatMissingQueueMessage(mode === "followUp" ? "followup" : "steer"));
|
|
407
|
-
return { kind: "handled" };
|
|
408
|
-
}
|
|
409
|
-
// Compaction is maintenance, not user work. A new message cancels it and is
|
|
410
|
-
// kept as a normal queued turn instead of trying to steer an agent loop that
|
|
411
|
-
// is currently disconnected for summarization.
|
|
412
|
-
if (runner.interruptCompaction()) {
|
|
413
|
-
log.logInfoEvent("agent.compaction.interrupted", "Compaction interrupted for a new user message", {
|
|
414
|
-
channelId: event.channelId,
|
|
415
|
-
});
|
|
416
|
-
return { kind: "requeue", text: trimmedQueueText };
|
|
417
|
-
}
|
|
418
|
-
// A task step runs in the task's own session and is muted: a steer here would land in
|
|
419
|
-
// the background task's context and its answer would never reach the user, while the
|
|
420
|
-
// message itself is kept out of the chat session. Run it as the next chat turn instead.
|
|
421
|
-
const taskLoop = runner.getTaskLoop();
|
|
422
|
-
if (taskLoop) {
|
|
423
|
-
await bot.sendPlain(event.channelId, `后台任务 \`${taskLoop.taskId}\` 正在执行一步,你的消息会在这一步结束后处理;要给该任务补充指示,用 \`/tasks steer ${taskLoop.taskId} <内容>\`。`);
|
|
424
|
-
log.logEvent("info", "agent.turn.followup_queued", "Message deferred past a task step", {
|
|
425
|
-
ctx: { channelId: event.channelId, userName: event.userName },
|
|
426
|
-
fields: { messageLength: trimmedQueueText.length, taskId: taskLoop.taskId },
|
|
427
|
-
});
|
|
428
|
-
return { kind: "requeue", text: trimmedQueueText };
|
|
429
|
-
}
|
|
430
|
-
if (mode === "followUp") {
|
|
431
|
-
log.logEvent("info", "agent.turn.followup_queued", "Follow-up queued", {
|
|
432
|
-
ctx: { channelId: event.channelId, userName: event.userName },
|
|
433
|
-
fields: { messageLength: trimmedQueueText.length },
|
|
434
|
-
});
|
|
435
|
-
return { kind: "requeue", text: trimmedQueueText };
|
|
436
|
-
}
|
|
437
|
-
try {
|
|
438
|
-
await runner.queueSteer(trimmedQueueText, event.userName, event.images);
|
|
439
|
-
await archiveIncomingMessage(event.channelId, {
|
|
440
|
-
date: new Date().toISOString(),
|
|
441
|
-
ts: event.ts,
|
|
442
|
-
user: event.user,
|
|
443
|
-
userName: event.userName,
|
|
444
|
-
text: event.text,
|
|
445
|
-
isBot: false,
|
|
446
|
-
deliveryMode: mode,
|
|
447
|
-
skipContextSync: true,
|
|
448
|
-
images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
|
|
449
|
-
}, `${mode} message`);
|
|
450
|
-
await bot.sendPlain(event.channelId, formatSteerQueued(!event.text.trim().startsWith("/")));
|
|
451
|
-
log.logEvent("info", "agent.turn.steer_queued", "Steer queued", {
|
|
452
|
-
ctx: { channelId: event.channelId, userName: event.userName },
|
|
453
|
-
fields: { messageLength: trimmedQueueText.length },
|
|
454
|
-
});
|
|
455
|
-
return { kind: "handled" };
|
|
456
|
-
}
|
|
457
|
-
catch (err) {
|
|
458
|
-
const errMsg = errorMessage(err);
|
|
459
|
-
if (isNoRunningTaskQueueError(err)) {
|
|
460
|
-
log.logInfoEvent("agent.turn.requeued", "Busy window closed; message requeued as a normal turn", {
|
|
461
|
-
channelId: event.channelId,
|
|
462
|
-
fields: { mode },
|
|
463
|
-
});
|
|
464
|
-
return { kind: "requeue", text: trimmedQueueText };
|
|
465
|
-
}
|
|
466
|
-
log.logWarn("agent.turn.queue_failed", "Busy message queueing failed", {
|
|
467
|
-
channelId: event.channelId,
|
|
468
|
-
reason: errMsg,
|
|
469
|
-
fields: { mode },
|
|
470
|
-
});
|
|
471
|
-
await bot.sendPlain(event.channelId, `这条消息没能排进当前回合:${errMsg}\n等当前回合结束后重发,或用 \`/followup <消息>\` 排到它之后。`);
|
|
472
|
-
return { kind: "handled" };
|
|
473
|
-
}
|
|
474
|
-
},
|
|
475
|
-
/**
|
|
476
|
-
* Persist one downloaded inbound image under the channel's `inbox/` (spec 049). Bootstrap
|
|
477
|
-
* owns this, not the transport, because it holds the workspace root; see the doc comment
|
|
478
|
-
* on `DingTalkHandler.persistInboundImage` for the full contract (`mimeType: null` case
|
|
479
|
-
* included).
|
|
480
|
-
*/
|
|
481
|
-
async persistInboundImage(channelId, image) {
|
|
482
|
-
try {
|
|
483
|
-
const dir = join(getChannelDir(options.paths.workspaceDir, channelId), "inbox");
|
|
484
|
-
await mkdir(dir, { recursive: true });
|
|
485
|
-
const extension = extensionForMimeType(image.mimeType);
|
|
486
|
-
const path = join(dir, `image-${localStampForFilename()}-${Math.random().toString(36).slice(2, 8)}.${extension}`);
|
|
487
|
-
await writeFile(path, image.data, { mode: 0o600 });
|
|
488
|
-
return {
|
|
489
|
-
path,
|
|
490
|
-
mimeType: image.mimeType ?? "application/octet-stream",
|
|
491
|
-
byteSize: image.data.byteLength,
|
|
492
|
-
...(image.mimeType === null ? { unsupportedFormat: true } : {}),
|
|
493
|
-
};
|
|
494
|
-
}
|
|
495
|
-
catch (err) {
|
|
496
|
-
log.logWarn("dingtalk.media.persist_failed", "Inbound image persist failed", {
|
|
497
|
-
channelId: channelId,
|
|
498
|
-
reason: errorMessage(err),
|
|
499
|
-
});
|
|
500
|
-
return null;
|
|
501
|
-
}
|
|
502
|
-
},
|
|
503
|
-
reserveEvent(event) {
|
|
504
|
-
// This must remain synchronous. DingTalkBot calls it before awaiting the queued
|
|
505
|
-
// handler, making the busy state observable to another message in the same tick.
|
|
506
|
-
getRunner(event.channelId).beginTurn(event.text);
|
|
507
|
-
},
|
|
508
|
-
async handleEvent(inboundEvent, bot, _isEvent) {
|
|
509
|
-
let event = inboundEvent;
|
|
510
|
-
if (isShuttingDown()) {
|
|
511
|
-
log.logInfoEvent("runtime.shutdown.event_ignored", "Event ignored during shutdown", {
|
|
512
|
-
channelId: event.channelId,
|
|
513
|
-
});
|
|
514
|
-
return;
|
|
515
|
-
}
|
|
516
|
-
const runner = getRunner(event.channelId);
|
|
517
|
-
const durable = getDurableDispatch();
|
|
518
|
-
if (durable && !(await durable.markStarted(event.dispatchId))) {
|
|
519
|
-
// A stale delivery of a wake an earlier turn already absorbed and handled.
|
|
520
|
-
runner.endTurn();
|
|
521
|
-
return;
|
|
522
|
-
}
|
|
523
|
-
let structuredWakeFinalized = event.internalWake === undefined;
|
|
524
|
-
/** Other completion wakes folded into this turn; finished together with this one. */
|
|
525
|
-
let absorbedDispatchIds = [];
|
|
526
|
-
if (durable && event.dispatchId && isCoalescableWake(event)) {
|
|
527
|
-
const absorbed = await durable
|
|
528
|
-
.absorbPending(event.channelId, event.dispatchId, isCoalescableWake, MAX_COALESCED_WAKES - 1)
|
|
529
|
-
.catch((error) => {
|
|
530
|
-
log.logWarn("dispatch.wake.absorb_failed", "Wake coalescing failed", {
|
|
531
|
-
channelId: event.channelId,
|
|
532
|
-
reason: errorMessage(error),
|
|
533
|
-
});
|
|
534
|
-
return [];
|
|
535
|
-
});
|
|
536
|
-
if (absorbed.length > 0) {
|
|
537
|
-
event = mergeCompletionWakes(event, absorbed);
|
|
538
|
-
absorbedDispatchIds = absorbed.flatMap((absorbedEvent) => absorbedEvent.dispatchId ? [absorbedEvent.dispatchId] : []);
|
|
539
|
-
log.logInfoEvent("dispatch.wake.coalesced", "Completion wakes coalesced", {
|
|
540
|
-
channelId: event.channelId,
|
|
541
|
-
fields: { primary: event.dispatchId, absorbed: absorbedDispatchIds.length },
|
|
542
|
-
});
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
const task = (async () => {
|
|
546
|
-
let baseCtx;
|
|
547
|
-
try {
|
|
548
|
-
// Computed before archiving so a command's own text can be excluded from
|
|
549
|
-
// memory-extraction input (review 2026-08-24 §1.2): it is control-plane
|
|
550
|
-
// traffic, not conversation, and the history stays queryable via session_search.
|
|
551
|
-
const builtInCommand = parseBuiltInCommand(event.text);
|
|
552
|
-
await archiveIncomingMessage(event.channelId, {
|
|
553
|
-
date: new Date().toISOString(),
|
|
554
|
-
ts: event.ts,
|
|
555
|
-
user: event.user,
|
|
556
|
-
userName: event.userName,
|
|
557
|
-
text: event.text,
|
|
558
|
-
isBot: false,
|
|
559
|
-
skipContextSync: Boolean(builtInCommand),
|
|
560
|
-
images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
|
|
561
|
-
}, "user message");
|
|
562
|
-
// Background wakes deliver their result, not their process: no progress card, no
|
|
563
|
-
// thinking stream, nothing to clean up when a check-in ends `[SILENT]`.
|
|
564
|
-
// Awaited completions deliver their result too, without opening another progress card.
|
|
565
|
-
const backgroundOnly = Boolean(_isEvent);
|
|
566
|
-
// Spec 051, D3: a task-driver dispatch runs as a *task step* — in the task cycle's
|
|
567
|
-
// own session, with a brief instead of the wake text, and silent unless the step
|
|
568
|
-
// asked for a notify. Everything below (busy state, /stop, delivery) is unchanged;
|
|
569
|
-
// only which session the turn is bound to, and what reaches the channel, differ.
|
|
570
|
-
let taskStep;
|
|
571
|
-
baseCtx = createDingTalkContext(event, bot, store, backgroundOnly ? "none" : undefined);
|
|
572
|
-
let ctx = baseCtx;
|
|
573
|
-
if (builtInCommand) {
|
|
574
|
-
const commandStartedAt = Date.now();
|
|
575
|
-
const logCtx = { channelId: event.channelId, userName: event.userName };
|
|
576
|
-
log.logEvent("info", "runtime.command.started", "Executing command", {
|
|
577
|
-
ctx: logCtx,
|
|
578
|
-
fields: { command: builtInCommand.name },
|
|
579
|
-
});
|
|
580
|
-
try {
|
|
581
|
-
if (isIdleRuntimeCommandName(builtInCommand.name)) {
|
|
582
|
-
const response = await handler.runRuntimeCommand(event, builtInCommand.name, builtInCommand.args);
|
|
583
|
-
const delivered = await bot.sendPlain(event.channelId, response, {
|
|
584
|
-
title: `/${builtInCommand.name}`,
|
|
585
|
-
markdown: true,
|
|
586
|
-
});
|
|
587
|
-
if (!delivered) {
|
|
588
|
-
log.logWarn("delivery.command_reply.failed", "Command reply delivery failed", {
|
|
589
|
-
channelId: event.channelId,
|
|
590
|
-
fields: { command: builtInCommand.name, chars: response.length },
|
|
591
|
-
});
|
|
592
|
-
}
|
|
593
|
-
}
|
|
594
|
-
else if (isRunnerBuiltInCommand(builtInCommand)) {
|
|
595
|
-
await runner.handleBuiltinCommand(ctx, builtInCommand);
|
|
596
|
-
}
|
|
597
|
-
log.logEvent("info", "runtime.command.completed", "Command completed", {
|
|
598
|
-
ctx: logCtx,
|
|
599
|
-
fields: { command: builtInCommand.name, durationMs: Date.now() - commandStartedAt },
|
|
600
|
-
});
|
|
601
|
-
}
|
|
602
|
-
catch (err) {
|
|
603
|
-
log.logEvent("warn", "runtime.command.failed", "Command failed", {
|
|
604
|
-
ctx: logCtx,
|
|
605
|
-
fields: {
|
|
606
|
-
command: builtInCommand.name,
|
|
607
|
-
durationMs: Date.now() - commandStartedAt,
|
|
608
|
-
error: errorMessage(err),
|
|
609
|
-
},
|
|
610
|
-
});
|
|
611
|
-
throw err;
|
|
612
|
-
}
|
|
613
|
-
return;
|
|
614
|
-
}
|
|
615
|
-
// Reject an unknown slash command instead of spending a full LLM turn
|
|
616
|
-
// letting the model guess what `/modle` meant. Session commands,
|
|
617
|
-
// skills, and prompt templates are recognized by isKnownSlashCommand.
|
|
618
|
-
if (event.text.trim().startsWith("/") && !runner.isKnownSlashCommand(event.text)) {
|
|
619
|
-
const name = slashCommandName(event.text) ?? "";
|
|
620
|
-
await bot.sendPlain(event.channelId, formatUnknownCommandMessage(name));
|
|
621
|
-
return;
|
|
622
|
-
}
|
|
623
|
-
log.logEvent("info", "agent.turn.started", "Starting turn", {
|
|
624
|
-
ctx: { channelId: event.channelId, userName: event.userName },
|
|
625
|
-
fields: { messageLength: event.text.length, source: _isEvent ? "event" : "message" },
|
|
626
|
-
});
|
|
627
|
-
// A completion wake for a task's job or delegation: verified against the resource's own
|
|
628
|
-
// record before it may reopen the task (see `claimVerifiedWake`). Plain "belongs to task"
|
|
629
|
-
// text in a message never counts — only the producer-created `internalWake` envelope.
|
|
630
|
-
if (event.internalWake) {
|
|
631
|
-
const { kind, resourceId, taskId: wakeTaskId } = event.internalWake;
|
|
632
|
-
const claimed = await claimVerifiedWake(event, options.paths.workspaceDir, kind === "job" ? getJobs().get(event.channelId) : getRuns().get(event.channelId), options.wakeTransitionHooks?.[kind]);
|
|
633
|
-
if (!claimed) {
|
|
634
|
-
log.logWarn("dispatch.wake.unverified", "Unverifiable wake ignored", {
|
|
635
|
-
channelId: event.channelId,
|
|
636
|
-
fields: { kind, resourceId, taskId: wakeTaskId },
|
|
637
|
-
});
|
|
638
|
-
structuredWakeFinalized = true;
|
|
639
|
-
return;
|
|
640
|
-
}
|
|
641
|
-
await claimed.finish();
|
|
642
|
-
structuredWakeFinalized = true;
|
|
643
|
-
// Drop without a turn only when something else is still driving this task (a sibling
|
|
644
|
-
// wake in the same fan-out already reopened it); in every other case nobody else will
|
|
645
|
-
// look at this result, so it still reaches a normal turn.
|
|
646
|
-
if (!claimed.activated && claimed.taskStillDriven)
|
|
647
|
-
return;
|
|
648
|
-
}
|
|
649
|
-
// Verified job/run wakes that activate a task are task steps too. Verification must happen
|
|
650
|
-
// first: routing directly from user-controlled wake text would grant task-only tools.
|
|
651
|
-
taskStep = await prepareTaskStep(event, runner);
|
|
652
|
-
if (taskStep) {
|
|
653
|
-
await baseCtx.close();
|
|
654
|
-
event = { ...event, text: taskStep.brief };
|
|
655
|
-
baseCtx = createDingTalkContext(event, bot, store, "none");
|
|
656
|
-
ctx = muteChannelContext(baseCtx);
|
|
657
|
-
}
|
|
658
|
-
if (!backgroundOnly && !taskStep)
|
|
659
|
-
ctx.primeCard(1500);
|
|
660
|
-
const result = await runner.run(ctx, store);
|
|
661
|
-
if (taskStep)
|
|
662
|
-
await finishTaskStep(event.channelId, taskStep.taskId, bot);
|
|
663
|
-
if (result.stopReason === "aborted" && runner.getTurnStatus().stopRequested) {
|
|
664
|
-
log.logInfoEvent("agent.turn.stopped", "Turn stopped", { channelId: event.channelId });
|
|
665
|
-
}
|
|
666
|
-
}
|
|
667
|
-
catch (err) {
|
|
668
|
-
log.logEvent("error", "agent.turn.failed", "Turn failed", {
|
|
669
|
-
ctx: { channelId: event.channelId, userName: event.userName },
|
|
670
|
-
fields: { error: errorMessage(err) },
|
|
671
|
-
});
|
|
672
|
-
}
|
|
673
|
-
finally {
|
|
674
|
-
await baseCtx?.close().catch((error) => {
|
|
675
|
-
log.logWarn("delivery.close.failed", "Delivery close failed", {
|
|
676
|
-
channelId: event.channelId,
|
|
677
|
-
reason: errorMessage(error),
|
|
678
|
-
});
|
|
679
|
-
});
|
|
680
|
-
if (structuredWakeFinalized)
|
|
681
|
-
await getDurableDispatch()?.markCompleted(event.dispatchId);
|
|
682
|
-
else
|
|
683
|
-
await getDurableDispatch()?.markRetryable(event.dispatchId);
|
|
684
|
-
// Absorbed wakes are chat-level only (no structured claim), so the turn finishing is
|
|
685
|
-
// what finalizes them — exactly as it would have for each on its own.
|
|
686
|
-
for (const absorbedId of absorbedDispatchIds)
|
|
687
|
-
await getDurableDispatch()?.markCompleted(absorbedId);
|
|
688
|
-
runner.endTurn();
|
|
689
|
-
// A finished turn may have written task files; rescan now so `outcome: continue`
|
|
690
|
-
// queues the next step immediately instead of waiting out the current sleep.
|
|
691
|
-
getTaskDriver().nudge?.();
|
|
692
|
-
}
|
|
693
|
-
})();
|
|
694
|
-
activeTasks.add(task);
|
|
695
|
-
try {
|
|
696
|
-
await task;
|
|
697
|
-
}
|
|
698
|
-
finally {
|
|
699
|
-
activeTasks.delete(task);
|
|
700
|
-
}
|
|
701
|
-
},
|
|
702
|
-
};
|
|
703
|
-
return handler;
|
|
704
|
-
}
|
|
705
67
|
export async function createRuntimeContext(options) {
|
|
706
68
|
const startServices = options.startServices ?? true;
|
|
707
69
|
const registerSignalHandlers = options.registerSignalHandlers ?? true;
|
|
@@ -720,7 +82,6 @@ export async function createRuntimeContext(options) {
|
|
|
720
82
|
const channelIndex = createChannelIndex({ workspaceDir: options.paths.workspaceDir });
|
|
721
83
|
let durableDispatch;
|
|
722
84
|
let shuttingDown = false;
|
|
723
|
-
let shutdownPromise = null;
|
|
724
85
|
const archiveIncomingMessage = async (channelId, message, contextLabel) => {
|
|
725
86
|
try {
|
|
726
87
|
await store.logMessage(channelId, message);
|
|
@@ -769,7 +130,7 @@ export async function createRuntimeContext(options) {
|
|
|
769
130
|
const getJobs = () => jobs;
|
|
770
131
|
const getRuns = () => runs;
|
|
771
132
|
const getTaskDriver = () => taskDriver;
|
|
772
|
-
const handler =
|
|
133
|
+
const handler = createTurnHandler({
|
|
773
134
|
options,
|
|
774
135
|
store,
|
|
775
136
|
channelRunners,
|
|
@@ -929,101 +290,22 @@ export async function createRuntimeContext(options) {
|
|
|
929
290
|
notify: (receipt) => bot.sendPlain(receipt.channelId, receipt.text),
|
|
930
291
|
isEnabled: tasksToolEnabled,
|
|
931
292
|
});
|
|
932
|
-
const shutdownWithReason =
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
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: () => {
|
|
937
306
|
shuttingDown = true;
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
durableDispatch?.stop();
|
|
941
|
-
memoryMaintenanceScheduler.stop();
|
|
942
|
-
eventsWatcher.stop();
|
|
943
|
-
runs.stop();
|
|
944
|
-
jobs.stop();
|
|
945
|
-
await bot.stop();
|
|
946
|
-
const runningTasks = Array.from(activeTasks);
|
|
947
|
-
if (runningTasks.length > 0) {
|
|
948
|
-
log.logInfoEvent("runtime.shutdown.waiting", "Waiting for active turns to finish", {
|
|
949
|
-
fields: { activeTurns: runningTasks.length },
|
|
950
|
-
});
|
|
951
|
-
const completed = await waitForTasks(runningTasks, SHUTDOWN_WAIT_MS);
|
|
952
|
-
if (!completed) {
|
|
953
|
-
log.logWarn("runtime.shutdown.grace_exceeded", "Shutdown grace period exceeded; aborting active turns", {
|
|
954
|
-
fields: { waitMs: SHUTDOWN_WAIT_MS },
|
|
955
|
-
});
|
|
956
|
-
const aborts = [];
|
|
957
|
-
for (const [channelId, runner] of channelRunners) {
|
|
958
|
-
if (!runner.isBusy())
|
|
959
|
-
continue;
|
|
960
|
-
runner.requestStop();
|
|
961
|
-
log.logInfoEvent("runtime.shutdown.aborting", "Aborting active turn for shutdown", {
|
|
962
|
-
channelId: channelId,
|
|
963
|
-
});
|
|
964
|
-
aborts.push(runner.abort().catch((err) => {
|
|
965
|
-
log.logWarn("runtime.shutdown.abort_failed", "Turn abort during shutdown failed", {
|
|
966
|
-
channelId: channelId,
|
|
967
|
-
reason: errorMessage(err),
|
|
968
|
-
});
|
|
969
|
-
}));
|
|
970
|
-
}
|
|
971
|
-
await Promise.allSettled(aborts);
|
|
972
|
-
const remainingTasks = Array.from(activeTasks);
|
|
973
|
-
if (remainingTasks.length > 0) {
|
|
974
|
-
const abortedCompleted = await waitForTasks(remainingTasks, SHUTDOWN_ABORT_WAIT_MS);
|
|
975
|
-
if (!abortedCompleted) {
|
|
976
|
-
log.logWarn("runtime.shutdown.forced", "Shutdown forced with turns still active", {
|
|
977
|
-
fields: { activeTurns: remainingTasks.length },
|
|
978
|
-
});
|
|
979
|
-
}
|
|
980
|
-
}
|
|
981
|
-
}
|
|
982
|
-
}
|
|
983
|
-
// Idle runners are disposed (flush memory, unsubscribe, release the SDK session); a
|
|
984
|
-
// still-busy one — its turn already aborted above — is just dropped from the cache and
|
|
985
|
-
// left to unwind on its own as the process exits.
|
|
986
|
-
const disposals = [];
|
|
987
|
-
for (const [channelId, runner] of channelRunners) {
|
|
988
|
-
if (runner.isBusy())
|
|
989
|
-
continue;
|
|
990
|
-
disposals.push(runner.dispose().catch((err) => {
|
|
991
|
-
log.logWarn("runtime.shutdown.dispose_failed", "Runner dispose during shutdown failed", {
|
|
992
|
-
channelId: channelId,
|
|
993
|
-
reason: errorMessage(err),
|
|
994
|
-
});
|
|
995
|
-
}));
|
|
996
|
-
}
|
|
997
|
-
if (disposals.length > 0) {
|
|
998
|
-
log.logInfoEvent("runtime.shutdown.disposing", "Disposing idle channel runners", {
|
|
999
|
-
fields: { count: disposals.length },
|
|
1000
|
-
});
|
|
1001
|
-
const disposed = await waitForTasks(disposals, SHUTDOWN_FLUSH_WAIT_MS);
|
|
1002
|
-
if (!disposed) {
|
|
1003
|
-
log.logWarn("runtime.shutdown.dispose_timeout", "Runner disposal during shutdown timed out", {
|
|
1004
|
-
fields: { waitMs: SHUTDOWN_FLUSH_WAIT_MS },
|
|
1005
|
-
});
|
|
1006
|
-
}
|
|
1007
|
-
}
|
|
1008
|
-
channelRunners.clear();
|
|
1009
|
-
const storageFlushes = [
|
|
1010
|
-
store.close(),
|
|
1011
|
-
// Cancels the debounce timer and lands the last activity times.
|
|
1012
|
-
channelIndex.close(),
|
|
1013
|
-
getUsageLedger().flush?.() ?? Promise.resolve(),
|
|
1014
|
-
flushSecurityLogs(),
|
|
1015
|
-
...(eventsWatcher.flush ? [eventsWatcher.flush()] : []),
|
|
1016
|
-
];
|
|
1017
|
-
const storageFlushed = await waitForTasks(storageFlushes, SHUTDOWN_LOG_FLUSH_WAIT_MS);
|
|
1018
|
-
if (!storageFlushed) {
|
|
1019
|
-
log.logWarn("runtime.shutdown.flush_timeout", "Log flush during shutdown timed out", {
|
|
1020
|
-
fields: { waitMs: SHUTDOWN_LOG_FLUSH_WAIT_MS },
|
|
1021
|
-
});
|
|
1022
|
-
}
|
|
1023
|
-
await waitForTasks([log.flushLogging()], SHUTDOWN_LOG_FLUSH_WAIT_MS);
|
|
1024
|
-
})();
|
|
1025
|
-
return shutdownPromise;
|
|
1026
|
-
};
|
|
307
|
+
},
|
|
308
|
+
});
|
|
1027
309
|
if (registerSignalHandlers) {
|
|
1028
310
|
process.once("SIGINT", () => {
|
|
1029
311
|
void shutdownWithReason("SIGINT").finally(() => {
|