pi-team-mode 0.1.2 → 0.1.3

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,7 +2,7 @@
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
- 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.
5
+ **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
6
 
7
7
  ## Install
8
8
 
@@ -14,20 +14,28 @@ This nested directory is the npm packaging target. If installing it directly fro
14
14
 
15
15
  On fresh TUI startup, an unpinned, Pi-managed install from the official GitHub repository checks whether `main` is ahead of the installed commit. The read-only check runs in the background, times out after two seconds, and stays silent offline, on failure, and for local, pinned, or npm sources. `PI_TEAM_NO_UPDATE_CHECK=1` disables this check, not Pi’s own package notice; `pi --offline` disables both.
16
16
 
17
- 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.
17
+ 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
18
 
19
- 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 namespaced links under `agents/`. 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.
19
+ 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
20
 
21
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.
22
22
 
23
23
  ## Use
24
24
 
25
- - `/team` opens the profile picker; `/team profile engineer|research|audit` switches directly.
25
+ - `/team` opens the Team Mode menu: **Switch profile**, **Create profile from template**, **Turn Team Mode off/on**, **Status**, **Configure role model**, and **Help**. Navigate with ↑/↓ and Enter; Esc closes the current picker. `/team profile` opens the profile-ID picker directly. `/team help` lists all commands.
26
+ - `/team profile <id>` switches directly and turns Team Mode on. `/team profile status` only switches if a custom profile has that ID; for status use `/team status`.
26
27
  - `/team on`, `/team off`, `/team status`, `/team cancel`, `/team reset`, `/team doctor`.
28
+ - `/team profile create <id> --from <template>` saves a personal copy without switching or changing the default. The **Create profile from template** menu item prompts for the template and new ID, saves, then asks **Switch to the new profile?**. **No** or Esc at that final question leaves the copy saved but does not switch.
27
29
  - `/team config edit [project]`, `/team config validate`, `/team config reload`.
28
- - `/team model <role> <provider/model-id>` adds an available model to that role's pool and selects it for the next worker run (or switches the foreground Lead now). Usage is tracked locally for five-entry pool eviction.
30
+ - **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.
29
31
 
30
- User settings live in `<Pi agent directory>/team-mode.json`; trusted project overrides live in `.pi/team-mode.json`. Roles inherit defaults by ID. 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:
32
+ 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
+
34
+ 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
+
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.
37
+
38
+ 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:
31
39
 
32
40
  ```json
33
41
  {
@@ -50,7 +58,7 @@ Every built-in pool in Engineer, Research, and Audit is empty. A blank Lead pool
50
58
 
51
59
  Each entry is a model string or an object with `model` and optional `thinkingLevel`. Both accept exact `provider/model-id` values or aliases from `aliases`. Use `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max`; Pi clamps to model capabilities. An entry without a level keeps the normal Pi/backend behavior. An explicit or inherited level is forwarded through compatible RPC v2, or applied directly with the SDK if the RPC peer cannot be trusted to honor it. SDK continuations also apply the current requested level before prompting.
52
60
 
53
- Trusted project settings replace user pool arrays; an explicit `[]` restores foreground inheritance. For workers, a task’s explicit model wins over the pending `/team model` selection, which wins over the configured default or foreground fallback. Task overrides must be in the pool or match the inherited default; non-default choices need a reason unless selected by `/team model`. Selection uses the matched entry’s thinking level. Learned alternatives and usage live in `<Pi agent directory>/team-mode-models.json`; a command does not rewrite config or make learned alternatives permanent defaults. The live foreground fallback is not stored as a pool member. Removing the package leaves both user files intact.
61
+ Trusted project settings replace user pool arrays; an explicit `[]` restores foreground inheritance. For workers, a task’s explicit model wins over the pending `/team model` selection, which wins over the configured default or foreground fallback. Task overrides must be in the pool or match the inherited default; non-default choices need a reason unless selected by `/team model`. Selection uses the matched entry’s thinking level. Learned alternatives and usage live in `<Pi agent directory>/team-mode-models.json`; a command does not rewrite config or make learned alternatives permanent defaults. The live foreground fallback is not stored as a pool member. Removing the package leaves personal profiles, settings and model history intact.
54
62
 
55
63
  `access: null` adds no routine role checks. An optional `access.tools` list selects SDK worker tools; this is not OS isolation. Peer references are profile metadata in this release; workers report to Lead and do not have a separate team-chat feature. The built-in scheduler serializes jobs marked as writers in the shared workspace; worker worktree orchestration and durable job reattachment are not yet implemented.
56
64
 
@@ -71,4 +79,6 @@ Pack releases from this nested directory with `npm pack` (without `--ignore-scri
71
79
 
72
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.
73
81
 
