@ktkid/kmh-subagent-team 0.0.0-stage → 0.1.1
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 +38 -2
- package/cordis.patch.yml +4 -0
- package/lib/src/acp/client.d.ts +35 -0
- package/lib/src/acp/client.js +343 -0
- package/lib/src/acp/process.d.ts +22 -0
- package/lib/src/acp/process.js +146 -0
- package/lib/src/acp/protocol.d.ts +66 -0
- package/lib/src/acp/protocol.js +193 -0
- package/lib/src/adapters/agy.d.ts +2 -0
- package/lib/src/adapters/agy.js +99 -0
- package/lib/src/adapters/codex.d.ts +14 -0
- package/lib/src/adapters/codex.js +168 -0
- package/lib/src/adapters/grok.d.ts +2 -0
- package/lib/src/adapters/grok.js +147 -0
- package/lib/src/adapters/registry.d.ts +3 -0
- package/lib/src/adapters/registry.js +64 -0
- package/lib/src/adapters/types.d.ts +59 -0
- package/lib/src/adapters/types.js +141 -0
- package/lib/src/adapters/workbuddy-auth.d.ts +6 -0
- package/lib/src/adapters/workbuddy-auth.js +116 -0
- package/lib/src/adapters/workbuddy.d.ts +9 -0
- package/lib/src/adapters/workbuddy.js +179 -0
- package/lib/src/adapters/zcode.d.ts +51 -0
- package/lib/src/adapters/zcode.js +226 -0
- package/lib/src/config.d.ts +46 -0
- package/lib/src/config.js +82 -0
- package/lib/src/index.d.ts +10 -0
- package/lib/src/index.js +184 -0
- package/lib/src/prompt.d.ts +4 -0
- package/lib/src/prompt.js +30 -0
- package/lib/src/runtime/approval.d.ts +29 -0
- package/lib/src/runtime/approval.js +88 -0
- package/lib/src/runtime/manager.d.ts +65 -0
- package/lib/src/runtime/manager.js +270 -0
- package/package.json +56 -4
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
const tokenCount = z.number().int().nonnegative();
|
|
3
|
+
const rawUsageSchema = z.object({
|
|
4
|
+
inputTokens: tokenCount,
|
|
5
|
+
outputTokens: tokenCount,
|
|
6
|
+
totalTokens: tokenCount.optional(),
|
|
7
|
+
cachedReadTokens: tokenCount.default(0),
|
|
8
|
+
cacheCreationTokens: tokenCount.default(0),
|
|
9
|
+
reasoningTokens: tokenCount.optional(),
|
|
10
|
+
usageIsIncomplete: z.boolean().optional(),
|
|
11
|
+
});
|
|
12
|
+
/** 读取 JSON-RPC 消息的请求/响应 ID(同时兼容 number 与 string)。 */
|
|
13
|
+
export function jsonRpcIdOf(message) {
|
|
14
|
+
const id = asRecord(message)?.["id"];
|
|
15
|
+
if (typeof id === "number" && Number.isFinite(id))
|
|
16
|
+
return id;
|
|
17
|
+
if (typeof id === "string" && id !== "")
|
|
18
|
+
return id;
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
/** 读取 JSON-RPC 错误信息。 */
|
|
22
|
+
export function rpcErrorMessage(message) {
|
|
23
|
+
const err = asRecord(asRecord(message)?.["error"]);
|
|
24
|
+
if (err === undefined)
|
|
25
|
+
return undefined;
|
|
26
|
+
return nonEmptyString(err["message"]) ?? "未知 JSON-RPC 错误";
|
|
27
|
+
}
|
|
28
|
+
/** 读取 sessionId(兼容顶层 result.sessionId)。 */
|
|
29
|
+
export function sessionIdOf(message) {
|
|
30
|
+
return nonEmptyString(asRecord(asRecord(message)?.["result"])?.["sessionId"]);
|
|
31
|
+
}
|
|
32
|
+
/** 读取 session/prompt 回执里的 stopReason。 */
|
|
33
|
+
export function stopReasonOf(message) {
|
|
34
|
+
return nonEmptyString(asRecord(asRecord(message)?.["result"])?.["stopReason"]);
|
|
35
|
+
}
|
|
36
|
+
/** 解析 session/update 通知中的正文、思考增量与工具调用记录。 */
|
|
37
|
+
export function parseSessionUpdate(message) {
|
|
38
|
+
const row = asRecord(message);
|
|
39
|
+
if (row?.["method"] !== "session/update")
|
|
40
|
+
return undefined;
|
|
41
|
+
const update = asRecord(asRecord(row["params"])?.["update"]);
|
|
42
|
+
if (update === undefined)
|
|
43
|
+
return undefined;
|
|
44
|
+
const kind = update["sessionUpdate"];
|
|
45
|
+
if (kind === "agent_message_chunk" || kind === "agent_thought_chunk") {
|
|
46
|
+
const text = nonEmptyString(asRecord(update["content"])?.["text"]);
|
|
47
|
+
if (text === undefined)
|
|
48
|
+
return undefined;
|
|
49
|
+
return {
|
|
50
|
+
kind: kind === "agent_message_chunk" ? "text" : "reasoning",
|
|
51
|
+
text,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
if (kind === "tool_call" || kind === "tool_call_update") {
|
|
55
|
+
const toolCallId = nonEmptyString(update["toolCallId"]);
|
|
56
|
+
const toolKind = nonEmptyString(update["kind"]);
|
|
57
|
+
const title = nonEmptyString(update["title"]) ?? toolKind ?? "tool_call";
|
|
58
|
+
const status = nonEmptyString(update["status"]);
|
|
59
|
+
return {
|
|
60
|
+
kind: "tool",
|
|
61
|
+
tool: {
|
|
62
|
+
title,
|
|
63
|
+
...(toolCallId === undefined ? {} : { toolCallId }),
|
|
64
|
+
...(toolKind === undefined ? {} : { kind: toolKind }),
|
|
65
|
+
...(status === undefined ? {} : { status }),
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
/** 解析子 ACP 发来的 session/request_permission 请求(支持 number/string id)。 */
|
|
72
|
+
export function parsePermissionRequest(message) {
|
|
73
|
+
const row = asRecord(message);
|
|
74
|
+
if (row?.["method"] !== "session/request_permission")
|
|
75
|
+
return undefined;
|
|
76
|
+
const id = jsonRpcIdOf(row);
|
|
77
|
+
if (id === undefined)
|
|
78
|
+
return undefined;
|
|
79
|
+
const params = asRecord(row["params"]);
|
|
80
|
+
const sessionId = nonEmptyString(params?.["sessionId"]);
|
|
81
|
+
if (sessionId === undefined)
|
|
82
|
+
return undefined;
|
|
83
|
+
const tool = asRecord(params?.["toolCall"]);
|
|
84
|
+
const toolCallId = nonEmptyString(tool?.["toolCallId"]);
|
|
85
|
+
const toolKind = nonEmptyString(tool?.["kind"]);
|
|
86
|
+
const title = nonEmptyString(tool?.["title"]) ?? toolKind ?? "外部工具操作";
|
|
87
|
+
const options = parseOptions(params?.["options"]);
|
|
88
|
+
if (options.length === 0)
|
|
89
|
+
return undefined;
|
|
90
|
+
return {
|
|
91
|
+
id,
|
|
92
|
+
sessionId,
|
|
93
|
+
title,
|
|
94
|
+
options,
|
|
95
|
+
...(toolCallId === undefined ? {} : { toolCallId }),
|
|
96
|
+
...(toolKind === undefined ? {} : { kind: toolKind }),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* 安全映射审批决策到 ACP outcome(约束 C2):
|
|
101
|
+
* - cancel 一律返回 cancelled;
|
|
102
|
+
* - allow 仅匹配 kind 含 allow 的选项(优先 allow_once),找不到则 cancelled;
|
|
103
|
+
* - reject 仅匹配 kind 含 reject 的选项,找不到时固定返回 cancelled,绝不兜底选 options[0]。
|
|
104
|
+
*/
|
|
105
|
+
export function selectPermissionOutcome(decision, options) {
|
|
106
|
+
if (decision === "cancel")
|
|
107
|
+
return { outcome: "cancelled" };
|
|
108
|
+
if (decision === "allow") {
|
|
109
|
+
const once = options.find((opt) => opt.kind === "allow_once");
|
|
110
|
+
const anyAllow = options.find((opt) => opt.kind.includes("allow"));
|
|
111
|
+
const chosen = once ?? anyAllow;
|
|
112
|
+
return chosen === undefined
|
|
113
|
+
? { outcome: "cancelled" }
|
|
114
|
+
: { outcome: "selected", optionId: chosen.optionId };
|
|
115
|
+
}
|
|
116
|
+
const rejectOpt = options.find((opt) => opt.kind === "reject_once") ??
|
|
117
|
+
options.find((opt) => opt.kind.includes("reject"));
|
|
118
|
+
return rejectOpt === undefined
|
|
119
|
+
? { outcome: "cancelled" }
|
|
120
|
+
: { outcome: "selected", optionId: rejectOpt.optionId };
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* 从 session/prompt 回执提取并归一化 token 用量(约束 C4:不捏造估算值)。
|
|
124
|
+
* grok 口径下 inputTokens 已包含缓存读写,需扣减后填入 DSH 互斥输入桶。
|
|
125
|
+
*/
|
|
126
|
+
export function extractPromptUsage(message, inputIncludesCache) {
|
|
127
|
+
const meta = asRecord(asRecord(asRecord(message)?.["result"])?.["_meta"]);
|
|
128
|
+
const parsed = rawUsageSchema.safeParse(meta?.["usage"]);
|
|
129
|
+
if (!parsed.success)
|
|
130
|
+
return undefined;
|
|
131
|
+
const raw = parsed.data;
|
|
132
|
+
if (raw.usageIsIncomplete)
|
|
133
|
+
return undefined;
|
|
134
|
+
const totalTokens = raw.totalTokens ?? raw.inputTokens + raw.outputTokens;
|
|
135
|
+
if (totalTokens === 0 || !Number.isSafeInteger(totalTokens))
|
|
136
|
+
return undefined;
|
|
137
|
+
const inputTokens = inputIncludesCache
|
|
138
|
+
? raw.inputTokens - raw.cachedReadTokens - raw.cacheCreationTokens
|
|
139
|
+
: raw.inputTokens;
|
|
140
|
+
if (inputTokens < 0)
|
|
141
|
+
return undefined;
|
|
142
|
+
if ((raw.reasoningTokens ?? 0) > raw.outputTokens)
|
|
143
|
+
return undefined;
|
|
144
|
+
return {
|
|
145
|
+
inputTokens,
|
|
146
|
+
outputTokens: raw.outputTokens,
|
|
147
|
+
totalTokens,
|
|
148
|
+
cacheReadTokens: raw.cachedReadTokens,
|
|
149
|
+
cacheWriteTokens: raw.cacheCreationTokens,
|
|
150
|
+
...(raw.reasoningTokens === undefined
|
|
151
|
+
? {}
|
|
152
|
+
: { reasoningTokens: raw.reasoningTokens }),
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
/** 读取 configOptions 中指定 id 的 currentValue。 */
|
|
156
|
+
export function configCurrentValue(message, id) {
|
|
157
|
+
const list = asRecord(asRecord(message)?.["result"])?.["configOptions"];
|
|
158
|
+
if (!Array.isArray(list))
|
|
159
|
+
return undefined;
|
|
160
|
+
for (const item of list) {
|
|
161
|
+
const row = asRecord(item);
|
|
162
|
+
if (nonEmptyString(row?.["id"]) !== id)
|
|
163
|
+
continue;
|
|
164
|
+
return nonEmptyString(row?.["currentValue"]);
|
|
165
|
+
}
|
|
166
|
+
return undefined;
|
|
167
|
+
}
|
|
168
|
+
function parseOptions(value) {
|
|
169
|
+
if (!Array.isArray(value))
|
|
170
|
+
return [];
|
|
171
|
+
const list = [];
|
|
172
|
+
for (const item of value) {
|
|
173
|
+
const row = asRecord(item);
|
|
174
|
+
const optionId = nonEmptyString(row?.["optionId"]);
|
|
175
|
+
if (optionId === undefined)
|
|
176
|
+
continue;
|
|
177
|
+
list.push({
|
|
178
|
+
optionId,
|
|
179
|
+
kind: nonEmptyString(row?.["kind"]) ?? "",
|
|
180
|
+
name: nonEmptyString(row?.["name"]) ?? optionId,
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
return list;
|
|
184
|
+
}
|
|
185
|
+
export function asRecord(value) {
|
|
186
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
187
|
+
return undefined;
|
|
188
|
+
}
|
|
189
|
+
return value;
|
|
190
|
+
}
|
|
191
|
+
export function nonEmptyString(value) {
|
|
192
|
+
return typeof value === "string" && value !== "" ? value : undefined;
|
|
193
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/** Antigravity ACP 适配器(入口 `agy acp`)。 */
|
|
2
|
+
import { asRecord, extractPromptUsage, nonEmptyString, rpcErrorMessage, } from "../acp/protocol.js";
|
|
3
|
+
import { looksUnauthenticated, probeAcpSession, readNamedList, } from "./types.js";
|
|
4
|
+
const AGY_LOGIN_HINT = "请在终端运行 `agy` 并完成 Google / Gemini 账号登录后重试。";
|
|
5
|
+
export const agyAdapter = {
|
|
6
|
+
async probe(member, env, cwd, timeoutMs, open) {
|
|
7
|
+
const probed = await probeAcpSession(member, env, cwd, timeoutMs, true, open);
|
|
8
|
+
if (!probed.ok) {
|
|
9
|
+
return {
|
|
10
|
+
id: member.id,
|
|
11
|
+
name: member.name,
|
|
12
|
+
adapter: member.adapter,
|
|
13
|
+
status: probed.reason === "not-installed" ? "not-installed" : "error",
|
|
14
|
+
detail: probed.message,
|
|
15
|
+
models: [],
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
const sessionErr = probed.session === undefined ? undefined : rpcErrorMessage(probed.session);
|
|
19
|
+
if (sessionErr !== undefined) {
|
|
20
|
+
const unauth = looksUnauthenticated(sessionErr);
|
|
21
|
+
return {
|
|
22
|
+
id: member.id,
|
|
23
|
+
name: member.name,
|
|
24
|
+
adapter: member.adapter,
|
|
25
|
+
status: unauth ? "not-logged-in" : "error",
|
|
26
|
+
detail: sessionErr,
|
|
27
|
+
...(unauth ? { loginHint: AGY_LOGIN_HINT } : {}),
|
|
28
|
+
models: [],
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
const result = asRecord(asRecord(probed.session)?.["result"]);
|
|
32
|
+
const modelsBlock = asRecord(result?.["models"]);
|
|
33
|
+
const modesBlock = asRecord(result?.["modes"]);
|
|
34
|
+
const models = readNamedList(modelsBlock?.["availableModels"], "modelId").map((m) => ({ id: m.id, name: m.name }));
|
|
35
|
+
const modes = readNamedList(modesBlock?.["availableModes"], "id").map((m) => m.id);
|
|
36
|
+
const defaultModel = nonEmptyString(modelsBlock?.["currentModelId"]);
|
|
37
|
+
return {
|
|
38
|
+
id: member.id,
|
|
39
|
+
name: member.name,
|
|
40
|
+
adapter: member.adapter,
|
|
41
|
+
status: "ready",
|
|
42
|
+
detail: models.length > 0
|
|
43
|
+
? `已就绪,发现 ${String(models.length)} 个可用模型。`
|
|
44
|
+
: "已就绪。",
|
|
45
|
+
models,
|
|
46
|
+
...(modes.length > 0 ? { modes } : {}),
|
|
47
|
+
...(defaultModel === undefined ? {} : { defaultModel }),
|
|
48
|
+
};
|
|
49
|
+
},
|
|
50
|
+
buildArgs(member, _options) {
|
|
51
|
+
// agy acp 子命令本身不接受 --model/--mode 参数,全部在 session 阶段通过 ACP 方法设置。
|
|
52
|
+
return member.args;
|
|
53
|
+
},
|
|
54
|
+
async configureSession(call, sessionId, createdResult, _initResult, options) {
|
|
55
|
+
const result = asRecord(asRecord(createdResult)?.["result"]);
|
|
56
|
+
const modelsBlock = asRecord(result?.["models"]);
|
|
57
|
+
const modesBlock = asRecord(result?.["modes"]);
|
|
58
|
+
if (options.model !== undefined) {
|
|
59
|
+
const available = readNamedList(modelsBlock?.["availableModels"], "modelId");
|
|
60
|
+
if (available.length > 0 &&
|
|
61
|
+
!available.some((item) => item.id === options.model)) {
|
|
62
|
+
throw new Error(`agy-acp 不支持模型 "${options.model}"。可用模型:${available.map((m) => m.id).join(", ")}`);
|
|
63
|
+
}
|
|
64
|
+
const currentModel = nonEmptyString(modelsBlock?.["currentModelId"]);
|
|
65
|
+
if (currentModel !== options.model) {
|
|
66
|
+
const resp = await call("session/set_model", {
|
|
67
|
+
sessionId,
|
|
68
|
+
modelId: options.model,
|
|
69
|
+
});
|
|
70
|
+
const err = rpcErrorMessage(resp);
|
|
71
|
+
if (err !== undefined) {
|
|
72
|
+
throw new Error(`agy-acp 切换模型 "${options.model}" 失败:${err}`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
const wantedMode = options.mode ?? (options.autoApprove ? "auto" : undefined);
|
|
77
|
+
if (wantedMode !== undefined) {
|
|
78
|
+
const availableModes = readNamedList(modesBlock?.["availableModes"], "id");
|
|
79
|
+
if (availableModes.length > 0 &&
|
|
80
|
+
!availableModes.some((item) => item.id === wantedMode)) {
|
|
81
|
+
throw new Error(`agy-acp 不支持模式 "${wantedMode}"。可用模式:${availableModes.map((m) => m.id).join(", ")}`);
|
|
82
|
+
}
|
|
83
|
+
const currentMode = nonEmptyString(modesBlock?.["currentModeId"]);
|
|
84
|
+
if (currentMode !== wantedMode) {
|
|
85
|
+
const resp = await call("session/set_mode", {
|
|
86
|
+
sessionId,
|
|
87
|
+
modeId: wantedMode,
|
|
88
|
+
});
|
|
89
|
+
const err = rpcErrorMessage(resp);
|
|
90
|
+
if (err !== undefined) {
|
|
91
|
+
throw new Error(`agy-acp 切换模式 "${wantedMode}" 失败:${err}`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
extractUsage(promptResponse) {
|
|
97
|
+
return extractPromptUsage(promptResponse, false);
|
|
98
|
+
},
|
|
99
|
+
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { AcpMemberConfig } from "../config.ts";
|
|
2
|
+
import { type AcpAdapter } from "./types.ts";
|
|
3
|
+
/**
|
|
4
|
+
* 解析 codex-acp 实际可执行入口:
|
|
5
|
+
* 1. 若配置显式指定非占位命令(非 "codex-acp"),直接沿用;
|
|
6
|
+
* 2. 优先读取环境变量 CODEX_ACP_PATH;
|
|
7
|
+
* 3. 自动探测同级兄弟插件 `kmh-codex-cli/vendor/codex-acp/index.js`(避免在源码中硬编码本机路径)。
|
|
8
|
+
*/
|
|
9
|
+
export declare function resolveCodexLaunch(member: AcpMemberConfig, baseEnv?: NodeJS.ProcessEnv): {
|
|
10
|
+
readonly command: string;
|
|
11
|
+
readonly args: readonly string[];
|
|
12
|
+
readonly env: Readonly<Record<string, string>>;
|
|
13
|
+
};
|
|
14
|
+
export declare const codexAdapter: AcpAdapter;
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/** Codex ACP 适配器(优先使用环境变量或同级 kmh-codex-cli 随包分发的 codex-acp 与 codex)。 */
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { asRecord, extractPromptUsage, nonEmptyString, rpcErrorMessage, } from "../acp/protocol.js";
|
|
6
|
+
import { looksUnauthenticated, probeAcpSession, readNamedList, } from "./types.js";
|
|
7
|
+
const CODEX_LOGIN_HINT = "请在终端或 KMH Codex 设置页完成 ChatGPT / OpenAI API Key 登录后重试。";
|
|
8
|
+
/**
|
|
9
|
+
* 解析 codex-acp 实际可执行入口:
|
|
10
|
+
* 1. 若配置显式指定非占位命令(非 "codex-acp"),直接沿用;
|
|
11
|
+
* 2. 优先读取环境变量 CODEX_ACP_PATH;
|
|
12
|
+
* 3. 自动探测同级兄弟插件 `kmh-codex-cli/vendor/codex-acp/index.js`(避免在源码中硬编码本机路径)。
|
|
13
|
+
*/
|
|
14
|
+
export function resolveCodexLaunch(member, baseEnv = process.env) {
|
|
15
|
+
const extraEnv = { ...member.env };
|
|
16
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
17
|
+
const siblingCandidates = [
|
|
18
|
+
path.resolve(here, "../../../kmh-codex-cli"),
|
|
19
|
+
path.resolve(here, "../../../../kmh-codex-cli"),
|
|
20
|
+
];
|
|
21
|
+
const siblingRoot = siblingCandidates.find((dir) => existsSync(dir)) ?? siblingCandidates[0];
|
|
22
|
+
const siblingCodexBin = path.join(siblingRoot, "bin/codex");
|
|
23
|
+
if (extraEnv["CODEX_PATH"] === undefined &&
|
|
24
|
+
baseEnv["CODEX_PATH"] === undefined &&
|
|
25
|
+
existsSync(siblingCodexBin)) {
|
|
26
|
+
extraEnv["CODEX_PATH"] = siblingCodexBin;
|
|
27
|
+
}
|
|
28
|
+
if (member.command !== "codex-acp") {
|
|
29
|
+
return { command: member.command, args: member.args, env: extraEnv };
|
|
30
|
+
}
|
|
31
|
+
const envBridge = baseEnv["CODEX_ACP_PATH"];
|
|
32
|
+
if (envBridge !== undefined && envBridge !== "" && existsSync(envBridge)) {
|
|
33
|
+
return {
|
|
34
|
+
command: process.execPath,
|
|
35
|
+
args: [envBridge, ...member.args],
|
|
36
|
+
env: extraEnv,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
const siblingBridge = path.join(siblingRoot, "vendor/codex-acp/index.js");
|
|
40
|
+
if (existsSync(siblingBridge)) {
|
|
41
|
+
return {
|
|
42
|
+
command: process.execPath,
|
|
43
|
+
args: [siblingBridge, ...member.args],
|
|
44
|
+
env: extraEnv,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
return { command: member.command, args: member.args, env: extraEnv };
|
|
48
|
+
}
|
|
49
|
+
export const codexAdapter = {
|
|
50
|
+
async probe(member, env, cwd, timeoutMs, open) {
|
|
51
|
+
const resolved = resolveCodexLaunch(member, env);
|
|
52
|
+
const effectiveMember = {
|
|
53
|
+
...member,
|
|
54
|
+
command: resolved.command,
|
|
55
|
+
args: [...resolved.args],
|
|
56
|
+
env: { ...resolved.env },
|
|
57
|
+
};
|
|
58
|
+
const probed = await probeAcpSession(effectiveMember, env, cwd, timeoutMs, true, open);
|
|
59
|
+
if (!probed.ok) {
|
|
60
|
+
return {
|
|
61
|
+
id: member.id,
|
|
62
|
+
name: member.name,
|
|
63
|
+
adapter: member.adapter,
|
|
64
|
+
status: probed.reason === "not-installed" ? "not-installed" : "error",
|
|
65
|
+
detail: probed.message,
|
|
66
|
+
models: [],
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
const sessionErr = probed.session === undefined ? undefined : rpcErrorMessage(probed.session);
|
|
70
|
+
if (sessionErr !== undefined) {
|
|
71
|
+
const unauth = looksUnauthenticated(sessionErr);
|
|
72
|
+
return {
|
|
73
|
+
id: member.id,
|
|
74
|
+
name: member.name,
|
|
75
|
+
adapter: member.adapter,
|
|
76
|
+
status: unauth ? "not-logged-in" : "error",
|
|
77
|
+
detail: sessionErr,
|
|
78
|
+
...(unauth ? { loginHint: CODEX_LOGIN_HINT } : {}),
|
|
79
|
+
models: [],
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
const result = asRecord(asRecord(probed.session)?.["result"]);
|
|
83
|
+
const modelsBlock = asRecord(result?.["models"]);
|
|
84
|
+
const modesBlock = asRecord(result?.["modes"]);
|
|
85
|
+
const models = readNamedList(modelsBlock?.["availableModels"], "modelId").map((m) => ({ id: m.id, name: m.name }));
|
|
86
|
+
const modes = readNamedList(modesBlock?.["availableModes"], "id").map((m) => m.id);
|
|
87
|
+
const defaultModel = nonEmptyString(modelsBlock?.["currentModelId"]);
|
|
88
|
+
if (models.length === 0) {
|
|
89
|
+
return {
|
|
90
|
+
id: member.id,
|
|
91
|
+
name: member.name,
|
|
92
|
+
adapter: member.adapter,
|
|
93
|
+
status: "not-logged-in",
|
|
94
|
+
detail: "Codex ACP 未返回可用模型目录,可能尚未登录或凭证已失效。",
|
|
95
|
+
loginHint: CODEX_LOGIN_HINT,
|
|
96
|
+
models: [],
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
id: member.id,
|
|
101
|
+
name: member.name,
|
|
102
|
+
adapter: member.adapter,
|
|
103
|
+
status: "ready",
|
|
104
|
+
detail: `已就绪,发现 ${String(models.length)} 个可用模型。`,
|
|
105
|
+
models,
|
|
106
|
+
...(modes.length > 0 ? { modes } : {}),
|
|
107
|
+
...(defaultModel === undefined ? {} : { defaultModel }),
|
|
108
|
+
};
|
|
109
|
+
},
|
|
110
|
+
resolveLaunch(member, baseEnv) {
|
|
111
|
+
return resolveCodexLaunch(member, baseEnv);
|
|
112
|
+
},
|
|
113
|
+
buildArgs(member, _options) {
|
|
114
|
+
return resolveCodexLaunch(member).args;
|
|
115
|
+
},
|
|
116
|
+
async configureSession(call, sessionId, createdResult, _initResult, options) {
|
|
117
|
+
const result = asRecord(asRecord(createdResult)?.["result"]);
|
|
118
|
+
const modelsBlock = asRecord(result?.["models"]);
|
|
119
|
+
const modesBlock = asRecord(result?.["modes"]);
|
|
120
|
+
// Codex 模型 ID 形如 gpt-6.2-sol[high],若传了 effort 且 model 未带括号,支持自动匹配。
|
|
121
|
+
let wantedModel = options.model;
|
|
122
|
+
if (wantedModel !== undefined &&
|
|
123
|
+
options.effort !== undefined &&
|
|
124
|
+
!wantedModel.includes("[")) {
|
|
125
|
+
wantedModel = `${wantedModel}[${options.effort}]`;
|
|
126
|
+
}
|
|
127
|
+
if (wantedModel !== undefined) {
|
|
128
|
+
const available = readNamedList(modelsBlock?.["availableModels"], "modelId");
|
|
129
|
+
if (available.length > 0 &&
|
|
130
|
+
!available.some((item) => item.id === wantedModel)) {
|
|
131
|
+
throw new Error(`codex-acp 不支持模型 "${wantedModel}"。可用模型:${available.map((m) => m.id).join(", ")}`);
|
|
132
|
+
}
|
|
133
|
+
const currentModel = nonEmptyString(modelsBlock?.["currentModelId"]);
|
|
134
|
+
if (currentModel !== wantedModel) {
|
|
135
|
+
const resp = await call("session/set_model", {
|
|
136
|
+
sessionId,
|
|
137
|
+
modelId: wantedModel,
|
|
138
|
+
});
|
|
139
|
+
const err = rpcErrorMessage(resp);
|
|
140
|
+
if (err !== undefined) {
|
|
141
|
+
throw new Error(`codex-acp 切换模型 "${wantedModel}" 失败:${err}`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const wantedMode = options.mode;
|
|
146
|
+
if (wantedMode !== undefined) {
|
|
147
|
+
const availableModes = readNamedList(modesBlock?.["availableModes"], "id");
|
|
148
|
+
if (availableModes.length > 0 &&
|
|
149
|
+
!availableModes.some((item) => item.id === wantedMode)) {
|
|
150
|
+
throw new Error(`codex-acp 不支持模式 "${wantedMode}"。可用模式:${availableModes.map((m) => m.id).join(", ")}`);
|
|
151
|
+
}
|
|
152
|
+
const currentMode = nonEmptyString(modesBlock?.["currentModeId"]);
|
|
153
|
+
if (currentMode !== wantedMode) {
|
|
154
|
+
const resp = await call("session/set_mode", {
|
|
155
|
+
sessionId,
|
|
156
|
+
modeId: wantedMode,
|
|
157
|
+
});
|
|
158
|
+
const err = rpcErrorMessage(resp);
|
|
159
|
+
if (err !== undefined) {
|
|
160
|
+
throw new Error(`codex-acp 切换模式 "${wantedMode}" 失败:${err}`);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
},
|
|
165
|
+
extractUsage(promptResponse) {
|
|
166
|
+
return extractPromptUsage(promptResponse, false);
|
|
167
|
+
},
|
|
168
|
+
};
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/** Grok Build ACP 适配器(入口 `grok agent stdio`)。 */
|
|
2
|
+
import { asRecord, configCurrentValue, extractPromptUsage, nonEmptyString, rpcErrorMessage, } from "../acp/protocol.js";
|
|
3
|
+
import { looksUnauthenticated, probeAcpSession, } from "./types.js";
|
|
4
|
+
const GROK_LOGIN_HINT = "请在终端运行 `grok login` 完成 xAI / Grok 登录认证后重试。";
|
|
5
|
+
export const grokAdapter = {
|
|
6
|
+
async probe(member, env, cwd, timeoutMs, open) {
|
|
7
|
+
const probed = await probeAcpSession(member, env, cwd, timeoutMs, false, open);
|
|
8
|
+
if (!probed.ok) {
|
|
9
|
+
return {
|
|
10
|
+
id: member.id,
|
|
11
|
+
name: member.name,
|
|
12
|
+
adapter: member.adapter,
|
|
13
|
+
status: probed.reason === "not-installed" ? "not-installed" : "error",
|
|
14
|
+
detail: probed.message,
|
|
15
|
+
models: [],
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
const initErr = rpcErrorMessage(probed.init);
|
|
19
|
+
if (initErr !== undefined) {
|
|
20
|
+
const unauth = looksUnauthenticated(initErr);
|
|
21
|
+
return {
|
|
22
|
+
id: member.id,
|
|
23
|
+
name: member.name,
|
|
24
|
+
adapter: member.adapter,
|
|
25
|
+
status: unauth ? "not-logged-in" : "error",
|
|
26
|
+
detail: initErr,
|
|
27
|
+
...(unauth ? { loginHint: GROK_LOGIN_HINT } : {}),
|
|
28
|
+
models: [],
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
const result = asRecord(asRecord(probed.init)?.["result"]);
|
|
32
|
+
const meta = asRecord(result?.["_meta"]);
|
|
33
|
+
const modelState = asRecord(meta?.["modelState"]);
|
|
34
|
+
const models = parseGrokModels(modelState?.["availableModels"]);
|
|
35
|
+
const defaultModel = nonEmptyString(modelState?.["currentModelId"]);
|
|
36
|
+
if (models.length === 0) {
|
|
37
|
+
return {
|
|
38
|
+
id: member.id,
|
|
39
|
+
name: member.name,
|
|
40
|
+
adapter: member.adapter,
|
|
41
|
+
status: "not-logged-in",
|
|
42
|
+
detail: "Grok 未返回可用模型目录,可能尚未登录或凭证已失效。",
|
|
43
|
+
loginHint: GROK_LOGIN_HINT,
|
|
44
|
+
models: [],
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
id: member.id,
|
|
49
|
+
name: member.name,
|
|
50
|
+
adapter: member.adapter,
|
|
51
|
+
status: "ready",
|
|
52
|
+
detail: `已就绪,发现 ${String(models.length)} 个可用模型。`,
|
|
53
|
+
models,
|
|
54
|
+
...(defaultModel === undefined ? {} : { defaultModel }),
|
|
55
|
+
};
|
|
56
|
+
},
|
|
57
|
+
buildArgs(member, options) {
|
|
58
|
+
// grok agent [OPTIONS] stdio:选项必须放在子命令 stdio 之前。
|
|
59
|
+
const base = [...member.args];
|
|
60
|
+
const stdioIdx = base.lastIndexOf("stdio");
|
|
61
|
+
const prefix = stdioIdx >= 0 ? base.slice(0, stdioIdx) : base;
|
|
62
|
+
const suffix = stdioIdx >= 0 ? base.slice(stdioIdx) : [];
|
|
63
|
+
const extra = [];
|
|
64
|
+
if (options.model !== undefined) {
|
|
65
|
+
extra.push("--model", options.model);
|
|
66
|
+
}
|
|
67
|
+
if (options.effort !== undefined) {
|
|
68
|
+
extra.push("--reasoning-effort", options.effort);
|
|
69
|
+
}
|
|
70
|
+
if (options.autoApprove) {
|
|
71
|
+
extra.push("--always-approve");
|
|
72
|
+
}
|
|
73
|
+
return [...prefix, ...extra, ...suffix];
|
|
74
|
+
},
|
|
75
|
+
async configureSession(call, sessionId, createdResult, initResult, options) {
|
|
76
|
+
const modelState = asRecord(asRecord(asRecord(asRecord(initResult)?.["result"])?.["_meta"])?.["modelState"]);
|
|
77
|
+
const available = parseGrokModels(modelState?.["availableModels"]);
|
|
78
|
+
if (options.model !== undefined) {
|
|
79
|
+
if (available.length > 0 &&
|
|
80
|
+
!available.some((m) => m.id === options.model)) {
|
|
81
|
+
throw new Error(`grok-acp 不支持模型 "${options.model}"。可用模型:${available.map((m) => m.id).join(", ")}`);
|
|
82
|
+
}
|
|
83
|
+
await syncConfigOptionIfPresent(call, sessionId, createdResult, "model", options.model);
|
|
84
|
+
}
|
|
85
|
+
if (options.effort !== undefined) {
|
|
86
|
+
const targetModelId = options.model ?? nonEmptyString(modelState?.["currentModelId"]);
|
|
87
|
+
const targetModel = available.find((m) => m.id === targetModelId);
|
|
88
|
+
if (targetModel?.efforts !== undefined &&
|
|
89
|
+
targetModel.efforts.length > 0 &&
|
|
90
|
+
!targetModel.efforts.includes(options.effort)) {
|
|
91
|
+
throw new Error(`模型 "${targetModel.id}" 不支持思考档位 "${options.effort}"。可用档位:${targetModel.efforts.join(", ")}`);
|
|
92
|
+
}
|
|
93
|
+
await syncConfigOptionIfPresent(call, sessionId, createdResult, "reasoning_effort", options.effort);
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
extractUsage(promptResponse) {
|
|
97
|
+
// Grok 的 inputTokens 包含缓存读取与创建,需扣减。
|
|
98
|
+
return extractPromptUsage(promptResponse, true);
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
async function syncConfigOptionIfPresent(call, sessionId, createdResult, configId, wanted) {
|
|
102
|
+
const current = configCurrentValue(createdResult, configId);
|
|
103
|
+
// 若启动参数已生效且回包未返回 configOptions,不误判失败;若返回且不一致则显式切换并核对。
|
|
104
|
+
if (current === undefined || current === wanted)
|
|
105
|
+
return;
|
|
106
|
+
const updated = await call("session/set_config_option", {
|
|
107
|
+
sessionId,
|
|
108
|
+
configId,
|
|
109
|
+
value: wanted,
|
|
110
|
+
});
|
|
111
|
+
const err = rpcErrorMessage(updated);
|
|
112
|
+
if (err !== undefined) {
|
|
113
|
+
throw new Error(`切换 ${configId}="${wanted}" 失败:${err}`);
|
|
114
|
+
}
|
|
115
|
+
const after = configCurrentValue(updated, configId);
|
|
116
|
+
if (after !== undefined && after !== wanted) {
|
|
117
|
+
throw new Error(`切换 ${configId}="${wanted}" 未生效(当前仍为 ${after})。`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
function parseGrokModels(value) {
|
|
121
|
+
if (!Array.isArray(value))
|
|
122
|
+
return [];
|
|
123
|
+
const list = [];
|
|
124
|
+
for (const item of value) {
|
|
125
|
+
const row = asRecord(item);
|
|
126
|
+
const id = nonEmptyString(row?.["modelId"]);
|
|
127
|
+
if (id === undefined)
|
|
128
|
+
continue;
|
|
129
|
+
const name = nonEmptyString(row?.["name"]) ?? id;
|
|
130
|
+
const meta = asRecord(row?.["_meta"]);
|
|
131
|
+
const rawEfforts = meta?.["reasoningEfforts"];
|
|
132
|
+
const efforts = [];
|
|
133
|
+
if (Array.isArray(rawEfforts)) {
|
|
134
|
+
for (const eff of rawEfforts) {
|
|
135
|
+
const effId = nonEmptyString(asRecord(eff)?.["id"]);
|
|
136
|
+
if (effId !== undefined)
|
|
137
|
+
efforts.push(effId);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
list.push({
|
|
141
|
+
id,
|
|
142
|
+
name,
|
|
143
|
+
...(efforts.length > 0 ? { efforts } : {}),
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
return list;
|
|
147
|
+
}
|