modelpace 0.0.0-stage → 0.1.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,337 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import {
6
+ normalizePolicy,
7
+ starterPolicy,
8
+ appendDispatchRecord,
9
+ collectDispatchScores,
10
+ collectSpeed,
11
+ } from '../src/index.mjs';
12
+ import { planDispatch, resolveDays } from '../src/context.mjs';
13
+ import pkg from '../package.json' with { type: 'json' };
14
+
15
+ const SERVER_INFO = { name: 'modelpace', version: pkg.version };
16
+ const PROTOCOL_VERSION = '2024-11-05';
17
+
18
+ const CONFIG_PATH = {
19
+ type: 'string',
20
+ description: 'Path to a dispatch.config.json policy. Omit to use MODELPACE_CONFIG, else the built-in policy for the official T3 Code instances codex, claudeAgent and antigravity.',
21
+ };
22
+ const SCORES_PATH = {
23
+ type: 'string',
24
+ description: 'Path to the JSONL acceptance ledger. Omit to use MODELPACE_SCORES, else $XDG_DATA_HOME/modelpace/scores.jsonl (%LOCALAPPDATA% on Windows).',
25
+ };
26
+ const DAYS = {
27
+ type: 'integer',
28
+ minimum: 1,
29
+ maximum: 365,
30
+ description: 'Speed window in days (default 30).',
31
+ };
32
+
33
+ export const MCP_TOOLS = [
34
+ {
35
+ name: 'dispatch_plan',
36
+ description:
37
+ 'Call this BEFORE delegate_task to choose which provider instance and model should take a task. It gates candidates on live quota (Even Pace, reset credits), prefers models with passing acceptance records, and returns a recommendation only; it never starts anything. ' +
38
+ 'Read `action`: "run" -> pass `recommended.target` ({ providerInstanceId, model, options }) to delegate_task as is; "wait" -> retry at `waitUntil`; "redeem" -> ask the user to redeem the reset credit in `redeemCandidate`, then call again; "refresh" -> the usage snapshot is missing or stale, retry with a fresh source (t3Auto or t3Origin); "pause" -> every candidate is blocked, see `reasons`, retry at `nextCheckAt`. ' +
39
+ 'Keep `recommended.executor` and add a `site` label to it when you later call dispatch_record. ' +
40
+ 'Needs a usage source: t3Auto (local T3 Code), t3Origin (with MODELPACE_TOKEN), or snapshotPath/snapshot; without one the call fails with an error that names these options.',
41
+ inputSchema: {
42
+ type: 'object',
43
+ properties: {
44
+ task: {
45
+ type: 'string',
46
+ enum: ['general', 'research', 'review', 'slice', 'long'],
47
+ description: 'Task category; selects the slot through the config\'s taskToSlot and the score cell that is looked up. Default general. Use slice for a bounded implementation piece, long for large or hard work, review for read-only checking, research for investigation.',
48
+ },
49
+ tier: { type: 'string', description: 'Permission/sensitivity tier from the config\'s `tiers` (for example work, personal, public); candidates not allowed for it are skipped. Omit to skip tier gating. Not the score tier.' },
50
+ slot: { type: 'string', description: 'Policy slot name; overrides the slot chosen through task. Leave unset unless you know the config\'s slots.' },
51
+ waitMinutes: { type: 'number', minimum: 0, maximum: 1440, description: 'How many minutes you are willing to wait for a quota reset before settling for "wait" (default 0).' },
52
+ claudeModel: { type: 'string', description: 'Claude model family (for example sonnet, opus) when a Claude window is shared by family.' },
53
+ configPath: CONFIG_PATH,
54
+ scoresPath: SCORES_PATH,
55
+ t3Auto: { type: 'boolean', description: 'Read quota from the local T3 Code through a 2-minute orchestration:read session that is revoked afterwards (also enabled by MODELPACE_AUTO=1).' },
56
+ t3Origin: { type: 'string', description: 'URL of a running T3 server (for example http://127.0.0.1:3773). The bearer token comes from MODELPACE_TOKEN or MODELPACE_TOKEN_CMD.' },
57
+ snapshotPath: { type: 'string', description: 'Path to a saved usage snapshot JSON (see docs/SCHEMA.md); also MODELPACE_SNAPSHOT. Snapshots older than 15 minutes produce "refresh".' },
58
+ snapshot: { type: 'object', description: 'The same as snapshotPath, passed inline: a UsageSnapshot v2 or a raw T3 server.getConfig response.' },
59
+ budgetPath: { type: 'string', description: 'Optional pay-as-you-go budget overlay JSON for API-billed instances.' },
60
+ includeSpeed: { type: 'boolean', description: 'Measure real tok/s from local session logs and use it to break ties between equally qualified candidates. Scans log files, so it is slower.' },
61
+ speedMetrics: { type: 'object', description: 'Explicit speed metrics keyed by model, for example { "gpt-5.3-codex": { "longRate": 120 } }; overrides includeSpeed.' },
62
+ days: DAYS,
63
+ },
64
+ additionalProperties: false,
65
+ },
66
+ },
67
+ {
68
+ name: 'dispatch_record',
69
+ description:
70
+ 'Call this AFTER you have independently verified a delegated task (tests, diff review or explicit user acceptance), never on the sub-agent\'s own report. It appends one acceptance record to the ledger so later dispatch_plan calls can prefer models that really pass; a candidate becomes "qualified" after 5 successful records for the same executor and task. ' +
71
+ 'Build `record.executor` from `recommended.executor` of the plan you followed plus a `site` label (for example "local"). All fifteen record fields are required; an invalid record is rejected with a message naming the missing or wrong field. Returns { file, identity, task }.',
72
+ inputSchema: {
73
+ type: 'object',
74
+ required: ['record'],
75
+ properties: {
76
+ record: {
77
+ type: 'object',
78
+ description: 'One acceptance record with all fifteen fields: date (YYYY-MM-DD), taskId, title, task (general|research|review|slice|long), executor { provider, model, effort, tier, site }, scorer, accepted, firstPass, reworkRounds, scopeViolation, falseReport, stoppedOnDenial (boolean or null), durationMin (number or null), quotaDelta (number or null), note (string). Field meanings: docs/SCHEMA.md.',
79
+ },
80
+ scoresPath: SCORES_PATH,
81
+ configPath: CONFIG_PATH,
82
+ },
83
+ additionalProperties: false,
84
+ },
85
+ },
86
+ {
87
+ name: 'dispatch_scores',
88
+ description:
89
+ 'Read-only summary of the acceptance ledger: for every executor identity and task the pass rate with its 90% credible interval, sample count, median duration of successes and nominal cost, plus the qualified / trial ranking per task. Use it to see why dispatch_plan prefers a model or to review quality over time. An empty or missing ledger returns an empty summary, not an error.',
90
+ inputSchema: {
91
+ type: 'object',
92
+ properties: {
93
+ scoresPath: SCORES_PATH,
94
+ configPath: CONFIG_PATH,
95
+ },
96
+ additionalProperties: false,
97
+ },
98
+ },
99
+ {
100
+ name: 'dispatch_speed',
101
+ description:
102
+ 'Read-only local speed leaderboard: median tok/s of long requests and short-request latency per model, measured from this machine\'s own session logs (Claude Code, Codex, OpenCode, Antigravity), merged with dispatch pass counts from the ledger. Rows with fewer than 20 long requests are marked lowSample and are not used as tie-breakers. Returns { days, ranking, metrics, sources, warnings }; `warnings` lists log sources that were missing or unreadable.',
103
+ inputSchema: {
104
+ type: 'object',
105
+ properties: {
106
+ days: DAYS,
107
+ scoresPath: SCORES_PATH,
108
+ configPath: CONFIG_PATH,
109
+ },
110
+ additionalProperties: false,
111
+ },
112
+ },
113
+ ];
114
+
115
+ function loadPolicy(configPath, env) {
116
+ const target = configPath ?? env.MODELPACE_CONFIG;
117
+ if (!target) return starterPolicy();
118
+ return normalizePolicy(JSON.parse(fs.readFileSync(path.resolve(target), 'utf8')));
119
+ }
120
+
121
+ export async function handleToolCall(name, args = {}, { env = process.env, now = () => Date.now() } = {}) {
122
+ if (name === 'dispatch_plan') {
123
+ const policy = loadPolicy(args.configPath, env);
124
+ const currentMs = now();
125
+ const snapFile = args.snapshotPath ?? env.MODELPACE_SNAPSHOT;
126
+ const rawSnapshot = args.snapshot
127
+ ?? (snapFile ? JSON.parse(fs.readFileSync(path.resolve(snapFile), 'utf8')) : null);
128
+ const origin = args.t3Origin ?? env.MODELPACE_ORIGIN;
129
+ const auto = args.t3Auto === true || env.MODELPACE_AUTO === '1';
130
+ if (!rawSnapshot && !origin && !auto) {
131
+ throw new Error('No usage source configured: set t3Auto: true (local T3 Code), t3Origin (with MODELPACE_TOKEN), snapshotPath, or snapshot; the MODELPACE_AUTO=1, MODELPACE_ORIGIN and MODELPACE_SNAPSHOT environment variables work too');
132
+ }
133
+ const planned = await planDispatch({
134
+ policy,
135
+ request: {
136
+ ...(args.slot ? { slot: args.slot } : {}),
137
+ ...(args.task ? { task: args.task } : {}),
138
+ ...(args.tier ? { tier: args.tier } : {}),
139
+ ...(args.claudeModel ? { claudeModel: args.claudeModel } : {}),
140
+ waitMinutes: args.waitMinutes ?? 0,
141
+ },
142
+ rawSnapshot,
143
+ origin,
144
+ bearer: env.MODELPACE_TOKEN,
145
+ tokenCommand: env.MODELPACE_TOKEN_CMD,
146
+ auto,
147
+ budget: args.budgetPath ? JSON.parse(fs.readFileSync(path.resolve(args.budgetPath), 'utf8')) : null,
148
+ scoresPath: args.scoresPath ?? env.MODELPACE_SCORES,
149
+ speedMetrics: args.speedMetrics ?? null,
150
+ speedScan: args.includeSpeed === true,
151
+ days: resolveDays(args.days),
152
+ env,
153
+ now: currentMs,
154
+ });
155
+
156
+ return planned.decision;
157
+ }
158
+
159
+ if (name === 'dispatch_speed') {
160
+ const policy = loadPolicy(args.configPath, env);
161
+ const speed = await collectSpeed({
162
+ days: resolveDays(args.days),
163
+ now: now(),
164
+ scoresFile: args.scoresPath ?? env.MODELPACE_SCORES,
165
+ scoring: policy.scoring,
166
+ env,
167
+ });
168
+ return {
169
+ days: speed.days,
170
+ ranking: speed.ranking,
171
+ metrics: speed.metrics,
172
+ sources: speed.sources,
173
+ warnings: speed.warnings,
174
+ };
175
+ }
176
+
177
+ if (name === 'dispatch_record') {
178
+ const policy = loadPolicy(args.configPath, env);
179
+ if (!args.record || typeof args.record !== 'object') {
180
+ throw new Error('dispatch_record requires a record object');
181
+ }
182
+ return appendDispatchRecord(args.record, {
183
+ scoresFile: args.scoresPath,
184
+ env,
185
+ config: policy.scoring,
186
+ });
187
+ }
188
+
189
+ if (name === 'dispatch_scores') {
190
+ const policy = loadPolicy(args.configPath, env);
191
+ return collectDispatchScores({ scoresFile: args.scoresPath, env }, policy.scoring);
192
+ }
193
+
194
+ throw new Error(`Unknown tool: ${name}`);
195
+ }
196
+
197
+ export async function handleJsonRpcMessage(msg, context = {}) {
198
+ if (!msg || typeof msg !== 'object' || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') {
199
+ return {
200
+ jsonrpc: '2.0',
201
+ id: msg?.id ?? null,
202
+ error: { code: -32600, message: 'Invalid Request' },
203
+ };
204
+ }
205
+
206
+ const hasId = Object.hasOwn(msg, 'id') && msg.id !== undefined;
207
+ const { method, params, id } = msg;
208
+
209
+ // Notifications have no id and expect no response
210
+ if (method.startsWith('notifications/') || !hasId) {
211
+ return null;
212
+ }
213
+
214
+ if (method === 'initialize') {
215
+ return {
216
+ jsonrpc: '2.0',
217
+ id,
218
+ result: {
219
+ protocolVersion: params?.protocolVersion ?? PROTOCOL_VERSION,
220
+ capabilities: { tools: {} },
221
+ serverInfo: SERVER_INFO,
222
+ },
223
+ };
224
+ }
225
+
226
+ if (method === 'ping') {
227
+ return { jsonrpc: '2.0', id, result: {} };
228
+ }
229
+
230
+ if (method === 'tools/list') {
231
+ return {
232
+ jsonrpc: '2.0',
233
+ id,
234
+ result: { tools: MCP_TOOLS },
235
+ };
236
+ }
237
+
238
+ if (method === 'tools/call') {
239
+ const toolName = params?.name;
240
+ const toolArgs = params?.arguments ?? {};
241
+ try {
242
+ const output = await handleToolCall(toolName, toolArgs, context);
243
+ return {
244
+ jsonrpc: '2.0',
245
+ id,
246
+ result: {
247
+ content: [{ type: 'text', text: JSON.stringify(output, null, 2) }],
248
+ structuredContent: output,
249
+ isError: false,
250
+ },
251
+ };
252
+ } catch (error) {
253
+ return {
254
+ jsonrpc: '2.0',
255
+ id,
256
+ result: {
257
+ content: [{ type: 'text', text: String(error?.message ?? error) }],
258
+ isError: true,
259
+ },
260
+ };
261
+ }
262
+ }
263
+
264
+ return {
265
+ jsonrpc: '2.0',
266
+ id,
267
+ error: { code: -32601, message: `Method not found: ${method}` },
268
+ };
269
+ }
270
+
271
+ export function startMcpServer({ stdin = process.stdin, stdout = process.stdout, env = process.env, now = () => Date.now() } = {}) {
272
+ let buffer = Buffer.alloc(0);
273
+
274
+ const send = (payload) => {
275
+ if (!payload) return;
276
+ stdout.write(`${JSON.stringify(payload)}\n`);
277
+ };
278
+
279
+ const processLine = async (line) => {
280
+ const trimmed = line.trim();
281
+ if (!trimmed) return;
282
+ let msg;
283
+ try {
284
+ msg = JSON.parse(trimmed);
285
+ } catch {
286
+ send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } });
287
+ return;
288
+ }
289
+ const reply = await handleJsonRpcMessage(msg, { env, now });
290
+ send(reply);
291
+ };
292
+
293
+ let chain = Promise.resolve();
294
+ const enqueue = (fn) => {
295
+ chain = chain.then(fn, () => {});
296
+ };
297
+
298
+ stdin.on('data', (chunk) => {
299
+ buffer = Buffer.concat([buffer, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)]);
300
+ while (buffer.length > 0) {
301
+ const head = buffer.subarray(0, 15).toString('ascii');
302
+ if (head.toLowerCase().startsWith('content-length:')) {
303
+ const headerEnd = buffer.indexOf('\r\n\r\n');
304
+ if (headerEnd === -1) break;
305
+ const headerText = buffer.subarray(0, headerEnd).toString('ascii');
306
+ const match = headerText.match(/content-length:\s*(\d+)/i);
307
+ if (!match) {
308
+ buffer = buffer.subarray(headerEnd + 4);
309
+ continue;
310
+ }
311
+ const length = Number(match[1]);
312
+ const bodyStart = headerEnd + 4;
313
+ if (buffer.length < bodyStart + length) break;
314
+ const body = buffer.subarray(bodyStart, bodyStart + length).toString('utf8');
315
+ buffer = buffer.subarray(bodyStart + length);
316
+ enqueue(() => processLine(body));
317
+ } else {
318
+ const nl = buffer.indexOf('\n');
319
+ if (nl === -1) break;
320
+ const line = buffer.subarray(0, nl).toString('utf8');
321
+ buffer = buffer.subarray(nl + 1);
322
+ enqueue(() => processLine(line));
323
+ }
324
+ }
325
+ });
326
+
327
+ stdin.on('end', () => {
328
+ const rest = buffer.toString('utf8').trim();
329
+ if (rest) {
330
+ enqueue(() => processLine(rest));
331
+ }
332
+ });
333
+ }
334
+
335
+ if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
336
+ startMcpServer();
337
+ }