pi-team-mode 0.1.3 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  Team Mode puts a Team Lead in the foreground and runs useful work in background Pi workers. Engineer is on by default in the interactive TUI. Its stock Lead coordinates workers individually—no meetings. This is profile behavior, not an Engineer-specific permission rule. A routine fix can use one worker to investigate, edit and verify; larger jobs use dependencies and parallel workers as needed.
4
4
 
5
+ **0.1.6** adds live worker models to **Status**, remembers the selected profile per Pi session, and shows live scheduler counts in the footer. **0.1.5** introduced padded role badges and removed the duplicate queue acknowledgement. **0.1.4** was not published to npm.
6
+
5
7
  **0.1.3** adds personal profiles, template-based creation, and a Team Mode menu. As in **0.1.2**, compatible stock subagents show Team role badges and task briefs in the native Agents rows. Team generates definitions on first dispatch; SDK-only installs still work without stock subagents.
6
8
 
7
9
  ## Install
@@ -16,9 +18,21 @@ On fresh TUI startup, an unpinned, Pi-managed install from the official GitHub r
16
18
 
17
19
  Use `pi update npm:pi-team-mode` for npm installs or `pi update git:github.com/flaminigo/pi-team-mode` for GitHub installs to update just Team Mode, then `/reload` or restart Pi. Run it from the trusted project for project-scoped installs (`--approve` if trust isn’t saved). On Pi 1.7, `pi update --extensions` updates all packages and `pi update` updates Pi itself; `pi upgrade --extensions` is not valid. For this nested local checkout, rebuild after changing source, then reload. If `pi list` already shows the repository root, `/reload` or a restart reads the working-tree TypeScript without a build or reinstall. To switch sources, remove the old source in its original scope before installing the checkout.
18
20
 
21
+ Open `/team` → **Status** or run `/team status` for the same read-only view. It keeps the selected profile, on/off or blocked state, and task IDs and states (including settled tasks). The **Live workers** section lists queued, starting, and running Team jobs on either backend, showing the configured role, task ID, brief preview, and the exact `provider/model-id` once the worker starts. Before then it shows `pending` (with the pin if explicit), or `inherits foreground at start` when the queued job is set to inherit. Use ↑/↓ or `j`/`k` to scroll and Esc to close. Opening the view does not make model requests. The dispatch transcript still shows only the padded role badge, brief and `background` for each task; the Lead still receives the original queue result.
22
+
19
23
  With stock `@tintinweb/pi-subagents` 0.26.3, Team creates real Markdown definitions on first dispatch, including for configured profiles and roles. The native **Agents** row shows the role badge (red Validator) and the brief. The worker receives the current role prompt instead of inheriting Lead's. Team keeps the definitions in `<Pi agent directory>/team-mode-workers/` with flat namespaced links `agents/pi-team-mode-worker-<profile>-<role>-<unique-id>.md`. Stock 0.26.3 reads only direct `*.md` children in personal `agents/`, workspace `.agents/agents/` and project `.pi/agents/`, and in package manifest-declared directories. Manifest-declared individual nested files are supported, not recursive discovery. Team keeps its existing flat registrations and does not create package manifests or change stock discovery settings. It reuses matching Team-owned definitions without rewriting them. Changed content or a name collision gets a new identity; existing definitions are left intact. Team does not change stock settings or clean up generated definitions on uninstall.
20
24
 
21
- Explicit tool allowlists, SDK continuations, and unavailable native definitions use Pi SDK child sessions without an Agents row. Model and thinking settings do not by themselves change routes on a compatible build. SDK workers use core tools, not foreground extensions. The adapter uses a compact handoff when upstream cannot resume a finished job; SDK sessions can continue a handful of recent tasks. `/team doctor` reports backend availability, not exact definition resolution. Stock RPC cannot verify definition ownership or disable fallback per call. Team checks for existing claims before dispatch and reports a mismatched run type, but stock cannot guarantee safety against a concurrent file change.
25
+ **Extension-registered models:** Stock 0.26.3 inherits the foreground Pi model runtime. Except for Cursor (below), SDK workers replay only the selected provider's Pi registration (including its stream/auth callbacks) in their own runtime; they use Pi's normal auth configuration and do not reload extensions or copy session-only credentials. This supports providers whose registrations work without child extension lifecycle hooks. Team reports an unregistered provider, an unlisted model, or an unavailable model without choosing a substitute.
26
+
27
+ Explicit tool allowlists, SDK continuations, and unavailable native definitions use Pi SDK child sessions without an Agents row. Except for Cursor, model and thinking settings do not by themselves change routes on a compatible build. SDK workers use core Pi tools, not foreground extensions. The adapter uses a compact handoff when upstream cannot resume a finished job; SDK sessions can continue a handful of recent tasks. `/team doctor` reports backend availability, not exact definition resolution. Stock RPC cannot verify definition ownership or disable fallback per call. Team checks for existing claims before dispatch and reports a mismatched run type, but stock cannot guarantee safety against a concurrent file change.
28
+
29
+ ### Cursor workers
30
+
31
+ To use a Cursor model for an unrestricted role, select its exact `cursor/<model-id>` in `/team model` or in that role’s model pool. Team requires `npm:pi-cursor-sdk` to be enabled, installed, and configured in Pi’s user settings or in a project Pi has trusted. Team does not install it, accept a task-supplied extension path, or reload unrelated extensions. The selected model must be in the worker’s own Cursor catalog and usable with Pi’s configured Cursor authentication. Team does not fall back to another model.
32
+
33
+ Cursor workers always use the Pi SDK, even with stock subagents available. Each worker owns its Cursor extension binding and model runtime; cancellation and recent-task continuation work through Team. These workers appear in Team’s dispatch and results, **not** in the native **Agents** hierarchy. Compatibility with `pi-cursor-sdk` 0.5.32 was verified offline without real auth or Cursor requests.
34
+
35
+ Cursor’s native tools and ambient MCP configuration are separate from Pi’s tool list. Team fails closed for roles with an explicit `access.tools` allowlist rather than running a Cursor worker that could exceed it. In a project Pi does not trust, start Pi with `PI_CURSOR_SETTING_SOURCES=none` to prevent Cursor from loading ambient settings. Team does not change Cursor settings or process environment for you.
22
36
 
23
37
  ## Use
24
38
 
@@ -29,11 +43,15 @@ Explicit tool allowlists, SDK continuations, and unavailable native definitions
29
43
  - `/team config edit [project]`, `/team config validate`, `/team config reload`.
30
44
  - **Configure role model** or `/team model` opens a role picker, then an available-model picker; `/team model <role>` opens just the latter. `/team model <role> <provider/model-id>` (or configured alias) adds an available model to the role's pool and selects it for the next worker run (or switches the foreground Lead now, if Team Mode is on). Usage is tracked locally for five-entry pool eviction. Menus, pickers, and config editing do not prompt outside the TUI.
31
45
 
46
+ The last explicitly selected profile is remembered in the current Pi session and restored on `/reload` or resume against the latest configuration. A new session, or one whose selected profile is no longer available, uses the configured default. Pi does not create a session file until there is a user or assistant message; `--no-session` choices stay in memory. The on/off setting for a reopened session still comes from config. Jobs and worker activity are not restored or replayed.
47
+
48
+ The footer shows the active profile and live counts: queued, starting, confirmed running, stopping, and outcomes. Outcome counts stay until you reset, change profiles, reload, or turn Team Mode off. Only SDK-reported Pi tools contribute to the optional `using tools` count. Stock RPC reports its lifecycle without guessing at tool use or thinking; neither backend infers thinking from model settings.
49
+
32
50
  Team Mode ships a read-only catalog: `engineer_template`, `research_template`, `audit_template`. These IDs are for copying, not switching. On interactive activation (including `/reload`), Team saves only missing personal `engineer`, `research`, and `audit` profiles as JSON in `<Pi agent directory>/team-mode-profiles/`. Saved profiles are full copies; inline personal entries (including sparse ones) count as existing profiles and are never rewritten by seeding. The effective order is built-in fallback → full personal files by ID → inline `team-mode.json` → trusted `.pi/team-mode.json`. Personal files do not inherit later template changes. If a starter file is removed and no inline entry exists, the next interactive activation backfills it again.
