@audiofool/moondog 0.3.0-beta.9 → 0.3.1

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 (69) hide show
  1. package/README.md +100 -136
  2. package/package.json +9 -7
  3. package/scripts/moondog.mjs +47 -9
  4. package/src/core/apple-projection-domain-services.mjs +4 -0
  5. package/src/core/capability-catalog.mjs +46 -14
  6. package/src/core/host.mjs +30 -0
  7. package/src/core/library-store.mjs +82 -6
  8. package/src/core/listening-now.mjs +7 -2
  9. package/src/core/listening-profile-domain-services.mjs +4 -0
  10. package/src/core/moondog-application.mjs +412 -144
  11. package/src/i18n/messages/de.mjs +4 -3
  12. package/src/i18n/messages/en.mjs +4 -3
  13. package/src/i18n/messages/es.mjs +4 -3
  14. package/src/i18n/messages/fr.mjs +4 -3
  15. package/src/i18n/messages/it.mjs +4 -3
  16. package/src/i18n/messages/ja.mjs +4 -3
  17. package/src/i18n/messages/ko.mjs +4 -3
  18. package/src/i18n/messages/pt.mjs +4 -3
  19. package/src/i18n/messages/zh-Hant.mjs +4 -3
  20. package/src/i18n/messages/zh.mjs +4 -3
  21. package/src/i18n/screen/es.mjs +54 -7
  22. package/src/i18n/screen/ja.mjs +54 -7
  23. package/src/i18n/screen/pt.mjs +54 -7
  24. package/src/i18n/screen/zh.mjs +54 -7
  25. package/src/importers/zip-reader.mjs +61 -0
  26. package/src/integrations/apple-music/music-app.mjs +3 -2
  27. package/src/integrations/lastfm/history.mjs +2 -1
  28. package/src/integrations/lyrics/lrclib.mjs +1 -1
  29. package/src/integrations/netease/ncm-cli-player.mjs +62 -20
  30. package/src/integrations/open-music-similarity/artist-radio.mjs +3 -3
  31. package/src/integrations/playlist-links.mjs +114 -0
  32. package/src/integrations/public-playlists.mjs +41 -8
  33. package/src/integrations/spotify/account-data-history.mjs +63 -57
  34. package/src/integrations/spotify/authentication.mjs +2 -22
  35. package/src/integrations/spotify/extended-streaming-history.mjs +48 -40
  36. package/src/integrations/spotify/history-archive.mjs +2 -13
  37. package/src/integrations/spotify/service.mjs +88 -58
  38. package/src/integrations/spotify/web-api-client.mjs +12 -4
  39. package/src/integrations/user-agent.mjs +6 -0
  40. package/src/integrations/web/codex-web.mjs +3 -1
  41. package/src/integrations/web/deepseek-web.mjs +1 -1
  42. package/src/integrations/web/moondog-web.mjs +57 -0
  43. package/src/integrations/web/web-research.mjs +106 -22
  44. package/src/integrations/web/web-result.mjs +61 -12
  45. package/src/integrations/youtube-music/takeout.mjs +11 -16
  46. package/src/profile/history-import.mjs +3 -1
  47. package/src/profile/listening-history-store.mjs +55 -1
  48. package/src/profile/listening-profile-projection.mjs +1 -1
  49. package/src/profile/music-import-bundle.mjs +3 -1
  50. package/src/profile/music-providers.mjs +3 -0
  51. package/src/runtime/pi/agent-runtime.mjs +247 -148
  52. package/src/runtime/pi/configured-runtime.mjs +4 -1
  53. package/src/runtime/pi/image-input.mjs +148 -0
  54. package/src/runtime/pi/memory-agent-runtime.mjs +1 -1
  55. package/src/runtime/pi/model-roles.mjs +138 -0
  56. package/src/runtime/pi/model-settings.mjs +141 -6
  57. package/src/runtime/pi/model-transport.mjs +9 -0
  58. package/src/runtime/pi/moondog-model.mjs +159 -0
  59. package/src/runtime/pi/next-songs.mjs +71 -0
  60. package/src/runtime/pi/persistent-credential-store.mjs +2 -0
  61. package/src/runtime/pi/profile-build-runtime.mjs +1 -1
  62. package/src/runtime/pi/public-model-catalog.mjs +11 -4
  63. package/src/runtime/pi/runtime-settings.mjs +7 -3
  64. package/src/surfaces/cli/brand-components.mjs +3 -3
  65. package/src/surfaces/cli/command-completions.mjs +43 -3
  66. package/src/surfaces/cli/format-output.mjs +19 -7
  67. package/src/surfaces/cli/invite-command.mjs +65 -0
  68. package/src/surfaces/cli/model-roles-command.mjs +60 -0
  69. package/src/surfaces/cli/tui.mjs +91 -5
