Files
claude-code/src/commands.ts
claude-code-best 084e487943 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>
2026-06-20 19:52:08 +08:00

851 lines
28 KiB
TypeScript

// biome-ignore-all assist/source/organizeImports: ANT-ONLY import markers must not be reordered
import addDir from './commands/add-dir/index.js'
import autofixPr from './commands/autofix-pr/index.js'
import backfillSessions from './commands/backfill-sessions/index.js'
import btw from './commands/btw/index.js'
import goodClaude from './commands/good-claude/index.js'
import issue from './commands/issue/index.js'
import feedback from './commands/feedback/index.js'
import clear from './commands/clear/index.js'
import color from './commands/color/index.js'
import commit from './commands/commit.js'
import copy from './commands/copy/index.js'
import desktop from './commands/desktop/index.js'
import commitPushPr from './commands/commit-push-pr.js'
import compact from './commands/compact/index.js'
import config from './commands/config/index.js'
import { context, contextNonInteractive } from './commands/context/index.js'
// cost/index.ts re-exports usage — /cost is now an alias of /usage
import diff from './commands/diff/index.js'
import doctor from './commands/doctor/index.js'
import memory from './commands/memory/index.js'
import mode from './commands/mode/index.js'
import help from './commands/help/index.js'
import ide from './commands/ide/index.js'
import init from './commands/init.js'
import initVerifiers from './commands/init-verifiers.js'
import keybindings from './commands/keybindings/index.js'
import lang from './commands/lang/index.js'
import login from './commands/login/index.js'
import logout from './commands/logout/index.js'
import installGitHubApp from './commands/install-github-app/index.js'
import installSlackApp from './commands/install-slack-app/index.js'
import breakCache, {
breakCacheNonInteractive,
} from './commands/break-cache/index.js'
import mcp from './commands/mcp/index.js'
import mobile from './commands/mobile/index.js'
import onboarding from './commands/onboarding/index.js'
import pr_comments from './commands/pr_comments/index.js'
import releaseNotes from './commands/release-notes/index.js'
import rename from './commands/rename/index.js'
import resume from './commands/resume/index.js'
import review, { ultrareview } from './commands/review.js'
import session from './commands/session/index.js'
import share from './commands/share/index.js'
import skills from './commands/skills/index.js'
import status from './commands/status/index.js'
import tasks from './commands/tasks/index.js'
import teleport from './commands/teleport/index.js'
import agentsPlatform from './commands/agents-platform/index.js'
import scheduleCommand from './commands/schedule/index.js'
import memoryStoresCommand from './commands/memory-stores/index.js'
import skillStoreCommand from './commands/skill-store/index.js'
import vaultCommand from './commands/vault/index.js'
import localVaultCommand from './commands/local-vault/index.js'
import localMemoryCommand from './commands/local-memory/index.js'
import securityReview from './commands/security-review.js'
import bughunter from './commands/bughunter/index.js'
import terminalSetup from './commands/terminalSetup/index.js'
import usage from './commands/usage/index.js'
import theme from './commands/theme/index.js'
import vim from './commands/vim/index.js'
import webTools from './commands/web-tools/index.js'
import { feature } from 'bun:bundle'
// Dead code elimination: conditional imports
/* eslint-disable @typescript-eslint/no-require-imports */
const proactive =
feature('PROACTIVE') || feature('KAIROS')
? require('./commands/proactive.js').default
: null
const briefCommand =
feature('KAIROS') || feature('KAIROS_BRIEF')
? require('./commands/brief.js').default
: null
const assistantCommand = feature('KAIROS')
? require('./commands/assistant/index.js').default
: null
const bridge = feature('BRIDGE_MODE')
? require('./commands/bridge/index.js').default
: null
const remoteControlServerCommand = feature('BRIDGE_MODE')
? require('./commands/remoteControlServer/index.js').default
: null
const voiceCommand = feature('VOICE_MODE')
? require('./commands/voice/index.js').default
: null
const monitorCmd = feature('MONITOR_TOOL')
? require('./commands/monitor.js').default
: null
const coordinatorCmd = feature('COORDINATOR_MODE')
? require('./commands/coordinator.js').default
: null
const forceSnip = feature('HISTORY_SNIP')
? require('./commands/force-snip.js').default
: null
const workflowsCmd = feature('WORKFLOW_SCRIPTS')
? (
require('./commands/workflows/index.js') as typeof import('./commands/workflows/index.js')
).default
: null
const webCmd = feature('CCR_REMOTE_SETUP')
? (
require('./commands/remote-setup/index.js') as typeof import('./commands/remote-setup/index.js')
).default
: null
const clearSkillIndexCache = feature('EXPERIMENTAL_SKILL_SEARCH')
? (
require('./services/skillSearch/localSearch.js') as typeof import('./services/skillSearch/localSearch.js')
).clearSkillIndexCache
: null
const subscribePr = feature('KAIROS_GITHUB_WEBHOOKS')
? require('./commands/subscribe-pr.js').default
: null
const ultraplan = feature('ULTRAPLAN')
? require('./commands/ultraplan.js').default
: null
const torch = feature('TORCH') ? require('./commands/torch.js').default : null
const daemonCmd =
feature('DAEMON') || feature('BG_SESSIONS')
? require('./commands/daemon/index.js').default
: null
const jobCmd = feature('TEMPLATES')
? require('./commands/job/index.js').default
: null
const peersCmd = feature('UDS_INBOX')
? (
require('./commands/peers/index.js') as typeof import('./commands/peers/index.js')
).default
: null
const attachCmd = feature('UDS_INBOX')
? require('./commands/attach/index.js').default
: null
const detachCmd = feature('UDS_INBOX')
? require('./commands/detach/index.js').default
: null
const sendCmd = feature('UDS_INBOX')
? require('./commands/send/index.js').default
: null
const pipesCmd = feature('UDS_INBOX')
? require('./commands/pipes/index.js').default
: null
const pipeStatusCmd = feature('UDS_INBOX')
? require('./commands/pipe-status/index.js').default
: null
const historyCmd = feature('UDS_INBOX')
? require('./commands/history/index.js').default
: null
const claimMainCmd = feature('UDS_INBOX')
? require('./commands/claim-main/index.js').default
: null
const forkCmd = feature('FORK_SUBAGENT')
? (
require('./commands/fork/index.js') as typeof import('./commands/fork/index.js')
).default
: null
const buddy = feature('BUDDY')
? (
require('./commands/buddy/index.js') as typeof import('./commands/buddy/index.js')
).default
: null
const poor = feature('POOR')
? (
require('./commands/poor/index.js') as typeof import('./commands/poor/index.js')
).default
: null
const goalCmd = feature('GOAL')
? (
require('./commands/goal/index.js') as typeof import('./commands/goal/index.js')
).default
: null
/* eslint-enable @typescript-eslint/no-require-imports */
import thinkback from './commands/thinkback/index.js'
import thinkbackPlay from './commands/thinkback-play/index.js'
import permissions from './commands/permissions/index.js'
import plan from './commands/plan/index.js'
import fast from './commands/fast/index.js'
import passes from './commands/passes/index.js'
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'
import rewind from './commands/rewind/index.js'
import heapDump from './commands/heapdump/index.js'
import mockLimits from './commands/mock-limits/index.js'
import bridgeKick from './commands/bridge-kick.js'
import version from './commands/version.js'
import summary from './commands/summary/index.js'
import recap from './commands/recap/index.js'
import skillLearning from './commands/skill-learning/index.js'
import skillSearch from './commands/skill-search/index.js'
import {
resetLimits,
resetLimitsNonInteractive,
} from './commands/reset-limits/index.js'
import antTrace from './commands/ant-trace/index.js'
import perfIssue from './commands/perf-issue/index.js'
import sandboxToggle from './commands/sandbox-toggle/index.js'
import tui, { tuiNonInteractive } from './commands/tui/index.js'
import chrome from './commands/chrome/index.js'
import stickers from './commands/stickers/index.js'
import advisor from './commands/advisor.js'
import autonomy from './commands/autonomy.js'
import provider from './commands/provider.js'
import { logError } from './utils/log.js'
import { toError } from './utils/errors.js'
import { logForDebugging } from './utils/debug.js'
import {
getSkillDirCommands,
clearSkillCaches,
getDynamicSkills,
} from './skills/loadSkillsDir.js'
import { getBundledSkills } from './skills/bundledSkills.js'
import { getBuiltinPluginSkillCommands } from './plugins/builtinPlugins.js'
import {
getPluginCommands,
clearPluginCommandCache,
getPluginSkills,
clearPluginSkillsCache,
} from './utils/plugins/loadPluginCommands.js'
import memoize from 'lodash-es/memoize.js'
import { isUsing3PServices, isClaudeAISubscriber } from './utils/auth.js'
import { isFirstPartyAnthropicBaseUrl } from './utils/model/providers.js'
import env from './commands/env/index.js'
import exit from './commands/exit/index.js'
import exportCommand from './commands/export/index.js'
import model from './commands/model/index.js'
import tag from './commands/tag/index.js'
import outputStyle from './commands/output-style/index.js'
import remoteEnv from './commands/remote-env/index.js'
import upgrade from './commands/upgrade/index.js'
import {
extraUsage,
extraUsageNonInteractive,
} from './commands/extra-usage/index.js'
import rateLimitOptions from './commands/rate-limit-options/index.js'
import statusline from './commands/statusline.js'
import effort from './commands/effort/index.js'
// stats/index.ts re-exports usage — /stats is now an alias of /usage
// insights.ts is 113KB (3200 lines, includes diffLines/html rendering). Lazy
// shim defers the heavy module until /insights is actually invoked.
const usageReport: Command = {
type: 'prompt',
name: 'insights',
description: 'Generate a report analyzing your Claude Code sessions',
contentLength: 0,
progressMessage: 'analyzing your sessions',
source: 'builtin',
async getPromptForCommand(args, context) {
const real = (await import('./commands/insights.js')).default
if (real.type !== 'prompt') throw new Error('unreachable')
return real.getPromptForCommand(args, context)
},
}
import oauthRefresh from './commands/oauth-refresh/index.js'
import debugToolCall from './commands/debug-tool-call/index.js'
import { getSettingSourceName } from './utils/settings/constants.js'
import {
type Command,
getCommandName,
isCommandEnabled,
} from './types/command.js'
// Re-export types from the centralized location
export type {
Command,
CommandBase,
CommandResultDisplay,
LocalCommandResult,
LocalJSXCommandContext,
PromptCommand,
ResumeEntrypoint,
} from './types/command.js'
export { getCommandName, isCommandEnabled } from './types/command.js'
// Commands that get eliminated from the external build
// Public-but-previously-locked commands moved to the main COMMANDS array below:
// commit, commitPushPr, bridgeKick, initVerifiers, autofixPr, onboarding
// Remaining items here are truly Anthropic-internal (admin/diagnostics endpoints
// with no fork backend), so they only show up under USER_TYPE=ant.
export const INTERNAL_ONLY_COMMANDS = [
backfillSessions,
bughunter,
goodClaude,
mockLimits,
resetLimits,
resetLimitsNonInteractive,
antTrace,
oauthRefresh,
].filter(Boolean)
// Declared as a function so that we don't run this until getCommands is called,
// since underlying functions read from config, which can't be read at module initialization time
const COMMANDS = memoize((): Command[] => [
addDir,
advisor,
agentsPlatform,
scheduleCommand,
memoryStoresCommand,
skillStoreCommand,
vaultCommand,
localVaultCommand,
localMemoryCommand,
autonomy,
provider,
artifacts,
agents,
branch,
btw,
chrome,
clear,
color,
compact,
config,
copy,
desktop,
context,
contextNonInteractive,
diff,
doctor,
effort,
exit,
fast,
files,
heapDump,
help,
ide,
init,
keybindings,
lang,
installGitHubApp,
installSlackApp,
mcp,
memory,
mobile,
mode,
model,
outputStyle,
remoteEnv,
plugin,
pr_comments,
releaseNotes,
reloadPlugins,
rename,
resume,
session,
skills,
status,
statusline,
stickers,
tag,
theme,
feedback,
review,
ultrareview,
rewind,
securityReview,
terminalSetup,
upgrade,
extraUsage,
extraUsageNonInteractive,
rateLimitOptions,
usage,
usageReport,
vim,
webTools,
...(webCmd ? [webCmd] : []),
...(forkCmd ? [forkCmd] : []),
...(buddy ? [buddy] : []),
...(poor ? [poor] : []),
...(goalCmd ? [goalCmd] : []),
...(proactive ? [proactive] : []),
...(monitorCmd ? [monitorCmd] : []),
...(coordinatorCmd ? [coordinatorCmd] : []),
...(briefCommand ? [briefCommand] : []),
...(assistantCommand ? [assistantCommand] : []),
...(bridge ? [bridge] : []),
...(remoteControlServerCommand ? [remoteControlServerCommand] : []),
...(voiceCommand ? [voiceCommand] : []),
thinkback,
thinkbackPlay,
permissions,
plan,
privacySettings,
hooks,
exportCommand,
sandboxToggle,
...(!isUsing3PServices() ? [logout, login()] : []),
passes,
...(peersCmd ? [peersCmd] : []),
...(attachCmd ? [attachCmd] : []),
...(detachCmd ? [detachCmd] : []),
...(sendCmd ? [sendCmd] : []),
...(pipesCmd ? [pipesCmd] : []),
...(pipeStatusCmd ? [pipeStatusCmd] : []),
...(historyCmd ? [historyCmd] : []),
...(claimMainCmd ? [claimMainCmd] : []),
tasks,
...(workflowsCmd ? [workflowsCmd] : []),
...(ultraplan ? [ultraplan] : []),
...(torch ? [torch] : []),
...(daemonCmd ? [daemonCmd] : []),
...(jobCmd ? [jobCmd] : []),
...(forceSnip ? [forceSnip] : []),
summary,
recap,
skillLearning,
skillSearch,
autofixPr,
commit,
commitPushPr,
bridgeKick,
version,
...(subscribePr ? [subscribePr] : []),
initVerifiers,
env,
debugToolCall,
perfIssue,
breakCache,
breakCacheNonInteractive,
issue,
share,
teleport,
tui,
tuiNonInteractive,
onboarding,
...(process.env.USER_TYPE === 'ant' && !process.env.IS_DEMO
? INTERNAL_ONLY_COMMANDS
: []),
])
export const builtInCommandNames = memoize(
(): Set<string> =>
new Set(COMMANDS().flatMap(_ => [_.name, ...(_.aliases ?? [])])),
)
async function getSkills(cwd: string): Promise<{
skillDirCommands: Command[]
pluginSkills: Command[]
bundledSkills: Command[]
builtinPluginSkills: Command[]
}> {
try {
const [skillDirCommands, pluginSkills] = await Promise.all([
getSkillDirCommands(cwd).catch(err => {
logError(toError(err))
logForDebugging(
'Skill directory commands failed to load, continuing without them',
)
return []
}),
getPluginSkills().catch(err => {
logError(toError(err))
logForDebugging('Plugin skills failed to load, continuing without them')
return []
}),
])
// Bundled skills are registered synchronously at startup
const bundledSkills = getBundledSkills()
// Built-in plugin skills come from enabled built-in plugins
const builtinPluginSkills = getBuiltinPluginSkillCommands()
logForDebugging(
`getSkills returning: ${skillDirCommands.length} skill dir commands, ${pluginSkills.length} plugin skills, ${bundledSkills.length} bundled skills, ${builtinPluginSkills.length} builtin plugin skills`,
)
return {
skillDirCommands,
pluginSkills,
bundledSkills,
builtinPluginSkills,
}
} catch (err) {
// This should never happen since we catch at the Promise level, but defensive
logError(toError(err))
logForDebugging('Unexpected error in getSkills, returning empty')
return {
skillDirCommands: [],
pluginSkills: [],
bundledSkills: [],
builtinPluginSkills: [],
}
}
}
/* eslint-disable @typescript-eslint/no-require-imports */
const getWorkflowCommands = feature('WORKFLOW_SCRIPTS')
? (
require('./workflow/namedWorkflowCommands.js') as typeof import('./workflow/namedWorkflowCommands.js')
).getWorkflowCommands
: null
/* eslint-enable @typescript-eslint/no-require-imports */
/**
* Filters commands by their declared `availability` (auth/provider requirement).
* Commands without `availability` are treated as universal.
* This runs before `isEnabled()` so that provider-gated commands are hidden
* regardless of feature-flag state.
*
* Not memoized — auth state can change mid-session (e.g. after /login),
* so this must be re-evaluated on every getCommands() call.
*/
export function meetsAvailabilityRequirement(cmd: Command): boolean {
if (!cmd.availability || cmd.availability.length === 0) return true
for (const a of cmd.availability) {
switch (a) {
case 'claude-ai':
if (isClaudeAISubscriber()) return true
break
case 'console':
// Console API key user = direct 1P API customer (not 3P, not claude.ai).
// Excludes 3P (Bedrock/Vertex/Foundry) who don't set ANTHROPIC_BASE_URL
// and gateway users who proxy through a custom base URL.
if (
!isClaudeAISubscriber() &&
!isUsing3PServices() &&
isFirstPartyAnthropicBaseUrl()
)
return true
break
default: {
const _exhaustive: never = a
void _exhaustive
break
}
}
}
return false
}
/**
* Loads all command sources (skills, plugins, workflows). Memoized by cwd
* because loading is expensive (disk I/O, dynamic imports).
*/
const loadAllCommands = memoize(async (cwd: string): Promise<Command[]> => {
const [
{ skillDirCommands, pluginSkills, bundledSkills, builtinPluginSkills },
pluginCommands,
workflowCommands,
] = await Promise.all([
getSkills(cwd),
getPluginCommands(),
getWorkflowCommands ? getWorkflowCommands(cwd) : Promise.resolve([]),
])
return [
...bundledSkills,
...builtinPluginSkills,
...skillDirCommands,
...(workflowCommands as Command[]),
...(pluginCommands as Command[]),
...pluginSkills,
...COMMANDS(),
]
})
/**
* Returns commands available to the current user. The expensive loading is
* memoized, but availability and isEnabled checks run fresh every call so
* auth changes (e.g. /login) take effect immediately.
*/
export async function getCommands(cwd: string): Promise<Command[]> {
const allCommands = await loadAllCommands(cwd)
// Get dynamic skills discovered during file operations
const dynamicSkills = getDynamicSkills()
// Build base commands without dynamic skills
const baseCommands = allCommands.filter(
_ => meetsAvailabilityRequirement(_) && isCommandEnabled(_),
)
if (dynamicSkills.length === 0) {
return baseCommands
}
// Dedupe dynamic skills - only add if not already present
const baseCommandNames = new Set(baseCommands.map(c => c.name))
const uniqueDynamicSkills = dynamicSkills.filter(
s =>
!baseCommandNames.has(s.name) &&
meetsAvailabilityRequirement(s) &&
isCommandEnabled(s),
)
if (uniqueDynamicSkills.length === 0) {
return baseCommands
}
// Insert dynamic skills after plugin skills but before built-in commands
const builtInNames = new Set(COMMANDS().map(c => c.name))
const insertIndex = baseCommands.findIndex(c => builtInNames.has(c.name))
if (insertIndex === -1) {
return [...baseCommands, ...uniqueDynamicSkills]
}
return [
...baseCommands.slice(0, insertIndex),
...uniqueDynamicSkills,
...baseCommands.slice(insertIndex),
]
}
/**
* Clears only the memoization caches for commands, WITHOUT clearing skill caches.
* Use this when dynamic skills are added to invalidate cached command lists.
*/
export function clearCommandMemoizationCaches(): void {
loadAllCommands.cache?.clear?.()
getSkillToolCommands.cache?.clear?.()
getSlashCommandToolSkills.cache?.clear?.()
// getSkillIndex in skillSearch/localSearch.ts is a separate memoization layer
// built ON TOP of getSkillToolCommands/getCommands. Clearing only the inner
// caches is a no-op for the outer — lodash memoize returns the cached result
// without ever reaching the cleared inners. Must clear it explicitly.
clearSkillIndexCache?.()
}
export function clearCommandsCache(): void {
clearCommandMemoizationCaches()
clearPluginCommandCache()
clearPluginSkillsCache()
clearSkillCaches()
}
/**
* Filter AppState.mcp.commands to MCP-provided skills (prompt-type,
* model-invocable, loaded from MCP). These live outside getCommands() so
* callers that need MCP skills in their skill index thread them through
* separately.
*/
export function getMcpSkillCommands(
mcpCommands: readonly Command[],
): readonly Command[] {
if (feature('MCP_SKILLS')) {
return mcpCommands.filter(
cmd =>
cmd.type === 'prompt' &&
cmd.loadedFrom === 'mcp' &&
!cmd.disableModelInvocation,
)
}
return []
}
// SkillTool shows ALL prompt-based commands that the model can invoke
// This includes both skills (from /skills/) and commands (from /commands/)
export const getSkillToolCommands = memoize(
async (cwd: string): Promise<Command[]> => {
const allCommands = await getCommands(cwd)
return allCommands.filter(
cmd =>
cmd.type === 'prompt' &&
!cmd.disableModelInvocation &&
cmd.source !== 'builtin' &&
// Always include skills from /skills/ dirs, bundled skills, and legacy /commands/ entries
// (they all get an auto-derived description from the first line if frontmatter is missing).
// Plugin/MCP commands still require an explicit description to appear in the listing.
(cmd.loadedFrom === 'bundled' ||
cmd.loadedFrom === 'skills' ||
cmd.loadedFrom === 'commands_DEPRECATED' ||
cmd.hasUserSpecifiedDescription ||
cmd.whenToUse),
)
},
)
// Filters commands to include only skills. Skills are commands that provide
// specialized capabilities for the model to use. They are identified by
// loadedFrom being 'skills', 'plugin', or 'bundled', or having disableModelInvocation set.
export const getSlashCommandToolSkills = memoize(
async (cwd: string): Promise<Command[]> => {
try {
const allCommands = await getCommands(cwd)
return allCommands.filter(
cmd =>
cmd.type === 'prompt' &&
cmd.source !== 'builtin' &&
(cmd.hasUserSpecifiedDescription || cmd.whenToUse) &&
(cmd.loadedFrom === 'skills' ||
cmd.loadedFrom === 'plugin' ||
cmd.loadedFrom === 'bundled' ||
cmd.disableModelInvocation),
)
} catch (error) {
logError(toError(error))
// Return empty array rather than throwing - skills are non-critical
// This prevents skill loading failures from breaking the entire system
logForDebugging('Returning empty skills array due to load failure')
return []
}
},
)
/**
* Commands that are safe to use in remote mode (--remote).
* These only affect local TUI state and don't depend on local filesystem,
* git, shell, IDE, MCP, or other local execution context.
*
* Used in two places:
* 1. Pre-filtering commands in main.tsx before REPL renders (prevents race with CCR init)
* 2. Preserving local-only commands in REPL's handleRemoteInit after CCR filters
*/
export const REMOTE_SAFE_COMMANDS: Set<Command> = new Set([
session, // Shows QR code / URL for remote session
exit, // Exit the TUI
clear, // Clear screen
help, // Show help
theme, // Change terminal theme
color, // Change agent color
vim, // Toggle vim mode
usage, // Show session cost, plan usage, and activity stats (/cost and /stats are aliases)
copy, // Copy last message
btw, // Quick note
feedback, // Send feedback
plan, // Plan mode toggle
proactive, // Toggle proactive mode
keybindings, // Keybinding management
statusline, // Status line toggle
stickers, // Stickers
mobile, // Mobile QR code
])
/**
* Builtin commands of type 'local' that ARE safe to execute when received
* over the Remote Control bridge. These produce text output that streams
* back to the mobile/web client and have no terminal-only side effects.
*
* 'local-jsx' commands are blocked by type (they render Ink UI) and
* 'prompt' commands are allowed by type (they expand to text sent to the
* model) — this set only gates 'local' commands.
*
* When adding a new 'local' command that should work from mobile, add it
* here. Default is blocked.
*/
export const BRIDGE_SAFE_COMMANDS: Set<Command> = new Set(
[
compact, // Shrink context — useful mid-session from a phone
clear, // Wipe transcript
usage, // Show session cost (/cost alias)
summary, // Summarize conversation
releaseNotes, // Show changelog
files, // List tracked files
].filter((c): c is Command => c !== null),
)
/**
* Whether a slash command is safe to execute when its input arrived over the
* Remote Control bridge (mobile/web client).
*
* PR #19134 blanket-blocked all slash commands from bridge inbound because
* `/model` from iOS was popping the local Ink picker. This predicate relaxes
* that with an explicit allowlist: 'prompt' commands (skills) expand to text
* and are safe by construction; 'local' commands need an explicit opt-in via
* BRIDGE_SAFE_COMMANDS; 'local-jsx' commands render Ink UI and stay blocked.
*/
export function isBridgeSafeCommand(cmd: Command): boolean {
if (cmd.type === 'local-jsx') return cmd.bridgeSafe === true
if (cmd.type === 'prompt') return true
return cmd.bridgeSafe === true || BRIDGE_SAFE_COMMANDS.has(cmd)
}
export function getBridgeCommandSafety(
cmd: Command,
args: string,
): { ok: true } | { ok: false; reason?: string } {
if (!isBridgeSafeCommand(cmd)) return { ok: false }
const reason = cmd.getBridgeInvocationError?.(args)
return reason ? { ok: false, reason } : { ok: true }
}
/**
* Filter commands to only include those safe for remote mode.
* Used to pre-filter commands when rendering the REPL in --remote mode,
* preventing local-only commands from being briefly available before
* the CCR init message arrives.
*/
export function filterCommandsForRemoteMode(commands: Command[]): Command[] {
return commands.filter(cmd => REMOTE_SAFE_COMMANDS.has(cmd))
}
export function findCommand(
commandName: string,
commands: Command[],
): Command | undefined {
return commands.find(
_ =>
_.name === commandName ||
getCommandName(_) === commandName ||
_.aliases?.includes(commandName),
)
}
export function hasCommand(commandName: string, commands: Command[]): boolean {
return findCommand(commandName, commands) !== undefined
}
export function getCommand(commandName: string, commands: Command[]): Command {
const command = findCommand(commandName, commands)
if (!command) {
throw ReferenceError(
`Command ${commandName} not found. Available commands: ${commands
.map(_ => {
const name = getCommandName(_)
return _.aliases ? `${name} (aliases: ${_.aliases.join(', ')})` : name
})
.sort((a, b) => a.localeCompare(b))
.join(', ')}`,
)
}
return command
}
/**
* Formats a command's description with its source annotation for user-facing UI.
* Use this in typeahead, help screens, and other places where users need to see
* where a command comes from.
*
* For model-facing prompts (like SkillTool), use cmd.description directly.
*/
export function formatDescriptionWithSource(cmd: Command): string {
if (cmd.type !== 'prompt') {
return cmd.description
}
if (cmd.kind === 'workflow') {
return `${cmd.description} (workflow)`
}
if (cmd.source === 'plugin') {
const pluginName = cmd.pluginInfo?.pluginManifest.name
if (pluginName) {
return `(${pluginName}) ${cmd.description}`
}
return `${cmd.description} (plugin)`
}
if (cmd.source === 'builtin' || cmd.source === 'mcp') {
return cmd.description
}
if (cmd.source === 'bundled') {
return `${cmd.description} (bundled)`
}
return `${cmd.description} (${getSettingSourceName(cmd.source)})`
}