@oyasmi/pipiclaw 0.9.2-beta.4 → 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.
Files changed (76) hide show
  1. package/dist/agent/channel-runner.d.ts +32 -1
  2. package/dist/agent/channel-runner.js +112 -12
  3. package/dist/agent/context-budget.d.ts +9 -1
  4. package/dist/agent/context-budget.js +11 -5
  5. package/dist/agent/job-manager.d.ts +2 -0
  6. package/dist/agent/job-manager.js +1 -0
  7. package/dist/agent/session-events.js +2 -22
  8. package/dist/agent/types.d.ts +2 -1
  9. package/dist/channel/channel-context.d.ts +4 -0
  10. package/dist/channel/channel-event.d.ts +39 -0
  11. package/dist/channel/channel-event.js +11 -1
  12. package/dist/channel/project-scope-store.js +6 -11
  13. package/dist/channel/store.d.ts +7 -0
  14. package/dist/commands/catalog.d.ts +1 -1
  15. package/dist/memory/bootstrap.js +3 -5
  16. package/dist/memory/candidates.js +2 -4
  17. package/dist/memory/files.d.ts +0 -1
  18. package/dist/memory/files.js +6 -9
  19. package/dist/memory/maintenance-state.js +4 -0
  20. package/dist/runtime/bootstrap.d.ts +12 -6
  21. package/dist/runtime/bootstrap.js +144 -75
  22. package/dist/runtime/delivery.js +1 -0
  23. package/dist/runtime/dingtalk.d.ts +59 -3
  24. package/dist/runtime/dingtalk.js +192 -83
  25. package/dist/runtime/inbound-media.d.ts +60 -0
  26. package/dist/runtime/inbound-media.js +95 -0
  27. package/dist/runtime/task-driver.d.ts +7 -0
  28. package/dist/runtime/task-driver.js +23 -44
  29. package/dist/runtime/task-migration.d.ts +11 -0
  30. package/dist/runtime/task-migration.js +11 -0
  31. package/dist/security/command-guard.js +1 -3
  32. package/dist/security/config.d.ts +1 -1
  33. package/dist/security/config.js +8 -32
  34. package/dist/security/path-guard.js +1 -6
  35. package/dist/security/project-scope.js +1 -3
  36. package/dist/settings.d.ts +2 -2
  37. package/dist/settings.js +13 -20
  38. package/dist/shared/atomic-file.d.ts +2 -3
  39. package/dist/shared/atomic-file.js +8 -9
  40. package/dist/shared/config-diagnostic.d.ts +21 -0
  41. package/dist/shared/config-diagnostic.js +32 -0
  42. package/dist/shared/numeric.d.ts +7 -0
  43. package/dist/shared/numeric.js +19 -0
  44. package/dist/shared/text-utils.d.ts +10 -0
  45. package/dist/shared/text-utils.js +16 -0
  46. package/dist/shared/types.d.ts +23 -0
  47. package/dist/shared/types.js +12 -0
  48. package/dist/shared/with-timeout.d.ts +3 -0
  49. package/dist/shared/with-timeout.js +8 -0
  50. package/dist/subagents/discovery.d.ts +7 -7
  51. package/dist/subagents/discovery.js +27 -59
  52. package/dist/subagents/runs.d.ts +6 -0
  53. package/dist/subagents/runs.js +11 -0
  54. package/dist/subagents/tool.js +195 -128
  55. package/dist/subagents/workspace-lease.js +1 -3
  56. package/dist/tasks/control.d.ts +2 -0
  57. package/dist/tasks/control.js +2 -0
  58. package/dist/tasks/ledger.d.ts +0 -9
  59. package/dist/tasks/ledger.js +92 -158
  60. package/dist/tools/config.d.ts +1 -1
  61. package/dist/tools/config.js +9 -46
  62. package/dist/tools/skill.js +1 -3
  63. package/dist/tools/truncate.js +24 -28
  64. package/dist/tui/app.js +1 -1
  65. package/dist/web/config.js +3 -15
  66. package/examples/sub-agents/builder.md +1 -1
  67. package/examples/sub-agents/documenter.md +1 -1
  68. package/examples/sub-agents/explorer.md +4 -4
  69. package/examples/sub-agents/git-committer.md +4 -4
  70. package/examples/sub-agents/log-sifter.md +3 -3
  71. package/examples/sub-agents/planner.md +1 -1
  72. package/examples/sub-agents/reviewer.md +1 -1
  73. package/examples/sub-agents/worker.md +1 -1
  74. package/package.json +3 -2
  75. package/dist/agent/index.d.ts +0 -2
  76. package/dist/agent/index.js +0 -1
