@abelxiaoxing/cadence 1.8.3 → 2.0.0

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 (208) hide show
  1. package/README.md +324 -111
  2. package/THIRD_PARTY_NOTICES.md +15 -0
  3. package/agents/design-explorer.md +14 -26
  4. package/agents/diagnosis-worker.md +14 -25
  5. package/agents/implementation-worker.md +16 -35
  6. package/config/.env.example +2 -5
  7. package/config/workflow-task.example.json +7 -0
  8. package/docs/remote-access.md +60 -0
  9. package/docs/reuse-and-distribution.md +44 -0
  10. package/docs/service-management.md +108 -0
  11. package/licenses/bundled-web.txt +6245 -0
  12. package/licenses/pi-web-ui-MIT.txt +21 -0
  13. package/licenses/pi-web-ui-reuse.md +22 -0
  14. package/package.json +94 -21
  15. package/src/index.ts +22 -1807
  16. package/src/native-build.ts +6 -0
  17. package/src/native-client.ts +103 -0
  18. package/src/native-export.ts +58 -0
  19. package/src/native-history.ts +359 -0
  20. package/src/operator-cli.mjs +453 -1937
  21. package/src/plan-proposal.ts +87 -0
  22. package/src/sdk-worker.mjs +549 -0
  23. package/src/service/contracts/active.ts +82 -0
  24. package/src/service/contracts/budget.ts +148 -0
  25. package/src/service/contracts/build.ts +67 -0
  26. package/src/service/contracts/capture.ts +48 -0
  27. package/src/service/contracts/core.ts +33 -0
  28. package/src/service/contracts/current.ts +261 -0
  29. package/src/service/contracts/domain.ts +68 -0
  30. package/src/service/contracts/history.ts +2245 -0
  31. package/src/service/contracts/models.ts +139 -0
  32. package/src/service/coordination.ts +862 -0
  33. package/src/service/private-files.ts +204 -0
  34. package/src/service-cli.mjs +5592 -0
  35. package/src/service-client.ts +747 -0
  36. package/src/service-contract.ts +245 -0
  37. package/src/service-host.mjs +22382 -0
  38. package/src/service-http-client.ts +425 -0
  39. package/src/service-wire.ts +372 -0
  40. package/src/task-shell.ts +1045 -0
  41. package/src/task-store.ts +479 -0
  42. package/src/task-types.ts +184 -0
  43. package/src/verification-diagnostics.ts +29 -72
  44. package/src/worker-capture.mjs +1197 -0
  45. package/src/worker-public.mjs +1753 -0
  46. package/src/worker-redaction.mjs +608 -0
  47. package/src/worker-tools.mjs +202 -0
  48. package/web/dist/assets/KaTeX_AMS-Regular.ttf +0 -0
  49. package/web/dist/assets/KaTeX_AMS-Regular.woff +0 -0
  50. package/web/dist/assets/KaTeX_AMS-Regular.woff2 +0 -0
  51. package/web/dist/assets/KaTeX_Caligraphic-Bold.ttf +0 -0
  52. package/web/dist/assets/KaTeX_Caligraphic-Bold.woff +0 -0
  53. package/web/dist/assets/KaTeX_Caligraphic-Bold.woff2 +0 -0
  54. package/web/dist/assets/KaTeX_Caligraphic-Regular.ttf +0 -0
  55. package/web/dist/assets/KaTeX_Caligraphic-Regular.woff +0 -0
  56. package/web/dist/assets/KaTeX_Caligraphic-Regular.woff2 +0 -0
  57. package/web/dist/assets/KaTeX_Fraktur-Bold.ttf +0 -0
  58. package/web/dist/assets/KaTeX_Fraktur-Bold.woff +0 -0
  59. package/web/dist/assets/KaTeX_Fraktur-Bold.woff2 +0 -0
  60. package/web/dist/assets/KaTeX_Fraktur-Regular.ttf +0 -0
  61. package/web/dist/assets/KaTeX_Fraktur-Regular.woff +0 -0
  62. package/web/dist/assets/KaTeX_Fraktur-Regular.woff2 +0 -0
  63. package/web/dist/assets/KaTeX_Main-Bold.ttf +0 -0
  64. package/web/dist/assets/KaTeX_Main-Bold.woff +0 -0
  65. package/web/dist/assets/KaTeX_Main-Bold.woff2 +0 -0
  66. package/web/dist/assets/KaTeX_Main-BoldItalic.ttf +0 -0
  67. package/web/dist/assets/KaTeX_Main-BoldItalic.woff +0 -0
  68. package/web/dist/assets/KaTeX_Main-BoldItalic.woff2 +0 -0
  69. package/web/dist/assets/KaTeX_Main-Italic.ttf +0 -0
  70. package/web/dist/assets/KaTeX_Main-Italic.woff +0 -0
  71. package/web/dist/assets/KaTeX_Main-Italic.woff2 +0 -0
  72. package/web/dist/assets/KaTeX_Main-Regular.ttf +0 -0
  73. package/web/dist/assets/KaTeX_Main-Regular.woff +0 -0
  74. package/web/dist/assets/KaTeX_Main-Regular.woff2 +0 -0
  75. package/web/dist/assets/KaTeX_Math-BoldItalic.ttf +0 -0
  76. package/web/dist/assets/KaTeX_Math-BoldItalic.woff +0 -0
  77. package/web/dist/assets/KaTeX_Math-BoldItalic.woff2 +0 -0
  78. package/web/dist/assets/KaTeX_Math-Italic.ttf +0 -0
  79. package/web/dist/assets/KaTeX_Math-Italic.woff +0 -0
  80. package/web/dist/assets/KaTeX_Math-Italic.woff2 +0 -0
  81. package/web/dist/assets/KaTeX_SansSerif-Bold.ttf +0 -0
  82. package/web/dist/assets/KaTeX_SansSerif-Bold.woff +0 -0
  83. package/web/dist/assets/KaTeX_SansSerif-Bold.woff2 +0 -0
  84. package/web/dist/assets/KaTeX_SansSerif-Italic.ttf +0 -0
  85. package/web/dist/assets/KaTeX_SansSerif-Italic.woff +0 -0
  86. package/web/dist/assets/KaTeX_SansSerif-Italic.woff2 +0 -0
  87. package/web/dist/assets/KaTeX_SansSerif-Regular.ttf +0 -0
  88. package/web/dist/assets/KaTeX_SansSerif-Regular.woff +0 -0
  89. package/web/dist/assets/KaTeX_SansSerif-Regular.woff2 +0 -0
  90. package/web/dist/assets/KaTeX_Script-Regular.ttf +0 -0
  91. package/web/dist/assets/KaTeX_Script-Regular.woff +0 -0
  92. package/web/dist/assets/KaTeX_Script-Regular.woff2 +0 -0
  93. package/web/dist/assets/KaTeX_Size1-Regular.ttf +0 -0
  94. package/web/dist/assets/KaTeX_Size1-Regular.woff +0 -0
  95. package/web/dist/assets/KaTeX_Size1-Regular.woff2 +0 -0
  96. package/web/dist/assets/KaTeX_Size2-Regular.ttf +0 -0
  97. package/web/dist/assets/KaTeX_Size2-Regular.woff +0 -0
  98. package/web/dist/assets/KaTeX_Size2-Regular.woff2 +0 -0
  99. package/web/dist/assets/KaTeX_Size3-Regular.ttf +0 -0
  100. package/web/dist/assets/KaTeX_Size3-Regular.woff +0 -0
  101. package/web/dist/assets/KaTeX_Size3-Regular.woff2 +0 -0
  102. package/web/dist/assets/KaTeX_Size4-Regular.ttf +0 -0
  103. package/web/dist/assets/KaTeX_Size4-Regular.woff +0 -0
  104. package/web/dist/assets/KaTeX_Size4-Regular.woff2 +0 -0
  105. package/web/dist/assets/KaTeX_Typewriter-Regular.ttf +0 -0
  106. package/web/dist/assets/KaTeX_Typewriter-Regular.woff +0 -0
  107. package/web/dist/assets/KaTeX_Typewriter-Regular.woff2 +0 -0
  108. package/web/dist/assets/cadence.css +2 -0
  109. package/web/dist/assets/cadence.js +7 -0
  110. package/web/dist/assets/markdown.js +296 -0
  111. package/web/dist/assets/react.js +9 -0
  112. package/web/dist/assets/rolldown-runtime.js +1 -0
  113. package/web/dist/assets/timeline-client.js +41 -0
  114. package/web/dist/assets/vis-timeline.css +1274 -0
  115. package/web/dist/assets/vis-timeline.js +32 -0
  116. package/web/dist/index.html +18 -0
  117. package/web/dist/manifest.json +505 -0
  118. package/config/plan-draft.example.json +0 -125
  119. package/config/plan-draft.multiple-tasks.example.json +0 -375
  120. package/config/plan-draft.quick.example.json +0 -78
  121. package/config/routes.example.json +0 -39
  122. package/prompts/abel-design.md +0 -382
  123. package/prompts/abel-diagnose.md +0 -71
  124. package/prompts/abel-implement.md +0 -284
  125. package/prompts/abel-init.md +0 -52
  126. package/src/activation.ts +0 -44
  127. package/src/activity-contracts.ts +0 -82
  128. package/src/agent-registry.ts +0 -53
  129. package/src/apply-transaction.ts +0 -1437
  130. package/src/artifact-store.ts +0 -213
  131. package/src/build-windows-job.mjs +0 -95
  132. package/src/candidate-artifact.ts +0 -143
  133. package/src/candidate-patch.ts +0 -271
  134. package/src/candidate-workspace.ts +0 -80
  135. package/src/canonical.ts +0 -16
  136. package/src/change-contract-schema.ts +0 -191
  137. package/src/change-contract.ts +0 -324
  138. package/src/change-verification.ts +0 -1617
  139. package/src/child-budget.ts +0 -58
  140. package/src/child-model.ts +0 -142
  141. package/src/child-session.ts +0 -640
  142. package/src/contracts.ts +0 -2476
  143. package/src/control-contracts.ts +0 -382
  144. package/src/delivery-compiler.ts +0 -1805
  145. package/src/delivery-revision.ts +0 -42
  146. package/src/design-control.ts +0 -1299
  147. package/src/design-diagnostics.ts +0 -181
  148. package/src/design-journal.ts +0 -1773
  149. package/src/directory-sync.ts +0 -36
  150. package/src/durable-contracts.ts +0 -231
  151. package/src/durable-workflow.ts +0 -978
  152. package/src/evidence-draft.ts +0 -122
  153. package/src/execution-profile.ts +0 -64
  154. package/src/execution-retention.ts +0 -77
  155. package/src/file-snapshot.ts +0 -163
  156. package/src/implement-continuation.ts +0 -559
  157. package/src/implement-graph.ts +0 -690
  158. package/src/implement-plan.ts +0 -72
  159. package/src/install-config.d.mts +0 -6
  160. package/src/isolation-backend.ts +0 -353
  161. package/src/model-source.ts +0 -22
  162. package/src/openspec-cli.ts +0 -494
  163. package/src/operator-cli-entry.mjs +0 -24
  164. package/src/operator-tools.ts +0 -309
  165. package/src/package-candidate.ts +0 -227
  166. package/src/package-delivery.ts +0 -486
  167. package/src/package-state.ts +0 -320
  168. package/src/package-verification.ts +0 -635
  169. package/src/package-workflow.ts +0 -342
  170. package/src/packet-runtime.ts +0 -570
  171. package/src/parent-provider.ts +0 -375
  172. package/src/phase-execution.ts +0 -2259
  173. package/src/pi-adapter.ts +0 -19
  174. package/src/plan-draft-summary.ts +0 -527
  175. package/src/plan-draft.ts +0 -502
  176. package/src/remove-path.ts +0 -32
  177. package/src/route-policy.ts +0 -545
  178. package/src/run-state.ts +0 -420
  179. package/src/run-store.ts +0 -1179
  180. package/src/safe-path.ts +0 -77
  181. package/src/scoped-grep-worker.mjs +0 -23
  182. package/src/scoped-tools.ts +0 -775
  183. package/src/single-task-draft.ts +0 -142
  184. package/src/sqlite-schema.ts +0 -171
  185. package/src/state-root.ts +0 -215
  186. package/src/storage-schema.ts +0 -360
  187. package/src/subagent-activity.ts +0 -1417
  188. package/src/submit-tool.ts +0 -950
  189. package/src/task-ledger.ts +0 -1338
  190. package/src/transport-budget.ts +0 -52
  191. package/src/verification-capability.ts +0 -1191
  192. package/src/verification-environment-io.ts +0 -389
  193. package/src/verification-environment.ts +0 -162
  194. package/src/verification-identity.ts +0 -77
  195. package/src/verification-scan.ts +0 -64
  196. package/src/windows-job-backend.ts +0 -419
  197. package/src/windows-job.c +0 -149
  198. package/src/worker-broker.ts +0 -806
  199. package/src/workflow-engine.ts +0 -28
  200. package/src/workflow-policy.ts +0 -1679
  201. package/src/workflow-recovery-policy.ts +0 -97
  202. package/src/workflow-scheduling.ts +0 -105
  203. package/src/workflow-state-machine.ts +0 -4355
  204. package/src/workflow-status.ts +0 -576
  205. package/src/workspace-io-entry.mjs +0 -76
  206. package/src/workspace-io-worker.mjs +0 -1312
  207. package/src/workspace-io.ts +0 -89
  208. package/src/workspace-store.ts +0 -634
