@jameslovespancakes/pi-plus 1.0.11 → 1.0.13
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 +67 -22
- package/config/skills/workflow-code-review-actions/SKILL.md +44 -0
- package/package.json +9 -4
- package/src/core/accounts/oauth-pool.ts +137 -0
- package/src/core/accounts/registry.ts +12 -25
- package/src/core/accounts/routing.ts +144 -0
- package/src/core/anthropic/client-identity.ts +9 -64
- package/src/core/anthropic/identity.ts +54 -0
- package/src/core/anthropic/oauth.ts +3 -0
- package/src/core/anthropic/quota.ts +232 -78
- package/src/core/anthropic/routing.ts +40 -115
- package/src/core/anthropic/store.ts +11 -10
- package/src/core/catalog/quality.ts +33 -15
- package/src/core/codex/quota.ts +46 -8
- package/src/core/codex/store.ts +29 -16
- package/src/core/config.ts +16 -17
- package/src/core/store.ts +13 -12
- package/src/domains/agents/format.ts +97 -0
- package/src/domains/agents/index.ts +58 -47
- package/src/domains/compact/archive.ts +140 -0
- package/src/domains/compact/chunking.ts +166 -0
- package/src/domains/compact/index.ts +452 -0
- package/src/domains/compact/jev.ts +242 -0
- package/src/domains/compact/policy.ts +255 -0
- package/src/domains/compact/types.ts +79 -0
- package/src/domains/models/provider-picker.ts +1 -1
- package/src/domains/setup/index.ts +23 -23
- package/src/domains/subscriptions/accounts-picker.ts +61 -40
- package/src/domains/subscriptions/accounts.ts +53 -36
- package/src/domains/subscriptions/footer.ts +48 -29
- package/src/domains/subscriptions/index.ts +11 -27
- package/src/domains/subscriptions/provider.ts +79 -103
- package/src/domains/subscriptions/providers/anthropic.ts +42 -22
- package/src/domains/subscriptions/providers/codex.ts +146 -113
- package/src/domains/subscriptions/providers/hosted.ts +18 -0
- package/src/domains/subscriptions/providers/oauth-pool.ts +325 -0
- package/src/domains/subscriptions/routing.ts +19 -11
- package/src/domains/workflows/LICENSE.md +21 -0
- package/src/domains/workflows/index.ts +836 -0
- package/src/domains/workflows/runtime/advisory-challenge.ts +75 -0
- package/src/domains/workflows/runtime/advisory-evidence.ts +90 -0
- package/src/domains/workflows/runtime/advisory-schema.ts +83 -0
- package/src/domains/workflows/runtime/agent-attempt.ts +177 -0
- package/src/domains/workflows/runtime/agent-failure.ts +14 -0
- package/src/domains/workflows/runtime/agent-limits.ts +66 -0
- package/src/domains/workflows/runtime/agent-replay.ts +399 -0
- package/src/domains/workflows/runtime/agent-retry.ts +116 -0
- package/src/domains/workflows/runtime/agent-runner-types.ts +96 -0
- package/src/domains/workflows/runtime/agent-runner.ts +225 -0
- package/src/domains/workflows/runtime/agent-session-identity.ts +256 -0
- package/src/domains/workflows/runtime/agent-session-providers.ts +50 -0
- package/src/domains/workflows/runtime/agent-session.ts +382 -0
- package/src/domains/workflows/runtime/agent-skills.ts +270 -0
- package/src/domains/workflows/runtime/agent-workspace.ts +79 -0
- package/src/domains/workflows/runtime/background-workflow-tool.ts +75 -0
- package/src/domains/workflows/runtime/background-workflows.ts +492 -0
- package/src/domains/workflows/runtime/budget.ts +53 -0
- package/src/domains/workflows/runtime/cancellation.ts +87 -0
- package/src/domains/workflows/runtime/command-completions.ts +36 -0
- package/src/domains/workflows/runtime/concurrency.ts +403 -0
- package/src/domains/workflows/runtime/debug.ts +3 -0
- package/src/domains/workflows/runtime/diff-capture.ts +81 -0
- package/src/domains/workflows/runtime/discovery.ts +137 -0
- package/src/domains/workflows/runtime/dynamax-shortcuts.ts +122 -0
- package/src/domains/workflows/runtime/dynamax.ts +330 -0
- package/src/domains/workflows/runtime/engine.ts +579 -0
- package/src/domains/workflows/runtime/filesystem-error.ts +4 -0
- package/src/domains/workflows/runtime/finalizers.ts +66 -0
- package/src/domains/workflows/runtime/identity-canonicalization.ts +138 -0
- package/src/domains/workflows/runtime/identity-fingerprint.ts +15 -0
- package/src/domains/workflows/runtime/inline-workflow.ts +403 -0
- package/src/domains/workflows/runtime/journal.ts +313 -0
- package/src/domains/workflows/runtime/model-profiles.ts +310 -0
- package/src/domains/workflows/runtime/options.ts +157 -0
- package/src/domains/workflows/runtime/perf.ts +146 -0
- package/src/domains/workflows/runtime/pi-compat.ts +32 -0
- package/src/domains/workflows/runtime/process-runner.ts +260 -0
- package/src/domains/workflows/runtime/progress-types.ts +59 -0
- package/src/domains/workflows/runtime/progress.ts +400 -0
- package/src/domains/workflows/runtime/provider-usage-limit.ts +191 -0
- package/src/domains/workflows/runtime/replay-path-identity.ts +48 -0
- package/src/domains/workflows/runtime/research-contract.ts +89 -0
- package/src/domains/workflows/runtime/research-evidence.ts +289 -0
- package/src/domains/workflows/runtime/resume-context.ts +751 -0
- package/src/domains/workflows/runtime/review/code-review-orchestration.ts +24 -0
- package/src/domains/workflows/runtime/review/github-pr-comments.ts +249 -0
- package/src/domains/workflows/runtime/review/patch-validation.ts +120 -0
- package/src/domains/workflows/runtime/review/review-actions.ts +180 -0
- package/src/domains/workflows/runtime/review/review-budget.ts +45 -0
- package/src/domains/workflows/runtime/review/review-fix-workflow.ts +153 -0
- package/src/domains/workflows/runtime/review/review-format.ts +133 -0
- package/src/domains/workflows/runtime/review/review-handoff.ts +38 -0
- package/src/domains/workflows/runtime/review/review-issues.ts +87 -0
- package/src/domains/workflows/runtime/review/review-report.ts +42 -0
- package/src/domains/workflows/runtime/review/review-results-flow.ts +52 -0
- package/src/domains/workflows/runtime/review/review-results-viewer.ts +312 -0
- package/src/domains/workflows/runtime/review/review-session-coordinator.ts +153 -0
- package/src/domains/workflows/runtime/review/review-snapshot.ts +294 -0
- package/src/domains/workflows/runtime/review-diff-target.ts +130 -0
- package/src/domains/workflows/runtime/session-identity.ts +6 -0
- package/src/domains/workflows/runtime/structured-output.ts +32 -0
- package/src/domains/workflows/runtime/tool-capabilities.ts +44 -0
- package/src/domains/workflows/runtime/tool-source-identity.ts +150 -0
- package/src/domains/workflows/runtime/tree-fingerprint.ts +404 -0
- package/src/domains/workflows/runtime/types.ts +255 -0
- package/src/domains/workflows/runtime/ui/display-text.ts +28 -0
- package/src/domains/workflows/runtime/ui/dynamax-editor-decoration.ts +220 -0
- package/src/domains/workflows/runtime/ui/workflow-format.ts +165 -0
- package/src/domains/workflows/runtime/ui/workflow-inspector.ts +435 -0
- package/src/domains/workflows/runtime/ui/workflow-result-renderer.ts +171 -0
- package/src/domains/workflows/runtime/ui/workflow-viewer-layout.ts +51 -0
- package/src/domains/workflows/runtime/ui/workflow-widget.ts +78 -0
- package/src/domains/workflows/runtime/unknown-error.ts +8 -0
- package/src/domains/workflows/runtime/usage.ts +341 -0
- package/src/domains/workflows/runtime/workflow-advisory-utils.ts +245 -0
- package/src/domains/workflows/runtime/workflow-execution.ts +121 -0
- package/src/domains/workflows/runtime/workflow-module.ts +75 -0
- package/src/domains/workflows/runtime/workflow-run-background.ts +72 -0
- package/src/domains/workflows/runtime/workflow-run-controller.ts +342 -0
- package/src/domains/workflows/runtime/workflow-run-history.ts +164 -0
- package/src/domains/workflows/runtime/workflow-run-record.ts +636 -0
- package/src/domains/workflows/runtime/workflow-run-store.ts +176 -0
- package/src/domains/workflows/runtime/workflow-usage-limit-scheduler.ts +80 -0
- package/src/domains/workflows/runtime/workflows.ts +40 -0
- package/src/domains/workflows/runtime/worktree.ts +615 -0
- package/src/domains/workflows/workflows/code-review.ts +232 -0
- package/src/domains/workflows/workflows/diagnose.ts +154 -0
- package/src/domains/workflows/workflows/perf-review.ts +149 -0
- package/src/domains/workflows/workflows/refactor-scout.ts +143 -0
- package/src/domains/workflows/workflows/research.ts +169 -0
- package/src/services/usage-service.ts +6 -30
- package/src/ui/usage-bars.ts +1 -2
- package/src/core/codex/oauth.ts +0 -129
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import type { Api, ModelAuth, OAuthAuth, OAuthCredential, Provider } from "@earendil-works/pi-ai";
|
|
3
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import type { AccountContext, AccountProvider, ManagedAccount, RoutingMode } from "../../../core/accounts/registry.ts";
|
|
5
|
+
import {
|
|
6
|
+
quotaStateFromHeaders,
|
|
7
|
+
refreshAbortSignal,
|
|
8
|
+
selectRoutingCandidate,
|
|
9
|
+
} from "../../../core/accounts/routing.ts";
|
|
10
|
+
import {
|
|
11
|
+
oauthIdentity,
|
|
12
|
+
setPrimaryQuota,
|
|
13
|
+
sharedOAuthPoolStore,
|
|
14
|
+
type PooledOAuthAccount,
|
|
15
|
+
type PooledOAuthStore,
|
|
16
|
+
} from "../../../core/accounts/oauth-pool.ts";
|
|
17
|
+
|
|
18
|
+
export interface PooledOAuthProviderSpec<TApi extends Api> {
|
|
19
|
+
id: string;
|
|
20
|
+
label: string;
|
|
21
|
+
createProvider(): Provider<TApi>;
|
|
22
|
+
/** Backing storage. Defaults to the shared pi-plus OAuth pool file. */
|
|
23
|
+
store?: PooledOAuthStore;
|
|
24
|
+
/** Confirmation shown before an interactive `add`. */
|
|
25
|
+
addPrompt?: string;
|
|
26
|
+
/** Display label for an account. */
|
|
27
|
+
describeAccount?(account: PooledOAuthAccount): string;
|
|
28
|
+
/** Stable identity used to reject a duplicate login. Defaults to JWT claims. */
|
|
29
|
+
identityOf?(access: string): string | undefined;
|
|
30
|
+
/**
|
|
31
|
+
* Records a response's quota signal against an account. Defaults to the
|
|
32
|
+
* generic `x-ratelimit-*` reader; providers with their own headers (Codex
|
|
33
|
+
* sends `x-codex-*`) override it. Must never throw: it runs inside the
|
|
34
|
+
* awaited `onResponse`, so a rejection would kill an in-flight stream.
|
|
35
|
+
*/
|
|
36
|
+
recordQuota?(accountId: string, status: number, headers: Record<string, string>): void;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const MAIN = "main";
|
|
40
|
+
|
|
41
|
+
const lastUsed = new Map<string, number>();
|
|
42
|
+
const refreshes = new Map<string, Promise<PooledOAuthAccount>>();
|
|
43
|
+
|
|
44
|
+
function storeFor<TApi extends Api>(spec: PooledOAuthProviderSpec<TApi>): PooledOAuthStore {
|
|
45
|
+
return spec.store ?? sharedOAuthPoolStore(spec.id);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function oauthFor<TApi extends Api>(spec: PooledOAuthProviderSpec<TApi>): OAuthAuth {
|
|
49
|
+
const oauth = spec.createProvider().auth.oauth;
|
|
50
|
+
if (!oauth) throw new Error(`${spec.label} does not expose subscription OAuth.`);
|
|
51
|
+
return oauth;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function notifyAuthEvent(ctx: AccountContext, event: any): Promise<void> {
|
|
55
|
+
if (event?.type === "device_code") {
|
|
56
|
+
const url = String(event.verificationUri ?? "");
|
|
57
|
+
if (url) await ctx.openBrowser(url).catch(() => undefined);
|
|
58
|
+
ctx.ui.notify(`Enter code ${String(event.userCode ?? "")} at ${url}`, "info");
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if (event?.type === "auth_url") {
|
|
62
|
+
const url = String(event.url ?? "");
|
|
63
|
+
if (url) await ctx.openBrowser(url).catch(() => undefined);
|
|
64
|
+
ctx.ui.notify(event.instructions ? `${event.instructions}\n${url}` : url, "info");
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (typeof event?.message === "string") ctx.ui.notify(event.message, "info");
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function authenticate<TApi extends Api>(spec: PooledOAuthProviderSpec<TApi>, ctx: AccountContext): Promise<OAuthCredential> {
|
|
71
|
+
const signal = ctx.signal ?? new AbortController().signal;
|
|
72
|
+
return oauthFor(spec).login({
|
|
73
|
+
signal,
|
|
74
|
+
notify: (event) => { void notifyAuthEvent(ctx, event); },
|
|
75
|
+
prompt: async (prompt) => {
|
|
76
|
+
if (prompt.type === "select") {
|
|
77
|
+
const labels = prompt.options.map((option) => option.label);
|
|
78
|
+
const selected = await ctx.ui.select(prompt.message, labels);
|
|
79
|
+
const index = selected ? labels.indexOf(selected) : -1;
|
|
80
|
+
if (index < 0) throw new Error("Login cancelled.");
|
|
81
|
+
return prompt.options[index].id;
|
|
82
|
+
}
|
|
83
|
+
const value = await ctx.ui.input(prompt.message, prompt.placeholder);
|
|
84
|
+
if (!value) throw new Error("Login cancelled.");
|
|
85
|
+
return value;
|
|
86
|
+
},
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function accountLabel<TApi extends Api>(spec: PooledOAuthProviderSpec<TApi>, account: PooledOAuthAccount): string {
|
|
91
|
+
return spec.describeAccount?.(account) ?? (account.label || account.identity || account.id.slice(0, 8));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function identityFor<TApi extends Api>(spec: PooledOAuthProviderSpec<TApi>, access: string): string | undefined {
|
|
95
|
+
return (spec.identityOf ?? oauthIdentity)(access);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function duplicateAccount<TApi extends Api>(
|
|
99
|
+
spec: PooledOAuthProviderSpec<TApi>,
|
|
100
|
+
credential: OAuthCredential,
|
|
101
|
+
excludeId?: string,
|
|
102
|
+
): PooledOAuthAccount | undefined {
|
|
103
|
+
const identity = identityFor(spec, credential.access);
|
|
104
|
+
return storeFor(spec).load().accounts.find((account) =>
|
|
105
|
+
account.id !== excludeId && (identity ? account.identity === identity : account.access === credential.access));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function createPooledOAuthAdapter<TApi extends Api>(spec: PooledOAuthProviderSpec<TApi>): AccountProvider {
|
|
109
|
+
const store = () => storeFor(spec);
|
|
110
|
+
|
|
111
|
+
return {
|
|
112
|
+
id: spec.id,
|
|
113
|
+
label: spec.label,
|
|
114
|
+
|
|
115
|
+
async list(): Promise<ManagedAccount[]> {
|
|
116
|
+
return store().load().accounts.map((account) => {
|
|
117
|
+
const identity = account.identity ?? identityFor(spec, account.access);
|
|
118
|
+
return {
|
|
119
|
+
id: account.id,
|
|
120
|
+
label: accountLabel(spec, account),
|
|
121
|
+
enabled: account.enabled !== false,
|
|
122
|
+
expiresAt: account.expires,
|
|
123
|
+
...(identity && { identity }),
|
|
124
|
+
};
|
|
125
|
+
});
|
|
126
|
+
},
|
|
127
|
+
|
|
128
|
+
identify: (accessToken) => identityFor(spec, accessToken),
|
|
129
|
+
|
|
130
|
+
async add(ctx, label): Promise<string | undefined> {
|
|
131
|
+
const prompt = spec.addPrompt ?? `Sign in with another ${spec.label} subscription?`;
|
|
132
|
+
if (!await ctx.ui.confirm(`Add ${spec.label} account`, prompt)) return undefined;
|
|
133
|
+
|
|
134
|
+
const credential = await authenticate(spec, ctx);
|
|
135
|
+
const duplicate = duplicateAccount(spec, credential);
|
|
136
|
+
if (duplicate) throw new Error(`That account is already saved as “${accountLabel(spec, duplicate)}”.`);
|
|
137
|
+
|
|
138
|
+
store().saveAccount({
|
|
139
|
+
...credential,
|
|
140
|
+
id: randomUUID(),
|
|
141
|
+
label,
|
|
142
|
+
enabled: true,
|
|
143
|
+
identity: identityFor(spec, credential.access),
|
|
144
|
+
addedAt: Date.now(),
|
|
145
|
+
});
|
|
146
|
+
return label;
|
|
147
|
+
},
|
|
148
|
+
|
|
149
|
+
async reauth(ctx, accountId): Promise<string | undefined> {
|
|
150
|
+
const account = store().load().accounts.find(
|
|
151
|
+
(candidate) => candidate.id === accountId || candidate.label === accountId,
|
|
152
|
+
);
|
|
153
|
+
if (!account) throw new Error(`${spec.label} account “${accountId}” not found.`);
|
|
154
|
+
|
|
155
|
+
const credential = await authenticate(spec, ctx);
|
|
156
|
+
const duplicate = duplicateAccount(spec, credential, account.id);
|
|
157
|
+
if (duplicate) throw new Error(`That account is already saved as “${accountLabel(spec, duplicate)}”.`);
|
|
158
|
+
store().saveAccount({
|
|
159
|
+
...account,
|
|
160
|
+
...credential,
|
|
161
|
+
identity: identityFor(spec, credential.access),
|
|
162
|
+
});
|
|
163
|
+
return account.label;
|
|
164
|
+
},
|
|
165
|
+
|
|
166
|
+
async setEnabled(accountId, enabled): Promise<void> {
|
|
167
|
+
const account = store().load().accounts.find((candidate) => candidate.id === accountId);
|
|
168
|
+
if (!account) throw new Error(`${spec.label} account “${accountId}” not found.`);
|
|
169
|
+
store().saveAccount({ ...account, enabled });
|
|
170
|
+
},
|
|
171
|
+
|
|
172
|
+
async rename(accountId, label): Promise<void> {
|
|
173
|
+
const account = store().load().accounts.find((candidate) => candidate.id === accountId);
|
|
174
|
+
if (!account) throw new Error(`${spec.label} account “${accountId}” not found.`);
|
|
175
|
+
store().saveAccount({ ...account, label });
|
|
176
|
+
},
|
|
177
|
+
|
|
178
|
+
routing: {
|
|
179
|
+
async get(): Promise<RoutingMode> {
|
|
180
|
+
return store().load().mode;
|
|
181
|
+
},
|
|
182
|
+
async set(mode): Promise<RoutingMode> {
|
|
183
|
+
store().saveMode(mode);
|
|
184
|
+
return mode;
|
|
185
|
+
},
|
|
186
|
+
describe(mode): string {
|
|
187
|
+
return mode === "quota-aware"
|
|
188
|
+
? `Uses the ${spec.label} subscription with the most remaining quota.`
|
|
189
|
+
: `Uses ${spec.label} subscriptions in order, moving on when one is exhausted.`;
|
|
190
|
+
},
|
|
191
|
+
},
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export function chooseCredential<TApi extends Api>(
|
|
196
|
+
spec: PooledOAuthProviderSpec<TApi>,
|
|
197
|
+
primary: OAuthCredential,
|
|
198
|
+
): { id: string; credential: OAuthCredential; account?: PooledOAuthAccount } {
|
|
199
|
+
const pool = storeFor(spec).load();
|
|
200
|
+
const candidates = [
|
|
201
|
+
{
|
|
202
|
+
id: MAIN,
|
|
203
|
+
order: 0,
|
|
204
|
+
lastUsed: lastUsed.get(`${spec.id}:${MAIN}`) ?? 0,
|
|
205
|
+
quota: storeFor(spec).primaryQuota(),
|
|
206
|
+
value: { id: MAIN, credential: primary },
|
|
207
|
+
},
|
|
208
|
+
...pool.accounts
|
|
209
|
+
.filter((account) => account.enabled !== false && account.access)
|
|
210
|
+
.map((account, index) => ({
|
|
211
|
+
id: account.id,
|
|
212
|
+
order: index + 1,
|
|
213
|
+
lastUsed: lastUsed.get(`${spec.id}:${account.id}`) ?? account.lastUsed ?? 0,
|
|
214
|
+
quota: account.quota,
|
|
215
|
+
value: { id: account.id, credential: account, account },
|
|
216
|
+
})),
|
|
217
|
+
];
|
|
218
|
+
return selectRoutingCandidate(candidates, pool.mode)?.value ?? { id: MAIN, credential: primary };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async function freshCredential<TApi extends Api>(
|
|
222
|
+
spec: PooledOAuthProviderSpec<TApi>,
|
|
223
|
+
account: PooledOAuthAccount,
|
|
224
|
+
): Promise<PooledOAuthAccount> {
|
|
225
|
+
if (account.expires > Date.now() + 60_000) return account;
|
|
226
|
+
|
|
227
|
+
const key = `${spec.id}:${account.id}`;
|
|
228
|
+
const active = refreshes.get(key);
|
|
229
|
+
if (active) return active;
|
|
230
|
+
|
|
231
|
+
// Bounded: nothing upstream constrains this call, and a hung refresh would be
|
|
232
|
+
// shared by every later request for the account through the map above.
|
|
233
|
+
const refresh = oauthFor(spec).refresh(account, refreshAbortSignal()).then((credential) => {
|
|
234
|
+
const updated = { ...account, ...credential };
|
|
235
|
+
storeFor(spec).saveAccount(updated);
|
|
236
|
+
return updated;
|
|
237
|
+
}).finally(() => refreshes.delete(key));
|
|
238
|
+
refreshes.set(key, refresh);
|
|
239
|
+
return refresh;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
async function routedAuth<TApi extends Api>(
|
|
243
|
+
spec: PooledOAuthProviderSpec<TApi>,
|
|
244
|
+
oauth: OAuthAuth,
|
|
245
|
+
primary: OAuthCredential,
|
|
246
|
+
): Promise<ModelAuth> {
|
|
247
|
+
const selected = chooseCredential(spec, primary);
|
|
248
|
+
const credential = selected.account ? await freshCredential(spec, selected.account) : primary;
|
|
249
|
+
const now = Date.now();
|
|
250
|
+
lastUsed.set(`${spec.id}:${selected.id}`, now);
|
|
251
|
+
|
|
252
|
+
if (selected.account && now - (selected.account.lastUsed ?? 0) >= 60_000) {
|
|
253
|
+
storeFor(spec).saveAccount({ ...selected.account, ...credential, lastUsed: now });
|
|
254
|
+
}
|
|
255
|
+
return oauth.toAuth(credential);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export function registerPooledOAuthProvider<TApi extends Api>(pi: ExtensionAPI, spec: PooledOAuthProviderSpec<TApi>): void {
|
|
259
|
+
const provider = spec.createProvider();
|
|
260
|
+
const oauth = provider.auth.oauth;
|
|
261
|
+
if (!oauth) return;
|
|
262
|
+
|
|
263
|
+
const withQuotaObserver = (options: any) => ({
|
|
264
|
+
...options,
|
|
265
|
+
onResponse: async (response: { status: number; headers: Record<string, string> }, model: unknown) => {
|
|
266
|
+
try {
|
|
267
|
+
recordQuotaResponse(spec, requestAccessToken(options), response.status, response.headers);
|
|
268
|
+
} catch {
|
|
269
|
+
// Quota accounting is telemetry; it must never fail the response.
|
|
270
|
+
}
|
|
271
|
+
await options?.onResponse?.(response, model);
|
|
272
|
+
},
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
pi.registerProvider({
|
|
276
|
+
...provider,
|
|
277
|
+
auth: {
|
|
278
|
+
...provider.auth,
|
|
279
|
+
oauth: {
|
|
280
|
+
...oauth,
|
|
281
|
+
toAuth: (primary) => routedAuth(spec, oauth, primary),
|
|
282
|
+
},
|
|
283
|
+
},
|
|
284
|
+
stream: (model: any, context: any, options: any) => provider.stream(model, context, withQuotaObserver(options)),
|
|
285
|
+
streamSimple: (model: any, context: any, options: any) => provider.streamSimple(model, context, withQuotaObserver(options)),
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function requestAccessToken(options: any): string | undefined {
|
|
290
|
+
if (typeof options?.apiKey === "string") return options.apiKey;
|
|
291
|
+
const headers = options?.headers;
|
|
292
|
+
if (!headers || typeof headers !== "object") return undefined;
|
|
293
|
+
const authorization = Object.entries(headers).find(([key]) => key.toLowerCase() === "authorization")?.[1];
|
|
294
|
+
if (typeof authorization !== "string") return undefined;
|
|
295
|
+
const match = /^Bearer\s+(.+)$/i.exec(authorization);
|
|
296
|
+
return match?.[1];
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** Resolves which pooled account served a request, falling back to the primary. */
|
|
300
|
+
function accountIdForToken<TApi extends Api>(spec: PooledOAuthProviderSpec<TApi>, access: string | undefined): string {
|
|
301
|
+
if (!access) return MAIN;
|
|
302
|
+
return storeFor(spec).load().accounts.find((candidate) => candidate.access === access)?.id ?? MAIN;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function recordQuotaResponse<TApi extends Api>(
|
|
306
|
+
spec: PooledOAuthProviderSpec<TApi>,
|
|
307
|
+
access: string | undefined,
|
|
308
|
+
status: number,
|
|
309
|
+
headers: Record<string, string>,
|
|
310
|
+
): void {
|
|
311
|
+
if (spec.recordQuota) {
|
|
312
|
+
spec.recordQuota(accountIdForToken(spec, access), status, headers);
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
if (!access) return;
|
|
317
|
+
const store = storeFor(spec);
|
|
318
|
+
const account = store.load().accounts.find((candidate) => candidate.access === access);
|
|
319
|
+
const previous = account?.quota ?? store.primaryQuota();
|
|
320
|
+
const quota = quotaStateFromHeaders(status, headers, previous);
|
|
321
|
+
if (!quota || quota === previous) return;
|
|
322
|
+
|
|
323
|
+
if (account) store.saveAccount({ ...account, quota });
|
|
324
|
+
else setPrimaryQuota(spec.id, quota);
|
|
325
|
+
}
|
|
@@ -2,16 +2,16 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
|
2
2
|
import { accountProvider, routableProviders, type RoutingMode } from "../../core/accounts/registry.ts";
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* `/routing [
|
|
5
|
+
* `/routing [sequential|quota-aware] [provider]`
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
7
|
+
* sequential account 1, then account 2 when the first is exhausted
|
|
8
|
+
* quota-aware use the account with the most remaining capacity
|
|
9
9
|
*
|
|
10
10
|
* With no provider named, the mode is applied to every provider that supports
|
|
11
11
|
* routing. With no mode, the current modes are reported.
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
|
-
const MODES: RoutingMode[] = ["
|
|
14
|
+
const MODES: RoutingMode[] = ["sequential", "quota-aware"];
|
|
15
15
|
|
|
16
16
|
function isMode(value: string): value is RoutingMode {
|
|
17
17
|
return (MODES as string[]).includes(value);
|
|
@@ -19,12 +19,20 @@ function isMode(value: string): value is RoutingMode {
|
|
|
19
19
|
|
|
20
20
|
export function registerRoutingCommands(pi: ExtensionAPI): void {
|
|
21
21
|
pi.registerCommand("routing", {
|
|
22
|
-
description: "Account routing:
|
|
23
|
-
getArgumentCompletions: (prefix) =>
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
22
|
+
description: "Account routing: sequential or quota-aware",
|
|
23
|
+
getArgumentCompletions: (prefix) => {
|
|
24
|
+
const [mode, providerPrefix = ""] = prefix.trim().split(/\s+/, 2);
|
|
25
|
+
if (!/\s/.test(prefix)) {
|
|
26
|
+
return MODES.filter((candidate) => candidate.startsWith(mode ?? "")).map((candidate) => ({
|
|
27
|
+
value: candidate,
|
|
28
|
+
label: candidate === "quota-aware" ? "quota-aware: use remaining capacity" : "sequential: account 1, then 2",
|
|
29
|
+
}));
|
|
30
|
+
}
|
|
31
|
+
if (!mode || !isMode(mode)) return [];
|
|
32
|
+
return routableProviders()
|
|
33
|
+
.filter((provider) => provider.id.startsWith(providerPrefix))
|
|
34
|
+
.map((provider) => ({ value: `${mode} ${provider.id}`, label: provider.id }));
|
|
35
|
+
},
|
|
28
36
|
handler: async (args, ctx) => {
|
|
29
37
|
const [first, second] = args.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
|
30
38
|
const providers = second ? [accountProvider(second)].filter((entry) => !!entry) : routableProviders();
|
|
@@ -53,7 +61,7 @@ export function registerRoutingCommands(pi: ExtensionAPI): void {
|
|
|
53
61
|
}
|
|
54
62
|
|
|
55
63
|
if (!isMode(first)) {
|
|
56
|
-
ctx.ui.notify(`Usage: /routing [
|
|
64
|
+
ctx.ui.notify(`Usage: /routing [sequential|quota-aware] [provider]`, "warning");
|
|
57
65
|
return;
|
|
58
66
|
}
|
|
59
67
|
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 timbrinded
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|