@aitne/daemon 0.1.3 → 0.1.4

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 (249) hide show
  1. package/dist/adapters/whatsapp-adapter.d.ts.map +1 -1
  2. package/dist/adapters/whatsapp-adapter.js +0 -1
  3. package/dist/adapters/whatsapp-adapter.js.map +1 -1
  4. package/dist/api/integration-route-gate.d.ts +15 -11
  5. package/dist/api/integration-route-gate.d.ts.map +1 -1
  6. package/dist/api/integration-route-gate.js +60 -23
  7. package/dist/api/integration-route-gate.js.map +1 -1
  8. package/dist/api/json-body.d.ts +22 -7
  9. package/dist/api/json-body.d.ts.map +1 -1
  10. package/dist/api/json-body.js +27 -8
  11. package/dist/api/json-body.js.map +1 -1
  12. package/dist/api/routes/agent.d.ts.map +1 -1
  13. package/dist/api/routes/agent.js +18 -0
  14. package/dist/api/routes/agent.js.map +1 -1
  15. package/dist/api/routes/backends.d.ts.map +1 -1
  16. package/dist/api/routes/backends.js +96 -1
  17. package/dist/api/routes/backends.js.map +1 -1
  18. package/dist/api/routes/books.js +1 -1
  19. package/dist/api/routes/books.js.map +1 -1
  20. package/dist/api/routes/context.d.ts.map +1 -1
  21. package/dist/api/routes/context.js +13 -1
  22. package/dist/api/routes/context.js.map +1 -1
  23. package/dist/api/routes/dashboard.d.ts.map +1 -1
  24. package/dist/api/routes/dashboard.js +75 -5
  25. package/dist/api/routes/dashboard.js.map +1 -1
  26. package/dist/api/routes/github.d.ts.map +1 -1
  27. package/dist/api/routes/github.js +38 -5
  28. package/dist/api/routes/github.js.map +1 -1
  29. package/dist/api/routes/integrations.d.ts +35 -6
  30. package/dist/api/routes/integrations.d.ts.map +1 -1
  31. package/dist/api/routes/integrations.js +191 -16
  32. package/dist/api/routes/integrations.js.map +1 -1
  33. package/dist/api/routes/mail.d.ts.map +1 -1
  34. package/dist/api/routes/mail.js +112 -46
  35. package/dist/api/routes/mail.js.map +1 -1
  36. package/dist/api/routes/observations.d.ts.map +1 -1
  37. package/dist/api/routes/observations.js +161 -8
  38. package/dist/api/routes/observations.js.map +1 -1
  39. package/dist/api/routes/setup-migrate.d.ts +9 -1
  40. package/dist/api/routes/setup-migrate.d.ts.map +1 -1
  41. package/dist/api/routes/setup-migrate.js +4 -2
  42. package/dist/api/routes/setup-migrate.js.map +1 -1
  43. package/dist/api/routes/skills.d.ts.map +1 -1
  44. package/dist/api/routes/skills.js +39 -1
  45. package/dist/api/routes/skills.js.map +1 -1
  46. package/dist/api/routes/voice.d.ts.map +1 -1
  47. package/dist/api/routes/voice.js +62 -4
  48. package/dist/api/routes/voice.js.map +1 -1
  49. package/dist/bootstrap/adapters.d.ts +109 -0
  50. package/dist/bootstrap/adapters.d.ts.map +1 -0
  51. package/dist/bootstrap/adapters.js +237 -0
  52. package/dist/bootstrap/adapters.js.map +1 -0
  53. package/dist/bootstrap/catchup.d.ts +23 -0
  54. package/dist/bootstrap/catchup.d.ts.map +1 -0
  55. package/dist/bootstrap/catchup.js +124 -0
  56. package/dist/bootstrap/catchup.js.map +1 -0
  57. package/dist/bootstrap/schedule-helpers.d.ts +18 -0
  58. package/dist/bootstrap/schedule-helpers.d.ts.map +1 -0
  59. package/dist/bootstrap/schedule-helpers.js +96 -0
  60. package/dist/bootstrap/schedule-helpers.js.map +1 -0
  61. package/dist/bootstrap/services.d.ts +60 -0
  62. package/dist/bootstrap/services.d.ts.map +1 -0
  63. package/dist/bootstrap/services.js +209 -0
  64. package/dist/bootstrap/services.js.map +1 -0
  65. package/dist/core/backends/backend-router.d.ts +23 -0
  66. package/dist/core/backends/backend-router.d.ts.map +1 -1
  67. package/dist/core/backends/backend-router.js +48 -3
  68. package/dist/core/backends/backend-router.js.map +1 -1
  69. package/dist/core/backends/claude-auth.d.ts +70 -0
  70. package/dist/core/backends/claude-auth.d.ts.map +1 -0
  71. package/dist/core/backends/claude-auth.js +198 -0
  72. package/dist/core/backends/claude-auth.js.map +1 -0
  73. package/dist/core/backends/claude-code-core.d.ts +47 -119
  74. package/dist/core/backends/claude-code-core.d.ts.map +1 -1
  75. package/dist/core/backends/claude-code-core.js +112 -1565
  76. package/dist/core/backends/claude-code-core.js.map +1 -1
  77. package/dist/core/backends/claude-delegated.d.ts +86 -0
  78. package/dist/core/backends/claude-delegated.d.ts.map +1 -0
  79. package/dist/core/backends/claude-delegated.js +801 -0
  80. package/dist/core/backends/claude-delegated.js.map +1 -0
  81. package/dist/core/backends/claude-errors.d.ts +39 -0
  82. package/dist/core/backends/claude-errors.d.ts.map +1 -0
  83. package/dist/core/backends/claude-errors.js +71 -0
  84. package/dist/core/backends/claude-errors.js.map +1 -0
  85. package/dist/core/backends/claude-probe.d.ts +103 -0
  86. package/dist/core/backends/claude-probe.d.ts.map +1 -0
  87. package/dist/core/backends/claude-probe.js +336 -0
  88. package/dist/core/backends/claude-probe.js.map +1 -0
  89. package/dist/core/backends/claude-tool-collection.d.ts +135 -0
  90. package/dist/core/backends/claude-tool-collection.d.ts.map +1 -0
  91. package/dist/core/backends/claude-tool-collection.js +831 -0
  92. package/dist/core/backends/claude-tool-collection.js.map +1 -0
  93. package/dist/core/backends/gemini-cli-core.d.ts +21 -0
  94. package/dist/core/backends/gemini-cli-core.d.ts.map +1 -1
  95. package/dist/core/backends/gemini-cli-core.js +84 -6
  96. package/dist/core/backends/gemini-cli-core.js.map +1 -1
  97. package/dist/core/backends/prompt-utils.d.ts +1 -0
  98. package/dist/core/backends/prompt-utils.d.ts.map +1 -1
  99. package/dist/core/backends/prompt-utils.js +60 -3
  100. package/dist/core/backends/prompt-utils.js.map +1 -1
  101. package/dist/core/context-builder.d.ts +36 -12
  102. package/dist/core/context-builder.d.ts.map +1 -1
  103. package/dist/core/context-builder.js +179 -89
  104. package/dist/core/context-builder.js.map +1 -1
  105. package/dist/core/dispatcher-date-utils.d.ts +49 -0
  106. package/dist/core/dispatcher-date-utils.d.ts.map +1 -0
  107. package/dist/core/dispatcher-date-utils.js +132 -0
  108. package/dist/core/dispatcher-date-utils.js.map +1 -0
  109. package/dist/core/dispatcher-error-handling.d.ts +159 -0
  110. package/dist/core/dispatcher-error-handling.d.ts.map +1 -0
  111. package/dist/core/dispatcher-error-handling.js +393 -0
  112. package/dist/core/dispatcher-error-handling.js.map +1 -0
  113. package/dist/core/dispatcher-hourly-check.d.ts +150 -0
  114. package/dist/core/dispatcher-hourly-check.d.ts.map +1 -0
  115. package/dist/core/dispatcher-hourly-check.js +665 -0
  116. package/dist/core/dispatcher-hourly-check.js.map +1 -0
  117. package/dist/core/dispatcher-message-handler.d.ts +170 -0
  118. package/dist/core/dispatcher-message-handler.d.ts.map +1 -0
  119. package/dist/core/dispatcher-message-handler.js +1054 -0
  120. package/dist/core/dispatcher-message-handler.js.map +1 -0
  121. package/dist/core/dispatcher-morning-routine.d.ts +169 -0
  122. package/dist/core/dispatcher-morning-routine.d.ts.map +1 -0
  123. package/dist/core/dispatcher-morning-routine.js +434 -0
  124. package/dist/core/dispatcher-morning-routine.js.map +1 -0
  125. package/dist/core/dispatcher-prompt.d.ts +107 -0
  126. package/dist/core/dispatcher-prompt.d.ts.map +1 -0
  127. package/dist/core/dispatcher-prompt.js +227 -0
  128. package/dist/core/dispatcher-prompt.js.map +1 -0
  129. package/dist/core/dispatcher-repository-helpers.d.ts +39 -0
  130. package/dist/core/dispatcher-repository-helpers.d.ts.map +1 -0
  131. package/dist/core/dispatcher-repository-helpers.js +86 -0
  132. package/dist/core/dispatcher-repository-helpers.js.map +1 -0
  133. package/dist/core/dispatcher-result-processor.d.ts +145 -0
  134. package/dist/core/dispatcher-result-processor.d.ts.map +1 -0
  135. package/dist/core/dispatcher-result-processor.js +414 -0
  136. package/dist/core/dispatcher-result-processor.js.map +1 -0
  137. package/dist/core/dispatcher-scheduled-tasks.d.ts +406 -0
  138. package/dist/core/dispatcher-scheduled-tasks.d.ts.map +1 -0
  139. package/dist/core/dispatcher-scheduled-tasks.js +998 -0
  140. package/dist/core/dispatcher-scheduled-tasks.js.map +1 -0
  141. package/dist/core/dispatcher-types.d.ts +296 -0
  142. package/dist/core/dispatcher-types.d.ts.map +1 -0
  143. package/dist/core/dispatcher-types.js +106 -0
  144. package/dist/core/dispatcher-types.js.map +1 -0
  145. package/dist/core/dispatcher.d.ts +86 -610
  146. package/dist/core/dispatcher.d.ts.map +1 -1
  147. package/dist/core/dispatcher.js +293 -3542
  148. package/dist/core/dispatcher.js.map +1 -1
  149. package/dist/core/integration-health.d.ts +18 -10
  150. package/dist/core/integration-health.d.ts.map +1 -1
  151. package/dist/core/integration-health.js +31 -1
  152. package/dist/core/integration-health.js.map +1 -1
  153. package/dist/core/integration-lifecycle.d.ts +65 -0
  154. package/dist/core/integration-lifecycle.d.ts.map +1 -1
  155. package/dist/core/integration-lifecycle.js +167 -16
  156. package/dist/core/integration-lifecycle.js.map +1 -1
  157. package/dist/core/integration-main-backend.d.ts +40 -0
  158. package/dist/core/integration-main-backend.d.ts.map +1 -1
  159. package/dist/core/integration-main-backend.js +89 -2
  160. package/dist/core/integration-main-backend.js.map +1 -1
  161. package/dist/core/management-md.d.ts +51 -17
  162. package/dist/core/management-md.d.ts.map +1 -1
  163. package/dist/core/management-md.js +233 -56
  164. package/dist/core/management-md.js.map +1 -1
  165. package/dist/core/output-language-policy.d.ts +74 -0
  166. package/dist/core/output-language-policy.d.ts.map +1 -0
  167. package/dist/core/output-language-policy.js +194 -0
  168. package/dist/core/output-language-policy.js.map +1 -0
  169. package/dist/core/prompts.d.ts +1 -0
  170. package/dist/core/prompts.d.ts.map +1 -1
  171. package/dist/core/prompts.js +121 -3
  172. package/dist/core/prompts.js.map +1 -1
  173. package/dist/core/repository-management-docs.d.ts +24 -0
  174. package/dist/core/repository-management-docs.d.ts.map +1 -1
  175. package/dist/core/repository-management-docs.js +210 -26
  176. package/dist/core/repository-management-docs.js.map +1 -1
  177. package/dist/core/routine-acquisition-plan.d.ts +131 -0
  178. package/dist/core/routine-acquisition-plan.d.ts.map +1 -0
  179. package/dist/core/routine-acquisition-plan.js +268 -0
  180. package/dist/core/routine-acquisition-plan.js.map +1 -0
  181. package/dist/core/routine-fetch-window-runner.d.ts +201 -0
  182. package/dist/core/routine-fetch-window-runner.d.ts.map +1 -0
  183. package/dist/core/routine-fetch-window-runner.js +661 -0
  184. package/dist/core/routine-fetch-window-runner.js.map +1 -0
  185. package/dist/core/routine-windows.d.ts +156 -0
  186. package/dist/core/routine-windows.d.ts.map +1 -0
  187. package/dist/core/routine-windows.js +330 -0
  188. package/dist/core/routine-windows.js.map +1 -0
  189. package/dist/core/skills-compiler.d.ts +11 -0
  190. package/dist/core/skills-compiler.d.ts.map +1 -1
  191. package/dist/core/skills-compiler.js +102 -13
  192. package/dist/core/skills-compiler.js.map +1 -1
  193. package/dist/core/skills-manifest.d.ts.map +1 -1
  194. package/dist/core/skills-manifest.js +26 -0
  195. package/dist/core/skills-manifest.js.map +1 -1
  196. package/dist/core/system-reset.d.ts.map +1 -1
  197. package/dist/core/system-reset.js +25 -2
  198. package/dist/core/system-reset.js.map +1 -1
  199. package/dist/db/observations.d.ts +45 -2
  200. package/dist/db/observations.d.ts.map +1 -1
  201. package/dist/db/observations.js +112 -14
  202. package/dist/db/observations.js.map +1 -1
  203. package/dist/db/schema.d.ts.map +1 -1
  204. package/dist/db/schema.js +13 -25
  205. package/dist/db/schema.js.map +1 -1
  206. package/dist/index.js +83 -610
  207. package/dist/index.js.map +1 -1
  208. package/dist/observers/delegated-sync-worker.d.ts +45 -2
  209. package/dist/observers/delegated-sync-worker.d.ts.map +1 -1
  210. package/dist/observers/delegated-sync-worker.js +71 -21
  211. package/dist/observers/delegated-sync-worker.js.map +1 -1
  212. package/dist/observers/mail-poller.d.ts +12 -5
  213. package/dist/observers/mail-poller.d.ts.map +1 -1
  214. package/dist/observers/mail-poller.js +36 -14
  215. package/dist/observers/mail-poller.js.map +1 -1
  216. package/dist/observers/manager.d.ts +37 -5
  217. package/dist/observers/manager.d.ts.map +1 -1
  218. package/dist/observers/manager.js +28 -10
  219. package/dist/observers/manager.js.map +1 -1
  220. package/dist/services/delegated-backend-invoker.d.ts +1 -51
  221. package/dist/services/delegated-backend-invoker.d.ts.map +1 -1
  222. package/dist/services/delegated-backend-invoker.js +41 -480
  223. package/dist/services/delegated-backend-invoker.js.map +1 -1
  224. package/dist/services/delegated-invoker-audit.d.ts +94 -0
  225. package/dist/services/delegated-invoker-audit.d.ts.map +1 -0
  226. package/dist/services/delegated-invoker-audit.js +238 -0
  227. package/dist/services/delegated-invoker-audit.js.map +1 -0
  228. package/dist/services/delegated-invoker-cache-hits.d.ts +34 -0
  229. package/dist/services/delegated-invoker-cache-hits.d.ts.map +1 -0
  230. package/dist/services/delegated-invoker-cache-hits.js +104 -0
  231. package/dist/services/delegated-invoker-cache-hits.js.map +1 -0
  232. package/dist/services/delegated-invoker-janitors.d.ts +28 -0
  233. package/dist/services/delegated-invoker-janitors.d.ts.map +1 -0
  234. package/dist/services/delegated-invoker-janitors.js +104 -0
  235. package/dist/services/delegated-invoker-janitors.js.map +1 -0
  236. package/dist/services/delegated-invoker-utils.d.ts +42 -0
  237. package/dist/services/delegated-invoker-utils.d.ts.map +1 -0
  238. package/dist/services/delegated-invoker-utils.js +100 -0
  239. package/dist/services/delegated-invoker-utils.js.map +1 -0
  240. package/dist/services/delegated-task-runtime.d.ts +1 -1
  241. package/dist/services/delegated-task-runtime.js +1 -1
  242. package/dist/services/integrations/snapshot-partitions.d.ts +5 -0
  243. package/dist/services/integrations/snapshot-partitions.d.ts.map +1 -1
  244. package/dist/services/integrations/snapshot-partitions.js +12 -0
  245. package/dist/services/integrations/snapshot-partitions.js.map +1 -1
  246. package/dist/services/voice/transcriber-impl.d.ts.map +1 -1
  247. package/dist/services/voice/transcriber-impl.js +7 -8
  248. package/dist/services/voice/transcriber-impl.js.map +1 -1
  249. package/package.json +2 -2
