@timmyjl12/pi-subagents 0.0.0-stage → 0.21.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 (244) hide show
  1. package/CHANGELOG.md +862 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1125 -3
  5. package/SECURITY.md +97 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/active-agents-prompt.d.ts +40 -0
  9. package/dist/active-agents-prompt.js +98 -0
  10. package/dist/advisor-status.d.ts +16 -0
  11. package/dist/advisor-status.js +74 -0
  12. package/dist/agent-color.d.ts +35 -0
  13. package/dist/agent-color.js +131 -0
  14. package/dist/agent-file-toggle.d.ts +125 -0
  15. package/dist/agent-file-toggle.js +264 -0
  16. package/dist/agent-manager.d.ts +872 -0
  17. package/dist/agent-manager.js +2910 -0
  18. package/dist/agent-runner.d.ts +358 -0
  19. package/dist/agent-runner.js +1219 -0
  20. package/dist/agent-types.d.ts +142 -0
  21. package/dist/agent-types.js +315 -0
  22. package/dist/awaited-result.d.ts +37 -0
  23. package/dist/awaited-result.js +150 -0
  24. package/dist/child-context.d.ts +15 -0
  25. package/dist/child-context.js +181 -0
  26. package/dist/child-session-shutdown.d.ts +21 -0
  27. package/dist/child-session-shutdown.js +97 -0
  28. package/dist/cleanup-plans.d.ts +10 -0
  29. package/dist/cleanup-plans.js +112 -0
  30. package/dist/context.d.ts +12 -0
  31. package/dist/context.js +56 -0
  32. package/dist/cross-extension-rpc.d.ts +73 -0
  33. package/dist/cross-extension-rpc.js +192 -0
  34. package/dist/custom-agents.d.ts +79 -0
  35. package/dist/custom-agents.js +583 -0
  36. package/dist/default-agents.d.ts +7 -0
  37. package/dist/default-agents.js +125 -0
  38. package/dist/enabled-models.d.ts +49 -0
  39. package/dist/enabled-models.js +145 -0
  40. package/dist/env.d.ts +6 -0
  41. package/dist/env.js +28 -0
  42. package/dist/error-log.d.ts +64 -0
  43. package/dist/error-log.js +176 -0
  44. package/dist/force-main-model.d.ts +21 -0
  45. package/dist/force-main-model.js +28 -0
  46. package/dist/goal-bridge.d.ts +155 -0
  47. package/dist/goal-bridge.js +305 -0
  48. package/dist/group-join.d.ts +36 -0
  49. package/dist/group-join.js +161 -0
  50. package/dist/index.d.ts +52 -0
  51. package/dist/index.js +6390 -0
  52. package/dist/invocation-config.d.ts +164 -0
  53. package/dist/invocation-config.js +158 -0
  54. package/dist/memory.d.ts +53 -0
  55. package/dist/memory.js +165 -0
  56. package/dist/mention-clone.d.ts +87 -0
  57. package/dist/mention-clone.js +178 -0
  58. package/dist/mention.d.ts +81 -0
  59. package/dist/mention.js +131 -0
  60. package/dist/model-resolver.d.ts +36 -0
  61. package/dist/model-resolver.js +95 -0
  62. package/dist/model-scope.d.ts +49 -0
  63. package/dist/model-scope.js +48 -0
  64. package/dist/nested-tools.d.ts +76 -0
  65. package/dist/nested-tools.js +393 -0
  66. package/dist/output-diagnostics.d.ts +11 -0
  67. package/dist/output-diagnostics.js +64 -0
  68. package/dist/output-file.d.ts +64 -0
  69. package/dist/output-file.js +351 -0
  70. package/dist/prompts.d.ts +61 -0
  71. package/dist/prompts.js +94 -0
  72. package/dist/recovery.d.ts +56 -0
  73. package/dist/recovery.js +341 -0
  74. package/dist/report-cleanup.d.ts +204 -0
  75. package/dist/report-cleanup.js +1632 -0
  76. package/dist/report-store.d.ts +738 -0
  77. package/dist/report-store.js +3612 -0
  78. package/dist/schedule-store.d.ts +52 -0
  79. package/dist/schedule-store.js +240 -0
  80. package/dist/schedule.d.ts +121 -0
  81. package/dist/schedule.js +420 -0
  82. package/dist/settings.d.ts +388 -0
  83. package/dist/settings.js +268 -0
  84. package/dist/skill-loader.d.ts +24 -0
  85. package/dist/skill-loader.js +93 -0
  86. package/dist/standalone-fallback.d.ts +30 -0
  87. package/dist/standalone-fallback.js +239 -0
  88. package/dist/status-note.d.ts +61 -0
  89. package/dist/status-note.js +85 -0
  90. package/dist/structured-output.d.ts +61 -0
  91. package/dist/structured-output.js +112 -0
  92. package/dist/terminal-progress.d.ts +115 -0
  93. package/dist/terminal-progress.js +206 -0
  94. package/dist/types.d.ts +411 -0
  95. package/dist/types.js +5 -0
  96. package/dist/ui/agent-mention.d.ts +82 -0
  97. package/dist/ui/agent-mention.js +187 -0
  98. package/dist/ui/agent-widget.d.ts +304 -0
  99. package/dist/ui/agent-widget.js +770 -0
  100. package/dist/ui/cleanup-preview.d.ts +59 -0
  101. package/dist/ui/cleanup-preview.js +466 -0
  102. package/dist/ui/conversation-viewer.d.ts +105 -0
  103. package/dist/ui/conversation-viewer.js +544 -0
  104. package/dist/ui/fleet-list.d.ts +183 -0
  105. package/dist/ui/fleet-list.js +494 -0
  106. package/dist/ui/fleet-overlay.d.ts +203 -0
  107. package/dist/ui/fleet-overlay.js +887 -0
  108. package/dist/ui/hub-feed.d.ts +52 -0
  109. package/dist/ui/hub-feed.js +148 -0
  110. package/dist/ui/native-transcript.d.ts +33 -0
  111. package/dist/ui/native-transcript.js +234 -0
  112. package/dist/ui/schedule-menu.d.ts +16 -0
  113. package/dist/ui/schedule-menu.js +94 -0
  114. package/dist/ui/select-item.d.ts +27 -0
  115. package/dist/ui/select-item.js +34 -0
  116. package/dist/ui/tool-progress.d.ts +22 -0
  117. package/dist/ui/tool-progress.js +56 -0
  118. package/dist/ui/viewer-keys.d.ts +20 -0
  119. package/dist/ui/viewer-keys.js +17 -0
  120. package/dist/ui/workflow-card.d.ts +175 -0
  121. package/dist/ui/workflow-card.js +332 -0
  122. package/dist/ui/workflow-dialog.d.ts +305 -0
  123. package/dist/ui/workflow-dialog.js +848 -0
  124. package/dist/ui/workflow-menu.d.ts +60 -0
  125. package/dist/ui/workflow-menu.js +147 -0
  126. package/dist/usage.d.ts +147 -0
  127. package/dist/usage.js +147 -0
  128. package/dist/workflow/collisions.d.ts +95 -0
  129. package/dist/workflow/collisions.js +88 -0
  130. package/dist/workflow/entry.d.ts +32 -0
  131. package/dist/workflow/entry.js +29 -0
  132. package/dist/workflow/host.d.ts +65 -0
  133. package/dist/workflow/host.js +477 -0
  134. package/dist/workflow/journal.d.ts +113 -0
  135. package/dist/workflow/journal.js +177 -0
  136. package/dist/workflow/json-schema.d.ts +51 -0
  137. package/dist/workflow/json-schema.js +111 -0
  138. package/dist/workflow/meta.d.ts +67 -0
  139. package/dist/workflow/meta.js +317 -0
  140. package/dist/workflow/progress.d.ts +224 -0
  141. package/dist/workflow/progress.js +361 -0
  142. package/dist/workflow/runtime.d.ts +373 -0
  143. package/dist/workflow/runtime.js +919 -0
  144. package/dist/workflow/saved.d.ts +90 -0
  145. package/dist/workflow/saved.js +203 -0
  146. package/dist/workflow/task.d.ts +145 -0
  147. package/dist/workflow/task.js +213 -0
  148. package/dist/workflow/tool-description.d.ts +43 -0
  149. package/dist/workflow/tool-description.js +204 -0
  150. package/dist/workflow/worker-source.d.ts +47 -0
  151. package/dist/workflow/worker-source.js +778 -0
  152. package/dist/worktree.d.ts +52 -0
  153. package/dist/worktree.js +164 -0
  154. package/dist/xml.d.ts +10 -0
  155. package/dist/xml.js +12 -0
  156. package/docs/DEVELOPMENT.md +40 -0
  157. package/docs/artifacts.md +93 -0
  158. package/docs/recovery.md +62 -0
  159. package/docs/rpc.md +252 -0
  160. package/docs/runtime-performance.md +53 -0
  161. package/docs/workflows.md +467 -0
  162. package/examples/agent-tool-description.md +43 -0
  163. package/examples/workflows/compose.js +51 -0
  164. package/examples/workflows/fan-out-audit.js +47 -0
  165. package/examples/workflows/gated-fix.js +60 -0
  166. package/examples/workflows/lib/count-child.js +27 -0
  167. package/examples/workflows/review-panel.js +66 -0
  168. package/examples/workflows/structured-findings.js +78 -0
  169. package/package.json +75 -6
  170. package/src/abortable.ts +43 -0
  171. package/src/active-agents-prompt.ts +115 -0
  172. package/src/advisor-status.ts +74 -0
  173. package/src/agent-color.ts +169 -0
  174. package/src/agent-file-toggle.ts +273 -0
  175. package/src/agent-manager.ts +3312 -0
  176. package/src/agent-runner.ts +1500 -0
  177. package/src/agent-types.ts +390 -0
  178. package/src/awaited-result.ts +187 -0
  179. package/src/child-context.ts +173 -0
  180. package/src/child-session-shutdown.ts +114 -0
  181. package/src/cleanup-plans.ts +112 -0
  182. package/src/context.ts +58 -0
  183. package/src/cross-extension-rpc.ts +257 -0
  184. package/src/custom-agents.ts +689 -0
  185. package/src/default-agents.ts +129 -0
  186. package/src/enabled-models.ts +180 -0
  187. package/src/env.ts +33 -0
  188. package/src/error-log.ts +202 -0
  189. package/src/force-main-model.ts +29 -0
  190. package/src/goal-bridge.ts +468 -0
  191. package/src/group-join.ts +188 -0
  192. package/src/index.ts +6856 -0
  193. package/src/invocation-config.ts +276 -0
  194. package/src/memory.ts +179 -0
  195. package/src/mention-clone.ts +221 -0
  196. package/src/mention.ts +141 -0
  197. package/src/model-resolver.ts +118 -0
  198. package/src/model-scope.ts +70 -0
  199. package/src/nested-tools.ts +553 -0
  200. package/src/output-diagnostics.ts +68 -0
  201. package/src/output-file.ts +380 -0
  202. package/src/prompts.ts +151 -0
  203. package/src/recovery.ts +320 -0
  204. package/src/report-cleanup.ts +2044 -0
  205. package/src/report-store.ts +4130 -0
  206. package/src/schedule-store.ts +244 -0
  207. package/src/schedule.ts +450 -0
  208. package/src/settings.ts +632 -0
  209. package/src/skill-loader.ts +102 -0
  210. package/src/standalone-fallback.ts +195 -0
  211. package/src/status-note.ts +90 -0
  212. package/src/structured-output.ts +130 -0
  213. package/src/terminal-progress.ts +215 -0
  214. package/src/types.ts +424 -0
  215. package/src/ui/agent-mention.ts +216 -0
  216. package/src/ui/agent-widget.ts +866 -0
  217. package/src/ui/cleanup-preview.ts +518 -0
  218. package/src/ui/conversation-viewer.ts +527 -0
  219. package/src/ui/fleet-list.ts +563 -0
  220. package/src/ui/fleet-overlay.ts +1048 -0
  221. package/src/ui/hub-feed.ts +179 -0
  222. package/src/ui/native-transcript.ts +224 -0
  223. package/src/ui/schedule-menu.ts +105 -0
  224. package/src/ui/select-item.ts +45 -0
  225. package/src/ui/tool-progress.ts +67 -0
  226. package/src/ui/viewer-keys.ts +39 -0
  227. package/src/ui/workflow-card.ts +470 -0
  228. package/src/ui/workflow-dialog.ts +1119 -0
  229. package/src/ui/workflow-menu.ts +193 -0
  230. package/src/usage.ts +217 -0
  231. package/src/workflow/collisions.ts +123 -0
  232. package/src/workflow/entry.ts +47 -0
  233. package/src/workflow/host.ts +524 -0
  234. package/src/workflow/journal.ts +221 -0
  235. package/src/workflow/json-schema.ts +128 -0
  236. package/src/workflow/meta.ts +325 -0
  237. package/src/workflow/progress.ts +550 -0
  238. package/src/workflow/runtime.ts +1342 -0
  239. package/src/workflow/saved.ts +217 -0
  240. package/src/workflow/task.ts +313 -0
  241. package/src/workflow/tool-description.ts +205 -0
  242. package/src/workflow/worker-source.ts +781 -0
  243. package/src/worktree.ts +205 -0
  244. package/src/xml.ts +13 -0
