specrails-desktop 2.6.0 → 2.7.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 (48) hide show
  1. package/client/dist/assets/{ActivityFeedPage-CoWwVcty.js → ActivityFeedPage-LKqd18-G.js} +1 -1
  2. package/client/dist/assets/{AgentsPage-CgPvynWc.js → AgentsPage-Cb-b-6Ot.js} +1 -1
  3. package/client/dist/assets/AnalyticsPage-HVxQQ1wy.js +1 -0
  4. package/client/dist/assets/{BarChart-BKXQPcoW.js → BarChart-BOyHB0dw.js} +1 -1
  5. package/client/dist/assets/{CodePage-CYhXRKiI.js → CodePage-DnOnwKGB.js} +1 -1
  6. package/client/dist/assets/{DesktopAnalyticsPage-CBfPCT3q.js → DesktopAnalyticsPage-D2auU39x.js} +1 -1
  7. package/client/dist/assets/{DocsDialog-uRTBV-3T.js → DocsDialog-CTuDX3GK.js} +1 -1
  8. package/client/dist/assets/{DocsPage-gH0Lc54I.js → DocsPage-DRyMmu0Z.js} +1 -1
  9. package/client/dist/assets/{ExportDropdown-DAp7zWib.js → ExportDropdown-DO-GGiMh.js} +1 -1
  10. package/client/dist/assets/{IntegrationsPage-D40Si_7s.js → IntegrationsPage-BhbO4jFT.js} +1 -1
  11. package/client/dist/assets/{JobDetailPage-DSxAvB1n.js → JobDetailPage-DJooEg1s.js} +1 -1
  12. package/client/dist/assets/{JobsPage-ZMBc1BHE.js → JobsPage-BbaC-YOg.js} +1 -1
  13. package/client/dist/assets/{addspec-DeDOztDr.js → addspec-B-BKlvDj.js} +1 -1
  14. package/client/dist/assets/{addspec-v8j6A7CD.js → addspec-BErjOdNK.js} +1 -1
  15. package/client/dist/assets/{addspec-B1FTtI2a.js → addspec-CIGb34PS.js} +1 -1
  16. package/client/dist/assets/{addspec-GWm4ffKl.js → addspec-C_3NBarY.js} +1 -1
  17. package/client/dist/assets/{addspec-Dw-0Dg-4.js → addspec-DDvvnE6N.js} +1 -1
  18. package/client/dist/assets/{addspec-DpRgmfmx.js → addspec-RuL8Zd7w.js} +1 -1
  19. package/client/dist/assets/{addspec-rp496P_F.js → addspec-rmhOaH7N.js} +1 -1
  20. package/client/dist/assets/{addspec-BCT9vm_c.js → addspec-xjDbYZWL.js} +1 -1
  21. package/client/dist/assets/{dist-js-CKqmDyXR.js → dist-js-CiIVMsx3.js} +1 -1
  22. package/client/dist/assets/{dist-js-bTZuok_W.js → dist-js-Xc2lRKp2.js} +1 -1
  23. package/client/dist/assets/{index-B9IKK_QQ.js → index-DK214dak.js} +34 -34
  24. package/client/dist/assets/index-DgKfQFcf.css +2 -0
  25. package/client/dist/assets/{lib-B5mjOeEi.js → lib-Bo5s6xpe.js} +1 -1
  26. package/client/dist/assets/{useProjectCache-Cf83MBQh.js → useProjectCache-DVNypkmR.js} +1 -1
  27. package/client/dist/index.html +3 -3
  28. package/docs/adding-a-provider.md +107 -0
  29. package/docs/agy-cli-provider-study.md +179 -0
  30. package/docs/gemini-cli-provider-study.md +301 -0
  31. package/docs/gemini-core-support-evaluation.md +160 -0
  32. package/docs/gemini.md +106 -0
  33. package/package.json +1 -1
  34. package/server/dist/chat-manager.js +1 -1
  35. package/server/dist/core-package.js +6 -1
  36. package/server/dist/desktop-router.js +27 -8
  37. package/server/dist/explore-cwd-manager.js +1 -1
  38. package/server/dist/mobile/mobile-datachannel.js +65 -4
  39. package/server/dist/pricing.js +13 -0
  40. package/server/dist/project-router-tickets.js +63 -18
  41. package/server/dist/providers/gemini-adapter.js +234 -0
  42. package/server/dist/providers/index.js +4 -1
  43. package/server/dist/setup-manager.js +13 -7
  44. package/server/dist/setup-prerequisites.js +4 -0
  45. package/server/dist/spec-models.js +17 -3
  46. package/server/dist/util/cli-prompt.js +17 -1
  47. package/client/dist/assets/AnalyticsPage-ioz3Ub2D.js +0 -1
  48. package/client/dist/assets/index-BqAXaTbC.css +0 -2
@@ -8,7 +8,12 @@ exports.CORE_PACKAGE_SPEC = void 0;
8
8
  * minute it is published — adopting a new major is a deliberate one-line
9
9
  * bump here, shipped through the app's own release pipeline.
10
10
  *
