dsh-plugin-subscriptions 0.5.0 → 0.5.2

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.
Files changed (44) hide show
  1. package/README.md +21 -6
  2. package/README.zh.md +20 -6
  3. package/lib/auth/device-flow.d.ts +55 -0
  4. package/lib/auth/device-flow.js +177 -0
  5. package/lib/auth/oauth-flow.js +1 -1
  6. package/lib/auth/rpc.d.ts +18 -2
  7. package/lib/auth/rpc.js +98 -3
  8. package/lib/auth/store.d.ts +20 -2
  9. package/lib/auth/store.js +45 -9
  10. package/lib/client/SubscriptionsSection.d.ts +18 -1
  11. package/lib/client/SubscriptionsSection.js +216 -6
  12. package/lib/client/index.js +11 -0
  13. package/lib/client/locales.d.ts +72 -0
  14. package/lib/client/locales.js +72 -0
  15. package/lib/client.js +725 -144
  16. package/lib/client.js.map +1 -1
  17. package/lib/http.d.ts +114 -0
  18. package/lib/http.js +402 -0
  19. package/lib/index.d.ts +3 -2
  20. package/lib/index.js +2256 -226
  21. package/lib/providers/antigravity.d.ts +90 -0
  22. package/lib/providers/antigravity.js +392 -0
  23. package/lib/providers/catalog-store.js +15 -0
  24. package/lib/providers/claude.d.ts +20 -1
  25. package/lib/providers/claude.js +51 -33
  26. package/lib/providers/codex.js +58 -13
  27. package/lib/providers/common.d.ts +32 -1
  28. package/lib/providers/common.js +48 -1
  29. package/lib/providers/copilot.d.ts +315 -0
  30. package/lib/providers/copilot.js +787 -0
  31. package/lib/providers/grok.d.ts +7 -2
  32. package/lib/providers/grok.js +53 -24
  33. package/lib/tools/image-generate.js +2 -1
  34. package/lib/tools/video-generate.js +2 -1
  35. package/lib/tools/x-search.js +2 -1
  36. package/lib/translate/anthropic.d.ts +47 -6
  37. package/lib/translate/anthropic.js +135 -20
  38. package/lib/translate/antigravity.d.ts +110 -0
  39. package/lib/translate/antigravity.js +303 -0
  40. package/lib/translate/chat-completions.d.ts +120 -0
  41. package/lib/translate/chat-completions.js +363 -0
  42. package/lib/translate/responses.d.ts +49 -5
  43. package/lib/translate/responses.js +40 -7
  44. package/package.json +11 -7
