bylua-lspec-subagents 1.0.2

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 (86) hide show
  1. package/CHANGELOG.md +482 -0
  2. package/LICENSE +21 -0
  3. package/README.md +123 -0
  4. package/dist/agent-manager.d.ts +108 -0
  5. package/dist/agent-manager.js +391 -0
  6. package/dist/agent-runner.d.ts +95 -0
  7. package/dist/agent-runner.js +377 -0
  8. package/dist/agent-types.d.ts +58 -0
  9. package/dist/agent-types.js +157 -0
  10. package/dist/context.d.ts +12 -0
  11. package/dist/context.js +56 -0
  12. package/dist/cross-extension-rpc.d.ts +46 -0
  13. package/dist/cross-extension-rpc.js +76 -0
  14. package/dist/custom-agents.d.ts +14 -0
  15. package/dist/custom-agents.js +127 -0
  16. package/dist/default-agents.d.ts +12 -0
  17. package/dist/default-agents.js +489 -0
  18. package/dist/env.d.ts +6 -0
  19. package/dist/env.js +28 -0
  20. package/dist/group-join.d.ts +32 -0
  21. package/dist/group-join.js +116 -0
  22. package/dist/index.d.ts +13 -0
  23. package/dist/index.js +1863 -0
  24. package/dist/invocation-config.d.ts +22 -0
  25. package/dist/invocation-config.js +15 -0
  26. package/dist/memory.d.ts +49 -0
  27. package/dist/memory.js +151 -0
  28. package/dist/model-config-loader.d.ts +58 -0
  29. package/dist/model-config-loader.js +157 -0
  30. package/dist/model-resolver.d.ts +19 -0
  31. package/dist/model-resolver.js +62 -0
  32. package/dist/output-file.d.ts +24 -0
  33. package/dist/output-file.js +86 -0
  34. package/dist/prompts.d.ts +29 -0
  35. package/dist/prompts.js +65 -0
  36. package/dist/schedule-store.d.ts +38 -0
  37. package/dist/schedule-store.js +155 -0
  38. package/dist/schedule.d.ts +109 -0
  39. package/dist/schedule.js +338 -0
  40. package/dist/settings.d.ts +66 -0
  41. package/dist/settings.js +130 -0
  42. package/dist/skill-loader.d.ts +24 -0
  43. package/dist/skill-loader.js +93 -0
  44. package/dist/types.d.ts +164 -0
  45. package/dist/types.js +8 -0
  46. package/dist/ui/agent-widget.d.ts +134 -0
  47. package/dist/ui/agent-widget.js +451 -0
  48. package/dist/ui/conversation-viewer.d.ts +35 -0
  49. package/dist/ui/conversation-viewer.js +252 -0
  50. package/dist/ui/schedule-menu.d.ts +16 -0
  51. package/dist/ui/schedule-menu.js +95 -0
  52. package/dist/usage.d.ts +50 -0
  53. package/dist/usage.js +49 -0
  54. package/dist/worktree.d.ts +36 -0
  55. package/dist/worktree.js +139 -0
  56. package/install.sh +77 -0
  57. package/lspec-model-config.example.json +17 -0
  58. package/package.json +50 -0
  59. package/src/agent-manager.ts +483 -0
  60. package/src/agent-runner.ts +486 -0
  61. package/src/agent-types.ts +188 -0
  62. package/src/context.ts +58 -0
  63. package/src/cross-extension-rpc.ts +122 -0
  64. package/src/custom-agents.ts +136 -0
  65. package/src/default-agents.ts +501 -0
  66. package/src/env.ts +33 -0
  67. package/src/group-join.ts +141 -0
  68. package/src/index.ts +2032 -0
  69. package/src/invocation-config.ts +40 -0
  70. package/src/memory.ts +165 -0
  71. package/src/model-config-loader.ts +193 -0
  72. package/src/model-resolver.ts +81 -0
  73. package/src/output-file.ts +96 -0
  74. package/src/prompts.ts +91 -0
  75. package/src/schedule-store.ts +153 -0
  76. package/src/schedule.ts +365 -0
  77. package/src/settings.ts +186 -0
  78. package/src/skill-loader.ts +102 -0
  79. package/src/types.ts +179 -0
  80. package/src/ui/agent-widget.ts +533 -0
  81. package/src/ui/conversation-viewer.ts +261 -0
  82. package/src/ui/schedule-menu.ts +104 -0
  83. package/src/usage.ts +60 -0
  84. package/src/worktree.ts +162 -0
  85. package/uninstall.sh +55 -0
  86. package/update.sh +64 -0
