@amoree-code/ocean 1.6.2 → 1.8.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 (84) hide show
  1. package/README.md +10 -1
  2. package/dist/application/clients/desktop-watcher.js +234 -0
  3. package/dist/application/clients/opencode-plugin.js +4 -3
  4. package/dist/application/layout/layout-plan.js +1 -0
  5. package/dist/application/onboarding/steps.js +20 -1
  6. package/dist/infrastructure/desktop/claude-export.js +84 -0
  7. package/dist/infrastructure/desktop/desktop-chat.js +165 -0
  8. package/dist/infrastructure/desktop/indexeddb.js +158 -0
  9. package/dist/infrastructure/desktop/leveldb.js +247 -0
  10. package/dist/infrastructure/desktop/snappy.js +74 -0
  11. package/dist/infrastructure/process/service.js +8 -0
  12. package/dist/interfaces/cli/brief-command.js +17 -0
  13. package/dist/interfaces/cli/capture-command.js +1 -1
  14. package/dist/interfaces/cli/clients-command.js +15 -2
  15. package/dist/interfaces/cli/command-registry.js +31 -2
  16. package/dist/interfaces/cli/desktop-command.js +124 -0
  17. package/dist/interfaces/cli/distill-command.js +36 -0
  18. package/dist/interfaces/cli/express-command.js +18 -0
  19. package/dist/interfaces/cli/harvest-command.js +58 -0
  20. package/dist/interfaces/cli/help-command.js +34 -2
  21. package/dist/interfaces/cli/interests-command.js +33 -0
  22. package/dist/interfaces/cli/memory-command.js +37 -3
  23. package/dist/interfaces/cli/note-command.js +7 -0
  24. package/dist/interfaces/cli/setup-command.js +2 -1
  25. package/dist/interfaces/cli/telemetry-command.js +23 -0
  26. package/node_modules/@ocean/brain/dist/brain/brain-reindex.js +4 -1
  27. package/node_modules/@ocean/brain/dist/brain/brain-service.js +11 -1
  28. package/node_modules/@ocean/brain/dist/memory/brain-dump.js +73 -24
  29. package/node_modules/@ocean/brain/dist/memory/fact-routing.js +54 -0
  30. package/node_modules/@ocean/brain/dist/memory/frontmatter-flatten.js +89 -0
  31. package/node_modules/@ocean/brain/dist/memory/lessons.js +20 -0
  32. package/node_modules/@ocean/brain/dist/memory/memory-paths.js +3 -1
  33. package/node_modules/@ocean/brain/dist/memory/memory-review.js +19 -2
  34. package/node_modules/@ocean/brain/dist/memory/memory-write.js +45 -3
  35. package/node_modules/@ocean/brain/dist/memory/people.js +70 -0
  36. package/node_modules/@ocean/brain/dist/memory/routing.json +39 -0
  37. package/node_modules/@ocean/brain/dist/memory/session-facts.js +7 -1
  38. package/node_modules/@ocean/brain/dist/memory/session-promotion.js +1 -1
  39. package/node_modules/@ocean/brain/package.json +1 -1
  40. package/node_modules/@ocean/context/package.json +1 -1
  41. package/node_modules/@ocean/core/dist/shared/paths.js +7 -0
  42. package/node_modules/@ocean/core/package.json +1 -1
  43. package/node_modules/@ocean/loop/dist/handoff/handoff-service.js +5 -1
  44. package/node_modules/@ocean/loop/dist/hooks/desktop-facts.js +154 -0
  45. package/node_modules/@ocean/loop/dist/hooks/session-end-hook.js +1 -1
  46. package/node_modules/@ocean/loop/package.json +1 -1
  47. package/node_modules/@ocean/market/package.json +1 -1
  48. package/node_modules/@ocean/services/dist/brief/brief.js +218 -0
  49. package/node_modules/@ocean/services/dist/brief/interest-discovery.js +236 -0
  50. package/node_modules/@ocean/services/dist/brief/source-registry.json +35 -0
  51. package/node_modules/@ocean/services/dist/distill/distill.js +258 -0
  52. package/node_modules/@ocean/services/dist/doctor/workspace-doctor.js +129 -8
  53. package/node_modules/@ocean/services/dist/express/express.js +99 -0
  54. package/node_modules/@ocean/services/dist/harvest/harvest.js +453 -0
  55. package/node_modules/@ocean/services/dist/infrastructure/mcp/ocean-server.js +17 -1
  56. package/node_modules/@ocean/services/dist/journey/telemetry.js +81 -0
  57. package/node_modules/@ocean/services/dist/obsidian/folder-templates.js +82 -0
  58. package/node_modules/@ocean/services/dist/onboarding/onboarding.js +62 -0
  59. package/node_modules/@ocean/services/package.json +1 -1
  60. package/ocean-marketplace.json +82 -28
  61. package/package.json +7 -7
  62. package/skills/core/daily-harvest/SKILL.md +72 -0
  63. package/skills/core/memory-review/SKILL.md +53 -0
  64. package/skills/core/weekly-review/SKILL.md +24 -0
  65. package/skills/index.json +18 -0
  66. package/templates/workspace/02-personal/education/study/study.base +15 -0
  67. package/templates/workspace/02-personal/milestones/milestones.base +14 -0
  68. package/templates/workspace/02-personal/people/people.base +18 -0
  69. package/templates/workspace/06-templates/TEMPLATES.md +12 -0
  70. package/templates/workspace/06-templates/capture.md +9 -0
  71. package/templates/workspace/06-templates/daily.md +13 -0
  72. package/templates/workspace/06-templates/decision.md +8 -0
  73. package/templates/workspace/06-templates/failure.md +13 -0
  74. package/templates/workspace/06-templates/intelligence.md +7 -0
  75. package/templates/workspace/06-templates/interest.md +13 -0
  76. package/templates/workspace/06-templates/lesson.md +16 -0
  77. package/templates/workspace/06-templates/milestone.md +10 -0
  78. package/templates/workspace/06-templates/note.md +8 -0
  79. package/templates/workspace/06-templates/person.md +15 -0
  80. package/templates/workspace/06-templates/session.md +10 -0
  81. package/templates/workspace/06-templates/solution.md +14 -0
  82. package/templates/workspace/06-templates/study.md +14 -0
  83. package/templates/workspace/07-notes/.gitkeep +0 -0
  84. package/templates/workspace/MANIFEST.json +14 -0