@@ -1,294 +1,23 @@
1
1
  import type Database from "better-sqlite3";
2
- import type { Event, MessageEvent, AgentResult, BackendId, IntegrationKey, IntegrationState } from "@aitne/shared";
2
+ import type { Event } from "@aitne/shared";
3
3
  import type { AgentConfig } from "../config.js";
4
4
  import type { DocsCitationLookup } from "./docs/citation-validator.js";
5
5
  import type { SignalDetector } from "./signal-detector.js";
6
6
  import type { ServiceRegistry } from "../services/service-registry.js";
7
7
  import { EventBus } from "./event-bus.js";
8
- import { type IAgentRouter } from "./backends/backend-router.js";
8
+ import type { IAgentRouter } from "./backends/backend-router.js";
9
9
  import type { TodayWriteLockManager } from "./today-write-lock.js";
10
10
  import type { RoadmapWriteLockManager } from "./roadmap-write-lock.js";
11
11
  import type { AgentWriteTracker } from "../safety/agent-write-tracker.js";
12
12
  import type { AttachmentStore } from "../services/attachments/store.js";
13
13
  import type { VoiceTranscriber } from "../services/voice/transcriber.js";
14
- import type { SessionInfoPayload } from "../api/chat-binding-query.js";
15
- import type { DeferredSessionEffects } from "./session-manager.js";
16
14
  export type { IAgentCore, StreamCallbacks } from "./agent-core.js";
