toolroll 0.9.129 → 0.9.131

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 (155) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/dist/agent-fence.js +0 -2
  3. package/dist/agent-state.js +1 -1
  4. package/dist/agents-board.js +0 -3
  5. package/dist/assignment.js +4 -3
  6. package/dist/backup-ui.js +6 -3
  7. package/dist/bounded-spawn.js +0 -1
  8. package/dist/browser/manifest.json +57 -0
  9. package/dist/browser/terminal.4d1cf20c32ad7c2099df657358d540d5fd92bb55195a88121e74b28467238b42.css.br +0 -0
  10. package/dist/browser/terminal.4d1cf20c32ad7c2099df657358d540d5fd92bb55195a88121e74b28467238b42.css.gz +0 -0
  11. package/dist/browser/{terminal.js → terminal.8978c8cbb268e1006f4b0be371c2401b58078e6d9f1380f4a5c2a12da843909f.js} +1 -1
  12. package/dist/browser/terminal.8978c8cbb268e1006f4b0be371c2401b58078e6d9f1380f4a5c2a12da843909f.js.br +0 -0
  13. package/dist/browser/terminal.8978c8cbb268e1006f4b0be371c2401b58078e6d9f1380f4a5c2a12da843909f.js.gz +0 -0
  14. package/dist/browser/{workspace.js → workspace.4f5935dc80574baadf1adafd39a08c567fb1fac1323052ca355546622f9b06d2.js} +25 -25
  15. package/dist/browser/workspace.4f5935dc80574baadf1adafd39a08c567fb1fac1323052ca355546622f9b06d2.js.br +0 -0
  16. package/dist/browser/workspace.4f5935dc80574baadf1adafd39a08c567fb1fac1323052ca355546622f9b06d2.js.gz +0 -0
  17. package/dist/browser/{workspace.css → workspace.a0752f935cfeaf16758d1085fe8f3e1719a7cd525b91a9c9943c789d65879a54.css} +1 -1
  18. package/dist/browser/workspace.a0752f935cfeaf16758d1085fe8f3e1719a7cd525b91a9c9943c789d65879a54.css.br +0 -0
  19. package/dist/browser/workspace.a0752f935cfeaf16758d1085fe8f3e1719a7cd525b91a9c9943c789d65879a54.css.gz +0 -0
  20. package/dist/browser-shell.js +271 -25
  21. package/dist/builder-restart.js +13 -4
  22. package/dist/builder.js +4 -1
  23. package/dist/canvas-freshness.js +122 -0
  24. package/dist/canvas-fs.js +273 -0
  25. package/dist/canvas-reads.js +747 -0
  26. package/dist/canvas-state-key.js +45 -0
  27. package/dist/canvas-state-worker.js +12 -0
  28. package/dist/central-recovery-stage.js +3 -3
  29. package/dist/chat-actions.js +26 -0
  30. package/dist/chat-channel.js +4 -3
  31. package/dist/chat-follow.js +4 -0
  32. package/dist/chat-task-actions.js +1 -1
  33. package/dist/chat-warmth.js +0 -1
  34. package/dist/check-report.js +0 -6
  35. package/dist/commit-extract.js +79 -40
  36. package/dist/companion/access.js +1 -0
  37. package/dist/companion/actions.js +79 -16
  38. package/dist/companion/canvas.js +141 -0
  39. package/dist/companion/chat-origin.js +92 -0
  40. package/dist/companion/chat.js +571 -0
  41. package/dist/companion/daemon.js +46 -5
  42. package/dist/companion/finish.js +51 -0
  43. package/dist/companion/reads.js +5 -1
  44. package/dist/companion/schema.js +64 -0
  45. package/dist/companion/service.js +1 -0
  46. package/dist/companion/store.js +1 -0
  47. package/dist/companion/webauthn.js +11 -2
  48. package/dist/console-instance.js +0 -4
  49. package/dist/contracts/console-api.js +1 -1
  50. package/dist/converse.js +0 -1
  51. package/dist/coordinator.js +1 -1
  52. package/dist/db-tuning.js +16 -0
  53. package/dist/desktop-config.js +156 -0
  54. package/dist/desktop-host.js +6 -152
  55. package/dist/desktop-update.js +1 -1
  56. package/dist/discord.js +9 -3
  57. package/dist/dispatch.js +32 -4
  58. package/dist/doctor.js +30 -0
  59. package/dist/evidence.js +49 -3
  60. package/dist/exec.js +3 -0
  61. package/dist/finished-task-sql.js +14 -0
  62. package/dist/flexible-answers.js +0 -1
  63. package/dist/git-views.js +7 -1
  64. package/dist/github-read.js +41 -0
  65. package/dist/guides.js +4 -3
  66. package/dist/invoke.js +12 -2
  67. package/dist/lead-doors.js +50 -3
  68. package/dist/lead-queue-runtime.js +18 -6
  69. package/dist/lead-queue.js +25 -0
  70. package/dist/lead-status.js +3 -3
  71. package/dist/live-backup-change.js +93 -0
  72. package/dist/live-backup.js +75 -31
  73. package/dist/live-bus.js +3 -2
  74. package/dist/live-records.js +0 -1
  75. package/dist/local-owner.js +0 -1
  76. package/dist/loop-recovery.js +40 -0
  77. package/dist/maintenance.js +29 -1
  78. package/dist/model-choices.js +0 -11
  79. package/dist/needs-you.js +2 -0
  80. package/dist/nightly-check.js +0 -3
  81. package/dist/nightly-github.js +1 -2
  82. package/dist/notification-retention.js +119 -0
  83. package/dist/observations.js +0 -1
  84. package/dist/operate.js +393 -56
  85. package/dist/planner.js +4 -1
  86. package/dist/pull-request-flow.js +56 -15
  87. package/dist/qr.js +0 -25
  88. package/dist/query-index-schema.js +10 -0
  89. package/dist/read-executor-worker.js +9 -7
  90. package/dist/read-executor.js +18 -1
  91. package/dist/read-worker-connection.js +7 -0
  92. package/dist/release-adapters.js +63 -48
  93. package/dist/release-auto.js +17 -13
  94. package/dist/release-card.js +0 -4
  95. package/dist/release-cli.js +58 -10
  96. package/dist/release-next.js +1 -1
  97. package/dist/release-stops.js +71 -0
  98. package/dist/release-supersede.js +125 -0
  99. package/dist/release-supervise.js +90 -0
  100. package/dist/release.js +265 -42
  101. package/dist/restore-retirement.js +4 -1
  102. package/dist/result-review.js +0 -3
  103. package/dist/retention-ui.js +1 -1
  104. package/dist/retention.js +14 -21
  105. package/dist/review-context.js +0 -5
  106. package/dist/route-rules.js +1 -5
  107. package/dist/runner.js +36 -1
  108. package/dist/sandbox-runtime.js +0 -1
  109. package/dist/scope.js +1 -13
  110. package/dist/scout.js +4 -7
  111. package/dist/serve.js +122 -12
  112. package/dist/server/kit.js +1 -0
  113. package/dist/server/live.js +9 -2
  114. package/dist/server/pages.js +3 -2
  115. package/dist/server/phone-engine-api.js +22 -2
  116. package/dist/server/render-pages.js +1 -11
  117. package/dist/server/render-results.js +0 -1
  118. package/dist/server/render-tasks.js +0 -68
  119. package/dist/server/route-table.js +1 -1
  120. package/dist/server/settings-phone.js +32 -9
  121. package/dist/server/settings-scripts.js +1 -1
  122. package/dist/server/settings-section-table.js +0 -3
  123. package/dist/server/settings-sections.js +4 -2
  124. package/dist/server/settings.js +20 -5
  125. package/dist/server/terminals.js +2 -1
  126. package/dist/shutdown-proof.js +29 -0
  127. package/dist/slack.js +9 -3
  128. package/dist/sqlite-telemetry.js +26 -14
  129. package/dist/statement-cache.js +137 -0
  130. package/dist/store.js +86 -14
  131. package/dist/structured-output.js +0 -1
  132. package/dist/style-asset.js +20 -7
  133. package/dist/tailnet.js +0 -3
  134. package/dist/task-control.js +5 -0
  135. package/dist/task-sizing.js +0 -1
  136. package/dist/task-status.js +1 -1
  137. package/dist/teams.js +9 -3
  138. package/dist/teardown-git.js +10 -1
  139. package/dist/telegram.js +4 -1
  140. package/dist/toolroll-update-cli.js +19 -3
  141. package/dist/toolroll-update-ui.js +2 -2
  142. package/dist/toolroll-update.js +95 -15
  143. package/dist/up-processes.js +16 -1
  144. package/dist/up-role-child.js +2 -0
  145. package/dist/wake-hub.js +15 -6
  146. package/dist/work-index.js +101 -44
  147. package/dist/work-reads.js +53 -9
  148. package/dist/work-snapshots.js +185 -0
  149. package/dist/worker-statement-cache.js +83 -0
  150. package/dist/workspace-revision.js +145 -21
  151. package/package.json +1 -1
  152. package/dist/companion/webauthn-test-support.js +0 -44
  153. package/dist/contracts/contract-test.js +0 -55
  154. package/dist/unfenced-test-support.js +0 -6
  155. /package/dist/browser/{terminal.css → terminal.4d1cf20c32ad7c2099df657358d540d5fd92bb55195a88121e74b28467238b42.css} +0 -0
