@magpie-community/opencode-factory-auth 0.1.10 → 0.1.12
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/README.md +12 -3
- package/index.mjs +118 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -29,9 +29,18 @@ The sign-in is kept wherever the host keeps provider sign-ins:
|
|
|
29
29
|
It holds WorkOS's access and refresh tokens, with the organization,
|
|
30
30
|
region and host.
|
|
31
31
|
|
|
32
|
-
**Refreshing.**
|
|
33
|
-
|
|
34
|
-
|
|
32
|
+
**Refreshing.**
|
|
33
|
+
- magpie renews the access token three minutes before it lapses, through
|
|
34
|
+
the plugin's `auth.refresh`, once for the account and before its
|
|
35
|
+
requests and usage need it; magpie saves the new tokens. OpenCode
|
|
36
|
+
doesn't call that hook: there the token is renewed two minutes before it
|
|
37
|
+
lapses, before a request, and the plugin saves it.
|
|
38
|
+
- WorkOS rotates the refresh token, so the plugin never runs two refreshes
|
|
39
|
+
at once, and never spends one refresh token twice: a request that comes
|
|
40
|
+
before magpie has saved a renewal goes on with the new tokens.
|
|
41
|
+
- The account counts as signed out only when WorkOS refuses the refresh
|
|
42
|
+
token (a 4xx other than 429). Any other failure keeps the sign-in, and
|
|
43
|
+
the current token is used while it lasts.
|
|
35
44
|
|
|
36
45
|
**Refusals.** If Factory refuses the organization a request names, the
|
|
37
46
|
plugin asks `whoami` again and resends the request once. If the refusal
|
package/index.mjs
CHANGED
|
@@ -16,6 +16,10 @@ const CLIENT_ID = "client_01HNM792M5G5G1A2THWPXKFMXB"
|
|
|
16
16
|
const VERSION = "0.231.0"
|
|
17
17
|
// how long before an access token lapses it is renewed (droid: a minute)
|
|
18
18
|
const REFRESH_LEAD = 2 * 60 * 1000
|
|
19
|
+
// and how long before, magpie renews it ahead of time (auth.refresh): a
|
|
20
|
+
// minute more, so under magpie the check before a request finds it fresh.
|
|
21
|
+
// WorkOS's access tokens are short-lived, so not much more
|
|
22
|
+
const MAGPIE_LEAD = 3 * 60 * 1000
|
|
19
23
|
// how long an account whose whoami failed waits before asking again
|
|
20
24
|
const ASK_AGAIN = 10 * 60 * 1000
|
|
21
25
|
|
|
@@ -600,7 +604,20 @@ const SYSTEM_MODEL_CONTEXT = /(^|\n\n)You are powered by the model (?:named )?[^
|
|
|
600
604
|
const SYSTEM_MODEL_UPDATE = /^You are powered by the model (?:named )?[^\n<>]+\.(?=\n\n|$)/
|
|
601
605
|
const SYSTEM_ENV_UPDATE = /^# Environment update\n(?: {1,2}- [^\n]*\n)+(?=\n|$)/
|
|
602
606
|
const SYSTEM_TOKEN_CONTEXT = /(?:^|\n\n)<total_tokens>\d+ tokens left<\/total_tokens>(?=\n\n|$)/
|
|
607
|
+
// A SessionStart hook's output comes ahead of the generated context in the
|
|
608
|
+
// same message (Claude Code 2.1.288 with a hook installed, #634): the
|
|
609
|
+
// context after it is adapted as it would be on its own, the hook's output
|
|
610
|
+
// is left as it is.
|
|
611
|
+
const HOOK_OUTPUT = /^SessionStart:[^\n]* hook success:/
|
|
612
|
+
const HOOK_CONTEXT = "\n# Environment\nYou have been invoked in the following environment:"
|
|
603
613
|
function systemContext(text) {
|
|
614
|
+
if (HOOK_OUTPUT.test(text)) {
|
|
615
|
+
const at = text.indexOf(HOOK_CONTEXT)
|
|
616
|
+
return at < 0 ? text : text.slice(0, at + 1) + generatedContext(text.slice(at + 1))
|
|
617
|
+
}
|
|
618
|
+
return generatedContext(text)
|
|
619
|
+
}
|
|
620
|
+
function generatedContext(text) {
|
|
604
621
|
const environment = SYSTEM_ENV_CONTEXT.test(text)
|
|
605
622
|
if (!environment && !((SYSTEM_MODEL_UPDATE.test(text) || SYSTEM_ENV_UPDATE.test(text)) && SYSTEM_TOKEN_CONTEXT.test(text))) return text
|
|
606
623
|
let out = text.replace(SYSTEM_MODEL_CONTEXT, (paragraph) => paragraph
|
|
@@ -620,6 +637,22 @@ function systemContext(text) {
|
|
|
620
637
|
return out
|
|
621
638
|
}
|
|
622
639
|
|
|
640
|
+
// The model line inside a system prompt (Claude Desktop's, #634) is the
|
|
641
|
+
// same generated sentence as in a reminder; only that line changes.
|
|
642
|
+
const SYSTEM_MODEL_LINE = /(^|\n)You are powered by the model [^\n<>]+/g
|
|
643
|
+
function systemModelLine(text) {
|
|
644
|
+
return text.replace(SYSTEM_MODEL_LINE, (line) => line
|
|
645
|
+
.replace("You are powered by the model named", "Current model name:")
|
|
646
|
+
.replace("You are powered by the model", "Current model:")
|
|
647
|
+
.replace("The exact model ID is", "Model ID:")
|
|
648
|
+
.replace("Assistant knowledge cutoff is", "Model knowledge cutoff:"))
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// The reminder carrying CLAUDE.md files names the global one with a phrase
|
|
652
|
+
// Factory refuses; only that phrase in the generated reminder changes.
|
|
653
|
+
const INSTRUCTIONS_REMINDER = "<system-reminder>\nCodebase and user instructions are shown below"
|
|
654
|
+
const GLOBAL_INSTRUCTIONS = "(user's private global instructions for all projects)"
|
|
655
|
+
|
|
623
656
|
// Factory also refuses these fixed client phrases when they are quoted in
|
|
624
657
|
// tool output, e.g. while reading this adapter's source. Keep the original
|
|
625
658
|
// text recoverable: a JSON string with explicit decoding instructions,
|
|
@@ -672,6 +705,12 @@ function anthropicBody(body) {
|
|
|
672
705
|
if (block?.type === "text" && CLAUDE_IDENTITIES.has(block.text)) {
|
|
673
706
|
block.text = DROID_LINE
|
|
674
707
|
changed = true
|
|
708
|
+
} else if (block?.type === "text") {
|
|
709
|
+
const adapted = systemModelLine(block.text)
|
|
710
|
+
if (adapted !== block.text) {
|
|
711
|
+
block.text = adapted
|
|
712
|
+
changed = true
|
|
713
|
+
}
|
|
675
714
|
}
|
|
676
715
|
kept.push(block)
|
|
677
716
|
}
|
|
@@ -724,7 +763,17 @@ function anthropicBody(body) {
|
|
|
724
763
|
continue
|
|
725
764
|
}
|
|
726
765
|
if (block?.type !== "text" || typeof block.text !== "string") continue
|
|
727
|
-
if (
|
|
766
|
+
if (block.text.startsWith(INSTRUCTIONS_REMINDER) && block.text.includes(GLOBAL_INSTRUCTIONS)) {
|
|
767
|
+
block.text = block.text.replaceAll(GLOBAL_INSTRUCTIONS, "(global instructions)")
|
|
768
|
+
changed = true
|
|
769
|
+
} else if (HOOK_OUTPUT.test(block.text)) {
|
|
770
|
+
// a system message folded into the user's turn on its way here
|
|
771
|
+
const adapted = systemContext(block.text)
|
|
772
|
+
if (adapted !== block.text) {
|
|
773
|
+
block.text = adapted
|
|
774
|
+
changed = true
|
|
775
|
+
}
|
|
776
|
+
} else if (ENV_REMINDER.test(block.text)) {
|
|
728
777
|
block.text = block.text.replace("# Environment", "# Runtime context")
|
|
729
778
|
.replace("You have been invoked in the following environment:", "The session environment is:")
|
|
730
779
|
changed = true
|
|
@@ -757,6 +806,24 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
757
806
|
lock = run.catch(() => {})
|
|
758
807
|
return run
|
|
759
808
|
}
|
|
809
|
+
// renewed is what each refresh this process ran gave, by the refresh
|
|
810
|
+
// token it spent: a sign-in still holding that one (magpie not yet
|
|
811
|
+
// saving what auth.refresh gave, or a save that failed) goes on with
|
|
812
|
+
// the new tokens rather than spending the old one again
|
|
813
|
+
const renewed = new Map()
|
|
814
|
+
const took = (spent, c) => {
|
|
815
|
+
for (const [k, v] of renewed) if (v.expires > 0 && Date.now() >= v.expires) renewed.delete(k)
|
|
816
|
+
renewed.set(spent, { access: c.access, refresh: c.refresh, expires: c.expires, orgId: c.orgId, activeOrganizationId: c.activeOrganizationId, region: c.region, premBaseHost: c.premBaseHost })
|
|
817
|
+
}
|
|
818
|
+
// latest is c with the newest tokens this process got for it
|
|
819
|
+
const latest = (c) => {
|
|
820
|
+
for (let i = 0; i < 16 && c.refresh; i++) {
|
|
821
|
+
const got = renewed.get(c.refresh)
|
|
822
|
+
if (!got || got.access === c.access || (c.expires > 0 && got.expires > 0 && got.expires <= c.expires)) break
|
|
823
|
+
c = { ...c, ...got }
|
|
824
|
+
}
|
|
825
|
+
return c
|
|
826
|
+
}
|
|
760
827
|
// when each account last asked whoami for its org, so one whoami can't
|
|
761
828
|
// answer doesn't ask before every request, nor hold back the others
|
|
762
829
|
const asked = new Map()
|
|
@@ -819,16 +886,17 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
819
886
|
// it was, the built-in's clearing of the account's lapse.
|
|
820
887
|
const fresh = (renewed) =>
|
|
821
888
|
locked(async () => {
|
|
822
|
-
const c = await current()
|
|
889
|
+
const c = latest(await current())
|
|
823
890
|
if (c.key) return keyed(c) // an API key: nothing to renew, and no org with it
|
|
824
891
|
if ((c.expires > 0 && Date.now() < c.expires - REFRESH_LEAD) || !c.refresh) return orgOf(c)
|
|
892
|
+
const spent = c.refresh
|
|
825
893
|
let t
|
|
826
894
|
try {
|
|
827
|
-
t = await renew(
|
|
895
|
+
t = await renew(spent, "")
|
|
828
896
|
} catch (e) {
|
|
829
897
|
// a hiccup while the token still runs: go on with it
|
|
830
898
|
if (!refused(e) && c.expires > 0 && Date.now() < c.expires) return orgOf(c)
|
|
831
|
-
if (refused(e)) throw
|
|
899
|
+
if (refused(e)) throw lapsed(c, e)
|
|
832
900
|
throw e
|
|
833
901
|
}
|
|
834
902
|
c.access = t.access_token
|
|
@@ -837,6 +905,7 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
837
905
|
// droid asks whoami again for each new token, keeping the org it names
|
|
838
906
|
await reconcile(c)
|
|
839
907
|
ask(c)
|
|
908
|
+
took(spent, c)
|
|
840
909
|
await save(c)
|
|
841
910
|
renewed?.()
|
|
842
911
|
return c
|
|
@@ -852,7 +921,7 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
852
921
|
locked(async () => {
|
|
853
922
|
if (status !== 403) return false
|
|
854
923
|
const isOrg = orgRefused(status, text)
|
|
855
|
-
const c = await current()
|
|
924
|
+
const c = latest(await current())
|
|
856
925
|
if (c.key) return false // an API key carries no org droid would send
|
|
857
926
|
if (c.activeOrganizationId) {
|
|
858
927
|
if (!isOrg) return false // the org was sent: the refusal is about something else
|
|
@@ -877,9 +946,10 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
877
946
|
org = await firstOrg(c)
|
|
878
947
|
} catch {}
|
|
879
948
|
if (!org) return false
|
|
949
|
+
const spent = c.refresh
|
|
880
950
|
let t
|
|
881
951
|
try {
|
|
882
|
-
t = await renew(
|
|
952
|
+
t = await renew(spent, org)
|
|
883
953
|
} catch {
|
|
884
954
|
return false
|
|
885
955
|
}
|
|
@@ -887,6 +957,7 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
887
957
|
c.expires = expiry(t.access_token)
|
|
888
958
|
c.orgId = org
|
|
889
959
|
if (t.refresh_token) c.refresh = t.refresh_token
|
|
960
|
+
took(spent, c)
|
|
890
961
|
await save(c)
|
|
891
962
|
renewed?.()
|
|
892
963
|
return true
|
|
@@ -928,6 +999,18 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
928
999
|
return { fresh, mendOrg, usage }
|
|
929
1000
|
}
|
|
930
1001
|
|
|
1002
|
+
// lapsed is WorkOS refusing c's refresh token for good: the account
|
|
1003
|
+
// needs signing in again
|
|
1004
|
+
const lapsed = (c, e) =>
|
|
1005
|
+
Object.assign(new Error(`${c.accountId || "the account"}'s Factory sign-in has expired — sign in again (${e.message})`), { lapsed: true, signIn: "expired" })
|
|
1006
|
+
|
|
1007
|
+
// renewal is what of c magpie keeps over the stored sign-in
|
|
1008
|
+
const renewal = (c) => {
|
|
1009
|
+
const out = { access: c.access, refresh: c.refresh, expires: c.expires }
|
|
1010
|
+
for (const k of ["orgId", "activeOrganizationId", "region", "premBaseHost"]) if (typeof c[k] === "string") out[k] = c[k]
|
|
1011
|
+
return out
|
|
1012
|
+
}
|
|
1013
|
+
|
|
931
1014
|
return {
|
|
932
1015
|
config: async (config) => {
|
|
933
1016
|
config.provider ??= {}
|
|
@@ -951,6 +1034,35 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
951
1034
|
// droid's FACTORY_API_KEY: the key is the bearer, never renewed
|
|
952
1035
|
{ type: "api", label: "Factory API key (fk-…)", placeholder: "fk-…" },
|
|
953
1036
|
],
|
|
1037
|
+
// magpie renews the sign-in MAGPIE_LEAD before its end, before its
|
|
1038
|
+
// requests and usage ask for it, and saves what this gives. Under
|
|
1039
|
+
// the same lock as the renewal before a request, so the two never
|
|
1040
|
+
// spend one refresh token; that check stays for OpenCode, which
|
|
1041
|
+
// doesn't call this
|
|
1042
|
+
refreshLead: MAGPIE_LEAD,
|
|
1043
|
+
async refresh(auth) {
|
|
1044
|
+
if (auth?.type !== "oauth" || !auth.access || !auth.refresh) return undefined
|
|
1045
|
+
return locked(async () => {
|
|
1046
|
+
const c = latest({ ...auth })
|
|
1047
|
+
// renewed here already, the store not yet saying so
|
|
1048
|
+
if (c.access !== auth.access && c.expires > 0 && Date.now() < c.expires - MAGPIE_LEAD) return renewal(c)
|
|
1049
|
+
const spent = c.refresh
|
|
1050
|
+
let t
|
|
1051
|
+
try {
|
|
1052
|
+
t = await renew(spent, "")
|
|
1053
|
+
} catch (e) {
|
|
1054
|
+
if (refused(e)) throw lapsed(c, e)
|
|
1055
|
+
throw e
|
|
1056
|
+
}
|
|
1057
|
+
c.access = t.access_token
|
|
1058
|
+
c.expires = expiry(t.access_token)
|
|
1059
|
+
if (t.refresh_token) c.refresh = t.refresh_token
|
|
1060
|
+
await reconcile(c)
|
|
1061
|
+
ask(c)
|
|
1062
|
+
took(spent, c)
|
|
1063
|
+
return renewal(c)
|
|
1064
|
+
})
|
|
1065
|
+
},
|
|
954
1066
|
// magpie's own hook: the account's limits
|
|
955
1067
|
async usage(getAuth) {
|
|
956
1068
|
return account(getAuth).usage()
|