|
| 1 | +import { z } from 'zod/v4' |
| 2 | +import { buildTool, type ToolDef } from 'src/Tool.js' |
| 3 | +import { jsonStringify } from 'src/utils/slowOperations.js' |
| 4 | +import { lazySchema } from 'src/utils/lazySchema.js' |
| 5 | +import { |
| 6 | + completeGoal, |
| 7 | + formatGoalElapsed, |
| 8 | + formatGoalStatusLabel, |
| 9 | + getGoal, |
| 10 | + recordBlockedAttempt, |
| 11 | +} from 'src/services/goal/goalState.js' |
| 12 | +import { persistCurrentGoal } from 'src/services/goal/goalStorage.js' |
| 13 | +import { GOAL_TOOL_NAME } from './constants.js' |
| 14 | +import { DESCRIPTION, generatePrompt } from './prompt.js' |
| 15 | + |
| 16 | +function toolLog(msg: string): void { |
| 17 | + try { |
| 18 | + const { logForDebugging } = |
| 19 | + require('src/utils/debug.js') as typeof import('src/utils/debug.js') |
| 20 | + logForDebugging(`[goal] tool: ${msg}`) |
| 21 | + } catch { |
| 22 | + /* debug not available */ |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +const inputSchema = lazySchema(() => |
| 27 | + z.strictObject({ |
| 28 | + action: z |
| 29 | + .enum(['get', 'update']) |
| 30 | + .optional() |
| 31 | + .describe( |
| 32 | + 'Action to perform: "get" to read status, "update" to mark complete or blocked. Defaults to "update" if status is provided, otherwise "get".', |
| 33 | + ), |
| 34 | + status: z |
| 35 | + .enum(['complete', 'blocked']) |
| 36 | + .optional() |
| 37 | + .describe( |
| 38 | + 'Required for "update". Only "complete" or "blocked" are accepted.', |
| 39 | + ), |
| 40 | + reason: z |
| 41 | + .string() |
| 42 | + .optional() |
| 43 | + .describe('Explanation for the status change. Required for "update".'), |
| 44 | + }), |
| 45 | +) |
| 46 | +type InputSchema = ReturnType<typeof inputSchema> |
| 47 | + |
| 48 | +const outputSchema = lazySchema(() => |
| 49 | + z.object({ |
| 50 | + success: z.boolean(), |
| 51 | + goal: z |
| 52 | + .object({ |
| 53 | + objective: z.string(), |
| 54 | + status: z.string(), |
| 55 | + tokensUsed: z.number(), |
| 56 | + tokenBudget: z.number().nullable(), |
| 57 | + elapsed: z.string(), |
| 58 | + turnsExecuted: z.number(), |
| 59 | + }) |
| 60 | + .optional(), |
| 61 | + message: z.string().optional(), |
| 62 | + report: z.string().optional(), |
| 63 | + error: z.string().optional(), |
| 64 | + }), |
| 65 | +) |
| 66 | +type OutputSchema = ReturnType<typeof outputSchema> |
| 67 | + |
| 68 | +export type Input = z.infer<InputSchema> |
| 69 | +export type Output = z.infer<OutputSchema> |
| 70 | + |
| 71 | +function buildGoalSnapshot() { |
| 72 | + const goal = getGoal() |
| 73 | + if (!goal) return undefined |
| 74 | + return { |
| 75 | + objective: goal.objective, |
| 76 | + status: formatGoalStatusLabel(goal.status), |
| 77 | + tokensUsed: goal.tokensUsed, |
| 78 | + tokenBudget: goal.tokenBudget, |
| 79 | + elapsed: formatGoalElapsed(goal), |
| 80 | + turnsExecuted: goal.turnsExecuted, |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +function buildCompletionReport(): string { |
| 85 | + const goal = getGoal() |
| 86 | + if (!goal) return '' |
| 87 | + const budget = |
| 88 | + goal.tokenBudget !== null |
| 89 | + ? `Token usage: ${goal.tokensUsed} / ${goal.tokenBudget}` |
| 90 | + : `Token usage: ${goal.tokensUsed}` |
| 91 | + return [ |
| 92 | + 'Goal achieved — usage report:', |
| 93 | + ` ${budget}`, |
| 94 | + ` Active time: ${formatGoalElapsed(goal)}`, |
| 95 | + ` Continuation turns: ${goal.turnsExecuted}`, |
| 96 | + ].join('\n') |
| 97 | +} |
| 98 | + |
| 99 | +export const GoalTool = buildTool({ |
| 100 | + name: GOAL_TOOL_NAME, |
| 101 | + searchHint: 'get or update the active goal (complete/blocked)', |
| 102 | + maxResultSizeChars: 10_000, |
| 103 | + async description() { |
| 104 | + return DESCRIPTION |
| 105 | + }, |
| 106 | + async prompt() { |
| 107 | + return generatePrompt() |
| 108 | + }, |
| 109 | + get inputSchema(): InputSchema { |
| 110 | + return inputSchema() |
| 111 | + }, |
| 112 | + get outputSchema(): OutputSchema { |
| 113 | + return outputSchema() |
| 114 | + }, |
| 115 | + userFacingName() { |
| 116 | + return 'Goal' |
| 117 | + }, |
| 118 | + shouldDefer: true, |
| 119 | + isConcurrencySafe() { |
| 120 | + return true |
| 121 | + }, |
| 122 | + isReadOnly(input: Input) { |
| 123 | + const action = input.action ?? (input.status ? 'update' : 'get') |
| 124 | + return action === 'get' |
| 125 | + }, |
| 126 | + toAutoClassifierInput(input: Input) { |
| 127 | + const action = input.action ?? (input.status ? 'update' : 'get') |
| 128 | + if (action === 'get') return 'get goal status' |
| 129 | + return `update goal: ${input.status} — ${input.reason ?? ''}` |
| 130 | + }, |
| 131 | + async checkPermissions(input: Input) { |
| 132 | + return { behavior: 'allow' as const, updatedInput: input } |
| 133 | + }, |
| 134 | + renderToolUseMessage(input: Input) { |
| 135 | + const action = input.action ?? (input.status ? 'update' : 'get') |
| 136 | + if (action === 'get') return 'Checking goal status…' |
| 137 | + return `Updating goal: ${input.status}${input.reason ? ` — ${input.reason}` : ''}` |
| 138 | + }, |
| 139 | + renderToolResultMessage(output: Output) { |
| 140 | + if (output.error) return `Goal error: ${output.error}` |
| 141 | + if (output.report) return output.report |
| 142 | + if (output.goal) { |
| 143 | + return `Goal "${output.goal.objective}" — ${output.goal.status}` |
| 144 | + } |
| 145 | + return output.message ?? 'Done' |
| 146 | + }, |
| 147 | + renderToolUseRejectedMessage() { |
| 148 | + return 'Goal operation rejected' |
| 149 | + }, |
| 150 | + async call(input: Input): Promise<{ data: Output }> { |
| 151 | + const action = input.action ?? (input.status ? 'update' : 'get') |
| 152 | + toolLog( |
| 153 | + `called: action=${action}${input.status ? ` status=${input.status}` : ''}${input.reason ? ` reason="${input.reason.slice(0, 60)}"` : ''}`, |
| 154 | + ) |
| 155 | + if (action === 'get') { |
| 156 | + const snapshot = buildGoalSnapshot() |
| 157 | + if (!snapshot) { |
| 158 | + return { |
| 159 | + data: { |
| 160 | + success: true, |
| 161 | + message: |
| 162 | + 'No active goal. The user can set one with `/goal <objective>`.', |
| 163 | + }, |
| 164 | + } |
| 165 | + } |
| 166 | + return { data: { success: true, goal: snapshot } } |
| 167 | + } |
| 168 | + |
| 169 | + // action === 'update' |
| 170 | + if (!input.status) { |
| 171 | + return { |
| 172 | + data: { |
| 173 | + success: false, |
| 174 | + error: |
| 175 | + 'The "status" field is required for update. Use "complete" or "blocked".', |
| 176 | + }, |
| 177 | + } |
| 178 | + } |
| 179 | + |
| 180 | + const goal = getGoal() |
| 181 | + if (!goal) { |
| 182 | + return { |
| 183 | + data: { |
| 184 | + success: false, |
| 185 | + error: 'No active goal to update.', |
| 186 | + }, |
| 187 | + } |
| 188 | + } |
| 189 | + |
| 190 | + if (input.status === 'complete') { |
| 191 | + const report = buildCompletionReport() |
| 192 | + completeGoal() |
| 193 | + persistCurrentGoal() |
| 194 | + return { |
| 195 | + data: { |
| 196 | + success: true, |
| 197 | + goal: buildGoalSnapshot(), |
| 198 | + report, |
| 199 | + }, |
| 200 | + } |
| 201 | + } |
| 202 | + |
| 203 | + // status === 'blocked' |
| 204 | + const reason = input.reason ?? 'unspecified blocker' |
| 205 | + const result = recordBlockedAttempt(reason) |
| 206 | + if (!result) { |
| 207 | + return { |
| 208 | + data: { |
| 209 | + success: false, |
| 210 | + error: 'Goal is not in a state that accepts blocked attempts.', |
| 211 | + }, |
| 212 | + } |
| 213 | + } |
| 214 | + persistCurrentGoal() |
| 215 | + |
| 216 | + if (result.status === 'blocked') { |
| 217 | + return { |
| 218 | + data: { |
| 219 | + success: true, |
| 220 | + goal: buildGoalSnapshot(), |
| 221 | + message: `Goal marked as blocked after ${result.attempts} consecutive attempts. Reason: ${reason}`, |
| 222 | + }, |
| 223 | + } |
| 224 | + } |
| 225 | + |
| 226 | + return { |
| 227 | + data: { |
| 228 | + success: true, |
| 229 | + goal: buildGoalSnapshot(), |
| 230 | + message: `Blocked attempt ${result.attempts} recorded. The goal remains active — the same condition must persist for 3 consecutive turns before it is marked blocked.`, |
| 231 | + }, |
| 232 | + } |
| 233 | + }, |
| 234 | + mapToolResultToToolResultBlockParam(content: Output, toolUseID: string) { |
| 235 | + if (content.error) { |
| 236 | + return { |
| 237 | + tool_use_id: toolUseID, |
| 238 | + type: 'tool_result' as const, |
| 239 | + content: `Error: ${content.error}`, |
| 240 | + is_error: true, |
| 241 | + } |
| 242 | + } |
| 243 | + const parts: string[] = [] |
| 244 | + if (content.message) parts.push(content.message) |
| 245 | + if (content.report) parts.push(content.report) |
| 246 | + if (content.goal) parts.push(jsonStringify(content.goal)) |
| 247 | + return { |
| 248 | + tool_use_id: toolUseID, |
| 249 | + type: 'tool_result' as const, |
| 250 | + content: parts.join('\n') || 'Done', |
| 251 | + } |
| 252 | + }, |
| 253 | +} satisfies ToolDef<InputSchema, Output>) |
0 commit comments