74
- 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 first-dispatch creation, reuse after `/reload`, Engineer and Research 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.
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.
83
+
84
+ 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/config.js CHANGED
@@ -1,41 +1,18 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import { modelRef } from './models.js';
4
+ import { copyTemplate, starterProfiles } from './profile-templates.js';
5
+ import { readPersonalProfiles } from './profile-store.js';
4
6
  export function resolvePoolEntry(entry, aliases) {
5
7
  return typeof entry === 'string' ? { ...modelRef(entry, aliases), thinkingLevel: undefined }
6
8
  : { ...modelRef(entry.model, aliases), thinkingLevel: entry.thinkingLevel };
7
9
  }
8
10
  const DEFAULT_CONCURRENCY = 5;
9
11
  const MAX_CONCURRENCY = 20;
10
- const worker = (name, workScope, personality) => ({ name, workScope, personality, peers: ['lead'], enable: true, access: null, modelPool: [] });
11
- const profile = (name, leadScope, roles) => ({
12
- name, roles: { lead: { ...worker('Team Lead', leadScope, 'decisive'), peers: Object.keys(roles) }, ...roles },
13
- });
12
+ // Keep the old fallback layer so sparse files and read-only homes remain runnable.
14
13
  export function defaults() {
15
- const engineer = profile('Engineer', 'Coordinate workers individually. Receive their results and handle follow-ups yourself, without convening meetings. Prefer one worker for a bounded fix; add specialists only when useful.', {
16
- arch: worker('Architecture', 'Identify interfaces, invariants and design trade-offs.', 'deliberate'),
17
- scout: worker('Scout', 'Locate relevant files and symbols quickly.', 'direct'),
18
- reviewer: worker('Reviewer', 'Assess the change for regressions and correctness.', 'skeptical'),
19
- coder: worker('Coder', 'Investigate, implement and verify the assigned change.', 'pragmatic'),
20
- validator: worker('Validator', 'Select and run useful checks; report coverage and failures.', 'exacting'),
21
- analyzer: worker('Analyzer', 'Diagnose ambiguous failures or performance signals.', 'analytical'),
22
- });
23
- return { schemaVersion: 1, enabled: true, defaultProfile: 'engineer', concurrency: DEFAULT_CONCURRENCY, aliases: {}, profiles: {
24
- engineer,
25
- research: profile('Research', 'Frame questions, parallelize independent inquiries, and reconcile evidence with citations.', {
26
- arch: worker('Architecture', 'Design an inquiry and source criteria.', 'deliberate'),
27
- researcher: worker('Researcher', 'Find primary sources and report citations and uncertainty.', 'curious'),
28
- coder: worker('Coder', 'Build analysis scripts or research artifacts as needed.', 'pragmatic'),
29
- validator: worker('Validator', 'Check reproducibility and provenance.', 'exacting'),
30
- reviewer: worker('Reviewer', 'Challenge conclusions and verify important claims.', 'skeptical'),
31
- }),
32
- audit: profile('Audit', 'Clarify scope, prioritize findings by impact, and disclose coverage gaps.', {
33
- arch: worker('Architecture', 'Map relevant controls and boundaries.', 'methodical'),
34
- analyzer: worker('Analyzer', 'Gather evidence and recommend mitigations; do not remediate.', 'analytical'),
35
- reviewer: worker('Reviewer', 'Independently evaluate findings and their confidence.', 'skeptical'),
36
- validator: worker('Validator', 'Use evidence and non-invasive checks to confirm findings.', 'exacting'),
37
- }),
38
- } };
14
+ return { schemaVersion: 1, enabled: true, defaultProfile: 'engineer', concurrency: DEFAULT_CONCURRENCY, aliases: {},
15
+ profiles: Object.fromEntries(Object.entries(starterProfiles).map(([id, template]) => [id, copyTemplate(template)])) };
39
16
  }
40
17
  const obj = (value, path) => {
41
18
  if (!value || typeof value !== 'object' || Array.isArray(value))
@@ -108,8 +85,10 @@ function overlay(base, extra) {
108
85
  }
109
86
  return result;
110
87
  }
