mirror of
https://github.com/claude-code-best/claude-code.git
synced 2026-06-20 23:35:51 +00:00
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:
@@ -179,6 +179,7 @@ import privacySettings from './commands/privacy-settings/index.js'
|
||||
import hooks from './commands/hooks/index.js'
|
||||
import files from './commands/files/index.js'
|
||||
import branch from './commands/branch/index.js'
|
||||
import artifacts from './commands/artifacts/index.js'
|
||||
import agents from './commands/agents/index.js'
|
||||
import plugin from './commands/plugin/index.js'
|
||||
import reloadPlugins from './commands/reload-plugins/index.js'
|
||||
@@ -305,6 +306,7 @@ const COMMANDS = memoize((): Command[] => [
|
||||
localMemoryCommand,
|
||||
autonomy,
|
||||
provider,
|
||||
artifacts,
|
||||
agents,
|
||||
branch,
|
||||
btw,
|
||||
|
||||
94
src/commands/artifacts/ArtifactsMenu.tsx
Normal file
94
src/commands/artifacts/ArtifactsMenu.tsx
Normal file
@@ -0,0 +1,94 @@
|
||||
import * as React from 'react';
|
||||
import { Box, Text, setClipboard, useInput } from '@anthropic/ink';
|
||||
import type { ArtifactInfo } from './scanner.js';
|
||||
import { openBrowser } from 'src/utils/browser.js';
|
||||
|
||||
type Props = {
|
||||
artifacts: ArtifactInfo[];
|
||||
onExit: () => void;
|
||||
};
|
||||
|
||||
export function ArtifactsMenu({ artifacts, onExit }: Props): React.ReactElement {
|
||||
const [selected, setSelected] = React.useState(0);
|
||||
|
||||
useInput((input, key) => {
|
||||
if (input === 'q' || key.escape) {
|
||||
onExit();
|
||||
return;
|
||||
}
|
||||
if (artifacts.length === 0) return;
|
||||
if (key.upArrow) {
|
||||
setSelected(s => (s - 1 + artifacts.length) % artifacts.length);
|
||||
return;
|
||||
}
|
||||
if (key.downArrow) {
|
||||
setSelected(s => (s + 1) % artifacts.length);
|
||||
return;
|
||||
}
|
||||
if (key.return) {
|
||||
const target = artifacts[selected];
|
||||
if (target.url) {
|
||||
void openBrowser(target.url);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (input === 'c') {
|
||||
const target = artifacts[selected];
|
||||
if (target.url) {
|
||||
void setClipboard(target.url).then(raw => {
|
||||
if (raw) process.stdout.write(raw);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} paddingY={0}>
|
||||
<Box marginBottom={1}>
|
||||
<Text bold>Artifacts ({artifacts.length})</Text>
|
||||
</Box>
|
||||
|
||||
{artifacts.length === 0 ? (
|
||||
<Text color="subtle">No artifacts uploaded this session. Run /use-artifacts to learn how.</Text>
|
||||
) : (
|
||||
<Box flexDirection="column">
|
||||
{artifacts.map((a, idx) => (
|
||||
<ArtifactRow key={a.toolUseId} artifact={a} isSelected={idx === selected} />
|
||||
))}
|
||||
<Box marginTop={1}>
|
||||
<Text color="subtle">{'↑/↓ select · Enter open · c copy URL · Esc exit'}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function ArtifactRow({ artifact, isSelected }: { artifact: ArtifactInfo; isSelected: boolean }): React.ReactElement {
|
||||
const marker = isSelected ? '›' : ' ';
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Box>
|
||||
<Text color={isSelected ? 'suggestion' : undefined}>{marker} </Text>
|
||||
<Text bold={isSelected} color={artifact.isError ? 'error' : undefined}>
|
||||
{artifact.basename}
|
||||
</Text>
|
||||
{artifact.hash ? <Text color="subtle"> ({artifact.hash})</Text> : null}
|
||||
</Box>
|
||||
{artifact.url ? (
|
||||
<Box marginLeft={2}>
|
||||
<Text color="background">{artifact.url}</Text>
|
||||
</Box>
|
||||
) : (
|
||||
<Box marginLeft={2}>
|
||||
<Text color="error">{artifact.rawContent}</Text>
|
||||
</Box>
|
||||
)}
|
||||
{artifact.expiresAt ? (
|
||||
<Box marginLeft={2}>
|
||||
<Text color="subtle">expires: {artifact.expiresAt}</Text>
|
||||
</Box>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
158
src/commands/artifacts/__tests__/scanner.test.ts
Normal file
158
src/commands/artifacts/__tests__/scanner.test.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
import { describe, expect, test } from 'bun:test'
|
||||
import { extractArtifacts } from '../scanner.js'
|
||||
import type { Message } from 'src/types/message.js'
|
||||
|
||||
function assistantToolUse(id: string, input: Record<string, unknown>): Message {
|
||||
return {
|
||||
type: 'assistant',
|
||||
uuid: crypto.randomUUID(),
|
||||
message: {
|
||||
role: 'assistant',
|
||||
content: [{ type: 'tool_use' as const, id, name: 'artifact', input }],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function userToolResult(id: string, content: string, isError = false): Message {
|
||||
return {
|
||||
type: 'user',
|
||||
uuid: crypto.randomUUID(),
|
||||
message: {
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'tool_result' as const,
|
||||
tool_use_id: id,
|
||||
content,
|
||||
is_error: isError,
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
describe('extractArtifacts', () => {
|
||||
test('returns empty list when no artifact tool_use messages', () => {
|
||||
expect(extractArtifacts([])).toEqual([])
|
||||
expect(
|
||||
extractArtifacts([
|
||||
{
|
||||
type: 'user',
|
||||
uuid: crypto.randomUUID(),
|
||||
message: {
|
||||
role: 'user',
|
||||
content: [{ type: 'text' as const, text: 'hi' }],
|
||||
},
|
||||
},
|
||||
]),
|
||||
).toEqual([])
|
||||
})
|
||||
|
||||
test('pairs a successful tool_use with its tool_result and returns parsed fields', () => {
|
||||
const messages: Message[] = [
|
||||
assistantToolUse('tu1', { file_path: '/tmp/report.html', ttl: 7 }),
|
||||
userToolResult(
|
||||
'tu1',
|
||||
'Artifact uploaded: https://x.test/7d/abc.html (id: abc, expires: 2026-06-27T10:00:00.000Z)',
|
||||
),
|
||||
]
|
||||
|
||||
const result = extractArtifacts(messages)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0]).toMatchObject({
|
||||
filePath: '/tmp/report.html',
|
||||
hash: 'abc',
|
||||
url: 'https://x.test/7d/abc.html',
|
||||
expiresAt: '2026-06-27T10:00:00.000Z',
|
||||
basename: 'report.html',
|
||||
isError: false,
|
||||
})
|
||||
})
|
||||
|
||||
test('skips artifact tool_use without a matching tool_result', () => {
|
||||
const messages: Message[] = [
|
||||
assistantToolUse('tu1', { file_path: '/tmp/report.html', ttl: 7 }),
|
||||
]
|
||||
|
||||
expect(extractArtifacts(messages)).toEqual([])
|
||||
})
|
||||
|
||||
test('keeps error results with isError=true and no parsed fields', () => {
|
||||
const messages: Message[] = [
|
||||
assistantToolUse('tu1', { file_path: '/tmp/missing.html', ttl: 7 }),
|
||||
userToolResult(
|
||||
'tu1',
|
||||
'File does not exist or is not readable: /tmp/missing.html',
|
||||
true,
|
||||
),
|
||||
]
|
||||
|
||||
const result = extractArtifacts(messages)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0]).toMatchObject({
|
||||
filePath: '/tmp/missing.html',
|
||||
basename: 'missing.html',
|
||||
isError: true,
|
||||
})
|
||||
expect(result[0].url).toBeUndefined()
|
||||
})
|
||||
|
||||
test('parses url/id/expires from array-form tool_result content', () => {
|
||||
const messages: Message[] = [
|
||||
assistantToolUse('tu1', { file_path: '/tmp/report.html', ttl: 7 }),
|
||||
{
|
||||
type: 'user',
|
||||
uuid: crypto.randomUUID(),
|
||||
message: {
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'tool_result' as const,
|
||||
tool_use_id: 'tu1',
|
||||
content: [
|
||||
{ type: 'text' as const, text: 'Artifact uploaded: ' },
|
||||
{
|
||||
type: 'text' as const,
|
||||
text: 'https://x.test/7d/def.html (id: def, expires: 2026-06-27T10:00:00.000Z)',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
const result = extractArtifacts(messages)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0]).toMatchObject({
|
||||
filePath: '/tmp/report.html',
|
||||
hash: 'def',
|
||||
url: 'https://x.test/7d/def.html',
|
||||
expiresAt: '2026-06-27T10:00:00.000Z',
|
||||
basename: 'report.html',
|
||||
isError: false,
|
||||
})
|
||||
})
|
||||
|
||||
test('orders newest first (last in conversation appears at top)', () => {
|
||||
const messages: Message[] = [
|
||||
assistantToolUse('tu1', { file_path: '/tmp/a.html', ttl: 7 }),
|
||||
userToolResult(
|
||||
'tu1',
|
||||
'Artifact uploaded: https://x.test/7d/a.html (id: a, expires: 2026-06-27T10:00:00.000Z)',
|
||||
),
|
||||
assistantToolUse('tu2', { file_path: '/tmp/b.html', ttl: 7 }),
|
||||
userToolResult(
|
||||
'tu2',
|
||||
'Artifact uploaded: https://x.test/7d/b.html (id: b, expires: 2026-06-27T10:00:00.000Z)',
|
||||
),
|
||||
]
|
||||
|
||||
const result = extractArtifacts(messages)
|
||||
|
||||
expect(result.map(r => r.basename)).toEqual(['b.html', 'a.html'])
|
||||
})
|
||||
})
|
||||
11
src/commands/artifacts/artifacts.tsx
Normal file
11
src/commands/artifacts/artifacts.tsx
Normal file
@@ -0,0 +1,11 @@
|
||||
import * as React from 'react';
|
||||
import type { LocalJSXCommandOnDone } from 'src/types/command.js';
|
||||
import type { ToolUseContext } from 'src/Tool.js';
|
||||
import { ArtifactsMenu } from './ArtifactsMenu.js';
|
||||
import { extractArtifacts } from './scanner.js';
|
||||
|
||||
export async function call(onDone: LocalJSXCommandOnDone, context: ToolUseContext): Promise<React.ReactNode> {
|
||||
const messages = context.messages ?? [];
|
||||
const artifacts = extractArtifacts(messages);
|
||||
return <ArtifactsMenu artifacts={artifacts} onExit={onDone} />;
|
||||
}
|
||||
12
src/commands/artifacts/index.ts
Normal file
12
src/commands/artifacts/index.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import type { Command } from '../../commands.js'
|
||||
|
||||
const artifacts = {
|
||||
type: 'local-jsx',
|
||||
name: 'artifacts',
|
||||
description:
|
||||
'List HTML artifacts uploaded to cloud-artifacts in this session',
|
||||
isEnabled: () => true,
|
||||
load: () => import('./artifacts.js'),
|
||||
} satisfies Command
|
||||
|
||||
export default artifacts
|
||||
97
src/commands/artifacts/scanner.ts
Normal file
97
src/commands/artifacts/scanner.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import { basename } from 'path'
|
||||
import type { Message } from 'src/types/message.js'
|
||||
|
||||
export type ArtifactInfo = {
|
||||
toolUseId: string
|
||||
filePath: string
|
||||
basename: string
|
||||
hash?: string
|
||||
url?: string
|
||||
expiresAt?: string
|
||||
rawContent: string
|
||||
isError: boolean
|
||||
}
|
||||
|
||||
const URL_REGEX = /https?:\/\/[^\s)"',]+\.html\b/
|
||||
const ID_REGEX = /\bid:\s*([A-Za-z0-9_-]+)/
|
||||
const EXPIRES_REGEX = /\bexpires:\s*([0-9T:.Z+-]+)/
|
||||
|
||||
export function extractArtifacts(messages: Message[]): ArtifactInfo[] {
|
||||
const results: ArtifactInfo[] = []
|
||||
|
||||
for (const message of messages) {
|
||||
if (message.type !== 'assistant') continue
|
||||
const content = message.message?.content
|
||||
if (!Array.isArray(content)) continue
|
||||
|
||||
for (const block of content) {
|
||||
if (typeof block !== 'object' || block === null) continue
|
||||
if (!('type' in block)) continue
|
||||
const b = block as unknown as Record<string, unknown>
|
||||
if (b.type !== 'tool_use') continue
|
||||
if (b.name !== 'artifact') continue
|
||||
|
||||
const toolUseId = b.id as string
|
||||
const input = b.input as { file_path?: string } | undefined
|
||||
const filePath = input?.file_path ?? '<unknown>'
|
||||
|
||||
const resultBlock = findToolResult(messages, toolUseId)
|
||||
if (!resultBlock) continue
|
||||
|
||||
const rawContent =
|
||||
typeof resultBlock.content === 'string'
|
||||
? resultBlock.content
|
||||
: Array.isArray(resultBlock.content)
|
||||
? resultBlock.content
|
||||
.map(c =>
|
||||
typeof c === 'string'
|
||||
? c
|
||||
: 'text' in c
|
||||
? (c as { text: string }).text
|
||||
: '',
|
||||
)
|
||||
.join('')
|
||||
: ''
|
||||
|
||||
const isError = resultBlock.is_error === true
|
||||
const urlMatch = rawContent.match(URL_REGEX)
|
||||
const idMatch = rawContent.match(ID_REGEX)
|
||||
const expiresMatch = rawContent.match(EXPIRES_REGEX)
|
||||
|
||||
results.push({
|
||||
toolUseId,
|
||||
filePath,
|
||||
basename: basename(filePath),
|
||||
hash: idMatch?.[1],
|
||||
url: urlMatch?.[0],
|
||||
expiresAt: expiresMatch?.[1],
|
||||
rawContent,
|
||||
isError,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// newest first
|
||||
return results.reverse()
|
||||
}
|
||||
|
||||
function findToolResult(
|
||||
messages: Message[],
|
||||
toolUseId: string,
|
||||
): { content: unknown; is_error?: boolean } | null {
|
||||
for (const message of messages) {
|
||||
if (message.type !== 'user') continue
|
||||
const content = message.message?.content
|
||||
if (!Array.isArray(content)) continue
|
||||
|
||||
for (const block of content) {
|
||||
if (typeof block !== 'object' || block === null) continue
|
||||
if (!('type' in block)) continue
|
||||
const b = block as unknown as Record<string, unknown>
|
||||
if (b.type !== 'tool_result') continue
|
||||
if (b.tool_use_id !== toolUseId) continue
|
||||
return { content: b.content, is_error: b.is_error as boolean | undefined }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
38
src/query.ts
38
src/query.ts
@@ -522,21 +522,35 @@ async function* queryLoop(
|
||||
|
||||
let messagesForQuery = getMessagesAfterCompactBoundary(messages)
|
||||
|
||||
// Release toolUseResult payloads from previous turns. By this point the
|
||||
// UI has already rendered those results and the next API call only needs
|
||||
// message.message.content (tool_result blocks), not the raw output object.
|
||||
// This prevents unbounded memory growth in long sessions before compact
|
||||
// triggers — a single FileRead of a 400KB file would otherwise stay in
|
||||
// mutableMessages forever.
|
||||
for (const msg of messagesForQuery) {
|
||||
// Release toolUseResult payloads from previous turns — the next API call
|
||||
// only needs message.message.content (tool_result blocks), not the raw
|
||||
// output object. This prevents unbounded memory growth in long sessions
|
||||
// before compact triggers (a single FileRead of a 400KB file would
|
||||
// otherwise stay in mutableMessages forever).
|
||||
//
|
||||
// IMPORTANT: shallow-copy rather than mutate. messagesForQuery elements
|
||||
// are references shared with mutableMessages (UI state); deleting
|
||||
// toolUseResult in place strips it from the live message while React may
|
||||
// still be rendering it. The next query can start within milliseconds of
|
||||
// tool_result creation (model immediately calls the next tool), before
|
||||
// the UI commit lands — UserToolSuccessMessage reads
|
||||
// message.toolUseResult to delegate to tool.renderToolResultMessage, so a
|
||||
// mutation race makes tool-result rows render blank. Map to a stripped
|
||||
// copy 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.
|
||||
messagesForQuery = messagesForQuery.map(msg => {
|
||||
if (
|
||||
msg.type === 'user' &&
|
||||
'toolUseResult' in msg &&
|
||||
msg.toolUseResult !== undefined
|
||||
msg.type !== 'user' ||
|
||||
!('toolUseResult' in msg) ||
|
||||
(msg as { toolUseResult?: unknown }).toolUseResult === undefined
|
||||
) {
|
||||
delete (msg as Message & { toolUseResult?: unknown }).toolUseResult
|
||||
return msg
|
||||
}
|
||||
}
|
||||
const copy: typeof msg = { ...msg }
|
||||
delete (copy as Message & { toolUseResult?: unknown }).toolUseResult
|
||||
return copy
|
||||
})
|
||||
|
||||
let tracking = autoCompactTracking
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { registerKeybindingsSkill } from './keybindings.js'
|
||||
import { registerLoremIpsumSkill } from './loremIpsum.js'
|
||||
import { registerRememberSkill } from './remember.js'
|
||||
import { registerSimplifySkill } from './simplify.js'
|
||||
import { registerUseArtifactsSkill } from './useArtifacts.js'
|
||||
import { registerSkillifySkill } from './skillify.js'
|
||||
import { registerStuckSkill } from './stuck.js'
|
||||
import { registerUltracodeSkill } from './ultracode.js'
|
||||
@@ -34,6 +35,7 @@ export function initBundledSkills(): void {
|
||||
registerSkillifySkill()
|
||||
registerRememberSkill()
|
||||
registerSimplifySkill()
|
||||
registerUseArtifactsSkill()
|
||||
registerBatchSkill()
|
||||
registerStuckSkill()
|
||||
registerUltracodeSkill()
|
||||
|
||||
101
src/skills/bundled/useArtifacts.ts
Normal file
101
src/skills/bundled/useArtifacts.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
import { registerBundledSkill } from '../bundledSkills.js'
|
||||
|
||||
const USE_ARTIFACTS_PROMPT = `# Using Artifacts
|
||||
|
||||
Artifacts are public HTML pages you upload to a hosting service. They have stable URLs that you can share with the user or open in a browser. Use them to surface work-in-progress, summaries, and reports.
|
||||
|
||||
## When to use artifacts
|
||||
|
||||
**Good artifact content:**
|
||||
- Progress panels / kanbans (task list with status)
|
||||
- Research reports and analysis (data + findings + recommendations)
|
||||
- Design docs / decision records (with context and rationale)
|
||||
- Data visualizations (tables, SVG charts, flow diagrams)
|
||||
- Final deliverables (the "thing the user asked for" rendered as HTML)
|
||||
|
||||
**Do NOT use artifacts for:**
|
||||
- Code snippets — use files directly
|
||||
- One-line answers — keep them in chat
|
||||
- Internal debug logs — keep them in chat
|
||||
- Large data dumps — link to source files instead
|
||||
|
||||
## Cadence — when to upload
|
||||
|
||||
- **Task start**: if the task is complex (multi-step, research, deliverable), upload a skeleton artifact first as scaffolding (placeholder sections).
|
||||
- **Milestones**: when you complete a phase (research done / implementation done / tests pass), update the artifact.
|
||||
- **User asks**: upload immediately.
|
||||
- **Task end**: ship the final artifact as the deliverable.
|
||||
|
||||
**Do NOT upload:**
|
||||
- After every tool call (noise)
|
||||
- Mid-step with no meaningful change (e.g. fixed a typo)
|
||||
|
||||
## How to invoke (deferred tool)
|
||||
|
||||
\`artifact\` is a deferred tool. The first call requires two steps; subsequent calls one step.
|
||||
|
||||
**First upload (creates a new artifact):**
|
||||
\`\`\`
|
||||
1. Use the Write tool to write HTML to a local file (location is your choice).
|
||||
2. SearchExtraTools({ query: "select:artifact" }) // loads the tool schema
|
||||
3. ExecuteExtraTool({ tool_name: "artifact", params: { file_path: "<absolute-path>.html" } })
|
||||
4. Save the returned \`id\` from the tool result — this is the hash.
|
||||
\`\`\`
|
||||
|
||||
**Subsequent updates (overwrites in place, URL stays stable):**
|
||||
\`\`\`
|
||||
1. Update the local HTML file.
|
||||
2. ExecuteExtraTool({ tool_name: "artifact", params: { file_path: "<absolute-path>.html", hash: "<id-from-first-call>" } })
|
||||
\`\`\`
|
||||
|
||||
The URL returned on every call is the same when you pass the same \`hash\`. The user can open it at any time to see the latest version.
|
||||
|
||||
## Minimal HTML skeleton
|
||||
|
||||
\`\`\`html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Artifact Title</title>
|
||||
<style>
|
||||
body { font: 14px/1.5 -apple-system, sans-serif; max-width: 800px; margin: 2rem auto; padding: 0 1rem; }
|
||||
h1, h2 { color: #1a1a1a; }
|
||||
table { border-collapse: collapse; width: 100%; }
|
||||
th, td { border: 1px solid #ddd; padding: 6px 10px; text-align: left; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Artifact Title</h1>
|
||||
<!-- content here -->
|
||||
</body>
|
||||
</html>
|
||||
\`\`\`
|
||||
|
||||
The hosting service serves the HTML verbatim (including any \`<script>\` you include), so you can use vanilla JS/SVG/CSS as needed. Do not embed secrets.
|
||||
|
||||
## Notes
|
||||
|
||||
- Artifacts expire (default 7 days; pass \`ttl: 30\` for 30-day retention).
|
||||
- Anyone with the URL can view the artifact — treat the URL as the secret.
|
||||
- The \`/artifacts\` slash command (user-invoked) shows all artifacts uploaded in the current session.
|
||||
`
|
||||
|
||||
export function registerUseArtifactsSkill(): void {
|
||||
registerBundledSkill({
|
||||
name: 'use-artifacts',
|
||||
description:
|
||||
'Teach the agent when and how to use the artifact tool: what content belongs in artifacts, when to upload/update, and the SearchExtraTools + ExecuteExtraTool invocation flow for the deferred artifact tool.',
|
||||
whenToUse:
|
||||
'Use this skill at the start of any complex task that would benefit from a living progress document or a deliverable HTML report.',
|
||||
userInvocable: true,
|
||||
argumentHint: '[optional focus note]',
|
||||
async getPromptForCommand(args) {
|
||||
let prompt = USE_ARTIFACTS_PROMPT
|
||||
if (args && args.trim().length > 0) {
|
||||
prompt += `\n\n## Additional Focus\n\n${args.trim()}\n`
|
||||
}
|
||||
return [{ type: 'text', text: prompt }]
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -62,6 +62,7 @@ import { TaskOutputTool } from '@claude-code-best/builtin-tools/tools/TaskOutput
|
||||
import { WebSearchTool } from '@claude-code-best/builtin-tools/tools/WebSearchTool/WebSearchTool.js'
|
||||
import { TodoWriteTool } from '@claude-code-best/builtin-tools/tools/TodoWriteTool/TodoWriteTool.js'
|
||||
import { ExitPlanModeV2Tool } from '@claude-code-best/builtin-tools/tools/ExitPlanModeTool/ExitPlanModeV2Tool.js'
|
||||
import { ArtifactTool } from '@claude-code-best/builtin-tools/tools/ArtifactTool/ArtifactTool.js'
|
||||
import { TestingPermissionTool } from '@claude-code-best/builtin-tools/tools/testing/TestingPermissionTool.js'
|
||||
import { GrepTool } from '@claude-code-best/builtin-tools/tools/GrepTool/GrepTool.js'
|
||||
import { TungstenTool } from '@claude-code-best/builtin-tools/tools/TungstenTool/TungstenTool.js'
|
||||
@@ -228,6 +229,7 @@ export function getAllBaseTools(): Tools {
|
||||
FileEditTool,
|
||||
FileWriteTool,
|
||||
NotebookEditTool,
|
||||
ArtifactTool,
|
||||
WebFetchTool,
|
||||
TodoWriteTool,
|
||||
WebSearchTool,
|
||||
|
||||
Reference in New Issue
Block a user