@adhdev/daemon-core 0.9.82-rc.16 → 0.9.82-rc.161

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 (209) hide show
  1. package/dist/boot/process-hardening.d.ts +50 -0
  2. package/dist/chat/source-machine.d.ts +166 -0
  3. package/dist/chat/source-resolver.d.ts +104 -0
  4. package/dist/chat/subscription-updates.d.ts +1 -0
  5. package/dist/cli-adapter-types.d.ts +19 -2
  6. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  7. package/dist/cli-adapters/cli-state-engine.d.ts +178 -0
  8. package/dist/cli-adapters/provider-cli-adapter.d.ts +104 -63
  9. package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
  10. package/dist/cli-adapters/provider-cli-shared.d.ts +27 -0
  11. package/dist/commands/handler.d.ts +66 -0
  12. package/dist/commands/mesh-coordinator.d.ts +72 -1
  13. package/dist/commands/router.d.ts +22 -0
  14. package/dist/config/chat-history.d.ts +7 -0
  15. package/dist/config/config.d.ts +5 -0
  16. package/dist/config/mesh-config.d.ts +71 -1
  17. package/dist/git/git-commands.d.ts +5 -1
  18. package/dist/index.d.ts +31 -6
  19. package/dist/index.js +17210 -3575
  20. package/dist/index.js.map +1 -1
  21. package/dist/index.mjs +17127 -3551
  22. package/dist/index.mjs.map +1 -1
  23. package/dist/installer.d.ts +1 -4
  24. package/dist/ipc/local-ipc-server.d.ts +91 -0
  25. package/dist/launch.d.ts +1 -1
  26. package/dist/logging/async-batch-writer.d.ts +10 -0
  27. package/dist/mesh/beads-db.d.ts +72 -0
  28. package/dist/mesh/contracts.d.ts +164 -0
  29. package/dist/mesh/coordinator-prompt.d.ts +30 -0
  30. package/dist/mesh/coordinator-registry.d.ts +59 -0
  31. package/dist/mesh/mesh-active-work.d.ts +90 -0
  32. package/dist/mesh/mesh-events.d.ts +77 -5
  33. package/dist/mesh/mesh-fast-forward.d.ts +39 -0
  34. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  35. package/dist/mesh/mesh-ledger.d.ts +58 -1
  36. package/dist/mesh/mesh-refine-status.d.ts +26 -0
  37. package/dist/mesh/mesh-work-queue.d.ts +44 -5
  38. package/dist/mesh/preview-freshness.d.ts +18 -0
  39. package/dist/mesh/refine-config.d.ts +193 -0
  40. package/dist/mesh/worktree-bootstrap-config.d.ts +113 -0
  41. package/dist/providers/approval-utils.d.ts +9 -0
  42. package/dist/providers/cli-provider-instance.d.ts +7 -2
  43. package/dist/providers/contracts.d.ts +98 -5
  44. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  45. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  46. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  47. package/dist/providers/native-history/dispatcher.d.ts +24 -0
  48. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  49. package/dist/providers/native-history/index.d.ts +13 -0
  50. package/dist/providers/provider-loader.d.ts +19 -1
  51. package/dist/providers/read-chat-contract.d.ts +29 -0
  52. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  53. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
  54. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  55. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +64 -0
  56. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  57. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  58. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  59. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  60. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  61. package/dist/providers/sdk/v1/index.d.ts +30 -0
  62. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  63. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  64. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  65. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  66. package/dist/providers/sdk/v1/types/common/index.d.ts +169 -0
  67. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  68. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  69. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  70. package/dist/providers/spec/adapter.d.ts +56 -0
  71. package/dist/providers/spec/cli-adapter.d.ts +76 -0
  72. package/dist/providers/spec/driver.d.ts +148 -0
  73. package/dist/providers/spec/evaluator.d.ts +47 -0
  74. package/dist/providers/spec/loader.d.ts +14 -0
  75. package/dist/providers/spec/native-history-executor.d.ts +39 -0
  76. package/dist/providers/spec/route.d.ts +4 -0
  77. package/dist/providers/spec/schema.gen.d.ts +507 -0
  78. package/dist/providers/spec/types.d.ts +211 -0
  79. package/dist/providers/transcript-v2.d.ts +176 -0
  80. package/dist/repo-mesh-types.d.ts +100 -1
  81. package/dist/sessions/registry.d.ts +3 -0
  82. package/dist/shared-types.d.ts +12 -0
  83. package/dist/status/reporter.d.ts +2 -0
  84. package/dist/status/snapshot.d.ts +1 -0
  85. package/dist/types.d.ts +5 -0
  86. package/package.json +7 -2
  87. package/src/boot/daemon-lifecycle.ts +17 -10
  88. package/src/boot/process-hardening.ts +89 -0
  89. package/src/chat/source-machine.ts +534 -0
  90. package/src/chat/source-resolver.ts +0 -0
  91. package/src/chat/subscription-updates.ts +14 -1
  92. package/src/cli-adapter-types.d.ts +1 -0
  93. package/src/cli-adapter-types.ts +18 -2
  94. package/src/cli-adapters/cli-script-runner.ts +421 -0
  95. package/src/cli-adapters/cli-state-engine.ts +1086 -0
  96. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  97. package/src/cli-adapters/provider-cli-adapter.ts +664 -1137
  98. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  99. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  100. package/src/cli-adapters/provider-cli-runtime.ts +3 -1
  101. package/src/cli-adapters/provider-cli-shared.d.ts +2 -0
  102. package/src/cli-adapters/provider-cli-shared.ts +57 -11
  103. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +17 -1
  104. package/src/cli-adapters/terminal-backends/xterm-backend.ts +8 -1
  105. package/src/commands/chat-commands.ts +1597 -60
  106. package/src/commands/cli-manager.ts +195 -3
  107. package/src/commands/handler.ts +547 -2
  108. package/src/commands/mesh-coordinator.ts +231 -127
  109. package/src/commands/router.ts +3547 -502
  110. package/src/config/chat-history.ts +87 -24
  111. package/src/config/config.ts +12 -0
  112. package/src/config/mesh-config.ts +264 -2
  113. package/src/config/recent-activity.ts +8 -2
  114. package/src/daemon/dev-cli-debug.ts +10 -1
  115. package/src/detection/ide-detector.ts +26 -16
  116. package/src/git/git-commands.ts +17 -5
  117. package/src/git/git-worktree.ts +8 -1
  118. package/src/index.ts +91 -5
  119. package/src/installer.d.ts +1 -1
  120. package/src/installer.ts +8 -6
  121. package/src/ipc/local-ipc-server.ts +278 -0
  122. package/src/launch.d.ts +1 -1
  123. package/src/launch.ts +37 -28
  124. package/src/logging/async-batch-writer.ts +55 -0
  125. package/src/logging/logger.ts +2 -1
  126. package/src/mesh/beads-db.ts +479 -0
  127. package/src/mesh/contracts.ts +329 -0
  128. package/src/mesh/coordinator-prompt.ts +204 -30
  129. package/src/mesh/coordinator-registry.ts +121 -0
  130. package/src/mesh/mesh-active-work.ts +437 -0
  131. package/src/mesh/mesh-events.ts +820 -61
  132. package/src/mesh/mesh-fast-forward.ts +430 -0
  133. package/src/mesh/mesh-host-ownership.ts +73 -0
  134. package/src/mesh/mesh-ledger.ts +457 -104
  135. package/src/mesh/mesh-refine-status.ts +144 -0
  136. package/src/mesh/mesh-work-queue.ts +216 -158
  137. package/src/mesh/preview-freshness.ts +118 -0
  138. package/src/mesh/refine-config.ts +366 -0
  139. package/src/mesh/worktree-bootstrap-config.ts +247 -0
  140. package/src/providers/approval-utils.ts +39 -5
  141. package/src/providers/chat-message-normalization.ts +4 -11
  142. package/src/providers/cli-provider-instance.ts +388 -47
  143. package/src/providers/contracts.ts +105 -5
  144. package/src/providers/ide-provider-instance.ts +17 -3
  145. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  146. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  147. package/src/providers/native-history/codex-cli-transcript.ts +419 -0
  148. package/src/providers/native-history/dispatcher.ts +227 -0
  149. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  150. package/src/providers/native-history/index.ts +30 -0
  151. package/src/providers/provider-loader.ts +420 -31
  152. package/src/providers/provider-schema.ts +31 -13
  153. package/src/providers/read-chat-contract.ts +76 -16
  154. package/src/providers/sdk/README.md +49 -0
  155. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  156. package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
  157. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  158. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +245 -0
  159. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  160. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  161. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  162. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  163. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  164. package/src/providers/sdk/v1/index.ts +152 -0
  165. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  166. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  167. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  168. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +457 -0
  169. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  170. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  171. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  172. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  173. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  174. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  175. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  176. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  177. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +119 -0
  178. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  179. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  180. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  181. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  182. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  183. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  184. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  185. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  186. package/src/providers/sdk/v1/types/common/index.ts +210 -0
  187. package/src/providers/sdk/v1/validators/index.ts +19 -0
  188. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  189. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  190. package/src/providers/spec/adapter.ts +153 -0
  191. package/src/providers/spec/cli-adapter.ts +318 -0
  192. package/src/providers/spec/driver.ts +498 -0
  193. package/src/providers/spec/evaluator.ts +268 -0
  194. package/src/providers/spec/loader.ts +130 -0
  195. package/src/providers/spec/native-history-executor.ts +612 -0
  196. package/src/providers/spec/route.ts +51 -0
  197. package/src/providers/spec/schema.gen.ts +507 -0
  198. package/src/providers/spec/schema.json +210 -0
  199. package/src/providers/spec/types.ts +230 -0
  200. package/src/providers/transcript-v2.ts +567 -0
  201. package/src/providers/version-archive.ts +38 -20
  202. package/src/repo-mesh-types.ts +110 -1
  203. package/src/sessions/registry.ts +3 -0
  204. package/src/shared-types.ts +9 -0
  205. package/src/status/builders.ts +23 -6
  206. package/src/status/reporter.ts +15 -0
  207. package/src/status/snapshot.ts +35 -11
  208. package/src/system/host-memory.ts +29 -12
  209. package/src/types.ts +5 -0
