@oyasmi/pipiclaw 0.9.0-beta.8 → 0.9.0-beta.9

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 (51) hide show
  1. package/dist/agent/channel-runner.d.ts +1 -0
  2. package/dist/agent/channel-runner.js +21 -2
  3. package/dist/agent/index.d.ts +1 -1
  4. package/dist/agent/index.js +1 -1
  5. package/dist/agent/job-manager.d.ts +3 -3
  6. package/dist/agent/job-manager.js +0 -1
  7. package/dist/agent/runner-factory.d.ts +16 -4
  8. package/dist/agent/runner-factory.js +9 -23
  9. package/dist/agent/types.d.ts +9 -1
  10. package/dist/agent/types.js +3 -16
  11. package/dist/runtime/bootstrap.d.ts +10 -2
  12. package/dist/runtime/bootstrap.js +74 -50
  13. package/dist/runtime/channel-event.d.ts +41 -0
  14. package/dist/runtime/channel-event.js +1 -0
  15. package/dist/runtime/delivery.d.ts +3 -2
  16. package/dist/runtime/dingtalk.d.ts +9 -31
  17. package/dist/runtime/durable-dispatch.d.ts +3 -2
  18. package/dist/runtime/events.d.ts +3 -2
  19. package/dist/runtime/events.js +2 -3
  20. package/dist/runtime/task-commands.js +2 -2
  21. package/dist/runtime/task-driver.d.ts +7 -7
  22. package/dist/runtime/task-driver.js +1 -4
  23. package/dist/runtime/task-migration.js +1 -1
  24. package/dist/runtime/task-wake.d.ts +4 -4
  25. package/dist/settings.d.ts +0 -106
  26. package/dist/settings.js +0 -224
  27. package/dist/shared/types.d.ts +1 -0
  28. package/dist/shared/types.js +10 -1
  29. package/dist/subagents/external/run.js +2 -8
  30. package/dist/subagents/runs.d.ts +3 -3
  31. package/dist/subagents/runs.js +2 -12
  32. package/dist/subagents/tool.d.ts +11 -4
  33. package/dist/subagents/tool.js +1 -13
  34. package/dist/tasks/ledger.js +1 -1
  35. package/dist/{shared → tasks}/task-schedule.js +1 -1
  36. package/dist/tools/bash.js +1 -1
  37. package/dist/tools/event-manage.js +1 -4
  38. package/dist/tools/grep.js +2 -3
  39. package/dist/tools/job.js +5 -5
  40. package/dist/tools/memory-manage.js +3 -6
  41. package/dist/tools/session-search.js +0 -1
  42. package/dist/tools/skill-manage.js +3 -3
  43. package/dist/tools/subagent-manage.js +3 -3
  44. package/dist/tools/task-manage/shared.js +2 -2
  45. package/dist/tools/task-manage.js +1 -4
  46. package/dist/tools/web-fetch.js +0 -1
  47. package/dist/tui/app.js +4 -4
  48. package/package.json +1 -1
  49. /package/dist/{shared → tasks}/task-events.d.ts +0 -0
  50. /package/dist/{shared → tasks}/task-events.js +0 -0
  51. /package/dist/{shared → tasks}/task-schedule.d.ts +0 -0
