pi-onlooker 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,22 @@
1
+ # Changelog
2
+
3
+ Pi shows the entries newer than your installed version after `pi update`.
4
+
5
+ ## [Unreleased]
6
+
7
+ ## [0.1.0] - 2026-11-16
8
+
9
+ - First release. A second AI model checks the Pi agent's work and tells it when it breaks your instructions, repeats a failure or claims work it did not do. It works in a private session and reports Blockers, Concerns and Nits, each with evidence.
10
+ - Requires Pi 1.5.1 or later. On Pi 1.5.0, grep results for lines that contain a carriage return are hidden.
11
+ - Each finding the agent receives states the last turn the Review observed, the number of later turns it did not review, and its evidence as `tool#ref` or a quote. The Onlooker drops a finding whose quote does not occur verbatim in the evidence it was given. This reduces the risk that the agent acts on an outdated or invented finding; it does not prove the finding still applies.
12
+ - Concerns and Blockers can trigger one corrective continuation per interactive request. Set `correct` to `false` to disable it. Cancelling during post-run compaction suppresses pending and late corrective continuations until a new user request.
13
+ - The Onlooker can only use `read`, `grep`, `find` and `ls`, inside the project and the agent's session file. Secret files are refused.
14
+ - The agent can ask the Onlooker a question with `onlooker_ask`.
15
+ - With `--no-session`, the Onlooker keeps its private session in memory and writes no file.
16
+ - `ONLOOKER.md` files give the Onlooker review guidance the agent never sees.
17
+ - The footer shows the Onlooker state with activity, waiting and pause icons, its display name and its model. `/onlooker status` shows the details.
18
+ - Set the display name in the `/onlooker` menu or with `/onlooker set name "Inspector gadget"`. Renaming keeps the private session and the attribution of earlier findings.
19
+ - At its tool call limit, the Onlooker is asked to report with what it has, instead of being paused.
20
+ - The default prompt tells the Onlooker that the agent's choice of tool for a step is not an instruction violation.
21
+ - `/onlooker status` shows the cost of Reviews, consultations and compactions separately, and the evidence the Onlooker did not see in full.
22
+ - `/onlooker` command and menu with six settings (`enabled`, `name`, `model`, `thinkingLevel`, `reviewEvery`, `correct`) per session, project or global scope, and `/skill:pi-onlooker` for diagnosis. Other limits are fixed. Anthropic Reviews use the 1-hour prompt cache with Pi's `PI_CACHE_RETENTION=long`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hugo Lopes
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,175 @@
1
- # Temporary Holding Version
1
+ # pi-onlooker: a second pair of eyes for the Pi coding agent
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![CI](https://github.com/HugoLopes45/pi-extensions/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/HugoLopes45/pi-extensions/actions/workflows/ci.yml)
4
+ [![npm](https://img.shields.io/npm/v/pi-onlooker)](https://www.npmjs.com/package/pi-onlooker)
5
+ [![Pi package](https://img.shields.io/badge/pi.dev-package-blue)](https://pi.dev/packages/pi-onlooker)
6
+ [![Node.js](https://img.shields.io/node/v/pi-onlooker)](https://nodejs.org)
7
+ [![License: MIT](https://img.shields.io/npm/l/pi-onlooker)](LICENSE)
8
+
9
+ **A second AI model checks the Pi agent's work while it runs.** When the agent gets something wrong, the Onlooker tells it, and the agent fixes it before you have to.
10
+
11
+ ```bash
12
+ pi install npm:pi-onlooker
13
+ ```
14
+
15
+ > **Not on npm yet.** Until the first release, this command fails. Run `pi install ./packages/pi-onlooker` from the root of your pi-extensions clone instead.
16
+
17
+ Then turn it on with `/onlooker on --global`. Each Review is a paid model request that sees your conversation: read [Limits](#limits) first.
18
+
19
+ ## Why pi-onlooker
20
+
21
+ Coding agents sometimes say "done, all tests pass" when the last test run failed. They skip one of your instructions, or retry the same broken command again and again.
22
+
23
+ - **Unproven claims.** It catches a claim such as "tests pass" or "done" that the work does not prove.
24
+ - **Broken instructions.** It catches an instruction that the agent broke, or work that you did not ask for.
25
+ - **Repeated failures.** It catches a failure that the agent repeats without a change.
26
+ - **Small cleanups.** It suggests a small cleanup worth doing.
27
+ - **Proof, not opinions.** Each finding points to a tool call or a quote from the session. The Onlooker drops a finding without proof.
28
+ - **The agent fixes it, not you.** Findings reach the agent through Pi's message queue.
29
+ - **Advice, not a gate.** It never blocks the agent and never overrides you. To block commands before they run, use a permission extension, such as Pi's `permission-gate` example.
30
+ - **The models you already have.** By default, it uses the agent's model. You can pick any model that Pi can use.
31
+
32
+ ## What you see
33
+
34
+ The agent writes "All tests pass." After the Review, the agent receives this message:
35
+
36
+ ```text
37
+ Onlooker blocker: The agent says the tests pass, but the last test run (ref kX3b9_Qa) failed.
38
+ ```
39
+
40
+ The agent reads it at its next step and corrects its work. You do nothing.
41
+
42
+ ## Quick start
43
+
44
+ You need Pi 1.5.1 or later and Node.js 22.19 or later.
45
+
46
+ 1. Install the package with the command above.
47
+ 2. In Pi, run `/onlooker on --global`. The Onlooker stays off until you turn it on.
48
+ 3. Look at the footer. It shows `○ Onlooker` and the Onlooker model while waiting for work.
49
+ 4. To stop, run `/onlooker off --global`.
50
+
51
+ ## Footer
52
+
53
+ | Footer | State |
54
+ | -------------------------------- | ------------------------------------------------------------------------- |
55
+ | `○ Onlooker · claude-haiku-4-5` | Waiting for the next Review; dim indicator. |
56
+ | `● Onlooker · claude-haiku-4-5` | Reviewing or answering `onlooker_ask`; colored activity indicator. |
57
+ | `! Onlooker · claude-haiku-4-5` | Paused; warning-colored indicator. See `/onlooker status` for the reason. |
58
+ | nothing | Off. |
59
+
60
+ The footer uses the configured display name and shows the model without its provider. The backlog count stays in `/onlooker status`, not in the footer.
61
+
62
+ ## Commands
63
+
64
+ ```text
65
+ /onlooker settings menu
66
+ /onlooker status state, settings, backlog, cost, last error
67
+ /onlooker on | off enable, disable, or resume after a pause
68
+ /onlooker set <key> <JSON> change a setting
69
+ /onlooker inherit [key] remove a setting at this scope (no key: enabled)
70
+ ```
71
+
72
+ A change applies to the current session only. Add `--project` or `--global` to save it. The session value wins over the project value, which wins over the global value. Project settings need a trusted project.
73
+
74
+ Values are JSON, so put text in quotes: `/onlooker set model "anthropic/claude-haiku-4-5"`.
75
+
76
+ ## How it works
77
+
78
+ After the agent finishes a turn, the Onlooker reviews it. Each finding has a severity:
79
+
80
+ | Severity | Use | Effect |
81
+ | --------- | ----------------------------------- | ------------------------------------------- |
82
+ | `blocker` | Wrong or unsafe work, false claims. | Steers the running agent. |
83
+ | `concern` | A real risk or a likely wrong path. | Steers the running agent. |
84
+ | `nit` | Small, low-risk cleanup. | Added to the conversation without steering. |
85
+
86
+ Steering is Pi's native message queue: the agent reads the finding at its next step, without an abort. Findings are advice: the agent decides whether each applies. After a Concern or Blocker, in an interactive session, the Onlooker starts one hidden turn when the run ends (a Corrective Turn): the agent decides what to do with the findings, then continues your task. Set `correct` to `false` to turn this off. The Onlooker never blocks a tool and never overrides you. Failures pause it while the agent continues, except an exhausted consultation quota.
87
+
88
+ The agent can also ask the Onlooker a question with the `onlooker_ask` tool. The answer is plain Markdown and creates no finding. After 8 investigative calls, further calls are blocked and the model gets one turn to conclude. If it requests more tools on that turn, the consultation fails without pausing automatic Reviews. Supply the diff in the question or observed context for a change review: the Onlooker has no Git command tool.
89
+
90
+ ## Settings
91
+
92
+ You can also write them in Pi's `settings.json` (`~/.pi/agent/settings.json` or `.pi/settings.json`), under `onlooker`:
93
+
94
+ ```json
95
+ { "onlooker": { "enabled": true, "model": "anthropic/claude-haiku-4-5", "reviewEvery": "request" } }
96
+ ```
97
+
98
+ | Key | Default | Meaning |
99
+ | --------------- | ----------------- | ------------------------------------------------------------------------------------------------------- |
100
+ | `name` | `"Onlooker"` | Display name, such as `"Marcel"` or `"Inspector gadget"`. |
101
+ | `enabled` | `false` | Onlooker on or off. |
102
+ | `model` | the agent's model | `"provider/model-id"` for Reviews and `onlooker_ask`. |
103
+ | `thinkingLevel` | `"high"` | `"off"`, `"minimal"`, `"low"`, `"medium"`, `"high"`, `"xhigh"` or `"max"`. Never copied from the agent. |
104
+ | `reviewEvery` | `"turn"` | `"turn"`, `"request"` or a number of turns. See below. |
105
+ | `correct` | `true` | After a Concern or Blocker, start one Corrective Turn so the agent continues. |
106
+
107
+ Other limits are fixed: at most 4 findings per Review, 1 Corrective Turn per request, 8 tool calls and 120 s per Review or `onlooker_ask` call, tool results cut to 4,000 characters, a first Context Seed of a quarter of the model's context window (at most 50,000 tokens), and compaction of the Onlooker history past half the window (at most 100,000 tokens). The agent waits for the running Review, at most 30 s, when 3 turns are not yet reviewed. The Onlooker always sees the agent's reasoning. For a 1-hour Anthropic prompt cache, set Pi's `PI_CACHE_RETENTION=long`; OpenAI Reviews always use the long cache.
108
+
109
+ ### Display name
110
+
111
+ Open `/onlooker`, select `name`, and enter Marcel or Inspector gadget. Spaces are allowed; blank names, surrounding whitespace and control characters are rejected. Enter `inherit` to remove the selected scope’s override.
112
+
113
+ To save a name globally, run `/onlooker set name "Inspector gadget" --global`. The name appears in the footer, status and findings. Renaming keeps the private session and earlier findings’ attribution unchanged. The menu title, `/onlooker` command and `onlooker_ask` tool identifier stay fixed.
114
+
115
+ ### `reviewEvery`
116
+
117
+ - `"turn"`: a Review after each turn that changes something. A turn that only reads waits for the next Review.
118
+ - a number `N`: a Review every N turns and at the end of the request.
119
+ - `"request"`: one Review at the end of the request. Cheapest; findings come after the agent stops.
120
+
121
+ A failed tool call starts a Review at once, whatever the value.
122
+
123
+ ### `ONLOOKER.md`
124
+
125
+ Write what the Onlooker should watch for in an `ONLOOKER.md` file. The agent never sees it. The Onlooker reads `~/.pi/agent/ONLOOKER.md`, then `ONLOOKER.md` and `.pi/ONLOOKER.md` in each folder from the git root (or your home folder) down to the working folder. All files apply, in that order. Project guidance files and their `.pi` directories must not be symlinks; such links stop session creation. The Onlooker already judges the agent against the agent's own `AGENTS.md` files, so do not copy them here.
126
+
127
+ ## Limits
128
+
129
+ - **It rarely makes the agent wait.** The agent waits, at most 30 s, only when 3 turns are not yet reviewed.
130
+ - **It needs a trusted provider.** The Onlooker model receives the agent's conversation.
131
+
132
+ ### Cost
133
+
134
+ Each Review can make several paid requests to the Onlooker model. Each request resends its active private history; cache savings depend on the provider. Seed and compaction budgets are estimates, not spending caps. To pay less: `reviewEvery: "request"`, a cheaper `model`, or a lower `thinkingLevel`. `/onlooker status` shows, separately for Reviews, consultations and compactions: model calls, input, cache and output tokens, cost and time. It also counts the observed messages the Onlooker did not see in full.
135
+
136
+ ### Privacy and access
137
+
138
+ - It cannot edit files, run commands or use the network.
139
+ - The Onlooker runs in its own private Pi session, with the agent's providers and credentials. That session loads no other extension, skill or context file.
140
+ - Its tools can only read: `read`, `grep`, `find`, `ls`. They see the project folder, but cannot read the observed session journal, even inside that folder. They refuse known secret filenames such as `.env`, private keys, credentials and `.git`. Paths containing Unicode spaces that Pi rewrites are rejected.
141
+ - The extension itself runs with Pi's permissions. Install it only if you trust it.
142
+
143
+ ## Troubleshooting
144
+
145
+ Run `/onlooker status` first. It shows the error and the counts of withheld and dropped findings. For a guided diagnosis, run `/skill:pi-onlooker`.
146
+
147
+ **`Onlooker: paused: ...`**: fix the cause in the message, then run `/onlooker on`.
148
+
149
+ **`Onlooker model is unavailable: ...`**: set a model from `/model`, or run `/onlooker inherit model`.
150
+
151
+ **`Onlooker review deadline exceeded`**: pick a faster `model` or a lower `thinkingLevel`, then run `/onlooker on`.
152
+
153
+ **`Onlooker project settings require a trusted project`**: trust the project, or use `--global`.
154
+
155
+ **`... is not JSON; quote text values ...`**: put the value in quotes.
156
+
157
+ ## Update, try or remove
158
+
159
+ ```bash
160
+ pi update npm:pi-onlooker # update, then restart Pi
161
+ pi -e npm:pi-onlooker # try for one session without installing
162
+ pi remove npm:pi-onlooker # remove, then restart Pi
163
+ ```
164
+
165
+ ## Contributing
166
+
167
+ See [CONTRIBUTING.md](https://github.com/HugoLopes45/pi-extensions/blob/main/CONTRIBUTING.md) for setup, checks and releases. Report bugs on [GitHub Issues](https://github.com/HugoLopes45/pi-extensions/issues), and vulnerabilities through [SECURITY.md](https://github.com/HugoLopes45/pi-extensions/blob/main/SECURITY.md).
168
+
169
+ ## Author
170
+
171
+ Built by [Hugo Lopes](https://github.com/HugoLopes45), a senior frontend developer based in Paris, passionate about AI and agent harnesses.
172
+
173
+ ## License
174
+
175
+ [MIT](LICENSE)
@@ -0,0 +1,410 @@
1
+ import * as piSdk from "@earendil-works/pi-coding-agent";
2
+ import type {
3
+ AgentSession,
4
+ ExtensionAPI,
5
+ ExtensionContext,
6
+ ExtensionUIContext,
7
+ } from "@earendil-works/pi-coding-agent";
8
+ import { Type } from "typebox";
9
+
10
+ import { completeOnlookerCommandArguments, parseOnlookerCommand } from "../src/onlooker-command.js";
11
+ import {
12
+ OnlookerSettingsMenu,
13
+ type OnlookerMenuHost,
14
+ type OnlookerScopedOptions,
15
+ } from "../src/onlooker-menu.js";
16
+ import { OnlookerObserver } from "../src/onlooker-observer.js";
17
+ import {
18
+ onlookerAskToolName as askToolName,
19
+ onlookerFooterText,
20
+ onlookerStatusHeadline,
21
+ renderOnlookerAskCall,
22
+ renderOnlookerAskResult,
23
+ renderOnlookerIntervention,
24
+ renderOnlookerStatus,
25
+ type OnlookerActivity,
26
+ type OnlookerRenderTheme,
27
+ type OnlookerStatusEntry,
28
+ } from "../src/onlooker-rendering.js";
29
+ import { isOnlookerSession } from "../src/onlooker-session.js";
30
+ import {
31
+ readOnlookerLayers,
32
+ readOnlookerOverrides,
33
+ readOnlookerSettings,
34
+ writeOnlookerSettings,
35
+ type OnlookerLayers,
36
+ type OnlookerChange,
37
+ type OnlookerAppliedChange,
38
+ type OnlookerSettingScope,
39
+ } from "../src/onlooker-settings.js";
40
+ import { TROUBLESHOOTING_HINT } from "../src/troubleshooting-skill.js";
41
+ import { expandEntryOnClick, expandMessageOnClick } from "../src/utils/expand-on-click.js";
42
+ import { acceptNullForOptionalArguments } from "../src/utils/null-optional-arguments.js";
43
+ import { discoverPiAgentSession } from "../src/utils/pi-agent-session-discovery.js";
44
+ import { noticeText } from "../src/utils/ui.js";
45
+
46
+ const askToolParameters = Type.Object(
47
+ { message: Type.String({ minLength: 1 }) },
48
+ { additionalProperties: false },
49
+ );
50
+ /** Live status fields while no Onlooker Session observes. */
51
+ function idleStatus(enabled: boolean) {
52
+ return {
53
+ state: enabled ? ("armed" as const) : ("disabled" as const),
54
+ backlog: 0,
55
+ effectiveModel: null,
56
+ effectiveThinkingLevel: null,
57
+ usage: null,
58
+ cost: null,
59
+ spend: null,
60
+ droppedFindings: { unsupported: 0, invalidReviews: 0 },
61
+ lastError: null,
62
+ };
63
+ }
64
+
65
+ /** Review an observed session without changing its tools or standing instructions. */
66
+ export default function onlooker(pi: ExtensionAPI): void {
67
+ let warn: (message: string) => void = () => {};
68
+ let footer: ExtensionUIContext | undefined;
69
+ /** The open settings menu, refreshed on state changes and closed on session changes. */
70
+ let activeMenu: { refresh: () => void; close: () => void } | undefined;
71
+ let observed: AgentSession | undefined;
72
+ let error: string | undefined;
73
+ let displayName = "Onlooker";
74
+ let layers: OnlookerLayers = { global: {}, project: {} };
75
+ let generation = 0;
76
+ let privateSession = false;
77
+ let observer: OnlookerObserver | undefined;
78
+ let askToolRegistered = false;
79
+ pi.registerEntryRenderer(
80
+ "pi-onlooker-status",
81
+ expandEntryOnClick((entry, { expanded }, theme) =>
82
+ renderOnlookerStatus(entry.data, expanded, theme),
83
+ ),
84
+ );
85
+ pi.registerMessageRenderer(
86
+ "pi-onlooker",
87
+ expandMessageOnClick((message, options, theme) =>
88
+ renderOnlookerIntervention(message.details, options, theme),
89
+ ),
90
+ );
91
+
92
+ /** Show the current Onlooker state in the open settings menu and the footer. */
93
+ function publishState(): void {
94
+ activeMenu?.refresh();
95
+ if (!footer) return;
96
+ const root: OnlookerActivity | undefined =
97
+ observer?.status ?? (observed && error ? { state: "paused", name: displayName } : undefined);
98
+ try {
99
+ footer.setStatus("onlooker", onlookerFooterText(root, footer.theme));
100
+ } catch {
101
+ // A replaced session's UI is stale; status entries remain authoritative.
102
+ }
103
+ }
104
+
105
+ function setAskToolAvailable(available: boolean): void {
106
+ if (available && !askToolRegistered) {
107
+ const askTool = piSdk.defineTool({
108
+ name: askToolName,
109
+ label: "Ask Onlooker",
110
+ description:
111
+ "Ask the Onlooker, a second model that reviews your work, for analysis or a second opinion. Waits for its answer. It reads files but cannot edit them or run commands.",
112
+ parameters: askToolParameters,
113
+ annotations: {
114
+ readOnlyHint: true,
115
+ destructiveHint: false,
116
+ idempotentHint: true,
117
+ openWorldHint: false,
118
+ },
119
+ executionMode: "sequential",
120
+ renderCall: (args, theme, context) =>
121
+ renderOnlookerAskCall(args, context.expanded, theme, context),
122
+ renderResult: (result, options, theme, context) =>
123
+ renderOnlookerAskResult(
124
+ result.content.map((item) => (item.type === "text" ? item.text : "")).join(""),
125
+ { expanded: options.expanded, isPartial: options.isPartial, isError: context.isError },
126
+ theme,
127
+ context,
128
+ ),
129
+ execute: async (_id, { message }, signal) => {
130
+ try {
131
+ const current = observer;
132
+ if (!current)
133
+ throw new Error(
134
+ `${error ?? "Onlooker consultation is unavailable"}. Inspect /onlooker status, then run /onlooker on or correct its configuration.`,
135
+ );
136
+ const answer = await current.consult(message, signal);
137
+ return { content: [{ type: "text", text: answer }], details: {} };
138
+ } catch (cause) {
139
+ // Caller cancellation is not a malfunction the Skill diagnoses.
140
+ if (signal?.aborted) throw cause;
141
+ const text = cause instanceof Error ? cause.message : String(cause);
142
+ throw new Error(`${text}\n\n${TROUBLESHOOTING_HINT}`, { cause });
143
+ }
144
+ },
145
+ });
146
+ pi.registerTool(acceptNullForOptionalArguments(askTool));
147
+ askToolRegistered = true;
148
+ return;
149
+ }
150
+ if (!askToolRegistered) return;
151
+ const active = pi.getActiveTools();
152
+ if (available === active.includes(askToolName)) return;
153
+ pi.setActiveTools(
154
+ available ? [...active, askToolName] : active.filter((name) => name !== askToolName),
155
+ );
156
+ }
157
+
158
+ pi.on("session_start", async (_event, ctx) => {
159
+ activeMenu?.close();
160
+ const stamp = ++generation;
161
+ const previous = observer;
162
+ observer = undefined;
163
+ await previous?.dispose();
164
+ if (stamp !== generation) return;
165
+ observed = undefined;
166
+ error = undefined;
167
+ privateSession = isOnlookerSession(ctx.sessionManager);
168
+ displayName = "Onlooker";
169
+ if (privateSession) {
170
+ setAskToolAvailable(false);
171
+ return;
172
+ }
173
+ const { ui } = ctx;
174
+ footer = ctx.hasUI ? ui : undefined;
175
+ warn = (message) => {
176
+ try {
177
+ ui.notify(message, "warning");
178
+ } catch {
179
+ // A replaced session's UI is stale; the native status entry remains the durable record.
180
+ }
181
+ };
182
+ const found = discoverPiAgentSession(pi, piSdk.AgentSession);
183
+ if (found.ok) {
184
+ observed = found.session;
185
+ layers = readOnlookerLayers(observed.settingsManager);
186
+ await refresh(ctx);
187
+ } else {
188
+ error = found.warning;
189
+ setAskToolAvailable(true);
190
+ }
191
+ });
192
+ pi.on("session_tree", async (_event, ctx) => {
193
+ activeMenu?.close();
194
+ generation++;
195
+ observer?.reset();
196
+ await refresh(ctx);
197
+ });
198
+ pi.on("model_select", () => observer?.modelChanged());
199
+ // Since Pi 1.2 a custom message's run, such as a corrective continuation, fires this too.
200
+ pi.on("before_agent_start", (event) => {
201
+ if (event.messageType !== "custom") observer?.beforeTask();
202
+ });
203
+ pi.on("agent_before_settle", (event) => observer?.beforeSettle(event));
204
+ pi.on("agent_settled", (event) => observer?.settled(event.aborted));
205
+ pi.on("session_shutdown", async () => {
206
+ activeMenu?.close();
207
+ generation++;
208
+ observed = undefined;
209
+ await observer?.dispose();
210
+ observer = undefined;
211
+ publishState();
212
+ footer = undefined;
213
+ });
214
+
215
+ async function refresh(ctx: ExtensionContext): Promise<void> {
216
+ if (!observed || privateSession) return;
217
+ try {
218
+ const { settings } = readOnlookerSettings(observed, layers);
219
+ displayName = settings.name;
220
+ if (observer) observer.configure(settings);
221
+ else
222
+ observer = new OnlookerObserver(
223
+ observed,
224
+ settings,
225
+ ctx.hasUI ? "interactive" : "headless-root",
226
+ {
227
+ onError: (message) => {
228
+ pi.appendEntry("pi-onlooker-status", {
229
+ state: "paused",
230
+ error: message,
231
+ settings: { name: displayName },
232
+ });
233
+ warn(noticeText(displayName, `paused: ${message}`));
234
+ },
235
+ onStateChange: publishState,
236
+ },
237
+ );
238
+ setAskToolAvailable(settings.enabled);
239
+ } catch (cause) {
240
+ error = cause instanceof Error ? cause.message : String(cause);
241
+ setAskToolAvailable(true);
242
+ await observer?.dispose();
243
+ observer = undefined;
244
+ }
245
+ publishState();
246
+ }
247
+
248
+ /** Current effective settings and live Onlooker state, as recorded in status entries. */
249
+ function statusData(subject: AgentSession): OnlookerStatusEntry {
250
+ const resolved = readOnlookerSettings(subject, layers);
251
+ const live = observer?.status ?? idleStatus(resolved.settings.enabled);
252
+ return { ...resolved, ...live, error: error ?? live.lastError };
253
+ }
254
+
255
+ function status(ctx: ExtensionContext, changes: readonly OnlookerAppliedChange[] = []): void {
256
+ try {
257
+ if (!observed) throw new Error(error ?? "Onlooker session is unavailable");
258
+ const entry = statusData(observed);
259
+ if (changes.length) entry.changes = [...changes];
260
+ pi.appendEntry("pi-onlooker-status", entry);
261
+ } catch (cause) {
262
+ error = cause instanceof Error ? cause.message : String(cause);
263
+ pi.appendEntry("pi-onlooker-status", { state: "paused", error, usage: null, cost: null });
264
+ }
265
+ if (error) ctx.ui.notify(noticeText(displayName, error), "error");
266
+ }
267
+
268
+ /** Persist one validated change at its scope and reconfigure; undefined if superseded. */
269
+ async function applyChange(
270
+ ctx: ExtensionContext,
271
+ subject: AgentSession,
272
+ scope: OnlookerSettingScope,
273
+ change: OnlookerChange,
274
+ isCurrent: () => boolean,
275
+ ): Promise<OnlookerAppliedChange | undefined> {
276
+ if (scope === "session") {
277
+ const overrides = readOnlookerOverrides(subject.sessionManager);
278
+ if (change.action === "inherit") delete overrides[change.key];
279
+ else Object.assign(overrides, change.patch);
280
+ pi.appendEntry("pi-onlooker-settings", { version: 1, overrides });
281
+ } else {
282
+ const updated = await writeOnlookerSettings(
283
+ subject.settingsManager,
284
+ scope,
285
+ change,
286
+ isCurrent,
287
+ );
288
+ if (!isCurrent() || !updated) return undefined;
289
+ layers[scope] = updated;
290
+ }
291
+ error = undefined;
292
+ await refresh(ctx);
293
+ return { scope, key: change.key, options: change.action === "inherit" ? {} : change.patch };
294
+ }
295
+
296
+ /** The settings menu's view of this extension's settings authority. */
297
+ function menuHost(
298
+ ctx: ExtensionContext,
299
+ subject: AgentSession,
300
+ theme: OnlookerRenderTheme,
301
+ applied: OnlookerAppliedChange[],
302
+ ): OnlookerMenuHost {
303
+ return {
304
+ view() {
305
+ const data = statusData(subject);
306
+ const authored: Partial<OnlookerScopedOptions> = {
307
+ session: readOnlookerOverrides(subject.sessionManager),
308
+ };
309
+ if (!(layers.project instanceof Error)) authored.project = layers.project;
310
+ if (!(layers.global instanceof Error)) authored.global = layers.global;
311
+ return {
312
+ headline: onlookerStatusHeadline(data, theme),
313
+ paused: data.state === "paused",
314
+ scopes: subject.settingsManager.isProjectTrusted()
315
+ ? ["session", "project", "global"]
316
+ : ["session", "global"],
317
+ settings: data.settings ?? {},
318
+ sources: data.sources ?? {},
319
+ authored,
320
+ models: ctx.modelRegistry.getAvailable().map((model) => `${model.provider}/${model.id}`),
321
+ };
322
+ },
323
+ async apply(scope, change) {
324
+ const stamp = ++generation;
325
+ const result = await applyChange(
326
+ ctx,
327
+ subject,
328
+ scope,
329
+ change,
330
+ () => generation === stamp && observed === subject,
331
+ );
332
+ if (result) applied.push(result);
333
+ },
334
+ async resume() {
335
+ error = undefined;
336
+ await refresh(ctx);
337
+ },
338
+ };
339
+ }
340
+
341
+ /** Native settings list in the editor area, as `/settings` does; one status entry on close. */
342
+ async function openMenu(ctx: ExtensionContext, subject: AgentSession): Promise<void> {
343
+ const applied: OnlookerAppliedChange[] = [];
344
+ let discarded = false;
345
+ let menu: OnlookerSettingsMenu | undefined;
346
+ await ctx.ui.custom<void>((tui, theme, _keybindings, done) => {
347
+ const opened = new OnlookerSettingsMenu(
348
+ menuHost(ctx, subject, theme, applied),
349
+ {
350
+ tui,
351
+ theme,
352
+ },
353
+ () => done(),
354
+ );
355
+ menu = opened;
356
+ activeMenu = {
357
+ refresh: () => {
358
+ opened.refresh();
359
+ tui.requestRender();
360
+ },
361
+ close: () => {
362
+ discarded = true;
363
+ activeMenu = undefined;
364
+ done();
365
+ },
366
+ };
367
+ return opened;
368
+ });
369
+ activeMenu = undefined;
370
+ // Edits started before closing are still recorded once they settle.
371
+ await menu?.settled();
372
+ if (!discarded && observed === subject && applied.length) status(ctx, applied);
373
+ }
374
+
375
+ pi.registerCommand("onlooker", {
376
+ description: "Onlooker settings menu, or on, off, inherit, set, and status",
377
+ getArgumentCompletions: completeOnlookerCommandArguments,
378
+ async handler(args, ctx) {
379
+ if (privateSession) {
380
+ pi.appendEntry("pi-onlooker-status", {
381
+ state: "private",
382
+ error: "Private Onlooker Sessions cannot create another Onlooker",
383
+ });
384
+ return;
385
+ }
386
+ const subject = observed;
387
+ let stamp = generation;
388
+ const isCurrent = () => generation === stamp && observed === subject;
389
+ let applied: OnlookerAppliedChange | undefined;
390
+ try {
391
+ if (!subject) throw new Error(error ?? "Onlooker session is unavailable");
392
+ const command = parseOnlookerCommand(args);
393
+ if (command.action === "menu" && ctx.mode === "tui") {
394
+ // Opening fails closed to the status entry when settings cannot be read.
395
+ statusData(subject);
396
+ await openMenu(ctx, subject);
397
+ return;
398
+ }
399
+ if (command.action !== "status" && command.action !== "menu") {
400
+ stamp = ++generation;
401
+ applied = await applyChange(ctx, subject, command.scope, command, isCurrent);
402
+ }
403
+ } catch (cause) {
404
+ if (!isCurrent()) return;
405
+ error = cause instanceof Error ? cause.message : String(cause);
406
+ }
407
+ if (isCurrent()) status(ctx, applied ? [applied] : []);
408
+ },
409
+ });
410
+ }