feat: 添加 /goal 命令,支持长时间运行任务的目标管理 (#1222)

* feat: 添加 /goal 命令,支持长时间运行任务的目标管理

从 Codex 项目移植 /goal 命令到 Claude Code,实现:
- Goal 状态管理模块(active/paused/budget_limited/complete)
- /goal 斜杠命令(set/clear/pause/resume/complete)
- Goal 模型工具(get/set/complete)
- Continuation prompt 自动注入系统提示
- Token 用量自动追踪

Co-Authored-By: mimo-v2.5-pro <XiaomiMiMo@claude-code-best.win>

* fix: goal 状态改为 session-scoped,避免多会话泄漏

将 currentGoal 单例替换为 Map<string, GoalState>,按 sessionId 隔离,
遵循 sessionIngress.ts 的模式。所有函数支持可选 sessionId 参数。

Co-Authored-By: mimo-v2.5-pro <XiaomiMiMo@claude-code-best.win>

* fix: 对 goal 的 tokenBudget/tokensUsed 添加数值校验

setGoal 中 tokenBudget 非 finite 或负数时归零;
updateGoalTokens 中 usage 非 finite 或负数时归零。

Co-Authored-By: mimo-v2.5-pro <XiaomiMiMo@claude-code-best.win>

* fix: 暂停期间 goal 时间不再继续计数

新增 pausedAt/accumulatedActiveMs 字段,pauseGoal 累积已活跃时间,
resumeGoal 重置 startTime,计时统一使用 getActiveElapsedMs()。

Co-Authored-By: mimo-v2.5-pro <XiaomiMiMo@claude-code-best.win>

---------

Co-authored-by: mimo-v2.5-pro <XiaomiMiMo@claude-code-best.win>
This commit is contained in:
Fearless
2026-05-17 10:05:46 +08:00
committed by GitHub
parent 48a19b8a0d
commit d66a6f6124
10 changed files with 483 additions and 0 deletions

View File

@@ -12,6 +12,7 @@ export { AskUserQuestionTool } from './tools/AskUserQuestionTool/AskUserQuestion
export { BashTool } from './tools/BashTool/BashTool.js'
export { BriefTool } from './tools/BriefTool/BriefTool.js'
export { ConfigTool } from './tools/ConfigTool/ConfigTool.js'
export { GoalTool } from './tools/GoalTool/GoalTool.js'
export { EnterPlanModeTool } from './tools/EnterPlanModeTool/EnterPlanModeTool.js'
export { EnterWorktreeTool } from './tools/EnterWorktreeTool/EnterWorktreeTool.js'
export { ExitPlanModeV2Tool } from './tools/ExitPlanModeTool/ExitPlanModeV2Tool.js'

View File

@@ -0,0 +1,212 @@
import { z } from 'zod/v4'
import { buildTool, type ToolDef } from 'src/Tool.js'
import { lazySchema } from 'src/utils/lazySchema.js'
import {
completeGoal,
formatGoalStatus,
getActiveElapsedMs,
getGoal,
setGoal,
} from 'src/services/goal/goalState.js'
import { DESCRIPTION, generatePrompt } from './prompt.js'
import type { ToolResultBlockParam } from '@anthropic-ai/sdk/resources/index.mjs'
const inputSchema = lazySchema(() =>
z.strictObject({
action: z
.enum(['get', 'set', 'complete'])
.describe('The action to perform on the goal.'),
objective: z
.string()
.optional()
.describe('The goal objective. Required for "set" action.'),
message: z
.string()
.optional()
.describe('Completion message for "complete" action.'),
}),
)
type InputSchema = ReturnType<typeof inputSchema>
const outputSchema = lazySchema(() =>
z.object({
success: z.boolean(),
action: z.string(),
goal: z
.object({
objective: z.string(),
status: z.string(),
tokensUsed: z.number(),
tokenBudget: z.number().nullable(),
elapsedSeconds: z.number(),
})
.optional(),
message: z.string().optional(),
error: z.string().optional(),
}),
)
type OutputSchema = ReturnType<typeof outputSchema>
export type Input = z.infer<InputSchema>
export type Output = z.infer<OutputSchema>
export const GoalTool = buildTool({
name: 'goal',
searchHint: 'manage long-running task goals',
maxResultSizeChars: 10_000,
async description() {
return DESCRIPTION
},
async prompt() {
return generatePrompt()
},
get inputSchema(): InputSchema {
return inputSchema()
},
get outputSchema(): OutputSchema {
return outputSchema()
},
userFacingName() {
return 'Goal'
},
shouldDefer: true,
isConcurrencySafe() {
return true
},
isReadOnly(input: Input) {
return input.action === 'get'
},
toAutoClassifierInput(input) {
if (input.action === 'get') return 'get goal status'
if (input.action === 'set') return `set goal: ${input.objective}`
return `complete goal: ${input.message ?? ''}`
},
async checkPermissions(input: Input) {
if (input.action === 'get') {
return { behavior: 'allow' as const, updatedInput: input }
}
return {
behavior: 'ask' as const,
message:
input.action === 'set'
? `Set goal: ${input.objective}`
: `Complete goal${input.message ? `: ${input.message}` : ''}`,
}
},
async call({ action, objective, message }: Input): Promise<{ data: Output }> {
if (action === 'get') {
const goal = getGoal()
if (!goal) {
return { data: { success: true, action, message: 'No active goal.' } }
}
const elapsedSeconds = Math.floor(getActiveElapsedMs(goal) / 1000)
return {
data: {
success: true,
action,
goal: {
objective: goal.objective,
status: goal.status,
tokensUsed: goal.tokensUsed,
tokenBudget: goal.tokenBudget,
elapsedSeconds,
},
},
}
}
if (action === 'set') {
if (!objective) {
return {
data: {
success: false,
action,
error: 'objective is required for set action.',
},
}
}
setGoal(objective)
return {
data: {
success: true,
action,
message: `Goal set: ${objective}`,
goal: {
objective,
status: 'active',
tokensUsed: 0,
tokenBudget: null,
elapsedSeconds: 0,
},
},
}
}
if (action === 'complete') {
if (!completeGoal()) {
return {
data: {
success: false,
action,
error: 'No active goal to complete.',
},
}
}
return {
data: {
success: true,
action,
message: message
? `Goal completed: ${message}`
: 'Goal marked as complete.',
},
}
}
return {
data: { success: false, action, error: `Unknown action: ${action}` },
}
},
renderToolUseMessage(input: Partial<Input>) {
if (input.action === 'get') return 'Getting goal status'
if (input.action === 'set') return `Setting goal: ${input.objective ?? ''}`
if (input.action === 'complete') return 'Completing goal'
return 'Managing goal'
},
renderToolResultMessage(content: Output) {
if (!content.success) return `Error: ${content.error}`
if (content.action === 'get' && content.goal) {
const g = content.goal
return `Goal: ${g.objective} [${g.status}]`
}
return content.message ?? 'Done.'
},
mapToolResultToToolResultBlockParam(
content: Output,
toolUseID: string,
): ToolResultBlockParam {
if (!content.success) {
return {
tool_use_id: toolUseID,
type: 'tool_result' as const,
content: `Error: ${content.error}`,
is_error: true,
}
}
if (content.action === 'get' && content.goal) {
const g = content.goal
return {
tool_use_id: toolUseID,
type: 'tool_result' as const,
content: `Goal: ${g.objective}\nStatus: ${g.status}\nTokens: ${g.tokensUsed}${g.tokenBudget !== null ? ` / ${g.tokenBudget}` : ''}\nElapsed: ${g.elapsedSeconds}s`,
}
}
return {
tool_use_id: toolUseID,
type: 'tool_result' as const,
content: content.message ?? 'Done.',
}
},
} satisfies ToolDef<InputSchema, Output>)

View File

@@ -0,0 +1,18 @@
export const DESCRIPTION = 'Manage the active goal for long-running tasks.'
export function generatePrompt(): string {
return `Manage the active goal for long-running tasks.
Use this tool to get, set, or complete a goal. A goal is an objective that the system tracks across the session, injecting continuation prompts to keep working toward it.
## Actions
- **get** — Get the current goal status
- **set** — Set or update the goal objective
- **complete** — Mark the goal as complete when the objective is achieved
## Examples
- Get current goal: { "action": "get" }
- Set a goal: { "action": "set", "objective": "Improve test coverage to 80%" }
- Complete a goal: { "action": "complete", "message": "All tests now pass with 82% coverage." }
`
}