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