@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
@@ -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";
@@ -16,7 +17,7 @@ export class OfflineAgentRuntime {
16
17
  return {
17
18
  state: "offline",
18
19
  adapter: "pi_agent_core",
19
- pi_version: "1.0.1",
20
+ pi_version: "1.6.0",
20
21
  reason: this.reason,
21
22
  ...this.selection,
22
23
  session_persistence: "none",
@@ -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
+ }
@@ -1,5 +1,5 @@
1
1
  import { Agent } from "@earendil-works/pi-agent-core";
2
- import { Type } from "@earendil-works/pi-ai";
2
+ import { Type } from "typebox";
3
3
 
4
4
  import { createConfiguredRuntime } from "./configured-runtime.mjs";
5
5
 
@@ -0,0 +1,138 @@
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 { isMoondogProvider } from "./moondog-model.mjs";
6
+ import { resolveMoondogAuthFile } from "./persistent-credential-store.mjs";
7
+
8
+ // What each model is for, after Hermes Agent's main model and auxiliary tasks: one chat model answers,
9
+ // and a side task can have a model of its own. A role without a saved choice is "auto": vision uses the
10
+ // chat model when it can see images, and web search takes the first service that is set up.
11
+ // The chat model stays in settings.json, which older Moondogs read with a fixed shape; the other
12
+ // roles live in model-roles.json beside it.
13
+ //
14
+ // kind "model" is a provider and model from the catalog; kind "service" is a web service by id.
15
+ // A "planned" role holds its place in the settings and in this file, but nothing can choose it yet.
16
+ //
17
+ // Moondog's own model sees images and has Moondog's own web search, so choosing it as the chat model
18
+ // puts vision and web search back on auto, where both use Moondog's (see followChatModel). The
19
+ // listener can choose others again after.
20
+ export const MODEL_ROLES = Object.freeze([
21
+ Object.freeze({ id: "chat", kind: "model", state: "enabled", stored: "settings" }),
22
+ Object.freeze({ id: "vision", kind: "model", state: "enabled", input: "image" }),
23
+ Object.freeze({ id: "web_search", kind: "service", state: "enabled" }),
24
+ Object.freeze({ id: "audio", kind: "model", state: "planned", input: "audio" }),
25
+ ]);
26
+
27
+ export const WEB_SERVICES = Object.freeze(["moondog", "deepseek", "brave", "codex"]);
28
+
29
+ const ROLES_VERSION = 1;
30
+ const printable = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max && !/[\p{C}\s]/u.test(value);
31
+
32
+ function rolesError(message, cause) {
33
+ const error = new Error(message, cause ? { cause } : undefined);
34
+ error.name = "MoondogRuntimeSettingsError";
35
+ error.code = "model_roles_invalid";
36
+ return error;
37
+ }
38
+
39
+ export const modelRole = (id) => MODEL_ROLES.find((role) => role.id === id) ?? null;
40
+
41
+ /** One role's choice in its saved shape, or null for auto. Throws on a shape the role can't take. */
42
+ export function normalizeRoleChoice(roleId, value) {
43
+ const role = modelRole(roleId);
44
+ if (!role || role.stored) throw rolesError(`Moondog has no model role called ${roleId}.`);
45
+ if (value === null || value === undefined || value === "auto") return null;
46
+ if (role.kind === "service") {
47
+ const service = typeof value?.service === "string" ? value.service.trim().toLowerCase() : "";
48
+ if (!WEB_SERVICES.includes(service)) throw rolesError(`Web search can use ${WEB_SERVICES.join(", ")} or auto.`);
49
+ return { service };
50
+ }
51
+ const provider = typeof value?.provider === "string" ? value.provider.trim().toLowerCase() : "";
52
+ const model = typeof value?.model === "string" ? value.model.trim() : "";
53
+ if (!printable(provider, 80) || !printable(model, 200)) throw rolesError(`The ${roleId} role needs a provider and a model.`);
54
+ return { provider, model, ...(typeof value.effort === "string" && printable(value.effort, 20) ? { effort: value.effort } : {}) };
55
+ }
56
+
57
+ export function resolveModelRolesFile(environment = process.env) {
58
+ return path.join(path.dirname(resolveMoondogAuthFile(environment)), "model-roles.json");
59
+ }
60
+
61
+ // Every saved role as it is in the file, including roles a newer Moondog wrote, so a write here
62
+ // never drops them.
63
+ async function readDocument(environment) {
64
+ let source;
65
+ try {
66
+ source = await readFile(resolveModelRolesFile(environment), "utf8");
67
+ } catch (error) {
68
+ if (error?.code === "ENOENT") return {};
69
+ throw rolesError("Moondog could not read its model roles.", error);
70
+ }
71
+ let document;
72
+ try {
73
+ document = JSON.parse(source);
74
+ } catch (error) {
75
+ throw rolesError("Moondog's model roles are not valid JSON.", error);
76
+ }
77
+ if (!document || typeof document !== "object" || document.version !== ROLES_VERSION ||
78
+ !document.roles || typeof document.roles !== "object" || Array.isArray(document.roles)) {
79
+ throw rolesError("Moondog's model roles use an unsupported shape.");
80
+ }
81
+ return document.roles;
82
+ }
83
+
84
+ /** The saved choice for each role this Moondog knows, by role id; a role left on auto is absent. */
85
+ export async function readModelRoles(environment = process.env) {
86
+ const saved = await readDocument(environment);
87
+ const roles = {};
88
+ for (const role of MODEL_ROLES) {
89
+ if (role.stored || role.state !== "enabled" || saved[role.id] === undefined) continue;
90
+ // One bad entry leaves that role on auto instead of failing every role.
91
+ try {
92
+ const choice = normalizeRoleChoice(role.id, saved[role.id]);
93
+ if (choice) roles[role.id] = choice;
94
+ } catch {}
95
+ }
96
+ return roles;
97
+ }
98
+
99
+ /**
100
+ * The roles a new chat model brings with it. Moondog's own model puts vision and web search on auto,
101
+ * where vision uses the model itself and web search Moondog's own. Returns the roles it changed.
102
+ */
103
+ export async function followChatModel(selection, environment = process.env) {
104
+ if (!isMoondogProvider(selection?.provider)) return [];
105
+ const saved = await readModelRoles(environment).catch(() => ({}));
106
+ const changed = ["vision", "web_search"].filter((roleId) => saved[roleId]);
107
+ for (const roleId of changed) await writeModelRole(roleId, null, environment);
108
+ return changed;
109
+ }
110
+
111
+ // One change at a time, so two quick choices never lose either.
112
+ let writing = Promise.resolve();
113
+ /** Saves one role's choice; null puts it back on auto. */
114
+ export function writeModelRole(roleId, value, environment = process.env) {
115
+ const role = modelRole(roleId);
116
+ if (!role || role.stored) return Promise.reject(rolesError(`Moondog has no model role called ${roleId}.`));
117
+ if (role.state !== "enabled") return Promise.reject(rolesError(`The ${roleId} role isn't available yet.`));
118
+ let choice;
119
+ try { choice = normalizeRoleChoice(roleId, value); } catch (error) { return Promise.reject(error); }
120
+ const next = writing.then(async () => {
121
+ const roles = { ...(await readDocument(environment).catch(() => ({}))) };
122
+ if (choice) roles[roleId] = choice;
123
+ else delete roles[roleId];
124
+ const file = resolveModelRolesFile(environment);
125
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
126
+ // Another Moondog may read the roles at any moment, so it never sees half a file.
127
+ const temporary = `${file}.${randomUUID()}.tmp`;
128
+ try {
129
+ await writeFile(temporary, `${JSON.stringify({ version: ROLES_VERSION, roles }, null, 2)}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
130
+ await rename(temporary, file);
131
+ } finally {
132
+ await rm(temporary, { force: true });
133
+ }
134
+ return choice;
135
+ });
136
+ writing = next.catch(() => {});
137
+ return next;
138
+ }
@@ -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 { followChatModel, 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,81 @@ 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
+
257
+ // A new default chat model brings its roles with it: Moondog's own puts vision and web search on
258
+ // auto, where both use Moondog's. Returns the roles it changed.
259
+ async followChat(selection) {
260
+ try {
261
+ return await followChatModel(selection, environment);
262
+ } catch (error) {
263
+ throw moondogError(error) ?? failure("model_roles_invalid", "Moondog could not save its model roles.");
264
+ }
265
+ },
266
+
193
267
  // The model each conversation was given in the window's menu, and a change to one: null gives a
194
268
  // conversation back to the default.
195
269
  conversationModels: () => readConversationModels(environment),
@@ -210,6 +284,22 @@ export function createModelSettings({
210
284
  }
211
285
  },
212
286
 
287
+ // Puts the menu's models in the order given. A model the order leaves out keeps its place after
288
+ // the ones it names, and a model the menu lacks is not added.
289
+ async setOrder(order) {
290
+ const entries = await menu(await current());
291
+ const wanted = (Array.isArray(order) ? order : [])
292
+ .map(entry => ({ provider: String(entry?.provider ?? "").trim().toLowerCase(), model: String(entry?.model ?? "").trim() }))
293
+ .map(entry => entries.find(kept => sameModel(kept, entry)))
294
+ .filter(Boolean);
295
+ const next = [...wanted, ...entries.filter(entry => !wanted.some(kept => sameModel(kept, entry)))];
296
+ try {
297
+ await writeModelList(next, environment);
298
+ } catch (error) {
299
+ throw moondogError(error) ?? failure("model_list_invalid", "Moondog could not save its model list.");
300
+ }
301
+ },
302
+
213
303
  // A new endpoint whose model IDs were typed goes straight into the menu with them; listed ones
214
304
  // wait to be chosen, since an endpoint such as OpenRouter lists hundreds.
215
305
  async saveEndpoint(input) {
@@ -228,6 +318,51 @@ export function createModelSettings({
228
318
  return saved.endpoint;
229
319
  },
230
320
 
321
+ // Saves an invite code for Moondog's own model once the gateway takes it, and puts the model in
322
+ // the menu. It becomes the default when no model is chosen yet or the chosen one can't answer,
323
+ // so a listener with only a code can talk at once. Returns { label, dailyTokens, usedToday,
324
+ // becameDefault }, never the code. As the default, it brings its vision and web search along.
325
+ async saveInvite(value) {
326
+ let allowance;
327
+ try {
328
+ allowance = await saveInvite(value, environment);
329
+ } catch (error) {
330
+ throw moondogError(error) ?? failure("invite_save_failed", "Moondog could not save that invite code.");
331
+ }
332
+ const source = await catalog();
333
+ await source.readEndpoints?.();
334
+ const own = { provider: MOONDOG_PROVIDER, model: MOONDOG_MODEL };
335
+ const selection = await current().catch(() => null);
336
+ const answers = Boolean(selection) && Boolean(await withAuth(source).checkAuth(selection.provider).catch(() => undefined));
337
+ const becameDefault = !answers;
338
+ try {
339
+ if (becameDefault) {
340
+ await writePiRuntimeSelection(own, environment);
341
+ await followChatModel(own, environment);
342
+ }
343
+ const entries = await menu(becameDefault ? own : selection);
344
+ await writeModelList(entries.some(entry => sameModel(entry, own)) ? entries : [...entries, own].slice(0, 40), environment);
345
+ } catch (error) {
346
+ throw moondogError(error) ?? failure("model_list_invalid", "Moondog could not save its model list.");
347
+ }
348
+ return { ...allowance, becameDefault };
349
+ },
350
+
351
+ // Forgets the invite code. A default on Moondog's model stays saved, and asks for another model
352
+ // until one is chosen.
353
+ async removeInvite() {
354
+ try {
355
+ await removeInvite(environment);
356
+ } catch (error) {
357
+ throw moondogError(error) ?? failure("invite_remove_failed", "Moondog could not remove the invite code.");
358
+ }
359
+ const selection = await current().catch(() => null);
360
+ const entries = await menu(null);
361
+ const kept = entries.filter(entry => entry.provider !== MOONDOG_PROVIDER || sameModel(entry, selection));
362
+ if (kept.length !== entries.length) await writeModelList(kept, environment);
363
+ await (await catalog()).readEndpoints?.();
364
+ },
365
+
231
366
  // Removes an endpoint, its key and its models from the menu. A default on it stays saved, and asks
232
367
  // for another model until one is chosen.
233
368
  async removeEndpoint(id) {
@@ -262,7 +397,7 @@ export function createModelSettings({
262
397
  refresh,
263
398
  models: source.models(providerId).filter(({ id }) => !LEGACY_MODEL_ALIASES.includes(id)).map(({ id, name, contextWindow, reasoning, catalogNote }) => {
264
399
  const model = full.getModel(providerId, id);
265
- return { id, name, ...(contextWindow ? { contextWindow } : {}), reasoning,
400
+ return { id, name, ...(contextWindow ? { contextWindow } : {}), reasoning, vision: takes(model, "image"),
266
401
  effortLevels: model ? getSupportedThinkingLevels(model) : [],
267
402
  ...(catalogNote ? { retained: true } : {}) };
268
403
  }),
@@ -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;