# oil-icon

Adopt this skill: https://proskills.md/skills/other/oil-oil-oil-icon

Page: https://proskills.md/skills/other/oil-oil-oil-icon
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: SKILL.md
size: 6601
sha: 302ba97001dc6685f6541aa0c76f18be4caae119
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/SKILL.md

```text
---
name: oil-icon
description: "生成风格统一的图标集合，通过宫格生图、切分和去背景交付透明 PNG。用户需要成套自定义图标、栏目图标或匹配品牌风格的图标时使用；不用于单个简单矢量图标或小尺寸密集功能符号。"
---

# oil-icon

Generate a **set** of icons that share one visual style, output as transparent PNGs.

Image generation runs on a flat grey backdrop as a 4×4 sheet — 16 icons in one generation, 有助于统一风格，但仍需逐个检查 — then each cell is sliced out and background-removed.

Agent owns the design decisions (which style, which palette, which metaphors, whether to match a brand); image generation and slicing are mechanical steps.

## API Key 配置入口

需要外部服务凭据时先读[API Key 配置与业务读取](references/api-key-setup.md)：复用已有安全入口；本机缺少 Key 时使用随附固定页面，保存后通过业务包装入口读取。内置能力与纯本地流程不要求配置 Key。

## Workflow

1. **Choose the style.** Either pick a built-in from `styles/` (table below), or **match the user's brand** by reading their project's design tokens / assets and deriving a custom style-spec — see `reference/style-adaptation.md`. Freeze the result as a style-spec with the same fields as the built-in JSONs; 后续批次复用同一规范，并检查生成偏差.
2. **List the icons.** Write each concept as `name — short concrete metaphor` (e.g. `settlement — a wallet with a coin`). One clear idea per icon; keep the detail level consistent across the set. 默认每张 **16** 格；明确选择 **9** 格时，提示词使用 3×3，切图命令必须同时传 `--grid 3`。 If the user asks for an exact count below 16, still use a **4x4 / 16-cell sheet**: place the requested icons first in row-major order, then explicitly ask the remaining cells to stay empty grey background.
3. **Compose the prompt.** `style.preamble` + the style's `construction` fields (as short guidance) + palette-lock line + numbered metaphors + the fixed composition text — see `reference/prompt-template.md` and `reference/construction.md`.
4. **Generate the sheet(s).** Choose an image provider by capability, in order (see `reference/image-providers.md`) — never assume Codex is present:
   1. **Built-in / host imagegen first** — if the running agent already has a callable image-generation tool, including Codex's built-in `image_gen` tool or the `imagegen` skill, call it directly. Do not delegate to external Codex CLI just to reach imagegen from another process.
   2. **Codex CLI fallback** — only if this agent has no callable image-generation tool, and Codex is available （从可用 Skill 清单定位 codex，或使用 PATH 中已有的 codex）, delegate generation to it.
   3. **External API fallback** — only if neither of the above exists, 沿用用户已授权的供应商；缺少凭据时按配置说明打开随附页面，不索要聊天中的 Key; for OpenAI Images, `scripts/gen_image.py --prompt "…" --out raw/<style>.png` is ready.
   Save or copy each generated sheet to `raw/<style>.png` on flat grey `#808080`. Built-in imagegen may save under `$CODEX_HOME/generated_images/...`; after generation, move or copy the selected PNG into the task output `raw/` folder. 同一张图更容易保持共同风格，但仍须逐个验收，不能把一次生成视为一致性保证； a provider only has to turn the prompt into a grey-background PNG.
5. **Slice.** Run `scripts/setup.sh` once, then:
   `.venv/bin/python3 scripts/slice_icons.py <raw>.png <outdir> --mode <cutout> [--thresh N] [--grid 4] [--count N]`
   using the style's `cutout` mode (`floodfill` for flat/hard-edge, `rembg` for soft / 3D / glossy / photo).
6. **QA (mandatory).** Composite the sliced PNGs onto a contrasting colour (e.g. magenta) and check every icon for (a) a fragment bled in from a neighbouring cell, (b) leftover grey, and (c) consistency against the style's `construction` — uniform stroke, one radius, matched detail level, shared parts, motif present, single perspective, and no accent out-weighting the defining element (in line styles the accent must be lighter and smaller than the stroke). Re-slice or regenerate any that fail — never ship an icon carrying part of the one above it.
7. **Deliver** the transparent PNGs, organized and named.

## Built-in styles

| style | look | cutout | fits |
|---|---|---|---|
| linear | mono line / outline | floodfill | utility, settings |
| filled | solid single-colour glyphs | floodfill | mobile nav / tab bars |
| colorblock | bold flat multi-colour blocks | floodfill | kids, creative |
| cartoon | sticker-style cartoon | rembg | games, entertainment |
| isometric | isometric 3D miniatures | rembg | SaaS, dashboards |
| render3d | glossy puffy 3D | rembg | rewards, onboarding |
| sticker | die-cut glossy vinyl | rembg | social, reactions |
| realistic | photoreal product renders | rembg | e-commerce, hero |
| animal-badge | animal emblems in badges | rembg | avatars, kids |

Each `styles/<name>.json` holds the preamble, locked palette, cutout mode, threshold, construction system, and what it fits.

## Key rules (see `reference/design-rules.md`)

- **Lock the palette as hex** in the spec — colourful styles drift run-to-run otherwise.
- **Never make black filled icons** — near-black / black may be used as a thin outline or line stroke, but never as the dominant filled mass of an icon set. If the brand foreground is black, map it to strokes only; for filled or duotone styles, choose a mid-light brand colour for the main shape and keep dark colours small.
- **Start from the real product context** — when a user gives a live site, screenshot, mascot, logo, or brand asset, derive the icon concepts and construction from that source first. Do not jump straight into generic style families such as isometric, duotone, 3D, or colorblock; those are finishes applied after the product motif, real navigation, and real feature names are locked.
- **Slicing drops neighbour bleed** — the slicer keeps only the centred icon per cell.
- **Cutout by edge type** — flat/hard-edge → floodfill; soft / 3D / glossy / photo → rembg.
- **Design sophistication comes from a construction system + a brand motif**, not from tinting a generic set — each style's `construction` object encodes the grid, stroke, radius, detail budget, shared parts, and motif (see `reference/construction.md`). A rigorous system ultimately wants vector; raster is for direction and spot icons.
```

## File: README.md
size: 6942
sha: d05eb9a0d162473bd7d9220f5d26f5f40c10f34e
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/README.md

````text
<p align="center">
  <img src="./assets/readme/readme-hero.png" width="100%" alt="oil-icon：一次生成一整套，让每个图标都像来自同一个设计师。">
</p>

<p align="center">
  <img src="./assets/readme/readme-section-what.svg" width="100%" alt="02 oil-icon 是什么">
</p>

生成风格一致的图标集合，完成宫格切分、背景去除和逐个检查，交付透明 PNG。

上面的两组图标使用了完全相同的 16 个概念：配色、网格、魔法棒、图层、品牌、标签、卡片、分类、空状态、营销、产品、角色、切图、透明背景、质检和导出。改变的是整套的画法，因此一组是柔软 3D，另一组是等轴微缩。

它适合产品功能、分类、营销卡片、空状态和品牌化插图；如果只是制作 16–24px 的按钮小图标，直接使用 Lucide 等矢量图标库会更合适。

<p align="center">
  <img src="./assets/readme/readme-section-consistency.svg" width="100%" alt="03 为什么整套生成更统一">
</p>

让模型一张一张画，后面的图标很容易忘记前面的线宽、圆角、视角和颜色。`oil-icon` 把 16 个图标放在同一次生成里，让模型始终看见整套作品；开始画之前，还会先把共同的规则定清楚。

一套图标会共同遵守：

- **同一套画法**：网格、视角、线宽、圆角和繁简程度一致。
- **同一套颜色**：色值直接锁定，避免每一批越画越艳、越画越偏。
- **同一个记号**：反复出现的小火花、切角或其他母题，让图标拥有自己的身份。
- **同一次生成**：16 个图标共享同一段视觉上下文，比逐张生成更容易保持一致。

所以它不是给通用图标换一套颜色，而是先把整套的画法定清楚，再让模型按照这些规则画完。

<p align="center">
  <img src="./assets/readme/readme-section-workflow.svg" width="100%" alt="04 一张图，得到 16 张透明 PNG">
</p>

```text
图标清单 + 风格或项目素材
          ↓
定好颜色、视角、圆角和专属记号
          ↓
在纯灰背景生成一张 4×4 图标图
          ↓
自动切成 16 张图片并移除背景
          ↓
在高对比底色检查灰边、串格和一致性
          ↓
