@niwa-labs/harness-mcode 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,177 @@
1
+ /**
2
+ * The native format of a MiniMax Code journal: one JSON envelope per line,
3
+ * `{message_id, turn_id, message}`, and the parts of it the reading side maps. The working
4
+ * directory is not a field: it sits in the `<agent-context>` block prepended to the first human
5
+ * message, and that block is machine text, not the human's words. Nothing here touches the disk.
6
+ */
7
+
8
+ import { z } from "zod";
9
+
10
+ /** A block of content: text, a thought, or a call of a tool. */
11
+ const ContentBlockSchema = z.object({
12
+ type: z.string(),
13
+ text: z.string().optional(),
14
+ thinking: z.string().optional(),
15
+ /** A thought the harness keeps sealed: it carries no text. */
16
+ redacted: z.boolean().optional(),
17
+ id: z.string().optional(),
18
+ name: z.string().optional(),
19
+ arguments: z.unknown().optional(),
20
+ });
21
+
22
+ /** One native message. */
23
+ export const MessageSchema = z.object({
24
+ role: z.string(),
25
+ timestamp: z.number().optional(),
26
+ content: z.union([z.string(), z.array(ContentBlockSchema)]).optional(),
27
+ model: z.string().optional(),
28
+ toolCallId: z.string().optional(),
29
+ toolName: z.string().optional(),
30
+ isError: z.boolean().optional(),
31
+ summary: z.string().optional(),
32
+ });
33
+
34
+ /** The envelope of a journal record. */
35
+ const EnvelopeSchema = z.object({
36
+ message_id: z.string().optional(),
37
+ turn_id: z.string().optional(),
38
+ message: MessageSchema,
39
+ });
40
+
41
+ export type McodeRecord = z.output<typeof EnvelopeSchema>;
42
+ export type McodeMessage = z.output<typeof MessageSchema>;
43
+
44
+ /** The harness's own record whole, as `raw` gives it. */
45
+ export const RawRecordSchema = z.looseObject({
46
+ message_id: z.string().optional(),
47
+ turn_id: z.string().optional(),
48
+ message: MessageSchema,
49
+ });
50
+
51
+ /** The blocks of machine preamble: the harness's text, not the human's words. */
52
+ const NOISE_BLOCKS: readonly RegExp[] = [
53
+ /<system-reminder>[\s\S]*?<\/system-reminder>/g,
54
+ /<local-command-caveat>[\s\S]*?<\/local-command-caveat>/g,
55
+ /<agent-context>[\s\S]*?<\/agent-context>/g,
56
+ /<command-name>[\s\S]*?<\/command-name>/g,
57
+ /<command-message>[\s\S]*?<\/command-message>/g,
58
+ /<command-args>[\s\S]*?<\/command-args>/g,
59
+ /<command-contents>[\s\S]*?<\/command-contents>/g,
60
+ /<user-prompt-submit-hook>[\s\S]*?<\/user-prompt-submit-hook>/g,
61
+ ];
62
+
63
+ /** The real text of a human message: the machine preamble is cut out. */
64
+ export function stripHarnessNoise(text: string): string {
65
+ let out = text;
66
+ for (const block of NOISE_BLOCKS) out = out.replace(block, "");
67
+ out = out.replace(/^\s*Caveat: The messages below[\s\S]*?\n(?=\S)/, "");
68
+ return out.trim();
69
+ }
70
+
71
+ /** The text is wrapped in an XML wrapper — a harness's injection, not the human's words. */
72
+ export function isWrappedNoise(text: string): boolean {
73
+ const trimmed = text.trim();
74
+ return /^<[a-zA-Z][\w-]*(\s[^>]*)?>/.test(trimmed) && /<\/[a-zA-Z][\w-]*>\s*$/.test(trimmed);
75
+ }
76
+
77
+ /** What the preamble of a session says about the session itself. */
78
+ export type AgentContext = {
79
+ /** The role of the session in the run: "root", "branch", "worker". */
80
+ readonly sessionRole: string | null;
81
+ /** The id of this session, as the harness states it. */
82
+ readonly sessionId: string | null;
83
+ /** The id of the session this one was spawned in, when it was. */
84
+ readonly parentSessionId: string | null;
85
+ /** The working directory the session ran in. */
86
+ readonly workspaceDir: string | null;
87
+ };
88
+
89
+ /** Read the `agent-context` block out of the text of a message. */
90
+ export function readAgentContext(text: string): AgentContext {
91
+ const block = /<agent-context>([\s\S]*?)<\/agent-context>/.exec(text);
92
+ const body = block?.[1] ?? "";
93
+ const line = (key: string): string | null => {
94
+ const match = new RegExp(`^\\s*${key}:\\s*(.+)$`, "m").exec(body);
95
+ return match?.[1]?.trim() ?? null;
96
+ };
97
+ return {
98
+ sessionRole: line("SESSION ROLE"),
99
+ sessionId: line("YOUR SESSION ID"),
100
+ parentSessionId: line("PARENT SESSION"),
101
+ workspaceDir: line("YOUR WORKSPACE DIRECTORY") ?? line("workspaceDir"),
102
+ };
103
+ }
104
+
105
+ /** The text of a content: a string as it is, blocks by their text parts. */
106
+ export function textOf(content: McodeMessage["content"]): string {
107
+ if (content === undefined) return "";
108
+ if (typeof content === "string") return content;
109
+ return content
110
+ .map((block) => block.text ?? block.thinking ?? "")
111
+ .filter((part) => part.length > 0)
112
+ .join("\n");
113
+ }
114
+
115
+ /** Parse a line of the journal. `null` — the line is not a record of the journal. */
116
+ export function parseNativeRecord(value: unknown): McodeRecord | null {
117
+ const parsed = EnvelopeSchema.safeParse(value);
118
+ return parsed.success ? parsed.data : null;
119
+ }
120
+
121
+ /** Whole milliseconds, or `undefined` when the value is not a usable time. */
122
+ export function millisOf(timestamp: number | undefined): number | undefined {
123
+ if (timestamp === undefined || !Number.isFinite(timestamp)) return undefined;
124
+ const whole = Math.max(0, Math.floor(timestamp));
125
+ return Number.isSafeInteger(whole) ? whole : undefined;
126
+ }
127
+
128
+ /* ------------------------------------------------------------------ the ledger */
129
+
130
+ /** A call of a tool, as the display entries of the ledger carry it. */
131
+ const LedgerToolCallSchema = z.object({
132
+ tool_name: z.string().optional(),
133
+ tool_call_id: z.string().optional(),
134
+ tool_call_args: z.string().optional(),
135
+ });
136
+
137
+ /** The message of a display entry: what the user saw, in the fields of its own. */
138
+ export const LedgerDisplayMessageSchema = z.object({
139
+ msg_id: z.string().optional(),
140
+ role: z.string(),
141
+ msg_type: z.number().optional(),
142
+ msg_content: z.string().optional(),
143
+ timestamp: z.number().optional(),
144
+ thinking_content: z.string().optional(),
145
+ tool_calls: z.array(LedgerToolCallSchema).optional(),
146
+ });
147
+
148
+ export type LedgerDisplayMessage = z.output<typeof LedgerDisplayMessageSchema>;
149
+
150
+ /**
151
+ * One entry of the ledger: an event of the session, and the turns it carries.
152
+ *
153
+ * `message` is a display entry (what the user saw), `messages` is a piece of the history the agent
154
+ * was given, and `record` is what an event states about the session itself.
155
+ */
156
+ export const LedgerEntrySchema = z.looseObject({
157
+ kind: z.string(),
158
+ sessionId: z.string().optional(),
159
+ seq: z.number().optional(),
160
+ message: LedgerDisplayMessageSchema.optional(),
161
+ messages: z.array(MessageSchema).optional(),
162
+ record: z.looseObject({ workspaceDir: z.string().optional() }).optional(),
163
+ });
164
+
165
+ export type LedgerEntry = z.output<typeof LedgerEntrySchema>;
166
+
167
+ /** The manifest of a session: the source of truth for its id and its times. */
168
+ export const ManifestSchema = z.object({
169
+ schemaVersion: z.number().optional(),
170
+ sessionId: z.string().optional(),
171
+ createdAtMs: z.number().optional(),
172
+ updatedAtMs: z.number().optional(),
173
+ source: z.string().optional(),
174
+ layout: z.string().optional(),
175
+ });
176
+
177
+ export type Manifest = z.output<typeof ManifestSchema>;
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The MiniMax Code harness kind: the published `@minimax-ai/code`.
3
+ * The owner's fork of it is the kind `ncode` (`../ncode/index.ts`); the two share one
4
+ * reading side and one control side.
5
+ *
6
+ * It serves the reading side and the control side. The reading side reads the files MiniMax Code
7
+ * writes; the control side drives MiniMax Code over the Agent Client Protocol. It has no insert
8
+ * side.
9
+ */
10
+
11
+ import type { HarnessBinding, SideCapabilities } from "@niwa-labs/harness";
12
+
13
+ import { minimaxKind, minimaxSides } from "./kind.ts";
14
+ import type { McodeOptions, MinimaxKindSpec } from "./kind.ts";
15
+
16
+ export { McodeReading } from "./reading.ts";
17
+ export type { McodeReadingOptions } from "./reading.ts";
18
+ export { mcodeControl } from "./control.ts";
19
+ export type {
20
+ McodeControlOptions,
21
+ McodeSessionControl,
22
+ MinimaxLineage,
23
+ PermissionDecision,
24
+ PermissionPolicy,
25
+ PermissionRequest,
26
+ } from "./control.ts";
27
+ export type { McodeInstanceOptions, McodeOptions } from "./kind.ts";
28
+
29
+ /** The sides an upstream MiniMax Code instance has by default. */
30
+ export const mcodeSides: SideCapabilities = minimaxSides();
31
+
32
+ /**
33
+ * How the upstream installation is found: the launcher of the published build (`mcode`),
34
+ * and the directory it keeps its sessions in.
35
+ */
36
+ const MCODE_KIND: MinimaxKindSpec = {
37
+ name: "mcode",
38
+ lineage: "upstream",
39
+ detect: { binary: "mcode", home: "~/.minimax" },
40
+ };
41
+
42
+ /** The kind "mcode". */
43
+ export const mcodeKind = minimaxKind(MCODE_KIND);
44
+
45
+ /** One installation of the published build: `mcode` at the home of its profile (`~/.minimax`) unless the options say otherwise. */
46
+ export function mcode(options: McodeOptions = {}): HarnessBinding {
47
+ return mcodeKind.bind({ ...options, id: options.id ?? "mcode" });
48
+ }
49
+
50
+ export { mcodeSkills } from "./skills.ts";
@@ -0,0 +1,147 @@
1
+ /**
2
+ * What the two MiniMax Code kinds share: `mcode`, the published
3
+ * `@minimax-ai/code`, and `ncode`, the owner's fork of it. They read the same files and speak the
4
+ * same Agent Client Protocol; they differ in the program, the lineage the control side is set up
5
+ * for, and the name of the kind.
6
+ */
7
+
8
+ import { existsSync } from "node:fs";
9
+
10
+ import { ADMITTED, NO_INSERT, NoOptions, UNSUPPORTED, VERIFIED, defineHarnessKind, kindOptions } from "@niwa-labs/harness";
11
+ import type { HarnessDetection, InstanceOptions, KindCapabilities, SideCapabilities } from "@niwa-labs/harness";
12
+
13
+ import { DEFAULT_BINARIES, MCODE_LAUNCH, mcodeControl } from "./control.ts";
14
+ import type { McodeControlOptions, MinimaxLineage } from "./control.ts";
15
+ import { versionedPrograms } from "../ncode/launcher.ts";
16
+ import { durablePathOf } from "./durable.ts";
17
+ import { DEFAULT_PROFILE, homeOfProfile } from "./paths.ts";
18
+ import { McodeReading } from "./reading.ts";
19
+
20
+ /**
21
+ * The sides a MiniMax Code instance has by default.
22
+ *
23
+ * The reading side lists and reads the files MiniMax Code writes; it does not follow a session
24
+ * while it grows. The control side starts, resumes, sends, interrupts and asks; the agent is
25
+ * asked for JSON that matches the schema and the control side validates the answer: `ask` returns
26
+ * a value that passed the schema.
27
+ */
28
+ export function minimaxSides(): SideCapabilities {
29
+ return {
30
+ reading: { list: true, read: true, watch: false },
31
+ control: {
32
+ start: true,
33
+ resume: true,
34
+ send: true,
35
+ interrupt: true,
36
+ ask: true,
37
+ structuredOutput: true,
38
+ launch: MCODE_LAUNCH,
39
+ tools: { niwaOnly: false, allow: false },
40
+ },
41
+ };
42
+ }
43
+
44
+ /**
45
+ * What the two kinds declare they can serve. The upstream build is proved against a live
46
+ * MiniMax Code; of the fork, only a start with a permission answered is proved live, and the rest
47
+ * is taken from the code it shares with the upstream build.
48
+ */
49
+ export function minimaxCapabilities(lineage: MinimaxLineage): KindCapabilities {
50
+ const proved = lineage === "upstream" ? VERIFIED : ADMITTED;
51
+ return {
52
+ reading: { list: VERIFIED, read: VERIFIED, watch: UNSUPPORTED },
53
+ control: {
54
+ start: VERIFIED,
55
+ resume: proved,
56
+ send: proved,
57
+ interrupt: proved,
58
+ ask: proved,
59
+ structuredOutput: proved,
60
+ launch: { model: proved, effort: MCODE_LAUNCH.effort, modes: MCODE_LAUNCH.modes },
61
+ tools: { niwaOnly: UNSUPPORTED, allow: UNSUPPORTED },
62
+ },
63
+ insert: NO_INSERT,
64
+ };
65
+ }
66
+
67
+ /** What an installation of a MiniMax Code kind is given: its id, home and model, and how its control side is set up. */
68
+ export interface McodeInstanceOptions extends InstanceOptions {
69
+ /**
70
+ * The account profile the installation belongs to. The control side is started with it, and the
71
+ * home is derived from it (`default` is `~/.minimax`, any other `~/.minimax-<profile>`) when no
72
+ * home is given. Without a profile the control side is started with `--profile default` when the
73
+ * home holds a durable history (the fork of the harness, whose wrapper has a default profile of its
74
+ * own that could move sessions to another home), and without one otherwise. The published build
75
+ * takes no profile: naming one for `mcode` refuses its starts and resumes.
76
+ */
77
+ readonly profile?: string;
78
+ /**
79
+ * How the control side is set up: the account profile it drives and what it does with a permission
80
+ * request. Its own defaults are used when it is absent.
81
+ */
82
+ readonly control?: Omit<McodeControlOptions, "harness" | "lineage" | "home" | "model">;
83
+ }
84
+
85
+ /** What the caller names of one installation: every part has a default. */
86
+ export type McodeOptions = Partial<McodeInstanceOptions>;
87
+
88
+ /** One of the two kinds: its name, its lineage and how its installation is found. */
89
+ export interface MinimaxKindSpec {
90
+ readonly name: "mcode" | "ncode";
91
+ readonly lineage: MinimaxLineage;
92
+ readonly detect: HarnessDetection;
93
+ }
94
+
95
+ /** The profile an installation names, in its own options or its control side's. */
96
+ const profileNamed = (options: McodeInstanceOptions): string | undefined => options.profile ?? options.control?.profile;
97
+
98
+ /** The kind of `spec`. Each installation is bound to its own home, the home of its profile unless it names one. */
99
+ export function minimaxKind(spec: MinimaxKindSpec) {
100
+ return defineHarnessKind<McodeInstanceOptions>({
101
+ name: spec.name,
102
+ capabilities: minimaxCapabilities(spec.lineage),
103
+ implements: ["reading", "control"],
104
+ sides: minimaxSides(),
105
+ detect: spec.detect,
106
+ options: kindOptions(spec.name, NoOptions),
107
+ home: (options) => homeOfProfile(profileNamed(options)),
108
+ // Its program, the runtime the program runs on, and the home of its profile (sign-in, sessions,
109
+ // logs, configuration). Its model endpoint depends on the profile: the installation names it (`net`).
110
+ profile: {
111
+ status: spec.lineage === "fork" ? "verified" : "admitted",
112
+ of: (options) => (context) => {
113
+ const launcher = context.bin(options.control?.binary ?? DEFAULT_BINARIES[spec.lineage]);
114
+ const versioned = spec.lineage === "fork" && launcher[0] !== undefined
115
+ ? versionedPrograms(launcher[0], context)
116
+ : undefined;
117
+ return { read: [...launcher, ...(versioned ?? context.bin("node"))], write: [options.home] };
118
+ },
119
+ },
120
+ bind: (options) => ({
121
+ reading: new McodeReading({ harness: options.id, home: options.home, perSessionHistory: spec.lineage === "fork" }),
122
+ control: mcodeControl({
123
+ harness: options.id,
124
+ ...(options.control ?? {}),
125
+ ...(options.model === undefined ? {} : { model: options.model }),
126
+ home: options.home,
127
+ ...profileOf(options, spec.lineage),
128
+ lineage: spec.lineage,
129
+ }),
130
+ }),
131
+ });
132
+ }
133
+
134
+ /**
135
+ * The profile the control side is started with. A profile that is named is passed. Without one the
136
+ * fork of the harness (the one with a durable history in the home) is started with `--profile
137
+ * default`, so that the default profile of its wrapper cannot move sessions to another home; the
138
+ * upstream harness is started without one, whatever its home holds.
139
+ */
140
+ function profileOf(options: McodeInstanceOptions & { readonly home: string }, lineage: MinimaxLineage): { profile?: string } {
141
+ const named = profileNamed(options);
142
+ if (named !== undefined) return { profile: named };
143
+ // Upstream `mcode acp` has no --profile option (it exits with its usage text), and its home may hold a
144
+ // durable history too: only the fork's wrapper has a profile of its own to pin.
145
+ if (lineage !== "fork") return {};
146
+ return existsSync(durablePathOf(options.home)) ? { profile: DEFAULT_PROFILE } : {};
147
+ }
@@ -0,0 +1,199 @@
1
+ /**
2
+ * The ledger of a session: the history of a session that kept no journal of its own.
3
+ *
4
+ * A session directory holds a journal (`messages.jsonl`). When it holds none, the history of the
5
+ * session is in its ledger (`ledger.jsonl`): one entry per line, every entry an event of the
6
+ * session. Most entries are bookkeeping (`session.created`, `session.metadata_updated`,
7
+ * `session.snapshot_created`); two kinds carry turns:
8
+ *
9
+ * - `message.pi_history_appended` and `message.pi_history_replaced` carry the history the agent was
10
+ * given, in the shape the journal itself uses: a message with blocks of text, of thought and of
11
+ * calls of tools. A `replaced` entry states the whole history as it is now; an `appended` one
12
+ * adds to it.
13
+ * - `message.display_upserted` carries what the user saw, in fields of its own: the text of the
14
+ * message, the calls of tools it made, the time. It is put in the shape of a message of the
15
+ * journal here, so that a turn is read the same way whichever entry carried it.
16
+ *
17
+ * The same turn comes in both, so only one of them is read: the history when the ledger has it, the
18
+ * display when it does not. Nothing here touches the disk.
19
+ */
20
+
21
+ import { LedgerEntrySchema } from "./format.ts";
22
+ import type { LedgerDisplayMessage, McodeMessage } from "./format.ts";
23
+
24
+ /** One line of the ledger, with where it is and whether it is whole. */
25
+ export interface LedgerLine {
26
+ /** The offset of the start of the line. */
27
+ readonly byte: number;
28
+ /** The bytes of the line, without its line feed. */
29
+ readonly bytes: Buffer;
30
+ /** The line has no line feed yet: it is the half-written tail of the file. */
31
+ readonly complete: boolean;
32
+ }
33
+
34
+ /** A turn of the conversation, as the ledger carries it. */
35
+ export interface LedgerTurn {
36
+ /** The message of the turn, in the shape a message of the journal has; `null` when the line is not JSON. */
37
+ readonly message: McodeMessage | null;
38
+ /** The entry of the ledger as the harness wrote it: what `raw` gives back. */
39
+ readonly raw: unknown;
40
+ /** The line of the ledger that carried the turn. */
41
+ readonly line: LedgerLine;
42
+ /** The place of the turn in that line. */
43
+ readonly index: number;
44
+ }
45
+
46
+ /** What a ledger holds. */
47
+ export interface LedgerContent {
48
+ /** The turns of the conversation, in the order they happened. */
49
+ readonly turns: readonly LedgerTurn[];
50
+ /** The head of the ledger: the bytes the revision of a locator hashes. */
51
+ readonly head: Buffer;
52
+ /** How many bytes the ledger has. */
53
+ readonly size: number;
54
+ /** The working directory the session states, when it states one. */
55
+ readonly workspaceDir: string | undefined;
56
+ }
57
+
58
+ /** Bytes of the head of the ledger the revision of a locator hashes. */
59
+ const HEAD_BYTES = 4096;
60
+
61
+ /** The ledger of a session, as the bytes of its file. */
62
+ export function parseLedger(bytes: Buffer): LedgerContent {
63
+ const history: LedgerTurn[] = [];
64
+ const broken: LedgerTurn[] = [];
65
+ const display = new Map<string, LedgerTurn>();
66
+ const displayOrder: string[] = [];
67
+ let workspaceDir: string | undefined;
68
+ let sawHistory = false;
69
+
70
+ for (const line of splitLines(bytes)) {
71
+ if (line.bytes.length === 0) continue;
72
+ const text = line.bytes.toString("utf8");
73
+ if (text.trim().length === 0) continue;
74
+
75
+ let parsed: unknown;
76
+ try {
77
+ parsed = JSON.parse(text);
78
+ } catch {
79
+ // A line that is not JSON is kept whole: it is not an error, and it is not a turn either.
80
+ broken.push({ message: null, raw: text, line, index: 0 });
81
+ continue;
82
+ }
83
+ const entry = LedgerEntrySchema.safeParse(parsed);
84
+ if (!entry.success) continue;
85
+ const event = entry.data;
86
+
87
+ // The session states what it is: the working directory it runs in.
88
+ const stated = event.record?.workspaceDir;
89
+ if (stated !== undefined && stated.length > 0) workspaceDir = stated;
90
+
91
+ if (event.kind === "message.pi_history_replaced") {
92
+ // The history as it is now: what came before it is no longer part of it.
93
+ history.length = 0;
94
+ sawHistory = true;
95
+ pushMessages(history, event.messages ?? [], line, parsed);
96
+ continue;
97
+ }
98
+ if (event.kind === "message.pi_history_appended") {
99
+ sawHistory = true;
100
+ pushMessages(history, event.messages ?? [], line, parsed);
101
+ continue;
102
+ }
103
+ if (event.kind === "message.display_upserted" && event.message !== undefined) {
104
+ const turn = displayTurn(event.message, line, parsed);
105
+ const key = event.message.msg_id;
106
+ if (key !== undefined) {
107
+ display.set(key, turn);
108
+ if (!displayOrder.includes(key)) displayOrder.push(key);
109
+ } else {
110
+ const anon = displayOrder.length.toString();
111
+ displayOrder.push(anon);
112
+ display.set(anon, turn);
113
+ }
114
+ }
115
+ }
116
+
117
+ const shown = sawHistory ? history : displayOrder.flatMap((key) => display.get(key) ?? []);
118
+ // A line that is not JSON stays where it was: it is read in the order of the file.
119
+ const turns = [...shown, ...broken].sort((a, b) => a.line.byte - b.line.byte);
120
+ return { turns, head: bytes.subarray(0, HEAD_BYTES), size: bytes.length, workspaceDir };
121
+ }
122
+
123
+ /** The turns of one entry: the messages it carries, in the order it carries them. */
124
+ function pushMessages(
125
+ turns: LedgerTurn[],
126
+ messages: readonly McodeMessage[],
127
+ line: LedgerLine,
128
+ raw: unknown,
129
+ ): void {
130
+ for (const [index, message] of messages.entries()) {
131
+ turns.push({ message, raw, line, index });
132
+ }
133
+ }
134
+
135
+ /** A display entry, put in the shape a message of the journal has. */
136
+ function displayTurn(message: LedgerDisplayMessage, line: LedgerLine, raw: unknown): LedgerTurn {
137
+ return { message: displayToMessage(message), raw, line, index: 0 };
138
+ }
139
+
140
+ /** The message of a display entry, as a message of the journal reads it. */
141
+ function displayToMessage(message: LedgerDisplayMessage): McodeMessage {
142
+ const at = message.timestamp === undefined ? {} : { timestamp: message.timestamp };
143
+ if (message.role === "user") {
144
+ return { role: "user", content: message.msg_content ?? "", ...at };
145
+ }
146
+ if (message.role !== "assistant") {
147
+ return { role: message.role, ...at };
148
+ }
149
+ const blocks: {
150
+ type: string;
151
+ text?: string;
152
+ thinking?: string;
153
+ id?: string;
154
+ name?: string;
155
+ arguments?: unknown;
156
+ }[] = [];
157
+ if (message.thinking_content !== undefined && message.thinking_content.length > 0) {
158
+ blocks.push({ type: "thinking", thinking: message.thinking_content });
159
+ }
160
+ if (message.msg_content !== undefined && message.msg_content.length > 0) {
161
+ blocks.push({ type: "text", text: message.msg_content });
162
+ }
163
+ for (const call of message.tool_calls ?? []) {
164
+ if (call.tool_call_id === undefined || call.tool_name === undefined) continue;
165
+ const args = call.tool_call_args === undefined ? undefined : parseArgs(call.tool_call_args);
166
+ blocks.push({
167
+ type: "toolCall",
168
+ id: call.tool_call_id,
169
+ name: call.tool_name,
170
+ ...(args === undefined ? {} : { arguments: args }),
171
+ });
172
+ }
173
+ return { role: "assistant", content: blocks, ...at };
174
+ }
175
+
176
+ /** The arguments of a call: JSON as a string, or the string itself when it is not JSON. */
177
+ function parseArgs(text: string): unknown {
178
+ try {
179
+ return JSON.parse(text) as unknown;
180
+ } catch {
181
+ return text;
182
+ }
183
+ }
184
+
185
+ /** The lines of the ledger, with the tail marked when it is not whole. */
186
+ function splitLines(bytes: Buffer): LedgerLine[] {
187
+ const lines: LedgerLine[] = [];
188
+ let start = 0;
189
+ for (;;) {
190
+ const lf = bytes.indexOf(0x0a, start);
191
+ if (lf < 0) break;
192
+ lines.push({ byte: start, bytes: bytes.subarray(start, lf), complete: true });
193
+ start = lf + 1;
194
+ }
195
+ if (start < bytes.length) {
196
+ lines.push({ byte: start, bytes: bytes.subarray(start), complete: false });
197
+ }
198
+ return lines;
199
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Where the sessions of a MiniMax Code installation live:
3
+ * `<home>/v2/sessions/YYYY/MM/DD/hh-mm-ss-mmm-session_<base64url(id)>/{messages.jsonl,manifest.json}`.
4
+ * The directory name carries the encoded id (cut to 180 characters), the manifest is authoritative.
5
+ */
6
+
7
+ import { readdir } from "node:fs/promises";
8
+ import { homedir } from "node:os";
9
+ import { join } from "node:path";
10
+
11
+ export const LOG_NAME = "messages.jsonl";
12
+ export const MANIFEST_NAME = "manifest.json";
13
+ /** The ledger of a session: the history of the sessions that kept no journal of their own. */
14
+ export const LEDGER_NAME = "ledger.jsonl";
15
+
16
+ const SESSION_DIR = /^\d{2}-\d{2}-\d{2}-\d{3}-session_[A-Za-z0-9_-]+$/;
17
+
18
+ /** Is this directory name the directory of a session? */
19
+ export function isSessionDir(name: string): boolean {
20
+ return SESSION_DIR.test(name);
21
+ }
22
+
23
+ /** The journal and the manifest of a session directory. */
24
+ export function logPathOf(dir: string): string {
25
+ return join(dir, LOG_NAME);
26
+ }
27
+
28
+ export function manifestPathOf(dir: string): string {
29
+ return join(dir, MANIFEST_NAME);
30
+ }
31
+
32
+ /** The ledger of a session directory. */
33
+ export function ledgerPathOf(dir: string): string {
34
+ return join(dir, LEDGER_NAME);
35
+ }
36
+
37
+ /** The id as the directory name carries it: base64url, no padding. */
38
+ export function encodeNativeId(id: string): string {
39
+ return Buffer.from(id, "utf8").toString("base64url");
40
+ }
41
+
42
+ /** The id a directory name carries; `null` when the name is not by the rules. */
43
+ export function nativeIdFromDirName(dirName: string): string | null {
44
+ const payload = /^(?:\d{2}-\d{2}-\d{2}-\d{3}-)?session_(.+)$/.exec(dirName)?.[1];
45
+ if (payload === undefined) return null;
46
+ const decoded = Buffer.from(payload, "base64url").toString("utf8");
47
+ return /^[A-Za-z0-9_-]+$/.test(decoded) ? decoded : null;
48
+ }
49
+
50
+ /** Does the directory name carry this encoded id? */
51
+ export function dirNameHoldsId(dirName: string, encodedId: string): boolean {
52
+ return dirName.endsWith(`session_${encodedId}`);
53
+ }
54
+
55
+ /** The subdirectories of a path, newest name first; a missing path has none. */
56
+ export async function subdirsOf(path: string, pattern?: RegExp): Promise<string[]> {
57
+ try {
58
+ const entries = await readdir(path, { withFileTypes: true });
59
+ return entries
60
+ .filter((e) => e.isDirectory() && (pattern === undefined || pattern.test(e.name)))
61
+ .map((e) => e.name)
62
+ .sort()
63
+ .reverse();
64
+ } catch {
65
+ return [];
66
+ }
67
+ }
68
+
69
+ /** The profile the installation at `~/.minimax` belongs to. */
70
+ export const DEFAULT_PROFILE = "default";
71
+
72
+ /** The name of the home directory (under the user's home) of a profile; no profile is the default one. */
73
+ export function homeNameOfProfile(profile: string | undefined): string {
74
+ return profile === undefined || profile === DEFAULT_PROFILE ? ".minimax" : `.minimax-${profile}`;
75
+ }
76
+
77
+ /** The home of the installation a profile belongs to, under `base` (the user's home by default). */
78
+ export function homeOfProfile(profile: string | undefined, base: string = homedir()): string {
79
+ return join(base, homeNameOfProfile(profile));
80
+ }