@omercnet/paseo-pr-radar 3.3.0-next.532.1 → 3.3.0-next.534.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
@@ -36,7 +36,17 @@ DevTools before capture. Both PNGs come from an isolated Paseo test daemon at 2
36
36
  - `Start New Agent`: available on every PR (orange when a local checkout/worktree exists, brown when `CWD-TBD` and a clone or directory pick is needed). Opens an interactive directory/worktree chooser (supporting incremental typing, GUI selection, `CWD-WORKTREE` vs `CWD-BASE`, and one-click clone + worktree creation), or launches immediately when configured in Settings.
37
37
  - `Open Existing Agent`: jumps directly to an existing linked Paseo agent.
38
38
  - `Ask agent` / `Open workspace` / `Copy link` / `Open PR`.
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.
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). Symbolic links on the configured path are checked hop by hop: each link must be owned by you or root, and the directory holding it and that directory's parents must not be writable by group or others. The check reads owners and the classic permission bits only: it does not read macOS extended ACLs (or POSIX ACLs on Linux), so an ACL that grants another user write access to the script or one of its directories is not detected. Review `ls -le` output for such entries yourself. The script runs with a minimal environment and a fixed `PATH` (`/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`, not the daemon's), so an interpreter named with `#!/usr/bin/env` is found only there (a directory in that list is dropped if another user owns it, or if group or others can write it or one of its parents. Homebrew leaves `/opt/homebrew/bin` writable by the `admin` group on many Macs, so `#!/usr/bin/env python3` then finds the root-owned `/usr/bin/python3`. To use Homebrew's interpreter, run `chmod go-w` on `/opt/homebrew/bin` and on any parent that group or others can write; that restores the PATH entry but does not check the interpreter it links to (for example under `Cellar`). A `#!/opt/homebrew/bin/python3` line also works but skips this check: any `admin` member could replace that interpreter); name any other tool by absolute path. The interpreter a `#!` line names is not itself checked. It has a 30 second timeout (time spent waiting for an earlier call counts against it) a 1 MiB output cap, and a 1 MiB cap on the input it is sent (PR text is written by others; an oversize payload is refused and the script is not run, and the launch then goes ahead without routing). One script runs at a time: up to two more calls wait their turn, and further calls are refused while they wait (not on Windows). Its whole process group is killed as soon as the script exits, so a background process it starts does not outlive it unless it detaches itself (`setsid`). When Paseo stops, reloads or disables the plugin, the plugin's cleanup ends a script that is still running (SIGTERM, then SIGKILL after one second) and refuses calls still waiting; the script runs in its own process group, so stopping the plugin process alone would not reach it. A daemon that is killed outright (SIGKILL, a crash) never runs the cleanup, and the script then keeps running until it ends by itself, because nothing is left to time it out. 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
+
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.
40
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
@@ -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/index.server.ts CHANGED
@@ -1,4 +1,9 @@
1
1
  import type { PluginServerContext } from "@getpaseo/plugin/server";
2
+ import {
3
+ runRoutingScriptHandler,
4
+ startRoutingScripts,
5
+ stopRoutingScripts,
6
+ } from "./server/routing-script";
2
7
  import {
3
8
  acknowledgeViewerUpdates,
4
9
  resolveViewerScope,
@@ -8,7 +13,6 @@ import {
8
13
  listLocalDirsHandler,
9
14
  prepareWorkspaceCwdHandler,
10
15
  type ReadWorkspaceSettings,
11
- runRoutingScriptHandler,
12
16
  } from "./server/workspace-ops";
13
17
  import { prRadarSettings } from "./shared/settings";
14
18
  import {
@@ -20,6 +24,7 @@ import {
20
24
  } from "./shared/viewer-scope";
21
25
 
22
26
  export default function contribute(server: PluginServerContext) {
27
+ startRoutingScripts();
23
28
  const settings = server.registerSettings(prRadarSettings);
24
29
  // Directories and the routing script come from these registered settings, never from RPC input.
25
30
  const readSettings: ReadWorkspaceSettings = async () => {
@@ -36,5 +41,10 @@ export default function contribute(server: PluginServerContext) {
36
41
  server.handle(runRoutingScript, (input) => runRoutingScriptHandler(input, readSettings));
37
42
  // Keep GitHub data warm so opening the radar never waits on gh.
38
43
  const stop = startBackgroundRefresh();
39
- return () => stop();
44
+ // Cleanup runs when the daemon stops, reloads or disables the plugin; the routing script is
45
+ // detached from the plugin process, so it is ended here.
46
+ return async () => {
47
+ stop();
48
+ await stopRoutingScripts();
49
+ };
40
50
  }
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.534.1",
4
4
  "type": "module",
5
5
  "description": "A viewer-aware delivery queue for pull requests linked to Paseo workspaces.",
6
6
  "license": "MIT",