package/README.md CHANGED
@@ -142,8 +142,16 @@ prints its usage and never runs it. To hand `--help` to a wrapped client, put it
142
142
  | `ocean browser` | drive a browser session | Runs; `upload`, `submit` need `--approve` |
143
143
  | `ocean memory` | search, read, review and maintain memory | Reads; `approve`, `delete`, `restore`, `reindex`, `sync --apply`, `purge --yes` write |
144
144
  | `ocean pull` | pull what AI clients hold into Ocean as review candidates | Reads (dry run); `--yes` writes |
145
+ | `ocean desktop` | capture facts from Claude Desktop's chat, read from the app's local store, as review candidates | Reads (`--dry-run`); a run writes candidates |
145
146
  | `ocean observe` | run a command and record its output | Runs |
146
147
  | `ocean capture` / `idea` | capture ideas, then promote or discard them | Writes |
148
+ | `ocean note` | `ocean note "<text>"`: capture a thought into `00-inbox/captures/` with frontmatter | Writes |
149
+ | `ocean brief` | write the daily or weekly brief from your interests' feeds | Writes |
150
+ | `ocean interests` | propose interests from your projects or recurring session topics (as candidates), decay, keep/skip | Writes |
151
+ | `ocean distill` | `--week`: a weekly digest, decisions and lessons as candidates; `--month`: last month against your goals | Writes |
152
+ | `ocean harvest` | a day's sessions from every client into its summary; decisions, fixes and lessons filed into knowledge (undo per day); archive after 30 days | Writes |
153
+ | `ocean telemetry` | recurring session errors and failing providers, as proposed backlog lines | Writes |
154
+ | `ocean express` | draft a CV section, LinkedIn post or scholarship paragraph from milestones | Writes |
147
155
  | `ocean handoff` | hand work from one session or client to another | Reads; `create` writes |
148
156
  | `ocean daily` | prepare today's note | Reads; `--apply` writes |
149
157
  | `ocean skill` | sync, add, review and learn skills | Reads; `add`, `review`, `learn`, `sync` write |
@@ -166,7 +174,7 @@ only and receives no provider credentials. It offers:
166
174
 
167
175
  - **reads** — `brain_search`, `brain_read`, `brain_neighbors`, `memory_read`,
168
176
  `memory_history`, tasks, sessions, handoffs, projects, profiles, `ocean_context`,
