@linxiraos/pi-messenger 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +741 -676
  2. package/LICENSE +45 -0
  3. package/README.md +424 -424
  4. package/THIRD-PARTY-NOTICES.txt +22951 -0
  5. package/config-overlay.ts +175 -171
  6. package/config.ts +221 -209
  7. package/crew/agents/crew-plan-sync.md +66 -64
  8. package/crew/agents/crew-planner.md +173 -172
  9. package/crew/agents/crew-reviewer.md +58 -58
  10. package/crew/agents/crew-worker.md +130 -129
  11. package/crew/agents.ts +507 -434
  12. package/crew/handlers/coordination.ts +350 -332
  13. package/crew/handlers/plan.ts +988 -906
  14. package/crew/handlers/review.ts +354 -333
  15. package/crew/handlers/revise.ts +400 -376
  16. package/crew/handlers/status.ts +303 -295
  17. package/crew/handlers/sync.ts +237 -233
  18. package/crew/handlers/task.ts +820 -792
  19. package/crew/handlers/team.ts +294 -235
  20. package/crew/handlers/work.ts +467 -425
  21. package/crew/id-allocator.ts +30 -30
  22. package/crew/index.ts +297 -257
  23. package/crew/live-progress.ts +58 -58
  24. package/crew/lobby.ts +504 -473
  25. package/crew/prompt.ts +262 -252
  26. package/crew/registry.ts +114 -114
  27. package/crew/spawn.ts +135 -111
  28. package/crew/state-autonomous.ts +163 -164
  29. package/crew/state-planning.ts +264 -263
  30. package/crew/state.ts +20 -20
  31. package/crew/store.ts +646 -642
  32. package/crew/task-actions.ts +162 -131
  33. package/crew/team/store.ts +572 -479
  34. package/crew/team/subagent-roles.ts +105 -87
  35. package/crew/team/types.ts +50 -50
  36. package/crew/types.ts +194 -194
  37. package/crew/utils/artifacts.ts +57 -62
  38. package/crew/utils/config.ts +158 -156
  39. package/crew/utils/discover.ts +221 -219
  40. package/crew/utils/install.ts +94 -85
  41. package/crew/utils/migrations.ts +126 -0
  42. package/crew/utils/progress.ts +191 -187
  43. package/crew/utils/result.ts +16 -16
  44. package/crew/utils/risk-labels.ts +5 -7
  45. package/crew/utils/task-format.ts +14 -14
  46. package/crew/utils/team-roles.ts +44 -28
  47. package/crew/utils/truncate.ts +76 -79
  48. package/crew/utils/verdict.ts +55 -55
  49. package/editor-binary.ts +150 -0
  50. package/editor-command.ts +107 -0
  51. package/editor-target.ts +40 -0
  52. package/feed.ts +321 -268
  53. package/handlers.ts +1041 -1107
  54. package/index.ts +1314 -1206
  55. package/install.mjs +187 -189
  56. package/lib.ts +587 -467
  57. package/overlay-actions.ts +519 -511
  58. package/overlay-coordinator.ts +150 -150
  59. package/overlay-render.ts +770 -676
  60. package/overlay.ts +872 -830
  61. package/package.json +64 -60
  62. package/paths.ts +60 -0
  63. package/skills/pi-messenger-crew/SKILL.md +375 -347
  64. package/store.ts +1147 -1139
  65. package/teamagent-command.ts +321 -0
  66. package/vitest.config.ts +10 -10
