@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,5 +1,4 @@
|
|
|
1
|
-
import type { ChannelEvent } from "../channel/channel-event.js";
|
|
2
|
-
import type { DingTalkBot } from "./dingtalk.js";
|
|
1
|
+
import type { ChannelEvent, ChannelEventSink } from "../channel/channel-event.js";
|
|
3
2
|
type DispatchStatus = "pending" | "queued" | "running" | "exhausted";
|
|
4
3
|
export interface DurableDispatchRecord {
|
|
5
4
|
version: 1;
|
|
@@ -15,7 +14,7 @@ export interface DurableDispatchRecord {
|
|
|
15
14
|
}
|
|
16
15
|
export interface DurableDispatchOptions {
|
|
17
16
|
stateDir: string;
|
|
18
|
-
bot:
|
|
17
|
+
bot: ChannelEventSink;
|
|
19
18
|
leaseMs?: number;
|
|
20
19
|
intervalMs?: number;
|
|
21
20
|
/** Called once, at most, when a dispatch id hits `MAX_DELIVERIES` without ever completing —
|
|
@@ -24,6 +23,11 @@ export interface DurableDispatchOptions {
|
|
|
24
23
|
* caller is expected to notify the channel. */
|
|
25
24
|
onExhausted?: (record: DurableDispatchRecord) => void | Promise<void>;
|
|
26
25
|
}
|
|
26
|
+
/**
|
|
27
|
+
* The notice a channel gets when a wake is given up on (`onExhausted`). It names the source and
|
|
28
|
+
* the record's absolute path — never the wake text, which is a model prompt (spec 053, D2/D6).
|
|
29
|
+
*/
|
|
30
|
+
export declare function renderDispatchExhaustedNotice(record: DurableDispatchRecord, stateDir: string): string;
|
|
27
31
|
/**
|
|
28
32
|
* Tiny file-backed outbox for synthetic work. It intentionally provides
|
|
29
33
|
* at-least-once delivery: a crash after enqueue may replay a task/event, while
|
|
@@ -45,6 +49,14 @@ export declare class DurableDispatchService {
|
|
|
45
49
|
* lease lapses.
|
|
46
50
|
*/
|
|
47
51
|
private readonly running;
|
|
52
|
+
/**
|
|
53
|
+
* Queued dispatch ids folded into another record's turn by `absorbPending`. Each still has its
|
|
54
|
+
* own closure waiting in the channel queue; `markStarted` turns that stale delivery away instead
|
|
55
|
+
* of running the same wake a second time.
|
|
56
|
+
*/
|
|
57
|
+
private readonly absorbed;
|
|
58
|
+
/** Bumped by `discardQueuedClaims`; lets an in-flight `absorbPending` notice that its closures were dropped. */
|
|
59
|
+
private readonly discardEpoch;
|
|
48
60
|
constructor(options: DurableDispatchOptions);
|
|
49
61
|
start(): void;
|
|
50
62
|
/**
|
|
@@ -57,7 +69,34 @@ export declare class DurableDispatchService {
|
|
|
57
69
|
dispatch(event: ChannelEvent): Promise<boolean>;
|
|
58
70
|
/** Reset any in-flight records for a channel so a stop/abort can redeliver on the next tick, not after the lease expires. */
|
|
59
71
|
cancelChannel(channelId: string): Promise<number>;
|
|
60
|
-
|
|
72
|
+
/**
|
|
73
|
+
* `/stop` just cleared the channel's queued closures, synchronously and before any await, so
|
|
74
|
+
* no queued delivery of an absorbed wake survives to consume its stale-delivery mark. Dropping
|
|
75
|
+
* the marks here records that fact at the moment it is true, independent of when (or whether)
|
|
76
|
+
* `cancelChannel` and the turn's own finish run. Not for non-stop failures: there the closures
|
|
77
|
+
* are alive and the marks are what prevents a duplicate run.
|
|
78
|
+
*/
|
|
79
|
+
/** Opaque `/stop` counter; sample it synchronously at admission entry and hand it to `absorbPending`. */
|
|
80
|
+
stopEpoch(channelId: string): number;
|
|
81
|
+
discardQueuedClaims(channelId: string): void;
|
|
82
|
+
/**
|
|
83
|
+
* Claim a dispatch for the turn about to run it. Returns false — run nothing — for a stale
|
|
84
|
+
* delivery of a record another turn already absorbed (see `absorbPending`).
|
|
85
|
+
*/
|
|
86
|
+
markStarted(id: string | undefined): Promise<boolean>;
|
|
87
|
+
/**
|
|
88
|
+
* Fold other not-yet-started dispatches of `channelId` that `accept` into the turn that is
|
|
89
|
+
* starting `primaryId`, oldest first, at most `limit` of them. Each one is claimed exactly as
|
|
90
|
+
* `markStarted` would claim it (running, leased, counted as a delivery), so the caller must
|
|
91
|
+
* finish every returned id with `markCompleted` / `markRetryable` alongside the primary — and a
|
|
92
|
+
* crash mid-turn redelivers each of them on its own, unchanged. Returned events carry their
|
|
93
|
+
* own redelivery notice, like a normal delivery would.
|
|
94
|
+
*/
|
|
95
|
+
absorbPending(channelId: string, primaryId: string, accept: (event: ChannelEvent) => boolean, limit: number,
|
|
96
|
+
/** `stopEpoch` sampled when the caller's admission began; a later `/stop` suppresses the stale-delivery marks. */
|
|
97
|
+
epoch?: number): Promise<ChannelEvent[]>;
|
|
98
|
+
/** Not started anywhere: still waiting for delivery (`pending`) or queued behind the current turn. */
|
|
99
|
+
private isAbsorbable;
|
|
61
100
|
markCompleted(id: string | undefined): Promise<void>;
|
|
62
101
|
/** Release a failed handler's in-process claim without deleting its durable record. Structured
|
|
63
102
|
* wake activation uses this for transient task/job/run persistence failures so the next drain
|
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The durable outbox for synthetic events (job and delegation completions, task wakes, scheduled events):
|
|
3
|
+
* records are written to disk before they enter the in-memory channel queue, leased, retried and
|
|
4
|
+
* redelivered after a crash — at-least-once.
|
|
5
|
+
*/
|
|
1
6
|
import { createHash } from "node:crypto";
|
|
2
7
|
import { readdir, readFile, unlink } from "node:fs/promises";
|
|
3
8
|
import { join } from "node:path";
|
|
@@ -55,6 +60,40 @@ function withRedeliveryNotice(event, deliveries) {
|
|
|
55
60
|
event.text,
|
|
56
61
|
};
|
|
57
62
|
}
|
|
63
|
+
/**
|
|
64
|
+
* What a wake was for, in the user's terms (spec 053, D2). The wake's own `text` is a prompt for
|
|
65
|
+
* the model and its `user` an internal producer tag (`TASK_DRIVER`, `SUBAGENT`, …), so neither
|
|
66
|
+
* may reach the chat; every in-process producer prefixes its text with a `[KIND:id…]` tag, which
|
|
67
|
+
* is what this reads instead.
|
|
68
|
+
*/
|
|
69
|
+
function describeWakeSource(event) {
|
|
70
|
+
const tag = /^\[(TASK_DRIVER|SUBAGENT|JOB|EVENT):([^:\]\s]+)/.exec(event.text);
|
|
71
|
+
const id = tag?.[2];
|
|
72
|
+
switch (tag?.[1]) {
|
|
73
|
+
case "TASK_DRIVER":
|
|
74
|
+
return { label: `任务 \`${id}\` 的一次后台唤醒`, nextStep: `用 \`/tasks show ${id}\` 确认任务状态` };
|
|
75
|
+
case "SUBAGENT":
|
|
76
|
+
return { label: `委派 \`${id}\` 的完成通知`, nextStep: `用 \`/subagents show ${id}\` 查看结果` };
|
|
77
|
+
case "JOB":
|
|
78
|
+
return { label: `后台作业 \`${id}\` 的完成通知`, nextStep: "需要时让我查看这个作业的结果" };
|
|
79
|
+
case "EVENT": {
|
|
80
|
+
const name = id?.replace(/\.json$/, "");
|
|
81
|
+
return { label: `定时事件 \`${name}\` 的一次触发`, nextStep: `用 \`/events history ${name}\` 查看触发记录` };
|
|
82
|
+
}
|
|
83
|
+
default:
|
|
84
|
+
return { label: "一次后台唤醒" };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* The notice a channel gets when a wake is given up on (`onExhausted`). It names the source and
|
|
89
|
+
* the record's absolute path — never the wake text, which is a model prompt (spec 053, D2/D6).
|
|
90
|
+
*/
|
|
91
|
+
export function renderDispatchExhaustedNotice(record, stateDir) {
|
|
92
|
+
const source = describeWakeSource(record.event);
|
|
93
|
+
const where = `排查记录在 \`${recordPath(stateDir, record.id)}\``;
|
|
94
|
+
return (`⚠️ ${source.label}连续 ${record.deliveries} 次未能完成,已停止重试。\n` +
|
|
95
|
+
(source.nextStep ? `${source.nextStep};${where}。` : `${where}。`));
|
|
96
|
+
}
|
|
58
97
|
function dispatchId(event) {
|
|
59
98
|
return createHash("sha256")
|
|
60
99
|
.update(JSON.stringify([event.channelId, event.user, event.ts, event.text, event.conversationId]))
|
|
@@ -105,6 +144,14 @@ export class DurableDispatchService {
|
|
|
105
144
|
* lease lapses.
|
|
106
145
|
*/
|
|
107
146
|
this.running = new Set();
|
|
147
|
+
/**
|
|
148
|
+
* Queued dispatch ids folded into another record's turn by `absorbPending`. Each still has its
|
|
149
|
+
* own closure waiting in the channel queue; `markStarted` turns that stale delivery away instead
|
|
150
|
+
* of running the same wake a second time.
|
|
151
|
+
*/
|
|
152
|
+
this.absorbed = new Map();
|
|
153
|
+
/** Bumped by `discardQueuedClaims`; lets an in-flight `absorbPending` notice that its closures were dropped. */
|
|
154
|
+
this.discardEpoch = new Map();
|
|
108
155
|
this.leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS;
|
|
109
156
|
}
|
|
110
157
|
start() {
|
|
@@ -121,7 +168,7 @@ export class DurableDispatchService {
|
|
|
121
168
|
*/
|
|
122
169
|
drainSafely() {
|
|
123
170
|
this.drainOnce().catch((error) => {
|
|
124
|
-
log.
|
|
171
|
+
log.logWarn("dispatch.drain.failed", "Durable dispatch drain failed", { reason: errorMessage(error) });
|
|
125
172
|
});
|
|
126
173
|
}
|
|
127
174
|
stop() {
|
|
@@ -179,6 +226,8 @@ export class DurableDispatchService {
|
|
|
179
226
|
// Drop the liveness claim too, or the renew branch above would keep this record
|
|
180
227
|
// alive forever and the cancelled turn would never be redelivered.
|
|
181
228
|
this.running.delete(id);
|
|
229
|
+
// `/stop` already dropped the queued closures; the redelivery must not be turned away.
|
|
230
|
+
this.absorbed.delete(id);
|
|
182
231
|
record.leaseExpiresAt = undefined;
|
|
183
232
|
await this.write(record);
|
|
184
233
|
canceled++;
|
|
@@ -186,9 +235,32 @@ export class DurableDispatchService {
|
|
|
186
235
|
}
|
|
187
236
|
return canceled;
|
|
188
237
|
}
|
|
238
|
+
/**
|
|
239
|
+
* `/stop` just cleared the channel's queued closures, synchronously and before any await, so
|
|
240
|
+
* no queued delivery of an absorbed wake survives to consume its stale-delivery mark. Dropping
|
|
241
|
+
* the marks here records that fact at the moment it is true, independent of when (or whether)
|
|
242
|
+
* `cancelChannel` and the turn's own finish run. Not for non-stop failures: there the closures
|
|
243
|
+
* are alive and the marks are what prevents a duplicate run.
|
|
244
|
+
*/
|
|
245
|
+
/** Opaque `/stop` counter; sample it synchronously at admission entry and hand it to `absorbPending`. */
|
|
246
|
+
stopEpoch(channelId) {
|
|
247
|
+
return this.discardEpoch.get(channelId) ?? 0;
|
|
248
|
+
}
|
|
249
|
+
discardQueuedClaims(channelId) {
|
|
250
|
+
this.discardEpoch.set(channelId, (this.discardEpoch.get(channelId) ?? 0) + 1);
|
|
251
|
+
for (const [id, owner] of this.absorbed)
|
|
252
|
+
if (owner === channelId)
|
|
253
|
+
this.absorbed.delete(id);
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Claim a dispatch for the turn about to run it. Returns false — run nothing — for a stale
|
|
257
|
+
* delivery of a record another turn already absorbed (see `absorbPending`).
|
|
258
|
+
*/
|
|
189
259
|
async markStarted(id) {
|
|
190
260
|
if (!id)
|
|
191
|
-
return;
|
|
261
|
+
return true;
|
|
262
|
+
if (this.absorbed.delete(id))
|
|
263
|
+
return false;
|
|
192
264
|
this.running.add(id);
|
|
193
265
|
await this.queue.run(id, async () => {
|
|
194
266
|
const record = await this.read(id);
|
|
@@ -198,6 +270,81 @@ export class DurableDispatchService {
|
|
|
198
270
|
record.leaseExpiresAt = new Date(Date.now() + this.leaseMs).toISOString();
|
|
199
271
|
await this.write(record);
|
|
200
272
|
});
|
|
273
|
+
return true;
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Fold other not-yet-started dispatches of `channelId` that `accept` into the turn that is
|
|
277
|
+
* starting `primaryId`, oldest first, at most `limit` of them. Each one is claimed exactly as
|
|
278
|
+
* `markStarted` would claim it (running, leased, counted as a delivery), so the caller must
|
|
279
|
+
* finish every returned id with `markCompleted` / `markRetryable` alongside the primary — and a
|
|
280
|
+
* crash mid-turn redelivers each of them on its own, unchanged. Returned events carry their
|
|
281
|
+
* own redelivery notice, like a normal delivery would.
|
|
282
|
+
*/
|
|
283
|
+
async absorbPending(channelId, primaryId, accept, limit,
|
|
284
|
+
/** `stopEpoch` sampled when the caller's admission began; a later `/stop` suppresses the stale-delivery marks. */
|
|
285
|
+
epoch = this.stopEpoch(channelId)) {
|
|
286
|
+
if (limit <= 0)
|
|
287
|
+
return [];
|
|
288
|
+
let filenames;
|
|
289
|
+
try {
|
|
290
|
+
filenames = (await readdir(this.options.stateDir)).filter((name) => name.endsWith(".json"));
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
return [];
|
|
294
|
+
}
|
|
295
|
+
const candidates = [];
|
|
296
|
+
for (const filename of filenames) {
|
|
297
|
+
const id = decodeDispatchId(filename.slice(0, -".json".length));
|
|
298
|
+
if (id === primaryId || this.running.has(id))
|
|
299
|
+
continue;
|
|
300
|
+
const record = await this.read(id);
|
|
301
|
+
if (record && this.isAbsorbable(record, channelId, accept))
|
|
302
|
+
candidates.push({ id, createdAt: record.createdAt });
|
|
303
|
+
}
|
|
304
|
+
candidates.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
|
|
305
|
+
const events = [];
|
|
306
|
+
for (const { id } of candidates.slice(0, limit)) {
|
|
307
|
+
try {
|
|
308
|
+
await this.queue.run(id, async () => {
|
|
309
|
+
// Re-checked under the record's own lock: a drain or its own delivery may have moved it.
|
|
310
|
+
const record = await this.read(id);
|
|
311
|
+
if (!record || this.running.has(id) || !this.isAbsorbable(record, channelId, accept))
|
|
312
|
+
return;
|
|
313
|
+
const wasQueued = record.status === "queued";
|
|
314
|
+
if (!wasQueued)
|
|
315
|
+
record.deliveries++;
|
|
316
|
+
record.status = "running";
|
|
317
|
+
record.leaseExpiresAt = new Date(Date.now() + this.leaseMs).toISOString();
|
|
318
|
+
record.nextAttemptAt = undefined;
|
|
319
|
+
await this.write(record);
|
|
320
|
+
// Publish in-process claims only after persistence succeeds. A failed write
|
|
321
|
+
// must leave the original queued delivery / pending drain eligible to run.
|
|
322
|
+
// Unless /stop dropped the closure meanwhile: then there is nothing left to turn away.
|
|
323
|
+
if (wasQueued && this.stopEpoch(channelId) === epoch)
|
|
324
|
+
this.absorbed.set(id, channelId);
|
|
325
|
+
this.running.add(id);
|
|
326
|
+
events.push(withRedeliveryNotice({ ...record.event, dispatchId: record.id }, record.deliveries));
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
catch (error) {
|
|
330
|
+
log.logWarn("dispatch.wake.absorb_failed", "Wake coalescing failed", {
|
|
331
|
+
channelId,
|
|
332
|
+
reason: errorMessage(error),
|
|
333
|
+
fields: { dispatchId: id },
|
|
334
|
+
});
|
|
335
|
+
// Earlier claims still belong to this turn: return them for processing and
|
|
336
|
+
// settlement instead of losing their ids through the caller's catch(() => []).
|
|
337
|
+
break;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
return events;
|
|
341
|
+
}
|
|
342
|
+
/** Not started anywhere: still waiting for delivery (`pending`) or queued behind the current turn. */
|
|
343
|
+
isAbsorbable(record, channelId, accept) {
|
|
344
|
+
return (record.event.channelId === channelId &&
|
|
345
|
+
(record.status === "pending" || record.status === "queued") &&
|
|
346
|
+
record.deliveries < MAX_DELIVERIES &&
|
|
347
|
+
accept(record.event));
|
|
201
348
|
}
|
|
202
349
|
async markCompleted(id) {
|
|
203
350
|
if (!id)
|
|
@@ -283,7 +430,10 @@ export class DurableDispatchService {
|
|
|
283
430
|
await this.options.onExhausted?.(record);
|
|
284
431
|
}
|
|
285
432
|
catch (err) {
|
|
286
|
-
log.
|
|
433
|
+
log.logWarn("dispatch.exhausted_handler.failed", "Exhausted-dispatch handler failed", {
|
|
434
|
+
reason: errorMessage(err),
|
|
435
|
+
fields: { dispatchId: id },
|
|
436
|
+
});
|
|
287
437
|
}
|
|
288
438
|
return;
|
|
289
439
|
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { InboundImage } from "../channel/channel-event.js";
|
|
2
|
+
/**
|
|
3
|
+
* Absolute `InboundImage.path`s → paths relative to the channel directory, for
|
|
4
|
+
* `LoggedMessage.images` (spec 049). `log.jsonl` already stores everything else channel-relative
|
|
5
|
+
* (it lives inside the channel directory itself); an absolute path there would be dead on any
|
|
6
|
+
* machine other than the one that wrote it, and `~/.pipiclaw` itself can move between backup and
|
|
7
|
+
* restore.
|
|
8
|
+
*/
|
|
9
|
+
export declare function relativeImagePaths(workspaceDir: string, channelId: string, images: InboundImage[] | undefined): string[];
|
|
10
|
+
/**
|
|
11
|
+
* Persist one downloaded inbound image under the channel's `inbox/` (spec 049). The runtime owns
|
|
12
|
+
* this, not the transport, because it holds the workspace root; see the doc comment on
|
|
13
|
+
* `DingTalkHandler.persistInboundImage` for the full contract (`mimeType: null` case included).
|
|
14
|
+
*/
|
|
15
|
+
export declare function persistInboundImage(workspaceDir: string, channelId: string, image: {
|
|
16
|
+
data: Buffer;
|
|
17
|
+
mimeType: string | null;
|
|
18
|
+
}): Promise<InboundImage | null>;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Inbound images on the runtime side: persist a downloaded image under the channel's `inbox/`, and
|
|
3
|
+
* map absolute image paths back to channel-relative ones for the message archive.
|
|
4
|
+
*/
|
|
5
|
+
import { mkdir, writeFile } from "fs/promises";
|
|
6
|
+
import { join, relative } from "path";
|
|
7
|
+
import { getChannelDir } from "../channel/channel-paths.js";
|
|
8
|
+
import { extensionForMimeType } from "../dingtalk/inbound-media.js";
|
|
9
|
+
import * as log from "../log.js";
|
|
10
|
+
import { localStampForFilename } from "../shared/local-time.js";
|
|
11
|
+
import { errorMessage } from "../shared/text-utils.js";
|
|
12
|
+
/**
|
|
13
|
+
* Absolute `InboundImage.path`s → paths relative to the channel directory, for
|
|
14
|
+
* `LoggedMessage.images` (spec 049). `log.jsonl` already stores everything else channel-relative
|
|
15
|
+
* (it lives inside the channel directory itself); an absolute path there would be dead on any
|
|
16
|
+
* machine other than the one that wrote it, and `~/.pipiclaw` itself can move between backup and
|
|
17
|
+
* restore.
|
|
18
|
+
*/
|
|
19
|
+
export function relativeImagePaths(workspaceDir, channelId, images) {
|
|
20
|
+
if (!images || images.length === 0)
|
|
21
|
+
return [];
|
|
22
|
+
const channelDir = getChannelDir(workspaceDir, channelId);
|
|
23
|
+
return images.map((image) => relative(channelDir, image.path));
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Persist one downloaded inbound image under the channel's `inbox/` (spec 049). The runtime owns
|
|
27
|
+
* this, not the transport, because it holds the workspace root; see the doc comment on
|
|
28
|
+
* `DingTalkHandler.persistInboundImage` for the full contract (`mimeType: null` case included).
|
|
29
|
+
*/
|
|
30
|
+
export async function persistInboundImage(workspaceDir, channelId, image) {
|
|
31
|
+
try {
|
|
32
|
+
const dir = join(getChannelDir(workspaceDir, channelId), "inbox");
|
|
33
|
+
await mkdir(dir, { recursive: true });
|
|
34
|
+
const extension = extensionForMimeType(image.mimeType);
|
|
35
|
+
const path = join(dir, `image-${localStampForFilename()}-${Math.random().toString(36).slice(2, 8)}.${extension}`);
|
|
36
|
+
await writeFile(path, image.data, { mode: 0o600 });
|
|
37
|
+
return {
|
|
38
|
+
path,
|
|
39
|
+
mimeType: image.mimeType ?? "application/octet-stream",
|
|
40
|
+
byteSize: image.data.byteLength,
|
|
41
|
+
...(image.mimeType === null ? { unsupportedFormat: true } : {}),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
catch (err) {
|
|
45
|
+
log.logWarn("dingtalk.media.persist_failed", "Inbound image persist failed", {
|
|
46
|
+
channelId: channelId,
|
|
47
|
+
reason: errorMessage(err),
|
|
48
|
+
});
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ordered daemon shutdown: stop the schedulers, stop admission, wait for active turns (aborting
|
|
3
|
+
* them past a grace window), dispose idle runners, then flush storage and logs. Idempotent: every
|
|
4
|
+
* call after the first returns the first call's promise.
|
|
5
|
+
*/
|
|
6
|
+
import type { AgentRunner } from "../agent/types.js";
|
|
7
|
+
import type { ChannelIndex } from "../channel/channel-index.js";
|
|
8
|
+
import type { ChannelStore } from "../channel/store.js";
|
|
9
|
+
export interface ShutdownDeps {
|
|
10
|
+
taskDriver: {
|
|
11
|
+
stop(): void;
|
|
12
|
+
};
|
|
13
|
+
getDurableDispatch: () => {
|
|
14
|
+
stop(): void;
|
|
15
|
+
} | undefined;
|
|
16
|
+
memoryMaintenanceScheduler: {
|
|
17
|
+
stop(): void;
|
|
18
|
+
};
|
|
19
|
+
eventsWatcher: {
|
|
20
|
+
stop(): void;
|
|
21
|
+
flush?(): Promise<void>;
|
|
22
|
+
};
|
|
23
|
+
runs: {
|
|
24
|
+
stop(): void;
|
|
25
|
+
};
|
|
26
|
+
jobs: {
|
|
27
|
+
stop(): void;
|
|
28
|
+
};
|
|
29
|
+
bot: {
|
|
30
|
+
stop(): Promise<void>;
|
|
31
|
+
};
|
|
32
|
+
store: ChannelStore;
|
|
33
|
+
channelIndex: ChannelIndex;
|
|
34
|
+
channelRunners: Map<string, AgentRunner>;
|
|
35
|
+
activeTasks: Set<Promise<void>>;
|
|
36
|
+
/** Flips the runtime's `isShuttingDown()` the moment shutdown begins. */
|
|
37
|
+
markShuttingDown: () => void;
|
|
38
|
+
}
|
|
39
|
+
export declare function createShutdown(deps: ShutdownDeps): (reason?: NodeJS.Signals | "manual") => Promise<void>;
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import * as log from "../log.js";
|
|
2
|
+
import { flushSecurityLogs } from "../security/logger.js";
|
|
3
|
+
import { errorMessage } from "../shared/text-utils.js";
|
|
4
|
+
import { getUsageLedger } from "../usage/ledger.js";
|
|
5
|
+
const SHUTDOWN_WAIT_MS = 15000;
|
|
6
|
+
const SHUTDOWN_FLUSH_WAIT_MS = 45000;
|
|
7
|
+
const SHUTDOWN_ABORT_WAIT_MS = 5000;
|
|
8
|
+
const SHUTDOWN_LOG_FLUSH_WAIT_MS = 10_000;
|
|
9
|
+
function waitForTasks(tasks, timeoutMs) {
|
|
10
|
+
if (tasks.length === 0) {
|
|
11
|
+
return Promise.resolve(true);
|
|
12
|
+
}
|
|
13
|
+
return new Promise((resolve) => {
|
|
14
|
+
const timer = setTimeout(() => resolve(false), timeoutMs);
|
|
15
|
+
timer.unref?.();
|
|
16
|
+
void Promise.allSettled(tasks).then(() => {
|
|
17
|
+
clearTimeout(timer);
|
|
18
|
+
resolve(true);
|
|
19
|
+
});
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
export function createShutdown(deps) {
|
|
23
|
+
const { taskDriver, memoryMaintenanceScheduler, eventsWatcher, runs, jobs, bot, store, channelIndex, channelRunners, activeTasks, } = deps;
|
|
24
|
+
let shutdownPromise = null;
|
|
25
|
+
return async (reason = "manual") => {
|
|
26
|
+
if (shutdownPromise) {
|
|
27
|
+
return shutdownPromise;
|
|
28
|
+
}
|
|
29
|
+
shutdownPromise = (async () => {
|
|
30
|
+
deps.markShuttingDown();
|
|
31
|
+
log.logInfoEvent("runtime.shutdown.started", "Shutting down", { fields: { reason } });
|
|
32
|
+
taskDriver.stop();
|
|
33
|
+
deps.getDurableDispatch()?.stop();
|
|
34
|
+
memoryMaintenanceScheduler.stop();
|
|
35
|
+
eventsWatcher.stop();
|
|
36
|
+
runs.stop();
|
|
37
|
+
jobs.stop();
|
|
38
|
+
await bot.stop();
|
|
39
|
+
const runningTasks = Array.from(activeTasks);
|
|
40
|
+
if (runningTasks.length > 0) {
|
|
41
|
+
log.logInfoEvent("runtime.shutdown.waiting", "Waiting for active turns to finish", {
|
|
42
|
+
fields: { activeTurns: runningTasks.length },
|
|
43
|
+
});
|
|
44
|
+
const completed = await waitForTasks(runningTasks, SHUTDOWN_WAIT_MS);
|
|
45
|
+
if (!completed) {
|
|
46
|
+
log.logWarn("runtime.shutdown.grace_exceeded", "Shutdown grace period exceeded; aborting active turns", {
|
|
47
|
+
fields: { waitMs: SHUTDOWN_WAIT_MS },
|
|
48
|
+
});
|
|
49
|
+
const aborts = [];
|
|
50
|
+
for (const [channelId, runner] of channelRunners) {
|
|
51
|
+
if (!runner.isBusy())
|
|
52
|
+
continue;
|
|
53
|
+
runner.requestStop();
|
|
54
|
+
log.logInfoEvent("runtime.shutdown.aborting", "Aborting active turn for shutdown", {
|
|
55
|
+
channelId: channelId,
|
|
56
|
+
});
|
|
57
|
+
aborts.push(runner.abort().catch((err) => {
|
|
58
|
+
log.logWarn("runtime.shutdown.abort_failed", "Turn abort during shutdown failed", {
|
|
59
|
+
channelId: channelId,
|
|
60
|
+
reason: errorMessage(err),
|
|
61
|
+
});
|
|
62
|
+
}));
|
|
63
|
+
}
|
|
64
|
+
await Promise.allSettled(aborts);
|
|
65
|
+
const remainingTasks = Array.from(activeTasks);
|
|
66
|
+
if (remainingTasks.length > 0) {
|
|
67
|
+
const abortedCompleted = await waitForTasks(remainingTasks, SHUTDOWN_ABORT_WAIT_MS);
|
|
68
|
+
if (!abortedCompleted) {
|
|
69
|
+
log.logWarn("runtime.shutdown.forced", "Shutdown forced with turns still active", {
|
|
70
|
+
fields: { activeTurns: remainingTasks.length },
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
// Idle runners are disposed (flush memory, unsubscribe, release the SDK session); a
|
|
77
|
+
// still-busy one — its turn already aborted above — is just dropped from the cache and
|
|
78
|
+
// left to unwind on its own as the process exits.
|
|
79
|
+
const disposals = [];
|
|
80
|
+
for (const [channelId, runner] of channelRunners) {
|
|
81
|
+
if (runner.isBusy())
|
|
82
|
+
continue;
|
|
83
|
+
disposals.push(runner.dispose().catch((err) => {
|
|
84
|
+
log.logWarn("runtime.shutdown.dispose_failed", "Runner dispose during shutdown failed", {
|
|
85
|
+
channelId: channelId,
|
|
86
|
+
reason: errorMessage(err),
|
|
87
|
+
});
|
|
88
|
+
}));
|
|
89
|
+
}
|
|
90
|
+
if (disposals.length > 0) {
|
|
91
|
+
log.logInfoEvent("runtime.shutdown.disposing", "Disposing idle channel runners", {
|
|
92
|
+
fields: { count: disposals.length },
|
|
93
|
+
});
|
|
94
|
+
const disposed = await waitForTasks(disposals, SHUTDOWN_FLUSH_WAIT_MS);
|
|
95
|
+
if (!disposed) {
|
|
96
|
+
log.logWarn("runtime.shutdown.dispose_timeout", "Runner disposal during shutdown timed out", {
|
|
97
|
+
fields: { waitMs: SHUTDOWN_FLUSH_WAIT_MS },
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
channelRunners.clear();
|
|
102
|
+
const storageFlushes = [
|
|
103
|
+
store.close(),
|
|
104
|
+
// Cancels the debounce timer and lands the last activity times.
|
|
105
|
+
channelIndex.close(),
|
|
106
|
+
getUsageLedger().flush?.() ?? Promise.resolve(),
|
|
107
|
+
flushSecurityLogs(),
|
|
108
|
+
...(eventsWatcher.flush ? [eventsWatcher.flush()] : []),
|
|
109
|
+
];
|
|
110
|
+
const storageFlushed = await waitForTasks(storageFlushes, SHUTDOWN_LOG_FLUSH_WAIT_MS);
|
|
111
|
+
if (!storageFlushed) {
|
|
112
|
+
log.logWarn("runtime.shutdown.flush_timeout", "Log flush during shutdown timed out", {
|
|
113
|
+
fields: { waitMs: SHUTDOWN_LOG_FLUSH_WAIT_MS },
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
await waitForTasks([log.flushLogging()], SHUTDOWN_LOG_FLUSH_WAIT_MS);
|
|
117
|
+
})();
|
|
118
|
+
return shutdownPromise;
|
|
119
|
+
};
|
|
120
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `/stop` watchdog: a stopped turn that never ends is force-released after a grace window, so
|
|
3
|
+
* the channel does not keep reporting "a turn is already running".
|
|
4
|
+
*/
|
|
5
|
+
import type { AgentRunner } from "../agent/types.js";
|
|
6
|
+
/**
|
|
7
|
+
* Watchdog for `/stop`: release the channel if the stopped turn has not ended
|
|
8
|
+
* once the grace window elapses. Returns true when it had to force the release.
|
|
9
|
+
*/
|
|
10
|
+
export declare function forceEndStuckTurnAfterStop(input: {
|
|
11
|
+
channelId: string;
|
|
12
|
+
runner: AgentRunner;
|
|
13
|
+
graceMs?: number;
|
|
14
|
+
pollMs?: number;
|
|
15
|
+
notify?: (text: string) => Promise<unknown>;
|
|
16
|
+
}): Promise<boolean>;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `/stop` watchdog: a stopped turn that never ends is force-released after a grace window, so
|
|
3
|
+
* the channel does not keep reporting "a turn is already running".
|
|
4
|
+
*/
|
|
5
|
+
import { sleepUnref } from "../shared/with-timeout.js";
|
|
6
|
+
/**
|
|
7
|
+
* How long `/stop` waits for the turn to actually end before force-releasing it.
|
|
8
|
+
* `requestStop` + `abort` only reach the agent loop; a turn wedged in its
|
|
9
|
+
* epilogue (delivery drain, session-resource reload, memory flush) ignores both
|
|
10
|
+
* and would otherwise keep the channel reporting "已有回合在运行" indefinitely.
|
|
11
|
+
*/
|
|
12
|
+
const STOP_FORCE_END_GRACE_MS = 15_000;
|
|
13
|
+
const STOP_FORCE_END_POLL_MS = 250;
|
|
14
|
+
/**
|
|
15
|
+
* Watchdog for `/stop`: release the channel if the stopped turn has not ended
|
|
16
|
+
* once the grace window elapses. Returns true when it had to force the release.
|
|
17
|
+
*/
|
|
18
|
+
export async function forceEndStuckTurnAfterStop(input) {
|
|
19
|
+
const graceMs = input.graceMs ?? STOP_FORCE_END_GRACE_MS;
|
|
20
|
+
const pollMs = input.pollMs ?? STOP_FORCE_END_POLL_MS;
|
|
21
|
+
const deadline = Date.now() + graceMs;
|
|
22
|
+
while (input.runner.isBusy() && Date.now() < deadline) {
|
|
23
|
+
await sleepUnref(Math.min(pollMs, Math.max(1, deadline - Date.now())));
|
|
24
|
+
}
|
|
25
|
+
if (!input.runner.forceEndTurn(`/stop did not take effect within ${graceMs}ms`)) {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
await input
|
|
29
|
+
.notify?.(`⚠️ 上一个回合的收尾卡住了,已强制结束以释放会话(后台清理仍在继续)。现在可以正常发消息或使用 \`/new\`、\`/model\`。`)
|
|
30
|
+
.catch(() => undefined);
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { ChannelEvent } from "../channel/channel-event.js";
|
|
2
2
|
import { type DiscoverOptions } from "../channel/channel-index.js";
|
|
3
|
-
import { type PipiclawTaskDriverSettings } from "../settings.js";
|
|
4
|
-
import { type
|
|
3
|
+
import { type PipiclawTaskDriverSettings } from "../config/settings.js";
|
|
4
|
+
import { type BudgetBreach } from "../tasks/budget.js";
|
|
5
|
+
import { type TaskLedgerEntry } from "../tasks/contract.js";
|
|
5
6
|
export interface TaskDriverOptions {
|
|
6
7
|
workspaceDir: string;
|
|
7
8
|
getKnownChannelIds?: () => Iterable<string>;
|
|
@@ -29,9 +30,10 @@ export declare function createTaskDriverEvent(channelId: string, entry: TaskLedg
|
|
|
29
30
|
/**
|
|
30
31
|
* The deterministic receipt a runtime stop produces (spec 051, D11). It is delivered directly,
|
|
31
32
|
* without opening a model turn: the user needs to know their task stopped, and spending an LLM
|
|
32
|
-
* call to phrase that is exactly the kind of cost this design removes.
|
|
33
|
+
* call to phrase that is exactly the kind of cost this design removes. A budget stop also says
|
|
34
|
+
* how to resume with more of the dimension that ran out (spec 053, D6).
|
|
33
35
|
*/
|
|
34
|
-
export declare function taskStopReceipt(channelId: string, entry: TaskLedgerEntry, reason: string, nowMs: number): ChannelEvent;
|
|
36
|
+
export declare function taskStopReceipt(channelId: string, entry: TaskLedgerEntry, reason: string, nowMs: number, breach?: BudgetBreach): ChannelEvent;
|
|
35
37
|
/**
|
|
36
38
|
* Native, ticket-driven scheduler for the persistent task ledger (spec 051, D9; spec 052).
|
|
37
39
|
*
|