pal-code 0.0.19 → 0.0.21

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.
@@ -0,0 +1,178 @@
1
+ /**
2
+ * OSC 7501 — the Program Status Protocol.
3
+ *
4
+ * Lets pal tell the terminal what it is doing (`working`, `blocked`, `done`,
5
+ * `error`, `idle`) so an agent inbox such as Herdr can list it beside every
6
+ * other agent. The terminal never guesses and never scrapes the screen: the
7
+ * program that knows its own state is the one reporting it.
8
+ *
9
+ * Spec: https://www.superlogical.com/rex/docs/build/program-status (v0.4)
10
+ *
11
+ * Everything here is pure — the exact bytes for a status, in order — so it is
12
+ * testable without a terminal. The caller only decides *when* to report.
13
+ *
14
+ * Grammar (the parts that bite):
15
+ *
16
+ * OSC 7501 ; [key=value (":" key=value)*] ST
17
+ * key := [a-z]+
18
+ * value := [A-Za-z0-9_.,+/=-]*
19
+ *
20
+ * - The separator is `:` and nothing else. `;` between pairs makes the whole
21
+ * report unparseable, which is the mistake the herdr-plus notes record.
22
+ * - `state` is required; an unrecognized value discards the entire report, so
23
+ * a state from a newer revision never silently degrades to `idle`.
24
+ * - Free text (`msg`, `title`) is base64 UTF-8 and MUST NOT contain control
25
+ * characters, newline or tab. A report whose decoded text holds one is
26
+ * dropped whole, so {@link encodeStatusText} flattens before encoding.
27
+ * - Each report *replaces* its record completely. A key omitted from this
28
+ * report is gone from the record afterwards, which is why every report here
29
+ * repeats `app`.
30
+ * - Terminators: `BEL` and `ST` (`ESC \`) are both legal. `BEL` matches the
31
+ * `\u0007` form pal's other OSC builders use (see `osc52.ts`).
32
+ */
33
+
34
+ /** The states a program may report. `clear` is not a state — see {@link buildOscStatusClear}. */
35
+ export type ProgramStatusState = 'idle' | 'working' | 'done' | 'blocked' | 'error';
36
+
37
+ /** Why a `blocked` program cannot continue. Ignored for any other state. */
38
+ export type ProgramStatusKind = 'permission' | 'question' | 'auth';
39
+
40
+ /**
41
+ * The stable program identifier pal registers under.
42
+ *
43
+ * Matches the `app` value Herdr shows as the agent's identity and the key
44
+ * herdr-plus writes into `programs.json`, so the name, icon and tile resolve.
45
+ */
46
+ export const PAL_APP_NAME = 'pal';
47
+
48
+ /** A status report, before encoding. */
49
+ export interface ProgramStatus {
50
+ state: ProgramStatusState;
51
+ /** Defaults to {@link PAL_APP_NAME} at build time. */
52
+ app?: string;
53
+ /** Only meaningful with `state: 'blocked'`. */
54
+ kind?: ProgramStatusKind;
55
+ /** 0–100, only meaningful with `working`/`blocked`. Absent means indeterminate. */
56
+ progress?: number;
57
+ /** One human-readable line. Base64-encoded on the wire. */
58
+ msg?: string;
59
+ }
60
+
61
+ /**
62
+ * Flatten free text to a single control-character-free line.
63
+ *
64
+ * The spec discards the whole report if decoded `msg`/`title` contains
65
+ * `U+0000`–`U+001F` or `U+007F`–`U+009F`, so a stray newline in an error
66
+ * message would silently cost the status update. Collapse every run of
67
+ * whitespace to one space instead of dropping the report.
68
+ */
69
+ export function encodeStatusText(text: string): string {
70
+ const flat = text
71
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: the point is to strip them.
72
+ .replace(/[\u0000-\u001f\u007f-\u009f]+/g, ' ')
73
+ .trim();
74
+ return Buffer.from(flat, 'utf8').toString('base64');
75
+ }
76
+
77
+ /** Clamp to the spec's 0–100 integer range, or `undefined` when not a usable number. */
78
+ function normaliseProgress(progress: number | undefined): number | undefined {
79
+ if (progress === undefined || !Number.isFinite(progress)) return undefined;
80
+ return Math.min(100, Math.max(0, Math.round(progress)));
81
+ }
82
+
83
+ /**
84
+ * Normalise a candidate `app` value to the spec's `[A-Za-z0-9_.+-]{1,32}`.
85
+ *
86
+ * An out-of-charset value is *treated as absent* by a conforming terminal,
87
+ * which would quietly strip pal's identity and leave the pane labelled by its
88
+ * process name. Sanitise instead of dropping.
89
+ */
90
+ function normaliseApp(app: string): string {
91
+ const cleaned = app.replace(/[^A-Za-z0-9_.+-]/g, '').slice(0, 32);
92
+ return cleaned.length > 0 ? cleaned : PAL_APP_NAME;
93
+ }
94
+
95
+ /**
96
+ * Build the OSC 7501 report for `status`.
97
+ *
98
+ * Pairs are emitted in a stable order (`state` first, since it is required)
99
+ * so the output is diffable in tests and logs.
100
+ */
101
+ export function buildOscStatus(status: ProgramStatus): string {
102
+ const pairs: string[] = [`state=${status.state}`];
103
+
104
+ // Present on every report: a report replaces its record, so omitting `app`
105
+ // would erase pal's identity from the record on the next update.
106
+ pairs.push(`app=${normaliseApp(status.app ?? PAL_APP_NAME)}`);
107
+
108
+ if (status.state === 'blocked' && status.kind !== undefined) {
109
+ pairs.push(`kind=${status.kind}`);
110
+ }
111
+
112
+ if (status.state === 'working' || status.state === 'blocked') {
113
+ const progress = normaliseProgress(status.progress);
114
+ if (progress !== undefined) pairs.push(`progress=${progress}`);
115
+ }
116
+
117
+ if (status.msg !== undefined && status.msg.length > 0) {
118
+ pairs.push(`msg=${encodeStatusText(status.msg)}`);
119
+ }
120
+
121
+ return `\x1b]7501;${pairs.join(':')}\x07`;
122
+ }
123
+
124
+ /**
125
+ * Build the report that removes pal's records.
126
+ *
127
+ * Sent on exit so a pane that is no longer running pal does not leave a stale
128
+ * `done` badge behind. Without an `id` this clears every record on the
129
+ * terminal, which is correct: pal is the only program reporting through its
130
+ * own tty.
131
+ */
132
+ export function buildOscStatusClear(app?: string): string {
133
+ if (app === undefined) return '\x1b]7501;state=clear\x07';
134
+ return `\x1b]7501;state=clear:app=${normaliseApp(app)}\x07`;
135
+ }
136
+
137
+ /**
138
+ * Build the feature-detection query (`OSC 7501;?ST`).
139
+ *
140
+ * Detection is optional, and a program that cannot read replies may skip it —
141
+ * unknown OSCs are ignored by every well-behaved terminal. Exported because
142
+ * `pal doctor` (and a future protocol-version check) wants to ask.
143
+ */
144
+ export function buildOscStatusQuery(): string {
145
+ return '\x1b]7501;?\x07';
146
+ }
147
+
148
+ /** Human-readable `state`/`kind` for the status line and `pal doctor` output. */
149
+ export function describeStatus(state: ProgramStatusState, kind?: ProgramStatusKind): string {
150
+ switch (state) {
151
+ case 'working':
152
+ return 'working';
153
+ case 'blocked':
154
+ return kind === undefined ? 'needs you' : `needs you (${kind})`;
155
+ case 'done':
156
+ return 'done';
157
+ case 'error':
158
+ return 'error';
159
+ default:
160
+ return 'idle';
161
+ }
162
+ }
163
+
164
+ /**
165
+ * The state to report once a turn settles.
166
+ *
167
+ * `done` is not "idle with extra steps": the spec says it means *finished, and
168
+ * the user has not looked yet*, and that it survives the shell prompt that
169
+ * follows. That is exactly what an agent inbox is for — it is how a pane that
170
+ * finished while you were in another tab asks for attention.
171
+ *
172
+ * An interrupted turn is `idle`, not `error`: the spec's own rule is that when
173
+ * the user cancels, report `idle`. The user knows what they did; a red badge
174
+ * on a deliberate stop is noise.
175
+ */
176
+ export function settledStatus(interrupted: boolean): ProgramStatusState {
177
+ return interrupted ? 'idle' : 'done';
178
+ }
@@ -117,6 +117,10 @@ function askUser(
117
117
  state.permissionResolver = (allow: boolean) => {
118
118
  state.permissionResolver = null;
119
119
 
120
+ // Back to work the moment the prompt is answered: the turn continues, so
121
+ // leaving the terminal showing "needs you" would be a lie.
122
+ state.statusReporter.report('working');
123
+
120
124
  onResult(allow);
121
125
 
122
126
  // If there are queued permissions, show the next one immediately
@@ -133,6 +137,10 @@ function askUser(
133
137
  state.pendingPermission = {toolName, target, summary};
134
138
  state.overlayMode = 'permission';
135
139
 
140
+ // Herdr's most urgent agent state: a pane suffix "needs you" and a badge in
141
+ // the agents list. This is the whole reason OSC 7501 carries `blocked`.
142
+ state.statusReporter.report('blocked', {kind: 'permission', msg: summary});
143
+
136
144
  // Show the centered permission modal (removes editor, adds prompt to messages)
137
145
  state.showPermissionModal();
138
146
 
@@ -161,12 +169,17 @@ function showNextQueuedPermission(): void {
161
169
  } else {
162
170
  state.overlayMode = 'none';
163
171
  state.pendingPermission = null;
172
+ // Queue drained — the turn resumes.
173
+ state.statusReporter.report('working');
164
174
  }
165
175
  };
166
176
 
167
177
  // Swap the pending permission atomically — the mounted PermissionPrompt
168
178
  // component reads this on each render, so it updates in-place.
169
179
  state.pendingPermission = {toolName: next.toolName, target: next.target, summary: next.summary};
180
+ // Still blocked, just on a different request: the `msg` changes so the
181
+ // terminal shows what is actually being asked.
182
+ state.statusReporter.report('blocked', {kind: 'permission', msg: next.summary});
170
183
  state.refreshStatusLine();
171
184
  }
172
185
 
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Emit pal's lifecycle as OSC 7501 program-status reports.
3
+ *
4
+ * `osc-status.ts` owns the bytes; this owns *when* to send them. The split
5
+ * keeps the grammar testable without a terminal and leaves exactly one place
6
+ * that writes to stdout.
7
+ *
8
+ * Design notes:
9
+ *
10
+ * - **No detection round-trip.** Feature detection (`OSC 7501;?`) is optional
11
+ * by spec, and a terminal that does not know the sequence ignores it. pal
12
+ * cannot reliably read the reply anyway (it is rendering a TUI), so it sends
13
+ * reports unconditionally — the spec explicitly allows this.
14
+ * - **Dedupe.** The TUI re-renders constantly and several events map to
15
+ * `working`; sending an identical report per event would be pure noise. The
16
+ * last record is remembered and identical consecutive reports are dropped.
17
+ * - **Never throw.** A status report is a courtesy. It must not fail a turn,
18
+ * end a session, or smear an error across the TUI frame.
19
+ * - **Only a TTY.** When stdout is a pipe (CI, `pal ... | head`), the escape
20
+ * sequences are not a status channel, they are corruption. Skip them.
21
+ */
22
+
23
+ import {
24
+ buildOscStatus,
25
+ buildOscStatusClear,
26
+ PAL_APP_NAME,
27
+ type ProgramStatus,
28
+ type ProgramStatusKind,
29
+ type ProgramStatusState,
30
+ } from './osc-status.js';
31
+
32
+ /** What the reporter was constructed with. */
33
+ export interface StatusReporterOptions {
34
+ /** Where to write. Defaults to `process.stdout`. */
35
+ write?: (chunk: string) => void;
36
+ /** Whether to report at all. Defaults to "stdout is a TTY". */
37
+ enabled?: boolean;
38
+ /** `app` identity on the wire. Defaults to {@link PAL_APP_NAME}. */
39
+ app?: string;
40
+ }
41
+
42
+ /** The narrow surface the CLI/UI layer calls. */
43
+ export interface StatusReporter {
44
+ /** Report a state change. `undefined`/`true` mean "enabled". */
45
+ report(
46
+ state: ProgramStatusState,
47
+ detail?: {kind?: ProgramStatusKind; msg?: string; progress?: number},
48
+ ): void;
49
+ /** Clear pal's records — sent on exit so no stale badge is left behind. */
50
+ clear(): void;
51
+ /** The status last put on the wire, for the status line / `pal doctor`. */
52
+ current(): ProgramStatusState | null;
53
+ }
54
+
55
+ /** A reporter that does nothing. Used when status reporting is switched off. */
56
+ export const nullStatusReporter: StatusReporter = {
57
+ report() {},
58
+ clear() {},
59
+ current() {
60
+ return null;
61
+ },
62
+ };
63
+
64
+ /**
65
+ * Whether pal should emit status reports in this process.
66
+ *
67
+ * `PAL_NO_STATUS=1` opts out (and is what a test harness or a wrapper that
68
+ * wants a silent run sets). Otherwise stdout being a TTY is the whole test:
69
+ * a terminal is the only thing that can consume the sequence.
70
+ */
71
+ export function statusReportingEnabled(
72
+ env: Record<string, string | undefined> = process.env,
73
+ ): boolean {
74
+ if (env.PAL_NO_STATUS === '1') return false;
75
+ return process.stdout.isTTY === true;
76
+ }
77
+
78
+ /** Create the reporter the session uses for its whole lifetime. */
79
+ export function createStatusReporter(options: StatusReporterOptions = {}): StatusReporter {
80
+ const enabled = options.enabled ?? statusReportingEnabled();
81
+ if (!enabled) return nullStatusReporter;
82
+
83
+ const app = options.app ?? PAL_APP_NAME;
84
+ const write = options.write ?? ((chunk: string) => void process.stdout.write(chunk));
85
+
86
+ let last: string | null = null;
87
+ let current: ProgramStatusState | null = null;
88
+
89
+ return {
90
+ report(state, detail) {
91
+ const status: ProgramStatus = {
92
+ state,
93
+ app,
94
+ kind: detail?.kind,
95
+ msg: detail?.msg,
96
+ progress: detail?.progress,
97
+ };
98
+ const sequence = buildOscStatus(status);
99
+ current = state;
100
+ // The dedupe key is the whole sequence, not the state: a `blocked` that
101
+ // gains a different `kind` is a different thing to show.
102
+ if (sequence === last) return;
103
+ last = sequence;
104
+ try {
105
+ write(sequence);
106
+ } catch {
107
+ // A closed or wedged stdout must not take the session down with it.
108
+ }
109
+ },
110
+
111
+ clear() {
112
+ try {
113
+ write(buildOscStatusClear(app));
114
+ last = null;
115
+ current = null;
116
+ } catch {
117
+ // Same reasoning as report().
118
+ }
119
+ },
120
+
121
+ current() {
122
+ return current;
123
+ },
124
+ };
125
+ }