ceulen 0.20.0 → 0.25.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/CHANGELOG.md +176 -0
- package/extensions/lib/env.test.ts +45 -0
- package/extensions/lib/env.ts +56 -3
- package/extensions/lib/registry.ts +8 -0
- package/extensions/lib/skill-path.test.ts +1 -1
- package/extensions/modules/a2a/lib/gateway.ts +3 -0
- package/extensions/modules/a2a/lib/persistence.ts +3 -2
- package/extensions/modules/a2a/test/persistence.test.ts +12 -0
- package/extensions/modules/classifier/index.ts +12 -1
- package/extensions/modules/classifier/lib/settings.ts +21 -0
- package/extensions/modules/classifier/lib/think-gate.ts +211 -0
- package/extensions/modules/classifier/test/classifier.test.ts +285 -1
- package/extensions/modules/composer/lib/shapes.ts +2 -1
- package/extensions/modules/cron/index.ts +1 -0
- package/extensions/modules/cron/lib/jobs.ts +2 -1
- package/extensions/modules/cron/test/cwd-repro.test.ts +10 -1
- package/extensions/modules/goal/configPanel.ts +63 -0
- package/extensions/modules/goal/index.ts +545 -0
- package/extensions/modules/goal/lib/settings.ts +73 -0
- package/extensions/modules/goal/lib/state.ts +223 -0
- package/extensions/modules/goal/test/goal.test.ts +522 -0
- package/extensions/modules/jfind/index.ts +13 -4
- package/extensions/modules/jfind/lib/cascade.ts +5 -2
- package/extensions/modules/jfind/lib/tree.ts +8 -3
- package/extensions/modules/jfind/test/cascade.test.ts +28 -1
- package/extensions/modules/munin/configPanel.ts +13 -3
- package/extensions/modules/munin/index.ts +7 -4
- package/extensions/modules/munin/test/configPanel.test.ts +9 -3
- package/extensions/modules/munin/test/extension.test.ts +31 -0
- package/extensions/modules/permission/index.ts +20 -9
- package/extensions/modules/permission/test/permission.test.ts +33 -1
- package/extensions/modules/plan/index.ts +36 -7
- package/extensions/modules/plan/lib/shell-gate.ts +93 -26
- package/extensions/modules/plan/test/module.test.ts +114 -1
- package/extensions/modules/plan/test/shell-gate.test.ts +64 -0
- package/extensions/modules/repair/lib/guards.ts +4 -1
- package/extensions/modules/repair/test/guards.test.ts +9 -0
- package/extensions/modules/router/lib/client.ts +24 -0
- package/extensions/modules/router/test/unit.test.ts +33 -3
- package/extensions/modules/sg/index.ts +3 -3
- package/extensions/modules/sg/lib/ops.ts +15 -1
- package/extensions/modules/sg/test/sg.test.ts +16 -2
- package/extensions/modules/subagent/index.ts +12 -1
- package/extensions/modules/subagent/lib/herdr.ts +37 -3
- package/extensions/modules/subagent/lib/history.ts +6 -2
- package/extensions/modules/subagent/lib/settings.ts +2 -1
- package/extensions/modules/subagent/test/extension.test.ts +31 -0
- package/extensions/modules/subagent/test/file-modes.test.ts +40 -0
- package/extensions/modules/subagent/test/herdr-stalled.test.ts +39 -0
- package/extensions/modules/web/lib/chatgpt.ts +2 -1
- package/extensions/scripts/probe-thinking.mjs +108 -0
- package/package.json +4 -4
- package/skills/review/SKILL.md +45 -0
|
@@ -0,0 +1,545 @@
|
|
|
1
|
+
// ceulen-goal — autonomous goal mode for Pi (OMP/Codex self-continuation).
|
|
2
|
+
//
|
|
3
|
+
// /goal <objective> sets a session goal; after every settled turn the module
|
|
4
|
+
// re-injects a continuation prompt (objective + budget + OMP's completion
|
|
5
|
+
// audit) until the agent calls goal({op:"complete"}) with verified evidence,
|
|
6
|
+
// the token budget flips (one wrap-up turn), the turn cap hits, or the user
|
|
7
|
+
// pauses/clears. The safety surface is UNCHANGED: goal mode never bypasses
|
|
8
|
+
// plan-mode gates or bash approvals — it only keeps the agent working.
|
|
9
|
+
//
|
|
10
|
+
// // ponytail: ported from oh-my-pi packages/coding-agent/src/goals (runtime,
|
|
11
|
+
// prompts) + @bacnh85/pi-plan commands/goal.ts lineage, trimmed to pi's
|
|
12
|
+
// public extension API. Deliberate deviations from OMP (enumerated):
|
|
13
|
+
// - Budget wrap-up is a FOLLOW-UP TURN (triggerTurn:true), not OMP's
|
|
14
|
+
// deliverAs:"steer": OMP folds usage mid-turn (loop live, steer consumed);
|
|
15
|
+
// pi folds at turn boundaries where no loop can consume a steer — a
|
|
16
|
+
// non-triggering steer would strand the wrap-up forever (advisor-found).
|
|
17
|
+
// - Lifecycle ops (create/pause/resume/drop) live on the /goal command; the
|
|
18
|
+
// `goal` tool carries only get/complete — the USER owns lifecycle, the
|
|
19
|
+
// AGENT owns completion reporting.
|
|
20
|
+
// - No OMP todo-coupling (goalOpenWorkAllBlocked): ceulen's todo is
|
|
21
|
+
// phase-granular; the turn cap bounds any blocked-phase spin.
|
|
22
|
+
// - No RPC/interactive continuation-mode split: one path, gated only by
|
|
23
|
+
// plan-mode mutual exclusion and the pause/abort rules.
|
|
24
|
+
//
|
|
25
|
+
// The `goal` tool is DIRECT, never deferred (munin-loop lesson: a protocol's
|
|
26
|
+
// terminal action must stay in the live schema across plan baselines and
|
|
27
|
+
// branch restores). Plan mode blocks it via plan-tools.ts BLOCKED_TOOLS.
|
|
28
|
+
|
|
29
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
30
|
+
import { Type } from "typebox";
|
|
31
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
32
|
+
import { isPlanActive } from "../../lib/plan-bridge.js";
|
|
33
|
+
import { readGoalSettings } from "./lib/settings.js";
|
|
34
|
+
import {
|
|
35
|
+
activePrompt,
|
|
36
|
+
applyUsage,
|
|
37
|
+
budgetError,
|
|
38
|
+
budgetLimitPrompt,
|
|
39
|
+
completionBudgetReport,
|
|
40
|
+
continuationPrompt,
|
|
41
|
+
goalTokenDelta,
|
|
42
|
+
shouldContinue,
|
|
43
|
+
statusLine,
|
|
44
|
+
type GoalState,
|
|
45
|
+
type UsageLike,
|
|
46
|
+
type UsageSnapshot,
|
|
47
|
+
} from "./lib/state.js";
|
|
48
|
+
|
|
49
|
+
const GOAL_ENTRY = "ceulen-goal"; // state snapshots (appendEntry data, no renderer)
|
|
50
|
+
const GOAL_STATUS_KEY = "ceulen-goal";
|
|
51
|
+
const GOAL_REPORT_TYPE = "ceulen-goal-report"; // display entry (achieved/stopped)
|
|
52
|
+
const CONTINUE_TYPE = "ceulen-goal-continue"; // hidden continuation turn
|
|
53
|
+
const BUDGET_TYPE = "ceulen-goal-budget"; // hidden wrap-up turn
|
|
54
|
+
|
|
55
|
+
function truncate(text: string, max: number): string {
|
|
56
|
+
return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function defaultMaxTurns(): number {
|
|
60
|
+
return readGoalSettings().maxTurns;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function defaultBudget(): number | undefined {
|
|
64
|
+
return readGoalSettings().defaultBudget;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Goal module factory. All state is module-scoped (one session = one goal);
|
|
69
|
+
* persistence rides pi.appendEntry (branch-scoped, todo/plan pattern) and
|
|
70
|
+
* rehydrates PAUSED on session_start — an unattended loop never resumes by
|
|
71
|
+
* itself after a process restart.
|
|
72
|
+
*/
|
|
73
|
+
export default function goalModule(pi: ExtensionAPI): void {
|
|
74
|
+
let goal: GoalState | undefined;
|
|
75
|
+
// Usage accounting: lastSeenUsage is the last assistant usage snapshot seen
|
|
76
|
+
// (goal or not). Billing: with a pre-goal baseline, only the post-goal delta
|
|
77
|
+
// counts (goal set mid-run); with none (fresh session), the full snapshot
|
|
78
|
+
// bills — the goal fired this session's first run, so all of it is goal work.
|
|
79
|
+
let lastSeenUsage: UsageSnapshot | undefined;
|
|
80
|
+
let lastAccountedAt = 0;
|
|
81
|
+
let pendingDelta = 0;
|
|
82
|
+
// One wrap-up turn per goal: reset on create/resume/budget-raise/clear.
|
|
83
|
+
let budgetReported = false;
|
|
84
|
+
|
|
85
|
+
const setStatus = (ctx?: Pick<ExtensionContext, "ui">): void => {
|
|
86
|
+
try {
|
|
87
|
+
const text =
|
|
88
|
+
goal && goal.status !== "complete" && goal.status !== "stopped"
|
|
89
|
+
? `🎯 ${truncate(goal.objective, 30)} · turn ${goal.turns}/${goal.maxTurns}${
|
|
90
|
+
goal.tokenBudget !== undefined
|
|
91
|
+
? ` · ${Math.min(100, Math.floor((goal.tokensUsed / goal.tokenBudget) * 100))}%`
|
|
92
|
+
: ""
|
|
93
|
+
}`
|
|
94
|
+
: undefined;
|
|
95
|
+
ctx?.ui.setStatus(GOAL_STATUS_KEY, text);
|
|
96
|
+
} catch {
|
|
97
|
+
/* headless ui — statuses are cosmetic */
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const commit = (next: GoalState | undefined, ctx?: Pick<ExtensionContext, "ui">): void => {
|
|
102
|
+
goal = next;
|
|
103
|
+
if (next) pi.appendEntry(GOAL_ENTRY, next);
|
|
104
|
+
setStatus(ctx);
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
const notify = (ctx: Pick<ExtensionContext, "ui">, message: string, level: "info" | "warning" | "error" = "info"): void => {
|
|
108
|
+
try {
|
|
109
|
+
ctx.ui.notify(message, level);
|
|
110
|
+
} catch {
|
|
111
|
+
/* headless */
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
// ---------- lifecycle helpers shared by command and tool ----------
|
|
116
|
+
|
|
117
|
+
const parseBudgetFlag = (text: string): { objective: string; budget?: number; error?: string } => {
|
|
118
|
+
const match = text.match(/\s--budget[=\s](\d+)(?=\s|$)/);
|
|
119
|
+
if (!match) {
|
|
120
|
+
const bad = text.match(/\s--budget(?:[=\s]\S+)?/);
|
|
121
|
+
return bad
|
|
122
|
+
? { objective: text.replace(bad[0], " ").trim(), error: `Invalid --budget value: ${bad[0].trim()} (positive integer expected)` }
|
|
123
|
+
: { objective: text.trim() };
|
|
124
|
+
}
|
|
125
|
+
const budget = Number.parseInt(match[1], 10);
|
|
126
|
+
const objective = text.replace(match[0], " ").trim();
|
|
127
|
+
return { objective, budget };
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
const setGoal = (rawArgs: string, ctx: ExtensionContext): void => {
|
|
131
|
+
const { objective, budget, error } = parseBudgetFlag(rawArgs);
|
|
132
|
+
if (error) {
|
|
133
|
+
notify(ctx, `Goal not set — ${error}`, "error");
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (!objective) {
|
|
137
|
+
showStatus(ctx);
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
if (isPlanActive()) {
|
|
141
|
+
notify(ctx, "Exit plan mode before setting a goal (run /plan).", "warning");
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (goal && goal.status !== "complete" && goal.status !== "stopped") {
|
|
145
|
+
notify(ctx, `A goal is already ${goal.status}: ${goal.objective}. /goal clear first to replace it.`, "warning");
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const db = defaultBudget() ?? 0;
|
|
149
|
+
const effectiveBudget = budget ?? (db > 0 ? db : undefined); // 0 = unbounded default
|
|
150
|
+
const bErr = budgetError(effectiveBudget);
|
|
151
|
+
if (bErr) {
|
|
152
|
+
notify(ctx, `Goal not set — ${bErr}`, "error");
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
const now = Date.now();
|
|
156
|
+
const next: GoalState = {
|
|
157
|
+
objective, // stored RAW; prompt renderers escape at render time
|
|
158
|
+
status: "active",
|
|
159
|
+
tokenBudget: effectiveBudget,
|
|
160
|
+
tokensUsed: 0,
|
|
161
|
+
timeUsedSeconds: 0,
|
|
162
|
+
turns: 0,
|
|
163
|
+
maxTurns: defaultMaxTurns(),
|
|
164
|
+
startedAt: now,
|
|
165
|
+
};
|
|
166
|
+
lastAccountedAt = now;
|
|
167
|
+
budgetReported = false;
|
|
168
|
+
commit(next, ctx);
|
|
169
|
+
notify(ctx, `Goal set: ${objective} (cap ${next.maxTurns} turns${next.tokenBudget !== undefined ? `, budget ${next.tokenBudget} tokens` : ", unbounded"})`);
|
|
170
|
+
void pi.sendUserMessage(objective, { deliverAs: "followUp" });
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
const showStatus = (ctx: Pick<ExtensionContext, "ui">): void => {
|
|
174
|
+
if (!goal) {
|
|
175
|
+
notify(ctx, "No goal set. Use /goal <objective>.");
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
notify(ctx, statusLine(goal));
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
const pauseGoal = (ctx: ExtensionContext, reason?: string): void => {
|
|
182
|
+
if (!goal || goal.status === "complete" || goal.status === "stopped") {
|
|
183
|
+
notify(ctx, "No active goal to pause.");
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
if (goal.status === "paused") {
|
|
187
|
+
notify(ctx, "Goal is already paused.");
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
goal.status = "paused";
|
|
191
|
+
if (reason) goal.lastReason = reason;
|
|
192
|
+
commit(goal, ctx);
|
|
193
|
+
notify(ctx, `Goal paused${reason ? ` (${reason})` : ""}. /goal resume to continue.`);
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const resumeGoal = (ctx: ExtensionContext): void => {
|
|
197
|
+
if (!goal) {
|
|
198
|
+
notify(ctx, "No goal to resume.");
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
if (goal.status === "complete") {
|
|
202
|
+
notify(ctx, "Goal is already complete.");
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
if (goal.status === "active" || goal.status === "budget-limited") {
|
|
206
|
+
notify(ctx, "Goal is already running.");
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
goal.status = "active";
|
|
210
|
+
goal.lastReason = undefined;
|
|
211
|
+
budgetReported = false;
|
|
212
|
+
lastAccountedAt = Date.now();
|
|
213
|
+
commit(goal, ctx);
|
|
214
|
+
notify(ctx, `Goal resumed: ${goal.objective}`);
|
|
215
|
+
void pi.sendMessage(
|
|
216
|
+
{ customType: CONTINUE_TYPE, content: continuationPrompt(goal), display: false },
|
|
217
|
+
{ triggerTurn: true, deliverAs: "followUp" },
|
|
218
|
+
);
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
const clearGoal = (ctx: ExtensionContext): void => {
|
|
222
|
+
if (!goal) {
|
|
223
|
+
notify(ctx, "No goal set.");
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
const was = truncate(goal.objective, 60);
|
|
227
|
+
// Terminal tombstone: the LAST ceulen-goal entry must never be an
|
|
228
|
+
// "active" snapshot, or a restart would resurrect a cleared goal.
|
|
229
|
+
pi.appendEntry(GOAL_ENTRY, { ...goal, status: "stopped" });
|
|
230
|
+
commit(undefined, ctx);
|
|
231
|
+
notify(ctx, `Goal cleared: ${was}`);
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
const mutateBudget = (args: string, ctx: ExtensionContext): void => {
|
|
235
|
+
if (!goal || goal.status === "complete" || goal.status === "stopped") {
|
|
236
|
+
notify(ctx, "No live goal to budget.");
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
const value = args.trim().toLowerCase();
|
|
240
|
+
if (value === "off" || value === "none") {
|
|
241
|
+
goal.tokenBudget = undefined;
|
|
242
|
+
if (goal.status === "budget-limited") goal.status = "active";
|
|
243
|
+
budgetReported = false;
|
|
244
|
+
commit(goal, ctx);
|
|
245
|
+
notify(ctx, "Goal budget removed (unbounded).");
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
const budget = Number.parseInt(value, 10);
|
|
249
|
+
const err = budgetError(budget) ?? (String(budget) !== value ? "goal token budget must be a positive integer when provided" : undefined);
|
|
250
|
+
if (err) {
|
|
251
|
+
notify(ctx, err, "error");
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
goal.tokenBudget = budget;
|
|
255
|
+
// OMP onBudgetMutated semantics, both directions:
|
|
256
|
+
// set a budget already exceeded → budget-limited NOW (+ the one wrap-up
|
|
257
|
+
// turn); raise above usage → back to active.
|
|
258
|
+
if (goal.status === "active" && goal.tokensUsed >= budget) {
|
|
259
|
+
goal.status = "budget-limited";
|
|
260
|
+
if (!budgetReported) {
|
|
261
|
+
budgetReported = true;
|
|
262
|
+
try {
|
|
263
|
+
pi.sendMessage(
|
|
264
|
+
{ customType: BUDGET_TYPE, content: budgetLimitPrompt(goal), display: false },
|
|
265
|
+
{ triggerTurn: true, deliverAs: "followUp" },
|
|
266
|
+
);
|
|
267
|
+
} catch {
|
|
268
|
+
/* fire-and-forget */
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
} else if (goal.status === "budget-limited" && goal.tokensUsed < budget) {
|
|
272
|
+
goal.status = "active";
|
|
273
|
+
budgetReported = false;
|
|
274
|
+
lastAccountedAt = Date.now();
|
|
275
|
+
}
|
|
276
|
+
commit(goal, ctx);
|
|
277
|
+
notify(ctx, `Goal budget set to ${budget} (${goal.tokensUsed.toLocaleString()} used).`);
|
|
278
|
+
};
|
|
279
|
+
|
|
280
|
+
// ---------- /goal command ----------
|
|
281
|
+
|
|
282
|
+
pi.registerCommand("goal", {
|
|
283
|
+
description: "Autonomous goal mode: /goal <objective> [--budget N] | status | pause | resume | clear | budget <N|off>",
|
|
284
|
+
handler: async (args, ctx) => {
|
|
285
|
+
const trimmed = args.trim();
|
|
286
|
+
const [first, ...rest] = trimmed.split(/\s+/);
|
|
287
|
+
const lower = (first ?? "").toLowerCase();
|
|
288
|
+
if (!trimmed || lower === "status") {
|
|
289
|
+
showStatus(ctx);
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
if (lower === "pause") return pauseGoal(ctx);
|
|
293
|
+
if (lower === "resume") return resumeGoal(ctx);
|
|
294
|
+
if (lower === "clear" || lower === "stop" || lower === "off" || lower === "cancel") return clearGoal(ctx);
|
|
295
|
+
if (lower === "budget") return mutateBudget(rest.join(" "), ctx);
|
|
296
|
+
if (lower === "help") {
|
|
297
|
+
notify(
|
|
298
|
+
ctx,
|
|
299
|
+
"/goal <objective> [--budget N] · /goal status · /goal pause · /goal resume · /goal clear · /goal budget <N|off>",
|
|
300
|
+
);
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
setGoal(trimmed, ctx);
|
|
304
|
+
},
|
|
305
|
+
});
|
|
306
|
+
|
|
307
|
+
// ---------- goal tool (DIRECT — never deferred; munin-loop lesson) ----------
|
|
308
|
+
|
|
309
|
+
pi.registerTool({
|
|
310
|
+
name: "goal",
|
|
311
|
+
label: "Goal",
|
|
312
|
+
description:
|
|
313
|
+
'Report on the active goal. op:"get" returns goal + budget state; op:"complete" ends the autonomous loop — call it ONLY when current repo state (files read, commands run, tests passed) directly proves every deliverable of the objective. Budget exhaustion is NOT completion.',
|
|
314
|
+
promptSnippet: 'Report goal progress (get) or verified completion (complete) for the active goal.',
|
|
315
|
+
promptGuidelines: [
|
|
316
|
+
'Call goal({op:"complete"}) only with direct current-state evidence for EVERY deliverable — a bare claim of done is not evidence.',
|
|
317
|
+
"Budget exhaustion ≠ completion: with unfinished work, keep working and leave the goal active.",
|
|
318
|
+
],
|
|
319
|
+
parameters: Type.Object({
|
|
320
|
+
op: Type.Union([Type.Literal("get"), Type.Literal("complete")], {
|
|
321
|
+
description: '"get" = current goal/budget state; "complete" = verified completion, ends the loop.',
|
|
322
|
+
}),
|
|
323
|
+
}),
|
|
324
|
+
annotations: { readOnlyHint: false, idempotentHint: false },
|
|
325
|
+
async execute(_id, params, _signal, _onUpdate, ctx) {
|
|
326
|
+
if (!goal || goal.status === "stopped") {
|
|
327
|
+
return {
|
|
328
|
+
content: [{ type: "text", text: "No active goal." }],
|
|
329
|
+
details: { goal: null },
|
|
330
|
+
isError: true,
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
if (params.op === "get") {
|
|
334
|
+
return {
|
|
335
|
+
content: [{ type: "text", text: statusLine(goal) }],
|
|
336
|
+
details: { goal },
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
// op === "complete"
|
|
340
|
+
if (goal.status === "paused") {
|
|
341
|
+
return {
|
|
342
|
+
content: [{ type: "text", text: "Goal is paused — call goal({op:\"get\"}) and continue working, or wait for the user to resume." }],
|
|
343
|
+
details: { goal },
|
|
344
|
+
isError: true,
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
if (goal.status === "complete") {
|
|
348
|
+
return {
|
|
349
|
+
content: [{ type: "text", text: "Goal is already complete." }],
|
|
350
|
+
details: { goal },
|
|
351
|
+
isError: true,
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
const done: GoalState = { ...goal, status: "complete" };
|
|
355
|
+
const report = `Goal achieved: ${done.objective} · ${done.turns} turn(s) · ${done.tokensUsed.toLocaleString()} tokens`;
|
|
356
|
+
pi.appendEntry(GOAL_ENTRY, done); // terminal tombstone — no restart resurrection
|
|
357
|
+
commit(undefined, ctx);
|
|
358
|
+
budgetReported = false;
|
|
359
|
+
try {
|
|
360
|
+
pi.sendMessage({
|
|
361
|
+
customType: GOAL_REPORT_TYPE,
|
|
362
|
+
content: report,
|
|
363
|
+
display: true,
|
|
364
|
+
details: done,
|
|
365
|
+
});
|
|
366
|
+
ctx.ui.notify(`✓ ${report}`, "info");
|
|
367
|
+
} catch {
|
|
368
|
+
/* headless — the tool result still reports */
|
|
369
|
+
}
|
|
370
|
+
const budgetReport = completionBudgetReport(done);
|
|
371
|
+
return {
|
|
372
|
+
content: [
|
|
373
|
+
{
|
|
374
|
+
type: "text",
|
|
375
|
+
text: budgetReport
|
|
376
|
+
? `${report}\n${budgetReport}`
|
|
377
|
+
: `${report}\nGoal mode ended — report completion to the user in your final answer.`,
|
|
378
|
+
},
|
|
379
|
+
],
|
|
380
|
+
details: { goal: done },
|
|
381
|
+
};
|
|
382
|
+
},
|
|
383
|
+
renderResult: (result, options, theme) => {
|
|
384
|
+
if (options.isPartial || !result) return new Text("", 0, 0);
|
|
385
|
+
const isError = "isError" in result && result.isError;
|
|
386
|
+
const text = result.content.find((c) => c.type === "text");
|
|
387
|
+
const body = text && "text" in text ? text.text : "";
|
|
388
|
+
const icon = isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
|
|
389
|
+
const first = body.split("\n")[0] ?? "";
|
|
390
|
+
return new Text(`${icon} ${first}`, 0, 0);
|
|
391
|
+
},
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
// ---------- display renderer for the achieved/stopped report ----------
|
|
395
|
+
|
|
396
|
+
pi.registerMessageRenderer?.(GOAL_REPORT_TYPE, (message, _opts, theme) => {
|
|
397
|
+
const text = typeof message.content === "string" ? message.content : "Goal report";
|
|
398
|
+
return new Text(theme.fg("success", `🎯 ${text}`), 0, 0);
|
|
399
|
+
});
|
|
400
|
+
|
|
401
|
+
// ---------- usage accounting ----------
|
|
402
|
+
|
|
403
|
+
pi.on("message_end", (event) => {
|
|
404
|
+
const message = event.message as { role?: string; usage?: UsageLike };
|
|
405
|
+
if (message.role !== "assistant" || !message.usage) return;
|
|
406
|
+
const u = message.usage;
|
|
407
|
+
const snap: UsageSnapshot = {
|
|
408
|
+
input: u.input ?? 0,
|
|
409
|
+
output: u.output ?? 0,
|
|
410
|
+
cacheRead: u.cacheRead ?? 0,
|
|
411
|
+
cacheWrite: u.cacheWrite ?? 0,
|
|
412
|
+
};
|
|
413
|
+
const prior = lastSeenUsage;
|
|
414
|
+
lastSeenUsage = snap;
|
|
415
|
+
if (!goal || (goal.status !== "active" && goal.status !== "budget-limited")) return;
|
|
416
|
+
// Billing baseline:
|
|
417
|
+
// - prior snapshot exists (goal set mid-run or after earlier turns) → bill
|
|
418
|
+
// only the post-goal delta.
|
|
419
|
+
// - no prior (fresh session, /goal fired the first run) → bill the full
|
|
420
|
+
// snapshot from a zero baseline: every token this session spent IS goal
|
|
421
|
+
// work (OMP bills turn-1 input the same way). Live-test finding
|
|
422
|
+
// 2026-11-01: lazy-init here dropped the whole first turn (46K tok).
|
|
423
|
+
if (goal.status === "active") {
|
|
424
|
+
pendingDelta += prior
|
|
425
|
+
? goalTokenDelta(snap, prior)
|
|
426
|
+
: Math.max(0, snap.input) + Math.max(0, snap.output) + Math.max(0, snap.cacheWrite);
|
|
427
|
+
}
|
|
428
|
+
});
|
|
429
|
+
|
|
430
|
+
pi.on("turn_end", () => {
|
|
431
|
+
if (!goal || (goal.status !== "active" && goal.status !== "budget-limited")) {
|
|
432
|
+
pendingDelta = 0;
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
const now = Date.now();
|
|
436
|
+
const wallSeconds = lastAccountedAt ? Math.max(0, Math.floor((now - lastAccountedAt) / 1000)) : 0;
|
|
437
|
+
const delta = pendingDelta;
|
|
438
|
+
pendingDelta = 0;
|
|
439
|
+
if (delta <= 0 && wallSeconds <= 0) return;
|
|
440
|
+
goal.timeUsedSeconds += wallSeconds;
|
|
441
|
+
goal.lastReason = undefined;
|
|
442
|
+
const flipped = applyUsage(goal, delta);
|
|
443
|
+
if (lastAccountedAt) lastAccountedAt = now;
|
|
444
|
+
if (flipped && !budgetReported) {
|
|
445
|
+
budgetReported = true;
|
|
446
|
+
// The wrap-up turn STARTS here: followUp + triggerTurn (never a steer —
|
|
447
|
+
// at a turn boundary no live loop can consume one; advisor-found).
|
|
448
|
+
try {
|
|
449
|
+
pi.sendMessage(
|
|
450
|
+
{ customType: BUDGET_TYPE, content: budgetLimitPrompt(goal), display: false },
|
|
451
|
+
{ triggerTurn: true, deliverAs: "followUp" },
|
|
452
|
+
);
|
|
453
|
+
} catch {
|
|
454
|
+
/* send is fire-and-forget; a throw must not abort usage folding */
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
pi.appendEntry(GOAL_ENTRY, goal);
|
|
458
|
+
});
|
|
459
|
+
|
|
460
|
+
// ---------- the continuation loop ----------
|
|
461
|
+
|
|
462
|
+
pi.on("agent_settled", (event, ctx) => {
|
|
463
|
+
const verdict = shouldContinue(goal, { aborted: event.aborted, planActive: isPlanActive() });
|
|
464
|
+
if (verdict === "none") return;
|
|
465
|
+
if (verdict === "pause") {
|
|
466
|
+
pauseGoal(ctx, event.aborted ? "run aborted" : "plan mode active");
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
if (verdict === "stop") {
|
|
470
|
+
const reason = `turn cap ${goal!.maxTurns} reached`;
|
|
471
|
+
if (goal) goal.lastReason = reason;
|
|
472
|
+
goal = goal ? { ...goal, status: "stopped" } : undefined;
|
|
473
|
+
if (goal) pi.appendEntry(GOAL_ENTRY, goal);
|
|
474
|
+
setStatus(ctx);
|
|
475
|
+
notify(ctx, `Goal stopped: ${reason}. ${goal?.objective ?? ""}`, "warning");
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
// continue — fire the next turn (cron's fire mechanism).
|
|
479
|
+
try {
|
|
480
|
+
const current = goal!;
|
|
481
|
+
current.turns += 1;
|
|
482
|
+
commit(current, ctx);
|
|
483
|
+
try {
|
|
484
|
+
pi.sendMessage(
|
|
485
|
+
{ customType: CONTINUE_TYPE, content: continuationPrompt(current), display: false },
|
|
486
|
+
{ triggerTurn: true, deliverAs: "followUp" },
|
|
487
|
+
);
|
|
488
|
+
} catch (e) {
|
|
489
|
+
pauseGoal(ctx, `continuation failed: ${e instanceof Error ? e.message : e}`);
|
|
490
|
+
}
|
|
491
|
+
} catch (e) {
|
|
492
|
+
pauseGoal(ctx, `continuation failed: ${e instanceof Error ? e.message : e}`);
|
|
493
|
+
}
|
|
494
|
+
});
|
|
495
|
+
|
|
496
|
+
// ---------- system-prompt composer (append-only; BEFORE rules/steering) ----------
|
|
497
|
+
|
|
498
|
+
pi.on("before_agent_start", (event) => {
|
|
499
|
+
if (!goal || (goal.status !== "active" && goal.status !== "budget-limited")) return undefined;
|
|
500
|
+
return { systemPrompt: `${event.systemPrompt}\n\n${activePrompt(goal)}` };
|
|
501
|
+
});
|
|
502
|
+
|
|
503
|
+
// ---------- rehydration ----------
|
|
504
|
+
|
|
505
|
+
pi.on("session_start", (_event, ctx) => {
|
|
506
|
+
try {
|
|
507
|
+
const entries = ctx.sessionManager.getBranch() as unknown as
|
|
508
|
+
| { type?: string; customType?: string; data?: GoalState }[]
|
|
509
|
+
| undefined;
|
|
510
|
+
if (!Array.isArray(entries)) return;
|
|
511
|
+
for (let i = entries.length - 1; i >= 0; i -= 1) {
|
|
512
|
+
const entry = entries[i];
|
|
513
|
+
if (entry?.type !== "custom" || entry?.customType !== GOAL_ENTRY) continue;
|
|
514
|
+
const saved = entry.data;
|
|
515
|
+
if (!saved || typeof saved !== "object" || !saved.objective) break;
|
|
516
|
+
// Safe default: an unattended loop NEVER resumes by itself after a
|
|
517
|
+
// process restart — active/budget-limited goals come back paused.
|
|
518
|
+
goal =
|
|
519
|
+
saved.status === "active" || saved.status === "budget-limited"
|
|
520
|
+
? { ...saved, status: "paused", lastReason: "restored paused after restart" }
|
|
521
|
+
: saved;
|
|
522
|
+
lastSeenUsage = undefined;
|
|
523
|
+
lastAccountedAt = 0;
|
|
524
|
+
budgetReported = false;
|
|
525
|
+
setStatus(ctx);
|
|
526
|
+
if (goal.status === "paused") {
|
|
527
|
+
notify(ctx, `Goal restored paused (run /goal resume): ${truncate(goal.objective, 60)}`);
|
|
528
|
+
}
|
|
529
|
+
break;
|
|
530
|
+
}
|
|
531
|
+
} catch {
|
|
532
|
+
/* rehydration is best-effort */
|
|
533
|
+
}
|
|
534
|
+
});
|
|
535
|
+
|
|
536
|
+
// test seam — module-scoped state introspection
|
|
537
|
+
if ((process.env as Record<string, string | undefined>).CEULEN_GOAL_TEST === "1") {
|
|
538
|
+
(pi as unknown as { __goalTest?: object }).__goalTest = {
|
|
539
|
+
get: () => goal,
|
|
540
|
+
set: (next: GoalState | undefined) => {
|
|
541
|
+
goal = next;
|
|
542
|
+
},
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// goal settings — the `goal` section of the GLOBAL agent-dir settings.json.
|
|
2
|
+
// Read per event so a /config save needs no /reload.
|
|
3
|
+
//
|
|
4
|
+
// "goal": {
|
|
5
|
+
// "maxTurns": 50, // hard cap on autonomous continuation turns
|
|
6
|
+
// "defaultBudget": 0 // 0 = unbounded; default token budget for new goals
|
|
7
|
+
// }
|
|
8
|
+
|
|
9
|
+
import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
10
|
+
import os from "node:os";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
|
|
13
|
+
export interface GoalSettings {
|
|
14
|
+
maxTurns: number;
|
|
15
|
+
/** 0 = unbounded (no default token budget). */
|
|
16
|
+
defaultBudget: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export const DEFAULT_GOAL_SETTINGS: GoalSettings = { maxTurns: 50, defaultBudget: 0 };
|
|
20
|
+
|
|
21
|
+
function agentDir(): string {
|
|
22
|
+
return process.env.PI_CODING_AGENT_DIR || path.join(os.homedir(), ".pi", "agent");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function globalSettingsPath(): string {
|
|
26
|
+
return path.join(agentDir(), "settings.json");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function readJson(file: string): Record<string, unknown> | null {
|
|
30
|
+
try {
|
|
31
|
+
if (!existsSync(file)) return null;
|
|
32
|
+
return JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>;
|
|
33
|
+
} catch {
|
|
34
|
+
return null; // unreadable/corrupt → this layer contributes nothing
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function section(json: Record<string, unknown> | null): Record<string, unknown> {
|
|
39
|
+
const raw = json?.goal;
|
|
40
|
+
return raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Read-modify-write `goal` fields into the GLOBAL settings.json (merge, never
|
|
44
|
+
* clobber; atomic tmp+rename; a corrupt file refuses to clobber). Returns the
|
|
45
|
+
* written path. Exported for tests. */
|
|
46
|
+
export function writeGoalSection(patch: Partial<GoalSettings>): string {
|
|
47
|
+
const file = globalSettingsPath();
|
|
48
|
+
let settings: Record<string, unknown>;
|
|
49
|
+
try {
|
|
50
|
+
settings = existsSync(file) ? (JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>) : {};
|
|
51
|
+
} catch {
|
|
52
|
+
// Corrupt ≠ missing: writing here would replace the whole file with ONLY
|
|
53
|
+
// this section — refuse and let the caller surface the error.
|
|
54
|
+
throw new Error(`settings.json is corrupt, refusing to write: ${file}`);
|
|
55
|
+
}
|
|
56
|
+
const next: Record<string, unknown> = { ...(settings.goal as Record<string, unknown> | undefined), ...patch };
|
|
57
|
+
const merged: Record<string, unknown> = { ...settings, goal: next };
|
|
58
|
+
const tmp = `${file}.tmp`;
|
|
59
|
+
writeFileSync(tmp, `${JSON.stringify(merged, null, 2)}\n`);
|
|
60
|
+
renameSync(tmp, file);
|
|
61
|
+
return file;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Effective goal settings: defaults ← global settings.json. */
|
|
65
|
+
export function readGoalSettings(): GoalSettings {
|
|
66
|
+
const out: GoalSettings = { ...DEFAULT_GOAL_SETTINGS };
|
|
67
|
+
const s = section(readJson(globalSettingsPath()));
|
|
68
|
+
if (typeof s.maxTurns === "number" && Number.isInteger(s.maxTurns) && s.maxTurns > 0) out.maxTurns = s.maxTurns;
|
|
69
|
+
if (typeof s.defaultBudget === "number" && Number.isInteger(s.defaultBudget) && s.defaultBudget >= 0) {
|
|
70
|
+
out.defaultBudget = s.defaultBudget;
|
|
71
|
+
}
|
|
72
|
+
return out;
|
|
73
|
+
}
|