pi-team-mode 0.1.7 → 0.1.9
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 +30 -10
- package/dist/backend.js +31 -31
- package/dist/config.js +16 -7
- package/dist/dispatch-call.js +3 -7
- package/dist/extension.js +125 -13
- package/dist/profile-templates.js +1 -1
- package/dist/role-colors.js +8 -0
- package/dist/scheduler.js +35 -4
- package/dist/status-view.js +4 -2
- package/dist/team-agents.js +119 -0
- package/dist/worker-activity.js +78 -0
- package/package.json +1 -1
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
|
-
**0.1.7** adds optional skill indexes to worker roles without changing dispatch backends or the native Agents display. **0.1.6** adds live worker models to **Status**, remembers the selected profile per Pi session, and shows live scheduler counts in the footer. **0.1.5** introduced padded role badges and removed the duplicate queue acknowledgement. **0.1.4** was not published to npm.
|
|
5
|
+
**0.1.8** adds the SDK-only **Team Agents** tree and session-scoped **Backend** and **Concurrency** controls. **0.1.7** adds optional skill indexes to worker roles without changing dispatch backends or the native Agents display. **0.1.6** adds live worker models to **Status**, remembers the selected profile per Pi session, and shows live scheduler counts in the footer. **0.1.5** introduced padded role badges and removed the duplicate queue acknowledgement. **0.1.4** was not published to npm.
|
|
6
6
|
|
|
7
7
|
**0.1.3** adds personal profiles, template-based creation, and a Team Mode menu. As in **0.1.2**, compatible stock subagents show Team role badges and task briefs in the native Agents rows. Team generates definitions on first dispatch; SDK-only installs still work without stock subagents.
|
|
8
8
|
|
|
@@ -18,28 +18,45 @@ On fresh TUI startup, an unpinned, Pi-managed install from the official GitHub r
|
|
|
18
18
|
|
|
19
19
|
Use `pi update npm:pi-team-mode` for npm installs or `pi update git:github.com/flaminigo/pi-team-mode` for GitHub installs to update just Team Mode, then `/reload` or restart Pi. Run it from the trusted project for project-scoped installs (`--approve` if trust isn’t saved). On Pi 1.7, `pi update --extensions` updates all packages and `pi update` updates Pi itself; `pi upgrade --extensions` is not valid. For this nested local checkout, rebuild after changing source, then reload. If `pi list` already shows the repository root, `/reload` or a restart reads the working-tree TypeScript without a build or reinstall. To switch sources, remove the old source in its original scope before installing the checkout.
|
|
20
20
|
|
|
21
|
-
Open `/team` → **Status** or run `/team status` for the same read-only view. It keeps the selected profile, on/off or blocked state, and task IDs and states (including settled tasks). The **Live workers** section lists queued, starting, and running Team jobs on either backend, showing the configured role, task ID, brief preview, and the exact `provider/model-id` once the worker starts. Before then it shows `pending` (with the pin if explicit), or `inherits foreground at start` when the queued job is set to inherit. Use ↑/↓ or `j`/`k` to scroll and Esc to close. Opening the view does not make model requests. The dispatch transcript still shows only the padded role badge, brief and `background` for each task; the Lead still receives the original queue result.
|
|
21
|
+
Open `/team` → **Status** or run `/team status` for the same read-only view. It keeps the selected profile, on/off or blocked state, effective concurrency, and task IDs and states (including settled tasks). The **Live workers** section lists queued, starting, and running Team jobs on either backend, showing the configured role, task ID, brief preview, and the exact `provider/model-id` once the worker starts. Before then it shows `pending` (with the pin if explicit), or `inherits foreground at start` when the queued job is set to inherit. Use ↑/↓ or `j`/`k` to scroll and Esc to close. Opening the view does not make model requests. The dispatch transcript still shows only the padded role badge, brief and `background` for each task; the Lead still receives the original queue result.
|
|
22
22
|
|
|
23
|
-
|
|
23
|
+
Open `/team` → **Backend** to see the effective preference and its source. **Auto** (the default) prefers ready, compatible `pi-subagents` for eligible jobs, otherwise uses the built-in Pi SDK. **SDK** routes all new Team worker launches to the SDK. Jobs waiting in Team's scheduler use the preference when they start; workers already starting, running, or queued by stock keep their route. The picker does not dispatch, cancel, or retry workers, and it leaves the stock extension, its **Agents** widget, and non-Team jobs alone.
|
|
24
|
+
|
|
25
|
+
**Use config** clears the session override and records that choice, so an older override on the same branch does not come back. The picker and **Status** show the effective preference and its source. The latest choice on the active branch survives profile changes, Team on/off, `/team config reload`, Pi `/reload`, and resume of the same session. `/tree` restores the choice at the selected point; a new session, including a fork or clone, uses current config. The picker writes only Pi session metadata, not global or project settings, and no jobs are replayed. Before Pi saves a conversation, or with `--no-session`, choices are held in memory. For a lasting default, set top-level `"backend": "auto"` or `"backend": "sdk"` in personal or trusted project `team-mode.json` and run `/team config reload` when idle. Precedence is session override > trusted project value > personal value > built-in Auto.
|
|
26
|
+
|
|
27
|
+
On the stock route (`@tintinweb/pi-subagents` 0.26.3 tested), 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.
|
|
24
28
|
|
|
25
29
|
**Extension-registered models:** Stock 0.26.3 inherits the foreground Pi model runtime. Except for Cursor (below), SDK workers replay only the selected provider's Pi registration (including its stream/auth callbacks) in their own runtime; they use Pi's normal auth configuration and do not reload extensions or copy session-only credentials. This supports providers whose registrations work without child extension lifecycle hooks. Team reports an unregistered provider, an unlisted model, or an unavailable model without choosing a substitute.
|
|
26
30
|
|
|
27
|
-
Explicit tool allowlists, SDK continuations, and unavailable native definitions use Pi SDK child sessions without
|
|
31
|
+
Explicit tool allowlists, SDK continuations, and unavailable native definitions use Pi SDK child sessions without a stock Agents row. Except for Cursor, model and thinking settings do not by themselves change routes on a compatible build. SDK workers use core Pi tools, not foreground extensions. `/team doctor` reports the preference and compatible RPC readiness, not exact definition resolution. Fallback to SDK happens only before an RPC spawn attempt; a rejection, timeout or mismatched type is not retried on SDK. 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.
|
|
32
|
+
|
|
33
|
+
The separate **● Team Agents** tree above the editor shows only jobs routed to the SDK. A magenta heading tops aligned rows with a status indicator, a bold padded role badge, the exact confirmed model (`pending` during startup, `not started` if it settles before start), and a task preview. The status column is one cell wide: a spinner for running jobs, a green `✓` for successful jobs, and a distinct glyph for other states. Labels such as `failed`, `cancelled`, and `queued` follow the task preview when there’s room. Tasks still waiting for a backend are shown only in **Status**.
|
|
34
|
+
|
|
35
|
+
The Braille spinner indicates an in-progress job, not model thinking. When there’s room, a child line shows `thinking…` only during an observed thinking stream, `responding…` during a text stream, or a tool action such as `running command…` during execution. It shows `working…` when Pi reports no specific activity. The line never displays streamed content, tool arguments, or tool results. It clears when the job settles or is cancelled; a cancelled job keeps its slot and says `stopping` until it unwinds. One visual-only timer redraws while SDK jobs are running; it does not poll workers or run inference. The tree keeps up to five recent outcomes, fits a bounded viewport, and clears on reset, profile change, config reload, disable, or runtime replacement. **Status** remains the combined view.
|
|
36
|
+
|
|
37
|
+
### Worker follow-ups
|
|
38
|
+
|
|
39
|
+
Lead dispatches fresh by default. If the follow-up needs context a short brief can’t carry, Lead sets `resume` to the completed same-role task ID. For example, to have Coder use the investigation from `trace-startup` to diagnose a retry failure, Lead dispatches a new `check-retry` Coder task with `resume: "trace-startup"`. Lead decides when to request it; Team Mode checks compatibility, routes the job, and handles fallback.
|
|
40
|
+
|
|
41
|
+
A retained SDK session can be reused in **Auto** or **SDK** with the same role, exact model, and tool list. The SDK keeps up to six sessions in memory and evicts the earliest-retained one on overflow, regardless of dispatch order. Reuse consumes the old resume reference. If `check-retry` completes and retains the session, use `check-retry`, not `trace-startup`, for the next continuation. Tasks and retained sessions do not survive `/reload` or reopening Pi.
|
|
42
|
+
|
|
43
|
+
If the prior task is still known but its SDK session is evicted, otherwise unavailable, or incompatible, or the prior task ran on stock RPC, the follow-up starts fresh with a compact `Earlier result` summary instead of transcript history. Status and `team_results` do not label the continuation outcome. Keeping history for a follow-up does not guarantee token savings.
|
|
28
44
|
|
|
29
45
|
### Cursor workers
|
|
30
46
|
|
|
31
47
|
To use a Cursor model for an unrestricted role, select its exact `cursor/<model-id>` in `/team model` or in that role’s model pool. Team requires `npm:pi-cursor-sdk` to be enabled, installed, and configured in Pi’s user settings or in a project Pi has trusted. Team does not install it, accept a task-supplied extension path, or reload unrelated extensions. The selected model must be in the worker’s own Cursor catalog and usable with Pi’s configured Cursor authentication. Team does not fall back to another model.
|
|
32
48
|
|
|
33
|
-
Cursor workers always use the Pi SDK, even with stock subagents available. Each worker owns its Cursor extension binding and model runtime; cancellation and recent-task continuation work through Team. These workers appear in Team’s dispatch and results, **not** in the native **Agents** hierarchy. Compatibility with `pi-cursor-sdk` 0.5.32 was verified offline without real auth or Cursor requests.
|
|
49
|
+
Cursor workers always use the Pi SDK, even with stock subagents available. Each worker owns its Cursor extension binding and model runtime; cancellation and recent-task continuation work through Team. These workers appear in **Team Agents**, Team’s dispatch and results, **not** in the native **Agents** hierarchy. Compatibility with `pi-cursor-sdk` 0.5.32 was verified offline without real auth or Cursor requests.
|
|
34
50
|
|
|
35
51
|
Cursor’s native tools and ambient MCP configuration are separate from Pi’s tool list. Team fails closed for roles with an explicit `access.tools` allowlist rather than running a Cursor worker that could exceed it. In a project Pi does not trust, start Pi with `PI_CURSOR_SETTING_SOURCES=none` to prevent Cursor from loading ambient settings. Team does not change Cursor settings or process environment for you.
|
|
36
52
|
|
|
37
53
|
## Use
|
|
38
54
|
|
|
39
|
-
- `/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.
|
|
55
|
+
- `/team` opens the Team Mode menu: **Switch profile**, **Create profile from template**, **Turn Team Mode off/on**, **Status**, **Configure role model**, **Concurrency**, **Backend**, and **Help**. Navigate with ↑/↓ and Enter; Esc closes the current picker. `/team profile` opens the profile-ID picker directly. `/team help` lists all commands.
|
|
40
56
|
- `/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`.
|
|
41
57
|
- `/team on`, `/team off`, `/team status`, `/team cancel`, `/team reset`, `/team doctor`.
|
|
42
58
|
- `/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.
|
|
59
|
+
- **Concurrency** or `/team concurrency 10` sets a session ceiling override; enter `default` in the picker or run `/team concurrency default` to use config.
|
|
43
60
|
- `/team config edit [project]`, `/team config validate`, `/team config reload`.
|
|
44
61
|
- **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.
|
|
45
62
|
|
|
@@ -47,7 +64,7 @@ The last explicitly selected profile is remembered in the current Pi session and
|
|
|
47
64
|
|
|
48
65
|
The footer shows the active profile and live counts: queued, starting, confirmed running, stopping, and outcomes. Outcome counts stay until you reset, change profiles, reload, or turn Team Mode off. Only SDK-reported Pi tools contribute to the optional `using tools` count. Stock RPC reports its lifecycle without guessing at tool use or thinking; neither backend infers thinking from model settings.
|
|
49
66
|
|
|
50
|
-
Team Mode ships a read-only catalog: `engineer_template`, `research_template`, `audit_template`. These IDs are for copying, not switching. On interactive activation (including `/reload`), Team saves only missing personal `engineer`, `research`, and `audit` profiles as JSON in `<Pi agent directory>/team-mode-profiles/`. Saved profiles are full copies; inline personal entries (including sparse ones) count as existing profiles and are never rewritten by seeding. The effective order is built-in fallback → full personal files by ID → inline `team-mode.json` → trusted `.pi/team-mode.json`. Personal files do not inherit later template changes. If a starter file is removed and no inline entry exists, the next interactive activation backfills it again.
|
|
67
|
+
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. Built-in defaults and new copies ask Lead to own recovery and replanning, without changing existing saved scopes or explicit overrides.
|
|
51
68
|
|
|
52
69
|
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`.
|
|
53
70
|
|
|
@@ -58,6 +75,7 @@ User settings live in `<Pi agent directory>/team-mode.json`; trusted project ove
|
|
|
58
75
|
```json
|
|
59
76
|
{
|
|
60
77
|
"schemaVersion": 1,
|
|
78
|
+
"backend": "auto",
|
|
61
79
|
"concurrency": 5,
|
|
62
80
|
"profiles": {
|
|
63
81
|
"engineer": {
|
|
@@ -70,7 +88,9 @@ User settings live in `<Pi agent directory>/team-mode.json`; trusted project ove
|
|
|
70
88
|
}
|
|
71
89
|
```
|
|
72
90
|
|
|
73
|
-
`concurrency` is an integer from 1 to 20 and defaults to **5**. It's a ceiling on simultaneous worker jobs per Team session, not a target: Lead dispatches only useful work, and the scheduler starts only ready jobs.
|
|
91
|
+
`concurrency` is an integer from 1 to 20 and defaults to **5**. It's a ceiling on simultaneous worker jobs per Team session, not a target: Lead dispatches only useful work, and the scheduler starts only ready jobs. Precedence is session override > trusted project value > personal value > built-in 5. Like Backend, the choice is saved in Pi session metadata on the active branch. It survives profile changes, Team on/off, `/team config reload`, Pi `/reload`, and resume or switching back to that session. `/tree` restores the choice at the selected point; new sessions, including forks and clones, use current config. `default` records an explicit clear so an older override on the branch doesn't return. Before Pi saves a conversation, or with `--no-session`, choices are held in memory. No global or project settings are written, and no jobs are replayed.
|
|
92
|
+
|
|
93
|
+
Raising the ceiling immediately schedules ready jobs; lowering it never cancels or evicts active jobs. See the effective value and source in **Status** and the **Concurrency** picker. The separate limit of 16 tasks per dispatch is unchanged; the concurrency ceiling applies across dispatches. Stock subagents and model providers may allow fewer workers to run at once. Jobs marked as writers still run one at a time in the shared workspace.
|
|
74
94
|
|
|
75
95
|
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.
|
|
76
96
|
|
|
@@ -116,9 +136,9 @@ npm pack --dry-run # preview release contents; does not publish
|
|
|
116
136
|
|
|
117
137
|
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.
|
|
118
138
|
|
|
119
|
-
Before publication, run `python3 test/npm-tarball-smoke.py /path/to/pi-team-mode-0.1.
|
|
139
|
+
Before publication, run `python3 test/npm-tarball-smoke.py /path/to/pi-team-mode-0.1.8.tgz` to serve the exact MIT tarball from a loopback npm registry. After publication, run `python3 test/pi-smoke.py npm:pi-team-mode <version>` to check the actual npm install and version in a disposable Pi home. The package install uses the npm registry, but the TUI and worker use only the loopback fake model.
|
|
120
140
|
|
|
121
|
-
To exercise the native Agents rows, set `PI_TEAM_TEST_SUBAGENTS` to the absolute path of an unmodified local `@tintinweb/pi-subagents` 0.26.3 package before running `npm run test:pi`. The PTY uses fake loopback models and checks both Status entry points, no extra inference, live model and settled summary updates, profile seeding, the `/team` menu (template copy and switch, role-model picker and
|
|
141
|
+
To exercise the native Agents rows, set `PI_TEAM_TEST_SUBAGENTS` to the absolute path of an unmodified local `@tintinweb/pi-subagents` 0.26.3 package before running `npm run test:pi`. The PTY uses fake loopback models and checks both Status entry points, no extra inference, live model and settled summary updates, profile seeding, the `/team` menu (template copy and switch, role-model picker, toggle, concurrency, and Backend override/reset), CLI help and input errors, the `my-engineering` CLI create, edit, reload and no-clobber workflow, first-dispatch definition creation, reuse after `/reload`, Engineer, Research and My Engineering Validator rows (red, no suffix, plain brief), exact profile prompt/model/thinking/tools, and an ordinary `Agent (twin)` launched with the stock Agent tool. From the repository root, run `python3 pi-team-mode/test/pi-smoke.py --git-mirror .` to test the committed `main` via a private temporary Git mirror and a mocked GitHub response. Local-source smoke runs check that the Research worker uses an extension-only loopback provider without reloading the provider extension. Local and npm smoke runs (npm 0.1.8 and later) also check that Concurrency survives `/reload` and reopening, `/new` starts at 5, `/resume` restores each of two saved sessions' own ceiling, and `default` survives reload and reopening without replaying work. These checks run with or without stock subagents. All smoke paths use a disposable Pi config and fake credentials. Run the stock smoke again with `PI_TEAM_TEST_BACKEND=sdk` to select SDK through the picker, dispatch through the SDK after `/reload` with stock installed, and check the picker, Status and Doctor on resume. That run also checks `/new` isolation, switching back with `/resume`, and **Use config** surviving reload and a subsequent reopen without replaying work. The same stock and forced-SDK flags work with the loopback tarball smoke.
|
|
122
142
|
|
|
123
143
|
To check Cursor ownership offline with Node 24, build and run `PI_TEAM_TEST_CURSOR=/absolute/path/to/installed/pi-cursor-sdk node --test test/cursor-worker.test.mjs`. The fixture expects 0.5.32, uses a disposable Pi home and fake credential, and stubs the Cursor SDK and network transport. It leaves the real Cursor extension registration, ownership guard, and session hooks in place.
|
|
124
144
|
|
package/dist/backend.js
CHANGED
|
@@ -2,11 +2,12 @@ import { randomUUID } from 'node:crypto';
|
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { createAgentSession, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
|
|
4
4
|
import { checkCursorWorkerPolicy, closeCursorWorker, createCursorWorker } from './cursor-worker.js';
|
|
5
|
+
import { trackWorkerActivity } from './worker-activity.js';
|
|
5
6
|
export class NativeBackend {
|
|
6
7
|
cwd;
|
|
7
8
|
agentDir;
|
|
8
9
|
retained = new Map();
|
|
9
|
-
running = new
|
|
10
|
+
running = new Map();
|
|
10
11
|
pending = new Set();
|
|
11
12
|
closed = false;
|
|
12
13
|
constructor(cwd, agentDir) {
|
|
@@ -52,8 +53,16 @@ export class NativeBackend {
|
|
|
52
53
|
({ session } = await createAgentSession({ cwd: this.cwd, agentDir: this.agentDir, model: work.model, modelRuntime,
|
|
53
54
|
thinkingLevel: work.thinkingLevel, tools: work.tools, sessionManager: SessionManager.inMemory(this.cwd), settingsManager, resourceLoader }));
|
|
54
55
|
}
|
|
55
|
-
|
|
56
|
-
|
|
56
|
+
const activity = trackWorkerActivity(update => work.activity?.(update));
|
|
57
|
+
let stopping = false;
|
|
58
|
+
const stop = () => {
|
|
59
|
+
if (stopping)
|
|
60
|
+
return;
|
|
61
|
+
stopping = true;
|
|
62
|
+
void session.abort().catch(() => { });
|
|
63
|
+
activity.reset();
|
|
64
|
+
};
|
|
65
|
+
this.running.set(session, stop);
|
|
57
66
|
signal.addEventListener('abort', stop, { once: true });
|
|
58
67
|
let retain = false;
|
|
59
68
|
try {
|
|
@@ -70,22 +79,15 @@ export class NativeBackend {
|
|
|
70
79
|
throw Error(`Worker session did not select the exact model ${model}.`);
|
|
71
80
|
}
|
|
72
81
|
const start = session.messages.length;
|
|
73
|
-
const activeTools = new Set();
|
|
74
82
|
let started = false;
|
|
75
83
|
const unsubscribe = session.subscribe(event => {
|
|
76
|
-
if (
|
|
84
|
+
if (stopping || signal.aborted)
|
|
85
|
+
return;
|
|
86
|
+
if (event.type === 'agent_start' && !started) {
|
|
77
87
|
started = true;
|
|
78
88
|
work.started(actual);
|
|
79
89
|
}
|
|
80
|
-
|
|
81
|
-
return;
|
|
82
|
-
const wasActive = activeTools.size > 0;
|
|
83
|
-
if (event.type === 'tool_execution_start')
|
|
84
|
-
activeTools.add(event.toolCallId);
|
|
85
|
-
else
|
|
86
|
-
activeTools.delete(event.toolCallId);
|
|
87
|
-
if (wasActive !== (activeTools.size > 0))
|
|
88
|
-
work.toolsActive?.(!wasActive);
|
|
90
|
+
activity.accept(event);
|
|
89
91
|
});
|
|
90
92
|
const cursorFailure = `Cursor worker could not complete ${model}. Check Cursor authentication, model availability, and pi-cursor-sdk setup in Pi.`;
|
|
91
93
|
try {
|
|
@@ -99,8 +101,7 @@ export class NativeBackend {
|
|
|
99
101
|
}
|
|
100
102
|
finally {
|
|
101
103
|
unsubscribe();
|
|
102
|
-
|
|
103
|
-
work.toolsActive?.(false);
|
|
104
|
+
activity.reset();
|
|
104
105
|
}
|
|
105
106
|
signal.throwIfAborted();
|
|
106
107
|
const last = session.messages.slice(start).findLast(m => m.role === 'assistant');
|
|
@@ -133,8 +134,8 @@ export class NativeBackend {
|
|
|
133
134
|
}
|
|
134
135
|
async dispose() {
|
|
135
136
|
this.closed = true;
|
|
136
|
-
for (const
|
|
137
|
-
|
|
137
|
+
for (const stop of this.running.values())
|
|
138
|
+
stop();
|
|
138
139
|
const retained = [...this.retained.values()];
|
|
139
140
|
this.retained.clear();
|
|
140
141
|
await Promise.allSettled([...this.pending, ...retained.map(({ session }) => this.closeSession(session))]);
|
|
@@ -180,28 +181,27 @@ export function workerResult(text, resume) {
|
|
|
180
181
|
export class SubagentsBackend {
|
|
181
182
|
bus;
|
|
182
183
|
available = false;
|
|
183
|
-
|
|
184
|
+
probeRevision = 0;
|
|
184
185
|
closed = false;
|
|
185
186
|
subscriptions;
|
|
186
187
|
constructor(bus) {
|
|
187
188
|
this.bus = bus;
|
|
188
189
|
this.subscriptions = [bus.on('subagents:ready', () => { void this.probe(); }),
|
|
189
|
-
bus.on('subagents:disposed', () => { this.available = false; })];
|
|
190
|
+
bus.on('subagents:disposed', () => { this.available = false; this.probeRevision++; })];
|
|
190
191
|
}
|
|
191
192
|
get ready() { return this.available && !this.closed; }
|
|
192
193
|
supports(work) {
|
|
193
|
-
return work.model.provider !== 'cursor' && this.ready &&
|
|
194
|
+
return work.model.provider !== 'cursor' && this.ready && work.tools === undefined && work.resume === undefined;
|
|
194
195
|
}
|
|
195
196
|
async probe() {
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
this.available = false;
|
|
197
|
+
if (this.closed)
|
|
198
|
+
return false;
|
|
199
|
+
const revision = ++this.probeRevision;
|
|
200
|
+
const ping = await this.rpc('ping', {}, 200).catch(() => undefined);
|
|
201
|
+
// The `get` marker identifies RPC v2 builds with owned snapshots and
|
|
202
|
+
// documented spawn.options.thinkingLevel forwarding (0.26.2+).
|
|
203
|
+
if (revision === this.probeRevision) {
|
|
204
|
+
this.available = ping?.version === 2 && Array.isArray(ping.features) && ping.features.includes('get');
|
|
205
205
|
}
|
|
206
206
|
return this.ready;
|
|
207
207
|
}
|
|
@@ -328,6 +328,6 @@ export class SubagentsBackend {
|
|
|
328
328
|
off();
|
|
329
329
|
}
|
|
330
330
|
}
|
|
331
|
-
dispose() { this.closed = true; for (const off of this.subscriptions)
|
|
331
|
+
dispose() { this.closed = true; this.probeRevision++; for (const off of this.subscriptions)
|
|
332
332
|
off(); }
|
|
333
333
|
}
|
package/dist/config.js
CHANGED
|
@@ -8,10 +8,19 @@ export function resolvePoolEntry(entry, aliases) {
|
|
|
8
8
|
: { ...modelRef(entry.model, aliases), thinkingLevel: entry.thinkingLevel };
|
|
9
9
|
}
|
|
10
10
|
const DEFAULT_CONCURRENCY = 5;
|
|
11
|
-
const MAX_CONCURRENCY = 20;
|
|
11
|
+
export const MAX_CONCURRENCY = 20;
|
|
12
|
+
export function isConcurrency(value) {
|
|
13
|
+
return typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= MAX_CONCURRENCY;
|
|
14
|
+
}
|
|
15
|
+
export function checkedConcurrency(value) {
|
|
16
|
+
if (!isConcurrency(value)) {
|
|
17
|
+
throw Error(`concurrency: expected integer 1–${MAX_CONCURRENCY}`);
|
|
18
|
+
}
|
|
19
|
+
return value;
|
|
20
|
+
}
|
|
12
21
|
// Keep the old fallback layer so sparse files and read-only homes remain runnable.
|
|
13
22
|
export function defaults() {
|
|
14
|
-
return { schemaVersion: 1, enabled: true, defaultProfile: 'engineer', concurrency: DEFAULT_CONCURRENCY, aliases: {},
|
|
23
|
+
return { schemaVersion: 1, enabled: true, defaultProfile: 'engineer', concurrency: DEFAULT_CONCURRENCY, backend: 'auto', aliases: {},
|
|
15
24
|
profiles: Object.fromEntries(Object.entries(starterProfiles).map(([id, template]) => [id, copyTemplate(template)])) };
|
|
16
25
|
}
|
|
17
26
|
const obj = (value, path) => {
|
|
@@ -131,11 +140,11 @@ export function parseConfig(user = {}, project = {}, personalProfiles = {}) {
|
|
|
131
140
|
const defaultProfile = text(raw.defaultProfile, 'defaultProfile');
|
|
132
141
|
if (!Object.hasOwn(profiles, defaultProfile))
|
|
133
142
|
throw Error(`Unknown default profile ${defaultProfile}`);
|
|
134
|
-
const
|
|
135
|
-
if (
|
|
136
|
-
throw Error(
|
|
137
|
-
|
|
138
|
-
|
|
143
|
+
const backend = raw.backend;
|
|
144
|
+
if (backend !== 'auto' && backend !== 'sdk')
|
|
145
|
+
throw Error('backend: expected auto or sdk');
|
|
146
|
+
return { schemaVersion: 1, profiles, defaultProfile, backend, concurrency: checkedConcurrency(raw.concurrency),
|
|
147
|
+
aliases, enabled: bool(raw.enabled, 'enabled') };
|
|
139
148
|
}
|
|
140
149
|
export function configPaths(agentDir, cwd) {
|
|
141
150
|
return { user: join(agentDir, 'team-mode.json'), project: join(cwd, '.pi', 'team-mode.json') };
|
package/dist/dispatch-call.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Container,
|
|
2
|
-
import {
|
|
1
|
+
import { Container, visibleWidth } from '@earendil-works/pi-tui';
|
|
2
|
+
import { roleBadge } from './role-colors.js';
|
|
3
3
|
import { clip, singleLine } from './ui-text.js';
|
|
4
4
|
const queueText = (ids) => `Queued: ${ids.join(', ')}. Team Mode will notify you when a decision or final summary is due.`;
|
|
5
5
|
export function dispatchQueuedResult(ids) {
|
|
@@ -47,11 +47,7 @@ export function renderDispatchCall(args, theme, context, currentProfile) {
|
|
|
47
47
|
const showBackground = textRoom >= 2;
|
|
48
48
|
const roleWidth = showBackground ? Math.floor(textRoom / 2) : width - padding;
|
|
49
49
|
const label = `${pad}${clip(name, roleWidth)}${pad}`;
|
|
50
|
-
const
|
|
51
|
-
// Match stock's high-contrast foreground for these fixed palette colors.
|
|
52
|
-
const lightText = role === 'validator' || (role === 'researcher' && theme.getColorMode() === 'truecolor');
|
|
53
|
-
const badge = color ? theme.style(label, { bg: parseColor(color.hex), fg: parseColor(lightText ? '#FFFFFF' : '#000000'), bold: true })
|
|
54
|
-
: theme.style(label, { bg: 'selectedBg', fg: 'text', bold: true });
|
|
50
|
+
const badge = roleBadge(role, label, theme);
|
|
55
51
|
// Restore Pi's enclosing tool-card background after the badge's reset.
|
|
56
52
|
if (showBackground)
|
|
57
53
|
return `${badge}${shellBg} ${clip(brief, room - visibleWidth(label))} ${background}`;
|
package/dist/extension.js
CHANGED
|
@@ -4,7 +4,7 @@ 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 { configInputs, configPaths, defaults, loadConfig, parseConfig, resolvePoolEntry } from './config.js';
|
|
7
|
+
import { checkedConcurrency, isConcurrency, MAX_CONCURRENCY, configInputs, configPaths, defaults, loadConfig, parseConfig, resolvePoolEntry } from './config.js';
|
|
8
8
|
import { createProfile, seedProfiles } from './profiles.js';
|
|
9
9
|
import { templateIds } from './profile-templates.js';
|
|
10
10
|
import { ModelPools, modelRef } from './models.js';
|
|
@@ -16,9 +16,31 @@ import { ensureWorkerType, roleBody, workerRules } from './worker-agents.js';
|
|
|
16
16
|
import { workerSkillIndex } from './worker-skills.js';
|
|
17
17
|
import { dispatchQueuedResult, renderDispatchCall, renderDispatchResult } from './dispatch-call.js';
|
|
18
18
|
import { statusView } from './status-view.js';
|
|
19
|
+
import { teamAgentsWidget } from './team-agents.js';
|
|
19
20
|
const keys = ['team_dispatch', 'team_results', 'team_publish'];
|
|
20
21
|
const statusKey = 'team-mode';
|
|
22
|
+
const agentsWidgetKey = 'pi-team-mode:team-agents';
|
|
21
23
|
const profileEntry = 'pi-team-mode-profile';
|
|
24
|
+
const backendEntry = 'pi-team-mode-backend';
|
|
25
|
+
const concurrencyEntry = 'pi-team-mode-concurrency';
|
|
26
|
+
function lastOverride(ctx, type, key, valid) {
|
|
27
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
28
|
+
// Forks and clones can copy the entries, but get a different session ID.
|
|
29
|
+
for (const entry of ctx.sessionManager.getBranch().reverse()) {
|
|
30
|
+
if (entry.type !== 'custom' || entry.customType !== type)
|
|
31
|
+
continue;
|
|
32
|
+
const data = entry.data;
|
|
33
|
+
if (!data || typeof data !== 'object' || !('sessionId' in data) || data.sessionId !== sessionId)
|
|
34
|
+
continue;
|
|
35
|
+
const value = data[key];
|
|
36
|
+
if (value === null)
|
|
37
|
+
return undefined; // Explicit Use config, not a missing override.
|
|
38
|
+
if (valid(value))
|
|
39
|
+
return value;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const lastBackend = (ctx) => lastOverride(ctx, backendEntry, 'backend', (value) => value === 'auto' || value === 'sdk');
|
|
43
|
+
const lastConcurrency = (ctx) => lastOverride(ctx, concurrencyEntry, 'concurrency', isConcurrency);
|
|
22
44
|
function lastProfile(ctx) {
|
|
23
45
|
// This preference is session-wide, not branch-local model context.
|
|
24
46
|
for (const entry of ctx.sessionManager.getEntries().reverse()) {
|
|
@@ -31,10 +53,12 @@ function lastProfile(ctx) {
|
|
|
31
53
|
}
|
|
32
54
|
const createUsage = 'Usage: /team profile create <id> --from <template>';
|
|
33
55
|
const modelUsage = 'Usage: /team model <role> <provider/model-id> (or configured alias)';
|
|
56
|
+
const concurrencyUsage = `Usage: /team concurrency <1–${MAX_CONCURRENCY}|default>`;
|
|
34
57
|
const configUsage = 'Usage: /team config edit [project] | validate | reload';
|
|
35
58
|
const teamHelp = [
|
|
36
|
-
'/team — open the Team Mode menu',
|
|
37
|
-
'/team status — show Team status and live worker models',
|
|
59
|
+
'/team — open the Team Mode menu (including the session Backend picker)',
|
|
60
|
+
'/team status — show Team status, effective concurrency, and live worker models',
|
|
61
|
+
'/team concurrency [<1–20>|default] — set or clear the session ceiling override',
|
|
38
62
|
'/team profile [<id>] — pick or switch profiles',
|
|
39
63
|
'/team profile create <id> --from <template> — save a personal copy',
|
|
40
64
|
`Templates: ${templateIds.join(', ')}`,
|
|
@@ -55,6 +79,7 @@ export function leadPrompt(profile) {
|
|
|
55
79
|
.map(([id, role]) => `${id}: ${role.workScope}`).join('\n');
|
|
56
80
|
return `You are ${lead.name} in the ${profile.name} team (${lead.personality}). ${lead.workScope}\n` +
|
|
57
81
|
'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. ' +
|
|
82
|
+
'Dispatch fresh unless a specific follow-up needs context a short brief cannot carry; then pass the completed same-role task ID in resume. ' +
|
|
58
83
|
'Use dependencies for preplanned work; mark all editing jobs writes=true. Do not redispatch merely to check progress. ' +
|
|
59
84
|
'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;
|
|
60
85
|
}
|
|
@@ -87,7 +112,33 @@ export default function teamExtension(pi) {
|
|
|
87
112
|
let publicationGeneration = 0;
|
|
88
113
|
const reported = new WeakSet();
|
|
89
114
|
let refreshStatusView;
|
|
115
|
+
let concurrencyOverride;
|
|
116
|
+
let backendOverride;
|
|
117
|
+
let agentsWidget;
|
|
118
|
+
let agentsUI;
|
|
90
119
|
const roles = () => config.profiles[selected];
|
|
120
|
+
const concurrency = () => concurrencyOverride ?? config.concurrency;
|
|
121
|
+
const concurrencyText = () => `Concurrency: ${concurrency()} (${concurrencyOverride === undefined ? 'config' : 'session override'})`;
|
|
122
|
+
const backendPreference = () => backendOverride ?? config.backend;
|
|
123
|
+
const backendText = () => `Backend: ${backendPreference()} (${backendOverride === undefined ? 'config' : 'session override'})`;
|
|
124
|
+
function clearAgents() {
|
|
125
|
+
agentsUI?.setWidget(agentsWidgetKey, undefined);
|
|
126
|
+
agentsUI = undefined;
|
|
127
|
+
agentsWidget = undefined;
|
|
128
|
+
}
|
|
129
|
+
function reportAgents(ctx) {
|
|
130
|
+
if (!interactive(ctx))
|
|
131
|
+
return;
|
|
132
|
+
const rows = enabled ? scheduler?.teamAgents() : undefined;
|
|
133
|
+
if (!rows?.length)
|
|
134
|
+
clearAgents();
|
|
135
|
+
else if (agentsWidget)
|
|
136
|
+
agentsWidget.update(rows);
|
|
137
|
+
else {
|
|
138
|
+
agentsUI = ctx.ui;
|
|
139
|
+
ctx.ui.setWidget(agentsWidgetKey, (tui, theme) => agentsWidget = teamAgentsWidget(tui, theme, role => roles().roles[role]?.name, rows));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
91
142
|
function restoreProfile(ctx) {
|
|
92
143
|
selected = preferredProfile && Object.hasOwn(config.profiles, preferredProfile) ? preferredProfile : config.defaultProfile;
|
|
93
144
|
if (!error && preferredProfile && selected !== preferredProfile) {
|
|
@@ -99,11 +150,12 @@ export default function teamExtension(pi) {
|
|
|
99
150
|
if (!ctx?.hasUI)
|
|
100
151
|
return;
|
|
101
152
|
const counts = Object.entries(scheduler?.counts() ?? {}).filter(([, n]) => n).map(([label, n]) => `${n} ${label}`);
|
|
102
|
-
const usingTools = scheduler?.list().filter(job => job.state === 'running' && job.toolsActive).length ?? 0;
|
|
153
|
+
const usingTools = scheduler?.list().filter(job => job.state === 'running' && job.activity?.toolsActive).length ?? 0;
|
|
103
154
|
if (usingTools)
|
|
104
155
|
counts.push(`${usingTools} using tools`);
|
|
105
156
|
const bits = [roles().name, ...(error ? ['blocked'] : counts)];
|
|
106
157
|
ctx.ui.setStatus(statusKey, enabled ? `Team: ${bits.join(' · ')}` : undefined);
|
|
158
|
+
reportAgents(ctx);
|
|
107
159
|
};
|
|
108
160
|
function applyTools() {
|
|
109
161
|
if (enabled) {
|
|
@@ -159,7 +211,9 @@ export default function teamExtension(pi) {
|
|
|
159
211
|
return { model, ref };
|
|
160
212
|
}
|
|
161
213
|
function newScheduler() {
|
|
162
|
-
const generation = new Scheduler(
|
|
214
|
+
const generation = new Scheduler(concurrency(), async (task, deps, signal, observe) => {
|
|
215
|
+
// Scheduler waiters pick up changes, but an attempt already starting keeps its preference.
|
|
216
|
+
const preference = backendPreference();
|
|
163
217
|
const role = roles().roles[task.role];
|
|
164
218
|
// Explicit task choices were authorized at dispatch. Only defaults and one-shot
|
|
165
219
|
// selections are resolved at worker start, against Pi's live foreground context.
|
|
@@ -200,14 +254,16 @@ export default function teamExtension(pi) {
|
|
|
200
254
|
}
|
|
201
255
|
catch { /* Usage is best-effort; do not block work. */ }
|
|
202
256
|
},
|
|
203
|
-
queued: () => observe({ kind: 'queued' }),
|
|
204
|
-
if (external.supports(work)) {
|
|
257
|
+
queued: () => observe({ kind: 'queued' }), activity: activity => observe({ kind: 'activity', activity }) };
|
|
258
|
+
if (preference === 'auto' && external.supports(work)) {
|
|
205
259
|
signal.throwIfAborted();
|
|
206
260
|
// Stock's top-level loader discovers project agents from process.cwd().
|
|
207
261
|
const type = ensureWorkerType(selected, roles().name, task.role, role, process.cwd(), agentDir, projectTrusted, skillIndex);
|
|
262
|
+
// Once spawn is attempted, do not retry on the SDK, even on timeout.
|
|
208
263
|
if (type)
|
|
209
264
|
return external.run({ ...work, type, description: task.brief, prompt: workerBrief(task, deps) + earlier }, signal);
|
|
210
265
|
}
|
|
266
|
+
observe({ kind: 'sdk' });
|
|
211
267
|
return native.run(work, signal, ctx.modelRegistry, projectTrusted);
|
|
212
268
|
}, (reason, jobs) => {
|
|
213
269
|
reportStatus();
|
|
@@ -373,11 +429,11 @@ export default function teamExtension(pi) {
|
|
|
373
429
|
async function showStatus(ctx) {
|
|
374
430
|
const summary = () => {
|
|
375
431
|
const profile = `${roles().name} (${selected})`;
|
|
376
|
-
return `Team: ${enabled ? profile : `off; selected profile: ${profile}`}${error ? ' · blocked; see /team doctor' : ''}
|
|
432
|
+
return [`Team: ${enabled ? profile : `off; selected profile: ${profile}`}${error ? ' · blocked; see /team doctor' : ''}`, concurrencyText(), backendText()];
|
|
377
433
|
};
|
|
378
434
|
const tasks = () => scheduler?.list().map(j => `${j.task.id}: ${j.state}`) ?? [];
|
|
379
435
|
if (!interactive(ctx)) {
|
|
380
|
-
ctx.ui.notify([summary(), ...tasks()].join('\n'), 'info');
|
|
436
|
+
ctx.ui.notify([summary().join(' · '), ...tasks()].join('\n'), 'info');
|
|
381
437
|
return;
|
|
382
438
|
}
|
|
383
439
|
await ctx.ui.custom((tui, theme, _keys, close) => {
|
|
@@ -392,6 +448,40 @@ export default function teamExtension(pi) {
|
|
|
392
448
|
refreshStatusView = undefined; });
|
|
393
449
|
});
|
|
394
450
|
}
|
|
451
|
+
async function configureConcurrency(ctx, value) {
|
|
452
|
+
if (value === undefined) {
|
|
453
|
+
if (!interactive(ctx)) {
|
|
454
|
+
ctx.ui.notify(concurrencyText(), 'info');
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
value = await ctx.ui.input(`Team concurrency (1–${MAX_CONCURRENCY}, or default to use config) · ${concurrencyText()}`, String(concurrency()));
|
|
458
|
+
if (value === undefined)
|
|
459
|
+
return;
|
|
460
|
+
value = value.trim();
|
|
461
|
+
}
|
|
462
|
+
if (value !== 'default' && !/^[0-9]+$/.test(value))
|
|
463
|
+
throw Error(concurrencyUsage);
|
|
464
|
+
const ceiling = value === 'default' ? null : checkedConcurrency(Number(value));
|
|
465
|
+
pi.appendEntry(concurrencyEntry, { sessionId: ctx.sessionManager.getSessionId(), concurrency: ceiling });
|
|
466
|
+
concurrencyOverride = ceiling ?? undefined;
|
|
467
|
+
scheduler?.setConcurrency(concurrency());
|
|
468
|
+
ctx.ui.notify(concurrencyText(), 'info');
|
|
469
|
+
}
|
|
470
|
+
async function pickBackend(ctx) {
|
|
471
|
+
const auto = 'Auto — prefer ready, compatible stock; otherwise SDK';
|
|
472
|
+
const sdk = 'SDK — use the Pi SDK for all new Team jobs';
|
|
473
|
+
const configured = 'Use config — clear the session override';
|
|
474
|
+
const choice = await ctx.ui.select(`${backendText()} · New launches only`, [auto, sdk, configured]);
|
|
475
|
+
if (choice !== auto && choice !== sdk && choice !== configured)
|
|
476
|
+
return;
|
|
477
|
+
const previous = backendPreference();
|
|
478
|
+
const backend = choice === auto ? 'auto' : choice === sdk ? 'sdk' : null;
|
|
479
|
+
pi.appendEntry(backendEntry, { sessionId: ctx.sessionManager.getSessionId(), backend });
|
|
480
|
+
backendOverride = backend ?? undefined;
|
|
481
|
+
if (previous === 'sdk' && backendPreference() === 'auto')
|
|
482
|
+
await external.probe();
|
|
483
|
+
ctx.ui.notify(backendText(), 'info');
|
|
484
|
+
}
|
|
395
485
|
async function mainMenu(ctx) {
|
|
396
486
|
if (!interactive(ctx)) {
|
|
397
487
|
ctx.ui.notify(teamHelp, 'info');
|
|
@@ -399,7 +489,7 @@ export default function teamExtension(pi) {
|
|
|
399
489
|
}
|
|
400
490
|
const toggle = enabled ? 'Turn Team Mode off' : 'Turn Team Mode on';
|
|
401
491
|
const choice = await ctx.ui.select(`Team Mode (${enabled ? 'on' : 'off'} · ${selected})`, [
|
|
402
|
-
'Switch profile', 'Create profile from template', toggle, 'Status', 'Configure role model', 'Help',
|
|
492
|
+
'Switch profile', 'Create profile from template', toggle, 'Status', 'Configure role model', 'Concurrency', 'Backend', 'Help',
|
|
403
493
|
]);
|
|
404
494
|
switch (choice) {
|
|
405
495
|
case 'Switch profile': return pickProfile(ctx);
|
|
@@ -408,12 +498,16 @@ export default function teamExtension(pi) {
|
|
|
408
498
|
case 'Turn Team Mode on': return activate(ctx);
|
|
409
499
|
case 'Status': return showStatus(ctx);
|
|
410
500
|
case 'Configure role model': return configureModel(ctx);
|
|
501
|
+
case 'Concurrency': return configureConcurrency(ctx);
|
|
502
|
+
case 'Backend': return pickBackend(ctx);
|
|
411
503
|
case 'Help': ctx.ui.notify(teamHelp, 'info');
|
|
412
504
|
}
|
|
413
505
|
}
|
|
414
506
|
let updateCheck;
|
|
415
507
|
pi.on('session_start', async (event, ctx) => {
|
|
416
508
|
foreground = ctx;
|
|
509
|
+
backendOverride = lastBackend(ctx);
|
|
510
|
+
concurrencyOverride = lastConcurrency(ctx);
|
|
417
511
|
if (!ctx.hasUI || ctx.mode !== 'tui')
|
|
418
512
|
return;
|
|
419
513
|
if (event.reason === 'startup' && !updateCheck) {
|
|
@@ -446,11 +540,13 @@ export default function teamExtension(pi) {
|
|
|
446
540
|
restoreProfile(ctx);
|
|
447
541
|
if (config.enabled)
|
|
448
542
|
await activate(ctx);
|
|
449
|
-
|
|
543
|
+
if (backendPreference() === 'auto')
|
|
544
|
+
void external.probe();
|
|
450
545
|
});
|
|
451
546
|
pi.on('model_select', (_event, ctx) => { foreground = ctx; });
|
|
452
547
|
pi.on('session_shutdown', async () => {
|
|
453
548
|
updateCheck?.abort();
|
|
549
|
+
clearAgents();
|
|
454
550
|
enabled = false;
|
|
455
551
|
scheduler?.dispose();
|
|
456
552
|
external.dispose();
|
|
@@ -458,6 +554,15 @@ export default function teamExtension(pi) {
|
|
|
458
554
|
await native?.dispose();
|
|
459
555
|
});
|
|
460
556
|
pi.on('session_before_tree', () => { publicationGeneration++; scheduler?.cancel(); pending = undefined; queued = false; });
|
|
557
|
+
pi.on('session_tree', (_event, ctx) => {
|
|
558
|
+
const previous = backendPreference();
|
|
559
|
+
backendOverride = lastBackend(ctx);
|
|
560
|
+
concurrencyOverride = lastConcurrency(ctx);
|
|
561
|
+
scheduler?.setConcurrency(concurrency());
|
|
562
|
+
if (previous === 'sdk' && backendPreference() === 'auto')
|
|
563
|
+
void external.probe();
|
|
564
|
+
refreshStatusView?.();
|
|
565
|
+
});
|
|
461
566
|
pi.on('before_agent_start', event => {
|
|
462
567
|
if (!enabled)
|
|
463
568
|
return;
|
|
@@ -577,9 +682,14 @@ export default function teamExtension(pi) {
|
|
|
577
682
|
}
|
|
578
683
|
else if (command === 'status')
|
|
579
684
|
await showStatus(ctx);
|
|
685
|
+
else if (command === 'concurrency') {
|
|
686
|
+
if (rest.length)
|
|
687
|
+
throw Error(concurrencyUsage);
|
|
688
|
+
await configureConcurrency(ctx, arg);
|
|
689
|
+
}
|
|
580
690
|
else if (command === 'doctor') {
|
|
581
|
-
const available = await external.probe();
|
|
582
|
-
ctx.ui.notify(`${error ?? 'Configuration OK'}\
|
|
691
|
+
const available = backendPreference() === 'auto' && await external.probe();
|
|
692
|
+
ctx.ui.notify(`${error ?? 'Configuration OK'}\n${backendText()} · ${available ? 'pi-subagents RPC v2 ready; SDK for ineligible jobs' : 'built-in Pi SDK'}`, error ? 'error' : 'info');
|
|
583
693
|
}
|
|
584
694
|
else if (command === 'model')
|
|
585
695
|
await configureModel(ctx, arg, rest.length ? rest.join(' ') : undefined);
|
|
@@ -626,6 +736,8 @@ export default function teamExtension(pi) {
|
|
|
626
736
|
native = new NativeBackend(ctx.cwd, agentDir);
|
|
627
737
|
config = next;
|
|
628
738
|
error = undefined;
|
|
739
|
+
if (backendPreference() === 'auto')
|
|
740
|
+
void external.probe();
|
|
629
741
|
restoreProfile(ctx);
|
|
630
742
|
if (enabled)
|
|
631
743
|
await activate(ctx);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Not a source of runnable IDs. Only detached copies leave this module.
|
|
2
2
|
const worker = (name, workScope, personality) => ({ name, workScope, personality, peers: ['lead'], enable: true, access: null, modelPool: [] });
|
|
3
3
|
const profile = (name, leadScope, roles) => ({
|
|
4
|
-
name, roles: { lead: { ...worker('Team Lead', leadScope
|
|
4
|
+
name, roles: { lead: { ...worker('Team Lead', `${leadScope} Own the outcome: recover and replan on failures or conflicts; involve the user only at critical checkpoints or blockers you can’t resolve.`, 'decisive'), peers: Object.keys(roles) }, ...roles },
|
|
5
5
|
});
|
|
6
6
|
function catalog() {
|
|
7
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.', {
|
package/dist/role-colors.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { parseColor } from '@earendil-works/pi-tui';
|
|
1
2
|
// Stock pi-subagents 0.26.3 named colors used by our native Team definitions.
|
|
2
3
|
const colors = new Map([
|
|
3
4
|
['arch', { name: 'blue', hex: '#6A9BCC' }],
|
|
@@ -9,3 +10,10 @@ const colors = new Map([
|
|
|
9
10
|
['researcher', { name: 'teal', hex: '#008080' }],
|
|
10
11
|
]);
|
|
11
12
|
export const roleColor = (role) => colors.get(role);
|
|
13
|
+
export function roleBadge(role, label, theme) {
|
|
14
|
+
const color = roleColor(role);
|
|
15
|
+
// Match stock's high-contrast foreground for these fixed palette colors.
|
|
16
|
+
const lightText = role === 'validator' || (role === 'researcher' && theme.getColorMode() === 'truecolor');
|
|
17
|
+
return color ? theme.style(label, { bg: parseColor(color.hex), fg: parseColor(lightText ? '#FFFFFF' : '#000000'), bold: true })
|
|
18
|
+
: theme.style(label, { bg: 'selectedBg', fg: 'text', bold: true });
|
|
19
|
+
}
|
package/dist/scheduler.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { checkedConcurrency } from './config.js';
|
|
1
2
|
const terminal = (state) => state !== 'running' && state !== 'queued';
|
|
3
|
+
const recentSdkLimit = 5;
|
|
2
4
|
const liveState = (job) => job.state === 'queued' ? 'queued' :
|
|
3
5
|
job.startedModel ? 'running' : job.backendQueued ? 'queued' : 'starting';
|
|
4
6
|
const briefLimit = 12_000;
|
|
@@ -11,6 +13,7 @@ export class Scheduler {
|
|
|
11
13
|
onChange;
|
|
12
14
|
jobs = new Map();
|
|
13
15
|
controllers = new Map();
|
|
16
|
+
recentSdk = [];
|
|
14
17
|
stopped = false;
|
|
15
18
|
revision = 0;
|
|
16
19
|
notifiedIdle = true;
|
|
@@ -19,6 +22,19 @@ export class Scheduler {
|
|
|
19
22
|
this.execute = execute;
|
|
20
23
|
this.onChange = onChange;
|
|
21
24
|
}
|
|
25
|
+
setConcurrency(value) {
|
|
26
|
+
const next = checkedConcurrency(value);
|
|
27
|
+
if (next === this.concurrency)
|
|
28
|
+
return;
|
|
29
|
+
this.concurrency = next;
|
|
30
|
+
this.pump(); // Existing reservations and writer ownership are unchanged.
|
|
31
|
+
}
|
|
32
|
+
teamAgents() {
|
|
33
|
+
return [...this.controllers.keys()].flatMap(id => {
|
|
34
|
+
const job = this.jobs.get(id);
|
|
35
|
+
return job.usesSdk ? [{ job, status: job.state === 'cancelled' ? 'stopping' : liveState(job) }] : [];
|
|
36
|
+
}).concat(this.recentSdk.map(job => ({ job, status: job.state })));
|
|
37
|
+
}
|
|
22
38
|
get busy() { return this.list().some(j => !terminal(j.state)); }
|
|
23
39
|
get active() { return this.busy || this.controllers.size > 0; }
|
|
24
40
|
list() { return [...this.jobs.values()]; }
|
|
@@ -81,13 +97,16 @@ export class Scheduler {
|
|
|
81
97
|
if (this.busy || this.controllers.size)
|
|
82
98
|
throw Error('Wait for workers to finish stopping before resetting tasks');
|
|
83
99
|
this.jobs.clear();
|
|
100
|
+
this.recentSdk = [];
|
|
84
101
|
this.onChange('progress', []);
|
|
85
102
|
}
|
|
86
103
|
cancel() {
|
|
87
104
|
this.revision++;
|
|
88
105
|
for (const job of this.jobs.values())
|
|
89
|
-
if (!terminal(job.state))
|
|
106
|
+
if (!terminal(job.state)) {
|
|
90
107
|
job.state = 'cancelled';
|
|
108
|
+
delete job.activity;
|
|
109
|
+
}
|
|
91
110
|
for (const controller of this.controllers.values())
|
|
92
111
|
controller.abort();
|
|
93
112
|
this.notifiedIdle = true;
|
|
@@ -132,23 +151,35 @@ export class Scheduler {
|
|
|
132
151
|
return this.execute(job.task, deps, controller.signal, progress => {
|
|
133
152
|
if (job.state !== 'running' || controller.signal.aborted)
|
|
134
153
|
return;
|
|
135
|
-
if (progress.kind === '
|
|
154
|
+
if (progress.kind === 'sdk' && !job.usesSdk)
|
|
155
|
+
job.usesSdk = true;
|
|
156
|
+
else if (progress.kind === 'started' && !job.startedModel)
|
|
136
157
|
job.startedModel = progress.model;
|
|
137
158
|
else if (progress.kind === 'queued' && !job.startedModel)
|
|
138
159
|
job.backendQueued = true;
|
|
139
|
-
else if (progress.kind === '
|
|
140
|
-
|
|
160
|
+
else if (progress.kind === 'activity' && job.usesSdk && job.startedModel) {
|
|
161
|
+
if (progress.activity.label || progress.activity.toolsActive)
|
|
162
|
+
job.activity = progress.activity;
|
|
163
|
+
else
|
|
164
|
+
delete job.activity;
|
|
165
|
+
}
|
|
141
166
|
else
|
|
142
167
|
return;
|
|
143
168
|
this.onChange('progress', this.list());
|
|
144
169
|
});
|
|
145
170
|
}).catch((error) => ({ status: 'failed', summary: String(error) })).then(result => {
|
|
146
171
|
this.controllers.delete(job.task.id);
|
|
172
|
+
delete job.activity;
|
|
147
173
|
const current = revision === this.revision;
|
|
148
174
|
if (current) {
|
|
149
175
|
job.result = { ...result, summary: summaryText(result.summary) };
|
|
150
176
|
job.state = result.status;
|
|
151
177
|
}
|
|
178
|
+
if (!this.stopped && job.usesSdk) {
|
|
179
|
+
this.recentSdk.unshift(job);
|
|
180
|
+
if (this.recentSdk.length > recentSdkLimit)
|
|
181
|
+
this.recentSdk.pop();
|
|
182
|
+
}
|
|
152
183
|
this.pump(current && result.status !== 'done');
|
|
153
184
|
});
|
|
154
185
|
}
|
package/dist/status-view.js
CHANGED
|
@@ -34,11 +34,13 @@ export function statusView(summary, tasks, live, tui, theme, close, dispose) {
|
|
|
34
34
|
...(formatted.length ? formatted : [clip('No queued or running Team tasks.', width)]),
|
|
35
35
|
...(history.length ? [theme.fg('accent', clip('Task summary', width)), ...history.map(line => clip(line, width))] : []),
|
|
36
36
|
];
|
|
37
|
-
const
|
|
37
|
+
const heading = summary();
|
|
38
|
+
const size = Math.max(1, Math.min(16, tui.terminal.rows - heading.length - 3));
|
|
38
39
|
offset = Math.max(0, Math.min(offset, lines.length - size));
|
|
39
40
|
const hint = lines.length > size
|
|
40
41
|
? `${offset + 1}–${offset + size} of ${lines.length} · ↑/↓ or j/k Scroll · Esc Close` : 'Esc Close';
|
|
41
|
-
return [theme.fg('accent', clip(singleLine(
|
|
42
|
+
return [...heading.map((line, index) => theme.fg(index === 0 ? 'accent' : 'muted', clip(singleLine(line), width))),
|
|
43
|
+
...lines.slice(offset, offset + size),
|
|
42
44
|
theme.fg('muted', clip(hint, width))];
|
|
43
45
|
},
|
|
44
46
|
};
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { parseColor, visibleWidth } from '@earendil-works/pi-tui';
|
|
2
|
+
import { roleBadge } from './role-colors.js';
|
|
3
|
+
import { clip, singleLine } from './ui-text.js';
|
|
4
|
+
const pad = (text, width) => text + ' '.repeat(Math.max(0, width - visibleWidth(text)));
|
|
5
|
+
const field = (text, width) => pad(clip(text, width), width);
|
|
6
|
+
// Pi's accent token is violet by default and can be any hue on custom themes.
|
|
7
|
+
// Use an explicit magenta for the header, adjusted for the theme's background.
|
|
8
|
+
const headingColors = { light: parseColor('#A83080'), dark: parseColor('#E178BC') };
|
|
9
|
+
const workingFrames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
|
|
10
|
+
const statusStyle = {
|
|
11
|
+
queued: ['◌', 'muted'], starting: ['○', 'muted'], running: ['', 'accent'], stopping: ['Ⅱ', 'warning'],
|
|
12
|
+
done: ['✓', 'success'], blocked: ['!', 'warning'], failed: ['✗', 'error'], cancelled: ['–', 'warning'],
|
|
13
|
+
};
|
|
14
|
+
export function renderTeamAgents(rows, name, width, terminalRows, theme, frame = 0) {
|
|
15
|
+
if (!rows.length || width < 1)
|
|
16
|
+
return [];
|
|
17
|
+
const limit = Math.min(9, Math.max(2, Math.floor(terminalRows / 3)));
|
|
18
|
+
const hasActivity = ({ status }) => status === 'running' && width > 6;
|
|
19
|
+
const rowCost = (row) => hasActivity(row) ? 2 : 1;
|
|
20
|
+
// Reserve an overflow line if needed and fit parent/child pairs together.
|
|
21
|
+
const bodyBudget = rows.reduce((total, row) => total + rowCost(row), 0) > limit ? limit - 1 : limit;
|
|
22
|
+
let used = 0;
|
|
23
|
+
const shown = [];
|
|
24
|
+
for (const row of rows) {
|
|
25
|
+
const cost = rowCost(row);
|
|
26
|
+
if (used && used + cost > bodyBudget)
|
|
27
|
+
break;
|
|
28
|
+
const showActivity = hasActivity(row) && used + cost <= bodyBudget;
|
|
29
|
+
used += showActivity ? 2 : 1;
|
|
30
|
+
const { job, status } = row;
|
|
31
|
+
const { role, id, brief } = job.task;
|
|
32
|
+
const waiting = status === 'queued' || status === 'starting' || status === 'stopping';
|
|
33
|
+
shown.push({ role, status, name: singleLine(name(role)) || singleLine(role) || 'Worker',
|
|
34
|
+
model: singleLine(job.startedModel) || (waiting ? 'pending' : 'not started'),
|
|
35
|
+
task: `${singleLine(id)} · ${singleLine(brief)}`,
|
|
36
|
+
activity: showActivity ? singleLine(job.activity?.label) || 'working…' : undefined });
|
|
37
|
+
}
|
|
38
|
+
const statusWidth = 1; // All status glyphs and spinner frames occupy one cell.
|
|
39
|
+
const room = width - 3 - statusWidth - 3; // Tree prefix and the three inter-column gaps.
|
|
40
|
+
const roleWidth = Math.min(24, Math.max(...shown.map(row => visibleWidth(row.name) + 2)), Math.floor(room / 3));
|
|
41
|
+
const modelWidth = Math.min(42, Math.max(...shown.map(row => visibleWidth(row.model))), Math.floor((room - roleWidth) * 2 / 3));
|
|
42
|
+
const taskWidth = room - roleWidth - modelWidth;
|
|
43
|
+
const omitted = rows.length - shown.length;
|
|
44
|
+
// These prefixes use single-cell glyphs. Truncate literally so even a one-cell
|
|
45
|
+
// viewport keeps the connector instead of replacing it with an ellipsis.
|
|
46
|
+
const guide = (prefix) => theme.fg('dim', prefix.slice(0, width));
|
|
47
|
+
const lines = shown.flatMap(({ role, status, name, model, task, activity }, i) => {
|
|
48
|
+
// The overflow notice is itself the final sibling when present.
|
|
49
|
+
const hasNextSibling = i + 1 < shown.length || omitted > 0;
|
|
50
|
+
const branch = guide(hasNextSibling ? '├─ ' : '└─ ');
|
|
51
|
+
const [glyph, color] = statusStyle[status];
|
|
52
|
+
const indicator = status === 'running' ? workingFrames[frame % workingFrames.length] : glyph;
|
|
53
|
+
const statusCell = width > 3 ? theme.fg(color, field(indicator, statusWidth)) : '';
|
|
54
|
+
let line;
|
|
55
|
+
if (roleWidth < 3 || modelWidth < 1 || taskWidth < 1) {
|
|
56
|
+
line = branch + statusCell + clip(` ${name} ${model} ${task}`, Math.max(0, width - 3 - statusWidth));
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
const label = ` ${clip(name, roleWidth - 2)} `;
|
|
60
|
+
// Fit lifecycle text after the preview without shifting the shared columns.
|
|
61
|
+
const suffix = status === 'running' || status === 'done' ? '' : ` · ${status}`;
|
|
62
|
+
const suffixWidth = visibleWidth(suffix);
|
|
63
|
+
const preview = suffix && taskWidth > suffixWidth
|
|
64
|
+
? clip(task, taskWidth - suffixWidth) + theme.fg(color, suffix)
|
|
65
|
+
: clip(task, taskWidth);
|
|
66
|
+
line = `${branch}${statusCell} ${roleBadge(role, label, theme)}${pad('', roleWidth - visibleWidth(label))} ` +
|
|
67
|
+
`${theme.fg('muted', field(model, modelWidth))} ${preview}`;
|
|
68
|
+
}
|
|
69
|
+
if (!activity)
|
|
70
|
+
return [line];
|
|
71
|
+
const child = guide(hasNextSibling ? '│ ⎿ ' : ' ⎿ ');
|
|
72
|
+
// Only the detail label gets the muted foreground, not the whole branch.
|
|
73
|
+
return [line, child + theme.fg('muted', clip(activity, width - 6))];
|
|
74
|
+
});
|
|
75
|
+
if (omitted)
|
|
76
|
+
lines.push(guide('└─ ') +
|
|
77
|
+
theme.fg('muted', clip(`+${omitted} more · /team status`, Math.max(0, width - 3))));
|
|
78
|
+
return [theme.style(clip('● Team Agents', width), { fg: headingColors[theme.appearance] }), ...lines];
|
|
79
|
+
}
|
|
80
|
+
export function teamAgentsWidget(tui, theme, name, initialRows) {
|
|
81
|
+
let rows = initialRows;
|
|
82
|
+
let frame = 0;
|
|
83
|
+
let timer;
|
|
84
|
+
let disposed = false;
|
|
85
|
+
function stopAnimation() {
|
|
86
|
+
clearInterval(timer);
|
|
87
|
+
timer = undefined;
|
|
88
|
+
frame = 0;
|
|
89
|
+
}
|
|
90
|
+
function syncAnimation() {
|
|
91
|
+
if (!rows.some(row => row.status === 'running'))
|
|
92
|
+
stopAnimation();
|
|
93
|
+
else if (!timer) {
|
|
94
|
+
// Scheduler events alone determine when the animation runs. A tick only redraws.
|
|
95
|
+
timer = setInterval(() => {
|
|
96
|
+
frame = (frame + 1) % workingFrames.length;
|
|
97
|
+
tui.requestRender();
|
|
98
|
+
}, 120);
|
|
99
|
+
timer.unref();
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
syncAnimation();
|
|
103
|
+
return {
|
|
104
|
+
invalidate() { },
|
|
105
|
+
render: (width) => renderTeamAgents(rows, name, width, tui.terminal.rows, theme, frame),
|
|
106
|
+
update(next) {
|
|
107
|
+
if (disposed)
|
|
108
|
+
return;
|
|
109
|
+
rows = next;
|
|
110
|
+
syncAnimation();
|
|
111
|
+
tui.requestRender();
|
|
112
|
+
},
|
|
113
|
+
dispose() {
|
|
114
|
+
disposed = true;
|
|
115
|
+
stopAnimation();
|
|
116
|
+
rows = [];
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { clip, singleLine } from './ui-text.js';
|
|
2
|
+
const toolActions = new Map([
|
|
3
|
+
['read', 'reading'], ['bash', 'running command'], ['edit', 'editing'], ['write', 'writing'],
|
|
4
|
+
['grep', 'searching'], ['find', 'finding files'], ['ls', 'listing'],
|
|
5
|
+
]);
|
|
6
|
+
// One tracker per prompt, including when a retained session is resumed. Never keep
|
|
7
|
+
// streamed content, tool arguments, or tool results; the widget needs phases only.
|
|
8
|
+
export function trackWorkerActivity(report) {
|
|
9
|
+
const tools = new Map();
|
|
10
|
+
const blocks = new Map();
|
|
11
|
+
let previous = { toolsActive: false };
|
|
12
|
+
function publish() {
|
|
13
|
+
let label = tools.values().next().value;
|
|
14
|
+
const toolsActive = tools.size > 0;
|
|
15
|
+
if (!toolsActive)
|
|
16
|
+
for (const phase of blocks.values())
|
|
17
|
+
label = phase;
|
|
18
|
+
if (previous.label === label && previous.toolsActive === toolsActive)
|
|
19
|
+
return;
|
|
20
|
+
report(previous = { label, toolsActive });
|
|
21
|
+
}
|
|
22
|
+
function reset() {
|
|
23
|
+
tools.clear();
|
|
24
|
+
blocks.clear();
|
|
25
|
+
publish();
|
|
26
|
+
}
|
|
27
|
+
return {
|
|
28
|
+
reset,
|
|
29
|
+
accept(event) {
|
|
30
|
+
switch (event.type) {
|
|
31
|
+
case 'agent_end':
|
|
32
|
+
case 'turn_end':
|
|
33
|
+
reset();
|
|
34
|
+
return;
|
|
35
|
+
case 'message_start':
|
|
36
|
+
case 'message_end':
|
|
37
|
+
if (event.message.role === 'assistant')
|
|
38
|
+
blocks.clear();
|
|
39
|
+
break;
|
|
40
|
+
case 'message_update': {
|
|
41
|
+
if (event.message.role !== 'assistant')
|
|
42
|
+
return;
|
|
43
|
+
const stream = event.assistantMessageEvent;
|
|
44
|
+
switch (stream.type) {
|
|
45
|
+
case 'thinking_start':
|
|
46
|
+
case 'thinking_delta':
|
|
47
|
+
blocks.set(stream.contentIndex, 'thinking…');
|
|
48
|
+
break;
|
|
49
|
+
case 'text_start':
|
|
50
|
+
case 'text_delta':
|
|
51
|
+
blocks.set(stream.contentIndex, 'responding…');
|
|
52
|
+
break;
|
|
53
|
+
case 'thinking_end':
|
|
54
|
+
case 'text_end':
|
|
55
|
+
blocks.delete(stream.contentIndex);
|
|
56
|
+
break;
|
|
57
|
+
case 'done':
|
|
58
|
+
case 'error':
|
|
59
|
+
blocks.clear();
|
|
60
|
+
break;
|
|
61
|
+
default: return; // Streaming a tool call is not executing it.
|
|
62
|
+
}
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
case 'tool_execution_start': {
|
|
66
|
+
const name = clip(singleLine(event.toolName), 32);
|
|
67
|
+
tools.set(event.toolCallId, `${toolActions.get(name) ?? (name ? `using ${name}` : 'using tool')}…`);
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
case 'tool_execution_end':
|
|
71
|
+
tools.delete(event.toolCallId);
|
|
72
|
+
break;
|
|
73
|
+
default: return;
|
|
74
|
+
}
|
|
75
|
+
publish();
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
}
|