@saturn-universe/runtime-host 0.0.0-stage → 0.1.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 (116) hide show
  1. package/LICENSE +661 -0
  2. package/dist/builtin-plugins/saturn-plugin-ctf/README.md +13 -0
  3. package/dist/builtin-plugins/saturn-plugin-ctf/index.mjs +1473 -0
  4. package/dist/builtin-plugins/saturn-plugin-ctf/package.json +10 -0
  5. package/dist/builtin-plugins/saturn-plugin-ctf/src/board.mjs +321 -0
  6. package/dist/builtin-plugins/saturn-plugin-ctf/src/ledger.mjs +1143 -0
  7. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/ctfd.mjs +154 -0
  8. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/ctfplus.mjs +769 -0
  9. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/gzctf.mjs +130 -0
  10. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/http.mjs +336 -0
  11. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/index.mjs +133 -0
  12. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/lease.mjs +153 -0
  13. package/dist/builtin-plugins/saturn-plugin-ctf/src/server.mjs +336 -0
  14. package/dist/builtin-plugins/saturn-plugin-ctf/src/view.mjs +714 -0
  15. package/dist/command-dispatch.d.ts +10 -0
  16. package/dist/command-dispatch.js +65 -0
  17. package/dist/completion-judge.d.ts +10 -0
  18. package/dist/completion-judge.js +156 -0
  19. package/dist/composition.d.ts +108 -0
  20. package/dist/composition.js +1180 -0
  21. package/dist/configuration.d.ts +49 -0
  22. package/dist/configuration.js +51 -0
  23. package/dist/context-extensions.d.ts +681 -0
  24. package/dist/context-extensions.js +289 -0
  25. package/dist/cordis/context-core-plugin.d.ts +35 -0
  26. package/dist/cordis/context-core-plugin.js +296 -0
  27. package/dist/cordis/env-probe-plugin.d.ts +27 -0
  28. package/dist/cordis/env-probe-plugin.js +114 -0
  29. package/dist/cordis/host-context.d.ts +65 -0
  30. package/dist/cordis/host-context.js +199 -0
  31. package/dist/cordis/model-responses-plugin.d.ts +81 -0
  32. package/dist/cordis/model-responses-plugin.js +209 -0
  33. package/dist/cordis/plugin-contributions.d.ts +47 -0
  34. package/dist/cordis/plugin-contributions.js +119 -0
  35. package/dist/cordis/plugin-lifecycle.d.ts +57 -0
  36. package/dist/cordis/plugin-lifecycle.js +222 -0
  37. package/dist/cordis/plugin-loader.d.ts +18 -0
  38. package/dist/cordis/plugin-loader.js +310 -0
  39. package/dist/cordis/plugin-sdk-adapter.d.ts +17 -0
  40. package/dist/cordis/plugin-sdk-adapter.js +283 -0
  41. package/dist/cordis/required-host-plugin.d.ts +6 -0
  42. package/dist/cordis/required-host-plugin.js +1 -0
  43. package/dist/cordis/runtime-hooks-plugin.d.ts +23 -0
  44. package/dist/cordis/runtime-hooks-plugin.js +103 -0
  45. package/dist/cordis/sandbox-plugin.d.ts +18 -0
  46. package/dist/cordis/sandbox-plugin.js +21 -0
  47. package/dist/cordis/scoped-layers.d.ts +63 -0
  48. package/dist/cordis/scoped-layers.js +170 -0
  49. package/dist/cordis/tools/builtin-agent-tools-plugin.d.ts +11 -0
  50. package/dist/cordis/tools/builtin-agent-tools-plugin.js +171 -0
  51. package/dist/cordis/tools/index.d.ts +17 -0
  52. package/dist/cordis/tools/index.js +40 -0
  53. package/dist/cordis/tools/mcp-tools-plugin.d.ts +7 -0
  54. package/dist/cordis/tools/mcp-tools-plugin.js +116 -0
  55. package/dist/cordis/tools/process-manager-plugin.d.ts +11 -0
  56. package/dist/cordis/tools/process-manager-plugin.js +39 -0
  57. package/dist/cordis/tools/sandbox-target-tools-plugin.d.ts +13 -0
  58. package/dist/cordis/tools/sandbox-target-tools-plugin.js +255 -0
  59. package/dist/cordis/tools/tool-guidance.d.ts +4 -0
  60. package/dist/cordis/tools/tool-guidance.js +30 -0
  61. package/dist/cordis/tools/tools-core-plugin.d.ts +128 -0
  62. package/dist/cordis/tools/tools-core-plugin.js +486 -0
  63. package/dist/cordis/tools/web-fetch.d.ts +17 -0
  64. package/dist/cordis/tools/web-fetch.js +529 -0
  65. package/dist/cordis/tools/web-search-tools-plugin.d.ts +10 -0
  66. package/dist/cordis/tools/web-search-tools-plugin.js +191 -0
  67. package/dist/cordis/tools/workspace-tools-plugin.d.ts +8 -0
  68. package/dist/cordis/tools/workspace-tools-plugin.js +145 -0
  69. package/dist/env-probe.d.ts +8 -0
  70. package/dist/env-probe.js +172 -0
  71. package/dist/host-configuration.d.ts +27 -0
  72. package/dist/host-configuration.js +185 -0
  73. package/dist/host-tools.d.ts +19 -0
  74. package/dist/host-tools.js +30 -0
  75. package/dist/index.d.ts +2 -0
  76. package/dist/index.js +140 -0
  77. package/dist/ipc.d.ts +24 -0
  78. package/dist/ipc.js +162 -0
  79. package/dist/logger.d.ts +11 -0
  80. package/dist/logger.js +84 -0
  81. package/dist/mcp-configuration.d.ts +17 -0
  82. package/dist/mcp-configuration.js +50 -0
  83. package/dist/modes.d.ts +27 -0
  84. package/dist/modes.js +472 -0
  85. package/dist/ownership.d.ts +7 -0
  86. package/dist/ownership.js +100 -0
  87. package/dist/plugin-configuration.d.ts +9 -0
  88. package/dist/plugin-configuration.js +21 -0
  89. package/dist/plugin-tool-grants.d.ts +18 -0
  90. package/dist/plugin-tool-grants.js +21 -0
  91. package/dist/process-workspaces.d.ts +4 -0
  92. package/dist/process-workspaces.js +28 -0
  93. package/dist/progress.d.ts +30 -0
  94. package/dist/progress.js +699 -0
  95. package/dist/provider-catalog.d.ts +754 -0
  96. package/dist/provider-catalog.js +471 -0
  97. package/dist/run-budget.d.ts +24 -0
  98. package/dist/run-budget.js +47 -0
  99. package/dist/run-checkpoint.d.ts +2 -0
  100. package/dist/run-checkpoint.js +52 -0
  101. package/dist/sandbox-manager.d.ts +111 -0
  102. package/dist/sandbox-manager.js +1519 -0
  103. package/dist/session-paths.d.ts +15 -0
  104. package/dist/session-paths.js +40 -0
  105. package/dist/side-question.d.ts +14 -0
  106. package/dist/side-question.js +89 -0
  107. package/dist/skills-runtime.d.ts +13 -0
  108. package/dist/skills-runtime.js +243 -0
  109. package/dist/token-estimator.d.ts +3 -0
  110. package/dist/token-estimator.js +73 -0
  111. package/dist/tool-result.d.ts +2 -0
  112. package/dist/tool-result.js +91 -0
  113. package/dist/user-config.d.ts +23 -0
  114. package/dist/user-config.js +36 -0
  115. package/package.json +28 -3
  116. package/README.md +0 -3