交付 16 张透明 PNG
```

硬边图标使用颜色识别清除背景，3D、贴纸等软边图标使用背景移除模型。切图程序只保留每个格子中心的主体，避免把旁边图标的碎片一起带走。

<p align="center">
  <img src="./assets/readme/readme-section-styles.svg" width="100%" alt="05 支持哪些风格">
</p>

仓库里现在有 9 种内置预设，每一种都有自己的色彩、构造规则和背景移除方式：

| 预设 | 视觉特点 | 更适合 |
| --- | --- | --- |
| `linear` · 线性 | 单色描边、统一线宽、圆角收笔 | 工具、设置和内容密集的界面 |
| `filled` · 面性单色 | 清楚的实心轮廓，只使用一种主色 | 导航、标签栏和小面积强调 |
| `colorblock` · 撞色 | 2～3 种颜色组成简洁的几何色块 | 创意、教育和轻松活泼的产品 |
| `cartoon` · 卡通 | 粗描边、圆润造型和贴纸感 | 游戏、娱乐和角色化内容 |
| `isometric` · 等轴微缩 | 统一视角的立体小物件，结构清楚 | 工作台、功能介绍和 SaaS 产品 |
| `render3d` · 3D 渲染 | 柔软膨胀的形状、糖果色和细腻材质 | 引导、奖励、会员和营销卡片 |
| `sticker` · 贴纸 | 清楚的外轮廓、亮面材质和独立贴纸造型 | 社区、聊天、表情和活动素材 |
| `realistic` · 真实实物 | 接近产品摄影的真实物体 | 电商、商品分类和首屏展示 |
| `animal-badge` · 动物徽标 | 动物角色与统一徽章结构结合 | 头像、儿童产品和角色系统 |

这 9 种只是随仓库提供的稳定起点，不是 `oil-icon` 能做的全部风格。我们还可以：

- **直接修改预设**：替换配色，调整线宽、圆角、视角、材质和细节多少。
- **匹配现有品牌**：读取网站、Logo、截图和设计变量，把真实的颜色与形状规则整理成一套图标风格。
- **从文字描述开始**：没有现成设计也没关系，可以先用一句话确定方向，再生成第一张风格样板。
- **保存专属规则**：风格确认后，把色板、构造方式和专属记号固定下来，之后继续生成的新图标也会沿用同一套规则。

内置预设解决的是快速开始，品牌适配解决的是让图标真正属于这个产品。

<p align="center">
  <img src="./assets/readme/readme-section-start.svg" width="100%" alt="06 怎么使用">
</p>

**方式一 · 执行命令**

```bash
npx skills add oil-oil/oil-icon
```

**方式二 · 直接交给 Agent**

把下面这句话发给任何支持 Skill 的 Agent：

```text
请安装这个 Skill：https://github.com/oil-oil/oil-icon
```

安装完成后，可以直接描述图标清单和使用场景：

```text
[$oil-icon] 根据这个产品的页面和配色，生成一套 16 个功能图标。
```

如果没有现成品牌，也可以指定一个方向：

```text
[$oil-icon] 为我的 AI 写作工具生成一套柔软 3D 图标，包含创作、改写、翻译、素材、历史和导出。
```

`oil-icon` 会优先使用 Agent 当前可用的图片生成能力；没有内置图片工具时，再根据环境选择其他生成方式。切图与检查流程保持一致。

<details>
<summary><strong>仓库里有什么</strong></summary>

- `SKILL.md`：完整工作流与执行规则
- `styles/`：内置风格和构造规范
- `reference/`：提示词、品牌适配、图标设计与生成说明
- `scripts/`：环境安装、切图和背景移除工具

</details>

<p align="center">
  <a href="https://github.com/oil-oil/beautify-github-readme"><img src="./assets/readme/made-with-beautify.svg" width="300" alt="README made with beautify-github-readme"></a>
</p>

## License

MIT

## 配置、依赖与使用边界

依赖已授权的生图工具；切图需 scripts/setup.sh 安装的 Python 图像依赖。软边缘风格按需使用 rembg。无需把 Key 发到聊天。

产物保存在任务目录。9 格使用 --grid 3，16 格使用 --grid 4；小尺寸功能图标优先矢量库。一次生成不保证一致性。

使用示例：

```text
用 oil-icon 为这六个功能画一组配套图标。
```

## API Key 配置页面

首次使用外部服务时，可以在本机配置页亲自填写 Key；已有配置会复用，密钥存入系统凭据库。只为实际使用的外部服务配置；纯本地处理不需要 Key。页面需要 Node.js 22.18+ 与可用的系统凭据服务，业务运行仍使用原依赖。

安装、状态检查、打开页面和带凭据运行的完整入口见[配置说明](references/api-key-setup.md)。页面保存与业务读取已经接通；不把 Key 发进聊天，也不自动迁移旧文件。
````

## File: scripts/credential-ui/README.md
size: 8173
sha: f257604bf4630d9e5a9328e9bb2b78e7bd26d42a
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/README.md

````text
# 可复用凭据输入页

供本机桌面 Skill 配置 API Key、访问令牌等单行凭据。一个 Key 使用紧凑单输入框，多个 Key 在同页纵向排列，共用一个保存按钮。页面默认黑白灰，密钥只存系统凭据库。

## 适用范围

适合没有现成安全配置入口、需要用户首次填写或更换 API Key、访问令牌、Client Secret 的本机桌面 Skill。已有宿主凭据能力优先复用。

| 其他场景 | 使用方式 |
| --- | --- |
| OAuth、验证码或账号登录 | 服务官方授权流程 |
| 模型名、地址、目录等普通设置 | 普通配置文件或设置页 |
| 私钥文件、证书、多行密钥 | 专用凭据或文件授权机制 |
| CI、容器、远程服务器 | 已有 Secret 管理与可信运行时注入，不暴露本机输入页到网络 |

本组件减少密钥进入 Agent 对话和工具输出的机会，不是对同一用户下任意代码执行或浏览器控制的强隔离。

## 安装与单项配置

要求 Node.js 22.18+，以及下文对应系统凭据服务。首次下载依赖后，本地输入页可离线运行：

```bash
npm ci --ignore-scripts
npm run configure -- --label "服务 API Key" --title "输入密钥" --placeholder "粘贴你的密钥"
npm start
```

用户打开返回的本机链接，亲自填写并保存。默认字段文件为 manifests/default.json；configure 只修改非敏感声明，不接收密钥。支持 --dry-run 和 --save-label。

字段声明示例：

```json
{
  "version": 1,
  "id": "sample-skill",
  "label": "服务 API Key",
  "credential": "sample-skill/service/default",
  "ui": { "title": "输入密钥", "placeholder": "粘贴你的密钥", "saveLabel": "保存" }
}
```

id、label、credential 必填，ui 可省略。每项只接受非空单行密钥，最长 2500 个字符；系统后端的容量限制仍可能更低，失败时不会改存明文文件。密钥值不属于声明字段。

## 同页填写多个 Key

先创建另一项独立声明：

```bash
npm run configure -- --manifest manifests/image.json --id sample-skill --label "图片服务 API Key" --credential sample-skill/image/default --placeholder "粘贴图片服务密钥"
```

临时组合：

```bash
npm start -- --manifest manifests/default.json --manifest manifests/image.json
```

可复用页面配置：

```bash
npm run configure-page -- --page manifests/setup.page.json --manifest manifests/default.json --manifest manifests/image.json --title "连接服务" --label "两项服务" --save-label "保存"
npm start -- --page manifests/setup.page.json
```

页面 JSON 只保存引用与文案：

```json
{
  "version": 1,
  "manifests": ["default.json", "image.json"],
  "ui": { "title": "连接服务", "label": "两项服务", "saveLabel": "保存" }
}
```

每页 1 至 16 项，顺序由 manifests 决定。文件内的路径相对于页面配置文件，CLI 参数路径相对于运行目录。配置命令自动转换为相对路径；支持三端搬移。

只改页面文案：

```bash
npm run configure-page -- --page manifests/setup.page.json --title "配置服务"
```

不传 --manifest 保留列表，传入时替换整组。支持 --dry-run。字段标签和占位文字继续由 configure 修改；同页标题与按钮来自页面 ui。修改配置后重新启动。--page 和启动时的 --manifest 互斥。

已有字段声明的 id 与 credential 不可直接改写；新账号另建声明，不同账号使用不同引用。移除页面字段只改变表单，不删除系统凭据。

## 保存与恢复

尚未配置项必填；已有项显示“已配置”，留空保留，输入新值才替换。原值不会回填页面。替换按钮固定显示“替换并保存”，自定义文案不能覆盖这一提示。

整组预检通过后顺序保存。系统凭据库没有跨项事务：中途失败保留成功项、停止后续写入，并逐项标明结果，不自动回滚。用户先核对状态，再补填未完成项；后端报错可能存在结果不确定的情况，不能据此断言未写入。

提交结束或离开页面会清空输入。会话 30 分钟有效，全部成功后保留结果 90 秒。取消和过期不撤销此前保存。网络超时后先查状态，不重复提交。

Agent 只处理入口与脱敏状态，不自动操作含真实密钥的页面。/agent/status 使用启动令牌认证；只有 saved 表示全部成功，partial 表示部分失败。不要分享本机会话链接或让用户将密钥贴进聊天。

## 存储与平台

| 平台 | 后端 | 前提与管理入口 |
| --- | --- | --- |
| macOS | Keychain 钥匙串 | 当前用户钥匙串可访问；“钥匙串访问”中管理，系统授权由用户确认 |
| Windows | Credential Manager 凭据管理器 | 当前用户会话可用；“凭据管理器 → Windows 凭据”中的对应通用凭据 |
| Linux | secret-tool / Secret Service | libsecret 工具、用户 D-Bus 会话及已解锁的 Secret Service 实现，例如 GNOME Keyring；管理入口依桌面环境而定 |

macOS / Windows 通过 @napi-rs/keyring 原生绑定。Linux 显式调用 secret-tool，保存值经标准输入传递，不使用可能降级到临时 keyutils 的默认绑定。

服务标识为 org.oiloil.skill-credentials，账号属性为声明的 credential。不同后端界面显示名称可能不同。存储属于当前系统用户，本组件不负责跨设备同步、备份或迁移旧文件。

凭据库不可用或被锁定时停止，明确提示检查服务；不自动安装、解锁或降级到 JSON、浏览器存储等明文介质。服务器、无桌面 Linux 或其他凭据实现必须另行确认实际能力。

当前 macOS 已验证；Windows / Linux 已实现适配但尚未实机验证。

## 业务使用

把真实可信程序与环境变量名代入：

```bash
node src/run.ts --manifest manifests/default.json --env SERVICE_API_KEY -- your-program your-arguments
```

一次任务读取多个 Key：

```bash
node src/run.ts --manifest manifests/default.json --env FIRST_API_KEY --manifest manifests/image.json --env SECOND_API_KEY -- your-program your-arguments
```

全部读取成功后才启动程序，重复变量或缺少凭据时停止。页面文件只定义填写方式，业务端仍逐项绑定，避免注入不需要的密钥。密钥不进入命令参数或父进程环境。

包装器不是沙箱：可信子进程取得原值后仍可能打印或外传。需要强隔离时使用独立可信执行服务或宿主权限边界，不依赖密码框或系统凭据库作绝对保证。

检查单项状态：

```bash
npm run status -- --manifest manifests/image.json
```

仅返回配置状态与后端；未配置退出码 2，后端失败退出码 1。可信 Node.js 程序也可内部使用 nativeBackend 的 get / set / delete；保存与删除须用户授权，不向 Agent 暴露任意读取或删除接口。

## 开发验收

```bash
npm run check
npm run build
npm test
npm run test:native
```

常规测试使用假后端与受控 DOM，不操作真实浏览器。原生测试经真实同页 HTTP 入口写入随机假凭据，检查多变量业务读取与隔离，最后清理测试项。修改前端后必须提交一致的 public/app.js，最终用户无需编译。

维护时同时验证单 Key、同页多 Key、留空保留、部分失败重试、未知字段拒绝、会话隔离、状态脱敏及系统后端。不能用另写的静态演示替代正式页面测试。

## 固定业务入口

`manifests/profiles.json` 只保存业务名、声明文件和环境变量，不保存密钥。目标 Skill 接入时提供实际配置名；单项或多项复用相同页面与运行器：

```bash
node src/profile.ts status default
node src/profile.ts setup default
node src/profile.ts run default -- your-program your-arguments
```

status 退出码 0 表示所需凭据可读取，2 表示缺失，1 表示后端或配置错误。setup 由用户亲自填写；run 优先复用运行时环境变量，缺失时仅读取对应声明，不把其他服务凭据注入任务。指定其他服务时同时修改业务参数，不能只换凭据。
````

## File: scripts/credential-ui/component.json
size: 2237
sha: 9f2e8809bf4677f1433b5f50cb38e58c1711c16f
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/component.json

```text
{
  "version": 1,
  "files": {
    "README.md": "c66161233e7b45ed3027d43a1dacbb3f5eca68c8db52cac20d3781f4a868f786",
    "tsconfig.web.json": "7ced73bff9909988639b0369bbd4bfbb756d8570f75ac711a02b29a6e42d88e7",
    "package-lock.json": "0b457e658ad62b3d699d4aa3b0a504ae03e9f879a9d0a8d8d4e15d0db1a3845c",
    "package.json": "82c1b1b85ee7f5ce2be69d2f389167de6a7f3bfb47ef210a83c4dd4ec51d720d",
    "tsconfig.json": "005d701b301f56cf02563ba2936134899a60685d1b41536c13726457eab351a5",
    "web/app.ts": "c279800cdbdd67b145802ae0716588e605f05c43ad7468b43c1b26392bde461d",
    "tests/profile.test.ts": "48dcbbb90f0b39c4adaec1615c51edf33a76fff57549907da5e197ffde425da5",
    "tests/configure.test.ts": "3f360ed0102c944b7a502d783eea3c63016fdcaa3c230a1a6ec0865eb513cbd6",
    "tests/run.test.ts": "157f946c795d5f5b0a4c049201818bf0f646305050324d14f0913e751df1ca45",
    "tests/page.test.ts": "85772cc4b949443ff80d090bc1fc2fbc77f30ec4d8c26e40aa6530dd4270417a",
    "tests/native-smoke.ts": "d0a7ed2dd1ce7135a2a63bb8cfb779c24ccba19290cbabefaa280598866e0990",
    "tests/ui.test.ts": "613a90efc3607315a058a65a161e8d701453e4cba66a4cef89651a7ecd6c490a",
    "tests/credentials.test.ts": "2e33bbdfac5ffe04919526e755680e259e0a4aeef4cf411c5b39b1ccbeac0b13",
    "tests/multi-key.test.ts": "1879363e3718e8c538f01dcb180f78cbaa9b4a672e759068ec10b1188c1be654",
    "public/index.html": "859d06fa573f9f5409bc7d575e752a06dd08ce77fc67f464eea248f3b8f274be",
    "public/style.css": "7a993fc7fbd5edd29dfbff919c3370da3dc44fd6abc022709d55b892e3c0a893",
    "public/app.js": "7e08218bf04a2614bf801bc5c1c33f239bcdd2975804aa5869e60fdb6c4aaa3d",
    "public/favicon.svg": "574d5efbf305158c498636fbc81ecd27756b7cb7ff77ad73b4051fcf07d8fe42",
    "src/cli.ts": "a29c42750d81061f4721ce44ac3684d17d66fec791db155452234116c8988f34",
    "src/page.ts": "fbad1e2a9b1b2157444a715f55257f9992fea9b8dd8a9d3af15ef9545775f7f8",
    "src/profile.ts": "215ba42fa05cda235d1c9d09d42afbfc8c43a1d53fa4d7b7b4253948d6a3cdaf",
    "src/config.ts": "6d84f58c7859b49d291429819a4cd8b73051720ec420b34fcfb86538ed1cb687",
    "src/server.ts": "b84d14af6d805e1872875bd1aae94823b80d429139af9dc61ed937281795e2bf",
    "src/run.ts": "fe6b0ed145b6737ed472c929bb0e7f6c77721a0e4dfa9b6d785c3f09a2c5c028"
  }
}
```

## File: scripts/credential-ui/manifests/default.json
size: 230
sha: e2480e1b4c76d648e65d5b6e5b4a43f1f45264b5
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/manifests/default.json

```text
{
  "version": 1,
  "id": "oil-icon",
  "label": "图片 API Key",
  "credential": "oil-icon/openai/default",
  "ui": {
    "title": "配置服务",
    "placeholder": "粘贴该服务的 API Key",
    "saveLabel": "保存"
  }
}
```

## File: scripts/credential-ui/manifests/profiles.json
size: 147
sha: baa33b1bf6405652515190d2d112536ace1abcd8
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/manifests/profiles.json

```text
{
  "version": 1,
  "profiles": {
    "default": [
      {
        "manifest": "default.json",
        "env": "OPENAI_API_KEY"
      }
    ]
  }
}
```

## File: scripts/credential-ui/package-lock.json
size: 8679
sha: b9f47b1c1f795a24e61601b2f052a31eed79a848
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/package-lock.json

```text
{
  "name": "skill-credentials",
  "version": "0.1.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "skill-credentials",
      "version": "0.1.0",
      "dependencies": {
        "@napi-rs/keyring": "2.0.0"
      },
      "devDependencies": {
        "@types/node": "22.20.1",
        "typescript": "~5.9.3"
      },
      "engines": {
        "node": ">=22.18.0"
      }
    },
    "node_modules/@napi-rs/keyring": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/@napi-rs/keyring/-/keyring-2.0.0.tgz",
      "integrity": "sha512-TnrIt0nO9U2Ue9E9vJQjso1hqhIYiGrn2Ew1HBsMSqQe4+ceOqPJJwRVsV0/Wy7pqp04/doOLASyIFM3gGwZJw==",
      "license": "MIT",
      "engines": {
        "node": ">= 10"
      },
      "funding": {
        "type": "github",
        "url": "https://github.com/sponsors/Brooooooklyn"
      },
      "optionalDependencies": {
        "@napi-rs/keyring-darwin-arm64": "2.0.0",
        "@napi-rs/keyring-darwin-x64": "2.0.0",
        "@napi-rs/keyring-freebsd-x64": "2.0.0",
        "@napi-rs/keyring-linux-arm-gnueabihf": "2.0.0",
        "@napi-rs/keyring-linux-arm64-gnu": "2.0.0",
        "@napi-rs/keyring-linux-arm64-musl": "2.0.0",
        "@napi-rs/keyring-linux-riscv64-gnu": "2.0.0",
        "@napi-rs/keyring-linux-x64-gnu": "2.0.0",
        "@napi-rs/keyring-linux-x64-musl": "2.0.0",
        "@napi-rs/keyring-win32-arm64-msvc": "2.0.0",
        "@napi-rs/keyring-win32-ia32-msvc": "2.0.0",
        "@napi-rs/keyring-win32-x64-msvc": "2.0.0"
      }
    },
    "node_modules/@napi-rs/keyring-darwin-arm64": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/@napi-rs/keyring-darwin-arm64/-/keyring-darwin-arm64-2.0.0.tgz",
      "integrity": "sha512-yvIfviiXpsDSsPdyzWWd7STZt7v774biPfMBpWkiK7rwauwWbOmVjUzgiJ11rbhJbWLqXE3CuQMyLgvcbm3jIA==",
      "cpu": [
        "arm64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "darwin"
      ],
      "engines": {
        "node": ">= 10"
      }
    },
    "node_modules/@napi-rs/keyring-darwin-x64": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/@napi-rs/keyring-darwin-x64/-/keyring-darwin-x64-2.0.0.tgz",
      "integrity": "sha512-XJUONH0c5cg7M9/1Vj3WeIi8TtWYdZlo8Jqho09ga8OWm9cFNxUv7+4QZx5UK/3JSp2qiyhTlresyKdcpwpnRw==",
      "cpu": [
        "x64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "darwin"
      ],
      "engines": {
        "node": ">= 10"
      }
    },
    "node_modules/@napi-rs/keyring-freebsd-x64": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/@napi-rs/keyring-freebsd-x64/-/keyring-freebsd-x64-2.0.0.tgz",
      "integrity": "sha512-u/M114J9Lp3RqtIZihIqhvreNQ5f8wgLFo9tJFy+bIIO/xEHkMR0LENrfUF8hSY6FTNyS2kSbbkN6yOItBFY5g==",
      "cpu": [
        "x64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "freebsd"
      ],
      "engines": {
        "node": ">= 10"
      }
    },
    "node_modules/@napi-rs/keyring-linux-arm-gnueabihf": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/@napi-rs/keyring-linux-arm-gnueabihf/-/keyring-linux-arm-gnueabihf-2.0.0.tgz",
      "integrity": "sha512-CHMv/KTuELo/MsrGUha52KrFGPBuBkeAonnMFUd3nNcxBTSmeJbCAZTuVSXzpessdpb4tT9xIMQsv2ZdWrl8iw==",
      "cpu": [
        "arm"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">= 10"
      }
    },
    "node_modules/@napi-rs/keyring-linux-arm64-gnu": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/@napi-rs/keyring-linux-arm64-gnu/-/keyring-linux-arm64-gnu-2.0.0.tgz",
      "integrity": "sha512-BeUUPGSnW026yDGT4pKuNXDnwxw0xslwiSK6cuOIsDNLi3UO93rfF/7moqKznrBldgsZr8pl9LkMdRk8bnbjEA==",
      "cpu": [
        "arm64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">= 10"
      }
    },
    "node_modules/@napi-rs/keyring-linux-arm64-musl": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/@napi-rs/keyring-linux-arm64-musl/-/keyring-linux-arm64-musl-2.0.0.tgz",
      "integrity": "sha512-zj7wZ23Vs7SL4odnGDbWnhZhiyrnEgBe4+8dzKHDi1mTBX1d00FYlGOubkjvx3AeK7mm6G2FyFDDFqIxyR82gA==",
      "cpu": [
        "arm64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">= 10"
      }
    },
    "node_modules/@napi-rs/keyring-linux-riscv64-gnu": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/@napi-rs/keyring-linux-riscv64-gnu/-/keyring-linux-riscv64-gnu-2.0.0.tgz",
      "integrity": "sha512-xk/1SOhuk2yQvXiN+pBhR4njSfquLm1SUKUIJcPIeYV1bHFXbUsYrXdfy4NtynSW0lhs41zWjLXSdE8TLeTt2g==",
      "cpu": [
        "riscv64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">= 10"
      }
    },
    "node_modules/@napi-rs/keyring-linux-x64-gnu": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/@napi-rs/keyring-linux-x64-gnu/-/keyring-linux-x64-gnu-2.0.0.tgz",
      "integrity": "sha512-12Dq6t2TOrQTibcJcfV5bnHbTvMwEz6zSDqQLHMO2x388gGFQBAeEvw7Hmt+R1QavxspTa2ptgI7axomu9TH+w==",
      "cpu": [
        "x64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">= 10"
      }
    },
    "node_modules/@napi-rs/keyring-linux-x64-musl": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/@napi-rs/keyring-linux-x64-musl/-/keyring-linux-x64-musl-2.0.0.tgz",
      "integrity": "sha512-7NJZvFUiL1FPCrSIQ1L4IUzN6l/2zoxT3IN6j3rHTuDdIEunJaycrUovDMvPlBNP1Vh3fSYz6Pp7tFjdt/1/oQ==",
      "cpu": [
        "x64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">= 10"
      }
    },
    "node_modules/@napi-rs/keyring-win32-arm64-msvc": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/@napi-rs/keyring-win32-arm64-msvc/-/keyring-win32-arm64-msvc-2.0.0.tgz",
      "integrity": "sha512-JTktZGXKow0HF/rhaZiQYB8DUS/iSX7S7FvJDoGxPT8mGavKE3w/vadtfKSBNDL4uGef3wu2Ll0XxSfDKBsm2Q==",
      "cpu": [
        "arm64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "win32"
      ],
      "engines": {
        "node": ">= 10"
      }
    },
    "node_modules/@napi-rs/keyring-win32-ia32-msvc": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/@napi-rs/keyring-win32-ia32-msvc/-/keyring-win32-ia32-msvc-2.0.0.tgz",
      "integrity": "sha512-AzvIFTqn1hJzCPu0foeYWn+kXruAIrVq3Z2IfJ24WPbIXUdD7+rcj49fqco7b14Z6C1aUfsSTyvrAgDfUWhKvA==",
      "cpu": [
        "ia32"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "win32"
      ],
      "engines": {
        "node": ">= 10"
      }
    },
    "node_modules/@napi-rs/keyring-win32-x64-msvc": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/@napi-rs/keyring-win32-x64-msvc/-/keyring-win32-x64-msvc-2.0.0.tgz",
      "integrity": "sha512-POpEUTV6U+pb69cpuOgtLV4xhcyEWDWq+/9zdiZmNxTL1AenE0MllWrbepS+Hng4M7EarQ5TB3kX69ASqGwfIw==",
      "cpu": [
        "x64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "win32"
      ],
      "engines": {
        "node": ">= 10"
      }
    },
    "node_modules/@types/node": {
      "version": "22.20.1",
      "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.1.tgz",
      "integrity": "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q==",
      "dev": true,
      "license": "MIT",
      "dependencies": {
        "undici-types": "~6.21.0"
      }
    },
    "node_modules/typescript": {
      "version": "5.9.3",
      "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
      "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
      "dev": true,
      "license": "Apache-2.0",
      "bin": {
        "tsc": "bin/tsc",
        "tsserver": "bin/tsserver"
      },
      "engines": {
        "node": ">=14.17"
      }
    },
    "node_modules/undici-types": {
      "version": "6.21.0",
      "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
      "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
      "dev": true,
      "license": "MIT"
    }
  }
}
```

## File: scripts/credential-ui/package.json
size: 656
sha: 95b4c6d5e57d53b04c10251dfecf501cd5158878
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/package.json

```text
{
  "name": "skill-credentials",
  "version": "0.1.0",
  "private": true,
  "type": "module",
  "engines": {
    "node": ">=22.18.0"
  },
  "scripts": {
    "build": "tsc -p tsconfig.web.json",
    "check": "tsc --noEmit -p tsconfig.json",
    "start": "node src/server.ts",
    "configure": "node src/cli.ts configure",
    "configure-page": "node src/cli.ts configure-page",
    "status": "node src/cli.ts status",
    "test": "node --test tests/*.test.ts",
    "test:native": "node tests/native-smoke.ts"
  },
  "devDependencies": {
    "@types/node": "22.20.1",
    "typescript": "~5.9.3"
  },
  "dependencies": {
    "@napi-rs/keyring": "2.0.0"
  }
}
```

## File: scripts/credential-ui/public/app.js
size: 6440
sha: 153fc6d8647fbe0d81d6b2927e8f376cc052a5bc
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/public/app.js

```text
"use strict";
const get = (id) => document.getElementById(id);
const form = get('credential-form');
const button = get('save');
let inputs = [];
let meta;
let busy = false;
const saveLabel = () => inputs.some((input, index) => input.value.trim() && meta.fields[index].configured)
    ? '替换并保存' : (meta.page.saveLabel ?? (meta.fields.length === 1 ? meta.fields[0].ui?.saveLabel : undefined) ?? '保存');
