@by-lua/lspec-subagents 1.0.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 +482 -0
- package/LICENSE +21 -0
- package/README.md +123 -0
- package/dist/agent-manager.d.ts +108 -0
- package/dist/agent-manager.js +391 -0
- package/dist/agent-runner.d.ts +95 -0
- package/dist/agent-runner.js +377 -0
- package/dist/agent-types.d.ts +58 -0
- package/dist/agent-types.js +157 -0
- package/dist/context.d.ts +12 -0
- package/dist/context.js +56 -0
- package/dist/cross-extension-rpc.d.ts +46 -0
- package/dist/cross-extension-rpc.js +76 -0
- package/dist/custom-agents.d.ts +14 -0
- package/dist/custom-agents.js +127 -0
- package/dist/default-agents.d.ts +12 -0
- package/dist/default-agents.js +489 -0
- package/dist/env.d.ts +6 -0
- package/dist/env.js +28 -0
- package/dist/group-join.d.ts +32 -0
- package/dist/group-join.js +116 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +1863 -0
- package/dist/invocation-config.d.ts +22 -0
- package/dist/invocation-config.js +15 -0
- package/dist/memory.d.ts +49 -0
- package/dist/memory.js +151 -0
- package/dist/model-config-loader.d.ts +58 -0
- package/dist/model-config-loader.js +157 -0
- package/dist/model-resolver.d.ts +19 -0
- package/dist/model-resolver.js +62 -0
- package/dist/output-file.d.ts +24 -0
- package/dist/output-file.js +86 -0
- package/dist/prompts.d.ts +29 -0
- package/dist/prompts.js +65 -0
- package/dist/schedule-store.d.ts +38 -0
- package/dist/schedule-store.js +155 -0
- package/dist/schedule.d.ts +109 -0
- package/dist/schedule.js +338 -0
- package/dist/settings.d.ts +66 -0
- package/dist/settings.js +130 -0
- package/dist/skill-loader.d.ts +24 -0
- package/dist/skill-loader.js +93 -0
- package/dist/types.d.ts +164 -0
- package/dist/types.js +8 -0
- package/dist/ui/agent-widget.d.ts +134 -0
- package/dist/ui/agent-widget.js +451 -0
- package/dist/ui/conversation-viewer.d.ts +35 -0
- package/dist/ui/conversation-viewer.js +252 -0
- package/dist/ui/schedule-menu.d.ts +16 -0
- package/dist/ui/schedule-menu.js +95 -0
- package/dist/usage.d.ts +50 -0
- package/dist/usage.js +49 -0
- package/dist/worktree.d.ts +36 -0
- package/dist/worktree.js +139 -0
- package/install.sh +77 -0
- package/lspec-model-config.example.json +17 -0
- package/package.json +50 -0
- package/src/agent-manager.ts +483 -0
- package/src/agent-runner.ts +486 -0
- package/src/agent-types.ts +188 -0
- package/src/context.ts +58 -0
- package/src/cross-extension-rpc.ts +122 -0
- package/src/custom-agents.ts +136 -0
- package/src/default-agents.ts +501 -0
- package/src/env.ts +33 -0
- package/src/group-join.ts +141 -0
- package/src/index.ts +2032 -0
- package/src/invocation-config.ts +40 -0
- package/src/memory.ts +165 -0
- package/src/model-config-loader.ts +193 -0
- package/src/model-resolver.ts +81 -0
- package/src/output-file.ts +96 -0
- package/src/prompts.ts +91 -0
- package/src/schedule-store.ts +153 -0
- package/src/schedule.ts +365 -0
- package/src/settings.ts +186 -0
- package/src/skill-loader.ts +102 -0
- package/src/types.ts +179 -0
- package/src/ui/agent-widget.ts +533 -0
- package/src/ui/conversation-viewer.ts +261 -0
- package/src/ui/schedule-menu.ts +104 -0
- package/src/usage.ts +60 -0
- package/src/worktree.ts +162 -0
- package/uninstall.sh +55 -0
- package/update.sh +64 -0
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agent-runner.ts — Core execution engine: creates sessions, runs agents, collects results.
|
|
3
|
+
*/
|
|
4
|
+
import type { Model } from "@mariozechner/pi-ai";
|
|
5
|
+
import type { ExtensionContext } from "@mariozechner/pi-coding-agent";
|
|
6
|
+
import { type AgentSession, type ExtensionAPI } from "@mariozechner/pi-coding-agent";
|
|
7
|
+
import type { SubagentType, ThinkingLevel } from "./types.js";
|
|
8
|
+
/** Normalize max turns. undefined or 0 = unlimited, otherwise minimum 1. */
|
|
9
|
+
export declare function normalizeMaxTurns(n: number | undefined): number | undefined;
|
|
10
|
+
/** Get the default max turns value. undefined = unlimited. */
|
|
11
|
+
export declare function getDefaultMaxTurns(): number | undefined;
|
|
12
|
+
/** Set the default max turns value. undefined or 0 = unlimited, otherwise minimum 1. */
|
|
13
|
+
export declare function setDefaultMaxTurns(n: number | undefined): void;
|
|
14
|
+
/** Get the grace turns value. */
|
|
15
|
+
export declare function getGraceTurns(): number;
|
|
16
|
+
/** Set the grace turns value (minimum 1). */
|
|
17
|
+
export declare function setGraceTurns(n: number): void;
|
|
18
|
+
/** Info about a tool event in the subagent. */
|
|
19
|
+
export interface ToolActivity {
|
|
20
|
+
type: "start" | "end";
|
|
21
|
+
toolName: string;
|
|
22
|
+
}
|
|
23
|
+
export interface RunOptions {
|
|
24
|
+
/** ExtensionAPI instance — used for pi.exec() instead of execSync. */
|
|
25
|
+
pi: ExtensionAPI;
|
|
26
|
+
/** Manager-assigned id; suffixes session name to disambiguate parallel spawns (e.g. `Explore#a1b2c3d4`). */
|
|
27
|
+
agentId?: string;
|
|
28
|
+
model?: Model<any>;
|
|
29
|
+
maxTurns?: number;
|
|
30
|
+
signal?: AbortSignal;
|
|
31
|
+
isolated?: boolean;
|
|
32
|
+
inheritContext?: boolean;
|
|
33
|
+
thinkingLevel?: ThinkingLevel;
|
|
34
|
+
/** Override working directory (e.g. for worktree isolation). */
|
|
35
|
+
cwd?: string;
|
|
36
|
+
/** Called on tool start/end with activity info. */
|
|
37
|
+
onToolActivity?: (activity: ToolActivity) => void;
|
|
38
|
+
/** Called on streaming text deltas from the assistant response. */
|
|
39
|
+
onTextDelta?: (delta: string, fullText: string) => void;
|
|
40
|
+
onSessionCreated?: (session: AgentSession) => void;
|
|
41
|
+
/** Called at the end of each agentic turn with the cumulative count. */
|
|
42
|
+
onTurnEnd?: (turnCount: number) => void;
|
|
43
|
+
/**
|
|
44
|
+
* Called once per assistant message_end with that message's usage delta.
|
|
45
|
+
* Lets callers maintain a lifetime accumulator that survives compaction
|
|
46
|
+
* (which replaces session.state.messages and resets stats-derived sums).
|
|
47
|
+
*/
|
|
48
|
+
onAssistantUsage?: (usage: {
|
|
49
|
+
input: number;
|
|
50
|
+
output: number;
|
|
51
|
+
cacheWrite: number;
|
|
52
|
+
}) => void;
|
|
53
|
+
/**
|
|
54
|
+
* Called when the session successfully compacts. `tokensBefore` is upstream's
|
|
55
|
+
* pre-compaction context size estimate. Aborted compactions don't fire.
|
|
56
|
+
*/
|
|
57
|
+
onCompaction?: (info: {
|
|
58
|
+
reason: "manual" | "threshold" | "overflow";
|
|
59
|
+
tokensBefore: number;
|
|
60
|
+
}) => void;
|
|
61
|
+
}
|
|
62
|
+
export interface RunResult {
|
|
63
|
+
responseText: string;
|
|
64
|
+
session: AgentSession;
|
|
65
|
+
/** True if the agent was hard-aborted (max_turns + grace exceeded). */
|
|
66
|
+
aborted: boolean;
|
|
67
|
+
/** True if the agent was steered to wrap up (hit soft turn limit) but finished in time. */
|
|
68
|
+
steered: boolean;
|
|
69
|
+
}
|
|
70
|
+
export declare function runAgent(ctx: ExtensionContext, type: SubagentType, prompt: string, options: RunOptions): Promise<RunResult>;
|
|
71
|
+
/**
|
|
72
|
+
* Send a new prompt to an existing session (resume).
|
|
73
|
+
*/
|
|
74
|
+
export declare function resumeAgent(session: AgentSession, prompt: string, options?: {
|
|
75
|
+
onToolActivity?: (activity: ToolActivity) => void;
|
|
76
|
+
onAssistantUsage?: (usage: {
|
|
77
|
+
input: number;
|
|
78
|
+
output: number;
|
|
79
|
+
cacheWrite: number;
|
|
80
|
+
}) => void;
|
|
81
|
+
onCompaction?: (info: {
|
|
82
|
+
reason: "manual" | "threshold" | "overflow";
|
|
83
|
+
tokensBefore: number;
|
|
84
|
+
}) => void;
|
|
85
|
+
signal?: AbortSignal;
|
|
86
|
+
}): Promise<string>;
|
|
87
|
+
/**
|
|
88
|
+
* Send a steering message to a running subagent.
|
|
89
|
+
* The message will interrupt the agent after its current tool execution.
|
|
90
|
+
*/
|
|
91
|
+
export declare function steerAgent(session: AgentSession, message: string): Promise<void>;
|
|
92
|
+
/**
|
|
93
|
+
* Get the subagent's conversation messages as formatted text.
|
|
94
|
+
*/
|
|
95
|
+
export declare function getAgentConversation(session: AgentSession): string;
|
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agent-runner.ts — Core execution engine: creates sessions, runs agents, collects results.
|
|
3
|
+
*/
|
|
4
|
+
import { createAgentSession, DefaultResourceLoader, getAgentDir, SessionManager, SettingsManager, } from "@mariozechner/pi-coding-agent";
|
|
5
|
+
import { getAgentConfig, getConfig, getMemoryToolNames, getReadOnlyMemoryToolNames, getToolNamesForType } from "./agent-types.js";
|
|
6
|
+
import { buildParentContext, extractText } from "./context.js";
|
|
7
|
+
import { DEFAULT_AGENTS } from "./default-agents.js";
|
|
8
|
+
import { detectEnv } from "./env.js";
|
|
9
|
+
import { buildMemoryBlock, buildReadOnlyMemoryBlock } from "./memory.js";
|
|
10
|
+
import { buildAgentPrompt } from "./prompts.js";
|
|
11
|
+
import { preloadSkills } from "./skill-loader.js";
|
|
12
|
+
/** Names of tools registered by this extension that subagents must NOT inherit. */
|
|
13
|
+
const EXCLUDED_TOOL_NAMES = ["Agent", "get_subagent_result", "steer_subagent"];
|
|
14
|
+
/** Default max turns. undefined = unlimited (no turn limit). */
|
|
15
|
+
let defaultMaxTurns;
|
|
16
|
+
/** Normalize max turns. undefined or 0 = unlimited, otherwise minimum 1. */
|
|
17
|
+
export function normalizeMaxTurns(n) {
|
|
18
|
+
if (n == null || n === 0)
|
|
19
|
+
return undefined;
|
|
20
|
+
return Math.max(1, n);
|
|
21
|
+
}
|
|
22
|
+
/** Get the default max turns value. undefined = unlimited. */
|
|
23
|
+
export function getDefaultMaxTurns() { return defaultMaxTurns; }
|
|
24
|
+
/** Set the default max turns value. undefined or 0 = unlimited, otherwise minimum 1. */
|
|
25
|
+
export function setDefaultMaxTurns(n) { defaultMaxTurns = normalizeMaxTurns(n); }
|
|
26
|
+
/** Additional turns allowed after the soft limit steer message. */
|
|
27
|
+
let graceTurns = 5;
|
|
28
|
+
/** Get the grace turns value. */
|
|
29
|
+
export function getGraceTurns() { return graceTurns; }
|
|
30
|
+
/** Set the grace turns value (minimum 1). */
|
|
31
|
+
export function setGraceTurns(n) { graceTurns = Math.max(1, n); }
|
|
32
|
+
/**
|
|
33
|
+
* Try to find the right model for an agent type.
|
|
34
|
+
* Priority: explicit option > config.model > parent model.
|
|
35
|
+
*/
|
|
36
|
+
function resolveDefaultModel(parentModel, registry, configModel) {
|
|
37
|
+
if (configModel) {
|
|
38
|
+
const slashIdx = configModel.indexOf("/");
|
|
39
|
+
if (slashIdx !== -1) {
|
|
40
|
+
const provider = configModel.slice(0, slashIdx);
|
|
41
|
+
const modelId = configModel.slice(slashIdx + 1);
|
|
42
|
+
// Build a set of available model keys for fast lookup
|
|
43
|
+
const available = registry.getAvailable?.();
|
|
44
|
+
const availableKeys = available
|
|
45
|
+
? new Set(available.map((m) => `${m.provider}/${m.id}`))
|
|
46
|
+
: undefined;
|
|
47
|
+
const isAvailable = (p, id) => !availableKeys || availableKeys.has(`${p}/${id}`);
|
|
48
|
+
const found = registry.find(provider, modelId);
|
|
49
|
+
if (found && isAvailable(provider, modelId))
|
|
50
|
+
return found;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return parentModel;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Subscribe to a session and collect the last assistant message text.
|
|
57
|
+
* Returns an object with a `getText()` getter and an `unsubscribe` function.
|
|
58
|
+
*/
|
|
59
|
+
function collectResponseText(session) {
|
|
60
|
+
let text = "";
|
|
61
|
+
const unsubscribe = session.subscribe((event) => {
|
|
62
|
+
if (event.type === "message_start") {
|
|
63
|
+
text = "";
|
|
64
|
+
}
|
|
65
|
+
if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
|
|
66
|
+
text += event.assistantMessageEvent.delta;
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
return { getText: () => text, unsubscribe };
|
|
70
|
+
}
|
|
71
|
+
/** Get the last assistant text from the completed session history. */
|
|
72
|
+
function getLastAssistantText(session) {
|
|
73
|
+
for (let i = session.messages.length - 1; i >= 0; i--) {
|
|
74
|
+
const msg = session.messages[i];
|
|
75
|
+
if (msg.role !== "assistant")
|
|
76
|
+
continue;
|
|
77
|
+
const text = extractText(msg.content).trim();
|
|
78
|
+
if (text)
|
|
79
|
+
return text;
|
|
80
|
+
}
|
|
81
|
+
return "";
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Wire an AbortSignal to abort a session.
|
|
85
|
+
* Returns a cleanup function to remove the listener.
|
|
86
|
+
*/
|
|
87
|
+
function forwardAbortSignal(session, signal) {
|
|
88
|
+
if (!signal)
|
|
89
|
+
return () => { };
|
|
90
|
+
const onAbort = () => session.abort();
|
|
91
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
92
|
+
return () => signal.removeEventListener("abort", onAbort);
|
|
93
|
+
}
|
|
94
|
+
export async function runAgent(ctx, type, prompt, options) {
|
|
95
|
+
const config = getConfig(type);
|
|
96
|
+
const agentConfig = getAgentConfig(type);
|
|
97
|
+
// Resolve working directory: worktree override > parent cwd
|
|
98
|
+
const effectiveCwd = options.cwd ?? ctx.cwd;
|
|
99
|
+
const env = await detectEnv(options.pi, effectiveCwd);
|
|
100
|
+
// Get parent system prompt for append-mode agents
|
|
101
|
+
const parentSystemPrompt = ctx.getSystemPrompt();
|
|
102
|
+
// Build prompt extras (memory, skill preloading)
|
|
103
|
+
const extras = {};
|
|
104
|
+
// Resolve extensions/skills: isolated overrides to false
|
|
105
|
+
const extensions = options.isolated ? false : config.extensions;
|
|
106
|
+
const skills = options.isolated ? false : config.skills;
|
|
107
|
+
// Skill preloading: when skills is string[], preload their content into prompt
|
|
108
|
+
if (Array.isArray(skills)) {
|
|
109
|
+
const loaded = preloadSkills(skills, effectiveCwd);
|
|
110
|
+
if (loaded.length > 0) {
|
|
111
|
+
extras.skillBlocks = loaded;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
let toolNames = getToolNamesForType(type);
|
|
115
|
+
// Persistent memory: detect write capability and branch accordingly.
|
|
116
|
+
// Account for disallowedTools — a tool in the base set but on the denylist is not truly available.
|
|
117
|
+
if (agentConfig?.memory) {
|
|
118
|
+
const existingNames = new Set(toolNames);
|
|
119
|
+
const denied = agentConfig.disallowedTools ? new Set(agentConfig.disallowedTools) : undefined;
|
|
120
|
+
const effectivelyHas = (name) => existingNames.has(name) && !denied?.has(name);
|
|
121
|
+
const hasWriteTools = effectivelyHas("write") || effectivelyHas("edit");
|
|
122
|
+
if (hasWriteTools) {
|
|
123
|
+
// Read-write memory: add any missing memory tool names (read/write/edit)
|
|
124
|
+
const extraNames = getMemoryToolNames(existingNames);
|
|
125
|
+
if (extraNames.length > 0)
|
|
126
|
+
toolNames = [...toolNames, ...extraNames];
|
|
127
|
+
extras.memoryBlock = buildMemoryBlock(agentConfig.name, agentConfig.memory, effectiveCwd);
|
|
128
|
+
}
|
|
129
|
+
else {
|
|
130
|
+
// Read-only memory: only add read tool name, use read-only prompt
|
|
131
|
+
const extraNames = getReadOnlyMemoryToolNames(existingNames);
|
|
132
|
+
if (extraNames.length > 0)
|
|
133
|
+
toolNames = [...toolNames, ...extraNames];
|
|
134
|
+
extras.memoryBlock = buildReadOnlyMemoryBlock(agentConfig.name, agentConfig.memory, effectiveCwd);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
// Build system prompt from agent config
|
|
138
|
+
let systemPrompt;
|
|
139
|
+
if (agentConfig) {
|
|
140
|
+
systemPrompt = buildAgentPrompt(agentConfig, effectiveCwd, env, parentSystemPrompt, extras);
|
|
141
|
+
}
|
|
142
|
+
else {
|
|
143
|
+
// Unknown type fallback: spread the canonical orchestrator config (defensive —
|
|
144
|
+
// unreachable in practice since index.ts resolves unknown types before calling runAgent).
|
|
145
|
+
const fallback = DEFAULT_AGENTS.get("orchestrator");
|
|
146
|
+
if (!fallback)
|
|
147
|
+
throw new Error(`No fallback config available for unknown type "${type}"`);
|
|
148
|
+
systemPrompt = buildAgentPrompt({ ...fallback, name: type }, effectiveCwd, env, parentSystemPrompt, extras);
|
|
149
|
+
}
|
|
150
|
+
// When skills is string[], we've already preloaded them into the prompt.
|
|
151
|
+
// Still pass noSkills: true since we don't need the skill loader to load them again.
|
|
152
|
+
const noSkills = skills === false || Array.isArray(skills);
|
|
153
|
+
const agentDir = getAgentDir();
|
|
154
|
+
// Load extensions/skills: true or string[] → load; false → don't.
|
|
155
|
+
// Suppress AGENTS.md/CLAUDE.md and APPEND_SYSTEM.md — upstream's
|
|
156
|
+
// buildSystemPrompt() re-appends both AFTER systemPromptOverride, which
|
|
157
|
+
// would defeat prompt_mode: replace and isolated: true. Parent context, if
|
|
158
|
+
// wanted, reaches the subagent via prompt_mode: append (parentSystemPrompt
|
|
159
|
+
// is embedded in systemPromptOverride) or inherit_context (conversation).
|
|
160
|
+
const loader = new DefaultResourceLoader({
|
|
161
|
+
cwd: effectiveCwd,
|
|
162
|
+
agentDir,
|
|
163
|
+
noExtensions: extensions === false,
|
|
164
|
+
noSkills,
|
|
165
|
+
noPromptTemplates: true,
|
|
166
|
+
noThemes: true,
|
|
167
|
+
noContextFiles: true,
|
|
168
|
+
systemPromptOverride: () => systemPrompt,
|
|
169
|
+
appendSystemPromptOverride: () => [],
|
|
170
|
+
});
|
|
171
|
+
await loader.reload();
|
|
172
|
+
// Resolve model: explicit option > config.model > parent model
|
|
173
|
+
const model = options.model ?? resolveDefaultModel(ctx.model, ctx.modelRegistry, agentConfig?.model);
|
|
174
|
+
// Resolve thinking level: explicit option > agent config > undefined (inherit)
|
|
175
|
+
const thinkingLevel = options.thinkingLevel ?? agentConfig?.thinking;
|
|
176
|
+
const sessionOpts = {
|
|
177
|
+
cwd: effectiveCwd,
|
|
178
|
+
agentDir,
|
|
179
|
+
sessionManager: SessionManager.inMemory(effectiveCwd),
|
|
180
|
+
settingsManager: SettingsManager.create(effectiveCwd, agentDir),
|
|
181
|
+
modelRegistry: ctx.modelRegistry,
|
|
182
|
+
model,
|
|
183
|
+
tools: toolNames,
|
|
184
|
+
resourceLoader: loader,
|
|
185
|
+
};
|
|
186
|
+
if (thinkingLevel) {
|
|
187
|
+
sessionOpts.thinkingLevel = thinkingLevel;
|
|
188
|
+
}
|
|
189
|
+
const { session } = await createAgentSession(sessionOpts);
|
|
190
|
+
const baseSessionName = agentConfig?.name ?? type;
|
|
191
|
+
session.setSessionName(options.agentId ? `${baseSessionName}#${options.agentId.slice(0, 8)}` : baseSessionName);
|
|
192
|
+
// Build disallowed tools set from agent config
|
|
193
|
+
const disallowedSet = agentConfig?.disallowedTools
|
|
194
|
+
? new Set(agentConfig.disallowedTools)
|
|
195
|
+
: undefined;
|
|
196
|
+
// Filter active tools: remove our own tools to prevent nesting,
|
|
197
|
+
// apply extension allowlist if specified, and apply disallowedTools denylist
|
|
198
|
+
if (extensions !== false) {
|
|
199
|
+
const builtinToolNameSet = new Set(toolNames);
|
|
200
|
+
const activeTools = session.getActiveToolNames().filter((t) => {
|
|
201
|
+
if (EXCLUDED_TOOL_NAMES.includes(t))
|
|
202
|
+
return false;
|
|
203
|
+
if (disallowedSet?.has(t))
|
|
204
|
+
return false;
|
|
205
|
+
if (builtinToolNameSet.has(t))
|
|
206
|
+
return true;
|
|
207
|
+
if (Array.isArray(extensions)) {
|
|
208
|
+
return extensions.some(ext => t.startsWith(ext) || t.includes(ext));
|
|
209
|
+
}
|
|
210
|
+
return true;
|
|
211
|
+
});
|
|
212
|
+
session.setActiveToolsByName(activeTools);
|
|
213
|
+
}
|
|
214
|
+
else if (disallowedSet) {
|
|
215
|
+
// Even with extensions disabled, apply denylist to built-in tools
|
|
216
|
+
const activeTools = session.getActiveToolNames().filter(t => !disallowedSet.has(t));
|
|
217
|
+
session.setActiveToolsByName(activeTools);
|
|
218
|
+
}
|
|
219
|
+
// Bind extensions so that session_start fires and extensions can initialize
|
|
220
|
+
// (e.g. loading credentials, setting up state). Placed after tool filtering
|
|
221
|
+
// so extension-provided skills/prompts from extendResourcesFromExtensions()
|
|
222
|
+
// respect the active tool set. All ExtensionBindings fields are optional.
|
|
223
|
+
await session.bindExtensions({
|
|
224
|
+
onError: (err) => {
|
|
225
|
+
options.onToolActivity?.({
|
|
226
|
+
type: "end",
|
|
227
|
+
toolName: `extension-error:${err.extensionPath}`,
|
|
228
|
+
});
|
|
229
|
+
},
|
|
230
|
+
});
|
|
231
|
+
options.onSessionCreated?.(session);
|
|
232
|
+
// Track turns for graceful max_turns enforcement
|
|
233
|
+
let turnCount = 0;
|
|
234
|
+
const maxTurns = normalizeMaxTurns(options.maxTurns ?? agentConfig?.maxTurns ?? defaultMaxTurns);
|
|
235
|
+
let softLimitReached = false;
|
|
236
|
+
let aborted = false;
|
|
237
|
+
let currentMessageText = "";
|
|
238
|
+
const unsubTurns = session.subscribe((event) => {
|
|
239
|
+
if (event.type === "turn_end") {
|
|
240
|
+
turnCount++;
|
|
241
|
+
options.onTurnEnd?.(turnCount);
|
|
242
|
+
if (maxTurns != null) {
|
|
243
|
+
if (!softLimitReached && turnCount >= maxTurns) {
|
|
244
|
+
softLimitReached = true;
|
|
245
|
+
session.steer("You have reached your turn limit. Wrap up immediately — provide your final answer now.");
|
|
246
|
+
}
|
|
247
|
+
else if (softLimitReached && turnCount >= maxTurns + graceTurns) {
|
|
248
|
+
aborted = true;
|
|
249
|
+
session.abort();
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
if (event.type === "message_start") {
|
|
254
|
+
currentMessageText = "";
|
|
255
|
+
}
|
|
256
|
+
if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
|
|
257
|
+
currentMessageText += event.assistantMessageEvent.delta;
|
|
258
|
+
options.onTextDelta?.(event.assistantMessageEvent.delta, currentMessageText);
|
|
259
|
+
}
|
|
260
|
+
if (event.type === "tool_execution_start") {
|
|
261
|
+
options.onToolActivity?.({ type: "start", toolName: event.toolName });
|
|
262
|
+
}
|
|
263
|
+
if (event.type === "tool_execution_end") {
|
|
264
|
+
options.onToolActivity?.({ type: "end", toolName: event.toolName });
|
|
265
|
+
}
|
|
266
|
+
if (event.type === "message_end" && event.message.role === "assistant") {
|
|
267
|
+
const u = event.message.usage;
|
|
268
|
+
if (u)
|
|
269
|
+
options.onAssistantUsage?.({
|
|
270
|
+
input: u.input ?? 0,
|
|
271
|
+
output: u.output ?? 0,
|
|
272
|
+
cacheWrite: u.cacheWrite ?? 0,
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
if (event.type === "compaction_end" && !event.aborted && event.result) {
|
|
276
|
+
options.onCompaction?.({ reason: event.reason, tokensBefore: event.result.tokensBefore });
|
|
277
|
+
}
|
|
278
|
+
});
|
|
279
|
+
const collector = collectResponseText(session);
|
|
280
|
+
const cleanupAbort = forwardAbortSignal(session, options.signal);
|
|
281
|
+
// Build the effective prompt: optionally prepend parent context
|
|
282
|
+
let effectivePrompt = prompt;
|
|
283
|
+
if (options.inheritContext) {
|
|
284
|
+
const parentContext = buildParentContext(ctx);
|
|
285
|
+
if (parentContext) {
|
|
286
|
+
effectivePrompt = parentContext + prompt;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
try {
|
|
290
|
+
await session.prompt(effectivePrompt);
|
|
291
|
+
}
|
|
292
|
+
finally {
|
|
293
|
+
unsubTurns();
|
|
294
|
+
collector.unsubscribe();
|
|
295
|
+
cleanupAbort();
|
|
296
|
+
}
|
|
297
|
+
const responseText = collector.getText().trim() || getLastAssistantText(session);
|
|
298
|
+
return { responseText, session, aborted, steered: softLimitReached };
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Send a new prompt to an existing session (resume).
|
|
302
|
+
*/
|
|
303
|
+
export async function resumeAgent(session, prompt, options = {}) {
|
|
304
|
+
const collector = collectResponseText(session);
|
|
305
|
+
const cleanupAbort = forwardAbortSignal(session, options.signal);
|
|
306
|
+
const unsubEvents = (options.onToolActivity || options.onAssistantUsage || options.onCompaction)
|
|
307
|
+
? session.subscribe((event) => {
|
|
308
|
+
if (event.type === "tool_execution_start")
|
|
309
|
+
options.onToolActivity?.({ type: "start", toolName: event.toolName });
|
|
310
|
+
if (event.type === "tool_execution_end")
|
|
311
|
+
options.onToolActivity?.({ type: "end", toolName: event.toolName });
|
|
312
|
+
if (event.type === "message_end" && event.message.role === "assistant") {
|
|
313
|
+
const u = event.message.usage;
|
|
314
|
+
if (u)
|
|
315
|
+
options.onAssistantUsage?.({
|
|
316
|
+
input: u.input ?? 0,
|
|
317
|
+
output: u.output ?? 0,
|
|
318
|
+
cacheWrite: u.cacheWrite ?? 0,
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
if (event.type === "compaction_end" && !event.aborted && event.result) {
|
|
322
|
+
options.onCompaction?.({ reason: event.reason, tokensBefore: event.result.tokensBefore });
|
|
323
|
+
}
|
|
324
|
+
})
|
|
325
|
+
: () => { };
|
|
326
|
+
try {
|
|
327
|
+
await session.prompt(prompt);
|
|
328
|
+
}
|
|
329
|
+
finally {
|
|
330
|
+
collector.unsubscribe();
|
|
331
|
+
unsubEvents();
|
|
332
|
+
cleanupAbort();
|
|
333
|
+
}
|
|
334
|
+
return collector.getText().trim() || getLastAssistantText(session);
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Send a steering message to a running subagent.
|
|
338
|
+
* The message will interrupt the agent after its current tool execution.
|
|
339
|
+
*/
|
|
340
|
+
export async function steerAgent(session, message) {
|
|
341
|
+
await session.steer(message);
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Get the subagent's conversation messages as formatted text.
|
|
345
|
+
*/
|
|
346
|
+
export function getAgentConversation(session) {
|
|
347
|
+
const parts = [];
|
|
348
|
+
for (const msg of session.messages) {
|
|
349
|
+
if (msg.role === "user") {
|
|
350
|
+
const text = typeof msg.content === "string"
|
|
351
|
+
? msg.content
|
|
352
|
+
: extractText(msg.content);
|
|
353
|
+
if (text.trim())
|
|
354
|
+
parts.push(`[User]: ${text.trim()}`);
|
|
355
|
+
}
|
|
356
|
+
else if (msg.role === "assistant") {
|
|
357
|
+
const textParts = [];
|
|
358
|
+
const toolCalls = [];
|
|
359
|
+
for (const c of msg.content) {
|
|
360
|
+
if (c.type === "text" && c.text)
|
|
361
|
+
textParts.push(c.text);
|
|
362
|
+
else if (c.type === "toolCall")
|
|
363
|
+
toolCalls.push(` Tool: ${c.name ?? c.toolName ?? "unknown"}`);
|
|
364
|
+
}
|
|
365
|
+
if (textParts.length > 0)
|
|
366
|
+
parts.push(`[Assistant]: ${textParts.join("\n")}`);
|
|
367
|
+
if (toolCalls.length > 0)
|
|
368
|
+
parts.push(`[Tool Calls]:\n${toolCalls.join("\n")}`);
|
|
369
|
+
}
|
|
370
|
+
else if (msg.role === "toolResult") {
|
|
371
|
+
const text = extractText(msg.content);
|
|
372
|
+
const truncated = text.length > 200 ? text.slice(0, 200) + "..." : text;
|
|
373
|
+
parts.push(`[Tool Result (${msg.toolName})]: ${truncated}`);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
return parts.join("\n\n");
|
|
377
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agent-types.ts — Unified agent type registry.
|
|
3
|
+
*
|
|
4
|
+
* Merges embedded default agents with user-defined agents from .pi/agents/*.md.
|
|
5
|
+
* User agents override defaults with the same name. Disabled agents are kept but excluded from spawning.
|
|
6
|
+
*
|
|
7
|
+
* L-Spec addition: model placeholders ({{model:agent_name}}) are resolved at registration
|
|
8
|
+
* from lspec-model-config.json via model-config-loader.ts.
|
|
9
|
+
*/
|
|
10
|
+
import type { AgentConfig } from "./types.js";
|
|
11
|
+
/** All known built-in tool names. */
|
|
12
|
+
export declare const BUILTIN_TOOL_NAMES: string[];
|
|
13
|
+
/**
|
|
14
|
+
* Register agents into the unified registry.
|
|
15
|
+
* Starts with DEFAULT_AGENTS, then overlays user agents (overrides defaults with same name).
|
|
16
|
+
* Model placeholders ({{model:name}}) are resolved from lspec-model-config.json.
|
|
17
|
+
* Disabled agents (enabled === false) are kept in the registry but excluded from spawning.
|
|
18
|
+
*/
|
|
19
|
+
export declare function registerAgents(userAgents: Map<string, AgentConfig>): void;
|
|
20
|
+
/**
|
|
21
|
+
* Reload the model config from disk (in case it changed since session start).
|
|
22
|
+
*/
|
|
23
|
+
export declare function reloadModelConfig(cwd?: string): void;
|
|
24
|
+
/** Get the current model config (for UI display / debugging). */
|
|
25
|
+
export declare function getModelConfig(): import("./model-config-loader.js").ModelConfig;
|
|
26
|
+
/** Resolve a type name case-insensitively. Returns the canonical key or undefined. */
|
|
27
|
+
export declare function resolveType(name: string): string | undefined;
|
|
28
|
+
/** Get the agent config for a type (case-insensitive). */
|
|
29
|
+
export declare function getAgentConfig(name: string): AgentConfig | undefined;
|
|
30
|
+
/** Get all enabled type names (for spawning and tool descriptions). */
|
|
31
|
+
export declare function getAvailableTypes(): string[];
|
|
32
|
+
/** Get all type names including disabled (for UI listing). */
|
|
33
|
+
export declare function getAllTypes(): string[];
|
|
34
|
+
/** Get names of default agents currently in the registry. */
|
|
35
|
+
export declare function getDefaultAgentNames(): string[];
|
|
36
|
+
/** Get names of user-defined agents (non-defaults) currently in the registry. */
|
|
37
|
+
export declare function getUserAgentNames(): string[];
|
|
38
|
+
/** Check if a type is valid and enabled (case-insensitive). */
|
|
39
|
+
export declare function isValidType(type: string): boolean;
|
|
40
|
+
/**
|
|
41
|
+
* Get memory tool names (read/write/edit) not already in the provided set.
|
|
42
|
+
*/
|
|
43
|
+
export declare function getMemoryToolNames(existingToolNames: Set<string>): string[];
|
|
44
|
+
/**
|
|
45
|
+
* Get read-only memory tool names not already in the provided set.
|
|
46
|
+
*/
|
|
47
|
+
export declare function getReadOnlyMemoryToolNames(existingToolNames: Set<string>): string[];
|
|
48
|
+
/** Get built-in tool names for a type (case-insensitive). */
|
|
49
|
+
export declare function getToolNamesForType(type: string): string[];
|
|
50
|
+
/** Get config for a type (case-insensitive, returns a SubagentTypeConfig-compatible object). Falls back to orchestrator. */
|
|
51
|
+
export declare function getConfig(type: string): {
|
|
52
|
+
displayName: string;
|
|
53
|
+
description: string;
|
|
54
|
+
builtinToolNames: string[];
|
|
55
|
+
extensions: true | string[] | false;
|
|
56
|
+
skills: true | string[] | false;
|
|
57
|
+
promptMode: "replace" | "append";
|
|
58
|
+
};
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agent-types.ts — Unified agent type registry.
|
|
3
|
+
*
|
|
4
|
+
* Merges embedded default agents with user-defined agents from .pi/agents/*.md.
|
|
5
|
+
* User agents override defaults with the same name. Disabled agents are kept but excluded from spawning.
|
|
6
|
+
*
|
|
7
|
+
* L-Spec addition: model placeholders ({{model:agent_name}}) are resolved at registration
|
|
8
|
+
* from lspec-model-config.json via model-config-loader.ts.
|
|
9
|
+
*/
|
|
10
|
+
import { DEFAULT_AGENTS } from "./default-agents.js";
|
|
11
|
+
import { loadModelConfig, resolveAllPlaceholders } from "./model-config-loader.js";
|
|
12
|
+
/** All known built-in tool names. */
|
|
13
|
+
export const BUILTIN_TOOL_NAMES = ["read", "bash", "edit", "write", "grep", "find", "ls"];
|
|
14
|
+
/** Unified runtime registry of all agents (defaults + user-defined). */
|
|
15
|
+
const agents = new Map();
|
|
16
|
+
/** Cached model config, loaded once per session. */
|
|
17
|
+
let modelConfig = loadModelConfig(process.cwd());
|
|
18
|
+
/**
|
|
19
|
+
* Register agents into the unified registry.
|
|
20
|
+
* Starts with DEFAULT_AGENTS, then overlays user agents (overrides defaults with same name).
|
|
21
|
+
* Model placeholders ({{model:name}}) are resolved from lspec-model-config.json.
|
|
22
|
+
* Disabled agents (enabled === false) are kept in the registry but excluded from spawning.
|
|
23
|
+
*/
|
|
24
|
+
export function registerAgents(userAgents) {
|
|
25
|
+
agents.clear();
|
|
26
|
+
// Start with defaults
|
|
27
|
+
for (const [name, config] of DEFAULT_AGENTS) {
|
|
28
|
+
agents.set(name, config);
|
|
29
|
+
}
|
|
30
|
+
// Overlay user agents (overrides defaults with same name)
|
|
31
|
+
for (const [name, config] of userAgents) {
|
|
32
|
+
agents.set(name, config);
|
|
33
|
+
}
|
|
34
|
+
// Resolve model placeholders against the model config
|
|
35
|
+
// This replaces {{model:orchestrator}} etc. with actual model strings
|
|
36
|
+
reloadModelConfig();
|
|
37
|
+
resolveAllPlaceholders(agents, modelConfig);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Reload the model config from disk (in case it changed since session start).
|
|
41
|
+
*/
|
|
42
|
+
export function reloadModelConfig(cwd) {
|
|
43
|
+
modelConfig = loadModelConfig(cwd ?? process.cwd());
|
|
44
|
+
}
|
|
45
|
+
/** Get the current model config (for UI display / debugging). */
|
|
46
|
+
export function getModelConfig() {
|
|
47
|
+
return modelConfig;
|
|
48
|
+
}
|
|
49
|
+
/** Case-insensitive key resolution. */
|
|
50
|
+
function resolveKey(name) {
|
|
51
|
+
if (agents.has(name))
|
|
52
|
+
return name;
|
|
53
|
+
const lower = name.toLowerCase();
|
|
54
|
+
for (const key of agents.keys()) {
|
|
55
|
+
if (key.toLowerCase() === lower)
|
|
56
|
+
return key;
|
|
57
|
+
}
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
/** Resolve a type name case-insensitively. Returns the canonical key or undefined. */
|
|
61
|
+
export function resolveType(name) {
|
|
62
|
+
return resolveKey(name);
|
|
63
|
+
}
|
|
64
|
+
/** Get the agent config for a type (case-insensitive). */
|
|
65
|
+
export function getAgentConfig(name) {
|
|
66
|
+
const key = resolveKey(name);
|
|
67
|
+
return key ? agents.get(key) : undefined;
|
|
68
|
+
}
|
|
69
|
+
/** Get all enabled type names (for spawning and tool descriptions). */
|
|
70
|
+
export function getAvailableTypes() {
|
|
71
|
+
return [...agents.entries()]
|
|
72
|
+
.filter(([_, config]) => config.enabled !== false)
|
|
73
|
+
.map(([name]) => name);
|
|
74
|
+
}
|
|
75
|
+
/** Get all type names including disabled (for UI listing). */
|
|
76
|
+
export function getAllTypes() {
|
|
77
|
+
return [...agents.keys()];
|
|
78
|
+
}
|
|
79
|
+
/** Get names of default agents currently in the registry. */
|
|
80
|
+
export function getDefaultAgentNames() {
|
|
81
|
+
return [...agents.entries()]
|
|
82
|
+
.filter(([_, config]) => config.isDefault === true)
|
|
83
|
+
.map(([name]) => name);
|
|
84
|
+
}
|
|
85
|
+
/** Get names of user-defined agents (non-defaults) currently in the registry. */
|
|
86
|
+
export function getUserAgentNames() {
|
|
87
|
+
return [...agents.entries()]
|
|
88
|
+
.filter(([_, config]) => config.isDefault !== true)
|
|
89
|
+
.map(([name]) => name);
|
|
90
|
+
}
|
|
91
|
+
/** Check if a type is valid and enabled (case-insensitive). */
|
|
92
|
+
export function isValidType(type) {
|
|
93
|
+
const key = resolveKey(type);
|
|
94
|
+
if (!key)
|
|
95
|
+
return false;
|
|
96
|
+
return agents.get(key)?.enabled !== false;
|
|
97
|
+
}
|
|
98
|
+
/** Tool names required for memory management. */
|
|
99
|
+
const MEMORY_TOOL_NAMES = ["read", "write", "edit"];
|
|
100
|
+
/**
|
|
101
|
+
* Get memory tool names (read/write/edit) not already in the provided set.
|
|
102
|
+
*/
|
|
103
|
+
export function getMemoryToolNames(existingToolNames) {
|
|
104
|
+
return MEMORY_TOOL_NAMES.filter(n => !existingToolNames.has(n));
|
|
105
|
+
}
|
|
106
|
+
/** Tool names needed for read-only memory access. */
|
|
107
|
+
const READONLY_MEMORY_TOOL_NAMES = ["read"];
|
|
108
|
+
/**
|
|
109
|
+
* Get read-only memory tool names not already in the provided set.
|
|
110
|
+
*/
|
|
111
|
+
export function getReadOnlyMemoryToolNames(existingToolNames) {
|
|
112
|
+
return READONLY_MEMORY_TOOL_NAMES.filter(n => !existingToolNames.has(n));
|
|
113
|
+
}
|
|
114
|
+
/** Get built-in tool names for a type (case-insensitive). */
|
|
115
|
+
export function getToolNamesForType(type) {
|
|
116
|
+
const key = resolveKey(type);
|
|
117
|
+
const raw = key ? agents.get(key) : undefined;
|
|
118
|
+
const config = raw?.enabled !== false ? raw : undefined;
|
|
119
|
+
const names = config?.builtinToolNames?.length ? config.builtinToolNames : [...BUILTIN_TOOL_NAMES];
|
|
120
|
+
return names;
|
|
121
|
+
}
|
|
122
|
+
/** Get config for a type (case-insensitive, returns a SubagentTypeConfig-compatible object). Falls back to orchestrator. */
|
|
123
|
+
export function getConfig(type) {
|
|
124
|
+
const key = resolveKey(type);
|
|
125
|
+
const config = key ? agents.get(key) : undefined;
|
|
126
|
+
if (config && config.enabled !== false) {
|
|
127
|
+
return {
|
|
128
|
+
displayName: config.displayName ?? config.name,
|
|
129
|
+
description: config.description,
|
|
130
|
+
builtinToolNames: config.builtinToolNames ?? BUILTIN_TOOL_NAMES,
|
|
131
|
+
extensions: config.extensions,
|
|
132
|
+
skills: config.skills,
|
|
133
|
+
promptMode: config.promptMode,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
// Fallback for unknown/disabled types — orchestrator config
|
|
137
|
+
const fallback = agents.get("orchestrator");
|
|
138
|
+
if (fallback && fallback.enabled !== false) {
|
|
139
|
+
return {
|
|
140
|
+
displayName: fallback.displayName ?? fallback.name,
|
|
141
|
+
description: fallback.description,
|
|
142
|
+
builtinToolNames: fallback.builtinToolNames ?? BUILTIN_TOOL_NAMES,
|
|
143
|
+
extensions: fallback.extensions,
|
|
144
|
+
skills: fallback.skills,
|
|
145
|
+
promptMode: fallback.promptMode,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
// Absolute fallback (should never happen)
|
|
149
|
+
return {
|
|
150
|
+
displayName: "Orchestrator",
|
|
151
|
+
description: "L-Spec central coordinator — delegates to specialists, manages phases",
|
|
152
|
+
builtinToolNames: BUILTIN_TOOL_NAMES,
|
|
153
|
+
extensions: true,
|
|
154
|
+
skills: true,
|
|
155
|
+
promptMode: "replace",
|
|
156
|
+
};
|
|
157
|
+
}
|