@topline-build/harness-mcp 0.9.1 → 0.9.3
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/CHANGELOG.md +23 -1
- package/README.md +7 -5
- package/dist/index.d.ts +12 -1
- package/dist/index.js +594 -28
- package/docs/generated/build-mcp-manifest.json +303 -6
- package/docs/generated/build-mcp-reference.md +282 -5
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
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";
|
|
@@ -17,7 +18,7 @@ const MCP_SURFACES = ["build", "topline", "harness"];
|
|
|
17
18
|
export const DEFAULT_MCP_PROTOCOL_VERSION = "2025-11-25";
|
|
18
19
|
const DEFAULT_TIMEOUT_MS = 120_000;
|
|
19
20
|
export const BUILD_MCP_SERVER_NAME = "topline-build-stdio";
|
|
20
|
-
export const HARNESS_MCP_VERSION = "0.9.
|
|
21
|
+
export const HARNESS_MCP_VERSION = "0.9.3";
|
|
21
22
|
export const DEFAULT_OAUTH_SCOPES = Object.freeze(["harness:artifact:read", "harness:artifact:write", "harness:artifact:deploy", "harness:artifact:delete"]);
|
|
22
23
|
/** The Topline server's scopes: Build and Workspace. Consent shows what the seat allows. */
|
|
23
24
|
export const TOPLINE_OAUTH_SCOPES = Object.freeze([
|
|
@@ -116,7 +117,452 @@ export async function runHarnessMcpStdioCli() {
|
|
|
116
117
|
}
|
|
117
118
|
const opts = parseHarnessOptions(argv);
|
|
118
119
|
const mcp = createHarnessMcpStdioServer(opts);
|
|
120
|
+
// A browser sign-in holds a callback server and a 5-minute timer; once the
|
|
121
|
+
// host closes the connection nothing will use it, so do not linger.
|
|
122
|
+
mcp.onclose = () => { if (inFlightSignIns.size > 0)
|
|
123
|
+
process.exit(0); };
|
|
119
124
|
await mcp.connect(new StdioServerTransport());
|
|
125
|
+
void signInAtStartup(opts, () => mcp.sendToolListChanged());
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* The one Topline server lists most of its tools only once signed in, so a
|
|
129
|
+
* first chat that starts signed out would see almost nothing. Start the browser
|
|
130
|
+
* sign-in as soon as the server is up instead, and tell the host to list tools
|
|
131
|
+
* again after Allow. Returns whether it signed in. Never throws: a sign-in that
|
|
132
|
+
* is ignored or refused leaves the on-demand sign-in of the first tool call.
|
|
133
|
+
*/
|
|
134
|
+
export async function signInAtStartup(opts, onSignedIn, log = (message) => process.stderr.write(`${message}\n`)) {
|
|
135
|
+
if (opts.token || mcpSurface(opts) !== "topline")
|
|
136
|
+
return false;
|
|
137
|
+
try {
|
|
138
|
+
const stored = await readStoredOAuthCredentials(opts);
|
|
139
|
+
if (stored?.accessToken && Date.parse(stored.accessTokenExpiresAt ?? "") > Date.now())
|
|
140
|
+
return false;
|
|
141
|
+
if (stored?.refreshToken) {
|
|
142
|
+
// An expired access token: refresh it now, so a saved sign-in Topline
|
|
143
|
+
// has since refused opens the browser here instead of failing a tool call.
|
|
144
|
+
try {
|
|
145
|
+
if (await getBearerTokenWithoutSignIn(opts))
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
catch (err) {
|
|
149
|
+
if (!isSignInRejected(err))
|
|
150
|
+
return false;
|
|
151
|
+
log("Your saved Topline sign-in has expired.");
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
// Hosts often start one server per window or session; only one of them opens the browser.
|
|
155
|
+
if (!(await takeSignInLock(opts.authFile))) {
|
|
156
|
+
// Another window is signing in: list tools again here once it lands.
|
|
157
|
+
watchForSignIn(opts, onSignedIn, stored);
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
|
+
try {
|
|
161
|
+
log(`Opening your browser to sign in to Topline at ${platformBaseUrl(opts)}. Choose Allow to load the Topline tools.`);
|
|
162
|
+
await interactiveSignIn({
|
|
163
|
+
...opts,
|
|
164
|
+
quietOpenFailure: true,
|
|
165
|
+
openUrl: async (url) => {
|
|
166
|
+
await shareSignInUrl(opts.authFile, url);
|
|
167
|
+
// Printed every time: with no browser (SSH, a container) this is the only way to finish.
|
|
168
|
+
log(`If it does not open, visit this address:\n${url}`);
|
|
169
|
+
await (opts.openUrl ? opts.openUrl(url) : openBrowser({ ...opts, openUrl: undefined, quietOpenFailure: true }, url));
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
finally {
|
|
174
|
+
await releaseSignInLock(opts.authFile);
|
|
175
|
+
}
|
|
176
|
+
await onSignedIn().catch(() => undefined);
|
|
177
|
+
return true;
|
|
178
|
+
}
|
|
179
|
+
catch (err) {
|
|
180
|
+
log(`Topline sign-in did not finish (${err instanceof Error ? err.message : "unknown error"}). The first Topline tool will ask again.`);
|
|
181
|
+
return false;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
// How long a browser sign-in waits for Allow (the callback server's timeout).
|
|
185
|
+
const SIGN_IN_WINDOW_MS = 5 * 60 * 1000;
|
|
186
|
+
const SIGN_IN_WATCH_INTERVAL_MS = 500;
|
|
187
|
+
function signInLockFile(authFile) {
|
|
188
|
+
return `${path.resolve(authFile)}.signin-lock`;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* True when this process may run the browser sign-in for this auth file.
|
|
192
|
+
* Hosts start one server per window or session, and every one of them can be
|
|
193
|
+
* refused at once; the lock keeps that to one browser tab. A lock younger than
|
|
194
|
+
* the sign-in window means another process is running it.
|
|
195
|
+
*/
|
|
196
|
+
async function takeSignInLock(authFile) {
|
|
197
|
+
const lock = signInLockFile(authFile);
|
|
198
|
+
await mkdir(path.dirname(lock), { recursive: true });
|
|
199
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
200
|
+
try {
|
|
201
|
+
await writeFile(lock, `${JSON.stringify({ pid: process.pid })}\n`, { flag: "wx", mode: 0o600 });
|
|
202
|
+
heldSignInLocks.add(lock);
|
|
203
|
+
releaseSignInLocksOnExit();
|
|
204
|
+
return true;
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
const owner = await readSignInLock(lock);
|
|
208
|
+
// An owner that died (crash, closed window) cannot finish its sign-in; its lock is stale at once.
|
|
209
|
+
const ownerGone = owner?.pid !== undefined && owner.pid !== process.pid && !processAlive(owner.pid);
|
|
210
|
+
const age = Date.now() - ((await lstat(lock).catch(() => null))?.mtimeMs ?? 0);
|
|
211
|
+
if (!ownerGone && age < SIGN_IN_WINDOW_MS + 60 * 1000)
|
|
212
|
+
return false;
|
|
213
|
+
await rm(lock, { force: true }).catch(() => undefined);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return false;
|
|
217
|
+
}
|
|
218
|
+
/** The lock's owner and shared address. 0.9.2 wrote a bare pid. */
|
|
219
|
+
async function readSignInLock(lock) {
|
|
220
|
+
let text;
|
|
221
|
+
try {
|
|
222
|
+
text = await readFile(lock, "utf8");
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
return parseSignInLock(text);
|
|
228
|
+
}
|
|
229
|
+
function parseSignInLock(text) {
|
|
230
|
+
try {
|
|
231
|
+
const parsed = JSON.parse(text);
|
|
232
|
+
if (isRecord(parsed)) {
|
|
233
|
+
return {
|
|
234
|
+
...(Number.isInteger(parsed.pid) && parsed.pid > 0 ? { pid: parsed.pid } : {}),
|
|
235
|
+
...(typeof parsed.signInUrl === "string" ? { signInUrl: parsed.signInUrl } : {})
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
if (Number.isInteger(parsed) && parsed > 0)
|
|
239
|
+
return { pid: parsed };
|
|
240
|
+
}
|
|
241
|
+
catch {
|
|
242
|
+
// Not JSON.
|
|
243
|
+
}
|
|
244
|
+
return {};
|
|
245
|
+
}
|
|
246
|
+
/** False only when the process is known to be gone; EPERM means it exists under another user. */
|
|
247
|
+
function processAlive(pid) {
|
|
248
|
+
try {
|
|
249
|
+
process.kill(pid, 0);
|
|
250
|
+
return true;
|
|
251
|
+
}
|
|
252
|
+
catch (err) {
|
|
253
|
+
return err.code !== "ESRCH";
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
// Locks this process took, removed on exit so a closed window does not block the others.
|
|
257
|
+
const heldSignInLocks = new Set();
|
|
258
|
+
let releasesOnExit = false;
|
|
259
|
+
function releaseSignInLocksOnExit() {
|
|
260
|
+
if (releasesOnExit)
|
|
261
|
+
return;
|
|
262
|
+
releasesOnExit = true;
|
|
263
|
+
process.once("exit", () => {
|
|
264
|
+
for (const lock of heldSignInLocks) {
|
|
265
|
+
try {
|
|
266
|
+
if (parseSignInLock(readFileSync(lock, "utf8")).pid === process.pid)
|
|
267
|
+
rmSync(lock, { force: true });
|
|
268
|
+
}
|
|
269
|
+
catch {
|
|
270
|
+
// Already gone.
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
async function ownsSignInLock(lock) {
|
|
276
|
+
return (await readSignInLock(lock))?.pid === process.pid;
|
|
277
|
+
}
|
|
278
|
+
async function releaseSignInLock(authFile) {
|
|
279
|
+
const lock = signInLockFile(authFile);
|
|
280
|
+
heldSignInLocks.delete(lock);
|
|
281
|
+
if (await ownsSignInLock(lock))
|
|
282
|
+
await rm(lock, { force: true }).catch(() => undefined);
|
|
283
|
+
}
|
|
284
|
+
/** Put the authorize address in the lock, so other processes can hand the person the same tab. */
|
|
285
|
+
async function shareSignInUrl(authFile, signInUrl) {
|
|
286
|
+
const lock = signInLockFile(authFile);
|
|
287
|
+
if (!(await ownsSignInLock(lock)))
|
|
288
|
+
return;
|
|
289
|
+
await writeFile(lock, `${JSON.stringify({ pid: process.pid, signInUrl })}\n`, { mode: 0o600 }).catch(() => undefined);
|
|
290
|
+
}
|
|
291
|
+
/** 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. */
|
|
292
|
+
async function sharedSignInUrl(opts) {
|
|
293
|
+
const owner = await readSignInLock(signInLockFile(opts.authFile));
|
|
294
|
+
if (!owner?.signInUrl || owner.pid === undefined || !processAlive(owner.pid))
|
|
295
|
+
return null;
|
|
296
|
+
return shareableSignInUrl(opts, owner.signInUrl);
|
|
297
|
+
}
|
|
298
|
+
// What an authorize address may carry. Anything else, a verifier above all, is never shown.
|
|
299
|
+
const SHAREABLE_SIGN_IN_PARAMS = new Set(["response_type", "client_id", "redirect_uri", "scope", "resource", "code_challenge", "code_challenge_method", "state"]);
|
|
300
|
+
function shareableSignInUrl(opts, raw) {
|
|
301
|
+
let url;
|
|
302
|
+
try {
|
|
303
|
+
url = new URL(raw);
|
|
304
|
+
}
|
|
305
|
+
catch {
|
|
306
|
+
return null;
|
|
307
|
+
}
|
|
308
|
+
if (url.username || url.password || url.hash || `${url.origin}${url.pathname}` !== `${platformBaseUrl(opts)}/oauth/authorize`)
|
|
309
|
+
return null;
|
|
310
|
+
const keys = [...url.searchParams.keys()];
|
|
311
|
+
if (new Set(keys).size !== keys.length || keys.some((key) => !SHAREABLE_SIGN_IN_PARAMS.has(key)))
|
|
312
|
+
return null;
|
|
313
|
+
const param = (key) => url.searchParams.get(key) ?? "";
|
|
314
|
+
if (param("response_type") !== "code" || param("code_challenge_method") !== "S256")
|
|
315
|
+
return null;
|
|
316
|
+
if (!param("client_id") || !param("code_challenge") || !param("state"))
|
|
317
|
+
return null;
|
|
318
|
+
if (!/^http:\/\/127\.0\.0\.1:\d{1,5}\/callback$/.test(param("redirect_uri")))
|
|
319
|
+
return null;
|
|
320
|
+
return url.toString();
|
|
321
|
+
}
|
|
322
|
+
// Auth files this process is already watching for another process's sign-in.
|
|
323
|
+
const signInWatches = new Set();
|
|
324
|
+
function credentialsTag(stored) {
|
|
325
|
+
return stored ? JSON.stringify([stored.accessToken ?? null, stored.refreshToken ?? null]) : null;
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Another process runs the browser sign-in; poll the auth file (bounded by
|
|
329
|
+
* the sign-in window, never keeping the process alive) and list tools again
|
|
330
|
+
* once, when its new sign-in lands.
|
|
331
|
+
*/
|
|
332
|
+
function watchForSignIn(opts, onSignedIn, baseline) {
|
|
333
|
+
const key = path.resolve(opts.authFile);
|
|
334
|
+
if (signInWatches.has(key))
|
|
335
|
+
return;
|
|
336
|
+
signInWatches.add(key);
|
|
337
|
+
const tag = credentialsTag(baseline);
|
|
338
|
+
const deadline = Date.now() + SIGN_IN_WINDOW_MS;
|
|
339
|
+
let checking = false;
|
|
340
|
+
const stop = () => { clearInterval(timer); signInWatches.delete(key); };
|
|
341
|
+
const timer = setInterval(() => {
|
|
342
|
+
if (checking)
|
|
343
|
+
return;
|
|
344
|
+
if (Date.now() > deadline)
|
|
345
|
+
return stop();
|
|
346
|
+
checking = true;
|
|
347
|
+
void readStoredOAuthCredentials(opts).catch(() => null).then(async (current) => {
|
|
348
|
+
if (!current || credentialsTag(current) === tag)
|
|
349
|
+
return;
|
|
350
|
+
stop();
|
|
351
|
+
await onSignedIn().catch(() => undefined);
|
|
352
|
+
}).finally(() => { checking = false; });
|
|
353
|
+
}, SIGN_IN_WATCH_INTERVAL_MS);
|
|
354
|
+
timer.unref?.();
|
|
355
|
+
}
|
|
356
|
+
// One browser sign-in per auth file at a time: the startup sign-in and a tool
|
|
357
|
+
// call that needs a token share it instead of opening two approvals.
|
|
358
|
+
const inFlightSignIns = new Map();
|
|
359
|
+
async function interactiveSignIn(opts) {
|
|
360
|
+
const key = path.resolve(opts.authFile);
|
|
361
|
+
const pending = inFlightSignIns.get(key);
|
|
362
|
+
if (pending)
|
|
363
|
+
return pending;
|
|
364
|
+
const started = (async () => {
|
|
365
|
+
const credentials = await runOAuthLogin(opts);
|
|
366
|
+
await writeStoredOAuthCredentials(opts, credentials);
|
|
367
|
+
return credentials;
|
|
368
|
+
})();
|
|
369
|
+
inFlightSignIns.set(key, started);
|
|
370
|
+
try {
|
|
371
|
+
return await started;
|
|
372
|
+
}
|
|
373
|
+
finally {
|
|
374
|
+
inFlightSignIns.delete(key);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
// The address of the browser sign-in open for each auth file, so a tool call
|
|
378
|
+
// that joins it can still hand the person the link.
|
|
379
|
+
const signInUrls = new Map();
|
|
380
|
+
// When each auth file last finished a browser sign-in. A refusal right after
|
|
381
|
+
// one means Topline refuses the new sign-in too, so another browser tab would
|
|
382
|
+
// not help.
|
|
383
|
+
const lastSignIns = new Map();
|
|
384
|
+
const SIGN_IN_COOLDOWN_MS = 5 * 60 * 1000;
|
|
385
|
+
const signInUsage = new AsyncLocalStorage();
|
|
386
|
+
/** The auth file holds a different sign-in than the one the refused call used. */
|
|
387
|
+
function signInRenewedSince(usage, current) {
|
|
388
|
+
if (!current)
|
|
389
|
+
return false;
|
|
390
|
+
if (usage.bearer)
|
|
391
|
+
return current.accessToken !== usage.bearer && (Boolean(current.accessToken) || current.refreshToken !== usage.before?.refreshToken);
|
|
392
|
+
return usage.before !== null && credentialsTag(current) !== credentialsTag(usage.before);
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Topline refused this computer's saved sign-in (expired or revoked), so the
|
|
396
|
+
* person would otherwise have to clear it by hand. First rule out the cases
|
|
397
|
+
* where an Allow page would not help: another window (or a refresh) already
|
|
398
|
+
* renewed the sign-in, or one refresh of the saved sign-in works (a 401 for
|
|
399
|
+
* another reason, such as a gateway glitch); both return `sign_in_renewed`
|
|
400
|
+
* so the assistant calls again. Otherwise start the browser
|
|
401
|
+
* sign-in, without waiting for Allow, and return `sign_in_required` with the
|
|
402
|
+
* address so the assistant can ask the person to choose Allow and then call
|
|
403
|
+
* the tool again. The refused call is never replayed, and the saved sign-in is
|
|
404
|
+
* only replaced once the new one succeeds. A manual token, which only its
|
|
405
|
+
* owner can replace, keeps `authorization_required`.
|
|
406
|
+
*/
|
|
407
|
+
async function withSignInRecovery(opts, result, usage, onSignedIn) {
|
|
408
|
+
const error = isRecord(result.structuredContent) && isRecord(result.structuredContent.error) ? result.structuredContent.error : null;
|
|
409
|
+
if (error?.code !== "authorization_required" || opts.token || !servesBuild(opts))
|
|
410
|
+
return result;
|
|
411
|
+
let current = await readStoredOAuthCredentials(opts).catch(() => null);
|
|
412
|
+
if (signInRenewedSince(usage, current))
|
|
413
|
+
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.");
|
|
414
|
+
// Topline refused a token obtained moments ago: refreshing or signing in
|
|
415
|
+
// again would not help, and retrying would loop.
|
|
416
|
+
if (usage.bearer && current?.accessToken === usage.bearer && tokenIsFresh(current.obtainedAt))
|
|
417
|
+
return notASignInProblem(result);
|
|
418
|
+
const key = path.resolve(opts.authFile);
|
|
419
|
+
if (Date.now() - (lastSignIns.get(key) ?? 0) < SIGN_IN_COOLDOWN_MS)
|
|
420
|
+
return result;
|
|
421
|
+
if (current?.refreshToken && current.clientId) {
|
|
422
|
+
try {
|
|
423
|
+
await refreshStoredOAuthToken(opts, current);
|
|
424
|
+
// The saved sign-in still works once refreshed: no Allow page, just call again.
|
|
425
|
+
return signInErrorResult("sign_in_renewed", "Your Topline sign-in was renewed — try again.");
|
|
426
|
+
}
|
|
427
|
+
catch (err) {
|
|
428
|
+
// A temporary refresh failure says nothing about the sign-in; do not send the person to Allow.
|
|
429
|
+
if (!isSignInRejected(err))
|
|
430
|
+
return result;
|
|
431
|
+
}
|
|
432
|
+
current = await readStoredOAuthCredentials(opts).catch(() => null);
|
|
433
|
+
}
|
|
434
|
+
const started = await startBrowserSignIn(opts, onSignedIn, current);
|
|
435
|
+
// The sign-in could not even start (Topline unreachable): keep the original guidance.
|
|
436
|
+
if (started.kind === "failed")
|
|
437
|
+
return result;
|
|
438
|
+
if (started.kind === "renewed")
|
|
439
|
+
return signInErrorResult("sign_in_renewed", "Another Topline window finished a new sign-in just now. Nothing was replayed.");
|
|
440
|
+
return signInErrorResult("sign_in_required", started.kind === "elsewhere"
|
|
441
|
+
? "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."
|
|
442
|
+
: "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);
|
|
443
|
+
}
|
|
444
|
+
const FRESH_TOKEN_MS = 2 * 60 * 1000;
|
|
445
|
+
/** Obtained within the last 2 minutes. A time in the future (clock stepped back, bad value) is not fresh. */
|
|
446
|
+
function tokenIsFresh(obtainedAt) {
|
|
447
|
+
const age = Date.now() - Date.parse(obtainedAt ?? "");
|
|
448
|
+
return Number.isFinite(age) && age >= 0 && age < FRESH_TOKEN_MS;
|
|
449
|
+
}
|
|
450
|
+
function notASignInProblem(result) {
|
|
451
|
+
const content = result.structuredContent;
|
|
452
|
+
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." } };
|
|
453
|
+
return { ...result, content: [{ type: "text", text: JSON.stringify(structuredContent, null, 2) }], structuredContent };
|
|
454
|
+
}
|
|
455
|
+
function signInErrorResult(code, message, signInUrl, recovery) {
|
|
456
|
+
const structuredContent = {
|
|
457
|
+
ok: false,
|
|
458
|
+
error: {
|
|
459
|
+
code,
|
|
460
|
+
message,
|
|
461
|
+
...BUILD_MCP_RECOVERY_ERRORS[code],
|
|
462
|
+
...(signInUrl ? { signInUrl } : {}),
|
|
463
|
+
...(recovery !== undefined ? { recovery } : {})
|
|
464
|
+
}
|
|
465
|
+
};
|
|
466
|
+
return {
|
|
467
|
+
content: [
|
|
468
|
+
{ type: "text", text: JSON.stringify(structuredContent, null, 2) },
|
|
469
|
+
...(signInUrl ? [{ type: "resource_link", uri: signInUrl, name: "Sign in to Topline" }] : [])
|
|
470
|
+
],
|
|
471
|
+
structuredContent,
|
|
472
|
+
isError: true
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
// Serializes the decision to start a sign-in within this process, so two
|
|
476
|
+
// refused calls at once join one sign-in instead of racing for the lock.
|
|
477
|
+
const signInStarts = new Map();
|
|
478
|
+
/**
|
|
479
|
+
* Start (or join) the browser sign-in for this auth file without waiting for
|
|
480
|
+
* Allow. Only the process holding the cross-process sign-in lock opens a tab;
|
|
481
|
+
* the others watch the auth file and list tools again once it changes. With
|
|
482
|
+
* `expected`, the sign-in the caller saw, a newer one found after taking the
|
|
483
|
+
* lock is used instead of opening a tab.
|
|
484
|
+
*/
|
|
485
|
+
async function startBrowserSignIn(opts, onSignedIn, expected) {
|
|
486
|
+
const key = path.resolve(opts.authFile);
|
|
487
|
+
const known = signInUrls.get(key);
|
|
488
|
+
if (known)
|
|
489
|
+
return { kind: "started", signInUrl: known };
|
|
490
|
+
while (signInStarts.has(key))
|
|
491
|
+
await signInStarts.get(key);
|
|
492
|
+
let decided;
|
|
493
|
+
signInStarts.set(key, new Promise((resolve) => { decided = resolve; }));
|
|
494
|
+
let opened = () => undefined;
|
|
495
|
+
const address = new Promise((resolve) => { opened = resolve; });
|
|
496
|
+
let failed = false;
|
|
497
|
+
try {
|
|
498
|
+
const runsOwnSignIn = !inFlightSignIns.has(key);
|
|
499
|
+
if (runsOwnSignIn) {
|
|
500
|
+
if (!(await takeSignInLock(opts.authFile).catch(() => false))) {
|
|
501
|
+
watchForSignIn(opts, onSignedIn, expected !== undefined ? expected : await readStoredOAuthCredentials(opts).catch(() => null));
|
|
502
|
+
return { kind: "elsewhere", signInUrl: await sharedSignInUrl(opts) };
|
|
503
|
+
}
|
|
504
|
+
if (expected !== undefined && credentialsTag(await readStoredOAuthCredentials(opts).catch(() => null)) !== credentialsTag(expected)) {
|
|
505
|
+
await releaseSignInLock(opts.authFile);
|
|
506
|
+
return { kind: "renewed" };
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
const pending = interactiveSignIn({
|
|
510
|
+
...opts,
|
|
511
|
+
quietOpenFailure: true,
|
|
512
|
+
openUrl: async (url) => {
|
|
513
|
+
await shareSignInUrl(opts.authFile, url);
|
|
514
|
+
opened(url);
|
|
515
|
+
await (opts.openUrl ? opts.openUrl(url) : openBrowser({ ...opts, openUrl: undefined, quietOpenFailure: true }, url));
|
|
516
|
+
}
|
|
517
|
+
});
|
|
518
|
+
pending.then(() => { lastSignIns.set(key, Date.now()); return onSignedIn(); }, () => { failed = true; })
|
|
519
|
+
.catch(() => undefined)
|
|
520
|
+
.finally(() => {
|
|
521
|
+
opened(null);
|
|
522
|
+
// This process took the lock for its sign-in; a joined sign-in's owner releases its own.
|
|
523
|
+
if (runsOwnSignIn)
|
|
524
|
+
void releaseSignInLock(opts.authFile);
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
finally {
|
|
528
|
+
signInStarts.delete(key);
|
|
529
|
+
decided();
|
|
530
|
+
}
|
|
531
|
+
const timer = setTimeout(() => opened(null), opts.timeoutMs);
|
|
532
|
+
timer.unref?.();
|
|
533
|
+
// Joining a sign-in that has not published its address yet never calls
|
|
534
|
+
// this openUrl, so watch for the address it publishes instead.
|
|
535
|
+
const poll = setInterval(() => { const url = signInUrls.get(key); if (url)
|
|
536
|
+
opened(url); }, 100);
|
|
537
|
+
poll.unref?.();
|
|
538
|
+
const signInUrl = (await address) ?? signInUrls.get(key) ?? null;
|
|
539
|
+
clearTimeout(timer);
|
|
540
|
+
clearInterval(poll);
|
|
541
|
+
if (!signInUrl && failed)
|
|
542
|
+
return { kind: "failed" };
|
|
543
|
+
return { kind: "started", signInUrl };
|
|
544
|
+
}
|
|
545
|
+
/** `platform_sign_in`: a fresh browser sign-in the person or assistant asks for, signed in or not. */
|
|
546
|
+
async function signInTool(opts, onSignedIn) {
|
|
547
|
+
if (opts.token)
|
|
548
|
+
return structuredToolError("manual_token_sign_in_unavailable");
|
|
549
|
+
if (!servesBuild(opts))
|
|
550
|
+
return structuredToolError("sign_in_unavailable_on_harness_surface");
|
|
551
|
+
const started = await startBrowserSignIn(opts, onSignedIn);
|
|
552
|
+
if (started.kind === "failed" || started.kind === "renewed")
|
|
553
|
+
return structuredToolError("sign_in_unavailable: Topline did not answer the sign-in request. Try again shortly.");
|
|
554
|
+
const signInUrl = started.signInUrl;
|
|
555
|
+
const result = toolResult({
|
|
556
|
+
ok: true,
|
|
557
|
+
status: "sign_in_started",
|
|
558
|
+
message: started.kind === "elsewhere"
|
|
559
|
+
? "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."
|
|
560
|
+
: "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.",
|
|
561
|
+
...(signInUrl ? { signInUrl } : {})
|
|
562
|
+
});
|
|
563
|
+
if (signInUrl)
|
|
564
|
+
result.content.push({ type: "resource_link", uri: signInUrl, name: "Sign in to Topline" });
|
|
565
|
+
return result;
|
|
120
566
|
}
|
|
121
567
|
/**
|
|
122
568
|
* `topline-mcp login`: sign in once during setup so the assistant's next chat
|
|
@@ -195,6 +641,8 @@ export function createHarnessMcpStdioServer(opts, toolAllowlist) {
|
|
|
195
641
|
let hostedSessionSchemas = new Map();
|
|
196
642
|
// Only the newest listing writes shared state, so a slow older one cannot overwrite it.
|
|
197
643
|
let listingGeneration = 0;
|
|
644
|
+
// The tool list only changes when signing in (from signed out, which is
|
|
645
|
+
// null) or when the scopes change, so a token refresh is not a new grant.
|
|
198
646
|
const grantTag = (stored) => stored?.accessToken && Date.parse(stored.accessTokenExpiresAt ?? "") > Date.now()
|
|
199
647
|
? JSON.stringify([stored.clientId, stored.resource, [...stored.scopes].sort()]) : null;
|
|
200
648
|
// Identifies one sign-in regardless of access-token expiry: each browser
|
|
@@ -308,6 +756,8 @@ export function createHarnessMcpStdioServer(opts, toolAllowlist) {
|
|
|
308
756
|
}
|
|
309
757
|
const reportsProgress = req.params.name === "platform_deploy_artifact_app" || req.params.name === "platform_wait_artifact_deploy";
|
|
310
758
|
let refusedHidden = false;
|
|
759
|
+
// The sign-in this call starts from, and the bearer it sends.
|
|
760
|
+
const usage = { before: servesBuild(opts) && !opts.token ? await readStoredOAuthCredentials(opts).catch(() => null) : null };
|
|
311
761
|
try {
|
|
312
762
|
// A changed sign-in (for example a reconnect with new scopes) may offer
|
|
313
763
|
// the tool again; Topline still checks, so the call goes through.
|
|
@@ -319,20 +769,21 @@ export function createHarnessMcpStdioServer(opts, toolAllowlist) {
|
|
|
319
769
|
if (!forwardsHostedTool(req.params.name))
|
|
320
770
|
throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${req.params.name}`);
|
|
321
771
|
// Workspace and other hosted tools: Topline checks scopes and seat.
|
|
322
|
-
return await forwardHostedTool(opts, req.params.name, req.params.arguments ?? {});
|
|
772
|
+
return await signInUsage.run(usage, () => forwardHostedTool(opts, req.params.name, req.params.arguments ?? {}));
|
|
323
773
|
}
|
|
324
|
-
const result = await callHarnessTool(opts, req.params.name, req.params.arguments ?? {}, {
|
|
774
|
+
const result = await signInUsage.run(usage, () => callHarnessTool(opts, req.params.name, req.params.arguments ?? {}, {
|
|
325
775
|
...(reportsProgress ? { onProgress: (progress, message) => sendProgress(extra, progress, 1, message) } : {}),
|
|
326
|
-
inputSchema: hostedSessionSchemas.get(req.params.name)
|
|
327
|
-
|
|
328
|
-
|
|
776
|
+
inputSchema: hostedSessionSchemas.get(req.params.name),
|
|
777
|
+
onSignedIn: () => mcp.sendToolListChanged()
|
|
778
|
+
}));
|
|
779
|
+
return await withSignInRecovery(opts, result, usage, () => mcp.sendToolListChanged());
|
|
329
780
|
}
|
|
330
781
|
catch (err) {
|
|
331
782
|
if (err instanceof McpError)
|
|
332
783
|
throw err;
|
|
333
784
|
if (reportsProgress)
|
|
334
785
|
await sendProgress(extra, 1, 1, "Failed artifact deployment");
|
|
335
|
-
return structuredToolError(redactSecrets(err instanceof Error ? err.message : String(err), opts));
|
|
786
|
+
return await withSignInRecovery(opts, structuredToolError(redactSecrets(err instanceof Error ? err.message : String(err), opts)), usage, () => mcp.sendToolListChanged());
|
|
336
787
|
}
|
|
337
788
|
finally {
|
|
338
789
|
let listChanged = false;
|
|
@@ -368,6 +819,9 @@ export async function callHarnessTool(opts, name, args, hooks) {
|
|
|
368
819
|
return toolError(`Invalid arguments for ${name}: ${inputError}`);
|
|
369
820
|
let result;
|
|
370
821
|
switch (name) {
|
|
822
|
+
case "platform_sign_in":
|
|
823
|
+
result = await signInTool(opts, hooks?.onSignedIn ?? (async () => undefined));
|
|
824
|
+
break;
|
|
371
825
|
case "platform_connection_check":
|
|
372
826
|
case "platform_get_design_system_state":
|
|
373
827
|
case "platform_edit_design_system":
|
|
@@ -376,11 +830,21 @@ export async function callHarnessTool(opts, name, args, hooks) {
|
|
|
376
830
|
case "platform_list_artifact_drafts":
|
|
377
831
|
case "platform_deploy_operation":
|
|
378
832
|
case "platform_validate_artifact":
|
|
379
|
-
case "platform_run_artifact_smoke":
|
|
380
833
|
case "platform_plan_artifact_draft_delete":
|
|
381
834
|
case "platform_delete_artifact_draft":
|
|
382
835
|
result = toolResult(await callHostedBuildTool(opts, name, input));
|
|
383
836
|
break;
|
|
837
|
+
case "platform_run_artifact_smoke":
|
|
838
|
+
// A dev sandbox smoke returns its screenshot as image content, so pass the whole hosted result through.
|
|
839
|
+
if (input.target === "sandbox") {
|
|
840
|
+
if (!servesBuild(opts))
|
|
841
|
+
throw new Error(`${name}_requires_build_surface`);
|
|
842
|
+
result = await forwardHostedTool(opts, name, input);
|
|
843
|
+
}
|
|
844
|
+
else {
|
|
845
|
+
result = toolResult(await callHostedBuildTool(opts, name, input));
|
|
846
|
+
}
|
|
847
|
+
break;
|
|
384
848
|
case "platform_checkout_design_system":
|
|
385
849
|
result = toolResult(await checkoutDesignSystem(opts, input));
|
|
386
850
|
break;
|
|
@@ -403,7 +867,8 @@ export async function callHarnessTool(opts, name, args, hooks) {
|
|
|
403
867
|
result = toolResult(await getArtifactStatus(opts, stringArg(input, "artifactId"), numberArg(input, "limit")));
|
|
404
868
|
break;
|
|
405
869
|
case "platform_read_artifact_logs":
|
|
406
|
-
|
|
870
|
+
// Dev sandbox logs are only served by the hosted tool, not the REST logs route.
|
|
871
|
+
result = toolResult(input.target === "sandbox" ? await callHostedBuildTool(opts, name, input) : await readArtifactLogs(opts, input));
|
|
407
872
|
break;
|
|
408
873
|
case "platform_open_artifact":
|
|
409
874
|
result = toolResult(await openArtifact(opts, stringArg(input, "artifactId")));
|
|
@@ -491,8 +956,13 @@ export async function deployArtifactApp(opts, input, onProgress) {
|
|
|
491
956
|
if (input.artifactId !== undefined && input.artifactId !== sessionArtifactId)
|
|
492
957
|
throw new Error("build_session_artifact_mismatch");
|
|
493
958
|
}
|
|
494
|
-
else
|
|
495
|
-
|
|
959
|
+
else {
|
|
960
|
+
const sessionOnly = Object.entries({ artifactVersionId: sessionVersion, idempotencyKey, inspectedSourceHash, platformAppDir: suppliedPlatformAppDir })
|
|
961
|
+
.filter(([, value]) => value).map(([field]) => field);
|
|
962
|
+
// Name the fields so the caller can drop them for a plain deploy or start a session.
|
|
963
|
+
if (sessionOnly.length)
|
|
964
|
+
throw new Error(`build_session_id_required:${sessionOnly.join(",")}`);
|
|
965
|
+
}
|
|
496
966
|
await onProgress?.(0.4, "Creating private artifact draft");
|
|
497
967
|
const created = await fetchJson(opts, artifactAppsPath(opts), {
|
|
498
968
|
method: "POST",
|
|
@@ -1380,6 +1850,19 @@ const BUILD_MCP_TOOLS = [
|
|
|
1380
1850
|
required: ["ok", "verified", "product", "verifiedAt"]
|
|
1381
1851
|
}
|
|
1382
1852
|
},
|
|
1853
|
+
{
|
|
1854
|
+
name: "platform_sign_in",
|
|
1855
|
+
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.",
|
|
1856
|
+
annotations: mcpToolAnnotations("platform_sign_in", { readOnly: false, idempotent: true, openWorld: true }),
|
|
1857
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
|
1858
|
+
outputSchema: {
|
|
1859
|
+
type: "object",
|
|
1860
|
+
properties: {
|
|
1861
|
+
ok: { type: "boolean" }, status: { type: "string", enum: ["sign_in_started"] }, message: { type: "string" }, signInUrl: { type: "string" }
|
|
1862
|
+
},
|
|
1863
|
+
required: ["ok", "status", "message"]
|
|
1864
|
+
}
|
|
1865
|
+
},
|
|
1383
1866
|
{
|
|
1384
1867
|
name: "platform_init_artifact_app",
|
|
1385
1868
|
description: "Create a minimal, validated artifact app starter inside the configured local workspace.",
|
|
@@ -1517,7 +2000,7 @@ const BUILD_MCP_TOOLS = [
|
|
|
1517
2000
|
},
|
|
1518
2001
|
{
|
|
1519
2002
|
name: "platform_read_artifact_logs",
|
|
1520
|
-
description: "Read bounded, redacted deployment logs for a hosted artifact app.",
|
|
2003
|
+
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.",
|
|
1521
2004
|
annotations: mcpToolAnnotations("platform_read_artifact_logs", { readOnly: true, openWorld: true }),
|
|
1522
2005
|
inputSchema: {
|
|
1523
2006
|
type: "object",
|
|
@@ -1525,6 +2008,9 @@ const BUILD_MCP_TOOLS = [
|
|
|
1525
2008
|
artifactId: { type: "string", format: "uuid" },
|
|
1526
2009
|
deploymentRecordId: { type: "string", format: "uuid" },
|
|
1527
2010
|
environment: { type: "string", enum: ["draft", "live"] },
|
|
2011
|
+
target: { type: "string", enum: ["draft", "live", "sandbox"] },
|
|
2012
|
+
sessionId: { type: "string", format: "uuid" },
|
|
2013
|
+
sandboxId: { type: "string", format: "uuid" },
|
|
1528
2014
|
limit: { type: "integer", minimum: 1, maximum: 200 },
|
|
1529
2015
|
severity: { type: "string" },
|
|
1530
2016
|
contains: { type: "string" },
|
|
@@ -1672,9 +2158,9 @@ const BUILD_MCP_TOOLS = [
|
|
|
1672
2158
|
},
|
|
1673
2159
|
{
|
|
1674
2160
|
name: "platform_run_artifact_smoke",
|
|
1675
|
-
description: "Rerun the trusted draft smoke check and return fresh rendered-page evidence.",
|
|
2161
|
+
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).",
|
|
1676
2162
|
annotations: mcpToolAnnotations("platform_run_artifact_smoke", { readOnly: false, openWorld: true }),
|
|
1677
|
-
inputSchema: { type: "object", properties: { artifactId: { type: "string", format: "uuid" }, deploymentRecordId: { type: "string", format: "uuid" } }, required: ["artifactId"], additionalProperties: false },
|
|
2163
|
+
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 },
|
|
1678
2164
|
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"] }
|
|
1679
2165
|
},
|
|
1680
2166
|
{
|
|
@@ -1787,6 +2273,7 @@ function withRecoveryOutputSchema(value) {
|
|
|
1787
2273
|
message: { type: "string" },
|
|
1788
2274
|
retryable: { type: "boolean" },
|
|
1789
2275
|
recoveryAction: { type: "string" },
|
|
2276
|
+
signInUrl: { type: "string" },
|
|
1790
2277
|
...(DOMAIN_FORWARD_TOOLS.has(tool.name) ? { recovery: { type: "object", additionalProperties: true } } : {})
|
|
1791
2278
|
},
|
|
1792
2279
|
required: ["code", "message", "retryable", "recoveryAction"],
|
|
@@ -1830,9 +2317,16 @@ const BUILD_MCP_RECOVERY_ERROR_VALUES = {
|
|
|
1830
2317
|
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." }])),
|
|
1831
2318
|
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." },
|
|
1832
2319
|
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." },
|
|
1833
|
-
authorization_required: { retryable: false, recoveryAction: "
|
|
2320
|
+
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." },
|
|
2321
|
+
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." },
|
|
2322
|
+
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." },
|
|
2323
|
+
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." },
|
|
2324
|
+
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." },
|
|
2325
|
+
sign_in_unavailable: { retryable: true, recoveryAction: "Topline did not answer the sign-in request. Wait briefly, then call platform_sign_in again." },
|
|
1834
2326
|
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." },
|
|
1835
|
-
platform_mcp_tool_error: { retryable: false, recoveryAction: "
|
|
2327
|
+
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." },
|
|
2328
|
+
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." },
|
|
2329
|
+
artifact_external_session_active: { retryable: false, recoveryAction: "An open build session holds this app. If it is yours, pass its sessionId; otherwise close it with platform_close_build_session or wait for it to end." },
|
|
1836
2330
|
artifact_deploy_wait_timeout: { retryable: true, recoveryAction: "Call platform_wait_artifact_deploy again with the same artifactId and operationId." },
|
|
1837
2331
|
artifact_delete_plan_stale: { retryable: true, recoveryAction: "Call platform_plan_artifact_draft_delete again, review the new effects, and use its planToken." },
|
|
1838
2332
|
artifact_app_bundle_changed_after_inspection: { retryable: true, recoveryAction: "Call platform_inspect_artifact_app again, review the new bundle hash, then retry deployment with that hash." },
|
|
@@ -1855,9 +2349,32 @@ function structuredToolError(message) {
|
|
|
1855
2349
|
isError: true
|
|
1856
2350
|
};
|
|
1857
2351
|
}
|
|
2352
|
+
/** The code Topline put inside a wrapped tool error: JSON `{ error: { code } }`, `{ error: "code" }`, or a leading code token. */
|
|
2353
|
+
function hostedToolErrorCode(inner) {
|
|
2354
|
+
try {
|
|
2355
|
+
const parsed = JSON.parse(inner);
|
|
2356
|
+
if (isRecord(parsed)) {
|
|
2357
|
+
const error = parsed.error;
|
|
2358
|
+
const code = isRecord(error) ? error.code : typeof error === "string" ? error : parsed.code;
|
|
2359
|
+
if (typeof code === "string" && /^[a-z][a-z0-9_]{2,}$/.test(code))
|
|
2360
|
+
return code;
|
|
2361
|
+
}
|
|
2362
|
+
}
|
|
2363
|
+
catch {
|
|
2364
|
+
// Not JSON; fall back to a leading code token.
|
|
2365
|
+
}
|
|
2366
|
+
// Only a code-shaped token (it has an underscore): plain English such as
|
|
2367
|
+
// "missing scope ..." or "not found" is a message, not a code.
|
|
2368
|
+
return inner.match(/^([a-z][a-z0-9]*_[a-z0-9_]+)(?::|$|\s)/)?.[1] ?? null;
|
|
2369
|
+
}
|
|
1858
2370
|
function recoveryErrorCode(message) {
|
|
1859
2371
|
if (/^platform_harness_http_error:401(?::|$)/.test(message))
|
|
1860
2372
|
return "authorization_required";
|
|
2373
|
+
if (message.startsWith("platform_mcp_tool_error:")) {
|
|
2374
|
+
const inner = hostedToolErrorCode(message.slice("platform_mcp_tool_error:".length).trim());
|
|
2375
|
+
if (inner && !["unknown_error", "tool_failed", "empty_response"].includes(inner))
|
|
2376
|
+
return inner === "mcp_tool_failed" ? "platform_mcp_tool_error" : inner;
|
|
2377
|
+
}
|
|
1861
2378
|
if (DOMAIN_ERROR_CODES.has(message) || message === "domain_result_unknown")
|
|
1862
2379
|
return message;
|
|
1863
2380
|
const known = [
|
|
@@ -1866,8 +2383,9 @@ function recoveryErrorCode(message) {
|
|
|
1866
2383
|
"artifact_app_scaffold_target_not_empty",
|
|
1867
2384
|
"artifact_app_scaffold_shape_invalid",
|
|
1868
2385
|
"platform_harness_timeout",
|
|
1869
|
-
|
|
1870
|
-
"scope_required"
|
|
2386
|
+
// Before the generic wrapper, which every hosted error message starts with.
|
|
2387
|
+
"scope_required",
|
|
2388
|
+
"platform_mcp_tool_error"
|
|
1871
2389
|
].find((candidate) => message.includes(candidate));
|
|
1872
2390
|
if (known)
|
|
1873
2391
|
return known;
|
|
@@ -1910,12 +2428,16 @@ export async function getBearerToken(opts) {
|
|
|
1910
2428
|
[...opts.oauthScopes].sort().join(" ")
|
|
1911
2429
|
].join("\0");
|
|
1912
2430
|
const existing = inFlightBearerTokenRequests.get(key);
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
inFlightBearerTokenRequests.set(key, pending);
|
|
2431
|
+
const pending = existing ?? getOAuthBearerToken(opts);
|
|
2432
|
+
if (!existing)
|
|
2433
|
+
inFlightBearerTokenRequests.set(key, pending);
|
|
1917
2434
|
try {
|
|
1918
|
-
|
|
2435
|
+
const bearer = await pending;
|
|
2436
|
+
// Remembered for this tool call, so a refusal can tell whether the sign-in changed since.
|
|
2437
|
+
const usage = signInUsage.getStore();
|
|
2438
|
+
if (usage)
|
|
2439
|
+
usage.bearer = bearer;
|
|
2440
|
+
return bearer;
|
|
1919
2441
|
}
|
|
1920
2442
|
finally {
|
|
1921
2443
|
if (inFlightBearerTokenRequests.get(key) === pending)
|
|
@@ -1945,7 +2467,21 @@ async function refreshStoredOAuthToken(opts, stored) {
|
|
|
1945
2467
|
if (existing)
|
|
1946
2468
|
return existing;
|
|
1947
2469
|
const pending = (async () => {
|
|
1948
|
-
|
|
2470
|
+
let refreshed;
|
|
2471
|
+
try {
|
|
2472
|
+
refreshed = await refreshOAuthToken(opts, stored);
|
|
2473
|
+
}
|
|
2474
|
+
catch (err) {
|
|
2475
|
+
// Another server process may have rotated this refresh token a moment
|
|
2476
|
+
// ago; its new sign-in is then in the auth file, not refused.
|
|
2477
|
+
if (!isRefreshTokenRejected(err))
|
|
2478
|
+
throw err;
|
|
2479
|
+
const current = await readStoredOAuthCredentials(opts).catch(() => null);
|
|
2480
|
+
if (current?.refreshToken && current.refreshToken !== stored.refreshToken && current.accessToken
|
|
2481
|
+
&& Date.parse(current.accessTokenExpiresAt ?? "") - Date.now() > 60_000)
|
|
2482
|
+
return current;
|
|
2483
|
+
throw err;
|
|
2484
|
+
}
|
|
1949
2485
|
await writeStoredOAuthCredentials(opts, refreshed);
|
|
1950
2486
|
return refreshed;
|
|
1951
2487
|
})();
|
|
@@ -1973,8 +2509,7 @@ async function getOAuthBearerToken(opts) {
|
|
|
1973
2509
|
// Fall through to an interactive login; the stored refresh token may have been revoked.
|
|
1974
2510
|
}
|
|
1975
2511
|
}
|
|
1976
|
-
const loggedIn = await
|
|
1977
|
-
await writeStoredOAuthCredentials(opts, loggedIn);
|
|
2512
|
+
const loggedIn = await interactiveSignIn(opts);
|
|
1978
2513
|
return loggedIn.accessToken;
|
|
1979
2514
|
}
|
|
1980
2515
|
async function refreshOAuthToken(opts, stored) {
|
|
@@ -2035,6 +2570,7 @@ async function runOAuthLogin(opts) {
|
|
|
2035
2570
|
const codePromise = callback.waitForCode(state);
|
|
2036
2571
|
// A denial can land while the browser is still opening; it is reported below.
|
|
2037
2572
|
codePromise.catch(() => undefined);
|
|
2573
|
+
signInUrls.set(path.resolve(opts.authFile), authUrl.toString());
|
|
2038
2574
|
await openBrowser(opts, authUrl.toString());
|
|
2039
2575
|
const code = await codePromise;
|
|
2040
2576
|
const token = await oauthFetchJson(opts, `${issuer}/oauth/token`, {
|
|
@@ -2052,6 +2588,7 @@ async function runOAuthLogin(opts) {
|
|
|
2052
2588
|
return credentialsFromTokenResponse(issuer, resource, clientId, opts.oauthScopes, token);
|
|
2053
2589
|
}
|
|
2054
2590
|
finally {
|
|
2591
|
+
signInUrls.delete(path.resolve(opts.authFile));
|
|
2055
2592
|
await callback.close();
|
|
2056
2593
|
}
|
|
2057
2594
|
}
|
|
@@ -2094,6 +2631,7 @@ function credentialsFromTokenResponse(issuer, resource, clientId, requestedScope
|
|
|
2094
2631
|
accessToken,
|
|
2095
2632
|
accessTokenExpiresAt: new Date(Date.now() + Math.max(60, Math.floor(expiresIn)) * 1000).toISOString(),
|
|
2096
2633
|
refreshToken,
|
|
2634
|
+
obtainedAt: new Date().toISOString(),
|
|
2097
2635
|
scopes: scopeText.split(/[\s,]+/).filter(Boolean)
|
|
2098
2636
|
};
|
|
2099
2637
|
}
|
|
@@ -2122,6 +2660,7 @@ async function readStoredOAuthCredentials(opts) {
|
|
|
2122
2660
|
accessToken: typeof parsed.accessToken === "string" ? parsed.accessToken : undefined,
|
|
2123
2661
|
accessTokenExpiresAt: typeof parsed.accessTokenExpiresAt === "string" ? parsed.accessTokenExpiresAt : undefined,
|
|
2124
2662
|
refreshToken: typeof parsed.refreshToken === "string" ? parsed.refreshToken : undefined,
|
|
2663
|
+
...(typeof parsed.obtainedAt === "string" ? { obtainedAt: parsed.obtainedAt } : {}),
|
|
2125
2664
|
scopes
|
|
2126
2665
|
};
|
|
2127
2666
|
}
|
|
@@ -2129,9 +2668,36 @@ async function readStoredOAuthCredentials(opts) {
|
|
|
2129
2668
|
return null;
|
|
2130
2669
|
}
|
|
2131
2670
|
}
|
|
2671
|
+
/**
|
|
2672
|
+
* Replace the auth file in one step (a temporary file in the same directory,
|
|
2673
|
+
* then a rename), so another process never reads a half-written sign-in.
|
|
2674
|
+
*/
|
|
2132
2675
|
async function writeStoredOAuthCredentials(opts, credentials) {
|
|
2133
2676
|
await mkdir(path.dirname(opts.authFile), { recursive: true });
|
|
2134
|
-
|
|
2677
|
+
const temp = `${opts.authFile}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
|
2678
|
+
try {
|
|
2679
|
+
await writeFile(temp, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 0o600, flag: "wx" });
|
|
2680
|
+
// Windows refuses the rename for a moment while another process reads the
|
|
2681
|
+
// file: retry for about 1.5 s, then write in place so a finished Allow is never lost.
|
|
2682
|
+
for (const delay of [25, 50, 100, 200, 400, 700, -1]) {
|
|
2683
|
+
try {
|
|
2684
|
+
await rename(temp, opts.authFile);
|
|
2685
|
+
return;
|
|
2686
|
+
}
|
|
2687
|
+
catch (err) {
|
|
2688
|
+
const code = err.code;
|
|
2689
|
+
if (code !== "EPERM" && code !== "EACCES" && code !== "EBUSY")
|
|
2690
|
+
throw err;
|
|
2691
|
+
if (delay < 0)
|
|
2692
|
+
break;
|
|
2693
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
2694
|
+
}
|
|
2695
|
+
}
|
|
2696
|
+
await writeFile(opts.authFile, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 0o600 });
|
|
2697
|
+
}
|
|
2698
|
+
finally {
|
|
2699
|
+
await rm(temp, { force: true }).catch(() => undefined);
|
|
2700
|
+
}
|
|
2135
2701
|
}
|
|
2136
2702
|
async function startOAuthCallbackServer() {
|
|
2137
2703
|
let resolveCode = null;
|