@genspark/cli 1.12.0 → 1.13.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.
Files changed (59) hide show
  1. package/README.md +128 -2
  2. package/dist/client.d.ts +63 -2
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +321 -3
  5. package/dist/client.js.map +1 -1
  6. package/dist/commands/developer-preflight.d.ts +17 -0
  7. package/dist/commands/developer-preflight.d.ts.map +1 -0
  8. package/dist/commands/developer-preflight.js +131 -0
  9. package/dist/commands/developer-preflight.js.map +1 -0
  10. package/dist/commands/developer-project.d.ts +5 -0
  11. package/dist/commands/developer-project.d.ts.map +1 -0
  12. package/dist/commands/developer-project.js +140 -0
  13. package/dist/commands/developer-project.js.map +1 -0
  14. package/dist/commands/genspark-code-skills.d.ts +23 -0
  15. package/dist/commands/genspark-code-skills.d.ts.map +1 -0
  16. package/dist/commands/genspark-code-skills.js +49 -0
  17. package/dist/commands/genspark-code-skills.js.map +1 -0
  18. package/dist/commands/hosted-local.d.ts +10 -0
  19. package/dist/commands/hosted-local.d.ts.map +1 -0
  20. package/dist/commands/hosted-local.js +116 -0
  21. package/dist/commands/hosted-local.js.map +1 -0
  22. package/dist/commands/local-command-routing.d.ts +8 -0
  23. package/dist/commands/local-command-routing.d.ts.map +1 -0
  24. package/dist/commands/local-command-routing.js +33 -0
  25. package/dist/commands/local-command-routing.js.map +1 -0
  26. package/dist/commands/local-preview.d.ts +5 -0
  27. package/dist/commands/local-preview.d.ts.map +1 -0
  28. package/dist/commands/local-preview.js +35 -0
  29. package/dist/commands/local-preview.js.map +1 -0
  30. package/dist/config.d.ts +1 -1
  31. package/dist/config.d.ts.map +1 -1
  32. package/dist/config.js +1 -1
  33. package/dist/config.js.map +1 -1
  34. package/dist/developer-contract.d.ts +24 -0
  35. package/dist/developer-contract.d.ts.map +1 -0
  36. package/dist/developer-contract.js +64 -0
  37. package/dist/developer-contract.js.map +1 -0
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +92 -12
  40. package/dist/index.js.map +1 -1
  41. package/dist/local-source.d.ts +22 -0
  42. package/dist/local-source.d.ts.map +1 -0
  43. package/dist/local-source.js +204 -0
  44. package/dist/local-source.js.map +1 -0
  45. package/dist/project-binding.d.ts +31 -0
  46. package/dist/project-binding.d.ts.map +1 -0
  47. package/dist/project-binding.js +141 -0
  48. package/dist/project-binding.js.map +1 -0
  49. package/dist/types.d.ts +14 -0
  50. package/dist/types.d.ts.map +1 -1
  51. package/package.json +4 -2
  52. package/skills/gsk-aidrive/SKILL.md +19 -15
  53. package/skills/gsk-audio-generation/SKILL.md +1 -1
  54. package/skills/gsk-claw-share-link/SKILL.md +1 -1
  55. package/skills/gsk-google-calendar/SKILL.md +2 -1
  56. package/skills/gsk-outlook-calendar/SKILL.md +2 -1
  57. package/skills/gsk-sb-brain/SKILL.md +13 -82
  58. package/skills/gsk-second-brain/SKILL.md +158 -0
  59. package/skills/gsk-shared/SKILL.md +18 -0
package/README.md CHANGED
@@ -77,6 +77,115 @@ gsk img "A beautiful sunset over mountains" -o ./sunset.png
77
77
  gsk crawl "https://example.com/article"
