frizz 0.3.0 → 0.4.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 (98) hide show
  1. package/README.md +9 -4
  2. package/dist/claude-agent-broker.js +9 -4
  3. package/dist/dev-child.js +1783 -527
  4. package/dist/frizz.js +709 -233
  5. package/package.json +5 -3
  6. package/runtime/cc-worker/DECISIONS.md +17 -0
  7. package/runtime/cc-worker/bin/frizz-mcp.mjs +151 -174
  8. package/runtime/cc-worker/hooks/session-seed.mjs +1 -1
  9. package/web-dist/assets/{TerminalPane-CTdetDJJ.js → TerminalPane-sd3XXjx5.js} +1 -1
  10. package/web-dist/assets/{abnfDiagram-VRR7QNED-BDKrjCMs.js → abnfDiagram-VRR7QNED-Bry_FIqg.js} +1 -1
  11. package/web-dist/assets/architecture-TIHT7OUA-CoMJQ5Ya.js +1 -0
  12. package/web-dist/assets/{architectureDiagram-ZJ3FMSHR-BJebpUUM.js → architectureDiagram-ZJ3FMSHR-Baok4OeI.js} +1 -1
  13. package/web-dist/assets/{blockDiagram-677ZJIJ3-BNbuk25k.js → blockDiagram-677ZJIJ3-BgHIO9lI.js} +1 -1
  14. package/web-dist/assets/{c4Diagram-LMCZKHZV-lCfyotdU.js → c4Diagram-LMCZKHZV-rfj9Z17Z.js} +1 -1
  15. package/web-dist/assets/channel-D6uS1y7I.js +1 -0
  16. package/web-dist/assets/{chunk-32BRIVSS-DP72SEkr.js → chunk-32BRIVSS-BwaHfK1Y.js} +1 -1
  17. package/web-dist/assets/{chunk-52WLFC77-DxO3gN-p.js → chunk-52WLFC77-BmdQDZOA.js} +1 -1
  18. package/web-dist/assets/{chunk-C7G6YPKG-BXFx9Vlr.js → chunk-C7G6YPKG-ByQFjoZe.js} +1 -1
  19. package/web-dist/assets/{chunk-EX3LRPZG-CR3sHpPf.js → chunk-EX3LRPZG-DQFudBKr.js} +1 -1
  20. package/web-dist/assets/{chunk-FWX5IMBZ-CJ8L__oG.js → chunk-FWX5IMBZ-OW9qEPiq.js} +2 -2
  21. package/web-dist/assets/{chunk-HOUHSVGY-BCl3JSWr.js → chunk-HOUHSVGY-BdKLF8nO.js} +1 -1
  22. package/web-dist/assets/{chunk-ICXQ74PX-CZxFMci1.js → chunk-ICXQ74PX-C1roqKR1.js} +1 -1
  23. package/web-dist/assets/{chunk-MOJQB5TN-Ck3_47dB.js → chunk-MOJQB5TN-Cx0u1ZDK.js} +1 -1
  24. package/web-dist/assets/{chunk-OGEWGWER-CVXjES-F.js → chunk-OGEWGWER-rxv9xtNR.js} +1 -1
  25. package/web-dist/assets/{chunk-PUDLZKDR-JjrVgaR7.js → chunk-PUDLZKDR-BXWPPPPi.js} +1 -1
  26. package/web-dist/assets/{chunk-Q4XR5HBZ-C5YMRAQ0.js → chunk-Q4XR5HBZ-CpqbD101.js} +1 -1
  27. package/web-dist/assets/{chunk-V7JOEXUC-DK0mfUHU.js → chunk-V7JOEXUC-CP8_3qVt.js} +1 -1
  28. package/web-dist/assets/{chunk-VAUOI2AC-BKBntpid.js → chunk-VAUOI2AC-Dl7xahpk.js} +1 -1
  29. package/web-dist/assets/{chunk-VR4S4FIN-zgE1dG6U.js → chunk-VR4S4FIN-BKtMX64l.js} +1 -1
  30. package/web-dist/assets/{chunk-WYO6CB5R-CZhh1IBq.js → chunk-WYO6CB5R-DmLOdJcu.js} +1 -1
  31. package/web-dist/assets/{chunk-ZGVPDNZ5-CrNjIEem.js → chunk-ZGVPDNZ5-5wN7eXvS.js} +1 -1
  32. package/web-dist/assets/classDiagram-OUVF2IWQ-BW5YiBf4.js +1 -0
  33. package/web-dist/assets/classDiagram-v2-EOCWNBFH-BW5YiBf4.js +1 -0
  34. package/web-dist/assets/{cynefin-VYW2F7L2-Ca_BPfTG.js → cynefin-VYW2F7L2-DUYahBXb.js} +1 -1
  35. package/web-dist/assets/{cynefinDiagram-TSTJHNR4-CsINQf6g.js → cynefinDiagram-TSTJHNR4-Rm0i30nE.js} +1 -1
  36. package/web-dist/assets/{dagre-VKFMJZFB-CE0DYMFy.js → dagre-VKFMJZFB-3uhsB-W3.js} +1 -1
  37. package/web-dist/assets/{diagram-FQU43EPY-BqTduEYE.js → diagram-FQU43EPY-BUvflNRQ.js} +1 -1
  38. package/web-dist/assets/{diagram-G47NLZAW-Cho718s6.js → diagram-G47NLZAW-DUluIZel.js} +1 -1
  39. package/web-dist/assets/{diagram-NH7WQ7WH-D0Z8t9UC.js → diagram-NH7WQ7WH-BBrwsbed.js} +1 -1
  40. package/web-dist/assets/{diagram-OA4YK3LP-CBacyeDx.js → diagram-OA4YK3LP-DWnTQBw4.js} +1 -1
  41. package/web-dist/assets/{diagram-WEI45ONY-CozpXa4j.js → diagram-WEI45ONY-BjEavoC0.js} +1 -1
  42. package/web-dist/assets/{ebnfDiagram-CCIWWBDH-ba4NbQQo.js → ebnfDiagram-CCIWWBDH-CW4xZAZH.js} +1 -1
  43. package/web-dist/assets/{erDiagram-Q63AITRT-B3BciOYa.js → erDiagram-Q63AITRT-BemQ1R4B.js} +1 -1
  44. package/web-dist/assets/eventmodeling-45OFAUF4-BF5KB7ja.js +1 -0
  45. package/web-dist/assets/flowDiagram-23GEKE2U-BYo4Eytx.js +1 -0
  46. package/web-dist/assets/{ganttDiagram-NO4QXBWP-lPmrRit4.js → ganttDiagram-NO4QXBWP-lDdG5I_z.js} +1 -1
  47. package/web-dist/assets/{gitGraph-TEB2WS4Q-BjyclOq0.js → gitGraph-TEB2WS4Q-Bw87a_Se.js} +1 -1
  48. package/web-dist/assets/{gitGraphDiagram-IHSO6WYX-pzeb4Yrw.js → gitGraphDiagram-IHSO6WYX-B762r0yi.js} +1 -1
  49. package/web-dist/assets/index-B3QArXu2.css +1 -0
  50. package/web-dist/assets/index-CAapfhMv.js +365 -0
  51. package/web-dist/assets/{info-DKCQHKI2-Bwycegvf.js → info-DKCQHKI2-DGOv6Gx0.js} +1 -1
  52. package/web-dist/assets/{infoDiagram-FWYZ7A6U-BCvRGj_5.js → infoDiagram-FWYZ7A6U-DL92kAzf.js} +1 -1
  53. package/web-dist/assets/{ishikawaDiagram-FXEZZL3T-Ofw1RMj3.js → ishikawaDiagram-FXEZZL3T-CFYd4OtU.js} +1 -1
  54. package/web-dist/assets/{journeyDiagram-5HDEW3XC-C5ROwFio.js → journeyDiagram-5HDEW3XC-QHuYL5zq.js} +1 -1
  55. package/web-dist/assets/{kanban-definition-HUTT4EX6-YLPLkpeT.js → kanban-definition-HUTT4EX6-DwmMluQ8.js} +1 -1
  56. package/web-dist/assets/{line-KtkNqRgI.js → line-Je_PFFHm.js} +1 -1
  57. package/web-dist/assets/{mermaid-parser.core-D_FfqBe7.js → mermaid-parser.core-BeiGWsn3.js} +3 -3
  58. package/web-dist/assets/{mermaid.core-Ffv8anVf.js → mermaid.core-BP8JrW48.js} +3 -3
  59. package/web-dist/assets/{mindmap-definition-LN4V7U3C-B2jj4vfm.js → mindmap-definition-LN4V7U3C-BsmjCIrM.js} +1 -1
  60. package/web-dist/assets/{packet-7NZHBO7P-BjmWHwra.js → packet-7NZHBO7P-D6ekYYGJ.js} +1 -1
  61. package/web-dist/assets/{pegDiagram-2B236MQR-Dq3iJDyq.js → pegDiagram-2B236MQR-CQc2Kt0u.js} +1 -1
  62. package/web-dist/assets/{pie-RZYD4A2V-jBbH1lv9.js → pie-RZYD4A2V-C_45fO8J.js} +1 -1
  63. package/web-dist/assets/{pieDiagram-ENE6RG2P-C3ETW9lq.js → pieDiagram-ENE6RG2P-Dg5z6iWt.js} +1 -1
  64. package/web-dist/assets/{quadrantDiagram-ABIIQ3AL-DItSmme7.js → quadrantDiagram-ABIIQ3AL-c7gZxuCX.js} +1 -1
  65. package/web-dist/assets/{radar-I7S5WNFK-6ey6crgP.js → radar-I7S5WNFK-D80XNJQq.js} +1 -1
  66. package/web-dist/assets/{railroad-3IZDKUUU-Cii-Mn0E.js → railroad-3IZDKUUU-Brz7eZQ0.js} +1 -1
  67. package/web-dist/assets/railroad-abnf-AHOZXSZD-D44pcGhJ.js +1 -0
  68. package/web-dist/assets/railroad-ebnf-EBAXGLYW-CiWVH5SP.js +1 -0
  69. package/web-dist/assets/railroad-peg-LSFZ7HO6-Cy1B6-pN.js +1 -0
  70. package/web-dist/assets/{railroadDiagram-RFXS5EU6-M363ils_.js → railroadDiagram-RFXS5EU6-Db9K7bty.js} +1 -1
  71. package/web-dist/assets/{requirementDiagram-TGXJPOKE-CTs2_V6T.js → requirementDiagram-TGXJPOKE-m1ipMrDe.js} +1 -1
  72. package/web-dist/assets/{sankeyDiagram-HTMAVEWB-QTLLcDPD.js → sankeyDiagram-HTMAVEWB-4Zz9ry0k.js} +1 -1
  73. package/web-dist/assets/{sequenceDiagram-DBY2YBRQ-Bxw9Tr6e.js → sequenceDiagram-DBY2YBRQ-CZeGHw4X.js} +1 -1
  74. package/web-dist/assets/{stateDiagram-2N3HPSRC-BecB6roG.js → stateDiagram-2N3HPSRC-rLUVs1Pg.js} +1 -1
  75. package/web-dist/assets/stateDiagram-v2-6OUMAXLB-w7QDFEvx.js +1 -0
  76. package/web-dist/assets/{swimlanes-5IMT3BWC-COiYgS0w.js → swimlanes-5IMT3BWC-BAeBdscz.js} +1 -1
  77. package/web-dist/assets/swimlanesDiagram-G3AALYLV-UhdgWpNZ.js +8 -0
  78. package/web-dist/assets/{timeline-definition-FHXFAJF6-Ci22coeH.js → timeline-definition-FHXFAJF6-DL0eWMF-.js} +1 -1
  79. package/web-dist/assets/{treeView-QDETBFTQ-4DW35czh.js → treeView-QDETBFTQ-gEtzLMA8.js} +1 -1
  80. package/web-dist/assets/{treemap-6X3UGDF4-Dq_-Z6-Y.js → treemap-6X3UGDF4-CCym1Gz6.js} +1 -1
  81. package/web-dist/assets/{vennDiagram-L72KCM5P-CHQSIEYq.js → vennDiagram-L72KCM5P-cF97-nb5.js} +1 -1
  82. package/web-dist/assets/{wardley-OPB4EBWU-Bwlh7HCY.js → wardley-OPB4EBWU-DQJHCGbM.js} +1 -1
  83. package/web-dist/assets/{wardleyDiagram-EHGQE667-DctjuPYn.js → wardleyDiagram-EHGQE667-0CnHzXLX.js} +1 -1
  84. package/web-dist/assets/{xychartDiagram-FW5EYKEG-ZoIGosv8.js → xychartDiagram-FW5EYKEG-9YDOp4m5.js} +1 -1
  85. package/web-dist/index.html +2 -2
  86. package/web-dist/assets/architecture-TIHT7OUA-ChUMo004.js +0 -1
  87. package/web-dist/assets/channel-pr7r6raB.js +0 -1
  88. package/web-dist/assets/classDiagram-OUVF2IWQ-CvGbPMn_.js +0 -1
  89. package/web-dist/assets/classDiagram-v2-EOCWNBFH-CvGbPMn_.js +0 -1
  90. package/web-dist/assets/eventmodeling-45OFAUF4-DKmyo-jd.js +0 -1
  91. package/web-dist/assets/flowDiagram-23GEKE2U-DluCBvT4.js +0 -1
  92. package/web-dist/assets/index-BQtjYMpV.css +0 -1
  93. package/web-dist/assets/index-CLW1Q49U.js +0 -360
  94. package/web-dist/assets/railroad-abnf-AHOZXSZD-U_vb4BrX.js +0 -1
  95. package/web-dist/assets/railroad-ebnf-EBAXGLYW-BIHG7gNU.js +0 -1
  96. package/web-dist/assets/railroad-peg-LSFZ7HO6-Cpd9r-tB.js +0 -1
  97. package/web-dist/assets/stateDiagram-v2-6OUMAXLB-JXw9T96l.js +0 -1
  98. package/web-dist/assets/swimlanesDiagram-G3AALYLV--1Wv7FQQ.js +0 -8
