@rfc0/patty 1.1.0 → 1.2.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.
package/README.md CHANGED
@@ -54,6 +54,7 @@ npx @rfc0/patty@latest setup claude-desktop # Claude Desktop
54
54
  npx @rfc0/patty@latest setup copilot # VS Code / GitHub Copilot
55
55
  npx @rfc0/patty@latest setup antigravity # Google Antigravity
56
56
  npx @rfc0/patty@latest setup codex # OpenAI Codex (prints snippet)
57
+ npx @rfc0/patty@latest setup opencode # OpenCode (JSONC-safe)
57
58
  ```
58
59
 
59
60
  Run without a tool name to list all options and the config file each one writes:
@@ -30,6 +30,7 @@ Available tools:
30
30
  vscode VS Code / GitHub Copilot (alias for copilot)
31
31
  antigravity Google Antigravity (~/.gemini/config/mcp_config.json)
32
32
  codex OpenAI Codex (prints the config snippet to paste)
33
+ opencode OpenCode (~/.config/opencode/opencode.jsonc or opencode.json; honours XDG_CONFIG_HOME)
33
34
 
34
35
  ${PRODUCT_NAME} requires a login. The first time, setup asks you to choose the owner's username and password
35
36
  (typed twice, never echoed), writes the client's config, then offers to sign that client in. Re-running it is safe: an
@@ -48,6 +49,7 @@ Examples:
48
49
  ${NPX_COMMAND} setup copilot
49
50
  ${NPX_COMMAND} setup vscode
50
51
  ${NPX_COMMAND} setup antigravity
52
+ ${NPX_COMMAND} setup opencode
51
53
  `.trimStart(),
52
54
  unknownTool: (tool) => `patty setup: unknown tool "${tool}"\n\nRun without arguments to see available tools.`,
53
55
  settingUp: (label) => `Setting up ${PRODUCT_NAME} MCP for ${label}...`,
@@ -1,18 +1,18 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
- import { dirname, join } from 'node:path';
3
+ import { dirname, isAbsolute, join } from 'node:path';
4
4
  import { err, ok, Result } from 'neverthrow';
5
5
  import * as R from 'remeda';
6
6
  import { DEFAULT_PROFILE, PROFILE_ENV_VAR } from '../../models/auth/sign-in.js';
7
- import { clientConfigFailures } from '../../models/client-config.js';
7
+ import { clientConfigFailures, INVALID_ROOT_MESSAGE, LEFT_UNCHANGED, } from '../../models/client-config.js';
8
8
  import { DEMO_SERVER_NAME } from '../../models/demo/core.js';
9
9
  import { PACKAGE_SPEC } from '../../models/package.js';
10
- import { ServersKey } from '../../wire/out/client-config.js';
11
- import { mergeMcpServersKey, mergeServersKey, resolveConfigObject, SERVER_NAME, STDIO_ENTRY, VSCODE_ENTRY, withDemo, withoutServer, withProfile, } from './merge.js';
10
+ import { EnvKey, ServersKey } from '../../wire/out/client-config.js';
11
+ import { detectLayout, layoutRefusal, OPENCODE_UNUSABLE_MESSAGE, parseDocument, withoutServerText, withFinalNewline, withServerText, } from './jsonc.js';
12
+ import { mergeMcpServersKey, mergeServersKey, OPENCODE_ENTRY, resolveConfigObject, SERVER_NAME, STDIO_ENTRY, VSCODE_ENTRY, withDemo, withoutServer, withProfile, } from './merge.js';
12
13
  // ---------------------------------------------------------------------------
13
14
  // FS helpers
14
15
  // ---------------------------------------------------------------------------
15
- const INVALID_ROOT_MESSAGE = 'does not contain a JSON object at the root';
16
16
  const invalidConfigWarning = (path) => `patty setup: ${path} ${INVALID_ROOT_MESSAGE} — replacing it during setup.`;
17
17
  // The throwing system calls, wrapped once: everything below this block is Results.
