pi-auto-web-search 0.1.2 → 1.2.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/src/tools.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { statSync } from "node:fs";
1
+ import { readdirSync, statSync } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  import type { ExtensionCommandContext, Theme, ToolDefinition } from "@earendil-works/pi-coding-agent";
4
4
  import { validateToolArguments, type JsonObject, type JsonValue } from "@earendil-works/pi-ai";
@@ -9,6 +9,11 @@ import { ConfigStore, type LoadedConfig, type ResolveConfigOptions } from "./con
9
9
  import {
10
10
  CloudflareOAuth,
11
11
  DEFAULT_CONFIG_PATH,
12
+ LEGACY_OAUTH_TARGET,
13
+ logoutLegacyOAuth,
14
+ migrateLegacyOAuthToken,
15
+ readAllInstanceOAuthTokens,
16
+ readInstanceOAuthToken,
12
17
  readOAuthToken,
13
18
  type OAuthToken,
14
19
  } from "./cloudflare-oauth.ts";
@@ -35,8 +40,10 @@ export function resolveConfigPath(env: NodeJS.ProcessEnv = process.env): string
35
40
 
36
41
  export interface SearchRuntimeOptions {
37
42
  configPath: string;
38
- /** Cloudflare OAuth 令牌文件路径,默认与配置文件同目录下的 search-oauth.json。 */
39
- tokenPath?: string;
43
+ /** Cloudflare OAuth 多实例令牌目录,默认与配置文件同目录下的 search-oauth。 */
44
+ oauthDir?: string;
45
+ /** 旧版 Cloudflare OAuth 单文件令牌路径,默认与配置文件同目录下的 search-oauth.json。 */
46
+ legacyTokenPath?: string;
40
47
  /** 按密钥调用次数记录文件路径,默认与配置文件同目录下的 search-usage.json。 */
41
48
  usagePath?: string;
42
49
  env?: NodeJS.ProcessEnv;
@@ -50,7 +57,8 @@ export interface SearchRuntimeOptions {
50
57
  /** 搜索与抓取工具的运行期状态:配置未变时复用同一个 HttpClient,冷却与并发闸门才能跨调用生效。 */
51
58
  export class SearchRuntime {
52
59
  readonly configPath: string;
53
- readonly tokenPath: string;
60
+ readonly oauthDir: string;
61
+ readonly legacyTokenPath: string;
54
62
  readonly usagePath: string;
55
63
  readonly store: ConfigStore;
56
64
  readonly usage: UsageStore;
@@ -60,13 +68,16 @@ export class SearchRuntime {
60
68
  private readonly oauthAccountsUrl?: string;
61
69
  private readonly oauthRevokeUrl?: string;
62
70
  private loaded?: { signature: string; config: LoadedConfig; service: SearchService };
63
- private oauthCache?: { key: string; client: CloudflareOAuth };
71
+ private readonly oauthCache = new Map<string, { key: string; client: CloudflareOAuth }>();
64
72
  lastSuccess?: string;
65
73
  private readonly failures = new Map<string, string>();
74
+ private readonly oauthReadErrors = new Map<string | undefined, string>();
75
+ private migrationError?: string;
66
76
 
67
77
  constructor(options: SearchRuntimeOptions) {
68
78
  this.configPath = options.configPath;
69
- this.tokenPath = options.tokenPath ?? join(dirname(options.configPath), "search-oauth.json");
79
+ this.oauthDir = options.oauthDir ?? join(dirname(options.configPath), "search-oauth");
80
+ this.legacyTokenPath = options.legacyTokenPath ?? join(dirname(options.configPath), "search-oauth.json");
70
81
  this.usagePath = options.usagePath ?? join(dirname(options.configPath), "search-usage.json");
71
82
  this.store = new ConfigStore(options.configPath);
72
83
  this.clock = options.clock;
@@ -77,49 +88,116 @@ export class SearchRuntime {
77
88
  this.oauthRevokeUrl = options.oauthRevokeUrl;
78
89
  }
79
90
 
80
- /** 当前本地保存的 Cloudflare OAuth 令牌。 */
81
- oauthToken(): OAuthToken | undefined {
82
- return readOAuthToken(this.tokenPath);
91
+ migrateLegacyTokens(targetId?: string): string[] {
92
+ if (!statSync(this.legacyTokenPath, { throwIfNoEntry: false })) return [];
93
+ const eligible = this.store.load(this.env).instances.filter(instance => instance.usesCloudflareOAuth);
94
+ const only = eligible.length === 1 ? eligible[0] : undefined;
95
+ if (!targetId && only?.accountIdSetting && (!only.accountId || only.accountId !== this.legacyToken()?.account_id)) return [];
96
+ return migrateLegacyOAuthToken({
97
+ legacyTokenPath: this.legacyTokenPath, tokenDir: this.oauthDir,
98
+ instanceIds: eligible.map(instance => instance.id), targetId,
99
+ });
100
+ }
101
+
102
+ legacyToken(): OAuthToken | undefined {
103
+ return readOAuthToken(this.legacyTokenPath);
104
+ }
105
+
106
+ logoutLegacy() {
107
+ return logoutLegacyOAuth({
108
+ legacyTokenPath: this.legacyTokenPath, tokenDir: this.oauthDir, config: this.store.load(this.env).cloudflareOAuth,
109
+ fetch: this.oauthFetch, revokeUrl: this.oauthRevokeUrl,
110
+ });
111
+ }
112
+
113
+ oauthProblem(id: string): string | undefined {
114
+ return this.oauthReadErrors.get(id) ?? this.oauthReadErrors.get(undefined) ?? this.migrationError;
115
+ }
116
+
117
+ oauthNotices(): string[] {
118
+ const notices = Array.from(this.oauthReadErrors, ([id, error]) =>
119
+ `Cloudflare OAuth ${id ? `实例 ${id} 的凭据` : "目录"}读取失败:${error}`);
120
+ if (this.migrationError) notices.push(this.migrationError);
121
+ else {
122
+ try {
123
+ if (this.legacyToken()) notices.push(`旧版 OAuth 授权尚未迁移:/search migrate cloudflare <实例> 认领,或 /search logout cloudflare ${LEGACY_OAUTH_TARGET} 撤销`);
124
+ } catch (error) {
125
+ notices.push(`旧版 OAuth 凭据读取失败:${messageOf(error)}`);
126
+ }
127
+ }
128
+ return notices;
129
+ }
130
+
131
+ private autoMigrate(): void {
132
+ try {
133
+ this.migrateLegacyTokens();
134
+ this.migrationError = undefined;
135
+ } catch (error) {
136
+ this.migrationError = `旧版 OAuth 迁移失败:${messageOf(error)}`;
137
+ }
138
+ }
139
+
140
+ /** 读取指定实例当前保存的 Cloudflare OAuth 令牌。 */
141
+ oauthToken(instanceId: string): OAuthToken | undefined {
142
+ try {
143
+ return readInstanceOAuthToken(this.oauthDir, instanceId)?.token;
144
+ } catch (error) {
145
+ this.oauthReadErrors.set(instanceId, messageOf(error));
146
+ return undefined;
147
+ }
148
+ }
149
+
150
+ /** 读取所有已保存的 Cloudflare OAuth 实例令牌。 */
151
+ oauthTokens(): Record<string, OAuthToken> {
152
+ this.oauthReadErrors.clear();
153
+ return readAllInstanceOAuthTokens(this.oauthDir, (id, error) => this.oauthReadErrors.set(id, messageOf(error)));
83
154
  }
84
155
 
85
156
  /** 供配置解析使用的 OAuth 摘要,让无静态 key 的 cloudflare sdk 实例在登录后立即就绪。 */
86
157
  resolveOptions(): ResolveConfigOptions {
87
- const token = this.oauthToken();
88
- return token ? { cloudflareOAuthToken: { accountId: token.account_id || undefined } } : {};
158
+ const tokens = this.oauthTokens();
159
+ const summaries = Object.entries(tokens).map(([id, token]) => [id, { accountId: token.account_id || undefined }] as const);
160
+ const failures = new Set(this.oauthReadErrors.keys());
161
+ if (this.migrationError) failures.add(undefined);
162
+ return { cloudflareOAuthTokens: Object.fromEntries(summaries), cloudflareOAuthReadFailures: failures };
89
163
  }
90
164
 
91
- /** 复用同一个 CloudflareOAuth 实例,保留 beginLogin → completeLogin 之间的内存 state。 */
92
- cloudflareOAuth(config?: LoadedConfig): CloudflareOAuth {
93
- const oauthConfig = (config ?? this.store.load(this.env, this.resolveOptions())).cloudflareOAuth;
165
+ /** 按实例复用 CloudflareOAuth 客户端,保留 beginLogin → completeLogin 之间的内存 state。 */
166
+ cloudflareOAuth(instanceId: string, config?: LoadedConfig): CloudflareOAuth {
167
+ const oauthConfig = (config ?? this.store.load(this.env)).cloudflareOAuth;
94
168
  const key = JSON.stringify(oauthConfig);
95
- if (this.oauthCache?.key !== key) {
96
- this.oauthCache = {
97
- key,
98
- client: new CloudflareOAuth({
99
- config: oauthConfig,
100
- configPath: this.configPath,
101
- tokenPath: this.tokenPath,
102
- env: this.env,
103
- fetch: this.oauthFetch,
104
- accountsUrl: this.oauthAccountsUrl,
105
- revokeUrl: this.oauthRevokeUrl,
106
- }),
107
- };
169
+ const cached = this.oauthCache.get(instanceId);
170
+ if (cached?.key !== key) {
171
+ const client = new CloudflareOAuth({
172
+ instanceId,
173
+ config: oauthConfig,
174
+ configPath: this.configPath,
175
+ tokenDir: this.oauthDir,
176
+ env: this.env,
177
+ clock: this.clock,
178
+ fetch: this.oauthFetch,
179
+ accountsUrl: this.oauthAccountsUrl,
180
+ revokeUrl: this.oauthRevokeUrl,
181
+ });
182
+ this.oauthCache.set(instanceId, { key, client });
183
+ return client;
108
184
  }
109
- return this.oauthCache.client;
185
+ return cached.client;
110
186
  }
111
187
 
112
188
  /** 读取配置并返回服务;配置或 OAuth 令牌文件改动后重建,解析失败时直接抛出配置错误。 */
113
189
  snapshot(): { config: LoadedConfig; service: SearchService } {
190
+ this.autoMigrate();
114
191
  const signature = this.signature();
115
192
  if (this.loaded?.signature !== signature) {
116
193
  const config = this.store.load(this.env, this.resolveOptions());
117
- const cloudflareOAuth = this.cloudflareOAuth(config);
118
194
  const service = new SearchService(
119
195
  config,
120
196
  new HttpClient(config, {
121
197
  env: this.env,
122
- cloudflareOAuth,
198
+ cloudflareOAuth: {
199
+ accessToken: (id, account) => this.cloudflareOAuth(id, config).accessToken(account),
200
+ },
123
201
  usage: this.usage,
124
202
  onInstanceFailure: (hop) => this.recordFailure(hop.instance, failureLabel(hop.code, hop.status)),
125
203
  clock: this.clock,
@@ -150,19 +228,33 @@ export class SearchRuntime {
150
228
  }
151
229
 
152
230
  private signature(): string {
153
- return `${fileSignature(this.configPath)}|${fileSignature(this.tokenPath)}`;
231
+ return `${fileSignature(this.configPath)}|${fileSignature(this.legacyTokenPath)}|${oauthDirSignature(this.oauthDir)}`;
154
232
  }
155
233
  }
156
234
 
157
235
  function fileSignature(path: string): string {
158
236
  try {
159
237
  const stats = statSync(path);
160
- return `${stats.mtimeMs}:${stats.size}`;
161
- } catch {
162
- return "missing";
238
+ return `${stats.ino}:${stats.ctimeMs}:${stats.mtimeMs}:${stats.size}`;
239
+ } catch (error) {
240
+ return `stat:${(error as NodeJS.ErrnoException).code}`;
163
241
  }
164
242
  }
165
243
 
244
+ function oauthDirSignature(dir: string): string {
245
+ let entries: string[];
246
+ try {
247
+ entries = readdirSync(dir);
248
+ } catch (error) {
249
+ return `readdir:${(error as NodeJS.ErrnoException).code}`;
250
+ }
251
+ return entries
252
+ .filter((name) => name.endsWith(".json"))
253
+ .sort()
254
+ .map((name) => `${name}:${fileSignature(join(dir, name))}`)
255
+ .join(",");
256
+ }
257
+
166
258
  /** 纯 enum 的字符串枚举:各供应商都接受,且能保留字面量类型。 */
167
259
  function stringEnum<const T extends readonly string[]>(values: T, description: string) {
168
260
  return Type.Unsafe<T[number]>({ type: "string", enum: [...values], description });
@@ -846,9 +938,12 @@ export function statusText(runtime: SearchRuntime): string {
846
938
  } catch (error) {
847
939
  return [header, `读取失败:${messageOf(error)}`].join("\n");
848
940
  }
941
+ const tokens = runtime.oauthTokens();
942
+ const notices = runtime.oauthNotices();
849
943
  if (config.instances.length === 0) {
850
944
  return [
851
945
  header,
946
+ ...notices,
852
947
  "还没有实例。在该文件里加入,例如:",
853
948
  '{"instances": [{"id": "anysearch", "preset": "anysearch", "mode": "sdk", "keys": []}]}',
854
949
  "保存后运行 /search 查看状态,/search test [实例] 发一次真实请求。",
@@ -865,15 +960,22 @@ export function statusText(runtime: SearchRuntime): string {
865
960
  const lastError = runtime.lastFailure(instance.id);
866
961
  lines.push(` ${instance.id.padEnd(width)} ${instance.preset.id} · ${instance.mode} · ${state}${quotaPart}${warnings}${lastError ? ` · 上次错误 ${lastError}` : ""}`);
867
962
  }
868
- const token = runtime.oauthToken();
869
- if (token || config.instances.some((instance) => instance.preset.id === "cloudflare")) {
870
- const oauthLabel = token
871
- ? token.account_id
872
- ? `已登录(accountId ${token.account_id})`
873
- : "已登录"
874
- : "未登录(/search login cloudflare)";
875
- lines.push(`Cloudflare OAuth:${oauthLabel}`);
963
+ const oauthInstanceIds = [
964
+ ...new Set([
965
+ ...config.instances.filter((instance) => instance.usesCloudflareOAuth).map((instance) => instance.id),
966
+ ...Object.keys(tokens),
967
+ ]),
968
+ ];
969
+ if (oauthInstanceIds.length > 0) {
970
+ const items = oauthInstanceIds.map((id) => {
971
+ const token = tokens[id];
972
+ if (!token && runtime.oauthProblem(id)) return `${id} 凭据不可用`;
973
+ if (!token) return `${id} 未登录(/search login cloudflare ${id})`;
974
+ return token.account_id ? `${id} 已登录(accountId ${token.account_id})` : `${id} 已登录`;
975
+ });
976
+ lines.push(`Cloudflare OAuth:${items.join(";")}`);
876
977
  }
978
+ lines.push(...notices);
877
979
  if (runtime.lastSuccess) lines.push(`上次命中:${runtime.lastSuccess}`);
878
980
  lines.push(`搜索链:${config.searchChain.join(" → ") || "(空)"}`);
879
981
  lines.push(`抓取链:${config.fetchChain.join(" → ") || "(空)"}`);
@@ -881,37 +983,71 @@ export function statusText(runtime: SearchRuntime): string {
881
983
  return lines.join("\n");
882
984
  }
883
985
 
884
- /** /search 命令:无参数时在交互式终端打开面板,支持 status、test、login/logout cloudflare。 */
986
+ function resolveCommandOAuthTarget(
987
+ runtime: SearchRuntime,
988
+ target: string | undefined,
989
+ instanceArg: string | undefined,
990
+ includeStoredTokens: boolean,
991
+ ): { ok: true; instanceId?: string } | { ok: false } {
992
+ if (target === undefined) return { ok: true };
993
+ if (target === "cloudflare") return { ok: true, instanceId: instanceArg };
994
+ try {
995
+ const matched = runtime.snapshot().config.instances.find((item) => item.id === target);
996
+ if (matched?.usesCloudflareOAuth) return { ok: true, instanceId: target };
997
+ } catch {
998
+ // 忽略读取异常,交由后续登录/登出流程统一报告配置错误。
999
+ }
1000
+ if (includeStoredTokens && runtime.oauthToken(target)) return { ok: true, instanceId: target };
1001
+ return { ok: false };
1002
+ }
1003
+
1004
+ /** /search 命令:无参数时在交互式终端打开面板,支持 status、test、login/logout cloudflare [实例]。 */
885
1005
  export function createSearchCommand(runtime: SearchRuntime): {
886
1006
  description: string;
887
1007
  handler: (args: string, ctx: ExtensionCommandContext) => Promise<void>;
888
1008
  } {
889
1009
  return {
890
- description: "打开设置面板、查看状态、测试连接或登录 Cloudflare OAuth:/search [status|test [实例]|login cloudflare|logout cloudflare]",
1010
+ description: "打开设置面板、查看状态、测试连接或登录 Cloudflare OAuth:/search [status|test [实例]|login cloudflare [实例]|logout cloudflare [实例|@legacy]|migrate cloudflare <实例>]",
891
1011
  async handler(args, ctx) {
892
- const [action, target] = args.trim().split(/\s+/).filter(Boolean);
1012
+ const [action, target, instanceArg] = args.trim().split(/\s+/).filter(Boolean);
893
1013
  if (action === "test") {
894
1014
  await testConnection(runtime, target, ctx);
895
1015
  return;
896
1016
  }
1017
+ if (action === "migrate") {
1018
+ if (target !== "cloudflare" || !instanceArg) {
1019
+ ctx.ui.notify("用法:/search migrate cloudflare <实例>", "warning");
1020
+ return;
1021
+ }
1022
+ try {
1023
+ const claimed = runtime.migrateLegacyTokens(instanceArg);
1024
+ runtime.reload();
1025
+ ctx.ui.notify(claimed.length ? `旧版 OAuth 授权已迁移到 ${instanceArg}` : "没有可迁移的旧版 OAuth 授权", claimed.length ? "info" : "warning");
1026
+ } catch (error) {
1027
+ ctx.ui.notify(`旧版 OAuth 迁移失败:${messageOf(error)}`, "error");
1028
+ }
1029
+ return;
1030
+ }
897
1031
  if (action === "login") {
898
- if (target !== undefined && target !== "cloudflare") {
899
- ctx.ui.notify("当前仅支持 Cloudflare OAuth 登录:/search login cloudflare", "warning");
1032
+ const resolved = resolveCommandOAuthTarget(runtime, target, instanceArg, false);
1033
+ if (!resolved.ok) {
1034
+ ctx.ui.notify("当前仅支持 Cloudflare OAuth 登录:/search login cloudflare [实例]", "warning");
900
1035
  return;
901
1036
  }
902
1037
  if (!ctx.hasUI) {
903
- ctx.ui.notify("Cloudflare OAuth 登录需要在交互式终端中运行:/search login cloudflare", "warning");
1038
+ ctx.ui.notify("Cloudflare OAuth 登录需要在交互式终端中运行:/search login cloudflare [实例]", "warning");
904
1039
  return;
905
1040
  }
906
- await runCloudflareLogin(ctx, { source: runtime, failureText });
1041
+ await runCloudflareLogin(ctx, { source: runtime, failureText }, resolved.instanceId);
907
1042
  return;
908
1043
  }
909
1044
  if (action === "logout") {
910
- if (target !== undefined && target !== "cloudflare") {
911
- ctx.ui.notify("当前仅支持 Cloudflare OAuth 退出:/search logout cloudflare", "warning");
1045
+ const resolved = resolveCommandOAuthTarget(runtime, target, instanceArg, true);
1046
+ if (!resolved.ok) {
1047
+ ctx.ui.notify("当前仅支持 Cloudflare OAuth 退出:/search logout cloudflare [实例]", "warning");
912
1048
  return;
913
1049
  }
914
- await runCloudflareLogout(ctx, { source: runtime, failureText });
1050
+ await runCloudflareLogout(ctx, { source: runtime, failureText }, resolved.instanceId);
915
1051
  return;
916
1052
  }
917
1053
  if (action === undefined) {
@@ -925,7 +1061,7 @@ export function createSearchCommand(runtime: SearchRuntime): {
925
1061
  }
926
1062
  if (action !== "status") {
927
1063
  ctx.ui.notify(
928
- "用法:/search 打开设置面板;/search status 查看状态;/search test [实例] 测试连接;/search login|logout cloudflare",
1064
+ "用法:/search 打开设置面板;/search status 查看状态;/search test [实例] 测试连接;/search login|logout cloudflare [实例];/search migrate cloudflare <实例>",
929
1065
  "warning",
930
1066
  );
931
1067
  return;