package/dist/frizz.js CHANGED
@@ -10,6 +10,180 @@ var __export = (target2, all) => {
10
10
  __defProp(target2, name, { get: all[name], enumerable: true });
11
11
  };
12
12
 
13
+ // packages/server/src/local-origin.ts
14
+ import { isIP } from "node:net";
15
+ function publicAuthority(policy) {
16
+ const raw = policy?.publicOrigin;
17
+ if (!raw) return null;
18
+ let url;
19
+ try {
20
+ url = new URL(raw);
21
+ } catch {
22
+ return null;
23
+ }
24
+ if (url.origin !== raw) return null;
25
+ return {
26
+ hostname: normalizedHostname(url.hostname),
27
+ port: explicitPort(url),
28
+ authority: url.host.toLowerCase(),
29
+ scheme: url.protocol === "https:" ? "https" : "http"
30
+ };
31
+ }
32
+ function authoritySendsFetchMetadata(authority) {
33
+ return LOCAL_HOSTNAMES.has(authority.hostname) || authority.scheme === "https";
34
+ }
35
+ function acceptsHostname(hostname, policy) {
36
+ if (LOCAL_HOSTNAMES.has(hostname)) return true;
37
+ if (!policy?.exposed) return false;
38
+ if (isIP(hostname) !== 0) return true;
39
+ return (policy.allowedHosts ?? []).some((allowed) => allowed === "*" || allowed.toLowerCase() === hostname);
40
+ }
41
+ function oneHeader(value) {
42
+ return typeof value === "string" && value.length > 0 ? value : void 0;
43
+ }
44
+ function normalizedHostname(hostname) {
45
+ const lower = hostname.toLowerCase();
46
+ return lower.startsWith("[") && lower.endsWith("]") ? lower.slice(1, -1) : lower;
47
+ }
48
+ function explicitPort(url) {
49
+ if (url.port) return Number(url.port);
50
+ return url.protocol === "https:" ? 443 : 80;
51
+ }
52
+ function validExpectedPort(port) {
53
+ return Number.isInteger(port) && port >= 1 && port <= 65535;
54
+ }
55
+ function parseLocalHttpOrigin(value, expectedPort, policy) {
56
+ const raw = oneHeader(value);
57
+ if (!raw || !validExpectedPort(expectedPort) || raw !== raw.trim()) return null;
58
+ const declared = publicAuthority(policy);
59
+ if (declared && raw === policy?.publicOrigin) return declared;
60
+ let url;
61
+ try {
62
+ url = new URL(raw);
63
+ } catch {
64
+ return null;
65
+ }
66
+ if (url.protocol !== "http:" || url.origin !== raw) return null;
67
+ const hostname = normalizedHostname(url.hostname);
68
+ if (!acceptsHostname(hostname, policy) || explicitPort(url) !== expectedPort) return null;
69
+ return { hostname, port: expectedPort, authority: url.host, scheme: "http" };
70
+ }
71
+ function parseLocalHost(value, expectedPort, policy) {
72
+ const raw = oneHeader(value);
73
+ if (!raw || !validExpectedPort(expectedPort) || raw !== raw.trim() || raw.includes(",")) return null;
74
+ let url;
75
+ try {
76
+ url = new URL(`http://${raw}`);
77
+ } catch {
78
+ return null;
79
+ }
80
+ if (url.username || url.password || url.pathname !== "/" || url.search || url.hash) return null;
81
+ if (url.host.toLowerCase() !== raw.toLowerCase()) return null;
82
+ const hostname = normalizedHostname(url.hostname);
83
+ const declared = publicAuthority(policy);
84
+ if (declared && hostname === declared.hostname) {
85
+ return url.port === "" || Number(url.port) === declared.port ? declared : null;
86
+ }
87
+ if (!acceptsHostname(hostname, policy) || explicitPort(url) !== expectedPort) return null;
88
+ return { hostname, port: expectedPort, authority: url.host.toLowerCase(), scheme: "http" };
89
+ }
90
+ function hasForwardedAuthority(headers) {
91
+ return FORWARDED_HEADERS.some((name) => headers[name] !== void 0);
92
+ }
93
+ function forwardedAuthorityAllowed(headers, host, policy) {
94
+ if (!hasForwardedAuthority(headers)) return true;
95
+ const declared = publicAuthority(policy);
96
+ return !!declared && declared.hostname === host.hostname;
97
+ }
98
+ function isTrustedLocalHttpRequest(headers, expectedPort, allowMissingOrigin = false, policy) {
99
+ const host = parseLocalHost(headers.host, expectedPort, policy);
100
+ if (!host) return false;
101
+ if (!forwardedAuthorityAllowed(headers, host, policy)) return false;
102
+ if (headers.origin === void 0) return allowMissingOrigin;
103
+ const origin = parseLocalHttpOrigin(headers.origin, expectedPort, policy);
104
+ return !!origin && host.hostname === origin.hostname && host.port === origin.port;
105
+ }
106
+ function allowedLocalCorsOrigin(origin, expectedPort, policy) {
107
+ return parseLocalHttpOrigin(origin, expectedPort, policy) ? origin : void 0;
108
+ }
109
+ function normalizeBindHost(value) {
110
+ const trimmed = value.trim();
111
+ if (!trimmed) throw new Error("--host requires an address");
112
+ const bare = trimmed.startsWith("[") && trimmed.endsWith("]") ? trimmed.slice(1, -1) : trimmed;
113
+ const lower = bare.toLowerCase();
114
+ if (lower === "localhost") return LOOPBACK_BIND_HOST;
115
+ if (isIP(bare) === 0) {
116
+ throw new Error(`invalid --host address: ${value} (use an IP address such as 0.0.0.0, :: or 127.0.0.1)`);
117
+ }
118
+ return bare;
119
+ }
120
+ function bindHostIsExposed(host) {
121
+ return !LOOPBACK_BIND_HOSTS.has(host.trim().toLowerCase());
122
+ }
123
+ function normalizePublicOrigin(value) {
124
+ const trimmed = value.trim();
125
+ const invalid = (why) => new Error(`invalid --public-origin: ${value} (${why})`);
126
+ if (!trimmed) throw new Error("--public-origin requires a URL");
127
+ let url;
128
+ try {
129
+ url = new URL(trimmed);
130
+ } catch {
131
+ throw invalid("use a full URL such as https://frizz.example.com");
132
+ }
133
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw invalid("only http and https are supported");
134
+ if (url.username || url.password) throw invalid("an origin carries no credentials");
135
+ if (url.pathname !== "/" || url.search || url.hash) throw invalid("an origin is a scheme and host only, with no path");
136
+ if (!url.hostname) throw invalid("no hostname");
137
+ return url.origin;
138
+ }
139
+ function normalizeAllowedHosts(values) {
140
+ const seen = /* @__PURE__ */ new Set();
141
+ for (const value of values) {
142
+ for (const entry of value.split(",")) {
143
+ const host = entry.trim().toLowerCase();
144
+ if (host) seen.add(host);
145
+ }
146
+ }
147
+ return [...seen];
148
+ }
149
+ function rejectWebSocketUpgrade(socket, status = 403, reason = "Forbidden") {
150
+ const body = `${reason}
151
+ `;
152
+ const response = [
153
+ `HTTP/1.1 ${status} ${reason}`,
154
+ "Connection: close",
155
+ "Content-Type: text/plain; charset=utf-8",
156
+ `Content-Length: ${Buffer.byteLength(body)}`,
157
+ "",
158
+ body
159
+ ].join("\r\n");
160
+ try {
161
+ socket.end(response);
162
+ } catch {
163
+ try {
164
+ socket.destroy();
165
+ } catch {
166
+ }
167
+ }
168
+ }
169
+ var LOCAL_HOSTNAMES, FORWARDED_HEADERS, LOOPBACK_BIND_HOST, ALL_INTERFACES_BIND_HOST, LOOPBACK_BIND_HOSTS;
170
+ var init_local_origin = __esm({
171
+ "packages/server/src/local-origin.ts"() {
172
+ "use strict";
173
+ LOCAL_HOSTNAMES = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1"]);
174
+ FORWARDED_HEADERS = [
175
+ "forwarded",
176
+ "x-forwarded-for",
177
+ "x-forwarded-host",
178
+ "x-forwarded-port",
179
+ "x-forwarded-proto"
180
+ ];
181
+ LOOPBACK_BIND_HOST = "127.0.0.1";
182
+ ALL_INTERFACES_BIND_HOST = "0.0.0.0";
183
+ LOOPBACK_BIND_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "::1", "localhost", "[::1]"]);
184
+ }
185
+ });
186
+
13
187
  // packages/server/src/frizz-paths.ts
14
188
  import { existsSync } from "node:fs";
15
189
  import { homedir as homedir2, tmpdir } from "node:os";
@@ -1250,160 +1424,6 @@ var init_project_launch = __esm({
1250
1424
  }
1251
1425
  });
1252
1426
 
