teamsmith 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/package.json +1 -1
- package/skills/teamsmith/CHANGELOG.md +28 -0
- package/skills/teamsmith/SKILL.md +14 -7
- package/skills/teamsmith/extension/team-notify.ts +37 -6
- package/skills/teamsmith/extension/team.ts +438 -0
- package/skills/teamsmith/references/config.md +39 -6
- package/skills/teamsmith/references/migration.md +197 -47
- package/skills/teamsmith/references/protocol.md +176 -19
- package/skills/teamsmith/references/troubleshooting.md +124 -7
- package/skills/teamsmith/references/workflows.md +36 -2
- package/skills/teamsmith/scripts/lib/cmd-agents.sh +318 -23
- package/skills/teamsmith/scripts/lib/cmd-bootstrap.sh +2 -2
- package/skills/teamsmith/scripts/lib/cmd-config.sh +349 -67
- package/skills/teamsmith/scripts/lib/cmd-draft.sh +4 -4
- package/skills/teamsmith/scripts/lib/cmd-help.sh +677 -0
- package/skills/teamsmith/scripts/lib/cmd-init.sh +157 -5
- package/skills/teamsmith/scripts/lib/cmd-interrupt.sh +461 -0
- package/skills/teamsmith/scripts/lib/cmd-meeting.sh +2 -25
- package/skills/teamsmith/scripts/lib/cmd-project.sh +30 -103
- package/skills/teamsmith/scripts/lib/cmd-reap.sh +277 -0
- package/skills/teamsmith/scripts/lib/cmd-reply.sh +3 -3
- package/skills/teamsmith/scripts/lib/cmd-review.sh +175 -30
- package/skills/teamsmith/scripts/lib/cmd-status.sh +226 -17
- package/skills/teamsmith/scripts/lib/cmd-update.sh +36 -7
- package/skills/teamsmith/scripts/lib/cmd-watch.sh +564 -46
- package/skills/teamsmith/scripts/lib/common.sh +773 -48
- package/skills/teamsmith/scripts/lib/gate-lock.sh +544 -0
- package/skills/teamsmith/scripts/panel/draft-send.sh +11 -1
- package/skills/teamsmith/scripts/panel/panel.js +207 -207
- package/skills/teamsmith/scripts/panel/src/App.tsx +58 -21
- package/skills/teamsmith/scripts/panel/src/clipboard.ts +11 -5
- package/skills/teamsmith/scripts/panel/src/compose.ts +6 -3
- package/skills/teamsmith/scripts/panel/src/data.ts +11 -3
- package/skills/teamsmith/scripts/panel/src/layout.ts +209 -69
- package/skills/teamsmith/scripts/panel/src/main.tsx +33 -8
- package/skills/teamsmith/scripts/panel/src/strings/en.ts +39 -29
- package/skills/teamsmith/scripts/panel/src/strings/zh.ts +41 -31
- package/skills/teamsmith/scripts/panel/src/types.ts +28 -3
- package/skills/teamsmith/scripts/replies.mjs +4 -1
- package/skills/teamsmith/scripts/shim/tmux +18 -0
- package/skills/teamsmith/scripts/strings/commands.tsv +86 -0
- package/skills/teamsmith/scripts/strings/help.en.tsv +503 -0
- package/skills/teamsmith/scripts/strings/help.zh.tsv +489 -0
- package/skills/teamsmith/scripts/team +19 -6
- package/skills/teamsmith/templates/AGENTS.section.md.tmpl +8 -1
- package/skills/teamsmith/templates/config.sh.tmpl +20 -1
- package/skills/teamsmith/templates/pm-prompt.md.tmpl +21 -0
- package/skills/teamsmith/tests/bg-ledger-harness.mjs +464 -40
- package/skills/teamsmith/tests/bg-ledger.sh +168 -10
- package/skills/teamsmith/tests/checkout-shape-probe.sh +3 -1
- package/skills/teamsmith/tests/config-cli.sh +160 -14
- package/skills/teamsmith/tests/fixtures/delivery-truth-real/scenario.sh +7 -1
- package/skills/teamsmith/tests/fixtures/p287/lint-good.sh.in +3 -0
- package/skills/teamsmith/tests/fixtures/p287/lint-hardcoded.sh.in +3 -0
- package/skills/teamsmith/tests/fixtures/p287/lint-no-ns.sh.in +3 -0
- package/skills/teamsmith/tests/fixtures/p55/flip-p49.sh +18 -6
- package/skills/teamsmith/tests/flip-m33.sh +5 -3
- package/skills/teamsmith/tests/flip-m37.sh +4 -1
- package/skills/teamsmith/tests/flip-m4.3.sh +4 -1
- package/skills/teamsmith/tests/flip-m6.3.sh +4 -1
- package/skills/teamsmith/tests/flip-m6.5.sh +4 -1
- package/skills/teamsmith/tests/flip-m7.2.sh +4 -1
- package/skills/teamsmith/tests/flip-p158.sh +2 -1
- package/skills/teamsmith/tests/flip-p210.sh +4 -1
- package/skills/teamsmith/tests/flip-p217.sh +4 -1
- package/skills/teamsmith/tests/flip-p287-lock.sh +342 -0
- package/skills/teamsmith/tests/flip-p287-name.sh +279 -0
- package/skills/teamsmith/tests/flip-p304-read-side.sh +98 -0
- package/skills/teamsmith/tests/flip-p308-skip-not-pass.sh +151 -0
- package/skills/teamsmith/tests/flip-p309-p162-deep.sh +122 -0
- package/skills/teamsmith/tests/flip-p310-lock.sh +216 -0
- package/skills/teamsmith/tests/flip-p310-socket.sh +125 -0
- package/skills/teamsmith/tests/help-surface.sh +1664 -0
- package/skills/teamsmith/tests/install-shape.sh +279 -20
- package/skills/teamsmith/tests/key-replies-pty.sh +9 -10
- package/skills/teamsmith/tests/key-replies-ui.sh +0 -7
- package/skills/teamsmith/tests/key-replies.sh +240 -1
- package/skills/teamsmith/tests/ledger-ban.sh +5 -4
- package/skills/teamsmith/tests/ledger-claim.sh +2 -1
- package/skills/teamsmith/tests/lib/bounded-spin.sh +90 -0
- package/skills/teamsmith/tests/lib/model-policy.sh +4 -0
- package/skills/teamsmith/tests/lib/model-routing-flips.py +51 -0
- package/skills/teamsmith/tests/lib/reply-fixture.sh +4 -9
- package/skills/teamsmith/tests/lib/section-guard.sh +258 -13
- package/skills/teamsmith/tests/lib/tmp-root.sh +139 -27
- package/skills/teamsmith/tests/lib/tmux-cap.sh +10 -1
- package/skills/teamsmith/tests/lib/tmux-iso.sh +31 -13
- package/skills/teamsmith/tests/loop-inventory.tsv +59 -47
- package/skills/teamsmith/tests/panel-b2.sh +106 -3
- package/skills/teamsmith/tests/panel-b3-stub.sh +112 -4
- package/skills/teamsmith/tests/panel-b3.sh +175 -19
- package/skills/teamsmith/tests/panel-choices.sh +11 -6
- package/skills/teamsmith/tests/panel-cpu.sh +2 -1
- package/skills/teamsmith/tests/panel-knobs.sh +7 -1
- package/skills/teamsmith/tests/panel-p21.sh +156 -73
- package/skills/teamsmith/tests/panel-snapshots.sh +41 -225
- package/skills/teamsmith/tests/panel-strings.mjs +33 -18
- package/skills/teamsmith/tests/perf.sh +121 -30
- package/skills/teamsmith/tests/routes.sh +327 -93
- package/skills/teamsmith/tests/seat-interrupt.sh +1002 -0
- package/skills/teamsmith/tests/seat-visibility.sh +675 -0
- package/skills/teamsmith/tests/section-budgets.tsv +20 -10
- package/skills/teamsmith/tests/section-guard.sh +6 -1
- package/skills/teamsmith/tests/section-needs-audit.sh +24 -7
- package/skills/teamsmith/tests/section-paths.tsv +19 -13
- package/skills/teamsmith/tests/section-select.sh +8 -1
- package/skills/teamsmith/tests/slash-team-e2e.sh +323 -0
- package/skills/teamsmith/tests/slash-team.sh +617 -0
- package/skills/teamsmith/tests/smoke.sh +2972 -440
- package/skills/teamsmith/tests/task-model-routing.sh +507 -10
- package/skills/teamsmith/tests/tmp-hygiene.sh +782 -45
- package/skills/teamsmith/tests/tmux-identity-leak.sh +773 -0
- package/skills/teamsmith/tests/tmux-lint-legacy.txt +12 -18
- package/skills/teamsmith/tests/upgrade-recipe.sh +537 -0
- package/skills/teamsmith-init/SKILL.md +12 -12
- package/skills/teamsmith-init/references/bootstrap.md +3 -3
package/README.md
CHANGED
|
@@ -56,14 +56,14 @@ than replaced (`--force` replaces only an entry recognised as this skill).
|
|
|
56
56
|
### As a Pi package (no global CLI)
|
|
57
57
|
|
|
58
58
|
```bash
|
|
59
|
-
pi install git:git@github.com:Track07-cda/teamsmith@v0.
|
|
60
|
-
pi install -l git:git@github.com:Track07-cda/teamsmith@v0.
|
|
59
|
+
pi install git:git@github.com:Track07-cda/teamsmith@v0.3.0 # user level: every project
|
|
60
|
+
pi install -l git:git@github.com:Track07-cda/teamsmith@v0.3.0 # project level: recorded in .pi/settings.json
|
|
61
61
|
```
|
|
62
62
|
|
|
63
63
|
- **Pin a released tag**: `@v<version>`, the version `team version` prints. Latest tag:
|
|
64
64
|
`git tag --sort=-v:refname | head -1`.
|
|
65
|
-
- The `git@github.com:` form (or `ssh://git@github.com/Track07-cda/teamsmith@v0.
|
|
66
|
-
whether or not you have a token; the shorthand `git:github.com/Track07-cda/teamsmith@v0.
|
|
65
|
+
- The `git@github.com:` form (or `ssh://git@github.com/Track07-cda/teamsmith@v0.3.0`) uses your SSH key and works
|
|
66
|
+
whether or not you have a token; the shorthand `git:github.com/Track07-cda/teamsmith@v0.3.0` takes the HTTPS
|
|
67
67
|
route, so it works anonymously on the public repository and asks for credentials if your access is private.
|
|
68
68
|
- The clone lands in `~/.pi/agent/git/<host>/<path>` (user level) or `.pi/git/<host>/<path>` (project level); the
|
|
69
69
|
skill directory — the `<skill>` used in every command below — is `<clone>/skills/teamsmith`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "teamsmith",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Turn one agent session into a project owner: self-contained task briefs dispatched to worker agents in their own git worktrees, independent verification on a separate checkout, and an auditable ledger (BOARD / reviews / threads / DECISIONS). Runs on Pi today.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"bin": {
|
|
@@ -5,6 +5,34 @@
|
|
|
5
5
|
> `SKILL.md`/`references/**`/`templates/**`/`extension/**` 在 Pi 里输入 `/reload`(或 `/pi-team-reload`)即生效;
|
|
6
6
|
> 判断自己是不是旧的:`team mark-loaded`(开局记一次)→ `team version --check`。
|
|
7
7
|
|
|
8
|
+
## v0.3.0(2026-10-18)
|
|
9
|
+
|
|
10
|
+
### ⚠️ 默认变化:临时根落到磁盘(tmp-root-on-disk)
|
|
11
|
+
|
|
12
|
+
夹具、门禁、评审与清扫用的临时根,默认从 `/tmp` 搬到**磁盘**上的 `/var/tmp/teamsmith-<项目 ns>`
|
|
13
|
+
(`/var/tmp` 不可写时退回 `/tmp`)。理由:本机 `/tmp` 是 tmpfs —— 夹具写盘吃的是 RAM,与 OOM killer
|
|
14
|
+
读同一个池(现场读数见 `openspec/changes/tmp-root-on-disk/design.md`)。
|
|
15
|
+
|
|
16
|
+
- **一个解析函数**:`team_tmp_root`(`TMPDIR` → `TEAM_TMP_ROOT` → 平台默认)是唯一实现;清扫器、门禁、
|
|
17
|
+
派单地板、doctor、面板与夹具都调它。谁怎么解析的会被打印出来:`team status`、派单的余量行、
|
|
18
|
+
`tmp-hygiene --status` 都在根旁边写 `source=tmpdir|config|default`;环境里的 `TMPDIR` 盖过项目钉的
|
|
19
|
+
`TEAM_TMP_ROOT` 时,输出**点名**这件事。
|
|
20
|
+
- **升级须知**(老项目不用做任何事,但有三件事会变):
|
|
21
|
+
1. 第一次写盘时创建 `/var/tmp/teamsmith-<ns>`(0700);显式指定的根(`TMPDIR` / `TEAM_TMP_ROOT`)**不会**
|
|
22
|
+
被代建 —— 不可用就具名失败(点名路径 + 修法)并拒绝派单,绝不静默换一个根。
|
|
23
|
+
2. 旧默认根 `/tmp` 里的残留不会自己搬家:`tmp-hygiene --status` 会报旧根下的家族目录数量,并给出
|
|
24
|
+
`TMPDIR=/tmp … --sweep` 这一条(同一条清扫命令,把旧基准显式选出来);清扫器一次只作用于一个基准
|
|
25
|
+
(混着判会把新根里的东西判成「别家」)。
|
|
26
|
+
3. `tmp-hygiene --lint` 多一条规则:任何自己算临时根的地方(`${TMPDIR:-/tmp}`、`${TMPDIR}`、面板源码里的
|
|
27
|
+
`process.env.TMPDIR` / 无参 `tmpdir()`)都是 finding。豁免只有两处:解析函数自己、以及**冻结的**门禁锁
|
|
28
|
+
发布路径 `/tmp/teamsmith-smoke.lock`(P287:搬它会在升级窗口里新开一条静默并发窗口)。
|
|
29
|
+
- **回滚**:在项目配置 `.pi/team/config.sh` 里写 `TEAM_TMP_ROOT="/tmp"`(旧行为;`team config set` 按
|
|
30
|
+
`refuse` 类拒绝改它 —— 搬家是操作者动作)。门禁锁的位置不受这个键影响,它仍是 `/tmp/teamsmith-smoke.lock`。
|
|
31
|
+
- **锁不搬**:项目锁与门禁锁的位置仍按环境里的 `TMPDIR`(未设则 `/tmp`),**不**跟着临时根走 ——
|
|
32
|
+
锁是跨版本串行用的共享状态,跟着搬会在升级窗口里让新旧两版各取各的锁(与 P287 冻结门禁锁发布路径同一条纪律)。
|
|
33
|
+
- **地板**:派单的字节/inode 余量判的是**选定的**那个根(不再硬编码 `/tmp`),拒绝文案点名它;
|
|
34
|
+
doctor 多一行「锁文件系统」只警告行 —— 锁所在的文件系统可能没被别的行覆盖,但它不拒绝派单。
|
|
35
|
+
|
|
8
36
|
## v0.2.0 · 2026-10-14
|
|
9
37
|
|
|
10
38
|
功能版:**按任务类别分配模型**(含破坏式配置迁移)、**Pulse 关键回复页**,以及长作业车道的提示词侧。
|
|
@@ -3,7 +3,7 @@ name: teamsmith
|
|
|
3
3
|
description: teamsmith gives one agent real ownership of a project — it plans, writes self-contained task briefs, dispatches worker agents into their own tmux windows and git worktrees, verifies their work on an independent checkout, merges, and keeps an auditable ledger (BOARD/reviews/threads/DECISIONS). A pulse window (the periodic patrol) wakes the owner only when there is pending work, and the owner can deliberately stand down. Works with Pi; the launch/notify seam is an internal seam (frozen) reserved for a possible future non-Pi adapter, with no compatibility promise. Use when the user wants an agent to own a project end to end, dispatch tasks to worker agents, run agents in parallel in tmux with git worktree isolation, act as a PM/orchestrator over other agents, review an agent's work independently, run the patrol (`pulse`) as a tmux window, wake the PM only when there is pending work, or resume and coordinate a multi-agent project. To start a new project, use the teamsmith-init skill.
|
|
4
4
|
license: MIT
|
|
5
5
|
metadata:
|
|
6
|
-
version: "0.
|
|
6
|
+
version: "0.3.0"
|
|
7
7
|
---
|
|
8
8
|
|
|
9
9
|
# teamsmith · one agent that actually owns the project
|
|
@@ -51,7 +51,7 @@ everything below is the daily loop, which starts once the project is up.
|
|
|
51
51
|
| Init / self-check | `team init [--session s] [--agents "a b"] [--vcs local\|remote] --task-models '<category=provider/model …>' --pm-model '<provider/model>' [--copy\|--no-skills]` (fresh projects must pass both model inputs; installs both skills into the project's `.pi/skills/`), `team doctor` (reports that install, warns on drift) |
|
|
52
52
|
| Observe | `team roster` (windows/branch/dirty/ahead), `team status [ID]`, `team ps` (capacity + model limits + PM/pulse liveness), `team digest` (PM's pending work) |
|
|
53
53
|
| Inbox | `team inbox [agent] [--ack] [--all]` |
|
|
54
|
-
| Key replies | `team reply post --from <seat> --title "<short>" --stdin
|
|
54
|
+
| Key replies | **The outlet for replies written for the user** (a landed milestone, a ruling, a conclusion, an answer, a status or progress report, a decision you ask the user for, a delivery or verification summary — however short, and never held back because it reads like process rather than like a conclusion): publish the complete reply — the substance the user needs to read, not a play-by-play — with `team reply post --from <seat> --title "<short>" --stdin`, then send that same body; a batch of user-facing replies may be one reply. A reply written to the patrol, to another seat or to another project's PM, and a tool receipt, are not for the user and stay out. Distinct from the internal channels: `say`/`notify` carry one-line coordination to a seat or the PM, not the reply itself. A saved receipt means project-local durable publication only — never user delivery, approval, read status or a refreshed console. `team reply list [--before <no>] [--json]`, `team reply show <no> [--json\|--raw]` (readers are observation-only: no mkdir, no writes, no lock; `--raw` exports the original bytes and refuses a TTY). The console's page 5 shows the latest reply plus the numbered history. See `references/protocol.md` §4b |
|
|
55
55
|
| Document contracts | `team task <ID> --title ... --agent a`, `team board add\|assign\|set\|ls`, `team change status <id> [--json]` (readiness view: tasks/evidence, declared vs touched delta files, blockers; exit 0 iff every mapped task is finished), `team thread <a> "..." --from pm --re <ID>`, `team report <ID> <a>` |
|
|
56
56
|
| Dispatch | `team add-agent <a> [--register] [--create] [--no-install] [--print]`, `team dispatch <a> <ID> <taskfile> [--model m] [--branch <name>] [--fresh] [--allow-overflow] [--force] [--print]` (a new dispatch selects the brief's `category:` model from `TEAM_TASK_MODELS` unless `--model` overrides; same-task recovery keeps the committed model/SID; all pre-launch guards are judged in **one pass**: one refusal lists every blocker, each with a paste-able `修法:<command>` or `改行:<exact line>` and a final count line; `--force` overrides only the guards that carry an override, printed as a warning and logged after a real launch) |
|
|
57
57
|
| Collaborate | `team say <a> "<one-line message>" [--no-verify]` (verifies delivery; falls back to the inbox when the agent is not running), `team notify <a> "<one line>" [--from <sender>]` (agent → PM; the sender comes from the runtime directory — an unresolved sender is refused, never recorded as `pm`) |
|
|
@@ -66,7 +66,7 @@ everything below is the daily loop, which starts once the project is up.
|
|
|
66
66
|
| PM/agent lifecycle | `team up [--agents]` (recover the PM), `team resume` (PM's tool: continue stopped agents), `team standby on\|off` (PM deliberately stands down) |
|
|
67
67
|
| Cross-project meetings | `team meeting open/say/read/list/inbox/propose/agree/close` (PM-to-PM peer exchange: interface work, advice, problem reports; **not a command channel** — consensus needs both sides) |
|
|
68
68
|
| Updates | `team mark-loaded` (record the version at session start), `team version --check` (should I reload?), `team changelog [--since X]`, `team reload` |
|
|
69
|
-
| Diagnostics | `team paths` (resolved paths/session), `team smoke` (end-to-end self-test; `TEAM_SMOKE_FAST=1 team smoke` = **fast mode**, pure-logic sections only, ~10s, skipped process sections print `SKIP (FAST mode)`; the **full** run is for delivery/review and queues on the gate lock — `TEAM_SMOKE_LOCK` / `TEAM_SMOKE_LOCK_WAIT`, holder in `<
|
|
69
|
+
| Diagnostics | `team paths` (resolved paths/session), `team smoke` (end-to-end self-test; `TEAM_SMOKE_FAST=1 team smoke` = **fast mode**, pure-logic sections only, ~10s, skipped process sections print `SKIP (FAST mode)`; the **full** run is for delivery/review and queues on the gate lock — `TEAM_SMOKE_LOCK` / `TEAM_SMOKE_LOCK_WAIT`, the mutex is a pair (published `<lock>` + dot-prefixed companion `<lock>.machine`, the holder recorded in `<companion>.holder`; neither file is ever unlinked, and losing the companion mid-run stops the run loudly), and `team review` takes the same pair before its timeout so the record's `queued`/`ran` are separate; the gate judges **correctness only** — its panel section keeps the time-independent knob check), `team version` |
|
|
70
70
|
| Performance | `team perf [--host \| --container]` (**separate from correctness**: the wall-clock/CPU red lines — interactive first frame, frame assembly, steady-state pane CPU — with the unchanged thresholds (2000 ms / 2000 ms / < 1 %), premise factors (`0.75` / `0.25`), medians, visible `SKIP` and exit codes `0`/`2`/`4`/`3`; its own lock `TEAM_PERF_LOCK`, never the gate lock; default = the pinned `ci/Containerfile` image, `--host` is labelled **not the reference**) |
|
|
71
71
|
|
|
72
72
|
The two gates answer different questions and are run at different times. **Correctness, on every change:**
|
|
@@ -164,6 +164,7 @@ bash <skill>/scripts/team changelog # change history (--since v1.8.0 for
|
|
|
164
164
|
| `scripts/**` (CLI) | **Nothing to do**: every call reads from disk |
|
|
165
165
|
| `SKILL.md` / `references/**` / `templates/**` | Type **`/reload`** in Pi (or `/teamsmith-reload`, or let the model call the `reload_skills` tool). **Note**: `/reload` refreshes the skill list/descriptions (system prompt) and extensions; **text already read into the conversation history does not change**, so after reloading you must `read <skill>/SKILL.md` again (the extension sends a follow-up prompt that triggers that re-read) |
|
|
166
166
|
| `extension/team-notify.ts`, `extension/team-bg.ts`, `extension/team-inbox-watch.ts` | **Restart the process** — the launch paths pass the extensions with `pi -e`, and `-e` modules are read at process start (`/reload` hot-reloads only extensions from Pi's auto-discovery locations, `~/.pi/agent/extensions/` and `.pi/extensions/`). PM: `team up`; worker: `team resume <agent>`. `team version --check` fingerprints them |
|
|
167
|
+
| `extension/team.ts` (the `/team` slash command) | **`/reload`** — `team init` installs it into the project's `.pi/extensions/team.ts`, which Pi discovers from the working directory; it is deliberately **not** injected with `-e` (that needs a process restart, and `/reload` is the point) and it is installed only in the main worktree — a worker worktree has no `/team` (seats call the CLI from bash). `team doctor` reports its install state; it is **not** part of the session fingerprint |
|
|
167
168
|
|
|
168
169
|
Rationale: Pi's `/reload` rediscovers skills, rebuilds the system prompt and re-imports extensions from its
|
|
169
170
|
auto-discovery locations; extensions passed with `-e` (which is how the team launch paths load them) are a
|
|
@@ -246,11 +247,17 @@ about them). They stay writable so the seam can be maintained and diagnosed; to
|
|
|
246
247
|
## Non-negotiable rules (verified during review)
|
|
247
248
|
- **Never claim something passed without having run it.** Reports must include commands and output tails; the PM
|
|
248
249
|
re-runs independently.
|
|
249
|
-
- **Publish the body before you answer
|
|
250
|
-
|
|
250
|
+
- **Publish the body before you answer — it is a standing duty.** Whenever the reply is written for the user — an
|
|
251
|
+
answer, a status or progress report, a conclusion or a ruling, a delivery or verification summary, a decision you
|
|
252
|
+
ask the user for, however short, and never held back because it reads like process rather than like a conclusion —
|
|
253
|
+
publish the complete reply (the substance the user needs to read, not a play-by-play) with
|
|
254
|
+
`team reply post --from <seat> --title "<short>" --stdin`, then send that same body normally — saved, input error,
|
|
251
255
|
storage error, busy or unconfirmed never changes what you send (the failure notice goes to stderr, never into the
|
|
252
|
-
answer). A
|
|
253
|
-
|
|
256
|
+
answer). A batch of user-facing replies may be one reply. A reply written to the patrol, to another seat or to
|
|
257
|
+
another project's PM, and a tool receipt, are not for the user and stay out; when the reader is unclear, ask who
|
|
258
|
+
the reply is written for and treat an unsettled case as written for the user. A saved
|
|
259
|
+
receipt means project-local durable publication only: not user delivery, not approval, not read status, not a
|
|
260
|
+
refreshed console, and it creates no pending work, no outbox/inbox entry and no wake-up. See
|
|
254
261
|
`references/protocol.md` §4b.
|
|
255
262
|
- Agents only touch directories they own (`OWNERSHIP.md`); cross-directory needs → write `BLOCKED:` in the report.
|
|
256
263
|
- Agents must not push the protected branch, force-push, merge PR/MRs, or rebase/delete other people's branches.
|
|
@@ -528,15 +528,47 @@ export default function (pi: ExtensionAPI) {
|
|
|
528
528
|
}
|
|
529
529
|
|
|
530
530
|
const line = `${new Date().toISOString()} ${dirtyFlag}${tag} ${summary}${revStamp}${completed && last ? ` :: ${last}` : ''}`
|
|
531
|
+
// turn-notice-merge(写入侧合并 + 明细):判定「扩展末尾的同类 run 还是新起一行」在 CLI 的收件箱
|
|
532
|
+
// 写入口里(每收件人一把锁 + 先明细后合并),扩展只消费写入结果 —— 只有写下**新行**才入队 knock。
|
|
533
|
+
const cli = join(skillDir(), 'scripts/team')
|
|
534
|
+
const lineFile = join(stateDir, `notify-line-${process.pid}-${Date.now()}.txt`)
|
|
535
|
+
let writeOut = ''
|
|
531
536
|
try {
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
537
|
+
writeFileSync(lineFile, line)
|
|
538
|
+
writeOut = execFileSync(
|
|
539
|
+
'bash',
|
|
540
|
+
[cli, '--root', root, '__inbox-write', '--agent', agent, '--from-file', lineFile],
|
|
541
|
+
{ encoding: 'utf8', timeout: 5000 },
|
|
542
|
+
)
|
|
535
543
|
log(`inbox ${tag} ${summary}`, cfg)
|
|
536
544
|
} catch (error) {
|
|
545
|
+
writeOut = ''
|
|
537
546
|
log(`inbox write failed: ${String(error)}`, cfg)
|
|
547
|
+
} finally {
|
|
548
|
+
try { rmSync(lineFile, { force: true }) } catch { /* ignore */ }
|
|
549
|
+
}
|
|
550
|
+
const writeState = /^state=([a-z]+)/m.exec(writeOut)?.[1] ?? ''
|
|
551
|
+
if (writeState !== 'new') {
|
|
552
|
+
// 扩展既有 run(state=extended)的 settle 不入队、不敲字:计数抖动看得见但不叫醒。
|
|
553
|
+
// 写盘失败(异常 / state=failed)也不叫醒 —— 与手工路径的「写失败不得授权唤醒」同一条规则。
|
|
554
|
+
log(`no knock (inbox write state=${writeState || 'failed'})`, cfg)
|
|
555
|
+
return
|
|
538
556
|
}
|
|
539
557
|
|
|
558
|
+
// 挂起只记录、不叫醒(用户裁定 2026-10-14):`[auto·suspended]` 是设计好的状态(席位起了长任务并
|
|
559
|
+
// 正确地结束回合等叫醒),PM 没有可行动的事 —— 行、明细、面板、digest 照旧,但不入队 knock。交付
|
|
560
|
+
// (要复验/合并)与中断(要诊断)照旧敲门;挂起中的失败面(席位死去、任务永不完)归巡检的
|
|
561
|
+
// 「任务未完成 + 窗口不在」那一档,不由这条通知兜。
|
|
562
|
+
if (suspended) {
|
|
563
|
+
log('no knock (suspended records only)', cfg)
|
|
564
|
+
return
|
|
565
|
+
}
|
|
566
|
+
const firstEvent = /^first=(\S+)/m.exec(writeOut)?.[1] ?? ''
|
|
567
|
+
const mergeKey = /^key=(\S*)/m.exec(writeOut)?.[1] ?? ''
|
|
568
|
+
// knock 的去重身份 = **行身份**(席位 + 合并键 + 首事件时间):两条文本逐字相同但不同的行不会互吞,
|
|
569
|
+
// 同一 run 的重复 settle 也绝不会二次敲门(此时它连条目都不入队)。席位是 mergeKey 的第一个分量。
|
|
570
|
+
const lineIdentity = `line|${mergeKey}|${firstEvent}`
|
|
571
|
+
|
|
540
572
|
if (!cfg.notifyTmux || !window) return
|
|
541
573
|
const target = `${cfg.session}:${cfg.pmWindow}`
|
|
542
574
|
try {
|
|
@@ -553,17 +585,16 @@ export default function (pi: ExtensionAPI) {
|
|
|
553
585
|
}
|
|
554
586
|
// 敲门不再自己 send-keys:交给 teamsmith 的投递守卫 + 延后队列(delivery-guard)。
|
|
555
587
|
// 为什么:扩展原来直接 `send-keys -l` + Enter,人正在 PM 输入框里写草稿时会把草稿粘走
|
|
556
|
-
// (D20
|
|
588
|
+
// (D20 的原始事故)。入队时带上 knock 自己的**行身份**(lineIdentity),两层抑制不会打架。
|
|
557
589
|
// 失败只记日志:绝不回退到打字(那会悄悄重建同一个 bug)。
|
|
558
590
|
const notice = `${dirtyFlag}${tag} ${summary}${revStamp}${completed && last ? `\n> ${last}` : ''}`
|
|
559
|
-
const cli = join(skillDir(), 'scripts/team')
|
|
560
591
|
const tmp = join(stateDir, `knock-${process.pid}-${Date.now()}.txt`)
|
|
561
592
|
try {
|
|
562
593
|
writeFileSync(tmp, notice)
|
|
563
594
|
const out = execFileSync(
|
|
564
595
|
'bash',
|
|
565
596
|
[cli, '--root', root, 'outbox', 'enqueue', '--kind', 'knock', '--target', target,
|
|
566
|
-
'--from', agent, '--dedup',
|
|
597
|
+
'--from', agent, '--dedup', lineIdentity, '--from-file', tmp],
|
|
567
598
|
{ encoding: 'utf8', timeout: 5000 },
|
|
568
599
|
)
|
|
569
600
|
log(`knock queued (${String(out).trim() || 'entry written'})`, cfg)
|
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
// teamsmith /team extension
|
|
2
|
+
/**
|
|
3
|
+
* teamsmith · `/team` 斜杠命令(change: slash-team)
|
|
4
|
+
*
|
|
5
|
+
* 用户坐在 Pi 会话里,用 `/team …` 跑项目自己的 `team` CLI:一条命令都不重新实现,把用户打的 token
|
|
6
|
+
* 原样交给子进程(cwd = 项目根),把 stdout/stderr/退出码如实带回对话。这是「前门」,不是第二套 CLI。
|
|
7
|
+
*
|
|
8
|
+
* 结构(design §3.8 的两层):
|
|
9
|
+
* - **纯逻辑**(本文件里不碰任何 Pi API 的部分):白名单表、分词、匹配、菜单、项目根/CLI 解析、
|
|
10
|
+
* `runTeamCommand(deps, argv)`。夹具用假 pi 直接驱动它们。
|
|
11
|
+
* - **Pi 粘合**:文件末尾的默认导出 —— 只 `registerCommand("team", …)` 一次,**从不**注册任何
|
|
12
|
+
* 模型可调用的工具(模型不能自己触发这条命令)
|
|
13
|
+
*
|
|
14
|
+
* 加载方式(design §3.1):`team init`/`bootstrap` 把它装到 `<main worktree>/.pi/extensions/team.ts`
|
|
15
|
+
* (默认软链),Pi 从工作目录自动发现、`/reload` 即生效;**不**用 `pi -e` 注入(那要重启进程)。
|
|
16
|
+
*
|
|
17
|
+
* 零运行时依赖:只有 `node:*` 内建与 `import type`(被擦除),所以 `bun -e "await import(...)"` 能加载。
|
|
18
|
+
*/
|
|
19
|
+
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
|
|
20
|
+
import { existsSync } from 'node:fs'
|
|
21
|
+
import { dirname, join, resolve } from 'node:path'
|
|
22
|
+
import { fileURLToPath } from 'node:url'
|
|
23
|
+
|
|
24
|
+
// ---------------------------------------------------------------- 文案表(design §3.7)
|
|
25
|
+
// 一行一条、语言是一列:今天只有 zh 一份;P260 若落地 TEAM_LANG,这里加一列而不是改写调用点。
|
|
26
|
+
type StringRow = { key: string; zh: string }
|
|
27
|
+
const STRINGS: StringRow[] = [
|
|
28
|
+
{ key: 'menu.title', zh: 'teamsmith /team · 在对话里跑项目自己的 team 命令(输出进对话,退出码照实报)' },
|
|
29
|
+
{ key: 'menu.group.read', zh: '读取' },
|
|
30
|
+
{ key: 'menu.group.action', zh: '你自己动手' },
|
|
31
|
+
{ key: 'menu.footer', zh: '不在上面的命令是 PM / 席位的工具,请到终端跑。' },
|
|
32
|
+
{ key: 'refuse.outside', zh: '✗ /team 不认这条命令:{{name}} —— 这是 PM / 席位的命令,请到终端执行(输入 /team 看能用什么)' },
|
|
33
|
+
{ key: 'refuse.shape', zh: '✗ /team 不认这个形状:team {{argv}} —— {{path}} 只认自己的形状({{forms}});{{extra}}要跑别的形状(那是 PM / 席位的工具)请到终端。' },
|
|
34
|
+
{ key: 'refuse.pm-restart', zh: '✗ /team 不跑 up:这个会话就是 PM 会话,从这里重启会把当前对话一起带走 —— 要重启请到终端跑 team up。' },
|
|
35
|
+
{ key: 'refuse.no-project', zh: '✗ /team 找不到项目:当前目录 {{cwd}} 向上没有 .pi/team/config.sh —— 到 teamsmith 项目里再用,或先跑 team init。' },
|
|
36
|
+
{ key: 'refuse.no-cli', zh: '✗ /team 找不到 team CLI:{{root}} 下既没有 .pi/skills/teamsmith/scripts/team,也没有可用的 TEAM_CLI —— 跑 team init 装项目本地 skill。' },
|
|
37
|
+
{ key: 'refuse.quote', zh: '✗ /team 参数里的引号没有闭合:{{raw}} —— 不猜,什么都不跑(补上引号再来)。' },
|
|
38
|
+
{ key: 'refuse.escape', zh: '✗ /team 参数以反斜杠结尾:{{raw}} —— 不猜,什么都不跑。' },
|
|
39
|
+
{ key: 'run.header', zh: '$ team {{argv}}' },
|
|
40
|
+
{ key: 'run.exit', zh: 'exit {{code}}' },
|
|
41
|
+
{ key: 'run.killed', zh: 'killed:超时 {{sec}}s' },
|
|
42
|
+
{ key: 'run.stdout', zh: '--- stdout ---' },
|
|
43
|
+
{ key: 'run.stderr', zh: '--- stderr ---' },
|
|
44
|
+
{ key: 'run.elided', zh: '…(省略 {{lines}} 行 / {{bytes}} 字节;完整输出:在终端跑 team {{argv}})' },
|
|
45
|
+
{ key: 'fail.exit', zh: '命令失败:team {{argv}}(exit {{code}})' },
|
|
46
|
+
{ key: 'fail.killed', zh: '命令超时被杀:team {{argv}}({{sec}}s 上限)' },
|
|
47
|
+
{ key: 'command.description', zh: '跑项目自己的 team 命令(白名单:读取 + 你自己动手的操作)' },
|
|
48
|
+
]
|
|
49
|
+
const STRING_INDEX: Record<string, string> = (() => {
|
|
50
|
+
const m: Record<string, string> = {}
|
|
51
|
+
for (const row of STRINGS) m[row.key] = row.zh
|
|
52
|
+
return m
|
|
53
|
+
})()
|
|
54
|
+
/** 取文案(今天只有 zh;P260 的 TEAM_LANG 落地后在这里选列)。 */
|
|
55
|
+
export function t(key: string, vars?: Record<string, string>): string {
|
|
56
|
+
let s = STRING_INDEX[key]
|
|
57
|
+
if (s === undefined) return key
|
|
58
|
+
if (vars) for (const k of Object.keys(vars)) s = s.split(`{{${k}}}`).join(vars[k])
|
|
59
|
+
return s
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// ---------------------------------------------------------------- 白名单:一张表,两种行(design §3.2)
|
|
63
|
+
/** 读行形状里的「一个自由 token」占位符(`<ID>` / `<n>` / `<slug>`)。 */
|
|
64
|
+
export const ARG = '<arg>'
|
|
65
|
+
export type Group = 'read' | 'action'
|
|
66
|
+
export type Row = {
|
|
67
|
+
group: Group
|
|
68
|
+
/** 命令路径(菜单/补全/探针都用它;一行可以有多条路径,例如 pulse 的三个动词)。 */
|
|
69
|
+
paths: string[][]
|
|
70
|
+
/** 读行专有:逐字接受的 token 形状(`ARG` = 恰好一个自由 token)。动行没有它 = 路径 + 自由尾巴。 */
|
|
71
|
+
forms?: string[][]
|
|
72
|
+
/** 菜单里那一句用途。 */
|
|
73
|
+
purpose: string
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export const TEAM_ROWS: Row[] = [
|
|
77
|
+
{ group: 'read', paths: [['status']], forms: [['status'], ['status', ARG]], purpose: '名册 + 任务/report 状态' },
|
|
78
|
+
{ group: 'read', paths: [['digest']], forms: [['digest']], purpose: '给 PM 的待办摘要' },
|
|
79
|
+
{ group: 'read', paths: [['ps']], forms: [['ps']], purpose: '容量:RAM/swap/还能再跑几个 agent' },
|
|
80
|
+
{ group: 'read', paths: [['board']], forms: [['board'], ['board', 'ls']], purpose: '看板(BOARD.md)' },
|
|
81
|
+
{ group: 'read', paths: [['reply', 'list']], forms: [['reply', 'list']], purpose: '关键回复列表(JSON)' },
|
|
82
|
+
{ group: 'read', paths: [['reply', 'show']], forms: [['reply', 'show', ARG]], purpose: '读第 n 条关键回复' },
|
|
83
|
+
{ group: 'read', paths: [['config', 'list']], forms: [['config', 'list']], purpose: '项目契约的每个键与当前值' },
|
|
84
|
+
{ group: 'read', paths: [['version']], forms: [['version']], purpose: '磁盘版本 / 本会话加载版本' },
|
|
85
|
+
{ group: 'read', paths: [['doctor']], forms: [['doctor']], purpose: '环境自检' },
|
|
86
|
+
{ group: 'read', paths: [['meeting', 'inbox']], forms: [['meeting', 'inbox']], purpose: '待回应的会议' },
|
|
87
|
+
{ group: 'read', paths: [['meeting', 'read']], forms: [['meeting', 'read', ARG]], purpose: '读一场会议' },
|
|
88
|
+
{ group: 'action', paths: [['pulse', 'up'], ['pulse', 'down'], ['pulse', 'status']], purpose: '巡检窗口(起/停/看)' },
|
|
89
|
+
{ group: 'action', paths: [['config', 'upgrade-models']], purpose: '模型策略升级(写盘要 --yes)' },
|
|
90
|
+
{ group: 'action', paths: [['meeting', 'say']], purpose: '给对面 PM 发言(--intent 必填)' },
|
|
91
|
+
{ group: 'action', paths: [['meeting', 'close']], purpose: '结束一场会议' },
|
|
92
|
+
]
|
|
93
|
+
|
|
94
|
+
/** 表外命令的**具名**前缀(拒绝文案要点名 `dispatch` / `config set` 这样的命令,而不是只报第一个词)。 */
|
|
95
|
+
export const REFUSED_PATHS: string[][] = [
|
|
96
|
+
['up'], ['dispatch'], ['say'], ['notify'], ['close'], ['teardown'],
|
|
97
|
+
['config', 'set'], ['smoke'], ['gate'], ['perf'], ['review'], ['change'],
|
|
98
|
+
['archive'], ['bg'], ['add-agent'], ['init'], ['bootstrap'], ['draft'],
|
|
99
|
+
['outbox'], ['inbox'], ['thread'], ['monitor'], ['pr'], ['gh'],
|
|
100
|
+
]
|
|
101
|
+
|
|
102
|
+
// ---------------------------------------------------------------- 分词(design §3.3)
|
|
103
|
+
export type TokenizeResult = { ok: true; tokens: string[] } | { ok: false; error: string }
|
|
104
|
+
|
|
105
|
+
/** 空白分隔;单/双引号;引号外反斜杠转义;未闭合引号(或结尾反斜杠)⇒ 拒绝,什么都不跑。 */
|
|
106
|
+
export function tokenize(raw: string): TokenizeResult {
|
|
107
|
+
const tokens: string[] = []
|
|
108
|
+
let cur = ''
|
|
109
|
+
let started = false
|
|
110
|
+
let i = 0
|
|
111
|
+
while (i < raw.length) {
|
|
112
|
+
const ch = raw[i]
|
|
113
|
+
if (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') {
|
|
114
|
+
if (started) { tokens.push(cur); cur = ''; started = false }
|
|
115
|
+
i++
|
|
116
|
+
continue
|
|
117
|
+
}
|
|
118
|
+
started = true
|
|
119
|
+
if (ch === "'") {
|
|
120
|
+
const j = raw.indexOf("'", i + 1)
|
|
121
|
+
if (j < 0) return { ok: false, error: t('refuse.quote', { raw }) }
|
|
122
|
+
cur += raw.slice(i + 1, j)
|
|
123
|
+
i = j + 1
|
|
124
|
+
continue
|
|
125
|
+
}
|
|
126
|
+
if (ch === '"') {
|
|
127
|
+
i++
|
|
128
|
+
let closed = false
|
|
129
|
+
while (i < raw.length) {
|
|
130
|
+
const c = raw[i]
|
|
131
|
+
if (c === '"') { closed = true; i++; break }
|
|
132
|
+
if (c === '\\' && i + 1 < raw.length && (raw[i + 1] === '"' || raw[i + 1] === '\\')) {
|
|
133
|
+
cur += raw[i + 1]; i += 2; continue
|
|
134
|
+
}
|
|
135
|
+
cur += c; i++
|
|
136
|
+
}
|
|
137
|
+
if (!closed) return { ok: false, error: t('refuse.quote', { raw }) }
|
|
138
|
+
continue
|
|
139
|
+
}
|
|
140
|
+
if (ch === '\\') {
|
|
141
|
+
if (i + 1 >= raw.length) return { ok: false, error: t('refuse.escape', { raw }) }
|
|
142
|
+
cur += raw[i + 1]; i += 2; continue
|
|
143
|
+
}
|
|
144
|
+
cur += ch; i++
|
|
145
|
+
}
|
|
146
|
+
if (started) tokens.push(cur)
|
|
147
|
+
return { ok: true, tokens }
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// ---------------------------------------------------------------- 匹配(design §3.2 / §3.3)
|
|
151
|
+
export type Match =
|
|
152
|
+
| { kind: 'menu' }
|
|
153
|
+
| { kind: 'run'; row: Row; tokens: string[] }
|
|
154
|
+
| { kind: 'refuse'; message: string }
|
|
155
|
+
|
|
156
|
+
function formMatches(form: string[], tokens: string[]): boolean {
|
|
157
|
+
if (form.length !== tokens.length) return false
|
|
158
|
+
for (let i = 0; i < form.length; i++) if (form[i] !== ARG && form[i] !== tokens[i]) return false
|
|
159
|
+
return true
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function startsWithPath(tokens: string[], path: string[]): boolean {
|
|
163
|
+
if (tokens.length < path.length) return false
|
|
164
|
+
for (let i = 0; i < path.length; i++) if (tokens[i] !== path[i]) return false
|
|
165
|
+
return true
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function formsText(row: Row): string {
|
|
169
|
+
return (row.forms ?? []).map((f) => 'team ' + f.join(' ')).join(' / ')
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** 表外命令的具名前缀:最长匹配(`config set` 优先于 `config`)。 */
|
|
173
|
+
export function refusedName(tokens: string[]): string {
|
|
174
|
+
let best: string[] | null = null
|
|
175
|
+
for (const p of REFUSED_PATHS) {
|
|
176
|
+
if (!startsWithPath(tokens, p)) continue
|
|
177
|
+
if (best === null || p.length > best.length) best = p
|
|
178
|
+
}
|
|
179
|
+
if (best) return best.join(' ')
|
|
180
|
+
return tokens[0] ?? ''
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export function matchInvocation(tokens: string[]): Match {
|
|
184
|
+
if (tokens.length === 0) return { kind: 'menu' }
|
|
185
|
+
if (tokens.length === 1 && tokens[0] === 'help') return { kind: 'menu' }
|
|
186
|
+
// design §3.2 坑 1:会重启/新建 PM 会话的调用一律拒绝(up 与任何带 --fresh-pm 的调用)。
|
|
187
|
+
if (tokens[0] === 'up' || tokens.indexOf('--fresh-pm') >= 0) {
|
|
188
|
+
return { kind: 'refuse', message: t('refuse.pm-restart') }
|
|
189
|
+
}
|
|
190
|
+
// ① 读行:严格形状,整个 argv 吃完才算命中。
|
|
191
|
+
for (const row of TEAM_ROWS) {
|
|
192
|
+
if (!row.forms) continue
|
|
193
|
+
for (const form of row.forms) if (formMatches(form, tokens)) return { kind: 'run', row, tokens }
|
|
194
|
+
}
|
|
195
|
+
// ② 读行的形状不符(多/少 token):点名那一行与多出来的 token,零副作用。
|
|
196
|
+
for (const row of TEAM_ROWS) {
|
|
197
|
+
if (!row.forms) continue
|
|
198
|
+
if (!startsWithPath(tokens, row.paths[0])) continue
|
|
199
|
+
const extra = tokens.slice(row.paths[0].length).join(' ')
|
|
200
|
+
return {
|
|
201
|
+
kind: 'refuse',
|
|
202
|
+
message: t('refuse.shape', {
|
|
203
|
+
argv: tokens.join(' '),
|
|
204
|
+
path: row.paths[0].join(' '),
|
|
205
|
+
forms: formsText(row),
|
|
206
|
+
extra: extra ? `多出来的 token ${extra} 不原样透传;` : '',
|
|
207
|
+
}),
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
// ③ 动行:命令路径 + 用户自己的尾巴(原样透传,由 CLI 校验)。
|
|
211
|
+
for (const row of TEAM_ROWS) {
|
|
212
|
+
if (row.forms) continue
|
|
213
|
+
for (const path of row.paths) if (startsWithPath(tokens, path)) return { kind: 'run', row, tokens }
|
|
214
|
+
}
|
|
215
|
+
// ④ 表外:一个进程都不起。
|
|
216
|
+
return { kind: 'refuse', message: t('refuse.outside', { name: refusedName(tokens) }) }
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// ---------------------------------------------------------------- 菜单与补全(design §3.2,单真源)
|
|
220
|
+
function rowName(row: Row): string {
|
|
221
|
+
return row.paths.map((p) => p.join(' ')).join(' / ')
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export function renderMenu(): string {
|
|
225
|
+
const lines: string[] = [t('menu.title')]
|
|
226
|
+
let width = 0
|
|
227
|
+
for (const row of TEAM_ROWS) width = Math.max(width, rowName(row).length)
|
|
228
|
+
for (const group of ['read', 'action'] as Group[]) {
|
|
229
|
+
lines.push('')
|
|
230
|
+
lines.push(t(group === 'read' ? 'menu.group.read' : 'menu.group.action'))
|
|
231
|
+
for (const row of TEAM_ROWS) {
|
|
232
|
+
if (row.group !== group) continue
|
|
233
|
+
const name = rowName(row)
|
|
234
|
+
lines.push(' ' + name + ' '.repeat(width - name.length + 2) + row.purpose)
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
lines.push('')
|
|
238
|
+
lines.push(t('menu.footer'))
|
|
239
|
+
return lines.join('\n')
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export type CompletionItem = { value: string; label: string; description?: string }
|
|
243
|
+
|
|
244
|
+
export function completions(prefix: string): CompletionItem[] {
|
|
245
|
+
const raw = prefix.replace(/^\s+/, '')
|
|
246
|
+
const pt = raw.split(/\s+/).filter((s) => s !== '')
|
|
247
|
+
const items: CompletionItem[] = []
|
|
248
|
+
for (const row of TEAM_ROWS) {
|
|
249
|
+
for (const path of row.paths) {
|
|
250
|
+
let hit = true
|
|
251
|
+
if (pt.length > path.length) hit = false
|
|
252
|
+
for (let i = 0; hit && i < pt.length; i++) {
|
|
253
|
+
if (i === pt.length - 1) { if (!path[i].startsWith(pt[i])) hit = false }
|
|
254
|
+
else if (path[i] !== pt[i]) hit = false
|
|
255
|
+
}
|
|
256
|
+
if (hit) items.push({ value: path.join(' '), label: path.join(' '), description: row.purpose })
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return items
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// ---------------------------------------------------------------- 项目根与 CLI 解析(design §3.5)
|
|
263
|
+
/** 从 `cwd` 向上找第一个含 `.pi/team/config.sh` 的目录;找不到 = null(不是 teamsmith 项目)。 */
|
|
264
|
+
export function findProjectRoot(cwd: string): string | null {
|
|
265
|
+
let d = resolve(cwd)
|
|
266
|
+
for (;;) {
|
|
267
|
+
if (existsSync(join(d, '.pi', 'team', 'config.sh'))) return d
|
|
268
|
+
const up = dirname(d)
|
|
269
|
+
if (up === d) return null
|
|
270
|
+
d = up
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* CLI 路径(顺序有意,design §3.5):项目本地安装永远赢 → `${TEAM_CLI}`(测试/非默认安装旋钮)
|
|
276
|
+
* → 扩展自己的兄弟目录 `<ext-dir>/../scripts/team`(`-e` 或 realpath 解析过的软链形态)→ null。
|
|
277
|
+
*/
|
|
278
|
+
export function resolveCli(root: string, env: Record<string, string | undefined>, extDir?: string): string | null {
|
|
279
|
+
const local = join(root, '.pi', 'skills', 'teamsmith', 'scripts', 'team')
|
|
280
|
+
if (existsSync(local)) return local
|
|
281
|
+
const envCli = env['TEAM_CLI']
|
|
282
|
+
if (envCli !== undefined && envCli !== '') return envCli
|
|
283
|
+
if (extDir !== undefined && extDir !== '') {
|
|
284
|
+
const sibling = resolve(extDir, '..', 'scripts', 'team')
|
|
285
|
+
if (existsSync(sibling)) return sibling
|
|
286
|
+
}
|
|
287
|
+
return null
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// ---------------------------------------------------------------- 执行与输出(design §3.4 / §3.5)
|
|
291
|
+
export const CUSTOM_TYPE = 'teamsmith-team'
|
|
292
|
+
export const WAIT_MS = 60000
|
|
293
|
+
export const SHORT_LINE_MAX = 200
|
|
294
|
+
export const FUSE_LINES = 500
|
|
295
|
+
export const FUSE_BYTES = 64 * 1024
|
|
296
|
+
export const FUSE_HEAD_LINES = 200
|
|
297
|
+
export const FUSE_TAIL_LINES = 100
|
|
298
|
+
/** 唯一一处收紧:剥掉「替用户说 yes」的三个变量(用户自己打的 --yes 照旧到达)。 */
|
|
299
|
+
export const UNSET_VARS = ['TEAM_ASSUME_YES', 'TEAM_UPGRADE_CONFIRMED', 'TEAM_ALLOW_FOREIGN_SESSION']
|
|
300
|
+
|
|
301
|
+
export type ExecOptions = { cwd?: string; timeout?: number }
|
|
302
|
+
export type ExecResult = { stdout: string; stderr: string; code: number; killed: boolean }
|
|
303
|
+
export type ExecFn = (command: string, args: string[], options?: ExecOptions) => Promise<ExecResult>
|
|
304
|
+
export type CustomMessage = { customType: string; content: string; display?: boolean }
|
|
305
|
+
export type Deps = {
|
|
306
|
+
cwd: string
|
|
307
|
+
exec: ExecFn
|
|
308
|
+
sendMessage: (message: CustomMessage) => void
|
|
309
|
+
notify: (message: string, type?: 'info' | 'warning' | 'error') => void
|
|
310
|
+
env?: Record<string, string | undefined>
|
|
311
|
+
extDir?: string
|
|
312
|
+
}
|
|
313
|
+
export type Outcome =
|
|
314
|
+
| { kind: 'menu'; text: string }
|
|
315
|
+
| { kind: 'refused'; message: string }
|
|
316
|
+
| { kind: 'ran'; argv: string[]; code: number; killed: boolean; content: string; short: boolean }
|
|
317
|
+
|
|
318
|
+
/** 剥离包装:`bash -c 'unset …; exec "$0" "$@"' <cli> <tokens…>` —— 只转交,不做二次解析。 */
|
|
319
|
+
export function wrapScript(): string {
|
|
320
|
+
const unset = UNSET_VARS.length > 0 ? `unset ${UNSET_VARS.join(' ')}; ` : ''
|
|
321
|
+
return `${unset}exec "$0" "$@"`
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function utf8Bytes(s: string): number {
|
|
325
|
+
let n = 0
|
|
326
|
+
for (let i = 0; i < s.length; i++) {
|
|
327
|
+
const c = s.charCodeAt(i)
|
|
328
|
+
if (c < 0x80) n += 1
|
|
329
|
+
else if (c < 0x800) n += 2
|
|
330
|
+
else if (c >= 0xd800 && c <= 0xdbff) { n += 4; i++ }
|
|
331
|
+
else n += 3
|
|
332
|
+
}
|
|
333
|
+
return n
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** 保险丝:超过 500 行或 64 KiB(先到先算)时保留前 200 + 后 100 行,中间显式说明去哪看全文。 */
|
|
337
|
+
export function fuseOutput(text: string, argv: string[]): string {
|
|
338
|
+
const lines = text.split('\n')
|
|
339
|
+
const bytes = utf8Bytes(text)
|
|
340
|
+
if (lines.length <= FUSE_LINES && bytes <= FUSE_BYTES) return text
|
|
341
|
+
const head = lines.slice(0, FUSE_HEAD_LINES)
|
|
342
|
+
const tail = lines.slice(lines.length - FUSE_TAIL_LINES)
|
|
343
|
+
const dropped = lines.length - head.length - tail.length
|
|
344
|
+
const droppedBytes = Math.max(0, bytes - utf8Bytes(head.join('\n')) - utf8Bytes(tail.join('\n')))
|
|
345
|
+
const notice = t('run.elided', { lines: String(dropped), bytes: String(droppedBytes), argv: argv.join(' ') })
|
|
346
|
+
return head.concat([notice], tail).join('\n')
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** 单行且 ≤ 200 字符(按码点)的成功结果 ⇒ 通知,不进对话。 */
|
|
350
|
+
export function isShortSuccess(res: ExecResult): boolean {
|
|
351
|
+
if (res.killed || res.code !== 0) return false
|
|
352
|
+
const text = (res.stdout ?? '').replace(/^\s+/, '').replace(/\s+$/, '')
|
|
353
|
+
if (text === '' || text.indexOf('\n') >= 0) return false
|
|
354
|
+
return Array.from(text).length <= SHORT_LINE_MAX
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
export function shortText(res: ExecResult): string {
|
|
358
|
+
return (res.stdout ?? '').replace(/^\s+/, '').replace(/\s+$/, '')
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** 正文条目:命令行 + 退出码(或被杀原因)+ stdout(+ stderr)。 */
|
|
362
|
+
export function formatEntry(argv: string[], res: ExecResult): string {
|
|
363
|
+
const header = t('run.header', { argv: argv.join(' ') })
|
|
364
|
+
const status = res.killed ? t('run.killed', { sec: String(WAIT_MS / 1000) }) : t('run.exit', { code: String(res.code) })
|
|
365
|
+
let body = t('run.stdout') + '\n' + (res.stdout ?? '')
|
|
366
|
+
if ((res.stderr ?? '') !== '') body += '\n' + t('run.stderr') + '\n' + res.stderr
|
|
367
|
+
return header + '\n' + status + '\n' + fuseOutput(body, argv)
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
export function failureNotice(argv: string[], res: ExecResult): string {
|
|
371
|
+
if (res.killed) return t('fail.killed', { argv: argv.join(' '), sec: String(WAIT_MS / 1000) })
|
|
372
|
+
return t('fail.exit', { argv: argv.join(' '), code: String(res.code) })
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function refuse(deps: Deps, message: string): Outcome {
|
|
376
|
+
deps.sendMessage({ customType: CUSTOM_TYPE, content: message, display: true })
|
|
377
|
+
return { kind: 'refused', message }
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* 纯逻辑入口:拒绝/菜单/执行与落点都在这里。`deps` 是全部外部接触面(exec / sendMessage / notify),
|
|
382
|
+
* 所以假 pi 可以直接驱动它,而它自己不认识任何 Pi API。
|
|
383
|
+
*/
|
|
384
|
+
export async function runTeamCommand(deps: Deps, argv: string[]): Promise<Outcome> {
|
|
385
|
+
const m = matchInvocation(argv)
|
|
386
|
+
if (m.kind === 'menu') {
|
|
387
|
+
const text = renderMenu()
|
|
388
|
+
deps.sendMessage({ customType: CUSTOM_TYPE, content: text, display: true })
|
|
389
|
+
return { kind: 'menu', text }
|
|
390
|
+
}
|
|
391
|
+
if (m.kind === 'refuse') return refuse(deps, m.message)
|
|
392
|
+
|
|
393
|
+
const root = findProjectRoot(deps.cwd)
|
|
394
|
+
if (root === null) return refuse(deps, t('refuse.no-project', { cwd: deps.cwd }))
|
|
395
|
+
const cli = resolveCli(root, deps.env ?? {}, deps.extDir)
|
|
396
|
+
if (cli === null) return refuse(deps, t('refuse.no-cli', { root }))
|
|
397
|
+
|
|
398
|
+
const res = await deps.exec('bash', ['-c', wrapScript(), cli, ...m.tokens], { cwd: root, timeout: WAIT_MS })
|
|
399
|
+
|
|
400
|
+
if (isShortSuccess(res)) {
|
|
401
|
+
const text = shortText(res)
|
|
402
|
+
deps.notify(text, 'info')
|
|
403
|
+
return { kind: 'ran', argv: m.tokens, code: res.code, killed: res.killed, content: text, short: true }
|
|
404
|
+
}
|
|
405
|
+
const content = formatEntry(m.tokens, res)
|
|
406
|
+
deps.sendMessage({ customType: CUSTOM_TYPE, content, display: true })
|
|
407
|
+
if (res.killed || res.code !== 0) deps.notify(failureNotice(m.tokens, res), 'error')
|
|
408
|
+
return { kind: 'ran', argv: m.tokens, code: res.code, killed: res.killed, content, short: false }
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// ---------------------------------------------------------------- Pi 粘合(唯一使用 Pi API 的地方)
|
|
412
|
+
const HERE = (() => {
|
|
413
|
+
try { return dirname(fileURLToPath(import.meta.url)) } catch { return undefined }
|
|
414
|
+
})()
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* 默认导出:**只**注册 `/team` 一条命令。不注册任何模型可调用的工具 —— 模型不能自己触发它;
|
|
418
|
+
* 不弹任何自己的确认框 —— 前门不给用户加第二道自己的政策(CLI 的守卫原样生效)。
|
|
419
|
+
*/
|
|
420
|
+
export default function teamExtension(pi: ExtensionAPI): void {
|
|
421
|
+
pi.registerCommand('team', {
|
|
422
|
+
description: t('command.description'),
|
|
423
|
+
getArgumentCompletions: (prefix: string) => completions(prefix),
|
|
424
|
+
handler: async (args: string, ctx) => {
|
|
425
|
+
const deps: Deps = {
|
|
426
|
+
cwd: ctx.cwd,
|
|
427
|
+
exec: (command, argv, options) => pi.exec(command, argv, options),
|
|
428
|
+
sendMessage: (message) => pi.sendMessage(message),
|
|
429
|
+
notify: (message, type) => ctx.ui.notify(message, type),
|
|
430
|
+
env: process.env as Record<string, string | undefined>,
|
|
431
|
+
extDir: HERE,
|
|
432
|
+
}
|
|
433
|
+
const parsed = tokenize(args)
|
|
434
|
+
if (!parsed.ok) { refuse(deps, parsed.error); return }
|
|
435
|
+
await runTeamCommand(deps, parsed.tokens)
|
|
436
|
+
},
|
|
437
|
+
})
|
|
438
|
+
}
|