@blackbelt-technology/pi-dashboard-extension 0.5.4 → 0.6.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 (254) hide show
  1. package/.pi/skills/browser/LICENSE +201 -0
  2. package/.pi/skills/browser/SKILL.md +105 -0
  3. package/.pi/skills/browser/UPSTREAM.md +46 -0
  4. package/.pi/skills/browser/references/electron.md +351 -0
  5. package/.pi/skills/browser/references/web.md +2789 -0
  6. package/.pi/skills/browser/scripts/detect-dashboard.sh +55 -0
  7. package/.pi/skills/doctor/AGENTS.md +27 -0
  8. package/.pi/skills/doctor/SKILL.md +89 -0
  9. package/.pi/skills/doctor/_lib/checks.ts +177 -0
  10. package/.pi/skills/doctor/_lib/derive-tokens.ts +43 -0
  11. package/.pi/skills/doctor/_lib/front-matter.ts +122 -0
  12. package/.pi/skills/doctor/_lib/index.ts +14 -0
  13. package/.pi/skills/doctor/_lib/knowledge-hash.ts +74 -0
  14. package/.pi/skills/doctor/_lib/provenance.ts +50 -0
  15. package/.pi/skills/doctor/_lib/regenerate.ts +100 -0
  16. package/.pi/skills/doctor/_lib/router.ts +155 -0
  17. package/.pi/skills/doctor/_lib/server-tier.ts +62 -0
  18. package/.pi/skills/doctor/modules/build-reload.knowledge.hash +1 -0
  19. package/.pi/skills/doctor/modules/build-reload.md +51 -0
  20. package/.pi/skills/doctor/modules/env-node.knowledge.hash +1 -0
  21. package/.pi/skills/doctor/modules/env-node.md +49 -0
  22. package/.pi/skills/doctor/modules/install-topology.knowledge.hash +1 -0
  23. package/.pi/skills/doctor/modules/install-topology.md +53 -0
  24. package/.pi/skills/doctor/modules/model-resolution.knowledge.hash +1 -0
  25. package/.pi/skills/doctor/modules/model-resolution.md +53 -0
  26. package/.pi/skills/doctor/modules/peers.knowledge.hash +1 -0
  27. package/.pi/skills/doctor/modules/peers.md +57 -0
  28. package/.pi/skills/doctor/modules/pi-resolution.knowledge.hash +1 -0
  29. package/.pi/skills/doctor/modules/pi-resolution.md +60 -0
  30. package/.pi/skills/doctor/modules/plugins-bridges.knowledge.hash +1 -0
  31. package/.pi/skills/doctor/modules/plugins-bridges.md +56 -0
  32. package/.pi/skills/pi-dashboard/SKILL.md +68 -0
  33. package/.pi/skills/pi-dashboard/commands/README.md +45 -0
  34. package/.pi/skills/pi-dashboard/commands/dashboard-flow-abort.md +10 -0
  35. package/.pi/skills/pi-dashboard/commands/dashboard-flow-auto.md +10 -0
  36. package/.pi/skills/pi-dashboard/commands/dashboard-git-branches.md +6 -0
  37. package/.pi/skills/pi-dashboard/commands/dashboard-git-init.md +8 -0
  38. package/.pi/skills/pi-dashboard/commands/dashboard-git-stash-pop.md +8 -0
  39. package/.pi/skills/pi-dashboard/commands/dashboard-list-models.md +10 -0
  40. package/.pi/skills/pi-dashboard/commands/dashboard-peer-list.md +6 -0
  41. package/.pi/skills/pi-dashboard/commands/dashboard-peer-scan.md +6 -0
  42. package/.pi/skills/pi-dashboard/commands/dashboard-pin-list.md +5 -0
  43. package/.pi/skills/pi-dashboard/commands/dashboard-proposal-archive.md +6 -0
  44. package/.pi/skills/pi-dashboard/commands/dashboard-proposal-attach.md +10 -0
  45. package/.pi/skills/pi-dashboard/commands/dashboard-proposal-detach.md +10 -0
  46. package/.pi/skills/pi-dashboard/commands/dashboard-server-config.md +5 -0
  47. package/.pi/skills/pi-dashboard/commands/dashboard-server-health.md +6 -0
  48. package/.pi/skills/pi-dashboard/commands/dashboard-server-tunnel-off.md +6 -0
  49. package/.pi/skills/pi-dashboard/commands/dashboard-server-tunnel-on.md +6 -0
  50. package/.pi/skills/pi-dashboard/commands/dashboard-server-tunnel-status.md +6 -0
  51. package/.pi/skills/pi-dashboard/commands/dashboard-session-abort-all.md +14 -0
  52. package/.pi/skills/pi-dashboard/commands/dashboard-session-abort.md +10 -0
  53. package/.pi/skills/pi-dashboard/commands/dashboard-session-diff.md +11 -0
  54. package/.pi/skills/pi-dashboard/commands/dashboard-session-fork.md +10 -0
  55. package/.pi/skills/pi-dashboard/commands/dashboard-session-hide.md +10 -0
  56. package/.pi/skills/pi-dashboard/commands/dashboard-session-info.md +11 -0
  57. package/.pi/skills/pi-dashboard/commands/dashboard-session-kill.md +10 -0
  58. package/.pi/skills/pi-dashboard/commands/dashboard-session-list-active.md +8 -0
  59. package/.pi/skills/pi-dashboard/commands/dashboard-session-list-here.md +8 -0
  60. package/.pi/skills/pi-dashboard/commands/dashboard-session-list.md +6 -0
  61. package/.pi/skills/pi-dashboard/commands/dashboard-session-model.md +10 -0
  62. package/.pi/skills/pi-dashboard/commands/dashboard-session-rename.md +10 -0
  63. package/.pi/skills/pi-dashboard/commands/dashboard-session-resume.md +10 -0
  64. package/.pi/skills/pi-dashboard/commands/dashboard-session-spawn.md +10 -0
  65. package/.pi/skills/pi-dashboard/commands/dashboard-session-tell.md +10 -0
  66. package/.pi/skills/pi-dashboard/commands/dashboard-session-thinking.md +10 -0
  67. package/.pi/skills/pi-dashboard/commands/dashboard-session-unhide.md +10 -0
  68. package/.pi/skills/pi-dashboard/references/api-reference.md +30 -0
  69. package/.pi/skills/pi-dashboard/references/recipes.md +38 -0
  70. package/.pi/skills/pi-dashboard/references/slash-commands.md +71 -0
  71. package/.pi/skills/pi-dashboard/scripts/dashboard-api.sh +6 -0
  72. package/.pi/skills/pi-dashboard/scripts/dashboard-bus.ts +217 -0
  73. package/.pi/skills/project-init/SKILL.md +279 -0
  74. package/.pi/skills/project-init/dox-doctrine.md +104 -0
  75. package/.pi/skills/project-init/profiles/coding/AGENTS.md.tmpl +111 -0
  76. package/.pi/skills/project-init/profiles/coding/profile.json +5 -0
  77. package/.pi/skills/project-init/profiles/coding/prompts/plan-change.md +5 -0
  78. package/.pi/skills/project-init/profiles/coding/prompts/tdd-loop.md +6 -0
  79. package/.pi/skills/project-init/profiles/coding/settings.json.tmpl +9 -0
  80. package/.pi/skills/project-init/profiles/docs/AGENTS.md.tmpl +37 -0
  81. package/.pi/skills/project-init/profiles/docs/profile.json +4 -0
  82. package/.pi/skills/project-init/profiles/docs/prompts/draft-page.md +5 -0
  83. package/.pi/skills/project-init/profiles/docs/settings.json.tmpl +9 -0
  84. package/package.json +12 -4
  85. package/src/AGENTS.md +56 -0
  86. package/src/__tests__/abort-latch.test.ts +97 -0
  87. package/src/__tests__/agent-settled.test.ts +82 -0
  88. package/src/__tests__/artifact-roots.test.ts +83 -0
  89. package/src/__tests__/ask-user-attachments.test.ts +106 -0
  90. package/src/__tests__/ask-user-tool.test.ts +90 -27
  91. package/src/__tests__/auto-session-namer.test.ts +339 -0
  92. package/src/__tests__/bridge-default-model-apply.test.ts +242 -0
  93. package/src/__tests__/bridge-default-model-gate.test.ts +6 -3
  94. package/src/__tests__/bridge-followup-mutation.test.ts +217 -0
  95. package/src/__tests__/bridge-followup-queue-drain.test.ts +266 -0
  96. package/src/__tests__/bridge-hasui-flip.test.ts +109 -0
  97. package/src/__tests__/bridge-no-queue-mutation.test.ts +112 -0
  98. package/src/__tests__/bridge-plugin-emit-event.test.ts +44 -0
  99. package/src/__tests__/bridge-shutdown-reset.test.ts +57 -136
  100. package/src/__tests__/bridge-slash-command-routing.test.ts +7 -7
  101. package/src/__tests__/bridge-stop-after-turn.test.ts +72 -0
  102. package/src/__tests__/bridge-system-followup.test.ts +163 -0
  103. package/src/__tests__/bridge-thinking-level-select.test.ts +68 -0
  104. package/src/__tests__/browser-skill-registered.test.ts +84 -0
  105. package/src/__tests__/build-provider-catalogue.test.ts +35 -1
  106. package/src/__tests__/command-handler.test.ts +331 -35
  107. package/src/__tests__/commit-draft.test.ts +100 -0
  108. package/src/__tests__/connection-dropped-frames.test.ts +78 -0
  109. package/src/__tests__/custom-provider-apikey-roundtrip.test.ts +128 -0
  110. package/src/__tests__/cwd-missing-probe.test.ts +82 -0
  111. package/src/__tests__/dashboard-commands-shipped.test.ts +53 -0
  112. package/src/__tests__/dashboard-context-injector.test.ts +190 -0
  113. package/src/__tests__/doctor/checks.test.ts +121 -0
  114. package/src/__tests__/doctor/modules.test.ts +64 -0
  115. package/src/__tests__/doctor/provenance-hash.test.ts +94 -0
  116. package/src/__tests__/doctor/router.test.ts +143 -0
  117. package/src/__tests__/empty-actionable-guard-config.test.ts +32 -0
  118. package/src/__tests__/empty-actionable-guard.test.ts +73 -0
  119. package/src/__tests__/enrich-model-metadata.test.ts +21 -0
  120. package/src/__tests__/extension-slash-command-detection.test.ts +37 -1
  121. package/src/__tests__/filter-enabled-models.test.ts +151 -0
  122. package/src/__tests__/fixtures/turn-actionability-fixtures.ts +69 -0
  123. package/src/__tests__/git-info-status.test.ts +73 -0
  124. package/src/__tests__/git-poll.test.ts +69 -0
  125. package/src/__tests__/markdown-image-inliner.test.ts +37 -0
  126. package/src/__tests__/model-resolve.test.ts +379 -0
  127. package/src/__tests__/pi-version-tracker.test.ts +109 -0
  128. package/src/__tests__/process-scanner.test.ts +112 -22
  129. package/src/__tests__/project-init-detect-stack.test.ts +61 -0
  130. package/src/__tests__/project-init-dox-kb-config.test.ts +53 -0
  131. package/src/__tests__/project-init-profiles.test.ts +84 -0
  132. package/src/__tests__/project-init-scaffold.test.ts +139 -0
  133. package/src/__tests__/project-init-seed-doctrine.test.ts +100 -0
  134. package/src/__tests__/project-trust.test.ts +92 -0
  135. package/src/__tests__/prompt-expander.test.ts +191 -1
  136. package/src/__tests__/provider-register-reload.test.ts +36 -6
  137. package/src/__tests__/provider-register-thinking-levels.test.ts +51 -0
  138. package/src/__tests__/retry-tracker.test.ts +75 -70
  139. package/src/__tests__/role-manager.test.ts +585 -0
  140. package/src/__tests__/role-model-tools-registry-readiness.test.ts +114 -0
  141. package/src/__tests__/role-model-tools.test.ts +229 -0
  142. package/src/__tests__/search-files-completeness.test.ts +111 -0
  143. package/src/__tests__/search-files-ranking.test.ts +168 -0
  144. package/src/__tests__/server-auto-start.test.ts +121 -4
  145. package/src/__tests__/server-launcher-launch.test.ts +24 -6
  146. package/src/__tests__/server-launcher.test.ts +19 -2
  147. package/src/__tests__/session-sync.test.ts +36 -0
  148. package/src/__tests__/subagent-frame-buffer.test.ts +239 -0
  149. package/src/__tests__/tool-result-image-inliner.test.ts +206 -0
  150. package/src/__tests__/tui-prompt-adapter.test.ts +70 -64
  151. package/src/__tests__/turn-actionability.test.ts +86 -0
  152. package/src/__tests__/vcs-info.test.ts +145 -4
  153. package/src/__tests__/visibility-intent.test.ts +43 -0
  154. package/src/abort-latch.ts +55 -0
  155. package/src/abort-latch.ts.AGENTS.md +3 -0
  156. package/src/agent-settled.ts +72 -0
  157. package/src/agent-settled.ts.AGENTS.md +3 -0
  158. package/src/artifact-roots.ts +73 -0
  159. package/src/artifact-roots.ts.AGENTS.md +3 -0
  160. package/src/ask-user-attachments.ts +121 -0
  161. package/src/ask-user-attachments.ts.AGENTS.md +3 -0
  162. package/src/ask-user-tool.ts +56 -58
  163. package/src/ask-user-tool.ts.AGENTS.md +3 -0
  164. package/src/auto-session-namer.ts +334 -0
  165. package/src/auto-session-namer.ts.AGENTS.md +3 -0
  166. package/src/bridge-context.ts +86 -8
  167. package/src/bridge-context.ts.AGENTS.md +3 -0
  168. package/src/bridge-default-model-gate.ts +22 -6
  169. package/src/bridge-default-model-gate.ts.AGENTS.md +3 -0
  170. package/src/bridge.ts +1241 -360
  171. package/src/bridge.ts.AGENTS.md +3 -0
  172. package/src/canvas-tool.ts +107 -0
  173. package/src/command-handler.ts +490 -51
  174. package/src/command-handler.ts.AGENTS.md +3 -0
  175. package/src/commit-draft-agent.ts +114 -0
  176. package/src/commit-draft-agent.ts.AGENTS.md +3 -0
  177. package/src/commit-draft.ts +136 -0
  178. package/src/commit-draft.ts.AGENTS.md +3 -0
  179. package/src/connection.ts +32 -1
  180. package/src/connection.ts.AGENTS.md +3 -0
  181. package/src/dashboard-context-injector.ts +124 -0
  182. package/src/dashboard-context-injector.ts.AGENTS.md +3 -0
  183. package/src/dashboard-default-adapter.ts.AGENTS.md +3 -0
  184. package/src/dev-build.ts.AGENTS.md +3 -0
  185. package/src/empty-actionable-guard-config.ts +32 -0
  186. package/src/empty-actionable-guard-config.ts.AGENTS.md +3 -0
  187. package/src/empty-actionable-guard.ts +90 -0
  188. package/src/empty-actionable-guard.ts.AGENTS.md +3 -0
  189. package/src/event-forwarder.ts.AGENTS.md +3 -0
  190. package/src/flow-event-wiring.ts +4 -14
  191. package/src/flow-event-wiring.ts.AGENTS.md +3 -0
  192. package/src/git-link-builder.ts.AGENTS.md +3 -0
  193. package/src/git-poll.ts +38 -0
  194. package/src/git-poll.ts.AGENTS.md +3 -0
  195. package/src/hasui-flip.ts +56 -0
  196. package/src/hasui-flip.ts.AGENTS.md +3 -0
  197. package/src/markdown-image-inliner.ts +45 -2
  198. package/src/markdown-image-inliner.ts.AGENTS.md +3 -0
  199. package/src/model-tracker.ts +145 -19
  200. package/src/model-tracker.ts.AGENTS.md +3 -0
  201. package/src/multiselect-decode.ts.AGENTS.md +3 -0
  202. package/src/multiselect-list.ts.AGENTS.md +3 -0
  203. package/src/multiselect-polyfill.ts.AGENTS.md +3 -0
  204. package/src/process-metrics.ts.AGENTS.md +3 -0
  205. package/src/process-scanner.ts +114 -103
  206. package/src/process-scanner.ts.AGENTS.md +3 -0
  207. package/src/project-init/AGENTS.md +12 -0
  208. package/src/project-init/detect-stack.ts +146 -0
  209. package/src/project-init/dox-kb-config.ts +47 -0
  210. package/src/project-init/profiles.ts +135 -0
  211. package/src/project-init/scaffold.ts +192 -0
  212. package/src/project-init/seed-doctrine.ts +95 -0
  213. package/src/project-trust.ts +63 -0
  214. package/src/project-trust.ts.AGENTS.md +3 -0
  215. package/src/prompt-bus.ts +10 -1
  216. package/src/prompt-bus.ts.AGENTS.md +3 -0
  217. package/src/prompt-expander.ts +238 -37
  218. package/src/prompt-expander.ts.AGENTS.md +3 -0
  219. package/src/provider-register.ts +323 -54
  220. package/src/provider-register.ts.AGENTS.md +3 -0
  221. package/src/retry-tracker.ts +64 -39
  222. package/src/retry-tracker.ts.AGENTS.md +3 -0
  223. package/src/role-manager.ts +436 -0
  224. package/src/role-manager.ts.AGENTS.md +3 -0
  225. package/src/role-model-tools.ts +301 -0
  226. package/src/role-model-tools.ts.AGENTS.md +3 -0
  227. package/src/server-auto-start.ts +59 -23
  228. package/src/server-auto-start.ts.AGENTS.md +3 -0
  229. package/src/server-launcher.ts +56 -16
  230. package/src/server-launcher.ts.AGENTS.md +3 -0
  231. package/src/session-sync.ts +111 -15
  232. package/src/session-sync.ts.AGENTS.md +3 -0
  233. package/src/slash-dispatch.ts +13 -11
  234. package/src/slash-dispatch.ts.AGENTS.md +3 -0
  235. package/src/source-detector.ts.AGENTS.md +3 -0
  236. package/src/subagent-frame-buffer.ts +220 -0
  237. package/src/subagent-frame-buffer.ts.AGENTS.md +3 -0
  238. package/src/tool-result-image-inliner.ts +204 -0
  239. package/src/tool-result-image-inliner.ts.AGENTS.md +3 -0
  240. package/src/tui-prompt-adapter.ts +123 -0
  241. package/src/tui-prompt-adapter.ts.AGENTS.md +3 -0
  242. package/src/turn-actionability.ts +117 -0
  243. package/src/turn-actionability.ts.AGENTS.md +3 -0
  244. package/src/ui-modules.ts.AGENTS.md +3 -0
  245. package/src/vcs-info.ts +91 -129
  246. package/src/vcs-info.ts.AGENTS.md +3 -0
  247. package/src/visibility-intent.ts +34 -0
  248. package/src/visibility-intent.ts.AGENTS.md +3 -0
  249. package/src/__tests__/bridge-retry-ordering.test.ts +0 -148
  250. package/src/__tests__/bridge-shadow-queue-drain.test.ts +0 -221
  251. package/src/__tests__/fixtures/usage-limit-error-strings.ts +0 -127
  252. package/src/__tests__/usage-limit-orderer.test.ts +0 -117
  253. package/src/__tests__/vcs-info-jj.test.ts +0 -145
  254. package/src/usage-limit-orderer.ts +0 -93
