@4yi-dev/cli 0.1.13 → 0.1.15
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/README.md +3 -0
- package/bin/4yi.mjs +32 -1
- package/package.json +1 -1
- package/src/codex-migrate.mjs +361 -0
- package/src/connect.mjs +26 -10
package/README.md
CHANGED
|
@@ -26,6 +26,7 @@ Both packages install the `4yi` command. The dev package points at `https://xcla
|
|
|
26
26
|
4yi code
|
|
27
27
|
4yi connect claude
|
|
28
28
|
4yi connect codex
|
|
29
|
+
4yi migrate codex
|
|
29
30
|
4yi status all
|
|
30
31
|
4yi restore all
|
|
31
32
|
```
|
|
@@ -40,6 +41,8 @@ On macOS, `4yi connect claude` also configures an installed Claude Desktop throu
|
|
|
40
41
|
|
|
41
42
|
Codex CLI and Codex App share the same Codex home on native Windows (`%USERPROFILE%\\.codex`). After `4yi connect codex`, finish active App tasks, fully quit and reopen the App, and start a new chat so its embedded Codex process loads the new provider. Microsoft Store/AppX installations may not expose a conventional executable path, but that detection does not gate the shared configuration update.
|
|
42
43
|
|
|
44
|
+
Existing Codex tasks keep the provider they were created with. Run `4yi migrate codex`, choose a recent task by number, and 4YI creates a new task with the same history and project using your Plan's default model. The original task is not modified. Scripts can use `--thread <id>` and optionally `--model <id>`.
|
|
45
|
+
|
|
43
46
|
The Codex provider uses the official command-backed authentication configuration. Its helper reads the current token from `~/.4yi/config.json`; `config.toml` and the model catalog do not contain the bearer token.
|
|
44
47
|
|
|
45
48
|
For local development:
|
package/bin/4yi.mjs
CHANGED
|
@@ -2,16 +2,20 @@
|
|
|
2
2
|
import { login, loadSession, clearSession } from "../src/auth.mjs";
|
|
3
3
|
import { runCode } from "../src/opencode.mjs";
|
|
4
4
|
import { connect, connectionStatus, prepareConnectionTools, restoreConnection } from "../src/connect.mjs";
|
|
5
|
+
import { migrateCodexTask } from "../src/codex-migrate.mjs";
|
|
5
6
|
|
|
6
7
|
const command = process.argv[2] || "help";
|
|
7
8
|
|
|
8
9
|
if (command === "help" || command === "--help" || command === "-h") {
|
|
9
|
-
console.log("Usage: 4yi <login|whoami|logout|code|connect|status|restore>");
|
|
10
|
+
console.log("Usage: 4yi <login|whoami|logout|code|connect|migrate|status|restore>");
|
|
10
11
|
console.log(" 4yi code launch OpenCode; switch models live with Tab / /models");
|
|
11
12
|
console.log(" 4yi code --model X pin model X as the default for future sessions");
|
|
12
13
|
console.log(" 4yi connect <claude|codex|all> connect existing coding tools to 4YI");
|
|
13
14
|
console.log(" --yes install a missing CLI without prompting");
|
|
14
15
|
console.log(" Claude on macOS also configures installed Claude Desktop 3P Gateway mode");
|
|
16
|
+
console.log(" 4yi migrate codex continue an existing Codex task through 4YI");
|
|
17
|
+
console.log(" --thread ID select a specific task without prompting");
|
|
18
|
+
console.log(" --model X choose a model (defaults to your Plan model)");
|
|
15
19
|
console.log(" 4yi status [claude|codex|all] inspect the current connection");
|
|
16
20
|
console.log(" 4yi restore <claude|codex|all> restore the latest protected config");
|
|
17
21
|
process.exit(0);
|
|
@@ -39,6 +43,29 @@ function parseConnectArgs(args) {
|
|
|
39
43
|
return { target, scope, platformUrl, claudeBaseUrl, codexBaseUrl, skipCheck, autoInstall };
|
|
40
44
|
}
|
|
41
45
|
|
|
46
|
+
function parseMigrateArgs(args) {
|
|
47
|
+
const target = args[0];
|
|
48
|
+
if (target !== "codex") throw new Error("Use `4yi migrate codex`.");
|
|
49
|
+
let threadId;
|
|
50
|
+
let model;
|
|
51
|
+
for (let i = 1; i < args.length; i += 1) {
|
|
52
|
+
const arg = args[i];
|
|
53
|
+
if (arg === "--thread") {
|
|
54
|
+
threadId = args[++i];
|
|
55
|
+
if (!threadId || threadId.startsWith("-")) throw new Error("--thread requires a task id.");
|
|
56
|
+
}
|
|
57
|
+
else if (arg.startsWith("--thread=")) threadId = arg.slice("--thread=".length);
|
|
58
|
+
else if (arg === "--model" || arg === "-m") {
|
|
59
|
+
model = args[++i];
|
|
60
|
+
if (!model || model.startsWith("-")) throw new Error("--model requires a model id.");
|
|
61
|
+
}
|
|
62
|
+
else if (arg.startsWith("--model=")) model = arg.slice("--model=".length);
|
|
63
|
+
else throw new Error(`Unknown option: ${arg}`);
|
|
64
|
+
}
|
|
65
|
+
if (threadId === "" || model === "") throw new Error("--thread and --model require a value.");
|
|
66
|
+
return { threadId, model };
|
|
67
|
+
}
|
|
68
|
+
|
|
42
69
|
/** Split out `--model <id>` / `--model=<id>` / `-m <id>`; the rest pass through to OpenCode. */
|
|
43
70
|
function parseCodeArgs(args) {
|
|
44
71
|
let preferredModel = null;
|
|
@@ -87,6 +114,10 @@ try {
|
|
|
87
114
|
session = loadSession();
|
|
88
115
|
}
|
|
89
116
|
await connect({ session, ...connectArgs, skipToolCheck: true });
|
|
117
|
+
} else if (command === "migrate") {
|
|
118
|
+
const migrateArgs = parseMigrateArgs(process.argv.slice(3));
|
|
119
|
+
const session = loadSession();
|
|
120
|
+
await migrateCodexTask({ session, ...migrateArgs });
|
|
90
121
|
} else if (command === "status") {
|
|
91
122
|
const { target, scope } = parseConnectArgs(process.argv.slice(3));
|
|
92
123
|
connectionStatus({ target, scope });
|
package/package.json
CHANGED
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import process from "node:process";
|
|
5
|
+
import { spawn as nodeSpawn } from "node:child_process";
|
|
6
|
+
import { createInterface } from "node:readline/promises";
|
|
7
|
+
import { requestJson } from "./http.mjs";
|
|
8
|
+
|
|
9
|
+
const DEFAULT_LIMIT = 10;
|
|
10
|
+
const REQUEST_TIMEOUT_MS = 15_000;
|
|
11
|
+
const SESSION_SCAN_LIMIT = 500;
|
|
12
|
+
const SESSION_PREFIX_BYTES = 256 * 1024;
|
|
13
|
+
|
|
14
|
+
function executableName(command, platform = process.platform) {
|
|
15
|
+
return platform === "win32" ? `${command}.cmd` : command;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function appServerLaunch({ command, args, env, platform }) {
|
|
19
|
+
if (platform !== "win32") return { command, args, shell: false };
|
|
20
|
+
// Node 24 warns when `shell: true` receives an argv array (DEP0190). Invoke
|
|
21
|
+
// cmd.exe explicitly with constant, non-user-controlled arguments instead.
|
|
22
|
+
const shell = env.ComSpec || env.COMSPEC || "cmd.exe";
|
|
23
|
+
return { command: shell, args: ["/d", "/s", "/c", `${command} ${args.join(" ")}`], shell: false };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function oneLine(value, fallback) {
|
|
27
|
+
const line = String(value || "").split(/\r?\n/, 1)[0].replace(/\s+/g, " ").trim();
|
|
28
|
+
if (!line) return fallback;
|
|
29
|
+
return line.length > 64 ? `${line.slice(0, 61)}...` : line;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function relativeTime(timestamp, now = Date.now()) {
|
|
33
|
+
const elapsed = Math.max(0, Math.floor(now / 1000) - Number(timestamp || 0));
|
|
34
|
+
if (elapsed < 60) return "刚刚";
|
|
35
|
+
if (elapsed < 3600) return `${Math.floor(elapsed / 60)} 分钟前`;
|
|
36
|
+
if (elapsed < 86400) return `${Math.floor(elapsed / 3600)} 小时前`;
|
|
37
|
+
if (elapsed < 86400 * 30) return `${Math.floor(elapsed / 86400)} 天前`;
|
|
38
|
+
return new Date(Number(timestamp) * 1000).toLocaleDateString();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function codexHomeForEnv(env = process.env) {
|
|
42
|
+
if (env.CODEX_HOME) return env.CODEX_HOME;
|
|
43
|
+
const home = env.HOME || env.USERPROFILE || os.homedir();
|
|
44
|
+
return path.join(home, ".codex");
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function collectSessionFiles(root) {
|
|
48
|
+
const files = [];
|
|
49
|
+
const pending = [root];
|
|
50
|
+
while (pending.length > 0) {
|
|
51
|
+
const directory = pending.pop();
|
|
52
|
+
let entries;
|
|
53
|
+
try { entries = fs.readdirSync(directory, { withFileTypes: true }); } catch { continue; }
|
|
54
|
+
for (const entry of entries) {
|
|
55
|
+
const file = path.join(directory, entry.name);
|
|
56
|
+
if (entry.isDirectory()) pending.push(file);
|
|
57
|
+
else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
|
|
58
|
+
try { files.push({ file, mtimeMs: fs.statSync(file).mtimeMs }); } catch { /* Ignore a file removed during scanning. */ }
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return files.sort((left, right) => right.mtimeMs - left.mtimeMs).slice(0, SESSION_SCAN_LIMIT);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function readFilePrefix(file) {
|
|
66
|
+
const descriptor = fs.openSync(file, "r");
|
|
67
|
+
try {
|
|
68
|
+
const buffer = Buffer.alloc(SESSION_PREFIX_BYTES);
|
|
69
|
+
const bytes = fs.readSync(descriptor, buffer, 0, buffer.length, 0);
|
|
70
|
+
return buffer.toString("utf8", 0, bytes);
|
|
71
|
+
} finally {
|
|
72
|
+
fs.closeSync(descriptor);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function messageText(payload) {
|
|
77
|
+
if (payload?.type === "message" && payload.role === "user") {
|
|
78
|
+
if (typeof payload.content === "string") return payload.content;
|
|
79
|
+
if (Array.isArray(payload.content)) {
|
|
80
|
+
return payload.content
|
|
81
|
+
.map((item) => item?.text || item?.input_text || "")
|
|
82
|
+
.filter(Boolean)
|
|
83
|
+
.join(" ");
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (payload?.type === "user_message") return payload.message || payload.text || "";
|
|
87
|
+
return "";
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function sessionThreadFromFile({ file, mtimeMs }) {
|
|
91
|
+
let text;
|
|
92
|
+
try { text = readFilePrefix(file); } catch { return null; }
|
|
93
|
+
let metadata;
|
|
94
|
+
let preview = "";
|
|
95
|
+
for (const line of text.split(/\r?\n/)) {
|
|
96
|
+
if (!line.trim()) continue;
|
|
97
|
+
let record;
|
|
98
|
+
try { record = JSON.parse(line); } catch { continue; }
|
|
99
|
+
if (record.type === "session_meta") metadata = record.payload;
|
|
100
|
+
if (!preview && (record.type === "response_item" || record.type === "event_msg")) {
|
|
101
|
+
preview = messageText(record.payload);
|
|
102
|
+
}
|
|
103
|
+
if (metadata && preview) break;
|
|
104
|
+
}
|
|
105
|
+
const id = metadata?.id || metadata?.session_id;
|
|
106
|
+
if (!id) return null;
|
|
107
|
+
const created = Date.parse(metadata.timestamp || "");
|
|
108
|
+
return {
|
|
109
|
+
id,
|
|
110
|
+
modelProvider: metadata.model_provider || metadata.modelProvider || "openai",
|
|
111
|
+
cwd: metadata.cwd || "",
|
|
112
|
+
preview,
|
|
113
|
+
createdAt: Number.isFinite(created) ? Math.floor(created / 1000) : Math.floor(mtimeMs / 1000),
|
|
114
|
+
updatedAt: Math.floor(mtimeMs / 1000),
|
|
115
|
+
recencyAt: Math.floor(mtimeMs / 1000),
|
|
116
|
+
ephemeral: false,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function scanCodexSessionThreads({ codexHome = codexHomeForEnv() } = {}) {
|
|
121
|
+
const sessions = path.join(codexHome, "sessions");
|
|
122
|
+
return collectSessionFiles(sessions).map(sessionThreadFromFile).filter(Boolean);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function mergeCandidateThreads(serverThreads, sessionThreads, limit) {
|
|
126
|
+
const threads = new Map();
|
|
127
|
+
for (const thread of sessionThreads) if (thread?.id) threads.set(thread.id, thread);
|
|
128
|
+
for (const thread of serverThreads) if (thread?.id) threads.set(thread.id, { ...threads.get(thread.id), ...thread });
|
|
129
|
+
return [...threads.values()]
|
|
130
|
+
.filter((thread) => thread.modelProvider !== "4yi" && !thread.ephemeral)
|
|
131
|
+
.sort((left, right) => {
|
|
132
|
+
const leftTime = left.recencyAt || left.updatedAt || left.createdAt || 0;
|
|
133
|
+
const rightTime = right.recencyAt || right.updatedAt || right.createdAt || 0;
|
|
134
|
+
return rightTime - leftTime;
|
|
135
|
+
})
|
|
136
|
+
.slice(0, limit);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function describeCodexThread(thread, { now = Date.now() } = {}) {
|
|
140
|
+
const title = oneLine(thread.name || thread.preview, "未命名任务");
|
|
141
|
+
const project = path.basename(String(thread.cwd || "")) || String(thread.cwd || "未知项目");
|
|
142
|
+
const updatedAt = thread.recencyAt || thread.updatedAt || thread.createdAt;
|
|
143
|
+
return { title, project, age: relativeTime(updatedAt, now) };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export async function selectCodexThread(threads, {
|
|
147
|
+
input = process.stdin,
|
|
148
|
+
output = process.stdout,
|
|
149
|
+
now = Date.now(),
|
|
150
|
+
} = {}) {
|
|
151
|
+
if (!input?.isTTY || !output?.isTTY) {
|
|
152
|
+
throw new Error("Interactive task selection requires a terminal. Use --thread <id> in scripts.");
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
output.write("选择要迁移到 4YI 的 Codex 任务:\n\n");
|
|
156
|
+
threads.forEach((thread, index) => {
|
|
157
|
+
const item = describeCodexThread(thread, { now });
|
|
158
|
+
output.write(`${index + 1}. ${item.title}\n ${item.project} · ${item.age}\n`);
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
const readline = createInterface({ input, output });
|
|
162
|
+
try {
|
|
163
|
+
while (true) {
|
|
164
|
+
const answer = await readline.question("\n输入序号(默认 1,q 取消):");
|
|
165
|
+
const value = answer.trim().toLowerCase();
|
|
166
|
+
if (value === "q" || value === "quit") return null;
|
|
167
|
+
const index = value === "" ? 0 : Number(value) - 1;
|
|
168
|
+
if (Number.isInteger(index) && index >= 0 && index < threads.length) return threads[index];
|
|
169
|
+
output.write(`请输入 1-${threads.length} 之间的序号。\n`);
|
|
170
|
+
}
|
|
171
|
+
} finally {
|
|
172
|
+
readline.close();
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export class CodexAppServerClient {
|
|
177
|
+
constructor({
|
|
178
|
+
command = executableName("codex"),
|
|
179
|
+
args = ["app-server", "--stdio"],
|
|
180
|
+
env = process.env,
|
|
181
|
+
platform = process.platform,
|
|
182
|
+
spawn = nodeSpawn,
|
|
183
|
+
timeoutMs = REQUEST_TIMEOUT_MS,
|
|
184
|
+
} = {}) {
|
|
185
|
+
this.nextId = 1;
|
|
186
|
+
this.pending = new Map();
|
|
187
|
+
this.stderr = "";
|
|
188
|
+
this.timeoutMs = timeoutMs;
|
|
189
|
+
const launch = appServerLaunch({ command, args, env, platform });
|
|
190
|
+
this.child = spawn(launch.command, launch.args, {
|
|
191
|
+
env,
|
|
192
|
+
shell: launch.shell,
|
|
193
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
let stdoutBuffer = "";
|
|
197
|
+
this.child.stdout.setEncoding("utf8");
|
|
198
|
+
this.child.stdout.on("data", (chunk) => {
|
|
199
|
+
stdoutBuffer += chunk;
|
|
200
|
+
const lines = stdoutBuffer.split(/\r?\n/);
|
|
201
|
+
stdoutBuffer = lines.pop() || "";
|
|
202
|
+
for (const line of lines) this.#handleLine(line);
|
|
203
|
+
});
|
|
204
|
+
this.child.stderr.setEncoding("utf8");
|
|
205
|
+
this.child.stderr.on("data", (chunk) => {
|
|
206
|
+
this.stderr = `${this.stderr}${chunk}`.slice(-4000);
|
|
207
|
+
});
|
|
208
|
+
this.child.on("error", (error) => this.#rejectAll(error));
|
|
209
|
+
this.child.on("exit", (code, signal) => {
|
|
210
|
+
if (this.pending.size === 0) return;
|
|
211
|
+
const detail = this.stderr.trim();
|
|
212
|
+
const exitReason = signal || (code ?? "unknown");
|
|
213
|
+
this.#rejectAll(new Error(`Codex app-server stopped (${exitReason}).${detail ? ` ${detail}` : ""}`));
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
#handleLine(line) {
|
|
218
|
+
if (!line.trim()) return;
|
|
219
|
+
let message;
|
|
220
|
+
try { message = JSON.parse(line); } catch { return; }
|
|
221
|
+
if (message.id === undefined || message.id === null) return;
|
|
222
|
+
const pending = this.pending.get(message.id);
|
|
223
|
+
if (!pending) return;
|
|
224
|
+
this.pending.delete(message.id);
|
|
225
|
+
clearTimeout(pending.timer);
|
|
226
|
+
if (message.error) {
|
|
227
|
+
const text = message.error.message || JSON.stringify(message.error);
|
|
228
|
+
pending.reject(new Error(text));
|
|
229
|
+
} else {
|
|
230
|
+
pending.resolve(message.result);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
#rejectAll(error) {
|
|
235
|
+
for (const pending of this.pending.values()) {
|
|
236
|
+
clearTimeout(pending.timer);
|
|
237
|
+
pending.reject(error);
|
|
238
|
+
}
|
|
239
|
+
this.pending.clear();
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
request(method, params = {}) {
|
|
243
|
+
const id = this.nextId++;
|
|
244
|
+
return new Promise((resolve, reject) => {
|
|
245
|
+
const timer = setTimeout(() => {
|
|
246
|
+
this.pending.delete(id);
|
|
247
|
+
reject(new Error(`Codex app-server timed out while calling ${method}.`));
|
|
248
|
+
}, this.timeoutMs);
|
|
249
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
250
|
+
this.child.stdin.write(`${JSON.stringify({ id, method, params })}\n`, (error) => {
|
|
251
|
+
if (!error) return;
|
|
252
|
+
clearTimeout(timer);
|
|
253
|
+
this.pending.delete(id);
|
|
254
|
+
reject(error);
|
|
255
|
+
});
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
notify(method, params = {}) {
|
|
260
|
+
this.child.stdin.write(`${JSON.stringify({ method, params })}\n`);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
async initialize() {
|
|
264
|
+
const result = await this.request("initialize", {
|
|
265
|
+
clientInfo: { name: "4yi-cli", version: "0.1.0" },
|
|
266
|
+
capabilities: { experimentalApi: true },
|
|
267
|
+
});
|
|
268
|
+
this.notify("initialized", {});
|
|
269
|
+
return result;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
async close() {
|
|
273
|
+
this.child.stdin.end();
|
|
274
|
+
if (this.child.exitCode !== null) return;
|
|
275
|
+
await new Promise((resolve) => {
|
|
276
|
+
const timer = setTimeout(() => {
|
|
277
|
+
this.child.kill();
|
|
278
|
+
resolve();
|
|
279
|
+
}, 1000);
|
|
280
|
+
this.child.once("exit", () => {
|
|
281
|
+
clearTimeout(timer);
|
|
282
|
+
resolve();
|
|
283
|
+
});
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
async function loadDefaultCodexModel(session) {
|
|
289
|
+
const response = await requestJson(session.baseUrl, "/api/cli/models?runtime=codex", { token: session.token });
|
|
290
|
+
const ids = (response?.models || []).map((model) => model?.id).filter(Boolean);
|
|
291
|
+
if (ids.length === 0) throw new Error("Your active Plan has no Codex-compatible Responses models.");
|
|
292
|
+
return ids.includes(response.default_model) ? response.default_model : ids[0];
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
export async function migrateCodexTask({
|
|
296
|
+
session,
|
|
297
|
+
threadId,
|
|
298
|
+
model,
|
|
299
|
+
limit = DEFAULT_LIMIT,
|
|
300
|
+
input = process.stdin,
|
|
301
|
+
output = process.stdout,
|
|
302
|
+
stdout = console.log,
|
|
303
|
+
client,
|
|
304
|
+
clientOptions = {},
|
|
305
|
+
selectThread = selectCodexThread,
|
|
306
|
+
scanThreads = scanCodexSessionThreads,
|
|
307
|
+
} = {}) {
|
|
308
|
+
if (!session?.token) throw new Error("Not signed in. Run `4yi login`.");
|
|
309
|
+
const selectedModel = model || await loadDefaultCodexModel(session);
|
|
310
|
+
const appServer = client || new CodexAppServerClient(clientOptions);
|
|
311
|
+
try {
|
|
312
|
+
await appServer.initialize();
|
|
313
|
+
let selected;
|
|
314
|
+
if (threadId) {
|
|
315
|
+
selected = { id: threadId };
|
|
316
|
+
} else {
|
|
317
|
+
const response = await appServer.request("thread/list", {
|
|
318
|
+
limit: Math.max(limit * 3, 30),
|
|
319
|
+
sortKey: "updated_at",
|
|
320
|
+
sortDirection: "desc",
|
|
321
|
+
});
|
|
322
|
+
const sessionThreads = scanThreads({ codexHome: codexHomeForEnv(clientOptions.env || process.env) });
|
|
323
|
+
const candidates = mergeCandidateThreads(response?.data || [], sessionThreads, limit);
|
|
324
|
+
if (candidates.length === 0) {
|
|
325
|
+
throw new Error("没有自动找到可迁移的旧 Codex 任务。新任务已经会默认使用 4YI;如已知任务 ID,可运行 `4yi migrate codex --thread <任务ID>`。");
|
|
326
|
+
}
|
|
327
|
+
selected = await selectThread(candidates, { input, output });
|
|
328
|
+
if (!selected) {
|
|
329
|
+
stdout("已取消,没有修改任何任务。");
|
|
330
|
+
return { cancelled: true };
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
stdout(`正在创建新的 4YI 任务(${selectedModel})…`);
|
|
335
|
+
const result = await appServer.request("thread/fork", {
|
|
336
|
+
threadId: selected.id,
|
|
337
|
+
model: selectedModel,
|
|
338
|
+
modelProvider: "4yi",
|
|
339
|
+
excludeTurns: true,
|
|
340
|
+
});
|
|
341
|
+
if (!result?.thread?.id) throw new Error("Codex did not return the migrated task id.");
|
|
342
|
+
if (result.modelProvider !== "4yi" && result.thread.modelProvider !== "4yi") {
|
|
343
|
+
throw new Error("Codex created the task but did not apply the 4YI provider.");
|
|
344
|
+
}
|
|
345
|
+
stdout("✓ 已创建新的 4YI 任务,原任务未修改。");
|
|
346
|
+
stdout(`新任务 ID: ${result.thread.id}`);
|
|
347
|
+
return { cancelled: false, sourceThreadId: selected.id, threadId: result.thread.id, model: selectedModel };
|
|
348
|
+
} finally {
|
|
349
|
+
if (!client) await appServer.close();
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
export const __testing = {
|
|
354
|
+
appServerLaunch,
|
|
355
|
+
codexHomeForEnv,
|
|
356
|
+
loadDefaultCodexModel,
|
|
357
|
+
mergeCandidateThreads,
|
|
358
|
+
relativeTime,
|
|
359
|
+
scanCodexSessionThreads,
|
|
360
|
+
sessionThreadFromFile,
|
|
361
|
+
};
|
package/src/connect.mjs
CHANGED
|
@@ -97,10 +97,21 @@ function executableName(command, platform = process.platform) {
|
|
|
97
97
|
return platform === "win32" ? `${command}.cmd` : command;
|
|
98
98
|
}
|
|
99
99
|
|
|
100
|
-
function
|
|
101
|
-
|
|
100
|
+
function commandLaunch(command, args, { platform = process.platform, env = process.env } = {}) {
|
|
101
|
+
if (platform !== "win32") return { command, args, shell: false };
|
|
102
|
+
// Avoid Node 24 DEP0190 by invoking cmd.exe explicitly. Every token passed
|
|
103
|
+
// here is owned by the CLI (tool names, fixed flags, and npm package names),
|
|
104
|
+
// never user input.
|
|
105
|
+
const shell = env.ComSpec || env.COMSPEC || "cmd.exe";
|
|
106
|
+
return { command: shell, args: ["/d", "/s", "/c", `${command} ${args.join(" ")}`], shell: false };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function commandAvailable(command, { platform = process.platform, env = process.env, spawn = spawnSync } = {}) {
|
|
110
|
+
const launch = commandLaunch(executableName(command, platform), ["--version"], { platform, env });
|
|
111
|
+
const result = spawn(launch.command, launch.args, {
|
|
102
112
|
encoding: "utf8",
|
|
103
|
-
|
|
113
|
+
env,
|
|
114
|
+
shell: launch.shell,
|
|
104
115
|
stdio: "ignore",
|
|
105
116
|
});
|
|
106
117
|
return !result.error && result.status === 0;
|
|
@@ -123,29 +134,32 @@ async function ensureToolCli(target, {
|
|
|
123
134
|
input = process.stdin,
|
|
124
135
|
output = process.stdout,
|
|
125
136
|
platform = process.platform,
|
|
137
|
+
env = process.env,
|
|
126
138
|
spawn = spawnSync,
|
|
127
139
|
stdout = console.log,
|
|
128
140
|
} = {}) {
|
|
129
141
|
const meta = TOOL_METADATA[target];
|
|
130
|
-
if (commandAvailable(meta.command, { platform, spawn })) return { installed: false };
|
|
142
|
+
if (commandAvailable(meta.command, { platform, env, spawn })) return { installed: false };
|
|
131
143
|
|
|
132
144
|
const approved = autoInstall || await confirmInstall(meta, { input, output });
|
|
133
145
|
if (!approved) {
|
|
134
146
|
throw new Error(`${meta.label} CLI is required. Install it with \`npm install -g ${meta.npmPackage}\`, then run this command again.`);
|
|
135
147
|
}
|
|
136
|
-
if (!commandAvailable("npm", { platform, spawn })) {
|
|
148
|
+
if (!commandAvailable("npm", { platform, env, spawn })) {
|
|
137
149
|
throw new Error(`npm is required to install ${meta.label} CLI automatically. Install Node.js/npm, then run this command again.`);
|
|
138
150
|
}
|
|
139
151
|
|
|
140
152
|
stdout(`Installing ${meta.label} CLI (${meta.npmPackage})...`);
|
|
141
|
-
const
|
|
142
|
-
|
|
153
|
+
const launch = commandLaunch(executableName("npm", platform), ["install", "-g", meta.npmPackage], { platform, env });
|
|
154
|
+
const result = spawn(launch.command, launch.args, {
|
|
155
|
+
env,
|
|
156
|
+
shell: launch.shell,
|
|
143
157
|
stdio: "inherit",
|
|
144
158
|
});
|
|
145
159
|
if (result.error || result.status !== 0) {
|
|
146
160
|
throw new Error(`Could not install ${meta.label} CLI automatically. Run \`npm install -g ${meta.npmPackage}\` and try again.`);
|
|
147
161
|
}
|
|
148
|
-
if (!commandAvailable(meta.command, { platform, spawn })) {
|
|
162
|
+
if (!commandAvailable(meta.command, { platform, env, spawn })) {
|
|
149
163
|
throw new Error(`${meta.label} CLI was installed, but \`${meta.command}\` is not available in this terminal. Open a new terminal and run this command again.`);
|
|
150
164
|
}
|
|
151
165
|
stdout(`${meta.label} CLI installed.`);
|
|
@@ -448,9 +462,10 @@ function escapeRegExp(value) {
|
|
|
448
462
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
449
463
|
}
|
|
450
464
|
|
|
451
|
-
function parseBundledCatalog({ platform = process.platform, spawn = spawnSync } = {}) {
|
|
465
|
+
function parseBundledCatalog({ platform = process.platform, env = process.env, spawn = spawnSync } = {}) {
|
|
452
466
|
const command = executableName("codex", platform);
|
|
453
|
-
const
|
|
467
|
+
const launch = commandLaunch(command, ["debug", "models", "--bundled"], { platform, env });
|
|
468
|
+
const result = spawn(launch.command, launch.args, { encoding: "utf8", env, shell: launch.shell });
|
|
454
469
|
if (result.status !== 0 || !result.stdout) throw new Error("Codex CLI is required to build its 4YI model catalog. Install Codex, then run this command again.");
|
|
455
470
|
const catalog = JSON.parse(result.stdout);
|
|
456
471
|
const template = catalog.models?.find((model) => model.slug === "gpt-5.5") || catalog.models?.[0];
|
|
@@ -693,6 +708,7 @@ export const __testing = {
|
|
|
693
708
|
buildCodexCatalog,
|
|
694
709
|
checkCodex,
|
|
695
710
|
commandAvailable,
|
|
711
|
+
commandLaunch,
|
|
696
712
|
desktopAppCandidates,
|
|
697
713
|
ensureToolCli,
|
|
698
714
|
executableName,
|