@avi2dg/subquo 0.0.0 → 0.1.0
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/.bun-version +1 -0
- package/.github/actions/setup/action.yml +21 -0
- package/.github/actions/setup/bun-without-unzip.sh +20 -0
- package/.github/workflows/ci.yml +177 -0
- package/.github/workflows/main.yml +108 -0
- package/.github/workflows/mutation.yml +106 -0
- package/.github/workflows/pr-title.yml +43 -0
- package/.github/workflows/release.yml +34 -0
- package/.jscpd.json +5 -0
- package/.no-mistakes.yaml +3 -0
- package/AGENTS.md +15 -0
- package/CHANGELOG.md +21 -0
- package/CLAUDE.md +2 -0
- package/LICENSE +21 -0
- package/README.md +80 -0
- package/VISION.md +39 -0
- package/bun.lock +909 -0
- package/bunfig.toml +3 -0
- package/checks.config.ts +7 -0
- package/docs/accounts.md +55 -0
- package/docs/design.md +122 -0
- package/docs/shadow-run.md +49 -0
- package/docs/stage-1-findings.md +65 -0
- package/knip.config.ts +3 -0
- package/oxlint.config.ts +3 -0
- package/package.json +45 -3
- package/scripts/release-assets.ts +28 -0
- package/src/accounts.ts +62 -0
- package/src/cli.ts +122 -0
- package/src/codex-credentials.ts +1 -0
- package/src/collect.ts +45 -0
- package/src/collectors.ts +210 -0
- package/src/index.ts +146 -0
- package/src/keychain.ts +25 -0
- package/src/launch.ts +21 -0
- package/src/pi-codex.ts +17 -0
- package/src/renewal.ts +158 -0
- package/src/storage.ts +48 -0
- package/src/usage.ts +400 -0
- package/stryker.conf.mjs +3 -0
- package/templates/adr.md +32 -0
- package/templates/agents.md +9 -0
- package/templates/changelog.md +39 -0
- package/templates/claude.md +2 -0
- package/templates/explanation.md +15 -0
- package/templates/how-to.md +33 -0
- package/templates/readme.md +48 -0
- package/templates/reference.md +15 -0
- package/templates/tutorial.md +31 -0
- package/templates/vision.md +16 -0
- package/tests/e2e/cli.test.ts +193 -0
- package/tests/e2e/npm-package.test.ts +30 -0
- package/tests/e2e/release-assets.test.ts +53 -0
- package/tests/fixtures/snapshots/fresh.json +54 -0
- package/tests/fixtures/snapshots/incomplete.json +66 -0
- package/tests/unit/collect.test.ts +51 -0
- package/tests/unit/collectors.test.ts +401 -0
- package/tests/unit/no-mistakes.test.ts +8 -0
- package/tests/unit/renewal.test.ts +17 -0
- package/tests/unit/snapshot.test.ts +169 -0
- package/tsconfig.json +46 -0
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { Clock, Effect, FileSystem, Predicate, Result } from "effect";
|
|
2
|
+
import type { EnrolledAccount } from "./accounts";
|
|
3
|
+
import { readKeychainPassword } from "./keychain";
|
|
4
|
+
import type { Reading } from "./collect";
|
|
5
|
+
import {
|
|
6
|
+
measuredAt,
|
|
7
|
+
parseClaudeCredentials,
|
|
8
|
+
parseClaudeUsagePayload,
|
|
9
|
+
parseCodexCredentials,
|
|
10
|
+
parseCodexUsagePayload,
|
|
11
|
+
parseJson,
|
|
12
|
+
parseOpenCodeKey,
|
|
13
|
+
parseOpenCodeUsagePayload,
|
|
14
|
+
type ClaudeCredentials,
|
|
15
|
+
} from "./usage";
|
|
16
|
+
import type { CodexCredentials } from "./codex-credentials";
|
|
17
|
+
|
|
18
|
+
const ClaudeUsageUrl = "https://api.anthropic.com/api/oauth/usage";
|
|
19
|
+
const CodexUsageUrls = ["https://chatgpt.com/backend-api/wham/usage", "https://chatgpt.com/backend-api/codex/usage"];
|
|
20
|
+
const OpenCodeUsageUrl = "https://opencode.ai/zen/go/v1/usage";
|
|
21
|
+
|
|
22
|
+
type FetchInit = { readonly headers: Record<string, string>; readonly signal: AbortSignal; readonly redirect: "error" };
|
|
23
|
+
export type FetchImpl = (url: string, init: FetchInit) => Promise<Response>;
|
|
24
|
+
|
|
25
|
+
type FetchOutcome =
|
|
26
|
+
| { readonly kind: "limited" }
|
|
27
|
+
| { readonly kind: "timedOut" }
|
|
28
|
+
| { readonly kind: "unverified" }
|
|
29
|
+
| { readonly kind: "response"; readonly response: Response };
|
|
30
|
+
|
|
31
|
+
function expiredAtRejection(expiresAt: number | undefined, rejectedAt: number): boolean {
|
|
32
|
+
return expiresAt !== undefined && expiresAt <= rejectedAt;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const required: Reading = { code: "auth_required" };
|
|
36
|
+
const limited: Reading = { code: "rate_limited" };
|
|
37
|
+
const timedOut: Reading = { code: "timeout" };
|
|
38
|
+
const unverified: Reading = { code: "auth_unverified" };
|
|
39
|
+
|
|
40
|
+
function aborted(error: unknown): boolean {
|
|
41
|
+
return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function attemptFetch(url: string, init: FetchInit, fetchImpl: FetchImpl): Promise<FetchOutcome> {
|
|
45
|
+
return fetchImpl(url, init).then(
|
|
46
|
+
(response) => (response.status === 429 ? { kind: "limited" } : { kind: "response", response }),
|
|
47
|
+
(error: unknown) => (aborted(error) ? { kind: "timedOut" } : { kind: "unverified" }),
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const fetchOutcome = (url: string, headers: Record<string, string>, fetchImpl: FetchImpl) =>
|
|
52
|
+
Effect.promise((signal) => attemptFetch(url, {
|
|
53
|
+
headers, signal: AbortSignal.any([signal, AbortSignal.timeout(4_500)]), redirect: "error",
|
|
54
|
+
}, fetchImpl));
|
|
55
|
+
|
|
56
|
+
const readBody = Effect.fnUntraced(function*(response: Response) {
|
|
57
|
+
const text = yield* Effect.promise(() => response.text().then((value) => value, () => undefined));
|
|
58
|
+
return text;
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
export const requestClaudeReading = Effect.fnUntraced(function*(
|
|
62
|
+
credentials: ClaudeCredentials,
|
|
63
|
+
fetchImpl: FetchImpl = fetch,
|
|
64
|
+
now: number = Date.now(),
|
|
65
|
+
) {
|
|
66
|
+
if (credentials.expiresAt !== undefined && credentials.expiresAt <= now) return unverified;
|
|
67
|
+
const outcome = yield* fetchOutcome(ClaudeUsageUrl, {
|
|
68
|
+
authorization: "Bearer " + credentials.accessToken,
|
|
69
|
+
"anthropic-beta": "oauth-2025-04-20",
|
|
70
|
+
"User-Agent": "claude-code/2.1.202",
|
|
71
|
+
accept: "application/json",
|
|
72
|
+
}, fetchImpl);
|
|
73
|
+
if (outcome.kind !== "response") return outcome.kind === "limited" ? limited : outcome.kind === "timedOut" ? timedOut : unverified;
|
|
74
|
+
if (outcome.response.status === 401) {
|
|
75
|
+
const rejectedAt = yield* Clock.currentTimeMillis;
|
|
76
|
+
return expiredAtRejection(credentials.expiresAt, rejectedAt) ? unverified : required;
|
|
77
|
+
}
|
|
78
|
+
if (!outcome.response.ok) return unverified;
|
|
79
|
+
const text = yield* readBody(outcome.response);
|
|
80
|
+
if (text === undefined) return unverified;
|
|
81
|
+
const windows = parseClaudeUsagePayload(parseJson(text));
|
|
82
|
+
if (!windows) return unverified;
|
|
83
|
+
return measuredAt(new Date(now).toISOString(), windows);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
const attemptCodexEndpoint = Effect.fnUntraced(function*(
|
|
87
|
+
url: string,
|
|
88
|
+
credentials: CodexCredentials,
|
|
89
|
+
fetchImpl: FetchImpl,
|
|
90
|
+
now: number,
|
|
91
|
+
) {
|
|
92
|
+
const headers: Record<string, string> = { authorization: "Bearer " + credentials.accessToken, accept: "application/json" };
|
|
93
|
+
if (credentials.accountId) headers["ChatGPT-Account-Id"] = credentials.accountId;
|
|
94
|
+
const outcome = yield* fetchOutcome(url, headers, fetchImpl);
|
|
95
|
+
if (outcome.kind !== "response") {
|
|
96
|
+
if (outcome.kind === "limited") return { kind: "done", reading: limited } as const;
|
|
97
|
+
if (outcome.kind === "timedOut") return { kind: "done", reading: timedOut } as const;
|
|
98
|
+
return { kind: "next" } as const;
|
|
99
|
+
}
|
|
100
|
+
if (outcome.response.status === 401 || outcome.response.status === 403) {
|
|
101
|
+
const rejectedAt = yield* Clock.currentTimeMillis;
|
|
102
|
+
return { kind: "rejected", expired: expiredAtRejection(credentials.expiresAt, rejectedAt) } as const;
|
|
103
|
+
}
|
|
104
|
+
if (!outcome.response.ok) return { kind: "next" } as const;
|
|
105
|
+
const text = yield* readBody(outcome.response);
|
|
106
|
+
if (text === undefined) return { kind: "next" } as const;
|
|
107
|
+
const windows = parseCodexUsagePayload(parseJson(text), now);
|
|
108
|
+
if (!windows) return { kind: "next" } as const;
|
|
109
|
+
return { kind: "done", reading: measuredAt(new Date(now).toISOString(), windows) } as const;
|
|
110
|
+
});
|
|
111
|
+
export const requestCodexReading = Effect.fnUntraced(function*(
|
|
112
|
+
credentials: CodexCredentials,
|
|
113
|
+
fetchImpl: FetchImpl = fetch,
|
|
114
|
+
now: number = Date.now(),
|
|
115
|
+
) {
|
|
116
|
+
let rejection: boolean | undefined;
|
|
117
|
+
for (const url of CodexUsageUrls) {
|
|
118
|
+
const attempt = yield* attemptCodexEndpoint(url, credentials, fetchImpl, now);
|
|
119
|
+
if (attempt.kind === "done") return attempt.reading;
|
|
120
|
+
if (attempt.kind === "rejected" && rejection === undefined) rejection = attempt.expired;
|
|
121
|
+
}
|
|
122
|
+
if (rejection === undefined) return unverified;
|
|
123
|
+
return rejection ? unverified : required;
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
export const requestOpenCodeReading = Effect.fnUntraced(function*(
|
|
127
|
+
key: string,
|
|
128
|
+
fetchImpl: FetchImpl = fetch,
|
|
129
|
+
now: number = Date.now(),
|
|
130
|
+
) {
|
|
131
|
+
const outcome = yield* fetchOutcome(OpenCodeUsageUrl, { authorization: "Bearer " + key, accept: "application/json" }, fetchImpl);
|
|
132
|
+
if (outcome.kind !== "response") return outcome.kind === "limited" ? limited : outcome.kind === "timedOut" ? timedOut : unverified;
|
|
133
|
+
if (outcome.response.status === 401 || outcome.response.status === 403) return required;
|
|
134
|
+
if (!outcome.response.ok) return unverified;
|
|
135
|
+
const text = yield* readBody(outcome.response);
|
|
136
|
+
if (text === undefined) return unverified;
|
|
137
|
+
const windows = parseOpenCodeUsagePayload(parseJson(text), now);
|
|
138
|
+
if (!windows) return unverified;
|
|
139
|
+
return measuredAt(new Date(now).toISOString(), windows);
|
|
140
|
+
});
|
|
141
|
+
const readKeychainContent = Effect.fnUntraced(function*(
|
|
142
|
+
login: Extract<EnrolledAccount["login"], { readonly store: "macos-keychain" }>,
|
|
143
|
+
env: Record<string, string | undefined>,
|
|
144
|
+
) {
|
|
145
|
+
return yield* readKeychainPassword(login, env).pipe(Effect.orElseSucceed(() => undefined as string | undefined));
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
const readNamedFile = Effect.fnUntraced(function*(file: string) {
|
|
149
|
+
const fs = yield* FileSystem.FileSystem;
|
|
150
|
+
const info = yield* fs.stat(file).pipe(Effect.result);
|
|
151
|
+
if (Result.isFailure(info)) return Predicate.isTagged(info.failure.reason, "NotFound") ? required : unverified;
|
|
152
|
+
if (info.success.type !== "File") return unverified;
|
|
153
|
+
const content = yield* fs.readFileString(file).pipe(Effect.orElseSucceed(() => undefined as string | undefined));
|
|
154
|
+
if (content === undefined) return unverified;
|
|
155
|
+
return content;
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
const readClaudeAccount = Effect.fnUntraced(function*(
|
|
159
|
+
account: Extract<EnrolledAccount, { readonly provider: "claude" }>,
|
|
160
|
+
fetchImpl: FetchImpl,
|
|
161
|
+
env: Record<string, string | undefined>,
|
|
162
|
+
now: number,
|
|
163
|
+
) {
|
|
164
|
+
if (account.login.store === "macos-keychain" && process.platform !== "darwin") return unverified;
|
|
165
|
+
const content = yield* (account.login.store === "file"
|
|
166
|
+
? readNamedFile(account.login.path)
|
|
167
|
+
: readKeychainContent(account.login, env));
|
|
168
|
+
if (typeof content !== "string") return content ?? unverified;
|
|
169
|
+
const credentials = parseClaudeCredentials(content);
|
|
170
|
+
if (!credentials) return unverified;
|
|
171
|
+
const reading = yield* requestClaudeReading(credentials, fetchImpl, now);
|
|
172
|
+
if ("code" in reading && reading.code === "auth_required") return reading;
|
|
173
|
+
return { ...reading, loginExpiresAt: credentials.refreshExpiresAt ?? null } satisfies Reading;
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
const readCodexAccount = Effect.fnUntraced(function*(
|
|
177
|
+
file: string,
|
|
178
|
+
fetchImpl: FetchImpl,
|
|
179
|
+
now: number,
|
|
180
|
+
) {
|
|
181
|
+
const content = yield* readNamedFile(file);
|
|
182
|
+
if (typeof content !== "string") return content;
|
|
183
|
+
const credentials = parseCodexCredentials(content);
|
|
184
|
+
if (!credentials) return unverified;
|
|
185
|
+
return yield* requestCodexReading(credentials, fetchImpl, now).pipe(Effect.orElseSucceed(() => unverified));
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
const readOpenCodeAccount = Effect.fnUntraced(function*(
|
|
189
|
+
file: string,
|
|
190
|
+
fetchImpl: FetchImpl,
|
|
191
|
+
now: number,
|
|
192
|
+
) {
|
|
193
|
+
const content = yield* readNamedFile(file);
|
|
194
|
+
if (typeof content !== "string") return content;
|
|
195
|
+
const key = parseOpenCodeKey(content);
|
|
196
|
+
if (!key) return unverified;
|
|
197
|
+
return yield* requestOpenCodeReading(key, fetchImpl, now).pipe(Effect.orElseSucceed(() => unverified));
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
export const readAccount = Effect.fnUntraced(function*(
|
|
201
|
+
account: EnrolledAccount,
|
|
202
|
+
options: { readonly fetchImpl?: FetchImpl; readonly env?: Record<string, string | undefined> } = {},
|
|
203
|
+
) {
|
|
204
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
205
|
+
const now = yield* Clock.currentTimeMillis;
|
|
206
|
+
if (account.provider === "claude") return yield* readClaudeAccount(account, fetchImpl, options.env ?? {}, now);
|
|
207
|
+
const file = account.login.path;
|
|
208
|
+
if (account.provider === "codex") return yield* readCodexAccount(file, fetchImpl, now);
|
|
209
|
+
return yield* readOpenCodeAccount(file, fetchImpl, now);
|
|
210
|
+
});
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { Effect, Option, Schema } from "effect";
|
|
2
|
+
|
|
3
|
+
const freshnessMs = 120_000;
|
|
4
|
+
const Timestamp = Schema.String.check(
|
|
5
|
+
Schema.makeFilter((value) => {
|
|
6
|
+
const time = Date.parse(value);
|
|
7
|
+
return Number.isFinite(time) && new Date(time).toISOString() === value;
|
|
8
|
+
}),
|
|
9
|
+
);
|
|
10
|
+
export const Label = Schema.String.check(Schema.isPattern(/^[a-z0-9][a-z0-9_-]{0,63}$/u));
|
|
11
|
+
const FailureCode = Schema.Literals(["timeout", "rate_limited", "auth_required", "auth_unverified"]);
|
|
12
|
+
const Window = Schema.Struct({
|
|
13
|
+
id: Label,
|
|
14
|
+
scope: Label,
|
|
15
|
+
percentLeft: Schema.NullOr(Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 100 }))),
|
|
16
|
+
resetsAt: Schema.NullOr(Timestamp),
|
|
17
|
+
});
|
|
18
|
+
const Provider = Schema.Literals(["claude", "codex", "opencode-go"]);
|
|
19
|
+
const Windows = Schema.NonEmptyArray(Window).check(
|
|
20
|
+
Schema.makeFilter((windows) => new Set(windows.map(({ id }) => id)).size === windows.length),
|
|
21
|
+
);
|
|
22
|
+
|
|
23
|
+
function deadlineAt(observedAt: string, windows: typeof Windows.Type): number {
|
|
24
|
+
return windows.reduce(
|
|
25
|
+
(earliest, { resetsAt }) => (resetsAt === null ? earliest : Math.min(earliest, Date.parse(resetsAt))),
|
|
26
|
+
Date.parse(observedAt) + freshnessMs,
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const measurement = {
|
|
31
|
+
observedAt: Timestamp,
|
|
32
|
+
source: Schema.Literal("provider"),
|
|
33
|
+
windows: Windows,
|
|
34
|
+
};
|
|
35
|
+
const Fresh = Schema.Struct({
|
|
36
|
+
status: Schema.Literal("fresh"),
|
|
37
|
+
...measurement,
|
|
38
|
+
validUntil: Timestamp,
|
|
39
|
+
}).check(
|
|
40
|
+
Schema.makeFilter(({ observedAt, windows, validUntil }) => {
|
|
41
|
+
return Date.parse(validUntil) === deadlineAt(observedAt, windows);
|
|
42
|
+
}),
|
|
43
|
+
).pipe(Schema.brand("BoundedFreshObservation"));
|
|
44
|
+
const Stale = Schema.Struct({
|
|
45
|
+
status: Schema.Literal("stale"),
|
|
46
|
+
...measurement,
|
|
47
|
+
code: Schema.NullOr(FailureCode),
|
|
48
|
+
});
|
|
49
|
+
const Unavailable = Schema.Struct({
|
|
50
|
+
status: Schema.Literal("unavailable"),
|
|
51
|
+
code: FailureCode,
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
const Observation = Schema.Union([Fresh, Stale, Unavailable]);
|
|
55
|
+
type FreshObservation = typeof Fresh.Type;
|
|
56
|
+
type Observation = typeof Observation.Type;
|
|
57
|
+
const dayMs = 86_400_000;
|
|
58
|
+
const loginWarningDays = 7;
|
|
59
|
+
const Account = Schema.Struct({
|
|
60
|
+
id: Label,
|
|
61
|
+
provider: Provider,
|
|
62
|
+
observation: Observation,
|
|
63
|
+
loginEndsInDays: Schema.optionalKey(Schema.NullOr(Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: loginWarningDays })))),
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
export function loginWarningAt(expiresAt: number, now: number): number | undefined {
|
|
67
|
+
if (expiresAt <= now) return 0;
|
|
68
|
+
const days = Math.ceil((expiresAt - now) / dayMs);
|
|
69
|
+
return days <= loginWarningDays ? days : undefined;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function isFreshAt(observation: FreshObservation, now: number): boolean {
|
|
73
|
+
return Date.parse(observation.observedAt) <= now && now < Date.parse(observation.validUntil);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const Snapshot = Schema.Struct({
|
|
77
|
+
version: Schema.Literal("subquo.v1"),
|
|
78
|
+
writtenAt: Timestamp,
|
|
79
|
+
accounts: Schema.Array(Account),
|
|
80
|
+
}).check(
|
|
81
|
+
Schema.makeFilter(({ accounts, writtenAt }) => {
|
|
82
|
+
if (new Set(accounts.map(({ id }) => id)).size !== accounts.length) return false;
|
|
83
|
+
const writtenAtMs = Date.parse(writtenAt);
|
|
84
|
+
return accounts.every(({ observation }) => {
|
|
85
|
+
if (observation.status === "unavailable") return true;
|
|
86
|
+
if (observation.status === "stale") return Date.parse(observation.observedAt) <= writtenAtMs;
|
|
87
|
+
return isFreshAt(observation, writtenAtMs);
|
|
88
|
+
});
|
|
89
|
+
}),
|
|
90
|
+
);
|
|
91
|
+
|
|
92
|
+
export type Snapshot = typeof Snapshot.Type;
|
|
93
|
+
export type Account = typeof Account.Type;
|
|
94
|
+
export type FailureCode = typeof FailureCode.Type;
|
|
95
|
+
export type QuotaWindow = typeof Window.Type;
|
|
96
|
+
export { Windows };
|
|
97
|
+
|
|
98
|
+
const makeFresh = Schema.decodeUnknownOption(Fresh);
|
|
99
|
+
|
|
100
|
+
export function measuredObservation(
|
|
101
|
+
observedAt: string,
|
|
102
|
+
windows: typeof Windows.Type,
|
|
103
|
+
now: number,
|
|
104
|
+
): Observation {
|
|
105
|
+
if (Date.parse(observedAt) > now) return { status: "unavailable", code: "auth_unverified" };
|
|
106
|
+
const validUntil = deadlineAt(observedAt, windows);
|
|
107
|
+
const reading = { observedAt, source: "provider" as const, windows };
|
|
108
|
+
if (validUntil <= now) {
|
|
109
|
+
return { status: "stale", ...reading, code: null };
|
|
110
|
+
}
|
|
111
|
+
const fresh = makeFresh({ status: "fresh", ...reading, validUntil: new Date(validUntil).toISOString() });
|
|
112
|
+
return Option.getOrElse(fresh, () => ({ status: "unavailable", code: "auth_unverified" }) as const);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
class InvalidSnapshot extends Schema.TaggedError<InvalidSnapshot>()("InvalidSnapshot", {}) {}
|
|
116
|
+
|
|
117
|
+
const SnapshotJson = Schema.fromJsonString(Snapshot);
|
|
118
|
+
const decodeJson = Schema.decodeUnknownEffect(SnapshotJson, { onExcessProperty: "ignore" });
|
|
119
|
+
const encodeJson = Schema.encodeUnknownEffect(SnapshotJson, { onExcessProperty: "ignore" });
|
|
120
|
+
|
|
121
|
+
const invalidSnapshot = () => new InvalidSnapshot();
|
|
122
|
+
|
|
123
|
+
export function parseSnapshot(json: string): Effect.Effect<Snapshot, InvalidSnapshot> {
|
|
124
|
+
return decodeJson(json).pipe(Effect.mapError(invalidSnapshot));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function serializeSnapshot(input: unknown): Effect.Effect<string, InvalidSnapshot> {
|
|
128
|
+
return Effect.suspend(() => encodeJson(input)).pipe(
|
|
129
|
+
Effect.mapError(invalidSnapshot),
|
|
130
|
+
Effect.catchDefect(() => Effect.fail(invalidSnapshot())),
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function observationAt(observation: Observation, now: number): Observation {
|
|
135
|
+
if (observation.status !== "fresh" || isFreshAt(observation, now)) return observation;
|
|
136
|
+
const { observedAt, source, windows } = observation;
|
|
137
|
+
return { status: "stale", observedAt, source, windows, code: null };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function pickEvidenceAt(observation: Observation, now: number): FreshObservation | undefined {
|
|
141
|
+
const current = observationAt(observation, now);
|
|
142
|
+
if (current.status !== "fresh") return undefined;
|
|
143
|
+
return current.windows.every(({ percentLeft, resetsAt }) => percentLeft !== null && resetsAt !== null)
|
|
144
|
+
? current
|
|
145
|
+
: undefined;
|
|
146
|
+
}
|
package/src/keychain.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { Effect, Stream } from "effect";
|
|
2
|
+
import { ChildProcess, ChildProcessSpawner } from "effect/process";
|
|
3
|
+
import { validClaudeKeychainService, type EnrolledAccount } from "./accounts";
|
|
4
|
+
|
|
5
|
+
export type MacosKeychainLogin = Extract<EnrolledAccount["login"], { readonly store: "macos-keychain" }>;
|
|
6
|
+
|
|
7
|
+
export const readKeychainPassword = Effect.fnUntraced(function*(
|
|
8
|
+
login: MacosKeychainLogin,
|
|
9
|
+
env: Record<string, string | undefined>,
|
|
10
|
+
) {
|
|
11
|
+
if (!validClaudeKeychainService(login)) return yield* Effect.succeed(undefined as string | undefined);
|
|
12
|
+
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
|
13
|
+
const command = ChildProcess.make("/usr/bin/security", ["find-generic-password", "-s", login.service, "-w"], {
|
|
14
|
+
env,
|
|
15
|
+
stdin: "ignore",
|
|
16
|
+
stderr: "ignore",
|
|
17
|
+
killSignal: "SIGKILL",
|
|
18
|
+
});
|
|
19
|
+
return yield* Effect.scoped(Effect.gen(function*() {
|
|
20
|
+
const child = yield* spawner.spawn(command);
|
|
21
|
+
const content = yield* child.stdout.pipe(Stream.decodeText, Stream.mkString);
|
|
22
|
+
if ((yield* child.exitCode) !== 0) return undefined;
|
|
23
|
+
return content;
|
|
24
|
+
}));
|
|
25
|
+
});
|
package/src/launch.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
#!/usr/bin/env -S bun --no-env-file
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
import manifest from "../package.json";
|
|
4
|
+
|
|
5
|
+
const args = process.argv.slice(2);
|
|
6
|
+
const supported = (process.platform === "linux" && process.arch === "x64") || (process.platform === "darwin" && process.arch === "arm64");
|
|
7
|
+
const name = `${manifest.name}-${process.platform}-${process.arch}`;
|
|
8
|
+
|
|
9
|
+
if (supported && process.execve !== undefined) {
|
|
10
|
+
await Effect.runPromise(Effect.option(Effect.try(() => {
|
|
11
|
+
const binary = Bun.fileURLToPath(import.meta.resolve(`${name}/subquo-${manifest.version}`));
|
|
12
|
+
process.execve?.(binary, [binary, ...args]);
|
|
13
|
+
})));
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const source = Bun.fileURLToPath(new URL("./cli.ts", import.meta.url));
|
|
17
|
+
if (process.platform !== "win32" && process.execve !== undefined) {
|
|
18
|
+
process.execve(process.execPath, [process.execPath, "--no-env-file", source, ...args]);
|
|
19
|
+
}
|
|
20
|
+
const child = Bun.spawn([process.execPath, "--no-env-file", source, ...args], { stdin: "inherit", stdout: "inherit", stderr: "inherit" });
|
|
21
|
+
process.exitCode = await child.exited;
|
package/src/pi-codex.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Option, Schema } from "effect";
|
|
2
|
+
|
|
3
|
+
import type { CodexCredentials } from "./codex-credentials";
|
|
4
|
+
|
|
5
|
+
const PiCodexLogin = Schema.Struct({
|
|
6
|
+
type: Schema.Literal("oauth"),
|
|
7
|
+
access: Schema.NonEmptyString,
|
|
8
|
+
accountId: Schema.NonEmptyString,
|
|
9
|
+
expires: Schema.Finite,
|
|
10
|
+
});
|
|
11
|
+
const decodePiCodexLogin = Schema.decodeUnknownOption(PiCodexLogin);
|
|
12
|
+
|
|
13
|
+
export function parsePiCodexLogin(value: unknown): Required<CodexCredentials> | undefined {
|
|
14
|
+
const login = decodePiCodexLogin(value);
|
|
15
|
+
if (Option.isNone(login)) return undefined;
|
|
16
|
+
return { accessToken: login.value.access, accountId: login.value.accountId, expiresAt: login.value.expires };
|
|
17
|
+
}
|
package/src/renewal.ts
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { Clock, Effect, FileSystem, Option, Path, Schema, Stream } from "effect";
|
|
2
|
+
import { claudeDefaultKeychainService, type EnrolledAccount } from "./accounts";
|
|
3
|
+
import { readKeychainPassword } from "./keychain";
|
|
4
|
+
|
|
5
|
+
const ClaudeLogin = Schema.Struct({
|
|
6
|
+
claudeAiOauth: Schema.Struct({
|
|
7
|
+
expiresAt: Schema.Finite,
|
|
8
|
+
refreshToken: Schema.NonEmptyString,
|
|
9
|
+
}),
|
|
10
|
+
});
|
|
11
|
+
const CodexLogin = Schema.Struct({
|
|
12
|
+
tokens: Schema.Struct({
|
|
13
|
+
access_token: Schema.NonEmptyString,
|
|
14
|
+
refresh_token: Schema.NonEmptyString,
|
|
15
|
+
}),
|
|
16
|
+
});
|
|
17
|
+
const Claims = Schema.Struct({ exp: Schema.Finite });
|
|
18
|
+
const RpcResponse = Schema.Struct({
|
|
19
|
+
id: Schema.Int,
|
|
20
|
+
result: Schema.optional(Schema.Struct({
|
|
21
|
+
account: Schema.optional(Schema.NullOr(Schema.Struct({ type: Schema.String }))),
|
|
22
|
+
})),
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const decodeClaude = Schema.decodeUnknownOption(Schema.fromJsonString(ClaudeLogin));
|
|
26
|
+
const decodeCodex = Schema.decodeUnknownOption(Schema.fromJsonString(CodexLogin));
|
|
27
|
+
const decodeClaims = Schema.decodeUnknownOption(Schema.StringFromBase64Url.pipe(Schema.decodeTo(Schema.fromJsonString(Claims))));
|
|
28
|
+
const decodeResponse = Schema.decodeUnknownOption(Schema.fromJsonString(RpcResponse));
|
|
29
|
+
|
|
30
|
+
type OAuthProvider = Exclude<EnrolledAccount["provider"], "opencode-go">;
|
|
31
|
+
class RenewalUnchecked extends Schema.TaggedError<RenewalUnchecked>()("RenewalUnchecked", {}) {}
|
|
32
|
+
|
|
33
|
+
const unchecked = () => new RenewalUnchecked();
|
|
34
|
+
|
|
35
|
+
export function renewalExpiry(provider: OAuthProvider, json: string): number | undefined {
|
|
36
|
+
if (provider === "claude") {
|
|
37
|
+
const login = decodeClaude(json);
|
|
38
|
+
return Option.isSome(login) ? login.value.claudeAiOauth.expiresAt : undefined;
|
|
39
|
+
}
|
|
40
|
+
const login = decodeCodex(json);
|
|
41
|
+
if (Option.isNone(login)) return undefined;
|
|
42
|
+
const parts = login.value.tokens.access_token.split(".");
|
|
43
|
+
const [, encoded] = parts;
|
|
44
|
+
if (parts.length !== 3 || !encoded) return undefined;
|
|
45
|
+
const claims = decodeClaims(encoded);
|
|
46
|
+
return Option.isSome(claims) ? claims.value.exp * 1_000 : undefined;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const readKeychain = Effect.fnUntraced(function*(
|
|
50
|
+
login: Extract<EnrolledAccount["login"], { readonly store: "macos-keychain" }>,
|
|
51
|
+
env: Record<string, string | undefined>,
|
|
52
|
+
) {
|
|
53
|
+
const content = yield* readKeychainPassword(login, env).pipe(
|
|
54
|
+
Effect.timeoutOrElse({ duration: 5_000, orElse: () => Effect.fail(unchecked()) }),
|
|
55
|
+
);
|
|
56
|
+
if (content === undefined) return yield* unchecked();
|
|
57
|
+
return content;
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
const runClaude = Effect.fnUntraced(function*(env: Record<string, string | undefined>, configDir: string | undefined) {
|
|
61
|
+
const child = yield* Effect.try({
|
|
62
|
+
try: () => Bun.spawn(["claude", "doctor"], {
|
|
63
|
+
env: configDir === undefined ? env : { ...env, CLAUDE_CONFIG_DIR: configDir },
|
|
64
|
+
stdin: "ignore",
|
|
65
|
+
stdout: "ignore",
|
|
66
|
+
stderr: "ignore",
|
|
67
|
+
}),
|
|
68
|
+
catch: unchecked,
|
|
69
|
+
});
|
|
70
|
+
return yield* Effect.promise(() => child.exited);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
function rpc(message: object): string {
|
|
74
|
+
return `${JSON.stringify(message)}\n`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const runCodex = Effect.fnUntraced(function*(env: Record<string, string | undefined>, configDir: string) {
|
|
78
|
+
const child = yield* Effect.try({
|
|
79
|
+
try: () => Bun.spawn(["codex", "-c", 'cli_auth_credentials_store="file"', "app-server"], {
|
|
80
|
+
env: { ...env, CODEX_HOME: configDir }, stdin: "pipe", stdout: "pipe", stderr: "ignore",
|
|
81
|
+
}),
|
|
82
|
+
catch: unchecked,
|
|
83
|
+
});
|
|
84
|
+
const send = Effect.fnUntraced(function*(message: object) {
|
|
85
|
+
yield* Effect.tryPromise({ try: () => Promise.resolve(child.stdin.write(rpc(message))), catch: unchecked });
|
|
86
|
+
yield* Effect.tryPromise({ try: () => Promise.resolve(child.stdin.flush()), catch: unchecked });
|
|
87
|
+
});
|
|
88
|
+
const closeStdin = Effect.tryPromise({ try: () => Promise.resolve(child.stdin.end()), catch: unchecked })
|
|
89
|
+
.pipe(Effect.orElseSucceed(() => undefined));
|
|
90
|
+
const initialized = send({ method: "initialized" });
|
|
91
|
+
const request = send({ id: 2, method: "account/read", params: { refreshToken: true } });
|
|
92
|
+
let requested = false;
|
|
93
|
+
let accepted = false;
|
|
94
|
+
const response = Stream.fromReadableStream({ evaluate: () => child.stdout, onError: unchecked }).pipe(
|
|
95
|
+
Stream.decodeText,
|
|
96
|
+
Stream.splitLines,
|
|
97
|
+
Stream.runForEach((line) => Effect.gen(function*() {
|
|
98
|
+
const decoded = decodeResponse(line);
|
|
99
|
+
if (Option.isNone(decoded)) return;
|
|
100
|
+
const { id, result } = decoded.value;
|
|
101
|
+
if (id === 1 && !requested) {
|
|
102
|
+
if (result === undefined) {
|
|
103
|
+
yield* closeStdin;
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
requested = true;
|
|
107
|
+
yield* initialized;
|
|
108
|
+
yield* request;
|
|
109
|
+
}
|
|
110
|
+
if (id === 2 && requested) {
|
|
111
|
+
accepted = result?.account?.type === "chatgpt";
|
|
112
|
+
yield* closeStdin;
|
|
113
|
+
}
|
|
114
|
+
})),
|
|
115
|
+
);
|
|
116
|
+
yield* send({ id: 1, method: "initialize", params: { clientInfo: { name: "subquo", version: "1" } } }).pipe(
|
|
117
|
+
Effect.andThen(response),
|
|
118
|
+
Effect.ensuring(closeStdin),
|
|
119
|
+
);
|
|
120
|
+
return (yield* Effect.promise(() => child.exited)) === 0 && accepted;
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
function vendorDir(login: EnrolledAccount["login"], provider: EnrolledAccount["provider"], fileDir: string): string | undefined {
|
|
124
|
+
if (login.store === "file") return fileDir;
|
|
125
|
+
if (provider === "claude" && login.service === claudeDefaultKeychainService) return undefined;
|
|
126
|
+
return login.config_dir;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
type RenewalResult = "not_needed" | "not_supported" | "renewed" | "auth_required" | "auth_unverified";
|
|
130
|
+
|
|
131
|
+
export const renewIdleLogin = Effect.fnUntraced(function*(
|
|
132
|
+
account: EnrolledAccount,
|
|
133
|
+
env: Record<string, string | undefined>,
|
|
134
|
+
) {
|
|
135
|
+
if (account.provider === "opencode-go") return "not_supported" satisfies RenewalResult;
|
|
136
|
+
const fs = yield* FileSystem.FileSystem;
|
|
137
|
+
const path = yield* Path.Path;
|
|
138
|
+
const login = account.login;
|
|
139
|
+
const read = login.store === "file"
|
|
140
|
+
? fs.readFileString(login.path)
|
|
141
|
+
: readKeychain(login, env);
|
|
142
|
+
if (account.provider === "claude" && (login.store === "macos-keychain") !== (process.platform === "darwin")) {
|
|
143
|
+
return "auth_unverified" satisfies RenewalResult;
|
|
144
|
+
}
|
|
145
|
+
const expires = yield* read.pipe(Effect.map((json) => renewalExpiry(account.provider, json)));
|
|
146
|
+
if (expires === undefined) return "auth_unverified" satisfies RenewalResult;
|
|
147
|
+
if (expires > (yield* Clock.currentTimeMillis)) return "not_needed" satisfies RenewalResult;
|
|
148
|
+
|
|
149
|
+
const fileDir = login.store === "file" ? path.dirname(login.path) : login.config_dir;
|
|
150
|
+
const accepted = account.provider === "claude"
|
|
151
|
+
? (yield* runClaude(env, vendorDir(login, account.provider, fileDir))) === 0
|
|
152
|
+
: yield* runCodex(env, vendorDir(login, account.provider, fileDir) ?? fileDir);
|
|
153
|
+
const after = yield* read.pipe(Effect.map((json) => renewalExpiry(account.provider, json)), Effect.option);
|
|
154
|
+
if (Option.isNone(after) || after.value === undefined) return "auth_required" satisfies RenewalResult;
|
|
155
|
+
return accepted && after.value > (yield* Clock.currentTimeMillis)
|
|
156
|
+
? "renewed" satisfies RenewalResult
|
|
157
|
+
: "auth_unverified" satisfies RenewalResult;
|
|
158
|
+
}, Effect.orElseSucceed(() => "auth_unverified" as const));
|
package/src/storage.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { Database, SQLiteError } from "bun:sqlite";
|
|
2
|
+
import { Effect, FileSystem, Path, Schema } from "effect";
|
|
3
|
+
import { parseSnapshot, serializeSnapshot, type Snapshot } from "./index";
|
|
4
|
+
|
|
5
|
+
class SnapshotUnavailable extends Schema.TaggedError<SnapshotUnavailable>()("SnapshotUnavailable", {}) {}
|
|
6
|
+
class StateUnavailable extends Schema.TaggedError<StateUnavailable>()("StateUnavailable", {}) {}
|
|
7
|
+
|
|
8
|
+
const snapshotUnavailable = () => new SnapshotUnavailable();
|
|
9
|
+
const stateUnavailable = () => new StateUnavailable();
|
|
10
|
+
|
|
11
|
+
export const readSnapshot = Effect.fnUntraced(function*(file: string) {
|
|
12
|
+
const fs = yield* FileSystem.FileSystem;
|
|
13
|
+
const info = yield* fs.stat(file).pipe(Effect.mapError(snapshotUnavailable));
|
|
14
|
+
if (info.type !== "File") return yield* snapshotUnavailable();
|
|
15
|
+
const json = yield* fs.readFileString(file).pipe(Effect.mapError(snapshotUnavailable));
|
|
16
|
+
return yield* parseSnapshot(json);
|
|
17
|
+
}, Effect.timeoutOrElse({ duration: 900, orElse: () => Effect.fail(snapshotUnavailable()) }));
|
|
18
|
+
|
|
19
|
+
export const writeSnapshot = Effect.fnUntraced(function*(file: string, snapshot: Snapshot) {
|
|
20
|
+
const fs = yield* FileSystem.FileSystem;
|
|
21
|
+
const path = yield* Path.Path;
|
|
22
|
+
const json = yield* serializeSnapshot(snapshot);
|
|
23
|
+
const temporaryDir = yield* fs.makeTempDirectoryScoped({ directory: path.dirname(file), prefix: ".snapshot-" });
|
|
24
|
+
const temporaryFile = path.join(temporaryDir, "snapshot");
|
|
25
|
+
yield* fs.writeFileString(temporaryFile, `${json}\n`, { flag: "wx", mode: 0o600 });
|
|
26
|
+
yield* fs.rename(temporaryFile, file);
|
|
27
|
+
}, Effect.scoped);
|
|
28
|
+
|
|
29
|
+
export const withStateLock = Effect.fnUntraced(function*<A, E, R>(lockfile: string, work: Effect.Effect<A, E, R>) {
|
|
30
|
+
const fs = yield* FileSystem.FileSystem;
|
|
31
|
+
const path = yield* Path.Path;
|
|
32
|
+
yield* fs.makeDirectory(path.dirname(lockfile), { recursive: true, mode: 0o700 });
|
|
33
|
+
const db = yield* Effect.acquireRelease(
|
|
34
|
+
Effect.try({ try: () => new Database(lockfile), catch: stateUnavailable }),
|
|
35
|
+
(connection) => Effect.sync(() => connection.close()),
|
|
36
|
+
);
|
|
37
|
+
class StateBusy extends Schema.TaggedError<StateBusy>()("StateBusy", {}) {}
|
|
38
|
+
const acquired = yield* Effect.try({
|
|
39
|
+
try: () => {
|
|
40
|
+
db.run("PRAGMA busy_timeout = 0");
|
|
41
|
+
db.run("BEGIN IMMEDIATE");
|
|
42
|
+
return true;
|
|
43
|
+
},
|
|
44
|
+
catch: (error) => error instanceof SQLiteError && error.code === "SQLITE_BUSY" ? new StateBusy() : stateUnavailable(),
|
|
45
|
+
}).pipe(Effect.catchTag("StateBusy", () => Effect.succeed(false)));
|
|
46
|
+
if (!acquired) return { status: "busy" } as const;
|
|
47
|
+
return { status: "complete", value: yield* work } as const;
|
|
48
|
+
}, Effect.scoped);
|