@topline-build/harness-mcp 0.9.2 → 0.9.4

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/dist/index.js CHANGED
@@ -1,13 +1,15 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { createHash, randomBytes } from "node:crypto";
3
- import { existsSync } from "node:fs";
3
+ import { existsSync, readFileSync, rmSync } from "node:fs";
4
4
  import { cp, mkdir, mkdtemp, readdir, readFile, realpath, lstat, writeFile, rm, rename } from "node:fs/promises";
5
5
  import { createServer } from "node:http";
6
+ import { AsyncLocalStorage } from "node:async_hooks";
6
7
  import os from "node:os";
7
8
  import path from "node:path";
8
9
  import { gzipSync } from "node:zlib";
9
10
  import { externalBuildHelperTools, EXTERNAL_BUILD_FORWARD_TOOLS, EXTERNAL_BUILD_SESSION_FORWARD_TOOLS, EXTERNAL_BUILD_SESSION_TOOLS } from "./build-session-tools.js";
10
11
  import { domainHelperTools, DOMAIN_FORWARD_TOOLS, DOMAIN_ERROR_CODES } from "./domain-tools.js";
12
+ import { ARTIFACT_STARTER_IDS, artifactStarterRecipe, artifactStarterSource, findArtifactStarter } from "./artifact-starters.js";
11
13
  import { boundedTransfer, extractArtifactSourceArchive, MAX_SOURCE_ARCHIVE_BYTES, safeSourcePath } from "./source-checkout.js";
12
14
  import { Server as McpServer } from "@modelcontextprotocol/sdk/server/index.js";
13
15
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
@@ -17,7 +19,7 @@ const MCP_SURFACES = ["build", "topline", "harness"];
17
19
  export const DEFAULT_MCP_PROTOCOL_VERSION = "2025-11-25";
18
20
  const DEFAULT_TIMEOUT_MS = 120_000;
19
21
  export const BUILD_MCP_SERVER_NAME = "topline-build-stdio";
20
- export const HARNESS_MCP_VERSION = "0.9.2";
22
+ export const HARNESS_MCP_VERSION = "0.9.4";
21
23
  export const DEFAULT_OAUTH_SCOPES = Object.freeze(["harness:artifact:read", "harness:artifact:write", "harness:artifact:deploy", "harness:artifact:delete"]);
22
24
  /** The Topline server's scopes: Build and Workspace. Consent shows what the seat allows. */