17
15
  export type { IAgentRouter } from "./backends/backend-router.js";
18
- /**
19
- * P22 §3.4 step 4 — the optimizer-only allowedTools envelope. Every
20
- * `routine.skill_curation` event runs the agent with exactly these tools
21
- * and nothing else. The curl glob is anchored on the daemon's loopback URL
22
- * so a hook-bypassed request still hits the curation API's chokepoint
23
- * (Zod, run-token, smoke test); `Read` is required for the agent to
24
- * consume the inlined data dump under the workdir's `data/` subtree.
25
- *
26
- * Kept narrow on purpose: adding any other tool here widens the optimizer's
27
- * blast radius. If a future signal source needs the agent to write to a
28
- * different surface, add a new curation API endpoint and let the curl glob
29
- * cover it — do NOT add `Bash(*)` or `Write` here.
30
- */
31
- export declare const SKILL_CURATION_OPTIMIZER_ALLOWED_TOOLS: readonly ["Read", "Bash(curl http://localhost:8321/api/skill-curation/*)"];
32
- export interface ReplyActivityHandle {
33
- stop(): Promise<void>;
34
- }
35
- /** Interface for streaming adapter (dashboard SSE) */
36
- export interface IDashboardStream {
37
- sendStreamChunk(channelId: string, chunk: string): void;
38
- sendStreamEnd(channelId: string): void;
39
- sendMessageMeta?(channelId: string, meta: {
40
- backend?: string;
41
- model?: string;
42
- durationMs?: number;
43
- costUsd?: number;
44
- }): void;
45
- sendSessionInfo?(channelId: string, info: SessionInfoPayload): void;
46
- sendError?(channelId: string, message: string): void;
47
- /**
48
- * Chat-attachments Phase 1 — ship the outbound attachment list produced
49
- * during the just-completed turn to the dashboard. Consumed by the
50
- * transcript renderer to show download chips / inline thumbnails
51
- * alongside the assistant message.
52
- */
53
- sendAttachments?(channelId: string, attachments: Array<{
54
- id: string;
55
- originalFilename: string;
56
- mimeType: string;
57
- sizeBytes: number;
58
- caption?: string;
59
- }>): void;
60
- }
61
- /** Interface for ContextBuilder — implemented in Phase 1D */
62
- export interface IContextBuilder {
63
- build(event: Event): Promise<string>;
64
- }
65
- /** Function type for resolving task flow templates by event type */
66
- export type GetTaskFlow = (eventType: string, backendId?: string, integrations?: Partial<Record<IntegrationKey, IntegrationState>>) => string;
67
- /** Interface for NotificationManager — implemented in Phase 1F */
68
- export interface INotificationManager {
69
- send(message: string, event: Event, options?: {
70
- priority?: string;
71
- category?: string;
72
- destinationMode?: "default" | "configured_only";
73
- originSessionId?: number;
74
- }): Promise<void>;
75
- beginReplyActivity(event: MessageEvent): Promise<ReplyActivityHandle>;
76
- }
77
- /** Interface for SessionManager — implemented in Phase 2A */
78
- export interface ISessionManager {
79
- getOrCreate(params: {
80
- platform: string;
81
- channel: string;
82
- threadId: string | null;
83
- isDm?: boolean;
84
- /**
85
- * MessageEvent.intent — forks the dashboard DM tuple into a separate
86
- * scope (chat vs docs_qa) so the two surfaces don't share a session.
87
- */
88
- intent?: "chat" | "docs_qa";
89
- requiredBackend?: BackendId;
90
- /**
91
- * When set and it differs from the active session's stored `model`,
92
- * treat the mismatch like a backend switch: reset the SDK session in
93
- * place (dashboard) or close + recreate (other DMs/threads) so the
94
- * new model starts fresh and history is re-injected as prompt text.
95
- * Omitting it falls back to the pre-existing "backend-only" match.
96
- */
97
- requiredModel?: string;
98
- }): Promise<{
99
- id: number;
100
- isActive: boolean;
101
- sessionId: string | null;
102
- model: string;
103
- backend?: BackendId;
104
- requiresHistoryInjection?: boolean;
105
- }>;
106
- /** Find an existing active session without creating one. Returns null if none exists. */
107
- findActive(params: {
108
- platform: string;
109
- channel: string;
110
- threadId: string | null;
111
- isDm?: boolean;
112
- intent?: "chat" | "docs_qa";
113
- }): Promise<{
114
- id: number;
115
- } | null>;
116
- updateSession(id: number, sessionId: string, model: string, backend?: BackendId): Promise<void>;
117
- touchSession(id: number): void;
118
- closeSession(id: number): void;
119
- /**
120
- * Transaction-safe close variant — callers already inside a
121
- * `db.transaction(...)` body collect side effects into the supplied
122
- * buffer and flush them with `flushEffects` after commit.
123
- */
124
- closeSessionInTx(id: number, effects: DeferredSessionEffects): void;
125
- newEffectsBuffer(): DeferredSessionEffects;
126
- flushEffects(effects: DeferredSessionEffects): void;
127
- /**
128
- * DB-backed lookup for the currently-bound dashboard channel_id of an
129
- * active session. Returns null when the session is not active or not
130
- * found. Used by dispatcher to route stream/meta/error events to
131
- * whichever browser tab is currently connected, instead of the stale
132
- * event.channel captured when the user POSTed their message.
133
- */
134
- getActiveChannelIdForSession(sessionId: number): string | null;
135
- isCloseCommand(content: string): boolean;
136
- getDmPlatformsWithNewMessages(): string[];
137
- getUnsummarizedDmMessages(platform: string): {
138
- role: string;
139
- content: string;
140
- timestamp: string;
141
- metadata?: string | null;
142
- }[];
143
- getPreviousDmSummary(platform: string): string | null;
144
- saveDmSummary(platform: string, summary: string, messageCount: number): void;
145
- }
146
- /** Interface for MessageRecorder — records messages to DB. Returns
147
- * `true` when the row was persisted, `false` when the INSERT/UPDATE
148
- * transaction rolled back (logged internally). The atomic
149
- * INSERT-plus-touch contract means callers no longer need to pair
150
- * `recordMessage` with a separate `touchSession` — on success the
151
- * session's `last_message_at` and `message_count` are already in sync
152
- * with the `messages` row; on failure, neither moves. */
153
- export interface IMessageRecorder {
154
- recordMessage(params: {
155
- sessionId: number;
156
- role: "user" | "assistant" | "system";
157
- content: string;
158
- platform: string;
159
- senderId?: string;
160
- backend?: BackendId;
161
- modelId?: string;
162
- metadata?: Record<string, unknown>;
163
- notificationDispatchId?: string | null;
164
- }): boolean;
165
- }
166
- /** Interface for AuditLogger — implemented in Phase 1D */
167
- export interface IAuditLogger {
168
- logAction(params: {
169
- event: Event;
170
- model: string;
171
- costUsd: number;
172
- usage: AgentResult["usage"];
173
- modelUsage: AgentResult["modelUsage"];
174
- durationMs: number;
175
- numTurns: number;
176
- trigger: "reactive" | "autonomous";
177
- backend?: BackendId;
178
- costSource?: AgentResult["costSource"];
179
- /**
180
- * Whether the agent made at least one PUT/PATCH call to /api/context/*.
181
- * Used for observer-event observability — see Phase 6 of
182
- * docs/observer-context-update-fix.md.
183
- */
184
- contextUpdated?: boolean;
185
- /**
186
- * Number of server-side advisor tool invocations. Populated by the Claude
187
- * Code backend when the `advisor_20260301` tool is active; otherwise 0.
188
- */
189
- advisorCallCount?: number;
190
- /**
191
- * STAGE-C-DM-FRESHNESS-PLAN §Task 4 — DM-only freshness telemetry.
192
- * Captured for DM dispatches so the dashboard's
193
- * `dm_freshness_metrics` view can roll up resume rate, snapshot lag,
194
- * and refetch-hit rate without a separate table. Persisted into
195
- * `agent_actions.detail` as `{ dm_freshness: {...} }`.
196
- */
197
- dmFreshness?: {
198
- resumed: boolean;
199
- agentLogLagMinutes: number;
200
- loudWritesSinceSessionStart: number;
201
- quietWritesSinceSessionStart: number;
202
- refetchedToday: boolean;
203
- triggerMatched: boolean;
204
- };
205
- }): void;
206
- logSkip(event: Event, reason: string, trigger: "reactive" | "autonomous"): void;
207
- logError(event: Event, error: Error, trigger: "reactive" | "autonomous", context?: {
208
- durationMs?: number;
209
- backendId?: BackendId;
210
- modelId?: string;
211
- failureKind?: string;
212
- failureCode?: string;
213
- }): void;
214
- /**
215
- * Chat-attachments Phase 1 — log an inbound (user→agent) or outbound
216
- * (agent→user) attachment upload to `agent_actions` so the dashboard
217
- * events/cost views surface them alongside agent turns.
218
- */
219
- logAttachment(params: {
220
- direction: "inbound" | "outbound";
221
- attachmentId: string;
222
- mimeType: string;
223
- sizeBytes: number;
224
- provenance: string;
225
- originalFilename: string;
226
- }): void;
227
- /**
228
- * Messaging bang-commands (`!stop` / `!start` / `!cost` / `!report`) —
229
- * write an `agent_actions` row with `action_type='bang_command'` so the
230
- * audit trail covers every owner control message, including paused-decline
231
- * non-bang DMs. See docs/design/backlog/messaging-bang-commands.md §6.6.
232
- */
233
- logBangCommand(event: MessageEvent, detail: BangCommandDetail): void;
234
- }
235
- /**
236
- * Audit detail for `bang_command` rows. `status` distinguishes:
237
- * - `ok` — recognised + handler ran successfully
238
- * - `skipped` — recognised but no-op (e.g. `!stop` while already paused)
239
- * - `unknown` — bang-prefixed but no matching key (not while paused)
240
- * - `paused_decline` — any DM declined while paused (bang or non-bang)
241
- *
242
- * Map to `agent_actions.result` per §6.6 (ok→success, skipped/paused_decline
243
- * →skipped, unknown→failed).
244
- */
245
- export interface BangCommandDetail {
246
- command: string;
247
- status: "ok" | "skipped" | "unknown" | "paused_decline";
248
- [extra: string]: unknown;
249
- }
250
- export type TriggerHourlyCheckSkipReason = "morning_routine_active" | "hourly_check_in_progress" | "below_threshold" | "setup_incomplete" | "setup_in_progress" | "vault_degraded" | "user_paused" | "gate_stage0_silent" | "gate_stage2_log_only";
251
- export type SetupMode = "initial" | "update";
252
- export interface TriggerHourlyCheckOptions {
253
- force?: boolean;
254
- /** Optional model hint — injected as `requestedModel` on the enqueued
255
- * routine.hourly_check event so the user can force an Opus run from
256
- * /api/agent/run-now without touching process_backend_config. */
257
- requestedModel?: "sonnet" | "opus";
258
- }
259
- export interface TriggerHourlyCheckResult {
260
- status: "queued" | "skipped";
261
- reason?: TriggerHourlyCheckSkipReason;
262
- pendingCount?: number;
263
- minObservations: number;
264
- forced: boolean;
265
- /**
266
- * cost-reduction-structural §B — populated whenever the gate ran
267
- * (any mode). Mirrors what was logged to `agent_actions` so the
268
- * cron caller's metrics path can attribute without a re-read.
269
- */
270
- gateStage?: "stage0_silent" | "stage2" | "stage3";
271
- /** Effective stage actually executed when mode!=off. */
272
- appliedStage?: "stage0_silent" | "stage2_log_only" | "stage3" | "stage3_shadow";
273
- gateMode?: "off" | "shadow" | "live";
274
- gateReason?: string;
275
- }
276
- /**
277
- * cost-reduction-structural §B — extract the JSON verdict from a
278
- * Stage 2 triage response. The contract is strict: a single line
279
- * matching `{ "action": "log_only" | "escalate", ... }`. Anything else
280
- * — empty output, prose around the JSON, missing fields, malformed JSON
281
- * — falls back to `failed` so the caller cautiously escalates rather
282
- * than silently silencing.
283
- */
284
- export declare function parseStage2Verdict(output: string): "log_only" | "escalate" | "failed";
285
- export interface InFlightExecutionInfo {
286
- kind: "session_chain" | "routine" | "scheduled_task";
287
- key?: string;
288
- id?: number;
289
- taskType?: string;
290
- detail?: string;
291
- }
16
+ import { parseStage2Verdict, type ReplyActivityHandle, type IDashboardStream, type IContextBuilder, type GetTaskFlow, type INotificationManager, type ISessionManager, type IMessageRecorder, type IAuditLogger, type BangCommandDetail, type TriggerHourlyCheckSkipReason, type SetupMode, type TriggerHourlyCheckOptions, type TriggerHourlyCheckResult, type InFlightExecutionInfo } from "./dispatcher-types.js";
17
+ export { parseStage2Verdict, };
18
+ export type { ReplyActivityHandle, IDashboardStream, IContextBuilder, GetTaskFlow, INotificationManager, ISessionManager, IMessageRecorder, IAuditLogger, BangCommandDetail, TriggerHourlyCheckSkipReason, SetupMode, TriggerHourlyCheckOptions, TriggerHourlyCheckResult, InFlightExecutionInfo, };
19
+ import { SKILL_CURATION_OPTIMIZER_ALLOWED_TOOLS } from "./dispatcher-scheduled-tasks.js";
20
+ export { SKILL_CURATION_OPTIMIZER_ALLOWED_TOOLS };
292
21
  export declare class EventDispatcher {
293
22
  private readonly eventBus;
294
23
  private readonly agentRouter;
@@ -432,22 +161,83 @@ export declare class EventDispatcher {
432
161
  * same logical run.
433
162
  */
434
163
  private readonly notifiedEvents;
164
+ /**
165
+ * Phase D-2 coordinator (`docs/design/appendices/file-split-plan.md`):
166
+ * owns task-flow prompt assembly and the inbound-attachment lifecycle
167
+ * (token issue/release, staging into the session dir, voice
168
+ * transcription, and the "[Attached files]" prompt block). Borrows
169
+ * a live reference to `activeTurnTokens` so the dispatcher's public
170
+ * `validateAttachmentTurnToken` keeps reading the same map.
171
+ */
172
+ private readonly prompt;
173
+ /**
174
+ * Phase D-2 coordinator: owns the failure-path machinery — shallow
175
+ * retry wrapper, post-throw cleanup + DM/dashboard notification,
176
+ * quota-error formatting, and the §4.5 delegated-connector health
177
+ * warning consult/dispatch pair. Holds live references to the
178
+ * dispatcher's `notifiedEvents` Set and `shutdownAwaiters` Set;
179
+ * reads `shutdown` and the dashboard stream through accessor
180
+ * callbacks so lazy injection still flows through.
181
+ */
182
+ private readonly errorRouter;
183
+ /**
184
+ * Phase D-2 coordinator: closes out the success-side dispatch
185
+ * lifecycle — notify, audit, scheduled-task finalize, and the
186
+ * cross-session conversation-history / proactive-forward heuristics.
187
+ * The DispatcherErrorRouter routes through this on the failure
188
+ * path via the `onRetemplateFinalize` / `onManagementScanFinalize`
189
+ * callbacks wired in the constructor.
190
+ */
191
+ private readonly resultProcessor;
192
+ /**
193
+ * Phase D-2 coordinator: owns `triggerHourlyCheck` and the
194
+ * cost-reduction-structural §B three-stage gate. Borrows live
195
+ * accessors for the dispatcher's `hourlyCheckInProgress` flag so the
196
+ * pre-existing C1 atomic check-and-set semantics survive the split.
197
+ */
198
+ /**
199
+ * ROUTINE_DATA_ACQUISITION_DESIGN.md Phase 4 / D1 — shared pre-pass
200
+ * runner for `routine.fetch_window`. Injected into HourlyCheckCoordinator
201
+ * (D3), MorningRoutineRunner (D2), and ScheduledTaskRunner (D4) so
202
+ * every routine that has rows in `ROUTINE_WINDOWS` gets the same
203
+ * fetcher session ahead of its parent dispatch. Pure helper, no
204
+ * mutable state of its own.
205
+ */
206
+ private readonly fetchWindowRunner;
207
+ private readonly hourlyCheck;
208
+ /**
209
+ * Phase D-2 coordinator: owns morning-routine execution end-to-end
210
+ * (lock acquisition, prompt-variant selection, retry chain, today.md
211
+ * health check, post-morning catchups + roadmap refresh, and the
212
+ * exponential-back-off retry scheduler). Borrows the dispatcher's
213
+ * `morningRoutineInProgress` flag through a setter callback so the
214
+ * B2 retry-chain invariant (flag stays true across attempts)
215
+ * survives the split.
216
+ */
217
+ private readonly morningRoutine;
218
+ /**
219
+ * Phase D-2 coordinator: owns every non-message dispatch path —
220
+ * scheduled.task (generic + repository run + git project doc + retry
221
+ * detection), routine.morning_routine retries, routine.roadmap_refresh,
222
+ * routine.skill_curation, plus the catch-all executeDefault. Also
223
+ * provides the today.md utilities (`rotateDayFiles`,
224
+ * `diagnoseTodayMdState`, `hasCurrentAgentDayTodayMd`) that
225
+ * `MorningRoutineRunner` consumes via dep callbacks.
226
+ */
227
+ private readonly scheduledTasks;
228
+ /**
229
+ * Phase D-3 coordinator: owns the reactive message-event path —
230
+ * `handle` (was `handleMessage`), `handleAuthCommand`, and
231
+ * `collectDmFreshnessTelemetry`. Borrows live accessors for every
232
+ * dispatcher field the path used to read directly (`currentSetupMode`,
233
+ * lazy-injected stream / store / detectors / auth subsystems) so
234
+ * existing tests that reach through `(dispatcher as any).handleMessage`
235
+ * / `(dispatcher as any).handleAuthCommand` keep working via the
236
+ * thin shims that forward into this handler.
237
+ */
238
+ private readonly messageHandler;
435
239
  constructor(eventBus: EventBus, agentRouter: IAgentRouter, contextBuilder: IContextBuilder, getTaskFlow: GetTaskFlow, notificationMgr: INotificationManager, sessionMgr: ISessionManager, messageRecorder: IMessageRecorder, audit: IAuditLogger, db: Database.Database, config: AgentConfig, todayWriteLock?: TodayWriteLockManager | undefined, services?: ServiceRegistry | undefined, roadmapWriteLock?: RoadmapWriteLockManager | undefined, writeTracker?: AgentWriteTracker | undefined);
436
240
  private loadPersistedSetupMode;
437
- /**
438
- * B-007 §5.8 — compose the final prompt by loading the task-flow
439
- * template and appending the vault policy-files block (rules/*.md,
440
- * routines/<cadence>.md, custom routine file, etc.). Centralised
441
- * here so every dispatch path sees the same policy bundle.
442
- */
443
- private assemblePrompt;
444
- /**
445
- * Policy-file prompt assembly must not fall back to `<dataDir>/context`
446
- * while degraded. Reactive sessions still run so the user can repair the
447
- * vault, but the prompt must not silently inject stale rulebooks from a
448
- * legacy location.
449
- */
450
- private getPromptPolicyContextDir;
451
241
  /** Set the SignalDetector for implicit feedback collection from user messages. */
452
242
  setSignalDetector(detector: SignalDetector): void;
453
243
  /** Set the dashboard stream adapter for real-time response streaming. */
@@ -490,16 +280,6 @@ export declare class EventDispatcher {
490
280
  validateAttachmentTurnToken(token: string): {
491
281
  sessionId: number;
492
282
  } | null;
493
- /** Internal — issue a turn token bound to a session. Cleared by
494
- * `releaseAttachmentTurnToken` in a `finally`. */
495
- private issueAttachmentTurnToken;
496
- private releaseAttachmentTurnToken;
497
- /**
498
- * Stage inbound attachments into `<sessionDir>/_attachments/` via
499
- * hard-link (or copy on EXDEV). Returns the rows that were actually
500
- * staged — callers feed these into the prompt-block builder.
501
- */
502
- private stageInboundAttachments;
503
283
  /**
504
284
  * Read the `messages.id` that was just persisted for this session.
505
285
  * Used to bind inbound attachment rows to the user message (so the
@@ -519,21 +299,6 @@ export declare class EventDispatcher {
519
299
  * against a future event constructor that forgets to set it).
520
300
  */
521
301
  private lookupCustomBangCommandForEvent;
522
- /**
523
- * Run local-Whisper transcription on every audio attachment in `rows`.
524
- * Cached transcripts are returned without re-running inference. Returns
525
- * an empty map when the transcriber is unset, when no rows are audio,
526
- * or when every transcription failed — callers always render the path
527
- * even if the transcript is missing.
528
- */
529
- private transcribeAttachments;
530
- /**
531
- * Compose the "[Attached files]" prompt block that the dispatcher
532
- * appends to the task-flow body for turns with inbound attachments.
533
- * Kept in the dispatcher (not in prompts.ts) because the attachment
534
- * rows are local state for this turn only.
535
- */
536
- private buildAttachmentPromptBlock;
537
302
  /**
538
303
  * Phase 5: set the auth recovery manager so owner DMs like `/auth fix codex`
539
304
  * can be intercepted before reaching the agent backend.
@@ -615,46 +380,12 @@ export declare class EventDispatcher {
615
380
  private shouldSkipForCostCap;
616
381
  private handleEvent;
617
382
  private handleEventInner;
618
- triggerHourlyCheck(source: string, options?: TriggerHourlyCheckOptions): Promise<TriggerHourlyCheckResult>;
619
383
  /**
620
- * cost-reduction-structural §B pull a fresh signal snapshot and run
621
- * the deterministic gate. Helper so the dispatcher's call site stays
622
- * compact and tests can spy on the boundary.
384
+ * Public entry point. Delegates to the HourlyCheckCoordinator.
385
+ * The dispatcher keeps the wrapper because tests + the cron entry
386
+ * call `dispatcher.triggerHourlyCheck(source, opts)` directly.
623
387
  */
624
- private computeHourlyCheckGateDecision;
625
- private readTodayMdSafe;
626
- /**
627
- * cost-reduction-structural §B — daemon-direct silent path. Used by
628
- * Stage 0 and Stage 2 log-only verdicts. Consumes pending user
629
- * observations + appends a single Agent Log line + records the gate
630
- * verdict to `agent_actions`. The flag is reset before return.
631
- */
632
- private runSilentHourlyCheckPath;
633
- private enqueueStage3HourlyCheck;
634
- private logGateAuditRow;
635
- /**
636
- * cost-reduction-structural §B Stage 2 — synchronous lite-tier triage.
637
- * Builds a `routine.hourly_check.triage` RoutineEvent and runs it
638
- * inline through the agent router (NOT the EventBus, so the result
639
- * is available before we decide whether to silence or escalate).
640
- *
641
- * The agent contract is JSON-only output (`{ "action": "log_only" |
642
- * "escalate", "reason": "..." }`); on parse failure we return
643
- * `'failed'` and the caller treats that as cautious escalate.
644
- *
645
- * Tool/turn clamp (defense-in-depth):
646
- * - `allowedToolsOverride: []` removes every tool from the SDK's
647
- * allowlist for the spawn. Stage 2 has nothing to do but emit a
648
- * JSON line; the design's "no write tools" rule is enforced here
649
- * instead of relying on the prompt alone.
650
- * - `maxTurns: 1` caps the spawn at a single assistant turn. Even
651
- * if a future prompt change accidentally invites tool use, the
652
- * spawn cannot loop. Codex/Gemini have no per-spawn `allowedTools`
653
- * surface today (acknowledged gap in `agent-core.ts`); the
654
- * `maxTurns` cap and process_backend_config envelope are the
655
- * remaining safety floor on those backends.
656
- */
657
- private runStage2Triage;
388
+ triggerHourlyCheck(source: string, options?: TriggerHourlyCheckOptions): Promise<TriggerHourlyCheckResult>;
658
389
  /**
659
390
  * Advisory check: is a morning routine execution or retry currently in
660
391
  * progress? Synchronous (no async) so callers can atomically gate other
@@ -686,146 +417,6 @@ export declare class EventDispatcher {
686
417
  * SCHEDULED-DM-IMPLEMENTATION-PLAN §3.6.
687
418
  */
688
419
  private runWithSessionGates;
689
- /**
690
- * Morning routine execution with pre-processing (lock, rotateDayFiles,
691
- * prompt variant selection). Only called for routine === "morning_routine".
692
- * Tier is resolved by BackendRouter from process-key defaults or user config.
693
- */
694
- private executeMorningRoutine;
695
- /**
696
- * Read the operator-or-preset configured tier for `routine.morning_routine`
697
- * so the non-configurable `morning_routine_initial` variant can mirror it.
698
- * Returns null when no row exists (fresh install before the setup wizard
699
- * applies a preset) or when the pinned model isn't in the registry — the
700
- * caller falls back to the router's default tier in those cases.
701
- */
702
- private inferConfiguredMorningRoutineTier;
703
- private emitPostMorningCatchups;
704
- /**
705
- * Schedule a retry of the morning routine when today.md wasn't generated.
706
- *
707
- * Uses the existing agent_schedule → ScheduleWatcher path rather than
708
- * re-enqueuing on the EventBus directly. Benefits:
709
- * 1. Retry persists across daemon restarts.
710
- * 2. Shares the same Opus cost-limit and concurrency gates.
711
- * 3. Back-off delay is enforced by scheduled_for timestamp.
712
- *
713
- * Retry policy: exponential back-off (5 min → 10 min → 15 min), max 3
714
- * attempts. After the 3rd failure, send a critical notification to
715
- * the user and stop retrying.
716
- *
717
- * Retry count is tracked via `event.data.retryCount` on the RoutineEvent.
718
- * On the first failure the count comes from the cron-fired RoutineEvent
719
- * (undefined → 0). On subsequent failures handleMorningRoutineRetry
720
- * synthesizes a new RoutineEvent carrying the previous count from the
721
- * wake task's taskContext, so the chain propagates through a single
722
- * code path: event.data.retryCount → +1 → task_context.retryCount
723
- * → next event.data.retryCount → ...
724
- *
725
- * Dedup protects against pathological cases:
726
- * - M1: another retry is already pending/running → skip
727
- */
728
- private scheduleMorningRetry;
729
- private buildRepositoryRunPrompt;
730
- private prepareRepositoryRunSessionDir;
731
- private executeRepositoryRunTask;
732
- /**
733
- * Execute a scheduled task with the model specified when the task was
734
- * registered via POST /api/schedule.
735
- *
736
- * Morning-routine retry tasks take a dedicated fast path: they skip
737
- * the generic scheduled.task prompt and run the *real* morning routine
738
- * flow via executeMorningRoutine, so the retry carries the same rotateDayFiles
739
- * / prompt selection / roadmap-refresh chain as the cron-fired path.
740
- */
741
- private executeScheduledTask;
742
- /**
743
- * Legacy git project documentation tasks used to run as autonomous Claude
744
- * task-flows. That made file creation probabilistic: the backend could
745
- * finish "successfully" without calling the daemon context API, or fail
746
- * before receiving the `<task_context>` block. The daemon now owns these
747
- * writes directly, matching the manual Daily git management buttons and
748
- * the repository-management cron.
749
- */
750
- private executeGitProjectDocTaskIfApplicable;
751
- private resolveGitProjectDocProcessKey;
752
- private resolveRepositoryForGitProjectDocTask;
753
- private markScheduledTaskCompleted;
754
- private executeScheduledRoutine;
755
- /**
756
- * Handle a morning-routine retry wake task.
757
- *
758
- * Steps:
759
- * 1. Early skip: if today.md already exists (e.g., the cron-fired
760
- * morning routine raced us to it), mark this wake task completed
761
- * without running the agent — saves one Opus session.
762
- * 2. Synthesize a RoutineEvent with `event.data.retryCount` carrying
763
- * the current attempt number, so that the recursive
764
- * scheduleMorningRetry call from executeMorningRoutine can increment the
765
- * retry chain naturally via the event.data code path.
766
- * 3. Invoke executeMorningRoutine — this reuses the full morning-routine flow
767
- * (rotateDayFiles, prompt selection, agent execute, post-result
768
- * today.md check, roadmap_refresh emission).
769
- * 4. Mark the wake task row completed. processResult inside the
770
- * executeMorningRoutine call operates on the synthetic RoutineEvent, which
771
- * is not an AgentTaskEvent, so it does not touch scheduleId — we
772
- * must do it ourselves.
773
- */
774
- private handleMorningRoutineRetry;
775
- private hasCurrentAgentDayTodayMd;
776
- /**
777
- * Inspect today.md and report its state relative to the current agent-day.
778
- * Used by the post-routine retry gate so the log can distinguish between
779
- * "file is missing" and "file has stale H1 date", which are different
780
- * failure modes (process crash vs. format-confusion bug).
781
- */
782
- private diagnoseTodayMdState;
783
- /**
784
- * Rotate day files before Morning Routine:
785
- * 1. today.md → schedule/YYYY-MM-DD.md (archive)
786
- * 2. today.md → yesterday.md (rename for context injection)
787
- *
788
- * After this, ContextBuilder will read yesterday.md as <yesterday>
789
- * and today.md will not exist (agent generates it fresh).
790
- */
791
- private rotateDayFiles;
792
- /**
793
- * Lightweight execution path — delegates tier selection entirely to the
794
- * BackendRouter via process-key defaults (or user-configured
795
- * `process_backend_config` overrides). No hardcoded requestedTier.
796
- */
797
- /**
798
- * Roadmap-refresh execution with an exclusive cross-request write
799
- * lock. The lockId is surfaced to the session context as
800
- * `<roadmap_write_lock_id>` so the task-flow PUT / PATCH calls can
801
- * pass `X-Lock-Id` and other concurrent flows (DM handler, evening
802
- * sweeper) that attempt to write `/api/context/roadmap` during the
803
- * refresh receive a 409.
804
- *
805
- * If the lock cannot be acquired (another session is mid-write), the
806
- * refresh is skipped — `emitRoadmapRefresh` will retry on the next
807
- * qualifying signal (dedup window permitting). This is the correct
808
- * behaviour: the holder is already producing a fresher roadmap than
809
- * anything we would emit right now.
810
- */
811
- private executeRoadmapRefresh;
812
- /**
813
- * P22 §3.4 — skill curation routine. Provisions an isolated optimizer
814
- * workdir, hands the runId + runToken into the agent's task context via
815
- * `event.data`, and tears the workdir down regardless of success/failure.
816
- *
817
- * The standard `executeDefault` path produces the agent session itself —
818
- * the only differences from a normal routine are: (a) the workdir is the
819
- * pre-built optimizer dir (built by `materializeOptimizerWorkdir`), and
820
- * (b) `executeDefault` recognises `routine.skill_curation` events and
821
- * pins `allowedToolsOverride` to `SKILL_CURATION_OPTIMIZER_ALLOWED_TOOLS`,
822
- * which the Claude SDK consumes verbatim and which suspends Allow-mode
823
- * `bypassPermissions`. The curation API's run-token + Zod chokepoint
824
- * remains the safety floor for the rare case the override is bypassed
825
- * (e.g. a future backend that doesn't read `allowedTools`).
826
- */
827
- private executeSkillCurationRoutine;
828
- private executeDefault;
829
420
  /**
830
421
  * Handle `/auth` prefix commands from owner DMs.
831
422
  * Phase 5 §4.2 (fix codex, cancel), Phase 6 §5.3 (fix gemini),
@@ -850,51 +441,6 @@ export declare class EventDispatcher {
850
441
  * isolation.
851
442
  */
852
443
  private collectDmFreshnessTelemetry;
853
- private processResult;
854
- /**
855
- * P6 (git-lifecycle-and-triggers.md Decision 8) — restore in-flight
856
- * `git.project.retemplate` targets from backup whenever a retemplate
857
- * scheduled task settles. The agent itself cannot reliably roll back
858
- * its own writes (process exit, exceeded turns, backend faults), so
859
- * the daemon owns rollback at the dispatcher's two terminal sites
860
- * (`processResult` + `handleError`). The status grid is the source of
861
- * truth for which files to restore; `finalizeRetemplate` is idempotent
862
- * via the `finalizedAt` marker so calling both paths is safe.
863
- */
864
- private finalizeRetemplateRunIfApplicable;
865
- /**
866
- * Unified-repositories §4.5 — settle a `repository_management` row when
867
- * a `git.project.init` / `git.project.update` event the daemon emitted
868
- * for management terminates. Runs unconditionally on every event
869
- * because management events live on the EventBus only (no
870
- * `agent_schedule` row), so the scheduleId-guarded path can't see
871
- * them; the method early-returns for any taskContext that doesn't
872
- * carry management metadata.
873
- *
874
- * Status mapping (v1):
875
- * - `git.project.init` success → `recordManagementInitDone`
876
- * - `git.project.update` success → `recordManagementScan('ok')`
877
- * (resets `scan_failure_count`)
878
- * - either, error → `recordManagementScan('failed')`
879
- * (bumps `scan_failure_count`)
880
- *
881
- * `'skipped_no_activity'` is reserved for future task-flow callback —
882
- * the dispatcher cannot reliably distinguish "agent decided no
883
- * journal entry needed" from "agent succeeded but didn't write" here.
884
- */
885
- private finalizeManagementScanIfApplicable;
886
- private hasRecentProactiveForwardContext;
887
- private logProactiveForwardDisavowalIfMatched;
888
- private formatSummaryRole;
889
- private buildCrossSessionConversationHistory;
890
- private shouldNotify;
891
- /**
892
- * Autonomous "observer" events: external-change detections that the
893
- * daemon pushes into the pipeline, as opposed to user-initiated
894
- * messages, cron routines, or scheduled tasks. Used for the
895
- * contextUpdated observability log in processResult.
896
- */
897
- private isObserverEvent;
898
444
  /**
899
445
  * Create rolling summaries for DM conversations.
900
446
  * Called at 4 AM (day boundary) before morning routine.
@@ -925,75 +471,5 @@ export declare class EventDispatcher {
925
471
  emitRoadmapRefresh(source: string, options?: {
926
472
  bypassDedup?: boolean;
927
473
  }): void;
928
- private localDateTimeToUtcMs;
929
- private getTimeZoneOffsetMinutes;
930
- private getLocalDateParts;
931
- private compareLocalDateParts;
932
- private isRetryable;
933
- /**
934
- * Defense-in-depth retry wrapper around BackendRouter.execute().
935
- *
936
- * **Primary retry responsibility lives inside each BackendCore** (§12/§13).
937
- * Quota errors, timeouts, and auth failures are all normalized into
938
- * BackendDecisiveFailure / BackendQuotaError before they reach this layer.
939
- * The BackendRouter handles fallback on decisive failures.
940
- *
941
- * This outer loop exists solely as a safety net for raw 5xx errors that
942
- * somehow escape the BackendCore → Router chain (e.g., an unexpected HTTP
943
- * error from the SDK transport layer). In practice it almost never fires.
944
- */
945
- private executeWithRetry;
946
- private handleError;
947
- /**
948
- * Best-effort inline error to the dashboard tab whose POST triggered
949
- * this event. `DashboardAdapter` is `notificationEligible=false`, so
950
- * the normal `notificationMgr.send` path skips it — without this hook
951
- * the browser sees the request accepted (200 OK), watches nothing
952
- * happen, and hits the 120s waiting timeout with no explanation. We
953
- * target the originating channel id; if the tab already reconnected
954
- * with a new UUID the adapter silently drops, which matches the
955
- * chat_error semantics.
956
- */
957
- private notifyDashboardError;
958
- private extractQuotaError;
959
- private formatQuotaMessage;
960
- private formatBackendLabel;
961
- private resolveQuotaResetAtMs;
962
- /**
963
- * DELEGATED-MODE-V2-DESIGN.md §4.5 — at every DM dispatch, consult the
964
- * cached probe for delegated integrations whose effective backend
965
- * matches the session backend. Surfaces a one-shot DM (deduped via
966
- * `runtime_state`) when the cached probe says required capabilities
967
- * are no longer present.
968
- *
969
- * The consult itself is synchronous DB-only work (cheap on the hot
970
- * path). The DM dispatch is fire-and-forget so the agent's response
971
- * latency is not gated on Slack/Telegram round-trips. Per-warning
972
- * dispatch failures are swallowed so a flaky messaging adapter never
973
- * breaks the user's actual DM.
974
- */
975
- /**
976
- * Phase 1 of the §4.5 health check — synchronous cache consult only.
977
- * Returns the warnings the dispatcher must surface this turn (or `[]`
978
- * when nothing is broken / setup mode is active / the consult itself
979
- * threw). Recovery markers are cleared inline by the consult helper, so
980
- * the caller does not have to track them.
981
- *
982
- * Split from the dispatch step so the actual DM (and its messages-table
983
- * persist) fires AFTER the dispatcher has recorded the inbound user
984
- * message — otherwise the warning row's `CURRENT_TIMESTAMP` lands before
985
- * the user-message row's, which makes `chat_meta` history reload reorder
986
- * the bubbles (warning above user) and a one-time visual flicker leaks
987
- * to the user. See `runDelegatedConnectorWarningDispatch` below.
988
- */
989
- private consultDelegatedConnectorWarnings;
990
- /**
991
- * Phase 2 of the §4.5 health check — asynchronous DM dispatch + post-
992
- * delivery bookkeeping (throttle marker + dashboard-channel persist).
993
- * Caller invokes this AFTER the user message is recorded so the DM's
994
- * messages-table row carries a strictly-later `CURRENT_TIMESTAMP`
995
- * (preserves pre-reconcile chat order on the dashboard).
996
- */
997
- private runDelegatedConnectorWarningDispatch;
998
474
  }
999
475
  //# sourceMappingURL=dispatcher.d.ts.map