@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.
- package/LICENSE +21 -0
- package/README.md +2 -2
- package/package.json +17 -4
- package/src/index.ts +13 -0
- package/src/mcode/control.ts +1840 -0
- package/src/mcode/durable.ts +445 -0
- package/src/mcode/fixtures.ts +93 -0
- package/src/mcode/format.ts +177 -0
- package/src/mcode/index.ts +50 -0
- package/src/mcode/kind.ts +147 -0
- package/src/mcode/ledger.ts +199 -0
- package/src/mcode/paths.ts +80 -0
- package/src/mcode/protocol.ts +91 -0
- package/src/mcode/reading.ts +1153 -0
- package/src/mcode/reverse.ts +201 -0
- package/src/mcode/skills.ts +6 -0
- package/src/mcode/titles.ts +51 -0
- package/src/mcode/tools.ts +56 -0
- package/src/mcode/transport.ts +31 -0
- package/src/ncode/index.ts +34 -0
- package/src/ncode/launcher.ts +33 -0
- package/src/ncode/protocol.ts +146 -0
- package/src/ncode/skills.ts +6 -0
- package/test/live/ncode-permission.test.ts +82 -0
- package/test/mcode-conformance.test.ts +52 -0
- package/test/mcode-control.test.ts +1616 -0
- package/test/mcode-durable.test.ts +722 -0
- package/test/mcode-ledger.test.ts +357 -0
- package/test/mcode-reading.test.ts +286 -0
- package/test/mcode-transport.test.ts +48 -0
- package/test/profile.test.ts +89 -0
- package/tsconfig.json +6 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What MiniMax Code asks of its client in the middle of a turn, as niwa's common questions
|
|
3
|
+
* ("reverse requests"). Pure mapping: the wiring (who is asked, when
|
|
4
|
+
* the wait is over, what is written back) is the control side's.
|
|
5
|
+
*
|
|
6
|
+
* MiniMax Code asks in two ways, both read from its own ACP layer:
|
|
7
|
+
*
|
|
8
|
+
* - `session/request_permission`, for a tool. The fork may offer lasting options too (`allow_always`,
|
|
9
|
+
* `reject_always`); only the once-only ones are ever offered or picked.
|
|
10
|
+
* - a questionnaire for a person. A client that declares `elicitation.form` gets `elicitation/create`
|
|
11
|
+
* with a form (one property per step); one that does not gets the first step, when it is a
|
|
12
|
+
* single choice with no other, as a `session/request_permission` whose option ids start with
|
|
13
|
+
* `questionnaire:<id>:`. That request is a question, not a permission.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { z } from "zod";
|
|
17
|
+
|
|
18
|
+
import type { Answer, Question, QuestionOption } from "@niwa-labs/core";
|
|
19
|
+
import { OptionIdSchema, pickedOptions, stableJson } from "@niwa-labs/core";
|
|
20
|
+
|
|
21
|
+
/** What an answer to `session/request_permission` is, in the agent's words. */
|
|
22
|
+
export type PermissionOutcome =
|
|
23
|
+
| { readonly outcome: "selected"; readonly optionId: string }
|
|
24
|
+
| { readonly outcome: "cancelled" };
|
|
25
|
+
|
|
26
|
+
/** A permission request, as a question, and how an answer to it goes back. */
|
|
27
|
+
export interface PermissionAsk {
|
|
28
|
+
readonly question: Question;
|
|
29
|
+
readonly outcomeOf: (answer: Answer) => PermissionOutcome;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** How much of a tool's input a question shows as its detail. */
|
|
33
|
+
const DETAIL_CHARS = 500;
|
|
34
|
+
|
|
35
|
+
/** The prefix of the option ids of a questionnaire that arrives as a permission request. */
|
|
36
|
+
const QUESTIONNAIRE_PREFIX = "questionnaire:";
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* What a permission question holds when the agent offered nothing it could be answered with: the
|
|
40
|
+
* only answer there is. It is never picked; the request ends as cancelled.
|
|
41
|
+
*/
|
|
42
|
+
const REJECT_ONLY: QuestionOption = { id: OptionIdSchema.parse("cancel"), label: "Cancel", flavor: "reject_once" };
|
|
43
|
+
|
|
44
|
+
const CANCELLED: PermissionOutcome = { outcome: "cancelled" };
|
|
45
|
+
|
|
46
|
+
const OfferedSchema = z.object({ optionId: z.string().min(1), name: z.string().optional(), kind: z.string().optional() });
|
|
47
|
+
|
|
48
|
+
const ToolCallSchema = z.object({
|
|
49
|
+
toolCallId: z.string().optional(),
|
|
50
|
+
title: z.string().optional(),
|
|
51
|
+
name: z.string().min(1).optional(),
|
|
52
|
+
kind: z.string().min(1).optional(),
|
|
53
|
+
rawInput: z.unknown().optional(),
|
|
54
|
+
locations: z.array(z.object({ path: z.string() })).optional(),
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
const PermissionParamsSchema = z.object({
|
|
58
|
+
toolCall: ToolCallSchema.catch({}).default({}),
|
|
59
|
+
options: z.array(z.unknown()).default([]),
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
/** The pieces of a `session/request_permission` request, and the prefix of its options when it is a questionnaire. */
|
|
63
|
+
function permissionParts(params: unknown) {
|
|
64
|
+
const parsed = PermissionParamsSchema.safeParse(params);
|
|
65
|
+
const { toolCall, options } = parsed.success ? parsed.data : { toolCall: {}, options: [] };
|
|
66
|
+
const offered = options.flatMap((entry) => {
|
|
67
|
+
const option = OfferedSchema.safeParse(entry);
|
|
68
|
+
return option.success ? [option.data] : [];
|
|
69
|
+
});
|
|
70
|
+
const prefix = toolCall.toolCallId === undefined ? undefined : `${QUESTIONNAIRE_PREFIX}${toolCall.toolCallId}:`;
|
|
71
|
+
const questionnaire = prefix !== undefined && offered.length > 0 && offered.every((option) => option.optionId.startsWith(prefix));
|
|
72
|
+
return { toolCall, offered, prefix, questionnaire };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Whether a `session/request_permission` request is a question for a person, not a permission: the
|
|
77
|
+
* answers of a questionnaire are offered as once-only options, and no policy may pick one of them.
|
|
78
|
+
*/
|
|
79
|
+
export function isQuestionnaire(params: unknown): boolean {
|
|
80
|
+
return permissionParts(params).questionnaire;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The question of a `session/request_permission` request, and how its answer goes back. */
|
|
84
|
+
export function permissionAsk(params: unknown): PermissionAsk {
|
|
85
|
+
const { toolCall, offered, prefix, questionnaire } = permissionParts(params);
|
|
86
|
+
if (questionnaire && prefix !== undefined) return questionnaireAsk(toolCall.title, offered, prefix);
|
|
87
|
+
|
|
88
|
+
const title = toolCall.title ?? toolCall.name ?? "a tool";
|
|
89
|
+
const once: QuestionOption[] = offered.flatMap((option) =>
|
|
90
|
+
option.kind === "allow_once" || option.kind === "reject_once"
|
|
91
|
+
? [{ id: OptionIdSchema.parse(option.optionId), label: option.name ?? option.kind, flavor: option.kind }]
|
|
92
|
+
: [],
|
|
93
|
+
);
|
|
94
|
+
const paths = toolCall.locations?.map((location) => location.path) ?? [];
|
|
95
|
+
const question: Question = {
|
|
96
|
+
kind: "permission",
|
|
97
|
+
title,
|
|
98
|
+
...(toolCall.rawInput === undefined ? {} : { detail: stableJson(toolCall.rawInput).slice(0, DETAIL_CHARS) }),
|
|
99
|
+
options: once.length === 0 ? [REJECT_ONLY] : once,
|
|
100
|
+
subject: {
|
|
101
|
+
...(toolCall.name === undefined ? {} : { tool: toolCall.name }),
|
|
102
|
+
kind: toolCall.kind ?? "other",
|
|
103
|
+
target: paths.length > 0 ? paths.join("\n") : toolCall.rawInput === undefined ? title : stableJson(toolCall.rawInput),
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
return { question, outcomeOf: (answer) => selectedOf(question, answer, once) };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The single-choice questionnaire that arrives as a permission request: the options are the answers, the cancel is the refusal. */
|
|
110
|
+
function questionnaireAsk(
|
|
111
|
+
title: string | undefined,
|
|
112
|
+
offered: ReadonlyArray<z.output<typeof OfferedSchema>>,
|
|
113
|
+
prefix: string,
|
|
114
|
+
): PermissionAsk {
|
|
115
|
+
const choices: QuestionOption[] = offered.flatMap((option) =>
|
|
116
|
+
option.optionId === `${prefix}cancel`
|
|
117
|
+
? []
|
|
118
|
+
: [{ id: OptionIdSchema.parse(option.optionId), label: option.name ?? option.optionId.slice(prefix.length), flavor: "plain" }],
|
|
119
|
+
);
|
|
120
|
+
if (choices.length === 0) {
|
|
121
|
+
const question: Question = { kind: "choice", title: title ?? "MiniMax Code needs your input", options: [REJECT_ONLY], allowOther: false };
|
|
122
|
+
return { question, outcomeOf: () => CANCELLED };
|
|
123
|
+
}
|
|
124
|
+
const question: Question = { kind: "choice", title: title ?? "MiniMax Code needs your input", options: choices, allowOther: false };
|
|
125
|
+
return { question, outcomeOf: (answer) => selectedOf(question, answer, choices) };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** The option an answer picked, when it is one of `allowed`: anything else, a cancel included, cancels. */
|
|
129
|
+
function selectedOf(question: Question, answer: Answer, allowed: readonly QuestionOption[]): PermissionOutcome {
|
|
130
|
+
const picked = pickedOptions(question, answer)[0];
|
|
131
|
+
if (picked === undefined || !allowed.some((option) => option.id === picked.id)) return CANCELLED;
|
|
132
|
+
return { outcome: "selected", optionId: picked.id };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// -- a form -------------------------------------------------------------------------------------
|
|
136
|
+
|
|
137
|
+
const ChoiceSchema = z.object({ const: z.string().min(1), title: z.string().optional(), description: z.string().optional() });
|
|
138
|
+
|
|
139
|
+
const PropertySchema = z.union([
|
|
140
|
+
z.object({ type: z.literal("array"), title: z.string().optional(), description: z.string().optional(), items: z.object({ anyOf: z.array(ChoiceSchema).min(1) }) }),
|
|
141
|
+
z.object({ type: z.literal("string"), title: z.string().optional(), description: z.string().optional(), oneOf: z.array(ChoiceSchema).min(1) }),
|
|
142
|
+
z.object({ type: z.literal("string"), title: z.string().optional(), description: z.string().optional() }),
|
|
143
|
+
]);
|
|
144
|
+
|
|
145
|
+
const FormSchema = z.object({
|
|
146
|
+
message: z.string().optional(),
|
|
147
|
+
requestedSchema: z.object({ properties: z.record(z.string(), z.unknown()) }),
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
/** One step of a form: its question and the field it is answered in. */
|
|
151
|
+
export interface FormStep {
|
|
152
|
+
readonly key: string;
|
|
153
|
+
/** The field the words go in when the person answers with their own, when the form has one. */
|
|
154
|
+
readonly otherKey: string | undefined;
|
|
155
|
+
readonly question: Question;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** The steps of an `elicitation/create` form, in order; `undefined` when the form is not one niwa can ask. */
|
|
159
|
+
export function formSteps(params: unknown): FormStep[] | undefined {
|
|
160
|
+
const parsed = FormSchema.safeParse(params);
|
|
161
|
+
if (!parsed.success) return undefined;
|
|
162
|
+
const properties = Object.entries(parsed.data.requestedSchema.properties);
|
|
163
|
+
const keys = new Set(properties.map(([key]) => key));
|
|
164
|
+
const otherOf = (key: string): string | undefined => (keys.has(`${key}__other`) ? `${key}__other` : undefined);
|
|
165
|
+
const owned = new Set(properties.flatMap(([key]) => otherOf(key) ?? []));
|
|
166
|
+
|
|
167
|
+
const steps: FormStep[] = [];
|
|
168
|
+
for (const [key, value] of properties) {
|
|
169
|
+
if (owned.has(key)) continue;
|
|
170
|
+
const property = PropertySchema.safeParse(value);
|
|
171
|
+
if (!property.success) return undefined;
|
|
172
|
+
const shape = property.data;
|
|
173
|
+
const title = shape.title ?? key;
|
|
174
|
+
const detail = [parsed.data.message, shape.description].filter((part): part is string => part !== undefined && part !== "").join("\n");
|
|
175
|
+
const wording = { title, ...(detail === "" ? {} : { detail }) };
|
|
176
|
+
const otherKey = otherOf(key);
|
|
177
|
+
if ("items" in shape || "oneOf" in shape) {
|
|
178
|
+
const choices = "items" in shape ? shape.items.anyOf : shape.oneOf;
|
|
179
|
+
const options: QuestionOption[] = choices.map((choice) => ({
|
|
180
|
+
id: OptionIdSchema.parse(choice.const),
|
|
181
|
+
label: choice.title ?? choice.const,
|
|
182
|
+
...(choice.description === undefined ? {} : { description: choice.description }),
|
|
183
|
+
flavor: "plain",
|
|
184
|
+
}));
|
|
185
|
+
steps.push({ key, otherKey, question: { kind: "items" in shape ? "multi" : "choice", ...wording, options, allowOther: otherKey !== undefined } });
|
|
186
|
+
} else {
|
|
187
|
+
steps.push({ key, otherKey: undefined, question: { kind: "text", ...wording } });
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return steps.length === 0 ? undefined : steps;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** The fields of the form an answer to one step fills; `undefined` when the step was left without an answer. */
|
|
194
|
+
export function formFields(step: FormStep, answer: Answer): Record<string, string | string[]> | undefined {
|
|
195
|
+
if ("text" in answer) return { [step.otherKey ?? step.key]: answer.text };
|
|
196
|
+
if (!("ids" in answer)) return undefined;
|
|
197
|
+
const ids = pickedOptions(step.question, answer).map((option) => String(option.id));
|
|
198
|
+
if (step.question.kind === "multi") return { [step.key]: ids };
|
|
199
|
+
const [first] = ids;
|
|
200
|
+
return first === undefined ? {} : { [step.key]: first };
|
|
201
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Where MiniMax Code reads skills from: the root shared by the agents that read `.agents/skills`. */
|
|
2
|
+
|
|
3
|
+
import { SHARED_AGENTS_SKILLS } from "@niwa-labs/harness";
|
|
4
|
+
import type { KindSkills } from "@niwa-labs/harness";
|
|
5
|
+
|
|
6
|
+
export const mcodeSkills: KindSkills = { kind: "mcode", roots: SHARED_AGENTS_SKILLS };
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The titles MiniMax Code gives its sessions: `<home>/v2/sqlite/runtime-state.sqlite`, table
|
|
3
|
+
* `local_runtime_sessions`, columns `session_id` and `title`. The harness writes the title itself
|
|
4
|
+
* (a short summary of what the session is about).
|
|
5
|
+
*
|
|
6
|
+
* The database is the harness's own runtime state: it is opened read-only, and one that is not
|
|
7
|
+
* there, cannot be read or has no such table gives no titles. A title is a nicety, so nothing is
|
|
8
|
+
* told when it is missing.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { existsSync } from "node:fs";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
|
|
14
|
+
import { Database } from "bun:sqlite";
|
|
15
|
+
|
|
16
|
+
/** The runtime state of an installation, beside its sessions. */
|
|
17
|
+
export function runtimeStatePathOf(home: string): string {
|
|
18
|
+
return join(home, "v2", "sqlite", "runtime-state.sqlite");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** How many ids a query names at most; more than that reads the whole table. */
|
|
22
|
+
const MAX_NAMED = 500;
|
|
23
|
+
|
|
24
|
+
/** The titles of the sessions, by native id; of only `natives` when they are given. */
|
|
25
|
+
export function sessionTitles(path: string, natives?: readonly string[]): Map<string, string> {
|
|
26
|
+
const titles = new Map<string, string>();
|
|
27
|
+
if (!existsSync(path)) return titles;
|
|
28
|
+
let db: Database | undefined;
|
|
29
|
+
try {
|
|
30
|
+
db = new Database(path, { readonly: true });
|
|
31
|
+
db.run("pragma busy_timeout = 250");
|
|
32
|
+
const named = natives !== undefined && natives.length > 0 && natives.length <= MAX_NAMED;
|
|
33
|
+
const rows = db
|
|
34
|
+
.query(
|
|
35
|
+
`select session_id as id, title from local_runtime_sessions where title is not null${
|
|
36
|
+
named ? ` and session_id in (${natives.map(() => "?").join(", ")})` : ""
|
|
37
|
+
}`,
|
|
38
|
+
)
|
|
39
|
+
.all(...(named ? natives : [])) as { id: unknown; title: unknown }[];
|
|
40
|
+
for (const row of rows) {
|
|
41
|
+
if (typeof row.id !== "string" || typeof row.title !== "string") continue;
|
|
42
|
+
const title = row.title.replace(/\s+/g, " ").trim();
|
|
43
|
+
if (title.length > 0) titles.set(row.id, title);
|
|
44
|
+
}
|
|
45
|
+
} catch {
|
|
46
|
+
// The state cannot be read, or it holds no such table: the sessions are listed without it.
|
|
47
|
+
} finally {
|
|
48
|
+
db?.close();
|
|
49
|
+
}
|
|
50
|
+
return titles;
|
|
51
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** MiniMax Code's own tools, as the common model describes them. */
|
|
2
|
+
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
|
|
5
|
+
import { shapeOf } from "@niwa-labs/harness";
|
|
6
|
+
import type { Checklist, ChecklistState, ToolShape, ToolTable } from "@niwa-labs/harness";
|
|
7
|
+
|
|
8
|
+
/** The built-in tools of MiniMax Code (`agent-core` `builtin-defs`). */
|
|
9
|
+
export const MCODE_TOOLS: ToolTable = {
|
|
10
|
+
bash: { category: "shell", target: ["command"] },
|
|
11
|
+
read: { category: "read", target: ["path"] },
|
|
12
|
+
write: { category: "edit", target: ["path"] },
|
|
13
|
+
edit: { category: "edit", target: ["path"] },
|
|
14
|
+
grep: { category: "search", target: ["pattern"] },
|
|
15
|
+
glob: { category: "search", target: ["pattern"] },
|
|
16
|
+
todowrite: { category: "plan" },
|
|
17
|
+
task: { category: "subagent", target: ["description"] },
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/** A call of a MiniMax Code tool, in the common model's words. */
|
|
21
|
+
export function mcodeToolShape(name: string, input: unknown): ToolShape {
|
|
22
|
+
return shapeOf(MCODE_TOOLS, name, input);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The input of MiniMax Code's `todowrite`. Its states are strings (`pending`, `in_progress`,
|
|
27
|
+
* `completed`, `cancelled`), as in the tool it copies.
|
|
28
|
+
*/
|
|
29
|
+
const TodoWriteInput = z.object({
|
|
30
|
+
todos: z.array(z.object({ content: z.string(), status: z.string() })),
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
const TODO_STATES: Readonly<Record<string, ChecklistState | null>> = {
|
|
34
|
+
pending: "pending",
|
|
35
|
+
in_progress: "active",
|
|
36
|
+
completed: "done",
|
|
37
|
+
// A cancelled item is no longer part of the work.
|
|
38
|
+
cancelled: null,
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The checklist a call leaves, when it is a `todowrite` the common model can read: an item in a
|
|
43
|
+
* state it does not know makes the whole list unreadable, never a guess.
|
|
44
|
+
*/
|
|
45
|
+
export function mcodeChecklist(name: string, input: unknown): Checklist | undefined {
|
|
46
|
+
if (name !== "todowrite") return undefined;
|
|
47
|
+
const parsed = TodoWriteInput.safeParse(input);
|
|
48
|
+
if (!parsed.success) return undefined;
|
|
49
|
+
const items: Checklist["items"] = [];
|
|
50
|
+
for (const todo of parsed.data.todos) {
|
|
51
|
+
const state = Object.hasOwn(TODO_STATES, todo.status) ? TODO_STATES[todo.status] : undefined;
|
|
52
|
+
if (state === undefined) return undefined;
|
|
53
|
+
if (state !== null) items.push({ text: todo.content, state });
|
|
54
|
+
}
|
|
55
|
+
return { items };
|
|
56
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The input of an agent process: where the lines of the protocol are written.
|
|
3
|
+
*
|
|
4
|
+
* A line written to a child that is gone is not an error for the stream until its callback says so,
|
|
5
|
+
* and a closed stream can be told in advance. Both are reported here, so that a message that did not
|
|
6
|
+
* go out is never taken for one that did.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { Writable } from "node:stream";
|
|
10
|
+
|
|
11
|
+
/** Whether the input can still take a line. */
|
|
12
|
+
export function inputOpen(input: Writable | undefined): input is Writable {
|
|
13
|
+
return input !== undefined && input.writable && !input.destroyed;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Write one line, ending it with a line feed. Throws at once when the input is closed or the stream
|
|
18
|
+
* refuses the write; otherwise the promise settles when the stream has taken the line, or rejects
|
|
19
|
+
* with the failure it reported for it.
|
|
20
|
+
*/
|
|
21
|
+
export function writeLine(input: Writable | undefined, line: string): Promise<void> {
|
|
22
|
+
if (!inputOpen(input)) throw new Error("the agent's input is closed");
|
|
23
|
+
let accepted!: () => void;
|
|
24
|
+
let failed!: (error: Error) => void;
|
|
25
|
+
const done = new Promise<void>((resolve, reject) => {
|
|
26
|
+
accepted = resolve;
|
|
27
|
+
failed = reject;
|
|
28
|
+
});
|
|
29
|
+
input.write(`${line}\n`, (error) => (error === null || error === undefined ? accepted() : failed(error)));
|
|
30
|
+
return done;
|
|
31
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `ncode` harness kind: the owner's fork of MiniMax Code.
|
|
3
|
+
*
|
|
4
|
+
* It reads the files and speaks the protocol of `mcode` and shares its code. It differs in the
|
|
5
|
+
* program (`ncode`, the launcher of the fork), in taking the working mode in `session/new` too,
|
|
6
|
+
* and in marking tool calls with the permission decision, which its control side reports in the
|
|
7
|
+
* signs of life.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { HarnessBinding, SideCapabilities } from "@niwa-labs/harness";
|
|
11
|
+
import { minimaxKind, minimaxSides } from "../mcode/kind.ts";
|
|
12
|
+
import type { McodeOptions, MinimaxKindSpec } from "../mcode/kind.ts";
|
|
13
|
+
|
|
14
|
+
export type { McodeInstanceOptions as NcodeInstanceOptions, McodeOptions as NcodeOptions } from "../mcode/kind.ts";
|
|
15
|
+
|
|
16
|
+
/** The sides a fork instance has by default. */
|
|
17
|
+
export const ncodeSides: SideCapabilities = minimaxSides();
|
|
18
|
+
|
|
19
|
+
/** How the fork is found: its launcher (`ncode`), and the directory it keeps its sessions in. */
|
|
20
|
+
const NCODE_KIND: MinimaxKindSpec = {
|
|
21
|
+
name: "ncode",
|
|
22
|
+
lineage: "fork",
|
|
23
|
+
detect: { binary: "ncode", home: "~/.minimax" },
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** The kind "ncode". */
|
|
27
|
+
export const ncodeKind = minimaxKind(NCODE_KIND);
|
|
28
|
+
|
|
29
|
+
/** One installation of the fork: `ncode` at the home of its profile (`~/.minimax`) unless the options say otherwise. */
|
|
30
|
+
export function ncode(options: McodeOptions = {}): HarnessBinding {
|
|
31
|
+
return ncodeKind.bind({ ...options, id: options.id ?? "ncode" });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export { ncodeSkills } from "./skills.ts";
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
2
|
+
import { basename, dirname, join } from "node:path";
|
|
3
|
+
import type { ProfileContext } from "@niwa-labs/sandbox";
|
|
4
|
+
|
|
5
|
+
/** The active package of a versioned ncode launcher and the Node installation it pins. */
|
|
6
|
+
export function versionedPrograms(launcher: string, context: ProfileContext): readonly string[] | undefined {
|
|
7
|
+
if (basename(launcher) !== "ncode" || basename(dirname(launcher)) !== "bin") return undefined;
|
|
8
|
+
try {
|
|
9
|
+
const file = statSync(launcher);
|
|
10
|
+
if (!file.isFile() || file.size > 4096) return undefined;
|
|
11
|
+
const script = readFileSync(launcher, "utf8");
|
|
12
|
+
const revision = /^MCODE_BUILD_ID=([0-9a-f]{40})$/m.exec(script)?.[1];
|
|
13
|
+
const command = /^exec (\/[^\s'"]+\/node) (\/[^\s'"]+\/cli\.js) "\$@"$/m.exec(script);
|
|
14
|
+
if (!revision || !command?.[1] || !command[2]) return undefined;
|
|
15
|
+
const prefix = dirname(dirname(launcher));
|
|
16
|
+
const release = join("installs", "ncode", revision, "lib", "node_modules", "@niwa-labs", "ncode");
|
|
17
|
+
const pkg = dirname(command[2]);
|
|
18
|
+
const installed = join(realpathSync(prefix), release);
|
|
19
|
+
if (realpathSync(pkg) !== installed || realpathSync(command[2]) !== join(installed, "cli.js")) return undefined;
|
|
20
|
+
const metadata = JSON.parse(readFileSync(join(pkg, "package.json"), "utf8"));
|
|
21
|
+
const build = JSON.parse(readFileSync(join(pkg, "release.json"), "utf8"));
|
|
22
|
+
if (metadata.name !== "@niwa-labs/ncode" || build.revision !== revision) return undefined;
|
|
23
|
+
|
|
24
|
+
// A distribution's own bin/node and public development header identify its prefix. Never
|
|
25
|
+
// grant that prefix: the executable and the one active release are the entire read grant.
|
|
26
|
+
const runtime = realpathSync(command[1]);
|
|
27
|
+
if (basename(runtime) !== "node" || basename(dirname(runtime)) !== "bin" || Bun.which(runtime) === null) return undefined;
|
|
28
|
+
if (!existsSync(join(dirname(dirname(runtime)), "include", "node", "node_version.h"))) return undefined;
|
|
29
|
+
return [...context.bin(pkg), ...context.bin(command[1])];
|
|
30
|
+
} catch {
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the owner's fork of MiniMax Code (0.7.2) adds to the ACP
|
|
3
|
+
* dialect of upstream (`../mcode/protocol.ts`): read only for an `ncode` session, never for an
|
|
4
|
+
* upstream one.
|
|
5
|
+
*
|
|
6
|
+
* Hand-written, since the fork publishes no schema, from its sources (the ACP layer:
|
|
7
|
+
* agent, updates, extensions and interactions; the runtime port):
|
|
8
|
+
*
|
|
9
|
+
* - the working mode of a session, `_meta["minimax-code/permissionMode"]` on `session/new`,
|
|
10
|
+
* `session/load` and `session/resume`, and the -32603 refusal of a daemon that cannot take it;
|
|
11
|
+
* - the decision on a tool call, `_meta["minimax-code/permission"]`, and the parent tool call of a
|
|
12
|
+
* delegated one, `_meta["minimax-code/parentToolCallId"]`, on `tool_call` and `tool_call_update`;
|
|
13
|
+
* - service speech, `_meta.informational`, on `agent_message_chunk`;
|
|
14
|
+
* - the `deny-always` option (`reject_always`) of a permission request, an ACP kind niwa never picks;
|
|
15
|
+
* - the methods `mcode/session/turn_status` and `session/history`.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { z } from "zod";
|
|
19
|
+
|
|
20
|
+
import { assertNever } from "@niwa-labs/core";
|
|
21
|
+
import { ProtocolNameSchema } from "@niwa-labs/harness";
|
|
22
|
+
import { Acp, McodePermissionMode } from "../mcode/protocol.ts";
|
|
23
|
+
|
|
24
|
+
/** The name niwa gives the fork's protocol in the unknowns it records. */
|
|
25
|
+
export const NCODE_ACP_PROTOCOL = ProtocolNameSchema.parse(`acp-${Acp.ACP_SDK_VERSION}/ncode`);
|
|
26
|
+
|
|
27
|
+
/** The `_meta` key of the working mode of a session. */
|
|
28
|
+
export const PERMISSION_MODE_META = "minimax-code/permissionMode";
|
|
29
|
+
|
|
30
|
+
/** The `_meta` of `session/new`, `session/load` and `session/resume`: upstream's `permissionMode` values, per session. */
|
|
31
|
+
export const NcodeSessionMeta = z.object({ [PERMISSION_MODE_META]: McodePermissionMode });
|
|
32
|
+
export type NcodeSessionMeta = z.output<typeof NcodeSessionMeta>;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The refusal of a daemon too old to take the mode of a session: -32603 with this message (the
|
|
36
|
+
* SDK puts "Internal error: " before it), and no data.
|
|
37
|
+
*/
|
|
38
|
+
export const MODE_UNSUPPORTED = { code: -32603, message: "runtime does not support per-session permissionMode; restart mcoded" } as const;
|
|
39
|
+
|
|
40
|
+
/** Whether a refusal of `session/new`, `session/load` or `session/resume` is that of a daemon too old for the mode. */
|
|
41
|
+
export function refusesSessionMode(code: number | undefined, message: string): boolean {
|
|
42
|
+
return code === MODE_UNSUPPORTED.code && message.includes(MODE_UNSUPPORTED.message);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The decision the fork marks a tool call with. */
|
|
46
|
+
export const NcodePermissionMark = z.object({
|
|
47
|
+
decision: z.enum(["allow", "deny"]),
|
|
48
|
+
decidedBy: z.enum(["classifier", "rule", "mode", "hook", "user"]),
|
|
49
|
+
/** `null` when no rule decided; a build before the key existed sends none. */
|
|
50
|
+
ruleKind: z.enum(["builtin", "session", "agent", "global"]).nullable().default(null),
|
|
51
|
+
mode: z.enum(["default", "auto", "bypassPermissions", "acceptEdits", "dontAsk", "off"]),
|
|
52
|
+
reason: z.string().min(1),
|
|
53
|
+
});
|
|
54
|
+
export type NcodePermissionMark = z.output<typeof NcodePermissionMark>;
|
|
55
|
+
|
|
56
|
+
/** The `_meta` of a tool call; a mark not of the shape reads as none, never as a lost update. */
|
|
57
|
+
export const NcodeToolMeta = z.object({
|
|
58
|
+
"minimax-code/permission": NcodePermissionMark.optional().catch(undefined),
|
|
59
|
+
"minimax-code/parentToolCallId": Acp.ToolCallId.optional().catch(undefined),
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
/** The `_meta` of service speech: a subscription wait, or a compaction. */
|
|
63
|
+
export const NcodeInformationalMeta = z.object({
|
|
64
|
+
informational: z.literal(true),
|
|
65
|
+
severity: z.enum(["warning", "info"]).optional(),
|
|
66
|
+
subscriptionStatus: z.enum(["waiting", "recovered", "exhausted", "cancelled"]).optional(),
|
|
67
|
+
nextRetryAtMs: z.number().optional(),
|
|
68
|
+
compactionStage: z.enum(["preparing", "installed", "failed"]).optional(),
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
type UpdateOption = (typeof Acp.SessionUpdate.options)[number];
|
|
72
|
+
type UpdateVariant<K extends Acp.SessionUpdate["sessionUpdate"]> = Extract<UpdateOption, z.ZodObject<{ sessionUpdate: z.ZodLiteral<K> }>>;
|
|
73
|
+
|
|
74
|
+
/** The snapshot's own schema of one kind of update. */
|
|
75
|
+
function variantOf<K extends Acp.SessionUpdate["sessionUpdate"]>(kind: K): UpdateVariant<K> {
|
|
76
|
+
const found = Acp.SessionUpdate.options.find((option): option is UpdateVariant<K> => option.shape.sessionUpdate.value === kind);
|
|
77
|
+
if (found === undefined) throw new Error(`the ACP snapshot has no session update ${kind}`);
|
|
78
|
+
return found;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const toolMeta = { _meta: NcodeToolMeta.nullable().optional().catch(undefined) };
|
|
82
|
+
|
|
83
|
+
/** A session update of the fork: upstream's, with the fork's `_meta` where the fork puts it. */
|
|
84
|
+
export const NcodeSessionUpdate = z
|
|
85
|
+
.discriminatedUnion("sessionUpdate", [
|
|
86
|
+
variantOf("user_message_chunk"),
|
|
87
|
+
variantOf("agent_message_chunk").extend({ _meta: NcodeInformationalMeta.nullable().optional().catch(undefined) }),
|
|
88
|
+
variantOf("agent_thought_chunk"),
|
|
89
|
+
variantOf("tool_call").extend(toolMeta),
|
|
90
|
+
variantOf("tool_call_update").extend(toolMeta),
|
|
91
|
+
variantOf("plan"),
|
|
92
|
+
variantOf("plan_update"),
|
|
93
|
+
variantOf("plan_removed"),
|
|
94
|
+
variantOf("available_commands_update"),
|
|
95
|
+
variantOf("current_mode_update"),
|
|
96
|
+
variantOf("config_option_update"),
|
|
97
|
+
variantOf("session_info_update"),
|
|
98
|
+
variantOf("usage_update"),
|
|
99
|
+
])
|
|
100
|
+
.brand<"NcodeSessionUpdate">();
|
|
101
|
+
export type NcodeSessionUpdate = z.output<typeof NcodeSessionUpdate>;
|
|
102
|
+
|
|
103
|
+
/** What the fork adds to an update: whether it is service speech, and the decision on a tool call. */
|
|
104
|
+
export interface NcodeUpdateMarks {
|
|
105
|
+
readonly informational: boolean;
|
|
106
|
+
readonly permission: NcodePermissionMark | undefined;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The fork's marks on an update upstream's reading already accepted. */
|
|
110
|
+
export function ncodeMarks(update: Acp.SessionUpdate): NcodeUpdateMarks {
|
|
111
|
+
const fork = NcodeSessionUpdate.parse(update);
|
|
112
|
+
switch (fork.sessionUpdate) {
|
|
113
|
+
case "agent_message_chunk":
|
|
114
|
+
return { informational: fork._meta?.informational === true, permission: undefined };
|
|
115
|
+
case "tool_call":
|
|
116
|
+
case "tool_call_update":
|
|
117
|
+
return { informational: false, permission: fork._meta?.["minimax-code/permission"] };
|
|
118
|
+
// The fork adds nothing to the other updates.
|
|
119
|
+
case "user_message_chunk":
|
|
120
|
+
case "agent_thought_chunk":
|
|
121
|
+
case "plan":
|
|
122
|
+
case "plan_update":
|
|
123
|
+
case "plan_removed":
|
|
124
|
+
case "available_commands_update":
|
|
125
|
+
case "current_mode_update":
|
|
126
|
+
case "config_option_update":
|
|
127
|
+
case "session_info_update":
|
|
128
|
+
case "usage_update":
|
|
129
|
+
return { informational: false, permission: undefined };
|
|
130
|
+
default:
|
|
131
|
+
return assertNever(fork, "ncode session update");
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** `mcode/session/turn_status`: whether a session has an active turn, whoever started it. */
|
|
136
|
+
export const TURN_STATUS = "mcode/session/turn_status";
|
|
137
|
+
export const TurnStatusResult = z.object({
|
|
138
|
+
activeTurn: z
|
|
139
|
+
.object({ turnId: z.string(), busyReason: z.enum(["turn", "compaction"]), locallyOwned: z.boolean() })
|
|
140
|
+
.nullable(),
|
|
141
|
+
latestActivity: z
|
|
142
|
+
.object({ turnId: z.string(), acceptedAtMs: z.number(), completedAtMs: z.number().optional(), activityAtMs: z.number() })
|
|
143
|
+
.nullable(),
|
|
144
|
+
queue: z.object({ pendingCount: z.number().int().nonnegative(), paused: z.boolean() }),
|
|
145
|
+
});
|
|
146
|
+
export type TurnStatusResult = z.output<typeof TurnStatusResult>;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Where the fork of MiniMax Code reads skills from: the root shared by the agents that read `.agents/skills`. */
|
|
2
|
+
|
|
3
|
+
import { SHARED_AGENTS_SKILLS } from "@niwa-labs/harness";
|
|
4
|
+
import type { KindSkills } from "@niwa-labs/harness";
|
|
5
|
+
|
|
6
|
+
export const ncodeSkills: KindSkills = { kind: "ncode", roots: SHARED_AGENTS_SKILLS };
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// Live: the `ncode` kind (the owner's fork of MiniMax Code) takes the permission mode per session.
|
|
2
|
+
//
|
|
3
|
+
// A session started in mode `auto` runs `echo $NIWA_ID` in its shell, and what it answers is the
|
|
4
|
+
// id the session was started with. niwa refuses every permission request the fork sends
|
|
5
|
+
// (`permissions: "deny"`), so the command runs only when the mode itself lets it through. A
|
|
6
|
+
// resume in a new process (session/load) names the mode again and succeeds; the fork would open
|
|
7
|
+
// the session in `default` otherwise. The permission marks of the fork, when its build puts them
|
|
8
|
+
// on tool calls, must all name `auto`.
|
|
9
|
+
//
|
|
10
|
+
// The prompt that follows a cold resume is not asserted: the installed build (0.7.2) ends it
|
|
11
|
+
// at once with no answer, for the `mcode` kind too and with no `_meta` on the load, so it says
|
|
12
|
+
// nothing about the mode.
|
|
13
|
+
//
|
|
14
|
+
// Both sides run in the working directory of this process: a resume in a new process has no
|
|
15
|
+
// directory of its own and loads the session where the process stands.
|
|
16
|
+
//
|
|
17
|
+
// The test is skipped unless NIWA_LIVE=1 and the "mcode" launcher is on the PATH. If the fork's
|
|
18
|
+
// auth needs another region, run it with `MAVIS_REGION=en`: the test passes the variable on from
|
|
19
|
+
// its own environment and sets none.
|
|
20
|
+
|
|
21
|
+
import { afterEach, expect, test } from "bun:test";
|
|
22
|
+
import { z } from "zod";
|
|
23
|
+
|
|
24
|
+
import { promptFromText, type SessionControl } from "@niwa-labs/harness";
|
|
25
|
+
import { ncode } from "../../src/ncode/index.ts";
|
|
26
|
+
import { live } from "@niwa-labs/testing";
|
|
27
|
+
|
|
28
|
+
let control: SessionControl | undefined;
|
|
29
|
+
|
|
30
|
+
afterEach(async () => {
|
|
31
|
+
await control?.dispose?.();
|
|
32
|
+
control = undefined;
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
/** The environment the fork's own auth needs: the region, when the caller's environment names one. */
|
|
36
|
+
const region: Record<string, string> = {};
|
|
37
|
+
if (process.env["MAVIS_REGION"] !== undefined) region["MAVIS_REGION"] = process.env["MAVIS_REGION"];
|
|
38
|
+
|
|
39
|
+
/** The control side of a fresh instance of the kind. */
|
|
40
|
+
function controlOfKind(): SessionControl {
|
|
41
|
+
const side = ncode({ control: { turnTimeoutMs: 180_000, permissions: "deny" } }).control;
|
|
42
|
+
if (side === undefined) throw new Error("the ncode kind has no control side");
|
|
43
|
+
return side;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
test.skipIf(!(live && Bun.which("ncode")))(
|
|
47
|
+
"ncode in mode auto answers the NIWA_ID of its session, and a resume in a new process takes the mode again",
|
|
48
|
+
async () => {
|
|
49
|
+
const first = controlOfKind();
|
|
50
|
+
control = first;
|
|
51
|
+
const niwaId = "niwa-live-session-id";
|
|
52
|
+
const { session: id } = await first.start({
|
|
53
|
+
prompt: promptFromText(""),
|
|
54
|
+
mode: "auto",
|
|
55
|
+
env: { NIWA_ID: niwaId, ...region },
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
const marks: Array<string | undefined> = [];
|
|
59
|
+
const watcher = (async () => {
|
|
60
|
+
for await (const event of first.life(id)) {
|
|
61
|
+
if (event.kind === "activity" && event.permission !== undefined) marks.push(event.permission.mode);
|
|
62
|
+
}
|
|
63
|
+
})().catch(() => undefined);
|
|
64
|
+
const reply = await first.ask(id, {
|
|
65
|
+
schema: z.object({ id: z.string() }),
|
|
66
|
+
prompt: promptFromText(
|
|
67
|
+
'Run `echo $NIWA_ID` in your shell. Answer with the exact output of that command, nothing else, in the field "id".',
|
|
68
|
+
),
|
|
69
|
+
});
|
|
70
|
+
expect(reply.value.id.trim()).toBe(niwaId);
|
|
71
|
+
await first.dispose?.();
|
|
72
|
+
await watcher;
|
|
73
|
+
expect(marks.every((mark) => mark === "auto")).toBe(true);
|
|
74
|
+
|
|
75
|
+
// A new process loads the session and names the mode again.
|
|
76
|
+
const second = controlOfKind();
|
|
77
|
+
control = second;
|
|
78
|
+
await second.resume(id, { mode: "auto", env: { NIWA_ID: niwaId, ...region } });
|
|
79
|
+
expect(await second.state(id)).toBe("idle");
|
|
80
|
+
},
|
|
81
|
+
300_000,
|
|
82
|
+
);
|