pi-team-mode 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 sxu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,68 @@
1
- # Temporary Holding Version
1
+ # Pi Team Mode
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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
+
5
+ ## Install
6
+
7
+ The extension targets Pi 1.7.0. Install the npm release with `pi install npm:pi-team-mode`; uninstall it with `pi remove npm:pi-team-mode`.
8
+
9
+ Alternatively, install the GitHub default branch with `pi install git:github.com/flaminigo/pi-team-mode` and remove it with `pi remove git:github.com/flaminigo/pi-team-mode`. For a local checkout use `pi install "$PWD"` and `pi remove "$PWD"` from the **repository root**. The root Pi package loads tracked TypeScript; Git and local root installs do not require `dist/` or a manual build. See the [user manual](https://github.com/flaminigo/pi-team-mode#readme) for examples.
10
+
11
+ This nested directory is the npm packaging target. If installing it directly from a checkout instead of the root, run `npm ci && npm run build` here first, then `pi install "$PWD"`. Use `--local` on both Pi install and remove for a project-scoped registration. Restart Pi or use `/reload` after changing the installation.
12
+
13
+ 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.
14
+
15
+ 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.
16
+
17
+ An existing compatible `@tintinweb/pi-subagents` installation is reused through RPC v2 when it supports the worker’s policy. Otherwise workers run in Pi SDK child sessions; no second install is required. The fallback runs normal core tools, not the foreground's extension catalog. The adapter uses compact handoffs when upstream cannot resume a finished job; SDK sessions can continue a handful of recent tasks. `/team doctor` reports backend availability.
18
+
19
+ ## Use
20
+
21
+ - `/team` opens the profile picker; `/team profile engineer|research|audit` switches directly.
22
+ - `/team on`, `/team off`, `/team status`, `/team cancel`, `/team reset`, `/team doctor`.
23
+ - `/team config edit [project]`, `/team config validate`, `/team config reload`.
24
+ - `/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.
25
+
26
+ 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:
27
+
28
+ ```json
29
+ {
30
+ "schemaVersion": 1,
31
+ "concurrency": 3,
32
+ "profiles": {
33
+ "engineer": {
34
+ "roles": {
35
+ "coder": { "modelPool": [{ "model": "provider/model-id", "thinkingLevel": "high" }, "provider/alternate-id"], "access": null },
36
+ "scout": { "access": { "tools": ["read", "grep", "find", "ls"] } }
37
+ }
38
+ }
39
+ }
40
+ }
41
+ ```
42
+
43
+ Every built-in pool in Engineer, Research, and Audit is empty. A blank Lead pool leaves Pi’s current model and thinking level alone, including when switching from a profile that set them. Blank worker pools inherit live foreground thinking at worker start, even for queued dependents; the live foreground model is the default. The first entry in a nonempty configured pool is the default: Lead applies it on activation, profile switch or config reload, and workers use it instead of inheriting. An unavailable configured Lead model warns and leaves the current model and level unchanged. `/team off` restores the pre-Team model and thinking level without changing Pi defaults.
44
+
45
+ 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.
46
+
47
+ 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.
48
+
49
+ `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.
50
+
51
+ ### Serious actions
52
+
53
+ The Lead can request one approval covering a GitHub push, opening a PR, and requesting review. It operates on a committed revision, verifies the remote and revision, never force-pushes, and does not automatically retry a partial publication. `git` and (for PRs/review) `gh` are needed. Local edits and checks do not ask for approval. Checkpoints cover Team Mode's brokered operations only: normal shell tools are not a sandbox and ambient account credentials can bypass a broker. Advanced isolation and custom checkpoint handlers are not part of this release.
54
+
55
+ ## Test without model credits
56
+
57
+ ```sh
58
+ npm ci # from this nested directory
59
+ npm test # fake workers, mocked remote actions, loopback-only fake model
60
+ npm run test:pi # real Pi TUI lifecycle, using the nested build
61
+ npm pack --dry-run # preview release contents; does not publish
62
+ ```
63
+
64
+ 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.
65
+
66
+ 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.
67
+
68
+ To exercise the RPC adapter in the real TUI, set `PI_TEAM_TEST_SUBAGENTS` to the absolute path of a local compatible `pi-subagents` package before running `npm run test:pi`. 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. This checks Git install, manual update, reload, and removal without contacting GitHub or a model service. All smoke paths use a disposable Pi config and fake credentials.
@@ -0,0 +1,218 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { createAgentSession, DefaultResourceLoader, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
3
+ export class NativeBackend {
4
+ cwd;
5
+ agentDir;
6
+ retained = new Map();
7
+ running = new Set();
8
+ closed = false;
9
+ constructor(cwd, agentDir) {
10
+ this.cwd = cwd;
11
+ this.agentDir = agentDir;
12
+ }
13
+ canResume(token, role, model, tools) {
14
+ const prior = this.retained.get(token);
15
+ return !!prior && prior.role === role && prior.model === model && prior.tools === JSON.stringify(tools);
16
+ }
17
+ async run(work, signal) {
18
+ signal.throwIfAborted();
19
+ if (this.closed)
20
+ throw Error('Worker backend closed');
21
+ const model = `${work.model.provider}/${work.model.id}`;
22
+ const tools = JSON.stringify(work.tools);
23
+ const prior = work.resume ? this.retained.get(work.resume) : undefined;
24
+ let session;
25
+ if (prior && prior.role === work.role && prior.model === model && prior.tools === tools) {
26
+ this.retained.delete(work.resume);
27
+ session = prior.session;
28
+ }
29
+ else {
30
+ const settingsManager = SettingsManager.inMemory({ retry: { enabled: true, maxRetries: 1 } });
31
+ const resourceLoader = new DefaultResourceLoader({ cwd: this.cwd, agentDir: this.agentDir, settingsManager,
32
+ noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true });
33
+ await resourceLoader.reload();
34
+ signal.throwIfAborted();
35
+ ({ session } = await createAgentSession({ cwd: this.cwd, agentDir: this.agentDir, model: work.model,
36
+ thinkingLevel: work.thinkingLevel, tools: work.tools, sessionManager: SessionManager.inMemory(this.cwd), settingsManager, resourceLoader }));
37
+ }
38
+ this.running.add(session);
39
+ const stop = () => { void session.abort().catch(() => { }); };
40
+ signal.addEventListener('abort', stop, { once: true });
41
+ let retain = false;
42
+ try {
43
+ signal.throwIfAborted();
44
+ if (this.closed)
45
+ throw Error('Worker backend closed');
46
+ if (work.tools && (session.getActiveToolNames().length !== work.tools.length || work.tools.some(tool => !session.getActiveToolNames().includes(tool)))) {
47
+ throw Error('At least one configured worker tool is unavailable');
48
+ }
49
+ if (session === prior?.session && work.thinkingLevel !== undefined)
50
+ session.setThinkingLevel(work.thinkingLevel);
51
+ const start = session.messages.length;
52
+ work.started();
53
+ await session.prompt(work.prompt, { expandPromptTemplates: false });
54
+ signal.throwIfAborted();
55
+ const last = session.messages.slice(start).findLast(m => m.role === 'assistant');
56
+ 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.' };
58
+ }
59
+ retain = !this.closed;
60
+ if (retain) {
61
+ this.retained.set(work.id, { session, role: work.role, model, tools });
62
+ if (this.retained.size > 6) {
63
+ const [id, oldest] = this.retained.entries().next().value;
64
+ oldest.session.dispose();
65
+ this.retained.delete(id);
66
+ }
67
+ }
68
+ return workerResult(session.getLastAssistantText() || 'Worker completed without a summary.', retain ? work.id : undefined);
69
+ }
70
+ finally {
71
+ signal.removeEventListener('abort', stop);
72
+ this.running.delete(session);
73
+ if (!retain)
74
+ session.dispose();
75
+ }
76
+ }
77
+ dispose() {
78
+ this.closed = true;
79
+ for (const session of this.running)
80
+ void session.abort().catch(() => { });
81
+ for (const { session } of this.retained.values())
82
+ session.dispose();
83
+ this.retained.clear();
84
+ }
85
+ }
86
+ export function workerResult(text, resume) {
87
+ const marker = /^\s*(DONE|BLOCKED|FAILED)\s*:\s*/i.exec(text);
88
+ const status = (marker?.[1].toLowerCase() ?? 'done');
89
+ return { status, summary: marker ? text.slice(marker[0].length) : text, resume };
90
+ }
91
+ export class SubagentsBackend {
92
+ bus;
93
+ available = false;
94
+ thinkingSupported = false;
95
+ closed = false;
96
+ subscriptions;
97
+ constructor(bus) {
98
+ this.bus = bus;
99
+ this.subscriptions = [bus.on('subagents:ready', () => { void this.probe(); }),
100
+ bus.on('subagents:disposed', () => { this.available = false; })];
101
+ }
102
+ get ready() { return this.available && !this.closed; }
103
+ supports(work) {
104
+ return this.ready && work.tools === undefined && work.resume === undefined
105
+ && (work.thinkingLevel === undefined || this.thinkingSupported);
106
+ }
107
+ async probe() {
108
+ try {
109
+ const ping = await this.rpc('ping', {}, 200);
110
+ this.available = ping?.version === 2;
111
+ // RPC v2 predates feature discovery. The upstream `get` marker (0.26.2+)
112
+ // identifies builds with documented spawn.options.thinkingLevel forwarding.
113
+ this.thinkingSupported = this.available && Array.isArray(ping.features) && ping.features.includes('get');
114
+ }
115
+ catch {
116
+ this.available = false;
117
+ }
118
+ return this.ready;
119
+ }
120
+ rpc(method, args, timeout = 8000) {
121
+ const requestId = randomUUID();
122
+ return new Promise((resolve, reject) => {
123
+ const channel = `subagents:rpc:${method}`;
124
+ const off = this.bus.on(`${channel}:reply:${requestId}`, value => {
125
+ cleanup();
126
+ const reply = value;
127
+ if (reply.success)
128
+ resolve(reply.data);
129
+ else
130
+ reject(Error(reply.error ?? `${method} failed`));
131
+ });
132
+ const timer = setTimeout(() => { cleanup(); reject(Error(`Subagents ${method} timed out`)); }, timeout);
133
+ function cleanup() { clearTimeout(timer); off(); }
134
+ try {
135
+ this.bus.emit(channel, { requestId, ...args });
136
+ }
137
+ catch (error) {
138
+ cleanup();
139
+ reject(error);
140
+ }
141
+ });
142
+ }
143
+ async run(work, signal) {
144
+ signal.throwIfAborted();
145
+ if (!this.supports(work))
146
+ throw Error('Subagents RPC does not support this worker policy');
147
+ let id;
148
+ let terminal = false;
149
+ let counted = false;
150
+ let stopSent = false;
151
+ let resolve;
152
+ const result = new Promise(r => { resolve = r; });
153
+ const started = () => { if (!counted) {
154
+ counted = true;
155
+ work.started();
156
+ } };
157
+ const finish = (entry) => {
158
+ if (entry.id !== id || terminal)
159
+ return;
160
+ terminal = true;
161
+ if (['completed', 'steered'].includes(entry.status)) {
162
+ started();
163
+ resolve(workerResult(entry.result ?? 'Worker completed without a summary.'));
164
+ }
165
+ else
166
+ resolve({ status: 'failed', summary: entry.error ?? entry.result ?? `Worker ${entry.status}.` });
167
+ // Emit synchronously so the upstream completion notifier sees the consumption.
168
+ void this.rpc('consume', { agentId: id }).catch(() => { });
169
+ };
170
+ const subscription = ['completed', 'failed', 'started'].map(kind => this.bus.on(`subagents:${kind}`, raw => {
171
+ const entry = raw;
172
+ if (kind === 'started') {
173
+ if (entry.id === id)
174
+ started();
175
+ }
176
+ else
177
+ finish(entry);
178
+ }));
179
+ const abort = () => {
180
+ if (!id || terminal || stopSent)
181
+ return;
182
+ stopSent = true;
183
+ void this.rpc('stop', { agentId: id, settleTimeoutMs: 5000 }).then(reply => {
184
+ if (reply.settled)
185
+ resolve({ status: 'failed', summary: 'Worker cancelled.' });
186
+ // If still settling, wait for its terminal event before releasing the writer slot.
187
+ }).catch(() => { });
188
+ };
189
+ signal.addEventListener('abort', abort, { once: true });
190
+ const disposed = this.bus.on('subagents:disposed', () => resolve({ status: 'failed', summary: 'Subagents backend shut down.' }));
191
+ try {
192
+ const bind = (agentId) => { id = agentId; if (signal.aborted)
193
+ abort(); };
194
+ const spawn = await this.rpc('spawn', { type: 'general-purpose', prompt: work.prompt, options: {
195
+ description: `Team: ${work.role} (${work.id})`, model: work.model, isBackground: true,
196
+ inheritContext: false, isolated: true, signal, onSpawned: bind, onQueued: bind,
197
+ ...(work.thinkingLevel !== undefined ? { thinkingLevel: work.thinkingLevel } : {}),
198
+ } }, 30_000);
199
+ bind(spawn.id);
200
+ if (!terminal) {
201
+ const got = await this.rpc('get', { agentId: id }).catch(() => undefined);
202
+ const entry = got?.agent;
203
+ if (entry && ['completed', 'steered', 'error', 'stopped', 'aborted'].includes(entry.status) && !entry.settling)
204
+ finish(entry);
205
+ else if (entry?.status === 'running')
206
+ started();
207
+ }
208
+ return await result;
209
+ }
210
+ finally {
211
+ signal.removeEventListener('abort', abort);
212
+ for (const off of [...subscription, disposed])
213
+ off();
214
+ }
215
+ }
216
+ dispose() { this.closed = true; for (const off of this.subscriptions)
217
+ off(); }
218
+ }
package/dist/config.js ADDED
@@ -0,0 +1,173 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { modelRef } from './models.js';
4
+ export function resolvePoolEntry(entry, aliases) {
5
+ return typeof entry === 'string' ? { ...modelRef(entry, aliases), thinkingLevel: undefined }
6
+ : { ...modelRef(entry.model, aliases), thinkingLevel: entry.thinkingLevel };
7
+ }
8
+ const worker = (name, workScope, personality) => ({ name, workScope, personality, peers: ['lead'], enable: true, access: null, modelPool: [] });
9
+ const profile = (name, leadScope, roles) => ({
10
+ name, roles: { lead: { ...worker('Team Lead', leadScope, 'decisive'), peers: Object.keys(roles) }, ...roles },
11
+ });
12
+ export function defaults() {
13
+ 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.', {
14
+ arch: worker('Architecture', 'Identify interfaces, invariants and design trade-offs.', 'deliberate'),
15
+ scout: worker('Scout', 'Locate relevant files and symbols quickly.', 'direct'),
16
+ reviewer: worker('Reviewer', 'Assess the change for regressions and correctness.', 'skeptical'),
17
+ coder: worker('Coder', 'Investigate, implement and verify the assigned change.', 'pragmatic'),
18
+ validator: worker('Validator', 'Select and run useful checks; report coverage and failures.', 'exacting'),
19
+ analyzer: worker('Analyzer', 'Diagnose ambiguous failures or performance signals.', 'analytical'),
20
+ });
21
+ return { schemaVersion: 1, enabled: true, defaultProfile: 'engineer', concurrency: 3, aliases: {}, profiles: {
22
+ engineer,
23
+ research: profile('Research', 'Frame questions, parallelize independent inquiries, and reconcile evidence with citations.', {
24
+ arch: worker('Architecture', 'Design an inquiry and source criteria.', 'deliberate'),
25
+ researcher: worker('Researcher', 'Find primary sources and report citations and uncertainty.', 'curious'),
26
+ coder: worker('Coder', 'Build analysis scripts or research artifacts as needed.', 'pragmatic'),
27
+ validator: worker('Validator', 'Check reproducibility and provenance.', 'exacting'),
28
+ reviewer: worker('Reviewer', 'Challenge conclusions and verify important claims.', 'skeptical'),
29
+ }),
30
+ audit: profile('Audit', 'Clarify scope, prioritize findings by impact, and disclose coverage gaps.', {
31
+ arch: worker('Architecture', 'Map relevant controls and boundaries.', 'methodical'),
32
+ analyzer: worker('Analyzer', 'Gather evidence and recommend mitigations; do not remediate.', 'analytical'),
33
+ reviewer: worker('Reviewer', 'Independently evaluate findings and their confidence.', 'skeptical'),
34
+ validator: worker('Validator', 'Use evidence and non-invasive checks to confirm findings.', 'exacting'),
35
+ }),
36
+ } };
37
+ }
38
+ const obj = (value, path) => {
39
+ if (!value || typeof value !== 'object' || Array.isArray(value))
40
+ throw Error(`${path}: expected an object`);
41
+ return value;
42
+ };
43
+ const text = (value, path) => {
44
+ if (typeof value !== 'string' || !value.trim())
45
+ throw Error(`${path}: expected nonempty text`);
46
+ return value;
47
+ };
48
+ const list = (value, path) => {
49
+ if (!Array.isArray(value))
50
+ throw Error(`${path}: expected a list`);
51
+ const items = value.map((v) => text(v, path));
52
+ if (new Set(items).size !== items.length)
53
+ throw Error(`${path}: duplicate entries`);
54
+ return items;
55
+ };
56
+ const thinkingLevels = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
57
+ function parsePool(value, path, aliases) {
58
+ if (!Array.isArray(value))
59
+ throw Error(`${path}: expected a list`);
60
+ if (value.length > 5)
61
+ throw Error(`${path}: max five entries`);
62
+ const refs = new Set();
63
+ return value.map((raw, i) => {
64
+ const at = `${path}[${i}]`;
65
+ let entry;
66
+ if (typeof raw === 'string')
67
+ entry = text(raw, at);
68
+ else {
69
+ const fields = obj(raw, at);
70
+ if (Object.keys(fields).some(k => k !== 'model' && k !== 'thinkingLevel'))
71
+ throw Error(`${at}: expected only model and thinkingLevel`);
72
+ const model = text(fields.model, `${at}.model`);
73
+ const level = fields.thinkingLevel;
74
+ if (level !== undefined && !thinkingLevels.includes(level)) {
75
+ throw Error(`${at}.thinkingLevel: expected one of ${thinkingLevels.join(', ')}`);
76
+ }
77
+ entry = level === undefined ? { model } : { model, thinkingLevel: level };
78
+ }
79
+ let ref;
80
+ try {
81
+ ({ ref } = resolvePoolEntry(entry, aliases));
82
+ }
83
+ catch (err) {
84
+ throw Error(`${at}: ${String(err)}`);
85
+ }
86
+ if (refs.has(ref))
87
+ throw Error(`${at}: duplicate model ${ref}`);
88
+ refs.add(ref);
89
+ return entry;
90
+ });
91
+ }
92
+ const bool = (value, path) => {
93
+ if (typeof value !== 'boolean')
94
+ throw Error(`${path}: expected a boolean`);
95
+ return value;
96
+ };
97
+ function overlay(base, extra) {
98
+ const result = { ...base };
99
+ for (const [key, value] of Object.entries(extra)) {
100
+ if (['__proto__', 'constructor', 'prototype'].includes(key))
101
+ throw Error(`Reserved config key ${key}`);
102
+ const prior = Object.hasOwn(base, key) ? base[key] : undefined;
103
+ // Access objects are whole settings, so a preset cannot leave stale fields behind.
104
+ result[key] = key !== 'access' && value && prior && typeof value === 'object' && typeof prior === 'object'
105
+ && !Array.isArray(value) && !Array.isArray(prior) ? overlay(prior, value) : value;
106
+ }
107
+ return result;
108
+ }
109
+ export function parseConfig(user = {}, project = {}) {
110
+ const u = overlay(defaults(), obj(user, 'user config'));
111
+ const p = obj(project, 'project config');
112
+ const raw = overlay(u, p);
113
+ if (raw.schemaVersion !== 1)
114
+ throw Error('schemaVersion: expected 1');
115
+ const aliases = Object.fromEntries(Object.entries(obj(raw.aliases, 'aliases')).map(([k, v]) => [k, text(v, `aliases.${k}`)]));
116
+ const profiles = Object.create(null);
117
+ for (const [id, value] of Object.entries(obj(raw.profiles, 'profiles'))) {
118
+ const pp = `profiles.${id}`;
119
+ const entry = obj(value, pp);
120
+ const roles = Object.create(null);
121
+ for (const [rid, rv] of Object.entries(obj(entry.roles, `${pp}.roles`))) {
122
+ const rp = `${pp}.roles.${rid}`;
123
+ const role = obj(rv, rp);
124
+ const configured = role.access ?? null;
125
+ let access = null;
126
+ if (configured !== null) {
127
+ const rule = obj(configured, `${rp}.access`);
128
+ if (Object.keys(rule).some(k => k !== 'tools'))
129
+ throw Error(`${rp}.access: only a tool allowlist is currently supported`);
130
+ access = { tools: list(rule.tools, `${rp}.access.tools`) };
131
+ }
132
+ const userRole = (u.profiles[id]?.roles[rid]);
133
+ if (userRole?.access?.tools && (!access || access.tools.some(t => !userRole.access.tools.includes(t)))) {
134
+ throw Error(`${rp}.access: project cannot widen the user tool allowlist`);
135
+ }
136
+ const modelPool = parsePool(role.modelPool ?? [], `${rp}.modelPool`, aliases);
137
+ roles[rid] = { name: text(role.name, `${rp}.name`), enable: bool(role.enable ?? true, `${rp}.enable`),
138
+ workScope: text(role.workScope, `${rp}.workScope`), personality: text(role.personality ?? 'neutral', `${rp}.personality`),
139
+ peers: list(role.peers ?? (rid === 'lead' ? [] : ['lead']), `${rp}.peers`), access, modelPool };
140
+ }
141
+ if (!roles.lead?.enable)
142
+ throw Error(`${pp}.roles.lead: an enabled Lead is required`);
143
+ for (const [rid, r] of Object.entries(roles)) {
144
+ if (r.peers.some(peer => peer === rid || !Object.hasOwn(roles, peer)))
145
+ throw Error(`${pp}.roles.${rid}.peers: invalid peer`);
146
+ }
147
+ profiles[id] = { name: text(entry.name, `${pp}.name`), roles };
148
+ }
149
+ const defaultProfile = text(raw.defaultProfile, 'defaultProfile');
150
+ if (!Object.hasOwn(profiles, defaultProfile))
151
+ throw Error(`Unknown default profile ${defaultProfile}`);
152
+ const concurrency = raw.concurrency;
153
+ if (typeof concurrency !== 'number' || !Number.isInteger(concurrency) || concurrency < 1 || concurrency > 16)
154
+ throw Error('concurrency: expected integer 1–16');
155
+ return { schemaVersion: 1, profiles, defaultProfile, concurrency, aliases, enabled: bool(raw.enabled, 'enabled') };
156
+ }
157
+ export function configPaths(agentDir, cwd) {
158
+ return { user: join(agentDir, 'team-mode.json'), project: join(cwd, '.pi', 'team-mode.json') };
159
+ }
160
+ function read(path) {
161
+ try {
162
+ return JSON.parse(readFileSync(path, 'utf8'));
163
+ }
164
+ catch (err) {
165
+ if (err.code === 'ENOENT')
166
+ return {};
167
+ throw Error(`${path}: ${String(err)}`);
168
+ }
169
+ }
170
+ export function loadConfig(agentDir, cwd, trusted) {
171
+ const paths = configPaths(agentDir, cwd);
172
+ return parseConfig(read(paths.user), trusted ? read(paths.project) : {});
173
+ }
@@ -0,0 +1,423 @@
1
+ import { readFileSync, mkdirSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { Type } from 'typebox';
5
+ import { clampThinkingLevel } from '@earendil-works/pi-ai';
6
+ import { getAgentDir } from '@earendil-works/pi-coding-agent';
7
+ import { configPaths, defaults, loadConfig, resolvePoolEntry } from './config.js';
8
+ import { ModelPools, modelRef } from './models.js';
9
+ import { NativeBackend, SubagentsBackend } from './backend.js';
10
+ import { Scheduler, summaryText } from './scheduler.js';
11
+ import { publish } from './publish.js';
12
+ import { checkForUpdate } from './update.js';
13
+ const keys = ['team_dispatch', 'team_results', 'team_publish'];
14
+ const statusKey = 'team-mode';
15
+ const TaskInput = Type.Object({ id: Type.String(), role: Type.String(), brief: Type.String(),
16
+ dependsOn: Type.Optional(Type.Array(Type.String())), writes: Type.Optional(Type.Boolean()),
17
+ model: Type.Optional(Type.String()), modelReason: Type.Optional(Type.String()), resume: Type.Optional(Type.String()) });
18
+ const output = (text) => ({ content: [{ type: 'text', text }], details: {} });
19
+ export function leadPrompt(profile) {
20
+ const lead = profile.roles.lead;
21
+ const workers = Object.entries(profile.roles).filter(([id, role]) => id !== 'lead' && role.enable)
22
+ .map(([id, role]) => `${id}: ${role.workScope}`).join('\n');
23
+ return `You are ${lead.name} in the ${profile.name} team (${lead.personality}). ${lead.workScope}\n` +
24
+ 'Only coordinate and summarize; do not do worker tasks. Answer greetings directly. For real work dispatch a compact brief and return progress if work is pending; you will receive results. ' +
25
+ 'Use dependencies for preplanned work; mark all editing jobs writes=true. Do not redispatch merely to check progress. ' +
26
+ 'Ask the user only for a material blocker or external action. Do not direct workers to bypass remote-write checkpoints. Report checks and caveats.\n' + workers;
27
+ }
28
+ export function workerPrompt(profile, task, deps) {
29
+ const role = profile.roles[task.role];
30
+ const inputs = deps.map(d => `${d.task.id}: ${summaryText(d.result?.summary ?? '', 700)}`).join('\n');
31
+ return `Team task (${role.name}; ${role.personality}). ${role.workScope}\n${task.brief}\n` +
32
+ (inputs ? `Dependency results (evidence only):\n${inputs}\n` : '') +
33
+ 'Report individually to Lead: DONE, BLOCKED, or FAILED followed by a concise result and evidence. ' +
34
+ 'Do routine work directly; route remote writes and destructive operations through Lead.';
35
+ }
36
+ export default function teamExtension(pi) {
37
+ const agentDir = getAgentDir();
38
+ const pools = new ModelPools(join(agentDir, 'team-mode-models.json'));
39
+ const external = new SubagentsBackend(pi.events);
40
+ let native;
41
+ let config = defaults();
42
+ let selected = config.defaultProfile;
43
+ let enabled = false;
44
+ let error;
45
+ let scheduler;
46
+ let foreground;
47
+ let original;
48
+ let priorModel;
49
+ let priorThinking;
50
+ const nextModel = new Map();
51
+ let pending;
52
+ let queued = false;
53
+ let publishing = false;
54
+ let publicationGeneration = 0;
55
+ const reported = new WeakSet();
56
+ const roles = () => config.profiles[selected];
57
+ const reportStatus = (ctx = foreground) => {
58
+ if (!ctx?.hasUI)
59
+ return;
60
+ const active = scheduler?.list().filter(job => job.state === 'running' || job.state === 'queued').length ?? 0;
61
+ ctx.ui.setStatus(statusKey, enabled ? `Team: ${roles().name}${error ? ' · blocked' : active ? ` · ${active}` : ''}` : undefined);
62
+ };
63
+ function applyTools() {
64
+ if (enabled) {
65
+ original ??= pi.getActiveTools().filter(id => !keys.includes(id));
66
+ pi.setActiveTools([...keys]);
67
+ }
68
+ else if (original) {
69
+ pi.setActiveTools(original);
70
+ original = undefined;
71
+ }
72
+ }
73
+ function flush() {
74
+ if (!enabled || !pending || queued)
75
+ return;
76
+ const content = pending;
77
+ pending = undefined;
78
+ for (const job of scheduler?.list() ?? [])
79
+ if (job.result)
80
+ reported.add(job);
81
+ queued = true;
82
+ pi.sendMessage({ customType: 'pi-team-result', content, display: false }, { deliverAs: 'followUp', triggerTurn: true });
83
+ }
84
+ function configuredPool(role) {
85
+ return roles().roles[role].modelPool.map(entry => resolvePoolEntry(entry, config.aliases));
86
+ }
87
+ function selectModel(task, ctx, configured = configuredPool(task.role)) {
88
+ const members = pools.get(selected, task.role, configured.map(entry => entry.ref));
89
+ const requested = nextModel.get(`${selected}/${task.role}`);
90
+ // The live foreground is a fallback, not a learned or configured pool entry.
91
+ const inherited = configured.length ? undefined : ctx.model;
92
+ const inheritedRef = inherited && `${inherited.provider}/${inherited.id}`;
93
+ const defaultRef = configured[0]?.ref ?? inheritedRef;
94
+ const ref = task.model !== undefined ? modelRef(task.model, config.aliases).ref : requested ?? defaultRef;
95
+ if (!ref)
96
+ throw Error(`No model available for ${task.role}`);
97
+ if (inherited && ref === inheritedRef)
98
+ return { model: inherited, ref };
99
+ if (!members.includes(ref))
100
+ throw Error(`${ref} is not in the ${task.role} pool; use /team model to add it.`);
101
+ if (ref !== defaultRef && ref !== requested && !task.modelReason?.trim())
102
+ throw Error('A non-default model needs a reason');
103
+ return registeredModel(ref, ctx);
104
+ }
105
+ function registeredModel(ref, ctx) {
106
+ const { provider, id } = modelRef(ref, {});
107
+ const model = ctx.modelRegistry.find(provider, id);
108
+ if (!model)
109
+ throw Error(`Unregistered model ${ref}`);
110
+ return { model, ref };
111
+ }
112
+ function newScheduler() {
113
+ const generation = new Scheduler(config.concurrency, async (task, deps, signal) => {
114
+ const role = roles().roles[task.role];
115
+ // Explicit task choices were authorized at dispatch. Only defaults and one-shot
116
+ // selections are resolved at worker start, against Pi's live foreground context.
117
+ const ctx = foreground;
118
+ const configured = configuredPool(task.role);
119
+ const { model, ref } = task.model === undefined ? selectModel(task, ctx, configured) : registeredModel(task.model, ctx);
120
+ const explicitThinking = configured.find(entry => entry.ref === ref)?.thinkingLevel;
121
+ const thinkingLevel = configured.length ? explicitThinking : pi.getThinkingLevel();
122
+ if (explicitThinking !== undefined) {
123
+ const effective = clampThinkingLevel(model, explicitThinking);
124
+ if (effective !== explicitThinking)
125
+ ctx.ui.notify(`${task.role}: ${ref} uses ${effective} thinking instead of ${explicitThinking}.`, 'warning');
126
+ }
127
+ const nextKey = `${selected}/${task.role}`;
128
+ if (nextModel.get(nextKey) === ref)
129
+ nextModel.delete(nextKey);
130
+ const previous = scheduler?.list().find(j => j.task.id === task.resume && j.task.role === task.role);
131
+ const resume = previous?.result?.resume;
132
+ const prompt = workerPrompt(roles(), task, deps) + (previous && (!resume || !native?.canResume(resume, task.role, ref, role.access?.tools))
133
+ ? `\nEarlier result: ${summaryText(previous.result?.summary ?? '', 900)}` : '');
134
+ const work = { id: task.id, role: task.role, prompt, model, thinkingLevel, resume, tools: role.access?.tools,
135
+ started: () => { try {
136
+ pools.started(selected, task.role, ref);
137
+ }
138
+ catch { /* Usage is best-effort; do not block work. */ } } };
139
+ return (external.supports(work) ? external : native).run(work, signal);
140
+ }, (reason, jobs) => {
141
+ reportStatus();
142
+ if (reason === 'progress')
143
+ return;
144
+ const unseen = jobs.filter(j => j.result && !reported.has(j));
145
+ const results = unseen.map(j => `${j.task.id} [${j.state}]: ${summaryText(j.result.summary, 550)}`).join('\n');
146
+ pending = `${reason === 'finished' ? 'Team tasks settled; summarize or replan.' : 'Team task needs a decision.'}\n${summaryText(results, 4500)}`;
147
+ // If the foreground is still running, coalesce until its final idle boundary.
148
+ if (foreground?.isIdle())
149
+ flush();
150
+ });
151
+ return generation;
152
+ }
153
+ async function setLeadModel(ref, thinkingLevel, ctx) {
154
+ const { model } = registeredModel(ref, ctx);
155
+ if (!await pi.setModel(model))
156
+ throw Error(`Lead model unavailable: ${ref}`);
157
+ if (thinkingLevel !== undefined) {
158
+ pi.setThinkingLevel(thinkingLevel);
159
+ const effective = pi.getThinkingLevel();
160
+ if (effective !== thinkingLevel)
161
+ ctx.ui.notify(`Lead: ${ref} uses ${effective} thinking instead of ${thinkingLevel}.`, 'warning');
162
+ }
163
+ }
164
+ async function activate(ctx) {
165
+ foreground = ctx;
166
+ if (!enabled) {
167
+ priorModel = ctx.model;
168
+ priorThinking = pi.getThinkingLevel();
169
+ }
170
+ enabled = true;
171
+ scheduler ??= newScheduler();
172
+ applyTools();
173
+ const leadDefault = configuredPool('lead')[0];
174
+ if (leadDefault) {
175
+ try {
176
+ await setLeadModel(leadDefault.ref, leadDefault.thinkingLevel, ctx);
177
+ }
178
+ catch (e) {
179
+ ctx.ui.notify(`${String(e)}; using the current Pi model and thinking level.`, 'warning');
180
+ }
181
+ }
182
+ reportStatus(ctx);
183
+ }
184
+ async function disable(ctx) {
185
+ if (scheduler?.active)
186
+ throw Error('Workers are still active; use /team cancel and wait.');
187
+ scheduler?.dispose();
188
+ scheduler = undefined;
189
+ native?.dispose();
190
+ native = new NativeBackend(ctx.cwd, agentDir);
191
+ pending = undefined;
192
+ queued = false;
193
+ enabled = false;
194
+ applyTools();
195
+ reportStatus(ctx);
196
+ if (priorModel && !await pi.setModel(priorModel))
197
+ ctx.ui.notify('The pre-Team model is no longer available.', 'warning');
198
+ if (priorThinking !== undefined)
199
+ pi.setThinkingLevel(priorThinking);
200
+ priorModel = undefined;
201
+ priorThinking = undefined;
202
+ }
203
+ async function switchProfile(name, ctx) {
204
+ if (!Object.hasOwn(config.profiles, name))
205
+ throw Error(`Unknown profile: ${name}`);
206
+ scheduler?.reset();
207
+ scheduler?.dispose();
208
+ scheduler = undefined;
209
+ native?.dispose();
210
+ native = new NativeBackend(ctx.cwd, agentDir);
211
+ selected = name;
212
+ pending = undefined;
213
+ queued = false;
214
+ await activate(ctx);
215
+ }
216
+ let updateCheck;
217
+ pi.on('session_start', async (event, ctx) => {
218
+ foreground = ctx;
219
+ if (!ctx.hasUI || ctx.mode !== 'tui')
220
+ return;
221
+ if (event.reason === 'startup' && !updateCheck) {
222
+ const controller = updateCheck = new AbortController();
223
+ void checkForUpdate({ entry: fileURLToPath(import.meta.url), agentDir, cwd: ctx.cwd,
224
+ projectTrusted: ctx.isProjectTrusted(), signal: controller.signal }).then(notice => {
225
+ if (notice && !controller.signal.aborted)
226
+ ctx.ui.notify(notice, 'info');
227
+ }).catch(() => { });
228
+ }
229
+ native = new NativeBackend(ctx.cwd, agentDir);
230
+ try {
231
+ config = loadConfig(agentDir, ctx.cwd, ctx.isProjectTrusted());
232
+ }
233
+ catch (err) {
234
+ error = String(err);
235
+ ctx.ui.notify(error, 'error');
236
+ }
237
+ selected = config.defaultProfile;
238
+ if (config.enabled)
239
+ await activate(ctx);
240
+ void external.probe();
241
+ });
242
+ pi.on('model_select', (_event, ctx) => { foreground = ctx; });
243
+ pi.on('session_shutdown', () => {
244
+ updateCheck?.abort();
245
+ enabled = false;
246
+ scheduler?.dispose();
247
+ native?.dispose();
248
+ external.dispose();
249
+ });
250
+ pi.on('session_before_tree', () => { publicationGeneration++; scheduler?.cancel(); pending = undefined; queued = false; });
251
+ pi.on('before_agent_start', event => {
252
+ if (!enabled)
253
+ return;
254
+ queued = false;
255
+ applyTools();
256
+ event.systemPromptOptions.sections.pi_team_lead = leadPrompt(roles()) + (error ? '\nTeam is blocked; direct the user to /team doctor.' : '');
257
+ });
258
+ pi.on('tool_call', event => {
259
+ if (enabled && !keys.includes(event.toolName))
260
+ return { block: true, reason: 'Team Lead coordinates; delegate concrete work.' };
261
+ });
262
+ pi.on('agent_settled', event => {
263
+ if (event.aborted) {
264
+ publicationGeneration++;
265
+ scheduler?.cancel();
266
+ pending = undefined;
267
+ queued = false;
268
+ return;
269
+ }
270
+ flush();
271
+ });
272
+ 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.',
273
+ defaultActive: false, parameters: Type.Object({ tasks: Type.Array(TaskInput, { minItems: 1, maxItems: 16 }) }),
274
+ async execute(_id, { tasks }, _signal, _update, ctx) {
275
+ const owner = scheduler;
276
+ if (!enabled || !owner || error)
277
+ throw Error(error ?? 'Team Mode is off');
278
+ if (publishing)
279
+ throw Error('A remote action is in progress');
280
+ foreground = ctx;
281
+ const batch = tasks.map(task => {
282
+ if (task.role === 'lead' || !roles().roles[task.role]?.enable)
283
+ throw Error(`Unavailable worker role ${task.role}`);
284
+ if (task.resume && !owner.list().some(j => j.task.id === task.resume && j.task.role === task.role && j.result))
285
+ throw Error(`Unknown completed ${task.role} task ${task.resume}`);
286
+ const { ref } = selectModel(task, ctx);
287
+ return { ...task, model: task.model === undefined ? undefined : ref, writes: task.writes ?? task.role === 'coder' };
288
+ });
289
+ return output(`Queued: ${owner.submit(batch).join(', ')}. Team Mode will notify you when a decision or final summary is due.`);
290
+ } });
291
+ pi.registerTool({ name: 'team_results', label: 'Inspect team results', description: 'Read compact team status or one task result; do not poll.', defaultActive: false,
292
+ parameters: Type.Object({ id: Type.Optional(Type.String()) }),
293
+ async execute(_id, { id }) {
294
+ if (!enabled || !scheduler)
295
+ throw Error('Team Mode is off');
296
+ const items = scheduler.list().filter(j => !id || j.task.id === id);
297
+ return output(items.map(j => `${j.task.id} (${j.task.role}): ${j.state}${id && j.result ? `\n${j.result.summary}` : ''}`).join('\n') || 'No matching task.');
298
+ } });
299
+ pi.registerTool({ name: 'team_publish', label: 'Approve remote GitHub actions', defaultActive: false,
300
+ description: 'After requested local work is verified and committed, ask once to push a commit, open a GitHub PR, or request review. No force-push, merge or deployment.',
301
+ parameters: Type.Object({ remote: Type.String(), branch: Type.String(), push: Type.Optional(Type.Boolean()),
302
+ pullRequest: Type.Optional(Type.Object({ base: Type.String(), title: Type.String({ minLength: 1, maxLength: 250 }), body: Type.String({ maxLength: 12000 }) })),
303
+ reviewers: Type.Optional(Type.Array(Type.String(), { maxItems: 10 })) }),
304
+ async execute(_id, args, signal, _update, ctx) {
305
+ if (!enabled || !scheduler || error || !ctx.hasUI)
306
+ throw Error('Team Mode with interactive approval is required');
307
+ if (scheduler.active || publishing)
308
+ throw Error('Finish active work before requesting a remote action');
309
+ const owner = scheduler;
310
+ const generation = publicationGeneration;
311
+ publishing = true;
312
+ try {
313
+ return output(await publish(args, pi.exec, ctx.cwd, signal, description => ctx.ui.confirm('Approve these remote actions?', description), () => enabled && owner === scheduler && !owner.active && generation === publicationGeneration));
314
+ }
315
+ finally {
316
+ publishing = false;
317
+ }
318
+ } });
319
+ pi.registerCommand('team', { description: 'Manage team mode: on, off, profile, status, cancel, doctor, model, config',
320
+ async handler(args, ctx) {
321
+ const [command, arg, ...rest] = args.trim().split(/\s+/);
322
+ try {
323
+ if (!command) {
324
+ const names = Object.keys(config.profiles);
325
+ const choice = await ctx.ui.select('Team profile', names);
326
+ if (choice)
327
+ await switchProfile(choice, ctx);
328
+ }
329
+ else if (command === 'on') {
330
+ native ??= new NativeBackend(ctx.cwd, agentDir);
331
+ await activate(ctx);
332
+ }
333
+ else if (command === 'off')
334
+ await disable(ctx);
335
+ else if (command === 'profile')
336
+ await switchProfile(arg, ctx);
337
+ else if (command === 'cancel') {
338
+ publicationGeneration++;
339
+ pending = undefined;
340
+ queued = false;
341
+ scheduler?.cancel();
342
+ }
343
+ else if (command === 'reset') {
344
+ scheduler?.reset();
345
+ native?.dispose();
346
+ native = new NativeBackend(ctx.cwd, agentDir);
347
+ pending = undefined;
348
+ queued = false;
349
+ }
350
+ else if (command === 'status') {
351
+ const jobs = scheduler?.list().map(j => `${j.task.id}: ${j.state}`).join('\n');
352
+ ctx.ui.notify(`Team: ${enabled ? roles().name : 'off'}${jobs ? `\n${jobs}` : ''}`, 'info');
353
+ }
354
+ else if (command === 'doctor') {
355
+ const available = await external.probe();
356
+ ctx.ui.notify(`${error ?? 'Configuration OK'}\nBackend: ${available ? 'pi-subagents RPC v2 (SDK for unsupported worker policies)' : 'built-in Pi SDK'}`, error ? 'error' : 'info');
357
+ }
358
+ else if (command === 'model') {
359
+ if (!roles().roles[arg]?.enable || !rest.length)
360
+ throw Error('Usage: /team model <role> <provider/model-id>');
361
+ const { provider, id, ref } = modelRef(rest.join(' '), config.aliases);
362
+ if (!ctx.modelRegistry.getAvailable().some(m => m.provider === provider && m.id === id))
363
+ throw Error(`Model unavailable: ${ref}`);
364
+ if (arg === 'lead' && !enabled)
365
+ throw Error('Enable Team Mode before switching its Lead model');
366
+ const configured = configuredPool(arg);
367
+ if (arg === 'lead')
368
+ await setLeadModel(ref, configured.find(entry => entry.ref === ref)?.thinkingLevel, ctx);
369
+ const list = pools.add(selected, arg, configured.map(entry => entry.ref), ref);
370
+ if (arg !== 'lead')
371
+ nextModel.set(`${selected}/${arg}`, ref);
372
+ ctx.ui.notify(`Selected ${ref} for ${arg}: ${list.join(', ')}`, 'info');
373
+ }
374
+ else if (command === 'config' && arg === 'validate') {
375
+ loadConfig(agentDir, ctx.cwd, ctx.isProjectTrusted());
376
+ ctx.ui.notify('Team configuration OK', 'info');
377
+ }
378
+ else if (command === 'config' && (arg === 'reload' || arg === 'edit')) {
379
+ if (scheduler?.active)
380
+ throw Error('Wait for current tasks to finish before changing team config');
381
+ if (arg === 'edit') {
382
+ const paths = configPaths(agentDir, ctx.cwd);
383
+ const isProject = rest[0] === 'project';
384
+ if (isProject && !ctx.isProjectTrusted())
385
+ throw Error('Project is not trusted');
386
+ const path = isProject ? paths.project : paths.user;
387
+ let source = '{\n "schemaVersion": 1\n}\n';
388
+ try {
389
+ source = readFileSync(path, 'utf8');
390
+ }
391
+ catch (e) {
392
+ if (e.code !== 'ENOENT')
393
+ throw e;
394
+ }
395
+ const next = await ctx.ui.editor(`Edit ${path}`, source);
396
+ if (next === undefined)
397
+ return;
398
+ JSON.parse(next);
399
+ mkdirSync(dirname(path), { recursive: true });
400
+ writeFileSync(path, next.endsWith('\n') ? next : `${next}\n`);
401
+ }
402
+ const next = loadConfig(agentDir, ctx.cwd, ctx.isProjectTrusted());
403
+ scheduler?.reset();
404
+ scheduler?.dispose();
405
+ scheduler = undefined;
406
+ native?.dispose();
407
+ native = new NativeBackend(ctx.cwd, agentDir);
408
+ config = next;
409
+ error = undefined;
410
+ if (!Object.hasOwn(config.profiles, selected))
411
+ selected = config.defaultProfile;
412
+ if (enabled)
413
+ await activate(ctx);
414
+ ctx.ui.notify('Team configuration reloaded', 'info');
415
+ }
416
+ else
417
+ throw Error('Usage: /team [on|off|profile <id>|status|cancel|reset|doctor|model|config]');
418
+ }
419
+ catch (err) {
420
+ ctx.ui.notify(String(err), 'error');
421
+ }
422
+ } });
423
+ }
package/dist/models.js ADDED
@@ -0,0 +1,74 @@
1
+ import { mkdirSync, readFileSync, renameSync, rmdirSync, writeFileSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ export function modelRef(value, aliases) {
5
+ const ref = Object.hasOwn(aliases, value) ? aliases[value] : value;
6
+ const slash = ref.indexOf('/');
7
+ if (slash < 1 || slash === ref.length - 1)
8
+ throw Error(`Use an exact provider/model-id or configured alias for ${value}`);
9
+ return { ref, provider: ref.slice(0, slash), id: ref.slice(slash + 1) };
10
+ }
11
+ function pool(entry, configured, add) {
12
+ const base = configured.filter((m, i) => i === 0 || !entry.excluded?.includes(m));
13
+ const models = [...new Set([...base, ...entry.added, ...(add ? [add] : [])])];
14
+ while (models.length > 5) {
15
+ const drop = models.slice(1).filter(m => m !== add).sort((a, b) => {
16
+ const x = entry.usage[a], y = entry.usage[b];
17
+ return (x?.count ?? 0) - (y?.count ?? 0) || (x?.last ?? 0) - (y?.last ?? 0) || a.localeCompare(b);
18
+ })[0];
19
+ models.splice(models.indexOf(drop), 1);
20
+ }
21
+ return models;
22
+ }
23
+ export class ModelPools {
24
+ path;
25
+ constructor(path) {
26
+ this.path = path;
27
+ }
28
+ get(profile, role, configured) {
29
+ const entry = this.read()[JSON.stringify([profile, role])] ?? { added: [], usage: {} };
30
+ return pool(entry, configured);
31
+ }
32
+ add(profile, role, configured, model) {
33
+ return this.update(profile, role, entry => {
34
+ const next = pool(entry, configured, model);
35
+ // Persist the effective ordering, including evictions of configured alternatives.
36
+ entry.added = next.filter(m => !configured.includes(m));
37
+ entry.excluded = configured.filter(m => !next.includes(m));
38
+ return next;
39
+ });
40
+ }
41
+ started(profile, role, model) {
42
+ this.update(profile, role, entry => {
43
+ const prev = Object.hasOwn(entry.usage, model) ? entry.usage[model] : undefined;
44
+ entry.usage[model] = { count: (prev?.count ?? 0) + 1, last: Date.now() };
45
+ });
46
+ }
47
+ read() {
48
+ try {
49
+ return JSON.parse(readFileSync(this.path, 'utf8'));
50
+ }
51
+ catch (error) {
52
+ if (error.code === 'ENOENT')
53
+ return {};
54
+ throw error;
55
+ }
56
+ }
57
+ update(profile, role, fn) {
58
+ mkdirSync(dirname(this.path), { recursive: true });
59
+ const lock = `${this.path}.lock`;
60
+ mkdirSync(lock); // Never wait or overwrite a concurrent writer.
61
+ try {
62
+ const data = this.read();
63
+ const key = JSON.stringify([profile, role]);
64
+ const result = fn(data[key] ??= { added: [], usage: {} });
65
+ const tmp = `${this.path}.${randomUUID()}.tmp`;
66
+ writeFileSync(tmp, JSON.stringify(data), { mode: 0o600, flag: 'wx' });
67
+ renameSync(tmp, this.path);
68
+ return result;
69
+ }
70
+ finally {
71
+ rmdirSync(lock);
72
+ }
73
+ }
74
+ }
@@ -0,0 +1,74 @@
1
+ const ref = /^[a-zA-Z0-9][a-zA-Z0-9._/-]{0,150}$/;
2
+ const remoteName = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
3
+ const login = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,38}(\/[a-zA-Z0-9][a-zA-Z0-9-]{0,62})?$/;
4
+ export async function publish(input, run, cwd, signal, confirm, active) {
5
+ if (!input.push && !input.pullRequest && !input.reviewers?.length)
6
+ throw Error('Choose at least one remote action');
7
+ if (!remoteName.test(input.remote) || !ref.test(input.branch) || input.pullRequest && !ref.test(input.pullRequest.base))
8
+ throw Error('Invalid remote or branch');
9
+ if (input.reviewers?.some(name => !login.test(name)))
10
+ throw Error('Invalid review recipient');
11
+ async function exec(bin, args) {
12
+ signal?.throwIfAborted();
13
+ const result = await run(bin, args, { cwd, signal, timeout: 90_000 });
14
+ if (result.code !== 0)
15
+ throw Error(`${bin} ${args[0]} failed: ${(result.stderr || result.stdout).trim().slice(0, 800)}`);
16
+ return result.stdout.trim();
17
+ }
18
+ async function snapshot() {
19
+ const url = await exec('git', ['remote', 'get-url', '--push', input.remote]);
20
+ const match = /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([\w-]+\/[\w.-]+)$/.exec(url);
21
+ if (!match)
22
+ throw Error('The built-in publisher supports github.com HTTPS and SSH push remotes');
23
+ const sha = await exec('git', ['rev-parse', '--verify', 'HEAD^{commit}']);
24
+ if (!/^[a-f0-9]{40,64}$/.test(sha))
25
+ throw Error('Could not pin the candidate commit');
26
+ await exec('git', ['check-ref-format', '--branch', input.branch]);
27
+ if (input.pullRequest)
28
+ await exec('git', ['check-ref-format', '--branch', input.pullRequest.base]);
29
+ return { url, sha, repo: `github.com/${match[1].replace(/\.git$/, '')}` };
30
+ }
31
+ const target = await snapshot();
32
+ const description = [
33
+ `${target.repo} · ${input.branch} · ${target.sha}`,
34
+ input.push && 'Push the pinned commit (no force).',
35
+ input.pullRequest && `Open PR into ${input.pullRequest.base}: ${input.pullRequest.title}\n\n${input.pullRequest.body}`,
36
+ input.reviewers?.length && `Request review from ${input.reviewers.join(', ')}.`,
37
+ ].filter(Boolean).join('\n');
38
+ if (!await confirm(description))
39
+ return 'Remote actions declined; no remote changes made.';
40
+ if (!active())
41
+ throw Error('Team publication was cancelled or worker state changed');
42
+ const current = await snapshot();
43
+ if (!active())
44
+ throw Error('Team publication was cancelled or worker state changed');
45
+ if (current.url !== target.url || current.sha !== target.sha)
46
+ throw Error('Remote or revision changed; approval is no longer valid');
47
+ const completed = [];
48
+ try {
49
+ if (input.push) {
50
+ await exec('git', ['push', '--porcelain', '--no-follow-tags', '--', target.url, `${target.sha}:refs/heads/${input.branch}`]);
51
+ completed.push(`Pushed ${target.sha} to ${input.branch}.`);
52
+ }
53
+ if (input.pullRequest || input.reviewers?.length) {
54
+ // For PR-only/review-only requests, verify the existing remote head is the approved commit.
55
+ const remoteHead = await exec('git', ['ls-remote', '--', target.url, `refs/heads/${input.branch}`]);
56
+ if (remoteHead.split(/\s/)[0] !== target.sha)
57
+ throw Error('Remote branch no longer matches the approved revision');
58
+ }
59
+ if (input.pullRequest) {
60
+ const p = input.pullRequest;
61
+ const link = await exec('gh', ['pr', 'create', '--repo', target.repo, '--head', input.branch, '--base', p.base, `--title=${p.title}`, `--body=${p.body}`]);
62
+ completed.push(`Opened PR: ${link}`);
63
+ }
64
+ if (input.reviewers?.length) {
65
+ await exec('gh', ['pr', 'edit', input.branch, '--repo', target.repo, '--add-reviewer', input.reviewers.join(',')]);
66
+ completed.push(`Requested review from ${input.reviewers.join(', ')}.`);
67
+ }
68
+ return completed.join('\n');
69
+ }
70
+ catch (error) {
71
+ // Make partial effects visible; do not automatically replay writes.
72
+ return `${completed.length ? `${completed.join('\n')}\n` : ''}Stopped: ${String(error)}`;
73
+ }
74
+ }
@@ -0,0 +1,127 @@
1
+ const terminal = (state) => state !== 'running' && state !== 'queued';
2
+ const briefLimit = 12_000;
3
+ export function summaryText(value, limit = 2400) {
4
+ return value.length > limit ? `${value.slice(0, limit)}\n[truncated]` : value;
5
+ }
6
+ export class Scheduler {
7
+ concurrency;
8
+ execute;
9
+ onChange;
10
+ jobs = new Map();
11
+ controllers = new Map();
12
+ stopped = false;
13
+ revision = 0;
14
+ notifiedIdle = true;
15
+ constructor(concurrency, execute, onChange = () => { }) {
16
+ this.concurrency = concurrency;
17
+ this.execute = execute;
18
+ this.onChange = onChange;
19
+ }
20
+ get busy() { return this.list().some(j => !terminal(j.state)); }
21
+ get active() { return this.busy || this.controllers.size > 0; }
22
+ list() { return [...this.jobs.values()]; }
23
+ submit(tasks) {
24
+ if (this.stopped)
25
+ throw Error('Coordinator stopped');
26
+ if (!tasks.length || tasks.length > 16)
27
+ throw Error('Dispatch between 1 and 16 tasks');
28
+ if (this.jobs.size + tasks.length > 100)
29
+ throw Error('Task history is full; reset it when idle');
30
+ const batch = new Map();
31
+ for (const t of structuredClone(tasks)) {
32
+ if (!/^[a-zA-Z0-9_-]{1,40}$/.test(t.id) || this.jobs.has(t.id) || batch.has(t.id))
33
+ throw Error(`Invalid or duplicate task ID: ${t.id}`);
34
+ if (!t.brief.trim() || t.brief.length > briefLimit)
35
+ throw Error(`${t.id}: brief must be 1–${briefLimit} characters`);
36
+ batch.set(t.id, t);
37
+ }
38
+ for (const t of batch.values()) {
39
+ for (const dep of t.dependsOn ?? [])
40
+ if (!batch.has(dep) && !this.jobs.has(dep))
41
+ throw Error(`${t.id}: unknown dependency ${dep}`);
42
+ }
43
+ const visiting = new Set();
44
+ const visited = new Set();
45
+ const visit = (id) => {
46
+ if (visiting.has(id))
47
+ throw Error(`Cyclic dependency at ${id}`);
48
+ const t = batch.get(id);
49
+ if (!t || visited.has(id))
50
+ return;
51
+ visiting.add(id);
52
+ for (const dep of t.dependsOn ?? [])
53
+ visit(dep);
54
+ visiting.delete(id);
55
+ visited.add(id);
56
+ };
57
+ for (const id of batch.keys())
58
+ visit(id);
59
+ for (const task of batch.values())
60
+ this.jobs.set(task.id, { task, state: 'queued' });
61
+ this.notifiedIdle = false;
62
+ this.pump();
63
+ return [...batch.keys()];
64
+ }
65
+ reset() {
66
+ if (this.busy || this.controllers.size)
67
+ throw Error('Wait for workers to finish stopping before resetting tasks');
68
+ this.jobs.clear();
69
+ }
70
+ cancel() {
71
+ this.revision++;
72
+ for (const job of this.jobs.values())
73
+ if (!terminal(job.state))
74
+ job.state = 'cancelled';
75
+ for (const controller of this.controllers.values())
76
+ controller.abort();
77
+ this.notifiedIdle = true;
78
+ this.onChange('progress', this.list());
79
+ }
80
+ dispose() { this.stopped = true; this.cancel(); }
81
+ pump(decision = false) {
82
+ if (this.stopped)
83
+ return;
84
+ let changed;
85
+ do {
86
+ changed = false;
87
+ for (const job of this.jobs.values())
88
+ if (job.state === 'queued') {
89
+ const deps = (job.task.dependsOn ?? []).map(id => this.jobs.get(id));
90
+ const bad = deps.find(d => terminal(d.state) && d.state !== 'done');
91
+ if (bad) {
92
+ job.state = 'blocked';
93
+ job.result = { status: 'blocked', summary: `Dependency ${bad.task.id} ${bad.state}.` };
94
+ changed = true;
95
+ }
96
+ else if (deps.every(d => d.state === 'done') && this.controllers.size < this.concurrency &&
97
+ (!job.task.writes || ![...this.controllers.keys()].some(id => this.jobs.get(id)?.task.writes))) {
98
+ this.start(job, deps);
99
+ }
100
+ }
101
+ } while (changed);
102
+ if (!this.busy && !this.notifiedIdle) {
103
+ this.notifiedIdle = true;
104
+ this.onChange('finished', this.list());
105
+ }
106
+ else
107
+ this.onChange(decision ? 'decision' : 'progress', this.list());
108
+ }
109
+ start(job, deps) {
110
+ const revision = this.revision;
111
+ const controller = new AbortController();
112
+ job.state = 'running';
113
+ this.controllers.set(job.task.id, controller);
114
+ void Promise.resolve().then(() => {
115
+ controller.signal.throwIfAborted();
116
+ return this.execute(job.task, deps, controller.signal);
117
+ }).catch((error) => ({ status: 'failed', summary: String(error) })).then(result => {
118
+ this.controllers.delete(job.task.id);
119
+ const current = revision === this.revision;
120
+ if (current) {
121
+ job.result = { ...result, summary: summaryText(result.summary) };
122
+ job.state = result.status;
123
+ }
124
+ this.pump(current && result.status !== 'done');
125
+ });
126
+ }
127
+ }
package/dist/update.js ADDED
@@ -0,0 +1,88 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { readFile, realpath } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { promisify } from 'node:util';
5
+ export const UPSTREAM_SOURCE = 'git:github.com/flaminigo/pi-team-mode';
6
+ const slug = 'flaminigo/pi-team-mode';
7
+ const originPattern = /^(?:https:\/\/github\.com\/|ssh:\/\/git@github\.com\/|git@github\.com:)flaminigo\/pi-team-mode(?:\.git)?\/?$/i;
8
+ const shorthandPattern = /^(?:github\.com\/|github:)flaminigo\/pi-team-mode(?:\.git)?\/?$/i;
9
+ function isOfficialSource(source) {
10
+ const text = source.trim();
11
+ if (!text.startsWith('git:'))
12
+ return /^(https|ssh):\/\//.test(text) && originPattern.test(text);
13
+ const repo = text.slice(4).trim();
14
+ return shorthandPattern.test(repo) || originPattern.test(repo);
15
+ }
16
+ const sha = /^[a-f0-9]{40}$/;
17
+ const exec = promisify(execFile);
18
+ export const UPDATE_TIMEOUT_MS = 2_000;
19
+ export function updatesDisabled(env) {
20
+ return /^(1|true|yes)$/i.test(env.PI_OFFLINE ?? '') || /^(1|true|yes)$/i.test(env.PI_TEAM_NO_UPDATE_CHECK ?? '');
21
+ }
22
+ // Check the code that was actually loaded, not the Git repository of the user's cwd.
23
+ // Require both the Pi 1.7 managed location and an unpinned package declaration.
24
+ async function managedCheckout(options, signal) {
25
+ const entry = await realpath(options.entry);
26
+ const scopes = [{ dir: options.agentDir, project: false }];
27
+ if (options.projectTrusted)
28
+ scopes.push({ dir: join(options.cwd, '.pi'), project: true });
29
+ for (const { dir, project } of scopes) {
30
+ signal.throwIfAborted();
31
+ try {
32
+ const base = await realpath(dir);
33
+ const root = join(base, 'git', 'github.com', slug);
34
+ if (entry !== join(root, 'pi-team-mode', 'src', 'extension.ts'))
35
+ continue;
36
+ const { packages } = JSON.parse(await readFile(join(base, 'settings.json'), { encoding: 'utf8', signal }));
37
+ if (!Array.isArray(packages))
38
+ continue;
39
+ if (packages.some(item => {
40
+ const source = typeof item === 'string' ? item : item?.source;
41
+ return typeof source === 'string' && isOfficialSource(source);
42
+ }))
43
+ return { root, project };
44
+ }
45
+ catch { /* Unavailable or invalid settings: no check. */ }
46
+ }
47
+ }
48
+ export async function checkForUpdate(options) {
49
+ if (updatesDisabled(options.env ?? process.env))
50
+ return;
51
+ const signal = AbortSignal.any([options.signal, AbortSignal.timeout(UPDATE_TIMEOUT_MS)]);
52
+ try {
53
+ const checkout = await managedCheckout(options, signal);
54
+ if (!checkout)
55
+ return;
56
+ const { root, project } = checkout;
57
+ const gitDir = join(root, '.git');
58
+ if (await realpath(gitDir) !== gitDir)
59
+ return;
60
+ const git = async (...args) => (await exec('git', ['--git-dir', gitDir, ...args], {
61
+ signal, maxBuffer: 4096, windowsHide: true,
62
+ })).stdout.trim();
63
+ // Raw local config (not get-url): no insteadOf expansion or remote contact.
64
+ const origin = await git('config', '--local', '--get-all', 'remote.origin.url');
65
+ if (!originPattern.test(origin))
66
+ return;
67
+ if (await git('rev-parse', '--symbolic-full-name', '@{upstream}') !== 'refs/remotes/origin/main')
68
+ return;
69
+ const installed = await git('rev-parse', '--verify', 'HEAD');
70
+ if (!sha.test(installed))
71
+ return;
72
+ signal.throwIfAborted();
73
+ const request = options.request ?? fetch;
74
+ const response = await request(`https://api.github.com/repos/${slug}/compare/${installed}...main?per_page=1`, {
75
+ headers: { Accept: 'application/vnd.github+json' }, redirect: 'error', signal,
76
+ });
77
+ if (!response.ok) {
78
+ void response.body?.cancel().catch(() => { });
79
+ return;
80
+ }
81
+ const result = await response.json();
82
+ if (!signal.aborted && result?.status === 'ahead' && result.merge_base_commit?.sha === installed &&
83
+ Number.isInteger(result.ahead_by) && result.ahead_by > 0) {
84
+ return `Team Mode update available. ${project ? 'From this project, run' : 'Run'}: pi update ${UPSTREAM_SOURCE}; then /reload.`;
85
+ }
86
+ }
87
+ catch { /* Offline, timed out, no Git, unknown commit, or unreliable response: silently skip. */ }
88
+ }
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "pi-team-mode",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Efficiency-first teams for Pi with background workers and a foreground Team Lead",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/flaminigo/pi-team-mode.git",
9
+ "directory": "pi-team-mode"
10
+ },
11
+ "type": "module",
12
+ "engines": { "node": ">=22" },
13
+ "keywords": ["pi-package", "pi", "team"],
14
+ "files": ["dist", "README.md", "LICENSE"],
15
+ "pi": { "extensions": ["./dist/extension.js"] },
16
+ "scripts": {
17
+ "build": "tsc -p tsconfig.json",
18
+ "test": "npm run build && node --test test/*.test.mjs",
19
+ "test:pi": "npm run build && python3 test/pi-smoke.py",
20
+ "prepack": "npm run build && node -e \"require('node:fs').copyFileSync('../LICENSE', 'LICENSE')\""
21
+ },
22
+ "peerDependencies": {
23
+ "@earendil-works/pi-coding-agent": "*",
24
+ "@earendil-works/pi-ai": "*",
25
+ "typebox": "*"
26
+ },
27
+ "devDependencies": {
28
+ "@earendil-works/pi-coding-agent": "1.7.0",
29
+ "@earendil-works/pi-ai": "1.7.0",
30
+ "@types/node": "^24.0.0",
31
+ "typebox": "^1.3.27",
32
+ "typescript": "^6.0.1"
33
+ }
34
+ }