33
51
 
34
52
  Seed and create require valid personal settings on their own and as merged in the current workspace. Create refuses existing runnable IDs, including trusted project IDs, and never copies merged project settings. IDs for new files are 1–64 lowercase letters, digits, underscores or hyphens, starting with a letter or digit. Writes use a complete temporary file and atomic no-replace publication; if the filesystem cannot publish it, Team reports the problem and does not replace existing files. Read-only loading and validation do not seed. To customize a saved profile, edit its full `<id>.json` or overlay its fields inline, then use `/team config validate` and `/team config reload`.
35
53
 
36
- For example, run `/team profile create my-engineering --from engineer_template`, then `/team profile my-engineering` as a separate command. The footer says `Team: Engineer` until you change `name` to `My Engineering` in `<Pi agent directory>/team-mode-profiles/my-engineering.json`. In that same file, try setting `roles.validator.workScope` to `Verify the personal My Engineering profile.` Run `/team config validate` and `/team config reload` to apply the edit and see `Team: My Engineering`. The copy is still available after `/reload`; switch to it again unless you have set it as your default. Creating it again with the same ID leaves the edited file untouched.
54
+ For example, run `/team profile create my-engineering --from engineer_template`, then `/team profile my-engineering` as a separate command. The footer says `Team: Engineer` until you change `name` to `My Engineering` in `<Pi agent directory>/team-mode-profiles/my-engineering.json`. In that same file, try setting `roles.validator.workScope` to `Verify the personal My Engineering profile.` Run `/team config validate` and `/team config reload` to apply the edit and see `Team: My Engineering`. Team restores this selection after `/reload` or resume using the latest profile file. Creating it again with the same ID leaves the edited file untouched.
37
55
 
