@hearsay-tools/squawk 0.19.0-dev.9172 → 0.19.0-dev.9182

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 (138) hide show
  1. package/dist/contract/hosts.d.ts +925 -0
  2. package/dist/contract/index.js +104 -2
  3. package/dist/core/server-hook-registry.d.ts +13 -0
  4. package/dist/core/server-hook-registry.js.map +1 -1
  5. package/dist/delegation/transport.d.ts +78 -78
  6. package/dist/features/automations/automations-routes.d.ts +150 -150
  7. package/dist/features/hosts/admission.d.ts +52 -0
  8. package/dist/features/hosts/admission.js +89 -0
  9. package/dist/features/hosts/admission.js.map +1 -0
  10. package/dist/features/hosts/gateway.d.ts +14 -3
  11. package/dist/features/hosts/gateway.js +35 -21
  12. package/dist/features/hosts/gateway.js.map +1 -1
  13. package/dist/features/hosts/index.d.ts +7 -3
  14. package/dist/features/hosts/index.js +41 -7
  15. package/dist/features/hosts/index.js.map +1 -1
  16. package/dist/features/hosts/registry-reconciler.d.ts +41 -0
  17. package/dist/features/hosts/registry-reconciler.js +168 -0
  18. package/dist/features/hosts/registry-reconciler.js.map +1 -0
  19. package/dist/features/hosts/routes.d.ts +370 -4
  20. package/dist/features/hosts/routes.js +72 -62
  21. package/dist/features/hosts/routes.js.map +1 -1
  22. package/dist/features/hosts/runs-index-events.d.ts +23 -0
  23. package/dist/features/hosts/runs-index-events.js +116 -0
  24. package/dist/features/hosts/runs-index-events.js.map +1 -0
  25. package/dist/features/hosts/runs-index-patch.d.ts +203 -0
  26. package/dist/features/hosts/runs-index-patch.js +798 -0
  27. package/dist/features/hosts/runs-index-patch.js.map +1 -0
  28. package/dist/features/hosts/runs-index.d.ts +149 -0
  29. package/dist/features/hosts/runs-index.js +762 -0
  30. package/dist/features/hosts/runs-index.js.map +1 -0
  31. package/dist/features/hosts/runs-search.d.ts +28 -0
  32. package/dist/features/hosts/runs-search.js +151 -0
  33. package/dist/features/hosts/runs-search.js.map +1 -0
  34. package/dist/features/hosts/supervisor.d.ts +4 -0
  35. package/dist/features/hosts/supervisor.js +14 -6
  36. package/dist/features/hosts/supervisor.js.map +1 -1
  37. package/dist/plugin/index.d.ts +1 -1
  38. package/dist/plugin/index.js.map +1 -1
  39. package/dist/server/repo-routes.d.ts +52 -52
  40. package/dist/server/server.js +7 -1
  41. package/dist/server/server.js.map +1 -1
  42. package/dist/server/workspace-run-feed.d.ts +4 -0
  43. package/dist/server/workspace-run-feed.js +13 -0
  44. package/dist/server/workspace-run-feed.js.map +1 -1
  45. package/package.json +4 -4
  46. package/scripts/benchmark-hosts-runs-index-probes.ts +242 -0
  47. package/scripts/benchmark-hosts-runs-index.ts +776 -0
  48. package/web/dist/assets/accounts-section-DYQC-wSh.js +1 -0
  49. package/web/dist/assets/activity-motion-XvrmbNgR.js +1 -0
  50. package/web/dist/assets/{activity-route-C2zP5vVV.js → activity-route-Dj8ltoqG.js} +1 -1
  51. package/web/dist/assets/{agent-accounts-D_ZKAmaW.js → agent-accounts-C2ILQhZy.js} +1 -1
  52. package/web/dist/assets/{agent-config-section-CwK_izpU.js → agent-config-section-D16TRCE_.js} +2 -2
  53. package/web/dist/assets/agent-defaults-section-Dm0khLjs.js +1 -0
  54. package/web/dist/assets/{appearance-DvoRcoRX.js → appearance-CP6zVctf.js} +1 -1
  55. package/web/dist/assets/{archive-on-merge-field-DWPtF9dh.js → archive-on-merge-field-BA8aUtRQ.js} +1 -1
  56. package/web/dist/assets/{ask-card-D-om0EtP.js → ask-card-CLdlwd68.js} +1 -1
  57. package/web/dist/assets/attention-C7BUdd2s.js +1 -0
  58. package/web/dist/assets/automations-route-BVDO_Kai.js +2 -0
  59. package/web/dist/assets/{commit-list-CPJLP4DU.js → commit-list-Bdekr2K7.js} +1 -1
  60. package/web/dist/assets/{diff-BQJN6jzN.js → diff-Du0FsqAK.js} +2 -2
  61. package/web/dist/assets/{diff-controls-AsSX7gfO.js → diff-controls-DTC_6oqk.js} +1 -1
  62. package/web/dist/assets/{diff-view-BW5bbiaq.js → diff-view-TKooupFV.js} +1 -1
  63. package/web/dist/assets/{discard-changes-dialog-Bv4yc0N1.js → discard-changes-dialog-Bg-3Xbox.js} +1 -1
  64. package/web/dist/assets/{file-preview-CnrFxbea.js → file-preview-DMJCprVk.js} +1 -1
  65. package/web/dist/assets/{folder-browser-CFd1U5hn.js → folder-browser-3cBLlnE9.js} +1 -1
  66. package/web/dist/assets/{git-toolbar-C7iolhIi.js → git-toolbar-COhBdctn.js} +1 -1
  67. package/web/dist/assets/github-DUTSv2Hs.js +1 -0
  68. package/web/dist/assets/{global-activity-route-Dijwg4OL.js → global-activity-route-CypEKUv_.js} +1 -1
  69. package/web/dist/assets/hosts-iUyg8S3j.js +1 -0
  70. package/web/dist/assets/index-BV3EQb9T.js +21 -0
  71. package/web/dist/assets/index-Bh7COq0B.css +1 -0
  72. package/web/dist/assets/{label-CgU9vxuM.js → label-CWlxyeC-.js} +1 -1
  73. package/web/dist/assets/{markdown-Cljq4S1h.js → markdown-0uCxcToP.js} +1 -1
  74. package/web/dist/assets/{open-in-menu-BI7mnPPf.js → open-in-menu-Bf8JA2DJ.js} +1 -1
  75. package/web/dist/assets/{option-select-BcTkv-7t.js → option-select-DQJEHmHf.js} +1 -1
  76. package/web/dist/assets/{preferences-section-CEKXGhEj.js → preferences-section-Cvl5vyfN.js} +1 -1
  77. package/web/dist/assets/{preview-EtD19mg1.js → preview-BSFJfN4s.js} +1 -1
  78. package/web/dist/assets/{preview-pane-connected-CKRBfx7t.js → preview-pane-connected-i3GJtDL3.js} +2 -2
  79. package/web/dist/assets/{project-location-hufc_p8y.js → project-location-BcjOhqun.js} +1 -1
  80. package/web/dist/assets/{project-router-Dc6KBQsv.js → project-router-CwD1firw.js} +1 -1
  81. package/web/dist/assets/{projects-section-vOFZ4lbx.js → projects-section-CAOFPkDQ.js} +1 -1
  82. package/web/dist/assets/{prompt-templates-section-Caash2nq.js → prompt-templates-section-BXTfLET4.js} +1 -1
  83. package/web/dist/assets/queries-D9mg7sFY.js +1 -0
  84. package/web/dist/assets/{read-state-BeVNfGkB.js → read-state-BsTfJki5.js} +1 -1
  85. package/web/dist/assets/{reference-chip-BjerVjzM.js → reference-chip-CZKBU_Ud.js} +1 -1
  86. package/web/dist/assets/{remote-settings-notice-fNgh5LdN.js → remote-settings-notice-CUK4ZFYF.js} +1 -1
  87. package/web/dist/assets/repo-git-Dx85MEuK.js +1 -0
  88. package/web/dist/assets/{report-reader-CK1WDtEH.js → report-reader-BDdY5kpz.js} +1 -1
  89. package/web/dist/assets/{report-selection-CZ8eb9QP.js → report-selection-Y2F9NTAs.js} +1 -1
  90. package/web/dist/assets/{reports-B-GImLAo.js → reports-DWKpm_us.js} +1 -1
  91. package/web/dist/assets/{resources-section-ApF3gXrw.js → resources-section-D9tzbv9w.js} +1 -1
  92. package/web/dist/assets/{review-notes-drafts-BdjEFs1G.js → review-notes-drafts-BSkmq3Nj.js} +1 -1
  93. package/web/dist/assets/{review-panel-D4zmYH8O.js → review-panel-C9UZjWFl.js} +1 -1
  94. package/web/dist/assets/{review-strip-BpHXklAn.js → review-strip-qTG5JaOw.js} +1 -1
  95. package/web/dist/assets/{run-detail-refresh-CE0vyYYA.js → run-detail-refresh-SYZM94ch.js} +1 -1
  96. package/web/dist/assets/{run-diff-ClfLRsHF.js → run-diff-D26PXp6r.js} +1 -1
  97. package/web/dist/assets/run-header-BrUcSJu6.js +2 -0
  98. package/web/dist/assets/{select-CwDhRDtw.js → select-BUsS7uOZ.js} +1 -1
  99. package/web/dist/assets/{session-context-section-C87jx7RB.js → session-context-section-Bgzou-NG.js} +1 -1
  100. package/web/dist/assets/{settings-agent-picker-Dk8yJ57U.js → settings-agent-picker-CH3CQhOh.js} +1 -1
  101. package/web/dist/assets/{settings-save-bar-cu8BKCGT.js → settings-save-bar-cyvALSgW.js} +1 -1
  102. package/web/dist/assets/{settings-shell-mhQfQKf1.js → settings-shell-Cl-cu4r5.js} +1 -1
  103. package/web/dist/assets/{sidebar-section-DOQ5N1L6.js → sidebar-section-Cj2fDrhV.js} +1 -1
  104. package/web/dist/assets/{skills-DXJ1gQBD.js → skills-DLMbRR_5.js} +1 -1
  105. package/web/dist/assets/{status-dot-Bmn4xhch.js → status-dot-DTU7afRv.js} +1 -1
  106. package/web/dist/assets/{tab-link-6TltE1jl.js → tab-link-BJDe5cT4.js} +1 -1
  107. package/web/dist/assets/{task-changes-D9Sdmpmw.js → task-changes-ito4fOGh.js} +2 -2
  108. package/web/dist/assets/{task-commits-A0UIqxpL.js → task-commits-BYOIU9zy.js} +1 -1
  109. package/web/dist/assets/{task-file-scope-ID220XKo.js → task-file-scope-B8EEJyHp.js} +1 -1
  110. package/web/dist/assets/{task-files-Id2tuAAG.js → task-files-CF0QKnm-.js} +1 -1
  111. package/web/dist/assets/{task-github-item-YKUcwp2o.js → task-github-item-C6Fu8MvM.js} +1 -1
  112. package/web/dist/assets/{task-groups-DCg4iOB9.js → task-groups-BvVfsQKd.js} +1 -1
  113. package/web/dist/assets/{task-thread-A_vkygGX.js → task-thread-BWrvepxB.js} +2 -2
  114. package/web/dist/assets/{thread-state-6-BzRrJ_.js → thread-state-8E0eYXGu.js} +1 -1
  115. package/web/dist/assets/toaster-2ud_VdfV.js +4 -0
  116. package/web/dist/assets/{use-finish-run-DO-nnAaa.js → use-finish-run-a2qZy6zr.js} +1 -1
  117. package/web/dist/assets/{use-hand-to-agent-state-CADaL8U8.js → use-hand-to-agent-state-DT1ngmHe.js} +1 -1
  118. package/web/dist/assets/use-path-bases-CZ6F93wt.js +1 -0
  119. package/web/dist/assets/use-workspace-config-save-DDI7_WtK.js +1 -0
  120. package/web/dist/assets/{workflows-DOLG-Rns.js → workflows-2e0Sm6F1.js} +2 -2
  121. package/web/dist/assets/{workspace-tools-DTCJVDTE.js → workspace-tools-D4DO9w12.js} +1 -1
  122. package/web/dist/assets/{worktrees-section-BOHDbywt.js → worktrees-section-8-d6zWQ-.js} +5 -5
  123. package/web/dist/index.html +20 -20
  124. package/web/dist/assets/accounts-section-Bnr89jmC.js +0 -1
  125. package/web/dist/assets/activity-motion-BW0tAmYF.js +0 -1
  126. package/web/dist/assets/agent-defaults-section-RyEogH0g.js +0 -1
  127. package/web/dist/assets/attention-BI6592lk.js +0 -1
  128. package/web/dist/assets/automations-route-DfGE4xWT.js +0 -2
  129. package/web/dist/assets/github-DGElvfMU.js +0 -1
  130. package/web/dist/assets/hosts-CpDMDiQW.js +0 -1
  131. package/web/dist/assets/index-BVRdRJAN.css +0 -1
  132. package/web/dist/assets/index-DPfg7xSB.js +0 -21
  133. package/web/dist/assets/queries-IlC9MZgh.js +0 -1
  134. package/web/dist/assets/repo-git-5MK_RAR6.js +0 -1
  135. package/web/dist/assets/run-header-BUe92WWr.js +0 -2
  136. package/web/dist/assets/toaster-DNnL8v10.js +0 -4
  137. package/web/dist/assets/use-path-bases-CFAmFn_E.js +0 -1
  138. package/web/dist/assets/use-workspace-config-save-DScW6_8J.js +0 -1
