qlogicagent 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/README.md +45 -45
  2. package/package.json +56 -42
  3. package/dist/agent/agent.d.ts +0 -43
  4. package/dist/agent/agent.js +0 -113
  5. package/dist/agent/tool-loop.d.ts +0 -64
  6. package/dist/agent/tool-loop.js +0 -575
  7. package/dist/agent/types.d.ts +0 -175
  8. package/dist/agent/types.js +0 -14
  9. package/dist/cli/main.d.ts +0 -11
  10. package/dist/cli/main.js +0 -23
  11. package/dist/cli/stdio-server.d.ts +0 -45
  12. package/dist/cli/stdio-server.js +0 -463
  13. package/dist/config/config.d.ts +0 -17
  14. package/dist/config/config.js +0 -21
  15. package/dist/contracts/hooks.d.ts +0 -120
  16. package/dist/contracts/hooks.js +0 -7
  17. package/dist/contracts/index.d.ts +0 -10
  18. package/dist/contracts/index.js +0 -10
  19. package/dist/contracts/planner.d.ts +0 -35
  20. package/dist/contracts/planner.js +0 -2
  21. package/dist/contracts/skill-candidate.d.ts +0 -63
  22. package/dist/contracts/skill-candidate.js +0 -195
  23. package/dist/contracts/todo.d.ts +0 -14
  24. package/dist/contracts/todo.js +0 -9
  25. package/dist/index.d.ts +0 -13
  26. package/dist/index.js +0 -15
  27. package/dist/llm/builtin-providers.d.ts +0 -10
  28. package/dist/llm/builtin-providers.js +0 -531
  29. package/dist/llm/index.d.ts +0 -15
  30. package/dist/llm/index.js +0 -14
  31. package/dist/llm/llm-client.d.ts +0 -43
  32. package/dist/llm/llm-client.js +0 -67
  33. package/dist/llm/model-catalog.d.ts +0 -53
  34. package/dist/llm/model-catalog.js +0 -191
  35. package/dist/llm/provider-def.d.ts +0 -59
  36. package/dist/llm/provider-def.js +0 -12
  37. package/dist/llm/provider-registry.d.ts +0 -54
  38. package/dist/llm/provider-registry.js +0 -147
  39. package/dist/llm/transport.d.ts +0 -62
  40. package/dist/llm/transport.js +0 -27
  41. package/dist/llm/transports/anthropic-messages.d.ts +0 -31
  42. package/dist/llm/transports/anthropic-messages.js +0 -293
  43. package/dist/llm/transports/openai-chat.d.ts +0 -36
  44. package/dist/llm/transports/openai-chat.js +0 -165
  45. package/dist/orchestration/agent-registry.d.ts +0 -41
  46. package/dist/orchestration/agent-registry.js +0 -116
  47. package/dist/orchestration/approval-aware-tool-plan.d.ts +0 -32
  48. package/dist/orchestration/approval-aware-tool-plan.js +0 -87
  49. package/dist/orchestration/context-compression.d.ts +0 -220
  50. package/dist/orchestration/context-compression.js +0 -583
  51. package/dist/orchestration/conversation-repair.d.ts +0 -61
  52. package/dist/orchestration/conversation-repair.js +0 -429
  53. package/dist/orchestration/curator-scheduler.d.ts +0 -119
  54. package/dist/orchestration/curator-scheduler.js +0 -135
  55. package/dist/orchestration/embedded-failover-policy.d.ts +0 -110
  56. package/dist/orchestration/embedded-failover-policy.js +0 -168
  57. package/dist/orchestration/error-classification.d.ts +0 -12
  58. package/dist/orchestration/error-classification.js +0 -77
  59. package/dist/orchestration/failover-classification.d.ts +0 -8
  60. package/dist/orchestration/failover-classification.js +0 -381
  61. package/dist/orchestration/failover-error.d.ts +0 -33
  62. package/dist/orchestration/failover-error.js +0 -198
  63. package/dist/orchestration/fork-subagent.d.ts +0 -100
  64. package/dist/orchestration/fork-subagent.js +0 -98
  65. package/dist/orchestration/index.d.ts +0 -120
  66. package/dist/orchestration/index.js +0 -267
  67. package/dist/orchestration/memory-flush-policy.d.ts +0 -57
  68. package/dist/orchestration/memory-flush-policy.js +0 -85
  69. package/dist/orchestration/memory-provider.d.ts +0 -14
  70. package/dist/orchestration/memory-provider.js +0 -2
  71. package/dist/orchestration/parallel-tool-calls.d.ts +0 -41
  72. package/dist/orchestration/parallel-tool-calls.js +0 -59
  73. package/dist/orchestration/prompt-cache-strategy.d.ts +0 -126
  74. package/dist/orchestration/prompt-cache-strategy.js +0 -228
  75. package/dist/orchestration/reactive-compact.d.ts +0 -73
  76. package/dist/orchestration/reactive-compact.js +0 -78
  77. package/dist/orchestration/retry-loop.d.ts +0 -22
  78. package/dist/orchestration/retry-loop.js +0 -24
  79. package/dist/orchestration/skill-candidate.d.ts +0 -52
  80. package/dist/orchestration/skill-candidate.js +0 -141
  81. package/dist/orchestration/skill-consolidation.d.ts +0 -123
  82. package/dist/orchestration/skill-consolidation.js +0 -220
  83. package/dist/orchestration/skill-improvement.d.ts +0 -59
  84. package/dist/orchestration/skill-improvement.js +0 -66
  85. package/dist/orchestration/skill-similarity.d.ts +0 -98
  86. package/dist/orchestration/skill-similarity.js +0 -131
  87. package/dist/orchestration/streaming-tool-executor.d.ts +0 -73
  88. package/dist/orchestration/streaming-tool-executor.js +0 -96
  89. package/dist/orchestration/team-orchestration.d.ts +0 -195
  90. package/dist/orchestration/team-orchestration.js +0 -369
  91. package/dist/orchestration/team-tool-loop-wiring.d.ts +0 -92
  92. package/dist/orchestration/team-tool-loop-wiring.js +0 -147
  93. package/dist/orchestration/tool-choice-policy.d.ts +0 -54
  94. package/dist/orchestration/tool-choice-policy.js +0 -164
  95. package/dist/orchestration/tool-loop-state.d.ts +0 -50
  96. package/dist/orchestration/tool-loop-state.js +0 -133
  97. package/dist/orchestration/tool-schema.d.ts +0 -39
  98. package/dist/orchestration/tool-schema.js +0 -297
  99. package/dist/orchestration/transcript-repair.d.ts +0 -42
  100. package/dist/orchestration/transcript-repair.js +0 -426
  101. package/dist/orchestration/turn-loop-guard.d.ts +0 -86
  102. package/dist/orchestration/turn-loop-guard.js +0 -92
  103. package/dist/orchestration/web-browser-policy.d.ts +0 -17
  104. package/dist/orchestration/web-browser-policy.js +0 -39
  105. package/dist/runtime/context-compression.d.ts +0 -61
  106. package/dist/runtime/context-compression.js +0 -274
  107. package/dist/runtime/hook-registry.d.ts +0 -12
  108. package/dist/runtime/hook-registry.js +0 -53
  109. package/dist/runtime/memory-hooks.d.ts +0 -23
  110. package/dist/runtime/memory-hooks.js +0 -65
  111. package/dist/runtime/tool-eligibility.d.ts +0 -59
  112. package/dist/runtime/tool-eligibility.js +0 -111
  113. package/dist/skills/index.d.ts +0 -108
  114. package/dist/skills/index.js +0 -82
  115. package/dist/skills/memory-extractor.d.ts +0 -64
  116. package/dist/skills/memory-extractor.js +0 -173
  117. package/dist/skills/memory-query-tool.d.ts +0 -43
  118. package/dist/skills/memory-query-tool.js +0 -127
  119. package/dist/skills/memory-store.d.ts +0 -66
  120. package/dist/skills/memory-store.js +0 -228
  121. package/dist/skills/memory-tool.d.ts +0 -67
  122. package/dist/skills/memory-tool.js +0 -192
  123. package/dist/skills/portable-tool.d.ts +0 -71
  124. package/dist/skills/portable-tool.js +0 -14
  125. package/dist/skills/qmemory-adapter.d.ts +0 -52
  126. package/dist/skills/qmemory-adapter.js +0 -165
  127. package/dist/skills/skill-frontmatter.d.ts +0 -19
  128. package/dist/skills/skill-frontmatter.js +0 -344
  129. package/dist/skills/skill-guard.d.ts +0 -23
  130. package/dist/skills/skill-guard.js +0 -229
  131. package/dist/skills/skill-loader.d.ts +0 -16
  132. package/dist/skills/skill-loader.js +0 -303
  133. package/dist/skills/skill-source.d.ts +0 -119
  134. package/dist/skills/skill-source.js +0 -126
  135. package/dist/skills/skill-types.d.ts +0 -199
  136. package/dist/skills/skill-types.js +0 -6
  137. package/dist/skills/think-tool.d.ts +0 -16
  138. package/dist/skills/think-tool.js +0 -59
  139. package/dist/skills/todo-tool.d.ts +0 -63
  140. package/dist/skills/todo-tool.js +0 -114
  141. package/dist/skills/tools/agent-tool.d.ts +0 -91
  142. package/dist/skills/tools/agent-tool.js +0 -142
  143. package/dist/skills/tools/apply-patch-tool.d.ts +0 -29
  144. package/dist/skills/tools/apply-patch-tool.js +0 -184
  145. package/dist/skills/tools/ask-user-tool.d.ts +0 -80
  146. package/dist/skills/tools/ask-user-tool.js +0 -121
  147. package/dist/skills/tools/brief-tool.d.ts +0 -74
  148. package/dist/skills/tools/brief-tool.js +0 -95
  149. package/dist/skills/tools/browser-tool.d.ts +0 -114
  150. package/dist/skills/tools/browser-tool.js +0 -155
  151. package/dist/skills/tools/checkpoint-tool.d.ts +0 -66
  152. package/dist/skills/tools/checkpoint-tool.js +0 -102
  153. package/dist/skills/tools/config-tool.d.ts +0 -63
  154. package/dist/skills/tools/config-tool.js +0 -143
  155. package/dist/skills/tools/cron-tool.d.ts +0 -116
  156. package/dist/skills/tools/cron-tool.js +0 -175
  157. package/dist/skills/tools/edit-tool.d.ts +0 -43
  158. package/dist/skills/tools/edit-tool.js +0 -70
  159. package/dist/skills/tools/exec-tool.d.ts +0 -102
  160. package/dist/skills/tools/exec-tool.js +0 -133
  161. package/dist/skills/tools/image-generate-tool.d.ts +0 -62
  162. package/dist/skills/tools/image-generate-tool.js +0 -67
  163. package/dist/skills/tools/instructions-tool.d.ts +0 -103
  164. package/dist/skills/tools/instructions-tool.js +0 -187
  165. package/dist/skills/tools/lsp-tool.d.ts +0 -153
  166. package/dist/skills/tools/lsp-tool.js +0 -227
  167. package/dist/skills/tools/mcp-client-types.d.ts +0 -269
  168. package/dist/skills/tools/mcp-client-types.js +0 -53
  169. package/dist/skills/tools/mcp-tool.d.ts +0 -249
  170. package/dist/skills/tools/mcp-tool.js +0 -503
  171. package/dist/skills/tools/memory-tool.d.ts +0 -74
  172. package/dist/skills/tools/memory-tool.js +0 -88
  173. package/dist/skills/tools/monitor-tool.d.ts +0 -113
  174. package/dist/skills/tools/monitor-tool.js +0 -131
  175. package/dist/skills/tools/music-generate-tool.d.ts +0 -55
  176. package/dist/skills/tools/music-generate-tool.js +0 -62
  177. package/dist/skills/tools/notify-tool.d.ts +0 -53
  178. package/dist/skills/tools/notify-tool.js +0 -62
  179. package/dist/skills/tools/patch-tool.d.ts +0 -45
  180. package/dist/skills/tools/patch-tool.js +0 -505
  181. package/dist/skills/tools/pdf-tool.d.ts +0 -66
  182. package/dist/skills/tools/pdf-tool.js +0 -88
  183. package/dist/skills/tools/plan-mode-tool.d.ts +0 -59
  184. package/dist/skills/tools/plan-mode-tool.js +0 -122
  185. package/dist/skills/tools/read-tool.d.ts +0 -51
  186. package/dist/skills/tools/read-tool.js +0 -84
  187. package/dist/skills/tools/repl-tool.d.ts +0 -70
  188. package/dist/skills/tools/repl-tool.js +0 -69
  189. package/dist/skills/tools/search-tool.d.ts +0 -112
  190. package/dist/skills/tools/search-tool.js +0 -225
  191. package/dist/skills/tools/send-message-tool.d.ts +0 -51
  192. package/dist/skills/tools/send-message-tool.js +0 -76
  193. package/dist/skills/tools/skill-list-tool.d.ts +0 -33
  194. package/dist/skills/tools/skill-list-tool.js +0 -54
  195. package/dist/skills/tools/skill-manage-tool.d.ts +0 -73
  196. package/dist/skills/tools/skill-manage-tool.js +0 -153
  197. package/dist/skills/tools/skill-view-tool.d.ts +0 -37
  198. package/dist/skills/tools/skill-view-tool.js +0 -72
  199. package/dist/skills/tools/sleep-tool.d.ts +0 -49
  200. package/dist/skills/tools/sleep-tool.js +0 -81
  201. package/dist/skills/tools/structured-output-tool.d.ts +0 -116
  202. package/dist/skills/tools/structured-output-tool.js +0 -176
  203. package/dist/skills/tools/task-tool.d.ts +0 -104
  204. package/dist/skills/tools/task-tool.js +0 -161
  205. package/dist/skills/tools/team-tool.d.ts +0 -89
  206. package/dist/skills/tools/team-tool.js +0 -105
  207. package/dist/skills/tools/tool-search-tool.d.ts +0 -51
  208. package/dist/skills/tools/tool-search-tool.js +0 -110
  209. package/dist/skills/tools/tts-tool.d.ts +0 -38
  210. package/dist/skills/tools/tts-tool.js +0 -45
  211. package/dist/skills/tools/video-edit-tool.d.ts +0 -69
  212. package/dist/skills/tools/video-edit-tool.js +0 -74
  213. package/dist/skills/tools/video-generate-tool.d.ts +0 -62
  214. package/dist/skills/tools/video-generate-tool.js +0 -66
  215. package/dist/skills/tools/video-merge-tool.d.ts +0 -105
  216. package/dist/skills/tools/video-merge-tool.js +0 -92
  217. package/dist/skills/tools/video-upscale-tool.d.ts +0 -45
  218. package/dist/skills/tools/video-upscale-tool.js +0 -52
  219. package/dist/skills/tools/web-fetch-tool.d.ts +0 -78
  220. package/dist/skills/tools/web-fetch-tool.js +0 -92
  221. package/dist/skills/tools/web-search-tool.d.ts +0 -57
  222. package/dist/skills/tools/web-search-tool.js +0 -86
  223. package/dist/skills/tools/worktree-tool.d.ts +0 -69
  224. package/dist/skills/tools/worktree-tool.js +0 -147
  225. package/dist/skills/tools/write-tool.d.ts +0 -45
  226. package/dist/skills/tools/write-tool.js +0 -81