@@ -9,7 +9,6 @@ export const SPOTIFY_WEB_API_LIMITS = Object.freeze({
9
9
  queueItemsMax: 50,
10
10
  artistsPerItemMax: 5,
11
11
  searchResultsMax: 10,
12
- playlistTracksMax: 20,
13
12
  playlistsPageMax: 50,
14
13
  playlistItemsPageMax: 50,
15
14
  playlistEditTracksMax: 100,
@@ -160,14 +159,18 @@ function normalizeArtistNames(rawArtists) {
160
159
  }
161
160
 
162
161
  // Cover art a window can draw: one Spotify CDN image, the largest that is at most 640 pixels.
163
- function coverImage(images) {
162
+ function coverImage(images, allowed = /^https:\/\/i\.scdn\.co\/image\/[A-Za-z0-9_-]{1,128}$/u) {
164
163
  const usable = (Array.isArray(images) ? images : []).filter((image) =>
165
- typeof image?.url === "string" && /^https:\/\/i\.scdn\.co\/image\/[A-Za-z0-9_-]{1,128}$/u.test(image.url));
164
+ typeof image?.url === "string" && allowed.test(image.url));
166
165
  const sized = usable.filter((image) => !Number.isInteger(image.width) || image.width <= 640)
167
166
  .sort((left, right) => (right.width ?? 0) - (left.width ?? 0));
168
167
  return (sized[0] ?? usable.at(-1))?.url;
169
168
  }
170
169
 
170
+ // A playlist's cover lives on more hosts than an album's: one a listener uploaded on image-cdn-*.spotifycdn.com, the
171
+ // four-album mosaic on mosaic.scdn.co. The window's image policy (renderer/index.html) names the same two domains.
172
+ const PLAYLIST_COVER = /^https:\/\/[a-z0-9-]{1,40}\.(?:scdn\.co|spotifycdn\.com)\/[A-Za-z0-9_/-]{1,200}$/u;
173
+
171
174
  // A track's album, kept so a song played alone can go on into the rest of its album.
172
175
  // Hosts keep it next to the track URI and never show it to the model.
173
176
  function albumUri(raw) {
@@ -462,6 +465,8 @@ function normalizePlaylist(payload, { includeControlMetadata = false } = {}) {
462
465
  const snapshotId = safeText(payload.snapshot_id, 128);
463
466
  if (ownerId) playlist.owner_id = ownerId;
464
467
  if (snapshotId) playlist.snapshot_id = snapshotId;
468
+ const cover = coverImage(payload.images, PLAYLIST_COVER);
469
+ if (cover) playlist.image = cover;
465
470
  }
466
471
  const tracksTotal = safeInteger(
467
472
  payload.items?.total ?? payload.tracks?.total,
@@ -899,9 +904,12 @@ export function createSpotifyWebApiClient({
899
904
  await request("/me/playlists", {
900
905
  method: "POST",
901
906
  signal,
907
+ // Spotify writes the word "null" as the description when none is sent, so an empty one always goes.
908
+ // public: false asks to keep the playlist off the listener's profile. Spotify's own apps can still show it
909
+ // as a public playlist, and the Web API has no way to make one private, so no receipt calls it private.
902
910
  body: {
903
911
  name,
904
- ...(description ? { description } : {}),
912
+ description: description || "",
905
913
  public: false,
906
914
  },
907
915
  }),
@@ -0,0 +1,6 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ // The identity Moondog gives public music-data services: its name, version and project page.
4
+ const { version } = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
5
+
6
+ export const MOONDOG_USER_AGENT = `Moondog/${version} (https://github.com/Audiofool934/moondog)`;
@@ -6,6 +6,7 @@ import path from "node:path";
6
6
 
7
7
  import Ajv from "ajv";
8
8
 
9
+ import { environmentPathKey } from "../../core/host.mjs";
9
10
  import { createWebOperations, failure, webResult } from "./web-result.mjs";
10
11
 
11
12
  export { projectWebResearchResult, publicWebUrl } from "./web-result.mjs";
@@ -101,7 +102,8 @@ export async function runCodexProcess(binary, args, { environment, cwd, input =
101
102
  async function findCodex(environment) {
102
103
  const candidates = environment.MOONDOG_CODEX_BIN
103
104
  ? [environment.MOONDOG_CODEX_BIN]
104
- : (environment.PATH ?? "").split(path.delimiter).filter(Boolean).map((entry) => path.resolve(entry, "codex"));
105
+ : (environment[environmentPathKey(environment)] ?? "").split(path.delimiter).filter(Boolean)
106
+ .map((entry) => path.resolve(entry, process.platform === "win32" ? "codex.exe" : "codex"));
105
107
  for (const candidate of candidates) {
106
108
  if (!path.isAbsolute(candidate)) continue;
107
109
  try { await access(candidate, constants.X_OK); return candidate; } catch {}
@@ -69,7 +69,7 @@ export function createDeepSeekWebResearch({ apiKey, fetch: fetchImpl = globalThi
69
69
  if (status !== 200) throw serviceError(status, body);
70
70
  const title = typeof body.title === "string" && body.title.trim() ? clip(body.title.trim(), 300) : url;
71
71
  return webResult({ provider: "deepseek", kind: "read", status: "found", retrievedAt,
72
- summary: clip(text, webLimits.textChars), truncated: text.length > webLimits.textChars,
72
+ summary: clip(text, webLimits.fullTextChars), truncated: text.length > webLimits.fullTextChars,
73
73
  sources: [{ title, url, snippet: "", published_at: null }] });
74
74
  }
75
75
 
@@ -0,0 +1,57 @@
1
+ import { clip, createWebOperations, failure, requestWebService, searchSources, webLimits, webResult } from "./web-result.mjs";
2
+
3
+ // Moondog's own web search and page reading, through the same gateway and invite code as the
4
+ // Moondog model (see gateway/). Which service searches behind the gateway is the gateway's business.
5
+ // POST {gateway}/web/search { query, count } -> { results: [{ title, url, snippet, published_at }] }
6
+ // POST {gateway}/web/read { url } -> { status: "found", title, content } | { status: "unavailable" }
7
+ const limits = Object.freeze({ queryChars: 400, results: 10, searchTimeoutMs: 20_000, readTimeoutMs: 60_000 });
8
+
9
+ // The gateway's refusals, in the listener's terms. A search counts against the same daily allowance
10
+ // as the model.
11
+ function serviceError(status, body) {
12
+ const code = String(body?.error?.code ?? "");
13
+ if (code === "invite_invalid" || code === "invite_revoked") return failure("web_key_rejected", "Moondog's invite code no longer works. Enter a new one in Settings > Model.");
14
+ if (code === "beta_ended") return failure("web_service_failed", "The Moondog model's test period has ended, and its web search with it.");
15
+ if (code === "daily_allowance_used" || code === "beta_capacity_reached") {
16
+ return failure("web_quota_exhausted", "Today's Moondog allowance is used up, web search included. It starts again at midnight, Beijing time.");
17
+ }
18
+ if (status === 429) return failure("web_rate_limited", "Moondog's web search is limiting requests right now. Try again in a moment.");
19
+ if (status === 400) return failure("web_input_invalid", "Moondog's web search did not accept the request.");
20
+ return failure("web_service_failed", `Moondog's web search failed with HTTP ${status}. Try again in a moment.`);
21
+ }
22
+
23
+ export function createMoondogWebResearch({ baseUrl, apiKey, fetch: fetchImpl = globalThis.fetch, now = () => new Date() } = {}) {
24
+ const call = (operation, body, signal, timeoutMs) => requestWebService(fetchImpl, `${baseUrl}/web/${operation}`, {
25
+ name: "Moondog", method: "POST", signal, timeoutMs, body: JSON.stringify(body),
26
+ headers: { authorization: `Bearer ${apiKey}`, "content-type": "application/json", accept: "application/json" },
27
+ });
28
+
29
+ async function search(query, signal) {
30
+ const { status, body } = await call("search", { query, count: limits.results }, signal, limits.searchTimeoutMs);
31
+ if (status !== 200) throw serviceError(status, body);
32
+ if (!Array.isArray(body?.results)) throw failure("web_output_invalid", "Moondog's web search returned an unreadable result.");
33
+ const sources = searchSources(body.results);
34
+ return webResult({ provider: "moondog", kind: "search", status: sources.length ? "found" : "not_found", sources, retrievedAt: now().toISOString() });
35
+ }
36
+
37
+ async function read(url, signal) {
38
+ const { status, body } = await call("read", { url }, signal, limits.readTimeoutMs);
39
+ if (status !== 200) throw serviceError(status, body);
40
+ const retrievedAt = now().toISOString();
41
+ const text = body?.status === "found" && typeof body.content === "string" ? body.content.trim() : "";
42
+ if (!text) {
43
+ return webResult({ provider: "moondog", kind: "read", status: "unavailable", retrievedAt,
44
+ summary: "Moondog could not get readable text from this page. It may be down, blocked, or not a text page." });
45
+ }
46
+ const title = typeof body.title === "string" && body.title.trim() ? clip(body.title.trim(), 300) : url;
47
+ return webResult({ provider: "moondog", kind: "read", status: "found", retrievedAt,
48
+ summary: clip(text, webLimits.fullTextChars), truncated: text.length > webLimits.fullTextChars,
49
+ sources: [{ title, url, snippet: "", published_at: null }] });
50
+ }
51
+
52
+ return createWebOperations({
53
+ now, queryChars: limits.queryChars,
54
+ unavailable: () => apiKey ? null : failure("web_key_missing", "Moondog's web search needs an invite code. Enter one in Settings > Model."),
55
+ run: (kind, value, signal) => kind === "search" ? search(value, signal) : read(value, signal),
56
+ });
57
+ }
@@ -1,19 +1,29 @@
1
+ import { readModelRoles } from "../../runtime/pi/model-roles.mjs";
2
+ import { moondogModelUrl, readInvite } from "../../runtime/pi/moondog-model.mjs";
1
3
  import { createPersistentCredentialStore } from "../../runtime/pi/persistent-credential-store.mjs";
2
4
  import { createBraveWebResearch } from "./brave-web.mjs";
3
5
  import { createCodexWebResearch } from "./codex-web.mjs";
4
6
  import { createDeepSeekWebResearch } from "./deepseek-web.mjs";
7
+ import { createMoondogWebResearch } from "./moondog-web.mjs";
5
8
  import { failure, webProviderName } from "./web-result.mjs";
6
9
 
7
10
  // Search goes to the first backend that is set up; reading needs a backend that can open pages.
8
- // MOONDOG_WEB_SEARCH_PROVIDER and MOONDOG_WEB_READ_PROVIDER pick one instead.
9
- const order = Object.freeze({ search: ["deepseek", "brave", "codex"], read: ["deepseek", "codex"] });
10
- const providerIds = Object.freeze({ deepseek: "deepseek", brave: "brave", codex: "codex_cli" });
11
+ // Moondog's own comes first: a listener with an invite code has it without a key of their own.
12
+ // The web search role in Settings (model-roles.json) picks one instead, and MOONDOG_WEB_SEARCH_PROVIDER
13
+ // and MOONDOG_WEB_READ_PROVIDER pick over that. As in Hermes Agent, a call that fails on the chosen
14
+ // backend is tried once more on each other backend that is set up, so one service being down or out
15
+ // of credit doesn't leave the agent without the web.
16
+ const order = Object.freeze({ search: ["moondog", "deepseek", "brave", "codex"], read: ["moondog", "deepseek", "codex"] });
17
+ // Failures that another backend would only repeat.
18
+ const final = new Set(["web_cancelled", "web_input_invalid", "web_url_invalid"]);
19
+ const providerIds = Object.freeze({ moondog: "moondog", deepseek: "deepseek", brave: "brave", codex: "codex_cli" });
11
20
  const keys = Object.freeze({
12
21
  deepseek: { credential: "deepseek", variable: "DEEPSEEK_API_KEY" },
13
22
  brave: { credential: "brave", variable: "BRAVE_SEARCH_API_KEY" },
14
23
  });
15
24
 
16
25
  export const webSetupText = [
26
+ "- `/invite <code>` - Moondog's own search and page reading, on your invite code's daily allowance",
17
27
  "- `/auth deepseek` - DeepSeek Search and Fetch: search and page reading, $0.75 per 1,000 requests each",
18
28
  "- `/auth brave` - Brave Search: search only, with a free monthly credit",
19
29
  "- Install the Codex CLI and run `codex login` - search and reading through your ChatGPT plan",
@@ -33,43 +43,118 @@ export async function createWebResearch({
33
43
  credentials = createPersistentCredentialStore(environment),
34
44
  fetch = globalThis.fetch,
35
45
  createCodex = createCodexWebResearch,
46
+ readRoles = readModelRoles,
47
+ readCode = readInvite,
36
48
  now,
37
49
  } = {}) {
38
- let current = { backends: {}, choices: {} };
50
+ let current = { backends: {}, choices: {}, found: {} };
51
+
52
+ // A backend whose key did not change keeps its cache. A working Codex stays; one that was not ready
53
+ // is checked again, since the listener may have signed in since.
54
+ async function backendFor(name, found, previous) {
55
+ if (name === "codex") {
56
+ const kept = previous?.backends.codex;
57
+ return kept?.publicStatus().state === "configured" ? kept : createCodex({ environment, now });
58
+ }
59
+ const kept = previous?.backends[name] && previous.found[name]?.key === found[name]?.key;
60
+ if (kept) return previous.backends[name];
61
+ if (name === "moondog") return createMoondogWebResearch({ baseUrl: moondogModelUrl(environment), apiKey: found.moondog?.key, fetch, now });
62
+ return { deepseek: createDeepSeekWebResearch, brave: createBraveWebResearch }[name]({ apiKey: found[name]?.key, fetch, now });
63
+ }
39
64
 
40
65
  async function load(previous) {
66
+ const invite = await readCode(environment).catch(() => null);
41
67
  const found = {
68
+ moondog: invite?.code ? { key: invite.code, source: "your invite code" } : null,
42
69
  deepseek: await readKey(credentials, environment, keys.deepseek),
43
70
  brave: await readKey(credentials, environment, keys.brave),
44
71
  };
72
+ const role = (await readRoles(environment).catch(() => ({}))).web_search?.service ?? null;
45
73
  const choices = {};
46
74
  for (const kind of ["search", "read"]) {
47
75
  const wanted = environment[`MOONDOG_WEB_${kind.toUpperCase()}_PROVIDER`]?.trim().toLowerCase();
48
- if (wanted) choices[kind] = order[kind].includes(wanted) ? { name: wanted, override: true } : { name: null, reason: "web_provider_unknown", wanted };
76
+ if (wanted) choices[kind] = order[kind].includes(wanted) ? { name: wanted, selectedBy: `MOONDOG_WEB_${kind.toUpperCase()}_PROVIDER` } : { name: null, reason: "web_provider_unknown", wanted };
77
+ // Brave only searches, so with Brave chosen a read still goes to the first backend that can.
78
+ else if (role && order[kind].includes(role)) choices[kind] = { name: role, selectedBy: "settings" };
49
79
  else choices[kind] = { name: order[kind].find((name) => name !== "codex" && found[name]) ?? "codex" };
50
80
  }
51
81
  const backends = {};
52
82
  for (const name of new Set(Object.values(choices).map((choice) => choice.name).filter(Boolean))) {
53
- // A backend whose key did not change keeps its cache.
54
- const create = { deepseek: createDeepSeekWebResearch, brave: createBraveWebResearch }[name];
55
- if (create) {
56
- const kept = previous?.backends[name] && previous.found[name]?.key === found[name]?.key;
57
- backends[name] = kept ? previous.backends[name] : create({ apiKey: found[name]?.key, fetch, now });
58
- }
59
- // A working Codex stays; one that was not ready is checked again, since the listener may have signed in since.
60
- if (name === "codex") {
61
- const kept = previous?.backends.codex;
62
- backends.codex = kept?.publicStatus().state === "configured" ? kept : await createCodex({ environment, now });
63
- }
83
+ backends[name] = await backendFor(name, found, previous);
64
84
  }
65
85
  return { backends, choices, found };
66
86
  }
67
87
 
88
+ // The other backends a failed call can go to: ones with a key, and Codex once it is signed in.
89
+ async function alternatives(kind, tried) {
90
+ const names = [];
91
+ for (const name of order[kind]) {
92
+ if (name === tried) continue;
93
+ if (name !== "codex" && !current.found[name]) continue;
94
+ current.backends[name] ??= await backendFor(name, current.found, null);
95
+ if (name === "codex" && current.backends.codex.publicStatus().state !== "configured") continue;
96
+ names.push(name);
97
+ }
98
+ return names;
99
+ }
100
+
101
+ // Settings, an invite code or a key can change in another window or the terminal, so each call
102
+ // reads them again first. A backend whose key did not change is kept.
103
+ async function reload() {
104
+ const previous = current;
105
+ current = await load(previous);
106
+ for (const [name, entry] of Object.entries(previous.backends)) if (current.backends[name] !== entry) entry.close();
107
+ }
108
+
109
+ async function research(kind, input, options) {
110
+ await reload();
111
+ const first = backend(kind);
112
+ const name = current.choices[kind].name;
113
+ let failed;
114
+ try {
115
+ const result = await first[kind](input, options);
116
+ // A page the chosen backend could not read may open on another.
117
+ if (kind === "search" || result.status !== "unavailable") return result;
118
+ failed = result;
119
+ } catch (error) {
120
+ if (final.has(error?.code) || options?.signal?.aborted) throw error;
121
+ failed = error;
122
+ }
123
+ for (const other of await alternatives(kind, name)) {
124
+ try {
125
+ const result = await current.backends[other][kind](input, options);
126
+ if (kind === "search" || result.status !== "unavailable") return { ...result, fallback_from: providerIds[name] };
127
+ } catch (error) {
128
+ if (final.has(error?.code) || options?.signal?.aborted) throw error;
129
+ }
130
+ }
131
+ if (failed instanceof Error) throw failed;
132
+ return failed;
133
+ }
134
+
135
+ /** Each service, whether it is set up for each operation, and which one the role chose; for Settings. */
136
+ async function services() {
137
+ await reload();
138
+ const role = (await readRoles(environment).catch(() => ({}))).web_search?.service ?? null;
139
+ current.backends.codex ??= await backendFor("codex", current.found, null);
140
+ const codex = current.backends.codex.publicStatus().state === "configured";
141
+ return {
142
+ chosen: role,
143
+ search: operationStatus("search"),
144
+ read: operationStatus("read"),
145
+ services: order.search.map((name) => {
146
+ const ready = name === "codex" ? codex : Boolean(current.found[name]);
147
+ return { id: name, provider: providerIds[name], name: webProviderName(providerIds[name]), ready,
148
+ search: ready, read: ready && order.read.includes(name) };
149
+ }),
150
+ };
151
+ }
152
+
68
153
  function operationStatus(kind) {
69
154
  const choice = current.choices[kind];
70
155
  if (!choice?.name) return { provider: null, state: "unavailable", reason: choice?.reason ?? "web_provider_unknown", ...(choice?.wanted ? { requested: choice.wanted } : {}) };
71
156
  const provider = providerIds[choice.name];
72
- const override = choice.override ? { selected_by: `MOONDOG_WEB_${kind.toUpperCase()}_PROVIDER` } : {};
157
+ const override = choice.selectedBy ? { selected_by: choice.selectedBy } : {};
73
158
  if (choice.name === "codex") {
74
159
  const codex = current.backends.codex.publicStatus();
75
160
  return { provider, state: codex.state, ...(codex.reason ? { reason: codex.reason } : {}), ...override };
@@ -103,13 +188,12 @@ export async function createWebResearch({
103
188
  current = await load();
104
189
  return {
105
190
  publicStatus,
106
- search: async (input, options) => backend("search").search(input, options),
107
- read: async (input, options) => backend("read").read(input, options),
191
+ services,
192
+ search: (input, options) => research("search", input, options),
193
+ read: (input, options) => research("read", input, options),
108
194
  /** Reads keys and settings again, after /auth or /reload. */
109
195
  async refresh() {
110
- const previous = current;
111
- current = await load(previous);
112
- for (const [name, entry] of Object.entries(previous.backends)) if (current.backends[name] !== entry) entry.close();
196
+ await reload();
113
197
  return publicStatus();
114
198
  },
115
199
  close: closeAll,
@@ -4,12 +4,17 @@ import Ajv from "ajv";
4
4
 
5
5
  // Every web backend returns this one result shape, checked by the same rules,
6
6
  // so the agent and the screen never need to know which service answered.
7
+ // After Hermes Agent's web tools: a search gives five sources unless the agent asks for up to ten,
8
+ // and a read keeps the page's whole text, handing it out a window at a time; the agent asks for the
9
+ // next window with next_offset instead of losing everything past the first.
7
10
  export const webLimits = Object.freeze({
8
- sources: 5, snippetChars: 800, textChars: 12_000, cacheMs: 300_000, cacheEntries: 32, responseBytes: 2_000_000,
11
+ sources: 5, maxSources: 10, snippetChars: 1200, textChars: 15_000, fullTextChars: 200_000,
12
+ cacheMs: 300_000, cacheEntries: 32, responseBytes: 2_000_000,
9
13
  });
10
14
 
11
15
  // What each backend's text is, so the agent can tell a search engine's snippet from a model's summary.
12
16
  const backends = Object.freeze({
17
+ moondog: { name: "Moondog", evidence: "provider_api_response", content: { search: "search_engine_results", read: "fetched_page_text" } },
13
18
  codex_cli: { name: "Codex CLI", evidence: "native_web_operation_observed", content: { search: "model_generated_web_summary", read: "model_generated_web_summary" } },
14
19
  deepseek: { name: "DeepSeek", evidence: "provider_api_response", content: { search: "search_engine_results", read: "fetched_page_text" } },
15
20
  brave: { name: "Brave Search", evidence: "provider_api_response", content: { search: "search_engine_results" } },
@@ -19,13 +24,14 @@ export function webProviderName(provider) {
19
24
  return backends[provider]?.name ?? null;
20
25
  }
21
26
 
22
- const resultSchema = {
27
+ // A backend's result holds a page's whole text; the agent's holds one window of it.
28
+ const resultSchema = (textChars) => ({
23
29
  type: "object", additionalProperties: false,
24
30
  properties: {
25
31
  status: { type: "string", enum: ["found", "not_found", "unavailable"] },
26
- summary: { type: "string", maxLength: webLimits.textChars },
32
+ summary: { type: "string", maxLength: textChars },
27
33
  sources: {
28
- type: "array", maxItems: webLimits.sources,
34
+ type: "array", maxItems: webLimits.maxSources,
29
35
  items: {
30
36
  type: "object", additionalProperties: false,
31
37
  properties: {
@@ -39,8 +45,11 @@ const resultSchema = {
39
45
  },
40
46
  },
41
47
  required: ["status", "summary", "sources"],
42
- };
43
- const validate = new Ajv({ strict: false }).compile(resultSchema);
48
+ });
49
+ const ajv = new Ajv({ strict: false });
50
+ const validate = ajv.compile(resultSchema(webLimits.fullTextChars));
51
+ const validateWindow = ajv.compile(resultSchema(webLimits.textChars));
52
+ const offsetOf = (value) => (Number.isInteger(value) && value >= 0 ? value : null);
44
53
 
45
54
  export function failure(code, message) {
46
55
  return Object.assign(new Error(message), { code });
@@ -101,7 +110,7 @@ export function webResult({ provider, kind, status, summary = "", sources = [],
101
110
  export function projectWebResearchResult(value) {
102
111
  const payload = { status: value?.status, summary: value?.summary, sources: value?.sources };
103
112
  const backend = backends[value?.provider];
104
- if (!validate(payload) || (payload.status === "found" && !payload.sources.length) ||
113
+ if (!validateWindow(payload) || (payload.status === "found" && !payload.sources.length) ||
105
114
  !backend?.content[value.kind] || value.evidence !== backend.evidence || !Number.isFinite(Date.parse(value.retrieved_at))) {
106
115
  throw failure("web_output_invalid", `${backend?.name ?? "The web service"} returned an invalid or unsourced research result.`);
107
116
  }
@@ -110,6 +119,9 @@ export function projectWebResearchResult(value) {
110
119
  retrieved_at: new Date(value.retrieved_at).toISOString(), from_cache: value.from_cache === true,
111
120
  content_kind: backend.content[value.kind], trust: "untrusted_web_content", evidence: backend.evidence,
112
121
  ...(value.truncated === true ? { truncated: true } : {}),
122
+ ...(value.kind === "read" && offsetOf(value.total_chars) !== null ? {
123
+ text_offset: offsetOf(value.text_offset) ?? 0, total_chars: value.total_chars, next_offset: offsetOf(value.next_offset),
124
+ } : {}),
113
125
  summary: cleanText(payload.summary), sources: projectSources(payload.sources),
114
126
  };
115
127
  }
@@ -131,14 +143,46 @@ export function searchSources(items) {
131
143
  if (snippet) seen.add(snippet);
132
144
  const date = typeof item.published_at === "string" ? cleanText(item.published_at).slice(0, 100) : "";
133
145
  sources.push({ title, url, snippet, published_at: date || null });
134
- if (sources.length === webLimits.sources) break;
146
+ if (sources.length === webLimits.maxSources) break;
135
147
  }
136
148
  return sources;
137
149
  }
138
150
 
151
+ // One window of a page's text, ending at a line or word break near the limit when there is one.
152
+ function textWindow(text, offset) {
153
+ let end = Math.min(text.length, offset + webLimits.textChars);
154
+ if (end < text.length) {
155
+ const floor = offset + Math.floor(webLimits.textChars * 0.8);
156
+ const lineBreak = text.lastIndexOf("\n", end);
157
+ const space = text.lastIndexOf(" ", end);
158
+ end = lineBreak > floor ? lineBreak : space > floor ? space : end;
159
+ }
160
+ return { summary: text.slice(offset, end), end };
161
+ }
162
+
163
+ /** What one call asked for: up to `limit` sources of a search, or the window of a read from `offset`. */
164
+ function windowed(result, kind, { limit, offset }) {
165
+ if (kind === "search") return { ...result, sources: result.sources.slice(0, limit) };
166
+ const text = result.summary;
167
+ if (offset > 0 && offset >= text.length) {
168
+ throw failure("web_input_invalid", `The page has ${text.length} characters, so offset ${offset} is past its end.`);
169
+ }
170
+ const { summary, end } = textWindow(text, offset);
171
+ const more = end < text.length;
172
+ return { ...result, summary, text_offset: offset, total_chars: text.length, next_offset: more ? end : null,
173
+ ...(more || result.truncated ? { truncated: true } : {}) };
174
+ }
175
+
176
+ function integerIn(value, minimum, maximum, fallback, message) {
177
+ if (value === undefined) return fallback;
178
+ if (!Number.isInteger(value) || value < minimum || value > maximum) throw failure("web_input_invalid", message);
179
+ return value;
180
+ }
181
+
139
182
  /**
140
183
  * The parts every backend shares: one query or URL in, a cancellable request,
141
- * and a five-minute process-local cache of found results.
184
+ * and a five-minute process-local cache of found results. The cache keeps the whole result, so a
185
+ * smaller limit or a later window of the same page needs no second request.
142
186
  */
143
187
  export function createWebOperations({ unavailable = () => null, queryChars = 500, run, now = () => new Date() }) {
144
188
  const cache = new Map();
@@ -146,9 +190,14 @@ export function createWebOperations({ unavailable = () => null, queryChars = 500
146
190
  async function research(kind, input, { signal } = {}) {
147
191
  const blocked = unavailable(kind);
148
192
  if (blocked) throw blocked;
149
- if (!input || typeof input !== "object" || Object.keys(input).some((key) => key !== (kind === "search" ? "query" : "url"))) {
193
+ const allowed = kind === "search" ? ["query", "limit"] : ["url", "offset"];
194
+ if (!input || typeof input !== "object" || Object.keys(input).some((key) => !allowed.includes(key))) {
150
195
  throw failure("web_input_invalid", "Supply one search query or public URL.");
151
196
  }
197
+ const view = {
198
+ limit: integerIn(input.limit, 1, webLimits.maxSources, webLimits.sources, `Ask for 1 to ${webLimits.maxSources} search results.`),
199
+ offset: integerIn(input.offset, 0, webLimits.fullTextChars, 0, "The offset must be a whole number of characters, from 0."),
200
+ };
152
201
  const value = kind === "read" ? publicWebUrl(input.url) : typeof input.query === "string" ? input.query.trim() : input.query;
153
202
  if (typeof value !== "string" || !value) throw failure("web_input_invalid", "The web query or URL is empty.");
154
203
  if (value.length > (kind === "search" ? queryChars : 2048)) {
@@ -158,7 +207,7 @@ export function createWebOperations({ unavailable = () => null, queryChars = 500
158
207
  const key = `${kind}:${value}`;
159
208
  const cached = cache.get(key);
160
209
  if (cached && now().getTime() - Date.parse(cached.retrieved_at) < webLimits.cacheMs) {
161
- return { ...structuredClone(cached), from_cache: true };
210
+ return windowed({ ...structuredClone(cached), from_cache: true }, kind, view);
162
211
  }
163
212
  const controller = new AbortController();
164
213
  active.add(controller);
@@ -168,7 +217,7 @@ export function createWebOperations({ unavailable = () => null, queryChars = 500
168
217
  cache.set(key, result);
169
218
  if (cache.size > webLimits.cacheEntries) cache.delete(cache.keys().next().value);
170
219
  }
171
- return structuredClone(result);
220
+ return windowed(structuredClone(result), kind, view);
172
221
  } finally {
173
222
  active.delete(controller);
174
223
  }
@@ -1,12 +1,9 @@
1
- import { execFile } from "node:child_process";
2
1
  import { constants } from "node:fs";
3
- import { open, mkdtemp, writeFile, rm } from "node:fs/promises";
4
- import { tmpdir } from "node:os";
2
+ import { open } from "node:fs/promises";
5
3
  import path from "node:path";
6
- import { promisify } from "node:util";
4
+ import { openZipArchive } from "../../importers/zip-reader.mjs";
7
5
  import { musicHash, prepareMusicBundle } from "../../profile/music-import-bundle.mjs";
8
6
 
9
- const exec = promisify(execFile);
10
7
  const maximumBytes = 256 * 1024 * 1024;
11
8
  const memberBytes = 64 * 1024 * 1024;
12
9
  const maximumRecords = 100_000;
@@ -103,27 +100,25 @@ export async function readYouTubeMusicTakeout({ filePath, subjectId, capturedAt
103
100
  const sources = [];
104
101
  if (/\.zip$/iu.test(filePath)) {
105
102
  // Read from one private snapshot: manifest digest and preview describe exactly the same bytes.
106
- const root = await mkdtemp(path.join(tmpdir(), "moondog-takeout-"));
103
+ let zip;
107
104
  try {
108
- const zip = path.join(root, "takeout.zip");
109
- await writeFile(zip, bytes, { mode: 0o600 });
110
- const { stdout } = await exec("unzip", ["-Z1", zip], { maxBuffer: 1024 * 1024, timeout: 15_000 });
111
- const names = stdout.trimEnd().split("\n");
112
- const selected = names.filter((name) => /(?:^|\/)(?:watch-history\.json|music[- ]library[- ]songs\.csv|library[- ]songs\.csv)$/iu.test(name));
105
+ zip = await openZipArchive(bytes);
106
+ } catch {
107
+ throw new Error("Could not read this Takeout ZIP. Finish the download and use an unencrypted ZIP, or extract music-library-songs.csv and watch-history.json and import each file.");
108
+ }
109
+ try {
110
+ const selected = zip.names.filter((name) => /(?:^|\/)(?:watch-history\.json|music[- ]library[- ]songs\.csv|library[- ]songs\.csv)$/iu.test(name));
113
111
  if (!selected.length) throw new Error("No supported YouTube Music files in this ZIP. Include music library songs and history in Google Takeout; set history format to JSON, not HTML.");
114
112
  if (selected.length > 100 || new Set(selected).size !== selected.length) throw new Error("Takeout contains too many or duplicate music files.");
115
113
  let total = 0;
116
114
  for (const name of selected) {
117
115
  if (name.startsWith("/") || name.split("/").includes("..") || /[\\*?\[\]\u0000-\u001f\u007f]/u.test(name)) throw new Error("Unsupported archive member path.");
118
- const { stdout: content } = await exec("unzip", ["-p", zip, name], { encoding: "buffer", maxBuffer: memberBytes, timeout: 15_000 });
116
+ const content = await zip.read(name, memberBytes);
119
117
  total += content.length;
120
118
  if (total > maximumBytes) throw new Error("Unpacked music data exceeds 256 MB. Import the extracted files separately.");
121
119
  sources.push({ name: `${musicHash(name).slice(0, 12)}-${path.basename(name)}`, content });
122
120
  }
123
- } catch (error) {
124
- if (error.cmd || error.code === "ENOENT") throw new Error("Could not read this Takeout ZIP. Finish the download and use an unencrypted ZIP, or extract music-library-songs.csv and watch-history.json and import each file. ZIP reading requires unzip on this computer.");
125
- throw error;
126
- } finally { await rm(root, { recursive: true, force: true }); }
121
+ } finally { zip.close(); }
127
122
  } else {
128
123
  if (bytes.length > memberBytes) throw new Error("Choose a music CSV or history JSON smaller than 64 MB.");
129
124
  sources.push({ name: path.basename(filePath), content: bytes });
@@ -85,7 +85,9 @@ function literalPath(input) {
85
85
  if (quote && character === quote) {
86
86
  fail("history_import_path_invalid", "Paste one complete file path, not several quoted arguments.");
87
87
  }
88
- if (character === "\\" && quote !== "'") {
88
+ // Windows paths use backslashes as separators, including paths from the desktop file picker.
89
+ // Only POSIX input uses backslashes to escape spaces or shell punctuation.
90
+ if (character === "\\" && quote !== "'" && process.platform !== "win32") {
89
91
  const next = value[index + 1];
90
92
  const allowed = quote === '"' ? /["\\$`]/u : /[ \t()\[\]{}!&;'"\\#$~`]/u;
91
93
  if (!next || !allowed.test(next)) {
@@ -386,7 +386,7 @@ function normalizedProfileInput(value, batch) {
386
386
  record.provenance.source_kind !== "import" ||
387
387
  !(record.provenance.source_system === "spotify_account_data" ||
388
388
  (record.provenance.source_system === "spotify_web_api" && profileImport.source_key === "spotify.web_api_library") ||
389
- (["youtube_music", "qq_music", "netease", "lastfm"].includes(record.provenance.source_system) &&
389
+ (["youtube_music", "qq_music", "netease", "lastfm", "spotify_playlist", "apple_music_playlist"].includes(record.provenance.source_system) &&
390
390
  profileImport.source_key === `${record.provenance.source_system}.music_import`)) ||
391
391
  !profileImport.member_names.includes(record.provenance.source_member) ||
392
392
  record.provenance.profile_import_id?.toLowerCase() !== profileImportId ||
@@ -844,6 +844,7 @@ export class ListeningHistoryStore {
844
844
  #coverageSources = null;
845
845
  #evidence = null;
846
846
  #ledgerChanges = 0;
847
+ #listeningDays = null;
847
848
 
848
849
  constructor(database) {
849
850
  this.#database = database;
@@ -2058,6 +2059,59 @@ export class ListeningHistoryStore {
2058
2059
  ...(started.length ? { moondog_started_plays: started.length } : {}), top_artists: artists });
2059
2060
  }
2060
2061
 
2062
+ // The listener's own plays a local day at a time, for the window's taste record: every day's plays, the
2063
+ // same for the most played artists, and the plays Moondog started, kept apart as recentAttention keeps
2064
+ // them. Counts and artist names only. Kept until the stored plays change, since a long history is many rows.
2065
+ listeningDays({ subjectId, artists = 8 } = {}) {
2066
+ if (this.#closed) throw new Error("Listening history store is closed");
2067
+ if (!isUuid(subjectId)) throw new TypeError("A valid profile subject is required");
2068
+ if (!Number.isSafeInteger(artists) || artists < 0 || artists > 20) throw new TypeError("Artist count is invalid");
2069
+ const subject = subjectId.toLowerCase();
2070
+ const version = `${this.listeningDataVersion()}:${subject}:${artists}`;
2071
+ if (this.#listeningDays?.version === version) return structuredClone(this.#listeningDays.value);
2072
+ const effective = `e.subject_id = ?
2073
+ AND NOT EXISTS (SELECT 1 FROM listening_event_supersessions s WHERE s.superseded_event_id = e.listening_event_id)
2074
+ AND NOT EXISTS (SELECT 1 FROM listening_event_mirrors m WHERE m.mirror_event_id = e.listening_event_id)`;
2075
+ const suggestions = this.#suggestionsForMatching();
2076
+ const since = suggestions.length ? new Date(Date.parse(suggestions[0].requested_at) - SUGGESTION_WINDOW.beforeMs).toISOString() : null;
2077
+ const started = !since ? [] : markMoondogStartedPlays(this.#database.prepare(`SELECT
2078
+ e.listening_event_id, e.record_json AS event_json, t.record_json AS track_json FROM listening_events e
2079
+ JOIN track_refs t ON t.track_ref_id = e.track_ref_id AND t.revision = e.track_ref_revision
2080
+ WHERE ${effective} AND e.occurred_at >= ?`)
2081
+ .all(subject, since).map((row) => ({ id: row.listening_event_id, event: JSON.parse(row.event_json), track: JSON.parse(row.track_json) })),
2082
+ suggestions).rows.filter((row) => row.moondog_suggestion_id).map((row) => row.id);
2083
+ const own = `${effective} AND e.listening_event_id NOT IN (SELECT value FROM json_each(?))`;
2084
+ const left = JSON.stringify(started);
2085
+ const pairs = (rows) => rows.map((row) => [row.day, row.plays]);
2086
+ const days = this.#database.prepare(`SELECT date(e.occurred_at, 'localtime') AS day, COUNT(*) AS plays
2087
+ FROM listening_events e WHERE ${own} GROUP BY day ORDER BY day`).all(subject, left);
2088
+ let value = null;
2089
+ if (days.length) {
2090
+ const credited = `FROM listening_events e
2091
+ JOIN track_refs t ON t.track_ref_id = e.track_ref_id AND t.revision = e.track_ref_revision
2092
+ JOIN json_each(t.record_json, '$.artist_credits') a
2093
+ WHERE ${own} AND json_extract(a.value, '$.name') IS NOT NULL`;
2094
+ const top = artists === 0 ? [] : this.#database.prepare(`SELECT json_extract(a.value, '$.name') AS name, COUNT(*) AS plays
2095
+ ${credited} GROUP BY name ORDER BY plays DESC, name LIMIT ?`).all(subject, left, artists);
2096
+ const byArtist = new Map(top.map((row) => [row.name, []]));
2097
+ if (top.length) {
2098
+ for (const row of this.#database.prepare(`SELECT json_extract(a.value, '$.name') AS name,
2099
+ date(e.occurred_at, 'localtime') AS day, COUNT(*) AS plays
2100
+ ${credited} AND json_extract(a.value, '$.name') IN (SELECT value FROM json_each(?))
2101
+ GROUP BY name, day ORDER BY day`).iterate(subject, left, JSON.stringify(top.map((artist) => artist.name)))) {
2102
+ byArtist.get(row.name)?.push([row.day, row.plays]);
2103
+ }
2104
+ }
2105
+ const moondog = started.length ? this.#database.prepare(`SELECT date(occurred_at, 'localtime') AS day, COUNT(*) AS plays
2106
+ FROM listening_events WHERE listening_event_id IN (SELECT value FROM json_each(?)) GROUP BY day ORDER BY day`).all(left) : [];
2107
+ value = { first_day: days[0].day, last_day: days.at(-1).day, days: pairs(days),
2108
+ artists: top.map((artist) => ({ name: artist.name, plays: artist.plays, days: byArtist.get(artist.name) })),
2109
+ moondog_days: pairs(moondog) };
2110
+ }
2111
+ this.#listeningDays = { version, value };
2112
+ return structuredClone(value);
2113
+ }
2114
+
2061
2115
  // Which spans of time the stored plays cover, and where plays may be missing.
2062
2116
  listeningCoverage({ subjectId } = {}) {
2063
2117
  if (this.#closed) throw new Error("Listening history store is closed");
@@ -1616,7 +1616,7 @@ function persistedExplanation(record) {
1616
1616
  library_artist_followed: `The artist appears in the followed-artists snapshot captured at ${record.provenance.captured_at}.`,
1617
1617
  library_track_banned: `The track appears in the explicitly banned-tracks snapshot captured at ${record.provenance.captured_at}.`,
1618
1618
  library_artist_banned: `The artist appears in the explicitly banned-artists snapshot captured at ${record.provenance.captured_at}.`,
1619
- playlist_track_added: `The track appears in the ${provider} playlist named ${JSON.stringify(attributes.playlist_name)} at position ${attributes.playlist_position}.` + (attributes.selected_public_playlist ? " You selected this public playlist; ownership and listening are not established." : ""),
1619
+ playlist_track_added: `The track appears in the ${provider} playlist named ${JSON.stringify(attributes.playlist_name)} at position ${attributes.playlist_position}.` + (attributes.listener_made ? " You made this playlist; listening is not established." : attributes.selected_public_playlist ? " You selected this public playlist; ownership and listening are not established." : ""),
1620
1620
  search_result_interacted: `A Spotify search for ${JSON.stringify(label)} led to an interaction with a ${attributes.result_entity_type} result at ${record.observed_at}.`,
1621
1621
  wrapped_track_ranked: `Spotify Wrapped ranked this track at position ${attributes.rank} for ${attributes.period}.`,
1622
1622
  wrapped_artist_ranked: `Spotify Wrapped ranked this artist at position ${attributes.rank} for ${attributes.period}.`,