@audiofool/moondog 0.3.0-beta.9 → 0.3.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 (66) hide show
  1. package/README.md +40 -12
  2. package/package.json +5 -4
  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 +52 -6
  22. package/src/i18n/screen/ja.mjs +52 -6
  23. package/src/i18n/screen/pt.mjs +52 -6
  24. package/src/i18n/screen/zh.mjs +52 -6
  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/web-research.mjs +84 -17
  43. package/src/integrations/web/web-result.mjs +60 -12
  44. package/src/integrations/youtube-music/takeout.mjs +11 -16
  45. package/src/profile/history-import.mjs +3 -1
  46. package/src/profile/listening-history-store.mjs +55 -1
  47. package/src/profile/listening-profile-projection.mjs +1 -1
  48. package/src/profile/music-import-bundle.mjs +3 -1
  49. package/src/profile/music-providers.mjs +3 -0
  50. package/src/runtime/pi/agent-runtime.mjs +244 -146
  51. package/src/runtime/pi/configured-runtime.mjs +3 -0
  52. package/src/runtime/pi/image-input.mjs +148 -0
  53. package/src/runtime/pi/model-roles.mjs +121 -0
  54. package/src/runtime/pi/model-settings.mjs +112 -6
  55. package/src/runtime/pi/model-transport.mjs +9 -0
  56. package/src/runtime/pi/moondog-model.mjs +158 -0
  57. package/src/runtime/pi/next-songs.mjs +71 -0
  58. package/src/runtime/pi/persistent-credential-store.mjs +2 -0
  59. package/src/runtime/pi/public-model-catalog.mjs +10 -3
  60. package/src/runtime/pi/runtime-settings.mjs +7 -3
  61. package/src/surfaces/cli/brand-components.mjs +1 -1
  62. package/src/surfaces/cli/command-completions.mjs +43 -3
  63. package/src/surfaces/cli/format-output.mjs +19 -7
  64. package/src/surfaces/cli/invite-command.mjs +65 -0
  65. package/src/surfaces/cli/model-roles-command.mjs +60 -0
  66. package/src/surfaces/cli/tui.mjs +87 -5
@@ -2,6 +2,7 @@ import { getSupportedThinkingLevels } from "@earendil-works/pi-ai";
2
2
 
3
3
  import { PiAgentRuntime } from "./agent-runtime.mjs";
4
4
  import { createPiAuthContext } from "./authentication.mjs";
5
+ import { readModelRoles } from "./model-roles.mjs";
5
6
  import { getPublicPiModelCatalog } from "./public-model-catalog.mjs";
6
7
  import { createPersistentCredentialStore } from "./persistent-credential-store.mjs";
7
8
  import { clampEffort, EFFORT_LEVELS, readPiRuntimeSelection } from "./runtime-settings.mjs";
@@ -110,5 +111,7 @@ export async function createConfiguredRuntime(
110
111
  effortLevels: getSupportedThinkingLevels(model),
111
112
  thinkingLevel: effort ? clampEffort(model, effort) : undefined,
112
113
  ...(toolTrace ? { toolTrace } : {}),
114
+ // Read at each message with images: the vision model from Settings, or null for the chat model.
115
+ visionChoice: async () => (await readModelRoles(environment).catch(() => ({}))).vision ?? null,
113
116
  });
114
117
  }