11
+ * Floor bumped to 4.8.0 — the version that ships the Gemini provider target
12
+ * (`.gemini/` commands + agents). It also changes the `npx` package-spec string,
13
+ * which invalidates any stale `_npx` exec cache that npx would otherwise reuse
14
+ * for the old `^4.6.0` range (so users actually resolve the newer core).
15
+ *
11
16
  * `SPECRAILS_CORE_BIN` remains the escape hatch for local/linked builds
12
17
  * (see getCoreCommand in setup-manager.ts).
13
18
  */
14
- exports.CORE_PACKAGE_SPEC = 'specrails-core@^4.6.0';
19
+ exports.CORE_PACKAGE_SPEC = 'specrails-core@^4.8.0';
@@ -29,6 +29,14 @@ function isCodexBetaDisabled() {
29
29
  const v = process.env.SPECRAILS_CODEX_BETA ?? process.env.SPECRAILS_HUB_CODEX_BETA;
30
30
  return v === '0';
31
31
  }
32
+ // Gemini is opt-IN (default off): unlike codex, its stream-json schema has not
33
+ // yet been validated against a live binary, so it stays hidden + unselectable
34
+ // until SPECRAILS_GEMINI_BETA=1 (or 'true'). The adapter is always registered
35
+ // (pricing/getAdapter work); only project selection is gated.
36
+ function isGeminiBetaEnabled() {
37
+ const v = (process.env.SPECRAILS_GEMINI_BETA ?? '').toLowerCase();
38
+ return v === '1' || v === 'true';
39
+ }
32
40
  // Theme allow-list. Mirror of THEME_IDS in `client/src/lib/themes.ts` —
33
41
  // kept duplicated to avoid pulling client code into the server bundle.
34
42
  const THEME_ID_ALLOWLIST = new Set(['dracula', 'aurora-light', 'obsidian-dark', 'matrix', 'specrails']);
@@ -144,14 +152,19 @@ function createDesktopRouter(registry, broadcast) {
144
152
  const providers = (0, core_compat_1.detectAvailableCLIs)();
145
153
  // tiers: quick install is always available (app-driven config); full requires an AI CLI
146
154
  const tiers = ['quick'];
147
- if (providers.claude || providers.codex)
155
+ if (Object.values(providers).some(Boolean))
148
156
  tiers.push('full');
149
- const codexBetaOff = isCodexBetaDisabled();
150
- res.json({
151
- claude: providers.claude,
152
- codex: codexBetaOff ? false : providers.codex,
153
- tiers,
154
- });
157
+ // Return the full detected map (registry-driven) so a newly-registered
158
+ // provider surfaces here with no edit. Apply per-provider beta gates: codex
159
+ // is forced unavailable when SPECRAILS_CODEX_BETA=0 (emergency rollback).
160
+ const gated = { ...providers };
161
+ if (isCodexBetaDisabled())
162
+ gated.codex = false;
163
+ // Gemini is opt-in: omit it entirely (not just `false`) when the beta flag is
164
+ // off, so it stays fully invisible in the UI until SPECRAILS_GEMINI_BETA=1.
165
+ if (!isGeminiBetaEnabled())
166
+ delete gated.gemini;
167
+ res.json({ ...gated, tiers });
155
168
  });
156
169
  router.get('/setup-prerequisites', (req, res) => {
157
170
  const status = (0, setup_prerequisites_1.getSetupPrerequisitesStatus)();
@@ -218,6 +231,12 @@ function createDesktopRouter(registry, broadcast) {
218
231
  });
219
232
  return;
220
233
  }
234
+ if (providers.includes('gemini') && !isGeminiBetaEnabled()) {
235
+ res.status(400).json({
236
+ error: 'Gemini provider is in beta and disabled by default. Set SPECRAILS_GEMINI_BETA=1 to enable.',
237
+ });
238
+ return;
239
+ }
221
240
  const resolvedPath = path_1.default.resolve(projectPath);
222
241
  // Validate path exists
223
242
  if (!fs_1.default.existsSync(resolvedPath)) {
@@ -243,7 +262,7 @@ function createDesktopRouter(registry, broadcast) {
243
262
  name: derivedName,
244
263
  path: canonicalPath,
245
264
  provider: providers[0],
246
- providers: providers,
265
+ providers,
247
266
  });
