Skip to content

Commit 9a5c086

Browse files
committed
refactor(infra): consolidate service paths and usage rollups
1 parent 8f2850d commit 9a5c086

4 files changed

Lines changed: 66 additions & 186 deletions

File tree

‎src/daemon/node-service.ts‎

Lines changed: 8 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -33,17 +33,7 @@ function withNodeInstallEnv(args: GatewayServiceInstallArgs): GatewayServiceInst
3333
return {
3434
...args,
3535
env: withNodeServiceEnv(args.env),
36-
environment: {
37-
...args.environment,
38-
OPENCLAW_LAUNCHD_LABEL: resolveNodeLaunchAgentLabel(),
39-
OPENCLAW_SYSTEMD_UNIT: resolveNodeSystemdServiceName(),
40-
OPENCLAW_WINDOWS_TASK_NAME: resolveNodeWindowsTaskName(),
41-
OPENCLAW_WINDOWS_TASK_HIDDEN_LAUNCHER: "1",
42-
OPENCLAW_TASK_SCRIPT_NAME: NODE_WINDOWS_TASK_SCRIPT_NAME,
43-
OPENCLAW_LOG_PREFIX: "node",
44-
OPENCLAW_SERVICE_MARKER: NODE_SERVICE_MARKER,
45-
OPENCLAW_SERVICE_KIND: NODE_SERVICE_KIND,
46-
},
36+
environment: withNodeServiceEnv(args.environment ?? {}),
4737
};
4838
}
4939

