@omercnet/paseo-pr-radar 3.3.0-next.532.1 → 3.3.0-next.533.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.
package/README.md CHANGED
@@ -38,6 +38,16 @@ DevTools before capture. Both PNGs come from an isolated Paseo test daemon at 2
38
38
  - `Ask agent` / `Open workspace` / `Copy link` / `Open PR`.
39
39
  - Settings (`PR Radar settings`): configure `sourceCodeDir` (default `~/src`), `defaultCwdMode` (`CWD-WORKTREE` or `CWD-BASE`), `autoLaunchMode` (`prompt`, `existing_only`, or `existing_or_clone`), default agent launch options (profile, provider, model, effort, mode, context mode), and an optional absolute/`~/` routing script path (copy `examples/pr-radar-route.py`, a small example of the stdin/stdout contract, to e.g. `~/.config/pr-radar/route.py` and edit it). The script path and `sourceCodeDir` are read from the saved settings on the server, never from the request. The script must be an executable regular file owned by you or root, in directories that group and others cannot write (a sticky directory such as `/tmp` is fine); it runs with a minimal environment, a 30 second timeout and a 1 MiB output cap, one at a time (not on Windows). It may set only the `default`, `plan`, `acceptEdits` and `read-only` permission modes and the `contextMode` option; other values are ignored and the launch notice says so. A profile it names is ignored too when that profile sets another permission mode, option or feature value. Directories outside `sourceCodeDir` are refused for clones, checkouts and worktrees. These checks are defense in depth against crafted requests, not a privilege boundary: the settings are the trust source, but any Paseo client can write them.
40
40
 
