pi-better-server 0.6.0 → 0.7.0

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.
Files changed (120) hide show
  1. package/package.json +4 -3
  2. package/scripts/measure-full-runtime/frontend.ts +10 -2
  3. package/scripts/measure-full-runtime.mjs +2 -0
  4. package/src/runtime/background-tools.ts +54 -8
  5. package/src/runtime/background.ts +16 -4
  6. package/src/runtime/domain/background/process.mjs +49 -11
  7. package/src/runtime/domain/background/supervisor/store.mjs +3 -3
  8. package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
  9. package/src/runtime/domain/background-service/index.domain.mjs +19 -0
  10. package/src/runtime/domain/background-service/index.ts +19 -0
  11. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +87 -5
  12. package/src/runtime/domain/background-service/managed-frontend.ts +76 -5
  13. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +5 -0
  14. package/src/runtime/domain/background-service/navigator-provider.ts +4 -0
  15. package/src/runtime/domain/background-service/observed-waits.domain.mjs +203 -31
  16. package/src/runtime/domain/background-service/observed-waits.ts +168 -24
  17. package/src/runtime/domain/background-service/process.domain.mjs +49 -11
  18. package/src/runtime/domain/background-service/process.ts +45 -11
  19. package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
  20. package/src/runtime/domain/background-service/review-settings.ts +18 -0
  21. package/src/runtime/domain/background-service/runtime.domain.mjs +8 -70
  22. package/src/runtime/domain/background-service/runtime.ts +8 -73
  23. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +55 -28
  24. package/src/runtime/domain/background-service/shared-navigator.ts +47 -26
  25. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  26. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
  27. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +5 -1
  28. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +6 -0
  29. package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
  30. package/src/runtime/domain/background-service/stall.ts +7 -4
  31. package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
  32. package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
  33. package/src/runtime/domain/background-service/supervisor/README.md +1 -4
  34. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
  35. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +49 -11
  36. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
  37. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
  38. package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
  39. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
  40. package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
  41. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
  42. package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
  43. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
  44. package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
  45. package/src/runtime/domain/background-service/tools.domain.mjs +22 -16
  46. package/src/runtime/domain/background-service/tools.ts +26 -16
  47. package/src/runtime/domain/background-service/types.ts +4 -2
  48. package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
  49. package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
  50. package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
  51. package/src/runtime/domain/coordinator/src/store.mjs +5 -1
  52. package/src/runtime/domain/log-paths.mjs +8 -1
  53. package/src/runtime/domain/parse.mjs +9 -5
  54. package/src/runtime/domain/sandbox-policy/README.md +3 -3
  55. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  56. package/src/runtime/domain/session-store.mjs +7 -0
  57. package/src/runtime/domain/subagents/README.md +12 -10
  58. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +2 -5
  59. package/src/runtime/domain/subagents/assignment-outcomes.ts +2 -5
  60. package/src/runtime/domain/subagents/assignment-report.domain.mjs +22 -0
  61. package/src/runtime/domain/subagents/assignment-report.ts +20 -0
  62. package/src/runtime/domain/subagents/batch.mjs +13 -5
  63. package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
  64. package/src/runtime/domain/subagents/cleanup.ts +10 -2
  65. package/src/runtime/domain/subagents/config.domain.mjs +5 -0
  66. package/src/runtime/domain/subagents/config.ts +7 -1
  67. package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
  68. package/src/runtime/domain/subagents/continuation.ts +4 -2
  69. package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
  70. package/src/runtime/domain/subagents/failures.ts +10 -2
  71. package/src/runtime/domain/subagents/finalization.domain.mjs +5 -2
  72. package/src/runtime/domain/subagents/finalization.ts +7 -2
  73. package/src/runtime/domain/subagents/index.domain.mjs +163 -61
  74. package/src/runtime/domain/subagents/index.ts +163 -60
  75. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +515 -0
  76. package/src/runtime/domain/subagents/isolated-workspace.ts +557 -0
  77. package/src/runtime/domain/subagents/list.mjs +2 -2
  78. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +22 -5
  79. package/src/runtime/domain/subagents/managed-launch-client.ts +23 -6
  80. package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
  81. package/src/runtime/domain/subagents/output-payload.ts +26 -12
  82. package/src/runtime/domain/subagents/package.json +4 -2
  83. package/src/runtime/domain/subagents/parse.domain.mjs +9 -5
  84. package/src/runtime/domain/subagents/parse.ts +10 -5
  85. package/src/runtime/domain/subagents/registry.domain.mjs +24 -18
  86. package/src/runtime/domain/subagents/registry.ts +23 -5
  87. package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
  88. package/src/runtime/domain/subagents/retained-result.ts +65 -0
  89. package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
  90. package/src/runtime/domain/subagents/session-selection.ts +2 -1
  91. package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
  92. package/src/runtime/domain/subagents/session-store.ts +9 -0
  93. package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
  94. package/src/runtime/domain/subagents/settings-page.ts +147 -108
  95. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +23 -7
  96. package/src/runtime/domain/subagents/shared-catalog.ts +23 -7
  97. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +55 -28
  98. package/src/runtime/domain/subagents/shared-navigator.ts +47 -26
  99. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  100. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
  101. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +5 -1
  102. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +6 -0
  103. package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
  104. package/src/runtime/domain/subagents/task-guard.ts +13 -1
  105. package/src/runtime/domain/subagents/task-policy.domain.mjs +2 -1
  106. package/src/runtime/domain/subagents/task-policy.ts +5 -1
  107. package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
  108. package/src/runtime/domain/subagents/tools.ts +4 -7
  109. package/src/runtime/domain/subagents/work-observation.domain.mjs +25 -1
  110. package/src/runtime/domain/subagents/work-observation.ts +20 -1
  111. package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
  112. package/src/runtime/domain/subagents/workspace-files.ts +114 -0
  113. package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
  114. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
  115. package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
  116. package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
  117. package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
  118. package/src/runtime/read-model.ts +4 -2
  119. package/src/runtime/root.ts +5 -2
  120. package/src/version.ts +1 -1
