@compilr-dev/sdk 0.10.7 → 0.10.8

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/dist/index.d.ts CHANGED
@@ -35,9 +35,9 @@
35
35
  */
36
36
  export { createCompilrAgent } from './agent.js';
37
37
  export type { CompilrAgentConfig, CompilrAgent, RunOptions, RunResult, ToolCallRecord, ToolConfig, UsageInfo, ProviderType, PermissionCallback, GuardrailConfig, ContextConfig, CapabilitiesConfig, } from './config.js';
38
- export { AgentTeam, TeamAgent, SharedContextManager, ArtifactStore, DelegationTracker, ContextResolver, } from './team/index.js';
38
+ export { AgentTeam, TeamAgent, SharedContextManager, ArtifactStore, DelegationTracker, ContextResolver, createDelegationStatusTool, createHandoffTool, } from './team/index.js';
39
39
  export type { AgentTeamConfig, TeamAgentConfig, ITeamPersistence, IArtifactStorage, ISessionRegistry, CustomAgentDefinition, AgentTemplate, AgentWorkshopData, WorkshopRoleDef, WorkshopToolProfile, WorkshopModelTier, WorkshopSkillDef, PlanSubmitInfo, PlanSubmitResult, PlanModeExitInfo, PlanModeCallbacks, ToolConfig as TeamToolConfig, ToolTier, ToolGroup, ProfileInfo, } from './team/index.js';
40
- export type { AgentRole, RoleMetadata, ToolProfile, MascotExpression, BackgroundSessionInfo, SerializedTeam, SerializedTeamAgent, TeamMetadata, TeamEvent, TeamEventType, TeamEventHandler, Artifact, ArtifactType as TeamArtifactType, ArtifactSummary as TeamArtifactSummary, CreateArtifactOptions, UpdateArtifactOptions, SerializedArtifact, SharedContext, SharedProjectInfo, SharedTeamInfo, TeamRosterEntry, TeamActivity, TeamActivityType, SharedDecision, TokenBudget, SerializedSharedContext, ParsedMention, ParsedInput, ResolvedMention, ResolveOptions, ResolutionSource, Delegation, DelegationStatus, DelegationResult, CompletionEvent, CreateDelegationOptions, DelegationStats, DelegationTrackerEvents, SkillToolRequirement, } from './team/index.js';
40
+ export type { AgentRole, RoleMetadata, ToolProfile, MascotExpression, BackgroundSessionInfo, SerializedTeam, SerializedTeamAgent, TeamMetadata, TeamEvent, TeamEventType, TeamEventHandler, Artifact, ArtifactType as TeamArtifactType, ArtifactSummary as TeamArtifactSummary, CreateArtifactOptions, UpdateArtifactOptions, SerializedArtifact, SharedContext, SharedProjectInfo, SharedTeamInfo, TeamRosterEntry, TeamActivity, TeamActivityType, SharedDecision, TokenBudget, SerializedSharedContext, ParsedMention, ParsedInput, ResolvedMention, ResolveOptions, ResolutionSource, Delegation, DelegationStatus, DelegationResult, CompletionEvent, CreateDelegationOptions, DelegationStats, DelegationTrackerEvents, HandoffResult, HandoffToolConfig, SkillToolRequirement, } from './team/index.js';
41
41
  export { ROLE_METADATA, ROLE_EXPERTISE, ROLE_GROUPS, PREDEFINED_ROLE_IDS, TOOL_GROUPS, TOOL_PROFILES, PROFILE_INFO, SKILL_REQUIREMENTS, CUSTOM_MASCOTS, buildAgentWorkshopData, buildSuggestedRolesMap, PLAN_MODE_BLOCKED_TOOLS, PLAN_MODE_DENIAL_MESSAGE, PLAN_MODE_PROMPT, isToolAllowedInPlanMode, getPlanModePrompt, } from './team/index.js';
42
42
  export { getToolsForProfile, detectProfileFromTools, isProfileReadOnly, generateToolAwarenessPrompt, generateCoordinatorGuidance, generateSpecialistGuidance, createDefaultToolConfig, validateToolConfig, getAllGroupIds, getGroupInfo, getGroupsByTier, getGroupsForProfile, assignMascot, generateCustomAgentSystemPrompt, getCustomAgentToolFilter, getCustomAgentProfileLabel, validateAgentId, isAgentIdTaken, createCustomAgentDefinition, listTemplates, getTemplate, saveTemplate, updateTemplate, deleteTemplate, createAgentFromTemplate, parseInputForMentions, getReferencedAgents, hasReferences, buildMessageWithContext, buildContextMap, findAgentForRole, findAgentById, getAvailableSpecialists, getSpecialistsSummary, hasSpecialists, suggestOwner, suggestOwners, matchesAgentExpertise, wouldCreateLoop, recordAssignment, getAssignmentHistory, clearAssignmentHistory, clearAllAssignmentHistory, canReassign, resolveAgentIdCollision, setActiveSharedContext, getActiveSharedContext, recordTeamActivity, getDefinedSkillNames, getSkillRequirements, checkSkillCompatibility, getCompatibleSkills, getAllRequiredTools, getSkillsByCategory, } from './team/index.js';
