@oyasmi/pipiclaw 0.9.2-beta.4 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
@@ -2,6 +2,7 @@ import { Agent, type ThinkingLevel } from "@earendil-works/pi-agent-core";
2
2
  import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import { AgentSession, SettingsManager as SDKSettingsManager, SessionManager } from "@earendil-works/pi-coding-agent";
4
4
  import type { ChannelContext } from "../channel/channel-context.js";
5
+ import { type InboundImage } from "../channel/channel-event.js";
5
6
  import type { ChannelStore } from "../channel/store.js";
6
7
  import { type RunnerBuiltInCommand } from "../commands/catalog.js";
7
8
  import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
@@ -48,6 +49,13 @@ export declare class ChannelRunner implements AgentRunner {
48
49
  private readonly memoryActivityRecorder;
49
50
  private readonly sessionResourceGate;
50
51
  private readonly sessionReady;
52
+ /**
53
+ * Flips true only once `initializeSession` has fully assigned `this.session`
54
+ * and loaded its resources. Synchronous dispatch-path callers (`isKnownSlashCommand`)
55
+ * must not touch `this.session` before this — the model runtime takes hundreds
56
+ * of ms to build and the first message can arrive first (spec 048 F2).
57
+ */
58
+ private sessionInitialized;
51
59
  private sessionRuntime;
52
60
  private sessionUnsubscribe?;
53
61
  private subAgentDiscovery;
@@ -103,7 +111,7 @@ export declare class ChannelRunner implements AgentRunner {
103
111
  * full LLM turn.
104
112
  */
105
113
  isKnownSlashCommand(text: string): boolean;
106
- queueSteer(text: string, userName?: string): Promise<void>;
114
+ queueSteer(text: string, userName?: string, images?: InboundImage[]): Promise<void>;
107
115
  flushMemoryForShutdown(): Promise<void>;
108
116
  dispose(): Promise<void>;
109
117
  getMemoryMaintenanceContext(): Promise<MemoryMaintenanceRuntimeContext>;
@@ -158,6 +166,29 @@ export declare class ChannelRunner implements AgentRunner {
158
166
  */
159
167
  private persistOversizedInput;
160
168
  private formatUserMessage;
169
+ /**
170
+ * Turn `InboundImage`s (already downloaded and persisted by the transport, spec 049) into the
171
+ * `ImageContent[]` `AgentSession.prompt`/`steer` accept, plus any notices to surface to the
172
+ * user about images that did not make it into this turn.
173
+ *
174
+ * Two gates apply, both fail *open* toward "still deliver the message" rather than dropping
175
+ * the whole turn over one bad attachment:
176
+ *
177
+ * - The current model's `input` capability (spec 049 D7). A model that does not declare
178
+ * `"image"` support has its image blocks silently replaced with a text placeholder by the
179
+ * SDK's provider layer — exactly the failure this spec exists to fix, so it is checked
180
+ * explicitly here rather than trusted to fail loudly on its own. Re-checked on every call
181
+ * (including a mid-turn steer after a model fallback), since a fallback model's capability
182
+ * can differ from the one the turn started with.
183
+ * - A defense-in-depth size re-check against `MAX_INBOUND_IMAGE_BYTES`. The transport already
184
+ * enforces this at download time, but the check is cheap and free of assumptions about how
185
+ * an `InboundImage` reached this method.
186
+ *
187
+ * An image already marked `unsupportedFormat` (sniffing failed at download time) is skipped
188
+ * without its own notice — the `[图片N:格式不支持,已保存]` marker already in the message text
189
+ * covers it.
190
+ */
191
+ private prepareInboundImages;
161
192
  /**
162
193
  * Single source of truth for the busy-message window: steer is accepted while
163
194
  * the prompt is being assembled ("preparing") or while the agent loop is
@@ -4,6 +4,7 @@ import { AgentSession, AgentSessionRuntime, convertToLlm, createExtensionRuntime
4
4
  import { mkdir, readFile, writeFile } from "fs/promises";
5
5
  import { dirname, join, resolve } from "path";
6
6
  import { commitActiveSessionRef, resolveActiveSessionFile } from "../channel/active-session-store.js";
7
+ import { MAX_INBOUND_IMAGE_BYTES } from "../channel/channel-event.js";
7
8
  import { resolveProjectScope } from "../channel/project-scope-store.js";
8
9
  import { isKnownCommandName, renderBuiltInHelp, slashCommandName, } from "../commands/catalog.js";
9
10
  import * as log from "../log.js";
@@ -19,6 +20,7 @@ import { getApiKeyForModel } from "../models/api-keys.js";
19
20
  import { createModelRuntime, defaultModel, findExactModelReferenceMatch, formatModelReference, hasKnownModelPricing, resolveInitialModel, wrapModelRegistry, } from "../models/utils.js";
20
21
  import { loadRuntimePlaybookCatalog, selectRuntimePlaybooks } from "../playbooks/catalog.js";
21
22
  import { resolveProjectAccessPolicy } from "../security/project-scope.js";
23
+ import { TASK_DIGEST_SETTINGS } from "../settings.js";
22
24
  import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
23
25
  import { formatLocalTime, localStampForFilename, parseLocalTime } from "../shared/local-time.js";
24
26
  import { errorMessage } from "../shared/text-utils.js";
@@ -27,6 +29,7 @@ import { withTimeout } from "../shared/with-timeout.js";
27
29
  import { discoverSubAgents } from "../subagents/discovery.js";
28
30
  import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
29
31
  import { createPipiclawTools } from "../tools/index.js";
32
+ import { formatSize } from "../tools/truncate.js";
30
33
  import { getUsageLedger } from "../usage/ledger.js";
31
34
  import { createCommandExtension } from "./command-extension.js";
32
35
  import { estimateIncomingMessageTokens, getPreventiveCompactionDecision } from "./context-budget.js";
@@ -126,6 +129,13 @@ const SESSION_RELOAD_TIMEOUT_MS = 30_000;
126
129
  export class ChannelRunner {
127
130
  constructor(channelId, channelDir, paths, deps) {
128
131
  this.ledger = getUsageLedger();
132
+ /**
133
+ * Flips true only once `initializeSession` has fully assigned `this.session`
134
+ * and loaded its resources. Synchronous dispatch-path callers (`isKnownSlashCommand`)
135
+ * must not touch `this.session` before this — the model runtime takes hundreds
136
+ * of ms to build and the first message can arrive first (spec 048 F2).
137
+ */
138
+ this.sessionInitialized = false;
129
139
  this.currentTools = [];
130
140
  this.firstTurnMemoryBootstrapPending = true;
131
141
  /** Mirror of `tools.tasks.enabled` from the last tools-config load (see buildRuntimeTools). */
@@ -351,16 +361,27 @@ export class ChannelRunner {
351
361
  recalledMemory: recalledContextText,
352
362
  });
353
363
  promptText = assembled.text;
364
+ // Resolved before the compaction estimate below (which needs the image count) and
365
+ // refreshed inside `setModel` further down if a fallback switches models mid-turn
366
+ // (spec 049 D7) — a model's image support is looked up here explicitly because the
367
+ // SDK's own handling of an unsupported model is to silently replace each image block
368
+ // with a text placeholder.
369
+ let preparedImages = await this.prepareInboundImages(ctx.message.images);
370
+ for (const notice of preparedImages.notices) {
371
+ await ctx.respondInThread(notice);
372
+ }
354
373
  // Estimated against the fully assembled prompt (recall + task digest + bootstrap all
355
374
  // included above), not just the bare user message — those pieces can add thousands of
356
375
  // characters and must count against the projected context usage this guard is checking.
357
- await this.maybeRunPreventiveCompactionForIncomingText(promptText);
376
+ // Each image adds a fixed per-image estimate on top of the text: three attached photos
377
+ // can by themselves push a turn over the threshold that would trigger this guard.
378
+ await this.maybeRunPreventiveCompactionForIncomingText(promptText, preparedImages.images.length);
358
379
  this.lastTurnContextStats = assembled.stats;
359
380
  const fallbackDeps = {
360
381
  prompt: async (text) => {
361
382
  try {
362
383
  await this.sessionResourceGate.runPrompt(async () => {
363
- await this.session.prompt(text);
384
+ await this.session.prompt(text, preparedImages.images.length > 0 ? { images: preparedImages.images } : undefined);
364
385
  promptSubmitted = true;
365
386
  if (bootstrapPrepared)
366
387
  this.firstTurnMemoryBootstrapPending = false;
@@ -394,6 +415,13 @@ export class ChannelRunner {
394
415
  resolveFallbackModel: () => this.resolveFallbackModel(),
395
416
  setModel: async (model) => {
396
417
  await this.setModelWithThinkingPreservation(model);
418
+ // The fallback model's vision support can differ from the one this turn started
419
+ // on; re-resolve against it rather than resend whatever was prepared for the
420
+ // model that just failed.
421
+ preparedImages = await this.prepareInboundImages(ctx.message.images);
422
+ for (const notice of preparedImages.notices) {
423
+ await ctx.respondInThread(notice);
424
+ }
397
425
  },
398
426
  notifySwitch: (from, to, errorSummary) => {
399
427
  fallbackTargetRef = to;
@@ -593,6 +621,10 @@ export class ChannelRunner {
593
621
  }
594
622
  async handleBuiltinCommand(ctx, command) {
595
623
  try {
624
+ // `/help` and `/context` read `this.session` (prompt templates, active model).
625
+ // The session runtime is built asynchronously after construction, so a command
626
+ // that lands before it is ready would otherwise hit a TypeError (spec 048 F2).
627
+ await this.ensureSessionReady();
596
628
  switch (command.name) {
597
629
  case "help":
598
630
  await this.sendCommandReply(ctx, this.renderHelpWithDiscovery(command.args), "help");
@@ -642,10 +674,17 @@ export class ChannelRunner {
642
674
  if (isKnownCommandName(name, this.currentSkills.skills.map((skill) => skill.name.toLowerCase()))) {
643
675
  return true;
644
676
  }
677
+ // Synchronous dispatch-path call: before the session runtime finishes building,
678
+ // fall back to the static catalog + skills only. Misclassifying a prompt template
679
+ // as "unknown" for the first few hundred ms after a runner is created is far
680
+ // cheaper than throwing on the dispatch main path (spec 048 F2/D7).
681
+ if (!this.sessionInitialized) {
682
+ return false;
683
+ }
645
684
  return this.session.promptTemplates.some((template) => template.name.toLowerCase() === name);
646
685
  }
647
- async queueSteer(text, userName) {
648
- await this.queueBusyMessage(this.requireQueuedMessage(text, "steer"), userName);
686
+ async queueSteer(text, userName, images) {
687
+ await this.queueBusyMessage(this.requireQueuedMessage(text, "steer"), userName, images);
649
688
  }
650
689
  async flushMemoryForShutdown() {
651
690
  await this.flushMemoryActivity();
@@ -869,6 +908,63 @@ export class ChannelRunner {
869
908
  formatUserMessage(text, userName, now = new Date()) {
870
909
  return `[${formatLocalTime(now)}] [${userName || "unknown"}]: ${text}`;
871
910
  }
911
+ /**
912
+ * Turn `InboundImage`s (already downloaded and persisted by the transport, spec 049) into the
913
+ * `ImageContent[]` `AgentSession.prompt`/`steer` accept, plus any notices to surface to the
914
+ * user about images that did not make it into this turn.
915
+ *
916
+ * Two gates apply, both fail *open* toward "still deliver the message" rather than dropping
917
+ * the whole turn over one bad attachment:
918
+ *
919
+ * - The current model's `input` capability (spec 049 D7). A model that does not declare
920
+ * `"image"` support has its image blocks silently replaced with a text placeholder by the
921
+ * SDK's provider layer — exactly the failure this spec exists to fix, so it is checked
922
+ * explicitly here rather than trusted to fail loudly on its own. Re-checked on every call
923
+ * (including a mid-turn steer after a model fallback), since a fallback model's capability
924
+ * can differ from the one the turn started with.
925
+ * - A defense-in-depth size re-check against `MAX_INBOUND_IMAGE_BYTES`. The transport already
926
+ * enforces this at download time, but the check is cheap and free of assumptions about how
927
+ * an `InboundImage` reached this method.
928
+ *
929
+ * An image already marked `unsupportedFormat` (sniffing failed at download time) is skipped
930
+ * without its own notice — the `[图片N:格式不支持,已保存]` marker already in the message text
931
+ * covers it.
932
+ */
933
+ async prepareInboundImages(images) {
934
+ if (!images || images.length === 0) {
935
+ return { images: [], notices: [] };
936
+ }
937
+ const model = this.session.model ?? this.activeModel;
938
+ if (!model.input.includes("image")) {
939
+ const modelRef = formatModelReference(model);
940
+ return {
941
+ images: [],
942
+ notices: [
943
+ `⚠️ 当前模型 ${modelRef} 不支持图片输入,收到的图片已保存但未加入本轮上下文:\n` +
944
+ images.map((image) => `- \`${image.path}\``).join("\n") +
945
+ "\n可以切换到支持视觉的模型后让我 read 该文件。",
946
+ ],
947
+ };
948
+ }
949
+ const contents = [];
950
+ const notices = [];
951
+ for (const image of images) {
952
+ if (image.unsupportedFormat)
953
+ continue;
954
+ if (image.byteSize > MAX_INBOUND_IMAGE_BYTES) {
955
+ notices.push(`⚠️ 图片 \`${image.path}\`(${formatSize(image.byteSize)})超过 ${formatSize(MAX_INBOUND_IMAGE_BYTES)} 上限,未加入本轮上下文,可以让我 read 该文件查看。`);
956
+ continue;
957
+ }
958
+ try {
959
+ const data = await readFile(image.path);
960
+ contents.push({ type: "image", data: data.toString("base64"), mimeType: image.mimeType });
961
+ }
962
+ catch (error) {
963
+ notices.push(`⚠️ 图片 \`${image.path}\` 读取失败:${errorMessage(error)}`);
964
+ }
965
+ }
966
+ return { images: contents, notices };
967
+ }
872
968
  /**
873
969
  * Single source of truth for the busy-message window: steer is accepted while
874
970
  * the prompt is being assembled ("preparing") or while the agent loop is
@@ -884,7 +980,7 @@ export class ChannelRunner {
884
980
  }
885
981
  throw new Error("No task is currently running.");
886
982
  }
887
- async queueBusyMessage(text, userName) {
983
+ async queueBusyMessage(text, userName, images) {
888
984
  this.assertBusyWindowOpen();
889
985
  await this.ensureSessionReady();
890
986
  const oversized = text.replace(/\r/g, "").trim().length > MAX_USER_MESSAGE_CHARS;
@@ -894,11 +990,15 @@ export class ChannelRunner {
894
990
  log.logWarning(`[${this.channelId}] Queued message exceeded ${MAX_USER_MESSAGE_CHARS} chars and was clipped`);
895
991
  }
896
992
  const queuedMessage = this.formatUserMessage(clippedText, userName);
897
- await this.maybeRunPreventiveCompactionForIncomingText(queuedMessage);
993
+ const preparedImages = await this.prepareInboundImages(images);
994
+ for (const notice of preparedImages.notices) {
995
+ await this.runState.ctx?.respondInThread(notice);
996
+ }
997
+ await this.maybeRunPreventiveCompactionForIncomingText(queuedMessage, preparedImages.images.length);
898
998
  this.assertBusyWindowOpen();
899
999
  const queueMessage = async () => {
900
1000
  this.assertBusyWindowOpen();
901
- await this.session.steer(queuedMessage);
1001
+ await this.session.steer(queuedMessage, preparedImages.images.length > 0 ? preparedImages.images : undefined);
902
1002
  };
903
1003
  await this.sessionResourceGate.runPrompt(queueMessage);
904
1004
  }
@@ -1024,6 +1124,7 @@ export class ChannelRunner {
1024
1124
  this.subscribeToSessionEvents();
1025
1125
  await this.reloadSessionResources();
1026
1126
  await this.bindSessionExtensions();
1127
+ this.sessionInitialized = true;
1027
1128
  }
1028
1129
  async reloadSessionResources() {
1029
1130
  this.settingsManager.reload();
@@ -1066,11 +1167,11 @@ export class ChannelRunner {
1066
1167
  async ensureSessionReady() {
1067
1168
  await this.sessionReady;
1068
1169
  }
1069
- async maybeRunPreventiveCompactionForIncomingText(incomingText) {
1170
+ async maybeRunPreventiveCompactionForIncomingText(incomingText, imageCount = 0) {
1070
1171
  const currentModel = this.session.model ?? this.activeModel;
1071
1172
  const contextUsage = this.session.getContextUsage();
1072
1173
  const contextTokens = contextUsage?.tokens;
1073
- const incomingTokens = estimateIncomingMessageTokens(incomingText);
1174
+ const incomingTokens = estimateIncomingMessageTokens(incomingText, imageCount);
1074
1175
  const decision = getPreventiveCompactionDecision(contextTokens, incomingTokens, currentModel.contextWindow);
1075
1176
  if (!decision.shouldCompact) {
1076
1177
  return;
@@ -1370,11 +1471,10 @@ export class ChannelRunner {
1370
1471
  }
1371
1472
  /** Gated by the same master autonomy switch as the task_* tools and the TaskDriver. */
1372
1473
  buildTaskDigestForTurn() {
1373
- const taskDigestSettings = this.settingsManager.getTaskDigestSettings();
1374
1474
  return buildTaskDigest({
1375
1475
  channelDir: this.channelDir,
1376
- maxTasks: taskDigestSettings.maxTasks,
1377
- maxChars: taskDigestSettings.maxChars,
1476
+ maxTasks: TASK_DIGEST_SETTINGS.maxTasks,
1477
+ maxChars: TASK_DIGEST_SETTINGS.maxChars,
1378
1478
  maxUnits: TASK_AGENDA_MAX_UNITS,
1379
1479
  });
1380
1480
  }
@@ -1,4 +1,12 @@
1
1
  export declare const PREVENTIVE_COMPACTION_THRESHOLD_RATIO = 0.75;
2
+ /**
3
+ * Rough per-image token cost (spec 049), used only to keep the preventive-compaction projection
4
+ * honest when a turn carries inbound images — providers vary (roughly 250–1600 tokens per image
5
+ * depending on resolution/provider), so this is a conservative single constant rather than a
6
+ * per-provider table: the guard only needs to be in the right ballpark to decide whether to
7
+ * compact before sending, not to predict the exact bill.
8
+ */
9
+ export declare const ESTIMATED_TOKENS_PER_IMAGE = 1200;
2
10
  export interface PreventiveCompactionDecision {
3
11
  shouldCompact: boolean;
4
12
  projectedTokens: number | null;
@@ -13,5 +21,5 @@ export interface PreventiveCompactionDecision {
13
21
  * under the threshold and the turn went in without compacting — the case preventive compaction
14
22
  * exists to catch, on this product's most common input.
15
23
  */
16
- export declare function estimateIncomingMessageTokens(text: string): number;
24
+ export declare function estimateIncomingMessageTokens(text: string, imageCount?: number): number;
17
25
  export declare function getPreventiveCompactionDecision(contextTokens: number | null | undefined, incomingTokens: number, contextWindow: number, thresholdRatio?: number): PreventiveCompactionDecision;
@@ -1,5 +1,13 @@
1
1
  import { estimateTokens } from "../shared/token-estimate.js";
2
2
  export const PREVENTIVE_COMPACTION_THRESHOLD_RATIO = 0.75;
3
+ /**
4
+ * Rough per-image token cost (spec 049), used only to keep the preventive-compaction projection
5
+ * honest when a turn carries inbound images — providers vary (roughly 250–1600 tokens per image
6
+ * depending on resolution/provider), so this is a conservative single constant rather than a
7
+ * per-provider table: the guard only needs to be in the right ballpark to decide whether to
8
+ * compact before sending, not to predict the exact bill.
9
+ */
10
+ export const ESTIMATED_TOKENS_PER_IMAGE = 1200;
3
11
  /**
4
12
  * The incoming message's share of the projected context.
5
13
  *
@@ -8,11 +16,9 @@ export const PREVENTIVE_COMPACTION_THRESHOLD_RATIO = 0.75;
8
16
  * under the threshold and the turn went in without compacting — the case preventive compaction
9
17
  * exists to catch, on this product's most common input.
10
18
  */
11
- export function estimateIncomingMessageTokens(text) {
12
- if (!text) {
13
- return 0;
14
- }
15
- return estimateTokens(text);
19
+ export function estimateIncomingMessageTokens(text, imageCount = 0) {
20
+ const textTokens = text ? estimateTokens(text) : 0;
21
+ return textTokens + Math.max(0, imageCount) * ESTIMATED_TOKENS_PER_IMAGE;
16
22
  }
17
23
  export function getPreventiveCompactionDecision(contextTokens, incomingTokens, contextWindow, thresholdRatio = PREVENTIVE_COMPACTION_THRESHOLD_RATIO) {
18
24
  const normalizedContextWindow = Number.isFinite(contextWindow) ? Math.max(0, Math.floor(contextWindow)) : 0;
@@ -185,6 +185,8 @@ interface JobRuntimeConfig {
185
185
  /** Root of the per-channel record directories (`<jobsStateDir>/<channelId>/`). */
186
186
  jobsStateDir?: string;
187
187
  dispatch?: (event: ChannelEvent) => boolean | Promise<boolean>;
188
+ /** Sweep cadence override for the lazily-built channel managers (tests). */
189
+ sweepIntervalMs?: number;
188
190
  }
189
191
  /**
190
192
  * Give background jobs their persistence root and their way to wake a channel. Called once from
@@ -597,6 +597,7 @@ export function getChannelJobManager(channelId, executor) {
597
597
  manager = new ChannelJobManager(channelId, executor, {
598
598
  ...(runtimeConfig.jobsStateDir ? { stateDir: join(runtimeConfig.jobsStateDir, channelId) } : {}),
599
599
  ...(runtimeConfig.dispatch ? { dispatch: runtimeConfig.dispatch } : {}),
600
+ ...(runtimeConfig.sweepIntervalMs ? { sweepIntervalMs: runtimeConfig.sweepIntervalMs } : {}),
600
601
  });
601
602
  managers.set(channelId, manager);
602
603
  }
@@ -1,6 +1,7 @@
1
1
  import * as log from "../log.js";
2
2
  import { truncate } from "../shared/text-utils.js";
3
3
  import { isRecord } from "../shared/type-guards.js";
4
+ import { addUsage } from "../shared/types.js";
4
5
  import { describeToolCall } from "../tools/presentation.js";
5
6
  import { isArgumentValidationFailure, isRecoverableRejection, toolResultDetails, } from "../tools/tool-details.js";
6
7
  import { isEffectfulTool, noteChannelEffect } from "./effect-ledger.js";
@@ -22,28 +23,7 @@ function isWorkspaceSkillWrite(toolName, details, skillsDir) {
22
23
  return details.path === skillsDir || details.path.startsWith(`${skillsDir}/`);
23
24
  }
24
25
  function mergeSubAgentUsage(totalUsage, details) {
25
- totalUsage.input += details.usage.input;
26
- totalUsage.output += details.usage.output;
27
- totalUsage.cacheRead += details.usage.cacheRead;
28
- totalUsage.cacheWrite += details.usage.cacheWrite;
29
- totalUsage.total += details.usage.total;
30
- totalUsage.cost.input += details.usage.cost.input;
31
- totalUsage.cost.output += details.usage.cost.output;
32
- totalUsage.cost.cacheRead += details.usage.cost.cacheRead;
33
- totalUsage.cost.cacheWrite += details.usage.cost.cacheWrite;
34
- totalUsage.cost.total += details.usage.cost.total;
35
- }
36
- function addUsage(target, usage) {
37
- target.input += usage.input;
38
- target.output += usage.output;
39
- target.cacheRead += usage.cacheRead;
40
- target.cacheWrite += usage.cacheWrite;
41
- target.total += usage.total ?? usage.totalTokens ?? usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
42
- target.cost.input += usage.cost.input;
43
- target.cost.output += usage.cost.output;
44
- target.cost.cacheRead += usage.cost.cacheRead;
45
- target.cost.cacheWrite += usage.cost.cacheWrite;
46
- target.cost.total += usage.cost.total;
26
+ addUsage(totalUsage, details.usage);
47
27
  }
48
28
  function mergeAssistantUsage(runState, usage) {
49
29
  // totalUsage stays the console-summary tally (assistant + sub-agents).
@@ -1,4 +1,5 @@
1
1
  import type { ChannelContext } from "../channel/channel-context.js";
2
+ import type { InboundImage } from "../channel/channel-event.js";
2
3
  import type { ChannelStore } from "../channel/store.js";
3
4
  import type { RunnerBuiltInCommand } from "../commands/catalog.js";
4
5
  import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
@@ -46,7 +47,7 @@ export interface AgentRunner {
46
47
  handleBuiltinCommand(ctx: ChannelContext, command: RunnerBuiltInCommand): Promise<void>;
47
48
  /** True if `text` is a slash command the runtime or session layer can handle. */
48
49
  isKnownSlashCommand(text: string): boolean;
49
- queueSteer(text: string, userName?: string): Promise<void>;
50
+ queueSteer(text: string, userName?: string, images?: InboundImage[]): Promise<void>;
50
51
  flushMemoryForShutdown(): Promise<void>;
51
52
  getMemoryMaintenanceContext(): Promise<MemoryMaintenanceRuntimeContext>;
52
53
  getStatusSnapshot(): RunnerStatusSnapshot;
@@ -16,6 +16,7 @@
16
16
  * `tui` all depend on this file, and none of them should be reading anything out
17
17
  * of the DingTalk transport's directory to get it.
18
18
  */
19
+ import type { InboundImage } from "./channel-event.js";
19
20
  /**
20
21
  * How progress is surfaced during a run. Derived from the transport's response
21
22
  * mode so callers never branch on the raw enum string.
@@ -64,6 +65,9 @@ export interface ChannelContext {
64
65
  userName?: string;
65
66
  channel: string;
66
67
  ts: string;
68
+ /** Images the user sent alongside this message (spec 049). Empty on transports (TUI) that
69
+ * do not yet produce inbound attachments — the field stays optional for them. */
70
+ images?: InboundImage[];
67
71
  };
68
72
  channelName?: string;
69
73
  respond: (text: string, shouldLog?: boolean) => Promise<void>;
@@ -1,3 +1,40 @@
1
+ /**
2
+ * Inbound has no DingTalk-imposed size contract the way outbound does (`dingtalk.ts`'s
3
+ * `MAX_IMAGE_BYTES` mirrors the *send* limit); this instead mirrors `tools/truncate.ts`'s
4
+ * `MAX_INLINE_BINARY_BYTES` — the same ceiling `read` already applies to an on-disk image — so
5
+ * "a picture the user sent" and "a picture `read` loads from disk" behave identically for the
6
+ * model. Lives here, not in the DingTalk-specific `runtime/inbound-media.ts`, because both the
7
+ * transport (rejecting an oversized download) and `agent/channel-runner.ts` (skipping an
8
+ * oversized file before base64-encoding it) need the same number, and `agent/` never imports
9
+ * from `runtime/` (spec 049).
10
+ */
11
+ export declare const MAX_INBOUND_IMAGE_BYTES: number;
12
+ /**
13
+ * A user-sent image already downloaded to local disk (spec 049).
14
+ *
15
+ * Deliberately asymmetric with the outbound `OutboundMedia` (which carries a `Buffer`): outbound
16
+ * bytes come from an `Executor` that may be remote, with no local-file concept to point at.
17
+ * Inbound bytes must be persisted to satisfy the retention requirement regardless, and
18
+ * `ChannelEvent` is serialized into durable-dispatch records and logged — carrying the bytes a
19
+ * second time there would be pure waste. `path` is the natural handle once persistence already
20
+ * happened.
21
+ */
22
+ export interface InboundImage {
23
+ /** Absolute path under `<channelDir>/inbox/`. */
24
+ path: string;
25
+ /**
26
+ * Sniffed MIME type ("image/jpeg", …), or `"application/octet-stream"` when magic-byte
27
+ * sniffing did not recognize a supported image format — see `unsupportedFormat`.
28
+ */
29
+ mimeType: string;
30
+ /** On-disk byte size — lets the runner skip an oversized image without reading it into memory. */
31
+ byteSize: number;
32
+ /**
33
+ * True when the bytes were downloaded and persisted but are not a supported image format.
34
+ * Kept for the archive/record trail; the runner must never build an `ImageContent` from one.
35
+ */
36
+ unsupportedFormat?: boolean;
37
+ }
1
38
  /**
2
39
  * A message or wake, from any producer: a real inbound DingTalk message, a scheduled event, a
3
40
  * task-driver wake, or a job/subagent completion. `conversationId` is the one field genuinely
@@ -14,6 +51,8 @@ export interface ChannelEvent {
14
51
  user: string;
15
52
  userName: string;
16
53
  text: string;
54
+ /** Images the user sent alongside `text` (spec 049), already downloaded and persisted. */
55
+ images?: InboundImage[];
17
56
  /** DingTalk conversation id; absent on synthetic events, which have no DingTalk conversation. */
18
57
  conversationId?: string;
19
58
  conversationType: string;
@@ -1 +1,11 @@
1
- export {};
1
+ /**
2
+ * Inbound has no DingTalk-imposed size contract the way outbound does (`dingtalk.ts`'s
3
+ * `MAX_IMAGE_BYTES` mirrors the *send* limit); this instead mirrors `tools/truncate.ts`'s
4
+ * `MAX_INLINE_BINARY_BYTES` — the same ceiling `read` already applies to an on-disk image — so
5
+ * "a picture the user sent" and "a picture `read` loads from disk" behave identically for the
6
+ * model. Lives here, not in the DingTalk-specific `runtime/inbound-media.ts`, because both the
7
+ * transport (rejecting an oversized download) and `agent/channel-runner.ts` (skipping an
8
+ * oversized file before base64-encoding it) need the same number, and `agent/` never imports
9
+ * from `runtime/` (spec 049).
10
+ */
11
+ export const MAX_INBOUND_IMAGE_BYTES = 5 * 1024 * 1024;
@@ -1,8 +1,7 @@
1
- import { randomUUID } from "node:crypto";
2
- import { existsSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs";
1
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
3
2
  import { join } from "node:path";
4
3
  import { currentProjectSandboxStatus, isWithinAllowedRoots, } from "../security/project-scope.js";
5
- import { writeFileAtomically } from "../shared/atomic-file.js";
4
+ import { writeFileAtomically, writeFileAtomicallySync } from "../shared/atomic-file.js";
6
5
  const SELECTION_FILENAME = "project.json";
7
6
  export function getProjectSelectionPath(channelDir) {
8
7
  return join(channelDir, SELECTION_FILENAME);
@@ -29,15 +28,11 @@ export function readProjectSelection(channelDir) {
29
28
  }
30
29
  return raw;
31
30
  }
32
- /** Same durability tradeoff as every other atomic writer in this codebase (temp + rename), minus
33
- * the fsync `writeFileAtomically` does — used only for the one-time, in-constructor migration
34
- * write (D3.3); every explicit mutation (`/project set|reset`) goes through the fsync'd async
35
- * `writeFileAtomically` in `commitProjectSelection` instead. */
31
+ /** Used only for the one-time, in-constructor migration write (D3.3); every explicit mutation
32
+ * (`/project set|reset`) goes through the async `writeFileAtomically` in `commitProjectSelection`
33
+ * instead — that one is on a mutation path that can already afford to await. */
36
34
  function writeProjectSelectionSync(channelDir, selection) {
37
- const path = getProjectSelectionPath(channelDir);
38
- const tempPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
39
- writeFileSync(tempPath, `${JSON.stringify(selection, null, 2)}\n`, "utf-8");
40
- renameSync(tempPath, path);
35
+ writeFileAtomicallySync(getProjectSelectionPath(channelDir), `${JSON.stringify(selection, null, 2)}\n`);
41
36
  }
42
37
  export async function commitProjectSelection(channelDir, projectRoot, updatedBy) {
43
38
  const selection = {
@@ -8,6 +8,13 @@ export interface LoggedMessage {
8
8
  isBot: boolean;
9
9
  deliveryMode?: "steer" | "followUp";
10
10
  skipContextSync?: boolean;
11
+ /**
12
+ * Paths of any images the user sent alongside `text` (spec 049), relative to the channel
13
+ * directory. Kept even for an image that never made it into the model's context (unsupported
14
+ * format, oversized, model without vision support) — this is the only place that record
15
+ * survives once the turn's `[图片N: ...]` marker has scrolled out of `HISTORY.md`.
16
+ */
17
+ images?: string[];
11
18
  }
12
19
  export interface ChannelStoreConfig {
13
20
  workingDir: string;
@@ -14,7 +14,7 @@
14
14
  * next to this file enforces rule 5 (the length budget).
15
15
  */
16
16
  export type BuiltInCommandName = "help" | "steer" | "followup" | "stop" | "events" | "tasks" | "status" | "usage" | "context" | "subagents" | "project" | "skills";
17
- /** The four transport commands handled by `ChannelRunner.handleBuiltinCommand`. */
17
+ /** The five transport commands handled by `ChannelRunner.handleBuiltinCommand`. */
18
18
  export type RunnerBuiltInCommandName = "help" | "stop" | "steer" | "followup" | "context";
19
19
  /**
20
20
  * The commands with no mid-turn state to touch: each renders a text report from disk/in-memory
@@ -1,5 +1,6 @@
1
1
  import { splitH2Sections } from "../shared/markdown-sections.js";
2
2
  import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
3
+ import { stripCrAndTrim } from "../shared/text-utils.js";
3
4
  import { buildMemoryCandidateId } from "./candidates.js";
4
5
  import { parseChannelMemoryEntries } from "./files.js";
5
6
  const FIRST_TURN_MEMORY_SNAPSHOT_MAX_CHARS = 3_000;
@@ -12,9 +13,6 @@ const MIN_SECTION_CHARS = 600;
12
13
  const MIN_SECTION_UNITS = 100;
13
14
  const CHANNEL_MEMORY_WEIGHT = 0.6;
14
15
  const ZERO_BUDGET = { chars: 0, units: 0 };
15
- function normalizeContent(content) {
16
- return content.replace(/\r/g, "").trim();
17
- }
18
16
  function hasVisibleContent(content) {
19
17
  return content.replace(/<!--[\s\S]*?-->/g, "").trim().length > 0;
20
18
  }
@@ -93,8 +91,8 @@ export function buildFirstTurnMemoryBootstrapResult(options) {
93
91
  chars: options.maxChars ?? FIRST_TURN_MEMORY_SNAPSHOT_MAX_CHARS,
94
92
  units: options.maxUnits ?? FIRST_TURN_BOOTSTRAP_MAX_UNITS,
95
93
  };
96
- const channelMemory = normalizeContent(options.channelMemory);
97
- const workspaceMemory = normalizeContent(options.workspaceMemory);
94
+ const channelMemory = stripCrAndTrim(options.channelMemory);
95
+ const workspaceMemory = stripCrAndTrim(options.workspaceMemory);
98
96
  if (!channelMemory && !workspaceMemory) {
99
97
  return { renderedText: "", includedCandidateIds: [] };
100
98
  }
@@ -2,12 +2,10 @@ import { stat } from "fs/promises";
2
2
  import { join } from "path";
3
3
  import { readOptionalTextFile } from "../shared/fs-utils.js";
4
4
  import { splitH1Sections, splitH2Sections } from "../shared/markdown-sections.js";
5
+ import { stripCrAndTrim } from "../shared/text-utils.js";
5
6
  import { getChannelHistoryPath, getChannelMemoryPath, getChannelSessionPath, parseChannelMemoryEntries, parseUpdateHeadingTimestamp, } from "./files.js";
6
- function normalizeContent(content) {
7
- return content.replace(/\r/g, "").trim();
8
- }
9
7
  async function readOptionalFile(path) {
10
- return normalizeContent(await readOptionalTextFile(path));
8
+ return stripCrAndTrim(await readOptionalTextFile(path));
11
9
  }
12
10
  function slugify(value) {
13
11
  return (value
@@ -59,7 +59,6 @@ export interface HistoryBlock {
59
59
  export declare function getChannelMemoryPath(channelDir: string): string;
60
60
  export declare function getChannelHistoryPath(channelDir: string): string;
61
61
  export declare function getChannelSessionPath(channelDir: string): string;
62
- export declare function ensureChannelMemoryFiles(channelDir: string): Promise<void>;
63
62
  export declare function ensureChannelMemoryFilesSync(channelDir: string): void;
64
63
  export declare function readChannelMemory(channelDir: string): Promise<string>;
65
64
  export declare function readChannelHistory(channelDir: string): Promise<string>;