@magpie-community/opencode-factory-auth 0.1.9 → 0.1.11
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 +27 -6
- package/index.mjs +113 -8
- package/package.json +3 -2
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
|
|
@@ -77,9 +86,10 @@ magpie plugin login factory
|
|
|
77
86
|
Factory's Anthropic route requires Droid's fixed client preamble and
|
|
78
87
|
refuses some of Claude Code's fixed environment, model and built-in skill
|
|
79
88
|
metadata. The plugin adapts that metadata while preserving the coding
|
|
80
|
-
instructions, environment values, tool definitions,
|
|
81
|
-
|
|
82
|
-
|
|
89
|
+
instructions, environment values, tool definitions, images and reasoning
|
|
90
|
+
options. Ordinary Droid requests remain unchanged, and OpenAI routes keep
|
|
91
|
+
their existing request adapter. Quoted fixed metadata in tool results is
|
|
92
|
+
handled as described below.
|
|
83
93
|
|
|
84
94
|
For the built-in `update-config` skill, the adapter changes only the known
|
|
85
95
|
self-reference "not Claude" to "not the assistant" inside a complete
|
|
@@ -95,6 +105,17 @@ without the initial environment paragraph. Updates beginning with the known
|
|
|
95
105
|
model paragraph and containing complete generated token metadata are
|
|
96
106
|
adapted too, including accumulated switches when resuming a conversation.
|
|
97
107
|
Token budgets, permission instructions and conversation history are preserved.
|
|
108
|
+
The same model-update adaptation covers updates that start with the complete
|
|
109
|
+
generated `# Environment update` block after a working-directory change.
|
|
110
|
+
|
|
111
|
+
Factory can also refuse fixed client phrases quoted in tool results, such as
|
|
112
|
+
the identity/environment definitions printed when inspecting this plugin's
|
|
113
|
+
source. Those text results are represented as JSON strings with explicit
|
|
114
|
+
decoding instructions and Unicode escapes for the fixed phrases. Decoding
|
|
115
|
+
the string recovers the exact original output, including quotes, backslashes
|
|
116
|
+
and Unicode; the plugin does not delete the output or replace its identities
|
|
117
|
+
with different ones. Tool ids, cache/error markers and non-text blocks stay
|
|
118
|
+
unchanged. Ordinary tool results are forwarded as before.
|
|
98
119
|
|
|
99
120
|
Use magpie's Claude Code integration to select the Factory provider.
|
|
100
121
|
magpie manages the provider-specific client settings, including capability
|
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
|
|
|
@@ -592,15 +596,17 @@ const CONFIG_SKILL_COMPAT = CONFIG_SKILL_METADATA.replace("not Claude", "not the
|
|
|
592
596
|
// Claude 5 also sends its runtime metadata as a string-content system
|
|
593
597
|
// message, instead of user-message reminders. Preserve that role and all
|
|
594
598
|
// instructions. A model switch sends a separate update without the
|
|
595
|
-
// environment paragraph
|
|
596
|
-
// generated token context before
|
|
599
|
+
// environment paragraph, sometimes following a working-directory update;
|
|
600
|
+
// require the generated opening block and complete token context before
|
|
601
|
+
// adapting either update shape.
|
|
597
602
|
const SYSTEM_ENV_CONTEXT = /^# Environment\nYou have been invoked in the following environment:[ \t]*\n(?: {1,2}- [^\n]*\n)+(?=\n|$)/
|
|
598
603
|
const SYSTEM_MODEL_CONTEXT = /(^|\n\n)You are powered by the model (?:named )?[^\n<>]+\.(?=\n\n|$)/g
|
|
599
604
|
const SYSTEM_MODEL_UPDATE = /^You are powered by the model (?:named )?[^\n<>]+\.(?=\n\n|$)/
|
|
605
|
+
const SYSTEM_ENV_UPDATE = /^# Environment update\n(?: {1,2}- [^\n]*\n)+(?=\n|$)/
|
|
600
606
|
const SYSTEM_TOKEN_CONTEXT = /(?:^|\n\n)<total_tokens>\d+ tokens left<\/total_tokens>(?=\n\n|$)/
|
|
601
607
|
function systemContext(text) {
|
|
602
608
|
const environment = SYSTEM_ENV_CONTEXT.test(text)
|
|
603
|
-
if (!environment && !(SYSTEM_MODEL_UPDATE.test(text) && SYSTEM_TOKEN_CONTEXT.test(text))) return text
|
|
609
|
+
if (!environment && !((SYSTEM_MODEL_UPDATE.test(text) || SYSTEM_ENV_UPDATE.test(text)) && SYSTEM_TOKEN_CONTEXT.test(text))) return text
|
|
604
610
|
let out = text.replace(SYSTEM_MODEL_CONTEXT, (paragraph) => paragraph
|
|
605
611
|
.replace("You are powered by the model named", "Current model name:")
|
|
606
612
|
.replace("You are powered by the model", "Current model:")
|
|
@@ -618,6 +624,23 @@ function systemContext(text) {
|
|
|
618
624
|
return out
|
|
619
625
|
}
|
|
620
626
|
|
|
627
|
+
// Factory also refuses these fixed client phrases when they are quoted in
|
|
628
|
+
// tool output, e.g. while reading this adapter's source. Keep the original
|
|
629
|
+
// text recoverable: a JSON string with explicit decoding instructions,
|
|
630
|
+
// rather than deleting or rewriting the file's contents. Other output and
|
|
631
|
+
// the tool's id, error/cache markers and non-text blocks stay untouched.
|
|
632
|
+
const QUOTED_TOOL_PREFIX = "Tool output encoded as a JSON string. Decode the JSON string to recover the exact original text before using it:\n"
|
|
633
|
+
function quotedToolText(text) {
|
|
634
|
+
if (![...CLAUDE_IDENTITIES].some((identity) => text.includes(identity)) &&
|
|
635
|
+
!text.includes("You have been invoked in the following environment:") &&
|
|
636
|
+
!text.includes("x-anthropic-billing-header: cc_version=")) return text
|
|
637
|
+
let encoded = JSON.stringify(text)
|
|
638
|
+
for (const phrase of ["You are", "You have", "x-anthropic-billing-header", "system-reminder"]) {
|
|
639
|
+
encoded = encoded.replaceAll(phrase, "\\u" + phrase.charCodeAt(0).toString(16).padStart(4, "0") + phrase.slice(1))
|
|
640
|
+
}
|
|
641
|
+
return QUOTED_TOOL_PREFIX + encoded
|
|
642
|
+
}
|
|
643
|
+
|
|
621
644
|
function anthropicBody(body) {
|
|
622
645
|
let request
|
|
623
646
|
try {
|
|
@@ -685,6 +708,25 @@ function anthropicBody(body) {
|
|
|
685
708
|
}
|
|
686
709
|
if (message?.role !== "user" || !Array.isArray(message.content)) continue
|
|
687
710
|
for (const block of message.content) {
|
|
711
|
+
if (block?.type === "tool_result") {
|
|
712
|
+
if (typeof block.content === "string") {
|
|
713
|
+
const adapted = quotedToolText(block.content)
|
|
714
|
+
if (adapted !== block.content) {
|
|
715
|
+
block.content = adapted
|
|
716
|
+
changed = true
|
|
717
|
+
}
|
|
718
|
+
} else if (Array.isArray(block.content)) {
|
|
719
|
+
for (const part of block.content) {
|
|
720
|
+
if (part?.type !== "text" || typeof part.text !== "string") continue
|
|
721
|
+
const adapted = quotedToolText(part.text)
|
|
722
|
+
if (adapted !== part.text) {
|
|
723
|
+
part.text = adapted
|
|
724
|
+
changed = true
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
continue
|
|
729
|
+
}
|
|
688
730
|
if (block?.type !== "text" || typeof block.text !== "string") continue
|
|
689
731
|
if (ENV_REMINDER.test(block.text)) {
|
|
690
732
|
block.text = block.text.replace("# Environment", "# Runtime context")
|
|
@@ -719,6 +761,24 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
719
761
|
lock = run.catch(() => {})
|
|
720
762
|
return run
|
|
721
763
|
}
|
|
764
|
+
// renewed is what each refresh this process ran gave, by the refresh
|
|
765
|
+
// token it spent: a sign-in still holding that one (magpie not yet
|
|
766
|
+
// saving what auth.refresh gave, or a save that failed) goes on with
|
|
767
|
+
// the new tokens rather than spending the old one again
|
|
768
|
+
const renewed = new Map()
|
|
769
|
+
const took = (spent, c) => {
|
|
770
|
+
for (const [k, v] of renewed) if (v.expires > 0 && Date.now() >= v.expires) renewed.delete(k)
|
|
771
|
+
renewed.set(spent, { access: c.access, refresh: c.refresh, expires: c.expires, orgId: c.orgId, activeOrganizationId: c.activeOrganizationId, region: c.region, premBaseHost: c.premBaseHost })
|
|
772
|
+
}
|
|
773
|
+
// latest is c with the newest tokens this process got for it
|
|
774
|
+
const latest = (c) => {
|
|
775
|
+
for (let i = 0; i < 16 && c.refresh; i++) {
|
|
776
|
+
const got = renewed.get(c.refresh)
|
|
777
|
+
if (!got || got.access === c.access || (c.expires > 0 && got.expires > 0 && got.expires <= c.expires)) break
|
|
778
|
+
c = { ...c, ...got }
|
|
779
|
+
}
|
|
780
|
+
return c
|
|
781
|
+
}
|
|
722
782
|
// when each account last asked whoami for its org, so one whoami can't
|
|
723
783
|
// answer doesn't ask before every request, nor hold back the others
|
|
724
784
|
const asked = new Map()
|
|
@@ -781,16 +841,17 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
781
841
|
// it was, the built-in's clearing of the account's lapse.
|
|
782
842
|
const fresh = (renewed) =>
|
|
783
843
|
locked(async () => {
|
|
784
|
-
const c = await current()
|
|
844
|
+
const c = latest(await current())
|
|
785
845
|
if (c.key) return keyed(c) // an API key: nothing to renew, and no org with it
|
|
786
846
|
if ((c.expires > 0 && Date.now() < c.expires - REFRESH_LEAD) || !c.refresh) return orgOf(c)
|
|
847
|
+
const spent = c.refresh
|
|
787
848
|
let t
|
|
788
849
|
try {
|
|
789
|
-
t = await renew(
|
|
850
|
+
t = await renew(spent, "")
|
|
790
851
|
} catch (e) {
|
|
791
852
|
// a hiccup while the token still runs: go on with it
|
|
792
853
|
if (!refused(e) && c.expires > 0 && Date.now() < c.expires) return orgOf(c)
|
|
793
|
-
if (refused(e)) throw
|
|
854
|
+
if (refused(e)) throw lapsed(c, e)
|
|
794
855
|
throw e
|
|
795
856
|
}
|
|
796
857
|
c.access = t.access_token
|
|
@@ -799,6 +860,7 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
799
860
|
// droid asks whoami again for each new token, keeping the org it names
|
|
800
861
|
await reconcile(c)
|
|
801
862
|
ask(c)
|
|
863
|
+
took(spent, c)
|
|
802
864
|
await save(c)
|
|
803
865
|
renewed?.()
|
|
804
866
|
return c
|
|
@@ -814,7 +876,7 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
814
876
|
locked(async () => {
|
|
815
877
|
if (status !== 403) return false
|
|
816
878
|
const isOrg = orgRefused(status, text)
|
|
817
|
-
const c = await current()
|
|
879
|
+
const c = latest(await current())
|
|
818
880
|
if (c.key) return false // an API key carries no org droid would send
|
|
819
881
|
if (c.activeOrganizationId) {
|
|
820
882
|
if (!isOrg) return false // the org was sent: the refusal is about something else
|
|
@@ -839,9 +901,10 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
839
901
|
org = await firstOrg(c)
|
|
840
902
|
} catch {}
|
|
841
903
|
if (!org) return false
|
|
904
|
+
const spent = c.refresh
|
|
842
905
|
let t
|
|
843
906
|
try {
|
|
844
|
-
t = await renew(
|
|
907
|
+
t = await renew(spent, org)
|
|
845
908
|
} catch {
|
|
846
909
|
return false
|
|
847
910
|
}
|
|
@@ -849,6 +912,7 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
849
912
|
c.expires = expiry(t.access_token)
|
|
850
913
|
c.orgId = org
|
|
851
914
|
if (t.refresh_token) c.refresh = t.refresh_token
|
|
915
|
+
took(spent, c)
|
|
852
916
|
await save(c)
|
|
853
917
|
renewed?.()
|
|
854
918
|
return true
|
|
@@ -890,6 +954,18 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
890
954
|
return { fresh, mendOrg, usage }
|
|
891
955
|
}
|
|
892
956
|
|
|
957
|
+
// lapsed is WorkOS refusing c's refresh token for good: the account
|
|
958
|
+
// needs signing in again
|
|
959
|
+
const lapsed = (c, e) =>
|
|
960
|
+
Object.assign(new Error(`${c.accountId || "the account"}'s Factory sign-in has expired — sign in again (${e.message})`), { lapsed: true, signIn: "expired" })
|
|
961
|
+
|
|
962
|
+
// renewal is what of c magpie keeps over the stored sign-in
|
|
963
|
+
const renewal = (c) => {
|
|
964
|
+
const out = { access: c.access, refresh: c.refresh, expires: c.expires }
|
|
965
|
+
for (const k of ["orgId", "activeOrganizationId", "region", "premBaseHost"]) if (typeof c[k] === "string") out[k] = c[k]
|
|
966
|
+
return out
|
|
967
|
+
}
|
|
968
|
+
|
|
893
969
|
return {
|
|
894
970
|
config: async (config) => {
|
|
895
971
|
config.provider ??= {}
|
|
@@ -913,6 +989,35 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
913
989
|
// droid's FACTORY_API_KEY: the key is the bearer, never renewed
|
|
914
990
|
{ type: "api", label: "Factory API key (fk-…)", placeholder: "fk-…" },
|
|
915
991
|
],
|
|
992
|
+
// magpie renews the sign-in MAGPIE_LEAD before its end, before its
|
|
993
|
+
// requests and usage ask for it, and saves what this gives. Under
|
|
994
|
+
// the same lock as the renewal before a request, so the two never
|
|
995
|
+
// spend one refresh token; that check stays for OpenCode, which
|
|
996
|
+
// doesn't call this
|
|
997
|
+
refreshLead: MAGPIE_LEAD,
|
|
998
|
+
async refresh(auth) {
|
|
999
|
+
if (auth?.type !== "oauth" || !auth.access || !auth.refresh) return undefined
|
|
1000
|
+
return locked(async () => {
|
|
1001
|
+
const c = latest({ ...auth })
|
|
1002
|
+
// renewed here already, the store not yet saying so
|
|
1003
|
+
if (c.access !== auth.access && c.expires > 0 && Date.now() < c.expires - MAGPIE_LEAD) return renewal(c)
|
|
1004
|
+
const spent = c.refresh
|
|
1005
|
+
let t
|
|
1006
|
+
try {
|
|
1007
|
+
t = await renew(spent, "")
|
|
1008
|
+
} catch (e) {
|
|
1009
|
+
if (refused(e)) throw lapsed(c, e)
|
|
1010
|
+
throw e
|
|
1011
|
+
}
|
|
1012
|
+
c.access = t.access_token
|
|
1013
|
+
c.expires = expiry(t.access_token)
|
|
1014
|
+
if (t.refresh_token) c.refresh = t.refresh_token
|
|
1015
|
+
await reconcile(c)
|
|
1016
|
+
ask(c)
|
|
1017
|
+
took(spent, c)
|
|
1018
|
+
return renewal(c)
|
|
1019
|
+
})
|
|
1020
|
+
},
|
|
916
1021
|
// magpie's own hook: the account's limits
|
|
917
1022
|
async usage(getAuth) {
|
|
918
1023
|
return account(getAuth).usage()
|
package/package.json
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@magpie-community/opencode-factory-auth",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.11",
|
|
4
4
|
"description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.mjs",
|
|
7
7
|
"files": ["index.mjs", "README.md"],
|
|
8
8
|
"keywords": ["opencode", "opencode-plugin", "magpie", "factory", "droid"],
|
|
9
|
-
"license": "MIT"
|
|
9
|
+
"license": "MIT",
|
|
10
|
+
"repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/factory" }
|
|
10
11
|
}
|