@@ -0,0 +1,567 @@
1
+ /**
2
+ * Chat Transcript Contract v2
3
+ *
4
+ * First-class message identity, monotonic sequence, strict enums. Designed to
5
+ * replace the v1 contract (contracts.ts ReadChatResult + types.ts ChatMessage)
6
+ * during the A2 big-bang. This module defines the contract; it does not yet
7
+ * change runtime behaviour. v1 keeps working until A2 flips the switch.
8
+ *
9
+ * Invariants v2 enforces (and v1 does not):
10
+ * 1. Every ChatMessageV2 has providerUnitKey, bubbleId, sequence — none optional.
11
+ * 2. sequence is a monotonic integer per (sessionId, source) tuple. Producers
12
+ * never reuse it; consumers MAY assume strict ordering.
13
+ * 3. providerUnitKey is stable across re-reads: the same logical message
14
+ * always yields the same key even if its index shifts or content is
15
+ * edited mid-stream. Producers derive it from provider-owned identifiers
16
+ * (turn id, native message id), not from content hashes or array index.
17
+ * 4. timestamp is producer-asserted wall-clock; orderingTimestamp is monotonic
18
+ * and used for snapshot diffs. 1ms fallback increments are forbidden — if
19
+ * a producer cannot supply a stable monotonic value, the daemon assigns
20
+ * sequence at ingest and orderingTimestamp = ingestedAt.
21
+ * 5. visibility / source / role / kind are strict unions. No `(string & {})`
22
+ * escape hatches.
23
+ * 6. Coverage is exactly one of full/tail/current-turn. Mixing it with
24
+ * partialReason or unavailableReason is a contract violation.
25
+ * 7. workspace / sessionId are explicit on every ReadChatResultV2; the daemon
26
+ * no longer infers them from message bodies.
27
+ */
28
+
29
+ import type { MessagePart, ToolCallInfo } from './contracts.js';
30
+
31
+ // ─── Contract version ────────────────────────────────────────────────────
32
+
33
+ export const CHAT_CONTRACT_VERSION_V1 = '1.0' as const;
34
+ export const CHAT_CONTRACT_VERSION_V2 = '2.0' as const;
35
+
36
+ export type ChatContractVersion =
37
+ | typeof CHAT_CONTRACT_VERSION_V1
38
+ | typeof CHAT_CONTRACT_VERSION_V2;
39
+
40
+ export const SUPPORTED_CHAT_CONTRACT_VERSIONS: readonly ChatContractVersion[] = [
41
+ CHAT_CONTRACT_VERSION_V1,
42
+ CHAT_CONTRACT_VERSION_V2,
43
+ ] as const;
44
+
45
+ // ─── Strict role / kind / visibility / source enums ─────────────────────
46
+
47
+ export const CHAT_ROLES_V2 = ['user', 'assistant', 'system'] as const;
48
+ export type ChatRoleV2 = typeof CHAT_ROLES_V2[number];
49
+
50
+ export const CHAT_MESSAGE_KINDS_V2 = [
51
+ 'standard',
52
+ 'thought',
53
+ 'tool',
54
+ 'terminal',
55
+ 'system',
56
+ ] as const;
57
+ export type ChatMessageKindV2 = typeof CHAT_MESSAGE_KINDS_V2[number];
58
+
59
+ export const CHAT_VISIBILITIES_V2 = ['user', 'debug', 'internal', 'hidden'] as const;
60
+ export type ChatVisibilityV2 = typeof CHAT_VISIBILITIES_V2[number];
61
+
62
+ export const CHAT_AUDIENCES_V2 = ['chat', 'debug', 'trace', 'internal'] as const;
63
+ export type ChatAudienceV2 = typeof CHAT_AUDIENCES_V2[number];
64
+
65
+ export const CHAT_SOURCES_V2 = [
66
+ 'assistant_text',
67
+ 'tool_call',
68
+ 'terminal_command',
69
+ 'runtime_activity',
70
+ 'runtime_status',
71
+ 'provider_chrome',
72
+ 'control',
73
+ ] as const;
74
+ export type ChatSourceV2 = typeof CHAT_SOURCES_V2[number];
75
+
76
+ export const CHAT_BUBBLE_STATES_V2 = ['draft', 'streaming', 'final', 'removed'] as const;
77
+ export type ChatBubbleStateV2 = typeof CHAT_BUBBLE_STATES_V2[number];
78
+
79
+ // ─── Message identity ────────────────────────────────────────────────────
80
+
81
+ /**
82
+ * Stable identity of a single chat message. All fields are required in v2.
83
+ *
84
+ * - providerUnitKey: provider-owned canonical id. Must be derivable from
85
+ * provider primitives (native message id, turn id, bubble id), NOT from
86
+ * array index or content hash. Stable across re-reads of the same logical
87
+ * message even if neighbours change.
88
+ * - bubbleId: dashboard-owned bubble identity. May equal providerUnitKey when
89
+ * the provider already exposes a bubble-grained id; otherwise daemon
90
+ * derives it deterministically from providerUnitKey (e.g. `bubble:${key}`).
91
+ * - sequence: monotonic integer per (sessionId, source). Strictly increasing
92
+ * over the lifetime of the session. Used for snapshot diffs and dedup.
93
+ * - turnKey: stable identifier for the conversation turn this message belongs
94
+ * to. Required so consumers can group messages without re-deriving turns.
95
+ */
96
+ export interface MessageIdentityV2 {
97
+ providerUnitKey: string;
98
+ bubbleId: string;
99
+ sequence: number;
100
+ turnKey: string;
101
+ }
102
+
103
+ // ─── Timing ──────────────────────────────────────────────────────────────
104
+
105
+ /**
106
+ * Producer-asserted wall-clock time (ms since epoch). Forward jumps are
107
+ * permitted; consumers MUST NOT rely on this for ordering.
108
+ */
109
+ export type ChatTimestampMs = number;
110
+
111
+ /**
112
+ * Monotonic ordering value (ms since epoch, but assigned by the daemon at
113
+ * ingest to guarantee monotonicity even if the producer's wall clock skews).
114
+ * Used by snapshot diffs in place of timestamp.
115
+ */
116
+ export type ChatOrderingTimestampMs = number;
117
+
118
+ // ─── Message ─────────────────────────────────────────────────────────────
119
+
120
+ export interface ChatMessageV2 extends MessageIdentityV2 {
121
+ role: ChatRoleV2;
122
+ kind: ChatMessageKindV2;
123
+ content: string | MessagePart[];
124
+ bubbleState: ChatBubbleStateV2;
125
+ timestamp: ChatTimestampMs;
126
+ orderingTimestamp: ChatOrderingTimestampMs;
127
+ visibility: ChatVisibilityV2;
128
+ audience: ChatAudienceV2;
129
+ source: ChatSourceV2;
130
+ /** Sender display name (for shared sessions). Empty string when unused. */
131
+ senderName: string;
132
+ /** Tool calls associated with this message. Empty array when none. */
133
+ toolCalls: ToolCallInfo[];
134
+ /** Producer-defined metadata. Daemon never inspects this except for passthrough. */
135
+ meta: Readonly<Record<string, unknown>>;
136
+ }
137
+
138
+ // ─── Workspace / session context ─────────────────────────────────────────
139
+
140
+ export interface WorkspaceContextV2 {
141
+ /** Absolute realpath of the workspace the session is reading from. */
142
+ workspacePath: string;
143
+ /** Workspace the session was intended to operate on (may differ during cross-workspace ops). */
144
+ intendedWorkspacePath: string;
145
+ }
146
+
147
+ export interface SessionContextV2 {
148
+ /** Provider-owned session id (e.g. claude.jsonl uuid, codex session_meta.id). */
149
+ providerSessionId: string;
150
+ /** Optional daemon-side history alias used to disambiguate within a workspace. */
151
+ historySessionId?: string;
152
+ }
153
+
154
+ // ─── Coverage (honest signal) ────────────────────────────────────────────
155
+
156
+ /**
157
+ * v1 allowed `coverage='full'` to coexist with `partialReason`/`unavailableReason`,
158
+ * which is a contract lie. v2 makes the three states mutually exclusive.
159
+ */
160
+ export type CoverageHintV2 =
161
+ | { kind: 'full' }
162
+ | { kind: 'tail'; tailMessageCount: number }
163
+ | { kind: 'current-turn'; turnKey: string }
164
+ | { kind: 'partial'; partialReason: string }
165
+ | { kind: 'unavailable'; unavailableReason: string };
166
+
167
+ // ─── Canonical history declaration (provider.json) ───────────────────────
168
+
169
+ export type CanonicalHistoryModeV2 = 'native-source' | 'disabled' | 'materialized-mirror';
170
+
171
+ export interface CanonicalHistoryDeclarationV2 {
172
+ contractVersion: ChatContractVersion;
173
+ format: string;
174
+ mode: CanonicalHistoryModeV2;
175
+ watchPath?: string;
176
+ scripts: {
177
+ readSession: string;
178
+ listSessions: string;
179
+ };
180
+ }
181
+
182
+ // ─── ReadChat result ─────────────────────────────────────────────────────
183
+
184
+ export type ReadChatStatusV2 =
185
+ | 'idle'
186
+ | 'generating'
187
+ | 'waiting_approval'
188
+ | 'error'
189
+ | 'panel_hidden'
190
+ | 'streaming';
191
+
192
+ export type ReadChatTurnStatusV2 = 'open' | 'waiting_approval' | 'complete' | 'error';
193
+
194
+ export interface ReadChatResultV2 {
195
+ contractVersion: typeof CHAT_CONTRACT_VERSION_V2;
196
+ workspace: WorkspaceContextV2;
197
+ session: SessionContextV2;
198
+ coverage: CoverageHintV2;
199
+ status: ReadChatStatusV2;
200
+ messages: ChatMessageV2[];
201
+ currentTurnId: string;
202
+ turnStatus: ReadChatTurnStatusV2;
203
+ transcriptAuthority: 'provider' | 'daemon';
204
+ }
205
+
206
+ // ─── Validation primitives ───────────────────────────────────────────────
207
+
208
+ export class ChatContractViolationError extends Error {
209
+ readonly violationPath: string;
210
+ readonly contractVersion: ChatContractVersion;
211
+ constructor(
212
+ contractVersion: ChatContractVersion,
213
+ violationPath: string,
214
+ detail: string,
215
+ ) {
216
+ super(`chat contract ${contractVersion} violation at ${violationPath}: ${detail}`);
217
+ this.name = 'ChatContractViolationError';
218
+ this.violationPath = violationPath;
219
+ this.contractVersion = contractVersion;
220
+ }
221
+ }
222
+
223
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
224
+ return !!value && typeof value === 'object' && !Array.isArray(value);
225
+ }
226
+
227
+ function assertSequenceMonotonic(
228
+ messages: ReadonlyArray<{ sequence: number }>,
229
+ pathPrefix: string,
230
+ ): void {
231
+ for (let i = 1; i < messages.length; i += 1) {
232
+ const prev = messages[i - 1]!.sequence;
233
+ const cur = messages[i]!.sequence;
234
+ if (!(cur > prev)) {
235
+ throw new ChatContractViolationError(
236
+ CHAT_CONTRACT_VERSION_V2,
237
+ `${pathPrefix}[${i}].sequence`,
238
+ `sequence must be strictly increasing (prev=${prev}, current=${cur})`,
239
+ );
240
+ }
241
+ }
242
+ }
243
+
244
+ function assertOrderingTimestampMonotonic(
245
+ messages: ReadonlyArray<{ orderingTimestamp: number }>,
246
+ pathPrefix: string,
247
+ ): void {
248
+ for (let i = 1; i < messages.length; i += 1) {
249
+ const prev = messages[i - 1]!.orderingTimestamp;
250
+ const cur = messages[i]!.orderingTimestamp;
251
+ if (cur < prev) {
252
+ throw new ChatContractViolationError(
253
+ CHAT_CONTRACT_VERSION_V2,
254
+ `${pathPrefix}[${i}].orderingTimestamp`,
255
+ `orderingTimestamp must be monotonic non-decreasing (prev=${prev}, current=${cur})`,
256
+ );
257
+ }
258
+ }
259
+ }
260
+
261
+ function assertIdentity(message: Record<string, unknown>, index: number): MessageIdentityV2 {
262
+ const providerUnitKey = message['providerUnitKey'];
263
+ const bubbleId = message['bubbleId'];
264
+ const sequence = message['sequence'];
265
+ const turnKey = message['turnKey'];
266
+ if (typeof providerUnitKey !== 'string' || !providerUnitKey.length) {
267
+ throw new ChatContractViolationError(
268
+ CHAT_CONTRACT_VERSION_V2,
269
+ `messages[${index}].providerUnitKey`,
270
+ 'must be a non-empty string',
271
+ );
272
+ }
273
+ if (typeof bubbleId !== 'string' || !bubbleId.length) {
274
+ throw new ChatContractViolationError(
275
+ CHAT_CONTRACT_VERSION_V2,
276
+ `messages[${index}].bubbleId`,
277
+ 'must be a non-empty string',
278
+ );
279
+ }
280
+ if (typeof sequence !== 'number' || !Number.isInteger(sequence) || sequence < 0) {
281
+ throw new ChatContractViolationError(
282
+ CHAT_CONTRACT_VERSION_V2,
283
+ `messages[${index}].sequence`,
284
+ 'must be a non-negative integer',
285
+ );
286
+ }
287
+ if (typeof turnKey !== 'string' || !turnKey.length) {
288
+ throw new ChatContractViolationError(
289
+ CHAT_CONTRACT_VERSION_V2,
290
+ `messages[${index}].turnKey`,
291
+ 'must be a non-empty string',
292
+ );
293
+ }
294
+ return { providerUnitKey, bubbleId, sequence, turnKey };
295
+ }
296
+
297
+ function assertEnum<T extends string>(
298
+ value: unknown,
299
+ allowed: readonly T[],
300
+ path: string,
301
+ ): T {
302
+ if (typeof value !== 'string' || !(allowed as readonly string[]).includes(value)) {
303
+ throw new ChatContractViolationError(
304
+ CHAT_CONTRACT_VERSION_V2,
305
+ path,
306
+ `must be one of ${allowed.join(', ')} (got ${JSON.stringify(value)})`,
307
+ );
308
+ }
309
+ return value as T;
310
+ }
311
+
312
+ function assertContent(value: unknown, path: string): string | MessagePart[] {
313
+ if (typeof value === 'string') return value;
314
+ if (Array.isArray(value)) return value as MessagePart[];
315
+ throw new ChatContractViolationError(
316
+ CHAT_CONTRACT_VERSION_V2,
317
+ path,
318
+ 'must be a string or MessagePart[]',
319
+ );
320
+ }
321
+
322
+ function assertCoverage(value: unknown, path: string): CoverageHintV2 {
323
+ if (!isPlainObject(value)) {
324
+ throw new ChatContractViolationError(
325
+ CHAT_CONTRACT_VERSION_V2,
326
+ path,
327
+ 'must be a CoverageHintV2 object',
328
+ );
329
+ }
330
+ const kind = value['kind'];
331
+ switch (kind) {
332
+ case 'full':
333
+ return { kind: 'full' };
334
+ case 'tail': {
335
+ const n = value['tailMessageCount'];
336
+ if (typeof n !== 'number' || !Number.isInteger(n) || n < 0) {
337
+ throw new ChatContractViolationError(
338
+ CHAT_CONTRACT_VERSION_V2,
339
+ `${path}.tailMessageCount`,
340
+ 'must be a non-negative integer for tail coverage',
341
+ );
342
+ }
343
+ return { kind: 'tail', tailMessageCount: n };
344
+ }
345
+ case 'current-turn': {
346
+ const turnKey = value['turnKey'];
347
+ if (typeof turnKey !== 'string' || !turnKey.length) {
348
+ throw new ChatContractViolationError(
349
+ CHAT_CONTRACT_VERSION_V2,
350
+ `${path}.turnKey`,
351
+ 'current-turn coverage requires a non-empty turnKey',
352
+ );
353
+ }
354
+ return { kind: 'current-turn', turnKey };
355
+ }
356
+ case 'partial': {
357
+ const reason = value['partialReason'];
358
+ if (typeof reason !== 'string' || !reason.length) {
359
+ throw new ChatContractViolationError(
360
+ CHAT_CONTRACT_VERSION_V2,
361
+ `${path}.partialReason`,
362
+ 'partial coverage requires a non-empty partialReason',
363
+ );
364
+ }
365
+ return { kind: 'partial', partialReason: reason };
366
+ }
367
+ case 'unavailable': {
368
+ const reason = value['unavailableReason'];
369
+ if (typeof reason !== 'string' || !reason.length) {
370
+ throw new ChatContractViolationError(
371
+ CHAT_CONTRACT_VERSION_V2,
372
+ `${path}.unavailableReason`,
373
+ 'unavailable coverage requires a non-empty unavailableReason',
374
+ );
375
+ }
376
+ return { kind: 'unavailable', unavailableReason: reason };
377
+ }
378
+ default:
379
+ throw new ChatContractViolationError(
380
+ CHAT_CONTRACT_VERSION_V2,
381
+ `${path}.kind`,
382
+ `must be one of full | tail | current-turn | partial | unavailable (got ${JSON.stringify(kind)})`,
383
+ );
384
+ }
385
+ }
386
+
387
+ function assertMessageV2(raw: unknown, index: number): ChatMessageV2 {
388
+ if (!isPlainObject(raw)) {
389
+ throw new ChatContractViolationError(
390
+ CHAT_CONTRACT_VERSION_V2,
391
+ `messages[${index}]`,
392
+ 'must be an object',
393
+ );
394
+ }
395
+ const identity = assertIdentity(raw, index);
396
+ const role = assertEnum(raw['role'], CHAT_ROLES_V2, `messages[${index}].role`);
397
+ const kind = assertEnum(raw['kind'], CHAT_MESSAGE_KINDS_V2, `messages[${index}].kind`);
398
+ const content = assertContent(raw['content'], `messages[${index}].content`);
399
+ const bubbleState = assertEnum(
400
+ raw['bubbleState'],
401
+ CHAT_BUBBLE_STATES_V2,
402
+ `messages[${index}].bubbleState`,
403
+ );
404
+ const timestamp = raw['timestamp'];
405
+ if (typeof timestamp !== 'number' || !Number.isFinite(timestamp)) {
406
+ throw new ChatContractViolationError(
407
+ CHAT_CONTRACT_VERSION_V2,
408
+ `messages[${index}].timestamp`,
409
+ 'must be a finite number (ms since epoch)',
410
+ );
411
+ }
412
+ const orderingTimestamp = raw['orderingTimestamp'];
413
+ if (typeof orderingTimestamp !== 'number' || !Number.isFinite(orderingTimestamp)) {
414
+ throw new ChatContractViolationError(
415
+ CHAT_CONTRACT_VERSION_V2,
416
+ `messages[${index}].orderingTimestamp`,
417
+ 'must be a finite number (ms since epoch)',
418
+ );
419
+ }
420
+ const visibility = assertEnum(raw['visibility'], CHAT_VISIBILITIES_V2, `messages[${index}].visibility`);
421
+ const audience = assertEnum(raw['audience'], CHAT_AUDIENCES_V2, `messages[${index}].audience`);
422
+ const source = assertEnum(raw['source'], CHAT_SOURCES_V2, `messages[${index}].source`);
423
+ const senderName = typeof raw['senderName'] === 'string' ? (raw['senderName'] as string) : '';
424
+ const toolCalls = Array.isArray(raw['toolCalls']) ? (raw['toolCalls'] as ToolCallInfo[]) : [];
425
+ const meta = isPlainObject(raw['meta']) ? (raw['meta'] as Record<string, unknown>) : {};
426
+
427
+ return {
428
+ ...identity,
429
+ role,
430
+ kind,
431
+ content,
432
+ bubbleState,
433
+ timestamp,
434
+ orderingTimestamp,
435
+ visibility,
436
+ audience,
437
+ source,
438
+ senderName,
439
+ toolCalls,
440
+ meta,
441
+ };
442
+ }
443
+
444
+ /**
445
+ * Validate a v2 read_chat payload. Throws ChatContractViolationError on the
446
+ * first violation. v2 invariants beyond per-field checks:
447
+ * - messages[*].sequence strictly increasing
448
+ * - messages[*].orderingTimestamp monotonic non-decreasing
449
+ * - coverage union is well-formed
450
+ */
451
+ export function assertReadChatResultV2Payload(raw: unknown): ReadChatResultV2 {
452
+ if (!isPlainObject(raw)) {
453
+ throw new ChatContractViolationError(
454
+ CHAT_CONTRACT_VERSION_V2,
455
+ '$',
456
+ 'must be an object',
457
+ );
458
+ }
459
+ if (raw['contractVersion'] !== CHAT_CONTRACT_VERSION_V2) {
460
+ throw new ChatContractViolationError(
461
+ CHAT_CONTRACT_VERSION_V2,
462
+ 'contractVersion',
463
+ `expected ${CHAT_CONTRACT_VERSION_V2}, got ${JSON.stringify(raw['contractVersion'])}`,
464
+ );
465
+ }
466
+ const workspace = raw['workspace'];
467
+ if (!isPlainObject(workspace) || typeof workspace['workspacePath'] !== 'string'
468
+ || typeof workspace['intendedWorkspacePath'] !== 'string') {
469
+ throw new ChatContractViolationError(
470
+ CHAT_CONTRACT_VERSION_V2,
471
+ 'workspace',
472
+ 'must have workspacePath and intendedWorkspacePath strings',
473
+ );
474
+ }
475
+ const session = raw['session'];
476
+ if (!isPlainObject(session) || typeof session['providerSessionId'] !== 'string') {
477
+ throw new ChatContractViolationError(
478
+ CHAT_CONTRACT_VERSION_V2,
479
+ 'session',
480
+ 'must have providerSessionId string',
481
+ );
482
+ }
483
+ const coverage = assertCoverage(raw['coverage'], 'coverage');
484
+ const status = assertEnum(
485
+ raw['status'],
486
+ ['idle', 'generating', 'waiting_approval', 'error', 'panel_hidden', 'streaming'] as const,
487
+ 'status',
488
+ );
489
+ const turnStatus = assertEnum(
490
+ raw['turnStatus'],
491
+ ['open', 'waiting_approval', 'complete', 'error'] as const,
492
+ 'turnStatus',
493
+ );
494
+ const transcriptAuthority = assertEnum(
495
+ raw['transcriptAuthority'],
496
+ ['provider', 'daemon'] as const,
497
+ 'transcriptAuthority',
498
+ );
499
+ const currentTurnId = raw['currentTurnId'];
500
+ if (typeof currentTurnId !== 'string') {
501
+ throw new ChatContractViolationError(
502
+ CHAT_CONTRACT_VERSION_V2,
503
+ 'currentTurnId',
504
+ 'must be a string',
505
+ );
506
+ }
507
+ if (!Array.isArray(raw['messages'])) {
508
+ throw new ChatContractViolationError(
509
+ CHAT_CONTRACT_VERSION_V2,
510
+ 'messages',
511
+ 'must be an array',
512
+ );
513
+ }
514
+ const messages = raw['messages'].map((m, i) => assertMessageV2(m, i));
515
+ assertSequenceMonotonic(messages, 'messages');
516
+ assertOrderingTimestampMonotonic(messages, 'messages');
517
+
518
+ const historySessionId = typeof session['historySessionId'] === 'string'
519
+ ? (session['historySessionId'] as string)
520
+ : undefined;
521
+
522
+ return {
523
+ contractVersion: CHAT_CONTRACT_VERSION_V2,
524
+ workspace: {
525
+ workspacePath: workspace['workspacePath'] as string,
526
+ intendedWorkspacePath: workspace['intendedWorkspacePath'] as string,
527
+ },
528
+ session: historySessionId !== undefined
529
+ ? { providerSessionId: session['providerSessionId'] as string, historySessionId }
530
+ : { providerSessionId: session['providerSessionId'] as string },
531
+ coverage,
532
+ status,
533
+ messages,
534
+ currentTurnId,
535
+ turnStatus,
536
+ transcriptAuthority,
537
+ };
538
+ }
539
+
540
+ // ─── Contract version negotiation ────────────────────────────────────────
541
+
542
+ export function isSupportedChatContractVersion(value: unknown): value is ChatContractVersion {
543
+ return typeof value === 'string'
544
+ && (SUPPORTED_CHAT_CONTRACT_VERSIONS as readonly string[]).includes(value);
545
+ }
546
+
547
+ /**
548
+ * Read a provider's declared chat contract version from its parsed
549
+ * provider.json `canonicalHistory.contractVersion` field.
550
+ *
551
+ * - Absent or unrecognized → treated as v1 (legacy behaviour preserved during
552
+ * the A1 transition). A2 will tighten this to reject unsupported versions
553
+ * at provider load time.
554
+ * - Present and supported → returned as-is.
555
+ *
556
+ * The returned version drives which validator (assertReadChatResultV2Payload
557
+ * vs the legacy validateReadChatResultPayload) processes the provider's
558
+ * read_chat output.
559
+ */
560
+ export function readDeclaredChatContractVersion(
561
+ canonicalHistory: unknown,
562
+ ): ChatContractVersion {
563
+ if (!isPlainObject(canonicalHistory)) return CHAT_CONTRACT_VERSION_V1;
564
+ const declared = canonicalHistory['contractVersion'];
565
+ if (isSupportedChatContractVersion(declared)) return declared;
566
+ return CHAT_CONTRACT_VERSION_V1;
567
+ }
@@ -12,7 +12,7 @@
12
12
  import * as fs from 'fs';
