u1s1-cli 0.13.7 → 0.14.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.
@@ -24,6 +24,7 @@ export declare function cleanupBrandThemes(): void;
24
24
  export declare function writeWebToolsExtension(cfg: CliConfig, features: {
25
25
  webSearch: boolean;
26
26
  webFetchRender: boolean;
27
+ imageGen: boolean;
27
28
  }): void;
28
29
  /**
29
30
  * pi-web-ui 的就绪检测只认 <agentDir>/auth.json 里有没有凭据条目(models.json
@@ -130,12 +130,16 @@ export function writeWebToolsExtension(cfg, features) {
130
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
+ const imageLine = features.imageGen
134
+ ? ` pi.registerTool(tools.createImageTool({ baseUrl: ${JSON.stringify(cfg.baseUrl)}, apiKey: process.env.U1S1_API_KEY }));\n`
135
+ : "";
133
136
  writeFileSync(join(dir, "u1s1-tools.js"), `// 由 u1s1 每次启动自动生成,请勿手改\n` +
134
137
  `export default async function (pi) {\n` +
135
138
  ` if (process.env.U1S1_TOOLS_VIA_EXTENSION !== "1") return;\n` +
136
139
  ` const tools = await import(${JSON.stringify(toolsUrl)});\n` +
137
140
  searchLine +
138
141
  ` pi.registerTool(tools.createFetchTool({ baseUrl: ${JSON.stringify(cfg.baseUrl)}, apiKey: process.env.U1S1_API_KEY, renderFallback: ${features.webFetchRender} }));\n` +
142
+ imageLine +
139
143
  `}\n`);
140
144
  }
141
145
  /**
package/dist/api.d.ts CHANGED
@@ -48,6 +48,8 @@ export interface ApiFeatures {
48
48
  web_search?: boolean;
49
49
  /** 网关配了 Browser Rendering 才为 true;老网关没有 /v1/fetch,缺失按关闭处理。 */
50
50
  web_fetch_render?: boolean;
51
+ /** 网关配了方舟 ARK_API_KEY 才为 true;老网关没有 /v1/image,缺失按关闭处理。 */
52
+ image_gen?: boolean;
51
53
  }
52
54
  export interface ModelsResponse {
53
55
  models: ApiModel[];
@@ -95,4 +97,16 @@ export declare function renderPage(cfg: Pick<CliConfig, "baseUrl" | "apiKey">, u
95
97
  url: string;
96
98
  markdown: string;
97
99
  }>;
100
+ export interface ImageGenRequest {
101
+ prompt: string;
102
+ /** 参考图:http(s) URL 或 data:image/... base64,最多 10 张。 */
103
+ images?: string[];
104
+ /** 1K/2K/4K 或 宽x高(如 2048x2048);缺省由服务端定(2K)。 */
105
+ size?: string;
106
+ }
107
+ /** 生图走网关代理(方舟 key 只在服务端);返回 TOS 图片 URL(24h 有效),调用方应立即下载。 */
108
+ export declare function generateImage(cfg: Pick<CliConfig, "baseUrl" | "apiKey">, req: ImageGenRequest, signal?: AbortSignal): Promise<{
109
+ url: string;
110
+ size: string | null;
111
+ }>;
98
112
  export declare function fetchMe(cfg: CliConfig): Promise<MeResponse>;
package/dist/api.js CHANGED
@@ -107,6 +107,35 @@ export async function renderPage(cfg, url, signal) {
107
107
  }
108
108
  return (await resp.json());
109
109
  }