@@ -0,0 +1,303 @@
1
+ /**
2
+ * DeepSeek Harness message/tool vocabulary to Antigravity's Gemini-shaped
3
+ * v1internal request envelope, plus response/SSE translation back to the
4
+ * harness streaming contract.
5
+ */
6
+ import { randomUUID } from 'node:crypto';
7
+ import { CallId, EMPTY_RESPONSE_CODE, LlmError } from '@deepseek-ai/dsh-llm';
8
+ import { parseSse } from './sse.js';
9
+ /** Flatten a harness tool result to the JSON value Antigravity receives. */
10
+ function toolResultValue(block) {
11
+ const text = block.content.map(part => part.type === 'text' ? part.text : '').join('');
12
+ try {
13
+ return JSON.parse(text);
14
+ }
15
+ catch {
16
+ return { output: text, ...block.isError === true ? { isError: true } : {} };
17
+ }
18
+ }
19
+ /** Safely read per-block replay metadata emitted by this adapter. */
20
+ function replayBlocks(message) {
21
+ const source = message.source;
22
+ if (source?.kind !== 'model' || typeof source.replayState !== 'object' || source.replayState === null)
23
+ return [];
24
+ const envelope = source.replayState;
25
+ const response = envelope.response;
26
+ if (response?.kind !== 'antigravity' || response.version !== 1 || !Array.isArray(envelope.blocks))
27
+ return [];
28
+ return envelope.blocks.map((entry) => {
29
+ if (typeof entry !== 'object' || entry === null)
30
+ return {};
31
+ const signature = entry.thoughtSignature;
32
+ return typeof signature === 'string' && signature.length > 0 ? { thoughtSignature: signature } : {};
33
+ });
34
+ }
35
+ /** Map harness tool schemas to Gemini function declarations. */
36
+ export function toAntigravityTools(tools) {
37
+ if (tools.length === 0)
38
+ return [];
39
+ return [{
40
+ functionDeclarations: tools.map(tool => ({
41
+ name: tool.name,
42
+ description: tool.description,
43
+ parameters: tool.parameters,
44
+ })),
45
+ }];
46
+ }
47
+ /**
48
+ * Convert resolved harness messages into Gemini contents. Function response
49
+ * names are recovered from prior tool calls because DSH correlates results by
50
+ * id while the Gemini wire requires both id and name.
51
+ */
52
+ export function toAntigravityContents(messages) {
53
+ const out = [];
54
+ const callNames = new Map();
55
+ for (const message of messages) {
56
+ if (message.role === 'system')
57
+ continue;
58
+ const role = message.role === 'assistant' ? 'model' : 'user';
59
+ const metadata = replayBlocks(message);
60
+ const parts = [];
61
+ for (let index = 0; index < message.content.length; index++) {
62
+ const block = message.content[index];
63
+ switch (block.type) {
64
+ case 'text':
65
+ // Antigravity's Claude-backed models reject empty text parts.
66
+ parts.push({ text: block.text.trim().length > 0 ? block.text : '.' });
67
+ break;
68
+ case 'image':
69
+ if ('dataBase64' in block) {
70
+ parts.push({ inlineData: { mimeType: block.mediaType, data: block.dataBase64 } });
71
+ }
72
+ break;
73
+ case 'tool-call': {
74
+ callNames.set(String(block.id), block.name);
75
+ let args;
76
+ try {
77
+ args = JSON.parse(block.arguments);
78
+ }
79
+ catch {
80
+ args = {};
81
+ }
82
+ parts.push({
83
+ functionCall: { id: String(block.id), name: block.name, args },
84
+ ...metadata[index]?.thoughtSignature === undefined
85
+ ? {}
86
+ : { thoughtSignature: metadata[index].thoughtSignature },
87
+ });
88
+ break;
89
+ }
90
+ case 'tool-result': {
91
+ const id = String(block.toolCallId);
92
+ parts.push({
93
+ functionResponse: {
94
+ id,
95
+ name: callNames.get(id) ?? '',
96
+ response: toolResultValue(block),
97
+ },
98
+ });
99
+ break;
100
+ }
101
+ default:
102
+ // Reasoning is not replayed without its provider signature. The
103
+ // signature-bearing metadata remains attached to tool-call blocks.
104
+ break;
105
+ }
106
+ }
107
+ if (parts.length === 0)
108
+ continue;
109
+ const previous = out.at(-1);
110
+ if (previous?.role === role)
111
+ previous.parts.push(...parts);
112
+ else
113
+ out.push({ role, parts });
114
+ }
115
+ return out;
116
+ }
117
+ /** Build one v1internal generateContent/streamGenerateContent request. */
118
+ export function toAntigravityRequest(options, messages, projectId) {
119
+ const tools = toAntigravityTools(options.tools ?? []);
120
+ const generationConfig = {
121
+ ...options.maxTokens === undefined ? {} : { maxOutputTokens: options.maxTokens },
122
+ ...options.temperature === undefined ? {} : { temperature: options.temperature },
123
+ ...options.stop === undefined || options.stop.length === 0 ? {} : { stopSequences: options.stop },
124
+ ...options.reasoningEffort === undefined ? {} : {
125
+ thinkingConfig: { thinkingLevel: String(options.reasoningEffort), includeThoughts: true },
126
+ },
127
+ };
128
+ const systemTexts = messages.flatMap(message => message.role === 'system'
129
+ ? message.content.filter((block) => block.type === 'text').map(block => block.text)
130
+ : []);
131
+ const system = options.system ?? (systemTexts.length > 0 ? systemTexts.join('\n\n') : undefined);
132
+ const sessionId = options.sessionId === undefined ? randomUUID() : String(options.sessionId);
133
+ return {
134
+ project: projectId,
135
+ requestId: `agent/${String(Date.now())}/${randomUUID()}/4`,
136
+ model: options.model,
137
+ userAgent: 'antigravity',
138
+ requestType: 'agent',
139
+ request: {
140
+ contents: toAntigravityContents(messages),
141
+ sessionId,
142
+ ...system === undefined || system.length === 0 ? {} : { systemInstruction: { parts: [{ text: system }] } },
143
+ ...tools.length === 0 ? {} : {
144
+ tools,
145
+ toolConfig: { functionCallingConfig: { mode: 'VALIDATED' } },
146
+ },
147
+ ...Object.keys(generationConfig).length === 0 ? {} : { generationConfig },
148
+ },
149
+ };
150
+ }
151
+ /** Map Gemini usage metadata to the harness's disjoint counters. */
152
+ export function mapAntigravityUsage(metadata) {
153
+ const cached = metadata.cachedContentTokenCount ?? 0;
154
+ return {
155
+ inputTokens: Math.max(0, (metadata.promptTokenCount ?? 0) - cached),
156
+ outputTokens: metadata.candidatesTokenCount ?? 0,
157
+ ...cached > 0 ? { cacheReadTokens: cached } : {},
158
+ ...metadata.thoughtsTokenCount === undefined ? {} : { reasoningTokens: metadata.thoughtsTokenCount },
159
+ };
160
+ }
161
+ /** Push translator for both parsed SSE events and one non-stream response. */
162
+ export class AntigravityStreamTranslator {
163
+ blocks = new Map();
164
+ closed = [];
165
+ nextIndex = 0;
166
+ sawContent = false;
167
+ sawToolCall = false;
168
+ terminated = false;
169
+ open(key, kind, chunks, values = {}) {
170
+ const block = { index: this.nextIndex++, kind, text: '', ...values };
171
+ this.blocks.set(key, block);
172
+ chunks.push({ type: 'block-start', index: block.index, blockType: kind });
173
+ return block;
174
+ }
175
+ close(key, chunks) {
176
+ const block = this.blocks.get(key);
177
+ if (block === undefined)
178
+ return;
179
+ this.blocks.delete(key);
180
+ let content;
181
+ if (block.kind === 'text')
182
+ content = { type: 'text', text: block.text };
183
+ else if (block.kind === 'reasoning')
184
+ content = { type: 'reasoning', text: block.text };
185
+ else
186
+ content = {
187
+ type: 'tool-call',
188
+ id: CallId(block.id ?? `call_${randomUUID().replaceAll('-', '')}`),
189
+ name: block.name ?? '',
190
+ arguments: block.text,
191
+ };
192
+ this.closed[block.index] = block.thoughtSignature === undefined ? {} : { thoughtSignature: block.thoughtSignature };
193
+ chunks.push({ type: 'block-end', index: block.index, block: content });
194
+ }
195
+ closeAll(chunks) {
196
+ for (const key of [...this.blocks.keys()])
197
+ this.close(key, chunks);
198
+ }
199
+ finish(reason) {
200
+ const replayState = {
201
+ response: { kind: 'antigravity', version: 1 },
202
+ blocks: this.closed,
203
+ };
204
+ if (!this.sawContent) {
205
+ return {
206
+ type: 'finish',
207
+ reason: { kind: 'error', failure: { message: 'Antigravity returned no content', code: EMPTY_RESPONSE_CODE } },
208
+ };
209
+ }
210
+ if (reason === 'MAX_TOKENS')
211
+ return { type: 'finish', reason: { kind: 'max-tokens' }, replayState };
212
+ if (reason === 'SAFETY' || reason === 'RECITATION' || reason === 'BLOCKLIST') {
213
+ return {
214
+ type: 'finish',
215
+ reason: { kind: 'error', failure: { message: `Antigravity blocked the response (${reason})`, code: 'CONTENT_FILTER' } },
216
+ };
217
+ }
218
+ return { type: 'finish', reason: { kind: this.sawToolCall ? 'tool-calls' : 'stop' }, replayState };
219
+ }
220
+ /** Process one decoded Antigravity response frame. */
221
+ push(event) {
222
+ if (this.terminated)
223
+ return [];
224
+ const chunks = [];
225
+ const candidate = event.response?.candidates?.[0];
226
+ for (const [partIndex, part] of (candidate?.content?.parts ?? []).entries()) {
227
+ if (part.thought === true && typeof part.text === 'string' && part.text.length > 0) {
228
+ const block = this.blocks.get('reasoning') ?? this.open('reasoning', 'reasoning', chunks);
229
+ block.text += part.text;
230
+ if (part.thoughtSignature !== undefined)
231
+ block.thoughtSignature = part.thoughtSignature;
232
+ this.sawContent = true;
233
+ chunks.push({ type: 'reasoning-delta', index: block.index, text: part.text });
234
+ }
235
+ else if (typeof part.text === 'string' && part.text.length > 0) {
236
+ const block = this.blocks.get('text') ?? this.open('text', 'text', chunks);
237
+ block.text += part.text;
238
+ if (part.thoughtSignature !== undefined)
239
+ block.thoughtSignature = part.thoughtSignature;
240
+ this.sawContent = true;
241
+ chunks.push({ type: 'text-delta', index: block.index, text: part.text });
242
+ }
243
+ else if (part.functionCall !== undefined) {
244
+ const call = part.functionCall;
245
+ const id = typeof call.id === 'string' && call.id.length > 0
246
+ ? call.id
247
+ : `call_${randomUUID().replaceAll('-', '')}`;
248
+ const key = `call:${id}:${String(partIndex)}`;
249
+ const args = JSON.stringify(call.args ?? {});
250
+ const block = this.open(key, 'tool-call', chunks, {
251
+ id,
252
+ name: call.name ?? '',
253
+ ...part.thoughtSignature === undefined ? {} : { thoughtSignature: part.thoughtSignature },
254
+ });
255
+ block.text = args;
256
+ this.sawContent = true;
257
+ this.sawToolCall = true;
258
+ chunks.push({
259
+ type: 'tool-call-delta',
260
+ index: block.index,
261
+ id: CallId(id),
262
+ name: call.name ?? '',
263
+ argumentsDelta: args,
264
+ });
265
+ this.close(key, chunks);
266
+ }
267
+ }
268
+ if (candidate?.finishReason !== undefined) {
269
+ this.closeAll(chunks);
270
+ const usage = event.response?.usageMetadata;
271
+ if (usage !== undefined)
272
+ chunks.push({ type: 'usage', usage: mapAntigravityUsage(usage) });
273
+ chunks.push(this.finish(candidate.finishReason));
274
+ this.terminated = true;
275
+ }
276
+ return chunks;
277
+ }
278
+ }
279
+ /** Consume Antigravity's SSE response into the DSH streaming contract. */
280
+ export async function* streamAntigravity(stream, onActivity) {
281
+ const translator = new AntigravityStreamTranslator();
282
+ for await (const event of parseSse(stream, onActivity)) {
283
+ if (event.data === '[DONE]')
284
+ break;
285
+ let parsed;
286
+ try {
287
+ parsed = JSON.parse(event.data);
288
+ }
289
+ catch {
290
+ throw new LlmError(`malformed Antigravity SSE payload: ${event.data.slice(0, 120)}`, 'MALFORMED_RESPONSE');
291
+ }
292
+ yield* translator.push(parsed);
293
+ if (translator.terminated)
294
+ return;
295
+ }
296
+ if (!translator.terminated) {
297
+ throw new LlmError('Antigravity SSE stream ended before a finish chunk', 'STREAM_CLOSED');
298
+ }
299
+ }
300
+ /** Translate a non-stream generateContent response using the same state machine. */
301
+ export function parseAntigravityResponse(event) {
302
+ return new AntigravityStreamTranslator().push(event);
303
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Translate between the harness message vocabulary and the OpenAI chat
3
+ * completions wire format the Copilot provider speaks: request message/tool
4
+ * assembly and a push-model SSE-chunk → StreamChunk state machine
5
+ * ({@link ChatCompletionsStreamTranslator}) mirroring the Responses
6
+ * translator, so tests need no streams.
7
+ */
8
+ import type { StreamChunk, TokenUsage, ToolSchema } from '@deepseek-ai/dsh-llm';
9
+ import type { TranslatableMessage } from './resolved.js';
10
+ /**
11
+ * Convert harness messages into chat completions `messages`. System-role
12
+ * messages become one leading `system` message; an explicit `system` argument
13
+ * wins over them when both exist. Reasoning blocks are not replayed (matching
14
+ * the Responses translator). Images must arrive pre-resolved; an unresolved
15
+ * ImageBlock is skipped because its bytes are unreachable here. A user message
16
+ * carrying only text collapses to a plain string body (some endpoints still
17
+ * reject content-part arrays); tool results become separate `tool` messages.
18
+ * @param messages - ordered conversation messages with resolved images.
19
+ * @param system - explicit system prompt, which takes precedence.
20
+ * @returns the wire `messages` array.
21
+ */
22
+ export declare function toChatMessages(messages: readonly TranslatableMessage[], system?: string): Record<string, unknown>[];
23
+ /**
24
+ * Map harness tool schemas to chat completions function tools.
25
+ * @param tools - tool schemas from the request.
26
+ * @returns the wire `tools` array.
27
+ */
28
+ export declare function toChatTools(tools: readonly ToolSchema[]): Record<string, unknown>[];
29
+ /** The subset of chat-completion chunk shapes this translator reads. */
30
+ export interface ChatCompletionsStreamEvent {
31
+ choices?: {
32
+ index?: number;
33
+ delta?: {
34
+ content?: string | null;
35
+ role?: string;
36
+ reasoning_content?: string | null;
37
+ /** Copilot's Gemini models stream thinking as `reasoning_text`. */
38
+ reasoning_text?: string | null;
39
+ tool_calls?: {
40
+ index?: number;
41
+ id?: string;
42
+ function?: {
43
+ name?: string;
44
+ arguments?: string;
45
+ };
46
+ }[];
47
+ };
48
+ finish_reason?: string | null;
49
+ }[];
50
+ usage?: ChatCompletionsUsage | null;
51
+ }
52
+ /** Chat completions `usage` object shape. */
53
+ export interface ChatCompletionsUsage {
54
+ prompt_tokens: number;
55
+ completion_tokens: number;
56
+ prompt_tokens_details?: {
57
+ cached_tokens?: number;
58
+ };
59
+ completion_tokens_details?: {
60
+ reasoning_tokens?: number;
61
+ };
62
+ }
63
+ /**
64
+ * Map chat completions usage to disjoint harness counts (cached input is
65
+ * subtracted out of `inputTokens` and reported as `cacheReadTokens`).
66
+ * @param usage - wire usage from the terminal chunk.
67
+ * @returns harness token usage.
68
+ */
69
+ export declare function mapChatCompletionsUsage(usage: ChatCompletionsUsage): TokenUsage;
70
+ /**
71
+ * Push-model chat completions SSE translator: feed each parsed chunk object
72
+ * to {@link push} and collect the emitted harness StreamChunks. The terminal
73
+ * `finish_reason` chunk closes every block but only ARMS the finish chunk —
74
+ * usage must precede the terminal finish, and where usage lives differs by
75
+ * upstream: OpenAI-style streams send a trailing usage-only chunk
76
+ * (stream_options.include_usage), while Copilot's Gemini models attach a
77
+ * (zero) usage object to EVERY chunk and fold the real usage into the
78
+ * finish chunk itself. A chunk therefore never early-returns on `usage`
79
+ * alone: its deltas are always processed, and the terminal pair is drained
80
+ * when the finish is armed and usage arrived (or when a usage-only chunk
81
+ * follows an armed finish). `flush()` emits whatever remains when the
82
+ * stream's `[DONE]` (or EOF) arrives.
83
+ */
84
+ export declare class ChatCompletionsStreamTranslator {
85
+ /** Text/reasoning blocks keyed by kind; tool calls keyed by their wire index. */
86
+ private blocks;
87
+ private order;
88
+ private nextIndex;
89
+ private sawToolCall;
90
+ private pendingUsage;
91
+ private armedFinish;
92
+ /** Set once the terminal finish chunk was emitted. */
93
+ terminated: boolean;
94
+ private open;
95
+ private close;
96
+ private closeAll;
97
+ /** Build the terminal finish chunk for one wire finish reason. */
98
+ private finishChunk;
99
+ /** Usage, then the armed finish: the only order the harness accepts. */
100
+ private drainTerminal;
101
+ /**
102
+ * Process one parsed chat-completion chunk.
103
+ * @param event - the parsed chunk object.
104
+ * @returns the StreamChunks this event produced (possibly none).
105
+ */
106
+ push(event: ChatCompletionsStreamEvent): StreamChunk[];
107
+ /**
108
+ * Emit whatever the stream left pending (`[DONE]` or EOF without a final
109
+ * usage chunk). Safe to call repeatedly.
110
+ * @returns the remaining terminal chunks.
111
+ */
112
+ flush(): StreamChunk[];
113
+ }
114
+ /**
115
+ * Consume a chat completions SSE byte stream and yield harness StreamChunks.
116
+ * @param stream - raw response body.
117
+ * @param onActivity - transport-activity callback for the idle watchdog.
118
+ * @returns the chunk stream; throws when the stream ends before any finish chunk.
119
+ */
120
+ export declare function streamChatCompletions(stream: ReadableStream<Uint8Array>, onActivity?: () => void): AsyncGenerator<StreamChunk>;