248
267
  broadcast({
249
268
  type: 'desktop.project_added',
@@ -127,7 +127,7 @@ function ensureExploreCwd(input, baseDir) {
127
127
  // — provider is immutable post-creation but the lifecycle code MUST handle
128
128
  // the edge per spec), remove any stale instructions file authored by a
129
129
  // different provider so the explore-cwd doesn't carry both.
130
- const STALE_INSTRUCTION_FILES = ['CLAUDE.md', 'AGENTS.md'];
130
+ const STALE_INSTRUCTION_FILES = ['CLAUDE.md', 'AGENTS.md', 'GEMINI.md'];
131
131
  for (const stale of STALE_INSTRUCTION_FILES) {
132
132
  if (stale === adapter.instructionsFilename)
133
133
  continue;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DataChannelPeer = exports.DataChannelSocket = void 0;
3
+ exports.DataChannelPeer = exports.DataChannelSocket = exports.ChunkReassembler = void 0;
4
4
  // WebRTC DataChannel transport for the web companion (serverless double-QR
5
5
  // pairing). Instead of a LAN WSS gateway, the companion connects peer-to-peer
6
6
  // over a WebRTC DataChannel; this module bridges that channel onto the EXISTING
@@ -15,6 +15,63 @@ exports.DataChannelPeer = exports.DataChannelSocket = void 0;
15
15
  // without a real WebRTC stack, the database, or the loopback HTTP forward.
16
16
  const WS_OPEN = 1;
17
17
  const WS_CLOSED = 3;
18
+ // WebRTC DataChannels carry an SCTP per-message size cap (werift advertises a
19
+ // modest maxMessageSize; oversized sends throw). A large rpc_result — e.g. a
20
+ // JIRA-backed project's full ticket list — easily exceeds it, and the throw was
21
+ // swallowed silently, so the companion just timed out and rendered "0 tickets".
22
+ // We split any oversized frame into ordered `__chunk` envelopes and reassemble
23
+ // them on the far side. The channel is ordered+reliable, so chunks arrive in
24
+ // order; `g` (group id) keeps concurrent large messages from interleaving.
25
+ const CHUNK_SIZE = 16000;
26
+ let _chunkGroup = 0;
27
+ /** Send `data` over `ch`, splitting into `__chunk` frames when it exceeds the
28
+ * safe per-message size. Small frames go out verbatim (no envelope overhead). */
29
+ function framedSend(ch, data) {
30
+ if (data.length <= CHUNK_SIZE) {
31
+ ch.send(data);
32
+ return;
33
+ }
34
+ const g = _chunkGroup++;
35
+ const n = Math.ceil(data.length / CHUNK_SIZE);
36
+ for (let i = 0; i < n; i++) {
37
+ const d = data.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE);
38
+ ch.send(JSON.stringify({ type: '__chunk', g, i, n, d }));
39
+ }
40
+ }
41
+ /** Buffers inbound `__chunk` frames and yields the reassembled payload once a
42
+ * group is complete. Non-chunk frames pass straight through. */
43
+ class ChunkReassembler {
44
+ _groups = new Map();
45
+ /** Returns the string to handle (the frame itself, or a completed
46
+ * reassembly), or null when more chunks of the group are still pending. */
47
+ push(data) {
48
+ if (!data.startsWith('{"type":"__chunk"'))
49
+ return data;
50
+ let p;
51
+ try {
52
+ p = JSON.parse(data);
53
+ }
54
+ catch {
55
+ return data;
56
+ }
57
+ if (!p || p.n == null)
58
+ return data;
59
+ let grp = this._groups.get(p.g);
60
+ if (!grp) {
61
+ grp = { n: p.n, parts: new Array(p.n).fill(''), got: 0 };
62
+ this._groups.set(p.g, grp);
63
+ }
64
+ if (grp.parts[p.i] === '' && grp.got < grp.n) {
65
+ grp.parts[p.i] = p.d;
66
+ grp.got++;
67
+ }
68
+ if (grp.got < grp.n)
69
+ return null;
70
+ this._groups.delete(p.g);
71
+ return grp.parts.join('');
72
+ }
73
+ }
74
+ exports.ChunkReassembler = ChunkReassembler;
18
75
  /** Presents a DataChannel to MobileWsBridge as if it were a ws.WebSocket, so the
19
76
  * existing fan-out (redaction, per-subscription filtering, log batching) is
20
77
  * reused unchanged. WebRTC has no ping/pong frames, so ping() reports liveness
@@ -30,7 +87,7 @@ class DataChannelSocket {
30
87
  }
31
88
  send(data) {
32
89
  try {
33
- this._ch.send(data);
90
+ framedSend(this._ch, data);
34
91
  }
35
92
  catch {
36
93
  /* channel went away mid-send — onClose will reap it */
@@ -88,12 +145,16 @@ class DataChannelPeer {
88
145
  _sock;
89
146
  _authed = false;
90
147
  _token = '';
148
+ _reasm = new ChunkReassembler();
91
149
  constructor(_ch, _deps) {
92
150
  this._ch = _ch;
93
151
  this._deps = _deps;
94
152
  this._sock = new DataChannelSocket(_ch);
95
153
  _ch.onMessage((data) => {
96
- void this._onMessage(data);
154
+ const full = this._reasm.push(data);
155
+ if (full === null)
156
+ return;
157
+ void this._onMessage(full);
97
158
  });
98
159
  _ch.onClose(() => this._sock.closed());
99
160
  }
@@ -102,7 +163,7 @@ class DataChannelPeer {
102
163
  }
103
164
  _send(obj) {
104
165
  try {
105
- this._ch.send(JSON.stringify(obj));
166
+ framedSend(this._ch, JSON.stringify(obj));
106
167
  }
107
168
  catch {
108
169
  /* ignore */
@@ -32,6 +32,19 @@ exports.PRICING = {
32
32
  'codex:gpt-5.4': { inputPer1M: 2.50, outputPer1M: 10.00, cacheReadPer1M: 0.25, lastReviewedAt: '2026-05-17' },
33
33
  'codex:gpt-5.4-mini': { inputPer1M: 0.25, outputPer1M: 2.00, cacheReadPer1M: 0.025, lastReviewedAt: '2026-05-17' },
34
34
  'codex:gpt-5.3-codex': { inputPer1M: 1.50, outputPer1M: 6.00, cacheReadPer1M: 0.15, lastReviewedAt: '2026-05-17' },
35
+ // Gemini (Google). Reference: https://ai.google.dev/gemini-api/docs/pricing
36
+ // Standard paid tier, <=200k-context prices (Gemini Pro is context-tiered;
37
+ // prompts >200k are under-estimated in v1 — see docs/gemini-cli-provider-study.md §2).
38
+ // Current catalog (June 2026): 3.5-flash flagship default, 3.1-pro-preview max,
39
+ // 3.1-flash-lite budget, 2.5-flash-lite cheapest. Older 2.5-pro/2.5-flash rows
40
+ // are retained so historic invocations still price.
41
+ 'gemini:gemini-3.5-flash': { inputPer1M: 1.50, outputPer1M: 9.00, cacheReadPer1M: 0.15, lastReviewedAt: '2026-06-17' },
42
+ 'gemini:gemini-3.1-pro-preview': { inputPer1M: 2.00, outputPer1M: 12.00, cacheReadPer1M: 0.20, lastReviewedAt: '2026-06-17' },
43
+ 'gemini:gemini-3.1-flash-lite': { inputPer1M: 0.25, outputPer1M: 1.50, cacheReadPer1M: 0.025, lastReviewedAt: '2026-06-17' },
44
+ 'gemini:gemini-3-flash-preview': { inputPer1M: 0.50, outputPer1M: 3.00, cacheReadPer1M: 0.05, lastReviewedAt: '2026-06-17' },
45
+ 'gemini:gemini-2.5-pro': { inputPer1M: 1.25, outputPer1M: 10.00, cacheReadPer1M: 0.125, lastReviewedAt: '2026-06-17' },
46
+ 'gemini:gemini-2.5-flash': { inputPer1M: 0.30, outputPer1M: 2.50, cacheReadPer1M: 0.03, lastReviewedAt: '2026-06-17' },
47
+ 'gemini:gemini-2.5-flash-lite': { inputPer1M: 0.10, outputPer1M: 0.40, cacheReadPer1M: 0.01, lastReviewedAt: '2026-06-17' },
35
48
  };
36
49
  /**
37
50
  * Estimate cost in USD from a token usage breakdown. Returns `null` when:
@@ -393,24 +393,44 @@ function registerTicketsRoutes(deps) {
393
393
  broadcast(msg);
394
394
  return;
395
395
  }
396
- // Claude path.
397
- if (parsed.type === 'result') {
396
+ if (provider === 'claude') {
397
+ // Claude path.
398
+ if (parsed.type === 'result') {
399
+ lastResultEvent = parsed;
400
+ }
401
+ if (parsed.type === 'assistant') {
402
+ const msg = parsed.message;
403
+ const texts = (msg?.content ?? [])
404
+ .filter((c) => c.type === 'text')
405
+ .map((c) => c.text ?? '');
406
+ const newText = texts.join('');
407
+ if (newText) {
408
+ buffer += newText;
409
+ const wsMsg = {
410
+ type: 'spec_gen_stream', projectId, requestId,
411
+ delta: newText, timestamp: new Date().toISOString(),
412
+ };
413
+ broadcast(wsMsg);
414
+ }
415
+ }
416
+ return;
417
+ }
418
+ // Adapter-driven path (gemini + future providers): the adapter already
419
+ // parsed this line into a structured AdapterEvent above (`adapterEv`).
420
+ // Accumulate assistant text deltas into the buffer and capture the result
421
+ // event for usage extraction — mirrors the ai-edit endpoint's else branch.
422
+ // Without this, gemini (which emits `type:'message'`, not `type:'assistant'`)
423
+ // would never accumulate text → empty buffer → "Empty response from AI".
424
+ if (adapterEv?.kind === 'result') {
398
425
  lastResultEvent = parsed;
399
426
  }
400
- if (parsed.type === 'assistant') {
401
- const msg = parsed.message;
402
- const texts = (msg?.content ?? [])
403
- .filter((c) => c.type === 'text')
404
- .map((c) => c.text ?? '');
405
- const newText = texts.join('');
406
- if (newText) {
407
- buffer += newText;
408
- const wsMsg = {
409
- type: 'spec_gen_stream', projectId, requestId,
410
- delta: newText, timestamp: new Date().toISOString(),
411
- };
412
- broadcast(wsMsg);
413
- }
427
+ if (adapterEv?.kind === 'text-delta' && adapterEv.text) {
428
+ buffer += adapterEv.text;
429
+ const wsMsg = {
430
+ type: 'spec_gen_stream', projectId, requestId,
431
+ delta: adapterEv.text, timestamp: new Date().toISOString(),
432
+ };
433
+ broadcast(wsMsg);
414
434
  }
415
435
  });
416
436
  child.on('close', async (code) => {
@@ -1476,7 +1496,7 @@ function registerTicketsRoutes(deps) {
1476
1496
  // Use gpt-5.5 (default for Codex per CODEX_MODELS/PRESET_DEFAULTS in ModelSelector); never hardcode o4-mini
1477
1497
  args = ['exec', `${systemPrompt}\n\n${userPrompt}`, '--model', 'gpt-5.5'];
1478
1498
  }
1479
- else {
1499
+ else if (provider === 'claude') {
1480
1500
  binary = 'claude';
1481
1501
  args = [
1482
1502
  '--dangerously-skip-permissions',
@@ -1489,6 +1509,18 @@ function registerTicketsRoutes(deps) {
1489
1509
  '-p', userPrompt,
1490
1510
  ];
1491
1511
  }
1512
+ else {
1513
+ // Adapter-driven path (gemini + any future provider): binary, argv, and
1514
+ // stream parsing all come from the registered adapter — no per-provider
1515
+ // hardcoding. The claude/codex shapes above are kept byte-identical.
1516
+ const adapter = (0, providers_1.getAdapter)(provider);
1517
+ binary = adapter.binary;
1518
+ args = adapter.buildArgs('agent-refine', {
1519
+ prompt: userPrompt,
1520
+ systemPrompt,
1521
+ model: adapter.defaultModel(),
1522
+ });
1523
+ }
1492
1524
  // spawnAiCli reroutes multi-line argv values through stdin on Windows.
1493
1525
  console.log(`[project-router] ai-edit spawn: ${binary} (cwd=${project.path}, requestId=${requestId})`);
1494
1526
  const child = (0, cli_prompt_1.spawnAiCli)(binary, args, {
@@ -1534,7 +1566,7 @@ function registerTicketsRoutes(deps) {
1534
1566
  broadcast(msg);
1535
1567
  }
1536
1568
  }
1537
- else {
1569
+ else if (provider === 'claude') {
1538
1570
  let parsed = null;
1539
1571
  try {
1540
1572
  parsed = JSON.parse(line);
@@ -1558,6 +1590,19 @@ function registerTicketsRoutes(deps) {
1558
1590
  }
1559
1591
  }
1560
1592
  }
1593
+ else {
1594
+ // Adapter-driven parse (gemini + future providers): uniform AdapterEvent
1595
+ // stream — accumulate assistant text deltas.
1596
+ const ev = (0, providers_1.getAdapter)(provider).parseStreamLine(line);
1597
+ if (ev?.kind === 'text-delta' && ev.text) {
1598
+ buffer += ev.text;
1599
+ const wsMsg = {
1600
+ type: 'ticket_ai_edit_stream', projectId, ticketId: Number(ticketId),
1601
+ requestId, delta: ev.text, timestamp: new Date().toISOString(),
1602
+ };
1603
+ broadcast(wsMsg);
1604
+ }
1605
+ }
1561
1606
  });
1562
1607
  child.on('close', (code) => {
1563
1608
  _aiEditProcesses.delete(requestId);
@@ -0,0 +1,234 @@
1
+ "use strict";
2
+ // Gemini CLI (Google) adapter for gemini-cli 0.11.0+.
3
+ //
4
+ // Stream format (gemini `-p "<prompt>" --output-format stream-json`), one minified
5
+ // JSON object per line — pinned to gemini-cli >= 0.11 and locked by the fixtures
6
+ // under __fixtures__/gemini-*.ndjson:
7
+ // {"type":"init","session_id":"<UUID>","model":"gemini-3.5-flash"}
8
+ // {"type":"message","role":"assistant","content":"...","delta":true}
9
+ // {"type":"tool_use","tool_name":"read_file","tool_id":"t0","parameters":{...}}
10
+ // {"type":"tool_result","tool_id":"t0","status":"ok","output":"..."}
11
+ // {"type":"result","status":"success","stats":{"input_tokens":N,"output_tokens":N,
12
+ // "cached":N,"total_tokens":N,"duration_ms":N}}
13
+ //
14
+ // Differences vs codex: Gemini reports tokens but NOT cost, so `nativeCostUsd`
15
+ // is false and cost is estimated downstream via server/pricing.ts. Gemini DOES
16
+ // emit OTLP natively via `GEMINI_TELEMETRY_*` env (set by QueueManager), so
17
+ // `nativeOtelEnv` is true — no synthetic bridge. There is no `--system-prompt`
18
+ // flag (the CLI uses the `GEMINI_SYSTEM_MD` env), so `systemPromptArg` is false
19
+ // and the system prompt is folded for non-Explore actions; Explore turns trust
20
+ // the app-managed GEMINI.md in explore-cwd, exactly like codex/AGENTS.md.
21
+ //
22
+ // NOTE (pre-1.0): gemini-cli changes weekly. The exact argv/event field names
23
+ // here follow the documented 0.11 contract; they are guarded by the beta flag
24
+ // (SPECRAILS_GEMINI_BETA) and MUST be re-validated against a real binary via the
25
+ // fixtures before the gate is removed. Parsing is tolerant of missing fields.
26
+ //
27
+ // Spec: openspec/specs/multi-provider-architecture/spec.md
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports._GEMINI_MIN_VERSION = exports.geminiAdapter = void 0;
30
+ exports._compareSemver = compareSemver;
31
+ const child_process_1 = require("child_process");
32
+ const WHICH_CMD = process.platform === 'win32' ? 'where' : 'which';
33
+ // Floor where `--output-format stream-json` + headless `--resume` are available.
34
+ const GEMINI_MIN_VERSION = '0.11.0';
35
+ exports._GEMINI_MIN_VERSION = GEMINI_MIN_VERSION;
36
+ // Curated GA-id catalog (see docs/gemini-cli-provider-study.md §2). Preview ids
37
+ // rotate, so we pin concrete ids that pricing.ts has rows for.
38
+ const GEMINI_MODELS = [
39
+ { value: 'gemini-3.5-flash', label: 'Gemini 3.5 Flash', default: true },
40
+ { value: 'gemini-3.1-pro-preview', label: 'Gemini 3.1 Pro (preview)' },
41
+ { value: 'gemini-3.1-flash-lite', label: 'Gemini 3.1 Flash Lite' },
42
+ { value: 'gemini-2.5-flash-lite', label: 'Gemini 2.5 Flash Lite' },
43
+ ];
44
+ const STREAM_JSON_FLAGS = ['--output-format', 'stream-json'];
45
+ // Auto-approve tool calls so headless turns never block on an approval prompt.
46
+ // Parity with codex's workspace-write/full-access sandbox; the non-destructive
47
+ // stance for Explore is carried by GEMINI.md + the system prompt, not a sandbox.
48
+ const YOLO_FLAG = '--yolo';
49
+ /** Fold system prompt into the user prompt for providers without --system-prompt. */
50
+ function fold(systemPrompt, prompt) {
51
+ if (!systemPrompt)
52
+ return prompt;
53
+ return `${systemPrompt}\n\n---\n\n${prompt}`;
54
+ }
55
+ function buildGeminiArgs(action, opts) {
56
+ const model = ['--model', opts.model];
57
+ switch (action) {
58
+ case 'chat-turn': {
59
+ // Explore turns spawn from the app-managed explore-cwd, which ships a
60
+ // GEMINI.md with the Explore stance. Folding the long system prompt into a
61
+ // short user message ("quiero hacer un tetris") makes the model answer the
62
+ // system instructions instead of the user — so pass user text only and
63
+ // trust GEMINI.md, exactly like the codex adapter trusts AGENTS.md.
64
+ return ['-p', opts.prompt, ...model, ...STREAM_JSON_FLAGS, YOLO_FLAG, ...(opts.extraArgs ?? [])];
65
+ }
66
+ case 'chat-resume': {
67
+ if (!opts.sessionId)
68
+ throw new Error(`${action} requires sessionId`);
69
+ return ['-p', opts.prompt, ...model, ...STREAM_JSON_FLAGS, '--resume', opts.sessionId, YOLO_FLAG, ...(opts.extraArgs ?? [])];
70
+ }
71
+ case 'chat-stream': {
72
+ // Gemini has no persistent-stdin multi-turn transport; the Explore
73
+ // fast-path gates on capabilities.persistentStdin (omitted), so this is
74
+ // never reached. Throw defensively rather than emit a broken argv.
75
+ throw new Error('gemini does not support persistent stdin streaming (chat-stream)');
76
+ }
77
+ case 'spec-gen':
78
+ case 'agent-refine':
79
+ case 'auto-title':
80
+ case 'setup-enrich':
81
+ case 'rail-job': {
82
+ return ['-p', fold(opts.systemPrompt, opts.prompt), ...model, ...STREAM_JSON_FLAGS, YOLO_FLAG, ...(opts.extraArgs ?? [])];
83
+ }
84
+ case 'setup-enrich-resume': {
85
+ if (!opts.sessionId)
86
+ throw new Error(`${action} requires sessionId`);
87
+ return ['-p', fold(opts.systemPrompt, opts.prompt), ...model, ...STREAM_JSON_FLAGS, '--resume', opts.sessionId, YOLO_FLAG, ...(opts.extraArgs ?? [])];
88
+ }
89
+ }
90
+ }
91
+ function parseGeminiStreamLine(line) {
92
+ if (line.length === 0)
93
+ return null;
94
+ let parsed;
95
+ try {
96
+ parsed = JSON.parse(line);
97
+ }
98
+ catch {
99
+ return null;
100
+ }
101
+ const type = parsed.type;
102
+ if (!type)
103
+ return { kind: 'other', type: '<missing>', raw: parsed };
104
+ if (type === 'init') {
105
+ const sid = parsed.session_id;
106
+ if (sid)
107
+ return { kind: 'session-started', sessionId: sid };
108
+ return { kind: 'other', type, raw: parsed };
109
+ }
110
+ if (type === 'result') {
111
+ return { kind: 'result', payload: parsed };
112
+ }
113
+ if (type === 'message') {
114
+ // Only assistant text is a delta; the user echo (role 'user') is ignored.
115
+ const role = parsed.role;
116
+ if (role === 'assistant') {
117
+ const text = parsed.content ?? '';
118
+ if (text)
119
+ return { kind: 'text-delta', text };
120
+ }
121
+ return { kind: 'other', type, raw: parsed };
122
+ }
123
+ if (type === 'tool_use') {
124
+ const name = parsed.tool_name ?? '<unnamed>';
125
+ const params = parsed.parameters;
126
+ const inputPreview = params !== undefined ? JSON.stringify(params).slice(0, 200) : '';
127
+ return { kind: 'tool-use', name, inputPreview };
128
+ }
129
+ // tool_result, error, and any unknown event type carry no normalised meaning.
130
+ return { kind: 'other', type, raw: parsed };
131
+ }
132
+ function extractGeminiResult(events) {
133
+ let sessionId;
134
+ let resultPayload = null;
135
+ let turnCount = 0;
136
+ for (const ev of events) {
137
+ if (ev.kind === 'session-started')
138
+ sessionId = ev.sessionId;
139
+ else if (ev.kind === 'result') {
140
+ resultPayload = ev.payload;
141
+ turnCount += 1;
142
+ }
143
+ }
144
+ if (!resultPayload) {
145
+ return { session_id: sessionId };
146
+ }
147
+ const stats = resultPayload.stats;
148
+ return {
149
+ tokens_in: stats?.input_tokens,
150
+ tokens_out: stats?.output_tokens,
151
+ // Gemini reports a single `cached` read tier; map it to cache_read. No
152
+ // separate cache-creation tier — `cached` is counted as a subset of
153
+ // input_tokens (consistent with codex `cached_input_tokens`), so pricing.ts
154
+ // must not double-count.
155
+ tokens_cache_read: stats?.cached,
156
+ tokens_cache_create: undefined,
157
+ // total_cost_usd intentionally absent — estimated via pricing.ts.
158
+ num_turns: turnCount || 1,
159
+ // Stream events do not carry the model; the manager wrapper stamps the
160
+ // requested model on the row.
161
+ model: undefined,
162
+ duration_ms: typeof stats?.duration_ms === 'number' ? stats.duration_ms : undefined,
163
+ duration_api_ms: undefined,
164
+ session_id: sessionId,
165
+ };
166
+ }
167
+ function compareSemver(a, b) {
168
+ const aParts = a.split('.').map((n) => parseInt(n, 10));
169
+ const bParts = b.split('.').map((n) => parseInt(n, 10));
170
+ for (let i = 0; i < 3; i++) {
171
+ const av = aParts[i] ?? 0;
172
+ const bv = bParts[i] ?? 0;
173
+ if (av > bv)
174
+ return 1;
175
+ if (av < bv)
176
+ return -1;
177
+ }
178
+ return 0;
179
+ }
180
+ async function detectGeminiInstalled() {
181
+ try {
182
+ (0, child_process_1.execSync)(`${WHICH_CMD} gemini`, { stdio: 'ignore' });
183
+ }
184
+ catch {
185
+ return { installed: false, executable: false };
186
+ }
187
+ try {
188
+ const raw = (0, child_process_1.execSync)('gemini --version', {
189
+ encoding: 'utf-8',
190
+ stdio: ['pipe', 'pipe', 'ignore'],
191
+ timeout: 3000,
192
+ }).trim();
193
+ const match = raw.match(/\d+\.\d+\.\d+/);
194
+ const version = match ? match[0] : raw;
195
+ const meetsMinimum = match ? compareSemver(version, GEMINI_MIN_VERSION) >= 0 : false;
196
+ const result = {
197
+ installed: true,
198
+ executable: true,
199
+ version,
200
+ meetsMinimum,
201
+ };
202
+ if (!meetsMinimum) {
203
+ result.error = `gemini ${version} is older than required ${GEMINI_MIN_VERSION}. Upgrade with: npm i -g @google/gemini-cli (or see https://github.com/google-gemini/gemini-cli).`;
204
+ }
205
+ return result;
206
+ }
207
+ catch {
208
+ return { installed: true, executable: false };
209
+ }
210
+ }
211
+ exports.geminiAdapter = {
212
+ id: 'gemini',
213
+ displayName: 'Gemini CLI',
214
+ binary: 'gemini',
215
+ minCliVersion: GEMINI_MIN_VERSION,
216
+ projectDirName: '.gemini',
217
+ instructionsFilename: 'GEMINI.md',
218
+ mcpRegistration: 'project-json',
219
+ capabilities: {
220
+ nativeResume: true,
221
+ nativeStreamJson: true,
222
+ nativeCostUsd: false,
223
+ nativeOtelEnv: true,
224
+ profileEnvSupport: true,
225
+ systemPromptArg: false,
226
+ },
227
+ modelCatalog: () => GEMINI_MODELS,
228
+ defaultModel: () => 'gemini-3.5-flash',
229
+ buildArgs: buildGeminiArgs,
230
+ parseStreamLine: parseGeminiStreamLine,
231
+ extractResult: extractGeminiResult,
232
+ baselineAgents: () => ['sr-architect', 'sr-developer', 'sr-reviewer'],
233
+ detectInstalled: detectGeminiInstalled,
234
+ };
@@ -7,14 +7,17 @@
7
7
  //
8
8
  // Spec: openspec/specs/multi-provider-architecture/spec.md
9
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.UnknownProviderError = exports.codexAdapter = exports.claudeAdapter = exports.listAdapters = exports.hasAdapter = exports.getAdapter = void 0;
10
+ exports.UnknownProviderError = exports.geminiAdapter = exports.codexAdapter = exports.claudeAdapter = exports.listAdapters = exports.hasAdapter = exports.getAdapter = void 0;
11
11
  const registry_1 = require("./registry");
12
12
  const claude_adapter_1 = require("./claude-adapter");
13
13
  Object.defineProperty(exports, "claudeAdapter", { enumerable: true, get: function () { return claude_adapter_1.claudeAdapter; } });
14
14
  const codex_adapter_1 = require("./codex-adapter");
15
15
  Object.defineProperty(exports, "codexAdapter", { enumerable: true, get: function () { return codex_adapter_1.codexAdapter; } });
16
+ const gemini_adapter_1 = require("./gemini-adapter");
17
+ Object.defineProperty(exports, "geminiAdapter", { enumerable: true, get: function () { return gemini_adapter_1.geminiAdapter; } });
16
18
  (0, registry_1.register)(claude_adapter_1.claudeAdapter);
17
19
  (0, registry_1.register)(codex_adapter_1.codexAdapter);
20
+ (0, registry_1.register)(gemini_adapter_1.geminiAdapter);
18
21
  var registry_2 = require("./registry");
19
22
  Object.defineProperty(exports, "getAdapter", { enumerable: true, get: function () { return registry_2.getAdapter; } });
20
23
  Object.defineProperty(exports, "hasAdapter", { enumerable: true, get: function () { return registry_2.hasAdapter; } });
@@ -456,8 +456,14 @@ function computeSummary(projectPath, tier, provider = 'claude') {
456
456
  }
457
457
  }
458
458
  else {
459
- // Claude layout (unchanged).
460
- const dir = SPECRAILS_DIR;
459
+ // Claude / Gemini layout: agents at `<dir>/agents/sr-*.md`, slash commands
460
+ // at `<dir>/commands/{specrails,opsx}/*.<ext>`. Gemini installs into
461
+ // `.gemini/` and its commands are TOML (`.gemini/commands/specrails/*.toml`);
462
+ // claude installs into `.claude/` with Markdown commands. Without the
463
+ // per-provider dir + extension below, a gemini install summarised 0/0/0
464
+ // because it probed `.claude/` for `.md` files that don't exist.
465
+ const dir = provider === 'gemini' ? '.gemini' : SPECRAILS_DIR;
466
+ const commandExt = provider === 'gemini' ? '.toml' : '.md';
461
467
  const agentsDir = (0, path_1.join)(projectPath, dir, 'agents');
462
468
  if ((0, fs_1.existsSync)(agentsDir)) {
463
469
  const files = (0, fs_1.readdirSync)(agentsDir);
@@ -470,10 +476,10 @@ function computeSummary(projectPath, tier, provider = 'claude') {
470
476
  const commandsDirSpecrails = (0, path_1.join)(projectPath, dir, 'commands', 'specrails');
471
477
  const commandsDirOpsx = (0, path_1.join)(projectPath, dir, 'commands', 'opsx');
472
478
  if ((0, fs_1.existsSync)(commandsDirSpecrails)) {
473
- specrailsCommands = (0, fs_1.readdirSync)(commandsDirSpecrails).filter((f) => f.endsWith('.md')).length;
479
+ specrailsCommands = (0, fs_1.readdirSync)(commandsDirSpecrails).filter((f) => f.endsWith(commandExt)).length;
474
480
  }
475
481
  if ((0, fs_1.existsSync)(commandsDirOpsx)) {
476
- opsxCommands = (0, fs_1.readdirSync)(commandsDirOpsx).filter((f) => f.endsWith('.md')).length;
482
+ opsxCommands = (0, fs_1.readdirSync)(commandsDirOpsx).filter((f) => f.endsWith(commandExt)).length;
477
483
  }
478
484
  }
479
485
  }
@@ -604,7 +610,7 @@ class SetupManager {
604
610
  try {
605
611
  const text = (0, fs_1.readFileSync)(configPath, 'utf-8');
606
612
  const m = text.match(/^provider:\s*(\w+)/m);
607
- if (m && (m[1] === 'claude' || m[1] === 'codex')) {
613
+ if (m && m[1] && (0, providers_1.hasAdapter)(m[1])) {
608
614
  this._projectProviders.set(projectId, m[1]);
609
615
  }
610
616
  }
@@ -1153,8 +1159,8 @@ class SetupManager {
1153
1159
  try {
1154
1160
  const text = (0, fs_1.readFileSync)((0, path_1.join)(projectPath, '.specrails', 'install-config.yaml'), 'utf-8');
1155
1161
  const m = text.match(/^provider:\s*(\w+)/m);
1156
- if (m && m[1] === 'codex')
1157
- provider = 'codex';
1162
+ if (m && m[1] && (0, providers_1.hasAdapter)(m[1]))
1163
+ provider = m[1];
1158
1164
  }
1159
1165
  catch {
1160
1166
  // Missing install-config — stay on claude default.
@@ -332,6 +332,8 @@ function providerInstallUrl(id) {
332
332
  return 'https://claude.com/download';
333
333
  case 'codex':
334
334
  return 'https://developers.openai.com/codex';
335
+ case 'gemini':
336
+ return 'https://github.com/google-gemini/gemini-cli';
335
337
  default:
336
338
  return 'https://github.com';
337
339
  }
@@ -346,6 +348,8 @@ function providerInstallHint(id, platform) {
346
348
  : platform === 'win32'
347
349
  ? 'Install Codex CLI from https://developers.openai.com/codex, authenticate with `codex login`, then restart Specrails.'
348
350
  : 'Install Codex CLI from https://developers.openai.com/codex (or `pipx install codex-cli`), authenticate with `codex login`, then restart Specrails.';
351
+ case 'gemini':
352
+ return 'Install Gemini CLI via `npm i -g @google/gemini-cli` (or see https://github.com/google-gemini/gemini-cli), set GEMINI_API_KEY, then restart Specrails.';
349
353
  default:
350
354
  return `Install the ${id} CLI and restart Specrails.`;
351
355
  }