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,252 +0,0 @@
|
|
|
1
|
-
import * as fs from "fs/promises";
|
|
2
|
-
import * as path from "path";
|
|
3
|
-
import {
|
|
4
|
-
PluginManifest,
|
|
5
|
-
CustomSlashCommand,
|
|
6
|
-
Skill,
|
|
7
|
-
LspConfig,
|
|
8
|
-
McpConfig,
|
|
9
|
-
PartialHookConfiguration,
|
|
10
|
-
} from "../types/index.js";
|
|
11
|
-
import { scanCommandsDirectory } from "../utils/customCommands.js";
|
|
12
|
-
import { parseSkillFile } from "../utils/skillParser.js";
|
|
13
|
-
import {
|
|
14
|
-
parseAgentFile,
|
|
15
|
-
type SubagentConfiguration,
|
|
16
|
-
} from "../utils/subagentParser.js";
|
|
17
|
-
import { logger } from "../utils/globalLogger.js";
|
|
18
|
-
|
|
19
|
-
export class PluginLoader {
|
|
20
|
-
/**
|
|
21
|
-
* Load and validate a plugin manifest from a directory
|
|
22
|
-
* @param pluginPath Absolute path to the plugin directory
|
|
23
|
-
*/
|
|
24
|
-
static async loadManifest(pluginPath: string): Promise<PluginManifest> {
|
|
25
|
-
const dotWavePluginPath = path.join(pluginPath, ".wave-plugin");
|
|
26
|
-
|
|
27
|
-
// Check if .wave-plugin/ directory exists
|
|
28
|
-
let wavePluginDirExists = false;
|
|
29
|
-
try {
|
|
30
|
-
const entries = await fs.readdir(dotWavePluginPath);
|
|
31
|
-
wavePluginDirExists = true;
|
|
32
|
-
// T018: Ensure plugin.json is the only file in .wave-plugin/
|
|
33
|
-
const misplaced = entries.filter((e) => e !== "plugin.json");
|
|
34
|
-
if (misplaced.length > 0) {
|
|
35
|
-
throw new Error(
|
|
36
|
-
`Misplaced files/directories in .wave-plugin/: ${misplaced.join(", ")}. Only plugin.json should be in this directory.`,
|
|
37
|
-
);
|
|
38
|
-
}
|
|
39
|
-
} catch (error) {
|
|
40
|
-
if (
|
|
41
|
-
error instanceof Error &&
|
|
42
|
-
(error as { code?: string }).code === "ENOENT"
|
|
43
|
-
) {
|
|
44
|
-
// .wave-plugin/ doesn't exist, will try .claude-plugin/ fallback below
|
|
45
|
-
} else {
|
|
46
|
-
throw error;
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
if (wavePluginDirExists) {
|
|
51
|
-
const manifestPath = path.join(dotWavePluginPath, "plugin.json");
|
|
52
|
-
try {
|
|
53
|
-
const content = await fs.readFile(manifestPath, "utf-8");
|
|
54
|
-
const manifest = JSON.parse(content) as PluginManifest;
|
|
55
|
-
this.validateManifest(manifest);
|
|
56
|
-
return manifest;
|
|
57
|
-
} catch (error) {
|
|
58
|
-
if (
|
|
59
|
-
error instanceof Error &&
|
|
60
|
-
(error as { code?: string }).code === "ENOENT"
|
|
61
|
-
) {
|
|
62
|
-
throw new Error(`Plugin manifest not found at ${manifestPath}`);
|
|
63
|
-
}
|
|
64
|
-
throw new Error(
|
|
65
|
-
`Failed to load plugin manifest at ${manifestPath}: ${
|
|
66
|
-
error instanceof Error ? error.message : String(error)
|
|
67
|
-
}`,
|
|
68
|
-
);
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
// Fallback to .claude-plugin/
|
|
73
|
-
const dotClaudePluginPath = path.join(pluginPath, ".claude-plugin");
|
|
74
|
-
const claudeManifestPath = path.join(dotClaudePluginPath, "plugin.json");
|
|
75
|
-
try {
|
|
76
|
-
const content = await fs.readFile(claudeManifestPath, "utf-8");
|
|
77
|
-
const manifest = JSON.parse(content) as PluginManifest;
|
|
78
|
-
this.validateManifest(manifest);
|
|
79
|
-
return manifest;
|
|
80
|
-
} catch (error) {
|
|
81
|
-
if (
|
|
82
|
-
error instanceof Error &&
|
|
83
|
-
(error as { code?: string }).code === "ENOENT"
|
|
84
|
-
) {
|
|
85
|
-
throw new Error(
|
|
86
|
-
`Plugin manifest not found at ${dotWavePluginPath} or ${dotClaudePluginPath}`,
|
|
87
|
-
);
|
|
88
|
-
}
|
|
89
|
-
throw new Error(
|
|
90
|
-
`Failed to load plugin manifest at ${claudeManifestPath}: ${
|
|
91
|
-
error instanceof Error ? error.message : String(error)
|
|
92
|
-
}`,
|
|
93
|
-
);
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/**
|
|
98
|
-
* Load commands from a plugin's commands directory
|
|
99
|
-
* @param pluginPath Absolute path to the plugin directory
|
|
100
|
-
*/
|
|
101
|
-
static loadCommands(pluginPath: string): CustomSlashCommand[] {
|
|
102
|
-
const commandsPath = path.join(pluginPath, "commands");
|
|
103
|
-
return scanCommandsDirectory(commandsPath);
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/**
|
|
107
|
-
* Load skills from a plugin's skills directory
|
|
108
|
-
* @param pluginPath Absolute path to the plugin directory
|
|
109
|
-
*/
|
|
110
|
-
static async loadSkills(pluginPath: string): Promise<Skill[]> {
|
|
111
|
-
const skillsPath = path.join(pluginPath, "skills");
|
|
112
|
-
const skills: Skill[] = [];
|
|
113
|
-
|
|
114
|
-
try {
|
|
115
|
-
const entries = await fs.readdir(skillsPath, { withFileTypes: true });
|
|
116
|
-
for (const entry of entries) {
|
|
117
|
-
if (entry.isDirectory()) {
|
|
118
|
-
const skillDir = path.join(skillsPath, entry.name);
|
|
119
|
-
const skillFilePath = path.join(skillDir, "SKILL.md");
|
|
120
|
-
try {
|
|
121
|
-
await fs.stat(skillFilePath);
|
|
122
|
-
const parsed = parseSkillFile(skillFilePath, {
|
|
123
|
-
basePath: skillDir,
|
|
124
|
-
validateMetadata: true,
|
|
125
|
-
});
|
|
126
|
-
if (parsed.isValid) {
|
|
127
|
-
skills.push({
|
|
128
|
-
...parsed.skillMetadata,
|
|
129
|
-
type: "project", // Plugin skills are treated as project skills
|
|
130
|
-
pluginRoot: pluginPath,
|
|
131
|
-
content: parsed.content,
|
|
132
|
-
frontmatter: parsed.frontmatter,
|
|
133
|
-
isValid: parsed.isValid,
|
|
134
|
-
errors: parsed.validationErrors,
|
|
135
|
-
});
|
|
136
|
-
}
|
|
137
|
-
} catch {
|
|
138
|
-
// Skip directories without SKILL.md
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
} catch {
|
|
143
|
-
// skills directory might not exist
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
return skills;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
/**
|
|
150
|
-
* Load LSP configuration from a plugin
|
|
151
|
-
*/
|
|
152
|
-
static async loadLspConfig(
|
|
153
|
-
pluginPath: string,
|
|
154
|
-
): Promise<LspConfig | undefined> {
|
|
155
|
-
const lspPath = path.join(pluginPath, ".lsp.json");
|
|
156
|
-
try {
|
|
157
|
-
const content = await fs.readFile(lspPath, "utf-8");
|
|
158
|
-
return JSON.parse(content) as LspConfig;
|
|
159
|
-
} catch {
|
|
160
|
-
return undefined;
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
/**
|
|
165
|
-
* Load MCP configuration from a plugin
|
|
166
|
-
*/
|
|
167
|
-
static async loadMcpConfig(
|
|
168
|
-
pluginPath: string,
|
|
169
|
-
): Promise<McpConfig | undefined> {
|
|
170
|
-
const mcpPath = path.join(pluginPath, ".mcp.json");
|
|
171
|
-
try {
|
|
172
|
-
const content = await fs.readFile(mcpPath, "utf-8");
|
|
173
|
-
// Return raw config — let McpManager resolve templates and capture originalUrl
|
|
174
|
-
return JSON.parse(content) as McpConfig;
|
|
175
|
-
} catch {
|
|
176
|
-
return undefined;
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* Load hooks configuration from a plugin
|
|
182
|
-
*/
|
|
183
|
-
static async loadHooksConfig(
|
|
184
|
-
pluginPath: string,
|
|
185
|
-
): Promise<PartialHookConfiguration | undefined> {
|
|
186
|
-
const hooksPath = path.join(pluginPath, "hooks", "hooks.json");
|
|
187
|
-
try {
|
|
188
|
-
const content = await fs.readFile(hooksPath, "utf-8");
|
|
189
|
-
const parsed = JSON.parse(content);
|
|
190
|
-
// Claude Code wrapper format: { "hooks": { "SessionStart": [...] } }
|
|
191
|
-
// (optional "description" sibling key)
|
|
192
|
-
if (parsed && typeof parsed === "object" && "hooks" in parsed) {
|
|
193
|
-
return parsed.hooks as PartialHookConfiguration;
|
|
194
|
-
}
|
|
195
|
-
return undefined;
|
|
196
|
-
} catch {
|
|
197
|
-
return undefined;
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
/**
|
|
202
|
-
* Load agent configurations from a plugin's agents directory
|
|
203
|
-
*/
|
|
204
|
-
static async loadAgents(
|
|
205
|
-
pluginPath: string,
|
|
206
|
-
): Promise<SubagentConfiguration[]> {
|
|
207
|
-
const agentsPath = path.join(pluginPath, "agents");
|
|
208
|
-
const agents: SubagentConfiguration[] = [];
|
|
209
|
-
|
|
210
|
-
try {
|
|
211
|
-
const entries = await fs.readdir(agentsPath, { withFileTypes: true });
|
|
212
|
-
for (const entry of entries) {
|
|
213
|
-
if (entry.isFile() && entry.name.endsWith(".md")) {
|
|
214
|
-
const agentFilePath = path.join(agentsPath, entry.name);
|
|
215
|
-
try {
|
|
216
|
-
const config = parseAgentFile(agentFilePath, "plugin", pluginPath);
|
|
217
|
-
agents.push(config);
|
|
218
|
-
} catch (parseError) {
|
|
219
|
-
// Log error but continue with other files
|
|
220
|
-
logger?.warn(
|
|
221
|
-
`Warning: ${parseError instanceof Error ? parseError.message : String(parseError)}`,
|
|
222
|
-
);
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
} catch {
|
|
227
|
-
// agents directory might not exist
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
return agents;
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
/**
|
|
234
|
-
* Validate the plugin manifest structure
|
|
235
|
-
*/
|
|
236
|
-
private static validateManifest(manifest: PluginManifest): void {
|
|
237
|
-
if (!manifest.name) {
|
|
238
|
-
throw new Error("Plugin manifest missing 'name'");
|
|
239
|
-
}
|
|
240
|
-
if (!manifest.description) {
|
|
241
|
-
throw new Error("Plugin manifest missing 'description'");
|
|
242
|
-
}
|
|
243
|
-
if (!manifest.version) {
|
|
244
|
-
throw new Error("Plugin manifest missing 'version'");
|
|
245
|
-
}
|
|
246
|
-
if (!/^[a-z0-9-]+$/.test(manifest.name)) {
|
|
247
|
-
throw new Error(
|
|
248
|
-
`Invalid plugin name: ${manifest.name}. Only lowercase letters, numbers, and hyphens are allowed.`,
|
|
249
|
-
);
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
}
|
|
@@ -1,366 +0,0 @@
|
|
|
1
|
-
import * as fs from "node:fs";
|
|
2
|
-
import { homedir } from "node:os";
|
|
3
|
-
import * as path from "node:path";
|
|
4
|
-
|
|
5
|
-
import { authService, createAuthAwareFetch } from "./authService.js";
|
|
6
|
-
import type {
|
|
7
|
-
RemoteSettingsCache,
|
|
8
|
-
RemoteSettingsFetchResult,
|
|
9
|
-
RemoteSettingsResponse,
|
|
10
|
-
} from "../types/configuration.js";
|
|
11
|
-
import type { WaveConfiguration } from "../types/configuration.js";
|
|
12
|
-
import type { HookEvent, HookEventConfig } from "../types/hooks.js";
|
|
13
|
-
import { logger } from "../utils/globalLogger.js";
|
|
14
|
-
|
|
15
|
-
const CACHE_FILE = path.join(homedir(), ".wave", "remote-settings.json");
|
|
16
|
-
const POLLING_INTERVAL_MS = 60 * 60 * 1000; // 60 minutes
|
|
17
|
-
const FETCH_TIMEOUT_MS = 10_000;
|
|
18
|
-
|
|
19
|
-
let _cachedSettings: RemoteSettingsCache | null = null;
|
|
20
|
-
let _pollingTimer: ReturnType<typeof setInterval> | null = null;
|
|
21
|
-
let _onSettingsUpdateCallbacks: Array<() => void | Promise<void>> = [];
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Register a callback invoked when remote settings change (checksum differs).
|
|
25
|
-
* Returns an unsubscribe function.
|
|
26
|
-
*/
|
|
27
|
-
export function onSettingsUpdate(
|
|
28
|
-
callback: () => void | Promise<void>,
|
|
29
|
-
): () => void {
|
|
30
|
-
_onSettingsUpdateCallbacks.push(callback);
|
|
31
|
-
return () => {
|
|
32
|
-
_onSettingsUpdateCallbacks = _onSettingsUpdateCallbacks.filter(
|
|
33
|
-
(cb) => cb !== callback,
|
|
34
|
-
);
|
|
35
|
-
};
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
async function notifySettingsUpdate(): Promise<void> {
|
|
39
|
-
for (const cb of _onSettingsUpdateCallbacks) {
|
|
40
|
-
try {
|
|
41
|
-
await cb();
|
|
42
|
-
} catch {
|
|
43
|
-
// Don't let callback errors break the fetch flow
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
function loadCacheFromDisk(): void {
|
|
49
|
-
try {
|
|
50
|
-
if (!fs.existsSync(CACHE_FILE)) {
|
|
51
|
-
return;
|
|
52
|
-
}
|
|
53
|
-
const raw = fs.readFileSync(CACHE_FILE, "utf-8");
|
|
54
|
-
const parsed: RemoteSettingsCache = JSON.parse(raw);
|
|
55
|
-
_cachedSettings = parsed;
|
|
56
|
-
logger.debug("remoteSettings: loaded cache from disk", {
|
|
57
|
-
checksum: parsed.checksum,
|
|
58
|
-
});
|
|
59
|
-
} catch (err) {
|
|
60
|
-
logger.debug("remoteSettings: failed to load cache from disk", { err });
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
function writeCacheToDisk(): void {
|
|
65
|
-
if (!_cachedSettings) {
|
|
66
|
-
return;
|
|
67
|
-
}
|
|
68
|
-
try {
|
|
69
|
-
const dir = path.dirname(CACHE_FILE);
|
|
70
|
-
if (!fs.existsSync(dir)) {
|
|
71
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
72
|
-
}
|
|
73
|
-
fs.writeFileSync(CACHE_FILE, JSON.stringify(_cachedSettings, null, 2), {
|
|
74
|
-
mode: 0o600,
|
|
75
|
-
});
|
|
76
|
-
logger.debug("remoteSettings: wrote cache to disk", {
|
|
77
|
-
checksum: _cachedSettings.checksum,
|
|
78
|
-
});
|
|
79
|
-
} catch (err) {
|
|
80
|
-
logger.debug("remoteSettings: failed to write cache to disk", { err });
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
function removeCacheFromDisk(): void {
|
|
85
|
-
try {
|
|
86
|
-
if (fs.existsSync(CACHE_FILE)) {
|
|
87
|
-
fs.unlinkSync(CACHE_FILE);
|
|
88
|
-
}
|
|
89
|
-
} catch (err) {
|
|
90
|
-
logger.debug("remoteSettings: failed to remove cache file", { err });
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
async function fetchRemoteSettings(): Promise<RemoteSettingsFetchResult> {
|
|
95
|
-
if (!authService.isSSOAuthenticated()) {
|
|
96
|
-
logger.debug("remoteSettings: skipping fetch — not SSO authenticated");
|
|
97
|
-
return { success: false, error: "Not SSO authenticated" };
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
const token = authService.getSSOToken();
|
|
101
|
-
const serverUrl = authService.getServerUrl();
|
|
102
|
-
if (!token || !serverUrl) {
|
|
103
|
-
return { success: false, error: "Missing SSO token or server URL" };
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
const oldChecksum = _cachedSettings?.checksum;
|
|
107
|
-
|
|
108
|
-
const headers: Record<string, string> = {
|
|
109
|
-
Authorization: `Bearer ${token}`,
|
|
110
|
-
};
|
|
111
|
-
if (_cachedSettings?.checksum) {
|
|
112
|
-
headers["If-None-Match"] = _cachedSettings.checksum;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
try {
|
|
116
|
-
const authFetch = createAuthAwareFetch(globalThis.fetch);
|
|
117
|
-
const response = await authFetch(`${serverUrl}/api/wave/settings`, {
|
|
118
|
-
method: "GET",
|
|
119
|
-
headers,
|
|
120
|
-
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
|
121
|
-
});
|
|
122
|
-
|
|
123
|
-
if (response.status === 304) {
|
|
124
|
-
logger.debug("remoteSettings: 304 unchanged", {
|
|
125
|
-
checksum: _cachedSettings?.checksum,
|
|
126
|
-
});
|
|
127
|
-
return {
|
|
128
|
-
success: true,
|
|
129
|
-
settings: _cachedSettings!.settings,
|
|
130
|
-
checksum: _cachedSettings!.checksum,
|
|
131
|
-
};
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
if (response.status === 404) {
|
|
135
|
-
logger.debug("remoteSettings: 404 not configured — clearing stale cache");
|
|
136
|
-
_cachedSettings = null;
|
|
137
|
-
removeCacheFromDisk();
|
|
138
|
-
if (oldChecksum) {
|
|
139
|
-
await notifySettingsUpdate();
|
|
140
|
-
}
|
|
141
|
-
return { success: true, notConfigured: true, settings: null };
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
if (!response.ok) {
|
|
145
|
-
const body = await response.text().catch(() => "");
|
|
146
|
-
logger.debug("remoteSettings: fetch failed", {
|
|
147
|
-
status: response.status,
|
|
148
|
-
body: body.slice(0, 200),
|
|
149
|
-
});
|
|
150
|
-
return {
|
|
151
|
-
success: false,
|
|
152
|
-
error: `HTTP ${response.status}`,
|
|
153
|
-
settings: _cachedSettings?.settings ?? null,
|
|
154
|
-
};
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
const data = (await response.json()) as RemoteSettingsResponse;
|
|
158
|
-
_cachedSettings = {
|
|
159
|
-
uuid: data.uuid,
|
|
160
|
-
checksum: data.checksum,
|
|
161
|
-
settings: data.settings,
|
|
162
|
-
fetchedAt: new Date().toISOString(),
|
|
163
|
-
};
|
|
164
|
-
writeCacheToDisk();
|
|
165
|
-
logger.debug("remoteSettings: fetched new settings", {
|
|
166
|
-
checksum: data.checksum,
|
|
167
|
-
});
|
|
168
|
-
if (data.checksum !== oldChecksum) {
|
|
169
|
-
await notifySettingsUpdate();
|
|
170
|
-
}
|
|
171
|
-
return {
|
|
172
|
-
success: true,
|
|
173
|
-
settings: data.settings,
|
|
174
|
-
checksum: data.checksum,
|
|
175
|
-
};
|
|
176
|
-
} catch (err) {
|
|
177
|
-
logger.debug("remoteSettings: network error, using cache", { err });
|
|
178
|
-
return {
|
|
179
|
-
success: false,
|
|
180
|
-
error: err instanceof Error ? err.message : String(err),
|
|
181
|
-
settings: _cachedSettings?.settings ?? null,
|
|
182
|
-
};
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
function startPolling(): void {
|
|
187
|
-
if (_pollingTimer) {
|
|
188
|
-
return;
|
|
189
|
-
}
|
|
190
|
-
_pollingTimer = setInterval(async () => {
|
|
191
|
-
try {
|
|
192
|
-
await fetchRemoteSettings();
|
|
193
|
-
} catch (err) {
|
|
194
|
-
logger.debug("remoteSettings: polling fetch error", { err });
|
|
195
|
-
}
|
|
196
|
-
}, POLLING_INTERVAL_MS);
|
|
197
|
-
_pollingTimer.unref();
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
export function initialize(): void {
|
|
201
|
-
// Load disk cache synchronously so getRemoteSettingsSync() returns cached
|
|
202
|
-
// managed settings during loadMergedConfiguration() (must run BEFORE it).
|
|
203
|
-
loadCacheFromDisk();
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
/**
|
|
207
|
-
* Start the fire-and-forget initial network fetch + background polling.
|
|
208
|
-
*
|
|
209
|
-
* Must be called AFTER loadMergedConfiguration() so disk-cached managed
|
|
210
|
-
* settings are merged before the fetch, and so settings `env` WAVE_SERVER_URL
|
|
211
|
-
* is mirrored to process.env (by setEnvironmentVars) before the fetch. The
|
|
212
|
-
* fetch uses authService.getServerUrl(), which reads process.env.WAVE_SERVER_URL
|
|
213
|
-
* — the settings value is visible there, so there is no init-ordering race
|
|
214
|
-
* that would fall back to DEFAULT_SERVER_URL (prod) and hit a test endpoint (401).
|
|
215
|
-
*/
|
|
216
|
-
export function startBackgroundFetch(): void {
|
|
217
|
-
fetchRemoteSettings()
|
|
218
|
-
.then(() => startPolling())
|
|
219
|
-
.catch((err) => {
|
|
220
|
-
logger.debug("remoteSettings: initial fetch failed", { err });
|
|
221
|
-
startPolling();
|
|
222
|
-
});
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
export function getRemoteSettingsSync(): WaveConfiguration | null {
|
|
226
|
-
return _cachedSettings?.settings ?? null;
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
export async function refresh(): Promise<RemoteSettingsFetchResult> {
|
|
230
|
-
// Clear in-memory so we force a fresh fetch
|
|
231
|
-
_cachedSettings = null;
|
|
232
|
-
removeCacheFromDisk();
|
|
233
|
-
return fetchRemoteSettings();
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
export function clear(): void {
|
|
237
|
-
_cachedSettings = null;
|
|
238
|
-
removeCacheFromDisk();
|
|
239
|
-
if (_pollingTimer) {
|
|
240
|
-
clearInterval(_pollingTimer);
|
|
241
|
-
_pollingTimer = null;
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
export function shutdown(): void {
|
|
246
|
-
if (_pollingTimer) {
|
|
247
|
-
clearInterval(_pollingTimer);
|
|
248
|
-
_pollingTimer = null;
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
function dedupe(arr: string[]): string[] {
|
|
253
|
-
return [...new Set(arr)];
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
function mergeHooks(
|
|
257
|
-
local: Partial<Record<HookEvent, HookEventConfig[]>> | undefined,
|
|
258
|
-
remote: Partial<Record<HookEvent, HookEventConfig[]>> | undefined,
|
|
259
|
-
): Partial<Record<HookEvent, HookEventConfig[]>> | undefined {
|
|
260
|
-
if (!remote && !local) {
|
|
261
|
-
return undefined;
|
|
262
|
-
}
|
|
263
|
-
if (!remote) {
|
|
264
|
-
return local;
|
|
265
|
-
}
|
|
266
|
-
if (!local) {
|
|
267
|
-
return remote;
|
|
268
|
-
}
|
|
269
|
-
const merged: Partial<Record<HookEvent, HookEventConfig[]>> = { ...local };
|
|
270
|
-
for (const [event, remoteHooks] of Object.entries(remote)) {
|
|
271
|
-
const localHooks = merged[event as HookEvent] ?? [];
|
|
272
|
-
// Concatenate + dedupe by JSON serialization
|
|
273
|
-
const combined = [...localHooks, ...(remoteHooks ?? [])];
|
|
274
|
-
const seen = new Set<string>();
|
|
275
|
-
merged[event as HookEvent] = combined.filter((h) => {
|
|
276
|
-
const key = JSON.stringify(h);
|
|
277
|
-
if (seen.has(key)) {
|
|
278
|
-
return false;
|
|
279
|
-
}
|
|
280
|
-
seen.add(key);
|
|
281
|
-
return true;
|
|
282
|
-
});
|
|
283
|
-
}
|
|
284
|
-
return merged;
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
export function mergeRemoteSettings(
|
|
288
|
-
localMerged: WaveConfiguration,
|
|
289
|
-
remote: WaveConfiguration,
|
|
290
|
-
): WaveConfiguration {
|
|
291
|
-
const result: WaveConfiguration = { ...localMerged };
|
|
292
|
-
|
|
293
|
-
// env: merge by key, remote wins per-key
|
|
294
|
-
if (remote.env || localMerged.env) {
|
|
295
|
-
result.env = { ...localMerged.env, ...remote.env };
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
// permissions
|
|
299
|
-
if (remote.permissions || localMerged.permissions) {
|
|
300
|
-
const lp = localMerged.permissions ?? {};
|
|
301
|
-
const rp = remote.permissions ?? {};
|
|
302
|
-
result.permissions = {
|
|
303
|
-
// allow: concatenate + dedupe
|
|
304
|
-
allow:
|
|
305
|
-
lp.allow || rp.allow
|
|
306
|
-
? dedupe([...(lp.allow ?? []), ...(rp.allow ?? [])])
|
|
307
|
-
: undefined,
|
|
308
|
-
// deny: concatenate + dedupe
|
|
309
|
-
deny:
|
|
310
|
-
lp.deny || rp.deny
|
|
311
|
-
? dedupe([...(lp.deny ?? []), ...(rp.deny ?? [])])
|
|
312
|
-
: undefined,
|
|
313
|
-
// permissionMode: remote wins (scalar)
|
|
314
|
-
permissionMode: rp.permissionMode ?? lp.permissionMode,
|
|
315
|
-
// additionalDirectories: concatenate + dedupe
|
|
316
|
-
additionalDirectories:
|
|
317
|
-
lp.additionalDirectories || rp.additionalDirectories
|
|
318
|
-
? dedupe([
|
|
319
|
-
...(lp.additionalDirectories ?? []),
|
|
320
|
-
...(rp.additionalDirectories ?? []),
|
|
321
|
-
])
|
|
322
|
-
: undefined,
|
|
323
|
-
};
|
|
324
|
-
// Clean up undefined keys
|
|
325
|
-
if (!result.permissions.allow) delete result.permissions.allow;
|
|
326
|
-
if (!result.permissions.deny) delete result.permissions.deny;
|
|
327
|
-
if (!result.permissions.permissionMode)
|
|
328
|
-
delete result.permissions.permissionMode;
|
|
329
|
-
if (!result.permissions.additionalDirectories)
|
|
330
|
-
delete result.permissions.additionalDirectories;
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
// hooks: concatenate per-event
|
|
334
|
-
result.hooks = mergeHooks(localMerged.hooks, remote.hooks);
|
|
335
|
-
|
|
336
|
-
// Scalar / last-write-wins fields: remote wins
|
|
337
|
-
if (remote.language !== undefined) result.language = remote.language;
|
|
338
|
-
if (remote.model !== undefined) result.model = remote.model;
|
|
339
|
-
if (remote.autoMemoryEnabled !== undefined)
|
|
340
|
-
result.autoMemoryEnabled = remote.autoMemoryEnabled;
|
|
341
|
-
if (remote.autoMemoryFrequency !== undefined)
|
|
342
|
-
result.autoMemoryFrequency = remote.autoMemoryFrequency;
|
|
343
|
-
if (remote.worktree !== undefined) result.worktree = remote.worktree;
|
|
344
|
-
if (remote.models !== undefined) result.models = remote.models;
|
|
345
|
-
if (remote.marketplaces !== undefined)
|
|
346
|
-
result.marketplaces = remote.marketplaces;
|
|
347
|
-
if (remote.enabledPlugins !== undefined)
|
|
348
|
-
result.enabledPlugins = remote.enabledPlugins;
|
|
349
|
-
|
|
350
|
-
return result;
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
/**
|
|
354
|
-
* Singleton object for consumers that prefer a namespace-style import.
|
|
355
|
-
* Usage: import { remoteSettingsService } from "./remoteSettingsService.js"
|
|
356
|
-
*/
|
|
357
|
-
export const remoteSettingsService = {
|
|
358
|
-
initialize,
|
|
359
|
-
startBackgroundFetch,
|
|
360
|
-
getRemoteSettingsSync,
|
|
361
|
-
refresh,
|
|
362
|
-
clear,
|
|
363
|
-
shutdown,
|
|
364
|
-
mergeRemoteSettings,
|
|
365
|
-
onSettingsUpdate,
|
|
366
|
-
} as const;
|