@oyasmi/pipiclaw 0.9.3-beta.3 → 0.9.3-beta.5
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/README.en.md +12 -12
- package/README.md +12 -12
- package/dist/agent/channel-runner.d.ts +4 -18
- package/dist/agent/channel-runner.js +26 -121
- package/dist/agent/context-budget.js +1 -1
- package/dist/agent/job-manager.d.ts +11 -17
- package/dist/agent/job-manager.js +77 -67
- package/dist/agent/prompt/builder.js +1 -17
- package/dist/agent/prompt/manifest.d.ts +0 -1
- package/dist/agent/prompt/manifest.js +2 -2
- package/dist/agent/prompt/sections.js +0 -9
- package/dist/agent/prompt/types.d.ts +2 -18
- package/dist/agent/prompt/types.js +1 -1
- package/dist/agent/runner-factory.d.ts +4 -0
- package/dist/agent/session-adapter.d.ts +19 -0
- package/dist/agent/session-adapter.js +77 -0
- package/dist/app-services.d.ts +18 -0
- package/dist/app-services.js +43 -0
- package/dist/channel/channel-context.d.ts +2 -2
- package/dist/channel/channel-context.js +2 -2
- package/dist/channel/channel-event.d.ts +3 -3
- package/dist/{runtime → events}/events.d.ts +1 -1
- package/dist/memory/journal.js +1 -1
- package/dist/memory/maintenance-gates.d.ts +0 -3
- package/dist/memory/maintenance-gates.js +2 -2
- package/dist/memory/maintenance-migration.d.ts +5 -0
- package/dist/memory/maintenance-migration.js +91 -0
- package/dist/memory/maintenance-state.js +5 -44
- package/dist/memory/migrate.js +1 -1
- package/dist/memory/reflect-job.d.ts +1 -9
- package/dist/memory/reflect-job.js +1 -3
- package/dist/memory/reflect.js +1 -1
- package/dist/memory/session-corpus.js +1 -1
- package/dist/memory/store.js +1 -1
- package/dist/models/auth-cli.js +1 -1
- package/dist/playbooks/agent-delegation.md +15 -11
- package/dist/playbooks/background-jobs.md +1 -1
- package/dist/playbooks/runtime-orientation.md +2 -0
- package/dist/playbooks/task-loop.md +1 -1
- package/dist/runtime/bootstrap.d.ts +5 -15
- package/dist/runtime/bootstrap.js +44 -65
- package/dist/runtime/delivery.d.ts +1 -2
- package/dist/runtime/delivery.js +57 -62
- package/dist/runtime/dingtalk.d.ts +15 -8
- package/dist/runtime/dingtalk.js +101 -35
- package/dist/runtime/subagent-commands.d.ts +2 -1
- package/dist/runtime/subagent-commands.js +10 -12
- package/dist/runtime/task-wake.d.ts +4 -5
- package/dist/runtime/task-wake.js +2 -12
- package/dist/security/types.d.ts +7 -0
- package/dist/security/types.js +16 -1
- package/dist/settings.d.ts +8 -0
- package/dist/settings.js +24 -1
- package/dist/shared/exact-keys.d.ts +13 -0
- package/dist/shared/exact-keys.js +1 -0
- package/dist/shared/format.d.ts +20 -0
- package/dist/shared/format.js +64 -0
- package/dist/shared/{fs-utils.d.ts → os.d.ts} +6 -0
- package/dist/shared/{fs-utils.js → os.js} +8 -0
- package/dist/subagents/discovery.d.ts +16 -3
- package/dist/subagents/discovery.js +13 -9
- package/dist/subagents/external/claude-code.js +3 -1
- package/dist/subagents/external/harness.d.ts +4 -2
- package/dist/subagents/external/run.d.ts +2 -1
- package/dist/subagents/external/run.js +13 -5
- package/dist/subagents/external/settlement.js +10 -5
- package/dist/subagents/format.d.ts +1 -1
- package/dist/subagents/format.js +1 -1
- package/dist/subagents/runs.d.ts +13 -12
- package/dist/subagents/runs.js +109 -91
- package/dist/subagents/tool.d.ts +7 -7
- package/dist/subagents/tool.js +11 -11
- package/dist/tasks/brief.js +1 -0
- package/dist/tools/command-optimizer.js +1 -1
- package/dist/tools/config.d.ts +7 -0
- package/dist/tools/config.js +16 -1
- package/dist/tools/event-manage.d.ts +1 -1
- package/dist/tools/event-manage.js +3 -3
- package/dist/tools/grep.js +1 -1
- package/dist/tools/index.d.ts +4 -0
- package/dist/tools/index.js +4 -2
- package/dist/tools/job.js +1 -1
- package/dist/tools/read.js +1 -1
- package/dist/tools/registry.d.ts +3 -3
- package/dist/tools/registry.js +18 -56
- package/dist/tools/skill.js +1 -1
- package/dist/tools/subagent-manage.d.ts +2 -0
- package/dist/tools/subagent-manage.js +7 -7
- package/dist/tools/subagent-tool-names.d.ts +2 -2
- package/dist/tools/subagent-tool-names.js +2 -2
- package/dist/tools/task-manage/shared.js +4 -9
- package/dist/tools/task-manage/types.d.ts +4 -0
- package/dist/tui/app.js +22 -7
- package/dist/web/config.js +1 -1
- package/examples/sub-agents/README.md +65 -81
- package/examples/sub-agents/agents/claude-high.md +23 -0
- package/examples/sub-agents/agents/claude-main.md +23 -0
- package/examples/sub-agents/agents/codex-flash.md +23 -0
- package/examples/sub-agents/agents/codex-high.md +23 -0
- package/examples/sub-agents/agents/codex-main.md +23 -0
- package/examples/sub-agents/agents/glm-flash.md +23 -0
- package/examples/sub-agents/agents/glm-high.md +23 -0
- package/package.json +2 -1
- package/dist/shared/duration.d.ts +0 -2
- package/dist/shared/duration.js +0 -7
- package/dist/shared/file-stamp.d.ts +0 -10
- package/dist/shared/file-stamp.js +0 -19
- package/dist/shared/numeric.d.ts +0 -7
- package/dist/shared/numeric.js +0 -19
- package/dist/shared/shell-escape.d.ts +0 -5
- package/dist/shared/shell-escape.js +0 -7
- package/dist/shared/token-estimate.d.ts +0 -1
- package/dist/shared/token-estimate.js +0 -19
- /package/dist/{runtime → events}/event-commands.d.ts +0 -0
- /package/dist/{runtime → events}/event-commands.js +0 -0
- /package/dist/{runtime → events}/event-validation.d.ts +0 -0
- /package/dist/{runtime → events}/event-validation.js +0 -0
- /package/dist/{runtime → events}/events.js +0 -0
- /package/examples/sub-agents/{builder-hard.md → roles/builder-hard.md} +0 -0
- /package/examples/sub-agents/{builder.md → roles/builder.md} +0 -0
- /package/examples/sub-agents/{explorer.md → roles/explorer.md} +0 -0
- /package/examples/sub-agents/{git-committer.md → roles/git-committer.md} +0 -0
- /package/examples/sub-agents/{planner.md → roles/planner.md} +0 -0
- /package/examples/sub-agents/{reviewer.md → roles/reviewer.md} +0 -0
- /package/examples/sub-agents/{verifier.md → roles/verifier.md} +0 -0
- /package/examples/sub-agents/{worker.md → roles/worker.md} +0 -0
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { mkdir, writeFile } from "fs/promises";
|
|
2
2
|
import { join, relative } from "path";
|
|
3
|
-
import {
|
|
3
|
+
import { createJobRuntime } from "../agent/job-manager.js";
|
|
4
4
|
import { loadDetachedMaintenanceContext } from "../agent/maintenance-context.js";
|
|
5
5
|
import { createRunner } from "../agent/runner-factory.js";
|
|
6
6
|
import { renderStatus } from "../agent/status-render.js";
|
|
7
7
|
import { scanWorkspaceForInterruptedTurns } from "../agent/turn-recovery.js";
|
|
8
|
+
import { prepareAppServices } from "../app-services.js";
|
|
8
9
|
import { createFreshActiveSession } from "../channel/active-session-store.js";
|
|
9
10
|
import { muteChannelContext } from "../channel/channel-context.js";
|
|
10
11
|
import { createChannelIndex } from "../channel/channel-index.js";
|
|
@@ -12,37 +13,36 @@ import { ensureChannelDir, getChannelDir } from "../channel/channel-paths.js";
|
|
|
12
13
|
import { resolveProjectScope } from "../channel/project-scope-store.js";
|
|
13
14
|
import { ChannelStore } from "../channel/store.js";
|
|
14
15
|
import { BUILT_IN_COMMANDS, formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../commands/catalog.js";
|
|
16
|
+
import { handleEventsCommand as runEventsCommand } from "../events/event-commands.js";
|
|
17
|
+
import { createEventsWatcher } from "../events/events.js";
|
|
15
18
|
import { createExecutor } from "../executor.js";
|
|
16
19
|
import * as log from "../log.js";
|
|
20
|
+
import { migrateMemoryMaintenanceStates } from "../memory/maintenance-migration.js";
|
|
17
21
|
import { MemoryMaintenanceScheduler } from "../memory/scheduler.js";
|
|
18
22
|
import { defaultModel } from "../models/utils.js";
|
|
19
23
|
import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
|
|
20
24
|
import { flushSecurityLogs } from "../security/logger.js";
|
|
21
25
|
import { resolveProjectAccessPolicy } from "../security/project-scope.js";
|
|
22
26
|
import { PipiclawSettingsManager, TASK_DRIVER_SETTINGS } from "../settings.js";
|
|
23
|
-
import {
|
|
24
|
-
import { fileStamp } from "../shared/file-stamp.js";
|
|
27
|
+
import { fileStamp } from "../shared/format.js";
|
|
25
28
|
import { localStampForFilename } from "../shared/local-time.js";
|
|
26
29
|
import { errorMessage } from "../shared/text-utils.js";
|
|
27
30
|
import { sleepUnref } from "../shared/with-timeout.js";
|
|
28
31
|
import { loadDetachedSubAgentDiscovery } from "../subagents/detached-discovery.js";
|
|
29
|
-
import {
|
|
32
|
+
import { createSubAgentRuntime } from "../subagents/runs.js";
|
|
30
33
|
import { buildTaskStepBrief } from "../tasks/brief.js";
|
|
31
34
|
import { readActiveTasks } from "../tasks/ledger.js";
|
|
32
35
|
import { consumeTaskNotice } from "../tasks/steer.js";
|
|
33
36
|
import { readStoredTask } from "../tasks/store.js";
|
|
34
|
-
import { getToolsConfigPath, loadToolsConfig
|
|
37
|
+
import { getToolsConfigPath, loadToolsConfig } from "../tools/config.js";
|
|
35
38
|
import { getUsageLedger } from "../usage/ledger.js";
|
|
36
39
|
import { parseUsageMode, renderUsageReport } from "../usage/render.js";
|
|
37
40
|
import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, loadConfig, parseArgs, printBootstrapSummary, readCliVersion, } from "./app-home.js";
|
|
38
41
|
import { createDingTalkContext } from "./delivery.js";
|
|
39
42
|
import { DingTalkBot, } from "./dingtalk.js";
|
|
40
43
|
import { DurableDispatchService } from "./durable-dispatch.js";
|
|
41
|
-
import { handleEventsCommand as runEventsCommand } from "./event-commands.js";
|
|
42
|
-
import { createEventsWatcher } from "./events.js";
|
|
43
44
|
import { extensionForMimeType } from "./inbound-media.js";
|
|
44
45
|
import { handleProjectCommand as runProjectCommand } from "./project-commands.js";
|
|
45
|
-
import { installLlmProxy } from "./proxy.js";
|
|
46
46
|
import { handleSkillsCommand as runSkillsCommand } from "./skill-commands.js";
|
|
47
47
|
import { renderRunNotice, handleSubagentsCommand as runSubagentsCommand } from "./subagent-commands.js";
|
|
48
48
|
import { pauseTask, handleTasksCommand as runTasksCommand } from "./task-commands.js";
|
|
@@ -149,7 +149,7 @@ export async function forceEndStuckTurnAfterStop(input) {
|
|
|
149
149
|
return true;
|
|
150
150
|
}
|
|
151
151
|
function createDingTalkHandler(deps) {
|
|
152
|
-
const { options, store, channelRunners, sessionResetChains, activeTasks, stopWatchdogs, channelIndex, archiveIncomingMessage, getRunner, cliVersion, startedAt, isShuttingDown, getDurableDispatch,
|
|
152
|
+
const { options, store, channelRunners, sessionResetChains, activeTasks, stopWatchdogs, channelIndex, archiveIncomingMessage, getRunner, cliVersion, startedAt, isShuttingDown, getDurableDispatch, getJobs, getRuns, getTaskDriver, } = deps;
|
|
153
153
|
/**
|
|
154
154
|
* Turn a `[TASK_DRIVER:<id>]` dispatch into a task loop step: bind the runner to the task
|
|
155
155
|
* cycle's own session and replace the wake text with the step brief. Returns `undefined` for
|
|
@@ -369,6 +369,7 @@ function createDingTalkHandler(deps) {
|
|
|
369
369
|
case "subagents":
|
|
370
370
|
return runSubagentsCommand({
|
|
371
371
|
args,
|
|
372
|
+
runManager: getRuns().get(event.channelId),
|
|
372
373
|
channelId: event.channelId,
|
|
373
374
|
discovery: channelRunners.get(event.channelId)?.getSubAgentDiscoverySnapshot(),
|
|
374
375
|
// `roles` needs a role directory even for a channel that has never spoken this boot —
|
|
@@ -388,11 +389,12 @@ function createDingTalkHandler(deps) {
|
|
|
388
389
|
actor: "dingtalk-command",
|
|
389
390
|
isBusy: () => channelRunners.get(event.channelId)?.isBusy() ?? false,
|
|
390
391
|
listActiveBlockers: () => [
|
|
391
|
-
...
|
|
392
|
+
...getRuns()
|
|
393
|
+
.get(event.channelId)
|
|
392
394
|
.list()
|
|
393
395
|
.filter((record) => record.status === "running")
|
|
394
396
|
.map((record) => `subagent run \`${record.runId}\` (${record.agent})`),
|
|
395
|
-
...
|
|
397
|
+
...getJobs().runningLines(event.channelId),
|
|
396
398
|
],
|
|
397
399
|
// D4.2: dispose the cached runner so the next access rebuilds it under the new scope.
|
|
398
400
|
// The active-session ref is untouched — same session, new project root.
|
|
@@ -512,6 +514,7 @@ function createDingTalkHandler(deps) {
|
|
|
512
514
|
await getDurableDispatch()?.markStarted(event.dispatchId);
|
|
513
515
|
let structuredWakeFinalized = event.internalWake === undefined;
|
|
514
516
|
const task = (async () => {
|
|
517
|
+
let baseCtx;
|
|
515
518
|
try {
|
|
516
519
|
// Computed before archiving so a command's own text can be excluded from
|
|
517
520
|
// memory-extraction input (review 2026-08-24 §1.2): it is control-plane
|
|
@@ -528,16 +531,15 @@ function createDingTalkHandler(deps) {
|
|
|
528
531
|
images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
|
|
529
532
|
}, "user message");
|
|
530
533
|
// Background wakes deliver their result, not their process: no progress card, no
|
|
531
|
-
// thinking stream, nothing to
|
|
532
|
-
//
|
|
533
|
-
|
|
534
|
-
const backgroundOnly = Boolean(_isEvent) && event.presentation !== "awaited";
|
|
534
|
+
// thinking stream, nothing to clean up when a check-in ends `[SILENT]`.
|
|
535
|
+
// Awaited completions deliver their result too, without opening another progress card.
|
|
536
|
+
const backgroundOnly = Boolean(_isEvent);
|
|
535
537
|
// Spec 051, D3: a task-driver dispatch runs as a *task step* — in the task cycle's
|
|
536
538
|
// own session, with a brief instead of the wake text, and silent unless the step
|
|
537
539
|
// asked for a notify. Everything below (busy state, /stop, delivery) is unchanged;
|
|
538
540
|
// only which session the turn is bound to, and what reaches the channel, differ.
|
|
539
541
|
let taskStep;
|
|
540
|
-
|
|
542
|
+
baseCtx = createDingTalkContext(event, bot, store, backgroundOnly ? "none" : undefined);
|
|
541
543
|
let ctx = baseCtx;
|
|
542
544
|
if (builtInCommand) {
|
|
543
545
|
const commandStartedAt = Date.now();
|
|
@@ -590,9 +592,6 @@ function createDingTalkHandler(deps) {
|
|
|
590
592
|
ctx: { channelId: event.channelId, userName: event.userName },
|
|
591
593
|
fields: { messageLength: event.text.length, source: _isEvent ? "event" : "message" },
|
|
592
594
|
});
|
|
593
|
-
if (!backgroundOnly) {
|
|
594
|
-
ctx.primeCard(350);
|
|
595
|
-
}
|
|
596
595
|
// Both wake formats below carry an unauthenticated claim in plain text: anything
|
|
597
596
|
// that can put a message on this channel can *write* "[JOB:x] ... belongs to task
|
|
598
597
|
// y." or "[SUBAGENT:x] ... belongs to task y." — including another user, or an
|
|
@@ -608,7 +607,7 @@ function createDingTalkHandler(deps) {
|
|
|
608
607
|
: jobTextMatch;
|
|
609
608
|
if (jobMatch) {
|
|
610
609
|
const [, jobId, jobTaskId] = jobMatch;
|
|
611
|
-
const claimed = await claimVerifiedJobWake(event, options.paths.workspaceDir,
|
|
610
|
+
const claimed = await claimVerifiedJobWake(event, options.paths.workspaceDir, getJobs().get(event.channelId), options.wakeTransitionHooks?.job);
|
|
612
611
|
if (claimed) {
|
|
613
612
|
await claimed.finish();
|
|
614
613
|
structuredWakeFinalized = true;
|
|
@@ -636,7 +635,7 @@ function createDingTalkHandler(deps) {
|
|
|
636
635
|
: delegationTextMatch;
|
|
637
636
|
if (delegationMatch) {
|
|
638
637
|
const [, runId, delegationTaskId] = delegationMatch;
|
|
639
|
-
const claimed = await claimVerifiedDelegationWake(event, options.paths.workspaceDir, options.wakeTransitionHooks?.subagent);
|
|
638
|
+
const claimed = await claimVerifiedDelegationWake(event, options.paths.workspaceDir, getRuns().get(event.channelId), options.wakeTransitionHooks?.subagent);
|
|
640
639
|
if (claimed) {
|
|
641
640
|
await claimed.finish();
|
|
642
641
|
structuredWakeFinalized = true;
|
|
@@ -657,10 +656,13 @@ function createDingTalkHandler(deps) {
|
|
|
657
656
|
// first: routing directly from user-controlled wake text would grant task-only tools.
|
|
658
657
|
taskStep = await prepareTaskStep(event, runner);
|
|
659
658
|
if (taskStep) {
|
|
659
|
+
await baseCtx.close();
|
|
660
660
|
event = { ...event, text: taskStep.brief };
|
|
661
|
-
baseCtx = createDingTalkContext(event, bot, store,
|
|
661
|
+
baseCtx = createDingTalkContext(event, bot, store, "none");
|
|
662
662
|
ctx = muteChannelContext(baseCtx);
|
|
663
663
|
}
|
|
664
|
+
if (!backgroundOnly && !taskStep)
|
|
665
|
+
ctx.primeCard(1500);
|
|
664
666
|
const result = await runner.run(ctx, store);
|
|
665
667
|
if (taskStep)
|
|
666
668
|
await finishTaskStep(event.channelId, taskStep.taskId, bot);
|
|
@@ -675,6 +677,9 @@ function createDingTalkHandler(deps) {
|
|
|
675
677
|
});
|
|
676
678
|
}
|
|
677
679
|
finally {
|
|
680
|
+
await baseCtx?.close().catch((error) => {
|
|
681
|
+
log.logWarning(`[${event.channelId}] Failed to close delivery`, errorMessage(error));
|
|
682
|
+
});
|
|
678
683
|
if (structuredWakeFinalized)
|
|
679
684
|
await getDurableDispatch()?.markCompleted(event.dispatchId);
|
|
680
685
|
else
|
|
@@ -697,6 +702,7 @@ function createDingTalkHandler(deps) {
|
|
|
697
702
|
return handler;
|
|
698
703
|
}
|
|
699
704
|
export async function createRuntimeContext(options) {
|
|
705
|
+
await migrateMemoryMaintenanceStates(options.paths.appHomeDir);
|
|
700
706
|
const startServices = options.startServices ?? true;
|
|
701
707
|
const registerSignalHandlers = options.registerSignalHandlers ?? true;
|
|
702
708
|
const store = new ChannelStore({ workingDir: options.paths.workspaceDir });
|
|
@@ -734,6 +740,8 @@ export async function createRuntimeContext(options) {
|
|
|
734
740
|
}
|
|
735
741
|
const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
|
|
736
742
|
const runner = createRunner(channelId, channelDir, {
|
|
743
|
+
jobManager: jobs.get(channelId),
|
|
744
|
+
runManager: runs.get(channelId),
|
|
737
745
|
appHomeDir: options.paths.appHomeDir,
|
|
738
746
|
authConfigPath: options.paths.authConfigPath,
|
|
739
747
|
modelsConfigPath: options.paths.modelsConfigPath,
|
|
@@ -754,7 +762,8 @@ export async function createRuntimeContext(options) {
|
|
|
754
762
|
// task driver's own `notify` needs) — these two closures resolve them lazily, the same way
|
|
755
763
|
// `getRunner` above already resolves `bot` before its own declaration: nothing here calls
|
|
756
764
|
// through them until long after the whole function has finished setting up.
|
|
757
|
-
const
|
|
765
|
+
const getJobs = () => jobs;
|
|
766
|
+
const getRuns = () => runs;
|
|
758
767
|
const getTaskDriver = () => taskDriver;
|
|
759
768
|
const handler = createDingTalkHandler({
|
|
760
769
|
options,
|
|
@@ -770,7 +779,8 @@ export async function createRuntimeContext(options) {
|
|
|
770
779
|
startedAt,
|
|
771
780
|
isShuttingDown,
|
|
772
781
|
getDurableDispatch,
|
|
773
|
-
|
|
782
|
+
getJobs,
|
|
783
|
+
getRuns,
|
|
774
784
|
getTaskDriver,
|
|
775
785
|
});
|
|
776
786
|
const bot = options.createBot
|
|
@@ -790,10 +800,10 @@ export async function createRuntimeContext(options) {
|
|
|
790
800
|
`记录文件:state/dispatch/${record.id}.json(已保留,供排查)。`);
|
|
791
801
|
},
|
|
792
802
|
});
|
|
793
|
-
const executor = createExecutor();
|
|
803
|
+
const executor = options.executor ?? createExecutor();
|
|
794
804
|
// Background jobs get their persistence root and their way to wake a channel before any turn
|
|
795
805
|
// can start one, then re-adopt whatever survived the last shutdown (spec 031, D6).
|
|
796
|
-
|
|
806
|
+
const jobs = createJobRuntime(executor, {
|
|
797
807
|
jobsStateDir: join(options.paths.appHomeDir, "state", "jobs"),
|
|
798
808
|
workspaceDir: options.paths.workspaceDir,
|
|
799
809
|
dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
|
|
@@ -801,7 +811,7 @@ export async function createRuntimeContext(options) {
|
|
|
801
811
|
});
|
|
802
812
|
// Delegation runs get the same treatment (spec 040, D1/D7): persistence root, wake delivery,
|
|
803
813
|
// and the usage/archive authority, wired before any turn can start a run.
|
|
804
|
-
|
|
814
|
+
const runs = createSubAgentRuntime({
|
|
805
815
|
stateDir: join(options.paths.appHomeDir, "state", "subagent-runs"),
|
|
806
816
|
dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
|
|
807
817
|
// P0-1/P1a: a best-effort out-of-band notice, independent of the completion wake — it reaches
|
|
@@ -826,8 +836,9 @@ export async function createRuntimeContext(options) {
|
|
|
826
836
|
// Spec 042 D11: `restoreChannelJobs` used to be a bare `void` while `restoreAllSubAgentRuns`
|
|
827
837
|
// was already awaited — the same admission race P0-1 closed for delegation runs was still open
|
|
828
838
|
// for background jobs.
|
|
829
|
-
await
|
|
830
|
-
await
|
|
839
|
+
await jobs.restore();
|
|
840
|
+
await runs.restore();
|
|
841
|
+
runs.start();
|
|
831
842
|
// Spec 043, D10 point 1: repair any turn interrupted by the last shutdown/crash before opening
|
|
832
843
|
// admission — a message routed to a still-dangling session would 400 against the provider on
|
|
833
844
|
// every attempt (F3) until a human ran /new. Runs before bot.start() for the same reason as
|
|
@@ -917,7 +928,8 @@ export async function createRuntimeContext(options) {
|
|
|
917
928
|
durableDispatch?.stop();
|
|
918
929
|
memoryMaintenanceScheduler.stop();
|
|
919
930
|
eventsWatcher.stop();
|
|
920
|
-
|
|
931
|
+
runs.stop();
|
|
932
|
+
jobs.stop();
|
|
921
933
|
await bot.stop();
|
|
922
934
|
const runningTasks = Array.from(activeTasks);
|
|
923
935
|
if (runningTasks.length > 0) {
|
|
@@ -1004,6 +1016,8 @@ export async function createRuntimeContext(options) {
|
|
|
1004
1016
|
}
|
|
1005
1017
|
return {
|
|
1006
1018
|
handler,
|
|
1019
|
+
jobs,
|
|
1020
|
+
runs,
|
|
1007
1021
|
store,
|
|
1008
1022
|
bot,
|
|
1009
1023
|
taskDriver,
|
|
@@ -1011,41 +1025,6 @@ export async function createRuntimeContext(options) {
|
|
|
1011
1025
|
shutdown: shutdownWithReason,
|
|
1012
1026
|
};
|
|
1013
1027
|
}
|
|
1014
|
-
/**
|
|
1015
|
-
* Transport-neutral app services shared by the DingTalk runtime and the terminal
|
|
1016
|
-
* TUI: loads settings (surfacing load errors) and reports tool/security config
|
|
1017
|
-
* diagnostics. Does NOT touch DingTalk config, so the TUI can call it without any
|
|
1018
|
-
* DingTalk credentials.
|
|
1019
|
-
*
|
|
1020
|
-
* Extracted verbatim from `bootstrap()`; the DingTalk path calls it in the same
|
|
1021
|
-
* position (after `loadConfig`, before `logStartup`) so its behavior is
|
|
1022
|
-
* unchanged. Logging configuration is intentionally left to each caller
|
|
1023
|
-
* (DingTalk: `createRuntimeContext`; TUI: right after this) to preserve the
|
|
1024
|
-
* existing "diagnostics logged with default logging config" ordering.
|
|
1025
|
-
*/
|
|
1026
|
-
export function prepareAppServices(paths = DEFAULT_BOOTSTRAP_PATHS) {
|
|
1027
|
-
// Shared by the DingTalk daemon and the TUI (both call prepareAppServices), so this
|
|
1028
|
-
// covers every entrypoint that talks to an LLM provider.
|
|
1029
|
-
installLlmProxy();
|
|
1030
|
-
const settingsManager = new PipiclawSettingsManager(paths.appHomeDir);
|
|
1031
|
-
for (const { scope, error } of settingsManager.drainErrors()) {
|
|
1032
|
-
log.logWarning(`Failed to load ${scope} settings`, `${error.message}\n${paths.settingsConfigPath}`);
|
|
1033
|
-
}
|
|
1034
|
-
// Errors already went out above with a richer message; this pass exists for the
|
|
1035
|
-
// warnings, chiefly retired settings keys (spec 035 D3).
|
|
1036
|
-
for (const diagnostic of settingsManager.getDiagnostics()) {
|
|
1037
|
-
if (diagnostic.severity === "error")
|
|
1038
|
-
continue;
|
|
1039
|
-
log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
|
|
1040
|
-
}
|
|
1041
|
-
for (const diagnostic of loadToolsConfigWithDiagnostics(paths.appHomeDir).diagnostics) {
|
|
1042
|
-
log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
|
|
1043
|
-
}
|
|
1044
|
-
for (const diagnostic of loadSecurityConfigWithDiagnostics(paths.appHomeDir).diagnostics) {
|
|
1045
|
-
log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
|
|
1046
|
-
}
|
|
1047
|
-
return { settingsManager };
|
|
1048
|
-
}
|
|
1049
1028
|
export async function bootstrap(argv, options = {}) {
|
|
1050
1029
|
const io = options.io ?? console;
|
|
1051
1030
|
const paths = options.paths ?? DEFAULT_BOOTSTRAP_PATHS;
|
|
@@ -7,8 +7,7 @@ import type { DingTalkBot } from "./dingtalk.js";
|
|
|
7
7
|
*
|
|
8
8
|
* `progressStyleOverride` lets the caller quiet a turn the user did not ask for. Background wakes
|
|
9
9
|
* (task driver, finished jobs, scheduled events) pass `"none"`: without it every autonomous step
|
|
10
|
-
* created an AI card in the human's conversation
|
|
11
|
-
* the `[SILENT]` turns that are the *normal* outcome of a check-in — deleted the card again. The
|
|
10
|
+
* created an AI card in the human's conversation even when the check-in ended `[SILENT]`. The
|
|
12
11
|
* final answer is unaffected; it is delivered by `respondPlain`/`replaceMessage` either way, so a
|
|
13
12
|
* background turn that has something to say still says it.
|
|
14
13
|
*/
|
package/dist/runtime/delivery.js
CHANGED
|
@@ -2,7 +2,8 @@ import * as log from "../log.js";
|
|
|
2
2
|
import { errorMessage } from "../shared/text-utils.js";
|
|
3
3
|
const MIN_UPDATE_INTERVAL_MS = 800;
|
|
4
4
|
const ROLLING_WINDOW_SIZE = 3;
|
|
5
|
-
const
|
|
5
|
+
const WAITING_TEXT = "正在处理…";
|
|
6
|
+
const MAX_PROGRESS_FAILURES = 2;
|
|
6
7
|
// DingTalk's card renderer swallows a bare "\n" between plain lines (and a blank-line
|
|
7
8
|
// paragraph break leaves too much vertical gap), but it does reliably break a markdown
|
|
8
9
|
// list onto separate lines. Render each progress entry as a list item instead.
|
|
@@ -29,6 +30,8 @@ class ChannelDeliveryController {
|
|
|
29
30
|
this.running = false;
|
|
30
31
|
this.closed = false;
|
|
31
32
|
this.finalResponseDelivered = false;
|
|
33
|
+
this.ending = false;
|
|
34
|
+
this.progressFailures = 0;
|
|
32
35
|
this.cardWarmupScheduled = false;
|
|
33
36
|
this.cardWarmupTriggered = false;
|
|
34
37
|
this.progressStartedAt = 0;
|
|
@@ -41,6 +44,10 @@ class ChannelDeliveryController {
|
|
|
41
44
|
this.sentProgressChars = 0;
|
|
42
45
|
this.replayRequired = false;
|
|
43
46
|
this.finalReplacementText = "";
|
|
47
|
+
this.cardGeneration = bot.getCardGeneration(event.channelId);
|
|
48
|
+
}
|
|
49
|
+
get isCurrent() {
|
|
50
|
+
return this.bot.isCardGenerationCurrent(this.event.channelId, this.cardGeneration);
|
|
44
51
|
}
|
|
45
52
|
/** The style this turn actually delivers with: the override when present, else the channel's. */
|
|
46
53
|
get progressStyle() {
|
|
@@ -64,7 +71,7 @@ class ChannelDeliveryController {
|
|
|
64
71
|
respondPlain: async (text, shouldLog = true, title) => this.sendFinal(text, shouldLog, title),
|
|
65
72
|
replaceMessage: async (text) => this.replaceWithFinal(text),
|
|
66
73
|
respondInThread: async (text) => {
|
|
67
|
-
if (this.closed || !text.trim()) {
|
|
74
|
+
if (this.closed || !this.isCurrent || !text.trim()) {
|
|
68
75
|
return;
|
|
69
76
|
}
|
|
70
77
|
const delivered = await this.bot.sendPlain(this.event.channelId, text);
|
|
@@ -83,29 +90,24 @@ class ChannelDeliveryController {
|
|
|
83
90
|
};
|
|
84
91
|
}
|
|
85
92
|
primeCard(delayMs) {
|
|
86
|
-
if (this.closed ||
|
|
93
|
+
if (this.closed ||
|
|
94
|
+
this.ending ||
|
|
95
|
+
this.progressStyle === "none" ||
|
|
96
|
+
this.cardWarmupScheduled ||
|
|
97
|
+
this.cardWarmupTriggered) {
|
|
87
98
|
return;
|
|
88
99
|
}
|
|
89
100
|
this.cardWarmupScheduled = true;
|
|
90
101
|
this.cardWarmupTimer = setTimeout(() => {
|
|
91
102
|
this.cardWarmupScheduled = false;
|
|
92
103
|
this.cardWarmupTimer = null;
|
|
93
|
-
|
|
104
|
+
if (this.closed || this.ending || !this.isCurrent || this.desiredRevision > 0)
|
|
105
|
+
return;
|
|
106
|
+
this.cardWarmupTriggered = true;
|
|
107
|
+
// Use the same serialized loop as progress and completion; no detached create request.
|
|
108
|
+
this.bumpRevision(true);
|
|
94
109
|
}, Math.max(0, delayMs));
|
|
95
110
|
}
|
|
96
|
-
async triggerCardWarmup() {
|
|
97
|
-
if (this.closed || this.finalResponseDelivered || this.desiredRevision > 0) {
|
|
98
|
-
return;
|
|
99
|
-
}
|
|
100
|
-
this.cardWarmupTriggered = true;
|
|
101
|
-
try {
|
|
102
|
-
await this.bot.ensureCard(this.event.channelId);
|
|
103
|
-
}
|
|
104
|
-
catch (err) {
|
|
105
|
-
log.logWarning(`[${this.event.channelId}] Failed to warm AI card`, errorMessage(err));
|
|
106
|
-
this.bot.discardCard(this.event.channelId);
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
111
|
clearCardWarmup() {
|
|
110
112
|
this.cardWarmupScheduled = false;
|
|
111
113
|
if (this.cardWarmupTimer) {
|
|
@@ -119,7 +121,7 @@ class ChannelDeliveryController {
|
|
|
119
121
|
});
|
|
120
122
|
}
|
|
121
123
|
async appendProgress(text, shouldLog) {
|
|
122
|
-
if (this.closed || this.
|
|
124
|
+
if (this.closed || this.ending || !this.isCurrent || !text.trim())
|
|
123
125
|
return;
|
|
124
126
|
// Final-card-only mode shows no progress; ignore any stray progress writes
|
|
125
127
|
// so we never create or flicker a card before the final replacement.
|
|
@@ -154,9 +156,13 @@ class ChannelDeliveryController {
|
|
|
154
156
|
this.bumpRevision(false);
|
|
155
157
|
}
|
|
156
158
|
async sendFinal(text, shouldLog, title) {
|
|
157
|
-
if (this.closed || this.
|
|
159
|
+
if (this.closed || this.ending || !this.isCurrent || !text.trim())
|
|
158
160
|
return this.finalResponseDelivered;
|
|
161
|
+
this.ending = true;
|
|
159
162
|
this.clearCardWarmup();
|
|
163
|
+
if (this.timer)
|
|
164
|
+
clearTimeout(this.timer);
|
|
165
|
+
this.timer = null;
|
|
160
166
|
const delivered = await this.bot.sendPlain(this.event.channelId, text, title ? { title, markdown: true } : undefined);
|
|
161
167
|
if (!delivered) {
|
|
162
168
|
// Do not archive a response we failed to deliver: the conversation log
|
|
@@ -172,18 +178,23 @@ class ChannelDeliveryController {
|
|
|
172
178
|
return true;
|
|
173
179
|
}
|
|
174
180
|
async replaceWithFinal(text) {
|
|
175
|
-
if (this.closed || this.finalResponseDelivered)
|
|
181
|
+
if (this.closed || this.finalResponseDelivered || !this.isCurrent || !text.trim())
|
|
176
182
|
return;
|
|
183
|
+
this.ending = true;
|
|
177
184
|
this.clearCardWarmup();
|
|
178
185
|
this.finalReplacementText = text;
|
|
179
186
|
this.mode = "finalize-with-fallback";
|
|
180
187
|
this.bumpRevision(true);
|
|
188
|
+
await this.flush();
|
|
189
|
+
if (!this.finalResponseDelivered && this.isCurrent) {
|
|
190
|
+
throw new Error("最终答复发送失败,请稍后重试。");
|
|
191
|
+
}
|
|
181
192
|
}
|
|
182
193
|
async silence() {
|
|
183
|
-
if (this.closed)
|
|
194
|
+
if (this.closed || this.finalResponseDelivered)
|
|
184
195
|
return;
|
|
196
|
+
this.ending = true;
|
|
185
197
|
this.clearCardWarmup();
|
|
186
|
-
this.finalResponseDelivered = true;
|
|
187
198
|
this.mode = "silent";
|
|
188
199
|
this.bumpRevision(true);
|
|
189
200
|
}
|
|
@@ -221,7 +232,7 @@ class ChannelDeliveryController {
|
|
|
221
232
|
const body = this.getProgressText();
|
|
222
233
|
const progressText = mode === "progress" && this.progressStyle === "rolling" && body
|
|
223
234
|
? `${this.buildRollingHeader()}\n\n${body}`
|
|
224
|
-
: body;
|
|
235
|
+
: body || (this.cardWarmupTriggered ? WAITING_TEXT : "");
|
|
225
236
|
const throttleBaseAt = this.lastDeliveredAt > 0 ? this.lastDeliveredAt : this.progressWindowStartedAt;
|
|
226
237
|
if (mode === "progress" && throttleBaseAt > 0) {
|
|
227
238
|
const remaining = MIN_UPDATE_INTERVAL_MS - (Date.now() - throttleBaseAt);
|
|
@@ -239,71 +250,51 @@ class ChannelDeliveryController {
|
|
|
239
250
|
let touchedRemote = false;
|
|
240
251
|
try {
|
|
241
252
|
if (mode === "progress") {
|
|
242
|
-
if (content) {
|
|
253
|
+
if (content && this.isCurrent && this.progressFailures < MAX_PROGRESS_FAILURES) {
|
|
243
254
|
const nextSentChars = progressText.length;
|
|
244
|
-
if (this.replayRequired) {
|
|
245
|
-
touchedRemote = await this.bot.replaceCard(this.event.channelId, progressText);
|
|
255
|
+
if (this.replayRequired || this.sentProgressChars === 0) {
|
|
256
|
+
touchedRemote = await this.bot.replaceCard(this.event.channelId, progressText, false, false, this.cardGeneration);
|
|
246
257
|
}
|
|
247
258
|
else {
|
|
248
259
|
const delta = progressText.slice(this.sentProgressChars);
|
|
249
|
-
touchedRemote = delta
|
|
260
|
+
touchedRemote = delta
|
|
261
|
+
? await this.bot.appendToCard(this.event.channelId, delta, false, false, this.cardGeneration)
|
|
262
|
+
: true;
|
|
250
263
|
}
|
|
251
264
|
if (!touchedRemote) {
|
|
252
|
-
this.
|
|
265
|
+
this.progressFailures++;
|
|
253
266
|
this.replayRequired = true;
|
|
254
267
|
}
|
|
255
268
|
else {
|
|
256
|
-
this.sentProgressChars = nextSentChars;
|
|
269
|
+
this.sentProgressChars = body ? nextSentChars : 0;
|
|
257
270
|
this.replayRequired = false;
|
|
258
271
|
}
|
|
259
272
|
}
|
|
260
273
|
}
|
|
261
274
|
else if (mode === "finalize-existing") {
|
|
262
275
|
if (content || this.cardWarmupTriggered) {
|
|
263
|
-
const
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
// (`||` binds tighter than `?:` — this used to read as one condition and
|
|
268
|
-
// was a standing invitation to misparse it.)
|
|
269
|
-
const finalCardText = content || isRolling ? finalProgressText : NO_CONTENT;
|
|
270
|
-
touchedRemote = await this.bot.replaceCard(this.event.channelId, finalCardText, true);
|
|
271
|
-
if (!touchedRemote) {
|
|
272
|
-
this.bot.discardCard(this.event.channelId);
|
|
273
|
-
}
|
|
274
|
-
else {
|
|
275
|
-
this.sentProgressChars = finalProgressText.length;
|
|
276
|
-
this.replayRequired = false;
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
else {
|
|
280
|
-
this.bot.discardCard(this.event.channelId);
|
|
276
|
+
const finalProgressText = this.progressStyle === "rolling"
|
|
277
|
+
? this.buildSummaryText()
|
|
278
|
+
: [body, "答复已发送。"].filter(Boolean).join("\n\n");
|
|
279
|
+
touchedRemote = await this.bot.finalizeExistingCard(this.event.channelId, finalProgressText, this.cardGeneration);
|
|
281
280
|
}
|
|
282
281
|
}
|
|
283
282
|
else if (mode === "finalize-with-fallback") {
|
|
284
283
|
if (replacementText.trim()) {
|
|
285
|
-
touchedRemote = await this.bot.finalizeCard(this.event.channelId, replacementText);
|
|
286
|
-
|
|
287
|
-
this.bot.discardCard(this.event.channelId);
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
else {
|
|
291
|
-
this.bot.discardCard(this.event.channelId);
|
|
284
|
+
touchedRemote = await this.bot.finalizeCard(this.event.channelId, replacementText, this.cardGeneration);
|
|
285
|
+
this.finalResponseDelivered = touchedRemote;
|
|
292
286
|
}
|
|
293
287
|
}
|
|
294
288
|
else if (mode === "silent") {
|
|
295
|
-
if (
|
|
296
|
-
touchedRemote = await this.bot.
|
|
297
|
-
}
|
|
298
|
-
if (!touchedRemote) {
|
|
299
|
-
this.bot.discardCard(this.event.channelId);
|
|
289
|
+
if (content) {
|
|
290
|
+
touchedRemote = await this.bot.finalizeExistingCard(this.event.channelId, [body, "处理已结束。"].filter(Boolean).join("\n\n"), this.cardGeneration);
|
|
300
291
|
}
|
|
301
292
|
}
|
|
302
293
|
}
|
|
303
294
|
catch (err) {
|
|
304
295
|
log.logWarning(`[${this.event.channelId}] Delivery sync failed`, errorMessage(err));
|
|
305
|
-
this.bot.discardCard(this.event.channelId);
|
|
306
296
|
if (mode === "progress") {
|
|
297
|
+
this.progressFailures++;
|
|
307
298
|
this.replayRequired = true;
|
|
308
299
|
}
|
|
309
300
|
}
|
|
@@ -363,7 +354,12 @@ class ChannelDeliveryController {
|
|
|
363
354
|
}
|
|
364
355
|
this.closed = true;
|
|
365
356
|
this.clearCardWarmup();
|
|
357
|
+
if (this.mode === "progress") {
|
|
358
|
+
this.mode = "silent";
|
|
359
|
+
this.bumpRevision(true);
|
|
360
|
+
}
|
|
366
361
|
await this.flush();
|
|
362
|
+
this.bot.discardCard(this.event.channelId, this.cardGeneration);
|
|
367
363
|
}
|
|
368
364
|
getProgressText() {
|
|
369
365
|
if (!this.progressTextDirty) {
|
|
@@ -427,8 +423,7 @@ class ChannelDeliveryController {
|
|
|
427
423
|
*
|
|
428
424
|
* `progressStyleOverride` lets the caller quiet a turn the user did not ask for. Background wakes
|
|
429
425
|
* (task driver, finished jobs, scheduled events) pass `"none"`: without it every autonomous step
|
|
430
|
-
* created an AI card in the human's conversation
|
|
431
|
-
* the `[SILENT]` turns that are the *normal* outcome of a check-in — deleted the card again. The
|
|
426
|
+
* created an AI card in the human's conversation even when the check-in ended `[SILENT]`. The
|
|
432
427
|
* final answer is unaffected; it is delivered by `respondPlain`/`replaceMessage` either way, so a
|
|
433
428
|
* background turn that has something to say still says it.
|
|
434
429
|
*/
|
|
@@ -89,6 +89,8 @@ export declare class DingTalkBot implements MediaSender {
|
|
|
89
89
|
private tokenExpiry;
|
|
90
90
|
private tokenRefreshPromise;
|
|
91
91
|
private activeCards;
|
|
92
|
+
private cardGenerations;
|
|
93
|
+
private cardCreationAttempted;
|
|
92
94
|
private cardCreationInFlight;
|
|
93
95
|
private convMeta;
|
|
94
96
|
private channelLastActiveAt;
|
|
@@ -144,18 +146,19 @@ export declare class DingTalkBot implements MediaSender {
|
|
|
144
146
|
*/
|
|
145
147
|
enqueueEvent(event: DingTalkEvent): boolean;
|
|
146
148
|
private enqueueStreamMessage;
|
|
147
|
-
/**
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
149
|
+
/** Capture the current turn's identity; close, /stop and /new invalidate it. */
|
|
150
|
+
getCardGeneration(channelId: string): symbol;
|
|
151
|
+
isCardGenerationCurrent(channelId: string, generation: symbol): boolean;
|
|
152
|
+
/** Get or create an AI card without joining an earlier turn's in-flight creation. */
|
|
153
|
+
ensureCard(channelId: string, generation?: symbol): Promise<void>;
|
|
151
154
|
/**
|
|
152
155
|
* Replace the active card content with a full snapshot.
|
|
153
156
|
*/
|
|
154
|
-
replaceCard(channelId: string, content: string, finalize?: boolean, failed?: boolean): Promise<boolean>;
|
|
157
|
+
replaceCard(channelId: string, content: string, finalize?: boolean, failed?: boolean, generation?: symbol): Promise<boolean>;
|
|
155
158
|
/**
|
|
156
159
|
* Append a delta to the active card transcript.
|
|
157
160
|
*/
|
|
158
|
-
appendToCard(channelId: string, content: string, finalize?: boolean, failed?: boolean): Promise<boolean>;
|
|
161
|
+
appendToCard(channelId: string, content: string, finalize?: boolean, failed?: boolean, generation?: symbol): Promise<boolean>;
|
|
159
162
|
/**
|
|
160
163
|
* Shared body of `replaceCard`/`appendToCard`: whether to open a fresh card differs between the
|
|
161
164
|
* two (a full-snapshot replace opens one for a finalize/failed close too; a delta append only
|
|
@@ -167,8 +170,11 @@ export declare class DingTalkBot implements MediaSender {
|
|
|
167
170
|
/**
|
|
168
171
|
* Finalize and remove the active card for a channel.
|
|
169
172
|
*/
|
|
170
|
-
finalizeCard(channelId: string, content: string): Promise<boolean>;
|
|
171
|
-
|
|
173
|
+
finalizeCard(channelId: string, content: string, generation?: symbol): Promise<boolean>;
|
|
174
|
+
/** Finish progress only: never create a card or send a fallback chat message. */
|
|
175
|
+
finalizeExistingCard(channelId: string, content: string, generation?: symbol): Promise<boolean>;
|
|
176
|
+
/** Invalidate this turn's local state. This is not a remote message deletion. */
|
|
177
|
+
discardCard(channelId: string, generation?: symbol | undefined): void;
|
|
172
178
|
/**
|
|
173
179
|
* Send a normal message natively mapping DM and Group to correct endpoints (fallback when no card).
|
|
174
180
|
*
|
|
@@ -235,6 +241,7 @@ export declare class DingTalkBot implements MediaSender {
|
|
|
235
241
|
private createCard;
|
|
236
242
|
private createCardUncached;
|
|
237
243
|
private streamCard;
|
|
244
|
+
private streamCardRequest;
|
|
238
245
|
private getAccessToken;
|
|
239
246
|
private refreshAccessToken;
|
|
240
247
|
private onStreamMessage;
|