qlogicagent 0.5.0 → 0.5.3

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 (173) hide show
  1. package/README.md +402 -402
  2. package/dist/agent.js +18 -0
  3. package/dist/cli.js +360 -0
  4. package/dist/contracts.js +1 -0
  5. package/dist/index.js +22 -0
  6. package/dist/orchestration.js +125 -0
  7. package/dist/types/agent/agent.d.ts +43 -0
  8. package/dist/types/agent/constants.d.ts +47 -0
  9. package/dist/types/agent/tool-loop.d.ts +96 -0
  10. package/dist/types/agent/types.d.ts +250 -0
  11. package/dist/types/cli/main.d.ts +11 -0
  12. package/dist/types/cli/stdio-server.d.ts +56 -0
  13. package/dist/types/cli/tool-bootstrap.d.ts +21 -0
  14. package/dist/types/config/config.d.ts +17 -0
  15. package/dist/types/contracts/hooks.d.ts +175 -0
  16. package/dist/types/contracts/index.d.ts +10 -0
  17. package/dist/types/contracts/planner.d.ts +35 -0
  18. package/dist/types/contracts/skill-candidate.d.ts +63 -0
  19. package/dist/types/contracts/todo.d.ts +14 -0
  20. package/dist/types/index.d.ts +13 -0
  21. package/dist/types/llm/builtin-providers.d.ts +10 -0
  22. package/dist/types/llm/debug-transport.d.ts +12 -0
  23. package/dist/types/llm/index.d.ts +16 -0
  24. package/dist/types/llm/llm-client.d.ts +43 -0
  25. package/dist/types/llm/model-catalog.d.ts +53 -0
  26. package/dist/types/llm/provider-def.d.ts +59 -0
  27. package/dist/types/llm/provider-registry.d.ts +54 -0
  28. package/dist/types/llm/transport.d.ts +62 -0
  29. package/dist/types/llm/transports/anthropic-messages.d.ts +31 -0
  30. package/dist/types/llm/transports/openai-chat.d.ts +36 -0
  31. package/dist/types/orchestration/agent-registry.d.ts +46 -0
  32. package/dist/types/orchestration/context-collapse.d.ts +58 -0
  33. package/dist/types/orchestration/context-compression.d.ts +301 -0
  34. package/dist/types/orchestration/conversation-repair.d.ts +61 -0
  35. package/dist/types/orchestration/curator-scheduler.d.ts +119 -0
  36. package/dist/types/orchestration/error-classification.d.ts +12 -0
  37. package/dist/types/orchestration/failover-classification.d.ts +8 -0
  38. package/dist/types/orchestration/failover-error.d.ts +33 -0
  39. package/dist/types/orchestration/fork-subagent.d.ts +100 -0
  40. package/dist/types/orchestration/index.d.ts +113 -0
  41. package/dist/types/orchestration/memory-provider.d.ts +14 -0
  42. package/dist/types/orchestration/reactive-compact.d.ts +73 -0
  43. package/dist/types/orchestration/retry-loop.d.ts +69 -0
  44. package/dist/types/orchestration/skill-candidate.d.ts +52 -0
  45. package/dist/types/orchestration/skill-consolidation.d.ts +123 -0
  46. package/dist/types/orchestration/skill-improvement.d.ts +59 -0
  47. package/dist/types/orchestration/skill-similarity.d.ts +98 -0
  48. package/dist/types/orchestration/task-types.d.ts +142 -0
  49. package/dist/types/orchestration/team-orchestration.d.ts +195 -0
  50. package/dist/types/orchestration/team-tool-loop-wiring.d.ts +92 -0
  51. package/dist/types/orchestration/tool-choice-policy.d.ts +54 -0
  52. package/dist/types/orchestration/tool-loop-state.d.ts +50 -0
  53. package/dist/types/orchestration/tool-schema.d.ts +39 -0
  54. package/dist/types/orchestration/turn-loop-guard.d.ts +86 -0
  55. package/dist/types/runtime/execution/dream-agent.d.ts +199 -0
  56. package/dist/types/runtime/execution/forked-agent.d.ts +111 -0
  57. package/dist/types/runtime/execution/index.d.ts +6 -0
  58. package/dist/types/runtime/execution/progress-tracker.d.ts +78 -0
  59. package/dist/types/runtime/execution/remote-agent.d.ts +63 -0
  60. package/dist/types/runtime/execution/streaming-tool-executor.d.ts +100 -0
  61. package/dist/types/runtime/execution/tool-eligibility.d.ts +59 -0
  62. package/dist/types/runtime/execution/tool-result-storage.d.ts +87 -0
  63. package/dist/types/runtime/hooks/context-compression.d.ts +61 -0
  64. package/dist/types/runtime/hooks/hook-registry.d.ts +12 -0
  65. package/dist/types/runtime/hooks/index.d.ts +3 -0
  66. package/dist/types/runtime/hooks/memory-hooks.d.ts +49 -0
  67. package/dist/types/runtime/index.d.ts +5 -0
  68. package/dist/types/runtime/infra/cleanup-registry.d.ts +23 -0
  69. package/dist/types/runtime/infra/file-watcher.d.ts +72 -0
  70. package/dist/types/runtime/infra/index.d.ts +6 -0
  71. package/dist/types/runtime/infra/secure-storage.d.ts +81 -0
  72. package/dist/types/runtime/infra/task-runtime.d.ts +108 -0
  73. package/dist/types/runtime/infra/token-budget.d.ts +92 -0
  74. package/dist/types/runtime/infra/worktree-backend.d.ts +85 -0
  75. package/dist/types/runtime/prompt/environment-context.d.ts +23 -0
  76. package/dist/types/runtime/prompt/index.d.ts +3 -0
  77. package/dist/types/runtime/prompt/instruction-loader.d.ts +64 -0
  78. package/dist/types/runtime/prompt/system-prompt-sections.d.ts +63 -0
  79. package/dist/types/runtime/session/index.d.ts +2 -0
  80. package/dist/types/runtime/session/session-memory.d.ts +91 -0
  81. package/dist/types/runtime/session/session-persistence.d.ts +94 -0
  82. package/dist/types/runtime/session/session-state.d.ts +117 -0
  83. package/dist/types/skills/index.d.ts +125 -0
  84. package/dist/types/skills/mcp/index.d.ts +3 -0
  85. package/dist/types/skills/mcp/mcp-http-client.d.ts +66 -0
  86. package/dist/types/skills/mcp/mcp-manager.d.ts +84 -0
  87. package/dist/types/skills/mcp/mcp-stdio-client.d.ts +84 -0
  88. package/dist/types/skills/memory-extractor.d.ts +64 -0
  89. package/dist/types/skills/memory-query-tool.d.ts +43 -0
  90. package/dist/types/skills/memory-store.d.ts +66 -0
  91. package/dist/types/skills/memory-tool.d.ts +67 -0
  92. package/dist/types/skills/permissions/bash-classifier.d.ts +30 -0
  93. package/dist/types/skills/permissions/classifier-cache.d.ts +51 -0
  94. package/dist/types/skills/permissions/denial-tracking.d.ts +42 -0
  95. package/dist/types/skills/permissions/hook-runner.d.ts +85 -0
  96. package/dist/types/skills/permissions/index.d.ts +12 -0
  97. package/dist/types/skills/permissions/permission-classifier.d.ts +41 -0
  98. package/dist/types/skills/permissions/rule-engine.d.ts +41 -0
  99. package/dist/types/skills/permissions/settings-watcher.d.ts +46 -0
  100. package/dist/types/skills/permissions/types.d.ts +113 -0
  101. package/dist/types/skills/plugins/index.d.ts +2 -0
  102. package/dist/types/skills/plugins/plugin-api.d.ts +38 -0
  103. package/dist/types/skills/plugins/plugin-loader.d.ts +45 -0
  104. package/dist/types/skills/plugins/plugin-marketplace.d.ts +61 -0
  105. package/dist/types/skills/portable-tool.d.ts +71 -0
  106. package/dist/types/skills/qmemory-adapter.d.ts +42 -0
  107. package/dist/types/skills/skill-frontmatter.d.ts +19 -0
  108. package/dist/types/skills/skill-guard.d.ts +23 -0
  109. package/dist/types/skills/skill-loader.d.ts +16 -0
  110. package/dist/types/skills/skill-source.d.ts +119 -0
  111. package/dist/types/skills/skill-types.d.ts +199 -0
  112. package/dist/types/skills/think-tool.d.ts +16 -0
  113. package/dist/types/skills/todo-tool.d.ts +63 -0
  114. package/dist/types/skills/tool-registry.d.ts +29 -0
  115. package/dist/types/skills/tools/agent-tool.d.ts +91 -0
  116. package/dist/types/skills/tools/apply-patch-tool.d.ts +29 -0
  117. package/dist/types/skills/tools/ask-user-tool.d.ts +80 -0
  118. package/dist/types/skills/tools/brief-tool.d.ts +74 -0
  119. package/dist/types/skills/tools/browser-tool.d.ts +114 -0
  120. package/dist/types/skills/tools/checkpoint-tool.d.ts +66 -0
  121. package/dist/types/skills/tools/config-tool.d.ts +63 -0
  122. package/dist/types/skills/tools/cron-tool.d.ts +116 -0
  123. package/dist/types/skills/tools/edit-tool.d.ts +43 -0
  124. package/dist/types/skills/tools/exec-tool.d.ts +97 -0
  125. package/dist/types/skills/tools/image-generate-tool.d.ts +62 -0
  126. package/dist/types/skills/tools/instructions-tool.d.ts +103 -0
  127. package/dist/types/skills/tools/lsp-tool.d.ts +153 -0
  128. package/dist/types/skills/tools/mcp-client-types.d.ts +269 -0
  129. package/dist/types/skills/tools/mcp-resource-tools.d.ts +14 -0
  130. package/dist/types/skills/tools/mcp-tool.d.ts +249 -0
  131. package/dist/types/skills/tools/memory-tool.d.ts +74 -0
  132. package/dist/types/skills/tools/monitor-tool.d.ts +113 -0
  133. package/dist/types/skills/tools/music-generate-tool.d.ts +55 -0
  134. package/dist/types/skills/tools/notebook-edit-tool.d.ts +15 -0
  135. package/dist/types/skills/tools/notify-tool.d.ts +53 -0
  136. package/dist/types/skills/tools/patch-tool.d.ts +45 -0
  137. package/dist/types/skills/tools/pdf-tool.d.ts +66 -0
  138. package/dist/types/skills/tools/plan-mode-tool.d.ts +98 -0
  139. package/dist/types/skills/tools/read-tool.d.ts +51 -0
  140. package/dist/types/skills/tools/repl-tool.d.ts +70 -0
  141. package/dist/types/skills/tools/search-tool.d.ts +112 -0
  142. package/dist/types/skills/tools/send-message-tool.d.ts +51 -0
  143. package/dist/types/skills/tools/shell/bash-provider.d.ts +26 -0
  144. package/dist/types/skills/tools/shell/command-classification.d.ts +44 -0
  145. package/dist/types/skills/tools/shell/command-semantics.d.ts +14 -0
  146. package/dist/types/skills/tools/shell/destructive-command-warning.d.ts +10 -0
  147. package/dist/types/skills/tools/shell/exec-permissions.d.ts +52 -0
  148. package/dist/types/skills/tools/shell/index.d.ts +17 -0
  149. package/dist/types/skills/tools/shell/powershell-provider.d.ts +15 -0
  150. package/dist/types/skills/tools/shell/shell-command.d.ts +54 -0
  151. package/dist/types/skills/tools/shell/shell-exec.d.ts +33 -0
  152. package/dist/types/skills/tools/shell/shell-provider.d.ts +85 -0
  153. package/dist/types/skills/tools/shell/task-output.d.ts +45 -0
  154. package/dist/types/skills/tools/skill-invoke-tool.d.ts +46 -0
  155. package/dist/types/skills/tools/skill-list-tool.d.ts +33 -0
  156. package/dist/types/skills/tools/skill-manage-tool.d.ts +73 -0
  157. package/dist/types/skills/tools/skill-view-tool.d.ts +37 -0
  158. package/dist/types/skills/tools/sleep-tool.d.ts +49 -0
  159. package/dist/types/skills/tools/structured-output-tool.d.ts +116 -0
  160. package/dist/types/skills/tools/task-tool.d.ts +104 -0
  161. package/dist/types/skills/tools/team-tool.d.ts +89 -0
  162. package/dist/types/skills/tools/tool-search-tool.d.ts +51 -0
  163. package/dist/types/skills/tools/tts-tool.d.ts +38 -0
  164. package/dist/types/skills/tools/video-edit-tool.d.ts +69 -0
  165. package/dist/types/skills/tools/video-generate-tool.d.ts +62 -0
  166. package/dist/types/skills/tools/video-merge-tool.d.ts +105 -0
  167. package/dist/types/skills/tools/video-upscale-tool.d.ts +45 -0
  168. package/dist/types/skills/tools/web-fetch-tool.d.ts +78 -0
  169. package/dist/types/skills/tools/web-search-tool.d.ts +57 -0
  170. package/dist/types/skills/tools/workflow-tool.d.ts +44 -0
  171. package/dist/types/skills/tools/worktree-tool.d.ts +69 -0
  172. package/dist/types/skills/tools/write-tool.d.ts +45 -0
  173. package/package.json +4 -2
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Task Type Taxonomy — CC-aligned sub-agent task state system.
3
+ *
4
+ * CC defines 7 task types for sub-agent dispatch. Each type has different:
5
+ * - Execution model (in-process, subprocess, remote)
6
+ * - Isolation level (shared, worktree, container)
7
+ * - Permission handling (interactive, coordinator, worker)
8
+ * - Tool access (full, restricted, read-only)
9
+ *
10
+ * Reference: claude-code src/tasks/types.ts
11
+ */
12
+ /**
13
+ * The 7 task types from CC's sub-agent architecture.
14
+ *
15
+ * - local_bash: Subprocess shell execution (bash/powershell)
16
+ * - local_agent: Background forked Node process with its own tool loop
17
+ * - remote_agent: Cloud environment (polling-based, e.g., CCR sandbox)
18
+ * - in_process_teammate: Same process, AsyncLocalStorage-isolated agent
19
+ * - local_workflow: DAG/pipeline execution (planned)
20
+ * - monitor_mcp: MCP server monitoring agent (planned)
21
+ * - dream: Background memory consolidation agent
22
+ */
23
+ export type TaskType = "local_bash" | "local_agent" | "remote_agent" | "in_process_teammate" | "local_workflow" | "monitor_mcp" | "dream";
24
+ /**
25
+ * How a sub-agent is isolated from the parent execution.
26
+ *
27
+ * - shared: Same working directory, same filesystem (default fork)
28
+ * - worktree: Git worktree checkout — separate branch, merges back
29
+ * - container: Container sandbox (docker/remote)
30
+ */
31
+ export type IsolationMode = "shared" | "worktree" | "container";
32
+ /**
33
+ * Permission context for sub-agent execution.
34
+ * Determines which PermissionChecker variant is used.
35
+ *
36
+ * CC reference: 3 permission handler variants
37
+ * - interactive: User-facing agent, prompts for approval
38
+ * - coordinator: Orchestrator agent, auto-approves most non-destructive ops
39
+ * - worker: Headless worker, classifier-only (no user prompts)
40
+ */
41
+ export type PermissionRole = "interactive" | "coordinator" | "worker";
42
+ /** Common state fields shared by all task types. */
43
+ export interface TaskStateBase {
44
+ /** Unique task ID. */
45
+ taskId: string;
46
+ /** Task type discriminant. */
47
+ type: TaskType;
48
+ /** Human-readable label. */
49
+ label: string;
50
+ /** The permission role for this task's agent. */
51
+ permissionRole: PermissionRole;
52
+ /** Isolation mode. */
53
+ isolation: IsolationMode;
54
+ /** Current lifecycle state. */
55
+ lifecycle: TaskLifecycle;
56
+ /** Parent task ID (for nested sub-agents). */
57
+ parentTaskId?: string;
58
+ /** Execution depth (0 = root). */
59
+ depth: number;
60
+ /** Maximum turns before forced stop. */
61
+ maxTurns: number;
62
+ /** Token budget for this task. */
63
+ tokenBudget: number;
64
+ /** Start timestamp (ms). */
65
+ startedAt: number;
66
+ /** End timestamp (ms), set when completed/failed. */
67
+ endedAt?: number;
68
+ }
69
+ export type TaskLifecycle = "pending" | "running" | "completed" | "failed" | "cancelled" | "timeout";
70
+ /** Local bash task — subprocess shell execution. */
71
+ export interface LocalBashTaskState extends TaskStateBase {
72
+ type: "local_bash";
73
+ command: string;
74
+ cwd: string;
75
+ pid?: number;
76
+ }
77
+ /** Local agent task — forked agent with its own tool loop. */
78
+ export interface LocalAgentTaskState extends TaskStateBase {
79
+ type: "local_agent";
80
+ agentName: string;
81
+ systemPrompt: string;
82
+ /** Restricted tool set (empty = inherit parent). */
83
+ allowedTools: string[];
84
+ /** Worktree branch name (if isolation === "worktree"). */
85
+ worktreeBranch?: string;
86
+ }
87
+ /** Remote agent task — cloud sandbox execution. */
88
+ export interface RemoteAgentTaskState extends TaskStateBase {
89
+ type: "remote_agent";
90
+ /** Remote session/environment ID. */
91
+ remoteSessionId: string;
92
+ /** Polling endpoint for status checks. */
93
+ pollEndpoint?: string;
94
+ }
95
+ /** In-process teammate — AsyncLocalStorage-isolated, same process. */
96
+ export interface InProcessTeammateTaskState extends TaskStateBase {
97
+ type: "in_process_teammate";
98
+ teamName: string;
99
+ agentName: string;
100
+ /** Teammate's independent permission mode. */
101
+ permissionMode: string;
102
+ /** Async mailbox for coordinator ↔ worker communication. */
103
+ mailboxId?: string;
104
+ }
105
+ /** A single dream agent turn — text output + tool use count. */
106
+ export interface DreamTurn {
107
+ text: string;
108
+ toolUseCount: number;
109
+ }
110
+ /** Dream phase lifecycle — CC alignment. */
111
+ export type DreamPhase = "starting" | "updating" | "completed" | "failed";
112
+ /** Dream task — background memory consolidation agent (CC autoDream parity). */
113
+ export interface DreamTaskState extends TaskStateBase {
114
+ type: "dream";
115
+ sessionId: string;
116
+ /** Current dream phase. */
117
+ phase: DreamPhase;
118
+ /** Number of sessions being reviewed. */
119
+ sessionsReviewing: number;
120
+ /** Memory files touched by the dream agent. */
121
+ filesTouched: string[];
122
+ /** Dream agent turn history (capped). */
123
+ turns: DreamTurn[];
124
+ /** Stashed lock mtime for rollback on failure. */
125
+ priorLockMtime: number;
126
+ }
127
+ /** Placeholder for planned task types. */
128
+ export interface PlannedTaskState extends TaskStateBase {
129
+ type: "local_workflow" | "monitor_mcp";
130
+ }
131
+ /** Union of all concrete task states. */
132
+ export type TaskState = LocalBashTaskState | LocalAgentTaskState | RemoteAgentTaskState | InProcessTeammateTaskState | DreamTaskState | PlannedTaskState;
133
+ /**
134
+ * Filter available tools by permission role.
135
+ *
136
+ * @param role - The agent's permission role
137
+ * @param availableTools - Full set of tool names
138
+ * @returns Filtered tool names appropriate for the role
139
+ */
140
+ export declare function filterToolsByRole(role: PermissionRole, availableTools: string[]): string[];
141
+ /** Create a new task state with defaults populated. */
142
+ export declare function createTaskState(overrides: Pick<TaskStateBase, "taskId" | "type" | "label"> & Partial<TaskStateBase>): TaskStateBase;
@@ -0,0 +1,195 @@
1
+ /**
2
+ * Team Orchestration Strategy — multi-agent coordination layer.
3
+ *
4
+ * Extends the existing sidechain foundation with team/swarm semantics:
5
+ * - Parallel agent spawning (multiple sidechains at once)
6
+ * - Role-based agent assignment (planner / executor / reviewer)
7
+ * - Shared knowledge pool via merge policies
8
+ * - Budget-aware concurrency limits
9
+ * - Lifecycle state machine for team coordination
10
+ *
11
+ * Architecture:
12
+ * Gateway ─── Hub ─── orchestration (this module, pure strategy)
13
+ * │
14
+ * ┌───────────┼───────────┐
15
+ * │ TeamCoordinator │ ← Hub runtime (multi-sidechain-coordinator.ts)
16
+ * │ │ │
17
+ * │ ├── Agent #1 (planner)
18
+ * │ ├── Agent #2 (executor)
19
+ * │ └── Agent #3 (reviewer)
20
+ * └───────────────────────┘
21
+ *
22
+ * This module provides:
23
+ * 1. Type definitions (TeamPlan, AgentRole, TeamLifecycle)
24
+ * 2. Pure strategy functions (plan resolution, role assignment, budget allocation)
25
+ * 3. Merge/aggregation policies (how agent results combine)
26
+ *
27
+ * Hub consumes these types and strategy functions in its coordinator runtime.
28
+ * Gateway consumes TeamPlan to spawn/manage multiple sidechain executions.
29
+ */
30
+ import type { SidechainType, SidechainMergePolicy, SidechainBudgetTier, SidechainToolAccessMode } from "./index.js";
31
+ /** Roles an agent can take within a team execution. */
32
+ export type AgentRole = "planner" | "executor" | "reviewer" | "researcher" | "custom";
33
+ /** Execution mode for a team. */
34
+ export type TeamExecutionMode = "parallel" | "sequential" | "pipeline" | "adaptive";
35
+ /** How team results are aggregated into the parent execution. */
36
+ export type TeamAggregationPolicy = "first-success" | "majority-vote" | "merge-all" | "reviewer-gate" | "planner-sync";
37
+ /** Current lifecycle state of a team execution. */
38
+ export type TeamLifecycleState = "planning" | "spawning" | "executing" | "aggregating" | "reviewing" | "completed" | "failed" | "cancelled";
39
+ /** Specification for a single agent within a team. */
40
+ export interface TeamAgentSpec {
41
+ /** Unique ID within the team (e.g., "agent-1", "researcher-a"). */
42
+ agentId: string;
43
+ /** Role this agent plays. */
44
+ role: AgentRole;
45
+ /** Human-readable label for tracing. */
46
+ label: string;
47
+ /** The sidechain type this agent maps to. */
48
+ sidechainType: SidechainType;
49
+ /** Task description / system prompt override for this agent. */
50
+ taskDescription: string;
51
+ /** Tool access mode for this agent's sidechain. */
52
+ toolAccessMode: SidechainToolAccessMode;
53
+ /** Budget tier for this agent. */
54
+ budgetTier: SidechainBudgetTier;
55
+ /** Which agents this one depends on (for sequential/pipeline modes). */
56
+ dependsOn: string[];
57
+ /** Maximum tokens this agent can consume. */
58
+ maxTokenBudget: number;
59
+ /** Maximum tool calls this agent can make. */
60
+ maxToolCalls: number;
61
+ /** Timeout in milliseconds (0 = inherit from team). */
62
+ timeoutMs: number;
63
+ }
64
+ /** A complete team execution plan. */
65
+ export interface TeamPlan {
66
+ /** Unique team execution ID. */
67
+ teamId: string;
68
+ /** Execution mode for this team. */
69
+ mode: TeamExecutionMode;
70
+ /** How results from all agents are aggregated. */
71
+ aggregationPolicy: TeamAggregationPolicy;
72
+ /** All agent specs in this team. */
73
+ agents: TeamAgentSpec[];
74
+ /** Maximum concurrent agent executions (0 = unlimited). */
75
+ maxConcurrency: number;
76
+ /** Team-level timeout in ms (0 = no timeout). */
77
+ timeoutMs: number;
78
+ /** Total token budget across all agents. */
79
+ totalTokenBudget: number;
80
+ /** Whether early termination is allowed when one agent fails. */
81
+ failFast: boolean;
82
+ /** Shared context provided to all agents. */
83
+ sharedContext: string;
84
+ /** Merge policy for the final team output back to parent. */
85
+ mergePolicy: SidechainMergePolicy;
86
+ }
87
+ /** Result from a single agent within a team. */
88
+ export interface TeamAgentResult {
89
+ agentId: string;
90
+ role: AgentRole;
91
+ status: "completed" | "failed" | "cancelled" | "timeout";
92
+ output: string;
93
+ tokenUsage: {
94
+ prompt: number;
95
+ completion: number;
96
+ };
97
+ toolCallCount: number;
98
+ durationMs: number;
99
+ error?: string;
100
+ }
101
+ /** Aggregated result from team execution. */
102
+ export interface TeamResult {
103
+ teamId: string;
104
+ state: TeamLifecycleState;
105
+ agentResults: TeamAgentResult[];
106
+ aggregatedOutput: string;
107
+ totalTokenUsage: {
108
+ prompt: number;
109
+ completion: number;
110
+ };
111
+ totalDurationMs: number;
112
+ }
113
+ /** Maximum agents allowed in a team (safety bound). */
114
+ export declare const TEAM_MAX_AGENTS = 8;
115
+ /** Maximum recursion depth (teams spawning teams). */
116
+ export declare const TEAM_MAX_DEPTH = 2;
117
+ /**
118
+ * Resolve a team plan from a high-level task decomposition.
119
+ *
120
+ * This is the main entry point: given a set of subtasks and constraints,
121
+ * produce a concrete TeamPlan that the coordinator can execute.
122
+ */
123
+ export declare function resolveTeamPlan(params: {
124
+ teamId: string;
125
+ subtasks: Array<{
126
+ id: string;
127
+ role: AgentRole;
128
+ label: string;
129
+ task: string;
130
+ dependsOn?: string[];
131
+ }>;
132
+ mode?: TeamExecutionMode;
133
+ aggregationPolicy?: TeamAggregationPolicy;
134
+ totalTokenBudget?: number;
135
+ timeoutMs?: number;
136
+ failFast?: boolean;
137
+ sharedContext?: string;
138
+ mergePolicy?: SidechainMergePolicy;
139
+ }): TeamPlan;
140
+ /**
141
+ * Map agent role to sidechain type for existing Hub plumbing compatibility.
142
+ */
143
+ export declare function mapRoleToSidechainType(role: AgentRole): SidechainType;
144
+ /**
145
+ * Resolve tool access mode for a given role.
146
+ */
147
+ export declare function resolveAgentToolAccess(role: AgentRole): SidechainToolAccessMode;
148
+ /**
149
+ * Allocate token budgets proportionally by role weight.
150
+ */
151
+ export declare function allocateTokenBudgets(agents: TeamAgentSpec[], totalBudget: number): TeamAgentSpec[];
152
+ /**
153
+ * Infer execution mode from agent dependency graph.
154
+ */
155
+ export declare function inferExecutionMode(agents: TeamAgentSpec[]): TeamExecutionMode;
156
+ /**
157
+ * Infer aggregation policy from mode and agent composition.
158
+ */
159
+ export declare function inferAggregationPolicy(mode: TeamExecutionMode, agents: TeamAgentSpec[]): TeamAggregationPolicy;
160
+ /**
161
+ * Determine the execution order for agents given their dependency graph.
162
+ * Returns groups of agent IDs that can execute concurrently.
163
+ *
164
+ * Example: [[planner], [executor-a, executor-b], [reviewer]]
165
+ */
166
+ export declare function resolveExecutionOrder(agents: TeamAgentSpec[]): string[][];
167
+ /**
168
+ * Aggregate team results into a single output string.
169
+ */
170
+ export declare function aggregateTeamResults(results: TeamAgentResult[], policy: TeamAggregationPolicy): string;
171
+ /**
172
+ * Validate a team plan before execution.
173
+ * Returns a list of issues (empty = valid).
174
+ */
175
+ export declare function validateTeamPlan(plan: TeamPlan): string[];
176
+ /**
177
+ * Determine if a team execution should be cancelled early based on current state.
178
+ */
179
+ export declare function shouldCancelTeam(params: {
180
+ plan: TeamPlan;
181
+ results: TeamAgentResult[];
182
+ elapsedMs: number;
183
+ }): {
184
+ cancel: boolean;
185
+ reason: string;
186
+ };
187
+ /**
188
+ * Build the task prompt for a specific agent, incorporating shared context
189
+ * and outputs from dependency agents.
190
+ */
191
+ export declare function buildAgentTaskPrompt(params: {
192
+ agent: TeamAgentSpec;
193
+ plan: TeamPlan;
194
+ dependencyResults: TeamAgentResult[];
195
+ }): string;
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Team Tool Loop Wiring — Connects team orchestration to the tool loop.
3
+ *
4
+ * When the LLM invokes `team_create`, this module:
5
+ * 1. Validates the team plan
6
+ * 2. Maps team agents to fork contexts
7
+ * 3. Coordinates execution according to the team execution mode
8
+ * 4. Aggregates results according to the aggregation policy
9
+ * 5. Returns the aggregated result as a tool_result
10
+ *
11
+ * This bridges the gap between the pure strategy layer (team-orchestration.ts)
12
+ * and the Hub's tool loop.
13
+ */
14
+ import type { AgentRole, TeamExecutionMode, TeamAggregationPolicy, TeamLifecycleState } from "./team-orchestration.js";
15
+ import type { AgentDefinition } from "./agent-registry.js";
16
+ import type { ForkResult } from "./fork-subagent.js";
17
+ export interface TeamToolRequest {
18
+ /** Team name for identification. */
19
+ name: string;
20
+ /** Agent specs for the team. */
21
+ agents: TeamAgentRequest[];
22
+ /** Execution mode. */
23
+ mode: TeamExecutionMode;
24
+ /** How to aggregate results. */
25
+ aggregation: TeamAggregationPolicy;
26
+ }
27
+ export interface TeamAgentRequest {
28
+ /** Role within the team. */
29
+ role: AgentRole;
30
+ /** Agent type from built-in registry. */
31
+ agentType: string;
32
+ /** Task prompt for this agent. */
33
+ prompt: string;
34
+ /** Max turns override. */
35
+ maxTurns?: number;
36
+ /** Dependencies (agent IDs that must complete before this one). */
37
+ dependsOn?: string[];
38
+ }
39
+ export interface TeamExecutionPlan {
40
+ /** Ordered batches for execution. */
41
+ batches: TeamExecutionBatch[];
42
+ /** Total estimated token budget. */
43
+ totalBudget: number;
44
+ /** Lifecycle state. */
45
+ state: TeamLifecycleState;
46
+ }
47
+ export interface TeamExecutionBatch {
48
+ /** Agents in this batch (run in parallel within a batch). */
49
+ agents: TeamAgentRequest[];
50
+ /** Batch mode (parallel or sequential within the batch). */
51
+ mode: "parallel" | "serial";
52
+ }
53
+ /**
54
+ * Resolve the execution plan for a team request.
55
+ * Validates the request, resolves dependencies into ordered batches,
56
+ * and determines the execution topology.
57
+ */
58
+ export declare function resolveTeamExecutionPlan(request: TeamToolRequest): TeamExecutionPlan;
59
+ export interface TeamAggregatedResult {
60
+ /** Whether the team execution succeeded overall. */
61
+ ok: boolean;
62
+ /** Aggregated output text. */
63
+ output: string;
64
+ /** Individual agent results. */
65
+ agentResults: Array<{
66
+ agentId: string;
67
+ role: AgentRole;
68
+ result: ForkResult;
69
+ }>;
70
+ /** Total tokens consumed by all agents. */
71
+ totalTokensUsed: number;
72
+ /** Lifecycle state after aggregation. */
73
+ finalState: TeamLifecycleState;
74
+ }
75
+ /**
76
+ * Aggregate results from team agents according to the aggregation policy.
77
+ */
78
+ export declare function aggregateTeamToolResults(results: Array<{
79
+ agentId: string;
80
+ role: AgentRole;
81
+ result: ForkResult;
82
+ }>, policy: TeamAggregationPolicy): TeamAggregatedResult;
83
+ /**
84
+ * Map a team tool_call into the format needed for the tool loop to dispatch.
85
+ * Returns the list of fork configs the tool loop should execute.
86
+ */
87
+ export declare function mapTeamRequestToForkConfigs(request: TeamToolRequest, agentRegistry: (name: string) => AgentDefinition | undefined): Array<{
88
+ agentDef: AgentDefinition;
89
+ prompt: string;
90
+ maxTurns?: number;
91
+ role: AgentRole;
92
+ }>;
@@ -0,0 +1,54 @@
1
+ import type { RuntimeToolEligibilityContract } from "qlogicagent-runtime-contracts";
2
+ export type ToolChoiceLike = "auto" | "none" | "required" | {
3
+ type: "function";
4
+ function?: {
5
+ name?: string;
6
+ };
7
+ } | Record<string, unknown> | undefined;
8
+ export interface ToolChoiceToolLike {
9
+ type?: string;
10
+ function?: {
11
+ name?: string;
12
+ description?: string;
13
+ parameters?: Record<string, unknown>;
14
+ };
15
+ name?: string;
16
+ description?: string;
17
+ requiresApproval?: boolean;
18
+ }
19
+ export type ToolEligibilityLike = RuntimeToolEligibilityContract;
20
+ export interface ToolChoiceCompatibilityPolicy {
21
+ allowNamedToolChoice?: boolean;
22
+ allowRequiredToolChoice?: boolean;
23
+ requiredFallback?: "required" | "auto" | "none";
24
+ namedFallback?: "required" | "auto" | "none";
25
+ requireAutoWhenThinking?: boolean;
26
+ }
27
+ export interface ApplyToolChoicePolicyInput<TTool extends ToolChoiceToolLike> {
28
+ tools: readonly TTool[];
29
+ toolChoice: ToolChoiceLike;
30
+ eligibility?: readonly ToolEligibilityLike[];
31
+ thinkingEnabled?: boolean;
32
+ compatibility?: ToolChoiceCompatibilityPolicy;
33
+ }
34
+ export interface ApplyToolChoicePolicyResult<TTool extends ToolChoiceToolLike> {
35
+ tools: TTool[];
36
+ normalizedToolChoice?: ToolChoiceLike;
37
+ extraSystemPrompt?: string;
38
+ warnings: string[];
39
+ }
40
+ export declare function filterEligibleTools<TTool extends ToolChoiceToolLike>(params: {
41
+ tools: readonly TTool[];
42
+ eligibility?: readonly ToolEligibilityLike[];
43
+ }): TTool[];
44
+ export declare function normalizeAnthropicFunctionToolDefinition(tool: unknown): Record<string, unknown> | undefined;
45
+ export declare function normalizeAnthropicToolChoice(toolChoice: unknown): unknown;
46
+ export declare function applyToolChoiceCompatibility(params: {
47
+ toolChoice: ToolChoiceLike;
48
+ thinkingEnabled?: boolean;
49
+ compatibility?: ToolChoiceCompatibilityPolicy;
50
+ }): {
51
+ normalizedToolChoice?: ToolChoiceLike;
52
+ warnings: string[];
53
+ };
54
+ export declare function applyToolChoicePolicy<TTool extends ToolChoiceToolLike>(params: ApplyToolChoicePolicyInput<TTool>): ApplyToolChoicePolicyResult<TTool>;
@@ -0,0 +1,50 @@
1
+ import { type ConversationRepairOptions, type OpenAiChatMessageLike, type OpenAiResponsesItemLike } from "./conversation-repair.js";
2
+ export interface ToolLoopState<TMessage = unknown> {
3
+ round: number;
4
+ maxRounds: number;
5
+ pendingToolCallIds: string[];
6
+ completedToolCallIds: string[];
7
+ lastStopReason?: string;
8
+ replayMessages: TMessage[];
9
+ }
10
+ export interface ToolLoopRepairAction {
11
+ kind: "strip-forced-stop-tool-metadata" | "inject-placeholder-tool-result" | "drop-orphan-tool-result" | "rewrite-openai-function-call-pair" | "drop-trailing-reasoning";
12
+ detail?: string;
13
+ }
14
+ export interface RepairToolLoopStateResult<TMessage> {
15
+ state: ToolLoopState<TMessage>;
16
+ recoveryActions: ToolLoopRepairAction[];
17
+ }
18
+ export declare function createToolLoopState<TMessage>(params: {
19
+ maxRounds: number;
20
+ replayMessages?: readonly TMessage[];
21
+ round?: number;
22
+ pendingToolCallIds?: readonly string[];
23
+ completedToolCallIds?: readonly string[];
24
+ lastStopReason?: string;
25
+ }): ToolLoopState<TMessage>;
26
+ export declare function advanceToolLoopState<TMessage>(state: ToolLoopState<TMessage>, params: {
27
+ replayMessages?: readonly TMessage[];
28
+ pendingToolCallIds?: readonly string[];
29
+ completedToolCallIds?: readonly string[];
30
+ lastStopReason?: string;
31
+ }): ToolLoopState<TMessage>;
32
+ export declare function settleToolLoopState<TMessage>(state: ToolLoopState<TMessage>, params: {
33
+ replayMessages?: readonly TMessage[];
34
+ completedToolCallIds?: readonly string[];
35
+ lastStopReason?: string;
36
+ }): ToolLoopState<TMessage>;
37
+ export declare function recoverToolLoopStateFromChatConversation<TMessage extends OpenAiChatMessageLike>(params: {
38
+ maxRounds: number;
39
+ replayMessages: readonly TMessage[];
40
+ round?: number;
41
+ lastStopReason?: string;
42
+ options?: ConversationRepairOptions;
43
+ }): RepairToolLoopStateResult<TMessage>;
44
+ export declare function recoverToolLoopStateFromResponsesItems<TItem extends OpenAiResponsesItemLike>(params: {
45
+ maxRounds: number;
46
+ replayItems: readonly TItem[];
47
+ round?: number;
48
+ lastStopReason?: string;
49
+ options?: ConversationRepairOptions;
50
+ }): RepairToolLoopStateResult<TItem>;
@@ -0,0 +1,39 @@
1
+ import type { OpenAiToolCall } from "./conversation-repair.js";
2
+ export type ToolSchemaProvider = {
3
+ modelProvider?: string;
4
+ modelId?: string;
5
+ };
6
+ export interface FunctionToolSource {
7
+ name: string;
8
+ description?: string;
9
+ parameters?: Record<string, unknown>;
10
+ }
11
+ export interface FunctionToolDefinition {
12
+ type: "function";
13
+ function: {
14
+ name: string;
15
+ description?: string;
16
+ parameters: Record<string, unknown>;
17
+ };
18
+ }
19
+ export interface CapabilityToolManifestLike {
20
+ name: string;
21
+ description?: string;
22
+ requiredParameters?: string[];
23
+ }
24
+ export declare function isXaiProvider(modelProvider?: string, modelId?: string): boolean;
25
+ export declare function normalizeFunctionToolParameters(parameters: Record<string, unknown> | undefined, options?: ToolSchemaProvider): Record<string, unknown>;
26
+ export declare function convertFunctionTools(tools: readonly FunctionToolSource[], options?: ToolSchemaProvider): FunctionToolDefinition[];
27
+ export declare function convertCapabilityToolManifestsToFunctionTools(tools: readonly CapabilityToolManifestLike[]): FunctionToolDefinition[];
28
+ export declare function normalizeMessageTextContent(content: unknown): string;
29
+ export declare function parseOpenAiToolCallsFromChatResponse(responseBody: string): {
30
+ toolCalls: OpenAiToolCall[];
31
+ responseText: string;
32
+ };
33
+ export declare function buildAssistantToolCallMessage(toolCalls: OpenAiToolCall[]): Record<string, unknown>;
34
+ export declare function buildToolResultMessage(callId: string, result: {
35
+ ok: boolean;
36
+ payload?: unknown;
37
+ error?: string;
38
+ }): Record<string, unknown>;
39
+ export declare function cleanToolSchemaForGemini(schema: Record<string, unknown>): unknown;
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Turn Loop Guard — Abort signal + token budget warning for preventive termination.
3
+ *
4
+ * Aligned with Claude Code's multi-condition termination:
5
+ * 1. AbortSignal from user cancellation
6
+ * 2. Token budget pre-check (don't send API call if over budget)
7
+ * 3. max_output_tokens escalation on truncation
8
+ * 4. Prompt-too-long reactive compact trigger
9
+ */
10
+ export interface TurnLoopGuardConfig {
11
+ /** Context window size in tokens. */
12
+ contextWindowTokens: number;
13
+ /** Buffer reserved for response (default: 13000). */
14
+ responseBufferTokens: number;
15
+ /** Max output tokens for current model. */
16
+ maxOutputTokens: number;
17
+ /** Abort signal for user cancellation. */
18
+ abortSignal?: AbortSignal;
19
+ /** Whether reactive compact is available. */
20
+ reactiveCompactEnabled: boolean;
21
+ /** Whether max_output_tokens escalation is allowed. */
22
+ outputEscalationEnabled: boolean;
23
+ }
24
+ export type TokenWarningState = {
25
+ level: "ok";
26
+ } | {
27
+ level: "warning";
28
+ usagePercent: number;
29
+ remainingTokens: number;
30
+ } | {
31
+ level: "blocking";
32
+ usagePercent: number;
33
+ reason: "prompt_too_long" | "budget_exhausted";
34
+ };
35
+ export interface TurnLoopGuardState {
36
+ /** Current accumulated prompt tokens. */
37
+ promptTokens: number;
38
+ /** Whether reactive compact has already been attempted this turn. */
39
+ hasAttemptedReactiveCompact: boolean;
40
+ /** Current max_output_tokens (may escalate). */
41
+ currentMaxOutputTokens: number;
42
+ /** Number of consecutive max_tokens truncations. */
43
+ consecutiveTruncations: number;
44
+ /** Whether the turn has been aborted. */
45
+ aborted: boolean;
46
+ }
47
+ /** Initial guard state. */
48
+ export declare function createTurnLoopGuardState(config: TurnLoopGuardConfig): TurnLoopGuardState;
49
+ /**
50
+ * Calculate token warning state before making an API call.
51
+ * If level is "blocking", do NOT send the API call.
52
+ */
53
+ export declare function calculateTokenWarningState(state: TurnLoopGuardState, config: TurnLoopGuardConfig): TokenWarningState;
54
+ /**
55
+ * Handle API error and determine recovery action.
56
+ */
57
+ export type ApiErrorRecovery = {
58
+ action: "reactive_compact";
59
+ } | {
60
+ action: "escalate_output_tokens";
61
+ newMax: number;
62
+ } | {
63
+ action: "retry";
64
+ reason: string;
65
+ } | {
66
+ action: "abort";
67
+ reason: string;
68
+ };
69
+ export declare function resolveApiErrorRecovery(error: {
70
+ type?: string;
71
+ status?: number;
72
+ message?: string;
73
+ }, state: TurnLoopGuardState, config: TurnLoopGuardConfig): ApiErrorRecovery;
74
+ /**
75
+ * Handle finish_reason === "max_tokens" — escalate max_output_tokens.
76
+ *
77
+ * CC pattern: double the output token budget up to model max.
78
+ */
79
+ export declare function resolveOutputTokenEscalation(state: TurnLoopGuardState, config: TurnLoopGuardConfig, modelMaxOutput: number): {
80
+ shouldEscalate: boolean;
81
+ newMax: number;
82
+ };
83
+ /**
84
+ * Check if the turn should be aborted (user cancellation).
85
+ */
86
+ export declare function shouldAbortTurn(state: TurnLoopGuardState, config: TurnLoopGuardConfig): boolean;