1253
- // packages/server/src/local-origin.ts
1254
- import { isIP } from "node:net";
1255
- function publicAuthority(policy) {
1256
- const raw = policy?.publicOrigin;
1257
- if (!raw) return null;
1258
- let url;
1259
- try {
1260
- url = new URL(raw);
1261
- } catch {
1262
- return null;
1263
- }
1264
- if (url.origin !== raw) return null;
1265
- return {
1266
- hostname: normalizedHostname(url.hostname),
1267
- port: explicitPort(url),
1268
- authority: url.host.toLowerCase(),
1269
- scheme: url.protocol === "https:" ? "https" : "http"
1270
- };
1271
- }
1272
- function authoritySendsFetchMetadata(authority) {
1273
- return LOCAL_HOSTNAMES.has(authority.hostname) || authority.scheme === "https";
1274
- }
1275
- function acceptsHostname(hostname, policy) {
1276
- if (LOCAL_HOSTNAMES.has(hostname)) return true;
1277
- if (!policy?.exposed) return false;
1278
- if (isIP(hostname) !== 0) return true;
1279
- return (policy.allowedHosts ?? []).some((allowed) => allowed === "*" || allowed.toLowerCase() === hostname);
1280
- }
1281
- function oneHeader(value) {
1282
- return typeof value === "string" && value.length > 0 ? value : void 0;
1283
- }
1284
- function normalizedHostname(hostname) {
1285
- const lower = hostname.toLowerCase();
1286
- return lower.startsWith("[") && lower.endsWith("]") ? lower.slice(1, -1) : lower;
1287
- }
1288
- function explicitPort(url) {
1289
- if (url.port) return Number(url.port);
1290
- return url.protocol === "https:" ? 443 : 80;
1291
- }
1292
- function validExpectedPort(port) {
1293
- return Number.isInteger(port) && port >= 1 && port <= 65535;
1294
- }
1295
- function parseLocalHttpOrigin(value, expectedPort, policy) {
1296
- const raw = oneHeader(value);
1297
- if (!raw || !validExpectedPort(expectedPort) || raw !== raw.trim()) return null;
1298
- const declared = publicAuthority(policy);
1299
- if (declared && raw === policy?.publicOrigin) return declared;
1300
- let url;
1301
- try {
1302
- url = new URL(raw);
1303
- } catch {
1304
- return null;
1305
- }
1306
- if (url.protocol !== "http:" || url.origin !== raw) return null;
1307
- const hostname = normalizedHostname(url.hostname);
1308
- if (!acceptsHostname(hostname, policy) || explicitPort(url) !== expectedPort) return null;
1309
- return { hostname, port: expectedPort, authority: url.host, scheme: "http" };
1310
- }
1311
- function parseLocalHost(value, expectedPort, policy) {
1312
- const raw = oneHeader(value);
1313
- if (!raw || !validExpectedPort(expectedPort) || raw !== raw.trim() || raw.includes(",")) return null;
1314
- let url;
1315
- try {
1316
- url = new URL(`http://${raw}`);
1317
- } catch {
1318
- return null;
1319
- }
1320
- if (url.username || url.password || url.pathname !== "/" || url.search || url.hash) return null;
1321
- if (url.host.toLowerCase() !== raw.toLowerCase()) return null;
1322
- const hostname = normalizedHostname(url.hostname);
1323
- const declared = publicAuthority(policy);
1324
- if (declared && hostname === declared.hostname) {
1325
- return url.port === "" || Number(url.port) === declared.port ? declared : null;
1326
- }
1327
- if (!acceptsHostname(hostname, policy) || explicitPort(url) !== expectedPort) return null;
1328
- return { hostname, port: expectedPort, authority: url.host.toLowerCase(), scheme: "http" };
1329
- }
1330
- function hasForwardedAuthority(headers) {
1331
- return FORWARDED_HEADERS.some((name) => headers[name] !== void 0);
1332
- }
1333
- function forwardedAuthorityAllowed(headers, host, policy) {
1334
- if (!hasForwardedAuthority(headers)) return true;
1335
- const declared = publicAuthority(policy);
1336
- return !!declared && declared.hostname === host.hostname;
1337
- }
1338
- function isTrustedLocalHttpRequest(headers, expectedPort, allowMissingOrigin = false, policy) {
1339
- const host = parseLocalHost(headers.host, expectedPort, policy);
1340
- if (!host) return false;
1341
- if (!forwardedAuthorityAllowed(headers, host, policy)) return false;
1342
- if (headers.origin === void 0) return allowMissingOrigin;
1343
- const origin = parseLocalHttpOrigin(headers.origin, expectedPort, policy);
1344
- return !!origin && host.hostname === origin.hostname && host.port === origin.port;
1345
- }
1346
- function allowedLocalCorsOrigin(origin, expectedPort, policy) {
1347
- return parseLocalHttpOrigin(origin, expectedPort, policy) ? origin : void 0;
1348
- }
1349
- function normalizeBindHost(value) {
1350
- const trimmed = value.trim();
1351
- if (!trimmed) throw new Error("--host requires an address");
1352
- const bare = trimmed.startsWith("[") && trimmed.endsWith("]") ? trimmed.slice(1, -1) : trimmed;
1353
- const lower = bare.toLowerCase();
1354
- if (lower === "localhost") return LOOPBACK_BIND_HOST;
1355
- if (isIP(bare) === 0) {
1356
- throw new Error(`invalid --host address: ${value} (use an IP address such as 0.0.0.0, :: or 127.0.0.1)`);
1357
- }
1358
- return bare;
1359
- }
1360
- function bindHostIsExposed(host) {
1361
- return !LOOPBACK_BIND_HOSTS.has(host.trim().toLowerCase());
1362
- }
1363
- function normalizePublicOrigin(value) {
1364
- const trimmed = value.trim();
1365
- const invalid = (why) => new Error(`invalid --public-origin: ${value} (${why})`);
1366
- if (!trimmed) throw new Error("--public-origin requires a URL");
1367
- let url;
1368
- try {
1369
- url = new URL(trimmed);
1370
- } catch {
1371
- throw invalid("use a full URL such as https://frizz.example.com");
1372
- }
1373
- if (url.protocol !== "https:" && url.protocol !== "http:") throw invalid("only http and https are supported");
1374
- if (url.username || url.password) throw invalid("an origin carries no credentials");
1375
- if (url.pathname !== "/" || url.search || url.hash) throw invalid("an origin is a scheme and host only, with no path");
1376
- if (!url.hostname) throw invalid("no hostname");
1377
- return url.origin;
1378
- }
1379
- function normalizeAllowedHosts(values) {
1380
- const seen = /* @__PURE__ */ new Set();
1381
- for (const value of values) {
1382
- for (const entry of value.split(",")) {
1383
- const host = entry.trim().toLowerCase();
1384
- if (host) seen.add(host);
1385
- }
1386
- }
1387
- return [...seen];
1388
- }
1389
- var LOCAL_HOSTNAMES, FORWARDED_HEADERS, LOOPBACK_BIND_HOST, ALL_INTERFACES_BIND_HOST, LOOPBACK_BIND_HOSTS;
1390
- var init_local_origin = __esm({
1391
- "packages/server/src/local-origin.ts"() {
1392
- "use strict";
1393
- LOCAL_HOSTNAMES = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1"]);
1394
- FORWARDED_HEADERS = [
1395
- "forwarded",
1396
- "x-forwarded-for",
1397
- "x-forwarded-host",
1398
- "x-forwarded-port",
1399
- "x-forwarded-proto"
1400
- ];
1401
- LOOPBACK_BIND_HOST = "127.0.0.1";
1402
- ALL_INTERFACES_BIND_HOST = "0.0.0.0";
1403
- LOOPBACK_BIND_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "::1", "localhost", "[::1]"]);
1404
- }
1405
- });
1406
-
1407
1427
  // packages/server/src/boot-progress.ts
1408
1428
  import { mkdirSync as mkdirSync4, readFileSync as readFileSync4, renameSync as renameSync3, rmSync as rmSync4, writeFileSync as writeFileSync4 } from "node:fs";
1409
1429
  import { basename as basename3, dirname as dirname4, join as join6 } from "node:path";