async function request(url, options = {}) {
    let response;
    try {
        response = await fetch(url, { ...options, credentials: 'same-origin', cache: 'no-store',
            headers: { 'Content-Type': 'application/json', 'X-Local-Request': '1', ...options.headers }, signal: AbortSignal.timeout(25_000) });
    }
    catch {
        throw new Error('未收到服务回复，请刷新确认保存结果，不要重复提交。');
    }
    const result = await response.json();
    if (!response.ok)
        throw new Error(result.error ?? '操作未完成，请重试。');
    return result;
}
function message(text) { const node = get('message'); node.textContent = text; node.hidden = false; }
function clearInputs() { inputs.forEach(input => { input.value = ''; }); }
function done() {
    clearInputs();
    form.hidden = true;
    get('heading').textContent = '已保存';
    get('hint').hidden = true;
    message('可以关闭此页，回到对话继续。');
}
function update() {
    button.disabled = busy || !meta || !['waiting', 'partial'].includes(meta.outcome)
        || !inputs.some(input => input.value.trim())
        || inputs.some((input, index) => !meta.fields[index].configured && !input.value.trim());
    if (meta && !busy)
        button.textContent = saveLabel();
}
function render() {
    clearInputs();
    inputs = [];
    const multi = meta.fields.length > 1;
    form.classList.toggle('multi', multi);
    const container = get('fields');
    container.replaceChildren();
    meta.fields.forEach((field, index) => {
        const wrapper = document.createElement('div');
        wrapper.className = 'field';
        const label = document.createElement('label');
        label.htmlFor = 'secret-' + index;
        label.textContent = field.label;
        if (!multi)
            label.className = 'visually-hidden';
        if (field.configured) {
            const state = document.createElement('span');
            state.className = 'field-state';
            state.textContent = '已配置';
            label.append(state);
        }
        const input = document.createElement('input');
        input.id = label.htmlFor;
        input.type = 'password';
        input.autocomplete = 'new-password';
        input.autocapitalize = 'off';
        input.spellcheck = false;
        input.maxLength = 2500;
        input.required = !field.configured;
        input.setAttribute('aria-describedby', 'hint message');
        input.placeholder = field.configured ? '留空保留，输入则替换' : (field.ui?.placeholder ?? '粘贴 API Key');
        input.disabled = !['waiting', 'partial'].includes(meta.outcome);
        wrapper.append(label, input);
        container.append(wrapper);
        inputs.push(input);
    });
    get('context').textContent = meta.page.label ?? (multi ? meta.fields.length + ' 项凭据' : meta.fields[0].label);
    const title = meta.page.title ?? (multi ? '输入密钥' : meta.fields[0].ui?.title) ?? '输入密钥';
    get('heading').textContent = title;
    document.title = title;
    const storage = [...new Set(meta.fields.map(field => field.storage))].join('、');
    get('hint').textContent = '仅保存到' + storage + (meta.fields.some(field => field.configured) ? ' · 已配置项留空保留' : '');
    update();
    if (meta.outcome === 'saved')
        done();
    else if (meta.outcome === 'partial')
        message('上次仅部分保存。请核对已配置项，补填未完成项后重试。');
    else if (meta.outcome !== 'waiting')
        message('本次配置已结束，请重新打开入口。');
}
form.addEventListener('input', () => { update(); get('message').hidden = true; });
form.addEventListener('submit', async (event) => {
    event.preventDefault();
    if (busy || button.disabled)
        return;
    busy = true;
    update();
    inputs.forEach(input => { input.disabled = true; });
    button.textContent = '正在保存…';
    try {
        const entries = inputs.flatMap((input, index) => input.value.trim() ? [{ credential: meta.fields[index].credential,
                value: input.value, revision: meta.fields[index].revision, replaceExisting: meta.fields[index].configured }] : []);
        const result = await request('/api/save', { method: 'POST', body: JSON.stringify({ entries }) });
        if (result.status === 'saved') {
            meta.outcome = 'saved';
            done();
        }
        else {
            clearInputs();
            meta = await request('/api/meta');
            render();
            const statuses = { saved: '已保存', failed: '未确认成功', not_attempted: '未尝试' };
            message((result.results ?? []).map(item => (meta.fields.find(field => field.credential === item.credential)?.label ?? '凭据') + '：' + (statuses[item.status] ?? '请核对')).join('；')
                + '。请核对状态后重新填写未完成项。');
        }
    }
    catch (error) {
        clearInputs();
        try {
            meta = await request('/api/meta');
            render();
        }
        catch {
            meta.outcome = 'unknown';
        }
        if (meta.outcome !== 'saved')
            message(error instanceof Error ? error.message : '保存未完成，请刷新确认结果。');
    }
    finally {
        clearInputs();
        busy = false;
        inputs.forEach(input => { input.disabled = !['waiting', 'partial'].includes(meta.outcome); });
        update();
    }
});
window.addEventListener('pagehide', clearInputs);
async function initialize() {
    const token = location.hash.slice(1);
    if (token) {
        history.replaceState(null, '', location.pathname);
        await request('/api/session', { method: 'POST', headers: { Authorization: 'Bearer ' + token }, body: '{}' });
    }
    meta = await request('/api/meta');
    render();
}
initialize().catch(error => { get('context').textContent = '暂时无法连接'; message(error instanceof Error ? error.message : '请重新打开配置入口。'); });
```

## File: scripts/credential-ui/public/favicon.svg
size: 315
sha: 3e53faae2439312a643d5d475a18a415216a94da
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/public/favicon.svg

```text
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40"><rect width="40" height="40" rx="12" fill="#292929"/><path d="M12 19v-4a8 8 0 0 1 16 0v4" fill="none" stroke="#eeeeee" stroke-width="3"/><rect x="9" y="18" width="22" height="16" rx="5" fill="#eeeeee"/><circle cx="20" cy="25" r="2" fill="#292929"/></svg>
```

## File: scripts/credential-ui/public/index.html
size: 1188
sha: 507af4a257bed24d6eeca9c848e904d67de42f8b
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/public/index.html

```text
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="color-scheme" content="light" />
  <meta name="referrer" content="no-referrer" />
  <title>输入密钥</title>
  <link rel="icon" href="/favicon.svg" type="image/svg+xml" />
  <link rel="stylesheet" href="/style.css" />
  <script type="module" src="/app.js"></script>
</head>
<body>
  <main>
    <h1 id="heading">输入密钥</h1>
    <p id="context" class="context">正在连接…</p>
    <form id="credential-form" autocomplete="off">
      <div id="fields">
      <label for="secret" class="visually-hidden">密钥</label>
      <input id="secret" name="secret" type="password" placeholder="粘贴 API Key" autocomplete="new-password" autocapitalize="off" autocorrect="off" spellcheck="false" maxlength="2500" required disabled aria-describedby="hint message" />
      </div>
      <button id="save" type="submit" disabled>保存</button>
    </form>
    <p id="hint" class="hint">仅保存到本机系统凭据库</p>
    <p id="message" class="message" role="status" aria-live="polite" hidden></p>
  </main>
</body>
</html>
```

## File: scripts/credential-ui/public/style.css
size: 3155
sha: 3187d768d516bef3f5ff257d9e45a50f2cd03fd2
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/public/style.css

```text
@charset "UTF-8";

:root {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
  color: #282828;
  background: #fafafa;
  font-synthesis: none;
  color-scheme: light;
  -webkit-font-smoothing: antialiased;
}

