@omercnet/paseo-pr-radar 3.3.0 → 3.4.0-next.541.1

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,269 @@
1
+ // Labels a routing script asks for. The script sees PR text on stdin, so its output is untrusted:
2
+ // every label is validated all or nothing, and a bad set blocks the launch instead of dropping
3
+ // labels (a dropped trust-downgrade label would launch an agent without it).
4
+
5
+ // The extra labels a script may add. PR Radar always adds `pr-radar.cwd` on top of these.
6
+ export const MAX_SCRIPT_LABELS = 16;
7
+ export const MAX_LABEL_KEY_LEN = 128;
8
+ export const MAX_LABEL_VALUE_LEN = 128;
9
+ export const ROUTE_NAMESPACE = "pr-radar.route.";
10
+ const MAX_SHOWN_KEY_LEN = 64;
11
+
12
+ const LABEL_KEY = /^[A-Za-z0-9][A-Za-z0-9._/-]*$/;
13
+ // Unicode general categories Cc (C0, DEL and C1 controls), Cf (format characters: bidi controls
14
+ // such as U+202A-U+202E and U+2066-U+2069 used by Trojan Source, CVE-2021-42574, zero-width
15
+ // U+200B-U+200F, U+2060-U+2064, U+FEFF, tag characters), Cs (lone surrogates), Zl and Zp.
16
+ // Default_Ignorable_Code_Point adds invisible fillers (U+3164, U+115F, U+FFA0) and variation selectors.
17
+ const UNSAFE_CHARS = /[\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}]/u;
18
+ const ESCAPED_CHARS = /[\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}]/gu;
19
+ // A script that returns more raw keys than this is rejected before any per-key work.
20
+ const MAX_RAW_LABELS = MAX_SCRIPT_LABELS * 4;
21
+ const MAX_LISTED_REJECTIONS = 5;
22
+ const RESERVED_ROOTS = ["pr-radar", "paseo"];
23
+
24
+ export interface RejectedLabel {
25
+ key: string;
26
+ reason: string;
27
+ }
28
+
29
+ export interface CheckedLabels {
30
+ labels: Record<string, string>;
31
+ rejected: RejectedLabel[];
32
+ }
33
+
34
+ export interface LabelPolicy {
35
+ routingLabelPrefixes: string;
36
+ }
37
+
38
+ export type RoutedLabelsDecision =
39
+ | { status: "ok"; labels: Record<string, string> }
40
+ | { status: "blocked"; rejected: RejectedLabel[]; message: string };
41
+
42
+ export class RoutedLabelsBlockedError extends Error {
43
+ readonly rejected: RejectedLabel[];
44
+
45
+ constructor(message: string, rejected: RejectedLabel[]) {
46
+ super(message);
47
+ this.name = "RoutedLabelsBlockedError";
48
+ this.rejected = rejected;
49
+ }
50
+ }
51
+
52
+ // A prefix that is a root of a reserved family (`p`, `paseo`) or extends one (`paseo-`, `pr-radar/`)
53
+ // could admit look-alikes of reserved keys. One malformed entry voids the whole setting, so a typo
54
+ // can never widen a prefix: every script label then stays namespaced.
55
+ export function parseLabelPrefixes(raw: string): string[] {
56
+ const prefixes = splitPrefixes(raw);
57
+ return prefixes.every((prefix) => prefixProblem(prefix) === null) ? prefixes : [];
58
+ }
59
+
60
+ function splitPrefixes(raw: string): string[] {
61
+ return raw.split(/[\s,]+/).filter((prefix) => prefix.length > 0);
62
+ }
63
+
64
+ function prefixProblem(prefix: string): string | null {
65
+ if (prefix.length > MAX_LABEL_KEY_LEN) {
66
+ return `is longer than ${MAX_LABEL_KEY_LEN} characters`;
67
+ }
68
+ if (!LABEL_KEY.test(prefix)) {
69
+ return "may only use letters, digits and . _ / - and must start with a letter or digit";
70
+ }
71
+ const lower = prefix.toLowerCase();
72
+ if (RESERVED_ROOTS.some((root) => root.startsWith(lower) || lower.startsWith(root))) {
73
+ return "is, or starts like, a reserved name (pr-radar, paseo)";
74
+ }
75
+ return null;
76
+ }
77
+
78
+ // Why the whole setting is void, naming the first bad entry; null when every entry is usable.
79
+ // The settings screen shows it, so a typo does not silently turn every prefix off.
80
+ export function labelPrefixesProblem(raw: string): string | null {
81
+ for (const prefix of splitPrefixes(raw)) {
82
+ const problem = prefixProblem(prefix);
83
+ if (problem) {
84
+ return `Ignoring every prefix: ${quoteLabelKey(prefix)} ${problem}. Fix or remove it.`;
85
+ }
86
+ }
87
+ return null;
88
+ }
89
+
90
+ // Keys shown in a notice come from the script, so control and invisible characters are written out.
91
+ export function displayLabelKey(key: string, maxShown = MAX_SHOWN_KEY_LEN): string {
92
+ const escaped = key
93
+ .replaceAll("\\", "\\\\")
94
+ .replace(
95
+ ESCAPED_CHARS,
96
+ (char) => `\\u{${(char.codePointAt(0) ?? 0).toString(16).toUpperCase()}}`,
97
+ );
98
+ return escaped.length > maxShown ? `${escaped.slice(0, maxShown)}...` : escaped;
99
+ }
100
+
101
+ function quoteLabelKey(key: string, maxShown = MAX_SHOWN_KEY_LEN): string {
102
+ return `"${displayLabelKey(key, maxShown).replaceAll('"', '\\"')}"`;
103
+ }
104
+
105
+ // How a label is shown in the modal: quoted, so a value cannot pass for a second label. Keys and
106
+ // values are quoted the same way, so a backslash is written once as two, never doubled again.
107
+ // Only accepted labels reach here: they hold no control or invisible characters, so escaping can at
108
+ // most double a character, and twice the limits shows a key or value in full.
109
+ export function describeLabel(key: string, value: string): string {
110
+ return `${quoteLabelKey(key, 2 * MAX_LABEL_KEY_LEN)}=${quoteLabelKey(value, 2 * MAX_LABEL_VALUE_LEN)}`;
111
+ }
112
+
113
+ function isReservedKey(key: string): boolean {
114
+ const lower = key.toLowerCase();
115
+ return (
116
+ lower === "pr-radar" ||
117
+ lower.startsWith("pr-radar.") ||
118
+ lower === "paseo" ||
119
+ lower.startsWith("paseo.")
120
+ );
121
+ }
122
+
123
+ function keyProblem(rawKey: string): string | null {
124
+ if (UNSAFE_CHARS.test(rawKey)) return "key contains control or invisible characters";
125
+ const key = rawKey.trim();
126
+ if (!key) return "key is empty";
127
+ if (isReservedKey(key)) {
128
+ return "key is reserved (pr-radar, pr-radar.*, paseo and paseo.* belong to PR Radar and Paseo)";
129
+ }
130
+ if (!LABEL_KEY.test(key)) {
131
+ return "key may only use letters, digits and . _ / - and must start with a letter or digit";
132
+ }
133
+ return null;
134
+ }
135
+
136
+ function valueProblem(rawValue: unknown): string | null {
137
+ if (typeof rawValue !== "string") return "value must be a string";
138
+ if (UNSAFE_CHARS.test(rawValue)) return "value contains control or invisible characters";
139
+ const value = rawValue.trim();
140
+ if (!value) return "value is empty";
141
+ if (value.length > MAX_LABEL_VALUE_LEN) {
142
+ return `value is longer than ${MAX_LABEL_VALUE_LEN} characters`;
143
+ }
144
+ return null;
145
+ }
146
+
147
+ // A prefix admits a key that equals it, any key under a prefix that ends in a separator (`ade.`),
148
+ // and a key whose next character after the prefix is a separator (`ade.kind` admits `ade.kind.x`,
149
+ // not `ade.kinder`; `team` admits `team/x`, not `teamx`).
150
+ const SEPARATORS = [".", "/"];
151
+
152
+ function admits(prefix: string, key: string): boolean {
153
+ if (!key.startsWith(prefix)) return false;
154
+ if (key.length === prefix.length) return true;
155
+ return SEPARATORS.includes(prefix.slice(-1)) || SEPARATORS.includes(key.charAt(prefix.length));
156
+ }
157
+
158
+ // A key that an allowed prefix admits keeps its name; any other key goes under pr-radar.route.
159
+ function finalKey(key: string, prefixes: readonly string[]): string {
160
+ return prefixes.some((prefix) => admits(prefix, key)) ? key : `${ROUTE_NAMESPACE}${key}`;
161
+ }
162
+
163
+ interface LabelEntry {
164
+ rawKey: string;
165
+ key: string;
166
+ value: string;
167
+ problem: string | null;
168
+ }
169
+
170
+ function toEntry(
171
+ [rawKey, rawValue]: [string, unknown],
172
+ prefixes: readonly string[],
173
+ ): LabelEntry & { final: string | null } {
174
+ const keyIssue = keyProblem(rawKey);
175
+ const key = rawKey.trim();
176
+ const final = keyIssue ? null : finalKey(key, prefixes);
177
+ const lengthIssue =
178
+ final && final.length > MAX_LABEL_KEY_LEN
179
+ ? `key is longer than ${MAX_LABEL_KEY_LEN} characters once namespaced as ${displayLabelKey(final.slice(0, 32))}...`
180
+ : null;
181
+ const problem = keyIssue ?? lengthIssue ?? valueProblem(rawValue);
182
+ const value = typeof rawValue === "string" ? rawValue.trim() : "";
183
+ return { rawKey, key, value, problem, final: lengthIssue ? null : final };
184
+ }
185
+
186
+ export function checkRoutedLabels(raw: unknown, prefixes: readonly string[]): CheckedLabels {
187
+ if (raw === undefined || raw === null) return { labels: {}, rejected: [] };
188
+ if (typeof raw !== "object" || Array.isArray(raw)) {
189
+ return {
190
+ labels: {},
191
+ rejected: [{ key: "labels", reason: "labels must be an object of string values" }],
192
+ };
193
+ }
194
+ const rawEntries = Object.entries(raw);
195
+ if (rawEntries.length > MAX_RAW_LABELS) {
196
+ return {
197
+ labels: {},
198
+ rejected: [
199
+ {
200
+ key: "labels",
201
+ reason: `${rawEntries.length} labels returned; at most ${MAX_SCRIPT_LABELS} are allowed`,
202
+ },
203
+ ],
204
+ };
205
+ }
206
+ const entries = rawEntries.map((entry) => toEntry(entry, prefixes));
207
+
208
+ const bySlot = new Map<string, string[]>();
209
+ for (const { final, rawKey } of entries) {
210
+ if (final) bySlot.set(final, [...(bySlot.get(final) ?? []), rawKey]);
211
+ }
212
+
213
+ const rejected: RejectedLabel[] = [];
214
+ const labels: Record<string, string> = {};
215
+ for (const entry of entries) {
216
+ const sharing = entry.final ? (bySlot.get(entry.final) ?? []) : [];
217
+ const collision =
218
+ sharing.length > 1
219
+ ? `key collides with ${sharing
220
+ .filter((other) => other !== entry.rawKey)
221
+ .slice(0, 2)
222
+ .map((other) => quoteLabelKey(other))
223
+ .join(", ")} (both become ${entry.final})`
224
+ : null;
225
+ const problem = entry.problem ?? collision;
226
+ if (problem) {
227
+ rejected.push({ key: entry.rawKey, reason: problem });
228
+ } else if (entry.final) {
229
+ labels[entry.final] = entry.value;
230
+ }
231
+ }
232
+ if (rejected.length === 0 && Object.keys(labels).length > MAX_SCRIPT_LABELS) {
233
+ rejected.push({
234
+ key: "labels",
235
+ reason: `${Object.keys(labels).length} labels returned; at most ${MAX_SCRIPT_LABELS} are allowed`,
236
+ });
237
+ }
238
+ return { labels: rejected.length > 0 ? {} : labels, rejected };
239
+ }
240
+
241
+ export function describeRejection({ key, reason }: RejectedLabel): string {
242
+ return `${quoteLabelKey(key)}: ${reason}`;
243
+ }
244
+
245
+ export const BLOCKED_HEADLINE =
246
+ "Launch blocked: the routing script returned labels PR Radar will not apply";
247
+
248
+ // The notice lists the first few; the Start New Agent window lists them all.
249
+ export function describeRejected(rejected: readonly RejectedLabel[]): string {
250
+ const listed = rejected.slice(0, MAX_LISTED_REJECTIONS).map(describeRejection);
251
+ const more = rejected.length - listed.length;
252
+ const rest = more > 0 ? `; and ${more} more (Start New Agent lists every rejected label)` : "";
253
+ return `${listed.join("; ")}${rest}`;
254
+ }
255
+
256
+ export function decideRoutedLabels(input: {
257
+ labels: unknown;
258
+ policy: LabelPolicy;
259
+ }): RoutedLabelsDecision {
260
+ const { labels, policy } = input;
261
+ const checked = checkRoutedLabels(labels, parseLabelPrefixes(policy.routingLabelPrefixes));
262
+ if (checked.rejected.length === 0) return { status: "ok", labels: checked.labels };
263
+
264
+ return {
265
+ status: "blocked",
266
+ rejected: checked.rejected,
267
+ message: `${BLOCKED_HEADLINE} (${describeRejected(checked.rejected)}). Fix the script.`,
268
+ };
269
+ }
@@ -18,6 +18,7 @@ export const DEFAULT_PR_RADAR_SETTINGS = {
18
18
  defaultModeId: "",
19
19
  defaultContextMode: "",
20
20
  routingScriptPath: "",
21
+ routingLabelPrefixes: "",
21
22
  } as const;
