feat: 新增 artifacts 功能 (#1278)

* feat: 新增 cloud-artifacts 包(Cloudflare Worker HTML artifact 托管)

POST /upload 鉴权上传 HTML 到 R2 返回 hash URL,GET /<7d|30d>/<id>.html
由 Worker 代理读取并直出 text/html。R2 lifecycle rule 自动 7/30 天删除。
独立服务,不被主 CLI 引用(类似 packages/remote-control-server/ 定位)。

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* docs: 完善 cloud-artifacts 文档并统一出口域名

- CLAUDE.md 加 cloud-artifacts 到 Workspace Packages 表和新增 HTML Artifact Hosting 段落
- docs.json 注册 cloud-artifacts 到运行模式 group
- README 加 Quickstart、架构图(含 Deno Deploy 代理层)、Security Considerations、Troubleshooting
- 统一出口域名为 https://cloud-artifacts.claude-code-best.win(wrangler.toml PUBLIC_URL、test.sh 默认 WORKER_URL、所有文档示例)
- test.sh expect() 加 [via body] fallback:经 Deno Deploy 代理(status 抹平为 200)时按 body 的 error 字段断言

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* docs: 修正 CLAUDE.md cloud-artifacts 引用死链

之前指向不存在的 docs/features/cloud-artifacts.md(用户未注册到 docs.json),
改为指向已存在的 packages/cloud-artifacts/README.md,并补充生产出口域名
与 Deno Deploy status 抹平副作用的说明。

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* chore: 同步 cloud-artifacts 测试默认 TOKEN 到新值

用户已通过 wrangler secret put 把生产 TOKEN 改为 claude-code-best,
test.sh 的默认值(之前用旧 token 作 fallback)和注释示例同步更新。
现在直接 bash scripts/test.sh 即可跑通(无需显式传 TOKEN)。

src/index.ts 不依赖具体 token 值(只读 env.TOKEN 做比较),
wrangler.toml 不含 secret,README/.dev.vars.example 用 <your-token>
占位符故无需改。

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* docs: add artifacts feature implementation plan

* feat(artifact): add cloud-artifacts config with token/URL defaults

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): add HTTP client with body-error parsing

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): add tool name, description, and prompt

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): add buildTool definition with file validation

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* test(artifact): add end-to-end tool tests for upload/error paths

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): export ArtifactTool from builtin-tools barrel

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): register ArtifactTool in tools list

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): add /use-artifacts bundled skill

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): add extractArtifacts message scanner

Scans Message[] for artifact tool_use/tool_result pairs, parses URL/id/expires
from the upload response string, and returns ArtifactInfo[] newest-first.

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* fix(artifact): scanner type narrowing and url regex

- Use double assertion (`as unknown as Record<string, unknown>`) at lines 30
  and 90 to fix TS2352 per project convention
- Tighten URL_REGEX to avoid capturing trailing punctuation (parens,
  quotes, commas) when URL is embedded in text
- Add test case for array-form tool_result content path

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): add ArtifactsMenu Ink component

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): add /artifacts slash command entry

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): register /artifacts command

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* fix(artifact): use setClipboard instead of pbcopy for cross-platform support

* fix(artifact): drop userFacingName override so display matches /artifacts

* fix(rcs): add resJson helper to resolve strict mode type errors in tests

Hono Response.json() returns Promise<unknown> under strict TypeScript,
causing 121 TS errors across middleware and routes test files.

Co-Authored-By: glm-5-turbo <zai-org@claude-code-best.win>

* fix(cloud-artifacts): add type stubs so tsc passes without worker-configuration.d.ts

The wrangler-generated worker-configuration.d.ts is gitignored, causing CI to
fail with missing ExportedHandler/Env/R2Bucket types. This file provides minimal
stubs for all Cloudflare Workers types used by the artifact upload Worker.

Co-Authored-By: glm-5-turbo <zai-org@claude-code-best.win>

* fix(query): shallow-copy messages before stripping toolUseResult

Previously the per-query cleanup mutated messagesForQuery entries in
place via `delete msg.toolUseResult`. Those entries are references
shared with mutableMessages (UI state), so the delete stripped the
field from the live message object. The next query can start within
milliseconds of tool_result creation — before the React UI commit
lands — so UserToolSuccessMessage's `!message.toolUseResult` check
returned null and tool.renderToolResultMessage was never called,
leaving tool-result rows blank.

Map to a stripped copy instead so mutableMessages keeps the original
for the UI. Downstream API transformations (applyToolResultBudget,
snip, microcompact) already build new arrays via .map(), so they
compose cleanly with this copy.

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): show uploaded URL inline below ExecuteExtraTool

