u1s1-cli 0.13.6 → 0.13.7

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.
@@ -21,7 +21,10 @@ export declare function cleanupBrandThemes(): void;
21
21
  * 环境变量,文件里不落密钥。U1S1_TOOLS_VIA_EXTENSION 守卫:旧版 CLI 仍在
22
22
  * 进程内注册工具且不设该变量,残留的本文件在旧版下自动空转,避免双重注册。
23
23
  */
24
- export declare function writeWebToolsExtension(cfg: CliConfig, webSearchEnabled: boolean): void;
24
+ export declare function writeWebToolsExtension(cfg: CliConfig, features: {
25
+ webSearch: boolean;
26
+ webFetchRender: boolean;
27
+ }): void;
25
28
  /**
26
29
  * pi-web-ui 的就绪检测只认 <agentDir>/auth.json 里有没有凭据条目(models.json
27
30
  * 的 apiKey 它不看),空 {} 会在网页里弹「未检测到 pi agent 配置」引导装 pi。
@@ -123,11 +123,11 @@ export function cleanupBrandThemes() {
123
123
  * 环境变量,文件里不落密钥。U1S1_TOOLS_VIA_EXTENSION 守卫:旧版 CLI 仍在
124
124
  * 进程内注册工具且不设该变量,残留的本文件在旧版下自动空转,避免双重注册。
125
125
  */
