@hcflabs/pi-goal 0.0.0-stage → 0.2.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/LICENSE +22 -0
- package/README.md +63 -2
- package/docs/goal-flow.html +97 -0
- package/docs/goal-flow.svg +82 -0
- package/extensions/goal.ts +279 -0
- package/package.json +48 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Henry Wang
|
|
4
|
+
Copyright (c) 2026 hcflabs
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,64 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@hcflabs/pi-goal`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Give the agent one goal, and Pi continues the work after each stop. The loop ends when the agent gives evidence for each deliverable, or when a stop limit applies.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pi install npm:@hcflabs/pi-goal
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Use
|
|
12
|
+
|
|
13
|
+
Ask the agent to work toward a goal, for example: "Make this a goal: all tests pass and the README documents `/export`." The agent calls `goal` with action `create`. When the agent stops before completion, Pi sends a hidden continuation, and the agent continues.
|
|
14
|
+
|
|
15
|
+
| Surface | Type | Purpose |
|
|
16
|
+
| --- | --- | --- |
|
|
17
|
+
| `/goal` | command | For users: show the goal, its status, and tokens used. |
|
|
18
|
+
| `/goal drop` | command | For users: drop the active goal and stop continuation. |
|
|
19
|
+
| `goal` | tool | For agents: create, get, complete, or drop the goal. |
|
|
20
|
+
| Footer status | ui | Shows the active goal objective and tokens used. |
|
|
21
|
+
|
|
22
|
+
The `goal` tool is available to the model only. Other tools, such as `codemode`, cannot call it.
|
|
23
|
+
|
|
24
|
+
### Tool actions
|
|
25
|
+
|
|
26
|
+
| Action | Parameters | Result |
|
|
27
|
+
| --- | --- | --- |
|
|
28
|
+
| `create` | `objective`, optional `deliverables` and `token_budget` | Starts a goal. Fails when a goal is already active. |
|
|
29
|
+
| `get` | — | Shows the goal, tokens used, and remaining budget. |
|
|
30
|
+
| `complete` | `evidence`: one `{ deliverable, evidence }` item for each deliverable | Completes the goal. |
|
|
31
|
+
| `drop` | — | Drops the active goal. |
|
|
32
|
+
|
|
33
|
+
When the goal has no deliverables, `complete` needs one evidence item with deliverable `objective`. The tool rejects missing, blank, duplicate, or unknown evidence items. The agent must get evidence from current state, such as files, command output, or tests. Memory of earlier turns is not evidence.
|
|
34
|
+
|
|
35
|
+
## Flow
|
|
36
|
+
|
|
37
|
+

|
|
38
|
+
|
|
39
|
+
1. Before each user prompt, Pi Goal adds the goal, the budget numbers, and the completion rules as hidden context.
|
|
40
|
+
2. When the agent stops, Pi Goal checks the stop limits. If no limit applies, it adds a hidden continuation with the same goal context.
|
|
41
|
+
3. The agent continues in the same run. A successful `complete` or `drop` ends the loop.
|
|
42
|
+
|
|
43
|
+
Pi Goal does not add a continuation when another extension already continues the same stop. One continuation request then serves both extensions.
|
|
44
|
+
|
|
45
|
+
## State and storage
|
|
46
|
+
|
|
47
|
+
Pi Goal keeps no goal state in memory or in files. It reads the latest goal record from the current conversation branch each time:
|
|
48
|
+
|
|
49
|
+
- `goal` tool results store the full goal in their `details`.
|
|
50
|
+
- `/goal drop` appends a `pi-goal` custom entry.
|
|
51
|
+
- Each continuation is a hidden `pi-goal-continuation` message.
|
|
52
|
+
|
|
53
|
+
Branch navigation, `/tree`, forks, resume, and `/undo` rewinds show the goal of the selected branch. A rewind to a point before `create` removes the goal from that branch.
|
|
54
|
+
|
|
55
|
+
## Limits and recovery
|
|
56
|
+
|
|
57
|
+
| Limit | Behavior | Recovery |
|
|
58
|
+
| --- | --- | --- |
|
|
59
|
+
| Interactive only | Continuation needs a UI. Print mode and other modes without UI do not continue. | Send each next prompt manually. |
|
|
60
|
+
| Maximum continuations | Continuation stops after 20 automatic turns since the latest user prompt. The count includes all goals, so a new goal does not reset it. | Send a prompt to continue. |
|
|
61
|
+
| No progress | Continuation stops when two automatic turns in sequence show identical tool activity. | Send a prompt with new direction, or run `/goal drop`. |
|
|
62
|
+
| Budget | Tokens used are the input, cache write, and output tokens of assistant responses after `create`. Cache reads do not count, because each turn reads the cached context again. Continuation stops when tokens used reach `token_budget`. The goal stays active; it is not complete. | Send a prompt to continue, or run `/goal drop`. |
|
|
63
|
+
| Abort, error, compaction | Continuation stops after an abort or error. A compaction aborts the run, and Pi itself then stops continuation. | Send a prompt to continue. |
|
|
64
|
+
| Evidence | Evidence is model-reported text. Pi Goal checks that it is present, not that it is true. | Examine the evidence in the `complete` result before you accept the work. |
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
+
<title>Pi Goal continuation flow</title>
|
|
7
|
+
<link href="https://fonts.googleapis.com/css2?family=Instrument+Serif&family=Geist:wght@400;600&family=Geist+Mono&display=swap" rel="stylesheet">
|
|
8
|
+
<style>
|
|
9
|
+
body { margin: 0; background: #f0eee9; color: #101828; }
|
|
10
|
+
.diagram-container { overflow-x: auto; }
|
|
11
|
+
svg { display: block; min-width: 1280px; }
|
|
12
|
+
</style>
|
|
13
|
+
</head>
|
|
14
|
+
<body>
|
|
15
|
+
<div class="diagram-container">
|
|
16
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="720" viewBox="0 0 1280 720" role="img" aria-labelledby="goal-flow-title goal-flow-desc">
|
|
17
|
+
<title id="goal-flow-title">Pi Goal continuation flow</title>
|
|
18
|
+
<desc id="goal-flow-desc">A user prompt starts an agent run with hidden goal context. When the agent stops, stop guards decide: if all pass, a hidden continuation starts the next turn in the same run; if any guard stops, Pi settles. A complete or dropped goal ends the loop.</desc>
|
|
19
|
+
<defs>
|
|
20
|
+
<marker id="arrow" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="8" markerHeight="8" orient="auto"><path d="M0 0 L8 4 L0 8Z" fill="#4c5665"/></marker>
|
|
21
|
+
<marker id="arrow-blue" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="8" markerHeight="8" orient="auto"><path d="M0 0 L8 4 L0 8Z" fill="#1d4ed8"/></marker>
|
|
22
|
+
</defs>
|
|
23
|
+
<rect width="1280" height="720" fill="#f0eee9"/>
|
|
24
|
+
<text x="40" y="52" font-family="Instrument Serif, serif" font-size="28" fill="#101828">One goal, continued until evidence or a stop limit</text>
|
|
25
|
+
<!-- Connections precede nodes. Each path has its own attachment point. -->
|
|
26
|
+
<g fill="none" stroke="#4c5665" stroke-width="1.2" marker-end="url(#arrow)">
|
|
27
|
+
<path d="M240 168 H320"/>
|
|
28
|
+
<path d="M560 168 H640"/>
|
|
29
|
+
<path d="M860 168 H960"/>
|
|
30
|
+
<path d="M1100 400 V480"/>
|
|
31
|
+
<path d="M380 216 V480"/>
|
|
32
|
+
<path d="M560 528 H960"/>
|
|
33
|
+
</g>
|
|
34
|
+
<g fill="none" stroke="#1d4ed8" stroke-width="1.6" marker-end="url(#arrow-blue)">
|
|
35
|
+
<path d="M960 352 H860"/>
|
|
36
|
+
<path d="M640 352 H508 Q500 352 500 344 V216"/>
|
|
37
|
+
</g>
|
|
38
|
+
<!-- Label masks stay clear of their connectors and all node rectangles. -->
|
|
39
|
+
<g fill="#f0eee9">
|
|
40
|
+
<rect x="880" y="332" width="60" height="12"/>
|
|
41
|
+
<rect x="532" y="332" width="76" height="12"/>
|
|
42
|
+
<rect x="1104" y="436" width="84" height="12"/>
|
|
43
|
+
<rect x="384" y="292" width="84" height="12"/>
|
|
44
|
+
<rect x="696" y="508" width="128" height="12"/>
|
|
45
|
+
</g>
|
|
46
|
+
<g font-family="Geist Mono, monospace" font-size="8" fill="#4c5665">
|
|
47
|
+
<text x="910" y="341" text-anchor="middle" fill="#1d4ed8">ALL PASS</text>
|
|
48
|
+
<text x="570" y="341" text-anchor="middle" fill="#1d4ed8">CONTINUE: TRUE</text>
|
|
49
|
+
<text x="1108" y="445">ANY GUARD STOPS</text>
|
|
50
|
+
<text x="388" y="301">COMPLETE OR DROP</text>
|
|
51
|
+
<text x="760" y="517" text-anchor="middle">NEXT STOP: NO ACTIVE GOAL</text>
|
|
52
|
+
</g>
|
|
53
|
+
<rect x="40" y="120" width="200" height="96" rx="8" fill="#ffffff" stroke="#101828" stroke-opacity="0.2"/>
|
|
54
|
+
<rect x="320" y="120" width="240" height="96" rx="8" fill="#ffffff" stroke="#101828" stroke-opacity="0.2"/>
|
|
55
|
+
<rect x="640" y="120" width="220" height="96" rx="8" fill="#ffffff" stroke="#101828" stroke-opacity="0.2"/>
|
|
56
|
+
<rect x="960" y="96" width="280" height="304" rx="8" fill="#e6e4de" stroke="#101828" stroke-opacity="0.2"/>
|
|
57
|
+
<rect x="640" y="304" width="220" height="96" rx="8" fill="#1d4ed8" fill-opacity="0.08" stroke="#1d4ed8"/>
|
|
58
|
+
<rect x="320" y="480" width="240" height="96" rx="8" fill="#ffffff" stroke="#101828" stroke-opacity="0.2"/>
|
|
59
|
+
<rect x="960" y="480" width="280" height="96" rx="8" fill="#e6e4de" stroke="#101828" stroke-opacity="0.2"/>
|
|
60
|
+
<g font-family="Geist, sans-serif" font-size="12" font-weight="600" fill="#101828">
|
|
61
|
+
<text x="60" y="152">User prompt</text>
|
|
62
|
+
<text x="340" y="152">Agent run</text>
|
|
63
|
+
<text x="660" y="152">Agent stops</text>
|
|
64
|
+
<text x="984" y="128">Stop guards</text>
|
|
65
|
+
<text x="660" y="336">Hidden continuation</text>
|
|
66
|
+
<text x="340" y="512">Goal complete or dropped</text>
|
|
67
|
+
<text x="984" y="512">Settle</text>
|
|
68
|
+
</g>
|
|
69
|
+
<g font-family="Geist Mono, monospace" font-size="8" fill="#4c5665">
|
|
70
|
+
<text x="60" y="176">before_agent_start</text>
|
|
71
|
+
<text x="60" y="196">+ hidden pi-goal-context</text>
|
|
72
|
+
<text x="340" y="176">model turns and tool calls</text>
|
|
73
|
+
<text x="340" y="196">goal: create / get</text>
|
|
74
|
+
<text x="660" y="176">agent_before_settle</text>
|
|
75
|
+
<text x="660" y="196">goal read from branch</text>
|
|
76
|
+
<text x="984" y="152">another handler continues</text>
|
|
77
|
+
<text x="984" y="176">no active goal</text>
|
|
78
|
+
<text x="984" y="200">no UI</text>
|
|
79
|
+
<text x="984" y="224">outcome: abort or error</text>
|
|
80
|
+
<text x="984" y="248">compaction aborts the run</text>
|
|
81
|
+
<text x="984" y="272">tokens used ≥ token_budget</text>
|
|
82
|
+
<text x="984" y="296">20 continuations since prompt</text>
|
|
83
|
+
<text x="984" y="320">same tool activity twice</text>
|
|
84
|
+
<text x="660" y="360">pi-goal-continuation</text>
|
|
85
|
+
<text x="660" y="380">full goal context</text>
|
|
86
|
+
<text x="340" y="536">complete: evidence per deliverable</text>
|
|
87
|
+
<text x="340" y="556">/goal drop</text>
|
|
88
|
+
<text x="984" y="536">agent_settled</text>
|
|
89
|
+
<text x="984" y="556">an active goal stays active</text>
|
|
90
|
+
</g>
|
|
91
|
+
<text x="984" y="376" font-family="Geist, sans-serif" font-size="12" fill="#4c5665">Any match stops continuation.</text>
|
|
92
|
+
<path d="M40 644 H1240" stroke="#101828" stroke-opacity="0.12"/>
|
|
93
|
+
<text x="40" y="680" font-family="Geist, sans-serif" font-size="12" fill="#4c5665">Hidden messages are not shown in the transcript. Each check reads the goal from the current conversation branch.</text>
|
|
94
|
+
</svg>
|
|
95
|
+
</div>
|
|
96
|
+
</body>
|
|
97
|
+
</html>
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="720" viewBox="0 0 1280 720" role="img" aria-labelledby="goal-flow-title goal-flow-desc" id="goal-flow-root">
|
|
3
|
+
<title id="goal-flow-title">Pi Goal continuation flow</title>
|
|
4
|
+
<desc id="goal-flow-desc">A user prompt starts an agent run with hidden goal context. When the agent stops, stop guards decide: if all pass, a hidden continuation starts the next turn in the same run; if any guard stops, Pi settles. A complete or dropped goal ends the loop.</desc>
|
|
5
|
+
<defs>
|
|
6
|
+
<style>@import url('https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&family=Geist:wght@400;500;600&family=Geist+Mono:wght@400;500;600&display=swap');
|
|
7
|
+
#goal-flow-root { color: #101828; }</style>
|
|
8
|
+
<marker id="goal-flow-arrow" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="8" markerHeight="8" orient="auto"><path d="M0 0 L8 4 L0 8Z" fill="#4c5665"/></marker>
|
|
9
|
+
<marker id="goal-flow-arrow-blue" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="8" markerHeight="8" orient="auto"><path d="M0 0 L8 4 L0 8Z" fill="#1d4ed8"/></marker>
|
|
10
|
+
</defs>
|
|
11
|
+
<rect width="1280" height="720" fill="#f0eee9"/>
|
|
12
|
+
<text x="40" y="52" font-family="Instrument Serif, serif" font-size="28" fill="#101828">One goal, continued until evidence or a stop limit</text>
|
|
13
|
+
<!-- Connections precede nodes. Each path has its own attachment point. -->
|
|
14
|
+
<g fill="none" stroke="#4c5665" stroke-width="1.2" marker-end="url(#goal-flow-arrow)">
|
|
15
|
+
<path d="M240 168 H320"/>
|
|
16
|
+
<path d="M560 168 H640"/>
|
|
17
|
+
<path d="M860 168 H960"/>
|
|
18
|
+
<path d="M1100 400 V480"/>
|
|
19
|
+
<path d="M380 216 V480"/>
|
|
20
|
+
<path d="M560 528 H960"/>
|
|
21
|
+
</g>
|
|
22
|
+
<g fill="none" stroke="#1d4ed8" stroke-width="1.6" marker-end="url(#goal-flow-arrow-blue)">
|
|
23
|
+
<path d="M960 352 H860"/>
|
|
24
|
+
<path d="M640 352 H508 Q500 352 500 344 V216"/>
|
|
25
|
+
</g>
|
|
26
|
+
<!-- Label masks stay clear of their connectors and all node rectangles. -->
|
|
27
|
+
<g fill="#f0eee9">
|
|
28
|
+
<rect x="880" y="332" width="60" height="12"/>
|
|
29
|
+
<rect x="532" y="332" width="76" height="12"/>
|
|
30
|
+
<rect x="1104" y="436" width="84" height="12"/>
|
|
31
|
+
<rect x="384" y="292" width="84" height="12"/>
|
|
32
|
+
<rect x="696" y="508" width="128" height="12"/>
|
|
33
|
+
</g>
|
|
34
|
+
<g font-family="Geist Mono, monospace" font-size="8" fill="#4c5665">
|
|
35
|
+
<text x="910" y="341" text-anchor="middle" fill="#1d4ed8">ALL PASS</text>
|
|
36
|
+
<text x="570" y="341" text-anchor="middle" fill="#1d4ed8">CONTINUE: TRUE</text>
|
|
37
|
+
<text x="1108" y="445">ANY GUARD STOPS</text>
|
|
38
|
+
<text x="388" y="301">COMPLETE OR DROP</text>
|
|
39
|
+
<text x="760" y="517" text-anchor="middle">NEXT STOP: NO ACTIVE GOAL</text>
|
|
40
|
+
</g>
|
|
41
|
+
<rect x="40" y="120" width="200" height="96" rx="8" fill="#ffffff" stroke="#101828" stroke-opacity="0.2"/>
|
|
42
|
+
<rect x="320" y="120" width="240" height="96" rx="8" fill="#ffffff" stroke="#101828" stroke-opacity="0.2"/>
|
|
43
|
+
<rect x="640" y="120" width="220" height="96" rx="8" fill="#ffffff" stroke="#101828" stroke-opacity="0.2"/>
|
|
44
|
+
<rect x="960" y="96" width="280" height="304" rx="8" fill="#e6e4de" stroke="#101828" stroke-opacity="0.2"/>
|
|
45
|
+
<rect x="640" y="304" width="220" height="96" rx="8" fill="#1d4ed8" fill-opacity="0.08" stroke="#1d4ed8"/>
|
|
46
|
+
<rect x="320" y="480" width="240" height="96" rx="8" fill="#ffffff" stroke="#101828" stroke-opacity="0.2"/>
|
|
47
|
+
<rect x="960" y="480" width="280" height="96" rx="8" fill="#e6e4de" stroke="#101828" stroke-opacity="0.2"/>
|
|
48
|
+
<g font-family="Geist, sans-serif" font-size="12" font-weight="600" fill="#101828">
|
|
49
|
+
<text x="60" y="152">User prompt</text>
|
|
50
|
+
<text x="340" y="152">Agent run</text>
|
|
51
|
+
<text x="660" y="152">Agent stops</text>
|
|
52
|
+
<text x="984" y="128">Stop guards</text>
|
|
53
|
+
<text x="660" y="336">Hidden continuation</text>
|
|
54
|
+
<text x="340" y="512">Goal complete or dropped</text>
|
|
55
|
+
<text x="984" y="512">Settle</text>
|
|
56
|
+
</g>
|
|
57
|
+
<g font-family="Geist Mono, monospace" font-size="8" fill="#4c5665">
|
|
58
|
+
<text x="60" y="176">before_agent_start</text>
|
|
59
|
+
<text x="60" y="196">+ hidden pi-goal-context</text>
|
|
60
|
+
<text x="340" y="176">model turns and tool calls</text>
|
|
61
|
+
<text x="340" y="196">goal: create / get</text>
|
|
62
|
+
<text x="660" y="176">agent_before_settle</text>
|
|
63
|
+
<text x="660" y="196">goal read from branch</text>
|
|
64
|
+
<text x="984" y="152">another handler continues</text>
|
|
65
|
+
<text x="984" y="176">no active goal</text>
|
|
66
|
+
<text x="984" y="200">no UI</text>
|
|
67
|
+
<text x="984" y="224">outcome: abort or error</text>
|
|
68
|
+
<text x="984" y="248">compaction aborts the run</text>
|
|
69
|
+
<text x="984" y="272">tokens used ≥ token_budget</text>
|
|
70
|
+
<text x="984" y="296">20 continuations since prompt</text>
|
|
71
|
+
<text x="984" y="320">same tool activity twice</text>
|
|
72
|
+
<text x="660" y="360">pi-goal-continuation</text>
|
|
73
|
+
<text x="660" y="380">full goal context</text>
|
|
74
|
+
<text x="340" y="536">complete: evidence per deliverable</text>
|
|
75
|
+
<text x="340" y="556">/goal drop</text>
|
|
76
|
+
<text x="984" y="536">agent_settled</text>
|
|
77
|
+
<text x="984" y="556">an active goal stays active</text>
|
|
78
|
+
</g>
|
|
79
|
+
<text x="984" y="376" font-family="Geist, sans-serif" font-size="12" fill="#4c5665">Any match stops continuation.</text>
|
|
80
|
+
<path d="M40 644 H1240" stroke="#101828" stroke-opacity="0.12"/>
|
|
81
|
+
<text x="40" y="680" font-family="Geist, sans-serif" font-size="12" fill="#4c5665">Hidden messages are not shown in the transcript. Each check reads the goal from the current conversation branch.</text>
|
|
82
|
+
</svg>
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import type { ExtensionAPI, ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { Type, type Static } from "typebox";
|
|
4
|
+
import { Errors } from "typebox/value";
|
|
5
|
+
|
|
6
|
+
const GOAL_ENTRY = "pi-goal";
|
|
7
|
+
const CONTEXT_MESSAGE = "pi-goal-context";
|
|
8
|
+
export const CONTINUATION_MESSAGE = "pi-goal-continuation";
|
|
9
|
+
export const MAX_CONTINUATIONS = 20;
|
|
10
|
+
const OBJECTIVE_DELIVERABLE = "objective";
|
|
11
|
+
|
|
12
|
+
export interface Goal {
|
|
13
|
+
id: string;
|
|
14
|
+
objective: string;
|
|
15
|
+
deliverables: string[];
|
|
16
|
+
tokenBudget?: number;
|
|
17
|
+
status: "active" | "complete" | "dropped";
|
|
18
|
+
evidence?: Evidence[];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
interface ContinuationDetails {
|
|
22
|
+
activity: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const CLOSED = { additionalProperties: false } as const;
|
|
26
|
+
const NonBlank = Type.String({ pattern: "\\S" });
|
|
27
|
+
const EvidenceItem = Type.Object({
|
|
28
|
+
deliverable: Type.String({ description: `A declared deliverable, or "${OBJECTIVE_DELIVERABLE}" when the goal has none` }),
|
|
29
|
+
evidence: Type.String({ description: "What you inspected now (file, command output, test result) and what it shows" }),
|
|
30
|
+
}, CLOSED);
|
|
31
|
+
type Evidence = Static<typeof EvidenceItem>;
|
|
32
|
+
const Actions = {
|
|
33
|
+
create: Type.Object({
|
|
34
|
+
action: Type.Literal("create"),
|
|
35
|
+
objective: NonBlank,
|
|
36
|
+
deliverables: Type.Optional(Type.Array(NonBlank)),
|
|
37
|
+
token_budget: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
38
|
+
}, CLOSED),
|
|
39
|
+
get: Type.Object({ action: Type.Literal("get") }, CLOSED),
|
|
40
|
+
complete: Type.Object({ action: Type.Literal("complete"), evidence: Type.Array(EvidenceItem, { minItems: 1 }) }, CLOSED),
|
|
41
|
+
drop: Type.Object({ action: Type.Literal("drop") }, CLOSED),
|
|
42
|
+
};
|
|
43
|
+
type GoalInput = { [Action in keyof typeof Actions]: Static<typeof Actions[Action]> }[keyof typeof Actions];
|
|
44
|
+
|
|
45
|
+
// Some providers reject a root union, so the model sees one flat object and execute checks the action variant.
|
|
46
|
+
const GoalParameters = Type.Object({
|
|
47
|
+
action: Type.Union([Type.Literal("create"), Type.Literal("get"), Type.Literal("complete"), Type.Literal("drop")]),
|
|
48
|
+
objective: Type.Optional(Type.String({ description: "create: the full user objective" })),
|
|
49
|
+
deliverables: Type.Optional(Type.Array(Type.String(), { description: "create: concrete outcomes that completion must prove" })),
|
|
50
|
+
token_budget: Type.Optional(Type.Integer({ minimum: 1, description: "create: optional token limit for continuation" })),
|
|
51
|
+
evidence: Type.Optional(Type.Array(EvidenceItem, { description: "complete: one item for each deliverable" })),
|
|
52
|
+
}, CLOSED);
|
|
53
|
+
|
|
54
|
+
function checkedInput(params: Static<typeof GoalParameters>): GoalInput {
|
|
55
|
+
const { action } = params;
|
|
56
|
+
const issue = Errors(Actions[action], params)[0];
|
|
57
|
+
if (!issue) return params as GoalInput;
|
|
58
|
+
// TypeBox reports an unexpected property as a false subschema at that property's path.
|
|
59
|
+
const message = issue.keyword === "boolean" ? "is not allowed" : issue.message;
|
|
60
|
+
throw new Error(`Invalid goal ${action} arguments: ${issue.instancePath || "/"} ${message}.`);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function checkedEvidence(goal: Goal, items: Evidence[]): Evidence[] {
|
|
64
|
+
const required = goal.deliverables.length ? goal.deliverables : [OBJECTIVE_DELIVERABLE];
|
|
65
|
+
const found = new Map<string, string>();
|
|
66
|
+
for (const item of items) {
|
|
67
|
+
const deliverable = item.deliverable.trim();
|
|
68
|
+
if (!required.includes(deliverable)) throw new Error(`Unknown deliverable "${deliverable}". Expected: ${required.map((name) => `"${name}"`).join(", ")}.`);
|
|
69
|
+
if (found.has(deliverable)) throw new Error(`Duplicate evidence for "${deliverable}".`);
|
|
70
|
+
if (!item.evidence.trim()) throw new Error(`Evidence for "${deliverable}" is blank.`);
|
|
71
|
+
found.set(deliverable, item.evidence.trim());
|
|
72
|
+
}
|
|
73
|
+
const missing = required.filter((name) => !found.has(name));
|
|
74
|
+
if (missing.length) throw new Error(`Missing evidence for: ${missing.map((name) => `"${name}"`).join(", ")}.`);
|
|
75
|
+
return required.map((deliverable) => ({ deliverable, evidence: found.get(deliverable)! }));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function goalRecord(entry: SessionEntry): Goal | undefined {
|
|
79
|
+
if (entry.type === "custom" && entry.customType === GOAL_ENTRY) return (entry.data as { goal?: Goal } | undefined)?.goal;
|
|
80
|
+
if (entry.type !== "message" || entry.message.role !== "toolResult") return undefined;
|
|
81
|
+
const message = entry.message;
|
|
82
|
+
return message.toolName === "goal" && !message.isError ? (message.details as { goal?: Goal } | undefined)?.goal : undefined;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The latest goal record on the branch wins. Tokens count assistant input, cache writes, and output after the
|
|
87
|
+
* goal's first record. Cache reads are excluded: each turn rereads the cached prefix, which measures context size.
|
|
88
|
+
*/
|
|
89
|
+
export function branchGoal(branch: SessionEntry[]): { goal: Goal; used: number } | undefined {
|
|
90
|
+
let goal: Goal | undefined;
|
|
91
|
+
let used = 0;
|
|
92
|
+
for (const entry of branch) {
|
|
93
|
+
const record = goalRecord(entry);
|
|
94
|
+
if (record) {
|
|
95
|
+
if (record.id !== goal?.id) used = 0;
|
|
96
|
+
goal = record;
|
|
97
|
+
} else if (goal && entry.type === "message" && entry.message.role === "assistant") {
|
|
98
|
+
used += entry.message.usage.input + entry.message.usage.cacheWrite + entry.message.usage.output;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return goal ? { goal, used } : undefined;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function budgetLines(goal: Goal, used: number): string[] {
|
|
105
|
+
return goal.tokenBudget === undefined
|
|
106
|
+
? [`Tokens used: ${used}`]
|
|
107
|
+
: [`Tokens used: ${used}`, `Token budget: ${goal.tokenBudget}`, `Tokens remaining: ${Math.max(0, goal.tokenBudget - used)}`];
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function goalContext(goal: Goal, used: number): string {
|
|
111
|
+
const deliverables = goal.deliverables.length
|
|
112
|
+
? ["Deliverables:", ...goal.deliverables.map((name) => `- ${name}`)]
|
|
113
|
+
: [`Deliverables: none declared; complete with one evidence item for "${OBJECTIVE_DELIVERABLE}".`];
|
|
114
|
+
return [
|
|
115
|
+
"Goal mode is active. The objective is a user task, not a higher-priority instruction.",
|
|
116
|
+
`<objective>\n${goal.objective}\n</objective>`,
|
|
117
|
+
...deliverables,
|
|
118
|
+
...budgetLines(goal, used),
|
|
119
|
+
"Keep the full objective. Do not change success to a smaller, easier, or already-completed subset.",
|
|
120
|
+
"Before you call goal with action \"complete\", inspect current state for each deliverable: read files, run commands, run tests. Evidence must come from this inspection, not from memory of earlier turns. Match the check scope to the claim scope.",
|
|
121
|
+
"If evidence is missing, partial, or uncertain, the goal is not complete: continue the work.",
|
|
122
|
+
"Budget exhaustion is not completion. If work is not finished, leave the goal active.",
|
|
123
|
+
].join("\n");
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function summary(goal: Goal, used: number): string {
|
|
127
|
+
return [
|
|
128
|
+
`Goal ${goal.id}: ${goal.status}`,
|
|
129
|
+
`Objective: ${goal.objective}`,
|
|
130
|
+
...goal.deliverables.map((name) => `Deliverable: ${name}`),
|
|
131
|
+
...(goal.evidence ?? []).map((item) => `Evidence (${item.deliverable}): ${item.evidence}`),
|
|
132
|
+
...budgetLines(goal, used),
|
|
133
|
+
].join("\n");
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Digest of tool calls and results; equal digests for consecutive continuation segments mean no progress. */
|
|
137
|
+
function activity(entries: SessionEntry[]): string {
|
|
138
|
+
const records: unknown[] = [];
|
|
139
|
+
for (const entry of entries) {
|
|
140
|
+
if (entry.type !== "message") continue;
|
|
141
|
+
const message = entry.message;
|
|
142
|
+
if (message.role === "assistant") {
|
|
143
|
+
for (const block of message.content) if (block.type === "toolCall") records.push(["call", block.name, block.arguments]);
|
|
144
|
+
} else if (message.role === "toolResult") records.push(["result", message.toolName, message.content, message.isError]);
|
|
145
|
+
}
|
|
146
|
+
return createHash("sha256").update(JSON.stringify(records)).digest("hex");
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export default function goalExtension(pi: ExtensionAPI): void {
|
|
150
|
+
// Transient notice state only; the goal itself is always derived from the branch.
|
|
151
|
+
const notices = new Set<string>();
|
|
152
|
+
|
|
153
|
+
const showStatus = (ctx: ExtensionContext, state: { goal: Goal; used: number } | undefined) => {
|
|
154
|
+
if (state?.goal.status !== "active") return ctx.ui.setStatus(GOAL_ENTRY, undefined);
|
|
155
|
+
const { goal, used } = state;
|
|
156
|
+
const objective = goal.objective.length > 40 ? `${goal.objective.slice(0, 39)}…` : goal.objective;
|
|
157
|
+
ctx.ui.setStatus(GOAL_ENTRY, `Goal: ${objective} (${used}${goal.tokenBudget === undefined ? "" : `/${goal.tokenBudget}`} tokens)`);
|
|
158
|
+
};
|
|
159
|
+
const refresh = (ctx: ExtensionContext) => showStatus(ctx, branchGoal(ctx.sessionManager.getBranch()));
|
|
160
|
+
const stop = (ctx: ExtensionContext, key: string, message: string) => {
|
|
161
|
+
if (notices.has(key)) return;
|
|
162
|
+
notices.add(key);
|
|
163
|
+
ctx.ui.notify(message, "warning");
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
pi.registerTool({
|
|
167
|
+
name: "goal",
|
|
168
|
+
label: "Goal",
|
|
169
|
+
description: [
|
|
170
|
+
"Track one persistent goal on this conversation branch. While a goal is active, Pi continues work automatically when you stop.",
|
|
171
|
+
"create: set objective, optional deliverables and token_budget. Fails if a goal is already active.",
|
|
172
|
+
"get: show the goal, tokens used, and remaining budget.",
|
|
173
|
+
`complete: give non-empty evidence for every deliverable (or one item for "${OBJECTIVE_DELIVERABLE}" when none are declared). Evidence must come from inspecting current state (files, command output, tests) now, not from memory.`,
|
|
174
|
+
"drop: abandon the goal.",
|
|
175
|
+
].join("\n"),
|
|
176
|
+
promptSnippet: "Track a persistent goal and complete it only with current-state evidence",
|
|
177
|
+
parameters: GoalParameters,
|
|
178
|
+
// Nested calls (codemode, ctx.executeTool) leave no transcript result, so the branch would lose them.
|
|
179
|
+
exposure: "model-only",
|
|
180
|
+
executionMode: "sequential",
|
|
181
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
182
|
+
const input = checkedInput(params);
|
|
183
|
+
const state = branchGoal(ctx.sessionManager.getBranch());
|
|
184
|
+
const active = state?.goal.status === "active" ? state : undefined;
|
|
185
|
+
let next: { goal: Goal; used: number };
|
|
186
|
+
if (input.action === "create") {
|
|
187
|
+
if (active) throw new Error(`Goal ${active.goal.id} is already active. Complete or drop it first.`);
|
|
188
|
+
const deliverables = (input.deliverables ?? []).map((name) => name.trim());
|
|
189
|
+
if (new Set(deliverables).size !== deliverables.length) throw new Error("Deliverables must be unique.");
|
|
190
|
+
next = { used: 0, goal: {
|
|
191
|
+
id: randomUUID(), objective: input.objective.trim(), deliverables,
|
|
192
|
+
...(input.token_budget === undefined ? {} : { tokenBudget: input.token_budget }),
|
|
193
|
+
status: "active",
|
|
194
|
+
} };
|
|
195
|
+
} else if (input.action === "get") {
|
|
196
|
+
if (!state) throw new Error("No goal on this branch.");
|
|
197
|
+
next = state;
|
|
198
|
+
} else {
|
|
199
|
+
if (!active) throw new Error("No active goal on this branch.");
|
|
200
|
+
next = { used: active.used, goal: input.action === "complete"
|
|
201
|
+
? { ...active.goal, status: "complete", evidence: checkedEvidence(active.goal, input.evidence) }
|
|
202
|
+
: { ...active.goal, status: "dropped" } };
|
|
203
|
+
}
|
|
204
|
+
showStatus(ctx, next);
|
|
205
|
+
return { content: [{ type: "text", text: summary(next.goal, next.used) }], details: { goal: next.goal } };
|
|
206
|
+
},
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
pi.registerCommand("goal", {
|
|
210
|
+
description: "Show the goal, or drop it with /goal drop",
|
|
211
|
+
handler: async (args, ctx) => {
|
|
212
|
+
const state = branchGoal(ctx.sessionManager.getBranch());
|
|
213
|
+
if (!args.trim()) {
|
|
214
|
+
ctx.ui.notify(state ? summary(state.goal, state.used) : "No goal on this branch.", "info");
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
if (args.trim() !== "drop") {
|
|
218
|
+
ctx.ui.notify("Usage: /goal [drop]", "error");
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
if (state?.goal.status !== "active") {
|
|
222
|
+
ctx.ui.notify("No active goal on this branch.", "info");
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
pi.appendEntry(GOAL_ENTRY, { goal: { ...state.goal, status: "dropped" } });
|
|
226
|
+
refresh(ctx);
|
|
227
|
+
ctx.ui.notify("Goal dropped.", "info");
|
|
228
|
+
},
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
pi.on("session_start", (_event, ctx) => {
|
|
232
|
+
notices.clear();
|
|
233
|
+
refresh(ctx);
|
|
234
|
+
});
|
|
235
|
+
pi.on("session_tree", (_event, ctx) => refresh(ctx));
|
|
236
|
+
pi.on("agent_settled", (_event, ctx) => refresh(ctx));
|
|
237
|
+
|
|
238
|
+
pi.on("before_agent_start", (_event, ctx) => {
|
|
239
|
+
const state = branchGoal(ctx.sessionManager.getBranch());
|
|
240
|
+
if (state?.goal.status !== "active") return;
|
|
241
|
+
return { message: { customType: CONTEXT_MESSAGE, display: false, content: `<goal_context>\n${goalContext(state.goal, state.used)}\n</goal_context>` } };
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
pi.on("agent_before_settle", (event, ctx) => {
|
|
245
|
+
// Another handler already requests the next turn; one request serves both, and its draft must survive.
|
|
246
|
+
if (event.continue || event.entries.some((entry) => entry.type === "custom_message")) return;
|
|
247
|
+
if (!ctx.hasUI) return;
|
|
248
|
+
const branch = ctx.sessionManager.getBranch();
|
|
249
|
+
const state = branchGoal(branch);
|
|
250
|
+
if (state?.goal.status !== "active" || event.outcome !== "completed") return;
|
|
251
|
+
const { goal, used } = state;
|
|
252
|
+
if (goal.tokenBudget !== undefined && used >= goal.tokenBudget) {
|
|
253
|
+
stop(ctx, `budget:${goal.id}`, `Goal token budget is exhausted (${used}/${goal.tokenBudget}). The goal stays active, not complete. Continue it with a prompt or run /goal drop.`);
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
const userIndex = branch.findLastIndex((entry) => entry.type === "message" && entry.message.role === "user");
|
|
257
|
+
// Count across goals: completing and recreating a goal must not reset the cap within one user turn.
|
|
258
|
+
const continuations = branch.flatMap((entry, index) => index > userIndex && entry.type === "custom_message" &&
|
|
259
|
+
entry.customType === CONTINUATION_MESSAGE ? [index] : []);
|
|
260
|
+
if (continuations.length >= MAX_CONTINUATIONS) {
|
|
261
|
+
stop(ctx, `max:${branch[userIndex]?.id}`, `Goal continuation stopped after ${MAX_CONTINUATIONS} automatic turns. Send a prompt to continue.`);
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
const latest = continuations.at(-1);
|
|
265
|
+
const current = activity(branch.slice((latest ?? userIndex) + 1));
|
|
266
|
+
if (latest !== undefined && (branch[latest] as { details?: ContinuationDetails }).details?.activity === current) {
|
|
267
|
+
stop(ctx, `idle:${branch[latest]!.id}`, "Goal continuation stopped: the last automatic turn made no new tool progress. Send a prompt to continue.");
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
const details: ContinuationDetails = { activity: current };
|
|
271
|
+
return {
|
|
272
|
+
entries: [...event.entries, {
|
|
273
|
+
type: "custom_message" as const, customType: CONTINUATION_MESSAGE, display: false, details,
|
|
274
|
+
content: `Continue the active goal. Do the next step; do not describe the continuation.\n\n${goalContext(goal, used)}`,
|
|
275
|
+
}],
|
|
276
|
+
continue: true,
|
|
277
|
+
};
|
|
278
|
+
});
|
|
279
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,50 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hcflabs/pi-goal",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Persistent Pi goals that continue automatically until completion is proven with evidence.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"pi-package",
|
|
7
|
+
"pi",
|
|
8
|
+
"goal",
|
|
9
|
+
"autonomous"
|
|
10
|
+
],
|
|
11
|
+
"type": "module",
|
|
12
|
+
"engines": {
|
|
13
|
+
"node": ">=22.19.0"
|
|
14
|
+
},
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"files": [
|
|
17
|
+
"LICENSE",
|
|
18
|
+
"docs",
|
|
19
|
+
"extensions",
|
|
20
|
+
"README.md"
|
|
21
|
+
],
|
|
22
|
+
"scripts": {
|
|
23
|
+
"test": "node --test test/*.test.ts",
|
|
24
|
+
"typecheck": "tsc --noEmit --allowImportingTsExtensions --target ES2023 --module NodeNext --moduleResolution NodeNext --skipLibCheck extensions/goal.ts test/*.test.ts",
|
|
25
|
+
"pack:check": "npm pack --dry-run"
|
|
26
|
+
},
|
|
27
|
+
"peerDependencies": {
|
|
28
|
+
"@earendil-works/pi-coding-agent": "^1.6.0",
|
|
29
|
+
"typebox": "^1.3.15"
|
|
30
|
+
},
|
|
31
|
+
"repository": {
|
|
32
|
+
"type": "git",
|
|
33
|
+
"url": "git+https://github.com/hcflabs/pi-harness.git",
|
|
34
|
+
"directory": "extensions/pi-goal"
|
|
35
|
+
},
|
|
36
|
+
"bugs": {
|
|
37
|
+
"url": "https://github.com/hcflabs/pi-harness/issues"
|
|
38
|
+
},
|
|
39
|
+
"publishConfig": {
|
|
40
|
+
"access": "public"
|
|
41
|
+
},
|
|
42
|
+
"pi": {
|
|
43
|
+
"extensions": [
|
|
44
|
+
"./extensions/goal.ts"
|
|
45
|
+
]
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@earendil-works/pi-coding-agent": "1.6.0"
|
|
49
|
+
}
|
|
50
|
+
}
|