@@ -1,52 +1,298 @@
1
- import { readFileSync } from 'node:fs';
1
+ import { createHash } from 'node:crypto';
2
+ import { closeSync, constants, copyFileSync, fstatSync, lstatSync, lutimesSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { brotliDecompressSync, gunzipSync } from 'node:zlib';
2
6
  import {} from './browser-workspace.js';
3
7
  import { html, jsonScript, replaceMarkup, scriptElement } from './html.js';
4
- const assets = new Map();
5
- const BROWSER_ASSETS = [['workspace.js', 'text/javascript; charset=utf-8'], ['workspace.css', 'text/css; charset=utf-8'], ['terminal.js', 'text/javascript; charset=utf-8'],
6
- ['terminal.css', 'text/css; charset=utf-8'], ['THIRD_PARTY_NOTICES.txt', 'text/plain; charset=utf-8']];
7
- function readAsset(name) {
8
- for (const location of [new URL(`./browser/${name}`, import.meta.url), new URL(`../dist/browser/${name}`, import.meta.url)]) {
8
+ import { acceptedEncodings, identityAccepted } from './style-asset.js';
9
+ const ASSET_NAMES = ['workspace.js', 'workspace.css', 'terminal.js', 'terminal.css'];
10
+ const TYPES = { js: 'text/javascript; charset=utf-8', css: 'text/css; charset=utf-8' };
11
+ const HASHED = /^(workspace|terminal)\.([0-9a-f]{64})\.(js|css)$/;
12
+ const NOTICES = 'THIRD_PARTY_NOTICES.txt';
13
+ export const RETAINED_BUILDS = 4;
14
+ const MAX_ASSET_BYTES = 32 * 1024 * 1024;
15
+ const MAX_MANIFEST_BYTES = 64 * 1024;
16
+ const DAY_MS = 86_400_000;
17
+ const OWNER = typeof process.getuid === 'function' ? process.getuid() : null;
18
+ const NOFOLLOW = constants.O_NOFOLLOW ?? 0;
19
+ const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex');
20
+ function privateFolder(path) {
21
+ try {
22
+ const stat = lstatSync(path);
23
+ return stat.isDirectory() && stat.uid === OWNER && (stat.mode & 0o077) === 0 ? stat : null;
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ }
29
+ function readPlain(path, max, owned) {
30
+ let fd = null;
31
+ try {
32
+ fd = openSync(path, constants.O_RDONLY | NOFOLLOW);
33
+ const stat = fstatSync(fd);
34
+ if (!stat.isFile() || stat.size > max || (owned && stat.uid !== OWNER))
35
+ return null;
36
+ const body = readFileSync(fd);
37
+ return body.length <= max ? body : null;
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ finally {
43
+ if (fd !== null)
44
+ closeSync(fd);
45
+ }
46
+ }
47
+ function readManifest(dir, kept) {
48
+ try {
49
+ const raw = readPlain(join(dir, 'manifest.json'), MAX_MANIFEST_BYTES, kept);
50
+ if (raw === null)
51
+ return null;
52
+ const parsed = JSON.parse(raw.toString('utf8'));
53
+ if (parsed.schemaVersion !== 1 || parsed.assets === null || typeof parsed.assets !== 'object')
54
+ return null;
55
+ const entries = new Map();
56
+ for (const name of ASSET_NAMES) {
57
+ const one = parsed.assets[name];
58
+ if (one === null || typeof one !== 'object')
59
+ continue;
60
+ const { file, br, gzip } = one;
61
+ const match = typeof file === 'string' ? HASHED.exec(file) : null;
62
+ if (match === null || `${match[1]}.${match[3]}` !== name)
63
+ continue;
64
+ const encodings = ['br', 'gzip'].filter(encoding => ({ br, gzip })[encoding] !== null && typeof ({ br, gzip })[encoding] === 'object');
65
+ entries.set(name, { dir, file: file, digest: match[2], type: TYPES[match[3]], encodings, kept });
66
+ }
67
+ return { raw, entries };
68
+ }
69
+ catch {
70
+ return null;
71
+ }
72
+ }
73
+ const bodies = new Map();
74
+ function proven(entry, encoding) {
75
+ if (entry.kept && privateFolder(entry.dir) === null)
76
+ return null;
77
+ const file = encoding === 'identity' ? entry.file : `${entry.file}.${encoding === 'br' ? 'br' : 'gz'}`;
78
+ const key = [entry.dir, file, entry.digest, encoding].join('\u0000');
79
+ const held = bodies.get(key);
80
+ if (held !== undefined)
81
+ return held;
82
+ const bytes = readPlain(join(entry.dir, file), MAX_ASSET_BYTES, entry.kept);
83
+ if (bytes === null)
84
+ return null;
85
+ let decoded;
86
+ try {
87
+ decoded = encoding === 'identity' ? bytes : encoding === 'br' ? brotliDecompressSync(bytes, { maxOutputLength: MAX_ASSET_BYTES }) : gunzipSync(bytes, { maxOutputLength: MAX_ASSET_BYTES });
88
+ }
89
+ catch {
90
+ return null;
91
+ }
92
+ if (sha256(decoded) !== entry.digest)
93
+ return null;
94
+ const sent = { bytes, etag: `"${(encoding === 'identity' ? entry.digest : sha256(bytes)).slice(0, 32)}"` };
95
+ bodies.set(key, sent);
96
+ return sent;
97
+ }
98
+ let current = null;
99
+ let notices = null;
100
+ function currentBuild() {
101
+ if (current !== null)
102
+ return current;
103
+ const here = dirname(fileURLToPath(import.meta.url));
104
+ for (const dir of [join(here, 'browser'), join(here, '..', 'dist', 'browser')]) {
105
+ const manifest = readManifest(dir, false);
106
+ if (manifest === null || manifest.entries.size !== ASSET_NAMES.length)
107
+ continue;
108
+ if (![...manifest.entries.values()].every(entry => proven(entry, 'identity') !== null))
109
+ continue;
9
110
  try {
10
- return readFileSync(location);
111
+ notices = readFileSync(join(dir, NOTICES));
11
112
  }
12
- catch { }
113
+ catch {
114
+ continue;
115
+ }
116
+ current = manifest;
117
+ return current;
13
118
  }
14
119
  return null;
15
120
  }
16
121
  export function browserAssetsAvailable() {
17
- if (assets.size === BROWSER_ASSETS.length)
18
- return true;
19
- for (const [name, type] of BROWSER_ASSETS) {
20
- const body = readAsset(name);
122
+ return currentBuild() !== null;
123
+ }
124
+ export function browserAssetPath(name) {
125
+ const entry = currentBuild()?.entries.get(name);
126
+ return entry === undefined ? `/assets/${name}` : `/assets/${entry.file}`;
127
+ }
128
+ export function retainBrowserAssets(cacheDir) {
129
+ const build = currentBuild();
130
+ if (build === null || OWNER === null)
131
+ return new Map();
132
+ let fd = null;
133
+ try {
134
+ mkdirSync(cacheDir, { recursive: true, mode: 0o700 });
135
+ fd = openSync(cacheDir, constants.O_RDONLY | constants.O_DIRECTORY | NOFOLLOW);
136
+ const root = fstatSync(fd);
137
+ if (!root.isDirectory() || root.uid !== OWNER || (root.mode & 0o077) !== 0)
138
+ return new Map();
139
+ const steady = () => {
140
+ const now = privateFolder(cacheDir);
141
+ if (now === null || now.dev !== root.dev || now.ino !== root.ino)
142
+ throw new Error('The kept-assets folder moved.');
143
+ };
144
+ const id = sha256(build.raw).slice(0, 16);
145
+ const home = join(cacheDir, id);
146
+ steady();
147
+ if (lstatSync(home, { throwIfNoEntry: false }) === undefined) {
148
+ steady();
149
+ const incoming = mkdtempSync(join(cacheDir, '.incoming-'));
150
+ if (privateFolder(incoming) === null)
151
+ throw new Error('The incoming folder is not private.');
152
+ try {
153
+ for (const entry of build.entries.values()) {
154
+ for (const file of [entry.file, ...entry.encodings.map(encoding => `${entry.file}.${encoding === 'br' ? 'br' : 'gz'}`)]) {
155
+ steady();
156
+ copyFileSync(join(entry.dir, file), join(incoming, file), constants.COPYFILE_EXCL);
157
+ }
158
+ }
159
+ steady();
160
+ writeFileSync(join(incoming, 'manifest.json'), build.raw, { flag: 'wx', mode: 0o600 });
161
+ steady();
162
+ renameSync(incoming, home);
163
+ }
164
+ catch (error) {
165
+ try {
166
+ steady();
167
+ if (privateFolder(incoming) !== null)
168
+ rmSync(incoming, { recursive: true, force: true });
169
+ }
170
+ catch { }
171
+ if (privateFolder(home) === null)
172
+ throw error;
173
+ }
174
+ }
175
+ steady();
176
+ if (privateFolder(home) === null)
177
+ return new Map();
178
+ const now = new Date();
179
+ lutimesSync(home, now, now);
180
+ steady();
181
+ const builds = readdirSync(cacheDir).flatMap(name => {
182
+ if (!/^[0-9a-f]{16}$/.test(name))
183
+ return [];
184
+ const stat = privateFolder(join(cacheDir, name));
185
+ return stat === null ? [] : [{ name, at: stat.mtimeMs }];
186
+ }).sort((a, b) => b.at - a.at || a.name.localeCompare(b.name));
187
+ const keep = [id, ...builds.map(one => one.name).filter(name => name !== id)].slice(0, RETAINED_BUILDS);
188
+ for (const one of builds) {
189
+ if (keep.includes(one.name))
190
+ continue;
191
+ steady();
192
+ if (privateFolder(join(cacheDir, one.name)) !== null)
193
+ rmSync(join(cacheDir, one.name), { recursive: true, force: true });
194
+ }
195
+ steady();
196
+ for (const name of readdirSync(cacheDir)) {
197
+ if (!name.startsWith('.incoming-'))
198
+ continue;
199
+ steady();
200
+ const stat = privateFolder(join(cacheDir, name));
201
+ if (stat !== null && stat.mtimeMs < now.getTime() - DAY_MS)
202
+ rmSync(join(cacheDir, name), { recursive: true, force: true });
203
+ }
204
+ const retained = new Map();
205
+ for (const name of keep.slice(1)) {
206
+ steady();
207
+ const kept = privateFolder(join(cacheDir, name)) === null ? null : readManifest(join(cacheDir, name), true);
208
+ if (kept === null || sha256(kept.raw).slice(0, 16) !== name)
209
+ continue;
210
+ for (const entry of kept.entries.values()) {
211
+ const path = `/assets/${entry.file}`;
212
+ if (!retained.has(path))
213
+ retained.set(path, entry);
214
+ }
215
+ }
216
+ return retained;
217
+ }
218
+ catch {
219
+ return new Map();
220
+ }
221
+ finally {
222
+ if (fd !== null)
223
+ closeSync(fd);
224
+ }
225
+ }
226
+ function sendHashed(request, response, entry) {
227
+ const header = request.headers['accept-encoding'];
228
+ const identity = identityAccepted(header);
229
+ for (const encoding of [...acceptedEncodings(header, entry.encodings), ...(identity ? ['identity'] : [])]) {
230
+ const body = proven(entry, encoding);
21
231
  if (body === null)
22
- return false;
23
- assets.set(`/assets/${name}`, { body, type });
232
+ continue;
233
+ const headers = {
234
+ 'Content-Type': entry.type,
235
+ 'Cache-Control': 'public, max-age=31536000, immutable',
236
+ 'Content-Security-Policy': "default-src 'none'",
237
+ 'X-Content-Type-Options': 'nosniff',
238
+ 'Vary': 'Accept-Encoding',
239
+ 'ETag': body.etag,
240
+ ...(encoding === 'identity' ? {} : { 'Content-Encoding': encoding }),
241
+ };
242
+ const ifNoneMatch = request.headers['if-none-match'] ?? '';
243
+ if (ifNoneMatch.split(',').some(value => value.trim() === '*' || value.trim().replace(/^W\//, '') === body.etag)) {
244
+ response.writeHead(304, headers);
245
+ response.end();
246
+ return 'sent';
247
+ }
248
+ response.writeHead(200, { ...headers, 'Content-Length': body.bytes.length });
249
+ response.end(request.method === 'HEAD' ? undefined : body.bytes);
250
+ return 'sent';
24
251
  }
25
- return true;
252
+ return identity ? 'missing' : 'unacceptable';
26
253
  }
27
- export function serveBrowserAsset(request, response, path) {
28
- if (!BROWSER_ASSETS.some(([name]) => path === `/assets/${name}`))
254
+ export function serveBrowserAsset(request, response, path, retained = null) {
255
+ const name = path.startsWith('/assets/') ? path.slice('/assets/'.length) : '';
256
+ const fixed = name === NOTICES || ASSET_NAMES.includes(name);
257
+ if (!fixed && !HASHED.test(name))
29
258
  return false;
30
259
  if (request.method !== 'GET' && request.method !== 'HEAD') {
31
260
  response.writeHead(405, { allow: 'GET, HEAD', 'cache-control': 'no-store' });
32
261
  response.end();
33
262
  return true;
34
263
  }
35
- browserAssetsAvailable();
36
- const asset = assets.get(path);
37
- response.writeHead(asset ? 200 : 404, {
38
- 'content-type': asset?.type ?? 'text/plain; charset=utf-8',
264
+ const build = currentBuild();
265
+ const refusal = { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'content-security-policy': "default-src 'none'" };
266
+ if (!fixed) {
267
+ const entry = [...build?.entries.values() ?? []].find(one => one.file === name) ?? retained?.get(path);
268
+ const outcome = entry === undefined ? 'missing' : sendHashed(request, response, entry);
269
+ if (outcome === 'sent')
270
+ return true;
271
+ if (outcome === 'unacceptable') {
272
+ response.writeHead(406, { ...refusal, vary: 'Accept-Encoding' });
273
+ response.end(request.method === 'HEAD' ? undefined : 'No acceptable encoding.');
274
+ return true;
275
+ }
276
+ response.writeHead(404, refusal);
277
+ response.end(request.method === 'HEAD' ? undefined : 'No such address.');
278
+ return true;
279
+ }
280
+ const entry = build?.entries.get(name);
281
+ const body = name === NOTICES ? notices : entry === undefined ? null : proven(entry, 'identity')?.bytes ?? null;
282
+ const type = name === NOTICES ? 'text/plain; charset=utf-8' : entry?.type ?? 'text/plain; charset=utf-8';
283
+ response.writeHead(body !== null ? 200 : 404, {
284
+ 'content-type': body !== null ? type : 'text/plain; charset=utf-8',
39
285
  'cache-control': 'no-store', 'x-content-type-options': 'nosniff',
40
286
  'content-security-policy': "default-src 'none'",
41
- ...(asset ? { 'content-length': asset.body.length } : {}),
287
+ ...(body !== null ? { 'content-length': body.length } : {}),
42
288
  });
43
- response.end(request.method === 'HEAD' ? undefined : asset?.body ?? 'Browser assets are not built.');
289
+ response.end(request.method === 'HEAD' ? undefined : body ?? 'Browser assets are not built.');
44
290
  return true;
45
291
  }
46
292
  export function browserWorkspaceDocument(document, workspace, nonce, functionalScript, beside = html ``) {
47
293
  const initialize = `window.addEventListener('standing-orders:workspace-rendered',function initializeWorkspace(){window.removeEventListener('standing-orders:workspace-rendered',initializeWorkspace);${functionalScript}});`;
48
294
  const settleFades = `(function(){function s(e){var f=e.viewTransition;if(f)[f.finished,f.ready,f.updateCallbackDone].forEach(function(p){if(p)p.catch(function(){})})}addEventListener('pageswap',s);addEventListener('pagereveal',s)})();`;
49
- let out = replaceMarkup(document, /<\/head>/, () => html `<link rel="stylesheet" href="/assets/workspace.css">${workspace.sensitive ? "" : scriptElement(settleFades, { nonce })}</head>`);
295
+ let out = replaceMarkup(document, /<\/head>/, () => html `<link rel="stylesheet" href="${browserAssetPath('workspace.css')}">${workspace.sensitive ? "" : scriptElement(settleFades, { nonce })}</head>`);
50
296
  out = replaceMarkup(out, /<body>/, () => html `<body><div id="standing-orders-workspace" data-live-reader="stream">`);
51
- return replaceMarkup(out, /<\/body>/, () => html `</div>${beside}${jsonScript(workspace, { id: "standing-orders-workspace-data", nonce })}${scriptElement(initialize, { nonce })}<script type="module" src="/assets/workspace.js" nonce="${nonce}"></script></body>`);
297
+ return replaceMarkup(out, /<\/body>/, () => html `</div>${beside}${jsonScript(workspace, { id: "standing-orders-workspace-data", nonce })}${scriptElement(initialize, { nonce })}<script type="module" src="${browserAssetPath('workspace.js')}" nonce="${nonce}"></script></body>`);
52
298
  }
@@ -2,7 +2,9 @@ import { updateAdmissionPaused } from "./desktop-update-gate.js";
2
2
  import { drainOf } from "./runner.js";
3
3
  import { readSchemaVersion } from "./store.js";
4
4
  export const RESTART_LIMIT = 3;
5
- export const RESTART_WINDOW_MS = 30 * 60_000;
5
+ export const RESTART_BACKOFF_MS = 5 * 60_000;
6
+ export const RESTART_BACKOFF_MAX_MS = 30 * 60_000;
7
+ export const RESTART_MEMORY_MS = 6 * 60 * 60_000;
6
8
  export function builderWish(store) {
7
9
  const row = store.handle.prepare("SELECT desired, build, schema_version, set_by, set_at FROM builder_service WHERE id = 1").get();
8
10
  return row === undefined ? null : { desired: row["desired"] === "running" ? "running" : "stopped", build: String(row["build"]), schema: Number(row["schema_version"]), setBy: String(row["set_by"]), setAt: String(row["set_at"]) };
@@ -27,11 +29,18 @@ export function admitBuilderRestart(store, now) {
27
29
  return "not-wanted";
28
30
  if (restartPaused(store, now))
29
31
  return "paused";
30
- const since = new Date(now.getTime() - RESTART_WINDOW_MS).toISOString();
31
- const tried = Number(store.handle.prepare("SELECT COUNT(*) AS n FROM builder_restart WHERE at > ?").get(since)?.["n"] ?? 0);
32
- if (tried >= RESTART_LIMIT)
32
+ if (restartBackoffMs(store, now) > 0)
33
33
  return "attempts";
34
34
  store.handle.prepare("INSERT INTO builder_restart (at) VALUES (?)").run(now.toISOString());
35
35
  return "admitted";
36
36
  });
37
37
  }
38
+ export function restartBackoffMs(store, now) {
39
+ const remembered = new Date(now.getTime() - RESTART_MEMORY_MS).toISOString();
40
+ const row = store.handle.prepare("SELECT COUNT(*) AS n, MAX(at) AS last FROM builder_restart WHERE at > ?").get(remembered);
41
+ const count = Number(row?.["n"] ?? 0);
42
+ if (count < RESTART_LIMIT || row?.["last"] == null)
43
+ return 0;
44
+ const wait = Math.min(RESTART_BACKOFF_MAX_MS, RESTART_BACKOFF_MS * 2 ** Math.min(count - RESTART_LIMIT, 8));
45
+ return Math.max(0, Date.parse(String(row["last"])) + wait - now.getTime());
46
+ }
package/dist/builder.js CHANGED
@@ -32,6 +32,7 @@ import { stopRequestedFor, stopWords, underStopWatch } from "./task-control.js";
32
32
  import { witnessedRunner } from "./process-custody.js";
33
33
  import { runWithIsolatedDatabase } from "./child-database.js";
34
34
  import { recordWorktreeProcess, saveWorkPatch } from "./worktree.js";
35
+ import { isDatabaseBusy } from "./store.js";
35
36
  import { launchSandboxOf, protectedChanges, protectedLinks } from "./agent-fence.js";
36
37
  import { fallbackBriefFor, pinnedEntryOf, ranOutOnChain } from "./fallback.js";
37
38
  import { approvalOf, digestOf, idleClock, isAcpProfile, LIVE_CHAIN_VERSION, liveChainFromJson, profileDigestOf, releaseCheckScope, routeParityProblem, watchdogsOf } from "./scope.js";
@@ -797,7 +798,9 @@ export async function build(store, request) {
797
798
  if (!answer.ok)
798
799
  fencedMidBuild = true;
799
800
  }
800
- catch {
801
+ catch (error) {
802
+ if (isDatabaseBusy(error))
803
+ return;
801
804
  fencedMidBuild = true;
802
805
  }
803
806
  if (!fencedMidBuild) {
@@ -0,0 +1,122 @@
1
+ import { Worker } from "node:worker_threads";
2
+ const TTL_MS = 60_000;
3
+ const KEEP_MS = 10 * 60_000;
4
+ const MAX_QUEUED = 16;
5
+ const MAX_KEPT = 128;
6
+ export class CanvasFreshness {
7
+ compute;
8
+ ttlMs;
9
+ keepMs;
10
+ maxQueued;
11
+ nowMs;
12
+ kept = new Map();
13
+ working = new Map();
14
+ waiting = [];
15
+ running = false;
16
+ constructor(options = {}) {
17
+ this.compute = options.compute ?? workerStateKey;
18
+ this.ttlMs = options.ttlMs ?? TTL_MS;
19
+ this.keepMs = options.keepMs ?? KEEP_MS;
20
+ this.maxQueued = options.maxQueued ?? MAX_QUEUED;
21
+ this.nowMs = options.nowMs ?? Date.now;
22
+ }
23
+ get pending() { return this.working.size; }
24
+ async get(repo, pathspecs, waitMs) {
25
+ const id = `${repo}\0${pathspecs.join("\0")}`;
26
+ const kept = this.kept.get(id);
27
+ const now = this.nowMs();
28
+ if (kept !== undefined && now - kept.at < this.ttlMs)
29
+ return { key: kept.key, known: kept.key !== null };
30
+ const work = this.start(id, repo, pathspecs);
31
+ if (work !== null && waitMs > 0) {
32
+ let timer;
33
+ const late = new Promise(resolve => { timer = setTimeout(() => resolve(undefined), waitMs); timer.unref?.(); });
34
+ const key = await Promise.race([work, late]);
35
+ clearTimeout(timer);
36
+ if (key !== undefined)
37
+ return { key, known: key !== null };
38
+ }
39
+ const last = this.kept.get(id);
40
+ return last !== undefined && this.nowMs() - last.at < this.keepMs && last.key !== null ? { key: last.key, known: true } : { key: null, known: false };
41
+ }
42
+ start(id, repo, pathspecs) {
43
+ const already = this.working.get(id);
44
+ if (already !== undefined)
45
+ return already;
46
+ if (this.working.size >= this.maxQueued)
47
+ return null;
48
+ const work = new Promise(resolve => {
49
+ this.waiting.push(() => {
50
+ Promise.resolve().then(() => this.compute(repo, pathspecs)).catch(() => null).then(key => {
51
+ this.kept.delete(id);
52
+ this.kept.set(id, { key, at: this.nowMs() });
53
+ while (this.kept.size > MAX_KEPT)
54
+ this.kept.delete(this.kept.keys().next().value);
55
+ this.working.delete(id);
56
+ this.running = false;
57
+ resolve(key);
58
+ this.next();
59
+ });
60
+ });
61
+ });
62
+ this.working.set(id, work);
63
+ this.next();
64
+ return work;
65
+ }
66
+ next() {
67
+ if (this.running)
68
+ return;
69
+ const job = this.waiting.shift();
70
+ if (job === undefined)
71
+ return;
72
+ this.running = true;
73
+ job();
74
+ }
75
+ }
76
+ const JOB_MS = 30_000;
77
+ let worker = null;
78
+ let nextJob = 1;
79
+ const answers = new Map();
80
+ function startWorker() {
81
+ const made = import.meta.url.endsWith(".ts")
82
+ ? new Worker(`import('tsx/esm/api').then(tsx => { tsx.register(); return import(${JSON.stringify(new URL("./canvas-state-worker.ts", import.meta.url).href)}); });`, { eval: true })
83
+ : new Worker(new URL("./canvas-state-worker.js", import.meta.url));
84
+ made.on("message", ({ id, key }) => {
85
+ answers.get(id)?.(typeof key === "string" && /^s-[0-9a-f]{12}$/.test(key) ? key : null);
86
+ answers.delete(id);
87
+ if (answers.size === 0)
88
+ made.unref();
89
+ });
90
+ const fail = () => {
91
+ if (worker === made)
92
+ worker = null;
93
+ for (const answer of answers.values())
94
+ answer(null);
95
+ answers.clear();
96
+ };
97
+ made.on("error", fail);
98
+ made.on("exit", fail);
99
+ return made;
100
+ }
101
+ export function workerStateKey(repo, pathspecs) {
102
+ if (worker === null)
103
+ worker = startWorker();
104
+ const running = worker;
105
+ running.ref();
106
+ const id = nextJob++;
107
+ return new Promise(resolve => {
108
+ const timer = setTimeout(() => { if (answers.delete(id)) {
109
+ resolve(null);
110
+ void running.terminate();
111
+ } }, JOB_MS);
112
+ timer.unref?.();
113
+ answers.set(id, key => { clearTimeout(timer); resolve(key); });
114
+ running.postMessage({ id, repo, pathspecs: [...pathspecs] });
115
+ });
116
+ }
117
+ export async function stopCanvasStateWorker() {
118
+ const running = worker;
119
+ worker = null;
120
+ if (running !== null)
121
+ await running.terminate();
122
+ }