@audiofool/moondog 0.4.0-beta.2 → 0.4.0-beta.3
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.
- package/README.md +1 -1
- package/package.json +1 -1
- package/scripts/moondog.mjs +35 -3
- package/src/core/apple-projection-domain-services.mjs +4 -0
- package/src/core/listening-profile-domain-services.mjs +4 -0
- package/src/core/moondog-application.mjs +49 -10
- package/src/core/play-follower.mjs +68 -0
- package/src/i18n/screen/es.mjs +1 -0
- package/src/i18n/screen/ja.mjs +1 -0
- package/src/i18n/screen/pt.mjs +1 -0
- package/src/i18n/screen/zh.mjs +1 -0
- package/src/integrations/apple-music/music-app-listening.mjs +107 -0
- package/src/integrations/apple-music/music-app.mjs +6 -2
- package/src/memory/reflection-worker.mjs +18 -0
- package/src/profile/listener-profile-build.mjs +5 -1
- package/src/profile/listener-profile-store.mjs +35 -3
- package/src/profile/listener-profile-worker.mjs +12 -2
- package/src/profile/listening-history-store.mjs +46 -2
- package/src/profile/listening-profile-projection.mjs +7 -4
- package/src/runtime/pi/agent-runtime.mjs +8 -6
- package/src/runtime/pi/memory-agent-runtime.mjs +2 -0
- package/src/runtime/pi/moondog-model.mjs +6 -0
- package/src/runtime/pi/profile-build-runtime.mjs +5 -1
- package/src/surfaces/cli/listener-profile-command.mjs +2 -0
package/README.md
CHANGED
package/package.json
CHANGED
package/scripts/moondog.mjs
CHANGED
|
@@ -13,7 +13,7 @@ import {
|
|
|
13
13
|
} from "../src/core/apple-projection-domain-services.mjs";
|
|
14
14
|
import { readAppleMusicSourceStatus } from "../src/core/apple-library-source-status.mjs";
|
|
15
15
|
import { createListeningProfileDomainServices } from "../src/core/listening-profile-domain-services.mjs";
|
|
16
|
-
import { runMemoryReflection } from "../src/memory/reflection-worker.mjs";
|
|
16
|
+
import { runMemoryReflection, runMemoryReflectionIfDue } from "../src/memory/reflection-worker.mjs";
|
|
17
17
|
import { createConfiguredRuntime } from "../src/runtime/pi/configured-runtime.mjs";
|
|
18
18
|
import { createModelSettings } from "../src/runtime/pi/model-settings.mjs";
|
|
19
19
|
import { createToolTrace } from "../src/runtime/pi/tool-trace.mjs";
|
|
@@ -46,6 +46,7 @@ import {
|
|
|
46
46
|
import { runSpotifyCommand } from "../src/surfaces/cli/spotify-command.mjs";
|
|
47
47
|
import { runListenBrainzCommand } from "../src/surfaces/cli/listenbrainz-command.mjs";
|
|
48
48
|
import { openListeningHistoryStore } from "../src/profile/listening-history-store.mjs";
|
|
49
|
+
import { createMusicAppListening, projectMusicAppPlays } from "../src/integrations/apple-music/music-app-listening.mjs";
|
|
49
50
|
import { musicHash, prepareMusicBundle } from "../src/profile/music-import-bundle.mjs";
|
|
50
51
|
import { commitSpotifyQuickImport, prepareHistoryImport, prepareSpotifyQuickImport } from "../src/profile/history-import.mjs";
|
|
51
52
|
import { persistAppleLibraryImport, refreshAppleLibraryImport } from "../src/profile/apple-library-import.mjs";
|
|
@@ -323,6 +324,20 @@ async function syncRecentSpotifyListening({ signal } = {}) {
|
|
|
323
324
|
}
|
|
324
325
|
}
|
|
325
326
|
|
|
327
|
+
// Stores finished Music app plays in an existing history. Like Spotify's recent plays, they never
|
|
328
|
+
// start one: a listener who has imported nothing yet still chooses when to begin.
|
|
329
|
+
async function recordMusicAppPlays(plays) {
|
|
330
|
+
const store = await openListeningHistoryStore();
|
|
331
|
+
try {
|
|
332
|
+
const appleSubjectId = await optionalAppleMusicSubjectId();
|
|
333
|
+
const subjectId = store.localSubjectId(appleSubjectId ? { preferredSubjectId: appleSubjectId } : {});
|
|
334
|
+
if (!subjectId) return null;
|
|
335
|
+
return store.ingest(projectMusicAppPlays({ subjectId, plays }));
|
|
336
|
+
} finally {
|
|
337
|
+
store.close();
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
326
341
|
async function runSpotifySurface(options) {
|
|
327
342
|
const syncContext = await spotifyRecentSyncContext(options.args);
|
|
328
343
|
try {
|
|
@@ -948,13 +963,24 @@ async function main() {
|
|
|
948
963
|
// One-shot commands get none: they would exit in the middle of the first song.
|
|
949
964
|
// In the desktop app, the window's own player plays them instead.
|
|
950
965
|
const previewPlayer = options.command ? null : host ? host.musicPreviewPlayer : await createTerminalPreviewPlayer();
|
|
951
|
-
// What the listener plays in the Music app on this Mac, read but never opened.
|
|
952
|
-
|
|
966
|
+
// What the listener plays in the Music app on this Mac, read but never opened. While the room is
|
|
967
|
+
// open, what it plays goes into the listening history, as Spotify's recent plays do.
|
|
968
|
+
let musicAppListening = null;
|
|
969
|
+
const musicApp = createMusicAppPlayer({ onRead: (answer) => musicAppListening?.observe(answer) });
|
|
953
970
|
// NetEase Cloud Music plays through ncm-cli in the terminal and the window alike. Its tools
|
|
954
971
|
// appear once ncm-cli says it is signed in; only listeners who chose it wait for that check.
|
|
955
972
|
const neteasePlayer = createNeteasePlayer();
|
|
956
973
|
const playbackService = await resolvePlaybackService();
|
|
957
974
|
if (playbackService === "netease") await neteasePlayer.check();
|
|
975
|
+
let musicAppWrites = Promise.resolve();
|
|
976
|
+
if (!options.command && musicApp.available) {
|
|
977
|
+
musicAppListening = createMusicAppListening({
|
|
978
|
+
read: () => musicApp.nowPlaying(),
|
|
979
|
+
record: (play) => { musicAppWrites = musicAppWrites.then(() => recordMusicAppPlays([play])).catch(() => null); },
|
|
980
|
+
// A listener who chose Apple Music has the room read the Music app from the start.
|
|
981
|
+
allowed: playbackService === "apple_music",
|
|
982
|
+
});
|
|
983
|
+
}
|
|
958
984
|
// Moondog makes music on this Mac with Stable Audio 3 once the listener turns it on, in a room
|
|
959
985
|
// that can play what it makes: Moondog's own install, downloaded when they ask, or their folder.
|
|
960
986
|
// The terminal and the window each keep one generator, so each makes one track at a time; a
|
|
@@ -1111,6 +1137,7 @@ async function main() {
|
|
|
1111
1137
|
);
|
|
1112
1138
|
}
|
|
1113
1139
|
lyrics = await createLyricService().catch(() => null);
|
|
1140
|
+
musicAppListening?.watch();
|
|
1114
1141
|
// Each step stands alone, so a Spotify outage does not hold back a due rebuild.
|
|
1115
1142
|
listeningUpkeep = startListeningUpkeep({
|
|
1116
1143
|
run: async ({ signal }) => {
|
|
@@ -1130,6 +1157,9 @@ async function main() {
|
|
|
1130
1157
|
}
|
|
1131
1158
|
}
|
|
1132
1159
|
signal.throwIfAborted();
|
|
1160
|
+
// Completed conversations become durable memory a batch at a time, before the longer rebuild.
|
|
1161
|
+
await runMemoryReflectionIfDue({ application }).catch(() => null);
|
|
1162
|
+
signal.throwIfAborted();
|
|
1133
1163
|
await application.refreshListenerProfile({ signal });
|
|
1134
1164
|
},
|
|
1135
1165
|
});
|
|
@@ -1343,6 +1373,8 @@ async function main() {
|
|
|
1343
1373
|
unwatchStreamMusicApp?.();
|
|
1344
1374
|
atmosphereStream?.stop("closed");
|
|
1345
1375
|
listeningUpkeep?.stop();
|
|
1376
|
+
musicAppListening?.stop();
|
|
1377
|
+
await musicAppWrites;
|
|
1346
1378
|
lyrics?.close();
|
|
1347
1379
|
// Conversations close first: their domain services are forks of the main application's.
|
|
1348
1380
|
for (const conversation of conversations) conversation.close();
|
|
@@ -1305,6 +1305,10 @@ export class AppleProjectionDomainServices {
|
|
|
1305
1305
|
return this.#listeningHistoryStore?.recordMoondogSuggestions?.({ entries }) ?? null;
|
|
1306
1306
|
}
|
|
1307
1307
|
|
|
1308
|
+
recordSuggestionOutcome(outcome) {
|
|
1309
|
+
return this.#listeningHistoryStore?.recordSuggestionOutcome?.(outcome) ?? null;
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1308
1312
|
moondogSuggestionHistory(tracks) {
|
|
1309
1313
|
return this.#listeningHistoryStore?.moondogSuggestionHistory?.({ subjectId: this.#subjectId, tracks }) ?? null;
|
|
1310
1314
|
}
|
|
@@ -515,6 +515,10 @@ export class ListeningProfileDomainServices {
|
|
|
515
515
|
return this.#store.recordMoondogSuggestions?.({ entries }) ?? null;
|
|
516
516
|
}
|
|
517
517
|
|
|
518
|
+
recordSuggestionOutcome(outcome) {
|
|
519
|
+
return this.#store?.recordSuggestionOutcome?.(outcome) ?? null;
|
|
520
|
+
}
|
|
521
|
+
|
|
518
522
|
moondogSuggestionHistory(tracks) {
|
|
519
523
|
return this.#store.moondogSuggestionHistory?.({ subjectId: this.#subjectId, tracks }) ?? null;
|
|
520
524
|
}
|
|
@@ -225,6 +225,21 @@ function exactArtistReleaseHint(searchResult, artistName) {
|
|
|
225
225
|
// How long the model may take to name a conversation before its first message stays the name.
|
|
226
226
|
export const CONVERSATION_NAME_TIMEOUT_MS = 20_000;
|
|
227
227
|
|
|
228
|
+
// What memory keeps in place of a reply that used Spotify's data: counts, never names.
|
|
229
|
+
export function spotifyTurnReceipt(receipts = [], queued = 0) {
|
|
230
|
+
const counts = new Map();
|
|
231
|
+
for (const receipt of Array.isArray(receipts) ? receipts : []) {
|
|
232
|
+
const action = typeof receipt?.action === "string" ? receipt.action.replace(/[^a-z._]/gu, "").slice(0, 40) : "";
|
|
233
|
+
const state = typeof receipt?.state === "string" ? receipt.state.replace(/[^a-z_]/gu, "").slice(0, 20) : "";
|
|
234
|
+
if (!action) continue;
|
|
235
|
+
const key = state ? `${action} ${state}` : action;
|
|
236
|
+
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
237
|
+
}
|
|
238
|
+
const sent = [...counts].map(([key, count]) => `${key} x${count}`);
|
|
239
|
+
if (Number.isSafeInteger(queued) && queued > 0) sent.push(`queue plan queued x${queued}`);
|
|
240
|
+
return `[Moondog's reply used Spotify data, so memory keeps only this line.${sent.length ? ` Sent to Spotify: ${sent.join(", ")}.` : ""}]`;
|
|
241
|
+
}
|
|
242
|
+
|
|
228
243
|
export class MoondogApplication {
|
|
229
244
|
// Model calls naming conversations, stopped when the application closes.
|
|
230
245
|
#naming = new Set();
|
|
@@ -1206,8 +1221,8 @@ export class MoondogApplication {
|
|
|
1206
1221
|
return { compiled, receipt: {
|
|
1207
1222
|
shaped_by: compiled.descriptors, left_out: compiled.dropped,
|
|
1208
1223
|
...(compiled.bpm ? { bpm: compiled.bpm, bpm_source: compiled.bpm_source } : {}),
|
|
1209
|
-
//
|
|
1210
|
-
...(typeof request === "string" && !transient
|
|
1224
|
+
// The listener's own words, also in a conversation that read Spotify: they are theirs, not Spotify's.
|
|
1225
|
+
...(typeof request === "string" && !transient ? { request: Array.from(request).slice(0, 300).join("") } : {}),
|
|
1211
1226
|
avoids_in_force: context.avoids.length,
|
|
1212
1227
|
} };
|
|
1213
1228
|
}
|
|
@@ -1742,7 +1757,7 @@ export class MoondogApplication {
|
|
|
1742
1757
|
active_memories: status.active_memories,
|
|
1743
1758
|
reflection,
|
|
1744
1759
|
policy:
|
|
1745
|
-
"Completed dialogue becomes short-term episodes.
|
|
1760
|
+
"Completed dialogue becomes short-term episodes. While the room is open, a background Memory Agent reviews them a batch at a time, at most every few hours once caught up, and promotes high-confidence explicit general assertions into durable claims. Inferred claims and music taste stay reviewable candidates; the listener's Like and Avoid choices are the profile's own channel. In a conversation that read Spotify, memory keeps the listener's words and a host line with counts, never the reply.",
|
|
1746
1761
|
};
|
|
1747
1762
|
}
|
|
1748
1763
|
return {
|
|
@@ -1880,8 +1895,8 @@ export class MoondogApplication {
|
|
|
1880
1895
|
if (standalone) this.beginConversationEntry(user);
|
|
1881
1896
|
let status = 'failed';
|
|
1882
1897
|
try {
|
|
1883
|
-
//
|
|
1884
|
-
//
|
|
1898
|
+
// A conversation that read Spotify keeps the listener's words in memory, never the reply
|
|
1899
|
+
// that carried Spotify's data.
|
|
1885
1900
|
const result = this.transientSpotifyContext ? this.commitTransientPrompt(memoryMutations, user)
|
|
1886
1901
|
: this.memoryStore ? this.memoryStore.commitCompletedPrompt(this.ensureMemorySession().session_id,
|
|
1887
1902
|
{ user, assistant, memoryMutations, turnId: this.conversationEntry.entryId }) : { recorded: false, memory_results: [] };
|
|
@@ -1896,17 +1911,27 @@ export class MoondogApplication {
|
|
|
1896
1911
|
return this.commitCompletedPrompt(user, assistant);
|
|
1897
1912
|
}
|
|
1898
1913
|
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1914
|
+
// A turn in a conversation that read Spotify. Spotify's developer policy keeps its content,
|
|
1915
|
+
// metadata included, out of AI models, so the reply, which can carry Spotify's names, stays in
|
|
1916
|
+
// the conversation journal only. Memory, recall and reflection keep the listener's own words and
|
|
1917
|
+
// a host line with counts of what Moondog sent to Spotify. Explicit claims keep the verified
|
|
1918
|
+
// quote, never the model's paraphrase, which could carry provider content into a valid quote.
|
|
1919
|
+
commitTransientPrompt(memoryMutations = [], user = "", { spotifyReceipts = [], queued = 0 } = {}) {
|
|
1903
1920
|
const eligible = memoryMutations.filter((mutation) => mutation.type === "forget" ||
|
|
1904
1921
|
(mutation.type === "remember" && typeof mutation.sourceUserText === "string" &&
|
|
1905
1922
|
mutation.sourceUserText.length > 0 && user.includes(mutation.sourceUserText) &&
|
|
1906
1923
|
normalizeMemoryContent(mutation.sourceUserText) === mutation.content));
|
|
1924
|
+
const discarded = memoryMutations.length - eligible.length;
|
|
1925
|
+
if (this.memoryStore && typeof user === "string" && user.trim()) {
|
|
1926
|
+
const committed = this.memoryStore.commitCompletedPrompt(this.ensureMemorySession().session_id, {
|
|
1927
|
+
user, assistant: spotifyTurnReceipt(spotifyReceipts, queued), memoryMutations: eligible,
|
|
1928
|
+
...(this.conversationEntry ? { turnId: this.conversationEntry.entryId } : {}),
|
|
1929
|
+
});
|
|
1930
|
+
return { recorded: false, listener_words_recorded: true, memory_results: committed.memory_results, discarded_memories: discarded };
|
|
1931
|
+
}
|
|
1907
1932
|
return { recorded: false,
|
|
1908
1933
|
memory_results: this.memoryStore?.commitMemoryMutations(eligible) ?? [],
|
|
1909
|
-
discarded_memories:
|
|
1934
|
+
discarded_memories: discarded };
|
|
1910
1935
|
}
|
|
1911
1936
|
|
|
1912
1937
|
#clearConversationState() {
|
|
@@ -2939,6 +2964,20 @@ export class MoondogApplication {
|
|
|
2939
2964
|
} catch { /* The music still plays; only its origin goes unrecorded. */ }
|
|
2940
2965
|
}
|
|
2941
2966
|
|
|
2967
|
+
/**
|
|
2968
|
+
* How a song went that a player saw end: { service, providerTrackId, title, artists or
|
|
2969
|
+
* artistCredit, played_ms, skipped, completed, ended_at }. It is kept only for a song Moondog
|
|
2970
|
+
* started, as that suggestion's outcome; the listener's own plays keep none.
|
|
2971
|
+
*/
|
|
2972
|
+
noteSuggestionOutcome({ service, providerTrackId = null, title, artists, artistCredit, played_ms: heardMs, skipped, completed, ended_at: endedAt } = {}) {
|
|
2973
|
+
if (typeof this.domainServices?.recordSuggestionOutcome !== "function" || typeof title !== "string" || !title.trim()) return null;
|
|
2974
|
+
try {
|
|
2975
|
+
return this.domainServices.recordSuggestionOutcome({ service, providerTrackId, title, artists, artistCredit,
|
|
2976
|
+
outcome: completed ? "completed" : skipped ? "skipped" : "partial", heardMs: Math.max(0, Math.round(heardMs ?? 0)),
|
|
2977
|
+
at: new Date(endedAt ?? Date.now()).toISOString() });
|
|
2978
|
+
} catch { return null; }
|
|
2979
|
+
}
|
|
2980
|
+
|
|
2942
2981
|
// An album row goes with the song it started at: named song or named album, it is the listener's.
|
|
2943
2982
|
#withoutListenerNamed(tracks) {
|
|
2944
2983
|
const named = (track) => this.#listenerNamed(track.title ?? track.release, creditedArtists(track));
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// Follows one player from its reads and tells each finished play apart: a play that reached 30
|
|
2
|
+
// seconds, or the song's end, is a play; a shorter one is a skip. The Music app's plays go into the
|
|
3
|
+
// listening history this way, and the songs Moondog starts on Spotify get their outcome.
|
|
4
|
+
|
|
5
|
+
// A stream, as streaming services count one.
|
|
6
|
+
export const COUNTED_PLAY_MS = 30_000;
|
|
7
|
+
// Less than this was not really heard: a song seen only paused, or gone at once.
|
|
8
|
+
const HEARD_MS = 2_000;
|
|
9
|
+
// The last seconds of a song count as its end; reads come a few seconds apart.
|
|
10
|
+
const END_SLACK_MS = 10_000;
|
|
11
|
+
// A position that moves back this far, near the start, is the same song again.
|
|
12
|
+
const RESTART_MS = 5_000;
|
|
13
|
+
// Between reads a position can move a little more than the clock, never much more.
|
|
14
|
+
const READ_SLACK_MS = 2_000;
|
|
15
|
+
|
|
16
|
+
const songKey = (song) => song.id ? `id:${song.id}` : `song:${song.title}\n${song.artists.join(", ")}\n${song.album ?? ""}`;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* `observe` takes each read: { state: "playing" | "paused" | "stopped" | ..., song: { id, title,
|
|
20
|
+
* artists, album, duration_ms }, position_ms, playlist }. Any state but playing or paused, or no
|
|
21
|
+
* song, ends the play in progress. `record` gets each finished play: { song, playlist, ended_at,
|
|
22
|
+
* played_ms, skipped, completed }.
|
|
23
|
+
*/
|
|
24
|
+
export function createPlayFollower({ record }) {
|
|
25
|
+
let current = null;
|
|
26
|
+
|
|
27
|
+
function finish({ ended = false } = {}) {
|
|
28
|
+
const play = current;
|
|
29
|
+
current = null;
|
|
30
|
+
if (!play || play.playedMs < HEARD_MS) return;
|
|
31
|
+
const duration = play.song.duration_ms;
|
|
32
|
+
const completed = ended || (Number.isSafeInteger(duration) && duration > 0 && play.furthestMs >= duration - END_SLACK_MS);
|
|
33
|
+
const skipped = !completed && play.playedMs < COUNTED_PLAY_MS;
|
|
34
|
+
try {
|
|
35
|
+
record({ song: play.song, playlist: play.playlist, ended_at: play.lastAt, played_ms: Math.round(play.playedMs), skipped, completed });
|
|
36
|
+
} catch { /* A play that can't be stored is let go; the next one tries again. */ }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function observe(answer, at) {
|
|
40
|
+
const song = answer?.song;
|
|
41
|
+
if (!["playing", "paused"].includes(answer?.state) || !song?.title || !song.artists?.length) {
|
|
42
|
+
finish();
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const position = Number.isFinite(answer.position_ms) ? answer.position_ms : 0;
|
|
46
|
+
const playing = answer.state === "playing";
|
|
47
|
+
const key = songKey(song);
|
|
48
|
+
if (current?.key === key) {
|
|
49
|
+
// A position back near the start after the song had played on is the same song again, as on repeat.
|
|
50
|
+
const again = position < RESTART_MS && current.lastPositionMs > position + RESTART_MS;
|
|
51
|
+
if (!again) {
|
|
52
|
+
// Music that was playing at the last read played until about now, even if it is paused now.
|
|
53
|
+
if (current.playing) {
|
|
54
|
+
const moved = position - current.lastPositionMs;
|
|
55
|
+
if (moved > 0) current.playedMs += Math.min(moved, at - current.lastAt + READ_SLACK_MS);
|
|
56
|
+
}
|
|
57
|
+
Object.assign(current, { lastAt: at, lastPositionMs: position, playing, furthestMs: Math.max(current.furthestMs, position) });
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
finish({ ended: current.furthestMs >= (song.duration_ms ?? Infinity) - END_SLACK_MS });
|
|
61
|
+
} else {
|
|
62
|
+
finish();
|
|
63
|
+
}
|
|
64
|
+
current = { key, song, playlist: answer.playlist?.name ?? null, lastAt: at, lastPositionMs: position, furthestMs: position, playing, playedMs: 0 };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return { observe, finish: () => finish() };
|
|
68
|
+
}
|
package/src/i18n/screen/es.mjs
CHANGED
|
@@ -398,6 +398,7 @@ export default {
|
|
|
398
398
|
"No saved reading yet. Use {prefix} build with a connected model.": "Aún no hay una lectura guardada. Usa {prefix} build con un modelo conectado.",
|
|
399
399
|
"Your saved listening profile · v{version}": "Tu perfil de escucha guardado · v{version}",
|
|
400
400
|
"Evidence, choices or analysis changed. Use {prefix} build to update this reading.": "La evidencia, tus elecciones o el análisis han cambiado. Usa {prefix} build para actualizar esta lectura.",
|
|
401
|
+
"The last update, on {date}, did not finish: {reason}": "La última actualización, el {date}, no terminó: {reason}",
|
|
401
402
|
"The final check still flagged:": "La revisión final aún señaló:",
|
|
402
403
|
"Use {prefix} explain <number> for a finding's evidence.": "Usa {prefix} explain <número> para ver la evidencia de un hallazgo.",
|
|
403
404
|
"All {count} findings: {prefix} saved 0": "Los {count} hallazgos: {prefix} saved 0",
|
package/src/i18n/screen/ja.mjs
CHANGED
|
@@ -398,6 +398,7 @@ export default {
|
|
|
398
398
|
"No saved reading yet. Use {prefix} build with a connected model.": "保存した読み取りはまだありません。モデルを接続して {prefix} build を使ってください。",
|
|
399
399
|
"Your saved listening profile · v{version}": "保存したリスニングプロフィール · v{version}",
|
|
400
400
|
"Evidence, choices or analysis changed. Use {prefix} build to update this reading.": "根拠、選択、または分析が変わりました。{prefix} build でこの読み取りを更新してください。",
|
|
401
|
+
"The last update, on {date}, did not finish: {reason}": "前回の更新({date})は完了しませんでした: {reason}",
|
|
401
402
|
"The final check still flagged:": "最終確認でまだ指摘があります:",
|
|
402
403
|
"Use {prefix} explain <number> for a finding's evidence.": "発見の根拠は {prefix} explain <番号> で見られます。",
|
|
403
404
|
"All {count} findings: {prefix} saved 0": "発見 {count} 件すべて: {prefix} saved 0",
|
package/src/i18n/screen/pt.mjs
CHANGED
|
@@ -398,6 +398,7 @@ export default {
|
|
|
398
398
|
"No saved reading yet. Use {prefix} build with a connected model.": "Ainda não há leitura salva. Use {prefix} build com um modelo conectado.",
|
|
399
399
|
"Your saved listening profile · v{version}": "Seu perfil de escuta salvo · v{version}",
|
|
400
400
|
"Evidence, choices or analysis changed. Use {prefix} build to update this reading.": "A evidência, suas escolhas ou a análise mudaram. Use {prefix} build para atualizar esta leitura.",
|
|
401
|
+
"The last update, on {date}, did not finish: {reason}": "A última atualização, em {date}, não terminou: {reason}",
|
|
401
402
|
"The final check still flagged:": "A verificação final ainda apontou:",
|
|
402
403
|
"Use {prefix} explain <number> for a finding's evidence.": "Use {prefix} explain <número> para ver a evidência de uma descoberta.",
|
|
403
404
|
"All {count} findings: {prefix} saved 0": "Todas as {count} descobertas: {prefix} saved 0",
|
package/src/i18n/screen/zh.mjs
CHANGED
|
@@ -398,6 +398,7 @@ export default {
|
|
|
398
398
|
"No saved reading yet. Use {prefix} build with a connected model.": "还没有保存的解读。连接模型后使用 {prefix} build。",
|
|
399
399
|
"Your saved listening profile · v{version}": "你保存的聆听资料 · v{version}",
|
|
400
400
|
"Evidence, choices or analysis changed. Use {prefix} build to update this reading.": "证据、选择或分析有变化。使用 {prefix} build 更新这份解读。",
|
|
401
|
+
"The last update, on {date}, did not finish: {reason}": "上次更新({date})没有完成:{reason}",
|
|
401
402
|
"The final check still flagged:": "最终检查仍然指出:",
|
|
402
403
|
"Use {prefix} explain <number> for a finding's evidence.": "使用 {prefix} explain <编号> 查看某条发现的证据。",
|
|
403
404
|
"All {count} findings: {prefix} saved 0": "全部 {count} 条发现:{prefix} saved 0",
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// What the listener plays in the Music app on this Mac, kept as dated plays in their listening
|
|
2
|
+
// history, as Spotify's recent plays are. Apple gives no play history to read later, so the room
|
|
3
|
+
// keeps watch while it is open: every read of the Music app, the window's and its own, shows how
|
|
4
|
+
// far the playing song got. A play that reached 30 seconds, or the song's end, is a play; a
|
|
5
|
+
// shorter one is a skip. Each is stored when the next song starts or the music stops.
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
|
|
8
|
+
import { createPlayFollower } from "../../core/play-follower.mjs";
|
|
9
|
+
import { isUuid, uuidV5 } from "../../core/uuid-v5.mjs";
|
|
10
|
+
|
|
11
|
+
export { COUNTED_PLAY_MS } from "../../core/play-follower.mjs";
|
|
12
|
+
export const MUSIC_APP_LISTENING_SOURCE = "apple_music.music_app";
|
|
13
|
+
const TRACK_NAMESPACE = "5c4f693a-f35c-40e6-a9f6-653067b014c7";
|
|
14
|
+
const EVENT_NAMESPACE = "4943e59e-6f5f-4e47-a055-d233a687eae8";
|
|
15
|
+
|
|
16
|
+
// The room reads the Music app itself this often when nothing else has.
|
|
17
|
+
export const MUSIC_APP_WATCH_MS = 20_000;
|
|
18
|
+
|
|
19
|
+
const sha256 = (value) => createHash("sha256").update(value).digest("hex");
|
|
20
|
+
const clip = (value, maximum) => Array.from(String(value).replace(/\s+/gu, " ").trim()).slice(0, maximum).join("");
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
/** The listening-history bundle for finished Music app plays (at most 50). */
|
|
24
|
+
export function projectMusicAppPlays({ subjectId, plays, capturedAt = new Date().toISOString() }) {
|
|
25
|
+
if (!isUuid(subjectId)) throw new TypeError("A trusted subject ID is required");
|
|
26
|
+
if (!Array.isArray(plays) || plays.length > 50) throw new TypeError("Music app plays are not bounded");
|
|
27
|
+
const subject = subjectId.toLowerCase();
|
|
28
|
+
const trackRefs = new Map();
|
|
29
|
+
const listeningEvents = [];
|
|
30
|
+
let cursor = 0;
|
|
31
|
+
for (const play of plays) {
|
|
32
|
+
const title = clip(play.song.title, 512);
|
|
33
|
+
const artists = play.song.artists.map((name) => clip(name, 512)).filter(Boolean).slice(0, 5);
|
|
34
|
+
const endedAt = new Date(play.ended_at).toISOString();
|
|
35
|
+
// A library song keeps its own id, hashed as the library import hashes it; a radio song has only its names.
|
|
36
|
+
const identity = play.song.id ? `library\0${play.song.id}` : `named\0${title}\0${artists.join("\0")}\0${play.song.album ?? ""}`;
|
|
37
|
+
const trackRefId = uuidV5(identity, TRACK_NAMESPACE);
|
|
38
|
+
if (!trackRefs.has(trackRefId)) {
|
|
39
|
+
trackRefs.set(trackRefId, {
|
|
40
|
+
schema_version: 1, track_ref_id: trackRefId, revision: 1, identity_status: "resolved",
|
|
41
|
+
display_label: clip(`${title} - ${artists.join(", ")}`, 512), title,
|
|
42
|
+
artist_credits: artists.map((name) => ({ name, role: "unknown" })),
|
|
43
|
+
...(play.song.album ? { release: { title: clip(play.song.album, 512) } } : {}),
|
|
44
|
+
...(Number.isSafeInteger(play.song.duration_ms) && play.song.duration_ms > 0 ? { duration_ms: play.song.duration_ms } : {}),
|
|
45
|
+
external_refs: [{ system: "apple_music", entity_type: "apple_music.music_app_track", external_id: sha256(identity) }],
|
|
46
|
+
created_at: endedAt, resolved_at: endedAt,
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
const fingerprint = sha256(`apple_music.music_app\0${subject}\0${identity}\0${endedAt}`);
|
|
50
|
+
listeningEvents.push({
|
|
51
|
+
schema_version: 1, listening_event_id: uuidV5(fingerprint, EVENT_NAMESPACE), subject_id: subject,
|
|
52
|
+
track_ref_id: trackRefId, track_ref_revision: 1,
|
|
53
|
+
event_type: play.skipped ? "play_skipped" : "play_observed",
|
|
54
|
+
// As Spotify's: when the play ended.
|
|
55
|
+
occurred_at: endedAt, ingested_at: capturedAt, played_ms: play.played_ms, interaction_mode: "unknown",
|
|
56
|
+
context: { context_type: play.playlist ? "playlist" : "unknown" },
|
|
57
|
+
extensions: { "apple_music.skipped": play.skipped, "apple_music.completed": play.completed },
|
|
58
|
+
provenance: { source_kind: "tool", captured_at: capturedAt,
|
|
59
|
+
external_ref: { system: "apple_music", entity_type: "apple_music.music_app_play", external_id: fingerprint } },
|
|
60
|
+
deduplication_key: fingerprint,
|
|
61
|
+
});
|
|
62
|
+
cursor = Math.max(cursor, Date.parse(endedAt));
|
|
63
|
+
}
|
|
64
|
+
return { source_key: MUSIC_APP_LISTENING_SOURCE, captured_at: capturedAt, cursor_after_ms: cursor || null, window_full: false,
|
|
65
|
+
track_refs: [...trackRefs.values()], listening_events: listeningEvents };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Follows the Music app from its reads. `observe` takes each nowPlaying answer; `record` gets
|
|
70
|
+
* each finished play. `watch` reads the app itself when nothing else has for a while, but only
|
|
71
|
+
* once a read has shown that the listener let Moondog see the Music app, so it never asks first.
|
|
72
|
+
*/
|
|
73
|
+
export function createMusicAppListening({ read, record, now = Date.now, watchMs = MUSIC_APP_WATCH_MS, allowed: alreadyAllowed = false,
|
|
74
|
+
setTimer = setInterval, clearTimer = clearInterval }) {
|
|
75
|
+
let allowed = alreadyAllowed;
|
|
76
|
+
let lastRead = 0;
|
|
77
|
+
let timer = null;
|
|
78
|
+
const follower = createPlayFollower({ record });
|
|
79
|
+
|
|
80
|
+
function observe(answer, at = now()) {
|
|
81
|
+
lastRead = at;
|
|
82
|
+
if (!answer || answer.state === "unavailable" || answer.state === "not_allowed") return;
|
|
83
|
+
// A closed Music app answers without asking the listener anything; a running one answers only
|
|
84
|
+
// once they let Moondog see it.
|
|
85
|
+
if (answer.state !== "not_running") allowed = true;
|
|
86
|
+
follower.observe(answer, at);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return {
|
|
90
|
+
observe,
|
|
91
|
+
/** Reads the Music app on a slow clock, between other reads, once the listener has allowed it. */
|
|
92
|
+
watch() {
|
|
93
|
+
if (timer) return;
|
|
94
|
+
timer = setTimer(() => {
|
|
95
|
+
if (!allowed || now() - lastRead < watchMs - 1_000) return;
|
|
96
|
+
read().then((answer) => observe(answer), () => {});
|
|
97
|
+
}, watchMs);
|
|
98
|
+
timer?.unref?.();
|
|
99
|
+
},
|
|
100
|
+
/** Stores the play in progress, as when the room closes. */
|
|
101
|
+
stop() {
|
|
102
|
+
if (timer) clearTimer(timer);
|
|
103
|
+
timer = null;
|
|
104
|
+
follower.finish();
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
}
|
|
@@ -172,7 +172,7 @@ function nowPlayingOf(answer) {
|
|
|
172
172
|
};
|
|
173
173
|
}
|
|
174
174
|
|
|
175
|
-
export function createMusicAppPlayer({ platform = process.platform, environment = process.env, run = osascript, now = Date.now } = {}) {
|
|
175
|
+
export function createMusicAppPlayer({ platform = process.platform, environment = process.env, run = osascript, now = Date.now, onRead } = {}) {
|
|
176
176
|
// Disposable desktop checks can opt out of the listener's system Music app as well as local data.
|
|
177
177
|
const available = platform === "darwin" && environment.MOONDOG_SYSTEM_MUSIC !== "off";
|
|
178
178
|
let refusedAt = null;
|
|
@@ -191,12 +191,16 @@ export function createMusicAppPlayer({ platform = process.platform, environment
|
|
|
191
191
|
}
|
|
192
192
|
}
|
|
193
193
|
const read = async (action, argument) => {
|
|
194
|
+
let answer;
|
|
194
195
|
try {
|
|
195
|
-
|
|
196
|
+
answer = available ? nowPlayingOf(await ask(action, argument)) : { state: "unavailable" };
|
|
196
197
|
} catch (error) {
|
|
197
198
|
if (error?.code === "music_app_not_allowed") return { state: "not_allowed", reason: error.message };
|
|
198
199
|
throw error;
|
|
199
200
|
}
|
|
201
|
+
// Whoever reads, the window or the room, the listening history sees how far the song got.
|
|
202
|
+
try { onRead?.(answer); } catch { /* A watcher's trouble never fails a read. */ }
|
|
203
|
+
return answer;
|
|
200
204
|
};
|
|
201
205
|
|
|
202
206
|
return {
|
|
@@ -85,3 +85,21 @@ export async function runMemoryReflection({
|
|
|
85
85
|
throw error;
|
|
86
86
|
}
|
|
87
87
|
}
|
|
88
|
+
|
|
89
|
+
// The room reflects without being asked, on its listening upkeep. A backlog drains one batch at
|
|
90
|
+
// a time, one each upkeep; after that, reflection waits a few hours between runs, and a failed run
|
|
91
|
+
// waits as long before the next try.
|
|
92
|
+
export const REFLECTION_CADENCE = Object.freeze({ backlogGapMs: 25 * 60_000, gapMs: 6 * 3_600_000 });
|
|
93
|
+
|
|
94
|
+
/** Reflect on completed conversations when enough time has passed since the last run. */
|
|
95
|
+
export async function runMemoryReflectionIfDue({ application, now = Date.now(), ...options } = {}) {
|
|
96
|
+
if (!application?.memoryStore) return { state: "unavailable" };
|
|
97
|
+
const status = application.memoryReflectionStatus();
|
|
98
|
+
if (status.state === "running") return { state: "busy" };
|
|
99
|
+
if (!status.pending_episodes) return { state: "no_work" };
|
|
100
|
+
const last = status.last_run;
|
|
101
|
+
const backlog = status.pending_episodes >= MAX_REFLECTION_EPISODES && last?.status !== "failed";
|
|
102
|
+
const since = now - Date.parse(last?.started_at ?? "");
|
|
103
|
+
if (since < (backlog ? REFLECTION_CADENCE.backlogGapMs : REFLECTION_CADENCE.gapMs)) return { state: "waiting" };
|
|
104
|
+
return runMemoryReflection({ ...options, application, trigger: "schedule" });
|
|
105
|
+
}
|
|
@@ -386,9 +386,12 @@ export function readListenerProfile({ input, getInput, store, getChoices }, { of
|
|
|
386
386
|
const current = store.current();
|
|
387
387
|
const revision = revisionId ? store.revision(revisionId) : current;
|
|
388
388
|
if (revisionId && !revision) throw new Error("That saved profile version is unavailable");
|
|
389
|
+
// A background update that failed since this reading was saved, so a surface can say so.
|
|
390
|
+
const failure = revisionId ? null : store.lastFailure?.() ?? null;
|
|
389
391
|
if (!revision) {
|
|
390
392
|
const choices = getChoices?.();
|
|
391
|
-
return { state: "missing", total_claims: 0, claims: [], next_offset: null, ...(choices ? { listener_choices: choices } : {})
|
|
393
|
+
return { state: "missing", total_claims: 0, claims: [], next_offset: null, ...(choices ? { listener_choices: choices } : {}),
|
|
394
|
+
...(failure ? { last_build_failure: failure } : {}) };
|
|
392
395
|
}
|
|
393
396
|
// Most new listeners have no saved reading. Do not scan their source archive
|
|
394
397
|
// merely to tell an ordinary conversation that the reading is missing.
|
|
@@ -406,6 +409,7 @@ export function readListenerProfile({ input, getInput, store, getChoices }, { of
|
|
|
406
409
|
parent_revision_id: revision.parent_revision_id, built_at: revision.built_at, model: revision.model,
|
|
407
410
|
synthesis_version: revision.synthesis_version,
|
|
408
411
|
verification: revision.verification,
|
|
412
|
+
...(failure && state !== "current" ? { last_build_failure: failure } : {}),
|
|
409
413
|
summary: revision.summary, coverage: revision.coverage,
|
|
410
414
|
total_claims: revision.claims.length,
|
|
411
415
|
claims: revision.claims.slice(offset, offset + limit), offset,
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { profileDigest } from "./listener-profile-build.mjs";
|
|
3
3
|
|
|
4
|
+
const isAbort = (error) => error?.name === "AbortError" || error?.code === "ABORT_ERR";
|
|
5
|
+
|
|
4
6
|
// listener_profile_partitions holds page findings from builds before
|
|
5
7
|
// listener-synthesis/4. New builds no longer write it; it stays so existing
|
|
6
8
|
// databases open unchanged.
|
|
@@ -56,6 +58,7 @@ export class ListenerProfileStore {
|
|
|
56
58
|
const modelKey = profileDigest(model);
|
|
57
59
|
this.database.exec("BEGIN IMMEDIATE");
|
|
58
60
|
try {
|
|
61
|
+
this.#releaseAbandoned();
|
|
59
62
|
const parent = this.current()?.revision_id ?? null;
|
|
60
63
|
const existing = force ? null : this.database.prepare(`SELECT record_json FROM listener_profile_builds
|
|
61
64
|
WHERE subject_id = ? AND input_digest = ? AND model_key = ? AND state <> 'complete'
|
|
@@ -100,10 +103,39 @@ export class ListenerProfileStore {
|
|
|
100
103
|
} catch (error) { this.database.exec("ROLLBACK"); throw error; }
|
|
101
104
|
}
|
|
102
105
|
|
|
103
|
-
|
|
104
|
-
|
|
106
|
+
// The reason stays with the build, so the taste page and /taste can say why a reading stopped updating.
|
|
107
|
+
interrupt(build, error = null) {
|
|
108
|
+
const failure = error && !isAbort(error) ? {
|
|
109
|
+
at: new Date().toISOString(),
|
|
110
|
+
code: typeof error.code === "string" ? error.code.slice(0, 64) : null,
|
|
111
|
+
// The first paragraph names the cause; the rest is the terminal's advice to retry.
|
|
112
|
+
message: String(error.message ?? error).split("\n\n")[0].slice(0, 300),
|
|
113
|
+
} : null;
|
|
114
|
+
this.database.prepare(`UPDATE listener_profile_builds SET state = 'interrupted',
|
|
115
|
+
record_json = CASE WHEN ? IS NULL THEN record_json ELSE json_set(record_json, '$.failure', json(?)) END
|
|
105
116
|
WHERE subject_id = ? AND build_id = ? AND lease_token = ? AND state = 'building'`)
|
|
106
|
-
.run(this.subjectId, build.build_id, build.lease_token);
|
|
117
|
+
.run(failure && JSON.stringify(failure), failure && JSON.stringify(failure), this.subjectId, build.build_id, build.lease_token);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The latest build that failed after the current reading was saved, or null. */
|
|
121
|
+
lastFailure() {
|
|
122
|
+
const builtAt = this.current()?.built_at ?? "";
|
|
123
|
+
const row = this.database.prepare(`SELECT json_extract(record_json, '$.failure') AS failure,
|
|
124
|
+
json_extract(record_json, '$.model') AS model
|
|
125
|
+
FROM listener_profile_builds WHERE subject_id = ? AND state = 'interrupted'
|
|
126
|
+
AND json_extract(record_json, '$.failure.at') > ?
|
|
127
|
+
ORDER BY json_extract(record_json, '$.failure.at') DESC LIMIT 1`).get(this.subjectId, builtAt);
|
|
128
|
+
return row?.failure ? { ...JSON.parse(row.failure), model: row.model ? JSON.parse(row.model) : null } : null;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// A build whose process ended without a word (a quit, a crash) keeps its lease forever; a day later
|
|
132
|
+
// nothing holds it, so it reads as interrupted.
|
|
133
|
+
#releaseAbandoned() {
|
|
134
|
+
const before = new Date(Date.now() - 24 * 3_600_000).toISOString();
|
|
135
|
+
this.database.prepare(`UPDATE listener_profile_builds SET state = 'interrupted'
|
|
136
|
+
WHERE subject_id = ? AND state = 'building'
|
|
137
|
+
AND COALESCE(json_extract(record_json, '$.attempted_at'), json_extract(record_json, '$.started_at')) < ?`)
|
|
138
|
+
.run(this.subjectId, before);
|
|
107
139
|
}
|
|
108
140
|
|
|
109
141
|
complete(build, profile, assertCurrentInput = () => {}) {
|
|
@@ -11,6 +11,8 @@ import { createConfiguredProfileBuildRuntime } from "../runtime/pi/profile-build
|
|
|
11
11
|
// a model that hits its turn limit continue the same stage.
|
|
12
12
|
const MAX_REVISIONS = 1;
|
|
13
13
|
const MAX_SESSIONS = 8;
|
|
14
|
+
const MAX_CUT_REPLIES = 2;
|
|
15
|
+
const RETRIED_FAILURES = new Set(["profile_model_reply_cut", "model_connection_failed"]);
|
|
14
16
|
|
|
15
17
|
const HOUR_MS = 3_600_000;
|
|
16
18
|
// A reading that only new plays have overtaken is rebuilt after a week or 300 plays.
|
|
@@ -147,6 +149,7 @@ export async function runListenerProfileBuild({
|
|
|
147
149
|
signal?.throwIfAborted();
|
|
148
150
|
onProgress(progress());
|
|
149
151
|
let sessions = 0;
|
|
152
|
+
let cutReplies = 0;
|
|
150
153
|
while (phase() !== "complete") {
|
|
151
154
|
signal?.throwIfAborted();
|
|
152
155
|
session.phase = phase();
|
|
@@ -155,7 +158,14 @@ export async function runListenerProfileBuild({
|
|
|
155
158
|
throw new Error("The profile build reached its session limit. Your previous reading and the saved draft are kept. Use /profile build to continue.");
|
|
156
159
|
}
|
|
157
160
|
const inspectedBefore = inspected.size;
|
|
158
|
-
|
|
161
|
+
try {
|
|
162
|
+
await runtime.investigate(session);
|
|
163
|
+
} catch (error) {
|
|
164
|
+
// A reply cut off on its way, or a dropped connection, loses only that session; the saved
|
|
165
|
+
// draft and checks stay, and the same stage runs again.
|
|
166
|
+
if (!RETRIED_FAILURES.has(error?.code) || ++cutReplies > MAX_CUT_REPLIES || signal?.aborted) throw error;
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
159
169
|
signal?.throwIfAborted();
|
|
160
170
|
assertCurrentInput();
|
|
161
171
|
if (!stageFinished && inspected.size === inspectedBefore) {
|
|
@@ -170,7 +180,7 @@ export async function runListenerProfileBuild({
|
|
|
170
180
|
} }, assertCurrentInput);
|
|
171
181
|
return { state: "ready", revision: await application.getListenerProfile(), ...progress() };
|
|
172
182
|
} catch (error) {
|
|
173
|
-
store.interrupt(build);
|
|
183
|
+
store.interrupt(build, error);
|
|
174
184
|
throw error;
|
|
175
185
|
} finally {
|
|
176
186
|
signal?.removeEventListener("abort", abort);
|
|
@@ -220,6 +220,16 @@ const schema = `
|
|
|
220
220
|
CREATE INDEX IF NOT EXISTS moondog_suggestions_time
|
|
221
221
|
ON moondog_suggestions(requested_at);
|
|
222
222
|
|
|
223
|
+
-- How each song Moondog started went: played through, skipped within 30 seconds, or left
|
|
224
|
+
-- partway. An outcome of a suggestion, never a dislike. Older Moondogs leave this table alone.
|
|
225
|
+
CREATE TABLE IF NOT EXISTS moondog_suggestion_outcomes (
|
|
226
|
+
suggestion_id TEXT NOT NULL,
|
|
227
|
+
outcome TEXT NOT NULL CHECK (outcome IN ('completed', 'skipped', 'partial')),
|
|
228
|
+
heard_ms INTEGER NOT NULL,
|
|
229
|
+
observed_at TEXT NOT NULL,
|
|
230
|
+
PRIMARY KEY (suggestion_id, observed_at)
|
|
231
|
+
) STRICT;
|
|
232
|
+
|
|
223
233
|
${listenerProfileSchema}
|
|
224
234
|
`;
|
|
225
235
|
|
|
@@ -676,6 +686,7 @@ const COVERAGE_SOURCE_LABELS = {
|
|
|
676
686
|
"spotify.extended_history.play": "Spotify Extended Streaming History file",
|
|
677
687
|
"spotify.account_data.play_history": "Spotify Account Data file",
|
|
678
688
|
"listenbrainz.listen": "ListenBrainz export file",
|
|
689
|
+
"apple_music.music_app_play": "Music app plays on this Mac, kept while Moondog runs",
|
|
679
690
|
};
|
|
680
691
|
|
|
681
692
|
const SCROBBLE_SOURCE_KEY = "lastfm.music_import";
|
|
@@ -1880,9 +1891,35 @@ export class ListeningHistoryStore {
|
|
|
1880
1891
|
return { recorded };
|
|
1881
1892
|
}
|
|
1882
1893
|
|
|
1894
|
+
/**
|
|
1895
|
+
* How a song Moondog started went. It belongs to the latest suggestion of that song requested
|
|
1896
|
+
* up to six hours before the play ended; a song Moondog did not start keeps no outcome.
|
|
1897
|
+
*/
|
|
1898
|
+
recordSuggestionOutcome({ service, providerTrackId = null, title, artists, artistCredit, outcome, heardMs, at } = {}) {
|
|
1899
|
+
if (this.#closed) throw new Error("Listening history store is closed");
|
|
1900
|
+
if (!["completed", "skipped", "partial"].includes(outcome) || !Number.isSafeInteger(heardMs) || heardMs < 0) {
|
|
1901
|
+
throw new TypeError("Suggestion outcome is invalid");
|
|
1902
|
+
}
|
|
1903
|
+
const observedMs = Date.parse(at);
|
|
1904
|
+
if (!Number.isFinite(observedMs)) throw new TypeError("Suggestion outcome time is invalid");
|
|
1905
|
+
const entry = suggestionEntry({ service, action: "lookup", providerTrackId, title, artists, artistCredit, requestedAt: at });
|
|
1906
|
+
if (!entry) return { recorded: false };
|
|
1907
|
+
const identities = new Set(suggestionIdentities(entry).filter((identity) => !identity.startsWith("release:")));
|
|
1908
|
+
const from = new Date(observedMs - SUGGESTION_WINDOW.afterMs).toISOString();
|
|
1909
|
+
const to = new Date(observedMs + SUGGESTION_WINDOW.beforeMs).toISOString();
|
|
1910
|
+
const candidates = this.#database.prepare(`SELECT suggestion_id, provider_track_id, isrc, track_key, release_key, title, artist_credit,
|
|
1911
|
+
requested_at FROM moondog_suggestions WHERE requested_at BETWEEN ? AND ? ORDER BY requested_at DESC, suggestion_id`).all(from, to);
|
|
1912
|
+
const match = candidates.find((suggestion) => suggestionIdentities(suggestion).some((identity) => identities.has(identity)));
|
|
1913
|
+
if (!match) return { recorded: false };
|
|
1914
|
+
const inserted = this.#database.prepare(`INSERT OR IGNORE INTO moondog_suggestion_outcomes (suggestion_id, outcome, heard_ms, observed_at)
|
|
1915
|
+
VALUES (?, ?, ?, ?)`).run(match.suggestion_id, outcome, heardMs, new Date(observedMs).toISOString());
|
|
1916
|
+
return { recorded: inserted.changes === 1, suggestion_id: match.suggestion_id };
|
|
1917
|
+
}
|
|
1918
|
+
|
|
1883
1919
|
/**
|
|
1884
1920
|
* Moondog's earlier suggestions of each track, matched as stored plays are: the same provider
|
|
1885
|
-
* track, ISRC or song. Adopted means the listener later played it again on their own
|
|
1921
|
+
* track, ISRC or song. Adopted means the listener later played it again on their own; outcomes
|
|
1922
|
+
* count how the plays Moondog started went.
|
|
1886
1923
|
*/
|
|
1887
1924
|
moondogSuggestionHistory({ subjectId, tracks } = {}) {
|
|
1888
1925
|
if (!Array.isArray(tracks)) throw new TypeError("Suggestion history tracks are invalid");
|
|
@@ -1895,13 +1932,20 @@ export class ListeningHistoryStore {
|
|
|
1895
1932
|
byIdentity.set(identity, [...(byIdentity.get(identity) ?? []), suggestion]);
|
|
1896
1933
|
}
|
|
1897
1934
|
}
|
|
1935
|
+
const outcomes = new Map();
|
|
1936
|
+
for (const row of this.#database.prepare("SELECT suggestion_id, outcome FROM moondog_suggestion_outcomes").all()) {
|
|
1937
|
+
outcomes.set(row.suggestion_id, [...(outcomes.get(row.suggestion_id) ?? []), row.outcome]);
|
|
1938
|
+
}
|
|
1898
1939
|
return tracks.map((track) => {
|
|
1899
1940
|
const entry = suggestionEntry({ service: "spotify", action: "lookup", ...track });
|
|
1900
1941
|
const matches = new Set(entry ? suggestionIdentities(entry).flatMap((identity) => byIdentity.get(identity) ?? []) : []);
|
|
1901
1942
|
if (!matches.size) return null;
|
|
1902
1943
|
const last = [...matches].reduce((latest, item) => item.requested_at > latest ? item.requested_at : latest, "");
|
|
1944
|
+
const heard = { completed: 0, skipped: 0, partial: 0 };
|
|
1945
|
+
for (const item of matches) for (const row of outcomes.get(item.suggestion_id) ?? []) heard[row] += 1;
|
|
1903
1946
|
return { times: matches.size, last_suggested_at: last.slice(0, 10),
|
|
1904
|
-
adopted: [...matches].some((item) => adopted.has(item.suggestion_id))
|
|
1947
|
+
adopted: [...matches].some((item) => adopted.has(item.suggestion_id)),
|
|
1948
|
+
...(heard.completed + heard.skipped + heard.partial ? { outcomes: heard } : {}) };
|
|
1905
1949
|
});
|
|
1906
1950
|
}
|
|
1907
1951
|
|
|
@@ -785,17 +785,19 @@ function aggregateEvents(subjectId, eventRows, explanations) {
|
|
|
785
785
|
}
|
|
786
786
|
const skipped =
|
|
787
787
|
event?.event_type === "play_skipped" ||
|
|
788
|
-
event?.extensions?.["spotify.skipped"] === true
|
|
788
|
+
event?.extensions?.["spotify.skipped"] === true ||
|
|
789
|
+
event?.extensions?.["apple_music.skipped"] === true;
|
|
789
790
|
eligible.push({
|
|
790
791
|
event,
|
|
791
792
|
track: row.track,
|
|
792
793
|
playedMs,
|
|
793
794
|
timed: hasPlayedDuration,
|
|
794
795
|
skipped,
|
|
795
|
-
//
|
|
796
|
-
//
|
|
796
|
+
// Spotify's extended history says whether a play was skipped, not for every play, and
|
|
797
|
+
// the Music app plays Moondog kept say it for each.
|
|
797
798
|
skipKnown:
|
|
798
|
-
skipped || typeof event?.extensions?.["spotify.skipped"] === "boolean"
|
|
799
|
+
skipped || typeof event?.extensions?.["spotify.skipped"] === "boolean" ||
|
|
800
|
+
typeof event?.extensions?.["apple_music.skipped"] === "boolean",
|
|
799
801
|
});
|
|
800
802
|
}
|
|
801
803
|
const earliest = eligible.reduce(
|
|
@@ -2640,6 +2642,7 @@ export function projectListeningProfile({
|
|
|
2640
2642
|
if (system.startsWith("listenbrainz")) return "listenbrainz";
|
|
2641
2643
|
if (system === "youtube_music") return "youtube_music";
|
|
2642
2644
|
if (system === "lastfm") return "lastfm";
|
|
2645
|
+
if (system === "apple_music") return "apple_music";
|
|
2643
2646
|
return "other";
|
|
2644
2647
|
})
|
|
2645
2648
|
.filter(Boolean),
|
|
@@ -3184,9 +3184,12 @@ function projectSpotifySearch(value) {
|
|
|
3184
3184
|
// How often Moondog suggested a candidate in earlier sessions, from the host's ledger.
|
|
3185
3185
|
function projectSuggestedBefore(value) {
|
|
3186
3186
|
if (!isPlainObject(value?.suggested_before)) return {};
|
|
3187
|
-
const { times, last_suggested_at: last, adopted } = value.suggested_before;
|
|
3187
|
+
const { times, last_suggested_at: last, adopted, outcomes } = value.suggested_before;
|
|
3188
3188
|
if (!Number.isSafeInteger(times) || times < 1 || typeof last !== "string" || !/^\d{4}-\d{2}-\d{2}$/u.test(last)) return {};
|
|
3189
|
-
|
|
3189
|
+
const count = (key) => Number.isSafeInteger(outcomes?.[key]) && outcomes[key] > 0 ? outcomes[key] : 0;
|
|
3190
|
+
const heard = { played_through: count("completed"), skipped: count("skipped"), left_partway: count("partial") };
|
|
3191
|
+
return { suggested_before: { times, last_suggested_at: last, adopted: adopted === true,
|
|
3192
|
+
...(heard.played_through + heard.skipped + heard.left_partway ? { when_moondog_played_it: heard } : {}) } };
|
|
3190
3193
|
}
|
|
3191
3194
|
|
|
3192
3195
|
// The host's declared mix of a set: how many songs sit where in the listener's own plays.
|
|
@@ -7191,7 +7194,7 @@ Current music catalog rules:
|
|
|
7191
7194
|
- For open-world discovery, use the profile when personalization matters, then combine music knowledge, available web research and bounded Spotify verification. Apple catalog search and artist adjacency are optional additional evidence; an empty result from either is not the end of discovery while Spotify search remains available.
|
|
7192
7195
|
- External search is lexical catalog retrieval, not audio analysis. Use known musical context as qualified curatorial judgment; never present a query phrase or bare title as measured sound evidence.
|
|
7193
7196
|
- Known or previously heard tracks remain eligible unless the listener explicitly requests unfamiliar music. Honor active Avoid. A bounded knownness check never proves lifetime novelty; report that limit when relevant.
|
|
7194
|
-
- A candidate's suggested_before means Moondog already played or queued it in an earlier session. Prefer music not suggested in recent sessions unless the listener asks for it again or it was adopted (the listener played it again on their own).
|
|
7197
|
+
- A candidate's suggested_before means Moondog already played or queued it in an earlier session. Prefer music not suggested in recent sessions unless the listener asks for it again or it was adopted (the listener played it again on their own). Its when_moondog_played_it counts how those plays went: played through, skipped within 30 seconds, or left partway. A skip is an outcome, never a dislike; after repeated skips, pick something else unless the listener asks for it.
|
|
7195
7198
|
- For open-ended external discovery, diversify the final plan across releases and artists. The local planner allows one selected track per release and at most two per artist unless the user's intent explicitly names that release or artist.
|
|
7196
7199
|
- If catalog candidates are sparse or low quality, say so and refine the bounded queries instead of presenting weak matches as confident recommendations.
|
|
7197
7200
|
- For optional artist-adjacency planning, selected_profile_track can provide a retained seed. Use moondog_music_artist_similarity when that evidence is helpful. A named song/artist or style request can instead start from musical hypotheses, available public web research and Spotify verification; a private-library seed is never required. Queue requests continue with Spotify-verified references and queue_batch, without a playlist plan.
|
|
@@ -7987,8 +7990,6 @@ export class PiAgentRuntime {
|
|
|
7987
7990
|
attempt: state.generationAttempts,
|
|
7988
7991
|
moment: now instanceof Date && Number.isFinite(now.getTime()) ? listenerClock(now) : null,
|
|
7989
7992
|
request: state.promptText,
|
|
7990
|
-
// A conversation that read Spotify keeps the listener's words out of the receipt, as out of memory.
|
|
7991
|
-
transient: this.transientSpotifyContext || this.application.transientSpotifyContext === true,
|
|
7992
7993
|
// A stream names each track after its first with this conversation's model, at the hour that track is made.
|
|
7993
7994
|
nameRecord: (context, { signal } = {}) => {
|
|
7994
7995
|
const at = this.clock?.();
|
|
@@ -8566,7 +8567,8 @@ export class PiAgentRuntime {
|
|
|
8566
8567
|
: this.application.recordCompletedTurn?.(text, finalResultText);
|
|
8567
8568
|
memoryRecorded = committed?.recorded === true;
|
|
8568
8569
|
} else if (resultText) {
|
|
8569
|
-
const committed = this.application.commitTransientPrompt?.(promptState.stagedMemoryMutations, text
|
|
8570
|
+
const committed = this.application.commitTransientPrompt?.(promptState.stagedMemoryMutations, text, {
|
|
8571
|
+
spotifyReceipts: promptState.spotifyWriteReceipts, queued: promptState.spotifyQueuePlan?.queued?.length ?? 0 });
|
|
8570
8572
|
if (committed?.discarded_memories > 0) {
|
|
8571
8573
|
const note = t("memory.spotifyExcluded");
|
|
8572
8574
|
finalResultText += note;
|
|
@@ -2,6 +2,7 @@ import { Agent } from "@earendil-works/pi-agent-core";
|
|
|
2
2
|
import { Type } from "typebox";
|
|
3
3
|
|
|
4
4
|
import { createConfiguredRuntime } from "./configured-runtime.mjs";
|
|
5
|
+
import { backgroundRequestHeaders } from "./moondog-model.mjs";
|
|
5
6
|
|
|
6
7
|
export const MAX_REFLECTION_EPISODES = 24;
|
|
7
8
|
export const MEMORY_AGENT_WORKER_VERSION = "memory-reflection/1";
|
|
@@ -291,6 +292,7 @@ export class MemoryAgentRuntime {
|
|
|
291
292
|
streamFn: (model, context, options) =>
|
|
292
293
|
this.models.streamSimple(model, context, {
|
|
293
294
|
...options,
|
|
295
|
+
headers: backgroundRequestHeaders(this.provider, options?.headers),
|
|
294
296
|
toolChoice: toolChoiceForApi(model.api),
|
|
295
297
|
}),
|
|
296
298
|
toolExecution: "sequential",
|
|
@@ -38,6 +38,12 @@ function inviteError(code, message, cause) {
|
|
|
38
38
|
|
|
39
39
|
export const isMoondogProvider = (providerId) => providerId === MOONDOG_PROVIDER;
|
|
40
40
|
|
|
41
|
+
// Work that runs out of sight, such as rebuilding the reading or reflecting on memory, asks Moondog's
|
|
42
|
+
// gateway for the whole reply at once. A long reasoning answer relayed token by token can use up the
|
|
43
|
+
// gateway's CPU and end without its last event; nobody watches these replies arrive anyway.
|
|
44
|
+
export const backgroundRequestHeaders = (providerId, headers) =>
|
|
45
|
+
isMoondogProvider(providerId) ? { ...headers, "x-moondog-delivery": "whole" } : headers;
|
|
46
|
+
|
|
41
47
|
// The gateway's address. MOONDOG_MODEL_URL points a development build at another gateway.
|
|
42
48
|
export function moondogModelUrl(environment = process.env) {
|
|
43
49
|
const configured = environment.MOONDOG_MODEL_URL?.trim();
|
|
@@ -3,8 +3,11 @@ import { Agent } from "@earendil-works/pi-agent-core";
|
|
|
3
3
|
import { Type } from "typebox";
|
|
4
4
|
import { createConfiguredRuntime } from "./configured-runtime.mjs";
|
|
5
5
|
import { createModelConnectionError, createModelFetch, isModelConnectionFailure, safeProviderErrorMessage } from "./model-transport.mjs";
|
|
6
|
+
import { backgroundRequestHeaders } from "./moondog-model.mjs";
|
|
6
7
|
|
|
7
8
|
export const PROFILE_BUILD_WORKER_VERSION = "profile-investigation/2";
|
|
9
|
+
// A reply that stopped before its end: the worker can run the same stage again.
|
|
10
|
+
const REPLY_CUT = /Stream ended without finish_reason|terminated|premature close/iu;
|
|
8
11
|
const reference = Type.String({ minLength: 1, maxLength: 80 });
|
|
9
12
|
const references = (minimum = 0, maximum = 8) => Type.Array(reference, { minItems: minimum, maxItems: maximum, uniqueItems: true });
|
|
10
13
|
const insight = Type.Object({
|
|
@@ -110,6 +113,7 @@ export class ProfileBuildRuntime {
|
|
|
110
113
|
streamFn: (model, context, options) => this.models.streamSimple(model, context, {
|
|
111
114
|
...options,
|
|
112
115
|
maxRetries: 0,
|
|
116
|
+
headers: backgroundRequestHeaders(this.provider, options?.headers),
|
|
113
117
|
// Reuse the normal conversation transport's bounded HTTP retries.
|
|
114
118
|
// Replaying the agent loop could repeat checkpoint tools.
|
|
115
119
|
fetch: ["google-generative-ai", "google-vertex"].includes(model.api) ? undefined : createModelFetch({
|
|
@@ -143,7 +147,7 @@ export class ProfileBuildRuntime {
|
|
|
143
147
|
const message = safeProviderErrorMessage(agent.state.errorMessage, this.provider);
|
|
144
148
|
const error = connectionFailure || isModelConnectionFailure(message)
|
|
145
149
|
? createModelConnectionError({ provider: this.provider, cause: connectionFailure ?? new Error(message) })
|
|
146
|
-
: Object.assign(new Error(message), { code: "profile_model_request_failed" });
|
|
150
|
+
: Object.assign(new Error(message), { code: REPLY_CUT.test(message) ? "profile_model_reply_cut" : "profile_model_request_failed" });
|
|
147
151
|
error.message += "\n\nYour previous reading and any saved draft are kept. Use /profile build to continue.";
|
|
148
152
|
throw error;
|
|
149
153
|
}
|
|
@@ -24,6 +24,8 @@ function formatSaved(value, prefix, allFindings = false, tr) {
|
|
|
24
24
|
const lines = [
|
|
25
25
|
`# ${tr("Your saved listening profile · v{version}", { version: value.sequence })}`,
|
|
26
26
|
value.state === "stale" ? tr("Evidence, choices or analysis changed. Use {prefix} build to update this reading.", { prefix }) : builtLine(value, tr),
|
|
27
|
+
...(value.last_build_failure ? [tr("The last update, on {date}, did not finish: {reason}",
|
|
28
|
+
{ date: value.last_build_failure.at.slice(0, 10), reason: sanitizeTerminalText(value.last_build_failure.message) })] : []),
|
|
27
29
|
"", value.summary, "",
|
|
28
30
|
];
|
|
29
31
|
// The TUI renders this text as Markdown, which renumbers an ordered list from its
|