@harrylabsj/kiwi 0.12.26 → 0.12.27
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/a2a/admission.d.ts +35 -0
- package/dist/a2a/admission.js +74 -0
- package/dist/a2a/admission.js.map +1 -0
- package/dist/a2a/node.d.ts +5 -8
- package/dist/a2a/node.js +8 -25
- package/dist/a2a/node.js.map +1 -1
- package/dist/a2a/reception/agent-runtime.js.map +1 -1
- package/dist/a2a/reception/engine.js +6 -1
- package/dist/a2a/reception/engine.js.map +1 -1
- package/dist/a2a/server/merchant-handler.js +21 -6
- package/dist/a2a/server/merchant-handler.js.map +1 -1
- package/dist/a2a/server/server.js +2 -0
- package/dist/a2a/server/server.js.map +1 -1
- package/dist/a2a/throttle-config.d.ts +24 -0
- package/dist/a2a/throttle-config.js +33 -0
- package/dist/a2a/throttle-config.js.map +1 -0
- package/dist/agent/kernel-builder.d.ts +7 -1
- package/dist/agent/kernel-builder.js +8 -6
- package/dist/agent/kernel-builder.js.map +1 -1
- package/dist/agent/kernel.d.ts +10 -0
- package/dist/agent/kernel.js +13 -8
- package/dist/agent/kernel.js.map +1 -1
- package/dist/agent/merchant/merchant-tools.d.ts +5 -0
- package/dist/agent/merchant/merchant-tools.js +6 -2
- package/dist/agent/merchant/merchant-tools.js.map +1 -1
- package/dist/agent/merchant/read-only-tools.d.ts +17 -0
- package/dist/agent/merchant/read-only-tools.js +27 -0
- package/dist/agent/merchant/read-only-tools.js.map +1 -0
- package/dist/auth/merchant-oauth.d.ts +10 -0
- package/dist/auth/merchant-oauth.js +53 -4
- package/dist/auth/merchant-oauth.js.map +1 -1
- package/dist/auth/merchant-scopes.d.ts +33 -0
- package/dist/auth/merchant-scopes.js +39 -0
- package/dist/auth/merchant-scopes.js.map +1 -0
- package/dist/buyer-core/stale-merchant-wake.d.ts +27 -0
- package/dist/buyer-core/stale-merchant-wake.js +117 -0
- package/dist/buyer-core/stale-merchant-wake.js.map +1 -0
- package/dist/cloud/bootstrap.js +15 -1
- package/dist/cloud/bootstrap.js.map +1 -1
- package/dist/cloud/config.d.ts +14 -0
- package/dist/cloud/config.js +30 -0
- package/dist/cloud/config.js.map +1 -1
- package/dist/config/profile.d.ts +19 -0
- package/dist/config/profile.js +38 -1
- package/dist/config/profile.js.map +1 -1
- package/dist/http/merchant-management/api.d.ts +3 -0
- package/dist/http/merchant-management/api.js +62 -0
- package/dist/http/merchant-management/api.js.map +1 -1
- package/dist/http/merchant-management/page.js +74 -1
- package/dist/http/merchant-management/page.js.map +1 -1
- package/dist/mcp/merchant-auth.d.ts +30 -0
- package/dist/mcp/merchant-auth.js +72 -0
- package/dist/mcp/merchant-auth.js.map +1 -1
- package/dist/mcp/merchant-conversation.d.ts +91 -0
- package/dist/mcp/merchant-conversation.js +207 -0
- package/dist/mcp/merchant-conversation.js.map +1 -0
- package/dist/mcp/merchant-runtime-assembly.d.ts +3 -1
- package/dist/mcp/merchant-runtime-assembly.js +74 -7
- package/dist/mcp/merchant-runtime-assembly.js.map +1 -1
- package/dist/mcp/merchant-server.d.ts +22 -2
- package/dist/mcp/merchant-server.js +45 -4
- package/dist/mcp/merchant-server.js.map +1 -1
- package/dist/mcp/merchant-tools.d.ts +6 -12
- package/dist/mcp/merchant-tools.js +129 -8
- package/dist/mcp/merchant-tools.js.map +1 -1
- package/dist/mcp/read-audit.d.ts +63 -0
- package/dist/mcp/read-audit.js +111 -0
- package/dist/mcp/read-audit.js.map +1 -0
- package/dist/merchant/ai-runtime/owner-sdk-tools.d.ts +1 -1
- package/dist/merchant/ai-runtime/owner-storage-admission.js +11 -7
- package/dist/merchant/ai-runtime/owner-storage-admission.js.map +1 -1
- package/dist/merchant/operations-report.d.ts +12 -0
- package/dist/merchant/operations-report.js +17 -0
- package/dist/merchant/operations-report.js.map +1 -1
- package/dist/merchant/workbench-service.d.ts +45 -3
- package/dist/merchant/workbench-service.js +119 -4
- package/dist/merchant/workbench-service.js.map +1 -1
- package/dist/merchant-core/service.d.ts +7 -0
- package/dist/merchant-core/service.js +12 -0
- package/dist/merchant-core/service.js.map +1 -1
- package/dist/merchant-core/storage/redact.js +3 -0
- package/dist/merchant-core/storage/redact.js.map +1 -1
- package/dist/merchant-gateway/cli.js +9 -1
- package/dist/merchant-gateway/cli.js.map +1 -1
- package/dist/merchant-gateway/entry-server.js +2 -1
- package/dist/merchant-gateway/entry-server.js.map +1 -1
- package/dist/merchant-gateway/instance-tool-policy.d.ts +23 -0
- package/dist/merchant-gateway/instance-tool-policy.js +26 -0
- package/dist/merchant-gateway/instance-tool-policy.js.map +1 -0
- package/dist/runtime/tools.d.ts +1 -1
- package/dist/weixin/brand.d.ts +19 -0
- package/dist/weixin/brand.js +28 -0
- package/dist/weixin/brand.js.map +1 -0
- package/dist/weixin/ilink-client.d.ts +16 -3
- package/dist/weixin/ilink-client.js +39 -6
- package/dist/weixin/ilink-client.js.map +1 -1
- package/dist/weixin/login.d.ts +3 -1
- package/dist/weixin/login.js +82 -46
- package/dist/weixin/login.js.map +1 -1
- package/dist/weixin/types.d.ts +16 -1
- package/dist/weixin/types.js.map +1 -1
- package/dist/workbuddy-adapter/binding.d.ts +19 -0
- package/dist/workbuddy-adapter/binding.js +66 -0
- package/dist/workbuddy-adapter/binding.js.map +1 -0
- package/dist/workbuddy-adapter/cli.d.ts +31 -0
- package/dist/workbuddy-adapter/cli.js +754 -0
- package/dist/workbuddy-adapter/cli.js.map +1 -0
- package/dist/workbuddy-adapter/client-cache.d.ts +11 -0
- package/dist/workbuddy-adapter/client-cache.js +17 -0
- package/dist/workbuddy-adapter/client-cache.js.map +1 -0
- package/dist/workbuddy-adapter/index.d.ts +7 -0
- package/dist/workbuddy-adapter/index.js +8 -0
- package/dist/workbuddy-adapter/index.js.map +1 -0
- package/dist/workbuddy-adapter/mcp-client.d.ts +34 -0
- package/dist/workbuddy-adapter/mcp-client.js +167 -0
- package/dist/workbuddy-adapter/mcp-client.js.map +1 -0
- package/dist/workbuddy-adapter/oauth.d.ts +84 -0
- package/dist/workbuddy-adapter/oauth.js +327 -0
- package/dist/workbuddy-adapter/oauth.js.map +1 -0
- package/dist/workbuddy-adapter/token-store.d.ts +35 -0
- package/dist/workbuddy-adapter/token-store.js +137 -0
- package/dist/workbuddy-adapter/token-store.js.map +1 -0
- package/dist/workbuddy-adapter/write-lock.d.ts +19 -0
- package/dist/workbuddy-adapter/write-lock.js +90 -0
- package/dist/workbuddy-adapter/write-lock.js.map +1 -0
- package/package.json +17 -13
- package/skills/kiwi-buyer/SKILL.md +10 -2
|
@@ -0,0 +1,754 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* WorkBuddy 本机 stdio 适配器入口。
|
|
4
|
+
*
|
|
5
|
+
* kiwi-workbuddy-adapter setup 本机受控页面绑定唯一实例 + OAuth PKCE
|
|
6
|
+
* kiwi-workbuddy-adapter serve WorkBuddy stdio MCP(只读运营 + 只读对话)
|
|
7
|
+
* kiwi-workbuddy-adapter status 查看绑定状态(不含 token/sharecode)
|
|
8
|
+
* kiwi-workbuddy-adapter logout 清除本次 token(不撤旧授权时明确说明)
|
|
9
|
+
*
|
|
10
|
+
* 绑定/令牌/密钥只在本机数据目录;分享码只在 setup 表单输入并由加密 token
|
|
11
|
+
* store 保存以支持续期,不进入模型、stdout 或日志。serve 只访问绑定文件里的
|
|
12
|
+
* 固定实例,不接受工具参数指定 URL。
|
|
13
|
+
*/
|
|
14
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
15
|
+
import { createServer } from "node:http";
|
|
16
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
17
|
+
import { homedir } from "node:os";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
import { fileURLToPath } from "node:url";
|
|
20
|
+
import { McpServer } from "../mcp/server.js";
|
|
21
|
+
import { createFixedInstanceBinding, } from "./binding.js";
|
|
22
|
+
import { createAuthorizationRequest, discoverOAuth, exchangeAdapterCode, refreshAdapterToken, registerAdapterClient, revokeAdapterToken, } from "./oauth.js";
|
|
23
|
+
import { withAdapterStateLock } from "./write-lock.js";
|
|
24
|
+
import { FixedInstanceMcpClient } from "./mcp-client.js";
|
|
25
|
+
import { TokenBoundClientCache } from "./client-cache.js";
|
|
26
|
+
import { AdapterTokenStore } from "./token-store.js";
|
|
27
|
+
const DEFAULT_DATA_DIR = path.join(homedir(), ".kiwi", "workbuddy-adapter");
|
|
28
|
+
const BODY_LIMIT = 16 * 1024;
|
|
29
|
+
const SERVER_VERSION = "0.1.0";
|
|
30
|
+
function pathsFor(dir) {
|
|
31
|
+
return {
|
|
32
|
+
dir,
|
|
33
|
+
binding: path.join(dir, "binding.json"),
|
|
34
|
+
token: path.join(dir, "token.enc"),
|
|
35
|
+
key: path.join(dir, "adapter-key"),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function ensureDir(dir) {
|
|
39
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
40
|
+
chmodSync(dir, 0o700);
|
|
41
|
+
}
|
|
42
|
+
function atomicJson(file, value) {
|
|
43
|
+
const temp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
44
|
+
try {
|
|
45
|
+
writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
46
|
+
// chmod before rename; after a successful rename we must not throw and
|
|
47
|
+
// leave the caller believing the commit failed.
|
|
48
|
+
chmodSync(temp, 0o600);
|
|
49
|
+
renameSync(temp, file);
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
rmSync(temp, { force: true });
|
|
53
|
+
throw error;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function loadOrCreateSecret(file) {
|
|
57
|
+
ensureDir(path.dirname(file));
|
|
58
|
+
const read = () => {
|
|
59
|
+
const value = readFileSync(file, "utf8").trim();
|
|
60
|
+
if (value.length < 32)
|
|
61
|
+
throw new Error("本机密钥文件损坏");
|
|
62
|
+
return value;
|
|
63
|
+
};
|
|
64
|
+
if (existsSync(file))
|
|
65
|
+
return read();
|
|
66
|
+
const secret = randomBytes(32).toString("base64url");
|
|
67
|
+
try {
|
|
68
|
+
// Exclusive create: concurrent status/setup/serve must not overwrite a key
|
|
69
|
+
// another process just generated (that would orphan the encrypted token).
|
|
70
|
+
writeFileSync(file, `${secret}\n`, { mode: 0o600, flag: "wx" });
|
|
71
|
+
chmodSync(file, 0o600);
|
|
72
|
+
return secret;
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
if (error.code === "EEXIST")
|
|
76
|
+
return read();
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function loadBinding(paths) {
|
|
81
|
+
if (!existsSync(paths.binding))
|
|
82
|
+
return undefined;
|
|
83
|
+
const value = JSON.parse(readFileSync(paths.binding, "utf8"));
|
|
84
|
+
if (value.version !== 1)
|
|
85
|
+
throw new Error("绑定文件版本不支持");
|
|
86
|
+
return value;
|
|
87
|
+
}
|
|
88
|
+
function saveBinding(paths, binding) {
|
|
89
|
+
ensureDir(paths.dir);
|
|
90
|
+
atomicJson(paths.binding, binding);
|
|
91
|
+
}
|
|
92
|
+
/** 不含 token/sharecode 的绑定版本指纹,用于跨进程提交前复核。 */
|
|
93
|
+
function bindingSignature(binding) {
|
|
94
|
+
if (binding === undefined)
|
|
95
|
+
return "";
|
|
96
|
+
return createHash("sha256")
|
|
97
|
+
.update([
|
|
98
|
+
binding.instanceUrl,
|
|
99
|
+
binding.issuer,
|
|
100
|
+
binding.clientId,
|
|
101
|
+
Array.isArray(binding.metadata?.scopes_supported)
|
|
102
|
+
? binding.metadata.scopes_supported.join(" ")
|
|
103
|
+
: "",
|
|
104
|
+
].join("\u0000"))
|
|
105
|
+
.digest("hex");
|
|
106
|
+
}
|
|
107
|
+
function storeFor(paths, binding) {
|
|
108
|
+
return new AdapterTokenStore({
|
|
109
|
+
file: paths.token,
|
|
110
|
+
binding,
|
|
111
|
+
secret: loadOrCreateSecret(paths.key),
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
function jsonResult(value, isError = false) {
|
|
115
|
+
return {
|
|
116
|
+
content: [{ type: "text", text: JSON.stringify(value) }],
|
|
117
|
+
...(isError ? { isError: true } : {}),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
function failure() {
|
|
121
|
+
return {
|
|
122
|
+
content: [{ type: "text", text: "商家实例操作失败(已收敛;请检查绑定、授权或网络)" }],
|
|
123
|
+
isError: true,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
function tool(name, description, inputSchema, handle) {
|
|
127
|
+
return { name, description, inputSchema, handle };
|
|
128
|
+
}
|
|
129
|
+
function parseArgs(argv) {
|
|
130
|
+
const command = argv[0] ?? "serve";
|
|
131
|
+
let dataDir = process.env.KIWI_WORKBUDDY_ADAPTER_DIR ?? DEFAULT_DATA_DIR;
|
|
132
|
+
for (let i = 1; i < argv.length; i += 1) {
|
|
133
|
+
if (argv[i] === "--data-dir" && argv[i + 1] !== undefined) {
|
|
134
|
+
dataDir = argv[i + 1];
|
|
135
|
+
i += 1;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return { command, dataDir };
|
|
139
|
+
}
|
|
140
|
+
class BoundInstance {
|
|
141
|
+
paths;
|
|
142
|
+
binding;
|
|
143
|
+
cache = new TokenBoundClientCache();
|
|
144
|
+
clientInFlight;
|
|
145
|
+
tokenInFlight;
|
|
146
|
+
constructor(paths, binding) {
|
|
147
|
+
this.paths = paths;
|
|
148
|
+
this.binding = binding;
|
|
149
|
+
}
|
|
150
|
+
async ensureToken() {
|
|
151
|
+
if (this.tokenInFlight !== undefined)
|
|
152
|
+
return this.tokenInFlight;
|
|
153
|
+
const run = this.doEnsureToken();
|
|
154
|
+
this.tokenInFlight = run;
|
|
155
|
+
try {
|
|
156
|
+
return await run;
|
|
157
|
+
}
|
|
158
|
+
finally {
|
|
159
|
+
if (this.tokenInFlight === run)
|
|
160
|
+
this.tokenInFlight = undefined;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
validateStoredToken(token) {
|
|
164
|
+
if (!token.scope.includes("merchant:read") ||
|
|
165
|
+
token.scope.some((scope) => scope !== "merchant:read" && scope !== "merchant:owner")) {
|
|
166
|
+
throw new Error("stored token has unsupported scope");
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
async doEnsureToken() {
|
|
170
|
+
return withAdapterStateLock(this.paths.dir, async () => {
|
|
171
|
+
// 锁内读最新 binding/token;运行中的 serve 不得在 setup 重绑定后继续使用旧实例。
|
|
172
|
+
const currentBinding = loadBinding(this.paths);
|
|
173
|
+
if (currentBinding === undefined ||
|
|
174
|
+
currentBinding.instanceUrl !== this.binding.instanceUrl ||
|
|
175
|
+
currentBinding.issuer !== this.binding.issuer ||
|
|
176
|
+
currentBinding.clientId !== this.binding.clientId) {
|
|
177
|
+
throw new Error("instance binding changed");
|
|
178
|
+
}
|
|
179
|
+
const fixed = createFixedInstanceBinding({
|
|
180
|
+
instanceUrl: this.binding.instanceUrl,
|
|
181
|
+
issuer: this.binding.issuer,
|
|
182
|
+
});
|
|
183
|
+
const store = storeFor(this.paths, fixed);
|
|
184
|
+
const current = store.load();
|
|
185
|
+
if (current === undefined)
|
|
186
|
+
throw new Error("adapter token missing");
|
|
187
|
+
this.validateStoredToken(current);
|
|
188
|
+
if (!store.isExpired(current))
|
|
189
|
+
return current;
|
|
190
|
+
if (current.refresh_token === undefined) {
|
|
191
|
+
throw new Error("access token 已过期且无 refresh token,需要重新授权");
|
|
192
|
+
}
|
|
193
|
+
// 锁覆盖“读取/判断过期/一次有界网络刷新/保存”:其他 serve 不会重复
|
|
194
|
+
// 使用 rotating refresh token;setup/logout 会等待本次提交或超时 fail-closed。
|
|
195
|
+
const refreshed = await refreshAdapterToken({
|
|
196
|
+
binding: fixed,
|
|
197
|
+
metadata: this.binding.metadata,
|
|
198
|
+
shareCode: current.share_code ?? "",
|
|
199
|
+
clientId: this.binding.clientId,
|
|
200
|
+
refreshToken: current.refresh_token,
|
|
201
|
+
scopes: current.scope,
|
|
202
|
+
});
|
|
203
|
+
// 防御性复核:即使有绕过锁的外部写入,也不能用旧 refresh 结果覆盖新绑定/token。
|
|
204
|
+
const afterBinding = loadBinding(this.paths);
|
|
205
|
+
if (afterBinding === undefined ||
|
|
206
|
+
afterBinding.instanceUrl !== this.binding.instanceUrl ||
|
|
207
|
+
afterBinding.issuer !== this.binding.issuer ||
|
|
208
|
+
afterBinding.clientId !== this.binding.clientId) {
|
|
209
|
+
throw new Error("instance binding changed");
|
|
210
|
+
}
|
|
211
|
+
const latest = store.load();
|
|
212
|
+
if (latest === undefined)
|
|
213
|
+
throw new Error("adapter token missing");
|
|
214
|
+
if (latest.access_token !== current.access_token) {
|
|
215
|
+
this.validateStoredToken(latest);
|
|
216
|
+
if (!store.isExpired(latest))
|
|
217
|
+
return latest;
|
|
218
|
+
throw new Error("token changed concurrently; retry");
|
|
219
|
+
}
|
|
220
|
+
if (!store.isExpired(latest))
|
|
221
|
+
return latest;
|
|
222
|
+
const merged = {
|
|
223
|
+
...refreshed,
|
|
224
|
+
...(current.share_code !== undefined ? { share_code: current.share_code } : {}),
|
|
225
|
+
};
|
|
226
|
+
this.validateStoredToken(merged);
|
|
227
|
+
store.save(merged);
|
|
228
|
+
return merged;
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
async clientFor() {
|
|
232
|
+
// 先检查/续期 token,再决定是否复用正在创建的 client;并发刷新共享一次。
|
|
233
|
+
const token = await this.ensureToken();
|
|
234
|
+
const existing = this.clientInFlight;
|
|
235
|
+
if (existing !== undefined && existing.token === token.access_token) {
|
|
236
|
+
return existing.promise;
|
|
237
|
+
}
|
|
238
|
+
const entry = {
|
|
239
|
+
token: token.access_token,
|
|
240
|
+
promise: this.cache.get(token, async (current) => {
|
|
241
|
+
const fixed = createFixedInstanceBinding({
|
|
242
|
+
instanceUrl: this.binding.instanceUrl,
|
|
243
|
+
issuer: this.binding.issuer,
|
|
244
|
+
});
|
|
245
|
+
const client = new FixedInstanceMcpClient({
|
|
246
|
+
binding: fixed,
|
|
247
|
+
accessToken: current.access_token,
|
|
248
|
+
shareCode: current.share_code ?? "",
|
|
249
|
+
});
|
|
250
|
+
await client.initialize();
|
|
251
|
+
return client;
|
|
252
|
+
}),
|
|
253
|
+
};
|
|
254
|
+
this.clientInFlight = entry;
|
|
255
|
+
try {
|
|
256
|
+
return await entry.promise;
|
|
257
|
+
}
|
|
258
|
+
finally {
|
|
259
|
+
if (this.clientInFlight === entry)
|
|
260
|
+
this.clientInFlight = undefined;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
async call(name, args) {
|
|
264
|
+
try {
|
|
265
|
+
const client = await this.clientFor();
|
|
266
|
+
const result = await client.callTool(name, args);
|
|
267
|
+
return {
|
|
268
|
+
content: [
|
|
269
|
+
{ type: "text", text: result.text || JSON.stringify(result.structuredContent ?? {}) },
|
|
270
|
+
],
|
|
271
|
+
...(result.isError ? { isError: true } : {}),
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
catch {
|
|
275
|
+
// 不在不确定是否已执行时重试;只读工具也避免重复对话 turn。
|
|
276
|
+
this.cache.clear();
|
|
277
|
+
return failure();
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
export function parseListNegotiationArgs(args) {
|
|
282
|
+
const allowed = new Set(["cursor", "status", "limit"]);
|
|
283
|
+
if (Object.keys(args).some((key) => !allowed.has(key)))
|
|
284
|
+
return undefined;
|
|
285
|
+
const parsed = {};
|
|
286
|
+
if (args.cursor !== undefined) {
|
|
287
|
+
if (typeof args.cursor !== "string" || !/^\d+$/.test(args.cursor))
|
|
288
|
+
return undefined;
|
|
289
|
+
parsed.cursor = args.cursor;
|
|
290
|
+
}
|
|
291
|
+
if (args.status !== undefined) {
|
|
292
|
+
if (args.status !== "active" && args.status !== "agreement" && args.status !== "all") {
|
|
293
|
+
return undefined;
|
|
294
|
+
}
|
|
295
|
+
parsed.status = args.status;
|
|
296
|
+
}
|
|
297
|
+
if (args.limit !== undefined) {
|
|
298
|
+
if (typeof args.limit !== "number" ||
|
|
299
|
+
!Number.isSafeInteger(args.limit) ||
|
|
300
|
+
args.limit < 1 ||
|
|
301
|
+
args.limit > 100) {
|
|
302
|
+
return undefined;
|
|
303
|
+
}
|
|
304
|
+
parsed.limit = args.limit;
|
|
305
|
+
}
|
|
306
|
+
return parsed;
|
|
307
|
+
}
|
|
308
|
+
async function serve(dataDir) {
|
|
309
|
+
const paths = pathsFor(dataDir);
|
|
310
|
+
const stored = loadBinding(paths);
|
|
311
|
+
if (stored === undefined) {
|
|
312
|
+
process.stderr.write("未绑定实例:请先运行 kiwi-workbuddy-adapter setup\n");
|
|
313
|
+
return 2;
|
|
314
|
+
}
|
|
315
|
+
const fixed = createFixedInstanceBinding({
|
|
316
|
+
instanceUrl: stored.instanceUrl,
|
|
317
|
+
issuer: stored.issuer,
|
|
318
|
+
});
|
|
319
|
+
const store = storeFor(paths, fixed);
|
|
320
|
+
if (store.load() === undefined) {
|
|
321
|
+
process.stderr.write("未授权:请先运行 kiwi-workbuddy-adapter setup\n");
|
|
322
|
+
return 2;
|
|
323
|
+
}
|
|
324
|
+
const bound = new BoundInstance(paths, stored);
|
|
325
|
+
const tools = [
|
|
326
|
+
tool("kiwi_merchant_connection_status", "读取本机绑定的固定商家实例与授权状态(不含 token/sharecode)。", { type: "object", properties: {}, additionalProperties: false }, async () => {
|
|
327
|
+
try {
|
|
328
|
+
const token = await bound.ensureToken();
|
|
329
|
+
return jsonResult({
|
|
330
|
+
bound: true,
|
|
331
|
+
instance: fixed.instanceOrigin,
|
|
332
|
+
mcp_url: fixed.mcpUrl,
|
|
333
|
+
scope: token.scope,
|
|
334
|
+
expires_at: token.expires_at,
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
catch {
|
|
338
|
+
return failure();
|
|
339
|
+
}
|
|
340
|
+
}),
|
|
341
|
+
tool("kiwi_merchant_get_operations_report", "读取本商家实例运营报告(只读;固定绑定实例)。", {
|
|
342
|
+
type: "object",
|
|
343
|
+
properties: {
|
|
344
|
+
period: { type: "string", enum: ["day", "week", "month"] },
|
|
345
|
+
},
|
|
346
|
+
additionalProperties: false,
|
|
347
|
+
}, (args) => bound.call("kiwi_merchant_get_operations_report", args)),
|
|
348
|
+
tool("kiwi_merchant_list_a2a_negotiations", "列出本商家实例 A2A 磋商(只读;支持 cursor/status/limit)。", {
|
|
349
|
+
type: "object",
|
|
350
|
+
properties: {
|
|
351
|
+
cursor: { type: "string", pattern: "^\\d+$" },
|
|
352
|
+
status: { type: "string", enum: ["active", "agreement", "all"] },
|
|
353
|
+
limit: { type: "integer", minimum: 1, maximum: 100 },
|
|
354
|
+
},
|
|
355
|
+
additionalProperties: false,
|
|
356
|
+
}, (args) => {
|
|
357
|
+
const parsed = parseListNegotiationArgs(args);
|
|
358
|
+
if (parsed === undefined) {
|
|
359
|
+
return Promise.resolve({
|
|
360
|
+
content: [{ type: "text", text: "参数无效:cursor/status/limit" }],
|
|
361
|
+
isError: true,
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
return bound.call("kiwi_merchant_list_a2a_negotiations", parsed);
|
|
365
|
+
}),
|
|
366
|
+
tool("kiwi_merchant_get_a2a_negotiation", "按 negotiation_id 读取本商家实例磋商详情(只读)。", {
|
|
367
|
+
type: "object",
|
|
368
|
+
properties: { negotiation_id: { type: "string" } },
|
|
369
|
+
required: ["negotiation_id"],
|
|
370
|
+
additionalProperties: false,
|
|
371
|
+
}, (args) => bound.call("kiwi_merchant_get_a2a_negotiation", args)),
|
|
372
|
+
tool("kiwi_merchant_chat", "与本商家实例同一个云端 Kiwi 智能体只读多轮对话;返回 conversation_id。", {
|
|
373
|
+
type: "object",
|
|
374
|
+
properties: {
|
|
375
|
+
message: { type: "string" },
|
|
376
|
+
conversation_id: { type: "string" },
|
|
377
|
+
},
|
|
378
|
+
required: ["message"],
|
|
379
|
+
additionalProperties: false,
|
|
380
|
+
}, (args) => bound.call("kiwi_merchant_chat", args)),
|
|
381
|
+
];
|
|
382
|
+
const server = new McpServer({
|
|
383
|
+
tools,
|
|
384
|
+
serverInfo: { name: "kiwi-workbuddy-adapter", version: SERVER_VERSION },
|
|
385
|
+
});
|
|
386
|
+
await server.serve();
|
|
387
|
+
return 0;
|
|
388
|
+
}
|
|
389
|
+
function readBody(request) {
|
|
390
|
+
return new Promise((resolve, reject) => {
|
|
391
|
+
const chunks = [];
|
|
392
|
+
let size = 0;
|
|
393
|
+
request.on("data", (chunk) => {
|
|
394
|
+
size += chunk.length;
|
|
395
|
+
if (size > BODY_LIMIT) {
|
|
396
|
+
reject(new Error("body_too_large"));
|
|
397
|
+
request.destroy();
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
chunks.push(chunk);
|
|
401
|
+
});
|
|
402
|
+
request.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
|
403
|
+
request.on("error", reject);
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
function html(title, body) {
|
|
407
|
+
return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><title>${title}</title>
|
|
408
|
+
<style>body{font-family:system-ui,sans-serif;max-width:720px;margin:40px auto;padding:0 20px;line-height:1.6}code{background:#eef3ee;padding:2px 5px;border-radius:4px}.err{color:#b3261e}input{width:100%;padding:10px;margin:6px 0;border:1px solid #ccd}button{padding:9px 18px;border:0;border-radius:999px;background:#1b5e20;color:#fff}</style></head><body>${body}</body></html>`;
|
|
409
|
+
}
|
|
410
|
+
export async function startSetupServer(dataDir) {
|
|
411
|
+
const paths = pathsFor(dataDir);
|
|
412
|
+
ensureDir(dataDir);
|
|
413
|
+
const csrf = randomBytes(32).toString("base64url");
|
|
414
|
+
const pending = new Map();
|
|
415
|
+
const drafts = new Map();
|
|
416
|
+
let generation = 0;
|
|
417
|
+
let origin = "";
|
|
418
|
+
const server = createServer(async (request, response) => {
|
|
419
|
+
try {
|
|
420
|
+
if (String(request.headers.host ?? "") !== origin.replace("http://", "")) {
|
|
421
|
+
response.writeHead(421).end("host invalid");
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
if (request.method === "GET" && request.url === "/") {
|
|
425
|
+
response.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
|
|
426
|
+
response.end(html("绑定商家实例", `<h1>绑定唯一商家实例</h1>
|
|
427
|
+
<p>本页面只在本机 ${origin} 打开。绑定后 WorkBuddy stdio 适配器只访问该固定实例。</p>
|
|
428
|
+
<form method="post" action="/bind">
|
|
429
|
+
<input type="hidden" name="csrf" value="${csrf}">
|
|
430
|
+
<label>实例 MCP HTTPS 地址(必须 /mcp)</label>
|
|
431
|
+
<input name="instance" placeholder="https://your-instance.example.com/mcp" required>
|
|
432
|
+
<label>分享凭据(仅门禁;不是商家身份)</label>
|
|
433
|
+
<input name="share" type="password" autocomplete="off" required>
|
|
434
|
+
<button type="submit">开始 OAuth 授权</button>
|
|
435
|
+
</form>
|
|
436
|
+
<p>分享凭据只保存在本机加密 token store,用于门禁请求与续期;不写入模型/日志。</p>`));
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
if (request.method === "POST" && request.url === "/bind") {
|
|
440
|
+
if (String(request.headers.origin ?? "") !== origin) {
|
|
441
|
+
response.writeHead(403).end("origin invalid");
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
const form = new URLSearchParams(await readBody(request));
|
|
445
|
+
if (!safeEqual(form.get("csrf") ?? "", csrf)) {
|
|
446
|
+
response.writeHead(403).end("csrf invalid");
|
|
447
|
+
return;
|
|
448
|
+
}
|
|
449
|
+
const instanceUrl = (form.get("instance") ?? "").trim();
|
|
450
|
+
const shareCode = (form.get("share") ?? "").trim();
|
|
451
|
+
if (instanceUrl === "" || shareCode === "") {
|
|
452
|
+
response.writeHead(400).end("missing fields");
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
// 新绑定一开始就使旧 draft/pending 失效;即使本次 discovery 失败,
|
|
456
|
+
// 旧流程也不能回跳覆盖新选择。
|
|
457
|
+
const baseBinding = bindingSignature(loadBinding(paths));
|
|
458
|
+
generation += 1;
|
|
459
|
+
drafts.clear();
|
|
460
|
+
pending.clear();
|
|
461
|
+
const binding = createFixedInstanceBinding({ instanceUrl });
|
|
462
|
+
const metadata = await discoverOAuth(binding, shareCode);
|
|
463
|
+
const draftId = randomBytes(24).toString("base64url");
|
|
464
|
+
drafts.set(draftId, { binding, metadata, shareCode, generation, baseBinding });
|
|
465
|
+
const ownerAvailable = metadata.scopes_supported.includes("merchant:owner");
|
|
466
|
+
response.writeHead(200, {
|
|
467
|
+
"content-type": "text/html; charset=utf-8",
|
|
468
|
+
"cache-control": "no-store",
|
|
469
|
+
});
|
|
470
|
+
response.end(html("确认授权范围", `<h1>确认授权范围</h1>
|
|
471
|
+
<p>实例:<code>${binding.instanceOrigin}</code></p>
|
|
472
|
+
<p>默认只申请 <code>merchant:read</code>。${ownerAvailable ? "该实例声明支持店主报价读取,可按需勾选;不勾选则不会申请 owner scope。" : "该实例未声明 merchant:owner,不能申请店主报价读取。"}</p>
|
|
473
|
+
<form method="post" action="/authorize">
|
|
474
|
+
<input type="hidden" name="csrf" value="${csrf}">
|
|
475
|
+
<input type="hidden" name="draft" value="${draftId}">
|
|
476
|
+
${ownerAvailable ? '<label><input type="checkbox" name="owner_scope" value="1" style="width:auto"> 同时申请 merchant:owner(商家本人明确选择;用于读取自己的报价)</label>' : ""}
|
|
477
|
+
<button type="submit">继续 OAuth 授权</button>
|
|
478
|
+
</form>`));
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
if (request.method === "POST" && request.url === "/authorize") {
|
|
482
|
+
if (String(request.headers.origin ?? "") !== origin) {
|
|
483
|
+
response.writeHead(403).end("origin invalid");
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
const form = new URLSearchParams(await readBody(request));
|
|
487
|
+
if (!safeEqual(form.get("csrf") ?? "", csrf)) {
|
|
488
|
+
response.writeHead(403).end("csrf invalid");
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
const draftId = form.get("draft") ?? "";
|
|
492
|
+
const draft = drafts.get(draftId);
|
|
493
|
+
if (draft === undefined || draft.generation !== generation) {
|
|
494
|
+
response.writeHead(400).end("draft invalid or superseded");
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
const ownerRequested = form.get("owner_scope") === "1";
|
|
498
|
+
if (ownerRequested && !draft.metadata.scopes_supported.includes("merchant:owner")) {
|
|
499
|
+
response.writeHead(400).end("owner scope not supported by instance");
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
const scopes = ownerRequested ? ["merchant:read", "merchant:owner"] : ["merchant:read"];
|
|
503
|
+
const redirectUri = `${origin}/callback`;
|
|
504
|
+
const clientId = await registerAdapterClient(draft.binding, draft.metadata, redirectUri, draft.shareCode);
|
|
505
|
+
const auth = createAuthorizationRequest({
|
|
506
|
+
binding: draft.binding,
|
|
507
|
+
metadata: draft.metadata,
|
|
508
|
+
clientId,
|
|
509
|
+
redirectUri,
|
|
510
|
+
shareCode: draft.shareCode,
|
|
511
|
+
scopes,
|
|
512
|
+
});
|
|
513
|
+
drafts.delete(draftId);
|
|
514
|
+
pending.set(auth.state, {
|
|
515
|
+
request: auth,
|
|
516
|
+
shareCode: draft.shareCode,
|
|
517
|
+
binding: draft.binding,
|
|
518
|
+
metadata: draft.metadata,
|
|
519
|
+
clientId,
|
|
520
|
+
scopes,
|
|
521
|
+
generation: draft.generation,
|
|
522
|
+
baseBinding: draft.baseBinding,
|
|
523
|
+
});
|
|
524
|
+
response.writeHead(303, { location: auth.url, "cache-control": "no-store" }).end();
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
if (request.method === "GET" && request.url?.startsWith("/callback")) {
|
|
528
|
+
const url = new URL(request.url, origin);
|
|
529
|
+
const state = url.searchParams.get("state") ?? "";
|
|
530
|
+
const item = pending.get(state);
|
|
531
|
+
if (item === undefined) {
|
|
532
|
+
response.writeHead(400, { "content-type": "text/html; charset=utf-8" });
|
|
533
|
+
response.end(html("绑定失败", "<p class='err'>state 无效或已过期。</p>"));
|
|
534
|
+
return;
|
|
535
|
+
}
|
|
536
|
+
pending.delete(state);
|
|
537
|
+
if (item.generation !== generation) {
|
|
538
|
+
response.writeHead(400, { "content-type": "text/html; charset=utf-8" });
|
|
539
|
+
response.end(html("绑定失败", "<p class='err'>该授权流程已被新的绑定取代,请重新开始。</p>"));
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
const code = url.searchParams.get("code") ?? "";
|
|
543
|
+
if (url.searchParams.get("error") !== null || code === "") {
|
|
544
|
+
response.writeHead(400, { "content-type": "text/html; charset=utf-8" });
|
|
545
|
+
response.end(html("绑定失败", "<p class='err'>授权被拒绝或缺少 code,请重新绑定。</p>"));
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
const token = await exchangeAdapterCode({
|
|
549
|
+
binding: item.binding,
|
|
550
|
+
metadata: item.metadata,
|
|
551
|
+
shareCode: item.shareCode,
|
|
552
|
+
clientId: item.clientId,
|
|
553
|
+
redirectUri: `${origin}/callback`,
|
|
554
|
+
code,
|
|
555
|
+
verifier: item.request.verifier,
|
|
556
|
+
scopes: item.scopes,
|
|
557
|
+
});
|
|
558
|
+
// 交换期间若商家开始了新绑定,旧流程不得覆盖新实例/新 token。
|
|
559
|
+
if (item.generation !== generation) {
|
|
560
|
+
response.writeHead(400, { "content-type": "text/html; charset=utf-8" });
|
|
561
|
+
response.end(html("绑定失败", "<p class='err'>该授权流程已被新的绑定取代,请重新开始。</p>"));
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
await withAdapterStateLock(paths.dir, () => {
|
|
565
|
+
if (item.generation !== generation) {
|
|
566
|
+
throw new Error("binding flow superseded");
|
|
567
|
+
}
|
|
568
|
+
// 跨进程复核:另一个 setup 已提交不同绑定时,本流程不得覆盖。
|
|
569
|
+
if (bindingSignature(loadBinding(paths)) !== item.baseBinding) {
|
|
570
|
+
throw new Error("binding changed by another setup");
|
|
571
|
+
}
|
|
572
|
+
const store = storeFor(paths, item.binding);
|
|
573
|
+
const previousToken = existsSync(paths.token) ? readFileSync(paths.token) : undefined;
|
|
574
|
+
try {
|
|
575
|
+
store.save({ ...token, share_code: item.shareCode });
|
|
576
|
+
saveBinding(paths, {
|
|
577
|
+
version: 1,
|
|
578
|
+
instanceUrl: item.binding.mcpUrl,
|
|
579
|
+
issuer: item.binding.issuer,
|
|
580
|
+
mcpUrl: item.binding.mcpUrl,
|
|
581
|
+
metadata: item.metadata,
|
|
582
|
+
clientId: item.clientId,
|
|
583
|
+
redirectUri: `${origin}/callback`,
|
|
584
|
+
createdAt: new Date().toISOString(),
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
catch (error) {
|
|
588
|
+
// 绑定写入失败时恢复旧 token,避免新 token 与旧 binding 交叉。
|
|
589
|
+
if (previousToken !== undefined) {
|
|
590
|
+
writeFileSync(paths.token, previousToken, { mode: 0o600 });
|
|
591
|
+
chmodSync(paths.token, 0o600);
|
|
592
|
+
}
|
|
593
|
+
else {
|
|
594
|
+
rmSync(paths.token, { force: true });
|
|
595
|
+
}
|
|
596
|
+
throw error;
|
|
597
|
+
}
|
|
598
|
+
});
|
|
599
|
+
response.writeHead(303, { location: "/done", "cache-control": "no-store" }).end();
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
if (request.method === "GET" && request.url === "/done") {
|
|
603
|
+
response.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
|
|
604
|
+
response.end(html("绑定完成", `<h1>绑定完成</h1><p>本机已保存固定实例绑定与加密 token。可以关闭本页面。</p>
|
|
605
|
+
<p>WorkBuddy 中配置本机 stdio 命令:<code>kiwi-workbuddy-adapter serve</code></p>`));
|
|
606
|
+
return;
|
|
607
|
+
}
|
|
608
|
+
response.writeHead(404).end("not found");
|
|
609
|
+
}
|
|
610
|
+
catch {
|
|
611
|
+
response.writeHead(400).end("绑定失败(已收敛)");
|
|
612
|
+
}
|
|
613
|
+
});
|
|
614
|
+
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
|
615
|
+
const address = server.address();
|
|
616
|
+
const port = typeof address === "object" && address !== null ? address.port : 0;
|
|
617
|
+
origin = `http://127.0.0.1:${port}`;
|
|
618
|
+
return {
|
|
619
|
+
origin,
|
|
620
|
+
close: () => new Promise((resolve) => {
|
|
621
|
+
server.closeAllConnections?.();
|
|
622
|
+
server.close(() => resolve());
|
|
623
|
+
}),
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
async function setup(dataDir) {
|
|
627
|
+
const handle = await startSetupServer(dataDir);
|
|
628
|
+
process.stdout.write(`本机绑定页面:${handle.origin}/\n`);
|
|
629
|
+
process.stdout.write("请在浏览器完成商家授权;不要通过聊天/命令行传递分享凭据。\n");
|
|
630
|
+
return 0;
|
|
631
|
+
}
|
|
632
|
+
function safeEqual(a, b) {
|
|
633
|
+
const left = Buffer.from(a);
|
|
634
|
+
const right = Buffer.from(b);
|
|
635
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
636
|
+
}
|
|
637
|
+
function status(dataDir) {
|
|
638
|
+
const paths = pathsFor(dataDir);
|
|
639
|
+
if (!existsSync(paths.binding)) {
|
|
640
|
+
process.stdout.write(JSON.stringify({ bound: false }) + "\n");
|
|
641
|
+
return Promise.resolve(1);
|
|
642
|
+
}
|
|
643
|
+
return withAdapterStateLock(paths.dir, () => {
|
|
644
|
+
const binding = loadBinding(paths);
|
|
645
|
+
if (binding === undefined) {
|
|
646
|
+
process.stdout.write(JSON.stringify({ bound: false }) + "\n");
|
|
647
|
+
return 1;
|
|
648
|
+
}
|
|
649
|
+
const fixed = createFixedInstanceBinding({
|
|
650
|
+
instanceUrl: binding.instanceUrl,
|
|
651
|
+
issuer: binding.issuer,
|
|
652
|
+
});
|
|
653
|
+
const store = storeFor(paths, fixed);
|
|
654
|
+
const token = store.load();
|
|
655
|
+
const expired = token !== undefined && store.isExpired(token);
|
|
656
|
+
process.stdout.write(JSON.stringify({
|
|
657
|
+
bound: true,
|
|
658
|
+
instance: fixed.instanceOrigin,
|
|
659
|
+
mcp_url: fixed.mcpUrl,
|
|
660
|
+
authorized: token !== undefined && !expired,
|
|
661
|
+
expired,
|
|
662
|
+
scope: token?.scope,
|
|
663
|
+
expires_at: token?.expires_at,
|
|
664
|
+
}) + "\n");
|
|
665
|
+
return token === undefined ? 1 : 0;
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
async function logout(dataDir) {
|
|
669
|
+
const paths = pathsFor(dataDir);
|
|
670
|
+
if (!existsSync(paths.binding))
|
|
671
|
+
return 0;
|
|
672
|
+
const snapshot = await withAdapterStateLock(paths.dir, () => {
|
|
673
|
+
const binding = loadBinding(paths);
|
|
674
|
+
if (binding === undefined)
|
|
675
|
+
return undefined;
|
|
676
|
+
const fixed = createFixedInstanceBinding({
|
|
677
|
+
instanceUrl: binding.instanceUrl,
|
|
678
|
+
issuer: binding.issuer,
|
|
679
|
+
});
|
|
680
|
+
const store = storeFor(paths, fixed);
|
|
681
|
+
return { binding, fixed, store, token: store.load() };
|
|
682
|
+
});
|
|
683
|
+
if (snapshot === undefined)
|
|
684
|
+
return 0;
|
|
685
|
+
const { binding, fixed, store, token } = snapshot;
|
|
686
|
+
if (token === undefined) {
|
|
687
|
+
process.stdout.write(JSON.stringify({ cleared: true, revoked: false }) + "\n");
|
|
688
|
+
return 0;
|
|
689
|
+
}
|
|
690
|
+
// 网络撤销不持锁;提交清理前在锁内复核 token 代次。
|
|
691
|
+
const revokedAccess = await revokeAdapterToken({
|
|
692
|
+
binding: fixed,
|
|
693
|
+
metadata: binding.metadata,
|
|
694
|
+
shareCode: token.share_code ?? "",
|
|
695
|
+
token: token.access_token,
|
|
696
|
+
});
|
|
697
|
+
const revokedRefresh = token.refresh_token === undefined
|
|
698
|
+
? false
|
|
699
|
+
: await revokeAdapterToken({
|
|
700
|
+
binding: fixed,
|
|
701
|
+
metadata: binding.metadata,
|
|
702
|
+
shareCode: token.share_code ?? "",
|
|
703
|
+
token: token.refresh_token,
|
|
704
|
+
});
|
|
705
|
+
await withAdapterStateLock(paths.dir, () => {
|
|
706
|
+
const current = store.load();
|
|
707
|
+
if (current !== undefined && current.access_token !== token.access_token) {
|
|
708
|
+
throw new Error("token changed concurrently; logout not applied");
|
|
709
|
+
}
|
|
710
|
+
store.clear();
|
|
711
|
+
});
|
|
712
|
+
process.stdout.write(JSON.stringify({
|
|
713
|
+
cleared: true,
|
|
714
|
+
access_revoked: revokedAccess,
|
|
715
|
+
refresh_revoked: revokedRefresh,
|
|
716
|
+
}) + "\n");
|
|
717
|
+
return 0;
|
|
718
|
+
}
|
|
719
|
+
export async function runWorkbuddyAdapterCli(argv) {
|
|
720
|
+
const { command, dataDir } = parseArgs(argv);
|
|
721
|
+
try {
|
|
722
|
+
if (command === "serve")
|
|
723
|
+
return await serve(dataDir);
|
|
724
|
+
if (command === "setup")
|
|
725
|
+
return await setup(dataDir);
|
|
726
|
+
if (command === "status")
|
|
727
|
+
return await status(dataDir);
|
|
728
|
+
if (command === "logout")
|
|
729
|
+
return await logout(dataDir);
|
|
730
|
+
}
|
|
731
|
+
catch {
|
|
732
|
+
process.stderr.write("适配器操作失败(已收敛;请检查本机绑定/密钥/网络)\n");
|
|
733
|
+
return 2;
|
|
734
|
+
}
|
|
735
|
+
process.stderr.write("用法:kiwi-workbuddy-adapter setup|serve|status|logout [--data-dir DIR]\n");
|
|
736
|
+
return 2;
|
|
737
|
+
}
|
|
738
|
+
const argv1 = process.argv[1];
|
|
739
|
+
if (argv1 !== undefined) {
|
|
740
|
+
let isMain = false;
|
|
741
|
+
try {
|
|
742
|
+
isMain = realpathSync(argv1) === realpathSync(fileURLToPath(import.meta.url));
|
|
743
|
+
}
|
|
744
|
+
catch {
|
|
745
|
+
isMain = false;
|
|
746
|
+
}
|
|
747
|
+
if (isMain) {
|
|
748
|
+
void runWorkbuddyAdapterCli(process.argv.slice(2)).then((code) => {
|
|
749
|
+
if (code !== 0)
|
|
750
|
+
process.exitCode = code;
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
//# sourceMappingURL=cli.js.map
|