@oyasmi/pipiclaw 0.9.2-beta.3 → 0.9.2-beta.6
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.md +3 -0
- package/dist/agent/channel-runner.d.ts +45 -19
- package/dist/agent/channel-runner.js +156 -102
- package/dist/agent/command-extension.js +1 -1
- package/dist/agent/context-budget.d.ts +17 -1
- package/dist/agent/context-budget.js +20 -6
- package/dist/agent/job-manager.d.ts +3 -1
- package/dist/agent/job-manager.js +7 -1
- package/dist/agent/prompt/builder.d.ts +0 -1
- package/dist/agent/prompt/builder.js +1 -14
- package/dist/agent/prompt/manifest.js +2 -1
- package/dist/agent/prompt/sections.js +1 -1
- package/dist/agent/runner-factory.d.ts +19 -1
- package/dist/agent/runner-factory.js +8 -1
- package/dist/agent/session-events.d.ts +2 -2
- package/dist/agent/session-events.js +2 -22
- package/dist/agent/turn-prompt.d.ts +35 -0
- package/dist/agent/turn-prompt.js +37 -0
- package/dist/agent/turn-recovery.js +1 -1
- package/dist/agent/turn-state.d.ts +60 -0
- package/dist/agent/turn-state.js +95 -0
- package/dist/agent/types.d.ts +5 -4
- package/dist/{runtime → channel}/channel-context.d.ts +10 -2
- package/dist/{runtime → channel}/channel-context.js +6 -2
- package/dist/{runtime → channel}/channel-event.d.ts +39 -0
- package/dist/channel/channel-event.js +11 -0
- package/dist/channel/channel-paths.d.ts +16 -0
- package/dist/{runtime → channel}/channel-paths.js +20 -0
- package/dist/{runtime → channel}/project-scope-store.js +6 -11
- package/dist/{runtime → channel}/store.d.ts +7 -0
- package/dist/{agent/commands.d.ts → commands/catalog.d.ts} +17 -2
- package/dist/{agent/commands.js → commands/catalog.js} +30 -0
- package/dist/index.d.ts +1 -1
- package/dist/log.js +14 -5
- package/dist/main.js +29 -0
- package/dist/memory/bootstrap.js +3 -5
- package/dist/memory/candidates.js +2 -4
- package/dist/memory/commands.js +2 -2
- package/dist/memory/files.d.ts +0 -1
- package/dist/memory/files.js +6 -9
- package/dist/memory/maintenance-state.d.ts +8 -0
- package/dist/memory/maintenance-state.js +51 -4
- package/dist/memory/scheduler.d.ts +6 -0
- package/dist/memory/scheduler.js +19 -16
- package/dist/playbooks/agent-delegation.md +2 -2
- package/dist/runtime/bootstrap.d.ts +14 -8
- package/dist/runtime/bootstrap.js +158 -81
- package/dist/runtime/delivery.d.ts +3 -3
- package/dist/runtime/delivery.js +1 -0
- package/dist/runtime/dingtalk.d.ts +62 -6
- package/dist/runtime/dingtalk.js +194 -85
- package/dist/runtime/durable-dispatch.d.ts +7 -1
- package/dist/runtime/durable-dispatch.js +12 -2
- package/dist/runtime/event-commands.js +2 -2
- package/dist/runtime/events.d.ts +8 -1
- package/dist/runtime/events.js +15 -3
- package/dist/runtime/inbound-media.d.ts +60 -0
- package/dist/runtime/inbound-media.js +95 -0
- package/dist/runtime/project-commands.js +2 -2
- package/dist/runtime/skill-commands.d.ts +27 -0
- package/dist/runtime/skill-commands.js +72 -0
- package/dist/runtime/subagent-commands.js +1 -1
- package/dist/runtime/task-commands.js +2 -2
- package/dist/runtime/task-driver.d.ts +12 -1
- package/dist/runtime/task-driver.js +36 -56
- package/dist/runtime/task-migration.d.ts +11 -0
- package/dist/runtime/task-migration.js +14 -2
- package/dist/runtime/task-wake.d.ts +1 -1
- package/dist/runtime/task-wake.js +1 -1
- package/dist/security/command-guard.js +1 -3
- package/dist/security/config.d.ts +1 -1
- package/dist/security/config.js +8 -32
- package/dist/security/path-guard.js +1 -6
- package/dist/security/project-scope.js +1 -3
- package/dist/settings.d.ts +3 -2
- package/dist/settings.js +82 -20
- package/dist/shared/atomic-file.d.ts +2 -3
- package/dist/shared/atomic-file.js +8 -9
- package/dist/shared/config-diagnostic.d.ts +21 -0
- package/dist/shared/config-diagnostic.js +32 -0
- package/dist/shared/numeric.d.ts +7 -0
- package/dist/shared/numeric.js +19 -0
- package/dist/shared/text-utils.d.ts +10 -0
- package/dist/shared/text-utils.js +16 -0
- package/dist/shared/token-estimate.d.ts +1 -0
- package/dist/shared/token-estimate.js +19 -0
- package/dist/shared/types.d.ts +23 -0
- package/dist/shared/types.js +12 -0
- package/dist/shared/with-timeout.d.ts +3 -0
- package/dist/shared/with-timeout.js +8 -0
- package/dist/subagents/discovery.d.ts +7 -7
- package/dist/subagents/discovery.js +27 -59
- package/dist/subagents/runs.d.ts +15 -4
- package/dist/subagents/runs.js +118 -11
- package/dist/subagents/tool.js +199 -131
- package/dist/subagents/workspace-lease.js +1 -3
- package/dist/tasks/control.d.ts +2 -0
- package/dist/tasks/control.js +2 -0
- package/dist/tasks/ledger.d.ts +0 -9
- package/dist/tasks/ledger.js +92 -158
- package/dist/tools/config.d.ts +1 -1
- package/dist/tools/config.js +9 -46
- package/dist/tools/glob-match.d.ts +25 -4
- package/dist/tools/glob-match.js +175 -53
- package/dist/tools/glob.js +5 -2
- package/dist/tools/index.d.ts +1 -1
- package/dist/tools/registry.d.ts +1 -1
- package/dist/tools/send-media.d.ts +1 -1
- package/dist/tools/skill.d.ts +15 -0
- package/dist/tools/skill.js +17 -11
- package/dist/tools/truncate.js +24 -28
- package/dist/tui/app.js +6 -4
- package/dist/tui/commands.d.ts +1 -0
- package/dist/tui/commands.js +3 -1
- 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 +2 -1
- package/dist/tui/turn-controller.js +2 -1
- package/dist/web/config.js +3 -15
- package/examples/sub-agents/README.md +2 -2
- package/examples/sub-agents/builder.md +1 -1
- package/examples/sub-agents/documenter.md +1 -1
- package/examples/sub-agents/explorer.md +4 -4
- package/examples/sub-agents/git-committer.md +5 -4
- package/examples/sub-agents/log-sifter.md +4 -4
- package/examples/sub-agents/planner.md +1 -1
- package/examples/sub-agents/reviewer.md +1 -1
- package/examples/sub-agents/verifier.md +1 -1
- package/examples/sub-agents/worker.md +3 -3
- package/package.json +3 -2
- package/dist/agent/index.d.ts +0 -2
- package/dist/agent/index.js +0 -1
- package/dist/runtime/channel-event.js +0 -1
- package/dist/runtime/channel-paths.d.ts +0 -4
- /package/dist/{runtime → channel}/active-session-store.d.ts +0 -0
- /package/dist/{runtime → channel}/active-session-store.js +0 -0
- /package/dist/{runtime → channel}/channel-index.d.ts +0 -0
- /package/dist/{runtime → channel}/channel-index.js +0 -0
- /package/dist/{runtime → channel}/project-scope-store.d.ts +0 -0
- /package/dist/{runtime → channel}/store.js +0 -0
- /package/dist/{agent → commands}/reply-limits.d.ts +0 -0
- /package/dist/{agent → commands}/reply-limits.js +0 -0
|
@@ -1,11 +1,17 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { mkdir, writeFile } from "fs/promises";
|
|
2
|
+
import { join, relative } from "path";
|
|
3
3
|
import { channelEffectCount, noteTaskEffects, taskEffectCount } from "../agent/effect-ledger.js";
|
|
4
|
-
import { createRunner } from "../agent/index.js";
|
|
5
4
|
import { channelRunningJobLines, configureJobRuntime, restoreChannelJobs } from "../agent/job-manager.js";
|
|
6
5
|
import { loadDetachedMaintenanceContext } from "../agent/maintenance-context.js";
|
|
6
|
+
import { createRunner } from "../agent/runner-factory.js";
|
|
7
7
|
import { renderStatus } from "../agent/status-render.js";
|
|
8
8
|
import { scanWorkspaceForInterruptedTurns } from "../agent/turn-recovery.js";
|
|
9
|
+
import { createFreshActiveSession } from "../channel/active-session-store.js";
|
|
10
|
+
import { createChannelIndex } from "../channel/channel-index.js";
|
|
11
|
+
import { ensureChannelDir, getChannelDir } from "../channel/channel-paths.js";
|
|
12
|
+
import { resolveProjectScope } from "../channel/project-scope-store.js";
|
|
13
|
+
import { ChannelStore } from "../channel/store.js";
|
|
14
|
+
import { BUILT_IN_COMMANDS, formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../commands/catalog.js";
|
|
9
15
|
import { createExecutor } from "../executor.js";
|
|
10
16
|
import * as log from "../log.js";
|
|
11
17
|
import { ensureChannelMemoryFilesSync } from "../memory/files.js";
|
|
@@ -14,29 +20,28 @@ import { defaultModel } from "../models/utils.js";
|
|
|
14
20
|
import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
|
|
15
21
|
import { flushSecurityLogs } from "../security/logger.js";
|
|
16
22
|
import { resolveProjectAccessPolicy } from "../security/project-scope.js";
|
|
17
|
-
import { PipiclawSettingsManager } from "../settings.js";
|
|
23
|
+
import { PipiclawSettingsManager, TASK_DRIVER_SETTINGS } from "../settings.js";
|
|
18
24
|
import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
|
|
19
25
|
import { fileStamp } from "../shared/file-stamp.js";
|
|
26
|
+
import { localStampForFilename } from "../shared/local-time.js";
|
|
20
27
|
import { errorMessage } from "../shared/text-utils.js";
|
|
28
|
+
import { sleepUnref } from "../shared/with-timeout.js";
|
|
21
29
|
import { loadDetachedSubAgentDiscovery } from "../subagents/detached-discovery.js";
|
|
22
30
|
import { configureSubAgentRuntime, getSubAgentRunManager, restoreAllSubAgentRuns, stopSubAgentGarbageCollector, } from "../subagents/runs.js";
|
|
23
31
|
import { readActiveTasks } from "../tasks/ledger.js";
|
|
24
32
|
import { getToolsConfigPath, loadToolsConfig, loadToolsConfigWithDiagnostics } from "../tools/config.js";
|
|
25
33
|
import { getUsageLedger } from "../usage/ledger.js";
|
|
26
34
|
import { parseUsageMode, renderUsageReport } from "../usage/render.js";
|
|
27
|
-
import { createFreshActiveSession } from "./active-session-store.js";
|
|
28
35
|
import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, loadConfig, parseArgs, printBootstrapSummary, readCliVersion, } from "./app-home.js";
|
|
29
|
-
import { createChannelIndex } from "./channel-index.js";
|
|
30
|
-
import { ensureChannelDir, getChannelDir } from "./channel-paths.js";
|
|
31
36
|
import { createDingTalkContext } from "./delivery.js";
|
|
32
37
|
import { DingTalkBot, } from "./dingtalk.js";
|
|
33
38
|
import { DurableDispatchService } from "./durable-dispatch.js";
|
|
34
39
|
import { handleEventsCommand as runEventsCommand } from "./event-commands.js";
|
|
35
40
|
import { createEventsWatcher } from "./events.js";
|
|
41
|
+
import { extensionForMimeType } from "./inbound-media.js";
|
|
36
42
|
import { handleProjectCommand as runProjectCommand } from "./project-commands.js";
|
|
37
|
-
import { resolveProjectScope } from "./project-scope-store.js";
|
|
38
43
|
import { installLlmProxy } from "./proxy.js";
|
|
39
|
-
import {
|
|
44
|
+
import { handleSkillsCommand as runSkillsCommand } from "./skill-commands.js";
|
|
40
45
|
import { renderRunNotice, handleSubagentsCommand as runSubagentsCommand } from "./subagent-commands.js";
|
|
41
46
|
import { pauseTask, handleTasksCommand as runTasksCommand } from "./task-commands.js";
|
|
42
47
|
import { createTaskDriverEvent, TaskDriver } from "./task-driver.js";
|
|
@@ -89,6 +94,19 @@ async function evictIdleRunnersOverCap(channelRunners) {
|
|
|
89
94
|
function isNoRunningTaskQueueError(err) {
|
|
90
95
|
return err instanceof Error && err.message === "No task is currently running.";
|
|
91
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
|
+
}
|
|
92
110
|
/**
|
|
93
111
|
* The `runRuntimeCommand` names usable on the idle-turn path — every `BUILT_IN_COMMANDS` entry
|
|
94
112
|
* *not* marked `runnerHandled`, i.e. every stateless report. `context` is the one deliberate
|
|
@@ -109,12 +127,6 @@ function isIdleRuntimeCommandName(name) {
|
|
|
109
127
|
*/
|
|
110
128
|
const STOP_FORCE_END_GRACE_MS = 15_000;
|
|
111
129
|
const STOP_FORCE_END_POLL_MS = 250;
|
|
112
|
-
function sleepUnref(ms) {
|
|
113
|
-
return new Promise((resolve) => {
|
|
114
|
-
const timer = setTimeout(resolve, ms);
|
|
115
|
-
timer.unref?.();
|
|
116
|
-
});
|
|
117
|
-
}
|
|
118
130
|
/**
|
|
119
131
|
* Watchdog for `/stop`: release the channel if the stopped turn has not ended
|
|
120
132
|
* once the grace window elapses. Returns true when it had to force the release.
|
|
@@ -134,65 +146,14 @@ export async function forceEndStuckTurnAfterStop(input) {
|
|
|
134
146
|
.catch(() => undefined);
|
|
135
147
|
return true;
|
|
136
148
|
}
|
|
137
|
-
|
|
138
|
-
const
|
|
139
|
-
const registerSignalHandlers = options.registerSignalHandlers ?? true;
|
|
140
|
-
const store = new ChannelStore({ workingDir: options.paths.workspaceDir });
|
|
141
|
-
const runtimeSettingsManager = options.settingsManager ?? new PipiclawSettingsManager(options.paths.appHomeDir);
|
|
142
|
-
log.configureLogging(runtimeSettingsManager.getLoggingSettings());
|
|
143
|
-
const startedAt = Date.now();
|
|
144
|
-
const cliVersion = readCliVersion();
|
|
145
|
-
const channelRunners = new Map();
|
|
146
|
-
const sessionResetChains = new Map();
|
|
147
|
-
const activeTasks = new Set();
|
|
148
|
-
/** Channels with a `/stop` watchdog in flight, so a burst of `/stop` starts only one. */
|
|
149
|
-
const stopWatchdogs = new Set();
|
|
150
|
-
// `workspace/CHANNELS.md`: names every channel id so the workspace, the logs and the agent
|
|
151
|
-
// stop dealing in `group_cid...`. Writes are debounced internally (see channel-index.ts).
|
|
152
|
-
const channelIndex = createChannelIndex({ workspaceDir: options.paths.workspaceDir });
|
|
153
|
-
let durableDispatch;
|
|
154
|
-
let shuttingDown = false;
|
|
155
|
-
let shutdownPromise = null;
|
|
156
|
-
const archiveIncomingMessage = async (channelId, message, contextLabel) => {
|
|
157
|
-
try {
|
|
158
|
-
await store.logMessage(channelId, message);
|
|
159
|
-
}
|
|
160
|
-
catch (err) {
|
|
161
|
-
log.logWarning(`[${channelId}] Failed to archive ${contextLabel}`, errorMessage(err));
|
|
162
|
-
}
|
|
163
|
-
};
|
|
164
|
-
const getRunner = (channelId) => {
|
|
165
|
-
const existing = channelRunners.get(channelId);
|
|
166
|
-
if (existing) {
|
|
167
|
-
// Re-insert to move this channel to the end (most-recently-used) of the Map's
|
|
168
|
-
// iteration order, which evictIdleRunnersOverCap relies on.
|
|
169
|
-
channelRunners.delete(channelId);
|
|
170
|
-
channelRunners.set(channelId, existing);
|
|
171
|
-
return existing;
|
|
172
|
-
}
|
|
173
|
-
const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
|
|
174
|
-
ensureChannelMemoryFilesSync(channelDir);
|
|
175
|
-
const runner = createRunner(channelId, channelDir, {
|
|
176
|
-
appHomeDir: options.paths.appHomeDir,
|
|
177
|
-
authConfigPath: options.paths.authConfigPath,
|
|
178
|
-
modelsConfigPath: options.paths.modelsConfigPath,
|
|
179
|
-
settingsManager: runtimeSettingsManager,
|
|
180
|
-
onSessionEvent: options.observer,
|
|
181
|
-
// The DingTalk bot is the media sender for this transport; enables `send_media`.
|
|
182
|
-
// `bot` is defined below in this same scope and initialized before any message
|
|
183
|
-
// (and thus any getRunner call) can arrive.
|
|
184
|
-
mediaSender: bot,
|
|
185
|
-
});
|
|
186
|
-
channelRunners.set(channelId, runner);
|
|
187
|
-
void evictIdleRunnersOverCap(channelRunners);
|
|
188
|
-
return runner;
|
|
189
|
-
};
|
|
149
|
+
function createDingTalkHandler(deps) {
|
|
150
|
+
const { options, store, channelRunners, sessionResetChains, activeTasks, stopWatchdogs, channelIndex, archiveIncomingMessage, getRunner, cliVersion, startedAt, isShuttingDown, getDurableDispatch, getExecutor, getTaskDriver, } = deps;
|
|
190
151
|
const handler = {
|
|
191
152
|
isRunning(channelId) {
|
|
192
153
|
return channelRunners.get(channelId)?.isBusy() ?? false;
|
|
193
154
|
},
|
|
194
155
|
noteChannelActivity(observation) {
|
|
195
|
-
if (
|
|
156
|
+
if (isShuttingDown())
|
|
196
157
|
return;
|
|
197
158
|
channelIndex.note(observation);
|
|
198
159
|
},
|
|
@@ -220,7 +181,7 @@ export async function createRuntimeContext(options) {
|
|
|
220
181
|
void runner.abort().catch((err) => {
|
|
221
182
|
log.logWarning(`[${channelId}] Failed to abort run`, errorMessage(err));
|
|
222
183
|
});
|
|
223
|
-
void
|
|
184
|
+
void getDurableDispatch()
|
|
224
185
|
?.cancelChannel(channelId)
|
|
225
186
|
.then((canceled) => {
|
|
226
187
|
if (canceled)
|
|
@@ -249,7 +210,7 @@ export async function createRuntimeContext(options) {
|
|
|
249
210
|
return { pausedTaskId };
|
|
250
211
|
},
|
|
251
212
|
async handleNewSession(event, _bot) {
|
|
252
|
-
if (
|
|
213
|
+
if (isShuttingDown())
|
|
253
214
|
return;
|
|
254
215
|
const previous = sessionResetChains.get(event.channelId) ?? Promise.resolve();
|
|
255
216
|
const reset = previous
|
|
@@ -291,6 +252,7 @@ export async function createRuntimeContext(options) {
|
|
|
291
252
|
userName: event.userName,
|
|
292
253
|
text: event.text,
|
|
293
254
|
isBot: false,
|
|
255
|
+
images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
|
|
294
256
|
}, "/new command");
|
|
295
257
|
}
|
|
296
258
|
catch (error) {
|
|
@@ -334,7 +296,7 @@ export async function createRuntimeContext(options) {
|
|
|
334
296
|
// unique per invocation rather than sharing the driver's occurrence key (D1).
|
|
335
297
|
const now = Date.now();
|
|
336
298
|
const driverEvent = createTaskDriverEvent(event.channelId, entry, now);
|
|
337
|
-
return ((await
|
|
299
|
+
return ((await getDurableDispatch()?.dispatch({
|
|
338
300
|
...driverEvent,
|
|
339
301
|
dispatchId: `task:${event.channelId}:${entry.id}:manual:${new Date(now).toISOString()}`,
|
|
340
302
|
})) ?? false);
|
|
@@ -392,10 +354,17 @@ export async function createRuntimeContext(options) {
|
|
|
392
354
|
});
|
|
393
355
|
},
|
|
394
356
|
});
|
|
357
|
+
case "skills":
|
|
358
|
+
return runSkillsCommand({
|
|
359
|
+
args,
|
|
360
|
+
workspaceDir: options.paths.workspaceDir,
|
|
361
|
+
appHomeDir: options.paths.appHomeDir,
|
|
362
|
+
channelId: event.channelId,
|
|
363
|
+
});
|
|
395
364
|
}
|
|
396
365
|
},
|
|
397
366
|
async handleBusyMessage(event, bot, mode, queueText) {
|
|
398
|
-
if (
|
|
367
|
+
if (isShuttingDown()) {
|
|
399
368
|
return { kind: "handled" };
|
|
400
369
|
}
|
|
401
370
|
const runner = getRunner(event.channelId);
|
|
@@ -420,7 +389,7 @@ export async function createRuntimeContext(options) {
|
|
|
420
389
|
return { kind: "requeue", text: trimmedQueueText };
|
|
421
390
|
}
|
|
422
391
|
try {
|
|
423
|
-
await runner.queueSteer(trimmedQueueText, event.userName);
|
|
392
|
+
await runner.queueSteer(trimmedQueueText, event.userName, event.images);
|
|
424
393
|
await archiveIncomingMessage(event.channelId, {
|
|
425
394
|
date: new Date().toISOString(),
|
|
426
395
|
ts: event.ts,
|
|
@@ -430,6 +399,7 @@ export async function createRuntimeContext(options) {
|
|
|
430
399
|
isBot: false,
|
|
431
400
|
deliveryMode: mode,
|
|
432
401
|
skipContextSync: true,
|
|
402
|
+
images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
|
|
433
403
|
}, `${mode} message`);
|
|
434
404
|
const confirmation = event.text.trim().startsWith("/")
|
|
435
405
|
? "已作为 steer 排队,当前工具步骤结束后生效。"
|
|
@@ -452,18 +422,43 @@ export async function createRuntimeContext(options) {
|
|
|
452
422
|
return { kind: "handled" };
|
|
453
423
|
}
|
|
454
424
|
},
|
|
425
|
+
/**
|
|
426
|
+
* Persist one downloaded inbound image under the channel's `inbox/` (spec 049). Bootstrap
|
|
427
|
+
* owns this, not the transport, because it holds the workspace root; see the doc comment
|
|
428
|
+
* on `DingTalkHandler.persistInboundImage` for the full contract (`mimeType: null` case
|
|
429
|
+
* included).
|
|
430
|
+
*/
|
|
431
|
+
async persistInboundImage(channelId, image) {
|
|
432
|
+
try {
|
|
433
|
+
const dir = join(getChannelDir(options.paths.workspaceDir, channelId), "inbox");
|
|
434
|
+
await mkdir(dir, { recursive: true });
|
|
435
|
+
const extension = extensionForMimeType(image.mimeType);
|
|
436
|
+
const path = join(dir, `image-${localStampForFilename()}-${Math.random().toString(36).slice(2, 8)}.${extension}`);
|
|
437
|
+
await writeFile(path, image.data, { mode: 0o600 });
|
|
438
|
+
return {
|
|
439
|
+
path,
|
|
440
|
+
mimeType: image.mimeType ?? "application/octet-stream",
|
|
441
|
+
byteSize: image.data.byteLength,
|
|
442
|
+
...(image.mimeType === null ? { unsupportedFormat: true } : {}),
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
catch (err) {
|
|
446
|
+
log.logWarning(`[${channelId}] Failed to persist inbound image`, errorMessage(err));
|
|
447
|
+
return null;
|
|
448
|
+
}
|
|
449
|
+
},
|
|
455
450
|
reserveEvent(event) {
|
|
456
451
|
// This must remain synchronous. DingTalkBot calls it before awaiting the queued
|
|
457
452
|
// handler, making the busy state observable to another message in the same tick.
|
|
458
453
|
getRunner(event.channelId).beginTurn(event.text);
|
|
459
454
|
},
|
|
460
455
|
async handleEvent(event, bot, _isEvent) {
|
|
461
|
-
if (
|
|
456
|
+
if (isShuttingDown()) {
|
|
462
457
|
log.logInfo(`[${event.channelId}] Ignoring event during shutdown`);
|
|
463
458
|
return;
|
|
464
459
|
}
|
|
465
460
|
const runner = getRunner(event.channelId);
|
|
466
|
-
await
|
|
461
|
+
await getDurableDispatch()?.markStarted(event.dispatchId);
|
|
467
462
|
let structuredWakeFinalized = event.internalWake === undefined;
|
|
468
463
|
const task = (async () => {
|
|
469
464
|
try {
|
|
@@ -479,6 +474,7 @@ export async function createRuntimeContext(options) {
|
|
|
479
474
|
text: event.text,
|
|
480
475
|
isBot: false,
|
|
481
476
|
skipContextSync: Boolean(builtInCommand),
|
|
477
|
+
images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
|
|
482
478
|
}, "user message");
|
|
483
479
|
// Background wakes deliver their result, not their process: no progress card, no
|
|
484
480
|
// thinking stream, nothing to delete when the check-in ends `[SILENT]`. An "awaited"
|
|
@@ -560,7 +556,7 @@ export async function createRuntimeContext(options) {
|
|
|
560
556
|
let recoveredJobTaskId;
|
|
561
557
|
if (jobMatch) {
|
|
562
558
|
const [, jobId, jobTaskId] = jobMatch;
|
|
563
|
-
const claimed = await claimVerifiedJobWake(event, options.paths.workspaceDir,
|
|
559
|
+
const claimed = await claimVerifiedJobWake(event, options.paths.workspaceDir, getExecutor(), options.wakeTransitionHooks?.job);
|
|
564
560
|
if (claimed) {
|
|
565
561
|
if (claimed.activated)
|
|
566
562
|
recoveredJobTaskId = claimed.taskId;
|
|
@@ -631,13 +627,13 @@ export async function createRuntimeContext(options) {
|
|
|
631
627
|
}
|
|
632
628
|
finally {
|
|
633
629
|
if (structuredWakeFinalized)
|
|
634
|
-
await
|
|
630
|
+
await getDurableDispatch()?.markCompleted(event.dispatchId);
|
|
635
631
|
else
|
|
636
|
-
await
|
|
632
|
+
await getDurableDispatch()?.markRetryable(event.dispatchId);
|
|
637
633
|
runner.endTurn();
|
|
638
634
|
// A finished turn may have written task files (progress/complete/set); rescan
|
|
639
635
|
// now so a continuing task chain advances immediately instead of after a full sleep.
|
|
640
|
-
|
|
636
|
+
getTaskDriver().nudge?.();
|
|
641
637
|
}
|
|
642
638
|
})();
|
|
643
639
|
activeTasks.add(task);
|
|
@@ -649,6 +645,86 @@ export async function createRuntimeContext(options) {
|
|
|
649
645
|
}
|
|
650
646
|
},
|
|
651
647
|
};
|
|
648
|
+
return handler;
|
|
649
|
+
}
|
|
650
|
+
export async function createRuntimeContext(options) {
|
|
651
|
+
const startServices = options.startServices ?? true;
|
|
652
|
+
const registerSignalHandlers = options.registerSignalHandlers ?? true;
|
|
653
|
+
const store = new ChannelStore({ workingDir: options.paths.workspaceDir });
|
|
654
|
+
const runtimeSettingsManager = options.settingsManager ?? new PipiclawSettingsManager(options.paths.appHomeDir);
|
|
655
|
+
log.configureLogging(runtimeSettingsManager.getLoggingSettings());
|
|
656
|
+
const startedAt = Date.now();
|
|
657
|
+
const cliVersion = readCliVersion();
|
|
658
|
+
const channelRunners = new Map();
|
|
659
|
+
const sessionResetChains = new Map();
|
|
660
|
+
const activeTasks = new Set();
|
|
661
|
+
/** Channels with a `/stop` watchdog in flight, so a burst of `/stop` starts only one. */
|
|
662
|
+
const stopWatchdogs = new Set();
|
|
663
|
+
// `workspace/CHANNELS.md`: names every channel id so the workspace, the logs and the agent
|
|
664
|
+
// stop dealing in `group_cid...`. Writes are debounced internally (see channel-index.ts).
|
|
665
|
+
const channelIndex = createChannelIndex({ workspaceDir: options.paths.workspaceDir });
|
|
666
|
+
let durableDispatch;
|
|
667
|
+
let shuttingDown = false;
|
|
668
|
+
let shutdownPromise = null;
|
|
669
|
+
const archiveIncomingMessage = async (channelId, message, contextLabel) => {
|
|
670
|
+
try {
|
|
671
|
+
await store.logMessage(channelId, message);
|
|
672
|
+
}
|
|
673
|
+
catch (err) {
|
|
674
|
+
log.logWarning(`[${channelId}] Failed to archive ${contextLabel}`, errorMessage(err));
|
|
675
|
+
}
|
|
676
|
+
};
|
|
677
|
+
const getRunner = (channelId) => {
|
|
678
|
+
const existing = channelRunners.get(channelId);
|
|
679
|
+
if (existing) {
|
|
680
|
+
// Re-insert to move this channel to the end (most-recently-used) of the Map's
|
|
681
|
+
// iteration order, which evictIdleRunnersOverCap relies on.
|
|
682
|
+
channelRunners.delete(channelId);
|
|
683
|
+
channelRunners.set(channelId, existing);
|
|
684
|
+
return existing;
|
|
685
|
+
}
|
|
686
|
+
const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
|
|
687
|
+
ensureChannelMemoryFilesSync(channelDir);
|
|
688
|
+
const runner = createRunner(channelId, channelDir, {
|
|
689
|
+
appHomeDir: options.paths.appHomeDir,
|
|
690
|
+
authConfigPath: options.paths.authConfigPath,
|
|
691
|
+
modelsConfigPath: options.paths.modelsConfigPath,
|
|
692
|
+
settingsManager: runtimeSettingsManager,
|
|
693
|
+
onSessionEvent: options.observer,
|
|
694
|
+
// The DingTalk bot is the media sender for this transport; enables `send_media`.
|
|
695
|
+
// `bot` is defined below in this same scope and initialized before any message
|
|
696
|
+
// (and thus any getRunner call) can arrive.
|
|
697
|
+
mediaSender: bot,
|
|
698
|
+
});
|
|
699
|
+
channelRunners.set(channelId, runner);
|
|
700
|
+
void evictIdleRunnersOverCap(channelRunners);
|
|
701
|
+
return runner;
|
|
702
|
+
};
|
|
703
|
+
const isShuttingDown = () => shuttingDown;
|
|
704
|
+
const getDurableDispatch = () => durableDispatch;
|
|
705
|
+
// `executor`/`taskDriver` are declared further down this function (after `bot`, which the
|
|
706
|
+
// task driver's own `notify` needs) — these two closures resolve them lazily, the same way
|
|
707
|
+
// `getRunner` above already resolves `bot` before its own declaration: nothing here calls
|
|
708
|
+
// through them until long after the whole function has finished setting up.
|
|
709
|
+
const getExecutor = () => executor;
|
|
710
|
+
const getTaskDriver = () => taskDriver;
|
|
711
|
+
const handler = createDingTalkHandler({
|
|
712
|
+
options,
|
|
713
|
+
store,
|
|
714
|
+
channelRunners,
|
|
715
|
+
sessionResetChains,
|
|
716
|
+
activeTasks,
|
|
717
|
+
stopWatchdogs,
|
|
718
|
+
channelIndex,
|
|
719
|
+
archiveIncomingMessage,
|
|
720
|
+
getRunner,
|
|
721
|
+
cliVersion,
|
|
722
|
+
startedAt,
|
|
723
|
+
isShuttingDown,
|
|
724
|
+
getDurableDispatch,
|
|
725
|
+
getExecutor,
|
|
726
|
+
getTaskDriver,
|
|
727
|
+
});
|
|
652
728
|
const bot = options.createBot
|
|
653
729
|
? options.createBot(handler, options.dingtalkConfig)
|
|
654
730
|
: new DingTalkBot(handler, options.dingtalkConfig);
|
|
@@ -672,6 +748,7 @@ export async function createRuntimeContext(options) {
|
|
|
672
748
|
configureJobRuntime({
|
|
673
749
|
jobsStateDir: join(options.paths.appHomeDir, "state", "jobs"),
|
|
674
750
|
dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
|
|
751
|
+
...(options.jobSweepIntervalMs ? { sweepIntervalMs: options.jobSweepIntervalMs } : {}),
|
|
675
752
|
});
|
|
676
753
|
// Delegation runs get the same treatment (spec 040, D1/D7): persistence root, wake delivery,
|
|
677
754
|
// and the usage/archive authority, wired before any turn can start a run.
|
|
@@ -780,7 +857,7 @@ export async function createRuntimeContext(options) {
|
|
|
780
857
|
notify: (receipt) => bot.sendPlain(receipt.channelId, receipt.text),
|
|
781
858
|
getSettings: () => {
|
|
782
859
|
runtimeSettingsManager.reload();
|
|
783
|
-
return
|
|
860
|
+
return TASK_DRIVER_SETTINGS;
|
|
784
861
|
},
|
|
785
862
|
isEnabled: tasksToolEnabled,
|
|
786
863
|
});
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import type { ChannelContext, ProgressStyle } from "
|
|
2
|
-
import type { ChannelEvent } from "
|
|
1
|
+
import type { ChannelContext, ProgressStyle } from "../channel/channel-context.js";
|
|
2
|
+
import type { ChannelEvent } from "../channel/channel-event.js";
|
|
3
|
+
import type { ChannelStore } from "../channel/store.js";
|
|
3
4
|
import type { DingTalkBot } from "./dingtalk.js";
|
|
4
|
-
import type { ChannelStore } from "./store.js";
|
|
5
5
|
/**
|
|
6
6
|
* Build the delivery contract for one turn.
|
|
7
7
|
*
|
package/dist/runtime/delivery.js
CHANGED
|
@@ -55,6 +55,7 @@ class ChannelDeliveryController {
|
|
|
55
55
|
userName: this.event.userName,
|
|
56
56
|
channel: this.event.channelId,
|
|
57
57
|
ts: this.event.ts,
|
|
58
|
+
images: this.event.images,
|
|
58
59
|
},
|
|
59
60
|
// The group title when the transport supplied one; the raw id is the fallback so a
|
|
60
61
|
// synthetic event (which carries no conversation payload) still names its channel.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import type {
|
|
3
|
-
import type {
|
|
4
|
-
import type
|
|
1
|
+
import type { FinalDelivery, MediaSender, MediaSendResult, OutboundMedia, ProgressStyle } from "../channel/channel-context.js";
|
|
2
|
+
import type { ChannelEvent, InboundImage } from "../channel/channel-event.js";
|
|
3
|
+
import type { ChannelObservation } from "../channel/channel-index.js";
|
|
4
|
+
import { type RuntimeCommandName } from "../commands/catalog.js";
|
|
5
5
|
export type BusyMessageMode = "steer" | "followUp";
|
|
6
6
|
export type BusyMessageDefaultConfig = BusyMessageMode | "followup";
|
|
7
7
|
export type ResponseMode = "full_progress_then_plain_final" | "rolling_progress_then_plain_final" | "final_card_only";
|
|
@@ -69,6 +69,18 @@ export interface DingTalkHandler {
|
|
|
69
69
|
*/
|
|
70
70
|
runRuntimeCommand(event: DingTalkEvent, name: RuntimeCommandName, args: string): Promise<string>;
|
|
71
71
|
handleBusyMessage(event: DingTalkEvent, bot: DingTalkBot, mode: BusyMessageMode, queueText: string): Promise<BusyMessageResult>;
|
|
72
|
+
/**
|
|
73
|
+
* Persist one downloaded inbound image under the channel's `inbox/` (spec 049). Owned by
|
|
74
|
+
* bootstrap — it holds the workspace root — not the transport, which only knows how to fetch
|
|
75
|
+
* bytes over the DingTalk API. `mimeType` is `null` when magic-byte sniffing did not recognize
|
|
76
|
+
* a supported image format; the file is still persisted (for the archive/record) but the
|
|
77
|
+
* transport excludes it from the model-facing text marker. Returns `null` on a local I/O
|
|
78
|
+
* failure, surfaced to the user as "保存失败" — the rest of the message is still delivered.
|
|
79
|
+
*/
|
|
80
|
+
persistInboundImage?(channelId: string, image: {
|
|
81
|
+
data: Buffer;
|
|
82
|
+
mimeType: string | null;
|
|
83
|
+
}): Promise<InboundImage | null>;
|
|
72
84
|
}
|
|
73
85
|
export declare class DingTalkBot implements MediaSender {
|
|
74
86
|
private handler;
|
|
@@ -81,6 +93,8 @@ export declare class DingTalkBot implements MediaSender {
|
|
|
81
93
|
private convMeta;
|
|
82
94
|
private channelLastActiveAt;
|
|
83
95
|
private queues;
|
|
96
|
+
private inboundIngestQueue;
|
|
97
|
+
private pendingInboundIngestCount;
|
|
84
98
|
private client;
|
|
85
99
|
private lastSocketAvailableTime;
|
|
86
100
|
private activeMessageProcessing;
|
|
@@ -113,7 +127,6 @@ export declare class DingTalkBot implements MediaSender {
|
|
|
113
127
|
private clearReconnectTimer;
|
|
114
128
|
private clearReconnectDelay;
|
|
115
129
|
private clearAllTimers;
|
|
116
|
-
private sleep;
|
|
117
130
|
private waitForDelay;
|
|
118
131
|
private waitForSocketState;
|
|
119
132
|
private markClientDisconnected;
|
|
@@ -143,6 +156,14 @@ export declare class DingTalkBot implements MediaSender {
|
|
|
143
156
|
* Append a delta to the active card transcript.
|
|
144
157
|
*/
|
|
145
158
|
appendToCard(channelId: string, content: string, finalize?: boolean, failed?: boolean): Promise<boolean>;
|
|
159
|
+
/**
|
|
160
|
+
* Shared body of `replaceCard`/`appendToCard`: whether to open a fresh card differs between the
|
|
161
|
+
* two (a full-snapshot replace opens one for a finalize/failed close too; a delta append only
|
|
162
|
+
* opens one for genuinely new content), so that predicate stays keyed on `append` rather than
|
|
163
|
+
* being collapsed away — everything after it (stream, then drop the card on finalize/failed/a
|
|
164
|
+
* failed stream) is identical either way.
|
|
165
|
+
*/
|
|
166
|
+
private writeCard;
|
|
146
167
|
/**
|
|
147
168
|
* Finalize and remove the active card for a channel.
|
|
148
169
|
*/
|
|
@@ -177,6 +198,34 @@ export declare class DingTalkBot implements MediaSender {
|
|
|
177
198
|
* with a non-zero `errcode` on failure, so the body is inspected explicitly.
|
|
178
199
|
*/
|
|
179
200
|
private uploadMedia;
|
|
201
|
+
/**
|
|
202
|
+
* Two-step DingTalk inbound file download (spec 049): `messageFiles/download` exchanges the
|
|
203
|
+
* message's `downloadCode` for a short-lived `downloadUrl`, then that URL is fetched for the
|
|
204
|
+
* actual bytes. Both hops reuse `getAccessToken()` — the same app access token works across
|
|
205
|
+
* DingTalk's hosts, as the comment on `DINGTALK_OAPI` above explains for the outbound side.
|
|
206
|
+
*
|
|
207
|
+
* This runs from `onStreamMessage`'s per-channel ingestion queue, never from inside a turn: a
|
|
208
|
+
* busy channel can queue a message for minutes (`USER_MESSAGE_QUEUE_LIMIT`), and by the time a
|
|
209
|
+
* queued turn actually ran, a `downloadCode`/`downloadUrl` fetched only then could easily have
|
|
210
|
+
* already expired.
|
|
211
|
+
*
|
|
212
|
+
* `protected` so the deterministic e2e harness can override it and run this path with zero
|
|
213
|
+
* network, the same pattern `HarnessDingTalkBot` already uses for outbound calls.
|
|
214
|
+
*/
|
|
215
|
+
protected downloadMessageFile(downloadCode: string): Promise<{
|
|
216
|
+
data: Buffer;
|
|
217
|
+
} | null>;
|
|
218
|
+
/**
|
|
219
|
+
* Resolve one parsed message's image credentials into persisted `InboundImage`s and a text
|
|
220
|
+
* with every `[图片N]` marker either left as-is (success) or replaced with a reason (spec 049
|
|
221
|
+
* D8): a download failure, an unrecognized format, an oversized file, or a message that
|
|
222
|
+
* simply carried more images than `MAX_INBOUND_IMAGES_PER_MESSAGE` allows. A failure on one
|
|
223
|
+
* image never drops the rest of the message — only that one marker changes.
|
|
224
|
+
*
|
|
225
|
+
* No-op (no network call at all) when the message carries no image credentials, so a plain
|
|
226
|
+
* text message never pays for this method's existence.
|
|
227
|
+
*/
|
|
228
|
+
private resolveInboundAttachments;
|
|
180
229
|
/**
|
|
181
230
|
* POST a robot message with an arbitrary msgKey/msgParam, routing DM vs group
|
|
182
231
|
* to the correct endpoint. The single outbound path for every non-card message:
|
|
@@ -188,8 +237,13 @@ export declare class DingTalkBot implements MediaSender {
|
|
|
188
237
|
private streamCard;
|
|
189
238
|
private getAccessToken;
|
|
190
239
|
private refreshAccessToken;
|
|
191
|
-
private extractContent;
|
|
192
240
|
private onStreamMessage;
|
|
241
|
+
/**
|
|
242
|
+
* Command / busy / `/new` routing for one inbound event, ending in `enqueueStreamMessage`
|
|
243
|
+
* for a normal message. Split out of `onStreamMessage` so the deterministic e2e harness
|
|
244
|
+
* (spec 048) can exercise the real transport queue and busy semantics without a socket.
|
|
245
|
+
*/
|
|
246
|
+
routeInboundEvent(event: DingTalkEvent): Promise<void>;
|
|
193
247
|
/**
|
|
194
248
|
* Drop queued-but-not-started messages for a channel (e.g. on /stop) so they
|
|
195
249
|
* do not run after the user halts the current task. Returns dropped count.
|
|
@@ -200,6 +254,8 @@ export declare class DingTalkBot implements MediaSender {
|
|
|
200
254
|
* still unwind on its old queue object, while subsequent messages get a fresh queue.
|
|
201
255
|
*/
|
|
202
256
|
resetChannelQueue(channelId: string): number;
|
|
257
|
+
/** Test seam (spec 048): true when no channel queue has pending or in-flight work. */
|
|
258
|
+
allChannelQueuesIdle(): boolean;
|
|
203
259
|
private getQueue;
|
|
204
260
|
private getConversationMeta;
|
|
205
261
|
private setConversationMeta;
|