pi-onlooker 0.1.2 → 0.1.3

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 CHANGED
@@ -2,6 +2,13 @@
2
2
 
3
3
  Pi shows the entries newer than your installed version after `pi update`.
4
4
 
5
+ ## 0.1.3
6
+
7
+ ### Patch Changes
8
+
9
+ - A Review that passes its 120 s deadline no longer pauses the Onlooker. The next turn's Review covers its turns instead, and the Onlooker pauses only after 3 late Reviews in a row.
10
+ - Text from the reviewer model, provider errors and settings now shows without terminal control sequences, so it can no longer change the window title, clear the screen or add hidden links. Line breaks and tabs stay.
11
+
5
12
  ## 0.1.2
6
13
 
7
14
  ### Patch Changes
package/README.md CHANGED
@@ -146,7 +146,7 @@ Run `/onlooker status` first. It shows the error and the counts of withheld and
146
146
 
147
147
  **`Onlooker model is unavailable: ...`**: set a model from `/model`, or run `/onlooker inherit model`.
148
148
 
149
- **`Onlooker review deadline exceeded`**: pick a faster `model` or a lower `thinkingLevel`, then run `/onlooker on`.
149
+ **`Onlooker review deadline exceeded`**: 3 Reviews in a row passed their 120 s deadline. A single late Review is left to the next turn. Pick a faster `model` or a lower `thinkingLevel`, then run `/onlooker on`.
150
150
 
151
151
  **`Onlooker project settings require a trusted project`**: trust the project, or use `--global`.
152
152
 
@@ -89,6 +89,14 @@ export function resolveLayeredOptions<Config extends object>(
89
89
  return { settings, sources };
90
90
  }
91
91
 