@@ -0,0 +1,148 @@
1
+ import { readFile as readFileFromDisk } from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ import { clampThinkingLevel } from "@earendil-works/pi-ai";
6
+
7
+ // Images the listener attaches to a message, after Hermes Agent's image routing
8
+ // (agent/image_routing.py, image_input_mode "auto"):
9
+ //
10
+ // - A vision model chosen in Settings describes each image first ("text"): its words go into the
11
+ // message, and the chat model reads them. A chosen auxiliary model wins over the chat model, as in
12
+ // Hermes, so the listener can keep a cheap chat model and a good eye.
13
+ // - Otherwise a chat model that takes images gets them as they are ("native").
14
+ // - Otherwise nothing can see them, and the message is refused with what to change.
15
+ //
16
+ // Either way the conversation keeps only text: a short stand-in for a native image, or the vision
17
+ // model's description, so a conversation picked up later still knows what was shown.
18
+
19
+ export const IMAGE_LIMITS = Object.freeze({
20
+ count: 4,
21
+ // Base64 characters of one image, about 6 MB of image; the window scales larger ones down first.
22
+ dataChars: 8_000_000,
23
+ mimeTypes: Object.freeze(["image/png", "image/jpeg", "image/webp", "image/gif"]),
24
+ nameChars: 120,
25
+ // Conversation entries hold at most 8,000 characters, the listener's own words first.
26
+ entryChars: 8_000,
27
+ descriptionChars: 1_600,
28
+ });
29
+
30
+ const VISION_PROMPT = [
31
+ "You describe an image for another model, which answers a music listener in Moondog and cannot see it.",
32
+ "Read any text exactly as written: track lists, artist and album names, playlists, setlists, posters,",
33
+ "streaming app screenshots, chat messages. Name album covers, artists, instruments or places you can recognise,",
34
+ "and say how sure you are when you guess. Describe mood and setting briefly.",
35
+ "Write plain text without a preamble, under 180 words.",
36
+ ].join(" ");
37
+
38
+ function failure(code, message) {
39
+ return Object.assign(new Error(message), { code });
40
+ }
41
+
42
+ const takesImages = (model) => Array.isArray(model?.input) && model.input.includes("image");
43
+
44
+ /** The attached images as Pi takes them, checked; an empty list when there are none. */
45
+ export function normalizeImages(images) {
46
+ if (images === undefined || images === null) return [];
47
+ if (!Array.isArray(images)) throw failure("image_input_invalid", "Images must come as a list.");
48
+ if (images.length > IMAGE_LIMITS.count) throw failure("image_input_too_many", `Attach at most ${IMAGE_LIMITS.count} images to one message.`);
49
+ return images.map((image, index) => {
50
+ const mimeType = String(image?.mimeType ?? "").toLowerCase();
51
+ const data = typeof image?.data === "string" ? image.data.replace(/^data:[^,]*,/u, "") : "";
52
+ if (!IMAGE_LIMITS.mimeTypes.includes(mimeType)) throw failure("image_input_unsupported", "Moondog takes PNG, JPEG, WebP and GIF images.");
53
+ if (!data || data.length > IMAGE_LIMITS.dataChars || !/^[A-Za-z0-9+/]+={0,2}$/u.test(data)) {
54
+ throw failure("image_input_too_large", "That image is too large or unreadable. Try a smaller one.");
55
+ }
56
+ const name = typeof image?.name === "string" && image.name.trim()
57
+ ? image.name.trim().replace(/[\p{C}[\]]/gu, "").slice(0, IMAGE_LIMITS.nameChars) : `image ${index + 1}`;
58
+ return { type: "image", data, mimeType, name };
59
+ });
60
+ }
61
+
62
+ // Local image paths in a terminal message, as Hermes Agent's gateway finds them: an absolute or ~/
63
+ // path ending in an image extension, quoted when it has spaces, or with the "\ " a Finder drag writes.
64
+ const EXTENSION_TYPES = Object.freeze({ png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp", gif: "image/gif" });
65
+ const QUOTED_PATH = /(["'])((?:~\/|\/)[^"'\n]+?\.(?:png|jpe?g|webp|gif))\1/giu;
66
+ const BARE_PATH = /(?<![\w./:])((?:~\/|\/)(?:\\ |[^\s"'])+?\.(?:png|jpe?g|webp|gif))(?=[\s,.;:!?)]*(?:\s|$))/giu;
67
+
68
+ /** The image files a message names, read from disk; paths that aren't readable images are left as words. */
69
+ export async function imagesFromText(text, { readFile = readFileFromDisk, home = os.homedir() } = {}) {
70
+ const found = [];
71
+ const quoted = String(text ?? "").replace(QUOTED_PATH, (_, _quote, file) => { found.push(file); return " "; });
72
+ for (const match of quoted.matchAll(BARE_PATH)) found.push(match[1].replace(/\\ /gu, " "));
73
+ const images = [];
74
+ for (const written of [...new Set(found)].slice(0, IMAGE_LIMITS.count)) {
75
+ const file = written.startsWith("~/") ? path.join(home, written.slice(2)) : written;
76
+ let bytes;
77
+ try { bytes = await readFile(file); } catch { continue; }
78
+ const mimeType = EXTENSION_TYPES[path.extname(file).slice(1).toLowerCase()];
79
+ const data = Buffer.from(bytes).toString("base64");
80
+ if (data.length > IMAGE_LIMITS.dataChars) {
81
+ throw failure("image_input_too_large", `${path.basename(file)} is too large to send. Try a smaller copy or a screenshot of part of it.`);
82
+ }
83
+ images.push({ data, mimeType, name: path.basename(file) });
84
+ }
85
+ return images;
86
+ }
87
+
88
+ const modelLabel = (model) => model?.name ?? model?.id ?? "the vision model";
89
+
90
+ /** Native, text through a vision model, or a refusal; the vision model is resolved here. */
91
+ export async function chooseImageRoute({ models, model, visionChoice }) {
92
+ if (visionChoice?.provider && visionChoice?.model) {
93
+ const vision = models.getModel(visionChoice.provider, visionChoice.model);
94
+ if (!vision || !takesImages(vision)) {
95
+ throw failure("vision_model_unavailable", "The vision model chosen in Settings can't see images any more. Choose another under Model > Auxiliary models > Vision.");
96
+ }
97
+ if (!(await models.checkAuth?.(visionChoice.provider))) {
98
+ throw failure("vision_model_signed_out", `${modelLabel(vision)} needs a sign-in before it can see images. Add its key in Settings > Model.`);
99
+ }
100
+ return { mode: "text", vision };
101
+ }
102
+ if (takesImages(model)) return { mode: "native" };
103
+ throw failure("vision_model_missing",
104
+ `${modelLabel(model)} can't see images. Choose a model that can under Settings > Model > Auxiliary models > Vision, or switch to one that sees.`);
105
+ }
106
+
107
+ async function describe({ models, vision, image, text, signal }) {
108
+ const lightest = clampThinkingLevel(vision, "off");
109
+ const message = await models.completeSimple(vision, {
110
+ systemPrompt: VISION_PROMPT,
111
+ messages: [{ role: "user", timestamp: Date.now(), content: [
112
+ { type: "text", text: text ? `The listener's message, for context: ${text.slice(0, 1_000)}` : "The listener sent this image without words." },
113
+ { type: "image", data: image.data, mimeType: image.mimeType },
114
+ ] }],
115
+ }, { maxTokens: 900, maxRetries: 1, signal, ...(lightest !== "off" ? { reasoning: lightest } : {}) });
116
+ if (!message || message.stopReason === "aborted") throw failure("vision_cancelled", "Stopped describing the image.");
117
+ if (message.stopReason === "error") throw failure("vision_failed", `${modelLabel(vision)} couldn't describe the image. Try again in a moment.`);
118
+ return message.content.filter((block) => block.type === "text").map((block) => block.text).join("").replace(/\s+/gu, " ").trim();
119
+ }
120
+
121
+ const clip = (value, limit) => (value.length > limit ? `${value.slice(0, limit - 1).trimEnd()}…` : value);
122
+
123
+ /**
124
+ * The message as the conversation keeps it, and the images the chat model gets with it (only in
125
+ * native mode). Without images it returns the text unchanged.
126
+ */
127
+ export async function prepareImageInput({ text, images, models, model, visionChoice, signal }) {
128
+ const attached = normalizeImages(images);
129
+ if (!attached.length) return { text, images: [], mode: null };
130
+ const route = await chooseImageRoute({ models, model, visionChoice });
131
+ const words = String(text ?? "").trim();
132
+ const room = Math.max(400, IMAGE_LIMITS.entryChars - words.length - 40);
133
+ const each = Math.min(IMAGE_LIMITS.descriptionChars, Math.floor(room / attached.length) - 60);
134
+ const notes = [];
135
+ for (const [index, image] of attached.entries()) {
136
+ const label = attached.length > 1 ? `Image ${index + 1} (${image.name})` : `Image (${image.name})`;
137
+ if (route.mode === "native") { notes.push(`[${label} attached]`); continue; }
138
+ const seen = await describe({ models, vision: route.vision, image, text: words, signal });
139
+ notes.push(`[${label}, as ${modelLabel(route.vision)} describes it: ${clip(seen || "nothing it could make out", Math.max(80, each))}]`);
140
+ }
141
+ const kept = [words, notes.join("\n")].filter(Boolean).join("\n\n");
142
+ return {
143
+ text: kept.slice(0, IMAGE_LIMITS.entryChars),
144
+ images: route.mode === "native" ? attached.map(({ type, data, mimeType }) => ({ type, data, mimeType })) : [],
145
+ mode: route.mode,
146
+ ...(route.vision ? { vision: { provider: route.vision.provider, model: route.vision.id, name: modelLabel(route.vision) } } : {}),
147
+ };
148
+ }
@@ -0,0 +1,121 @@
1
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import path from "node:path";
4
+
5
+ import { resolveMoondogAuthFile } from "./persistent-credential-store.mjs";
6
+
7
+ // What each model is for, after Hermes Agent's main model and auxiliary tasks: one chat model answers,
8
+ // and a side task can have a model of its own. A role without a saved choice is "auto": vision uses the
9
+ // chat model when it can see images, and web search takes the first service that is set up.
10
+ // The chat model stays in settings.json, which older Moondogs read with a fixed shape; the other
11
+ // roles live in model-roles.json beside it.
12
+ //
13
+ // kind "model" is a provider and model from the catalog; kind "service" is a web service by id.
14
+ // A "planned" role holds its place in the settings and in this file, but nothing can choose it yet.
15
+ export const MODEL_ROLES = Object.freeze([
16
+ Object.freeze({ id: "chat", kind: "model", state: "enabled", stored: "settings" }),
17
+ Object.freeze({ id: "vision", kind: "model", state: "enabled", input: "image" }),
18
+ Object.freeze({ id: "web_search", kind: "service", state: "enabled" }),
19
+ Object.freeze({ id: "audio", kind: "model", state: "planned", input: "audio" }),
20
+ ]);
21
+
22
+ export const WEB_SERVICES = Object.freeze(["deepseek", "brave", "codex"]);
23
+
24
+ const ROLES_VERSION = 1;
25
+ const printable = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max && !/[\p{C}\s]/u.test(value);
26
+
27
+ function rolesError(message, cause) {
28
+ const error = new Error(message, cause ? { cause } : undefined);
29
+ error.name = "MoondogRuntimeSettingsError";
30
+ error.code = "model_roles_invalid";
31
+ return error;
32
+ }
33
+
34
+ export const modelRole = (id) => MODEL_ROLES.find((role) => role.id === id) ?? null;
35
+
36
+ /** One role's choice in its saved shape, or null for auto. Throws on a shape the role can't take. */
37
+ export function normalizeRoleChoice(roleId, value) {
38
+ const role = modelRole(roleId);
39
+ if (!role || role.stored) throw rolesError(`Moondog has no model role called ${roleId}.`);
40
+ if (value === null || value === undefined || value === "auto") return null;
41
+ if (role.kind === "service") {
42
+ const service = typeof value?.service === "string" ? value.service.trim().toLowerCase() : "";
43
+ if (!WEB_SERVICES.includes(service)) throw rolesError(`Web search can use ${WEB_SERVICES.join(", ")} or auto.`);
44
+ return { service };
45
+ }
46
+ const provider = typeof value?.provider === "string" ? value.provider.trim().toLowerCase() : "";
47
+ const model = typeof value?.model === "string" ? value.model.trim() : "";
48
+ if (!printable(provider, 80) || !printable(model, 200)) throw rolesError(`The ${roleId} role needs a provider and a model.`);
49
+ return { provider, model, ...(typeof value.effort === "string" && printable(value.effort, 20) ? { effort: value.effort } : {}) };
50
+ }
51
+
52
+ export function resolveModelRolesFile(environment = process.env) {
53
+ return path.join(path.dirname(resolveMoondogAuthFile(environment)), "model-roles.json");
54
+ }
55
+
56
+ // Every saved role as it is in the file, including roles a newer Moondog wrote, so a write here
57
+ // never drops them.
58
+ async function readDocument(environment) {
59
+ let source;
60
+ try {
61
+ source = await readFile(resolveModelRolesFile(environment), "utf8");
62
+ } catch (error) {
63
+ if (error?.code === "ENOENT") return {};
64
+ throw rolesError("Moondog could not read its model roles.", error);
65
+ }
66
+ let document;
67
+ try {
68
+ document = JSON.parse(source);
69
+ } catch (error) {
70
+ throw rolesError("Moondog's model roles are not valid JSON.", error);
71
+ }
72
+ if (!document || typeof document !== "object" || document.version !== ROLES_VERSION ||
73
+ !document.roles || typeof document.roles !== "object" || Array.isArray(document.roles)) {
74
+ throw rolesError("Moondog's model roles use an unsupported shape.");
75
+ }
76
+ return document.roles;
77
+ }
78
+
79
+ /** The saved choice for each role this Moondog knows, by role id; a role left on auto is absent. */
80
+ export async function readModelRoles(environment = process.env) {
81
+ const saved = await readDocument(environment);
82
+ const roles = {};
83
+ for (const role of MODEL_ROLES) {
84
+ if (role.stored || role.state !== "enabled" || saved[role.id] === undefined) continue;
85
+ // One bad entry leaves that role on auto instead of failing every role.
86
+ try {
87
+ const choice = normalizeRoleChoice(role.id, saved[role.id]);
88
+ if (choice) roles[role.id] = choice;
89
+ } catch {}
90
+ }
91
+ return roles;
92
+ }
93
+
94
+ // One change at a time, so two quick choices never lose either.
95
+ let writing = Promise.resolve();
96
+ /** Saves one role's choice; null puts it back on auto. */
97
+ export function writeModelRole(roleId, value, environment = process.env) {
98
+ const role = modelRole(roleId);
99
+ if (!role || role.stored) return Promise.reject(rolesError(`Moondog has no model role called ${roleId}.`));
100
+ if (role.state !== "enabled") return Promise.reject(rolesError(`The ${roleId} role isn't available yet.`));
101
+ let choice;
102
+ try { choice = normalizeRoleChoice(roleId, value); } catch (error) { return Promise.reject(error); }
103
+ const next = writing.then(async () => {
104
+ const roles = { ...(await readDocument(environment).catch(() => ({}))) };
105
+ if (choice) roles[roleId] = choice;
106
+ else delete roles[roleId];
107
+ const file = resolveModelRolesFile(environment);
108
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
109
+ // Another Moondog may read the roles at any moment, so it never sees half a file.
110
+ const temporary = `${file}.${randomUUID()}.tmp`;
111
+ try {
112
+ await writeFile(temporary, `${JSON.stringify({ version: ROLES_VERSION, roles }, null, 2)}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
113
+ await rename(temporary, file);
114
+ } finally {
115
+ await rm(temporary, { force: true });
116
+ }
117
+ return choice;
118
+ });
119
+ writing = next.catch(() => {});
120
+ return next;
121
+ }
@@ -9,10 +9,12 @@ import {
9
9
  import { isEndpointProvider, removeEndpoint, saveEndpoint } from "./custom-endpoints.mjs";
10
10
  import { LEGACY_MODEL_ALIASES } from "./model-catalog.mjs";
11
11
  import { readConversationModels, readModelList, sameModel, writeConversationModel, writeModelList } from "./model-list.mjs";
12
+ import { isMoondogProvider, MOONDOG_MODEL, MOONDOG_PROVIDER, removeInvite, saveInvite } from "./moondog-model.mjs";
13
+ import { MODEL_ROLES, modelRole, readModelRoles, writeModelRole } from "./model-roles.mjs";
12
14
  import { chatgptProviderId } from "./provider-registry.mjs";
13
15
  import { createPersistentCredentialStore } from "./persistent-credential-store.mjs";
14
16
  import { getPublicPiModelCatalog } from "./public-model-catalog.mjs";
15
- import { clampEffort, readPiRuntimeSelection } from "./runtime-settings.mjs";
17
+ import { clampEffort, readPiRuntimeSelection, writePiRuntimeSelection } from "./runtime-settings.mjs";
16
18
 
17
19
  // The desktop window picks models and signs in through this service, as the
18
20
  // terminal does with /model and /auth. It returns status shapes only: never a
@@ -22,6 +24,8 @@ import { clampEffort, readPiRuntimeSelection } from "./runtime-settings.mjs";
22
24
  // key, then Anthropic, Google and xAI. Any other service is reached as an endpoint by address; Pi's
23
25
  // other providers show only once a key for one is saved or in the environment.
24
26
  const FEATURED = ["openai", "anthropic", "google", "xai"];
27
+ // Whether a catalog model takes an input besides text, such as "image".
28
+ const takes = (model, input) => Boolean(input) && Array.isArray(model?.input) && model.input.includes(input);
25
29
  // Moondog's own errors carry fixed text. Pi wraps them, and its own text may not be safe.
26
30
  const moondogErrorNames = new Set(["MoondogCredentialStoreError", "MoondogRuntimeSettingsError"]);
27
31
 
@@ -41,6 +45,7 @@ const aborted = () => new DOMException("The sign-in was cancelled.", "AbortError
41
45
 
42
46
  function signInKind(providerId) {
43
47
  if (isEndpointProvider(providerId)) return "endpoint";
48
+ if (isMoondogProvider(providerId)) return "invite";
44
49
  return supportedAuthProviderIds.includes(providerId) ? "api_key" : "environment_only";
45
50
  }
46
51
 
@@ -146,17 +151,18 @@ export function createModelSettings({
146
151
  return {
147
152
  current,
148
153
 
149
- // Settings' providers: the featured ones in their order, then any other provider that has a key or
154
+ // Settings' providers: Moondog's own model first, then the featured ones in their order, then any other provider that has a key or
150
155
  // is in use, by name, then the listener's endpoints in the order they were added.
151
156
  async providers({ current: currentProvider } = {}) {
152
157
  currentProvider ??= (await current().catch(() => null))?.provider;
153
158
  const source = await catalog();
154
159
  const all = await rows(source, listed(source));
155
160
  const featured = FEATURED.map(id => all.find(provider => provider.id === id)).filter(Boolean);
156
- const others = all.filter(provider => !FEATURED.includes(provider.id) && provider.signIn !== "endpoint" &&
161
+ const own = all.filter(provider => provider.signIn === "invite");
162
+ const others = all.filter(provider => !FEATURED.includes(provider.id) && provider.signIn !== "endpoint" && provider.signIn !== "invite" &&
157
163
  (provider.signedIn || provider.id === currentProvider)).sort((left, right) => left.name.localeCompare(right.name));
158
164
  const endpoints = (source.endpoints ?? []).map(endpoint => all.find(provider => provider.id === endpoint.id)).filter(Boolean);
159
- return [...featured, ...others, ...endpoints];
165
+ return [...own, ...featured, ...others, ...endpoints];
160
166
  },
161
167
 
162
168
  // The menu's models, each with its provider's name and whether it can answer now, and the default
@@ -183,13 +189,71 @@ export function createModelSettings({
183
189
  const model = models.getModel(entry.provider, entry.model);
184
190
  return { provider: entry.provider, model: entry.model, name: model?.name ?? entry.model,
185
191
  providerName: names.get(entry.provider) ?? entry.provider, ready: Boolean(model) && ready.get(entry.provider) === true,
186
- reasoning: thinks(model) };
192
+ reasoning: thinks(model), vision: takes(model, "image") };
187
193
  }),
188
194
  default: selection ? { provider: selection.provider, model: selection.model, effort: selection.effort ?? null,
189
195
  reasoning: thinks(defaultModel), thinking: selection.effort && defaultModel ? clampEffort(defaultModel, selection.effort) : null } : null,
190
196
  };
191
197
  },
192
198
 
199
+ // What each model is for: the chat model from settings.json, then each other role's choice from
200
+ // model-roles.json, null for auto. Vision on auto uses the chat model when it can see images.
201
+ // web is the web research's services(), which knows the web services; Settings passes it in.
202
+ async roles({ web = null } = {}) {
203
+ const selection = await current();
204
+ let saved;
205
+ try {
206
+ saved = await readModelRoles(environment);
207
+ } catch (error) {
208
+ throw moondogError(error) ?? failure("model_roles_invalid", "Moondog could not read its model roles.");
209
+ }
210
+ const source = await catalog();
211
+ let models;
212
+ try {
213
+ models = withAuth(source);
214
+ } catch (error) {
215
+ throw moondogError(error) ?? failure("auth_status_failed", "Moondog could not read its saved sign-ins.");
216
+ }
217
+ const names = new Map(source.providers().map(provider => [provider.id, provider.name]));
218
+ const describe = (choice) => {
219
+ const model = models.getModel(choice.provider, choice.model);
220
+ return { provider: choice.provider, model: choice.model, name: model?.name ?? choice.model,
221
+ providerName: names.get(choice.provider) ?? choice.provider, known: Boolean(model), vision: takes(model, "image") };
222
+ };
223
+ const chat = selection ? describe(selection) : null;
224
+ return MODEL_ROLES.map((role) => {
225
+ const base = { id: role.id, kind: role.kind, state: role.state, ...(role.input ? { input: role.input } : {}) };
226
+ if (role.id === "chat") return { ...base, choice: chat };
227
+ if (role.id === "web_search") {
228
+ return { ...base, choice: saved.web_search ?? null,
229
+ ...(web ? { services: web.services, search: web.search?.provider ?? null, read: web.read?.provider ?? null } : {}) };
230
+ }
231
+ if (role.state !== "enabled") return { ...base, choice: null };
232
+ // Hermes Agent's auxiliary vision on auto: the main model when it takes images, else none.
233
+ return { ...base, choice: saved[role.id] ? describe(saved[role.id]) : null,
234
+ auto: chat && takes(models.getModel(selection.provider, selection.model), role.input) ? chat : null };
235
+ });
236
+ },
237
+
238
+ // Saves one role's choice; null puts it on auto. A model must be in the catalog and take the
239
+ // input its role is for.
240
+ async setRole(roleId, choice) {
241
+ const role = modelRole(String(roleId ?? ""));
242
+ if (!role || role.stored) throw failure("model_role_unknown", "Moondog has no such model role.");
243
+ if (role.state !== "enabled") throw failure("model_role_unavailable", "That model role isn't available yet.");
244
+ if (role.kind === "model" && choice) {
245
+ const provider = String(choice.provider ?? "").trim().toLowerCase();
246
+ const model = (await catalog()).createModels().getModel(provider, String(choice.model ?? "").trim());
247
+ if (!model) throw failure("model_unknown", "Moondog doesn't know that model.");
248
+ if (!takes(model, role.input)) throw failure("model_role_unsuitable", `That model can't take ${role.input} input.`);
249
+ }
250
+ try {
251
+ return await writeModelRole(role.id, choice ?? null, environment);
252
+ } catch (error) {
253
+ throw moondogError(error) ?? failure("model_roles_invalid", "Moondog could not save its model roles.");
254
+ }
255
+ },
256
+
193
257
  // The model each conversation was given in the window's menu, and a change to one: null gives a
194
258
  // conversation back to the default.
195
259
  conversationModels: () => readConversationModels(environment),
@@ -228,6 +292,48 @@ export function createModelSettings({
228
292
  return saved.endpoint;
229
293
  },
230
294
 
295
+ // Saves an invite code for Moondog's own model once the gateway takes it, and puts the model in
296
+ // the menu. It becomes the default when no model is chosen yet or the chosen one can't answer,
297
+ // so a listener with only a code can talk at once. Returns { label, dailyTokens, usedToday,
298
+ // becameDefault }, never the code.
299
+ async saveInvite(value) {
300
+ let allowance;
301
+ try {
302
+ allowance = await saveInvite(value, environment);
303
+ } catch (error) {
304
+ throw moondogError(error) ?? failure("invite_save_failed", "Moondog could not save that invite code.");
305
+ }
306
+ const source = await catalog();
307
+ await source.readEndpoints?.();
308
+ const own = { provider: MOONDOG_PROVIDER, model: MOONDOG_MODEL };
309
+ const selection = await current().catch(() => null);
310
+ const answers = Boolean(selection) && Boolean(await withAuth(source).checkAuth(selection.provider).catch(() => undefined));
311
+ const becameDefault = !answers;
312
+ try {
313
+ if (becameDefault) await writePiRuntimeSelection(own, environment);
314
+ const entries = await menu(becameDefault ? own : selection);
315
+ await writeModelList(entries.some(entry => sameModel(entry, own)) ? entries : [...entries, own].slice(0, 40), environment);
316
+ } catch (error) {
317
+ throw moondogError(error) ?? failure("model_list_invalid", "Moondog could not save its model list.");
318
+ }
319
+ return { ...allowance, becameDefault };
320
+ },
321
+
322
+ // Forgets the invite code. A default on Moondog's model stays saved, and asks for another model
323
+ // until one is chosen.
324
+ async removeInvite() {
325
+ try {
326
+ await removeInvite(environment);
327
+ } catch (error) {
328
+ throw moondogError(error) ?? failure("invite_remove_failed", "Moondog could not remove the invite code.");
329
+ }
330
+ const selection = await current().catch(() => null);
331
+ const entries = await menu(null);
332
+ const kept = entries.filter(entry => entry.provider !== MOONDOG_PROVIDER || sameModel(entry, selection));
333
+ if (kept.length !== entries.length) await writeModelList(kept, environment);
334
+ await (await catalog()).readEndpoints?.();
335
+ },
336
+
231
337
  // Removes an endpoint, its key and its models from the menu. A default on it stays saved, and asks
232
338
  // for another model until one is chosen.
233
339
  async removeEndpoint(id) {
@@ -262,7 +368,7 @@ export function createModelSettings({
262
368
  refresh,
263
369
  models: source.models(providerId).filter(({ id }) => !LEGACY_MODEL_ALIASES.includes(id)).map(({ id, name, contextWindow, reasoning, catalogNote }) => {
264
370
  const model = full.getModel(providerId, id);
265
- return { id, name, ...(contextWindow ? { contextWindow } : {}), reasoning,
371
+ return { id, name, ...(contextWindow ? { contextWindow } : {}), reasoning, vision: takes(model, "image"),
266
372
  effortLevels: model ? getSupportedThinkingLevels(model) : [],
267
373
  ...(catalogNote ? { retained: true } : {}) };
268
374
  }),
@@ -1,5 +1,7 @@
1
1
  import { setTimeout as delay } from "node:timers/promises";
2
2
 
3
+ import { isMoondogProvider, moondogRefusal } from "./moondog-model.mjs";
4
+
3
5
  const maximumRetries = 2;
4
6
  const retryableCodes = new Set([
5
7
  "ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT", "EAI_AGAIN",
@@ -116,6 +118,7 @@ export function createModelFetch({
116
118
  wait = retryDelay,
117
119
  onRetry,
118
120
  onFailure,
121
+ onRefusal,
119
122
  } = {}) {
120
123
  return async (input, init) => {
121
124
  const signal = init?.signal ?? (input instanceof Request ? input.signal : undefined);
@@ -137,6 +140,12 @@ export function createModelFetch({
137
140
  await wait(retryAfter, signal);
138
141
  continue;
139
142
  }
143
+ // Moondog's gateway says why it refused, such as a used-up daily allowance. Pi still gets
144
+ // the response; the reason travels beside it so each surface can say it in its own words.
145
+ if (onRefusal && isMoondogProvider(provider)) {
146
+ const refusal = await moondogRefusal(response);
147
+ if (refusal) onRefusal(refusal);
148
+ }
140
149
  return response;
141
150
  } catch (cause) {
142
151
  if (signal?.aborted || cause?.name === "AbortError") throw cause;
@@ -0,0 +1,158 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ import { createProvider } from "@earendil-works/pi-ai";
6
+ import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy";
7
+
8
+ import { acquirePrivateFileLock, resolveMoondogAuthFile } from "./persistent-credential-store.mjs";
9
+
10
+ // Moondog's own model: one model named Moondog, answered by Moondog's gateway (see gateway/). A
11
+ // listener reaches it with an invite code, which is the key. Which model answers behind the gateway
12
+ // is the gateway's business, so no release is needed to change it. The code stays in its own
13
+ // private file: auth.json and settings.json are read with a fixed shape by older Moondogs.
14
+ export const MOONDOG_PROVIDER = "moondog";
15
+ export const MOONDOG_MODEL = "moondog";
16
+ const DEFAULT_URL = "https://moondog-api.audiofool.ai/v1";
17
+ const DOCUMENT_VERSION = 1;
18
+ const INVITE = /md-[0-9a-hjkmnp-tv-z]{24}/u;
19
+ const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
20
+
21
+ // What the gateway says when it refuses, in the listener's terms. The window has its own words for
22
+ // each code; the terminal shows these.
23
+ const REFUSALS = Object.freeze({
24
+ invite_invalid: "Moondog doesn't know this invite code. Check it and enter it again.",
25
+ invite_revoked: "This invite code is no longer active.",
26
+ beta_ended: "The Moondog model's test period has ended.",
27
+ daily_allowance_used: "You've used today's Moondog allowance. It starts again at midnight, Beijing time.",
28
+ beta_capacity_reached: "The Moondog model is at today's limit for all testers. It starts again at midnight, Beijing time.",
29
+ rate_limited: "Too many requests in a minute. Wait a moment and try again.",
30
+ });
31
+
32
+ function inviteError(code, message, cause) {
33
+ const error = new Error(message, cause ? { cause } : undefined);
34
+ error.name = "MoondogRuntimeSettingsError";
35
+ error.code = code;
36
+ return error;
37
+ }
38
+
39
+ export const isMoondogProvider = (providerId) => providerId === MOONDOG_PROVIDER;
40
+
41
+ // The gateway's address. MOONDOG_MODEL_URL points a development build at another gateway.
42
+ export function moondogModelUrl(environment = process.env) {
43
+ const configured = environment.MOONDOG_MODEL_URL?.trim();
44
+ if (!configured) return DEFAULT_URL;
45
+ let url;
46
+ try { url = new URL(configured); } catch { return DEFAULT_URL; }
47
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK.has(url.hostname))) return DEFAULT_URL;
48
+ return url.href.replace(/\/+$/u, "");
49
+ }
50
+
51
+ // A code as the listener has it: typed, pasted, or inside an invite link.
52
+ export function parseInvite(value) {
53
+ const code = INVITE.exec(String(value ?? "").trim().toLowerCase())?.[0];
54
+ if (!code) throw inviteError("invite_invalid", "That isn't an invite code. A code starts with md- and has 24 more characters.");
55
+ return code;
56
+ }
57
+
58
+ export function resolveInviteFile(environment = process.env) {
59
+ return path.join(path.dirname(resolveMoondogAuthFile(environment)), "moondog-model.json");
60
+ }
61
+
62
+ export async function readInvite(environment = process.env) {
63
+ let source;
64
+ try {
65
+ source = await readFile(resolveInviteFile(environment), "utf8");
66
+ } catch (error) {
67
+ if (error?.code === "ENOENT") return null;
68
+ throw inviteError("invite_store_invalid", "Moondog could not read its invite code.", error);
69
+ }
70
+ let document;
71
+ try { document = JSON.parse(source); } catch { document = null; }
72
+ if (!document || document.version !== DOCUMENT_VERSION || typeof document.code !== "string" || !INVITE.test(document.code)) {
73
+ throw inviteError("invite_store_invalid", "Moondog's invite file uses a shape it can't read. Enter the code again in Settings.");
74
+ }
75
+ return { code: parseInvite(document.code), ...(typeof document.label === "string" ? { label: document.label.slice(0, 80) } : {}) };
76
+ }
77
+
78
+ // Asks the gateway whether it takes the code, and what it allows.
79
+ export async function checkInvite(code, environment = process.env, { fetchImpl = globalThis.fetch, timeoutMs = 10_000 } = {}) {
80
+ let reply;
81
+ try {
82
+ reply = await fetchImpl(`${moondogModelUrl(environment)}/invite`, {
83
+ headers: { authorization: `Bearer ${code}` },
84
+ signal: AbortSignal.timeout(timeoutMs),
85
+ });
86
+ } catch (error) {
87
+ throw inviteError("invite_unreachable", "Moondog could not reach its model service to check the code. Check your connection and try again.", error);
88
+ }
89
+ const body = await reply.json().catch(() => null);
90
+ if (!reply.ok) {
91
+ const code = body?.error?.code;
92
+ if (Object.hasOwn(REFUSALS, code)) throw inviteError(code, REFUSALS[code]);
93
+ throw inviteError("invite_unreachable", "Moondog's model service could not check the code. Try again in a moment.");
94
+ }
95
+ const number = (value) => (Number.isSafeInteger(value) && value >= 0 ? value : null);
96
+ return {
97
+ label: typeof body?.label === "string" ? body.label.slice(0, 80) : "",
98
+ dailyTokens: number(body?.daily_tokens),
99
+ usedToday: number(body?.used_today),
100
+ };
101
+ }
102
+
103
+ // Saves a code once the gateway takes it, so a mistyped one never becomes the listener's model.
104
+ export async function saveInvite(value, environment = process.env, options = {}) {
105
+ const code = parseInvite(value);
106
+ const allowance = await checkInvite(code, environment, options);
107
+ const file = resolveInviteFile(environment);
108
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
109
+ const release = await acquirePrivateFileLock(file);
110
+ const temporary = `${file}.${randomUUID()}.tmp`;
111
+ try {
112
+ await writeFile(temporary, `${JSON.stringify({ version: DOCUMENT_VERSION, code, label: allowance.label }, null, 2)}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
113
+ await rename(temporary, file);
114
+ } finally {
115
+ await rm(temporary, { force: true });
116
+ await release();
117
+ }
118
+ return allowance;
119
+ }
120
+
121
+ export async function removeInvite(environment = process.env) {
122
+ const file = resolveInviteFile(environment);
123
+ const had = (await readInvite(environment).catch(() => true)) !== null;
124
+ await rm(file, { force: true });
125
+ return had;
126
+ }
127
+
128
+ // The provider is always in the catalog, so Settings can offer it; it can answer once a code is saved.
129
+ export function addMoondogModel(models, invite, environment = process.env) {
130
+ const baseUrl = moondogModelUrl(environment);
131
+ models.setProvider(createProvider({
132
+ id: MOONDOG_PROVIDER, name: "Moondog", baseUrl,
133
+ models: [{
134
+ id: MOONDOG_MODEL, name: "Moondog", provider: MOONDOG_PROVIDER, api: "openai-completions", baseUrl,
135
+ reasoning: false, input: ["text"],
136
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
137
+ contextWindow: 128_000, maxTokens: 8192,
138
+ }],
139
+ auth: { apiKey: { name: "Moondog invite code", resolve: async () => (invite?.code ? { auth: { apiKey: invite.code }, source: "stored credential" } : undefined) } },
140
+ api: openAICompletionsApi(),
141
+ }));
142
+ return models;
143
+ }
144
+
145
+ /**
146
+ * Reads why the gateway refused a model request. Returns an error whose code is the gateway's, with
147
+ * words for the listener, or null when the answer is not one of the gateway's refusals.
148
+ */
149
+ export async function moondogRefusal(response) {
150
+ if (!response || response.ok || ![401, 403, 429].includes(response.status)) return null;
151
+ const body = await response.clone().json().catch(() => null);
152
+ const code = body?.error?.code;
153
+ if (!Object.hasOwn(REFUSALS, code)) return null;
154
+ const error = new Error(REFUSALS[code]);
155
+ error.name = "MoondogModelRefusal";
156
+ error.code = `moondog_${code}`;
157
+ return error;
158
+ }