Deferred tools (shouldDefer: true) are invoked via SearchExtraTools →
ExecuteExtraTool, so their tool_result rows used to render blank —
the UI looked up ExecuteExtraTool, which had no renderToolResultMessage,
and returned null. Add a generic delegation in ExecuteTool that forwards
renderToolResultMessage to the inner tool when it defines one, unwrapping
the { result, tool_name } envelope and the params from the input shape.
All 28 deferred tools can now render their own UI by defining
renderToolResultMessage.

For ArtifactTool specifically, render the uploaded URL as an OSC 8
hyperlink (Link component) in warning color so it's visually prominent,
with the expiry timestamp on a second line and a separate error branch.
Also add `error: z.string().optional()` to outputSchema — zod's default
strip mode was dropping the field, so error states never reached the UI.

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* fix(cloud-artifacts): make Env stubs actually take effect in CI

The previous stub file (2e29e362) wrapped `interface Env` in
`declare global { ... }`, but the file has no top-level import/export so
it's a script, not a module. TS2669 forbids `declare global` in scripts,
and in .d.ts files that error is silently swallowed — so the Env stubs
were never merged into the global scope. Locally typecheck passed only
because worker-configuration.d.ts (gitignored) provided Env separately;
in CI / fresh clones, `BUCKET`, `MAX_BYTES`, `DEFAULT_TTL_DAYS`,
`PUBLIC_URL` were all missing on Env.

Drop the wrapper. Top-level `interface Env` in a script .d.ts is already
global ambient and merges with worker-configuration.d.ts via interface
declaration merging, so both environments typecheck cleanly.

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

---------

Co-authored-by: glm-5.2 <zai-org@claude-code-best.win>
This commit is contained in:
claude-code-best
2026-06-20 19:52:08 +08:00
committed by GitHub
parent 5d74071ebf
commit 084e487943
36 changed files with 3713 additions and 113 deletions

View File

@@ -0,0 +1,119 @@
import { nanoid } from 'nanoid'
// TOKEN 通过 `wrangler secret put TOKEN` 注入wrangler types 不为 secret 生成类型
// 所以这里显式扩展全局 Env与 worker-configuration.d.ts 合并)
declare global {
interface Env {
TOKEN: string
}
}
const HASH_PATTERN = /^[A-Za-z0-9_-]{1,128}$/
const TTL_PREFIXES = ['7d', '30d']
const ALLOWED_TTLS = [7, 30]
const HTML_CONTENT_TYPE = 'text/html; charset=utf-8'
// GET /<prefix>/<id>.html —— prefix 与 lifecycle rule 对应,限制只能是 7d 或 30d
const GET_PATH_PATTERN = /^\/(7d|30d)\/([A-Za-z0-9_-]{1,128})\.html$/
export default {
async fetch(req: Request, env: Env): Promise<Response> {
const url = new URL(req.url)
if (req.method === 'GET') {
return handleGet(url, env)
}
if (url.pathname === '/upload' && req.method === 'POST') {
return handleUpload(req, env, url)
}
return json({ error: 'not_found' }, 404)
},
} satisfies ExportedHandler<Env>
// GET /7d/<id>.html 或 /30d/<id>.html —— 从 R2 读,返回 text/html
async function handleGet(url: URL, env: Env): Promise<Response> {
const match = GET_PATH_PATTERN.exec(url.pathname)
if (!match) {
return json({ error: 'not_found' }, 404)
}
const [, prefix, id] = match
const obj = await env.BUCKET.get(`${prefix}/${id}.html`)
if (obj === null) {
return new Response('Not Found', { status: 404 })
}
const headers = new Headers()
obj.writeHttpMetadata(headers)
headers.set('content-type', HTML_CONTENT_TYPE)
headers.set('cache-control', 'public, max-age=86400')
return new Response(obj.body, { headers, status: 200 })
}
async function handleUpload(
req: Request,
env: Env,
url: URL,
): Promise<Response> {
const auth = req.headers.get('authorization') ?? ''
const token = auth.startsWith('Bearer ') ? auth.slice(7) : ''
if (!env.TOKEN || !token || token !== env.TOKEN) {
return json({ error: 'unauthorized' }, 401)
}
const contentType = (req.headers.get('content-type') ?? '').toLowerCase()
if (!contentType.startsWith('text/html')) {
return json({ error: 'unsupported_media_type' }, 415)
}
const maxBytes = Number.parseInt(env.MAX_BYTES, 10) || 10 * 1024 * 1024
const declaredLength = Number.parseInt(
req.headers.get('content-length') ?? '',
10,
)
if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
return json({ error: 'payload_too_large' }, 413)
}
const defaultTtl = Number.parseInt(env.DEFAULT_TTL_DAYS, 10) || 7
const ttlParam = url.searchParams.get('ttl')
const ttl = ttlParam === null ? defaultTtl : Number.parseInt(ttlParam, 10)
if (!Number.isFinite(ttl) || !ALLOWED_TTLS.includes(ttl)) {
return json({ error: 'invalid_ttl' }, 400)
}
const hashParam = url.searchParams.get('hash')
let id: string
if (hashParam !== null) {
if (!HASH_PATTERN.test(hashParam)) {
return json({ error: 'invalid_hash' }, 400)
}
id = hashParam
// 覆盖:先删所有 ttl prefix 下可能的旧 keyR2 delete 不存在的 key 不报错)
await Promise.all(
TTL_PREFIXES.map(p => env.BUCKET.delete(`${p}/${id}.html`)),
)
} else {
id = nanoid(21)
}
const body = await req.arrayBuffer()
if (body.byteLength > maxBytes) {
return json({ error: 'payload_too_large' }, 413)
}
const key = `${ttl}d/${id}.html`
await env.BUCKET.put(key, body, {
httpMetadata: { contentType: HTML_CONTENT_TYPE },
})
const expiresAt = new Date(Date.now() + ttl * 24 * 60 * 60 * 1000)
return json(
{ id, url: `${env.PUBLIC_URL}/${key}`, expiresAt: expiresAt.toISOString() },
200,
)
}
function json(body: unknown, status: number): Response {
return new Response(JSON.stringify(body), {
status,
headers: { 'content-type': 'application/json' },
})
}