package/src/context.ts ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * context.ts — Extract parent conversation context for subagent inheritance.
3
+ */
4
+
5
+ import type { ExtensionContext } from "@mariozechner/pi-coding-agent";
6
+
7
+ /** Extract text from a message content block array. */
8
+ export function extractText(content: unknown[]): string {
9
+ return content
10
+ .filter((c: any) => c.type === "text")
11
+ .map((c: any) => c.text ?? "")
12
+ .join("\n");
13
+ }
14
+
15
+ /**
16
+ * Build a text representation of the parent conversation context.
17
+ * Used when inherit_context is true to give the subagent visibility
18
+ * into what has been discussed/done so far.
19
+ */
20
+ export function buildParentContext(ctx: ExtensionContext): string {
21
+ const entries = ctx.sessionManager.getBranch();
22
+ if (!entries || entries.length === 0) return "";
23
+
24
+ const parts: string[] = [];
25
+
26
+ for (const entry of entries) {
27
+ if (entry.type === "message") {
28
+ const msg = entry.message;
29
+ if (msg.role === "user") {
30
+ const text = typeof msg.content === "string"
31
+ ? msg.content
32
+ : extractText(msg.content);
33
+ if (text.trim()) parts.push(`[User]: ${text.trim()}`);
34
+ } else if (msg.role === "assistant") {
35
+ const text = extractText(msg.content);
36
+ if (text.trim()) parts.push(`[Assistant]: ${text.trim()}`);
37
+ }
38
+ // Skip toolResult messages — too verbose for context
39
+ } else if (entry.type === "compaction") {
40
+ // Include compaction summaries — they're already condensed
41
+ if (entry.summary) {
42
+ parts.push(`[Summary]: ${entry.summary}`);
43
+ }
44
+ }
45
+ }
46
+
47
+ if (parts.length === 0) return "";
48
+
49
+ return `# Parent Conversation Context
50
+ The following is the conversation history from the parent session that spawned you.
51
+ Use this context to understand what has been discussed and decided so far.
52
+
53
+ ${parts.join("\n\n")}
54
+
55
+ ---
56
+ # Your Task (below)
57
+ `;
58
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Cross-extension RPC handlers for the subagents extension.
3
+ *
4
+ * Exposes ping, spawn, and stop RPCs over the pi.events event bus,
5
+ * using per-request scoped reply channels.
6
+ *
7
+ * Reply envelope follows pi-mono convention:
8
+ * success → { success: true, data?: T }
9
+ * error → { success: false, error: string }
10
+ */
11
+
12
+ import { type ModelRegistry, resolveModel } from "./model-resolver.js";
13
+
14
+ /** Minimal event bus interface needed by the RPC handlers. */
15
+ export interface EventBus {
16
+ on(event: string, handler: (data: unknown) => void): () => void;
17
+ emit(event: string, data: unknown): void;
18
+ }
19
+
20
+ /** RPC reply envelope — matches pi-mono's RpcResponse shape. */
21
+ export type RpcReply<T = void> =
22
+ | { success: true; data?: T }
23
+ | { success: false; error: string };
24
+
25
+ /** RPC protocol version — bumped when the envelope or method contracts change. */
26
+ export const PROTOCOL_VERSION = 2;
27
+
28
+ /** Minimal AgentManager interface needed by the spawn/stop RPCs. */
29
+ export interface SpawnCapable {
30
+ spawn(pi: unknown, ctx: unknown, type: string, prompt: string, options: any): string;
31
+ abort(id: string): boolean;
32
+ }
33
+
34
+ export interface RpcDeps {
35
+ events: EventBus;
36
+ pi: unknown; // passed through to manager.spawn
37
+ getCtx: () => unknown | undefined; // returns current ExtensionContext
38
+ manager: SpawnCapable;
39
+ }
40
+
41
+ export interface RpcHandle {
42
+ unsubPing: () => void;
43
+ unsubSpawn: () => void;
44
+ unsubStop: () => void;
45
+ }
46
+
47
+ /**
48
+ * Wire a single RPC handler: listen on `channel`, run `fn(params)`,
49
+ * emit the reply envelope on `channel:reply:${requestId}`.
50
+ */
51
+ function handleRpc<P extends { requestId: string }>(
52
+ events: EventBus,
53
+ channel: string,
54
+ fn: (params: P) => unknown | Promise<unknown>,
55
+ ): () => void {
56
+ return events.on(channel, async (raw: unknown) => {
57
+ const params = raw as P;
58
+ try {
59
+ const data = await fn(params);
60
+ const reply: { success: true; data?: unknown } = { success: true };
61
+ if (data !== undefined) reply.data = data;
62
+ events.emit(`${channel}:reply:${params.requestId}`, reply);
63
+ } catch (err: any) {
64
+ events.emit(`${channel}:reply:${params.requestId}`, {
65
+ success: false, error: err?.message ?? String(err),
66
+ });
67
+ }
68
+ });
69
+ }
70
+
71
+ /**
72
+ * Register ping, spawn, and stop RPC handlers on the event bus.
73
+ * Returns unsub functions for cleanup.
74
+ */
75
+ export function registerRpcHandlers(deps: RpcDeps): RpcHandle {
76
+ const { events, pi, getCtx, manager } = deps;
77
+
78
+ const unsubPing = handleRpc(events, "subagents:rpc:ping", () => {
79
+ return { version: PROTOCOL_VERSION };
80
+ });
81
+
82
+ const unsubSpawn = handleRpc<{ requestId: string; type: string; prompt: string; options?: any }>(
83
+ events, "subagents:rpc:spawn", ({ type, prompt, options }) => {
84
+ const ctx = getCtx();
85
+ if (!ctx) throw new Error("No active session");
86
+
87
+ // Cross-extension RPC callers (e.g. pi-tasks TaskExecute) naturally
88
+ // forward serializable values, so options.model can be a string like
89
+ // "openai-codex/gpt-5.5". Resolve it to a real Model instance here
90
+ // — same pattern the scheduler path already uses — so the spawned
91
+ // agent's auth lookup doesn't crash with "No API key found for
92
+ // undefined".
93
+ let normalizedOptions = options ?? {};
94
+ if (typeof normalizedOptions.model === "string") {
95
+ const registry = (ctx as { modelRegistry?: ModelRegistry }).modelRegistry;
96
+ if (!registry) {
97
+ throw new Error(
98
+ `Model override "${normalizedOptions.model}" provided but ctx.modelRegistry is unavailable`,
99
+ );
100
+ }
101
+ const resolved = resolveModel(normalizedOptions.model, registry);
102
+ if (typeof resolved === "string") {
103
+ // resolveModel returns a human-readable error string when the
104
+ // input doesn't match any available model. Surface it instead of
105
+ // silently falling back so the caller sees the auth/typo issue.
106
+ throw new Error(resolved);
107
+ }
108
+ normalizedOptions = { ...normalizedOptions, model: resolved };
109
+ }
110
+
111
+ return { id: manager.spawn(pi, ctx, type, prompt, normalizedOptions) };
112
+ },
113
+ );
114
+
115
+ const unsubStop = handleRpc<{ requestId: string; agentId: string }>(
116
+ events, "subagents:rpc:stop", ({ agentId }) => {
117
+ if (!manager.abort(agentId)) throw new Error("Agent not found");
118
+ },
119
+ );
120
+
121
+ return { unsubPing, unsubSpawn, unsubStop };
122
+ }
@@ -0,0 +1,136 @@
1
+ /**
2
+ * custom-agents.ts — Load user-defined agents from project (.pi/agents/) and global ($PI_CODING_AGENT_DIR/agents/, default ~/.pi/agent/agents/) locations.
3
+ */
4
+
5
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
6
+ import { basename, join } from "node:path";
7
+ import { getAgentDir, parseFrontmatter } from "@mariozechner/pi-coding-agent";
8
+ import { BUILTIN_TOOL_NAMES } from "./agent-types.js";
9
+ import type { AgentConfig, MemoryScope, ThinkingLevel } from "./types.js";
10
+
11
+ /**
12
+ * Scan for custom agent .md files from multiple locations.
13
+ * Discovery hierarchy (higher priority wins):
14
+ * 1. Project: <cwd>/.pi/agents/*.md
15
+ * 2. Global: $PI_CODING_AGENT_DIR/agents/*.md (default: ~/.pi/agent/agents/*.md)
16
+ *
17
+ * Project-level agents override global ones with the same name.
18
+ * Any name is allowed — names matching defaults (e.g. "Explore") override them.
19
+ */
20
+ export function loadCustomAgents(cwd: string): Map<string, AgentConfig> {
21
+ const globalDir = join(getAgentDir(), "agents");
22
+ const projectDir = join(cwd, ".pi", "agents");
23
+
24
+ const agents = new Map<string, AgentConfig>();
25
+ loadFromDir(globalDir, agents, "global"); // lower priority
26
+ loadFromDir(projectDir, agents, "project"); // higher priority (overwrites)
27
+ return agents;
28
+ }
29
+
30
+ /** Load agent configs from a directory into the map. */
31
+ function loadFromDir(dir: string, agents: Map<string, AgentConfig>, source: "project" | "global"): void {
32
+ if (!existsSync(dir)) return;
33
+
34
+ let files: string[];
35
+ try {
36
+ files = readdirSync(dir).filter(f => f.endsWith(".md"));
37
+ } catch {
38
+ return;
39
+ }
40
+
41
+ for (const file of files) {
42
+ const name = basename(file, ".md");
43
+
44
+ let content: string;
45
+ try {
46
+ content = readFileSync(join(dir, file), "utf-8");
47
+ } catch {
48
+ continue;
49
+ }
50
+
51
+ const { frontmatter: fm, body } = parseFrontmatter<Record<string, unknown>>(content);
52
+
53
+ agents.set(name, {
54
+ name,
55
+ displayName: str(fm.display_name),
56
+ description: str(fm.description) ?? name,
57
+ builtinToolNames: csvList(fm.tools, BUILTIN_TOOL_NAMES),
58
+ disallowedTools: csvListOptional(fm.disallowed_tools),
59
+ extensions: inheritField(fm.extensions ?? fm.inherit_extensions),
60
+ skills: inheritField(fm.skills ?? fm.inherit_skills),
61
+ model: str(fm.model),
62
+ thinking: str(fm.thinking) as ThinkingLevel | undefined,
63
+ maxTurns: nonNegativeInt(fm.max_turns),
64
+ systemPrompt: body.trim(),
65
+ promptMode: fm.prompt_mode === "append" ? "append" : "replace",
66
+ inheritContext: fm.inherit_context != null ? fm.inherit_context === true : undefined,
67
+ runInBackground: fm.run_in_background != null ? fm.run_in_background === true : undefined,
68
+ isolated: fm.isolated != null ? fm.isolated === true : undefined,
69
+ memory: parseMemory(fm.memory),
70
+ isolation: fm.isolation === "worktree" ? "worktree" : undefined,
71
+ enabled: fm.enabled !== false, // default true; explicitly false disables
72
+ source,
73
+ });
74
+ }
75
+ }
76
+
77
+ // ---- Field parsers ----
78
+ // All follow the same convention: omitted → default, "none"/empty → nothing, value → exact.
79
+
80
+ /** Extract a string or undefined. */
81
+ function str(val: unknown): string | undefined {
82
+ return typeof val === "string" ? val : undefined;
83
+ }
84
+
85
+ /** Extract a non-negative integer or undefined. 0 means unlimited for max_turns. */
86
+ function nonNegativeInt(val: unknown): number | undefined {
87
+ return typeof val === "number" && val >= 0 ? val : undefined;
88
+ }
89
+
90
+ /**
91
+ * Parse a raw CSV field value into items, or undefined if absent/empty/"none".
92
+ */
93
+ function parseCsvField(val: unknown): string[] | undefined {
94
+ if (val === undefined || val === null) return undefined;
95
+ const s = String(val).trim();
96
+ if (!s || s === "none") return undefined;
97
+ const items = s.split(",").map(t => t.trim()).filter(Boolean);
98
+ return items.length > 0 ? items : undefined;
99
+ }
100
+
101
+ /**
102
+ * Parse a comma-separated list field with defaults.
103
+ * omitted → defaults; "none"/empty → []; csv → listed items.
104
+ */
105
+ function csvList(val: unknown, defaults: string[]): string[] {
106
+ if (val === undefined || val === null) return defaults;
107
+ return parseCsvField(val) ?? [];
108
+ }
109
+
110
+ /**
111
+ * Parse an optional comma-separated list field.
112
+ * omitted → undefined; "none"/empty → undefined; csv → listed items.
113
+ */
114
+ function csvListOptional(val: unknown): string[] | undefined {
115
+ return parseCsvField(val);
116
+ }
117
+
118
+ /**
119
+ * Parse a memory scope field.
120
+ * omitted → undefined; "user"/"project"/"local" → MemoryScope.
121
+ */
122
+ function parseMemory(val: unknown): MemoryScope | undefined {
123
+ if (val === "user" || val === "project" || val === "local") return val;
124
+ return undefined;
125
+ }
126
+
127
+ /**
128
+ * Parse an inherit field (extensions, skills).
129
+ * omitted/true → true (inherit all); false/"none"/empty → false; csv → listed names.
130
+ */
131
+ function inheritField(val: unknown): true | string[] | false {
132
+ if (val === undefined || val === null || val === true) return true;
133
+ if (val === false || val === "none") return false;
134
+ const items = csvList(val, []);
135
+ return items.length > 0 ? items : false;
136
+ }