@@ -52,25 +42,13 @@ export function resolveNodeService(): GatewayService {
5242
const base = resolveGatewayService();
5343
return {
5444
...base,
55-
stage: async (args) => {
56-
return base.stage(withNodeInstallEnv(args));
57-
},
58-
install: async (args) => {
59-
return base.install(withNodeInstallEnv(args));
60-
},
61-
uninstall: async (args) => {
62-
return base.uninstall({ ...args, env: withNodeServiceEnv(args.env) });
63-
},
64-
start: async (args) => {
65-
return base.start({ ...args, env: withNodeServiceEnv(args.env ?? {}) });
66-
},
67-
stop: async (args) => {
68-
return base.stop({ ...args, env: withNodeServiceEnv(args.env ?? {}) });
69-
},
70-
restart: async (args) => {
71-
return base.restart({ ...args, env: withNodeServiceEnv(args.env ?? {}) });
72-
},
73-
isLoaded: async (args) => {
45+
stage: (args) => base.stage(withNodeInstallEnv(args)),
46+
install: (args) => base.install(withNodeInstallEnv(args)),
47+
uninstall: (args) => base.uninstall({ ...args, env: withNodeServiceEnv(args.env) }),
48+
start: (args) => base.start({ ...args, env: withNodeServiceEnv(args.env ?? {}) }),
49+
stop: (args) => base.stop({ ...args, env: withNodeServiceEnv(args.env ?? {}) }),
50+
restart: (args) => base.restart({ ...args, env: withNodeServiceEnv(args.env ?? {}) }),
51+
isLoaded: (args) => {
7452
// Preserve the status read deadline so node probes fail soft under a
7553
// wedged service manager instead of hanging the whole status command.
7654
return base.isLoaded({ env: withNodeServiceEnv(args.env ?? {}), timeoutMs: args.timeoutMs });

‎src/daemon/service-env.ts‎

Lines changed: 43 additions & 113 deletions
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,6 @@ type MinimalServicePathOptions = {
3232
includeMissingUserBinDefaults?: boolean;
3333
};
3434

35-
type BuildServicePathOptions = MinimalServicePathOptions & {
36-
env?: Record<string, string | undefined>;
37-
};
38-
3935
type SharedServiceEnvironmentFields = {
4036
stateDir: string | undefined;
4137
configPath: string | undefined;
@@ -239,16 +235,10 @@ function resolveSystemPathDirs(platform: NodeJS.Platform): string[] {
239235
return [];
240236
}
241237

242-
/**
243-
* Resolve common user bin directories for macOS.
244-
* These are paths where npm global installs and node version managers typically place binaries.
245-
*
246-
* Key differences from Linux:
247-
* - fnm: macOS uses ~/Library/Application Support/fnm (not ~/.local/share/fnm)
248-
* - pnpm: macOS uses ~/Library/pnpm (not ~/.local/share/pnpm)
249-
*/
250-
function resolveDarwinUserBinDirs(
238+
/** Resolve common user bin directories while preserving platform-specific manager roots. */
239+
function resolveUserBinDirs(
251240
home: string | undefined,
241+
platform: "darwin" | "linux",
252242
env?: Record<string, string | undefined>,
253243
existsSync: (candidate: string) => boolean = fs.existsSync,
254244
options: Pick<MinimalServicePathOptions, "cwd" | "home" | "includeMissingUserBinDefaults"> = {},
@@ -261,76 +251,42 @@ function resolveDarwinUserBinDirs(
261251
const pathOptions = { ...options, home };
262252
const includeMissingUserBinDefaults = options.includeMissingUserBinDefaults ?? true;
263253

264-
// Env-configured bin roots (override defaults when present).
265-
// Note: FNM_DIR on macOS defaults to ~/Library/Application Support/fnm
266-
// Note: PNPM_HOME on macOS defaults to ~/Library/pnpm
267254
addCommonEnvConfiguredBinDirs(dirs, env, pathOptions);
268-
// nvm: no stable default path, relies on env or user's shell config
269-
// User must set NVM_DIR and source nvm.sh for it to work
270-
addEnvConfiguredBinDir(dirs, env?.NVM_DIR, pathOptions);
271-
// fnm: use aliases/default (not current)
255+
addEnvConfiguredBinDir(
256+
dirs,
257+
platform === "darwin" ? env?.NVM_DIR : appendSubdir(env?.NVM_DIR, "current/bin"),
258+
pathOptions,
259+
);
272260
addEnvConfiguredBinDir(dirs, appendSubdir(env?.FNM_DIR, "aliases/default/bin"), pathOptions);
273-
// pnpm 10 placed binaries directly in PNPM_HOME; pnpm 11 uses PNPM_HOME/bin.
274-
275-
// Common user bin directories
276-
addCommonUserBinDirs(dirs, home, existsSync, includeMissingUserBinDefaults);
277-
278-
// Nix Home Manager (cross-platform)
279-
addNixProfileBinDirs(dirs, home, env, pathOptions, includeMissingUserBinDefaults, existsSync);
280-
281-
// Node version managers - macOS specific paths
282-
// nvm: no stable default path, depends on user's shell configuration
283-
// fnm: macOS default is ~/Library/Application Support/fnm, not ~/.fnm
284-
addExistingDir(dirs, `${home}/Library/Application Support/fnm/aliases/default/bin`, existsSync); // fnm default
285-
addExistingDir(dirs, `${home}/.fnm/aliases/default/bin`, existsSync); // fnm if customized to ~/.fnm
286-
// pnpm: macOS default is ~/Library/pnpm, not ~/.local/share/pnpm
287-
addExistingDir(dirs, `${home}/Library/pnpm/bin`, existsSync); // pnpm 11 default
288-
addExistingDir(dirs, `${home}/Library/pnpm`, existsSync); // pnpm default
289-
addExistingDir(dirs, `${home}/.local/share/pnpm/bin`, existsSync); // pnpm 11 XDG fallback
290-
addExistingDir(dirs, `${home}/.local/share/pnpm`, existsSync); // pnpm XDG fallback
291-
292-
return dirs;
293-
}
294-
295-
/**
296-
* Resolve common user bin directories for Linux.
297-
* These are paths where npm global installs and node version managers typically place binaries.
298-
*/
299-
function resolveLinuxUserBinDirs(
300-
home: string | undefined,
301-
env?: Record<string, string | undefined>,
302-
existsSync: (candidate: string) => boolean = fs.existsSync,
303-
options: Pick<MinimalServicePathOptions, "cwd" | "home" | "includeMissingUserBinDefaults"> = {},
304-
): string[] {
305-
if (!home) {
306-
return [];
261+
if (platform === "linux") {
262+
addEnvConfiguredBinDir(dirs, appendSubdir(env?.FNM_DIR, "current/bin"), pathOptions);
307263
}
308-
309-
const dirs: string[] = [];
310-
const pathOptions = { ...options, home };
311-
const includeMissingUserBinDefaults = options.includeMissingUserBinDefaults ?? true;
312-
313-
// Env-configured bin roots (override defaults when present).
314-
addCommonEnvConfiguredBinDirs(dirs, env, pathOptions);
315-
addEnvConfiguredBinDir(dirs, appendSubdir(env?.NVM_DIR, "current/bin"), pathOptions);
316-
addEnvConfiguredBinDir(dirs, appendSubdir(env?.FNM_DIR, "aliases/default/bin"), pathOptions);
317-
addEnvConfiguredBinDir(dirs, appendSubdir(env?.FNM_DIR, "current/bin"), pathOptions);
318-
319-
// Common user bin directories
320264
addCommonUserBinDirs(dirs, home, existsSync, includeMissingUserBinDefaults);
321-
322-
// Nix Home Manager (cross-platform)
323265
addNixProfileBinDirs(dirs, home, env, pathOptions, includeMissingUserBinDefaults, existsSync);
324-
325-
// Node version managers
326-
addExistingDir(dirs, `${home}/.nvm/current/bin`, existsSync); // nvm with current symlink
327-
addExistingDir(dirs, `${home}/.local/share/fnm/aliases/default/bin`, existsSync); // fnm default
328-
addExistingDir(dirs, `${home}/.local/share/fnm/current/bin`, existsSync); // fnm legacy current symlink
329-
addExistingDir(dirs, `${home}/.fnm/aliases/default/bin`, existsSync); // fnm if customized to ~/.fnm
330-
addExistingDir(dirs, `${home}/.fnm/current/bin`, existsSync); // fnm legacy current symlink
331-
addExistingDir(dirs, `${home}/.local/share/pnpm/bin`, existsSync); // pnpm 11 global bin
332-
addExistingDir(dirs, `${home}/.local/share/pnpm`, existsSync); // pnpm global bin
333-
266+
// macOS uses Library roots; Linux uses XDG/current symlinks. Preserve both
267+
// the pnpm root (v10) and its bin subdirectory (v11) in their original order.
268+
const managerDirs =
269+
platform === "darwin"
270+
? [
271+
"Library/Application Support/fnm/aliases/default/bin",
272+
".fnm/aliases/default/bin",
273+
"Library/pnpm/bin",
274+
"Library/pnpm",
275+
".local/share/pnpm/bin",
276+
".local/share/pnpm",
277+
]
278+
: [
279+
".nvm/current/bin",
280+
".local/share/fnm/aliases/default/bin",
281+
".local/share/fnm/current/bin",
282+
".fnm/aliases/default/bin",
283+
".fnm/current/bin",
284+
".local/share/pnpm/bin",
285+
".local/share/pnpm",
286+
];
287+
for (const directory of managerDirs) {
288+
addExistingDir(dirs, `${home}/${directory}`, existsSync);
289+
}
334290
return dirs;
335291
}
336292

@@ -342,43 +298,22 @@ function getMinimalServicePathParts(options: MinimalServicePathOptions = {}): st
342298
return [];
343299
}
344300

345-
const parts: string[] = [];
346301
const extraDirs = options.extraDirs ?? [];
347302
const systemDirs = resolveSystemPathDirs(platform);
348303
const includeUserDirs = options.includeUserDirs ?? platform !== "darwin";
349304

350305
const existsSync = options.existsSync ?? fs.existsSync;
351-
const userDirs = includeUserDirs
352-
? platform === "linux"
353-
? resolveLinuxUserBinDirs(options.home, options.env, existsSync, options)
354-
: platform === "darwin"
355-
? resolveDarwinUserBinDirs(options.home, options.env, existsSync, options)
356-
: []
357-
: [];
358-
359-
const add = (dir: string) => {
360-
if (!dir) {
361-
return;
362-
}
363-
if (!parts.includes(dir)) {
364-
parts.push(dir);
365-
}
366-
};
367-
368-
for (const dir of extraDirs) {
369-
add(dir);
370-
}
371-
for (const dir of systemDirs) {
372-
add(dir);
373-
}
374-
for (const dir of userDirs) {
375-
add(dir);
376-
}
306+
const userDirs =
307+
includeUserDirs && (platform === "linux" || platform === "darwin")
308+
? resolveUserBinDirs(options.home, platform, options.env, existsSync, options)
309+
: [];
377310

378-
return parts;
311+
return [...new Set([...extraDirs, ...systemDirs, ...userDirs].filter(Boolean))];
379312
}
380313

381-
export function getMinimalServicePathPartsFromEnv(options: BuildServicePathOptions = {}): string[] {
314+
export function getMinimalServicePathPartsFromEnv(
315+
options: MinimalServicePathOptions = {},
316+
): string[] {
382317
const env = options.env ?? process.env;
383318
return getMinimalServicePathParts({
384319
...options,
@@ -387,13 +322,8 @@ export function getMinimalServicePathPartsFromEnv(options: BuildServicePathOptio
387322
});
388323
}
389324

390-
function buildMinimalServicePath(options: BuildServicePathOptions = {}): string {
325+
function buildMinimalServicePath(options: MinimalServicePathOptions = {}): string {
391326
const env = options.env ?? process.env;
392-
const platform = options.platform ?? process.platform;
393-
if (platform === "win32") {
394-
return env.PATH ?? "";
395-
}
396-
397327
return getMinimalServicePathPartsFromEnv({ ...options, env }).join(path.posix.delimiter);
398328
}
399329

‎src/infra/session-cost-usage-rollup.ts‎

Lines changed: 13 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,8 @@ type SessionUsageLatencyAggregate = {
3636
sum: number;
3737
};
3838

39-
type SessionUsageRollupBucket = {
39+
type SessionUsageRollupBucket = SessionUsageUntimestampedRollup & {
4040
timestampMs: number;
41-
totals: CostUsageTotals;
42-
messageCounts: SessionMessageCounts;
43-
tools: Array<{ name: string; count: number }>;
44-
models: SessionModelUsage[];
4541
latency: SessionUsageLatencyAggregate;
4642
};
4743

@@ -224,10 +220,7 @@ function addMessageContribution(
224220
function createBucket(timestampMs: number): SessionUsageRollupBucket {
225221
return {
226222
timestampMs,
227-
totals: createEmptyCostUsageTotals(),
228-
messageCounts: emptyMessageCounts(),
229-
tools: [],
230-
models: [],
223+
...createUntimestampedRollup(),
231224
latency: createLatencyAggregate(),
232225
};
233226
}
@@ -237,23 +230,11 @@ export function appendSessionUsageRollupContribution(
237230
contribution: SessionUsageRollupContribution,
238231
): void {
239232
const timestamp = contribution.timestamp;
240-
if (timestamp === undefined) {
241-
addMessageContribution(rollup.untimestamped.messageCounts, contribution);
242-
for (const toolName of contribution.toolNames) {
243-
incrementTool(rollup.untimestamped.tools, toolName);
244-
}
245-
if (contribution.usageTotals) {
246-
addCostUsageTotals(rollup.untimestamped.totals, contribution.usageTotals);
247-
addModelUsage(
248-
rollup.untimestamped.models,
249-
contribution.provider,
250-
contribution.model,
251-
contribution.usageTotals,
252-
);
253-
}
254-
return;
255-
}
256-
const bucket = (rollup.buckets[String(timestamp)] ??= createBucket(timestamp));
233+
const timedBucket =
234+
timestamp === undefined
235+
? undefined
236+
: (rollup.buckets[String(timestamp)] ??= createBucket(timestamp));
237+
const bucket = timedBucket ?? rollup.untimestamped;
257238
addMessageContribution(bucket.messageCounts, contribution);
258239
for (const toolName of contribution.toolNames) {
259240
incrementTool(bucket.tools, toolName);
@@ -267,20 +248,23 @@ export function appendSessionUsageRollupContribution(
267248
contribution.usageTotals,
268249
);
269250
}
251+
if (!timedBucket) {
252+
return;
253+
}
270254
if (contribution.role === "assistant") {
271255
const sourceUserTimestamp =
272256
contribution.durationMs === undefined ? rollup.lastUserTimestamp : undefined;
273257
const latencyMs =
274258
contribution.durationMs ??
275259
(sourceUserTimestamp !== undefined
276-
? Math.max(0, timestamp - sourceUserTimestamp)
260+
? Math.max(0, timedBucket.timestampMs - sourceUserTimestamp)
277261
: undefined);
278262
if (latencyMs !== undefined && Number.isFinite(latencyMs) && latencyMs <= MAX_LATENCY_MS) {
279-
addLatencyValue(bucket.latency, latencyMs);
263+
addLatencyValue(timedBucket.latency, latencyMs);
280264
}
281265
}
282266
if (contribution.role === "user") {
283-
rollup.lastUserTimestamp = timestamp;
267+
rollup.lastUserTimestamp = timedBucket.timestampMs;
284268
}
285269
}
286270

‎src/infra/session-cost-usage.types.ts‎

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -70,25 +70,13 @@ type SessionDailyUsage = {
7070
cost: number;
7171
};
7272

73-
export type SessionDailyMessageCounts = {
73+
export type SessionDailyMessageCounts = SessionMessageCounts & {
7474
date: string; // YYYY-MM-DD
75-
total: number;
76-
user: number;
77-
assistant: number;
78-
toolCalls: number;
79-
toolResults: number;
80-
errors: number;
8175
};
8276

83-
export type SessionUtcQuarterHourMessageCounts = {
77+
export type SessionUtcQuarterHourMessageCounts = SessionMessageCounts & {
8478
date: string; // YYYY-MM-DD (UTC)
8579
quarterIndex: number; // 0-95, UTC quarter-hour bucket (index = floor((utcH * 60 + utcM) / 15))
86-
total: number;
87-
user: number;
88-
assistant: number;
89-
toolCalls: number;
90-
toolResults: number;
91-
errors: number;
9280
};
9381

9482
export type SessionUtcQuarterHourTokenUsage = {

0 commit comments

Comments
 (0)