78
78
  ```
79
79
 
80
+ ## Local developer projects, previews, and source deployments
81
+
82
+ ```bash
83
+ gsk project create --kind web --name "Example" --yes
84
+ gsk project bind <project-id>
85
+ gsk project status
86
+ gsk preflight --kind web --operation preview
87
+ gsk preflight --kind web --operation hosted-deploy
88
+ gsk service-url --local --port 3000
89
+ gsk get_service_url --local --port 3000
90
+ gsk hosted deploy-local --source .
91
+ ```
92
+
93
+ Create explicitly asks for confirmation; `--yes` confirms creation in automation.
94
+ It never retries creation after a network error. Check your project list and
95
+ bind the returned/existing project before trying to create another one.
96
+ Binding and status use the server's owner-authorized developer endpoint.
97
+
98
+ The nearest ancestor `.gsk/project.json` binds a checkout:
99
+
100
+ ```json
101
+ {"version":1,"project_id":"example-id","kind":"web","base_url":"https://www.genspark.ai"}
102
+ ```
103
+
104
+ Only these four fields are allowed. No command above writes credentials or
105
+ changes global project configuration. Project selection is **`--project-id` >
106
+ `GSK_PROJECT_ID` > nearest binding > legacy global config**. The active server
107
+ still comes from `--base-url`, `GSK_BASE_URL`, or global config; a binding for a
108
+ different server blocks cloud operations even with an explicit project ID.
109
+ Invalid bindings fail visibly. A different existing/inherited binding is never
110
+ silently overwritten: use another checkout or explicitly remove the old binding.
111
+ Concurrent writers use atomic create-if-absent publication.
112
+
113
+ Preview requires explicit `--local`, runs before schema fetching or update checks,
114
+ and needs no login. Ports must be decimal integers in 1–65535. A bounded TCP probe
115
+ of `127.0.0.1` returns `{status, local_only:true, url, reachable, probe, message}`;
116
+ TCP reachability does not imply HTTP/application health. There is no public tunnel
117
+ and no fallback from a failed remote URL request to localhost.
118
+
119
+ Preflight operations are `preview`, `hosted-deploy`, `github`, `cloudflare`,
120
+ `shopify`, and `android`. Checks are advisory and operation-specific: web preview
121
+ does not require Flutter, and platform hosting does not require local Wrangler
122
+ or Shopify authorization. Missing login, malformed binding, and unavailable
123
+ platform checks preserve local check results with actionable status. Local
124
+ provider login (`gh auth login`, `wrangler login`, `shopify auth login`) is
125
+ separate from platform connectors and `sandbox_auth_*` remote sandbox setup.
126
+
127
+ `hosted deploy-local` streams a private temporary ZIP snapshot, uploads it, then
128
+ submits its validated receipt to the existing `hosted_deploy` approval flow.
129
+ It does **not** approve the action, including with `--yes`. Review the returned
130
+ pending action/source digest in the project and approve explicitly. The CLI
131
+ does not run build scripts. Source must include the Wrangler configuration and
132
+ entry points required by the backend's hosted build pipeline.
133
+
134
+ Packaging rejects symlinks, non-regular files, traversal, unsafe paths, and
135
+ case/Unicode-normalization collisions. Exclusions apply at every depth:
136
+ `.env*`, `.git`, `node_modules`, `.wrangler`, `.gsk`, `.genspark-code`, local
137
+ credential/config directories and files (including `.ssh`, `.aws`, `.azure`,
138
+ `.config`, `.npmrc`, `.netrc`, `credentials.json`, private keys), plus the active
139
+ custom CLI config file if it is inside the source tree. Limits are
140
+ 20,000 visited non-excluded entries, 250 MiB ZIP, and 500 MiB expanded source.
141
+ Source changes detected while packaging abort the upload.
142
+
143
+ The receipt is saved before submission to `.gsk/pending-source-<uuid>.json`.
144
+ This file is retained after submission as a recovery record, not proof of action
145
+ status. On a dropped response, inspect hosted actions in the project before
146
+ resubmitting. Upload and submission are never automatically retried. No remote
147
+ source is substituted when an upload/receipt/server capability fails.
148
+
149
+ ### Developer API contract
150
+
151
+ All paths below are relative to `<base_url>/api/tool_cli`; calls use existing
152
+ `ApiClient` token auth (`X-Api-Key`), `X-GSK-CLI-Caps`, and selected `X-Project-ID`.
153
+
154
+ | Request | Response |
155
+ | --- | --- |
156
+ | `POST /developer/projects` JSON `{kind,name}` | `{project:{project_id,kind,name,url}}` |
157
+ | `GET /developer/projects/{id}` (owner-authorized) | `{project:{project_id,kind,name,url}}` |
158
+ | `GET /developer/preflight?kind=...&operation=...&project_id=...` (project ID omitted when unbound) | `{checks:[{name,status,code,message,action_url?}],project?:{project_id,kind,name,url}}` |
159
+ | `POST /hosted/source`, raw `application/zip`, required `X-Project-ID` | HTTP 201 `{local_source:receipt}` |
160
+ | Existing `executeTool('hosted_deploy', {local_source:receipt})` | Existing tool envelope/pending approval |
161
+
162
+ Check `status` is `ready`, `action_required`, `unknown`, or `not_applicable`.
163
+ Project/check response objects permit additional server fields but only the
164
+ documented project/check fields are consumed. Source receipts are passed unchanged:
165
+ `{version:1,owner_cogen_id,project_id,object_key,sha256,size_bytes,expanded_bytes,
166
+ file_count,created_at,expires_at}` (timestamps: integer Unix seconds). The CLI
167
+ checks project ID, digest, sizes/count, required receipt fields, and expiry before
168
+ submitting. Backend ownership/digest/expiry validation remains authoritative.
169
+
170
+ The CLI advertises `cli-local-source-v1`; its tools cache is isolated from older
171
+ capability views. The static `hosted` parent is seeded so existing grouped hosted
172
+ metadata and legacy flat commands coexist. No new hosted group metadata is needed
173
+ on old servers. Any future metadata that shadows a static command must be gated
174
+ to supporting capabilities, not sent to old binaries.
175
+
176
+ Backend source writes default off. HTTP 503 explains that supported writers must
177
+ be enabled only after all readers/executors converge; 404/405 reports an unsupported
178
+ server. Release requires verified backend endpoint support and reader rollout.
179
+ There is no client-side bypass or remote-source fallback.
180
+
181
+ ### Local verification
182
+
183
+ ```bash
184
+ npm test
185
+ # Optional published-client shared-HOME matrix against mocked HTTP transport:
186
+ GSK_COMPAT_CLI=/path/to/published/@genspark/cli/dist/index.js npm test
187
+ ```
188
+
80
189
  ## Authentication
81
190
 
82
191
  Log in with your Genspark account:
@@ -312,6 +421,24 @@ gsk init-skills -o ./docs/gsk-skills
312
421
 
313
422
  `--agent pi` writes (`pi` auto-loads it) `AGENTS.md` referencing `CONTEXT.md`; `--agent claude` writes/appends `CLAUDE.md` and `--agent gemini` writes `gemini-extension.json`.
314
423
 
424
+ ### init-genspark-code-skills
425
+
426
+ Fetch the genspark-code (code sandbox) skill documents into the current project for AI agent discovery. Covers the full developer-skill set a sandbox can install — web / Cloudflare / Flutter / Shopify / HTML5-game development, hosted deployment, and GitHub workflows. The bundle is served by the backend (`/api/tool_cli/genspark-code-skills`), so newly edited skill docs reach released CLIs without a package update.
427
+
428
+ ```bash
429
+ # Copy skills to .genspark-code/skills/
430
+ gsk init-genspark-code-skills
431
+
432
+ # Custom output directory
433
+ gsk init-genspark-code-skills -o ./docs/genspark-code-skills
434
+ ```
435
+
436
+ | Option | Default | Description |
437
+ |--------|---------|-------------|
438
+ | `-o, --out <dir>` | `.genspark-code/skills` (cwd) | Output directory for skills |
439
+
440
+ There is no `--agent` flag: an existing `CONTEXT.md` from `gsk init-skills` is left untouched. A built-in whose requirement the caller doesn't satisfy — the org-only `gsk-hosted-org-member` for a non-member — is omitted, so an agent never sees docs for a capability the server would refuse.
441
+
315
442
  ### Search & Crawl
316
443
 
317
444
  ### web_search (alias: `search`)
@@ -1240,8 +1367,7 @@ gsk mesh forward -L 8080:localhost:80 workstation # browse its local web app a
1240
1367
  |-------|-------------|
1241
1368
  | `elevenlabs/music` | ElevenLabs music generation with vocals/singing. Lyrics auto-generated (no custom lyrics). Duration: 10s-5min |
1242
1369
  | `CassetteAI/music-generator` | Background music generation. Duration: 10-180 seconds |
1243
- | `mureka/song-generator` | Professional song generation with lyrics. Supports style prompts, reference tracks, vocal and melody inputs. Max: 180s |
1244
- | `mureka/instrumental-generator` | Instrumental music generation without vocals. Supports style prompts and reference tracks. Max: 180s |
1370
+ | `mureka` | Mureka music, `params.mode` picks the product: `song` (default, vocals over `lyrics`, style prompt or reference track), `instrumental` (vocal-free from the prompt), `remix` (re-sing an existing `source_audio_file` mp3/m4a 10-350s with new `lyrics`) |
1245
1371
  | `google/lyria-music` | Google Lyria 3 text-to-music (`sub_model`: `lyria-3-clip` 30s clip or `lyria-3-pro` full song). 44.1kHz stereo, vocals with lyrics in multiple languages |
1246
1372
  | `minimax/music-3.0` | MiniMax Music 3.0 song generation with lyrics (`is_instrumental` for tracks without vocals). Supports (Verse), (Chorus), (Bridge) markers |
1247
1373
 
package/dist/client.d.ts CHANGED
@@ -1,20 +1,67 @@
1
1
  /**
2
2
  * API Client for Genspark Tool CLI
3
3
  */
4
- import type { GlobalOptions, ApiResponse, ToolListResponse, UserInfo, FileUploadUrlRequest, FileUploadUrlResponse, FileDownloadRequest, FileDownloadResponse } from './types.js';
4
+ import type { DeveloperProject, DeveloperPreflight } from './developer-contract.js';
5
+ import type { GlobalOptions, ApiResponse, ToolListResponse, UserInfo, FileUploadUrlRequest, FileUploadUrlResponse, FileDownloadRequest, FileDownloadResponse, GensparkCodeSkillsResponse } from './types.js';
5
6
  /**
6
7
  * Make an unauthenticated request to the backend.
7
8
  * Used for device-flow auth endpoints that don't require an API key.
8
9
  */
9
10
  export declare function unauthenticatedRequest<T>(baseUrl: string, endpoint: string, method?: 'GET' | 'POST', body?: unknown): Promise<T>;
11
+ /** Hard ceiling on one automatic rate-limit wait (ms). */
12
+ export declare const MAX_RATE_LIMIT_WAIT_MS = 65000;
13
+ export interface RateLimitDenial {
14
+ /** Seconds the server told us to wait. */
15
+ retryAfter: number;
16
+ message: string;
17
+ instructionForAgent?: string;
18
+ }
19
+ /**
20
+ * Read a 429 denial out of a response, or return null if it isn't one.
21
+ *
22
+ * The server sends both a standard `Retry-After` header and a `retry_after`
23
+ * field in the NDJSON envelope; the header wins because a proxy may answer
24
+ * without our body at all, and the body is the fallback for the reverse.
25
+ * Both are ignored unless they parse to a positive finite number — a `0`
26
+ * or a garbled value would otherwise license the immediate retry this
27
+ * exists to stop (#61436).
28
+ */
29
+ export declare function parseRateLimitDenial(status: number, headers: Headers, bodyText: string): RateLimitDenial | null;
30
+ /** Milliseconds to sleep for a denial, capped and jittered. */
31
+ export declare function rateLimitWaitMs(denial: RateLimitDenial): number;
10
32
  /**
11
33
  * Error carrying the HTTP status behind a failed API call, so callers can
12
34
  * branch on auth failures (401/403) without parsing message strings.
13
35
  */
14
36
  export declare class ApiHttpError extends Error {
15
37
  readonly httpStatus?: number;
16
- constructor(message: string, httpStatus?: number);
38
+ /**
39
+ * Parsed `{detail: {code, message}}` from a structured developer error, when
40
+ * the body carried one (e.g. `project_kind_mismatch`). Lets callers branch on
41
+ * the server's own code instead of scraping the message string.
42
+ */
43
+ readonly serverDetail?: {
44
+ code?: string;
45
+ message?: string;
46
+ };
47
+ constructor(message: string, httpStatus?: number, serverDetail?: {
48
+ code?: string;
49
+ message?: string;
50
+ });
17
51
  }
52
+ /**
53
+ * Parse a developer API error body. The backend returns structured
54
+ * `{"detail": {"code", "message"}}` for application errors (missing project,
55
+ * kind mismatch, ...); a route that does not exist on this server answers with
56
+ * a plain `{"detail": "Not Found"}` instead. `structured` is what tells the two
57
+ * apart, so a real 404 like `project_not_found` is never reported as an
58
+ * unsupported server.
59
+ */
60
+ export declare function parseDeveloperErrorDetail(body: string): {
61
+ structured: boolean;
62
+ code?: string;
63
+ message?: string;
64
+ };
18
65
  /** True when the error is an HTTP-level auth rejection (401/403). */
19
66
  export declare function isAuthError(err: unknown): boolean;
20
67
  export declare class ApiClient {
@@ -40,6 +87,16 @@ export declare class ApiClient {
40
87
  * tool executions, which all go through the streaming path).
41
88
  */
42
89
  private baseHeaders;
90
+ /** Make one bounded request; creation and source writes must never be retried. */
91
+ private developerRequest;
92
+ /** Explicitly create a project once, using the existing token identity. */
93
+ createDeveloperProject(kind: string, name: string): Promise<DeveloperProject>;
94
+ /** Fetch a project through the server's owner-only developer route. */
95
+ getDeveloperProject(id: string): Promise<DeveloperProject>;
96
+ /** Read advisory account checks without creating a project or sandbox. */
97
+ developerPreflight(kind: string, operation: string): Promise<DeveloperPreflight>;
98
+ /** Stream a ZIP to the selected project and return its unmodified source receipt. */
99
+ uploadHostedSource(filename: string, size: number): Promise<Record<string, unknown>>;
43
100
  private request;
44
101
  /**
45
102
  * Simple JSON request (non-streaming) for endpoints that return plain JSON.
@@ -102,6 +159,10 @@ export declare class ApiClient {
102
159
  * Get OpenCode configuration JSON
103
160
  */
104
161
  getOpencodeConfig(model?: string): Promise<Record<string, unknown>>;
162
+ /**
163
+ * Get the genspark-code (code sandbox) skill bundle
164
+ */
165
+ getGensparkCodeSkills(): Promise<GensparkCodeSkillsResponse>;
105
166
  /**
106
167
  * Get Pi (pi.dev) config bundle: `{ models, settings, genspark }`.
107
168
  */
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;GAEG;AAKH,OAAO,KAAK,EACV,aAAa,EACb,WAAW,EACX,gBAAgB,EAChB,QAAQ,EACR,oBAAoB,EACpB,qBAAqB,EACrB,mBAAmB,EACnB,oBAAoB,EACrB,MAAM,YAAY,CAAA;AAEnB;;;GAGG;AACH,wBAAsB,sBAAsB,CAAC,CAAC,EAC5C,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,MAAM,GAAE,KAAK,GAAG,MAAc,EAC9B,IAAI,CAAC,EAAE,OAAO,GACb,OAAO,CAAC,CAAC,CAAC,CAoBZ;AAKD;;;GAGG;AACH,qBAAa,YAAa,SAAQ,KAAK;IACr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AAM,GAAG,OAAO,CAAA;KAAE,KAAK,IAAI,EACrD,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,WAAW,CAAC;IAYvB;;OAEG;IACG,cAAc,CAClB,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,MAAM,GAAE,MAAe,GACtB,OAAO,CAAC,WAAW,CAAC;IAQvB;;OAEG;IACG,YAAY,CAChB,MAAM,EAAE,oBAAoB,GAC3B,OAAO,CAAC,WAAW,CAAC,qBAAqB,CAAC,CAAC;IAQ9C;;OAEG;IACG,cAAc,CAClB,MAAM,EAAE,mBAAmB,GAC1B,OAAO,CAAC,WAAW,CAAC,oBAAoB,CAAC,CAAC;IAI7C;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,QAAQ,CAAC;IAIhC;;OAEG;IACG,iBAAiB,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAKzE;;OAEG;IACG,qBAAqB,IAAI,OAAO,CAAC,0BAA0B,CAAC;IAIlE;;OAEG;IACG,WAAW,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAKnE;;;;OAIG;IACG,gBAAgB,CAAC,CAAC,EACtB,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,OAAO,EACb,SAAS,EAAE,CAAC,GAAG,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;KAAE,KAAK,IAAI,EACpD,cAAc,CAAC,EAAE,WAAW,GAC3B,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;CAyI3B"}
package/dist/client.js CHANGED
@@ -2,7 +2,9 @@
2
2
  * API Client for Genspark Tool CLI
3
3
  */
4
4
  import { createRequire } from 'module';
5
- import { debug, error as logError } from './logger.js';
5
+ import { createReadStream } from 'node:fs';
6
+ import { jsonObject, parseDeveloperProject, parseDeveloperPreflight, } from './developer-contract.js';
7
+ import { debug, info, error as logError } from './logger.js';
6
8
  import { GSK_CLI_CAPS } from './config.js';
7
9
  /**
8
10
  * Make an unauthenticated request to the backend.
@@ -27,16 +29,146 @@ export async function unauthenticatedRequest(baseUrl, endpoint, method = 'GET',
27
29
  }
28
30
  const _require = createRequire(import.meta.url);
29
31
  const { version: CLI_VERSION } = _require('../package.json');
32
+ /** Hard ceiling on one automatic rate-limit wait (ms). */
33
+ export const MAX_RATE_LIMIT_WAIT_MS = 65_000;
34
+ /** Padding past the advertised wait, so we land after the window rolls. */
35
+ const RATE_LIMIT_WAIT_PADDING_MS = 1_000;
36
+ /** Extra spread so concurrent callers don't all fire at the same instant. */
37
+ const RATE_LIMIT_WAIT_JITTER_MS = 1_000;
38
+ /**
39
+ * Budget the retry itself must still have after the wait.
40
+ *
41
+ * Checking only that the WAIT fits the deadline is not enough: the retry then
42
+ * starts with milliseconds left, the timeout controller aborts it mid-flight,
43
+ * and the caller gets a bare `Request timeout` — losing `error_code`,
44
+ * `retry_after` and `instruction_for_agent`. That is strictly worse than not
45
+ * waiting at all, because the agent can no longer even tell a rate limit from
46
+ * a dead backend.
47
+ */
48
+ const MIN_RETRY_BUDGET_MS = 5_000;
49
+ /**
50
+ * Seconds from a `Retry-After` header, in either RFC 9110 form.
51
+ *
52
+ * The header is defined as delay-seconds **or** an HTTP-date, and CDNs and
53
+ * WAFs in front of us do emit the date form. `Number("Wed, 11 Sep 2026
54
+ * 14:20:57 GMT")` is NaN, which silently fell through to the body's much
55
+ * smaller `retry_after` (or to the 1s floor) — advertising a wait far
56
+ * shorter than the one actually imposed.
57
+ */
58
+ function parseRetryAfterHeader(raw) {
59
+ if (!raw)
60
+ return 0;
61
+ const seconds = Number(raw);
62
+ if (Number.isFinite(seconds))
63
+ return seconds > 0 ? seconds : 0;
64
+ const at = Date.parse(raw);
65
+ if (!Number.isFinite(at))
66
+ return 0;
67
+ return Math.max(0, Math.ceil((at - Date.now()) / 1000));
68
+ }
69
+ /**
70
+ * Read a 429 denial out of a response, or return null if it isn't one.
71
+ *
72
+ * The server sends both a standard `Retry-After` header and a `retry_after`
73
+ * field in the NDJSON envelope; the header wins because a proxy may answer
74
+ * without our body at all, and the body is the fallback for the reverse.
75
+ * Both are ignored unless they parse to a positive finite number — a `0`
76
+ * or a garbled value would otherwise license the immediate retry this
77
+ * exists to stop (#61436).
78
+ */
79
+ export function parseRateLimitDenial(status, headers, bodyText) {
80
+ if (status !== 429)
81
+ return null;
82
+ let retryAfter = parseRetryAfterHeader(headers.get('retry-after'));
83
+ // A non-JSON body is the fallback message, but it can be a whole WAF or
84
+ // proxy HTML page — this path used to return the short `statusText`, so
85
+ // passing the page through unbounded would be a regression in its own
86
+ // right. JSON envelopes below replace this wholesale and are not capped.
87
+ let message = bodyText.slice(0, 300);
88
+ let instructionForAgent;
89
+ // The body is NDJSON and a denial is a single line, but parse defensively.
90
+ // Take every field from ONE object: stitching `message` off one line and
91
+ // `retry_after` off another would describe a response that was never sent.
92
+ // The first line that carries an envelope wins, the way the CLI's own
93
+ // stream reader treats the first status-bearing line as the result.
94
+ for (const line of bodyText.trim().split('\n')) {
95
+ const trimmed = line.trim();
96
+ if (!trimmed.startsWith('{'))
97
+ continue;
98
+ let parsed;
99
+ try {
100
+ parsed = JSON.parse(trimmed);
101
+ }
102
+ catch {
103
+ continue; // Not JSON — keep looking; the raw text stays the fallback.
104
+ }
105
+ if (typeof parsed.message === 'string')
106
+ message = parsed.message;
107
+ if (typeof parsed.instruction_for_agent === 'string') {
108
+ instructionForAgent = parsed.instruction_for_agent;
109
+ }
110
+ const bodyRetry = Number(parsed.retry_after);
111
+ if (!retryAfter && Number.isFinite(bodyRetry) && bodyRetry > 0) {
112
+ retryAfter = bodyRetry;
113
+ }
114
+ break;
115
+ }
116
+ // A 429 with no usable hint still means "wait"; one second is the
117
+ // smallest honest answer and is still infinitely better than none.
118
+ return { retryAfter: retryAfter || 1, message, instructionForAgent };
119
+ }
120
+ /** Milliseconds to sleep for a denial, capped and jittered. */
121
+ export function rateLimitWaitMs(denial) {
122
+ const raw = denial.retryAfter * 1000 + RATE_LIMIT_WAIT_PADDING_MS;
123
+ return (Math.min(raw, MAX_RATE_LIMIT_WAIT_MS) +
124
+ Math.floor(Math.random() * RATE_LIMIT_WAIT_JITTER_MS));
125
+ }
126
+ function sleep(ms) {
127
+ return new Promise(resolve => setTimeout(resolve, ms));
128
+ }
30
129
  /**
31
130
  * Error carrying the HTTP status behind a failed API call, so callers can
32
131
  * branch on auth failures (401/403) without parsing message strings.
33
132
  */
34
133
  export class ApiHttpError extends Error {
35
134
  httpStatus;
36
- constructor(message, httpStatus) {
135
+ /**
136
+ * Parsed `{detail: {code, message}}` from a structured developer error, when
137
+ * the body carried one (e.g. `project_kind_mismatch`). Lets callers branch on
138
+ * the server's own code instead of scraping the message string.
139
+ */
140
+ serverDetail;
141
+ constructor(message, httpStatus, serverDetail) {
37
142
  super(message);
38
143
  this.name = 'ApiHttpError';
39
144
  this.httpStatus = httpStatus;
145
+ this.serverDetail = serverDetail;
146
+ }
147
+ }
148
+ /**
149
+ * Parse a developer API error body. The backend returns structured
150
+ * `{"detail": {"code", "message"}}` for application errors (missing project,
151
+ * kind mismatch, ...); a route that does not exist on this server answers with
152
+ * a plain `{"detail": "Not Found"}` instead. `structured` is what tells the two
153
+ * apart, so a real 404 like `project_not_found` is never reported as an
154
+ * unsupported server.
155
+ */
156
+ export function parseDeveloperErrorDetail(body) {
157
+ try {
158
+ const parsed = JSON.parse(body);
159
+ const detail = parsed?.detail;
160
+ if (!detail || typeof detail !== 'object' || Array.isArray(detail)) {
161
+ return { structured: false };
162
+ }
163
+ const record = detail;
164
+ return {
165
+ structured: true,
166
+ ...(typeof record.code === 'string' ? { code: record.code } : {}),
167
+ ...(typeof record.message === 'string' ? { message: record.message } : {}),
168
+ };
169
+ }
170
+ catch {
171
+ return { structured: false };
40
172
  }
41
173
  }
42
174
  /** True when the error is an HTTP-level auth rejection (401/403). */
@@ -102,6 +234,92 @@ export class ApiClient {
102
234
  headers['X-Debug'] = 'true';
103
235
  return headers;
104
236
  }
237
+ /** Make one bounded request; creation and source writes must never be retried. */
238
+ async developerRequest(endpoint, init = {}) {
239
+ if (!this.apiKey) {
240
+ throw new Error('Run `gsk login` or provide GSK_API_KEY for cloud operations.');
241
+ }
242
+ const controller = new AbortController();
243
+ const timer = setTimeout(() => controller.abort(), this.timeout);
244
+ try {
245
+ const response = await fetch(`${this.baseUrl}/api/tool_cli${endpoint}`, {
246
+ ...init,
247
+ headers: { ...this.baseHeaders(), ...init.headers },
248
+ redirect: 'error',
249
+ signal: controller.signal,
250
+ });
251
+ if (!response.ok) {
252
+ const body = await response.text();
253
+ const detail = parseDeveloperErrorDetail(body);
254
+ // Only a *route* 404/405 means the server is too old. An application
255
+ // 404 (structured detail, e.g. project_not_found) is a normal answer.
256
+ const missingEndpoint = (response.status === 404 || response.status === 405) &&
257
+ !detail.structured;
258
+ const guidance = response.status === 503
259
+ ? ' Local-source/project writes may be disabled. Ask the operator to enable supported writers only after backend rollout; do not fall back to remote source.'
260
+ : missingEndpoint
261
+ ? ' This server does not support this developer CLI API. Use a supported backend; no remote-source fallback is available.'
262
+ : response.status === 401 || response.status === 403
263
+ ? ' Run `gsk login` and verify project ownership and account access.'
264
+ : '';
265
+ throw new ApiHttpError(`HTTP ${response.status}: ${body}${guidance}`, response.status, detail.structured
266
+ ? { code: detail.code, message: detail.message }
267
+ : undefined);
268
+ }
269
+ return await response.json();
270
+ }
271
+ finally {
272
+ clearTimeout(timer);
273
+ }
274
+ }
275
+ /** Explicitly create a project once, using the existing token identity. */
276
+ async createDeveloperProject(kind, name) {
277
+ const response = jsonObject(await this.developerRequest('/developer/projects', {
278
+ method: 'POST',
279
+ body: JSON.stringify({ kind, name }),
280
+ }));
281
+ return parseDeveloperProject(response.project);
282
+ }
283
+ /** Fetch a project through the server's owner-only developer route. */
284
+ async getDeveloperProject(id) {
285
+ const response = jsonObject(await this.developerRequest(`/developer/projects/${encodeURIComponent(id)}`));
286
+ const project = parseDeveloperProject(response.project);
287
+ if (project.project_id !== id) {
288
+ throw new Error('Server returned a different project; refusing to bind');
289
+ }
290
+ return project;
291
+ }
292
+ /** Read advisory account checks without creating a project or sandbox. */
293
+ async developerPreflight(kind, operation) {
294
+ const query = new URLSearchParams({ kind, operation });
295
+ if (this.projectId)
296
+ query.set('project_id', this.projectId);
297
+ return parseDeveloperPreflight(await this.developerRequest(`/developer/preflight?${query}`));
298
+ }
299
+ /** Stream a ZIP to the selected project and return its unmodified source receipt. */
300
+ async uploadHostedSource(filename, size) {
301
+ if (!this.projectId) {
302
+ throw new Error('Bind a project before uploading local source');
303
+ }
304
+ const stream = createReadStream(filename);
305
+ try {
306
+ const init = {
307
+ method: 'POST',
308
+ duplex: 'half',
309
+ headers: {
310
+ 'Content-Type': 'application/zip',
311
+ 'Content-Length': String(size),
312
+ },
313
+ // Node fetch accepts a Node Readable; DOM RequestInit omits that overload.
314
+ body: stream,
315
+ };
316
+ const response = jsonObject(await this.developerRequest('/hosted/source', init));
317
+ return jsonObject(response.local_source);
318
+ }
319
+ finally {
320
+ stream.destroy();
321
+ }
322
+ }
105
323
  async request(endpoint, method = 'GET', body) {
106
324
  const url = `${this.baseUrl}/api/tool_cli${endpoint}`;
107
325
  debug(`Request: ${method} ${url}`);
@@ -125,6 +343,23 @@ export class ApiClient {
125
343
  if (!response.ok) {
126
344
  const errorText = await response.text();
127
345
  debug(`Error response: ${errorText}`);
346
+ const denial = parseRateLimitDenial(response.status, response.headers, errorText);
347
+ if (denial) {
348
+ // This buffered path discarded the body entirely, so a 429 reached
349
+ // the caller as the bare statusText — not even the prose wait
350
+ // survived (#61436).
351
+ return {
352
+ status: 'error',
353
+ message: denial.message,
354
+ data: null,
355
+ http_status: response.status,
356
+ error_code: 'rate_limited',
357
+ retry_after: denial.retryAfter,
358
+ ...(denial.instructionForAgent
359
+ ? { instruction_for_agent: denial.instructionForAgent }
360
+ : {}),
361
+ };
362
+ }
128
363
  return {
129
364
  status: 'error',
130
365
  message: `HTTP ${response.status}: ${response.statusText}`,
@@ -310,14 +545,73 @@ export class ApiClient {
310
545
  }
311
546
  onProgress?.(msg);
312
547
  };
548
+ const deadline = Date.now() + this.timeout;
549
+ let denial = null;
313
550
  try {
314
- return await this.requestStreaming(`/${toolName}`, args, wrappedOnProgress, timeoutController.signal);
551
+ // Wait out a rate-limit denial instead of handing it straight back.
552
+ //
553
+ // #61436: one agent took 17,755 429s in 12 hours against a 60/min
554
+ // mutation cap — every rejected call came back instantly, so the model
555
+ // simply issued the next one, and 7 hours of a task were spent on
556
+ // requests that could not land. The denial happens BEFORE any work, so
557
+ // re-sending after the window rolls is safe for a mutation too.
558
+ //
559
+ // Deliberately ONE automatic wait, not a loop: it paces a caller onto
560
+ // the cap without hiding a genuinely stuck agent behind minutes of
561
+ // invisible sleeping, and a second denial still reaches the model with
562
+ // `error_code` + `retry_after` to act on.
563
+ for (let attempt = 0;; attempt++) {
564
+ const result = await this.requestStreaming(`/${toolName}`, args, wrappedOnProgress, timeoutController.signal);
565
+ if (attempt > 0 ||
566
+ result.error_code !== 'rate_limited' ||
567
+ (toolName === 'hosted_deploy' && Object.hasOwn(args, 'local_source'))) {
568
+ return result;
569
+ }
570
+ const waitMs = rateLimitWaitMs({
571
+ retryAfter: result.retry_after ?? 1,
572
+ message: result.message,
573
+ });
574
+ // Never sleep past the caller's own timeout, and never spend it down
575
+ // to a retry that cannot finish — reporting the denial now beats
576
+ // converting it into an unrecognizable timeout.
577
+ if (Date.now() + waitMs + MIN_RETRY_BUDGET_MS >= deadline)
578
+ return result;
579
+ // Remembered so an abort during the retry still reports the rate
580
+ // limit rather than a bare timeout.
581
+ denial = result;
582
+ // The wait is silent on the wire, and `resolve_retry_after` falls
583
+ // back to the 60s window — so the common case is ~62s of zero
584
+ // output, long enough to trip an inactivity timer (Claude Code's
585
+ // Bash tool, 2-min default; issue #30305).
586
+ //
587
+ // This goes out on `info` (unconditional stderr) and NOT only via
588
+ // `wrappedOnProgress`, because no `executeTool` call site in
589
+ // index.ts passes an `onProgress` — all six are two-argument calls,
590
+ // including the generic `gsk <tool>` path a `gsk gmail` takes. A
591
+ // heartbeat routed solely through that callback reaches nobody in
592
+ // production, and `debug()` needs `--debug`. `info` not `progress`:
593
+ // `progress` is TTY-gated, and the sandbox agent is exactly the
594
+ // reader that needs these bytes.
595
+ const waitSeconds = Math.round(waitMs / 1000);
596
+ info(`Rate limited; waiting ${waitSeconds}s before one retry`);
597
+ wrappedOnProgress({
598
+ message: `Rate limited; waiting ${waitSeconds}s before one retry`,
599
+ rate_limited: true,
600
+ retry_after: result.retry_after ?? null,
601
+ });
602
+ await sleep(waitMs);
603
+ }
315
604
  }
316
605
  catch (err) {
317
606
  // requestStreaming re-throws AbortError when externalSignal fired.
318
607
  // Convert to an ApiResponse so existing callers don't need to
319
608
  // handle exceptions.
320
609
  if (err instanceof Error && err.name === 'AbortError') {
610
+ // A timeout that lands on the RETRY is still a rate limit as far as
611
+ // the agent is concerned; returning the bare timeout would strip the
612
+ // fields the prompt rule and the backoff both key on.
613
+ if (denial)
614
+ return denial;
321
615
  return {
322
616
  status: 'error',
323
617
  message: `Request timeout after ${this.timeout}ms`,
@@ -501,6 +795,12 @@ export class ApiClient {
501
795
  const query = model ? `?model=${encodeURIComponent(model)}` : '';
502
796
  return this.requestJson(`/opencode-config${query}`);
503
797
  }
798
+ /**
799
+ * Get the genspark-code (code sandbox) skill bundle
800
+ */
801
+ async getGensparkCodeSkills() {
802
+ return this.requestJson('/genspark-code-skills');
803
+ }
504
804
  /**
505
805
  * Get Pi (pi.dev) config bundle: `{ models, settings, genspark }`.
506
806
  */
@@ -539,10 +839,28 @@ export class ApiClient {
539
839
  if (!response.ok) {
540
840
  clearTimeout(timeoutId);
541
841
  const errorText = await response.text();
842
+ const denial = parseRateLimitDenial(response.status, response.headers, errorText);
843
+ if (denial) {
844
+ // Surface the wait as fields, not only as prose inside a string —
845
+ // executeTool backs off on these, and a model reading the result
846
+ // gets a sentence it can act on instead of `HTTP 429: {…}`.
847
+ return {
848
+ status: 'error',
849
+ message: denial.message,
850
+ data: null,
851
+ http_status: response.status,
852
+ error_code: 'rate_limited',
853
+ retry_after: denial.retryAfter,
854
+ ...(denial.instructionForAgent
855
+ ? { instruction_for_agent: denial.instructionForAgent }
856
+ : {}),
857
+ };
858
+ }
542
859
  return {
543
860
  status: 'error',
544
861
  message: `HTTP ${response.status}: ${errorText}`,
545
862
  data: null,
863
+ http_status: response.status,
546
864
  };
547
865
  }
548
866
  if (!response.body) {