@wu529778790/open-im 1.11.8-beta.6 → 1.11.8-beta.8
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/dist/adapters/codebuddy-adapter.js +3 -17
- package/dist/adapters/codex-adapter.js +3 -16
- package/dist/adapters/opencode-adapter.js +3 -16
- package/dist/codebuddy/cli-runner.d.ts +2 -22
- package/dist/codebuddy/cli-runner.js +9 -27
- package/dist/codex/cli-runner.d.ts +2 -22
- package/dist/codex/cli-runner.js +24 -75
- package/dist/commands/handler.d.ts +1 -0
- package/dist/commands/handler.js +34 -0
- package/dist/config/types.d.ts +19 -0
- package/dist/config-web-auth.d.ts +13 -0
- package/dist/config-web-auth.js +114 -0
- package/dist/config-web-browser.d.ts +4 -0
- package/dist/config-web-browser.js +48 -0
- package/dist/config-web-cors.d.ts +5 -0
- package/dist/config-web-cors.js +48 -0
- package/dist/config-web-health.d.ts +7 -0
- package/dist/config-web-health.js +65 -0
- package/dist/config-web-http.d.ts +3 -0
- package/dist/config-web-http.js +31 -0
- package/dist/config-web-payload.d.ts +84 -0
- package/dist/config-web-payload.js +260 -0
- package/dist/config-web-probes.d.ts +2 -0
- package/dist/config-web-probes.js +271 -0
- package/dist/config-web.d.ts +3 -11
- package/dist/config-web.js +17 -814
- package/dist/config.js +20 -1
- package/dist/constants.d.ts +10 -0
- package/dist/constants.js +11 -0
- package/dist/opencode/cli-runner.d.ts +2 -22
- package/dist/opencode/cli-runner.js +47 -68
- package/dist/opencode/sdk-runner.d.ts +2 -22
- package/dist/opencode/sdk-runner.js +2 -1
- package/dist/platform/handle-ai-request.js +18 -1
- package/dist/shared/ai-task.d.ts +15 -0
- package/dist/shared/ai-task.js +171 -1
- package/dist/shared/cli-runner-base.d.ts +39 -0
- package/dist/shared/cli-runner-base.js +108 -0
- package/dist/shared/session-invalid-detector.d.ts +5 -0
- package/dist/shared/session-invalid-detector.js +20 -0
- package/package.json +1 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { runCodeBuddy } from '../codebuddy/cli-runner.js';
|
|
2
|
+
import { isSessionInvalidMessage } from '../shared/session-invalid-detector.js';
|
|
2
3
|
export class CodeBuddyAdapter {
|
|
3
4
|
cliPath;
|
|
4
5
|
toolId = 'codebuddy';
|
|
@@ -10,25 +11,10 @@ export class CodeBuddyAdapter {
|
|
|
10
11
|
onText: callbacks.onText,
|
|
11
12
|
onThinking: callbacks.onThinking,
|
|
12
13
|
onToolUse: callbacks.onToolUse,
|
|
13
|
-
onComplete:
|
|
14
|
-
const result = {
|
|
15
|
-
success: raw.success,
|
|
16
|
-
result: raw.result,
|
|
17
|
-
accumulated: raw.accumulated,
|
|
18
|
-
cost: raw.cost,
|
|
19
|
-
durationMs: raw.durationMs,
|
|
20
|
-
model: raw.model,
|
|
21
|
-
numTurns: raw.numTurns,
|
|
22
|
-
toolStats: raw.toolStats,
|
|
23
|
-
};
|
|
24
|
-
callbacks.onComplete(result);
|
|
25
|
-
},
|
|
14
|
+
onComplete: callbacks.onComplete,
|
|
26
15
|
onError: (err) => {
|
|
27
16
|
const msg = typeof err === 'string' ? err : String(err);
|
|
28
|
-
const friendly = msg
|
|
29
|
-
msg.includes('Session not found') ||
|
|
30
|
-
msg.includes('Invalid session') ||
|
|
31
|
-
msg.includes('Unable to resume')
|
|
17
|
+
const friendly = isSessionInvalidMessage(msg)
|
|
32
18
|
? 'CodeBuddy 会话已失效,旧 session 已清理。请直接重试当前请求。'
|
|
33
19
|
: msg;
|
|
34
20
|
callbacks.onError(friendly);
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* Codex Adapter - run tasks through OpenAI Codex CLI (`codex exec`)
|
|
3
3
|
*/
|
|
4
4
|
import { runCodex } from "../codex/cli-runner.js";
|
|
5
|
+
import { isSessionInvalidMessage } from "../shared/session-invalid-detector.js";
|
|
5
6
|
export class CodexAdapter {
|
|
6
7
|
cliPath;
|
|
7
8
|
toolId = "codex";
|
|
@@ -21,24 +22,10 @@ export class CodexAdapter {
|
|
|
21
22
|
onText: callbacks.onText,
|
|
22
23
|
onThinking: callbacks.onThinking,
|
|
23
24
|
onToolUse: callbacks.onToolUse,
|
|
24
|
-
onComplete:
|
|
25
|
-
const result = {
|
|
26
|
-
success: raw.success,
|
|
27
|
-
result: raw.result,
|
|
28
|
-
accumulated: raw.accumulated,
|
|
29
|
-
cost: raw.cost,
|
|
30
|
-
durationMs: raw.durationMs,
|
|
31
|
-
model: raw.model,
|
|
32
|
-
numTurns: raw.numTurns,
|
|
33
|
-
toolStats: raw.toolStats,
|
|
34
|
-
};
|
|
35
|
-
callbacks.onComplete(result);
|
|
36
|
-
},
|
|
25
|
+
onComplete: callbacks.onComplete,
|
|
37
26
|
onError: (err) => {
|
|
38
27
|
const msg = typeof err === "string" ? err : String(err);
|
|
39
|
-
const friendly = msg
|
|
40
|
-
msg.includes("No conversation found") ||
|
|
41
|
-
msg.includes("Unable to find session")
|
|
28
|
+
const friendly = isSessionInvalidMessage(msg)
|
|
42
29
|
? "Codex 会话已失效,旧 session 已清理。请直接重试当前请求。"
|
|
43
30
|
: msg;
|
|
44
31
|
callbacks.onError(friendly);
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { runOpenCodeSdk } from '../opencode/sdk-runner.js';
|
|
2
|
+
import { isSessionInvalidMessage } from '../shared/session-invalid-detector.js';
|
|
2
3
|
export class OpenCodeAdapter {
|
|
3
4
|
toolId = 'opencode';
|
|
4
5
|
run(prompt, sessionId, workDir, callbacks, options) {
|
|
@@ -6,24 +7,10 @@ export class OpenCodeAdapter {
|
|
|
6
7
|
onText: callbacks.onText,
|
|
7
8
|
onThinking: callbacks.onThinking,
|
|
8
9
|
onToolUse: callbacks.onToolUse,
|
|
9
|
-
onComplete:
|
|
10
|
-
const result = {
|
|
11
|
-
success: raw.success,
|
|
12
|
-
result: raw.result,
|
|
13
|
-
accumulated: raw.accumulated,
|
|
14
|
-
cost: raw.cost,
|
|
15
|
-
durationMs: raw.durationMs,
|
|
16
|
-
model: raw.model,
|
|
17
|
-
numTurns: raw.numTurns,
|
|
18
|
-
toolStats: raw.toolStats,
|
|
19
|
-
};
|
|
20
|
-
callbacks.onComplete(result);
|
|
21
|
-
},
|
|
10
|
+
onComplete: callbacks.onComplete,
|
|
22
11
|
onError: (err) => {
|
|
23
12
|
const msg = typeof err === 'string' ? err : String(err);
|
|
24
|
-
const friendly = msg
|
|
25
|
-
msg.includes('Session not found') ||
|
|
26
|
-
msg.includes('no sessions found')
|
|
13
|
+
const friendly = isSessionInvalidMessage(msg)
|
|
27
14
|
? 'OpenCode 会话已失效,旧 session 已清理。请直接重试当前请求。'
|
|
28
15
|
: msg;
|
|
29
16
|
callbacks.onError(friendly);
|
|
@@ -1,29 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
onText: (accumulated: string) => void;
|
|
3
|
-
onThinking?: (accumulated: string) => void;
|
|
4
|
-
onToolUse?: (toolName: string, toolInput?: Record<string, unknown>) => void;
|
|
5
|
-
onComplete: (result: {
|
|
6
|
-
success: boolean;
|
|
7
|
-
result: string;
|
|
8
|
-
accumulated: string;
|
|
9
|
-
cost: number;
|
|
10
|
-
durationMs: number;
|
|
11
|
-
model?: string;
|
|
12
|
-
numTurns: number;
|
|
13
|
-
toolStats: Record<string, number>;
|
|
14
|
-
}) => void;
|
|
15
|
-
onError: (error: string) => void;
|
|
16
|
-
onSessionId?: (sessionId: string) => void;
|
|
17
|
-
onSessionInvalid?: () => void;
|
|
18
|
-
}
|
|
1
|
+
import type { RunCallbacks, RunHandle } from '../adapters/tool-adapter.interface.js';
|
|
19
2
|
export interface CodeBuddyRunOptions {
|
|
20
3
|
skipPermissions?: boolean;
|
|
21
4
|
permissionMode?: 'default' | 'acceptEdits' | 'plan';
|
|
22
5
|
model?: string;
|
|
23
6
|
}
|
|
24
|
-
export interface CodeBuddyRunHandle {
|
|
25
|
-
abort: () => void;
|
|
26
|
-
}
|
|
27
7
|
export declare function buildCodeBuddyArgs(prompt: string, sessionId: string | undefined, options?: CodeBuddyRunOptions): string[];
|
|
28
8
|
export declare function extractBufferedPayloads(state: {
|
|
29
9
|
buffer: string;
|
|
@@ -41,4 +21,4 @@ export declare function flushBufferedPayloads(state: {
|
|
|
41
21
|
* - 其他情况 → 拼接(不丢内容)
|
|
42
22
|
*/
|
|
43
23
|
export declare function mergeAssistantReply(previous: string, incoming: string): string;
|
|
44
|
-
export declare function runCodeBuddy(cliPath: string, prompt: string, sessionId: string | undefined, workDir: string, callbacks:
|
|
24
|
+
export declare function runCodeBuddy(cliPath: string, prompt: string, sessionId: string | undefined, workDir: string, callbacks: RunCallbacks, options?: CodeBuddyRunOptions): RunHandle;
|
|
@@ -2,8 +2,9 @@ import { execFileSync, spawn } from 'node:child_process';
|
|
|
2
2
|
import { accessSync, constants } from 'node:fs';
|
|
3
3
|
import { isAbsolute, join } from 'node:path';
|
|
4
4
|
import { createLogger } from '../logger.js';
|
|
5
|
-
import { processEnvForNonClaudeCliChild } from '../config/file-io.js';
|
|
6
5
|
import { killProcessTree, trackChild } from '../shared/process-kill.js';
|
|
6
|
+
import { isSessionInvalidMessage } from '../shared/session-invalid-detector.js';
|
|
7
|
+
import { clearWallClockTimeout, buildBaseSpawnOptions } from '../shared/cli-runner-base.js';
|
|
7
8
|
const log = createLogger('CodeBuddyCli');
|
|
8
9
|
export function buildCodeBuddyArgs(prompt, sessionId, options) {
|
|
9
10
|
const args = ['--print', '--output-format', 'stream-json'];
|
|
@@ -190,24 +191,12 @@ export function runCodeBuddy(cliPath, prompt, sessionId, workDir, callbacks, opt
|
|
|
190
191
|
...options,
|
|
191
192
|
permissionMode: normalizePermissionMode(options?.permissionMode),
|
|
192
193
|
});
|
|
193
|
-
const env = processEnvForNonClaudeCliChild();
|
|
194
|
-
if (process.platform === 'win32') {
|
|
195
|
-
env.LANG = env.LANG || 'C.UTF-8';
|
|
196
|
-
env.LC_ALL = env.LC_ALL || 'C.UTF-8';
|
|
197
|
-
}
|
|
198
194
|
const isCmd = process.platform === 'win32' && (/\.(cmd|bat)$/i.test(normalizedCliPath) ||
|
|
199
195
|
normalizedCliPath === 'codebuddy');
|
|
200
196
|
const spawnCmd = isCmd ? 'cmd.exe' : normalizedCliPath;
|
|
201
197
|
const spawnArgs = isCmd ? ['/c', normalizedCliPath, ...args] : args;
|
|
202
198
|
log.info(`Spawning CodeBuddy CLI: path=${normalizedCliPath}, cwd=${workDir}, session=${sessionId ?? 'new'}, args=${args.join(' ')}`);
|
|
203
|
-
const child = spawn(spawnCmd, spawnArgs,
|
|
204
|
-
cwd: workDir,
|
|
205
|
-
// Unix 上放入独立进程组,使 abort/关停能用 process.kill(-pid) 杀掉整棵子树(含 MCP/shell 孙进程)
|
|
206
|
-
detached: process.platform !== 'win32',
|
|
207
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
208
|
-
env,
|
|
209
|
-
windowsHide: process.platform === 'win32',
|
|
210
|
-
});
|
|
199
|
+
const child = spawn(spawnCmd, spawnArgs, buildBaseSpawnOptions(workDir, ['ignore', 'pipe', 'pipe']));
|
|
211
200
|
trackChild(child);
|
|
212
201
|
let cliTimeoutHandle = null;
|
|
213
202
|
let accumulated = '';
|
|
@@ -222,7 +211,7 @@ export function runCodeBuddy(cliPath, prompt, sessionId, workDir, callbacks, opt
|
|
|
222
211
|
const MAX_STDERR = 8 * 1024;
|
|
223
212
|
let stderrText = '';
|
|
224
213
|
const handleErrorText = (message) => {
|
|
225
|
-
if (sessionId &&
|
|
214
|
+
if (sessionId && isSessionInvalidMessage(message)) {
|
|
226
215
|
callbacks.onSessionInvalid?.();
|
|
227
216
|
}
|
|
228
217
|
callbacks.onError(message);
|
|
@@ -317,10 +306,8 @@ export function runCodeBuddy(cliPath, prompt, sessionId, workDir, callbacks, opt
|
|
|
317
306
|
}
|
|
318
307
|
});
|
|
319
308
|
child.on('close', (code) => {
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
cliTimeoutHandle = null;
|
|
323
|
-
}
|
|
309
|
+
clearWallClockTimeout(cliTimeoutHandle);
|
|
310
|
+
cliTimeoutHandle = null;
|
|
324
311
|
if (completed)
|
|
325
312
|
return;
|
|
326
313
|
if (stdoutState.buffer.trim()) {
|
|
@@ -353,10 +340,8 @@ export function runCodeBuddy(cliPath, prompt, sessionId, workDir, callbacks, opt
|
|
|
353
340
|
});
|
|
354
341
|
});
|
|
355
342
|
child.on('error', (err) => {
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
cliTimeoutHandle = null;
|
|
359
|
-
}
|
|
343
|
+
clearWallClockTimeout(cliTimeoutHandle);
|
|
344
|
+
cliTimeoutHandle = null;
|
|
360
345
|
if (completed)
|
|
361
346
|
return;
|
|
362
347
|
completed = true;
|
|
@@ -378,10 +363,7 @@ export function runCodeBuddy(cliPath, prompt, sessionId, workDir, callbacks, opt
|
|
|
378
363
|
if (completed)
|
|
379
364
|
return;
|
|
380
365
|
completed = true;
|
|
381
|
-
|
|
382
|
-
clearTimeout(cliTimeoutHandle);
|
|
383
|
-
cliTimeoutHandle = null;
|
|
384
|
-
}
|
|
366
|
+
clearWallClockTimeout(cliTimeoutHandle);
|
|
385
367
|
killProcessTree(child);
|
|
386
368
|
},
|
|
387
369
|
};
|
|
@@ -1,24 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Codex CLI runner for `codex exec --json` JSONL output.
|
|
3
3
|
*/
|
|
4
|
-
|
|
5
|
-
onText: (accumulated: string) => void;
|
|
6
|
-
onThinking?: (accumulated: string) => void;
|
|
7
|
-
onToolUse?: (toolName: string, toolInput?: Record<string, unknown>) => void;
|
|
8
|
-
onComplete: (result: {
|
|
9
|
-
success: boolean;
|
|
10
|
-
result: string;
|
|
11
|
-
accumulated: string;
|
|
12
|
-
cost: number;
|
|
13
|
-
durationMs: number;
|
|
14
|
-
model?: string;
|
|
15
|
-
numTurns: number;
|
|
16
|
-
toolStats: Record<string, number>;
|
|
17
|
-
}) => void;
|
|
18
|
-
onError: (error: string) => void;
|
|
19
|
-
onSessionId?: (sessionId: string) => void;
|
|
20
|
-
onSessionInvalid?: () => void;
|
|
21
|
-
}
|
|
4
|
+
import type { RunCallbacks, RunHandle } from '../adapters/tool-adapter.interface.js';
|
|
22
5
|
export interface CodexRunOptions {
|
|
23
6
|
skipPermissions?: boolean;
|
|
24
7
|
permissionMode?: 'default' | 'acceptEdits' | 'plan';
|
|
@@ -27,9 +10,6 @@ export interface CodexRunOptions {
|
|
|
27
10
|
hookPort?: number;
|
|
28
11
|
proxy?: string;
|
|
29
12
|
}
|
|
30
|
-
export interface CodexRunHandle {
|
|
31
|
-
abort: () => void;
|
|
32
|
-
}
|
|
33
13
|
export declare function extractPromptImagePaths(prompt: string): string[];
|
|
34
14
|
export declare function buildCodexArgs(prompt: string, sessionId: string | undefined, workDir: string, options?: CodexRunOptions): string[];
|
|
35
|
-
export declare function runCodex(cliPath: string, prompt: string, sessionId: string | undefined, workDir: string, callbacks:
|
|
15
|
+
export declare function runCodex(cliPath: string, prompt: string, sessionId: string | undefined, workDir: string, callbacks: RunCallbacks, options?: CodexRunOptions): RunHandle;
|
package/dist/codex/cli-runner.js
CHANGED
|
@@ -6,8 +6,9 @@ import { existsSync, readFileSync } from 'node:fs';
|
|
|
6
6
|
import { dirname, join } from 'node:path';
|
|
7
7
|
import { createInterface } from 'node:readline';
|
|
8
8
|
import { createLogger } from '../logger.js';
|
|
9
|
-
import { processEnvForNonClaudeCliChild } from '../config/file-io.js';
|
|
10
9
|
import { killProcessTree, trackChild } from '../shared/process-kill.js';
|
|
10
|
+
import { isSessionInvalidMessage } from '../shared/session-invalid-detector.js';
|
|
11
|
+
import { createStderrBuffer, appendStderr, reconstructStderr, createFinalizeGate, isFinalizeReady, clearWallClockTimeout, buildBaseSpawnOptions, } from '../shared/cli-runner-base.js';
|
|
11
12
|
const log = createLogger('CodexCli');
|
|
12
13
|
const windowsCodexLaunchCache = new Map();
|
|
13
14
|
const SUPPORTED_IMAGE_EXTENSIONS = new Set([
|
|
@@ -163,22 +164,18 @@ function resolveWindowsCodexLaunch(cliPath, args) {
|
|
|
163
164
|
}
|
|
164
165
|
export function runCodex(cliPath, prompt, sessionId, workDir, callbacks, options) {
|
|
165
166
|
const args = buildCodexArgs(prompt, sessionId, workDir, options);
|
|
166
|
-
const
|
|
167
|
+
const extraEnv = {};
|
|
167
168
|
if (options?.chatId)
|
|
168
|
-
|
|
169
|
+
extraEnv.CC_IM_CHAT_ID = options.chatId;
|
|
169
170
|
if (options?.hookPort)
|
|
170
|
-
|
|
171
|
+
extraEnv.CC_IM_HOOK_PORT = String(options.hookPort);
|
|
171
172
|
if (options?.proxy) {
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
}
|
|
179
|
-
if (process.platform === 'win32') {
|
|
180
|
-
env.LANG = env.LANG || 'C.UTF-8';
|
|
181
|
-
env.LC_ALL = env.LC_ALL || 'C.UTF-8';
|
|
173
|
+
extraEnv.HTTPS_PROXY = options.proxy;
|
|
174
|
+
extraEnv.HTTP_PROXY = options.proxy;
|
|
175
|
+
extraEnv.https_proxy = options.proxy;
|
|
176
|
+
extraEnv.http_proxy = options.proxy;
|
|
177
|
+
extraEnv.ALL_PROXY = options.proxy;
|
|
178
|
+
extraEnv.all_proxy = options.proxy;
|
|
182
179
|
}
|
|
183
180
|
const argsForLog = args.join(' ');
|
|
184
181
|
log.info(`Spawning Codex CLI: path=${cliPath}, cwd=${workDir}, session=${sessionId ?? 'new'}, args=${argsForLog}`);
|
|
@@ -200,14 +197,7 @@ export function runCodex(cliPath, prompt, sessionId, workDir, callbacks, options
|
|
|
200
197
|
`chcp 65001>nul && ${formatWindowsCommandName(cliPath)} ${args.map(quoteForWindowsCmd).join(' ')}`,
|
|
201
198
|
]
|
|
202
199
|
: args;
|
|
203
|
-
const child = spawn(spawnCmd, spawnArgs,
|
|
204
|
-
cwd: workDir,
|
|
205
|
-
// Unix 上放入独立进程组,使 abort/关停能用 process.kill(-pid) 杀掉整棵子树(含 MCP/shell 孙进程)
|
|
206
|
-
detached: process.platform !== 'win32',
|
|
207
|
-
stdio: ['pipe', 'pipe', 'pipe'],
|
|
208
|
-
env,
|
|
209
|
-
windowsHide: process.platform === 'win32',
|
|
210
|
-
});
|
|
200
|
+
const child = spawn(spawnCmd, spawnArgs, buildBaseSpawnOptions(workDir, ['pipe', 'pipe', 'pipe'], extraEnv));
|
|
211
201
|
trackChild(child);
|
|
212
202
|
child.stdin?.write(prompt);
|
|
213
203
|
child.stdin?.end();
|
|
@@ -217,27 +207,10 @@ export function runCodex(cliPath, prompt, sessionId, workDir, callbacks, options
|
|
|
217
207
|
const toolStats = {};
|
|
218
208
|
const startTime = Date.now();
|
|
219
209
|
const rl = createInterface({ input: child.stdout });
|
|
220
|
-
const
|
|
221
|
-
const MAX_STDERR_TAIL = 6 * 1024;
|
|
222
|
-
let stderrHead = '';
|
|
223
|
-
let stderrTail = '';
|
|
224
|
-
let stderrTotal = 0;
|
|
225
|
-
let stderrHeadFull = false;
|
|
210
|
+
const stderrBuf = createStderrBuffer();
|
|
226
211
|
child.stderr?.on('data', (chunk) => {
|
|
227
212
|
const text = chunk.toString();
|
|
228
|
-
|
|
229
|
-
if (!stderrHeadFull) {
|
|
230
|
-
const room = MAX_STDERR_HEAD - stderrHead.length;
|
|
231
|
-
if (room > 0) {
|
|
232
|
-
stderrHead += text.slice(0, room);
|
|
233
|
-
if (stderrHead.length >= MAX_STDERR_HEAD)
|
|
234
|
-
stderrHeadFull = true;
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
stderrTail += text;
|
|
238
|
-
if (stderrTail.length > MAX_STDERR_TAIL) {
|
|
239
|
-
stderrTail = stderrTail.slice(-MAX_STDERR_TAIL);
|
|
240
|
-
}
|
|
213
|
+
appendStderr(stderrBuf, text);
|
|
241
214
|
log.debug(`[stderr] ${text.trimEnd()}`);
|
|
242
215
|
});
|
|
243
216
|
rl.on('line', (line) => {
|
|
@@ -329,38 +302,18 @@ export function runCodex(cliPath, prompt, sessionId, workDir, callbacks, options
|
|
|
329
302
|
}
|
|
330
303
|
});
|
|
331
304
|
let exitCode = null;
|
|
332
|
-
|
|
333
|
-
let childClosed = false;
|
|
305
|
+
const gate = createFinalizeGate();
|
|
334
306
|
let cliTimeoutHandle = null;
|
|
335
307
|
const finalize = () => {
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
}
|
|
340
|
-
if (!rlClosed || !childClosed)
|
|
308
|
+
clearWallClockTimeout(cliTimeoutHandle);
|
|
309
|
+
cliTimeoutHandle = null;
|
|
310
|
+
if (!isFinalizeReady(gate))
|
|
341
311
|
return;
|
|
342
312
|
if (completed)
|
|
343
313
|
return;
|
|
344
314
|
if (exitCode !== null && exitCode !== 0) {
|
|
345
|
-
|
|
346
|
-
if (
|
|
347
|
-
if (!stderrHeadFull) {
|
|
348
|
-
errMsg = stderrHead;
|
|
349
|
-
}
|
|
350
|
-
else if (stderrTotal <= MAX_STDERR_HEAD + MAX_STDERR_TAIL) {
|
|
351
|
-
errMsg = stderrHead + stderrTail.slice(stderrTail.length - (stderrTotal - MAX_STDERR_HEAD));
|
|
352
|
-
}
|
|
353
|
-
else {
|
|
354
|
-
errMsg =
|
|
355
|
-
stderrHead +
|
|
356
|
-
`\n\n... (omitted ${stderrTotal - MAX_STDERR_HEAD - MAX_STDERR_TAIL} bytes) ...\n\n` +
|
|
357
|
-
stderrTail;
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
if (sessionId &&
|
|
361
|
-
(errMsg.includes('No session found') ||
|
|
362
|
-
errMsg.includes('No conversation found') ||
|
|
363
|
-
errMsg.includes('Unable to find session'))) {
|
|
315
|
+
const errMsg = reconstructStderr(stderrBuf);
|
|
316
|
+
if (sessionId && isSessionInvalidMessage(errMsg)) {
|
|
364
317
|
callbacks.onSessionInvalid?.();
|
|
365
318
|
}
|
|
366
319
|
callbacks.onError(errMsg || `Codex CLI exited with code ${exitCode}`);
|
|
@@ -379,11 +332,11 @@ export function runCodex(cliPath, prompt, sessionId, workDir, callbacks, options
|
|
|
379
332
|
child.on('close', (code) => {
|
|
380
333
|
log.info(`Codex CLI closed: exitCode=${code}, pid=${child.pid}`);
|
|
381
334
|
exitCode = code;
|
|
382
|
-
childClosed = true;
|
|
335
|
+
gate.childClosed = true;
|
|
383
336
|
finalize();
|
|
384
337
|
});
|
|
385
338
|
rl.on('close', () => {
|
|
386
|
-
rlClosed = true;
|
|
339
|
+
gate.rlClosed = true;
|
|
387
340
|
finalize();
|
|
388
341
|
});
|
|
389
342
|
child.on('error', (err) => {
|
|
@@ -393,7 +346,7 @@ export function runCodex(cliPath, prompt, sessionId, workDir, callbacks, options
|
|
|
393
346
|
completed = true;
|
|
394
347
|
callbacks.onError(`Failed to start Codex CLI: ${err.message}`);
|
|
395
348
|
}
|
|
396
|
-
childClosed = true;
|
|
349
|
+
gate.childClosed = true;
|
|
397
350
|
finalize();
|
|
398
351
|
});
|
|
399
352
|
// 墙钟超时:防止 CLI 挂死(网络卡住、工具死循环等)永久占用用户队列槽
|
|
@@ -401,7 +354,6 @@ export function runCodex(cliPath, prompt, sessionId, workDir, callbacks, options
|
|
|
401
354
|
cliTimeoutHandle = setTimeout(() => {
|
|
402
355
|
if (completed)
|
|
403
356
|
return;
|
|
404
|
-
log.warn(`Codex CLI 超过 ${cliTimeoutMs}ms,强制终止 (pid=${child.pid})`);
|
|
405
357
|
completed = true;
|
|
406
358
|
rl.close();
|
|
407
359
|
killProcessTree(child);
|
|
@@ -413,10 +365,7 @@ export function runCodex(cliPath, prompt, sessionId, workDir, callbacks, options
|
|
|
413
365
|
if (completed)
|
|
414
366
|
return;
|
|
415
367
|
completed = true;
|
|
416
|
-
|
|
417
|
-
clearTimeout(cliTimeoutHandle);
|
|
418
|
-
cliTimeoutHandle = null;
|
|
419
|
-
}
|
|
368
|
+
clearWallClockTimeout(cliTimeoutHandle);
|
|
420
369
|
rl.close();
|
|
421
370
|
killProcessTree(child);
|
|
422
371
|
},
|
|
@@ -23,6 +23,7 @@ export declare class CommandHandler {
|
|
|
23
23
|
dispatch(text: string, chatId: string, userId: string, platform: Platform, handleClaudeRequest: ClaudeRequestHandler,
|
|
24
24
|
/** 若提供,本条消息的斜杠命令回复走此 sender(须与 handleTextFlow 的 sendTextReply 一致,如带 msgId)。 */
|
|
25
25
|
senderOverride?: MessageSender): Promise<boolean>;
|
|
26
|
+
private handleAutopilotStatus;
|
|
26
27
|
private handleHelp;
|
|
27
28
|
private handlePlugins;
|
|
28
29
|
private handleSessions;
|
package/dist/commands/handler.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { resolvePlatformAiCommand } from '../config.js';
|
|
2
2
|
import { escapePathForMarkdown } from '../shared/utils.js';
|
|
3
|
+
import { getAutopilotPendingStatus } from '../shared/ai-task.js';
|
|
3
4
|
import { TERMINAL_ONLY_COMMANDS } from '../constants.js';
|
|
4
5
|
import { createLogger } from '../logger.js';
|
|
5
6
|
import { ClaudeSDKAdapter } from '../adapters/claude-sdk-adapter.js';
|
|
@@ -103,6 +104,8 @@ export class CommandHandler {
|
|
|
103
104
|
return this.handlePwd(chatId, userId);
|
|
104
105
|
if (t === '/status')
|
|
105
106
|
return this.handleStatus(chatId, userId, platform);
|
|
107
|
+
if (t === '/autopilot')
|
|
108
|
+
return this.handleAutopilotStatus(chatId, userId);
|
|
106
109
|
// 快捷命令 — 直接发送预设 prompt 给 AI
|
|
107
110
|
if (t === '/git commit')
|
|
108
111
|
return this.handleQuickCommand(chatId, userId, 'git commit -m "AI generated commit"', platform);
|
|
@@ -133,6 +136,36 @@ export class CommandHandler {
|
|
|
133
136
|
}
|
|
134
137
|
return runBody();
|
|
135
138
|
}
|
|
139
|
+
async handleAutopilotStatus(chatId, userId) {
|
|
140
|
+
const ap = this.deps.config.autopilot;
|
|
141
|
+
const lines = [
|
|
142
|
+
'🤖 限流自动恢复 (Autopilot)',
|
|
143
|
+
'',
|
|
144
|
+
`状态: ${ap.enabled ? '✅ 已启用' : '❌ 已禁用'}`,
|
|
145
|
+
`最大重试: ${ap.maxRetries} 次`,
|
|
146
|
+
`默认等待: ${ap.defaultIntervalHours} 小时`,
|
|
147
|
+
`短延迟: ${ap.shortRetrySeconds} 秒`,
|
|
148
|
+
`恢复提示: "${ap.autoResumePrompt}"`,
|
|
149
|
+
];
|
|
150
|
+
const pending = getAutopilotPendingStatus(userId);
|
|
151
|
+
if (pending) {
|
|
152
|
+
const remaining = Math.max(pending.retryAt.getTime() - Date.now(), 0);
|
|
153
|
+
const hours = Math.floor(remaining / 3600000);
|
|
154
|
+
const minutes = Math.floor((remaining % 3600000) / 60000);
|
|
155
|
+
lines.push('');
|
|
156
|
+
lines.push('⏳ 当前等待中:');
|
|
157
|
+
lines.push(` 类型: ${pending.type}`);
|
|
158
|
+
lines.push(` 恢复时间: ${pending.retryAt.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}`);
|
|
159
|
+
lines.push(` 剩余: ${hours > 0 ? `${hours}小时` : ''}${minutes}分钟`);
|
|
160
|
+
lines.push(` 重试次数: ${pending.retryCount}/${ap.maxRetries}`);
|
|
161
|
+
}
|
|
162
|
+
else {
|
|
163
|
+
lines.push('');
|
|
164
|
+
lines.push('当前无等待中的限流恢复任务。');
|
|
165
|
+
}
|
|
166
|
+
await this.replySender().sendTextReply(chatId, lines.join('\n'));
|
|
167
|
+
return true;
|
|
168
|
+
}
|
|
136
169
|
async handleHelp(chatId) {
|
|
137
170
|
const help = [
|
|
138
171
|
'📋 可用命令:',
|
|
@@ -151,6 +184,7 @@ export class CommandHandler {
|
|
|
151
184
|
'/status - 显示状态',
|
|
152
185
|
'/cd <路径> - 切换工作目录',
|
|
153
186
|
'/pwd - 当前工作目录',
|
|
187
|
+
'/autopilot - 查看限流自动恢复状态',
|
|
154
188
|
'',
|
|
155
189
|
'⚡ 快捷命令:',
|
|
156
190
|
'/git commit - 提交代码',
|
package/dist/config/types.d.ts
CHANGED
|
@@ -53,6 +53,17 @@ export interface Config {
|
|
|
53
53
|
/** 可选 Bearer,与采集端一致 */
|
|
54
54
|
token?: string;
|
|
55
55
|
};
|
|
56
|
+
/**
|
|
57
|
+
* 限流自动恢复(Autopilot)。
|
|
58
|
+
* 当 AI 工具遇到限流错误时,自动等待并在恢复后重试。
|
|
59
|
+
*/
|
|
60
|
+
autopilot: {
|
|
61
|
+
enabled: boolean;
|
|
62
|
+
maxRetries: number;
|
|
63
|
+
defaultIntervalHours: number;
|
|
64
|
+
shortRetrySeconds: number;
|
|
65
|
+
autoResumePrompt: string;
|
|
66
|
+
};
|
|
56
67
|
platforms: {
|
|
57
68
|
telegram?: {
|
|
58
69
|
enabled: boolean;
|
|
@@ -176,6 +187,14 @@ export interface FileToolClaude {
|
|
|
176
187
|
proxy?: string;
|
|
177
188
|
/** Claude API 配置(优先级:环境变量 > tools.claude.env > ~/.claude/settings.json) */
|
|
178
189
|
env?: Record<string, string>;
|
|
190
|
+
/** 限流自动恢复配置 */
|
|
191
|
+
autopilot?: {
|
|
192
|
+
enabled?: boolean;
|
|
193
|
+
maxRetries?: number;
|
|
194
|
+
defaultIntervalHours?: number;
|
|
195
|
+
shortRetrySeconds?: number;
|
|
196
|
+
autoResumePrompt?: string;
|
|
197
|
+
};
|
|
179
198
|
}
|
|
180
199
|
export interface FileToolCodex {
|
|
181
200
|
cliPath?: string;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { IncomingMessage } from "node:http";
|
|
2
|
+
export interface LoginTokenInfo {
|
|
3
|
+
expiresAt: number;
|
|
4
|
+
}
|
|
5
|
+
export declare function getWebConfigHost(): string;
|
|
6
|
+
/** 设为 true 时,非本机绑定的 Web 配置服务跳过登录 Cookie 校验(仅适用于受信网络;生产建议配合 HTTPS 反向代理) */
|
|
7
|
+
export declare function allowRemoteApiWithoutAuth(): boolean;
|
|
8
|
+
export declare function consumeLoginToken(loginToken: string): LoginTokenInfo | undefined;
|
|
9
|
+
export declare function createLoginToken(ttlMs: number): string;
|
|
10
|
+
export declare function createSession(request: IncomingMessage, ttlMs: number): string;
|
|
11
|
+
export declare function isSessionValid(request: IncomingMessage): boolean;
|
|
12
|
+
export declare function buildSessionCookie(sessionId: string, ttlMs: number): string;
|
|
13
|
+
export declare function generateLoginUrl(host: string, port: number, loginTtlMs: number): string;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
const pendingLogins = new Map();
|
|
3
|
+
const activeSessions = new Map();
|
|
4
|
+
export function getWebConfigHost() {
|
|
5
|
+
const envHost = process.env.OPEN_IM_WEB_HOST?.trim();
|
|
6
|
+
if (envHost)
|
|
7
|
+
return envHost;
|
|
8
|
+
return "127.0.0.1";
|
|
9
|
+
}
|
|
10
|
+
/** 设为 true 时,非本机绑定的 Web 配置服务跳过登录 Cookie 校验(仅适用于受信网络;生产建议配合 HTTPS 反向代理) */
|
|
11
|
+
export function allowRemoteApiWithoutAuth() {
|
|
12
|
+
return process.env.OPEN_IM_ALLOW_REMOTE_API === "true";
|
|
13
|
+
}
|
|
14
|
+
function generateRandomToken(bytes = 32) {
|
|
15
|
+
return randomBytes(bytes).toString("base64url");
|
|
16
|
+
}
|
|
17
|
+
function cleanupExpiredAuth(now) {
|
|
18
|
+
for (const [token, info] of pendingLogins) {
|
|
19
|
+
if (info.expiresAt <= now)
|
|
20
|
+
pendingLogins.delete(token);
|
|
21
|
+
}
|
|
22
|
+
for (const [sessionId, info] of activeSessions) {
|
|
23
|
+
if (info.expiresAt <= now)
|
|
24
|
+
activeSessions.delete(sessionId);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
export function consumeLoginToken(loginToken) {
|
|
28
|
+
const info = pendingLogins.get(loginToken);
|
|
29
|
+
if (!info)
|
|
30
|
+
return undefined;
|
|
31
|
+
pendingLogins.delete(loginToken);
|
|
32
|
+
const now = Date.now();
|
|
33
|
+
if (info.expiresAt <= now)
|
|
34
|
+
return undefined;
|
|
35
|
+
return info;
|
|
36
|
+
}
|
|
37
|
+
export function createLoginToken(ttlMs) {
|
|
38
|
+
const now = Date.now();
|
|
39
|
+
cleanupExpiredAuth(now);
|
|
40
|
+
const token = generateRandomToken(32);
|
|
41
|
+
pendingLogins.set(token, { expiresAt: now + ttlMs });
|
|
42
|
+
return token;
|
|
43
|
+
}
|
|
44
|
+
export function createSession(request, ttlMs) {
|
|
45
|
+
const now = Date.now();
|
|
46
|
+
cleanupExpiredAuth(now);
|
|
47
|
+
const sessionId = generateRandomToken(32);
|
|
48
|
+
const remoteAddr = request.socket.remoteAddress;
|
|
49
|
+
const userAgent = typeof request.headers["user-agent"] === "string" ? request.headers["user-agent"] : undefined;
|
|
50
|
+
activeSessions.set(sessionId, {
|
|
51
|
+
expiresAt: now + ttlMs,
|
|
52
|
+
remoteAddr,
|
|
53
|
+
userAgent,
|
|
54
|
+
});
|
|
55
|
+
return sessionId;
|
|
56
|
+
}
|
|
57
|
+
function parseCookies(request) {
|
|
58
|
+
const header = request.headers.cookie;
|
|
59
|
+
if (!header)
|
|
60
|
+
return {};
|
|
61
|
+
const cookies = {};
|
|
62
|
+
const parts = header.split(";");
|
|
63
|
+
for (const part of parts) {
|
|
64
|
+
const [rawKey, ...rest] = part.split("=");
|
|
65
|
+
const key = rawKey.trim();
|
|
66
|
+
if (!key)
|
|
67
|
+
continue;
|
|
68
|
+
const value = rest.join("=").trim();
|
|
69
|
+
cookies[key] = decodeURIComponent(value);
|
|
70
|
+
}
|
|
71
|
+
return cookies;
|
|
72
|
+
}
|
|
73
|
+
function getSessionIdFromRequest(request) {
|
|
74
|
+
const cookies = parseCookies(request);
|
|
75
|
+
const sessionId = cookies.openim_session;
|
|
76
|
+
return sessionId && typeof sessionId === "string" && sessionId.length > 0 ? sessionId : null;
|
|
77
|
+
}
|
|
78
|
+
export function isSessionValid(request) {
|
|
79
|
+
const sessionId = getSessionIdFromRequest(request);
|
|
80
|
+
if (!sessionId)
|
|
81
|
+
return false;
|
|
82
|
+
const info = activeSessions.get(sessionId);
|
|
83
|
+
if (!info)
|
|
84
|
+
return false;
|
|
85
|
+
const now = Date.now();
|
|
86
|
+
if (info.expiresAt <= now) {
|
|
87
|
+
activeSessions.delete(sessionId);
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
// Optional: tie session to basic client fingerprint (remote address)
|
|
91
|
+
const remoteAddr = request.socket.remoteAddress;
|
|
92
|
+
if (info.remoteAddr && remoteAddr && remoteAddr !== info.remoteAddr) {
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
export function buildSessionCookie(sessionId, ttlMs) {
|
|
98
|
+
const maxAgeSec = Math.floor(ttlMs / 1000);
|
|
99
|
+
const parts = [
|
|
100
|
+
`openim_session=${encodeURIComponent(sessionId)}`,
|
|
101
|
+
"Path=/",
|
|
102
|
+
"HttpOnly",
|
|
103
|
+
"SameSite=Lax",
|
|
104
|
+
`Max-Age=${maxAgeSec}`,
|
|
105
|
+
];
|
|
106
|
+
// 不设置 Secure,方便本地 http 使用;如果放在 https 反代后,可以在代理层加 Secure
|
|
107
|
+
return parts.join("; ");
|
|
108
|
+
}
|
|
109
|
+
export function generateLoginUrl(host, port, loginTtlMs) {
|
|
110
|
+
const loginToken = createLoginToken(loginTtlMs);
|
|
111
|
+
const displayHost = host === "0.0.0.0" ? "127.0.0.1" : host;
|
|
112
|
+
const baseUrl = `http://${displayHost}:${port}`;
|
|
113
|
+
return `${baseUrl}/?login_token=${encodeURIComponent(loginToken)}`;
|
|
114
|
+
}
|