169
- `ocean_status` and `ocean_doctor`;
177
+ `ocean_status`, `ocean_doctor` and `people_lookup` (a person by exact name or alias);
170
178
  - **writes** — `memory_write` (only when you ask a client to remember or change something;
171
179
  an update must name the record's current hash), `memory_propose` (a candidate for your
172
180
  review), `memory_delete` (soft, undone by `memory_restore`), `ocean_handoff_create`, and
@@ -197,6 +205,7 @@ session, and `ocean skill review <candidate-id> promoted` activates it.
197
205
  ~/ocean/ private workspace (OCEAN_ROOT) — local only, never published
198
206
  ├── 00-inbox/ … 06-templates/ your records: inbox, daily, personal, professional,
199
207
  │ projects, knowledge, templates
208
+ ├── 07-notes/ your own notes: agents read them, never write them
200
209
  ├── charter/ your rules and the policies they route to
201
210
  └── bridge/ machine state: sessions, config, client integrations, shims
202
211
 
@@ -0,0 +1,234 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { readFile, unlink } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { sessionFactsEnabled } from "@ocean/brain/memory/memory-audit.js";
7
+ import { desktopFactsLastRunFile } from "@ocean/loop/hooks/desktop-facts.js";
8
+ import { appendJournal, defaultClientEnv, edit, newBatch, planClients, readJournal, temporaryEntryProblem, } from "./clients.js";
9
+ import { oceanInvocation } from "./opencode-plugin.js";
10
+ // Claude Desktop's plain chat has no hooks (T-315), so a per-user LaunchAgent stands in for
11
+ // one: launchd runs `ocean desktop capture` when the app writes its local chat store
12
+ // (WatchPaths, at most once per ThrottleInterval) and every StartInterval, which catches a
13
+ // conversation that went quiet after the last write. The capture itself skips conversations
14
+ // still being written. The plist is Ocean's alone: written whole, journaled, loaded with
15
+ // launchctl, unloaded and removed on restore. It is offered only on macOS, with Claude Desktop
16
+ // installed and session facts on — the same consent that turns on capture for every client.
17
+ export const DESKTOP_WATCHER_LABEL = "com.ocean.desktop-capture";
18
+ export const DESKTOP_WATCHER_FILE = `Library/LaunchAgents/${DESKTOP_WATCHER_LABEL}.plist`;
19
+ const CLIENT = "claude-desktop";
20
+ const KEY = "desktop-watcher";
21
+ const THROTTLE_SECONDS = 300;
22
+ const INTERVAL_SECONDS = 900;
23
+ const sha = (text) => createHash("sha256").update(text).digest("hex");
24
+ const xml = (text) => text
25
+ .replaceAll("&", "&amp;")
26
+ .replaceAll("<", "&lt;")
27
+ .replaceAll(">", "&gt;")
28
+ .replaceAll('"', "&quot;");
29
+ export function desktopStoreDir(home) {
30
+ return path.join(home, "Library", "Application Support", "Claude", "IndexedDB", "https_claude.ai_0.indexeddb.leveldb");
31
+ }
32
+ export function desktopWatcherPlist(env) {
33
+ const args = [...oceanInvocation(env), "desktop", "capture"];
34
+ const strings = (items) => items.map((item) => `<string>${xml(item)}</string>`).join("");
35
+ // launchd starts jobs with a bare PATH; the capture's model call needs the client's CLI.
36
+ const pathValue = [...new Set([...env.pathDirs, "/usr/bin", "/bin"])].join(":");
37
+ return `<?xml version="1.0" encoding="UTF-8"?>
38
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
39
+ <!-- Written by \`ocean clients apply\`; \`ocean clients restore\` removes it. -->
40
+ <plist version="1.0"><dict>
41
+ <key>Label</key><string>${DESKTOP_WATCHER_LABEL}</string>
42
+ <key>ProgramArguments</key><array>${strings(args)}</array>
43
+ <key>WatchPaths</key><array>${strings([desktopStoreDir(env.home)])}</array>
44
+ <key>StartInterval</key><integer>${INTERVAL_SECONDS}</integer>
45
+ <key>ThrottleInterval</key><integer>${THROTTLE_SECONDS}</integer>
46
+ <key>RunAtLoad</key><false/>
47
+ <key>ProcessType</key><string>Background</string>
48
+ <key>LowPriorityIO</key><true/>
49
+ <key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(pathValue)}</string></dict>
50
+ <key>StandardOutPath</key><string>/dev/null</string>
51
+ <key>StandardErrorPath</key><string>/dev/null</string>
52
+ </dict></plist>
53
+ `;
54
+ }
55
+ async function readIfPresent(file) {
56
+ try {
57
+ return await readFile(file, "utf8");
58
+ }
59
+ catch (error) {
60
+ if (error.code === "ENOENT")
61
+ return null;
62
+ throw error;
63
+ }
64
+ }
65
+ function planText(text, want) {
66
+ const plan = { client: CLIENT, file: `~/${DESKTOP_WATCHER_FILE}` };
67
+ if (text === want)
68
+ return { ...plan, status: "current" };
69
+ if (text === null ||
70
+ text.includes(`<string>${DESKTOP_WATCHER_LABEL}</string>`))
71
+ return { ...plan, status: "change" };
72
+ return {
73
+ ...plan,
74
+ status: "manual",
75
+ reason: "a plist Ocean did not write has this name",
76
+ };
77
+ }
78
+ export async function planDesktopWatcher(options = {}) {
79
+ const env = options.env ?? defaultClientEnv();
80
+ if ((options.platform ?? process.platform) !== "darwin")
81
+ return [];
82
+ const installed = (await planClients(env)).some((plan) => plan.client === CLIENT && plan.installed);
83
+ if (!installed)
84
+ return [];
85
+ const text = await readIfPresent(path.join(env.home, DESKTOP_WATCHER_FILE));
86
+ if (!(await (options.enabled ?? sessionFactsEnabled)()))
87
+ return [
88
+ {
89
+ client: CLIENT,
90
+ file: `~/${DESKTOP_WATCHER_FILE}`,
91
+ status: text === null ? "off" : "current",
92
+ reason: "session facts are off",
93
+ },
94
+ ];
95
+ return [planText(text, desktopWatcherPlist(env))];
96
+ }
97
+ const runCommand = (command, args) => promisify(execFile)(command, args);
98
+ const domain = () => `gui/${process.getuid?.() ?? ""}`;
99
+ // Writes the plist and (re)loads the job. Loading is best effort: the plist stays, and the next
100
+ // login loads it.
101
+ export async function applyDesktopWatcher(options = {}) {
102
+ const env = options.env ?? defaultClientEnv();
103
+ const batch = options.batch ?? newBatch();
104
+ if (options.clients && !options.clients.includes(CLIENT))
105
+ return { batch, results: [] };
106
+ const [plan] = await planDesktopWatcher({ ...options, env });
107
+ if (plan?.status !== "change")
108
+ return { batch, results: [] };
109
+ if (options.durable ?? !options.env) {
110
+ const problem = temporaryEntryProblem(env.entry);
111
+ if (problem)
112
+ throw new Error(`Refusing to add the Desktop watcher: ${problem}`);
113
+ }
114
+ const want = desktopWatcherPlist(env);
115
+ const file = path.join(env.home, DESKTOP_WATCHER_FILE);
116
+ const result = await edit(file, (text) => {
117
+ const current = text === "" ? null : text;
118
+ if (planText(current, want).status !== "change")
119
+ return null;
120
+ return {
121
+ next: want,
122
+ entries: [
123
+ {
124
+ client: CLIENT,
125
+ file: DESKTOP_WATCHER_FILE,
126
+ op: "hook-add",
127
+ key: KEY,
128
+ before: current === null ? null : { sha256: sha(current) },
129
+ after: { sha256: sha(want) },
130
+ },
131
+ ],
132
+ };
133
+ }, batch);
134
+ if (result === "written") {
135
+ const run = options.run ?? runCommand;
136
+ await run("launchctl", [
137
+ "bootout",
138
+ `${domain()}/${DESKTOP_WATCHER_LABEL}`,
139
+ ]).catch(() => { });
140
+ const loaded = await run("launchctl", ["bootstrap", domain(), file]).then(() => true, () => false);
141
+ return {
142
+ batch,
143
+ results: [
144
+ {
145
+ client: CLIENT,
146
+ result: loaded ? "written" : "written (loads at next login)",
147
+ },
148
+ ],
149
+ };
150
+ }
151
+ return { batch, results: [{ client: CLIENT, result }] };
152
+ }
153
+ // Unloads and removes the plist one apply batch wrote, unless it changed since (a conflict).
154
+ export async function restoreDesktopWatcher(options) {
155
+ const env = options.env ?? defaultClientEnv();
156
+ const entries = (await readJournal()).filter((entry) => entry.batch === options.batch &&
157
+ entry.client === CLIENT &&
158
+ entry.key === KEY &&
159
+ !entry.restoreOf);
160
+ const restored = [];
161
+ const conflicts = [];
162
+ for (const entry of entries) {
163
+ const file = path.join(env.home, entry.file);
164
+ const text = await readIfPresent(file);
165
+ const after = entry.after?.sha256;
166
+ if (text === null || sha(text) !== after) {
167
+ conflicts.push(`${CLIENT}:${KEY}`);
168
+ continue;
169
+ }
170
+ await (options.run ?? runCommand)("launchctl", [
171
+ "bootout",
172
+ `${domain()}/${DESKTOP_WATCHER_LABEL}`,
173
+ ]).catch(() => { });
174
+ await unlink(file);
175
+ await appendJournal([
176
+ {
177
+ ...entry,
178
+ batch: newBatch(),
179
+ ts: new Date().toISOString(),
180
+ restoreOf: options.batch,
181
+ },
182
+ ]);
183
+ restored.push(`${CLIENT}:${KEY}`);
184
+ }
185
+ return { restored, conflicts };
186
+ }
187
+ // Doctor view: the watcher is wanted but missing or stale; the last capture run failed to read
188
+ // the store (the format changed with an app update); or the last run, when it was.
189
+ export async function desktopWatcherFindings(options = {}) {
190
+ const plans = await planDesktopWatcher(options);
191
+ const plan = plans[0];
192
+ if (!plan || plan.status === "off")
193
+ return [];
194
+ const findings = [];
195
+ if (plan.status === "change")
196
+ findings.push({
197
+ code: "DESKTOP_WATCHER_MISSING",
198
+ severity: "WARN",
199
+ message: "Claude Desktop chat is not captured: its watcher is missing or out of date — run `ocean clients apply --yes`",
200
+ fixable: true,
201
+ });
202
+ else if (plan.status === "manual")
203
+ findings.push({
204
+ code: "DESKTOP_WATCHER_MANUAL",
205
+ severity: "WARN",
206
+ message: `Claude Desktop watcher: ${plan.reason} (${plan.file})`,
207
+ fixable: false,
208
+ });
209
+ let last = null;
210
+ try {
211
+ last = JSON.parse(await readFile(desktopFactsLastRunFile(), "utf8"));
212
+ }
213
+ catch {
214
+ last = null;
215
+ }
216
+ if (last?.code)
217
+ findings.push({
218
+ code: last.code,
219
+ severity: "WARN",
220
+ message: `Claude Desktop chat could not be read at ${last.at}: ${last.reason ?? "unknown"} — the app's local format may have changed with an update; Desktop facts are not captured until Ocean is updated`,
221
+ fixable: false,
222
+ });
223
+ else if (plan.status === "current")
224
+ findings.push({
225
+ code: "DESKTOP_WATCHER_OK",
226
+ severity: "OK",
227
+ message: last?.at
228
+ ? `Claude Desktop chat watcher loaded; last run ${last.at} (${last.status}, ${last.candidates ?? 0} candidate(s))`
229
+ : "Claude Desktop chat watcher installed; no run recorded yet",
230
+ fixable: false,
231
+ });
232
+ return findings;
233
+ }
234
+ //# sourceMappingURL=desktop-watcher.js.map
@@ -10,8 +10,9 @@ import { appendJournal, defaultClientEnv, edit, newBatch, planClients, readJourn
10
10
  export const OPENCODE_PLUGIN_FILE = ".config/opencode/plugins/ocean.js";
11
11
  const MARKER = "// Ocean session context for OpenCode";
12
12
  const sha = (text) => createHash("sha256").update(text).digest("hex");
13
- // The engine invocation the plugin spawns (no shell: argv words only).
14
- function invocation(env) {
13
+ // The engine invocation the plugin spawns (no shell: argv words only); the Desktop watcher
14
+ // runs the same.
15
+ export function oceanInvocation(env) {
15
16
  const program = Array.isArray(env.entry.args)
16
17
  ? String(env.entry.args[0])
17
18
  : "";
@@ -23,7 +24,7 @@ export function opencodePluginSource(env) {
23
24
  return `${MARKER} (written by \`ocean clients apply\`; \`ocean clients restore\` removes it).
24
25
  import { spawn } from "node:child_process";
25
26
 
26
- const OCEAN = ${JSON.stringify(invocation(env))};
27
+ const OCEAN = ${JSON.stringify(oceanInvocation(env))};
27
28
  const contexts = new Map();
28
29
 
29
30
  function startLine(sessionID, directory) {
@@ -11,6 +11,7 @@ const RECORD_AREAS = [
11
11
  "04-projects",
12
12
  "05-knowledge",
13
13
  "06-templates",
14
+ "07-notes",
14
15
  "99-archive",
15
16
  ".index",
16
17
  "charter",
@@ -2,8 +2,9 @@ import { writeFile } from "node:fs/promises";
2
2
  import { oceanPath, PERSONAL_DIR } from "@ocean/core/shared/paths.js";
3
3
  import { copyClientSkills, populateSkillHub, } from "@ocean/market/skills/skill-hub.js";
4
4
  import { connectObsidianVault } from "@ocean/services/obsidian/vault-discovery.js";
5
+ import { ONBOARDING_QUESTIONS, onboard, } from "@ocean/services/onboarding/onboarding.js";
5
6
  // Bump when a step is added; completed steps stay completed, only new ids run.
6
- export const ONBOARDING_VERSION = 3;
7
+ export const ONBOARDING_VERSION = 4;
7
8
  async function yes(io, question) {
8
9
  return (await io.ask(`${question} [Y/n] `, "y")).trim().toLowerCase() !== "n";
9
10
  }
@@ -140,6 +141,24 @@ export function buildSteps(deps) {
140
141
  return "done";
141
142
  },
142
143
  },
144
+ {
145
+ id: "interests",
146
+ title: "Goals and interests (proposed for your review)",
147
+ optional: true,
148
+ async run(io) {
149
+ const answers = {};
150
+ for (const { key, question } of ONBOARDING_QUESTIONS)
151
+ answers[key] = (await io.ask(` ${question} `, "")).trim();
152
+ if (!Object.values(answers).some(Boolean))
153
+ return "skipped";
154
+ const result = await onboard(answers);
155
+ const count = result.facts.length + result.interests.proposed.length;
156
+ io.say(count
157
+ ? ` ${count} proposal(s) wait for review: ocean memory review`
158
+ : " Nothing new to propose.");
159
+ return "done";
160
+ },
161
+ },
143
162
  {
144
163
  id: "clients",
145
164
  title: "AI clients (which CLIs Ocean observes)",
@@ -0,0 +1,84 @@
1
+ import { readFile, stat } from "node:fs/promises";
2
+ import path from "node:path";
3
+ // The official claude.ai data export (Settings → Privacy → Export) as a source for the same
4
+ // capture as Desktop chat (T-315): `conversations.json` holds every conversation, from any
5
+ // device, as `{uuid, updated_at, chat_messages: [{uuid, sender, text, content, created_at}]}`.
6
+ // Messages are in order and carry no index, so the cursor is the message's creation time,
7
+ // which the Desktop store carries too: a conversation read from either is read once.
8
+ export class ClaudeExportError extends Error {
9
+ }
10
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
11
+ function isoDate(value) {
12
+ if (typeof value !== "string")
13
+ return "";
14
+ const time = Date.parse(value);
15
+ return Number.isNaN(time) ? "" : new Date(time).toISOString();
16
+ }
17
+ function messageText(message) {
18
+ if (Array.isArray(message.content)) {
19
+ const text = message.content
20
+ .filter((block) => isObject(block) &&
21
+ block.type === "text" &&
22
+ typeof block.text === "string")
23
+ .map((block) => block.text.trim())
24
+ .filter(Boolean)
25
+ .join("\n\n");
26
+ if (text)
27
+ return text;
28
+ }
29
+ return typeof message.text === "string" ? message.text.trim() : "";
30
+ }
31
+ export function exportConversation(raw) {
32
+ if (!isObject(raw) || typeof raw.uuid !== "string")
33
+ return null;
34
+ if (!Array.isArray(raw.chat_messages))
35
+ return null;
36
+ const messages = [];
37
+ raw.chat_messages.forEach((value, index) => {
38
+ if (!isObject(value))
39
+ return;
40
+ const sender = value.sender;
41
+ if (sender !== "human" && sender !== "assistant")
42
+ return;
43
+ messages.push({
44
+ uuid: typeof value.uuid === "string" ? value.uuid : `${raw.uuid}#${index}`,
45
+ index,
46
+ sender,
47
+ text: messageText(value),
48
+ createdAt: isoDate(value.created_at),
49
+ });
50
+ });
51
+ return {
52
+ uuid: raw.uuid,
53
+ updatedAt: isoDate(raw.updated_at) || (messages.at(-1)?.createdAt ?? ""),
54
+ messageCount: messages.length,
55
+ messages,
56
+ };
57
+ }
58
+ // Every conversation in an unpacked export folder, newest first.
59
+ export async function readExportChats(directory) {
60
+ const file = path.join(directory, "conversations.json");
61
+ if (!(await stat(file).catch(() => null)))
62
+ throw new ClaudeExportError(`conversations.json not found in ${directory}`);
63
+ let parsed;
64
+ try {
65
+ parsed = JSON.parse(await readFile(file, "utf8"));
66
+ }
67
+ catch {
68
+ throw new ClaudeExportError("conversations.json is not valid JSON");
69
+ }
70
+ if (!Array.isArray(parsed))
71
+ throw new ClaudeExportError("conversations.json is not a list");
72
+ const conversations = [];
73
+ let skipped = 0;
74
+ for (const raw of parsed) {
75
+ const conversation = exportConversation(raw);
76
+ if (conversation)
77
+ conversations.push(conversation);
78
+ else
79
+ skipped++;
80
+ }
81
+ conversations.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
82
+ return { status: "ok", conversations, skipped };
83
+ }
84
+ //# sourceMappingURL=claude-export.js.map
@@ -0,0 +1,165 @@
1
+ import { copyFile, mkdtemp, readdir, rm } from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { readIndexedDb } from "./indexeddb.js";
5
+ // Claude Desktop's plain chat, read from the app's own IndexedDB (T-315). The app keeps the
6
+ // conversations it has open or opened recently in the "trees" object store of its claude.ai
7
+ // origin: one record per conversation, holding the message tree. The format is undocumented
8
+ // and may change with any app update, so any surprise ends in DesktopChatUnreadable, and a
9
+ // record that does not decode is skipped. Read-only: the LevelDB folder is copied aside and the
10
+ // copy is read; the app's LOCK is never taken and nothing in its folders is written.
11
+ export const DESKTOP_CHAT_UNREADABLE = "DESKTOP_CHAT_UNREADABLE";
12
+ export class DesktopChatUnreadable extends Error {
13
+ code = DESKTOP_CHAT_UNREADABLE;
14
+ }
15
+ const ORIGIN = "https_claude.ai_0.indexeddb";
16
+ const TREES_STORE = "trees";
17
+ const ROOT_PARENT = "00000000-0000-4000-8000-000000000000";
18
+ const LEVELDB_FILE = /^(CURRENT|MANIFEST-\d+|\d+\.(log|ldb|sst))$/;
19
+ // Where Claude Desktop keeps its IndexedDB: the app's user-data folder on each platform.
20
+ export function desktopIndexedDbDir(home = os.homedir(), platform = process.platform) {
21
+ if (platform === "win32")
22
+ return path.join(process.env.APPDATA ?? path.join(home, "AppData", "Roaming"), "Claude", "IndexedDB");
23
+ if (platform === "darwin")
24
+ return path.join(home, "Library", "Application Support", "Claude", "IndexedDB");
25
+ return path.join(home, ".config", "Claude", "IndexedDB");
26
+ }
27
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
28
+ function isoDate(value) {
29
+ if (typeof value === "number" && Number.isFinite(value))
30
+ return new Date(value).toISOString();
31
+ if (typeof value === "string" && !Number.isNaN(Date.parse(value)))
32
+ return new Date(value).toISOString();
33
+ if (value instanceof Date && !Number.isNaN(value.getTime()))
34
+ return value.toISOString();
35
+ return null;
36
+ }
37
+ // The text of a message: its `text` blocks only. Thinking, tool calls, tool results and
38
+ // attachments are left out.
39
+ function messageText(content) {
40
+ if (!Array.isArray(content))
41
+ return "";
42
+ return content
43
+ .filter((block) => isObject(block) &&
44
+ block.type === "text" &&
45
+ typeof block.text === "string")
46
+ .map((block) => block.text.trim())
47
+ .filter(Boolean)
48
+ .join("\n\n");
49
+ }
50
+ function rawMessage(value) {
51
+ if (!isObject(value))
52
+ return null;
53
+ const { uuid, sender, index } = value;
54
+ if (typeof uuid !== "string" || typeof index !== "number")
55
+ return null;
56
+ if (sender !== "human" && sender !== "assistant")
57
+ return null;
58
+ return {
59
+ uuid,
60
+ index,
61
+ sender,
62
+ text: messageText(value.content),
63
+ createdAt: isoDate(value.created_at) ?? "",
64
+ parent: typeof value.parent_message_uuid === "string"
65
+ ? value.parent_message_uuid
66
+ : null,
67
+ };
68
+ }
69
+ // An edited or retried message leaves sibling branches in the tree. The conversation is the
70
+ // branch that ends at the newest leaf: highest index, then latest creation.
71
+ export function currentBranch(all) {
72
+ const byUuid = new Map(all.map((message) => [message.uuid, message]));
73
+ const parents = new Set(all.map((message) => message.parent));
74
+ const leaves = all.filter((message) => !parents.has(message.uuid));
75
+ leaves.sort((a, b) => b.index - a.index || b.createdAt.localeCompare(a.createdAt));
76
+ const branch = [];
77
+ const seen = new Set();
78
+ let cursor = leaves[0];
79
+ while (cursor && !seen.has(cursor.uuid)) {
80
+ seen.add(cursor.uuid);
81
+ const { parent, ...message } = cursor;
82
+ branch.push(message);
83
+ cursor = parent && parent !== ROOT_PARENT ? byUuid.get(parent) : undefined;
84
+ }
85
+ return branch.reverse();
86
+ }
87
+ export function conversationFromRecord(value) {
88
+ if (!isObject(value) || typeof value.conversationUuid !== "string")
89
+ return null;
90
+ const tree = value.tree;
91
+ if (!isObject(tree) || !Array.isArray(tree.messages))
92
+ return null;
93
+ const raw = tree.messages
94
+ .map(rawMessage)
95
+ .filter((m) => m !== null);
96
+ const messages = currentBranch(raw);
97
+ const updatedAt = isoDate(value.conversationUpdatedAt) ??
98
+ messages.at(-1)?.createdAt ??
99
+ isoDate(value.writtenAt) ??
100
+ "";
101
+ return {
102
+ uuid: value.conversationUuid,
103
+ updatedAt,
104
+ messageCount: messages.length,
105
+ messages,
106
+ };
107
+ }
108
+ // Copy the LevelDB files aside. A compaction can delete a file between listing and copying;
109
+ // then the copy starts over.
110
+ async function snapshot(source, target) {
111
+ for (let attempt = 0;; attempt++) {
112
+ try {
113
+ for (const name of (await readdir(source)).filter((n) => LEVELDB_FILE.test(n)))
114
+ await copyFile(path.join(source, name), path.join(target, name));
115
+ return;
116
+ }
117
+ catch (error) {
118
+ if (error.code !== "ENOENT" || attempt >= 2)
119
+ throw error;
120
+ }
121
+ }
122
+ }
123
+ export async function readDesktopChats(indexedDbDir = desktopIndexedDbDir()) {
124
+ const leveldb = path.join(indexedDbDir, `${ORIGIN}.leveldb`);
125
+ const blobs = path.join(indexedDbDir, `${ORIGIN}.blob`);
126
+ try {
127
+ await readdir(leveldb);
128
+ }
129
+ catch {
130
+ return { status: "absent" };
131
+ }
132
+ const copy = await mkdtemp(path.join(os.tmpdir(), "ocean-desktop-"));
133
+ try {
134
+ await snapshot(leveldb, copy);
135
+ const { records, skipped } = await readIndexedDb(copy, blobs, (store) => store === TREES_STORE);
136
+ const newest = new Map();
137
+ let unshaped = 0;
138
+ for (const record of records) {
139
+ const conversation = conversationFromRecord(record.value);
140
+ if (!conversation) {
141
+ unshaped++;
142
+ continue;
143
+ }
144
+ const seen = newest.get(conversation.uuid);
145
+ if (!seen || seen.updatedAt < conversation.updatedAt)
146
+ newest.set(conversation.uuid, conversation);
147
+ }
148
+ if (newest.size === 0 && skipped + unshaped > 0)
149
+ throw new DesktopChatUnreadable(`${skipped + unshaped} conversation record(s) found, none readable`);
150
+ return {
151
+ status: "ok",
152
+ conversations: [...newest.values()].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)),
153
+ skipped: skipped + unshaped,
154
+ };
155
+ }
156
+ catch (error) {
157
+ if (error instanceof DesktopChatUnreadable)
158
+ throw error;
159
+ throw new DesktopChatUnreadable(error.message);
160
+ }
161
+ finally {
162
+ await rm(copy, { recursive: true, force: true });
163
+ }
164
+ }
165
+ //# sourceMappingURL=desktop-chat.js.map