18
18
  const readText = Result.fromThrowable((path) => readFileSync(path, 'utf8'), R.identity());
@@ -22,7 +22,7 @@ const writeText = Result.fromThrowable((path, text) => {
22
22
  }, R.identity());
23
23
  const parseJson = Result.fromThrowable((text) => JSON.parse(text), R.identity());
24
24
  const replaceUnusable = (path) => ok({ config: {}, warnings: [invalidConfigWarning(path)] });
25
- const refuseUnusable = (path) => err(clientConfigFailures.readFailed(path, `${INVALID_ROOT_MESSAGE}, or is not plain JSON — left unchanged`));
25
+ const refuseUnusable = (path) => err(clientConfigFailures.readFailed(path, `${INVALID_ROOT_MESSAGE}, or is not plain JSON${LEFT_UNCHANGED}`));
26
26
  /** The demo entry refuses an unusable file instead of replacing it. */
27
27
  export const readJsonOrEmpty = (path, whenUnusable = replaceUnusable) => {
28
28
  if (!existsSync(path))
@@ -38,6 +38,22 @@ export const readJsonOrEmpty = (path, whenUnusable = replaceUnusable) => {
38
38
  });
39
39
  };
40
40
  const writeJson = (path, data) => writeText(path, JSON.stringify(data, null, 2) + '\n').mapErr((cause) => clientConfigFailures.writeFailed(path, cause));
41
+ /** Reads an OpenCode config (JSON or JSONC) for editing: a missing or empty file is an empty document, and one that
42
+ * cannot be edited without damage — unparsable, a non-object root, a V1 layout — is refused, never replaced. */
43
+ const readJsoncDocument = (path) => {
44
+ const refuse = (reason) => err(clientConfigFailures.readFailed(path, reason));
45
+ const content = existsSync(path) ? readText(path) : ok('');
46
+ return content
47
+ .mapErr((cause) => clientConfigFailures.readFailed(path, cause))
48
+ .andThen((text) => {
49
+ const document = parseDocument(text);
50
+ if (document === null)
51
+ return refuse(OPENCODE_UNUSABLE_MESSAGE);
52
+ const refusal = layoutRefusal(detectLayout(document.root));
53
+ return refusal === null ? ok(document) : refuse(refusal);
54
+ });
55
+ };
56
+ const writeJsonc = (path, text) => writeText(path, withFinalNewline(text)).mapErr((cause) => clientConfigFailures.writeFailed(path, cause));
41
57
  // ---------------------------------------------------------------------------
42
58
  // Platform-aware config path helpers
43
59
  // ---------------------------------------------------------------------------
@@ -58,15 +74,23 @@ const writeEntry = (configPath, merge, entry, next, whenUnusable = replaceUnusab
58
74
  // What was raised while reading is still owed to the person, ahead of the failure.
59
75
  .mapErr((failure) => ({ ...failure, warnings })));
60
76
  const nothingToRemove = (reason) => ok({ warnings: [], lines: [` ${reason}`] });
77
+ const demoRemoval = {
78
+ noFile: (configPath) => nothingToRemove(`No demo entry to remove: ${configPath} does not exist`),
79
+ noEntry: (configPath) => nothingToRemove(`No ${DEMO_SERVER_NAME} entry in ${configPath}`),
80
+ removed: (configPath, next) => ({
81
+ warnings: [],
82
+ lines: [` Removed ${DEMO_SERVER_NAME} from ${configPath}`, next],
83
+ }),
84
+ };
61
85
  const removeDemoEntry = (configPath, key, next) => {
62
86
  if (!existsSync(configPath))
63
- return nothingToRemove(`No demo entry to remove: ${configPath} does not exist`);
87
+ return demoRemoval.noFile(configPath);
64
88
  return readJsonOrEmpty(configPath, refuseUnusable).andThen(({ config, warnings }) => {
65
89
  const without = withoutServer(config, key, DEMO_SERVER_NAME);
66
90
  if (without === null)
67
- return nothingToRemove(`No ${DEMO_SERVER_NAME} entry in ${configPath}`);
91
+ return demoRemoval.noEntry(configPath);
68
92
  return writeJson(configPath, without)
69
- .map(() => ({ warnings, lines: [` Removed ${DEMO_SERVER_NAME} from ${configPath}`, next] }))
93
+ .map(() => ({ ...demoRemoval.removed(configPath, next), warnings }))
70
94
  .mapErr((failure) => ({ ...failure, warnings }));
71
95
  });
72
96
  };
