@rfc0/patty 1.0.2 → 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:
@@ -0,0 +1,14 @@
1
+ import { ChangeEventRowSchema, RowIdSchema } from '../wire/db/change-events.js';
2
+ const NO_ID = 0;
3
+ const idOf = (row) => RowIdSchema.safeParse(row).data?.id ?? NO_ID;
4
+ /** A stored row as the relay's entry: the decoded event, or the reason it could not be decoded (never thrown). */
5
+ export const dbToModel = (row) => {
6
+ const decoded = ChangeEventRowSchema.safeParse(row);
7
+ return decoded.success
8
+ ? {
9
+ id: decoded.data.id,
10
+ origin: decoded.data.origin,
11
+ event: { userId: decoded.data.userId, entities: decoded.data.entities },
12
+ }
13
+ : { id: idOf(row), skipped: decoded.error.issues.map(({ message }) => message).join('; ') };
14
+ };
@@ -0,0 +1 @@
1
+ export const sleep = (ms) => new Promise((resume) => setTimeout(resume, ms));
@@ -23,5 +23,6 @@ export const boot = (config) => safeTry(async function* () {
23
23
  return err(demoNotReady(config.DB_PATH));
24
24
  }
25
25
  const prepared = await prepareAuth(config, db, runtime.authRunEffects);
26
+ await runtime.changeLog.prune();
26
27
  return ok({ db, runtime, prepared });
27
28
  });
