@zhexin/pi-agy 0.0.3 → 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/README.md CHANGED
@@ -12,7 +12,7 @@ pi auth login agy
12
12
 
13
13
  ## Usage
14
14
 
15
- Run `/agy usage` to show remaining 5-hour and weekly quota, with reset times.
15
+ Install [`@zhexin/pi-usage`](../usage/README.md) and run `/usage agy` to show remaining 5-hour and weekly quota, with reset times.
16
16
 
17
17
  ## License
18
18
 
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.3",
4
+ "version": "0.1.0",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "keywords": [
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,11 +174,11 @@ 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
  );
177
-
178
- const variants = ids.map((id) => {
181
+ const variants = chatIds.map((id) => {
179
182
  const info = catalog.models[id]!;
180
183
  const match = /^(.*)-(off|minimal|low|medium|high|xhigh|max)$/.exec(id);
181
184
  const modelId = match?.[1] ?? id;
@@ -190,7 +193,7 @@ export async function fetchModels(
190
193
  maxOutputTokens: info.maxOutputTokens,
191
194
  };
192
195
  });
193
- const models = [...Map.groupBy(variants, ({ modelId }) => modelId)].map(
196
+ const chatModels = [...Map.groupBy(variants, ({ modelId }) => modelId)].map(
194
197
  ([id, variants]): Model<"google-generative-ai"> => {
195
198
  const levels = variants.flatMap(({ level, id }) => (level ? [[level, id]] : []));
196
199
  const thinkingLevelMap: ThinkingLevelMap = {
@@ -218,5 +221,22 @@ export async function fetchModels(
218
221
  };
219
222
  },
220
223
  );
221
- return models;
224
+
225
+ const imageModels =
226
+ catalog.imageGenerationModelIds?.map((id): ImageModel<"agy-images"> => {
227
+ const info = catalog.models[id];
228
+ return {
229
+ type: "image",
230
+ id,
231
+ name: info?.displayName || id,
232
+ provider: "agy",
233
+ api: "agy-images",
234
+ baseUrl: credential.endpoint,
235
+ input: info?.supportsImages ? ["text", "image"] : ["text"],
236
+ output: ["text", "image"],
237
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
238
+ };
239
+ }) ?? [];
240
+
241
+ return [...chatModels, ...imageModels];
222
242
  }
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,44 +4,33 @@ 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
- const commands: Record<
10
- string,
11
- {
12
- description: string;
13
- handler: (args: string, ctx: ExtensionCommandContext) => Promise<void>;
14
- }
15
- > = {
16
- usage: { description: "Show remaining quota", handler: usage },
17
- };
18
-
19
10
  export default function (pi: ExtensionAPI): void {
20
- pi.registerCommand("agy", {
21
- description: "Antigravity commands",
22
- getArgumentCompletions: (prefix) => {
23
- const items = Object.entries(commands)
24
- .filter(([name]) => name.startsWith(prefix))
25
- .map(([name, command]) => ({
26
- value: name,
27
- label: name,
28
- description: command.description,
29
- }));
30
- return items.length ? items : null;
31
- },
32
- handler: async (input, ctx) => {
33
- const [name = "", ...args] = input.trim().split(/\s+/);
34
- const command = Object.hasOwn(commands, name) ? commands[name] : undefined;
35
- if (command) {
36
- await command.handler(args.join(" "), ctx);
37
- return;
38
- }
39
- const help = Object.entries(commands)
40
- .map(([name, command]) => `/agy ${name} — ${command.description}`)
41
- .join("\n");
42
- if (ctx.hasUI) ctx.ui.notify(help, "info");
43
- else console.log(help);
44
- },
11
+ pi.events.on("pi-usage:discover", (data) => {
12
+ const discovery = data as {
13
+ add: (provider: { id: string; label: string; authHint: string }) => void;
14
+ };
15
+ if (typeof discovery?.add !== "function") return;
16
+ discovery.add({
17
+ id: "agy",
18
+ label: "Antigravity",
19
+ authHint: "Run /login agy to authenticate.",
20
+ });
21
+ });
22
+
23
+ pi.events.on("pi-usage:request", async (data) => {
24
+ const request = data as { provider: string; ctx: ExtensionCommandContext } | undefined;
25
+ if (request?.provider !== "agy" || !request.ctx) return;
26
+ const { ctx } = request;
27
+ try {
28
+ await usage(ctx);
29
+ } catch (error) {
30
+ const message = `Antigravity quota query failed: ${error instanceof Error ? error.message : String(error)}`;
31
+ if (ctx.hasUI) ctx.ui.notify(message, "error");
32
+ else console.error(message);
33
+ }
45
34
  });
46
35
 
47
36
  pi.on("before_agent_start", async (event, ctx) => {
@@ -62,6 +51,7 @@ export default function (pi: ExtensionAPI): void {
62
51
  name: "Antigravity",
63
52
  auth: { oauth },
64
53
  models: [],
54
+ images: { ["agy-images"]: imagesApi },
65
55
  async fetchModels({ credential, signal }) {
66
56
  if (credential?.type !== "oauth") throw new Error("Run /login agy to authenticate.");
67
57
  return fetchModels(agyCredential(credential), signal);
package/src/usage.ts CHANGED
@@ -28,7 +28,7 @@ function resetLabel(resetTime: string | undefined, now: number): string {
28
28
  return ` · resets in ${remaining}`;
29
29
  }
30
30
 
31
- export async function usage(_args: string, ctx: ExtensionCommandContext): Promise<void> {
31
+ export async function usage(ctx: ExtensionCommandContext): Promise<void> {
32
32
  const output = (text: string) => {
33
33
  if (ctx.hasUI) ctx.ui.notify(text);
34
34
  else console.log(text);