@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.
Files changed (142) hide show
  1. package/README.md +3 -0
  2. package/dist/agent/channel-runner.d.ts +45 -19
  3. package/dist/agent/channel-runner.js +156 -102
  4. package/dist/agent/command-extension.js +1 -1
  5. package/dist/agent/context-budget.d.ts +17 -1
  6. package/dist/agent/context-budget.js +20 -6
  7. package/dist/agent/job-manager.d.ts +3 -1
  8. package/dist/agent/job-manager.js +7 -1
  9. package/dist/agent/prompt/builder.d.ts +0 -1
  10. package/dist/agent/prompt/builder.js +1 -14
  11. package/dist/agent/prompt/manifest.js +2 -1
  12. package/dist/agent/prompt/sections.js +1 -1
  13. package/dist/agent/runner-factory.d.ts +19 -1
  14. package/dist/agent/runner-factory.js +8 -1
  15. package/dist/agent/session-events.d.ts +2 -2
  16. package/dist/agent/session-events.js +2 -22
  17. package/dist/agent/turn-prompt.d.ts +35 -0
  18. package/dist/agent/turn-prompt.js +37 -0
  19. package/dist/agent/turn-recovery.js +1 -1
  20. package/dist/agent/turn-state.d.ts +60 -0
  21. package/dist/agent/turn-state.js +95 -0
  22. package/dist/agent/types.d.ts +5 -4
  23. package/dist/{runtime → channel}/channel-context.d.ts +10 -2
  24. package/dist/{runtime → channel}/channel-context.js +6 -2
  25. package/dist/{runtime → channel}/channel-event.d.ts +39 -0
  26. package/dist/channel/channel-event.js +11 -0
  27. package/dist/channel/channel-paths.d.ts +16 -0
  28. package/dist/{runtime → channel}/channel-paths.js +20 -0
  29. package/dist/{runtime → channel}/project-scope-store.js +6 -11
  30. package/dist/{runtime → channel}/store.d.ts +7 -0
  31. package/dist/{agent/commands.d.ts → commands/catalog.d.ts} +17 -2
  32. package/dist/{agent/commands.js → commands/catalog.js} +30 -0
  33. package/dist/index.d.ts +1 -1
  34. package/dist/log.js +14 -5
  35. package/dist/main.js +29 -0
  36. package/dist/memory/bootstrap.js +3 -5
  37. package/dist/memory/candidates.js +2 -4
  38. package/dist/memory/commands.js +2 -2
  39. package/dist/memory/files.d.ts +0 -1
  40. package/dist/memory/files.js +6 -9
  41. package/dist/memory/maintenance-state.d.ts +8 -0
  42. package/dist/memory/maintenance-state.js +51 -4
  43. package/dist/memory/scheduler.d.ts +6 -0
  44. package/dist/memory/scheduler.js +19 -16
  45. package/dist/playbooks/agent-delegation.md +2 -2
  46. package/dist/runtime/bootstrap.d.ts +14 -8
  47. package/dist/runtime/bootstrap.js +158 -81
  48. package/dist/runtime/delivery.d.ts +3 -3
  49. package/dist/runtime/delivery.js +1 -0
  50. package/dist/runtime/dingtalk.d.ts +62 -6
  51. package/dist/runtime/dingtalk.js +194 -85
  52. package/dist/runtime/durable-dispatch.d.ts +7 -1
  53. package/dist/runtime/durable-dispatch.js +12 -2
  54. package/dist/runtime/event-commands.js +2 -2
  55. package/dist/runtime/events.d.ts +8 -1
  56. package/dist/runtime/events.js +15 -3
  57. package/dist/runtime/inbound-media.d.ts +60 -0
  58. package/dist/runtime/inbound-media.js +95 -0
  59. package/dist/runtime/project-commands.js +2 -2
  60. package/dist/runtime/skill-commands.d.ts +27 -0
  61. package/dist/runtime/skill-commands.js +72 -0
  62. package/dist/runtime/subagent-commands.js +1 -1
  63. package/dist/runtime/task-commands.js +2 -2
  64. package/dist/runtime/task-driver.d.ts +12 -1
  65. package/dist/runtime/task-driver.js +36 -56
  66. package/dist/runtime/task-migration.d.ts +11 -0
  67. package/dist/runtime/task-migration.js +14 -2
  68. package/dist/runtime/task-wake.d.ts +1 -1
  69. package/dist/runtime/task-wake.js +1 -1
  70. package/dist/security/command-guard.js +1 -3
  71. package/dist/security/config.d.ts +1 -1
  72. package/dist/security/config.js +8 -32
  73. package/dist/security/path-guard.js +1 -6
  74. package/dist/security/project-scope.js +1 -3
  75. package/dist/settings.d.ts +3 -2
  76. package/dist/settings.js +82 -20
  77. package/dist/shared/atomic-file.d.ts +2 -3
  78. package/dist/shared/atomic-file.js +8 -9
  79. package/dist/shared/config-diagnostic.d.ts +21 -0
  80. package/dist/shared/config-diagnostic.js +32 -0
  81. package/dist/shared/numeric.d.ts +7 -0
  82. package/dist/shared/numeric.js +19 -0
  83. package/dist/shared/text-utils.d.ts +10 -0
  84. package/dist/shared/text-utils.js +16 -0
  85. package/dist/shared/token-estimate.d.ts +1 -0
  86. package/dist/shared/token-estimate.js +19 -0
  87. package/dist/shared/types.d.ts +23 -0
  88. package/dist/shared/types.js +12 -0
  89. package/dist/shared/with-timeout.d.ts +3 -0
  90. package/dist/shared/with-timeout.js +8 -0
  91. package/dist/subagents/discovery.d.ts +7 -7
  92. package/dist/subagents/discovery.js +27 -59
  93. package/dist/subagents/runs.d.ts +15 -4
  94. package/dist/subagents/runs.js +118 -11
  95. package/dist/subagents/tool.js +199 -131
  96. package/dist/subagents/workspace-lease.js +1 -3
  97. package/dist/tasks/control.d.ts +2 -0
  98. package/dist/tasks/control.js +2 -0
  99. package/dist/tasks/ledger.d.ts +0 -9
  100. package/dist/tasks/ledger.js +92 -158
  101. package/dist/tools/config.d.ts +1 -1
  102. package/dist/tools/config.js +9 -46
  103. package/dist/tools/glob-match.d.ts +25 -4
  104. package/dist/tools/glob-match.js +175 -53
  105. package/dist/tools/glob.js +5 -2
  106. package/dist/tools/index.d.ts +1 -1
  107. package/dist/tools/registry.d.ts +1 -1
  108. package/dist/tools/send-media.d.ts +1 -1
  109. package/dist/tools/skill.d.ts +15 -0
  110. package/dist/tools/skill.js +17 -11
  111. package/dist/tools/truncate.js +24 -28
  112. package/dist/tui/app.js +6 -4
  113. package/dist/tui/commands.d.ts +1 -0
  114. package/dist/tui/commands.js +3 -1
  115. package/dist/tui/terminal-context.d.ts +2 -2
  116. package/dist/tui/terminal-media-sender.d.ts +1 -1
  117. package/dist/tui/turn-controller.d.ts +2 -1
  118. package/dist/tui/turn-controller.js +2 -1
  119. package/dist/web/config.js +3 -15
  120. package/examples/sub-agents/README.md +2 -2
  121. package/examples/sub-agents/builder.md +1 -1
  122. package/examples/sub-agents/documenter.md +1 -1
  123. package/examples/sub-agents/explorer.md +4 -4
  124. package/examples/sub-agents/git-committer.md +5 -4
  125. package/examples/sub-agents/log-sifter.md +4 -4
  126. package/examples/sub-agents/planner.md +1 -1
  127. package/examples/sub-agents/reviewer.md +1 -1
  128. package/examples/sub-agents/verifier.md +1 -1
  129. package/examples/sub-agents/worker.md +3 -3
  130. package/package.json +3 -2
  131. package/dist/agent/index.d.ts +0 -2
  132. package/dist/agent/index.js +0 -1
  133. package/dist/runtime/channel-event.js +0 -1
  134. package/dist/runtime/channel-paths.d.ts +0 -4
  135. /package/dist/{runtime → channel}/active-session-store.d.ts +0 -0
  136. /package/dist/{runtime → channel}/active-session-store.js +0 -0
  137. /package/dist/{runtime → channel}/channel-index.d.ts +0 -0
  138. /package/dist/{runtime → channel}/channel-index.js +0 -0
  139. /package/dist/{runtime → channel}/project-scope-store.d.ts +0 -0
  140. /package/dist/{runtime → channel}/store.js +0 -0
  141. /package/dist/{agent → commands}/reply-limits.d.ts +0 -0
  142. /package/dist/{agent → commands}/reply-limits.js +0 -0