104
packages/cloud-artifacts/src/types.d.ts vendored Normal file
View File

@@ -0,0 +1,104 @@
/**
* Minimal Cloudflare Workers type stubs for cloud-artifacts Worker.
*
* The canonical types are in worker-configuration.d.ts (generated by `wrangler types`,
* gitignored). This file provides just enough so `tsc --noEmit` passes even when that
* generated file is absent (e.g. CI, fresh clone).
*/
// -- R2 types ---------------------------------------------------------------
interface R2Checksums {
readonly md5?: ArrayBuffer
readonly sha1?: ArrayBuffer
readonly sha256?: ArrayBuffer
readonly sha384?: ArrayBuffer
readonly sha512?: ArrayBuffer
}
interface R2HTTPMetadata {
contentType?: string
contentLanguage?: string
contentDisposition?: string
contentEncoding?: string
cacheControl?: string
cacheExpiry?: Date
}
interface R2Range {
offset: number
length?: number
}
declare abstract class R2Object {
readonly key: string
readonly version: string
readonly size: number
readonly etag: string
readonly httpEtag: string
readonly checksums: R2Checksums
readonly uploaded: Date
readonly httpMetadata?: R2HTTPMetadata
readonly customMetadata?: Record<string, string>
readonly range?: R2Range
readonly storageClass: string
readonly ssecKeyMd5?: string
writeHttpMetadata(headers: Headers): void
}
interface R2ObjectBody extends R2Object {
get body(): ReadableStream
get bodyUsed(): boolean
}
interface R2PutOptions {
httpMetadata?: R2HTTPMetadata | Headers
customMetadata?: Record<string, string>
}
interface R2Bucket {
head(key: string): Promise<R2Object | null>
get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>
put(
key: string,
value:
| ReadableStream
| ArrayBuffer
| ArrayBufferView
| string
| null
| Blob,
options?: R2PutOptions,
): Promise<R2Object>
delete(keys: string | string[]): Promise<void>
}
// Empty placeholder — R2GetOptions is unused beyond an optional parameter
type R2GetOptions = {}
// -- ExportedHandler -------------------------------------------------------
interface ExportedHandler<Env = unknown> {
fetch?: (
request: Request,
env: Env,
ctx: ExecutionContext,
) => Response | Promise<Response>
}
// -- Env -------------------------------------------------------------------
// Wrangler-generated worker-configuration.d.ts supplies TOKEN via `wrangler secret put`.
// This declaration provides the R2 binding + wrangler vars so the Worker compiles
// without the generated file.
//
// NOTE: 这个文件是脚本(没有 top-level import/export顶层 interface 自动是 global
// ambient会和 worker-configuration.d.ts 的 `interface Env` 走 interface declaration
// merging。不要用 `declare global { ... }` 包裹——脚本文件里那种写法是 TS2669 错误,
// 在 .d.ts 里甚至会被静默吞掉,导致 Env 桩完全不生效CI 上就是这种情况)。
interface Env {
BUCKET: R2Bucket
TOKEN: string
MAX_BYTES: string
DEFAULT_TTL_DAYS: string
PUBLIC_URL: string
}