@@ -0,0 +1,714 @@
1
+ export const styles = String.raw`
2
+ :root { color-scheme: dark; font: 13px ui-monospace, Consolas, monospace; background: #07080c; color: #ebe5da; }
3
+ * { box-sizing: border-box; }
4
+ body { margin: 0; }
5
+ header { height: 54px; border-bottom: 1px solid rgba(255,255,255,0.085); display: flex; align-items: center;
6
+ justify-content: space-between; gap: 12px; padding: 0 clamp(10px, 2.5vw, 36px); }
7
+ .brand { display: flex; align-items: center; gap: 10px; min-width: 0; }
8
+ #session-select { max-width: 170px; background: rgba(255,255,255,0.04); color: #dfc79d;
9
+ border: 1px solid rgba(216,195,158,0.28); border-radius: 5px; padding: 3px 7px;
10
+ font: 11px ui-monospace, Consolas, monospace; cursor: pointer; }
11
+ #session-select option { background: #0c0e15; color: #ebe5da; }
12
+ h1 { min-width: 0; font-size: 14px; font-weight: 600; margin: 0; color: #f2efe9; letter-spacing: .1em;
13
+ text-transform: uppercase; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
14
+ #metrics { display: flex; flex: 0 1 auto; gap: clamp(6px, 2vw, 28px); font-variant-numeric: tabular-nums; white-space: nowrap; }
15
+ .metric { display: flex; align-items: baseline; gap: .55em; }
16
+ .metric-label { font-size: .82em; color: #5c5850; }
17
+ .metric:first-child .metric-value { color: #dfc79d; }
18
+ .metric:nth-child(2) .metric-value { color: #6ee7b7; }
19
+ #orbit { position: fixed; inset: 54px 0 0; }
20
+ canvas { display: block; width: 100%; height: 100%; touch-action: none; cursor: grab; }
21
+ canvas:active { cursor: grabbing; }
22
+ #controls { position: absolute; bottom: 12px; left: 14px; display: flex; gap: 6px; }
23
+ #controls button { padding: 5px 7px; border: 0; background: transparent; color: #5c5850;
24
+ font: 10px ui-monospace, Consolas, monospace; letter-spacing: .12em; cursor: pointer; }
25
+ #controls button:hover, #controls button:focus-visible { color: #f2efe9; }
26
+ #panel { position: absolute; top: 0; left: 0; width: min(312px, calc(100vw - 28px));
27
+ max-height: calc(100% - 28px); overflow: auto; padding: 12px 13px;
28
+ background: rgba(12, 14, 21, 0.92); backdrop-filter: blur(18px);
29
+ border: 1px solid rgba(216, 195, 158, 0.3); border-radius: 10px;
30
+ box-shadow: 0 18px 48px rgba(0,0,0,0.62); overflow-wrap: anywhere;
31
+ font-size: 11px; line-height: 1.45; }
32
+ #panel .eyebrow { display: flex; align-items: center; gap: 7px; min-height: 16px; margin: 0 22px 7px 0;
33
+ color: #b3a896; font-size: 9px; letter-spacing: .09em; text-transform: uppercase; }
34
+ #panel .status-dot { flex: 0 0 5px; height: 5px; border-radius: 50%; background: #dfc79d; }
35
+ #panel .title-row { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; margin-bottom: 8px; }
36
+ #panel h2 { color: #faf6ee; font-size: 14px; margin: 0; }
37
+ #panel .points { color: #dfc79d; white-space: nowrap; }
38
+ #panel .details { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 5px 12px;
39
+ margin: 0; padding: 7px 0; border-block: 1px solid #ffffff12; }
40
+ #panel dt, #panel h3 { color: #a49a8b; font-size: 10px; font-weight: 500; }
41
+ #panel dd { margin: 0; }
42
+ #panel h3 { margin: 8px 0 3px; }
43
+ #panel p { color: #d3cbc0; white-space: pre-wrap; margin: 0; }
44
+ #panel ul { list-style: none; padding: 0; margin: 0; }
45
+ #panel .ledger-entry { margin: 3px 0; border-left: 1px solid #68645e; padding-left: 7px; white-space: pre-wrap; }
46
+ #panel .hypothesis { border-left-color: #dfc79d; color: #dfc79d; }
47
+ #panel .artifacts { color: #b3a896; font: 10px/1.55 ui-monospace, Consolas, monospace; }
48
+ #panel .artifacts li { white-space: pre-wrap; }
49
+ #panel button { font: inherit; color: inherit; background: transparent; border: 0; cursor: pointer; }
50
+ #panel .close { position: absolute; right: 6px; top: 4px; font-size: 19px; line-height: 1; padding: 4px 6px; color: #b3a896; }
51
+ #panel .close:hover, #panel .close:focus-visible { color: #faf6ee; }
52
+ #panel .jump { display: flex; width: 100%; text-align: left; justify-content: space-between;
53
+ gap: 8px; padding: 6px 1px; border-top: 1px solid #ffffff12; }
54
+ #panel .jump:hover, #panel .jump:focus-visible { color: #fff; background: #ffffff12; }
55
+ @media (max-width: 630px) {
56
+ #metrics { font-size: clamp(8px, 2.8vw, 11px); gap: clamp(3px, 2vw, 13px); }
57
+ #panel { max-height: min(56%, calc(100% - 28px)); }
58
+ }
59
+ @media (max-width: 450px) {
60
+ header { display: grid; grid-template-columns: minmax(0, 1fr); align-content: center; gap: 4px; }
61
+ #metrics { justify-self: end; }
62
+ }
63
+ @media (max-width: 320px) {
64
+ .metric { gap: .25em; }
65
+ #metrics { gap: 5px; }
66
+ }
67
+ `;
68
+
69
+ export const clientScript = String.raw`
70
+ const canvas = document.querySelector('canvas');
71
+ const ctx = canvas.getContext('2d');
72
+ const title = document.querySelector('h1');
73
+ const sessionSelect = document.getElementById('session-select');
74
+ const metrics = [...document.querySelectorAll('.metric-value')];
75
+ const panel = document.getElementById('panel');
76
+ const pauseButton = document.getElementById('pause');
77
+ const colors = { solved: '#6ee7b7', running: '#7dd3fc', blocked: '#fbbf24', queued: '#94a3b8' };
78
+ const planetGlyphs = [' ', '·', ':', ';', '+', '*', '#'];
79
+ const planetColors = ['#2b2824', '#524b41', '#857763', '#bca98d', '#e5d8c1', '#faf6ee'];
80
+ const moonGlyphs = ['·', ':', '+', '*'];
81
+ const bg = '#07080c';
82
+ const tau = Math.PI * 2;
83
+ const cameraDistance = 12;
84
+ const defaultYaw = .25, defaultPitch = .36, tiltZ = -.32;
85
+ const cosT = Math.cos(tiltZ), sinT = Math.sin(tiltZ);
86
+ const labelFont = '11px monospace';
87
+ const labelOffset = 23;
88
+ const tokenFormat = new Intl.NumberFormat('zh-CN', { notation: 'compact' });
89
+ const clamp = (value, low, high) => Math.max(low, Math.min(high, value));
90
+ const smoothstep = (low, high, value) => {
91
+ const t = clamp((value - low) / (high - low), 0, 1);
92
+ return t * t * (3 - 2 * t);
93
+ };
94
+ const stars = Array.from({ length: 90 }, (_, i) => [
95
+ (i * .618034 + .47) % 1, (i * .754878 + .19) % 1, .11 + .24 * ((i * .414214) % 1),
96
+ ]);
97
+ const ringRadii = [1.38, 1.48, 1.58, 1.68, 1.92, 2.04, 2.16];
98
+ const ringSamples = 220;
99
+ const ringLight = { x: -.54, y: -.42, z: .73 };
100
+ const ringLightLength = Math.hypot(ringLight.x, ringLight.y, ringLight.z);
101
+ const ringLayers = ringRadii.map((r, layer) => Array.from({ length: ringSamples }, (_, i) => {
102
+ const a = (i + layer * .19) * tau / ringSamples;
103
+ const x0 = r * Math.cos(a);
104
+ const pt = { x: x0 * cosT, y: x0 * sinT, z: r * Math.sin(a) };
105
+ const projSun = pt.x * ringLight.x + pt.y * ringLight.y + pt.z * ringLight.z;
106
+ const perpDist = Math.sqrt(Math.max(0, r * r - (projSun / ringLightLength) ** 2));
107
+ const shadowFactor = projSun < 0 ? .18 + .82 * smoothstep(.72, 1.32, perpDist) : 1;
108
+ const sunBias = .86 + .14 * (projSun / r);
109
+ return { pt, brightness: shadowFactor * sunBias * (layer < 4 ? .89 : .72),
110
+ glyph: i % 17 === 0 ? ':' : '·' };
111
+ }));
112
+
113
+ let board = { metadata: {}, challenges: [], revision: -1 };
114
+ let boardSessionId;
115
+ const initialParams = new URLSearchParams(location.search);
116
+ let requestedSessionId = initialParams.get('session') || initialParams.get('sessionId') || '';
117
+ let stream;
118
+ const phases = new Map();
119
+ let selected;
120
+ let ledger;
121
+ let detailRequest;
122
+ let elapsedField;
123
+ let width = 1, height = 1, camPitch = defaultPitch, camYaw = defaultYaw;
124
+ let targetPitch = camPitch, targetYaw = camYaw, cosY, sinY, cosP, sinP;
125
+ let spin = 0, helperTime = 0, paused = false, lastTime = 0, lastTelemetry = 0;
126
+ let pointer, hover;
127
+ let hit = [], center = { x: 0, y: 0, r: 0 };
128
+
129
+ function updateTelemetry(now = Date.now()) {
130
+ const items = board.challenges;
131
+ const solved = items.filter((item) => item.status === 'solved');
132
+ const running = items.filter((item) => item.status === 'running').length;
133
+ const seconds = Math.max(0, Math.ceil((Date.parse(board.metadata.endTime) - now) / 1000));
134
+ const two = (v) => String(v).padStart(2, '0');
135
+ const countdown = Number.isFinite(seconds)
136
+ ? [Math.floor(seconds / 3600), Math.floor(seconds / 60) % 60, seconds % 60].map(two).join(':') : '—';
137
+ const values = [
138
+ countdown, two(solved.length) + '/' + two(items.length), running,
139
+ solved.reduce((n, item) => n + (item.points || 0), 0),
140
+ tokenFormat.format(items.reduce((n, item) => n + (item.tokens || 0), 0)),
141
+ ];
142
+ values.forEach((value, index) => { metrics[index].textContent = value; });
143
+ if (elapsedField) elapsedField.textContent = formatElapsed(challengeElapsed(
144
+ items.find((item) => item.id === selected), now));
145
+ }
146
+
147
+ function resize() {
148
+ const rect = canvas.getBoundingClientRect();
149
+ width = Math.max(1, rect.width);
150
+ height = Math.max(1, rect.height);
151
+ const scale = Math.min(2, devicePixelRatio || 1);
152
+ canvas.width = Math.round(width * scale);
153
+ canvas.height = Math.round(height * scale);
154
+ ctx.setTransform(scale, 0, 0, scale, 0, 0);
155
+ }
156
+ new ResizeObserver(resize).observe(canvas);
157
+ resize();
158
+
159
+ function rotate({ x, y, z }) {
160
+ const x1 = x * cosY + z * sinY;
161
+ const z1 = -x * sinY + z * cosY;
162
+ return { x: x1, y: y * cosP + z1 * sinP, z: -y * sinP + z1 * cosP };
163
+ }
164
+
165
+ function project(p, radius = center.r) {
166
+ const scale = cameraDistance / Math.max(3.5, cameraDistance - p.z);
167
+ return { x: center.x + p.x * radius * scale, y: center.y + p.y * radius * scale, z: p.z };
168
+ }
169
+
170
+ function projectRings() {
171
+ const rear = [], front = [];
172
+ const stride = center.r < 70 ? 2 : 1;
173
+ for (const layer of ringLayers) {
174
+ for (let index = 0; index < layer.length; index += stride) {
175
+ const { pt, brightness, glyph } = layer[index];
176
+ const p = project(rotate(pt));
177
+ const depthEase = .42 + .58 * (.5 + .5 * Math.tanh(p.z * .85));
178
+ (p.z < 0 ? rear : front).push({ x: p.x, y: p.y, i: depthEase * brightness, glyph });
179
+ }
180
+ }
181
+ return { rear, front };
182
+ }
183
+
184
+ function paintRings(points) {
185
+ ctx.font = '10px monospace';
186
+ for (const { x, y, i, glyph } of points) {
187
+ ctx.fillStyle = 'rgba(' + Math.round(92 + 153 * i) + ',' + Math.round(82 + 151 * i) + ','
188
+ + Math.round(68 + 142 * i) + ',' + (.24 + .72 * i) + ')';
189
+ ctx.fillText(glyph, x, y);
190
+ }
191
+ }
192
+
193
+ function disc(x, y, r) {
194
+ ctx.beginPath();
195
+ ctx.arc(x, y, r, 0, tau);
196
+ ctx.fill();
197
+ }
198
+
199
+ function paintPlanet() {
200
+ const { x, y, r } = center;
201
+ ctx.fillStyle = bg;
202
+ disc(x, y, .99 * r);
203
+ const cell = clamp(r / 12, 7.2, 10);
204
+ ctx.font = (cell * 1.15) + 'px monospace';
205
+ const axis = rotate({ x: -sinT, y: cosT, z: 0 });
206
+ const meridian = rotate({ x: cosT, y: sinT, z: 0 });
207
+ const equator = rotate({ x: 0, y: 0, z: 1 });
208
+ const cosSpin = Math.cos(spin), sinSpin = Math.sin(spin);
209
+ const bound = Math.floor(r / cell) * cell;
210
+ for (let dy = -bound; dy <= bound; dy += cell) {
211
+ for (let dx = -bound; dx <= bound; dx += cell) {
212
+ const nx = dx / r, ny = dy / r, rr = nx * nx + ny * ny;
213
+ if (rr > 1) continue;
214
+ const nz = Math.sqrt(1 - rr);
215
+ const light = Math.max(0, -.52 * nx - .44 * ny + .73 * nz);
216
+ const latitude = axis.x * nx + axis.y * ny + axis.z * nz;
217
+ const longitude = (meridian.x * nx + meridian.y * ny + meridian.z * nz) * cosSpin
218
+ + (equator.x * nx + equator.y * ny + equator.z * nz) * sinSpin;
219
+ const belts = .071 * Math.sin(latitude * 29 + .38 * Math.sin(longitude * 8))
220
+ + .032 * Math.cos(latitude * 61 + longitude);
221
+ const tone = clamp((.15 + .85 * light + belts) * Math.pow(nz, .35), 0, 1);
222
+ ctx.fillStyle = planetColors[Math.round(tone * (planetColors.length - 1))];
223
+ ctx.fillText(planetGlyphs[Math.round(tone * (planetGlyphs.length - 1))], x + dx, y + dy);
224
+ }
225
+ }
226
+ }
227
+
228
+ function tinySphere(x, y, radius, color) {
229
+ const halo = ctx.createRadialGradient(x, y, radius * .55, x, y, radius * 1.55);
230
+ halo.addColorStop(0, color + '44');
231
+ halo.addColorStop(1, color + '00');
232
+ ctx.fillStyle = halo;
233
+ disc(x, y, radius * 1.55);
234
+ ctx.fillStyle = bg;
235
+ disc(x, y, radius);
236
+ ctx.font = '7px monospace';
237
+ for (let row = -2; row <= 2; row++) {
238
+ for (let col = -2; col <= 2; col++) {
239
+ const nx = col / 2.2, ny = row / 2.2, rr = nx * nx + ny * ny;
240
+ if (rr > 1) continue;
241
+ const nz = Math.sqrt(1 - rr);
242
+ const tone = clamp((.19 - .52 * nx - .44 * ny + .73 * nz) * Math.pow(nz, .35), 0, 1);
243
+ ctx.fillStyle = tone >= .81 ? '#faf6ee' : tone >= .45 ? color : color + '65';
244
+ ctx.fillText(moonGlyphs[Math.round(tone * (moonGlyphs.length - 1))],
245
+ x + nx * radius * .92, y + ny * radius * .92);
246
+ }
247
+ }
248
+ }
249
+
250
+ function orbit(theta, inclination, radius) {
251
+ const swing = Math.sin(theta);
252
+ return project(rotate({
253
+ x: radius * Math.cos(theta),
254
+ y: radius * swing * Math.sin(inclination),
255
+ z: radius * swing * Math.cos(inclination),
256
+ }));
257
+ }
258
+
259
+ function fitLabel(label, maxWidth) {
260
+ if (ctx.measureText(label).width <= maxWidth) return label;
261
+ if (ctx.measureText('…').width > maxWidth) return '';
262
+ const chars = [...label];
263
+ let low = 0, high = Math.min(chars.length, Math.ceil(maxWidth));
264
+ while (low < high) {
265
+ const mid = Math.ceil((low + high) / 2);
266
+ if (ctx.measureText(chars.slice(0, mid).join('') + '…').width <= maxWidth) low = mid;
267
+ else high = mid - 1;
268
+ }
269
+ return chars.slice(0, low).join('') + '…';
270
+ }
271
+
272
+ function paintSatellite(satellite, hovered) {
273
+ const { item, p, theta, radius, inclination, label } = satellite;
274
+ const color = colors[item.status] || colors.queued;
275
+ const locked = selected === item.id;
276
+ const dustCount = locked ? 44 : 26;
277
+ ctx.fillStyle = color;
278
+ for (let k = dustCount - 1; k >= 0; k--) {
279
+ const dust = orbit(theta - (k + 1) * .012, inclination, radius);
280
+ const fade = 1 - k / dustCount;
281
+ ctx.globalAlpha = Math.pow(fade, 1.8) * .32;
282
+ disc(dust.x, dust.y, .95 + .35 * fade);
283
+ }
284
+ ctx.globalAlpha = 1;
285
+ const helpers = (item.helpers || []).map((_, index, list) => {
286
+ const a = helperTime + index * tau / list.length;
287
+ return rotate({ x: Math.cos(a) * cosT, y: Math.cos(a) * sinT, z: Math.sin(a) });
288
+ });
289
+ function paintHelpers(front) {
290
+ ctx.font = '9px monospace';
291
+ ctx.fillStyle = color;
292
+ for (const helper of helpers) {
293
+ if ((helper.z >= 0) !== front) continue;
294
+ ctx.globalAlpha = .55 + .28 * helper.z;
295
+ const scale = 17 / (1 - .12 * helper.z);
296
+ ctx.fillText('·', p.x + helper.x * scale, p.y + helper.y * scale);
297
+ }
298
+ ctx.globalAlpha = 1;
299
+ }
300
+ paintHelpers(false);
301
+ tinySphere(p.x, p.y, 9.5 + clamp(p.z * .35, -1, 1), color);
302
+ paintHelpers(true);
303
+ ctx.font = labelFont;
304
+ ctx.strokeStyle = 'rgba(7, 8, 12, 0.88)';
305
+ ctx.lineWidth = 3;
306
+ ctx.lineJoin = 'round';
307
+ ctx.strokeText(label, p.x, p.y - labelOffset);
308
+ ctx.fillStyle = locked || hovered ? '#faf6ee' : 'rgba(235, 229, 218, 0.78)';
309
+ ctx.fillText(label, p.x, p.y - labelOffset);
310
+ if (locked) {
311
+ ctx.strokeStyle = '#dfc79d';
312
+ ctx.lineWidth = 1;
313
+ ctx.beginPath();
314
+ for (const sx of [-1, 1]) for (const sy of [-1, 1]) {
315
+ const x = p.x + sx * 14, y = p.y + sy * 14;
316
+ ctx.moveTo(x - sx * 5, y);
317
+ ctx.lineTo(x, y);
318
+ ctx.lineTo(x, y - sy * 5);
319
+ }
320
+ ctx.stroke();
321
+ }
322
+ }
323
+
324
+ function positionPanel(anchor, anchorRadius, labelHalfWidth = 0) {
325
+ if (!anchor || panel.hidden) return;
326
+ const boxWidth = panel.offsetWidth, boxHeight = panel.offsetHeight;
327
+ const margin = 14;
328
+ const maxX = Math.max(margin, width - boxWidth - margin);
329
+ const maxY = Math.max(margin, height - boxHeight - margin);
330
+ const gap = anchorRadius + 19;
331
+ const sideGap = Math.max(gap, labelHalfWidth + 8);
332
+ const right = anchor.x + sideGap, left = anchor.x - sideGap - boxWidth;
333
+ let x, y;
334
+ if (right <= maxX || left >= margin) {
335
+ x = right <= maxX ? right : left;
336
+ y = clamp(anchor.y - boxHeight * .36, margin, maxY);
337
+ } else {
338
+ x = clamp(anchor.x - boxWidth / 2, margin, maxX);
339
+ const below = anchor.y + gap, above = anchor.y - gap - boxHeight;
340
+ y = below <= maxY ? below : above >= margin ? above : anchor.y < height / 2 ? maxY : margin;
341
+ }
342
+ x = Math.round(x);
343
+ y = Math.round(y);
344
+ const transform = 'translate(' + x + 'px, ' + y + 'px)';
345
+ if (panel.style.transform !== transform) panel.style.transform = transform;
346
+ const nearestX = clamp(anchor.x, x, x + boxWidth);
347
+ const nearestY = clamp(anchor.y, y, y + boxHeight);
348
+ const dx = nearestX - anchor.x, dy = nearestY - anchor.y;
349
+ const distance = Math.hypot(dx, dy);
350
+ const start = Math.min(anchorRadius, distance / 2);
351
+ if (!distance) return;
352
+ ctx.strokeStyle = 'rgba(223, 199, 157, 0.35)';
353
+ ctx.lineWidth = 1;
354
+ ctx.beginPath();
355
+ ctx.moveTo(anchor.x + dx * start / distance, anchor.y + dy * start / distance);
356
+ ctx.lineTo(nearestX, nearestY);
357
+ ctx.stroke();
358
+ }
359
+
360
+ function satelliteAt(x, y) {
361
+ const behindPlanet = Math.hypot(x - center.x, y - center.y) <= .99 * center.r;
362
+ for (let i = hit.length - 1; i >= 0; i--) {
363
+ const { p, labelHalfWidth } = hit[i];
364
+ if (p.z < 0 && behindPlanet) continue;
365
+ if (Math.hypot(x - p.x, y - p.y) <= 16
366
+ || (labelHalfWidth > 0 && Math.abs(x - p.x) <= labelHalfWidth + 3
367
+ && Math.abs(y - p.y + labelOffset) <= 7)) return hit[i];
368
+ }
369
+ }
370
+
371
+ function frame(timestamp) {
372
+ const tick = lastTime ? clamp((timestamp - lastTime) / (1000 / 60), 0, 3) : 1;
373
+ lastTime = timestamp;
374
+ if (!paused) {
375
+ spin = (spin + .0024 * tick) % tau;
376
+ helperTime = (helperTime + .008 * tick) % tau;
377
+ }
378
+ camPitch += (targetPitch - camPitch) * .14;
379
+ camYaw += (targetYaw - camYaw) * .14;
380
+ cosY = Math.cos(camYaw);
381
+ sinY = Math.sin(camYaw);
382
+ cosP = Math.cos(camPitch);
383
+ sinP = Math.sin(camPitch);
384
+ if (timestamp - lastTelemetry >= 1000) {
385
+ updateTelemetry();
386
+ lastTelemetry = timestamp;
387
+ }
388
+ ctx.fillStyle = bg;
389
+ ctx.fillRect(0, 0, width, height);
390
+ for (const [x, y, a] of stars) {
391
+ ctx.fillStyle = 'rgba(216,221,245,' + a + ')';
392
+ ctx.fillRect(x * width + sinY * a * 21, y * height + camPitch * a * 15, a > .31 ? 1.4 : 1, 1);
393
+ }
394
+ ctx.textAlign = 'center';
395
+ ctx.textBaseline = 'middle';
396
+ center = { x: width / 2, y: height / 2, r: Math.max(1, Math.min(width * .19, height * .218, 218)) };
397
+ ctx.font = labelFont;
398
+ const labelWidth = Math.min(146, width * .34);
399
+ const safeOffset = Math.max(0, Math.min(width / 2 - Math.max(23, labelWidth / 2 + 6), height / 2 - 34));
400
+ // Invert the maximum perspective displacement of a sphere of possible orbital positions.
401
+ const safeUnits = safeOffset / center.r;
402
+ const maxSafeOrbitR = Math.min(6, cameraDistance * safeUnits / Math.hypot(cameraDistance, safeUnits));
403
+ const orbiting = board.challenges.filter((item) => item.status === 'running');
404
+ const activeIds = new Set(orbiting.map((item) => item.id));
405
+ for (const id of phases.keys()) if (!activeIds.has(id)) phases.delete(id);
406
+ hit = orbiting.map((item, i, list) => {
407
+ let theta = phases.get(item.id) ?? (i * tau / list.length + .26);
408
+ if (!paused && selected !== item.id) theta = (theta + (.0006 + ((i * 7) % 11) * .00009) * tick) % tau;
409
+ phases.set(item.id, theta);
410
+ const fraction = .64 + (i % 4) * .12;
411
+ const radius = Math.min(maxSafeOrbitR, Math.max(1.24, maxSafeOrbitR * fraction));
412
+ const inclination = (i % 5 - 2) * .19;
413
+ const p = orbit(theta, inclination, radius);
414
+ const label = fitLabel(item.title, labelWidth);
415
+ return { item, theta, radius, inclination, label, p, labelHalfWidth: ctx.measureText(label).width / 2 };
416
+ }).sort((a, b) => a.p.z - b.p.z);
417
+ const hovered = hover && !pointer?.dragged ? satelliteAt(hover.x, hover.y) : undefined;
418
+ const rings = projectRings();
419
+ for (const satellite of hit) if (satellite.p.z < 0) paintSatellite(satellite, satellite === hovered);
420
+ paintRings(rings.rear);
421
+ paintPlanet();
422
+ paintRings(rings.front);
423
+ for (const satellite of hit) if (satellite.p.z >= 0) paintSatellite(satellite, satellite === hovered);
424
+ if (selected === null) positionPanel(center, center.r);
425
+ else if (selected !== undefined) {
426
+ const locked = hit.find(({ item }) => item.id === selected);
427
+ if (locked) positionPanel(locked.p, 14, locked.labelHalfWidth);
428
+ else if (board.challenges.some((item) => item.id === selected)) positionPanel(center, center.r);
429
+ }
430
+ requestAnimationFrame(frame);
431
+ }
432
+
433
+ function element(tag, text, className) {
434
+ const node = document.createElement(tag);
435
+ node.textContent = text;
436
+ if (className) node.className = className;
437
+ return node;
438
+ }
439
+
440
+ function challengeElapsed(item, now = Date.now()) {
441
+ return item?.status === 'running' && item.startedAt ? now - Date.parse(item.startedAt) : item?.elapsedMs;
442
+ }
443
+
444
+ function formatElapsed(elapsed) {
445
+ return Number.isFinite(elapsed) ? (Math.max(0, elapsed) / 1000).toFixed(1) + ' s' : '—';
446
+ }
447
+
448
+ function renderPanel() {
449
+ elapsedField = undefined;
450
+ panel.hidden = selected === undefined;
451
+ if (panel.hidden) return;
452
+ const item = board.challenges.find((item) => item.id === selected);
453
+ const close = element('button', '×', 'close');
454
+ close.setAttribute('aria-label', '关闭');
455
+ close.onclick = () => select(undefined);
456
+ const eyebrow = element('div', '', 'eyebrow');
457
+ const dot = element('span', '', 'status-dot');
458
+ if (item) dot.style.backgroundColor = colors[item.status] || colors.queued;
459
+ eyebrow.append(dot, element('span', item
460
+ ? [item.category || '—', item.status, 'ORBIT LOCKED'].join(' · ') : '任务调度'));
461
+ const titleRow = element('div', '', 'title-row');
462
+ titleRow.append(element('h2', item?.title || '调度总览'));
463
+ if (item) titleRow.append(element('span', item.points == null ? '—' : item.points + ' pts', 'points'));
464
+ panel.replaceChildren(eyebrow, close, titleRow);
465
+ function section(label, value) {
466
+ if (value) panel.append(element('h3', label), element('p', value));
467
+ }
468
+ if (!item) {
469
+ const order = { running: 0, blocked: 1, solved: 2, queued: 3 };
470
+ const sorted = [...board.challenges].sort(
471
+ (a, b) => (order[a.status] ?? 4) - (order[b.status] ?? 4),
472
+ );
473
+ section('当前调度', board.challenges.length + ' 项 · ' + board.challenges.filter((ch) => ch.status === 'running').length
474
+ + '/' + (board.settings?.maxActiveChallenges ?? '—') + ' 运行');
475
+ for (const challenge of sorted) {
476
+ const button = element('button', '', 'jump');
477
+ const status = element('span', challenge.status);
478
+ status.style.color = colors[challenge.status];
479
+ button.append(element('span', challenge.title), status);
480
+ button.onclick = () => select(challenge.id);
481
+ panel.append(button);
482
+ }
483
+ return;
484
+ }
485
+ const details = element('dl', '', 'details');
486
+ const elapsed = challengeElapsed(item);
487
+ elapsedField = element('dd', formatElapsed(elapsed));
488
+ for (const [label, value] of [
489
+ ['Solver', element('dd', item.worker || '—')],
490
+ ['Helpers', element('dd', (item.helpers || []).join('、') || '—')],
491
+ ['耗时', elapsedField],
492
+ ['Token', element('dd', item.tokens ?? '—')],
493
+ ]) {
494
+ const pair = element('div', '');
495
+ pair.append(element('dt', label), value);
496
+ details.append(pair);
497
+ }
498
+ panel.append(details);
499
+ if (item.status === 'running' && elapsed >= board.settings?.perChallengeWallTimeMs)
500
+ section('时限', '已达到单题时限');
501
+ section('任务描述', item.description || '—');
502
+ section('摘要', item.summary);
503
+ const entries = element('ul', '');
504
+ for (const [records, className] of [
505
+ [ledger?.facts || [], 'ledger-entry'], [ledger?.hypotheses || [], 'ledger-entry hypothesis'],
506
+ ]) {
507
+ for (const entry of records) entries.append(element('li', entry.id + ' ' + (entry.summary || entry.title)
508
+ + (entry.evidence ? ' · ' + entry.evidence : ''), className));
509
+ }
510
+ panel.append(element('h3', 'Ledger'), entries.childElementCount ? entries : element('p', '—'));
511
+ const artifacts = element('ul', '', 'artifacts');
512
+ for (const path of item.artifacts || []) artifacts.append(element('li', path));
513
+ panel.append(element('h3', '产物路径'), artifacts.childElementCount ? artifacts : element('p', '—'));
514
+ }
515
+
516
+ async function loadLedger() {
517
+ detailRequest?.abort();
518
+ if (typeof selected !== 'string') return;
519
+ const id = selected;
520
+ const request = new AbortController();
521
+ detailRequest = request;
522
+ try {
523
+ const query = '?challengeId=' + encodeURIComponent(id)
524
+ + (requestedSessionId ? '&sessionId=' + encodeURIComponent(requestedSessionId) : '');
525
+ const response = await fetch('/api/board' + query, { signal: request.signal });
526
+ if (!response.ok) return;
527
+ const value = await response.json();
528
+ if (!request.signal.aborted && selected === id) {
529
+ ledger = value.ledger;
530
+ renderPanel();
531
+ }
532
+ } catch {
533
+ // The live stream or the next selection can refresh the detail.
534
+ }
535
+ }
536
+
537
+ function select(id) {
538
+ selected = selected === id ? undefined : id;
539
+ ledger = undefined;
540
+ renderPanel();
541
+ void loadLedger();
542
+ }
543
+
544
+ canvas.addEventListener('pointerdown', (event) => {
545
+ if (pointer || event.button !== 0) return;
546
+ pointer = { id: event.pointerId, x: event.clientX, y: event.clientY, pitch: targetPitch, yaw: targetYaw, dragged: false };
547
+ canvas.setPointerCapture(pointer.id);
548
+ });
549
+ canvas.addEventListener('pointermove', (event) => {
550
+ const rect = canvas.getBoundingClientRect();
551
+ if (event.pointerType !== 'touch') hover = { x: event.clientX - rect.left, y: event.clientY - rect.top };
552
+ if (pointer?.id !== event.pointerId) return;
553
+ const dx = event.clientX - pointer.x, dy = event.clientY - pointer.y;
554
+ if (!pointer.dragged && Math.hypot(dx, dy) < 5) return;
555
+ pointer.dragged = true;
556
+ targetYaw = pointer.yaw + dx * .007;
557
+ targetPitch = clamp(pointer.pitch - dy * .006, -1.1, 1.1);
558
+ });
559
+ canvas.addEventListener('pointerup', (event) => {
560
+ if (pointer?.id !== event.pointerId) return;
561
+ const { dragged } = pointer;
562
+ pointer = undefined;
563
+ if (dragged) return;
564
+ const rect = canvas.getBoundingClientRect();
565
+ const x = event.clientX - rect.left, y = event.clientY - rect.top;
566
+ const candidate = satelliteAt(x, y);
567
+ select(candidate ? candidate.item.id : Math.hypot(x - center.x, y - center.y) <= center.r ? null : undefined);
568
+ });
569
+ canvas.addEventListener('pointerleave', () => { hover = undefined; });
570
+ canvas.addEventListener('lostpointercapture', (event) => { if (pointer?.id === event.pointerId) pointer = undefined; });
571
+ canvas.addEventListener('keydown', (event) => { if (event.key === 'Enter') select(null); });
572
+ document.addEventListener('keydown', (event) => { if (event.key === 'Escape') select(undefined); });
573
+
574
+ pauseButton.addEventListener('click', () => {
575
+ paused = !paused;
576
+ pauseButton.textContent = paused ? 'RESUME' : 'PAUSE';
577
+ });
578
+ document.getElementById('reset').addEventListener('click', () => {
579
+ camYaw = targetYaw = defaultYaw;
580
+ camPitch = targetPitch = defaultPitch;
581
+ spin = helperTime = 0;
582
+ phases.clear();
583
+ select(undefined);
584
+ });
585
+
586
+ function sessionQuery() {
587
+ return requestedSessionId ? '?sessionId=' + encodeURIComponent(requestedSessionId) : '';
588
+ }
589
+
590
+ function accept(value) {
591
+ if (!value || typeof value !== 'object') return;
592
+ const incomingSession = value.sessionId || boardSessionId;
593
+ if (boardSessionId && incomingSession === boardSessionId && value.revision < board.revision) return;
594
+ boardSessionId = incomingSession;
595
+ if (!requestedSessionId && incomingSession) requestedSessionId = incomingSession;
596
+ board = value;
597
+ const ids = new Set(value.challenges.map((item) => item.id));
598
+ for (const id of phases.keys()) if (!ids.has(id)) phases.delete(id);
599
+ if (typeof selected === 'string' && !ids.has(selected)) selected = undefined;
600
+ title.textContent = value.metadata.title;
601
+ document.title = value.metadata.title;
602
+ updateTelemetry();
603
+ renderPanel();
604
+ void loadLedger();
605
+ }
606
+
607
+ async function fetchBoardNow() {
608
+ try {
609
+ const response = await fetch('/api/board' + sessionQuery());
610
+ if (response.ok) accept(await response.json());
611
+ } catch {
612
+ // Next SSE frame or fallback timer will retry.
613
+ }
614
+ }
615
+
616
+ async function refreshSessions() {
617
+ try {
618
+ const response = await fetch('/api/sessions');
619
+ if (!response.ok) return;
620
+ const data = await response.json();
621
+ const list = Array.isArray(data.sessions) ? data.sessions : [];
622
+ const active = requestedSessionId || data.defaultSessionId || '';
623
+ if (list.length > 1) {
624
+ sessionSelect.hidden = false;
625
+ sessionSelect.replaceChildren();
626
+ for (const s of list) {
627
+ const opt = document.createElement('option');
628
+ opt.value = s.id;
629
+ const solvedText = typeof s.solved === 'number' && typeof s.total === 'number'
630
+ ? ' (' + s.solved + '/' + s.total + ')' : '';
631
+ opt.textContent = (s.id === 'legacy' ? 'legacy' : s.id.slice(0, 8))
632
+ + (s.title ? ' · ' + s.title : '') + solvedText;
633
+ if (s.id === active) opt.selected = true;
634
+ sessionSelect.append(opt);
635
+ }
636
+ } else {
637
+ sessionSelect.hidden = true;
638
+ }
639
+ } catch {
640
+ // Optional multi-session list failure does not block current board.
641
+ }
642
+ }
643
+
644
+ function connectStream() {
645
+ if (stream) stream.close();
646
+ stream = new EventSource('/api/events' + sessionQuery());
647
+ stream.onmessage = (event) => accept(JSON.parse(event.data));
648
+ stream.onerror = () => {
649
+ void fetchBoardNow();
650
+ };
651
+ }
652
+
653
+ sessionSelect.addEventListener('change', () => {
654
+ requestedSessionId = sessionSelect.value;
655
+ boardSessionId = undefined;
656
+ board = { metadata: {}, challenges: [], revision: -1 };
657
+ selected = undefined;
658
+ ledger = undefined;
659
+ phases.clear();
660
+ const nextUrl = new URL(location.href);
661
+ if (requestedSessionId) nextUrl.searchParams.set('session', requestedSessionId);
662
+ else nextUrl.searchParams.delete('session');
663
+ nextUrl.searchParams.delete('sessionId');
664
+ history.replaceState(null, '', nextUrl);
665
+ connectStream();
666
+ void fetchBoardNow();
667
+ });
668
+
669
+ connectStream();
670
+ void fetchBoardNow();
671
+ void refreshSessions();
672
+ setInterval(() => {
673
+ if (!stream || stream.readyState !== 1) void fetchBoardNow();
674
+ }, 5_000);
675
+ setInterval(() => {
676
+ void fetchBoardNow();
677
+ void refreshSessions();
678
+ }, 15_000);
679
+ requestAnimationFrame(frame);
680
+ `;
681
+
682
+ export const boardHtml = `<!doctype html>
683
+ <html lang="zh-CN">
684
+ <head>
685
+ <meta charset="utf-8">
686
+ <meta name="viewport" content="width=device-width,initial-scale=1">
687
+ <title>Saturn</title>
688
+ <style>${styles}</style>
689
+ </head>
690
+ <body>
691
+ <header>
692
+ <div class="brand">
693
+ <h1>Saturn</h1>
694
+ <select id="session-select" hidden aria-label="切换会话"></select>
695
+ </div>
696
+ <div id="metrics">
697
+ <span class="metric"><span class="metric-label">剩余</span><span class="metric-value">—</span></span>
698
+ <span class="metric"><span class="metric-label">完成</span><span class="metric-value">00/00</span></span>
699
+ <span class="metric"><span class="metric-label">运行</span><span class="metric-value">0</span></span>
700
+ <span class="metric"><span class="metric-label">得分</span><span class="metric-value">0</span></span>
701
+ <span class="metric"><span class="metric-label">消耗</span><span class="metric-value">0</span></span>
702
+ </div>
703
+ </header>
704
+ <main id="orbit">
705
+ <canvas tabindex="0" aria-label="任务星轨,按 Enter 打开调度总览"></canvas>
706
+ <div id="controls" role="group" aria-label="星轨控制">
707
+ <button id="pause" type="button">PAUSE</button>
708
+ <button id="reset" type="button">RESET</button>
709
+ </div>
710
+ <section id="panel" aria-label="任务详情" hidden></section>
711
+ </main>
712
+ <script>${clientScript}</script>
713
+ </body>
714
+ </html>`;