@@ -0,0 +1,321 @@
1
+ /**
2
+ * /teamagent — register crew/team roles as spawnable subagents.
3
+ *
4
+ * Team roles live in the crew store as labels plus a prompt
5
+ * (TeamRoleDefinition: name/description/thinking/skills). That shape cannot
6
+ * be spawned: the task dispatch path needs an AgentDefinition, which requires
7
+ * tools/spawns/model and a system prompt. Rather than grow a second registry,
8
+ * this command writes the role into the standard agents directory
9
+ * (`<project>/.zeta/agents/` or `~/.zeta/agent/agents/`), where discovery
10
+ * already looks — project scope first, then user, then plugin packages.
11
+ *
12
+ * Scope defaults to project so a team definition travels with the repository;
13
+ * `--user` writes the global directory instead. Project scope requires the
14
+ * repository to opt in (trustProjectAgents in <project>/.zeta/pi-messenger.json),
15
+ * since project agents load for every session in that repository. A file per
16
+ * agent is the on-disk format the parser expects, so removal is just an unlink.
17
+ */
18
+
19
+ import * as fs from "node:fs";
20
+ import * as path from "node:path";
21
+ import type { ExtensionAPI, ExtensionCommandContext } from "@linxiraos/zeta";
22
+ import { getAgentDir } from "@linxiraos/pi-utils/dirs";
23
+ import * as teamStore from "./crew/team/store.ts";
24
+ import { isProjectAgentsTrusted } from "./config.ts";
25
+ import { getProjectConfigPath } from "./paths.ts";
26
+
27
+ /** Reserved names the agent parser rejects; mirrored so we fail early. */
28
+ const RESERVED_NAMES = new Set(["main", "sub"]);
29
+
30
+ const NAME_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
31
+
32
+ export interface TeamAgentScope {
33
+ /** "project" = <cwd>/.zeta/agents, "user" = ~/.zeta/agent/agents. */
34
+ kind: "project" | "user";
35
+ dir: string;
36
+ }
37
+
38
+ /** Resolve the target directory for a scope. */
39
+ export function resolveAgentsDir(scope: "project" | "user", cwd: string): TeamAgentScope {
40
+ if (scope === "user") {
41
+ // The runtime discovers user agents from getAgentDir()/agents
42
+ // (~/.zeta/agent/agents) — the same directory /teamagent must write.
43
+ return { kind: "user", dir: path.join(getAgentDir(), "agents") };
44
+ }
45
+ return { kind: "project", dir: path.join(path.resolve(cwd), ".zeta", "agents") };
46
+ }
47
+
48
+ function agentFilePath(dir: string, name: string): string {
49
+ return path.join(dir, `${name}.md`);
50
+ }
51
+
52
+ /** Quote a YAML scalar/sequence safely (JSON syntax is valid YAML flow). */
53
+ function yamlString(value: string | string[]): string {
54
+ return JSON.stringify(value);
55
+ }
56
+
57
+ /**
58
+ * Render an agent markdown file from a role. Only fields the role actually
59
+ * carries are emitted — the parser treats absent keys as "unset", and writing
60
+ * empty defaults would silently pin behaviour the role never asked for.
61
+ */
62
+ export function renderAgentMarkdown(role: {
63
+ name: string;
64
+ description: string;
65
+ model?: string;
66
+ thinking?: string;
67
+ skills?: string[];
68
+ prompt?: string;
69
+ }): string {
70
+ const lines: string[] = ["---", `name: ${yamlString(role.name)}`, `description: ${yamlString(role.description)}`];
71
+ if (role.model) lines.push(`model: ${yamlString(role.model)}`);
72
+ if (role.thinking) lines.push(`thinking: ${yamlString(role.thinking)}`);
73
+ if (role.skills && role.skills.length > 0) lines.push(`autoloadSkills: ${yamlString(role.skills)}`);
74
+ lines.push("---", "");
75
+ lines.push(role.prompt?.trim() || `You are the ${role.name} role. ${role.description}`);
76
+ return `${lines.join("\n")}\n`;
77
+ }
78
+
79
+ export interface AddResult {
80
+ ok: boolean;
81
+ message: string;
82
+ filePath?: string;
83
+ }
84
+
85
+ /** Write one role as an agent file. Refuses reserved/invalid names up front. */
86
+ export function addTeamAgent(
87
+ role: { name: string; description: string; model?: string; thinking?: string; skills?: string[]; prompt?: string },
88
+ scope: "project" | "user",
89
+ cwd: string,
90
+ ): AddResult {
91
+ const name = role.name.trim().toLowerCase();
92
+ if (!NAME_PATTERN.test(name)) {
93
+ return { ok: false, message: `Invalid agent name "${role.name}". Use lowercase letters, digits and hyphens.` };
94
+ }
95
+ if (RESERVED_NAMES.has(name)) {
96
+ return { ok: false, message: `"${name}" is reserved by the runtime and cannot be an agent name.` };
97
+ }
98
+ if (!role.description.trim()) {
99
+ return { ok: false, message: "A description is required (the dispatch path matches on it)." };
100
+ }
101
+ const { dir } = resolveAgentsDir(scope, cwd);
102
+ const filePath = agentFilePath(dir, name);
103
+ if (fs.existsSync(filePath)) {
104
+ return { ok: false, message: `${name} already exists at ${filePath}. Remove it first to replace it.` };
105
+ }
106
+ fs.mkdirSync(dir, { recursive: true });
107
+ fs.writeFileSync(filePath, renderAgentMarkdown({ ...role, name }), "utf8");
108
+ return { ok: true, message: `Registered ${name} (${scope} scope)`, filePath };
109
+ }
110
+
111
+ /** Remove an agent file from a scope. */
112
+ export function removeTeamAgent(name: string, scope: "project" | "user", cwd: string): AddResult {
113
+ const normalized = name.trim().toLowerCase();
114
+ const { dir } = resolveAgentsDir(scope, cwd);
115
+ const filePath = agentFilePath(dir, normalized);
116
+ if (!fs.existsSync(filePath)) {
117
+ return { ok: false, message: `No ${scope}-scope agent named ${normalized} (looked in ${dir}).` };
118
+ }
119
+ fs.rmSync(filePath);
120
+ return { ok: true, message: `Removed ${normalized} (${scope} scope)` };
121
+ }
122
+
123
+ /** List agent files in a scope. */
124
+ export function listTeamAgents(scope: "project" | "user", cwd: string): string[] {
125
+ const { dir } = resolveAgentsDir(scope, cwd);
126
+ let entries: string[];
127
+ try {
128
+ entries = fs.readdirSync(dir);
129
+ } catch {
130
+ return [];
131
+ }
132
+ return entries
133
+ .filter(f => f.endsWith(".md"))
134
+ .map(f => f.slice(0, -3))
135
+ .sort();
136
+ }
137
+
138
+ function twoCol(rows: Array<[string, string]>, gap = 2): string {
139
+ if (rows.length === 0) return "(none)";
140
+ const width = Math.max(...rows.map(([left]) => left.length));
141
+ return rows.map(([left, right]) => `${left.padEnd(width + gap)}${right}`).join("\n");
142
+ }
143
+
144
+ function profiles(cwd: string): string {
145
+ const active = teamStore.getActiveTeam(cwd);
146
+ const saved = teamStore.listProfiles();
147
+ const lines = [
148
+ `Active team: ${active ? `${active.name} (profile: ${active.profile ?? "default"})` : "(none — run /teamagent setup <name>)"}`,
149
+ "",
150
+ "Profiles:",
151
+ twoCol(saved.map(profile => [profile.name, profile.description ?? ""] as [string, string])),
152
+ ];
153
+ return lines.join("\n");
154
+ }
155
+
156
+ function roles(cwd: string): string {
157
+ const resolved = teamStore.resolveRoles(cwd);
158
+ const rows = Object.values(resolved)
159
+ .sort((a, b) => a.name.localeCompare(b.name))
160
+ .map(role => [role.name, role.description ?? ""] as [string, string]);
161
+ return `Roles (${rows.length}):\n${twoCol(rows)}`;
162
+ }
163
+
164
+ function status(cwd: string): string {
165
+ const team = teamStore.getActiveTeam(cwd);
166
+ if (!team) return "No active team in this project. Activate one with /teamagent setup <name>.";
167
+ const profile = teamStore.loadActiveProfile(cwd);
168
+ const counts = teamStore.memoryCounts(cwd);
169
+ const memory = Object.entries(counts)
170
+ .map(([type, count]) => `${type}=${count}`)
171
+ .join(" ");
172
+ return [
173
+ `Team: ${team.name}`,
174
+ `Profile: ${team.profile ?? "default"}`,
175
+ `Description: ${profile?.description ?? "(none)"}`,
176
+ `Memory: ${memory || "(empty)"}`,
177
+ `Charter: ${teamStore.readCharter(cwd) ? "set" : "(none)"}`,
178
+ ].join("\n");
179
+ }
180
+
181
+ function charter(cwd: string): string {
182
+ const text = teamStore.readCharter(cwd);
183
+ return text ?? "No charter yet. Create one with /teamagent charter <text>.";
184
+ }
185
+
186
+ const SUBCOMMANDS: Record<string, { description: string; run: (cwd: string, rest: string) => string }> = {
187
+ "profile.list": { description: "List team profiles and the active team", run: profiles },
188
+ roles: { description: "List resolvable roles (built-in + profile overrides)", run: roles },
189
+ status: { description: "Show active team, memory counts and charter state", run: status },
190
+ "charter.show": { description: "Print the active team charter", run: charter },
191
+ };
192
+
193
+ /** Registered slash command: /teamagent <add|list|remove> … */
194
+ export function registerTeamAgentCommand(pi: ExtensionAPI): void {
195
+ pi.registerCommand("teamagent", {
196
+ description: "Register crew roles as spawnable subagents (project or user scope)",
197
+ getArgumentCompletions: prefix => {
198
+ const token = prefix.trim().toLowerCase();
199
+ const verbs = ["roles", "status", "profile.list", "charter.show", "agents", "add", "remove"].filter(v =>
200
+ v.startsWith(token),
201
+ );
202
+ if (verbs.length === 0) return null;
203
+ return verbs.map(v => ({ value: `${v} `, label: v }));
204
+ },
205
+ handler: async (args: string, ctx: ExtensionCommandContext) => {
206
+ const [verb, ...rest] = args.trim().split(/\s+/).filter(Boolean);
207
+ const reply = (text: string) =>
208
+ pi.sendMessage({ customType: "teamagent_result", content: text, display: true }, { deliverAs: "aside" });
209
+
210
+ if (!verb) {
211
+ reply(
212
+ [
213
+ "Usage:",
214
+ " /teamagent roles list crew roles",
215
+ " /teamagent status active team, memory, charter",
216
+ " /teamagent profile.list team profiles",
217
+ " /teamagent charter.show print the charter",
218
+ " /teamagent agents list registered subagents",
219
+ " /teamagent add <role> [--user] register a crew role as a spawnable subagent",
220
+ " /teamagent remove <name> [--user]",
221
+ "",
222
+ "Default scope is the project (<cwd>/.zeta/agents, requires \"trustProjectAgents\": true in",
223
+ " <cwd>/.zeta/pi-messenger.json); --user writes ~/.zeta/agent/agents.",
224
+ ].join("\n"),
225
+ );
226
+ return;
227
+ }
228
+
229
+ const userScope = rest.includes("--user");
230
+ const positional = rest.filter(a => a !== "--user" && a !== "--project");
231
+ const scope = userScope ? "user" : "project";
232
+
233
+ // Read-only team state first: these verbs predate agent registration
234
+ // and answer from the crew store, not the agents directory.
235
+ const readOnly = SUBCOMMANDS[verb];
236
+ if (readOnly) {
237
+ try {
238
+ reply(readOnly.run(ctx.cwd, positional.join(" ")));
239
+ } catch (err) {
240
+ reply(`Failed to read team state: ${err instanceof Error ? err.message : String(err)}`);
241
+ }
242
+ return;
243
+ }
244
+
245
+ if (verb === "agents") {
246
+ const projectAgents = listTeamAgents("project", ctx.cwd);
247
+ const userAgents = listTeamAgents("user", ctx.cwd);
248
+ reply(
249
+ [
250
+ `Project scope (${resolveAgentsDir("project", ctx.cwd).dir}):`,
251
+ projectAgents.length ? projectAgents.map(a => ` ${a}`).join("\n") : " (none)",
252
+ "",
253
+ `User scope (${resolveAgentsDir("user", ctx.cwd).dir}):`,
254
+ userAgents.length ? userAgents.map(a => ` ${a}`).join("\n") : " (none)",
255
+ ].join("\n"),
256
+ );
257
+ return;
258
+ }
259
+
260
+ if (verb === "add") {
261
+ const roleName = positional[0];
262
+ if (!roleName) {
263
+ reply("Usage: /teamagent add <role> [--user]");
264
+ return;
265
+ }
266
+ if (scope === "project" && !isProjectAgentsTrusted(ctx.cwd)) {
267
+ // Project agents load for every session in this repository, so
268
+ // writing one requires an explicit per-project opt-in.
269
+ reply(
270
+ [
271
+ `Refused: this project has not opted in to project-level crew agents.`,
272
+ `Project agents (${resolveAgentsDir("project", ctx.cwd).dir}) are loaded automatically for every session in this repository.`,
273
+ `To enable, set "trustProjectAgents": true in ${getProjectConfigPath(ctx.cwd)}, then rerun /teamagent add.`,
274
+ `Or register a personal agent instead: /teamagent add ${roleName} --user`,
275
+ ].join("\n"),
276
+ );
277
+ return;
278
+ }
279
+ const role = teamStore.resolveRoles(ctx.cwd)[roleName];
280
+ if (!role) {
281
+ const known = Object.keys(teamStore.resolveRoles(ctx.cwd)).sort().join(", ");
282
+ reply(`Unknown role "${roleName}". Known roles: ${known}`);
283
+ return;
284
+ }
285
+ const result = addTeamAgent(
286
+ {
287
+ name: role.name,
288
+ description: role.description ?? `${role.name} crew role`,
289
+ model: role.model,
290
+ thinking: role.thinking,
291
+ skills: role.skills,
292
+ },
293
+ scope,
294
+ ctx.cwd,
295
+ );
296
+ // Agent discovery re-reads agent files on every task request, so a
297
+ // freshly written file is spawnable immediately — no restart and no
298
+ // /reload-plugins needed for spawning.
299
+ reply(
300
+ result.ok
301
+ ? `${result.message} → ${result.filePath}\nSpawnable now: discovery re-reads agent files on every task request.`
302
+ : result.message,
303
+ );
304
+ return;
305
+ }
306
+
307
+ if (verb === "remove") {
308
+ const name = positional[0];
309
+ if (!name) {
310
+ reply("Usage: /teamagent remove <name> [--user]");
311
+ return;
312
+ }
313
+ const result = removeTeamAgent(name, scope, ctx.cwd);
314
+ reply(result.message);
315
+ return;
316
+ }
317
+
318
+ reply(`Unknown subcommand "${verb}". Use add, list or remove.`);
319
+ },
320
+ });
321
+ }
package/vitest.config.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { defineConfig } from "vitest/config";
2
-
3
- export default defineConfig({
4
- test: {
5
- environment: "node",
6
- include: ["tests/**/*.test.ts"],
7
- clearMocks: true,
8
- restoreMocks: true,
9
- },
10
- });
1
+ import { defineConfig } from "vitest/config";
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ environment: "node",
6
+ include: ["tests/**/*.test.ts"],
7
+ clearMocks: true,
8
+ restoreMocks: true,
9
+ },
10
+ });