@hienlh/ppm 0.25.0 → 0.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.25.1] - 2026-11-14
4
+
5
+ ### Added
6
+
7
+ - **The Assistant can make an existing chat a project's manager chat** (`manager_assign`), or stop it being one (`manager_unassign`), after a card. It prefers adopting a chat you point at over creating a new one.
8
+ - **`ppm manager list | assign | unassign`** does the same from a terminal, through the running PPM.
9
+
3
10
  ## [0.25.0] - 2026-11-13
4
11
 
5
12
  ### Added
@@ -83,4 +83,4 @@ This skill covers the `ppm` CLI, its HTTP API, and its config DB. It does **not*
83
83
  - Third-party extensions (inspect via `ppm ext list`).
84
84
  - The Claude Agent SDK internals (separate skill).
85
85
 
86
- <!-- Generated for PPM v0.25.0 at build time. Re-run `ppm export skill --install` to refresh. -->
86
+ <!-- Generated for PPM v0.25.1 at build time. Re-run `ppm export skill --install` to refresh. -->
@@ -1512,6 +1512,36 @@ Remove a language server PPM installed (one on PATH or in a project is left alon
1512
1512
 
1513
1513
  **Usage:** `ppm lsp remove [options] <id>`
1514
1514
 
1515
+ ## `ppm manager`
1516
+
1517
+ Each project's manager chat: the chat PPM Assistant messages without asking
1518
+
1519
+ **Usage:** `ppm manager [options] [command]`
1520
+
1521
+ ### `ppm manager list`
1522
+
1523
+ List every project's manager chat
1524
+
1525
+ **Options:**
1526
+ - `--json` — Print JSON
1527
+
1528
+ ### `ppm manager assign`
1529
+
1530
+ Make an existing Claude chat its project's manager chat. Refused from an AI chat (use manager_assign)
1531
+
1532
+ **Options:**
1533
+ - `-p, --project <name>` — Project name or path (default: the project PPM recorded for the chat)
1534
+ - `--replace` — Take the role from the project's current manager chat
1535
+
1536
+ **Usage:** `ppm manager assign [options] <session>`
1537
+
1538
+ ### `ppm manager unassign`
1539
+
1540
+ Stop a project's manager chat being the manager; the chat is kept. Refused from an AI chat (use manager_unassign)
1541
+
1542
+ **Options:**
1543
+ - `-p, --project <name>` — Project name or path (default: the current folder's project)
1544
+
1515
1545
  ## `ppm mcp`
1516
1546
 
1517
1547
  The MCP servers every chat starts with
@@ -838,4 +838,4 @@ Authenticate with `?token=<token>` (see Authentication).
838
838
  - `/ws/android`
839
839
  - `/ws/project/<project>/<type>/<id>` — `<type>`: `terminal`, `chat`, `group`, `lsp` (for `chat`, `<id>` is the session id)
840
840
 
841
- <!-- Generated from src/server/routes/ for PPM v0.25.0 -->
841
+ <!-- Generated from src/server/routes/ for PPM v0.25.1 -->
@@ -174,6 +174,13 @@ stream starts, so a chat made a manager while its stream is live gets the server
174
174
  the project's manager, in the mode Settings → PPM Assistant gives new manager chats
175
175
  (`manager_default_mode`), with the rules files below. No card: a person pressed the button.
176
176
 
177
+ The Assistant adopts an existing chat with `manager_assign` and takes the role away with
178
+ `manager_unassign` (both under "Running the user's chats"); `ppm manager list | assign <session>
179
+ [-p project] [--replace] | unassign [-p project]` does the same from a terminal through
180
+ `/api/assistant/managers` on the running PPM (`src/cli/commands/manager-cmd.ts`, server only:
181
+ with no PPM running it stops and says so). `assign` and `unassign` are refused from an AI chat
182
+ (advisory, keyed on the AI-chat mark) and point to the two tools.
183
+
177
184
  ### Manager rules
178
185
 
179
186
  A manager chat works by `<project>/.ppm/manager.md` (`src/services/assistant-managers/manager-rules-*.ts`).
@@ -598,6 +605,25 @@ the user. `session_status` with
598
605
  no ids lists every manager chat, and each Assistant turn's shared context carries the list (project
599
606
  → session id, title; `assistant-managers-context.ts`), re-sent when it changes.
600
607
 
608
+ An existing chat becomes the manager through **`manager_assign`** (`project`, `sessionId`, optional
609
+ `providerId`, `replace`), and stops being it through **`manager_unassign`** (`project`); the
610
+ instructions tell the Assistant to adopt a chat the user points at rather than create a new one.
611
+ Both are the `manager` tool family (`assistant-manager-{tools,write-tools,tool-definitions}.ts`,
612
+ names in `src/shared/assistant-manager-tool-names.ts`, card in
613
+ `assistant-approval-summary-manager.ts`). They reach no route: they call `managerChats`, the
614
+ service behind the session row's *Set as manager chat* / *Unset manager chat*, so the rules files,
615
+ `assistant:managers_changed` and the badges are the screen's; the row is written with
616
+ `assigned_by: "assistant"`. Refused before any card: an unattended turn, a chat that is not this
617
+ project's (missing, another project's, an Assistant chat — `resolveAssistantSessionTarget`), a
618
+ Codex chat, a design chat (the service's own `checkAssign`), the chat already being the manager,
619
+ and a project that already has one unless `replace: true`. The card shows the project, the chat
620
+ (title and whole id), its provider, its last activity (the transcript's mtime), its mode (which
621
+ assigning leaves as it is, flagged in bypass), the chat that stops being the manager when replacing,
622
+ and the consequence in the dialog's words plus the rules-file note. After the answer both tools read
623
+ the chat and the project's manager again and change nothing if either moved; an assignment with
624
+ nothing to replace is still compare-and-set (`onlyIfNone`). A running turn does not block either:
625
+ the route does not require it, and a live stream simply gets the manager tools at its next start.
626
+
601
627
 
602
628
  - **`chats_attention`** (`src/services/assistant-hub/chat-attention.service.ts`) answers "which
603
629
  chats need me": chats waiting on a card or question, running, whose card was lost (an unread
@@ -656,6 +682,7 @@ writes the database directly, so an open PPM never heard of the change.
656
682
  | Projects | (`projects_list`) | `project_update`, `project_remove` |
657
683
  | Chats | (`chat_list_sessions`, `chats_attention`), `chat_changes` | `chat_stop`, `chat_delete`; `chat_organize`, `chat_changes_answer` (see below) |
658
684
  | Database connections | (`db_list_connections`), `db_connection_test` | `db_connection_save`, `db_connection_delete` |
685
+ | Manager chats | (`session_status`, the shared context) | `manager_assign`, `manager_unassign` (see "Running the user's chats") |
659
686
 
660
687
  The connection family (`assistant-db-connection-*.ts`, names in
661
688
  `src/shared/assistant-db-connection-tool-names.ts`) reaches only the connection list, one
@@ -1264,7 +1291,9 @@ and runs in bypass mode:
1264
1291
  connected if the phone should get cards.
1265
1292
  2. *Digest & quiet hours*: the digest time and quiet hours, saved from a browser in the user's zone.
1266
1293
  3. In the project, right-click (long-press) the chat → *Set as manager chat*. Its mode stays what it
1267
- was; in bypass mode the dialog says "This chat runs without approval prompts."
1294
+ was; in bypass mode the dialog says "This chat runs without approval prompts." Asking the
1295
+ Assistant ("make Quản lý the Nxsys manager") does the same through `manager_assign` and a card,
1296
+ and `ppm manager assign <session> -p <project>` from a terminal.
1268
1297
  4. *Manager chats* → the project's row → *Edit* in its Rules column. Keep two things in `.ppm/manager.md`: a pointer
1269
1298
  ("read and follow `<path to the guide>`") and the safety rules **inline** — only what is inline is
1270
1299
  guarded; the guide stays the manager's own working file.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hienlh/ppm",
3
- "version": "0.25.0",
4
- "description": "Personal Project Manager — mobile-first web IDE with AI assistance",
3
+ "version": "0.25.1",
4
+ "description": "Personal Project Manager — mobile-first web IDE with AI assistance",
5
5
  "author": "hienlh",
6
6
  "license": "SEE LICENSE IN LICENSE",
7
7
  "module": "src/index.ts",
@@ -0,0 +1,86 @@
1
+ import type { Command } from "commander";
2
+ import { inAiChat } from "../../services/ai-chat-env.ts";
3
+ import type { ManagerAssignCheck, ManagerChatSummary } from "../../shared/assistant-managers.ts";
4
+ import { ppmApiRequest } from "../utils/settings-request.ts";
5
+ import { C, currentProjectName, fail, resolveChatTarget, run } from "./chat-cmd-request.ts";
6
+ import { printTable } from "./cli-table.ts";
7
+
8
+ /**
9
+ * `ppm manager`: each project's manager chat — the chat PPM Assistant messages without asking —
10
+ * through `/api/assistant/managers`, the routes the session list's "Set as manager chat" and
11
+ * "Unset manager chat" call, so the rules files, the checks and every open PPM's badges are the
12
+ * screen's. Server only: the role is checked against the live chats and announced by the running
13
+ * PPM. `assign` and `unassign` are refused from an AI chat (advisory): the PPM Assistant has
14
+ * `manager_assign` and `manager_unassign`, which show the user a card.
15
+ */
16
+
17
+ const SERVER_ONLY = "Manager chats are set in the running PPM.";
18
+ const managersPath = (project: string) => `/assistant/managers/${encodeURIComponent(project)}`;
19
+ const api = <T>(method: string, path: string, body?: unknown) => ppmApiRequest<T>(method, path, body, { serverOnly: SERVER_ONLY });
20
+
21
+ function refuseInAiChat(command: string, tool: string): void {
22
+ if (!inAiChat()) return;
23
+ fail(`ppm manager ${command} is refused here from an AI chat: the manager chat is the one PPM Assistant messages without asking. `
24
+ + `The PPM Assistant uses its ${tool} tool (the user sees a card); otherwise the user does it from the chat's menu in PPM, or runs the command.`);
25
+ }
26
+
27
+ export function registerManagerCommands(program: Command): void {
28
+ const manager = program.command("manager").description("Each project's manager chat: the chat PPM Assistant messages without asking");
29
+ const chatProjectFlag = ["-p, --project <name>", "Project name or path (default: the project PPM recorded for the chat)"] as const;
30
+ const projectFlag = ["-p, --project <name>", "Project name or path (default: the current folder's project)"] as const;
31
+
32
+ manager
33
+ .command("list")
34
+ .description("List every project's manager chat")
35
+ .option("--json", "Print JSON")
36
+ .action((opts: { json?: boolean }) => run(async () => {
37
+ const { managers } = await api<{ managers: ManagerChatSummary[] }>("GET", "/assistant/managers");
38
+ if (opts.json) {
39
+ console.log(JSON.stringify(managers, null, 2));
40
+ return;
41
+ }
42
+ if (managers.length === 0) {
43
+ console.log(`${C.yellow}No manager chats yet.${C.reset} Set one with \`ppm manager assign <session> -p <project>\` or from a chat's menu in PPM.`);
44
+ return;
45
+ }
46
+ printTable(["Project", "Chat", "Session", "State", "Mode"], managers.map((m) => [
47
+ m.projectName, m.title ?? "(untitled)", m.sessionId, m.phase, m.permissionMode,
48
+ ]));
49
+ })());
50
+
51
+ manager
52
+ .command("assign <session>")
53
+ .description("Make an existing Claude chat its project's manager chat. Refused from an AI chat (use manager_assign)")
54
+ .option(...chatProjectFlag)
55
+ .option("--replace", "Take the role from the project's current manager chat")
56
+ .action((session: string, opts: { project?: string; replace?: boolean }) => run(async () => {
57
+ refuseInAiChat("assign", "manager_assign");
58
+ const chat = await resolveChatTarget(session, opts.project);
59
+ const project = chat.project;
60
+ const check = await api<ManagerAssignCheck>("GET", `${managersPath(project)}/check?sessionId=${encodeURIComponent(chat.id)}`);
61
+ if (check.already) {
62
+ console.log(`${C.dim}${chat.id} already is the manager chat of ${project}.${C.reset}`);
63
+ return;
64
+ }
65
+ if (check.replaces && !opts.replace) {
66
+ fail(`${project} already has a manager chat: "${check.replaces.title ?? "(untitled)"}" (${check.replaces.sessionId}). `
67
+ + "Pass --replace to take the role from it, or run `ppm manager unassign` first.");
68
+ }
69
+ const done = await api<{ sessionId: string; replaced: string | null }>("PUT", managersPath(project), { sessionId: chat.id });
70
+ console.log(`${C.green}Manager chat of ${project}:${C.reset} ${done.sessionId}${done.replaced ? ` (replaces ${done.replaced}, which keeps its history)` : ""}`);
71
+ if (check.permissionMode === "bypassPermissions") console.log(`${C.yellow}This chat runs without approval prompts.${C.reset}`);
72
+ })());
73
+
74
+ manager
75
+ .command("unassign")
76
+ .description("Stop a project's manager chat being the manager; the chat is kept. Refused from an AI chat (use manager_unassign)")
77
+ .option(...projectFlag)
78
+ .action((opts: { project?: string }) => run(async () => {
79
+ refuseInAiChat("unassign", "manager_unassign");
80
+ const project = await currentProjectName(opts.project);
81
+ const { removed } = await api<{ removed: boolean }>("DELETE", managersPath(project));
82
+ console.log(removed
83
+ ? `${C.green}Unassigned:${C.reset} ${project} has no manager chat now; the chat is kept.`
84
+ : `${C.dim}${project} had no manager chat; nothing changed.${C.reset}`);
85
+ })());
86
+ }
@@ -21,6 +21,9 @@ export async function registerCommandGroups(program: Command): Promise<void> {
21
21
  const { registerTagsCommands } = await import("./commands/tags-cmd.ts");
22
22
  registerTagsCommands(program);
23
23
 
24
+ const { registerManagerCommands } = await import("./commands/manager-cmd.ts");
25
+ registerManagerCommands(program);
26
+
24
27
  const { registerThemeCommands } = await import("./commands/settings-theme-cmd.ts");
25
28
  registerThemeCommands(program);
26
29
 
@@ -21,6 +21,11 @@ export const ASSISTANT_CHATS_SUBSECTIONS = `### Running the user's chats
21
21
  - \`create_session\` with \`manager: true\` asks the user once to create a project's manager chat
22
22
  (refused when it has one). Without \`manager\` it opens an ordinary chat in the project you name
23
23
  and gives it a task, after a card, and only when the user asked for it.
24
+ - An existing Claude chat becomes a project's manager with \`manager_assign\` (one card;
25
+ \`replace: true\` takes the role from the current manager), and \`manager_unassign\` takes the
26
+ role away, keeping the chat. When the user points at a chat they already use ("make Quản lý the
27
+ manager"), adopt it with \`manager_assign\` rather than creating a new one. The user can do the
28
+ same from that chat's menu in the session list: "Set as manager chat" / "Unset manager chat".
24
29
  - \`session_status\` with no ids reports every manager chat.
25
30
  - When the user wants their own words passed on, give them word for word, in quotes, rather
26
31
  than in your paraphrase; the manager still takes them as your report, not as the user's OK
@@ -19,7 +19,8 @@ export function assistantManagersContextEntry(managers: readonly ManagerListing[
19
19
  const head = "Manager chats (written by PPM): each project's manager chat, which you message with send_to_session and "
20
20
  + "no card. Every other chat needs the user's OK on a card.";
21
21
  if (managers.length === 0) {
22
- return `${head}\nNo project has a manager chat yet. create_session with manager: true asks the user to create one.`;
22
+ return `${head}\nNo project has a manager chat yet. manager_assign makes a chat the user already has the manager; `
23
+ + "create_session with manager: true creates a new one. Both ask the user first.";
23
24
  }
24
25
  const sorted = [...managers].sort((a, b) => a.projectName.localeCompare(b.projectName));
25
26
  const lines = sorted.slice(0, MAX_LISTED).map((m) => {
@@ -139,6 +139,7 @@ export function ppmCliReferenceHeader(instance: PpmInstance, opts: ReferenceOpti
139
139
  "- chat stop/rename/pin/tag/read/delete: prefer chat_stop, chat_organize and chat_delete",
140
140
  "- chat stop sends the stop PPM's Stop button sends; chat delete stops a running turn first and deletes nothing if it does not stop",
141
141
  "- chat changes/turns/revert-turn: prefer chat_changes and chat_changes_answer; revert-turn prints its preview and writes only with --yes",
142
+ "- manager assign/unassign: refused from an AI chat; use manager_assign and manager_unassign (the user sees a card). They need a running PPM",
142
143
  "- git: prefer the git tools; every git command takes -p <project> and --repo <path> (a repository inside the project)",
143
144
  "- db add/edit/remove/test: prefer db_connection_save, db_connection_delete and db_connection_test. Neither path sends",
144
145
  " read-only: a new connection is read-only, and the tools cannot make one writable. A shell command can reach any of",
@@ -683,6 +684,21 @@ ppm tags remove <tag>
683
684
  Delete a tag; its chats keep existing, untagged
684
685
  -p, --project <name> — Project name or path (default: the current folder's project)
685
686
  \`\`\`
687
+ ## ppm manager — Each project's manager chat: the chat PPM Assistant messages without asking
688
+ \`\`\`
689
+ ppm manager list
690
+ List every project's manager chat
691
+ --json — Print JSON
692
+
693
+ ppm manager assign <session>
694
+ Make an existing Claude chat its project's manager chat. Refused from an AI chat (use manager_assign)
695
+ -p, --project <name> — Project name or path (default: the project PPM recorded for the chat)
696
+ --replace — Take the role from the project's current manager chat
697
+
698
+ ppm manager unassign
699
+ Stop a project's manager chat being the manager; the chat is kept. Refused from an AI chat (use manager_unassign)
700
+ -p, --project <name> — Project name or path (default: the current folder's project)
701
+ \`\`\`
686
702
  ## ppm theme — Show, pick, import or remove PPM's themes
687
703
  \`\`\`
688
704
  ppm theme get
@@ -23,6 +23,7 @@ const SERVER = [
23
23
  "chat changes list", "chat changes diff", "chat changes keep", "chat changes reopen", "chat changes revert",
24
24
  "chat changes undo", "chat turns", "chat revert-turn",
25
25
  "tags list", "tags add", "tags rename", "tags remove",
26
+ "manager list", "manager assign", "manager unassign",
26
27
  "git status", "git log", "git diff", "git stage", "git unstage", "git discard", "git commit",
27
28
  "git undo discard", "git undo commit", "git fetch", "git pull", "git push", "git publish",
28
29
  "git branch create", "git branch checkout", "git branch delete", "git branch merge",
@@ -0,0 +1,62 @@
1
+ import type { ApprovalFact, ApprovalSummary } from "../../shared/assistant-approval.ts";
2
+ import { MANAGER_ASSIGN_BYPASS, MANAGER_ASSIGN_CONSEQUENCE, MANAGER_TOOLS_NEXT_START } from "../../shared/assistant-managers.ts";
3
+ import { unnamedChat } from "../assistant-watch/watched-chat-title.ts";
4
+ import { chatFact, exactFact, fact, modeLabel, providerLabel } from "./assistant-approval-summary.ts";
5
+
6
+ /**
7
+ * The approval cards of `manager_assign` and `manager_unassign`. Pure: built from the chats as PPM
8
+ * records them, never from anything the agent said. The consequence is worded as the "Set as
9
+ * manager chat" dialog words it, so the card and the screen promise the same thing.
10
+ */
11
+
12
+ const HEADLINE_TITLE_CHARS = 80;
13
+ const cut = (text: string, max: number) => (text.length > max ? `${text.slice(0, max)}…` : text);
14
+ const nameOf = (title: string | null, sessionId: string) => cut(title || unnamedChat(sessionId), HEADLINE_TITLE_CHARS);
15
+
16
+ export const MANAGER_RULES_NOTE = "If the project has no manager rules yet, PPM writes them to .ppm/manager.md (and .ppm/.gitignore) "
17
+ + "in its folder; a file already there is held for you to review.";
18
+ export const MANAGER_REPLACED_NOTE = "The chat it replaces keeps its history; you then message it only with a card.";
19
+ export const MANAGER_UNASSIGN_NOTE = "The chat itself is kept, with its history and mode. PPM Assistant no longer messages it "
20
+ + "without asking, and .ppm/manager.md stays in the folder.";
21
+
22
+ interface ChatRef { sessionId: string; title: string | null }
23
+
24
+ export interface ManagerAssignApproval {
25
+ project: string;
26
+ chat: ChatRef & { providerId: string; lastActivity: number | null };
27
+ /** The mode the chat runs in; assigning leaves it as it is. */
28
+ permissionMode: string;
29
+ /** The project's manager chat that stops being it; null when the project has none. */
30
+ replaces: ChatRef | null;
31
+ }
32
+
33
+ export function managerAssignSummary(input: ManagerAssignApproval): ApprovalSummary {
34
+ const { chat, replaces } = input;
35
+ const bypass = input.permissionMode === "bypassPermissions";
36
+ const facts: ApprovalFact[] = [
37
+ exactFact("Project", input.project),
38
+ chatFact(chat.title, chat.sessionId),
39
+ fact("Provider", providerLabel(chat.providerId)),
40
+ fact("Last activity", chat.lastActivity === null ? "Unknown" : new Date(chat.lastActivity).toISOString()),
41
+ fact("Mode (unchanged)", modeLabel(input.permissionMode), bypass ? "warning" : undefined),
42
+ ...(replaces ? [{ ...chatFact(replaces.title, replaces.sessionId), label: "Stops being the manager", tone: "warning" as const }] : []),
43
+ ];
44
+ return {
45
+ headline: replaces
46
+ ? `Make "${nameOf(chat.title, chat.sessionId)}" the manager chat of "${input.project}", replacing "${nameOf(replaces.title, replaces.sessionId)}"`
47
+ : `Make "${nameOf(chat.title, chat.sessionId)}" the manager chat of "${input.project}"`,
48
+ facts,
49
+ warning: [
50
+ MANAGER_ASSIGN_CONSEQUENCE, ...(bypass ? [MANAGER_ASSIGN_BYPASS] : []), MANAGER_RULES_NOTE, MANAGER_TOOLS_NEXT_START,
51
+ ...(replaces ? [MANAGER_REPLACED_NOTE] : []),
52
+ ].join(" "),
53
+ };
54
+ }
55
+
56
+ export function managerUnassignSummary(input: { project: string; chat: ChatRef }): ApprovalSummary {
57
+ return {
58
+ headline: `Stop "${nameOf(input.chat.title, input.chat.sessionId)}" being the manager chat of "${input.project}"`,
59
+ facts: [exactFact("Project", input.project), chatFact(input.chat.title, input.chat.sessionId)],
60
+ warning: MANAGER_UNASSIGN_NOTE,
61
+ };
62
+ }
@@ -0,0 +1,43 @@
1
+ import { MANAGER_ASSIGN_TOOL, MANAGER_UNASSIGN_TOOL } from "../../shared/assistant-manager-tool-names.ts";
2
+ import type { AssistantToolDefinition } from "./assistant-tool-family.ts";
3
+
4
+ /**
5
+ * How the manager-chat tools are described to the agent, in the order of `MANAGER_TOOLS`.
6
+ * Definitions only, so the tool list can be built without loading what the tools reach (handlers:
7
+ * `assistant-manager-tools.ts`).
8
+ */
9
+
10
+ const object = (properties: Record<string, unknown>, required: string[] = []) => ({
11
+ type: "object", properties, required, additionalProperties: false,
12
+ });
13
+
14
+ const PROJECT = { type: "string", description: "Name of a registered PPM project, as projects_list gives it." };
15
+
16
+ export const MANAGER_TOOL_DEFINITIONS: readonly AssistantToolDefinition[] = [
17
+ {
18
+ name: MANAGER_ASSIGN_TOOL,
19
+ title: "Make an existing chat the project's manager chat",
20
+ description: "Make one of a project's existing chats its manager chat: the chat you then message without a card, "
21
+ + "also while the user is away. Prefer this to creating a new manager chat when the user points at a chat they "
22
+ + "already use. Always asks the user first; the card shows the chat, its mode and what the role allows. "
23
+ + "Refused, before asking, for a chat of another project, a PPM Assistant or design chat, a Codex chat (manager "
24
+ + "chats run on Claude), and while the project already has a manager chat unless `replace: true` (the card then "
25
+ + "names the chat that stops being the manager). The user can do the same from the chat's menu: \"Set as manager chat\".",
26
+ inputSchema: object({
27
+ project: PROJECT,
28
+ sessionId: { type: "string", description: "The chat's session id, from chat_list_sessions or chat_search." },
29
+ providerId: { type: "string", enum: ["claude", "codex"], description: "The chat's provider, when known." },
30
+ replace: { type: "boolean", description: "Take the role from the project's current manager chat (default false)." },
31
+ }, ["project", "sessionId"]),
32
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
33
+ },
34
+ {
35
+ name: MANAGER_UNASSIGN_TOOL,
36
+ title: "Stop a chat being the project's manager chat",
37
+ description: "Take the manager-chat role away from a project's manager chat. The chat itself is kept, with its "
38
+ + "history and mode; you then message it only with a card, like any other chat. Always asks the user first; "
39
+ + "refused when the project has no manager chat. The user can do the same from the chat's menu: \"Unset manager chat\".",
40
+ inputSchema: object({ project: PROJECT }, ["project"]),
41
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
42
+ },
43
+ ];
@@ -0,0 +1,89 @@
1
+ import { statSync } from "node:fs";
2
+ import type { Json } from "../mcp-http-endpoint.ts";
3
+ import { MANAGER_ASSIGN_TOOL, MANAGER_UNASSIGN_TOOL } from "../../shared/assistant-manager-tool-names.ts";
4
+ import { pinClaudeSessionDir } from "../agent-transcript/session-ownership.ts";
5
+ import { isUnattendedTurn } from "../chat-control/chat-control.ts";
6
+ import { createLogger } from "../logger.ts";
7
+ import { projectService } from "../project.service.ts";
8
+ import { resolveAssistantSessionTarget } from "./assistant-project-scope.ts";
9
+ import type { RouteRule } from "./assistant-route-rules.ts";
10
+ import type { FamilyHandler, FamilyHandlers, ToolContext } from "./assistant-tool-family.ts";
11
+ import { errorResult } from "./assistant-tool-output.ts";
12
+ import { managerAssign, managerUnassign, type ManagerToolDeps } from "./assistant-manager-write-tools.ts";
13
+
14
+ /**
15
+ * The manager-chat tools' handlers. They reach no route: they call `managerChats`, the service
16
+ * behind `PUT`/`DELETE /api/assistant/managers/:project` (the session list's "Set as manager chat"
17
+ * and "Unset manager chat"), which writes the rules files and announces the change on `/ws/global`
18
+ * itself.
19
+ */
20
+ export const MANAGER_ROUTES: readonly RouteRule[] = [];
21
+
22
+ const log = createLogger("assistant-managers");
23
+
24
+ /** When the chat last wrote its transcript; only a Claude chat can be a manager. */
25
+ function claudeLastActivity(sessionId: string, providerId: string, projectPath: string): number | null {
26
+ if (providerId !== "claude") return null;
27
+ const dir = pinClaudeSessionDir(sessionId, projectPath);
28
+ try {
29
+ return dir ? statSync(`${dir}.jsonl`).mtimeMs : null;
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+
35
+ /**
36
+ * PPM's own answers, built for each call. The manager service and the chat registry are loaded
37
+ * here rather than at the top — they reach the providers, which import the endpoint this family
38
+ * serves — so the handler's reads (`managerOf`, `mode`, `unassign`) can stay synchronous, as the
39
+ * card and its re-check need them to be.
40
+ */
41
+ export async function realManagerToolDeps(): Promise<ManagerToolDeps> {
42
+ const { managerChats } = await import("../assistant-managers/manager-chats.service.ts");
43
+ const { managerChatTitle } = await import("../assistant-managers/manager-chats-announce.ts");
44
+ const { chatTargetMode } = await import("../../server/ws/chat.ts");
45
+ return {
46
+ projects: () => projectService.list(),
47
+ target: (project, sessionId, providerId) => resolveAssistantSessionTarget(project, sessionId, providerId),
48
+ title: managerChatTitle,
49
+ lastActivity: claudeLastActivity,
50
+ mode: (sessionId) => chatTargetMode(sessionId, "claude").mode,
51
+ managerOf: (projectPath) => {
52
+ const row = managerChats.managerFor(projectPath);
53
+ return row ? { sessionId: row.sessionId, providerId: row.providerId } : null;
54
+ },
55
+ checkAssign: (projectName, sessionId) => managerChats.checkAssign(projectName, sessionId),
56
+ assign: async (projectName, sessionId, onlyIfNone) => {
57
+ const { row, replaced } = await managerChats.assign(projectName, sessionId, "assistant", { onlyIfNone });
58
+ log.info(`Manager chat of ${projectName} is now ${row.sessionId}${replaced ? ` (replaces ${replaced})` : ""}, set by the Assistant`);
59
+ return { replaced };
60
+ },
61
+ unassign: (projectName) => {
62
+ const removed = managerChats.unassign(projectName);
63
+ if (removed) log.info(`${projectName} has no manager chat now, unset by the Assistant`);
64
+ return removed;
65
+ },
66
+ unattended: (sessionId) => isUnattendedTurn(sessionId),
67
+ };
68
+ }
69
+
70
+ type DepsHandler = (ctx: ToolContext, args: Record<string, unknown>, deps: ManagerToolDeps) => Promise<Json>;
71
+
72
+ /** A handler over `deps`, answering an unexpected failure as a tool error rather than a 500. */
73
+ const bind = (run: DepsHandler, deps: () => Promise<ManagerToolDeps>): FamilyHandler => async (ctx, args) => {
74
+ try {
75
+ return await run(ctx, args, await deps());
76
+ } catch (e) {
77
+ return errorResult(`The manager tool failed: ${(e as Error).message}. Nothing more was done.`);
78
+ }
79
+ };
80
+
81
+ /** The handlers over given dependencies; tests pass their own. */
82
+ export function createManagerToolHandlers(deps: () => Promise<ManagerToolDeps> = realManagerToolDeps): FamilyHandlers {
83
+ return {
84
+ [MANAGER_ASSIGN_TOOL]: bind(managerAssign, deps),
85
+ [MANAGER_UNASSIGN_TOOL]: bind(managerUnassign, deps),
86
+ };
87
+ }
88
+
89
+ export const MANAGER_TOOL_HANDLERS: FamilyHandlers = createManagerToolHandlers();
@@ -0,0 +1,130 @@
1
+ import type { Json } from "../mcp-http-endpoint.ts";
2
+ import { MANAGER_ASSIGN_TOOL, MANAGER_UNASSIGN_TOOL } from "../../shared/assistant-manager-tool-names.ts";
3
+ import { MANAGER_CLAUDE_ONLY, MANAGER_PROVIDER_ID } from "../../shared/assistant-managers.ts";
4
+ import { UNATTENDED_TURN_REFUSAL } from "../chat-control/chat-control.ts";
5
+ import { managerAssignSummary, managerUnassignSummary } from "./assistant-approval-summary-manager.ts";
6
+ import { resolveAssistantProject, type AssistantProject, type AssistantSessionTarget, type Scoped } from "./assistant-project-scope.ts";
7
+ import type { ToolContext } from "./assistant-tool-family.ts";
8
+ import { errorResult, jsonResult, notApprovedResult } from "./assistant-tool-output.ts";
9
+
10
+ /**
11
+ * `manager_assign` and `manager_unassign`: find the project and the chat, refuse what must not
12
+ * happen before asking, build the card from PPM's records, ask, read again (the answer can come
13
+ * much later), and only then change the role — through `managerChats`, the service the session
14
+ * list's "Set as manager chat" and "Unset manager chat" call, so the rules files, the
15
+ * `assistant:managers_changed` broadcast and the session lists' badges are exactly the screen's.
16
+ */
17
+
18
+ export interface ManagerToolDeps {
19
+ projects(): AssistantProject[];
20
+ /** The chat proven to belong to `project`; Assistant sessions are refused here. */
21
+ target(project: AssistantProject, sessionId: unknown, providerId?: unknown): Scoped<AssistantSessionTarget>;
22
+ title(sessionId: string, providerId: string, projectPath: string): Promise<string | null>;
23
+ /** When the chat last wrote to its transcript (ms), or null when PPM cannot tell. */
24
+ lastActivity(sessionId: string, providerId: string, projectPath: string): number | null;
25
+ /** The permission mode the chat runs in. */
26
+ mode(sessionId: string): string;
27
+ /** The project's manager chat, or null. */
28
+ managerOf(projectPath: string): { sessionId: string; providerId: string } | null;
29
+ /** The service's own check (design chat, stored project, provider); throws its refusal. Writes nothing. */
30
+ checkAssign(projectName: string, sessionId: string): Promise<{ sessionId: string }>;
31
+ /** Assigns as the session list does; `onlyIfNone` refuses in the same step when a manager appeared. */
32
+ assign(projectName: string, sessionId: string, onlyIfNone: boolean): Promise<{ replaced: string | null }>;
33
+ unassign(projectName: string): boolean;
34
+ /** The Assistant's own turn was started by PPM (a watch report) and nobody has written in it since. */
35
+ unattended(assistantSessionId: string): boolean;
36
+ }
37
+
38
+ type Chat = AssistantSessionTarget & { title: string | null };
39
+
40
+ async function chatIn(project: AssistantProject, sessionId: unknown, providerId: unknown, deps: ManagerToolDeps): Promise<Scoped<Chat>> {
41
+ const target = deps.target(project, sessionId, providerId);
42
+ if (!target.ok) return target;
43
+ if (target.value.providerId !== MANAGER_PROVIDER_ID) return { ok: false, error: `${MANAGER_CLAUDE_ONLY}; that chat runs on Codex.` };
44
+ try {
45
+ await deps.checkAssign(project.name, target.value.sessionId);
46
+ } catch (e) {
47
+ return { ok: false, error: (e as Error).message };
48
+ }
49
+ return { ok: true, value: { ...target.value, title: await deps.title(target.value.sessionId, target.value.providerId, project.path) } };
50
+ }
51
+
52
+ const label = (title: string | null, sessionId: string) => (title ? `"${title}" (session ${sessionId})` : `session ${sessionId}`);
53
+
54
+ export async function managerAssign(ctx: ToolContext, args: Record<string, unknown>, deps: ManagerToolDeps): Promise<Json> {
55
+ if (deps.unattended(ctx.sessionId)) return errorResult(UNATTENDED_TURN_REFUSAL);
56
+ const project = resolveAssistantProject(args.project, () => deps.projects());
57
+ if (!project.ok) return errorResult(project.error);
58
+ if (args.providerId !== undefined && args.providerId !== MANAGER_PROVIDER_ID) return errorResult(`Not assigned: ${MANAGER_CLAUDE_ONLY}.`);
59
+ if (args.replace !== undefined && typeof args.replace !== "boolean") return errorResult("`replace`, when given, must be true or false.");
60
+ const replace = args.replace === true;
61
+ const p = project.value;
62
+ const found = await chatIn(p, args.sessionId, args.providerId, deps);
63
+ if (!found.ok) return errorResult(`Not assigned: ${found.error}`);
64
+ const chat = found.value;
65
+
66
+ const current = deps.managerOf(p.path);
67
+ if (current?.sessionId === chat.sessionId) return errorResult(`${label(chat.title, chat.sessionId)} already is the manager chat of "${p.name}"; nothing to do.`);
68
+ let replaces: { sessionId: string; title: string | null } | null = null;
69
+ if (current) {
70
+ const title = await deps.title(current.sessionId, current.providerId, p.path);
71
+ if (!replace) {
72
+ return errorResult(`Not assigned: "${p.name}" already has a manager chat, ${label(title, current.sessionId)}. `
73
+ + "Unassign it first with manager_unassign, or call again with `replace: true` if the user wants this chat to take its place.");
74
+ }
75
+ replaces = { sessionId: current.sessionId, title };
76
+ }
77
+
78
+ const verdict = await ctx.ask({
79
+ tool: MANAGER_ASSIGN_TOOL,
80
+ input: { project: p.name, sessionId: chat.sessionId, ...(replaces ? { replace: true } : {}) },
81
+ summary: managerAssignSummary({
82
+ project: p.name,
83
+ chat: { sessionId: chat.sessionId, title: chat.title, providerId: chat.providerId, lastActivity: deps.lastActivity(chat.sessionId, chat.providerId, p.path) },
84
+ permissionMode: deps.mode(chat.sessionId),
85
+ replaces,
86
+ }),
87
+ });
88
+ if (verdict.verdict !== "approved") return notApprovedResult(MANAGER_ASSIGN_TOOL, verdict, { project: p.name, sessionId: chat.sessionId });
89
+
90
+ // The card showed the chat and the project's manager as they stood: either may have changed since.
91
+ const again = await chatIn(p, chat.sessionId, chat.providerId, deps);
92
+ if (!again.ok) return errorResult(`Not assigned (stale): ${again.error}`);
93
+ const now = deps.managerOf(p.path);
94
+ if ((now?.sessionId ?? null) !== (current?.sessionId ?? null)) {
95
+ return errorResult(`Not assigned (stale): the manager chat of "${p.name}" changed while the card waited${now ? ` (it is session ${now.sessionId} now)` : ""}. Nothing was changed; ask again if this chat should still be the manager.`);
96
+ }
97
+ try {
98
+ const { replaced } = await deps.assign(p.name, chat.sessionId, replaces === null);
99
+ return jsonResult({
100
+ outcome: "assigned", project: p.name, sessionId: chat.sessionId, ...(replaced ? { replaced } : {}),
101
+ note: "Message it with send_to_session. Its manager tools arrive the next time it starts.",
102
+ });
103
+ } catch (e) {
104
+ return errorResult(`Not assigned: ${(e as Error).message}`);
105
+ }
106
+ }
107
+
108
+ export async function managerUnassign(ctx: ToolContext, args: Record<string, unknown>, deps: ManagerToolDeps): Promise<Json> {
109
+ if (deps.unattended(ctx.sessionId)) return errorResult(UNATTENDED_TURN_REFUSAL);
110
+ const project = resolveAssistantProject(args.project, () => deps.projects());
111
+ if (!project.ok) return errorResult(project.error);
112
+ const p = project.value;
113
+ const current = deps.managerOf(p.path);
114
+ if (!current) return errorResult(`"${p.name}" has no manager chat; there is nothing to unassign.`);
115
+ const title = await deps.title(current.sessionId, current.providerId, p.path);
116
+
117
+ const verdict = await ctx.ask({
118
+ tool: MANAGER_UNASSIGN_TOOL,
119
+ input: { project: p.name },
120
+ summary: managerUnassignSummary({ project: p.name, chat: { sessionId: current.sessionId, title } }),
121
+ });
122
+ if (verdict.verdict !== "approved") return notApprovedResult(MANAGER_UNASSIGN_TOOL, verdict, { project: p.name });
123
+
124
+ const now = deps.managerOf(p.path);
125
+ if (now?.sessionId !== current.sessionId) {
126
+ return errorResult(`Not unassigned (stale): the manager chat of "${p.name}" changed while the card waited. Nothing was changed; read the managers again and ask the user.`);
127
+ }
128
+ if (!deps.unassign(p.name)) return errorResult(`"${p.name}" had no manager chat by the time it was unassigned; nothing was changed.`);
129
+ return jsonResult({ outcome: "unassigned", project: p.name, sessionId: current.sessionId, note: "The chat is kept; it is no longer the manager." });
130
+ }
@@ -14,6 +14,7 @@ import { CHAT_TOOL_DEFINITIONS } from "./assistant-chat-tool-definitions.ts";
14
14
  import { DB_CONNECTION_TOOL_DEFINITIONS } from "./assistant-db-connection-tool-definitions.ts";
15
15
  import { NOTEBOOK_TOOL_DEFINITIONS } from "./assistant-notebook-tool-definitions.ts";
16
16
  import { TERMINAL_TYPE_TOOL_DEFINITION } from "./assistant-terminal-type-tool-definition.ts";
17
+ import { MANAGER_TOOL_DEFINITIONS } from "./assistant-manager-tool-definitions.ts";
17
18
 
18
19
  /**
19
20
  * The tools the Assistant's MCP endpoint serves, and how long a call may take. The names each
@@ -230,5 +231,6 @@ export const ASSISTANT_TOOL_DEFINITIONS = [
230
231
  ...PROJECT_TOOL_DEFINITIONS,
231
232
  ...CHAT_TOOL_DEFINITIONS,
232
233
  ...DB_CONNECTION_TOOL_DEFINITIONS,
234
+ ...MANAGER_TOOL_DEFINITIONS,
233
235
  TERMINAL_TYPE_TOOL_DEFINITION,
234
236
  ] as const;
@@ -15,10 +15,12 @@ import { CHAT_TOOLS } from "../../shared/assistant-chat-tool-names.ts";
15
15
  import { CHAT_ROUTES, CHAT_TOOL_HANDLERS } from "./assistant-chat-tools.ts";
16
16
  import { DB_CONNECTION_TOOLS } from "../../shared/assistant-db-connection-tool-names.ts";
17
17
  import { DB_CONNECTION_ROUTES, DB_CONNECTION_TOOL_HANDLERS } from "./assistant-db-connection-tools.ts";
18
+ import { MANAGER_TOOLS } from "../../shared/assistant-manager-tool-names.ts";
19
+ import { MANAGER_ROUTES, MANAGER_TOOL_HANDLERS } from "./assistant-manager-tools.ts";
18
20
 
19
21
  /**
20
22
  * The tool families that work through PPM's own routes — git, schedules, tunnels, projects, chats,
21
- * database connections — and how the
23
+ * database connections, manager chats — and how the
22
24
  * endpoint reaches them. Each family owns its files (names, definitions, handlers and the routes
23
25
  * it may call), so they can grow side by side without editing a shared switch.
24
26
  *
@@ -29,7 +31,7 @@ import { DB_CONNECTION_ROUTES, DB_CONNECTION_TOOL_HANDLERS } from "./assistant-d
29
31
  * import cycle with this dispatcher.
30
32
  */
31
33
 
32
- export type ToolFamily = "git" | "schedule" | "tunnel" | "project" | "chat" | "dbconn";
34
+ export type ToolFamily = "git" | "schedule" | "tunnel" | "project" | "chat" | "dbconn" | "manager";
33
35
 
34
36
  /** What one call of a family tool is handed. */
35
37
  export interface ToolContext {
@@ -85,6 +87,7 @@ export function toolFamilies(): readonly ToolFamilyEntry[] {
85
87
  { family: "project", tools: PROJECT_TOOLS, handlers: PROJECT_TOOL_HANDLERS, routes: PROJECT_ROUTES },
86
88
  { family: "chat", tools: CHAT_TOOLS, handlers: CHAT_TOOL_HANDLERS, routes: CHAT_ROUTES },
87
89
  { family: "dbconn", tools: DB_CONNECTION_TOOLS, handlers: DB_CONNECTION_TOOL_HANDLERS, routes: DB_CONNECTION_ROUTES },
90
+ { family: "manager", tools: MANAGER_TOOLS, handlers: MANAGER_TOOL_HANDLERS, routes: MANAGER_ROUTES },
88
91
  ];
89
92
  return families;
90
93
  }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The PPM Assistant's tools that give a project's manager-chat role to one of its existing chats,
3
+ * or take it away, in the order `tools/list` gives them. Spread into `ASSISTANT_TOOLS`
4
+ * (`assistant-tool-names.ts`); definitions and handlers live in
5
+ * `src/services/assistant-mcp/assistant-manager-*.ts`. Creating a new manager chat is not here:
6
+ * that is `create_session` with `manager: true`, on PPM's session tools.
7
+ */
8
+ export const MANAGER_ASSIGN_TOOL = "manager_assign";
9
+ export const MANAGER_UNASSIGN_TOOL = "manager_unassign";
10
+
11
+ export const MANAGER_TOOLS = [MANAGER_ASSIGN_TOOL, MANAGER_UNASSIGN_TOOL] as const;
@@ -10,6 +10,7 @@ import { TUNNEL_TOOLS } from "./assistant-tunnel-tool-names.ts";
10
10
  import { PROJECT_TOOLS } from "./assistant-project-tool-names.ts";
11
11
  import { CHAT_TOOLS } from "./assistant-chat-tool-names.ts";
12
12
  import { DB_CONNECTION_TOOLS } from "./assistant-db-connection-tool-names.ts";
13
+ import { MANAGER_TOOLS } from "./assistant-manager-tool-names.ts";
13
14
 
14
15
  export const PROJECTS_LIST_TOOL = "projects_list";
15
16
  export const PROJECT_ADD_TOOL = "project_add";
@@ -41,7 +42,7 @@ export const TERMINAL_TYPE_TOOL = "terminal_type";
41
42
 
42
43
  /**
43
44
  * Every tool the endpoint serves, in the order `tools/list` gives them. The git, schedule, tunnel,
44
- * project, chat and database-connection families keep their names in their own files and come next, in that order — the order
45
+ * project, chat, database-connection and manager-chat families keep their names in their own files and come next, in that order — the order
45
46
  * `ASSISTANT_TOOL_DEFINITIONS` spreads their definitions in — and `terminal_type` comes last. Opening and messaging the user's
46
47
  * chats is not here: the Assistant uses PPM's session tools (`ppm-sessions`) for that.
47
48
  */
@@ -54,7 +55,7 @@ export const ASSISTANT_TOOLS = [
54
55
  CHAT_WATCH_TOOL, CHAT_UNWATCH_TOOL, CHAT_LIST_WATCHES_TOOL,
55
56
  NOTEBOOK_ADD_TOOL, NOTEBOOK_EDIT_TOOL, NOTEBOOK_DELETE_TOOL,
56
57
  ...GIT_TOOLS, ...SCHEDULE_TOOLS, ...TUNNEL_TOOLS, ...PROJECT_TOOLS, ...CHAT_TOOLS, ...DB_CONNECTION_TOOLS,
57
- TERMINAL_TYPE_TOOL,
58
+ ...MANAGER_TOOLS, TERMINAL_TYPE_TOOL,
58
59
  ] as const;
59
60
  export type AssistantToolName = (typeof ASSISTANT_TOOLS)[number];
60
61