38
56
  User settings live in `<Pi agent directory>/team-mode.json`; trusted project overrides live in `.pi/team-mode.json`. To add a profile, define a new ID under `profiles` with a `name` and `roles` containing an enabled `lead`. To add a role, define a new ID under that profile’s `roles` with `name` and `workScope`. Use `/team profile <id>` to switch or set `defaultProfile` to use it at startup; see the [custom profile example](https://github.com/flaminigo/pi-team-mode#create-profiles-and-roles). Example override for built-in roles:
39
57
 
@@ -77,8 +95,10 @@ npm pack --dry-run # preview release contents; does not publish
77
95
 
78
96
  Pack releases from this nested directory with `npm pack` (without `--ignore-scripts`). The `prepack` hook builds the extension and copies the repository-root `LICENSE` verbatim into the npm package; the root file is the source of truth.
79
97
 
80
- After publication, run `python3 test/pi-smoke.py npm:pi-team-mode <version>` to check the actual npm install and version in a disposable Pi home. The package install uses the npm registry, but the TUI and worker use only the loopback fake model.
98
+ Before publication, run `python3 test/npm-tarball-smoke.py /path/to/pi-team-mode-0.1.6.tgz` to serve the exact MIT tarball from a loopback npm registry. After publication, run `python3 test/pi-smoke.py npm:pi-team-mode <version>` to check the actual npm install and version in a disposable Pi home. The package install uses the npm registry, but the TUI and worker use only the loopback fake model.
99
+
100
+ To exercise the native Agents rows, set `PI_TEAM_TEST_SUBAGENTS` to the absolute path of an unmodified local `@tintinweb/pi-subagents` 0.26.3 package before running `npm run test:pi`. The PTY uses fake loopback models and checks both Status entry points, no extra inference, live model and settled summary updates, profile seeding, the `/team` menu (template copy and switch, role-model picker and toggle), CLI help and input errors, the `my-engineering` CLI create, edit, reload and no-clobber workflow, first-dispatch definition creation, reuse after `/reload`, Engineer, Research and My Engineering Validator rows (red, no suffix, plain brief), exact profile prompt/model/thinking/tools, and an ordinary `Agent (twin)` launched with the stock Agent tool. From the repository root, run `python3 pi-team-mode/test/pi-smoke.py --git-mirror .` to test the committed `main` via a private temporary Git mirror and a mocked GitHub response. Local-source smoke runs also check that the Research worker uses an extension-only loopback provider without reloading the provider extension, with or without stock subagents. All smoke paths use a disposable Pi config and fake credentials.
81
101
 
82
- To exercise the native Agents rows, set `PI_TEAM_TEST_SUBAGENTS` to the absolute path of an unmodified local `@tintinweb/pi-subagents` 0.26.3 package before running `npm run test:pi`. The PTY uses fake loopback models and checks profile seeding, the `/team` menu (template copy and switch, role-model picker and toggle), CLI help and input errors, the `my-engineering` CLI create, edit, reload and no-clobber workflow, first-dispatch definition creation, reuse after `/reload`, Engineer, Research and My Engineering Validator rows (red, no suffix, plain brief), exact profile prompt/model/thinking/tools, and an ordinary `Agent (twin)` launched with the stock Agent tool. From the repository root, run `python3 pi-team-mode/test/pi-smoke.py --git-mirror .` to test the committed `main` via a private temporary Git mirror and a mocked GitHub response. All smoke paths use a disposable Pi config and fake credentials.
102
+ To check Cursor ownership offline with Node 24, build and run `PI_TEAM_TEST_CURSOR=/absolute/path/to/installed/pi-cursor-sdk node --test test/cursor-worker.test.mjs`. The fixture expects 0.5.32, uses a disposable Pi home and fake credential, and stubs the Cursor SDK and network transport. It leaves the real Cursor extension registration, ownership guard, and session hooks in place.
83
103
 
84
104
  To check discovery itself, run `python3 test/stock-agent-probe.py "$PI_TEAM_TEST_SUBAGENTS"` and repeat with `--strict-fallback`. Stock discovers a late flat file and an explicitly manifest-declared nested file, but does not discover nested files just because their parent’s parent was scanned.
package/dist/backend.js CHANGED
@@ -1,10 +1,13 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { createAgentSession, DefaultResourceLoader, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
2
+ import { join } from 'node:path';
3
+ import { createAgentSession, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
4
+ import { checkCursorWorkerPolicy, closeCursorWorker, createCursorWorker } from './cursor-worker.js';
3
5
  export class NativeBackend {
4
6
  cwd;
5
7
  agentDir;
6
8
  retained = new Map();
7
9
  running = new Set();
10
+ pending = new Set();
8
11
  closed = false;
9
12
  constructor(cwd, agentDir) {
10
13
  this.cwd = cwd;
@@ -14,11 +17,21 @@ export class NativeBackend {
14
17
  const prior = this.retained.get(token);
15
18
  return !!prior && prior.role === role && prior.model === model && prior.tools === JSON.stringify(tools);
16
19
  }
17
- async run(work, signal) {
20
+ run(work, signal, foreground, projectTrusted = false) {
21
+ const pending = this.runSession(work, signal, foreground, projectTrusted);
22
+ this.pending.add(pending);
23
+ const settled = () => { this.pending.delete(pending); };
24
+ void pending.then(settled, settled);
25
+ return pending;
26
+ }
27
+ async runSession(work, signal, foreground, projectTrusted) {
18
28
  signal.throwIfAborted();
19
29
  if (this.closed)
20
30
  throw Error('Worker backend closed');
21
31
  const model = `${work.model.provider}/${work.model.id}`;
32
+ const cursor = work.model.provider === 'cursor';
33
+ if (cursor)
34
+ checkCursorWorkerPolicy(work, projectTrusted);
22
35
  const tools = JSON.stringify(work.tools);
23
36
  const prior = work.resume ? this.retained.get(work.resume) : undefined;
24
37
  let session;
@@ -26,13 +39,17 @@ export class NativeBackend {
26
39
  this.retained.delete(work.resume);
27
40
  session = prior.session;
28
41
  }
42
+ else if (cursor) {
43
+ session = await createCursorWorker(this.cwd, this.agentDir, projectTrusted, work, signal);
44
+ }
29
45
  else {
30
46
  const settingsManager = SettingsManager.inMemory({ retry: { enabled: true, maxRetries: 1 } });
31
47
  const resourceLoader = new DefaultResourceLoader({ cwd: this.cwd, agentDir: this.agentDir, settingsManager,
32
48
  noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true });
33
49
  await resourceLoader.reload();
34
50
  signal.throwIfAborted();
35
- ({ session } = await createAgentSession({ cwd: this.cwd, agentDir: this.agentDir, model: work.model,
51
+ const modelRuntime = await workerModelRuntime(this.agentDir, foreground, work.model, signal);
52
+ ({ session } = await createAgentSession({ cwd: this.cwd, agentDir: this.agentDir, model: work.model, modelRuntime,
36
53
  thinkingLevel: work.thinkingLevel, tools: work.tools, sessionManager: SessionManager.inMemory(this.cwd), settingsManager, resourceLoader }));
37
54
  }
38
55
  this.running.add(session);
@@ -48,21 +65,55 @@ export class NativeBackend {
48
65
  }
49
66
  if (session === prior?.session && work.thinkingLevel !== undefined)
50
67
  session.setThinkingLevel(work.thinkingLevel);
68
+ const actual = session.model;
69
+ if (actual?.provider !== work.model.provider || actual.id !== work.model.id) {
70
+ throw Error(`Worker session did not select the exact model ${model}.`);
71
+ }
51
72
  const start = session.messages.length;
52
- work.started();
53
- await session.prompt(work.prompt, { expandPromptTemplates: false });
73
+ const activeTools = new Set();
74
+ let started = false;
75
+ const unsubscribe = session.subscribe(event => {
76
+ if (event.type === 'agent_start' && !started && !signal.aborted) {
77
+ started = true;
78
+ work.started(actual);
79
+ }
80
+ if (event.type !== 'tool_execution_start' && event.type !== 'tool_execution_end')
81
+ return;
82
+ const wasActive = activeTools.size > 0;
83
+ if (event.type === 'tool_execution_start')
84
+ activeTools.add(event.toolCallId);
85
+ else
86
+ activeTools.delete(event.toolCallId);
87
+ if (wasActive !== (activeTools.size > 0))
88
+ work.toolsActive?.(!wasActive);
89
+ });
90
+ const cursorFailure = `Cursor worker could not complete ${model}. Check Cursor authentication, model availability, and pi-cursor-sdk setup in Pi.`;
91
+ try {
92
+ await session.prompt(work.prompt, { expandPromptTemplates: false });
93
+ }
94
+ catch (error) {
95
+ signal.throwIfAborted();
96
+ if (!cursor)
97
+ throw error;
98
+ return { status: 'failed', summary: cursorFailure };
99
+ }
100
+ finally {
101
+ unsubscribe();
102
+ if (activeTools.size)
103
+ work.toolsActive?.(false);
104
+ }
54
105
  signal.throwIfAborted();
55
106
  const last = session.messages.slice(start).findLast(m => m.role === 'assistant');
56
107
  if (!last || last.role !== 'assistant' || last.stopReason === 'error' || last.stopReason === 'aborted') {
57
- return { status: 'failed', summary: (last?.role === 'assistant' && last.errorMessage) || 'Worker returned no completed response.' };
108
+ return { status: 'failed', summary: cursor ? cursorFailure : last?.errorMessage || 'Worker returned no completed response.' };
58
109
  }
59
110
  retain = !this.closed;
60
111
  if (retain) {
61
112
  this.retained.set(work.id, { session, role: work.role, model, tools });
62
113
  if (this.retained.size > 6) {
63
114
  const [id, oldest] = this.retained.entries().next().value;
64
- oldest.session.dispose();
65
115
  this.retained.delete(id);
116
+ await this.closeSession(oldest.session);
66
117
  }
67
118
  }
68
119
  return workerResult(session.getLastAssistantText() || 'Worker completed without a summary.', retain ? work.id : undefined);
@@ -71,18 +122,56 @@ export class NativeBackend {
71
122
  signal.removeEventListener('abort', stop);
72
123
  this.running.delete(session);
73
124
  if (!retain)
74
- session.dispose();
125
+ await this.closeSession(session);
75
126
  }
76
127
  }
77
- dispose() {
128
+ async closeSession(session) {
129
+ if (session.model?.provider === 'cursor')
130
+ await closeCursorWorker(session).catch(() => { });
131
+ else
132
+ session.dispose();
133
+ }
134
+ async dispose() {
78
135
  this.closed = true;
79
136
  for (const session of this.running)
80
137
  void session.abort().catch(() => { });
81
- for (const { session } of this.retained.values())
82
- session.dispose();
138
+ const retained = [...this.retained.values()];
83
139
  this.retained.clear();
140
+ await Promise.allSettled([...this.pending, ...retained.map(({ session }) => this.closeSession(session))]);
84
141
  }
85
142
  }
143
+ async function workerModelRuntime(agentDir, foreground, model, signal) {
144
+ const { provider, id } = model;
145
+ // Replay the raw registration, not the composed provider or resolved credentials.
146
+ // The SDK still loads no extensions. Callbacks must work without child lifecycle hooks.
147
+ const native = foreground.getRegisteredNativeProvider(provider);
148
+ const config = foreground.getRegisteredProviderConfig(provider);
149
+ const runtime = await ModelRuntime.create({ authPath: join(agentDir, 'auth.json'), modelsPath: join(agentDir, 'models.json'), signal });
150
+ signal.throwIfAborted();
151
+ try {
152
+ if (native)
153
+ runtime.registerNativeProvider(native);
154
+ else if (config)
155
+ runtime.registerProvider(provider, config);
156
+ }
157
+ catch {
158
+ throw Error(`Cannot register worker provider ${provider}; its extension registration is not compatible with an isolated Pi SDK session.`);
159
+ }
160
+ if ((native || config) && !runtime.getModel(provider, id)) {
161
+ // A dynamic registration may only restore its model list during a cache-only refresh.
162
+ await runtime.refresh({ providers: [provider], allowNetwork: false, signal }).catch(() => undefined);
163
+ signal.throwIfAborted();
164
+ }
165
+ if (!runtime.getModel(provider, id)) {
166
+ throw Error(`Model unavailable in the isolated worker catalog: ${provider}/${id}. Check the provider's model list and worker compatibility.`);
167
+ }
168
+ const available = await runtime.getAvailable(provider, { signal }).catch(() => undefined);
169
+ signal.throwIfAborted();
170
+ if (!available?.some(m => m.id === id)) {
171
+ throw Error(`Model unavailable in the isolated worker: ${provider}/${id}. Check Pi authentication and whether the provider requires session-local state.`);
172
+ }
173
+ return runtime;
174
+ }
86
175
  export function workerResult(text, resume) {
87
176
  const marker = /^\s*(DONE|BLOCKED|FAILED)\s*:\s*/i.exec(text);
88
177
  const status = (marker?.[1].toLowerCase() ?? 'done');
@@ -101,7 +190,7 @@ export class SubagentsBackend {
101
190
  }
102
191
  get ready() { return this.available && !this.closed; }
103
192
  supports(work) {
104
- return this.ready && this.snapshotsSupported && work.tools === undefined && work.resume === undefined;
193
+ return work.model.provider !== 'cursor' && this.ready && this.snapshotsSupported && work.tools === undefined && work.resume === undefined;
105
194
  }
106
195
  async probe() {
107
196
  try {
@@ -147,11 +236,14 @@ export class SubagentsBackend {
147
236
  let terminal = false;
148
237
  let counted = false;
149
238
  let stopSent = false;
239
+ const earlyStarts = new Set();
150
240
  let resolve;
151
241
  const result = new Promise(r => { resolve = r; });
152
- const started = () => { if (!counted) {
242
+ // RPC v2 honors the supplied model object verbatim; its public lifecycle
243
+ // exposes the owned start, but not child model or stream/tool events.
244
+ const started = () => { if (!counted && !signal.aborted) {
153
245
  counted = true;
154
- work.started();
246
+ work.started(work.model);
155
247
  } };
156
248
  const unexpected = (entry) => `pi-subagents started ${entry.type} instead of ${work.type}; check Team agent discovery and upstream fallback.`;
157
249
  let mismatch;
@@ -172,12 +264,16 @@ export class SubagentsBackend {
172
264
  };
173
265
  const subscription = ['completed', 'failed', 'started'].map(kind => this.bus.on(`subagents:${kind}`, raw => {
174
266
  const entry = raw;
175
- if (kind === 'started') {
176
- if (entry.id === id && entry.type === work.type)
267
+ if (kind !== 'started')
268
+ finish(entry);
269
+ else if (entry.type === work.type) {
270
+ if (entry.id === id)
177
271
  started();
272
+ // Stock can synchronously announce a start before onSpawned supplies
273
+ // the ID. Match only once ownership is established.
274
+ else if (!id)
275
+ earlyStarts.add(entry.id);
178
276
  }
179
- else
180
- finish(entry);
181
277
  }));
182
278
  const abort = () => {
183
279
  if (!id || terminal || stopSent)
@@ -192,25 +288,37 @@ export class SubagentsBackend {
192
288
  signal.addEventListener('abort', abort, { once: true });
193
289
  const disposed = this.bus.on('subagents:disposed', () => resolve({ status: 'failed', summary: 'Subagents backend shut down.' }));
194
290
  try {
195
- const bind = (agentId) => { id = agentId; if (signal.aborted)
196
- abort(); };
291
+ const bind = (agentId) => {
292
+ id = agentId;
293
+ if (earlyStarts.has(id))
294
+ started();
295
+ earlyStarts.clear();
296
+ if (signal.aborted)
297
+ abort();
298
+ };
197
299
  const spawn = await this.rpc('spawn', { type: work.type, prompt: work.prompt, options: {
198
300
  description: work.description, model: work.model, isBackground: true,
199
- inheritContext: false, isolated: true, signal, onSpawned: bind, onQueued: bind,
301
+ inheritContext: false, isolated: true, signal, onSpawned: bind,
302
+ onQueued: (agentId) => { bind(agentId); if (!signal.aborted)
303
+ work.queued?.(); },
200
304
  ...(work.thinkingLevel !== undefined ? { thinkingLevel: work.thinkingLevel } : {}),
201
305
  } }, 30_000);
202
306
  bind(spawn.id);
203
307
  if (!terminal) {
204
308
  const got = await this.rpc('get', { agentId: id }).catch(() => undefined);
205
309
  const entry = got?.agent;
206
- if (entry && ['completed', 'steered', 'error', 'stopped', 'aborted'].includes(entry.status) && !entry.settling)
207
- finish(entry);
208
- else if (entry && entry.type !== work.type) {
209
- mismatch = unexpected(entry);
210
- abort();
310
+ if (!terminal && entry && entry.id === id) {
311
+ if (['completed', 'steered', 'error', 'stopped', 'aborted'].includes(entry.status) && !entry.settling)
312
+ finish(entry);
313
+ else if (entry.type !== work.type) {
314
+ mismatch = unexpected(entry);
315
+ abort();
316
+ }
317
+ else if (entry.status === 'running')
318
+ started();
319
+ else if (entry.status === 'queued' && !signal.aborted)
320
+ work.queued?.();
211
321
  }
212
- else if (entry?.status === 'running')
213
- started();
214
322
  }
215
323
  return await result;
216
324
  }
@@ -0,0 +1,135 @@
1
+ import { readFile, realpath } from 'node:fs/promises';
2
+ import { isAbsolute, join, resolve } from 'node:path';
3
+ import { createAgentSession, createCodingTools, DefaultPackageManager, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
4
+ const cursorPackage = /^npm:pi-cursor-sdk(?:@[^\s/:]+)?$/;
5
+ const cursorEntry = './dist/index.js';
6
+ async function configuredCursorEntry(cwd, agentDir, projectTrusted) {
7
+ const settingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted });
8
+ const packages = new DefaultPackageManager({ cwd, agentDir, settingsManager, commandOutput: 'capture' });
9
+ // Resolve Pi's normal package filters and precedence, but never install anything.
10
+ // This only enumerates resources; it does not evaluate extension code.
11
+ const { extensions } = await packages.resolve(async () => 'skip');
12
+ const paths = new Set();
13
+ for (const { path, enabled, metadata } of extensions) {
14
+ if (!enabled || metadata.origin !== 'package' || !metadata.packageRoot ||
15
+ (metadata.scope !== 'user' && !(projectTrusted && metadata.scope === 'project')) ||
16
+ !cursorPackage.test(metadata.source) || !isAbsolute(path) ||
17
+ resolve(path) !== resolve(metadata.packageRoot, cursorEntry))
18
+ continue;
19
+ const root = await realpath(metadata.packageRoot);
20
+ const manifest = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));
21
+ if (manifest.name !== 'pi-cursor-sdk' || !Array.isArray(manifest.pi?.extensions) ||
22
+ !manifest.pi.extensions.includes(cursorEntry))
23
+ continue;
24
+ const realEntry = await realpath(path);
25
+ if (realEntry === join(root, cursorEntry))
26
+ paths.add(realEntry);
27
+ }
28
+ return paths.size === 1 ? [...paths][0] : undefined;
29
+ }
30
+ export async function closeCursorWorker(session) {
31
+ try {
32
+ await session.extensionRunner.emit({ type: 'session_shutdown', reason: 'quit' });
33
+ }
34
+ finally {
35
+ session.dispose();
36
+ }
37
+ }
38
+ export function checkCursorWorkerPolicy(work, projectTrusted) {
39
+ const ref = `cursor/${work.model.id}`;
40
+ // A Pi allowlist governs the bridge, not Cursor-native tools/ambient MCP. There
41
+ // is no per-session public Cursor setting to enforce that policy here.
42
+ if (work.tools !== undefined) {
43
+ throw Error(`Cannot run ${ref} with a Team tool allowlist: pi-cursor-sdk can run tools outside Pi's allowlist. Choose another model for this role.`);
44
+ }
45
+ if (work.model.api !== 'cursor-sdk') {
46
+ throw Error(`Cannot run ${ref}: the selected Cursor model does not use the pi-cursor-sdk API.`);
47
+ }
48
+ // Cursor's ambient SDK settings can load project plugins/MCP independently of Pi.
49
+ if (!projectTrusted && process.env.PI_CURSOR_SETTING_SOURCES?.trim().toLowerCase() !== 'none') {
50
+ throw Error('Cursor workers in an untrusted project require PI_CURSOR_SETTING_SOURCES=none to disable ambient Cursor settings. Restart Pi with that setting or choose another model.');
51
+ }
52
+ }
53
+ export async function createCursorWorker(cwd, agentDir, projectTrusted, work, signal) {
54
+ const ref = `cursor/${work.model.id}`;
55
+ let entry;
56
+ try {
57
+ entry = await configuredCursorEntry(cwd, agentDir, projectTrusted);
58
+ }
59
+ catch {
60
+ signal.throwIfAborted();
61
+ throw Error('Could not resolve the configured pi-cursor-sdk extension. Check your Pi package configuration and reload Pi.');
62
+ }
63
+ signal.throwIfAborted();
64
+ if (!entry) {
65
+ throw Error('Cursor workers require one enabled, already-installed npm:pi-cursor-sdk Pi package in user or trusted project settings. Check your Pi configuration and reload Pi.');
66
+ }
67
+ // Pass only the verified local file, not an npm source (which can install).
68
+ // In-memory settings ensure no other configured packages are resolved here.
69
+ const settingsManager = SettingsManager.inMemory({ retry: { enabled: true, maxRetries: 1 } }, { projectTrusted });
70
+ const resourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager, noExtensions: true,
71
+ additionalExtensionPaths: [entry], noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true });
72
+ let session;
73
+ try {
74
+ const modelRuntime = await ModelRuntime.create({ authPath: join(agentDir, 'auth.json'), modelsPath: join(agentDir, 'models.json'),
75
+ modelsStorePath: join(agentDir, 'models-store.json'), allowModelNetwork: false, refreshOnCreate: false, signal });
76
+ signal.throwIfAborted();
77
+ await resourceLoader.reload();
78
+ const { extensions, errors } = resourceLoader.getExtensions();
79
+ if (errors.length || extensions.length !== 1)
80
+ throw Error();
81
+ // Pi registers the extension providers and Cursor restores its cache during
82
+ // binding. Seed the selected identity (not a fallback); replace it before any prompt.
83
+ ({ session } = await createAgentSession({ cwd, agentDir, model: work.model, modelRuntime, thinkingLevel: work.thinkingLevel,
84
+ tools: createCodingTools(cwd).map(tool => tool.name), sessionManager: SessionManager.inMemory(cwd), settingsManager, resourceLoader }));
85
+ signal.throwIfAborted();
86
+ let startupFailed = false;
87
+ const worker = session;
88
+ await worker.bindExtensions({ mode: 'print', abortHandler: () => { void worker.abort().catch(() => { }); },
89
+ shutdownHandler: () => { void worker.abort().catch(() => { }); },
90
+ onError: error => { if (error.event === 'session_start')
91
+ startupFailed = true; } });
92
+ signal.throwIfAborted();
93
+ if (startupFailed || !worker.extensionRunner.hasHandlers('before_provider_headers') ||
94
+ !modelRuntime.getRegisteredNativeProvider('cursor'))
95
+ throw Error();
96
+ }
97
+ catch {
98
+ if (session)
99
+ await closeCursorWorker(session).catch(() => { });
100
+ signal.throwIfAborted();
101
+ throw Error('Could not load and start pi-cursor-sdk in the Team worker. Check that the installed package is compatible with this Pi version and reload Pi.');
102
+ }
103
+ try {
104
+ const runtime = session.modelRuntime;
105
+ const exact = runtime.getPhysicalModel('cursor', work.model.id);
106
+ if (!exact || exact.api !== 'cursor-sdk' ||
107
+ !runtime.getRegisteredNativeProvider('cursor')?.getModels().some(model => model.id === exact.id && model.api === exact.api)) {
108
+ throw Error(`Model ${ref} is not listed by this worker's pi-cursor-sdk catalog. Refresh the Cursor catalog in Pi or choose a listed model.`);
109
+ }
110
+ try {
111
+ const auth = await runtime.checkAuth('cursor', { signal });
112
+ // Cursor may report catalog availability while logged out; its fallback
113
+ // placeholder is not usable auth for a request. Do not resolve or log keys here.
114
+ if (!auth || auth.source === 'fallback')
115
+ throw Error();
116
+ const available = await runtime.getAvailable('cursor', { signal });
117
+ signal.throwIfAborted();
118
+ if (!available.some(model => model.id === exact.id && model.api === exact.api))
119
+ throw Error();
120
+ await session.setModel(exact);
121
+ }
122
+ catch {
123
+ signal.throwIfAborted();
124
+ throw Error(`Model unavailable in the Cursor worker: ${ref}. Check pi-cursor-sdk authentication in Pi.`);
125
+ }
126
+ signal.throwIfAborted();
127
+ if (work.thinkingLevel !== undefined)
128
+ session.setThinkingLevel(work.thinkingLevel);
129
+ return session;
130
+ }
131
+ catch (error) {
132
+ await closeCursorWorker(session).catch(() => { });
133
+ throw error;
134
+ }
135
+ }
@@ -0,0 +1,63 @@
1
+ import { Container, parseColor, visibleWidth } from '@earendil-works/pi-tui';
2
+ import { roleColor } from './role-colors.js';
3
+ import { clip, singleLine } from './ui-text.js';
4
+ const queueText = (ids) => `Queued: ${ids.join(', ')}. Team Mode will notify you when a decision or final summary is due.`;
5
+ export function dispatchQueuedResult(ids) {
6
+ return { content: [{ type: 'text', text: queueText(ids) }], details: { kind: 'queued', ids } };
7
+ }
8
+ export function renderDispatchResult(result, { isPartial }, _theme, context) {
9
+ const details = record(result.details);
10
+ const [block] = result.content;
11
+ if (!isPartial && !context.isError && details?.kind === 'queued' && Object.keys(details).length === 2 &&
12
+ Array.isArray(details.ids) && result.content.length === 1 && block?.type === 'text' && block.text === queueText(details.ids)) {
13
+ return new Container(); // Zero lines; the existing call rows are the whole acknowledgement.
14
+ }
15
+ // Pi's documented renderer fallback keeps normal result styling, truncation and image handling.
16
+ throw Error('Use Pi’s default rendering for non-acknowledgement dispatch results');
17
+ }
18
+ const background = 'background';
19
+ const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
20
+ export function renderDispatchCall(args, theme, context, currentProfile) {
21
+ // Pi keeps this state with the live transcript row, even after switching profiles.
22
+ const profile = context.state.profile ??= currentProfile;
23
+ const tasks = record(args)?.tasks;
24
+ const rows = Array.isArray(tasks) ? Array.from(tasks, value => {
25
+ const task = record(value);
26
+ const role = typeof task?.role === 'string' ? task.role : '';
27
+ const configured = Object.hasOwn(profile.roles, role) ? profile.roles[role].name : undefined;
28
+ const name = singleLine(configured) || singleLine(role) || 'Role pending';
29
+ const brief = singleLine(task?.brief) || 'Brief pending';
30
+ return { role, name, brief };
31
+ }) : [];
32
+ const shellBg = theme.getBgAnsi(context.isPartial ? 'toolPendingBg' : context.isError ? 'toolErrorBg' : 'toolSuccessBg');
33
+ return {
34
+ invalidate() { },
35
+ render(width) {
36
+ if (width < 1)
37
+ return [];
38
+ if (!rows.length)
39
+ return [clip('Dispatch team tasks', width)];
40
+ return rows.map(({ role, name, brief }) => {
41
+ // Make room for both badge spaces whenever at least one name cell fits with them.
42
+ const pad = width >= 3 ? ' ' : '';
43
+ const padding = 2 * pad.length;
44
+ // Keep the mode visible when all three fields fit; at tiny widths keep the role first.
45
+ const room = width - background.length - 2;
46
+ const textRoom = room - padding;
47
+ const showBackground = textRoom >= 2;
48
+ const roleWidth = showBackground ? Math.floor(textRoom / 2) : width - padding;
49
+ const label = `${pad}${clip(name, roleWidth)}${pad}`;
50
+ const color = roleColor(role);
51
+ // Match stock's high-contrast foreground for these fixed palette colors.
52
+ const lightText = role === 'validator' || (role === 'researcher' && theme.getColorMode() === 'truecolor');
53
+ const badge = color ? theme.style(label, { bg: parseColor(color.hex), fg: parseColor(lightText ? '#FFFFFF' : '#000000'), bold: true })
54
+ : theme.style(label, { bg: 'selectedBg', fg: 'text', bold: true });
55
+ // Restore Pi's enclosing tool-card background after the badge's reset.
56
+ if (showBackground)
57
+ return `${badge}${shellBg} ${clip(brief, room - visibleWidth(label))} ${background}`;
58
+ const briefWidth = width - visibleWidth(label) - 1;
59
+ return briefWidth >= 1 ? `${badge}${shellBg} ${clip(brief, briefWidth)}` : badge + shellBg;
60
+ });
61
+ },
62
+ };
63
+ }
package/dist/extension.js CHANGED
@@ -13,17 +13,31 @@ import { Scheduler, summaryText } from './scheduler.js';
13
13
  import { publish } from './publish.js';
14
14
  import { checkForUpdate } from './update.js';
15
15
  import { ensureWorkerType, roleBody, workerRules } from './worker-agents.js';
16
+ import { dispatchQueuedResult, renderDispatchCall, renderDispatchResult } from './dispatch-call.js';
17
+ import { statusView } from './status-view.js';
16
18
  const keys = ['team_dispatch', 'team_results', 'team_publish'];
17
19
  const statusKey = 'team-mode';
20
+ const profileEntry = 'pi-team-mode-profile';
21
+ function lastProfile(ctx) {
22
+ // This preference is session-wide, not branch-local model context.
23
+ for (const entry of ctx.sessionManager.getEntries().reverse()) {
24
+ if (entry.type !== 'custom' || entry.customType !== profileEntry)
25
+ continue;
26
+ const data = entry.data;
27
+ if (data && typeof data === 'object' && 'profile' in data && typeof data.profile === 'string' && data.profile)
28
+ return data.profile;
29
+ }
30
+ }
18
31
  const createUsage = 'Usage: /team profile create <id> --from <template>';
19
32
  const modelUsage = 'Usage: /team model <role> <provider/model-id> (or configured alias)';
20
33
  const configUsage = 'Usage: /team config edit [project] | validate | reload';
21
34
  const teamHelp = [
22
35
  '/team — open the Team Mode menu',
36
+ '/team status — show Team status and live worker models',
23
37
  '/team profile [<id>] — pick or switch profiles',
24
38
  '/team profile create <id> --from <template> — save a personal copy',
25
39
  `Templates: ${templateIds.join(', ')}`,
26
- '/team on | off | status | cancel | reset | doctor',
40
+ '/team on | off | cancel | reset | doctor',
27
41
  '/team model [<role> [<provider/model-id>]] — pick or select a role model',
28
42
  '/team config edit [project] | validate | reload',
29
43
  '/team help — show these commands',
@@ -57,6 +71,7 @@ export default function teamExtension(pi) {
57
71
  let native;
58
72
  let config = defaults();
59
73
  let selected = config.defaultProfile;
74
+ let preferredProfile;
60
75
  let enabled = false;
61
76
  let error;
62
77
  let scheduler;
@@ -70,12 +85,24 @@ export default function teamExtension(pi) {
70
85
  let publishing = false;
71
86
  let publicationGeneration = 0;
72
87
  const reported = new WeakSet();
88
+ let refreshStatusView;
73
89
  const roles = () => config.profiles[selected];
90
+ function restoreProfile(ctx) {
91
+ selected = preferredProfile && Object.hasOwn(config.profiles, preferredProfile) ? preferredProfile : config.defaultProfile;
92
+ if (!error && preferredProfile && selected !== preferredProfile) {
93
+ ctx.ui.notify(`Team profile ${preferredProfile} is unavailable; using ${selected}.`, 'warning');
94
+ }
95
+ }
74
96
  const reportStatus = (ctx = foreground) => {
97
+ refreshStatusView?.();
75
98
  if (!ctx?.hasUI)
76
99
  return;
77
- const active = scheduler?.list().filter(job => job.state === 'running' || job.state === 'queued').length ?? 0;
78
- ctx.ui.setStatus(statusKey, enabled ? `Team: ${roles().name}${error ? ' · blocked' : active ? ` · ${active}` : ''}` : undefined);
100
+ const counts = Object.entries(scheduler?.counts() ?? {}).filter(([, n]) => n).map(([label, n]) => `${n} ${label}`);
101
+ const usingTools = scheduler?.list().filter(job => job.state === 'running' && job.toolsActive).length ?? 0;
102
+ if (usingTools)
103
+ counts.push(`${usingTools} using tools`);
104
+ const bits = [roles().name, ...(error ? ['blocked'] : counts)];
105
+ ctx.ui.setStatus(statusKey, enabled ? `Team: ${bits.join(' · ')}` : undefined);
79
106
  };
80
107
  function applyTools() {
81
108
  if (enabled) {
@@ -122,18 +149,25 @@ export default function teamExtension(pi) {
122
149
  function registeredModel(ref, ctx) {
123
150
  const { provider, id } = modelRef(ref, {});
124
151
  const model = ctx.modelRegistry.find(provider, id);
125
- if (!model)
126
- throw Error(`Unregistered model ${ref}`);
152
+ if (!model) {
153
+ if (!ctx.modelRegistry.getProvider(provider) && !ctx.modelRegistry.getRegisteredProviderIds().includes(provider)) {
154
+ throw Error(`Provider ${provider} is not registered in this Pi session (${ref}). Enable or configure it in Pi and reload.`);
155
+ }
156
+ throw Error(`Model ${ref} is not listed by registered provider ${provider}. Check its model catalog or select an available model with /team model.`);
157
+ }
127
158
  return { model, ref };
128
159
  }
129
160
  function newScheduler() {
130
- const generation = new Scheduler(config.concurrency, async (task, deps, signal) => {
161
+ const generation = new Scheduler(config.concurrency, async (task, deps, signal, observe) => {
131
162
  const role = roles().roles[task.role];
132
163
  // Explicit task choices were authorized at dispatch. Only defaults and one-shot
133
164
  // selections are resolved at worker start, against Pi's live foreground context.
134
165
  const ctx = foreground;
135
166
  const configured = configuredPool(task.role);
136
167
  const { model, ref } = task.model === undefined ? selectModel(task, ctx, configured) : registeredModel(task.model, ctx);
168
+ if (!ctx.modelRegistry.getAvailable().some(m => m.provider === model.provider && m.id === model.id)) {
169
+ throw Error(`Model unavailable: ${ref}. Check provider authentication and the Pi model catalog, then retry.`);
170
+ }
137
171
  const explicitThinking = configured.find(entry => entry.ref === ref)?.thinkingLevel;
138
172
  const thinkingLevel = configured.length ? explicitThinking : pi.getThinkingLevel();
139
173
  if (explicitThinking !== undefined) {
@@ -150,10 +184,15 @@ export default function teamExtension(pi) {
150
184
  ? `\n\nEarlier result: ${summaryText(previous.result?.summary ?? '', 900)}` : '';
151
185
  const work = { id: task.id, role: task.role, prompt: workerPrompt(roles(), task, deps) + earlier,
152
186
  model, thinkingLevel, resume, tools: role.access?.tools,
153
- started: () => { try {
154
- pools.started(selected, task.role, ref);
155
- }
156
- catch { /* Usage is best-effort; do not block work. */ } } };
187
+ started: actual => {
188
+ const model = `${actual.provider}/${actual.id}`;
189
+ observe({ kind: 'started', model });
190
+ try {
191
+ pools.started(selected, task.role, model);
192
+ }
193
+ catch { /* Usage is best-effort; do not block work. */ }
194
+ },
195
+ queued: () => observe({ kind: 'queued' }), toolsActive: active => observe({ kind: 'tools', active }) };
157
196
  if (external.supports(work)) {
158
197
  signal.throwIfAborted();
159
198
  // Stock's top-level loader discovers project agents from process.cwd().
@@ -161,7 +200,7 @@ export default function teamExtension(pi) {
161
200
  if (type)
162
201
  return external.run({ ...work, type, description: task.brief, prompt: workerBrief(task, deps) + earlier }, signal);
163
202
  }
164
- return native.run(work, signal);
203
+ return native.run(work, signal, ctx.modelRegistry, ctx.isProjectTrusted());
165
204
  }, (reason, jobs) => {
166
205
  reportStatus();
167
206
  if (reason === 'progress')
@@ -212,7 +251,7 @@ export default function teamExtension(pi) {
212
251
  throw Error('Workers are still active; use /team cancel and wait.');
213
252
  scheduler?.dispose();
214
253
  scheduler = undefined;
215
- native?.dispose();
254
+ await native?.dispose();
216
255
  native = new NativeBackend(ctx.cwd, agentDir);
217
256
  pending = undefined;
218
257
  queued = false;
@@ -236,17 +275,16 @@ export default function teamExtension(pi) {
236
275
  scheduler?.reset();
237
276
  scheduler?.dispose();
238
277
  scheduler = undefined;
239
- native?.dispose();
278
+ await native?.dispose();
240
279
  native = new NativeBackend(ctx.cwd, agentDir);
241
280
  selected = name;
242
281
  pending = undefined;
243
282
  queued = false;
244
283
  await activate(ctx);
245
- }
246
- function showStatus(ctx) {
247
- const jobs = scheduler?.list().map(j => `${j.task.id}: ${j.state}`).join('\n');
248
- const profile = `${roles().name} (${selected})`;
249
- ctx.ui.notify(`Team: ${enabled ? profile : `off; selected profile: ${profile}`}${error ? ' · blocked; see /team doctor' : ''}${jobs ? `\n${jobs}` : ''}`, 'info');
284
+ if (preferredProfile !== name) {
285
+ pi.appendEntry(profileEntry, { profile: name });
286
+ preferredProfile = name;
287
+ }
250
288
  }
251
289
  async function pickProfile(ctx) {
252
290
  if (!interactive(ctx))
@@ -303,9 +341,11 @@ export default function teamExtension(pi) {
303
341
  throw Error(`${error}; see /team doctor.`);
304
342
  if (value !== undefined && role !== undefined) {
305
343
  checkModelRole(role);
306
- const { provider, id, ref } = modelRef(value, config.aliases);
307
- if (!ctx.modelRegistry.getAvailable().some(m => m.provider === provider && m.id === id))
308
- throw Error(`Model unavailable: ${ref}`);
344
+ const { ref } = modelRef(value, config.aliases);
345
+ const { model } = registeredModel(ref, ctx);
346
+ if (!ctx.modelRegistry.getAvailable().some(m => m.provider === model.provider && m.id === model.id)) {
347
+ throw Error(`Model unavailable: ${ref}. Check provider authentication and the Pi model catalog.`);
348
+ }
309
349
  await chooseModel(role, ref, ctx);
310
350
  return;
311
351
  }
@@ -322,6 +362,28 @@ export default function teamExtension(pi) {
322
362
  if (ref !== undefined)
323
363
  await chooseModel(role, ref, ctx);
324
364
  }
365
+ async function showStatus(ctx) {
366
+ const summary = () => {
367
+ const profile = `${roles().name} (${selected})`;
368
+ return `Team: ${enabled ? profile : `off; selected profile: ${profile}`}${error ? ' · blocked; see /team doctor' : ''}`;
369
+ };
370
+ const tasks = () => scheduler?.list().map(j => `${j.task.id}: ${j.state}`) ?? [];
371
+ if (!interactive(ctx)) {
372
+ ctx.ui.notify([summary(), ...tasks()].join('\n'), 'info');
373
+ return;
374
+ }
375
+ await ctx.ui.custom((tui, theme, _keys, close) => {
376
+ const refresh = () => tui.requestRender();
377
+ refreshStatusView = refresh;
378
+ return statusView(summary, tasks, () => scheduler?.liveJobs().map(({ job, status }) => {
379
+ const role = roles().roles[job.task.role];
380
+ return { job, status, role: role.name,
381
+ inherits: job.state === 'queued' && !job.task.model && !role.modelPool.length &&
382
+ !nextModel.has(`${selected}/${job.task.role}`) };
383
+ }) ?? [], tui, theme, close, () => { if (refreshStatusView === refresh)
384
+ refreshStatusView = undefined; });
385
+ });
386
+ }
325
387
  async function mainMenu(ctx) {
326
388
  if (!interactive(ctx)) {
327
389
  ctx.ui.notify(teamHelp, 'info');
@@ -372,18 +434,20 @@ export default function teamExtension(pi) {
372
434
  error = errorMessage(err);
373
435
  ctx.ui.notify(error, 'error');
374
436
  }
375
- selected = config.defaultProfile;
437
+ preferredProfile = lastProfile(ctx);
438
+ restoreProfile(ctx);
376
439
  if (config.enabled)
377
440
  await activate(ctx);
378
441
  void external.probe();
379
442
  });
380
443
  pi.on('model_select', (_event, ctx) => { foreground = ctx; });
381
- pi.on('session_shutdown', () => {
444
+ pi.on('session_shutdown', async () => {
382
445
  updateCheck?.abort();
383
446
  enabled = false;
384
447
  scheduler?.dispose();
385
- native?.dispose();
386
448
  external.dispose();
449
+ reportStatus();
450
+ await native?.dispose();
387
451
  });
388
452
  pi.on('session_before_tree', () => { publicationGeneration++; scheduler?.cancel(); pending = undefined; queued = false; });
389
453
  pi.on('before_agent_start', event => {
@@ -409,7 +473,9 @@ export default function teamExtension(pi) {
409
473
  });
410
474
  pi.registerTool({ name: 'team_dispatch', label: 'Dispatch team tasks', description: 'Queue useful background work, optionally with dependencies; returns immediately. Use a new ID for each task.',
411
475
  defaultActive: false, parameters: Type.Object({ tasks: Type.Array(TaskInput, { minItems: 1, maxItems: 16 }) }),
412
- async execute(_id, { tasks }, _signal, _update, ctx) {
476
+ renderCall: (args, theme, context) => renderDispatchCall(args, theme, context, roles()),
477
+ renderResult: renderDispatchResult,
478
+ async execute(_callId, { tasks }, _signal, _update, ctx) {
413
479
  const owner = scheduler;
414
480
  if (!enabled || !owner || error)
415
481
  throw Error(error ?? 'Team Mode is off');
@@ -424,7 +490,7 @@ export default function teamExtension(pi) {
424
490
  const { ref } = selectModel(task, ctx);
425
491
  return { ...task, model: task.model === undefined ? undefined : ref, writes: task.writes ?? task.role === 'coder' };
426
492
  });
427
- return output(`Queued: ${owner.submit(batch).join(', ')}. Team Mode will notify you when a decision or final summary is due.`);
493
+ return dispatchQueuedResult(owner.submit(batch));
428
494
  } });
429
495
  pi.registerTool({ name: 'team_results', label: 'Inspect team results', description: 'Read compact team status or one task result; do not poll.', defaultActive: false,
430
496
  parameters: Type.Object({ id: Type.Optional(Type.String()) }),
@@ -496,13 +562,13 @@ export default function teamExtension(pi) {
496
562
  }
497
563
  else if (command === 'reset') {
498
564
  scheduler?.reset();
499
- native?.dispose();
565
+ await native?.dispose();
500
566
  native = new NativeBackend(ctx.cwd, agentDir);
501
567
  pending = undefined;
502
568
  queued = false;
503
569
  }
504
570
  else if (command === 'status')
505
- showStatus(ctx);
571
+ await showStatus(ctx);
506
572
  else if (command === 'doctor') {
507
573
  const available = await external.probe();
508
574
  ctx.ui.notify(`${error ?? 'Configuration OK'}\nBackend: ${available ? 'pi-subagents RPC v2 (SDK when native Team roles or worker policies are unavailable)' : 'built-in Pi SDK'}`, error ? 'error' : 'info');
@@ -548,12 +614,11 @@ export default function teamExtension(pi) {
548
614
  scheduler?.reset();
549
615
  scheduler?.dispose();
550
616
  scheduler = undefined;
551
- native?.dispose();
617
+ await native?.dispose();
552
618
  native = new NativeBackend(ctx.cwd, agentDir);
553
619
  config = next;
554
620
  error = undefined;
555
- if (!Object.hasOwn(config.profiles, selected))
556
- selected = config.defaultProfile;
621
+ restoreProfile(ctx);
557
622
  if (enabled)
558
623
  await activate(ctx);
559
624
  ctx.ui.notify('Team configuration reloaded', 'info');
@@ -0,0 +1,11 @@
1
+ // Stock pi-subagents 0.26.3 named colors used by our native Team definitions.
2
+ const colors = new Map([
3
+ ['arch', { name: 'blue', hex: '#6A9BCC' }],
4
+ ['scout', { name: 'cyan', hex: '#0891B2' }],
5
+ ['reviewer', { name: 'purple', hex: '#827DBD' }],
6
+ ['coder', { name: 'green', hex: '#16A34A' }],
7
+ ['validator', { name: 'red', hex: '#DC2626' }],
8
+ ['analyzer', { name: 'yellow', hex: '#CA8A04' }],
9
+ ['researcher', { name: 'teal', hex: '#008080' }],
10
+ ]);
11
+ export const roleColor = (role) => colors.get(role);
package/dist/scheduler.js CHANGED
@@ -1,4 +1,6 @@
1
1
  const terminal = (state) => state !== 'running' && state !== 'queued';
2
+ const liveState = (job) => job.state === 'queued' ? 'queued' :
3
+ job.startedModel ? 'running' : job.backendQueued ? 'queued' : 'starting';
2
4
  const briefLimit = 12_000;
3
5
  export function summaryText(value, limit = 2400) {
4
6
  return value.length > limit ? `${value.slice(0, limit)}\n[truncated]` : value;
@@ -20,6 +22,19 @@ export class Scheduler {
20
22
  get busy() { return this.list().some(j => !terminal(j.state)); }
21
23
  get active() { return this.busy || this.controllers.size > 0; }
22
24
  list() { return [...this.jobs.values()]; }
25
+ liveJobs() {
26
+ return this.list().filter(job => !terminal(job.state)).map(job => ({ job, status: liveState(job) }));
27
+ }
28
+ counts() {
29
+ const counts = { queued: 0, starting: 0, running: 0, stopping: 0, done: 0, blocked: 0, failed: 0, cancelled: 0 };
30
+ for (const [id, job] of this.jobs) {
31
+ if (job.state === 'cancelled' && this.controllers.has(id))
32
+ counts.stopping++;
33
+ else
34
+ counts[terminal(job.state) ? job.state : liveState(job)]++;
35
+ }
36
+ return counts;
37
+ }
23
38
  submit(tasks) {
24
39
  if (this.stopped)
25
40
  throw Error('Coordinator stopped');
@@ -66,6 +81,7 @@ export class Scheduler {
66
81
  if (this.busy || this.controllers.size)
67
82
  throw Error('Wait for workers to finish stopping before resetting tasks');
68
83
  this.jobs.clear();
84
+ this.onChange('progress', []);
69
85
  }
70
86
  cancel() {
71
87
  this.revision++;
@@ -113,7 +129,19 @@ export class Scheduler {
113
129
  this.controllers.set(job.task.id, controller);
114
130
  void Promise.resolve().then(() => {
115
131
  controller.signal.throwIfAborted();
116
- return this.execute(job.task, deps, controller.signal);
132
+ return this.execute(job.task, deps, controller.signal, progress => {
133
+ if (job.state !== 'running' || controller.signal.aborted)
134
+ return;
135
+ if (progress.kind === 'started' && !job.startedModel)
136
+ job.startedModel = progress.model;
137
+ else if (progress.kind === 'queued' && !job.startedModel)
138
+ job.backendQueued = true;
139
+ else if (progress.kind === 'tools')
140
+ job.toolsActive = progress.active;
141
+ else
142
+ return;
143
+ this.onChange('progress', this.list());
144
+ });
117
145
  }).catch((error) => ({ status: 'failed', summary: String(error) })).then(result => {
118
146
  this.controllers.delete(job.task.id);
119
147
  const current = revision === this.revision;
@@ -0,0 +1,45 @@
1
+ import { matchesKey } from '@earendil-works/pi-tui';
2
+ import { clip, singleLine } from './ui-text.js';
3
+ export function statusView(summary, tasks, live, tui, theme, close, dispose) {
4
+ let offset = 0;
5
+ return {
6
+ dispose,
7
+ invalidate() { },
8
+ handleInput(data) {
9
+ if (matchesKey(data, 'escape') || matchesKey(data, 'enter') || matchesKey(data, 'ctrl+c'))
10
+ close();
11
+ else {
12
+ const up = matchesKey(data, 'up') || data === 'k';
13
+ const down = matchesKey(data, 'down') || data === 'j';
14
+ if (!up && !down)
15
+ return;
16
+ offset += up ? -1 : 1;
17
+ tui.requestRender();
18
+ }
19
+ },
20
+ render(width) {
21
+ if (width < 1)
22
+ return [];
23
+ const formatted = live().flatMap(({ job, role, status, inherits }) => {
24
+ const { task, startedModel } = job;
25
+ const name = singleLine(role) || singleLine(task.role);
26
+ const brief = singleLine(task.brief);
27
+ const model = startedModel ? singleLine(startedModel) : task.model ? `pending (pinned: ${singleLine(task.model)})` :
28
+ inherits ? 'inherits foreground at start' : 'pending';
29
+ return [clip(`${status} · ${name} · ${task.id}${brief ? ` · ${brief}` : ''}`, width),
30
+ theme.fg('muted', clip(` Model: ${model}`, width))];
31
+ });
32
+ const history = tasks();
33
+ const lines = [theme.fg('accent', clip('Live workers', width)),
34
+ ...(formatted.length ? formatted : [clip('No queued or running Team tasks.', width)]),
35
+ ...(history.length ? [theme.fg('accent', clip('Task summary', width)), ...history.map(line => clip(line, width))] : []),
36
+ ];
37
+ const size = Math.max(1, Math.min(16, tui.terminal.rows - 4));
38
+ offset = Math.max(0, Math.min(offset, lines.length - size));
39
+ const hint = lines.length > size
40
+ ? `${offset + 1}–${offset + size} of ${lines.length} · ↑/↓ or j/k Scroll · Esc Close` : 'Esc Close';
41
+ return [theme.fg('accent', clip(singleLine(summary()), width)), ...lines.slice(offset, offset + size),
42
+ theme.fg('muted', clip(hint, width))];
43
+ },
44
+ };
45
+ }
@@ -0,0 +1,5 @@
1
+ import { replaceControlCharacters, stripTerminalSequences, truncateToWidth } from '@earendil-works/pi-tui';
2
+ export const singleLine = (value) => typeof value === 'string' ? replaceControlCharacters(stripTerminalSequences(value))
3
+ .replace(/\p{Surrogate}/gu, '\ufffd').replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '').replace(/\s+/gu, ' ').trim() : '';
4
+ // The TUI truncator adds resets around its ellipsis; clip plain text before applying any styling.
5
+ export const clip = (text, width) => stripTerminalSequences(truncateToWidth(text, width, '…'));
@@ -2,19 +2,19 @@ import { createHash, randomUUID } from 'node:crypto';
2
2
  import { lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, realpathSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
3
3
  import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
4
  import { DefaultPackageManager, parseFrontmatter, SettingsManager } from '@earendil-works/pi-coding-agent';
5
+ import { roleColor } from './role-colors.js';
5
6
  const prefix = 'pi-team-mode-worker-';
6
- const colors = { arch: 'blue', scout: 'cyan', reviewer: 'purple', coder: 'green',
7
- validator: 'red', analyzer: 'yellow', researcher: 'teal' };
8
7
  const slug = (id) => id.toLowerCase().replace(/[^a-z0-9]+/g, '-').slice(0, 32);
9
8
  export const workerRules = 'Report individually to Lead: DONE, BLOCKED, or FAILED followed by a concise result and evidence. ' +
10
9
  'Do routine work directly; route remote writes and destructive operations through Lead.';
11
10
  export const roleBody = (role) => `Team task (${role.name}; ${role.personality}). ${role.workScope}`;
12
11
  function definition(name, profileName, role, config) {
12
+ const color = roleColor(role);
13
13
  return `---
14
14
  name: ${name}
15
15
  display_name: ${JSON.stringify(config.name)}
16
16
  description: ${JSON.stringify(`Team Mode ${profileName} ${config.name} worker`)}
17
- ${Object.hasOwn(colors, role) ? `color: ${colors[role]}\n` : ''}prompt_mode: replace
17
+ ${color ? `color: ${color.name}\n` : ''}prompt_mode: replace
18
18
  tools: read, bash, edit, write, grep, find, ls
19
19
  extensions: false
20
20
  skills: false
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-team-mode",
3
- "version": "0.1.3",
3
+ "version": "0.1.6",
4
4
  "description": "Efficiency-first teams for Pi with background workers and a foreground Team Lead",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -22,11 +22,13 @@
22
22
  "peerDependencies": {
23
23
  "@earendil-works/pi-coding-agent": "*",
24
24
  "@earendil-works/pi-ai": "*",
25
+ "@earendil-works/pi-tui": "*",
25
26
  "typebox": "*"
26
27
  },
27
28
  "devDependencies": {
28
29
  "@earendil-works/pi-coding-agent": "1.7.0",
29
30
  "@earendil-works/pi-ai": "1.7.0",
31
+ "@earendil-works/pi-tui": "1.7.0",
30
32
  "@types/node": "^24.0.0",
31
33
  "typebox": "^1.3.27",
32
34
  "typescript": "^6.0.1"