offrouter-adapter-gemini 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/install.ts DELETED
@@ -1,483 +0,0 @@
1
- /**
2
- * Profile-scoped installer for Gemini personal profiles.
3
- *
4
- * Mirrors the Codex adapter's safety model but writes ONE MCP server entry
5
- * into the profile's JSON settings file (profile-scoped) at
6
- * <profileDir>/settings.json and records rollback metadata inside the target
7
- * profile (.offrouter/gemini-install-state.json).
8
- *
9
- * Gemini CLI settings.json uses native JSON (parsed with JSON, not ad hoc
10
- * string surgery). MCP servers live under the top-level `mcpServers` key.
11
- */
12
- import { access, mkdir, readFile, writeFile } from "node:fs/promises";
13
- import { constants } from "node:fs";
14
- import { createHash } from "node:crypto";
15
- import { dirname, join } from "node:path";
16
- import { homedir as osHomedir } from "node:os";
17
- import {
18
- ROUTE_PROTOCOL_VERSION,
19
- routeRequest,
20
- type OffRouterConfig,
21
- type PolicyDenialCode,
22
- type RouteRequest,
23
- } from "offrouter-core";
24
- import { z } from "zod";
25
- import {
26
- isGeminiHarnessProfile,
27
- isSafeProfileId,
28
- isWorkLikeProfile,
29
- resolveGeminiProfileDir,
30
- } from "./profile.js";
31
-
32
- export const GEMINI_INSTALL_STATE_REL =
33
- ".offrouter/gemini-install-state.json" as const;
34
-
35
- export const GEMINI_CONFIG_REL = "settings.json" as const;
36
-
37
- /** Key name and command/args for the OffRouter MCP server entry. */
38
- const OFFROUTER_MCP_SERVER_NAME = "offrouter";
39
- const OFFROUTER_MCP_SERVERS_KEY = "mcpServers";
40
- const OFFROUTER_MCP_COMMAND = "offrouter";
41
- const OFFROUTER_MCP_ARGS: readonly string[] = ["mcp", "serve"];
42
-
43
- export const GeminiInstallStateSchema = z.object({
44
- version: z.literal(1),
45
- profile: z.string().min(1),
46
- harness: z.literal("gemini"),
47
- installedAt: z.string().min(1),
48
- configRelative: z.literal(GEMINI_CONFIG_REL),
49
- files: z.record(
50
- z.string().min(1),
51
- z.object({
52
- previous: z.string().nullable(),
53
- hash: z.string().optional(),
54
- }),
55
- ),
56
- });
57
-
58
- export type GeminiInstallState = z.infer<typeof GeminiInstallStateSchema>;
59
-
60
- export type InstallChangeKind = "create" | "update" | "unchanged" | "remove";
61
-
62
- export interface InstallFileChange {
63
- path: string;
64
- relativePath: string;
65
- kind: InstallChangeKind;
66
- /** Diff-like summary line for human output. */
67
- summary: string;
68
- }
69
-
70
- export interface GeminiInstallOptions {
71
- profile: string;
72
- config: OffRouterConfig;
73
- env?: NodeJS.ProcessEnv;
74
- homedir?: () => string;
75
- dryRun?: boolean;
76
- }
77
-
78
- export interface GeminiInstallResult {
79
- ok: boolean;
80
- dryRun: boolean;
81
- profile: string;
82
- profileDir: string;
83
- changes: InstallFileChange[];
84
- message: string;
85
- errorCode?: PolicyDenialCode | "install_error";
86
- statePath?: string;
87
- }
88
-
89
- async function pathExists(path: string): Promise<boolean> {
90
- try {
91
- await access(path, constants.F_OK);
92
- return true;
93
- } catch {
94
- return false;
95
- }
96
- }
97
-
98
- function sha256(content: string): string {
99
- return createHash("sha256").update(content).digest("hex");
100
- }
101
-
102
- function changeSummary(kind: InstallChangeKind, relativePath: string): string {
103
- switch (kind) {
104
- case "create":
105
- return `+ ${relativePath}`;
106
- case "update":
107
- return `~ ${relativePath}`;
108
- case "unchanged":
109
- return `= ${relativePath}`;
110
- case "remove":
111
- return `- ${relativePath}`;
112
- default:
113
- return `? ${relativePath}`;
114
- }
115
- }
116
-
117
- /**
118
- * Produce the desired settings.json content for the OffRouter MCP entry
119
- * using a native JSON parser instead of ad hoc string surgery.
120
- *
121
- * - Missing/empty/invalid file => fresh config containing only the MCP entry.
122
- * - Existing file already has mcpServers.offrouter with matching
123
- * command/args => return the original bytes unchanged (idempotent).
124
- * - Existing file has a conflicting offrouter entry (or none) => set/replace
125
- * the entry and stringify, preserving all other unrelated keys.
126
- */
127
- export function patchConfigForMcp(existing: string | null): string {
128
- if (existing === null || existing.trim() === "") {
129
- return stringifyConfig(freshOffrouterConfig());
130
- }
131
-
132
- let root: Record<string, unknown>;
133
- try {
134
- const parsed = JSON.parse(existing);
135
- root = isJsonObject(parsed) ? parsed : {};
136
- } catch {
137
- // Invalid JSON: treat as empty so install can still add the entry.
138
- return stringifyConfig(freshOffrouterConfig());
139
- }
140
-
141
- const servers = isJsonObject(root[OFFROUTER_MCP_SERVERS_KEY])
142
- ? (root[OFFROUTER_MCP_SERVERS_KEY] as Record<string, unknown>)
143
- : undefined;
144
-
145
- if (
146
- servers !== undefined &&
147
- isOffrouterMcpEntry(servers[OFFROUTER_MCP_SERVER_NAME])
148
- ) {
149
- return existing;
150
- }
151
-
152
- const nextRoot: Record<string, unknown> = {
153
- ...root,
154
- [OFFROUTER_MCP_SERVERS_KEY]: {
155
- ...(servers ?? {}),
156
- [OFFROUTER_MCP_SERVER_NAME]: offrouterMcpEntry(),
157
- },
158
- };
159
- return stringifyConfig(nextRoot);
160
- }
161
-
162
- function stringifyConfig(root: Record<string, unknown>): string {
163
- return `${JSON.stringify(root, null, 2)}\n`;
164
- }
165
-
166
- function isJsonObject(value: unknown): value is Record<string, unknown> {
167
- return typeof value === "object" && value !== null && !Array.isArray(value);
168
- }
169
-
170
- /**
171
- * True when an existing mcpServers.offrouter entry already matches the
172
- * OffRouter command/args. Detects a correct prior install by value (not by
173
- * string equality) so a conflicting entry is overwritten.
174
- */
175
- function isOffrouterMcpEntry(value: unknown): boolean {
176
- if (!isJsonObject(value)) {
177
- return false;
178
- }
179
- if (value.command !== OFFROUTER_MCP_COMMAND) {
180
- return false;
181
- }
182
- const args = value.args;
183
- if (!Array.isArray(args) || args.length !== OFFROUTER_MCP_ARGS.length) {
184
- return false;
185
- }
186
- return args.every((item, index) => item === OFFROUTER_MCP_ARGS[index]);
187
- }
188
-
189
- function offrouterMcpEntry(): Record<string, unknown> {
190
- return {
191
- command: OFFROUTER_MCP_COMMAND,
192
- args: [...OFFROUTER_MCP_ARGS],
193
- };
194
- }
195
-
196
- function freshOffrouterConfig(): Record<string, unknown> {
197
- return {
198
- [OFFROUTER_MCP_SERVERS_KEY]: {
199
- [OFFROUTER_MCP_SERVER_NAME]: offrouterMcpEntry(),
200
- },
201
- };
202
- }
203
-
204
- function tinyPolicyProbeRequest(profile: string): RouteRequest {
205
- return {
206
- requestId: "install-policy-probe",
207
- protocolVersion: ROUTE_PROTOCOL_VERSION,
208
- harness: { kind: "gemini", profile },
209
- task: {
210
- promptPreview: "install policy probe",
211
- promptDigest: "sha256:install-policy-probe",
212
- kind: "other",
213
- risk: "low",
214
- },
215
- workspace: { cwd: "/tmp/offrouter-install-probe", trusted: true },
216
- constraints: {
217
- subscriptionFirst: true,
218
- allowApiKeyFallback: false,
219
- },
220
- };
221
- }
222
-
223
- /**
224
- * Use routeRequest with empty candidates so work/unallowlisted profile denials
225
- * reuse the same core policy codes users see from route explain / hooks.
226
- */
227
- export function evaluateInstallProfilePolicy(
228
- profile: string,
229
- config: OffRouterConfig,
230
- ): { allowed: boolean; errorCode?: PolicyDenialCode; message?: string } {
231
- const decision = routeRequest(
232
- tinyPolicyProbeRequest(profile),
233
- [],
234
- config.policy,
235
- );
236
- const denials = decision.policyDenials ?? [];
237
- const hard = denials.find(
238
- (d) =>
239
- d.code === "work_profile_denied" ||
240
- d.code === "profile_not_allowlisted" ||
241
- d.code === "privacy_label_denied",
242
- );
243
- if (hard) {
244
- return {
245
- allowed: false,
246
- errorCode: hard.code,
247
- message: hard.message,
248
- };
249
- }
250
- // Empty candidates also sets needsConfiguration + may include
251
- // profile_not_allowlisted even for personal unallowlisted. When allowlisted,
252
- // only needsConfiguration remains; that is fine for install.
253
- const profileDenial = denials.find((d) => d.target === "profile");
254
- if (profileDenial) {
255
- return {
256
- allowed: false,
257
- errorCode: profileDenial.code,
258
- message: profileDenial.message,
259
- };
260
- }
261
- if (!config.policy.allowlistedProfiles.includes(profile)) {
262
- return {
263
- allowed: false,
264
- errorCode: "profile_not_allowlisted",
265
- message: `Profile ${profile} is not allowlisted. Add it explicitly before installing or routing.`,
266
- };
267
- }
268
- return { allowed: true };
269
- }
270
-
271
- /**
272
- * Install the OffRouter Gemini MCP entry into a single profile directory.
273
- */
274
- export async function installGeminiProfile(
275
- options: GeminiInstallOptions,
276
- ): Promise<GeminiInstallResult> {
277
- const {
278
- profile,
279
- config,
280
- dryRun = false,
281
- env = process.env,
282
- homedir = osHomedir,
283
- } = options;
284
-
285
- if (!isSafeProfileId(profile)) {
286
- return {
287
- ok: false,
288
- dryRun,
289
- profile,
290
- profileDir: "",
291
- changes: [],
292
- message:
293
- "Unsafe profile id. Use letters, numbers, dots, underscores, and dashes only.",
294
- errorCode: "install_error",
295
- };
296
- }
297
-
298
- const profileDir = resolveGeminiProfileDir(profile, { env, homedir });
299
- const statePath = join(profileDir, GEMINI_INSTALL_STATE_REL);
300
- const configPath = join(profileDir, GEMINI_CONFIG_REL);
301
-
302
- if (!isGeminiHarnessProfile(profile)) {
303
- return {
304
- ok: false,
305
- dryRun,
306
- profile,
307
- profileDir,
308
- changes: [],
309
- message:
310
- "Gemini install supports only profile ids named gemini or starting with gemini-.",
311
- errorCode: "install_error",
312
- };
313
- }
314
-
315
- // Work-like profile ids (e.g. gemini-work, gemini-work-staging) are never
316
- // installable, even when allowlisted. This mirrors the filter used by
317
- // listAllowlistedPersonalGeminiProfiles so explicit and --all-personal
318
- // installs apply the same personal-only boundary.
319
- if (isWorkLikeProfile(profile)) {
320
- return {
321
- ok: false,
322
- dryRun,
323
- profile,
324
- profileDir,
325
- changes: [],
326
- message: `Profile ${profile} looks like a work profile and is never installable, even if allowlisted. Use a personal profile such as gemini-personal.`,
327
- errorCode: "work_profile_denied",
328
- };
329
- }
330
-
331
- const policy = evaluateInstallProfilePolicy(profile, config);
332
- if (!policy.allowed) {
333
- return {
334
- ok: false,
335
- dryRun,
336
- profile,
337
- profileDir,
338
- changes: [],
339
- message: policy.message ?? `Profile ${profile} is not installable.`,
340
- errorCode: policy.errorCode ?? "install_error",
341
- };
342
- }
343
-
344
- // Preserve original previous contents across re-installs (idempotent rollback).
345
- let priorState: GeminiInstallState | null = null;
346
- if (await pathExists(statePath)) {
347
- try {
348
- const raw = await readFile(statePath, "utf8");
349
- priorState = GeminiInstallStateSchema.parse(JSON.parse(raw));
350
- } catch (err) {
351
- const detail = err instanceof Error ? err.message : String(err);
352
- return {
353
- ok: false,
354
- dryRun,
355
- profile,
356
- profileDir,
357
- changes: [],
358
- message: `Invalid install state at ${statePath}: ${detail}`,
359
- errorCode: "install_error",
360
- };
361
- }
362
- }
363
-
364
- const changes: InstallFileChange[] = [];
365
-
366
- // --- settings.json MCP entry ---
367
- let current: string | null = null;
368
- if (await pathExists(configPath)) {
369
- current = await readFile(configPath, "utf8");
370
- }
371
-
372
- const priorFile = priorState?.files[GEMINI_CONFIG_REL];
373
- const previous = priorFile !== undefined ? priorFile.previous : current;
374
-
375
- const desired = patchConfigForMcp(current);
376
-
377
- let kind: InstallChangeKind;
378
- if (current === null) {
379
- kind = "create";
380
- } else if (current === desired) {
381
- kind = "unchanged";
382
- } else {
383
- kind = "update";
384
- }
385
-
386
- changes.push({
387
- path: configPath,
388
- relativePath: GEMINI_CONFIG_REL,
389
- kind,
390
- summary: changeSummary(kind, GEMINI_CONFIG_REL),
391
- });
392
-
393
- if (!dryRun && kind !== "unchanged") {
394
- await mkdir(dirname(configPath), { recursive: true });
395
- await writeFile(configPath, desired, "utf8");
396
- }
397
-
398
- // --- install state metadata ---
399
- const state: GeminiInstallState = {
400
- version: 1,
401
- profile,
402
- harness: "gemini",
403
- installedAt: priorState?.installedAt ?? new Date().toISOString(),
404
- configRelative: GEMINI_CONFIG_REL,
405
- files: {
406
- [GEMINI_CONFIG_REL]: {
407
- previous,
408
- hash: sha256(desired),
409
- },
410
- },
411
- };
412
-
413
- const stateJson = `${JSON.stringify(state, null, 2)}\n`;
414
- let stateKind: InstallChangeKind = "create";
415
- if (await pathExists(statePath)) {
416
- const existing = await readFile(statePath, "utf8");
417
- stateKind = existing === stateJson ? "unchanged" : "update";
418
- }
419
- changes.push({
420
- path: statePath,
421
- relativePath: GEMINI_INSTALL_STATE_REL,
422
- kind: stateKind,
423
- summary: changeSummary(stateKind, GEMINI_INSTALL_STATE_REL),
424
- });
425
-
426
- if (!dryRun && stateKind !== "unchanged") {
427
- await mkdir(dirname(statePath), { recursive: true });
428
- await writeFile(statePath, stateJson, "utf8");
429
- }
430
-
431
- const wrote = changes.filter(
432
- (c) => c.kind === "create" || c.kind === "update",
433
- );
434
- const message = dryRun
435
- ? `Dry run: would apply ${wrote.length} file change(s) for profile ${profile}.`
436
- : `Installed OffRouter Gemini MCP entry for profile ${profile} (${wrote.length} file change(s)).`;
437
-
438
- return {
439
- ok: true,
440
- dryRun,
441
- profile,
442
- profileDir,
443
- changes,
444
- message,
445
- statePath,
446
- };
447
- }
448
-
449
- /**
450
- * Human-readable diff-like text for an install/uninstall result matrix.
451
- */
452
- export function formatInstallDiffText(
453
- results: GeminiInstallResult[],
454
- headline?: string,
455
- ): string {
456
- const lines: string[] = [];
457
- if (headline) {
458
- lines.push(headline);
459
- }
460
- for (const result of results) {
461
- lines.push(``);
462
- lines.push(
463
- `## ${result.profile} (${result.ok ? (result.dryRun ? "dry-run" : "applied") : "error"})`,
464
- );
465
- lines.push(`profileDir: ${result.profileDir}`);
466
- if (!result.ok) {
467
- lines.push(`error: ${result.message}`);
468
- continue;
469
- }
470
- for (const change of result.changes) {
471
- if (change.kind === "unchanged") continue;
472
- lines.push(change.summary);
473
- }
474
- const unchanged = result.changes.filter(
475
- (c) => c.kind === "unchanged",
476
- ).length;
477
- if (unchanged > 0) {
478
- lines.push(`= ${unchanged} unchanged`);
479
- }
480
- lines.push(result.message);
481
- }
482
- return lines.join("\n").trimEnd() + "\n";
483
- }
package/src/profile.ts DELETED
@@ -1,99 +0,0 @@
1
- /**
2
- * Gemini profile directory resolution and allowlist helpers.
3
- *
4
- * Mirrors the Codex adapter's profile isolation model:
5
- * - env OFFROUTER_GEMINI_PROFILES_DIR set => <root>/<profile>
6
- * - profile === "gemini" => env GEMINI_HOME || ~/.gemini (bare global; only
7
- * mutable when explicitly allowlisted)
8
- * - otherwise => ~/.<profile> (e.g. gemini-personal => ~/.gemini-personal)
9
- */
10
- import { homedir as osHomedir } from "node:os";
11
- import { join, resolve } from "node:path";
12
- import type { OffRouterConfig } from "offrouter-core";
13
-
14
- export const SAFE_PROFILE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
15
-
16
- export function isSafeProfileId(profile: string): boolean {
17
- return SAFE_PROFILE_ID_RE.test(profile);
18
- }
19
-
20
- export interface ResolveGeminiProfileDirOptions {
21
- env?: NodeJS.ProcessEnv;
22
- homedir?: () => string;
23
- }
24
-
25
- function envValue(
26
- env: NodeJS.ProcessEnv | undefined,
27
- key: string,
28
- ): string | undefined {
29
- const v = env?.[key]?.trim();
30
- return v || undefined;
31
- }
32
-
33
- /**
34
- * Resolve the on-disk Gemini profile directory for a OffRouter profile id.
35
- *
36
- * - When OFFROUTER_GEMINI_PROFILES_DIR is set: $DIR/<profile>
37
- * - profile id `gemini` -> GEMINI_HOME (if set) else ~/.gemini
38
- * - otherwise -> ~/.<profile> (e.g. gemini-personal -> ~/.gemini-personal)
39
- */
40
- export function resolveGeminiProfileDir(
41
- profile: string,
42
- options: ResolveGeminiProfileDirOptions = {},
43
- ): string {
44
- if (!isSafeProfileId(profile)) {
45
- throw new Error(
46
- `Unsafe profile id "${profile}". Use letters, numbers, dots, underscores, and dashes only.`,
47
- );
48
- }
49
- const env = options.env ?? process.env;
50
- const home = (options.homedir ?? osHomedir)();
51
- const profilesRoot = envValue(env, "OFFROUTER_GEMINI_PROFILES_DIR");
52
- if (profilesRoot) {
53
- return resolve(join(profilesRoot, profile));
54
- }
55
- if (profile === "gemini") {
56
- const geminiHome = envValue(env, "GEMINI_HOME");
57
- return resolve(geminiHome ?? join(home, ".gemini"));
58
- }
59
- return resolve(join(home, `.${profile}`));
60
- }
61
-
62
- /**
63
- * Personal Gemini profiles only: id starts with "gemini" or is exactly "gemini".
64
- */
65
- export function isGeminiHarnessProfile(profile: string): boolean {
66
- return profile === "gemini" || profile.startsWith("gemini-");
67
- }
68
-
69
- export function isWorkLikeProfile(profile: string): boolean {
70
- return profile.endsWith("-work") || profile.includes("-work-");
71
- }
72
-
73
- function matchGlob(pattern: string, value: string): boolean {
74
- const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
75
- const re = new RegExp(`^${escaped.replace(/\*/g, ".*")}$`);
76
- return re.test(value);
77
- }
78
-
79
- /**
80
- * Allowlisted personal Gemini profiles eligible for install --all-personal.
81
- * Excludes the bare global `gemini` profile (only mutable when explicit) and
82
- * work-like ids, and applies deniedProfilePatterns glob filters.
83
- */
84
- export function listAllowlistedPersonalGeminiProfiles(
85
- config: OffRouterConfig,
86
- ): string[] {
87
- return [...config.policy.allowlistedProfiles]
88
- .filter(
89
- (id) =>
90
- isSafeProfileId(id) &&
91
- isGeminiHarnessProfile(id) &&
92
- id !== "gemini" &&
93
- !isWorkLikeProfile(id) &&
94
- !(config.policy.deniedProfilePatterns ?? []).some((p) =>
95
- matchGlob(p, id),
96
- ),
97
- )
98
- .sort((a, b) => a.localeCompare(b));
99
- }