wave-agent-sdk 1.0.4 → 1.0.6
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/agent.d.ts +23 -1
- package/dist/agent.js +34 -4
- package/dist/managers/aiManager.d.ts +36 -0
- package/dist/managers/aiManager.js +240 -8
- package/dist/managers/messageManager.d.ts +1 -3
- package/dist/managers/messageManager.js +19 -9
- package/dist/managers/slashCommandManager.js +28 -0
- package/dist/managers/subagentManager.d.ts +0 -2
- package/dist/services/session.js +2 -9
- package/dist/telemetry/instrumentation.d.ts +1 -1
- package/dist/telemetry/instrumentation.js +57 -28
- package/dist/tools/bashTool.js +16 -6
- package/dist/tools/grepTool.js +11 -3
- package/dist/types/index.d.ts +3 -0
- package/dist/types/messaging.d.ts +2 -0
- package/dist/utils/containerSetup.js +0 -3
- package/dist/utils/messageOperations.d.ts +10 -1
- package/dist/utils/messageOperations.js +19 -1
- package/dist/utils/notificationXml.js +5 -0
- package/dist/utils/ripgrep.d.ts +4 -4
- package/dist/utils/ripgrep.js +4 -27
- package/package.json +20 -8
- package/bin/rg +0 -79
- package/dist/managers/forkedAgentManager.d.ts +0 -50
- package/dist/managers/forkedAgentManager.js +0 -130
- package/scripts/install_ripgrep.js +0 -111
- package/scripts/postinstall.js +0 -38
- package/src/agent.ts +0 -1271
- package/src/constants/subagents.ts +0 -4
- package/src/constants/toolLimits.ts +0 -15
- package/src/constants/tools.ts +0 -24
- package/src/core/plugin.ts +0 -237
- package/src/core/session.ts +0 -9
- package/src/index.ts +0 -38
- package/src/managers/MemoryRuleManager.ts +0 -198
- package/src/managers/aiManager.ts +0 -2429
- package/src/managers/backgroundTaskManager.ts +0 -480
- package/src/managers/bangManager.ts +0 -119
- package/src/managers/cronManager.ts +0 -401
- package/src/managers/foregroundTaskManager.ts +0 -30
- package/src/managers/forkedAgentManager.ts +0 -216
- package/src/managers/hookManager.ts +0 -1089
- package/src/managers/liveConfigManager.ts +0 -445
- package/src/managers/lspManager.ts +0 -470
- package/src/managers/mcpManager.ts +0 -1010
- package/src/managers/messageManager.ts +0 -1180
- package/src/managers/messageQueue.ts +0 -157
- package/src/managers/permissionManager.ts +0 -1140
- package/src/managers/planManager.ts +0 -112
- package/src/managers/pluginManager.ts +0 -330
- package/src/managers/pluginScopeManager.ts +0 -124
- package/src/managers/reversionManager.ts +0 -178
- package/src/managers/skillManager.ts +0 -578
- package/src/managers/slashCommandManager.ts +0 -564
- package/src/managers/subagentManager.ts +0 -915
- package/src/managers/toolManager.ts +0 -489
- package/src/managers/workflowManager.ts +0 -493
- package/src/prompts/autoMemory.ts +0 -33
- package/src/prompts/autoMemoryExtraction.ts +0 -146
- package/src/prompts/index.ts +0 -506
- package/src/prompts/planModeReminders.ts +0 -126
- package/src/services/GitService.ts +0 -131
- package/src/services/MarketplaceService.ts +0 -1052
- package/src/services/MemoryRuleService.ts +0 -71
- package/src/services/aiService.ts +0 -919
- package/src/services/authService.ts +0 -565
- package/src/services/autoMemoryService.ts +0 -280
- package/src/services/configurationService.ts +0 -1520
- package/src/services/fileWatcher.ts +0 -319
- package/src/services/hook.ts +0 -348
- package/src/services/initializationService.ts +0 -357
- package/src/services/interactionService.ts +0 -229
- package/src/services/jsonlHandler.ts +0 -295
- package/src/services/memory.ts +0 -234
- package/src/services/pluginLoader.ts +0 -252
- package/src/services/remoteSettingsService.ts +0 -366
- package/src/services/reversionService.ts +0 -122
- package/src/services/session.ts +0 -922
- package/src/services/taskManager.ts +0 -321
- package/src/telemetry/events.ts +0 -65
- package/src/telemetry/instrumentation.ts +0 -499
- package/src/telemetry/sessionTracing.ts +0 -348
- package/src/tools/agentTool.ts +0 -322
- package/src/tools/askUserQuestion.ts +0 -160
- package/src/tools/bashTool.ts +0 -621
- package/src/tools/buildTool.ts +0 -61
- package/src/tools/cronCreateTool.ts +0 -161
- package/src/tools/cronDeleteTool.ts +0 -51
- package/src/tools/cronListTool.ts +0 -47
- package/src/tools/editTool.ts +0 -313
- package/src/tools/enterPlanMode.ts +0 -124
- package/src/tools/enterWorktreeTool.ts +0 -190
- package/src/tools/exitPlanMode.ts +0 -139
- package/src/tools/exitWorktreeTool.ts +0 -236
- package/src/tools/globTool.ts +0 -167
- package/src/tools/grepTool.ts +0 -399
- package/src/tools/lspTool.ts +0 -883
- package/src/tools/readTool.ts +0 -426
- package/src/tools/skillTool.ts +0 -248
- package/src/tools/taskManagementTools.ts +0 -574
- package/src/tools/taskStopTool.ts +0 -78
- package/src/tools/types.ts +0 -137
- package/src/tools/webFetchTool.ts +0 -373
- package/src/tools/workflowTool.ts +0 -205
- package/src/tools/writeTool.ts +0 -267
- package/src/types/agent.ts +0 -128
- package/src/types/auth.ts +0 -19
- package/src/types/commands.ts +0 -30
- package/src/types/config.ts +0 -43
- package/src/types/configuration.ts +0 -168
- package/src/types/core.ts +0 -105
- package/src/types/cron.ts +0 -13
- package/src/types/environment.ts +0 -106
- package/src/types/fileSearch.ts +0 -4
- package/src/types/history.ts +0 -7
- package/src/types/hooks.ts +0 -256
- package/src/types/index.ts +0 -41
- package/src/types/lsp.ts +0 -98
- package/src/types/marketplace.ts +0 -71
- package/src/types/mcp.ts +0 -43
- package/src/types/memoryRule.ts +0 -31
- package/src/types/messaging.ts +0 -114
- package/src/types/permissions.ts +0 -80
- package/src/types/plugins.ts +0 -39
- package/src/types/processes.ts +0 -99
- package/src/types/reversion.ts +0 -29
- package/src/types/session.ts +0 -12
- package/src/types/skills.ts +0 -108
- package/src/types/tasks.ts +0 -13
- package/src/types/telemetry.ts +0 -98
- package/src/types/tools.ts +0 -44
- package/src/types/workflow.ts +0 -6
- package/src/utils/abortUtils.ts +0 -118
- package/src/utils/atomicWrite.ts +0 -61
- package/src/utils/bashParser.ts +0 -899
- package/src/utils/cacheControlUtils.ts +0 -426
- package/src/utils/commandArgumentParser.ts +0 -161
- package/src/utils/commandPathResolver.ts +0 -88
- package/src/utils/configPaths.ts +0 -220
- package/src/utils/configValidator.ts +0 -100
- package/src/utils/constants.ts +0 -39
- package/src/utils/container.ts +0 -92
- package/src/utils/containerSetup.ts +0 -371
- package/src/utils/convertMessagesForAPI.ts +0 -326
- package/src/utils/cronTasks.ts +0 -128
- package/src/utils/cronTasksLock.ts +0 -182
- package/src/utils/cronToHuman.ts +0 -99
- package/src/utils/customCommands.ts +0 -95
- package/src/utils/editUtils.ts +0 -20
- package/src/utils/fileFormat.ts +0 -40
- package/src/utils/fileSearch.ts +0 -151
- package/src/utils/fileUtils.ts +0 -223
- package/src/utils/gitUtils.ts +0 -315
- package/src/utils/globalLogger.ts +0 -128
- package/src/utils/groupMessagesByApiRound.ts +0 -121
- package/src/utils/hookMatcher.ts +0 -176
- package/src/utils/markdownParser.ts +0 -317
- package/src/utils/mcpUtils.ts +0 -138
- package/src/utils/messageOperations.ts +0 -641
- package/src/utils/modelCapabilities.ts +0 -30
- package/src/utils/nameGenerator.ts +0 -99
- package/src/utils/notificationXml.ts +0 -57
- package/src/utils/openaiClient.ts +0 -251
- package/src/utils/parseCronExpression.ts +0 -78
- package/src/utils/path.ts +0 -72
- package/src/utils/pathEncoder.ts +0 -400
- package/src/utils/pathSafety.ts +0 -40
- package/src/utils/promptHistory.ts +0 -168
- package/src/utils/ripgrep.ts +0 -35
- package/src/utils/shellResolver.ts +0 -190
- package/src/utils/skillParser.ts +0 -246
- package/src/utils/stringUtils.ts +0 -156
- package/src/utils/subagentParser.ts +0 -279
- package/src/utils/taskReminder.ts +0 -96
- package/src/utils/tokenCalculation.ts +0 -43
- package/src/utils/tokenEstimate.ts +0 -34
- package/src/utils/toolResultStorage.ts +0 -117
- package/src/utils/worktreeSession.ts +0 -26
- package/src/utils/worktreeUtils.ts +0 -786
- package/src/workflow/budgetTracker.ts +0 -34
- package/src/workflow/concurrencyLimiter.ts +0 -47
- package/src/workflow/journal.ts +0 -95
- package/src/workflow/progressReporter.ts +0 -141
- package/src/workflow/runState.ts +0 -65
- package/src/workflow/scriptRuntime.ts +0 -274
- package/src/workflow/structuredOutput.ts +0 -123
- package/src/workflow/types.ts +0 -101
- package/src/workflow/workflowApis.ts +0 -410
- package/vendor/ripgrep/linux-aarch64/rg +0 -0
- package/vendor/ripgrep/linux-x86_64/rg +0 -0
- package/vendor/ripgrep/macos-aarch64/rg +0 -0
- package/vendor/ripgrep/macos-x86_64/rg +0 -0
- package/vendor/ripgrep/windows-aarch64/rg.exe +0 -0
- package/vendor/ripgrep/windows-x86_64/rg.exe +0 -0
|
@@ -1,123 +0,0 @@
|
|
|
1
|
-
import type { ToolPlugin, ToolResult } from "../tools/types.js";
|
|
2
|
-
|
|
3
|
-
const STRUCTURED_OUTPUT_TOOL_NAME = "StructuredOutput";
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Creates a system prompt addition that instructs the agent to use structured output
|
|
7
|
-
*/
|
|
8
|
-
export function createStructuredOutputPrompt(schema: object): string {
|
|
9
|
-
return `\n\nIMPORTANT: You MUST call the ${STRUCTURED_OUTPUT_TOOL_NAME} tool with your final answer. Do not just write the answer as text — call the tool with a JSON object matching this schema:\n${JSON.stringify(schema, null, 2)}\n\nCall this tool exactly once with your complete answer.`;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* Creates a StructuredOutput ToolPlugin that enforces the given schema
|
|
14
|
-
*/
|
|
15
|
-
export function createStructuredOutputTool(schema: object): ToolPlugin {
|
|
16
|
-
return {
|
|
17
|
-
name: STRUCTURED_OUTPUT_TOOL_NAME,
|
|
18
|
-
config: {
|
|
19
|
-
type: "function" as const,
|
|
20
|
-
function: {
|
|
21
|
-
name: STRUCTURED_OUTPUT_TOOL_NAME,
|
|
22
|
-
description:
|
|
23
|
-
"Output structured data matching the required schema. Call this with your final answer.",
|
|
24
|
-
parameters: schema as Record<string, unknown>,
|
|
25
|
-
},
|
|
26
|
-
},
|
|
27
|
-
execute: async (args: Record<string, unknown>): Promise<ToolResult> => {
|
|
28
|
-
// The tool just returns the args as-is — the real validation happens
|
|
29
|
-
// in extractStructuredResult after the agent completes
|
|
30
|
-
return {
|
|
31
|
-
success: true,
|
|
32
|
-
content: JSON.stringify(args),
|
|
33
|
-
};
|
|
34
|
-
},
|
|
35
|
-
};
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* Extract structured result from a completed subagent's messages.
|
|
40
|
-
* Looks for StructuredOutput tool calls in the messages.
|
|
41
|
-
* Falls back to JSON.parse on the last assistant message text.
|
|
42
|
-
*/
|
|
43
|
-
export function extractStructuredResult(
|
|
44
|
-
messages: Array<{
|
|
45
|
-
role: string;
|
|
46
|
-
content?: string;
|
|
47
|
-
tool_calls?: Array<{ function: { name: string; arguments: string } }>;
|
|
48
|
-
}>,
|
|
49
|
-
schema: object,
|
|
50
|
-
): unknown | null {
|
|
51
|
-
// Search messages in reverse for a StructuredOutput tool call
|
|
52
|
-
for (let i = messages.length - 1; i >= 0; i--) {
|
|
53
|
-
const msg = messages[i];
|
|
54
|
-
if (msg.tool_calls) {
|
|
55
|
-
for (const tc of msg.tool_calls) {
|
|
56
|
-
if (tc.function.name === STRUCTURED_OUTPUT_TOOL_NAME) {
|
|
57
|
-
try {
|
|
58
|
-
const parsed = JSON.parse(tc.function.arguments);
|
|
59
|
-
if (validateAgainstSchema(parsed, schema)) {
|
|
60
|
-
return parsed;
|
|
61
|
-
}
|
|
62
|
-
} catch {
|
|
63
|
-
// Parse error — continue searching
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
// Fallback: try to extract JSON from the last assistant message
|
|
71
|
-
for (let i = messages.length - 1; i >= 0; i--) {
|
|
72
|
-
const msg = messages[i];
|
|
73
|
-
if (msg.role === "assistant" && msg.content) {
|
|
74
|
-
// Try to find JSON in the content
|
|
75
|
-
const jsonMatch = msg.content.match(/```json\n([\s\S]*?)\n```/);
|
|
76
|
-
if (jsonMatch) {
|
|
77
|
-
try {
|
|
78
|
-
const parsed = JSON.parse(jsonMatch[1]);
|
|
79
|
-
if (validateAgainstSchema(parsed, schema)) {
|
|
80
|
-
return parsed;
|
|
81
|
-
}
|
|
82
|
-
} catch {
|
|
83
|
-
// Parse error — continue
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
// Try parsing the entire content as JSON
|
|
88
|
-
try {
|
|
89
|
-
const parsed = JSON.parse(msg.content);
|
|
90
|
-
if (validateAgainstSchema(parsed, schema)) {
|
|
91
|
-
return parsed;
|
|
92
|
-
}
|
|
93
|
-
} catch {
|
|
94
|
-
// Not JSON — continue
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
return null;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
/**
|
|
103
|
-
* Basic schema validation — checks that required fields exist.
|
|
104
|
-
* This is intentionally lightweight; full JSON Schema validation
|
|
105
|
-
* would require a dependency like ajv.
|
|
106
|
-
*/
|
|
107
|
-
function validateAgainstSchema(data: unknown, schema: object): boolean {
|
|
108
|
-
if (!data || typeof data !== "object") return false;
|
|
109
|
-
const schemaObj = schema as {
|
|
110
|
-
properties?: Record<string, unknown>;
|
|
111
|
-
required?: string[];
|
|
112
|
-
};
|
|
113
|
-
if (schemaObj.required && Array.isArray(schemaObj.required)) {
|
|
114
|
-
for (const field of schemaObj.required) {
|
|
115
|
-
if (!(field in (data as Record<string, unknown>))) {
|
|
116
|
-
return false;
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
return true;
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
export { STRUCTURED_OUTPUT_TOOL_NAME };
|
package/src/workflow/types.ts
DELETED
|
@@ -1,101 +0,0 @@
|
|
|
1
|
-
export interface WorkflowMetaPhase {
|
|
2
|
-
title: string;
|
|
3
|
-
detail?: string;
|
|
4
|
-
model?: string;
|
|
5
|
-
}
|
|
6
|
-
|
|
7
|
-
export interface WorkflowMeta {
|
|
8
|
-
name: string;
|
|
9
|
-
description: string;
|
|
10
|
-
whenToUse?: string;
|
|
11
|
-
phases?: WorkflowMetaPhase[];
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export interface WorkflowPhaseState {
|
|
15
|
-
title: string;
|
|
16
|
-
agentCount: number;
|
|
17
|
-
tokens: number;
|
|
18
|
-
elapsed: number;
|
|
19
|
-
startTime: number;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export interface WorkflowRun {
|
|
23
|
-
runId: string;
|
|
24
|
-
meta: WorkflowMeta;
|
|
25
|
-
status: "running" | "paused" | "completed" | "failed" | "aborted";
|
|
26
|
-
scriptPath: string;
|
|
27
|
-
args?: unknown;
|
|
28
|
-
startTime: number;
|
|
29
|
-
endTime?: number;
|
|
30
|
-
phases: WorkflowPhaseState[];
|
|
31
|
-
totalAgents: number;
|
|
32
|
-
totalTokens: number;
|
|
33
|
-
result?: unknown;
|
|
34
|
-
error?: string;
|
|
35
|
-
/** Resolves when the background execution finishes (completed/failed/aborted) */
|
|
36
|
-
completionPromise?: Promise<void>;
|
|
37
|
-
/** If set, this run resumes from a previous run's journal */
|
|
38
|
-
resumeFromRunId?: string;
|
|
39
|
-
/** Index of the agent that caused the workflow to fail */
|
|
40
|
-
failedAgentIndex?: number;
|
|
41
|
-
/** Error message from the failed agent */
|
|
42
|
-
failedAgentError?: string;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Serializable workflow run for stdio transport, with the non-serializable
|
|
47
|
-
* `completionPromise` stripped. Returned by the `getWorkflowRuns` RPC.
|
|
48
|
-
*/
|
|
49
|
-
export type SerializableWorkflowRun = Omit<WorkflowRun, "completionPromise">;
|
|
50
|
-
|
|
51
|
-
export interface JournalEntry {
|
|
52
|
-
agentIndex: number;
|
|
53
|
-
prompt: string;
|
|
54
|
-
opts: Record<string, unknown>;
|
|
55
|
-
result: unknown;
|
|
56
|
-
tokens: number;
|
|
57
|
-
/** Subagent instance ID for linking to the full conversation transcript */
|
|
58
|
-
subagentId?: string;
|
|
59
|
-
/** Path to the subagent's transcript JSONL file */
|
|
60
|
-
transcriptPath?: string;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
export interface AgentMeta {
|
|
64
|
-
agentType: string;
|
|
65
|
-
subagentId: string;
|
|
66
|
-
transcriptPath: string;
|
|
67
|
-
label?: string;
|
|
68
|
-
phase?: string;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
export interface LogEntry {
|
|
72
|
-
type: "log";
|
|
73
|
-
message: string;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
export interface AgentFailedEntry {
|
|
77
|
-
type: "agent_failed";
|
|
78
|
-
agentIndex: number;
|
|
79
|
-
error: string;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
export type JournalLine = JournalEntry | LogEntry | AgentFailedEntry;
|
|
83
|
-
|
|
84
|
-
export interface BudgetInfo {
|
|
85
|
-
total: number | null;
|
|
86
|
-
spent: () => number;
|
|
87
|
-
remaining: () => number;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
export interface WorkflowProgressEvent {
|
|
91
|
-
type:
|
|
92
|
-
| "phase_started"
|
|
93
|
-
| "phase_completed"
|
|
94
|
-
| "agent_started"
|
|
95
|
-
| "agent_completed"
|
|
96
|
-
| "agent_failed";
|
|
97
|
-
runId: string;
|
|
98
|
-
phaseIndex: number;
|
|
99
|
-
agentIndex?: number;
|
|
100
|
-
timestamp: number;
|
|
101
|
-
}
|
|
@@ -1,410 +0,0 @@
|
|
|
1
|
-
import type { SubagentManager } from "../managers/subagentManager.js";
|
|
2
|
-
import * as fs from "fs";
|
|
3
|
-
import * as path from "path";
|
|
4
|
-
import { ConcurrencyLimiter } from "./concurrencyLimiter.js";
|
|
5
|
-
import { BudgetTracker } from "./budgetTracker.js";
|
|
6
|
-
import { ProgressReporter } from "./progressReporter.js";
|
|
7
|
-
import { Journal } from "./journal.js";
|
|
8
|
-
import type { BudgetInfo, AgentMeta } from "./types.js";
|
|
9
|
-
import {
|
|
10
|
-
createStructuredOutputPrompt,
|
|
11
|
-
createStructuredOutputTool,
|
|
12
|
-
extractStructuredResult,
|
|
13
|
-
} from "./structuredOutput.js";
|
|
14
|
-
import { AGENT_TOOL_NAME, WORKFLOW_TOOL_NAME } from "../constants/tools.js";
|
|
15
|
-
import { logger } from "../utils/globalLogger.js";
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* Attempt to parse args if it was passed as a JSON string.
|
|
19
|
-
* LLMs may serialize array/object args as a string (e.g. "[3,8,15,42,7]")
|
|
20
|
-
* which would cause `for...of` to iterate character-by-character.
|
|
21
|
-
*/
|
|
22
|
-
function parseArgsIfNeeded(args: unknown): unknown {
|
|
23
|
-
if (typeof args === "string") {
|
|
24
|
-
try {
|
|
25
|
-
const parsed = JSON.parse(args);
|
|
26
|
-
// Only accept parsed arrays/objects, not primitives like "42" → 42
|
|
27
|
-
if (typeof parsed === "object" && parsed !== null) {
|
|
28
|
-
return parsed;
|
|
29
|
-
}
|
|
30
|
-
} catch {
|
|
31
|
-
// Not valid JSON — use as-is (string)
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
return args;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
const MAX_TOTAL_AGENTS = 1000;
|
|
38
|
-
const MAX_ITEMS_PER_CALL = 4096;
|
|
39
|
-
|
|
40
|
-
interface WorkflowApiContext {
|
|
41
|
-
subagentManager: SubagentManager;
|
|
42
|
-
concurrencyLimiter: ConcurrencyLimiter;
|
|
43
|
-
budgetTracker: BudgetTracker;
|
|
44
|
-
progressReporter: ProgressReporter;
|
|
45
|
-
journal: Journal;
|
|
46
|
-
abortSignal: AbortSignal;
|
|
47
|
-
args: unknown;
|
|
48
|
-
onLog?: (message: string) => void;
|
|
49
|
-
/** When resuming, offset the agent counter by this many existing entries */
|
|
50
|
-
initialAgentCount?: number;
|
|
51
|
-
/** Session directory for computing transcript paths */
|
|
52
|
-
sessionDir: string;
|
|
53
|
-
/** Per-run directory for writing agent metadata sidecars */
|
|
54
|
-
runDir: string;
|
|
55
|
-
/** Per-agent abort controllers for kill/skip support */
|
|
56
|
-
agentControllers: Map<number, AbortController>;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
interface AgentOpts {
|
|
60
|
-
label?: string;
|
|
61
|
-
phase?: string;
|
|
62
|
-
schema?: object;
|
|
63
|
-
model?: string;
|
|
64
|
-
isolation?: string;
|
|
65
|
-
agentType?: string;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
export interface WorkflowApis {
|
|
69
|
-
agent: (prompt: string, opts?: AgentOpts) => Promise<unknown>;
|
|
70
|
-
parallel: (thunks: Array<() => Promise<unknown>>) => Promise<unknown[]>;
|
|
71
|
-
pipeline: (
|
|
72
|
-
items: unknown[],
|
|
73
|
-
...stages: Array<
|
|
74
|
-
(prev: unknown, item: unknown, index: number) => Promise<unknown>
|
|
75
|
-
>
|
|
76
|
-
) => Promise<unknown[]>;
|
|
77
|
-
phase: (title: string) => void;
|
|
78
|
-
log: (message: string) => void;
|
|
79
|
-
args: unknown;
|
|
80
|
-
budget: BudgetInfo;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
export function createWorkflowApis(ctx: WorkflowApiContext): WorkflowApis {
|
|
84
|
-
let agentCounter = ctx.initialAgentCount ?? 0;
|
|
85
|
-
|
|
86
|
-
const agent = async (prompt: string, opts?: AgentOpts): Promise<unknown> => {
|
|
87
|
-
const index = agentCounter++;
|
|
88
|
-
|
|
89
|
-
// Check agent limit
|
|
90
|
-
if (index >= MAX_TOTAL_AGENTS) {
|
|
91
|
-
throw new Error(
|
|
92
|
-
`Workflow exceeded maximum agent count of ${MAX_TOTAL_AGENTS}`,
|
|
93
|
-
);
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
// Check abort
|
|
97
|
-
if (ctx.abortSignal.aborted) {
|
|
98
|
-
return null;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
// Check budget
|
|
102
|
-
if (ctx.budgetTracker.isExceeded()) {
|
|
103
|
-
throw new Error("Workflow token budget exceeded");
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
// Check journal for cached result (resume)
|
|
107
|
-
const cached = ctx.journal.getCachedResult(index);
|
|
108
|
-
if (cached !== undefined) {
|
|
109
|
-
logger.debug(`[Workflow] agent(${index}): using cached result`);
|
|
110
|
-
return cached;
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
// Acquire concurrency slot
|
|
114
|
-
await ctx.concurrencyLimiter.acquire();
|
|
115
|
-
|
|
116
|
-
// Create per-agent abort controller linked to the run's signal
|
|
117
|
-
const agentController = new AbortController();
|
|
118
|
-
ctx.agentControllers.set(index, agentController);
|
|
119
|
-
// If the run is already aborted, abort this agent immediately
|
|
120
|
-
if (ctx.abortSignal.aborted) {
|
|
121
|
-
agentController.abort();
|
|
122
|
-
}
|
|
123
|
-
// Propagate run abort to agent abort
|
|
124
|
-
const onRunAbort = () => agentController.abort();
|
|
125
|
-
ctx.abortSignal.addEventListener("abort", onRunAbort);
|
|
126
|
-
|
|
127
|
-
try {
|
|
128
|
-
// Resolve subagent type
|
|
129
|
-
const subagentType = opts?.agentType || "general-purpose";
|
|
130
|
-
let configuration = await ctx.subagentManager.findSubagent(subagentType);
|
|
131
|
-
|
|
132
|
-
if (!configuration) {
|
|
133
|
-
logger.warn(
|
|
134
|
-
`[Workflow] agent(${index}): subagent type "${subagentType}" not found, falling back to general-purpose`,
|
|
135
|
-
);
|
|
136
|
-
configuration =
|
|
137
|
-
await ctx.subagentManager.findSubagent("general-purpose");
|
|
138
|
-
if (!configuration) {
|
|
139
|
-
throw new Error(`No subagent type available for agent call`);
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
// Build the effective prompt
|
|
144
|
-
let effectivePrompt = prompt;
|
|
145
|
-
if (opts?.schema) {
|
|
146
|
-
effectivePrompt += createStructuredOutputPrompt(opts.schema);
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
// Set phase if specified
|
|
150
|
-
if (opts?.phase) {
|
|
151
|
-
ctx.progressReporter.setPhase(opts.phase);
|
|
152
|
-
}
|
|
153
|
-
ctx.progressReporter.agentStarted();
|
|
154
|
-
|
|
155
|
-
// Create subagent instance
|
|
156
|
-
const instance = await ctx.subagentManager.createInstance(configuration, {
|
|
157
|
-
description: opts?.label || `workflow-agent-${index}`,
|
|
158
|
-
prompt: effectivePrompt,
|
|
159
|
-
subagent_type: subagentType,
|
|
160
|
-
model: opts?.model,
|
|
161
|
-
});
|
|
162
|
-
|
|
163
|
-
// Capture subagent linkage info
|
|
164
|
-
const subagentId = instance.subagentId;
|
|
165
|
-
const transcriptPath = instance.messageManager.getTranscriptPath();
|
|
166
|
-
|
|
167
|
-
// If schema provided, register StructuredOutput tool on the subagent's tool manager
|
|
168
|
-
// and force the model to call it via tool_choice
|
|
169
|
-
if (opts?.schema) {
|
|
170
|
-
const structuredTool = createStructuredOutputTool(opts.schema);
|
|
171
|
-
instance.toolManager.register(structuredTool);
|
|
172
|
-
instance.aiManager.toolChoiceOverride = {
|
|
173
|
-
type: "function",
|
|
174
|
-
function: { name: "StructuredOutput" },
|
|
175
|
-
};
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
// Deny Agent and Workflow tools in workflow subagents
|
|
179
|
-
// (prevent infinite recursion)
|
|
180
|
-
instance.permissionManager.addTemporaryRules([
|
|
181
|
-
`${AGENT_TOOL_NAME}:deny`,
|
|
182
|
-
`${WORKFLOW_TOOL_NAME}:deny`,
|
|
183
|
-
]);
|
|
184
|
-
|
|
185
|
-
// Execute agent
|
|
186
|
-
const result = await ctx.subagentManager.executeAgent(
|
|
187
|
-
instance,
|
|
188
|
-
effectivePrompt,
|
|
189
|
-
agentController.signal,
|
|
190
|
-
false,
|
|
191
|
-
);
|
|
192
|
-
|
|
193
|
-
// Track token usage — sum from assistant messages' usage field
|
|
194
|
-
// (getUsages() is empty because onUsageAdded targets the parent agent)
|
|
195
|
-
const messages = instance.messageManager.getMessages();
|
|
196
|
-
const tokens = messages.reduce((sum, msg) => {
|
|
197
|
-
if (msg.role !== "assistant" || !msg.usage) return sum;
|
|
198
|
-
const u = msg.usage;
|
|
199
|
-
return (
|
|
200
|
-
sum +
|
|
201
|
-
(u.total_tokens || 0) +
|
|
202
|
-
(u.cache_read_input_tokens || 0) +
|
|
203
|
-
(u.cache_creation_input_tokens || 0)
|
|
204
|
-
);
|
|
205
|
-
}, 0);
|
|
206
|
-
ctx.budgetTracker.addUsage(tokens);
|
|
207
|
-
ctx.progressReporter.agentCompleted(tokens);
|
|
208
|
-
|
|
209
|
-
// Extract structured result if schema was provided
|
|
210
|
-
let finalResult: unknown;
|
|
211
|
-
if (opts?.schema) {
|
|
212
|
-
const messages = instance.messageManager.getMessages();
|
|
213
|
-
// Build the format extractStructuredResult expects:
|
|
214
|
-
// Look for StructuredOutput tool calls in ToolBlocks
|
|
215
|
-
const structuredToolBlocks = messages
|
|
216
|
-
.filter((m) => m.role === "assistant")
|
|
217
|
-
.flatMap((m) => m.blocks)
|
|
218
|
-
.filter(
|
|
219
|
-
(b): b is import("../types/messaging.js").ToolBlock =>
|
|
220
|
-
b.type === "tool" &&
|
|
221
|
-
b.name === "StructuredOutput" &&
|
|
222
|
-
b.stage === "end",
|
|
223
|
-
);
|
|
224
|
-
|
|
225
|
-
if (structuredToolBlocks.length > 0) {
|
|
226
|
-
// Parse the StructuredOutput tool call parameters
|
|
227
|
-
const lastBlock =
|
|
228
|
-
structuredToolBlocks[structuredToolBlocks.length - 1];
|
|
229
|
-
try {
|
|
230
|
-
const parsed = JSON.parse(lastBlock.parameters || "{}");
|
|
231
|
-
finalResult = parsed;
|
|
232
|
-
} catch {
|
|
233
|
-
// Parameters parse failed, try result
|
|
234
|
-
try {
|
|
235
|
-
const parsed = JSON.parse(lastBlock.result || "null");
|
|
236
|
-
finalResult = parsed;
|
|
237
|
-
} catch {
|
|
238
|
-
finalResult = result;
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
} else {
|
|
242
|
-
// Fallback: try extractStructuredResult with message content
|
|
243
|
-
finalResult = extractStructuredResult(
|
|
244
|
-
messages.map((m) => {
|
|
245
|
-
const textBlock = m.blocks.find(
|
|
246
|
-
(b): b is import("../types/messaging.js").TextBlock =>
|
|
247
|
-
b.type === "text",
|
|
248
|
-
);
|
|
249
|
-
return {
|
|
250
|
-
role: m.role,
|
|
251
|
-
content: textBlock?.content,
|
|
252
|
-
tool_calls: (
|
|
253
|
-
m as unknown as {
|
|
254
|
-
tool_calls?: Array<{
|
|
255
|
-
function: { name: string; arguments: string };
|
|
256
|
-
}>;
|
|
257
|
-
}
|
|
258
|
-
).tool_calls,
|
|
259
|
-
};
|
|
260
|
-
}),
|
|
261
|
-
opts.schema,
|
|
262
|
-
);
|
|
263
|
-
if (finalResult === null) {
|
|
264
|
-
// Schema enforcement failed — return the raw text
|
|
265
|
-
finalResult = result;
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
} else {
|
|
269
|
-
finalResult = result;
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
// Append to journal
|
|
273
|
-
ctx.journal.append({
|
|
274
|
-
agentIndex: index,
|
|
275
|
-
prompt,
|
|
276
|
-
opts: { ...opts } as Record<string, unknown>,
|
|
277
|
-
result: finalResult,
|
|
278
|
-
tokens,
|
|
279
|
-
subagentId,
|
|
280
|
-
transcriptPath,
|
|
281
|
-
});
|
|
282
|
-
|
|
283
|
-
// Write agent metadata sidecar
|
|
284
|
-
try {
|
|
285
|
-
const agentMeta: AgentMeta = {
|
|
286
|
-
agentType: subagentType,
|
|
287
|
-
subagentId,
|
|
288
|
-
transcriptPath,
|
|
289
|
-
label: opts?.label,
|
|
290
|
-
phase: opts?.phase,
|
|
291
|
-
};
|
|
292
|
-
const metaPath = path.join(ctx.runDir, "agents", `${index}.meta.json`);
|
|
293
|
-
await fs.promises.writeFile(
|
|
294
|
-
metaPath,
|
|
295
|
-
JSON.stringify(agentMeta, null, 2),
|
|
296
|
-
"utf-8",
|
|
297
|
-
);
|
|
298
|
-
} catch (metaErr) {
|
|
299
|
-
logger.warn(
|
|
300
|
-
`[Workflow] Failed to write agent meta for ${index}: ${metaErr instanceof Error ? metaErr.message : String(metaErr)}`,
|
|
301
|
-
);
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
// Cleanup
|
|
305
|
-
ctx.subagentManager.cleanupInstance(instance.subagentId);
|
|
306
|
-
|
|
307
|
-
return finalResult;
|
|
308
|
-
} catch (error) {
|
|
309
|
-
// Agent errors are logged but don't crash the workflow
|
|
310
|
-
// Return null so the caller can filter with .filter(Boolean)
|
|
311
|
-
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
312
|
-
logger.warn(`[Workflow] agent(${index}) failed: ${errorMsg}`);
|
|
313
|
-
|
|
314
|
-
// Write agent_failed entry to journal for skip/retry tracking
|
|
315
|
-
ctx.journal.append({
|
|
316
|
-
type: "agent_failed",
|
|
317
|
-
agentIndex: index,
|
|
318
|
-
error: errorMsg,
|
|
319
|
-
});
|
|
320
|
-
|
|
321
|
-
// Emit progress event for agent failure
|
|
322
|
-
ctx.progressReporter.agentFailed(index);
|
|
323
|
-
|
|
324
|
-
return null;
|
|
325
|
-
} finally {
|
|
326
|
-
ctx.agentControllers.delete(index);
|
|
327
|
-
ctx.abortSignal.removeEventListener("abort", onRunAbort);
|
|
328
|
-
ctx.concurrencyLimiter.release();
|
|
329
|
-
}
|
|
330
|
-
};
|
|
331
|
-
|
|
332
|
-
const parallel = async (
|
|
333
|
-
thunks: Array<() => Promise<unknown>>,
|
|
334
|
-
): Promise<unknown[]> => {
|
|
335
|
-
if (thunks.length > MAX_ITEMS_PER_CALL) {
|
|
336
|
-
throw new Error(
|
|
337
|
-
`parallel() accepts at most ${MAX_ITEMS_PER_CALL} items, got ${thunks.length}`,
|
|
338
|
-
);
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
// Note: thunks typically call agent() which acquires its own slot,
|
|
342
|
-
// so parallel does NOT acquire a slot per thunk to avoid deadlock.
|
|
343
|
-
const results = await Promise.allSettled(
|
|
344
|
-
thunks.map(async (thunk) => {
|
|
345
|
-
try {
|
|
346
|
-
return await thunk();
|
|
347
|
-
} catch {
|
|
348
|
-
return null;
|
|
349
|
-
}
|
|
350
|
-
}),
|
|
351
|
-
);
|
|
352
|
-
|
|
353
|
-
// Convert rejected promises to null
|
|
354
|
-
return results.map((r) => (r.status === "fulfilled" ? r.value : null));
|
|
355
|
-
};
|
|
356
|
-
|
|
357
|
-
const pipeline = async (
|
|
358
|
-
items: unknown[],
|
|
359
|
-
...stages: Array<
|
|
360
|
-
(prev: unknown, item: unknown, index: number) => Promise<unknown>
|
|
361
|
-
>
|
|
362
|
-
): Promise<unknown[]> => {
|
|
363
|
-
if (items.length > MAX_ITEMS_PER_CALL) {
|
|
364
|
-
throw new Error(
|
|
365
|
-
`pipeline() accepts at most ${MAX_ITEMS_PER_CALL} items, got ${items.length}`,
|
|
366
|
-
);
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
// Run each item through all stages, items are independent.
|
|
370
|
-
// Note: agent() inside stages acquires its own concurrency slot,
|
|
371
|
-
// so pipeline does NOT acquire a slot per item to avoid deadlock.
|
|
372
|
-
const results = await Promise.allSettled(
|
|
373
|
-
items.map(async (item, index) => {
|
|
374
|
-
try {
|
|
375
|
-
let result: unknown = undefined;
|
|
376
|
-
for (const stage of stages) {
|
|
377
|
-
result = await stage(result, item, index);
|
|
378
|
-
}
|
|
379
|
-
return result;
|
|
380
|
-
} catch (error) {
|
|
381
|
-
logger.warn(
|
|
382
|
-
`[Workflow] pipeline item ${index} failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
383
|
-
);
|
|
384
|
-
return null;
|
|
385
|
-
}
|
|
386
|
-
}),
|
|
387
|
-
);
|
|
388
|
-
|
|
389
|
-
return results.map((r) => (r.status === "fulfilled" ? r.value : null));
|
|
390
|
-
};
|
|
391
|
-
|
|
392
|
-
const phase = (title: string): void => {
|
|
393
|
-
ctx.progressReporter.setPhase(title);
|
|
394
|
-
};
|
|
395
|
-
|
|
396
|
-
const log = (message: string): void => {
|
|
397
|
-
ctx.journal.appendLog(message);
|
|
398
|
-
ctx.onLog?.(message);
|
|
399
|
-
};
|
|
400
|
-
|
|
401
|
-
return {
|
|
402
|
-
agent,
|
|
403
|
-
parallel,
|
|
404
|
-
pipeline,
|
|
405
|
-
phase,
|
|
406
|
-
log,
|
|
407
|
-
args: parseArgsIfNeeded(ctx.args),
|
|
408
|
-
budget: ctx.budgetTracker.toBudgetInfo(),
|
|
409
|
-
};
|
|
410
|
-
}
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|