@@ -76,10 +100,34 @@ const MERGE_BY_KEY = {
76
100
  };
77
101
  const fileClient = ({ label, path, key, entry, next }) => ({
78
102
  label,
79
- run: (profile) => writeEntry(path(), MERGE_BY_KEY[key], withProfile(entry, profile), next),
80
- addDemo: (databasePath) => writeEntry(path(), (existing, demoEntry) => MERGE_BY_KEY[key](existing, demoEntry, DEMO_SERVER_NAME), withDemo(entry, databasePath), next, refuseUnusable),
103
+ run: (profile) => writeEntry(path(), MERGE_BY_KEY[key], withProfile(entry, profile, EnvKey.enum.env), next),
104
+ addDemo: (databasePath) => writeEntry(path(), (existing, demoEntry) => MERGE_BY_KEY[key](existing, demoEntry, DEMO_SERVER_NAME), withDemo(entry, databasePath, EnvKey.enum.env), next, refuseUnusable),
81
105
  removeDemo: () => removeDemoEntry(path(), key, next),
82
106
  });
107
+ /** A client whose file is JSON with comments: edited in place, so what the person wrote survives. */
108
+ const jsoncClient = ({ label, path, entry, next }) => {
109
+ const setEntry = (name, withEnv) => {
110
+ const configPath = path();
111
+ return readJsoncDocument(configPath).andThen(({ text }) => writeJsonc(configPath, withServerText(text, name, withEnv)).map(() => ({ warnings: [], lines: [` Updated: ${configPath}`, next] })));
112
+ };
113
+ return {
114
+ label,
115
+ run: (profile) => setEntry(SERVER_NAME, withProfile(entry, profile, EnvKey.enum.environment)),
116
+ addDemo: (databasePath) => setEntry(DEMO_SERVER_NAME, withDemo(entry, databasePath, EnvKey.enum.environment)),
117
+ removeDemo: () => {
118
+ const configPath = path();
119
+ // A missing file is "nothing to remove", never a file to create.
120
+ if (!existsSync(configPath))
121
+ return demoRemoval.noFile(configPath);
122
+ return readJsoncDocument(configPath).andThen((document) => {
123
+ const without = withoutServerText(document, DEMO_SERVER_NAME);
124
+ if (without === null)
125
+ return demoRemoval.noEntry(configPath);
126
+ return writeJsonc(configPath, without).map(() => demoRemoval.removed(configPath, next));
127
+ });
128
+ },
129
+ };
130
+ };
83
131
  // Codex CLI MCP configuration path and format is not yet stable: describe the snippet and let the user place it.
84
132
  /** JSON-escaped: a path may hold backslashes or quotes. */