110
+ /** 生图走网关代理(方舟 key 只在服务端);返回 TOS 图片 URL(24h 有效),调用方应立即下载。 */
111
+ export async function generateImage(cfg, req, signal) {
112
+ if (!cfg.apiKey)
113
+ throw new Error("没有配置 API Key");
114
+ let resp;
115
+ try {
116
+ resp = await fetch(`${cfg.baseUrl}/image`, {
117
+ method: "POST",
118
+ headers: {
119
+ ...authHeaders(cfg.apiKey),
120
+ "content-type": "application/json",
121
+ },
122
+ body: JSON.stringify(req),
123
+ signal,
124
+ });
125
+ }
126
+ catch (e) {
127
+ if (signal?.aborted)
128
+ throw e;
129
+ throw new Error(`连不上 ${cfg.baseUrl},检查一下网络?`);
130
+ }
131
+ if (resp.status === 401)
132
+ throw new Error("这把 Key 不对或已失效,去 https://u1s1.io/dashboard 看看");
133
+ if (!resp.ok) {
134
+ const body = (await resp.json().catch(() => null));
135
+ throw new Error(body?.error?.message ?? `图片生成服务返回 ${resp.status},稍后再试`);
136
+ }
137
+ return (await resp.json());
138
+ }
110
139
  export async function fetchMe(cfg) {
111
140
  if (!cfg.apiKey)
112
141
  throw new Error("没有配置 API Key");
package/dist/index.js CHANGED
@@ -147,12 +147,15 @@ async function runAgent(cfg, args) {
147
147
  let webSearchEnabled = true;
148
148
  // 老网关没有 /v1/fetch,web_fetch_render 缺失时按关闭处理,直连失败不去白调
149
149
  let webFetchRenderEnabled = false;
150
+ // 老网关没有 /v1/image,image_gen 缺失时按关闭处理,不注册生图工具
151
+ let imageGenEnabled = false;
150
152
  const endpointsReady = loadCustomEndpoints(cfg);
151
153
  try {
152
154
  const { models, features } = await fetchModels(cfg);
153
155
  setModelsFromApi(models.map(apiModelToDef));
154
156
  webSearchEnabled = features.web_search !== false;
155
157
  webFetchRenderEnabled = features.web_fetch_render === true;
158
+ imageGenEnabled = features.image_gen === true;
156
159
  }
157
160
  catch (e) {
158
161
  console.error(" 获取模型列表失败,使用内置列表:", e.message);
@@ -161,7 +164,11 @@ async function runAgent(cfg, args) {
161
164
  ensureBrandPrompt(await shellReady);
162
165
  ensureProviderModels(cfg);
163
166
  // 联网工具经 agentDir/extensions 投影,TUI 和 u1s1 web 共用一份注册
164
- writeWebToolsExtension(cfg, { webSearch: webSearchEnabled, webFetchRender: webFetchRenderEnabled });
167
+ writeWebToolsExtension(cfg, {
168
+ webSearch: webSearchEnabled,
169
+ webFetchRender: webFetchRenderEnabled,
170
+ imageGen: imageGenEnabled,
171
+ });
165
172
  ensureTmuxKeyboardProtocol();
166
173
  // must be set before pi reads them (getAgentDir() reads at call time, env at import is fine too)
167
174
  process.env["PI_CODING_AGENT_DIR"] = agentDir;
package/dist/tools.d.ts CHANGED
@@ -8,6 +8,17 @@ 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
+ /** 生图工具:走 u1s1 网关代理火山方舟 Seedream,上游 key 不落到用户机器上。 */
12
+ export declare function createImageTool(cfg: Pick<CliConfig, "baseUrl" | "apiKey">): import("@earendil-works/pi-coding-agent").ToolDefinition<Type.TObject<{
13
+ prompt: Type.TString;
14
+ images: Type.TOptional<Type.TArray<Type.TString>>;
15
+ size: Type.TOptional<Type.TString>;
16
+ save_path: Type.TOptional<Type.TString>;
17
+ }>, {
18
+ path: string;
19
+ size: string | null;
20
+ bytes: number;
21
+ }, any> & import("@earendil-works/pi-coding-agent").ToolDefinition<any, any, any>;
11
22
  export interface FetchToolConfig {
12
23
  baseUrl: string;
13
24
  apiKey?: string;
package/dist/tools.js CHANGED
@@ -1,6 +1,8 @@
1
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
+ import { dirname, extname, resolve } from "node:path";
1
3
  import { defineTool } from "@earendil-works/pi-coding-agent";
2
4
  import { Type } from "typebox";
3
- import { renderPage, searchWeb } from "./api.js";
5
+ import { generateImage, renderPage, searchWeb } from "./api.js";
4
6
  const FETCH_TIMEOUT_MS = 20_000;
5
7
  const MAX_FETCH_BYTES = 2_000_000;
6
8
  const MAX_TEXT_CHARS = 30_000;
@@ -108,6 +110,105 @@ export function createSearchTool(cfg) {
108
110
  },
109
111
  });
110
112
  }
113
+ /** 生图链路 = 网关排队 + 方舟生成(2K 实测 ~10s,4K 更久)+ 下载落盘。 */
114
+ const IMAGE_TIMEOUT_MS = 150_000;
115
+ /** 方舟单张参考图原图上限 10MB。 */
116
+ const MAX_REF_IMAGE_BYTES = 10 * 1024 * 1024;
117
+ const REF_IMAGE_MIME = {
118
+ ".png": "image/png",
119
+ ".jpg": "image/jpeg",
120
+ ".jpeg": "image/jpeg",
121
+ ".webp": "image/webp",
122
+ ".bmp": "image/bmp",
123
+ ".gif": "image/gif",
124
+ };
125
+ /** 本地图片路径 → data URL;http(s) URL 原样透传给网关。 */
126
+ function refImageToPayload(ref) {
127
+ const s = ref.trim();
128
+ if (/^https?:\/\//.test(s))
129
+ return s;
130
+ const path = resolve(s);
131
+ if (!existsSync(path))
132
+ throw new Error(`参考图不存在: ${s}`);
133
+ const mime = REF_IMAGE_MIME[extname(path).toLowerCase()];
134
+ if (!mime)
135
+ throw new Error(`参考图格式不支持: ${s}(支持 png/jpg/jpeg/webp/bmp/gif)`);
136
+ if (statSync(path).size > MAX_REF_IMAGE_BYTES)
137
+ throw new Error(`参考图超过 10MB: ${s}`);
138
+ return `data:${mime};base64,${readFileSync(path).toString("base64")}`;
139
+ }
140
+ /** 结果落盘路径:模型没指定时按时间戳起名,已存在就加序号,不覆盖旧图。 */
141
+ function resolveSavePath(savePath, urlExt) {
142
+ if (savePath?.trim())
143
+ return resolve(savePath.trim());
144
+ const stamp = new Date()
145
+ .toISOString()
146
+ .replace(/[-:]/g, "")
147
+ .replace(/T(\d{6}).*/, "-$1");
148
+ const base = resolve(`image-${stamp}`);
149
+ let path = `${base}${urlExt}`;
150
+ for (let i = 1; existsSync(path); i++)
151
+ path = `${base}-${i}${urlExt}`;
152
+ return path;
153
+ }
154
+ /** 生图工具:走 u1s1 网关代理火山方舟 Seedream,上游 key 不落到用户机器上。 */
155
+ export function createImageTool(cfg) {
156
+ return defineTool({
157
+ name: "generate_image",
158
+ label: "生成图片",
159
+ description: "Generate an image from a text prompt, or edit/compose existing images, using the Seedream image model. " +
160
+ "Saves the result as a local image file and returns its path. " +
161
+ "Pass local file paths or http(s) URLs in `images` to edit an image or use references (style transfer, adding elements, combining up to 10 images). " +
162
+ "Prompts work in Chinese or English; describe content, style, composition, and any text to render.",
163
+ promptSnippet: "AI 生成/修改图片(文生图、改图、多图合成)",
164
+ promptGuidelines: [
165
+ "Use generate_image when the user wants a picture created or an existing image modified (logo, illustration, poster, placeholder art, 改图/换风格).",
166
+ "Each call generates one image and costs the user credits; refine the prompt first instead of regenerating repeatedly.",
167
+ "To edit an existing image, pass its path in `images` and describe only the change in `prompt`.",
168
+ ],
169
+ parameters: Type.Object({
170
+ prompt: Type.String({
171
+ description: "What to generate or how to edit the reference images. Be specific about subject, style, composition, colors, and any text to appear in the image.",
172
+ }),
173
+ images: Type.Optional(Type.Array(Type.String(), {
174
+ description: "Reference images to edit or draw from: local file paths or http(s) URLs, up to 10. Omit for pure text-to-image.",
175
+ })),
176
+ size: Type.Optional(Type.String({
177
+ description: 'Output resolution: "2K" (default, aspect ratio auto-adapts to the prompt), "4K", or explicit "WIDTHxHEIGHT" like "2048x2048" / "1664x2496".',
178
+ })),
179
+ save_path: Type.Optional(Type.String({
180
+ description: "Where to save the image (relative to cwd). Defaults to image-<timestamp>.<ext> in the current directory.",
181
+ })),
182
+ }),
183
+ async execute(_toolCallId, params, signal) {
184
+ const timeout = AbortSignal.timeout(IMAGE_TIMEOUT_MS);
185
+ const abort = signal ? AbortSignal.any([signal, timeout]) : timeout;
186
+ const images = (params.images ?? []).map(refImageToPayload);
187
+ const result = await generateImage(cfg, { prompt: params.prompt, images: images.length ? images : undefined, size: params.size }, abort);
188
+ let resp;
189
+ try {
190
+ resp = await fetch(result.url, { signal: abort });
191
+ }
192
+ catch (e) {
193
+ if (signal?.aborted)
194
+ throw e;
195
+ throw new Error(`图片生成成功但下载失败: ${e.message}`);
196
+ }
197
+ if (!resp.ok)
198
+ throw new Error(`图片生成成功但下载失败: HTTP ${resp.status}`);
199
+ const bytes = new Uint8Array(await resp.arrayBuffer());
200
+ const urlExt = extname(new URL(result.url).pathname).toLowerCase() || ".jpeg";
201
+ const path = resolveSavePath(params.save_path, urlExt);
202
+ mkdirSync(dirname(path), { recursive: true });
203
+ writeFileSync(path, bytes);
204
+ const sizeNote = result.size ? ` (${result.size})` : "";
205
+ return {
206
+ content: [{ type: "text", text: `图片已保存: ${path}${sizeNote}` }],
207
+ details: { path, size: result.size, bytes: bytes.byteLength },
208
+ };
209
+ },
210
+ });
211
+ }
111
212
  /** 直连失败里值得换浏览器再试的一类:网络不通/超时,或典型的反爬状态码。 */
112
213
  class DirectFetchError extends Error {
113
214
  renderWorthy;
package/dist/web.js CHANGED
@@ -32,12 +32,15 @@ export async function prepareWebEnv(cfg) {
32
32
  let webSearchEnabled = true;
33
33
  // 老网关没有 /v1/fetch,web_fetch_render 缺失时按关闭处理,直连失败不去白调
34
34
  let webFetchRenderEnabled = false;
35
+ // 老网关没有 /v1/image,image_gen 缺失时按关闭处理,不注册生图工具
36
+ let imageGenEnabled = false;
35
37
  const endpointsReady = loadCustomEndpoints(cfg);
36
38
  try {
37
39
  const { models, features } = await fetchModels(cfg);
38
40
  setModelsFromApi(models.map(apiModelToDef));
39
41
  webSearchEnabled = features.web_search !== false;
40
42
  webFetchRenderEnabled = features.web_fetch_render === true;
43
+ imageGenEnabled = features.image_gen === true;
41
44
  }
42
45
  catch (e) {
43
46
  console.error(" 获取模型列表失败,使用内置列表:", e.message);
@@ -48,7 +51,11 @@ export async function prepareWebEnv(cfg) {
48
51
  // pi-web-ui 靠 auth.json 判断「已配置」,否则网页会弹 pi 安装引导
49
52
  ensureAuthCredential();
50
53
  // 联网工具经 agentDir/extensions 投影,和 TUI 共用一份注册
51
- writeWebToolsExtension(cfg, { webSearch: webSearchEnabled, webFetchRender: webFetchRenderEnabled });
54
+ writeWebToolsExtension(cfg, {
55
+ webSearch: webSearchEnabled,
56
+ webFetchRender: webFetchRenderEnabled,
57
+ imageGen: imageGenEnabled,
58
+ });
52
59
  // 网页版新会话从 settings.json 的 defaultModel 取模型(TUI 是每次传 --model),
53
60
  // 确保它有值;resolvePreferredModel 优先尊重已有的 in-session 选择,不会回退覆盖。
54
61
  const pref = resolvePreferredModel(cfg);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "u1s1-cli",
3
- "version": "0.13.7",
3
+ "version": "0.14.0",
4
4
  "description": "u1s1 — 有一说一,最省心的 AI 编程搭子。终端里用中文说需求,AI 帮你读文件、改代码、跑命令。",
5
5
  "type": "module",
6
6
  "bin": {