glimmervoid 0.52.3-next.810 → 0.52.3-next.813

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 (160) hide show
  1. package/dist/bin/glimmervoid.js +18 -18
  2. package/dist/chunks/{adapters-CegV3T42.js → adapters-Cm8OfxJ-.js} +1 -1
  3. package/dist/chunks/{adapters-Bg-l7NBf.js → adapters-ZSls_tCx.js} +7 -7
  4. package/dist/chunks/agent-api-cli-BjMX0BWV.js +1 -0
  5. package/dist/chunks/{agent-api-cli-BkLD2K18.js → agent-api-cli-gDkCS2Sc.js} +3 -3
  6. package/dist/chunks/{agent-api-core-CADmSdvT.js → agent-api-core-BEroy0sS.js} +3 -3
  7. package/dist/chunks/{agent-setup-cli-D7XCboR8.js → agent-setup-cli-QUJ_PnAy.js} +1 -1
  8. package/dist/chunks/{config-CdUCPp52.js → config-CkV0C-0V.js} +2 -2
  9. package/dist/chunks/config-store-D_mx40Nb.js +1 -0
  10. package/dist/chunks/{config-store-RJTZlSL9.js → config-store-TJra5h8r.js} +3 -3
  11. package/dist/chunks/{control-messages-Cx_1p9iz.js → control-messages-BZms3f5z.js} +10 -12
  12. package/dist/chunks/{grok-DA9Dmmu3.js → grok-CR-AgrA2.js} +1 -1
  13. package/dist/chunks/{host-cli-CbCKHk5C.js → host-cli-BkPZk9qB.js} +3 -3
  14. package/dist/chunks/{host-registry-core-Cj9x_2Yr.js → host-registry-core-B9QtetVh.js} +1 -1
  15. package/dist/chunks/{kimi-Ck2t9UVT.js → kimi-Bns2rsve.js} +2 -2
  16. package/dist/chunks/kimi-DDuEOC7-.js +1 -0
  17. package/dist/chunks/{main-CcKJjRfc.js → main-D6uGScyA.js} +682 -904
  18. package/dist/chunks/{pack-agent-D9TcEpR3.js → pack-agent-BEsplgwO.js} +5 -5
  19. package/dist/chunks/{pack-bridge-BKP_4o4G.js → pack-bridge-BoiZXSUH.js} +1 -1
  20. package/dist/chunks/{pack-files-Cquc-WhV.js → pack-files-D-rDdLxB.js} +3 -3
  21. package/dist/chunks/{packs-cli-B8AP2zKu.js → packs-cli-awbr6FRB.js} +5 -5
  22. package/dist/chunks/{pair-cli-DJWfqOj3.js → pair-cli-BwYyx_rg.js} +2 -2
  23. package/dist/chunks/{pr-flows-cli-NUyOxO9a.js → pr-flows-cli-mCpN_Onm.js} +6 -6
  24. package/dist/chunks/{pr-flows-core-C5EdQcdl.js → pr-flows-core-BobD-dTi.js} +72 -30
  25. package/dist/chunks/{pr-flows-external-Bwwtnh-u.js → pr-flows-external-C4aO8Cz-.js} +3 -3
  26. package/dist/chunks/{remote-config-BxXgPLrF.js → remote-config-CldHW_6m.js} +1 -1
  27. package/dist/chunks/{session-C0cPFaQs.js → session-BvcMZ7BH.js} +10 -2
  28. package/dist/chunks/settings-cli-B25LN6Jx.js +1 -0
  29. package/dist/chunks/{settings-cli-Ce4-Yr_8.js → settings-cli-BnFILc3V.js} +5 -5
  30. package/dist/chunks/{settings-readout-core-O6-uLAi3.js → settings-readout-core-CvAedAf3.js} +2 -2
  31. package/dist/chunks/{spawn-env-CapiuFtq.js → spawn-env-C28Mf5v_.js} +1 -1
  32. package/dist/chunks/{ssh-sign-cli-zx7cdsL_.js → ssh-sign-cli-C0dooqO3.js} +2 -2
  33. package/dist/chunks/watch-cli-B_eClujk.js +949 -0
  34. package/dist/chunks/{watchee-settings-CjkenTD8.js → watchee-settings-Cn-9FKNw.js} +668 -69
  35. package/dist/chunks/{whiteboard-svg-core-CFm2oj-T.js → whiteboard-svg-core-ChuwroP9.js} +1 -1
  36. package/dist/client/assets/{action-status-CgUlY1YC.js → action-status-BbtDsUki.js} +1 -1
  37. package/dist/client/assets/action-status-BbtDsUki.js.br +0 -0
  38. package/dist/client/assets/{agent-mark---dx0kxc.js → agent-mark-B_oODF_J.js} +1 -1
  39. package/dist/client/assets/agent-mark-B_oODF_J.js.br +0 -0
  40. package/dist/client/assets/{arena-panel-CUfSZv_I.js → arena-panel-DVY5odKK.js} +2 -2
  41. package/dist/client/assets/arena-panel-DVY5odKK.js.br +0 -0
  42. package/dist/client/assets/{benchmark-panel-BJeO8SUk.js → benchmark-panel-Bx9vigxf.js} +1 -1
  43. package/dist/client/assets/benchmark-panel-Bx9vigxf.js.br +0 -0
  44. package/dist/client/assets/{boards-view-BsiGwzeZ.js → boards-view-BHEKyM11.js} +1 -1
  45. package/dist/client/assets/boards-view-BHEKyM11.js.br +0 -0
  46. package/dist/client/assets/button-5BtNNKgp.js +1 -0
  47. package/dist/client/assets/button-5BtNNKgp.js.br +0 -0
  48. package/dist/client/assets/{card-actions-D7SrqW9f.js → card-actions-Bf3QxhvD.js} +1 -1
  49. package/dist/client/assets/{card-registry-DdJYrnbX.js → card-registry-DKWiYa6i.js} +1 -1
  50. package/dist/client/assets/card-registry-DKWiYa6i.js.br +0 -0
  51. package/dist/client/assets/{community-panel-DyUUTirE.js → community-panel-JiOh829l.js} +1 -1
  52. package/dist/client/assets/community-panel-JiOh829l.js.br +0 -0
  53. package/dist/client/assets/{control-ws-C9XYFFfj.js → control-ws-yLgkhscU.js} +1 -1
  54. package/dist/client/assets/control-ws-yLgkhscU.js.br +0 -0
  55. package/dist/client/assets/{dialogs-C73Q7kRh.js → dialogs-DExVx25q.js} +1 -1
  56. package/dist/client/assets/dialogs-DExVx25q.js.br +0 -0
  57. package/dist/client/assets/{doc-editor-ui-BpAYQZti.js → doc-editor-ui-CbyajNKy.js} +1 -1
  58. package/dist/client/assets/doc-editor-ui-CbyajNKy.js.br +0 -0
  59. package/dist/client/assets/{feature-hint-DR9DbsF6.js → feature-hint-DgTIhWye.js} +1 -1
  60. package/dist/client/assets/feature-hint-DgTIhWye.js.br +0 -0
  61. package/dist/client/assets/{first-run-checklist-CdEsX89N.js → first-run-checklist-DTdRfGmD.js} +1 -1
  62. package/dist/client/assets/first-run-checklist-DTdRfGmD.js.br +0 -0
  63. package/dist/client/assets/{hooks-panel-DjzkfX42.js → hooks-panel-CaEZNndU.js} +1 -1
  64. package/dist/client/assets/hooks-panel-CaEZNndU.js.br +0 -0
  65. package/dist/client/assets/{index-BbMMfZ-e.js → index-CsCIzYnc.js} +5 -5
  66. package/dist/client/assets/index-CsCIzYnc.js.br +0 -0
  67. package/dist/client/assets/{issues-panel-L44tTW8x.js → issues-panel-DC6QuTMT.js} +1 -1
  68. package/dist/client/assets/issues-panel-DC6QuTMT.js.br +0 -0
  69. package/dist/client/assets/{lane-read-token-step-BX3-5r1Z.js → lane-read-token-step-DIKcunI3.js} +1 -1
  70. package/dist/client/assets/lane-read-token-step-DIKcunI3.js.br +0 -0
  71. package/dist/client/assets/{menu-Dazd3nW4.js → menu-B0zH_ttc.js} +1 -1
  72. package/dist/client/assets/menu-B0zH_ttc.js.br +0 -0
  73. package/dist/client/assets/{modal-B4PM2625.js → modal-Blqoecg2.js} +1 -1
  74. package/dist/client/assets/modal-Blqoecg2.js.br +0 -0
  75. package/dist/client/assets/{my-prs-panel-U4DkNVLl.js → my-prs-panel-BPAiG9R1.js} +1 -1
  76. package/dist/client/assets/my-prs-panel-BPAiG9R1.js.br +0 -0
  77. package/dist/client/assets/{nyan-cat-COn-mH4R.js → nyan-cat-BP8yrw3D.js} +1 -1
  78. package/dist/client/assets/nyan-cat-BP8yrw3D.js.br +0 -0
  79. package/dist/client/assets/{phone-shell-50_qMdWC.js → phone-shell-BLU0zhrd.js} +1 -1
  80. package/dist/client/assets/phone-shell-BLU0zhrd.js.br +0 -0
  81. package/dist/client/assets/{plan-face-hmsHFcdA.js → plan-face-BPobB1Lo.js} +1 -1
  82. package/dist/client/assets/plan-face-BPobB1Lo.js.br +0 -0
  83. package/dist/client/assets/{plan-render-ZZG0vbhY.js → plan-render-C5lxEWBl.js} +1 -1
  84. package/dist/client/assets/plan-render-C5lxEWBl.js.br +0 -0
  85. package/dist/client/assets/{pr-queue-columns-B5suDlYb.js → pr-queue-columns-CcdMFcBt.js} +1 -1
  86. package/dist/client/assets/pr-queue-columns-CcdMFcBt.js.br +0 -0
  87. package/dist/client/assets/{pr-status-icon-2dbYpTqp.js → pr-status-icon-D7rv3sS4.js} +1 -1
  88. package/dist/client/assets/pr-status-icon-D7rv3sS4.js.br +0 -0
  89. package/dist/client/assets/{radar-panel-BI1lBZDe.js → radar-panel-D5h01_Bn.js} +1 -1
  90. package/dist/client/assets/radar-panel-D5h01_Bn.js.br +0 -0
  91. package/dist/client/assets/{repo-roots-adder-Bf7mQo3-.js → repo-roots-adder-ME6scsNf.js} +1 -1
  92. package/dist/client/assets/repo-roots-adder-ME6scsNf.js.br +0 -0
  93. package/dist/client/assets/{resume-dialog-BA-hMjm5.js → resume-dialog-DKLEjjEN.js} +1 -1
  94. package/dist/client/assets/resume-dialog-DKLEjjEN.js.br +0 -0
  95. package/dist/client/assets/{review-queue-panel-CkHzEJ3Y.js → review-queue-panel-RgttbaLn.js} +1 -1
  96. package/dist/client/assets/review-queue-panel-RgttbaLn.js.br +0 -0
  97. package/dist/client/assets/{session-actions-BNiEWwbs.js → session-actions-CcRSsbu2.js} +2 -2
  98. package/dist/client/assets/session-actions-CcRSsbu2.js.br +0 -0
  99. package/dist/client/assets/{session-row-BnV-B0fL.js → session-row-D15uVSu_.js} +1 -1
  100. package/dist/client/assets/session-row-D15uVSu_.js.br +0 -0
  101. package/dist/client/assets/{session-tick-DkL0Rymq.js → session-tick-BujhndlK.js} +1 -1
  102. package/dist/client/assets/session-tick-BujhndlK.js.br +0 -0
  103. package/dist/client/assets/{settings-panel-B_T0712G.js → settings-panel-9Dn5fb9d.js} +2 -2
  104. package/dist/client/assets/settings-panel-9Dn5fb9d.js.br +0 -0
  105. package/dist/client/assets/{setup-step-C6Me6J42.js → setup-step-DWDiLWhL.js} +1 -1
  106. package/dist/client/assets/setup-step-DWDiLWhL.js.br +0 -0
  107. package/dist/client/assets/{trace-panel-BudhU9Bv.js → trace-panel-5NH6yM4d.js} +1 -1
  108. package/dist/client/assets/trace-panel-5NH6yM4d.js.br +0 -0
  109. package/dist/client/assets/{usage-panel-DHoAftpA.js → usage-panel-DVYzxmFJ.js} +1 -1
  110. package/dist/client/assets/usage-panel-DVYzxmFJ.js.br +0 -0
  111. package/dist/client/assets/{your-day-tip-Cpzaxh1I.js → your-day-tip-_5L4i0k0.js} +1 -1
  112. package/dist/client/assets/your-day-tip-_5L4i0k0.js.br +0 -0
  113. package/dist/client/index.html +13 -13
  114. package/dist/client/index.html.br +0 -0
  115. package/dist/server/index.js +1 -1
  116. package/package.json +1 -1
  117. package/dist/chunks/agent-api-cli-BNz1cOp2.js +0 -1
  118. package/dist/chunks/config-store-BG2_KF9v.js +0 -1
  119. package/dist/chunks/kimi-CZSsNDJi.js +0 -1
  120. package/dist/chunks/settings-cli-DdSs9MOa.js +0 -1
  121. package/dist/chunks/watch-cli-CMxNbyZx.js +0 -484
  122. package/dist/client/assets/action-status-CgUlY1YC.js.br +0 -0
  123. package/dist/client/assets/agent-mark---dx0kxc.js.br +0 -0
  124. package/dist/client/assets/arena-panel-CUfSZv_I.js.br +0 -0
  125. package/dist/client/assets/benchmark-panel-BJeO8SUk.js.br +0 -0
  126. package/dist/client/assets/boards-view-BsiGwzeZ.js.br +0 -0
  127. package/dist/client/assets/button-DOiRqykb.js +0 -1
  128. package/dist/client/assets/button-DOiRqykb.js.br +0 -0
  129. package/dist/client/assets/card-registry-DdJYrnbX.js.br +0 -0
  130. package/dist/client/assets/community-panel-DyUUTirE.js.br +0 -0
  131. package/dist/client/assets/control-ws-C9XYFFfj.js.br +0 -0
  132. package/dist/client/assets/dialogs-C73Q7kRh.js.br +0 -0
  133. package/dist/client/assets/doc-editor-ui-BpAYQZti.js.br +0 -0
  134. package/dist/client/assets/feature-hint-DR9DbsF6.js.br +0 -0
  135. package/dist/client/assets/first-run-checklist-CdEsX89N.js.br +0 -0
  136. package/dist/client/assets/hooks-panel-DjzkfX42.js.br +0 -0
  137. package/dist/client/assets/index-BbMMfZ-e.js.br +0 -0
  138. package/dist/client/assets/issues-panel-L44tTW8x.js.br +0 -0
  139. package/dist/client/assets/lane-read-token-step-BX3-5r1Z.js.br +0 -0
  140. package/dist/client/assets/menu-Dazd3nW4.js.br +0 -0
  141. package/dist/client/assets/modal-B4PM2625.js.br +0 -0
  142. package/dist/client/assets/my-prs-panel-U4DkNVLl.js.br +0 -0
  143. package/dist/client/assets/nyan-cat-COn-mH4R.js.br +0 -0
  144. package/dist/client/assets/phone-shell-50_qMdWC.js.br +0 -0
  145. package/dist/client/assets/plan-face-hmsHFcdA.js.br +0 -0
  146. package/dist/client/assets/plan-render-ZZG0vbhY.js.br +0 -0
  147. package/dist/client/assets/pr-queue-columns-B5suDlYb.js.br +0 -0
  148. package/dist/client/assets/pr-status-icon-2dbYpTqp.js.br +0 -0
  149. package/dist/client/assets/radar-panel-BI1lBZDe.js.br +0 -0
  150. package/dist/client/assets/repo-roots-adder-Bf7mQo3-.js.br +0 -0
  151. package/dist/client/assets/resume-dialog-BA-hMjm5.js.br +0 -0
  152. package/dist/client/assets/review-queue-panel-CkHzEJ3Y.js.br +0 -0
  153. package/dist/client/assets/session-actions-BNiEWwbs.js.br +0 -0
  154. package/dist/client/assets/session-row-BnV-B0fL.js.br +0 -0
  155. package/dist/client/assets/session-tick-DkL0Rymq.js.br +0 -0
  156. package/dist/client/assets/settings-panel-B_T0712G.js.br +0 -0
  157. package/dist/client/assets/setup-step-C6Me6J42.js.br +0 -0
  158. package/dist/client/assets/trace-panel-BudhU9Bv.js.br +0 -0
  159. package/dist/client/assets/usage-panel-DHoAftpA.js.br +0 -0
  160. package/dist/client/assets/your-day-tip-Cpzaxh1I.js.br +0 -0