@@ -0,0 +1,425 @@
1
+ import type { ServiceTransport } from "./service-client.ts";
2
+ import {
3
+ type CancelCommand,
4
+ type ChooseModelRequest,
5
+ type ClientBuild,
6
+ type Command,
7
+ ContractError,
8
+ canonicalJson,
9
+ decodeCancel,
10
+ decodeChooseModelRequest,
11
+ decodeClientBuild,
12
+ decodeCommand,
13
+ decodeEntityReadRequest,
14
+ decodeExportFrame,
15
+ decodeExportRequest,
16
+ decodeGraphReadRequest,
17
+ decodeId,
18
+ decodeListRequest,
19
+ decodePreflightRequest,
20
+ decodeReply,
21
+ decodeScope,
22
+ decodeSessionBootstrap,
23
+ type EntityReadRequest,
24
+ type ExportRequest,
25
+ type GraphReadRequest,
26
+ LIMITS,
27
+ type ListRequest,
28
+ type PreflightRequest,
29
+ parseWireJson,
30
+ type ReadCursor,
31
+ type Scope,
32
+ utf8Bytes,
33
+ } from "./service-contract.ts";
34
+ import {
35
+ decodeHttpInput,
36
+ decodeHttpOutput,
37
+ decodeSocketOutput,
38
+ type HttpOperation,
39
+ httpOutputLimit,
40
+ type SocketOutput,
41
+ WS_PATH,
42
+ wireRequest,
43
+ } from "./service-wire.ts";
44
+
45
+ /** Browser WebSocket or a native client's equivalent. No auth/query overlay API. */
46
+ export interface ReadSocket {
47
+ addEventListener(
48
+ type: "open" | "close" | "error",
49
+ listener: () => void,
50
+ ): void;
51
+ addEventListener(
52
+ type: "message",
53
+ listener: (event: { data: unknown }) => void,
54
+ ): void;
55
+ send(data: string): void;
56
+ close(): void;
57
+ }
58
+ export class HttpServiceTransport implements ServiceTransport {
59
+ private attachment: string | undefined;
60
+ private csrf: string | null = null;
61
+ private readonly fetcher: typeof fetch;
62
+ private readonly origin: string;
63
+ constructor(
64
+ private readonly options: {
65
+ origin: string;
66
+ build?: ClientBuild;
67
+ fetch?: typeof fetch;
68
+ /** Optional total bound for finite replies only, never streaming export. */
69
+ requestTimeoutMs?: number;
70
+ localCapability?: string;
71
+ socket?: (url: string) => ReadSocket;
72
+ },
73
+ ) {
74
+ const url = new URL(options.origin);
75
+ if (
76
+ url.origin !== options.origin ||
77
+ (url.protocol !== "https:" &&
78
+ !/^http:\/\/(?:127\.0\.0\.1|\[::1\]):[1-9][0-9]*$/.test(options.origin))
79
+ )
80
+ throw new ContractError("invalid");
81
+ this.origin = options.origin;
82
+ if (options.build) options.build = decodeClientBuild(options.build);
83
+ // Native browser fetch requires its Window receiver. Node/injected arrow
84
+ // fetchers tolerate the wrong `this`, so HTTP-only fixtures miss this bug.
85
+ this.fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
86
+ }
87
+ private headers(write: boolean): Record<string, string> {
88
+ const headers: Record<string, string> = { "Cache-Control": "no-store" };
89
+ if (this.options.build)
90
+ headers["X-Cadence-Build"] = canonicalJson(this.options.build);
91
+ if (this.attachment) headers["X-Cadence-Attachment"] = this.attachment;
92
+ if (this.options.localCapability)
93
+ headers["X-Cadence-Local"] = this.options.localCapability;
94
+ if (write) {
95
+ if (!this.attachment || (!this.options.localCapability && !this.csrf))
96
+ throw new ContractError("stale");
97
+ headers["Content-Type"] = "application/json";
98
+ if (this.csrf) headers["X-Cadence-CSRF"] = this.csrf;
99
+ }
100
+ return headers;
101
+ }
102
+ private async request(
103
+ operation: HttpOperation,
104
+ value: unknown,
105
+ signal?: AbortSignal,
106
+ ): Promise<unknown> {
107
+ const input = decodeHttpInput(operation, value),
108
+ wire = wireRequest(operation, input),
109
+ write = wire.method === "POST";
110
+ // No automatic session/preflight refresh, changed command ID, mutation retry,
111
+ // credential query or redirect follow after an uncertain HTTP outcome.
112
+ const response = await this.fetcher(`${this.origin}${wire.path}`, {
113
+ method: wire.method,
114
+ headers: this.headers(write),
115
+ credentials: "same-origin",
116
+ redirect: "error",
117
+ signal:
118
+ this.options.requestTimeoutMs === undefined
119
+ ? signal
120
+ : AbortSignal.any([
121
+ ...(signal ? [signal] : []),
122
+ AbortSignal.timeout(this.options.requestTimeoutMs),
123
+ ]),
124
+ ...(write ? { body: wire.body } : {}),
125
+ });
126
+ // Keep a known allocation even if its original response body is lost or
127
+ // malformed. Without a validated CSRF challenge detach may remain blocked;
128
+ // never silently forget that slot and acquire 16 replacement sessions.
129
+ let sessionAttachment: string | undefined;
130
+ try {
131
+ if (operation === "session" && response.ok) {
132
+ sessionAttachment = decodeId(
133
+ response.headers.get("x-cadence-attachment"),
134
+ );
135
+ this.attachment = sessionAttachment;
136
+ }
137
+ } catch (error) {
138
+ await response.body?.cancel().catch(() => {});
139
+ throw error;
140
+ }
141
+ const source = await boundedText(response, httpOutputLimit(operation)),
142
+ parsed = parseWireJson(source);
143
+ // Graph's category is known only after parsing. Count ORIGINAL wire bytes,
144
+ // not a canonical re-encoding which discards padding or alternate escapes.
145
+ if (utf8Bytes(source) > httpOutputLimit(operation, parsed))
146
+ throw new ContractError("oversize");
147
+ const result = decodeHttpOutput(operation, parsed);
148
+ if (operation === "session") {
149
+ const reply = decodeReply(result, decodeSessionBootstrap);
150
+ if (reply.kind === "ok") {
151
+ if (
152
+ (reply.value.authority === "local") !==
153
+ !!this.options.localCapability
154
+ )
155
+ throw new ContractError("forbidden");
156
+ this.attachment =
157
+ sessionAttachment ??
158
+ decodeId(response.headers.get("x-cadence-attachment"));
159
+ this.csrf = reply.value.csrf;
160
+ }
161
+ }
162
+ return result;
163
+ }
164
+ session(signal?: AbortSignal) {
165
+ return this.request("session", null, signal);
166
+ }
167
+ current(
168
+ request: import("./service-contract.ts").CurrentRequest,
169
+ signal?: AbortSignal,
170
+ ) {
171
+ return this.request("current", request, signal);
172
+ }
173
+ currentChanges(
174
+ request: import("./service-contract.ts").CurrentRequest,
175
+ signal?: AbortSignal,
176
+ ) {
177
+ return this.request("currentChanges", request, signal);
178
+ }
179
+ activeRuns(signal?: AbortSignal) {
180
+ return this.request("activeRuns", null, signal);
181
+ }
182
+ models(signal?: AbortSignal) {
183
+ return this.request("models", null, signal);
184
+ }
185
+ chooseModel(input: ChooseModelRequest) {
186
+ return this.request("chooseModel", decodeChooseModelRequest(input));
187
+ }
188
+ workspace(signal?: AbortSignal) {
189
+ return this.request("workspace", null, signal);
190
+ }
191
+ checkObligations(id: string, signal?: AbortSignal) {
192
+ return this.request("checkObligations", decodeId(id), signal);
193
+ }
194
+ entity(input: EntityReadRequest, signal?: AbortSignal) {
195
+ return this.request("entity", decodeEntityReadRequest(input), signal);
196
+ }
197
+ tasks(input: ListRequest, signal?: AbortSignal) {
198
+ return this.request("tasks", decodeListRequest(input), signal);
199
+ }
200
+ runs(input: ListRequest, signal?: AbortSignal) {
201
+ return this.request("runs", decodeListRequest(input), signal);
202
+ }
203
+ messages(input: ListRequest, signal?: AbortSignal) {
204
+ return this.request("messages", decodeListRequest(input), signal);
205
+ }
206
+ tools(input: ListRequest, signal?: AbortSignal) {
207
+ return this.request("tools", decodeListRequest(input), signal);
208
+ }
209
+ contents(input: ListRequest, signal?: AbortSignal) {
210
+ return this.request("contents", decodeListRequest(input), signal);
211
+ }
212
+ events(input: ListRequest, signal?: AbortSignal) {
213
+ return this.request("events", decodeListRequest(input), signal);
214
+ }
215
+ checks(input: ListRequest, signal?: AbortSignal) {
216
+ return this.request("checks", decodeListRequest(input), signal);
217
+ }
218
+ changes(input: ListRequest, signal?: AbortSignal) {
219
+ return this.request("changes", decodeListRequest(input), signal);
220
+ }
221
+ reviews(input: ListRequest, signal?: AbortSignal) {
222
+ return this.request("reviews", decodeListRequest(input), signal);
223
+ }
224
+ graph(input: GraphReadRequest, signal?: AbortSignal) {
225
+ return this.request("graph", decodeGraphReadRequest(input), signal);
226
+ }
227
+ preflight(input: PreflightRequest) {
228
+ return this.request("preflight", decodePreflightRequest(input));
229
+ }
230
+ command(input: Command) {
231
+ return this.request("command", decodeCommand(input));
232
+ }
233
+ cancel(input: CancelCommand) {
234
+ return this.request("cancel", decodeCancel(input));
235
+ }
236
+ receipt(id: string, signal?: AbortSignal) {
237
+ return this.request("receipt", decodeId(id), signal);
238
+ }
239
+ snapshot(input: Scope, signal?: AbortSignal) {
240
+ return this.request("snapshot", input, signal);
241
+ }
242
+ detail(input: ReadCursor, signal?: AbortSignal) {
243
+ return this.request("detail", input, signal);
244
+ }
245
+ search(input: ReadCursor, signal?: AbortSignal) {
246
+ return this.request("search", input, signal);
247
+ }
248
+ async detach(): Promise<unknown> {
249
+ const attachment = this.attachment;
250
+ if (!attachment) return;
251
+ const result = decodeReply(await this.request("detach", null), (value) => {
252
+ if (value !== null) throw new ContractError("invalid");
253
+ return null;
254
+ });
255
+ // A lost reply does not prove release. Retain the exact attachment for a
256
+ // later explicit detach rather than allocating another of the 16 slots.
257
+ // Stale means the server no longer owns this ID; rotation also revokes it.
258
+ if (
259
+ result.kind === "error" &&
260
+ result.error.code !== "stale" &&
261
+ result.error.code !== "unauthenticated"
262
+ )
263
+ throw new ContractError(result.error.code);
264
+ if (this.attachment === attachment) {
265
+ this.attachment = undefined;
266
+ this.csrf = null;
267
+ }
268
+ return result;
269
+ }
270
+ async *export(
271
+ input: ExportRequest,
272
+ signal: AbortSignal,
273
+ ): AsyncGenerator<unknown> {
274
+ const request = decodeExportRequest(input),
275
+ wire = wireRequest("export", request);
276
+ const response = await this.fetcher(`${this.origin}${wire.path}`, {
277
+ method: wire.method,
278
+ headers: this.headers(wire.method === "POST"),
279
+ ...(wire.body === undefined ? {} : { body: wire.body }),
280
+ credentials: "same-origin",
281
+ redirect: "error",
282
+ signal,
283
+ });
284
+ if (!response.ok || !response.body) {
285
+ await response.body?.cancel();
286
+ throw new ContractError("unavailable");
287
+ }
288
+ const reader = response.body.getReader(),
289
+ decoder = new TextDecoder("utf-8", { fatal: true });
290
+ let pending = "";
291
+ try {
292
+ for (;;) {
293
+ const { value, done } = await reader.read();
294
+ if (signal.aborted) throw new ContractError("unavailable");
295
+ // Fetch may coalesce many frames into one source chunk. Do not decode or
296
+ // retain a whole export-sized string before applying the per-line bound.
297
+ for (
298
+ let offset = 0;
299
+ offset < (done ? 1 : value.byteLength);
300
+ offset += LIMITS.chunkBytes
301
+ ) {
302
+ pending += done
303
+ ? decoder.decode()
304
+ : decoder.decode(
305
+ value.subarray(offset, offset + LIMITS.chunkBytes),
306
+ { stream: true },
307
+ );
308
+ let at = pending.indexOf("\n");
309
+ while (at !== -1) {
310
+ const line = pending.slice(0, at);
311
+ pending = pending.slice(at + 1);
312
+ yield decodeExportFrame(parseWireJson(line, LIMITS.controlBytes));
313
+ at = pending.indexOf("\n");
314
+ }
315
+ if (new TextEncoder().encode(pending).length > LIMITS.controlBytes)
316
+ throw new ContractError("oversize");
317
+ }
318
+ if (done) {
319
+ if (pending) throw new ContractError("invalid");
320
+ break;
321
+ }
322
+ }
323
+ } finally {
324
+ await reader.cancel().catch(() => {});
325
+ reader.releaseLock();
326
+ }
327
+ }
328
+ /** Explicit read-only connection. No reconnect, control commands or mutation replay.
329
+ * Native factories add ONLY their local-capability header to the socket handshake. */
330
+ subscribe(
331
+ scopeInput: Scope,
332
+ receive: (value: SocketOutput) => void,
333
+ status: (state: "current" | "stale" | "closed") => void,
334
+ ): () => void {
335
+ const scope = decodeScope(scopeInput);
336
+ if (!this.attachment || !this.options.socket)
337
+ throw new ContractError("unavailable");
338
+ const socket = this.options.socket(
339
+ `${this.origin.replace(/^http/, "ws")}${WS_PATH}?attachment=${this.attachment}`,
340
+ );
341
+ let active = false,
342
+ closed = false,
343
+ last = Date.now(),
344
+ reconciled = Date.now();
345
+ const stop = () => {
346
+ if (closed) return;
347
+ closed = true;
348
+ active = false;
349
+ clearInterval(timer);
350
+ try {
351
+ socket.close();
352
+ } catch {
353
+ /* Read transport is already closed locally. */
354
+ }
355
+ notify("closed");
356
+ };
357
+ const notify = (value: "current" | "stale" | "closed") => {
358
+ try {
359
+ status(value);
360
+ } catch {
361
+ /* View callback is not execution authority. */
362
+ }
363
+ };
364
+ const timer = setInterval(() => {
365
+ if (!active) return;
366
+ if (Date.now() - last >= LIMITS.staleMs) notify("stale");
367
+ try {
368
+ if (Date.now() - reconciled >= LIMITS.reconcileMs) {
369
+ socket.send(canonicalJson({ kind: "resync", scope }));
370
+ reconciled = Date.now();
371
+ } else socket.send('{"kind":"ping"}');
372
+ } catch {
373
+ stop();
374
+ }
375
+ }, LIMITS.heartbeatMs);
376
+ socket.addEventListener("open", () => {
377
+ if (closed) return;
378
+ active = true;
379
+ try {
380
+ socket.send(canonicalJson({ kind: "subscribe", scope }));
381
+ } catch {
382
+ stop();
383
+ }
384
+ });
385
+ socket.addEventListener("message", (event) => {
386
+ if (closed) return;
387
+ try {
388
+ if (typeof event.data !== "string") throw new ContractError("invalid");
389
+ const value = decodeSocketOutput(
390
+ parseWireJson(event.data, LIMITS.viewerBytes),
391
+ );
392
+ last = Date.now();
393
+ notify("current");
394
+ receive(value);
395
+ } catch {
396
+ stop();
397
+ }
398
+ });
399
+ socket.addEventListener("error", stop);
400
+ socket.addEventListener("close", stop);
401
+ return stop;
402
+ }
403
+ }
404
+ async function boundedText(
405
+ response: Response,
406
+ maximum: number,
407
+ ): Promise<string> {
408
+ if (!response.body) throw new ContractError("invalid");
409
+ const reader = response.body.getReader(),
410
+ decoder = new TextDecoder("utf-8", { fatal: true });
411
+ let bytes = 0,
412
+ result = "";
413
+ try {
414
+ for (;;) {
415
+ const { value, done } = await reader.read();
416
+ if (done) return result + decoder.decode();
417
+ bytes += value.byteLength;
418
+ if (bytes > maximum) throw new ContractError("oversize");
419
+ result += decoder.decode(value, { stream: true });
420
+ }
421
+ } finally {
422
+ await reader.cancel().catch(() => {});
423
+ reader.releaseLock();
424
+ }
425
+ }