85
133
  const inlineObject = (env) => `{ ${Object.entries(env)
@@ -104,7 +152,10 @@ const setupCodex = (profile) => ok({
104
152
  const codex = {
105
153
  label: 'OpenAI Codex',
106
154
  run: setupCodex,
107
- addDemo: (databasePath) => ok({ warnings: [], lines: [codexSnippet(DEMO_SERVER_NAME, withDemo(STDIO_ENTRY, databasePath).env)] }),
155
+ addDemo: (databasePath) => ok({
156
+ warnings: [],
157
+ lines: [codexSnippet(DEMO_SERVER_NAME, withDemo(STDIO_ENTRY, databasePath, EnvKey.enum.env).env)],
158
+ }),
108
159
  removeDemo: () => ok({ warnings: [], lines: [` Codex CLI: remove the "${DEMO_SERVER_NAME}" entry from your MCP config file.`] }),
109
160
  };
110
161
  // ---------------------------------------------------------------------------
@@ -138,6 +189,23 @@ const antigravity = fileClient({
138
189
  entry: STDIO_ENTRY,
139
190
  next: ' Reopen Antigravity or type /mcp in the CLI to refresh.',
140
191
  });
192
+ /** OpenCode's config root: `XDG_CONFIG_HOME` when it is an absolute path (the XDG rule), else `~/.config`. */
193
+ const xdgConfigHome = () => {
194
+ const configured = process.env['XDG_CONFIG_HOME'];
195
+ return configured !== undefined && isAbsolute(configured) ? configured : join(home, '.config');
196
+ };
197
+ /** `opencode.jsonc` when it exists, else `opencode.json` (created if neither does). */
198
+ const openCodeConfigPath = () => {
199
+ const directory = join(xdgConfigHome(), 'opencode');
200
+ const jsonc = join(directory, 'opencode.jsonc');
201
+ return existsSync(jsonc) ? jsonc : join(directory, 'opencode.json');
202
+ };
203
+ const openCode = jsoncClient({
204
+ label: 'OpenCode',
205
+ path: openCodeConfigPath,
206
+ entry: OPENCODE_ENTRY,
207
+ next: ' Verify with: opencode mcp list (or /mcps inside OpenCode)',
208
+ });
141
209
  const TOOLS = {
142
210
  'claude-code': claudeCode,
143
211
  'claude-desktop': claudeDesktop,
@@ -145,6 +213,7 @@ const TOOLS = {
145
213
  vscode: copilot,
146
214
  antigravity,
147
215
  codex,
216
+ opencode: openCode,
148
217
  };
149
218
  const findClient = (tool) => TOOLS[tool.trim().toLowerCase()];
150
219
  export const clientConfigs = { find: findClient };
@@ -0,0 +1,72 @@
1
+ import { applyEdits, modify, parse } from 'jsonc-parser';
2
+ import { INVALID_ROOT_MESSAGE, LEFT_UNCHANGED } from '../../models/client-config.js';
3
+ import { McpLayout } from '../../wire/out/client-config.js';
4
+ import { resolveConfigObject } from './merge.js';
5
+ // ---------------------------------------------------------------------------
6
+ // Pure JSONC editing of OpenCode's configuration (testable without FS)
7
+ // ---------------------------------------------------------------------------
8
+ /** The V2 layout keeps servers at `mcp.servers.<name>`. */
9
+ const MCP_KEY = 'mcp';
10
+ const SERVERS_KEY = 'servers';
11
+ const SERVERS_PATH = [MCP_KEY, SERVERS_KEY];
12
+ const BYTE_ORDER_MARK = '\uFEFF';
13
+ const EMPTY_DOCUMENT = '{}';
14
+ const CRLF = '\r\n';
15
+ const LF = '\n';
16
+ /** The document's own line ending: CRLF when it holds one, else LF. */
17
+ const lineEnding = (text) => (text.includes(CRLF) ? CRLF : LF);
18
+ export const OPENCODE_V1_LAYOUT_MESSAGE = 'is in OpenCode\'s V1 layout (servers directly under "mcp") — migrate it first (see "Migrate from V1" at ' +
19
+ `https://opencode.ai/docs/mcp-servers), then run setup again${LEFT_UNCHANGED}`;
20
+ export const OPENCODE_UNUSABLE_MESSAGE = `${INVALID_ROOT_MESSAGE}, or is not valid JSON/JSONC${LEFT_UNCHANGED}`;
21
+ const OPENCODE_SERVERS_NOT_OBJECT_MESSAGE = `has an "mcp" or "mcp.servers" that is not an object${LEFT_UNCHANGED}`;
22
+ /** Parses JSONC (comments and trailing commas allowed); `null` for anything that is not an object at the root. */
23
+ export const parseDocument = (text) => {
24
+ const unmarked = text.startsWith(BYTE_ORDER_MARK) ? text.slice(BYTE_ORDER_MARK.length) : text;
25
+ const errors = [];
26
+ const value = parse(unmarked, errors, { allowTrailingComma: true });
27
+ // Nothing but whitespace or comments is "no value yet": the comments stay, an empty object follows them.
28
+ const isBlank = value === undefined && errors.every(({ error }) => error === 4 /* ParseErrorCode.ValueExpected */);
29
+ if (errors.length > 0 && !isBlank)
30
+ return null;
31
+ if (isBlank)
32
+ return { text: `${unmarked.trimEnd()}${lineEnding(unmarked)}${EMPTY_DOCUMENT}`.trimStart(), root: {} };
33
+ const root = resolveConfigObject(value);
34
+ return root === null ? null : { text: unmarked, root };
35
+ };
36
+ /** A V1 server entry: an object saying how to start or reach the server. Global options (`timeout`, …) are not. */
37
+ const SERVER_ENTRY_KEYS = ['type', 'command', 'url'];
38
+ const isLegacyServerEntry = (value) => {
39
+ const entry = resolveConfigObject(value);
40
+ return entry !== null && SERVER_ENTRY_KEYS.some((key) => key in entry);
41
+ };
42
+ export const detectLayout = (root) => {
43
+ const mcp = root[MCP_KEY];
44
+ if (mcp === undefined)
45
+ return McpLayout.enum.fresh;
46
+ const section = resolveConfigObject(mcp);
47
+ if (section === null)
48
+ return McpLayout.enum.malformed;
49
+ if (!(SERVERS_KEY in section))
50
+ return Object.values(section).some(isLegacyServerEntry) ? McpLayout.enum.v1 : McpLayout.enum.fresh;
51
+ return resolveConfigObject(section[SERVERS_KEY]) === null ? McpLayout.enum.malformed : McpLayout.enum.v2;
52
+ };
53
+ const LAYOUT_REFUSALS = {
54
+ [McpLayout.enum.fresh]: null,
55
+ [McpLayout.enum.v2]: null,
56
+ [McpLayout.enum.v1]: OPENCODE_V1_LAYOUT_MESSAGE,
57
+ [McpLayout.enum.malformed]: OPENCODE_SERVERS_NOT_OBJECT_MESSAGE,
58
+ };
59
+ /** Why a layout cannot be edited; `null` when it can. */
60
+ export const layoutRefusal = (layout) => LAYOUT_REFUSALS[layout];
61
+ const editAt = (text, name, value) => applyEdits(text, modify(text, [...SERVERS_PATH, name], value, {
62
+ formattingOptions: { insertSpaces: true, tabSize: 2, eol: lineEnding(text) },
63
+ }));
64
+ /** The document with `mcp.servers.<name>` set to `entry`; comments, other keys and formatting stay as they were. */
65
+ export const withServerText = (text, name, entry) => editAt(text, name, entry);
66
+ /** The document without `mcp.servers.<name>`, or `null` when there is no such entry. */
67
+ export const withoutServerText = (document, name) => {
68
+ const servers = resolveConfigObject(resolveConfigObject(document.root[MCP_KEY])?.[SERVERS_KEY]);
69
+ return servers !== null && name in servers ? editAt(document.text, name, undefined) : null;
70
+ };
71
+ /** The text ending in a line break, in the document's own style. */
72
+ export const withFinalNewline = (text) => (text.endsWith(LF) ? text : `${text}${lineEnding(text)}`);
@@ -10,18 +10,23 @@ export const STDIO_ENTRY = {
10
10
  command: 'npx',
11
11
  args: ['-y', PACKAGE_SPEC],
12
12
  };