111
- export function parseConfig(user = {}, project = {}) {
112
- const u = overlay(defaults(), obj(user, 'user config'));
88
+ export function parseConfig(user = {}, project = {}, personalProfiles = {}) {
89
+ const base = defaults();
90
+ // A saved profile is a snapshot, not a patch to newer template content.
91
+ const u = overlay({ ...base, profiles: { ...base.profiles, ...personalProfiles } }, obj(user, 'user config'));
113
92
  const p = obj(project, 'project config');
114
93
  const raw = overlay(u, p);
115
94
  if (raw.schemaVersion !== 1)
@@ -131,7 +110,7 @@ export function parseConfig(user = {}, project = {}) {
131
110
  throw Error(`${rp}.access: only a tool allowlist is currently supported`);
132
111
  access = { tools: list(rule.tools, `${rp}.access.tools`) };
133
112
  }
134
- const userRole = (u.profiles[id]?.roles[rid]);
113
+ const userRole = u.profiles?.[id]?.roles?.[rid];
135
114
  if (userRole?.access?.tools && (!access || access.tools.some(t => !userRole.access.tools.includes(t)))) {
136
115
  throw Error(`${rp}.access: project cannot widen the user tool allowlist`);
137
116
  }
@@ -160,9 +139,9 @@ export function parseConfig(user = {}, project = {}) {
160
139
  export function configPaths(agentDir, cwd) {
161
140
  return { user: join(agentDir, 'team-mode.json'), project: join(cwd, '.pi', 'team-mode.json') };
162
141
  }
163
- function read(path) {
142
+ function readConfigJSON(path, source) {
164
143
  try {
165
- return JSON.parse(readFileSync(path, 'utf8'));
144
+ return JSON.parse(source ?? readFileSync(path, 'utf8'));
166
145
  }
167
146
  catch (err) {
168
147
  if (err.code === 'ENOENT')
@@ -170,7 +149,13 @@ function read(path) {
170
149
  throw Error(`${path}: ${String(err)}`);
171
150
  }
172
151
  }
173
- export function loadConfig(agentDir, cwd, trusted) {
152
+ export function configInputs(agentDir, cwd, trusted, edit) {
174
153
  const paths = configPaths(agentDir, cwd);
175
- return parseConfig(read(paths.user), trusted ? read(paths.project) : {});
154
+ return { user: readConfigJSON(paths.user, edit?.project === false ? edit.source : undefined),
155
+ project: trusted ? readConfigJSON(paths.project, edit?.project ? edit.source : undefined) : {},
156
+ personal: readPersonalProfiles(agentDir) };
157
+ }
158
+ export function loadConfig(agentDir, cwd, trusted) {
159
+ const { user, project, personal } = configInputs(agentDir, cwd, trusted);
160
+ return parseConfig(user, project, personal);
176
161
  }
package/dist/extension.js CHANGED
@@ -4,7 +4,9 @@ import { fileURLToPath } from 'node:url';
4
4
  import { Type } from 'typebox';
5
5
  import { clampThinkingLevel } from '@earendil-works/pi-ai';
6
6
  import { getAgentDir } from '@earendil-works/pi-coding-agent';
7
- import { configPaths, defaults, loadConfig, resolvePoolEntry } from './config.js';
7
+ import { configInputs, configPaths, defaults, loadConfig, parseConfig, resolvePoolEntry } from './config.js';
8
+ import { createProfile, seedProfiles } from './profiles.js';
9
+ import { templateIds } from './profile-templates.js';
8
10
  import { ModelPools, modelRef } from './models.js';
9
11
  import { NativeBackend, SubagentsBackend } from './backend.js';
10
12
  import { Scheduler, summaryText } from './scheduler.js';
@@ -13,6 +15,21 @@ import { checkForUpdate } from './update.js';
13
15
  import { ensureWorkerType, roleBody, workerRules } from './worker-agents.js';
14
16
  const keys = ['team_dispatch', 'team_results', 'team_publish'];
15
17
  const statusKey = 'team-mode';
18
+ const createUsage = 'Usage: /team profile create <id> --from <template>';
19
+ const modelUsage = 'Usage: /team model <role> <provider/model-id> (or configured alias)';
20
+ const configUsage = 'Usage: /team config edit [project] | validate | reload';
21
+ const teamHelp = [
22
+ '/team — open the Team Mode menu',
23
+ '/team profile [<id>] — pick or switch profiles',
24
+ '/team profile create <id> --from <template> — save a personal copy',
25
+ `Templates: ${templateIds.join(', ')}`,
26
+ '/team on | off | status | cancel | reset | doctor',
27
+ '/team model [<role> [<provider/model-id>]] — pick or select a role model',
28
+ '/team config edit [project] | validate | reload',
29
+ '/team help — show these commands',
30
+ ].join('\n');
31
+ const interactive = (ctx) => ctx.hasUI && ctx.mode === 'tui';
32
+ const errorMessage = (err) => err instanceof Error ? err.message : String(err);
16
33
  const TaskInput = Type.Object({ id: Type.String(), role: Type.String(), brief: Type.String(),
17
34
  dependsOn: Type.Optional(Type.Array(Type.String())), writes: Type.Optional(Type.Boolean()),
18
35
  model: Type.Optional(Type.String()), modelReason: Type.Optional(Type.String()), resume: Type.Optional(Type.String()) });
@@ -171,6 +188,7 @@ export default function teamExtension(pi) {
171
188
  }
172
189
  async function activate(ctx) {
173
190
  foreground = ctx;
191
+ native ??= new NativeBackend(ctx.cwd, agentDir);
174
192
  if (!enabled) {
175
193
  priorModel = ctx.model;
176
194
  priorThinking = pi.getThinkingLevel();
@@ -184,7 +202,7 @@ export default function teamExtension(pi) {
184
202
  await setLeadModel(leadDefault.ref, leadDefault.thinkingLevel, ctx);
185
203
  }
186
204
  catch (e) {
187
- ctx.ui.notify(`${String(e)}; using the current Pi model and thinking level.`, 'warning');
205
+ ctx.ui.notify(`${errorMessage(e)}; using the current Pi model and thinking level.`, 'warning');
188
206
  }
189
207
  }
190
208
  reportStatus(ctx);
@@ -209,8 +227,12 @@ export default function teamExtension(pi) {
209
227
  priorThinking = undefined;
210
228
  }
211
229
  async function switchProfile(name, ctx) {
212
- if (!Object.hasOwn(config.profiles, name))
213
- throw Error(`Unknown profile: ${name}`);
230
+ if (!Object.hasOwn(config.profiles, name)) {
231
+ const hint = name === 'status' ? 'Use /team status to show Team status.' : 'Use /team profile to pick a profile.';
232
+ throw Error(`Unknown profile: ${name}. ${hint}`);
233
+ }
234
+ if (scheduler?.active)
235
+ throw Error('Wait for current tasks to finish before switching profiles, or use /team cancel.');
214
236
  scheduler?.reset();
215
237
  scheduler?.dispose();
216
238
  scheduler = undefined;
@@ -221,6 +243,104 @@ export default function teamExtension(pi) {
221
243
  queued = false;
222
244
  await activate(ctx);
223
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');
250
+ }
251
+ async function pickProfile(ctx) {
252
+ if (!interactive(ctx))
253
+ throw Error('Usage: /team profile <id>. Use an interactive Pi TUI to pick a profile.');
254
+ const choice = await ctx.ui.select(`Switch profile (selected: ${selected})`, Object.keys(config.profiles));
255
+ if (choice !== undefined)
256
+ await switchProfile(choice, ctx);
257
+ }
258
+ function checkCanCreate(ctx) {
259
+ if (!interactive(ctx))
260
+ throw Error('Create a profile in an interactive Pi TUI.');
261
+ if (scheduler?.active)
262
+ throw Error('Wait for current tasks to finish before creating a profile.');
263
+ }
264
+ function saveProfile(id, template, ctx) {
265
+ checkCanCreate(ctx);
266
+ if (Object.hasOwn(config.profiles, id))
267
+ throw Error(`Profile ${id} already exists; nothing changed.`);
268
+ const created = createProfile(agentDir, ctx.cwd, ctx.isProjectTrusted(), id, template);
269
+ config.profiles[id] = created.profile;
270
+ ctx.ui.notify(`Created profile ${id} at ${created.path}; switch with /team profile ${id}.`, 'info');
271
+ }
272
+ async function pickTemplate(ctx) {
273
+ checkCanCreate(ctx);
274
+ const template = await ctx.ui.select('Choose a profile template', [...templateIds]);
275
+ if (template === undefined)
276
+ return;
277
+ const name = await ctx.ui.input('New profile ID (lowercase letters, digits, _ or -)', 'my-engineering');
278
+ if (name === undefined)
279
+ return;
280
+ const id = name.trim();
281
+ saveProfile(id, template, ctx);
282
+ if (await ctx.ui.confirm('Switch to the new profile?', `Select ${id} and turn Team Mode on now?`))
283
+ await switchProfile(id, ctx);
284
+ }
285
+ const modelRoles = () => Object.entries(roles().roles).filter(([, role]) => role.enable).map(([id]) => id);
286
+ function checkModelRole(role) {
287
+ if (!modelRoles().includes(role))
288
+ throw Error(`Unknown or disabled role: ${role}. Enabled roles: ${modelRoles().join(', ')}.\n${modelUsage}`);
289
+ if (role === 'lead' && !enabled)
290
+ throw Error('Enable Team Mode with /team on before switching its Lead model.');
291
+ }
292
+ async function chooseModel(role, ref, ctx) {
293
+ const configured = configuredPool(role);
294
+ if (role === 'lead')
295
+ await setLeadModel(ref, configured.find(entry => entry.ref === ref)?.thinkingLevel, ctx);
296
+ const list = pools.add(selected, role, configured.map(entry => entry.ref), ref);
297
+ if (role !== 'lead')
298
+ nextModel.set(`${selected}/${role}`, ref);
299
+ ctx.ui.notify(`Selected ${ref} for ${role}: ${list.join(', ')}`, 'info');
300
+ }
301
+ async function configureModel(ctx, role, value) {
302
+ if (error)
303
+ throw Error(`${error}; see /team doctor.`);
304
+ if (value !== undefined && role !== undefined) {
305
+ 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}`);
309
+ await chooseModel(role, ref, ctx);
310
+ return;
311
+ }
312
+ if (!interactive(ctx))
313
+ throw Error(`${modelUsage}. Enabled roles: ${modelRoles().join(', ')}.`);
314
+ role ??= await ctx.ui.select(`Choose a role (${selected})`, modelRoles());
315
+ if (role === undefined)
316
+ return;
317
+ checkModelRole(role);
318
+ const refs = [...new Set(ctx.modelRegistry.getAvailable().map(m => `${m.provider}/${m.id}`))].sort();
319
+ if (!refs.length)
320
+ throw Error('No models available. Configure a provider in Pi, then retry /team model.');
321
+ const ref = await ctx.ui.select(`Choose a model for ${role}`, refs);
322
+ if (ref !== undefined)
323
+ await chooseModel(role, ref, ctx);
324
+ }
325
+ async function mainMenu(ctx) {
326
+ if (!interactive(ctx)) {
327
+ ctx.ui.notify(teamHelp, 'info');
328
+ return;
329
+ }
330
+ const toggle = enabled ? 'Turn Team Mode off' : 'Turn Team Mode on';
331
+ const choice = await ctx.ui.select(`Team Mode (${enabled ? 'on' : 'off'} · ${selected})`, [
332
+ 'Switch profile', 'Create profile from template', toggle, 'Status', 'Configure role model', 'Help',
333
+ ]);
334
+ switch (choice) {
335
+ case 'Switch profile': return pickProfile(ctx);
336
+ case 'Create profile from template': return pickTemplate(ctx);
337
+ case 'Turn Team Mode off': return disable(ctx);
338
+ case 'Turn Team Mode on': return activate(ctx);
339
+ case 'Status': return showStatus(ctx);
340
+ case 'Configure role model': return configureModel(ctx);
341
+ case 'Help': ctx.ui.notify(teamHelp, 'info');
342
+ }
343
+ }
224
344
  let updateCheck;
225
345
  pi.on('session_start', async (event, ctx) => {
226
346
  foreground = ctx;
@@ -236,10 +356,20 @@ export default function teamExtension(pi) {
236
356
  }
237
357
  native = new NativeBackend(ctx.cwd, agentDir);
238
358
  try {
239
- config = loadConfig(agentDir, ctx.cwd, ctx.isProjectTrusted());
359
+ const trusted = ctx.isProjectTrusted();
360
+ const inputs = configInputs(agentDir, ctx.cwd, trusted);
361
+ config = parseConfig(inputs.user, inputs.project, inputs.personal);
362
+ error = undefined;
363
+ try {
364
+ if (seedProfiles(agentDir, inputs))
365
+ config = loadConfig(agentDir, ctx.cwd, trusted);
366
+ }
367
+ catch (err) {
368
+ ctx.ui.notify(`Could not seed personal team profiles: ${errorMessage(err)}`, 'warning');
369
+ }
240
370
  }
241
371
  catch (err) {
242
- error = String(err);
372
+ error = errorMessage(err);
243
373
  ctx.ui.notify(error, 'error');
244
374
  }
245
375
  selected = config.defaultProfile;
@@ -324,24 +454,40 @@ export default function teamExtension(pi) {
324
454
  publishing = false;
325
455
  }
326
456
  } });
327
- pi.registerCommand('team', { description: 'Manage team mode: on, off, profile, status, cancel, doctor, model, config',
457
+ pi.registerCommand('team', { description: 'Team Mode menu; use /team help for direct commands',
328
458
  async handler(args, ctx) {
329
- const [command, arg, ...rest] = args.trim().split(/\s+/);
459
+ const input = args.trim();
460
+ const [command, arg, ...rest] = input ? input.split(/\s+/) : [];
330
461
  try {
331
- if (!command) {
332
- const names = Object.keys(config.profiles);
333
- const choice = await ctx.ui.select('Team profile', names);
334
- if (choice)
335
- await switchProfile(choice, ctx);
462
+ if (/[\r\n]/.test(input))
463
+ throw Error('Run one /team command at a time. Use /team help for available commands.');
464
+ if (!command)
465
+ return await mainMenu(ctx);
466
+ if (arg !== undefined && ['help', 'on', 'off', 'status', 'cancel', 'reset', 'doctor'].includes(command)) {
467
+ throw Error(`Usage: /team ${command}`);
336
468
  }
337
- else if (command === 'on') {
338
- native ??= new NativeBackend(ctx.cwd, agentDir);
469
+ if (command === 'help')
470
+ ctx.ui.notify(teamHelp, 'info');
471
+ else if (command === 'on')
339
472
  await activate(ctx);
340
- }
341
473
  else if (command === 'off')
342
474
  await disable(ctx);
343
- else if (command === 'profile')
344
- await switchProfile(arg, ctx);
475
+ else if (command === 'profile') {
476
+ if (arg === undefined)
477
+ await pickProfile(ctx);
478
+ // A lone 'create' still switches to a legacy profile with that ID.
479
+ else if (arg === 'create' && (rest.length || !Object.hasOwn(config.profiles, arg))) {
480
+ if (rest.length !== 3 || rest[1] !== '--from') {
481
+ throw Error(`${createUsage}\nTemplates: ${templateIds.join(', ')}`);
482
+ }
483
+ const [id, , template] = rest;
484
+ saveProfile(id, template, ctx);
485
+ }
486
+ else if (rest.length)
487
+ throw Error(`Usage: /team profile <id>\n${createUsage}`);
488
+ else
489
+ await switchProfile(arg, ctx);
490
+ }
345
491
  else if (command === 'cancel') {
346
492
  publicationGeneration++;
347
493
  pending = undefined;
@@ -355,38 +501,28 @@ export default function teamExtension(pi) {
355
501
  pending = undefined;
356
502
  queued = false;
357
503
  }
358
- else if (command === 'status') {
359
- const jobs = scheduler?.list().map(j => `${j.task.id}: ${j.state}`).join('\n');
360
- ctx.ui.notify(`Team: ${enabled ? roles().name : 'off'}${jobs ? `\n${jobs}` : ''}`, 'info');
361
- }
504
+ else if (command === 'status')
505
+ showStatus(ctx);
362
506
  else if (command === 'doctor') {
363
507
  const available = await external.probe();
364
508
  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');
365
509
  }
366
- else if (command === 'model') {
367
- if (!roles().roles[arg]?.enable || !rest.length)
368
- throw Error('Usage: /team model <role> <provider/model-id>');
369
- const { provider, id, ref } = modelRef(rest.join(' '), config.aliases);
370
- if (!ctx.modelRegistry.getAvailable().some(m => m.provider === provider && m.id === id))
371
- throw Error(`Model unavailable: ${ref}`);
372
- if (arg === 'lead' && !enabled)
373
- throw Error('Enable Team Mode before switching its Lead model');
374
- const configured = configuredPool(arg);
375
- if (arg === 'lead')
376
- await setLeadModel(ref, configured.find(entry => entry.ref === ref)?.thinkingLevel, ctx);
377
- const list = pools.add(selected, arg, configured.map(entry => entry.ref), ref);
378
- if (arg !== 'lead')
379
- nextModel.set(`${selected}/${arg}`, ref);
380
- ctx.ui.notify(`Selected ${ref} for ${arg}: ${list.join(', ')}`, 'info');
381
- }
382
- else if (command === 'config' && arg === 'validate') {
383
- loadConfig(agentDir, ctx.cwd, ctx.isProjectTrusted());
384
- ctx.ui.notify('Team configuration OK', 'info');
385
- }
386
- else if (command === 'config' && (arg === 'reload' || arg === 'edit')) {
510
+ else if (command === 'model')
511
+ await configureModel(ctx, arg, rest.length ? rest.join(' ') : undefined);
512
+ else if (command === 'config') {
513
+ if (arg === 'validate' && !rest.length) {
514
+ loadConfig(agentDir, ctx.cwd, ctx.isProjectTrusted());
515
+ ctx.ui.notify('Team configuration OK', 'info');
516
+ return;
517
+ }
518
+ const validEdit = arg === 'edit' && (!rest.length || (rest.length === 1 && rest[0] === 'project'));
519
+ if (!validEdit && !(arg === 'reload' && !rest.length))
520
+ throw Error(configUsage);
387
521
  if (scheduler?.active)
388
522
  throw Error('Wait for current tasks to finish before changing team config');
389
- if (arg === 'edit') {
523
+ if (validEdit) {
524
+ if (!interactive(ctx))
525
+ throw Error('Edit Team configuration in an interactive Pi TUI, or edit the JSON file directly.');
390
526
  const paths = configPaths(agentDir, ctx.cwd);
391
527
  const isProject = rest[0] === 'project';
392
528
  if (isProject && !ctx.isProjectTrusted())
@@ -403,7 +539,8 @@ export default function teamExtension(pi) {
403
539
  const next = await ctx.ui.editor(`Edit ${path}`, source);
404
540
  if (next === undefined)
405
541
  return;
406
- JSON.parse(next);
542
+ const inputs = configInputs(agentDir, ctx.cwd, ctx.isProjectTrusted(), { project: isProject, source: next });
543
+ parseConfig(inputs.user, inputs.project, inputs.personal);
407
544
  mkdirSync(dirname(path), { recursive: true });
408
545
  writeFileSync(path, next.endsWith('\n') ? next : `${next}\n`);
409
546
  }
@@ -422,10 +559,10 @@ export default function teamExtension(pi) {
422
559
  ctx.ui.notify('Team configuration reloaded', 'info');
423
560
  }
424
561
  else
425
- throw Error('Usage: /team [on|off|profile <id>|status|cancel|reset|doctor|model|config]');
562
+ throw Error(`Unknown /team command: ${command}. Use /team help for available commands.`);
426
563
  }
427
564
  catch (err) {
428
- ctx.ui.notify(String(err), 'error');
565
+ ctx.ui.notify(errorMessage(err), 'error');
429
566
  }
430
567
  } });
431
568
  }
@@ -0,0 +1,85 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { constants, closeSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ const errorCode = (err) => err.code;
5
+ const profileIdPattern = /^[a-z0-9][a-z0-9_-]{0,63}$/;
6
+ export const validProfileId = (id) => profileIdPattern.test(id) && id !== 'constructor' && id !== 'prototype';
7
+ export const profilePath = (agentDir, id) => join(agentDir, 'team-mode-profiles', `${id}.json`);
8
+ const directory = (agentDir) => join(agentDir, 'team-mode-profiles');
9
+ function checkDirectory(dir) {
10
+ if (!lstatSync(dir).isDirectory())
11
+ throw Error(`${dir}: expected a real directory`);
12
+ }
13
+ /** Only full personal profiles, never project files or stock agent definitions. */
14
+ export function readPersonalProfiles(agentDir) {
15
+ const dir = directory(agentDir);
16
+ const profiles = Object.create(null);
17
+ let names;
18
+ try {
19
+ checkDirectory(dir);
20
+ names = readdirSync(dir).sort();
21
+ }
22
+ catch (err) {
23
+ if (errorCode(err) === 'ENOENT')
24
+ return profiles;
25
+ throw err;
26
+ }
27
+ for (const name of names) {
28
+ if (!name.endsWith('.json') || name.startsWith('.'))
29
+ continue;
30
+ const id = name.slice(0, -5);
31
+ const path = join(dir, name);
32
+ if (!validProfileId(id))
33
+ throw Error(`${path}: invalid profile ID`);
34
+ try {
35
+ if (!lstatSync(path).isFile())
36
+ throw Error('expected a regular file');
37
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
38
+ try {
39
+ if (!fstatSync(fd).isFile())
40
+ throw Error('expected a regular file');
41
+ profiles[id] = JSON.parse(readFileSync(fd, 'utf8'));
42
+ }
43
+ finally {
44
+ closeSync(fd);
45
+ }
46
+ }
47
+ catch (err) {
48
+ if (errorCode(err) === 'ENOENT')
49
+ continue; // Deleted during discovery.
50
+ throw Error(`${path}: ${String(err)}`);
51
+ }
52
+ }
53
+ return profiles;
54
+ }
55
+ /** Publish a complete file atomically, without ever replacing the destination. */
56
+ export function publishProfile(agentDir, id, profile) {
57
+ if (!validProfileId(id))
58
+ throw Error(`Invalid profile ID: ${id}`);
59
+ const dir = directory(agentDir);
60
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
61
+ checkDirectory(dir);
62
+ const temp = join(dir, `.pending-${randomUUID()}`);
63
+ const fd = openSync(temp, 'wx', 0o600);
64
+ try {
65
+ try {
66
+ writeFileSync(fd, `${JSON.stringify(profile, null, 2)}\n`);
67
+ fsyncSync(fd);
68
+ }
69
+ finally {
70
+ closeSync(fd);
71
+ }
72
+ try {
73
+ linkSync(temp, profilePath(agentDir, id));
74
+ }
75
+ catch (err) {
76
+ if (errorCode(err) === 'EEXIST')
77
+ return false;
78
+ throw err;
79
+ }
80
+ return true;
81
+ }
82
+ finally {
83
+ unlinkSync(temp);
84
+ }
85
+ }
@@ -0,0 +1,46 @@
1
+ // Not a source of runnable IDs. Only detached copies leave this module.
2
+ const worker = (name, workScope, personality) => ({ name, workScope, personality, peers: ['lead'], enable: true, access: null, modelPool: [] });
3
+ const profile = (name, leadScope, roles) => ({
4
+ name, roles: { lead: { ...worker('Team Lead', leadScope, 'decisive'), peers: Object.keys(roles) }, ...roles },
5
+ });
6
+ function catalog() {
7
+ const engineer = profile('Engineer', 'Coordinate workers individually. Receive their results and handle follow-ups yourself, without convening meetings. Prefer one worker for a bounded fix; add specialists only when useful.', {
8
+ arch: worker('Architecture', 'Identify interfaces, invariants and design trade-offs.', 'deliberate'),
9
+ scout: worker('Scout', 'Locate relevant files and symbols quickly.', 'direct'),
10
+ reviewer: worker('Reviewer', 'Assess the change for regressions and correctness.', 'skeptical'),
11
+ coder: worker('Coder', 'Investigate, implement and verify the assigned change.', 'pragmatic'),
12
+ validator: worker('Validator', 'Select and run useful checks; report coverage and failures.', 'exacting'),
13
+ analyzer: worker('Analyzer', 'Diagnose ambiguous failures or performance signals.', 'analytical'),
14
+ });
15
+ return {
16
+ engineer_template: engineer,
17
+ research_template: profile('Research', 'Frame questions, parallelize independent inquiries, and reconcile evidence with citations.', {
18
+ arch: worker('Architecture', 'Design an inquiry and source criteria.', 'deliberate'),
19
+ researcher: worker('Researcher', 'Find primary sources and report citations and uncertainty.', 'curious'),
20
+ coder: worker('Coder', 'Build analysis scripts or research artifacts as needed.', 'pragmatic'),
21
+ validator: worker('Validator', 'Check reproducibility and provenance.', 'exacting'),
22
+ reviewer: worker('Reviewer', 'Challenge conclusions and verify important claims.', 'skeptical'),
23
+ }),
24
+ audit_template: profile('Audit', 'Clarify scope, prioritize findings by impact, and disclose coverage gaps.', {
25
+ arch: worker('Architecture', 'Map relevant controls and boundaries.', 'methodical'),
26
+ analyzer: worker('Analyzer', 'Gather evidence and recommend mitigations; do not remediate.', 'analytical'),
27
+ reviewer: worker('Reviewer', 'Independently evaluate findings and their confidence.', 'skeptical'),
28
+ validator: worker('Validator', 'Use evidence and non-invasive checks to confirm findings.', 'exacting'),
29
+ }),
30
+ };
31
+ }
32
+ const freeze = (value) => {
33
+ for (const child of Object.values(value))
34
+ if (child && typeof child === 'object')
35
+ freeze(child);
36
+ Object.freeze(value);
37
+ };
38
+ const templates = catalog();
39
+ freeze(templates);
40
+ export const starterProfiles = Object.freeze({ engineer: 'engineer_template', research: 'research_template', audit: 'audit_template' });
41
+ export const templateIds = Object.freeze(Object.keys(templates));
42
+ export function copyTemplate(id) {
43
+ if (!Object.hasOwn(templates, id))
44
+ throw Error(`Unknown template ${id}; choose ${templateIds.join(', ')}`);
45
+ return structuredClone(templates[id]);
46
+ }
@@ -0,0 +1,35 @@
1
+ import { configInputs, parseConfig } from './config.js';
2
+ import { profilePath, publishProfile, validProfileId } from './profile-store.js';
3
+ import { copyTemplate, starterProfiles, templateIds } from './profile-templates.js';
4
+ /** Backfill missing personal slots only. Existing inline entries count even if sparse. */
5
+ export function seedProfiles(agentDir, inputs) {
6
+ const { user, project, personal } = inputs;
7
+ parseConfig(user, project, personal);
8
+ const inline = user.profiles ?? {};
9
+ const additions = Object.entries(starterProfiles)
10
+ .filter(([id]) => !Object.hasOwn(inline, id) && !Object.hasOwn(personal, id))
11
+ .map(([id, template]) => [id, copyTemplate(template)]);
12
+ if (!additions.length)
13
+ return false;
14
+ const next = { ...personal, ...Object.fromEntries(additions) };
15
+ parseConfig(user, {}, personal);
16
+ parseConfig(user, project, next);
17
+ for (const [id, profile] of additions)
18
+ publishProfile(agentDir, id, profile);
19
+ return true; // Re-read even if another Pi process won a file creation race.
20
+ }
21
+ export function createProfile(agentDir, cwd, trusted, id, template) {
22
+ if (!validProfileId(id) || templateIds.includes(id)) {
23
+ throw Error('Use a new lowercase profile ID (1–64 letters, digits, underscores or hyphens, starting with a letter or digit); template IDs are reserved.');
24
+ }
25
+ const profile = copyTemplate(template);
26
+ const { user, project, personal } = configInputs(agentDir, cwd, trusted);
27
+ const current = parseConfig(user, project, personal);
28
+ if (Object.hasOwn(current.profiles, id))
29
+ throw Error(`Profile ${id} already exists; nothing changed.`);
30
+ parseConfig(user, {}, personal);
31
+ const next = parseConfig(user, project, { ...personal, [id]: profile });
32
+ if (!publishProfile(agentDir, id, profile))
33
+ throw Error(`Profile ${id} already exists at ${profilePath(agentDir, id)}; nothing changed.`);
34
+ return { profile: next.profiles[id], path: profilePath(agentDir, id) };
35
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-team-mode",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "Efficiency-first teams for Pi with background workers and a foreground Team Lead",
5
5
  "license": "MIT",
6
6
  "repository": {