@@ -0,0 +1,798 @@
1
+ import { runIndexEntrySchema, } from '../../contract/index.js';
2
+ import { runsIndexResponseSchema, workspaceReadyEventSchema, workspaceRunDeletedEventSchema, workspaceRunSummaryEventSchema, workspaceUsageEventSchema, } from '../../contract/index.js';
3
+ /** Key a row uniquely within one host (`id` is unique only within a project). */
4
+ export function hostRowKey(projectId, runId) {
5
+ return `${projectId}\0${runId}`;
6
+ }
7
+ /**
8
+ * Newest-first comparator on ISO-8601 UTC `createdAt`.
9
+ * `RunStore.createRun` (`packages/cezar/src/runs/store.ts:441`) is the sole producer
10
+ * (`new Date().toISOString()`), matching `run-row.ts:40` and `run-summary-page.ts:33`.
11
+ */
12
+ export function compareCreatedAtDesc(a, b) {
13
+ return a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0;
14
+ }
15
+ /** Shallow-fast deep equality for JSON-shaped run summaries and process usage samples. */
16
+ export function deepEqualJson(a, b) {
17
+ if (a === b)
18
+ return true;
19
+ if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object')
20
+ return false;
21
+ if (Array.isArray(a) || Array.isArray(b)) {
22
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length)
23
+ return false;
24
+ for (let i = 0; i < a.length; i += 1) {
25
+ if (!deepEqualJson(a[i], b[i]))
26
+ return false;
27
+ }
28
+ return true;
29
+ }
30
+ const objA = a;
31
+ const objB = b;
32
+ const keysA = Object.keys(objA);
33
+ const keysB = Object.keys(objB);
34
+ if (keysA.length !== keysB.length)
35
+ return false;
36
+ for (const key of keysA) {
37
+ if (!Object.prototype.hasOwnProperty.call(objB, key))
38
+ return false;
39
+ if (!deepEqualJson(objA[key], objB[key]))
40
+ return false;
41
+ }
42
+ return true;
43
+ }
44
+ /**
45
+ * Mutable in-memory task index for one remote host.
46
+ * Stores rows already stamped with `hostId` so `GET /api/v1/hosts/runs-index` never copies
47
+ * every row on read, and caches the newest-first sorted view lazily.
48
+ */
49
+ export class HostIndexStore {
50
+ hostId;
51
+ rowsByKey = new Map();
52
+ keysByProject = new Map();
53
+ archivedCountByProject = new Map();
54
+ liveUsageKeysByProject = new Map();
55
+ truncatedSet = new Set();
56
+ referenceStatusesMap = {};
57
+ perProjectLimitValue;
58
+ generationValue;
59
+ eventSeqValue = 0;
60
+ sortedRunsCache = [];
61
+ sortedIndexByKey = new Map();
62
+ sortedDirty = false;
63
+ constructor(hostId) {
64
+ this.hostId = hostId;
65
+ }
66
+ get size() {
67
+ return this.rowsByKey.size;
68
+ }
69
+ get generation() {
70
+ return this.generationValue;
71
+ }
72
+ get eventSeq() {
73
+ return this.eventSeqValue;
74
+ }
75
+ get perProjectLimit() {
76
+ return this.perProjectLimitValue;
77
+ }
78
+ get truncated() {
79
+ return [...this.truncatedSet];
80
+ }
81
+ get referenceStatuses() {
82
+ return this.referenceStatusesMap;
83
+ }
84
+ /** Newest-first rows stamped with `hostId`; lazily sorted and cached until order changes. */
85
+ getSortedRuns() {
86
+ if (this.sortedDirty) {
87
+ this.sortedRunsCache = [...this.rowsByKey.values()].sort(compareCreatedAtDesc);
88
+ this.rebuildSortedIndex();
89
+ this.sortedDirty = false;
90
+ }
91
+ return this.sortedRunsCache;
92
+ }
93
+ /** Replace all rows and metadata from a fresh `GET /api/v1/workspace/runs-index` snapshot. */
94
+ replaceFromSnapshot(snapshot) {
95
+ const stamped = [];
96
+ for (const run of snapshot.runs) {
97
+ if (run.delegation?.role === 'worker')
98
+ continue;
99
+ stamped.push({ ...run, hostId: this.hostId });
100
+ }
101
+ return this.replaceFromPrepared({
102
+ runs: stamped,
103
+ referenceStatuses: snapshot.referenceStatuses,
104
+ perProjectLimit: snapshot.perProjectLimit,
105
+ truncated: snapshot.truncated,
106
+ generation: snapshot.generation,
107
+ eventSeq: snapshot.eventSeq,
108
+ });
109
+ }
110
+ /**
111
+ * Replace all rows and metadata from an already-validated, host-stamped snapshot.
112
+ * Returns `true` when rows or metadata actually differed from the previous store state.
113
+ */
114
+ replaceFromPrepared(prepared) {
115
+ const changed = this.differsFromPrepared(prepared);
116
+ this.rowsByKey.clear();
117
+ this.keysByProject.clear();
118
+ this.archivedCountByProject.clear();
119
+ this.liveUsageKeysByProject.clear();
120
+ this.truncatedSet.clear();
121
+ for (const projectId of prepared.truncated) {
122
+ this.truncatedSet.add(projectId);
123
+ }
124
+ this.referenceStatusesMap = { ...prepared.referenceStatuses };
125
+ this.perProjectLimitValue = prepared.perProjectLimit;
126
+ this.generationValue = prepared.generation;
127
+ this.eventSeqValue = prepared.eventSeq;
128
+ const sorted = [];
129
+ for (const stamped of prepared.runs) {
130
+ if (stamped.delegation?.role === 'worker')
131
+ continue;
132
+ this.insertRowInternal(stamped);
133
+ sorted.push(stamped);
134
+ }
135
+ // Snapshots arrive newest-first; sort defensively if a host returned out-of-order entries.
136
+ sorted.sort(compareCreatedAtDesc);
137
+ this.sortedRunsCache = sorted;
138
+ this.rebuildSortedIndex();
139
+ this.sortedDirty = false;
140
+ return changed;
141
+ }
142
+ clear() {
143
+ this.rowsByKey.clear();
144
+ this.keysByProject.clear();
145
+ this.archivedCountByProject.clear();
146
+ this.liveUsageKeysByProject.clear();
147
+ this.truncatedSet.clear();
148
+ this.referenceStatusesMap = {};
149
+ this.perProjectLimitValue = undefined;
150
+ this.generationValue = undefined;
151
+ this.eventSeqValue = 0;
152
+ this.sortedRunsCache = [];
153
+ this.sortedIndexByKey.clear();
154
+ this.sortedDirty = false;
155
+ }
156
+ rebuildSortedIndex() {
157
+ this.sortedIndexByKey.clear();
158
+ for (let i = 0; i < this.sortedRunsCache.length; i += 1) {
159
+ const row = this.sortedRunsCache[i];
160
+ this.sortedIndexByKey.set(hostRowKey(row.projectId, row.id), i);
161
+ }
162
+ }
163
+ differsFromPrepared(prepared) {
164
+ if (this.perProjectLimitValue !== prepared.perProjectLimit)
165
+ return true;
166
+ if (this.truncatedSet.size !== prepared.truncated.length)
167
+ return true;
168
+ for (const id of prepared.truncated) {
169
+ if (!this.truncatedSet.has(id))
170
+ return true;
171
+ }
172
+ if (!deepEqualJson(this.referenceStatusesMap, prepared.referenceStatuses))
173
+ return true;
174
+ if (this.rowsByKey.size !== prepared.runs.length)
175
+ return true;
176
+ for (const row of prepared.runs) {
177
+ const prev = this.rowsByKey.get(hostRowKey(row.projectId, row.id));
178
+ if (!prev || !deepEqualJson(prev, row))
179
+ return true;
180
+ }
181
+ return false;
182
+ }
183
+ /** Fold one `run-summary` or `run-deleted` frame into the host's index. */
184
+ applyChange(change) {
185
+ const project = change.project;
186
+ const key = hostRowKey(project, change.type === 'run' ? change.run.id : change.id);
187
+ const previous = this.rowsByKey.get(key);
188
+ const truncated = this.truncatedSet.has(project);
189
+ if (change.type === 'deleted') {
190
+ if (!previous)
191
+ return { changed: false, reconcile: false };
192
+ this.removeRowInternal(key, previous);
193
+ this.sortedDirty = true;
194
+ return { changed: true, reconcile: truncated && previous.archived };
195
+ }
196
+ if (change.run.delegation?.role === 'worker') {
197
+ if (!previous)
198
+ return { changed: false, reconcile: false };
199
+ this.removeRowInternal(key, previous);
200
+ this.sortedDirty = true;
201
+ return { changed: true, reconcile: false };
202
+ }
203
+ const next = { ...change.run, hostId: this.hostId, projectId: project };
204
+ if (previous) {
205
+ return this.applyExistingRowChange(key, previous, next, truncated);
206
+ }
207
+ return this.applyNewRowChange(next, truncated);
208
+ }
209
+ applyExistingRowChange(key, previous, next, truncated) {
210
+ if (deepEqualJson(previous, next))
211
+ return { changed: false, reconcile: false };
212
+ this.replaceRowInternal(key, previous, next);
213
+ if (!this.sortedDirty && previous.createdAt === next.createdAt) {
214
+ const idx = this.sortedIndexByKey.get(key);
215
+ if (idx !== undefined)
216
+ this.sortedRunsCache[idx] = next;
217
+ else
218
+ this.sortedDirty = true;
219
+ }
220
+ else {
221
+ this.sortedDirty = true;
222
+ }
223
+ const limit = this.perProjectLimitValue;
224
+ const archivedCount = this.archivedCountByProject.get(next.projectId) ?? 0;
225
+ const boundary = previous.archived !== next.archived
226
+ && (truncated || (limit !== undefined && archivedCount > limit));
227
+ return { changed: true, reconcile: boundary };
228
+ }
229
+ applyNewRowChange(next, truncated) {
230
+ const project = next.projectId;
231
+ const projectKnown = this.keysByProject.has(project)
232
+ || truncated
233
+ || Object.prototype.hasOwnProperty.call(this.referenceStatusesMap, project);
234
+ if (truncated) {
235
+ return this.applyToTruncatedWindow(next);
236
+ }
237
+ this.insertRowInternal(next);
238
+ this.sortedDirty = true;
239
+ const limit = this.perProjectLimitValue;
240
+ const archivedCount = this.archivedCountByProject.get(project) ?? 0;
241
+ const exceeded = next.archived && limit !== undefined && archivedCount > limit;
242
+ return { changed: true, reconcile: exceeded || !projectKnown };
243
+ }
244
+ /** Apply one project's live usage tick in O(live runs) without invalidating sort order. */
245
+ applyUsage(project, usage) {
246
+ const prevLive = this.liveUsageKeysByProject.get(project);
247
+ const nextLive = new Set();
248
+ let changed = false;
249
+ for (const [runId, sample] of Object.entries(usage)) {
250
+ const key = hostRowKey(project, runId);
251
+ const row = this.rowsByKey.get(key);
252
+ if (!row)
253
+ continue;
254
+ nextLive.add(key);
255
+ if (deepEqualJson(row.usage, sample))
256
+ continue;
257
+ const updated = { ...row, usage: sample };
258
+ this.rowsByKey.set(key, updated);
259
+ this.updateSortedSlotInPlace(key, updated);
260
+ changed = true;
261
+ }
262
+ if (prevLive) {
263
+ for (const key of prevLive) {
264
+ if (nextLive.has(key))
265
+ continue;
266
+ const row = this.rowsByKey.get(key);
267
+ if (!row || row.usage === undefined)
268
+ continue;
269
+ const { usage: _dropped, ...rest } = row;
270
+ this.rowsByKey.set(key, rest);
271
+ this.updateSortedSlotInPlace(key, rest);
272
+ changed = true;
273
+ }
274
+ }
275
+ if (nextLive.size > 0)
276
+ this.liveUsageKeysByProject.set(project, nextLive);
277
+ else
278
+ this.liveUsageKeysByProject.delete(project);
279
+ return changed;
280
+ }
281
+ updateSortedSlotInPlace(key, row) {
282
+ if (this.sortedDirty)
283
+ return;
284
+ const idx = this.sortedIndexByKey.get(key);
285
+ if (idx !== undefined) {
286
+ this.sortedRunsCache[idx] = row;
287
+ }
288
+ }
289
+ /** Remove all rows, truncated flags, and reference statuses for a removed project. */
290
+ dropProject(project) {
291
+ const keys = this.keysByProject.get(project);
292
+ const hadRows = keys !== undefined && keys.size > 0;
293
+ if (keys) {
294
+ for (const key of keys)
295
+ this.rowsByKey.delete(key);
296
+ this.keysByProject.delete(project);
297
+ }
298
+ this.archivedCountByProject.delete(project);
299
+ this.liveUsageKeysByProject.delete(project);
300
+ const hadTruncated = this.truncatedSet.delete(project);
301
+ const hadStatuses = Object.prototype.hasOwnProperty.call(this.referenceStatusesMap, project);
302
+ if (hadStatuses) {
303
+ const next = { ...this.referenceStatusesMap };
304
+ delete next[project];
305
+ this.referenceStatusesMap = next;
306
+ }
307
+ if (hadRows)
308
+ this.sortedDirty = true;
309
+ return hadRows || hadTruncated || hadStatuses;
310
+ }
311
+ applyToTruncatedWindow(row) {
312
+ const edge = this.windowEdge(row.projectId);
313
+ const insideWindow = edge !== undefined && row.createdAt > edge;
314
+ if (row.archived && !insideWindow) {
315
+ return { changed: false, reconcile: edge !== undefined && row.createdAt === edge };
316
+ }
317
+ this.insertRowInternal(row);
318
+ this.sortedDirty = true;
319
+ return {
320
+ changed: true,
321
+ reconcile: row.archived || edge === undefined || row.createdAt < edge,
322
+ };
323
+ }
324
+ windowEdge(project) {
325
+ const keys = this.keysByProject.get(project);
326
+ if (!keys)
327
+ return undefined;
328
+ let edge;
329
+ for (const key of keys) {
330
+ const row = this.rowsByKey.get(key);
331
+ if (row && row.archived && (edge === undefined || row.createdAt < edge)) {
332
+ edge = row.createdAt;
333
+ }
334
+ }
335
+ return edge;
336
+ }
337
+ insertRowInternal(row) {
338
+ const key = hostRowKey(row.projectId, row.id);
339
+ this.rowsByKey.set(key, row);
340
+ let projectKeys = this.keysByProject.get(row.projectId);
341
+ if (!projectKeys) {
342
+ projectKeys = new Set();
343
+ this.keysByProject.set(row.projectId, projectKeys);
344
+ }
345
+ projectKeys.add(key);
346
+ if (row.archived) {
347
+ this.archivedCountByProject.set(row.projectId, (this.archivedCountByProject.get(row.projectId) ?? 0) + 1);
348
+ }
349
+ if (row.usage !== undefined) {
350
+ let liveKeys = this.liveUsageKeysByProject.get(row.projectId);
351
+ if (!liveKeys) {
352
+ liveKeys = new Set();
353
+ this.liveUsageKeysByProject.set(row.projectId, liveKeys);
354
+ }
355
+ liveKeys.add(key);
356
+ }
357
+ }
358
+ replaceRowInternal(key, previous, next) {
359
+ this.rowsByKey.set(key, next);
360
+ if (previous.archived !== next.archived) {
361
+ const prevCount = this.archivedCountByProject.get(next.projectId) ?? 0;
362
+ const nextCount = next.archived ? prevCount + 1 : Math.max(0, prevCount - 1);
363
+ if (nextCount > 0)
364
+ this.archivedCountByProject.set(next.projectId, nextCount);
365
+ else
366
+ this.archivedCountByProject.delete(next.projectId);
367
+ }
368
+ if (next.usage !== undefined) {
369
+ let liveKeys = this.liveUsageKeysByProject.get(next.projectId);
370
+ if (!liveKeys) {
371
+ liveKeys = new Set();
372
+ this.liveUsageKeysByProject.set(next.projectId, liveKeys);
373
+ }
374
+ liveKeys.add(key);
375
+ }
376
+ else if (previous.usage !== undefined) {
377
+ const liveKeys = this.liveUsageKeysByProject.get(next.projectId);
378
+ if (liveKeys) {
379
+ liveKeys.delete(key);
380
+ if (liveKeys.size === 0)
381
+ this.liveUsageKeysByProject.delete(next.projectId);
382
+ }
383
+ }
384
+ }
385
+ removeRowInternal(key, previous) {
386
+ this.rowsByKey.delete(key);
387
+ const projectKeys = this.keysByProject.get(previous.projectId);
388
+ if (projectKeys) {
389
+ projectKeys.delete(key);
390
+ if (projectKeys.size === 0)
391
+ this.keysByProject.delete(previous.projectId);
392
+ }
393
+ if (previous.archived) {
394
+ const nextCount = Math.max(0, (this.archivedCountByProject.get(previous.projectId) ?? 0) - 1);
395
+ if (nextCount > 0)
396
+ this.archivedCountByProject.set(previous.projectId, nextCount);
397
+ else
398
+ this.archivedCountByProject.delete(previous.projectId);
399
+ }
400
+ if (previous.usage !== undefined) {
401
+ const liveKeys = this.liveUsageKeysByProject.get(previous.projectId);
402
+ if (liveKeys) {
403
+ liveKeys.delete(key);
404
+ if (liveKeys.size === 0)
405
+ this.liveUsageKeysByProject.delete(previous.projectId);
406
+ }
407
+ }
408
+ }
409
+ }
410
+ /**
411
+ * Per-stream overlay fencing concurrent SSE frames against an in-flight `/workspace/runs-index`
412
+ * snapshot, mirroring `IndexOverlay` in `packages/web/src/api/runs-index-cache.ts`.
413
+ */
414
+ export class HostStreamOverlay {
415
+ generation;
416
+ floor;
417
+ lastSeq;
418
+ changes = new Map();
419
+ get pendingChangeCount() {
420
+ return this.changes.size;
421
+ }
422
+ onReady(generation, seq) {
423
+ const generationChanged = this.generation !== undefined && this.generation !== generation;
424
+ const missedFrames = !generationChanged && this.lastSeq !== undefined && seq > this.lastSeq;
425
+ if (this.generation !== generation) {
426
+ this.changes.clear();
427
+ this.generation = generation;
428
+ this.floor = seq;
429
+ }
430
+ else {
431
+ this.floor = Math.max(this.floor ?? seq, seq);
432
+ }
433
+ this.lastSeq = seq;
434
+ return { generationChanged, missedFrames };
435
+ }
436
+ /**
437
+ * Record one stream change in sequence order. Set `retain: false` once the store is loaded and
438
+ * no snapshot refresh is in flight so applied frames are not retained for the connection lifetime
439
+ * (overlay entries are kept only while a refresh is pending/in-flight or on a gap).
440
+ */
441
+ record(change, options = {}) {
442
+ if (this.generation === undefined)
443
+ return { accepted: false, gap: false };
444
+ if (this.lastSeq !== undefined && change.seq <= this.lastSeq) {
445
+ return { accepted: false, gap: false };
446
+ }
447
+ const gap = this.lastSeq !== undefined && change.seq > this.lastSeq + 1;
448
+ if (this.floor === undefined || gap) {
449
+ this.floor = change.seq - 1;
450
+ }
451
+ this.lastSeq = change.seq;
452
+ const retain = (options.retain ?? true) || gap;
453
+ if (retain) {
454
+ const id = change.type === 'run' ? change.run.id : change.id;
455
+ const key = hostRowKey(change.project, id);
456
+ const isWorker = change.type === 'run' && change.run.delegation?.role === 'worker';
457
+ const held = this.changes.get(key);
458
+ if (!isWorker || held !== undefined) {
459
+ if (!held || held.seq < change.seq) {
460
+ this.changes.set(key, change);
461
+ }
462
+ }
463
+ }
464
+ return { accepted: true, gap };
465
+ }
466
+ /** Drop a previously recorded frame once applied to a loaded store with no refresh in flight. */
467
+ forget(change) {
468
+ const id = change.type === 'run' ? change.run.id : change.id;
469
+ const key = hostRowKey(change.project, id);
470
+ const held = this.changes.get(key);
471
+ if (held && held.seq <= change.seq) {
472
+ this.changes.delete(key);
473
+ }
474
+ this.floor = Math.max(this.floor ?? change.seq, change.seq);
475
+ }
476
+ dropProject(project) {
477
+ for (const [key, entry] of this.changes) {
478
+ if (entry.project === project)
479
+ this.changes.delete(key);
480
+ }
481
+ }
482
+ /**
483
+ * Replay overlay frames newer than `snapshot.eventSeq` onto `store` and prune covered frames.
484
+ * Returns whether a follow-up snapshot refresh is needed (because the snapshot predates `floor`
485
+ * or a replayed frame hit a truncated boundary), and whether store content changed.
486
+ */
487
+ reconcileSnapshot(store, snapshot) {
488
+ if (this.generation !== undefined && snapshot.generation !== this.generation) {
489
+ return { generationMismatch: true, needsRefresh: true, changed: false };
490
+ }
491
+ const missed = this.floor !== undefined && snapshot.eventSeq < this.floor;
492
+ let changed = isPreparedHostSnapshot(snapshot)
493
+ ? store.replaceFromPrepared(snapshot)
494
+ : store.replaceFromSnapshot(snapshot);
495
+ const newer = [];
496
+ for (const [key, entry] of this.changes) {
497
+ if (entry.seq <= snapshot.eventSeq) {
498
+ this.changes.delete(key);
499
+ }
500
+ else {
501
+ newer.push(entry);
502
+ }
503
+ }
504
+ newer.sort((a, b) => a.seq - b.seq);
505
+ let reconcile = missed;
506
+ let maxSeq = snapshot.eventSeq;
507
+ for (const change of newer) {
508
+ const applied = store.applyChange(change);
509
+ if (applied.changed)
510
+ changed = true;
511
+ if (applied.reconcile)
512
+ reconcile = true;
513
+ if (change.seq > maxSeq)
514
+ maxSeq = change.seq;
515
+ }
516
+ if (!reconcile) {
517
+ this.changes.clear();
518
+ this.floor = Math.max(this.floor ?? maxSeq, maxSeq);
519
+ }
520
+ else if (!missed) {
521
+ this.floor = snapshot.eventSeq;
522
+ }
523
+ return { generationMismatch: false, needsRefresh: reconcile, changed };
524
+ }
525
+ }
526
+ function isPreparedHostSnapshot(snapshot) {
527
+ return snapshot.runs.length === 0 || 'hostId' in snapshot.runs[0];
528
+ }
529
+ export const DEFAULT_SSE_MAX_EVENT_BYTES = 16 * 1024 * 1024;
530
+ /**
531
+ * Incremental WHATWG Server-Sent Events parser with bounded UTF-8 wire-byte buffering (`maxEventBytes` memory guard).
532
+ * When a blank line ends with `\r` as the last byte of a chunk, that line ending is counted as 2 bytes (as `\r\n`) before dispatch so no frame over `maxEventBytes` is ever dispatched, CR-only delivery stays immediate, and a following `\n` adds zero bytes.
533
+ * As a trade-off, a CR-only frame of exactly `maxEventBytes` bytes whose final `\r` ends a chunk is refused 1 byte early.
534
+ */
535
+ export class SseEventParser {
536
+ decoder = new TextDecoder('utf-8');
537
+ maxEventBytes;
538
+ lineBuffer = '';
539
+ pendingCR = false;
540
+ eventType = '';
541
+ dataLines = [];
542
+ bufferedBytes = 0;
543
+ constructor(maxEventBytes = DEFAULT_SSE_MAX_EVENT_BYTES) {
544
+ this.maxEventBytes = maxEventBytes;
545
+ }
546
+ push(chunk) {
547
+ const text = this.decoder.decode(chunk, { stream: true });
548
+ return this.pushText(text);
549
+ }
550
+ pushText(text) {
551
+ if (text.length === 0)
552
+ return [];
553
+ const events = [];
554
+ let start = 0;
555
+ let i = 0;
556
+ if (this.pendingCR) {
557
+ this.pendingCR = false;
558
+ if (text.length > 0 && text.charCodeAt(0) === 0x0a) {
559
+ if (this.bufferedBytes > 0)
560
+ this.addWireBytes(1);
561
+ start = 1;
562
+ i = 1;
563
+ }
564
+ }
565
+ for (; i < text.length; i += 1) {
566
+ const code = text.charCodeAt(i);
567
+ if (code === 0x0a || code === 0x0d) {
568
+ const segment = text.slice(start, i);
569
+ let delimiterBytes = 1;
570
+ if (code === 0x0d) {
571
+ if (i + 1 < text.length && text.charCodeAt(i + 1) === 0x0a) {
572
+ i += 1;
573
+ delimiterBytes = 2;
574
+ }
575
+ else if (i + 1 === text.length) {
576
+ this.pendingCR = true;
577
+ if (segment.length === 0 && this.lineBuffer.length === 0) {
578
+ delimiterBytes = 2;
579
+ }
580
+ }
581
+ }
582
+ this.appendToLine(segment, delimiterBytes);
583
+ const line = this.lineBuffer;
584
+ this.lineBuffer = '';
585
+ const emitted = this.processLine(line);
586
+ if (emitted)
587
+ events.push(emitted);
588
+ start = i + 1;
589
+ }
590
+ }
591
+ if (start < text.length) {
592
+ this.appendToLine(text.slice(start), 0);
593
+ }
594
+ return events;
595
+ }
596
+ addWireBytes(bytes) {
597
+ if (bytes <= 0)
598
+ return;
599
+ this.bufferedBytes += bytes;
600
+ if (this.bufferedBytes > this.maxEventBytes) {
601
+ throw new Error(`SSE event exceeded ${this.maxEventBytes} byte limit.`);
602
+ }
603
+ }
604
+ appendToLine(segment, delimiterBytes) {
605
+ const wireBytes = (segment.length > 0 ? Buffer.byteLength(segment, 'utf8') : 0) + delimiterBytes;
606
+ this.addWireBytes(wireBytes);
607
+ if (segment.length > 0)
608
+ this.lineBuffer += segment;
609
+ }
610
+ processLine(line) {
611
+ if (line.length === 0) {
612
+ const emitted = this.dataLines.length > 0
613
+ ? { event: this.eventType || 'message', data: this.dataLines.join('\n') }
614
+ : undefined;
615
+ this.eventType = '';
616
+ this.dataLines = [];
617
+ this.bufferedBytes = 0;
618
+ return emitted;
619
+ }
620
+ if (line.startsWith(':'))
621
+ return undefined;
622
+ const colon = line.indexOf(':');
623
+ const field = colon === -1 ? line : line.slice(0, colon);
624
+ let value = colon === -1 ? '' : line.slice(colon + 1);
625
+ if (value.startsWith(' '))
626
+ value = value.slice(1);
627
+ if (field === 'event') {
628
+ this.eventType = value;
629
+ }
630
+ else if (field === 'data') {
631
+ this.dataLines.push(value);
632
+ }
633
+ return undefined;
634
+ }
635
+ }
636
+ const snapshotHeaderSchema = runsIndexResponseSchema.omit({ runs: true });
637
+ export function parseJsonSafe(raw) {
638
+ try {
639
+ return JSON.parse(raw);
640
+ }
641
+ catch {
642
+ return undefined;
643
+ }
644
+ }
645
+ export function parseProjectIdField(rawData) {
646
+ const parsed = parseJsonSafe(rawData);
647
+ return typeof parsed?.id === 'string' && parsed.id.length > 0 ? parsed.id : undefined;
648
+ }
649
+ export function createTimedAbort(parent, timeoutMs) {
650
+ const controller = new AbortController();
651
+ const onParentAbort = () => {
652
+ controller.abort(parent.reason);
653
+ };
654
+ if (parent.aborted) {
655
+ controller.abort(parent.reason);
656
+ return { controller, cleanup: () => undefined };
657
+ }
658
+ parent.addEventListener('abort', onParentAbort, { once: true });
659
+ const timer = setTimeout(() => {
660
+ controller.abort(new DOMException('Host index request timed out.', 'TimeoutError'));
661
+ }, timeoutMs);
662
+ timer.unref();
663
+ return {
664
+ controller,
665
+ cleanup: () => {
666
+ clearTimeout(timer);
667
+ parent.removeEventListener('abort', onParentAbort);
668
+ },
669
+ };
670
+ }
671
+ /**
672
+ * Parse and validate a host snapshot in bounded slices (`sliceSize` rows per turn), yielding with
673
+ * `setImmediate` between slices so a 20,000-row snapshot never stalls the main server event loop.
674
+ */
675
+ export async function parseHostSnapshotInSlices(hostId, text, sliceSize, isCancelled) {
676
+ const decoded = parseJsonSafe(text);
677
+ if (typeof decoded !== 'object' || decoded === null || !Array.isArray(decoded.runs)) {
678
+ return undefined;
679
+ }
680
+ const header = snapshotHeaderSchema.safeParse(decoded);
681
+ if (!header.success)
682
+ return undefined;
683
+ const rawRuns = decoded.runs;
684
+ const stamped = [];
685
+ for (let offset = 0; offset < rawRuns.length; offset += sliceSize) {
686
+ if (isCancelled())
687
+ return undefined;
688
+ const end = Math.min(rawRuns.length, offset + sliceSize);
689
+ for (let i = offset; i < end; i += 1) {
690
+ const parsedRow = runIndexEntrySchema.safeParse(rawRuns[i]);
691
+ if (!parsedRow.success)
692
+ return undefined;
693
+ if (parsedRow.data.delegation?.role === 'worker')
694
+ continue;
695
+ stamped.push({ ...parsedRow.data, hostId });
696
+ }
697
+ if (end < rawRuns.length) {
698
+ await new Promise((resolve) => setImmediate(resolve));
699
+ }
700
+ }
701
+ if (isCancelled())
702
+ return undefined;
703
+ return {
704
+ runs: stamped,
705
+ referenceStatuses: header.data.referenceStatuses,
706
+ perProjectLimit: header.data.perProjectLimit,
707
+ truncated: header.data.truncated,
708
+ generation: header.data.generation,
709
+ eventSeq: header.data.eventSeq,
710
+ };
711
+ }
712
+ /** Linear k-way merge of already newest-first host stores (no full re-sort). */
713
+ export function mergeSortedHostStores(stores) {
714
+ const lists = [];
715
+ let total = 0;
716
+ for (const store of stores) {
717
+ const sorted = store.getSortedRuns();
718
+ if (sorted.length > 0) {
719
+ lists.push(sorted);
720
+ total += sorted.length;
721
+ }
722
+ }
723
+ if (lists.length === 0)
724
+ return [];
725
+ if (lists.length === 1)
726
+ return [...lists[0]];
727
+ const merged = [];
728
+ const cursors = new Int32Array(lists.length);
729
+ const kCount = lists.length;
730
+ for (let out = 0; out < total; out += 1) {
731
+ let bestIdx = -1;
732
+ let bestCreatedAt = '';
733
+ for (let k = 0; k < kCount; k += 1) {
734
+ const list = lists[k];
735
+ const pos = cursors[k];
736
+ if (pos < list.length) {
737
+ const ts = list[pos].createdAt;
738
+ if (bestIdx === -1 || ts > bestCreatedAt) {
739
+ bestIdx = k;
740
+ bestCreatedAt = ts;
741
+ }
742
+ }
743
+ }
744
+ const winnerPos = cursors[bestIdx];
745
+ merged.push(lists[bestIdx][winnerPos]);
746
+ cursors[bestIdx] = winnerPos + 1;
747
+ }
748
+ return merged;
749
+ }
750
+ export function clearTimer(timer) {
751
+ if (timer !== undefined)
752
+ clearTimeout(timer);
753
+ return undefined;
754
+ }
755
+ export function parseWorkspaceSseEvent(sse) {
756
+ switch (sse.event) {
757
+ case 'ready': {
758
+ const parsed = workspaceReadyEventSchema.safeParse(parseJsonSafe(sse.data));
759
+ if (!parsed.success)
760
+ return { type: 'invalid-ready' };
761
+ return { type: 'ready', generation: parsed.data.generation, seq: parsed.data.seq };
762
+ }
763
+ case 'run-summary': {
764
+ const parsed = workspaceRunSummaryEventSchema.safeParse(parseJsonSafe(sse.data));
765
+ if (!parsed.success)
766
+ return { type: 'ignore' };
767
+ return {
768
+ type: 'change',
769
+ change: { type: 'run', project: parsed.data.project, seq: parsed.data.seq, run: parsed.data.run },
770
+ };
771
+ }
772
+ case 'run-deleted': {
773
+ const parsed = workspaceRunDeletedEventSchema.safeParse(parseJsonSafe(sse.data));
774
+ if (!parsed.success)
775
+ return { type: 'ignore' };
776
+ return {
777
+ type: 'change',
778
+ change: { type: 'deleted', project: parsed.data.project, seq: parsed.data.seq, id: parsed.data.id },
779
+ };
780
+ }
781
+ case 'usage': {
782
+ const parsed = workspaceUsageEventSchema.safeParse(parseJsonSafe(sse.data));
783
+ if (!parsed.success)
784
+ return { type: 'ignore' };
785
+ return { type: 'usage', project: parsed.data.project, usage: parsed.data.usage };
786
+ }
787
+ case 'project-removed': {
788
+ const projectId = parseProjectIdField(sse.data);
789
+ return projectId ? { type: 'project-removed', projectId } : { type: 'ignore' };
790
+ }
791
+ case 'project-added':
792
+ case 'project-ready':
793
+ return { type: 'project-refresh' };
794
+ default:
795
+ return { type: 'ignore' };
796
+ }
797
+ }
798
+ //# sourceMappingURL=runs-index-patch.js.map