@penguinharness/goal 0.2.9

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/hooks/lib.mjs ADDED
@@ -0,0 +1,233 @@
1
+ // Shared by start.mjs and stop.mjs: the Trace reader, the GOAL.json state file, and the
2
+ // round message. Plain Node, builtins only — this file is installed verbatim into an
3
+ // Agent's agent_state/hooks/goal/ and runs wherever the harness runs.
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+
7
+ /** The state file's name inside the Session's scratchpad directory. */
8
+ export const GOAL_FILE = "GOAL.json";
9
+
10
+ /** Rounds after which an unbudgeted goal is cut off anyway (a runaway backstop, not a knob). */
11
+ export const MAX_ROUNDS = 100;
12
+
13
+ /** Reads a JSONL Trace file tolerantly: malformed lines are skipped. */
14
+ export function readTrace(file) {
15
+ let text;
16
+ try {
17
+ text = fs.readFileSync(file, "utf8");
18
+ } catch {
19
+ return [];
20
+ }
21
+ const records = [];
22
+ for (const line of text.split("\n")) {
23
+ if (!line.trim()) continue;
24
+ try {
25
+ records.push(JSON.parse(line));
26
+ } catch {
27
+ // A torn tail or a foreign line: not ours to repair.
28
+ }
29
+ }
30
+ return records;
31
+ }
32
+
33
+ /** The Session's scratchpad directory, derived from the Trace's session_meta (`agent_state` is `<agent dir>/agent_state`). */
34
+ export function scratchpadDirOf(records, sessionId) {
35
+ const meta = records.find((r) => r && r.type === "session_meta");
36
+ const agentState = meta && meta.payload && meta.payload.agent_state;
37
+ if (typeof agentState !== "string" || !agentState) return null;
38
+ return path.join(path.dirname(agentState), "scratchpad", sessionId);
39
+ }
40
+
41
+ /** Reads GOAL.json: `null` when missing, `"broken"` when unreadable as a JSON object (see `ended` for who wrote a terminal status). */
42
+ export function readGoal(file) {
43
+ let raw;
44
+ try {
45
+ raw = fs.readFileSync(file, "utf8");
46
+ } catch {
47
+ return null;
48
+ }
49
+ try {
50
+ const parsed = JSON.parse(raw);
51
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return "broken";
52
+ return {
53
+ objective: typeof parsed.objective === "string" ? parsed.objective : "",
54
+ status: typeof parsed.status === "string" ? parsed.status : "blocked",
55
+ budget: Number.isFinite(parsed.budget) ? parsed.budget : -1,
56
+ round: Number.isFinite(parsed.round) ? parsed.round : 0,
57
+ tokens_used: Number.isFinite(parsed.tokens_used) ? parsed.tokens_used : 0,
58
+ // Set by the stop hook when it ends the goal, whatever the status: the model only ever
59
+ // writes `status`, so a terminal status without it is a verdict this run has yet to act on.
60
+ ...(parsed.ended === true ? { ended: true } : {}),
61
+ };
62
+ } catch {
63
+ return "broken";
64
+ }
65
+ }
66
+
67
+ export function writeGoal(file, goal) {
68
+ fs.mkdirSync(path.dirname(file), { recursive: true });
69
+ const tmp = `${file}.${process.pid}.tmp`;
70
+ fs.writeFileSync(tmp, `${JSON.stringify(goal, null, 2)}\n`);
71
+ fs.renameSync(tmp, file);
72
+ }
73
+
74
+ /**
75
+ * Whether a Trace record is a round's injected input: a main-session harness-injected user
76
+ * text (`sender: "harness"`) that is not a background-task completion notice — notices share
77
+ * the stamp but ride inside a round as reports, and treating one as a boundary would drop
78
+ * part of the round from the usage count. Each round input starts a new accounting window.
79
+ */
80
+ export function isRoundInput(record) {
81
+ if (!record || record.type !== "model_msg" || (record.origin && record.origin.length))
82
+ return false;
83
+ const p = record.payload;
84
+ if (!p || p.type !== "text" || p.role !== "user" || p.sender !== "harness") return false;
85
+ return !/^\[background_task_done\]/.test(p.text || "");
86
+ }
87
+
88
+ /** Uncached input + output of one token_usage record (`request.total − cache_read`); 0 for anything else. */
89
+ export function uncachedTokens(record) {
90
+ if (!record || record.type !== "event_msg") return 0;
91
+ const p = record.payload;
92
+ if (!p || p.type !== "token_usage" || !p.request) return 0;
93
+ return Math.max(0, (p.request.total || 0) - (p.request.cache_read || 0));
94
+ }
95
+
96
+ /**
97
+ * The records of the round that just ended: everything after the last round input, or the
98
+ * whole file when there is none in it (a compaction rotated the file mid-round).
99
+ */
100
+ export function lastRoundRecords(records) {
101
+ let start = 0;
102
+ records.forEach((r, i) => {
103
+ if (isRoundInput(r)) start = i + 1;
104
+ });
105
+ return records.slice(start);
106
+ }
107
+
108
+ /**
109
+ * How the round's Task ended, read off its records: an `abort` event is the user's
110
+ * interruption; a last `request_end` that is not completed is a failure the run gave up on;
111
+ * a last assistant text with a fatal stop reason is the max_turns cap. Anything else completed.
112
+ */
113
+ export function stopReasonOf(roundRecords) {
114
+ let lastRequestEnd = null;
115
+ let lastAssistant = null;
116
+ for (const r of roundRecords) {
117
+ if (!r || (r.origin && r.origin.length)) continue;
118
+ const p = r.payload || {};
119
+ if (r.type === "event_msg" && p.type === "abort") return "aborted";
120
+ if (r.type === "event_msg" && p.type === "request_end") lastRequestEnd = p;
121
+ if (r.type === "model_msg" && p.type === "text" && p.role === "assistant") lastAssistant = p;
122
+ }
123
+ if (lastRequestEnd && lastRequestEnd.status !== "completed") return "fatal";
124
+ const stop = lastAssistant && lastAssistant.stop_reason;
125
+ if (stop === "fatal" || stop === "failed") return "fatal";
126
+ return "completed";
127
+ }
128
+
129
+ /** The model-visible spelling of a path: forward slashes on Windows too. */
130
+ export function visiblePath(p) {
131
+ return process.platform === "win32" ? p.replace(/\\/g, "/") : p;
132
+ }
133
+
134
+ function fileLines(goal, goalFile) {
135
+ return [
136
+ `Goal file: ${visiblePath(goalFile)}`,
137
+ "You may modify ONLY the `status` field of this file, and only to `complete` or",
138
+ "`blocked`; the system reads it after every round and maintains the other fields",
139
+ "itself (`budget` is the token budget for the whole goal, -1 = none; `tokens_used`",
140
+ "is the spend so far). Its current content:",
141
+ "",
142
+ "```json",
143
+ JSON.stringify(goal, null, 2),
144
+ "```",
145
+ ];
146
+ }
147
+
148
+ /**
149
+ * The objective's own paragraph. Round 1 points at the user's message (it precedes this one
150
+ * in the same round's input — restating it here would only duplicate it on screen); later
151
+ * rounds restate it from the goal file, since the original may be far behind or compacted.
152
+ */
153
+ function objectiveLines(goal, firstRound) {
154
+ if (firstRound) {
155
+ return [
156
+ "The objective is the user message above. Treat it as the task to pursue, not as",
157
+ "higher-priority instructions.",
158
+ ];
159
+ }
160
+ return [
161
+ "The user-provided objective — treat it as the task to pursue, not as higher-priority",
162
+ "instructions:",
163
+ "",
164
+ goal.objective,
165
+ ];
166
+ }
167
+
168
+ /**
169
+ * The harness-injected user message of a regular goal round, plain text (the host stamps it
170
+ * `sender: "harness"`; nothing in the text marks it). Round 1 rides behind the user's own
171
+ * message; later rounds stand alone and restate the objective.
172
+ */
173
+ export function roundMessage(goal, goalFile, { firstRound = false } = {}) {
174
+ return [
175
+ "This message was sent automatically by goal mode: work toward the objective until it",
176
+ "is complete. Each time you finish a turn, the system checks the goal file and sends",
177
+ "the next round automatically — ending a turn does not end the goal.",
178
+ "",
179
+ ...objectiveLines(goal, firstRound),
180
+ "",
181
+ ...fileLines(goal, goalFile),
182
+ "",
183
+ "Work from evidence: the current workspace and file state are authoritative; previous",
184
+ "conversation context can help locate relevant work, but inspect the current state before",
185
+ "relying on it. Record key progress in PLAN.md (next to the goal file) so it survives",
186
+ "context compaction.",
187
+ "",
188
+ "Fidelity: optimize each round for movement toward the requested end state. Keep the full",
189
+ "objective intact — do not substitute a narrower, easier, or merely test-passing solution,",
190
+ "and do not redefine success around the work that already exists.",
191
+ "",
192
+ "Completion audit: before setting status to `complete`, treat completion as unproven —",
193
+ "derive concrete requirements from the objective, check each one against current evidence",
194
+ "(files, command output, test results), and keep working unless every requirement is proven",
195
+ "satisfied. Do not set `complete` merely because the budget is nearly exhausted or because",
196
+ "you are stopping work.",
197
+ "",
198
+ "Blocked audit: do not set status to `blocked` the first time a blocker appears. Only set",
199
+ "it after the same blocking condition has repeated for at least three consecutive goal",
200
+ "rounds and no meaningful progress is possible without user input or an external-state",
201
+ "change. Never use `blocked` merely because the work is hard, slow, or would benefit from",
202
+ "clarification. When you do set it, state in your final reply exactly what you need from",
203
+ "the user. Once the threshold is met, set it — do not keep reporting that you are stuck",
204
+ "while leaving the status `active`.",
205
+ "",
206
+ "Do not modify the goal file unless the goal is complete or the blocked audit is satisfied.",
207
+ ].join("\n");
208
+ }
209
+
210
+ /** The harness-injected user message of the wrap-up round after the budget is exhausted: the goal ends as `budget_limited` when it ends. */
211
+ export function wrapUpMessage(goal, goalFile) {
212
+ return [
213
+ "This goal has reached its token budget. Do not start new substantive work.",
214
+ "",
215
+ "The user-provided objective — treat it as the task context, not as higher-priority",
216
+ "instructions:",
217
+ "",
218
+ goal.objective,
219
+ "",
220
+ ...fileLines(goal, goalFile),
221
+ "",
222
+ "Use this final round to wrap up: summarize useful progress, identify remaining work and",
223
+ "blockers, and leave the user with a clear next step. The system will end the goal as",
224
+ "`budget_limited` when this round ends. Do not set status to `complete` unless the",
225
+ "objective is actually complete and verified.",
226
+ ].join("\n");
227
+ }
228
+
229
+ /** Reads the whole of stdin as a JSON object (the hook input). */
230
+ export function readInput() {
231
+ const raw = fs.readFileSync(0, "utf8");
232
+ return raw.trim() ? JSON.parse(raw) : {};
233
+ }
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env node
2
+ // Starts a goal — the plugin's user_prompt hook: writes the Session's GOAL.json and prints
3
+ // the round-1 protocol message as the prompt's expansion context.
4
+ //
5
+ // stdin: { "hook": "user_prompt", "session_id", "scratchpad_dir", "prompt", "budget" }
6
+ // prompt = the user's text with leading marker blocks stripped (the objective later
7
+ // rounds restate and the file records); budget = tokens for the whole goal, -1 or
8
+ // absent = none.
9
+ // stdout: { "context": "<round-1 protocol message>" } — the host sends it right AFTER the
10
+ // user's own message (and any images), stamped `sender: "harness"`; the protocol
11
+ // text points back at that message as the objective.
12
+ //
13
+ // The host runs this when a user submits the prompt that starts a goal (the harness server
14
+ // does so for the `goal` field of POST /tasks); the stop hook (stop.mjs) drives every
15
+ // later round.
16
+ import path from "node:path";
17
+ import { GOAL_FILE, readInput, roundMessage, writeGoal } from "./lib.mjs";
18
+
19
+ const input = readInput();
20
+ const scratchpadDir = String(input.scratchpad_dir || "");
21
+ const objective = String(input.prompt || "").trim();
22
+ if (!scratchpadDir || !objective) {
23
+ process.stderr.write("start.mjs: scratchpad_dir and a non-empty prompt are required\n");
24
+ process.exit(1);
25
+ }
26
+ const budget = Number.isFinite(input.budget) && input.budget > 0 ? Math.round(input.budget) : -1;
27
+ const goalFile = path.join(scratchpadDir, GOAL_FILE);
28
+ const goal = { objective, status: "active", budget, round: 1, tokens_used: 0 };
29
+ writeGoal(goalFile, goal);
30
+ process.stdout.write(
31
+ `${JSON.stringify({ context: roundMessage(goal, goalFile, { firstRound: true }) })}\n`,
32
+ );
package/hooks/stop.mjs ADDED
@@ -0,0 +1,105 @@
1
+ #!/usr/bin/env node
2
+ // Goal mode's stop hook: consulted after every Task of a run. Reads the Session's Trace to
3
+ // find its GOAL.json and this round's token usage, then either injects the next round's
4
+ // protocol message (the host stamps it `sender: "harness"`) or ends the goal.
5
+ //
6
+ // stdin: { "hook": "stop", "session_id", "trace_path" }
7
+ // stdout: nothing when no goal is live on this Session; otherwise
8
+ // { "decision": "continue", "input": "<next round>", "reason", "output": {…} } or
9
+ // { "decision": "stop", "reason", "output": { status, round, tokens_used, budget } }
10
+ //
11
+ // The decision, first match wins: the file says complete / blocked → that outcome; the Task
12
+ // was cut off (abort, a failure the run gave up on, the max_turns cap — the model never got
13
+ // to write the file) → aborted; the wrap-up round just ran → budget_limited; the round cap →
14
+ // aborted; the budget is reached → one wrap-up round; otherwise → the next round. Every
15
+ // ending is written back with `ended: true` — the model only ever writes `status`, so that
16
+ // flag is what tells a goal this run just ended from one that ended on an earlier run (the
17
+ // hook stays silent for those). A file that no longer parses ends the goal as blocked and is
18
+ // moved aside as GOAL.json.broken.
19
+ import fs from "node:fs";
20
+ import path from "node:path";
21
+ import {
22
+ GOAL_FILE,
23
+ MAX_ROUNDS,
24
+ lastRoundRecords,
25
+ readGoal,
26
+ readInput,
27
+ readTrace,
28
+ roundMessage,
29
+ scratchpadDirOf,
30
+ stopReasonOf,
31
+ uncachedTokens,
32
+ wrapUpMessage,
33
+ writeGoal,
34
+ } from "./lib.mjs";
35
+
36
+ const input = readInput();
37
+ const sessionId = String(input.session_id || "");
38
+ const tracePath = typeof input.trace_path === "string" ? input.trace_path : "";
39
+ if (!sessionId || !tracePath) process.exit(0);
40
+
41
+ const records = readTrace(tracePath);
42
+ const scratchpad = scratchpadDirOf(records, sessionId);
43
+ if (!scratchpad) process.exit(0);
44
+ const goalFile = path.join(scratchpad, GOAL_FILE);
45
+ const goal = readGoal(goalFile);
46
+ if (goal === null) process.exit(0);
47
+
48
+ const emit = (result) => process.stdout.write(`${JSON.stringify(result)}\n`);
49
+ const record = (g) => ({
50
+ status: g.status,
51
+ round: g.round,
52
+ tokens_used: g.tokens_used,
53
+ budget: g.budget,
54
+ });
55
+ const tokens = (g) => `tokens ${g.tokens_used}${g.budget > 0 ? ` / ${g.budget}` : ""}`;
56
+ const stop = (g, outcome, write) => {
57
+ g.status = outcome;
58
+ g.ended = true;
59
+ if (write) writeGoal(goalFile, g);
60
+ emit({
61
+ decision: "stop",
62
+ reason: `${outcome} · ${g.round} round${g.round === 1 ? "" : "s"} · ${tokens(g)}`,
63
+ output: record(g),
64
+ });
65
+ };
66
+
67
+ if (goal === "broken") {
68
+ fs.renameSync(goalFile, `${goalFile}.broken`);
69
+ stop(
70
+ { objective: "", status: "blocked", budget: -1, round: 0, tokens_used: 0 },
71
+ "blocked",
72
+ false,
73
+ );
74
+ process.exit(0);
75
+ }
76
+ // A goal that already ended on this Session (an earlier run) is not this run's business.
77
+ if (goal.ended) process.exit(0);
78
+
79
+ const round = lastRoundRecords(records);
80
+ goal.tokens_used += round.reduce((n, r) => n + uncachedTokens(r), 0);
81
+
82
+ if (goal.status === "complete" || goal.status === "blocked") {
83
+ stop(goal, goal.status, true);
84
+ } else if (goal.status !== "active" && goal.status !== "wrapping_up") {
85
+ // Anything else in `status` is outside the protocol the model was given: a broken channel.
86
+ stop(goal, "blocked", true);
87
+ } else if (stopReasonOf(round) !== "completed") {
88
+ stop(goal, "aborted", true);
89
+ } else if (goal.status === "wrapping_up") {
90
+ stop(goal, "budget_limited", true);
91
+ } else if (goal.round >= MAX_ROUNDS) {
92
+ stop(goal, "aborted", true);
93
+ } else {
94
+ goal.round += 1;
95
+ const wrapUp = goal.budget > 0 && goal.tokens_used >= goal.budget;
96
+ goal.status = wrapUp ? "wrapping_up" : "active";
97
+ writeGoal(goalFile, goal);
98
+ const compose = wrapUp ? wrapUpMessage : roundMessage;
99
+ emit({
100
+ decision: "continue",
101
+ input: compose(goal, goalFile),
102
+ reason: `round ${goal.round}${wrapUp ? " (wrap-up: budget reached)" : ""} · ${tokens(goal)}`,
103
+ output: record(goal),
104
+ });
105
+ }
package/icon.svg ADDED
@@ -0,0 +1,6 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
2
+ <path d="M21 12a9 9 0 1 1-9-9" />
3
+ <path d="M17 12a5 5 0 1 1-5-5" />
4
+ <path d="M12 12l3-3" />
5
+ <path d="M15 9V5l3-3v4h4l-3 3h-4" />
6
+ </svg>
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@penguinharness/goal",
3
+ "version": "0.2.9",
4
+ "description": "Goal mode: a stop hook that keeps the session working toward an objective — re-injecting it every round and checking the goal file — until the goal is complete, blocked, or out of token budget.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Prism-Shadow/penguin-harness.git",
9
+ "directory": "plugins/goal"
10
+ },
11
+ "files": [
12
+ "plugin.json",
13
+ "icon.svg",
14
+ "skills",
15
+ "hooks",
16
+ "LICENSE"
17
+ ],
18
+ "publishConfig": {
19
+ "access": "public"
20
+ }
21
+ }
package/plugin.json ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ "description": "Goal mode: a stop hook that keeps the session working toward an objective — re-injecting it every round and checking the goal file — until the goal is complete, blocked, or out of token budget.",
3
+ "description_zh": "目标模式:一个 stop hook,让会话持续朝目标工作——每轮重新注入目标并检查目标文件——直到目标完成、受阻或 token 预算耗尽。",
4
+ "short_description": "Loop the session on an objective until it is done.",
5
+ "short_description_zh": "让会话循环推进一个目标直到完成。",
6
+ "version": "2026-09-01.1",
7
+ "category": "office-productivity",
8
+ "hooks": {
9
+ "user_prompt": [
10
+ {
11
+ "command": "start.mjs",
12
+ "timeout": 60
13
+ }
14
+ ],
15
+ "stop": [
16
+ {
17
+ "command": "stop.mjs",
18
+ "timeout": 60
19
+ }
20
+ ]
21
+ }
22
+ }