@@ -1,9 +1,25 @@
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;
5
13
  thresholdTokens: number;
6
14
  ratio: number;
7
15
  }
8
- export declare function estimateIncomingMessageTokens(text: string): number;
16
+ /**
17
+ * The incoming message's share of the projected context.
18
+ *
19
+ * Script-aware on purpose (shared with the prompt manifest): a flat characters-per-token ratio
20
+ * put a 12k-character Chinese message at ~4k tokens instead of ~12k, so the projection stayed
21
+ * under the threshold and the turn went in without compacting — the case preventive compaction
22
+ * exists to catch, on this product's most common input.
23
+ */
24
+ export declare function estimateIncomingMessageTokens(text: string, imageCount?: number): number;
9
25
  export declare function getPreventiveCompactionDecision(contextTokens: number | null | undefined, incomingTokens: number, contextWindow: number, thresholdRatio?: number): PreventiveCompactionDecision;
@@ -1,10 +1,24 @@
1
+ import { estimateTokens } from "../shared/token-estimate.js";
1
2
  export const PREVENTIVE_COMPACTION_THRESHOLD_RATIO = 0.75;
2
- const ESTIMATED_CHARS_PER_TOKEN = 3;
3
- export function estimateIncomingMessageTokens(text) {
4
- if (!text) {
5
- return 0;
6
- }
7
- return Math.ceil(text.length / ESTIMATED_CHARS_PER_TOKEN);
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;
11
+ /**
12
+ * The incoming message's share of the projected context.
13
+ *
14
+ * Script-aware on purpose (shared with the prompt manifest): a flat characters-per-token ratio
15
+ * put a 12k-character Chinese message at ~4k tokens instead of ~12k, so the projection stayed
16
+ * under the threshold and the turn went in without compacting — the case preventive compaction
17
+ * exists to catch, on this product's most common input.
18
+ */
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;
8
22
  }