43
43
  export { codingPreset, readOnlyPreset, resolvePreset } from './presets/index.js';
package/dist/index.js CHANGED
@@ -41,7 +41,7 @@ export { createCompilrAgent } from './agent.js';
41
41
  // Multi-Agent Team Orchestration
42
42
  // =============================================================================
43
43
  // Core classes
44
- export { AgentTeam, TeamAgent, SharedContextManager, ArtifactStore, DelegationTracker, ContextResolver, } from './team/index.js';
44
+ export { AgentTeam, TeamAgent, SharedContextManager, ArtifactStore, DelegationTracker, ContextResolver, createDelegationStatusTool, createHandoffTool, } from './team/index.js';
45
45
  // Constants
46
46
  export { ROLE_METADATA, ROLE_EXPERTISE, ROLE_GROUPS, PREDEFINED_ROLE_IDS, TOOL_GROUPS, TOOL_PROFILES, PROFILE_INFO, SKILL_REQUIREMENTS, CUSTOM_MASCOTS, buildAgentWorkshopData, buildSuggestedRolesMap,
47
47
  // Plan mode
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Delegation & Handoff Tools — SDK Factories
3
+ *
4
+ * Factory functions for creating delegation_status and handoff tools.
5
+ * Both CLI and Desktop call these with platform-specific dependencies.
6
+ */
7
+ import { type Tool } from '@compilr-dev/agents';
8
+ import type { DelegationTracker } from './delegation-tracker.js';
9
+ import type { AgentTeam } from './team.js';
10
+ interface DelegationStatusInput {
11
+ delegation_id?: string;
12
+ agent_id?: string;
13
+ status?: 'active' | 'completed' | 'failed' | 'all';
14
+ }
15
+ /**
16
+ * Create a delegation_status tool that queries the given tracker.
17
+ * Read-only — safe for parallel execution.
18
+ */
19
+ export declare function createDelegationStatusTool(tracker: DelegationTracker): Tool<DelegationStatusInput>;
20
+ interface HandoffInput {
21
+ agentId: string;
22
+ task: string;
23
+ reason?: string;
24
+ }
25
+ /**
26
+ * Result from the platform's handoff handler.
27
+ */
28
+ export interface HandoffResult {
29
+ /** Whether the handoff was executed */
30
+ success: boolean;
31
+ /** Whether the user declined the handoff */
32
+ declined?: boolean;
33
+ /** Error message (if any) */
34
+ error?: string;
35
+ }
36
+ /**
37
+ * Configuration for creating a handoff tool.
38
+ */
39
+ export interface HandoffToolConfig {
40
+ /** The team instance for roster validation and one-hop tracking */
41
+ team: AgentTeam;
42
+ /** The current agent's ID (for one-hop rule enforcement) */
43
+ currentAgentId: string;
44
+ /**
45
+ * Platform-specific handoff handler. Called after validation.
46
+ * Should show approval UI if needed and execute the switch.
47
+ */
48
+ onHandoff: (targetAgentId: string, task: string, reason?: string) => Promise<HandoffResult>;
49
+ }
50
+ /**
51
+ * Create a handoff tool for a specific agent.
52
+ *
53
+ * The tool enforces the one-hop rule: if this agent was itself handed a task,
54
+ * it can only hand back to the coordinator (default agent), not to another specialist.
55
+ */
56
+ export declare function createHandoffTool(config: HandoffToolConfig): Tool<HandoffInput>;
57
+ export {};
@@ -0,0 +1,224 @@
1
+ /**
2
+ * Delegation & Handoff Tools — SDK Factories
3
+ *
4
+ * Factory functions for creating delegation_status and handoff tools.
5
+ * Both CLI and Desktop call these with platform-specific dependencies.
6
+ */
7
+ import { defineTool } from '@compilr-dev/agents';
8
+ function formatDuration(from, to) {
9
+ const endTime = to ?? new Date();
10
+ const ms = endTime.getTime() - from.getTime();
11
+ const seconds = Math.floor(ms / 1000);
12
+ const minutes = Math.floor(seconds / 60);
13
+ const hours = Math.floor(minutes / 60);
14
+ if (hours > 0) {
15
+ return `${String(hours)}h ${String(minutes % 60)}m`;
16
+ }
17
+ else if (minutes > 0) {
18
+ return `${String(minutes)}m ${String(seconds % 60)}s`;
19
+ }
20
+ else {
21
+ return `${String(seconds)}s`;
22
+ }
23
+ }
24
+ function formatDelegation(d) {
25
+ const entry = {
26
+ id: d.id,
27
+ targetAgent: d.targetAgentId,
28
+ task: d.task.length > 100 ? d.task.slice(0, 100) + '...' : d.task,
29
+ status: d.status,
30
+ duration: formatDuration(d.createdAt, d.completedAt),
31
+ };
32
+ if (d.todoIndex !== undefined) {
33
+ entry.todoIndex = d.todoIndex;
34
+ }
35
+ if (d.result) {
36
+ entry.result = {
37
+ success: d.result.success,
38
+ summary: d.result.summary,
39
+ artifactIds: d.result.artifactIds,
40
+ ...(d.result.error ? { error: d.result.error } : {}),
41
+ };
42
+ }
43
+ return entry;
44
+ }
45
+ /**
46
+ * Create a delegation_status tool that queries the given tracker.
47
+ * Read-only — safe for parallel execution.
48
+ */
49
+ export function createDelegationStatusTool(tracker) {
50
+ return defineTool({
51
+ name: 'delegation_status',
52
+ description: 'Query the status of tasks delegated via delegate_background. ' +
53
+ 'Returns active delegations by default (pending and running). ' +
54
+ 'Use delegation_id for a specific delegation, agent_id to filter by agent, ' +
55
+ 'or status to see completed/failed/all delegations.',
56
+ inputSchema: {
57
+ type: 'object',
58
+ properties: {
59
+ delegation_id: {
60
+ type: 'string',
61
+ description: 'Specific delegation ID (e.g., "del_abc12345")',
62
+ },
63
+ agent_id: {
64
+ type: 'string',
65
+ description: 'Filter by target agent (e.g., "dev", "arch")',
66
+ },
67
+ status: {
68
+ type: 'string',
69
+ enum: ['active', 'completed', 'failed', 'all'],
70
+ description: 'Filter by status. Default: "active" (pending + running)',
71
+ },
72
+ },
73
+ },
74
+ execute: (input) => {
75
+ return Promise.resolve(executeDelegationStatus(tracker, input));
76
+ },
77
+ });
78
+ }
79
+ function executeDelegationStatus(tracker, input) {
80
+ // Single delegation lookup
81
+ if (input.delegation_id) {
82
+ const delegation = tracker.getDelegation(input.delegation_id);
83
+ if (!delegation) {
84
+ return {
85
+ success: false,
86
+ error: `Delegation ${input.delegation_id} not found`,
87
+ };
88
+ }
89
+ return {
90
+ success: true,
91
+ result: {
92
+ delegations: [formatDelegation(delegation)],
93
+ stats: tracker.getStats(),
94
+ },
95
+ };
96
+ }
97
+ // Get all delegations then filter
98
+ let delegations;
99
+ if (input.agent_id) {
100
+ delegations = tracker.getByAgent(input.agent_id);
101
+ }
102
+ else {
103
+ delegations = tracker.getAll();
104
+ }
105
+ // Apply status filter
106
+ const filter = input.status ?? 'active';
107
+ if (filter !== 'all') {
108
+ delegations = delegations.filter((d) => {
109
+ switch (filter) {
110
+ case 'active':
111
+ return d.status === 'pending' || d.status === 'running';
112
+ case 'completed':
113
+ return d.status === 'completed';
114
+ case 'failed':
115
+ return d.status === 'failed';
116
+ default:
117
+ return true;
118
+ }
119
+ });
120
+ }
121
+ return {
122
+ success: true,
123
+ result: {
124
+ delegations: delegations.map(formatDelegation),
125
+ stats: tracker.getStats(),
126
+ },
127
+ };
128
+ }
129
+ /**
130
+ * Create a handoff tool for a specific agent.
131
+ *
132
+ * The tool enforces the one-hop rule: if this agent was itself handed a task,
133
+ * it can only hand back to the coordinator (default agent), not to another specialist.
134
+ */
135
+ export function createHandoffTool(config) {
136
+ const { team, currentAgentId, onHandoff } = config;
137
+ return defineTool({
138
+ name: 'handoff',
139
+ description: 'Hand off the current task to another team agent. ' +
140
+ 'Use this when a task is outside your expertise or would benefit from another specialist. ' +
141
+ 'The user will be asked to approve the handoff before switching. ' +
142
+ 'Example: hand off architecture questions to $arch, implementation to $dev, testing to $qa.',
143
+ inputSchema: {
144
+ type: 'object',
145
+ properties: {
146
+ agentId: {
147
+ type: 'string',
148
+ description: 'Target agent ID (e.g., "arch", "dev", "qa", "default")',
149
+ },
150
+ task: {
151
+ type: 'string',
152
+ description: 'Task description for the target agent - be specific and clear',
153
+ },
154
+ reason: {
155
+ type: 'string',
156
+ description: 'Why this agent is better suited for the task (shown to user)',
157
+ },
158
+ },
159
+ required: ['agentId', 'task'],
160
+ },
161
+ execute: async (input) => {
162
+ // Validate input
163
+ if (!input.agentId || input.agentId.trim().length === 0) {
164
+ return { success: false, error: 'Agent ID is required' };
165
+ }
166
+ if (!input.task || input.task.trim().length === 0) {
167
+ return { success: false, error: 'Task description is required' };
168
+ }
169
+ const targetId = input.agentId.trim();
170
+ // Validate target agent exists in team
171
+ const allAgents = team.getAll();
172
+ const targetExists = allAgents.some((a) => a.id === targetId);
173
+ if (!targetExists) {
174
+ const available = allAgents.map((a) => a.id).join(', ');
175
+ return {
176
+ success: false,
177
+ error: `Agent "${targetId}" not found in team. Available: ${available}`,
178
+ };
179
+ }
180
+ // Enforce one-hop rule
181
+ if (team.wasHandedTo(currentAgentId) && targetId !== 'default') {
182
+ const source = team.getHandoffSource(currentAgentId);
183
+ return {
184
+ success: false,
185
+ error: `One-hop rule: you were handed this task by $${source ?? 'unknown'} ` +
186
+ `and cannot re-hand it to another specialist. ` +
187
+ `You can only hand back to $default (coordinator). ` +
188
+ `Either complete the task yourself or hand back to the coordinator.`,
189
+ };
190
+ }
191
+ // Execute handoff via platform callback
192
+ try {
193
+ const result = await onHandoff(targetId, input.task.trim(), input.reason?.trim());
194
+ if (result.error) {
195
+ return { success: false, error: result.error };
196
+ }
197
+ if (result.declined) {
198
+ return {
199
+ success: true,
200
+ result: {
201
+ handedOff: false,
202
+ message: 'User declined the handoff. Continue handling the task yourself.',
203
+ },
204
+ };
205
+ }
206
+ // Record the handoff for one-hop tracking
207
+ team.recordHandoff(targetId, currentAgentId);
208
+ return {
209
+ success: true,
210
+ result: {
211
+ handedOff: true,
212
+ message: `Task handed off to $${targetId}. They will handle it from here.`,
213
+ },
214
+ };
215
+ }
216
+ catch (err) {
217
+ return {
218
+ success: false,
219
+ error: `Handoff failed: ${err instanceof Error ? err.message : String(err)}`,
220
+ };
221
+ }
222
+ },
223
+ });
224
+ }
@@ -38,3 +38,5 @@ export { setActiveSharedContext, getActiveSharedContext, recordTeamActivity } fr
38
38
  export type { SkillToolRequirement } from './skill-requirements.js';
39
39
  export { SKILL_REQUIREMENTS, getDefinedSkillNames, getSkillRequirements, checkSkillCompatibility, getCompatibleSkills, getAllRequiredTools, getSkillsByCategory, } from './skill-requirements.js';
40
40
  export { resolveAgentIdCollision } from './collision-utils.js';
41
+ export { createDelegationStatusTool, createHandoffTool } from './delegation-tools.js';
42
+ export type { HandoffResult, HandoffToolConfig } from './delegation-tools.js';
@@ -31,3 +31,5 @@ export { setActiveSharedContext, getActiveSharedContext, recordTeamActivity } fr
31
31
  export { SKILL_REQUIREMENTS, getDefinedSkillNames, getSkillRequirements, checkSkillCompatibility, getCompatibleSkills, getAllRequiredTools, getSkillsByCategory, } from './skill-requirements.js';
32
32
  // Collision utils
33
33
  export { resolveAgentIdCollision } from './collision-utils.js';
34
+ // Delegation & Handoff tools (factory functions)
35
+ export { createDelegationStatusTool, createHandoffTool } from './delegation-tools.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@compilr-dev/sdk",
3
- "version": "0.10.7",
3
+ "version": "0.10.8",
4
4
  "description": "Universal agent runtime for building AI-powered applications",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",