@nones/agentflow-strategy-goal 0.0.0-stage → 0.1.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/README.md CHANGED
@@ -1,3 +1,73 @@
1
- # Temporary Holding Version
1
+ # Goal strategy
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `goalStrategy.compile(input)` accepts:
4
+
5
+ ```ts
6
+ {
7
+ agent: AgentSpec;
8
+ goal: string;
9
+ maxTurns?: number; // integer >= 1, no default
10
+ timeoutMs?: number; // integer >= 0, no default
11
+ verifier?: string | { name: string; evidence?: unknown };
12
+ }
13
+ ```
14
+
15
+ It returns a one-wave `RunPlan`. The compiled agent has:
16
+
17
+ - a prompt containing the original prompt, `Goal: <goal>`, and the completion protocol;
18
+ - `strategy: "goal"`;
19
+ - `strategyInput` containing the validated goal settings.
20
+
21
+ The settings on `strategyInput` are also how `decide` reads the goal because
22
+ `TurnContext` does not carry the run-level input. An embedded goal agent can be
23
+ built with the same settings directly:
24
+
25
+ ```ts
26
+ agent({
27
+ ...,
28
+ strategy: "goal",
29
+ strategyInput: { goal, maxTurns, timeoutMs, verifier },
30
+ });
31
+ ```
32
+
33
+ ## Completion protocol
34
+
35
+ Every reply must end with exactly one block:
36
+
37
+ ```
38
+ <<<AGENTFLOW_GOAL>>>
39
+ {"status":"continue","reason":"short reason"}
40
+ <<<AGENTFLOW_GOAL_END>>>
41
+ ```
42
+
43
+ `status` must be exactly `continue`, `reached`, or `blocked`. `reason` is
44
+ required for `blocked`. A `reached` reply may include `evidence` for a
45
+ configured verifier. Prose before the block is allowed; text after the end
46
+ marker, multiple blocks, unknown statuses, malformed JSON, and missing blocked
47
+ reasons are all rejected. Rejections produce a `paused` decision with an
48
+ `invalid goal response: ...` diagnostic.
49
+
50
+ For compatibility, a reply containing no protocol markers may instead be
51
+ exactly one status word (`continue`, `reached`, or `blocked`) or a JSON status
52
+ object (optionally in a single fenced block). A plain `blocked` word uses a
53
+ generic blocker reason because it has no detail. If a protocol marker appears,
54
+ only the canonical tagged form is accepted.
55
+
56
+ ## Decisions
57
+
58
+ - `reached` becomes `complete`, after the configured verifier passes.
59
+ - A configured verifier must be provided as `TurnContext.verify`. If it is
60
+ missing, throws, returns a non-boolean, or rejects the evidence, the goal does
61
+ not complete. A rejection becomes a `continue` decision with feedback for the
62
+ next turn, unless a budget is already exhausted.
63
+ - `continue` becomes a `continue` decision whose prompt includes the protocol
64
+ again, unless a budget is exhausted.
65
+ - `blocked` becomes `paused`.
66
+ - No decision carries a session ID, so core keeps the same session for every
67
+ continuation turn.
68
+
69
+ `TurnContext.turns` is treated as the 1-based number of the current goal turn.
70
+ An explicit `maxTurns` is checked after a `reached` reply has been handled, so a
71
+ successful final turn completes. A `continue` on the final turn pauses. With no
72
+ `maxTurns` or `timeoutMs`, continuation may run indefinitely. `timeoutMs` is
73
+ checked against `TurnContext.elapsedMs` in the same way.
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@nones/agentflow-strategy-goal",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Same-session goal AgentFlow strategy",
5
+ "type": "module",
6
+ "main": "./src/index.ts",
7
+ "module": "./src/index.ts",
8
+ "types": "./src/index.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./src/index.ts",
12
+ "import": "./src/index.ts",
13
+ "default": "./src/index.ts"
14
+ },
15
+ "./package.json": "./package.json"
16
+ },
17
+ "files": [
18
+ "src",
19
+ "README.md"
20
+ ],
21
+ "engines": {
22
+ "bun": ">=1.4.5"
23
+ },
24
+ "publishConfig": {
25
+ "access": "public",
26
+ "registry": "https://registry.npmjs.org/"
27
+ },
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/nones-tools/agentflow.git",
31
+ "directory": "strategy/goal"
32
+ },
33
+ "scripts": {
34
+ "build": "bun build ./src/index.ts --target=bun --outdir=.tmp/build --packages external",
35
+ "test": "bun test"
36
+ },
37
+ "dependencies": {
38
+ "@nones/agentflow-core": "^0.1.0"
39
+ }
40
+ }
package/src/index.ts ADDED
@@ -0,0 +1,16 @@
1
+ export { goalStrategy } from "./strategy";
2
+ export {
3
+ GOAL_PROTOCOL_END,
4
+ GOAL_PROTOCOL_MARKER,
5
+ appendGoalProtocol,
6
+ buildGoalPrompt,
7
+ goalProtocolText,
8
+ } from "./protocol";
9
+ export { GoalResponseError, parseGoalReply } from "./parse";
10
+ export type {
11
+ GoalInput,
12
+ GoalReply,
13
+ GoalSettings,
14
+ GoalStatus,
15
+ GoalVerifierConfig,
16
+ } from "./types";
@@ -0,0 +1,283 @@
1
+ import type { AgentSpec } from "@nones/agentflow-core";
2
+ import type { GoalInput, GoalSettings, GoalVerifierConfig } from "./types";
3
+
4
+ const ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
5
+
6
+ const AGENT_FIELDS = [
7
+ "id",
8
+ "prompt",
9
+ "cwd",
10
+ "profile",
11
+ "model",
12
+ "settings",
13
+ "strategy",
14
+ "strategyInput",
15
+ ] as const;
16
+
17
+ const GOAL_SETTINGS_FIELDS = [
18
+ "goal",
19
+ "maxTurns",
20
+ "timeoutMs",
21
+ "verifier",
22
+ ] as const;
23
+ const GOAL_INPUT_FIELDS = [
24
+ "agent",
25
+ "goal",
26
+ "maxTurns",
27
+ "timeoutMs",
28
+ "verifier",
29
+ ] as const;
30
+ const VERIFIER_FIELDS = ["name", "evidence"] as const;
31
+
32
+ export function isRecord(value: unknown): value is Record<string, unknown> {
33
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
34
+ return false;
35
+ }
36
+ const prototype = Object.getPrototypeOf(value);
37
+ return prototype === Object.prototype || prototype === null;
38
+ }
39
+
40
+ export function fail(path: string, message: string): never {
41
+ throw new TypeError(`${path}: ${message}`);
42
+ }
43
+
44
+ export function expectRecord(
45
+ value: unknown,
46
+ path: string,
47
+ ): Record<string, unknown> {
48
+ if (!isRecord(value)) {
49
+ fail(path, "must be a plain object");
50
+ }
51
+ return value;
52
+ }
53
+
54
+ export function assertOnlyKeys(
55
+ record: Record<string, unknown>,
56
+ allowed: readonly string[],
57
+ path: string,
58
+ ): void {
59
+ const allowedKeys = new Set(allowed);
60
+ for (const key of Object.keys(record)) {
61
+ if (!allowedKeys.has(key)) {
62
+ fail(`${path}.${key}`, "is not a recognized field");
63
+ }
64
+ }
65
+ }
66
+
67
+ export function expectString(value: unknown, path: string): string {
68
+ if (typeof value !== "string") {
69
+ fail(path, "must be a string");
70
+ }
71
+ if (value.trim().length === 0) {
72
+ fail(path, "must not be empty");
73
+ }
74
+ return value;
75
+ }
76
+
77
+ export function expectOptionalString(
78
+ value: unknown,
79
+ path: string,
80
+ ): string | undefined {
81
+ if (value === undefined) {
82
+ return undefined;
83
+ }
84
+ return expectString(value, path);
85
+ }
86
+
87
+ export function expectId(value: unknown, path: string): string {
88
+ const id = expectString(value, path);
89
+ if (!ID_PATTERN.test(id)) {
90
+ fail(
91
+ path,
92
+ "must start with an alphanumeric character and contain only letters, digits, '.', '_', ':' or '-'",
93
+ );
94
+ }
95
+ return id;
96
+ }
97
+
98
+ export function assertJsonValue(
99
+ value: unknown,
100
+ path: string,
101
+ seen: Set<object> = new Set<object>(),
102
+ ): void {
103
+ if (value === null) {
104
+ return;
105
+ }
106
+ switch (typeof value) {
107
+ case "string":
108
+ case "boolean":
109
+ return;
110
+ case "number":
111
+ if (!Number.isFinite(value)) {
112
+ fail(path, "must be a finite number");
113
+ }
114
+ return;
115
+ case "object": {
116
+ if (seen.has(value)) {
117
+ fail(path, "must not contain circular references");
118
+ }
119
+ if (Object.getOwnPropertySymbols(value).length > 0) {
120
+ fail(path, "must not contain symbol keys");
121
+ }
122
+ seen.add(value);
123
+ if (Array.isArray(value)) {
124
+ value.forEach((item, index) =>
125
+ assertJsonValue(item, `${path}[${index}]`, seen),
126
+ );
127
+ } else if (isRecord(value)) {
128
+ for (const [key, item] of Object.entries(value)) {
129
+ assertJsonValue(item, `${path}.${key}`, seen);
130
+ }
131
+ } else {
132
+ fail(path, "must be JSON-serializable");
133
+ }
134
+ seen.delete(value);
135
+ return;
136
+ }
137
+ default:
138
+ fail(path, `must be JSON-serializable (got ${typeof value})`);
139
+ }
140
+ }
141
+
142
+ export function cloneJson<T>(value: unknown, path: string): T {
143
+ assertJsonValue(value, path);
144
+ return JSON.parse(JSON.stringify(value)) as T;
145
+ }
146
+
147
+ export function normalizeAgent(value: unknown, path: string): AgentSpec {
148
+ const record = expectRecord(value, path);
149
+ assertOnlyKeys(record, AGENT_FIELDS, path);
150
+
151
+ const id = expectId(record.id, `${path}.id`);
152
+ const prompt = expectString(record.prompt, `${path}.prompt`);
153
+ const cwd = expectString(record.cwd, `${path}.cwd`);
154
+
155
+ const spec: AgentSpec = { id, prompt, cwd };
156
+
157
+ const profile = expectOptionalString(record.profile, `${path}.profile`);
158
+ if (profile !== undefined) {
159
+ spec.profile = profile;
160
+ }
161
+
162
+ const model = expectOptionalString(record.model, `${path}.model`);
163
+ if (model !== undefined) {
164
+ spec.model = model;
165
+ }
166
+
167
+ if (record.settings !== undefined) {
168
+ const settings = expectRecord(record.settings, `${path}.settings`);
169
+ spec.settings = cloneJson<Record<string, unknown>>(
170
+ settings,
171
+ `${path}.settings`,
172
+ );
173
+ }
174
+
175
+ const strategy = expectOptionalString(record.strategy, `${path}.strategy`);
176
+ if (strategy !== undefined) {
177
+ spec.strategy = strategy;
178
+ }
179
+
180
+ if (record.strategyInput !== undefined) {
181
+ spec.strategyInput = cloneJson<unknown>(
182
+ record.strategyInput,
183
+ `${path}.strategyInput`,
184
+ );
185
+ }
186
+
187
+ return spec;
188
+ }
189
+
190
+ function expectOptionalInteger(
191
+ value: unknown,
192
+ path: string,
193
+ minimum: number,
194
+ ): number | undefined {
195
+ if (value === undefined) {
196
+ return undefined;
197
+ }
198
+ if (
199
+ typeof value !== "number" ||
200
+ !Number.isInteger(value) ||
201
+ value < minimum
202
+ ) {
203
+ fail(path, `must be an integer greater than or equal to ${minimum}`);
204
+ }
205
+ return value;
206
+ }
207
+
208
+ function normalizeVerifier(value: unknown, path: string): GoalVerifierConfig {
209
+ if (typeof value === "string") {
210
+ return expectString(value, path);
211
+ }
212
+
213
+ const record = expectRecord(value, path);
214
+ assertOnlyKeys(record, VERIFIER_FIELDS, path);
215
+
216
+ const name = expectString(record.name, `${path}.name`);
217
+ const verifier: { name: string; evidence?: unknown } = { name };
218
+ if (record.evidence !== undefined) {
219
+ verifier.evidence = cloneJson<unknown>(record.evidence, `${path}.evidence`);
220
+ }
221
+ return verifier;
222
+ }
223
+
224
+ function readGoalFields(
225
+ record: Record<string, unknown>,
226
+ path: string,
227
+ ): GoalSettings {
228
+ const goal = expectString(record.goal, `${path}.goal`);
229
+ const settings: GoalSettings = { goal };
230
+
231
+ const maxTurns = expectOptionalInteger(
232
+ record.maxTurns,
233
+ `${path}.maxTurns`,
234
+ 1,
235
+ );
236
+ if (maxTurns !== undefined) {
237
+ settings.maxTurns = maxTurns;
238
+ }
239
+
240
+ const timeoutMs = expectOptionalInteger(
241
+ record.timeoutMs,
242
+ `${path}.timeoutMs`,
243
+ 0,
244
+ );
245
+ if (timeoutMs !== undefined) {
246
+ settings.timeoutMs = timeoutMs;
247
+ }
248
+
249
+ if (record.verifier !== undefined) {
250
+ settings.verifier = normalizeVerifier(record.verifier, `${path}.verifier`);
251
+ }
252
+
253
+ return settings;
254
+ }
255
+
256
+ /**
257
+ * Validate goal settings. Used both for full strategy input and for the
258
+ * `agent.strategyInput` payload of an embedded goal agent.
259
+ */
260
+ export function normalizeGoalSettings(
261
+ value: unknown,
262
+ path = "goal settings",
263
+ ): GoalSettings {
264
+ const record = expectRecord(value, path);
265
+ assertOnlyKeys(record, GOAL_SETTINGS_FIELDS, path);
266
+ return readGoalFields(record, path);
267
+ }
268
+
269
+ /** Validate the input of the top-level goal strategy. */
270
+ export function normalizeGoalInput(value: unknown): GoalInput {
271
+ const path = "goal strategy input";
272
+ const record = expectRecord(value, path);
273
+ assertOnlyKeys(record, GOAL_INPUT_FIELDS, path);
274
+
275
+ if (record.agent === undefined) {
276
+ fail(`${path}.agent`, "is required");
277
+ }
278
+
279
+ return {
280
+ agent: normalizeAgent(record.agent, `${path}.agent`),
281
+ ...readGoalFields(record, path),
282
+ };
283
+ }
package/src/parse.ts ADDED
@@ -0,0 +1,170 @@
1
+ import { isRecord } from "./internal";
2
+ import { GOAL_PROTOCOL_END, GOAL_PROTOCOL_MARKER } from "./protocol";
3
+ import type { GoalReply, GoalStatus } from "./types";
4
+
5
+ export class GoalResponseError extends Error {
6
+ constructor(message: string) {
7
+ super(message);
8
+ this.name = "GoalResponseError";
9
+ }
10
+ }
11
+
12
+ function protocolError(message: string): never {
13
+ throw new GoalResponseError(message);
14
+ }
15
+
16
+ function isGoalStatus(value: unknown): value is GoalStatus {
17
+ return value === "continue" || value === "reached" || value === "blocked";
18
+ }
19
+
20
+ function validateReplyObject(parsed: unknown): GoalReply {
21
+ if (!isRecord(parsed)) {
22
+ protocolError("goal status block must be a JSON object");
23
+ }
24
+
25
+ if (!isGoalStatus(parsed.status)) {
26
+ protocolError(
27
+ 'goal status must be exactly "continue", "reached" or "blocked"',
28
+ );
29
+ }
30
+
31
+ let reason: string | undefined;
32
+ if (parsed.reason !== undefined) {
33
+ if (typeof parsed.reason !== "string") {
34
+ protocolError('goal status "reason" must be a string');
35
+ }
36
+ if (parsed.reason.trim().length === 0) {
37
+ protocolError('goal status "reason" must not be empty');
38
+ }
39
+ reason = parsed.reason;
40
+ }
41
+
42
+ if (parsed.status === "blocked" && reason === undefined) {
43
+ protocolError('blocked goal status requires a non-empty "reason"');
44
+ }
45
+
46
+ const reply: GoalReply = { status: parsed.status };
47
+ if (reason !== undefined) {
48
+ reply.reason = reason;
49
+ }
50
+ if ("evidence" in parsed) {
51
+ reply.evidence = parsed.evidence;
52
+ }
53
+
54
+ return reply;
55
+ }
56
+
57
+ function parsePayload(payload: string): GoalReply {
58
+ let text = payload.trim();
59
+ if (text.length === 0) {
60
+ protocolError("goal status block is empty");
61
+ }
62
+
63
+ if (text.startsWith("```")) {
64
+ const fenceLines = text.split(/\r?\n/);
65
+ const opening = fenceLines[0]!.trim();
66
+ const closing = fenceLines[fenceLines.length - 1]?.trim();
67
+ if (!/^```[A-Za-z0-9_-]*$/.test(opening)) {
68
+ protocolError("goal status block has an invalid code fence");
69
+ }
70
+ if (fenceLines.length < 2 || closing !== "```") {
71
+ protocolError("goal status block has an unterminated code fence");
72
+ }
73
+ text = fenceLines.slice(1, -1).join("\n").trim();
74
+ if (text.length === 0) {
75
+ protocolError("goal status block is empty");
76
+ }
77
+ }
78
+
79
+ let parsed: unknown = undefined;
80
+ try {
81
+ parsed = JSON.parse(text);
82
+ } catch {
83
+ protocolError("goal status block is not valid JSON");
84
+ }
85
+
86
+ return validateReplyObject(parsed);
87
+ }
88
+
89
+ function parseTaggedReply(text: string): GoalReply {
90
+ const markerIndex = text.indexOf(GOAL_PROTOCOL_MARKER);
91
+ if (
92
+ markerIndex === -1 ||
93
+ text.indexOf(GOAL_PROTOCOL_MARKER, markerIndex + 1) !== -1
94
+ ) {
95
+ protocolError(
96
+ `goal reply must contain exactly one ${GOAL_PROTOCOL_MARKER}`,
97
+ );
98
+ }
99
+
100
+ const endIndex = text.indexOf(GOAL_PROTOCOL_END);
101
+ if (endIndex === -1 || text.indexOf(GOAL_PROTOCOL_END, endIndex + 1) !== -1) {
102
+ protocolError(`goal reply must contain exactly one ${GOAL_PROTOCOL_END}`);
103
+ }
104
+
105
+ if (markerIndex >= endIndex) {
106
+ protocolError("goal status block markers are out of order");
107
+ }
108
+ if (text.slice(endIndex + GOAL_PROTOCOL_END.length).trim().length > 0) {
109
+ protocolError("goal status block must be the last content in the reply");
110
+ }
111
+
112
+ return parsePayload(
113
+ text.slice(markerIndex + GOAL_PROTOCOL_MARKER.length, endIndex),
114
+ );
115
+ }
116
+
117
+ /**
118
+ * Compatibility fallback for a reply that is exactly a status word, a JSON
119
+ * status object, or a fenced JSON status object. It is only used when the
120
+ * tagged protocol markers are absent, so it cannot hide a malformed tagged
121
+ * block.
122
+ */
123
+ function parseLooseReply(text: string): GoalReply {
124
+ if (text === "continue" || text === "reached") {
125
+ return { status: text };
126
+ }
127
+ if (text === "blocked") {
128
+ return {
129
+ status: "blocked",
130
+ reason: "goal reported a blocker without details",
131
+ };
132
+ }
133
+
134
+ if (text.startsWith("```")) {
135
+ return parsePayload(text);
136
+ }
137
+
138
+ let parsed: unknown = undefined;
139
+ try {
140
+ parsed = JSON.parse(text);
141
+ } catch {
142
+ protocolError("goal reply is not a recognized status response");
143
+ }
144
+
145
+ return validateReplyObject(parsed);
146
+ }
147
+
148
+ /**
149
+ * Parse an untrusted model reply. The canonical form is a tagged block at the
150
+ * end of the reply. A reply containing either marker must use the tagged form;
151
+ * otherwise an exact status word or JSON status object is also accepted.
152
+ */
153
+ export function parseGoalReply(text: unknown): GoalReply {
154
+ if (typeof text !== "string") {
155
+ protocolError("goal reply must be a string");
156
+ }
157
+ const trimmed = text.trim();
158
+ if (trimmed.length === 0) {
159
+ protocolError("goal reply is empty");
160
+ }
161
+
162
+ if (
163
+ trimmed.includes(GOAL_PROTOCOL_MARKER) ||
164
+ trimmed.includes(GOAL_PROTOCOL_END)
165
+ ) {
166
+ return parseTaggedReply(text);
167
+ }
168
+
169
+ return parseLooseReply(trimmed);
170
+ }
@@ -0,0 +1,72 @@
1
+ import type { GoalVerifierConfig } from "./types";
2
+
3
+ export const GOAL_PROTOCOL_MARKER = "<<<AGENTFLOW_GOAL>>>";
4
+ export const GOAL_PROTOCOL_END = "<<<AGENTFLOW_GOAL_END>>>";
5
+
6
+ export function verifierName(
7
+ verifier?: GoalVerifierConfig,
8
+ ): string | undefined {
9
+ if (verifier === undefined) {
10
+ return undefined;
11
+ }
12
+ return typeof verifier === "string" ? verifier : verifier.name;
13
+ }
14
+
15
+ export function goalProtocolText(verifier?: GoalVerifierConfig): string {
16
+ const name = verifierName(verifier);
17
+ const lines = [
18
+ "AgentFlow goal protocol:",
19
+ "Finish every reply with exactly one goal status block. The block must be the last content in the reply.",
20
+ 'The "status" value must be exactly "continue", "reached" or "blocked". Use "reached" only when the goal is fully achieved, and "blocked" when operator input is required. "reason" is required for "blocked". Use valid JSON, emit exactly one status block, and put no text after the end marker.',
21
+ ];
22
+
23
+ if (name !== undefined) {
24
+ lines.push(
25
+ `A verifier named "${name}" must accept your evidence before a "reached" status completes. Put the evidence in the "evidence" field of the status block.`,
26
+ );
27
+ }
28
+
29
+ lines.push(
30
+ GOAL_PROTOCOL_MARKER,
31
+ '{"status":"continue","reason":"short reason"}',
32
+ GOAL_PROTOCOL_END,
33
+ );
34
+
35
+ return lines.join("\n");
36
+ }
37
+
38
+ /**
39
+ * Append the completion protocol unless the prompt already contains it.
40
+ */
41
+ export function appendGoalProtocol(
42
+ prompt: string,
43
+ verifier?: GoalVerifierConfig,
44
+ ): string {
45
+ if (prompt.includes(GOAL_PROTOCOL_MARKER)) {
46
+ return prompt;
47
+ }
48
+ return `${prompt.trimEnd()}\n\n${goalProtocolText(verifier)}`;
49
+ }
50
+
51
+ /**
52
+ * Build the first-turn prompt. The goal is placed before any existing protocol
53
+ * block so the completion protocol remains last.
54
+ */
55
+ export function buildGoalPrompt(
56
+ agentPrompt: string,
57
+ goal: string,
58
+ verifier?: GoalVerifierConfig,
59
+ ): string {
60
+ const goalSection = `Goal:\n${goal}`;
61
+ const markerIndex = agentPrompt.indexOf(GOAL_PROTOCOL_MARKER);
62
+ if (markerIndex !== -1) {
63
+ const head = agentPrompt.slice(0, markerIndex).trimEnd();
64
+ const tail = agentPrompt.slice(markerIndex);
65
+ return `${head}\n\n${goalSection}\n\n${tail}`;
66
+ }
67
+
68
+ return appendGoalProtocol(
69
+ `${agentPrompt.trimEnd()}\n\n${goalSection}`,
70
+ verifier,
71
+ );
72
+ }
@@ -0,0 +1,248 @@
1
+ import type {
2
+ AgentSpec,
3
+ RunPlan,
4
+ Strategy,
5
+ TurnContext,
6
+ TurnDecision,
7
+ } from "@nones/agentflow-core";
8
+ import {
9
+ isRecord,
10
+ normalizeGoalInput,
11
+ normalizeGoalSettings,
12
+ } from "./internal";
13
+ import { parseGoalReply } from "./parse";
14
+ import { buildGoalPrompt, goalProtocolText, verifierName } from "./protocol";
15
+ import type { GoalReply, GoalSettings, GoalVerifierConfig } from "./types";
16
+
17
+ const WAVE_ID = "wave-1";
18
+
19
+ function diagnostic(error: unknown): string {
20
+ if (error instanceof Error) {
21
+ return error.message;
22
+ }
23
+ return String(error);
24
+ }
25
+
26
+ function paused(reason: string): TurnDecision {
27
+ return { status: "paused", reason };
28
+ }
29
+
30
+ function failed(reason: string): TurnDecision {
31
+ return { status: "failed", reason };
32
+ }
33
+
34
+ function continuationPrompt(settings: GoalSettings, note?: string): string {
35
+ const lines = ["Continue working toward the goal."];
36
+ if (note !== undefined) {
37
+ lines.push("", note);
38
+ }
39
+ lines.push("", goalProtocolText(settings.verifier));
40
+ return lines.join("\n");
41
+ }
42
+
43
+ function budgetExhausted(
44
+ settings: GoalSettings,
45
+ turns: number,
46
+ elapsedMs: number,
47
+ ): string | undefined {
48
+ if (settings.maxTurns !== undefined && turns >= settings.maxTurns) {
49
+ return `turn budget of ${settings.maxTurns} is exhausted`;
50
+ }
51
+ if (settings.timeoutMs !== undefined && elapsedMs >= settings.timeoutMs) {
52
+ return `time budget of ${settings.timeoutMs}ms is exhausted`;
53
+ }
54
+ return undefined;
55
+ }
56
+
57
+ function verifierEvidence(
58
+ verifier: GoalVerifierConfig | undefined,
59
+ reply: GoalReply,
60
+ ): unknown {
61
+ if (
62
+ verifier !== undefined &&
63
+ typeof verifier !== "string" &&
64
+ "evidence" in verifier
65
+ ) {
66
+ return verifier.evidence;
67
+ }
68
+ return reply.evidence;
69
+ }
70
+
71
+ function invalidContext(context: TurnContext): string | undefined {
72
+ if (!isRecord(context)) {
73
+ return "turn context must be an object";
74
+ }
75
+ if (!isRecord(context.agent)) {
76
+ return "turn context agent must be an object";
77
+ }
78
+ if (!isRecord(context.result)) {
79
+ return "turn context result must be an object";
80
+ }
81
+ if (
82
+ typeof context.turns !== "number" ||
83
+ !Number.isInteger(context.turns) ||
84
+ context.turns < 0
85
+ ) {
86
+ return "turn context turns must be a non-negative integer";
87
+ }
88
+ if (
89
+ typeof context.elapsedMs !== "number" ||
90
+ !Number.isFinite(context.elapsedMs) ||
91
+ context.elapsedMs < 0
92
+ ) {
93
+ return "turn context elapsedMs must be a non-negative number";
94
+ }
95
+ if (typeof context.result.status !== "string") {
96
+ return "turn result status must be a string";
97
+ }
98
+ return undefined;
99
+ }
100
+
101
+ async function reachDecision(
102
+ settings: GoalSettings,
103
+ reply: GoalReply,
104
+ context: TurnContext,
105
+ turns: number,
106
+ ): Promise<TurnDecision> {
107
+ const name = verifierName(settings.verifier);
108
+ if (name === undefined) {
109
+ return {
110
+ status: "complete",
111
+ ...(reply.reason !== undefined ? { reason: reply.reason } : {}),
112
+ };
113
+ }
114
+
115
+ if (typeof context.verify !== "function") {
116
+ return paused(
117
+ `verifier "${name}" is configured but no verifier is registered in the runtime`,
118
+ );
119
+ }
120
+
121
+ let verified: unknown;
122
+ try {
123
+ verified = await context.verify(
124
+ name,
125
+ verifierEvidence(settings.verifier, reply),
126
+ );
127
+ } catch (error) {
128
+ return paused(`verifier "${name}" failed: ${diagnostic(error)}`);
129
+ }
130
+
131
+ if (typeof verified !== "boolean") {
132
+ return paused(`verifier "${name}" did not return a boolean`);
133
+ }
134
+
135
+ if (verified) {
136
+ return {
137
+ status: "complete",
138
+ ...(reply.reason !== undefined ? { reason: reply.reason } : {}),
139
+ };
140
+ }
141
+
142
+ const budget = budgetExhausted(settings, turns, context.elapsedMs);
143
+ if (budget !== undefined) {
144
+ return paused(`verifier "${name}" rejected the evidence and ${budget}`);
145
+ }
146
+
147
+ return {
148
+ status: "continue",
149
+ reason: `verification failed: ${name}`,
150
+ prompt: continuationPrompt(
151
+ settings,
152
+ `The verifier "${name}" rejected the evidence from the previous turn. Re-examine the evidence and continue the work.`,
153
+ ),
154
+ };
155
+ }
156
+
157
+ /**
158
+ * Goal strategy. Its input is `{ agent, goal, maxTurns?, timeoutMs?, verifier? }`.
159
+ * Compilation appends the completion protocol to the first prompt and stores the
160
+ * goal settings on the agent so every decision can read them. The session is
161
+ * retained by core because decisions never carry a session override.
162
+ */
163
+ export const goalStrategy: Strategy = {
164
+ id: "goal",
165
+ singleAdapter: true,
166
+ compile(input: unknown): RunPlan {
167
+ const goalInput = normalizeGoalInput(input);
168
+
169
+ const settings: GoalSettings = { goal: goalInput.goal };
170
+ if (goalInput.maxTurns !== undefined) {
171
+ settings.maxTurns = goalInput.maxTurns;
172
+ }
173
+ if (goalInput.timeoutMs !== undefined) {
174
+ settings.timeoutMs = goalInput.timeoutMs;
175
+ }
176
+ if (goalInput.verifier !== undefined) {
177
+ settings.verifier = goalInput.verifier;
178
+ }
179
+
180
+ const spec: AgentSpec = {
181
+ ...goalInput.agent,
182
+ prompt: buildGoalPrompt(
183
+ goalInput.agent.prompt,
184
+ goalInput.goal,
185
+ goalInput.verifier,
186
+ ),
187
+ strategy: "goal",
188
+ strategyInput: settings,
189
+ };
190
+
191
+ return {
192
+ waves: [{ id: WAVE_ID, agents: [spec] }],
193
+ };
194
+ },
195
+
196
+ async decide(context: TurnContext): Promise<TurnDecision> {
197
+ const contextError = invalidContext(context);
198
+ if (contextError !== undefined) {
199
+ return paused(contextError);
200
+ }
201
+
202
+ const result = context.result;
203
+ if (result.status === "failed") {
204
+ return failed(result.error?.trim() || "goal turn failed");
205
+ }
206
+ if (result.status !== "succeeded") {
207
+ return paused(`goal turn ended with status "${result.status}"`);
208
+ }
209
+
210
+ let settings: GoalSettings;
211
+ try {
212
+ settings = normalizeGoalSettings(
213
+ context.agent.strategyInput,
214
+ "agent.strategyInput",
215
+ );
216
+ } catch (error) {
217
+ return paused(`invalid goal settings: ${diagnostic(error)}`);
218
+ }
219
+
220
+ let reply: GoalReply;
221
+ try {
222
+ reply = parseGoalReply(result.text);
223
+ } catch (error) {
224
+ return paused(`invalid goal response: ${diagnostic(error)}`);
225
+ }
226
+
227
+ const turns = Math.max(1, context.turns);
228
+
229
+ if (reply.status === "reached") {
230
+ return reachDecision(settings, reply, context, turns);
231
+ }
232
+
233
+ if (reply.status === "blocked") {
234
+ return paused(`blocked: ${reply.reason}`);
235
+ }
236
+
237
+ const budget = budgetExhausted(settings, turns, context.elapsedMs);
238
+ if (budget !== undefined) {
239
+ return paused(`goal is not complete and ${budget}`);
240
+ }
241
+
242
+ return {
243
+ status: "continue",
244
+ ...(reply.reason !== undefined ? { reason: reply.reason } : {}),
245
+ prompt: continuationPrompt(settings),
246
+ };
247
+ },
248
+ };
package/src/types.ts ADDED
@@ -0,0 +1,27 @@
1
+ import type { AgentSpec } from "@nones/agentflow-core";
2
+
3
+ export type GoalVerifierConfig =
4
+ | string
5
+ | {
6
+ name: string;
7
+ evidence?: unknown;
8
+ };
9
+
10
+ export interface GoalSettings {
11
+ goal: string;
12
+ maxTurns?: number;
13
+ timeoutMs?: number;
14
+ verifier?: GoalVerifierConfig;
15
+ }
16
+
17
+ export interface GoalInput extends GoalSettings {
18
+ agent: AgentSpec;
19
+ }
20
+
21
+ export type GoalStatus = "continue" | "reached" | "blocked";
22
+
23
+ export interface GoalReply {
24
+ status: GoalStatus;
25
+ reason?: string;
26
+ evidence?: unknown;
27
+ }