@@ -0,0 +1,47 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { createRelayedChangeBus, pruneCutoff, startChangeRelay, } from '@rfc0/effect-runner';
3
+ import { changeLogStore } from '../diplomat/db/change-events.js';
4
+ import { isWorthAnnouncing } from '../logic/change-events.js';
5
+ import { CHANGE_EVENT_PRUNE_EVERY_MS, CHANGE_NOTIFICATION_FAILED, CHANGE_EVENT_RETENTION_MS, CHANGE_RELAY_BATCH_LIMIT, CHANGE_RELAY_POLL_MS, } from '../models/change-events.js';
6
+ import { LOG_PREFIX } from '../models/package.js';
7
+ /** stderr only — stdout carries the stdio MCP protocol (ADR-007). */
8
+ export const reportChangeError = (cause) => {
9
+ console.error(`${LOG_PREFIX} ${CHANGE_NOTIFICATION_FAILED}:`, cause);
10
+ };
11
+ /** The process's change bus (ADR-036 §2): `@rfc0/effect-runner`'s relayed bus over the SQLite store, so a publish
12
+ * reaches this process's subscribers first and the other processes' relays after. A subscriber's failure and a failed
13
+ * append go to `onError`, never to the write. */
14
+ export const createChangeLog = (db, onError, clock = () => new Date()) => {
15
+ const origin = randomUUID();
16
+ const store = changeLogStore(db);
17
+ const { bus, publishLocal, settled } = createRelayedChangeBus({
18
+ store,
19
+ origin,
20
+ onError,
21
+ shouldAppend: isWorthAnnouncing,
22
+ });
23
+ // Only a relay prunes on a timer, so every process prunes once at startup.
24
+ const prune = () => store.pruneBefore(pruneCutoff(clock(), CHANGE_EVENT_RETENTION_MS)).catch(onError);
25
+ const close = async () => {
26
+ await settled();
27
+ await store.close();
28
+ };
29
+ return { changeBus: bus, changeLog: { origin, onError, store, publishLocal, settled, prune, close } };
30
+ };
31
+ /**
32
+ * The relay of a process that serves a dashboard, with PATTY's values (ADR-036 §3). One that cannot start is reported
33
+ * and answers `null`; the dashboard then updates from this process's writes only.
34
+ */
35
+ export const startServingRelay = ({ changeLog }) => startChangeRelay({
36
+ store: changeLog.store,
37
+ publishLocal: changeLog.publishLocal,
38
+ origin: changeLog.origin,
39
+ pollMs: CHANGE_RELAY_POLL_MS,
40
+ retentionMs: CHANGE_EVENT_RETENTION_MS,
41
+ pruneEveryMs: CHANGE_EVENT_PRUNE_EVERY_MS,
42
+ batchLimit: CHANGE_RELAY_BATCH_LIMIT,
43
+ onError: changeLog.onError,
44
+ }).catch((cause) => {
45
+ changeLog.onError(cause);
46
+ return null;
47
+ });
@@ -72,6 +72,16 @@ const runPlan = async (scoped, plan, clock, today) => {
72
72
  export const seedDemo = async (db, options) => {
73
73
  const clock = { now: options.today };
74
74
  const runtime = createRuntime(db, { ...options.config, PATTY_LOCALE: undefined }, { clock: () => clock.now });
75
+ try {
76
+ return await seedOn(runtime, db, options, clock);
77
+ }
78
+ finally {
79
+ // The seed's writes queued change announcements: drain them and release the log connection before the caller
80
+ // closes or removes the database.
81
+ await runtime.changeLog.close();
82
+ }
83
+ };
84
+ const seedOn = async (runtime, db, options, clock) => {
75
85
  const scoped = scopedFor(runtime, OWNER_PRINCIPAL);
76
86
  const instanceSettings = instanceSettingsRepo(db);
77
87
  const start = await demoSeedStatus({ instance: scoped.deps.instance, instanceSettings });
@@ -2,6 +2,7 @@ import { ok, safeTry } from 'neverthrow';
2
2
  import Fastify from 'fastify';
3
3
  import { version } from '../common/build-version.js';
4
4
  import { boot } from './boot.js';
5
+ import { startServingRelay } from './change-log.js';
5
6
  import { DASHBOARD_PATH, httpOrigin, isPortInUse, LOOPBACK_HOST, portInUseReason } from '../common/net.js';
6
7
  import { DISABLED_AUTH } from '../diplomat/http/context.js';
7
8
  import { redactSecretQuery } from '../logic/auth/redact.js';
@@ -88,18 +89,26 @@ export const runHttp = (config) => safeTry(async function* () {
88
89
  const app = buildHttpApp(runtime, version, { auth: prepared.auth, trustProxy: config.TRUST_PROXY });
89
90
  // A repeated signal (or SIGINT followed by SIGTERM) must not double-close/double-exit.
90
91
  let shuttingDown = false;
92
+ let relay = null;
91
93
  const shutdown = () => {
92
94
  if (shuttingDown)
93
95
  return;
94
96
  shuttingDown = true;
95
- app
96
- .close()
97
- .catch((err) => app.log.error(err))
97
+ // Each stage is logged when it fails and never skips the next: a relay that fails to stop must not leave the
98
+ // listening socket and the change-log connection open.
99
+ const stage = (work) => Promise.resolve()
100
+ .then(work)
101
+ .then(() => undefined)
102
+ .catch((err) => app.log.error(err));
103
+ void stage(() => relay?.stop())
104
+ .then(() => stage(() => app.close()))
105
+ .then(() => stage(() => runtime.changeLog.close()))
98
106
  .finally(() => process.exit(0));
99
107
  };
100
108
  process.on('SIGINT', shutdown);
101
109
  process.on('SIGTERM', shutdown);
102
110
  await app.listen({ port: config.PORT, host: config.HOST });
111
+ relay = await startServingRelay(runtime);
103
112
  // config.PORT may be 0 (OS-assigned); read back the address actually bound for the banner.
104
113
  const boundPort = app.server.address().port;
105
114
  const origin = httpOrigin(config.HOST, boundPort);
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { createChangeBus, runEffects, runEffectsSequence } from '@rfc0/effect-runner';
2
+ import { runEffects, runEffectsSequence } from '@rfc0/effect-runner';
3
3
  import { AUTH_APPLIERS } from './auth.js';
4
+ import { createChangeLog, reportChangeError } from './change-log.js';
4
5
  import { createEngineContext } from '../diplomat/db/engine.js';
5
6
  import { createLocaleResolver } from '../diplomat/db/locale-cache.js';
6
7
  import { accountApplier, accountsRepo } from '../diplomat/db/repos/accounts.js';
@@ -34,9 +35,6 @@ import { RECURRING_ENTITY_TAG } from '../models/recurring.js';
34
35
  import { TAG_ENTITY_TAG } from '../models/tag.js';
35
36
  import { TRANSACTION_ENTITY_TAG } from '../models/transaction.js';
36
37
  import { TRANSACTION_TAG_ENTITY_TAG } from '../models/transaction-tag.js';
37
- const reportChangeError = (cause) => {
38
- console.error('[patty] change notification failed:', cause);
39
- };
40
38
  const applierRegistryFor = (userId) => ({
41
39
  [ACCOUNT_ENTITY_TAG]: accountApplier(userId),
42
40
  [TRANSACTION_ENTITY_TAG]: transactionApplier(userId),
@@ -82,10 +80,17 @@ const runnersOn = (engineContext, changeBus) => {
82
80
  authRunEffects: (flow) => runEffects(engineContext, AUTH_APPLIERS, flow, publishFor(null)),
83
81
  };
84
82
  };
83
+ const dropStaleLocale = (localeResolver) => ({ userId, entities }) => {
84
+ if (userId !== null && entities.includes(USER_SETTINGS_ENTITY_TAG))
85
+ localeResolver.resetLocale(userId);
86
+ };
85
87
  export const createRuntime = (db, config, options = {}) => {
86
88
  const onChangeError = options.onChangeError ?? reportChangeError;
87
89
  const localeResolver = createLocaleResolver(config.PATTY_LOCALE);
88
- const changeBus = createChangeBus({ onError: onChangeError });
90
+ const { changeBus, changeLog } = createChangeLog(db, onChangeError, options.clock);
91
+ // First subscriber, so it runs before any dashboard stream: another process's `set_locale` reaches this one as a
92
+ // relayed event, and the cached language must be gone by the time the refetch it triggers resolves a locale.
93
+ changeBus.subscribe(dropStaleLocale(localeResolver));
89
94
  const health = healthRepo(db);
90
95
  const instance = instanceRepo(db);
91
96
  const depsFor = ({ userId }) => {
@@ -111,5 +116,6 @@ export const createRuntime = (db, config, options = {}) => {
111
116
  ...runnersOn(createEngineContext(db, onChangeError), changeBus),
112
117
  resetLocaleFor: ({ userId }) => localeResolver.resetLocale(userId),
113
118
  changeBus,
119
+ changeLog,
114
120
  };
115
121
  };
@@ -29,8 +29,15 @@ export const startSignInServer = async (config, db) => {
29
29
  // Fastify binds `localhost` to both its IPv4 and IPv6 loopback addresses.
30
30
  await app.listen({ port: 0, host: LOCALHOST_NAME }).catch(async (cause) => {
31
31
  await app.close();
32
+ await runtime.changeLog.close();
32
33
  throw cause;
33
34
  });
34
35
  const { port } = app.server.address();
35
- return { origin: httpOrigin(LOCALHOST_NAME, port), close: () => app.close() };
36
+ return {
37
+ origin: httpOrigin(LOCALHOST_NAME, port),
38
+ close: async () => {
39
+ await app.close();
40
+ await runtime.changeLog.close();
41
+ },
42
+ };
36
43
  };
@@ -5,6 +5,7 @@ import { connectStdio } from '../diplomat/mcp/stdio.js';
5
5
  import { signInOrigin } from '../logic/auth/origin.js';
6
6
  import { AuthMode } from '../models/auth/mode.js';
7
7
  import { boot } from './boot.js';
8
+ import { startServingRelay } from './change-log.js';
8
9
  import { loadHttpModule } from './lazy-modules.js';
9
10
  const maybeStartSidecar = async (config, runtime, auth) => {
10
11
  if (!config.PATTY_HTTP)
@@ -35,7 +36,7 @@ const stdioAuthFor = (config, stdio, linkOrigin) => stdio
35
36
  }
36
37
  : { mode: AuthMode.enum.disabled };
37
38
  const closeLogged = (closing) => closing.catch((err) => console.error(err));
38
- const shutdownOf = ({ server, session }, sidecar) => {
39
+ const shutdownOf = ({ server, session }, sidecar, relay, { changeLog }) => {
39
40
  let shuttingDown = false;
40
41
  return () => {
41
42
  if (shuttingDown)
@@ -45,7 +46,11 @@ const shutdownOf = ({ server, session }, sidecar) => {
45
46
  closeLogged(server.close()),
46
47
  sidecar?.listening ? closeLogged(sidecar.app.close()) : Promise.resolve(),
47
48
  session?.close(),
48
- ]).finally(() => process.exit(0));
49
+ ])
50
+ // Writers have stopped: stop listening, then let the last write's queued announcement land.
51
+ .then(() => closeLogged(Promise.resolve(relay?.stop())))
52
+ .then(() => closeLogged(changeLog.close()))
53
+ .finally(() => process.exit(0));
49
54
  };
50
55
  };
51
56
  const shutDownOnDisconnect = (shutdown) => {
@@ -59,11 +64,13 @@ export const runStdio = (config) => safeTry(async function* () {
59
64
  const link = signInLink(config);
60
65
  const connection = await connectStdio(runtime, version, stdioAuthFor(config, prepared.stdio, link.origin));
61
66
  const sidecar = await maybeStartSidecar(config, runtime, prepared.auth);
67
+ // Only a process that serves a dashboard listens for the others' writes (ADR-036 §3).
68
+ const relay = sidecar?.listening ? await startServingRelay(runtime) : null;
62
69
  if (sidecar?.listening) {
63
70
  const boundOrigin = httpOrigin(config.HOST, sidecar.app.server.address().port);
64
71
  link.bind(boundOrigin);
65
72
  await prepared.issueAndAnnounceSetup(boundOrigin);
66
73
  }
67
- shutDownOnDisconnect(shutdownOf(connection, sidecar));
74
+ shutDownOnDisconnect(shutdownOf(connection, sidecar, relay, runtime));
68
75
  return ok(undefined);
69
76
  });
package/dist/config.js CHANGED
@@ -24,15 +24,13 @@ const DEFAULT_KEY_LOCK_PATH = join(DATA_DIRECTORY, 'db-key.lock');
24
24
  // published package; `npm run dev` overrides PORT back to the familiar 3001 (package.json), so
25
25
  // a contributor's local dev instance never collides with an already-running installed instance.
26
26
  const DEFAULT_PORT = 51737;
27
- // `TRUST_PROXY=0` trusts zero proxy hops: no proxy.
28
- const NO_PROXY_HOPS = 0;
29
27
  /** Whether anything besides this machine can reach the instance: a non-loopback bind, or a reverse proxy
30
28
  * configured in front of it (`PUBLIC_URL` names its external origin; `TRUST_PROXY` says to believe it). A
31
29
  * proxy typically connects to a loopback bind, so `HOST` alone would call that instance private. Only used to
32
30
  * refuse `PATTY_AUTH=disabled` on such an instance. */
33
31
  export const isExposed = (env) => !isLoopbackHost(env.HOST) ||
34
32
  env.PUBLIC_URL !== undefined ||
35
- (env.TRUST_PROXY !== undefined && env.TRUST_PROXY !== false && env.TRUST_PROXY !== NO_PROXY_HOPS);
33
+ (env.TRUST_PROXY !== undefined && env.TRUST_PROXY !== false);
36
34
  // An empty string (`PUBLIC_URL=` from a compose file or shell) means "unset", not "invalid".
37
35
  const unsetWhenEmpty = (value) => (value === '' ? undefined : value);
38
36
  const optionalEnv = (schema) => z.preprocess(unsetWhenEmpty, schema.optional());
@@ -44,18 +42,23 @@ const PublicUrl = z
44
42
  .refine((value) => /^https?:\/\//.test(value) && new URL(value).origin === value, {
45
43
  message: 'PUBLIC_URL must be an http(s) origin with no path or trailing slash, e.g. https://patty.example.com',
46
44
  });
47
- // Fastify's `trustProxy`: `true`/`false`, a hop count, or a comma-separated list of trusted
48
- // addresses/CIDRs. Anything else is passed through for Fastify (proxy-addr) to interpret.
45
+ // Fastify's `trustProxy`: `true`/`false`, or a comma-separated list of trusted addresses/CIDRs (anything else is
46
+ // passed through for Fastify (proxy-addr) to interpret). A hop count is refused: Fastify trusts nobody for one,
47
+ // because a client that reaches the instance directly could spoof X-Forwarded-*; `0` keeps meaning "no proxy".
49
48
  const HOP_COUNT = /^\d+$/;
49
+ const NO_PROXY_HOPS = '0';
50
+ export const HOP_COUNT_REFUSED_MESSAGE = 'TRUST_PROXY cannot be a hop count: a client that reaches PATTY directly could spoof X-Forwarded-For. ' +
51
+ "Name the proxy instead — an address or CIDR list such as 'loopback' or '10.0.0.0/8' — or 'true' to trust every proxy.";
50
52
  const TrustProxy = z
51
53
  .string()
52
54
  .min(1)
55
+ .refine((value) => !HOP_COUNT.test(value) || value === NO_PROXY_HOPS, { message: HOP_COUNT_REFUSED_MESSAGE })
53
56
  .transform((value) => {
54
57
  if (value === 'true')
55
58
  return true;
56
- if (value === 'false')
59
+ if (value === 'false' || value === NO_PROXY_HOPS)
57
60
  return false;
58
- return HOP_COUNT.test(value) ? Number(value) : value;
61
+ return value;
59
62
  });
60
63
  const Env = z
61
64
  .object({
@@ -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
  // ---------------------------------------------------------------------------