@@ -149,7 +149,7 @@ export async function applyChannelMemoryOps(channelDir, ops, timestamp = formatL
149
149
  if (ops.length === 0) {
150
150
  return result;
151
151
  }
152
- await ensureChannelMemoryFiles(channelDir);
152
+ ensureChannelMemoryFilesSync(channelDir);
153
153
  const path = getChannelMemoryPath(channelDir);
154
154
  const existing = await readOptionalTextFile(path);
155
155
  const lines = existing.replace(/\r/g, "").split("\n");
@@ -330,9 +330,6 @@ export function getChannelHistoryPath(channelDir) {
330
330
  export function getChannelSessionPath(channelDir) {
331
331
  return join(channelDir, "SESSION.md");
332
332
  }
333
- export async function ensureChannelMemoryFiles(channelDir) {
334
- ensureChannelMemoryFilesSync(channelDir);
335
- }
336
333
  export function ensureChannelMemoryFilesSync(channelDir) {
337
334
  const memoryPath = getChannelMemoryPath(channelDir);
338
335
  const historyPath = getChannelHistoryPath(channelDir);
@@ -358,7 +355,7 @@ export async function readChannelSession(channelDir) {
358
355
  return readOptionalTextFile(getChannelSessionPath(channelDir));
359
356
  }
360
357
  export async function rewriteChannelMemory(channelDir, content) {
361
- await ensureChannelMemoryFiles(channelDir);
358
+ ensureChannelMemoryFilesSync(channelDir);
362
359
  const path = getChannelMemoryPath(channelDir);
363
360
  await backupBeforeRewrite(channelDir, path);
364
361
  const nextContent = normalizeContent(content) || DEFAULT_CHANNEL_MEMORY;
@@ -366,14 +363,14 @@ export async function rewriteChannelMemory(channelDir, content) {
366
363
  await syncMemoryMetadata(channelDir, parseChannelMemoryEntries(nextContent));
367
364
  }
368
365
  export async function rewriteChannelHistory(channelDir, content) {
369
- await ensureChannelMemoryFiles(channelDir);
366
+ ensureChannelMemoryFilesSync(channelDir);
370
367
  const path = getChannelHistoryPath(channelDir);
371
368
  await backupBeforeRewrite(channelDir, path);
372
369
  const nextContent = normalizeContent(content) || DEFAULT_CHANNEL_HISTORY;
373
370
  await writeFileAtomically(path, nextContent);
374
371
  }
375
372
  export async function rewriteChannelSession(channelDir, content) {
376
- await ensureChannelMemoryFiles(channelDir);
373
+ ensureChannelMemoryFilesSync(channelDir);
377
374
  const nextContent = normalizeContent(content) || DEFAULT_CHANNEL_SESSION;
378
375
  await writeFileAtomically(getChannelSessionPath(channelDir), nextContent);
379
376
  }
@@ -390,7 +387,7 @@ export async function appendChannelHistoryArchive(channelDir, block) {
390
387
  if (!trimmedContent) {
391
388
  return;
392
389
  }
393
- await ensureChannelMemoryFiles(channelDir);
390
+ ensureChannelMemoryFilesSync(channelDir);
394
391
  const path = getChannelHistoryArchivePath(channelDir);
395
392
  const renderedBlock = [`## Archived ${block.timestamp}`, trimmedContent].join("\n\n");
396
393
  const currentSize = await stat(path)
@@ -414,7 +411,7 @@ export async function appendChannelHistoryBlock(channelDir, block) {
414
411
  if (!trimmedContent) {
415
412
  return;
416
413
  }
417
- await ensureChannelMemoryFiles(channelDir);
414
+ ensureChannelMemoryFilesSync(channelDir);
418
415
  const path = getChannelHistoryPath(channelDir);
419
416
  const existing = await readOptionalTextFile(path);
420
417
  const renderedBlock = [`## ${block.timestamp}`, trimmedContent].join("\n\n");
@@ -26,6 +26,10 @@ export function getMemoryMaintenanceStatePath(appHomeDir, channelId) {
26
26
  * `/`, and only matters until the next write moves the state to its canonical path — but the
27
27
  * state carries maintenance cadence and transcript cursors, so dropping it would silently
28
28
  * re-run structural maintenance and re-scan the transcript for every affected group.
29
+ *
30
+ * RETIRE AT v0.9.3, same rationale as the header comment in `../runtime/task-migration.js`:
31
+ * by the stable cut, every still-running group channel with a `/` in its id will have had its
32
+ * state folded onto the canonical path at least once, so this fallback read finds nothing.
29
33
  */
30
34
  function legacyStatePath(appHomeDir, channelId) {
31
35
  return getChannelDirName(channelId) === channelId
@@ -1,4 +1,4 @@
1
- import { type AgentRunner } from "../agent/index.js";
1
+ import type { AgentRunner } from "../agent/types.js";
2
2
  import type { ChannelEvent } from "../channel/channel-event.js";
3
3
  import { ChannelStore } from "../channel/store.js";
4
4
  import { type Executor } from "../executor.js";
@@ -6,6 +6,7 @@ import { PipiclawSettingsManager } from "../settings.js";
6
6
  import type { WakeTaskTransitionHooks } from "../tasks/store.js";
7
7
  import { type BootstrapIO, type BootstrapPaths } from "./app-home.js";
8
8
  import { DingTalkBot, type DingTalkConfig, type DingTalkHandler } from "./dingtalk.js";
9
+ import { TaskDriver } from "./task-driver.js";
9
10
  export interface BootstrapOptions {
10
11
  env?: NodeJS.ProcessEnv;
11
12
  io?: BootstrapIO;
@@ -55,6 +56,13 @@ export declare function forceEndStuckTurnAfterStop(input: {
55
56
  pollMs?: number;
56
57
  notify?: (text: string) => Promise<unknown>;
57
58
  }): Promise<boolean>;
59
+ /** The real `TaskDriver` class, or the minimal test-injectable shape `createTaskDriver` may
60
+ * supply instead — `taskDriver.nudge?.()` is the only member either side needs to guarantee. */
61
+ type TaskDriverLike = TaskDriver | {
62
+ start(): void;
63
+ stop(): void;
64
+ nudge?(): void;
65
+ };
58
66
  interface RuntimeContextOptions {
59
67
  paths: BootstrapPaths;
60
68
  dingtalkConfig: DingTalkConfig;
@@ -69,11 +77,9 @@ interface RuntimeContextOptions {
69
77
  stop(): void;
70
78
  };
71
79
  memoryMaintenanceSchedulerIntervalMs?: number;
72
- createTaskDriver?: () => {
73
- start(): void;
74
- stop(): void;
75
- nudge?(): void;
76
- };
80
+ /** Background-job sweep cadence override (tests use a short one for timely completion wakes). */
81
+ jobSweepIntervalMs?: number;
82
+ createTaskDriver?: () => TaskDriverLike;
77
83
  /** Receives raw SDK session events after subscription, without changing runtime handling. */
78
84
  observer?: (event: unknown, channelId: string) => void;
79
85
  /** Receives TaskDriver dispatch outcomes; used only by isolated evaluation workers. */
@@ -1,8 +1,9 @@
1
- import { join } from "path";
1
+ import { mkdir, writeFile } from "fs/promises";
2
+ import { join, relative } from "path";
2
3
  import { channelEffectCount, noteTaskEffects, taskEffectCount } from "../agent/effect-ledger.js";
3
- import { createRunner } from "../agent/index.js";
4
4
  import { channelRunningJobLines, configureJobRuntime, restoreChannelJobs } from "../agent/job-manager.js";
5
5
  import { loadDetachedMaintenanceContext } from "../agent/maintenance-context.js";
6
+ import { createRunner } from "../agent/runner-factory.js";
6
7
  import { renderStatus } from "../agent/status-render.js";
7
8
  import { scanWorkspaceForInterruptedTurns } from "../agent/turn-recovery.js";
8
9
  import { createFreshActiveSession } from "../channel/active-session-store.js";
@@ -19,10 +20,12 @@ import { defaultModel } from "../models/utils.js";
19
20
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
20
21
  import { flushSecurityLogs } from "../security/logger.js";
21
22
  import { resolveProjectAccessPolicy } from "../security/project-scope.js";
22
- import { PipiclawSettingsManager } from "../settings.js";
23
+ import { PipiclawSettingsManager, TASK_DRIVER_SETTINGS } from "../settings.js";
23
24
  import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
24
25
  import { fileStamp } from "../shared/file-stamp.js";
26
+ import { localStampForFilename } from "../shared/local-time.js";
25
27
  import { errorMessage } from "../shared/text-utils.js";
28
+ import { sleepUnref } from "../shared/with-timeout.js";
26
29
  import { loadDetachedSubAgentDiscovery } from "../subagents/detached-discovery.js";
27
30
  import { configureSubAgentRuntime, getSubAgentRunManager, restoreAllSubAgentRuns, stopSubAgentGarbageCollector, } from "../subagents/runs.js";
28
31
  import { readActiveTasks } from "../tasks/ledger.js";
@@ -35,6 +38,7 @@ import { DingTalkBot, } from "./dingtalk.js";
35
38
  import { DurableDispatchService } from "./durable-dispatch.js";
36
39
  import { handleEventsCommand as runEventsCommand } from "./event-commands.js";
37
40
  import { createEventsWatcher } from "./events.js";
41
+ import { extensionForMimeType } from "./inbound-media.js";
38
42
  import { handleProjectCommand as runProjectCommand } from "./project-commands.js";
39
43
  import { installLlmProxy } from "./proxy.js";
40
44
  import { handleSkillsCommand as runSkillsCommand } from "./skill-commands.js";
@@ -90,6 +94,19 @@ async function evictIdleRunnersOverCap(channelRunners) {
90
94
  function isNoRunningTaskQueueError(err) {
91
95
  return err instanceof Error && err.message === "No task is currently running.";
92
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
+ }
93
110
  /**
94
111
  * The `runRuntimeCommand` names usable on the idle-turn path — every `BUILT_IN_COMMANDS` entry
95
112
  * *not* marked `runnerHandled`, i.e. every stateless report. `context` is the one deliberate
@@ -110,12 +127,6 @@ function isIdleRuntimeCommandName(name) {
110
127
  */
111
128
  const STOP_FORCE_END_GRACE_MS = 15_000;
112
129
  const STOP_FORCE_END_POLL_MS = 250;
113
- function sleepUnref(ms) {
114
- return new Promise((resolve) => {
115
- const timer = setTimeout(resolve, ms);
116
- timer.unref?.();
117
- });
118
- }
119
130
  /**
120
131
  * Watchdog for `/stop`: release the channel if the stopped turn has not ended
121
132
  * once the grace window elapses. Returns true when it had to force the release.
@@ -135,65 +146,14 @@ export async function forceEndStuckTurnAfterStop(input) {
135
146
  .catch(() => undefined);
136
147
  return true;
137
148
  }
138
- export async function createRuntimeContext(options) {
139
- const startServices = options.startServices ?? true;
140
- const registerSignalHandlers = options.registerSignalHandlers ?? true;
141
- const store = new ChannelStore({ workingDir: options.paths.workspaceDir });
142
- const runtimeSettingsManager = options.settingsManager ?? new PipiclawSettingsManager(options.paths.appHomeDir);
143
- log.configureLogging(runtimeSettingsManager.getLoggingSettings());
144
- const startedAt = Date.now();
145
- const cliVersion = readCliVersion();
146
- const channelRunners = new Map();
147
- const sessionResetChains = new Map();
148
- const activeTasks = new Set();
149
- /** Channels with a `/stop` watchdog in flight, so a burst of `/stop` starts only one. */
150
- const stopWatchdogs = new Set();
151
- // `workspace/CHANNELS.md`: names every channel id so the workspace, the logs and the agent
152
- // stop dealing in `group_cid...`. Writes are debounced internally (see channel-index.ts).
153
- const channelIndex = createChannelIndex({ workspaceDir: options.paths.workspaceDir });
154
- let durableDispatch;
155
- let shuttingDown = false;
156
- let shutdownPromise = null;
157
- const archiveIncomingMessage = async (channelId, message, contextLabel) => {
158
- try {
159
- await store.logMessage(channelId, message);
160
- }
161
- catch (err) {
162
- log.logWarning(`[${channelId}] Failed to archive ${contextLabel}`, errorMessage(err));
163
- }
164
- };
165
- const getRunner = (channelId) => {
166
- const existing = channelRunners.get(channelId);
167
- if (existing) {
168
- // Re-insert to move this channel to the end (most-recently-used) of the Map's
169
- // iteration order, which evictIdleRunnersOverCap relies on.
170
- channelRunners.delete(channelId);
171
- channelRunners.set(channelId, existing);
172
- return existing;
173
- }
174
- const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
175
- ensureChannelMemoryFilesSync(channelDir);
176
- const runner = createRunner(channelId, channelDir, {
177
- appHomeDir: options.paths.appHomeDir,
178
- authConfigPath: options.paths.authConfigPath,
179
- modelsConfigPath: options.paths.modelsConfigPath,
180
- settingsManager: runtimeSettingsManager,
181
- onSessionEvent: options.observer,
182
- // The DingTalk bot is the media sender for this transport; enables `send_media`.
183
- // `bot` is defined below in this same scope and initialized before any message
184
- // (and thus any getRunner call) can arrive.
185
- mediaSender: bot,
186
- });
187
- channelRunners.set(channelId, runner);
188
- void evictIdleRunnersOverCap(channelRunners);
189
- return runner;
190
- };
149
+ function createDingTalkHandler(deps) {
150
+ const { options, store, channelRunners, sessionResetChains, activeTasks, stopWatchdogs, channelIndex, archiveIncomingMessage, getRunner, cliVersion, startedAt, isShuttingDown, getDurableDispatch, getExecutor, getTaskDriver, } = deps;
191
151
  const handler = {
192
152
  isRunning(channelId) {
193
153
  return channelRunners.get(channelId)?.isBusy() ?? false;
194
154
  },
195
155
  noteChannelActivity(observation) {
196
- if (shuttingDown)
156
+ if (isShuttingDown())
197
157
  return;
198
158
  channelIndex.note(observation);
199
159
  },
@@ -221,7 +181,7 @@ export async function createRuntimeContext(options) {
221
181
  void runner.abort().catch((err) => {
222
182
  log.logWarning(`[${channelId}] Failed to abort run`, errorMessage(err));
223
183
  });
224
- void durableDispatch
184
+ void getDurableDispatch()
225
185
  ?.cancelChannel(channelId)
226
186
  .then((canceled) => {
227
187
  if (canceled)
@@ -250,7 +210,7 @@ export async function createRuntimeContext(options) {
250
210
  return { pausedTaskId };
251
211
  },
252
212
  async handleNewSession(event, _bot) {
253
- if (shuttingDown)
213
+ if (isShuttingDown())
254
214
  return;
255
215
  const previous = sessionResetChains.get(event.channelId) ?? Promise.resolve();
256
216
  const reset = previous
@@ -292,6 +252,7 @@ export async function createRuntimeContext(options) {
292
252
  userName: event.userName,
293
253
  text: event.text,
294
254
  isBot: false,
255
+ images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
295
256
  }, "/new command");
296
257
  }
297
258
  catch (error) {
@@ -335,7 +296,7 @@ export async function createRuntimeContext(options) {
335
296
  // unique per invocation rather than sharing the driver's occurrence key (D1).
336
297
  const now = Date.now();
337
298
  const driverEvent = createTaskDriverEvent(event.channelId, entry, now);
338
- return ((await durableDispatch?.dispatch({
299
+ return ((await getDurableDispatch()?.dispatch({
339
300
  ...driverEvent,
340
301
  dispatchId: `task:${event.channelId}:${entry.id}:manual:${new Date(now).toISOString()}`,
341
302
  })) ?? false);
@@ -403,7 +364,7 @@ export async function createRuntimeContext(options) {
403
364
  }
404
365
  },
405
366
  async handleBusyMessage(event, bot, mode, queueText) {
406
- if (shuttingDown) {
367
+ if (isShuttingDown()) {
407
368
  return { kind: "handled" };
408
369
  }
409
370
  const runner = getRunner(event.channelId);
@@ -428,7 +389,7 @@ export async function createRuntimeContext(options) {
428
389
  return { kind: "requeue", text: trimmedQueueText };
429
390
  }
430
391
  try {
431
- await runner.queueSteer(trimmedQueueText, event.userName);
392
+ await runner.queueSteer(trimmedQueueText, event.userName, event.images);
432
393
  await archiveIncomingMessage(event.channelId, {
433
394
  date: new Date().toISOString(),
434
395
  ts: event.ts,
@@ -438,6 +399,7 @@ export async function createRuntimeContext(options) {
438
399
  isBot: false,
439
400
  deliveryMode: mode,
440
401
  skipContextSync: true,
402
+ images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
441
403
  }, `${mode} message`);
442
404
  const confirmation = event.text.trim().startsWith("/")
443
405
  ? "已作为 steer 排队,当前工具步骤结束后生效。"
@@ -460,18 +422,43 @@ export async function createRuntimeContext(options) {
460
422
  return { kind: "handled" };
461
423
  }
462
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
+ },
463
450
  reserveEvent(event) {
464
451
  // This must remain synchronous. DingTalkBot calls it before awaiting the queued
465
452
  // handler, making the busy state observable to another message in the same tick.
466
453
  getRunner(event.channelId).beginTurn(event.text);
467
454
  },
468
455
  async handleEvent(event, bot, _isEvent) {
469
- if (shuttingDown) {
456
+ if (isShuttingDown()) {
470
457
  log.logInfo(`[${event.channelId}] Ignoring event during shutdown`);
471
458
  return;
472
459
  }
473
460
  const runner = getRunner(event.channelId);
474
- await durableDispatch?.markStarted(event.dispatchId);
461
+ await getDurableDispatch()?.markStarted(event.dispatchId);
475
462
  let structuredWakeFinalized = event.internalWake === undefined;
476
463
  const task = (async () => {
477
464
  try {
@@ -487,6 +474,7 @@ export async function createRuntimeContext(options) {
487
474
  text: event.text,
488
475
  isBot: false,
489
476
  skipContextSync: Boolean(builtInCommand),
477
+ images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
490
478
  }, "user message");
491
479
  // Background wakes deliver their result, not their process: no progress card, no
492
480
  // thinking stream, nothing to delete when the check-in ends `[SILENT]`. An "awaited"
@@ -568,7 +556,7 @@ export async function createRuntimeContext(options) {
568
556
  let recoveredJobTaskId;
569
557
  if (jobMatch) {
570
558
  const [, jobId, jobTaskId] = jobMatch;
571
- const claimed = await claimVerifiedJobWake(event, options.paths.workspaceDir, executor, options.wakeTransitionHooks?.job);
559
+ const claimed = await claimVerifiedJobWake(event, options.paths.workspaceDir, getExecutor(), options.wakeTransitionHooks?.job);
572
560
  if (claimed) {
573
561
  if (claimed.activated)
574
562
  recoveredJobTaskId = claimed.taskId;
@@ -639,13 +627,13 @@ export async function createRuntimeContext(options) {
639
627
  }
640
628
  finally {
641
629
  if (structuredWakeFinalized)
642
- await durableDispatch?.markCompleted(event.dispatchId);
630
+ await getDurableDispatch()?.markCompleted(event.dispatchId);
643
631
  else
644
- await durableDispatch?.markRetryable(event.dispatchId);
632
+ await getDurableDispatch()?.markRetryable(event.dispatchId);
645
633
  runner.endTurn();
646
634
  // A finished turn may have written task files (progress/complete/set); rescan
647
635
  // now so a continuing task chain advances immediately instead of after a full sleep.
648
- taskDriver.nudge?.();
636
+ getTaskDriver().nudge?.();
649
637
  }
650
638
  })();
651
639
  activeTasks.add(task);
@@ -657,6 +645,86 @@ export async function createRuntimeContext(options) {
657
645
  }
658
646
  },
659
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
+ });
660
728
  const bot = options.createBot
661
729
  ? options.createBot(handler, options.dingtalkConfig)
662
730
  : new DingTalkBot(handler, options.dingtalkConfig);
@@ -680,6 +748,7 @@ export async function createRuntimeContext(options) {
680
748
  configureJobRuntime({
681
749
  jobsStateDir: join(options.paths.appHomeDir, "state", "jobs"),
682
750
  dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
751
+ ...(options.jobSweepIntervalMs ? { sweepIntervalMs: options.jobSweepIntervalMs } : {}),
683
752
  });
684
753
  // Delegation runs get the same treatment (spec 040, D1/D7): persistence root, wake delivery,
685
754
  // and the usage/archive authority, wired before any turn can start a run.
@@ -788,7 +857,7 @@ export async function createRuntimeContext(options) {
788
857
  notify: (receipt) => bot.sendPlain(receipt.channelId, receipt.text),
789
858
  getSettings: () => {
790
859
  runtimeSettingsManager.reload();
791
- return runtimeSettingsManager.getTaskDriverSettings();
860
+ return TASK_DRIVER_SETTINGS;
792
861
  },
793
862
  isEnabled: tasksToolEnabled,
794
863
  });
@@ -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,5 +1,5 @@
1
1
  import type { FinalDelivery, MediaSender, MediaSendResult, OutboundMedia, ProgressStyle } from "../channel/channel-context.js";
2
- import type { ChannelEvent } from "../channel/channel-event.js";
2
+ import type { ChannelEvent, InboundImage } from "../channel/channel-event.js";
3
3
  import type { ChannelObservation } from "../channel/channel-index.js";
4
4
  import { type RuntimeCommandName } from "../commands/catalog.js";
5
5
  export type BusyMessageMode = "steer" | "followUp";
@@ -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;