@@ -4,12 +4,13 @@ import { isConcurrencyCap } from "./config.ts";
4
4
  import { DELEGATION_MODES, type DelegationMode } from "./delegation.ts";
5
5
  import type { SkillExposureMode } from "./skills.ts";
6
6
  import { createSkillPicker, type DiscoveredSkill } from "./skill-picker.ts";
7
- import { validatedTimingMinutes } from "./timing.ts";
7
+ import { isTimingMinutes, MAX_TIMING_MINUTES, validatedTimingMinutes } from "./timing.ts";
8
8
 
9
9
  export type TimingSettingKey = "maxMinutes" | "toolWaitMinutes" | "stuckMinutes";
10
10
 
11
11
  export interface SubagentSettingsSnapshot {
12
12
  mode: DelegationMode;
13
+ gitWorkspace: "clone" | "worktree";
13
14
  maxConcurrent: number;
14
15
  maxMinutes: number;
15
16
  modeSource: "session" | "config";
@@ -34,6 +35,7 @@ export interface SubagentSettingsSnapshot {
34
35
 
35
36
  export interface SubagentSettingsHandlers {
36
37
  get(): SubagentSettingsSnapshot;
38
+ changeWorkspace(mode: "clone" | "worktree"): void;
37
39
  changeMode(mode: DelegationMode): void;
38
40
  changeCap(cap: number): void;
39
41
  changeTiming(key: TimingSettingKey, minutes: number): void;
@@ -48,16 +50,21 @@ export interface SubagentSettingsHandlers {
48
50
 
49
51
  type EditTarget = { kind: "cap" } | { kind: "toolWait" } | { kind: "stuck" } | { kind: "timeout" };
50
52
 
51
- type Row =
52
- | { kind: "mode" }
53
- | { kind: "cap" }
54
- | { kind: "toolWait" }
55
- | { kind: "stuck" }
56
- | { kind: "timeout" }
57
- | { kind: "skills" }
58
- | { kind: "choose" }
59
- | { kind: "agents" }
60
- | { kind: "reset" };
53
+ const rows = [
54
+ { kind: "mode", label: "Delegation mode" },
55
+ { kind: "cap", label: "Concurrent subagents" },
56
+ { kind: "workspace", label: "Git workspace" },
57
+ { kind: "timeout", label: "Run timeout" },
58
+ { kind: "toolWait", label: "Tool-wait alert" },
59
+ { kind: "stuck", label: "No-progress alert" },
60
+ { kind: "skills", label: "Skill exposure" },
61
+ { kind: "choose", label: "Selected skills" },
62
+ { kind: "agents", label: "Agents" },
63
+ { kind: "reset", label: "Reset to defaults" },
64
+ ] as const;
65
+
66
+ type Row = typeof rows[number];
67
+ const labelWidth = Math.max(...rows.map(({ label }) => Tui.visibleWidth(label)));
61
68
 
62
69
  const SKILL_MODES: readonly { mode: SkillExposureMode; label: string }[] = [
63
70
  { mode: "inherit", label: "Discover automatically" },
@@ -65,7 +72,17 @@ const SKILL_MODES: readonly { mode: SkillExposureMode; label: string }[] = [
65
72
  { mode: "explicit", label: "Selected skills" },
66
73
  ];
67
74
 
68
- const LABEL_WIDTH = 26;
75
+ const NO_LIMIT = "No limit";
76
+
77
+ function parseRunTimeout(input: string): number {
78
+ const text = input.trim();
79
+ if (text.toLowerCase() === NO_LIMIT.toLowerCase()) return 0;
80
+ const minutes = Number(text);
81
+ if (!text || !isTimingMinutes(minutes)) {
82
+ throw new Error(`Enter No limit or a duration up to ${MAX_TIMING_MINUTES} minutes.`);
83
+ }
84
+ return minutes;
85
+ }
69
86
 
70
87
  function skillLabel(mode: SkillExposureMode): string {
71
88
  return SKILL_MODES.find((entry) => entry.mode === mode)!.label;
@@ -76,15 +93,65 @@ function cycleSkillMode(mode: SkillExposureMode): SkillExposureMode {
76
93
  }
77
94
 
78
95
  function skillSource(settings: SubagentSettingsSnapshot): string {
79
- if (settings.skillsError) return `Config error: ${settings.skillsError}`;
80
96
  if (settings.skillsSource === "session") return "Source: this session (unsaved)";
81
97
  if (settings.skillsSource === "config") return "Source: config defaultSkills";
82
98
  return "Source: discovery default";
83
99
  }
84
100
 
85
- function cell(text: string, width: number): string {
86
- const clipped = Tui.truncateToWidth(text, width, "");
87
- return clipped + " ".repeat(Math.max(0, width - Tui.visibleWidth(clipped)));
101
+ function settingValue(kind: Row["kind"], s: SubagentSettingsSnapshot): string {
102
+ switch (kind) {
103
+ case "mode": return s.mode;
104
+ case "cap": return String(s.maxConcurrent);
105
+ case "workspace": return s.gitWorkspace === "worktree" ? "Worktree" : "Clone";
106
+ case "timeout": return s.maxMinutes === 0 ? NO_LIMIT : `${s.maxMinutes} min`;
107
+ case "toolWait": return s.toolWaitMinutes === 0 ? "Off" : `${s.toolWaitMinutes} min`;
108
+ case "stuck": return s.stuckMinutes === 0 ? "Off" : `${s.stuckMinutes} min`;
109
+ case "skills": return skillLabel(s.skillsMode);
110
+ case "choose": return s.skillsMode === "explicit" ? `${s.skillsPaths.length} checked` : "Choose…";
111
+ case "agents": return "Open";
112
+ case "reset": return "Restore";
113
+ }
114
+ }
115
+
116
+ function description(kind: Row["kind"], s: SubagentSettingsSnapshot): string {
117
+ switch (kind) {
118
+ case "mode": return {
119
+ manual: "Delegate when you ask or when the active workflow requires it.",
120
+ adaptive: "Delegate independent work when a suitable agent is available.",
121
+ coordinator: "Delegate work covered by an agent role. Keep coordination and verification in the foreground.",
122
+ }[s.mode];
123
+ case "cap": return "Set how many subagents can run at the same time.";
124
+ case "workspace": return s.gitWorkspace === "worktree"
125
+ ? "Create a linked worktree that shares the repository’s Git metadata."
126
+ : "Create a separate local clone for each isolated Git workspace.";
127
+ case "timeout": return "Stop a subagent when its run reaches this limit. Choose No limit to disable the timeout.";
128
+ case "toolWait": return "Notify the parent when a tool call stays open this long. Enter 0 to turn this alert off.";
129
+ case "stuck": return "Notify the parent after this long without progress. Time spent waiting for a tool is excluded. Enter 0 to turn this alert off.";
130
+ case "skills": return "Choose how new subagents discover skills.\n" + skillSource(s);
131
+ case "choose": return "Choose the skills to load for new subagents.";
132
+ case "agents": return "Browse agent roles and edit their profiles in /agents.";
133
+ case "reset": return "Restore saved defaults for this session, including its workspace, limits, and skills.";
134
+ }
135
+ }
136
+
137
+ function primaryKey(action: Tui.Keybinding, excludeSpace = false): string | undefined {
138
+ const key = Tui.getKeybindings().getKeys(action).find(key => !excludeSpace || key !== "space");
139
+ if (!key) return undefined;
140
+ if (key === "escape") return "Esc";
141
+ return key.split("+").map(part => part.length === 1 ? part : part[0]!.toUpperCase() + part.slice(1)).join("+");
142
+ }
143
+
144
+ function shortcuts(kind: Row["kind"], editing: boolean): string {
145
+ const cancel = primaryKey("tui.select.cancel");
146
+ const confirm = primaryKey(editing ? "tui.input.submit" : "tui.select.confirm", !editing);
147
+ const change = confirm ? `${confirm}/Space` : "Space";
148
+ const verb = kind === "agents" || kind === "choose" ? "open" : kind === "reset" ? "restore" : "change";
149
+ const actions = editing ? [confirm && `${confirm} to apply`]
150
+ : kind === "timeout" ? ["Space for No limit", confirm && `${confirm} to edit minutes`]
151
+ : [`${change} to ${verb}`];
152
+ if (!editing) actions.push("Ctrl+S to save defaults");
153
+ if (cancel) actions.push(`${cancel} to ${editing ? "cancel" : "go back"}`);
154
+ return actions.filter(Boolean).join(" · ");
88
155
  }
89
156
 
90
157
  export function createSubagentSettingsPage(
@@ -110,15 +177,6 @@ export function createSubagentSettingsPage(
110
177
  requestRender();
111
178
  }
112
179
 
113
- function rowsOf(settings: SubagentSettingsSnapshot): Row[] {
114
- const rows: Row[] = [
115
- { kind: "mode" }, { kind: "cap" }, { kind: "toolWait" }, { kind: "stuck" }, { kind: "timeout" },
116
- { kind: "skills" }, { kind: "choose" },
117
- ];
118
- rows.push({ kind: "agents" }, { kind: "reset" });
119
- return rows;
120
- }
121
-
122
180
  function startEditing(target: EditTarget, value: string): void {
123
181
  editing = target;
124
182
  input.setValue(value);
@@ -168,9 +226,12 @@ export function createSubagentSettingsPage(
168
226
  requestRender();
169
227
  }
170
228
 
171
- function action(settings: SubagentSettingsSnapshot, selected: Row): void {
229
+ function action(settings: SubagentSettingsSnapshot, selected: Row, key: string): void {
172
230
  try {
173
- if (selected.kind === "mode") {
231
+ if (selected.kind === "workspace") {
232
+ handlers.changeWorkspace(settings.gitWorkspace === "worktree" ? "clone" : "worktree");
233
+ report("Session workspace updated.");
234
+ } else if (selected.kind === "mode") {
174
235
  const next = DELEGATION_MODES[(DELEGATION_MODES.indexOf(settings.mode) + 1) % DELEGATION_MODES.length]!;
175
236
  handlers.changeMode(next);
176
237
  report("Session mode updated.");
@@ -181,7 +242,12 @@ export function createSubagentSettingsPage(
181
242
  } else if (selected.kind === "stuck") {
182
243
  startEditing({ kind: "stuck" }, String(settings.stuckMinutes));
183
244
  } else if (selected.kind === "timeout") {
184
- startEditing({ kind: "timeout" }, String(settings.maxMinutes));
245
+ if (key === " ") {
246
+ handlers.changeTiming("maxMinutes", 0);
247
+ report("Run timeout set to No limit.");
248
+ } else {
249
+ startEditing(selected, settings.maxMinutes === 0 ? NO_LIMIT : String(settings.maxMinutes));
250
+ }
185
251
  } else if (selected.kind === "skills") {
186
252
  if (settings.skillsMode === "explicit") rememberedSkillPaths = [...settings.skillsPaths];
187
253
  const next = cycleSkillMode(settings.skillsMode);
@@ -208,7 +274,6 @@ export function createSubagentSettingsPage(
208
274
  const submit = (value: string) => {
209
275
  const target = editing;
210
276
  if (!target) return;
211
- const settings = handlers.get();
212
277
  if (target.kind === "cap") {
213
278
  const cap = /^\d+$/.test(value.trim()) ? Number(value.trim()) : NaN;
214
279
  if (!isConcurrencyCap(cap)) {
@@ -226,7 +291,7 @@ export function createSubagentSettingsPage(
226
291
  const key = target.kind === "toolWait" ? "toolWaitMinutes"
227
292
  : target.kind === "stuck" ? "stuckMinutes" : "maxMinutes";
228
293
  try {
229
- const minutes = validatedTimingMinutes(value.trim(), key);
294
+ const minutes = target.kind === "timeout" ? parseRunTimeout(value) : validatedTimingMinutes(value.trim(), key);
230
295
  handlers.changeTiming(key, minutes);
231
296
  finishEditing(target.kind === "toolWait" ? "Tool-wait alert updated."
232
297
  : target.kind === "stuck" ? "No-progress alert updated." : "Timeout updated.");
@@ -262,13 +327,13 @@ export function createSubagentSettingsPage(
262
327
  requestRender();
263
328
  return;
264
329
  }
265
- const rows = rowsOf(settings);
266
- row = Math.min(row, rows.length - 1);
267
330
  const selected = rows[row]!;
268
- if (Tui.matchesKey(data, Tui.Key.escape)) close();
269
- else if (Tui.matchesKey(data, Tui.Key.up)) row = Math.max(0, row - 1);
270
- else if (Tui.matchesKey(data, Tui.Key.down)) row = Math.min(rows.length - 1, row + 1);
271
- else if (Tui.matchesKey(data, Tui.Key.enter) || data === " ") action(settings, selected);
331
+ const keys = Tui.getKeybindings();
332
+ if (keys.matches(data, "tui.select.cancel")) close();
333
+ else if (keys.matches(data, "tui.select.up") || keys.matches(data, "tui.select.down")) {
334
+ row = Math.max(0, Math.min(rows.length - 1, row + (keys.matches(data, "tui.select.up") ? -1 : 1)));
335
+ message = "";
336
+ } else if (keys.matches(data, "tui.select.confirm") || data === " ") action(settings, selected, data);
272
337
  else if (Tui.matchesKey(data, "ctrl+s")) {
273
338
  const result = handlers.save();
274
339
  if (result.ok) {
@@ -281,83 +346,57 @@ export function createSubagentSettingsPage(
281
346
  render(width: number) {
282
347
  if (picker) return picker.render(width);
283
348
  const settings = handlers.get();
284
- const rows = rowsOf(settings);
285
- row = Math.min(row, rows.length - 1);
286
349
  const w = Math.max(1, Math.floor(width));
287
- const compact = w < 40;
288
- const valueWidth = Math.max(1, w - LABEL_WIDTH - 1);
289
- const highlight = (text: string, selected: boolean): string => selected
290
- ? theme.bg("selectedBg", theme.bold(cell(text, w))) : text;
291
- const marker = (selected: boolean) => selected ? "> " : " ";
292
- const source = skillSource(settings);
293
- const lines: string[] = [theme.fg("accent", theme.bold(" Subagent settings")), ""];
294
-
295
- const pushSetting = (label: string, value: string, selected: boolean, active: string): void => {
296
- const title = theme.fg(selected ? "accent" : "text", marker(selected) + label);
297
- if (compact) {
298
- lines.push(highlight(title, selected));
299
- lines.push(" " + (selected ? theme.inverse(active) : theme.fg("text", active)));
300
- } else {
301
- lines.push(highlight(cell(title, LABEL_WIDTH) + " " +
302
- (selected ? theme.inverse(active) : theme.fg("text", active)), selected));
303
- }
304
- };
305
-
306
- let selectedStart = 2;
307
- let selectedEnd = 3;
308
- rows.forEach((entry, index) => {
309
- const selected = index === row;
310
- if (selected) selectedStart = lines.length;
311
- if (entry.kind === "mode" || entry.kind === "cap" || entry.kind === "toolWait"
312
- || entry.kind === "stuck" || entry.kind === "timeout") {
313
- const label = entry.kind === "mode" ? "Delegation mode"
314
- : entry.kind === "cap" ? "Concurrent subagents"
315
- : entry.kind === "toolWait" ? "Tool-wait alert"
316
- : entry.kind === "stuck" ? "No-progress alert" : "Timeout (minutes)";
317
- const value = entry.kind === "mode" ? settings.mode
318
- : entry.kind === "cap" ? String(settings.maxConcurrent)
319
- : entry.kind === "timeout" ? String(settings.maxMinutes)
320
- : `${entry.kind === "toolWait" ? settings.toolWaitMinutes : settings.stuckMinutes} min`;
321
- const active = editing?.kind === entry.kind
322
- ? input.render(compact ? Math.max(1, w - 2) : valueWidth)[0]!
323
- : value;
324
- pushSetting(label, value, selected, active);
325
- if (entry.kind === "stuck" && settings.timingError) {
326
- const sourceLine = compact ? " " + settings.timingError : " ".repeat(LABEL_WIDTH) + " " + settings.timingError;
327
- lines.push(theme.fg("error", Tui.truncateToWidth(sourceLine, w, "")));
328
- }
329
- } else if (entry.kind === "skills") {
330
- pushSetting("Skill exposure", skillLabel(settings.skillsMode), selected, skillLabel(settings.skillsMode));
331
- const sourceLine = compact ? " " + source : " ".repeat(LABEL_WIDTH) + " " + source;
332
- lines.push(theme.fg(settings.skillsError ? "error" : "muted",
333
- Tui.truncateToWidth(sourceLine, w, "")));
334
- } else if (entry.kind === "choose") {
335
- const value = settings.skillsMode === "explicit" ? `${settings.skillsPaths.length} checked` : "Choose…";
336
- pushSetting("Selected skills", value, selected, value);
337
- } else if (entry.kind === "agents") {
338
- lines.push(highlight(theme.fg(selected ? "accent" : "text", marker(selected) + "Agents"), selected));
350
+ const height = Math.max(1, Math.floor(getHeight()));
351
+ const valueColumn = 2 + labelWidth + 2;
352
+ const body: string[] = [];
353
+ let selectedStart = 0;
354
+ let selectedEnd = 0;
355
+ for (const [index, entry] of rows.entries()) {
356
+ const active = index === row;
357
+ const value = settingValue(entry.kind, settings);
358
+ const stacked = valueColumn + Math.max(Tui.visibleWidth(value), editing?.kind === entry.kind ? 8 : 0) > w;
359
+ const column = stacked ? Math.min(4, Math.max(0, w - 1)) : valueColumn;
360
+ const valueText = editing?.kind === entry.kind
361
+ ? input.render(Math.max(1, w - column))[0] ?? ""
362
+ : active ? theme.inverse(value) : theme.fg("muted", value);
363
+ const label = (active ? "> " : " ") + theme.fg(active ? "accent" : "text", entry.label);
364
+ if (active) selectedStart = body.length;
365
+ if (stacked) {
366
+ const valueLines = Tui.wrapTextWithAnsi(valueText, Math.max(1, w - column));
367
+ body.push(label, ...valueLines.map(line => " ".repeat(column) + line));
339
368
  } else {
340
- lines.push("");
341
- lines.push(highlight(theme.fg(selected ? "accent" : "text", marker(selected) + "Reset to defaults"), selected));
369
+ body.push(label + " ".repeat(valueColumn - Tui.visibleWidth(label)) + valueText);
342
370
  }
343
- if (selected) selectedEnd = lines.length;
344
- });
371
+ if (active) selectedEnd = body.length;
372
+ }
345
373
 
346
- const body = lines.slice(2);
347
- const footer: string[] = [];
348
- if (message) footer.push("", theme.fg(error ? "error" : "muted", message));
349
- footer.push("", theme.fg("dim", editing
350
- ? "Enter Apply · Esc Cancel"
351
- : "Up/Down Select · Space/Enter Change · ctrl+s Save default · Esc Back"));
352
- const height = Math.max(1, Math.floor(getHeight()));
353
- const room = Math.max(1, height - 2 - footer.length);
354
- if (selectedEnd - 2 > viewportStart + room) viewportStart = selectedEnd - 2 - room;
355
- if (selectedStart - 2 < viewportStart) viewportStart = selectedStart - 2;
374
+ const selected = rows[row]!.kind;
375
+ const hint = shortcuts(selected, editing !== undefined);
376
+ const wrap = (text: string, color: Parameters<Theme["fg"]>[0]) =>
377
+ Tui.wrapTextWithAnsi(text, Math.max(1, w - 2)).map(line => " " + theme.fg(color, line));
378
+ const help = wrap(description(selected, settings), "text");
379
+ const feedback = [
380
+ ...(settings.timingError ? wrap(settings.timingError, "error") : []),
381
+ ...(settings.skillsError ? wrap(`Config error: ${settings.skillsError}`, "error") : []),
382
+ ...(message ? wrap(message, error ? "error" : "muted") : []),
383
+ ];
384
+ const title = theme.bold(theme.fg("text", "Subagent settings"));
385
+ const header = height >= 6 ? [title, ""] : [];
386
+ // Reserve space for the focused control and validation before its help or shortcuts.
387
+ const footerRoom = Math.max(0, height - header.length - (selectedEnd - selectedStart));
388
+ const status = feedback.slice(0, footerRoom);
389
+ const hints = wrap(hint, "dim");
390
+ const footer = [...help, "", ...hints];
391
+ const budget = footerRoom - status.length;
392
+ const visibleHelp = footer.length + 1 <= budget ? ["", ...footer]
393
+ : editing ? hints.slice(0, budget) : help.slice(0, Math.min(budget, 2));
394
+ const room = Math.max(1, height - header.length - visibleHelp.length - status.length);
356
395
  viewportStart = Math.max(0, Math.min(viewportStart, body.length - room));
357
- const visible = [...lines.slice(0, 2), ...body.slice(viewportStart, viewportStart + room), ...footer];
358
- // A very short terminal prioritizes the active control over chrome.
359
- const result = height < 2 + footer.length + 1 ? body.slice(selectedStart - 2, selectedStart - 2 + height) : visible;
360
- return result.map((line) => Tui.truncateToWidth(line, w, ""));
396
+ if (selectedEnd > viewportStart + room) viewportStart = selectedEnd - room;
397
+ if (selectedStart < viewportStart) viewportStart = selectedStart;
398
+ return [...header, ...body.slice(viewportStart, viewportStart + room), ...visibleHelp, ...status]
399
+ .map(line => Tui.truncateToWidth(line, w, ""));
361
400
  },
362
401
  };
363
402
  }
@@ -5,7 +5,8 @@ import { connectWorkClient } from "./shared-work-client.mjs";
5
5
  import { catalogSnapshotFromWire, defaultUserRoot } from "./catalog-store.domain.mjs";
6
6
  import { catalogHostAuthority } from "./catalog-host-admission.domain.mjs";
7
7
  /** Short-lived catalog connection. No transcript or permission authority travels here. */
8
- export async function openSharedCatalog(cwd, userRoot = defaultUserRoot(), sessionId = "catalog", projectAccess) {
8
+ export async function openSharedCatalog(cwd, userRoot = defaultUserRoot(), sessionId = "catalog", projectAccess, signal) {
9
+ signal?.throwIfAborted();
9
10
  const agentDir = realpathSync(userRoot);
10
11
  let registration;
11
12
  try {
@@ -14,19 +15,19 @@ export async function openSharedCatalog(cwd, userRoot = defaultUserRoot(), sessi
14
15
  catch (error) {
15
16
  if (error.code !== "ENOENT")
16
17
  throw error;
17
- await ensureCatalogRuntime(agentDir);
18
+ await waitForCatalogSetup(ensureCatalogRuntime(agentDir, undefined, undefined, signal), signal);
18
19
  registration = JSON.parse(readFileSync(join(agentDir, "server-registration-v1.json"), "utf8"));
19
20
  }
20
21
  if (registration.version !== 1 || registration.agentDir !== agentDir)
21
22
  throw new Error("Invalid canonical runtime registration");
22
- const client = await connectCatalogClient(agentDir, registration.serverDir);
23
- const register = async () => {
23
+ const client = await connectCatalogClient(agentDir, registration.serverDir, undefined, signal);
24
+ const register = async (setupSignal) => {
24
25
  const authority = await catalogHostAuthority(agentDir, cwd, join(registration.serverDir, "pi-server.sock"));
26
+ setupSignal?.throwIfAborted();
25
27
  await client.request("runtime_register_catalog", { cwd, sessionId: authority?.sessionId ?? sessionId, authority, projectAccess: projectAccess === false ? "deny" : undefined });
26
28
  };
27
29
  try {
28
- await client.ready;
29
- await register();
30
+ await waitForCatalogSetup(register(signal), signal);
30
31
  }
31
32
  catch (error) {
32
33
  client.close();
@@ -58,11 +59,26 @@ export async function openSharedCatalog(cwd, userRoot = defaultUserRoot(), sessi
58
59
  };
59
60
  }
60
61
  /** Retry connection establishment only; never replay a Catalog edit or authorization failure. */
61
- export async function connectCatalogClient(agentDir, serverDir, ensure = ensureCatalogRuntime) {
62
+ export async function connectCatalogClient(agentDir, serverDir, ensure = ensureCatalogRuntime, signal) {
62
63
  return connectWorkClient(join(serverDir, "pi-server.sock"), agentDir, ["runtime-catalog-v1"], {
64
+ signal,
63
65
  recover: ({ timeoutMs, signal }) => ensure(agentDir, serverDir, timeoutMs, signal),
64
66
  });
65
67
  }
68
+ /** Cancel an individual wait without revoking a Catalog authority shared with other callers. */
69
+ export function waitForCatalogSetup(pending, signal) {
70
+ if (!signal)
71
+ return pending;
72
+ return new Promise((resolve, reject) => {
73
+ const abort = () => reject(signal.reason);
74
+ signal.addEventListener("abort", abort, { once: true });
75
+ void pending.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
76
+ if (signal.aborted) {
77
+ signal.removeEventListener("abort", abort);
78
+ abort();
79
+ }
80
+ });
81
+ }
66
82
  async function ensureCatalogRuntime(agentDir, serverDir, timeoutMs, signal) {
67
83
  const path = "./runtime-client/src/runtime/client.mjs";
68
84
  const { ensureRuntime } = await import(path);
@@ -6,24 +6,25 @@ import type { AgentSessionOverrides } from "./agent-session-settings.ts";
6
6
  import { catalogHostAuthority } from "./catalog-host-admission.ts";
7
7
 
8
8
  /** Short-lived catalog connection. No transcript or permission authority travels here. */
9
- export async function openSharedCatalog(cwd: string, userRoot = defaultUserRoot(), sessionId = "catalog", projectAccess?: boolean) {
9
+ export async function openSharedCatalog(cwd: string, userRoot = defaultUserRoot(), sessionId = "catalog", projectAccess?: boolean, signal?: AbortSignal) {
10
+ signal?.throwIfAborted();
10
11
  const agentDir = realpathSync(userRoot);
11
12
  let registration;
12
13
  try { registration = JSON.parse(readFileSync(join(agentDir, "server-registration-v1.json"), "utf8")); }
13
14
  catch (error) {
14
15
  if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
15
- await ensureCatalogRuntime(agentDir);
16
+ await waitForCatalogSetup(ensureCatalogRuntime(agentDir, undefined, undefined, signal), signal);
16
17
  registration = JSON.parse(readFileSync(join(agentDir, "server-registration-v1.json"), "utf8"));
17
18
  }
18
19
  if (registration.version !== 1 || registration.agentDir !== agentDir) throw new Error("Invalid canonical runtime registration");
19
- const client = await connectCatalogClient(agentDir, registration.serverDir);
20
- const register = async () => {
20
+ const client = await connectCatalogClient(agentDir, registration.serverDir, undefined, signal);
21
+ const register = async (setupSignal?: AbortSignal) => {
21
22
  const authority = await catalogHostAuthority(agentDir, cwd, join(registration.serverDir, "pi-server.sock"));
23
+ setupSignal?.throwIfAborted();
22
24
  await client.request("runtime_register_catalog", { cwd, sessionId: authority?.sessionId ?? sessionId, authority, projectAccess: projectAccess === false ? "deny" : undefined });
23
25
  };
24
26
  try {
25
- await client.ready;
26
- await register();
27
+ await waitForCatalogSetup(register(signal), signal);
27
28
  } catch (error) { client.close(); throw error; }
28
29
  return {
29
30
  async get(overlay?: AgentSessionOverrides): Promise<CatalogSnapshot> {
@@ -48,12 +49,27 @@ export async function openSharedCatalog(cwd: string, userRoot = defaultUserRoot(
48
49
  }
49
50
 
50
51
  /** Retry connection establishment only; never replay a Catalog edit or authorization failure. */
51
- export async function connectCatalogClient(agentDir: string, serverDir: string, ensure = ensureCatalogRuntime): Promise<WorkClient> {
52
+ export async function connectCatalogClient(agentDir: string, serverDir: string, ensure = ensureCatalogRuntime, signal?: AbortSignal): Promise<WorkClient> {
52
53
  return connectWorkClient(join(serverDir, "pi-server.sock"), agentDir, ["runtime-catalog-v1"], {
54
+ signal,
53
55
  recover: ({ timeoutMs, signal }) => ensure(agentDir, serverDir, timeoutMs, signal),
54
56
  });
55
57
  }
56
58
 
59
+ /** Cancel an individual wait without revoking a Catalog authority shared with other callers. */
60
+ export function waitForCatalogSetup<T>(pending: Promise<T>, signal?: AbortSignal): Promise<T> {
61
+ if (!signal) return pending;
62
+ return new Promise((resolve, reject) => {
63
+ const abort = () => reject(signal.reason);
64
+ signal.addEventListener("abort", abort, { once: true });
65
+ void pending.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
66
+ if (signal.aborted) {
67
+ signal.removeEventListener("abort", abort);
68
+ abort();
69
+ }
70
+ });
71
+ }
72
+
57
73
  async function ensureCatalogRuntime(agentDir: string, serverDir?: string, timeoutMs?: number, signal?: AbortSignal): Promise<void> {
58
74
  const path = "./runtime-client/src/runtime/client.mjs";
59
75
  const { ensureRuntime } = await import(path);