viewable-one 0.12.1 → 0.12.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 +71 -1
- package/README.md +31 -48
- package/SPAWN.md +136 -79
- package/glytch.mjs +41 -10
- package/lib/acp.mjs +152 -150
- package/lib/admission.mjs +25 -5
- package/lib/agent-selection.mjs +5 -4
- package/lib/agents.mjs +68 -24
- package/lib/answerTag.mjs +47 -0
- package/lib/atomic.mjs +1 -16
- package/lib/auth.mjs +172 -52
- package/lib/authenticatedHttp.mjs +10 -3
- package/lib/boardside.mjs +28 -12
- package/lib/child.mjs +129 -116
- package/lib/claudeModels.mjs +168 -0
- package/lib/codex-rpc.mjs +2 -2
- package/lib/codex.mjs +50 -50
- package/lib/codexApps.mjs +17 -3
- package/lib/codexToolInputs.mjs +98 -22
- package/lib/codingChecks.mjs +8 -4
- package/lib/conversationRules.mjs +47 -7
- package/lib/detect.mjs +39 -24
- package/lib/devserver.mjs +30 -19
- package/lib/doctor.mjs +10 -8
- package/lib/folderReads.mjs +96 -0
- package/lib/followUps.mjs +170 -0
- package/lib/hosted.mjs +13 -4
- package/lib/init-connect.mjs +29 -10
- package/lib/lateResume.mjs +135 -0
- package/lib/logindaemon.mjs +129 -49
- package/lib/logs.mjs +2 -2
- package/lib/mcpjson.mjs +35 -2
- package/lib/memberPreview.mjs +22 -14
- package/lib/multiwatch.mjs +28 -41
- package/lib/pagePictures.mjs +15 -12
- package/lib/pageRoutes.mjs +5 -2
- package/lib/paths.mjs +3 -3
- package/lib/permissionAsk.mjs +344 -61
- package/lib/previewGateway.mjs +4 -3
- package/lib/procs.mjs +73 -2
- package/lib/refusal.mjs +0 -2
- package/lib/registry.mjs +7 -7
- package/lib/repomap.mjs +4 -3
- package/lib/restartPass.mjs +39 -11
- package/lib/rowsAnswers.mjs +52 -69
- package/lib/rowsEvents.mjs +20 -2
- package/lib/runner-health.mjs +29 -5
- package/lib/runner.mjs +161 -1347
- package/lib/runnerAdmission.mjs +6 -12
- package/lib/runnerApi.mjs +20 -11
- package/lib/runnerBeat.mjs +384 -0
- package/lib/runnerCompletion.mjs +5 -2
- package/lib/runnerExecute.mjs +227 -0
- package/lib/runnerGates.mjs +338 -0
- package/lib/runnerLaunch.mjs +351 -0
- package/lib/runnerLease.mjs +31 -9
- package/lib/runnerOps.mjs +217 -0
- package/lib/runnerPace.mjs +10 -6
- package/lib/runnerRecovery.mjs +457 -0
- package/lib/runnerRegister.mjs +29 -8
- package/lib/runnerSettlement.mjs +43 -16
- package/lib/runnerWorkspace.mjs +19 -4
- package/lib/spawn.mjs +0 -5
- package/lib/sync.mjs +28 -16
- package/lib/uninstall-project.mjs +12 -11
- package/lib/uninstall.mjs +32 -25
- package/lib/update.mjs +4 -4
- package/lib/{glytchFolder.mjs → viewableFolder.mjs} +22 -16
- package/lib/worktree.mjs +83 -26
- package/lib/writePolicy.mjs +90 -10
- package/package.json +2 -2
package/lib/auth.mjs
CHANGED
|
@@ -49,7 +49,7 @@ import { createServer } from "node:http";
|
|
|
49
49
|
import { spawn } from "node:child_process";
|
|
50
50
|
import { join } from "node:path";
|
|
51
51
|
|
|
52
|
-
import {
|
|
52
|
+
import { viewableHome } from "./registry.mjs";
|
|
53
53
|
import { writeFileAtomic } from "./atomic.mjs";
|
|
54
54
|
import { movedAuth } from "./retired-address.mjs";
|
|
55
55
|
|
|
@@ -92,7 +92,7 @@ const LOGIN_TIMEOUT_MS = 5 * 60_000;
|
|
|
92
92
|
* hold the loopback socket open with no clock on it at all. */
|
|
93
93
|
const EXCHANGE_TIMEOUT_MS = 60_000;
|
|
94
94
|
|
|
95
|
-
const authFilePath = (env = process.env) => join(
|
|
95
|
+
const authFilePath = (env = process.env) => join(viewableHome(env), "auth.json");
|
|
96
96
|
|
|
97
97
|
const trimTrailingSlash = (s) => String(s).replace(/\/+$/, "");
|
|
98
98
|
|
|
@@ -122,7 +122,7 @@ export async function readAuthFile(env = process.env) {
|
|
|
122
122
|
}
|
|
123
123
|
|
|
124
124
|
async function writeAuthFile(data, env = process.env) {
|
|
125
|
-
const home =
|
|
125
|
+
const home = viewableHome(env);
|
|
126
126
|
await mkdir(home, { recursive: true });
|
|
127
127
|
// mode 0600 at creation; writeFileAtomic renames the temp file (created with
|
|
128
128
|
// this mode) into place, so the final file carries it too rather than
|
|
@@ -197,8 +197,9 @@ const LOCK_WAIT_MS = 10_000;
|
|
|
197
197
|
|
|
198
198
|
/** A lock directory older than this belonged to a process that died holding
|
|
199
199
|
* it. Generous against a slow network, short enough that a crash does not
|
|
200
|
-
* wedge a laptop until it reboots.
|
|
201
|
-
|
|
200
|
+
* wedge a laptop until it reboots. Allow the bounded exchange to finish
|
|
201
|
+
* and release its lock before another process may reclaim it. */
|
|
202
|
+
const LOCK_STALE_MS = 2 * EXCHANGE_TIMEOUT_MS;
|
|
202
203
|
|
|
203
204
|
const LOCK_POLL_MS = 50;
|
|
204
205
|
|
|
@@ -289,9 +290,9 @@ const DEAD_BACKOFF_MAX_MS = 30 * 60_000;
|
|
|
289
290
|
|
|
290
291
|
/** The OAuth error codes that mean "a person must sign in again", per RFC
|
|
291
292
|
* 6749 section 5.2 and what board-oauth actually answers. Everything else -
|
|
292
|
-
*
|
|
293
|
-
*
|
|
294
|
-
*
|
|
293
|
+
* received 5xx or a proxy error can back off while offering an unexpired
|
|
294
|
+
* cached access token. A timeout or unreadable success may have consumed
|
|
295
|
+
* the rotating token and must remain uncertain instead. */
|
|
295
296
|
const TERMINAL_REFRESH_ERRORS = new Set([
|
|
296
297
|
"invalid_grant",
|
|
297
298
|
"invalid_client",
|
|
@@ -337,6 +338,12 @@ const hasOAuthPair = (stored) =>
|
|
|
337
338
|
typeof stored?.refreshToken === "string" && stored.refreshToken !== "" &&
|
|
338
339
|
typeof stored?.tokenEndpoint === "string" && typeof stored?.clientId === "string";
|
|
339
340
|
|
|
341
|
+
// Personal login can move the OAuth bearer while a refresh is in flight.
|
|
342
|
+
// Resolve its field layout from whichever record is being read or written.
|
|
343
|
+
const oauthFields = (stored) => stored.personal === true
|
|
344
|
+
? { token: "oauthAccessToken", expires: "oauthAccessExpiresAt" }
|
|
345
|
+
: { token: "accessToken", expires: "accessExpiresAt" };
|
|
346
|
+
|
|
340
347
|
/** TWO CREDENTIALS, TWO MARKS (2026-09-19). A merged record - `personal:
|
|
341
348
|
* true` written by `login()` over an existing OAuth credential, which keeps
|
|
342
349
|
* the OAuth pair alongside the personal token rather than discarding it
|
|
@@ -428,7 +435,7 @@ async function clearDeadMark(env, kind) {
|
|
|
428
435
|
async function markCredentialDead(stored, env, now, reason, prior, notify, kind = "oauth") {
|
|
429
436
|
// A recovered credential may still carry history when its next refresh
|
|
430
437
|
// fails. Expire that history here too, before deriving the new failure.
|
|
431
|
-
if (prior && prior.reason
|
|
438
|
+
if (prior && !["refresh_refused", "refresh_uncertain"].includes(prior.reason) && now() - Number(prior.until) > DEAD_BACKOFF_MAX_MS) {
|
|
432
439
|
prior = null;
|
|
433
440
|
}
|
|
434
441
|
const keepRefreshWait = reason === "rejected" && prior?.reason === "refresh_transient" && now() < Number(prior.until);
|
|
@@ -440,11 +447,11 @@ async function markCredentialDead(stored, env, now, reason, prior, notify, kind
|
|
|
440
447
|
reason,
|
|
441
448
|
tries,
|
|
442
449
|
since: prior?.since ?? new Date(now()).toISOString(),
|
|
443
|
-
until:
|
|
450
|
+
until: ["refresh_refused", "refresh_uncertain"].includes(reason) ? null : keepRefreshWait ? prior.until : now() + wait,
|
|
444
451
|
notified: alreadyToldThem || reason !== "refresh_transient",
|
|
445
452
|
};
|
|
446
453
|
try {
|
|
447
|
-
await mkdir(
|
|
454
|
+
await mkdir(viewableHome(env), { recursive: true });
|
|
448
455
|
await writeFileAtomic(markPathFor(kind, env), `${JSON.stringify(mark, null, 2)}\n`, "utf8", { mode: 0o600 });
|
|
449
456
|
} catch { /* see above: the mark is an optimisation, not a precondition */ }
|
|
450
457
|
// The personal token gets its own sentence (B2): it is rejected, not
|
|
@@ -503,7 +510,7 @@ export async function noteCredentialRejected({ env = process.env, now = () => Da
|
|
|
503
510
|
// The forced refresh ran after this access-token rejection. Preserve its
|
|
504
511
|
// retry count and deadline while also suppressing the rejected access token.
|
|
505
512
|
const prior = await matchingDeadMark(stored, env, kind, true);
|
|
506
|
-
if (prior?.reason
|
|
513
|
+
if (!["refresh_refused", "refresh_uncertain"].includes(prior?.reason)) {
|
|
507
514
|
await markCredentialDead(stored, env, now, "rejected", prior, notify, kind);
|
|
508
515
|
}
|
|
509
516
|
return true;
|
|
@@ -603,7 +610,6 @@ export async function hostedToken({
|
|
|
603
610
|
// or a real 401 on the OAuth side asks for one.
|
|
604
611
|
return oauthAccessToken(stored, {
|
|
605
612
|
env, fetchImpl, now, notify, forceRefresh, log,
|
|
606
|
-
fields: { token: "oauthAccessToken", expires: "oauthAccessExpiresAt" },
|
|
607
613
|
});
|
|
608
614
|
}
|
|
609
615
|
|
|
@@ -638,13 +644,20 @@ export async function hostedToken({
|
|
|
638
644
|
* shape asked for the refresh. */
|
|
639
645
|
async function oauthAccessToken(stored, {
|
|
640
646
|
env, forceRefresh, fetchImpl, now, notify,
|
|
641
|
-
fields = { token: "accessToken", expires: "accessExpiresAt" },
|
|
642
647
|
log = () => {},
|
|
643
648
|
}) {
|
|
649
|
+
const fields = oauthFields(stored);
|
|
644
650
|
// Both ordinary credentials and a personal-token fallback obey this gate.
|
|
645
651
|
// Older finite refusals get one re-check after their cooldown.
|
|
652
|
+
const key = authFilePath(env);
|
|
653
|
+
const running = refreshInFlight.get(key);
|
|
654
|
+
if (running) return running;
|
|
646
655
|
const dead = await matchingDeadMark(stored, env, "oauth", true);
|
|
656
|
+
if (refreshInFlight.has(key)) return refreshInFlight.get(key);
|
|
647
657
|
if (dead?.reason === "refresh_refused" && dead.until === null) return null;
|
|
658
|
+
// A different process may still be rotating this token. Wait for its lock
|
|
659
|
+
// and re-read before interpreting the marker as an abandoned exchange.
|
|
660
|
+
const uncertain = dead?.reason === "refresh_uncertain" && dead.until === null;
|
|
648
661
|
if (dead !== null && now() < Number(dead.until)) {
|
|
649
662
|
const t = stored[fields.token];
|
|
650
663
|
return dead.reason === "refresh_transient" && typeof t === "string" && t !== "" &&
|
|
@@ -655,9 +668,10 @@ async function oauthAccessToken(stored, {
|
|
|
655
668
|
const t = row[fields.token];
|
|
656
669
|
return typeof t === "string" && t !== "" && Number(row[fields.expires]) - now() >= REFRESH_SKEW_MS;
|
|
657
670
|
};
|
|
658
|
-
if (!forceRefresh && fresh(stored)) return stored[fields.token];
|
|
671
|
+
if (!uncertain && !forceRefresh && fresh(stored)) return stored[fields.token];
|
|
659
672
|
|
|
660
673
|
if (!stored.refreshToken || !stored.tokenEndpoint || !stored.clientId) {
|
|
674
|
+
if (uncertain) return null;
|
|
661
675
|
// Nothing to refresh WITH. Still usable if it has not actually expired.
|
|
662
676
|
const t = stored[fields.token];
|
|
663
677
|
return typeof t === "string" && t !== "" && Number(stored[fields.expires]) > now() ? t : null;
|
|
@@ -668,13 +682,11 @@ async function oauthAccessToken(stored, {
|
|
|
668
682
|
// and must not queue behind each other. A given file only ever uses ONE
|
|
669
683
|
// `fields` shape at a time (a record is either personal or is not), so
|
|
670
684
|
// the path alone is still the right key.
|
|
671
|
-
const key = authFilePath(env);
|
|
672
|
-
const running = refreshInFlight.get(key);
|
|
673
|
-
if (running) return running;
|
|
674
|
-
|
|
675
685
|
const attempt = (async () => {
|
|
676
686
|
const lock = await takeRefreshLock(env, now);
|
|
677
687
|
let source = stored;
|
|
688
|
+
let previousMark;
|
|
689
|
+
let attempted = false;
|
|
678
690
|
try {
|
|
679
691
|
// DOUBLE-CHECKED, and the check is "did the token CHANGE", not "is it
|
|
680
692
|
// fresh now". A 401 forces a refresh on a token that may still be
|
|
@@ -687,7 +699,14 @@ async function oauthAccessToken(stored, {
|
|
|
687
699
|
source = current ?? stored;
|
|
688
700
|
// A process ahead of us may have recorded a failure while we waited.
|
|
689
701
|
const mark = await matchingDeadMark(source, env, "oauth", true);
|
|
690
|
-
if (mark?.reason
|
|
702
|
+
if (["refresh_refused", "refresh_uncertain"].includes(mark?.reason) && mark.until === null) {
|
|
703
|
+
// Only the lock holder can declare an abandoned exchange and persist
|
|
704
|
+
// its one notice. A live holder may still finish successfully.
|
|
705
|
+
if (lock !== null && mark.reason === "refresh_uncertain" && mark.notified !== true) {
|
|
706
|
+
await markCredentialDead(source, env, now, "refresh_uncertain", mark, notify, "oauth");
|
|
707
|
+
}
|
|
708
|
+
return null;
|
|
709
|
+
}
|
|
691
710
|
if (lock === null || (mark !== null && now() < Number(mark.until))) {
|
|
692
711
|
const t = source[fields.token];
|
|
693
712
|
return (mark === null || mark.reason === "refresh_transient") && typeof t === "string" &&
|
|
@@ -698,18 +717,33 @@ async function oauthAccessToken(stored, {
|
|
|
698
717
|
// nothing on file to refresh, already fresh, another process just
|
|
699
718
|
// refreshed - so reaching here means an HTTPS round trip is about to
|
|
700
719
|
// block whoever called `hostedToken`, silently until now.
|
|
720
|
+
previousMark = mark;
|
|
701
721
|
const refreshStartedAt = now();
|
|
722
|
+
// Persist uncertainty BEFORE spending a single-use token. A crash, timeout,
|
|
723
|
+
// unreadable body or failed save must never make it eligible for replay.
|
|
724
|
+
// Unlike the advisory backoff mark, failure to save this gate is fatal.
|
|
725
|
+
await writeFileAtomic(deadMarkPath(env), `${JSON.stringify({
|
|
726
|
+
fingerprint: credentialFingerprint(source.refreshToken),
|
|
727
|
+
reason: "refresh_uncertain", until: null, since: new Date(now()).toISOString(),
|
|
728
|
+
})}\n`, "utf8", { mode: 0o600 });
|
|
729
|
+
attempted = true;
|
|
702
730
|
const refreshed = await refreshStoredTokens(source, { fetchImpl, now });
|
|
731
|
+
const latest = await readAuthFile(env);
|
|
732
|
+
if (!latest || latest.refreshToken !== source.refreshToken) return null;
|
|
703
733
|
log(`refreshed hosted token (${Math.round(now() - refreshStartedAt)}ms)`);
|
|
734
|
+
// A personal login keeps this refresh token but changes the record and
|
|
735
|
+
// possibly its OAuth layout. Rotate into that latest record, never the
|
|
736
|
+
// snapshot from before the request, preserving the new personal bearer.
|
|
737
|
+
const latestFields = oauthFields(latest);
|
|
704
738
|
const updated = {
|
|
705
|
-
...
|
|
706
|
-
[
|
|
739
|
+
...latest,
|
|
740
|
+
[latestFields.token]: refreshed.accessToken,
|
|
707
741
|
// Rotation: a refresh token is single-use (board-oauth's own rule),
|
|
708
742
|
// shared by both field shapes because there is only ever one
|
|
709
743
|
// refresh token on a record no matter which access-token field it
|
|
710
744
|
// is renewing.
|
|
711
745
|
refreshToken: refreshed.refreshToken,
|
|
712
|
-
[
|
|
746
|
+
[latestFields.expires]: refreshed.accessExpiresAt,
|
|
713
747
|
};
|
|
714
748
|
await writeAuthFile(updated, env);
|
|
715
749
|
// The new access token can be tried, but a successful refresh is not
|
|
@@ -736,12 +770,28 @@ async function oauthAccessToken(stored, {
|
|
|
736
770
|
} else {
|
|
737
771
|
await clearDeadMark(env, "oauth");
|
|
738
772
|
}
|
|
739
|
-
return updated[
|
|
773
|
+
return updated[latestFields.token];
|
|
740
774
|
} catch (error) {
|
|
741
775
|
const current = await readAuthFile(env);
|
|
742
776
|
// A login during the request must not inherit the old token's failure.
|
|
743
|
-
if (current
|
|
744
|
-
|
|
777
|
+
if (!current || current.refreshToken !== source.refreshToken) return null;
|
|
778
|
+
if (attempted && error?.requestNotSent === true) {
|
|
779
|
+
// The adapter proved the request was not sent. Restore the exact prior
|
|
780
|
+
// gate, without incrementing backoff or pretending rotation occurred.
|
|
781
|
+
if (previousMark) {
|
|
782
|
+
await writeFileAtomic(deadMarkPath(env), `${JSON.stringify(previousMark)}\n`, "utf8", { mode: 0o600 });
|
|
783
|
+
} else {
|
|
784
|
+
await clearDeadMark(env, "oauth");
|
|
785
|
+
}
|
|
786
|
+
return null;
|
|
787
|
+
}
|
|
788
|
+
if (error?.uncertain === true || (attempted && error?.transient !== true && error?.terminal !== true)) {
|
|
789
|
+
const mark = await matchingDeadMark(current, env, "oauth", true);
|
|
790
|
+
await markCredentialDead(current, env, now, "refresh_uncertain", mark, notify, "oauth");
|
|
791
|
+
return null;
|
|
792
|
+
}
|
|
793
|
+
const priorMark = await matchingDeadMark(source, env, "oauth", true);
|
|
794
|
+
const prior = priorMark?.reason === "refresh_uncertain" ? previousMark : priorMark;
|
|
745
795
|
await markCredentialDead(source, env, now,
|
|
746
796
|
error?.terminal === true ? "refresh_refused" : "refresh_transient",
|
|
747
797
|
prior, notify, "oauth");
|
|
@@ -761,45 +811,99 @@ async function oauthAccessToken(stored, {
|
|
|
761
811
|
}
|
|
762
812
|
}
|
|
763
813
|
|
|
814
|
+
/** Only structured pre-connect evidence proves non-dispatch. A generic abort,
|
|
815
|
+
* socket reset or error-message match says nothing about token consumption.
|
|
816
|
+
* Aggregate connection attempts must ALL be proven unsent. */
|
|
817
|
+
function refreshRequestNotSent(error, seen = new Set()) {
|
|
818
|
+
if (!error || typeof error !== "object" || seen.has(error)) return false;
|
|
819
|
+
seen.add(error);
|
|
820
|
+
if (error.requestNotSent === true) return true;
|
|
821
|
+
if (Array.isArray(error.errors)) return error.errors.length > 0 &&
|
|
822
|
+
error.errors.every(cause => refreshRequestNotSent(cause, new Set(seen)));
|
|
823
|
+
if (error.cause) return refreshRequestNotSent(error.cause, seen);
|
|
824
|
+
return (["ENOTFOUND", "EAI_AGAIN"].includes(error.code) && error.syscall === "getaddrinfo") ||
|
|
825
|
+
(["ECONNREFUSED", "ENETUNREACH", "EHOSTUNREACH", "ETIMEDOUT"].includes(error.code) && error.syscall === "connect") ||
|
|
826
|
+
error.code === "UND_ERR_CONNECT_TIMEOUT";
|
|
827
|
+
}
|
|
828
|
+
|
|
764
829
|
/** The bare refresh_token grant: posts it, and returns just the new pair
|
|
765
830
|
* (never the rest of `stored`) so the caller decides which fields on the
|
|
766
831
|
* full record it belongs in - `accessToken`/`accessExpiresAt` for a plain
|
|
767
832
|
* OAuth record, `oauthAccessToken`/`oauthAccessExpiresAt` for a merged
|
|
768
833
|
* one's fallback (see oauthAccessToken's `fields`). */
|
|
769
834
|
async function refreshStoredTokens(stored, { fetchImpl, now }) {
|
|
770
|
-
const
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
835
|
+
const controller = new AbortController();
|
|
836
|
+
let timer;
|
|
837
|
+
let response, text;
|
|
838
|
+
try {
|
|
839
|
+
const deadline = new Promise((_, reject) => {
|
|
840
|
+
timer = setTimeout(() => {
|
|
841
|
+
controller.abort();
|
|
842
|
+
reject(new Error("Refresh response timed out."));
|
|
843
|
+
}, EXCHANGE_TIMEOUT_MS);
|
|
844
|
+
// A detached refresh must not keep an otherwise finished CLI alive.
|
|
845
|
+
timer.unref();
|
|
846
|
+
});
|
|
847
|
+
// Race the complete read as well as aborting fetch: injected transports
|
|
848
|
+
// (and broken streams) need not cooperate with AbortSignal.
|
|
849
|
+
({ response, text } = await Promise.race([(async () => {
|
|
850
|
+
let response;
|
|
851
|
+
try {
|
|
852
|
+
response = await fetchImpl(stored.tokenEndpoint, {
|
|
853
|
+
// Do not follow a redirect: a later DNS failure would not prove that
|
|
854
|
+
// the initial token endpoint never received this single-use token.
|
|
855
|
+
redirect: "manual", method: "POST", signal: controller.signal,
|
|
856
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
857
|
+
body: new URLSearchParams({ grant_type: "refresh_token",
|
|
858
|
+
refresh_token: stored.refreshToken, client_id: stored.clientId }),
|
|
859
|
+
});
|
|
860
|
+
} catch (cause) {
|
|
861
|
+
if (refreshRequestNotSent(cause)) {
|
|
862
|
+
throw Object.assign(new Error("Refresh request was not sent.", { cause }), { requestNotSent: true });
|
|
863
|
+
}
|
|
864
|
+
throw cause;
|
|
865
|
+
}
|
|
866
|
+
if (response.status >= 300 && response.status < 400) {
|
|
867
|
+
throw new Error("Refresh endpoint redirected; token rotation is uncertain.");
|
|
868
|
+
}
|
|
869
|
+
// Body errors cannot establish non-dispatch, even with a misleading
|
|
870
|
+
// code or adapter flag attached to them.
|
|
871
|
+
try { return { response, text: await response.text() }; }
|
|
872
|
+
catch (cause) { throw new Error("Refresh body was not received.", { cause }); }
|
|
873
|
+
})(), deadline]));
|
|
874
|
+
} catch (cause) {
|
|
875
|
+
if (cause?.requestNotSent === true) throw cause;
|
|
876
|
+
const error = new Error("Refresh response was not received; token rotation is uncertain.", { cause });
|
|
877
|
+
error.uncertain = true;
|
|
878
|
+
throw error;
|
|
879
|
+
} finally { clearTimeout(timer); }
|
|
780
880
|
let body;
|
|
781
881
|
try {
|
|
782
882
|
body = JSON.parse(text);
|
|
783
883
|
} catch {
|
|
784
|
-
|
|
884
|
+
const failure = new Error(`refresh: the token endpoint answered ${response.status} with unreadable JSON`);
|
|
885
|
+
if (!response.ok) failure.transient = true;
|
|
886
|
+
throw failure;
|
|
785
887
|
}
|
|
786
888
|
if (!response.ok || typeof body.access_token !== "string") {
|
|
787
|
-
const failure = new Error(`refresh:
|
|
889
|
+
const failure = new Error(`refresh: HTTP ${response.status}`);
|
|
788
890
|
// TERMINAL vs TRANSIENT, and the OAuth error code is the only honest way
|
|
789
891
|
// to tell them apart. `invalid_grant` means this refresh token will never
|
|
790
|
-
// work again; a 503
|
|
892
|
+
// work again; a received 503 means try later. A dropped connection
|
|
893
|
+
// cannot prove whether the single-use token was consumed. Marked on
|
|
791
894
|
// the error rather than decided here, because the caller is the one
|
|
792
895
|
// holding the refresh lock and the one that has to record it.
|
|
793
896
|
if (TERMINAL_REFRESH_ERRORS.has(body.error)) failure.terminal = true;
|
|
897
|
+
else if (!response.ok) failure.transient = true;
|
|
898
|
+
else failure.uncertain = true;
|
|
794
899
|
throw failure;
|
|
795
900
|
}
|
|
796
901
|
return {
|
|
797
902
|
accessToken: body.access_token,
|
|
798
903
|
// Rotation: a refresh token is single-use (board-oauth's own rule), so the
|
|
799
|
-
// new one replaces the old one.
|
|
800
|
-
//
|
|
801
|
-
|
|
802
|
-
refreshToken: typeof body.refresh_token === "string" ? body.refresh_token : stored.refreshToken,
|
|
904
|
+
// new one replaces the old one. An omitted token must never cause the
|
|
905
|
+
// consumed token to be presented again.
|
|
906
|
+
refreshToken: typeof body.refresh_token === "string" ? body.refresh_token : "",
|
|
803
907
|
accessExpiresAt: now() + Math.max(0, Number(body.expires_in) || 0) * 1000,
|
|
804
908
|
};
|
|
805
909
|
}
|
|
@@ -931,19 +1035,35 @@ async function discoverResource(fetchImpl, base, log) {
|
|
|
931
1035
|
return { resource: `${base}/mcp`, authorizationServerBase: base };
|
|
932
1036
|
}
|
|
933
1037
|
|
|
1038
|
+
/** The program and argument list that open `url` in the default browser, or
|
|
1039
|
+
* null when `url` is not a plain http(s) link. Never goes through a shell:
|
|
1040
|
+
* on Windows `cmd /c start` read each `&` in the link as a command separator
|
|
1041
|
+
* (the browser got a cut link, and anything after the `&` ran as a command),
|
|
1042
|
+
* so Windows uses rundll32, which gets the link as one argument. The link
|
|
1043
|
+
* comes from the app's discovery metadata, so a `file:` or other scheme is
|
|
1044
|
+
* refused too: the handler would run it. */
|
|
1045
|
+
export function browserCommand(url, platform = process.platform) {
|
|
1046
|
+
let parsed;
|
|
1047
|
+
try {
|
|
1048
|
+
parsed = new URL(String(url));
|
|
1049
|
+
} catch {
|
|
1050
|
+
return null;
|
|
1051
|
+
}
|
|
1052
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
|
|
1053
|
+
const link = String(url);
|
|
1054
|
+
if (platform === "darwin") return { file: "open", args: [link] };
|
|
1055
|
+
if (platform === "win32") return { file: "rundll32", args: ["url.dll,FileProtocolHandler", link] };
|
|
1056
|
+
return { file: "xdg-open", args: [link] };
|
|
1057
|
+
}
|
|
1058
|
+
|
|
934
1059
|
/** Open a URL in the person's default browser. Best-effort and silent on
|
|
935
1060
|
* failure - the caller always prints the URL too, which is the fallback that
|
|
936
1061
|
* matters on a headless box or an unfamiliar platform. */
|
|
937
|
-
export function openInBrowser(url) {
|
|
1062
|
+
export function openInBrowser(url, { platform = process.platform, spawnFn = spawn } = {}) {
|
|
938
1063
|
try {
|
|
939
|
-
const
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
? ["open", [url]]
|
|
943
|
-
: platform === "win32"
|
|
944
|
-
? ["cmd", ["/c", "start", "", url]]
|
|
945
|
-
: ["xdg-open", [url]];
|
|
946
|
-
const child = spawn(cmd, args, { stdio: "ignore", detached: true, windowsHide: true });
|
|
1064
|
+
const command = browserCommand(url, platform);
|
|
1065
|
+
if (!command) return false;
|
|
1066
|
+
const child = spawnFn(command.file, command.args, { stdio: "ignore", detached: true, windowsHide: true, shell: false });
|
|
947
1067
|
child.on("error", () => {});
|
|
948
1068
|
child.unref();
|
|
949
1069
|
return true;
|
|
@@ -29,7 +29,10 @@ export async function authenticatedJsonPost(url, body, options = {}) {
|
|
|
29
29
|
}, timeoutMs);
|
|
30
30
|
});
|
|
31
31
|
const boundedFetch = (target, init = {}) => {
|
|
32
|
-
controller.signal.
|
|
32
|
+
if (controller.signal.aborted) {
|
|
33
|
+
// Only this pre-dispatch boundary can prove a rotating token was not sent.
|
|
34
|
+
throw Object.assign(new Error('Request canceled before fetch.'), { requestNotSent: true });
|
|
35
|
+
}
|
|
33
36
|
return fetchImpl(target, { ...init, signal: init.signal ? AbortSignal.any([init.signal, controller.signal]) : controller.signal });
|
|
34
37
|
};
|
|
35
38
|
const post = async bearer => {
|
|
@@ -44,13 +47,17 @@ export async function authenticatedJsonPost(url, body, options = {}) {
|
|
|
44
47
|
return { response, text, payload };
|
|
45
48
|
};
|
|
46
49
|
const execute = async () => {
|
|
47
|
-
|
|
50
|
+
controller.signal.throwIfAborted();
|
|
51
|
+
// The shared refresh owns its finite deadline. This caller only stops
|
|
52
|
+
// waiting; it must not cancel another caller's rotating-token exchange.
|
|
53
|
+
const token = await hostedToken({ env, fetchImpl, forceRefresh });
|
|
48
54
|
controller.signal.throwIfAborted();
|
|
49
55
|
if (!token) return { authError: await reauthRequired(env) ? REAUTH_REQUIRED_HINT : NOT_SIGNED_IN_HINT };
|
|
50
56
|
let result = await post(token);
|
|
51
57
|
let lastBearer = token;
|
|
52
58
|
if (result.response.status === 401 && !forceRefresh) {
|
|
53
|
-
|
|
59
|
+
controller.signal.throwIfAborted();
|
|
60
|
+
const refreshed = await hostedToken({ env, fetchImpl, forceRefresh: true });
|
|
54
61
|
controller.signal.throwIfAborted();
|
|
55
62
|
if (refreshed && refreshed !== token) {
|
|
56
63
|
// A failed retry is a transport failure, not proof that the fresh
|
package/lib/boardside.mjs
CHANGED
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
// its own op (e.g. a `session_asks` view) and is not in this contract.
|
|
21
21
|
|
|
22
22
|
import { classifyExit } from "./exitClass.mjs";
|
|
23
|
+
import { lastAnswerIn, makeAnswerTracker } from "./answerTag.mjs";
|
|
23
24
|
import { callTool as hostedCallTool } from "./hosted.mjs";
|
|
24
25
|
|
|
25
26
|
/** The verdict, in words. The default set is the receipt's own (`finished` /
|
|
@@ -106,13 +107,12 @@ async function proposeOnBoard(session, ops, label, { callTool = hostedCallTool,
|
|
|
106
107
|
export async function commentOnAnchor(session, frameId, text, options = {}) {
|
|
107
108
|
if (!frameId) return null;
|
|
108
109
|
const { fields, ...rest } = options;
|
|
109
|
-
|
|
110
|
+
return proposeOnBoard(
|
|
110
111
|
session,
|
|
111
112
|
[{ call: "addComment", args: { id: frameId, text, ...(fields ?? {}) } }],
|
|
112
113
|
`Session ${session.key} outcome`,
|
|
113
114
|
rest,
|
|
114
115
|
);
|
|
115
|
-
return result.ok ? result.detail : null;
|
|
116
116
|
}
|
|
117
117
|
|
|
118
118
|
/** A question through `ask_user`, under the run's own session key. It lands as
|
|
@@ -120,14 +120,15 @@ export async function commentOnAnchor(session, frameId, text, options = {}) {
|
|
|
120
120
|
* circle of its own. Used for the one case the runner itself ever asks
|
|
121
121
|
* anything: a failed merge. Returns the question NOTE id parsed out of
|
|
122
122
|
* `ask_user`'s reply text (`pending (question_id: <noteId>)`), or null when the call failed or the id could not
|
|
123
|
-
* be found in the reply.
|
|
124
|
-
|
|
123
|
+
* be found in the reply. `askKey` makes the ask idempotent: the same key from
|
|
124
|
+
* the same session returns the note already asked (#5106). */
|
|
125
|
+
export async function askUserOnBoard(session, question, { why, fromId, options: choices, recommendation, images, purpose, askKey } = {}, options = {}) {
|
|
125
126
|
const outcome = await (options.callTool ?? hostedCallTool)(
|
|
126
127
|
"ask_user",
|
|
127
|
-
{ question, why, ...(fromId ? { from_id: fromId } : {}), ...(choices ? { options: choices } : {}), ...(recommendation ? { recommendation } : {}), ...(images?.length > 0 ? { images } : {}), ...(purpose ? { purpose } : {}) },
|
|
128
|
+
{ question, why, ...(fromId ? { from_id: fromId } : {}), ...(choices ? { options: choices } : {}), ...(recommendation ? { recommendation } : {}), ...(images?.length > 0 ? { images } : {}), ...(purpose ? { purpose } : {}), ...(askKey ? { ask_key: askKey } : {}) },
|
|
128
129
|
{ sessionKey: session.key, env: options.env },
|
|
129
130
|
);
|
|
130
|
-
if (outcome.isError) return { ok: false, detail: outcome.text };
|
|
131
|
+
if (outcome.isError) return { ok: false, detail: outcome.text, ...(outcome.refused === true ? { refused: true } : {}) };
|
|
131
132
|
const match = /question_id:\s*(\S+)\)/.exec(outcome.text ?? "");
|
|
132
133
|
return { ok: true, questionId: match?.[1] ?? null, detail: outcome.text };
|
|
133
134
|
}
|
|
@@ -138,12 +139,26 @@ export async function askUserOnBoard(session, question, { why, fromId, options:
|
|
|
138
139
|
// one line of figures. The hosted `addComment` on an idea lands it as a
|
|
139
140
|
// `reply` note carrying the agent, the run, a caption and the links.
|
|
140
141
|
|
|
141
|
-
/**
|
|
142
|
-
*
|
|
143
|
-
|
|
142
|
+
/** An explicitly delimited answer is the deliverable, not a coding handoff:
|
|
143
|
+
* preserve its whole shape. Other closing words are kept whole too; the hosted
|
|
144
|
+
* writer splits overflow into ideas (#3583), so nothing is cut here. */
|
|
144
145
|
export function closingTextOf(outcome) {
|
|
145
146
|
const raw = typeof outcome.envelope?.result === "string" ? outcome.envelope.result.trim() : "";
|
|
146
|
-
|
|
147
|
+
// A repo may require another message after the answer (#3611). Only the
|
|
148
|
+
// lead's explicit answer counts, never tool output or a subagent's reply.
|
|
149
|
+
// The envelope's own result wins; then the answer the child read as events
|
|
150
|
+
// streamed, which survives a log cut down by later tool output (#3634);
|
|
151
|
+
// then the log itself, for engines that do not stream one.
|
|
152
|
+
let answer = lastAnswerIn(raw) || (typeof outcome.answer === "string" ? outcome.answer : "");
|
|
153
|
+
if (!answer) {
|
|
154
|
+
const tracker = makeAnswerTracker();
|
|
155
|
+
for (const line of (outcome.log ?? "").split("\n")) {
|
|
156
|
+
try { tracker.push(JSON.parse(line)); } catch { /* A capped log can begin with a partial event. */ }
|
|
157
|
+
}
|
|
158
|
+
answer = tracker.answer();
|
|
159
|
+
}
|
|
160
|
+
if (answer) return answer;
|
|
161
|
+
return raw;
|
|
147
162
|
}
|
|
148
163
|
|
|
149
164
|
/** The first sentence of the closing words, for the circle's caption. */
|
|
@@ -171,7 +186,7 @@ export const IN_PLACE_NOTICE = "This ran in your folder itself, so Throw away ca
|
|
|
171
186
|
|
|
172
187
|
/** The reply's text and caption for a run that finished. Pure.
|
|
173
188
|
*
|
|
174
|
-
* The closing words
|
|
189
|
+
* The explicit answer (or the closing words, kept whole for the hosted splitter), then ONE line led by
|
|
175
190
|
* "Finished" that carries only how long it took: "Finished; 4m". The card
|
|
176
191
|
* footer reads "Took 4 minutes" (#470, #735); turns, the branch and the file
|
|
177
192
|
* count are developer words and stay on the session screen.
|
|
@@ -221,5 +236,6 @@ export async function reportOutcomeOnBoard(session, outcome, frameId, options =
|
|
|
221
236
|
// The plain line when a screen changed but no pictures could be taken (#2194).
|
|
222
237
|
const lines = [text, outcome.result?.fixAttempted && "Coding tried one fix.", outcome.picturesNote].filter(Boolean);
|
|
223
238
|
const closing = lines.join("\n\n");
|
|
224
|
-
|
|
239
|
+
const receipt = await commentOnAnchor(session, frameId, closing, { ...rest, fields });
|
|
240
|
+
return { landed: receipt?.ok === true && Boolean(closingTextOf(outcome)) };
|
|
225
241
|
}
|