23
25
  export const TOPLINE_OAUTH_SCOPES = Object.freeze([
@@ -135,17 +137,34 @@ export async function signInAtStartup(opts, onSignedIn, log = (message) => proce
135
137
  return false;
136
138
  try {
137
139
  const stored = await readStoredOAuthCredentials(opts);
138
- if (stored?.refreshToken || (stored?.accessToken && Date.parse(stored.accessTokenExpiresAt ?? "") > Date.now()))
140
+ if (stored?.accessToken && Date.parse(stored.accessTokenExpiresAt ?? "") > Date.now())
139
141
  return false;
142
+ if (stored?.refreshToken) {
143
+ // An expired access token: refresh it now, so a saved sign-in Topline
144
+ // has since refused opens the browser here instead of failing a tool call.
145
+ try {
146
+ if (await getBearerTokenWithoutSignIn(opts))
147
+ return false;
148
+ }
149
+ catch (err) {
150
+ if (!isSignInRejected(err))
151
+ return false;
152
+ log("Your saved Topline sign-in has expired.");
153
+ }
154
+ }
140
155
  // Hosts often start one server per window or session; only one of them opens the browser.
141
- if (!(await takeStartupSignInLock(opts.authFile)))
156
+ if (!(await takeSignInLock(opts.authFile))) {
157
+ // Another window is signing in: list tools again here once it lands.
158
+ watchForSignIn(opts, onSignedIn, stored);
142
159
  return false;
160
+ }
143
161
  try {
144
162
  log(`Opening your browser to sign in to Topline at ${platformBaseUrl(opts)}. Choose Allow to load the Topline tools.`);
145
163
  await interactiveSignIn({
146
164
  ...opts,
147
165
  quietOpenFailure: true,
148
166
  openUrl: async (url) => {
167
+ await shareSignInUrl(opts.authFile, url);
149
168
  // Printed every time: with no browser (SSH, a container) this is the only way to finish.
150
169
  log(`If it does not open, visit this address:\n${url}`);
151
170
  await (opts.openUrl ? opts.openUrl(url) : openBrowser({ ...opts, openUrl: undefined, quietOpenFailure: true }, url));
@@ -153,7 +172,7 @@ export async function signInAtStartup(opts, onSignedIn, log = (message) => proce
153
172
  });
154
173
  }
155
174
  finally {
156
- await rm(startupSignInLockFile(opts.authFile), { force: true }).catch(() => undefined);
175
+ await releaseSignInLock(opts.authFile);
157
176
  }
158
177
  await onSignedIn().catch(() => undefined);
159
178
  return true;
@@ -163,27 +182,178 @@ export async function signInAtStartup(opts, onSignedIn, log = (message) => proce
163
182
  return false;
164
183
  }
165
184
  }
166
- function startupSignInLockFile(authFile) {
185
+ // How long a browser sign-in waits for Allow (the callback server's timeout).
186
+ const SIGN_IN_WINDOW_MS = 5 * 60 * 1000;
187
+ const SIGN_IN_WATCH_INTERVAL_MS = 500;
188
+ function signInLockFile(authFile) {
167
189
  return `${path.resolve(authFile)}.signin-lock`;
168
190
  }
169
- /** True when this process may run the startup sign-in; a lock younger than the 5-minute sign-in window means another one is. */
170
- async function takeStartupSignInLock(authFile) {
171
- const lock = startupSignInLockFile(authFile);
191
+ /**
192
+ * True when this process may run the browser sign-in for this auth file.
193
+ * Hosts start one server per window or session, and every one of them can be
194
+ * refused at once; the lock keeps that to one browser tab. A lock younger than
195
+ * the sign-in window means another process is running it.
196
+ */
197
+ async function takeSignInLock(authFile) {
198
+ const lock = signInLockFile(authFile);
172
199
  await mkdir(path.dirname(lock), { recursive: true });
173
200
  for (let attempt = 0; attempt < 2; attempt += 1) {
174
201
  try {
175
- await writeFile(lock, `${process.pid}\n`, { flag: "wx", mode: 0o600 });
202
+ await writeFile(lock, `${JSON.stringify({ pid: process.pid })}\n`, { flag: "wx", mode: 0o600 });
203
+ heldSignInLocks.add(lock);
204
+ releaseSignInLocksOnExit();
176
205
  return true;
177
206
  }
178
207
  catch {
208
+ const owner = await readSignInLock(lock);
209
+ // An owner that died (crash, closed window) cannot finish its sign-in; its lock is stale at once.
210
+ const ownerGone = owner?.pid !== undefined && owner.pid !== process.pid && !processAlive(owner.pid);
179
211
  const age = Date.now() - ((await lstat(lock).catch(() => null))?.mtimeMs ?? 0);
180
- if (age < 6 * 60 * 1000)
212
+ if (!ownerGone && age < SIGN_IN_WINDOW_MS + 60 * 1000)
181
213
  return false;
182
214
  await rm(lock, { force: true }).catch(() => undefined);
183
215
  }
184
216
  }
185
217
  return false;
186
218
  }
219
+ /** The lock's owner and shared address. 0.9.2 wrote a bare pid. */
220
+ async function readSignInLock(lock) {
221
+ let text;
222
+ try {
223
+ text = await readFile(lock, "utf8");
224
+ }
225
+ catch {
226
+ return null;
227
+ }
228
+ return parseSignInLock(text);
229
+ }
230
+ function parseSignInLock(text) {
231
+ try {
232
+ const parsed = JSON.parse(text);
233
+ if (isRecord(parsed)) {
234
+ return {
235
+ ...(Number.isInteger(parsed.pid) && parsed.pid > 0 ? { pid: parsed.pid } : {}),
236
+ ...(typeof parsed.signInUrl === "string" ? { signInUrl: parsed.signInUrl } : {})
237
+ };
238
+ }
239
+ if (Number.isInteger(parsed) && parsed > 0)
240
+ return { pid: parsed };
241
+ }
242
+ catch {
243
+ // Not JSON.
244
+ }
245
+ return {};
246
+ }
247
+ /** False only when the process is known to be gone; EPERM means it exists under another user. */
248
+ function processAlive(pid) {
249
+ try {
250
+ process.kill(pid, 0);
251
+ return true;
252
+ }
253
+ catch (err) {
254
+ return err.code !== "ESRCH";
255
+ }
256
+ }
257
+ // Locks this process took, removed on exit so a closed window does not block the others.
258
+ const heldSignInLocks = new Set();
259
+ let releasesOnExit = false;
260
+ function releaseSignInLocksOnExit() {
261
+ if (releasesOnExit)
262
+ return;
263
+ releasesOnExit = true;
264
+ process.once("exit", () => {
265
+ for (const lock of heldSignInLocks) {
266
+ try {
267
+ if (parseSignInLock(readFileSync(lock, "utf8")).pid === process.pid)
268
+ rmSync(lock, { force: true });
269
+ }
270
+ catch {
271
+ // Already gone.
272
+ }
273
+ }
274
+ });
275
+ }
276
+ async function ownsSignInLock(lock) {
277
+ return (await readSignInLock(lock))?.pid === process.pid;
278
+ }
279
+ async function releaseSignInLock(authFile) {
280
+ const lock = signInLockFile(authFile);
281
+ heldSignInLocks.delete(lock);
282
+ if (await ownsSignInLock(lock))
283
+ await rm(lock, { force: true }).catch(() => undefined);
284
+ }
285
+ /** Put the authorize address in the lock, so other processes can hand the person the same tab. */
286
+ async function shareSignInUrl(authFile, signInUrl) {
287
+ const lock = signInLockFile(authFile);
288
+ if (!(await ownsSignInLock(lock)))
289
+ return;
290
+ await writeFile(lock, `${JSON.stringify({ pid: process.pid, signInUrl })}\n`, { mode: 0o600 }).catch(() => undefined);
291
+ }
292
+ /** The address another process's sign-in is waiting on, only when its owner is alive and it is a plain authorize address for this account. */
293
+ async function sharedSignInUrl(opts) {
294
+ const owner = await readSignInLock(signInLockFile(opts.authFile));
295
+ if (!owner?.signInUrl || owner.pid === undefined || !processAlive(owner.pid))
296
+ return null;
297
+ return shareableSignInUrl(opts, owner.signInUrl);
298
+ }
299
+ // What an authorize address may carry. Anything else, a verifier above all, is never shown.
300
+ const SHAREABLE_SIGN_IN_PARAMS = new Set(["response_type", "client_id", "redirect_uri", "scope", "resource", "code_challenge", "code_challenge_method", "state"]);
301
+ function shareableSignInUrl(opts, raw) {
302
+ let url;
303
+ try {
304
+ url = new URL(raw);
305
+ }
306
+ catch {
307
+ return null;
308
+ }
309
+ if (url.username || url.password || url.hash || `${url.origin}${url.pathname}` !== `${platformBaseUrl(opts)}/oauth/authorize`)
310
+ return null;
311
+ const keys = [...url.searchParams.keys()];
312
+ if (new Set(keys).size !== keys.length || keys.some((key) => !SHAREABLE_SIGN_IN_PARAMS.has(key)))
313
+ return null;
314
+ const param = (key) => url.searchParams.get(key) ?? "";
315
+ if (param("response_type") !== "code" || param("code_challenge_method") !== "S256")
316
+ return null;
317
+ if (!param("client_id") || !param("code_challenge") || !param("state"))
318
+ return null;
319
+ if (!/^http:\/\/127\.0\.0\.1:\d{1,5}\/callback$/.test(param("redirect_uri")))
320
+ return null;
321
+ return url.toString();
322
+ }
323
+ // Auth files this process is already watching for another process's sign-in.
324
+ const signInWatches = new Set();
325
+ function credentialsTag(stored) {
326
+ return stored ? JSON.stringify([stored.accessToken ?? null, stored.refreshToken ?? null]) : null;
327
+ }
328
+ /**
329
+ * Another process runs the browser sign-in; poll the auth file (bounded by
330
+ * the sign-in window, never keeping the process alive) and list tools again
331
+ * once, when its new sign-in lands.
332
+ */
333
+ function watchForSignIn(opts, onSignedIn, baseline) {
334
+ const key = path.resolve(opts.authFile);
335
+ if (signInWatches.has(key))
336
+ return;
337
+ signInWatches.add(key);
338
+ const tag = credentialsTag(baseline);
339
+ const deadline = Date.now() + SIGN_IN_WINDOW_MS;
340
+ let checking = false;
341
+ const stop = () => { clearInterval(timer); signInWatches.delete(key); };
342
+ const timer = setInterval(() => {
343
+ if (checking)
344
+ return;
345
+ if (Date.now() > deadline)
346
+ return stop();
347
+ checking = true;
348
+ void readStoredOAuthCredentials(opts).catch(() => null).then(async (current) => {
349
+ if (!current || credentialsTag(current) === tag)
350
+ return;
351
+ stop();
352
+ await onSignedIn().catch(() => undefined);
353
+ }).finally(() => { checking = false; });
354
+ }, SIGN_IN_WATCH_INTERVAL_MS);
355
+ timer.unref?.();
356
+ }
187
357
  // One browser sign-in per auth file at a time: the startup sign-in and a tool
188
358
  // call that needs a token share it instead of opening two approvals.
189
359
  const inFlightSignIns = new Map();
@@ -205,6 +375,196 @@ async function interactiveSignIn(opts) {
205
375
  inFlightSignIns.delete(key);
206
376
  }
207
377
  }
378
+ // The address of the browser sign-in open for each auth file, so a tool call
379
+ // that joins it can still hand the person the link.
380
+ const signInUrls = new Map();
381
+ // When each auth file last finished a browser sign-in. A refusal right after
382
+ // one means Topline refuses the new sign-in too, so another browser tab would
383
+ // not help.
384
+ const lastSignIns = new Map();
385
+ const SIGN_IN_COOLDOWN_MS = 5 * 60 * 1000;
386
+ const signInUsage = new AsyncLocalStorage();
387
+ /** The auth file holds a different sign-in than the one the refused call used. */
388
+ function signInRenewedSince(usage, current) {
389
+ if (!current)
390
+ return false;
391
+ if (usage.bearer)
392
+ return current.accessToken !== usage.bearer && (Boolean(current.accessToken) || current.refreshToken !== usage.before?.refreshToken);
393
+ return usage.before !== null && credentialsTag(current) !== credentialsTag(usage.before);
394
+ }
395
+ /**
396
+ * Topline refused this computer's saved sign-in (expired or revoked), so the
397
+ * person would otherwise have to clear it by hand. First rule out the cases
398
+ * where an Allow page would not help: another window (or a refresh) already
399
+ * renewed the sign-in, or one refresh of the saved sign-in works (a 401 for
400
+ * another reason, such as a gateway glitch); both return `sign_in_renewed`
401
+ * so the assistant calls again. Otherwise start the browser
402
+ * sign-in, without waiting for Allow, and return `sign_in_required` with the
403
+ * address so the assistant can ask the person to choose Allow and then call
404
+ * the tool again. The refused call is never replayed, and the saved sign-in is
405
+ * only replaced once the new one succeeds. A manual token, which only its
406
+ * owner can replace, keeps `authorization_required`.
407
+ */
408
+ async function withSignInRecovery(opts, result, usage, onSignedIn) {
409
+ const error = isRecord(result.structuredContent) && isRecord(result.structuredContent.error) ? result.structuredContent.error : null;
410
+ if (error?.code !== "authorization_required" || opts.token || !servesBuild(opts))
411
+ return result;
412
+ let current = await readStoredOAuthCredentials(opts).catch(() => null);
413
+ if (signInRenewedSince(usage, current))
414
+ return signInErrorResult("sign_in_renewed", "The Topline sign-in was renewed (by another window or a refresh) while this call was on its way, so it was refused with the old one. Nothing was replayed.");
415
+ // Topline refused a token obtained moments ago: refreshing or signing in
416
+ // again would not help, and retrying would loop.
417
+ if (usage.bearer && current?.accessToken === usage.bearer && tokenIsFresh(current.obtainedAt))
418
+ return notASignInProblem(result);
419
+ const key = path.resolve(opts.authFile);
420
+ if (Date.now() - (lastSignIns.get(key) ?? 0) < SIGN_IN_COOLDOWN_MS)
421
+ return result;
422
+ if (current?.refreshToken && current.clientId) {
423
+ try {
424
+ await refreshStoredOAuthToken(opts, current);
425
+ // The saved sign-in still works once refreshed: no Allow page, just call again.
426
+ return signInErrorResult("sign_in_renewed", "Your Topline sign-in was renewed — try again.");
427
+ }
428
+ catch (err) {
429
+ // A temporary refresh failure says nothing about the sign-in; do not send the person to Allow.
430
+ if (!isSignInRejected(err))
431
+ return result;
432
+ }
433
+ current = await readStoredOAuthCredentials(opts).catch(() => null);
434
+ }
435
+ const started = await startBrowserSignIn(opts, onSignedIn, current);
436
+ // The sign-in could not even start (Topline unreachable): keep the original guidance.
437
+ if (started.kind === "failed")
438
+ return result;
439
+ if (started.kind === "renewed")
440
+ return signInErrorResult("sign_in_renewed", "Another Topline window finished a new sign-in just now. Nothing was replayed.");
441
+ return signInErrorResult("sign_in_required", started.kind === "elsewhere"
442
+ ? "Topline no longer accepts this computer's saved sign-in (it expired or was revoked), and a sign-in is already waiting in your browser: another Topline window started it."
443
+ : "Topline no longer accepts this computer's saved sign-in (it expired or was revoked), so a new browser sign-in has started.", started.signInUrl, error.recovery);
444
+ }
445
+ const FRESH_TOKEN_MS = 2 * 60 * 1000;
446
+ /** Obtained within the last 2 minutes. A time in the future (clock stepped back, bad value) is not fresh. */
447
+ function tokenIsFresh(obtainedAt) {
448
+ const age = Date.now() - Date.parse(obtainedAt ?? "");
449
+ return Number.isFinite(age) && age >= 0 && age < FRESH_TOKEN_MS;
450
+ }
451
+ function notASignInProblem(result) {
452
+ const content = result.structuredContent;
453
+ const structuredContent = { ...content, error: { ...content.error, retryable: false, recoveryAction: "Topline refused this request even with a fresh sign-in, so it isn't a sign-in problem. Don't retry; report the error." } };
454
+ return { ...result, content: [{ type: "text", text: JSON.stringify(structuredContent, null, 2) }], structuredContent };
455
+ }
456
+ function signInErrorResult(code, message, signInUrl, recovery) {
457
+ const structuredContent = {
458
+ ok: false,
459
+ error: {
460
+ code,
461
+ message,
462
+ ...BUILD_MCP_RECOVERY_ERRORS[code],
463
+ ...(signInUrl ? { signInUrl } : {}),
464
+ ...(recovery !== undefined ? { recovery } : {})
465
+ }
466
+ };
467
+ return {
468
+ content: [
469
+ { type: "text", text: JSON.stringify(structuredContent, null, 2) },
470
+ ...(signInUrl ? [{ type: "resource_link", uri: signInUrl, name: "Sign in to Topline" }] : [])
471
+ ],
472
+ structuredContent,
473
+ isError: true
474
+ };
475
+ }
476
+ // Serializes the decision to start a sign-in within this process, so two
477
+ // refused calls at once join one sign-in instead of racing for the lock.
478
+ const signInStarts = new Map();
479
+ /**
480
+ * Start (or join) the browser sign-in for this auth file without waiting for
481
+ * Allow. Only the process holding the cross-process sign-in lock opens a tab;
482
+ * the others watch the auth file and list tools again once it changes. With
483
+ * `expected`, the sign-in the caller saw, a newer one found after taking the
484
+ * lock is used instead of opening a tab.
485
+ */
486
+ async function startBrowserSignIn(opts, onSignedIn, expected) {
487
+ const key = path.resolve(opts.authFile);
488
+ const known = signInUrls.get(key);
489
+ if (known)
490
+ return { kind: "started", signInUrl: known };
491
+ while (signInStarts.has(key))
492
+ await signInStarts.get(key);
493
+ let decided;
494
+ signInStarts.set(key, new Promise((resolve) => { decided = resolve; }));
495
+ let opened = () => undefined;
496
+ const address = new Promise((resolve) => { opened = resolve; });
497
+ let failed = false;
498
+ try {
499
+ const runsOwnSignIn = !inFlightSignIns.has(key);
500
+ if (runsOwnSignIn) {
501
+ if (!(await takeSignInLock(opts.authFile).catch(() => false))) {
502
+ watchForSignIn(opts, onSignedIn, expected !== undefined ? expected : await readStoredOAuthCredentials(opts).catch(() => null));
503
+ return { kind: "elsewhere", signInUrl: await sharedSignInUrl(opts) };
504
+ }
505
+ if (expected !== undefined && credentialsTag(await readStoredOAuthCredentials(opts).catch(() => null)) !== credentialsTag(expected)) {
506
+ await releaseSignInLock(opts.authFile);
507
+ return { kind: "renewed" };
508
+ }
509
+ }
510
+ const pending = interactiveSignIn({
511
+ ...opts,
512
+ quietOpenFailure: true,
513
+ openUrl: async (url) => {
514
+ await shareSignInUrl(opts.authFile, url);
515
+ opened(url);
516
+ await (opts.openUrl ? opts.openUrl(url) : openBrowser({ ...opts, openUrl: undefined, quietOpenFailure: true }, url));
517
+ }
518
+ });
519
+ pending.then(() => { lastSignIns.set(key, Date.now()); return onSignedIn(); }, () => { failed = true; })
520
+ .catch(() => undefined)
521
+ .finally(() => {
522
+ opened(null);
523
+ // This process took the lock for its sign-in; a joined sign-in's owner releases its own.
524
+ if (runsOwnSignIn)
525
+ void releaseSignInLock(opts.authFile);
526
+ });
527
+ }
528
+ finally {
529
+ signInStarts.delete(key);
530
+ decided();
531
+ }
532
+ const timer = setTimeout(() => opened(null), opts.timeoutMs);
533
+ timer.unref?.();
534
+ // Joining a sign-in that has not published its address yet never calls
535
+ // this openUrl, so watch for the address it publishes instead.
536
+ const poll = setInterval(() => { const url = signInUrls.get(key); if (url)
537
+ opened(url); }, 100);
538
+ poll.unref?.();
539
+ const signInUrl = (await address) ?? signInUrls.get(key) ?? null;
540
+ clearTimeout(timer);
541
+ clearInterval(poll);
542
+ if (!signInUrl && failed)
543
+ return { kind: "failed" };
544
+ return { kind: "started", signInUrl };
545
+ }
546
+ /** `platform_sign_in`: a fresh browser sign-in the person or assistant asks for, signed in or not. */
547
+ async function signInTool(opts, onSignedIn) {
548
+ if (opts.token)
549
+ return structuredToolError("manual_token_sign_in_unavailable");
550
+ if (!servesBuild(opts))
551
+ return structuredToolError("sign_in_unavailable_on_harness_surface");
552
+ const started = await startBrowserSignIn(opts, onSignedIn);
553
+ if (started.kind === "failed" || started.kind === "renewed")
554
+ return structuredToolError("sign_in_unavailable: Topline did not answer the sign-in request. Try again shortly.");
555
+ const signInUrl = started.signInUrl;
556
+ const result = toolResult({
557
+ ok: true,
558
+ status: "sign_in_started",
559
+ message: started.kind === "elsewhere"
560
+ ? "A Topline sign-in another Topline window started is already waiting in the person's browser. Ask them to sign in there and choose Allow; the Topline tools reload after that. The saved sign-in is only replaced once they allow it."
561
+ : "A Topline sign-in page opened in the person's browser. Ask them to sign in and choose Allow; the Topline tools reload after that. The saved sign-in is only replaced once they allow it.",
562
+ ...(signInUrl ? { signInUrl } : {})
563
+ });
564
+ if (signInUrl)
565
+ result.content.push({ type: "resource_link", uri: signInUrl, name: "Sign in to Topline" });
566
+ return result;
567
+ }
208
568
  /**
209
569
  * `topline-mcp login`: sign in once during setup so the assistant's next chat
210
570
  * starts already connected. Opens the browser, saves the refresh token to the
@@ -282,6 +642,8 @@ export function createHarnessMcpStdioServer(opts, toolAllowlist) {
282
642
  let hostedSessionSchemas = new Map();
283
643
  // Only the newest listing writes shared state, so a slow older one cannot overwrite it.
284
644
  let listingGeneration = 0;
645
+ // The tool list only changes when signing in (from signed out, which is
646
+ // null) or when the scopes change, so a token refresh is not a new grant.
285
647
  const grantTag = (stored) => stored?.accessToken && Date.parse(stored.accessTokenExpiresAt ?? "") > Date.now()
286
648
  ? JSON.stringify([stored.clientId, stored.resource, [...stored.scopes].sort()]) : null;
287
649
  // Identifies one sign-in regardless of access-token expiry: each browser
@@ -395,6 +757,8 @@ export function createHarnessMcpStdioServer(opts, toolAllowlist) {
395
757
  }
396
758
  const reportsProgress = req.params.name === "platform_deploy_artifact_app" || req.params.name === "platform_wait_artifact_deploy";
397
759
  let refusedHidden = false;
760
+ // The sign-in this call starts from, and the bearer it sends.
761
+ const usage = { before: servesBuild(opts) && !opts.token ? await readStoredOAuthCredentials(opts).catch(() => null) : null };
398
762
  try {
399
763
  // A changed sign-in (for example a reconnect with new scopes) may offer
400
764
  // the tool again; Topline still checks, so the call goes through.
@@ -406,20 +770,21 @@ export function createHarnessMcpStdioServer(opts, toolAllowlist) {
406
770
  if (!forwardsHostedTool(req.params.name))
407
771
  throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${req.params.name}`);
408
772
  // Workspace and other hosted tools: Topline checks scopes and seat.
409
- return await forwardHostedTool(opts, req.params.name, req.params.arguments ?? {});
773
+ return await signInUsage.run(usage, () => forwardHostedTool(opts, req.params.name, req.params.arguments ?? {}));
410
774
  }
411
- const result = await callHarnessTool(opts, req.params.name, req.params.arguments ?? {}, {
775
+ const result = await signInUsage.run(usage, () => callHarnessTool(opts, req.params.name, req.params.arguments ?? {}, {
412
776
  ...(reportsProgress ? { onProgress: (progress, message) => sendProgress(extra, progress, 1, message) } : {}),
413
- inputSchema: hostedSessionSchemas.get(req.params.name)
414
- });
415
- return result;
777
+ inputSchema: hostedSessionSchemas.get(req.params.name),
778
+ onSignedIn: () => mcp.sendToolListChanged()
779
+ }));
780
+ return await withSignInRecovery(opts, result, usage, () => mcp.sendToolListChanged());
416
781
  }
417
782
  catch (err) {
418
783
  if (err instanceof McpError)
419
784
  throw err;
420
785
  if (reportsProgress)
421
786
  await sendProgress(extra, 1, 1, "Failed artifact deployment");
422
- return structuredToolError(redactSecrets(err instanceof Error ? err.message : String(err), opts));
787
+ return await withSignInRecovery(opts, structuredToolError(redactSecrets(err instanceof Error ? err.message : String(err), opts)), usage, () => mcp.sendToolListChanged());
423
788
  }
424
789
  finally {
425
790
  let listChanged = false;
@@ -455,6 +820,9 @@ export async function callHarnessTool(opts, name, args, hooks) {
455
820
  return toolError(`Invalid arguments for ${name}: ${inputError}`);
456
821
  let result;
457
822
  switch (name) {
823
+ case "platform_sign_in":
824
+ result = await signInTool(opts, hooks?.onSignedIn ?? (async () => undefined));
825
+ break;
458
826
  case "platform_connection_check":
459
827
  case "platform_get_design_system_state":
460
828
  case "platform_edit_design_system":
@@ -463,11 +831,21 @@ export async function callHarnessTool(opts, name, args, hooks) {
463
831
  case "platform_list_artifact_drafts":
464
832
  case "platform_deploy_operation":
465
833
  case "platform_validate_artifact":
466
- case "platform_run_artifact_smoke":
467
834
  case "platform_plan_artifact_draft_delete":
468
835
  case "platform_delete_artifact_draft":
469
836
  result = toolResult(await callHostedBuildTool(opts, name, input));
470
837
  break;
838
+ case "platform_run_artifact_smoke":
839
+ // A dev sandbox smoke returns its screenshot as image content, so pass the whole hosted result through.
840
+ if (input.target === "sandbox") {
841
+ if (!servesBuild(opts))
842
+ throw new Error(`${name}_requires_build_surface`);
843
+ result = await forwardHostedTool(opts, name, input);
844
+ }
845
+ else {
846
+ result = toolResult(await callHostedBuildTool(opts, name, input));
847
+ }
848
+ break;
471
849
  case "platform_checkout_design_system":
472
850
  result = toolResult(await checkoutDesignSystem(opts, input));
473
851
  break;
@@ -490,7 +868,8 @@ export async function callHarnessTool(opts, name, args, hooks) {
490
868
  result = toolResult(await getArtifactStatus(opts, stringArg(input, "artifactId"), numberArg(input, "limit")));
491
869
  break;
492
870
  case "platform_read_artifact_logs":
493
- result = toolResult(await readArtifactLogs(opts, input));
871
+ // Dev sandbox logs are only served by the hosted tool, not the REST logs route.
872
+ result = toolResult(input.target === "sandbox" ? await callHostedBuildTool(opts, name, input) : await readArtifactLogs(opts, input));
494
873
  break;
495
874
  case "platform_open_artifact":
496
875
  result = toolResult(await openArtifact(opts, stringArg(input, "artifactId")));
@@ -989,6 +1368,12 @@ export async function initArtifactApp(opts, input) {
989
1368
  if (existsSync(absoluteAppDir) && (await readdir(absoluteAppDir)).length > 0)
990
1369
  throw new Error("artifact_app_scaffold_target_not_empty");
991
1370
  const shape = optionalString(input, "shape") ?? "single";
1371
+ const starterId = optionalString(input, "starter");
1372
+ const starter = starterId ? findArtifactStarter(starterId) : undefined;
1373
+ if (starterId && !starter)
1374
+ throw new Error("artifact_app_scaffold_starter_invalid");
1375
+ if (starter && shape !== "single")
1376
+ throw new Error("artifact_app_scaffold_starter_shape_conflict");
992
1377
  if (shape === "web-and-api")
993
1378
  return initWebAndApiArtifactApp(opts, { appDir, absoluteAppDir, manifestId, title });
994
1379
  if (shape !== "single")
@@ -998,21 +1383,23 @@ export async function initArtifactApp(opts, input) {
998
1383
  manifestVersion: 2,
999
1384
  id: manifestId,
1000
1385
  title,
1001
- kind: "tool",
1386
+ kind: starter?.kind ?? "tool",
1002
1387
  runtime: { target: "aws_lambda_function_url", region: "us-west-2", entryPoint: "artifactApp" },
1003
1388
  build: { command: "node src/index.js --build", outputDir: "dist" },
1004
1389
  validation: { localCommand: "node src/index.js --test", testCommand: "node src/index.js --test --artifact-tests-json" },
1005
- routes: [
1006
- { path: "/", kind: "page", handler: "artifactApp" },
1007
- { path: "/_artifact/health", kind: "api", handler: "artifactApp" }
1008
- ],
1390
+ routes: starter
1391
+ ? [{ path: "/", kind: "page", handler: "artifactApp" }, ...starter.routes.map((route) => ({ path: route.path, kind: "api", handler: "artifactApp" }))]
1392
+ : [
1393
+ { path: "/", kind: "page", handler: "artifactApp" },
1394
+ { path: "/_artifact/health", kind: "api", handler: "artifactApp" }
1395
+ ],
1009
1396
  sourceBindings: [],
1010
1397
  env: ["ARTIFACT_ID", "ARTIFACT_VERSION_ID", "ARTIFACT_MANIFEST_URI", "PLATFORM_ARTIFACT_ID", "PLATFORM_ARTIFACT_VERSION_ID", "PLATFORM_ARTIFACT_MANIFEST_URI"],
1011
1398
  viewerPolicy: "private"
1012
1399
  };
1013
1400
  const packageJson = { name: manifestId, private: true, type: "module", main: "src/index.js", scripts: { build: "node src/index.js --build", test: "node src/index.js --test" } };
1014
1401
  const safeTitle = title.replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[char]));
1015
- const source = `import { mkdirSync, writeFileSync } from "node:fs";\nimport path from "node:path";\n\nconst page = ${JSON.stringify(`<!doctype html><html><body><main data-platform-artifact-root><h1>${safeTitle}</h1><p>Ready.</p></main></body></html>`)};\n\nexport function artifactApp(_req, res) {\n res.setHeader("content-type", "text/html; charset=utf-8");\n res.end(page);\n}\n\nif (process.argv.includes("--build")) {\n mkdirSync("dist", { recursive: true });\n writeFileSync(path.join("dist", "index.html"), page, "utf8");\n}\n\nif (process.argv.includes("--test") && process.argv.includes("--artifact-tests-json")) {\n console.log(JSON.stringify({ tests: [{ description: "The artifact renders a visible app root.", required: true, status: "passed", summary: "The page includes data-platform-artifact-root.", evidence: { selector: "data-platform-artifact-root" } }] }));\n} else if (process.argv.includes("--build") || process.argv.includes("--test")) {\n console.log("artifact app template ok");\n}\n`;
1402
+ const source = starter ? artifactStarterSource(starter, title) : `import { mkdirSync, writeFileSync } from "node:fs";\nimport path from "node:path";\n\nconst page = ${JSON.stringify(`<!doctype html><html><body><main data-platform-artifact-root><h1>${safeTitle}</h1><p>Ready.</p></main></body></html>`)};\n\nexport function artifactApp(_req, res) {\n res.setHeader("content-type", "text/html; charset=utf-8");\n res.end(page);\n}\n\nif (process.argv.includes("--build")) {\n mkdirSync("dist", { recursive: true });\n writeFileSync(path.join("dist", "index.html"), page, "utf8");\n}\n\nif (process.argv.includes("--test") && process.argv.includes("--artifact-tests-json")) {\n console.log(JSON.stringify({ tests: [{ description: "Scaffold check: the artifact renders a visible app root.", required: true, status: "passed", summary: "Generated starter check; not proof of implemented behavior.", evidence: { selector: "data-platform-artifact-root", scaffold: true } }] }));\n} else if (process.argv.includes("--build") || process.argv.includes("--test")) {\n console.log("artifact app template ok");\n}\n`;
1016
1403
  await Promise.all([
1017
1404
  writeFile(path.join(absoluteAppDir, "artifact-app.json"), `${JSON.stringify(manifest, null, 2)}\n`, { flag: "wx" }),
1018
1405
  writeFile(path.join(absoluteAppDir, "package.json"), `${JSON.stringify(packageJson, null, 2)}\n`, { flag: "wx" }),
@@ -1024,7 +1411,10 @@ export async function initArtifactApp(opts, input) {
1024
1411
  manifestId,
1025
1412
  title,
1026
1413
  files: ["artifact-app.json", "package.json", "src/index.js"],
1027
- nextAction: `Run npm test in ${appDir}, then call platform_inspect_artifact_app with the same appDir before deployment.`
1414
+ ...(starter ? { starter: starter.id, recipe: artifactStarterRecipe(starter) } : {}),
1415
+ nextAction: starter
1416
+ ? `Read the ${starter.id} recipe (docs id build-cookbook-example-${starter.id}) and replace each placeholder route. Its tests are scaffold checks, not proof of behavior. Then run npm test in ${appDir} and call platform_inspect_artifact_app with the same appDir before deployment.`
1417
+ : `Run npm test in ${appDir}, then call platform_inspect_artifact_app with the same appDir before deployment.`
1028
1418
  };
1029
1419
  }
1030
1420
  const ARTIFACT_APP_ENV = ["ARTIFACT_ID", "ARTIFACT_VERSION_ID", "ARTIFACT_MANIFEST_URI", "PLATFORM_ARTIFACT_ID", "PLATFORM_ARTIFACT_VERSION_ID", "PLATFORM_ARTIFACT_MANIFEST_URI"];
@@ -1058,7 +1448,7 @@ async function initWebAndApiArtifactApp(opts, input) {
1058
1448
  const page = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${safeTitle}</title></head><body><main data-platform-artifact-root><h1>${safeTitle}</h1><p id="message">Loading...</p></main><script type="module" src="./app.js"></script></body></html>`;
1059
1449
  const browserScript = `fetch("./_artifact/api/hello").then((response) => response.json()).then((body) => { document.getElementById("message").textContent = body.message; }).catch(() => { document.getElementById("message").textContent = "The API is not reachable yet."; });\n`;
1060
1450
  const webBuild = `import { mkdirSync, writeFileSync } from "node:fs";\n\n// Asset URLs stay relative so the same files work on the draft, live, and version addresses.\nmkdirSync("dist", { recursive: true });\nwriteFileSync("dist/index.html", ${JSON.stringify(page)}, "utf8");\nwriteFileSync("dist/app.js", ${JSON.stringify(browserScript)}, "utf8");\nconsole.log("web build ok");\n`;
1061
- const apiSource = `export function artifactApp(req, res) {\n const url = new URL(req.url ?? "/", "http://artifact.local");\n res.setHeader("content-type", "application/json; charset=utf-8");\n if (url.pathname.endsWith("/_artifact/api/health")) {\n res.end(JSON.stringify({ ok: true, part: process.env.PLATFORM_ARTIFACT_PART ?? null }));\n return;\n }\n if (url.pathname.endsWith("/_artifact/api/hello")) {\n res.end(JSON.stringify({ ok: true, message: "Hello from the api part. Replace this endpoint with your API." }));\n return;\n }\n res.statusCode = 404;\n res.end(JSON.stringify({ error: "not_found" }));\n}\n\nif (process.argv.includes("--test") && process.argv.includes("--artifact-tests-json")) {\n console.log(JSON.stringify({ tests: [{ description: "The api part answers its hello route.", required: true, status: "passed", summary: "artifactApp handles /_artifact/api/hello." }] }));\n} else if (process.argv.includes("--test")) {\n console.log("api part ok");\n}\n`;
1451
+ const apiSource = `export function artifactApp(req, res) {\n const url = new URL(req.url ?? "/", "http://artifact.local");\n res.setHeader("content-type", "application/json; charset=utf-8");\n if (url.pathname.endsWith("/_artifact/api/health")) {\n res.end(JSON.stringify({ ok: true, part: process.env.PLATFORM_ARTIFACT_PART ?? null }));\n return;\n }\n if (url.pathname.endsWith("/_artifact/api/hello")) {\n res.end(JSON.stringify({ ok: true, message: "Hello from the api part. Replace this endpoint with your API." }));\n return;\n }\n res.statusCode = 404;\n res.end(JSON.stringify({ error: "not_found" }));\n}\n\nif (process.argv.includes("--test") && process.argv.includes("--artifact-tests-json")) {\n console.log(JSON.stringify({ tests: [{ description: "Scaffold check: the api part answers its hello route.", required: true, status: "passed", summary: "Generated starter check; not proof of implemented behavior.", evidence: { scaffold: true } }] }));\n} else if (process.argv.includes("--test")) {\n console.log("api part ok");\n}\n`;
1062
1452
  const files = [
1063
1453
  ["artifact-app.json", `${JSON.stringify(manifest, null, 2)}\n`],
1064
1454
  ["web/package.json", `${JSON.stringify(webPackage, null, 2)}\n`],
@@ -1472,6 +1862,19 @@ const BUILD_MCP_TOOLS = [
1472
1862
  required: ["ok", "verified", "product", "verifiedAt"]
1473
1863
  }
1474
1864
  },
1865
+ {
1866
+ name: "platform_sign_in",
1867
+ description: "Start a fresh Topline browser sign-in. Use it when the person asks to sign in to Topline again, or Topline keeps refusing this computer's sign-in. Returns at once: tell the person a sign-in page opened and ask them to sign in and choose Allow; if no page opened, give them signInUrl. The saved sign-in is replaced only after Allow, and the Topline tools reload then. Not available with a manual token.",
1868
+ annotations: mcpToolAnnotations("platform_sign_in", { readOnly: false, idempotent: true, openWorld: true }),
1869
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
1870
+ outputSchema: {
1871
+ type: "object",
1872
+ properties: {
1873
+ ok: { type: "boolean" }, status: { type: "string", enum: ["sign_in_started"] }, message: { type: "string" }, signInUrl: { type: "string" }
1874
+ },
1875
+ required: ["ok", "status", "message"]
1876
+ }
1877
+ },
1475
1878
  {
1476
1879
  name: "platform_init_artifact_app",
1477
1880
  description: "Create a minimal, validated artifact app starter inside the configured local workspace.",
@@ -1486,6 +1889,11 @@ const BUILD_MCP_TOOLS = [
1486
1889
  type: "string",
1487
1890
  enum: ["single", "web-and-api"],
1488
1891
  description: "single (default): one app. web-and-api: one artifact with a static website part and an API part under one address; use it instead of two artifacts."
1892
+ },
1893
+ starter: {
1894
+ type: "string",
1895
+ enum: ARTIFACT_STARTER_IDS,
1896
+ description: "Optional Build cookbook example to start from (single shape only). Scaffolds the recipe's page and private routes with placeholder answers and scaffold-labelled checks, and returns the recipe to follow. Datasets, source bindings and secrets are left for you to add from your own data."
1489
1897
  }
1490
1898
  },
1491
1899
  required: ["appDir"],
@@ -1493,7 +1901,16 @@ const BUILD_MCP_TOOLS = [
1493
1901
  },
1494
1902
  outputSchema: {
1495
1903
  type: "object",
1496
- properties: { ok: { type: "boolean" }, appDir: { type: "string" }, manifestId: { type: "string" }, title: { type: "string" }, files: { type: "array", items: { type: "string" } }, nextAction: { type: "string" } },
1904
+ properties: {
1905
+ ok: { type: "boolean" }, appDir: { type: "string" }, manifestId: { type: "string" }, title: { type: "string" }, files: { type: "array", items: { type: "string" } },
1906
+ starter: { type: "string" },
1907
+ recipe: {
1908
+ type: "object",
1909
+ properties: { example: { type: "string" }, summary: { type: "string" }, docsId: { type: "string" }, pluginPath: { type: "string" }, nextSteps: { type: "array", items: { type: "string" } } },
1910
+ required: ["example", "summary", "docsId", "pluginPath", "nextSteps"]
1911
+ },
1912
+ nextAction: { type: "string" }
1913
+ },
1497
1914
  required: ["ok", "appDir", "manifestId", "title", "files", "nextAction"]
1498
1915
  }
1499
1916
  },
@@ -1609,7 +2026,7 @@ const BUILD_MCP_TOOLS = [
1609
2026
  },
1610
2027
  {
1611
2028
  name: "platform_read_artifact_logs",
1612
- description: "Read bounded, redacted deployment logs for a hosted artifact app.",
2029
+ description: "Read bounded, redacted deployment logs for a hosted artifact app. Pass target \"sandbox\" with sessionId and sandboxId to read your own running dev sandbox's logs instead.",
1613
2030
  annotations: mcpToolAnnotations("platform_read_artifact_logs", { readOnly: true, openWorld: true }),
1614
2031
  inputSchema: {
1615
2032
  type: "object",
@@ -1617,6 +2034,9 @@ const BUILD_MCP_TOOLS = [
1617
2034
  artifactId: { type: "string", format: "uuid" },
1618
2035
  deploymentRecordId: { type: "string", format: "uuid" },
1619
2036
  environment: { type: "string", enum: ["draft", "live"] },
2037
+ target: { type: "string", enum: ["draft", "live", "sandbox"] },
2038
+ sessionId: { type: "string", format: "uuid" },
2039
+ sandboxId: { type: "string", format: "uuid" },
1620
2040
  limit: { type: "integer", minimum: 1, maximum: 200 },
1621
2041
  severity: { type: "string" },
1622
2042
  contains: { type: "string" },
@@ -1764,9 +2184,9 @@ const BUILD_MCP_TOOLS = [
1764
2184
  },
1765
2185
  {
1766
2186
  name: "platform_run_artifact_smoke",
1767
- description: "Rerun the trusted draft smoke check and return fresh rendered-page evidence. While you hold an open build session on the app, pass its sessionId.",
2187
+ description: "Rerun the trusted draft smoke check and return fresh rendered-page evidence. While you hold an open build session on the app, pass its sessionId. Pass target \"sandbox\" with sessionId and sandboxId to smoke your own running dev sandbox instead (advisory only).",
1768
2188
  annotations: mcpToolAnnotations("platform_run_artifact_smoke", { readOnly: false, openWorld: true }),
1769
- inputSchema: { type: "object", properties: { artifactId: { type: "string", format: "uuid" }, deploymentRecordId: { type: "string", format: "uuid" }, sessionId: { type: "string", format: "uuid" } }, required: ["artifactId"], additionalProperties: false },
2189
+ inputSchema: { type: "object", properties: { artifactId: { type: "string", format: "uuid" }, deploymentRecordId: { type: "string", format: "uuid" }, sessionId: { type: "string", format: "uuid" }, target: { type: "string", enum: ["draft", "sandbox"] }, sandboxId: { type: "string", format: "uuid" } }, required: ["artifactId"], additionalProperties: false },
1770
2190
  outputSchema: { type: "object", properties: { ok: { type: "boolean" }, phase: { type: "string" }, artifactId: { type: "string" }, deploymentRecordId: { type: "string" }, smoke: { type: "object" }, validation: { type: "object" } }, required: ["ok", "phase", "artifactId", "deploymentRecordId", "smoke", "validation"] }
1771
2191
  },
1772
2192
  {
@@ -1879,6 +2299,7 @@ function withRecoveryOutputSchema(value) {
1879
2299
  message: { type: "string" },
1880
2300
  retryable: { type: "boolean" },
1881
2301
  recoveryAction: { type: "string" },
2302
+ signInUrl: { type: "string" },
1882
2303
  ...(DOMAIN_FORWARD_TOOLS.has(tool.name) ? { recovery: { type: "object", additionalProperties: true } } : {})
1883
2304
  },
1884
2305
  required: ["code", "message", "retryable", "recoveryAction"],
@@ -1922,7 +2343,12 @@ const BUILD_MCP_RECOVERY_ERROR_VALUES = {
1922
2343
  recoveryAction: "Read current domain/address state and the original receipt with the saved pre-call key. Retain the exact original input. Review changed state, scopes or configuration before any new plan/key; never assume a rejected delivery means no effect." }])),
1923
2344
  domain_result_unknown: { retryable: false, recoveryAction: "The response did not establish an outcome. Recover the original receipt through platform_get_artifact_address (saved artifactId and apply key) or platform_read_artifact_domains (request/verify kind and key). Preserve the original plan/domain/input/key; an absent, pending or expired receipt does not authorize a fresh key. No mutation is replayed automatically." },
1924
2345
  build_session_tool_unavailable: { retryable: false, recoveryAction: "The connection's hosted Build tool list does not offer this build session tool, so the package does not list or run it. Call platform_capability_status to see what is missing, such as a scope or capability, and reconnect through browser sign-in with any missing scope. The package asks the host to list tools again, so the tool comes back once Topline offers it." },
1925
- authorization_required: { retryable: false, recoveryAction: "Clear only this connection's cached OAuth credentials, then reconnect the Build MCP through browser sign-in. If using a manual bearer token, replace the expired or revoked token. Recover existing artifact/deployment progress before retrying a write." },
2346
+ authorization_required: { retryable: false, recoveryAction: "Call platform_sign_in to start a fresh browser sign-in, and ask the person to choose Allow. If using a manual bearer token, replace the expired or revoked token instead. Recover existing artifact/deployment progress before retrying a write." },
2347
+ manual_token_sign_in_unavailable: { retryable: false, recoveryAction: "This connection uses a manual bearer token, which only its owner can replace. Ask the person to replace the token in their MCP configuration." },
2348
+ sign_in_unavailable_on_harness_surface: { retryable: false, recoveryAction: "The harness surface signs in with a token, not a browser. Ask the person to check this connection's token." },
2349
+ sign_in_required: { retryable: false, recoveryAction: "Tell the person a Topline sign-in page is open in their browser, and ask them to sign in and choose Allow. If no page opened, give them signInUrl to open when it is present. Do not retry on your own: wait for the person to choose Allow, then call again. Recover existing artifact/deployment progress before retrying a write." },
2350
+ sign_in_renewed: { retryable: true, recoveryAction: "The sign-in is already renewed, so call this tool again; the refused call was not replayed. Recover existing artifact/deployment progress before retrying a write." },
2351
+ sign_in_unavailable: { retryable: true, recoveryAction: "Topline did not answer the sign-in request. Wait briefly, then call platform_sign_in again." },
1926
2352
  platform_harness_timeout: { retryable: true, recoveryAction: "Retry the call. For a deployment, use platform_list_artifact_drafts to recover the artifact and platform_wait_artifact_deploy to resume progress." },
1927
2353
  platform_mcp_tool_error: { retryable: false, recoveryAction: "Topline refused the call without a code. Read the message, correct the request, then retry. Reconnect only when the message names a missing scope." },
1928
2354
  build_session_id_required: { retryable: false, recoveryAction: "The fields named after the code only work inside a build session. Remove them for a plain deploy of an app you created over MCP, or start a session and pass its sessionId." },
@@ -1936,12 +2362,23 @@ const BUILD_MCP_RECOVERY_ERROR_VALUES = {
1936
2362
  artifact_app_manifest_too_large: { retryable: false, recoveryAction: "Keep artifact-app.json below 512 KiB. Move application data and source into separate files, then inspect again." },
1937
2363
  scope_required: { retryable: false, recoveryAction: "Reconnect the Build MCP and approve the requested scope." },
1938
2364
  artifact_app_scaffold_target_not_empty: { retryable: false, recoveryAction: "Choose an empty appDir or deploy the existing app without scaffolding." },
1939
- artifact_app_scaffold_shape_invalid: { retryable: false, recoveryAction: "Use shape single or web-and-api." }
2365
+ artifact_app_scaffold_shape_invalid: { retryable: false, recoveryAction: "Use shape single or web-and-api." },
2366
+ artifact_app_scaffold_starter_invalid: { retryable: false, recoveryAction: `Use one of the starters: ${ARTIFACT_STARTER_IDS.join(", ")}.` },
2367
+ artifact_app_scaffold_starter_shape_conflict: { retryable: false, recoveryAction: "A starter scaffolds the single shape; leave shape out or set it to single." },
2368
+ // Stale preconditions: the same input can never succeed, whatever HTTP status an older Topline sends.
2369
+ artifact_version_conflict: { retryable: false, recoveryAction: "The session moved to a newer version. Read the session (platform_read_build_session), keep your local edits, run platform_inspect_artifact_app again, then deploy with the current artifactVersionId and the new inspectedSourceHash." },
2370
+ artifact_source_conflict: { retryable: false, recoveryAction: "inspectedSourceHash no longer matches the session's source fence. Read the session for its current sourceHash (or check out again into a new directory), keep your local edits, inspect again, then deploy with the fresh hash." },
2371
+ artifact_operation_pending: { retryable: false, recoveryAction: "Another operation on this app has not settled. Read it with platform_deploy_operation (a deploy that already landed settles on that read), or platform_read_build_session, then call this tool again once it is terminal." },
2372
+ artifact_deploy_in_flight: { retryable: true, recoveryAction: "A deploy for this app is still running. Wait until platform_deploy_operation says it is terminal, then retry the call that was refused (checkout, delete or deploy)." },
2373
+ artifact_logs_deployment_not_found: { retryable: false, recoveryAction: "There is no deployment to read runtime logs from yet. For a failed build, read platform_deploy_operation: its failure field carries the build error." }
1940
2374
  };
1941
2375
  export const BUILD_MCP_RECOVERY_ERRORS = Object.freeze(Object.fromEntries(Object.entries(BUILD_MCP_RECOVERY_ERROR_VALUES).map(([code, guidance]) => [code, Object.freeze(guidance)])));
1942
- function structuredToolError(message) {
2376
+ export function structuredToolError(message) {
1943
2377
  const code = recoveryErrorCode(message);
1944
- const selected = BUILD_MCP_RECOVERY_ERRORS[code] ?? { retryable: /^platform_harness_http_error:5|timeout|rate_limited/.test(message), recoveryAction: "Inspect the code and message, correct the input if needed, then retry the same tool." };
2378
+ // A 4xx means the same request will be refused again; only 5xx, timeouts and rate limits are worth retrying unchanged.
2379
+ const selected = BUILD_MCP_RECOVERY_ERRORS[code] ?? { retryable: /^platform_harness_http_error:5|timeout|rate_limited/.test(message), recoveryAction: /^platform_harness_http_error:4/.test(message)
2380
+ ? "Topline refused this request as sent. Read the code, correct the input or state it names, then call the tool again; the same input fails the same way."
2381
+ : "Inspect the code and message, correct the input if needed, then retry the same tool." };
1945
2382
  const structuredContent = { ok: false, error: { code, message, ...selected } };
1946
2383
  return {
1947
2384
  content: [{ type: "text", text: JSON.stringify(structuredContent, null, 2) }],
@@ -1977,11 +2414,30 @@ function recoveryErrorCode(message) {
1977
2414
  }
1978
2415
  if (DOMAIN_ERROR_CODES.has(message) || message === "domain_result_unknown")
1979
2416
  return message;
2417
+ // Topline's HTTP error body names its code (`{"ok":false,"error":"artifact_version_conflict"}`); use it.
2418
+ const http = /^platform_harness_http_error:(\d{3}):(.*)$/s.exec(message);
2419
+ if (http) {
2420
+ let inner = hostedToolErrorCode(http[2].trim());
2421
+ if (!inner) {
2422
+ // An error string can carry a suffix (`artifact_logs_deployment_not_found:draft`).
2423
+ try {
2424
+ const body = JSON.parse(http[2]);
2425
+ inner = typeof body.error === "string" ? body.error.match(/^([a-z][a-z0-9_]{2,})(?::|$)/)?.[1] ?? null : null;
2426
+ }
2427
+ catch {
2428
+ inner = null;
2429
+ }
2430
+ }
2431
+ if (inner && BUILD_MCP_RECOVERY_ERRORS[inner])
2432
+ return inner;
2433
+ }
1980
2434
  const known = [
1981
2435
  "artifact_delete_plan_stale",
1982
2436
  "artifact_deploy_wait_timeout",
1983
2437
  "artifact_app_scaffold_target_not_empty",
1984
2438
  "artifact_app_scaffold_shape_invalid",
2439
+ "artifact_app_scaffold_starter_invalid",
2440
+ "artifact_app_scaffold_starter_shape_conflict",
1985
2441
  "platform_harness_timeout",
1986
2442
  // Before the generic wrapper, which every hosted error message starts with.
1987
2443
  "scope_required",
@@ -2028,12 +2484,16 @@ export async function getBearerToken(opts) {
2028
2484
  [...opts.oauthScopes].sort().join(" ")
2029
2485
  ].join("\0");
2030
2486
  const existing = inFlightBearerTokenRequests.get(key);
2031
- if (existing)
2032
- return existing;
2033
- const pending = getOAuthBearerToken(opts);
2034
- inFlightBearerTokenRequests.set(key, pending);
2487
+ const pending = existing ?? getOAuthBearerToken(opts);
2488
+ if (!existing)
2489
+ inFlightBearerTokenRequests.set(key, pending);
2035
2490
  try {
2036
- return await pending;
2491
+ const bearer = await pending;
2492
+ // Remembered for this tool call, so a refusal can tell whether the sign-in changed since.
2493
+ const usage = signInUsage.getStore();
2494
+ if (usage)
2495
+ usage.bearer = bearer;
2496
+ return bearer;
2037
2497
  }
2038
2498
  finally {
2039
2499
  if (inFlightBearerTokenRequests.get(key) === pending)
@@ -2063,7 +2523,21 @@ async function refreshStoredOAuthToken(opts, stored) {
2063
2523
  if (existing)
2064
2524
  return existing;
2065
2525
  const pending = (async () => {
2066
- const refreshed = await refreshOAuthToken(opts, stored);
2526
+ let refreshed;
2527
+ try {
2528
+ refreshed = await refreshOAuthToken(opts, stored);
2529
+ }
2530
+ catch (err) {
2531
+ // Another server process may have rotated this refresh token a moment
2532
+ // ago; its new sign-in is then in the auth file, not refused.
2533
+ if (!isRefreshTokenRejected(err))
2534
+ throw err;
2535
+ const current = await readStoredOAuthCredentials(opts).catch(() => null);
2536
+ if (current?.refreshToken && current.refreshToken !== stored.refreshToken && current.accessToken
2537
+ && Date.parse(current.accessTokenExpiresAt ?? "") - Date.now() > 60_000)
2538
+ return current;
2539
+ throw err;
2540
+ }
2067
2541
  await writeStoredOAuthCredentials(opts, refreshed);
2068
2542
  return refreshed;
2069
2543
  })();
@@ -2152,6 +2626,7 @@ async function runOAuthLogin(opts) {
2152
2626
  const codePromise = callback.waitForCode(state);
2153
2627
  // A denial can land while the browser is still opening; it is reported below.
2154
2628
  codePromise.catch(() => undefined);
2629
+ signInUrls.set(path.resolve(opts.authFile), authUrl.toString());
2155
2630
  await openBrowser(opts, authUrl.toString());
2156
2631
  const code = await codePromise;
2157
2632
  const token = await oauthFetchJson(opts, `${issuer}/oauth/token`, {
@@ -2169,6 +2644,7 @@ async function runOAuthLogin(opts) {
2169
2644
  return credentialsFromTokenResponse(issuer, resource, clientId, opts.oauthScopes, token);
2170
2645
  }
2171
2646
  finally {
2647
+ signInUrls.delete(path.resolve(opts.authFile));
2172
2648
  await callback.close();
2173
2649
  }
2174
2650
  }
@@ -2211,6 +2687,7 @@ function credentialsFromTokenResponse(issuer, resource, clientId, requestedScope
2211
2687
  accessToken,
2212
2688
  accessTokenExpiresAt: new Date(Date.now() + Math.max(60, Math.floor(expiresIn)) * 1000).toISOString(),
2213
2689
  refreshToken,
2690
+ obtainedAt: new Date().toISOString(),
2214
2691
  scopes: scopeText.split(/[\s,]+/).filter(Boolean)
2215
2692
  };
2216
2693
  }
@@ -2239,6 +2716,7 @@ async function readStoredOAuthCredentials(opts) {
2239
2716
  accessToken: typeof parsed.accessToken === "string" ? parsed.accessToken : undefined,
2240
2717
  accessTokenExpiresAt: typeof parsed.accessTokenExpiresAt === "string" ? parsed.accessTokenExpiresAt : undefined,
2241
2718
  refreshToken: typeof parsed.refreshToken === "string" ? parsed.refreshToken : undefined,
2719
+ ...(typeof parsed.obtainedAt === "string" ? { obtainedAt: parsed.obtainedAt } : {}),
2242
2720
  scopes
2243
2721
  };
2244
2722
  }
@@ -2246,9 +2724,36 @@ async function readStoredOAuthCredentials(opts) {
2246
2724
  return null;
2247
2725
  }
2248
2726
  }
2727
+ /**
2728
+ * Replace the auth file in one step (a temporary file in the same directory,
2729
+ * then a rename), so another process never reads a half-written sign-in.
2730
+ */
2249
2731
  async function writeStoredOAuthCredentials(opts, credentials) {
2250
2732
  await mkdir(path.dirname(opts.authFile), { recursive: true });
2251
- await writeFile(opts.authFile, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 0o600 });
2733
+ const temp = `${opts.authFile}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
2734
+ try {
2735
+ await writeFile(temp, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 0o600, flag: "wx" });
2736
+ // Windows refuses the rename for a moment while another process reads the
2737
+ // file: retry for about 1.5 s, then write in place so a finished Allow is never lost.
2738
+ for (const delay of [25, 50, 100, 200, 400, 700, -1]) {
2739
+ try {
2740
+ await rename(temp, opts.authFile);
2741
+ return;
2742
+ }
2743
+ catch (err) {
2744
+ const code = err.code;
2745
+ if (code !== "EPERM" && code !== "EACCES" && code !== "EBUSY")
2746
+ throw err;
2747
+ if (delay < 0)
2748
+ break;
2749
+ await new Promise((resolve) => setTimeout(resolve, delay));
2750
+ }
2751
+ }
2752
+ await writeFile(opts.authFile, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 0o600 });
2753
+ }
2754
+ finally {
2755
+ await rm(temp, { force: true }).catch(() => undefined);
2756
+ }
2252
2757
  }
2253
2758
  async function startOAuthCallbackServer() {
2254
2759
  let resolveCode = null;