package/SECURITY.md ADDED
@@ -0,0 +1,97 @@
1
+ # Security Policy
2
+
3
+ This document explains the security model behind `@timmyjl12/pi-subagents` and
4
+ where the boundaries are.
5
+
6
+ `pi-subagents` is a [pi](https://pi.dev) extension. It spawns and orchestrates
7
+ autonomous sub-agents that run locally within the same security boundary as the
8
+ user running pi, and inherit pi's trust model. It is the responsibility of the
9
+ user to monitor those agents' operations or to contain them within a container,
10
+ virtual machine, or other sandbox solution.
11
+
12
+ Sub-agents run with the local user account's privileges and can use the tools
13
+ they are granted (reading and writing files, running commands, network access,
14
+ etc.). They treat the local user account and files writable by that account as
15
+ inside the same trust boundary as the pi process itself. If an attacker can
16
+ modify files under the user's home directory, workspace, shell startup files,
17
+ environment, pi configuration, or this extension's configuration, they can
18
+ generally influence pi, its sub-agents, or other local developer tools. Reports
19
+ that depend on such prior local write access are not security vulnerabilities
20
+ unless they demonstrate how `pi-subagents` grants that write access or crosses an
21
+ operating-system privilege boundary.
22
+
23
+ `pi-subagents` relies on the user only loading trustworthy agent definitions
24
+ (`.pi/agents/*.md`, `.agents/agents/*.md`, and global agents), skills, and
25
+ tools, and only using pi within trusted repositories. Files like `AGENTS.md`,
26
+ custom agent frontmatter/system prompts, preloaded skills, or instructions
27
+ embedded in repository content and comments can be used to prompt-inject the
28
+ coding agent and its sub-agents trivially, and this cannot be protected against.
29
+
30
+ ## Reporting a Vulnerability
31
+
32
+ If you believe you found a security vulnerability in `@timmyjl12/pi-subagents`,
33
+ please report it privately to the maintainer,
34
+ [@timmyjl12](https://github.com/timmyjl12), not in a public issue. If it also
35
+ affects upstream, report it to
36
+ [tintinweb/pi-subagents](https://github.com/tintinweb/pi-subagents/security/advisories/new)
37
+ as well.
38
+
39
+ Please include:
40
+
41
+ - A description of the issue and its impact
42
+ - Steps to reproduce, proof of concept, or relevant logs
43
+ - Affected version, commit, or configuration
44
+ - Any known mitigations
45
+
46
+ Do not open a public issue for security-sensitive reports. Reports will be
47
+ reviewed and disclosure coordinated as appropriate.
48
+
49
+ ## Scope
50
+
51
+ Security issues in the published npm package and the code in this repository are
52
+ in scope — for example, a flaw in `pi-subagents` that crosses an
53
+ operating-system privilege boundary, or that causes the extension to bypass a
54
+ tool restriction, denylist, or agent boundary it claims to enforce.
55
+
56
+ ## Out Of Scope
57
+
58
+ - Local code execution or sandboxing behavior (sub-agents intentionally do not
59
+ have a sandbox and run with the user's privileges)
60
+ - Behavior of pi itself, or of other pi extensions, skills, or tools installed by
61
+ the user (report those to their respective projects)
62
+ - Risks from working in untrusted repositories
63
+ - Risks from installing or loading untrusted agent definitions, skills,
64
+ extensions, packages, or tools
65
+ - Issues caused by non-trustworthy MITM proxies
66
+ - Public internet exposure of a pi installation
67
+ - Prompt injection attacks (including via `AGENTS.md`, agent frontmatter, custom
68
+ system prompts, preloaded skills, repository content, or context inheritance)
69
+ - Exposed secrets that are third-party/user-controlled credentials
70
+ - Reports requiring the ability to create, modify, delete, or replace files,
71
+ directories, symlinks, environment variables, shell configuration, or other
72
+ user-controlled local state on the target machine. This includes `.pi/agents/`,
73
+ `.agents/agents/`, agent and extension configuration, persistent agent memory,
74
+ workspace files, `AGENTS.md`, skills, dotfiles, and files synchronized through NFS, roaming
75
+ profiles, or dotfile managers, unless the report shows how `pi-subagents`
76
+ itself grants that access.
77
+ - Issues caused by intentionally weakened user configuration
78
+ - Resource/DOS claims that require trusted local input/config
79
+ - Reports about malicious model output
80
+ - User-approved or user-initiated local actions presented as vulnerabilities
81
+
82
+ ## Notes for Reporters
83
+
84
+ The most useful reports show a current, reproducible security boundary bypass
85
+ with demonstrated impact. Reports that only show expected local-agent behavior,
86
+ prompt injection, or a malicious trusted agent definition/skill are not security
87
+ vulnerabilities under this model.
88
+
89
+ For example, a report showing that malicious contents written to a trusted agent
90
+ definition or extension configuration cause a sub-agent to execute commands, load
91
+ attacker-controlled tools, or send credentials to an attacker-controlled endpoint
92
+ is out of scope.
93
+
94
+ When possible, include the exact affected path, package version or commit SHA,
95
+ configuration, and a proof of concept against the latest release or latest
96
+ `master`. For dependency reports, include evidence that the shipped dependency is
97
+ affected and that the issue is reachable through `pi-subagents`.
@@ -0,0 +1,12 @@
1
+ /**
2
+ * abortable.ts — race a promise against an AbortSignal without cancelling the
3
+ * underlying work.
4
+ *
5
+ * Used by the `get_subagent_result` wait paths (top-level and nested): pressing
6
+ * Esc cancels only the caller's wait; the background child keeps running and its
7
+ * result stays unconsumed. The listener is removed on every settle path so the
8
+ * signal accumulates no handlers, and a late settlement of the wrapped promise
9
+ * after an abort is absorbed as a no-op (no unhandled rejection).
10
+ */
11
+ /** Await a promise until it settles or the caller cancels, without aborting the underlying work. */
12
+ export declare function abortable<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T>;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * abortable.ts — race a promise against an AbortSignal without cancelling the
3
+ * underlying work.
4
+ *
5
+ * Used by the `get_subagent_result` wait paths (top-level and nested): pressing
6
+ * Esc cancels only the caller's wait; the background child keeps running and its
7
+ * result stays unconsumed. The listener is removed on every settle path so the
8
+ * signal accumulates no handlers, and a late settlement of the wrapped promise
9
+ * after an abort is absorbed as a no-op (no unhandled rejection).
10
+ */
11
+ /** Await a promise until it settles or the caller cancels, without aborting the underlying work. */
12
+ export function abortable(promise, signal) {
13
+ if (!signal)
14
+ return promise;
15
+ if (signal.aborted)
16
+ return Promise.reject(signal.reason);
17
+ return new Promise((resolve, reject) => {
18
+ let settled = false;
19
+ const cleanup = () => signal.removeEventListener("abort", onAbort);
20
+ const onAbort = () => {
21
+ if (settled)
22
+ return;
23
+ settled = true;
24
+ cleanup();
25
+ reject(signal.reason);
26
+ };
27
+ signal.addEventListener("abort", onAbort, { once: true });
28
+ promise.then((value) => {
29
+ if (settled)
30
+ return;
31
+ settled = true;
32
+ cleanup();
33
+ resolve(value);
34
+ }, (error) => {
35
+ if (settled)
36
+ return;
37
+ settled = true;
38
+ cleanup();
39
+ reject(error);
40
+ });
41
+ });
42
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Main-session awareness of live subagents.
3
+ *
4
+ * A compact `<pi-subagents>` status message lists running/queued agents, so the
5
+ * main model can interpret "cancel that task" and choose the appropriate stop
6
+ * or steer tool.
7
+ *
8
+ * Delivered as a hidden custom message appended at the next prompt — and only
9
+ * when the list differs from the last one on the branch — rather than as a
10
+ * system-prompt section. A section edit rewrites the prompt head: providers
11
+ * without mid-conversation system messages (pi collapses them into the head)
12
+ * lose the whole cached prefix on every start and finish, and append-mode
13
+ * children inherit the volatile list through `ctx.getSystemPrompt()`. An
14
+ * appended message leaves everything already sent untouched.
15
+ */
16
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
17
+ import type { AgentRecord } from "./types.ts";
18
+ /** `customType` of the status message; `display: false` keeps it out of the TUI. */
19
+ export declare const ACTIVE_AGENTS_MESSAGE_TYPE = "subagents-active";
20
+ type ListedRecord = Pick<AgentRecord, "id" | "handle" | "alias" | "description" | "status" | "isBackground">;
21
+ /** The subset of a branch entry this module reads. */
22
+ type BranchEntry = Pick<SessionEntry, "type"> & {
23
+ id?: string;
24
+ customType?: string;
25
+ content?: unknown;
26
+ firstKeptEntryId?: string | null;
27
+ };
28
+ /**
29
+ * List text for the running/queued agents, or undefined when there are none.
30
+ * Contains only stable fields — no durations or token counts — so the text
31
+ * changes only when the set of agents or their status does.
32
+ */
33
+ export declare function buildActiveAgentsSection(records: readonly ListedRecord[]): string | undefined;
34
+ /**
35
+ * Status message content to append at this prompt, or undefined when the
36
+ * branch already carries the current list. Once agents drain, the model is
37
+ * told so exactly once; a branch that never listed any gets nothing.
38
+ */
39
+ export declare function nextActiveAgentsMessage(records: readonly ListedRecord[], branch: readonly BranchEntry[]): string | undefined;
40
+ export {};
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Main-session awareness of live subagents.
3
+ *
4
+ * A compact `<pi-subagents>` status message lists running/queued agents, so the
5
+ * main model can interpret "cancel that task" and choose the appropriate stop
6
+ * or steer tool.
7
+ *
8
+ * Delivered as a hidden custom message appended at the next prompt — and only
9
+ * when the list differs from the last one on the branch — rather than as a
10
+ * system-prompt section. A section edit rewrites the prompt head: providers
11
+ * without mid-conversation system messages (pi collapses them into the head)
12
+ * lose the whole cached prefix on every start and finish, and append-mode
13
+ * children inherit the volatile list through `ctx.getSystemPrompt()`. An
14
+ * appended message leaves everything already sent untouched.
15
+ */
16
+ /** `customType` of the status message; `display: false` keeps it out of the TUI. */
17
+ export const ACTIVE_AGENTS_MESSAGE_TYPE = "subagents-active";
18
+ /** Rows listed in the message; the rest are summarized as a count. */
19
+ const MAX_ROWS = 10;
20
+ const NONE_ACTIVE = "No subagents are running or queued now.";
21
+ /**
22
+ * List text for the running/queued agents, or undefined when there are none.
23
+ * Contains only stable fields — no durations or token counts — so the text
24
+ * changes only when the set of agents or their status does.
25
+ */
26
+ export function buildActiveAgentsSection(records) {
27
+ const active = records.filter(r => r.status === "running" || r.status === "queued");
28
+ if (active.length === 0)
29
+ return undefined;
30
+ const rows = active.slice(0, MAX_ROWS).map(r => {
31
+ const handle = r.alias ?? r.handle;
32
+ const mode = r.isBackground === false ? "foreground" : "background";
33
+ const description = r.description.replace(/\s+/g, " ").trim();
34
+ return `- ${r.id}${handle ? ` (@${handle})` : ""} — ${description} — ${r.status}, ${mode}`;
35
+ });
36
+ if (active.length > MAX_ROWS)
37
+ rows.push(`- …and ${active.length - MAX_ROWS} more`);
38
+ return [
39
+ "Subagents currently running or queued:",
40
+ ...rows,
41
+ "If the user asks to cancel/stop one of these, call stop_subagent with its id or handle; to redirect it, call steer_subagent.",
42
+ ].join("\n");
43
+ }
44
+ /**
45
+ * The branch as the model still sees it after compaction. Mirrors pi's
46
+ * `buildContextEntries`: the latest compaction entry stands in for everything
47
+ * before it, except the entries it retained (`firstKeptEntryId` onwards) and
48
+ * everything after it. A branch that is already projected — the compaction
49
+ * first — passes through unchanged.
50
+ */
51
+ function projectedBranch(branch) {
52
+ let compactionAt = -1;
53
+ for (let i = branch.length - 1; i >= 0; i--) {
54
+ if (branch[i].type === "compaction") {
55
+ compactionAt = i;
56
+ break;
57
+ }
58
+ }
59
+ if (compactionAt < 0)
60
+ return branch;
61
+ const firstKept = branch[compactionAt].firstKeptEntryId;
62
+ const keptFrom = firstKept ? branch.findIndex(entry => entry.id === firstKept) : -1;
63
+ const retained = keptFrom >= 0 && keptFrom < compactionAt ? branch.slice(keptFrom, compactionAt) : [];
64
+ return [...retained, ...branch.slice(compactionAt + 1)];
65
+ }
66
+ /** Text of the latest status message the model still has on this branch. */
67
+ function lastAnnouncement(branch) {
68
+ const visible = projectedBranch(branch);
69
+ for (let i = visible.length - 1; i >= 0; i--) {
70
+ const entry = visible[i];
71
+ if (entry.type !== "custom_message" || entry.customType !== ACTIVE_AGENTS_MESSAGE_TYPE)
72
+ continue;
73
+ if (typeof entry.content === "string")
74
+ return entry.content;
75
+ if (!Array.isArray(entry.content))
76
+ return undefined;
77
+ return entry.content
78
+ .map((part) => (part.type === "text" && typeof part.text === "string" ? part.text : ""))
79
+ .join("");
80
+ }
81
+ return undefined;
82
+ }
83
+ /**
84
+ * Status message content to append at this prompt, or undefined when the
85
+ * branch already carries the current list. Once agents drain, the model is
86
+ * told so exactly once; a branch that never listed any gets nothing.
87
+ */
88
+ export function nextActiveAgentsMessage(records, branch) {
89
+ const list = buildActiveAgentsSection(records);
90
+ const last = lastAnnouncement(branch);
91
+ const wrap = (body) => `<pi-subagents>\n${body}\n</pi-subagents>`;
92
+ if (list) {
93
+ const text = wrap(list);
94
+ return text === last ? undefined : text;
95
+ }
96
+ const idle = wrap(NONE_ACTIVE);
97
+ return last === undefined || last === idle ? undefined : idle;
98
+ }
@@ -0,0 +1,16 @@
1
+ import type { AgentSession, EventBus } from "@earendil-works/pi-coding-agent";
2
+ export interface AdvisorStatus {
3
+ state: "off" | "starting" | "idle" | "reviewing" | "paused" | "error" | "no_model" | "stopped";
4
+ models: string[];
5
+ reviews: number;
6
+ /** Epoch milliseconds of the latest successful review, not the latest advice. */
7
+ lastReviewAt?: number;
8
+ }
9
+ export declare function parseAdvisorStatus(data: unknown): AdvisorStatus | undefined;
10
+ export declare function subscribeAdvisorStatus(bus: EventBus, onStatus?: (status: AdvisorStatus) => void): () => void;
11
+ /** Keep observing after a primary run settles so resume uses the same live channel. */
12
+ export declare function attachAdvisorStatusCleanup(session: AgentSession, unsubscribe: () => void): void;
13
+ export declare function releaseAdvisorStatus(session: AgentSession): void;
14
+ export declare function formatAdvisorLastReview(status?: AdvisorStatus, now?: number): string;
15
+ export declare function formatAdvisorState(status?: AdvisorStatus): string;
16
+ export declare function formatAdvisorStatus(status?: AdvisorStatus, now?: number): string;
@@ -0,0 +1,74 @@
1
+ const STATES = ["off", "starting", "idle", "reviewing", "paused", "error", "no_model", "stopped"];
2
+ const childSubscriptions = new WeakMap();
3
+ export function parseAdvisorStatus(data) {
4
+ if (!data || typeof data !== "object")
5
+ return undefined;
6
+ const value = data;
7
+ if (typeof value.state !== "string" || !STATES.includes(value.state))
8
+ return undefined;
9
+ if (!Array.isArray(value.models) || !value.models.every(model => typeof model === "string" && !/[\u0000-\u001f\u007f-\u009f]/.test(model)))
10
+ return undefined;
11
+ if (typeof value.reviews !== "number" || !Number.isSafeInteger(value.reviews) || value.reviews < 0)
12
+ return undefined;
13
+ if (value.lastReviewAt !== undefined && (typeof value.lastReviewAt !== "number" || !Number.isFinite(value.lastReviewAt) || value.lastReviewAt < 0))
14
+ return undefined;
15
+ return {
16
+ state: value.state,
17
+ models: [...value.models],
18
+ reviews: value.reviews,
19
+ ...(typeof value.lastReviewAt === "number" ? { lastReviewAt: value.lastReviewAt } : {}),
20
+ };
21
+ }
22
+ export function subscribeAdvisorStatus(bus, onStatus) {
23
+ return bus.on("pi-advisor:status", data => {
24
+ const status = parseAdvisorStatus(data);
25
+ if (status)
26
+ onStatus?.(status);
27
+ });
28
+ }
29
+ /** Keep observing after a primary run settles so resume uses the same live channel. */
30
+ export function attachAdvisorStatusCleanup(session, unsubscribe) {
31
+ childSubscriptions.set(session, unsubscribe);
32
+ }
33
+ export function releaseAdvisorStatus(session) {
34
+ childSubscriptions.get(session)?.();
35
+ childSubscriptions.delete(session);
36
+ }
37
+ export function formatAdvisorLastReview(status, now = Date.now()) {
38
+ if (!status)
39
+ return "unavailable";
40
+ if (status.lastReviewAt === undefined)
41
+ return "never";
42
+ const seconds = Math.max(0, Math.floor((now - status.lastReviewAt) / 1000));
43
+ if (seconds < 60)
44
+ return `${seconds}s ago`;
45
+ if (seconds < 3600)
46
+ return `${Math.floor(seconds / 60)}m ago`;
47
+ return `${Math.floor(seconds / 3600)}h ago`;
48
+ }
49
+ export function formatAdvisorState(status) {
50
+ if (!status)
51
+ return "unavailable";
52
+ if (status.state === "off")
53
+ return "OFF";
54
+ if (status.state === "error")
55
+ return "ERROR";
56
+ if (status.state === "paused")
57
+ return "PAUSED";
58
+ if (status.state === "no_model")
59
+ return "no model";
60
+ return status.state;
61
+ }
62
+ export function formatAdvisorStatus(status, now = Date.now()) {
63
+ if (!status)
64
+ return "advisor: unavailable";
65
+ if (status.state === "off" && status.reviews === 0 && status.lastReviewAt === undefined)
66
+ return "advisor: OFF";
67
+ const models = status.models.map(model => model.split("/").at(-1) ?? model).join(", ");
68
+ return [
69
+ `advisor: ${formatAdvisorState(status)}`,
70
+ ...(models ? [models] : []),
71
+ `${status.reviews} review${status.reviews === 1 ? "" : "s"}`,
72
+ `last ${formatAdvisorLastReview(status, now)}`,
73
+ ].join(" · ");
74
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * agent-color.ts — Claude Code-compatible agent name badges.
3
+ *
4
+ * Claude Code renders a subagent's name as a badge: the configured color is the
5
+ * background, the text an inverse foreground. Its eight named colors are
6
+ * reproduced here, along with six-digit hex and the extra palette names Agency
7
+ * Agents uses, so those definitions render as written.
8
+ */
9
+ type ColorMode = "truecolor" | "256color";
10
+ export interface AgentNameTheme {
11
+ fg(color: string, text: string): string;
12
+ bold(text: string): string;
13
+ getColorMode?(): ColorMode;
14
+ }
15
+ export interface AgentNameStyle {
16
+ /** Existing theme foreground used when no valid agent color is configured. */
17
+ fallbackColor?: string;
18
+ /** Reapply an enclosing background after the badge instead of resetting it. */
19
+ restoreBackground?: string;
20
+ bold?: boolean;
21
+ }
22
+ /** Resolve Claude Code/Agency Agents color syntax to normalized #RRGGBB. */
23
+ export declare function resolveAgentColor(value: string | undefined): string | undefined;
24
+ /**
25
+ * Render one name as a padded background badge when `color` is valid. Claude
26
+ * Code uses one inverse color for every badge's text; black or white is picked
27
+ * by WCAG contrast here instead, so each palette entry stays readable. Invalid
28
+ * or omitted colors preserve the caller's existing theme styling.
29
+ */
30
+ export declare function renderAgentNameLabel(name: string, color: string | undefined, theme: AgentNameTheme, style?: AgentNameStyle): string;
31
+ /** Whether an agent renders as a badge — i.e. it has a valid configured color. */
32
+ export declare function hasAgentBadge(type: string | undefined): boolean;
33
+ /** Render a registered agent's display name with its configured color. */
34
+ export declare function renderAgentName(type: string | undefined, theme: AgentNameTheme, style?: AgentNameStyle): string;
35
+ export {};
@@ -0,0 +1,131 @@
1
+ /**
2
+ * agent-color.ts — Claude Code-compatible agent name badges.
3
+ *
4
+ * Claude Code renders a subagent's name as a badge: the configured color is the
5
+ * background, the text an inverse foreground. Its eight named colors are
6
+ * reproduced here, along with six-digit hex and the extra palette names Agency
7
+ * Agents uses, so those definitions render as written.
8
+ */
9
+ import { getConfig } from "./agent-types.js";
10
+ const NAMED_AGENT_COLORS = {
11
+ // Claude Code's eight subagent colors, as its default theme renders them.
12
+ red: "#DC2626",
13
+ blue: "#6A9BCC",
14
+ green: "#16A34A",
15
+ yellow: "#CA8A04",
16
+ purple: "#827DBD",
17
+ orange: "#D97757",
18
+ pink: "#C46686",
19
+ cyan: "#0891B2",
20
+ // Agency Agents palette aliases.
21
+ amber: "#F59E0B",
22
+ teal: "#008080",
23
+ indigo: "#6366F1",
24
+ gold: "#EAB308",
25
+ "neon-green": "#10B981",
26
+ "neon-cyan": "#06B6D4",
27
+ "metallic-blue": "#3B82F6",
28
+ violet: "#8B5CF6",
29
+ rose: "#F43F5E",
30
+ lime: "#84CC16",
31
+ gray: "#6B7280",
32
+ grey: "#6B7280",
33
+ fuchsia: "#D946EF",
34
+ slate: "#64748B",
35
+ navy: "#1E3A8A",
36
+ };
37
+ const CUBE_VALUES = [0, 95, 135, 175, 215, 255];
38
+ const GRAY_VALUES = Array.from({ length: 24 }, (_, i) => 8 + i * 10);
39
+ const BLACK = { r: 0, g: 0, b: 0 };
40
+ const WHITE = { r: 255, g: 255, b: 255 };
41
+ /** Resolve Claude Code/Agency Agents color syntax to normalized #RRGGBB. */
42
+ export function resolveAgentColor(value) {
43
+ if (!value)
44
+ return undefined;
45
+ const normalized = value.trim().toLowerCase();
46
+ const resolved = NAMED_AGENT_COLORS[normalized] ?? normalized;
47
+ return /^#[0-9a-f]{6}$/i.test(resolved) ? resolved.toUpperCase() : undefined;
48
+ }
49
+ function parseHex(hex) {
50
+ return {
51
+ r: Number.parseInt(hex.slice(1, 3), 16),
52
+ g: Number.parseInt(hex.slice(3, 5), 16),
53
+ b: Number.parseInt(hex.slice(5, 7), 16),
54
+ };
55
+ }
56
+ /** Index of the entry in `values` closest to `value`. */
57
+ function nearest(values, value) {
58
+ return values.reduce((best, v, i) => (Math.abs(value - v) < Math.abs(value - values[best]) ? i : best), 0);
59
+ }
60
+ /**
61
+ * Quantize to the xterm-256 palette the way pi's own theme does, returning both
62
+ * the index to emit and the color the terminal will actually show — badge
63
+ * contrast is judged against the latter.
64
+ */
65
+ function rgbTo256({ r, g, b }) {
66
+ const [rIndex, gIndex, bIndex] = [r, g, b].map((channel) => nearest(CUBE_VALUES, channel));
67
+ const distance = ({ r: cr, g: cg, b: cb }) => 0.299 * (r - cr) ** 2 + 0.587 * (g - cg) ** 2 + 0.114 * (b - cb) ** 2;
68
+ const grayIndex = nearest(GRAY_VALUES, Math.round(0.299 * r + 0.587 * g + 0.114 * b));
69
+ const gray = { r: GRAY_VALUES[grayIndex], g: GRAY_VALUES[grayIndex], b: GRAY_VALUES[grayIndex] };
70
+ const cube = { r: CUBE_VALUES[rIndex], g: CUBE_VALUES[gIndex], b: CUBE_VALUES[bIndex] };
71
+ // Only near-neutral colors may take the gray ramp; anything else keeps its tint.
72
+ if (Math.max(r, g, b) - Math.min(r, g, b) < 10 && distance(gray) < distance(cube)) {
73
+ return { index: 232 + grayIndex, rgb: gray };
74
+ }
75
+ return { index: 16 + 36 * rIndex + 6 * gIndex + bIndex, rgb: cube };
76
+ }
77
+ function ansiColor(layer, color) {
78
+ const code = layer === "foreground" ? 38 : 48;
79
+ return typeof color === "number"
80
+ ? `\u001b[${code};5;${color}m`
81
+ : `\u001b[${code};2;${color.r};${color.g};${color.b}m`;
82
+ }
83
+ function relativeLuminance({ r, g, b }) {
84
+ const linear = (value) => {
85
+ const channel = value / 255;
86
+ return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
87
+ };
88
+ return 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);
89
+ }
90
+ /**
91
+ * Render one name as a padded background badge when `color` is valid. Claude
92
+ * Code uses one inverse color for every badge's text; black or white is picked
93
+ * by WCAG contrast here instead, so each palette entry stays readable. Invalid
94
+ * or omitted colors preserve the caller's existing theme styling.
95
+ */
96
+ export function renderAgentNameLabel(name, color, theme, style = {}) {
97
+ const resolved = resolveAgentColor(color);
98
+ if (!resolved) {
99
+ const text = style.bold ? theme.bold(name) : name;
100
+ return style.fallbackColor ? theme.fg(style.fallbackColor, text) : text;
101
+ }
102
+ const rgb = parseHex(resolved);
103
+ const quantized = (theme.getColorMode?.() ?? "truecolor") === "256color" ? rgbTo256(rgb) : undefined;
104
+ const shown = quantized?.rgb ?? rgb;
105
+ const contrasting = relativeLuminance(shown) > 0.179 ? BLACK : WHITE;
106
+ const label = style.bold ? theme.bold(` ${name} `) : ` ${name} `;
107
+ return ansiColor("background", quantized?.index ?? rgb)
108
+ + ansiColor("foreground", quantized ? rgbTo256(contrasting).index : contrasting)
109
+ + label
110
+ + "\u001b[39m"
111
+ + (style.restoreBackground ?? "\u001b[49m");
112
+ }
113
+ /** Whether an agent renders as a badge — i.e. it has a valid configured color. */
114
+ export function hasAgentBadge(type) {
115
+ return type !== undefined && resolveAgentColor(getConfig(type).color) !== undefined;
116
+ }
117
+ /** Render a registered agent's display name with its configured color. */
118
+ export function renderAgentName(type, theme, style = {}) {
119
+ if (!type)
120
+ return renderAgentNameLabel("Agent", undefined, theme, style);
121
+ const config = getConfig(type);
122
+ // displayName is user-authored config free text. Every caller feeds the
123
+ // result to a terminal ROW; a control byte here must not break the row.
124
+ // ANSI styling is added by renderAgentNameLabel after this flattening.
125
+ const displayName = config.displayName.replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g, " ")
126
+ .replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, " ")
127
+ .replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ")
128
+ .replace(/\s+/g, " ")
129
+ .trim();
130
+ return renderAgentNameLabel(displayName || type, config.color, theme, style);
131
+ }