@certalis/agent-smith 0.1.18 → 0.2.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.
@@ -0,0 +1,8 @@
1
+ {
2
+ "name": "agent-smith-provider-choice",
3
+ "version": "0.1.0",
4
+ "description": "Lets a Claude Code session choose an Agent-smith Claude-compatible provider without an automatic switch.",
5
+ "author": {
6
+ "name": "Agent-smith"
7
+ }
8
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "description": "Agent-smith provider-choice companion",
3
+ "modules": ["./register.js"]
4
+ }
@@ -0,0 +1,320 @@
1
+ const CAPACITY_HEADER = "x-agent-smith-provider-capacity";
2
+ const CAPACITY_DETAILS_HEADER = "x-agent-smith-provider-capacity-details";
3
+ const INTERACTIVE_CHOICE_HEADER = "x-agent-smith-interactive-provider-choice";
4
+ const PROVIDER_CHOICE_HEADER = "x-agent-smith-provider-choice";
5
+ const PROVIDER_CHOICE_MENU_HEADER = "x-agent-smith-provider-menu";
6
+ const PROVIDER_WAIT_HEADER = "x-agent-smith-provider-wait";
7
+ const PROMOTION_DECLINED_HEADER = "x-agent-smith-provider-promotion-declined";
8
+ const PROMOTION_DETAILS_HEADER = "x-agent-smith-provider-promotion-details";
9
+ const SERVED_PROVIDER_HEADER = "x-agent-smith-served-provider";
10
+ const SERVED_MODEL_HEADER = "x-agent-smith-served-model";
11
+ const WAIT = "Wait";
12
+
13
+ const CATEGORIES = new Set([
14
+ "five-hour-limit",
15
+ "weekly-limit",
16
+ "request-rate",
17
+ "token-allocation",
18
+ "burst",
19
+ "dynamic-throughput",
20
+ "temporary-capacity",
21
+ "unknown",
22
+ ]);
23
+
24
+ function headerValue(headers, name) {
25
+ if (headers && typeof headers.get === "function") return headers.get(name);
26
+ if (!headers || typeof headers !== "object") return null;
27
+ const found = Object.entries(headers).find(
28
+ ([key]) => key.toLowerCase() === name,
29
+ );
30
+ return typeof found?.[1] === "string" ? found[1] : null;
31
+ }
32
+
33
+ export function classifyCapacityResponse(status, headers) {
34
+ return (
35
+ (status === 409 || status === 429) &&
36
+ headerValue(headers, CAPACITY_HEADER) === "v1"
37
+ );
38
+ }
39
+
40
+ function isChoice(value) {
41
+ return (
42
+ typeof value === "object" &&
43
+ value !== null &&
44
+ typeof value.provider === "string" &&
45
+ value.provider.length > 0 &&
46
+ typeof value.model === "string" &&
47
+ value.model.length > 0
48
+ );
49
+ }
50
+
51
+ function isWait(value) {
52
+ return (
53
+ value === null ||
54
+ (typeof value === "object" &&
55
+ value !== null &&
56
+ Number.isSafeInteger(value.retryAt) &&
57
+ value.retryAt > 0)
58
+ );
59
+ }
60
+
61
+ function decodeHeaderJson(headers, name) {
62
+ const encoded = headerValue(headers, name);
63
+ if (!encoded || encoded.length > 16_384) return null;
64
+ try {
65
+ const base64 = encoded.replaceAll("-", "+").replaceAll("_", "/");
66
+ const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
67
+ return JSON.parse(
68
+ new TextDecoder().decode(
69
+ Uint8Array.from(atob(padded), (character) => character.charCodeAt(0)),
70
+ ),
71
+ );
72
+ } catch {
73
+ return null;
74
+ }
75
+ }
76
+
77
+ export function readCapacityDetails(headers) {
78
+ const value = decodeHeaderJson(headers, CAPACITY_DETAILS_HEADER);
79
+ try {
80
+ if (
81
+ typeof value !== "object" ||
82
+ value === null ||
83
+ typeof value.blockedProvider !== "string" ||
84
+ value.blockedProvider.length === 0 ||
85
+ typeof value.category !== "string" ||
86
+ !CATEGORIES.has(value.category) ||
87
+ !Array.isArray(value.choices) ||
88
+ !value.choices.every(isChoice) ||
89
+ !isWait(value.wait)
90
+ ) {
91
+ return null;
92
+ }
93
+ if (
94
+ value.kind !== undefined &&
95
+ value.kind !== "capacity" &&
96
+ value.kind !== "manual"
97
+ ) {
98
+ return null;
99
+ }
100
+ return value;
101
+ } catch {
102
+ return null;
103
+ }
104
+ }
105
+
106
+ export function readPromotionDetails(headers) {
107
+ const value = decodeHeaderJson(headers, PROMOTION_DETAILS_HEADER);
108
+ return typeof value === "object" &&
109
+ value !== null &&
110
+ Array.isArray(value.choices) &&
111
+ value.choices.length > 0 &&
112
+ value.choices.every(isChoice)
113
+ ? value
114
+ : null;
115
+ }
116
+
117
+ function withoutHeader(headers, name) {
118
+ return Object.fromEntries(
119
+ Object.entries(headers ?? {}).filter(([key]) => key.toLowerCase() !== name),
120
+ );
121
+ }
122
+
123
+ function choiceHeaders(
124
+ init,
125
+ provider,
126
+ declinePromotion = false,
127
+ openChoiceMenu = false,
128
+ waitForProvider = false,
129
+ ) {
130
+ const headers = withoutHeader(
131
+ withoutHeader(
132
+ withoutHeader(init?.headers, PROVIDER_CHOICE_HEADER),
133
+ PROVIDER_CHOICE_MENU_HEADER,
134
+ ),
135
+ PROMOTION_DECLINED_HEADER,
136
+ );
137
+ headers[INTERACTIVE_CHOICE_HEADER] = "v1";
138
+ if (provider) headers[PROVIDER_CHOICE_HEADER] = provider;
139
+ if (declinePromotion) headers[PROMOTION_DECLINED_HEADER] = "v1";
140
+ if (openChoiceMenu) headers[PROVIDER_CHOICE_MENU_HEADER] = "v1";
141
+ if (waitForProvider) headers[PROVIDER_WAIT_HEADER] = "v1";
142
+ return { ...init, headers };
143
+ }
144
+
145
+ function displayProvider(provider) {
146
+ return provider
147
+ .replace(/-claude$/, "")
148
+ .split(/[-_]/)
149
+ .filter(Boolean)
150
+ .map((part) => part.slice(0, 1).toUpperCase() + part.slice(1))
151
+ .join(" ");
152
+ }
153
+
154
+ function choiceLabel(choice) {
155
+ return `${displayProvider(choice.provider)} · ${choice.model}`;
156
+ }
157
+
158
+ function categoryLabel(category) {
159
+ return (
160
+ {
161
+ "five-hour-limit": "a five-hour session limit",
162
+ "weekly-limit": "a weekly limit",
163
+ "request-rate": "request rate",
164
+ "token-allocation": "token allocation",
165
+ burst: "traffic burst",
166
+ "dynamic-throughput": "temporary provider capacity",
167
+ "temporary-capacity": "temporary provider capacity",
168
+ unknown: "an unknown provider limit",
169
+ }[category] ?? "an unknown provider limit"
170
+ );
171
+ }
172
+
173
+ function servedStatus(response) {
174
+ const provider = headerValue(response.headers, SERVED_PROVIDER_HEADER);
175
+ const model = headerValue(response.headers, SERVED_MODEL_HEADER);
176
+ return provider && model ? `${displayProvider(provider)} · ${model}` : null;
177
+ }
178
+
179
+ function fetchResponse(result) {
180
+ if (typeof result !== "object" || result === null || !("value" in result)) {
181
+ return null;
182
+ }
183
+ const response = result.value;
184
+ return typeof response === "object" && response !== null ? response : null;
185
+ }
186
+
187
+ async function chooseProvider(details, ask) {
188
+ return await chooseChoices(
189
+ details.kind === "manual"
190
+ ? "Choose provider for this conversation."
191
+ : `${displayProvider(details.blockedProvider)} cannot serve this turn because of ${categoryLabel(details.category)}. Switch provider?`,
192
+ details.choices,
193
+ ask,
194
+ );
195
+ }
196
+
197
+ async function chooseChoices(question, choices, ask) {
198
+ let start = 0;
199
+ while (start < choices.length) {
200
+ const remaining = choices.length - start;
201
+ const take = remaining > 3 ? 2 : 3;
202
+ const page = choices.slice(start, start + take);
203
+ const hasMore = start + page.length < choices.length;
204
+ const labels = page.map(choiceLabel);
205
+ const answer = await ask(question, [
206
+ ...labels,
207
+ ...(hasMore ? ["More providers"] : []),
208
+ WAIT,
209
+ ]);
210
+ if (answer === WAIT) return null;
211
+ if (answer === "More providers" && hasMore) {
212
+ start += page.length;
213
+ continue;
214
+ }
215
+ const choice = page.find((candidate) => choiceLabel(candidate) === answer);
216
+ if (choice) return choice;
217
+ return undefined;
218
+ }
219
+ return undefined;
220
+ }
221
+
222
+ export async function choosePromotion(choices, ask) {
223
+ return await chooseChoices(
224
+ "A higher-ranked provider has an eligible Agent-smith account. Switch this conversation?",
225
+ choices,
226
+ ask,
227
+ );
228
+ }
229
+
230
+ /**
231
+ * The transport-neutral core of the Claude Code hook. It starts every eligible
232
+ * pool request in interactive mode, asks only after a versioned capacity
233
+ * response, then sends the unchanged request once more with the chosen provider.
234
+ */
235
+ export async function retryCapacityBlockedRequest({
236
+ init,
237
+ send,
238
+ ask,
239
+ setStatus,
240
+ initialChoice,
241
+ declinePromotion = false,
242
+ openChoiceMenu = false,
243
+ onPromotion,
244
+ }) {
245
+ let result = await send(
246
+ choiceHeaders(init, initialChoice, declinePromotion, openChoiceMenu),
247
+ );
248
+ let response = fetchResponse(result);
249
+ if (!response) return result;
250
+ const initialStatus = servedStatus(response);
251
+ if (initialStatus) setStatus(initialStatus);
252
+ if (!classifyCapacityResponse(response.status, response.headers)) {
253
+ const promotion = response.ok
254
+ ? readPromotionDetails(response.headers)
255
+ : null;
256
+ if (promotion) onPromotion?.(promotion.choices);
257
+ return result;
258
+ }
259
+
260
+ const details = readCapacityDetails(response.headers);
261
+ if (!details) return result;
262
+ if (details.choices.length === 0) {
263
+ return details.kind === "manual" ? await send(choiceHeaders(init)) : result;
264
+ }
265
+ let choice;
266
+ try {
267
+ choice = await chooseProvider(details, ask);
268
+ } catch {
269
+ setStatus(
270
+ "Agent-smith: provider choice dismissed; this turn remains blocked.",
271
+ );
272
+ return result;
273
+ }
274
+ if (choice === undefined) {
275
+ setStatus(
276
+ "Agent-smith: choose one listed provider or Wait; this turn remains blocked.",
277
+ );
278
+ return result;
279
+ }
280
+ if (choice === null && details.kind === "manual") {
281
+ setStatus("Agent-smith: provider choice left unchanged.");
282
+ return result;
283
+ }
284
+ if (choice === null && details.wait === null) {
285
+ setStatus(
286
+ "Agent-smith: the provider supplied no retry time, so this turn remains on its current provider.",
287
+ );
288
+ return result;
289
+ }
290
+ result = await send(
291
+ choiceHeaders(
292
+ init,
293
+ choice?.provider,
294
+ false,
295
+ false,
296
+ !choice && details.kind !== "manual",
297
+ ),
298
+ );
299
+ response = fetchResponse(result);
300
+ if (!response) return result;
301
+ const status = servedStatus(response);
302
+ if (status) setStatus(status);
303
+ if (!choice) {
304
+ const waitResult = readCapacityDetails(response.headers);
305
+ if (waitResult) {
306
+ setStatus(
307
+ "Agent-smith: it cannot hold this request until the provider retry time, so this turn remains blocked.",
308
+ );
309
+ }
310
+ }
311
+ return result;
312
+ }
313
+
314
+ export function isAnthropicPoolRequest(url) {
315
+ try {
316
+ return new URL(url).pathname.startsWith("/v1/pool/anthropic-messages/");
317
+ } catch {
318
+ return false;
319
+ }
320
+ }
@@ -0,0 +1,77 @@
1
+ import {
2
+ choosePromotion,
3
+ isAnthropicPoolRequest,
4
+ retryCapacityBlockedRequest,
5
+ } from "./provider-choice.js";
6
+
7
+ export function register(on) {
8
+ let promotion = null;
9
+ let promotionDecision = null;
10
+ let promotionReadyAfterTurn = 0;
11
+ let completedMainTurns = 0;
12
+ let openChoiceMenu = false;
13
+ const providerChoiceDecisions = new Map();
14
+ on("session.start", async ($, event, next) => {
15
+ await $.command.register({
16
+ name: "agent-smith-provider",
17
+ description: "Choose a provider for this conversation",
18
+ });
19
+ return await next(event);
20
+ });
21
+ on("command.run", { command: "agent-smith-provider" }, ($) => {
22
+ openChoiceMenu = true;
23
+ $.ui.status("Agent-smith: choose a provider on your next turn.");
24
+ return {
25
+ isTextDisplayOnly: true,
26
+ text: "Agent-smith: send your next message to choose a provider.",
27
+ };
28
+ });
29
+ on("turn.complete", async (_$, event, next) => {
30
+ if (!event.agentId) completedMainTurns += 1;
31
+ return await next(event);
32
+ });
33
+ on("http.fetch", async ($, event, next) => {
34
+ if (!isAnthropicPoolRequest(event.url)) return next(event);
35
+ let initialChoice;
36
+ const chooseNow = openChoiceMenu;
37
+ openChoiceMenu = false;
38
+ let declinePromotion = false;
39
+ if (
40
+ promotionDecision ||
41
+ (promotion && completedMainTurns >= promotionReadyAfterTurn)
42
+ ) {
43
+ promotionDecision ??= choosePromotion(promotion, (question, options) =>
44
+ $.ui.ask(question, { header: "Agent-smith", options }),
45
+ )
46
+ .then((choice) => choice?.provider)
47
+ .catch(() => undefined);
48
+ initialChoice = await promotionDecision;
49
+ declinePromotion = !initialChoice;
50
+ promotion = null;
51
+ promotionDecision = null;
52
+ }
53
+ return await retryCapacityBlockedRequest({
54
+ init: event.init,
55
+ initialChoice,
56
+ declinePromotion,
57
+ openChoiceMenu: chooseNow,
58
+ ask: (question, options) => {
59
+ const key = JSON.stringify([question, options]);
60
+ const existing = providerChoiceDecisions.get(key);
61
+ if (existing) return existing;
62
+ const decision = $.ui
63
+ .ask(question, { header: "Agent-smith", options })
64
+ .finally(() => providerChoiceDecisions.delete(key));
65
+ providerChoiceDecisions.set(key, decision);
66
+ return decision;
67
+ },
68
+ setStatus: (status) => $.ui.status(status),
69
+ onPromotion: (choices) => {
70
+ if (promotion) return;
71
+ promotion = choices;
72
+ promotionReadyAfterTurn = completedMainTurns + 1;
73
+ },
74
+ send: async (init) => await next({ ...event, init }),
75
+ });
76
+ });
77
+ }