126
- export function writeWebToolsExtension(cfg, webSearchEnabled) {
126
+ export function writeWebToolsExtension(cfg, features) {
127
127
  const dir = join(agentDir, "extensions");
128
128
  mkdirSync(dir, { recursive: true });
129
129
  const toolsUrl = new URL("./tools.js", import.meta.url).href;
130
- const searchLine = webSearchEnabled
130
+ const searchLine = features.webSearch
131
131
  ? ` pi.registerTool(tools.createSearchTool({ baseUrl: ${JSON.stringify(cfg.baseUrl)}, apiKey: process.env.U1S1_API_KEY }));\n`
132
132
  : "";
133
133
  writeFileSync(join(dir, "u1s1-tools.js"), `// 由 u1s1 每次启动自动生成,请勿手改\n` +
@@ -135,7 +135,7 @@ export function writeWebToolsExtension(cfg, webSearchEnabled) {
135
135
  ` if (process.env.U1S1_TOOLS_VIA_EXTENSION !== "1") return;\n` +
136
136
  ` const tools = await import(${JSON.stringify(toolsUrl)});\n` +
137
137
  searchLine +
138
- ` pi.registerTool(tools.webFetchTool);\n` +
138
+ ` pi.registerTool(tools.createFetchTool({ baseUrl: ${JSON.stringify(cfg.baseUrl)}, apiKey: process.env.U1S1_API_KEY, renderFallback: ${features.webFetchRender} }));\n` +
139
139
  `}\n`);
140
140
  }
141
141
  /**
package/dist/api.d.ts CHANGED
@@ -46,6 +46,8 @@ export interface ApiModel {
46
46
  /** 服务端能力开关;字段缺失(老网关)时按开启处理,保持现状。 */
47
47
  export interface ApiFeatures {
48
48
  web_search?: boolean;
49
+ /** 网关配了 Browser Rendering 才为 true;老网关没有 /v1/fetch,缺失按关闭处理。 */
50
+ web_fetch_render?: boolean;
49
51
  }
50
52
  export interface ModelsResponse {
51
53
  models: ApiModel[];
@@ -88,4 +90,9 @@ export interface SearchResponse {
88
90
  }
89
91
  /** 联网搜索走网关代理(上游 key 只在服务端)。maxResults 不传时由服务端决定默认值。 */
90
92
  export declare function searchWeb(cfg: Pick<CliConfig, "baseUrl" | "apiKey">, query: string, maxResults?: number, signal?: AbortSignal): Promise<SearchResponse>;
93
+ /** web_fetch 直连失败时的回退:网关用 Cloudflare Browser Rendering 渲染后转 markdown。 */
94
+ export declare function renderPage(cfg: Pick<CliConfig, "baseUrl" | "apiKey">, url: string, signal?: AbortSignal): Promise<{
95
+ url: string;
96
+ markdown: string;
97
+ }>;
91
98
  export declare function fetchMe(cfg: CliConfig): Promise<MeResponse>;
package/dist/api.js CHANGED
@@ -80,6 +80,33 @@ export async function searchWeb(cfg, query, maxResults, signal) {
80
80
  }
81
81
  return (await resp.json());
82
82
  }
83
+ /** web_fetch 直连失败时的回退:网关用 Cloudflare Browser Rendering 渲染后转 markdown。 */
84
+ export async function renderPage(cfg, url, signal) {
85
+ if (!cfg.apiKey)
86
+ throw new Error("没有配置 API Key");
87
+ let resp;
88
+ try {
89
+ resp = await fetch(`${cfg.baseUrl}/fetch`, {
90
+ method: "POST",
91
+ headers: {
92
+ ...authHeaders(cfg.apiKey),
93
+ "content-type": "application/json",
94
+ },
95
+ body: JSON.stringify({ url }),
96
+ signal,
97
+ });
98
+ }
99
+ catch {
100
+ throw new Error(`连不上 ${cfg.baseUrl}`);
101
+ }
102
+ if (resp.status === 401)
103
+ throw new Error("这把 Key 不对或已失效,去 https://u1s1.io/dashboard 看看");
104
+ if (!resp.ok) {
105
+ const body = (await resp.json().catch(() => null));
106
+ throw new Error(body?.error?.message ?? `渲染服务返回 ${resp.status}`);
107
+ }
108
+ return (await resp.json());
109
+ }
83
110
  export async function fetchMe(cfg) {
84
111
  if (!cfg.apiKey)
85
112
  throw new Error("没有配置 API Key");
package/dist/index.js CHANGED
@@ -145,11 +145,14 @@ async function runAgent(cfg, args) {
145
145
  // 服务端没开搜索(或老网关没有 features 字段)时不注册 web_search,模型就不会白调
146
146
  // 自定义端点与模型列表并行拉取,失败各自兜底(内置列表 / 本地缓存)
147
147
  let webSearchEnabled = true;
148
+ // 老网关没有 /v1/fetch,web_fetch_render 缺失时按关闭处理,直连失败不去白调
149
+ let webFetchRenderEnabled = false;
148
150
  const endpointsReady = loadCustomEndpoints(cfg);
149
151
  try {
150
152
  const { models, features } = await fetchModels(cfg);
151
153
  setModelsFromApi(models.map(apiModelToDef));
152
154
  webSearchEnabled = features.web_search !== false;
155
+ webFetchRenderEnabled = features.web_fetch_render === true;
153
156
  }
154
157
  catch (e) {
155
158
  console.error(" 获取模型列表失败,使用内置列表:", e.message);
@@ -158,7 +161,7 @@ async function runAgent(cfg, args) {
158
161
  ensureBrandPrompt(await shellReady);
159
162
  ensureProviderModels(cfg);
160
163
  // 联网工具经 agentDir/extensions 投影,TUI 和 u1s1 web 共用一份注册
161
- writeWebToolsExtension(cfg, webSearchEnabled);
164
+ writeWebToolsExtension(cfg, { webSearch: webSearchEnabled, webFetchRender: webFetchRenderEnabled });
162
165
  ensureTmuxKeyboardProtocol();
163
166
  // must be set before pi reads them (getAgentDir() reads at call time, env at import is fine too)
164
167
  process.env["PI_CODING_AGENT_DIR"] = agentDir;
package/dist/tools.d.ts CHANGED
@@ -8,11 +8,21 @@ export declare function createSearchTool(cfg: Pick<CliConfig, "baseUrl" | "apiKe
8
8
  query: string;
9
9
  count: number;
10
10
  }, any> & import("@earendil-works/pi-coding-agent").ToolDefinition<any, any, any>;
11
- /** 抓网页:纯客户端出网,不经过我们的服务器,也不额外计费。 */
12
- export declare const webFetchTool: import("@earendil-works/pi-coding-agent").ToolDefinition<Type.TObject<{
11
+ export interface FetchToolConfig {
12
+ baseUrl: string;
13
+ apiKey?: string;
14
+ /** 网关配了 Browser Rendering(features.web_fetch_render)才开;老网关没有 /v1/fetch。 */
15
+ renderFallback?: boolean;
16
+ }
17
+ /**
18
+ * 抓网页工具:先直连(免费、快),打不开或疑似被反爬/JS 空壳时,回退到
19
+ * 网关的 Cloudflare Browser Rendering 渲染(真无头浏览器,按次计费)。
20
+ */
21
+ export declare function createFetchTool(cfg: FetchToolConfig): import("@earendil-works/pi-coding-agent").ToolDefinition<Type.TObject<{
13
22
  url: Type.TString;
14
23
  }>, {
15
24
  url: string;
16
25
  contentType: string;
26
+ via: "direct" | "render";
17
27
  chars: number;
18
28
  }, any> & import("@earendil-works/pi-coding-agent").ToolDefinition<any, any, any>;
package/dist/tools.js CHANGED
@@ -1,9 +1,13 @@
1
1
  import { defineTool } from "@earendil-works/pi-coding-agent";
2
2
  import { Type } from "typebox";
3
- import { searchWeb } from "./api.js";
3
+ import { renderPage, searchWeb } from "./api.js";
4
4
  const FETCH_TIMEOUT_MS = 20_000;
5
5
  const MAX_FETCH_BYTES = 2_000_000;
6
6
  const MAX_TEXT_CHARS = 30_000;
7
+ /** 云端渲染是真开浏览器,比直连慢得多,给宽裕些。 */
8
+ const RENDER_TIMEOUT_MS = 45_000;
9
+ /** 200 但榨出的正文比这还短,多半是 JS 渲染的空壳页,值得上浏览器再试。 */
10
+ const MIN_HTML_TEXT_CHARS = 200;
7
11
  const HTML_ENTITIES = {
8
12
  "&nbsp;": " ",
9
13
  "&amp;": "&",
@@ -104,59 +108,113 @@ export function createSearchTool(cfg) {
104
108
  },
105
109
  });
106
110
  }
107
- /** 抓网页:纯客户端出网,不经过我们的服务器,也不额外计费。 */
108
- export const webFetchTool = defineTool({
109
- name: "web_fetch",
110
- label: "读取网页",
111
- description: "Fetch a URL and return its readable text content (HTML is stripped to text; JSON and plain text are returned as-is). Use it to read a page found via web_search, or any URL the user pasted.",
112
- promptSnippet: "抓取指定网址并转成可读文本",
113
- promptGuidelines: [
114
- "Use web_fetch to read a specific URL, and web_search when you still need to find the URL.",
115
- ],
116
- parameters: Type.Object({
117
- url: Type.String({ description: "Absolute http(s) URL to fetch." }),
118
- }),
119
- async execute(_toolCallId, params, signal) {
120
- let url;
121
- try {
122
- // 用户从聊天工具粘来的链接常带 "@https://…" 前缀,顺手剥掉
123
- url = new URL(params.url.trim().replace(/^@/, ""));
124
- }
125
- catch {
126
- throw new Error(`不是合法的网址: ${params.url}`);
127
- }
128
- if (url.protocol !== "http:" && url.protocol !== "https:") {
129
- throw new Error(`只支持 http/https,收到 ${url.protocol}`);
130
- }
131
- const timeout = AbortSignal.timeout(FETCH_TIMEOUT_MS);
111
+ /** 直连失败里值得换浏览器再试的一类:网络不通/超时,或典型的反爬状态码。 */
112
+ class DirectFetchError extends Error {
113
+ renderWorthy;
114
+ constructor(message, renderWorthy) {
115
+ super(message);
116
+ this.renderWorthy = renderWorthy;
117
+ }
118
+ }
119
+ /** 反爬/风控常用的状态码;404/500 这类真错误换浏览器也救不回来,不白花一次渲染。 */
120
+ const RENDER_WORTHY_STATUS = new Set([403, 405, 406, 429, 503]);
121
+ /** 直连抓取:纯客户端出网,不经过我们的服务器,也不额外计费。 */
122
+ async function fetchDirect(url, signal) {
123
+ const timeout = AbortSignal.timeout(FETCH_TIMEOUT_MS);
124
+ const abort = signal ? AbortSignal.any([signal, timeout]) : timeout;
125
+ let resp;
126
+ try {
127
+ resp = await fetch(url, {
128
+ redirect: "follow",
129
+ headers: {
130
+ accept: "text/html,application/xhtml+xml,application/json,text/plain;q=0.9,*/*;q=0.8",
131
+ "user-agent": "u1s1-cli",
132
+ },
133
+ signal: abort,
134
+ });
135
+ }
136
+ catch (e) {
137
+ // 用户主动打断不算失败,直接往外抛,不去碰云端渲染
138
+ if (signal?.aborted)
139
+ throw e;
140
+ throw new DirectFetchError(`打不开 ${url.href}: ${e.message}`, true);
141
+ }
142
+ if (!resp.ok) {
143
+ throw new DirectFetchError(`${url.href} 返回 ${resp.status} ${resp.statusText}`, RENDER_WORTHY_STATUS.has(resp.status));
144
+ }
145
+ const type = resp.headers.get("content-type") ?? "";
146
+ if (!/text\/|json|xml|javascript/i.test(type)) {
147
+ throw new DirectFetchError(`${url.href} 不是文本内容 (${type || "unknown"}),读不了`, false);
148
+ }
149
+ const raw = decodeBody(await readBodyCapped(resp, MAX_FETCH_BYTES), type);
150
+ const isHtml = /html|xml/i.test(type);
151
+ return { text: isHtml ? htmlToText(raw) : raw.trim(), contentType: type, isHtml };
152
+ }
153
+ /**
154
+ * 抓网页工具:先直连(免费、快),打不开或疑似被反爬/JS 空壳时,回退到
155
+ * 网关的 Cloudflare Browser Rendering 渲染(真无头浏览器,按次计费)。
156
+ */
157
+ export function createFetchTool(cfg) {
158
+ const canRender = () => !!(cfg.renderFallback && cfg.apiKey);
159
+ async function renderViaGateway(url, signal) {
160
+ const timeout = AbortSignal.timeout(RENDER_TIMEOUT_MS);
132
161
  const abort = signal ? AbortSignal.any([signal, timeout]) : timeout;
133
- let resp;
134
- try {
135
- resp = await fetch(url, {
136
- redirect: "follow",
137
- headers: {
138
- accept: "text/html,application/xhtml+xml,application/json,text/plain;q=0.9,*/*;q=0.8",
139
- "user-agent": "u1s1-cli",
140
- },
141
- signal: abort,
162
+ const { markdown } = await renderPage(cfg, url.href, abort);
163
+ return markdown.trim();
164
+ }
165
+ return defineTool({
166
+ name: "web_fetch",
167
+ label: "读取网页",
168
+ description: "Fetch a URL and return its readable text content (HTML is stripped to text; JSON and plain text are returned as-is). Use it to read a page found via web_search, or any URL the user pasted. If the direct fetch fails or the page needs JavaScript, it automatically retries through a cloud headless browser.",
169
+ promptSnippet: "抓取指定网址并转成可读文本",
170
+ promptGuidelines: [
171
+ "Use web_fetch to read a specific URL, and web_search when you still need to find the URL.",
172
+ ],
173
+ parameters: Type.Object({
174
+ url: Type.String({ description: "Absolute http(s) URL to fetch." }),
175
+ }),
176
+ async execute(_toolCallId, params, signal) {
177
+ let url;
178
+ try {
179
+ // 用户从聊天工具粘来的链接常带 "@https://…" 前缀,顺手剥掉
180
+ url = new URL(params.url.trim().replace(/^@/, ""));
181
+ }
182
+ catch {
183
+ throw new Error(`不是合法的网址: ${params.url}`);
184
+ }
185
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
186
+ throw new Error(`只支持 http/https,收到 ${url.protocol}`);
187
+ }
188
+ const ok = (text, via, contentType) => ({
189
+ content: [{ type: "text", text: truncate(`# ${url.href}\n\n${text || "(空白页面)"}`) }],
190
+ details: { url: url.href, contentType, via, chars: text.length },
142
191
  });
143
- }
144
- catch (e) {
145
- throw new Error(`打不开 ${url.href}: ${e.message}`);
146
- }
147
- if (!resp.ok)
148
- throw new Error(`${url.href} 返回 ${resp.status} ${resp.statusText}`);
149
- const type = resp.headers.get("content-type") ?? "";
150
- if (!/text\/|json|xml|javascript/i.test(type)) {
151
- throw new Error(`${url.href} 不是文本内容 (${type || "unknown"}),读不了`);
152
- }
153
- const raw = decodeBody(await readBodyCapped(resp, MAX_FETCH_BYTES), type);
154
- const text = /html|xml/i.test(type) ? htmlToText(raw) : raw.trim();
155
- return {
156
- content: [
157
- { type: "text", text: truncate(`# ${url.href}\n\n${text || "(空白页面)"}`) },
158
- ],
159
- details: { url: url.href, contentType: type, chars: text.length },
160
- };
161
- },
162
- });
192
+ let direct = null;
193
+ try {
194
+ direct = await fetchDirect(url, signal);
195
+ }
196
+ catch (e) {
197
+ if (!(e instanceof DirectFetchError) || !e.renderWorthy || !canRender())
198
+ throw e;
199
+ try {
200
+ return ok(await renderViaGateway(url, signal), "render", "text/markdown");
201
+ }
202
+ catch (re) {
203
+ throw new Error(`${e.message};云端浏览器渲染也失败: ${re.message}`);
204
+ }
205
+ }
206
+ // 直连 200 但正文近乎空:大概率是 JS 渲染的 SPA,换浏览器再试;渲染失败就退回空壳
207
+ if (direct.isHtml && direct.text.length < MIN_HTML_TEXT_CHARS && canRender()) {
208
+ try {
209
+ const rendered = await renderViaGateway(url, signal);
210
+ if (rendered.length > direct.text.length)
211
+ return ok(rendered, "render", "text/markdown");
212
+ }
213
+ catch {
214
+ // 直连结果虽薄但还在,渲染挂了不至于让整次调用失败
215
+ }
216
+ }
217
+ return ok(direct.text, "direct", direct.contentType);
218
+ },
219
+ });
220
+ }
package/dist/web.js CHANGED
@@ -30,11 +30,14 @@ export async function prepareWebEnv(cfg) {
30
30
  // 服务端没开搜索(或老网关没有 features 字段)时不注册 web_search
31
31
  // 自定义端点与模型列表并行拉取,失败各自兜底(内置列表 / 本地缓存)
32
32
  let webSearchEnabled = true;
33
+ // 老网关没有 /v1/fetch,web_fetch_render 缺失时按关闭处理,直连失败不去白调
34
+ let webFetchRenderEnabled = false;
33
35
  const endpointsReady = loadCustomEndpoints(cfg);
34
36
  try {
35
37
  const { models, features } = await fetchModels(cfg);
36
38
  setModelsFromApi(models.map(apiModelToDef));
37
39
  webSearchEnabled = features.web_search !== false;
40
+ webFetchRenderEnabled = features.web_fetch_render === true;
38
41
  }
39
42
  catch (e) {
40
43
  console.error(" 获取模型列表失败,使用内置列表:", e.message);
@@ -45,7 +48,7 @@ export async function prepareWebEnv(cfg) {
45
48
  // pi-web-ui 靠 auth.json 判断「已配置」,否则网页会弹 pi 安装引导
46
49
  ensureAuthCredential();
47
50
  // 联网工具经 agentDir/extensions 投影,和 TUI 共用一份注册
48
- writeWebToolsExtension(cfg, webSearchEnabled);
51
+ writeWebToolsExtension(cfg, { webSearch: webSearchEnabled, webFetchRender: webFetchRenderEnabled });
49
52
  // 网页版新会话从 settings.json 的 defaultModel 取模型(TUI 是每次传 --model),
50
53
  // 确保它有值;resolvePreferredModel 优先尊重已有的 in-session 选择,不会回退覆盖。
51
54
  const pref = resolvePreferredModel(cfg);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "u1s1-cli",
3
- "version": "0.13.6",
3
+ "version": "0.13.7",
4
4
  "description": "u1s1 — 有一说一,最省心的 AI 编程搭子。终端里用中文说需求,AI 帮你读文件、改代码、跑命令。",
5
5
  "type": "module",
6
6
  "bin": {