@@ -1,147 +0,0 @@
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
- /**
15
- * Resolve the execution plan for a team request.
16
- * Validates the request, resolves dependencies into ordered batches,
17
- * and determines the execution topology.
18
- */
19
- export function resolveTeamExecutionPlan(request) {
20
- const agents = request.agents;
21
- if (agents.length === 0) {
22
- return { batches: [], totalBudget: 0, state: "planning" };
23
- }
24
- if (agents.length > 8) {
25
- throw new Error(`Team cannot have more than 8 agents (got ${agents.length})`);
26
- }
27
- // For "parallel" mode — single batch with all agents
28
- if (request.mode === "parallel") {
29
- return {
30
- batches: [{ agents, mode: "parallel" }],
31
- totalBudget: agents.length * 50000,
32
- state: "spawning",
33
- };
34
- }
35
- // For "sequential" or "pipeline" — one agent per batch
36
- if (request.mode === "sequential" || request.mode === "pipeline") {
37
- return {
38
- batches: agents.map((a) => ({ agents: [a], mode: "serial" })),
39
- totalBudget: agents.length * 50000,
40
- state: "spawning",
41
- };
42
- }
43
- // "adaptive" — planner first, then remaining in parallel
44
- const planners = agents.filter((a) => a.role === "planner");
45
- const rest = agents.filter((a) => a.role !== "planner");
46
- const batches = [];
47
- if (planners.length > 0) {
48
- batches.push({ agents: planners, mode: "serial" });
49
- }
50
- if (rest.length > 0) {
51
- batches.push({ agents: rest, mode: "parallel" });
52
- }
53
- return {
54
- batches,
55
- totalBudget: agents.length * 50000,
56
- state: "spawning",
57
- };
58
- }
59
- /**
60
- * Aggregate results from team agents according to the aggregation policy.
61
- */
62
- export function aggregateTeamToolResults(results, policy) {
63
- const totalTokens = results.reduce((sum, r) => sum + r.result.tokensUsed, 0);
64
- const allOk = results.every((r) => r.result.ok);
65
- const anyOk = results.some((r) => r.result.ok);
66
- switch (policy) {
67
- case "first-success": {
68
- const first = results.find((r) => r.result.ok);
69
- return {
70
- ok: !!first,
71
- output: first?.result.output || "(No agent succeeded)",
72
- agentResults: results,
73
- totalTokensUsed: totalTokens,
74
- finalState: first ? "completed" : "failed",
75
- };
76
- }
77
- case "merge-all": {
78
- const outputs = results.map((r) => `### ${r.role} (${r.agentId})\n${r.result.output || "(no output)"}`);
79
- return {
80
- ok: anyOk,
81
- output: outputs.join("\n\n---\n\n"),
82
- agentResults: results,
83
- totalTokensUsed: totalTokens,
84
- finalState: anyOk ? "completed" : "failed",
85
- };
86
- }
87
- case "reviewer-gate": {
88
- const reviewer = results.find((r) => r.role === "reviewer");
89
- const executors = results.filter((r) => r.role !== "reviewer");
90
- const executorOutput = executors.map((r) => r.result.output).filter(Boolean).join("\n\n");
91
- if (reviewer && reviewer.result.ok) {
92
- return {
93
- ok: true,
94
- output: `## Reviewed Output\n${executorOutput}\n\n## Review\n${reviewer.result.output}`,
95
- agentResults: results,
96
- totalTokensUsed: totalTokens,
97
- finalState: "completed",
98
- };
99
- }
100
- return {
101
- ok: false,
102
- output: `Review failed: ${reviewer?.result.output || "no reviewer result"}`,
103
- agentResults: results,
104
- totalTokensUsed: totalTokens,
105
- finalState: "failed",
106
- };
107
- }
108
- case "planner-sync": {
109
- // Planner agent's output is the consolidated result
110
- const planner = results.find((r) => r.role === "planner");
111
- if (planner) {
112
- return {
113
- ok: planner.result.ok,
114
- output: planner.result.output,
115
- agentResults: results,
116
- totalTokensUsed: totalTokens,
117
- finalState: planner.result.ok ? "completed" : "failed",
118
- };
119
- }
120
- // Fallback to merge-all
121
- return aggregateTeamToolResults(results, "merge-all");
122
- }
123
- case "majority-vote":
124
- default: {
125
- // Simple: all outputs merged
126
- return aggregateTeamToolResults(results, "merge-all");
127
- }
128
- }
129
- }
130
- /**
131
- * Map a team tool_call into the format needed for the tool loop to dispatch.
132
- * Returns the list of fork configs the tool loop should execute.
133
- */
134
- export function mapTeamRequestToForkConfigs(request, agentRegistry) {
135
- return request.agents.map((agent) => {
136
- const def = agentRegistry(agent.agentType);
137
- if (!def) {
138
- throw new Error(`Unknown agent type "${agent.agentType}" in team request`);
139
- }
140
- return {
141
- agentDef: def,
142
- prompt: agent.prompt,
143
- maxTurns: agent.maxTurns,
144
- role: agent.role,
145
- };
146
- });
147
- }
@@ -1,54 +0,0 @@
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>;
@@ -1,164 +0,0 @@
1
- function resolveToolName(tool) {
2
- if (tool.function && typeof tool.function === "object" && typeof tool.function.name === "string") {
3
- return tool.function.name.trim();
4
- }
5
- if (typeof tool.name === "string") {
6
- return tool.name.trim();
7
- }
8
- return "";
9
- }
10
- function isEligibleStatus(status) {
11
- return status === "enabled-eligible" || status === "installed-awaiting-approval";
12
- }
13
- function buildEligibilityMap(eligibility) {
14
- return new Map((eligibility ?? []).map((entry) => [entry.toolName, entry]));
15
- }
16
- export function filterEligibleTools(params) {
17
- if (!params.eligibility?.length) {
18
- return [...params.tools];
19
- }
20
- const eligibilityMap = buildEligibilityMap(params.eligibility);
21
- return params.tools.filter((tool) => {
22
- const name = resolveToolName(tool);
23
- if (!name) {
24
- return false;
25
- }
26
- const eligibility = eligibilityMap.get(name);
27
- return !eligibility || isEligibleStatus(eligibility.status);
28
- });
29
- }
30
- export function normalizeAnthropicFunctionToolDefinition(tool) {
31
- if (!tool || typeof tool !== "object" || Array.isArray(tool)) {
32
- return undefined;
33
- }
34
- const toolRecord = tool;
35
- if (toolRecord.function && typeof toolRecord.function === "object") {
36
- return toolRecord;
37
- }
38
- const name = typeof toolRecord.name === "string" ? toolRecord.name.trim() : "";
39
- if (!name) {
40
- return toolRecord;
41
- }
42
- const functionSpec = {
43
- name,
44
- parameters: toolRecord.input_schema && typeof toolRecord.input_schema === "object"
45
- ? toolRecord.input_schema
46
- : toolRecord.parameters && typeof toolRecord.parameters === "object"
47
- ? toolRecord.parameters
48
- : { type: "object", properties: {} },
49
- };
50
- if (typeof toolRecord.description === "string" && toolRecord.description.trim()) {
51
- functionSpec.description = toolRecord.description;
52
- }
53
- if (typeof toolRecord.strict === "boolean") {
54
- functionSpec.strict = toolRecord.strict;
55
- }
56
- return {
57
- type: "function",
58
- function: functionSpec,
59
- };
60
- }
61
- export function normalizeAnthropicToolChoice(toolChoice) {
62
- if (!toolChoice || typeof toolChoice !== "object" || Array.isArray(toolChoice)) {
63
- return toolChoice;
64
- }
65
- const choice = toolChoice;
66
- if (choice.type === "auto") {
67
- return "auto";
68
- }
69
- if (choice.type === "none") {
70
- return "none";
71
- }
72
- if (choice.type === "required" || choice.type === "any") {
73
- return "required";
74
- }
75
- if (choice.type === "tool" && typeof choice.name === "string" && choice.name.trim()) {
76
- return {
77
- type: "function",
78
- function: { name: choice.name.trim() },
79
- };
80
- }
81
- return toolChoice;
82
- }
83
- export function applyToolChoiceCompatibility(params) {
84
- const warnings = [];
85
- const compatibility = params.compatibility ?? {};
86
- let normalizedToolChoice = params.toolChoice;
87
- if (params.thinkingEnabled && compatibility.requireAutoWhenThinking) {
88
- const type = typeof normalizedToolChoice === "object" && normalizedToolChoice && !Array.isArray(normalizedToolChoice)
89
- ? String(normalizedToolChoice.type ?? "")
90
- : normalizedToolChoice;
91
- if (type && type !== "auto" && type !== "none") {
92
- warnings.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility.");
93
- normalizedToolChoice = "auto";
94
- }
95
- }
96
- if (normalizedToolChoice === "required" && compatibility.allowRequiredToolChoice === false) {
97
- const fallback = compatibility.requiredFallback ?? "auto";
98
- warnings.push(`tool_choice=required is not supported by this provider; downgraded to ${fallback}.`);
99
- normalizedToolChoice = fallback;
100
- }
101
- if (normalizedToolChoice
102
- && typeof normalizedToolChoice === "object"
103
- && !Array.isArray(normalizedToolChoice)
104
- && normalizedToolChoice.type === "function"
105
- && compatibility.allowNamedToolChoice === false) {
106
- const fallback = compatibility.namedFallback ?? "required";
107
- warnings.push(`named tool_choice is not supported by this provider; downgraded to ${fallback}.`);
108
- normalizedToolChoice = fallback;
109
- }
110
- return { normalizedToolChoice, warnings };
111
- }
112
- export function applyToolChoicePolicy(params) {
113
- const compatibilityResult = applyToolChoiceCompatibility({
114
- toolChoice: params.toolChoice,
115
- thinkingEnabled: params.thinkingEnabled,
116
- compatibility: params.compatibility,
117
- });
118
- const toolChoice = compatibilityResult.normalizedToolChoice;
119
- const warnings = [...compatibilityResult.warnings];
120
- const tools = filterEligibleTools({
121
- tools: params.tools,
122
- eligibility: params.eligibility,
123
- });
124
- if (!toolChoice || toolChoice === "auto") {
125
- return { tools, normalizedToolChoice: toolChoice, warnings };
126
- }
127
- if (toolChoice === "none") {
128
- return { tools: [], normalizedToolChoice: "none", warnings };
129
- }
130
- if (toolChoice === "required") {
131
- if (tools.length === 0) {
132
- throw new Error("tool_choice=required but no tools were provided");
133
- }
134
- return {
135
- tools,
136
- normalizedToolChoice: "required",
137
- extraSystemPrompt: "You must call one of the available tools before responding.",
138
- warnings,
139
- };
140
- }
141
- if (typeof toolChoice === "object" && !Array.isArray(toolChoice) && toolChoice.type === "function") {
142
- const functionChoice = (toolChoice.function ?? undefined);
143
- const targetName = typeof functionChoice?.name === "string"
144
- ? functionChoice.name.trim()
145
- : "";
146
- if (!targetName) {
147
- throw new Error("tool_choice.function.name is required");
148
- }
149
- const matchedTools = tools.filter((tool) => resolveToolName(tool) === targetName);
150
- if (matchedTools.length === 0) {
151
- throw new Error(`tool_choice requested unknown tool: ${targetName}`);
152
- }
153
- return {
154
- tools: matchedTools,
155
- normalizedToolChoice: {
156
- type: "function",
157
- function: { name: targetName },
158
- },
159
- extraSystemPrompt: `You must call the ${targetName} tool before responding.`,
160
- warnings,
161
- };
162
- }
163
- return { tools, normalizedToolChoice: toolChoice, warnings };
164
- }
@@ -1,50 +0,0 @@
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>;
@@ -1,133 +0,0 @@
1
- import { injectDanglingToolCallPlaceholders, repairOpenAiResponsesItems, stripForcedStopAssistantToolMetadata, sanitizeOpenAiChatMessages, } from "./conversation-repair.js";
2
- function collectChatPendingToolCallIds(messages) {
3
- const called = new Set();
4
- const completed = new Set();
5
- for (const message of messages) {
6
- if (message.role === "assistant" && Array.isArray(message.tool_calls)) {
7
- for (const toolCall of message.tool_calls) {
8
- if (typeof toolCall.id === "string" && toolCall.id) {
9
- called.add(toolCall.id);
10
- }
11
- }
12
- }
13
- if (message.role === "tool" && typeof message.tool_call_id === "string" && message.tool_call_id) {
14
- completed.add(message.tool_call_id);
15
- }
16
- }
17
- return [...called].filter((callId) => !completed.has(callId));
18
- }
19
- function collectChatCompletedToolCallIds(messages) {
20
- const completed = new Set();
21
- for (const message of messages) {
22
- if (message.role === "tool" && typeof message.tool_call_id === "string" && message.tool_call_id) {
23
- completed.add(message.tool_call_id);
24
- }
25
- }
26
- return [...completed];
27
- }
28
- function collectResponsesPendingToolCallIds(items) {
29
- const called = new Set();
30
- const completed = new Set();
31
- for (const item of items) {
32
- if (item.type === "function_call") {
33
- const callId = typeof item.call_id === "string" && item.call_id
34
- ? item.call_id
35
- : typeof item.id === "string"
36
- ? item.id
37
- : "";
38
- if (callId) {
39
- called.add(callId);
40
- }
41
- }
42
- if (item.type === "function_call_output" && typeof item.call_id === "string" && item.call_id) {
43
- completed.add(item.call_id);
44
- }
45
- }
46
- return [...called].filter((callId) => !completed.has(callId));
47
- }
48
- function collectResponsesCompletedToolCallIds(items) {
49
- const completed = new Set();
50
- for (const item of items) {
51
- if (item.type === "function_call_output" && typeof item.call_id === "string" && item.call_id) {
52
- completed.add(item.call_id);
53
- }
54
- }
55
- return [...completed];
56
- }
57
- export function createToolLoopState(params) {
58
- return {
59
- round: params.round ?? 0,
60
- maxRounds: params.maxRounds,
61
- pendingToolCallIds: [...(params.pendingToolCallIds ?? [])],
62
- completedToolCallIds: [...(params.completedToolCallIds ?? [])],
63
- lastStopReason: params.lastStopReason,
64
- replayMessages: [...(params.replayMessages ?? [])],
65
- };
66
- }
67
- export function advanceToolLoopState(state, params) {
68
- return {
69
- round: state.round + 1,
70
- maxRounds: state.maxRounds,
71
- pendingToolCallIds: [...(params.pendingToolCallIds ?? state.pendingToolCallIds)],
72
- completedToolCallIds: [...(params.completedToolCallIds ?? state.completedToolCallIds)],
73
- lastStopReason: params.lastStopReason ?? state.lastStopReason,
74
- replayMessages: [...(params.replayMessages ?? state.replayMessages)],
75
- };
76
- }
77
- export function settleToolLoopState(state, params) {
78
- return {
79
- round: state.round,
80
- maxRounds: state.maxRounds,
81
- pendingToolCallIds: [],
82
- completedToolCallIds: [...(params.completedToolCallIds ?? state.completedToolCallIds)],
83
- lastStopReason: params.lastStopReason ?? state.lastStopReason,
84
- replayMessages: [...(params.replayMessages ?? state.replayMessages)],
85
- };
86
- }
87
- export function recoverToolLoopStateFromChatConversation(params) {
88
- const recoveryActions = [];
89
- const sanitizedMessages = sanitizeOpenAiChatMessages(params.replayMessages);
90
- if (sanitizedMessages.length !== params.replayMessages.length) {
91
- recoveryActions.push({ kind: "drop-orphan-tool-result", detail: "Removed orphan tool results or invalid assistant tool calls." });
92
- }
93
- const strippedMessages = stripForcedStopAssistantToolMetadata(sanitizedMessages, params.options);
94
- if (strippedMessages.some((message, index) => message !== sanitizedMessages[index])) {
95
- recoveryActions.push({ kind: "strip-forced-stop-tool-metadata", detail: "Removed assistant tool-call metadata after forced stop." });
96
- }
97
- const repairedMessages = injectDanglingToolCallPlaceholders(strippedMessages, params.options);
98
- if (repairedMessages.length > strippedMessages.length) {
99
- recoveryActions.push({ kind: "inject-placeholder-tool-result", detail: "Injected placeholder tool result for pending tool calls." });
100
- }
101
- return {
102
- state: createToolLoopState({
103
- maxRounds: params.maxRounds,
104
- round: params.round,
105
- lastStopReason: params.lastStopReason,
106
- replayMessages: repairedMessages,
107
- pendingToolCallIds: collectChatPendingToolCallIds(repairedMessages),
108
- completedToolCallIds: collectChatCompletedToolCallIds(repairedMessages),
109
- }),
110
- recoveryActions,
111
- };
112
- }
113
- export function recoverToolLoopStateFromResponsesItems(params) {
114
- const repairedItems = repairOpenAiResponsesItems(params.replayItems, params.options);
115
- const recoveryActions = [];
116
- if (repairedItems.length !== params.replayItems.length) {
117
- recoveryActions.push({ kind: "drop-trailing-reasoning", detail: "Dropped dangling reasoning blocks or injected missing function_call_output items." });
118
- }
119
- if (repairedItems.some((item, index) => item !== params.replayItems[index] && item.type === "function_call")) {
120
- recoveryActions.push({ kind: "rewrite-openai-function-call-pair", detail: "Rewrote OpenAI function_call pairing ids for replay compatibility." });
121
- }
122
- return {
123
- state: createToolLoopState({
124
- maxRounds: params.maxRounds,
125
- round: params.round,
126
- lastStopReason: params.lastStopReason,
127
- replayMessages: repairedItems,
128
- pendingToolCallIds: collectResponsesPendingToolCallIds(repairedItems),
129
- completedToolCallIds: collectResponsesCompletedToolCallIds(repairedItems),
130
- }),
131
- recoveryActions,
132
- };
133
- }
@@ -1,39 +0,0 @@
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;