imsg-mcp 1.19.4 → 1.21.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +2 -1
  3. package/dist/{app-config-BHA2RWD5.js → app-config-B_QqZFbl.js} +2 -2
  4. package/dist/{app-config-BHA2RWD5.js.map → app-config-B_QqZFbl.js.map} +1 -1
  5. package/dist/{attachment-sync-CIoN37ih.js → attachment-sync-DqIvfxPv.js} +2 -2
  6. package/dist/{attachment-sync-CIoN37ih.js.map → attachment-sync-DqIvfxPv.js.map} +1 -1
  7. package/dist/change-watcher-DNuxvzqL.js +151 -0
  8. package/dist/change-watcher-DNuxvzqL.js.map +1 -0
  9. package/dist/cli.js +51 -14
  10. package/dist/cli.js.map +1 -1
  11. package/dist/event-bus-DqXvbtEM.js +90 -0
  12. package/dist/event-bus-DqXvbtEM.js.map +1 -0
  13. package/dist/{exportStream-Bn0Ir89w.js → exportStream-DjdPdE1S.js} +2 -2
  14. package/dist/{exportStream-Bn0Ir89w.js.map → exportStream-DjdPdE1S.js.map} +1 -1
  15. package/dist/{imessage-db-BTy3p2Qk.js → imessage-db-Be6EywKE.js} +64 -2
  16. package/dist/imessage-db-Be6EywKE.js.map +1 -0
  17. package/dist/index.js +271 -35
  18. package/dist/index.js.map +1 -1
  19. package/dist/{media-intel-cache-E3ejWhWo.js → media-intel-cache-JJZzGCs4.js} +2 -2
  20. package/dist/{media-intel-cache-E3ejWhWo.js.map → media-intel-cache-JJZzGCs4.js.map} +1 -1
  21. package/dist/{media-intel-runtime-DwG4nhXt.js → media-intel-runtime-DbJ3jXLG.js} +3 -3
  22. package/dist/{media-intel-runtime-DwG4nhXt.js.map → media-intel-runtime-DbJ3jXLG.js.map} +1 -1
  23. package/dist/{setup-BRZC_tgU.js → setup-DxbCKuOU.js} +2 -2
  24. package/dist/{setup-BRZC_tgU.js.map → setup-DxbCKuOU.js.map} +1 -1
  25. package/dist/{setup-wizard-CM_3dRi_.js → setup-wizard-D70bqgzB.js} +3 -3
  26. package/dist/{setup-wizard-CM_3dRi_.js.map → setup-wizard-D70bqgzB.js.map} +1 -1
  27. package/dist/{shutdown-CWS6IvCE.js → shutdown-Dnj088id.js} +122 -80
  28. package/dist/shutdown-Dnj088id.js.map +1 -0
  29. package/dist/{tui-config-BPDDTKNp.js → tui-config-Bt1yixQj.js} +3 -3
  30. package/dist/tui-config-Bt1yixQj.js.map +1 -0
  31. package/dist/tui.js +387 -89
  32. package/dist/tui.js.map +1 -1
  33. package/dist/{watchdog-bq8BYT-s.js → watchdog-j-gArC02.js} +5 -10
  34. package/dist/watchdog-j-gArC02.js.map +1 -0
  35. package/package.json +5 -5
  36. package/skills/imsg-mcp/SKILL.md +2 -1
  37. package/dist/imessage-db-BTy3p2Qk.js.map +0 -1
  38. package/dist/shutdown-CWS6IvCE.js.map +0 -1
  39. package/dist/tui-config-BPDDTKNp.js.map +0 -1
  40. package/dist/watchdog-bq8BYT-s.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -3,6 +3,26 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and follows [Semantic Versioning](https://semver.org/).
5
5
 
6
+ # imsg-mcp [1.21.0](https://github.com/george43g/EQStack/compare/imsg-mcp-v1.20.0...imsg-mcp-v1.21.0) (2026-08-09)
7
+
8
+
9
+ ### Features
10
+
11
+ * **imsg-mcp:** live TUI updates via change stream ([68d56b1](https://github.com/george43g/EQStack/commit/68d56b1862ba41d61c6e65d3bb14ecaf68d640e6))
12
+ * **imsg-mcp:** wait_for_changes MCP tool — long-poll the change-event bus ([2704a61](https://github.com/george43g/EQStack/commit/2704a61b8d56aaa055662efdf53af5b2f36301a9)), closes [#66](https://github.com/george43g/EQStack/issues/66)
13
+
14
+ # imsg-mcp [1.20.0](https://github.com/george43g/EQStack/compare/imsg-mcp-v1.19.4...imsg-mcp-v1.20.0) (2026-08-09)
15
+
16
+
17
+ ### Bug Fixes
18
+
19
+ * **imsg-mcp:** incremental messagesByGuid map in ThreadPane ([d926b35](https://github.com/george43g/EQStack/commit/d926b351a0fbf7d173465c569f9ffe79d50f00d9))
20
+
21
+
22
+ ### Features
23
+
24
+ * **imsg-mcp:** cache hit-rate metrics ([26eeb5a](https://github.com/george43g/EQStack/commit/26eeb5a46e7d4b32e23a56a60ff129b4748507b6))
25
+
6
26
  ## imsg-mcp [1.19.4](https://github.com/george43g/EQStack/compare/imsg-mcp-v1.19.3...imsg-mcp-v1.19.4) (2026-08-09)
7
27
 
8
28
 
package/README.md CHANGED
@@ -74,7 +74,7 @@ Full walkthrough with screenshots: [**docs/WORKFLOWS.md**](docs/WORKFLOWS.md).
74
74
  ## MCP tools
75
75
 
76
76
  <details>
77
- <summary><b>17 tools shipped (click to expand)</b></summary>
77
+ <summary><b>18 tools shipped (click to expand)</b></summary>
78
78
 
79
79
  | Tool | Purpose |
80
80
  |------|---------|
@@ -84,6 +84,7 @@ Full walkthrough with screenshots: [**docs/WORKFLOWS.md**](docs/WORKFLOWS.md).
84
84
  | `search_messages` | Fuzzy + literal search across history. |
85
85
  | `send_message` | Send via Messages.app (text + attachments). |
86
86
  | `wait_for_reply` | Poll for the next reply — includes the user's own interjections from other devices. |
87
+ | `wait_for_changes` | Long-poll typed change events (`message.new` / `reaction`) across all conversations or one thread — push-fed by the chat.db WAL watcher. |
87
88
  | `export_messages` | Stream a chat to file (md/csv/json/ndjson). |
88
89
  | `search_attachments` | Find attachments by mime/date/chat. |
89
90
  | `get_attachment` | Fetch an attachment (image block / poster / audio) + optional AI interpretation (`interpret`). |
@@ -2,7 +2,7 @@ import { existsSync, mkdirSync, writeFileSync, readFileSync, chmodSync } from "n
2
2
  import { homedir } from "node:os";
3
3
  import { dirname, join } from "node:path";
4
4
  import { z } from "zod";
5
- import { c as getTranscribeCloudConfig } from "./shutdown-CWS6IvCE.js";
5
+ import { c as getTranscribeCloudConfig } from "./shutdown-Dnj088id.js";
6
6
  const HEX6 = /^#[0-9a-fA-F]{6}$/;
7
7
  const PROVIDER_PRESET_NAMES = [
8
8
  "openai",
@@ -248,4 +248,4 @@ export {
248
248
  writeCredentials,
249
249
  writeTuiConfig
250
250
  };
251
- //# sourceMappingURL=app-config-BHA2RWD5.js.map
251
+ //# sourceMappingURL=app-config-B_QqZFbl.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"app-config-BHA2RWD5.js","sources":["../src/app-config.ts"],"sourcesContent":["/**\n * Canonical persistent configuration for imsg-mcp — one JSON file that carries\n * both the flat TUI keys (theme / accentColor) AND the `interpret` block that\n * configures media interpretation (Stage 2 core: chains, providers, toggles).\n *\n * Resolution order (first one found wins) — unchanged from the original\n * tui-config module so existing files keep loading:\n * 1. $XDG_CONFIG_HOME/imsg-mcp/config.json\n * 2. $HOME/.config/imsg-mcp/config.json\n * 3. $HOME/.imsg-mcp/config.json (matches the slugs.db location)\n *\n * `src/tui-config.ts` re-exports this module verbatim for back-compat.\n *\n * API keys are NEVER stored in config.json. They live in\n * `~/.imsg-mcp/credentials.json` (chmod 600, `{ \"<providerName>\": \"sk-…\" }`)\n * or the legacy `IMSG_TRANSCRIBE_*` env vars, and are merged into providers only\n * at resolution time (`resolveInterpretConfig`).\n */\n\nimport { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { z } from \"zod\";\nimport { getTranscribeCloudConfig } from \"./config.js\";\nimport type { AutoMode, InterpretChains, InterpretConfig } from \"./media-intel.js\";\nimport type { ProviderConfig, ProviderPreset } from \"./media-providers.js\";\n\n// ── Schema ────────────────────────────────────────────────────────────────\n\nconst HEX6 = /^#[0-9a-fA-F]{6}$/;\n\n/** Preset names accepted in the `interpret.providers[].preset` field. Kept as a\n * literal tuple so Zod can build an enum without a runtime import of the\n * providers module (and asserted to stay in sync with `ProviderPreset`). */\nconst PROVIDER_PRESET_NAMES = [\n \"openai\",\n \"groq\",\n \"openrouter\",\n \"cloudflare\",\n \"huggingface\",\n \"ollama\",\n] as const satisfies readonly ProviderPreset[];\n\nconst ProviderModelsSchema = z\n .object({ transcribe: z.string().optional(), vision: z.string().optional() })\n .optional();\n\n/** A provider profile as stored in config.json — NO apiKey (that lives in\n * credentials.json / env and is merged in at resolution time). */\nconst ProviderConfigSchema = z\n .object({\n name: z.string().min(1),\n preset: z.enum(PROVIDER_PRESET_NAMES).optional(),\n baseUrl: z.string().url().optional(),\n accountId: z.string().optional(),\n models: ProviderModelsSchema,\n })\n .refine((p) => Boolean(p.preset) || Boolean(p.baseUrl), {\n message: \"provider needs either a preset or a baseUrl\",\n });\n\nconst ChainsSchema = z\n .object({\n audio: z.array(z.string()).default([\"apple\", \"local\"]),\n image: z.array(z.string()).default([]),\n video: z.array(z.string()).default([]),\n })\n .default({});\n\nconst NudgeSchema = z\n .object({\n enabled: z.boolean().default(true),\n tier2SyncNow: z.boolean().default(false),\n timeoutSeconds: z.number().int().positive().default(30),\n })\n .default({});\n\nexport const InterpretConfigSchema = z.object({\n /** Auto-interpretation gate. \"free\" (default) never makes a paid call without\n * an explicit force; \"all\" runs the full chain incl. cloud; \"off\" disables. */\n auto: z.enum([\"all\", \"free\", \"off\"]).default(\"free\"),\n /** Inline cached transcripts/captions in read surfaces (get_messages, TUI). */\n inlineTranscripts: z.boolean().default(true),\n /** Confirm before an export triggers more than this many uncached cloud calls. */\n exportConfirmThreshold: z.number().int().nonnegative().default(25),\n chains: ChainsSchema,\n providers: z.array(ProviderConfigSchema).default([]),\n nudge: NudgeSchema,\n});\n\nexport const AppConfigSchema = z.object({\n /** Glyph preset. \"safe\" is the universally-renderable default. */\n theme: z.enum([\"safe\", \"powerline\"]).default(\"safe\"),\n /** 6-digit hex color used to derive the whole UI palette. */\n accentColor: z.string().regex(HEX6, \"must be a 6-digit hex like #RRGGBB\").default(\"#1982FC\"),\n /** Media-interpretation config (optional — absent on TUI-only configs). */\n interpret: InterpretConfigSchema.optional(),\n});\n\nexport type AppConfig = z.infer<typeof AppConfigSchema>;\nexport type InterpretConfigInput = z.infer<typeof InterpretConfigSchema>;\n\n/** Back-compat alias — the TUI only ever reads theme/accentColor. */\nexport const TuiConfigSchema = AppConfigSchema;\nexport type TuiConfig = AppConfig;\n\nexport const DEFAULT_TUI_CONFIG: TuiConfig = {\n theme: \"safe\",\n accentColor: \"#1982FC\",\n};\n\n/** Free-first interpret defaults used when the block is absent from config. */\nexport const DEFAULT_INTERPRET_CONFIG: InterpretConfigInput = InterpretConfigSchema.parse({});\n\n// ── Path resolution ───────────────────────────────────────────────────────\n\n/** Candidate paths we try to read from, in order. Per the XDG spec, `~/.config`\n * is the DEFAULT VALUE of `$XDG_CONFIG_HOME` — not an additional search path —\n * so when the env var is set we must not fall through to the real `~/.config`\n * (that fall-through also let a dev machine's real config leak into tests that\n * point XDG at a temp dir). */\nfunction candidatePaths(): string[] {\n const home = homedir();\n const xdgBase = process.env.XDG_CONFIG_HOME || join(home, \".config\");\n return [join(xdgBase, \"imsg-mcp\", \"config.json\"), join(home, \".imsg-mcp\", \"config.json\")];\n}\n\n/** Where the file actually lives (first existing candidate), or null. */\nexport function findTuiConfigPath(): string | null {\n for (const p of candidatePaths()) {\n if (existsSync(p)) return p;\n }\n return null;\n}\n\n/** Where to write a fresh config file. Returns the *first* candidate so\n * XDG-style wins on a clean machine. */\nexport function defaultTuiConfigPath(): string {\n return candidatePaths()[0] ?? candidatePaths()[1];\n}\n\n// ── Loader ────────────────────────────────────────────────────────────────\n\nexport interface LoadedTuiConfig {\n config: AppConfig;\n /** Path of the file we read from, or `null` if defaults were used. */\n source: string | null;\n /** Human-readable warnings (parse errors, schema errors). Empty when clean. */\n warnings: string[];\n}\n\nexport function loadTuiConfig(): LoadedTuiConfig {\n const warnings: string[] = [];\n const path = findTuiConfigPath();\n if (!path) return { config: { ...DEFAULT_TUI_CONFIG }, source: null, warnings };\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(readFileSync(path, \"utf8\"));\n } catch (err) {\n warnings.push(\n `config: failed to read ${path} (${err instanceof Error ? err.message : String(err)}); using defaults`,\n );\n return { config: { ...DEFAULT_TUI_CONFIG }, source: path, warnings };\n }\n\n const result = AppConfigSchema.safeParse(parsed);\n if (result.success) return { config: result.data, source: path, warnings };\n\n // Full parse failed. Degrade gracefully: if the flat TUI keys alone are valid,\n // keep them (a malformed `interpret` block should not blow away the theme).\n const tuiOnly = AppConfigSchema.pick({ theme: true, accentColor: true }).safeParse(parsed);\n const issues = result.error.issues\n .map((i) => `${i.path.join(\".\") || \"<root>\"}: ${i.message}`)\n .join(\"; \");\n if (tuiOnly.success) {\n warnings.push(`config: ${path} has invalid fields (${issues}); ignoring them`);\n return { config: { ...tuiOnly.data }, source: path, warnings };\n }\n warnings.push(`config: ${path} has invalid fields (${issues}); using defaults`);\n return { config: { ...DEFAULT_TUI_CONFIG }, source: path, warnings };\n}\n\n// ── Writer (used by `imsg config edit` + `imsg setup`) ────────────────────\n\nexport function writeTuiConfig(config: AppConfig, path = defaultTuiConfigPath()): string {\n // Validate before writing so we never persist garbage.\n const validated = AppConfigSchema.parse(config);\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, `${JSON.stringify(validated, null, 2)}\\n`);\n return path;\n}\n\n// ── Credentials (chmod 600) ───────────────────────────────────────────────\n\n/** `~/.imsg-mcp/credentials.json` — `{ \"<providerName>\": \"<apiKey>\" }`. */\nexport function credentialsPath(): string {\n return join(homedir(), \".imsg-mcp\", \"credentials.json\");\n}\n\nexport function readCredentials(): Record<string, string> {\n const path = credentialsPath();\n if (!existsSync(path)) return {};\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf8\"));\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(parsed)) {\n if (typeof v === \"string\") out[k] = v;\n }\n return out;\n }\n } catch {\n // Corrupt credentials file — treat as empty (never throw on read).\n }\n return {};\n}\n\n/** Write the whole credentials map, enforcing 0600 on the file (and 0700 dir). */\nexport function writeCredentials(creds: Record<string, string>): string {\n const path = credentialsPath();\n const dir = dirname(path);\n mkdirSync(dir, { recursive: true });\n try {\n chmodSync(dir, 0o700);\n } catch {\n // Best-effort — a shared dir may already exist with other perms.\n }\n writeFileSync(path, `${JSON.stringify(creds, null, 2)}\\n`, { mode: 0o600 });\n // writeFileSync's `mode` is masked by umask on CREATE and ignored when the\n // file already exists — chmod unconditionally so 0600 is guaranteed.\n chmodSync(path, 0o600);\n return path;\n}\n\n/** Set (or clear, when key is empty) one provider's credential. */\nexport function setCredential(name: string, key: string): void {\n const creds = readCredentials();\n if (key) creds[name] = key;\n else delete creds[name];\n writeCredentials(creds);\n}\n\n// ── Interpret-config resolution (config + credentials + env → service) ─────\n\n/** The env-mapped implicit provider name (legacy IMSG_TRANSCRIBE_* path). */\nexport const ENV_PROVIDER_NAME = \"env\";\n\n/** Interpret config ready for `MediaIntelService`, plus the surfacing toggles\n * that frontends (Stage 4/6/7) read. Providers carry their merged apiKey. */\nexport interface ResolvedInterpretConfig extends InterpretConfig {\n inlineTranscripts: boolean;\n exportConfirmThreshold: number;\n nudge: { enabled: boolean; tier2SyncNow: boolean; timeoutSeconds: number };\n /** Where the config was read from (null = defaults). */\n configPath: string | null;\n warnings: string[];\n}\n\n/**\n * Resolve the full interpret configuration:\n * - start from the config file's `interpret` block (or free-first defaults),\n * - merge API keys from credentials.json into each named provider,\n * - map the legacy `IMSG_TRANSCRIBE_*` env vars to an implicit `env` provider\n * (and append `provider:env` to the audio chain if it has no provider yet),\n * preserving the shipped v1.7.0 cloud-transcription fallback.\n */\nexport function resolveInterpretConfig(): ResolvedInterpretConfig {\n const loaded = loadTuiConfig();\n const warnings = [...loaded.warnings];\n const block = InterpretConfigSchema.parse(loaded.config.interpret ?? {});\n const creds = readCredentials();\n\n const providers: ProviderConfig[] = block.providers.map((p) => ({\n ...p,\n apiKey: creds[p.name],\n }));\n const chains: InterpretChains = {\n audio: [...block.chains.audio],\n image: [...block.chains.image],\n video: [...block.chains.video],\n };\n\n // Legacy env fallback → implicit provider, if not already configured by name.\n const envCloud = getTranscribeCloudConfig();\n if (envCloud && !providers.some((p) => p.name === ENV_PROVIDER_NAME)) {\n providers.push({\n name: ENV_PROVIDER_NAME,\n baseUrl: envCloud.baseUrl,\n apiKey: envCloud.apiKey,\n models: { transcribe: envCloud.model },\n });\n if (!chains.audio.some((l) => l.startsWith(\"provider:\"))) {\n chains.audio.push(`provider:${ENV_PROVIDER_NAME}`);\n }\n }\n\n const auto: AutoMode = block.auto;\n return {\n auto,\n chains,\n providers,\n inlineTranscripts: block.inlineTranscripts,\n exportConfirmThreshold: block.exportConfirmThreshold,\n nudge: block.nudge,\n configPath: loaded.source,\n warnings,\n };\n}\n\n// ── Layered resolution (CLI > env > config > defaults) — TUI theme/accent ──\n\nexport interface TuiConfigOverrides {\n /** From `imsg --theme=...` */\n cliTheme?: string;\n /** From `imsg --accent=...` */\n cliAccent?: string;\n}\n\nexport interface ResolvedTuiConfig {\n theme: TuiConfig[\"theme\"];\n accentColor: string;\n /** Where each value came from, useful for `imsg config show`. */\n origin: {\n theme: \"cli\" | \"env\" | \"config\" | \"default\";\n accentColor: \"cli\" | \"env\" | \"config\" | \"default\";\n };\n /** The on-disk file path that contributed (or `null` if no file). */\n configPath: string | null;\n /** Any warnings raised during loading (malformed file, invalid env, etc). */\n warnings: string[];\n}\n\nexport function resolveTuiConfig(overrides: TuiConfigOverrides = {}): ResolvedTuiConfig {\n const loaded = loadTuiConfig();\n const warnings = [...loaded.warnings];\n\n // Theme precedence: CLI > env > config > default\n let theme: TuiConfig[\"theme\"] = loaded.config.theme;\n let themeOrigin: ResolvedTuiConfig[\"origin\"][\"theme\"] = loaded.source ? \"config\" : \"default\";\n\n if (process.env.IMSG_TUI_THEME) {\n const t = process.env.IMSG_TUI_THEME;\n if (t === \"safe\" || t === \"powerline\") {\n theme = t;\n themeOrigin = \"env\";\n } else {\n warnings.push(`IMSG_TUI_THEME=\"${t}\" is not \"safe\" or \"powerline\"; ignoring`);\n }\n }\n if (overrides.cliTheme !== undefined) {\n if (overrides.cliTheme === \"safe\" || overrides.cliTheme === \"powerline\") {\n theme = overrides.cliTheme;\n themeOrigin = \"cli\";\n } else {\n warnings.push(`--theme=\"${overrides.cliTheme}\" is not \"safe\" or \"powerline\"; ignoring`);\n }\n }\n\n // Accent precedence: CLI > env > config > default\n let accentColor = loaded.config.accentColor;\n let accentOrigin: ResolvedTuiConfig[\"origin\"][\"accentColor\"] = loaded.source\n ? \"config\"\n : \"default\";\n\n if (process.env.IMSG_TUI_ACCENT) {\n if (HEX6.test(process.env.IMSG_TUI_ACCENT)) {\n accentColor = process.env.IMSG_TUI_ACCENT;\n accentOrigin = \"env\";\n } else {\n warnings.push(\n `IMSG_TUI_ACCENT=\"${process.env.IMSG_TUI_ACCENT}\" is not a 6-digit hex; ignoring`,\n );\n }\n }\n if (overrides.cliAccent !== undefined) {\n if (HEX6.test(overrides.cliAccent)) {\n accentColor = overrides.cliAccent;\n accentOrigin = \"cli\";\n } else {\n warnings.push(`--accent=\"${overrides.cliAccent}\" is not a 6-digit hex; ignoring`);\n }\n }\n\n return {\n theme,\n accentColor,\n origin: { theme: themeOrigin, accentColor: accentOrigin },\n configPath: loaded.source,\n warnings,\n };\n}\n"],"names":[],"mappings":";;;;;AA6BA,MAAM,OAAO;AAKb,MAAM,wBAAwB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,MAAM,uBAAuB,EAC1B,OAAO,EAAE,YAAY,EAAE,SAAS,SAAA,GAAY,QAAQ,EAAE,OAAA,EAAS,WAAS,CAAG,EAC3E,SAAA;AAIH,MAAM,uBAAuB,EAC1B,OAAO;AAAA,EACN,MAAM,EAAE,SAAS,IAAI,CAAC;AAAA,EACtB,QAAQ,EAAE,KAAK,qBAAqB,EAAE,SAAA;AAAA,EACtC,SAAS,EAAE,O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AS,KAAK,aAAa,UAAU,SAAS,kCAAkC;AAAA,IAClF;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,QAAQ,EAAE,OAAO,aAAa,aAAa,aAAA;AAAA,IAC3C,YAAY,OAAO;AAAA,IACnB;AAAA,EAAA;AAEJ;"}
1
+ {"version":3,"file":"app-config-B_QqZFbl.js","sources":["../src/app-config.ts"],"sourcesContent":["/**\n * Canonical persistent configuration for imsg-mcp — one JSON file that carries\n * both the flat TUI keys (theme / accentColor) AND the `interpret` block that\n * configures media interpretation (Stage 2 core: chains, providers, toggles).\n *\n * Resolution order (first one found wins) — unchanged from the original\n * tui-config module so existing files keep loading:\n * 1. $XDG_CONFIG_HOME/imsg-mcp/config.json\n * 2. $HOME/.config/imsg-mcp/config.json\n * 3. $HOME/.imsg-mcp/config.json (matches the slugs.db location)\n *\n * `src/tui-config.ts` re-exports this module verbatim for back-compat.\n *\n * API keys are NEVER stored in config.json. They live in\n * `~/.imsg-mcp/credentials.json` (chmod 600, `{ \"<providerName>\": \"sk-…\" }`)\n * or the legacy `IMSG_TRANSCRIBE_*` env vars, and are merged into providers only\n * at resolution time (`resolveInterpretConfig`).\n */\n\nimport { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { z } from \"zod\";\nimport { getTranscribeCloudConfig } from \"./config.js\";\nimport type { AutoMode, InterpretChains, InterpretConfig } from \"./media-intel.js\";\nimport type { ProviderConfig, ProviderPreset } from \"./media-providers.js\";\n\n// ── Schema ────────────────────────────────────────────────────────────────\n\nconst HEX6 = /^#[0-9a-fA-F]{6}$/;\n\n/** Preset names accepted in the `interpret.providers[].preset` field. Kept as a\n * literal tuple so Zod can build an enum without a runtime import of the\n * providers module (and asserted to stay in sync with `ProviderPreset`). */\nconst PROVIDER_PRESET_NAMES = [\n \"openai\",\n \"groq\",\n \"openrouter\",\n \"cloudflare\",\n \"huggingface\",\n \"ollama\",\n] as const satisfies readonly ProviderPreset[];\n\nconst ProviderModelsSchema = z\n .object({ transcribe: z.string().optional(), vision: z.string().optional() })\n .optional();\n\n/** A provider profile as stored in config.json — NO apiKey (that lives in\n * credentials.json / env and is merged in at resolution time). */\nconst ProviderConfigSchema = z\n .object({\n name: z.string().min(1),\n preset: z.enum(PROVIDER_PRESET_NAMES).optional(),\n baseUrl: z.string().url().optional(),\n accountId: z.string().optional(),\n models: ProviderModelsSchema,\n })\n .refine((p) => Boolean(p.preset) || Boolean(p.baseUrl), {\n message: \"provider needs either a preset or a baseUrl\",\n });\n\nconst ChainsSchema = z\n .object({\n audio: z.array(z.string()).default([\"apple\", \"local\"]),\n image: z.array(z.string()).default([]),\n video: z.array(z.string()).default([]),\n })\n .default({});\n\nconst NudgeSchema = z\n .object({\n enabled: z.boolean().default(true),\n tier2SyncNow: z.boolean().default(false),\n timeoutSeconds: z.number().int().positive().default(30),\n })\n .default({});\n\nexport const InterpretConfigSchema = z.object({\n /** Auto-interpretation gate. \"free\" (default) never makes a paid call without\n * an explicit force; \"all\" runs the full chain incl. cloud; \"off\" disables. */\n auto: z.enum([\"all\", \"free\", \"off\"]).default(\"free\"),\n /** Inline cached transcripts/captions in read surfaces (get_messages, TUI). */\n inlineTranscripts: z.boolean().default(true),\n /** Confirm before an export triggers more than this many uncached cloud calls. */\n exportConfirmThreshold: z.number().int().nonnegative().default(25),\n chains: ChainsSchema,\n providers: z.array(ProviderConfigSchema).default([]),\n nudge: NudgeSchema,\n});\n\nexport const AppConfigSchema = z.object({\n /** Glyph preset. \"safe\" is the universally-renderable default. */\n theme: z.enum([\"safe\", \"powerline\"]).default(\"safe\"),\n /** 6-digit hex color used to derive the whole UI palette. */\n accentColor: z.string().regex(HEX6, \"must be a 6-digit hex like #RRGGBB\").default(\"#1982FC\"),\n /** Media-interpretation config (optional — absent on TUI-only configs). */\n interpret: InterpretConfigSchema.optional(),\n});\n\nexport type AppConfig = z.infer<typeof AppConfigSchema>;\nexport type InterpretConfigInput = z.infer<typeof InterpretConfigSchema>;\n\n/** Back-compat alias — the TUI only ever reads theme/accentColor. */\nexport const TuiConfigSchema = AppConfigSchema;\nexport type TuiConfig = AppConfig;\n\nexport const DEFAULT_TUI_CONFIG: TuiConfig = {\n theme: \"safe\",\n accentColor: \"#1982FC\",\n};\n\n/** Free-first interpret defaults used when the block is absent from config. */\nexport const DEFAULT_INTERPRET_CONFIG: InterpretConfigInput = InterpretConfigSchema.parse({});\n\n// ── Path resolution ───────────────────────────────────────────────────────\n\n/** Candidate paths we try to read from, in order. Per the XDG spec, `~/.config`\n * is the DEFAULT VALUE of `$XDG_CONFIG_HOME` — not an additional search path —\n * so when the env var is set we must not fall through to the real `~/.config`\n * (that fall-through also let a dev machine's real config leak into tests that\n * point XDG at a temp dir). */\nfunction candidatePaths(): string[] {\n const home = homedir();\n const xdgBase = process.env.XDG_CONFIG_HOME || join(home, \".config\");\n return [join(xdgBase, \"imsg-mcp\", \"config.json\"), join(home, \".imsg-mcp\", \"config.json\")];\n}\n\n/** Where the file actually lives (first existing candidate), or null. */\nexport function findTuiConfigPath(): string | null {\n for (const p of candidatePaths()) {\n if (existsSync(p)) return p;\n }\n return null;\n}\n\n/** Where to write a fresh config file. Returns the *first* candidate so\n * XDG-style wins on a clean machine. */\nexport function defaultTuiConfigPath(): string {\n return candidatePaths()[0] ?? candidatePaths()[1];\n}\n\n// ── Loader ────────────────────────────────────────────────────────────────\n\nexport interface LoadedTuiConfig {\n config: AppConfig;\n /** Path of the file we read from, or `null` if defaults were used. */\n source: string | null;\n /** Human-readable warnings (parse errors, schema errors). Empty when clean. */\n warnings: string[];\n}\n\nexport function loadTuiConfig(): LoadedTuiConfig {\n const warnings: string[] = [];\n const path = findTuiConfigPath();\n if (!path) return { config: { ...DEFAULT_TUI_CONFIG }, source: null, warnings };\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(readFileSync(path, \"utf8\"));\n } catch (err) {\n warnings.push(\n `config: failed to read ${path} (${err instanceof Error ? err.message : String(err)}); using defaults`,\n );\n return { config: { ...DEFAULT_TUI_CONFIG }, source: path, warnings };\n }\n\n const result = AppConfigSchema.safeParse(parsed);\n if (result.success) return { config: result.data, source: path, warnings };\n\n // Full parse failed. Degrade gracefully: if the flat TUI keys alone are valid,\n // keep them (a malformed `interpret` block should not blow away the theme).\n const tuiOnly = AppConfigSchema.pick({ theme: true, accentColor: true }).safeParse(parsed);\n const issues = result.error.issues\n .map((i) => `${i.path.join(\".\") || \"<root>\"}: ${i.message}`)\n .join(\"; \");\n if (tuiOnly.success) {\n warnings.push(`config: ${path} has invalid fields (${issues}); ignoring them`);\n return { config: { ...tuiOnly.data }, source: path, warnings };\n }\n warnings.push(`config: ${path} has invalid fields (${issues}); using defaults`);\n return { config: { ...DEFAULT_TUI_CONFIG }, source: path, warnings };\n}\n\n// ── Writer (used by `imsg config edit` + `imsg setup`) ────────────────────\n\nexport function writeTuiConfig(config: AppConfig, path = defaultTuiConfigPath()): string {\n // Validate before writing so we never persist garbage.\n const validated = AppConfigSchema.parse(config);\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, `${JSON.stringify(validated, null, 2)}\\n`);\n return path;\n}\n\n// ── Credentials (chmod 600) ───────────────────────────────────────────────\n\n/** `~/.imsg-mcp/credentials.json` — `{ \"<providerName>\": \"<apiKey>\" }`. */\nexport function credentialsPath(): string {\n return join(homedir(), \".imsg-mcp\", \"credentials.json\");\n}\n\nexport function readCredentials(): Record<string, string> {\n const path = credentialsPath();\n if (!existsSync(path)) return {};\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf8\"));\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(parsed)) {\n if (typeof v === \"string\") out[k] = v;\n }\n return out;\n }\n } catch {\n // Corrupt credentials file — treat as empty (never throw on read).\n }\n return {};\n}\n\n/** Write the whole credentials map, enforcing 0600 on the file (and 0700 dir). */\nexport function writeCredentials(creds: Record<string, string>): string {\n const path = credentialsPath();\n const dir = dirname(path);\n mkdirSync(dir, { recursive: true });\n try {\n chmodSync(dir, 0o700);\n } catch {\n // Best-effort — a shared dir may already exist with other perms.\n }\n writeFileSync(path, `${JSON.stringify(creds, null, 2)}\\n`, { mode: 0o600 });\n // writeFileSync's `mode` is masked by umask on CREATE and ignored when the\n // file already exists — chmod unconditionally so 0600 is guaranteed.\n chmodSync(path, 0o600);\n return path;\n}\n\n/** Set (or clear, when key is empty) one provider's credential. */\nexport function setCredential(name: string, key: string): void {\n const creds = readCredentials();\n if (key) creds[name] = key;\n else delete creds[name];\n writeCredentials(creds);\n}\n\n// ── Interpret-config resolution (config + credentials + env → service) ─────\n\n/** The env-mapped implicit provider name (legacy IMSG_TRANSCRIBE_* path). */\nexport const ENV_PROVIDER_NAME = \"env\";\n\n/** Interpret config ready for `MediaIntelService`, plus the surfacing toggles\n * that frontends (Stage 4/6/7) read. Providers carry their merged apiKey. */\nexport interface ResolvedInterpretConfig extends InterpretConfig {\n inlineTranscripts: boolean;\n exportConfirmThreshold: number;\n nudge: { enabled: boolean; tier2SyncNow: boolean; timeoutSeconds: number };\n /** Where the config was read from (null = defaults). */\n configPath: string | null;\n warnings: string[];\n}\n\n/**\n * Resolve the full interpret configuration:\n * - start from the config file's `interpret` block (or free-first defaults),\n * - merge API keys from credentials.json into each named provider,\n * - map the legacy `IMSG_TRANSCRIBE_*` env vars to an implicit `env` provider\n * (and append `provider:env` to the audio chain if it has no provider yet),\n * preserving the shipped v1.7.0 cloud-transcription fallback.\n */\nexport function resolveInterpretConfig(): ResolvedInterpretConfig {\n const loaded = loadTuiConfig();\n const warnings = [...loaded.warnings];\n const block = InterpretConfigSchema.parse(loaded.config.interpret ?? {});\n const creds = readCredentials();\n\n const providers: ProviderConfig[] = block.providers.map((p) => ({\n ...p,\n apiKey: creds[p.name],\n }));\n const chains: InterpretChains = {\n audio: [...block.chains.audio],\n image: [...block.chains.image],\n video: [...block.chains.video],\n };\n\n // Legacy env fallback → implicit provider, if not already configured by name.\n const envCloud = getTranscribeCloudConfig();\n if (envCloud && !providers.some((p) => p.name === ENV_PROVIDER_NAME)) {\n providers.push({\n name: ENV_PROVIDER_NAME,\n baseUrl: envCloud.baseUrl,\n apiKey: envCloud.apiKey,\n models: { transcribe: envCloud.model },\n });\n if (!chains.audio.some((l) => l.startsWith(\"provider:\"))) {\n chains.audio.push(`provider:${ENV_PROVIDER_NAME}`);\n }\n }\n\n const auto: AutoMode = block.auto;\n return {\n auto,\n chains,\n providers,\n inlineTranscripts: block.inlineTranscripts,\n exportConfirmThreshold: block.exportConfirmThreshold,\n nudge: block.nudge,\n configPath: loaded.source,\n warnings,\n };\n}\n\n// ── Layered resolution (CLI > env > config > defaults) — TUI theme/accent ──\n\nexport interface TuiConfigOverrides {\n /** From `imsg --theme=...` */\n cliTheme?: string;\n /** From `imsg --accent=...` */\n cliAccent?: string;\n}\n\nexport interface ResolvedTuiConfig {\n theme: TuiConfig[\"theme\"];\n accentColor: string;\n /** Where each value came from, useful for `imsg config show`. */\n origin: {\n theme: \"cli\" | \"env\" | \"config\" | \"default\";\n accentColor: \"cli\" | \"env\" | \"config\" | \"default\";\n };\n /** The on-disk file path that contributed (or `null` if no file). */\n configPath: string | null;\n /** Any warnings raised during loading (malformed file, invalid env, etc). */\n warnings: string[];\n}\n\nexport function resolveTuiConfig(overrides: TuiConfigOverrides = {}): ResolvedTuiConfig {\n const loaded = loadTuiConfig();\n const warnings = [...loaded.warnings];\n\n // Theme precedence: CLI > env > config > default\n let theme: TuiConfig[\"theme\"] = loaded.config.theme;\n let themeOrigin: ResolvedTuiConfig[\"origin\"][\"theme\"] = loaded.source ? \"config\" : \"default\";\n\n if (process.env.IMSG_TUI_THEME) {\n const t = process.env.IMSG_TUI_THEME;\n if (t === \"safe\" || t === \"powerline\") {\n theme = t;\n themeOrigin = \"env\";\n } else {\n warnings.push(`IMSG_TUI_THEME=\"${t}\" is not \"safe\" or \"powerline\"; ignoring`);\n }\n }\n if (overrides.cliTheme !== undefined) {\n if (overrides.cliTheme === \"safe\" || overrides.cliTheme === \"powerline\") {\n theme = overrides.cliTheme;\n themeOrigin = \"cli\";\n } else {\n warnings.push(`--theme=\"${overrides.cliTheme}\" is not \"safe\" or \"powerline\"; ignoring`);\n }\n }\n\n // Accent precedence: CLI > env > config > default\n let accentColor = loaded.config.accentColor;\n let accentOrigin: ResolvedTuiConfig[\"origin\"][\"accentColor\"] = loaded.source\n ? \"config\"\n : \"default\";\n\n if (process.env.IMSG_TUI_ACCENT) {\n if (HEX6.test(process.env.IMSG_TUI_ACCENT)) {\n accentColor = process.env.IMSG_TUI_ACCENT;\n accentOrigin = \"env\";\n } else {\n warnings.push(\n `IMSG_TUI_ACCENT=\"${process.env.IMSG_TUI_ACCENT}\" is not a 6-digit hex; ignoring`,\n );\n }\n }\n if (overrides.cliAccent !== undefined) {\n if (HEX6.test(overrides.cliAccent)) {\n accentColor = overrides.cliAccent;\n accentOrigin = \"cli\";\n } else {\n warnings.push(`--accent=\"${overrides.cliAccent}\" is not a 6-digit hex; ignoring`);\n }\n }\n\n return {\n theme,\n accentColor,\n origin: { theme: themeOrigin, accentColor: accentOrigin },\n configPath: loaded.source,\n warnings,\n };\n}\n"],"names":[],"mappings":";;;;;AA6BA,MAAM,OAAO;AAKb,MAAM,wBAAwB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,MAAM,uBAAuB,EAC1B,OAAO,EAAE,YAAY,EAAE,SAAS,SAAA,GAAY,QAAQ,EAAE,OAAA,EAAS,WAAS,CAAG,EAC3E,SAAA;AAIH,MAAM,uBAAuB,EAC1B,OAAO;AAAA,EACN,MAAM,EAAE,SAAS,IAAI,CAAC;AAAA,EACtB,QAAQ,EAAE,KAAK,qBAAqB,EAAE,SAAA;AAAA,EACtC,SAAS,EAAE,OAAA,EAAS,IAAA,EAAM,SAAA;AAAA,EAC1B,WAAW,EAAE,OA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F;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,QAAQ,EAAE,OAAO,aAAa,aAAa,aAAA;AAAA,IAC3C,YAAY,OAAO;AAAA,IACnB;AAAA,EAAA;AAEJ;"}
@@ -1,5 +1,5 @@
1
1
  import { existsSync } from "node:fs";
2
- import { s as syncNowViaSystemEvents, o as openConversationInMessages } from "./shutdown-CWS6IvCE.js";
2
+ import { s as syncNowViaSystemEvents, o as openConversationInMessages } from "./shutdown-Dnj088id.js";
3
3
  function defaultAttachmentSyncDeps() {
4
4
  return {
5
5
  fileExists: (p) => existsSync(p),
@@ -76,4 +76,4 @@ export {
76
76
  defaultAttachmentSyncDeps,
77
77
  ensureAttachmentDownloaded
78
78
  };
79
- //# sourceMappingURL=attachment-sync-CIoN37ih.js.map
79
+ //# sourceMappingURL=attachment-sync-DqIvfxPv.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"attachment-sync-CIoN37ih.js","sources":["../src/attachment-sync.ts"],"sourcesContent":["/**\n * Attachment sync nudge (Stage 7) — best-effort, tiered coaxing of Messages.app\n * into downloading an attachment whose bytes aren't on disk yet\n * (`transfer_state === -1`, purged/never-downloaded). iCloud syncs Messages\n * media only while a conversation is OPEN, and there is no public download API\n * (IMTransferAgent is a private SIP'd daemon). So we:\n *\n * Tier 1 (default): open the conversation in Messages via an `imessage:` URL\n * — community-verified to make the app pull that thread's media — then poll\n * `existsSync` until the file appears or a timeout elapses.\n * Tier 2 (opt-in, `nudge.tier2SyncNow`): UI-script Messages ▸ Settings ▸\n * iMessage ▸ \"Sync Now\". Needs Accessibility permission; we detect the\n * missing-permission error and return an actionable hint.\n * Tier 3: per-conversation \"download all\" UI script — documented only\n * (too fragile across macOS versions), no code here.\n *\n * This module is PURE ORCHESTRATION: every side effect (AppleScript, fs, timers)\n * is injected via {@link AttachmentSyncDeps}, so the tier/poll/timeout logic is\n * unit-tested deterministically with no real app launch and no real clock. The\n * default deps wire the real AppleScript primitives (themselves mocked under\n * Vitest) + node fs/timers.\n */\nimport { existsSync } from \"node:fs\";\nimport {\n openConversationInMessages,\n type SyncNowOutcome,\n syncNowViaSystemEvents,\n} from \"./applescript.js\";\n\nexport type { SyncNowOutcome };\n\n/** The subset of the resolved `nudge` config this module needs. */\nexport interface AttachmentSyncConfig {\n /** Master switch — when false, no tier runs and we never touch Messages. */\n enabled: boolean;\n /** Enable Tier 2 (System Events \"Sync Now\"). Default off. */\n tier2SyncNow: boolean;\n /** How long to wait for the file to appear after a nudge, in seconds. */\n timeoutSeconds: number;\n /** Poll cadence while waiting. Default 1000ms; floored at 100ms. */\n pollIntervalMs?: number;\n}\n\n/** Highest tier that actually ran (0 = none). */\nexport type SyncTier = 0 | 1 | 2;\n\nexport interface EnsureDownloadedInput {\n /** Absolute path (already `~`-expanded) we expect the file to appear at. */\n filePath: string;\n /** Chat identifier (handle or GUID) to open in Messages for Tier 1. */\n chatId?: string | null;\n /** `attachment.transfer_state` from chat.db (-1 = undownloaded); advisory. */\n transferState?: number | null;\n}\n\nexport interface EnsureDownloadedResult {\n /** True iff the file is on disk when we return. */\n downloaded: boolean;\n /** True iff we actually ran at least one tier (vs short-circuited). */\n attempted: boolean;\n /** Highest tier attempted. */\n tier: SyncTier;\n /** Machine-readable reason when not downloaded / skipped. */\n reason?: string;\n /** Human-actionable remediation (e.g. grant Accessibility). */\n hint?: string;\n}\n\n/** All side effects the orchestrator needs, injectable for tests. */\nexport interface AttachmentSyncDeps {\n fileExists(path: string): boolean;\n openConversation(chatId: string): Promise<void>;\n syncNow(): Promise<SyncNowOutcome>;\n sleep(ms: number): Promise<void>;\n now(): number;\n}\n\n/** Production deps: real fs + timers + AppleScript (AppleScript self-mocks under Vitest). */\nexport function defaultAttachmentSyncDeps(): AttachmentSyncDeps {\n return {\n fileExists: (p) => existsSync(p),\n openConversation: (chatId) => openConversationInMessages(chatId),\n syncNow: () => syncNowViaSystemEvents(),\n sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),\n now: () => Date.now(),\n };\n}\n\nfunction errMsg(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\n/**\n * Poll `fileExists` until it's true or `timeoutMs` elapses (measured against\n * `deps.now()`). Checks immediately first — opening the chat may have already\n * pulled the file — then sleeps `pollIntervalMs` between checks.\n */\nasync function pollForFile(\n deps: AttachmentSyncDeps,\n path: string,\n timeoutMs: number,\n pollIntervalMs: number,\n): Promise<boolean> {\n const start = deps.now();\n if (deps.fileExists(path)) return true;\n while (deps.now() - start < timeoutMs) {\n await deps.sleep(pollIntervalMs);\n if (deps.fileExists(path)) return true;\n }\n return false;\n}\n\n/**\n * Ensure `input.filePath` is on disk, nudging Messages to download it if not.\n * Best-effort: returns a structured result rather than throwing. Idempotent and\n * cheap when the file already exists (no side effects) or when disabled.\n */\nexport async function ensureAttachmentDownloaded(\n input: EnsureDownloadedInput,\n config: AttachmentSyncConfig,\n deps: AttachmentSyncDeps = defaultAttachmentSyncDeps(),\n): Promise<EnsureDownloadedResult> {\n const { filePath } = input;\n\n // Already on disk → nothing to do (no app launch).\n if (deps.fileExists(filePath)) {\n return { downloaded: true, attempted: false, tier: 0 };\n }\n if (!config.enabled) {\n return { downloaded: false, attempted: false, tier: 0, reason: \"sync nudge disabled\" };\n }\n\n const pollIntervalMs = Math.max(100, config.pollIntervalMs ?? 1000);\n const timeoutMs = Math.max(1000, config.timeoutSeconds * 1000);\n let tier: SyncTier = 0;\n let hint: string | undefined;\n\n // ── Tier 1: open the conversation so Messages pulls its media ──\n if (input.chatId) {\n tier = 1;\n try {\n await deps.openConversation(input.chatId);\n } catch (e) {\n hint = `Could not open the conversation in Messages: ${errMsg(e)}`;\n }\n if (await pollForFile(deps, filePath, timeoutMs, pollIntervalMs)) {\n return { downloaded: true, attempted: true, tier };\n }\n } else {\n hint = \"No chat identifier available to open the conversation in Messages.\";\n }\n\n // ── Tier 2 (opt-in): System Events \"Sync Now\" ──\n if (config.tier2SyncNow) {\n tier = 2;\n const outcome = await deps.syncNow();\n if (!outcome.ok) {\n if (outcome.needsAccessibility) {\n return {\n downloaded: deps.fileExists(filePath),\n attempted: true,\n tier,\n reason: \"accessibility-permission-required\",\n hint: \"Sync Now needs Accessibility permission. Grant it in System Settings ▸ Privacy & Security ▸ Accessibility for your terminal/IDE, then retry.\",\n };\n }\n hint = outcome.error ?? hint ?? \"Sync Now failed.\";\n } else if (await pollForFile(deps, filePath, timeoutMs, pollIntervalMs)) {\n return { downloaded: true, attempted: true, tier };\n }\n }\n\n return {\n downloaded: deps.fileExists(filePath),\n attempted: tier > 0,\n tier,\n reason: tier === 0 ? \"no sync tier could run\" : \"attachment did not download in time\",\n hint,\n };\n}\n"],"names":[],"mappings":";;AA8EO,SAAS,4BAAgD;AAC9D,SAAO;AAAA,IACL,YAAY,CAAC,MAAM,WAAW,CAAC;AAAA,IAC/B,kBAAkB,CAAC,WAAW,2BAA2B,MAAM;AAAA,IAC/D,SAAS,MAAM,uBAAA;AAAA,IACf,OAAO,CAAC,OAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AAAA,IAC/D,KAAK,MAAM,KAAK,IAAA;AAAA,EAAI;AAExB;AAEA,SAAS,OAAO,GAAoB;AAClC,SAAO,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC;AAClD;AAOA,eAAe,YACb,MACA,MACA,WACA,gBACkB;AAClB,QAAM,QAAQ,KAAK,IAAA;AACnB,MAAI,KAAK,WAAW,IAAI,EAAG,QAAO;AAClC,SAAO,KAAK,QAAQ,QAAQ,WAAW;AACrC,UAAM,KAAK,MAAM,cAAc;AAC/B,QAAI,KAAK,WAAW,IAAI,EAAG,QAAO;AAAA,EACpC;AACA,SAAO;AACT;AAOA,eAAsB,2BACpB,OACA,QACA,OAA2B,6BACM;AACjC,QAAM,EAAE,aAAa;AAGrB,MAAI,KAAK,WAAW,QAAQ,GAAG;AAC7B,WAAO,EAAE,YAAY,MAAM,WAAW,OAAO,MAAM,EAAA;AAAA,EACrD;AACA,MAAI,CAAC,O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stage 7) — best-effort, tiered coaxing of Messages.app\n * into downloading an attachment whose bytes aren't on disk yet\n * (`transfer_state === -1`, purged/never-downloaded). iCloud syncs Messages\n * media only while a conversation is OPEN, and there is no public download API\n * (IMTransferAgent is a private SIP'd daemon). So we:\n *\n * Tier 1 (default): open the conversation in Messages via an `imessage:` URL\n * — community-verified to make the app pull that thread's media — then poll\n * `existsSync` until the file appears or a timeout elapses.\n * Tier 2 (opt-in, `nudge.tier2SyncNow`): UI-script Messages ▸ Settings ▸\n * iMessage ▸ \"Sync Now\". Needs Accessibility permission; we detect the\n * missing-permission error and return an actionable hint.\n * Tier 3: per-conversation \"download all\" UI script — documented only\n * (too fragile across macOS versions), no code here.\n *\n * This module is PURE ORCHESTRATION: every side effect (AppleScript, fs, timers)\n * is injected via {@link AttachmentSyncDeps}, so the tier/poll/timeout logic is\n * unit-tested deterministically with no real app launch and no real clock. The\n * default deps wire the real AppleScript primitives (themselves mocked under\n * Vitest) + node fs/timers.\n */\nimport { existsSync } from \"node:fs\";\nimport {\n openConversationInMessages,\n type SyncNowOutcome,\n syncNowViaSystemEvents,\n} from \"./applescript.js\";\n\nexport type { SyncNowOutcome };\n\n/** The subset of the resolved `nudge` config this module needs. */\nexport interface AttachmentSyncConfig {\n /** Master switch — when false, no tier runs and we never touch Messages. */\n enabled: boolean;\n /** Enable Tier 2 (System Events \"Sync Now\"). Default off. */\n tier2SyncNow: boolean;\n /** How long to wait for the file to appear after a nudge, in seconds. */\n timeoutSeconds: number;\n /** Poll cadence while waiting. Default 1000ms; floored at 100ms. */\n pollIntervalMs?: number;\n}\n\n/** Highest tier that actually ran (0 = none). */\nexport type SyncTier = 0 | 1 | 2;\n\nexport interface EnsureDownloadedInput {\n /** Absolute path (already `~`-expanded) we expect the file to appear at. */\n filePath: string;\n /** Chat identifier (handle or GUID) to open in Messages for Tier 1. */\n chatId?: string | null;\n /** `attachment.transfer_state` from chat.db (-1 = undownloaded); advisory. */\n transferState?: number | null;\n}\n\nexport interface EnsureDownloadedResult {\n /** True iff the file is on disk when we return. */\n downloaded: boolean;\n /** True iff we actually ran at least one tier (vs short-circuited). */\n attempted: boolean;\n /** Highest tier attempted. */\n tier: SyncTier;\n /** Machine-readable reason when not downloaded / skipped. */\n reason?: string;\n /** Human-actionable remediation (e.g. grant Accessibility). */\n hint?: string;\n}\n\n/** All side effects the orchestrator needs, injectable for tests. */\nexport interface AttachmentSyncDeps {\n fileExists(path: string): boolean;\n openConversation(chatId: string): Promise<void>;\n syncNow(): Promise<SyncNowOutcome>;\n sleep(ms: number): Promise<void>;\n now(): number;\n}\n\n/** Production deps: real fs + timers + AppleScript (AppleScript self-mocks under Vitest). */\nexport function defaultAttachmentSyncDeps(): AttachmentSyncDeps {\n return {\n fileExists: (p) => existsSync(p),\n openConversation: (chatId) => openConversationInMessages(chatId),\n syncNow: () => syncNowViaSystemEvents(),\n sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),\n now: () => Date.now(),\n };\n}\n\nfunction errMsg(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\n/**\n * Poll `fileExists` until it's true or `timeoutMs` elapses (measured against\n * `deps.now()`). Checks immediately first — opening the chat may have already\n * pulled the file — then sleeps `pollIntervalMs` between checks.\n */\nasync function pollForFile(\n deps: AttachmentSyncDeps,\n path: string,\n timeoutMs: number,\n pollIntervalMs: number,\n): Promise<boolean> {\n const start = deps.now();\n if (deps.fileExists(path)) return true;\n while (deps.now() - start < timeoutMs) {\n await deps.sleep(pollIntervalMs);\n if (deps.fileExists(path)) return true;\n }\n return false;\n}\n\n/**\n * Ensure `input.filePath` is on disk, nudging Messages to download it if not.\n * Best-effort: returns a structured result rather than throwing. Idempotent and\n * cheap when the file already exists (no side effects) or when disabled.\n */\nexport async function ensureAttachmentDownloaded(\n input: EnsureDownloadedInput,\n config: AttachmentSyncConfig,\n deps: AttachmentSyncDeps = defaultAttachmentSyncDeps(),\n): Promise<EnsureDownloadedResult> {\n const { filePath } = input;\n\n // Already on disk → nothing to do (no app launch).\n if (deps.fileExists(filePath)) {\n return { downloaded: true, attempted: false, tier: 0 };\n }\n if (!config.enabled) {\n return { downloaded: false, attempted: false, tier: 0, reason: \"sync nudge disabled\" };\n }\n\n const pollIntervalMs = Math.max(100, config.pollIntervalMs ?? 1000);\n const timeoutMs = Math.max(1000, config.timeoutSeconds * 1000);\n let tier: SyncTier = 0;\n let hint: string | undefined;\n\n // ── Tier 1: open the conversation so Messages pulls its media ──\n if (input.chatId) {\n tier = 1;\n try {\n await deps.openConversation(input.chatId);\n } catch (e) {\n hint = `Could not open the conversation in Messages: ${errMsg(e)}`;\n }\n if (await pollForFile(deps, filePath, timeoutMs, pollIntervalMs)) {\n return { downloaded: true, attempted: true, tier };\n }\n } else {\n hint = \"No chat identifier available to open the conversation in Messages.\";\n }\n\n // ── Tier 2 (opt-in): System Events \"Sync Now\" ──\n if (config.tier2SyncNow) {\n tier = 2;\n const outcome = await deps.syncNow();\n if (!outcome.ok) {\n if (outcome.needsAccessibility) {\n return {\n downloaded: deps.fileExists(filePath),\n attempted: true,\n tier,\n reason: \"accessibility-permission-required\",\n hint: \"Sync Now needs Accessibility permission. Grant it in System Settings ▸ Privacy & Security ▸ Accessibility for your terminal/IDE, then retry.\",\n };\n }\n hint = outcome.error ?? hint ?? \"Sync Now failed.\";\n } else if (await pollForFile(deps, filePath, timeoutMs, pollIntervalMs)) {\n return { downloaded: true, attempted: true, tier };\n }\n }\n\n return {\n downloaded: deps.fileExists(filePath),\n attempted: tier > 0,\n tier,\n reason: tier === 0 ? \"no sync tier could run\" : \"attachment did not download in time\",\n hint,\n };\n}\n"],"names":[],"mappings":";;AA8EO,SAAS,4BAAgD;AAC9D,SAAO;AAAA,IACL,YAAY,CAAC,MAAM,WAAW,CAAC;AAAA,IAC/B,kBAAkB,CAAC,WAAW,2BAA2B,MAAM;AAAA,IAC/D,SAAS,MAAM,uBAAA;AAAA,IACf,OAAO,CAAC,OAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,S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,CAAC,QAAQ,IAAI;AACf,UAAI,QAAQ,oBAAoB;AAC9B,eAAO;AAAA,UACL,YAAY,KAAK,WAAW,QAAQ;AAAA,UACpC,WAAW;AAAA,UACX;AAAA,UACA,QAAQ;AAAA,UACR,MAAM;AAAA,QAAA;AAAA,MAEV;AACA,aAAO,QAAQ,SAAS,QAAQ;AAAA,IAClC,WAAW,MAAM,YAAY,MAAM,UAAU,WAAW,cAAc,GAAG;AACvE,aAAO,EAAE,YAAY,MAAM,WAAW,MAAM,KAAA;AAAA,IAC9C;AAAA,EACF;AAEA,SAAO;AAAA,IACL,YAAY,KAAK,WAAW,QAAQ;AAAA,IACpC,WAAW,OAAO;AAAA,IAClB;AAAA,IACA,QAAQ,SAAS,IAAI,2BAA2B;AAAA,IAChD;AAAA,EAAA;AAEJ;"}
@@ -0,0 +1,151 @@
1
+ import { watch } from "node:fs";
2
+ import { dirname, basename } from "node:path";
3
+ import { w as warn, i as info } from "./shutdown-Dnj088id.js";
4
+ class ChangeWatcher {
5
+ dbPath;
6
+ db;
7
+ bus;
8
+ debounceMs;
9
+ pollFallbackMs;
10
+ maxBatch;
11
+ watcher = null;
12
+ pollTimer = null;
13
+ debounceTimer = null;
14
+ highWaterRowid = 0;
15
+ draining = false;
16
+ rearm = false;
17
+ started = false;
18
+ usingPollFallback = false;
19
+ constructor(opts) {
20
+ this.dbPath = opts.dbPath;
21
+ this.db = opts.db;
22
+ this.bus = opts.bus;
23
+ this.debounceMs = opts.debounceMs ?? 150;
24
+ this.pollFallbackMs = opts.pollFallbackMs ?? 2e3;
25
+ this.maxBatch = opts.maxBatch ?? 500;
26
+ }
27
+ /**
28
+ * Seed the high-water mark from the CURRENT max ROWID (history is the
29
+ * initial-load path's job; the stream carries only what happens next) and
30
+ * arm the directory watch — or the poll fallback if fs.watch throws.
31
+ */
32
+ start() {
33
+ if (this.started) return;
34
+ this.started = true;
35
+ this.highWaterRowid = this.db.getMaxMessageRowId();
36
+ const dir = dirname(this.dbPath);
37
+ const dbFile = basename(this.dbPath);
38
+ try {
39
+ this.watcher = watch(dir, (_eventType, filename) => {
40
+ if (filename === null || filename === `${dbFile}-wal` || filename === dbFile) {
41
+ this.scheduleDrain();
42
+ }
43
+ });
44
+ this.watcher.unref();
45
+ this.watcher.on("error", (err) => {
46
+ warn("change_watcher_fs_error_falling_back_to_poll", { message: String(err) });
47
+ this.teardownWatch();
48
+ this.armPollFallback();
49
+ });
50
+ info("change_watcher_started", {
51
+ dir,
52
+ high_water_rowid: this.highWaterRowid,
53
+ debounce_ms: this.debounceMs
54
+ });
55
+ } catch (err) {
56
+ warn("change_watcher_fs_watch_unavailable", { message: String(err) });
57
+ this.armPollFallback();
58
+ }
59
+ }
60
+ /** Idempotent teardown — clears the watch, timers, and pending drains. */
61
+ stop() {
62
+ this.started = false;
63
+ this.teardownWatch();
64
+ if (this.pollTimer) {
65
+ clearInterval(this.pollTimer);
66
+ this.pollTimer = null;
67
+ }
68
+ if (this.debounceTimer) {
69
+ clearTimeout(this.debounceTimer);
70
+ this.debounceTimer = null;
71
+ }
72
+ }
73
+ /** Current cursor — exposed for the dev-stats panel and tests. */
74
+ getHighWaterRowid() {
75
+ return this.highWaterRowid;
76
+ }
77
+ /** True when running in the degenerate poll mode (fs.watch unavailable). */
78
+ isPolling() {
79
+ return this.usingPollFallback;
80
+ }
81
+ /**
82
+ * Trigger a delta read now, bypassing the debounce. The poll fallback and
83
+ * tests use this; the fs.watch path goes through `scheduleDrain`.
84
+ */
85
+ async pump() {
86
+ await this.drain();
87
+ }
88
+ teardownWatch() {
89
+ if (this.watcher) {
90
+ this.watcher.close();
91
+ this.watcher = null;
92
+ }
93
+ }
94
+ armPollFallback() {
95
+ if (this.pollTimer || !this.started) return;
96
+ this.usingPollFallback = true;
97
+ this.pollTimer = setInterval(() => {
98
+ void this.drain();
99
+ }, this.pollFallbackMs);
100
+ this.pollTimer.unref();
101
+ info("change_watcher_poll_fallback_armed", { interval_ms: this.pollFallbackMs });
102
+ }
103
+ scheduleDrain() {
104
+ if (!this.started) return;
105
+ if (this.debounceTimer) clearTimeout(this.debounceTimer);
106
+ this.debounceTimer = setTimeout(() => {
107
+ this.debounceTimer = null;
108
+ void this.drain();
109
+ }, this.debounceMs);
110
+ this.debounceTimer.unref();
111
+ }
112
+ /**
113
+ * Read rows past the high-water mark and emit them as one batch per page.
114
+ * Re-entrancy guard: fs events landing mid-drain set `rearm` so the drain
115
+ * runs once more instead of overlapping (overlapping reads would emit
116
+ * duplicate rows — both would read from the same stale cursor).
117
+ */
118
+ async drain() {
119
+ if (this.draining) {
120
+ this.rearm = true;
121
+ return;
122
+ }
123
+ this.draining = true;
124
+ try {
125
+ for (; ; ) {
126
+ const messages = await this.db.getMessagesAfterRowid(this.highWaterRowid, this.maxBatch);
127
+ if (messages.length === 0) break;
128
+ for (const m of messages) {
129
+ if (m.id > this.highWaterRowid) this.highWaterRowid = m.id;
130
+ }
131
+ this.bus.emit(messages.map(classify));
132
+ if (messages.length < this.maxBatch) break;
133
+ }
134
+ } catch (err) {
135
+ warn("change_watcher_drain_failed", { message: String(err) });
136
+ } finally {
137
+ this.draining = false;
138
+ if (this.rearm) {
139
+ this.rearm = false;
140
+ void this.drain();
141
+ }
142
+ }
143
+ }
144
+ }
145
+ function classify(message) {
146
+ return message.isReaction ? { type: "reaction", message } : { type: "message.new", message };
147
+ }
148
+ export {
149
+ ChangeWatcher
150
+ };
151
+ //# sourceMappingURL=change-watcher-DNuxvzqL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"change-watcher-DNuxvzqL.js","sources":["../src/change-watcher.ts"],"sourcesContent":["/**\n * ChangeWatcher — turns chat.db writes into typed EventBus batches.\n *\n * Detection primitive per docs/plans/realtime-streaming-and-api-surface.md\n * Part A: watch the DIRECTORY containing chat.db with fs.watch (FSEvents on\n * macOS) and react to events for the WAL file — SQLite appends there before\n * checkpointing, so every logical write touches it. A directory watch (not a\n * file watch) survives WAL truncate/rename during checkpoints; the\n * authoritative cursor is a high-water ROWID, never a file offset.\n *\n * On an event: debounce ~150ms (one logical message = several WAL writes),\n * then delta-read rows past the high-water mark via\n * `IMessageDB.getMessagesAfterRowid` — the same parse/convert pipeline as\n * every other reader (\"one parser, N callers\"; no forked streamer parser) —\n * classify, and emit ONE coalesced batch per drain. Bulk syncs loop the\n * delta read in `maxBatch` pages so thousands of rows become a few batches,\n * not a subscriber storm.\n *\n * If fs.watch is unavailable (exotic filesystems), degrade to the documented\n * fallback: a slow poll of the same drain path. Detection cost is identical;\n * only latency differs.\n *\n * The watcher never throws into the host process: drain errors are logged\n * and retried on the next event. Timers are unref'd; `stop()` is idempotent\n * and safe to register as a shutdown cleanup (the ENTRY POINT registers it —\n * this module stays side-effect-free at import, like the rest of core).\n */\n\nimport { watch } from \"node:fs\";\nimport { basename, dirname } from \"node:path\";\nimport type { ChangeEvent, EventBus } from \"./event-bus.js\";\nimport { info, warn } from \"./logger.js\";\nimport type { Message } from \"./types.js\";\n\n/** The DB surface the watcher needs — injectable for tests. */\nexport interface ChangeWatcherDb {\n getMaxMessageRowId(): number;\n getMessagesAfterRowid(afterRowid: number, limit?: number): Promise<Message[]>;\n}\n\nexport interface ChangeWatcherOptions {\n /** Path to chat.db — the watcher watches its parent directory. */\n dbPath: string;\n db: ChangeWatcherDb;\n bus: EventBus;\n /** Trailing-edge debounce between an fs event and the delta read. */\n debounceMs?: number;\n /** Poll cadence for the degenerate no-fs.watch fallback. */\n pollFallbackMs?: number;\n /** Rows per delta page; drains loop while a page comes back full. */\n maxBatch?: number;\n}\n\nexport class ChangeWatcher {\n private readonly dbPath: string;\n private readonly db: ChangeWatcherDb;\n private readonly bus: EventBus;\n private readonly debounceMs: number;\n private readonly pollFallbackMs: number;\n private readonly maxBatch: number;\n\n private watcher: ReturnType<typeof watch> | null = null;\n private pollTimer: ReturnType<typeof setInterval> | null = null;\n private debounceTimer: ReturnType<typeof setTimeout> | null = null;\n private highWaterRowid = 0;\n private draining = false;\n private rearm = false;\n private started = false;\n private usingPollFallback = false;\n\n constructor(opts: ChangeWatcherOptions) {\n this.dbPath = opts.dbPath;\n this.db = opts.db;\n this.bus = opts.bus;\n this.debounceMs = opts.debounceMs ?? 150;\n this.pollFallbackMs = opts.pollFallbackMs ?? 2_000;\n this.maxBatch = opts.maxBatch ?? 500;\n }\n\n /**\n * Seed the high-water mark from the CURRENT max ROWID (history is the\n * initial-load path's job; the stream carries only what happens next) and\n * arm the directory watch — or the poll fallback if fs.watch throws.\n */\n start(): void {\n if (this.started) return;\n this.started = true;\n this.highWaterRowid = this.db.getMaxMessageRowId();\n\n const dir = dirname(this.dbPath);\n const dbFile = basename(this.dbPath);\n try {\n this.watcher = watch(dir, (_eventType, filename) => {\n // WAL writes are the signal; plain-db events also count (non-WAL\n // journal modes, checkpoint truncations arriving as `rename`).\n // filename can be null on some platforms — treat that as a hit.\n if (filename === null || filename === `${dbFile}-wal` || filename === dbFile) {\n this.scheduleDrain();\n }\n });\n // Like the timers, the fs.watch handle must never keep the process\n // alive on its own — entry points arm the watcher lazily inside\n // request handlers, and shutdown() already stops it explicitly.\n this.watcher.unref();\n this.watcher.on(\"error\", (err) => {\n warn(\"change_watcher_fs_error_falling_back_to_poll\", { message: String(err) });\n this.teardownWatch();\n this.armPollFallback();\n });\n info(\"change_watcher_started\", {\n dir,\n high_water_rowid: this.highWaterRowid,\n debounce_ms: this.debounceMs,\n });\n } catch (err) {\n warn(\"change_watcher_fs_watch_unavailable\", { message: String(err) });\n this.armPollFallback();\n }\n }\n\n /** Idempotent teardown — clears the watch, timers, and pending drains. */\n stop(): void {\n this.started = false;\n this.teardownWatch();\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n }\n\n /** Current cursor — exposed for the dev-stats panel and tests. */\n getHighWaterRowid(): number {\n return this.highWaterRowid;\n }\n\n /** True when running in the degenerate poll mode (fs.watch unavailable). */\n isPolling(): boolean {\n return this.usingPollFallback;\n }\n\n /**\n * Trigger a delta read now, bypassing the debounce. The poll fallback and\n * tests use this; the fs.watch path goes through `scheduleDrain`.\n */\n async pump(): Promise<void> {\n await this.drain();\n }\n\n private teardownWatch(): void {\n if (this.watcher) {\n this.watcher.close();\n this.watcher = null;\n }\n }\n\n private armPollFallback(): void {\n if (this.pollTimer || !this.started) return;\n this.usingPollFallback = true;\n this.pollTimer = setInterval(() => {\n void this.drain();\n }, this.pollFallbackMs);\n this.pollTimer.unref();\n info(\"change_watcher_poll_fallback_armed\", { interval_ms: this.pollFallbackMs });\n }\n\n private scheduleDrain(): void {\n if (!this.started) return;\n if (this.debounceTimer) clearTimeout(this.debounceTimer);\n this.debounceTimer = setTimeout(() => {\n this.debounceTimer = null;\n void this.drain();\n }, this.debounceMs);\n this.debounceTimer.unref();\n }\n\n /**\n * Read rows past the high-water mark and emit them as one batch per page.\n * Re-entrancy guard: fs events landing mid-drain set `rearm` so the drain\n * runs once more instead of overlapping (overlapping reads would emit\n * duplicate rows — both would read from the same stale cursor).\n */\n private async drain(): Promise<void> {\n if (this.draining) {\n this.rearm = true;\n return;\n }\n this.draining = true;\n try {\n // Loop while pages come back full — a bulk sync writes thousands of\n // rows in one burst and each page becomes one coalesced batch.\n for (;;) {\n const messages = await this.db.getMessagesAfterRowid(this.highWaterRowid, this.maxBatch);\n if (messages.length === 0) break;\n for (const m of messages) {\n if (m.id > this.highWaterRowid) this.highWaterRowid = m.id;\n }\n this.bus.emit(messages.map(classify));\n if (messages.length < this.maxBatch) break;\n }\n } catch (err) {\n // Never throw into the host — the next WAL event retries naturally.\n warn(\"change_watcher_drain_failed\", { message: String(err) });\n } finally {\n this.draining = false;\n if (this.rearm) {\n this.rearm = false;\n void this.drain();\n }\n }\n }\n}\n\n/**\n * New-ROWID classification. Edited/unsent rows mutate EXISTING ROWIDs and are\n * invisible to the high-water delta — they belong to the mutation-detection\n * backlog item (date_edited / is_read deltas), not this path.\n */\nfunction classify(message: Message): ChangeEvent {\n return message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,WAAW,MAAM,KAAK,GAAG,sBAAsB,KAAK,gBAAgB,KAAK,QAAQ;AACvF,YAAI,SAAS,WAAW,EAAG;AAC3B,mBAAW,KAAK,UAAU;AACxB,cAAI,EAAE,KAAK,KAAK,eAAgB,MAAK,iBAAiB,EAAE;AAAA,QAC1D;AACA,aAAK,IAAI,KAAK,SAAS,IAAI,QAAQ,CAAC;AACpC,YAAI,SAAS,SAAS,KAAK,SAAU;AAAA,MACvC;AAAA,IACF,SAAS,KAAK;AAEZ,WAAK,+BAA+B,EAAE,SAAS,OAAO,GAAG,GAAG;AAAA,IAC9D,UAAA;AACE,WAAK,WAAW;AAChB,UAAI,KAAK,OAAO;AACd,aAAK,QAAQ;AACb,aAAK,KAAK,MAAA;AAAA,MACZ;AAAA,IACF;AAAA,EACF;AACF;AAOA,SAAS,SAAS,SAA+B;AAC/C,SAAO,QAAQ,aAAa,EAAE,MAAM,YAAY,YAAY,EAAE,MAAM,eAAe,QAAA;AACrF;"}
package/dist/cli.js CHANGED
@@ -3,7 +3,7 @@ import { existsSync, realpathSync } from "node:fs";
3
3
  import { createInterface } from "node:readline";
4
4
  import { fileURLToPath, pathToFileURL } from "node:url";
5
5
  import { Command } from "commander";
6
- import { A as APP_VERSION, d as checkLocalAccess, f as formatAccessReport, I as IMPLEMENTED_TYPES, e as ANALYTIC_INFO, i as installShutdownHandlers, r as registerCleanup, l as looksLikeThreadSlug } from "./shutdown-CWS6IvCE.js";
6
+ import { A as APP_VERSION, d as checkLocalAccess, f as formatAccessReport, I as IMPLEMENTED_TYPES, e as ANALYTIC_INFO, h as installShutdownHandlers, r as registerCleanup, l as looksLikeThreadSlug } from "./shutdown-Dnj088id.js";
7
7
  import { t as toYaml } from "./analytics-render-DC26KLXv.js";
8
8
  import { spawn } from "node:child_process";
9
9
  import { join, dirname } from "node:path";
@@ -173,6 +173,14 @@ function parseWindowDays(value, fallback) {
173
173
  }
174
174
  return n;
175
175
  }
176
+ function formatChangeEventLine(event, slugForLeg) {
177
+ if (!("message" in event)) return null;
178
+ const m = event.message;
179
+ const thread = (m.chatId ? slugForLeg(m.chatId) : null) ?? m.chatId ?? "?";
180
+ const who = m.isFromMe ? "me" : m.displayName ?? m.handle;
181
+ const snippet = (m.text ?? "(no text)").replace(/\s+/g, " ").trim().slice(0, 80);
182
+ return `[${event.type}] ~${thread} ${who}: ${snippet}`;
183
+ }
176
184
  function parseConsoleInput(line) {
177
185
  const parts = [];
178
186
  let current = "";
@@ -322,6 +330,33 @@ async function runConsoleCommand(cmd, args, client) {
322
330
  await printToolResult(client, "chat_analytics", { type, windowDays }, void 0, format);
323
331
  return;
324
332
  }
333
+ case "watch": {
334
+ const seconds = Number(args[0] ?? 60);
335
+ if (!Number.isFinite(seconds) || seconds <= 0) throw new Error("Usage: watch [seconds]");
336
+ const { EventBus } = await import("./event-bus-DqXvbtEM.js");
337
+ const { ChangeWatcher } = await import("./change-watcher-DNuxvzqL.js");
338
+ const { IMessageDB } = await import("./imessage-db-Be6EywKE.js").then((n) => n.i);
339
+ const { getContactsDbPaths, getImsgDbPath, getSlugsDbPath } = await import("./shutdown-Dnj088id.js").then((n) => n.af);
340
+ const db = new IMessageDB(getImsgDbPath(), getContactsDbPaths(), getSlugsDbPath());
341
+ const bus = new EventBus();
342
+ const watcher = new ChangeWatcher({ dbPath: getImsgDbPath(), db, bus });
343
+ const unsubscribe = bus.subscribe((events) => {
344
+ for (const e of events) {
345
+ const line = formatChangeEventLine(e, (leg) => db.getSlugForChatIdentifier(leg));
346
+ if (line) console.log(line);
347
+ }
348
+ });
349
+ watcher.start();
350
+ log(`Watching for new messages/reactions for ${seconds}s…`, "dim");
351
+ try {
352
+ await new Promise((r) => setTimeout(r, seconds * 1e3));
353
+ } finally {
354
+ unsubscribe();
355
+ watcher.stop();
356
+ await db.close();
357
+ }
358
+ return;
359
+ }
325
360
  case "logs":
326
361
  await printToolResult(client, "get_logs", args[0] ? { tail: Number(args[0]) } : {});
327
362
  return;
@@ -368,6 +403,7 @@ Available commands:
368
403
  search <query> [n] Search messages
369
404
  resolve <name> [n] Resolve a name/phrase to ranked conversations
370
405
  wait <chat> [secs] Wait for a reply (default 60s)
406
+ watch [secs] Stream new messages/reactions live (default 60s)
371
407
  send <target> <msg> Send a message
372
408
  contacts [verb] Contacts: list [n] [offset] | search <q> [n] | resolve <handle> | show <handle-or-id>
373
409
  humans <verb> Relationship files: init <contact|slug> | init top [n] | top [days]
@@ -446,9 +482,9 @@ async function runExportCommand(target, opts) {
446
482
  const { existsSync: existsSync2, mkdirSync, copyFileSync, statSync } = await import("node:fs");
447
483
  const { homedir } = await import("node:os");
448
484
  const { dirname: dirname2, join: join2, isAbsolute, resolve } = await import("node:path");
449
- const { getContactsDbPaths, getImsgDbPath, getSlugsDbPath } = await import("./shutdown-CWS6IvCE.js").then((n) => n.ae);
450
- const { IMessageDB } = await import("./imessage-db-BTy3p2Qk.js").then((n) => n.i);
451
- const { streamExport } = await import("./exportStream-Bn0Ir89w.js");
485
+ const { getContactsDbPaths, getImsgDbPath, getSlugsDbPath } = await import("./shutdown-Dnj088id.js").then((n) => n.af);
486
+ const { IMessageDB } = await import("./imessage-db-Be6EywKE.js").then((n) => n.i);
487
+ const { streamExport } = await import("./exportStream-DjdPdE1S.js");
452
488
  const { parseUserDate } = await import("./date-parse-DJXMfq3a.js");
453
489
  const format = normalizeFormat(opts.format ?? "md");
454
490
  const ext = extForFormat(format);
@@ -503,13 +539,13 @@ async function runExportCommand(target, opts) {
503
539
  if (since) filters.sinceMs = since.getTime();
504
540
  if (until) filters.untilMs = until.getTime();
505
541
  const attachments = db.searchAttachments(filters);
506
- const { resolveInterpretConfig } = await import("./app-config-BHA2RWD5.js");
542
+ const { resolveInterpretConfig } = await import("./app-config-B_QqZFbl.js");
507
543
  const nudge = resolveInterpretConfig().nudge;
508
544
  const firstMissing = attachments.find(
509
545
  (a) => a.filename && !existsSync2(a.filename.replace(/^~/, homedir()))
510
546
  );
511
547
  if (nudge.enabled && firstMissing && chatIdentifier) {
512
- const { ensureAttachmentDownloaded } = await import("./attachment-sync-CIoN37ih.js");
548
+ const { ensureAttachmentDownloaded } = await import("./attachment-sync-DqIvfxPv.js");
513
549
  log(` Nudging Messages to sync missing attachments…`, "dim");
514
550
  await ensureAttachmentDownloaded(
515
551
  { filePath: firstMissing.filename.replace(/^~/, homedir()), chatId: chatIdentifier },
@@ -718,10 +754,10 @@ program.command("interpret <rowId>").description("Interpret one attachment (tran
718
754
  process.exitCode = 1;
719
755
  return;
720
756
  }
721
- const { getContactsDbPaths, getImsgDbPath, getSlugsDbPath } = await import("./shutdown-CWS6IvCE.js").then((n) => n.ae);
722
- const { IMessageDB } = await import("./imessage-db-BTy3p2Qk.js").then((n) => n.i);
723
- const { getInterpretRuntime, refForAttachment } = await import("./media-intel-runtime-DwG4nhXt.js").then((n) => n.c);
724
- const { deleteMediaIntel } = await import("./media-intel-cache-E3ejWhWo.js");
757
+ const { getContactsDbPaths, getImsgDbPath, getSlugsDbPath } = await import("./shutdown-Dnj088id.js").then((n) => n.af);
758
+ const { IMessageDB } = await import("./imessage-db-Be6EywKE.js").then((n) => n.i);
759
+ const { getInterpretRuntime, refForAttachment } = await import("./media-intel-runtime-DbJ3jXLG.js").then((n) => n.c);
760
+ const { deleteMediaIntel } = await import("./media-intel-cache-JJZzGCs4.js");
725
761
  const db = new IMessageDB(getImsgDbPath(), getContactsDbPaths(), getSlugsDbPath());
726
762
  try {
727
763
  const rec = db.getAttachmentByRowId(rowId);
@@ -756,7 +792,7 @@ program.command("interpret <rowId>").description("Interpret one attachment (tran
756
792
  program.command("setup").description("Autodetect DB paths and emit an MCP host config snippet").option("-w, --write <host>", 'Write into a host config: "claude" or "cursor"').option("-r, --runtime <runtime>", 'Runtime command: "npx" (default), "bunx", or "global"').option("--print-only", "Just print the snippet (default behaviour)").option("-i, --interactive", "Configure media interpretation (providers, chains, keys)").action(
757
793
  async (opts) => {
758
794
  if (opts.interactive) {
759
- const { runSetupWizard } = await import("./setup-wizard-CM_3dRi_.js");
795
+ const { runSetupWizard } = await import("./setup-wizard-D70bqgzB.js");
760
796
  try {
761
797
  await runSetupWizard();
762
798
  } catch (err) {
@@ -768,7 +804,7 @@ program.command("setup").description("Autodetect DB paths and emit an MCP host c
768
804
  }
769
805
  return;
770
806
  }
771
- const { probeMachine, buildMcpSnippet, writeHostConfig } = await import("./setup-BRZC_tgU.js");
807
+ const { probeMachine, buildMcpSnippet, writeHostConfig } = await import("./setup-DxbCKuOU.js");
772
808
  const report = probeMachine();
773
809
  if (!report.imsgDb.readable) {
774
810
  log(`✗ Messages DB is not readable: ${report.imsgDb.path}`, "err");
@@ -811,7 +847,7 @@ program.command("setup").description("Autodetect DB paths and emit an MCP host c
811
847
  );
812
848
  const configCmd = program.command("config").description("Manage TUI settings (theme, accent color)");
813
849
  configCmd.command("show").description("Print resolved TUI settings and where each value came from").action(async () => {
814
- const { resolveTuiConfig, defaultTuiConfigPath } = await import("./tui-config-BPDDTKNp.js");
850
+ const { resolveTuiConfig, defaultTuiConfigPath } = await import("./tui-config-Bt1yixQj.js");
815
851
  const cfg = resolveTuiConfig();
816
852
  log(
817
853
  `config file : ${cfg.configPath ?? `(none — defaults; would write to ${defaultTuiConfigPath()})`}`
@@ -824,7 +860,7 @@ configCmd.command("show").description("Print resolved TUI settings and where eac
824
860
  for (const w of cfg.warnings) log(w, "warn");
825
861
  });
826
862
  configCmd.command("edit").description("Open the TUI config file in $EDITOR (creates it if missing)").action(async () => {
827
- const { defaultTuiConfigPath, findTuiConfigPath, writeTuiConfig, DEFAULT_TUI_CONFIG } = await import("./tui-config-BPDDTKNp.js");
863
+ const { defaultTuiConfigPath, findTuiConfigPath, writeTuiConfig, DEFAULT_TUI_CONFIG } = await import("./tui-config-Bt1yixQj.js");
828
864
  const path = findTuiConfigPath() ?? defaultTuiConfigPath();
829
865
  const { existsSync: existsSync2 } = await import("node:fs");
830
866
  if (!existsSync2(path)) {
@@ -861,6 +897,7 @@ if (invokedAsScript) {
861
897
  });
862
898
  }
863
899
  export {
900
+ formatChangeEventLine,
864
901
  parseConsoleInput,
865
902
  parseWindowDays,
866
903
  runConsoleCommand,