13
+ /** OpenCode's local server shape: the command is one array, and it is `type: 'local'`. */
14
+ export const OPENCODE_ENTRY = {
15
+ type: 'local',
16
+ command: ['npx', '-y', PACKAGE_SPEC],
17
+ };
13
18
  export const VSCODE_ENTRY = {
14
19
  type: 'stdio',
15
20
  command: 'npx',
16
21
  args: ['-y', PACKAGE_SPEC],
17
22
  };
18
- /** A client config entry that signs in as `profile`: `PATTY_PROFILE` is added to its `env` only when the profile
19
- * is not the default, so an ordinary install writes exactly the entry it always did (ADR-034 §5.2). */
20
- export const withProfile = (entry, profile) => profile === DEFAULT_PROFILE ? entry : { ...entry, env: { [PROFILE_ENV_VAR]: profile } };
21
- export const withDemo = (entry, databasePath) => ({
22
- ...entry,
23
- env: { DB_PATH: databasePath, PORT: String(DEMO_PORT), [DEMO_ENV_VAR]: DEMO_ENV_ON },
24
- });
23
+ /** The entry with `env` under the client's own key — the one place a computed key needs a cast. */
24
+ const withEnvironment = (entry, envKey, env) => ({ ...entry, [envKey]: env });
25
+ /** A client config entry that signs in as `profile`: `PATTY_PROFILE` is added to its environment (under `envKey`)
26
+ * only when the profile is not the default, so an ordinary install writes exactly the entry it always did
27
+ * (ADR-034 §5.2). */
28
+ export const withProfile = (entry, profile, envKey) => profile === DEFAULT_PROFILE ? entry : withEnvironment(entry, envKey, { [PROFILE_ENV_VAR]: profile });
29
+ export const withDemo = (entry, databasePath, envKey) => withEnvironment(entry, envKey, { DB_PATH: databasePath, PORT: String(DEMO_PORT), [DEMO_ENV_VAR]: DEMO_ENV_ON });
25
30
  // ---------------------------------------------------------------------------