@@ -6255,7 +6275,7 @@ var init_receipt_bus = __esm({
6255
6275
  function fallbackPort(base) {
6256
6276
  return base + 1e4;
6257
6277
  }
6258
- var ATTACHMENT_IMAGE_EXTENSIONS, ATTACHMENT_DOC_EXTENSIONS, ATTACHMENT_EXTENSIONS, ATTACHMENT_MAX_BASE64_CHARS, ATTACHMENT_MAX_BYTES, ATTACHMENT_EXT_SET, ATTACHMENT_ACCEPT, FrizzStatus, BlockMechanism, RuntimeState, Backend, CodexModel, ThreadProfileOption, ThreadAgent, SubAgentView, BgShellView, CompletionHoldOp, CompletionHold, AskOption, AskQuestion, PendingAsk, NativeInputRequired, AwaitingHint, SnoozeUntil, SNOOZE_PROMPT_MAX, SnoozePrompt, RECURRING_PROMPT_MAX, RECURRING_MIN_INTERVAL_SECONDS, RECURRING_MAX_INTERVAL_SECONDS, RecurringPromptText, RecurringIntervalSeconds, ThreadRecurringPrompt, TIMER_PROMPT_MAX, TIMER_MAX_DELAY_SECONDS, TimerPromptText, SIGNOFF_NUDGE_MARKER, SIGNOFF_NUDGE_MESSAGE, ThreadWatchKind, RegisterableThreadWatchKind, ThreadWatchTarget, ThreadWatchView, ThreadTimerView, ThreadFence, PlanView, LimitWindow, LimitPause, ThreadView, BoardErrorItem, BoardSnapshot, QuotaWindow, ProviderQuota, QuotaSnapshot, ProviderAuth, AccountEmails, AuthSnapshot, AccountLogoutInput, AccountLogoutResult, AccountLoginStartInput, AccountLoginStartResult, AccountLoginStatusInput, AccountLoginStatusResult, PermissionMode, LocalFileOpener, Settings, DispatchProviderPreferences, DispatchPreferences, DispatchProfileSnapshot, SetDispatchPreferenceInput, DispatchInput, ADOPT_THREAD_MESSAGE_MAX_CHARS, AdoptThreadInput, AdoptThreadResult, FollowUpInput, UnqueueFollowUpInput, UnqueueFollowUpResult, DeliverQueuedNowInput, DeliverQueuedNowResult, SetThreadSnoozeInput, SetThreadRecurringPromptInput, SetOwnThreadRecurringPromptInput, SetOwnThreadRecurringPromptResult, GetOwnThreadRecurringPromptInput, OwnThreadRecurringPromptResult, SetOwnThreadTimerInput, CancelOwnThreadTimerInput, ListOwnThreadTimersInput, OwnThreadTimersResult, SetOwnThreadTimerResult, CancelOwnThreadTimerResult, AddOwnThreadWatchInput, PromoteOwnThreadWatchInput, PromoteOwnThreadWatchResult, DropOwnThreadWatchInput, ListOwnThreadWatchesInput, OwnThreadWatchesResult, AddOwnThreadWatchResult, DropOwnThreadWatchResult, SetOwnThreadStopHookInput, SetOwnThreadHeartbeatInput, ThreadPluginReloadResult, ConfirmAwaitingInput, RenameThreadInput, AiRenameThreadInput, AiRenameThreadResult, SetThreadPermissionInput, SetThreadPermissionResult, ThreadProfileOptionsInput, ThreadProfileOptionsResult, SetThreadProfileInput, SetThreadProfileResult, DISPATCH_TASK_BANNER, DISPATCH_TASK_BANNER_MARKER, GithubWakeItem, GithubWakeSteer, WAKE_SCOPE, WAKE_REF, WAKE_SINGLE, WAKE_MULTI_HEAD, GithubStatus, GithubItem, GithubListInput, GithubListResult, GithubBatchInput, GithubBatchResult, BoardMeta, ServerEvent, TranscriptEdit, TranscriptTodo, TranscriptToolCall, TranscriptPart, TranscriptMessage, TranscriptPageCursor, TranscriptPage, TranscriptEarlierInput, SocketTranscriptSlug, SocketClientMsg, ProjectCard, PROJECT_ICON_MAX_BASE64_CHARS, DirectoryPickResult, ThreadLocation, FRIZZ_ROUTE_PREFIX, DEFAULT_PORT;
6278
+ var ATTACHMENT_IMAGE_EXTENSIONS, ATTACHMENT_DOC_EXTENSIONS, ATTACHMENT_EXTENSIONS, ATTACHMENT_MAX_BASE64_CHARS, ATTACHMENT_MAX_BYTES, ATTACHMENT_EXT_SET, ATTACHMENT_ACCEPT, FrizzStatus, BlockMechanism, RuntimeState, Backend, CodexModel, ThreadProfileOption, ThreadAgent, SubAgentView, BgShellView, CompletionHoldOp, CompletionHold, AskOption, AskQuestion, PendingAsk, NativeInputRequired, AwaitingHint, RETIRED_AWAITING_KINDS, RETIRED_LINE_RE, AWAITING_FOR_MAX_MS, SnoozeUntil, SNOOZE_PROMPT_MAX, SnoozePrompt, RECURRING_PROMPT_MAX, RECURRING_MIN_INTERVAL_SECONDS, RECURRING_MAX_INTERVAL_SECONDS, RecurringPromptText, RecurringIntervalSeconds, ThreadRecurringPrompt, TIMER_PROMPT_MAX, TIMER_MAX_DELAY_SECONDS, TimerPromptText, SIGNOFF_NUDGE_MARKER, SIGNOFF_NUDGE_MESSAGE, ThreadWatchKind, GithubChecksState, GithubMergeState, GithubWatchStatus, ThreadWatchView, PR_WATCH_DEFAULT_FOR_MS, PrWatchView, AddOwnPrWatchInput, AddOwnPrWatchResult, DropOwnPrWatchInput, DropOwnPrWatchResult, ListOwnPrWatchesInput, OwnPrWatchesResult, ThreadTimerView, ThreadFence, PlanView, LimitWindow, LimitPause, ThreadView, BoardErrorItem, BoardSnapshot, QuotaWindow, ProviderQuota, QuotaSnapshot, ProviderAuth, AccountEmails, AuthSnapshot, AccountLogoutInput, AccountLogoutResult, AccountLoginStartInput, AccountLoginStartResult, AccountLoginStatusInput, AccountLoginStatusResult, PermissionMode, LocalFileOpener, Settings, DispatchProviderPreferences, DispatchPreferences, DispatchProfileSnapshot, SetDispatchPreferenceInput, DispatchInput, ADOPT_THREAD_MESSAGE_MAX_CHARS, AdoptThreadInput, AdoptThreadResult, FollowUpInput, UnqueueFollowUpInput, UnqueueFollowUpResult, DeliverQueuedNowInput, DeliverQueuedNowResult, SetThreadSnoozeInput, SetThreadRecurringPromptInput, SetOwnThreadRecurringPromptInput, SetOwnThreadRecurringPromptResult, GetOwnThreadRecurringPromptInput, OwnThreadRecurringPromptResult, SetOwnThreadTimerInput, CancelOwnThreadTimerInput, ListOwnThreadTimersInput, OwnThreadTimersResult, ThreadActivityItem, ListOwnThreadActivityInput, OwnThreadActivityResult, SetOwnThreadTimerResult, CancelOwnThreadTimerResult, SetOwnThreadStopHookInput, SetOwnThreadHeartbeatInput, ThreadPluginReloadResult, ConfirmAwaitingInput, RenameThreadInput, AiRenameThreadInput, AiRenameThreadResult, SetThreadPermissionInput, SetThreadPermissionResult, ThreadProfileOptionsInput, ThreadProfileOptionsResult, SetThreadProfileInput, SetThreadProfileResult, DISPATCH_TASK_BANNER, DISPATCH_TASK_BANNER_MARKER, GithubWakeItem, GithubWakeSteer, WAKE_SCOPE, WAKE_REF, WAKE_SINGLE, WAKE_MULTI_HEAD, GithubStatus, GithubRefCard, GithubRefPreviewInput, GithubRefPreviewResult, GithubItem, GithubListInput, GithubListResult, GithubBatchInput, GithubBatchResult, BoardMeta, ServerEvent, TranscriptEdit, TranscriptTodo, TranscriptToolCall, TranscriptPart, TranscriptMessage, TranscriptPageCursor, TranscriptPage, TranscriptEarlierInput, SocketTranscriptSlug, SocketClientMsg, ProjectCard, PROJECT_ICON_MAX_BASE64_CHARS, DirectoryPickResult, ThreadLocation, FRIZZ_ROUTE_PREFIX, DEFAULT_PORT;
6259
6279
  var init_src = __esm({
6260
6280
  "packages/shared/src/index.ts"() {
6261
6281
  "use strict";
@@ -6467,7 +6487,15 @@ var init_src = __esm({
6467
6487
  command: external_exports.string().optional(),
6468
6488
  // ISO8601 of the shell output file's last write — "last active 6 min ago" for a quiet-but-live
6469
6489
  // watcher. Optional (see SubAgentView.lastActivityAt).
6470
- lastActivityAt: external_exports.string().optional()
6490
+ lastActivityAt: external_exports.string().optional(),
6491
+ // The PROVIDER's session-wide background-task handle (`bzvtnt3ig`), as distinct from `id`, which is
6492
+ // the launch tool_use id. Both name the same shell and neither is a substitute for the other:
6493
+ // `id` is what the two copies of a row reconcile on, and this is the handle the runtime hands the
6494
+ // MODEL — "Command running in background with ID: bzvtnt3ig" is the only id a worker ever sees, so
6495
+ // it is the one it registers a `shell` watcher against. Matching on `id`/`label` alone meant every
6496
+ // such watcher was unfireable (scheduler.evalWatchers, 2026-08-14). Absent for a CODEX row, whose
6497
+ // single `processId` IS its `id`, and for a Claude row between its tool_use and its launch ack.
6498
+ taskId: external_exports.string().optional()
6471
6499
  });
6472
6500
  CompletionHoldOp = external_exports.object({
6473
6501
  label: external_exports.string(),
@@ -6504,9 +6532,12 @@ var init_src = __esm({
6504
6532
  title: external_exports.string().max(120)
6505
6533
  });
6506
6534
  AwaitingHint = external_exports.object({
6507
- kind: external_exports.enum(["pr-watch", "human", "timer", "pr", "ci", "session"]),
6535
+ kind: external_exports.enum(["shell", "agent", "timer", "pr", "for", "reason"]),
6508
6536
  value: external_exports.string()
6509
6537
  });
6538
+ RETIRED_AWAITING_KINDS = ["watch", "pr-watch", "human", "ci", "session"];
6539
+ RETIRED_LINE_RE = new RegExp(`^\\s*(${RETIRED_AWAITING_KINDS.join("|")}):\\s*\\S`, "im");
6540
+ AWAITING_FOR_MAX_MS = 24 * 60 * 60 * 1e3;
6510
6541
  SnoozeUntil = external_exports.string().regex(
6511
6542
  /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/,
6512
6543
  "Snooze time must be an ISO-8601 UTC instant"
@@ -6529,12 +6560,6 @@ var init_src = __esm({
6529
6560
  stopHook: external_exports.boolean(),
6530
6561
  heartbeat: external_exports.boolean(),
6531
6562
  postCompaction: external_exports.boolean(),
6532
- /** NOT a fourth trigger — a HOLD over all three. While it is on, nothing is sent for as long as the
6533
- * thread is blocked on the human: an unanswered ```question fence, a native ask, or a permission
6534
- * prompt. The footer panel seeds it ON for a fresh arming, with the stop hook, because they are one
6535
- * intent — see scheduler.ts, "WHAT A PENDING QUESTION DOES TO ALL THREE TRIGGERS". The stored column
6536
- * still defaults OFF, so an existing row and an older caller both keep the behaviour they had. */
6537
- pauseOnQuestions: external_exports.boolean(),
6538
6563
  intervalSeconds: external_exports.number().int().positive().optional(),
6539
6564
  armedAt: external_exports.string(),
6540
6565
  /** Last delivery per trigger; stamped separately so each reads its own clock. */
@@ -6547,33 +6572,154 @@ var init_src = __esm({
6547
6572
  TimerPromptText = external_exports.string().trim().min(1).max(TIMER_PROMPT_MAX);
6548
6573
  SIGNOFF_NUDGE_MARKER = "**This message is from frizz, not from the human.**";
6549
6574
  SIGNOFF_NUDGE_MESSAGE = [
6550
- `${SIGNOFF_NUDGE_MARKER} Nothing about your task has changed, and this is not a request to do more work.`,
6575
+ `${SIGNOFF_NUDGE_MARKER} Nothing about your task has changed, and no new work is being asked of you.`,
6576
+ "",
6577
+ "You rested without a fence, so this thread cannot be triaged.",
6578
+ "",
6579
+ "**IF THE TASK STILL HAS PARTS LEFT, THE FENCE IS NOT WHAT YOU OWE \u2014 THE WORK IS.** If ANY part of the",
6580
+ "original task is unfinished, unverified, or deferred, resume it NOW, in THIS turn, and sign off once it",
6581
+ "is genuinely finished. A milestone, a green test run and a long turn are none of them endings, and",
6582
+ "neither is naming the next step or writing it into a scratch file.",
6583
+ "",
6584
+ "**AND THAT TASK IS ALSO THE CEILING \u2014 finish it, and nothing else.** Work you notice on the way is a",
6585
+ "FINDING TO REPORT in your sign-off, never work to take on: the bug beside the one you were sent for,",
6586
+ "the refactor the code obviously wants, the second issue the first one touches. Widening the job is not",
6587
+ "thoroughness \u2014 it is a different job nobody asked for, and it buries the answer they did ask for under",
6588
+ "changes they now have to review. If it should be done, name it in one line and let the human dispatch",
6589
+ "it.",
6551
6590
  "",
6552
- "You rested without a fence, so this thread cannot be triaged. Add one at the END of your next message:",
6591
+ "**IF WHAT YOU WERE ASKED FOR IS A DOCUMENT, THE DOCUMENT IS THE ENDING.** A triage, a review, an",
6592
+ "investigation, a recommendation, a plan \u2014 when that is the deliverable, the finished write-up IS the",
6593
+ "work. Implementing what it proposes is the NEXT job, and not yours unless you were asked. Sign off with",
6594
+ "the write-up.",
6595
+ "",
6596
+ "**DECIDE RATHER THAN ASK.** Stop only for a decision that is genuinely the human's AND that blocks you",
6597
+ "right now: ask that one in a question fence. Every other open choice INSIDE the task \u2014 a name, a",
6598
+ "default, a reversible design call \u2014 is yours to make: decide it, say in one line which way you went and",
6599
+ "what would reverse it, and carry on. A choice that would ENLARGE the task is not one of those: an",
6600
+ "unanswered question is not permission to go build the answer.",
6601
+ "",
6602
+ "Otherwise, add a fence at the END of your next message:",
6553
6603
  "",
6554
6604
  "- `` ```question `` \u2014 you need the human. One question per fence, lettered options, one recommended.",
6555
6605
  "- `` ```done `` \u2014 genuinely FINISHED. A DISMISSAL: the card is filed away and nobody looks again, so",
6556
6606
  " if anything is still owed, it is not done. Body: 1-3 sentences, then bullets, each opening with a",
6557
6607
  " **bolded verb phrase**.",
6558
- "- Blocked on a PR, CI, or your own background shell? Register it with `mcp__frizz__watch` and rest.",
6608
+ "- `` ```awaiting `` \u2014 you are WAITING on work that is actually running. It is PURE STRUCTURE: one line",
6609
+ " per thing you are waiting on, a REQUIRED `for:` duration, and one line of `reason:` prose.",
6610
+ "",
6611
+ " ```awaiting",
6612
+ " shell: <the id your runtime gave you>",
6613
+ " pr: owner/repo#123",
6614
+ " for: 2h",
6615
+ " reason: what you are waiting for, in one line",
6616
+ " ```",
6617
+ "",
6618
+ " Frizz CHECKS every line: name something that is not running and you are bumped rather than parked.",
6619
+ " A fence that names NOTHING is not a park at all \u2014 if you are not waiting on anything, you are not",
6620
+ " awaiting, you are done. Register a PR with `mcp__frizz__watch_pr` and a timer with",
6621
+ " `mcp__frizz__timer`; `mcp__frizz__activity` reads back everything you have running, with its id.",
6622
+ "",
6623
+ "**STILL OWED counts things you are not going to do yourself.** A decision you are RECOMMENDING, a",
6624
+ "draft you wrote but did not send, follow-up work you discovered \u2014 all of it dies with the card, even",
6625
+ "the part that is someone else's to do. Each ends on a question with your recommendation as option A,",
6626
+ "or gets its own card first via `mcp__frizz__spawn_thread`; none of them is a `done`. And what is not",
6627
+ 'worth a card is not worth a SENTENCE: delete the dangling "one thing to carry forward", never park it',
6628
+ "in the handoff.",
6559
6629
  "",
6560
6630
  "**DO NOT REPEAT YOURSELF.** If the message you just wrote already stands on its own, reply with the",
6561
6631
  "fence ALONE \u2014 the human reads both together, so restating it costs them the second read for nothing.",
6632
+ "The same holds inside one message: the card is the ledger of what shipped, the prose is only what a",
6633
+ "ledger cannot hold, and a sentence that reads the same in either belongs in exactly one of them.",
6562
6634
  "",
6563
6635
  "Only if it does NOT stand alone, fix that first, briefly. It has to be readable cold: the human has",
6564
6636
  "seen nothing since their own last message \u2014 the Goal, this reminder, a watcher wake all came from",
6565
6637
  "frizz \u2014 so anything you assumed they had followed, they have not."
6566
6638
  ].join("\n");
6567
6639
  ThreadWatchKind = external_exports.enum(["shell", "github"]);
6568
- RegisterableThreadWatchKind = external_exports.enum(["shell"]);
6569
- ThreadWatchTarget = external_exports.string().trim().min(1).max(200);
6640
+ GithubChecksState = external_exports.enum(["none", "running", "passing", "failing"]);
6641
+ GithubMergeState = external_exports.enum(["mergeable", "blocked", "conflicting", "unknown"]);
6642
+ GithubWatchStatus = external_exports.object({
6643
+ checks: GithubChecksState,
6644
+ /** The counts behind the verdict, so the card can say "3 running, 12 passed" the way GitHub does
6645
+ * rather than only "checks are running". */
6646
+ running: external_exports.number().int().nonnegative(),
6647
+ passed: external_exports.number().int().nonnegative(),
6648
+ failed: external_exports.number().int().nonnegative(),
6649
+ /** The failing job NAMES, capped — what a human actually needs to decide whether to look. */
6650
+ failing: external_exports.array(external_exports.string()).max(8).default([]),
6651
+ merge: GithubMergeState,
6652
+ /** OPEN | CLOSED | MERGED, lowercased. A merged or closed PR ends the wait outright. */
6653
+ state: external_exports.enum(["open", "closed", "merged"]),
6654
+ /** When frizz last heard from GitHub. A poll can fail or be rate-limited, and a stale reading stated
6655
+ * as current is worse than no reading. */
6656
+ polledAt: external_exports.string(),
6657
+ /** The head commit this verdict was reached on. A PR watcher reports a CI verdict when it is NEWS, and
6658
+ * "red again on a new commit" is news that the bare word `failing` cannot express. Optional because a
6659
+ * reading taken before 2026-08-17 carries none. */
6660
+ head: external_exports.string().optional(),
6661
+ /** A digest of WHICH jobs are failing right now. The head commit alone cannot express a re-run of the
6662
+ * same job, or a slower job going red after the first — both of which are a second failure the worker
6663
+ * must hear about. Empty when nothing is failing. */
6664
+ failureSig: external_exports.string().optional()
6665
+ }).strict();
6570
6666
  ThreadWatchView = external_exports.object({
6571
6667
  id: external_exports.string(),
6572
6668
  kind: ThreadWatchKind,
6573
6669
  target: external_exports.string(),
6574
6670
  state: external_exports.enum(["armed", "fired", "dropped"]),
6575
- createdAt: external_exports.string()
6671
+ createdAt: external_exports.string(),
6672
+ /** `github` rows only, and absent until the first successful poll. */
6673
+ github: GithubWatchStatus.optional()
6674
+ }).strict();
6675
+ PR_WATCH_DEFAULT_FOR_MS = 6 * 60 * 60 * 1e3;
6676
+ PrWatchView = external_exports.object({
6677
+ id: external_exports.string(),
6678
+ /** `owner/repo#N`, normalized — the same string the board's row and the status book are keyed by. */
6679
+ target: external_exports.string(),
6680
+ state: external_exports.enum(["armed", "dropped", "settled"]),
6681
+ createdAt: external_exports.string(),
6682
+ /** The PR's checks/mergeability as the poller last saw it. Absent until the first successful poll. */
6683
+ github: GithubWatchStatus.optional()
6576
6684
  }).strict();
6685
+ AddOwnPrWatchInput = external_exports.object({
6686
+ slug: ThreadSlug,
6687
+ /** `owner/repo#123` or a PR URL. Parsed server-side; an unparseable ref is refused rather than stored,
6688
+ * because a watcher that can never fire is worse than none — the worker rests believing it is covered. */
6689
+ target: external_exports.string().trim().min(1).max(200),
6690
+ /** How long to watch, as a DURATION (`30m`, `2h`, `3d` — parseAwaitingDuration).
6691
+ *
6692
+ * A PR nobody ever reviews would otherwise be polled forever, and a thread parked on it would wait
6693
+ * forever with it — the same unbounded wait the awaiting fence's `for:` closes, one level down. A
6694
+ * duration rather than an instant for the same reason it is one there: it cannot be written in the
6695
+ * past (maintainer 2026-08-15, asking for it explicitly).
6696
+ *
6697
+ * REQUIRED BY THE TOOL, OPTIONAL ON THE WIRE, and the asymmetry is deliberate. A worker's MCP server
6698
+ * outlives every frizz restart, so a session dispatched before this existed still holds a binary that
6699
+ * cannot send it — and making the RPC reject that would break `watch_pr` outright for every thread
6700
+ * already running, with no recourse from inside those threads. Absent ⇒ PR_WATCH_DEFAULT_FOR, which
6701
+ * still BOUNDS the poll; the point of the field is that a worker chooses, and one that cannot choose
6702
+ * is better bounded than broken. */
6703
+ for: external_exports.string().trim().min(1).max(16).optional()
6704
+ }).strict();
6705
+ AddOwnPrWatchResult = external_exports.object({
6706
+ id: external_exports.string(),
6707
+ target: external_exports.string(),
6708
+ /** True when this exact PR was ALREADY watched by this thread, so the call registered nothing new.
6709
+ * Re-registering after a compaction is the common case, and a duplicate would double every wake. */
6710
+ alreadyArmed: external_exports.boolean(),
6711
+ watches: external_exports.array(PrWatchView)
6712
+ }).strict();
6713
+ DropOwnPrWatchInput = external_exports.object({
6714
+ slug: ThreadSlug,
6715
+ id: external_exports.string().min(1).max(64)
6716
+ }).strict();
6717
+ DropOwnPrWatchResult = external_exports.object({
6718
+ dropped: external_exports.boolean(),
6719
+ watches: external_exports.array(PrWatchView)
6720
+ }).strict();
6721
+ ListOwnPrWatchesInput = external_exports.object({ slug: ThreadSlug }).strict();
6722
+ OwnPrWatchesResult = external_exports.object({ watches: external_exports.array(PrWatchView) }).strict();
6577
6723
  ThreadTimerView = external_exports.object({
6578
6724
  id: external_exports.string(),
6579
6725
  prompt: external_exports.string(),
@@ -6731,6 +6877,16 @@ var init_src = __esm({
6731
6877
  // AUTO-bump (the scheduler resumes the agent with exactly this text) rather than a reminder, which is
6732
6878
  // the distinction the held row's tooltip renders. Absent ⇒ the card merely re-surfaces.
6733
6879
  snoozePrompt: external_exports.string().optional(),
6880
+ /** The EVENT snooze on the resting card is armed for this exact rest — the human has said "hide this
6881
+ * until something reports". Distinct from `snoozedUntil`, which is a wall-clock park on the whole
6882
+ * thread: this one has no deadline and clears itself when the thread comes to a NEW rest.
6883
+ *
6884
+ * It travels because the chat has to honour it too (2026-08-14). Until then only the QUEUE did, on
6885
+ * the reasoning that the card states a FACT the drawer must keep showing or it blanks at rest and
6886
+ * reads as "the agent died". That reasoning holds for a thread nobody has parked; once the human has
6887
+ * explicitly parked THIS rest, showing them the same card with the same button one surface over is
6888
+ * not information, and they said so. */
6889
+ bgSnoozed: external_exports.boolean().optional(),
6734
6890
  // Which Claude transport serves this thread: "broker" = a session-broker-owned Agent SDK session
6735
6891
  // (typed control channel), "tmux" = the interactive TUI in a pane. Only the broker can be asked to
6736
6892
  // reload its plugin closure in place, so the board needs it to decide whether to offer that verb at
@@ -6848,6 +7004,13 @@ var init_src = __esm({
6848
7004
  // Optional so a pre-restart server keeps working; absent means "fall back to `/`", i.e. the old
6849
7005
  // behaviour. Registry-derived, so it is the same slug every other surface links to.
6850
7006
  projectSlug: external_exports.string().optional(),
7007
+ // The server's home directory — the expansion of a `~` a worker wrote in prose. Agents reference
7008
+ // files that way constantly (`~/.claude/CLAUDE.md`), and the browser has no way to derive it, so a
7009
+ // `~`-anchored Markdown link had no absolute path to become and stayed a same-origin anchor that
7010
+ // navigated out of Frizz. The client only ever uses it to build a path it then hands BACK to the
7011
+ // server, which realpath-gates it exactly as it gates one the author typed in full. Optional so a
7012
+ // pre-restart server keeps working; absent means `~` links stay unresolved, i.e. the old behaviour.
7013
+ homeDir: external_exports.string().optional(),
6851
7014
  // (No `.frizz/ exists` bit here on purpose. Threads are session-first — the ui.db registry IS the
6852
7015
  // board — so `.frizz/` presence says nothing about whether this project has one. Its only consumer
6853
7016
  // was a shell gate that dead-ended `.frizz`-less repos; the server still probes the directory
@@ -6954,13 +7117,23 @@ var init_src = __esm({
6954
7117
  // Default action for a vetted non-image local path in agent markdown. Image clicks always use the
6955
7118
  // OS default viewer so screenshots retain their expected behavior.
6956
7119
  localFileOpener: LocalFileOpener.optional(),
6957
- // GitHub batch-dispatch prompt templates (the picker's per-item worker prompt). Optional: when
6958
- // unset OR blank the server falls back to its exported DEFAULT_ISSUE_PROMPT / DEFAULT_PR_PROMPT.
6959
- // Substitution tokens the server fills: {repo} {n} {title} {url} {labels} {body}. The leading
6960
- // `THREAD: <slug>` tag is prepended by the server (not part of the editable template) so a custom
6961
- // prompt can never break the thread↔.frizz-file binding. Optional so old settings blobs parse.
6962
- githubIssuePrompt: external_exports.string().optional(),
6963
- githubPrPrompt: external_exports.string().optional()
7120
+ // The GitHub batch-dispatch prompt template (the picker's per-item worker prompt). Optional: when
7121
+ // unset OR blank the server falls back to its exported DEFAULT_GITHUB_PROMPT. Substitution tokens
7122
+ // the server fills: {repo} {n} {title} {url} {labels} {body}. The leading `THREAD: <slug>` tag is
7123
+ // prepended by the server (not part of the editable template) so a custom prompt can never break the
7124
+ // thread↔.frizz-file binding. Optional so old settings blobs parse.
7125
+ //
7126
+ // ONE field, not one per kind. Issue and PR each had their own template until 2026-08-15, and the two
7127
+ // said the same thing twice: read the whole thread, be skeptical, cite what you checked, post nothing.
7128
+ // A person tuning "be more dubious" had to make the same edit in two boxes and keep them in step. The
7129
+ // ONE thing that genuinely differs per kind — which `gh` command reads the item — is a line in the
7130
+ // metadata block, so the merged template just carries both, and the worker picks the one that applies.
7131
+ //
7132
+ // There is no migration off the two old keys, and that is deliberate (the maintainer's call): Settings
7133
+ // is a non-strict z.object, so `githubIssuePrompt`/`githubPrPrompt` are STRIPPED the moment an old
7134
+ // blob is parsed. Any existing override is dropped and the reader gets the new shipped default —
7135
+ // exactly the intended backfill. Merging two customized templates into one has no correct answer.
7136
+ githubPrompt: external_exports.string().optional()
6964
7137
  });
6965
7138
  DispatchProviderPreferences = external_exports.object({
6966
7139
  model: external_exports.string().trim().min(1).max(200).optional(),
@@ -7089,9 +7262,6 @@ var init_src = __esm({
7089
7262
  // so a client that predates it — an older tab, an older MCP server — keeps writing the row correctly
7090
7263
  // with the trigger off, which is the honest reading of a caller that has never heard of it.
7091
7264
  postCompaction: external_exports.boolean().default(false),
7092
- // The QUESTION HOLD (2026-08-11). Defaulted for the same reason as the trigger above: a caller that
7093
- // has never heard of it means "don't hold", which is also this option's own default.
7094
- pauseOnQuestions: external_exports.boolean().default(false),
7095
7265
  intervalSeconds: RecurringIntervalSeconds.optional()
7096
7266
  }).strict();
7097
7267
  SetOwnThreadRecurringPromptInput = external_exports.object({
@@ -7103,8 +7273,14 @@ var init_src = __esm({
7103
7273
  // so a client that predates it — an older tab, an older MCP server — keeps writing the row correctly
7104
7274
  // with the trigger off, which is the honest reading of a caller that has never heard of it.
7105
7275
  postCompaction: external_exports.boolean().default(false),
7106
- // The QUESTION HOLD (2026-08-11), defaulted exactly as the trigger above and for the same reason.
7107
- pauseOnQuestions: external_exports.boolean().default(false),
7276
+ /** ACCEPTED AND IGNORED. The question hold was deleted 2026-08-16 (see scheduler.ts) and no caller in
7277
+ * this repo sends it any more — but this object is `.strict()`, and the caller on the other end is a
7278
+ * DETACHED worker daemon holding the `frizz-mcp.mjs` it was spawned with. Those outlive a server
7279
+ * restart by design, so for as long as any pre-2026-08-16 worker is alive a `start` would otherwise
7280
+ * come back as a validation error on a field the model cannot see it is sending. Tolerated here rather
7281
+ * than in the router so the shape stays one declaration; delete it once no such worker can be running.
7282
+ * The BROWSER input above needs no such clause — a stale tab is one reload away. */
7283
+ pauseOnQuestions: external_exports.boolean().optional(),
7108
7284
  intervalSeconds: RecurringIntervalSeconds.optional()
7109
7285
  }).strict();
7110
7286
  SetOwnThreadRecurringPromptResult = external_exports.object({
@@ -7131,6 +7307,23 @@ var init_src = __esm({
7131
7307
  OwnThreadTimersResult = external_exports.object({
7132
7308
  timers: external_exports.array(ThreadTimerView)
7133
7309
  }).strict();
7310
+ ThreadActivityItem = external_exports.object({
7311
+ kind: external_exports.enum(["shell", "agent", "timer", "pr"]),
7312
+ /** The string a `<kind>:` fence line must carry. For a shell that is the runtime task id the worker
7313
+ * was shown; for a PR, `owner/repo#N`; for a timer, its `tmr_…` row id. */
7314
+ id: external_exports.string(),
7315
+ label: external_exports.string(),
7316
+ /** ISO8601 of when it started or was armed — absent when frizz has no instant for it. */
7317
+ since: external_exports.string().optional(),
7318
+ /** A timer's fire instant, or a PR's expiry. Absent for shells and sub-agents. */
7319
+ until: external_exports.string().optional()
7320
+ }).strict();
7321
+ ListOwnThreadActivityInput = external_exports.object({
7322
+ slug: ThreadSlug
7323
+ }).strict();
7324
+ OwnThreadActivityResult = external_exports.object({
7325
+ activity: external_exports.array(ThreadActivityItem)
7326
+ }).strict();
7134
7327
  SetOwnThreadTimerResult = external_exports.object({
7135
7328
  id: external_exports.string(),
7136
7329
  fireAt: external_exports.string(),
@@ -7140,49 +7333,6 @@ var init_src = __esm({
7140
7333
  cancelled: external_exports.boolean(),
7141
7334
  timers: external_exports.array(ThreadTimerView)
7142
7335
  }).strict();
7143
- AddOwnThreadWatchInput = external_exports.object({
7144
- slug: ThreadSlug,
7145
- // REGISTERABLE kinds only, which is `shell` and nothing else — deliberately narrower than
7146
- // `ThreadWatchKind`, whose `github` member is a board-derived VIEW row with no registration behind it.
7147
- // The MCP tool already refuses a PR here in words ("a pr wait does not belong here — use an ```awaiting
7148
- // fence"); this is the same refusal at the wire, where it cannot be talked past.
7149
- kind: RegisterableThreadWatchKind,
7150
- target: ThreadWatchTarget,
7151
- /** The worker is BLOCKING on this one inside its tool call, so the scheduler settles it silently
7152
- * instead of delivering a wake — see the column comment in storage.ts. Defaulted, so a caller that
7153
- * has never heard of it registers an ordinary background watch. */
7154
- foreground: external_exports.boolean().default(false)
7155
- }).strict();
7156
- PromoteOwnThreadWatchInput = external_exports.object({
7157
- slug: ThreadSlug,
7158
- id: external_exports.string().min(1).max(64)
7159
- }).strict();
7160
- PromoteOwnThreadWatchResult = external_exports.object({
7161
- promoted: external_exports.boolean(),
7162
- watches: external_exports.array(ThreadWatchView)
7163
- }).strict();
7164
- DropOwnThreadWatchInput = external_exports.object({
7165
- slug: ThreadSlug,
7166
- id: external_exports.string().min(1).max(64)
7167
- }).strict();
7168
- ListOwnThreadWatchesInput = external_exports.object({
7169
- slug: ThreadSlug
7170
- }).strict();
7171
- OwnThreadWatchesResult = external_exports.object({
7172
- watches: external_exports.array(ThreadWatchView)
7173
- }).strict();
7174
- AddOwnThreadWatchResult = external_exports.object({
7175
- id: external_exports.string(),
7176
- /** True when this exact (kind, target) was ALREADY armed on the thread, so the call registered
7177
- * nothing new. A worker re-registering after a compaction is the common case, and silently minting a
7178
- * duplicate would mean two wakes for one event. */
7179
- alreadyArmed: external_exports.boolean(),
7180
- watches: external_exports.array(ThreadWatchView)
7181
- }).strict();
7182
- DropOwnThreadWatchResult = external_exports.object({
7183
- dropped: external_exports.boolean(),
7184
- watches: external_exports.array(ThreadWatchView)
7185
- }).strict();
7186
7336
  SetOwnThreadStopHookInput = external_exports.object({
7187
7337
  slug: ThreadSlug,
7188
7338
  prompt: RecurringPromptText.nullable(),
@@ -7285,6 +7435,43 @@ ${DISPATCH_TASK_BANNER}
7285
7435
  nameWithOwner: external_exports.string().nullable(),
7286
7436
  authed: external_exports.boolean()
7287
7437
  });
7438
+ GithubRefCard = external_exports.object({
7439
+ ref: external_exports.string(),
7440
+ kind: external_exports.enum(["issue", "pr", "commit"]),
7441
+ repo: external_exports.string(),
7442
+ // owner/repo, for the card's header line
7443
+ url: external_exports.string(),
7444
+ title: external_exports.string(),
7445
+ body: external_exports.string(),
7446
+ // already truncated server-side to the card's excerpt budget
7447
+ state: external_exports.string(),
7448
+ // OPEN | CLOSED | MERGED | DRAFT — empty for a commit, which has no state
7449
+ stateReason: external_exports.string().optional(),
7450
+ // COMPLETED | NOT_PLANNED | REOPENED — GitHub's closed-issue nuance
7451
+ at: external_exports.string().optional(),
7452
+ // ISO: opened-at for an issue/PR, committed-at for a commit
7453
+ authorLogin: external_exports.string().optional(),
7454
+ authorName: external_exports.string().optional(),
7455
+ // commits carry a git author name with no GitHub account behind it
7456
+ authorAvatar: external_exports.string().optional(),
7457
+ labels: external_exports.array(external_exports.object({ name: external_exports.string(), color: external_exports.string() })).default([]),
7458
+ additions: external_exports.number().int().nonnegative().optional(),
7459
+ deletions: external_exports.number().int().nonnegative().optional(),
7460
+ changedFiles: external_exports.number().int().nonnegative().optional(),
7461
+ comments: external_exports.number().int().nonnegative().optional(),
7462
+ // Epoch ms of the fetch this card came from. The CLIENT owns the freshness decision (render the
7463
+ // cached card instantly, then revalidate if it is old), so it has to be able to see the age.
7464
+ fetchedAt: external_exports.number().int().nonnegative()
7465
+ });
7466
+ GithubRefPreviewInput = external_exports.object({
7467
+ refs: external_exports.array(external_exports.string().min(3).max(120)).min(1).max(100),
7468
+ refresh: external_exports.boolean().default(false)
7469
+ });
7470
+ GithubRefPreviewResult = external_exports.object({
7471
+ cards: external_exports.array(GithubRefCard),
7472
+ missing: external_exports.array(external_exports.string()),
7473
+ error: external_exports.string().optional()
7474
+ });
7288
7475
  GithubItem = external_exports.object({
7289
7476
  kind: external_exports.enum(["issue", "pr"]),
7290
7477
  number: external_exports.number().int().positive(),
@@ -7951,6 +8138,7 @@ var init_local_image = __esm({
7951
8138
  });
7952
8139
 
7953
8140
  // src/production.ts
8141
+ init_local_origin();
7954
8142
  import { readFileSync as readFileSync10 } from "node:fs";
7955
8143
  import { homedir as homedir8 } from "node:os";
7956
8144
  import { fileURLToPath as fileURLToPath2 } from "node:url";
@@ -8625,6 +8813,7 @@ ${SYNC_END}`);
8625
8813
  }),
8626
8814
  // Yellow, above the dim hint: exposing the board off loopback is the one launch outcome the
8627
8815
  // operator must not skim past, so it may not share the hint's low-contrast styling.
8816
+ ...options2.qr?.length ? ["", ...options2.qr.map((row) => ` ${row}`)] : [],
8628
8817
  ...options2.warning ? ["", ` ${this.c(ANSI.yellow, options2.warning)}`] : [],
8629
8818
  ...hint ? ["", ` ${this.c(ANSI.dim, hint)}`] : [],
8630
8819
  ""
@@ -8801,6 +8990,7 @@ function parseCliArgs(argv) {
8801
8990
  "--detach",
8802
8991
  "--stop",
8803
8992
  "--status",
8993
+ "--link",
8804
8994
  "--help",
8805
8995
  "-h",
8806
8996
  "--dev",
@@ -8832,6 +9022,7 @@ function parseCliArgs(argv) {
8832
9022
  // Retain the option in the parsed shape for callers, but normal frizz-dev is always attached.
8833
9023
  foreground: true,
8834
9024
  stop: args2.has("--stop"),
9025
+ link: args2.has("--link"),
8835
9026
  status: args2.has("--status"),
8836
9027
  help: args2.has("--help") || args2.has("-h"),
8837
9028
  dev: args2.has("--dev"),
@@ -8844,6 +9035,7 @@ function parseCliArgs(argv) {
8844
9035
  };
8845
9036
  }
8846
9037
  var EXPOSED_WARNING = "Anyone who can reach this address can run commands on this machine as you. Frizz has no login \u2014 only do this on a network you trust.";
9038
+ var REUSED_NETWORK_FLAGS_WARNING = "This joined the Frizz already running on this machine, so --host/--public-origin were ignored. Stop it first (frizz --stop) and relaunch with the flag to change how the board is reached.";
8847
9039
  var PUBLIC_ORIGIN_WARNING = "Frizz has no login of its own, so whatever sits in front of this origin IS the access control. Require authentication there (Cloudflare Access, Tailscale) \u2014 an unauthenticated tunnel lets anyone with the URL run commands on this machine as you.";
8848
9040
  function resolveBindSelection(options2, env = process.env) {
8849
9041
  const fromEnv = env.FRIZZ_HOST?.trim();
@@ -8854,7 +9046,14 @@ function resolveBindSelection(options2, env = process.env) {
8854
9046
  ]);
8855
9047
  const publicOriginRaw = options2.publicOrigin ?? env.FRIZZ_PUBLIC_ORIGIN?.trim();
8856
9048
  const publicOrigin = publicOriginRaw ? normalizePublicOrigin(publicOriginRaw) : void 0;
8857
- return { host, exposed: bindHostIsExposed(host), allowedHosts, ...publicOrigin ? { publicOrigin } : {} };
9049
+ const publicToken = publicOrigin ? env.FRIZZ_PUBLIC_TOKEN?.trim() || void 0 : void 0;
9050
+ return {
9051
+ host,
9052
+ exposed: bindHostIsExposed(host),
9053
+ allowedHosts,
9054
+ ...publicOrigin ? { publicOrigin } : {},
9055
+ ...publicToken ? { publicToken } : {}
9056
+ };
8858
9057
  }
8859
9058
  function boardAddress(url) {
8860
9059
  return url.includes("?") || url.endsWith("/") ? url : `${url}/`;
@@ -9140,16 +9339,129 @@ import { basename as basename6, dirname as dirname7, extname as extname2, isAbso
9140
9339
  import { fileURLToPath } from "node:url";
9141
9340
  import watcher from "@parcel/watcher";
9142
9341
 
9342
+ // packages/server/src/restart-supervisor.ts
9343
+ import { request as requestHttp, createServer as createServer2 } from "node:http";
9344
+ import { connect } from "node:net";
9345
+
9346
+ // packages/server/src/access-codes.ts
9347
+ import { randomBytes, timingSafeEqual, createHmac } from "node:crypto";
9348
+ var CODE_BYTES = 16;
9349
+ var SESSION_BYTES = 32;
9350
+ var DEFAULT_CODE_TTL_MS = 5 * 6e4;
9351
+ var DEFAULT_SESSION_TTL_MS = 365 * 24 * 60 * 6e4;
9352
+ function defaultRandomToken(bytes) {
9353
+ return randomBytes(bytes).toString("base64url");
9354
+ }
9355
+ function secretsMatch(a, b) {
9356
+ const left = Buffer.from(a);
9357
+ const right = Buffer.from(b);
9358
+ return left.length === right.length && timingSafeEqual(left, right);
9359
+ }
9360
+ var AccessStore = class {
9361
+ codes = /* @__PURE__ */ new Map();
9362
+ options;
9363
+ /** Signing key for sessions. Persisted by the caller; a fresh one signs every device out. */
9364
+ signingKey;
9365
+ constructor(options2 = {}) {
9366
+ this.signingKey = options2.signingKey ?? randomBytes(32);
9367
+ this.options = {
9368
+ codeTtlMs: options2.codeTtlMs ?? DEFAULT_CODE_TTL_MS,
9369
+ sessionTtlMs: options2.sessionTtlMs ?? DEFAULT_SESSION_TTL_MS,
9370
+ now: options2.now ?? Date.now,
9371
+ randomToken: options2.randomToken ?? defaultRandomToken,
9372
+ onConsumed: options2.onConsumed
9373
+ };
9374
+ }
9375
+ /** Mint a code to show as a QR or a link. Minting does not invalidate codes already outstanding. */
9376
+ issue() {
9377
+ this.sweep();
9378
+ const now = this.options.now();
9379
+ const code = {
9380
+ code: this.options.randomToken(CODE_BYTES),
9381
+ createdAt: now,
9382
+ expiresAt: now + this.options.codeTtlMs
9383
+ };
9384
+ this.codes.set(code.code, code);
9385
+ return { code: code.code, createdAt: code.createdAt, expiresAt: code.expiresAt };
9386
+ }
9387
+ /**
9388
+ * Trade a code for a session, at most once, ever.
9389
+ *
9390
+ * The consumed marker is set BEFORE anything else can observe success, and JS runs this method to
9391
+ * completion without interleaving, so two browsers racing the same code cannot both win. That
9392
+ * atomicity is what makes "single-use" true rather than aspirational — it is the first thing the
9393
+ * tests attack.
9394
+ */
9395
+ redeem(code) {
9396
+ if (!code) return { ok: false, reason: "unknown" };
9397
+ const stored = this.codes.get(code);
9398
+ if (!stored || !secretsMatch(stored.code, code)) return { ok: false, reason: "unknown" };
9399
+ const now = this.options.now();
9400
+ if (stored.consumedAt !== void 0) return { ok: false, reason: "already-used" };
9401
+ if (now >= stored.expiresAt) {
9402
+ this.sweep();
9403
+ return { ok: false, reason: "expired" };
9404
+ }
9405
+ stored.consumedAt = now;
9406
+ this.sweep();
9407
+ this.options.onConsumed?.(code);
9408
+ return { ok: true, session: this.mintSession(now), expiresAt: now + this.options.sessionTtlMs };
9409
+ }
9410
+ /**
9411
+ * A session is `<expiry>.<hmac>` — stateless, so it needs no server-side table, and signed with a key
9412
+ * the caller persists so it survives a restart. Self-describing expiry means a stale cookie is
9413
+ * rejected without a lookup, and rotating the key revokes every outstanding session at once.
9414
+ */
9415
+ mintSession(now) {
9416
+ const expiresAt = now + this.options.sessionTtlMs;
9417
+ const nonce = this.options.randomToken(SESSION_BYTES);
9418
+ const payload = `${expiresAt}.${nonce}`;
9419
+ return `${payload}.${this.sign(payload)}`;
9420
+ }
9421
+ sign(payload) {
9422
+ return createHmac("sha256", this.signingKey).update(payload).digest("base64url");
9423
+ }
9424
+ /** Is this cookie a session signed by this board's key, and still in date? */
9425
+ verifySession(session) {
9426
+ if (!session) return false;
9427
+ const cut = session.lastIndexOf(".");
9428
+ if (cut <= 0) return false;
9429
+ const payload = session.slice(0, cut);
9430
+ const signature = session.slice(cut + 1);
9431
+ if (!secretsMatch(signature, this.sign(payload))) return false;
9432
+ const expiresAt = Number(payload.slice(0, payload.indexOf(".")));
9433
+ return Number.isFinite(expiresAt) && this.options.now() < expiresAt;
9434
+ }
9435
+ /**
9436
+ * Drop codes past their expiry so a long-lived board does not accumulate them forever.
9437
+ *
9438
+ * A CONSUMED code is deliberately kept until that same expiry rather than deleted on use. Deleting it
9439
+ * immediately would make a replay indistinguishable from a typo — both "unknown" — and the difference
9440
+ * matters: "already-used" is the message that tells someone their link was used by somebody else.
9441
+ * It costs one small entry for at most the code TTL.
9442
+ */
9443
+ sweep() {
9444
+ const now = this.options.now();
9445
+ for (const [key, stored] of this.codes) {
9446
+ if (now >= stored.expiresAt) this.codes.delete(key);
9447
+ }
9448
+ }
9449
+ /** Outstanding codes that could still be redeemed — neither consumed nor expired. */
9450
+ outstanding() {
9451
+ this.sweep();
9452
+ return [...this.codes.values()].filter((stored) => stored.consumedAt === void 0).map(({ code, createdAt, expiresAt }) => ({ code, createdAt, expiresAt }));
9453
+ }
9454
+ };
9455
+
9143
9456
  // packages/server/src/restart-supervisor.ts
9144
9457
  init_local_origin();
9145
9458
  init_local_image();
9146
9459
  init_src();
9147
- import { request as requestHttp, createServer as createServer2 } from "node:http";
9148
- import { connect } from "node:net";
9149
9460
  var SUPERVISOR_CONTROL_PREFIX = "/_frizz/control";
9150
9461
  var SUPERVISOR_RESTART_PATH = `${SUPERVISOR_CONTROL_PREFIX}/restart`;
9151
9462
  var SUPERVISOR_UPDATE_RESTART_PATH = `${SUPERVISOR_CONTROL_PREFIX}/update-restart`;
9152
9463
  var SUPERVISOR_STATUS_PATH = `${SUPERVISOR_CONTROL_PREFIX}/status`;
9464
+ var SUPERVISOR_ACCESS_CODE_PATH = `${SUPERVISOR_CONTROL_PREFIX}/access-code`;
9153
9465
  var SUPERVISOR_CONTROL_PROTOCOL = 1;
9154
9466
  function responseJson(res, status, value) {
9155
9467
  res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
@@ -9168,9 +9480,27 @@ function proxyHeaders(req, childPort, vouchSameOrigin = false) {
9168
9480
  delete headers.connection;
9169
9481
  return headers;
9170
9482
  }
9483
+ var PUBLIC_TOKEN_PARAM = "frizz_token";
9484
+ var ACCESS_CODE_PARAM = "frizz_code";
9485
+ var PUBLIC_TOKEN_COOKIE = "frizz_public";
9486
+ var SESSION_COOKIE = "frizz_session";
9487
+ var LOOPBACK_HOSTNAMES = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1"]);
9488
+ function readCookie(header, name) {
9489
+ if (!header) return void 0;
9490
+ for (const pair of header.split(";")) {
9491
+ const eq = pair.indexOf("=");
9492
+ if (eq === -1) continue;
9493
+ if (pair.slice(0, eq).trim() === name) return pair.slice(eq + 1).trim();
9494
+ }
9495
+ return void 0;
9496
+ }
9497
+ function unauthorizedPage(reason) {
9498
+ const detail = reason === "already-used" ? "That link has already been used. Generate a fresh one." : reason === "expired" ? "That link expired. Generate a fresh one." : "This address needs a current access link.";
9499
+ return `<!doctype html><meta charset="utf-8"><title>Unauthorized</title><meta name="viewport" content="width=device-width,initial-scale=1"><style>body{margin:3rem;font:16px system-ui;color:#e7e7e7;background:#171717}main{max-width:30rem;padding:1.5rem;border:1px solid #444;border-radius:.75rem;background:#222}</style><main><h1>Unauthorized</h1>${detail ? `<p>${detail}</p>` : ""}</main>`;
9500
+ }
9171
9501
  function isControlRequest(req) {
9172
9502
  const url = new URL(req.url ?? "/", "http://frizz.invalid");
9173
- return url.pathname === SUPERVISOR_RESTART_PATH || url.pathname === SUPERVISOR_UPDATE_RESTART_PATH || url.pathname === SUPERVISOR_STATUS_PATH;
9503
+ return url.pathname === SUPERVISOR_RESTART_PATH || url.pathname === SUPERVISOR_UPDATE_RESTART_PATH || url.pathname === SUPERVISOR_STATUS_PATH || url.pathname === SUPERVISOR_ACCESS_CODE_PATH;
9174
9504
  }
9175
9505
  function isLocalImageRequest(req) {
9176
9506
  if (req.method !== "GET" && req.method !== "HEAD") return false;
@@ -9192,17 +9522,40 @@ var RestartSupervisorProxy = class {
9192
9522
  * judged here first.
9193
9523
  */
9194
9524
  policy;
9525
+ /**
9526
+ * Codes and sessions for the public origin, or null when no public origin is declared (loopback-only
9527
+ * boards are never gated, so there is nothing to store).
9528
+ */
9529
+ access;
9195
9530
  /** Both halves of every live upgraded pair, so close() can actually finish. See close(). */
9196
9531
  upgradedSockets = /* @__PURE__ */ new Set();
9197
9532
  constructor(options2) {
9198
9533
  this.options = options2;
9199
9534
  this.host = options2.host ?? LOOPBACK_BIND_HOST;
9535
+ this.access = options2.publicOrigin ? new AccessStore({
9536
+ onConsumed: () => options2.onCodeConsumed?.(),
9537
+ ...options2.sessionKey ? { signingKey: options2.sessionKey } : {}
9538
+ }) : null;
9200
9539
  this.policy = {
9201
9540
  exposed: bindHostIsExposed(this.host),
9202
9541
  allowedHosts: options2.allowedHosts ?? [],
9203
9542
  ...options2.publicOrigin ? { publicOrigin: options2.publicOrigin } : {}
9204
9543
  };
9205
9544
  }
9545
+ /**
9546
+ * Mint a single-use code for this board, or null when no public origin is declared.
9547
+ *
9548
+ * Issuing does NOT invalidate codes already outstanding — pressing the key twice, or two people
9549
+ * asking at once, must not silently break the first QR somebody is still walking towards.
9550
+ */
9551
+ issueAccessCode() {
9552
+ return this.access?.issue() ?? null;
9553
+ }
9554
+ /** The full URL to show as a link or a QR. */
9555
+ accessUrl(code) {
9556
+ const origin = this.options.publicOrigin;
9557
+ return origin ? `${origin}/?${ACCESS_CODE_PARAM}=${encodeURIComponent(code)}` : null;
9558
+ }
9206
9559
  async listen() {
9207
9560
  if (this.server) return;
9208
9561
  const server = createServer2((req, res) => this.handle(req, res));
@@ -9316,6 +9669,26 @@ var RestartSupervisorProxy = class {
9316
9669
  res.end("Forbidden");
9317
9670
  return;
9318
9671
  }
9672
+ if (pathname === SUPERVISOR_ACCESS_CODE_PATH) {
9673
+ if (this.arrivedPublicly(req)) {
9674
+ res.writeHead(403);
9675
+ res.end("Forbidden");
9676
+ return;
9677
+ }
9678
+ if (req.method !== "POST") {
9679
+ res.writeHead(405, { allow: "POST" });
9680
+ res.end();
9681
+ return;
9682
+ }
9683
+ const link = this.issueAccessCode();
9684
+ const url = link && this.accessUrl(link.code);
9685
+ if (!link || !url) {
9686
+ responseJson(res, 409, { error: "this board has no public origin, so there is nothing to link to" });
9687
+ return;
9688
+ }
9689
+ responseJson(res, 200, { url, expiresAt: link.expiresAt });
9690
+ return;
9691
+ }
9319
9692
  if (pathname === SUPERVISOR_STATUS_PATH && req.method === "GET") {
9320
9693
  responseJson(res, 200, { protocol: SUPERVISOR_CONTROL_PROTOCOL, ...this.status() });
9321
9694
  return;
@@ -9365,11 +9738,93 @@ var RestartSupervisorProxy = class {
9365
9738
  });
9366
9739
  res.end(req.method === "HEAD" ? void 0 : result.body);
9367
9740
  }
9741
+ /**
9742
+ * Is this request arriving as the declared public origin rather than over loopback?
9743
+ *
9744
+ * The token gate keys on this and not on "is the port exposed", because the two are independent:
9745
+ * a tunnelled board stays bound to 127.0.0.1 while being reachable from the internet by name.
9746
+ */
9747
+ arrivedPublicly(req) {
9748
+ const declared = this.options.publicOrigin;
9749
+ if (!declared) return false;
9750
+ const host = parseLocalHost(req.headers.host, this.options.port, this.policy);
9751
+ return !!host && !LOOPBACK_HOSTNAMES.has(host.hostname);
9752
+ }
9753
+ /**
9754
+ * Bearer check for the public origin. Two ways in: the cookie the exchange below sets, or the
9755
+ * one-time `?frizz_token=` in the URL the operator was handed at launch.
9756
+ *
9757
+ * Compared with `timingSafeEqual` on equal-length buffers — a plain `===` on a secret leaks its
9758
+ * prefix to a patient attacker, and this secret is the only thing between the internet and a shell.
9759
+ */
9760
+ /**
9761
+ * Is this request carrying a session this process minted?
9762
+ *
9763
+ * Sessions only. A raw `?frizz_code=` is NOT accepted here — it is redeemed once by exchangeCode()
9764
+ * below and traded for a session, so a code that has already been spent cannot keep working just by
9765
+ * staying in somebody's URL bar.
9766
+ */
9767
+ sessionAccepted(req) {
9768
+ if (!this.access) return true;
9769
+ if (this.options.publicToken && this.legacyTokenAccepted(req)) return true;
9770
+ return this.access.verifySession(readCookie(req.headers.cookie, SESSION_COOKIE));
9771
+ }
9772
+ /**
9773
+ * The standing `FRIZZ_PUBLIC_TOKEN`, for headless boxes where nobody can press a key to mint a code.
9774
+ * Deliberately kept as a separate, opt-in path rather than folded into sessions: it has the weaker
9775
+ * properties (never rotates, every copy stays valid) and the readout says so.
9776
+ */
9777
+ legacyTokenAccepted(req) {
9778
+ const expected2 = this.options.publicToken;
9779
+ if (!expected2) return false;
9780
+ const url = new URL(req.url ?? "/", "http://frizz.invalid");
9781
+ const supplied = url.searchParams.get(PUBLIC_TOKEN_PARAM) ?? readCookie(req.headers.cookie, PUBLIC_TOKEN_COOKIE);
9782
+ return !!supplied && secretsMatch(supplied, expected2);
9783
+ }
9784
+ /**
9785
+ * Trade `?frizz_code=…` (or the legacy `?frizz_token=…`) for a cookie, then bounce to the same URL
9786
+ * without the secret, so it never lands in history, a Referer header, or a screenshot.
9787
+ */
9788
+ exchangeCode(req, res) {
9789
+ const url = new URL(req.url ?? "/", "http://frizz.invalid");
9790
+ const code = url.searchParams.get(ACCESS_CODE_PARAM);
9791
+ const legacy = url.searchParams.get(PUBLIC_TOKEN_PARAM);
9792
+ if (code === null && legacy === null) return false;
9793
+ let cookie;
9794
+ if (code !== null) {
9795
+ const redeemed = this.access?.redeem(code);
9796
+ if (!redeemed?.ok) {
9797
+ res.writeHead(401, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
9798
+ res.end(unauthorizedPage(redeemed?.reason));
9799
+ return true;
9800
+ }
9801
+ cookie = `${SESSION_COOKIE}=${redeemed.session}`;
9802
+ } else {
9803
+ if (!this.legacyTokenAccepted(req)) return false;
9804
+ cookie = `${PUBLIC_TOKEN_COOKIE}=${this.options.publicToken}`;
9805
+ }
9806
+ url.searchParams.delete(ACCESS_CODE_PARAM);
9807
+ url.searchParams.delete(PUBLIC_TOKEN_PARAM);
9808
+ const target2 = `${url.pathname}${url.search}${url.hash}` || "/";
9809
+ res.writeHead(302, {
9810
+ location: target2,
9811
+ "set-cookie": `${cookie}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=31536000`,
9812
+ "cache-control": "no-store"
9813
+ });
9814
+ res.end();
9815
+ return true;
9816
+ }
9368
9817
  handle(req, res) {
9369
9818
  if (isControlRequest(req)) {
9370
9819
  void this.handleControl(req, res);
9371
9820
  return;
9372
9821
  }
9822
+ if (this.arrivedPublicly(req) && this.exchangeCode(req, res)) return;
9823
+ if (this.arrivedPublicly(req) && !this.sessionAccepted(req)) {
9824
+ res.writeHead(401, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
9825
+ res.end(unauthorizedPage());
9826
+ return;
9827
+ }
9373
9828
  if (!this.authorityAccepted(req)) {
9374
9829
  res.writeHead(403, { "content-type": "text/plain; charset=UTF-8" });
9375
9830
  res.end("Forbidden");
@@ -9403,6 +9858,10 @@ var RestartSupervisorProxy = class {
9403
9858
  req.pipe(upstream);
9404
9859
  }
9405
9860
  handleUpgrade(req, socket, head) {
9861
+ if (this.arrivedPublicly(req) && !this.sessionAccepted(req)) {
9862
+ rejectWebSocketUpgrade(socket, 401, "Unauthorized");
9863
+ return;
9864
+ }
9406
9865
  if (!this.authorityAccepted(req, false)) {
9407
9866
  socket.destroy();
9408
9867
  return;
@@ -9705,6 +10164,9 @@ var Supervisor = class {
9705
10164
  host: opts.host,
9706
10165
  allowedHosts: opts.allowedHosts,
9707
10166
  publicOrigin: opts.publicOrigin,
10167
+ publicToken: opts.publicToken,
10168
+ onCodeConsumed: opts.onCodeConsumed,
10169
+ sessionKey: opts.sessionKey,
9708
10170
  childPort: () => this.childPort,
9709
10171
  restart: () => this.restartFromBrowser(),
9710
10172
  updateRestart: this.updateRestart ? () => this.updateFromBrowser() : void 0,
@@ -9727,6 +10189,13 @@ var Supervisor = class {
9727
10189
  currentBoot() {
9728
10190
  return this.boot;
9729
10191
  }
10192
+ /** Mint a single-use access link for the public origin, or null when none is declared. */
10193
+ issueAccessLink() {
10194
+ const code = this.publicProxy.issueAccessCode();
10195
+ if (!code) return null;
10196
+ const url = this.publicProxy.accessUrl(code.code);
10197
+ return url ? { code: code.code, url, expiresAt: code.expiresAt } : null;
10198
+ }
9730
10199
  async start() {
9731
10200
  if (this.supervisorLock) {
9732
10201
  mkdirSync8(dirname7(this.supervisorLock), { recursive: true });
@@ -10333,6 +10802,7 @@ Options:
10333
10802
  --host [address] serve on a network address instead of loopback (bare --host means 0.0.0.0)
10334
10803
  --allowed-host <name> with --host, also accept this DNS name as the board's address (repeatable)
10335
10804
  --public-origin <url> serve behind a proxy/tunnel reachable at this exact origin
10805
+ --link print a fresh single-use access link for the running board
10336
10806
  --debug stream the full event feed to the terminal instead of the compact readout
10337
10807
  -h, --help show this help
10338
10808
 
@@ -10340,14 +10810,16 @@ Environment:
10340
10810
  FRIZZ_HOST same as --host
10341
10811
  FRIZZ_ALLOWED_HOSTS same as --allowed-host, comma separated
10342
10812
  FRIZZ_PUBLIC_ORIGIN same as --public-origin
10813
+ FRIZZ_PUBLIC_TOKEN standing secret for HEADLESS boxes that cannot show a QR
10343
10814
 
10344
10815
  --host puts a board that can run shell commands as you on the network, and Frizz has no login: anyone
10345
10816
  who reaches the port controls it. Only do this on a network you trust. An IP address works as-is; to
10346
10817
  reach the board by DNS name you must list that name with --allowed-host ("*" allows any).
10347
10818
 
10348
10819
  --public-origin serves the board through a tunnel or reverse proxy without putting it on the LAN
10349
- at all \u2014 Frizz stays on loopback and the tunnel dials it. Frizz still has no login, so require
10350
- authentication at the proxy: with Cloudflare Access, that is the whole of your access control.`
10820
+ at all \u2014 Frizz stays on loopback and the tunnel dials it. It prints a SINGLE-USE access link, and
10821
+ shows it as a QR so you can scan it from a phone; press L for a fresh one at any time. Scanning it
10822
+ trades the code for a session cookie, so the link itself stops working the moment it is used.`
10351
10823
  );
10352
10824
  process.exit(0);
10353
10825
  }
@@ -10459,15 +10931,17 @@ async function openOrPrint(port, reused, path = "") {
10459
10931
  }
10460
10932
  const network = reused ? [] : networkUrls(port, bind.host);
10461
10933
  const publicOrigin = reused ? void 0 : bind.publicOrigin;
10934
+ const networkFlagsIgnored = reused && (bind.publicOrigin !== void 0 || bindHostIsExposed(bind.host));
10462
10935
  const warnings = [
10463
10936
  ...network.length > 0 ? [EXPOSED_WARNING] : [],
10464
- ...publicOrigin ? [PUBLIC_ORIGIN_WARNING] : []
10937
+ ...publicOrigin ? [PUBLIC_ORIGIN_WARNING] : [],
10938
+ ...networkFlagsIgnored ? [REUSED_NETWORK_FLAGS_WARNING] : []
10465
10939
  ];
10466
10940
  if (!readout) {
10467
10941
  console.log(`${reused ? "reusing" : "started"} Frizz ${PACKAGE_VERSION} for ${workspace.root}`);
10468
10942
  console.log(url);
10469
10943
  for (const address of network) console.log(address);
10470
- if (publicOrigin) console.log(publicOrigin);
10944
+ if (publicOrigin) console.log(`${publicOrigin}/${bind.publicToken ? `?frizz_token=${bind.publicToken}` : ""}`);
10471
10945
  for (const warning of warnings) console.log(warning);
10472
10946
  return;
10473
10947
  }
@@ -10476,7 +10950,7 @@ async function openOrPrint(port, reused, path = "") {
10476
10950
  [
10477
10951
  { label: "Local", value: boardAddress(url), accent: true },
10478
10952
  ...network.map((address) => ({ label: "Network", value: `${address}/`, accent: true })),
10479
- ...publicOrigin ? [{ label: "Public", value: `${publicOrigin}/`, accent: true }] : [],
10953
+ ...publicOrigin ? [{ label: "Public", value: `${publicOrigin}/${bind.publicToken ? `?frizz_token=${bind.publicToken}` : ""}`, accent: true }] : [],
10480
10954
  { label: "Project", value: `${workspace.name} \u2014 ${tildePath(workspace.root, home)}` },
10481
10955
  ...logger.file ? [{ label: "Logs", value: tildePath(logger.file, home) }] : []
10482
10956
  ],
@@ -10525,6 +10999,7 @@ async function runSupervisor(port, token) {
10525
10999
  host: bind.host,
10526
11000
  allowedHosts: bind.allowedHosts,
10527
11001
  ...bind.publicOrigin ? { publicOrigin: bind.publicOrigin } : {},
11002
+ ...bind.publicToken ? { publicToken: bind.publicToken } : {},
10528
11003
  cwd: workspace.root,
10529
11004
  stateDir: workspace.stateDir,
10530
11005
  launchTarget: target,
@@ -10577,6 +11052,7 @@ async function runSupervisor(port, token) {
10577
11052
  });
10578
11053
  process.on("SIGINT", stop);
10579
11054
  process.on("SIGTERM", stop);
11055
+ process.on("SIGHUP", stop);
10580
11056
  void supervisor.stopRequested.then(stop);
10581
11057
  await supervisor.firstBoot;
10582
11058
  return await new Promise(() => {