* { box-sizing: border-box; }
body {
  margin: 0;
  min-height: 100svh;
  display: grid;
  place-items: center;
  padding: 24px;
}
main {
  width: 100%;
  max-width: 320px;
  margin-top: -5vh;
}
h1 {
  margin: 0 0 6px;
  font-size: 20px;
  font-weight: 580;
  letter-spacing: -.45px;
  line-height: 1.45;
}
.context {
  margin: 0 0 19px;
  font-size: 11.5px;
  color: #777777;
  line-height: 1.6;
  overflow-wrap: anywhere;
}
form {
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  align-items: start;
  gap: 8px;
}
#fields, .field { display: contents; }
form.multi { grid-template-columns: 1fr; gap: 18px; }
.multi #fields { display: grid; gap: 17px; }
.multi .field { display: grid; gap: 7px; }
.multi label { font-size: 12px; line-height: 1.5; overflow-wrap: anywhere; }
.field-state { color: #818181; font-size: 10.5px; margin-left: 7px; }
.multi button { justify-self: end; height: 36px; }
body:has(form.multi) { align-items: safe center; }
body:has(form.multi) main { margin-top: 0; }
input, button {
  font: inherit;
  border-radius: 8px;
  height: 42px;
}
input {
  width: 100%;
  min-width: 0;
  background: #fff;
  border: 1px solid #dddddd;
  padding: 0 12px;
  font-size: 14px;
  color: #303030;
  outline: none;
  box-shadow: 0 1px 2px #00000003;
  transition: border-color .15s, box-shadow .15s;
}
input::placeholder {
  color: #999999;
  font-size: 12px;
}
input:hover:not(:disabled) { border-color: #c5c5c5; }
input:focus {
  border-color: #929292;
  box-shadow: 0 0 0 3px #eeeeee, 0 1px 2px #00000003;
}
input:disabled { background: #f4f4f4; }
button {
  min-width: 62px;
  padding: 0 15px;
  background: #303030;
  border: 1px solid #292929;
  color: #fafafa;
  font-size: 12px;
  font-weight: 500;
  white-space: nowrap;
  cursor: pointer;
  box-shadow: inset 0 1px 0 #ffffff0d, 0 1px 2px #0000000c;
  transition: background .15s, border-color .15s, transform .12s;
}
button:hover:not(:disabled) {
  background: #454545;
  border-color: #3c3c3c;
}
button:active:not(:disabled) { transform: translateY(1px); }
button:disabled {
  background: #ececec;
  border-color: #e3e3e3;
  color: #949494;
  box-shadow: none;
  cursor: default;
}
button:focus-visible {
  outline: 3px solid #c9c9c9;
  outline-offset: 3px;
}
.hint {
  margin: 12px 0 0;
  font-size: 10.5px;
  color: #818181;
  line-height: 1.7;
}
.message {
  margin: 12px 0 0;
  font-size: 11px;
  color: #5c5c5c;
  line-height: 1.8;
}
.message.success { color: #5c5c5c; }
.visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}
[hidden] { display: none !important; }

@media (max-width: 480px) {
  main { margin-top: -8vh; }
  input { font-size: 16px; }
  input, button { height: 44px; }
}
@media (prefers-reduced-motion: reduce) {
  * { transition: none !important; }
}
```

## File: scripts/credential-ui/src/cli.ts
size: 6463
sha: 3c6a5af3cd59a18b2d779ec13364eb956fc549a4
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/src/cli.ts

```text
import { randomBytes } from 'node:crypto';
import { lstat, mkdir, open, readFile, rename, unlink } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { loadManifest, nativeBackend, PublicError, validateManifest, type Manifest } from './config.ts';
import { loadPage, validateFields, validatePageUI } from './page.ts';

async function writeConfiguration(file: string, configuration: object) {
  await mkdir(path.dirname(file), { recursive: true });
  const temporary = file + '.' + randomBytes(8).toString('hex') + '.tmp';
  try {
    const handle = await open(temporary, 'wx', 0o600);
    try { await handle.writeFile(JSON.stringify(configuration, null, 2) + '\n', 'utf8'); await handle.sync(); }
    finally { await handle.close(); }
    await rename(temporary, file);
  } finally { await unlink(temporary).catch(() => {}); }
}
export async function configurePage(file: string, manifests: string[], options: Record<string, string>, dryRun = false) {
  if (Object.keys(options).some(key => !['title', 'label', 'save-label'].includes(key))) throw new PublicError('存在不支持的页面配置项。');
  let existing: { manifests: string[]; ui?: Record<string, string> } | undefined;
  try {
    const stat = await lstat(file);
    if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink > 1) throw new PublicError('页面配置必须是独立的普通文件。');
    await loadPage(file);
    existing = JSON.parse(await readFile(file, 'utf8'));
  } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
  // 命令参数按当前目录解析；写入页面文件后统一保存为相对该文件的路径。
  const paths = manifests.length ? manifests.map(item => path.relative(path.dirname(file), path.resolve(item)).split(path.sep).join('/')) : existing?.manifests ?? [];
  validateFields(await Promise.all(paths.map(item => loadManifest(path.resolve(path.dirname(file), item)))));
  const ui = { ...existing?.ui };
  for (const [flag, key] of [['title', 'title'], ['label', 'label'], ['save-label', 'saveLabel']])
    if (options[flag] !== undefined) ui[key] = options[flag];
  const configuration = { version: 1, manifests: paths, ui: validatePageUI(ui) };
  if (!dryRun) await writeConfiguration(file, configuration);
  return { status: dryRun ? 'preview' : 'configured', page: file, configuration };
}

export async function configureManifest(file: string, options: Record<string, string>, dryRun = false) {
  const allowed = ['id', 'label', 'credential', 'title', 'placeholder', 'save-label'];
  if (Object.keys(options).some(k => !allowed.includes(k))) throw new PublicError('存在不支持的配置项。');
  let existing: Manifest | undefined;
  try {
    const stat = await lstat(file);
    if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink > 1) throw new PublicError('声明必须是独立的普通文件。');
    existing = await loadManifest(file);
  } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
  if (existing && ((options.id && options.id !== existing.id) || (options.credential && options.credential !== existing.credential)))
    throw new PublicError('已有声明的身份和凭据引用不可改写。请为新凭据指定新的 --manifest 文件。');
  const draft: Record<string, unknown> = { version: 1, ...existing };
  for (const key of ['id', 'label', 'credential']) if (options[key] !== undefined) draft[key] = options[key];
  const ui = { ...existing?.ui };
  for (const [flag, key] of [['title', 'title'], ['placeholder', 'placeholder'], ['save-label', 'saveLabel']] as const)
    if (options[flag] !== undefined) ui[key] = options[flag];
  if (Object.keys(ui).length) draft.ui = ui;
  const manifest = validateManifest(draft);
  if (!dryRun) await writeConfiguration(file, manifest);
  return { status: dryRun ? 'preview' : 'configured', manifest: file, configuration: manifest };
}
async function main() {
  const [command, ...args] = process.argv.slice(2);
  if (!command || command === '--help') {
    process.stdout.write('configure [--manifest 文件] --id 标识 --label 用途 --credential 引用 [--title 标题] [--placeholder 占位文字] [--save-label 按钮文字] [--dry-run]\nconfigure-page --page 文件 [--manifest 声明（可重复，替换整组）] [--title 标题] [--label 用途] [--save-label 按钮文字] [--dry-run]\nstatus [--manifest 文件]\n');
    return;
  }
  const flags: Record<string, string> = {};
  const manifests: string[] = [];
  let dryRun = false;
  for (let i = 0; i < args.length; i++) {
    if (args[i] === '--dry-run' && ['configure', 'configure-page'].includes(command)) { dryRun = true; continue; }
    if (command === 'configure-page' && args[i] === '--manifest' && args[i + 1] && !args[i + 1].startsWith('--')) { manifests.push(args[++i]); continue; }
    const name = args[i].replace(/^--/, '');
    if (!args[i].startsWith('--') || !args[i + 1] || args[i + 1].startsWith('--') || Object.hasOwn(flags, name))
      throw new PublicError('命令参数不正确。');
    flags[name] = args[++i];
  }
  if (command === 'configure-page') {
    if (!flags.page) throw new PublicError('请指定 --page 配置文件。');
    const file = path.resolve(flags.page); delete flags.page;
    process.stdout.write(JSON.stringify(await configurePage(file, manifests, flags, dryRun)) + '\n'); return;
  }
  const file = path.resolve(flags.manifest ?? fileURLToPath(new URL('../manifests/default.json', import.meta.url)));
  delete flags.manifest;
  if (command === 'configure') process.stdout.write(JSON.stringify(await configureManifest(file, flags, dryRun)) + '\n');
  else if (command === 'status' && !Object.keys(flags).length) {
    const m = await loadManifest(file);
    const backend = await nativeBackend(m.credential);
    const configured = (await backend.get()) !== undefined;
    process.stdout.write(JSON.stringify({ id: m.id, credential: m.credential, configured, storage: backend.name }) + '\n');
    if (!configured) process.exitCode = 2;
  } else throw new PublicError('命令不支持，请使用 --help。');
}
if (process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url)
  main().catch(error => {
    process.stderr.write((error instanceof PublicError ? error.message : '配置操作未完成，请检查文件位置与权限。') + '\n');
    process.exitCode = 1;
  });
```

## File: scripts/credential-ui/src/config.ts
size: 5876
sha: a32c57edcc0a377a6e23dfc2566fcb8d44193350
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/src/config.ts

```text
import { createHmac, randomBytes } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { execFile, spawn } from 'node:child_process';

export class PublicError extends Error {
  status: number;
  constructor(message: string, status = 400) { super(message); this.status = status; }
}
export type Manifest = {
  version: 1; id: string; label: string; credential: string;
  ui?: { title?: string; placeholder?: string; saveLabel?: string };
};
export const object = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
export async function loadManifest(file: string): Promise<Manifest> {
  let m: unknown;
  try { m = JSON.parse(await readFile(file, 'utf8')); } catch { throw new PublicError('无法读取配置声明。'); }
  return validateManifest(m);
}
export function validateManifest(m: unknown): Manifest {
  if (!object(m) || m.version !== 1 || typeof m.id !== 'string' || !/^[a-z0-9-]{1,80}$/.test(m.id)
    || typeof m.label !== 'string' || !m.label.trim() || m.label.length > 120
    || typeof m.credential !== 'string' || !/^[a-z0-9][a-z0-9/_.-]{0,150}$/.test(m.credential)
    || Object.keys(m).some(k => !['version', 'id', 'label', 'credential', 'ui'].includes(k))) throw new PublicError('配置声明不合法。');
  if (m.ui !== undefined && (!object(m.ui) || Object.entries(m.ui).some(([k, v]) =>
    !['title', 'placeholder', 'saveLabel'].includes(k) || typeof v !== 'string' || !v.trim() || v.length > 80)))
    throw new PublicError('页面配置不合法。');
  return m as Manifest;
}
export interface CredentialBackend {
  name: string;
  get(): Promise<string | undefined>;
  set(value: string): Promise<void>;
  delete(): Promise<void>;
}
export const service = 'org.oiloil.skill-credentials';
const backendError = () => new PublicError('无法访问系统凭据库，请解锁或检查系统凭据服务后重试。', 503);

// Linux 显式使用 Secret Service，不走可能回退到临时 keyutils 的默认绑定。
function linuxBackend(credential: string): CredentialBackend {
  const attributes = ['service', service, 'account', credential];
  const run = (args: string[]): Promise<string | undefined> => new Promise((resolve, reject) => {
    execFile('secret-tool', args, { timeout: 15_000, maxBuffer: 32_768, encoding: 'utf8' }, (error, stdout, stderr) => {
      if (error) {
        if (args[0] === 'lookup' && error.code === 1 && !stderr.trim()) resolve(undefined);
        else reject(backendError());
      } else resolve(stdout.replace(/\r?\n$/, ''));
    });
  });
  return { name: 'Linux Secret Service', get: () => run(['lookup', ...attributes]),
    set: value => new Promise((resolve, reject) => {
      const child = spawn('secret-tool', ['store', '--label=Skill 凭据', ...attributes], { stdio: ['pipe', 'ignore', 'ignore'], timeout: 15_000, shell: false });
      child.once('error', () => reject(backendError()));
      child.stdin.on('error', () => reject(backendError()));
      child.once('close', code => code === 0 ? resolve() : reject(backendError()));
      child.stdin.end(value + '\n');
    }),
    delete: async () => { await run(['clear', ...attributes]); }
  };
}
export async function nativeBackend(credential: string): Promise<CredentialBackend> {
  if (process.platform === 'linux') return linuxBackend(credential);
  if (!['darwin', 'win32'].includes(process.platform)) throw new PublicError('当前系统暂不支持凭据保存。', 503);
  try {
    const { AsyncEntry } = await import('@napi-rs/keyring');
    const entry = new AsyncEntry(service, credential);
    return { name: process.platform === 'darwin' ? 'macOS 钥匙串' : 'Windows 凭据管理器',
      // 原生绑定的空结果在实际运行中可能为 null，统一为接口约定的 undefined。
      get: async () => { try { return (await entry.getPassword()) ?? undefined; } catch { throw backendError(); } },
      set: async value => { try { await entry.setPassword(value); } catch { throw backendError(); } },
      delete: async () => { try { await entry.deleteCredential(); } catch { throw backendError(); } }
    };
  } catch { throw backendError(); }
}
export function createStore(manifest: Manifest, backend: CredentialBackend) {
  const salt = randomBytes(32);
  let busy = false;
  async function status() {
    let value: string | undefined;
    try { value = await backend.get(); } catch { throw backendError(); }
    const revision = createHmac('sha256', salt).update(value === undefined ? 'missing:' : 'exists:').update(value ?? '').digest('hex');
    return { revision, configured: value !== undefined, storage: backend.name };
  }
  async function validate(input: unknown) {
    if (!object(input) || typeof input.value !== 'string' || !input.value.trim() || input.value.length > 2500
      || /[\r\n\0]/.test(input.value) || typeof input.revision !== 'string'
      || Object.keys(input).some(k => !['value', 'revision', 'replaceExisting'].includes(k))) throw new PublicError('请填写有效的单行密钥。');
    const current = await status();
    if (current.revision !== input.revision) throw new PublicError('凭据已发生变化，请刷新后重试。', 409);
    if (current.configured && input.replaceExisting !== true) throw new PublicError('已有凭据，请确认替换后保存。', 409);
    return { value: input.value.trim() };
  }
  async function save(input: unknown) {
    if (busy) throw new PublicError('正在保存，请稍后。', 409);
    busy = true;
    try {
      const checked = await validate(input);
      await backend.set(checked.value);
      return { status: 'saved', skill: manifest.id, credential: manifest.credential, configured: true };
    } catch (error) { if (error instanceof PublicError) throw error; throw backendError(); }
    finally { busy = false; }
  }
  return { status, save, validate };
}
```

## File: scripts/credential-ui/src/page.ts
size: 1739
sha: b8ac6faed254509dd1bf8f5ff6b6c7177450fbe4
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/src/page.ts

```text
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { loadManifest, object, PublicError, validateManifest, type Manifest } from './config.ts';

export type PageUI = { title?: string; label?: string; saveLabel?: string };
export function validatePageUI(ui: unknown): PageUI {
  if (!object(ui) || Object.entries(ui).some(([key, value]) =>
    !['title', 'label', 'saveLabel'].includes(key) || typeof value !== 'string' || !value.trim() || value.length > 120))
    throw new PublicError('页面文案配置不合法。');
  return ui as PageUI;
}
export function validateFields(fields: Manifest[]): Manifest[] {
  if (!Array.isArray(fields) || fields.length < 1 || fields.length > 16) throw new PublicError('每页需要 1 至 16 项凭据声明。');
  fields.forEach(validateManifest);
  if (new Set(fields.map(field => field.credential)).size !== fields.length) throw new PublicError('同一页不能重复引用相同凭据。');
  return fields;
}
export async function loadPage(file: string) {
  let value: unknown;
  try { value = JSON.parse(await readFile(file, 'utf8')); } catch { throw new PublicError('无法读取页面配置。'); }
  if (!object(value) || value.version !== 1 || Object.keys(value).some(key => !['version', 'manifests', 'ui'].includes(key))
    || !Array.isArray(value.manifests) || !value.manifests.length || value.manifests.length > 16
    || value.manifests.some(item => typeof item !== 'string' || !item.trim())) throw new PublicError('页面配置不合法。');
  const ui = validatePageUI(value.ui ?? {});
  const manifests = validateFields(await Promise.all(value.manifests.map(item => loadManifest(path.resolve(path.dirname(file), item)))));
  return { manifests, ui };
}
```

## File: scripts/credential-ui/src/profile.ts
size: 4768
sha: 07c00570ef0d873d95e76569f8d8b100b87f8bcb
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/src/profile.ts

```text
import { readFile } from 'node:fs/promises';
import { spawn } from 'node:child_process';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { loadManifest, nativeBackend, object, PublicError } from './config.ts';
import { validateFields } from './page.ts';
import { parseBindings, prepareCommand } from './run.ts';
import { startServer } from './server.ts';

const root = fileURLToPath(new URL('../', import.meta.url));
type Binding = { manifest: string; env: string };
export async function loadProfile(name: string, directory = root): Promise<Binding[]> {
  let value: unknown;
  try { value = JSON.parse(await readFile(path.join(directory, 'manifests/profiles.json'), 'utf8')); }
  catch { throw new PublicError('未找到业务凭据配置。'); }
  if (!/^[a-z0-9-]+$/.test(name) || !object(value) || value.version !== 1 || !object(value.profiles)
    || !Object.hasOwn(value.profiles, name)) throw new PublicError('请选择已声明的业务配置。');
  const items = value.profiles[name];
  if (!Array.isArray(items) || !items.length || items.length > 16) throw new PublicError('业务凭据配置不合法。');
  const bindings: Binding[] = items.map(item => {
    if (!object(item) || Object.keys(item).some(k => !['manifest', 'env'].includes(k))
      || typeof item.manifest !== 'string' || !/^[a-z0-9-]+\.json$/.test(item.manifest)
      || typeof item.env !== 'string') throw new PublicError('业务凭据绑定不合法。');
    return { manifest: path.join(directory, 'manifests', item.manifest), env: item.env };
  });
  parseBindings([...bindingArgs(bindings), '--', 'check']);
  validateFields(await Promise.all(bindings.map(b => loadManifest(b.manifest))));
  return bindings;
}
function bindingArgs(bindings: Binding[]) {
  return bindings.flatMap(b => ['--manifest', b.manifest, '--env', b.env]);
}
export async function profileStatus(bindings: Binding[], environment = process.env,
  read = async (ref: string) => (await nativeBackend(ref)).get()) {
  const fields = [];
  for (const b of bindings) {
    const m = await loadManifest(b.manifest);
    const fromEnv = Boolean(environment[b.env]?.trim());
    const configured = fromEnv || Boolean(await read(m.credential));
    fields.push({ credential: m.credential, configured, source: fromEnv ? 'environment' : 'system-store' });
  }
  return { configured: fields.every(f => f.configured), fields };
}
export async function prepareProfile(bindings: Binding[], command: string[], environment = process.env,
  read = async (ref: string) => (await nativeBackend(ref)).get()) {
  if (!command.length) throw new PublicError('请指定真实业务程序。');
  // 环境注入优先；本次只读取所选业务需要的凭据。
  const missing = bindings.filter(b => !environment[b.env]?.trim());
  if (!missing.length) return { command: command[0], args: command.slice(1), env: { ...environment } };
  return prepareCommand([...bindingArgs(missing), '--', ...command], read, environment);
}
async function main() {
  const [action, name, ...args] = process.argv.slice(2);
  if (!['status', 'setup', 'run'].includes(action) || !name || (action !== 'run' && args.length)
    || (action === 'run' && (args[0] !== '--' || args.length < 2)))
    throw new PublicError('用法：node src/profile.ts status|setup 配置名；node src/profile.ts run 配置名 -- 程序 参数');
  const bindings = await loadProfile(name);
  if (action === 'status') {
    const status = await profileStatus(bindings);
    process.stdout.write(JSON.stringify(status) + '\n');
    if (!status.configured) process.exitCode = 2;
  } else if (action === 'setup') {
    const manifests = await Promise.all(bindings.map(b => loadManifest(b.manifest)));
    const app = await startServer({ manifests, onComplete: result => process.stdout.write(JSON.stringify(result) + '\n') });
    process.stdout.write(`本机配置页面（由用户亲自填写，30 分钟内有效）：\n${app.url}\n`);
    process.once('SIGINT', app.close); process.once('SIGTERM', app.close);
  } else {
    const plan = await prepareProfile(bindings, args.slice(1));
    const child = spawn(plan.command, plan.args, { env: plan.env, stdio: 'inherit', shell: false });
    for (const b of bindings) delete plan.env[b.env];
    child.once('error', () => { process.stderr.write('业务程序启动失败。\n'); process.exitCode = 1; });
    child.once('exit', code => { process.exitCode = code ?? 1; });
  }
}
if (process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url)
  main().catch(error => {
    process.stderr.write((error instanceof PublicError ? error.message : '配置未完成，请检查依赖与系统凭据服务。') + '\n');
    process.exitCode = 1;
  });
```

## File: scripts/credential-ui/src/run.ts
size: 3335
sha: d616d0e1b9268421c23ea6c48afa07ed2d5fc747
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/src/run.ts

```text
import { spawn } from 'node:child_process';
import { fileURLToPath, pathToFileURL } from 'node:url';
import path from 'node:path';
import { loadManifest, nativeBackend, PublicError } from './config.ts';

type Binding = { file: string; variable: string };
const defaultManifest = fileURLToPath(new URL('../manifests/default.json', import.meta.url));
const reserved = new Set(['PATH', 'HOME', 'SHELL', 'NODE_OPTIONS', 'LD_PRELOAD', 'DYLD_INSERT_LIBRARIES', 'PYTHONPATH', 'PYTHONSTARTUP', 'COMSPEC', 'SYSTEMROOT']);
export function parseBindings(args: string[]) {
  const split = args.indexOf('--');
  if (split < 0 || !args[split + 1]) throw new PublicError('请指定要启动的程序。');
  const bindings: Binding[] = [];
  const variables = new Set<string>();
  let pending: string | undefined;
  for (let i = 0; i < split; i += 2) {
    const value = args[i + 1];
    if (i + 1 >= split || !value || value.startsWith('--')) throw new PublicError('凭据绑定参数不完整。');
    if (args[i] === '--manifest' && pending === undefined) pending = value;
    else if (args[i] === '--env') {
      if (!/^[A-Z][A-Z0-9_]*$/.test(value) || reserved.has(value) || variables.has(value))
        throw new PublicError('环境变量名重复或不适合注入凭据。');
      bindings.push({ file: pending ?? defaultManifest, variable: value });
      variables.add(value); pending = undefined;
    } else throw new PublicError('凭据绑定参数不正确。');
  }
  if (pending !== undefined || !bindings.length || bindings.length > 16) throw new PublicError('请提供一至十六组完整的凭据绑定。');
  return { bindings, command: args[split + 1], args: args.slice(split + 2) };
}
export async function prepareCommand(
  args: string[],
  readCredential: (ref: string) => Promise<string | undefined> = async ref => (await nativeBackend(ref)).get(),
  baseEnv: NodeJS.ProcessEnv = process.env,
) {
  const plan = parseBindings(args);
  const manifests = await Promise.all(plan.bindings.map(binding => loadManifest(binding.file)));
  const env = { ...baseEnv };
  try {
    for (let i = 0; i < plan.bindings.length; i++) {
      const value = await readCredential(manifests[i].credential);
      if (!value) throw new PublicError('有凭据尚未配置，任务未启动。');
      env[plan.bindings[i].variable] = value;
    }
    return { ...plan, env };
  } catch (error) {
    for (const binding of plan.bindings) delete env[binding.variable];
    if (error instanceof PublicError) throw error;
    throw new PublicError('凭据读取未完成，任务未启动。');
  }
}
async function main() {
  const prepared = await prepareCommand(process.argv.slice(2));
  const child = spawn(prepared.command, prepared.args, { env: prepared.env, stdio: 'inherit', shell: false });
  for (const binding of prepared.bindings) delete prepared.env[binding.variable];
  child.once('error', () => { process.stderr.write('无法启动目标程序。\n'); process.exitCode = 1; });
  child.once('exit', code => { process.exitCode = code ?? 1; });
}
if (process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url)
  main().catch(error => {
    process.stderr.write((error instanceof PublicError ? error.message : '无法读取凭据或启动参数不正确。') + '\n');
    process.exitCode = 1;
  });
```

## File: scripts/credential-ui/src/server.ts
size: 11614
sha: 5feb0fecb075e14faefa0c094ab75425cf80ab67
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/src/server.ts

```text
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { randomBytes, timingSafeEqual } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { fileURLToPath, pathToFileURL } from 'node:url';
import path from 'node:path';
import { createStore, loadManifest, nativeBackend, object, PublicError, type Manifest, type CredentialBackend } from './config.ts';
import { loadPage, validateFields, validatePageUI, type PageUI } from './page.ts';

const root = fileURLToPath(new URL('../', import.meta.url));
function equal(a: string, b: string) { const x = Buffer.from(a); const y = Buffer.from(b); return x.length === y.length && timingSafeEqual(x, y); }
export async function startServer(options: { manifest?: Manifest; manifests?: Manifest[]; ui?: PageUI; backend?: CredentialBackend; backends?: CredentialBackend[]; port?: number; ttlMs?: number; onComplete?: (result: object) => void }) {
  if (options.manifest && options.manifests) throw new PublicError('不能同时指定单项与多项声明。');
  const fields = validateFields(options.manifests ?? (options.manifest ? [options.manifest] : []));
  const ui = validatePageUI(options.ui ?? {});
  if ((options.backends && options.backends.length !== fields.length) || (options.backend && (fields.length !== 1 || options.backends)))
    throw new PublicError('凭据后端与字段数量不匹配。');
  const stores = await Promise.all(fields.map(async (field, index) => createStore(field,
    options.backends?.[index] ?? options.backend ?? await nativeBackend(field.credential))));
  const store = stores[0];
  const identity = fields.length === 1 ? { skill: fields[0].id, credential: fields[0].credential }
    : { credentials: fields.map(field => ({ skill: field.id, credential: field.credential })) };
  let lastResult: object | undefined;
  const bootstrap = randomBytes(32).toString('hex');
  const session = randomBytes(32).toString('hex');
  // 同一主机上的不同端口共享 cookie 命名空间，因此每个会话使用独立名称。
  const cookieName = 'credentials_session_' + randomBytes(12).toString('hex');
  let origin = '';
  let outcome = 'waiting';
  let saving = false;
  let completedTimer: ReturnType<typeof setTimeout> | undefined;
  const assets: Record<string, [string, string]> = {
    '/': ['index.html', 'text/html; charset=utf-8'], '/app.js': ['app.js', 'text/javascript; charset=utf-8'],
    '/style.css': ['style.css', 'text/css; charset=utf-8'], '/favicon.svg': ['favicon.svg', 'image/svg+xml']
  };
  function json(res: ServerResponse, code: number, body: object) { res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8' }); res.end(JSON.stringify(body)); }
  async function body(req: IncomingMessage) {
    if (req.headers['content-type'] !== 'application/json') throw new PublicError('请求格式不支持。', 415);
    const parts: Buffer[] = []; let size = 0;
    for await (const chunk of req) {
      size += chunk.length;
      if (size > 256 * 1024) throw new PublicError('请求内容过大。', 413);
      parts.push(chunk);
    }
    try { return JSON.parse(Buffer.concat(parts).toString('utf8')) as unknown; }
    catch { throw new PublicError('请求格式不正确。'); }
  }
  const server = createServer(async (req, res) => {
    res.setHeader('Cache-Control', 'no-store');
    res.setHeader('X-Content-Type-Options', 'nosniff');
    res.setHeader('Referrer-Policy', 'no-referrer');
    res.setHeader('X-Frame-Options', 'DENY');
    res.setHeader('Content-Security-Policy', "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'");
    try {
      if (req.headers.host !== new URL(origin).host) throw new PublicError('请求来源不正确。', 403);
      const url = new URL(req.url ?? '/', origin);
      if (url.search) throw new PublicError('不接受 URL 查询参数。');
      if (req.headers.origin && req.headers.origin !== origin) throw new PublicError('不接受跨站请求。', 403);
      if (req.method === 'GET' && Object.hasOwn(assets, url.pathname)) {
        const [file, type] = assets[url.pathname];
        const content = await readFile(path.join(root, 'public', file));
        res.writeHead(200, { 'Content-Type': type }); res.end(content); return;
      }
      if (url.pathname === '/agent/status' && req.method === 'GET') {
        if (!equal(req.headers.authorization ?? '', `Bearer ${bootstrap}`)) throw new PublicError('无权访问。', 401);
        json(res, 200, { ...identity, status: outcome, result: lastResult }); return;
      }
      if (req.method === 'POST' && (req.headers.origin !== origin || req.headers['x-local-request'] !== '1'))
        throw new PublicError('请从本地配置页面提交。', 403);
      if (url.pathname === '/api/session' && req.method === 'POST') {
        if (!equal(req.headers.authorization ?? '', `Bearer ${bootstrap}`)) throw new PublicError('入口已失效，请重新打开工具提供的链接。', 401);
        res.setHeader('Set-Cookie', `${cookieName}=${session}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${Math.ceil((options.ttlMs ?? 30 * 60_000) / 1000)}`);
        json(res, 200, { status: 'ready' }); return;
      }
      const cookies = (req.headers.cookie ?? '').split(';').map(c => c.trim());
      if (!cookies.some(c => equal(c, `${cookieName}=${session}`))) throw new PublicError('请重新打开工具提供的配置链接。', 401);
      if (url.pathname === '/api/meta' && req.method === 'GET') {
        const metadata = await Promise.all(fields.map(async (field, index) => ({ ...field, ...await stores[index].status() })));
        json(res, 200, { ...metadata[0], fields: metadata, page: ui, outcome }); return;
      }
      if (url.pathname === '/api/save' && req.method === 'POST') {
        if (!['waiting', 'partial'].includes(outcome) || saving) throw new PublicError('配置正在保存或已结束，请稍后确认状态。', 409);
        saving = true;
        try {
          const input = await body(req);
          let result;
          if (fields.length === 1 && object(input) && !Object.hasOwn(input, 'entries')) result = await store.save(input);
          else {
            if (!object(input) || Object.keys(input).some(key => key !== 'entries') || !Array.isArray(input.entries)
              || !input.entries.length || input.entries.length > fields.length) throw new PublicError('提交字段不合法。');
            const seen = new Set<string>();
            const entries = input.entries.map(entry => {
              if (!object(entry) || typeof entry.credential !== 'string' || seen.has(entry.credential)) throw new PublicError('提交凭据重复或不合法。');
              seen.add(entry.credential);
              const index = fields.findIndex(field => field.credential === entry.credential);
              if (index === -1) throw new PublicError('提交了页面之外的凭据。');
              const { credential, ...payload } = entry;
              return { index, payload };
            });
            // 所有格式、替换授权和版本先验证；系统存储不提供跨项事务。
            await Promise.all([
              ...entries.map(entry => stores[entry.index].validate(entry.payload)),
              ...fields.map(async (field, index) => {
                if (!seen.has(field.credential) && !(await stores[index].status()).configured)
                  throw new PublicError('请填写所有尚未配置的密钥。');
              }),
            ]);
            const results: { credential: string; status: string }[] = [];
            let failed = false;
            for (const entry of entries) {
              let status = 'not_attempted';
              if (!failed) {
                try { await stores[entry.index].save(entry.payload); status = 'saved'; }
                catch { status = 'failed'; failed = true; }
              }
              results.push({ credential: fields[entry.index].credential, status });
            }
            result = { ...identity, status: failed ? 'partial' : 'saved', results };
          }
          outcome = result.status;
          lastResult = result;
          json(res, 200, result);
          options.onComplete?.(result);
          if (outcome === 'saved') { completedTimer = setTimeout(close, 90_000); completedTimer.unref(); }
          return;
        } finally { saving = false; }
      }
      if (url.pathname === '/api/cancel' && req.method === 'POST') {
        if (!['waiting', 'partial'].includes(outcome) || saving) throw new PublicError('配置正在保存或已结束。', 409);
        outcome = 'cancelled'; json(res, 200, { status: outcome });
        options.onComplete?.({ ...identity, status: outcome });
        completedTimer = setTimeout(close, 500); completedTimer.unref(); return;
      }
      throw new PublicError('接口不存在。', 404);
    } catch (error) {
      if (!res.headersSent) json(res, error instanceof PublicError ? error.status : 500,
        { error: error instanceof PublicError ? error.message : '操作未完成，请检查系统凭据服务。' });
      else res.end();
    }
  });
  server.requestTimeout = 15_000;
  server.headersTimeout = 10_000;
  server.maxHeadersCount = 30;
  await new Promise<void>((resolve, reject) => { server.once('error', reject); server.listen(options.port ?? 0, '127.0.0.1', () => resolve()); });
  const addr = server.address();
  if (!addr || typeof addr === 'string') throw new Error('无法启动本机服务。');
  origin = `http://127.0.0.1:${addr.port}`;
  const expiry = setTimeout(() => {
    if (['waiting', 'partial'].includes(outcome)) options.onComplete?.({ ...identity, status: 'expired', result: lastResult });
    close();
  }, options.ttlMs ?? 30 * 60_000);
  expiry.unref();
  function close() { clearTimeout(expiry); clearTimeout(completedTimer); server.close(); server.closeAllConnections(); }
  return { origin, url: `${origin}/#${bootstrap}`, bootstrap, close };
}

async function main() {
  const args = process.argv.slice(2);
  const manifestFiles: string[] = [];
  let pageFile: string | undefined;
  let port = 0;
  for (let i = 0; i < args.length; i++) {
    if (args[i] === '--manifest' && args[i + 1]) manifestFiles.push(path.resolve(args[++i]));
    else if (args[i] === '--page' && args[i + 1] && !pageFile) pageFile = path.resolve(args[++i]);
    else if (args[i] === '--port' && /^\d+$/.test(args[i + 1] ?? '')) port = Number(args[++i]);
    else throw new PublicError('用法：npm start -- [--manifest 声明路径（可重复） | --page 页面配置] [--port 端口]');
  }
  if (port > 65535) throw new PublicError('端口不合法。');
  if (pageFile && manifestFiles.length) throw new PublicError('--page 与 --manifest 不能同时使用。');
  const page = pageFile ? await loadPage(pageFile) : {
    manifests: await Promise.all((manifestFiles.length ? manifestFiles : [path.join(root, 'manifests', 'default.json')]).map(loadManifest))
  };
  const app = await startServer({ ...page, port,
    onComplete: result => process.stdout.write(JSON.stringify(result) + '\n') });
  process.stdout.write(`本机配置页面（30 分钟内有效）：\n${app.url}\n`);
  process.once('SIGINT', app.close); process.once('SIGTERM', app.close);
}
if (process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url) {
  main().catch(() => { process.stderr.write('启动失败，请检查 Node.js 版本、声明文件和端口。\n'); process.exitCode = 1; });
}
```

## File: scripts/credential-ui/tests/configure.test.ts
size: 2532
sha: 7ec84a3f573eff2e7884b40dd238c44c0bb8dabd
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/tests/configure.test.ts

```text
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { execFile } from 'node:child_process';
import { fileURLToPath } from 'node:url';

const script = fileURLToPath(new URL('../src/cli.ts', import.meta.url));
const run = (args: string[]) => new Promise<{ code: number; output: string }>(resolve => {
  execFile(process.execPath, [script, 'configure', ...args], { encoding: 'utf8' },
    (error, stdout, stderr) => resolve({ code: error ? 1 : 0, output: stdout + stderr }));
});
test('真实 CLI：创建、局部修改、幂等与只读预览', async t => {
  const dir = await mkdtemp(path.join(tmpdir(), 'credential-configure-')); t.after(() => rm(dir, { recursive: true, force: true }));
  const file = path.join(dir, 'service.credential.json');
  const create = ['--manifest', file, '--id', 'sample-skill', '--label', '服务凭据', '--credential', 'sample/service/default'];
  assert.equal((await run(create)).code, 0);
  const first = await readFile(file, 'utf8');
  assert.equal((await run(create)).code, 0); assert.equal(await readFile(file, 'utf8'), first);
  assert.equal((await run(['--manifest', file, '--title', '连接服务', '--placeholder', '输入访问凭据'])).code, 0);
  const updated = JSON.parse(await readFile(file, 'utf8'));
  assert.equal(updated.credential, 'sample/service/default'); assert.equal(updated.ui.title, '连接服务');
  const before = await readFile(file, 'utf8');
  assert.equal((await run(['--manifest', file, '--label', '预览', '--dry-run'])).code, 0);
  assert.equal(await readFile(file, 'utf8'), before);
});
test('真实 CLI：拒绝更换已有身份、未知字段和不完整声明', async t => {
  const dir = await mkdtemp(path.join(tmpdir(), 'credential-configure-')); t.after(() => rm(dir, { recursive: true, force: true }));
  const file = path.join(dir, 'service.credential.json');
  await run(['--manifest', file, '--id', 'sample-skill', '--label', '服务凭据', '--credential', 'sample/service/default']);
  const before = await readFile(file, 'utf8');
  assert.equal((await run(['--manifest', file, '--credential', 'other/account'])).code, 1);
  assert.equal((await run(['--manifest', file, '--api-key', 'FAKE_VALUE_FOR_TEST_ONLY'])).code, 1);
  assert.equal(await readFile(file, 'utf8'), before);
  assert.equal((await run(['--manifest', path.join(dir, 'incomplete.json'), '--label', '缺字段'])).code, 1);
});
```

## File: scripts/credential-ui/tests/credentials.test.ts
size: 6595
sha: a491230a2592f537135b1c25d018c5d3a3d73062
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/tests/credentials.test.ts

```text
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { request as httpRequest } from 'node:http';
import { fileURLToPath } from 'node:url';
import { readFile } from 'node:fs/promises';
import { createStore, loadManifest, type CredentialBackend } from '../src/config.ts';
import { startServer } from '../src/server.ts';

const manifest = await loadManifest(fileURLToPath(new URL('../manifests/default.json', import.meta.url)));
const fake = 'TEST_ONLY_NOT_A_REAL_SECRET_12345';
test('通用页面默认使用中性色，不引入未经配置的品牌色', async () => {
  const css = await readFile(new URL('../public/style.css', import.meta.url), 'utf8');
  for (const match of css.matchAll(/#([0-9a-f]{6})(?:[0-9a-f]{2})?\b/gi)) {
    const color = match[1];
    assert.equal(color.slice(0, 2), color.slice(2, 4));
    assert.equal(color.slice(2, 4), color.slice(4, 6));
  }
});
function memory(initial?: string) {
  let value = initial;
  let writes = 0;
  const backend: CredentialBackend = { name: '测试凭据库', get: async () => value,
    set: async v => { value = v; writes++; }, delete: async () => { value = undefined; } };
  return { backend, value: () => value, writes: () => writes };
}
test('首次保存只写入凭据后端；状态与结果不包含密钥', async () => {
  const m = memory();
  const store = createStore(manifest, m.backend);
  const before = await store.status();
  assert.equal(before.configured, false);
  const saved = await store.save({ revision: before.revision, value: fake });
  assert.equal(m.value(), fake);
  const after = await store.status();
  assert.equal(after.configured, true);
  assert.equal(JSON.stringify({ saved, after }).includes(fake), false);
  assert.equal('target' in after, false);
});
test('已有值需要确认替换，旧版本请求不能覆盖新值', async () => {
  const m = memory('TEST_OLD');
  const store = createStore(manifest, m.backend);
  const before = await store.status();
  await assert.rejects(store.save({ revision: before.revision, value: fake }), /确认替换/);
  assert.equal(m.writes(), 0);
  await store.save({ revision: before.revision, value: fake, replaceExisting: true });
  await assert.rejects(store.save({ revision: before.revision, value: 'TEST_STALE', replaceExisting: true }), /发生变化/);
  assert.equal(m.value(), fake);
});
test('凭据服务不可用时明确失败，不回退文件，不泄漏底层错误', async () => {
  const bad: CredentialBackend = { name: '不可用', get: async () => { throw Error(fake); },
    set: async () => { throw Error(fake); }, delete: async () => {} };
  await assert.rejects(createStore(manifest, bad).status(), e => e instanceof Error && !e.message.includes(fake) && /系统凭据/.test(e.message));
  const m = memory(); m.backend.set = async () => { throw Error(fake); };
  const store = createStore(manifest, m.backend);
  await assert.rejects(store.save({ revision: (await store.status()).revision, value: fake }), e => e instanceof Error && !e.message.includes(fake));
});
test('拒绝路径、旧 JSON 请求、空值、多行及超长密钥', async () => {
  const m = memory(); const store = createStore(manifest, m.backend);
  const revision = (await store.status()).revision;
  for (const input of [{ revision, value: fake, target: '/tmp/unwanted.json' },
    { revision, values: { api_key: fake } }, { revision, value: '' },
    { revision, value: 'one\ntwo' }, { revision, value: 'x'.repeat(2501) }])
    await assert.rejects(store.save(input));
  assert.equal(m.writes(), 0);
});
test('HTTP 认证、Host 和跨站保护、脱敏及默认单字段占位框', async t => {
  const m = memory(); const emitted: object[] = [];
  const app = await startServer({ manifest, backend: m.backend, onComplete: v => emitted.push(v) });
  t.after(app.close);
  assert.equal((await fetch(app.origin + '/api/meta')).status, 401);
  const wrongHost = await new Promise<number | undefined>((resolve, reject) => {
    const req = httpRequest(app.origin, { headers: { Host: 'attacker.example' } }, res => { res.resume(); resolve(res.statusCode); });
    req.on('error', reject); req.end();
  });
  assert.equal(wrongHost, 403);
  const html = await fetch(app.origin);
  assert.match(html.headers.get('Content-Security-Policy')!, /frame-ancestors 'none'/);
  assert.equal((await html.text()).match(/<input\b/g)?.length, 1);
  const headers: Record<string, string> = { Origin: app.origin, 'X-Local-Request': '1', 'Content-Type': 'application/json', Authorization: 'Bearer ' + app.bootstrap };
  const auth = await fetch(app.origin + '/api/session', { method: 'POST', headers, body: '{}' });
  assert.equal(auth.status, 200); headers.Cookie = auth.headers.get('set-cookie')!.split(';')[0];
  const meta = await (await fetch(app.origin + '/api/meta', { headers })).json();
  assert.equal(meta.label, manifest.label);
  assert.deepEqual(meta.ui, manifest.ui);
  const payload = { revision: meta.revision, value: fake };
  const post = (extras: Record<string, string>) => fetch(app.origin + '/api/save', { method: 'POST', headers: { ...headers, ...extras }, body: JSON.stringify(payload) });
  assert.equal((await post({ Origin: 'https://attacker.example' })).status, 403);
  assert.equal((await post({ 'X-Local-Request': '' })).status, 403);
  const result = await post({}); assert.equal(result.status, 200);
  const visible = [await result.text(), JSON.stringify(emitted)];
  visible.push(await (await fetch(app.origin + '/api/meta', { headers })).text());
  const agent = await (await fetch(app.origin + '/agent/status', { headers })).json();
  assert.equal(agent.status, 'saved'); visible.push(JSON.stringify(agent));
  assert.equal(visible.some(v => v.includes(fake)), false);
  assert.equal((await post({})).status, 409); assert.equal(m.writes(), 1);
});
test('取消不写凭据，取消后不能再保存', async t => {
  const m = memory(); const app = await startServer({ manifest, backend: m.backend }); t.after(app.close);
  const headers: Record<string, string> = { Origin: app.origin, 'X-Local-Request': '1', 'Content-Type': 'application/json', Authorization: 'Bearer ' + app.bootstrap };
  const auth = await fetch(app.origin + '/api/session', { method: 'POST', headers, body: '{}' });
  headers.Cookie = auth.headers.get('set-cookie')!.split(';')[0];
  assert.equal((await fetch(app.origin + '/api/cancel', { method: 'POST', headers, body: '{}' })).status, 200);
  assert.equal((await fetch(app.origin + '/api/save', { method: 'POST', headers, body: '{}' })).status, 409);
  assert.equal(m.writes(), 0);
});
```

## File: scripts/credential-ui/tests/multi-key.test.ts
size: 9884
sha: 39682e525d1f61dfaaad9a892f1105f45b9b9fa6
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/tests/multi-key.test.ts

```text
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { createStore, type CredentialBackend, type Manifest } from '../src/config.ts';
import { startServer } from '../src/server.ts';

const manifest = (name: string): Manifest => ({ version: 1, id: 'sample-skill', label: name, credential: 'sample-skill/' + name });
function memory() {
  const values = new Map<string, string>();
  const backend = (ref: string): CredentialBackend => ({
    name: '测试凭据库', get: async () => values.get(ref),
    set: async value => { values.set(ref, value); }, delete: async () => { values.delete(ref); }
  });
  return { values, backend };
}
test('同一个 Skill 的多个 key 独立保存、替换和删除', async () => {
  const m = memory(), a = manifest('first'), b = manifest('second');
  const sa = createStore(a, m.backend(a.credential)), sb = createStore(b, m.backend(b.credential));
  await sa.save({ value: 'FAKE_FIRST_VALUE', revision: (await sa.status()).revision });
  await sb.save({ value: 'FAKE_SECOND_VALUE', revision: (await sb.status()).revision });
  await sa.save({ value: 'FAKE_REPLACED_VALUE', revision: (await sa.status()).revision, replaceExisting: true });
  assert.equal(m.values.get(b.credential), 'FAKE_SECOND_VALUE');
  await m.backend(a.credential).delete();
  assert.equal((await sa.status()).configured, false); assert.equal((await sb.status()).configured, true);
});
test('多个端口共享浏览器 cookie 容器时，会话仍互不覆盖', async t => {
  const m = memory(), a = manifest('first'), b = manifest('second');
  const one = await startServer({ manifest: a, backend: m.backend(a.credential) });
  const two = await startServer({ manifest: b, backend: m.backend(b.credential) });
  t.after(one.close); t.after(two.close);
  const jar = new Map<string, string>();
  for (const app of [one, two]) {
    const auth = await fetch(app.origin + '/api/session', { method: 'POST',
      headers: { Origin: app.origin, Authorization: 'Bearer ' + app.bootstrap, 'X-Local-Request': '1' } });
    assert.equal(auth.status, 200);
    const cookie = auth.headers.get('set-cookie')!.split(';')[0], split = cookie.indexOf('=');
    jar.set(cookie.slice(0, split), cookie.slice(split + 1));
  }
  assert.equal(jar.size, 2);
  const cookie = [...jar].map(([k, v]) => k + '=' + v).join('; ');
  for (const [app, ref, value] of [[one, a.credential, 'FAKE_FIRST_VALUE'], [two, b.credential, 'FAKE_SECOND_VALUE']] as const) {
    const headers = { Cookie: cookie, Origin: app.origin, 'X-Local-Request': '1', 'Content-Type': 'application/json' };
    const response = await fetch(app.origin + '/api/meta', { headers }); assert.equal(response.status, 200);
    const meta = await response.json();
    const saved = await fetch(app.origin + '/api/save', { method: 'POST', headers, body: JSON.stringify({ revision: meta.revision, value }) });
    assert.equal(saved.status, 200);
    const status = await (await fetch(app.origin + '/agent/status', { headers: { Authorization: 'Bearer ' + app.bootstrap } })).json();
    assert.equal(status.credential, ref); assert.equal(status.status, 'saved');
  }
  assert.equal(m.values.size, 2);
  assert.equal((await fetch(one.origin + '/agent/status', { headers: { Authorization: 'Bearer ' + two.bootstrap } })).status, 401);
});
test('同一凭据的旧会话在其他会话保存后不能覆盖', async () => {
  const m = memory(), a = manifest('shared');
  const first = createStore(a, m.backend(a.credential)), second = createStore(a, m.backend(a.credential));
  const initial = await second.status();
  await first.save({ revision: (await first.status()).revision, value: 'FAKE_LATEST_VALUE' });
  await assert.rejects(second.save({ revision: initial.revision, value: 'FAKE_STALE_VALUE', replaceExisting: true }), /发生变化/);
  assert.equal(m.values.get(a.credential), 'FAKE_LATEST_VALUE');
});

async function session(app: Awaited<ReturnType<typeof startServer>>) {
  const headers: Record<string, string> = { Origin: app.origin, Authorization: 'Bearer ' + app.bootstrap,
    'X-Local-Request': '1', 'Content-Type': 'application/json' };
  const auth = await fetch(app.origin + '/api/session', { method: 'POST', headers });
  headers.Cookie = auth.headers.get('set-cookie')!.split(';')[0];
  return {
    meta: async () => (await fetch(app.origin + '/api/meta', { headers })).json(),
    save: (entries: object[]) => fetch(app.origin + '/api/save', { method: 'POST', headers, body: JSON.stringify({ entries }) }),
    agent: async () => (await fetch(app.origin + '/agent/status', { headers })).json(),
  };
}
test('同页多 key 真实 HTTP 保存、文案与状态脱敏', async t => {
  const m = memory(), fields = [manifest('one'), manifest('two')], emitted: object[] = [];
  const app = await startServer({ manifests: fields, backends: fields.map(field => m.backend(field.credential)),
    ui: { title: '连接服务', label: '双服务配置', saveLabel: '确认保存' }, onComplete: value => emitted.push(value) });
  t.after(app.close); const client = await session(app); const meta = await client.meta();
  assert.equal(meta.fields.length, 2); assert.equal(meta.page.title, '连接服务');
  const response = await client.save(meta.fields.map((field: any, index: number) => ({ credential: field.credential, revision: field.revision, value: 'FAKE_BATCH_' + index })));
  assert.equal(response.status, 200); const result = await response.json(); assert.equal(result.status, 'saved');
  assert.equal(m.values.get(fields[0].credential), 'FAKE_BATCH_0'); assert.equal(m.values.get(fields[1].credential), 'FAKE_BATCH_1');
  assert.equal(JSON.stringify([result, await client.meta(), await client.agent(), emitted]).includes('FAKE_BATCH_'), false);
});
test('整组预检拒绝无效项、重复项、越界引用、未确认替换和缺失项，零写入', async t => {
  const m = memory(), fields = [manifest('one'), manifest('two')];
  m.values.set(fields[0].credential, 'FAKE_OLD');
  const app = await startServer({ manifests: fields, backends: fields.map(field => m.backend(field.credential)) });
  t.after(app.close); const client = await session(app); const meta = await client.meta();
  const entries = meta.fields.map((field: any) => ({ credential: field.credential, revision: field.revision, value: 'FAKE_NEW', replaceExisting: true }));
  for (const invalid of [
    [entries[0]], [entries[0], { ...entries[1], value: 'multi\nline' }],
    [entries[0], entries[0]], [entries[0], { ...entries[1], credential: 'not/in/page' }],
    [{ ...entries[0], replaceExisting: false }, entries[1]],
    [entries[0], { ...entries[1], revision: 'stale' }],
    [entries[0], { ...entries[1], target: '/tmp/plaintext.json' }],
  ]) { assert.ok((await client.save(invalid)).status >= 400); assert.deepEqual([...m.values], [[fields[0].credential, 'FAKE_OLD']]); }
});
test('已有项留空不覆盖，中途失败保留已保存项并可仅重试失败项', async t => {
  const m = memory(), fields = [manifest('one'), manifest('two'), manifest('three'), manifest('four')];
  m.values.set(fields[0].credential, 'FAKE_KEEP');
  const backends = fields.map(field => m.backend(field.credential));
  let fail = true; const original = backends[2].set;
  backends[2].set = async value => { if (fail) throw Error(value); await original(value); };
  const app = await startServer({ manifests: fields, backends }); t.after(app.close);
  const client = await session(app); let meta = await client.meta();
  const response = await client.save(meta.fields.slice(1).map((field: any) => ({ credential: field.credential, revision: field.revision, value: 'FAKE_BATCH' })));
  const result = await response.json(); assert.equal(result.status, 'partial');
  assert.deepEqual(result.results.map((item: any) => item.status), ['saved', 'failed', 'not_attempted']);
  assert.equal(m.values.has(fields[3].credential), false);
  assert.equal((await client.agent()).status, 'partial'); assert.equal(JSON.stringify(result).includes('FAKE_BATCH'), false);
  assert.equal(m.values.get(fields[0].credential), 'FAKE_KEEP'); assert.equal(m.values.get(fields[1].credential), 'FAKE_BATCH');
  fail = false; meta = await client.meta();
  const retry = await client.save(meta.fields.slice(2).map((field: any) => ({ credential: field.credential, revision: field.revision, value: 'FAKE_RETRY' })));
  assert.equal((await retry.json()).status, 'saved'); assert.equal(m.values.get(fields[1].credential), 'FAKE_BATCH');
});
test('16 项预检并行读取，写入仍顺序执行且每项写前复验', async t => {
  const fields = Array.from({ length: 16 }, (_, index) => manifest('key-' + index));
  let active = 0, peak = 0, reads = 0, writes = 0;
  const backends = fields.map((): CredentialBackend => ({ name: '测试凭据库',
    get: async () => {
      reads++; active++; peak = Math.max(peak, active);
      await new Promise(resolve => setTimeout(resolve, 2)); active--; return undefined;
    },
    set: async () => { assert.equal(active, 0); writes++; }, delete: async () => {},
  }));
  const app = await startServer({ manifests: fields, backends }); t.after(app.close);
  const client = await session(app); const meta = await client.meta();
  peak = 0; reads = 0;
  const response = await client.save(meta.fields.map((field: any) => ({ credential: field.credential, revision: field.revision, value: 'FAKE_ONLY' })));
  assert.equal((await response.json()).status, 'saved');
  assert.equal(peak, 16); assert.equal(reads, 32); assert.equal(writes, 16);
});
test('页面拒绝重复引用、超限字段和空配置', async () => {
  const m = memory(), field = manifest('one');
  for (const fields of [[], [field, field], Array.from({ length: 17 }, (_, index) => manifest('key-' + index))])
    await assert.rejects(startServer({ manifests: fields, backends: fields.map(item => m.backend(item.credential)) }));
});
```

## File: scripts/credential-ui/tests/native-smoke.ts
size: 4166
sha: 0a9f5c15ff6ac36a369c97fb8aac928c624257aa
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/tests/native-smoke.ts

```text
import { randomUUID } from 'node:crypto';
import { mkdtemp, writeFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { execFile } from 'node:child_process';
import { nativeBackend, type CredentialBackend } from '../src/config.ts';
import { startServer } from '../src/server.ts';

const namespace = 'test/' + randomUUID();
const refs = [namespace + '/first', namespace + '/second'];
const entries: { backend: CredentialBackend; owned: boolean }[] = [];
const directory = await mkdtemp(path.join(tmpdir(), 'credential-native-'));
let phase = '初始化';
let cleanupFailed = false;
let app: Awaited<ReturnType<typeof startServer>> | undefined;
try {
  for (const ref of refs) {
    const backend = await nativeBackend(ref);
    if (await backend.get() !== undefined) throw Error();
    entries.push({ backend, owned: false });
  }
  const values = ['TEST_ONLY_A_' + randomUUID(), 'TEST_ONLY_B_' + randomUUID()];
  phase = '同页 HTTP 多 key 保存与回读';
  app = await startServer({ manifests: refs.map((credential, index) => ({ version: 1, id: 'sample-skill', label: '测试服务' + index, credential })) });
  const headers: Record<string, string> = { Origin: app.origin, Authorization: 'Bearer ' + app.bootstrap, 'X-Local-Request': '1', 'Content-Type': 'application/json' };
  const session = await fetch(app.origin + '/api/session', { method: 'POST', headers });
  headers.Cookie = session.headers.get('set-cookie')!.split(';')[0];
  const metadata = await (await fetch(app.origin + '/api/meta', { headers })).json();
  entries.forEach(entry => { entry.owned = true; });
  const saved = await fetch(app.origin + '/api/save', { method: 'POST', headers, body: JSON.stringify({
    entries: metadata.fields.map((field: { credential: string; revision: string }, index: number) => ({ credential: field.credential, revision: field.revision, value: values[index] }))
  }) });
  if (!saved.ok || (await saved.json()).status !== 'saved') throw Error();
  for (let i = 0; i < entries.length; i++) if (await entries[i].backend.get() !== values[i]) throw Error();
  phase = '替换隔离';
  values[0] = 'TEST_ONLY_A_REPLACED_' + randomUUID();
  await entries[0].backend.set(values[0]);
  if (await entries[1].backend.get() !== values[1]) throw Error();
  phase = '多 key 业务读取';
  const files = [path.join(directory, 'first.json'), path.join(directory, 'second.json')];
  for (let i = 0; i < files.length; i++)
    await writeFile(files[i], JSON.stringify({ version: 1, id: 'sample-skill', label: '测试服务', credential: refs[i] }));
  const script = fileURLToPath(new URL('../src/run.ts', import.meta.url));
  await new Promise<void>((resolve, reject) => execFile(process.execPath, [script,
    '--manifest', files[0], '--env', 'FIRST_API_KEY', '--manifest', files[1], '--env', 'SECOND_API_KEY', '--',
    process.execPath, '-e', 'process.exit(process.env.FIRST_API_KEY?.startsWith("TEST_ONLY_A_REPLACED_") && process.env.SECOND_API_KEY?.startsWith("TEST_ONLY_B_") ? 0 : 1)'],
    { timeout: 20_000 }, error => error ? reject(Error()) : resolve()));
  phase = '删除隔离';
  await entries[0].backend.delete();
  if (await entries[0].backend.get() !== undefined || await entries[1].backend.get() !== values[1]) throw Error();
  process.stdout.write('系统凭据库多 key 保存、替换隔离、业务读取和删除隔离验证通过（假凭据）。\n');
} catch {
  process.stderr.write('系统凭据库验证未通过，阶段：' + phase + '。\n'); process.exitCode = 1;
} finally {
  app?.close();
  for (const entry of entries) {
    if (!entry.owned) continue;
    try {
      if (await entry.backend.get() !== undefined) await entry.backend.delete();
      if (await entry.backend.get() !== undefined) cleanupFailed = true;
    } catch { cleanupFailed = true; }
  }
  await rm(directory, { recursive: true, force: true });
  if (cleanupFailed) {
    process.stderr.write('测试凭据清理失败，测试引用前缀：' + namespace + '\n'); process.exitCode = 1;
  } else process.stdout.write('测试凭据和临时声明已清理。\n');
}
```

## File: scripts/credential-ui/tests/page.test.ts
size: 2053
sha: 0ef1c94368600d0ac37eaad4b78d6f455be2286e
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/tests/page.test.ts

```text
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { execFile } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { loadPage } from '../src/page.ts';

test('页面配置真实 CLI：相对路径、独立字段文案、更新与只读预览', async t => {
  const dir = await mkdtemp(path.join(tmpdir(), 'credential-page-')); t.after(() => rm(dir, { recursive: true, force: true }));
  const files = ['one', 'two'].map(name => path.join(dir, name + '.json'));
  for (const [index, file] of files.entries()) await writeFile(file, JSON.stringify({ version: 1, id: 'sample-skill', label: '服务' + index,
    credential: 'sample/' + index, ui: { placeholder: '请输入测试凭据' + index } }));
  const page = path.join(dir, 'page.json');
  const script = fileURLToPath(new URL('../src/cli.ts', import.meta.url));
  const run = (args: string[]) => new Promise<number>(resolve => execFile(process.execPath,
    [script, 'configure-page', '--page', page, ...args], error => resolve(error ? 1 : 0)));
  const args = ['--manifest', files[0], '--manifest', files[1], '--title', '两项凭据'];
  assert.equal(await run(args), 0);
  assert.deepEqual(JSON.parse(await readFile(page, 'utf8')).manifests, ['one.json', 'two.json']);
  const loaded = await loadPage(page); assert.equal(loaded.manifests.length, 2); assert.equal(loaded.ui.title, '两项凭据');
  assert.equal(loaded.manifests[1].ui?.placeholder, '请输入测试凭据1');
  assert.equal(await run(['--label', '业务配置']), 0);
  const before = await readFile(page, 'utf8');
  assert.equal(await run(['--title', '只读预览', '--dry-run']), 0); assert.equal(await readFile(page, 'utf8'), before);
  assert.notEqual(await run(['--manifest', files[0], '--manifest', files[0]]), 0);
  assert.notEqual(await run(['--api-key', 'FAKE_ONLY']), 0);
  assert.equal(await readFile(page, 'utf8'), before);
});
```

## File: scripts/credential-ui/tests/profile.test.ts
size: 4149
sha: cd9bf25ce0507f4d3dff9d561c13d359615e3704
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/tests/profile.test.ts

```text
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { mkdtemp, mkdir, writeFile, rm, readFile } from 'node:fs/promises';
import path from 'node:path';
import { tmpdir } from 'node:os';
import { fileURLToPath } from 'node:url';
import { loadProfile, prepareProfile, profileStatus } from '../src/profile.ts';
import { loadManifest, type CredentialBackend } from '../src/config.ts';
import { startServer } from '../src/server.ts';

test('真实分发配置：正式页面保存后可被对应业务环境读取，状态与参数不含值', async () => {
  const root = fileURLToPath(new URL('../', import.meta.url));
  const config = JSON.parse(await readFile(path.join(root, 'manifests/profiles.json'), 'utf8'));
  for (const name of Object.keys(config.profiles)) {
    const bindings = await loadProfile(name);
    const manifests = await Promise.all(bindings.map(b => loadManifest(b.manifest)));
    const values = new Map<string, string>();
    const backendFactory = async (ref: string): Promise<CredentialBackend> => ({
      name: 'fake', get: async () => values.get(ref),
      set: async value => { values.set(ref, value); }, delete: async () => { values.delete(ref); },
    });
    const app = await startServer({ manifests, backends: await Promise.all(manifests.map(m => backendFactory(m.credential))) });
    try {
      const headers: Record<string, string> = { Origin: app.origin, Authorization: 'Bearer ' + app.bootstrap, 'X-Local-Request': '1', 'Content-Type': 'application/json' };
      const session = await fetch(app.origin + '/api/session', { method: 'POST', headers });
      headers.Cookie = session.headers.get('set-cookie')!.split(';')[0];
      assert.equal((await fetch(app.origin)).status, 200);
      const meta = await (await fetch(app.origin + '/api/meta', { headers })).json();
      const saved = await fetch(app.origin + '/api/save', { method: 'POST', headers, body: JSON.stringify({ entries: meta.fields.map((f: { credential: string; revision: string }, i: number) => ({ credential: f.credential, revision: f.revision, value: 'TEST_ONLY_PROFILE_' + i })) }) });
      assert.equal((await saved.json()).status, 'saved');
      const status = await profileStatus(bindings, {}, async ref => values.get(ref));
      assert.equal(status.configured, true);
      assert.equal(JSON.stringify(status).includes('TEST_ONLY'), false);
      const plan = await prepareProfile(bindings, ['business-program', '--input', 'a b'], {}, async ref => values.get(ref));
      for (const b of bindings) assert.match(plan.env[b.env]!, /^TEST_ONLY_PROFILE_/);
      assert.equal(JSON.stringify(plan.args).includes('TEST_ONLY'), false);
      assert.deepEqual(plan.args, ['--input', 'a b']);
    } finally { app.close(); }
  }
});

test('已有环境凭据无需读取系统库；缺失或后端失败时不启动业务', async () => {
  const bindings = await loadProfile('default');
  const env = Object.fromEntries(bindings.map(b => [b.env, 'TEST_ONLY_ENV']));
  const noRead = async () => { throw Error('TEST_ONLY_FAILURE'); };
  assert.equal((await profileStatus(bindings, env, noRead)).configured, true);
  assert.equal((await prepareProfile(bindings, ['business'], env, noRead)).env[bindings[0].env], 'TEST_ONLY_ENV');
  await assert.rejects(prepareProfile(bindings, ['business'], {}, async () => undefined), /未配置/);
  await assert.rejects(prepareProfile(bindings, ['business'], {}, noRead), error => error instanceof Error && !error.message.includes('TEST_ONLY'));
});

test('配置拒绝跨目录声明、危险变量与未知业务', async t => {
  const dir = await mkdtemp(path.join(tmpdir(), 'credential-profile-')); t.after(() => rm(dir, { recursive: true, force: true }));
  await mkdir(path.join(dir, 'manifests'));
  for (const binding of [{ manifest: '../outside.json', env: 'API_KEY' }, { manifest: 'default.json', env: 'NODE_OPTIONS' }]) {
    await writeFile(path.join(dir, 'manifests/profiles.json'), JSON.stringify({ version: 1, profiles: { default: [binding] } }));
    await assert.rejects(loadProfile('default', dir));
  }
  await assert.rejects(loadProfile('unknown', dir));
});
```

## File: scripts/credential-ui/tests/run.test.ts
size: 2799
sha: c5bccd621a4fd748613f3581429bcd10a34d534f
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/tests/run.test.ts

```text
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { mkdtemp, writeFile, rm } from 'node:fs/promises';
import path from 'node:path';
import { tmpdir } from 'node:os';
import { execFile } from 'node:child_process';
import { parseBindings, prepareCommand } from '../src/run.ts';

async function fixture() {
  const dir = await mkdtemp(path.join(tmpdir(), 'credential-run-'));
  const files = [path.join(dir, 'first.json'), path.join(dir, 'second.json')];
  await Promise.all(files.map((file, i) => writeFile(file, JSON.stringify({ version: 1, id: 'sample-skill', label: '服务', credential: 'sample/key-' + i }))));
  return { dir, files, cleanup: () => rm(dir, { recursive: true, force: true }) };
}
test('多个 key 同时注入一个真实子进程，命令参数不包含值', async t => {
  const f = await fixture(); t.after(f.cleanup);
  const plan = await prepareCommand(['--manifest', f.files[0], '--env', 'FIRST_API_KEY', '--manifest', f.files[1], '--env', 'SECOND_API_KEY', '--',
    process.execPath, '-e', 'process.exit(process.env.FIRST_API_KEY && process.env.SECOND_API_KEY && process.env.FIRST_API_KEY !== process.env.SECOND_API_KEY ? 0 : 1)'],
    async ref => ref.endsWith('0') ? 'FAKE_FIRST_VALUE' : 'FAKE_SECOND_VALUE');
  assert.equal(plan.env.FIRST_API_KEY, 'FAKE_FIRST_VALUE'); assert.equal(plan.env.SECOND_API_KEY, 'FAKE_SECOND_VALUE');
  assert.equal(JSON.stringify(plan.args).includes('FAKE_'), false);
  await new Promise<void>((resolve, reject) => execFile(plan.command, plan.args, { env: plan.env }, error => error ? reject(error) : resolve()));
});
test('任一 key 缺失或后端失败，不返回可启动的命令，也不修改父环境', async t => {
  const f = await fixture(); t.after(f.cleanup);
  const args = ['--manifest', f.files[0], '--env', 'FIRST_API_KEY', '--manifest', f.files[1], '--env', 'SECOND_API_KEY', '--', 'unused'];
  const base = { KEEP: 'unchanged' };
  await assert.rejects(prepareCommand(args, async ref => ref.endsWith('0') ? 'FAKE_FIRST_VALUE' : undefined, base), /未配置/);
  await assert.rejects(prepareCommand(args, async () => { throw Error('FAKE_VALUE_MUST_NOT_LEAK'); }, base),
    error => error instanceof Error && !error.message.includes('FAKE_'));
  assert.deepEqual(base, { KEEP: 'unchanged' });
});
test('拒绝重复变量和不完整绑定，兼容单 key 的原入口', () => {
  assert.throws(() => parseBindings(['--env', 'DUP_KEY', '--env', 'DUP_KEY', '--', 'unused']), /重复/);
  assert.throws(() => parseBindings(['--manifest', 'a.json', '--manifest', 'b.json', '--env', 'A_KEY', '--', 'unused']));
  assert.throws(() => parseBindings(['--env', 'HOME', '--', 'unused']));
  assert.equal(parseBindings(['--env', 'SERVICE_API_KEY', '--', 'program', 'arg']).bindings.length, 1);
});
```

## File: scripts/credential-ui/tests/ui.test.ts
size: 5074
sha: 05d485581a1ff4f0170ec9d7c105c1f28064ccf8
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/tests/ui.test.ts

```text
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { runInNewContext } from 'node:vm';
import { readFile } from 'node:fs/promises';

// 运行实际构建产物的 DOM 契约测试，不启动浏览器，不接触真实凭据。
class Element {
  children: Element[] = [];
  value = ''; textContent = ''; hidden = false; disabled = false; type = ''; required = false; placeholder = '';
  className = ''; id = ''; htmlFor = '';
  listeners: Record<string, (event: object) => unknown> = {};
  classes = new Set<string>();
  classList = { toggle: (key: string, enabled: boolean) => enabled ? this.classes.add(key) : this.classes.delete(key) };
  append(...children: Element[]) { this.children.push(...children); }
  replaceChildren() { this.children = []; }
  setAttribute() {}
  addEventListener(event: string, callback: (event: object) => unknown) { this.listeners[event] = callback; }
}
async function harness(configured = false, fail = false) {
  const nodes = Object.fromEntries(['credential-form', 'fields', 'save', 'heading', 'context', 'hint', 'message'].map(key => [key, new Element()]));
  const fields = [0, 1].map(index => ({ id: 'sample', label: index ? '<img src=x>' : '语音服务', credential: 'sample/' + index,
    configured: index === 0 && configured, revision: 'revision-' + index, storage: '测试凭据库', ui: { placeholder: '测试输入' } }));
  const metadata = { fields, page: { title: '连接服务', label: '两个服务', saveLabel: '确认保存' }, outcome: 'waiting' };
  const submitted: any[] = [];
  const lifecycle: Record<string, () => void> = {};
  const context = { document: { getElementById: (id: string) => nodes[id], createElement: () => new Element(), title: '' },
    location: { hash: '', pathname: '/' }, history: { replaceState() {} }, AbortSignal,
    window: { addEventListener: (key: string, callback: () => void) => { lifecycle[key] = callback; } },
    fetch: async (url: string, options: any) => {
      if (url === '/api/meta') return { ok: true, json: async () => structuredClone(metadata) };
      assert.equal(url, '/api/save'); submitted.push(JSON.parse(options.body));
      if (fail) {
        metadata.fields[0].configured = true; metadata.outcome = 'partial';
        return { ok: true, json: async () => ({ status: 'partial', results: [{ credential: 'sample/0', status: 'saved' }, { credential: 'sample/1', status: 'failed' }] }) };
      }
      metadata.outcome = 'saved'; return { ok: true, json: async () => ({ status: 'saved' }) };
    } };
  runInNewContext(await readFile(new URL('../public/app.js', import.meta.url), 'utf8'), context);
  await new Promise(resolve => setImmediate(resolve));
  const inputs = () => nodes.fields.children.map(field => field.children[1]);
  const input = () => nodes['credential-form'].listeners.input({});
  const submit = () => nodes['credential-form'].listeners.submit({ preventDefault() {} });
  return { nodes, inputs, input, submit, submitted, lifecycle };
}
test('真实前端产物：配置生成两个密码框、纯文本标签、必填与成功清空', async () => {
  const h = await harness();
  assert.equal(h.inputs().length, 2); assert.ok(h.inputs().every(input => input.type === 'password' && input.required));
  assert.equal(h.nodes.fields.children[1].children[0].textContent, '<img src=x>');
  assert.equal(h.nodes.heading.textContent, '连接服务');
  h.inputs()[0].value = 'FAKE_ONE'; h.input(); assert.equal(h.nodes.save.disabled, true);
  h.inputs()[1].value = 'FAKE_TWO'; h.input(); assert.equal(h.nodes.save.disabled, false);
  await h.submit(); assert.equal(h.submitted[0].entries.length, 2);
  assert.ok(h.inputs().every(input => !input.value)); assert.equal(h.nodes['credential-form'].hidden, true);
});
test('真实前端产物：已有项留空保留，替换按钮明确，离开清空', async () => {
  const h = await harness(true);
  assert.equal(h.inputs()[0].required, false); assert.match(h.inputs()[0].placeholder, /留空保留/);
  h.inputs()[0].value = 'FAKE_REPLACE'; h.input(); assert.equal(h.nodes.save.textContent, '替换并保存');
  h.inputs()[0].value = ''; h.inputs()[1].value = 'FAKE_SECOND'; h.input();
  await h.submit(); assert.equal(h.submitted[0].entries.length, 1); assert.equal(h.submitted[0].entries[0].credential, 'sample/1');
  h.inputs()[0].value = 'FAKE_LEAVE'; h.lifecycle.pagehide(); assert.equal(h.inputs()[0].value, '');
});
test('真实前端产物：部分失败不显示全部保存，刷新状态并允许补填', async () => {
  const h = await harness(false, true);
  h.inputs().forEach(input => { input.value = 'FAKE_ONLY'; }); h.input(); await h.submit();
  assert.equal(h.nodes['credential-form'].hidden, false); assert.match(h.nodes.message.textContent, /未确认成功/);
  assert.ok(h.inputs().every(input => !input.value)); assert.equal(h.inputs()[0].required, false);
  assert.equal(h.inputs()[1].required, true); assert.equal(h.nodes.save.disabled, true);
  h.inputs()[1].value = 'FAKE_RETRY'; h.input(); assert.equal(h.nodes.save.disabled, false);
});
```

## File: scripts/credential-ui/tsconfig.json
size: 353
sha: a699072438601e76d5ddbddc1160ba21a26189b9
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/tsconfig.json

```text
{
  "compilerOptions": {
    "target": "ES2023",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "strict": true,
    "allowImportingTsExtensions": true,
    "noEmit": true,
    "types": ["node"],
    "lib": ["ES2023", "DOM", "DOM.Iterable"],
    "skipLibCheck": true
  },
  "include": ["src/**/*.ts", "web/**/*.ts", "tests/**/*.ts"]
}
```

## File: scripts/credential-ui/tsconfig.web.json
size: 237
sha: 2b1806626aa2b5f389346b86c3a311b020d5935c
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/tsconfig.web.json

```text
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ES2022",
    "lib": ["ES2022", "DOM", "DOM.Iterable"],
    "strict": true,
    "rootDir": "web",
    "outDir": "public",
    "types": []
  },
  "include": ["web/**/*.ts"]
}
```

## File: scripts/credential-ui/web/app.ts
size: 6438
sha: c1f0bdc364885ed5b185f1c2a135f398508fb201
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/credential-ui/web/app.ts

```text
type Field = { id: string; label: string; credential: string; revision: string; configured: boolean; storage: string; ui?: { title?: string; placeholder?: string; saveLabel?: string } };
type Metadata = { fields: Field[]; page: { title?: string; label?: string; saveLabel?: string }; outcome: string };
type SaveResult = { status: string; results?: { credential: string; status: string }[] };
const get = <T extends HTMLElement = HTMLElement>(id: string) => document.getElementById(id) as T;
const form = get<HTMLFormElement>('credential-form');
const button = get<HTMLButtonElement>('save');
let inputs: HTMLInputElement[] = [];
let meta: Metadata;
let busy = false;
const saveLabel = () => inputs.some((input, index) => input.value.trim() && meta.fields[index].configured)
  ? '替换并保存' : (meta.page.saveLabel ?? (meta.fields.length === 1 ? meta.fields[0].ui?.saveLabel : undefined) ?? '保存');
async function request<T>(url: string, options: RequestInit = {}): Promise<T> {
  let response: Response;
  try {
    response = await fetch(url, { ...options, credentials: 'same-origin', cache: 'no-store',
      headers: { 'Content-Type': 'application/json', 'X-Local-Request': '1', ...options.headers }, signal: AbortSignal.timeout(25_000) });
  } catch { throw new Error('未收到服务回复，请刷新确认保存结果，不要重复提交。'); }
  const result = await response.json();
  if (!response.ok) throw new Error(result.error ?? '操作未完成，请重试。');
  return result as T;
}
function message(text: string) { const node = get('message'); node.textContent = text; node.hidden = false; }
function clearInputs() { inputs.forEach(input => { input.value = ''; }); }
function done() {
  clearInputs(); form.hidden = true; get('heading').textContent = '已保存';
  get('hint').hidden = true; message('可以关闭此页，回到对话继续。');
}
function update() {
  button.disabled = busy || !meta || !['waiting', 'partial'].includes(meta.outcome)
    || !inputs.some(input => input.value.trim())
    || inputs.some((input, index) => !meta.fields[index].configured && !input.value.trim());
  if (meta && !busy) button.textContent = saveLabel();
}
function render() {
  clearInputs(); inputs = [];
  const multi = meta.fields.length > 1;
  form.classList.toggle('multi', multi);
  const container = get('fields'); container.replaceChildren();
  meta.fields.forEach((field, index) => {
    const wrapper = document.createElement('div'); wrapper.className = 'field';
    const label = document.createElement('label'); label.htmlFor = 'secret-' + index; label.textContent = field.label;
    if (!multi) label.className = 'visually-hidden';
    if (field.configured) {
      const state = document.createElement('span'); state.className = 'field-state'; state.textContent = '已配置'; label.append(state);
    }
    const input = document.createElement('input'); input.id = label.htmlFor; input.type = 'password';
    input.autocomplete = 'new-password'; input.autocapitalize = 'off'; input.spellcheck = false; input.maxLength = 2500;
    input.required = !field.configured; input.setAttribute('aria-describedby', 'hint message');
    input.placeholder = field.configured ? '留空保留，输入则替换' : (field.ui?.placeholder ?? '粘贴 API Key');
    input.disabled = !['waiting', 'partial'].includes(meta.outcome);
    wrapper.append(label, input); container.append(wrapper); inputs.push(input);
  });
  get('context').textContent = meta.page.label ?? (multi ? meta.fields.length + ' 项凭据' : meta.fields[0].label);
  const title = meta.page.title ?? (multi ? '输入密钥' : meta.fields[0].ui?.title) ?? '输入密钥';
  get('heading').textContent = title; document.title = title;
  const storage = [...new Set(meta.fields.map(field => field.storage))].join('、');
  get('hint').textContent = '仅保存到' + storage + (meta.fields.some(field => field.configured) ? ' · 已配置项留空保留' : '');
  update();
  if (meta.outcome === 'saved') done();
  else if (meta.outcome === 'partial') message('上次仅部分保存。请核对已配置项，补填未完成项后重试。');
  else if (meta.outcome !== 'waiting') message('本次配置已结束，请重新打开入口。');
}
form.addEventListener('input', () => { update(); get('message').hidden = true; });
form.addEventListener('submit', async event => {
  event.preventDefault(); if (busy || button.disabled) return;
  busy = true; update(); inputs.forEach(input => { input.disabled = true; }); button.textContent = '正在保存…';
  try {
    const entries = inputs.flatMap((input, index) => input.value.trim() ? [{ credential: meta.fields[index].credential,
      value: input.value, revision: meta.fields[index].revision, replaceExisting: meta.fields[index].configured }] : []);
    const result = await request<SaveResult>('/api/save', { method: 'POST', body: JSON.stringify({ entries }) });
    if (result.status === 'saved') { meta.outcome = 'saved'; done(); }
    else {
      clearInputs(); meta = await request<Metadata>('/api/meta'); render();
      const statuses: Record<string, string> = { saved: '已保存', failed: '未确认成功', not_attempted: '未尝试' };
      message((result.results ?? []).map(item => (meta.fields.find(field => field.credential === item.credential)?.label ?? '凭据') + '：' + (statuses[item.status] ?? '请核对')).join('；')
        + '。请核对状态后重新填写未完成项。');
    }
  } catch (error) {
    clearInputs();
    try { meta = await request<Metadata>('/api/meta'); render(); }
    catch { meta.outcome = 'unknown'; }
    if (meta.outcome !== 'saved') message(error instanceof Error ? error.message : '保存未完成，请刷新确认结果。');
  } finally {
    clearInputs(); busy = false; inputs.forEach(input => { input.disabled = !['waiting', 'partial'].includes(meta.outcome); }); update();
  }
});
window.addEventListener('pagehide', clearInputs);
async function initialize() {
  const token = location.hash.slice(1);
  if (token) {
    history.replaceState(null, '', location.pathname);
    await request('/api/session', { method: 'POST', headers: { Authorization: 'Bearer ' + token }, body: '{}' });
  }
  meta = await request<Metadata>('/api/meta'); render();
}
initialize().catch(error => { get('context').textContent = '暂时无法连接'; message(error instanceof Error ? error.message : '请重新打开配置入口。'); });
```

## File: scripts/gen_image.py
size: 1425
sha: 6798e0577e2e8f8a2102d8b4783bfbde966de970
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/gen_image.py

```text
#!/usr/bin/env python3
"""External-API fallback provider: OpenAI Images (gpt-image).

Used only when the calling agent has no native image tool and Codex is not
available. For any other API (Replicate, Fal, Stability, …), call that API
directly instead — this script is just the ready-made OpenAI path.

  gen_image.py --prompt "<full sheet prompt>" --out raw/<style>.png

Reads OPENAI_API_KEY from the environment. No third-party deps (stdlib only).
"""
import argparse, base64, json, os, sys, urllib.request

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--prompt", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--model", default="gpt-image-1")
    ap.add_argument("--size", default="1024x1024")
    a = ap.parse_args()

    key = os.environ.get("OPENAI_API_KEY")
    if not key:
        sys.exit("OPENAI_API_KEY is not set")

    body = json.dumps({"model": a.model, "prompt": a.prompt, "size": a.size, "n": 1}).encode()
    req = urllib.request.Request(
        "https://api.openai.com/v1/images/generations",
        data=body,
        headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
    )
    with urllib.request.urlopen(req, timeout=300) as r:
        data = json.load(r)
    with open(a.out, "wb") as f:
        f.write(base64.b64decode(data["data"][0]["b64_json"]))
    print(a.out)

if __name__ == "__main__":
    main()
```

## File: scripts/setup.sh
size: 491
sha: c7e1c38c92772855a2d26eff28c00bfa6b7b2a07
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/setup.sh

```text
#!/bin/bash
# One-time setup: create the Python venv used by slice_icons.py
# (Pillow + numpy + scipy for slicing; rembg for soft/3D/photo cutout).
set -e
SK="$(cd "$(dirname "$0")/.." && pwd)"
VENV="$SK/.venv"
python3 -m venv "$VENV"
source "$VENV/bin/activate"
pip install --quiet --upgrade pip
pip install --quiet Pillow numpy scipy "rembg[cpu]"
echo "oil-icon venv ready: $VENV"
echo "slice with: $VENV/bin/python3 $SK/scripts/slice_icons.py <sheet>.png <outdir> --mode floodfill|rembg"
```

## File: scripts/slice_icons.py
size: 5573
sha: 95dd5948dfedcad902f488a67f8fd1aebe207784
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/scripts/slice_icons.py

```text
#!/usr/bin/env python3
"""图标切图器：4x4 分格 + 每格抠图 + 连通域清理，丢掉邻格漂进来的碎片。

关键：gpt-image 不会把图标摆在完美网格上，图标会上下左右漂。固定分格会把上一格
探进来的部分带进当前格。这里每格切完后做连通域分析：只保留【居中的主图标 + 紧挨
它的部件】，隔着间距的邻格碎片一律丢弃。

cutout 模式：
  floodfill —— 扁平图标 / 灰底，从边界连通域去背景（快、准）
  rembg     —— 软边 / 3D / 反光 / 照片，ML 抠图
"""
import sys, argparse
from pathlib import Path
import numpy as np
from PIL import Image
from scipy import ndimage

def floodfill_alpha(rgb, thresh, bg=(128, 128, 128)):
    """rgb: HxWx3 int。删掉所有接近灰底色的像素——包括图标内部被包围的镂空
    （放大镜镜片、齿轮中心、日历格子、锁孔），否则这些洞会残留灰底。
    背景基准用固定 #808080（我们生成时就固定这个灰），不逐格采样——避免大图标/
    带底色瓷砖的角落被误判成背景，从而把 cream 底当灰删掉。
    仅对『扁平图标 + 纯灰底』安全：这些风格的图标/瓷砖颜色都远离灰。"""
    bg = np.array(bg)
    diff = np.abs(rgb - bg).max(axis=2)
    return np.where(diff < thresh, 0, 255).astype(np.uint8)

def clean(alpha):
    """连通域清理：保留居中主图标 + 紧邻部件，丢掉邻格碎片和小杂点。"""
    mask = alpha > 40
    if not mask.any():
        return None
    labels, n = ndimage.label(mask)
    sizes = np.bincount(labels.ravel())
    sizes[0] = 0
    h, w = mask.shape
    cx, cy = w / 2.0, h / 2.0
    coms = ndimage.center_of_mass(mask, labels, range(1, n + 1))
    # 居中候选：质心落在中央 68% 框内
    cand = [l for l in range(1, n + 1)
            if abs(coms[l - 1][1] - cx) < 0.34 * w and abs(coms[l - 1][0] - cy) < 0.34 * h]
    if not cand:
        cand = [int(np.argmax(sizes))]
    main = max(cand, key=lambda l: sizes[l])
    slices = ndimage.find_objects(labels)
    mb = slices[main - 1]
    link = 0.05 * max(h, w)          # 与主体的间隙 < 5% 视为同一图标的部件
    min_area = 0.02 * sizes[main]     # 小于主体 2% 的当杂点丢掉
    keep = {main}
    for l in range(1, n + 1):
        if l == main or sizes[l] < min_area:
            continue
        b = slices[l - 1]
        dy = max(0, b[0].start - mb[0].stop, mb[0].start - b[0].stop)
        dx = max(0, b[1].start - mb[1].stop, mb[1].start - b[1].stop)
        if dy <= link and dx <= link:
            keep.add(l)
    out = alpha.copy()
    out[~np.isin(labels, list(keep))] = 0
    return out

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("sheet")
    ap.add_argument("outdir")
    ap.add_argument("--mode", choices=["floodfill", "rembg"], default="floodfill")
    ap.add_argument("--grid", type=int, default=4)
    ap.add_argument("--thresh", type=int, default=24)
    ap.add_argument("--size", type=int, default=512)
    ap.add_argument("--count", type=int, default=None,
                    help="number of real icons to export from row-major cells; later cells are intentional blanks")
    a = ap.parse_args()

    outdir = Path(a.outdir); outdir.mkdir(parents=True, exist_ok=True)
    im = Image.open(a.sheet).convert("RGB")
    W, H = im.size
    g = a.grid
    total_cells = g * g
    if a.count is not None and not (1 <= a.count <= total_cells):
        ap.error(f"--count must be between 1 and {total_cells}")
    cw, ch = W // g, H // g
    pad = int(0.06 * min(cw, ch))     # 略微外扩，兜住漂出格子的图标
    session = None
    if a.mode == "rembg":
        from rembg import new_session
        session = new_session("u2net")

    warned = []
    idx = 1
    for r in range(g):
        for c in range(g):
            if a.count is not None and idx > a.count:
                print(f"{a.sheet} -> {a.outdir}  mode={a.mode}  cells={idx-1}/{total_cells}  skipped_blank={total_cells - (idx - 1)}" + (f"  ⚠ {warned}" if warned else "  ✓"))
                return
            x0, y0 = c * cw, r * ch
            px0, py0 = max(0, x0 - pad), max(0, y0 - pad)
            px1, py1 = min(W, x0 + cw + pad), min(H, y0 + ch + pad)
            cell = im.crop((px0, py0, px1, py1))
            rgb = np.array(cell).astype(int)
            if a.mode == "floodfill":
                alpha = floodfill_alpha(rgb, a.thresh)
            else:
                from rembg import remove
                alpha = np.array(remove(cell, session=session).split()[-1])
            cleaned = clean(alpha)
            if cleaned is None or (cleaned > 0).sum() < 40:
                warned.append(f"{idx:02d}(空)")
                Image.new("RGBA", (a.size, a.size), (0, 0, 0, 0)).save(outdir / f"{idx:02d}.png")
                idx += 1
                continue
            ys, xs = np.where(cleaned > 0)
            rgba = np.dstack([rgb.astype(np.uint8), cleaned])[ys.min():ys.max() + 1, xs.min():xs.max() + 1]
            obj = Image.fromarray(rgba, "RGBA")
            side = int(max(obj.size) * 1.16)
            canvas = Image.new("RGBA", (side, side), (0, 0, 0, 0))
            canvas.paste(obj, ((side - obj.width) // 2, (side - obj.height) // 2), obj)
            canvas.resize((a.size, a.size), Image.LANCZOS).save(outdir / f"{idx:02d}.png")
            idx += 1
    print(f"{a.sheet} -> {a.outdir}  mode={a.mode}  cells={idx-1}" + (f"  ⚠ {warned}" if warned else "  ✓"))

if __name__ == "__main__":
    main()
```

## File: references/api-key-setup.md
size: 3888
sha: c4df57a09b854e0bf0496ae26aa7e797cdb7ec90
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/references/api-key-setup.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/references/api-key-setup.md

## File: assets/readme/made-with-beautify.svg
size: 1519
sha: f061062304cd2afcd7888808862136f5f491c684
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/made-with-beautify.svg

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/made-with-beautify.svg

## File: assets/readme/readme-hero.png
size: 488260
sha: 7faa502390b757d3c97cab488882db3dc93aa806
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/readme-hero.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/readme-hero.png

## File: assets/readme/readme-section-consistency.svg
size: 1420
sha: 32aa17db43a1754f8e1cb2862058782b042ecf2c
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/readme-section-consistency.svg

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/readme-section-consistency.svg

## File: assets/readme/readme-section-start.svg
size: 1358
sha: 4ba871e3190e77500e87c4c55d385d16782e4e0d
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/readme-section-start.svg

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/readme-section-start.svg

## File: assets/readme/readme-section-styles.svg
size: 1298
sha: 9bb1f50e7d99e536276f56cb70357fef54e00b35
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/readme-section-styles.svg

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/readme-section-styles.svg

## File: assets/readme/readme-section-what.svg
size: 1359
sha: d5dcfe6fff72cf459ca94b6de8b161fab2ae7aba
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/readme-section-what.svg

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/readme-section-what.svg

## File: assets/readme/readme-section-workflow.svg
size: 1451
sha: 74d429dc5f32d7fe5229b52c1257f5f2a18fe708
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/readme-section-workflow.svg

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/readme-section-workflow.svg

## File: assets/readme/showcase-isometric/01.png
size: 154135
sha: f58c3c8b6ab9f62b00718d6a65b1226bf55fadfd
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/01.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/01.png

## File: assets/readme/showcase-isometric/02.png
size: 171550
sha: a3150c613af48cd7bffb907c11546d95a5c2c88d
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/02.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/02.png

## File: assets/readme/showcase-isometric/03.png
size: 89402
sha: a22100b4e731092bcb56e5d49bc90f835a577153
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/03.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/03.png

## File: assets/readme/showcase-isometric/04.png
size: 166284
sha: 92e98fdfe970f87729f7f33f8fff818cae543ee5
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/04.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/04.png

## File: assets/readme/showcase-isometric/05.png
size: 161670
sha: 3f99ad3255c960ae6bf12596872833791d668a3c
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/05.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/05.png

## File: assets/readme/showcase-isometric/06.png
size: 151756
sha: 44e25ab2a1b71426a548491e69f3a7284ee00e1c
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/06.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/06.png

## File: assets/readme/showcase-isometric/07.png
size: 126971
sha: 24c5fdbfbb78243620f9b9984b33a76a0bcf5327
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/07.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/07.png

## File: assets/readme/showcase-isometric/08.png
size: 145911
sha: fd41cd1be9dfb104856a06326a95813182273e8d
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/08.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/08.png

## File: assets/readme/showcase-isometric/09.png
size: 148321
sha: 419a7d3372f97b4d8b97eb2a978a5c03d0f66094
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/09.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/09.png

## File: assets/readme/showcase-isometric/10.png
size: 166905
sha: f17b9146cec7190f115d4b500781e6d6ff905ca8
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/10.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/10.png

## File: assets/readme/showcase-isometric/11.png
size: 141442
sha: 82a2323d846f13ce0dee0eb4f9bb1cdcbc002364
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/11.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/11.png

## File: assets/readme/showcase-isometric/12.png
size: 192814
sha: af833c5d90289e5a84d7e86d8d836a798d61999a
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/12.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/12.png

## File: assets/readme/showcase-isometric/13.png
size: 134572
sha: 48f7fd6a034a6adb3b960dfacf6ea183e6c23179
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/13.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/13.png

## File: assets/readme/showcase-isometric/14.png
size: 159426
sha: 8cb16fca400f9d082f6ebffd35825885354d1595
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/14.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/14.png

## File: assets/readme/showcase-isometric/15.png
size: 154304
sha: adcd6cfa5cf857def6185554c353fc3d047d0bec
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/15.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/15.png

## File: assets/readme/showcase-isometric/16.png
size: 164618
sha: 6ee1218122f08569cda3f327f86cc7629cef106a
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/16.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-isometric/16.png

## File: assets/readme/showcase-soft3d/01.png
size: 185612
sha: e62ba49ddd9928cc026e3d794d719e60ca3a487d
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/01.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/01.png

## File: assets/readme/showcase-soft3d/02.png
size: 187647
sha: 6602dc6bd06379ddbddb31f2ef22b6970a35d15c
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/02.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/02.png

## File: assets/readme/showcase-soft3d/03.png
size: 99433
sha: c90e522bf4ffb5c74a50ed9e6df6a5c0a11b5b58
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/03.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/03.png

## File: assets/readme/showcase-soft3d/04.png
size: 191102
sha: 1145ee3cc8d301676bc8e31101597ce30d464007
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/04.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/04.png

## File: assets/readme/showcase-soft3d/05.png
size: 156974
sha: 200b147c9d146252f7926dda6cc74facaf79d2ef
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/05.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/05.png

## File: assets/readme/showcase-soft3d/06.png
size: 158186
sha: 6ffd93d044e47cbeac240355910a1a8a165f895e
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/06.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/06.png

## File: assets/readme/showcase-soft3d/07.png
size: 175632
sha: a98bc3a50feb67a107a25a4efa2493e92f83e77b
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/07.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/07.png

## File: assets/readme/showcase-soft3d/08.png
size: 142779
sha: c12c3feb3219f732ef9d700f8fd84228522d5c14
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/08.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/08.png

## File: assets/readme/showcase-soft3d/09.png
size: 171593
sha: cf74d6da5d4d2ee0cacd0f571e332611daa1ce5c
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/09.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/09.png

## File: assets/readme/showcase-soft3d/10.png
size: 171487
sha: f0609ebff9a99ad665b963845ba9899eee014d8f
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/10.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/10.png

## File: assets/readme/showcase-soft3d/11.png
size: 190548
sha: 117f45a40ff6bee7519e1db71d0c67dd8a96ef85
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/11.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/11.png

## File: assets/readme/showcase-soft3d/12.png
size: 206951
sha: 07b5e4b5f2ea34d45a35e44cf89b242929d45833
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/12.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/12.png

## File: assets/readme/showcase-soft3d/13.png
size: 158898
sha: 5ef5474ce31ac6a6f64a0e5e10436fb560614693
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/13.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/13.png

## File: assets/readme/showcase-soft3d/14.png
size: 172930
sha: f49f6f51a9046dd2c938853cb45751a47e20d828
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/14.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/14.png

## File: assets/readme/showcase-soft3d/15.png
size: 161787
sha: f9d25e8b6f8f899dd607e7ae398393fc9739fa54
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/15.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/15.png

## File: assets/readme/showcase-soft3d/16.png
size: 197032
sha: 3aa53fefced0a0dcec183ff5649590019f91529c
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/16.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/showcase-soft3d/16.png

## File: assets/readme/source/hero.html
size: 4687
sha: 93539a1789de57f0ebeaa19b5003808c02fd2aa7
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/source/hero.html

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/assets/readme/source/hero.html

## File: .github/workflows/credential-ui.yml
size: 601
sha: 2bd157517ec649d3513deb9e2b24eb282956ac05
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/.github/workflows/credential-ui.yml

```text
name: 凭据页面与业务绑定
on:
  push:
  pull_request:
permissions:
  contents: read
jobs:
  verify:
    runs-on: ubuntu-latest
    timeout-minutes: 5
    defaults:
      run:
        working-directory: scripts/credential-ui
    steps:
      - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
      - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
        with:
          node-version: '22.18.0'
      - run: npm ci --ignore-scripts
      - run: npm run check
      - run: npm run build
      - run: git diff --exit-code -- public/app.js
      - run: npm test
```

## File: .gitignore
size: 188
sha: 48e45b447caee7756208112c66ec2eabd04307a7
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/.gitignore

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/.gitignore

## File: LICENSE
size: 1064
sha: 80fa9b501db35793dcca9b6ccf3e8cdd2db0f057
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/LICENSE

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/LICENSE

## File: reference/construction.md
size: 4305
sha: 5f89a969e2259fe2a19dc82a5ea9386f43f616ef
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/reference/construction.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/reference/construction.md

## File: reference/design-rules.md
size: 5078
sha: 5c53c184054a82676f02c09b7399459ced2a9e80
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/reference/design-rules.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/reference/design-rules.md

## File: reference/image-providers.md
size: 2923
sha: 206a2d7a496f0ef7ff572e81161607a0459e8036
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/reference/image-providers.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/reference/image-providers.md

## File: reference/prompt-template.md
size: 3598
sha: 96312cfd1158c434206cd9a930e1cb8692f6f263
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/reference/prompt-template.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/reference/prompt-template.md

## File: reference/style-adaptation.md
size: 2410
sha: f7f8c00c9bb5a0c56e47375be5685b78b467b0f8
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/reference/style-adaptation.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/reference/style-adaptation.md

## File: styles/animal-badge.json
size: 1092
sha: 995e4a1bc968d86080d27714bc9e9237eda5f60a
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/styles/animal-badge.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/styles/animal-badge.json

## File: styles/cartoon.json
size: 1080
sha: 6969184d0d478bfe84f584a3abe2918cd8a38897
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/styles/cartoon.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/styles/cartoon.json

## File: styles/colorblock.json
size: 1072
sha: a09f2173b9a9f9ac03c10b9ba22f11f8ca4bec06
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/styles/colorblock.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/styles/colorblock.json

## File: styles/filled.json
size: 1076
sha: edffe7b02b549a19130faa42cb4926fe0b51a9ac
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/styles/filled.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/styles/filled.json

## File: styles/isometric.json
size: 1069
sha: b010f3bd7584f3dea2d6f5ed4778fa59f484532d
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/styles/isometric.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/styles/isometric.json

## File: styles/linear.json
size: 1124
sha: 51a29a8086f57e6eb4421dea5b3bc99de37bb981
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/styles/linear.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/styles/linear.json

## File: styles/realistic.json
size: 1129
sha: a29e9023408196fa4adaa041af5010da2805bf0d
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/styles/realistic.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/styles/realistic.json

## File: styles/render3d.json
size: 1129
sha: 2bfa277cc67ea7ca47855e53e1815c31469db73d
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/styles/render3d.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/styles/render3d.json

## File: styles/sticker.json
size: 1105
sha: 8e4bc3b59a530ea3268cd4f738494da4226b3daf
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/styles/sticker.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/styles/sticker.json

## File: tests/test_profile_business.py
size: 1190
sha: 89662eee31bd3def408844a2b9d23ab19d35a200
upstream: https://github.com/oil-oil/oil-icon/blob/HEAD/tests/test_profile_business.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/oil-oil/oil-icon/blob/HEAD/tests/test_profile_business.py