13
13
  import * as path from 'path';
14
14
  import * as os from 'os';
15
- import { execSync } from 'child_process';
15
+ // Removed execSync import
16
16
  import { platform } from 'os';
17
17
  import type { ProviderLoader } from './provider-loader.js';
18
18
  import type { ProviderModule } from './contracts.js';
@@ -117,22 +117,40 @@ export class VersionArchive {
117
117
 
118
118
  // ─── Version Detection ──────────────────────────────
119
119
 
120
- function runCommand(cmd: string, timeout = 10000): string | null {
121
- try {
122
- return execSync(cmd, {
120
+ import { exec } from 'child_process';
121
+
122
+ async function runCommand(cmd: string, timeout = 10000): Promise<string | null> {
123
+ return new Promise((resolve) => {
124
+ exec(cmd, {
123
125
  encoding: 'utf-8',
124
126
  timeout,
125
- stdio: ['pipe', 'pipe', 'pipe'],
126
- }).trim();
127
- } catch {
128
- return null;
129
- }
127
+ }, (error, stdout) => {
128
+ if (error) return resolve(null);
129
+ resolve(stdout.trim());
130
+ });
131
+ });
130
132
  }
131
133
 
132
134
  function findBinary(name: string): string | null {
133
- const cmd = platform() === 'win32' ? `where ${name}` : `which ${name}`;
134
- const result = runCommand(cmd, 5000);
135
- return result ? result.split('\n')[0] : null;
135
+ const isWin = platform() === 'win32';
136
+ const paths = (process.env.PATH || '').split(isWin ? ';' : ':');
137
+ const exes = isWin ? ['.exe', '.cmd', '.bat', ''] : [''];
138
+
139
+ for (const p of paths) {
140
+ if (!p) continue;
141
+ for (const ext of exes) {
142
+ const fullPath = path.join(p, name + ext);
143
+ try {
144
+ if (fs.existsSync(fullPath)) {
145
+ const stat = fs.statSync(fullPath);
146
+ if (stat.isFile() && (isWin || (stat.mode & 0o111))) {
147
+ return fullPath;
148
+ }
149
+ }
150
+ } catch { }
151
+ }
152
+ }
153
+ return null;
136
154
  }
137
155
 
138
156
  /** Extract version string from CLI output */
@@ -162,16 +180,16 @@ function getPlatformVersionCommand(
162
180
  return undefined;
163
181
  }
164
182
 
165
- function getVersion(binary: string, versionCommand?: string): string | null {
183
+ async function getVersion(binary: string, versionCommand?: string): Promise<string | null> {
166
184
  // Custom version command from provider.json
167
185
  if (versionCommand) {
168
- const raw = runCommand(versionCommand);
186
+ const raw = await runCommand(versionCommand);
169
187
  return raw ? parseVersion(raw) : null;
170
188
  }
171
189
 
172
190
  // Default: try --version, then -V, then -v
173
191
  for (const flag of ['--version', '-V', '-v']) {
174
- const raw = runCommand(`"${binary}" ${flag}`);
192
+ const raw = await runCommand(`"${binary}" ${flag}`);
175
193
  if (raw && raw.length < 500) return parseVersion(raw);
176
194
  }
177
195
  return null;
@@ -191,11 +209,11 @@ function checkPathExists(paths: string[]): string | null {
191
209
  }
192
210
 
193
211
  /** macOS: Get app version from Info.plist */
194
- function getMacAppVersion(appPath: string): string | null {
212
+ async function getMacAppVersion(appPath: string): Promise<string | null> {
195
213
  if (platform() !== 'darwin' || !appPath.endsWith('.app')) return null;
196
214
  const plistPath = path.join(appPath, 'Contents', 'Info.plist');
197
215
  if (!fs.existsSync(plistPath)) return null;
198
- const raw = runCommand(`/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "${plistPath}"`);
216
+ const raw = await runCommand(`/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "${plistPath}"`);
199
217
  return raw || null;
200
218
  }
201
219
 
@@ -242,10 +260,10 @@ export async function detectAllVersions(
242
260
 
243
261
  // Version: try CLI first, then plist
244
262
  if (resolvedBin) {
245
- info.version = getVersion(resolvedBin, versionCommand);
263
+ info.version = await getVersion(resolvedBin, versionCommand);
246
264
  }
247
265
  if (!info.version && appPath) {
248
- info.version = getMacAppVersion(appPath);
266
+ info.version = await getMacAppVersion(appPath);
249
267
  }
250
268
 
251
269
  } else if (provider.category === 'cli' || provider.category === 'acp') {
@@ -256,7 +274,7 @@ export async function detectAllVersions(
256
274
  info.binary = binPath || null;
257
275
 
258
276
  if (binPath) {
259
- info.version = getVersion(binPath, versionCommand);
277
+ info.version = await getVersion(binPath, versionCommand);
260
278
  }
261
279
 
262
280
  } else if (provider.category === 'extension') {