Open History to see the last commit
1import {
2 IsoDateTime,
3 MuseSettings,
4 ProviderDriverKind,
5 ProviderInstanceId,
6 resolveProviderInstanceEnabled,
7 type ServerSettings,
8} from "@t3tools/contracts";
9import * as Effect from "effect/Effect";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import * as Schema from "effect/Schema";
13import * as Scope from "effect/Scope";
14
15import { expandHomePath } from "../pathExpansion.ts";
16import { mergeProviderInstanceEnvironment } from "../provider/ProviderInstanceEnvironment.ts";
17import {
18 createMuseSdkHost,
19 createMuseSdkHostEffect,
20 type MuseSdkHost,
21} from "../provider/museSdk.ts";
22
23const SessionId = Schema.String.check(
24 Schema.isPattern(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i),
25);
26const SessionMetadata = Schema.Struct({
27 sessionId: SessionId,
28 path: Schema.String.check(Schema.isMaxLength(32_768)),
29 workspaceRoot: Schema.NullOr(Schema.String.check(Schema.isMaxLength(32_768))),
30 providerId: Schema.NullOr(Schema.String),
31 modelId: Schema.NullOr(Schema.String.check(Schema.isMaxLength(256))),
32 createdAt: IsoDateTime,
33 updatedAt: IsoDateTime,
34});
35export type MuseImportSession = typeof SessionMetadata.Type;
36
37const SessionList = Schema.Struct({
38 sessions: Schema.Array(SessionMetadata).check(Schema.isMaxLength(200)),
39 nextCursor: Schema.NullOr(Schema.String),
40});
41const decodeList = Schema.decodeUnknownEffect(SessionList);
42const decodeRead = Schema.decodeUnknownEffect(
43 Schema.Struct({
44 session: SessionMetadata,
45 history: Schema.Struct({
46 mode: Schema.String,
47 noneReason: Schema.optional(Schema.String),
48 snapshot: Schema.optional(Schema.NullOr(Schema.Struct({ schemaVersion: Schema.Int }))),
49 }),
50 }),
51);
52const MessageItem = Schema.Struct({
53 itemId: Schema.String,
54 kind: Schema.String,
55 revision: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
56 status: Schema.String,
57 text: Schema.optional(Schema.String),
58 displayText: Schema.optional(Schema.String),
59 recordedAt: Schema.optional(IsoDateTime),
60 retracted: Schema.optional(Schema.Boolean),
61 truncated: Schema.optional(Schema.Boolean),
62});
63const EffectiveModelId = Schema.String.check(Schema.isPattern(/^\S+$/), Schema.isMaxLength(256));
64const HistoryPage = Schema.Struct({
65 events: Schema.Array(
66 Schema.Struct({
67 method: Schema.String,
68 params: Schema.Struct({
69 sessionId: Schema.String,
70 item: Schema.optional(MessageItem),
71 modelId: Schema.optional(Schema.NullOr(EffectiveModelId)),
72 providerId: Schema.optional(Schema.NullOr(Schema.String)),
73 }),
74 }),
75 ).check(Schema.isMaxLength(200)),
76 nextCursor: Schema.NullOr(Schema.String),
77});
78const decodePage = Schema.decodeUnknownEffect(HistoryPage);
79
80export interface MuseImportInstance {
81 readonly instanceId: ProviderInstanceId;
82 readonly binaryPath: string;
83 readonly environment: NodeJS.ProcessEnv;
84}
85
86/** The host which lists a session owns its continuation; upstream providerId is not an account id. */
87export function museImportInstances(settings: ServerSettings, environment: NodeJS.ProcessEnv) {
88 const instances = Object.entries(settings.providerInstances)
89 .filter(
90 ([, instance]) => instance.driver === "muse" && resolveProviderInstanceEnabled(instance),
91 )
92 .map(([instanceId, config]) => ({ instanceId: ProviderInstanceId.make(instanceId), config }));
93 if (!Object.hasOwn(settings.providerInstances, "muse") && settings.providers.muse.enabled) {
94 instances.unshift({
95 instanceId: ProviderInstanceId.make("muse"),
96 config: { driver: ProviderDriverKind.make("muse"), config: settings.providers.muse },
97 });
98 }
99 instances.sort(
100 (left, right) => Number(right.instanceId === "muse") - Number(left.instanceId === "muse"),
101 );
102 const decode = Schema.decodeUnknownOption(MuseSettings);
103 return instances.flatMap(({ instanceId, config }): MuseImportInstance[] => {
104 const settings = decode(config.config ?? {});
105 return Option.isNone(settings)
106 ? []
107 : [
108 {
109 instanceId,
110 binaryPath: expandHomePath(settings.value.binaryPath),
111 environment: mergeProviderInstanceEnvironment(config.environment, environment),
112 },
113 ];
114 });
115}
116
117class MuseImportError extends Schema.TaggedError<MuseImportError>()("MuseImportError", {
118 detail: Schema.String,
119}) {}
120
121/** Read published MSP history while the caller holds real pre/post filesystem identities. */
122export const makeMuseSessionImport = Effect.fn("makeMuseSessionImport")(function* (
123 createHost: typeof createMuseSdkHost = createMuseSdkHost,
124) {
125 const scope = yield* Scope.Scope;
126 const path = yield* Path.Path;
127 const hosts = new Map<ProviderInstanceId, MuseSdkHost>();
128 const getHost = Effect.fn("MuseSessionImport.getHost")(function* (instance: MuseImportInstance) {
129 const existing = hosts.get(instance.instanceId);
130 if (existing) return existing;
131 const host = yield* Effect.acquireRelease(
132 createMuseSdkHostEffect(
133 {
134 binaryPath: instance.binaryPath,
135 environment: instance.environment,
136 readOnly: true,
137 // Stored history is unavailable to an ephemeral host. No sessions or turns are started.
138 sessionLogging: true,
139 startupTimeoutMs: 8_000,
140 },
141 createHost,
142 ),
143 (host) => Effect.promise(() => host.close()),
144 { interruptible: true },
145 ).pipe(Effect.provideService(Scope.Scope, scope));
146 if (
147 host.initializeResult.schema.version !== 1 ||
148 host.initializeResult.sessionDurability === "ephemeral"
149 ) {
150 return yield* new MuseImportError({
151 detail: "Muse does not expose supported durable history.",
152 });
153 }
154 hosts.set(instance.instanceId, host);
155 return host;
156 });
157 const request = (host: MuseSdkHost, method: string, params: Record<string, unknown>) =>
158 Effect.tryPromise(() => host.connection.request(method, params)).pipe(
159 Effect.timeout("10 seconds"),
160 );
161
162 const isRootSession = (host: MuseSdkHost, session: MuseImportSession) => {
163 if (
164 !session.path ||
165 !path.isAbsolute(session.path) ||
166 !session.workspaceRoot ||
167 !path.isAbsolute(session.workspaceRoot) ||
168 session.providerId !== "meta" ||
169 !session.modelId?.trim()
170 )
171 return false;
172 // Native root logs live under date/sessionId; nested subagent/reminder logs must not
173 // appear as independent projects. Unknown layouts are skipped without reading raw logs.
174 const parts = path
175 .relative(path.join(host.initializeResult.museHome, "sessions"), session.path)
176 .split(path.sep);
177 return (
178 parts.length === 5 &&
179 /^\d{4}$/.test(parts[0]!) &&
180 /^\d{2}$/.test(parts[1]!) &&
181 /^\d{2}$/.test(parts[2]!) &&
182 parts[3] === session.sessionId &&
183 parts[4] === "session.jsonl"
184 );
185 };
186
187 const list = Effect.fn("MuseSessionImport.list")(function* (
188 instance: MuseImportInstance,
189 limit: number,
190 ) {
191 const host = yield* getHost(instance);
192 const sessions: MuseImportSession[] = [];
193 const cursors = new Set<string>();
194 let cursor: string | null = null;
195 let inspected = 0;
196 do {
197 const page: typeof SessionList.Type = yield* request(host, "session/list", {
198 limit: Math.min(200, limit - inspected),
199 ...(cursor ? { cursor } : {}),
200 }).pipe(Effect.flatMap(decodeList));
201 inspected += page.sessions.length;
202 sessions.push(...page.sessions.filter((session) => isRootSession(host, session)));
203 cursor = page.nextCursor;
204 if (cursor !== null && (page.sessions.length === 0 || cursors.has(cursor))) {
205 return yield* new MuseImportError({ detail: "Muse session listing did not advance." });
206 }
207 if (cursor !== null) cursors.add(cursor);
208 } while (cursor !== null && inspected < limit);
209 return { sessions, truncated: cursor !== null };
210 });
211
212 const read = Effect.fn("MuseSessionImport.read")(function* (
213 instance: MuseImportInstance,
214 sessionId: string,
215 limits: { readonly records: number; readonly historyBytes: number; readonly messages: number },
216 ) {
217 const host = yield* getHost(instance);
218 const read = yield* request(host, "session/read", { sessionId, excludeItems: true }).pipe(
219 Effect.flatMap(decodeRead),
220 );
221 if (
222 read.session.sessionId !== sessionId ||
223 !isRootSession(host, read.session) ||
224 (read.history.snapshot && read.history.snapshot.schemaVersion !== 1) ||
225 (read.history.noneReason && !["excluded", "historyBudget"].includes(read.history.noneReason))
226 ) {
227 return yield* new MuseImportError({ detail: "Muse session history is unavailable." });
228 }
229 const items = new Map<string, typeof MessageItem.Type>();
230 const cursors = new Set<string>();
231 let cursor: string | null = null;
232 let recordCount = 0;
233 let historyBytes = 0;
234 let selectedModelId: string | undefined;
235 let observedModelId: string | undefined;
236 do {
237 if (recordCount >= limits.records)
238 return yield* new MuseImportError({
239 detail: "Muse history exceeds the import record budget.",
240 });
241 const page: typeof HistoryPage.Type = yield* request(host, "view/page", {
242 sessionId,
243 limit: Math.min(200, limits.records - recordCount),
244 ...(cursor ? { cursor } : {}),
245 }).pipe(Effect.flatMap(decodePage));
246 recordCount += page.events.length;
247 for (const event of page.events) {
248 if (event.params.sessionId !== sessionId)
249 return yield* new MuseImportError({ detail: "Muse returned another session's history." });
250 if (event.method === "session/modelChanged") {
251 if (
252 !event.params.modelId ||
253 (event.params.providerId !== undefined && event.params.providerId !== "meta")
254 )
255 return yield* new MuseImportError({ detail: "Muse model selection is unavailable." });
256 selectedModelId = event.params.modelId;
257 continue;
258 }
259 if (event.method === "session/tokenUsage") {
260 if (event.params.providerId !== undefined && event.params.providerId !== "meta")
261 return yield* new MuseImportError({ detail: "Muse model usage is unavailable." });
262 if (event.params.modelId) observedModelId = event.params.modelId;
263 continue;
264 }
265 if (!["item/started", "item/updated", "item/completed"].includes(event.method)) continue;
266 const item = event.params.item;
267 if (!item || (item.kind !== "userMessage" && item.kind !== "agentMessage")) continue;
268 const previous = items.get(item.itemId);
269 if (previous && previous.revision >= item.revision) continue;
270 historyBytes +=
271 Buffer.byteLength(item.text ?? "") +
272 Buffer.byteLength(item.displayText ?? "") -
273 Buffer.byteLength(previous?.text ?? "") -
274 Buffer.byteLength(previous?.displayText ?? "");
275 if (historyBytes > limits.historyBytes)
276 return yield* new MuseImportError({
277 detail: "Muse history exceeds the import text budget.",
278 });
279 items.set(item.itemId, item);
280 }
281 cursor = page.nextCursor;
282 if (cursor !== null && (page.events.length === 0 || cursors.has(cursor)))
283 return yield* new MuseImportError({ detail: "Muse history paging did not advance." });
284 if (cursor !== null) cursors.add(cursor);
285 } while (cursor !== null);
286 const messages = [...items.values()].flatMap((item) => {
287 if (item.retracted || item.status === "inProgress") return [];
288 const text = (
289 item.kind === "userMessage" ? (item.displayText ?? item.text) : item.text
290 )?.trim();
291 if (!text) return [];
292 return [
293 {
294 role: item.kind === "userMessage" ? ("user" as const) : ("assistant" as const),
295 text,
296 createdAt: item.recordedAt ?? read.session.createdAt,
297 },
298 ];
299 });
300 // A truncated native surface cannot be imported as if it were the complete reply.
301 if ([...items.values()].some((item) => item.truncated))
302 return yield* new MuseImportError({ detail: "Muse retained only a truncated message view." });
303 const firstUser = messages.find((message) => message.role === "user");
304 if (!firstUser)
305 return yield* new MuseImportError({ detail: "Muse history contains no user messages." });
306 // Muse 1.1.1 can save the base model in metadata for a Contributor session.
307 // Explicit selections outrank usage from an older turn finishing after a switch.
308 const modelId = selectedModelId ?? observedModelId;
309 if (!modelId)
310 return yield* new MuseImportError({
311 detail:
312 "Muse history does not identify its effective model. Complete a turn in Muse Code before importing.",
313 });
314 const recent = messages.slice(-limits.messages);
315 const retained = recent.includes(firstUser) ? recent : [firstUser, ...recent.slice(1)];
316 return {
317 session: { ...read.session, modelId },
318 messages: retained,
319 recordCount,
320 title: firstUser.text.split("\n")[0]?.slice(0, 100).trim() || "Imported thread",
321 };
322 });
323 return { list, read };
324});