92
+ // Settings text reaches terminal notifications; raw control characters would run escape sequences.
93
+ export function escapeControls(text: string): string {
94
+ return text.replace(
95
+ /\p{Cc}/gu,
96
+ (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`,
97
+ );
98
+ }
99
+
92
100
  /** Why {@link rewriteNamespaceDocument} refused a stored settings document. */
93
101
  export type InvalidSettingsDocument = "malformed" | "root" | "namespace";
94
102
 
@@ -151,6 +159,7 @@ export interface LayeredSettingsDefinition<
151
159
  merge?: Merge;
152
160
  /** Keep the namespace in a settings document after its last option is removed. */
153
161
  keepEmptyNamespace?: boolean;
162
+ globalOnlyKeys?: readonly (keyof Static<S> & keyof Config & string)[];
154
163
  }
155
164
 
156
165
  /**
@@ -275,8 +284,16 @@ export function defineLayeredSettings<
275
284
  type OptionKey = keyof Options & keyof Config & string;
276
285
  type Layers = LayeredSettingsLayers<Options>;
277
286
  type Change = LayeredSettingChange<Options>;
278
- const { namespace, label, schema, defaults, sessionEntryType, merge, keepEmptyNamespace } =
279
- definition;
287
+ const {
288
+ namespace,
289
+ label,
290
+ schema,
291
+ defaults,
292
+ sessionEntryType,
293
+ merge,
294
+ keepEmptyNamespace,
295
+ globalOnlyKeys = [],
296
+ } = definition;
280
297
  if (!Value.Check(schema, {}))
281
298
  throw new Error(`${label} settings schema must make every option optional`);
282
299
  const keySchema = Type.KeyOf(schema);
@@ -317,6 +334,16 @@ export function defineLayeredSettings<
317
334
  return structuredClone(empty);
318
335
  }
319
336
 
337
+ function checkScope(options: Options, source: LayeredSettingScope): void {
338
+ if (source === "global") return;
339
+ for (const key of globalOnlyKeys) {
340
+ if (Object.hasOwn(options, key))
341
+ throw new Error(
342
+ `Invalid ${source} ${label} settings: ${key} is global-only; set it in global settings`,
343
+ );
344
+ }
345
+ }
346
+
320
347
  // Native settings contain arbitrary authored JSON; the option schema validates it before use. SDK command tests exercise the boundary.
321
348
  function parseOptions(value: unknown, source: LayeredSettingScope): Options {
322
349
  if (value === undefined) return noOptions();
@@ -324,12 +351,13 @@ export function defineLayeredSettings<
324
351
  const issue = Value.Errors(schema, value)[0];
325
352
  if (issue?.schemaPath === "#/additionalProperties")
326
353
  throw new Error(
327
- `Invalid ${source} ${label} settings: unknown option ${issue.instancePath.slice(1)}`,
354
+ `Invalid ${source} ${label} settings: unknown option ${escapeControls(issue.instancePath.slice(1))}`,
328
355
  );
329
356
  throw new Error(
330
- `Invalid ${source} ${label} settings${issue?.instancePath ?? ""}: ${issue?.message ?? "invalid options"}`,
357
+ `Invalid ${source} ${label} settings${escapeControls(issue?.instancePath ?? "")}: ${issue?.message ?? "invalid options"}`,
331
358
  );
332
359
  }
360
+ checkScope(value, source);
333
361
  return structuredClone(value);
334
362
  }
335
363
 
@@ -340,6 +368,7 @@ export function defineLayeredSettings<
340
368
  .findLast((item) => item.type === "custom" && item.customType === sessionEntryType);
341
369
  if (!entry || entry.type !== "custom") return noOptions();
342
370
  if (!isSessionData(entry.data)) throw new Error(`Invalid ${label} session settings`);
371
+ checkScope(entry.data.overrides, "session");
343
372
  return structuredClone(entry.data.overrides);
344
373
  }
345
374
 
@@ -368,11 +397,12 @@ export function defineLayeredSettings<
368
397
  authored = readLayers(session.settingsManager),
369
398
  ) {
370
399
  if (authored.global instanceof Error) throw authored.global;
371
- const trusted = session.settingsManager.isProjectTrusted();
372
- if (trusted && authored.project instanceof Error) throw authored.project;
400
+ const project = session.settingsManager.isProjectTrusted() ? authored.project : noOptions();
401
+ if (project instanceof Error) throw project;
402
+ checkScope(project, "project");
373
403
  const layers: (readonly [LayeredSettingScope, LayeredSettingLayer<Config>])[] = [
374
404
  ["global", authored.global],
375
- ["project", trusted && !(authored.project instanceof Error) ? authored.project : noOptions()],
405
+ ["project", project],
376
406
  ];
377
407
  if (sessionEntryType !== undefined)
378
408
  layers.push(["session", readOverrides(session.sessionManager)]);
@@ -411,7 +441,7 @@ export function defineLayeredSettings<
411
441
  keepEmpty: keepEmptyNamespace === true,
412
442
  invalid: (reason, cause) =>
413
443
  reason === "malformed" && cause
414
- ? cause
444
+ ? new SyntaxError(escapeControls(cause.message), { cause })
415
445
  : new Error(`Invalid ${scope} settings document; refusing to overwrite it`),
416
446
  update: (stored) => {
417
447
  const next = { ...stored };
@@ -441,7 +471,12 @@ export function defineLayeredSettings<
441
471
  session: LayeredSettingsSession,
442
472
  ): LenientLayeredSettings<Options, Config> {
443
473
  // Pi reads an unloadable file as empty, so only its recorded error shows the problem.
444
- const invalid: Error[] = session.settingsManager.drainErrors().map((entry) => entry.error);
474
+ const invalid: Error[] = session.settingsManager.drainErrors().map(
475
+ (entry) =>
476
+ new Error(escapeControls(entry.error.message), {
477
+ cause: entry.error,
478
+ }),
479
+ );
445
480
  const layers = readLayers(session.settingsManager);
446
481
  const usable = (layer: Options | Error): Options => {
447
482
  if (!(layer instanceof Error)) return layer;
@@ -486,8 +521,9 @@ export function defineLayeredSettings<
486
521
  const overrides = readOverrides(session.sessionManager);
487
522
  if (change.action === "inherit") Reflect.deleteProperty(overrides, change.key);
488
523
  else Object.assign(overrides, change.patch);
489
- pi.appendEntry(sessionEntry, { version: 1, overrides });
490
- return overrides;
524
+ const validated = parseOptions(overrides, "session");
525
+ pi.appendEntry(sessionEntry, { version: 1, overrides: validated });
526
+ return validated;
491
527
  }
492
528
 
493
529
  return { ...settings, readOverrides, readSettingsLeniently, writeChange };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-onlooker",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "A second AI model checks the Pi coding agent's work and tells it when it breaks your instructions, repeats a failure or claims work it did not do.",
5
5
  "keywords": [
6
6
  "ai-agent",
@@ -29,14 +29,14 @@ Rules:
29
29
  | error `Onlooker project settings require a trusted project` | Project settings need a trusted project. | Trust the project, or use `--global`. |
30
30
  | paused, with an error | A Review or `onlooker_ask` failed. | Fix the named cause, then `/onlooker on`. |
31
31
  | error `Onlooker model is unavailable` | `model` names a model with no credentials or no entry. | `/onlooker set model "provider/model-id" --global`, then `/onlooker on`. |
32
- | error `Onlooker review deadline exceeded` | A Review took more than 120 s. | Faster `model` or lower `thinkingLevel`. Then `/onlooker on`. |
32
+ | error `Onlooker review deadline exceeded` | 3 Reviews in a row took more than 120 s. | Faster `model` or lower `thinkingLevel`. Then `/onlooker on`. |
33
33
  | `N findings without valid evidence dropped` | The finding cited no `ref` or quote, or an unknown `ref`. | If frequent, use a stronger `model`. |
34
34
  | `N Reviews ended by invalid reports` | The model sent 2 invalid `onlooker_report` calls. | If frequent, use a stronger `model`. |
35
35
  | high cost | Each Review re-reads the Onlooker history. | In this order: `reviewEvery` `"request"`, a cheaper `model`, a lower `thinkingLevel`. |
36
36
 
37
37
  Other symptoms:
38
38
 
39
- - **No Review.** `reviewEvery` `"turn"` skips a turn that only reads. `N` and `"request"` wait for their cadence point. A failed tool call always starts a Review.
39
+ - **No Review.** `reviewEvery` `"turn"` skips a turn that only reads. `N` and `"request"` wait for their cadence point. A failed tool call always starts a Review. A Review past its 120 s deadline leaves its turns to the next Review.
40
40
  - **`onlooker_ask` missing.** The tool exists only while `enabled` is true. While paused, it returns the pause reason.
41
41
  - **A finding ignores long tool output.** Results longer than 4,000 characters keep their start and end; the Onlooker can `read` the full result in the session file.
42
42
 
@@ -154,11 +154,13 @@ interface OperationBase {
154
154
  }
155
155
  interface Review extends OperationBase {
156
156
  kind: "review";
157
+ through: number;
157
158
  findings?: OnlookerFinding[];
158
159
  /** `onlooker_report` calls rejected as invalid in this Review. */
159
160
  rejectedReports: number;
160
161
  /** Set when rejected reports ended this Review; it then delivers and re-validates nothing. */
161
162
  invalid?: boolean;
163
+ timedOut?: true;
162
164
  }
163
165
  interface Consultation extends OperationBase {
164
166
  kind: "consultation";
@@ -219,6 +221,7 @@ async function awaitWithSignal(
219
221
 
220
222
  /** `onlooker_report` calls rejected in one Review before it ends without findings. */
221
223
  const reportAttempts = 2;
224
+ const maxDeadlinesInRow = 3;
222
225
 
223
226
  /**
224
227
  * The failure that ended the operation since `since`. A failed tool call followed by more work is
@@ -276,6 +279,9 @@ export class OnlookerObserver {
276
279
  private reviewed = 0;
277
280
  /** Completed turns a Review is due to cover, according to `reviewEvery`. */
278
281
  private dueThrough = 0;
282
+ /** A Review past its deadline waits for a new turn rather than retrying the same evidence. */
283
+ private skippedThrough = 0;
284
+ private deadlinesInRow = 0;
279
285
  /** Spend since this observer started, across Onlooker Session rebuilds and resets. */
280
286
  private spend: OnlookerSpend = {
281
287
  reviews: idleWork(),
@@ -526,7 +532,7 @@ export class OnlookerObserver {
526
532
  this.closed ||
527
533
  !this.config.enabled ||
528
534
  this.error ||
529
- this.dueThrough <= this.reviewed
535
+ this.dueThrough <= Math.max(this.reviewed, this.skippedThrough)
530
536
  )
531
537
  return;
532
538
  const review: Review = {
@@ -538,13 +544,16 @@ export class OnlookerObserver {
538
544
  calls: 0,
539
545
  started: Date.now(),
540
546
  rejectedReports: 0,
547
+ through: this.completed,
541
548
  };
542
549
  this.active = review;
543
550
  const operation = this.review(review)
544
551
  .then(() => this.compactAfter(review))
545
552
  .catch((cause) => {
546
- if (review.epoch === this.epoch && !this.closed && this.sameObservation(review))
547
- this.fail(errorText(cause));
553
+ if (review.epoch !== this.epoch || this.closed || !this.sameObservation(review)) return;
554
+ if (review.timedOut && ++this.deadlinesInRow < maxDeadlinesInRow)
555
+ this.skippedThrough = review.through;
556
+ else this.fail(errorText(cause));
548
557
  })
549
558
  .finally(() => {
550
559
  if (this.running !== operation) return;
@@ -563,10 +572,10 @@ export class OnlookerObserver {
563
572
  }
564
573
 
565
574
  private async review(review: Review): Promise<void> {
566
- const timer = setTimeout(
567
- () => review.cancellation.abort(new Error("Onlooker review deadline exceeded")),
568
- this.limits.reviewTimeoutMs,
569
- );
575
+ const timer = setTimeout(() => {
576
+ review.timedOut = true;
577
+ review.cancellation.abort(new Error("Onlooker review deadline exceeded"));
578
+ }, this.limits.reviewTimeoutMs);
570
579
  const cancelled = Promise.withResolvers<never>();
571
580
  const rejectCancellation = () => cancelled.reject(review.cancellation.signal.reason);
572
581
  review.cancellation.signal.addEventListener("abort", rejectCancellation, { once: true });
@@ -867,7 +876,7 @@ export class OnlookerObserver {
867
876
  }
868
877
 
869
878
  private async performReview(review: Review): Promise<void> {
870
- const through = this.completed;
879
+ const { through } = review;
871
880
  const snapshot = this.snapshot;
872
881
  if (!snapshot) return;
873
882
  const prepared = await this.prepareOperation(review, snapshot);
@@ -905,6 +914,7 @@ export class OnlookerObserver {
905
914
  this.suppliedBoundary = review.boundary;
906
915
  if (!review.findings) throw new Error("Onlooker Review did not call onlooker_report");
907
916
  this.reviewed = through;
917
+ this.deadlinesInRow = 0;
908
918
  // A Review ended by invalid reports judged nothing, so withheld findings wait for the next.
909
919
  if (!review.invalid) await this.deliver(review.findings, review, through);
910
920
  } finally {
@@ -1324,6 +1334,8 @@ export class OnlookerObserver {
1324
1334
  this.completed = 0;
1325
1335
  this.reviewed = 0;
1326
1336
  this.dueThrough = 0;
1337
+ this.skippedThrough = 0;
1338
+ this.deadlinesInRow = 0;
1327
1339
  this.error = undefined;
1328
1340
  this.pendingCorrection = false;
1329
1341
  this.restoreDedupe();
@@ -4,7 +4,14 @@ import {
4
4
  type Theme,
5
5
  type ThemeColor,
6
6
  } from "@earendil-works/pi-coding-agent";
7
- import { Container, Markdown, Spacer, Text, type Component } from "@earendil-works/pi-tui";
7
+ import {
8
+ Container,
9
+ Markdown,
10
+ Spacer,
11
+ stripTerminalSequences,
12
+ Text,
13
+ type Component,
14
+ } from "@earendil-works/pi-tui";
8
15
  import {
9
16
  callDurationFooter,
10
17
  COLLAPSED_LINES,
@@ -96,6 +103,23 @@ const messagePaint =
96
103
  (text) =>
97
104
  theme.fg("customMessageText", text);
98
105
 
106
+ /**
107
+ * Text from a model, a provider error, or a settings file, without terminal controls: pi-tui
108
+ * writes component text to the terminal as is, so an escape sequence in it would run there.
109
+ * Keeps tabs and line breaks.
110
+ */
111
+ function displayText(text: string): string {
112
+ return Array.from(stripTerminalSequences(text).replace(/\r\n?/g, "\n"))
113
+ .filter((char) => char === "\n" || char === "\t" || !isControlCharacter(char))
114
+ .join("");
115
+ }
116
+
117
+ /** C0, DEL and C1 controls. */
118
+ function isControlCharacter(char: string): boolean {
119
+ const code = char.charCodeAt(0);
120
+ return code < 0x20 || (code >= 0x7f && code <= 0x9f);
121
+ }
122
+
99
123
  /** Severity-labelled, attributed Intervention; invalid details fall back to Pi's renderer. */
100
124
  export function renderOnlookerIntervention(
101
125
  // Journaled custom-message details are validated by the finding schema below.
@@ -105,7 +129,7 @@ export function renderOnlookerIntervention(
105
129
  ): Component | undefined {
106
130
  if (!Value.Check(onlookerFindingSchema, details)) return undefined;
107
131
  const heading = theme.fg(severityColor[details.severity], details.severity);
108
- const body = new Markdown(details.message, 0, 0, getMarkdownTheme(), {
132
+ const body = new Markdown(displayText(details.message), 0, 0, getMarkdownTheme(), {
109
133
  color: messagePaint(theme),
110
134
  });
111
135
  return customMessageBox(
@@ -132,12 +156,13 @@ export function renderOnlookerAskCall(
132
156
  theme: OnlookerRenderTheme,
133
157
  context: DurationContext,
134
158
  ): Component {
135
- const [first = "", ...rest] = args.message.split("\n");
159
+ const message = displayText(args.message);
160
+ const [first = "", ...rest] = message.split("\n");
136
161
  const hidden = rest.length > 0 && !expanded;
137
162
  const heading = toolHeader(theme, onlookerAskToolName, expanded ? undefined : first);
138
163
  const container = new Container();
139
164
  container.addChild(new Text(hidden ? `${heading}${summaryExpandHint(theme)}` : heading, 0, 0));
140
- if (expanded) container.addChild(new Text(theme.fg("muted", `message: ${args.message}`), 0, 0));
165
+ if (expanded) container.addChild(new Text(theme.fg("muted", `message: ${message}`), 0, 0));
141
166
  container.addChild(callDurationFooter(theme, context));
142
167
  return container;
143
168
  }
@@ -150,17 +175,18 @@ export function renderOnlookerAskResult(
150
175
  context: DurationContext,
151
176
  ): Component {
152
177
  const container = new Container();
153
- if (answer) {
178
+ const shown = displayText(answer);
179
+ if (shown) {
154
180
  container.addChild(new Spacer(1));
155
181
  if (options.isError) {
156
- const lines = previewBody(theme, answer.split("\n"), {
182
+ const lines = previewBody(theme, shown.split("\n"), {
157
183
  limit: COLLAPSED_LINES.fallback,
158
184
  expanded: options.expanded,
159
185
  color: "error",
160
186
  });
161
187
  container.addChild(new Text(lines.join("\n"), 0, 0));
162
188
  } else {
163
- const body = new Markdown(answer, 0, 0, getMarkdownTheme(), {
189
+ const body = new Markdown(shown, 0, 0, getMarkdownTheme(), {
164
190
  color: (text) => theme.fg("toolOutput", text),
165
191
  });
166
192
  container.addChild(
@@ -241,7 +267,7 @@ function findingCounts(entry: OnlookerStatusEntry): string[] {
241
267
  /** Human-readable option value; an absent value inherits. */
242
268
  export function formatOnlookerOption(options: OnlookerOptions, key: keyof OnlookerOptions): string {
243
269
  const value = options[key];
244
- return value === undefined ? "inherit" : String(value);
270
+ return value === undefined ? "inherit" : displayText(String(value));
245
271
  }
246
272
 
247
273
  /** The word shown for a state: an armed Onlooker reads `on` to the user. */
@@ -268,15 +294,15 @@ function stateLine(
268
294
  return joinInline(theme, [
269
295
  label ? `${label} ${state}` : state,
270
296
  entry.effectiveModel
271
- ? `${paint(entry.effectiveModel)}${inherited ? theme.fg("dim", " (inherited)") : ""}`
297
+ ? `${paint(displayText(entry.effectiveModel))}${inherited ? theme.fg("dim", " (inherited)") : ""}`
272
298
  : undefined,
273
- entry.effectiveThinkingLevel ? paint(entry.effectiveThinkingLevel) : undefined,
299
+ entry.effectiveThinkingLevel ? paint(displayText(entry.effectiveThinkingLevel)) : undefined,
274
300
  entry.backlog ? paint(`backlog ${entry.backlog}`) : undefined,
275
301
  ]);
276
302
  }
277
303
 
278
304
  function errorLine(theme: OnlookerRenderTheme, error: string): string {
279
- return `${statusMark(theme, "failed")} ${theme.fg("error", error)}`;
305
+ return `${statusMark(theme, "failed")} ${theme.fg("error", displayText(error))}`;
280
306
  }
281
307
 
282
308
  /** Live state line plus any error, as shown at the top of the settings menu. */
@@ -395,8 +421,9 @@ export function onlookerFooterText(
395
421
  const paused = root.state === "paused";
396
422
  const busy = root.state === "reviewing" || root.state === "consulting";
397
423
  const mark = paused ? "warning" : busy ? "active" : "idle";
424
+ const model = root.effectiveModel?.slice(root.effectiveModel.indexOf("/") + 1);
398
425
  return `${statusMark(theme, mark)} ${joinInline(theme, [
399
426
  theme.fg("dim", root.name ?? "onlooker"),
400
- root.effectiveModel?.slice(root.effectiveModel.indexOf("/") + 1),
427
+ model === undefined ? undefined : displayText(model),
401
428
  ])}`;
402
429
  }