@@ -92,6 +92,7 @@ export declare class ChannelRunner implements AgentRunner {
92
92
  isKnownSlashCommand(text: string): boolean;
93
93
  queueSteer(text: string, userName?: string): Promise<void>;
94
94
  flushMemoryForShutdown(): Promise<void>;
95
+ dispose(): Promise<void>;
95
96
  getMemoryMaintenanceContext(): Promise<MemoryMaintenanceRuntimeContext>;
96
97
  getStatusSnapshot(): RunnerStatusSnapshot;
97
98
  abort(): Promise<void>;
@@ -17,7 +17,6 @@ import { getApiKeyForModel } from "../models/api-keys.js";
17
17
  import { createModelRuntime, defaultModel, findExactModelReferenceMatch, formatModelReference, hasKnownModelPricing, resolveInitialModel, wrapModelRegistry, } from "../models/utils.js";
18
18
  import { loadRuntimePlaybookCatalog, selectRuntimePlaybooks } from "../playbooks/catalog.js";
19
19
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
20
- import { PipiclawSettingsManager } from "../settings.js";
21
20
  import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
22
21
  import { formatLocalTime, localStampForFilename } from "../shared/local-time.js";
23
22
  import { countPromptUnits } from "../shared/prompt-units.js";
@@ -114,7 +113,7 @@ export class ChannelRunner {
114
113
  // Create session manager
115
114
  const contextFile = join(channelDir, "context.jsonl");
116
115
  this.sessionManager = SessionManager.open(contextFile, channelDir);
117
- this.settingsManager = new PipiclawSettingsManager(this.appHomeDir);
116
+ this.settingsManager = paths.settingsManager;
118
117
  this.reportSettingsDiagnostics();
119
118
  this.memoryCandidateStore = createMemoryCandidateStore();
120
119
  this.memoryActivityRecorder = createMemoryActivityRecorder({
@@ -606,6 +605,26 @@ export class ChannelRunner {
606
605
  await this.flushMemoryActivity();
607
606
  await this.memoryLifecycle.flushForShutdown();
608
607
  }
608
+ async dispose() {
609
+ await this.flushMemoryForShutdown();
610
+ if (this.isBusy()) {
611
+ // `session.dispose()` aborts in-flight work; a busy runner keeps its session and
612
+ // subscription until whoever holds it calls dispose() again once idle.
613
+ log.logWarning(`[${this.channelId}] dispose() called while busy; session left intact`, "");
614
+ return;
615
+ }
616
+ // Guards a dispose() racing construction: initializeSession assigns `this.session`
617
+ // asynchronously, so a runner disposed the instant after creation may not have one yet.
618
+ await this.sessionReady;
619
+ this.sessionUnsubscribe?.();
620
+ this.sessionUnsubscribe = undefined;
621
+ try {
622
+ this.session.dispose();
623
+ }
624
+ catch (error) {
625
+ log.logWarning(`[${this.channelId}] Session dispose failed`, errorMessage(error));
626
+ }
627
+ }
609
628
  async getMemoryMaintenanceContext() {
610
629
  await this.ensureSessionReady();
611
630
  this.settingsManager.reload();
@@ -1,2 +1,2 @@
1
- export { getOrCreateRunner } from "./runner-factory.js";
1
+ export { createRunner } from "./runner-factory.js";
2
2
  export type { AgentRunner } from "./types.js";
@@ -1 +1 @@
1
- export { getOrCreateRunner } from "./runner-factory.js";
1
+ export { createRunner } from "./runner-factory.js";
@@ -1,5 +1,5 @@
1
1
  import type { Executor } from "../executor.js";
2
- import type { DingTalkEvent } from "../runtime/dingtalk.js";
2
+ import type { ChannelEvent } from "../runtime/channel-event.js";
3
3
  /**
4
4
  * Per-channel manager for background bash jobs. A long command that ran synchronously would hold
5
5
  * the channel's run queue for its whole duration, blocking `/steer`, `/followup`, and every other
@@ -44,7 +44,7 @@ export interface JobManagerOptions {
44
44
  /** Directory for this channel's persisted job records. Omit to run without persistence. */
45
45
  stateDir?: string;
46
46
  /** Delivers the completion wake. Omit to disable waking (sub-agent and test paths). */
47
- dispatch?: (event: DingTalkEvent) => boolean | Promise<boolean>;
47
+ dispatch?: (event: ChannelEvent) => boolean | Promise<boolean>;
48
48
  sweepIntervalMs?: number;
49
49
  }
50
50
  /** Cap on concurrently running jobs per channel, so a runaway model can't spawn unbounded processes. */
@@ -166,7 +166,7 @@ export declare class ChannelJobManager {
166
166
  interface JobRuntimeConfig {
167
167
  /** Root of the per-channel record directories (`<jobsStateDir>/<channelId>/`). */
168
168
  jobsStateDir?: string;
169
- dispatch?: (event: DingTalkEvent) => boolean | Promise<boolean>;
169
+ dispatch?: (event: ChannelEvent) => boolean | Promise<boolean>;
170
170
  }
171
171
  /**
172
172
  * Give background jobs their persistence root and their way to wake a channel. Called once from
@@ -356,7 +356,6 @@ export class ChannelJobManager {
356
356
  `Full output: ${record.spillFile}\n` +
357
357
  "Continue whatever was waiting on this job. If it needs no follow-up, respond with exactly [SILENT].",
358
358
  ts: String(Date.now()),
359
- conversationId: "",
360
359
  conversationType: this.channelId.startsWith("group_") ? "2" : "1",
361
360
  dispatchId: `job:${this.channelId}:${record.id}:done`,
362
361
  ...(record.contract.taskId
@@ -1,19 +1,31 @@
1
1
  import type { MediaSender } from "../runtime/channel-context.js";
2
+ import type { PipiclawSettingsManager } from "../settings.js";
2
3
  import type { AgentRunner } from "./types.js";
3
4
  export interface RunnerFactoryPaths {
4
5
  appHomeDir: string;
5
6
  authConfigPath: string;
6
7
  modelsConfigPath: string;
8
+ /**
9
+ * The single app-level settings manager (from `prepareAppServices`), shared across every
10
+ * channel's runner rather than each constructing its own. Keeps `drainErrors()`/diagnostics
11
+ * ordering and `reload()`'s file-stamp guard meaningful instead of racing N independent copies.
12
+ */
13
+ settingsManager: PipiclawSettingsManager;
7
14
  /** Optional, side-effect-free observer used by the behavior-eval harness. */
8
15
  onSessionEvent?: (event: unknown, channelId: string) => void;
9
16
  /**
10
17
  * Transport that can deliver file attachments (the DingTalk bot, or the terminal).
11
- * Present enables the `send_media` tool; absent, the tool is not built. Not part
12
- * of the runner cache key — it is a stable per-process transport handle.
18
+ * Present enables the `send_media` tool; absent, the tool is not built.
13
19
  */
14
20
  mediaSender?: MediaSender;
15
21
  /** Runtime callback that durably enqueues an independent task verifier. */
16
22
  dispatchVerification?: (taskId: string) => Promise<boolean>;
17
23
  }
18
- export declare function getOrCreateRunner(channelId: string, channelDir: string, paths: RunnerFactoryPaths): AgentRunner;
19
- export declare function resetRunner(channelId: string, paths?: RunnerFactoryPaths, channelDir?: string): void;
24
+ /**
25
+ * Stateless: always constructs a fresh runner. The daemon (`runtime/bootstrap.ts`) and the TUI
26
+ * (`tui/app.ts`) are the only two callers, and each already owns exactly one cache appropriate to
27
+ * its own lifecycle (the daemon's runtime channel map with LRU eviction; the TUI's single local
28
+ * `const`, one channel per process) — a second cache here just duplicated that ownership and
29
+ * could hold a stale entry the real owner had already disposed.
30
+ */
31
+ export declare function createRunner(channelId: string, channelDir: string, paths: RunnerFactoryPaths): AgentRunner;
@@ -1,25 +1,11 @@
1
1
  import { ChannelRunner } from "./channel-runner.js";
2
- const channelRunners = new Map();
3
- function runnerKey(paths, channelId, channelDir) {
4
- return `${paths.appHomeDir}\0${channelDir}\0${channelId}`;
5
- }
6
- export function getOrCreateRunner(channelId, channelDir, paths) {
7
- const key = runnerKey(paths, channelId, channelDir);
8
- const existing = channelRunners.get(key);
9
- if (existing)
10
- return existing;
11
- const runner = new ChannelRunner(channelId, channelDir, paths);
12
- channelRunners.set(key, runner);
13
- return runner;
14
- }
15
- export function resetRunner(channelId, paths, channelDir) {
16
- if (paths && channelDir) {
17
- channelRunners.delete(runnerKey(paths, channelId, channelDir));
18
- return;
19
- }
20
- for (const key of channelRunners.keys()) {
21
- if (key.endsWith(`\0${channelId}`)) {
22
- channelRunners.delete(key);
23
- }
24
- }
2
+ /**
3
+ * Stateless: always constructs a fresh runner. The daemon (`runtime/bootstrap.ts`) and the TUI
4
+ * (`tui/app.ts`) are the only two callers, and each already owns exactly one cache appropriate to
5
+ * its own lifecycle (the daemon's runtime channel map with LRU eviction; the TUI's single local
6
+ * `const`, one channel per process) — a second cache here just duplicated that ownership and
7
+ * could hold a stale entry the real owner had already disposed.
8
+ */
9
+ export function createRunner(channelId, channelDir, paths) {
10
+ return new ChannelRunner(channelId, channelDir, paths);
25
11
  }
@@ -1,7 +1,7 @@
1
1
  import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
2
2
  import type { ChannelContext } from "../runtime/channel-context.js";
3
3
  import type { ChannelStore } from "../runtime/store.js";
4
- import type { UsageTotals } from "../shared/types.js";
4
+ import { type UsageTotals } from "../shared/types.js";
5
5
  import type { SubAgentDiscoveryResult } from "../subagents/discovery.js";
6
6
  import type { RunnerBuiltInCommand } from "./commands.js";
7
7
  export interface RunnerStatusSnapshot {
@@ -77,6 +77,14 @@ export interface AgentRunner {
77
77
  /** Mark the current turn as user-stopped (no-op when idle). */
78
78
  requestStop(): void;
79
79
  getTurnStatus(): TurnStatus;
80
+ /**
81
+ * Release this runner's resources: flush pending memory, unsubscribe from session events, and
82
+ * dispose the underlying SDK session. A no-op (memory still flushed) while `isBusy()` — disposing
83
+ * the SDK session aborts in-flight work, so a caller must never call this on a busy runner and
84
+ * expect the turn to survive. The owning cache (daemon runtime map, TUI's single runner) must
85
+ * drop its own reference after calling this; a disposed runner is not reusable.
86
+ */
87
+ dispose(): Promise<void>;
80
88
  }
81
89
  export type FinalOutcome = {
82
90
  kind: "none";
@@ -1,3 +1,4 @@
1
+ import { createEmptyUsageTotals } from "../shared/types.js";
1
2
  export function createEmptyRunState() {
2
3
  return {
3
4
  ctx: null,
@@ -5,22 +6,8 @@ export function createEmptyRunState() {
5
6
  store: null,
6
7
  queue: null,
7
8
  pendingTools: new Map(),
8
- totalUsage: {
9
- input: 0,
10
- output: 0,
11
- cacheRead: 0,
12
- cacheWrite: 0,
13
- total: 0,
14
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
15
- },
16
- assistantUsage: {
17
- input: 0,
18
- output: 0,
19
- cacheRead: 0,
20
- cacheWrite: 0,
21
- total: 0,
22
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
23
- },
9
+ totalUsage: createEmptyUsageTotals(),
10
+ assistantUsage: createEmptyUsageTotals(),
24
11
  costKnown: true,
25
12
  usageSources: 0,
26
13
  stopReason: "stop",
@@ -3,7 +3,8 @@ import { type Executor } from "../executor.js";
3
3
  import { PipiclawSettingsManager } from "../settings.js";
4
4
  import { type WakeTaskTransitionHooks } from "../tasks/store.js";
5
5
  import { type BootstrapIO, type BootstrapPaths } from "./app-home.js";
6
- import { DingTalkBot, type DingTalkConfig, type DingTalkEvent, type DingTalkHandler } from "./dingtalk.js";
6
+ import type { ChannelEvent } from "./channel-event.js";
7
+ import { DingTalkBot, type DingTalkConfig, type DingTalkHandler } from "./dingtalk.js";
7
8
  import { ChannelStore } from "./store.js";
8
9
  export interface BootstrapOptions {
9
10
  env?: NodeJS.ProcessEnv;
@@ -76,13 +77,20 @@ interface RuntimeContextOptions {
76
77
  /** Receives raw SDK session events after subscription, without changing runtime handling. */
77
78
  observer?: (event: unknown, channelId: string) => void;
78
79
  /** Receives TaskDriver dispatch outcomes; used only by isolated evaluation workers. */
79
- onTaskDriverDispatch?: (event: DingTalkEvent, accepted: boolean) => void;
80
+ onTaskDriverDispatch?: (event: ChannelEvent, accepted: boolean) => void;
80
81
  startServices?: boolean;
81
82
  registerSignalHandlers?: boolean;
82
83
  /** Test-only fault seams for the atomic structured-wake task transition. */
83
84
  wakeTransitionHooks?: Partial<Record<"job" | "subagent", WakeTaskTransitionHooks>>;
84
85
  /** Override the `/stop` watchdog's grace window (tests use a short one). */
85
86
  stopForceEndGraceMs?: number;
87
+ /**
88
+ * The app-level settings manager, shared by every channel's runner (see
89
+ * `agent/runner-factory.ts`'s `RunnerFactoryPaths.settingsManager`). `bootstrap()` passes the
90
+ * same instance `prepareAppServices()` already constructed and diagnosed; a caller that skips
91
+ * `prepareAppServices()` (tests) gets one built here instead.
92
+ */
93
+ settingsManager?: PipiclawSettingsManager;
86
94
  }
87
95
  export declare function createRuntimeContext(options: RuntimeContextOptions): Promise<RuntimeContext & {
88
96
  bot: DingTalkBot;
@@ -2,10 +2,9 @@ import { existsSync, mkdirSync, writeFileSync } from "fs";
2
2
  import { join } from "path";
3
3
  import { formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../agent/commands.js";
4
4
  import { channelEffectCount, noteTaskEffects, taskEffectCount } from "../agent/effect-ledger.js";
5
- import { getOrCreateRunner } from "../agent/index.js";
5
+ import { createRunner } from "../agent/index.js";
6
6
  import { configureJobRuntime, restoreChannelJobs } from "../agent/job-manager.js";
7
7
  import { loadDetachedMaintenanceContext } from "../agent/maintenance-context.js";
8
- import { resetRunner } from "../agent/runner-factory.js";
9
8
  import { renderStatus } from "../agent/status-render.js";
10
9
  import { createExecutor } from "../executor.js";
11
10
  import * as log from "../log.js";
@@ -56,17 +55,32 @@ function waitForTasks(tasks, timeoutMs) {
56
55
  });
57
56
  });
58
57
  }
59
- function flushInactiveChannelMemory(channelRunners) {
60
- const flushes = [];
58
+ /**
59
+ * Ceiling on cached runners per daemon process. A long-lived daemon otherwise accumulates one
60
+ * `ChannelRunner` (session, subscriptions, memory state) per distinct channel it has ever heard
61
+ * from, unbounded, for the life of the process. Eviction below only ever touches idle runners —
62
+ * a busy one is left cached past the cap rather than mid-turn disposed.
63
+ */
64
+ const MAX_CACHED_RUNNERS = 50;
65
+ /**
66
+ * Drop the least-recently-used *idle* runners until the cache is back at the cap, disposing each
67
+ * one (flush memory, unsubscribe, release the SDK session) before dropping it. `channelRunners`
68
+ * is a `Map`, so insertion order is iteration order; `getRunner` below re-inserts on every cache
69
+ * hit to keep that order equal to recency of use — the standard "LRU via Map" idiom.
70
+ */
71
+ async function evictIdleRunnersOverCap(channelRunners) {
72
+ if (channelRunners.size <= MAX_CACHED_RUNNERS)
73
+ return;
61
74
  for (const [channelId, runner] of channelRunners) {
62
- if (runner.isBusy()) {
75
+ if (channelRunners.size <= MAX_CACHED_RUNNERS)
76
+ break;
77
+ if (runner.isBusy())
63
78
  continue;
64
- }
65
- flushes.push(runner.flushMemoryForShutdown().catch((err) => {
66
- log.logWarning(`[${channelId}] Failed to flush memory during shutdown`, errorMessage(err));
67
- }));
79
+ channelRunners.delete(channelId);
80
+ await runner.dispose().catch((err) => {
81
+ log.logWarning(`[${channelId}] Failed to dispose evicted runner`, errorMessage(err));
82
+ });
68
83
  }
69
- return flushes;
70
84
  }
71
85
  function isNoRunningTaskQueueError(err) {
72
86
  return err instanceof Error && err.message === "No task is currently running.";
@@ -117,7 +131,7 @@ export async function createRuntimeContext(options) {
117
131
  const startServices = options.startServices ?? true;
118
132
  const registerSignalHandlers = options.registerSignalHandlers ?? true;
119
133
  const store = new ChannelStore({ workingDir: options.paths.workspaceDir });
120
- const runtimeSettingsManager = new PipiclawSettingsManager(options.paths.appHomeDir);
134
+ const runtimeSettingsManager = options.settingsManager ?? new PipiclawSettingsManager(options.paths.appHomeDir);
121
135
  log.configureLogging(runtimeSettingsManager.getLoggingSettings());
122
136
  const startedAt = Date.now();
123
137
  const cliVersion = readCliVersion();
@@ -140,30 +154,37 @@ export async function createRuntimeContext(options) {
140
154
  }
141
155
  };
142
156
  const getRunner = (channelId) => {
143
- let runner = channelRunners.get(channelId);
144
- if (!runner) {
145
- const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
146
- ensureChannelMemoryFilesSync(channelDir);
147
- runner = getOrCreateRunner(channelId, channelDir, {
148
- appHomeDir: options.paths.appHomeDir,
149
- authConfigPath: options.paths.authConfigPath,
150
- modelsConfigPath: options.paths.modelsConfigPath,
151
- onSessionEvent: options.observer,
152
- // The DingTalk bot is the media sender for this transport; enables `send_media`.
153
- // `bot` is defined below in this same scope and initialized before any message
154
- // (and thus any getRunner call) can arrive.
155
- mediaSender: bot,
156
- dispatchVerification: async (taskId) => {
157
- const entries = await readActiveTasks(join(channelDir, "tasks"));
158
- const entry = entries.find((candidate) => candidate.id === taskId);
159
- if (!entry)
160
- return false;
161
- const verificationEvent = createTaskVerificationEvent(channelId, entry, Date.now());
162
- return (await durableDispatch?.dispatch(verificationEvent)) ?? false;
163
- },
164
- });
165
- channelRunners.set(channelId, runner);
157
+ const existing = channelRunners.get(channelId);
158
+ if (existing) {
159
+ // Re-insert to move this channel to the end (most-recently-used) of the Map's
160
+ // iteration order, which evictIdleRunnersOverCap relies on.
161
+ channelRunners.delete(channelId);
162
+ channelRunners.set(channelId, existing);
163
+ return existing;
166
164
  }
165
+ const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
166
+ ensureChannelMemoryFilesSync(channelDir);
167
+ const runner = createRunner(channelId, channelDir, {
168
+ appHomeDir: options.paths.appHomeDir,
169
+ authConfigPath: options.paths.authConfigPath,
170
+ modelsConfigPath: options.paths.modelsConfigPath,
171
+ settingsManager: runtimeSettingsManager,
172
+ onSessionEvent: options.observer,
173
+ // The DingTalk bot is the media sender for this transport; enables `send_media`.
174
+ // `bot` is defined below in this same scope and initialized before any message
175
+ // (and thus any getRunner call) can arrive.
176
+ mediaSender: bot,
177
+ dispatchVerification: async (taskId) => {
178
+ const entries = await readActiveTasks(join(channelDir, "tasks"));
179
+ const entry = entries.find((candidate) => candidate.id === taskId);
180
+ if (!entry)
181
+ return false;
182
+ const verificationEvent = createTaskVerificationEvent(channelId, entry, Date.now());
183
+ return (await durableDispatch?.dispatch(verificationEvent)) ?? false;
184
+ },
185
+ });
186
+ channelRunners.set(channelId, runner);
187
+ void evictIdleRunnersOverCap(channelRunners);
167
188
  return runner;
168
189
  };
169
190
  const handler = {
@@ -646,23 +667,25 @@ export async function createRuntimeContext(options) {
646
667
  }
647
668
  }
648
669
  }
649
- const flushes = flushInactiveChannelMemory(channelRunners);
650
- if (flushes.length > 0) {
651
- log.logInfo(`Flushing memory for ${flushes.length} inactive channel(s) before shutdown`);
652
- const flushed = await waitForTasks(flushes, SHUTDOWN_FLUSH_WAIT_MS);
653
- if (!flushed) {
654
- log.logWarning(`Shutdown memory flush exceeded ${SHUTDOWN_FLUSH_WAIT_MS}ms`);
655
- }
670
+ // Idle runners are disposed (flush memory, unsubscribe, release the SDK session); a
671
+ // still-busy one — its turn already aborted above — is just dropped from the cache and
672
+ // left to unwind on its own as the process exits.
673
+ const disposals = [];
674
+ for (const [channelId, runner] of channelRunners) {
675
+ if (runner.isBusy())
676
+ continue;
677
+ disposals.push(runner.dispose().catch((err) => {
678
+ log.logWarning(`[${channelId}] Failed to dispose runner during shutdown`, errorMessage(err));
679
+ }));
656
680
  }
657
- for (const channelId of channelRunners.keys()) {
658
- const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
659
- resetRunner(channelId, {
660
- appHomeDir: options.paths.appHomeDir,
661
- authConfigPath: options.paths.authConfigPath,
662
- modelsConfigPath: options.paths.modelsConfigPath,
663
- onSessionEvent: options.observer,
664
- }, channelDir);
681
+ if (disposals.length > 0) {
682
+ log.logInfo(`Disposing ${disposals.length} idle channel runner(s) before shutdown`);
683
+ const disposed = await waitForTasks(disposals, SHUTDOWN_FLUSH_WAIT_MS);
684
+ if (!disposed) {
685
+ log.logWarning(`Shutdown runner disposal exceeded ${SHUTDOWN_FLUSH_WAIT_MS}ms`);
686
+ }
665
687
  }
688
+ channelRunners.clear();
666
689
  const storageFlushes = [
667
690
  store.close(),
668
691
  // Cancels the debounce timer and lands the last activity times.
@@ -775,13 +798,14 @@ export async function bootstrap(argv, options = {}) {
775
798
  }
776
799
  const dingtalkConfig = loadConfig(paths, io);
777
800
  dingtalkConfig.stateDir = paths.workspaceDir;
778
- prepareAppServices(paths);
801
+ const { settingsManager } = prepareAppServices(paths);
779
802
  log.logStartup(paths.workspaceDir);
780
803
  const runtime = await createRuntimeContext({
781
804
  paths,
782
805
  dingtalkConfig,
783
806
  registerSignalHandlers,
784
807
  startServices,
808
+ settingsManager,
785
809
  });
786
810
  return {
787
811
  bot: runtime.bot,
@@ -0,0 +1,41 @@
1
+ /**
2
+ * A message or wake, from any producer: a real inbound DingTalk message, a scheduled event, a
3
+ * task-driver wake, or a job/subagent completion. `conversationId` is the one field genuinely
4
+ * DingTalk-specific (needed to reply into the right conversation); every synthetic producer
5
+ * (job-manager, task-driver, events, subagents/runs) leaves it unset rather than faking a value,
6
+ * since it has no DingTalk conversation to route into. `conversationType` is not DingTalk-specific
7
+ * in practice — every producer, real or synthetic, can derive "1"/"2" from the channelId prefix —
8
+ * so it stays required.
9
+ */
10
+ export interface ChannelEvent {
11
+ type: "dm" | "group";
12
+ channelId: string;
13
+ ts: string;
14
+ user: string;
15
+ userName: string;
16
+ text: string;
17
+ /** DingTalk conversation id; absent on synthetic events, which have no DingTalk conversation. */
18
+ conversationId?: string;
19
+ conversationType: string;
20
+ /**
21
+ * Human-readable channel name: the group title, or the peer's nickname for a DM. Absent on
22
+ * synthetic events (scheduled events, task-driver wakes), which carry no conversation payload.
23
+ */
24
+ channelName?: string;
25
+ /** Runtime-owned durable-dispatch record, absent for normal inbound messages. */
26
+ dispatchId?: string;
27
+ /** Structured wake provenance created only by in-process producers. DingTalk inbound parsing
28
+ * never copies arbitrary payload fields into this event, so user text cannot manufacture it. */
29
+ internalWake?: {
30
+ kind: "job" | "subagent";
31
+ resourceId: string;
32
+ taskId: string;
33
+ dispatchId: string;
34
+ };
35
+ /**
36
+ * The `attemptGeneration` this event's claim recorded, for `[TASK_DRIVER:id]` events only.
37
+ * Carried through durable dispatch so `finishTaskAttempt` can tell a stale, superseded claim's
38
+ * turn from the current one, even when redelivery or claim races reorder completions.
39
+ */
40
+ taskAttemptGeneration?: number;
41
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,5 +1,6 @@
1
1
  import type { ChannelContext, ProgressStyle } from "./channel-context.js";
2
- import type { DingTalkBot, DingTalkEvent } from "./dingtalk.js";
2
+ import type { ChannelEvent } from "./channel-event.js";
3
+ import type { DingTalkBot } from "./dingtalk.js";
3
4
  import type { ChannelStore } from "./store.js";
4
5
  /**
5
6
  * Build the delivery contract for one turn.
@@ -11,4 +12,4 @@ import type { ChannelStore } from "./store.js";
11
12
  * final answer is unaffected; it is delivered by `respondPlain`/`replaceMessage` either way, so a
12
13
  * background turn that has something to say still says it.
13
14
  */
14
- export declare function createDingTalkContext(event: DingTalkEvent, bot: DingTalkBot, store: ChannelStore, progressStyleOverride?: ProgressStyle): ChannelContext;
15
+ export declare function createDingTalkContext(event: ChannelEvent, bot: DingTalkBot, store: ChannelStore, progressStyleOverride?: ProgressStyle): ChannelContext;
@@ -1,5 +1,6 @@
1
1
  import { type RuntimeCommandName } from "../agent/commands.js";
2
2
  import type { FinalDelivery, MediaSender, MediaSendResult, OutboundMedia, ProgressStyle } from "./channel-context.js";
3
+ import type { ChannelEvent } from "./channel-event.js";
3
4
  import type { ChannelObservation } from "./channel-index.js";
4
5
  export type BusyMessageMode = "steer" | "followUp";
5
6
  export type BusyMessageDefaultConfig = BusyMessageMode | "followup";
@@ -22,37 +23,14 @@ export interface DingTalkConfig {
22
23
  responseMode?: ResponseMode;
23
24
  cardAutoLayout?: boolean;
24
25
  }
25
- export interface DingTalkEvent {
26
- type: "dm" | "group";
27
- channelId: string;
28
- ts: string;
29
- user: string;
30
- userName: string;
31
- text: string;
32
- conversationId: string;
33
- conversationType: string;
34
- /**
35
- * Human-readable channel name: the group title, or the peer's nickname for a DM. Absent on
36
- * synthetic events (scheduled events, task-driver wakes), which carry no conversation payload.
37
- */
38
- channelName?: string;
39
- /** Runtime-owned durable-dispatch record, absent for normal inbound messages. */
40
- dispatchId?: string;
41
- /** Structured wake provenance created only by in-process producers. DingTalk inbound parsing
42
- * never copies arbitrary payload fields into this event, so user text cannot manufacture it. */
43
- internalWake?: {
44
- kind: "job" | "subagent";
45
- resourceId: string;
46
- taskId: string;
47
- dispatchId: string;
48
- };
49
- /**
50
- * The `attemptGeneration` this event's claim recorded, for `[TASK_DRIVER:id]` events only.
51
- * Carried through durable dispatch so `finishTaskAttempt` can tell a stale, superseded claim's
52
- * turn from the current one, even when redelivery or claim races reorder completions.
53
- */
54
- taskAttemptGeneration?: number;
55
- }
26
+ /**
27
+ * `DingTalkEvent` is kept as the public name (spec 035 D4: `src/index.ts`'s barrel is a
28
+ * compatibility promise, so exported names there stay stable). Internally the type now lives in
29
+ * `channel-event.ts` as `ChannelEvent`: most producers of this shape are not DingTalk at all
30
+ * (job-manager, task-driver, events, subagents/runs all synthesize wakes), so `ChannelEvent` is
31
+ * what the rest of the runtime imports.
32
+ */
33
+ export type DingTalkEvent = ChannelEvent;
56
34
  export type BusyMessageResult = {
57
35
  kind: "handled";
58
36
  } | {
@@ -1,4 +1,5 @@
1
- import type { DingTalkBot, DingTalkEvent } from "./dingtalk.js";
1
+ import type { ChannelEvent } from "./channel-event.js";
2
+ import type { DingTalkBot } from "./dingtalk.js";
2
3
  export interface DurableDispatchOptions {
3
4
  stateDir: string;
4
5
  bot: Pick<DingTalkBot, "enqueueEvent">;
@@ -29,7 +30,7 @@ export declare class DurableDispatchService {
29
30
  constructor(options: DurableDispatchOptions);
30
31
  start(): void;
31
32
  stop(): void;
32
- dispatch(event: DingTalkEvent): Promise<boolean>;
33
+ dispatch(event: ChannelEvent): Promise<boolean>;
33
34
  /** Reset any in-flight records for a channel so a stop/abort can redeliver on the next tick, not after the lease expires. */
34
35
  cancelChannel(channelId: string): Promise<number>;
35
36
  markStarted(id: string | undefined): Promise<void>;
@@ -1,6 +1,7 @@
1
1
  import type { Executor } from "../executor.js";
2
2
  import type { SecurityConfig } from "../security/types.js";
3
- import type { DingTalkBot, DingTalkEvent } from "./dingtalk.js";
3
+ import type { ChannelEvent } from "./channel-event.js";
4
+ import type { DingTalkBot } from "./dingtalk.js";
4
5
  export interface EventAction {
5
6
  type: "bash";
6
7
  command: string;
@@ -56,7 +57,7 @@ export interface EventHistoryRecord {
56
57
  export interface EventsWatcherOptions {
57
58
  historyPath?: string;
58
59
  /** Persist synthetic work before it enters the in-memory channel queue. */
59
- dispatch?: (event: DingTalkEvent) => boolean | Promise<boolean>;
60
+ dispatch?: (event: ChannelEvent) => boolean | Promise<boolean>;
60
61
  }
61
62
  export declare function parseScheduledEventContent(content: string, filename: string): ScheduledEvent;
62
63
  export declare class EventsWatcher {
@@ -6,9 +6,9 @@ import * as log from "../log.js";
6
6
  import { guardCommand } from "../security/command-guard.js";
7
7
  import { createJsonlAppender } from "../shared/jsonl-appender.js";
8
8
  import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
9
- import { taskEventPrefix } from "../shared/task-events.js";
10
9
  import { errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
11
10
  import { parseTaskFrontmatter } from "../tasks/ledger.js";
11
+ import { taskEventPrefix } from "../tasks/task-events.js";
12
12
  import { MAX_EVENT_FILES, MAX_ONE_SHOT_DELAY_MS, validateScheduledEvent } from "./event-validation.js";
13
13
  // ============================================================================
14
14
  // EventsWatcher
@@ -567,7 +567,7 @@ export class EventsWatcher {
567
567
  ? " This is a periodic runtime wake. If it produces no user-visible change or result, reply with exactly [SILENT]."
568
568
  : "";
569
569
  const message = `[EVENT:${filename}:${event.type}:${scheduleInfo}] ${event.text}${periodicContract}`;
570
- // Create synthetic DingTalkEvent
570
+ // Create synthetic ChannelEvent
571
571
  const syntheticEvent = {
572
572
  type: "dm",
573
573
  channelId: event.channelId,
@@ -575,7 +575,6 @@ export class EventsWatcher {
575
575
  userName: "EVENT",
576
576
  text: message,
577
577
  ts: Date.now().toString(),
578
- conversationId: "",
579
578
  conversationType: "1",
580
579
  dispatchId: eventDispatchId(filename, event, occurrence),
581
580
  };
@@ -3,8 +3,6 @@ import { readdir, readFile } from "node:fs/promises";
3
3
  import { join, resolve, sep } from "node:path";
4
4
  import { channelJobTaskIds } from "../agent/job-manager.js";
5
5
  import { formatLocalTime, parseLocalTime, parseWakeInput } from "../shared/local-time.js";
6
- import { parseTaskEventName, taskEventPrefix } from "../shared/task-events.js";
7
- import { nextTaskWake, validateTaskSchedule } from "../shared/task-schedule.js";
8
6
  import { errorMessage } from "../shared/text-utils.js";
9
7
  import { isRecord } from "../shared/type-guards.js";
10
8
  import { channelDelegationTaskIds } from "../subagents/runs.js";
@@ -12,6 +10,8 @@ import { applyTaskControlPatch, createDefaultTaskControl, retiredTaskControlKeys
12
10
  import { countTaskDodItems, extractTaskTitle, isTaskParked, missingStandardTaskSections, normalizeTaskId, readActiveTasks, recurringTaskMissedOccurrence, } from "../tasks/ledger.js";
13
11
  import { withTaskMutation } from "../tasks/mutation-lock.js";
14
12
  import { claimTaskAttempt, openRecurringTaskCycle, readStoredTask, releaseTaskAttemptClaim, taskBodyHash, writeStoredTask, } from "../tasks/store.js";
13
+ import { parseTaskEventName, taskEventPrefix } from "../tasks/task-events.js";
14
+ import { nextTaskWake, validateTaskSchedule } from "../tasks/task-schedule.js";
15
15
  import { normalizeStoredStatus, resolveTaskTransition } from "../tasks/transitions.js";
16
16
  import { readVerificationAttestation } from "../tasks/verification.js";
17
17
  import { parseScheduledEventContent } from "./events.js";