@moxxy/mode-goal 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,523 @@
1
+ import {
2
+ buildSystemPromptWithSkills,
3
+ collectProviderStream,
4
+ createStuckLoopDetector,
5
+ emitRequestsAndDetectStuck,
6
+ executeToolUses,
7
+ isContextOverflowError,
8
+ nextBackoffMs,
9
+ projectMessages,
10
+ runCompactionIfNeeded,
11
+ runElisionIfNeeded,
12
+ sleepWithAbort,
13
+ usageEventFields,
14
+ type ModeContext,
15
+ type MoxxyEvent,
16
+ type PermissionResolver,
17
+ } from '@moxxy/sdk';
18
+
19
+ import { detectGoalTerminal } from './completion.js';
20
+ import {
21
+ CONTINUE_NUDGE,
22
+ GOAL_ABANDON_TOOL,
23
+ GOAL_COMPLETE_TOOL,
24
+ GOAL_MAX_ITERATIONS,
25
+ GOAL_MAX_NOOP_ITERATIONS,
26
+ GOAL_MODE_NAME,
27
+ GOAL_PLUGIN_ID,
28
+ GOAL_SYSTEM_PROMPT,
29
+ GOAL_TOKEN_BUDGET,
30
+ MAX_CONSECUTIVE_RETRIES,
31
+ STALL_NUDGE,
32
+ } from './constants.js';
33
+
34
+ /** Exponential back-off base/cap for the retry schedule (attempt is 1-based). */
35
+ const RETRY_BACKOFF_BASE_MS = 500;
36
+ const RETRY_BACKOFF_CAP_MS = 30_000;
37
+
38
+ // Abort-aware sleep, injectable for tests so the back-off path runs instantly
39
+ // and deterministically. Production delegates to the SDK's sleepWithAbort: a
40
+ // real timer that clears (and drops its abort listener) when the signal fires,
41
+ // so a pending back-off never outlives a cancelled goal run.
42
+ let sleepImpl = (ms: number, signal: AbortSignal): Promise<void> => sleepWithAbort(ms, signal);
43
+
44
+ /**
45
+ * Override the retry back-off sleep (test seam). Returns a restore fn that
46
+ * callers MUST invoke (in a `finally`) — `sleepImpl` is a module-scoped
47
+ * singleton shared process-wide, so a leaked override bleeds the fake sleep
48
+ * into every other turn/test running in the same worker. Test-only.
49
+ */
50
+ export function __setRetrySleepForTests(
51
+ fn: (ms: number, signal: AbortSignal) => Promise<void>,
52
+ ): () => void {
53
+ const prev = sleepImpl;
54
+ sleepImpl = fn;
55
+ return () => {
56
+ sleepImpl = prev;
57
+ };
58
+ }
59
+
60
+ /**
61
+ * Goal mode driver.
62
+ *
63
+ * Unlike tool-use (which returns the instant the model stops emitting tools),
64
+ * goal mode treats "stopped emitting tools" as a cue to re-prompt: it keeps
65
+ * the model working autonomously across iterations until the model explicitly
66
+ * calls `goal_complete` (success) or `goal_abandon` (blocked). Every iteration
67
+ * is guarded so the loop always terminates:
68
+ *
69
+ * - hard iteration cap (`maxIterations`)
70
+ * - cumulative token budget
71
+ * - stuck-loop detector (same identical-call detection as tool-use)
72
+ * - no-progress detection (repeated idle iterations → stall stop)
73
+ * - `ctx.signal.aborted` checked every iteration and mid tool batch
74
+ *
75
+ * Tool calls are auto-approved for the whole run (the user opted into full
76
+ * autonomy) by swapping in a resolver that replaces only the PROMPT path:
77
+ * the session resolver's prompt-free `policyCheck` (user deny/allow rules
78
+ * from ~/.moxxy/permissions.json plus tool-declared rules) is consulted
79
+ * first, so a configured deny rule still denies here. Every call also still
80
+ * flows through `dispatchToolCall`, so tool-call HOOKS (e.g. a security
81
+ * plugin) still run and can deny. Auto-approve skips the prompt, not the
82
+ * policy.
83
+ */
84
+ export async function* runGoalMode(ctx: ModeContext): AsyncIterable<MoxxyEvent> {
85
+ if (ctx.signal.aborted) {
86
+ yield await ctx.emit({
87
+ type: 'abort',
88
+ sessionId: ctx.sessionId,
89
+ turnId: ctx.turnId,
90
+ source: 'system',
91
+ reason: 'aborted before goal mode start',
92
+ });
93
+ return;
94
+ }
95
+
96
+ // Auto-approve for the duration of the run — the user chose to let goal
97
+ // mode run unattended, so nothing may ever block on an interactive prompt.
98
+ // But ONLY the prompt is skipped: the session resolver's prompt-free
99
+ // `policyCheck` (deny/allow rules from ~/.moxxy/permissions.json, then the
100
+ // tool's own declared rule) is consulted first, so a user deny rule still
101
+ // denies in goal mode. Anything the policy doesn't decide is allowed.
102
+ // Scoped to goalCtx so it never leaks past this loop.
103
+ const sessionResolver = ctx.permissions;
104
+ const autoApprove: PermissionResolver = {
105
+ name: 'goal-auto-approve',
106
+ check: async (call, permCtx) => {
107
+ const policy = (await sessionResolver.policyCheck?.(call, permCtx)) ?? null;
108
+ if (policy) return policy;
109
+ return { mode: 'allow', reason: 'goal mode runs tools unattended (auto-approve)' };
110
+ },
111
+ };
112
+ const goalCtx: ModeContext = {
113
+ ...ctx,
114
+ systemPrompt: composeSystemPrompts(ctx.systemPrompt, GOAL_SYSTEM_PROMPT),
115
+ permissions: autoApprove,
116
+ };
117
+
118
+ yield await ctx.emit({
119
+ type: 'plugin_event',
120
+ sessionId: ctx.sessionId,
121
+ turnId: ctx.turnId,
122
+ source: 'plugin',
123
+ pluginId: GOAL_PLUGIN_ID,
124
+ subtype: 'goal_started',
125
+ payload: { autoApprove: true, maxIterations: ctx.maxIterations ?? GOAL_MAX_ITERATIONS },
126
+ });
127
+
128
+ const detector = createStuckLoopDetector(ctx.loopGuard);
129
+ // Coerce a caller/config-supplied bound to a positive integer. A degenerate
130
+ // value (0, negative, NaN, fractional) would otherwise make the for-loop
131
+ // never run and fall straight to the "iteration cap reached" fatal — work was
132
+ // never done, yet the message blames the model. The config schema validates
133
+ // this as a positive int, but programmatic callers (subagents/workflows)
134
+ // bypass that schema. Un-coercible (NaN) falls back to the default.
135
+ const requestedMaxIterations = ctx.maxIterations;
136
+ const maxIterations =
137
+ typeof requestedMaxIterations === 'number' && Number.isFinite(requestedMaxIterations)
138
+ ? Math.max(1, Math.floor(requestedMaxIterations))
139
+ : GOAL_MAX_ITERATIONS;
140
+ let noop = 0; // consecutive idle (no-tool) iterations
141
+ let totalTokens = 0;
142
+ let reactiveCompactions = 0;
143
+ const MAX_REACTIVE_COMPACTIONS = 2;
144
+ // Consecutive retryable-error count; reset on any clean provider call. Caps
145
+ // the busy-loop a sustained retryable condition (429 / overloaded / transient
146
+ // 5xx / ECONNRESET) would otherwise create — goal mode runs unattended with
147
+ // auto-approval, so a tight retry loop hammers the provider with nobody
148
+ // watching. The token budget can't backstop this: a request that errors
149
+ // before message_end reports no usage, so totalTokens never advances.
150
+ let consecutiveRetries = 0;
151
+
152
+ for (let iteration = 1; iteration <= maxIterations; iteration++) {
153
+ if (ctx.signal.aborted) {
154
+ yield await ctx.emit({
155
+ type: 'abort',
156
+ sessionId: ctx.sessionId,
157
+ turnId: ctx.turnId,
158
+ source: 'system',
159
+ reason: 'signal aborted',
160
+ });
161
+ return;
162
+ }
163
+
164
+ yield await ctx.emit({
165
+ type: 'mode_iteration',
166
+ sessionId: ctx.sessionId,
167
+ turnId: ctx.turnId,
168
+ source: 'system',
169
+ strategy: GOAL_MODE_NAME,
170
+ iteration,
171
+ });
172
+
173
+ await runCompactionIfNeeded(goalCtx);
174
+ await runElisionIfNeeded(goalCtx);
175
+
176
+ // Nudge only when the model went idle last iteration (no tool calls and no
177
+ // completion). After a productive iteration the tool results carry the
178
+ // model forward on their own — no nudge needed.
179
+ const nudge =
180
+ noop === 0 ? undefined : noop >= GOAL_MAX_NOOP_ITERATIONS - 1 ? STALL_NUDGE : CONTINUE_NUDGE;
181
+
182
+ const baseSystem = buildSystemPromptWithSkills(goalCtx.systemPrompt, goalCtx.skills.list()) ?? '';
183
+ const { messages, stablePrefixIndex } = projectMessages(goalCtx, {
184
+ ...(baseSystem ? { systemPrompt: baseSystem } : {}),
185
+ ...(nudge ? { trailingUserText: nudge } : {}),
186
+ });
187
+
188
+ yield await ctx.emit({
189
+ type: 'provider_request',
190
+ sessionId: ctx.sessionId,
191
+ turnId: ctx.turnId,
192
+ source: 'system',
193
+ provider: goalCtx.provider.name,
194
+ model: goalCtx.model,
195
+ });
196
+
197
+ const { text, toolUses, stopReason, error, usage, reasoning } = await collectProviderStream(
198
+ goalCtx,
199
+ messages,
200
+ {
201
+ iteration,
202
+ stablePrefixIndex,
203
+ // The nudge is volatile — injected for this call only, never appended
204
+ // to the log — so the cache strategy must keep its rolling tail
205
+ // breakpoint BEFORE it. Otherwise every idle iteration caches a
206
+ // prefix ending in a message that won't exist at that position next
207
+ // call: a guaranteed-wasted cache write.
208
+ ...(nudge ? { volatileTailCount: 1 } : {}),
209
+ },
210
+ );
211
+
212
+ yield await ctx.emit({
213
+ type: 'provider_response',
214
+ sessionId: ctx.sessionId,
215
+ turnId: ctx.turnId,
216
+ source: 'system',
217
+ provider: goalCtx.provider.name,
218
+ model: goalCtx.model,
219
+ ...usageEventFields(usage),
220
+ });
221
+
222
+ // Tally the FULL prompt of each call. Anthropic reports the cached portion
223
+ // separately (`inputTokens` is only the non-cached prefix), so on a long
224
+ // goal run — where the rolling cache breakpoint serves most of the prompt
225
+ // as cacheRead — counting input+output alone undercounts by a large factor
226
+ // and the runaway-budget backstop could be exceeded many times over before
227
+ // it trips. Include both cache fields so the budget reflects real usage.
228
+ if (usage)
229
+ totalTokens +=
230
+ (usage.inputTokens ?? 0) +
231
+ (usage.cacheReadTokens ?? 0) +
232
+ (usage.cacheCreationTokens ?? 0) +
233
+ (usage.outputTokens ?? 0);
234
+
235
+ if (error) {
236
+ const overflow = isContextOverflowError(error.message);
237
+ if (overflow && reactiveCompactions < MAX_REACTIVE_COMPACTIONS) {
238
+ const compacted = await runCompactionIfNeeded(goalCtx, { force: true });
239
+ if (compacted) {
240
+ // Only count an attempt that actually compacted — a no-op (overflow
241
+ // lives in the un-compactable recent tail) must not deny a later,
242
+ // genuinely compactable overflow its retry.
243
+ reactiveCompactions += 1;
244
+ yield await ctx.emit({
245
+ type: 'error',
246
+ sessionId: ctx.sessionId,
247
+ turnId: ctx.turnId,
248
+ source: 'system',
249
+ kind: 'retryable',
250
+ message: 'context window exceeded — compacted older turns, retrying',
251
+ });
252
+ continue;
253
+ }
254
+ }
255
+ // A context overflow that can't be compacted further is fatal regardless
256
+ // of the provider's `retryable` flag: some providers mark "reduce the
257
+ // length" errors retryable, but the prompt cannot shrink, so a retry just
258
+ // re-sends the identical over-budget request and overflows again — a tight
259
+ // loop bounded only by maxIterations (the request errors before usage is
260
+ // reported, so the token budget never advances to stop it).
261
+ const fatal = !error.retryable || overflow;
262
+ if (fatal) {
263
+ yield await ctx.emit({
264
+ type: 'error',
265
+ sessionId: ctx.sessionId,
266
+ turnId: ctx.turnId,
267
+ source: 'system',
268
+ kind: 'fatal',
269
+ message: `goal: ${error.message}`,
270
+ });
271
+ return;
272
+ }
273
+ // Retryable: surface it, then back off before retrying. A persistent
274
+ // retryable condition (sustained 429 / outage) must NOT busy-loop the
275
+ // provider — give up with a fatal error after the bounded retry count.
276
+ // The counter resets on any clean provider call, so a long run can still
277
+ // recover from transient blips.
278
+ consecutiveRetries += 1;
279
+ yield await ctx.emit({
280
+ type: 'error',
281
+ sessionId: ctx.sessionId,
282
+ turnId: ctx.turnId,
283
+ source: 'system',
284
+ kind: 'retryable',
285
+ message: `goal: ${error.message}`,
286
+ });
287
+ if (consecutiveRetries >= MAX_CONSECUTIVE_RETRIES) {
288
+ yield await ctx.emit({
289
+ type: 'error',
290
+ sessionId: ctx.sessionId,
291
+ turnId: ctx.turnId,
292
+ source: 'system',
293
+ kind: 'fatal',
294
+ message:
295
+ `goal: provider kept returning a retryable error ${consecutiveRetries} times in a row ` +
296
+ `(last: ${error.message}); giving up rather than hammering the provider.`,
297
+ });
298
+ return;
299
+ }
300
+ await sleepImpl(
301
+ nextBackoffMs(consecutiveRetries, RETRY_BACKOFF_BASE_MS, RETRY_BACKOFF_CAP_MS),
302
+ ctx.signal,
303
+ );
304
+ if (ctx.signal.aborted) {
305
+ yield await ctx.emit({
306
+ type: 'abort',
307
+ sessionId: ctx.sessionId,
308
+ turnId: ctx.turnId,
309
+ source: 'system',
310
+ reason: 'signal aborted during retry back-off',
311
+ });
312
+ return;
313
+ }
314
+ continue;
315
+ }
316
+ // Clean provider call — reset the overflow-recovery + retry budgets.
317
+ reactiveCompactions = 0;
318
+ consecutiveRetries = 0;
319
+
320
+ // Finalize the reasoning summary for THIS call before any exit decision or
321
+ // tool/assistant emit, so the log order is reasoning → tool_use → text
322
+ // (projection attaches the signed thinking block as content[0] of the same
323
+ // turn). Emitting it ahead of the budget backstop keeps every exit path
324
+ // consistent — the budget-exhausting call's reasoning is logged just like
325
+ // any other call's, rather than being silently dropped at this exit.
326
+ if (reasoning) {
327
+ yield await ctx.emit({
328
+ type: 'reasoning_message',
329
+ sessionId: ctx.sessionId,
330
+ turnId: ctx.turnId,
331
+ source: 'model',
332
+ content: reasoning.text,
333
+ ...(reasoning.signature ? { signature: reasoning.signature } : {}),
334
+ ...(reasoning.redacted ? { redacted: true } : {}),
335
+ ...(reasoning.encrypted ? { encrypted: reasoning.encrypted } : {}),
336
+ });
337
+ }
338
+
339
+ // Token budget backstop (alongside the iteration cap).
340
+ if (totalTokens > GOAL_TOKEN_BUDGET) {
341
+ // Persist the budget-exhausting call's assistant text before exiting,
342
+ // just like every productive iteration does (the assistant emit below
343
+ // this block is skipped by the `return`). Otherwise the model's last
344
+ // words vanish from the log, so a resume ("continue from here") loses
345
+ // that context. We do NOT execute its tool calls — the run is stopping.
346
+ if (text || stopReason === 'end_turn' || toolUses.length === 0) {
347
+ yield await ctx.emit({
348
+ type: 'assistant_message',
349
+ sessionId: ctx.sessionId,
350
+ turnId: ctx.turnId,
351
+ source: 'model',
352
+ content: text,
353
+ stopReason,
354
+ });
355
+ }
356
+ yield await ctx.emit({
357
+ type: 'plugin_event',
358
+ sessionId: ctx.sessionId,
359
+ turnId: ctx.turnId,
360
+ source: 'plugin',
361
+ pluginId: GOAL_PLUGIN_ID,
362
+ subtype: 'goal_budget_exhausted',
363
+ payload: { totalTokens, budget: GOAL_TOKEN_BUDGET, iteration },
364
+ });
365
+ yield await ctx.emit({
366
+ type: 'assistant_message',
367
+ sessionId: ctx.sessionId,
368
+ turnId: ctx.turnId,
369
+ source: 'system',
370
+ content:
371
+ `Goal mode stopped: token budget exhausted (${totalTokens.toLocaleString()} > ` +
372
+ `${GOAL_TOKEN_BUDGET.toLocaleString()}) before the goal was completed. ` +
373
+ `Send another message to continue from here.`,
374
+ stopReason: 'end_turn',
375
+ });
376
+ return;
377
+ }
378
+
379
+ const stuck = yield* emitRequestsAndDetectStuck(ctx, toolUses, detector, {
380
+ abortedResultMessage: 'goal mode aborted (stuck pattern) before this call ran',
381
+ nearHint: 'against the same target (only volatile args varied)',
382
+ extraOnStuck: ({ toolName, count, kind }) => [
383
+ {
384
+ type: 'plugin_event',
385
+ sessionId: ctx.sessionId,
386
+ turnId: ctx.turnId,
387
+ source: 'plugin',
388
+ pluginId: GOAL_PLUGIN_ID,
389
+ subtype: 'goal_stuck',
390
+ payload: { tool: toolName, count, kind },
391
+ },
392
+ ],
393
+ fatalMessage: ({ toolName, count, how }) =>
394
+ `goal mode aborted — stuck pattern: tool "${toolName}" called ${count} times ${how}. ` +
395
+ `The model is looping on the same call; send another message to redirect it.`,
396
+ });
397
+ if (stuck) return;
398
+
399
+ if (text || stopReason === 'end_turn' || toolUses.length === 0) {
400
+ yield await ctx.emit({
401
+ type: 'assistant_message',
402
+ sessionId: ctx.sessionId,
403
+ turnId: ctx.turnId,
404
+ source: 'model',
405
+ content: text,
406
+ stopReason,
407
+ });
408
+ }
409
+
410
+ if (toolUses.length === 0) {
411
+ // The model idled without calling goal_complete. Count it; nudge next
412
+ // iteration. After enough idle rounds, stop rather than spin forever.
413
+ noop += 1;
414
+ if (noop >= GOAL_MAX_NOOP_ITERATIONS) {
415
+ yield await ctx.emit({
416
+ type: 'plugin_event',
417
+ sessionId: ctx.sessionId,
418
+ turnId: ctx.turnId,
419
+ source: 'plugin',
420
+ pluginId: GOAL_PLUGIN_ID,
421
+ subtype: 'goal_stalled',
422
+ payload: { idleIterations: noop, iteration },
423
+ });
424
+ yield await ctx.emit({
425
+ type: 'assistant_message',
426
+ sessionId: ctx.sessionId,
427
+ turnId: ctx.turnId,
428
+ source: 'system',
429
+ content:
430
+ 'Goal mode stopped: the model went idle without calling `goal_complete`. ' +
431
+ 'It may believe the goal is done — review the work above, and send another message to continue if not.',
432
+ stopReason: 'end_turn',
433
+ });
434
+ return;
435
+ }
436
+ continue;
437
+ }
438
+ noop = 0;
439
+
440
+ const exited = yield* executeToolUses(goalCtx, toolUses, iteration);
441
+ if (exited) return;
442
+
443
+ // Did this batch end the run? (goal_complete / goal_abandon, confirmed via
444
+ // a successful tool_result in the log.) Only materialise the log (an O(n)
445
+ // copy of the ever-growing append-only log) when the batch actually used a
446
+ // goal tool — otherwise this ran on every productive iteration, O(n²) per
447
+ // run. detectGoalTerminal itself early-returns null on an empty batch, so a
448
+ // batch with no goal tools needs no log at all.
449
+ const hasGoalTool = toolUses.some(
450
+ (t) => t.name === GOAL_COMPLETE_TOOL || t.name === GOAL_ABANDON_TOOL,
451
+ );
452
+ const terminal = hasGoalTool ? detectGoalTerminal(ctx.log.slice(), toolUses) : null;
453
+ if (terminal?.kind === 'complete') {
454
+ yield await ctx.emit({
455
+ type: 'plugin_event',
456
+ sessionId: ctx.sessionId,
457
+ turnId: ctx.turnId,
458
+ source: 'plugin',
459
+ pluginId: GOAL_PLUGIN_ID,
460
+ subtype: 'goal_completed',
461
+ payload: { summary: terminal.summary, evidenceCount: terminal.evidence.length, iterations: iteration },
462
+ });
463
+ const evidenceBlock =
464
+ terminal.evidence.length > 0 ? `\n\n${terminal.evidence.map((e) => `- ${e}`).join('\n')}` : '';
465
+ yield await ctx.emit({
466
+ type: 'assistant_message',
467
+ sessionId: ctx.sessionId,
468
+ turnId: ctx.turnId,
469
+ source: 'system',
470
+ content: `✓ Goal complete — ${terminal.summary}${evidenceBlock}`,
471
+ stopReason: 'end_turn',
472
+ });
473
+ return;
474
+ }
475
+ if (terminal?.kind === 'abandon') {
476
+ yield await ctx.emit({
477
+ type: 'plugin_event',
478
+ sessionId: ctx.sessionId,
479
+ turnId: ctx.turnId,
480
+ source: 'plugin',
481
+ pluginId: GOAL_PLUGIN_ID,
482
+ subtype: 'goal_abandoned',
483
+ payload: { reason: terminal.reason, ...(terminal.needsFromUser ? { needsFromUser: terminal.needsFromUser } : {}), iterations: iteration },
484
+ });
485
+ const needs = terminal.needsFromUser ? `\n\nNeeds from you: ${terminal.needsFromUser}` : '';
486
+ yield await ctx.emit({
487
+ type: 'assistant_message',
488
+ sessionId: ctx.sessionId,
489
+ turnId: ctx.turnId,
490
+ source: 'system',
491
+ content: `Goal abandoned — ${terminal.reason}${needs}`,
492
+ stopReason: 'end_turn',
493
+ });
494
+ return;
495
+ }
496
+ }
497
+
498
+ // Iteration cap hit without the model declaring done.
499
+ yield await ctx.emit({
500
+ type: 'plugin_event',
501
+ sessionId: ctx.sessionId,
502
+ turnId: ctx.turnId,
503
+ source: 'plugin',
504
+ pluginId: GOAL_PLUGIN_ID,
505
+ subtype: 'goal_max_iterations',
506
+ payload: { maxIterations },
507
+ });
508
+ yield await ctx.emit({
509
+ type: 'error',
510
+ sessionId: ctx.sessionId,
511
+ turnId: ctx.turnId,
512
+ source: 'system',
513
+ kind: 'fatal',
514
+ message:
515
+ `goal mode reached the iteration cap (${maxIterations}) without calling goal_complete. ` +
516
+ `Stopping to avoid an unbounded run; send another message to continue.`,
517
+ });
518
+ }
519
+
520
+ function composeSystemPrompts(user: string | undefined, layer: string): string {
521
+ if (!user || user.trim() === '') return layer;
522
+ return `${layer}\n\n---\n\n${user}`;
523
+ }
@@ -0,0 +1,61 @@
1
+ import { defineTool } from '@moxxy/sdk';
2
+ import { z } from 'zod';
3
+
4
+ import { GOAL_ABANDON_TOOL, GOAL_COMPLETE_TOOL } from './constants.js';
5
+
6
+ /**
7
+ * The goal "utility": two side-effect-free tools the model calls to control the
8
+ * goal loop. They don't DO anything — calling them is the signal. The loop in
9
+ * `goal-loop.ts` watches for their (successful) tool_result and terminates.
10
+ *
11
+ * They're registered globally by the plugin, so they exist in every mode, but
12
+ * only goal mode's system prompt tells the model to use them; elsewhere they're
13
+ * inert. `permission: { action: 'allow' }` means they never trip a permission
14
+ * prompt — declaring done is not a privileged action.
15
+ */
16
+
17
+ export const goalCompleteTool = defineTool({
18
+ name: GOAL_COMPLETE_TOOL,
19
+ description:
20
+ 'Declare the goal FULLY ACHIEVED and end goal mode. Call this only after you have verified the work. ' +
21
+ 'Provide a short summary and concrete evidence (commands run + results, files changed, tests that passed). ' +
22
+ 'This is the only way to end a goal-mode run successfully.',
23
+ inputSchema: z.object({
24
+ summary: z.string().min(1).describe('One- or two-sentence summary of what was accomplished.'),
25
+ evidence: z
26
+ .array(z.string())
27
+ .optional()
28
+ .describe('Concrete proof the goal is met: commands run and their results, files changed, tests passed.'),
29
+ }),
30
+ permission: { action: 'allow' },
31
+ handler: (input) => {
32
+ const { summary, evidence } = input as { summary: string; evidence?: string[] };
33
+ return {
34
+ acknowledged: true,
35
+ summary,
36
+ evidenceCount: evidence?.length ?? 0,
37
+ };
38
+ },
39
+ });
40
+
41
+ export const goalAbandonTool = defineTool({
42
+ name: GOAL_ABANDON_TOOL,
43
+ description:
44
+ 'Give up on the goal because you are genuinely blocked — a missing credential, a destructive action you ' +
45
+ 'should not take unattended, or a requirement too ambiguous to proceed. Provide the reason and exactly what ' +
46
+ 'you need from the user. This ends goal mode without claiming success.',
47
+ inputSchema: z.object({
48
+ reason: z.string().min(1).describe('Why you cannot proceed.'),
49
+ needsFromUser: z
50
+ .string()
51
+ .optional()
52
+ .describe('What the user must provide or decide for the goal to continue.'),
53
+ }),
54
+ permission: { action: 'allow' },
55
+ handler: (input) => {
56
+ const { reason, needsFromUser } = input as { reason: string; needsFromUser?: string };
57
+ return { acknowledged: true, reason, ...(needsFromUser ? { needsFromUser } : {}) };
58
+ },
59
+ });
60
+
61
+ export const goalTools = [goalCompleteTool, goalAbandonTool];