@lifeaitools/clauth 1.30.6 → 1.30.7

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.
@@ -3,14 +3,11 @@ import fs from "fs";
3
3
  import os from "os";
4
4
  import path from "path";
5
5
  import { spawn } from "child_process";
6
- import ts from "typescript";
7
6
 
8
7
  const DEFAULT_POLL_TIMEOUT = 600_000;
9
8
  const MAX_POLL_TIMEOUT = 600_000;
10
9
  const MAX_EVENT_QUEUE = 100;
11
10
  const MAX_SNIPPET = 2_000;
12
- const STYLE_WRITE_EXTENSIONS = new Set([".css", ".scss", ".sass", ".less", ".html", ".jsx", ".tsx"]);
13
- const TEXT_WRITE_EXTENSIONS = new Set([".ts", ".tsx", ".js", ".jsx", ".html", ".md", ".txt", ".css", ".scss"]);
14
11
 
15
12
  const APP_TARGETS = {
16
13
  studio_test: {
@@ -47,152 +44,6 @@ function nowIso() {
47
44
  return new Date().toISOString();
48
45
  }
49
46
 
50
- const EDITOR_SETTINGS_FILENAME = ".studio-editor-settings.json";
51
-
52
- /**
53
- * Editable-prompts settings file — every Claude prompt built here has a default
54
- * baked into code; this loads the SAME-SHAPED override from
55
- * `<repoRoot>/.studio-editor-settings.json` if present (same file/shape
56
- * agent-pool.js's buildFullSystemPrompt() reads, different field). Read fresh
57
- * on every dispatch (no caching) so an edit takes effect on the next edit sent,
58
- * no daemon restart needed. Never throws.
59
- */
60
- function loadEditorSettings(repoRoot) {
61
- if (!repoRoot) return {};
62
- try {
63
- const settingsPath = path.join(repoRoot, EDITOR_SETTINGS_FILENAME);
64
- if (!fs.existsSync(settingsPath)) return {};
65
- const parsed = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
66
- return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
67
- } catch (e) {
68
- console.error(`[studio-debug] ${EDITOR_SETTINGS_FILENAME} malformed, using code default edit prompt: ${e.message}`);
69
- return {};
70
- }
71
- }
72
-
73
- /**
74
- * Build the per-edit dispatch prompt. Editable: set `editPromptTemplate` in
75
- * `<repoRoot>/.studio-editor-settings.json` to override the whole template —
76
- * tokens {targetFile} {purpose} {appSlug} {brandSlug} {repoRoot} {devUrl}
77
- * {mode} {selector} {currentText} {newText} {notes} are substituted (each
78
- * resolves to "" when the underlying value is absent, same as the default).
79
- */
80
- function buildEditPrompt(session, event) {
81
- const repoRoot = (session.repoRoot || session.cwd || "").replace(/\\/g, "/");
82
- const targetFile = event.file
83
- ? `TARGET FILE: ${event.file}`
84
- : `TARGET FILE: unknown — locate it from Selector "${event.selector || "unknown"}"${event.component ? ` (component: ${event.component})` : ""} in the repo below before editing anything.`;
85
- const tokens = {
86
- targetFile,
87
- purpose: event.instruction || "Make the requested edit.",
88
- appSlug: session.appSlug || "",
89
- brandSlug: session.brandSlug || "",
90
- repoRoot,
91
- devUrl: session.devUrl || "unknown",
92
- mode: event.mode || "direct_edit",
93
- selector: event.selector || "unknown",
94
- currentText: event.textSnippet || "",
95
- newText: event.textEdit?.newText || "",
96
- notes: event.notes || "",
97
- };
98
-
99
- const settings = loadEditorSettings(repoRoot);
100
- if (typeof settings.editPromptTemplate === "string" && settings.editPromptTemplate.trim()) {
101
- return Object.entries(tokens).reduce(
102
- (text, [key, value]) => text.replaceAll(`{${key}}`, value),
103
- settings.editPromptTemplate,
104
- );
105
- }
106
-
107
- return [
108
- `You are a Studio local-debug agent. Make ONE source edit to the codebase.`,
109
- ``,
110
- // Explicit file + purpose, stated up front and unmissable — required even when
111
- // no deterministic file hint exists, so a warm session's first turn is never
112
- // vague about what it's touching or why.
113
- tokens.targetFile,
114
- `PURPOSE: ${tokens.purpose}`,
115
- ``,
116
- `App: ${tokens.appSlug} (brand: ${tokens.brandSlug})`,
117
- `Repo: ${tokens.repoRoot}`,
118
- `Dev URL: ${tokens.devUrl}`,
119
- ``,
120
- `Edit event:`,
121
- ` Mode: ${tokens.mode}`,
122
- ` Selector: ${tokens.selector}`,
123
- tokens.currentText ? ` Current text: "${tokens.currentText}"` : "",
124
- tokens.newText ? ` New text: "${tokens.newText}"` : "",
125
- tokens.notes ? ` Notes: ${tokens.notes}` : "",
126
- ``,
127
- `Do not edit any file other than the one this edit targets.`,
128
- `After editing, output a JSON object: {"status":"done","message":"<what you did>","filesChanged":["<path>"]}`,
129
- ].filter(Boolean).join("\n");
130
- }
131
-
132
- /**
133
- * Build the prompt for a `mode:"chat"` event — a genuine conversational turn, not a
134
- * source edit. Deliberately does NOT reuse buildEditPrompt(): that template's "Make ONE
135
- * source edit" instruction plus the {"status","message","filesChanged"} JSON-output
136
- * contract make no sense for a question like "what does this page do?" and produced
137
- * broken chat replies (the agent trying to force a conversational answer into an edit
138
- * JSON shape, or refusing because there was no real target file to edit). Editable via
139
- * `<repoRoot>/.studio-editor-settings.json`'s `chatPromptTemplate` field (same token set
140
- * as `editPromptTemplate`, same substitution rule).
141
- */
142
- function buildChatPrompt(session, event) {
143
- const repoRoot = (session.repoRoot || session.cwd || "").replace(/\\/g, "/");
144
- const tokens = {
145
- purpose: event.instruction || "",
146
- appSlug: session.appSlug || "",
147
- brandSlug: session.brandSlug || "",
148
- repoRoot,
149
- devUrl: session.devUrl || "unknown",
150
- };
151
-
152
- const settings = loadEditorSettings(repoRoot);
153
- if (typeof settings.chatPromptTemplate === "string" && settings.chatPromptTemplate.trim()) {
154
- return Object.entries(tokens).reduce(
155
- (text, [key, value]) => text.replaceAll(`{${key}}`, value),
156
- settings.chatPromptTemplate,
157
- );
158
- }
159
-
160
- return [
161
- `You are a Studio local-debug chat assistant helping someone edit the "${tokens.appSlug}" app (brand: ${tokens.brandSlug}).`,
162
- `Repo: ${tokens.repoRoot}`,
163
- `Dev URL: ${tokens.devUrl}`,
164
- ``,
165
- `This is a conversational turn, not a source-edit dispatch — answer the question or`,
166
- `discuss the request in plain text. Only touch files if the person explicitly asks`,
167
- `you to make a change; if you do, describe what you changed in your reply.`,
168
- `Reply in plain prose — do NOT wrap your answer in the edit-dispatch JSON contract.`,
169
- ``,
170
- tokens.purpose,
171
- ].filter(Boolean).join("\n");
172
- }
173
-
174
- /**
175
- * Persist an editable-prompts settings patch to `<repoRoot>/.studio-editor-settings.json`,
176
- * merging with whatever is already on disk. Only `systemPrompt`, `editPromptTemplate`, and
177
- * `chatPromptTemplate` are recognized fields — the same keys loadEditorSettings()/buildEditPrompt() (this
178
- * file) and buildFullSystemPrompt()/buildStudioEditorSystemPrompt() (agent-pool.js) read.
179
- * Empty-string values clear that field back to the code default rather than persisting "".
180
- */
181
- function saveEditorSettings(repoRoot, patch) {
182
- if (!repoRoot) throw new Error("repoRoot required");
183
- const settingsPath = path.join(repoRoot, EDITOR_SETTINGS_FILENAME);
184
- const current = loadEditorSettings(repoRoot);
185
- const next = { ...current };
186
- for (const key of ["systemPrompt", "editPromptTemplate", "chatPromptTemplate"]) {
187
- if (!(key in patch)) continue;
188
- const value = typeof patch[key] === "string" ? patch[key].trim() : "";
189
- if (value) next[key] = value;
190
- else delete next[key];
191
- }
192
- fs.writeFileSync(settingsPath, JSON.stringify(next, null, 2) + "\n", "utf8");
193
- return next;
194
- }
195
-
196
47
  function safeString(value, max = MAX_SNIPPET) {
197
48
  if (typeof value !== "string") return value;
198
49
  return value.length > max ? value.slice(0, max) : value;
@@ -247,170 +98,6 @@ function writeJson(res, status, data, cors) {
247
98
  res.end(JSON.stringify(data));
248
99
  }
249
100
 
250
- function resolveSourceFile(session, file, allowedExtensions = STYLE_WRITE_EXTENSIONS) {
251
- if (!file || typeof file !== "string") return null;
252
- const root = path.resolve(session.repoRoot || session.cwd || process.cwd());
253
- const candidate = path.isAbsolute(file) ? path.resolve(file) : path.resolve(root, file);
254
- const rel = path.relative(root, candidate);
255
- if (rel.startsWith("..") || path.isAbsolute(rel)) return null;
256
- if (!allowedExtensions.has(path.extname(candidate).toLowerCase())) return null;
257
- return { root, path: candidate, relativePath: rel.replace(/\\/g, "/") };
258
- }
259
-
260
- function applyTextRangeEdit(sourceText, textEdit) {
261
- const source = textEdit.source;
262
- if (!source || !source.range || typeof source.range.start !== "number" || typeof source.range.end !== "number") {
263
- throw new Error("text-write requires source.range.start and source.range.end.");
264
- }
265
- const { start, end } = source.range;
266
- if (start < 0 || end < start || end > sourceText.length) {
267
- throw new Error(`text-write source range [${start}, ${end}] is out of bounds (file length: ${sourceText.length}).`);
268
- }
269
- if (textEdit.oldText !== undefined) {
270
- const oldSlice = sourceText.slice(start, end);
271
- if (oldSlice !== textEdit.oldText) {
272
- throw new Error(`text-write oldText mismatch at [${start}, ${end}]: expected "${String(textEdit.oldText).slice(0, 80)}", found "${oldSlice.slice(0, 80)}".`);
273
- }
274
- }
275
- return `${sourceText.slice(0, start)}${textEdit.newText}${sourceText.slice(end)}`;
276
- }
277
-
278
- function escapeRegExp(value) {
279
- return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
280
- }
281
-
282
- function applyCssTextEdit(source, property, value, lineNumber = null) {
283
- const propertyPattern = new RegExp(`(${escapeRegExp(property)}\\s*:\\s*)([^;\\n]+)(\\s*;?)`);
284
- if (Number.isInteger(lineNumber) && lineNumber > 0) {
285
- const lines = source.split(/\r?\n/);
286
- const index = Math.min(lines.length - 1, lineNumber - 1);
287
- const windowStart = Math.max(0, index - 8);
288
- const windowEnd = Math.min(lines.length - 1, index + 8);
289
- for (let i = windowStart; i <= windowEnd; i += 1) {
290
- if (propertyPattern.test(lines[i])) {
291
- lines[i] = lines[i].replace(propertyPattern, `$1${value}$3`);
292
- return { content: lines.join("\n"), strategy: "replace-near-line" };
293
- }
294
- }
295
- const anchor = lines[index] ?? "";
296
- const indent = anchor.match(/^\s*/)?.[0] ?? "";
297
- lines.splice(index + 1, 0, `${indent}${property}: ${value};`);
298
- return { content: lines.join("\n"), strategy: "insert-near-line" };
299
- }
300
- const replaced = source.replace(propertyPattern, `$1${value}$3`);
301
- if (replaced !== source) return { content: replaced, strategy: "replace-first" };
302
- throw new Error(`CSS property "${property}" was not found and no source line was provided.`);
303
- }
304
-
305
- function applyJsxStyleEdit(source, property, value, lineNumber = null) {
306
- const lines = source.split(/\r?\n/);
307
- const targetIndex = Number.isInteger(lineNumber) && lineNumber > 0 ? Math.min(lines.length - 1, lineNumber - 1) : -1;
308
- const windowStart = targetIndex >= 0 ? Math.max(0, targetIndex - 8) : 0;
309
- const windowEnd = targetIndex >= 0 ? Math.min(lines.length - 1, targetIndex + 8) : lines.length - 1;
310
- const camel = property.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
311
- const quoted = JSON.stringify(value);
312
- const propPattern = new RegExp(`(${camel}\\s*:\\s*)(["'\`])([^"'\`]+)(\\2)`);
313
-
314
- for (let i = windowStart; i <= windowEnd; i += 1) {
315
- if (propPattern.test(lines[i])) {
316
- lines[i] = lines[i].replace(propPattern, `$1${quoted}`);
317
- return { content: lines.join("\n"), strategy: "replace-js-style-near-line" };
318
- }
319
- }
320
-
321
- for (let i = windowStart; i <= windowEnd; i += 1) {
322
- if (lines[i].includes("style={{")) {
323
- lines[i] = lines[i].replace("style={{", `style={{ ${camel}: ${quoted},`);
324
- return { content: lines.join("\n"), strategy: "insert-js-style-near-line" };
325
- }
326
- }
327
-
328
- throw new Error(`No inline style object for "${property}" was found near the selected source line.`);
329
- }
330
-
331
- // Syntax-check extensions we know how to parse with the TS compiler. Non-TS/JS
332
- // source (e.g. plain .css, .md) is skipped — there is nothing meaningful for
333
- // ts.transpileModule to validate there.
334
- const SYNTAX_CHECK_EXTENSIONS = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"]);
335
-
336
- // Same pattern already proven in
337
- // packages/studio-local-debug/src/integration/editor-coverage-matrix.test.ts
338
- // (syntaxDiagnosticsLikeEditor) and returned by apps/studio's accept-adapter.ts
339
- // as `syntaxDiagnostics`. Kept identical here so results are directly comparable.
340
- function syntaxDiagnosticsFor(source, fileName) {
341
- const output = ts.transpileModule(source, {
342
- fileName,
343
- reportDiagnostics: true,
344
- compilerOptions: {
345
- jsx: ts.JsxEmit.Preserve,
346
- target: ts.ScriptTarget.ESNext,
347
- module: ts.ModuleKind.ESNext,
348
- },
349
- });
350
- return output.diagnostics || [];
351
- }
352
-
353
- function formatDiagnostic(diagnostic) {
354
- const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
355
- if (diagnostic.file && typeof diagnostic.start === "number") {
356
- const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
357
- return `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`;
358
- }
359
- return message;
360
- }
361
-
362
- /**
363
- * Read each changed file (relative to the session repo root) and run a TS
364
- * syntax check. Returns { ok, diagnostics } — diagnostics is a flat array of
365
- * human-readable strings, empty when every checkable file is syntax-clean.
366
- * Files outside SYNTAX_CHECK_EXTENSIONS, or that no longer exist on disk, are
367
- * skipped (not treated as failures) — this check validates parseability, not
368
- * file presence.
369
- */
370
- function checkFilesSyntax(session, filesChanged) {
371
- const diagnostics = [];
372
- const root = path.resolve(session.repoRoot || session.cwd || process.cwd());
373
- for (const file of Array.isArray(filesChanged) ? filesChanged : []) {
374
- if (!file || typeof file !== "string") continue;
375
- const ext = path.extname(file).toLowerCase();
376
- if (!SYNTAX_CHECK_EXTENSIONS.has(ext)) continue;
377
- const candidate = path.isAbsolute(file) ? path.resolve(file) : path.resolve(root, file);
378
- let source;
379
- try {
380
- source = fs.readFileSync(candidate, "utf8");
381
- } catch (err) {
382
- // A referenced file that no longer exists is itself suspicious, but the
383
- // agent may have renamed/moved it deliberately as part of the edit —
384
- // treat as unable-to-verify, not a hard syntax failure.
385
- continue;
386
- }
387
- const fileDiagnostics = syntaxDiagnosticsFor(source, candidate);
388
- for (const d of fileDiagnostics) {
389
- diagnostics.push(`${file}: ${formatDiagnostic(d)}`);
390
- }
391
- }
392
- return { ok: diagnostics.length === 0, diagnostics };
393
- }
394
-
395
- /**
396
- * Best-effort collection of the file(s) an event referenced, used as a
397
- * fallback filesChanged set when the agent's JSON reply fails to parse (or
398
- * omits filesChanged) — so a malformed-but-plausible-looking agent response
399
- * still gets its target file(s) syntax-checked instead of slipping through
400
- * ungated.
401
- */
402
- function filesReferencedByEvent(event) {
403
- const files = new Set();
404
- const add = (f) => {
405
- if (typeof f === "string" && f.trim()) files.add(f.trim());
406
- };
407
- add(event?.file);
408
- add(event?.target?.file);
409
- add(event?.textEdit?.source?.file);
410
- add(event?.styleEdit?.source?.file);
411
- return [...files];
412
- }
413
-
414
101
  async function isUrlReachable(url) {
415
102
  try {
416
103
  const response = await fetch(url, {
@@ -426,13 +113,11 @@ async function isUrlReachable(url) {
426
113
  function resolveTarget(input = {}) {
427
114
  const slug = String(input.appSlug || input.brandSlug || "prt").toLowerCase();
428
115
  const configured = APP_TARGETS[slug];
429
- // No registration required IF the caller supplies an explicit devUrl/devCommand
430
- // an arbitrary appSlug with an explicit target is a legitimate ad-hoc session. But
431
- // an unknown slug with NO explicit override has nothing to resolve to at all.
432
- if (!configured && !input.devUrl && !input.devCommand) {
116
+ if (!configured && !input.devCommand && !input.devUrl) {
433
117
  return {
434
118
  error: "unknown_app",
435
- message: `Unknown appSlug "${slug}" — not registered in APP_TARGETS and no devUrl/devCommand override was provided.`,
119
+ message: `No local debug target is configured for appSlug "${slug}".`,
120
+ appSlug: slug,
436
121
  };
437
122
  }
438
123
 
@@ -452,31 +137,6 @@ function resolveTarget(input = {}) {
452
137
  };
453
138
  }
454
139
 
455
- /**
456
- * A reachable HTTP server is not necessarily a genuine Next.js DEV server the editor
457
- * can attach HMR-based live edits to — it could be a production build (no HMR at all)
458
- * or a dev server sitting behind an auth gate the editor can't get past. Probe the
459
- * webpack-hmr path: a redirect (typically to a login page) or an auth-rejection status
460
- * means source-edit sessions cannot establish the HMR stream this feature depends on.
461
- */
462
- async function isGenuineDevServer(url) {
463
- try {
464
- const response = await fetch(`${url.replace(/\/$/, "")}/_next/webpack-hmr`, {
465
- method: "GET",
466
- redirect: "manual",
467
- signal: AbortSignal.timeout(1_500),
468
- });
469
- if (response.status >= 300 && response.status < 400) return false;
470
- if (response.status === 401 || response.status === 403) return false;
471
- return true;
472
- } catch {
473
- // Network-level errors on a websocket-upgrade path (abrupt close, protocol error)
474
- // are expected even for a genuine dev server hit with a plain GET — don't reject
475
- // on that basis alone, only on an explicit auth/redirect signal above.
476
- return true;
477
- }
478
- }
479
-
480
140
  function splitCommand(command) {
481
141
  if (!command || typeof command !== "string") return null;
482
142
  const parts = command.match(/(?:[^\s"]+|"[^"]*")+/g) || [];
@@ -522,22 +182,10 @@ function startDevProcess(target, logFile) {
522
182
  }
523
183
 
524
184
  export class StudioDebugSessionStore {
525
- constructor({
526
- port = 52437,
527
- logFile = path.join(os.tmpdir(), "clauth-serve.log"),
528
- dispatchAgent = null,
529
- acquireSessionWorker = null,
530
- releaseSessionWorker = null,
531
- } = {}) {
185
+ constructor({ port = 52437, logFile = path.join(os.tmpdir(), "clauth-serve.log") } = {}) {
532
186
  this.port = port;
533
187
  this.logFile = logFile;
534
188
  this.sessions = new Map();
535
- this.dispatchAgent = dispatchAgent;
536
- // One warm channel per editor session, acquired eagerly at start() and reused for
537
- // every dispatch (chat and direct-edit alike) via submitEvent()'s dispatchAgent call
538
- // through to session end — never a fresh one-shot process per edit.
539
- this.acquireSessionWorker = acquireSessionWorker;
540
- this.releaseSessionWorker = releaseSessionWorker;
541
189
  }
542
190
 
543
191
  async start(input = {}) {
@@ -548,14 +196,6 @@ export class StudioDebugSessionStore {
548
196
 
549
197
  const shouldLaunch = input.launchDevServer !== false;
550
198
  const reachable = await isUrlReachable(target.url);
551
- if (reachable && !(await isGenuineDevServer(target.url))) {
552
- return {
553
- ok: false,
554
- error: "non_dev_server",
555
- message: `${target.url} is reachable but its Next dev HMR stream is not accessible (redirected or auth-gated) — source-edit sessions require a genuine, reachable Next.js dev server.`,
556
- status: "error",
557
- };
558
- }
559
199
  const launch = reachable
560
200
  ? { started: false, command: target.command, url: target.url, alreadyRunning: true }
561
201
  : shouldLaunch
@@ -574,8 +214,6 @@ export class StudioDebugSessionStore {
574
214
  devCommand: target.command,
575
215
  devUrl: target.url,
576
216
  modeDefault: input.modeDefault || "direct_edit",
577
- agentModel: typeof input.agentModel === "string" && input.agentModel.trim() ? input.agentModel.trim() : null,
578
- warmAgent: input.warmAgent !== false,
579
217
  status: "waiting_for_agent",
580
218
  createdAt: nowIso(),
581
219
  updatedAt: nowIso(),
@@ -587,31 +225,13 @@ export class StudioDebugSessionStore {
587
225
  };
588
226
  this.sessions.set(sessionId, session);
589
227
 
590
- const relayBaseUrl = `http://127.0.0.1:${this.port}/studio/debug/${sessionId}`;
591
- const claudeBaseUrl = `http://127.0.0.1:${this.port}/studio/claude/${sessionId}`;
592
- const pollCommand = `node scripts/studio-debug-poll.mjs --session ${sessionId} --token ${token} --relay ${claudeBaseUrl}`;
593
-
594
- // When dispatchAgent is wired, events dispatch directly — no polling agent needed.
595
- if (this.dispatchAgent) {
596
- session.status = "waiting_for_event";
597
- }
598
-
599
- // Acquire this session's warm channel now, at session start — not lazily on the
600
- // first edit. Every subsequent dispatchAgent call for this sessionId (chat or
601
- // direct-edit) reuses the same pinned worker. Best-effort: a warm-pool exhaustion
602
- // here does not fail session start, dispatchToSession() will surface it per-turn.
603
- if (session.warmAgent && this.acquireSessionWorker) {
604
- try { this.acquireSessionWorker(sessionId, session.agentModel, session.repoRoot || session.cwd); } catch { /* best-effort */ }
605
- }
606
-
607
228
  return {
608
229
  ok: true,
609
230
  sessionId,
610
231
  token,
611
232
  devUrl: target.url,
612
- relayBaseUrl,
233
+ relayBaseUrl: `http://127.0.0.1:${this.port}/studio/debug/${sessionId}`,
613
234
  status: session.status,
614
- agentMode: session.warmAgent ? "warm" : "disabled",
615
235
  launch: {
616
236
  started: !!launch.started,
617
237
  alreadyRunning: !!launch.alreadyRunning,
@@ -619,8 +239,8 @@ export class StudioDebugSessionStore {
619
239
  url: launch.url,
620
240
  pid: launch.pid || null,
621
241
  },
622
- pollCommand,
623
- claudeBaseUrl,
242
+ pollCommand: `node scripts/studio-debug-poll.mjs --session ${sessionId} --token ${token} --relay http://127.0.0.1:${this.port}/studio/claude/${sessionId}`,
243
+ claudeBaseUrl: `http://127.0.0.1:${this.port}/studio/claude/${sessionId}`,
624
244
  };
625
245
  }
626
246
 
@@ -639,195 +259,10 @@ export class StudioDebugSessionStore {
639
259
  const auth = this.authenticate(sessionId, body.token);
640
260
  if (auth.error) return auth;
641
261
  const session = auth.session;
642
- if (!session.warmAgent) {
643
- return {
644
- error: "agent_disabled",
645
- message: "This direct-write session does not allow agent-dispatched events.",
646
- };
647
- }
648
262
  const event = normalizeEvent(session, body);
649
263
 
650
264
  session.updatedAt = nowIso();
651
265
  session.status = "event_pending";
652
-
653
- // If a dispatchAgent handler exists, spawn a full headless Claude agent.
654
- if (this.dispatchAgent) {
655
- // Stash images from the event body so the dispatcher can write them to tmp
656
- if (Array.isArray(body.images) && body.images.length > 0) {
657
- session._pendingImages = body.images;
658
- }
659
-
660
- // A chat turn is conversational, not a source-edit dispatch: use buildChatPrompt()
661
- // (plain prose, no "make ONE source edit" instruction, no edit-JSON output contract)
662
- // and skip the syntax-check-and-retry loop below entirely — there's no edited file
663
- // to check, and the agent's raw reply text IS the message, not something to parse
664
- // as JSON. Previously every chat message reused buildEditPrompt(), so the agent was
665
- // told to edit a file and reply in {"status","message","filesChanged"} JSON for what
666
- // was just a question — see submitEvent's mode branch below for the corresponding fix.
667
- if (event.mode === "chat") {
668
- const chatPrompt = buildChatPrompt(session, event);
669
- this.dispatchAgent(event.id, session.token, null, session, chatPrompt)
670
- .then((result) => {
671
- const message = String(result?.package ?? "").trim() || "(no reply)";
672
- session.replies.push({
673
- eventId: event.id,
674
- status: result?.ok === false ? "error" : "done",
675
- message,
676
- filesChanged: [],
677
- diagnostics: [],
678
- createdAt: nowIso(),
679
- });
680
- session.status = result?.ok === false ? "error" : "done";
681
- session.updatedAt = nowIso();
682
- })
683
- .catch((err) => {
684
- session.replies.push({
685
- eventId: event.id,
686
- status: "error",
687
- message: `Chat dispatch failed: ${err?.message || "unknown error"}`,
688
- filesChanged: [],
689
- diagnostics: [],
690
- createdAt: nowIso(),
691
- });
692
- session.status = "error";
693
- session.updatedAt = nowIso();
694
- });
695
- return { ok: true, eventId: event.id, status: session.status };
696
- }
697
-
698
- const prompt = buildEditPrompt(session, event);
699
-
700
- const fallbackFiles = filesReferencedByEvent(event);
701
-
702
- const parseAgentResult = (result) => {
703
- // BUG FIX (2026-07-02): AgentPool.dispatchToSession()/dispatch() resolve with
704
- // `result.package` (the agent's raw final-text response, see agent-pool.js:629
705
- // `package: (text || "").trim()`) -- NOT `result.stdout` or `result.output`,
706
- // neither of which exist on this result shape. Reading the wrong fields meant
707
- // JSON.parse("") always threw, parsed silently stayed {}, and EVERY dispatch
708
- // reported status:"done" / filesChanged:[] regardless of what the agent
709
- // actually did -- the syntax-check-and-retry loop below was checking an empty
710
- // file list every single time and never catching anything.
711
- const rawText = String(result?.package ?? "").trim();
712
- let parsed = {};
713
- try {
714
- parsed = JSON.parse(rawText);
715
- } catch {
716
- // Agents don't always emit pure JSON despite instructions -- a trailing/leading
717
- // sentence around the JSON object is common. Try to recover the LAST {...}
718
- // block in the text before giving up (never throws further).
719
- const match = rawText.match(/\{[\s\S]*\}/);
720
- if (match) {
721
- try { parsed = JSON.parse(match[0]); } catch { /* give up, use defaults below */ }
722
- }
723
- }
724
- const filesChanged = Array.isArray(parsed.filesChanged) && parsed.filesChanged.length > 0
725
- ? parsed.filesChanged
726
- : fallbackFiles;
727
- return {
728
- status: parsed.status || "done",
729
- message: parsed.message || rawText.slice(0, 500) || "Agent completed",
730
- filesChanged,
731
- };
732
- };
733
-
734
- // D1/D2 (studio-editor-v1-auto-escalation.md): after the dispatched agent
735
- // reports back, verify the file(s) it touched still parse before trusting
736
- // "status":"done". A malformed agent JSON reply (bare try/catch above)
737
- // must NOT bypass this — filesChanged falls back to whatever the original
738
- // event referenced so even an unparseable reply still gets checked.
739
- // On a syntax failure, re-dispatch exactly once with the diagnostic
740
- // appended; a second failure (or a second dispatch error) is a hard stop
741
- // to status "error" with diagnostics attached — never a silent accept,
742
- // never an unbounded retry loop.
743
- this.dispatchAgent(event.id, session.token, null, session, prompt)
744
- .then(async (result) => {
745
- const attempt1 = parseAgentResult(result);
746
- const check1 = checkFilesSyntax(session, attempt1.filesChanged);
747
-
748
- if (check1.ok) {
749
- session.replies.push({
750
- eventId: event.id,
751
- status: attempt1.status,
752
- message: attempt1.message,
753
- filesChanged: attempt1.filesChanged,
754
- diagnostics: [],
755
- createdAt: nowIso(),
756
- });
757
- session.status = "done";
758
- session.updatedAt = nowIso();
759
- return;
760
- }
761
-
762
- const retryPrompt = [
763
- prompt,
764
- ``,
765
- `Your previous edit broke the file's syntax. Diagnostic: ${check1.diagnostics.join("; ")}.`,
766
- `Fix the file so it is syntactically valid, preserving your intended change.`,
767
- ].join("\n");
768
-
769
- let attempt2Result;
770
- try {
771
- attempt2Result = await this.dispatchAgent(event.id, session.token, null, session, retryPrompt);
772
- } catch {
773
- session.replies.push({
774
- eventId: event.id,
775
- status: "error",
776
- message: "Agent retry dispatch failed after syntax check failure",
777
- filesChanged: attempt1.filesChanged,
778
- diagnostics: check1.diagnostics,
779
- createdAt: nowIso(),
780
- });
781
- session.status = "error";
782
- session.updatedAt = nowIso();
783
- return;
784
- }
785
-
786
- const attempt2 = parseAgentResult(attempt2Result);
787
- const check2 = checkFilesSyntax(session, attempt2.filesChanged);
788
-
789
- if (check2.ok) {
790
- session.replies.push({
791
- eventId: event.id,
792
- status: attempt2.status,
793
- message: attempt2.message,
794
- filesChanged: attempt2.filesChanged,
795
- diagnostics: [],
796
- createdAt: nowIso(),
797
- });
798
- session.status = "done";
799
- session.updatedAt = nowIso();
800
- return;
801
- }
802
-
803
- session.replies.push({
804
- eventId: event.id,
805
- status: "error",
806
- message: `Agent edit failed syntax check after retry: ${check2.diagnostics.join("; ")}`,
807
- filesChanged: attempt2.filesChanged,
808
- diagnostics: check2.diagnostics,
809
- createdAt: nowIso(),
810
- });
811
- session.status = "error";
812
- session.updatedAt = nowIso();
813
- })
814
- .catch(() => {
815
- session.replies.push({
816
- eventId: event.id,
817
- status: "error",
818
- message: "Agent dispatch failed",
819
- filesChanged: [],
820
- diagnostics: [],
821
- createdAt: nowIso(),
822
- });
823
- session.status = "error";
824
- session.updatedAt = nowIso();
825
- });
826
-
827
- return { ok: true, eventId: event.id, status: session.status };
828
- }
829
-
830
- // Legacy path: queue for a polling agent
831
266
  if (session.pendingPolls.length > 0) {
832
267
  const poll = session.pendingPolls.shift();
833
268
  poll(event);
@@ -889,79 +324,6 @@ export class StudioDebugSessionStore {
889
324
  return { ok: true, status: session.status, reply };
890
325
  }
891
326
 
892
- writeText(sessionId, body) {
893
- const auth = this.authenticate(sessionId, body.token);
894
- if (auth.error) return auth;
895
- const session = auth.session;
896
- const textEdit = body.textEdit && typeof body.textEdit === "object" ? body.textEdit : {};
897
- const source = textEdit.source && typeof textEdit.source === "object" ? textEdit.source : {};
898
- const file = source.file || textEdit.file || body.file;
899
- const fileInfo = resolveSourceFile(session, file, TEXT_WRITE_EXTENSIONS);
900
- if (!fileInfo) {
901
- return { error: "invalid_source", message: `text-write requires a source file inside the debug session repo (got: ${file || "(none)"}).` };
902
- }
903
- if (typeof textEdit.newText !== "string") {
904
- return { error: "invalid_body", message: "text-write requires textEdit.newText." };
905
- }
906
- try {
907
- const original = fs.readFileSync(fileInfo.path, "utf8");
908
- const updated = applyTextRangeEdit(original, { ...textEdit, source });
909
- fs.writeFileSync(fileInfo.path, updated, "utf8");
910
- const reply = {
911
- eventId: body.id || `text_${crypto.randomUUID()}`,
912
- status: "done",
913
- message: `Direct text write (source_replace [${source.range?.start}, ${source.range?.end}])`,
914
- filesChanged: [fileInfo.relativePath],
915
- createdAt: nowIso(),
916
- };
917
- session.replies.push(reply);
918
- session.status = "done";
919
- session.updatedAt = nowIso();
920
- return { ok: true, status: "done", eventId: reply.eventId, filesChanged: reply.filesChanged };
921
- } catch (err) {
922
- return { error: "text_write_failed", message: err instanceof Error ? err.message : String(err) };
923
- }
924
- }
925
-
926
- writeStyle(sessionId, body) {
927
- const auth = this.authenticate(sessionId, body.token);
928
- if (auth.error) return auth;
929
- const session = auth.session;
930
- const styleEdit = body.styleEdit && typeof body.styleEdit === "object" ? body.styleEdit : {};
931
- const deltas = Array.isArray(styleEdit.deltas) ? styleEdit.deltas : [];
932
- const source = styleEdit.source && typeof styleEdit.source === "object" ? styleEdit.source : {};
933
- const fileInfo = resolveSourceFile(session, source.file || body.file);
934
- if (!fileInfo) return { error: "invalid_source", message: "style-write requires a source file inside the debug session repo." };
935
- if (deltas.length !== 1) return { error: "invalid_delta", message: "style-write currently accepts exactly one deterministic CSS delta." };
936
-
937
- const delta = deltas[0] || {};
938
- if (typeof delta.property !== "string" || typeof delta.value !== "string") {
939
- return { error: "invalid_delta", message: "style-write requires string property and value." };
940
- }
941
-
942
- try {
943
- const original = fs.readFileSync(fileInfo.path, "utf8");
944
- const ext = path.extname(fileInfo.path).toLowerCase();
945
- const result = ext === ".jsx" || ext === ".tsx"
946
- ? applyJsxStyleEdit(original, delta.property, delta.value, source.line || body.line || null)
947
- : applyCssTextEdit(original, delta.property, delta.value, source.line || body.line || null);
948
- fs.writeFileSync(fileInfo.path, result.content, "utf8");
949
- const reply = {
950
- eventId: body.id || `style_${crypto.randomUUID()}`,
951
- status: "done",
952
- message: `Direct style write (${result.strategy})`,
953
- filesChanged: [fileInfo.relativePath],
954
- createdAt: nowIso(),
955
- };
956
- session.replies.push(reply);
957
- session.status = "done";
958
- session.updatedAt = nowIso();
959
- return { ok: true, status: "done", eventId: reply.eventId, filesChanged: reply.filesChanged, strategy: result.strategy };
960
- } catch (err) {
961
- return { error: "style_write_failed", message: err instanceof Error ? err.message : String(err) };
962
- }
963
- }
964
-
965
327
  status(sessionId, token) {
966
328
  const auth = this.authenticate(sessionId, token);
967
329
  if (auth.error) return auth;
@@ -1002,9 +364,6 @@ export class StudioDebugSessionStore {
1002
364
  }
1003
365
  for (const poll of session.pendingPolls.splice(0)) poll({ type: "stopped" });
1004
366
  this.sessions.delete(sessionId);
1005
- if (this.releaseSessionWorker) {
1006
- try { this.releaseSessionWorker(sessionId); } catch { /* best-effort */ }
1007
- }
1008
367
  return { ok: true, status: "stopped", sessionId };
1009
368
  }
1010
369
  }
@@ -1026,28 +385,7 @@ export function createStudioDebugRuntime(options) {
1026
385
  }
1027
386
  }
1028
387
 
1029
- // Editable-prompts settings — the UI for .studio-editor-settings.json (loadEditorSettings()
1030
- // above / buildFullSystemPrompt()+buildStudioEditorSystemPrompt() in agent-pool.js). GET
1031
- // returns what's on disk (empty object if never set); POST merges a partial patch.
1032
- if (reqPath === "/studio/editor-settings") {
1033
- const repoRoot = url.searchParams.get("repoRoot");
1034
- if (!repoRoot) return writeJson(res, 400, { ok: false, error: "repoRoot query param required" }, cors);
1035
- if (method === "GET") {
1036
- return writeJson(res, 200, { ok: true, settings: loadEditorSettings(repoRoot) }, cors);
1037
- }
1038
- if (method === "POST") {
1039
- try {
1040
- const patch = await readBody(req);
1041
- const settings = saveEditorSettings(repoRoot, patch || {});
1042
- return writeJson(res, 200, { ok: true, settings }, cors);
1043
- } catch (err) {
1044
- return writeJson(res, 400, { ok: false, error: err.message }, cors);
1045
- }
1046
- }
1047
- return writeJson(res, 405, { ok: false, error: "method not allowed" }, cors);
1048
- }
1049
-
1050
- const debugMatch = reqPath.match(/^\/studio\/debug\/([^/]+)\/(events|style-write|text-write|status|stop)$/);
388
+ const debugMatch = reqPath.match(/^\/studio\/debug\/([^/]+)\/(events|status|stop)$/);
1051
389
  const claudeMatch = reqPath.match(/^\/studio\/claude\/([^/]+)\/(poll|reply|status)$/);
1052
390
  if (!debugMatch && !claudeMatch) return false;
1053
391
  const [, sessionId, action] = debugMatch || claudeMatch;
@@ -1057,14 +395,6 @@ export function createStudioDebugRuntime(options) {
1057
395
  const result = store.submitEvent(sessionId, await readBody(req));
1058
396
  return writeJson(res, result.error === "unauthorized" ? 401 : result.error ? 404 : 200, result, cors);
1059
397
  }
1060
- if (method === "POST" && action === "style-write") {
1061
- const result = store.writeStyle(sessionId, await readBody(req));
1062
- return writeJson(res, result.error === "unauthorized" ? 401 : result.error ? 400 : 200, result, cors);
1063
- }
1064
- if (method === "POST" && action === "text-write") {
1065
- const result = store.writeText(sessionId, await readBody(req));
1066
- return writeJson(res, result.error === "unauthorized" ? 401 : result.error ? 400 : 200, result, cors);
1067
- }
1068
398
  if (method === "GET" && action === "poll") {
1069
399
  const result = await store.poll(sessionId, url.searchParams.get("token"), url.searchParams.get("timeout"));
1070
400
  return writeJson(res, result.error === "unauthorized" ? 401 : result.error ? 404 : 200, result, cors);
@@ -1092,4 +422,3 @@ export function createStudioDebugRuntime(options) {
1092
422
  }
1093
423
 
1094
424
  export const studioDebugTargets = APP_TARGETS;
1095
- export { buildEditPrompt, buildChatPrompt, loadEditorSettings };