@open-document/core 0.14.3 → 0.15.1
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/dist/{build-4K9V8ysT.js → build-CBMroMqd.js} +1 -1
- package/dist/{check-B40JlWME.js → check-C2kIZr3f.js} +3 -3
- package/dist/cli/bin.js +9 -9
- package/dist/{context-Clm_nmr1.js → context-DGp1jwN5.js} +1 -1
- package/dist/{dev-De3pLYn_.js → dev-DmzGncKf.js} +1 -1
- package/dist/{diff-nU9ybiMk.js → diff-CMI_PVzz.js} +2 -2
- package/dist/{export-B9rrNBx2.js → export-BQMUBoBB.js} +3 -3
- package/dist/{import-C3542Wry.js → import-CiSRqZyo.js} +3 -3
- package/dist/ops/index.js +2 -2
- package/dist/{ops-ByJnGyuE.js → ops-DQbZmYRF.js} +1 -1
- package/dist/{preview-id9mj3IU.js → preview-CERhZ_FX.js} +1 -1
- package/dist/{session-CdkoJhi1.js → session-DdaKKd7_.js} +1007 -4
- package/dist/{templates-UJ_v7H-a.js → templates-CBeC-v7e.js} +3 -3
- package/dist/vite/index.js +1 -1
- package/package.json +1 -1
- package/skills/doc-authoring/SKILL.md +14 -62
- package/skills/doc-authoring/references/diagrams.md +32 -0
- package/skills/doc-authoring/references/runtime.md +15 -0
- package/src/agent/consent.ts +42 -0
- package/src/agent/provider.ts +24 -1
- package/src/agent/providers/antigravity-local.ts +193 -0
- package/src/agent/providers/antigravity.ts +656 -0
- package/src/agent/providers/index.ts +2 -1
- package/src/agent/runner.ts +4 -0
- package/src/agent/sandbox-sync.ts +178 -0
- package/src/agent/status.ts +33 -1
- package/src/agent/types.ts +21 -3
- package/src/app/components/agent/agent-panel.tsx +180 -42
- package/src/app/components/agent/connect-view.tsx +294 -26
- package/src/app/components/agent/provider-logo.tsx +4 -0
- package/src/app/lib/agent/use-agent.ts +14 -1
- package/src/app/lib/i18n-ja/agent-panel.ts +49 -0
- package/src/app/lib/i18n-ko/agent-panel.ts +48 -0
- package/src/app/lib/i18n-zh-cn/agent-panel.ts +46 -0
- package/src/app/lib/i18n-zh-tw/agent-panel.ts +46 -0
- package/src/app/lib/use-locale.ts +43 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { l as createFromTemplate, u as listTemplates } from "./session-
|
|
2
|
-
import "./ops-
|
|
3
|
-
import { t as cliContext } from "./context-
|
|
1
|
+
import { l as createFromTemplate, u as listTemplates } from "./session-DdaKKd7_.js";
|
|
2
|
+
import "./ops-DQbZmYRF.js";
|
|
3
|
+
import { t as cliContext } from "./context-DGp1jwN5.js";
|
|
4
4
|
import chalk from "chalk";
|
|
5
5
|
//#region src/cli/templates.ts
|
|
6
6
|
/**
|
package/dist/vite/index.js
CHANGED
package/package.json
CHANGED
|
@@ -22,6 +22,8 @@ Read the matching reference **before** using a primitive:
|
|
|
22
22
|
| Tables, stat rows, `<Chart>`, `<Sparkline>`, `<Callout>` | rendering data or callouts | `references/tables-and-charts.md` |
|
|
23
23
|
| Assets + `<ImagePlaceholder>` | importing images or leaving a placeholder | `references/assets.md` |
|
|
24
24
|
| Footnotes, `<Figure>`, `<Ref>`, `<DataTable>`, `<Cite>`, `<Bibliography>`, `<CodeBlock>` | notes, figures, cross-references, citations, code blocks, or `.csv` | `references/long-form.md` |
|
|
25
|
+
| `<Diagram>` and `.mmd` diagrams | drawing a flow, architecture, or sequence | `references/diagrams.md` |
|
|
26
|
+
| Exports, `open-doc diff`, Word output, Inspect mode, Design panel | telling the user what they can do next, or an export / review step | `references/runtime.md` |
|
|
25
27
|
|
|
26
28
|
## Themes
|
|
27
29
|
|
|
@@ -145,59 +147,19 @@ Bare elements on the sheet start from a base drawn from the design, not from a b
|
|
|
145
147
|
|
|
146
148
|
## Footnotes, numbering, and data
|
|
147
149
|
|
|
148
|
-
|
|
149
|
-
contents list does. Read
|
|
150
|
-
|
|
151
|
-
- **`<Footnote>`** — numbered by position, printed at the foot of
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
- **`<
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
- **`<Ref to="id" />`** — "Figure 3", plus the page when the target is elsewhere.
|
|
158
|
-
- **`<Cite id="…" source="…" />` & `<Bibliography />`** — academic/report citations numbered in order of first appearance (`[1]`), deduplicated by `id`, and listed by `<Bibliography />`.
|
|
159
|
-
- **`<DataTable rows={…} splittable summaryRow>`** — a print-shaped table from an imported `.csv` (supports automatic multi-page splitting with repeated headers when `splittable` is set, plus `summaryRow`, `dataBar`, `'currency'`, and `'delta'` formats).
|
|
160
|
-
- **`<CodeBlock code={…} lang="ts" lineNumbers highlightLines={[…]} caption="…" />`** — zero-dependency syntax-highlighted code block with optional line numbers, highlighted lines, and figure numbering when given `caption`.
|
|
161
|
-
- **`<Callout type="note|tip|warning|danger" title="…">`** — semantic callout box styled with `--od-*` tokens.
|
|
162
|
-
- **`<Diagram chart={…} caption>`** — an architecture, flow, or sequence drawing from an imported `.mmd`. Given a caption it numbers as a figure, like `<Figure>`.
|
|
163
|
-
- **`<Chart data x y caption>` & `<Sparkline data={…} />`** — `bar`, `horizontal-bar`, `line`, `area`, or `pie` charts from rows, plus inline SVG `<Sparkline>` for tables and stat cards. See `references/tables-and-charts.md`.
|
|
150
|
+
These primitives resolve themselves from the rendered pages, the same way the
|
|
151
|
+
contents list does. Read the reference in brackets before using one.
|
|
152
|
+
|
|
153
|
+
- **`<Footnote>`** — numbered by position, printed at the foot of its page, its height taken out of that page's budget. On a fixed page, add `<Footnotes />` where they print. (`long-form.md`)
|
|
154
|
+
- **`<Figure caption id>`**, **`<Ref to="id" />`**, `<ListOfFigures />` / `<ListOfTables />` — numbered figures and tables, and references to them with the page. (`long-form.md`)
|
|
155
|
+
- **`<Cite id source />`** & **`<Bibliography />`** — citations numbered by first appearance. (`long-form.md`)
|
|
156
|
+
- **`<DataTable rows>`** from an imported `.csv`, splittable across pages; **`<CodeBlock code lang>`** with line numbers and highlights. (`long-form.md`)
|
|
157
|
+
- **`<Chart>`**, **`<Sparkline>`**, **`<Callout type>`** — charts from rows and semantic callouts. (`tables-and-charts.md`)
|
|
158
|
+
- **`<Diagram chart caption>`** — flowcharts and sequence diagrams written as `.mmd` text, compiled to SVG in the document's own ink. Never use an image of a diagram that can be written. (`diagrams.md`)
|
|
164
159
|
|
|
165
160
|
`meta.labels` sets what they are called (`圖`, `表`) — the numbering itself is
|
|
166
161
|
structural.
|
|
167
162
|
|
|
168
|
-
## Diagrams
|
|
169
|
-
|
|
170
|
-
Write the drawing as Mermaid-flavoured text in `docs/<id>/<name>.mmd`, import
|
|
171
|
-
it, and hand it to `<Diagram>`:
|
|
172
|
-
|
|
173
|
-
```mermaid
|
|
174
|
-
%% docs/my-doc/architecture.mmd
|
|
175
|
-
flowchart TD
|
|
176
|
-
Client[使用者] -->|HTTPS| Gate{驗證}
|
|
177
|
-
Gate -->|通過| App[應用伺服器]
|
|
178
|
-
Gate -.->|拒絕| Deny([401])
|
|
179
|
-
App --> DB[資料庫]
|
|
180
|
-
```
|
|
181
|
-
|
|
182
|
-
```tsx
|
|
183
|
-
import { Diagram } from '@open-document/core';
|
|
184
|
-
import architecture from './architecture.mmd';
|
|
185
|
-
|
|
186
|
-
<Diagram chart={architecture} caption="請求路徑" width={420} />
|
|
187
|
-
```
|
|
188
|
-
|
|
189
|
-
It is compiled to SVG at build time and drawn with the document's own theme
|
|
190
|
-
variables, so it prints with the same ink and faces as the prose around it.
|
|
191
|
-
Never reach for an image of a diagram when the diagram can be written.
|
|
192
|
-
|
|
193
|
-
Supported:
|
|
194
|
-
- `flowchart`/`graph` with `TD` or `LR`; nodes as `A[box]`, `A(round)`, `A([stadium])`, `A[(database)]`, `A{decision}`, `A((circle))`; links `-->`, `---`, `-.->`, `==>` with optional `|labels|`; chains `A --> B --> C`; `subgraph id [Title] ... end` clusters; `%%` comments. A link back to an earlier step is drawn round the side, clear of the steps in between.
|
|
195
|
-
- `sequenceDiagram` with `participant Id as Label`, message arrows (`->>`, `-->>`, `->`, `-->`), and `Note over A,B: text` (or `Note left of` / `Note right of`).
|
|
196
|
-
- Anything else in Mermaid's syntax is not supported, and a bad diagram fails the build with the line to fix.
|
|
197
|
-
|
|
198
|
-
Keep `width` inside the text block: a drawing wider than the column is a layout
|
|
199
|
-
fault, and `open-doc check` reports it as one.
|
|
200
|
-
|
|
201
163
|
## Table of contents
|
|
202
164
|
|
|
203
165
|
```tsx
|
|
@@ -356,19 +318,9 @@ A document is not a slide deck. Long-form copy is the point — but it still has
|
|
|
356
318
|
- Cite numbers with their source and date inline (`Q3 billing export, 2026-08-01`) — a report that can't be traced gets ignored.
|
|
357
319
|
- Don't invent data. If a number must come from the user, leave `<ImagePlaceholder>` for a chart or an explicit `TODO:` marker in the copy and tell them at hand-off.
|
|
358
320
|
|
|
359
|
-
##
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
- Document view: vertical scroll of real-size pages, a left rail that switches between page thumbnails, the outline, and the document's assets, zoom (actual size / fit width / fit page), page counter, and fullscreen reading (`F`).
|
|
363
|
-
- Export PDF (print pipeline, correct `@page` size) and export HTML (self-contained, printable).
|
|
364
|
-
- Hot reload: edit `index.tsx` and the pages update live.
|
|
365
|
-
- **Assets panel** (`/assets` in the dev UI): upload, rename, and delete files in the global `assets/` folder or any document's `assets/` folder, with an "unused" badge and a copy-ready import line. Files you reference in source are what it scans, so an import you write by hand shows up there immediately.
|
|
366
|
-
- **Inspect mode** (the "Inspect" button, dev only): click any element on a page to edit its text in place — the change is written straight back into `docs/<id>/index.tsx` — or leave a note for the agent, which is stored as a `@doc-comment` marker and processed by the `apply-comments` skill.
|
|
367
|
-
- **Download menu** — PDF (true page size) and self-contained HTML.
|
|
368
|
-
- **Headless render** — `open-doc export <id> --format pdf|html|png|docx` produces the same output from a script, and `open-doc check <id>` reports layout faults. Both drive the real viewer in a headless browser, so what they produce is what the Download menu produces. A PDF exported this way also carries the outline as bookmarks and is tagged for screen readers — the same headings the sidebar and `<TableOfContents />` list, so a heading marked `data-od-outline="skip"` stays out and `data-od-heading` sets the bookmark's text. (The Download menu prints through the browser's dialog, which writes no bookmarks.)
|
|
369
|
-
- **What changed** — `open-doc diff <id> [--since <rev>]` (MCP: `diff_document`) renders the document as it is and as it was at a git revision (default `HEAD`), pairs the pages by content, and lists each page as same, changed, added or removed, with the lines of text that moved. It also writes `out/<id>-diff.html`, a self-contained before/after report with the changed regions outlined — hand that to a reviewer. Run it before handing back an edit, so your summary of what changed is what actually changed on the page.
|
|
370
|
-
- **Word (DOCX)** — for review that runs in Word. It carries structure, not page breaks: headings become Word heading styles, `<TableOfContents />` a TOC field, `<Footnote>` real footnotes, a `flow()` header and footer a Word header and footer with page-number fields, and the theme's CJK font the East Asian font. Write headings as real `h1`–`h3` and tables as `<table>`/`<DataTable>` so they arrive as structure; anything drawn with boxes (a chart made of `div`s) arrives as a picture, and absolutely positioned layouts on fixed pages flow as plain paragraphs.
|
|
371
|
-
- **Design panel** (the "Design" button in the document view, dev only): live-tweaks the `design` const — palette, fonts, type scale, margin, leading, radius — previewing on the real pages and writing the values back into `docs/<id>/index.tsx` on save.
|
|
321
|
+
## Writing for the viewer's editors
|
|
322
|
+
|
|
323
|
+
The viewer, exports, `open-doc check` / `export` / `diff`, the Inspect mode and the Design panel come with the framework — `references/runtime.md` lists what each does. Two of them edit your source, so write it in the shape they can read.
|
|
372
324
|
|
|
373
325
|
### Writing for the inspector
|
|
374
326
|
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Diagrams
|
|
2
|
+
|
|
3
|
+
Write the drawing as Mermaid-flavoured text in `docs/<id>/<name>.mmd`, import
|
|
4
|
+
it, and hand it to `<Diagram>`:
|
|
5
|
+
|
|
6
|
+
```mermaid
|
|
7
|
+
%% docs/my-doc/architecture.mmd
|
|
8
|
+
flowchart TD
|
|
9
|
+
Client[使用者] -->|HTTPS| Gate{驗證}
|
|
10
|
+
Gate -->|通過| App[應用伺服器]
|
|
11
|
+
Gate -.->|拒絕| Deny([401])
|
|
12
|
+
App --> DB[資料庫]
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
```tsx
|
|
16
|
+
import { Diagram } from '@open-document/core';
|
|
17
|
+
import architecture from './architecture.mmd';
|
|
18
|
+
|
|
19
|
+
<Diagram chart={architecture} caption="請求路徑" width={420} />
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
It is compiled to SVG at build time and drawn with the document's own theme
|
|
23
|
+
variables, so it prints with the same ink and faces as the prose around it.
|
|
24
|
+
Never reach for an image of a diagram when the diagram can be written.
|
|
25
|
+
|
|
26
|
+
Supported:
|
|
27
|
+
- `flowchart`/`graph` with `TD` or `LR`; nodes as `A[box]`, `A(round)`, `A([stadium])`, `A[(database)]`, `A{decision}`, `A((circle))`; links `-->`, `---`, `-.->`, `==>` with optional `|labels|`; chains `A --> B --> C`; `subgraph id [Title] ... end` clusters; `%%` comments. A link back to an earlier step is drawn round the side, clear of the steps in between.
|
|
28
|
+
- `sequenceDiagram` with `participant Id as Label`, message arrows (`->>`, `-->>`, `->`, `-->`), and `Note over A,B: text` (or `Note left of` / `Note right of`).
|
|
29
|
+
- Anything else in Mermaid's syntax is not supported, and a bad diagram fails the build with the line to fix.
|
|
30
|
+
|
|
31
|
+
Keep `width` inside the text block: a drawing wider than the column is a layout
|
|
32
|
+
fault, and `open-doc check` reports it as one.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Runtime behavior you get for free
|
|
2
|
+
|
|
3
|
+
What the framework and its viewer already do, so a document never re-implements it.
|
|
4
|
+
|
|
5
|
+
- Home page lists every folder under `docs/` with a live thumbnail of page 1.
|
|
6
|
+
- Document view: vertical scroll of real-size pages, a left rail that switches between page thumbnails, the outline, and the document's assets, zoom (actual size / fit width / fit page), page counter, and fullscreen reading (`F`).
|
|
7
|
+
- Export PDF (print pipeline, correct `@page` size) and export HTML (self-contained, printable).
|
|
8
|
+
- Hot reload: edit `index.tsx` and the pages update live.
|
|
9
|
+
- **Assets panel** (`/assets` in the dev UI): upload, rename, and delete files in the global `assets/` folder or any document's `assets/` folder, with an "unused" badge and a copy-ready import line. Files you reference in source are what it scans, so an import you write by hand shows up there immediately.
|
|
10
|
+
- **Inspect mode** (the "Inspect" button, dev only): click any element on a page to edit its text in place — the change is written straight back into `docs/<id>/index.tsx` — or leave a note for the agent, which is stored as a `@doc-comment` marker and processed by the `apply-comments` skill.
|
|
11
|
+
- **Download menu** — PDF (true page size) and self-contained HTML.
|
|
12
|
+
- **Headless render** — `open-doc export <id> --format pdf|html|png|docx` produces the same output from a script, and `open-doc check <id>` reports layout faults. Both drive the real viewer in a headless browser, so what they produce is what the Download menu produces. A PDF exported this way also carries the outline as bookmarks and is tagged for screen readers — the same headings the sidebar and `<TableOfContents />` list, so a heading marked `data-od-outline="skip"` stays out and `data-od-heading` sets the bookmark's text. (The Download menu prints through the browser's dialog, which writes no bookmarks.)
|
|
13
|
+
- **What changed** — `open-doc diff <id> [--since <rev>]` (MCP: `diff_document`) renders the document as it is and as it was at a git revision (default `HEAD`), pairs the pages by content, and lists each page as same, changed, added or removed, with the lines of text that moved. It also writes `out/<id>-diff.html`, a self-contained before/after report with the changed regions outlined — hand that to a reviewer. Run it before handing back an edit, so your summary of what changed is what actually changed on the page.
|
|
14
|
+
- **Word (DOCX)** — for review that runs in Word. It carries structure, not page breaks: headings become Word heading styles, `<TableOfContents />` a TOC field, `<Footnote>` real footnotes, a `flow()` header and footer a Word header and footer with page-number fields, and the theme's CJK font the East Asian font. Write headings as real `h1`–`h3` and tables as `<table>`/`<DataTable>` so they arrive as structure; anything drawn with boxes (a chart made of `div`s) arrives as a picture, and absolutely positioned layouts on fixed pages flow as plain paragraphs.
|
|
15
|
+
- **Design panel** (the "Design" button in the document view, dev only): live-tweaks the `design` const — palette, fonts, type scale, margin, leading, radius — previewing on the real pages and writing the values back into `docs/<id>/index.tsx` on save.
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import type { AgentProviderId } from './types.ts';
|
|
4
|
+
|
|
5
|
+
type ConsentRecord = { version: string; acceptedAt: string };
|
|
6
|
+
type ConsentFile = Partial<Record<AgentProviderId, ConsentRecord>>;
|
|
7
|
+
|
|
8
|
+
export function consentFile(userCwd: string): string {
|
|
9
|
+
return path.join(userCwd, 'node_modules', '.open-doc', 'agent-consent.json');
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
async function readAll(userCwd: string): Promise<ConsentFile> {
|
|
13
|
+
try {
|
|
14
|
+
const raw = JSON.parse(await fs.readFile(consentFile(userCwd), 'utf8'));
|
|
15
|
+
return raw && typeof raw === 'object' ? (raw as ConsentFile) : {};
|
|
16
|
+
} catch {
|
|
17
|
+
return {};
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Acceptance is kept by the dev server, not the browser, so the provider can
|
|
22
|
+
// refuse a turn itself rather than trusting the panel to have asked.
|
|
23
|
+
export async function hasConsent(
|
|
24
|
+
userCwd: string,
|
|
25
|
+
provider: AgentProviderId,
|
|
26
|
+
version: string,
|
|
27
|
+
): Promise<boolean> {
|
|
28
|
+
return (await readAll(userCwd))[provider]?.version === version;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function setConsent(
|
|
32
|
+
userCwd: string,
|
|
33
|
+
provider: AgentProviderId,
|
|
34
|
+
version: string | null,
|
|
35
|
+
): Promise<void> {
|
|
36
|
+
const all = await readAll(userCwd);
|
|
37
|
+
if (version) all[provider] = { version, acceptedAt: new Date().toISOString() };
|
|
38
|
+
else delete all[provider];
|
|
39
|
+
const file = consentFile(userCwd);
|
|
40
|
+
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
41
|
+
await fs.writeFile(file, `${JSON.stringify(all, null, 2)}\n`);
|
|
42
|
+
}
|
package/src/agent/provider.ts
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
|
-
import type {
|
|
2
|
+
import type {
|
|
3
|
+
AgentEffort,
|
|
4
|
+
AgentModelOption,
|
|
5
|
+
AgentProviderAuth,
|
|
6
|
+
AgentProviderId,
|
|
7
|
+
AgentQuestion,
|
|
8
|
+
AgentRuntime,
|
|
9
|
+
} from './types.ts';
|
|
3
10
|
|
|
4
11
|
export type ProviderEvent =
|
|
5
12
|
| { type: 'session-id'; id: string }
|
|
@@ -20,6 +27,9 @@ export type PermissionRequest = { tool: string; title: string; detail: string |
|
|
|
20
27
|
|
|
21
28
|
export type ProviderRunOptions = {
|
|
22
29
|
cwd: string;
|
|
30
|
+
docsDir: string;
|
|
31
|
+
// The open document's folder; null when the turn has no document.
|
|
32
|
+
docDir: string | null;
|
|
23
33
|
// Directories the agent may write to without asking: the deck and asset
|
|
24
34
|
// folders. Edits anywhere else (configs, package.json) need approval.
|
|
25
35
|
writableRoots: string[];
|
|
@@ -45,6 +55,19 @@ export interface AgentProvider {
|
|
|
45
55
|
// Whether the agent's own commands can start a browser. `open-doc check` and
|
|
46
56
|
// the page preview both drive Chromium, which Codex's macOS sandbox kills.
|
|
47
57
|
canOpenBrowser: boolean;
|
|
58
|
+
auth?: AgentProviderAuth;
|
|
59
|
+
preview?: boolean;
|
|
60
|
+
// Set when the user must accept terms before a turn runs; bump it when the
|
|
61
|
+
// terms change so everyone accepts the new text.
|
|
62
|
+
consentVersion?: string;
|
|
63
|
+
// For 'api-key' agents, which have no SDK to resolve.
|
|
64
|
+
hasKey?(cwd: string): Promise<boolean>;
|
|
65
|
+
// Where the agent's tools run, for agents that can run either in the cloud
|
|
66
|
+
// or on this machine once `install` has fetched what that needs.
|
|
67
|
+
runtime?(cwd: string): Promise<AgentRuntime>;
|
|
68
|
+
install?(cwd: string): Promise<void>;
|
|
69
|
+
// Stops anything the provider started that outlives a turn.
|
|
70
|
+
dispose?(): void;
|
|
48
71
|
models(): Promise<AgentModelOption[]>;
|
|
49
72
|
run(opts: ProviderRunOptions): Promise<void>;
|
|
50
73
|
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { type ChildProcess, spawn } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import fs from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { gunzipSync } from 'node:zlib';
|
|
6
|
+
import { readTar } from '../sandbox-sync.ts';
|
|
7
|
+
|
|
8
|
+
// Pinned, with the release's own checksums, so the binary that runs file tools
|
|
9
|
+
// on the user's machine is exactly the one Google published.
|
|
10
|
+
export const GEMINI_API_CLI_VERSION = '0.4.6';
|
|
11
|
+
const RELEASE = `https://github.com/google-gemini/gemini-api-cli/releases/download/v${GEMINI_API_CLI_VERSION}`;
|
|
12
|
+
const CHECKSUMS: Record<string, string> = {
|
|
13
|
+
'darwin-arm64': 'c80b5ec2d0a6feee0cf18943427cfdaf9aab7183b7f62f50b956cd2431b98018',
|
|
14
|
+
'darwin-x64': '009a83ea43b1cd25f87375efc01c9418c12fcd7ea779a26a483eb4e875da4a70',
|
|
15
|
+
'linux-arm64': '6bf48dc0b6479b157d4dc35d074d06286c2c6e2f09ff99236bde9829763576f7',
|
|
16
|
+
'linux-x64': '78862dde519d9b47a9fb70b1f0340d19fa1245934d65e83f0e2dbc1d17cd2fa6',
|
|
17
|
+
};
|
|
18
|
+
const ASSETS: Record<string, string> = {
|
|
19
|
+
'darwin-arm64': 'gemini-api_Darwin_arm64.tar.gz',
|
|
20
|
+
'darwin-x64': 'gemini-api_Darwin_x86_64.tar.gz',
|
|
21
|
+
'linux-arm64': 'gemini-api_Linux_arm64.tar.gz',
|
|
22
|
+
'linux-x64': 'gemini-api_Linux_x86_64.tar.gz',
|
|
23
|
+
};
|
|
24
|
+
const API_BASE = 'https://generativelanguage.googleapis.com/v1beta';
|
|
25
|
+
const READY_TIMEOUT_MS = 10_000;
|
|
26
|
+
|
|
27
|
+
function platformKey(): string {
|
|
28
|
+
return `${process.platform}-${process.arch}`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function localModeSupported(): boolean {
|
|
32
|
+
return platformKey() in ASSETS;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function stateDir(cwd: string): string {
|
|
36
|
+
return path.join(cwd, 'node_modules', '.open-doc');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function cliPath(cwd: string): string {
|
|
40
|
+
return path.join(stateDir(cwd), 'bin', 'gemini-api');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function versionFile(cwd: string): string {
|
|
44
|
+
return path.join(stateDir(cwd), 'bin', 'gemini-api.version');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function installedCliVersion(cwd: string): Promise<string | null> {
|
|
48
|
+
try {
|
|
49
|
+
await fs.access(cliPath(cwd));
|
|
50
|
+
return (await fs.readFile(versionFile(cwd), 'utf8')).trim() || null;
|
|
51
|
+
} catch {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
let installing: Promise<void> | null = null;
|
|
57
|
+
|
|
58
|
+
export function installCli(cwd: string): Promise<void> {
|
|
59
|
+
installing ??= (async () => {
|
|
60
|
+
const key = platformKey();
|
|
61
|
+
const asset = ASSETS[key];
|
|
62
|
+
if (!asset) throw new Error(`Local mode is not available on ${key} yet.`);
|
|
63
|
+
const res = await fetch(`${RELEASE}/${asset}`);
|
|
64
|
+
if (!res.ok) throw new Error(`Could not download the gemini-api CLI (${res.status}).`);
|
|
65
|
+
const archive = new Uint8Array(await res.arrayBuffer());
|
|
66
|
+
const digest = createHash('sha256').update(archive).digest('hex');
|
|
67
|
+
if (digest !== CHECKSUMS[key]) {
|
|
68
|
+
throw new Error('The downloaded gemini-api CLI failed its checksum; nothing was installed.');
|
|
69
|
+
}
|
|
70
|
+
const entry = readTar(gunzipSync(archive)).find(
|
|
71
|
+
(e) => path.posix.basename(e.path) === 'gemini-api',
|
|
72
|
+
);
|
|
73
|
+
if (!entry) throw new Error('The gemini-api archive did not contain the CLI.');
|
|
74
|
+
const target = cliPath(cwd);
|
|
75
|
+
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
76
|
+
const partial = `${target}.partial`;
|
|
77
|
+
await fs.writeFile(partial, entry.data, { mode: 0o755 });
|
|
78
|
+
await fs.rename(partial, target);
|
|
79
|
+
await fs.writeFile(versionFile(cwd), `${GEMINI_API_CLI_VERSION}\n`);
|
|
80
|
+
})().finally(() => {
|
|
81
|
+
installing = null;
|
|
82
|
+
});
|
|
83
|
+
return installing;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
type EnvironmentRecord = { id: string; environment_key: string };
|
|
87
|
+
|
|
88
|
+
function environmentFile(cwd: string): string {
|
|
89
|
+
return path.join(stateDir(cwd), 'antigravity-environment.json');
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function readEnvironment(cwd: string): Promise<EnvironmentRecord | null> {
|
|
93
|
+
try {
|
|
94
|
+
const raw = JSON.parse(await fs.readFile(environmentFile(cwd), 'utf8'));
|
|
95
|
+
return typeof raw?.id === 'string' && typeof raw?.environment_key === 'string' ? raw : null;
|
|
96
|
+
} catch {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// The environment key is shown once, at creation, and lets anyone holding it
|
|
102
|
+
// take this environment's tool calls; it is stored owner-only.
|
|
103
|
+
export async function ensureEnvironment(cwd: string, apiKey: string): Promise<EnvironmentRecord> {
|
|
104
|
+
const existing = await readEnvironment(cwd);
|
|
105
|
+
if (existing) return existing;
|
|
106
|
+
const res = await fetch(`${API_BASE}/environments`, {
|
|
107
|
+
method: 'POST',
|
|
108
|
+
headers: { 'x-goog-api-key': apiKey, 'content-type': 'application/json' },
|
|
109
|
+
body: JSON.stringify({ mode: 'self_hosted' }),
|
|
110
|
+
});
|
|
111
|
+
if (!res.ok) {
|
|
112
|
+
throw new Error(`Could not create a local environment (Gemini API ${res.status}).`);
|
|
113
|
+
}
|
|
114
|
+
const body = (await res.json()) as Partial<EnvironmentRecord>;
|
|
115
|
+
if (!body.id || !body.environment_key) {
|
|
116
|
+
throw new Error('The Gemini API returned an environment without a key.');
|
|
117
|
+
}
|
|
118
|
+
const record = { id: body.id, environment_key: body.environment_key };
|
|
119
|
+
await fs.mkdir(stateDir(cwd), { recursive: true });
|
|
120
|
+
await fs.writeFile(environmentFile(cwd), `${JSON.stringify(record, null, 2)}\n`, {
|
|
121
|
+
mode: 0o600,
|
|
122
|
+
});
|
|
123
|
+
return record;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export async function forgetEnvironment(cwd: string): Promise<void> {
|
|
127
|
+
stopWorker();
|
|
128
|
+
await fs.rm(environmentFile(cwd), { force: true });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
type Worker = { process: ChildProcess; key: string; ready: Promise<void>; log: string[] };
|
|
132
|
+
let worker: Worker | null = null;
|
|
133
|
+
|
|
134
|
+
export function stopWorker(): void {
|
|
135
|
+
worker?.process.kill();
|
|
136
|
+
worker = null;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
process.once('exit', stopWorker);
|
|
140
|
+
|
|
141
|
+
export function workerLog(): string {
|
|
142
|
+
return worker?.log.slice(-5).join('\n') ?? '';
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* One worker per dev server, rooted at the workspace so the agent finds the
|
|
147
|
+
* project skills. `--disable-bash` leaves it only the file tools, which the CLI
|
|
148
|
+
* confines to the root with os.Root, so a model can never run a command here.
|
|
149
|
+
* The project-wide API key is withheld; the worker only needs its environment key.
|
|
150
|
+
*/
|
|
151
|
+
export function ensureWorker(cwd: string, env: EnvironmentRecord): Promise<void> {
|
|
152
|
+
if (worker && worker.key === env.environment_key && worker.process.exitCode === null) {
|
|
153
|
+
return worker.ready;
|
|
154
|
+
}
|
|
155
|
+
stopWorker();
|
|
156
|
+
const { GEMINI_API_KEY: _withheld, ...rest } = process.env;
|
|
157
|
+
const child = spawn(
|
|
158
|
+
cliPath(cwd),
|
|
159
|
+
['environments', 'connect', '--root-dir', cwd, '--workdir', cwd, '--disable-bash'],
|
|
160
|
+
{
|
|
161
|
+
cwd,
|
|
162
|
+
env: { ...rest, GEMINI_ENVIRONMENT_KEY: env.environment_key },
|
|
163
|
+
stdio: ['ignore', 'ignore', 'pipe'],
|
|
164
|
+
},
|
|
165
|
+
);
|
|
166
|
+
const log: string[] = [];
|
|
167
|
+
const ready = new Promise<void>((resolve, reject) => {
|
|
168
|
+
const timer = setTimeout(resolve, READY_TIMEOUT_MS);
|
|
169
|
+
child.stderr?.setEncoding('utf8');
|
|
170
|
+
child.stderr?.on('data', (chunk: string) => {
|
|
171
|
+
for (const line of chunk.split('\n').filter(Boolean)) {
|
|
172
|
+
log.push(line);
|
|
173
|
+
if (log.length > 50) log.shift();
|
|
174
|
+
if (/polling/i.test(line)) {
|
|
175
|
+
clearTimeout(timer);
|
|
176
|
+
resolve();
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
child.once('error', (err) => {
|
|
181
|
+
clearTimeout(timer);
|
|
182
|
+
reject(err);
|
|
183
|
+
});
|
|
184
|
+
child.once('exit', (code) => {
|
|
185
|
+
clearTimeout(timer);
|
|
186
|
+
if (worker?.process === child) worker = null;
|
|
187
|
+
reject(new Error(`The local worker stopped (exit ${code}). ${log.slice(-3).join(' ')}`));
|
|
188
|
+
});
|
|
189
|
+
});
|
|
190
|
+
ready.catch(() => {});
|
|
191
|
+
worker = { process: child, key: env.environment_key, ready, log };
|
|
192
|
+
return ready;
|
|
193
|
+
}
|