@zhexin/pi-agy 0.0.4 → 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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zhexin/pi-agy",
3
3
  "description": "Antigravity OAuth provider for the Pi agent.",
4
- "version": "0.0.4",
4
+ "version": "0.2.0",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "keywords": [
package/src/api.ts CHANGED
@@ -1,17 +1,11 @@
1
- import { randomBytes, timingSafeEqual } from "node:crypto";
2
- import { once } from "node:events";
3
- import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
4
- import { createInterface } from "node:readline";
5
- import { Readable } from "node:stream";
6
-
7
1
  import {
8
2
  clampThinkingLevel,
9
3
  lazyStream,
4
+ type FetchFunction,
10
5
  type GoogleOptions,
11
6
  type Model,
12
7
  type ModelThinkingLevel,
13
8
  type ProviderStreams,
14
- type SimpleStreamOptions,
15
9
  type StreamOptions,
16
10
  type TranscriptContext,
17
11
  } from "@earendil-works/pi-ai";
@@ -19,159 +13,128 @@ import { googleGenerativeAIApi } from "@earendil-works/pi-ai/compat";
19
13
 
20
14
  import { endpointUrl, PROJECT_HEADER, USER_AGENT } from "./ccpa.ts";
21
15
 
22
- async function readBody(request: IncomingMessage): Promise<unknown> {
23
- const chunks: Buffer[] = [];
24
- let size = 0;
25
- for await (const chunk of request) {
26
- size += chunk.length;
27
- if (size > 64 * 1024 * 1024) throw new Error("AGY request exceeds 64 MiB.");
28
- chunks.push(chunk);
29
- }
30
- return JSON.parse(Buffer.concat(chunks).toString("utf8"));
31
- }
32
-
33
- async function unwrap(
34
- upstream: Response,
35
- response: ServerResponse,
36
- signal: AbortSignal,
37
- ): Promise<void> {
38
- if (!upstream.body) throw new Error("AGY returned an empty response body.");
39
- const input = Readable.fromWeb(upstream.body).setEncoding("utf8");
40
- const lines = createInterface({ input, crlfDelay: Infinity });
16
+ function createSseUnwrapTransform(): TransformStream<string, string> {
17
+ let lineBuffer = "";
41
18
  let data: string[] = [];
42
- const flush = async () => {
19
+
20
+ const flushEvent = (controller: TransformStreamDefaultController<string>) => {
43
21
  if (!data.length) return;
44
22
  const text = data.join("\n");
45
23
  data = [];
46
24
  if (text === "[DONE]") return;
47
25
  const event = JSON.parse(text) as { response?: unknown };
48
- if (!response.write(`data: ${JSON.stringify(event.response ?? event)}\n\n`)) {
49
- await once(response, "drain", { signal });
50
- }
26
+ controller.enqueue(`data: ${JSON.stringify(event.response ?? event)}\n\n`);
51
27
  };
52
- try {
53
- for await (const line of lines) {
54
- signal.throwIfAborted();
55
- if (!line) await flush();
56
- else if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));
57
- }
58
- await flush();
59
- } finally {
60
- lines.close();
61
- input.destroy();
62
- }
28
+
29
+ const processLine = (line: string, controller: TransformStreamDefaultController<string>) => {
30
+ const normalized = line.endsWith("\r") ? line.slice(0, -1) : line;
31
+ if (!normalized) flushEvent(controller);
32
+ else if (normalized.startsWith("data:")) data.push(normalized.slice(5).replace(/^ /, ""));
33
+ };
34
+
35
+ return new TransformStream<string, string>({
36
+ transform(chunk, controller) {
37
+ lineBuffer += chunk;
38
+ const lines = lineBuffer.split("\n");
39
+ lineBuffer = lines.pop() ?? "";
40
+ for (const line of lines) processLine(line, controller);
41
+ },
42
+ flush(controller) {
43
+ if (lineBuffer) processLine(lineBuffer, controller);
44
+ flushEvent(controller);
45
+ },
46
+ });
47
+ }
48
+
49
+ async function parseRequestBody(
50
+ input: Parameters<FetchFunction>[0],
51
+ init?: RequestInit,
52
+ ): Promise<unknown> {
53
+ if (typeof init?.body === "string") return JSON.parse(init.body);
54
+ if (init?.body != null) return new Response(init.body).json();
55
+ if (input instanceof Request) return input.json();
56
+ throw new Error("AGY request is missing a JSON body.");
63
57
  }
64
58
 
65
- async function bridge(
59
+ function createAgyFetch(
66
60
  model: Model<string>,
67
61
  backendId: string,
68
62
  access: string,
69
63
  project: string,
70
64
  endpoint: string,
71
65
  options: StreamOptions,
72
- ) {
73
- const key = randomBytes(32).toString("base64url");
74
- const forward = async (request: IncomingMessage, response: ServerResponse) => {
75
- const supplied = request.headers["x-goog-api-key"];
76
- if (
77
- typeof supplied !== "string" ||
78
- Buffer.byteLength(supplied) !== Buffer.byteLength(key) ||
79
- !timingSafeEqual(Buffer.from(supplied), Buffer.from(key)) ||
80
- request.headers.origin
81
- ) {
82
- response.writeHead(401).end();
83
- return;
84
- }
85
- const url = new URL(request.url ?? "/", "http://127.0.0.1");
86
- const match = /^\/models\/([^/]+):streamGenerateContent$/.exec(url.pathname);
87
- if (request.method !== "POST" || !match?.[1]) {
88
- response.writeHead(404).end();
89
- return;
66
+ ): FetchFunction {
67
+ const baseFetch = options.fetch ?? fetch;
68
+
69
+ return async (input, init) => {
70
+ const rawUrl =
71
+ typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
72
+ const url = new URL(rawUrl);
73
+ const method = (
74
+ init?.method ?? (input instanceof Request ? input.method : "GET")
75
+ ).toUpperCase();
76
+ if (method !== "POST" || !/^\/models\/([^/]+):streamGenerateContent$/.test(url.pathname)) {
77
+ return new Response(null, { status: 404 });
90
78
  }
91
- const disconnected = new AbortController();
92
- response.on("close", () => disconnected.abort());
93
- const signal = AbortSignal.any([
94
- disconnected.signal,
95
- AbortSignal.timeout(options.timeoutMs ?? 300_000),
96
- ...(options.signal ? [options.signal] : []),
97
- ]);
98
- const body = await readBody(request);
99
- const upstream = await (options.fetch ?? fetch)(
100
- `${endpoint}/v1internal:streamGenerateContent?alt=sse`,
101
- {
102
- method: "POST",
103
- headers: {
104
- Authorization: `Bearer ${access}`,
105
- "Content-Type": "application/json",
106
- "User-Agent": USER_AGENT,
107
- },
108
- body: JSON.stringify({ project, model: backendId, request: body }),
109
- signal,
110
- redirect: "error",
79
+
80
+ const signals: AbortSignal[] = [AbortSignal.timeout(options.timeoutMs ?? 300_000)];
81
+ if (init?.signal) signals.push(init.signal);
82
+ if (options.signal && options.signal !== init?.signal) signals.push(options.signal);
83
+ const signal = AbortSignal.any(signals);
84
+
85
+ const body = await parseRequestBody(input, init);
86
+ const upstream = await baseFetch(`${endpoint}/v1internal:streamGenerateContent?alt=sse`, {
87
+ method: "POST",
88
+ headers: {
89
+ Authorization: `Bearer ${access}`,
90
+ "Content-Type": "application/json",
91
+ "User-Agent": USER_AGENT,
111
92
  },
112
- );
113
- try {
114
- await options.onResponse?.(
93
+ body: JSON.stringify({ project, model: backendId, request: body }),
94
+ signal,
95
+ redirect: "error",
96
+ });
97
+
98
+ await options
99
+ .onResponse?.(
115
100
  { status: upstream.status, headers: Object.fromEntries(upstream.headers) },
116
101
  model,
117
- );
118
- response.writeHead(upstream.status, {
119
- "Content-Type":
120
- upstream.headers.get("content-type") ??
121
- (upstream.ok ? "text/event-stream" : "application/json"),
122
- ...(upstream.headers.has("retry-after")
123
- ? { "Retry-After": upstream.headers.get("retry-after")! }
124
- : {}),
102
+ )
103
+ ?.catch(async (error) => {
104
+ await upstream.body?.cancel().catch(() => {});
105
+ throw error;
125
106
  });
126
- if (upstream.ok) await unwrap(upstream, response, signal);
127
- else response.write(Buffer.from(await upstream.arrayBuffer()));
128
- response.end();
129
- } finally {
130
- if (upstream.body && !upstream.body.locked) await upstream.body.cancel().catch(() => {});
131
- }
132
- };
133
- const server = createServer((request, response) => {
134
- void forward(request, response).catch((error: unknown) => {
135
- if (response.destroyed) return;
136
- if (response.headersSent) response.destroy(error instanceof Error ? error : undefined);
137
- else
138
- response.writeHead(502, { "Content-Type": "application/json" }).end(
139
- JSON.stringify({
140
- error: {
141
- code: 502,
142
- message: error instanceof Error ? error.message : "AGY forwarding failed",
143
- },
144
- }),
145
- );
107
+
108
+ if (!upstream.ok) return upstream;
109
+ if (!upstream.body) throw new Error("AGY returned an empty response body.");
110
+
111
+ const unwrapped = upstream.body
112
+ .pipeThrough(new TextDecoderStream())
113
+ .pipeThrough(createSseUnwrapTransform())
114
+ .pipeThrough(new TextEncoderStream());
115
+
116
+ return new Response(unwrapped, {
117
+ status: upstream.status,
118
+ statusText: upstream.statusText,
119
+ headers: {
120
+ "Content-Type": upstream.headers.get("content-type") ?? "text/event-stream",
121
+ },
146
122
  });
147
- });
148
- await new Promise<void>((resolve, reject) => {
149
- server.once("error", reject);
150
- server.listen(0, "127.0.0.1", resolve);
151
- });
152
- server.unref();
153
- const address = server.address();
154
- if (!address || typeof address === "string") {
155
- server.close();
156
- throw new Error("Could not start the AGY request adapter.");
157
- }
158
- return {
159
- key,
160
- baseUrl: `http://127.0.0.1:${address.port}`,
161
- close() {
162
- server.close();
163
- server.closeAllConnections();
164
- },
165
123
  };
166
124
  }
167
125
 
168
126
  const google = googleGenerativeAIApi();
169
127
 
170
- function stream(
171
- method: "stream" | "streamSimple",
128
+ function readGoogleThinkingLevel({ thinking }: GoogleOptions): ModelThinkingLevel {
129
+ if (!thinking?.enabled) return "off";
130
+ return (thinking.level?.toLowerCase() as ModelThinkingLevel | undefined) ?? "medium";
131
+ }
132
+
133
+ function streamAgy(
172
134
  model: Model<string>,
173
135
  context: TranscriptContext,
174
- options: SimpleStreamOptions & GoogleOptions = {},
136
+ options: GoogleOptions,
137
+ requestedLevel: ModelThinkingLevel,
175
138
  ) {
176
139
  return lazyStream(
177
140
  model,
@@ -180,47 +143,39 @@ function stream(
180
143
  const headers = new Headers();
181
144
  for (const [name, value] of Object.entries({ ...model.headers, ...options.headers }))
182
145
  if (value !== null) headers.set(name, value);
146
+
183
147
  const project = headers.get(PROJECT_HEADER);
184
148
  if (!options.apiKey || !project) throw new Error("Run /login agy to authenticate.");
185
- const requestedLevel =
186
- method === "streamSimple"
187
- ? (options.reasoning ?? "off")
188
- : options.thinking?.enabled
189
- ? ((options.thinking.level?.toLowerCase() as ModelThinkingLevel | undefined) ??
190
- "medium")
191
- : "off";
149
+
192
150
  const level = clampThinkingLevel(model, requestedLevel);
193
151
  const backendId = model.thinkingLevelMap?.[level];
194
- const adapter = await bridge(
195
- model,
196
- backendId ?? model.id,
197
- options.apiKey,
198
- project,
199
- endpointUrl(model.baseUrl),
200
- options,
201
- );
152
+ if (!backendId) {
153
+ throw new Error(`AGY model "${model.id}" has no backend ID for thinking level "${level}".`);
154
+ }
155
+
156
+ const endpoint = endpointUrl(model.baseUrl);
157
+ const agyFetch = createAgyFetch(model, backendId, options.apiKey, project, endpoint, options);
202
158
  const { fetch: _fetch, onResponse: _onResponse, ...innerOptions } = options;
159
+
203
160
  headers.delete(PROJECT_HEADER);
204
161
  headers.delete("authorization");
205
162
  headers.delete("x-goog-api-key");
206
- return (async function* () {
207
- try {
208
- // AGY selects thinking effort through the backend ID, not Gemini's thinking config.
209
- yield* google[backendId ? "stream" : method](
210
- { ...model, baseUrl: adapter.baseUrl, headers: Object.fromEntries(headers) },
211
- context,
212
- {
213
- ...innerOptions,
214
- maxTokens: innerOptions.maxTokens ?? model.maxTokens,
215
- ...(backendId ? { thinking: { enabled: true } } : {}),
216
- apiKey: adapter.key,
217
- headers: Object.fromEntries(headers),
218
- },
219
- );
220
- } finally {
221
- adapter.close();
222
- }
223
- })();
163
+ const cleanHeaders = Object.fromEntries(headers);
164
+
165
+ const streamOptions: GoogleOptions = {
166
+ ...innerOptions,
167
+ maxTokens: innerOptions.maxTokens ?? model.maxTokens,
168
+ // AGY selects thinking effort through the backend ID, not Gemini's thinking config.
169
+ thinking: { enabled: true },
170
+ apiKey: "agy",
171
+ headers: cleanHeaders,
172
+ fetch: agyFetch,
173
+ };
174
+ return google.stream(
175
+ { ...model, baseUrl: endpoint, headers: cleanHeaders },
176
+ context,
177
+ streamOptions,
178
+ );
224
179
  },
225
180
  undefined,
226
181
  options.signal,
@@ -228,6 +183,11 @@ function stream(
228
183
  }
229
184
 
230
185
  export const api: ProviderStreams = {
231
- stream: (model, context, options) => stream("stream", model, context, options),
232
- streamSimple: (model, context, options) => stream("streamSimple", model, context, options),
186
+ stream(model, context, options = {}) {
187
+ return streamAgy(model, context, options, readGoogleThinkingLevel(options));
188
+ },
189
+ streamSimple(model, context, options = {}) {
190
+ const { reasoning = "off", ...googleOptions } = options;
191
+ return streamAgy(model, context, googleOptions, reasoning);
192
+ },
233
193
  };
package/src/ccpa.ts CHANGED
@@ -2,6 +2,7 @@ import { arch, platform } from "node:os";
2
2
  import { setTimeout } from "node:timers/promises";
3
3
 
4
4
  import type {
5
+ ImageModel,
5
6
  Model,
6
7
  ModelThinkingLevel,
7
8
  OAuthCredential,
@@ -31,8 +32,10 @@ type Catalog = {
31
32
  maxTokens: number;
32
33
  maxOutputTokens: number;
33
34
  recommended?: boolean;
35
+ supportsImages?: boolean;
34
36
  }
35
37
  >;
38
+ imageGenerationModelIds?: string[];
36
39
  agentModelSorts: {
37
40
  groups: {
38
41
  modelIds: string[];
@@ -66,7 +69,7 @@ export async function jsonRequest<T>(
66
69
  const response = await fetch(url, {
67
70
  ...init,
68
71
  redirect: "error",
69
- signal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]),
72
+ signal,
70
73
  });
71
74
  const body = (await response.json().catch(() => undefined)) as
72
75
  | {
@@ -163,7 +166,7 @@ export async function onboard(
163
166
  export async function fetchModels(
164
167
  credential: AgyCredential,
165
168
  signal: AbortSignal,
166
- ): Promise<Model<"google-generative-ai">[]> {
169
+ ): Promise<(Model<"google-generative-ai"> | ImageModel<"agy-images">)[]> {
167
170
  const catalog = await rpc<Catalog>(
168
171
  credential.access,
169
172
  credential.endpoint,
@@ -171,28 +174,32 @@ export async function fetchModels(
171
174
  { project: credential.project },
172
175
  signal,
173
176
  );
174
- const ids = catalog.agentModelSorts.flatMap((sort) =>
177
+
178
+ const chatIds = catalog.agentModelSorts.flatMap((sort) =>
175
179
  sort.groups.flatMap((group) => group.modelIds),
176
180
  );
181
+ const variants = chatIds.flatMap((id) => {
182
+ const match = /^(.+)-(off|minimal|low|medium|high|xhigh|max)$/.exec(id);
183
+ if (!match) return [];
177
184
 
178
- const variants = ids.map((id) => {
179
185
  const info = catalog.models[id]!;
180
- const match = /^(.*)-(off|minimal|low|medium|high|xhigh|max)$/.exec(id);
181
- const modelId = match?.[1] ?? id;
182
- const level = match?.[2] as ModelThinkingLevel | undefined;
186
+ const modelId = match[1]!;
187
+ const level = match[2] as ModelThinkingLevel;
183
188
  const name = info.displayName || modelId;
184
- return {
185
- id,
186
- modelId,
187
- level,
188
- name: level ? name.replace(new RegExp(`\\s*\\(${level}\\)\\s*$`, "i"), "") : name,
189
- contextWindow: info.maxTokens,
190
- maxOutputTokens: info.maxOutputTokens,
191
- };
189
+ return [
190
+ {
191
+ id,
192
+ modelId,
193
+ level,
194
+ name: name.replace(new RegExp(`\\s*\\(${level}\\)\\s*$`, "i"), ""),
195
+ contextWindow: info.maxTokens,
196
+ maxOutputTokens: info.maxOutputTokens,
197
+ },
198
+ ];
192
199
  });
193
- const models = [...Map.groupBy(variants, ({ modelId }) => modelId)].map(
200
+ const chatModels = [...Map.groupBy(variants, ({ modelId }) => modelId)].map(
194
201
  ([id, variants]): Model<"google-generative-ai"> => {
195
- const levels = variants.flatMap(({ level, id }) => (level ? [[level, id]] : []));
202
+ const levels = variants.map(({ level, id }) => [level, id]);
196
203
  const thinkingLevelMap: ThinkingLevelMap = {
197
204
  off: null,
198
205
  minimal: null,
@@ -218,5 +225,22 @@ export async function fetchModels(
218
225
  };
219
226
  },
220
227
  );
221
- return models;
228
+
229
+ const imageModels =
230
+ catalog.imageGenerationModelIds?.map((id): ImageModel<"agy-images"> => {
231
+ const info = catalog.models[id];
232
+ return {
233
+ type: "image",
234
+ id,
235
+ name: info?.displayName || id,
236
+ provider: "agy",
237
+ api: "agy-images",
238
+ baseUrl: credential.endpoint,
239
+ input: info?.supportsImages ? ["text", "image"] : ["text"],
240
+ output: ["text", "image"],
241
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
242
+ };
243
+ }) ?? [];
244
+
245
+ return [...chatModels, ...imageModels];
222
246
  }
package/src/images.ts ADDED
@@ -0,0 +1,133 @@
1
+ import {
2
+ calculateCost,
3
+ type AssistantImages,
4
+ type ProviderImages,
5
+ type Usage,
6
+ } from "@earendil-works/pi-ai";
7
+
8
+ import { endpointUrl, PROJECT_HEADER, USER_AGENT } from "./ccpa.ts";
9
+
10
+ type GeminiResponse = {
11
+ responseId: string;
12
+ candidates: {
13
+ content: {
14
+ parts: {
15
+ thought: boolean;
16
+ text: string;
17
+ inlineData: { mimeType: string; data: string };
18
+ }[];
19
+ };
20
+ finishReason: string;
21
+ finishMessage: string;
22
+ }[];
23
+ promptFeedback: { blockReason: string; blockReasonMessage: string };
24
+ usageMetadata: {
25
+ promptTokenCount: number;
26
+ candidatesTokenCount: number;
27
+ cachedContentTokenCount: number;
28
+ thoughtsTokenCount: number;
29
+ totalTokenCount: number;
30
+ };
31
+ };
32
+
33
+ export const imagesApi: ProviderImages = {
34
+ async generateImages(model, context, options): Promise<AssistantImages> {
35
+ const result: AssistantImages = {
36
+ api: model.api,
37
+ provider: model.provider,
38
+ model: model.id,
39
+ output: [],
40
+ stopReason: "stop",
41
+ timestamp: Date.now(),
42
+ };
43
+ const signal = options?.signal;
44
+
45
+ try {
46
+ signal?.throwIfAborted();
47
+ const headers = new Headers();
48
+ for (const [name, value] of Object.entries({ ...model.headers, ...options?.headers }))
49
+ if (value !== null) headers.set(name, value);
50
+ const project = headers.get(PROJECT_HEADER);
51
+ if (!options?.apiKey || !project) throw new Error("Run /login agy to authenticate.");
52
+
53
+ const payload = {
54
+ contents: [
55
+ {
56
+ role: "user",
57
+ parts: context.input.map((item) =>
58
+ item.type === "text"
59
+ ? { text: item.text }
60
+ : { inlineData: { data: item.data, mimeType: item.mimeType } },
61
+ ),
62
+ },
63
+ ],
64
+ generationConfig: { responseModalities: ["TEXT", "IMAGE"] },
65
+ };
66
+
67
+ const httpResponse = await (options.fetch ?? fetch)(
68
+ `${endpointUrl(model.baseUrl)}/v1internal:generateContent`,
69
+ {
70
+ method: "POST",
71
+ headers: {
72
+ Authorization: `Bearer ${options.apiKey}`,
73
+ "Content-Type": "application/json",
74
+ "User-Agent": USER_AGENT,
75
+ },
76
+ body: JSON.stringify({
77
+ project,
78
+ model: model.id,
79
+ request: payload,
80
+ }),
81
+ redirect: "error",
82
+ signal: signal ?? null,
83
+ },
84
+ );
85
+
86
+ if (!httpResponse.ok) {
87
+ const body = (await httpResponse.json().catch(() => undefined)) as
88
+ | { error?: { message?: string } }
89
+ | undefined;
90
+ const message = body?.error?.message;
91
+ throw new Error(
92
+ `AGY image request failed (HTTP ${httpResponse.status})${message ? `: ${message}` : ""}`,
93
+ );
94
+ }
95
+
96
+ const wrapped = (await httpResponse.json()) as GeminiResponse & { response?: GeminiResponse };
97
+ const response = wrapped.response ?? wrapped;
98
+ const candidate = response.candidates?.[0];
99
+ for (const { thought, text, inlineData } of candidate?.content.parts ?? []) {
100
+ if (thought) continue;
101
+ if (text) result.output.push({ type: "text", text });
102
+ if (inlineData) result.output.push({ type: "image", ...inlineData });
103
+ }
104
+ if (response.responseId) result.responseId = response.responseId;
105
+ if (response.usageMetadata) {
106
+ const raw = response.usageMetadata;
107
+ const usage: Usage = {
108
+ input: raw.promptTokenCount - raw.cachedContentTokenCount,
109
+ output: raw.candidatesTokenCount + raw.thoughtsTokenCount,
110
+ cacheRead: raw.cachedContentTokenCount,
111
+ cacheWrite: 0,
112
+ reasoning: raw.thoughtsTokenCount,
113
+ totalTokens: raw.totalTokenCount,
114
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
115
+ };
116
+ calculateCost(model, usage);
117
+ result.usage = usage;
118
+ }
119
+ if (!result.output.some((block) => block.type === "image")) {
120
+ const reason =
121
+ response.promptFeedback?.blockReasonMessage ||
122
+ response.promptFeedback?.blockReason ||
123
+ candidate?.finishMessage ||
124
+ (candidate?.finishReason === "STOP" ? undefined : candidate?.finishReason);
125
+ throw new Error(`AGY returned no image${reason ? `: ${reason}` : "."}`);
126
+ }
127
+ } catch (error) {
128
+ result.stopReason = signal?.aborted ? "aborted" : "error";
129
+ result.errorMessage = error instanceof Error ? (error.stack ?? error.message) : String(error);
130
+ }
131
+ return result;
132
+ },
133
+ };
package/src/index.ts CHANGED
@@ -4,6 +4,7 @@ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-c
4
4
  import { api } from "./api.ts";
5
5
  import { oauth } from "./auth.ts";
6
6
  import { agyCredential, fetchModels } from "./ccpa.ts";
7
+ import { imagesApi } from "./images.ts";
7
8
  import { usage } from "./usage.ts";
8
9
 
9
10
  export default function (pi: ExtensionAPI): void {
@@ -50,6 +51,7 @@ export default function (pi: ExtensionAPI): void {
50
51
  name: "Antigravity",
51
52
  auth: { oauth },
52
53
  models: [],
54
+ images: { ["agy-images"]: imagesApi },
53
55
  async fetchModels({ credential, signal }) {
54
56
  if (credential?.type !== "oauth") throw new Error("Run /login agy to authenticate.");
55
57
  return fetchModels(agyCredential(credential), signal);