@omacode/micromanager 0.0.0-stage → 1.0.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.
- package/LICENSE +201 -0
- package/README.md +30 -2
- package/THIRD_PARTY.md +100 -0
- package/decider/.python-version +1 -0
- package/decider/README.md +35 -0
- package/decider/decider/__init__.py +1 -0
- package/decider/decider/server.py +327 -0
- package/decider/pyproject.toml +34 -0
- package/decider/uv.lock +1255 -0
- package/dist/agenda.js +51 -0
- package/dist/agents.js +58 -0
- package/dist/artifact/handoff.js +281 -0
- package/dist/ask.js +200 -0
- package/dist/backends.js +219 -0
- package/dist/backlog.js +414 -0
- package/dist/bench.js +427 -0
- package/dist/board.js +1 -0
- package/dist/brief.js +202 -0
- package/dist/browser.js +679 -0
- package/dist/budget.js +61 -0
- package/dist/catalog.js +187 -0
- package/dist/checkchange.js +145 -0
- package/dist/checkpoint.js +94 -0
- package/dist/cli.js +764 -0
- package/dist/comfy-gate.js +258 -0
- package/dist/compact.js +142 -0
- package/dist/config.js +344 -0
- package/dist/context/capture.js +1 -0
- package/dist/context/digest.js +1 -0
- package/dist/context/embed.js +1 -0
- package/dist/context/index.js +2 -0
- package/dist/context/ledger.js +1 -0
- package/dist/context/manager.js +1 -0
- package/dist/context/memory.js +1 -0
- package/dist/context/policy.js +1 -0
- package/dist/context/prices.js +1 -0
- package/dist/context/recall.js +1 -0
- package/dist/context/rules.js +1 -0
- package/dist/context/search.js +1 -0
- package/dist/context/status.js +1 -0
- package/dist/context/store.js +1 -0
- package/dist/context/summary.js +1 -0
- package/dist/context/tokens.js +1 -0
- package/dist/context/tools.js +1 -0
- package/dist/continuation.js +184 -0
- package/dist/contract.js +294 -0
- package/dist/contractround.js +178 -0
- package/dist/control.js +1 -0
- package/dist/creative-tools.js +237 -0
- package/dist/dataset.js +175 -0
- package/dist/decide.js +676 -0
- package/dist/decider.js +171 -0
- package/dist/design-shell.js +448 -0
- package/dist/design.js +1410 -0
- package/dist/desktop.js +44 -0
- package/dist/egress.js +156 -0
- package/dist/eval.js +60 -0
- package/dist/evolver.js +302 -0
- package/dist/features.js +193 -0
- package/dist/followups.js +32 -0
- package/dist/forms.js +195 -0
- package/dist/gate.js +108 -0
- package/dist/gatebox.js +46 -0
- package/dist/grants.js +189 -0
- package/dist/graph.js +65 -0
- package/dist/guard/index.js +1 -0
- package/dist/guard/wire.js +1 -0
- package/dist/helpers.js +85 -0
- package/dist/hooks.js +158 -0
- package/dist/image-models.js +117 -0
- package/dist/integration.js +3 -0
- package/dist/journal.js +1 -0
- package/dist/look.js +363 -0
- package/dist/memory.js +1 -0
- package/dist/mode.js +97 -0
- package/dist/native.js +3348 -0
- package/dist/nogit.js +259 -0
- package/dist/outcomes.js +148 -0
- package/dist/permission.js +35 -0
- package/dist/pick.js +89 -0
- package/dist/pipelines.js +262 -0
- package/dist/plan.js +641 -0
- package/dist/plandoc.js +211 -0
- package/dist/plugin.js +4736 -0
- package/dist/policy.js +58 -0
- package/dist/pools.js +1 -0
- package/dist/preview.js +274 -0
- package/dist/profile.js +165 -0
- package/dist/progress.js +1 -0
- package/dist/promote.js +313 -0
- package/dist/redact.js +1 -0
- package/dist/registry.js +179 -0
- package/dist/riskscore.js +126 -0
- package/dist/roles.js +1 -0
- package/dist/routing.js +1 -0
- package/dist/runner.js +1892 -0
- package/dist/sandbox.js +3 -0
- package/dist/sandboxgate.js +90 -0
- package/dist/scheduler.js +170 -0
- package/dist/services-main.js +131 -0
- package/dist/services.js +265 -0
- package/dist/session.js +241 -0
- package/dist/setup.js +423 -0
- package/dist/shell/decide.js +1 -0
- package/dist/shell/index.js +2 -0
- package/dist/shell/sandbox.js +1 -0
- package/dist/shell/wire.js +1 -0
- package/dist/skills.js +103 -0
- package/dist/state.js +1 -0
- package/dist/store.js +1 -0
- package/dist/switcher.js +1 -0
- package/dist/synth.js +418 -0
- package/dist/tools.js +477 -0
- package/dist/trials.js +223 -0
- package/dist/usage.js +1 -0
- package/dist/wait.js +167 -0
- package/dist/watchdog.js +476 -0
- package/dist/web-guidance.js +43 -0
- package/dist/which.js +20 -0
- package/dist/worktree/git.js +545 -0
- package/dist/writeguard.js +311 -0
- package/evolver/mm_evolve/__init__.py +1 -0
- package/evolver/mm_evolve/entry.py +3 -0
- package/evolver/mm_evolve/evaluator.py +119 -0
- package/evolver/mm_evolve/llm.py +76 -0
- package/evolver/mm_evolve/run.py +89 -0
- package/evolver/mm_evolve/spec.py +62 -0
- package/evolver/pyproject.toml +21 -0
- package/evolver/uv.lock +772 -0
- package/package.json +74 -4
- package/skills/THIRD_PARTY.md +58 -0
- package/skills/code-review/SKILL.md +46 -0
- package/skills/deck/SKILL.md +98 -0
- package/skills/deliberate/SKILL.md +39 -0
- package/skills/design/SKILL.md +150 -0
- package/skills/diagnosing-bugs/SKILL.md +75 -0
- package/skills/image/SKILL.md +66 -0
- package/skills/orchestrator/SKILL.md +107 -0
- package/skills/receiving-code-review/SKILL.md +36 -0
- package/skills/research/SKILL.md +18 -0
- package/skills/tdd/SKILL.md +56 -0
- package/skills/tdd/mocking.md +59 -0
- package/skills/tdd/tests.md +77 -0
- package/skills/verification-before-completion/SKILL.md +50 -0
- package/skills/video/SKILL.md +97 -0
- package/skills/web/SKILL.md +60 -0
package/dist/design.js
ADDED
|
@@ -0,0 +1,1410 @@
|
|
|
1
|
+
// The canvas session (S3): one worker worktree, served read-only on one loopback port and controlled on a second one.
|
|
2
|
+
// Both listeners bind port 0 and stay bound: the OS picks a free port at listen time, and no port is ever released
|
|
3
|
+
// between choosing it and using it. The worktree is an input, never a guess: sessions only exist for paths that
|
|
4
|
+
// prepareIntegration already handed to the plugin.
|
|
5
|
+
//
|
|
6
|
+
// The content port is a file server with no API surface. Every path is resolved through the artifact path rules —
|
|
7
|
+
// `realish` follows symlinks in the parts that exist and keeps the names of those that do not, and `insideResolved(root,
|
|
8
|
+
// candidate)` compares their real forms segment by segment — so neither `..` nor a symlink can reach outside the
|
|
9
|
+
// worktree. The control port is deliberately small here (health and CORS preflight); shell, API and SSE live on it in
|
|
10
|
+
// later stages of the design flow.
|
|
11
|
+
import { execFileSync } from "node:child_process";
|
|
12
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
13
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, watch, writeFileSync } from "node:fs";
|
|
14
|
+
import { writeFile } from "node:fs/promises";
|
|
15
|
+
import { createServer } from "node:http";
|
|
16
|
+
import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
17
|
+
import { insideResolved, realish } from "@omacode/core/safepath";
|
|
18
|
+
import { canonicalJson } from "@omacode/core/json";
|
|
19
|
+
import { inStateDir, statePath } from "@omacode/core/paths";
|
|
20
|
+
import { injectOverlay, isRawRequest, isSelection, rawPartUrl } from "@omacode/core/design/overlay";
|
|
21
|
+
import { runDesignChecks } from "@omacode/core/design/checks";
|
|
22
|
+
import { readDesignManifest } from "@omacode/core/design/manifest";
|
|
23
|
+
import { designTokensCssPath, designTokensPath, readDesignTokens, renderDesignTokensCss, serializeDesignTokens, } from "@omacode/core/design/tokens";
|
|
24
|
+
import { acquireDesignLock, currentHub, DEFAULT_HEARTBEAT_MS, designLockPath, heartbeatDesignLock, inspectDesignLock, parseDesignLock, } from "@omacode/core/design/revision";
|
|
25
|
+
import { sha256File } from "@omacode/core/hash";
|
|
26
|
+
import { designShellHtml } from "./design-shell.js";
|
|
27
|
+
import { commitPaths, exec } from "./worktree/git.js";
|
|
28
|
+
const LOOPBACK = "127.0.0.1";
|
|
29
|
+
const DESIGN_SUBDIR = "design"; // The same subtree the one-writer lock uses (DESIGN_LOCK_SUBDIR in the design package).
|
|
30
|
+
const SESSION_FILE = "session.json";
|
|
31
|
+
const normalizePartPath = (path) => path.split("\\").join("/").replace(/^\.\//, "").replace(/\/+$/, "");
|
|
32
|
+
const under = (base, path) => {
|
|
33
|
+
if (!base || base === ".")
|
|
34
|
+
return true;
|
|
35
|
+
return path === base || path.startsWith(`${base}/`);
|
|
36
|
+
};
|
|
37
|
+
// Whether a committed path belongs to a part: the part's own served directory, or its source when that lives outside
|
|
38
|
+
// it. A composition's source is the deck the agent edits while `path` is the build output, so a source commit has to
|
|
39
|
+
// settle the intent even though the path it names is not under the served directory.
|
|
40
|
+
function commitTouchesPart(part, path) {
|
|
41
|
+
const p = normalizePartPath(path);
|
|
42
|
+
if (under(normalizePartPath(part.path), p))
|
|
43
|
+
return true;
|
|
44
|
+
return part.source !== undefined && part.source !== "" && under(normalizePartPath(part.source), p);
|
|
45
|
+
}
|
|
46
|
+
// The newest modification time of a path. A file's own mtime is the answer; a directory is walked because a deck's
|
|
47
|
+
// source is usually a directory of slides, and the build is newer only when every file in it is older than the source
|
|
48
|
+
// tree's newest file. Symlinks are skipped: the thing linked to may live outside the project, and its bytes are not
|
|
49
|
+
// what the deck build consumed under this path. A missing or unreadable path has no answer, so the caller can treat it
|
|
50
|
+
// as "not stale" and leave the failure to design.parts.
|
|
51
|
+
function newestMtime(path) {
|
|
52
|
+
try {
|
|
53
|
+
const stats = statSync(path);
|
|
54
|
+
if (!stats.isDirectory())
|
|
55
|
+
return stats.mtimeMs;
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
let newest;
|
|
61
|
+
try {
|
|
62
|
+
for (const entry of readdirSync(path, { withFileTypes: true })) {
|
|
63
|
+
if (entry.isSymbolicLink())
|
|
64
|
+
continue;
|
|
65
|
+
const mtime = newestMtime(join(path, entry.name));
|
|
66
|
+
if (mtime !== undefined && (newest === undefined || mtime > newest))
|
|
67
|
+
newest = mtime;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
return newest;
|
|
74
|
+
}
|
|
75
|
+
// The composition parts whose source is newer than their built entry. This is a pure read of the worktree: the shell
|
|
76
|
+
// and design_status ask on every call so an edited deck is never served as if it were the build of those bytes.
|
|
77
|
+
export function compositionStaleness(worktree, parts) {
|
|
78
|
+
const stale = [];
|
|
79
|
+
for (const part of parts) {
|
|
80
|
+
if (part.kind !== "composition")
|
|
81
|
+
continue;
|
|
82
|
+
const entry = newestMtime(resolve(worktree, part.path, part.entry));
|
|
83
|
+
const source = newestMtime(resolve(worktree, part.source));
|
|
84
|
+
if (entry === undefined || source === undefined)
|
|
85
|
+
continue;
|
|
86
|
+
if (source > entry)
|
|
87
|
+
stale.push(part.id);
|
|
88
|
+
}
|
|
89
|
+
return stale;
|
|
90
|
+
}
|
|
91
|
+
// design_commit's refusal rule for a composition: `path` is the served build output while `source` is what the agent
|
|
92
|
+
// edits. Committing the build would put generated bytes in git and leave the real deck unchanged, so name the source
|
|
93
|
+
// instead. Paths outside this part are untouched: an html part and a deck part may share a directory shape.
|
|
94
|
+
export function designCommitRefusal(worktree, paths) {
|
|
95
|
+
const manifestPath = join(worktree, ".design.json");
|
|
96
|
+
if (!existsSync(manifestPath))
|
|
97
|
+
return undefined;
|
|
98
|
+
const manifest = readDesignManifest(manifestPath, { root: worktree }).manifest;
|
|
99
|
+
if (!manifest)
|
|
100
|
+
return undefined;
|
|
101
|
+
for (const part of manifest.parts) {
|
|
102
|
+
if (part.kind !== "composition")
|
|
103
|
+
continue;
|
|
104
|
+
const base = resolve(worktree, part.path);
|
|
105
|
+
const entry = resolve(base, part.entry);
|
|
106
|
+
const source = resolve(worktree, part.source);
|
|
107
|
+
for (const path of paths) {
|
|
108
|
+
const target = resolve(worktree, path);
|
|
109
|
+
const inPart = target === base || target.startsWith(`${base}${sep}`);
|
|
110
|
+
const inSource = target === source || target.startsWith(`${source}${sep}`);
|
|
111
|
+
if (target === entry || (inPart && !inSource)) {
|
|
112
|
+
return `composition ${part.id}: ${path} is built output; commit ${part.source} and leave the build out of git`;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
// The in-memory intent queue of one session. The HTTP handler only pushes; a turn drains with pull, and a landed
|
|
119
|
+
// commit settles. A push hands the queued count to the host's onIntent — the host may start the owning session's
|
|
120
|
+
// turn, the server itself never wakes an agent.
|
|
121
|
+
function createIntentStore(parts) {
|
|
122
|
+
const list = [];
|
|
123
|
+
const withState = (state) => list.filter((intent) => intent.state === state);
|
|
124
|
+
const withoutState = (intent) => ({
|
|
125
|
+
partId: intent.partId,
|
|
126
|
+
cssPath: intent.cssPath,
|
|
127
|
+
outerHTML: intent.outerHTML,
|
|
128
|
+
computedStyles: intent.computedStyles,
|
|
129
|
+
prompt: intent.prompt,
|
|
130
|
+
});
|
|
131
|
+
return {
|
|
132
|
+
pending: () => withState("queued"),
|
|
133
|
+
inflight: () => withState("inflight"),
|
|
134
|
+
push: (intent) => {
|
|
135
|
+
list.push({ ...intent, state: "queued" });
|
|
136
|
+
},
|
|
137
|
+
pull: () => {
|
|
138
|
+
const queued = withState("queued");
|
|
139
|
+
for (const intent of queued)
|
|
140
|
+
intent.state = "inflight";
|
|
141
|
+
return queued.map(withoutState);
|
|
142
|
+
},
|
|
143
|
+
settle: (paths) => {
|
|
144
|
+
const committed = paths.map(normalizePartPath);
|
|
145
|
+
const touched = new Set(parts.filter((part) => committed.some((path) => commitTouchesPart(part, path))).map((part) => part.id));
|
|
146
|
+
let done = 0;
|
|
147
|
+
for (const intent of list) {
|
|
148
|
+
if (intent.state !== "inflight" || !touched.has(intent.partId))
|
|
149
|
+
continue;
|
|
150
|
+
intent.state = "done";
|
|
151
|
+
done++;
|
|
152
|
+
}
|
|
153
|
+
return done;
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
export function createIntentWake(prompt, options = {}) {
|
|
158
|
+
const delayMs = options.delayMs ?? 1500;
|
|
159
|
+
let timer;
|
|
160
|
+
let cancelled = false;
|
|
161
|
+
const fire = (queued) => {
|
|
162
|
+
timer = undefined;
|
|
163
|
+
if (cancelled)
|
|
164
|
+
return;
|
|
165
|
+
const message = options.text
|
|
166
|
+
?? `[micromanager] The user queued ${queued} change(s) on the design canvas. Take the turn: call design_pull, edit the part files it names, then design_commit their part paths.`;
|
|
167
|
+
try {
|
|
168
|
+
// A wake that cannot start is not a data loss: the intent stays queued and the turn-start drain note still
|
|
169
|
+
// fires. The rejection is swallowed, not surfaced.
|
|
170
|
+
void Promise.resolve(prompt(message)).catch(() => { });
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
// Same for a prompt that throws synchronously.
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
return {
|
|
177
|
+
notify: (queued) => {
|
|
178
|
+
if (cancelled || timer !== undefined)
|
|
179
|
+
return;
|
|
180
|
+
timer = setTimeout(() => fire(queued), delayMs);
|
|
181
|
+
// A wake that never fires must not keep the process alive on its own.
|
|
182
|
+
timer.unref?.();
|
|
183
|
+
},
|
|
184
|
+
cancel: () => {
|
|
185
|
+
cancelled = true;
|
|
186
|
+
if (timer !== undefined) {
|
|
187
|
+
clearTimeout(timer);
|
|
188
|
+
timer = undefined;
|
|
189
|
+
}
|
|
190
|
+
},
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
export function createEventStream() {
|
|
194
|
+
const subscribers = new Set();
|
|
195
|
+
return {
|
|
196
|
+
subscribe(res) {
|
|
197
|
+
subscribers.add(res);
|
|
198
|
+
// A comment opens the stream, so a client's `open` event fires before the first real event and
|
|
199
|
+
// a client that connects to a quiet session knows the stream is live.
|
|
200
|
+
try {
|
|
201
|
+
res.write(": stream open\n\n");
|
|
202
|
+
}
|
|
203
|
+
catch {
|
|
204
|
+
// A subscriber that has gone away is dropped rather than breaking the others.
|
|
205
|
+
subscribers.delete(res);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
res.on("close", () => {
|
|
209
|
+
subscribers.delete(res);
|
|
210
|
+
});
|
|
211
|
+
},
|
|
212
|
+
publish(event) {
|
|
213
|
+
const frame = `event: ${event.type}\ndata: ${canonicalJson(event)}\n\n`;
|
|
214
|
+
for (const res of [...subscribers]) {
|
|
215
|
+
try {
|
|
216
|
+
res.write(frame);
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
// A subscriber that has gone away is dropped rather than breaking the others.
|
|
220
|
+
subscribers.delete(res);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
},
|
|
224
|
+
close() {
|
|
225
|
+
for (const res of [...subscribers]) {
|
|
226
|
+
try {
|
|
227
|
+
res.end();
|
|
228
|
+
}
|
|
229
|
+
catch {
|
|
230
|
+
// Ending a connection that is already gone is not a failure.
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
subscribers.clear();
|
|
234
|
+
},
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
// Keyed by the worktree path, so two projects can be open at once. A second open of an already open worktree is
|
|
238
|
+
// refused with the holder's sessionID instead of taking over its ports or its journal.
|
|
239
|
+
export const designSessions = new Map();
|
|
240
|
+
const opening = new Map();
|
|
241
|
+
export function designSession(worktree) {
|
|
242
|
+
return designSessions.get(worktree) ?? [...designSessions.values()].find((s) => realish(s.worktree) === realish(worktree));
|
|
243
|
+
}
|
|
244
|
+
export function designSessionPath(worktree) {
|
|
245
|
+
return statePath(worktree, DESIGN_SUBDIR, SESSION_FILE);
|
|
246
|
+
}
|
|
247
|
+
// Where the canvas URL is handed to the user. The shell URL carries the session token, so it must not live in the
|
|
248
|
+
// worktree's tracked files: it is written under the project state dir instead, with 0600.
|
|
249
|
+
export function designCanvasUrlPath(worktree) {
|
|
250
|
+
return statePath(worktree, DESIGN_SUBDIR, "canvas.url");
|
|
251
|
+
}
|
|
252
|
+
export function writeDesignCanvasUrl(worktree, shellUrl) {
|
|
253
|
+
const path = designCanvasUrlPath(worktree);
|
|
254
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
255
|
+
writeFileSync(path, `${shellUrl}\n`, { mode: 0o600 });
|
|
256
|
+
return path;
|
|
257
|
+
}
|
|
258
|
+
// The overlay options a design tool needs: the first part's id arms the selection bridge, so a click in any of the
|
|
259
|
+
// session's own iframes is labelled with a part the control port actually knows. A manifest that cannot be read or
|
|
260
|
+
// parsed is refused rather than opened with a guessed id — a canvas that silently labels selections "site" would
|
|
261
|
+
// queue intents for a part that may not exist.
|
|
262
|
+
export function designOpenOptions(worktree) {
|
|
263
|
+
const read = readDesignManifest(join(worktree, ".design.json"), { root: worktree });
|
|
264
|
+
const part = read.manifest?.parts[0];
|
|
265
|
+
if (!part)
|
|
266
|
+
throw new Error(`design_open needs a valid .design.json: ${read.errors.join("; ") || "no parts"}`);
|
|
267
|
+
return { partId: part.id };
|
|
268
|
+
}
|
|
269
|
+
// Open a design canvas for a worktree. Alias kept for the design tools (S9).
|
|
270
|
+
export async function openDesign(worktree, sessionID, options = {}) {
|
|
271
|
+
return startDesign(worktree, sessionID, options);
|
|
272
|
+
}
|
|
273
|
+
export async function startDesign(worktreeAbsPath, sessionID, options = {}) {
|
|
274
|
+
if (!isAbsolute(worktreeAbsPath))
|
|
275
|
+
throw new TypeError("design worktree must be an absolute path");
|
|
276
|
+
if (!sessionID.trim())
|
|
277
|
+
throw new TypeError("design session needs a sessionID");
|
|
278
|
+
if (!statSync(worktreeAbsPath).isDirectory())
|
|
279
|
+
throw new Error(`design worktree is not a directory: ${worktreeAbsPath}`);
|
|
280
|
+
try {
|
|
281
|
+
const inside = execFileSync("git", ["rev-parse", "--is-inside-work-tree"], { cwd: worktreeAbsPath, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
282
|
+
if (inside !== "true")
|
|
283
|
+
throw new Error("not a git worktree");
|
|
284
|
+
}
|
|
285
|
+
catch (err) {
|
|
286
|
+
if (err instanceof Error && err.message === "not a git worktree")
|
|
287
|
+
throw new Error(`design worktree is not inside a git worktree: ${worktreeAbsPath}`);
|
|
288
|
+
throw new Error(`design worktree is not inside a git worktree: ${worktreeAbsPath}`);
|
|
289
|
+
}
|
|
290
|
+
const holder = designSession(worktreeAbsPath);
|
|
291
|
+
if (holder)
|
|
292
|
+
throw new Error(`design worktree ${worktreeAbsPath} is already open by session ${holder.sessionID}`);
|
|
293
|
+
const pending = opening.get(worktreeAbsPath);
|
|
294
|
+
if (pending) {
|
|
295
|
+
const winner = await pending.catch(() => undefined);
|
|
296
|
+
if (winner)
|
|
297
|
+
throw new Error(`design worktree ${worktreeAbsPath} is already open by session ${winner.sessionID}`);
|
|
298
|
+
}
|
|
299
|
+
const started = bootDesign(worktreeAbsPath, sessionID, options);
|
|
300
|
+
opening.set(worktreeAbsPath, started);
|
|
301
|
+
try {
|
|
302
|
+
return await started;
|
|
303
|
+
}
|
|
304
|
+
finally {
|
|
305
|
+
opening.delete(worktreeAbsPath);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
async function bootDesign(worktree, sessionID, options) {
|
|
309
|
+
// One writer per worktree: the session takes the one-writer lock before it opens a port. A live lock held by
|
|
310
|
+
// someone else fails the open here, before any listener exists; a stale one (a restarted hub's, or a heartbeat
|
|
311
|
+
// long expired) is taken over by acquireDesignLock. The hub identity is fixed once for the session's life so
|
|
312
|
+
// every heartbeat compares against the same record and clock drift between calls cannot read as a restart.
|
|
313
|
+
const lockFile = designLockPath(worktree);
|
|
314
|
+
const now = options.now ?? Date.now;
|
|
315
|
+
const hub = currentHub(now());
|
|
316
|
+
const acquired = await acquireDesignLock(lockFile, { sessionID, worktree }, { now, hub });
|
|
317
|
+
if (!acquired.acquired)
|
|
318
|
+
throw new Error(`design worktree ${worktree} is locked: ${acquired.reason}`);
|
|
319
|
+
// Frees this session's own lock: only a record this session holds is removed, so a later holder's survives.
|
|
320
|
+
const releaseOwnLock = () => {
|
|
321
|
+
try {
|
|
322
|
+
const lock = parseDesignLock(JSON.parse(readFileSync(lockFile, "utf8")));
|
|
323
|
+
if (lock && lock.sessionID === sessionID && lock.worktree === worktree)
|
|
324
|
+
unlinkSync(lockFile);
|
|
325
|
+
}
|
|
326
|
+
catch {
|
|
327
|
+
// A missing or unreadable lock is already free.
|
|
328
|
+
}
|
|
329
|
+
};
|
|
330
|
+
const token = randomBytes(32).toString("hex");
|
|
331
|
+
let shellUrl = "";
|
|
332
|
+
const manifestPath = join(worktree, ".design.json");
|
|
333
|
+
const manifest = existsSync(manifestPath) ? readDesignManifest(manifestPath, { root: worktree }).manifest : undefined;
|
|
334
|
+
const shellParts = (manifest?.parts ?? []).map((p) => ({
|
|
335
|
+
id: p.id,
|
|
336
|
+
kind: p.kind,
|
|
337
|
+
path: p.path,
|
|
338
|
+
entry: p.entry,
|
|
339
|
+
driver: p.driver,
|
|
340
|
+
}));
|
|
341
|
+
const watchParts = options.parts ?? (manifest?.parts ?? []).map((p) => ({ id: p.id, path: p.path, source: p.source }));
|
|
342
|
+
// The parts that can carry design tokens (S13): the token file lives in the part's directory, and the manifest may
|
|
343
|
+
// name a different file for it.
|
|
344
|
+
const tokenParts = (manifest?.parts ?? []).map((p) => ({
|
|
345
|
+
id: p.id,
|
|
346
|
+
directory: p.path ? join(worktree, p.path) : worktree,
|
|
347
|
+
tokens: typeof p.tokens === "string" ? p.tokens : undefined,
|
|
348
|
+
}));
|
|
349
|
+
// S13 · The slider panel's controls. A numeric token becomes a slider over a range around its value; the design's own
|
|
350
|
+
// tokens decide which controls exist, so a design with no numeric tokens shows no sliders.
|
|
351
|
+
const shellSliders = await buildShellSliders(tokenParts);
|
|
352
|
+
const shellTokens = await readShellTokens(tokenParts);
|
|
353
|
+
const overlay = options.overlay === undefined && options.partId === undefined && options.shellOrigin === undefined
|
|
354
|
+
? undefined
|
|
355
|
+
: {
|
|
356
|
+
partId: options.partId,
|
|
357
|
+
source: options.overlay,
|
|
358
|
+
shellOrigin: () => options.shellOrigin ?? (shellUrl ? new URL(shellUrl).origin : ""),
|
|
359
|
+
};
|
|
360
|
+
// The shell's health ping is this session's heartbeat (design-shell.ts pings /api/health on an interval): every
|
|
361
|
+
// authorized health request refreshes the one-writer lock's lastHeartbeat. A heartbeat that cannot be written
|
|
362
|
+
// (the lock moved on) is not a health failure — the servers are what health answers for, and the reaper reads
|
|
363
|
+
// the lock it can see.
|
|
364
|
+
const beat = async () => {
|
|
365
|
+
try {
|
|
366
|
+
await heartbeatDesignLock(lockFile, sessionID, { now, hub });
|
|
367
|
+
}
|
|
368
|
+
catch {
|
|
369
|
+
// A lock that cannot be refreshed is not a health failure.
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
const content = createServer((req, res) => contentRequest(worktree, req, res, overlay));
|
|
373
|
+
let contentUrl = "";
|
|
374
|
+
let selection;
|
|
375
|
+
const store = { get: () => selection, set: (value) => { selection = value; } };
|
|
376
|
+
const intents = createIntentStore(watchParts);
|
|
377
|
+
const knownParts = new Set(watchParts.map((part) => part.id));
|
|
378
|
+
const events = createEventStream();
|
|
379
|
+
const watcher = watchParts.length > 0 ? createDesignWatcher({ root: worktree, parts: watchParts }) : undefined;
|
|
380
|
+
watcher?.on("reload", (event) => events.publish(event));
|
|
381
|
+
// Recompute the staleness per call: the agent may rebuild the deck, or edit its source, while the canvas is open,
|
|
382
|
+
// so /api/state must report the pair as it is now rather than the one the session opened with. The shell's initial
|
|
383
|
+
// HTML keeps the static parts; its 2 s poll replaces the badges from this.
|
|
384
|
+
const partsNow = () => {
|
|
385
|
+
const stale = compositionStaleness(worktree, manifest?.parts ?? []);
|
|
386
|
+
return shellParts.map((part) => ({ ...part, stale: stale.includes(part.id) }));
|
|
387
|
+
};
|
|
388
|
+
const control = createServer((req, res) => {
|
|
389
|
+
void controlRequest(req, res, token, worktree, sessionID, contentUrl, shellUrl, store, events, shellParts, partsNow, knownParts, intents, options.onIntent, beat, tokenParts, lockFile, shellSliders, shellTokens, now, hub).catch(() => {
|
|
390
|
+
if (res.headersSent)
|
|
391
|
+
res.end();
|
|
392
|
+
else
|
|
393
|
+
refuse(res, 500, "internal error");
|
|
394
|
+
});
|
|
395
|
+
});
|
|
396
|
+
try {
|
|
397
|
+
contentUrl = await bind(content);
|
|
398
|
+
const shellBase = await bind(control); // Both sockets are live at once, so port 0 cannot hand out the same port twice.
|
|
399
|
+
shellUrl = `${shellBase}/?token=${token}`;
|
|
400
|
+
}
|
|
401
|
+
catch (error) {
|
|
402
|
+
releaseOwnLock();
|
|
403
|
+
watcher?.close();
|
|
404
|
+
events.close();
|
|
405
|
+
await Promise.all([closeServer(content), closeServer(control)]);
|
|
406
|
+
throw error;
|
|
407
|
+
}
|
|
408
|
+
const journalPath = designSessionPath(worktree);
|
|
409
|
+
const journal = {
|
|
410
|
+
contentUrl,
|
|
411
|
+
shellUrl,
|
|
412
|
+
token,
|
|
413
|
+
pid: process.pid,
|
|
414
|
+
bootTime: Date.now() - Math.round(process.uptime() * 1000),
|
|
415
|
+
};
|
|
416
|
+
try {
|
|
417
|
+
mkdirSync(dirname(journalPath), { recursive: true });
|
|
418
|
+
writeFileSync(journalPath, `${canonicalJson(journal)}\n`, { mode: 0o600 });
|
|
419
|
+
}
|
|
420
|
+
catch (error) {
|
|
421
|
+
releaseOwnLock();
|
|
422
|
+
watcher?.close();
|
|
423
|
+
events.close();
|
|
424
|
+
await Promise.all([closeServer(content), closeServer(control)]);
|
|
425
|
+
throw error;
|
|
426
|
+
}
|
|
427
|
+
let closed = false;
|
|
428
|
+
const session = {
|
|
429
|
+
worktree,
|
|
430
|
+
sessionID,
|
|
431
|
+
contentUrl,
|
|
432
|
+
shellUrl,
|
|
433
|
+
token,
|
|
434
|
+
journalPath,
|
|
435
|
+
close: async (closeOptions = {}) => {
|
|
436
|
+
if (closed)
|
|
437
|
+
return;
|
|
438
|
+
closed = true;
|
|
439
|
+
watcher?.close();
|
|
440
|
+
events.close();
|
|
441
|
+
await Promise.all([closeServer(content), closeServer(control)]);
|
|
442
|
+
if (designSessions.get(worktree) === session)
|
|
443
|
+
designSessions.delete(worktree);
|
|
444
|
+
releaseOwnLock();
|
|
445
|
+
if (!closeOptions.keepJournal) {
|
|
446
|
+
try {
|
|
447
|
+
// Only remove our own journal: a later session may have replaced it after an earlier close.
|
|
448
|
+
const text = readFileSync(journalPath, "utf8");
|
|
449
|
+
if (JSON.parse(text).token === token)
|
|
450
|
+
unlinkSync(journalPath);
|
|
451
|
+
}
|
|
452
|
+
catch {
|
|
453
|
+
// A missing or unreadable journal is not a failure to release the ports.
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
},
|
|
457
|
+
status: () => {
|
|
458
|
+
return {
|
|
459
|
+
worktree,
|
|
460
|
+
sessionID,
|
|
461
|
+
contentUrl,
|
|
462
|
+
shellUrl,
|
|
463
|
+
parts: partsNow(),
|
|
464
|
+
selection: selection,
|
|
465
|
+
queued: intents.pending().length,
|
|
466
|
+
inflight: intents.inflight().length,
|
|
467
|
+
};
|
|
468
|
+
},
|
|
469
|
+
pullIntents: () => intents.pull(),
|
|
470
|
+
settleIntents: (paths) => intents.settle(paths),
|
|
471
|
+
};
|
|
472
|
+
designSessions.set(worktree, session);
|
|
473
|
+
return session;
|
|
474
|
+
}
|
|
475
|
+
// Reap the dead sessions, returning the worktrees that were reaped. The gate is the lock record itself: a session
|
|
476
|
+
// is reaped only when its own lock's heartbeat has been quiet past the timeout AND the owning session has ended. A
|
|
477
|
+
// record the session does not hold (a missing, corrupt or taken-over lock) is no heartbeat evidence, so such a
|
|
478
|
+
// session is left alone. Reaping closes both origins, frees the lock and keeps the journal for diagnosis.
|
|
479
|
+
export async function reapDesignSessions(reapOptions = {}) {
|
|
480
|
+
const now = reapOptions.now ?? Date.now;
|
|
481
|
+
const heartbeatMs = reapOptions.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
|
|
482
|
+
const sessionLive = reapOptions.sessionLive ?? (() => true);
|
|
483
|
+
const reaped = [];
|
|
484
|
+
for (const session of reapOptions.sessions ?? [...designSessions.values()]) {
|
|
485
|
+
let lock;
|
|
486
|
+
try {
|
|
487
|
+
lock = parseDesignLock(JSON.parse(readFileSync(designLockPath(session.worktree), "utf8")));
|
|
488
|
+
}
|
|
489
|
+
catch {
|
|
490
|
+
// No lock, no heartbeat evidence: not reaped.
|
|
491
|
+
}
|
|
492
|
+
if (!lock || lock.sessionID !== session.sessionID)
|
|
493
|
+
continue;
|
|
494
|
+
if (now() - lock.lastHeartbeat <= heartbeatMs)
|
|
495
|
+
continue;
|
|
496
|
+
if (sessionLive(session.sessionID))
|
|
497
|
+
continue;
|
|
498
|
+
await session.close({ keepJournal: true });
|
|
499
|
+
reaped.push(session.worktree);
|
|
500
|
+
}
|
|
501
|
+
return reaped;
|
|
502
|
+
}
|
|
503
|
+
// A journal's bootTime and this process's are both `now - uptime*1000`, which two computations round apart by a
|
|
504
|
+
// millisecond or two; a restarted process is off by its whole uptime instead. Tolerance separates those cases.
|
|
505
|
+
const BOOT_TOLERANCE_MS = 2_000;
|
|
506
|
+
// What a startDesign caller does instead of opening blind: read the worktree's journal, and when it belongs to this
|
|
507
|
+
// process AND its origins still answer with the journal's token, restore that live session — the same URLs, the
|
|
508
|
+
// same pair, not a second pair. Anything else (no journal, a journal of a dead process, a pair that no longer
|
|
509
|
+
// answers) is undefined, and the caller starts fresh; the lock's stale rule lets the open take over.
|
|
510
|
+
export async function recoverDesignSession(worktree, sessionID) {
|
|
511
|
+
let journal;
|
|
512
|
+
try {
|
|
513
|
+
journal = JSON.parse(readFileSync(designSessionPath(worktree), "utf8"));
|
|
514
|
+
}
|
|
515
|
+
catch {
|
|
516
|
+
return undefined; // No journal: nothing to recover.
|
|
517
|
+
}
|
|
518
|
+
const hub = currentHub();
|
|
519
|
+
// A different pid is a different process, whose servers died with it. A reused pid moves the boot time out of
|
|
520
|
+
// tolerance, so the two together name this process instance.
|
|
521
|
+
if (journal.pid !== hub.pid || Math.abs(journal.bootTime - hub.bootTime) > BOOT_TOLERANCE_MS)
|
|
522
|
+
return undefined;
|
|
523
|
+
const session = designSession(worktree);
|
|
524
|
+
if (!session || session.token !== journal.token)
|
|
525
|
+
return undefined;
|
|
526
|
+
if (sessionID !== undefined && session.sessionID !== sessionID)
|
|
527
|
+
return undefined;
|
|
528
|
+
// The URLs still have to answer, with the journal's token, before they are restored: a live pair is proved, not
|
|
529
|
+
// assumed.
|
|
530
|
+
try {
|
|
531
|
+
const health = new URL(journal.shellUrl);
|
|
532
|
+
health.pathname = "/health";
|
|
533
|
+
const res = await fetch(health, {
|
|
534
|
+
headers: { authorization: `Bearer ${journal.token}` },
|
|
535
|
+
signal: AbortSignal.timeout(1_000),
|
|
536
|
+
});
|
|
537
|
+
if (!res.ok)
|
|
538
|
+
return undefined;
|
|
539
|
+
}
|
|
540
|
+
catch {
|
|
541
|
+
return undefined;
|
|
542
|
+
}
|
|
543
|
+
return session;
|
|
544
|
+
}
|
|
545
|
+
// The design_release door: stop both servers, release the lock, keep the journal entry for diagnosis. The journal
|
|
546
|
+
// stays because a released canvas is a fact about the past — the worktree, the origins, when it closed — that the
|
|
547
|
+
// next diagnosis reads without the servers running.
|
|
548
|
+
export async function releaseDesign(worktree) {
|
|
549
|
+
const session = designSession(worktree);
|
|
550
|
+
if (!session)
|
|
551
|
+
return `No design session is open for ${realish(worktree)}.`;
|
|
552
|
+
const journalPath = session.journalPath;
|
|
553
|
+
await session.close({ keepJournal: true });
|
|
554
|
+
return `Released the design canvas for ${realish(worktree)}: both session servers are stopped and the lock is free. The session journal is kept at ${realish(journalPath)} for diagnosis.`;
|
|
555
|
+
}
|
|
556
|
+
// The module-level status: what the canvas holds now, without duplicating the control port's state logic.
|
|
557
|
+
export function designStatus(worktree) {
|
|
558
|
+
const session = designSession(worktree);
|
|
559
|
+
if (!session)
|
|
560
|
+
return { error: `No design session is open for ${realish(worktree)}.` };
|
|
561
|
+
return session.status();
|
|
562
|
+
}
|
|
563
|
+
// The four design rules over what the session's worktree holds right now. `status()` stays synchronous for the shell
|
|
564
|
+
// and the prompt hook; design_status awaits this so the agent sees the gate's verdicts, not only the part list. The
|
|
565
|
+
// lock names the project; without revision hashes the rule checks that much and says so.
|
|
566
|
+
export async function designChecks(worktree) {
|
|
567
|
+
const at = resolve(worktree);
|
|
568
|
+
return runDesignChecks({ root: at, lock: designLockPath(at) });
|
|
569
|
+
}
|
|
570
|
+
// design_status's reply: the session status and the gate's four verdicts, plus one short line when a composition's
|
|
571
|
+
// source is newer than its build. The line is text because it is the one fact the agent must act on before judging a
|
|
572
|
+
// render; it is not a fifth check and never changes a verdict. Exported so the exact text the tool returns is testable
|
|
573
|
+
// without going through the MCP wire.
|
|
574
|
+
export async function designStatusReport(worktree) {
|
|
575
|
+
const status = designStatus(worktree);
|
|
576
|
+
if ("error" in status)
|
|
577
|
+
return status;
|
|
578
|
+
const checks = await designChecks(status.worktree);
|
|
579
|
+
const reply = JSON.stringify({ ...status, checks });
|
|
580
|
+
const stale = status.parts.filter((part) => part.stale).map((part) => part.id);
|
|
581
|
+
if (stale.length === 0)
|
|
582
|
+
return reply;
|
|
583
|
+
return `${reply}\nstale: ${stale.join(", ")} (its source is newer than the built entry; run the deck build before judging the render)`;
|
|
584
|
+
}
|
|
585
|
+
// design_pull: hand the queued intents of a worktree to the agent turn that asks for them. The intents leave the queue
|
|
586
|
+
// and stay in-flight until a commit of their part lands, so a later turn is not given the same request again. A turn
|
|
587
|
+
// that drains nothing gets an empty list, not an error.
|
|
588
|
+
export function pullDesignIntents(worktree) {
|
|
589
|
+
const session = designSession(worktree);
|
|
590
|
+
if (!session)
|
|
591
|
+
return { error: `No design session is open for ${realish(worktree)}.` };
|
|
592
|
+
return { intents: session.pullIntents() };
|
|
593
|
+
}
|
|
594
|
+
// A commit landed: settle the in-flight intents of the parts it touched. Called by design_commit after commitPaths
|
|
595
|
+
// returned a hash, so an intent is done only when an actual commit carries its part.
|
|
596
|
+
export function settleDesignIntents(worktree, paths) {
|
|
597
|
+
return designSession(worktree)?.settleIntents(paths) ?? 0;
|
|
598
|
+
}
|
|
599
|
+
function bind(server) {
|
|
600
|
+
return new Promise((ok, fail) => {
|
|
601
|
+
const onError = (error) => fail(error);
|
|
602
|
+
server.once("error", onError);
|
|
603
|
+
server.listen(0, LOOPBACK, () => {
|
|
604
|
+
server.off("error", onError);
|
|
605
|
+
const address = server.address();
|
|
606
|
+
if (!address || typeof address === "string") {
|
|
607
|
+
fail(new Error("design server did not bind a loopback port"));
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
ok(`http://${LOOPBACK}:${address.port}`);
|
|
611
|
+
});
|
|
612
|
+
});
|
|
613
|
+
}
|
|
614
|
+
async function closeServer(server) {
|
|
615
|
+
if (!server.listening)
|
|
616
|
+
return;
|
|
617
|
+
await new Promise((ok) => {
|
|
618
|
+
// fetch() keeps connections alive. closeAllConnections makes close() finish and frees the port for the next test.
|
|
619
|
+
server.close(() => ok());
|
|
620
|
+
server.closeAllConnections();
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
const TYPES = {
|
|
624
|
+
".css": "text/css; charset=utf-8",
|
|
625
|
+
".html": "text/html; charset=utf-8",
|
|
626
|
+
".js": "text/javascript; charset=utf-8",
|
|
627
|
+
".json": "application/json; charset=utf-8",
|
|
628
|
+
".mjs": "text/javascript; charset=utf-8",
|
|
629
|
+
".png": "image/png",
|
|
630
|
+
".svg": "image/svg+xml",
|
|
631
|
+
".webp": "image/webp",
|
|
632
|
+
};
|
|
633
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
634
|
+
// The iframe that framed a part names its own part in the query. The value is untrusted text that ends up in the
|
|
635
|
+
// injected config, so only an id-shaped value is honoured; anything else falls back to the session's own part.
|
|
636
|
+
const DESIGN_PART_PARAM = "__design_part";
|
|
637
|
+
const DESIGN_PART_ID = /^[A-Za-z0-9._-]{1,64}$/;
|
|
638
|
+
// A refusal. With extra fields the answer is JSON (the token write refuses with the hash the client must re-read);
|
|
639
|
+
// without them it stays the plain text the other endpoints send.
|
|
640
|
+
function refuse(res, status, message, extra) {
|
|
641
|
+
if (extra) {
|
|
642
|
+
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
|
|
643
|
+
res.end(canonicalJson({ ok: false, error: message, ...extra }));
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
res.writeHead(status, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" });
|
|
647
|
+
res.end(message);
|
|
648
|
+
}
|
|
649
|
+
function contentRequest(root, req, res, overlay) {
|
|
650
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
651
|
+
res.setHeader("Allow", "GET, HEAD");
|
|
652
|
+
refuse(res, 405, "the content port is read-only");
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
let url;
|
|
656
|
+
let pathname;
|
|
657
|
+
try {
|
|
658
|
+
url = new URL(req.url ?? "/", `http://${LOOPBACK}`);
|
|
659
|
+
pathname = decodeURIComponent(url.pathname);
|
|
660
|
+
}
|
|
661
|
+
catch {
|
|
662
|
+
refuse(res, 400, "bad path");
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
665
|
+
// The content port is files only. There is no API here — the control port owns requests of that shape.
|
|
666
|
+
if (pathname === "/api" || pathname.startsWith("/api/")) {
|
|
667
|
+
refuse(res, 404, "not found");
|
|
668
|
+
return;
|
|
669
|
+
}
|
|
670
|
+
let candidate = resolve(root, `.${pathname}`);
|
|
671
|
+
const safe = (path) => insideResolved(root, path) && insideResolved(root, realish(path));
|
|
672
|
+
if (!safe(candidate)) {
|
|
673
|
+
refuse(res, 403, "outside the worktree");
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
676
|
+
const rel = relative(root, realish(candidate)).split(sep).join("/");
|
|
677
|
+
if (inStateDir(rel)) {
|
|
678
|
+
refuse(res, 404, "not found");
|
|
679
|
+
return;
|
|
680
|
+
}
|
|
681
|
+
try {
|
|
682
|
+
if (statSync(candidate).isDirectory()) {
|
|
683
|
+
candidate = join(candidate, "index.html");
|
|
684
|
+
if (!safe(candidate)) {
|
|
685
|
+
refuse(res, 403, "outside the worktree");
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
if (!statSync(candidate).isFile()) {
|
|
690
|
+
refuse(res, 404, "not found");
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
catch {
|
|
695
|
+
refuse(res, 404, "not found");
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
const type = TYPES[extname(candidate).toLowerCase()] ?? "application/octet-stream";
|
|
699
|
+
// The bytes on disk are never written here: the overlay is added to the response buffer only, and only for HTML.
|
|
700
|
+
// Every other type — including the raw copy the wrapper frames — leaves this function as the same Buffer it read.
|
|
701
|
+
let body = readFileSync(candidate);
|
|
702
|
+
if (overlay && type.startsWith("text/html") && !isRawRequest(url.search)) {
|
|
703
|
+
// The shell frames every part with its own id in the query, so a multi-part canvas labels each selection
|
|
704
|
+
// correctly. The session's partId stays the fallback for a page opened without that parameter.
|
|
705
|
+
const requestedPart = url.searchParams.get(DESIGN_PART_PARAM);
|
|
706
|
+
const partId = requestedPart && DESIGN_PART_ID.test(requestedPart) ? requestedPart : overlay.partId;
|
|
707
|
+
const result = injectOverlay(body.toString("utf8"), {
|
|
708
|
+
partId,
|
|
709
|
+
shellOrigin: overlay.shellOrigin(),
|
|
710
|
+
source: overlay.source,
|
|
711
|
+
src: rawPartUrl(pathname, url.search),
|
|
712
|
+
});
|
|
713
|
+
body = Buffer.from(result.html, "utf8");
|
|
714
|
+
}
|
|
715
|
+
res.writeHead(200, {
|
|
716
|
+
"Content-Type": type,
|
|
717
|
+
"Content-Length": body.byteLength,
|
|
718
|
+
"Cache-Control": "no-store",
|
|
719
|
+
"X-Content-Type-Options": "nosniff",
|
|
720
|
+
});
|
|
721
|
+
res.end(req.method === "HEAD" ? undefined : body);
|
|
722
|
+
}
|
|
723
|
+
// ---------------------------------------------------------------------------------------------
|
|
724
|
+
// S13 · Design tokens and the slider write.
|
|
725
|
+
//
|
|
726
|
+
// A slider writes the token file; the renderer derives the CSS from it; both land in one commit. The write is a
|
|
727
|
+
// local file write, not a model call: consent.ts gates model egress, and a slider drag never leaves the machine.
|
|
728
|
+
//
|
|
729
|
+
// Two rules make the write safe:
|
|
730
|
+
//
|
|
731
|
+
// * The lock is re-read first. A write that landed after this session lost the lock would put another writer's
|
|
732
|
+
// work into this session's commit, so a lock that is not live and ours refuses the write.
|
|
733
|
+
// * The part hash is re-read first. The client sends the hash of the token file it last saw; a file that changed
|
|
734
|
+
// since then means someone else edited the tokens, and this write would silently drop their change, so it
|
|
735
|
+
// refuses with the current hash so the client can re-read and retry.
|
|
736
|
+
//
|
|
737
|
+
// One promise chain per project serializes the writes and their commits: two slider drags that land together must
|
|
738
|
+
// not fight over git's index lock. The chain is per project (the worktree), not per session, so a second session on
|
|
739
|
+
// the same project queues behind the first instead of colliding.
|
|
740
|
+
//
|
|
741
|
+
// A burst of slider drags is one change, not many. A drag sends a request per step, and a burst of steps that
|
|
742
|
+
// arrive while a write is in flight is coalesced: the newest token values win, the file is written once and the
|
|
743
|
+
// commit is made once. Every request in the burst gets that one commit's answer.
|
|
744
|
+
const tokenWriteChains = new Map();
|
|
745
|
+
const pendingTokenWrites = new Map();
|
|
746
|
+
// Run one job after the previous job of the same project finished. The chain never rejects: a failed job must not
|
|
747
|
+
// poison the ones behind it.
|
|
748
|
+
function queueTokenWrite(project, job) {
|
|
749
|
+
const previous = tokenWriteChains.get(project) ?? Promise.resolve();
|
|
750
|
+
const next = previous.then(job, job);
|
|
751
|
+
const settled = next.then(() => undefined, () => undefined);
|
|
752
|
+
tokenWriteChains.set(project, settled);
|
|
753
|
+
void settled.then(() => {
|
|
754
|
+
// The chain is dropped once it is idle, so a long-lived process does not keep one entry per project forever.
|
|
755
|
+
if (tokenWriteChains.get(project) === settled)
|
|
756
|
+
tokenWriteChains.delete(project);
|
|
757
|
+
});
|
|
758
|
+
return next;
|
|
759
|
+
}
|
|
760
|
+
// How long a burst is gathered before the write lands. A drag sends a step every few tens of milliseconds, so a
|
|
761
|
+
// short wait turns a handful of steps into one write; a step that arrives alone waits only this long.
|
|
762
|
+
const TOKEN_BURST_MS = 60;
|
|
763
|
+
// The hash of the token surface: the token file and the CSS rendered from it. One hash covers both files, so a
|
|
764
|
+
// client that read them together is refused when either moved under it.
|
|
765
|
+
async function tokenSurfaceHash(tokenFile, cssFile) {
|
|
766
|
+
const tokens = await fileHash(tokenFile);
|
|
767
|
+
const css = await fileHash(cssFile);
|
|
768
|
+
return createHash("sha256").update(`${tokens}:${css}`).digest("hex");
|
|
769
|
+
}
|
|
770
|
+
async function headCommit(worktree) {
|
|
771
|
+
const out = await exec("git", ["rev-parse", "HEAD"], { cwd: worktree });
|
|
772
|
+
return out.code === 0 ? out.stdout.trim() : "";
|
|
773
|
+
}
|
|
774
|
+
// Stage exactly the given paths, and nothing else. `git commit -- <paths>` can only commit paths git already knows,
|
|
775
|
+
// so a token file that is new to the repository has to be staged before it can be committed. `git add -- <paths>`
|
|
776
|
+
// names the paths one by one: an unrelated dirty file keeps whatever state it had.
|
|
777
|
+
async function stagePaths(worktree, paths) {
|
|
778
|
+
if (paths.length === 0)
|
|
779
|
+
return;
|
|
780
|
+
await exec("git", ["add", "--", ...paths], { cwd: worktree });
|
|
781
|
+
}
|
|
782
|
+
// The token file of a part: beside the part's entry, unless the manifest names another one.
|
|
783
|
+
export function designTokenPaths(part) {
|
|
784
|
+
const tokenFile = designTokensPath(part.directory, part.tokens);
|
|
785
|
+
return { tokenFile, cssFile: designTokensCssPath(tokenFile) };
|
|
786
|
+
}
|
|
787
|
+
// The hash of a file that is not there yet is the empty string: a client that never saw the file sends it, and a
|
|
788
|
+
// file that appeared since is a stale hash.
|
|
789
|
+
async function fileHash(file) {
|
|
790
|
+
try {
|
|
791
|
+
return await sha256File(file);
|
|
792
|
+
}
|
|
793
|
+
catch {
|
|
794
|
+
return "";
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
// The token values of the first part that has a token file: the slider panel writes those.
|
|
798
|
+
async function readShellTokens(parts) {
|
|
799
|
+
for (const part of parts) {
|
|
800
|
+
const read = await readDesignTokens(designTokenPaths(part).tokenFile);
|
|
801
|
+
if (read.tokens)
|
|
802
|
+
return { ...read.tokens };
|
|
803
|
+
}
|
|
804
|
+
return {};
|
|
805
|
+
}
|
|
806
|
+
// A slider over a numeric token. The range is the token's own neighbourhood, so the slider starts on the value the
|
|
807
|
+
// design already has and moves it in units that make sense for that magnitude.
|
|
808
|
+
function shellSlider(token, value) {
|
|
809
|
+
const magnitude = Math.max(1, Math.abs(value));
|
|
810
|
+
const step = magnitude >= 100 ? 10 : magnitude >= 10 ? 1 : 0.5;
|
|
811
|
+
return {
|
|
812
|
+
token,
|
|
813
|
+
label: token,
|
|
814
|
+
min: Math.max(0, value - magnitude * 2),
|
|
815
|
+
max: value + magnitude * 2,
|
|
816
|
+
step,
|
|
817
|
+
};
|
|
818
|
+
}
|
|
819
|
+
// The panel's controls, in a stable order: the token names sorted, so the panel does not shuffle between reloads.
|
|
820
|
+
async function buildShellSliders(parts) {
|
|
821
|
+
const tokens = await readShellTokens(parts);
|
|
822
|
+
return Object.keys(tokens)
|
|
823
|
+
.sort()
|
|
824
|
+
.filter((name) => typeof tokens[name] === "number" && Number.isFinite(tokens[name]))
|
|
825
|
+
.map((name) => shellSlider(name, tokens[name]));
|
|
826
|
+
}
|
|
827
|
+
async function controlRequest(req, res, token, worktree, sessionID, contentUrl, shellUrl, selection, events, parts, partsNow, knownParts, intents, onIntent, beat, tokens, lockFile, shellSliders, shellTokens, now, hub) {
|
|
828
|
+
const contentOrigin = new URL(contentUrl).origin;
|
|
829
|
+
const shellOrigin = new URL(shellUrl).origin;
|
|
830
|
+
res.setHeader("Access-Control-Allow-Origin", contentOrigin);
|
|
831
|
+
res.setHeader("Vary", "Origin");
|
|
832
|
+
res.setHeader("Access-Control-Allow-Headers", "authorization, content-type");
|
|
833
|
+
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
834
|
+
res.setHeader("Access-Control-Max-Age", "600");
|
|
835
|
+
if (req.method === "OPTIONS") {
|
|
836
|
+
res.writeHead(204);
|
|
837
|
+
res.end();
|
|
838
|
+
return;
|
|
839
|
+
}
|
|
840
|
+
const url = new URL(req.url ?? "/", `http://${LOOPBACK}`);
|
|
841
|
+
const header = req.headers.authorization;
|
|
842
|
+
const bearer = typeof header === "string" && header.toLowerCase().startsWith("bearer ")
|
|
843
|
+
? header.slice("bearer ".length).trim()
|
|
844
|
+
: undefined;
|
|
845
|
+
const query = url.searchParams.get("token") ?? undefined;
|
|
846
|
+
const authorized = bearer === token || query === token;
|
|
847
|
+
const api = url.pathname === "/api" || url.pathname.startsWith("/api/");
|
|
848
|
+
if (api && !authorized) {
|
|
849
|
+
refuse(res, 403, "forbidden");
|
|
850
|
+
return;
|
|
851
|
+
}
|
|
852
|
+
if (req.method === "GET" && (url.pathname === "/" || url.pathname === "/shell")) {
|
|
853
|
+
if (!authorized) {
|
|
854
|
+
refuse(res, 403, "forbidden");
|
|
855
|
+
return;
|
|
856
|
+
}
|
|
857
|
+
const body = designShellHtml({ token, contentOrigin, shellOrigin, parts, sliders: shellSliders, tokens: shellTokens });
|
|
858
|
+
res.writeHead(200, {
|
|
859
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
860
|
+
"Cache-Control": "no-store",
|
|
861
|
+
"X-Content-Type-Options": "nosniff",
|
|
862
|
+
});
|
|
863
|
+
res.end(body);
|
|
864
|
+
return;
|
|
865
|
+
}
|
|
866
|
+
if (req.method === "GET" && (url.pathname === "/health" || url.pathname === "/api/health")) {
|
|
867
|
+
if (!authorized) {
|
|
868
|
+
refuse(res, 403, "forbidden");
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
871
|
+
// The health ping is the session's heartbeat (S8): an authorized ping refreshes the one-writer lock's
|
|
872
|
+
// lastHeartbeat, so a shell that stays open keeps its session's lock live. Only an authorized ping beats — an
|
|
873
|
+
// anonymous one must not keep a session the shell no longer speaks for.
|
|
874
|
+
await beat();
|
|
875
|
+
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
|
|
876
|
+
res.end(canonicalJson({ ok: true, worktree, sessionID, contentOrigin }));
|
|
877
|
+
return;
|
|
878
|
+
}
|
|
879
|
+
// The canvas reads its status here: parts, the current selection, and how many intents are queued.
|
|
880
|
+
if (req.method === "GET" && url.pathname === "/api/state") {
|
|
881
|
+
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
|
|
882
|
+
res.end(canonicalJson({ ok: true, worktree, sessionID, parts: partsNow(), selection: selection.get() ?? null, queued: intents.pending().length, inflight: intents.inflight().length }));
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
// The reload events, over server-sent events. The stream stays open for as long as the client
|
|
886
|
+
// wants it; the server writes a frame per changed part.
|
|
887
|
+
if (req.method === "GET" && url.pathname === "/api/events") {
|
|
888
|
+
res.writeHead(200, {
|
|
889
|
+
"Content-Type": "text/event-stream; charset=utf-8",
|
|
890
|
+
"Cache-Control": "no-store",
|
|
891
|
+
Connection: "keep-alive",
|
|
892
|
+
});
|
|
893
|
+
res.flushHeaders?.();
|
|
894
|
+
events.subscribe(res);
|
|
895
|
+
return;
|
|
896
|
+
}
|
|
897
|
+
// The current selection. The canvas reads it on load and after a relay, so a page refresh does not lose the pick.
|
|
898
|
+
if (req.method === "GET" && url.pathname === "/api/selection") {
|
|
899
|
+
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
|
|
900
|
+
res.end(canonicalJson({ selection: selection.get() ?? null }));
|
|
901
|
+
return;
|
|
902
|
+
}
|
|
903
|
+
// A selection reaches the server in one of two legitimate ways, both named by their Origin. The overlay checks the
|
|
904
|
+
// shell origin before it posts, so a direct post comes from the content origin; the shell is the only page that holds
|
|
905
|
+
// the token, so its relay is a same-origin fetch that carries the shell origin. Anything else — a missing or foreign
|
|
906
|
+
// origin — is refused.
|
|
907
|
+
if (req.method === "POST" && url.pathname === "/api/selection") {
|
|
908
|
+
if (req.headers.origin !== shellOrigin && req.headers.origin !== contentOrigin) {
|
|
909
|
+
refuse(res, 403, "selection must come from the shell or the content origin");
|
|
910
|
+
return;
|
|
911
|
+
}
|
|
912
|
+
let text = "";
|
|
913
|
+
for await (const chunk of req) {
|
|
914
|
+
text += chunk.toString("utf8");
|
|
915
|
+
if (text.length > 64 * 1024) {
|
|
916
|
+
refuse(res, 413, "selection too large");
|
|
917
|
+
return;
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
let value;
|
|
921
|
+
try {
|
|
922
|
+
value = JSON.parse(text);
|
|
923
|
+
}
|
|
924
|
+
catch {
|
|
925
|
+
refuse(res, 400, "bad selection JSON");
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
if (!isSelection(value)) {
|
|
929
|
+
refuse(res, 400, "selection is missing the overlay fields");
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
selection.set(value);
|
|
933
|
+
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
|
|
934
|
+
res.end(canonicalJson({ ok: true }));
|
|
935
|
+
return;
|
|
936
|
+
}
|
|
937
|
+
// The canvas prompt box posts an intent scoped to the current selection. The intent is queued for the agent to drain
|
|
938
|
+
// (S10): a successful push stores it and hands the queued count to the host's onIntent, which may start the owning
|
|
939
|
+
// session's turn. The server itself never wakes an agent, and a refused intent notifies nobody.
|
|
940
|
+
if (req.method === "POST" && url.pathname === "/api/intent") {
|
|
941
|
+
let text = "";
|
|
942
|
+
for await (const chunk of req) {
|
|
943
|
+
text += chunk.toString("utf8");
|
|
944
|
+
if (text.length > 64 * 1024) {
|
|
945
|
+
refuse(res, 413, "intent too large");
|
|
946
|
+
return;
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
let value;
|
|
950
|
+
try {
|
|
951
|
+
value = JSON.parse(text);
|
|
952
|
+
}
|
|
953
|
+
catch {
|
|
954
|
+
refuse(res, 400, "bad intent JSON");
|
|
955
|
+
return;
|
|
956
|
+
}
|
|
957
|
+
const rec = isRecord(value) ? value : undefined;
|
|
958
|
+
const prompt = typeof rec?.prompt === "string" ? rec.prompt : typeof rec?.intent === "string" ? rec.intent : undefined;
|
|
959
|
+
const partId = typeof rec?.partId === "string" ? rec.partId : undefined;
|
|
960
|
+
const cssPath = typeof rec?.cssPath === "string" ? rec.cssPath : "";
|
|
961
|
+
const outerHTML = typeof rec?.outerHTML === "string" ? rec.outerHTML : "";
|
|
962
|
+
const styles = isRecord(rec?.computedStyles) ? rec.computedStyles : undefined;
|
|
963
|
+
const computedStyles = {};
|
|
964
|
+
if (styles)
|
|
965
|
+
for (const [k, v] of Object.entries(styles))
|
|
966
|
+
if (typeof v === "string")
|
|
967
|
+
computedStyles[k] = v;
|
|
968
|
+
if (!prompt || !partId) {
|
|
969
|
+
refuse(res, 400, "intent needs prompt and partId");
|
|
970
|
+
return;
|
|
971
|
+
}
|
|
972
|
+
if (!knownParts.has(partId)) {
|
|
973
|
+
refuse(res, 400, `unknown part: ${partId}`);
|
|
974
|
+
return;
|
|
975
|
+
}
|
|
976
|
+
intents.push({ partId, cssPath, outerHTML, computedStyles, prompt });
|
|
977
|
+
try {
|
|
978
|
+
onIntent?.(intents.pending().length);
|
|
979
|
+
}
|
|
980
|
+
catch {
|
|
981
|
+
// A host callback that fails is not a refusal: the intent is stored and the turn-start drain note still
|
|
982
|
+
// picks it up.
|
|
983
|
+
}
|
|
984
|
+
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
|
|
985
|
+
res.end(canonicalJson({ ok: true, queued: intents.pending().length }));
|
|
986
|
+
return;
|
|
987
|
+
}
|
|
988
|
+
// S13 · The slider panel reads the current tokens and their hash. The hash is what a write must quote, so a client
|
|
989
|
+
// that read the tokens and then writes them back is refused if the file moved under it.
|
|
990
|
+
if (req.method === "GET" && url.pathname === "/api/tokens") {
|
|
991
|
+
const partId = url.searchParams.get("partId") ?? tokens[0]?.id;
|
|
992
|
+
const part = tokens.find((p) => p.id === partId);
|
|
993
|
+
if (!part) {
|
|
994
|
+
refuse(res, 404, "unknown part");
|
|
995
|
+
return;
|
|
996
|
+
}
|
|
997
|
+
const { tokenFile, cssFile } = designTokenPaths(part);
|
|
998
|
+
const read = await readDesignTokens(tokenFile);
|
|
999
|
+
if (read.errors.length > 0) {
|
|
1000
|
+
refuse(res, 422, read.errors.join("; "));
|
|
1001
|
+
return;
|
|
1002
|
+
}
|
|
1003
|
+
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
|
|
1004
|
+
res.end(canonicalJson({ ok: true, partId: part.id, tokens: read.tokens ?? {}, hash: await tokenSurfaceHash(tokenFile, cssFile) }));
|
|
1005
|
+
return;
|
|
1006
|
+
}
|
|
1007
|
+
// S13 · A slider writes the design tokens. The body names the part, the token values and the hash of the token
|
|
1008
|
+
// file the client last saw.
|
|
1009
|
+
if (req.method === "PUT" && url.pathname === "/api/tokens") {
|
|
1010
|
+
let text = "";
|
|
1011
|
+
for await (const chunk of req) {
|
|
1012
|
+
text += chunk.toString("utf8");
|
|
1013
|
+
if (text.length > 256 * 1024) {
|
|
1014
|
+
refuse(res, 413, "tokens too large");
|
|
1015
|
+
return;
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
let value;
|
|
1019
|
+
try {
|
|
1020
|
+
value = JSON.parse(text);
|
|
1021
|
+
}
|
|
1022
|
+
catch {
|
|
1023
|
+
refuse(res, 400, "bad tokens JSON");
|
|
1024
|
+
return;
|
|
1025
|
+
}
|
|
1026
|
+
const rec = isRecord(value) ? value : undefined;
|
|
1027
|
+
const partId = typeof rec?.partId === "string" ? rec.partId : undefined;
|
|
1028
|
+
const hash = typeof rec?.hash === "string" ? rec.hash : undefined;
|
|
1029
|
+
const next = rec?.tokens;
|
|
1030
|
+
if (!partId || !isRecord(next)) {
|
|
1031
|
+
refuse(res, 400, "tokens need partId and a tokens object");
|
|
1032
|
+
return;
|
|
1033
|
+
}
|
|
1034
|
+
const part = tokens.find((p) => p.id === partId);
|
|
1035
|
+
if (!part) {
|
|
1036
|
+
refuse(res, 400, `unknown part: ${partId}`);
|
|
1037
|
+
return;
|
|
1038
|
+
}
|
|
1039
|
+
const result = await writeDesignTokens({
|
|
1040
|
+
worktree,
|
|
1041
|
+
sessionID,
|
|
1042
|
+
lockFile,
|
|
1043
|
+
part,
|
|
1044
|
+
tokens: next,
|
|
1045
|
+
hash,
|
|
1046
|
+
now,
|
|
1047
|
+
hub,
|
|
1048
|
+
});
|
|
1049
|
+
if (!result.ok) {
|
|
1050
|
+
// 409 is the conflict answer: the caller sent a hash that is not the file's any more, or the lock is gone. The
|
|
1051
|
+
// current hash comes back so the client can re-read the tokens and retry.
|
|
1052
|
+
refuse(res, 409, result.reason ?? "the token write was refused", result.hash ? { hash: result.hash } : undefined);
|
|
1053
|
+
return;
|
|
1054
|
+
}
|
|
1055
|
+
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
|
|
1056
|
+
res.end(canonicalJson({ ok: true, commit: result.commit ?? null, hash: result.hash }));
|
|
1057
|
+
return;
|
|
1058
|
+
}
|
|
1059
|
+
refuse(res, 404, "not found");
|
|
1060
|
+
}
|
|
1061
|
+
export async function writeDesignTokens(request) {
|
|
1062
|
+
const { worktree, sessionID, lockFile, part, tokens } = request;
|
|
1063
|
+
const { tokenFile, cssFile } = designTokenPaths(part);
|
|
1064
|
+
const key = `${worktree}\u0000${part.id}`;
|
|
1065
|
+
const claimed = request.hash ?? "";
|
|
1066
|
+
// A burst is one change. A write for this part is already on its way: this request joins it, and the newest token
|
|
1067
|
+
// values win. The hash the burst started from stays the one the write checks, so a request that carries a
|
|
1068
|
+
// different hash is a conflict and is refused on its own.
|
|
1069
|
+
const pending = pendingTokenWrites.get(key);
|
|
1070
|
+
if (pending) {
|
|
1071
|
+
if ((pending.base || "") !== claimed) {
|
|
1072
|
+
return { ok: false, reason: "the tokens changed since you read them", hash: pending.base };
|
|
1073
|
+
}
|
|
1074
|
+
pending.tokens = tokens;
|
|
1075
|
+
return new Promise((resolve) => {
|
|
1076
|
+
pending.waiters.push(resolve);
|
|
1077
|
+
});
|
|
1078
|
+
}
|
|
1079
|
+
const slot = { project: worktree, partId: part.id, tokens, base: claimed, waiters: [] };
|
|
1080
|
+
pendingTokenWrites.set(key, slot);
|
|
1081
|
+
const answer = new Promise((resolve) => {
|
|
1082
|
+
slot.waiters.push(resolve);
|
|
1083
|
+
});
|
|
1084
|
+
void queueTokenWrite(worktree, async () => {
|
|
1085
|
+
// Let the rest of the burst arrive before the file is written, so a drag that sent three steps writes once.
|
|
1086
|
+
await new Promise((resolve) => setTimeout(resolve, TOKEN_BURST_MS));
|
|
1087
|
+
const result = await applyTokenWrite({ ...request, tokens: slot.tokens }, tokenFile, cssFile);
|
|
1088
|
+
pendingTokenWrites.delete(key);
|
|
1089
|
+
for (const waiter of slot.waiters)
|
|
1090
|
+
waiter(result);
|
|
1091
|
+
return result;
|
|
1092
|
+
}).catch((err) => {
|
|
1093
|
+
// A failed write answers every request of the burst the same way, so no request waits forever.
|
|
1094
|
+
const result = { ok: false, reason: err instanceof Error ? err.message : String(err) };
|
|
1095
|
+
pendingTokenWrites.delete(key);
|
|
1096
|
+
for (const waiter of slot.waiters)
|
|
1097
|
+
waiter(result);
|
|
1098
|
+
return result;
|
|
1099
|
+
});
|
|
1100
|
+
return answer;
|
|
1101
|
+
}
|
|
1102
|
+
// The write itself, in the order the contract names: the lock, then the hash, then the file, then the commit.
|
|
1103
|
+
async function applyTokenWrite(request, tokenFile, cssFile) {
|
|
1104
|
+
const { worktree, sessionID, lockFile, part, tokens } = request;
|
|
1105
|
+
// The lock, re-read now. A write under a lock this session no longer holds would put another writer's work into
|
|
1106
|
+
// this session's commit.
|
|
1107
|
+
const lock = await inspectDesignLock(lockFile, { now: request.now, hub: request.hub });
|
|
1108
|
+
if (lock.state !== "live")
|
|
1109
|
+
return { ok: false, reason: `the design lock is ${lock.state}: ${lock.reason ?? "no holder"}` };
|
|
1110
|
+
if (lock.lock?.sessionID !== sessionID)
|
|
1111
|
+
return { ok: false, reason: "the design lock belongs to another session" };
|
|
1112
|
+
// The part hash, re-read now. The file may have changed since the client read it. A client that sends no hash
|
|
1113
|
+
// claims it never saw the file, which is true only while there is no file: the empty hash is the hash of a file
|
|
1114
|
+
// that is not there.
|
|
1115
|
+
const current = await tokenSurfaceHash(tokenFile, cssFile);
|
|
1116
|
+
const claimed = request.hash ?? "";
|
|
1117
|
+
if (claimed !== current) {
|
|
1118
|
+
return { ok: false, reason: "the tokens changed since you read them", hash: current };
|
|
1119
|
+
}
|
|
1120
|
+
// The write: the token file and the CSS rendered from it. The CSS is a function of the tokens, so it is written
|
|
1121
|
+
// from the same values, never edited by hand.
|
|
1122
|
+
const css = renderDesignTokensCss(tokens);
|
|
1123
|
+
await writeFile(tokenFile, serializeDesignTokens(tokens), "utf8");
|
|
1124
|
+
await writeFile(cssFile, css, "utf8");
|
|
1125
|
+
// The commit: only the two token paths. An unrelated dirty file in the worktree stays dirty and out of the commit.
|
|
1126
|
+
const paths = [relative(worktree, tokenFile), relative(worktree, cssFile)];
|
|
1127
|
+
// `git commit -- <paths>` commits paths git already knows, so a token file or a CSS file that is new has to be
|
|
1128
|
+
// staged first. `git add -- <paths>` names the two paths and nothing else: an unrelated dirty file keeps its
|
|
1129
|
+
// state, staged or not, and never enters this commit.
|
|
1130
|
+
await stagePaths(worktree, paths);
|
|
1131
|
+
const committed = await commitPaths(worktree, paths, `design: update tokens for ${part.id}`);
|
|
1132
|
+
// `commitPaths` reports the commit it made; HEAD is the same commit, and reading it names the commit the way
|
|
1133
|
+
// git does (the full hash), which is what the shell shows next to the slider.
|
|
1134
|
+
const commit = committed === undefined ? undefined : await headCommit(worktree);
|
|
1135
|
+
return { ok: true, hash: await tokenSurfaceHash(tokenFile, cssFile), commit };
|
|
1136
|
+
}
|
|
1137
|
+
// ---------------------------------------------------------------------------------------------
|
|
1138
|
+
// S6 · The file watcher.
|
|
1139
|
+
//
|
|
1140
|
+
// The watcher follows the parts of one session on disk and turns a burst of filesystem events into
|
|
1141
|
+
// one reload event per changed part. Two rules keep the stream quiet:
|
|
1142
|
+
//
|
|
1143
|
+
// * Editor bookkeeping is not a change. Vim's `.<name>.swp`, the `~` backup an editor leaves
|
|
1144
|
+
// behind, a `.tmp` scratch file and the rename that moves one of them into place all describe
|
|
1145
|
+
// how a file was written, not that its content differs. Dot-directories are ignored for the
|
|
1146
|
+
// same reason: they hold the project's state, the job journals and the lock, none of which is
|
|
1147
|
+
// part of the canvas.
|
|
1148
|
+
// * A burst is one change. An editor that writes a file, renames a temporary over it and fixes
|
|
1149
|
+
// the metadata produces several filesystem events for one edit. The watcher waits for the
|
|
1150
|
+
// burst to settle and then reports the part once.
|
|
1151
|
+
//
|
|
1152
|
+
// The event carries the part's content hash, so a client that already applied that revision can
|
|
1153
|
+
// ignore it. The hash is over the bytes, not over the file list: editing a file and undoing the edit
|
|
1154
|
+
// gives the same hash again, which is what a browser wants to know.
|
|
1155
|
+
const DEFAULT_DEBOUNCE_MS = 60;
|
|
1156
|
+
// The names an editor writes through. A file whose name is one of these is the editor's bookkeeping
|
|
1157
|
+
// and never a change of the canvas.
|
|
1158
|
+
//
|
|
1159
|
+
// * `.<name>.swp` — vim's swap file, and the same shape for `.<name>.swo` and the `.un~` family.
|
|
1160
|
+
// * `~` — the backup emacs and gedit leave next to the original (`index.html~`).
|
|
1161
|
+
// * `.tmp` — the scratch file an atomic save writes through (`index.html.tmp`).
|
|
1162
|
+
//
|
|
1163
|
+
// A dot-prefixed name is ignored as well: `.git`, the project's state directory and the rest of the
|
|
1164
|
+
// dot world belong to the tools, not to the canvas.
|
|
1165
|
+
export function isEditorTempName(name) {
|
|
1166
|
+
const base = basename(name);
|
|
1167
|
+
if (!base)
|
|
1168
|
+
return true;
|
|
1169
|
+
if (base.startsWith("."))
|
|
1170
|
+
return true; // dot-files and dot-directories: the tools' own bookkeeping.
|
|
1171
|
+
if (base.endsWith("~"))
|
|
1172
|
+
return true; // emacs/gedit backups.
|
|
1173
|
+
if (base.endsWith(".tmp"))
|
|
1174
|
+
return true; // atomic saves write through a scratch file.
|
|
1175
|
+
if (/\.sw[a-p]$/.test(base))
|
|
1176
|
+
return true; // vim's swap files.
|
|
1177
|
+
if (/\.un~$/.test(base))
|
|
1178
|
+
return true; // emacs' undo files.
|
|
1179
|
+
return false;
|
|
1180
|
+
}
|
|
1181
|
+
// A part's directory as it is watched: the worktree root plus the part's path. The path is resolved
|
|
1182
|
+
// against the root and checked, so a part can never watch something outside the worktree.
|
|
1183
|
+
function watchDir(root, part) {
|
|
1184
|
+
const target = resolve(root, part.path);
|
|
1185
|
+
return insideResolved(root, target) && insideResolved(root, realish(target)) ? target : root;
|
|
1186
|
+
}
|
|
1187
|
+
// Every file of one part, relative to the worktree root, used for the content hash. The part's
|
|
1188
|
+
// directory is walked; its source file is added when it lives elsewhere.
|
|
1189
|
+
function partFiles(root, part) {
|
|
1190
|
+
const base = watchDir(root, part);
|
|
1191
|
+
const files = [];
|
|
1192
|
+
const walk = (dir) => {
|
|
1193
|
+
let entries;
|
|
1194
|
+
try {
|
|
1195
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
1196
|
+
}
|
|
1197
|
+
catch {
|
|
1198
|
+
return; // A directory that is not there yet contributes no files; the watcher picks it up later.
|
|
1199
|
+
}
|
|
1200
|
+
for (const entry of entries) {
|
|
1201
|
+
if (entry.isDirectory()) {
|
|
1202
|
+
if (entry.name.startsWith("."))
|
|
1203
|
+
continue; // Dot-directories hold the tools' state, not the canvas.
|
|
1204
|
+
walk(join(dir, entry.name));
|
|
1205
|
+
continue;
|
|
1206
|
+
}
|
|
1207
|
+
files.push(relative(root, join(dir, entry.name)).split(sep).join("/"));
|
|
1208
|
+
}
|
|
1209
|
+
};
|
|
1210
|
+
walk(base);
|
|
1211
|
+
if (part.source) {
|
|
1212
|
+
const source = resolve(root, part.source);
|
|
1213
|
+
if (insideResolved(root, source)) {
|
|
1214
|
+
const rel = relative(root, source).split(sep).join("/");
|
|
1215
|
+
if (!files.includes(rel))
|
|
1216
|
+
files.push(rel);
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
return files.sort();
|
|
1220
|
+
}
|
|
1221
|
+
// The content hash of one part: a digest over its files' paths and bytes. Two parts with the same
|
|
1222
|
+
// files and the same bytes hash the same, so the hash follows the content rather than the write.
|
|
1223
|
+
function hashPart(root, part) {
|
|
1224
|
+
const hash = createHash("sha256");
|
|
1225
|
+
for (const rel of partFiles(root, part)) {
|
|
1226
|
+
const file = resolve(root, rel);
|
|
1227
|
+
hash.update(rel);
|
|
1228
|
+
hash.update("\0");
|
|
1229
|
+
try {
|
|
1230
|
+
hash.update(readFileSync(file));
|
|
1231
|
+
}
|
|
1232
|
+
catch {
|
|
1233
|
+
hash.update("\0missing");
|
|
1234
|
+
}
|
|
1235
|
+
hash.update("\0");
|
|
1236
|
+
}
|
|
1237
|
+
return hash.digest("hex");
|
|
1238
|
+
}
|
|
1239
|
+
// Start watching the parts. Every part is watched by its own directory: recursively where the
|
|
1240
|
+
// platform supports it, and file by file where it does not. The recursive form is tried first and
|
|
1241
|
+
// its failure is not an error: the per-file form watches the same files on a machine that cannot
|
|
1242
|
+
// watch a tree.
|
|
1243
|
+
export function createDesignWatcher(options) {
|
|
1244
|
+
const root = options.root;
|
|
1245
|
+
const parts = options.parts;
|
|
1246
|
+
const debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;
|
|
1247
|
+
const schedule = options.schedule ??
|
|
1248
|
+
((fn, ms) => {
|
|
1249
|
+
const timer = setTimeout(fn, ms);
|
|
1250
|
+
timer.unref?.();
|
|
1251
|
+
return () => clearTimeout(timer);
|
|
1252
|
+
});
|
|
1253
|
+
const hashOf = options.hash ?? ((part) => hashPart(root, part));
|
|
1254
|
+
const watchTree = options.watchTree ?? "auto";
|
|
1255
|
+
const listeners = [];
|
|
1256
|
+
const watchers = [];
|
|
1257
|
+
const pending = new Map();
|
|
1258
|
+
const lastHash = new Map();
|
|
1259
|
+
// The parts' hashes as they are now. A part that has not changed since the watcher started has
|
|
1260
|
+
// nothing to report, so the first event after a start is a real change.
|
|
1261
|
+
for (const part of parts) {
|
|
1262
|
+
try {
|
|
1263
|
+
lastHash.set(part.id, hashOf(part));
|
|
1264
|
+
}
|
|
1265
|
+
catch {
|
|
1266
|
+
// A part that cannot be hashed yet is reported when it changes.
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
const emit = (partId) => {
|
|
1270
|
+
const part = parts.find((candidate) => candidate.id === partId);
|
|
1271
|
+
if (!part)
|
|
1272
|
+
return;
|
|
1273
|
+
let hash;
|
|
1274
|
+
try {
|
|
1275
|
+
hash = hashOf(part);
|
|
1276
|
+
}
|
|
1277
|
+
catch {
|
|
1278
|
+
hash = lastHash.get(partId) ?? "";
|
|
1279
|
+
}
|
|
1280
|
+
// The same bytes are not a change. A rename that moves a temporary file over a file with the
|
|
1281
|
+
// same content is the editor finishing its work, not a new revision of the part.
|
|
1282
|
+
if (hash && lastHash.get(partId) === hash)
|
|
1283
|
+
return;
|
|
1284
|
+
if (hash)
|
|
1285
|
+
lastHash.set(partId, hash);
|
|
1286
|
+
const event = { type: "reload", partId, hash };
|
|
1287
|
+
for (const listener of [...listeners])
|
|
1288
|
+
listener(event);
|
|
1289
|
+
};
|
|
1290
|
+
// A part is reported once its burst settles. A later event inside the same burst moves the
|
|
1291
|
+
// deadline rather than adding a second report.
|
|
1292
|
+
const scheduleReport = (partId) => {
|
|
1293
|
+
const cancel = pending.get(partId);
|
|
1294
|
+
if (cancel)
|
|
1295
|
+
cancel();
|
|
1296
|
+
const later = schedule(() => {
|
|
1297
|
+
pending.delete(partId);
|
|
1298
|
+
emit(partId);
|
|
1299
|
+
}, debounceMs);
|
|
1300
|
+
pending.set(partId, later);
|
|
1301
|
+
};
|
|
1302
|
+
// The part a changed path belongs to. A path inside a part's directory belongs to that part; a
|
|
1303
|
+
// part's source file belongs to the part even when it lives outside the directory. When two
|
|
1304
|
+
// parts cover the same path the one whose directory reaches deepest owns it.
|
|
1305
|
+
const partOf = (rootRelative) => {
|
|
1306
|
+
let best;
|
|
1307
|
+
let bestDepth = -1;
|
|
1308
|
+
for (const part of parts) {
|
|
1309
|
+
const base = relative(root, watchDir(root, part)).split(sep).join("/");
|
|
1310
|
+
const covers = base === "" || base === "." || rootRelative === base || rootRelative.startsWith(`${base}/`);
|
|
1311
|
+
const isSource = part.source !== undefined && rootRelative === part.source.split(sep).join("/");
|
|
1312
|
+
if (!covers && !isSource)
|
|
1313
|
+
continue;
|
|
1314
|
+
// A source file outside the directory is claimed by its own part; the directory's depth does
|
|
1315
|
+
// not apply to it. A part that watches the root has depth zero, so a part with a directory of
|
|
1316
|
+
// its own always wins over it.
|
|
1317
|
+
const depth = isSource && !covers ? Number.MAX_SAFE_INTEGER : base === "" || base === "." ? 0 : base.split("/").length;
|
|
1318
|
+
if (depth > bestDepth) {
|
|
1319
|
+
best = part.id;
|
|
1320
|
+
bestDepth = depth;
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
return best;
|
|
1324
|
+
};
|
|
1325
|
+
// A change reported by one watcher. `base` is the directory the watcher watches, because the
|
|
1326
|
+
// filename comes relative to that directory and not to the worktree root.
|
|
1327
|
+
const onFsEvent = (base, filename) => {
|
|
1328
|
+
if (filename === null)
|
|
1329
|
+
return;
|
|
1330
|
+
const name = (typeof filename === "string" ? filename : filename.toString("utf8")).split(sep).join("/");
|
|
1331
|
+
if (!name)
|
|
1332
|
+
return;
|
|
1333
|
+
const absolute = resolve(base, name);
|
|
1334
|
+
// A path inside a dot-directory is the tools' own bookkeeping.
|
|
1335
|
+
const rel = relative(root, absolute).split(sep).join("/");
|
|
1336
|
+
if (!rel || rel.startsWith(".."))
|
|
1337
|
+
return;
|
|
1338
|
+
if (rel.split("/").some((segment) => segment.startsWith(".")))
|
|
1339
|
+
return;
|
|
1340
|
+
if (isEditorTempName(rel))
|
|
1341
|
+
return;
|
|
1342
|
+
const partId = partOf(rel);
|
|
1343
|
+
if (!partId)
|
|
1344
|
+
return;
|
|
1345
|
+
scheduleReport(partId);
|
|
1346
|
+
};
|
|
1347
|
+
for (const part of parts) {
|
|
1348
|
+
const dir = watchDir(root, part);
|
|
1349
|
+
let tree = false;
|
|
1350
|
+
if (watchTree !== "files") {
|
|
1351
|
+
try {
|
|
1352
|
+
// Recursive where the platform has it: one watcher for the whole tree, including files that
|
|
1353
|
+
// are created after the watcher started.
|
|
1354
|
+
const recursive = watch(dir, { recursive: true });
|
|
1355
|
+
recursive.on("change", (_event, filename) => onFsEvent(dir, filename));
|
|
1356
|
+
watchers.push(recursive);
|
|
1357
|
+
tree = true;
|
|
1358
|
+
}
|
|
1359
|
+
catch {
|
|
1360
|
+
// No recursive watching here: fall through to the per-file form below.
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
if (watchTree === "tree" && !tree) {
|
|
1364
|
+
// The caller asked for the tree and the platform refused. There is nothing to watch.
|
|
1365
|
+
continue;
|
|
1366
|
+
}
|
|
1367
|
+
if (tree)
|
|
1368
|
+
continue;
|
|
1369
|
+
try {
|
|
1370
|
+
const flat = watch(dir);
|
|
1371
|
+
flat.on("change", (_event, filename) => onFsEvent(dir, filename));
|
|
1372
|
+
watchers.push(flat);
|
|
1373
|
+
}
|
|
1374
|
+
catch {
|
|
1375
|
+
// A directory that cannot be watched contributes no events; the other parts still work.
|
|
1376
|
+
}
|
|
1377
|
+
for (const rel of partFiles(root, part)) {
|
|
1378
|
+
const file = resolve(root, rel);
|
|
1379
|
+
try {
|
|
1380
|
+
const single = watch(file);
|
|
1381
|
+
// A watcher on one file reports that file's name, so the base is the file's own directory.
|
|
1382
|
+
single.on("change", (_event, filename) => onFsEvent(dirname(file), filename ?? basename(file)));
|
|
1383
|
+
watchers.push(single);
|
|
1384
|
+
}
|
|
1385
|
+
catch {
|
|
1386
|
+
// A file that cannot be watched (gone already, or a broken link) is simply not watched.
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
return {
|
|
1391
|
+
on(_event, listener) {
|
|
1392
|
+
listeners.push(listener);
|
|
1393
|
+
},
|
|
1394
|
+
close() {
|
|
1395
|
+
for (const cancel of pending.values())
|
|
1396
|
+
cancel();
|
|
1397
|
+
pending.clear();
|
|
1398
|
+
listeners.length = 0;
|
|
1399
|
+
for (const watcher of watchers) {
|
|
1400
|
+
try {
|
|
1401
|
+
watcher.close();
|
|
1402
|
+
}
|
|
1403
|
+
catch {
|
|
1404
|
+
// A watcher that is already closed is not a failure.
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
watchers.length = 0;
|
|
1408
|
+
},
|
|
1409
|
+
};
|
|
1410
|
+
}
|