mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-17 04:45:33 -08:00
Sync upstream web console updates into v2.5.0: a Subagents switch that tells the agent to use helpers (per project and skill, sent as a standing instruction only when it changes), a Subagents tab listing the helpers the agent reports, a standalone review that asks what to review instead of assuming the branch diff, a refusal for doc patches that move a version backwards, and the project name in the footer and browser tab title
This commit is contained in:
1 parent
8fb19ec933
commit
eac5f6590f
179 files changed
+14955
-466
No files matched your search
@@ -39,10 +39,10 @@ Three levels -- auto-detected, always respect explicit user override:
|
||||
| Scope | Trigger | Reviews |
|
||||
|-------|---------|---------|
|
||||
| **Focused** | User names files/functions, or conversation work detected | Specified files only |
|
||||
| **Branch** | "review my changes" or no context available | Branch changes vs main |
|
||||
| **Branch** | "review my changes", or picked when asked | Branch changes vs main |
|
||||
| **Full** | "full review" or names a subsystem | Entire codebase/subsystem |
|
||||
|
||||
**Detection:** 1) User prompt wins. 2) Conversation context = `focused`. 3) Fallback = `branch`. Ambiguous? Ask.
|
||||
**Detection:** 1) User prompt wins. 2) Conversation context = `focused`. 3) Scope already decided by a host workflow (a build's review, `building.md`) = use it. 4) Standalone with nothing named = scan, then ask (Step 1). Never default to `branch` silently. Ambiguous? Ask.
|
||||
|
||||
**Thoroughness:** Scope controls WHAT is reviewed, not HOW DEEPLY. Every review is thorough.
|
||||
|
||||
@@ -52,7 +52,7 @@ Three levels -- auto-detected, always respect explicit user override:
|
||||
|
||||
## Process
|
||||
|
||||
**Pre-flight:** Check AGENTS.md — use conventions if found, note if missing. Determine review target from user prompt or conversation context. If neither provides clear signal, use `ask_user_question` — never guess.
|
||||
**Pre-flight:** Check AGENTS.md — use conventions if found, note if missing. Determine review target from user prompt or conversation context. If neither provides clear signal, scan and use `ask_user_question` (Step 1) — never guess.
|
||||
|
||||
**Reference files:** Companion files loaded via Read directives. Fallback rules inline if unavailable.
|
||||
|
||||
@@ -62,7 +62,8 @@ Three levels -- auto-detected, always respect explicit user override:
|
||||
|
||||
1. **User prompt** — use it.
|
||||
2. **Conversation context** — recent work? Those artifacts. Scope: `focused`.
|
||||
3. **Git fallback** — run `review-scope.mjs`. It compares the branch with its base (`main`, else `master`; `--base` overrides; `base` says which it used) and adds staged, unstaged and untracked changes: `files` (status, lines), `counts`, `commits`, `mix`, `batchByRisk`. `empty: true`? Ask user. Exit 3 `no-base` (no `main` or `master`, or no such `--base`)? Rerun with `--base <trunk>`, asking the user which branch is the trunk if unclear. Exit 3 `not-a-repo`? Ask user which files to review.
|
||||
3. **Standalone, nothing named** — do not assume a target. Do a quick scan (no file reading): `review-scope.mjs`, `specs.mjs list`, recent commits. Then ask what to review (`ask_user_question`; a `choice` on the console, scope questions up front), offering only options the scan supports, each with its size: the branch's changes vs base (files, ~lines, `commits`), uncommitted changes only (when any), a spec/plan under `specs/` (when any), a named subsystem or full codebase, or specific files/folders (free text via Other). Recommend the likeliest first. Nothing found (`empty: true`, no specs)? Ask for files or a subsystem. Use the answer as the scope, then continue.
|
||||
4. **Scan details** — `review-scope.mjs` compares the branch with its base (`main`, else `master`; `--base` overrides; `base` says which it used) and adds staged, unstaged and untracked changes: `files` (status, lines), `counts`, `commits`, `mix`, `batchByRisk`. `empty: true`? Ask user. Exit 3 `no-base` (no `main` or `master`, or no such `--base`)? Rerun with `--base <trunk>`, asking the user which branch is the trunk if unclear. Exit 3 `not-a-repo`? Ask user which files to review.
|
||||
|
||||
**Classify review type** from context (auto-detect; use `ask_user_question` only if ambiguous):
|
||||
|
||||
|
||||
@@ -64,6 +64,13 @@ progress bar is the first thing someone watching a build looks at. The session
|
||||
meter counts the build's tasks from `cleared` as it rises, so keep it current,
|
||||
and start every phase (a second one in the same run too) at `"cleared": 0`.
|
||||
|
||||
`"version": 1` is for the first phase of a session only. A doc's version
|
||||
never goes back (console.md → House rules, rule 9), so a later phase in the
|
||||
same session reposts `phase` and `phasefile` at one more than the version the
|
||||
page holds, with the new phase's title and content. The same goes for
|
||||
`report` at sign-off and `review` in a mid-session review: version 1 the
|
||||
first time, then up from wherever the page has it.
|
||||
|
||||
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
|
||||
the person can read the prerequisites and task specs while you build. Re-post
|
||||
it whenever the file changes, which is every task: the checkbox write that
|
||||
@@ -111,6 +118,12 @@ printed), never into the project or into `~/.plan2code/console/` directly:
|
||||
- Do not call `wait` while building. There is nothing to collect, and the page
|
||||
holds anything the person sends until you next look.
|
||||
|
||||
A build may receive a `Subagents:` standing instruction, on `open` output or a
|
||||
`chat` check between tasks. Follow console.md → Standing instructions for
|
||||
handing independent tasks to helpers and reporting them as `helpers`. Keep the
|
||||
per-task progress posts, the checkbox writes, the chat checks and the sign-off
|
||||
with you.
|
||||
|
||||
### Quick questions between tasks
|
||||
|
||||
The person can ask a Quick question on the Ask tab at any point in a build
|
||||
@@ -195,7 +208,8 @@ only ever be offered once nothing could come of it:
|
||||
`reply` carries `Approve this phase: approved`, which is the terminal's
|
||||
`approved`. If the note that came with an approval asks for a change, treat it
|
||||
as "describe any issues": do the change first and ask again. `changes` means
|
||||
exactly what it says: address it, bump the report's version, and reopen the
|
||||
exactly what it says: address it, bump the report's version (a later phase's
|
||||
report starts above the last one's, too), and reopen the
|
||||
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
|
||||
person asking for the code review before they approve anything — see "The
|
||||
review, mid-session" below.
|
||||
|
||||
@@ -170,7 +170,7 @@ so even a kill at the worst possible moment costs you a repeat, never an answer.
|
||||
|
||||
| Exit | Meaning | What you do |
|
||||
| --- | --- | --- |
|
||||
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace). | Handle the cards (if any), the chat (if any) and any `workspace` changes, then post once (below, Quick questions and Workspace). |
|
||||
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace) and `subagents` (the helpers switch, see Standing instructions). | Handle the cards (if any), the chat (if any), any `workspace` changes and any `subagents` block, then post once (below, Quick questions, Workspace and Standing instructions). |
|
||||
| `10` | Still working. stdout has a short progress summary; `pendingWorkspace` counts workspace changes waiting for the next send. | Relay ONE line: the `message` field itself, "Waiting on your answer in the web console", followed by the `terminalLine`. Then call `wait` again. |
|
||||
| `20` | The server is gone. | `open --resume <sid>`, give them the new link, then keep waiting. |
|
||||
| `30` | They pressed Cancel. | Stop. Ask what they want to do, in the terminal. |
|
||||
@@ -647,6 +647,84 @@ for permission is not a failure; report only a read that failed after it.
|
||||
|
||||
---
|
||||
|
||||
## Standing instructions
|
||||
|
||||
On the skills that offer it (`implement`, `implement-review`, `quick-task`,
|
||||
`review`, `pathfinder`), the person can turn **helpers** (subagents) on or off
|
||||
from the top bar's Subagents button. Their pick is saved per project and per
|
||||
skill, off by default, and reaches you as a standing instruction, only when it
|
||||
changes.
|
||||
|
||||
### What arrives
|
||||
|
||||
A `subagents` field beside `reply`, and `Subagents:` lines last in `reply`,
|
||||
after the card lines, the `Quick question:` blocks and the `Workspace:` lines.
|
||||
It rides on `wait` exit `0`, `chat` exit `0` and `open` output. A setting
|
||||
change alone never ends a `wait` slice: it waits for the next send, or for
|
||||
your next `chat` check.
|
||||
|
||||
```
|
||||
Subagents: on (revision 2) — a console setting, not typed by the person.
|
||||
Hand independent work to helpers if your tools allow it; otherwise carry on alone.
|
||||
Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.
|
||||
With no way to start helpers, report one "working alone" entry for this skill run instead.
|
||||
Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.
|
||||
At most 3 helpers at once.
|
||||
```
|
||||
|
||||
beside `"subagents": { "state": "on", "revision": 2, "max": 3, "instruction": "…" }`.
|
||||
An edit while on arrives as `Subagents: on (revision 3, replaces revision 2) — …`
|
||||
with the whole block again; switching off arrives as one line:
|
||||
`Subagents: off (revision 4) — don't start new helpers for the rest of this session.`
|
||||
|
||||
It is a console setting, not something the person typed. It never answers a
|
||||
card, and it is never recorded under `specs/`.
|
||||
|
||||
### Obeying it
|
||||
|
||||
- **On:** hand independent work to helpers if your tools allow it, at most
|
||||
`max` at once, following the instruction lines. `max` is advisory: your
|
||||
harness's own limit still applies.
|
||||
- **A higher revision replaces a lower one.** Follow the latest block only.
|
||||
- **Off:** start no new helpers for the rest of the session. Let running ones
|
||||
finish and report them.
|
||||
- **Nothing arrives:** keep doing what the skill says.
|
||||
- **Scope is the skill run it arrived in.** After a dashboard launch, no block
|
||||
means the switch is off for this skill, even if an earlier skill in the same
|
||||
conversation was told "on": `open` starts the count again, and a launch with
|
||||
the switch off sends nothing.
|
||||
|
||||
### Reporting helpers
|
||||
|
||||
Post them, at your check-ins, so the page's Subagents tab can show them. The
|
||||
page never hears from a helper directly:
|
||||
|
||||
```jsonc
|
||||
{ "helpers": [
|
||||
{ "id": "h1", "title": "Read the store helpers", "ask": "Find every caller of readSubagentSetting.", "state": "running" },
|
||||
{ "id": "h2", "title": "Check the tests", "ask": "Run the subagents tests and report failures.", "state": "done", "result": "All 9 pass." }
|
||||
] }
|
||||
```
|
||||
|
||||
- `id` (non-empty), `title` (at most 80 characters), `ask` (at most 400) and
|
||||
`state` (`running`, `done` or `failed`) are required; `result` (at most 200)
|
||||
is the one line you add once a helper ends.
|
||||
- Merged by `id`: post a helper again with its new `state` and `result` and it
|
||||
updates in place. `"helpers": null` clears the list. A dashboard hop clears it
|
||||
too; a resume into the same skill keeps it.
|
||||
- One post per change worth seeing, not a stream.
|
||||
- Questions for the person stay with you, never with a helper: most harnesses
|
||||
give helpers no way to ask, and an answer only reaches the agent holding the
|
||||
session.
|
||||
- **No way to start helpers?** Post one `{ "id": "alone", "alone": true }`
|
||||
entry for the skill run instead. The tab then says you are working alone.
|
||||
- **Pathfinder:** research questions always use helpers and are always
|
||||
reported, whatever the switch says. The switch governs recon, sketches and
|
||||
lookups beside the conversation.
|
||||
- Helpers add no session meter points. Post no `run` for them.
|
||||
|
||||
---
|
||||
|
||||
## Launches (dashboard only)
|
||||
|
||||
A `dashboard` session is not a conversation: the page draws a menu of every
|
||||
@@ -763,7 +841,10 @@ commands follow the pipeline: the sign-off's is
|
||||
|
||||
### Review (`review`)
|
||||
|
||||
Scope questions up front, then the findings report as a doc (`id: "report"`),
|
||||
Scope questions up front — run standalone with nothing named, the first is
|
||||
a `choice`, "What should I review?", built from a quick scan (branch changes,
|
||||
uncommitted changes, specs, files you name; each option with its size),
|
||||
never an assumed target; a build's review skips it (`building.md`). Then the findings report as a doc (`id: "report"`),
|
||||
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
|
||||
id, carrying `"doc": "report"` so the card links straight to the findings.
|
||||
Settle that item (`"status": "answered"` plus the `answer` they sent) in
|
||||
@@ -797,6 +878,8 @@ that is what the person is there to download. The finish carries no
|
||||
- Chart Step 8's research subagents must all report back before the
|
||||
finish (Finishing → Nothing of yours may still be running); the finish
|
||||
body then names what each one found.
|
||||
- Report every research subagent as a helper, whatever the Subagents switch
|
||||
says (Standing instructions → Reporting helpers).
|
||||
- At every session end, post `finish` (headline, `body`, and Form A's command as
|
||||
`command`) BEFORE `stop`. Someone who spent the session in the browser never
|
||||
sees the Trail Footer, and without this their last screen promises a question
|
||||
@@ -1146,6 +1229,16 @@ A patch that breaks one of these is rejected with exit `3` and a message:
|
||||
(Session meter) and a non-empty `id`; a `folderIssue` needs non-empty
|
||||
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
|
||||
and 5 cover `reason` and `hint`.
|
||||
8. **`helpers` entries are well formed** (Standing instructions → Reporting
|
||||
helpers): an array of objects, each with a unique `id`, a `title`, an `ask`
|
||||
and a known `state` within their limits, plus at most one `alone` entry.
|
||||
Rules 4 and 5 cover `title`, `ask` and `result`.
|
||||
9. **A doc's `version` never goes back.** Sending a known doc a lower
|
||||
`version` than the page holds is refused: it is almost always a stale or
|
||||
copied payload. The same version again is fine, and a dashboard hop starts
|
||||
every doc fresh. Anything else reusing a doc id in the same session (a
|
||||
build's second phase, a second report or review) continues from the
|
||||
version the page holds.
|
||||
|
||||
These are workflow rules you already follow. The server just makes them checkable.
|
||||
|
||||
@@ -1167,7 +1260,9 @@ cannot see them, and the moment it says the session ended, the person is
|
||||
free to close that terminal and kill them mid-write. While you wait, post
|
||||
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
|
||||
and update the count as each returns. Never write a `finish.body` that says
|
||||
work "is running in the background" or "will finish on its own".
|
||||
work "is running in the background" or "will finish on its own". Mark every
|
||||
reported helper `done` or `failed` before the finish, so the Subagents tab
|
||||
never ends on a row still running.
|
||||
|
||||
### 1. Post the finish
|
||||
|
||||
|
||||
@@ -64,6 +64,8 @@ import {
|
||||
readChat,
|
||||
readJson,
|
||||
readLedger,
|
||||
readSubagentCursor,
|
||||
readSubagentSetting,
|
||||
readWorkspace,
|
||||
reapHandles,
|
||||
rememberedWorkspace,
|
||||
@@ -71,6 +73,7 @@ import {
|
||||
removeScratch,
|
||||
removeSessions,
|
||||
repoRoots,
|
||||
resetSubagentCursor,
|
||||
scanProject,
|
||||
SESSION_MAX_AGE_MS,
|
||||
sessionDir,
|
||||
@@ -88,9 +91,11 @@ import {
|
||||
workspaceForAgent,
|
||||
writeCursor,
|
||||
writeJsonAtomic,
|
||||
writeSubagentCursor,
|
||||
writeWorkspaceCursor,
|
||||
} from "./lib.mjs";
|
||||
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
|
||||
import { blockFor, offered } from "./public/subagents.js";
|
||||
import { changeLine } from "./public/workspace.js";
|
||||
|
||||
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
|
||||
@@ -310,7 +315,11 @@ async function cmdOpen() {
|
||||
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
|
||||
}
|
||||
state = written.state;
|
||||
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
|
||||
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] });
|
||||
// A new agent conversation has been told nothing yet (FR-6).
|
||||
try {
|
||||
resetSubagentCursor(dir);
|
||||
} catch {}
|
||||
trace("open: state written");
|
||||
|
||||
// Dashboard launches are recorded too (they score nothing), so the folder
|
||||
@@ -337,9 +346,18 @@ async function cmdOpen() {
|
||||
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
|
||||
};
|
||||
|
||||
// A standing instruction the new agent is owed, as `subagents` and a
|
||||
// `reply` holding only its lines; neither key when nothing is owed.
|
||||
const subagentsOwed = () => {
|
||||
awaitSubagentSync(dir, state.workflow);
|
||||
const [out, cursor] = withSubagents(dir, { reply: "" });
|
||||
return [out.subagents ? out : {}, cursor];
|
||||
};
|
||||
|
||||
// Reuse a live server if one is already serving this session.
|
||||
if (existing && (await reusable)) {
|
||||
if (!args["no-open"]) openBrowser(existing.url);
|
||||
const [owed, subCursor] = subagentsOwed();
|
||||
print({
|
||||
ok: true,
|
||||
sid,
|
||||
@@ -349,9 +367,11 @@ async function cmdOpen() {
|
||||
pendingResult: carried,
|
||||
terminalLine: terminalLine(existing.url),
|
||||
workspace,
|
||||
...owed,
|
||||
...swept,
|
||||
...remoteWarning(),
|
||||
});
|
||||
advanceSubagents(dir, subCursor);
|
||||
sweep();
|
||||
return;
|
||||
}
|
||||
@@ -384,6 +404,7 @@ async function cmdOpen() {
|
||||
const notes = [];
|
||||
if (remote.note) notes.push(remote.note);
|
||||
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
|
||||
const [owed, subCursor] = subagentsOwed();
|
||||
print({
|
||||
ok: true,
|
||||
sid,
|
||||
@@ -394,10 +415,12 @@ async function cmdOpen() {
|
||||
pendingResult: carried,
|
||||
terminalLine: terminalLine(handle.url),
|
||||
workspace,
|
||||
...owed,
|
||||
...swept,
|
||||
...(remote.remote ? { remote: remote.remote } : {}),
|
||||
...(notes.length ? { note: notes.join(" ") } : {}),
|
||||
});
|
||||
advanceSubagents(dir, subCursor);
|
||||
// After the print, never before it: the page and the link wait for nothing.
|
||||
sweep();
|
||||
}
|
||||
@@ -774,7 +797,7 @@ function serverGone(sid) {
|
||||
|
||||
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
|
||||
function deliverChat(dir, sid, entries, url) {
|
||||
const [out, changes] = withWorkspace(dir, {
|
||||
const [withWs, changes] = withWorkspace(dir, {
|
||||
type: "chat",
|
||||
at: nowIso(),
|
||||
sid,
|
||||
@@ -782,9 +805,11 @@ function deliverChat(dir, sid, entries, url) {
|
||||
chat: entries,
|
||||
reply: chatReplyLines(entries),
|
||||
});
|
||||
const [out, subCursor] = withSubagents(dir, withWs);
|
||||
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
||||
advanceCursor(dir, entries);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = 0;
|
||||
}
|
||||
|
||||
@@ -806,6 +831,52 @@ function advanceWorkspace(dir, changes) {
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// The server rewrites the session's setting for a new workflow only once its
|
||||
// watcher sees the state `open` just wrote, so a launch or hop that read the
|
||||
// file at once would find the old workflow's and owe the agent nothing until
|
||||
// its next pickup. Give the server a moment to catch up instead, never
|
||||
// writing the file ourselves (FR-7). A session with no setting file at all is
|
||||
// an older server, which never writes one: a short look, not the full wait.
|
||||
const SUBAGENT_SYNC_WAIT_MS = 1500;
|
||||
const SUBAGENT_SYNC_MISSING_MS = 250;
|
||||
function awaitSubagentSync(dir, workflow) {
|
||||
if (!offered(workflow)) return;
|
||||
const start = Date.now();
|
||||
for (;;) {
|
||||
const setting = readSubagentSetting(dir);
|
||||
if (setting && setting.workflow === workflow) return;
|
||||
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
|
||||
if (Date.now() - start >= budget) return;
|
||||
sleepSync(25);
|
||||
}
|
||||
}
|
||||
|
||||
// The Subagents switch the agent is owed, added to what it is about to read:
|
||||
// the setting as `subagents`, and its lines last in `reply`, after card lines,
|
||||
// Quick questions and Workspace lines (FR-9). Read from the session's own
|
||||
// setting file only, which only the server writes (FR-7). A setting for
|
||||
// another workflow is the server not having caught up with a hop yet: it
|
||||
// rides on the next pickup instead.
|
||||
function withSubagents(dir, out) {
|
||||
const setting = readSubagentSetting(dir);
|
||||
if (!setting) return [out, null];
|
||||
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
|
||||
if (setting.workflow !== workflow) return [out, null];
|
||||
const block = blockFor(setting, readSubagentCursor(dir));
|
||||
if (!block) return [out, null];
|
||||
const reply = [out.reply, ...block.lines].filter(Boolean).join("\n");
|
||||
return [{ ...out, subagents: block.field, reply }, block.cursor];
|
||||
}
|
||||
|
||||
// After the print, like advanceWorkspace(): a kill in between repeats the
|
||||
// block at the next pickup, never loses it.
|
||||
function advanceSubagents(dir, cursor) {
|
||||
if (!cursor) return;
|
||||
try {
|
||||
writeSubagentCursor(dir, cursor);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Print first, then this, exactly as consume() stamps a result: a kill in
|
||||
// between can only hand the same chat over again, and collectChat() drops
|
||||
// anything that already has a reply.
|
||||
@@ -832,15 +903,17 @@ async function cmdChat() {
|
||||
}
|
||||
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
|
||||
const changes = pendingWorkspaceChanges(dir);
|
||||
if (!entries.length && !changes.length) {
|
||||
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
||||
const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply });
|
||||
if (!entries.length && !changes.length && !subCursor) {
|
||||
print({ chat: [] });
|
||||
process.exitCode = 10;
|
||||
return;
|
||||
}
|
||||
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
||||
print({ chat: entries, workspace: changes, reply, terminalLine: terminalLine(handle.url) });
|
||||
print({ ...out, terminalLine: terminalLine(handle.url) });
|
||||
advanceCursor(dir, entries);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = 0;
|
||||
}
|
||||
|
||||
@@ -865,7 +938,8 @@ function consume(dir, resultPath, result, url, chat = []) {
|
||||
// never on result.json itself.
|
||||
const withChat = { ...collected, chat };
|
||||
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
|
||||
const [out, changes] = withWorkspace(dir, withChat);
|
||||
const [withWs, changes] = withWorkspace(dir, withChat);
|
||||
const [out, subCursor] = withSubagents(dir, withWs);
|
||||
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
|
||||
try {
|
||||
writeJsonAtomic(resultPath, collected);
|
||||
@@ -874,6 +948,7 @@ function consume(dir, resultPath, result, url, chat = []) {
|
||||
ledgerAnswers(dir, result);
|
||||
advanceCursor(dir, chat);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = result.type === "cancel" ? 30 : 0;
|
||||
}
|
||||
|
||||
@@ -986,12 +1061,18 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
path, description?, original? }], missing? }, the folders this
|
||||
console session reads as context, addressed as @name. The list is
|
||||
remembered per folder and spec in workspaces.json beside looks.json.
|
||||
May also print subagents: { state, revision, max, instruction } and
|
||||
a reply holding only its "Subagents: ..." lines, when a standing
|
||||
instruction (the page's Subagents switch) is owed to you.
|
||||
post --session <sid> --file <patch.json>
|
||||
Merge a patch into the session. Prints terminalLine while the
|
||||
server is live. Exit 3 = rejected; stderr says why. A patch may
|
||||
carry run: { event, id, tasks? } (session meter points) and folderIssue:
|
||||
{ name, reason, hint? } (a workspace folder you could not read);
|
||||
both go to the ledger, never into the state.
|
||||
both go to the ledger, never into the state. A patch may also
|
||||
carry helpers: [{ id, title, ask, state, result? }] or one
|
||||
{ id: "alone", alone: true }, merged by id, for the Subagents tab
|
||||
(see console.md → Standing instructions).
|
||||
wait --session <sid> [--seconds <N>]
|
||||
A bounded wait slice, sized below your shell timeout. Exit 0 = the
|
||||
result is on stdout, 10 = still waiting ("Waiting on your answer
|
||||
@@ -1002,10 +1083,14 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
"workspace" (changes since you last heard, each once, with a
|
||||
"Workspace: ..." line in reply); exit 10 counts them as
|
||||
pendingWorkspace, and a change alone never ends a slice.
|
||||
Exit 0 may also carry "subagents" (a console setting, not typed
|
||||
by the person, with its "Subagents: ..." lines last in reply); a
|
||||
setting change alone never ends a slice either.
|
||||
chat --session <sid>
|
||||
Collect Quick questions and workspace changes now, never waiting,
|
||||
never touching card sends. Exit 0 = { chat, workspace, reply,
|
||||
terminalLine }, 10 = none, 20 = server gone.
|
||||
Collect Quick questions, workspace changes and a Subagents
|
||||
setting change now, never waiting, never touching card sends.
|
||||
Exit 0 = { chat, workspace, subagents?, reply, terminalLine },
|
||||
10 = none, 20 = server gone.
|
||||
terminalLine is "→ Look at the web console: <url>": end your terminal
|
||||
messages with it during a console session.
|
||||
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
|
||||
|
||||
@@ -25,6 +25,7 @@ import { fileURLToPath } from "node:url";
|
||||
import { CHAT_LIMIT } from "./public/chat.js";
|
||||
import { DOC_TYPES } from "./public/answers.js";
|
||||
import { defaultName } from "./public/workspace.js";
|
||||
import { checkHelpers, cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
||||
|
||||
export const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
export const PUBLIC_DIR = path.join(HERE, "public");
|
||||
@@ -491,9 +492,16 @@ export async function removeSessions(sessionsDir, sids) {
|
||||
}
|
||||
|
||||
// The console folder's own files that no sweep may ever remove: the person's
|
||||
// looks, the folders remembered per project and spec, the pointer to this
|
||||
// console's directory, and the cached release check.
|
||||
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir", "update-check.json"]);
|
||||
// looks, the folders remembered per project and spec, the Subagents switch
|
||||
// saved per project and workflow, the pointer to this console's directory,
|
||||
// and the cached release check.
|
||||
export const PROTECTED_CONSOLE_FILES = new Set([
|
||||
"looks.json",
|
||||
"workspaces.json",
|
||||
"subagents.json",
|
||||
"console-dir",
|
||||
"update-check.json",
|
||||
]);
|
||||
|
||||
function isScratchName(name) {
|
||||
return (
|
||||
@@ -1142,6 +1150,19 @@ const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
|
||||
// Blocks merge by id like docs do, so a patch that only settles a block's
|
||||
// state keeps its text. Blocks left out of the patch stay as they are.
|
||||
function mergeDocs(current, patchList) {
|
||||
// A doc's version only moves forward. One going back is a stale or copied
|
||||
// payload (last phase's progress script, say), and the page would quietly
|
||||
// show the old content under the new run's name.
|
||||
for (const entry of patchList) {
|
||||
if (!isPlainObject(entry) || typeof entry.version !== "number") continue;
|
||||
const prev = (current || []).find((d) => d && d.id === entry.id);
|
||||
if (prev && typeof prev.version === "number" && entry.version < prev.version) {
|
||||
throw new Error(
|
||||
`doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` +
|
||||
"Versions only go up: bump it, and check the payload is the current one."
|
||||
);
|
||||
}
|
||||
}
|
||||
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
|
||||
for (const entry of patchList) {
|
||||
if (!Array.isArray(entry.blocks)) continue;
|
||||
@@ -1184,6 +1205,13 @@ export function applyPatch(state, patch) {
|
||||
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
|
||||
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
|
||||
break;
|
||||
case "helpers":
|
||||
// The agent's report of its helpers, for the page's Subagents tab.
|
||||
// Only `post` writes it; the server's /submit never touches it.
|
||||
if (!Array.isArray(v)) throw new Error('"helpers" must be an array');
|
||||
if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }');
|
||||
next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers");
|
||||
break;
|
||||
case "docs":
|
||||
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
|
||||
next.docs = mergeDocs(next.docs, v);
|
||||
@@ -1478,6 +1506,20 @@ export function validate(state) {
|
||||
JSON.stringify(state.menu || {});
|
||||
problems.push(...proseProblems(prose));
|
||||
|
||||
// The agent's report of its helpers: the shape the page draws from
|
||||
// (subagents.js), then the same prose scan as everything else it writes.
|
||||
if (state.helpers != null) {
|
||||
problems.push(...checkHelpers(state.helpers));
|
||||
for (const helper of Array.isArray(state.helpers) ? state.helpers : []) {
|
||||
if (!isPlainObject(helper)) continue;
|
||||
for (const field of ["title", "ask", "result"]) {
|
||||
if (typeof helper[field] === "string") {
|
||||
problems.push(...proseProblems(helper[field], `helper "${helper.id}" ${field}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
@@ -1507,7 +1549,8 @@ export function blankState({ sid, workflow, title, project, specDir }) {
|
||||
* A resume that passes through the dashboard (a finished skill going back to
|
||||
* it, or a launch from its menu) is a new skill taking the page over, so it
|
||||
* starts from a blank page: the last skill's questions, sections, docs,
|
||||
* headline and ending are its record on disk, not the next skill's opening.
|
||||
* helpers, headline and ending are its record on disk, not the next skill's
|
||||
* opening.
|
||||
* Only the session's identity carries across. `workspace.json`,
|
||||
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
|
||||
* and the meter outlive every hop.
|
||||
@@ -1534,6 +1577,8 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
|
||||
// workspace.json the server. Folders, version, change log, missing, remote.
|
||||
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
|
||||
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
|
||||
// subagents-setting.json the server. The Subagents switch for this session, with its revision.
|
||||
// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent.
|
||||
export const CHAT_FILE = "chat.ndjson";
|
||||
export const CHAT_CURSOR_FILE = "chat-cursor.json";
|
||||
export const WORKSPACE_FILE = "workspace.json";
|
||||
@@ -1989,6 +2034,98 @@ export function pendingWorkspaceChanges(dir) {
|
||||
return (readWorkspace(dir)?.changes || []).filter((c) => c.version > cursor);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ the Subagents switch */
|
||||
|
||||
// The person's Subagents switch, remembered per project folder and workflow:
|
||||
//
|
||||
// { "<folded project path>": { "<workflow>": { on, instruction, max } } }
|
||||
//
|
||||
// Keyed with foldKey(), as workspaces.json is. `instruction: null` is the
|
||||
// workflow's shipped default.
|
||||
export const SUBAGENTS_FILE = path.join(HOME_DIR, "subagents.json");
|
||||
const SUBAGENTS_LOCK = "subagents.json.lock";
|
||||
|
||||
function readSubagentStore() {
|
||||
const saved = readJson(SUBAGENTS_FILE, null);
|
||||
return saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {};
|
||||
}
|
||||
|
||||
// The saved `{ on, instruction, max }` for this folder and workflow, or the
|
||||
// default's when nothing (or something malformed) is saved.
|
||||
export function subagentStoreEntry(worktree, workflow) {
|
||||
const { on, instruction, max } = defaultSetting(workflow);
|
||||
const project = offered(workflow) ? readSubagentStore()[foldKey(worktree)] : null;
|
||||
const saved = project && typeof project === "object" ? cleanSetting(project[workflow]) : null;
|
||||
return saved && !saved.error ? saved : { on, instruction, max };
|
||||
}
|
||||
|
||||
// Single-writer rule: only server.mjs may call this.
|
||||
export function saveSubagentStoreEntry(worktree, workflow, value) {
|
||||
ensureDir(path.dirname(SUBAGENTS_FILE));
|
||||
withStateLock(
|
||||
path.dirname(SUBAGENTS_FILE),
|
||||
() => {
|
||||
const store = readSubagentStore();
|
||||
const key = foldKey(worktree);
|
||||
const project = store[key] && typeof store[key] === "object" ? store[key] : {};
|
||||
store[key] = { ...project, [workflow]: { on: value.on, instruction: value.instruction, max: value.max } };
|
||||
writeJsonAtomic(SUBAGENTS_FILE, store);
|
||||
},
|
||||
SUBAGENTS_LOCK
|
||||
);
|
||||
}
|
||||
|
||||
export const SUBAGENTS_SETTING_FILE = "subagents-setting.json";
|
||||
|
||||
const isCount = (n) => Number.isInteger(n) && n >= 0;
|
||||
|
||||
// This session's switch, `{ workflow, on, instruction, max, revision }`, or
|
||||
// null when there is none or it is malformed.
|
||||
export function readSubagentSetting(dir) {
|
||||
const s = readJson(path.join(dir, SUBAGENTS_SETTING_FILE), null);
|
||||
if (!s || typeof s !== "object") return null;
|
||||
if (typeof s.workflow !== "string" || typeof s.on !== "boolean" || !Number.isInteger(s.max) || !isCount(s.revision)) return null;
|
||||
return s;
|
||||
}
|
||||
|
||||
// Single-writer rule: only server.mjs may call this. The revision never goes
|
||||
// backwards within a session.
|
||||
export function writeSubagentSetting(dir, setting) {
|
||||
const previous = readSubagentSetting(dir);
|
||||
const revision = Math.max(previous ? previous.revision : 0, setting.revision);
|
||||
return writeJsonAtomic(path.join(dir, SUBAGENTS_SETTING_FILE), { ...setting, revision });
|
||||
}
|
||||
|
||||
export const SUBAGENTS_CURSOR_FILE = "subagents-cursor.json";
|
||||
const CURSOR_STATES = new Set(["none", "on", "off"]);
|
||||
|
||||
// What the agent was last told: `{ revision, state }`.
|
||||
export function readSubagentCursor(dir) {
|
||||
const saved = readJson(path.join(dir, SUBAGENTS_CURSOR_FILE), null);
|
||||
if (!saved || !isCount(saved.revision) || !CURSOR_STATES.has(saved.state)) return { revision: 0, state: "none" };
|
||||
return { revision: saved.revision, state: saved.state };
|
||||
}
|
||||
|
||||
// Single-writer rule: only console.mjs may call this. Never backwards, like
|
||||
// writeWorkspaceCursor(): a killed `wait` may repeat a change, never skip one.
|
||||
export function writeSubagentCursor(dir, cursor) {
|
||||
const old = readSubagentCursor(dir);
|
||||
const next = cursor.revision < old.revision ? old : { revision: cursor.revision, state: cursor.state };
|
||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), next);
|
||||
}
|
||||
|
||||
// The one place the cursor may go back: `open`, which starts a fresh agent.
|
||||
export function resetSubagentCursor(dir) {
|
||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), { revision: 0, state: "none" });
|
||||
}
|
||||
|
||||
// The `caps` of the last `open` event: what the agent's console copy can do.
|
||||
export function latestOpenCaps(dir) {
|
||||
const opens = readJsonLines(path.join(dir, "events.ndjson")).filter((e) => e.type === "open");
|
||||
const last = opens[opens.length - 1];
|
||||
return last && Array.isArray(last.caps) ? last.caps : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Flag the case where the link cannot be opened by the person it is for.
|
||||
*
|
||||
|
||||
@@ -208,6 +208,26 @@ body {
|
||||
.stop-btn:hover:not(:disabled) { color: var(--warn); border-color: var(--warn); }
|
||||
.brief-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
||||
|
||||
/* Subagents: an orchestrator and its helpers. Unlit is a hollow outline in
|
||||
the quiet ink; lit fills the nodes with the highlight color. */
|
||||
.subagents-btn { border-color: var(--rule-2); color: var(--ink-2); display: inline-flex; align-items: center; justify-content: center; }
|
||||
.btn.subagents-btn { padding: 0 6px; align-self: stretch; }
|
||||
.subagents-btn[hidden] { display: none; }
|
||||
.subagents-btn svg { width: 16px; height: 16px; display: block; }
|
||||
.subagents-btn .sa-link { fill: none; stroke: var(--ink-2); stroke-width: 1.2; stroke-linecap: round; }
|
||||
.subagents-btn .sa-hub { fill: none; stroke: var(--ink-2); stroke-width: 1.4; }
|
||||
.subagents-btn .sa-node { fill: none; stroke: var(--ink-2); stroke-width: 1.2; }
|
||||
.subagents-btn[aria-pressed="true"] .sa-hub,
|
||||
.subagents-btn[aria-pressed="true"] .sa-node { fill: var(--accent); stroke: var(--accent); }
|
||||
.subagents-btn[aria-pressed="true"] .sa-link { stroke: var(--accent); }
|
||||
.subagents-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
||||
.subagents-btn:hover:not(:disabled) .sa-link,
|
||||
.subagents-btn:hover:not(:disabled) .sa-hub,
|
||||
.subagents-btn:hover:not(:disabled) .sa-node { stroke: var(--accent); }
|
||||
.subagents-btn:disabled .sa-link,
|
||||
.subagents-btn:disabled .sa-hub,
|
||||
.subagents-btn:disabled .sa-node { stroke: var(--ink-3); fill: none; }
|
||||
|
||||
.ident { display: flex; align-items: baseline; gap: 12px; min-width: 0; }
|
||||
|
||||
/* The session meter: a ring that fills with the points and a few words, in
|
||||
@@ -1430,6 +1450,30 @@ h1 {
|
||||
.pill.done { background: var(--ok-soft); color: var(--ok); }
|
||||
.pill.staged { background: var(--stage-soft); color: var(--stage); }
|
||||
|
||||
/* The Subagents tab: one row per reported helper, newest state in a pill. */
|
||||
.sa-card h2 { margin: 0 0 6px; }
|
||||
.sa-card > .help { margin: 0 0 16px; }
|
||||
.sa-alone { margin: 0; color: var(--ink-2); }
|
||||
.sa-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; }
|
||||
.sa-row { border: 1px solid var(--rule); border-radius: 8px; background: var(--panel-2); padding: 12px 14px; }
|
||||
.sa-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
||||
.sa-title { min-width: 0; overflow-wrap: anywhere; }
|
||||
.sa-ask {
|
||||
margin: 4px 0 0; color: var(--ink-2); font-size: 13.5px;
|
||||
display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden;
|
||||
}
|
||||
.sa-result { margin: 8px 0 0; padding-top: 8px; border-top: 1px solid var(--rule); font-size: 13.5px; }
|
||||
.sa-pill { display: inline-flex; align-items: center; gap: 6px; flex: none; }
|
||||
.sa-pill.is-running { background: var(--accent-soft); color: var(--accent); border-color: var(--accent-line); }
|
||||
.sa-pill.is-done { background: var(--ok-soft); color: var(--ok); }
|
||||
.sa-pill.is-failed { background: var(--warn-soft); color: var(--warn); }
|
||||
.sa-pill .spinner.tiny { width: 10px; height: 10px; }
|
||||
/* The dialog's number box, themed like the page's other inputs. */
|
||||
.subagents input[type="number"] {
|
||||
width: 5em; font: inherit; color: var(--ink); background: var(--panel-2);
|
||||
border: 1px solid var(--rule-2); border-radius: 6px; padding: 4px 8px;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ settled answer */
|
||||
|
||||
.answered {
|
||||
@@ -1971,6 +2015,8 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
|
||||
cursor: pointer;
|
||||
}
|
||||
.footer-where:hover { text-decoration: underline; }
|
||||
/* The project name, in the person's highlight color. */
|
||||
.where-project { color: var(--accent); font-weight: 600; }
|
||||
/* A folder is missing or the agent could not read one: the dialog says which. */
|
||||
.where-alert {
|
||||
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
|
||||
|
||||
@@ -103,6 +103,15 @@ import { FOOTER_TIERS, footerLabel, nameProblem } from "./workspace.js";
|
||||
import { RED_BANNER } from "./meter.js";
|
||||
import { applyMention, matchNames, mentionAt } from "./mentions.js";
|
||||
import { faviconState, setFavicon } from "./favicon.js";
|
||||
import {
|
||||
CHECKIN_LINE,
|
||||
PATHFINDER_RESEARCH_LINE,
|
||||
defaultInstruction,
|
||||
helperRows,
|
||||
showSwitch,
|
||||
showTab,
|
||||
switchLabel,
|
||||
} from "./subagents.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
@@ -530,6 +539,9 @@ let meterFrame = null;
|
||||
// The frame's update ({ installed, latest }), present only when a newer
|
||||
// release is out; null otherwise.
|
||||
let updateFrame = null;
|
||||
// The frame's Subagents switch ({ offered, supported, on, instruction, max,
|
||||
// revision }), or null before a server that sends it.
|
||||
let subagentsFrame = null;
|
||||
let chatDot = false;
|
||||
let chatSending = false;
|
||||
let chatResetting = false;
|
||||
@@ -880,6 +892,8 @@ function adopt(body) {
|
||||
if (body.meter) meterFrame = body.meter;
|
||||
// Always replaced: an absent key means no update.
|
||||
updateFrame = body.update || null;
|
||||
// Always replaced too: an older server sends none, and then there is no switch.
|
||||
subagentsFrame = body.subagents || null;
|
||||
lastContact = Date.now();
|
||||
if (gone) {
|
||||
gone = false;
|
||||
@@ -1301,6 +1315,7 @@ function render() {
|
||||
renderChrome();
|
||||
renderStatus();
|
||||
renderBriefButton();
|
||||
renderSubagentsButton();
|
||||
renderStopButton();
|
||||
renderHomeButton();
|
||||
tabAdded = renderViews();
|
||||
@@ -1566,7 +1581,7 @@ function renderChrome() {
|
||||
renderMeter();
|
||||
$("title").textContent = S.title || "Session";
|
||||
$("badge").textContent = workflowLabel(S.workflow);
|
||||
document.title = (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
|
||||
renderTabTitle();
|
||||
|
||||
const h = S.headline || {};
|
||||
// On a finished session an open item is frozen: the send on it counts as
|
||||
@@ -1835,6 +1850,69 @@ function renderBriefButton() {
|
||||
if (offer) btn.disabled = gone || pendingResult;
|
||||
}
|
||||
|
||||
// Shown only where the skill opts in and the agent's console copy can deliver
|
||||
// it. Lit while helpers are on; a click opens the dialog, never toggles.
|
||||
function renderSubagentsButton() {
|
||||
const btn = $("btn-subagents");
|
||||
const offer = showSwitch(subagentsFrame);
|
||||
btn.hidden = !offer;
|
||||
if (!offer) return;
|
||||
const label = switchLabel(subagentsFrame);
|
||||
btn.setAttribute("aria-pressed", String(Boolean(subagentsFrame.on)));
|
||||
btn.title = label;
|
||||
btn.setAttribute("aria-label", label);
|
||||
btn.disabled = gone;
|
||||
}
|
||||
|
||||
// The Subagents dialog, filled from the frame each time it opens. A null
|
||||
// instruction is the shipped default, shown as its text so it can be edited.
|
||||
function openSubagents() {
|
||||
if (!showSwitch(subagentsFrame)) return;
|
||||
const on = Boolean(subagentsFrame.on);
|
||||
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) {
|
||||
radio.checked = radio.value === (on ? "on" : "off");
|
||||
}
|
||||
$("subagents-instruction").value = subagentsFrame.instruction ?? defaultInstruction(S.workflow);
|
||||
$("subagents-max").value = String(subagentsFrame.max);
|
||||
$("subagents-checkin").textContent = CHECKIN_LINE;
|
||||
const research = $("subagents-research");
|
||||
research.textContent = PATHFINDER_RESEARCH_LINE;
|
||||
research.hidden = S.workflow !== "pathfinder";
|
||||
$("subagents-status").textContent = "";
|
||||
$("subagents-save").disabled = false;
|
||||
$("subagents-modal").showModal();
|
||||
const checked = document.querySelector('input[name="subagents-on"]:checked');
|
||||
if (checked) checked.focus();
|
||||
}
|
||||
|
||||
const SUBAGENTS_ERRORS = {
|
||||
max: "Pick a number from 1 to 20.",
|
||||
"too-long": "The instruction is over 2,000 characters.",
|
||||
"not-offered": "This skill doesn't use helpers.",
|
||||
bad: "That didn't save. Try again.",
|
||||
};
|
||||
const SUBAGENTS_LOST = "Lost contact with Plan2Code. Try again once it's back.";
|
||||
|
||||
async function saveSubagents() {
|
||||
const save = $("subagents-save");
|
||||
const status = $("subagents-status");
|
||||
const picked = document.querySelector('input[name="subagents-on"]:checked');
|
||||
const text = $("subagents-instruction").value.trim();
|
||||
// The shipped default is stored as null, so a later release's wording
|
||||
// reaches everyone who never changed it.
|
||||
const instruction = text === defaultInstruction(S.workflow) ? null : text;
|
||||
const body = { on: Boolean(picked && picked.value === "on"), instruction, max: Number($("subagents-max").value) };
|
||||
save.disabled = true;
|
||||
status.textContent = "";
|
||||
const res = await postJson("/subagents", body);
|
||||
save.disabled = false;
|
||||
// The next state frame redraws the button.
|
||||
if (res.status === 200) return $("subagents-modal").close();
|
||||
if (res.status === 400) status.textContent = SUBAGENTS_ERRORS[res.body && res.body.error] || SUBAGENTS_ERRORS.bad;
|
||||
else if (res.status === 403 || res.status === 0) status.textContent = SUBAGENTS_LOST;
|
||||
else status.textContent = SUBAGENTS_ERRORS.bad;
|
||||
}
|
||||
|
||||
function renderViews() {
|
||||
const nav = $("views");
|
||||
nav.replaceChildren();
|
||||
@@ -1850,6 +1928,14 @@ function renderViews() {
|
||||
if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 });
|
||||
else if (view === "overview") view = "questions";
|
||||
for (const d of docs()) tabs.push({ id: "doc:" + d.id, label: d.title || "Document", count: 0 });
|
||||
// The helpers the agent reported, from the first one on; cleared by a
|
||||
// dashboard hop, which sends the person home like the Overview tab does.
|
||||
if (showTab(subagentsFrame, S.helpers)) {
|
||||
// From the rows the tab draws, so the badge never counts helpers the
|
||||
// working-alone note hides.
|
||||
const running = helperRows(S.helpers).rows.filter((r) => r.state === "running").length;
|
||||
tabs.push({ id: "subagents", label: "Subagents", count: running });
|
||||
} else if (view === "subagents") view = "questions";
|
||||
// Always last, on every workflow and after a finish: the Quick question chat.
|
||||
// The ring left of "Ask" shows exactly when the conversation's own ring does:
|
||||
// a question the agent picked up and has not answered yet.
|
||||
@@ -2130,6 +2216,7 @@ function paintMain(main) {
|
||||
if (view.startsWith("doc:")) return renderDoc(main, view.slice(4));
|
||||
if (view === "overview") return renderOverview(main);
|
||||
if (view === "ask") return renderAsk(main);
|
||||
if (view === "subagents") return renderSubagents(main);
|
||||
|
||||
// The session's own page, reached from the PAUSED / SESSION ENDED item at
|
||||
// the top of the rail. The hand-off lives here alone now, rather than
|
||||
@@ -4774,6 +4861,42 @@ function renderOverview(main) {
|
||||
main.appendChild(box);
|
||||
}
|
||||
|
||||
// The helpers the agent reported, as it last posted them. Everything here is
|
||||
// the agent's text, so it goes in as text, never as markup.
|
||||
function renderSubagents(main) {
|
||||
const card = el("section", "card sa-card");
|
||||
card.appendChild(el("h2", null, "Subagents"));
|
||||
card.appendChild(el("p", "help", CHECKIN_LINE));
|
||||
const { alone, rows } = helperRows(S.helpers);
|
||||
if (alone) {
|
||||
card.appendChild(
|
||||
el("p", "sa-alone", "Working alone: your agent has no way to start helpers here, so it is doing this skill's work itself.")
|
||||
);
|
||||
main.appendChild(card);
|
||||
return;
|
||||
}
|
||||
const list = el("ul", "sa-list");
|
||||
for (const row of rows) {
|
||||
const item = el("li", "sa-row");
|
||||
const head = el("div", "sa-head");
|
||||
head.appendChild(el("strong", "sa-title", row.title));
|
||||
const pill = el("span", "pill sa-pill is-" + row.state);
|
||||
if (row.state === "running") {
|
||||
const spin = el("span", "spinner tiny");
|
||||
spin.setAttribute("aria-hidden", "true");
|
||||
pill.appendChild(spin);
|
||||
}
|
||||
pill.appendChild(document.createTextNode(row.stateLabel));
|
||||
head.appendChild(pill);
|
||||
item.appendChild(head);
|
||||
item.appendChild(el("p", "sa-ask", row.ask));
|
||||
if (row.result) item.appendChild(el("p", "sa-result", row.result));
|
||||
list.appendChild(item);
|
||||
}
|
||||
card.appendChild(list);
|
||||
main.appendChild(card);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- ask */
|
||||
|
||||
// The frame's chat block, with `offline` worked out now rather than when the
|
||||
@@ -5956,10 +6079,30 @@ const workspaceFolders = () => (wsFrame && Array.isArray(wsFrame.folders) ? wsFr
|
||||
// session opened before the server wrote `worktree` has nothing to show, so
|
||||
// the slot stays hidden. The footer renders on every tick, so the DOM is only
|
||||
// touched when the labels change, or when a resize clears the key.
|
||||
// The project's name: the workspace's original folder, or the session's
|
||||
// worktree folder before a frame carries the workspace.
|
||||
function projectName() {
|
||||
const folders = workspaceFolders();
|
||||
if (folders.length && folders[0].name) return folders[0].name;
|
||||
const path = (S && S.worktree) || "";
|
||||
return path ? path.split(/[\\/]/).filter(Boolean).pop() || path : "";
|
||||
}
|
||||
|
||||
// The browser tab's title, led by the project so tabs from different
|
||||
// projects are told apart. Called from the chrome and the footer, since the
|
||||
// workspace frame can arrive after either.
|
||||
function renderTabTitle() {
|
||||
if (!S) return;
|
||||
const name = projectName();
|
||||
document.title =
|
||||
(name ? name + " · " : "") + (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
|
||||
}
|
||||
|
||||
function renderWhere() {
|
||||
const b = $("footer-where");
|
||||
const folders = workspaceFolders();
|
||||
const path = S.worktree || "";
|
||||
renderTabTitle();
|
||||
const alert = Boolean(folders.length && ((wsFrame.missing || []).length || (wsFrame.issues || []).length));
|
||||
const labels = folders.length
|
||||
? Array.from({ length: FOOTER_TIERS }, (_, tier) => footerLabel({ folders, branch: S.branch }, tier))
|
||||
@@ -5972,7 +6115,16 @@ function renderWhere() {
|
||||
let label = labels[0];
|
||||
for (const text of labels) {
|
||||
label = text;
|
||||
b.textContent = text;
|
||||
// The project name takes the highlight color, so several consoles side by
|
||||
// side tell apart at a glance; the rest of the label stays quiet.
|
||||
const name = projectName();
|
||||
b.textContent = "";
|
||||
if (name && text.startsWith(name)) {
|
||||
b.appendChild(el("span", "where-project", name));
|
||||
b.appendChild(document.createTextNode(text.slice(name.length)));
|
||||
} else {
|
||||
b.textContent = text;
|
||||
}
|
||||
if (alert) {
|
||||
const dot = el("span", "where-alert");
|
||||
dot.setAttribute("aria-hidden", "true");
|
||||
@@ -7197,6 +7349,7 @@ function lightDismiss(dlg) {
|
||||
});
|
||||
}
|
||||
lightDismiss($("looks-modal"));
|
||||
lightDismiss($("subagents-modal"));
|
||||
lightDismiss($("help-modal"));
|
||||
lightDismiss($("workspace-modal"));
|
||||
lightDismiss($("welcome-modal"));
|
||||
@@ -7499,6 +7652,13 @@ $("cleanup-scan").addEventListener("click", scanCleanup);
|
||||
$("cleanup-delete").addEventListener("click", deleteCleanup);
|
||||
|
||||
$("btn-brief").addEventListener("click", openBrief);
|
||||
$("btn-subagents").addEventListener("click", openSubagents);
|
||||
$("subagents-default").addEventListener("click", () => {
|
||||
$("subagents-instruction").value = defaultInstruction(S.workflow);
|
||||
});
|
||||
$("subagents-save").addEventListener("click", saveSubagents);
|
||||
$("subagents-cancel").addEventListener("click", () => $("subagents-modal").close());
|
||||
$("subagents-modal").addEventListener("close", () => $("btn-subagents").focus());
|
||||
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
|
||||
$("brief-go").addEventListener("click", sendBrief);
|
||||
for (const radio of document.querySelectorAll('input[name="brief-range"]')) {
|
||||
|
||||
@@ -19,6 +19,7 @@ export const HELP_TABS = Object.freeze([
|
||||
tab("dashboard", "The dashboard", true),
|
||||
tab("meter", "Session meter", false),
|
||||
tab("build", "Watching a build", false),
|
||||
tab("subagents", "Helpers (subagents)", false),
|
||||
tab("ask", "Ask a quick question", false),
|
||||
tab("finishing", "Stopping and finishing", false),
|
||||
tab("stuck", "When something looks stuck", true),
|
||||
@@ -39,6 +40,7 @@ export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow,
|
||||
if (gone || adrift) return "stuck";
|
||||
if (workspace) return "workspace";
|
||||
if (v === "ask") return "ask";
|
||||
if (v === "subagents") return "subagents";
|
||||
if (dashboard && meterRed) return "meter";
|
||||
if (dashboard) return "dashboard";
|
||||
if (v === "overview" || v.startsWith("doc:")) return "docs";
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
<link rel="modulepreload" href="/starters.js" />
|
||||
<link rel="modulepreload" href="/workspace.js" />
|
||||
<link rel="modulepreload" href="/meter.js" />
|
||||
<link rel="modulepreload" href="/subagents.js" />
|
||||
<link rel="modulepreload" href="/mentions.js" />
|
||||
<link rel="modulepreload" href="/favicon.js" />
|
||||
<link rel="modulepreload" href="/vendor/marked.esm.js" />
|
||||
@@ -172,6 +173,18 @@
|
||||
<button type="button" class="btn ghost small brief-btn" id="btn-brief" hidden>
|
||||
Write a brief
|
||||
</button>
|
||||
<!-- Subagents: opted-in skills only. Lit while helpers are on; a click
|
||||
opens the Subagents dialog and never toggles them itself. -->
|
||||
<button type="button" class="btn ghost small subagents-btn" id="btn-subagents" aria-pressed="false" hidden>
|
||||
<!-- An orchestrator and its helpers: one larger node linked to three smaller ones. -->
|
||||
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
||||
<path class="sa-link" d="M6.9 6.6L10.9 3.9M7.4 8h3.5M6.9 9.4l4 2.7" />
|
||||
<circle cx="4.6" cy="8" r="2.6" class="sa-hub" />
|
||||
<circle cx="12.4" cy="3" r="1.5" class="sa-node" />
|
||||
<circle cx="12.4" cy="8" r="1.5" class="sa-node" />
|
||||
<circle cx="12.4" cy="13" r="1.5" class="sa-node" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="views-group">
|
||||
<span class="views-arrow" aria-hidden="true">
|
||||
@@ -580,6 +593,13 @@
|
||||
<rect x="3" y="9" width="18" height="6" rx="3" />
|
||||
<path d="M6 12h7" />
|
||||
</symbol>
|
||||
<symbol id="hi-subagents" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="7" cy="12" r="3.5" />
|
||||
<circle cx="18" cy="5" r="2" />
|
||||
<circle cx="18" cy="12" r="2" />
|
||||
<circle cx="18" cy="19" r="2" />
|
||||
<path d="M10 10l6-4M10.5 12H16M10 14l6 4" />
|
||||
</symbol>
|
||||
<symbol id="hi-ask" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M4 5h16v11H10l-4 4v-4H4z" />
|
||||
<path d="M8 9.5h8M8 12.5h5" />
|
||||
@@ -1477,7 +1497,61 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 12: Ask a quick question -->
|
||||
<!-- Tab 12: Helpers (subagents) -->
|
||||
<section class="help-panel" data-tab="subagents">
|
||||
<h3>Helpers (subagents)</h3>
|
||||
<p>
|
||||
On a build, a review and Pathfinder, Plan2Code can hand independent
|
||||
pieces of work to helpers (subagents) while it keeps the conversation
|
||||
with you. The <strong>Subagents</strong> button in the top bar, after
|
||||
Stop session, is lit while helpers are on.
|
||||
</p>
|
||||
<h4>The switch</h4>
|
||||
<ul>
|
||||
<li>
|
||||
Clicking the button opens the <strong>Subagents</strong> dialog; it
|
||||
never switches helpers on or off by itself. Pick <strong>Use
|
||||
helpers</strong> or <strong>Work alone</strong>, edit the instruction
|
||||
Plan2Code follows (<strong>Reset to default</strong> puts the
|
||||
shipped one back), and say how many may run at once.
|
||||
</li>
|
||||
<li>
|
||||
It is off by default and saved for this project and this skill, so
|
||||
the next session of the same skill here starts the same way.
|
||||
</li>
|
||||
<li>
|
||||
The change reaches Plan2Code at its next check-in, as a setting,
|
||||
not as something you typed. How many helpers it can really start is
|
||||
up to your agent; some have no helpers at all.
|
||||
</li>
|
||||
<li>The button only appears on skills that use helpers, and only when Plan2Code can pass the setting on.</li>
|
||||
</ul>
|
||||
<h4>The Subagents tab</h4>
|
||||
<ul>
|
||||
<li>
|
||||
With the first helper, a <strong>Subagents</strong> tab appears before
|
||||
Ask: one row each, with what it was asked, whether it is running, done
|
||||
or failed, and a one-line result at the end. The number on the tab is
|
||||
how many are still running.
|
||||
</li>
|
||||
<li>
|
||||
Helpers report through Plan2Code, so the rows change at its
|
||||
check-ins, not live. The page cannot stop a helper; ask Plan2Code
|
||||
on the Ask tab if one should stop.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Working alone</strong> means your agent has no way to start
|
||||
helpers here, so it is doing the work itself.
|
||||
</li>
|
||||
<li>
|
||||
Pathfinder always uses helpers for its research questions, whatever
|
||||
the switch says, and they show here too.
|
||||
</li>
|
||||
<li>The tab clears when you go back to the dashboard.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- Tab 13: Ask a quick question -->
|
||||
<section class="help-panel" data-tab="ask">
|
||||
<h3>Ask a quick question</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1568,7 +1642,7 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 13: Stopping and finishing -->
|
||||
<!-- Tab 14: Stopping and finishing -->
|
||||
<section class="help-panel" data-tab="finishing">
|
||||
<h3>Stopping and finishing</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1650,7 +1724,7 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 14: When something looks stuck -->
|
||||
<!-- Tab 15: When something looks stuck -->
|
||||
<section class="help-panel" data-tab="stuck">
|
||||
<h3>When something looks stuck</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1772,7 +1846,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Tab 15: Keyboard and preferences -->
|
||||
<!-- Tab 16: Keyboard and preferences -->
|
||||
<section class="help-panel" data-tab="prefs">
|
||||
<h3>Keyboard and preferences</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1888,7 +1962,7 @@
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- Tab 16: Privacy and where things are saved -->
|
||||
<!-- Tab 17: Privacy and where things are saved -->
|
||||
<section class="help-panel" data-tab="privacy">
|
||||
<h3>Privacy and where things are saved</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1925,7 +1999,11 @@
|
||||
</li>
|
||||
<li>
|
||||
your role, theme, colors, card width and sounds, in
|
||||
<code>looks.json</code>.
|
||||
<code>looks.json</code>;
|
||||
</li>
|
||||
<li>
|
||||
your Subagents switch for each project and skill, in
|
||||
<code>subagents.json</code>.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
@@ -2039,6 +2117,46 @@
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- Subagents: the switch for this skill, filled from the frame's
|
||||
`subagents` by app.js and saved through POST /subagents. It borrows
|
||||
the User Preferences dialog's classes, so it needs no dialog styles of
|
||||
its own, only a themed number box. -->
|
||||
<dialog class="modal looks subagents" id="subagents-modal" aria-labelledby="subagents-title">
|
||||
<h2 id="subagents-title">Subagents</h2>
|
||||
<p class="modal-blurb">
|
||||
Let Plan2Code hand independent work to helpers in this skill. Saved for this
|
||||
project and this skill.
|
||||
</p>
|
||||
<fieldset class="modal-ranges looks-row">
|
||||
<legend>Helpers</legend>
|
||||
<label><input type="radio" name="subagents-on" value="on" /> <span>Use helpers</span></label>
|
||||
<label><input type="radio" name="subagents-on" value="off" checked /> <span>Work alone</span></label>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges">
|
||||
<legend>Instruction</legend>
|
||||
<textarea id="subagents-instruction" rows="4" maxlength="2000" aria-label="Instruction"></textarea>
|
||||
<div class="models-actions">
|
||||
<button type="button" class="btn small ghost" id="subagents-default">Reset to default</button>
|
||||
<span class="help">Passed to the agent as written, at its next check-in.</span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges">
|
||||
<legend>At most</legend>
|
||||
<label>
|
||||
<input type="number" id="subagents-max" min="1" max="20" step="1" aria-label="At most this many helpers at once" />
|
||||
<span>helpers at once</span>
|
||||
</label>
|
||||
<p class="help">Advisory: your agent's own limit still applies.</p>
|
||||
</fieldset>
|
||||
<p class="help" id="subagents-checkin"></p>
|
||||
<p class="help" id="subagents-research" hidden></p>
|
||||
<p class="help" id="subagents-status" role="status"></p>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn ghost" id="subagents-cancel">Cancel</button>
|
||||
<button type="button" class="btn primary" id="subagents-save">Save</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- The Workspace: the folder this session started in plus any added as
|
||||
context. The list is drawn by app.js from the frame's `workspace`;
|
||||
every change goes through the server's /workspace routes. -->
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
// Plan2Code Web Console - the Subagents switch's opt-in table, wording and checks.
|
||||
//
|
||||
// The source of truth for which workflows offer the switch, the instruction
|
||||
// each one ships with, the fixed frame every "on" block carries, the exact
|
||||
// lines the agent reads at a pickup (blockFor()), and the house rules for the
|
||||
// helpers an agent reports back (checkHelper()). No DOM access at module scope
|
||||
// and no imports: the server, console.mjs, the page and `node --test` all
|
||||
// import this file.
|
||||
|
||||
// The one place a skill opts in (FR-1). Wording is behaviour-level and names
|
||||
// no harness tool, so any agent can follow it or harmlessly ignore it.
|
||||
export const SUBAGENT_WORKFLOWS = Object.freeze({
|
||||
implement: Object.freeze({
|
||||
instruction:
|
||||
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
|
||||
}),
|
||||
"implement-review": Object.freeze({
|
||||
instruction:
|
||||
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
|
||||
}),
|
||||
"quick-task": Object.freeze({
|
||||
instruction:
|
||||
"Use helpers for side lookups, such as reading unfamiliar code or checking documentation, while you make the change yourself.",
|
||||
}),
|
||||
review: Object.freeze({
|
||||
instruction:
|
||||
"Split the review across helpers by area (for example correctness, tests and security), then merge and de-duplicate their findings yourself before you report.",
|
||||
}),
|
||||
pathfinder: Object.freeze({
|
||||
instruction:
|
||||
"Use helpers for codebase recon, sketches and lookups beside the conversation. Keep every question for the person with you.",
|
||||
}),
|
||||
});
|
||||
|
||||
export function offered(workflow) {
|
||||
return typeof workflow === "string" && Object.prototype.hasOwnProperty.call(SUBAGENT_WORKFLOWS, workflow);
|
||||
}
|
||||
|
||||
export const MAX_MIN = 1;
|
||||
export const MAX_MAX = 20;
|
||||
export const DEFAULT_MAX = 3;
|
||||
export const INSTRUCTION_MAX_CHARS = 2000;
|
||||
export const HELPER_TITLE_MAX = 80;
|
||||
export const HELPER_ASK_MAX = 400;
|
||||
export const HELPER_RESULT_MAX = 200;
|
||||
export const HELPER_STATES = Object.freeze(["running", "done", "failed"]);
|
||||
|
||||
/* ------------------------------------------------------------- settings */
|
||||
|
||||
export function defaultInstruction(workflow) {
|
||||
return offered(workflow) ? SUBAGENT_WORKFLOWS[workflow].instruction : "";
|
||||
}
|
||||
|
||||
// The person's own text when they wrote some, else the workflow's default.
|
||||
export function effectiveInstruction(setting) {
|
||||
const own = setting && typeof setting.instruction === "string" ? setting.instruction.trim() : "";
|
||||
return own || defaultInstruction(setting && setting.workflow);
|
||||
}
|
||||
|
||||
export function defaultSetting(workflow) {
|
||||
return { workflow, on: false, instruction: null, max: DEFAULT_MAX };
|
||||
}
|
||||
|
||||
/**
|
||||
* `{ on, instruction, max }` from untrusted input, or `{ error }` naming the
|
||||
* field that failed: "bad" (wrong type), "too-long" (instruction) or "max".
|
||||
* Returns an error object rather than throwing, so the route and the store
|
||||
* reader share one validator. An empty instruction means the default: null.
|
||||
*/
|
||||
export function cleanSetting(input) {
|
||||
if (!input || typeof input !== "object" || Array.isArray(input)) return { error: "bad" };
|
||||
if (typeof input.on !== "boolean") return { error: "bad" };
|
||||
let instruction = null;
|
||||
if (input.instruction !== null && input.instruction !== undefined) {
|
||||
if (typeof input.instruction !== "string") return { error: "bad" };
|
||||
const trimmed = input.instruction.trim();
|
||||
if (trimmed.length > INSTRUCTION_MAX_CHARS) return { error: "too-long" };
|
||||
instruction = trimmed || null;
|
||||
}
|
||||
const max = input.max;
|
||||
if (!Number.isInteger(max) || max < MAX_MIN || max > MAX_MAX) return { error: "max" };
|
||||
return { on: input.on, instruction, max };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ the lines */
|
||||
|
||||
// The non-editable part of every "on" block (FR-8).
|
||||
export const FRAME_LINES = Object.freeze([
|
||||
"Hand independent work to helpers if your tools allow it; otherwise carry on alone.",
|
||||
"Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.",
|
||||
'With no way to start helpers, report one "working alone" entry for this skill run instead.',
|
||||
]);
|
||||
|
||||
export const PATHFINDER_RESEARCH_LINE = "Research questions always use helpers, whatever this switch says.";
|
||||
|
||||
// Only the first line of a block starts at column 0, so no line inside it can
|
||||
// be read as an entry of its own (NFR-5).
|
||||
export function onLines({ revision, replaces, max, instruction }) {
|
||||
const label = replaces ? `revision ${revision}, replaces revision ${replaces}` : `revision ${revision}`;
|
||||
const own = String(instruction || "")
|
||||
.split("\n")
|
||||
.map((line) => line.trimEnd())
|
||||
.filter((line) => line.trim());
|
||||
return [
|
||||
`Subagents: on (${label}) — a console setting, not typed by the person.`,
|
||||
...[...FRAME_LINES, ...own, `At most ${max} helpers at once.`].map((line) => " " + line),
|
||||
];
|
||||
}
|
||||
|
||||
export function offLine(revision) {
|
||||
return `Subagents: off (revision ${revision}) — don't start new helpers for the rest of this session.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the agent is owed at a pickup, given the session setting and the
|
||||
* cursor of what it was last told: `null`, or `{ field, lines, cursor }`
|
||||
* where `cursor` is what to write once the lines are printed. Never says
|
||||
* "off" to an agent that was not told "on" (FR-6). Pure: no clock, no I/O.
|
||||
*/
|
||||
export function blockFor(setting, told) {
|
||||
const last = told || { revision: 0, state: "none" };
|
||||
if (!setting || !offered(setting.workflow) || !(setting.revision > last.revision)) return null;
|
||||
const { revision, max } = setting;
|
||||
const instruction = effectiveInstruction(setting);
|
||||
if (setting.on) {
|
||||
const replaces = last.state === "on" ? last.revision : undefined;
|
||||
return {
|
||||
field: { state: "on", revision, max, instruction },
|
||||
lines: onLines({ revision, replaces, max, instruction }),
|
||||
cursor: { revision, state: "on" },
|
||||
};
|
||||
}
|
||||
if (last.state !== "on") return null;
|
||||
return {
|
||||
field: { state: "off", revision, max, instruction },
|
||||
lines: [offLine(revision)],
|
||||
cursor: { revision, state: "off" },
|
||||
};
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ helpers */
|
||||
|
||||
const isPlainObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
||||
const nonEmpty = (v) => typeof v === "string" && v.trim() !== "";
|
||||
|
||||
// The problems with one reported helper, [] when it is fine.
|
||||
export function checkHelper(entry) {
|
||||
if (!isPlainObject(entry)) return ["helper: each entry must be an object"];
|
||||
if (!nonEmpty(entry.id)) return ["helper: id must be a non-empty string"];
|
||||
const who = `helper "${entry.id}"`;
|
||||
if (entry.alone === true) return entry.id === "alone" ? [] : [`${who}: the working-alone entry must have id "alone"`];
|
||||
const problems = [];
|
||||
if (!nonEmpty(entry.title)) problems.push(`${who}: title must be a non-empty string`);
|
||||
else if (entry.title.length > HELPER_TITLE_MAX) problems.push(`${who}: title must be at most ${HELPER_TITLE_MAX} characters`);
|
||||
if (!nonEmpty(entry.ask)) problems.push(`${who}: ask must be a non-empty string`);
|
||||
else if (entry.ask.length > HELPER_ASK_MAX) problems.push(`${who}: ask must be at most ${HELPER_ASK_MAX} characters`);
|
||||
if (!HELPER_STATES.includes(entry.state)) problems.push(`${who}: state must be running, done or failed`);
|
||||
if (entry.result !== undefined) {
|
||||
if (typeof entry.result !== "string") problems.push(`${who}: result must be a string`);
|
||||
else if (entry.result.length > HELPER_RESULT_MAX) problems.push(`${who}: result must be at most ${HELPER_RESULT_MAX} characters`);
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
// The problems with a whole merged list.
|
||||
export function checkHelpers(list) {
|
||||
if (!Array.isArray(list)) return ["helpers must be an array"];
|
||||
const problems = [];
|
||||
const seen = new Set();
|
||||
let alone = 0;
|
||||
for (const entry of list) {
|
||||
if (isPlainObject(entry) && nonEmpty(entry.id)) {
|
||||
if (seen.has(entry.id)) problems.push(`helper "${entry.id}": duplicate id`);
|
||||
seen.add(entry.id);
|
||||
if (entry.alone === true && ++alone === 2) problems.push(`helper "${entry.id}": only one working-alone entry is allowed`);
|
||||
}
|
||||
problems.push(...checkHelper(entry));
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ the page */
|
||||
|
||||
// The page's rules for the button, the modal and the tab, kept here so they
|
||||
// are tested without a browser. `frame` is the state frame's `subagents`
|
||||
// block; app.js only renders what these say.
|
||||
|
||||
export const CHECKIN_LINE = "Helpers report through Plan2Code, so their progress shows here at its check-ins, not live.";
|
||||
|
||||
const STATE_LABELS = Object.freeze({ running: "Running", done: "Done", failed: "Failed" });
|
||||
|
||||
// The switch shows only where the skill opts in AND the agent's console copy
|
||||
// said it can deliver it (FR-3).
|
||||
export function showSwitch(frame) {
|
||||
return Boolean(frame && frame.offered && frame.supported);
|
||||
}
|
||||
|
||||
// The button's tooltip and accessible name (FR-2).
|
||||
export function switchLabel(frame) {
|
||||
return frame && frame.on ? "Subagents: on" : "Subagents: off";
|
||||
}
|
||||
|
||||
// What the Subagents tab draws: the working-alone note, or one row per helper
|
||||
// in the order the agent reported them. A result shows once the helper ended.
|
||||
export function helperRows(helpers) {
|
||||
const list = Array.isArray(helpers) ? helpers.filter(isPlainObject) : [];
|
||||
if (list.some((h) => h.alone === true)) return { alone: true, rows: [] };
|
||||
const rows = list.map(({ id, title, ask, state, result }) => ({
|
||||
id,
|
||||
title,
|
||||
ask,
|
||||
state,
|
||||
stateLabel: STATE_LABELS[state] || STATE_LABELS.running,
|
||||
...((state === "done" || state === "failed") && typeof result === "string" && result ? { result } : {}),
|
||||
}));
|
||||
return { alone: false, rows };
|
||||
}
|
||||
|
||||
// Never an empty tab. Independent of on / off, so Pathfinder's research
|
||||
// helpers show even with the switch off (FR-11, FR-12).
|
||||
export function showTab(frame, helpers) {
|
||||
return showSwitch(frame) && Array.isArray(helpers) && helpers.length > 0;
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
LOOKS_FILE,
|
||||
PUBLIC_DIR,
|
||||
SHIPPED_MODELS_FILE,
|
||||
SUBAGENTS_SETTING_FILE,
|
||||
UPDATE_CHECK_FILE,
|
||||
USER_MODELS_FILE,
|
||||
WORKSPACE_FILE,
|
||||
@@ -38,6 +39,7 @@ import {
|
||||
fileStamp,
|
||||
handleFile,
|
||||
initialWorkspace,
|
||||
latestOpenCaps,
|
||||
nowIso,
|
||||
parseArgs,
|
||||
pendingChatCount,
|
||||
@@ -46,20 +48,25 @@ import {
|
||||
readJson,
|
||||
readLedger,
|
||||
readOverview,
|
||||
readSubagentSetting,
|
||||
readWorkspace,
|
||||
rememberWorkspace,
|
||||
rememberedWorkspace,
|
||||
removeCleanup,
|
||||
remoteWarning,
|
||||
saveSubagentStoreEntry,
|
||||
specKey,
|
||||
subagentStoreEntry,
|
||||
typedCount,
|
||||
withStateLock,
|
||||
writeJsonAtomic,
|
||||
writeSubagentSetting,
|
||||
writeWorkspace,
|
||||
} from "./lib.mjs";
|
||||
import { DOC_TYPES, MAX_ATTACHMENTS, MAX_DOC_BYTES, docExt, workflowLabel, workflowTitle } from "./public/answers.js";
|
||||
import { CHAT_LIMIT, CHAT_MAX_CHARS, chatOffline } from "./public/chat.js";
|
||||
import { meterView } from "./public/meter.js";
|
||||
import { cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
||||
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
|
||||
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
|
||||
import { checkForUpdate } from "./update-check.mjs";
|
||||
@@ -212,6 +219,7 @@ const SERVABLE = new Set([
|
||||
"starters.js",
|
||||
"workspace.js",
|
||||
"meter.js",
|
||||
"subagents.js",
|
||||
"mentions.js",
|
||||
"favicon.js",
|
||||
"start-stop.mp3",
|
||||
@@ -601,6 +609,48 @@ function ensureConversation(state) {
|
||||
if (entry) appendEvent(DIR, { type: "chat-reset", reason: entry.reason });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ subagents */
|
||||
|
||||
// subagents-setting.json has one writer, this server, and the agent hears of
|
||||
// it only through what console.mjs reads there; events.ndjson's latest `open`
|
||||
// says whether the agent's console copy can carry it. Both re-read only when
|
||||
// their file has moved.
|
||||
const SUBAGENTS_SETTING_PATH = path.join(DIR, SUBAGENTS_SETTING_FILE);
|
||||
const EVENTS_PATH = path.join(DIR, "events.ndjson");
|
||||
|
||||
let subagentSettingSeen = { stamp: null, setting: null };
|
||||
function subagentSettingNow() {
|
||||
const stamp = fileStamp(SUBAGENTS_SETTING_PATH);
|
||||
if (stamp !== subagentSettingSeen.stamp) subagentSettingSeen = { stamp, setting: readSubagentSetting(DIR) };
|
||||
return subagentSettingSeen.setting;
|
||||
}
|
||||
|
||||
let capsSeen = { stamp: null, caps: [] };
|
||||
function openCapsNow() {
|
||||
const stamp = fileStamp(EVENTS_PATH);
|
||||
if (stamp !== capsSeen.stamp) capsSeen = { stamp, caps: latestOpenCaps(DIR) };
|
||||
return capsSeen.caps;
|
||||
}
|
||||
|
||||
const sameSetting = (a, b) => a.workflow === b.workflow && a.on === b.on && a.instruction === b.instruction && a.max === b.max;
|
||||
|
||||
/**
|
||||
* Turn the per-project store into this session's setting, for the workflow
|
||||
* the session is in now. The only place that happens (FR-7): a session an
|
||||
* older server ran has no setting file, so nothing is ever injected into it.
|
||||
* A record that already matches is left alone, revision and all, so a
|
||||
* restart alone never re-tells the agent anything.
|
||||
*/
|
||||
function syncSubagentSetting(state) {
|
||||
if (!state || typeof state.workflow !== "string") return;
|
||||
const { workflow } = state;
|
||||
const { on, instruction, max } = offered(workflow) ? subagentStoreEntry(sessionWorktree(), workflow) : defaultSetting(workflow);
|
||||
const target = { workflow, on, instruction, max };
|
||||
const current = readSubagentSetting(DIR);
|
||||
if (current && sameSetting(current, target)) return;
|
||||
writeSubagentSetting(DIR, { ...target, revision: (current ? current.revision : 0) + 1 });
|
||||
}
|
||||
|
||||
// What the page needs to draw itself, in the shape of the SSE state frame.
|
||||
// `have` names that exact view, for the page to hand back when it opens its
|
||||
// stream (see /events).
|
||||
@@ -615,20 +665,33 @@ function stateFrame(state) {
|
||||
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
|
||||
workspace: workspaceView(),
|
||||
meter: meterView(ledgerEntries()),
|
||||
subagents: subagentsView(state),
|
||||
...(updateInfo ? { update: updateInfo } : {}),
|
||||
have: haveKey(),
|
||||
};
|
||||
}
|
||||
|
||||
// The page shows the switch only when `offered && supported` (FR-3); the
|
||||
// frame says both and leaves combining them to the page. `instruction: null`
|
||||
// is the shipped default, which the page reads from subagents.js itself.
|
||||
function subagentsView(state) {
|
||||
const workflow = state && state.workflow;
|
||||
const { on, instruction, max, revision } = subagentSettingNow() || { ...defaultSetting(workflow), revision: 0 };
|
||||
return { offered: offered(workflow), supported: openCapsNow().includes("subagents"), on, instruction, max, revision };
|
||||
}
|
||||
|
||||
function haveKey() {
|
||||
const { pending, stop } = resultFlags();
|
||||
chatEntries();
|
||||
chatPickedUp();
|
||||
workspaceNow();
|
||||
ledgerEntries();
|
||||
subagentSettingNow();
|
||||
openCapsNow();
|
||||
return (
|
||||
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
|
||||
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}`
|
||||
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}` +
|
||||
`.${subagentSettingSeen.stamp || ""}.${capsSeen.stamp || ""}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1172,6 +1235,39 @@ const server = http.createServer((req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
// The Subagents switch for the session's workflow. Saved per project folder
|
||||
// for the next session, and applied to this one with a bumped revision, which
|
||||
// is what console.mjs hands the agent at its next pickup. Never blocked by,
|
||||
// and never blocking, a card send.
|
||||
if (pathname === "/subagents" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const state = readState();
|
||||
if (!state || !offered(state.workflow)) return json(res, 400, { error: "not-offered" });
|
||||
const clean = cleanSetting(body);
|
||||
if (clean.error) return json(res, 400, { error: clean.error });
|
||||
const { on, instruction, max } = clean;
|
||||
const current = readSubagentSetting(DIR);
|
||||
const next = { workflow: state.workflow, on, instruction, max };
|
||||
// The store is per project, so another session may have moved it since
|
||||
// this one synced: it always takes the person's latest pick. Only a
|
||||
// real change to this session's setting bumps what the agent hears.
|
||||
const unchanged = Boolean(current && sameSetting(current, next));
|
||||
try {
|
||||
saveSubagentStoreEntry(sessionWorktree(), state.workflow, { on, instruction, max });
|
||||
if (!unchanged) writeSubagentSetting(DIR, { ...next, revision: (current ? current.revision : 0) + 1 });
|
||||
} catch (e) {
|
||||
return json(res, 500, { error: String(e.message) });
|
||||
}
|
||||
if (unchanged) return json(res, 200, { ok: true, setting: current });
|
||||
const setting = readSubagentSetting(DIR);
|
||||
appendEvent(DIR, { type: "subagents", on, revision: setting.revision });
|
||||
pushState();
|
||||
return json(res, 200, { ok: true, setting });
|
||||
});
|
||||
}
|
||||
|
||||
// The launcher's model menu: what ships (read-only here) and what the user added.
|
||||
if (pathname === "/models" && req.method === "GET") {
|
||||
const saved = readJson(USER_MODELS_FILE, null) || {};
|
||||
@@ -1400,6 +1496,9 @@ const server = http.createServer((req, res) => {
|
||||
try {
|
||||
ensureConversation(written.state);
|
||||
} catch {}
|
||||
try {
|
||||
syncSubagentSetting(written.state);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
// Name the items that went. A page with OTHER answers staged should drop
|
||||
@@ -1726,6 +1825,9 @@ function checkState() {
|
||||
try {
|
||||
ensureConversation(parsed);
|
||||
} catch {}
|
||||
try {
|
||||
syncSubagentSetting(parsed);
|
||||
} catch {}
|
||||
try {
|
||||
followSpecDir(parsed);
|
||||
} catch {}
|
||||
@@ -1900,6 +2002,9 @@ function onListening(port) {
|
||||
try {
|
||||
bootWorkspace();
|
||||
} catch {}
|
||||
try {
|
||||
syncSubagentSetting(readState());
|
||||
} catch {}
|
||||
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
|
||||
try {
|
||||
startUpdateCheck();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "Plan2Code",
|
||||
"version": "2.4.2",
|
||||
"version": "2.5.0",
|
||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
||||
"keywords": [
|
||||
"ai",
|
||||
@@ -17,6 +17,6 @@
|
||||
"url": "https://github.com/jparkerweb/plan2code"
|
||||
},
|
||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||
"releaseDate": "2026-10-05",
|
||||
"releaseDate": "2026-10-06",
|
||||
"mode": "utility"
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "Plan2Code",
|
||||
"version": "2.4.2",
|
||||
"version": "2.5.0",
|
||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
||||
"keywords": [
|
||||
"ai",
|
||||
@@ -17,6 +17,6 @@
|
||||
"url": "https://github.com/jparkerweb/plan2code"
|
||||
},
|
||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||
"releaseDate": "2026-10-05",
|
||||
"releaseDate": "2026-10-06",
|
||||
"mode": "utility"
|
||||
}
|
||||
Reference in new issue
Block a user