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,82 @@
1
+ ---
2
+ name: modelpace
3
+ description: Choose which T3 Code provider instance and model should take a delegated task, using live quota pacing and past acceptance records, and record the verified outcome afterwards. Use before calling delegate_task when more than one provider/model could take the work or quota may be tight, and after independently verifying a delegated result. Triggers on requests such as "which model should run this", "dispatch this task", "check my quota before delegating", "record this result", "which model passes more often".
4
+ license: MIT
5
+ compatibility: Needs Node.js 22+ and the modelpace CLI or its MCP server (dispatch_plan, dispatch_record, dispatch_scores, dispatch_speed). Live quota needs a running T3 Code; replaying a saved snapshot works offline.
6
+ ---
7
+
8
+ # modelpace
9
+
10
+ `modelpace` recommends a `delegate_task` target; it never starts work itself. `modelpace` below is `node <checkout>/bin/modelpace.mjs` or `npx modelpace`; each CLI command has an MCP tool of the same purpose (`dispatch_plan`, `dispatch_record`, `dispatch_scores`, `dispatch_speed`). Full setup, privacy notes and troubleshooting: [AGENTS.md](../../AGENTS.md). Field reference: [docs/SCHEMA.md](../../docs/SCHEMA.md).
11
+
12
+ ## 1. Plan before dispatching
13
+
14
+ ```bash
15
+ modelpace plan --t3-auto --task slice --format json
16
+ ```
17
+
18
+ - `--task`: `general` | `research` | `review` | `slice` (bounded implementation piece) | `long` (large or hard work). It selects the slot through the config.
19
+ - Optional: `--tier T` (permission tier from the config; omit to skip tier gating), `--wait-minutes N` (willing to wait for a reset), `--speed-scan` (break ties by measured tok/s).
20
+ - `--t3-auto` issues a 2-minute `orchestration:read` session on the local T3 Code and revokes it. If the user has not agreed to that, use `--snapshot FILE` or `--t3-origin URL` instead.
21
+ - Without `--config` the built-in policy for the official instances `codex`, `claudeAgent`, `antigravity` is used.
22
+
23
+ Act on `action`:
24
+
25
+ | `action` | What to do |
26
+ | --- | --- |
27
+ | `run` | Pass `recommended.target` (`{ providerInstanceId, model, options }`) to `delegate_task` unchanged. Keep `recommended.executor` for step 2. |
28
+ | `wait` | Retry at `waitUntil` or dispatch elsewhere. |
29
+ | `redeem` | Ask the user to redeem the credit in `redeemCandidate`, then plan again. |
30
+ | `refresh` | Quota data is missing or stale: re-run with `--t3-auto` or `--t3-origin`; when replaying a file add `--now` close to its `observedAt`. |
31
+ | `pause` | Every candidate is blocked: read `reasons`, retry at `nextCheckAt`, or tell the user. |
32
+
33
+ ## 2. Record after independent verification
34
+
35
+ Record only after you verified the delegated result yourself (tests, diff, or the user's explicit acceptance), never on the sub-agent's own report.
36
+
37
+ The `executor` in the record must be the identity the plan used, otherwise the record never counts. Copy `provider`, `model`, `effort` and `tier` from `recommended.executor` and add your own `site` label. Do not use the `--tier` permission tier here: the record's `tier` is the candidate's service tier (`default` unless the config sets `scoreTier`/`serviceTier`).
38
+
39
+ ```json
40
+ {
41
+ "date": "2026-11-23",
42
+ "taskId": "task-123",
43
+ "title": "Add retry to the sync job",
44
+ "task": "slice",
45
+ "executor": {
46
+ "provider": "codex",
47
+ "model": "gpt-5.3-codex",
48
+ "effort": "high",
49
+ "tier": "default",
50
+ "site": "local"
51
+ },
52
+ "scorer": "orchestrator",
53
+ "accepted": true,
54
+ "firstPass": true,
55
+ "reworkRounds": 0,
56
+ "scopeViolation": false,
57
+ "falseReport": false,
58
+ "stoppedOnDenial": null,
59
+ "durationMin": 4.2,
60
+ "quotaDelta": 3,
61
+ "note": "Verified with unit tests."
62
+ }
63
+ ```
64
+
65
+ Save it as `record.json` (the same content ships as `examples/record.example.json`) and run:
66
+
67
+ ```bash
68
+ modelpace record --json record.json
69
+ ```
70
+
71
+ All fifteen fields are required; a rejected record names the missing or wrong field. Judge honestly: `accepted` is whether the result was accepted after your verification, `firstPass` means no rework, `falseReport` means the executor claimed success that verification contradicted.
72
+
73
+ A candidate becomes `qualified` after 5 successful records for the same executor and task (success: accepted, no false report, no scope violation, at most one rework round). Until then it is `trial` and still eligible.
74
+
75
+ ## 3. Review rankings and speed
76
+
77
+ ```bash
78
+ modelpace scores
79
+ modelpace speed --days 30
80
+ ```
81
+
82
+ `scores` shows pass rate with a 90% interval, sample count, median duration and cost per executor and task. `speed` ranks models by tok/s measured from local session logs; rows marked `lowSample` (fewer than 20 long requests) are not used as tie-breakers. For a visual overview run `modelpace dashboard --t3-auto --out dashboard.html` and render the file with `html_render`.
@@ -0,0 +1,360 @@
1
+ import { normalizeT3ConfigToSnapshot, inferWindowPool } from './t3-config.mjs';
2
+
3
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
4
+
5
+ function toIsoTimestamp(value) {
6
+ if (value == null) return null;
7
+ if (typeof value === 'number' && Number.isFinite(value)) {
8
+ const millis = value < 1e12 ? value * 1000 : value;
9
+ const d = new Date(millis);
10
+ return Number.isFinite(d.getTime()) ? d.toISOString() : null;
11
+ }
12
+ if (typeof value === 'string' && value.trim()) {
13
+ const ms = Date.parse(value);
14
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : null;
15
+ }
16
+ return null;
17
+ }
18
+
19
+ function clampPercent(value) {
20
+ if (!Number.isFinite(value)) return null;
21
+ return Math.max(0, Math.min(100, value));
22
+ }
23
+
24
+ function normalizeLegacyClaudeEntry(entry, observedIso) {
25
+ const plan = isObject(entry.plan) ? entry.plan : entry;
26
+ const rawStatus = plan.status;
27
+ const status = rawStatus === 'ok' || rawStatus === 'ready'
28
+ ? 'ready'
29
+ : ['unavailable', 'not_applicable', 'disabled'].includes(rawStatus)
30
+ ? rawStatus
31
+ : 'unavailable';
32
+
33
+ const windows = [];
34
+ if (status === 'ready' && Array.isArray(plan.windows)) {
35
+ for (const win of plan.windows) {
36
+ if (!isObject(win)) continue;
37
+ const label = typeof win.label === 'string' ? win.label : null;
38
+ let id = typeof win.id === 'string' && win.id ? win.id : null;
39
+ if (!id && label) {
40
+ if (label === '5-hour limit') id = 'five_hour';
41
+ else if (label === 'Weekly · all models') id = 'seven_day';
42
+ else if (label.startsWith('Weekly · ') && label.slice(9).trim()) {
43
+ id = `seven_day_${label.slice(9).trim().toLowerCase().replace(/[^a-z0-9]/g, '_')}`;
44
+ }
45
+ }
46
+ const usedRaw = clampPercent(win.percentUsed ?? win.usedPercent);
47
+ const remRaw = clampPercent(win.remainingPercent);
48
+ const usedPercent = usedRaw ?? (remRaw !== null ? clampPercent(100 - remRaw) : null);
49
+ const remainingPercent = remRaw ?? (usedRaw !== null ? clampPercent(100 - usedRaw) : null);
50
+ const windowDurationMins = Number.isFinite(win.windowDurationMins) && win.windowDurationMins > 0
51
+ ? win.windowDurationMins
52
+ : id === 'five_hour'
53
+ ? 300
54
+ : id === 'seven_day' || id?.startsWith('seven_day_')
55
+ ? 10080
56
+ : null;
57
+ windows.push({
58
+ id: id ?? label ?? 'window',
59
+ kind: id === 'five_hour' ? 'session' : id === 'seven_day' || id?.startsWith('seven_day_') ? 'weekly' : 'other',
60
+ label: label ?? id ?? 'window',
61
+ pool: null,
62
+ modelIds: null,
63
+ providerIds: null,
64
+ usedPercent,
65
+ remainingPercent,
66
+ resetsAt: toIsoTimestamp(win.resetsAt),
67
+ windowDurationMins,
68
+ });
69
+ }
70
+ }
71
+
72
+ let resetCredits = null;
73
+ if (Array.isArray(plan.resetCredits)) {
74
+ const cards = plan.resetCredits
75
+ .filter((c) => isObject(c) && typeof c.resetType === 'string')
76
+ .map((c, idx) => {
77
+ const type = c.resetType;
78
+ const coversWindowIds = type === 'claudeSession'
79
+ ? ['five_hour']
80
+ : type === 'claudeFable'
81
+ ? ['seven_day_fable']
82
+ : null;
83
+ const coversWindowPrefixes = type === 'claudeWeekly' ? ['seven_day'] : null;
84
+ return {
85
+ creditId: c.creditId ?? `claude-card-${idx + 1}`,
86
+ resetType: type,
87
+ status: c.status ?? 'available',
88
+ resetsLeft: Number.isSafeInteger(c.resetsLeft) ? c.resetsLeft : 0,
89
+ coversWindowIds,
90
+ coversWindowPrefixes,
91
+ expiresAt: toIsoTimestamp(c.expiresAt),
92
+ };
93
+ });
94
+ const availSum = cards.filter((c) => c.status === 'available').reduce((sum, c) => sum + c.resetsLeft, 0);
95
+ const known = Number.isSafeInteger(plan.resetCreditAvailableCount)
96
+ ? plan.resetCreditAvailableCount === availSum
97
+ : true;
98
+ resetCredits = {
99
+ known,
100
+ availableCount: Number.isSafeInteger(plan.resetCreditAvailableCount)
101
+ ? plan.resetCreditAvailableCount
102
+ : availSum,
103
+ nextExpiresAt: toIsoTimestamp(plan.resetCreditExpiresAt) ?? cards.find((c) => c.expiresAt)?.expiresAt ?? null,
104
+ cards,
105
+ };
106
+ }
107
+
108
+ return {
109
+ instanceId: entry.instanceId ?? 'claude',
110
+ driver: 'claudeAgent',
111
+ displayName: entry.displayName ?? 'Claude',
112
+ enabled: status !== 'disabled',
113
+ status,
114
+ plan: typeof plan.plan === 'string'
115
+ ? plan.plan
116
+ : typeof plan.planType === 'string'
117
+ ? plan.planType
118
+ : null,
119
+ checkedAt: toIsoTimestamp(plan.observedAt ?? entry.observedAt) ?? observedIso,
120
+ detail: typeof plan.detail === 'string' ? plan.detail : null,
121
+ windows,
122
+ resetCredits,
123
+ budget: null,
124
+ };
125
+ }
126
+
127
+ function normalizeLegacyGenericEntry(entry, observedIso) {
128
+ const provider = String(entry.instanceId ?? entry.provider ?? '').trim();
129
+ const driver = String(entry.driver ?? provider).trim();
130
+ const status = ['ready', 'unavailable', 'not_applicable', 'disabled'].includes(entry.status)
131
+ ? entry.status
132
+ : 'unavailable';
133
+
134
+ let rawWindows = [];
135
+ if (status === 'ready') {
136
+ if (Array.isArray(entry.windows)) {
137
+ rawWindows = entry.windows;
138
+ } else if (Number.isFinite(entry.remainingPercent) || Number.isFinite(entry.usedPercent)) {
139
+ rawWindows = [{
140
+ id: 'primary',
141
+ label: 'primary',
142
+ remainingPercent: entry.remainingPercent,
143
+ usedPercent: entry.usedPercent,
144
+ resetsAt: entry.resetsAt,
145
+ windowDurationMins: entry.windowDurationMins,
146
+ }];
147
+ }
148
+ }
149
+
150
+ const windows = rawWindows.filter(isObject).map((win, idx) => {
151
+ const usedRaw = clampPercent(win.usedPercent);
152
+ const remRaw = clampPercent(win.remainingPercent);
153
+ const usedPercent = usedRaw ?? (remRaw !== null ? clampPercent(100 - remRaw) : null);
154
+ const remainingPercent = remRaw ?? (usedRaw !== null ? clampPercent(100 - usedRaw) : null);
155
+ const duration = Number.isFinite(win.windowDurationMins) && win.windowDurationMins > 0
156
+ ? win.windowDurationMins
157
+ : null;
158
+ return {
159
+ id: win.id ?? `window-${idx + 1}`,
160
+ kind: win.kind ?? (duration && duration < 1440 ? 'session' : duration === 10080 ? 'weekly' : 'other'),
161
+ label: win.label ?? win.id ?? `window-${idx + 1}`,
162
+ pool: inferWindowPool(driver, win),
163
+ modelIds: Array.isArray(win.modelIds) ? [...win.modelIds] : null,
164
+ providerIds: Array.isArray(win.providerIds) ? [...win.providerIds] : null,
165
+ usedPercent,
166
+ remainingPercent,
167
+ resetsAt: toIsoTimestamp(win.resetsAt),
168
+ windowDurationMins: duration,
169
+ };
170
+ });
171
+
172
+ let resetCredits = null;
173
+ if (Array.isArray(entry.resetCredits) || Number.isSafeInteger(entry.resetCreditAvailableCount)) {
174
+ const cards = Array.isArray(entry.resetCredits)
175
+ ? entry.resetCredits.filter(isObject).map((c, idx) => ({
176
+ creditId: c.creditId ?? `card-${idx + 1}`,
177
+ resetType: c.resetType ?? 'codexRateLimits',
178
+ status: c.status ?? 'available',
179
+ resetsLeft: Number.isSafeInteger(c.resetsLeft) ? c.resetsLeft : 1,
180
+ coversWindowIds: null,
181
+ coversWindowPrefixes: null,
182
+ expiresAt: toIsoTimestamp(c.expiresAt),
183
+ }))
184
+ : [];
185
+ const avail = cards.filter((c) => c.status === 'available').length;
186
+ const count = Number.isSafeInteger(entry.resetCreditAvailableCount) ? entry.resetCreditAvailableCount : avail;
187
+ resetCredits = {
188
+ known: cards.length > 0 ? count === avail : false,
189
+ availableCount: count,
190
+ nextExpiresAt: toIsoTimestamp(entry.resetCreditExpiresAt) ?? cards.find((c) => c.expiresAt)?.expiresAt ?? null,
191
+ cards,
192
+ };
193
+ }
194
+
195
+ return {
196
+ instanceId: provider,
197
+ driver,
198
+ displayName: entry.displayName ?? provider,
199
+ enabled: status !== 'disabled',
200
+ status,
201
+ plan: entry.planType ?? entry.plan ?? null,
202
+ checkedAt: toIsoTimestamp(entry.observedAt) ?? observedIso,
203
+ detail: typeof entry.detail === 'string' ? entry.detail : null,
204
+ windows,
205
+ resetCredits,
206
+ budget: null,
207
+ };
208
+ }
209
+
210
+ export function overlayBudgetEntries(snapshot, budgets) {
211
+ if (!budgets) return snapshot;
212
+ const list = Array.isArray(budgets)
213
+ ? budgets
214
+ : isObject(budgets) && typeof budgets.instanceId === 'string'
215
+ ? [budgets]
216
+ : isObject(budgets)
217
+ ? Object.entries(budgets).map(([instanceId, value]) => ({ instanceId, ...(isObject(value) ? value : {}) }))
218
+ : [];
219
+
220
+ if (!list.length) return snapshot;
221
+
222
+ const instances = { ...snapshot.instances };
223
+ for (const item of list) {
224
+ if (!isObject(item) || typeof item.instanceId !== 'string' || !item.instanceId.trim()) continue;
225
+ const id = item.instanceId.trim();
226
+ const existing = instances[id];
227
+ const budget = {
228
+ spent: Number.isFinite(item.spent) ? item.spent : 0,
229
+ budget: Number.isFinite(item.budget) ? item.budget : null,
230
+ balance: Number.isFinite(item.balance) ? item.balance : null,
231
+ isAvailable: typeof item.isAvailable === 'boolean' ? item.isAvailable : true,
232
+ currency: typeof item.currency === 'string' ? item.currency : null,
233
+ month: typeof item.month === 'string' ? item.month : null,
234
+ resetsAt: toIsoTimestamp(item.resetsAt),
235
+ };
236
+ const isUnavailable = budget.isAvailable === false;
237
+ instances[id] = existing
238
+ ? {
239
+ ...existing,
240
+ budget,
241
+ }
242
+ : {
243
+ instanceId: id,
244
+ driver: item.driver ?? 'api',
245
+ displayName: item.displayName ?? id,
246
+ enabled: item.enabled !== false,
247
+ status: item.enabled === false ? 'disabled' : isUnavailable ? 'unavailable' : 'ready',
248
+ plan: item.plan ?? 'pay-as-you-go',
249
+ checkedAt: toIsoTimestamp(item.checkedAt) ?? snapshot.observedAt,
250
+ detail: typeof item.detail === 'string' ? item.detail : null,
251
+ windows: [],
252
+ resetCredits: null,
253
+ budget,
254
+ };
255
+ }
256
+
257
+ return {
258
+ ...snapshot,
259
+ source: snapshot.source === 't3-rpc' ? 'mixed' : snapshot.source,
260
+ instances,
261
+ };
262
+ }
263
+
264
+ export function normalizeSnapshot(input, { now = Date.now(), budgets = null } = {}) {
265
+ if (!isObject(input)) {
266
+ throw new Error('Snapshot input must be a JSON object');
267
+ }
268
+ const nowMs = now instanceof Date ? now.getTime() : now;
269
+ const observedIso = new Date(nowMs).toISOString();
270
+ let snapshot;
271
+
272
+ // 1. Native UsageSnapshot v2
273
+ if (input.schemaVersion === 2 && isObject(input.instances)) {
274
+ const instances = {};
275
+ for (const [key, inst] of Object.entries(input.instances)) {
276
+ if (!isObject(inst)) continue;
277
+ const driver = String(inst.driver ?? key);
278
+ const windows = Array.isArray(inst.windows)
279
+ ? inst.windows.filter(isObject).map((win) => {
280
+ const usedRaw = clampPercent(win.usedPercent);
281
+ const remRaw = clampPercent(win.remainingPercent);
282
+ return {
283
+ ...win,
284
+ usedPercent: usedRaw ?? (remRaw !== null ? clampPercent(100 - remRaw) : null),
285
+ remainingPercent: remRaw ?? (usedRaw !== null ? clampPercent(100 - usedRaw) : null),
286
+ pool: inferWindowPool(driver, win),
287
+ resetsAt: toIsoTimestamp(win.resetsAt),
288
+ };
289
+ })
290
+ : [];
291
+ instances[key] = {
292
+ instanceId: inst.instanceId ?? key,
293
+ driver,
294
+ displayName: inst.displayName ?? key,
295
+ enabled: inst.enabled !== false,
296
+ status: inst.status ?? (inst.enabled === false ? 'disabled' : 'ready'),
297
+ plan: inst.plan ?? null,
298
+ checkedAt: toIsoTimestamp(inst.checkedAt) ?? toIsoTimestamp(input.observedAt) ?? observedIso,
299
+ detail: inst.detail ?? null,
300
+ ...(Array.isArray(inst.models) ? { models: [...inst.models] } : {}),
301
+ windows,
302
+ resetCredits: inst.resetCredits ?? null,
303
+ budget: inst.budget ?? null,
304
+ };
305
+ }
306
+ snapshot = {
307
+ schemaVersion: 2,
308
+ observedAt: toIsoTimestamp(input.observedAt) ?? observedIso,
309
+ source: input.source ?? 'json',
310
+ instances,
311
+ ...(Array.isArray(input.usageLimitSources) ? { usageLimitSources: input.usageLimitSources } : {}),
312
+ };
313
+ }
314
+ // 2. T3 server.getConfig dump
315
+ else if (
316
+ (Array.isArray(input.providers) && input.schemaVersion !== 1) ||
317
+ isObject(input.value) && Array.isArray(input.value.providers)
318
+ ) {
319
+ snapshot = {
320
+ ...normalizeT3ConfigToSnapshot(input, nowMs),
321
+ source: 'json',
322
+ };
323
+ }
324
+ // 3. Legacy schemaVersion 1 report
325
+ else if (input.schemaVersion === 1 && Array.isArray(input.providers)) {
326
+ const instances = {};
327
+ for (const entry of input.providers) {
328
+ if (!isObject(entry) || typeof entry.provider !== 'string') continue;
329
+ const norm = entry.provider === 'claude' || entry.provider === 'claudeAgent'
330
+ ? normalizeLegacyClaudeEntry(entry, observedIso)
331
+ : normalizeLegacyGenericEntry(entry, observedIso);
332
+ instances[norm.instanceId] = norm;
333
+ }
334
+ snapshot = {
335
+ schemaVersion: 2,
336
+ observedAt: toIsoTimestamp(input.observedAt) ?? observedIso,
337
+ source: 'json',
338
+ instances,
339
+ };
340
+ }
341
+ // 4. Standalone Claude desktop/plan JSON
342
+ else if (
343
+ isObject(input.plan) ||
344
+ (Array.isArray(input.windows) && ['ok', 'ready', 'unavailable', 'not_applicable'].includes(input.status))
345
+ ) {
346
+ const claudeInst = normalizeLegacyClaudeEntry(input, observedIso);
347
+ snapshot = {
348
+ schemaVersion: 2,
349
+ observedAt: claudeInst.checkedAt ?? observedIso,
350
+ source: 'json',
351
+ instances: {
352
+ [claudeInst.instanceId]: claudeInst,
353
+ },
354
+ };
355
+ } else {
356
+ throw new Error('Unsupported snapshot format');
357
+ }
358
+
359
+ return overlayBudgetEntries(snapshot, budgets);
360
+ }
@@ -0,0 +1,160 @@
1
+ import { execFile } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { promisify } from 'node:util';
6
+ import { T3RpcError, fetchT3ServerConfig, splitCommandArgs } from './t3-rpc.mjs';
7
+
8
+ const execFileAsync = promisify(execFile);
9
+
10
+ export const T3_BUNDLE_ID = 'com.t3tools.t3code';
11
+ const SESSION_TTL = '2m';
12
+ const SESSION_LABEL = 'modelpace';
13
+ // server.getConfig 只需要这一项权限;不传 --scope 时 T3 会签发包含终端与文件写入的标准客户端全套权限。
14
+ const SESSION_SCOPE = 'orchestration:read';
15
+ const SERVER_ENTRY = 'Contents/Resources/app.asar/apps/server/dist/bin.mjs';
16
+
17
+ const isExecutable = (file) => {
18
+ try {
19
+ fs.accessSync(file, fs.constants.X_OK);
20
+ return fs.statSync(file).isFile();
21
+ } catch {
22
+ return false;
23
+ }
24
+ };
25
+
26
+ function findOnPath(name, env) {
27
+ const exts = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
28
+ for (const dir of (env.PATH ?? '').split(path.delimiter).filter(Boolean)) {
29
+ for (const ext of exts) {
30
+ const candidate = path.join(dir, `${name}${ext}`);
31
+ if (isExecutable(candidate)) return candidate;
32
+ }
33
+ }
34
+ return null;
35
+ }
36
+
37
+ function bundleId(appDir) {
38
+ try {
39
+ const plist = fs.readFileSync(path.join(appDir, 'Contents', 'Info.plist'), 'utf8');
40
+ return /<key>CFBundleIdentifier<\/key>\s*<string>([^<]+)<\/string>/.exec(plist)?.[1] ?? null;
41
+ } catch {
42
+ return null;
43
+ }
44
+ }
45
+
46
+ function findMacApp(appDirs) {
47
+ for (const dir of appDirs) {
48
+ let names;
49
+ try {
50
+ names = fs.readdirSync(dir).filter((name) => name.endsWith('.app'));
51
+ } catch {
52
+ continue;
53
+ }
54
+ for (const name of names) {
55
+ const appDir = path.join(dir, name);
56
+ if (bundleId(appDir) !== T3_BUNDLE_ID) continue;
57
+ const exeDir = path.join(appDir, 'Contents', 'MacOS');
58
+ const exe = fs.readdirSync(exeDir).map((entry) => path.join(exeDir, entry)).find(isExecutable);
59
+ const entry = path.join(appDir, SERVER_ENTRY);
60
+ if (exe) return { file: exe, args: [entry], env: { ELECTRON_RUN_AS_NODE: '1' }, source: 'app-bundle' };
61
+ }
62
+ }
63
+ return null;
64
+ }
65
+
66
+ /** 发现本机 T3 Code CLI:MODELPACE_T3_BIN > PATH 上的 t3 > macOS 应用包(bundle id 匹配)。 */
67
+ export function discoverT3Cli({ env = process.env, homeDir = os.homedir(), platform = process.platform, appDirs } = {}) {
68
+ if (env.MODELPACE_T3_BIN?.trim()) {
69
+ const [file, ...args] = splitCommandArgs(env.MODELPACE_T3_BIN);
70
+ return { file, args, env: {}, source: 'env' };
71
+ }
72
+ const onPath = findOnPath('t3', env);
73
+ if (onPath) return { file: onPath, args: [], env: {}, source: 'path' };
74
+ if (platform === 'darwin') {
75
+ const found = findMacApp(appDirs ?? ['/Applications', path.join(homeDir, 'Applications')]);
76
+ if (found) return found;
77
+ }
78
+ throw new T3RpcError('Local T3 Code CLI not found (set MODELPACE_T3_BIN, or put t3 on PATH)', {
79
+ code: 'T3_CLI_NOT_FOUND',
80
+ });
81
+ }
82
+
83
+ const processAlive = (pid) => {
84
+ try {
85
+ process.kill(pid, 0);
86
+ return true;
87
+ } catch (error) {
88
+ return error.code === 'EPERM';
89
+ }
90
+ };
91
+
92
+ /** 本机服务 origin 取自运行态记录(只含 pid/端口/origin,不含任何凭据)。 */
93
+ export function discoverT3Origin({ baseDir, origin } = {}) {
94
+ if (origin) return origin;
95
+ const file = path.join(baseDir, 'userdata', 'server-runtime.json');
96
+ let state;
97
+ try {
98
+ state = JSON.parse(fs.readFileSync(file, 'utf8'));
99
+ } catch {
100
+ throw new T3RpcError('No running local T3 Code server found (start T3 Code, or pass an origin)', {
101
+ code: 'T3_SERVER_NOT_FOUND',
102
+ });
103
+ }
104
+ if (typeof state?.origin !== 'string' || (Number.isInteger(state.pid) && !processAlive(state.pid))) {
105
+ throw new T3RpcError('The recorded local T3 Code server is not running', { code: 'T3_SERVER_NOT_RUNNING' });
106
+ }
107
+ return state.origin;
108
+ }
109
+
110
+ /**
111
+ * 零配置连接本机 T3 Code:经官方 CLI 签发 2 分钟、仅含 orchestration:read 的会话令牌,拉取 server.getConfig,
112
+ * 无论成败都吊销该会话。不读取任何凭据或 auth 缓存文件。
113
+ */
114
+ export async function fetchT3AutoConfig({
115
+ env = process.env,
116
+ homeDir = os.homedir(),
117
+ baseDir,
118
+ origin,
119
+ cli,
120
+ run = (file, args, options) => execFileAsync(file, args, options),
121
+ fetchConfig = fetchT3ServerConfig,
122
+ timeoutMs = 15_000,
123
+ platform = process.platform,
124
+ } = {}) {
125
+ const resolvedBase = baseDir ?? env.T3CODE_HOME ?? path.join(homeDir, '.t3');
126
+ const command = cli ?? discoverT3Cli({ env, homeDir });
127
+ const serverOrigin = discoverT3Origin({ baseDir: resolvedBase, origin: origin ?? env.MODELPACE_ORIGIN });
128
+ // Windows 上 npm 装的 t3 是 t3.cmd,Node 只能经 shell 执行批处理,参数需逐个加引号。
129
+ const viaShell = platform === 'win32' && /\.(cmd|bat)$/i.test(command.file);
130
+ const quote = (arg) => `"${String(arg).replace(/"/g, '""')}"`;
131
+ const exec = (args) => {
132
+ const argv = [command.file, ...command.args, ...args, '--base-dir', resolvedBase];
133
+ const [file, ...rest] = viaShell ? argv.map(quote) : argv;
134
+ return run(file, rest, {
135
+ env: { ...env, ...command.env },
136
+ timeout: timeoutMs,
137
+ maxBuffer: 64 * 1024,
138
+ windowsHide: true,
139
+ shell: viaShell,
140
+ });
141
+ };
142
+
143
+ let issued;
144
+ try {
145
+ const { stdout } = await exec(['auth', 'session', 'issue', '--scope', SESSION_SCOPE, '--ttl', SESSION_TTL, '--label', SESSION_LABEL, '--json']);
146
+ issued = JSON.parse(String(stdout));
147
+ } catch {
148
+ throw new T3RpcError('Failed to issue a temporary T3 session via the local T3 CLI', { code: 'T3_ISSUE_FAILED' });
149
+ }
150
+ if (typeof issued?.token !== 'string' || !/^[\w-]+$/.test(issued?.sessionId ?? '')) {
151
+ throw new T3RpcError('The local T3 CLI returned an unexpected session payload', { code: 'T3_ISSUE_FAILED' });
152
+ }
153
+
154
+ try {
155
+ return await fetchConfig({ origin: serverOrigin, bearer: issued.token, timeoutMs });
156
+ } finally {
157
+ // 失败时不掩盖原错误,令牌自身 2 分钟后也会过期。
158
+ await exec(['auth', 'session', 'revoke', issued.sessionId]).catch(() => {});
159
+ }
160
+ }