pi-agent-swarm 0.0.0 → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +240 -2
- package/dist/chunks/chunk-77JHO3GV.ts +144 -0
- package/dist/chunks/chunk-77JHO3GV.ts.map +7 -0
- package/dist/chunks/menu-RH6GY6U4.ts +119 -0
- package/dist/chunks/menu-RH6GY6U4.ts.map +7 -0
- package/dist/index.ts +4092 -0
- package/dist/index.ts.map +7 -0
- package/package.json +54 -2
- package/src/color.ts +129 -0
- package/src/external.ts +150 -0
- package/src/footer.ts +63 -0
- package/src/i3-workspace.ts +281 -0
- package/src/index.ts +1 -0
- package/src/launch-envelope.ts +124 -0
- package/src/launcher.ts +93 -0
- package/src/menu.ts +131 -0
- package/src/pi-agent-swarm.ts +173 -0
- package/src/pi-invocation.ts +144 -0
- package/src/protocol.ts +766 -0
- package/src/reload-handoff.ts +33 -0
- package/src/renderer.ts +30 -0
- package/src/runtime-directory.ts +249 -0
- package/src/settings.ts +369 -0
- package/src/swarm-controller.ts +1353 -0
- package/src/terminal.ts +54 -0
- package/src/text.ts +42 -0
- package/src/tools.ts +275 -0
- package/src/transport-io.ts +155 -0
- package/src/transport.ts +939 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 narumiruna
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,241 @@
|
|
|
1
|
-
#
|
|
1
|
+
# 🚀 Pi Agent Swarm — Launch and Connect Local Pi Sessions
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/pi-agent-swarm) [](https://pi.dev) [](./LICENSE)
|
|
4
|
+
|
|
5
|
+
Launch another Pi process in an external terminal window without replacing the current session.
|
|
6
|
+
You can also connect trusted local Pi sessions for bounded notifications and one-turn requests.
|
|
7
|
+
Every agent is a real terminal window tiled by your window manager — never a headless child process.
|
|
8
|
+
|
|
9
|
+
## ✨ Features
|
|
10
|
+
|
|
11
|
+
- Opens a distinct Pi process in an external terminal window while preserving the parent session.
|
|
12
|
+
- Pins each new window to the lead session's workspace instead of the focused one.
|
|
13
|
+
- Inherits the cwd, model, thinking level, and optional first task after launch review.
|
|
14
|
+
- Waits for the child to authenticate before reporting that the new session is ready.
|
|
15
|
+
- Connects explicitly joined same-user sessions through owner-only local sockets and ephemeral invites.
|
|
16
|
+
- Delivers notifications without a model turn and bounds each allowed request to one turn.
|
|
17
|
+
- Relays user input from a worker window into the leader's model context.
|
|
18
|
+
- Shows a colored footer badge with the session name, id, and role, degrading through full, compact, and minimal tiers as the terminal narrows.
|
|
19
|
+
- Authenticates and bounds local protocol traffic, peers, retries, rates, deadlines, and diagnostics.
|
|
20
|
+
- Cleans all sockets, launchers, tasks, timers, and status on leave, reload, replacement, or shutdown.
|
|
21
|
+
|
|
22
|
+
## 📦 Install
|
|
23
|
+
|
|
24
|
+
Install persistently:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pi install npm:pi-agent-swarm
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Try the published package without a permanent install:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pi -e npm:pi-agent-swarm
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Build and load the extension from a local checkout:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
npm --workspace pi-agent-swarm run build
|
|
40
|
+
pi --no-extensions --no-skills --no-session -e ./packages/pi-agent-swarm
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
The package declares `dist/index.ts`, so an unbuilt local checkout must run the build before Pi loads the package directory.
|
|
44
|
+
A child started in any terminal uses normal Pi extension discovery.
|
|
45
|
+
Install Pi Agent Swarm persistently to test spawn-and-auto-join because the child does not inherit the parent's temporary `-e` argument.
|
|
46
|
+
|
|
47
|
+
Pi extensions execute with your user permissions.
|
|
48
|
+
Review extension source before installing it.
|
|
49
|
+
|
|
50
|
+
## 🚀 Quick start
|
|
51
|
+
|
|
52
|
+
Run `/swarm` to open the menu and spawn a worker Pi session, rename this session, or change its footer color.
|
|
53
|
+
Start a local group with `/swarm start`, then ask your model to launch a child session with the `session_spawn` tool; the child joins the group automatically.
|
|
54
|
+
Before creating a window, Pi Agent Swarm asks for the configured launch confirmation.
|
|
55
|
+
|
|
56
|
+
## 🧭 Launch flow
|
|
57
|
+
|
|
58
|
+
Edit `pi-agent-swarm.json` to change final launch confirmation or toggle lead-workspace pinning.
|
|
59
|
+
New windows are launched through the configured external terminal command.
|
|
60
|
+
|
|
61
|
+
After any configured launch confirmation, Pi Agent Swarm:
|
|
62
|
+
|
|
63
|
+
1. Creates or reuses an ephemeral local group.
|
|
64
|
+
2. Starts the external terminal command.
|
|
65
|
+
3. Starts a separate named Pi process in the selected cwd.
|
|
66
|
+
4. Waits for the child to authenticate and report readiness.
|
|
67
|
+
5. Sends the optional first task through a launch-specific one-time kickoff.
|
|
68
|
+
|
|
69
|
+
If the terminal creates a window but the child does not become ready, Pi Agent Swarm reports a partial launch.
|
|
70
|
+
It leaves the visible window open instead of closing a potentially useful process.
|
|
71
|
+
|
|
72
|
+
## 🛠️ Tools
|
|
73
|
+
|
|
74
|
+
### `session_spawn`
|
|
75
|
+
|
|
76
|
+
Creates a separate Pi process in an external terminal window.
|
|
77
|
+
|
|
78
|
+
| Parameter | Required | Description |
|
|
79
|
+
| --- | --- | --- |
|
|
80
|
+
| `direction` | No | `right`, `down`, `left`, or `up`; defaults to `right`. |
|
|
81
|
+
| `task` | No | First task sent only after authenticated readiness. |
|
|
82
|
+
| `name` | No | Child session display name. |
|
|
83
|
+
| `color` | No | Child color: a palette name or a `#rrggbb` hex. |
|
|
84
|
+
| `model` | No | Child model as `provider/id`; defaults to inheriting the current session model. |
|
|
85
|
+
| `cwd` | No | Existing directory; defaults to the current cwd. |
|
|
86
|
+
|
|
87
|
+
The tool supports only TUI and RPC modes because launch may require confirmation.
|
|
88
|
+
In JSON and print modes, it fails before creating a group, launcher, or window.
|
|
89
|
+
Successful details include `terminalId` and `terminalVersion`.
|
|
90
|
+
|
|
91
|
+
### `session_bus`
|
|
92
|
+
|
|
93
|
+
Lists or messages sessions in the active Pi Agent Swarm group.
|
|
94
|
+
|
|
95
|
+
| Action | Fields | Behavior |
|
|
96
|
+
| --- | --- | --- |
|
|
97
|
+
| `list` | none | Lists authenticated live peers and request policy. |
|
|
98
|
+
| `send` | `targetSessionId`, `message`, optional `mode` | Sends `notify` by default or a permitted one-turn `request`. |
|
|
99
|
+
| `reply` | `targetSessionId`, `message`, `replyTo` | Correlates a reply without starting another automatic turn. |
|
|
100
|
+
| `shutdown` | `targetSessionId` | Asks a peer to shut down gracefully. |
|
|
101
|
+
|
|
102
|
+
An accepted acknowledgement means the recipient extension accepted or deduplicated the message, not that the remote agent completed the work.
|
|
103
|
+
Rejected and busy acknowledgements use stable codes such as `requests_disabled`, `rate_limited`, `target_busy`, `shutdown_unauthorized`, and `delivery_failed`.
|
|
104
|
+
Rate-limited responses may include a bounded retry delay.
|
|
105
|
+
Peer-list text and details share a 40 KiB UTF-8 result budget below Pi's tool-output limit.
|
|
106
|
+
|
|
107
|
+
## 💬 Commands
|
|
108
|
+
|
|
109
|
+
| Command | Purpose |
|
|
110
|
+
| --- | --- |
|
|
111
|
+
| `/swarm` | Open the menu to spawn a worker, rename this session, or set its color. |
|
|
112
|
+
| `/swarm start` | Start a local group with this session as lead. |
|
|
113
|
+
| `/swarm <piagentswarm:v1:invite>` | Review the join confirmation and join one ephemeral local group. |
|
|
114
|
+
| `/lead` | Promote a session to leader or inspect the current leader. |
|
|
115
|
+
| `/color` | Set the current session's footer color. |
|
|
116
|
+
|
|
117
|
+
All routes support TUI and RPC, reject unknown or trailing arguments, and fail in print or JSON mode before opening sockets.
|
|
118
|
+
Review the [launch flow](#-launch-flow) and [Security and privacy](#-security-and-privacy): accepted peer requests can start paid model turns.
|
|
119
|
+
|
|
120
|
+
## 🏷️ Footer badge
|
|
121
|
+
|
|
122
|
+
Each window shows a footer badge with its swarm color, session name, session id, and role (LEADER/WORKER).
|
|
123
|
+
The badge never wraps and never drops the role; it degrades through three tiers as the terminal narrows, re-rendering on resize:
|
|
124
|
+
|
|
125
|
+
- **FULL**: name + full session id + role, when the badge fits within 55% of the terminal columns.
|
|
126
|
+
- **COMPACT**: name truncated with an ellipsis + 8-column id prefix + role. The prefix is a first-class identifier shared by `MANAGER-<prefix>` naming and `/lead` prefix matching, so it carries no ellipsis.
|
|
127
|
+
- **MINIMAL**: swarm-colored dot + role. The full identity stays available in the `/swarm` menu and message envelopes.
|
|
128
|
+
|
|
129
|
+
## 🖥️ External terminal backend
|
|
130
|
+
|
|
131
|
+
Pi Agent Swarm launches each session as a plain terminal window through a configurable command (default `alacritty -e`).
|
|
132
|
+
The window manager — any tiling window manager — decides where the window appears.
|
|
133
|
+
|
|
134
|
+
When `pinToLeadWorkspace` is enabled, Pi Agent Swarm snapshots the window tree before creating the window, locates the lead session's workspace by walking the process tree to the terminal's `_NET_WM_PID`, and moves the new window onto that workspace as soon as it appears.
|
|
135
|
+
Placement is best-effort: if the window manager cannot move the window, it stays where it was placed.
|
|
136
|
+
|
|
137
|
+
## ⚙️ Settings
|
|
138
|
+
|
|
139
|
+
Edit user settings in `<getAgentDir()>/pi-agent-swarm.json`, normally `~/.pi/agent/pi-agent-swarm.json`:
|
|
140
|
+
|
|
141
|
+
```json
|
|
142
|
+
{
|
|
143
|
+
"colorPalette": "muted",
|
|
144
|
+
"externalCommand": "alacritty -e",
|
|
145
|
+
"confirmSessionLaunch": true,
|
|
146
|
+
"pinToLeadWorkspace": false
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
| Setting | Values | Default | Behavior |
|
|
151
|
+
| --- | --- | --- | --- |
|
|
152
|
+
| `colorPalette` | `muted`, `bright` | `muted` | Roster badge palette derived from GitHub Linguist language colors: `muted` is the low-saturation set whose yellow matches the ROLE badge, `bright` is GitHub's original vivid set. Both share slot order, so a session keeps its hue when the palette switches. Switch live with `/swarm` → **Set theme** (persisted to this file) or edit the value directly and `/reload`. |
|
|
153
|
+
| `externalCommand` | any terminal command | `alacritty -e` | Command used to open each new window. |
|
|
154
|
+
| `confirmSessionLaunch` | `true`, `false` | `true` | Shows or skips the final launch preview for tool launches. |
|
|
155
|
+
| `pinToLeadWorkspace` | `true`, `false` | `false` | Moves each new window onto the lead session's workspace instead of the focused one. |
|
|
156
|
+
|
|
157
|
+
Pi Agent Swarm does not read project settings or extension-specific environment-variable overrides.
|
|
158
|
+
A missing file uses the defaults without creating the file.
|
|
159
|
+
Writes preserve unknown fields, run in order within one Pi process, and publish atomically through a private temporary file and rename.
|
|
160
|
+
Malformed or invalid files are reported and never overwritten.
|
|
161
|
+
Separate Pi processes do not share a settings lock, so do not edit this file concurrently from multiple sessions.
|
|
162
|
+
A change takes effect on the next session start or `/reload`.
|
|
163
|
+
|
|
164
|
+
Group secrets, request permission, peers, readiness state, and deduplication state stay in memory.
|
|
165
|
+
The `piagentswarm:v1` prefix versions the bearer-invite encoding separately from the version-3 socket protocol.
|
|
166
|
+
Version-3 messages normally expire after two minutes and cannot declare a lifetime longer than five minutes.
|
|
167
|
+
Accepted message ids remain deduplicated for ten minutes, longer than their valid delivery window.
|
|
168
|
+
A copied invite is still a reusable bearer secret, so discard it or start a new group when you need to rotate access.
|
|
169
|
+
A short-lived in-process handoff preserves a group across `/reload` for the same `sessionManager` only.
|
|
170
|
+
Membership does not carry into `/new`, `/resume`, or another logical session without a new invite.
|
|
171
|
+
|
|
172
|
+
The terminal child receives an internal launch-only environment envelope containing a parent-only kickoff capability.
|
|
173
|
+
The child consumes and deletes those values during `session_start` before Pi tools can inherit them.
|
|
174
|
+
These values are not user settings or supported environment overrides.
|
|
175
|
+
|
|
176
|
+
Incoming agent requests are blocked by default.
|
|
177
|
+
Enabling them permits trusted invite holders to start paid model turns that may edit the same workspace concurrently.
|
|
178
|
+
|
|
179
|
+
## 🔒 Security and privacy
|
|
180
|
+
|
|
181
|
+
- Runtime directories are owned by the current user and restricted to `0700`, which is the portable filesystem access boundary.
|
|
182
|
+
- Endpoint manifests and Unix sockets are restricted to `0600` as additional platform-specific defense in depth.
|
|
183
|
+
- Discovery ignores symlinks, non-regular files, oversized manifests, wrong owners, malformed records, endpoint filename mismatches, and incompatible versions.
|
|
184
|
+
- Discovery scans at most 512 directory entries, accepts at most 64 valid manifests, probes at most 16 peers concurrently, and finishes under one overall deadline.
|
|
185
|
+
- Invalid manifests do not consume the valid-peer quota, and bounded non-secret diagnostics distinguish saturation, conflicts, protocol failures, deadlines, and unreachable peers.
|
|
186
|
+
- Every manifest, request, and response is authenticated for its group and endpoint instance.
|
|
187
|
+
Frames also bind the logical target, claimed sender, clock window, nonce, and request id.
|
|
188
|
+
- The shared group MAC proves possession of the bearer invite, not a separate cryptographic identity for each peer.
|
|
189
|
+
- A trusted invite holder can claim another session id, so session and endpoint labels are collaboration hints rather than a separate authorization boundary.
|
|
190
|
+
- Launch kickoffs also require a random capability shared only through the parent-to-child launch envelope.
|
|
191
|
+
It is not published through peer discovery or persisted with delivered messages.
|
|
192
|
+
- Two simultaneously live endpoints claiming one session id are omitted from discovery and rejected as an explicit identity conflict.
|
|
193
|
+
- Bearer invites are consumed only from direct join input or the parent-to-child launch envelope.
|
|
194
|
+
- Pi Agent Swarm does not retain invites as durable settings or group state, but a recipient can copy and reuse one until every holder discards it or moves to a new group.
|
|
195
|
+
- Invites are not placed in tool output, status, notifications, custom renderers, or model context.
|
|
196
|
+
- Launch values briefly exist in a private `0700` launcher that unlinks itself before starting Pi, so terminal command metadata cannot retain them.
|
|
197
|
+
- Peer names, paths, messages, model ids, and errors are treated as untrusted terminal text and sanitized only at display boundaries.
|
|
198
|
+
- A same-user process or another privileged Pi extension is outside the security boundary and may inspect process arguments, private runtime files, memory, or environment.
|
|
199
|
+
- Pi Agent Swarm separates groups but does not sandbox them from the operating-system user.
|
|
200
|
+
|
|
201
|
+
## 🚧 Limitations
|
|
202
|
+
|
|
203
|
+
- Local same-user communication only.
|
|
204
|
+
- POSIX Unix-socket transport only.
|
|
205
|
+
- No LAN, internet, cross-user, remote-host, or public-room transport.
|
|
206
|
+
- No daemon, offline mailbox, separate Swarm history, delivery receipt, global ordering, or exactly-once guarantee.
|
|
207
|
+
- No automatic trust or discovery of every Pi process.
|
|
208
|
+
- No automatic close of a window after partial child startup.
|
|
209
|
+
- Protocol version 3 intentionally rejects version-1 and version-2 manifests and frames.
|
|
210
|
+
- One request uses one short-lived socket connection; there is no persistent multiplexed channel or delivery stream.
|
|
211
|
+
- Server connections use an absolute request deadline rather than an activity-reset timeout, and at most eight message deliveries run concurrently.
|
|
212
|
+
- Per-sender and endpoint-wide rate limits are fixed windows, so a busy response can require waiting before retrying.
|
|
213
|
+
- Old orphan temporary files, private launchers, and sockets are removed after a grace period.
|
|
214
|
+
Empty private group directories may remain to avoid cross-process startup races.
|
|
215
|
+
- No tab, window, resize, focus-navigation, or general layout manager.
|
|
216
|
+
- Multiple Pi sessions can still race while editing the same workspace.
|
|
217
|
+
|
|
218
|
+
## 🗂️ Package layout
|
|
219
|
+
|
|
220
|
+
```text
|
|
221
|
+
packages/pi-agent-swarm/
|
|
222
|
+
├── src/ # Authoritative implementation and helpers
|
|
223
|
+
│ ├── index.ts # Thin Pi entrypoint
|
|
224
|
+
│ ├── pi-agent-swarm.ts # Local session launch and messaging
|
|
225
|
+
│ ├── footer.ts # Width-adaptive roster badge (full/compact/minimal)
|
|
226
|
+
│ └── i3-workspace.ts # Lead-workspace window pinning
|
|
227
|
+
├── dist/ # Generated Jiti runtime
|
|
228
|
+
├── scripts/build-runtime.mjs # Runtime builder
|
|
229
|
+
└── test/ # Behavior and lifecycle coverage
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
The generated runtime is built from `src/index.ts` and does not import back into `src`.
|
|
233
|
+
|
|
234
|
+
## 🔎 Keywords
|
|
235
|
+
|
|
236
|
+
Pi extension, Pi Agent Swarm, Pi sessions, external terminal, tiling window manager, local agents, agent communication, Unix socket, TypeScript.
|
|
237
|
+
|
|
238
|
+
## 📄 License
|
|
239
|
+
|
|
240
|
+
MIT.
|
|
241
|
+
See [`LICENSE`](./LICENSE).
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// @generated by scripts/build-runtime.mjs; do not edit.
|
|
2
|
+
// @ts-nocheck -- the generated entry uses a .ts extension for Pi's Jiti loader.
|
|
3
|
+
|
|
4
|
+
// src/text.ts
|
|
5
|
+
function safeTerminalText(value) {
|
|
6
|
+
let output = "";
|
|
7
|
+
for (const character of value) {
|
|
8
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
9
|
+
if (isTerminalControl(codePoint)) continue;
|
|
10
|
+
output += character === " " ? " " : character;
|
|
11
|
+
}
|
|
12
|
+
return output;
|
|
13
|
+
}
|
|
14
|
+
function safeTerminalLine(value) {
|
|
15
|
+
return safeTerminalText(value).replace(/[\r\n]+/gu, " ").trim();
|
|
16
|
+
}
|
|
17
|
+
function safeError(error) {
|
|
18
|
+
return safeTerminalLine(error instanceof Error ? error.message : String(error));
|
|
19
|
+
}
|
|
20
|
+
function normalizeOptionalText(value, label, maxBytes) {
|
|
21
|
+
if (value === void 0) return void 0;
|
|
22
|
+
const normalized = value.trim();
|
|
23
|
+
if (!normalized) return void 0;
|
|
24
|
+
if (normalized.includes("\0") || Buffer.byteLength(normalized) > maxBytes) {
|
|
25
|
+
throw new Error(`Pi Agent Swarm ${label} is invalid or too large`);
|
|
26
|
+
}
|
|
27
|
+
return normalized;
|
|
28
|
+
}
|
|
29
|
+
function isTerminalControl(codePoint) {
|
|
30
|
+
return codePoint >= 0 && codePoint <= 8 || codePoint === 11 || codePoint === 12 || codePoint === 13 || codePoint >= 14 && codePoint <= 31 || codePoint >= 127 && codePoint <= 159 || codePoint >= 8234 && codePoint <= 8238 || codePoint >= 8294 && codePoint <= 8297;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// src/color.ts
|
|
34
|
+
import { getTerminalColorMode, parseColor, styleText } from "@earendil-works/pi-tui";
|
|
35
|
+
var SWARM_COLOR_PALETTES = {
|
|
36
|
+
muted: [
|
|
37
|
+
{ name: "red", hex: "#c22d40" },
|
|
38
|
+
// Scala
|
|
39
|
+
{ name: "orange", hex: "#b07219" },
|
|
40
|
+
// Java
|
|
41
|
+
{ name: "yellow", hex: "#ffc85a" },
|
|
42
|
+
// matches ROLE_BADGE_BACKGROUND in footer.ts
|
|
43
|
+
{ name: "green", hex: "#41b883" },
|
|
44
|
+
// Vue
|
|
45
|
+
{ name: "cyan", hex: "#4298b8" },
|
|
46
|
+
// Groovy
|
|
47
|
+
{ name: "blue", hex: "#3178c6" },
|
|
48
|
+
// TypeScript
|
|
49
|
+
{ name: "magenta", hex: "#b83998" },
|
|
50
|
+
// Erlang
|
|
51
|
+
{ name: "purple", hex: "#8847b9" }
|
|
52
|
+
// Elixir
|
|
53
|
+
],
|
|
54
|
+
bright: [
|
|
55
|
+
{ name: "red", hex: "#db5855" },
|
|
56
|
+
// Clojure
|
|
57
|
+
{ name: "orange", hex: "#dea584" },
|
|
58
|
+
// Rust
|
|
59
|
+
{ name: "yellow", hex: "#f1e05a" },
|
|
60
|
+
// JavaScript
|
|
61
|
+
{ name: "green", hex: "#89e051" },
|
|
62
|
+
// Shell
|
|
63
|
+
{ name: "cyan", hex: "#00add8" },
|
|
64
|
+
// Go
|
|
65
|
+
{ name: "blue", hex: "#3572a5" },
|
|
66
|
+
// Python
|
|
67
|
+
{ name: "magenta", hex: "#f34b7d" },
|
|
68
|
+
// C++
|
|
69
|
+
{ name: "purple", hex: "#a97bff" }
|
|
70
|
+
// Kotlin
|
|
71
|
+
]
|
|
72
|
+
};
|
|
73
|
+
var SWARM_COLORS = SWARM_COLOR_PALETTES.muted;
|
|
74
|
+
var LEGACY_SWARM_COLORS = [
|
|
75
|
+
{ name: "red", hex: "#ef4444" },
|
|
76
|
+
{ name: "orange", hex: "#f97316" },
|
|
77
|
+
{ name: "yellow", hex: "#eab308" },
|
|
78
|
+
{ name: "green", hex: "#22c55e" },
|
|
79
|
+
{ name: "cyan", hex: "#06b6d4" },
|
|
80
|
+
{ name: "blue", hex: "#3b82f6" },
|
|
81
|
+
{ name: "magenta", hex: "#d946ef" },
|
|
82
|
+
{ name: "purple", hex: "#8b5cf6" }
|
|
83
|
+
];
|
|
84
|
+
function swarmColorPalette(name) {
|
|
85
|
+
return SWARM_COLOR_PALETTES[name];
|
|
86
|
+
}
|
|
87
|
+
var HEX_RE = /^#[0-9a-f]{6}$/u;
|
|
88
|
+
var HEX_TO_NAME = /* @__PURE__ */ new Map();
|
|
89
|
+
for (const palette of [SWARM_COLOR_PALETTES.muted, SWARM_COLOR_PALETTES.bright, LEGACY_SWARM_COLORS]) {
|
|
90
|
+
for (const color of palette) {
|
|
91
|
+
if (!HEX_TO_NAME.has(color.hex)) HEX_TO_NAME.set(color.hex, color.name);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
function normalizeSwarmColor(value, palette = SWARM_COLORS) {
|
|
95
|
+
if (typeof value !== "string") return void 0;
|
|
96
|
+
const trimmed = value.trim().toLowerCase();
|
|
97
|
+
const named = palette.find((color) => color.name === trimmed);
|
|
98
|
+
if (named) return named.hex;
|
|
99
|
+
if (HEX_RE.test(trimmed)) return trimmed;
|
|
100
|
+
return void 0;
|
|
101
|
+
}
|
|
102
|
+
function pickSwarmColor(seed, palette = SWARM_COLORS) {
|
|
103
|
+
let hash = 0;
|
|
104
|
+
for (let i = 0; i < seed.length; i += 1) hash = hash * 31 + seed.charCodeAt(i) >>> 0;
|
|
105
|
+
return palette[hash % palette.length].hex;
|
|
106
|
+
}
|
|
107
|
+
function swarmColorName(hex) {
|
|
108
|
+
return HEX_TO_NAME.get(hex.toLowerCase());
|
|
109
|
+
}
|
|
110
|
+
function contrastTextColor(bgHex) {
|
|
111
|
+
const match = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/u.exec(bgHex.toLowerCase());
|
|
112
|
+
if (!match) return "#ffffff";
|
|
113
|
+
const [r, g, b] = match.slice(1).map((pair) => Number.parseInt(pair, 16));
|
|
114
|
+
const channel = (value) => {
|
|
115
|
+
const s = value / 255;
|
|
116
|
+
return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
|
|
117
|
+
};
|
|
118
|
+
const luminance = 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
|
|
119
|
+
const onBlack = (luminance + 0.05) / 0.05;
|
|
120
|
+
const onWhite = 1.05 / (luminance + 0.05);
|
|
121
|
+
return onBlack >= onWhite ? "#000000" : "#ffffff";
|
|
122
|
+
}
|
|
123
|
+
function badge(text, bgHex, fgHex) {
|
|
124
|
+
try {
|
|
125
|
+
return styleText(text, { fg: parseColor(fgHex), bg: parseColor(bgHex) }, getTerminalColorMode());
|
|
126
|
+
} catch {
|
|
127
|
+
return text;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export {
|
|
132
|
+
safeTerminalText,
|
|
133
|
+
safeTerminalLine,
|
|
134
|
+
safeError,
|
|
135
|
+
normalizeOptionalText,
|
|
136
|
+
SWARM_COLORS,
|
|
137
|
+
swarmColorPalette,
|
|
138
|
+
normalizeSwarmColor,
|
|
139
|
+
pickSwarmColor,
|
|
140
|
+
swarmColorName,
|
|
141
|
+
contrastTextColor,
|
|
142
|
+
badge
|
|
143
|
+
};
|
|
144
|
+
//# sourceMappingURL=chunk-77JHO3GV.ts.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/text.ts", "../../src/color.ts"],
|
|
4
|
+
"sourcesContent": ["export function safeTerminalText(value: string): string {\n let output = \"\";\n for (const character of value) {\n const codePoint = character.codePointAt(0) ?? 0;\n if (isTerminalControl(codePoint)) continue;\n output += character === \"\\t\" ? \" \" : character;\n }\n return output;\n}\n\nexport function safeTerminalLine(value: string): string {\n return safeTerminalText(value)\n .replace(/[\\r\\n]+/gu, \" \")\n .trim();\n}\n\nexport function safeError(error: unknown): string {\n return safeTerminalLine(error instanceof Error ? error.message : String(error));\n}\n\nexport function normalizeOptionalText(value: string | undefined, label: string, maxBytes: number): string | undefined {\n if (value === undefined) return undefined;\n const normalized = value.trim();\n if (!normalized) return undefined;\n if (normalized.includes(\"\\0\") || Buffer.byteLength(normalized) > maxBytes) {\n throw new Error(`Pi Agent Swarm ${label} is invalid or too large`);\n }\n return normalized;\n}\n\nfunction isTerminalControl(codePoint: number): boolean {\n return (\n (codePoint >= 0x00 && codePoint <= 0x08) ||\n codePoint === 0x0b ||\n codePoint === 0x0c ||\n codePoint === 0x0d ||\n (codePoint >= 0x0e && codePoint <= 0x1f) ||\n (codePoint >= 0x7f && codePoint <= 0x9f) ||\n (codePoint >= 0x202a && codePoint <= 0x202e) ||\n (codePoint >= 0x2066 && codePoint <= 0x2069)\n );\n}\n", "import { getTerminalColorMode, parseColor, styleText } from \"@earendil-works/pi-tui\";\n\nexport interface SwarmColor {\n name: string;\n hex: string;\n}\n\nexport type SwarmColorPaletteName = \"muted\" | \"bright\";\n\n/**\n * Roster palettes derived from GitHub Linguist language colors (the language bar on\n * github.com), one language per hue slot (see scripts/color-draft.mjs for the visual\n * draft). `muted` is the default low-saturation set; its yellow deliberately matches\n * the footer's ROLE badge (ROLE_BADGE_BACKGROUND) so a yellow session reads as one\n * warm block. `bright` keeps the same slots at GitHub's original vivid tones. Both\n * palettes share slot order, so a seed or stored name keeps its hue when the\n * `colorPalette` setting switches.\n */\nexport const SWARM_COLOR_PALETTES: Record<SwarmColorPaletteName, readonly SwarmColor[]> = {\n muted: [\n { name: \"red\", hex: \"#c22d40\" }, // Scala\n { name: \"orange\", hex: \"#b07219\" }, // Java\n { name: \"yellow\", hex: \"#ffc85a\" }, // matches ROLE_BADGE_BACKGROUND in footer.ts\n { name: \"green\", hex: \"#41b883\" }, // Vue\n { name: \"cyan\", hex: \"#4298b8\" }, // Groovy\n { name: \"blue\", hex: \"#3178c6\" }, // TypeScript\n { name: \"magenta\", hex: \"#b83998\" }, // Erlang\n { name: \"purple\", hex: \"#8847b9\" }, // Elixir\n ],\n bright: [\n { name: \"red\", hex: \"#db5855\" }, // Clojure\n { name: \"orange\", hex: \"#dea584\" }, // Rust\n { name: \"yellow\", hex: \"#f1e05a\" }, // JavaScript\n { name: \"green\", hex: \"#89e051\" }, // Shell\n { name: \"cyan\", hex: \"#00add8\" }, // Go\n { name: \"blue\", hex: \"#3572a5\" }, // Python\n { name: \"magenta\", hex: \"#f34b7d\" }, // C++\n { name: \"purple\", hex: \"#a97bff\" }, // Kotlin\n ],\n};\n\n/** Default roster palette: the muted GitHub-derived set. */\nexport const SWARM_COLORS: readonly SwarmColor[] = SWARM_COLOR_PALETTES.muted;\n\n/**\n * Pre-palette Tailwind colors. Kept only so hexes assigned by older versions still\n * resolve to a palette name in labels; never used for new assignments.\n */\nconst LEGACY_SWARM_COLORS: readonly SwarmColor[] = [\n { name: \"red\", hex: \"#ef4444\" },\n { name: \"orange\", hex: \"#f97316\" },\n { name: \"yellow\", hex: \"#eab308\" },\n { name: \"green\", hex: \"#22c55e\" },\n { name: \"cyan\", hex: \"#06b6d4\" },\n { name: \"blue\", hex: \"#3b82f6\" },\n { name: \"magenta\", hex: \"#d946ef\" },\n { name: \"purple\", hex: \"#8b5cf6\" },\n];\n\n/** The palette behind a `colorPalette` setting value. */\nexport function swarmColorPalette(name: SwarmColorPaletteName): readonly SwarmColor[] {\n return SWARM_COLOR_PALETTES[name];\n}\n\nconst HEX_RE = /^#[0-9a-f]{6}$/u;\nconst HEX_TO_NAME = new Map<string, string>();\nfor (const palette of [SWARM_COLOR_PALETTES.muted, SWARM_COLOR_PALETTES.bright, LEGACY_SWARM_COLORS]) {\n for (const color of palette) {\n if (!HEX_TO_NAME.has(color.hex)) HEX_TO_NAME.set(color.hex, color.name);\n }\n}\n\n/** Accept a palette name or a #rrggbb hex; return a normalized #rrggbb hex, or undefined. */\nexport function normalizeSwarmColor(value: unknown, palette: readonly SwarmColor[] = SWARM_COLORS): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim().toLowerCase();\n const named = palette.find((color) => color.name === trimmed);\n if (named) return named.hex;\n if (HEX_RE.test(trimmed)) return trimmed;\n return undefined;\n}\n\n/** Deterministic palette color from a seed string (stable, no coordination needed). */\nexport function pickSwarmColor(seed: string, palette: readonly SwarmColor[] = SWARM_COLORS): string {\n let hash = 0;\n for (let i = 0; i < seed.length; i += 1) hash = (hash * 31 + seed.charCodeAt(i)) >>> 0;\n return palette[hash % palette.length].hex;\n}\n\n/** Palette name for a hex, or undefined when the hex is off-palette. */\nexport function swarmColorName(hex: string): string | undefined {\n return HEX_TO_NAME.get(hex.toLowerCase());\n}\n\n/** Wrap text in a foreground color escape sequence (ANSI), best-effort. */\nexport function colorize(text: string, hex: string): string {\n try {\n return styleText(text, { fg: parseColor(hex) }, getTerminalColorMode());\n } catch {\n return text;\n }\n}\n\n/**\n * Pick black or white text for a filled badge on the given background, using WCAG\n * relative luminance so the choice is measured rather than eyeballed.\n */\nexport function contrastTextColor(bgHex: string): string {\n const match = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/u.exec(bgHex.toLowerCase());\n if (!match) return \"#ffffff\";\n const [r, g, b] = match.slice(1).map((pair) => Number.parseInt(pair, 16));\n const channel = (value: number): number => {\n const s = value / 255;\n return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;\n };\n const luminance = 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);\n const onBlack = (luminance + 0.05) / 0.05;\n const onWhite = 1.05 / (luminance + 0.05);\n return onBlack >= onWhite ? \"#000000\" : \"#ffffff\";\n}\n\n/** Wrap text in a filled badge (background with an explicit foreground), best-effort. */\nexport function badge(text: string, bgHex: string, fgHex: string): string {\n try {\n return styleText(text, { fg: parseColor(fgHex), bg: parseColor(bgHex) }, getTerminalColorMode());\n } catch {\n return text;\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;AAAO,SAAS,iBAAiB,OAAuB;AACtD,MAAI,SAAS;AACb,aAAW,aAAa,OAAO;AAC7B,UAAM,YAAY,UAAU,YAAY,CAAC,KAAK;AAC9C,QAAI,kBAAkB,SAAS,EAAG;AAClC,cAAU,cAAc,MAAO,SAAS;AAAA,EAC1C;AACA,SAAO;AACT;AAEO,SAAS,iBAAiB,OAAuB;AACtD,SAAO,iBAAiB,KAAK,EAC1B,QAAQ,aAAa,GAAG,EACxB,KAAK;AACV;AAEO,SAAS,UAAU,OAAwB;AAChD,SAAO,iBAAiB,iBAAiB,QAAQ,MAAM,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AI,KAAK,QAAQ,KAAK,EAAG,QAAQ,OAAO,KAAK,KAAK,WAAW,CAAC,MAAO;AACrF,SAAO,QAAQ,OAAO,QAAQ,MAAM,EAAE;AACxC;AAGO,SAAS,eAAe,KAAiC;AAC9D,SAAO,YAAY,IAAI,IAAI,YAAY,CAAC;AAC1C;AAeO,SAAS,kBAAkB,OAAuB;AACvD,QAAM,QAAQ,8CAA8C,KAAK,MAAM,YAAY,CAAC;AACpF,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,CAAC,GAAG,GAAG,CAAC,IAAI,MAAM,MAAM,CAAC,EAAE,IAAI,CAAC,SAAS,OAAO,SAAS,MAAM,EAAE,CAAC;AACxE,QAAM,UAAU,CAAC,UAA0B;AACzC,UAAM,IAAI,QAAQ;AAClB,WAAO,KAAK,UAAU,IAAI,UAAU,IAAI,SAAS,UAAU;AAAA,EAC7D;AACA,QAAM,YAAY,SAAS,QAAQ,CAAC,IAAI,SAAS,QAAQ,CAAC,IAAI,SAAS,QAAQ,CAAC;AAChF,QAAM,WAAW,YAAY,QAAQ;AACrC,QAAM,UAAU,QAAQ,YAAY;AACpC,SAAO,WAAW,UAAU,YAAY;AAC1C;AAGO,SAAS,MAAM,MAAc,OAAe,OAAuB;AACxE,MAAI;AACF,WAAO,UAAU,MAAM,EAAE,IAAI,WAAW,KAAK,GAAG,IAAI,WAAW,KAAK,EAAE,GAAG,qBAAqB,CAAC;AAAA,EACjG,QAAQ;AACN,WAAO;AAAA,EACT;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// @generated by scripts/build-runtime.mjs; do not edit.
|
|
2
|
+
// @ts-nocheck -- the generated entry uses a .ts extension for Pi's Jiti loader.
|
|
3
|
+
import {
|
|
4
|
+
SWARM_COLORS,
|
|
5
|
+
safeError
|
|
6
|
+
} from "./chunk-77JHO3GV.ts";
|
|
7
|
+
|
|
8
|
+
// src/menu.ts
|
|
9
|
+
var DIRECTION_OPTIONS = ["Right", "Down", "Left", "Up"];
|
|
10
|
+
var PALETTE_OPTIONS = [
|
|
11
|
+
{ label: "muted (default, low-saturation GitHub colors)", value: "muted" },
|
|
12
|
+
{ label: "bright (vivid GitHub colors)", value: "bright" }
|
|
13
|
+
];
|
|
14
|
+
function createSwarmMenu(source) {
|
|
15
|
+
const getState = ({ signal } = {}) => source.snapshot(signal);
|
|
16
|
+
const menu = {
|
|
17
|
+
start: "main",
|
|
18
|
+
screens: {
|
|
19
|
+
main: () => ({
|
|
20
|
+
kind: "actions",
|
|
21
|
+
title: "Pi Agent Swarm",
|
|
22
|
+
lines: ["Spawn workers and manage this session's badge."],
|
|
23
|
+
items: [
|
|
24
|
+
{
|
|
25
|
+
id: "spawn",
|
|
26
|
+
label: "Spawn",
|
|
27
|
+
action: "spawn"
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
id: "rename",
|
|
31
|
+
label: "Rename",
|
|
32
|
+
action: "rename"
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
id: "color",
|
|
36
|
+
label: "Set color",
|
|
37
|
+
action: "setColor"
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
id: "theme",
|
|
41
|
+
label: "Set theme",
|
|
42
|
+
action: "setTheme"
|
|
43
|
+
}
|
|
44
|
+
],
|
|
45
|
+
hint: "close"
|
|
46
|
+
})
|
|
47
|
+
},
|
|
48
|
+
actions: {
|
|
49
|
+
spawn: async ({ ctx, signal }) => {
|
|
50
|
+
const directionChoice = await ctx.ui.select("Terminal window direction", [...DIRECTION_OPTIONS], {
|
|
51
|
+
signal
|
|
52
|
+
});
|
|
53
|
+
if (!directionChoice || signal.aborted) return { kind: "stay" };
|
|
54
|
+
const task = await ctx.ui.input("Optional first task", "Submit an empty value for an idle child session", {
|
|
55
|
+
signal
|
|
56
|
+
});
|
|
57
|
+
if (task === void 0 || signal.aborted) return { kind: "stay" };
|
|
58
|
+
await source.spawn(
|
|
59
|
+
ctx,
|
|
60
|
+
{
|
|
61
|
+
direction: directionChoice.toLowerCase(),
|
|
62
|
+
...task ? { task } : {}
|
|
63
|
+
},
|
|
64
|
+
signal
|
|
65
|
+
);
|
|
66
|
+
return { kind: "close" };
|
|
67
|
+
},
|
|
68
|
+
rename: async ({ ctx, signal, state }) => {
|
|
69
|
+
const name = await ctx.ui.input("Rename session", state.self?.name ?? "Enter a new session name", {
|
|
70
|
+
signal
|
|
71
|
+
});
|
|
72
|
+
if (name === void 0 || !name.trim() || signal.aborted) return { kind: "stay" };
|
|
73
|
+
await source.rename(ctx, name, signal);
|
|
74
|
+
return { kind: "stay" };
|
|
75
|
+
},
|
|
76
|
+
setColor: async ({ ctx, signal }) => {
|
|
77
|
+
const choice = await ctx.ui.select("Session color", [...SWARM_COLORS.map((color) => color.name)], {
|
|
78
|
+
signal
|
|
79
|
+
});
|
|
80
|
+
if (!choice || signal.aborted) return { kind: "stay" };
|
|
81
|
+
await source.setColor(ctx, choice, signal);
|
|
82
|
+
return { kind: "stay" };
|
|
83
|
+
},
|
|
84
|
+
setTheme: async ({ ctx, signal }) => {
|
|
85
|
+
const choice = await ctx.ui.select(
|
|
86
|
+
"Roster theme (badge palette)",
|
|
87
|
+
PALETTE_OPTIONS.map((option) => option.label),
|
|
88
|
+
{ signal }
|
|
89
|
+
);
|
|
90
|
+
if (!choice || signal.aborted) return { kind: "stay" };
|
|
91
|
+
const palette = PALETTE_OPTIONS.find((option) => option.label === choice)?.value;
|
|
92
|
+
if (!palette) return { kind: "stay" };
|
|
93
|
+
await source.setPalette(ctx, palette, signal);
|
|
94
|
+
return { kind: "stay" };
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
return { menu, getState };
|
|
99
|
+
}
|
|
100
|
+
async function showSwarmMenu(ctx, source, ownership) {
|
|
101
|
+
const { runMenu } = await import("@narumitw/pi-tui-kit");
|
|
102
|
+
if (ownership.signal.aborted || !ownership.isCurrent()) return;
|
|
103
|
+
const controller = createSwarmMenu(source);
|
|
104
|
+
await runMenu(ctx, controller.menu, {
|
|
105
|
+
getState: controller.getState,
|
|
106
|
+
signal: ownership.signal,
|
|
107
|
+
isCurrent: ownership.isCurrent,
|
|
108
|
+
onError: (_ctx, error) => {
|
|
109
|
+
if (ownership.isCurrent() && !ownership.signal.aborted) {
|
|
110
|
+
ctx.ui.notify(`Pi Agent Swarm failed: ${safeError(error)}`, "error");
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
export {
|
|
116
|
+
createSwarmMenu,
|
|
117
|
+
showSwarmMenu
|
|
118
|
+
};
|
|
119
|
+
//# sourceMappingURL=menu-RH6GY6U4.ts.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/menu.ts"],
|
|
4
|
+
"sourcesContent": ["import type { ExtensionCommandContext } from \"@earendil-works/pi-coding-agent\";\nimport type { MenuDefinition } from \"@narumitw/pi-tui-kit\";\nimport { SWARM_COLORS, type SwarmColorPaletteName } from \"./color.js\";\nimport type { SpawnSessionInput, SwarmSnapshot } from \"./swarm-controller.js\";\nimport { safeError } from \"./text.js\";\n\nexport interface SwarmMenuState extends SwarmSnapshot {}\n\nexport interface SwarmMenuSource {\n snapshot(signal?: AbortSignal): Promise<SwarmMenuState>;\n spawn(ctx: ExtensionCommandContext, input: SpawnSessionInput, signal?: AbortSignal): Promise<void>;\n rename(ctx: ExtensionCommandContext, name: string, signal?: AbortSignal): Promise<void>;\n setColor(ctx: ExtensionCommandContext, color: string, signal?: AbortSignal): Promise<void>;\n setPalette(ctx: ExtensionCommandContext, palette: SwarmColorPaletteName, signal?: AbortSignal): Promise<void>;\n}\n\ntype Screen = \"main\";\ntype Action = \"spawn\" | \"rename\" | \"setColor\" | \"setTheme\";\n\nconst DIRECTION_OPTIONS = [\"Right\", \"Down\", \"Left\", \"Up\"] as const;\nconst PALETTE_OPTIONS = [\n { label: \"muted (default, low-saturation GitHub colors)\", value: \"muted\" },\n { label: \"bright (vivid GitHub colors)\", value: \"bright\" },\n] as const satisfies readonly { label: string; value: SwarmColorPaletteName }[];\n\nexport function createSwarmMenu(source: SwarmMenuSource) {\n const getState = ({ signal }: { signal?: AbortSignal } = {}) => source.snapshot(signal);\n const menu: MenuDefinition<SwarmMenuState, Screen, Action> = {\n start: \"main\",\n screens: {\n main: () => ({\n kind: \"actions\",\n title: \"Pi Agent Swarm\",\n lines: [\"Spawn workers and manage this session's badge.\"],\n items: [\n {\n id: \"spawn\",\n label: \"Spawn\",\n action: \"spawn\",\n },\n {\n id: \"rename\",\n label: \"Rename\",\n action: \"rename\",\n },\n {\n id: \"color\",\n label: \"Set color\",\n action: \"setColor\",\n },\n {\n id: \"theme\",\n label: \"Set theme\",\n action: \"setTheme\",\n },\n ],\n hint: \"close\",\n }),\n },\n actions: {\n spawn: async ({ ctx, signal }) => {\n const directionChoice = await ctx.ui.select(\"Terminal window direction\", [...DIRECTION_OPTIONS], {\n signal,\n });\n if (!directionChoice || signal.aborted) return { kind: \"stay\" };\n const task = await ctx.ui.input(\"Optional first task\", \"Submit an empty value for an idle child session\", {\n signal,\n });\n if (task === undefined || signal.aborted) return { kind: \"stay\" };\n await source.spawn(\n ctx,\n {\n direction: directionChoice.toLowerCase() as SpawnSessionInput[\"direction\"],\n ...(task ? { task } : {}),\n },\n signal,\n );\n return { kind: \"close\" };\n },\n rename: async ({ ctx, signal, state }) => {\n const name = await ctx.ui.input(\"Rename session\", state.self?.name ?? \"Enter a new session name\", {\n signal,\n });\n if (name === undefined || !name.trim() || signal.aborted) return { kind: \"stay\" };\n await source.rename(ctx, name, signal);\n return { kind: \"stay\" };\n },\n setColor: async ({ ctx, signal }) => {\n const choice = await ctx.ui.select(\"Session color\", [...SWARM_COLORS.map((color) => color.name)], {\n signal,\n });\n if (!choice || signal.aborted) return { kind: \"stay\" };\n await source.setColor(ctx, choice, signal);\n return { kind: \"stay\" };\n },\n setTheme: async ({ ctx, signal }) => {\n const choice = await ctx.ui.select(\n \"Roster theme (badge palette)\",\n PALETTE_OPTIONS.map((option) => option.label),\n { signal },\n );\n if (!choice || signal.aborted) return { kind: \"stay\" };\n const palette = PALETTE_OPTIONS.find((option) => option.label === choice)?.value;\n if (!palette) return { kind: \"stay\" };\n await source.setPalette(ctx, palette, signal);\n return { kind: \"stay\" };\n },\n },\n };\n return { menu, getState };\n}\n\nexport async function showSwarmMenu(\n ctx: ExtensionCommandContext,\n source: SwarmMenuSource,\n ownership: { signal: AbortSignal; isCurrent(): boolean },\n): Promise<void> {\n const { runMenu } = await import(\"@narumitw/pi-tui-kit\");\n if (ownership.signal.aborted || !ownership.isCurrent()) return;\n const controller = createSwarmMenu(source);\n await runMenu(ctx, controller.menu, {\n getState: controller.getState,\n signal: ownership.signal,\n isCurrent: ownership.isCurrent,\n onError: (_ctx, error) => {\n if (ownership.isCurrent() && !ownership.signal.aborted) {\n ctx.ui.notify(`Pi Agent Swarm failed: ${safeError(error)}`, \"error\");\n }\n },\n });\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;AAmBA,IAAM,oBAAoB,CAAC,SAAS,QAAQ,QAAQ,IAAI;AACxD,IAAM,kBAAkB;AAAA,EACtB,EAAE,OAAO,iDAAiD,OAAO,QAAQ;AAAA,EACzE,EAAE,OAAO,gCAAgC,OAAO,SAAS;AAC3D;AAEO,SAAS,gBAAgB,QAAyB;AACvD,QAAM,WAAW,CAAC,EAAE,OAAO,IAA8B,CAAC,MAAM,OAAO,SAAS,MAAM;AACtF,QAAM,OAAuD;AAAA,IAC3D,OAAO;AAAA,IACP,SAAS;AAAA,MACP,MAAM,OAAO;AAAA,QACX,MAAM;AAAA,QACN,OAAO;AAAA,QACP,OAAO,CAAC,gDAAgD;AAAA,QACxD,OAAO;AAAA,UACL;AAAA,YACE,IAAI;AAAA,YACJ,OAAO;AAAA,YACP,QAAQ;AAAA,UACV;AAAA,UACA;AAAA,YACE,IAAI;AAAA,YACJ,OA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