@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.
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "@moxxy/mode-goal",
3
+ "version": "0.26.0",
4
+ "description": "Goal mode: state a goal once and the agent works autonomously across many turns until it calls goal_complete (or goal_abandon), guarded by an iteration cap, a token budget, a stuck-loop detector, no-progress detection, and the user's abort.",
5
+ "keywords": [
6
+ "moxxy",
7
+ "agent",
8
+ "mode",
9
+ "autonomous",
10
+ "goal"
11
+ ],
12
+ "homepage": "https://moxxy.ai",
13
+ "bugs": {
14
+ "url": "https://github.com/moxxy-ai/moxxy/issues"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/moxxy-ai/moxxy.git",
19
+ "directory": "packages/mode-goal"
20
+ },
21
+ "author": "Michal Makowski <michal.makowski97@gmail.com>",
22
+ "license": "MIT",
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "type": "module",
27
+ "main": "./dist/index.js",
28
+ "types": "./dist/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.js"
33
+ }
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "src"
38
+ ],
39
+ "moxxy": {
40
+ "plugin": {
41
+ "entry": "./dist/index.js",
42
+ "kind": "mode"
43
+ }
44
+ },
45
+ "dependencies": {
46
+ "zod": "^3.24.0",
47
+ "@moxxy/sdk": "0.26.0"
48
+ },
49
+ "devDependencies": {
50
+ "@types/node": "^22.10.0",
51
+ "typescript": "^5.7.3",
52
+ "vitest": "^2.1.8",
53
+ "@moxxy/tsconfig": "0.0.0",
54
+ "@moxxy/core": "0.26.0",
55
+ "@moxxy/vitest-preset": "0.0.0",
56
+ "@moxxy/testing": "0.0.44"
57
+ },
58
+ "scripts": {
59
+ "build": "tsc -p tsconfig.json",
60
+ "typecheck": "tsc -p tsconfig.json --noEmit",
61
+ "test": "vitest run",
62
+ "test:watch": "vitest",
63
+ "clean": "rm -rf dist .turbo"
64
+ }
65
+ }
@@ -0,0 +1,68 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import type { CollectedToolUse, MoxxyEvent } from '@moxxy/sdk';
3
+
4
+ import { detectGoalTerminal } from './completion.js';
5
+ import { GOAL_ABANDON_TOOL, GOAL_COMPLETE_TOOL } from './constants.js';
6
+
7
+ // Minimal tool_result stand-in — detectGoalTerminal only reads type/ok/callId.
8
+ function result(callId: string, ok: boolean): MoxxyEvent {
9
+ return { type: 'tool_result', callId, ok } as unknown as MoxxyEvent;
10
+ }
11
+ function use(id: string, name: string, input: unknown): CollectedToolUse {
12
+ return { id, name, input };
13
+ }
14
+
15
+ describe('detectGoalTerminal', () => {
16
+ it('returns null when the batch has no goal tools', () => {
17
+ const log = [result('c1', true)];
18
+ expect(detectGoalTerminal(log, [use('c1', 'Bash', {})])).toBeNull();
19
+ });
20
+
21
+ it('detects a successful goal_complete and parses summary + evidence', () => {
22
+ const batch = [use('c1', GOAL_COMPLETE_TOOL, { summary: 'shipped', evidence: ['tests pass', 'built'] })];
23
+ const out = detectGoalTerminal([result('c1', true)], batch);
24
+ expect(out).toEqual({ kind: 'complete', summary: 'shipped', evidence: ['tests pass', 'built'] });
25
+ });
26
+
27
+ it('detects goal_abandon with reason + needsFromUser', () => {
28
+ const batch = [use('c2', GOAL_ABANDON_TOOL, { reason: 'missing key', needsFromUser: 'set API_KEY' })];
29
+ const out = detectGoalTerminal([result('c2', true)], batch);
30
+ expect(out).toEqual({ kind: 'abandon', reason: 'missing key', needsFromUser: 'set API_KEY' });
31
+ });
32
+
33
+ it('ignores a goal tool whose result failed (e.g. hook-denied)', () => {
34
+ const batch = [use('c3', GOAL_COMPLETE_TOOL, { summary: 'x' })];
35
+ expect(detectGoalTerminal([result('c3', false)], batch)).toBeNull();
36
+ });
37
+
38
+ it('only reacts to its OWN call ids (not a same-name result from elsewhere)', () => {
39
+ const batch = [use('c4', GOAL_COMPLETE_TOOL, { summary: 'x' })];
40
+ // A successful result exists, but for a different callId.
41
+ expect(detectGoalTerminal([result('other', true)], batch)).toBeNull();
42
+ });
43
+
44
+ it('defaults summary/reason when the model omitted them', () => {
45
+ const out = detectGoalTerminal([result('c5', true)], [use('c5', GOAL_COMPLETE_TOOL, {})]);
46
+ expect(out).toEqual({ kind: 'complete', summary: 'Goal completed.', evidence: [] });
47
+ });
48
+
49
+ it('drops non-string evidence elements from raw (unvalidated) model input', () => {
50
+ // `input` is the RAW provider-emitted tool input — the model can put
51
+ // anything in `evidence`. Non-string elements must be filtered out, not
52
+ // unsafely cast to string[].
53
+ const batch = [
54
+ use('c6', GOAL_COMPLETE_TOOL, {
55
+ summary: 'done',
56
+ evidence: ['tests pass', 1, { a: 1 }, null, 'built'],
57
+ }),
58
+ ];
59
+ const out = detectGoalTerminal([result('c6', true)], batch);
60
+ expect(out).toEqual({ kind: 'complete', summary: 'done', evidence: ['tests pass', 'built'] });
61
+ });
62
+
63
+ it('coerces a non-string summary to the default', () => {
64
+ const batch = [use('c7', GOAL_COMPLETE_TOOL, { summary: 42, evidence: [] })];
65
+ const out = detectGoalTerminal([result('c7', true)], batch);
66
+ expect(out).toEqual({ kind: 'complete', summary: 'Goal completed.', evidence: [] });
67
+ });
68
+ });
@@ -0,0 +1,55 @@
1
+ import type { CollectedToolUse, MoxxyEvent } from '@moxxy/sdk';
2
+
3
+ import { GOAL_ABANDON_TOOL, GOAL_COMPLETE_TOOL } from './constants.js';
4
+
5
+ export type GoalTerminal =
6
+ | { kind: 'complete'; summary: string; evidence: string[] }
7
+ | { kind: 'abandon'; reason: string; needsFromUser?: string }
8
+ | null;
9
+
10
+ /**
11
+ * Inspect a just-executed batch of tool uses for a terminal goal signal. We
12
+ * confirm against the event log that the goal tool's `tool_result` actually
13
+ * succeeded (`ok: true`) — a hook could in principle have denied the call — so
14
+ * a denied goal_complete doesn't silently end the run. Returns the parsed
15
+ * payload (pulled from the model's tool INPUT, which is what it intended) so
16
+ * the caller can surface a clean summary.
17
+ */
18
+ export function detectGoalTerminal(
19
+ log: ReadonlyArray<MoxxyEvent>,
20
+ batch: ReadonlyArray<CollectedToolUse>,
21
+ ): GoalTerminal {
22
+ // Map callId -> the goal tool use, so we only react to OUR tools.
23
+ const goalCalls = new Map<string, CollectedToolUse>();
24
+ for (const t of batch) {
25
+ if (t.name === GOAL_COMPLETE_TOOL || t.name === GOAL_ABANDON_TOOL) goalCalls.set(t.id, t);
26
+ }
27
+ if (goalCalls.size === 0) return null;
28
+
29
+ // Walk the log tail for the most recent successful result of one of those.
30
+ for (let i = log.length - 1; i >= 0; i--) {
31
+ const e = log[i];
32
+ if (!e || e.type !== 'tool_result' || !e.ok) continue;
33
+ const call = goalCalls.get(String(e.callId));
34
+ if (!call) continue;
35
+ const input = (call.input ?? {}) as Record<string, unknown>;
36
+ if (call.name === GOAL_COMPLETE_TOOL) {
37
+ return {
38
+ kind: 'complete',
39
+ summary: typeof input.summary === 'string' ? input.summary : 'Goal completed.',
40
+ // `input` is the RAW provider-emitted tool input (pre-zod), so the model
41
+ // can put anything in `evidence`. Keep only the string elements rather
42
+ // than asserting the type with an unchecked cast.
43
+ evidence: Array.isArray(input.evidence)
44
+ ? input.evidence.filter((x): x is string => typeof x === 'string')
45
+ : [],
46
+ };
47
+ }
48
+ return {
49
+ kind: 'abandon',
50
+ reason: typeof input.reason === 'string' ? input.reason : 'Goal abandoned.',
51
+ ...(typeof input.needsFromUser === 'string' ? { needsFromUser: input.needsFromUser } : {}),
52
+ };
53
+ }
54
+ return null;
55
+ }
@@ -0,0 +1,75 @@
1
+ import { asPluginId } from '@moxxy/sdk';
2
+
3
+ export const GOAL_MODE_NAME = 'goal';
4
+ export const GOAL_PLUGIN_ID = asPluginId('@moxxy/mode-goal');
5
+
6
+ /** Tool the model MUST call to declare the goal achieved (the terminator). */
7
+ export const GOAL_COMPLETE_TOOL = 'goal_complete';
8
+ /** Tool the model calls to give up gracefully (blocked, needs the user). */
9
+ export const GOAL_ABANDON_TOOL = 'goal_abandon';
10
+
11
+ /**
12
+ * Hard cap on autonomous iterations. Goal mode keeps re-prompting the model to
13
+ * continue until it calls {@link GOAL_COMPLETE_TOOL}; this is the backstop that
14
+ * guarantees the loop terminates even if the model never declares done. High
15
+ * enough for a substantial multi-step task, low enough to bound a runaway.
16
+ */
17
+ export const GOAL_MAX_ITERATIONS = 150;
18
+
19
+ /**
20
+ * Consecutive iterations where the model emits NO tool calls and hasn't
21
+ * completed. After this many we stop (a stall) rather than spin forever
22
+ * nudging a model that has decided it's done without saying so.
23
+ */
24
+ export const GOAL_MAX_NOOP_ITERATIONS = 3;
25
+
26
+ /**
27
+ * Cumulative token ceiling (full prompt — input + cacheRead + cacheCreation +
28
+ * output — across the whole goal run). A second backstop alongside the
29
+ * iteration cap: a few long-context iterations can burn a lot of tokens even
30
+ * under the iteration limit. Generous; the iteration cap is usually the binding
31
+ * guard.
32
+ */
33
+ export const GOAL_TOKEN_BUDGET = 4_000_000;
34
+
35
+ /**
36
+ * Max consecutive retryable provider errors before goal mode bails with a fatal
37
+ * error. Goal mode runs unattended with auto-approval, so a sustained retryable
38
+ * condition (429 / overloaded / transient 5xx / ECONNRESET) must NOT busy-loop
39
+ * the provider — back off exponentially and give up after this many in a row.
40
+ * The counter resets on any clean provider call, so a long run can still
41
+ * recover from transient blips.
42
+ */
43
+ export const MAX_CONSECUTIVE_RETRIES = 6;
44
+
45
+ /**
46
+ * Layered on top of any user system prompt for the whole goal run. The framing
47
+ * is the inverse of normal chat: stopping is NOT the signal to end — the model
48
+ * keeps going until it explicitly calls goal_complete. It runs unattended with
49
+ * tool calls auto-approved, so it must be conservative about irreversible
50
+ * actions and decisive about declaring done.
51
+ */
52
+ export const GOAL_SYSTEM_PROMPT = `You are operating in GOAL MODE. The user has given you a goal and you will work on it AUTONOMOUSLY, across as many steps as it takes, until it is genuinely done. You are running unattended — the user is not watching each step and your tool calls are auto-approved — so act like a careful senior engineer who has been handed the keys.
53
+
54
+ How goal mode ends — this is the most important rule:
55
+ - The loop does NOT end when you stop talking. It ends ONLY when you call the \`${GOAL_COMPLETE_TOOL}\` tool. If you produce a message without tool calls, you will simply be prompted to continue.
56
+ - When (and only when) the goal is FULLY achieved AND you have verified it, call \`${GOAL_COMPLETE_TOOL}\` with a short summary and concrete evidence (commands you ran and their results, files you changed, tests that passed).
57
+ - If you become genuinely blocked — a missing credential, a destructive action you shouldn't take unattended, or a requirement too ambiguous to proceed on — call \`${GOAL_ABANDON_TOOL}\` with the reason and exactly what you need from the user. Do NOT spin on something you cannot resolve.
58
+
59
+ While working:
60
+ - Break the goal into steps and just do them — don't stop to ask for confirmation on routine work; you have autonomy for this run.
61
+ - Verify your work as you go (run the project's tests / build / linter when relevant) before declaring the goal complete.
62
+ - Be careful with irreversible or destructive operations (deleting data, force-pushing, external side effects). When something is high-stakes and reversible-only-by-the-user, prefer to \`${GOAL_ABANDON_TOOL}\` and ask rather than guess.
63
+ - Don't repeat the same failing action. If an approach isn't working, change it; if nothing works, abandon with a clear explanation.
64
+ - Don't declare the goal complete prematurely. "I think this should work" is not done — verify first.`;
65
+
66
+ /** Trailing nudge appended when the model idles (no tool calls) without
67
+ * completing — reminds it the loop only ends via the completion tool. */
68
+ export const CONTINUE_NUDGE =
69
+ `You stopped without calling \`${GOAL_COMPLETE_TOOL}\`. If the goal is fully achieved AND verified, ` +
70
+ `call \`${GOAL_COMPLETE_TOOL}\` now. Otherwise, take the next concrete step toward it.`;
71
+
72
+ /** Sharper nudge once the model has idled repeatedly. */
73
+ export const STALL_NUDGE =
74
+ `You have produced no tool calls for several turns. Either take a concrete next action toward the goal, ` +
75
+ `or call \`${GOAL_COMPLETE_TOOL}\` (if done) / \`${GOAL_ABANDON_TOOL}\` (if blocked). Do not reply with only text again.`;