9
23
  export function getPreventiveCompactionDecision(contextTokens, incomingTokens, contextWindow, thresholdRatio = PREVENTIVE_COMPACTION_THRESHOLD_RATIO) {
10
24
  const normalizedContextWindow = Number.isFinite(contextWindow) ? Math.max(0, Math.floor(contextWindow)) : 0;
@@ -1,6 +1,6 @@
1
+ import type { ChannelEvent } from "../channel/channel-event.js";
1
2
  import type { Executor } from "../executor.js";
2
3
  import { type FileStore } from "../file-store.js";
3
- import type { ChannelEvent } from "../runtime/channel-event.js";
4
4
  /**
5
5
  * Per-channel manager for background bash jobs. A long command that ran synchronously would hold
6
6
  * the channel's run queue for its whole duration, blocking `/steer`, `/followup`, and every other
@@ -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
@@ -221,7 +221,12 @@ export class ChannelJobManager {
221
221
  return;
222
222
  }
223
223
  this.sweepTimer = setInterval(() => {
224
- void this.sweep();
224
+ // A timer callback is the last frame that can hold this promise: an unhandled
225
+ // rejection here (a probe that cannot spawn — EAGAIN/EMFILE/ENOMEM) exits the
226
+ // whole daemon, since nothing installs a process-level rejection handler.
227
+ this.sweep().catch((error) => {
228
+ log.logWarning("Background job sweep failed", errorMessage(error));
229
+ });
225
230
  }, this.sweepIntervalMs);
226
231
  // Do not keep the process alive just for the sweeper.
227
232
  this.sweepTimer.unref?.();
@@ -592,6 +597,7 @@ export function getChannelJobManager(channelId, executor) {
592
597
  manager = new ChannelJobManager(channelId, executor, {
593
598
  ...(runtimeConfig.jobsStateDir ? { stateDir: join(runtimeConfig.jobsStateDir, channelId) } : {}),
594
599
  ...(runtimeConfig.dispatch ? { dispatch: runtimeConfig.dispatch } : {}),
600
+ ...(runtimeConfig.sweepIntervalMs ? { sweepIntervalMs: runtimeConfig.sweepIntervalMs } : {}),
595
601
  });
596
602
  managers.set(channelId, manager);
597
603
  }
@@ -19,5 +19,4 @@ export declare const RUNTIME_PROMPT_TARGET_UNITS = 700;
19
19
  /** Over this it is a development error: runtime text has drifted well past its budget. */
20
20
  export declare const RUNTIME_PROMPT_HARD_UNITS = 1200;
21
21
  export declare function sha256(text: string): string;
22
- export declare function estimateTokens(text: string): number;
23
22
  export declare function buildPipiclawSystemPrompt(context: PromptBuildContext, definitions?: PromptSectionDefinition[]): PromptBuildResult;
@@ -13,6 +13,7 @@
13
13
  */
14
14
  import { createHash } from "node:crypto";
15
15
  import { countPromptUnits } from "../../shared/prompt-units.js";
16
+ import { estimateTokens } from "../../shared/token-estimate.js";
16
17
  import { FINAL_BOUNDARY_SECTION, MAIN_PROMPT_SECTIONS } from "./sections.js";
17
18
  /** Bumped whenever the runtime-authored prompt text changes in a way worth attributing in telemetry. */
18
19
  export const RUNTIME_PROMPT_VERSION = 3;
@@ -37,20 +38,6 @@ export const RUNTIME_PROMPT_HARD_UNITS = 1_200;
37
38
  export function sha256(text) {
38
39
  return createHash("sha256").update(text, "utf8").digest("hex");
39
40
  }
40
- /**
41
- * Rough token estimate for reporting only. CJK runs about one token per
42
- * character, Latin text about four characters per token; the provider's real
43
- * tokenizer is the authority, and the usage ledger records what it billed.
44
- */
45
- const CJK_REGEX = /\p{Script=Han}|\p{Script=Hiragana}|\p{Script=Katakana}|\p{Script=Hangul}/u;
46
- export function estimateTokens(text) {
47
- let cjk = 0;
48
- for (const char of text) {
49
- if (CJK_REGEX.test(char))
50
- cjk++;
51
- }
52
- return Math.ceil(cjk + (text.length - cjk) / 4);
53
- }
54
41
  function truncateItems(content, maxChars) {
55
42
  const lines = content.split("\n");
56
43
  const kept = [];
@@ -10,7 +10,8 @@
10
10
  * next to the report — not in the builder's budget path (spec 026 §9, §10.9).
11
11
  */
12
12
  import { countPromptUnits } from "../../shared/prompt-units.js";
13
- import { estimateTokens, RUNTIME_PROMPT_TARGET_UNITS, sha256 } from "./builder.js";
13
+ import { estimateTokens } from "../../shared/token-estimate.js";
14
+ import { RUNTIME_PROMPT_TARGET_UNITS, sha256 } from "./builder.js";
14
15
  /** The design ceiling for everything Pipiclaw auto-appends to a turn (spec 026 §5.3). */
15
16
  export const AUTOMATIC_TURN_CONTEXT_BUDGET_UNITS = 3_000;
16
17
  /**
@@ -133,7 +133,7 @@ export const SUBAGENTS_SECTION = {
133
133
  return [
134
134
  "## Sub-Agents",
135
135
  hasInline
136
- ? "No configured agent exists yet: delegate with `subagent_inline`, passing a `systemPrompt` (no configured agent is required)."
136
+ ? "No configured role is available, so use `subagent_inline` only as the fallback; provide a complete valid payload with required `task` and `systemPrompt`."
137
137
  : "No configured agent exists and `subagent_inline` is off; ask the deployer to add a role or enable it.",
138
138
  "A sub-agent starts blank — state goal, scope, paths, constraints, acceptance criteria in `task`.",
139
139
  "Read agent-delegation.md before non-trivial delegation.",
@@ -1,4 +1,7 @@
1
- import type { MediaSender } from "../runtime/channel-context.js";
1
+ import type { MediaSender } from "../channel/channel-context.js";
2
+ import { type Executor } from "../executor.js";
3
+ import { type FileStore } from "../file-store.js";
4
+ import { type LoadedSecurityConfig } from "../security/config.js";
2
5
  import type { PipiclawSettingsManager } from "../settings.js";
3
6
  import type { AgentRunner } from "./types.js";
4
7
  export interface RunnerFactoryPaths {
@@ -19,6 +22,21 @@ export interface RunnerFactoryPaths {
19
22
  */
20
23
  mediaSender?: MediaSender;
21
24
  }
25
+ /**
26
+ * The collaborators a runner uses but does not build. Composing them here rather than inside
27
+ * `ChannelRunner`'s constructor keeps the "which implementation" decision at the one place that
28
+ * already owns wiring, and is what makes `Executor`/`FileStore` real ports (a remote executor is
29
+ * a different value passed in, not a different branch inside the runner).
30
+ */
31
+ export interface RunnerDeps {
32
+ executor: Executor;
33
+ fileStore: FileStore;
34
+ /**
35
+ * Called per use, not resolved once: the runner re-reads security policy on every tool rebuild
36
+ * so an edited `security.json` takes effect without restarting the daemon.
37
+ */
38
+ loadSecurityConfig: () => LoadedSecurityConfig;
39
+ }
22
40
  /**
23
41
  * Stateless: always constructs a fresh runner. The daemon (`runtime/bootstrap.ts`) and the TUI
24
42
  * (`tui/app.ts`) are the only two callers, and each already owns exactly one cache appropriate to
@@ -1,3 +1,6 @@
1
+ import { createExecutor } from "../executor.js";
2
+ import { createFileStore } from "../file-store.js";
3
+ import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
1
4
  import { ChannelRunner } from "./channel-runner.js";
2
5
  /**
3
6
  * Stateless: always constructs a fresh runner. The daemon (`runtime/bootstrap.ts`) and the TUI
@@ -7,5 +10,9 @@ import { ChannelRunner } from "./channel-runner.js";
7
10
  * could hold a stale entry the real owner had already disposed.
8
11
  */
9
12
  export function createRunner(channelId, channelDir, paths) {
10
- return new ChannelRunner(channelId, channelDir, paths);
13
+ return new ChannelRunner(channelId, channelDir, paths, {
14
+ executor: createExecutor(),
15
+ fileStore: createFileStore(),
16
+ loadSecurityConfig: () => loadSecurityConfigWithDiagnostics(paths.appHomeDir),
17
+ });
11
18
  }
@@ -1,6 +1,6 @@
1
+ import type { ChannelContext } from "../channel/channel-context.js";
2
+ import type { ChannelStore } from "../channel/store.js";
1
3
  import type { MemoryLifecycle } from "../memory/lifecycle.js";
2
- import type { ChannelContext } from "../runtime/channel-context.js";
3
- import type { ChannelStore } from "../runtime/store.js";
4
4
  import type { UsageLedger } from "../usage/ledger.js";
5
5
  import type { PendingTool, RunLogContext, RunQueue, RunState } from "./types.js";
6
6
  export interface SessionEventHandlerContext {
@@ -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).
@@ -0,0 +1,35 @@
1
+ import type { PromptTurnContextStats } from "./prompt/manifest.js";
2
+ export interface TurnPromptParts {
3
+ /** The user's message, already clipped to `MAX_USER_MESSAGE_CHARS`. Measured, not rendered. */
4
+ clippedInput: string;
5
+ /** `clippedInput` carrying the runtime's `[time] [user]:` prefix. Unused when raw input is preserved. */
6
+ userMessage: string;
7
+ /**
8
+ * A slash command is forwarded byte-for-byte: the SDK matches it against its own command table,
9
+ * so a wrapper or a prepended context block would stop it from matching.
10
+ */
11
+ preserveRawInput: boolean;
12
+ /** `<runtime_turn_context>`: the channel facts kept out of the cached system prompt. */
13
+ channelCapsule: string;
14
+ durableMemoryBootstrap: string;
15
+ taskDigest: string;
16
+ recalledMemory: string;
17
+ }
18
+ export interface AssembledTurnPrompt {
19
+ text: string;
20
+ stats: PromptTurnContextStats;
21
+ }
22
+ /**
23
+ * Compose one turn's prompt from the pieces `run()` gathered, and measure what each piece cost.
24
+ *
25
+ * The order is a contract, not a preference: durable memory bootstrap → task agenda → recalled
26
+ * memory → channel capsule → the user's message. Everything the runtime supplies precedes the
27
+ * message it is context *for*, and the blocks that change least between turns come first, so the
28
+ * provider's prefix cache keeps as long a match as possible. An empty piece contributes no
29
+ * separator, so a turn with nothing to recall reads exactly like one where recall is disabled.
30
+ *
31
+ * `stats` measures the inputs, never the rendered wrapper — it is what `/context` reports as the
32
+ * previous turn's automatic context, and the per-piece unit caps are enforced upstream by the
33
+ * builders themselves (`memory/recall.ts`, `memory/task-digest.ts`, `memory/bootstrap.ts`).
34
+ */
35
+ export declare function assembleTurnPrompt(parts: TurnPromptParts): AssembledTurnPrompt;
@@ -0,0 +1,37 @@
1
+ import { countPromptUnits } from "../shared/prompt-units.js";
2
+ /**
3
+ * Compose one turn's prompt from the pieces `run()` gathered, and measure what each piece cost.
4
+ *
5
+ * The order is a contract, not a preference: durable memory bootstrap → task agenda → recalled
6
+ * memory → channel capsule → the user's message. Everything the runtime supplies precedes the
7
+ * message it is context *for*, and the blocks that change least between turns come first, so the
8
+ * provider's prefix cache keeps as long a match as possible. An empty piece contributes no
9
+ * separator, so a turn with nothing to recall reads exactly like one where recall is disabled.
10
+ *
11
+ * `stats` measures the inputs, never the rendered wrapper — it is what `/context` reports as the
12
+ * previous turn's automatic context, and the per-piece unit caps are enforced upstream by the
13
+ * builders themselves (`memory/recall.ts`, `memory/task-digest.ts`, `memory/bootstrap.ts`).
14
+ */
15
+ export function assembleTurnPrompt(parts) {
16
+ const stats = {
17
+ durableMemoryChars: parts.durableMemoryBootstrap.length,
18
+ durableMemoryUnits: countPromptUnits(parts.durableMemoryBootstrap),
19
+ taskDigestChars: parts.taskDigest.length,
20
+ taskDigestUnits: countPromptUnits(parts.taskDigest),
21
+ recalledMemoryChars: parts.recalledMemory.length,
22
+ recalledMemoryUnits: countPromptUnits(parts.recalledMemory),
23
+ channelCapsuleUnits: countPromptUnits(parts.channelCapsule),
24
+ userMessageChars: parts.clippedInput.length,
25
+ };
26
+ if (parts.preserveRawInput) {
27
+ return { text: parts.clippedInput, stats };
28
+ }
29
+ const blocks = [
30
+ parts.durableMemoryBootstrap,
31
+ parts.taskDigest,
32
+ parts.recalledMemory,
33
+ parts.channelCapsule,
34
+ `<user_message>\n${parts.userMessage}\n</user_message>`,
35
+ ];
36
+ return { text: blocks.filter((block) => block !== "").join("\n\n"), stats };
37
+ }
@@ -1,7 +1,7 @@
1
1
  import { readdir } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { SessionManager } from "@earendil-works/pi-coding-agent";
4
- import { resolveActiveSessionFile } from "../runtime/active-session-store.js";
4
+ import { resolveActiveSessionFile } from "../channel/active-session-store.js";
5
5
  /**
6
6
  * Repairs a session branch left with a declared-but-unfulfilled tool call by a process that
7
7
  * exited between the assistant's tool call and the tool result being recorded (spec 043, D8-D16).
@@ -0,0 +1,60 @@
1
+ import type { TurnPhase, TurnStatus } from "./types.js";
2
+ /**
3
+ * One turn's mutable state. `current()` hands it out so the owning `run()` can address *its own*
4
+ * turn for later phase writes: once `forceEnd()` has released a turn, the machine's current turn
5
+ * is a different object and the stale handle must lose.
6
+ */
7
+ export interface TurnHandle {
8
+ phase: TurnPhase;
9
+ stopRequested: boolean;
10
+ taskText?: string;
11
+ }
12
+ /**
13
+ * The runner's turn state machine (phases documented on `TurnPhase` in types.ts). Busy state has a
14
+ * single owner; transports call `begin`/`end` and everything else — the DingTalk busy routing, the
15
+ * TUI turn controller, the maintenance scheduler's idle check, `/status` — derives from `isBusy()`
16
+ * and `status()` instead of keeping a parallel flag.
17
+ *
18
+ * Extracted from `ChannelRunner` because its two load-bearing rules are invisible at the call sites
19
+ * and were previously reachable only through a live SDK session:
20
+ *
21
+ * 1. **A force-released turn's late `end()` is swallowed.** `forceEnd` hands the channel back to the
22
+ * next message while the wedged turn's epilogue is still running; when that epilogue finally
23
+ * calls `end()`, it would otherwise clear the busy state of whichever turn started in between.
24
+ * `abandoned` counts those outstanding releases so each one absorbs exactly one late `end()`.
25
+ * 2. **Phase writes are addressed to a turn, not to "whatever is current".** `setPhase` is a no-op
26
+ * once its handle is no longer current, for the same reason.
27
+ *
28
+ * No I/O and no logger import: both warning paths report through `onWarn`, so this stays a unit that
29
+ * can be exercised directly.
30
+ */
31
+ export declare class TurnStateMachine {
32
+ private readonly onWarn;
33
+ private turn;
34
+ /** Turns released by `forceEnd` whose owner has not called `end()` yet. */
35
+ private abandoned;
36
+ constructor(onWarn?: (message: string, detail?: string) => void);
37
+ /** Reserve the machine for a turn. Transports must call this in the tick they dequeue a message. */
38
+ begin(taskText: string): void;
39
+ /** Release the turn. Ignored when the turn was already released by `forceEnd`. */
40
+ end(): void;
41
+ /**
42
+ * Release a turn whose owner is wedged, so the channel stops reporting busy. Returns false when
43
+ * already idle. The wedged turn keeps running; its later `end()` is absorbed.
44
+ */
45
+ forceEnd(reason: string): boolean;
46
+ isBusy(): boolean;
47
+ phase(): TurnPhase;
48
+ /** The live handle for the current turn, for `setPhase` and for `run()`'s own-turn capture. */
49
+ current(): TurnHandle;
50
+ /** Advance a turn's phase, unless that turn has since been released. */
51
+ setPhase(turn: TurnHandle, phase: TurnPhase): void;
52
+ /**
53
+ * The agent loop reported its first message. Only a turn still assembling its prompt advances;
54
+ * a `message_start` arriving after the turn was released must not revive the next one.
55
+ */
56
+ markStreaming(): boolean;
57
+ /** Mark the current turn as user-stopped (no-op when idle). */
58
+ requestStop(): void;
59
+ status(): TurnStatus;
60
+ }
@@ -0,0 +1,95 @@
1
+ function idleTurn() {
2
+ return { phase: "idle", stopRequested: false };
3
+ }
4
+ /**
5
+ * The runner's turn state machine (phases documented on `TurnPhase` in types.ts). Busy state has a
6
+ * single owner; transports call `begin`/`end` and everything else — the DingTalk busy routing, the
7
+ * TUI turn controller, the maintenance scheduler's idle check, `/status` — derives from `isBusy()`
8
+ * and `status()` instead of keeping a parallel flag.
9
+ *
10
+ * Extracted from `ChannelRunner` because its two load-bearing rules are invisible at the call sites
11
+ * and were previously reachable only through a live SDK session:
12
+ *
13
+ * 1. **A force-released turn's late `end()` is swallowed.** `forceEnd` hands the channel back to the
14
+ * next message while the wedged turn's epilogue is still running; when that epilogue finally
15
+ * calls `end()`, it would otherwise clear the busy state of whichever turn started in between.
16
+ * `abandoned` counts those outstanding releases so each one absorbs exactly one late `end()`.
17
+ * 2. **Phase writes are addressed to a turn, not to "whatever is current".** `setPhase` is a no-op
18
+ * once its handle is no longer current, for the same reason.
19
+ *
20
+ * No I/O and no logger import: both warning paths report through `onWarn`, so this stays a unit that
21
+ * can be exercised directly.
22
+ */
23
+ export class TurnStateMachine {
24
+ constructor(onWarn = () => { }) {
25
+ this.onWarn = onWarn;
26
+ this.turn = idleTurn();
27
+ /** Turns released by `forceEnd` whose owner has not called `end()` yet. */
28
+ this.abandoned = 0;
29
+ }
30
+ /** Reserve the machine for a turn. Transports must call this in the tick they dequeue a message. */
31
+ begin(taskText) {
32
+ if (this.turn.phase !== "idle") {
33
+ this.onWarn(`beginTurn while phase=${this.turn.phase}; turns must be serialized`);
34
+ }
35
+ this.turn = { phase: "dispatching", stopRequested: false, taskText };
36
+ }
37
+ /** Release the turn. Ignored when the turn was already released by `forceEnd`. */
38
+ end() {
39
+ if (this.abandoned > 0) {
40
+ this.abandoned--;
41
+ return;
42
+ }
43
+ this.turn = idleTurn();
44
+ }
45
+ /**
46
+ * Release a turn whose owner is wedged, so the channel stops reporting busy. Returns false when
47
+ * already idle. The wedged turn keeps running; its later `end()` is absorbed.
48
+ */
49
+ forceEnd(reason) {
50
+ if (this.turn.phase === "idle") {
51
+ return false;
52
+ }
53
+ this.onWarn(`Force-ending a stuck turn (phase=${this.turn.phase})`, `${reason}; its own teardown is still running and will be ignored when it finishes`);
54
+ this.abandoned++;
55
+ this.turn = idleTurn();
56
+ return true;
57
+ }
58
+ isBusy() {
59
+ return this.turn.phase !== "idle";
60
+ }
61
+ phase() {
62
+ return this.turn.phase;
63
+ }
64
+ /** The live handle for the current turn, for `setPhase` and for `run()`'s own-turn capture. */
65
+ current() {
66
+ return this.turn;
67
+ }
68
+ /** Advance a turn's phase, unless that turn has since been released. */
69
+ setPhase(turn, phase) {
70
+ if (this.turn !== turn) {
71
+ return;
72
+ }
73
+ this.turn.phase = phase;
74
+ }
75
+ /**
76
+ * The agent loop reported its first message. Only a turn still assembling its prompt advances;
77
+ * a `message_start` arriving after the turn was released must not revive the next one.
78
+ */
79
+ markStreaming() {
80
+ if (this.turn.phase !== "preparing") {
81
+ return false;
82
+ }
83
+ this.turn.phase = "streaming";
84
+ return true;
85
+ }
86
+ /** Mark the current turn as user-stopped (no-op when idle). */
87
+ requestStop() {
88
+ if (this.turn.phase !== "idle") {
89
+ this.turn.stopRequested = true;
90
+ }
91
+ }
92
+ status() {
93
+ return { ...this.turn };
94
+ }
95
+ }
@@ -1,9 +1,10 @@
1
+ import type { ChannelContext } from "../channel/channel-context.js";
2
+ import type { InboundImage } from "../channel/channel-event.js";
3
+ import type { ChannelStore } from "../channel/store.js";
4
+ import type { RunnerBuiltInCommand } from "../commands/catalog.js";
1
5
  import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
2
- import type { ChannelContext } from "../runtime/channel-context.js";
3
- import type { ChannelStore } from "../runtime/store.js";
4
6
  import { type UsageTotals } from "../shared/types.js";
5
7
  import type { SubAgentDiscoveryResult } from "../subagents/discovery.js";
6
- import type { RunnerBuiltInCommand } from "./commands.js";
7
8
  export interface RunnerStatusSnapshot {
8
9
  model: string;
9
10
  contextTokens?: number;
@@ -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;
@@ -9,9 +9,14 @@
9
9
  * transport.
10
10
  *
11
11
  * These declarations previously lived in `runtime/dingtalk.ts` under the name
12
- * `DingTalkContext`; they were lifted here (and renamed) so a second transport
13
- * can implement the contract without importing anything DingTalk-specific.
12
+ * `DingTalkContext`; they were lifted out (and renamed) so a second transport
13
+ * can implement the contract without importing anything DingTalk-specific. They
14
+ * live in `src/channel/` rather than `src/runtime/` because a port belongs with
15
+ * the domain it describes, not with one of its adapters: `agent`, `tools` and
16
+ * `tui` all depend on this file, and none of them should be reading anything out
17
+ * of the DingTalk transport's directory to get it.
14
18
  */
19
+ import type { InboundImage } from "./channel-event.js";
15
20
  /**
16
21
  * How progress is surfaced during a run. Derived from the transport's response
17
22
  * mode so callers never branch on the raw enum string.
@@ -60,6 +65,9 @@ export interface ChannelContext {
60
65
  userName?: string;
61
66
  channel: string;
62
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[];
63
71
  };
64
72
  channelName?: string;
65
73
  respond: (text: string, shouldLog?: boolean) => Promise<void>;
@@ -9,7 +9,11 @@
9
9
  * transport.
10
10
  *
11
11
  * These declarations previously lived in `runtime/dingtalk.ts` under the name
12
- * `DingTalkContext`; they were lifted here (and renamed) so a second transport
13
- * can implement the contract without importing anything DingTalk-specific.
12
+ * `DingTalkContext`; they were lifted out (and renamed) so a second transport
13
+ * can implement the contract without importing anything DingTalk-specific. They
14
+ * live in `src/channel/` rather than `src/runtime/` because a port belongs with
15
+ * the domain it describes, not with one of its adapters: `agent`, `tools` and
16
+ * `tui` all depend on this file, and none of them should be reading anything out
17
+ * of the DingTalk transport's directory to get it.
14
18
  */
15
19
  export {};
@@ -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;
@@ -0,0 +1,11 @@
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;
@@ -0,0 +1,16 @@
1
+ export declare function isChannelId(value: string): boolean;
2
+ export declare function getChannelDirName(channelId: string): string;
3
+ export declare function getChannelDir(baseDir: string, channelId: string): string;
4
+ /**
5
+ * Collapse ids that name the same channel directory, keeping the first spelling offered.
6
+ *
7
+ * Background workers assemble their channel list from several sources, and only some of them
8
+ * store a real id: `CHANNELS.md` and the live runner map do, while a directory listing (of the
9
+ * workspace, or of the maintenance state dir) can only report the *escaped* name, which cannot
10
+ * be turned back into the id it came from. Left alone, one channel then appears twice — once
11
+ * under its real id and once under a spelling no transport can deliver to — and every unit of
12
+ * work for it runs twice. Callers pass their sources most-authoritative-first; this keeps that
13
+ * spelling and drops the rest.
14
+ */
15
+ export declare function dedupeChannelIdsByDirectory(channelIds: Iterable<string>): string[];
16
+ export declare function ensureChannelDir(baseDir: string, channelId: string): string;