26
31
  // Pure config merge helpers (testable without FS)
27
32
  // ---------------------------------------------------------------------------
@@ -2,6 +2,9 @@ import { z } from 'zod';
2
2
  import { reasonOf } from './error.js';
3
3
  /** Why a client's configuration file could not be used (expected failures of `setup`). */
4
4
  export const ClientConfigFailureCode = z.enum(['read_failed', 'write_failed']);
5
+ /** What every refusal of an unusable client file says first, and last. */
6
+ export const INVALID_ROOT_MESSAGE = 'does not contain a JSON object at the root';
7
+ export const LEFT_UNCHANGED = ' — left unchanged';
5
8
  export const clientConfigFailures = {
6
9
  readFailed: (path, cause) => ({
7
10
  code: ClientConfigFailureCode.enum.read_failed,
@@ -1,2 +1,14 @@
1
1
  import { z } from 'zod';
2
2
  export const ServersKey = z.enum(['mcpServers', 'servers']);
3
+ /** Where a client's MCP entry keeps its environment variables. */
4
+ export const EnvKey = z.enum(['env', 'environment']);
5
+ /** What an OpenCode config's `mcp` key says about its layout. */
6
+ export const McpLayout = z.enum([
7
+ /** No `mcp` key, or an empty one: the V2 shape is created. */
8
+ 'fresh',
9
+ 'v2',
10
+ /** Servers directly under `mcp`, no `mcp.servers`. */
11
+ 'v1',
12
+ /** `mcp` or `mcp.servers` exists but is not an object. */
13
+ 'malformed',
14
+ ]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rfc0/patty",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "AI-first personal finance manager — MCP server (local-first, encrypted libSQL).",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -77,6 +77,7 @@
77
77
  "@rfc0/effect-runner": "^0.6.0",
78
78
  "drizzle-orm": "^0.45.2",
79
79
  "fastify": "^5.12.8",
80
+ "jsonc-parser": "^3.3.1",
80
81
  "neverthrow": "^8.2.0",
81
82
  "openapi3-ts": "^4.6.0",
82
83
  "remeda": "^2.21.0",