22
23
 
23
24
  export const PrRadarSettingsSchema = z
@@ -55,14 +56,34 @@ export const PrRadarSettingsSchema = z
55
56
  .trim()
56
57
  .max(4_096)
57
58
  .default(DEFAULT_PR_RADAR_SETTINGS.routingScriptPath),
59
+ // Label key prefixes the routing script may use as-is, separated by commas or spaces (for
60
+ // example `ade.`). Every other script label is stored as `pr-radar.route.<key>`. Never admits
61
+ // `pr-radar`, `pr-radar.*`, `paseo` or `paseo.*`.
62
+ routingLabelPrefixes: z
63
+ .string()
64
+ .trim()
65
+ .max(1_024)
66
+ .default(DEFAULT_PR_RADAR_SETTINGS.routingLabelPrefixes),
58
67
  })
59
68
  .strict();
60
69
 
61
70
  export type PrRadarSettings = z.infer<typeof PrRadarSettingsSchema>;
62
71
 
72
+ // Settings saved before label fallback rules moved out of the label feature may still hold
73
+ // `routingLabelFallbacks`. The schema is strict, so the stored document must lose it before it is
74
+ // parsed; a retired rule then enables nothing.
75
+ const RETIRED_SETTINGS_KEYS = ["routingLabelFallbacks"] as const;
76
+
77
+ export function migratePrRadarSettings(values: unknown): unknown {
78
+ if (typeof values !== "object" || values === null || Array.isArray(values)) return values;
79
+ const retired: readonly string[] = RETIRED_SETTINGS_KEYS;
80
+ return Object.fromEntries(Object.entries(values).filter(([key]) => !retired.includes(key)));
81
+ }
82
+
63
83
  export const prRadarSettings = defineSettings({
64
84
  id: "pr-radar",
65
85
  scope: "host",
66
- version: 1,
86
+ version: 2,
67
87
  schema: PrRadarSettingsSchema,
88
+ migrate: migratePrRadarSettings,
68
89
  });
@@ -128,6 +128,10 @@ export const RoutingScriptResultSchema = z.object({
128
128
  modeId: z.string().optional(),
129
129
  contextMode: z.string().optional(),
130
130
  options: z.record(z.string(), z.unknown()).optional(),
131
+ // Extra Paseo agent labels the script asks for. Kept unvalidated here: `decideRoutedLabels`
132
+ // checks them all or nothing at launch, so a malformed value blocks the launch instead of
133
+ // disappearing from the routing result.
134
+ labels: z.unknown().optional(),
131
135
  reason: z.string().optional(),
132
136
  });
133
137