41
+ #### Routing script labels
42
+
43
+ A routing script may return `"labels": {"key": "value"}`, and PR Radar puts them on the agent it launches (next to its own `pr-radar.cwd`). The script reads PR text on stdin, so its labels are untrusted and are checked as a whole:
44
+
45
+ - **Namespaced by default.** A label key is stored as `pr-radar.route.<key>` (`{"kind": "external-review"}` becomes `pr-radar.route.kind=external-review`). The namespaced key must still fit the 128 character key limit.
46
+ - **Allowed label prefixes** (setting `routingLabelPrefixes`, empty by default; comma or space separated, for example `ade.kind` or `ade.`). A key that a prefix admits keeps its own name. Everything else stays namespaced. A prefix admits a key that equals it, a key that continues it with `.` or `/` (`ade.kind` admits `ade.kind` and `ade.kind.x`, not `ade.kinder`; `team` admits `team/x`, not `teamx`), and every key under a prefix that itself ends in `.` or `/` (`ade.` admits `ade.anything`). That can include keys other tools treat as control labels, so list the narrowest prefix you trust (`ade.kind` does not admit `ade.lead`) rather than a whole family (`ade.`) unless every key under it is safe for a script to set. A prefix never admits a reserved key, and a prefix that is a root of or extends `pr-radar` or `paseo` (`p`, `paseo-`, `pr-radar/`) or a malformed entry voids the whole setting, so every script label then stays namespaced.
47
+ - **Always reserved:** `pr-radar`, `pr-radar.*` (including `pr-radar.cwd`, which PR Radar sets itself, and `pr-radar.route.*`, which only PR Radar writes), `paseo` and `paseo.*`, compared without regard to case. A script cannot set them; naming one is an invalid label.
48
+ - **Limits:** at most 16 script labels (PR Radar adds `pr-radar.cwd`, so an agent carries up to 17), keys of letters, digits and `. _ / -` that start with a letter or digit, trimmed non-empty string values of at most 128 characters. A set with more than 64 keys is refused outright. Control characters (Unicode `Cc`), invisible or direction-changing format characters (`Cf`: zero-width characters, bidi overrides and isolates such as U+202A to U+202E and U+2066 to U+2069, the byte order mark), other default-ignorable characters (fillers, variation selectors), line and paragraph separators and lone surrogates are refused in keys and values. Notices quote the rejected keys and list the first five with `and N more`; the Start New Agent window lists every rejected key. Two keys that become the same label (for example after trimming) are both refused.
49
+ - **All or nothing, never silent.** If any label is invalid, no label is applied and the launch is blocked on both paths. The start-agent modal shows each rejected key with its reason and disables **Start New Agent**; auto-launch starts nothing and shows the same notice. A label set the script returns therefore either applies or stops the launch. This covers the labels only: if the script itself fails (error, timeout, oversized output, or a result with another invalid field), the modal shows the error and can still launch with your own choices, and auto-launch uses PR Radar defaults, so the script's labels are absent in that case.
50
+
41
51
  When PR Radar checks out or fetches a repository, it runs `git` with a hardened environment: `~/.gitconfig` and the system git config are ignored, repository hooks, filters, credential helpers and transport helpers are neutralized, and GitHub credentials come only from the `gh` CLI (never from git's environment). Network proxies must be provided through the environment (`HTTPS_PROXY`/`http_proxy`/`NO_PROXY` and friends), not through git config.
42
52
  - Linked workspaces and agents include those in background workspaces. Helpers, meaning background
43
53
  agents that Paseo hides from tabs, lists and attention, never appear on a row. They also do not
@@ -0,0 +1,188 @@
1
+ import {
2
+ decideRoutedLabels,
3
+ type LabelPolicy,
4
+ RoutedLabelsBlockedError,
5
+ } from "../shared/routed-labels";
6
+ import type { PrRadarSettings } from "../shared/settings";
7
+ import type { RoutingScriptResult } from "../shared/viewer-scope";
8
+ import {
9
+ type AgentLaunchOverrides,
10
+ type AgentProfileLike,
11
+ buildAgentConfig,
12
+ buildAgentLabels,
13
+ buildAgentPrompt,
14
+ type CwdTag,
15
+ type LabelableWorkspace,
16
+ labelWorkspaceCwd,
17
+ restrictRoutedLaunch,
18
+ routedProviderModel,
19
+ vetRoutedProfile,
20
+ } from "./radar";
21
+ import type { StartAgentLaunchRequest } from "./start-agent-modal";
22
+
23
+ type LaunchProfile = AgentProfileLike & { name: string };
24
+
25
+ export interface LaunchWorkspace extends LabelableWorkspace {
26
+ agents: {
27
+ create(options: {
28
+ config: ReturnType<typeof buildAgentConfig>;
29
+ title: string;
30
+ prompt: string;
31
+ labels: Record<string, string>;
32
+ }): Promise<{ id: string }>;
33
+ };
34
+ }
35
+
36
+ export interface LaunchPaseo {
37
+ workspaces: { open(cwd: string): Promise<LaunchWorkspace> };
38
+ config: { get(): Promise<{ config: { agentProfiles?: readonly LaunchProfile[] } }> };
39
+ }
40
+
41
+ export interface PrepareCwdInput {
42
+ repository: string;
43
+ prNumber: number;
44
+ itemKind: "pr" | "issue";
45
+ headRefName: string;
46
+ baseRefName: string;
47
+ targetDir: string | null;
48
+ allowClone: boolean;
49
+ cwdMode: StartAgentLaunchRequest["cwdMode"];
50
+ worktreeName: string | null;
51
+ }
52
+
53
+ export interface PreparedCwd {
54
+ cwd: string;
55
+ cwdTag: Exclude<CwdTag, "CWD-TBD">;
56
+ warning?: string;
57
+ }
58
+
59
+ export interface LaunchDeps {
60
+ paseo: LaunchPaseo;
61
+ prepareCwd(input: PrepareCwdInput): Promise<PreparedCwd>;
62
+ policy: LabelPolicy;
63
+ }
64
+
65
+ export interface LaunchedAgent {
66
+ agentId: string;
67
+ message: string;
68
+ }
69
+
70
+ /**
71
+ * Starts the agent for a Start New Agent request, from the modal or from auto-launch. The routing
72
+ * script's labels are validated here, before any worktree is prepared, so a path that skips its own
73
+ * check still cannot launch with a label set PR Radar rejected.
74
+ */
75
+ export async function launchNewAgent(
76
+ deps: LaunchDeps,
77
+ request: StartAgentLaunchRequest,
78
+ ): Promise<LaunchedAgent> {
79
+ const { row } = request;
80
+ if (!row.number) {
81
+ throw new Error("An issue or pull request number is required to start a new agent.");
82
+ }
83
+ const decision = decideRoutedLabels({
84
+ labels: request.overrides.labels,
85
+ policy: deps.policy,
86
+ });
87
+ if (decision.status === "blocked") {
88
+ throw new RoutedLabelsBlockedError(decision.message, decision.rejected);
89
+ }
90
+
91
+ const prepared = await deps.prepareCwd({
92
+ repository: row.repository,
93
+ prNumber: row.number,
94
+ itemKind: row.itemKind ?? "pr",
95
+ headRefName: row.headRefName,
96
+ baseRefName: row.baseRefName,
97
+ targetDir: request.targetDir,
98
+ allowClone: request.allowClone ?? false,
99
+ cwdMode: request.cwdMode,
100
+ worktreeName: request.worktreeName,
101
+ });
102
+
103
+ const targetWorkspace = await deps.paseo.workspaces.open(prepared.cwd);
104
+ await labelWorkspaceCwd(targetWorkspace, prepared.cwdTag);
105
+
106
+ const { config } = await deps.paseo.config.get();
107
+ const profiles = config.agentProfiles ?? [];
108
+ const wantedProfile = request.profileName.trim().toLowerCase();
109
+ const profile =
110
+ (wantedProfile
111
+ ? profiles.find((candidate) => candidate.name.toLowerCase() === wantedProfile)
112
+ : undefined) ??
113
+ profiles.find((candidate) => candidate.name.toLowerCase() === "model router") ??
114
+ profiles[0];
115
+
116
+ const created = await targetWorkspace.agents.create({
117
+ config: buildAgentConfig(profile, request.overrides),
118
+ title: `PR Radar: ${row.repository}#${row.number}`,
119
+ prompt: buildAgentPrompt(row),
120
+ labels: buildAgentLabels(prepared.cwdTag, decision.labels),
121
+ });
122
+
123
+ const baseMsg = `Started new agent in ${prepared.cwdTag} (${prepared.cwd}) for ${row.repository}#${row.number}.`;
124
+ const warnings = [request.routingWarning, prepared.warning].filter(Boolean);
125
+ return {
126
+ agentId: created.id,
127
+ message: warnings.length > 0 ? `${warnings.join(" ")} ${baseMsg}` : baseMsg,
128
+ };
129
+ }
130
+
131
+ export function defaultLaunchOverrides(settings: PrRadarSettings): AgentLaunchOverrides {
132
+ return {
133
+ provider: settings.defaultProvider,
134
+ model: settings.defaultModel,
135
+ thinkingOptionId: settings.defaultEffort,
136
+ modeId: settings.defaultModeId,
137
+ contextMode: settings.defaultContextMode,
138
+ };
139
+ }
140
+
141
+ export interface AutoRoutingInput {
142
+ settings: PrRadarSettings;
143
+ routed: RoutingScriptResult;
144
+ // Agent profiles from Paseo; only read when the script names a profile.
145
+ profiles: readonly LaunchProfile[];
146
+ }
147
+
148
+ export type AutoRouting =
149
+ | { status: "blocked"; message: string }
150
+ | {
151
+ status: "launch";
152
+ profileName: string;
153
+ overrides: AgentLaunchOverrides;
154
+ routingWarning?: string;
155
+ };
156
+
157
+ /**
158
+ * Applies a routing script's result to the auto-launch defaults. Auto-launch shows no preview, so a
159
+ * label set PR Radar rejects stops the launch here instead of reaching the agent.
160
+ */
161
+ export function applyAutoRouting(input: AutoRoutingInput): AutoRouting {
162
+ const { settings, routed, profiles } = input;
163
+ const decision = decideRoutedLabels({ labels: routed.labels, policy: settings });
164
+ if (decision.status === "blocked") return { status: "blocked", message: decision.message };
165
+
166
+ let overrides = defaultLaunchOverrides(settings);
167
+ let profileName = settings.defaultProfile;
168
+
169
+ const vetted = routed.profile
170
+ ? vetRoutedProfile(profiles, routed.profile)
171
+ : { profileName: undefined, ignored: [] as string[] };
172
+ if (vetted.profileName) profileName = vetted.profileName;
173
+ overrides = { ...overrides, ...routedProviderModel(overrides, routed) };
174
+ if (routed.thinkingOptionId) {
175
+ overrides = { ...overrides, thinkingOptionId: routed.thinkingOptionId };
176
+ }
177
+ const restricted = restrictRoutedLaunch(routed);
178
+ restricted.ignored.push(...vetted.ignored);
179
+ if (restricted.modeId) overrides = { ...overrides, modeId: restricted.modeId };
180
+ if (routed.contextMode) overrides = { ...overrides, contextMode: routed.contextMode };
181
+ if (restricted.options) overrides = { ...overrides, options: restricted.options };
182
+ if (routed.labels !== undefined) overrides = { ...overrides, labels: routed.labels };
183
+ const routingWarning =
184
+ restricted.ignored.length > 0
185
+ ? `Routing script values ignored (${restricted.ignored.join(", ")}).`
186
+ : undefined;
187
+ return { status: "launch", profileName, overrides, routingWarning };
188
+ }
@@ -23,29 +23,25 @@ import {
23
23
  runRoutingScript,
24
24
  } from "../shared/viewer-scope";
25
25
  import { HighlightedText } from "./highlighted-text";
26
+ import { applyAutoRouting, defaultLaunchOverrides, launchNewAgent } from "./launch";
26
27
  import {
27
28
  type AgentLaunchOverrides,
28
29
  agentActionFor,
29
30
  autoLaunchRequiresModal,
30
31
  BUCKET_TITLES,
31
32
  BUCKETS,
32
- buildAgentConfig,
33
33
  buildAgentPrompt,
34
34
  checkSummary,
35
35
  formatAge,
36
36
  hasActiveAgent,
37
- labelWorkspaceCwd,
38
37
  matchesRow,
39
38
  openPullRequestUrl,
40
39
  profileAgentConfig,
41
40
  type RadarBucket,
42
41
  type RadarRow,
43
- restrictRoutedLaunch,
44
- routedProviderModel,
45
42
  type SortKey,
46
43
  sortRows,
47
44
  splitDraftRows,
48
- vetRoutedProfile,
49
45
  } from "./radar";
50
46
  import {
51
47
  DIRECTORY_PARTIAL,
@@ -245,50 +241,11 @@ export function PrRadar({
245
241
 
246
242
  const startNewAgentMutation = useMutation({
247
243
  mutationFn: async (request: StartAgentLaunchRequest) => {
248
- const { row } = request;
249
- if (!row.number) {
250
- throw new Error("An issue or pull request number is required to start a new agent.");
251
- }
252
- const prepared = await prepareCwd({
253
- repository: row.repository,
254
- prNumber: row.number,
255
- itemKind: row.itemKind ?? "pr",
256
- headRefName: row.headRefName,
257
- baseRefName: row.baseRefName,
258
- targetDir: request.targetDir,
259
- allowClone: request.allowClone ?? false,
260
- cwdMode: request.cwdMode,
261
- worktreeName: request.worktreeName,
262
- });
263
-
264
- const targetWorkspace = await paseo.workspaces.open(prepared.cwd);
265
- await labelWorkspaceCwd(targetWorkspace, prepared.cwdTag);
266
-
267
- const { config } = await paseo.config.get();
268
- const profiles = config.agentProfiles ?? [];
269
- const wantedProfile = request.profileName.trim().toLowerCase();
270
- const profile =
271
- (wantedProfile
272
- ? profiles.find((candidate) => candidate.name.toLowerCase() === wantedProfile)
273
- : undefined) ??
274
- profiles.find((candidate) => candidate.name.toLowerCase() === "model router") ??
275
- profiles[0];
276
-
277
- const agentConfig = buildAgentConfig(profile, request.overrides);
278
- const prompt = buildAgentPrompt(row);
279
- const created = await targetWorkspace.agents.create({
280
- config: agentConfig,
281
- title: `PR Radar: ${row.repository}#${row.number}`,
282
- prompt,
283
- labels: { "pr-radar.cwd": prepared.cwdTag },
284
- });
285
-
244
+ const launched = await launchNewAgent({ paseo, prepareCwd, policy: settings }, request);
286
245
  if (navigation) {
287
- navigation.openAgent({ agentId: created.id, serverId: host.id });
246
+ navigation.openAgent({ agentId: launched.agentId, serverId: host.id });
288
247
  }
289
- const baseMsg = `Started new agent in ${prepared.cwdTag} (${prepared.cwd}) for ${row.repository}#${row.number}.`;
290
- const warnings = [request.routingWarning, prepared.warning].filter(Boolean);
291
- return warnings.length > 0 ? `${warnings.join(" ")} ${baseMsg}` : baseMsg;
248
+ return launched.message;
292
249
  },
293
250
  onMutate: (request) => {
294
251
  setOpenError(null);
@@ -322,13 +279,7 @@ export function PrRadar({
322
279
 
323
280
  autoLaunchingRef.current = true;
324
281
  try {
325
- let overrides: AgentLaunchOverrides = {
326
- provider: settings.defaultProvider,
327
- model: settings.defaultModel,
328
- thinkingOptionId: settings.defaultEffort,
329
- modeId: settings.defaultModeId,
330
- contextMode: settings.defaultContextMode,
331
- };
282
+ let overrides: AgentLaunchOverrides = defaultLaunchOverrides(settings);
332
283
  let profileName = settings.defaultProfile;
333
284
  let routingWarning: string | undefined;
334
285
 
@@ -375,26 +326,18 @@ export function PrRadar({
375
326
  },
376
327
  },
377
328
  });
378
- const vetted = routed.profile
379
- ? vetRoutedProfile(
380
- (await paseo.config.get()).config.agentProfiles ?? [],
381
- routed.profile,
382
- )
383
- : { ignored: [] as string[] };
384
- if (vetted.profileName) profileName = vetted.profileName;
385
- overrides = { ...overrides, ...routedProviderModel(overrides, routed) };
386
- if (routed.thinkingOptionId) {
387
- overrides = { ...overrides, thinkingOptionId: routed.thinkingOptionId };
388
- }
389
- const restricted = restrictRoutedLaunch(routed);
390
- restricted.ignored.push(...vetted.ignored);
391
- if (restricted.modeId) overrides = { ...overrides, modeId: restricted.modeId };
392
- if (routed.contextMode) overrides = { ...overrides, contextMode: routed.contextMode };
393
- if (restricted.options) overrides = { ...overrides, options: restricted.options };
394
- if (restricted.ignored.length > 0) {
395
- routingWarning = `Routing script values ignored (${restricted.ignored.join(", ")}).`;
396
- setActionNotice(routingWarning);
329
+ const profiles = routed.profile
330
+ ? ((await paseo.config.get()).config.agentProfiles ?? [])
331
+ : [];
332
+ const applied = applyAutoRouting({ settings, routed, profiles });
333
+ if (applied.status === "blocked") {
334
+ setActionNotice(applied.message);
335
+ return;
397
336
  }
337
+ profileName = applied.profileName;
338
+ overrides = applied.overrides;
339
+ routingWarning = applied.routingWarning;
340
+ if (routingWarning) setActionNotice(routingWarning);
398
341
  } catch (routerError) {
399
342
  const reason =
400
343
  routerError instanceof Error ? routerError.message : "Routing script failed.";
package/client/radar.ts CHANGED
@@ -744,7 +744,7 @@ export function checkSummary(row: RadarRow): string {
744
744
  return passed === 1 ? "1 check passed" : `${passed} checks passed`;
745
745
  }
746
746
 
747
- type AgentProfileLike = {
747
+ export type AgentProfileLike = {
748
748
  provider: string;
749
749
  model?: string;
750
750
  modeId?: string;
@@ -837,7 +837,7 @@ export function autoLaunchRequiresModal(
837
837
 
838
838
  const CWD_TAGS: readonly CwdTag[] = ["CWD-BASE", "CWD-WORKTREE", "CWD-TBD"];
839
839
 
840
- interface LabelableWorkspace {
840
+ export interface LabelableWorkspace {
841
841
  // Workspaces before Paseo 0.16.0-beta.1 have no setLabel.
842
842
  setLabel?(label: string, options: { assigned: boolean }): unknown;
843
843
  }
@@ -912,6 +912,17 @@ export interface AgentLaunchOverrides {
912
912
  thinkingOptionId?: string;
913
913
  contextMode?: string;
914
914
  options?: Record<string, unknown>;
915
+ // Raw routing-script output; `decideRoutedLabels` validates it at launch.
916
+ labels?: unknown;
917
+ }
918
+
919
+ // Labels for a launched agent: the labels already accepted by `decideRoutedLabels` plus PR Radar's
920
+ // own `pr-radar.cwd`, which a script can never set (the `pr-radar` keys are reserved).
921
+ export function buildAgentLabels(
922
+ cwdTag: string,
923
+ accepted: Record<string, string> = {},
924
+ ): Record<string, string> {
925
+ return { ...accepted, "pr-radar.cwd": cwdTag };
915
926
  }
916
927
 
917
928
  export function buildAgentConfig(
@@ -8,6 +8,7 @@ import {
8
8
  Loading,
9
9
  SettingsAction,
10
10
  SettingsCard,
11
+ SettingsInput,
11
12
  SettingsSection,
12
13
  SettingsSelect,
13
14
  useToast,
@@ -15,6 +16,7 @@ import {
15
16
  import { useQuery } from "@tanstack/react-query";
16
17
  import { useMemo, useRef, useState } from "react";
17
18
  import { Text, View } from "react-native";
19
+ import { labelPrefixesProblem } from "../shared/routed-labels";
18
20
  import {
19
21
  type AutoLaunchMode,
20
22
  type CwdMode,
@@ -66,6 +68,8 @@ function ReadyPrRadarSettings({
66
68
  const toast = useToast();
67
69
  const [dirQueryText, setDirQueryText] = useState(settings.values.sourceCodeDir);
68
70
  const [error, setError] = useState<string | null>(null);
71
+ // Remounts the prefix input after a reset: it only reads its initial value once.
72
+ const [prefixInputKey, setPrefixInputKey] = useState(0);
69
73
 
70
74
  const { profileOptions, providerOptions, modelOptions, modeOptions, contextModeOptions } =
71
75
  useAgentLaunchOptions();
@@ -149,6 +153,7 @@ function ReadyPrRadarSettings({
149
153
  setDirQueryText(DEFAULT_PR_RADAR_SETTINGS.sourceCodeDir);
150
154
  const saved = await savePatch({ ...DEFAULT_PR_RADAR_SETTINGS });
151
155
  if (saved) {
156
+ setPrefixInputKey((key) => key + 1);
152
157
  toast.show("PR Radar settings reset to defaults.", { variant: "success" });
153
158
  }
154
159
  }
@@ -268,6 +273,15 @@ function ReadyPrRadarSettings({
268
273
  theme={theme}
269
274
  onSelect={(next) => void savePatch({ routingScriptPath: next })}
270
275
  />
276
+ <SettingsInput
277
+ label="Allowed label prefixes"
278
+ hint="Routing script labels that one of these (comma or space separated) admits keep their name. A prefix admits itself, keys that continue it with . or / (ade.kind admits ade.kind.x, not ade.kinder), and every key under a prefix that ends in . or / (ade. admits ade.anything). Prefer the narrowest prefix, such as ade.kind. Every other script label is stored as pr-radar.route.<key>. pr-radar, pr-radar.*, paseo and paseo.* are always reserved."
279
+ key={prefixInputKey}
280
+ error={labelPrefixesProblem(settings.values.routingLabelPrefixes)}
281
+ initialValue={settings.values.routingLabelPrefixes}
282
+ placeholder="None: all script labels go under pr-radar.route."
283
+ onChangeText={(next) => void savePatch({ routingLabelPrefixes: next })}
284
+ />
271
285
  <SettingsAction
272
286
  label="Reset settings"
273
287
  hint="Restore all PR Radar settings to their defaults"
@@ -3,6 +3,12 @@ import { Icon, Modal, TextInput } from "@getpaseo/plugin/client/ui";
3
3
  import { useQuery } from "@tanstack/react-query";
4
4
  import { useEffect, useMemo, useRef, useState } from "react";
5
5
  import { Pressable, ScrollView, Text, View } from "react-native";
6
+ import {
7
+ BLOCKED_HEADLINE,
8
+ decideRoutedLabels,
9
+ describeLabel,
10
+ describeRejection,
11
+ } from "../shared/routed-labels";
6
12
  import type { CwdMode, PrRadarSettings } from "../shared/settings";
7
13
  import { listLocalDirs, type RoutingScriptResult, runRoutingScript } from "../shared/viewer-scope";
8
14
  import { ComboSelect, useAgentLaunchOptions } from "./agent-launch-options";
@@ -83,7 +89,19 @@ export function StartAgentModal({
83
89
  const [routedOptions, setRoutedOptions] = useState<Record<string, unknown> | undefined>(
84
90
  undefined,
85
91
  );
92
+ const [routedLabels, setRoutedLabels] = useState<unknown>(undefined);
86
93
  const [routeReason, setRouteReason] = useState<string | null>(null);
94
+ // What the launch will do with the routing script's labels: apply them or refuse to start.
95
+ const labelDecision = useMemo(
96
+ () => decideRoutedLabels({ labels: routedLabels, policy: settings }),
97
+ [routedLabels, settings.routingLabelPrefixes],
98
+ );
99
+ const routedLabelText =
100
+ labelDecision.status === "ok"
101
+ ? Object.entries(labelDecision.labels)
102
+ .map(([key, value]) => describeLabel(key, value))
103
+ .join(", ")
104
+ : "";
87
105
  const [routeError, setRouteError] = useState<string | null>(null);
88
106
  const [routingBusy, setRoutingBusy] = useState(false);
89
107
  const activeRowIdRef = useRef<string | null>(null);
@@ -111,6 +129,7 @@ export function StartAgentModal({
111
129
  setModeId(settings.defaultModeId);
112
130
  setContextMode(settings.defaultContextMode);
113
131
  setRoutedOptions(undefined);
132
+ setRoutedLabels(undefined);
114
133
  setRouteReason(null);
115
134
  setRouteError(null);
116
135
  setRoutingBusy(false);
@@ -137,6 +156,8 @@ export function StartAgentModal({
137
156
  const invocationSeq = ++routingSeqRef.current;
138
157
  setRoutingBusy(true);
139
158
  setRouteError(null);
159
+ setRoutedOptions(undefined);
160
+ setRoutedLabels(undefined);
140
161
  try {
141
162
  const result: RoutingScriptResult = await invokeRouter({
142
163
  payload: {
@@ -228,6 +249,7 @@ export function StartAgentModal({
228
249
  setContextMode(result.contextMode);
229
250
  }
230
251
  setRoutedOptions(restricted.options);
252
+ setRoutedLabels(result.labels);
231
253
  const ignoredNote =
232
254
  restricted.ignored.length > 0
233
255
  ? ` Ignored (not allowed): ${restricted.ignored.join(", ")}.`
@@ -552,6 +574,24 @@ export function StartAgentModal({
552
574
  ) : null}
553
575
  </View>
554
576
  {routeReason ? <Text style={styles.hint}>{routeReason}</Text> : null}
577
+ {routedLabelText ? (
578
+ <Text style={styles.hint}>{`Labels from routing script: ${routedLabelText}`}</Text>
579
+ ) : null}
580
+ {labelDecision.status === "blocked" ? (
581
+ <View>
582
+ <Text style={{ color: theme.colors.statusDanger, fontSize: 12 }}>
583
+ {`${BLOCKED_HEADLINE}. Fix the script:`}
584
+ </Text>
585
+ {labelDecision.rejected.map((rejection) => (
586
+ <Text
587
+ key={`${rejection.key}:${rejection.reason}`}
588
+ style={{ color: theme.colors.statusDanger, fontSize: 12 }}
589
+ >
590
+ {describeRejection(rejection)}
591
+ </Text>
592
+ ))}
593
+ </View>
594
+ ) : null}
555
595
  {routeError ? (
556
596
  <Text style={{ color: theme.colors.statusDanger, fontSize: 12 }}>{routeError}</Text>
557
597
  ) : null}
@@ -660,7 +700,7 @@ export function StartAgentModal({
660
700
  <Text style={styles.cancelText}>Cancel</Text>
661
701
  </Pressable>
662
702
  <Pressable
663
- disabled={pending || routingBusy}
703
+ disabled={pending || routingBusy || labelDecision.status === "blocked"}
664
704
  onPress={() =>
665
705
  onStart({
666
706
  row,
@@ -676,6 +716,7 @@ export function StartAgentModal({
676
716
  modeId,
677
717
  contextMode,
678
718
  ...(routedOptions ? { options: routedOptions } : {}),
719
+ ...(routedLabels === undefined ? {} : { labels: routedLabels }),
679
720
  },
680
721
  })
681
722
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omercnet/paseo-pr-radar",
3
- "version": "3.3.0-next.532.1",
3
+ "version": "3.3.0-next.533.1",
4
4
  "type": "module",
5
5
  "description": "A viewer-aware delivery queue for pull requests linked to Paseo workspaces.",
6
6
  "license": "MIT",
@@ -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