@@ -0,0 +1,436 @@
1
+ /**
2
+ * Role Manager Extension (Dashboard)
3
+ *
4
+ * Owns the `roles`, `rolePresets`, and `activePreset` keys of
5
+ * `~/.pi/agent/providers.json`. Registers the `roles:*` event handlers
6
+ * that back the dashboard's Settings → Roles UI. Previously hosted in
7
+ * pi-flows; ownership relocated here per OpenSpec change
8
+ * `adopt-model-resolve-handler-and-roles-ownership` (capabilities
9
+ * `dashboard-roles-ownership` and `dashboard-model-resolution`).
10
+ *
11
+ * Contract (spec: dashboard-roles-ownership):
12
+ * - Single source of truth on disk is `~/.pi/agent/providers.json`.
13
+ * - Reads tolerate missing file / malformed JSON (return empty config).
14
+ * - Writes use atomic tmp+rename, preserve unrelated keys (notably
15
+ * `providers` and pi-flows-owned `autonomousMode`).
16
+ * - Handlers re-read the file on every event so cross-session updates
17
+ * are visible without restart.
18
+ *
19
+ * Event API (dashboard-owned; the legacy `flow:` prefix was dropped — the
20
+ * compatibility window expired and pi-flows has zero role code):
21
+ * roles:get-all
22
+ * roles:set
23
+ * roles:remove
24
+ * roles:preset-load
25
+ * roles:preset-save
26
+ * roles:preset-delete
27
+ * See change: add-agent-role-model-tools (design D11).
28
+ * See change: add-custom-roles-ui (roles:remove + builtinRoleNames payload).
29
+ */
30
+
31
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
32
+ import { isValidRoleName } from "@blackbelt-technology/pi-dashboard-shared/role-name-validation.js";
33
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
34
+ import { homedir } from "node:os";
35
+ import { join } from "node:path";
36
+
37
+ // -- Types ----------------------------------------------------------------
38
+
39
+ export interface RolePreset {
40
+ name: string;
41
+ roles: Record<string, string>;
42
+ }
43
+
44
+ export interface RoleConfig {
45
+ roles: Record<string, string>;
46
+ rolePresets: RolePreset[];
47
+ activePreset: string | null;
48
+ /**
49
+ * User-added role names beyond DEFAULT_ROLE_NAMES. Persisted so an added
50
+ * role surfaces as an empty slot everywhere even before a model is assigned.
51
+ * See change: add-agent-role-model-tools (design D5, task 3.1).
52
+ */
53
+ roleNames?: string[];
54
+ /**
55
+ * Removal markers for DEFAULT role names the user removed, so the read-time
56
+ * overlay does NOT re-inject them. User-added names need no marker (dropping
57
+ * them from `roleNames` removes them from the effective schema).
58
+ */
59
+ removedRoles?: string[];
60
+ }
61
+
62
+ // -- Config path ----------------------------------------------------------
63
+
64
+ // Resolved lazily so HOME can be changed in tests.
65
+ function configPath(): string {
66
+ return join(homedir(), ".pi", "agent", "providers.json");
67
+ }
68
+
69
+ // -- Config I/O -----------------------------------------------------------
70
+
71
+ function loadFullConfig(): Record<string, unknown> {
72
+ const path = configPath();
73
+ if (!existsSync(path)) return {};
74
+ try {
75
+ const parsed = JSON.parse(readFileSync(path, "utf-8"));
76
+ return parsed && typeof parsed === "object" ? parsed as Record<string, unknown> : {};
77
+ } catch (err: any) {
78
+ console.warn(
79
+ `[dashboard] providers.json parse failed at ${path}: ${err?.message ?? String(err)}`,
80
+ );
81
+ return {};
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Read the role-relevant slice of `providers.json`. Tolerant of missing file
87
+ * and malformed JSON; both produce `{ roles: {}, rolePresets: [], activePreset: null }`.
88
+ *
89
+ * Re-read on every call — handlers depend on this to see cross-session updates.
90
+ */
91
+ export function loadRoleConfig(): RoleConfig {
92
+ const raw = loadFullConfig();
93
+ const roles: Record<string, string> = {};
94
+ const rawRoles = raw.roles;
95
+ if (rawRoles && typeof rawRoles === "object") {
96
+ for (const [k, v] of Object.entries(rawRoles)) {
97
+ if (typeof v === "string" && v.trim() !== "") roles[k] = v.trim();
98
+ }
99
+ }
100
+ const rolePresets: RolePreset[] = Array.isArray(raw.rolePresets)
101
+ ? (raw.rolePresets as RolePreset[])
102
+ : [];
103
+ const activePreset: string | null =
104
+ typeof raw.activePreset === "string" ? (raw.activePreset as string) : null;
105
+ const roleNames: string[] | undefined = Array.isArray(raw.roleNames)
106
+ ? (raw.roleNames as unknown[]).filter((n): n is string => typeof n === "string")
107
+ : undefined;
108
+ const removedRoles: string[] | undefined = Array.isArray(raw.removedRoles)
109
+ ? (raw.removedRoles as unknown[]).filter((n): n is string => typeof n === "string")
110
+ : undefined;
111
+ return { roles, rolePresets, activePreset, roleNames, removedRoles };
112
+ }
113
+
114
+ /**
115
+ * Atomic write of the role slice of `providers.json`. Preserves every other
116
+ * top-level key (notably `providers` — owned by provider-register.ts — and
117
+ * `autonomousMode` — owned by pi-flows).
118
+ */
119
+ export function saveRoleConfig(roleConfig: RoleConfig): void {
120
+ const path = configPath();
121
+ mkdirSync(join(homedir(), ".pi", "agent"), { recursive: true });
122
+ const full = loadFullConfig();
123
+ full.roles = roleConfig.roles;
124
+ full.rolePresets = roleConfig.rolePresets;
125
+ full.activePreset = roleConfig.activePreset;
126
+ // Persist the editable schema markers when present; drop empty arrays so we
127
+ // don't accrete empty keys on every write.
128
+ if (roleConfig.roleNames && roleConfig.roleNames.length > 0) full.roleNames = roleConfig.roleNames;
129
+ else delete full.roleNames;
130
+ if (roleConfig.removedRoles && roleConfig.removedRoles.length > 0) full.removedRoles = roleConfig.removedRoles;
131
+ else delete full.removedRoles;
132
+ // Atomic tmp+rename so readers never observe a partial file.
133
+ const tmp = `${path}.tmp-${process.pid}-${Date.now()}`;
134
+ writeFileSync(tmp, JSON.stringify(full, null, 2));
135
+ renameSync(tmp, path);
136
+ }
137
+
138
+ // -- Default roles --------------------------------------------------------
139
+ //
140
+ // Dashboard-owned canonical role-name set. Roles ownership moved off
141
+ // pi-flows (change: adopt-model-resolve-handler-and-roles-ownership), so the
142
+ // dashboard owns the default names too rather than depending on pi-flows
143
+ // being installed. Mirrors pi-flows' `KNOWN_MODEL_ROLES`.
144
+ //
145
+ // See change: roles-standalone-defaults-and-local-install-detection.
146
+ export const DEFAULT_ROLE_NAMES = [
147
+ "planning",
148
+ "coding",
149
+ "compact",
150
+ "fast",
151
+ "vision",
152
+ "research",
153
+ ] as const;
154
+
155
+ /**
156
+ * Overlay the default role names onto an assigned-roles map for DISPLAY.
157
+ * Assigned values win; default names absent from `roles` appear with an
158
+ * empty (unconfigured) value. Non-default assigned roles are preserved.
159
+ *
160
+ * Used by `roles:get-all` so the Roles table is never an empty dead
161
+ * end on a fresh install. NOT used by `role:resolve-model` (which reports
162
+ * the raw assigned map as `probe.available`).
163
+ */
164
+ export function overlayDefaultRoles(
165
+ roles: Record<string, string>,
166
+ ): Record<string, string> {
167
+ const out: Record<string, string> = {};
168
+ for (const name of DEFAULT_ROLE_NAMES) out[name] = "";
169
+ return { ...out, ...roles };
170
+ }
171
+
172
+ /**
173
+ * Effective role-name schema = (defaults ∪ added ∪ assigned) − removed,
174
+ * order-stable (defaults first, then adds, then any assigned extras).
175
+ * A removed default is NOT re-injected. See change: add-agent-role-model-tools.
176
+ */
177
+ export function effectiveRoleNames(
178
+ cfg: Pick<RoleConfig, "roles" | "roleNames" | "removedRoles">,
179
+ ): string[] {
180
+ const removed = new Set(cfg.removedRoles ?? []);
181
+ const out: string[] = [];
182
+ const seen = new Set<string>();
183
+ for (const n of [...DEFAULT_ROLE_NAMES, ...(cfg.roleNames ?? []), ...Object.keys(cfg.roles)]) {
184
+ if (removed.has(n) || seen.has(n)) continue;
185
+ seen.add(n);
186
+ out.push(n);
187
+ }
188
+ return out;
189
+ }
190
+
191
+ /**
192
+ * Read-time overlay keyed off the EFFECTIVE schema (defaults ∪ added − removed)
193
+ * instead of the hardcoded const. Every effective name appears (empty when
194
+ * unassigned); assigned values win. Used by roles:get-all.
195
+ */
196
+ export function overlayRoles(
197
+ cfg: Pick<RoleConfig, "roles" | "roleNames" | "removedRoles">,
198
+ ): Record<string, string> {
199
+ const out: Record<string, string> = {};
200
+ for (const name of effectiveRoleNames(cfg)) out[name] = "";
201
+ return { ...out, ...cfg.roles };
202
+ }
203
+
204
+ /**
205
+ * Register a role name in the editable schema. Clears any removal marker and
206
+ * (for non-defaults) records it in `roleNames`. Mutates `cfg` in place; the
207
+ * caller persists via saveRoleConfig. See change: add-agent-role-model-tools.
208
+ */
209
+ export function addRoleName(cfg: RoleConfig, role: string): void {
210
+ if (cfg.removedRoles) cfg.removedRoles = cfg.removedRoles.filter((r) => r !== role);
211
+ const isDefault = (DEFAULT_ROLE_NAMES as readonly string[]).includes(role);
212
+ if (!isDefault) {
213
+ cfg.roleNames = cfg.roleNames ?? [];
214
+ if (!cfg.roleNames.includes(role)) cfg.roleNames.push(role);
215
+ }
216
+ }
217
+
218
+ /**
219
+ * Purge a role from the schema, the active roles map, and EVERY preset, in a
220
+ * single mutation. A removed DEFAULT gains a removal marker so the overlay
221
+ * does not re-inject it. Mutates `cfg` in place; the caller persists atomically.
222
+ * See change: add-agent-role-model-tools (design D6, task 3.3).
223
+ */
224
+ export function removeRoleFromSchema(cfg: RoleConfig, role: string): void {
225
+ delete cfg.roles[role];
226
+ for (const p of cfg.rolePresets) delete p.roles[role];
227
+ if (cfg.roleNames) cfg.roleNames = cfg.roleNames.filter((r) => r !== role);
228
+ const isDefault = (DEFAULT_ROLE_NAMES as readonly string[]).includes(role);
229
+ if (isDefault) {
230
+ cfg.removedRoles = cfg.removedRoles ?? [];
231
+ if (!cfg.removedRoles.includes(role)) cfg.removedRoles.push(role);
232
+ }
233
+ }
234
+
235
+ // Persistence note (change: roles-standalone-defaults-and-local-install-detection):
236
+ // default role names are NOT auto-written to providers.json. The read-time
237
+ // overlay (`overlayDefaultRoles`) populates the Roles table without touching
238
+ // disk; a role reaches disk only when the user assigns a model via the
239
+ // existing `roles:set` handler. This avoids an uninvited write to the
240
+ // shared global providers.json on every session.
241
+
242
+ // -- In-memory cache ------------------------------------------------------
243
+ //
244
+ // Mirrors pi-flows' behaviour: a module-level snapshot of the current roles
245
+ // map populated at activate() and updated by `roles:set` /
246
+ // `roles:preset-load`. Used by `getModelRole(role)` for in-process callers
247
+ // (specifically `model:resolve` in provider-register.ts) that want to avoid
248
+ // a disk read in the hot path. The handlers themselves still re-read from
249
+ // disk per spec.
250
+
251
+ let currentRoles: Record<string, string> = {};
252
+
253
+ /**
254
+ * Single role-slice accessor. Strips a leading `@`, re-reads disk (so callers
255
+ * see cross-session edits without restart), and returns either the mapped
256
+ * literal `"provider/modelId"` or a structured not-configured `reason`.
257
+ *
258
+ * The one source of truth for `@role` → literal resolution, consumed by
259
+ * `model:resolve` (provider-register.ts), the deprecated `role:resolve-model`
260
+ * alias, and the `list_roles`/`update_roles` tools — no fourth independent
261
+ * reader. See change: add-agent-role-model-tools (design D10).
262
+ */
263
+ export function lookupRole(ref: string): { literal?: string; reason?: string } {
264
+ const roleName = ref.startsWith("@") ? ref.slice(1) : ref;
265
+ if (!roleName) return { reason: "empty role name" };
266
+ const cfg = loadRoleConfig();
267
+ currentRoles = cfg.roles;
268
+ const mapped = cfg.roles[roleName];
269
+ if (typeof mapped === "string" && mapped.trim() !== "") {
270
+ return { literal: mapped.trim() };
271
+ }
272
+ return { reason: `role '${roleName}' not configured yet` };
273
+ }
274
+
275
+ /** Look up the model literal assigned to `role`. Returns undefined if unset. */
276
+ export function getModelRole(role: string): string | undefined {
277
+ return lookupRole(role).literal;
278
+ }
279
+
280
+ // -- Extension entry point ------------------------------------------------
281
+
282
+ /**
283
+ * Register the five `roles:*` event handlers. No `flow:`-prefixed alias is
284
+ * retained — roles are 100% dashboard-owned and pi-flows has no role code.
285
+ * Writes are atomic tmp+rename so any concurrent writer leaves the file in a
286
+ * single consistent state (last writer wins). See change:
287
+ * add-agent-role-model-tools (design D11).
288
+ */
289
+ export function activate(pi: ExtensionAPI): void {
290
+ const initial = loadRoleConfig();
291
+ currentRoles = initial.roles;
292
+
293
+ // Resolve `@role` aliases for the subagents harness. pi-dashboard-subagents
294
+ // (>=0.2.0) emits `role:resolve-model` with probe `{ ref, resolved?,
295
+ // available? }` and reads back `probe.resolved` (a literal
296
+ // "provider/modelId"). The bridge's own `model:resolve` handler
297
+ // (provider-register.ts) uses a different probe shape, so the subagent
298
+ // spawn path never reached it — `@role` model fields hard-failed. This
299
+ // adapter maps the role name to its assigned model via providers.json#roles.
300
+ // DEPRECATED → model:resolve. Kept ONE release as an alias for legacy
301
+ // subagents-harness builds that read `probe.resolved` (a literal string)
302
+ // rather than `probe.model`. Delegates its `@role` → literal lookup to the
303
+ // shared lookupRole() accessor; preserves its probe.resolved/available/
304
+ // reason contract. Removed at next major.
305
+ // See change: add-agent-role-model-tools (design D9).
306
+ pi.events.on("role:resolve-model", (probe: any) => {
307
+ if (!probe || typeof probe.ref !== "string") return;
308
+ const ref = probe.ref.trim();
309
+ const roleName = ref.startsWith("@") ? ref.slice(1) : ref;
310
+ if (!roleName) return;
311
+ const cfg = loadRoleConfig();
312
+ currentRoles = cfg.roles;
313
+ probe.available = cfg.roles;
314
+ const { literal, reason } = lookupRole(ref);
315
+ if (literal) {
316
+ probe.resolved = literal;
317
+ } else {
318
+ // Shadow-disabled: role exists by name (default-seeded) or is unknown,
319
+ // but has no assigned model. Signal a structured "not configured yet"
320
+ // reason so the subagents harness surfaces an actionable spawn-time
321
+ // error instead of an opaque resolution failure.
322
+ probe.reason = reason;
323
+ }
324
+ });
325
+
326
+ pi.events.on("roles:get-all", (data: any) => {
327
+ const cfg = loadRoleConfig();
328
+ // Overlay the EFFECTIVE role-name schema (defaults ∪ added − removed) so
329
+ // the Roles table is never empty and tracks user edits. Assigned values
330
+ // win; unassigned effective names appear with an empty value.
331
+ data.roles = overlayRoles(cfg);
332
+ data.presets = cfg.rolePresets;
333
+ data.activePreset = cfg.activePreset;
334
+ // Single source of truth for the built-in/custom split; the client
335
+ // classifies roles off this instead of duplicating DEFAULT_ROLE_NAMES.
336
+ // See change: add-custom-roles-ui (design D2).
337
+ data.builtinRoleNames = [...DEFAULT_ROLE_NAMES];
338
+ });
339
+
340
+ pi.events.on("roles:set", (data: any) => {
341
+ const { role, modelId } = data ?? {};
342
+ // Defense-in-depth: re-validate the role NAME syntactically (empty
343
+ // `existing` → collision check skipped; assigning an existing role is
344
+ // legitimate). Rejects reserved chars/whitespace before any disk write.
345
+ // See change: add-custom-roles-ui (design D4, security-hardening).
346
+ if (!role || !modelId || !isValidRoleName(role, []).ok) {
347
+ data.success = false;
348
+ return;
349
+ }
350
+ const cfg = loadRoleConfig();
351
+ cfg.roles[role] = modelId;
352
+
353
+ // If a preset is active, update its roles map in-place too.
354
+ if (cfg.activePreset) {
355
+ const preset = cfg.rolePresets.find((p) => p.name === cfg.activePreset);
356
+ if (preset) preset.roles = { ...cfg.roles };
357
+ }
358
+
359
+ saveRoleConfig(cfg);
360
+ currentRoles = cfg.roles;
361
+ data.success = true;
362
+ });
363
+
364
+ pi.events.on("roles:preset-load", (data: any) => {
365
+ const { name } = data ?? {};
366
+ if (!name) {
367
+ data.success = false;
368
+ return;
369
+ }
370
+ const cfg = loadRoleConfig();
371
+ const preset = cfg.rolePresets.find((p) => p.name === name);
372
+ if (!preset) {
373
+ data.success = false;
374
+ return;
375
+ }
376
+ // Wholesale replacement (spec scenario "load replaces roles wholesale").
377
+ cfg.roles = { ...preset.roles };
378
+ cfg.activePreset = name;
379
+ saveRoleConfig(cfg);
380
+ currentRoles = cfg.roles;
381
+ data.success = true;
382
+ });
383
+
384
+ pi.events.on("roles:preset-save", (data: any) => {
385
+ const { name } = data ?? {};
386
+ if (!name) {
387
+ data.success = false;
388
+ return;
389
+ }
390
+ const cfg = loadRoleConfig();
391
+ const idx = cfg.rolePresets.findIndex((p) => p.name === name);
392
+ const preset: RolePreset = { name, roles: { ...cfg.roles } };
393
+ if (idx >= 0) cfg.rolePresets[idx] = preset;
394
+ else cfg.rolePresets.push(preset);
395
+ saveRoleConfig(cfg);
396
+ data.success = true;
397
+ });
398
+
399
+ pi.events.on("roles:remove", (data: any) => {
400
+ const { role } = data ?? {};
401
+ // Re-validate syntactically (empty `existing` → syntax-only), then reject
402
+ // built-ins server-side even though the UI never shows × on them (locked
403
+ // decision: built-ins permanent). See change: add-custom-roles-ui (D3, D4).
404
+ if (!role || !isValidRoleName(role, []).ok) {
405
+ data.success = false;
406
+ return;
407
+ }
408
+ if ((DEFAULT_ROLE_NAMES as readonly string[]).includes(role)) {
409
+ data.success = false;
410
+ return;
411
+ }
412
+ const cfg = loadRoleConfig();
413
+ removeRoleFromSchema(cfg, role);
414
+ saveRoleConfig(cfg);
415
+ currentRoles = cfg.roles;
416
+ data.success = true;
417
+ });
418
+
419
+ pi.events.on("roles:preset-delete", (data: any) => {
420
+ const { name } = data ?? {};
421
+ if (!name) {
422
+ data.success = false;
423
+ return;
424
+ }
425
+ const cfg = loadRoleConfig();
426
+ const before = cfg.rolePresets.length;
427
+ cfg.rolePresets = cfg.rolePresets.filter((p) => p.name !== name);
428
+ if (cfg.rolePresets.length === before) {
429
+ data.success = false;
430
+ return;
431
+ }
432
+ if (cfg.activePreset === name) cfg.activePreset = null;
433
+ saveRoleConfig(cfg);
434
+ data.success = true;
435
+ });
436
+ }
@@ -0,0 +1,3 @@
1
+ # role-manager.ts — index
2
+
3
+ Manages session model roles. Registers six `roles:*` handlers (`roles:get-all`/`set`/`remove`/`preset-load`/`preset-save`/`preset-delete`) — renamed from `flow:role-*`, NO alias (change: add-agent-role-model-tools D11). `roles:get-all` payload adds `builtinRoleNames = [...DEFAULT_ROLE_NAMES]`; `roles:set`+`roles:remove` re-validate name via shared `isValidRoleName(role, [])`; `roles:remove` rejects built-ins server-side then `removeRoleFromSchema`+save (change: add-custom-roles-ui). Exports `DEFAULT_ROLE_NAMES`, `lookupRole(ref)` (single `@role`→literal accessor: `{literal?,reason?}`, strips `@`, re-reads disk), `getModelRole` (delegates to `lookupRole`), `overlayDefaultRoles`, `overlayRoles(cfg)`/`effectiveRoleNames(cfg)` (effective schema = defaults ∪ added − removed), `addRoleName`/`removeRoleFromSchema` (mutate cfg; purge-on-remove). `RoleConfig` gains `roleNames`/`removedRoles`. `roles:get-all` overlays effective schema at read time — never empty, no auto-write. `role:resolve-model` = deprecated one-release alias via `lookupRole`; sets `probe.reason` when unconfigured. See change: add-agent-role-model-tools. See change: roles-standalone-defaults-and-local-install-detection.