@ktkid/kmh-subagent-team 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.
- 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 +327 -0
- package/lib/src/acp/process.d.ts +15 -0
- package/lib/src/acp/process.js +102 -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,64 @@
|
|
|
1
|
+
/** 成员适配器路由与通用 ACP 适配器兜底。 */
|
|
2
|
+
import { extractPromptUsage, rpcErrorMessage } from "../acp/protocol.js";
|
|
3
|
+
import { agyAdapter } from "./agy.js";
|
|
4
|
+
import { codexAdapter } from "./codex.js";
|
|
5
|
+
import { grokAdapter } from "./grok.js";
|
|
6
|
+
import { workbuddyAdapter } from "./workbuddy.js";
|
|
7
|
+
import { zcodeAdapter } from "./zcode.js";
|
|
8
|
+
import { looksUnauthenticated, probeAcpSession, } from "./types.js";
|
|
9
|
+
const genericAdapter = {
|
|
10
|
+
async probe(member, env, cwd, timeoutMs, open) {
|
|
11
|
+
const probed = await probeAcpSession(member, env, cwd, timeoutMs, false, open);
|
|
12
|
+
if (!probed.ok) {
|
|
13
|
+
return {
|
|
14
|
+
id: member.id,
|
|
15
|
+
name: member.name,
|
|
16
|
+
adapter: member.adapter,
|
|
17
|
+
status: probed.reason === "not-installed" ? "not-installed" : "error",
|
|
18
|
+
detail: probed.message,
|
|
19
|
+
models: [],
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
const err = rpcErrorMessage(probed.init);
|
|
23
|
+
if (err !== undefined) {
|
|
24
|
+
return {
|
|
25
|
+
id: member.id,
|
|
26
|
+
name: member.name,
|
|
27
|
+
adapter: member.adapter,
|
|
28
|
+
status: looksUnauthenticated(err) ? "not-logged-in" : "error",
|
|
29
|
+
detail: err,
|
|
30
|
+
models: [],
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
return {
|
|
34
|
+
id: member.id,
|
|
35
|
+
name: member.name,
|
|
36
|
+
adapter: member.adapter,
|
|
37
|
+
status: "ready",
|
|
38
|
+
detail: "通用 ACP 握手就绪。",
|
|
39
|
+
models: [],
|
|
40
|
+
};
|
|
41
|
+
},
|
|
42
|
+
buildArgs(member, _options) {
|
|
43
|
+
return member.args;
|
|
44
|
+
},
|
|
45
|
+
extractUsage(promptResponse) {
|
|
46
|
+
return extractPromptUsage(promptResponse, false);
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
export function adapterFor(adapter) {
|
|
50
|
+
switch (adapter) {
|
|
51
|
+
case "agy":
|
|
52
|
+
return agyAdapter;
|
|
53
|
+
case "grok":
|
|
54
|
+
return grokAdapter;
|
|
55
|
+
case "codex":
|
|
56
|
+
return codexAdapter;
|
|
57
|
+
case "workbuddy":
|
|
58
|
+
return workbuddyAdapter;
|
|
59
|
+
case "zcode":
|
|
60
|
+
return zcodeAdapter;
|
|
61
|
+
case "generic":
|
|
62
|
+
return genericAdapter;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/** ACP 成员适配器契约与公共握手探测工具。 */
|
|
2
|
+
import type { TokenUsage } from "@deepseek-ai/dsh-llm";
|
|
3
|
+
import { type StdioOpener } from "../acp/process.ts";
|
|
4
|
+
import type { AcpMemberConfig } from "../config.ts";
|
|
5
|
+
export interface MemberModelInfo {
|
|
6
|
+
readonly id: string;
|
|
7
|
+
readonly name: string;
|
|
8
|
+
readonly efforts?: readonly string[];
|
|
9
|
+
}
|
|
10
|
+
export interface MemberProbeResult {
|
|
11
|
+
readonly id: string;
|
|
12
|
+
readonly name: string;
|
|
13
|
+
readonly adapter: AcpMemberConfig["adapter"];
|
|
14
|
+
readonly status: "ready" | "not-logged-in" | "not-installed" | "error";
|
|
15
|
+
readonly detail: string;
|
|
16
|
+
readonly loginHint?: string;
|
|
17
|
+
readonly models: readonly MemberModelInfo[];
|
|
18
|
+
readonly modes?: readonly string[];
|
|
19
|
+
readonly defaultModel?: string;
|
|
20
|
+
}
|
|
21
|
+
export interface LaunchOptions {
|
|
22
|
+
readonly model?: string;
|
|
23
|
+
readonly effort?: string;
|
|
24
|
+
readonly mode?: string;
|
|
25
|
+
readonly autoApprove: boolean;
|
|
26
|
+
}
|
|
27
|
+
export interface AcpAdapter {
|
|
28
|
+
probe(member: AcpMemberConfig, env: NodeJS.ProcessEnv, cwd: string, timeoutMs: number, open?: StdioOpener): Promise<MemberProbeResult>;
|
|
29
|
+
buildArgs(member: AcpMemberConfig, options: LaunchOptions): readonly string[];
|
|
30
|
+
/** 可选覆盖实际启动命令与附加环境变量(支持异步读取本机桌面凭据)。 */
|
|
31
|
+
resolveLaunch?(member: AcpMemberConfig, baseEnv: NodeJS.ProcessEnv): {
|
|
32
|
+
readonly command: string;
|
|
33
|
+
readonly args: readonly string[];
|
|
34
|
+
readonly env: Readonly<Record<string, string>>;
|
|
35
|
+
} | Promise<{
|
|
36
|
+
readonly command: string;
|
|
37
|
+
readonly args: readonly string[];
|
|
38
|
+
readonly env: Readonly<Record<string, string>>;
|
|
39
|
+
}>;
|
|
40
|
+
configureSession?(call: (method: string, params: unknown) => Promise<unknown>, sessionId: string, createdResult: unknown, initResult: unknown, options: LaunchOptions): Promise<void>;
|
|
41
|
+
extractUsage(promptResponse: unknown): TokenUsage | undefined;
|
|
42
|
+
}
|
|
43
|
+
/** 启动一次轻量级 ACP 握手(可选附带 session/new),用于探测就绪状态与模型目录。 */
|
|
44
|
+
export declare function probeAcpSession(member: AcpMemberConfig, env: NodeJS.ProcessEnv, cwd: string, timeoutMs: number, includeNewSession: boolean, open?: StdioOpener): Promise<{
|
|
45
|
+
readonly ok: true;
|
|
46
|
+
readonly init: unknown;
|
|
47
|
+
readonly session?: unknown;
|
|
48
|
+
} | {
|
|
49
|
+
readonly ok: false;
|
|
50
|
+
readonly reason: "not-installed" | "timeout" | "error";
|
|
51
|
+
readonly message: string;
|
|
52
|
+
}>;
|
|
53
|
+
/** 通用未登录关键字判断。 */
|
|
54
|
+
export declare function looksUnauthenticated(text: string): boolean;
|
|
55
|
+
/** 从对象数组提取 string 字段。 */
|
|
56
|
+
export declare function readNamedList(value: unknown, idKey: string, nameKey?: string): readonly {
|
|
57
|
+
id: string;
|
|
58
|
+
name: string;
|
|
59
|
+
}[];
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { asRecord, jsonRpcIdOf, nonEmptyString } from "../acp/protocol.js";
|
|
2
|
+
import { buildControlledEnv, disposeStdioProcess, openStdioProcess, } from "../acp/process.js";
|
|
3
|
+
/** 启动一次轻量级 ACP 握手(可选附带 session/new),用于探测就绪状态与模型目录。 */
|
|
4
|
+
export async function probeAcpSession(member, env, cwd, timeoutMs, includeNewSession, open = openStdioProcess) {
|
|
5
|
+
let proc;
|
|
6
|
+
try {
|
|
7
|
+
proc = open(member.command, member.args, buildControlledEnv(env, member.env), cwd);
|
|
8
|
+
}
|
|
9
|
+
catch (err) {
|
|
10
|
+
const code = asRecord(err)?.["code"];
|
|
11
|
+
if (code === "ENOENT") {
|
|
12
|
+
return {
|
|
13
|
+
ok: false,
|
|
14
|
+
reason: "not-installed",
|
|
15
|
+
message: `未找到命令 "${member.command}",请先安装对应 CLI。`,
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
return {
|
|
19
|
+
ok: false,
|
|
20
|
+
reason: "error",
|
|
21
|
+
message: err instanceof Error ? err.message : String(err),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
let settled = false;
|
|
25
|
+
const timer = setTimeout(() => {
|
|
26
|
+
if (!settled)
|
|
27
|
+
proc.kill("SIGTERM");
|
|
28
|
+
}, timeoutMs);
|
|
29
|
+
timer.unref?.();
|
|
30
|
+
let initMsg;
|
|
31
|
+
let sessionMsg;
|
|
32
|
+
try {
|
|
33
|
+
proc.send(JSON.stringify({
|
|
34
|
+
jsonrpc: "2.0",
|
|
35
|
+
id: 1,
|
|
36
|
+
method: "initialize",
|
|
37
|
+
params: {
|
|
38
|
+
protocolVersion: 1,
|
|
39
|
+
clientCapabilities: {},
|
|
40
|
+
clientInfo: { name: "kmh-subagent-team", version: "0.1.0" },
|
|
41
|
+
},
|
|
42
|
+
}));
|
|
43
|
+
const exitPromise = proc.exited.catch(() => null);
|
|
44
|
+
let sentSession = false;
|
|
45
|
+
const readTask = (async () => {
|
|
46
|
+
for await (const line of proc.lines) {
|
|
47
|
+
let parsed;
|
|
48
|
+
try {
|
|
49
|
+
parsed = JSON.parse(line);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
const id = jsonRpcIdOf(parsed);
|
|
55
|
+
if (id === 1 && initMsg === undefined) {
|
|
56
|
+
initMsg = parsed;
|
|
57
|
+
if (!includeNewSession)
|
|
58
|
+
return;
|
|
59
|
+
sentSession = true;
|
|
60
|
+
proc.send(JSON.stringify({
|
|
61
|
+
jsonrpc: "2.0",
|
|
62
|
+
id: 2,
|
|
63
|
+
method: "session/new",
|
|
64
|
+
params: { cwd, mcpServers: [] },
|
|
65
|
+
}));
|
|
66
|
+
}
|
|
67
|
+
else if (id === 2 && sentSession) {
|
|
68
|
+
sessionMsg = parsed;
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
})();
|
|
73
|
+
const race = await Promise.race([
|
|
74
|
+
readTask.then(() => "done"),
|
|
75
|
+
exitPromise.then(() => "exited"),
|
|
76
|
+
]);
|
|
77
|
+
settled = true;
|
|
78
|
+
if (initMsg === undefined) {
|
|
79
|
+
return race === "exited"
|
|
80
|
+
? {
|
|
81
|
+
ok: false,
|
|
82
|
+
reason: "not-installed",
|
|
83
|
+
message: `启动 "${member.command}" 失败或立即退出。`,
|
|
84
|
+
}
|
|
85
|
+
: {
|
|
86
|
+
ok: false,
|
|
87
|
+
reason: "timeout",
|
|
88
|
+
message: `探测 "${member.command}" 握手超时(>${String(timeoutMs)}ms)。`,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
if (includeNewSession && sessionMsg === undefined) {
|
|
92
|
+
return {
|
|
93
|
+
ok: true,
|
|
94
|
+
init: initMsg,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
return {
|
|
98
|
+
ok: true,
|
|
99
|
+
init: initMsg,
|
|
100
|
+
...(sessionMsg === undefined ? {} : { session: sessionMsg }),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
catch (err) {
|
|
104
|
+
const code = asRecord(err)?.["code"];
|
|
105
|
+
if (code === "ENOENT") {
|
|
106
|
+
return {
|
|
107
|
+
ok: false,
|
|
108
|
+
reason: "not-installed",
|
|
109
|
+
message: `未找到命令 "${member.command}",请先安装对应 CLI。`,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
return {
|
|
113
|
+
ok: false,
|
|
114
|
+
reason: "error",
|
|
115
|
+
message: err instanceof Error ? err.message : String(err),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
finally {
|
|
119
|
+
settled = true;
|
|
120
|
+
clearTimeout(timer);
|
|
121
|
+
await disposeStdioProcess(proc, 500);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/** 通用未登录关键字判断。 */
|
|
125
|
+
export function looksUnauthenticated(text) {
|
|
126
|
+
return /not\s*logged\s*in|unauthenticated|auth|login\s*required|unauthorized|sign\s*in/i.test(text);
|
|
127
|
+
}
|
|
128
|
+
/** 从对象数组提取 string 字段。 */
|
|
129
|
+
export function readNamedList(value, idKey, nameKey = "name") {
|
|
130
|
+
if (!Array.isArray(value))
|
|
131
|
+
return [];
|
|
132
|
+
const items = [];
|
|
133
|
+
for (const row of value) {
|
|
134
|
+
const rec = asRecord(row);
|
|
135
|
+
const id = nonEmptyString(rec?.[idKey]);
|
|
136
|
+
if (id === undefined)
|
|
137
|
+
continue;
|
|
138
|
+
items.push({ id, name: nonEmptyString(rec?.[nameKey]) ?? id });
|
|
139
|
+
}
|
|
140
|
+
return items;
|
|
141
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 仅在 WorkBuddy 自带 Electron(ELECTRON_RUN_AS_NODE=1)下运行的只读凭据读取器。
|
|
3
|
+
* 解密本机 WorkBuddy 桌面端登录态,将凭据通过 stdout JSON 交给父进程内存使用,不落盘、不输出日志。
|
|
4
|
+
*/
|
|
5
|
+
import { createDecipheriv, createHash } from "node:crypto";
|
|
6
|
+
import { readFile } from "node:fs/promises";
|
|
7
|
+
import { resolve } from "node:path";
|
|
8
|
+
import { pathToFileURL } from "node:url";
|
|
9
|
+
import { z } from "zod";
|
|
10
|
+
const buildSchema = z.object({
|
|
11
|
+
atRestSecretKey: z.string().min(1),
|
|
12
|
+
});
|
|
13
|
+
const envelopeSchema = z.object({
|
|
14
|
+
keyId: z.string().min(1),
|
|
15
|
+
nonce: z.string().min(1),
|
|
16
|
+
authTag: z.string().min(1),
|
|
17
|
+
ciphertext: z.string().min(1),
|
|
18
|
+
});
|
|
19
|
+
const loginSchema = z.object({
|
|
20
|
+
account: z.object({
|
|
21
|
+
uid: z.string().min(1),
|
|
22
|
+
enterpriseId: z.string().optional(),
|
|
23
|
+
}),
|
|
24
|
+
auth: z.object({
|
|
25
|
+
expiresAt: z.number().positive(),
|
|
26
|
+
domain: z.string().optional(),
|
|
27
|
+
accessToken: z.union([
|
|
28
|
+
z.string().min(1),
|
|
29
|
+
z.object({ envelope: z.string().min(1) }),
|
|
30
|
+
]),
|
|
31
|
+
}),
|
|
32
|
+
});
|
|
33
|
+
function lengthPrefixed(value) {
|
|
34
|
+
const bytes = Buffer.from(value, "utf8");
|
|
35
|
+
const len = Buffer.alloc(4);
|
|
36
|
+
len.writeUInt32BE(bytes.length);
|
|
37
|
+
return Buffer.concat([len, bytes]);
|
|
38
|
+
}
|
|
39
|
+
function buildAad(keyId) {
|
|
40
|
+
const suite = Buffer.alloc(4);
|
|
41
|
+
suite.writeUInt32BE(1);
|
|
42
|
+
return Buffer.concat([
|
|
43
|
+
Buffer.from("WB-AAD\0", "ascii"),
|
|
44
|
+
Buffer.from([1]),
|
|
45
|
+
lengthPrefixed("WBEV1"),
|
|
46
|
+
lengthPrefixed("sym-v1"),
|
|
47
|
+
suite,
|
|
48
|
+
lengthPrefixed(keyId),
|
|
49
|
+
Buffer.from([2, 0, 0]),
|
|
50
|
+
]);
|
|
51
|
+
}
|
|
52
|
+
export function decryptWorkBuddyLogin(loginRaw, buildRaw) {
|
|
53
|
+
let key;
|
|
54
|
+
let plain;
|
|
55
|
+
try {
|
|
56
|
+
const session = loginSchema.parse(loginRaw);
|
|
57
|
+
if (session.auth.expiresAt <= Date.now()) {
|
|
58
|
+
throw new Error("WORKBUDDY_AUTH_EXPIRED");
|
|
59
|
+
}
|
|
60
|
+
let accessToken;
|
|
61
|
+
if (typeof session.auth.accessToken === "string") {
|
|
62
|
+
accessToken = session.auth.accessToken;
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
const { atRestSecretKey } = buildSchema.parse(buildRaw);
|
|
66
|
+
key = createHash("sha256").update(atRestSecretKey, "utf8").digest();
|
|
67
|
+
const keyId = createHash("sha256").update(key).digest("hex").slice(0, 16);
|
|
68
|
+
const encoded = Buffer.from(session.auth.accessToken.envelope, "base64");
|
|
69
|
+
const env = envelopeSchema.parse(JSON.parse(encoded.toString("utf8")));
|
|
70
|
+
if (env.keyId !== keyId)
|
|
71
|
+
throw new Error("KEY_MISMATCH");
|
|
72
|
+
const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(env.nonce, "base64"));
|
|
73
|
+
decipher.setAAD(buildAad(keyId));
|
|
74
|
+
decipher.setAuthTag(Buffer.from(env.authTag, "base64"));
|
|
75
|
+
plain = Buffer.concat([
|
|
76
|
+
decipher.update(Buffer.from(env.ciphertext, "base64")),
|
|
77
|
+
decipher.final(),
|
|
78
|
+
]);
|
|
79
|
+
accessToken = plain.toString("utf8");
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
accessToken,
|
|
83
|
+
userId: session.account.uid,
|
|
84
|
+
...(session.auth.domain === undefined ? {} : { domain: session.auth.domain }),
|
|
85
|
+
...(session.account.enterpriseId === undefined
|
|
86
|
+
? {}
|
|
87
|
+
: { enterpriseId: session.account.enterpriseId }),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
finally {
|
|
91
|
+
key?.fill(0);
|
|
92
|
+
plain?.fill(0);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
async function runCli() {
|
|
96
|
+
try {
|
|
97
|
+
const authFile = z.string().min(1).parse(process.argv[2]);
|
|
98
|
+
const linkedBinding = z
|
|
99
|
+
.function({ input: [z.string()], output: z.unknown() })
|
|
100
|
+
.parse(Reflect.get(process, "_linkedBinding"));
|
|
101
|
+
const storage = z
|
|
102
|
+
.object({ loggerGet: z.function({ input: [], output: z.string() }) })
|
|
103
|
+
.parse(linkedBinding("electron_browser_workbuddy_storage"));
|
|
104
|
+
const build = JSON.parse(storage.loggerGet());
|
|
105
|
+
const login = JSON.parse(await readFile(authFile, "utf8"));
|
|
106
|
+
process.stdout.write(JSON.stringify(decryptWorkBuddyLogin(login, build)));
|
|
107
|
+
}
|
|
108
|
+
catch (err) {
|
|
109
|
+
process.stderr.write(err instanceof Error ? err.message : "WORKBUDDY_AUTH_UNAVAILABLE");
|
|
110
|
+
process.exitCode = 1;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (process.argv[1] &&
|
|
114
|
+
import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
|
|
115
|
+
await runCli();
|
|
116
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { AcpMemberConfig } from "../config.ts";
|
|
2
|
+
import { type AcpAdapter } from "./types.ts";
|
|
3
|
+
/** 解析 WorkBuddy CLI 入口(支持配置覆盖、WORKBUDDY_CLI_PATH 环境变量或桌面端内置 CLI)。 */
|
|
4
|
+
export declare function resolveWorkBuddyLaunch(member: AcpMemberConfig, baseEnv?: NodeJS.ProcessEnv): Promise<{
|
|
5
|
+
readonly command: string;
|
|
6
|
+
readonly args: readonly string[];
|
|
7
|
+
readonly env: Readonly<Record<string, string>>;
|
|
8
|
+
}>;
|
|
9
|
+
export declare const workbuddyAdapter: AcpAdapter;
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/** WorkBuddy ACP 适配器(自动定位本机 WorkBuddy CLI 与桌面登录凭据)。 */
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { promisify } from "node:util";
|
|
8
|
+
import { asRecord, extractPromptUsage, nonEmptyString, rpcErrorMessage, } from "../acp/protocol.js";
|
|
9
|
+
import { looksUnauthenticated, probeAcpSession, readNamedList, } from "./types.js";
|
|
10
|
+
const runFile = promisify(execFile);
|
|
11
|
+
const WORKBUDDY_CLI_DEFAULT = "/Applications/WorkBuddy.app/Contents/Resources/app.asar.unpacked/cli/dist/codebuddy-lite-wb.mjs";
|
|
12
|
+
const WORKBUDDY_ELECTRON_DEFAULT = "/Applications/WorkBuddy.app/Contents/MacOS/Electron";
|
|
13
|
+
const WORKBUDDY_AUTH_FILE_DEFAULT = path.join(homedir(), "Library/Application Support/CodeBuddyExtension/Data/Public/auth/workbuddy-desktop.info");
|
|
14
|
+
const WORKBUDDY_LOGIN_HINT = "请在 WorkBuddy 桌面端完成登录,或配置 CODEBUDDY_AUTH_TOKEN / CODEBUDDY_API_KEY 后重试。";
|
|
15
|
+
/** 仅当环境变量未提供 token 时,尝试从本机 WorkBuddy 桌面登录文件只读解出凭据。 */
|
|
16
|
+
async function readDesktopAuthEnv(baseEnv) {
|
|
17
|
+
const electronPath = baseEnv["WORKBUDDY_ELECTRON_PATH"] ?? WORKBUDDY_ELECTRON_DEFAULT;
|
|
18
|
+
const authFile = baseEnv["WORKBUDDY_AUTH_FILE"] ?? WORKBUDDY_AUTH_FILE_DEFAULT;
|
|
19
|
+
if (!existsSync(electronPath) || !existsSync(authFile))
|
|
20
|
+
return {};
|
|
21
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
22
|
+
const jsReader = [
|
|
23
|
+
path.join(here, "workbuddy-auth.js"),
|
|
24
|
+
path.resolve(here, "../../lib/src/adapters/workbuddy-auth.js"),
|
|
25
|
+
].find((p) => existsSync(p));
|
|
26
|
+
if (jsReader === undefined)
|
|
27
|
+
return {};
|
|
28
|
+
try {
|
|
29
|
+
const { stdout } = await runFile(electronPath, [jsReader, authFile], {
|
|
30
|
+
env: { ...baseEnv, ELECTRON_RUN_AS_NODE: "1" },
|
|
31
|
+
encoding: "utf8",
|
|
32
|
+
timeout: 8_000,
|
|
33
|
+
maxBuffer: 64 * 1024,
|
|
34
|
+
});
|
|
35
|
+
const parsed = JSON.parse(stdout);
|
|
36
|
+
if (!parsed.accessToken || !parsed.userId)
|
|
37
|
+
return {};
|
|
38
|
+
const out = {
|
|
39
|
+
CODEBUDDY_AUTH_TOKEN: parsed.accessToken,
|
|
40
|
+
ACC_USER_ID: parsed.userId,
|
|
41
|
+
};
|
|
42
|
+
if (parsed.domain === "global" || parsed.domain === "internal") {
|
|
43
|
+
out["CODEBUDDY_INTERNET_ENVIRONMENT"] =
|
|
44
|
+
parsed.domain === "global" ? "public" : "internal";
|
|
45
|
+
}
|
|
46
|
+
if (parsed.enterpriseId) {
|
|
47
|
+
out["ACC_PRODUCT_CONFIG_V3"] = JSON.stringify({
|
|
48
|
+
endpoint: parsed.domain === "global"
|
|
49
|
+
? "https://www.workbuddy.ai"
|
|
50
|
+
: "https://www.workbuddy.cn",
|
|
51
|
+
enterpriseId: parsed.enterpriseId,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return {};
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/** 解析 WorkBuddy CLI 入口(支持配置覆盖、WORKBUDDY_CLI_PATH 环境变量或桌面端内置 CLI)。 */
|
|
61
|
+
export async function resolveWorkBuddyLaunch(member, baseEnv = process.env) {
|
|
62
|
+
const extraEnv = { ...member.env };
|
|
63
|
+
// buildControlledEnv 会过滤 _TOKEN / API_KEY,此处显式透传宿主中已配好的 WorkBuddy 凭据。
|
|
64
|
+
for (const key of [
|
|
65
|
+
"CODEBUDDY_AUTH_TOKEN",
|
|
66
|
+
"CODEBUDDY_API_KEY",
|
|
67
|
+
"ACC_USER_ID",
|
|
68
|
+
"CODEBUDDY_INTERNET_ENVIRONMENT",
|
|
69
|
+
"ACC_PRODUCT_CONFIG_V3",
|
|
70
|
+
]) {
|
|
71
|
+
const val = baseEnv[key];
|
|
72
|
+
if (extraEnv[key] === undefined && val !== undefined && val !== "") {
|
|
73
|
+
extraEnv[key] = val;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (extraEnv["CODEBUDDY_AUTH_TOKEN"] === undefined &&
|
|
77
|
+
extraEnv["CODEBUDDY_API_KEY"] === undefined &&
|
|
78
|
+
member.command === "workbuddy-acp") {
|
|
79
|
+
Object.assign(extraEnv, await readDesktopAuthEnv(baseEnv));
|
|
80
|
+
}
|
|
81
|
+
if (member.command !== "workbuddy-acp") {
|
|
82
|
+
return { command: member.command, args: member.args, env: extraEnv };
|
|
83
|
+
}
|
|
84
|
+
const cliPath = baseEnv["WORKBUDDY_CLI_PATH"] ?? WORKBUDDY_CLI_DEFAULT;
|
|
85
|
+
if (existsSync(cliPath)) {
|
|
86
|
+
return {
|
|
87
|
+
command: process.execPath,
|
|
88
|
+
args: [cliPath, "--serve", "--acp", "--acp-transport", "stdio"],
|
|
89
|
+
env: extraEnv,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
return { command: member.command, args: member.args, env: extraEnv };
|
|
93
|
+
}
|
|
94
|
+
export const workbuddyAdapter = {
|
|
95
|
+
resolveLaunch(member, baseEnv) {
|
|
96
|
+
return resolveWorkBuddyLaunch(member, baseEnv);
|
|
97
|
+
},
|
|
98
|
+
async probe(member, env, cwd, timeoutMs, open) {
|
|
99
|
+
const resolved = await resolveWorkBuddyLaunch(member, env);
|
|
100
|
+
const effectiveMember = {
|
|
101
|
+
...member,
|
|
102
|
+
command: resolved.command,
|
|
103
|
+
args: [...resolved.args],
|
|
104
|
+
env: { ...resolved.env },
|
|
105
|
+
};
|
|
106
|
+
const probed = await probeAcpSession(effectiveMember, env, cwd, timeoutMs, true, open);
|
|
107
|
+
if (!probed.ok) {
|
|
108
|
+
return {
|
|
109
|
+
id: member.id,
|
|
110
|
+
name: member.name,
|
|
111
|
+
adapter: member.adapter,
|
|
112
|
+
status: probed.reason === "not-installed" ? "not-installed" : "error",
|
|
113
|
+
detail: probed.message,
|
|
114
|
+
models: [],
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
const sessionErr = probed.session === undefined ? undefined : rpcErrorMessage(probed.session);
|
|
118
|
+
if (sessionErr !== undefined) {
|
|
119
|
+
const unauth = looksUnauthenticated(sessionErr);
|
|
120
|
+
return {
|
|
121
|
+
id: member.id,
|
|
122
|
+
name: member.name,
|
|
123
|
+
adapter: member.adapter,
|
|
124
|
+
status: unauth ? "not-logged-in" : "error",
|
|
125
|
+
detail: sessionErr,
|
|
126
|
+
...(unauth ? { loginHint: WORKBUDDY_LOGIN_HINT } : {}),
|
|
127
|
+
models: [],
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
const result = asRecord(asRecord(probed.session)?.["result"]);
|
|
131
|
+
const modelsBlock = asRecord(result?.["models"]);
|
|
132
|
+
const modesBlock = asRecord(result?.["modes"]);
|
|
133
|
+
const models = readNamedList(modelsBlock?.["availableModels"], "modelId").map((m) => ({ id: m.id, name: m.name }));
|
|
134
|
+
const modes = readNamedList(modesBlock?.["availableModes"], "id").map((m) => m.id);
|
|
135
|
+
const defaultModel = nonEmptyString(modelsBlock?.["currentModelId"]);
|
|
136
|
+
return {
|
|
137
|
+
id: member.id,
|
|
138
|
+
name: member.name,
|
|
139
|
+
adapter: member.adapter,
|
|
140
|
+
status: "ready",
|
|
141
|
+
detail: models.length > 0
|
|
142
|
+
? `已就绪,发现 ${String(models.length)} 个可用模型。`
|
|
143
|
+
: "已就绪。",
|
|
144
|
+
models,
|
|
145
|
+
...(modes.length > 0 ? { modes } : {}),
|
|
146
|
+
...(defaultModel === undefined ? {} : { defaultModel }),
|
|
147
|
+
};
|
|
148
|
+
},
|
|
149
|
+
buildArgs(member, options) {
|
|
150
|
+
const args = [...member.args];
|
|
151
|
+
if (options.model !== undefined) {
|
|
152
|
+
args.push("--model", options.model);
|
|
153
|
+
}
|
|
154
|
+
if (options.autoApprove) {
|
|
155
|
+
args.push("--permission-mode", "bypassPermissions");
|
|
156
|
+
}
|
|
157
|
+
return args;
|
|
158
|
+
},
|
|
159
|
+
async configureSession(call, sessionId, createdResult, _initResult, options) {
|
|
160
|
+
if (options.model === undefined)
|
|
161
|
+
return;
|
|
162
|
+
const result = asRecord(asRecord(createdResult)?.["result"]);
|
|
163
|
+
const modelsBlock = asRecord(result?.["models"]);
|
|
164
|
+
const currentModel = nonEmptyString(modelsBlock?.["currentModelId"]);
|
|
165
|
+
if (currentModel === undefined || currentModel === options.model)
|
|
166
|
+
return;
|
|
167
|
+
const resp = await call("session/set_model", {
|
|
168
|
+
sessionId,
|
|
169
|
+
modelId: options.model,
|
|
170
|
+
});
|
|
171
|
+
const err = rpcErrorMessage(resp);
|
|
172
|
+
if (err !== undefined) {
|
|
173
|
+
throw new Error(`workbuddy-acp 切换模型 "${options.model}" 失败:${err}`);
|
|
174
|
+
}
|
|
175
|
+
},
|
|
176
|
+
extractUsage(promptResponse) {
|
|
177
|
+
return extractPromptUsage(promptResponse, false);
|
|
178
|
+
},
|
|
179
|
+
};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/** ZCode 大臣适配器:复用宿主已接入的 zcode-cli 模型与 DSH subagents 能力,避免双进程抢锁。 */
|
|
2
|
+
import type { Context } from "@deepseek-ai/cordis";
|
|
3
|
+
import type { Agent } from "@deepseek-ai/dsh-agent";
|
|
4
|
+
import type { AcpRunResult } from "../acp/client.ts";
|
|
5
|
+
import type { AcpMemberConfig } from "../config.ts";
|
|
6
|
+
import type { AcpAdapter, MemberModelInfo } from "./types.ts";
|
|
7
|
+
/** 探测宿主中 zcode-cli 的可用模型与就绪状态。 */
|
|
8
|
+
export declare function probeZcodeHost(ctx: Context, member: AcpMemberConfig): Promise<{
|
|
9
|
+
id: string;
|
|
10
|
+
name: string;
|
|
11
|
+
adapter: "agy" | "grok" | "codex" | "workbuddy" | "zcode" | "generic";
|
|
12
|
+
status: "not-installed";
|
|
13
|
+
detail: string;
|
|
14
|
+
loginHint: string;
|
|
15
|
+
models: never[];
|
|
16
|
+
} | {
|
|
17
|
+
id: string;
|
|
18
|
+
name: string;
|
|
19
|
+
adapter: "agy" | "grok" | "codex" | "workbuddy" | "zcode" | "generic";
|
|
20
|
+
status: "not-logged-in";
|
|
21
|
+
detail: string;
|
|
22
|
+
loginHint: string;
|
|
23
|
+
models: never[];
|
|
24
|
+
} | {
|
|
25
|
+
defaultModel?: string;
|
|
26
|
+
id: string;
|
|
27
|
+
name: string;
|
|
28
|
+
adapter: "agy" | "grok" | "codex" | "workbuddy" | "zcode" | "generic";
|
|
29
|
+
status: "ready";
|
|
30
|
+
detail: string;
|
|
31
|
+
models: MemberModelInfo[];
|
|
32
|
+
loginHint?: never;
|
|
33
|
+
} | {
|
|
34
|
+
id: string;
|
|
35
|
+
name: string;
|
|
36
|
+
adapter: "agy" | "grok" | "codex" | "workbuddy" | "zcode" | "generic";
|
|
37
|
+
status: "error";
|
|
38
|
+
detail: string;
|
|
39
|
+
models: never[];
|
|
40
|
+
loginHint?: never;
|
|
41
|
+
}>;
|
|
42
|
+
/** 通过宿主 DSH subagents + zcode-cli 执行一轮异步任务并返回统一 AcpRunResult。 */
|
|
43
|
+
export declare function runZcodeViaHost(params: {
|
|
44
|
+
readonly ctx: Context;
|
|
45
|
+
readonly parentAgent: Agent;
|
|
46
|
+
readonly cwd: string;
|
|
47
|
+
readonly prompt: string;
|
|
48
|
+
readonly model?: string;
|
|
49
|
+
readonly signal: AbortSignal;
|
|
50
|
+
}): Promise<AcpRunResult>;
|
|
51
|
+
export declare const zcodeAdapter: AcpAdapter;
|