@@ -0,0 +1,949 @@
1
+ import { $i as SENT_EVENTS_FILENAME, C as workflowRepoWatchNames, G as createPrGh, S as workflowPrFromGithubPr, X as createGithubStorePoller, aa as classifyInboxReply, ca as describeRefusal, ga as WatcherJobAck, jn as orgSearchPlans, kt as mergedSinceDate, n as readWatcheeSettings, oa as createPingJob, r as watcherHomeDir, ra as createTickLoop, sa as deliveryRetryDelayMs, t as readJsonFileOrUndefined, ua as parseInboxUrl } from "./watchee-settings-Cn-9FKNw.js";
2
+ import { n as isRecord } from "./coerce-D6vRlIGO.js";
3
+ import { r as errorMessage } from "./text-BDF4aFhQ.js";
4
+ import { u as writeJsonAtomic } from "./json-file-BkbEyRoH.js";
5
+ import { i as DEFAULT_TIMER_FNS, t as canonicalizePath } from "./canonical-paths-tdQPG3Kv.js";
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import crypto from "node:crypto";
9
+ // cloud/watcher/job-inbox-client.ts
10
+ var REQUEST_TIMEOUT_MS = 1e4;
11
+ function describeUnreachable(error) {
12
+ const cause = error instanceof Error && isRecord(error.cause) ? error.cause : null;
13
+ return `inbox unreachable: ${(cause !== null && typeof cause.code === "string" ? cause.code : null) ?? errorMessage(error)}`;
14
+ }
15
+ function replyErrorOf(replyBody) {
16
+ if (!isRecord(replyBody) || typeof replyBody.error !== "string") return null;
17
+ return replyBody.error;
18
+ }
19
+ function parseReplyText(text) {
20
+ if (text === "") return null;
21
+ try {
22
+ return JSON.parse(text);
23
+ } catch {
24
+ return null;
25
+ }
26
+ }
27
+ function asError(error) {
28
+ return error instanceof Error ? error : new Error(String(error));
29
+ }
30
+ async function postJobOnce(jobsUrl, token, job) {
31
+ try {
32
+ const response = await fetch(jobsUrl, {
33
+ method: "POST",
34
+ headers: {
35
+ authorization: `Bearer ${token}`,
36
+ "content-type": "application/json"
37
+ },
38
+ body: JSON.stringify(job),
39
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
40
+ });
41
+ return {
42
+ status: response.status,
43
+ replyBody: parseReplyText(await response.text())
44
+ };
45
+ } catch (error) {
46
+ return asError(error);
47
+ }
48
+ }
49
+ function waitMs(durationMs) {
50
+ return new Promise((resolve) => setTimeout(resolve, durationMs));
51
+ }
52
+ async function sendJob({ jobsUrl, token, job, maxAttempts }) {
53
+ let lastFailureReason = "no delivery attempt was made";
54
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
55
+ if (attempt > 1) await waitMs(deliveryRetryDelayMs(attempt - 1, Math.random));
56
+ const reply = await postJobOnce(jobsUrl, token, job);
57
+ if (reply instanceof Error) {
58
+ lastFailureReason = describeUnreachable(reply);
59
+ continue;
60
+ }
61
+ const { status, replyBody } = reply;
62
+ const outcome = classifyInboxReply(status);
63
+ if (outcome === "retry") {
64
+ lastFailureReason = describeRefusal(status, replyErrorOf(replyBody));
65
+ continue;
66
+ }
67
+ if (outcome === "refused") return {
68
+ ok: false,
69
+ reason: describeRefusal(status, replyErrorOf(replyBody))
70
+ };
71
+ const ack = WatcherJobAck.safeParse(replyBody);
72
+ if (!ack.success || ack.data.jobId !== job.jobId) return {
73
+ ok: false,
74
+ reason: "the inbox sent a malformed ack"
75
+ };
76
+ return {
77
+ ok: true,
78
+ ack: ack.data
79
+ };
80
+ }
81
+ return {
82
+ ok: false,
83
+ reason: lastFailureReason
84
+ };
85
+ }
86
+ // cloud/watchees/github-store-watchee.ts
87
+ function createWatcheeGithubStore({ watcherHome, now, log }) {
88
+ return createGithubStorePoller({
89
+ github: createPrGh(watcherHome),
90
+ now,
91
+ isDashboardConnected: () => false,
92
+ exclusive: async (work) => work(),
93
+ setTimeoutFn: DEFAULT_TIMER_FNS.setTimeoutFn,
94
+ clearTimeoutFn: DEFAULT_TIMER_FNS.clearTimeoutFn,
95
+ log
96
+ });
97
+ }
98
+ function observedPayloadEventKey(payload, intervalStartMs) {
99
+ const { observedAt: _observedAt, ...observed } = payload;
100
+ return `${intervalStartMs}:${crypto.createHash("sha256").update(JSON.stringify(observed)).digest("hex")}`;
101
+ }
102
+ // cloud/watchees/issues/issues-listing.ts
103
+ var PAGE_SIZE = 100;
104
+ var MAX_LISTED_PAGES = Math.ceil(300 / PAGE_SIZE);
105
+ var PENDING_PULL_REQUEST_RECHECK_EVERY_LISTS = 6;
106
+ function hasPendingPullRequest(pullRequests) {
107
+ return pullRequests.some((pullRequest) => pullRequest.state === "open" || pullRequest.state === "draft");
108
+ }
109
+ function createIssuesListing({ store, now }) {
110
+ const pagesByPath = /* @__PURE__ */ new Map();
111
+ const pullRequestsByIssueKey = /* @__PURE__ */ new Map();
112
+ let viewer = null;
113
+ const searchedSourceKeys = /* @__PURE__ */ new Set();
114
+ let listCount = 0;
115
+ async function readPage(pagePath) {
116
+ const cachedPage = pagesByPath.get(pagePath);
117
+ const response = await store.requestIssuePage(pagePath, cachedPage?.etag ?? null, "no-wait");
118
+ if (response.isRateLimited) return {
119
+ kind: "rate-limited",
120
+ waitMs: response.waitMs
121
+ };
122
+ const page = response.value;
123
+ if (page.kind === "unchanged" && cachedPage) return cachedPage;
124
+ if (page.kind === "error") return {
125
+ kind: "failed",
126
+ reason: page.message
127
+ };
128
+ if (page.kind !== "ok") return {
129
+ kind: "failed",
130
+ reason: `GitHub answered an unasked-for 304 for ${pagePath}`
131
+ };
132
+ const readPage = {
133
+ etag: page.etag ?? "",
134
+ issues: page.issues,
135
+ nextPath: page.nextPath
136
+ };
137
+ if (page.etag) pagesByPath.set(pagePath, readPage);
138
+ return readPage;
139
+ }
140
+ async function listPages(firstPath) {
141
+ const issues = [];
142
+ let pagePath = firstPath;
143
+ for (let pageCount = 0; pagePath !== null && pageCount < MAX_LISTED_PAGES && issues.length < 300; pageCount += 1) {
144
+ const page = await readPage(pagePath);
145
+ if ("kind" in page) return page;
146
+ issues.push(...page.issues);
147
+ pagePath = page.nextPath;
148
+ }
149
+ if (!(pagePath === null || issues.length >= 300)) return { kind: "needs-search" };
150
+ return {
151
+ kind: "listed",
152
+ issues: issues.slice(0, 300),
153
+ isComplete: true
154
+ };
155
+ }
156
+ async function searchSource(query, isCapAuthoritative) {
157
+ const response = await store.requestIssueSearch(query, "no-wait");
158
+ if (response.isRateLimited) return {
159
+ kind: "rate-limited",
160
+ waitMs: response.waitMs
161
+ };
162
+ const searched = response.value;
163
+ if (!searched.ok) return {
164
+ kind: "failed",
165
+ reason: searched.error || "issue search failed"
166
+ };
167
+ const issues = searched.items.filter((issue) => issue.state === "open");
168
+ const isComplete = isCapAuthoritative || searched.isComplete && issues.length <= 300;
169
+ return {
170
+ kind: "listed",
171
+ issues: issues.slice(0, 300),
172
+ isComplete
173
+ };
174
+ }
175
+ async function listOrSearch(sourceKey, firstPath, searchQuery, isCapAuthoritative) {
176
+ if (!searchedSourceKeys.has(sourceKey)) {
177
+ const listing = await listPages(firstPath);
178
+ if (listing.kind !== "needs-search") return listing;
179
+ searchedSourceKeys.add(sourceKey);
180
+ }
181
+ return searchSource(searchQuery, isCapAuthoritative);
182
+ }
183
+ async function listSource(listed) {
184
+ if (listed.source === "project") return listOrSearch(`project:${listed.repo.toLowerCase()}`, `repos/${listed.repo}/issues?state=open&sort=updated&direction=desc&per_page=${PAGE_SIZE}`, `repo:${listed.repo} is:issue is:open`, true);
185
+ if (listed.source === "me") return listOrSearch("me", `issues?filter=assigned&state=open&sort=updated&direction=desc&per_page=${PAGE_SIZE}`, "is:issue is:open assignee:@me archived:false", false);
186
+ return searchSource(`is:issue is:open team:${listed.team} archived:false`, false);
187
+ }
188
+ async function refreshPullRequests(issues) {
189
+ const isPendingRecheck = listCount % PENDING_PULL_REQUEST_RECHECK_EVERY_LISTS === 0;
190
+ const listedKeys = new Set(issues.map((issue) => issue.key.toLowerCase()));
191
+ for (const issueKey of pullRequestsByIssueKey.keys()) if (!listedKeys.has(issueKey)) pullRequestsByIssueKey.delete(issueKey);
192
+ const dueIssues = issues.filter((issue) => {
193
+ const cached = pullRequestsByIssueKey.get(issue.key.toLowerCase());
194
+ return !cached || cached.updatedAt !== issue.updatedAt || isPendingRecheck && hasPendingPullRequest(cached.pullRequests);
195
+ });
196
+ if (dueIssues.length === 0) return;
197
+ const response = await store.requestIssueLinkedPullRequests(dueIssues.map((issue) => issue.key), "no-wait");
198
+ if (response.isRateLimited) return;
199
+ for (const issue of dueIssues) {
200
+ const pullRequests = response.value.get(issue.key);
201
+ if (pullRequests) pullRequestsByIssueKey.set(issue.key.toLowerCase(), {
202
+ updatedAt: issue.updatedAt,
203
+ pullRequests
204
+ });
205
+ }
206
+ }
207
+ function listedIssue({ state: _state, ...issue }) {
208
+ const cached = pullRequestsByIssueKey.get(issue.key.toLowerCase());
209
+ return cached ? {
210
+ ...issue,
211
+ pullRequests: cached.pullRequests
212
+ } : issue;
213
+ }
214
+ async function list(settings) {
215
+ const viewerRead = viewer === null ? await store.requestViewer("no-wait") : {
216
+ isRateLimited: false,
217
+ value: viewer
218
+ };
219
+ if (viewerRead.isRateLimited) return {
220
+ ok: false,
221
+ reason: "GitHub rate limit",
222
+ retryAfterMs: viewerRead.waitMs
223
+ };
224
+ viewer = viewerRead.value;
225
+ if (viewer === null) return {
226
+ ok: false,
227
+ reason: "gh is not signed in"
228
+ };
229
+ const listedViewer = viewer;
230
+ const sources = [
231
+ ...settings.projectRepos.map((repo) => ({
232
+ source: "project",
233
+ repo
234
+ })),
235
+ { source: "me" },
236
+ ...settings.teams.map((team) => ({
237
+ source: "team",
238
+ team
239
+ }))
240
+ ];
241
+ const listings = [];
242
+ for (const listed of sources) {
243
+ const listing = await listSource(listed);
244
+ if (listing.kind === "rate-limited") return {
245
+ ok: false,
246
+ reason: "GitHub rate limit",
247
+ retryAfterMs: listing.waitMs
248
+ };
249
+ if (listing.kind === "failed") listings.push({
250
+ listed,
251
+ issues: [],
252
+ isComplete: false,
253
+ error: listing.reason
254
+ });
255
+ if (listing.kind === "listed") listings.push({
256
+ listed,
257
+ issues: listing.issues,
258
+ isComplete: listing.isComplete,
259
+ error: null
260
+ });
261
+ }
262
+ listCount += 1;
263
+ await refreshPullRequests(listings.flatMap((listing) => listing.issues));
264
+ const observedAt = new Date(now()).toISOString();
265
+ return {
266
+ ok: true,
267
+ payloads: listings.map(({ listed, issues, isComplete, error }) => ({
268
+ ...listed,
269
+ observedAt,
270
+ viewer: listedViewer,
271
+ isComplete,
272
+ error,
273
+ issues: issues.map(listedIssue)
274
+ }))
275
+ };
276
+ }
277
+ return { list };
278
+ }
279
+ // cloud/watchees/issues/issues-watchee.ts
280
+ var MS_PER_MINUTE$3 = 6e4;
281
+ var issuesWatchee = {
282
+ kind: "issues.listing",
283
+ laneId: "issues",
284
+ trigger: (settings) => ({
285
+ kind: "interval",
286
+ everyMs: settings.issues.intervalMinutes * MS_PER_MINUTE$3
287
+ }),
288
+ gate: ({ issues }) => issues.enabled ? { run: true } : {
289
+ run: false,
290
+ reason: "issues is off"
291
+ },
292
+ start: (context) => {
293
+ const listing = createIssuesListing({
294
+ store: createWatcheeGithubStore(context),
295
+ now: context.now
296
+ });
297
+ return {
298
+ detect: async ({ issues }) => {
299
+ const listed = await listing.list(issues);
300
+ if (!listed.ok) return listed;
301
+ return {
302
+ ok: true,
303
+ events: listed.payloads
304
+ };
305
+ },
306
+ stop: () => {}
307
+ };
308
+ },
309
+ eventKey: observedPayloadEventKey
310
+ };
311
+ // cloud/watchees/my-prs/my-prs-search.ts
312
+ var OPEN_WATCH = "my-prs-open";
313
+ var MERGED_WATCH = "my-prs-merged";
314
+ function createMyPrsSearch({ store, now }) {
315
+ let viewer = null;
316
+ let registeredQualifiers = null;
317
+ async function search(settings) {
318
+ const viewerRead = viewer === null ? await store.requestViewer("no-wait") : {
319
+ isRateLimited: false,
320
+ value: viewer
321
+ };
322
+ if (viewerRead.isRateLimited) return {
323
+ ok: false,
324
+ reason: "GitHub rate limit asks to wait.",
325
+ retryAfterMs: viewerRead.waitMs
326
+ };
327
+ if (viewerRead.value === null) return {
328
+ ok: false,
329
+ reason: "Could not look up your GitHub account."
330
+ };
331
+ viewer = viewerRead.value;
332
+ registerWatches(settings.org);
333
+ const refreshed = await store.refreshWatches([OPEN_WATCH, MERGED_WATCH]);
334
+ if (!refreshed.ok) return {
335
+ ok: false,
336
+ reason: refreshed.error ?? "GitHub search failed."
337
+ };
338
+ return {
339
+ ok: true,
340
+ payload: {
341
+ observedAt: new Date(now()).toISOString(),
342
+ viewer,
343
+ ...searchResultFromSnapshot()
344
+ }
345
+ };
346
+ }
347
+ function registerWatches(org) {
348
+ const mergedSince = mergedSinceDate(now());
349
+ const qualifiers = `${org}:${mergedSince}`;
350
+ if (registeredQualifiers === qualifiers) return;
351
+ store.registerWatch({
352
+ name: OPEN_WATCH,
353
+ qualifiers: `is:open author:@me org:${org} sort:updated-desc`,
354
+ needsDetail: true
355
+ });
356
+ store.registerWatch({
357
+ name: MERGED_WATCH,
358
+ qualifiers: `is:merged author:@me org:${org} merged:>=${mergedSince} sort:updated-desc`,
359
+ needsDetail: true
360
+ });
361
+ registeredQualifiers = qualifiers;
362
+ }
363
+ function searchResultFromSnapshot() {
364
+ const snapshot = store.getSnapshot();
365
+ let isComplete = true;
366
+ let returnedCount = 0;
367
+ let totalCount = 0;
368
+ const prsOf = (name) => {
369
+ const watch = snapshot.watches[name];
370
+ if (!watch?.isLoaded || !watch.isComplete) isComplete = false;
371
+ returnedCount += watch?.returnedCount ?? 0;
372
+ totalCount += watch?.totalCount ?? 0;
373
+ return (watch?.keys ?? []).flatMap((key) => {
374
+ const pr = snapshot.prs[key];
375
+ if (pr) return [pr];
376
+ isComplete = false;
377
+ return [];
378
+ });
379
+ };
380
+ const open = prsOf(OPEN_WATCH);
381
+ const merged = prsOf(MERGED_WATCH);
382
+ return {
383
+ isComplete,
384
+ returnedCount,
385
+ totalCount,
386
+ open,
387
+ merged
388
+ };
389
+ }
390
+ function stop() {
391
+ store.unregisterWatch(OPEN_WATCH);
392
+ store.unregisterWatch(MERGED_WATCH);
393
+ registeredQualifiers = null;
394
+ }
395
+ return {
396
+ search,
397
+ stop
398
+ };
399
+ }
400
+ // cloud/watchees/my-prs/my-prs-watchee.ts
401
+ var MS_PER_MINUTE$2 = 6e4;
402
+ var myPrsWatchee = {
403
+ kind: "my-prs.candidates",
404
+ laneId: "my-prs",
405
+ trigger: (settings) => ({
406
+ kind: "interval",
407
+ everyMs: settings.myPrs.intervalMinutes * MS_PER_MINUTE$2
408
+ }),
409
+ gate: ({ myPrs }) => {
410
+ if (!myPrs.enabled) return {
411
+ run: false,
412
+ reason: "my pull requests is off"
413
+ };
414
+ if (!myPrs.org) return {
415
+ run: false,
416
+ reason: "my pull requests has no GitHub organization"
417
+ };
418
+ return { run: true };
419
+ },
420
+ start: (context) => {
421
+ const search = createMyPrsSearch({
422
+ store: createWatcheeGithubStore(context),
423
+ now: context.now
424
+ });
425
+ return {
426
+ detect: async ({ myPrs }) => {
427
+ const searched = await search.search(myPrs);
428
+ if (!searched.ok) return searched;
429
+ return {
430
+ ok: true,
431
+ events: [searched.payload]
432
+ };
433
+ },
434
+ stop: search.stop
435
+ };
436
+ },
437
+ eventKey: observedPayloadEventKey
438
+ };
439
+ // cloud/watchees/team-review/team-review-search.ts
440
+ var AUTHORS_PER_SEARCH = 5;
441
+ function createTeamReviewSearch({ store, now }) {
442
+ const watches = /* @__PURE__ */ new Map();
443
+ let viewer = null;
444
+ async function search(settings) {
445
+ const viewerRead = viewer === null ? await store.requestViewer("no-wait") : {
446
+ isRateLimited: false,
447
+ value: viewer
448
+ };
449
+ if (viewerRead.isRateLimited) return {
450
+ ok: false,
451
+ reason: "GitHub rate limit asks to wait.",
452
+ retryAfterMs: viewerRead.waitMs
453
+ };
454
+ if (viewerRead.value === null) return {
455
+ ok: false,
456
+ reason: "Could not look up your GitHub account."
457
+ };
458
+ viewer = viewerRead.value;
459
+ const membership = await requestTeamMembership(settings.teams);
460
+ if (!membership.ok) return membership;
461
+ registerWatches(settings, orgSearchPlans(settings.org, settings.teams, membership.memberLists, viewer));
462
+ const refreshed = await store.refreshWatches([...watches.keys()]);
463
+ if (!refreshed.ok) return {
464
+ ok: false,
465
+ reason: refreshed.error ?? "GitHub search failed."
466
+ };
467
+ const searched = searchResultFromSnapshot();
468
+ return {
469
+ ok: true,
470
+ payload: {
471
+ observedAt: new Date(now()).toISOString(),
472
+ viewer,
473
+ ...searched,
474
+ isComplete: membership.isComplete && searched.isComplete
475
+ }
476
+ };
477
+ }
478
+ async function requestTeamMembership(teams) {
479
+ const memberLists = [];
480
+ for (const team of teams) {
481
+ const membersRead = await store.requestTeamMembers(team.org, team.slug, "no-wait");
482
+ if (membersRead.isRateLimited) return {
483
+ ok: false,
484
+ reason: "GitHub rate limit asks to wait.",
485
+ retryAfterMs: membersRead.waitMs
486
+ };
487
+ memberLists.push(membersRead.value);
488
+ }
489
+ const fetchedMemberLists = memberLists.map((members) => members ?? []);
490
+ if (teams.length > 0 && fetchedMemberLists.every((members) => members.length === 0)) return {
491
+ ok: false,
492
+ reason: "Could not look up your team members."
493
+ };
494
+ return {
495
+ ok: true,
496
+ memberLists: fetchedMemberLists,
497
+ isComplete: memberLists.every((members) => members !== null)
498
+ };
499
+ }
500
+ function registerWatches(settings, searchPlans) {
501
+ const nextWatches = /* @__PURE__ */ new Map();
502
+ for (const plan of searchPlans) {
503
+ nextWatches.set(`team-review-direct:${plan.org.toLowerCase()}`, {
504
+ qualifiers: `is:open draft:false org:${plan.org} user-review-requested:@me`,
505
+ source: "direct"
506
+ });
507
+ for (let index = 0; index < plan.authors.length; index += AUTHORS_PER_SEARCH) {
508
+ const authors = plan.authors.slice(index, index + AUTHORS_PER_SEARCH).map((author) => `author:${author}`).join(" ");
509
+ nextWatches.set(`team-review-authored:${plan.org.toLowerCase()}:${index / AUTHORS_PER_SEARCH}`, {
510
+ qualifiers: `is:open draft:false org:${plan.org} ${authors}`,
511
+ source: "authored"
512
+ });
513
+ }
514
+ }
515
+ for (const team of settings.teams) nextWatches.set(`team-review-team:${team.org.toLowerCase()}/${team.slug.toLowerCase()}`, {
516
+ qualifiers: `is:open draft:false org:${team.org} team-review-requested:${team.org}/${team.slug}`,
517
+ source: "team"
518
+ });
519
+ for (const name of watches.keys()) if (!nextWatches.has(name)) store.unregisterWatch(name);
520
+ for (const [name, watch] of nextWatches) if (watches.get(name)?.qualifiers !== watch.qualifiers) store.registerWatch({
521
+ name,
522
+ qualifiers: watch.qualifiers,
523
+ needsDetail: true
524
+ });
525
+ watches.clear();
526
+ for (const [name, watch] of nextWatches) watches.set(name, watch);
527
+ }
528
+ function searchResultFromSnapshot() {
529
+ const snapshot = store.getSnapshot();
530
+ const prsBySource = {
531
+ direct: [],
532
+ team: [],
533
+ authored: []
534
+ };
535
+ let isComplete = true;
536
+ for (const [name, { source }] of watches) {
537
+ const watch = snapshot.watches[name];
538
+ if (!watch?.isLoaded || !watch.isComplete) isComplete = false;
539
+ for (const key of watch?.keys ?? []) {
540
+ const pr = snapshot.prs[key];
541
+ if (!pr) {
542
+ isComplete = false;
543
+ continue;
544
+ }
545
+ prsBySource[source].push(pr);
546
+ }
547
+ }
548
+ return {
549
+ isComplete,
550
+ directRequested: prsBySource.direct,
551
+ teamRequested: prsBySource.team,
552
+ authored: prsBySource.authored
553
+ };
554
+ }
555
+ function stop() {
556
+ for (const name of watches.keys()) store.unregisterWatch(name);
557
+ watches.clear();
558
+ }
559
+ return {
560
+ search,
561
+ stop
562
+ };
563
+ }
564
+ // cloud/watchees/team-review/team-review-watchee.ts
565
+ var MS_PER_MINUTE$1 = 6e4;
566
+ var teamReviewWatchee = {
567
+ kind: "team-review.candidates",
568
+ laneId: "team-review",
569
+ trigger: (settings) => ({
570
+ kind: "interval",
571
+ everyMs: settings.teamReview.intervalMinutes * MS_PER_MINUTE$1
572
+ }),
573
+ gate: ({ teamReview }) => {
574
+ if (!teamReview.enabled) return {
575
+ run: false,
576
+ reason: "team review is off"
577
+ };
578
+ if (!teamReview.org) return {
579
+ run: false,
580
+ reason: "team review has no GitHub organization or team"
581
+ };
582
+ return { run: true };
583
+ },
584
+ start: (context) => {
585
+ const search = createTeamReviewSearch({
586
+ store: createWatcheeGithubStore(context),
587
+ now: context.now
588
+ });
589
+ return {
590
+ detect: async ({ teamReview }) => {
591
+ const searched = await search.search(teamReview);
592
+ if (!searched.ok) return searched;
593
+ return {
594
+ ok: true,
595
+ events: [searched.payload]
596
+ };
597
+ },
598
+ stop: search.stop
599
+ };
600
+ },
601
+ eventKey: observedPayloadEventKey
602
+ };
603
+ // cloud/watchees/workflows/workflows-search.ts
604
+ var MAX_PRS_PER_WATCH = 50;
605
+ function createWorkflowsSearch({ store, now }) {
606
+ let viewer = null;
607
+ const qualifiersByWatchName = /* @__PURE__ */ new Map();
608
+ async function search(settings) {
609
+ const viewerRead = viewer === null ? await store.requestViewer("no-wait") : {
610
+ isRateLimited: false,
611
+ value: viewer
612
+ };
613
+ if (viewerRead.isRateLimited) return {
614
+ ok: false,
615
+ reason: "GitHub rate limit asks to wait.",
616
+ retryAfterMs: viewerRead.waitMs
617
+ };
618
+ if (viewerRead.value === null) return {
619
+ ok: false,
620
+ reason: "Could not look up your GitHub account."
621
+ };
622
+ viewer = viewerRead.value;
623
+ registerWatches(settings.repos);
624
+ const refreshed = await store.refreshWatches([...qualifiersByWatchName.keys()]);
625
+ if (!refreshed.ok) return {
626
+ ok: false,
627
+ reason: refreshed.error ?? "GitHub search failed."
628
+ };
629
+ const observedAt = new Date(now()).toISOString();
630
+ const listedViewer = viewer;
631
+ return {
632
+ ok: true,
633
+ payloads: settings.repos.map((repo) => ({
634
+ observedAt,
635
+ viewer: listedViewer,
636
+ ...repoFromSnapshot(repo)
637
+ }))
638
+ };
639
+ }
640
+ function registerWatches(repos) {
641
+ const mergedSince = mergedSinceDate(now());
642
+ const nextQualifiersByWatchName = /* @__PURE__ */ new Map();
643
+ for (const repo of repos) {
644
+ const { openWatchName, mergedWatchName } = workflowRepoWatchNames(repo);
645
+ nextQualifiersByWatchName.set(openWatchName, `is:open repo:${repo} sort:updated-desc`);
646
+ nextQualifiersByWatchName.set(mergedWatchName, `is:merged repo:${repo} merged:>=${mergedSince} sort:updated-desc`);
647
+ }
648
+ for (const name of qualifiersByWatchName.keys()) if (!nextQualifiersByWatchName.has(name)) store.unregisterWatch(name);
649
+ for (const [name, qualifiers] of nextQualifiersByWatchName) {
650
+ if (qualifiersByWatchName.get(name) === qualifiers) continue;
651
+ store.registerWatch({
652
+ name,
653
+ qualifiers,
654
+ needsDetail: true,
655
+ maxMembers: MAX_PRS_PER_WATCH,
656
+ intervalMs: 3e5
657
+ });
658
+ }
659
+ qualifiersByWatchName.clear();
660
+ for (const [name, qualifiers] of nextQualifiersByWatchName) qualifiersByWatchName.set(name, qualifiers);
661
+ }
662
+ function repoFromSnapshot(repo) {
663
+ const snapshot = store.getSnapshot();
664
+ const watches = Object.values(workflowRepoWatchNames(repo)).map((name) => snapshot.watches[name]);
665
+ const keys = new Set(watches.flatMap((watch) => watch?.keys ?? []));
666
+ const prs = [...keys].flatMap((key) => snapshot.prs[key] ? [snapshot.prs[key]] : []);
667
+ return {
668
+ repo,
669
+ isComplete: watches.every((watch) => watch?.isLoaded === true && watch.isComplete) && prs.length === keys.size,
670
+ prs: prs.map(workflowPrFromGithubPr)
671
+ };
672
+ }
673
+ function stop() {
674
+ for (const name of qualifiersByWatchName.keys()) store.unregisterWatch(name);
675
+ qualifiersByWatchName.clear();
676
+ }
677
+ return {
678
+ search,
679
+ stop
680
+ };
681
+ }
682
+ // cloud/watchees/workflows/workflows-watchee.ts
683
+ var MS_PER_MINUTE = 6e4;
684
+ // cloud/watchees/registry.ts
685
+ var WATCHEES = Object.freeze({
686
+ "team-review.candidates": teamReviewWatchee,
687
+ "my-prs.candidates": myPrsWatchee,
688
+ "workflows.candidates": {
689
+ kind: "workflows.candidates",
690
+ laneId: "workflows",
691
+ trigger: (settings) => ({
692
+ kind: "interval",
693
+ everyMs: settings.workflows.intervalMinutes * MS_PER_MINUTE
694
+ }),
695
+ gate: ({ workflows }) => {
696
+ if (!workflows.enabled) return {
697
+ run: false,
698
+ reason: "workflows is off"
699
+ };
700
+ if (workflows.repos.length === 0) return {
701
+ run: false,
702
+ reason: "no workflow rule names a repository"
703
+ };
704
+ return { run: true };
705
+ },
706
+ start: (context) => {
707
+ const search = createWorkflowsSearch({
708
+ store: createWatcheeGithubStore(context),
709
+ now: context.now
710
+ });
711
+ return {
712
+ detect: async ({ workflows }) => {
713
+ const searched = await search.search(workflows);
714
+ if (!searched.ok) return searched;
715
+ return {
716
+ ok: true,
717
+ events: searched.payloads
718
+ };
719
+ },
720
+ stop: search.stop
721
+ };
722
+ },
723
+ eventKey: observedPayloadEventKey
724
+ },
725
+ "issues.listing": issuesWatchee
726
+ });
727
+ // cloud/watcher/core/watchee-runner-core.ts
728
+ var UUID_VERSION_8 = 128;
729
+ var UUID_VARIANT_RFC = 128;
730
+ function jobIdForEvent(kind, eventKey) {
731
+ const digest = crypto.createHash("sha256").update(`${kind}:${eventKey}`).digest();
732
+ digest[6] = (digest[6] ?? 0) & 15 | UUID_VERSION_8;
733
+ digest[8] = (digest[8] ?? 0) & 63 | UUID_VARIANT_RFC;
734
+ const hex = digest.subarray(0, 16).toString("hex");
735
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
736
+ }
737
+ function intervalStartMs(nowMs, everyMs) {
738
+ return nowMs - nowMs % everyMs;
739
+ }
740
+ function pruneSentEvents(sentAtByJobId, nowMs, maxAgeMs) {
741
+ return Object.fromEntries(Object.entries(sentAtByJobId).filter(([, sentAtMs]) => nowMs - sentAtMs <= maxAgeMs));
742
+ }
743
+ function createWatcheeJob(jobId, kind, payload, sentAt) {
744
+ return {
745
+ version: 1,
746
+ jobId,
747
+ sentAt: sentAt.toISOString(),
748
+ kind,
749
+ payload
750
+ };
751
+ }
752
+ // cloud/watcher/watchee-runner.ts
753
+ var SENT_EVENTS_MAX_AGE_MS = 2592e6;
754
+ var JOB_DELIVERY_ATTEMPTS = 3;
755
+ var SETTINGS_RELOAD_DEBOUNCE_MS = 250;
756
+ function createWatcheeRunner({ watcherHome, jobsUrl, token, now = Date.now, log = console }) {
757
+ const sentEventsPath = path.join(watcherHome, SENT_EVENTS_FILENAME);
758
+ const runningByKind = /* @__PURE__ */ new Map();
759
+ let currentSettings = null;
760
+ const kindsToResend = /* @__PURE__ */ new Set();
761
+ let sentAtByJobId = {};
762
+ let settingsWatcher = null;
763
+ let pendingReload = null;
764
+ async function start() {
765
+ sentAtByJobId = pruneSentEvents(await readSentEvents(), now(), SENT_EVENTS_MAX_AGE_MS);
766
+ await fs.promises.mkdir(watcherHome, {
767
+ recursive: true,
768
+ mode: 448
769
+ });
770
+ await reload();
771
+ settingsWatcher = fs.watch(canonicalizePath(watcherHome), (_event, filename) => {
772
+ if (filename !== "watchees.json") return;
773
+ if (pendingReload !== null) clearTimeout(pendingReload);
774
+ pendingReload = setTimeout(() => {
775
+ reload();
776
+ }, SETTINGS_RELOAD_DEBOUNCE_MS);
777
+ });
778
+ }
779
+ async function readSentEvents() {
780
+ const saved = await readJsonFileOrUndefined(sentEventsPath);
781
+ if (saved === null || typeof saved !== "object" || Array.isArray(saved)) return {};
782
+ return Object.fromEntries(Object.entries(saved).filter((entry) => typeof entry[1] === "number"));
783
+ }
784
+ async function reload() {
785
+ pendingReload = null;
786
+ const read = await readWatcheeSettings(watcherHome);
787
+ if (!read.ok) {
788
+ log.warn(`[watcher] ${read.reason}; keeping the last good watchee settings`);
789
+ return;
790
+ }
791
+ currentSettings = read.settings;
792
+ for (const kind of Object.keys(WATCHEES)) kindsToResend.add(kind);
793
+ for (const kind of Object.keys(WATCHEES)) await applyWatchee(kind, read.settings);
794
+ }
795
+ async function applyWatchee(kind, settings) {
796
+ const watchee = WATCHEES[kind];
797
+ const running = runningByKind.get(kind);
798
+ const gate = watchee.gate(settings);
799
+ if (!gate.run) {
800
+ if (running) await stopWatchee(kind, running);
801
+ log.log(`[watcher] ${watchee.laneId} not watching: ${gate.reason}`);
802
+ return;
803
+ }
804
+ const trigger = watchee.trigger(settings);
805
+ if (trigger.kind !== "interval") return;
806
+ if (running?.everyMs === trigger.everyMs) {
807
+ running.loop.tickSoon();
808
+ return;
809
+ }
810
+ if (running) await stopWatchee(kind, running);
811
+ const detector = watchee.start({
812
+ watcherHome,
813
+ now,
814
+ log
815
+ });
816
+ const loop = createTickLoop({
817
+ tag: `watcher:${watchee.laneId}`,
818
+ intervalMs: trigger.everyMs,
819
+ tick: () => detectAndSend(kind, detector, trigger.everyMs),
820
+ quickRetries: true,
821
+ now,
822
+ log
823
+ });
824
+ runningByKind.set(kind, {
825
+ everyMs: trigger.everyMs,
826
+ loop,
827
+ detector
828
+ });
829
+ await loop.start();
830
+ log.log(`[watcher] ${watchee.laneId} watching every ${Math.round(trigger.everyMs / 6e4)} min`);
831
+ }
832
+ async function detectAndSend(kind, detector, everyMs) {
833
+ if (currentSettings === null) return void 0;
834
+ const watchee = WATCHEES[kind];
835
+ const detected = await detector.detect(currentSettings);
836
+ if (!detected.ok) {
837
+ log.warn(`[watcher] ${watchee.laneId} could not detect: ${detected.reason}`);
838
+ return detected.retryAfterMs === void 0 ? {
839
+ failed: true,
840
+ error: detected.reason
841
+ } : {
842
+ failed: true,
843
+ retryAfterMs: detected.retryAfterMs,
844
+ error: detected.reason
845
+ };
846
+ }
847
+ const intervalStart = intervalStartMs(now(), everyMs);
848
+ for (const payload of detected.events) {
849
+ const jobId = jobIdForEvent(kind, watchee.eventKey(payload, intervalStart));
850
+ if (sentAtByJobId[jobId] !== void 0 && !kindsToResend.has(kind)) continue;
851
+ const delivery = await sendJob({
852
+ jobsUrl,
853
+ token,
854
+ job: createWatcheeJob(jobId, kind, payload, new Date(now())),
855
+ maxAttempts: JOB_DELIVERY_ATTEMPTS
856
+ });
857
+ if (!delivery.ok) return {
858
+ failed: true,
859
+ error: `${watchee.laneId} job not delivered: ${delivery.reason}`
860
+ };
861
+ sentAtByJobId = {
862
+ ...pruneSentEvents(sentAtByJobId, now(), SENT_EVENTS_MAX_AGE_MS),
863
+ [jobId]: now()
864
+ };
865
+ await writeJsonAtomic(sentEventsPath, sentAtByJobId, {
866
+ mode: 384,
867
+ enforceMode: true,
868
+ mkdir: true
869
+ });
870
+ }
871
+ kindsToResend.delete(kind);
872
+ }
873
+ async function stopWatchee(kind, running) {
874
+ runningByKind.delete(kind);
875
+ running.detector.stop();
876
+ await running.loop.stop();
877
+ }
878
+ async function stop() {
879
+ settingsWatcher?.close();
880
+ if (pendingReload !== null) clearTimeout(pendingReload);
881
+ for (const [kind, running] of [...runningByKind]) await stopWatchee(kind, running);
882
+ }
883
+ return {
884
+ start,
885
+ stop
886
+ };
887
+ }
888
+ // cloud/watcher/watch-cli.ts
889
+ var WATCHER_TOKEN_ENV = "GLIMMERVOID_WATCHER_TOKEN";
890
+ var PING_DELIVERY_ATTEMPTS = 3;
891
+ var IDLE_KEEP_ALIVE_MS = 2 ** 30;
892
+ var PARENT_LEFT = Symbol("parent left");
893
+ function whenSupervisorLeaves() {
894
+ if (process.send === void 0) return null;
895
+ if (!process.connected) return Promise.resolve(PARENT_LEFT);
896
+ return new Promise((resolve) => {
897
+ process.once("disconnect", () => resolve(PARENT_LEFT));
898
+ });
899
+ }
900
+ function untilStopSignal(supervisorLeft) {
901
+ return new Promise((resolve) => {
902
+ const keepAlive = setInterval(() => {}, IDLE_KEEP_ALIVE_MS);
903
+ const stop = () => {
904
+ clearInterval(keepAlive);
905
+ resolve();
906
+ };
907
+ process.once("SIGTERM", stop);
908
+ process.once("SIGINT", stop);
909
+ supervisorLeft?.then(stop);
910
+ });
911
+ }
912
+ async function runWatchCli({ inboxUrl, isPingOnly }) {
913
+ const token = process.env[WATCHER_TOKEN_ENV] ?? "";
914
+ if (token === "") {
915
+ console.error(`watch: no ${WATCHER_TOKEN_ENV} set`);
916
+ return 1;
917
+ }
918
+ const inbox = parseInboxUrl(inboxUrl);
919
+ if (!inbox.ok) {
920
+ console.error(`watch: ${inbox.reason}`);
921
+ return 1;
922
+ }
923
+ const supervisorLeft = whenSupervisorLeaves();
924
+ const startedAtMs = Date.now();
925
+ const pingDelivery = sendJob({
926
+ jobsUrl: inbox.jobsUrl,
927
+ token,
928
+ job: createPingJob(crypto.randomUUID(), /* @__PURE__ */ new Date()),
929
+ maxAttempts: PING_DELIVERY_ATTEMPTS
930
+ });
931
+ const delivery = await Promise.race(supervisorLeft === null ? [pingDelivery] : [pingDelivery, supervisorLeft]);
932
+ if (delivery === PARENT_LEFT) return 0;
933
+ if (!delivery.ok) {
934
+ console.error(`watch: ${delivery.reason}`);
935
+ if (isPingOnly) return 1;
936
+ }
937
+ if (delivery.ok) console.log(`ping acked by ${inbox.jobsUrl} in ${Date.now() - startedAtMs} ms`);
938
+ if (isPingOnly) return 0;
939
+ const watcheeRunner = createWatcheeRunner({
940
+ watcherHome: watcherHomeDir(),
941
+ jobsUrl: inbox.jobsUrl,
942
+ token
943
+ });
944
+ await watcheeRunner.start();
945
+ await untilStopSignal(supervisorLeft);
946
+ await watcheeRunner.stop();
947
+ return 0;
948
+ }
949
+ export { runWatchCli };