refactor(src): split oversized modules
This commit is contained in:
BIN
src/commands/.DS_Store
vendored
Normal file
BIN
src/commands/.DS_Store
vendored
Normal file
Binary file not shown.
@@ -1,4 +1,3 @@
|
||||
import crypto from "node:crypto";
|
||||
import {
|
||||
resolveAgentDir,
|
||||
resolveAgentModelFallbacksOverride,
|
||||
@@ -7,13 +6,8 @@ import {
|
||||
} from "../agents/agent-scope.js";
|
||||
import { ensureAuthProfileStore } from "../agents/auth-profiles.js";
|
||||
import { runCliAgent } from "../agents/cli-runner.js";
|
||||
import { getCliSessionId, setCliSessionId } from "../agents/cli-session.js";
|
||||
import { lookupContextTokens } from "../agents/context.js";
|
||||
import {
|
||||
DEFAULT_CONTEXT_TOKENS,
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_PROVIDER,
|
||||
} from "../agents/defaults.js";
|
||||
import { getCliSessionId } from "../agents/cli-session.js";
|
||||
import { DEFAULT_MODEL, DEFAULT_PROVIDER } from "../agents/defaults.js";
|
||||
import { loadModelCatalog } from "../agents/model-catalog.js";
|
||||
import { runWithModelFallback } from "../agents/model-fallback.js";
|
||||
import {
|
||||
@@ -26,9 +20,7 @@ import {
|
||||
import { runEmbeddedPiAgent } from "../agents/pi-embedded.js";
|
||||
import { buildWorkspaceSkillSnapshot } from "../agents/skills.js";
|
||||
import { resolveAgentTimeoutMs } from "../agents/timeout.js";
|
||||
import { hasNonzeroUsage } from "../agents/usage.js";
|
||||
import { ensureAgentWorkspace } from "../agents/workspace.js";
|
||||
import type { MsgContext } from "../auto-reply/templating.js";
|
||||
import {
|
||||
formatThinkingLevels,
|
||||
formatXHighModelHint,
|
||||
@@ -38,25 +30,11 @@ import {
|
||||
type ThinkLevel,
|
||||
type VerboseLevel,
|
||||
} from "../auto-reply/thinking.js";
|
||||
import { type CliDeps, createDefaultDeps } from "../cli/deps.js";
|
||||
import { loadConfig } from "../config/config.js";
|
||||
import {
|
||||
getChannelPlugin,
|
||||
normalizeChannelId,
|
||||
} from "../channels/plugins/index.js";
|
||||
import type { ChannelOutboundTargetMode } from "../channels/plugins/types.js";
|
||||
import { DEFAULT_CHAT_CHANNEL } from "../channels/registry.js";
|
||||
import {
|
||||
type CliDeps,
|
||||
createDefaultDeps,
|
||||
createOutboundSendDeps,
|
||||
} from "../cli/deps.js";
|
||||
import { type ClawdbotConfig, loadConfig } from "../config/config.js";
|
||||
import {
|
||||
DEFAULT_IDLE_MINUTES,
|
||||
loadSessionStore,
|
||||
resolveAgentIdFromSessionKey,
|
||||
resolveSessionFilePath,
|
||||
resolveSessionKey,
|
||||
resolveStorePath,
|
||||
type SessionEntry,
|
||||
saveSessionStore,
|
||||
} from "../config/sessions.js";
|
||||
@@ -64,139 +42,14 @@ import {
|
||||
emitAgentEvent,
|
||||
registerAgentRunContext,
|
||||
} from "../infra/agent-events.js";
|
||||
import { deliverOutboundPayloads } from "../infra/outbound/deliver.js";
|
||||
import { buildOutboundResultEnvelope } from "../infra/outbound/envelope.js";
|
||||
import {
|
||||
formatOutboundPayloadLog,
|
||||
type NormalizedOutboundPayload,
|
||||
normalizeOutboundPayloads,
|
||||
normalizeOutboundPayloadsForJson,
|
||||
} from "../infra/outbound/payloads.js";
|
||||
import { resolveOutboundTarget } from "../infra/outbound/targets.js";
|
||||
import { normalizeMainKey } from "../routing/session-key.js";
|
||||
import { defaultRuntime, type RuntimeEnv } from "../runtime.js";
|
||||
import { applyVerboseOverride } from "../sessions/level-overrides.js";
|
||||
import { resolveSendPolicy } from "../sessions/send-policy.js";
|
||||
import {
|
||||
isInternalMessageChannel,
|
||||
resolveGatewayMessageChannel,
|
||||
resolveMessageChannel,
|
||||
} from "../utils/message-channel.js";
|
||||
|
||||
/** Image content block for Claude API multimodal messages. */
|
||||
type ImageContent = {
|
||||
type: "image";
|
||||
data: string;
|
||||
mimeType: string;
|
||||
};
|
||||
|
||||
type AgentCommandOpts = {
|
||||
message: string;
|
||||
/** Optional image attachments for multimodal messages. */
|
||||
images?: ImageContent[];
|
||||
to?: string;
|
||||
sessionId?: string;
|
||||
sessionKey?: string;
|
||||
thinking?: string;
|
||||
thinkingOnce?: string;
|
||||
verbose?: string;
|
||||
json?: boolean;
|
||||
timeout?: string;
|
||||
deliver?: boolean;
|
||||
/** Message channel context (webchat|voicewake|whatsapp|...). */
|
||||
messageChannel?: string;
|
||||
channel?: string; // delivery channel (whatsapp|telegram|...)
|
||||
deliveryTargetMode?: ChannelOutboundTargetMode;
|
||||
bestEffortDeliver?: boolean;
|
||||
abortSignal?: AbortSignal;
|
||||
lane?: string;
|
||||
runId?: string;
|
||||
extraSystemPrompt?: string;
|
||||
};
|
||||
|
||||
type SessionResolution = {
|
||||
sessionId: string;
|
||||
sessionKey?: string;
|
||||
sessionEntry?: SessionEntry;
|
||||
sessionStore?: Record<string, SessionEntry>;
|
||||
storePath: string;
|
||||
isNewSession: boolean;
|
||||
persistedThinking?: ThinkLevel;
|
||||
persistedVerbose?: VerboseLevel;
|
||||
};
|
||||
|
||||
function resolveSession(opts: {
|
||||
cfg: ClawdbotConfig;
|
||||
to?: string;
|
||||
sessionId?: string;
|
||||
sessionKey?: string;
|
||||
}): SessionResolution {
|
||||
const sessionCfg = opts.cfg.session;
|
||||
const scope = sessionCfg?.scope ?? "per-sender";
|
||||
const mainKey = normalizeMainKey(sessionCfg?.mainKey);
|
||||
const idleMinutes = Math.max(
|
||||
sessionCfg?.idleMinutes ?? DEFAULT_IDLE_MINUTES,
|
||||
1,
|
||||
);
|
||||
const idleMs = idleMinutes * 60_000;
|
||||
const explicitSessionKey = opts.sessionKey?.trim();
|
||||
const storeAgentId = resolveAgentIdFromSessionKey(explicitSessionKey);
|
||||
const storePath = resolveStorePath(sessionCfg?.store, {
|
||||
agentId: storeAgentId,
|
||||
});
|
||||
const sessionStore = loadSessionStore(storePath);
|
||||
const now = Date.now();
|
||||
|
||||
const ctx: MsgContext | undefined = opts.to?.trim()
|
||||
? { From: opts.to }
|
||||
: undefined;
|
||||
let sessionKey: string | undefined =
|
||||
explicitSessionKey ??
|
||||
(ctx ? resolveSessionKey(scope, ctx, mainKey) : undefined);
|
||||
let sessionEntry = sessionKey ? sessionStore[sessionKey] : undefined;
|
||||
|
||||
// If a session id was provided, prefer to re-use its entry (by id) even when no key was derived.
|
||||
if (
|
||||
!explicitSessionKey &&
|
||||
opts.sessionId &&
|
||||
(!sessionEntry || sessionEntry.sessionId !== opts.sessionId)
|
||||
) {
|
||||
const foundKey = Object.keys(sessionStore).find(
|
||||
(key) => sessionStore[key]?.sessionId === opts.sessionId,
|
||||
);
|
||||
if (foundKey) {
|
||||
sessionKey = sessionKey ?? foundKey;
|
||||
sessionEntry = sessionStore[foundKey];
|
||||
}
|
||||
}
|
||||
|
||||
const fresh = sessionEntry && sessionEntry.updatedAt >= now - idleMs;
|
||||
const sessionId =
|
||||
opts.sessionId?.trim() ||
|
||||
(fresh ? sessionEntry?.sessionId : undefined) ||
|
||||
crypto.randomUUID();
|
||||
const isNewSession = !fresh && !opts.sessionId;
|
||||
|
||||
const persistedThinking =
|
||||
fresh && sessionEntry?.thinkingLevel
|
||||
? normalizeThinkLevel(sessionEntry.thinkingLevel)
|
||||
: undefined;
|
||||
const persistedVerbose =
|
||||
fresh && sessionEntry?.verboseLevel
|
||||
? normalizeVerboseLevel(sessionEntry.verboseLevel)
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
sessionId,
|
||||
sessionKey,
|
||||
sessionEntry,
|
||||
sessionStore,
|
||||
storePath,
|
||||
isNewSession,
|
||||
persistedThinking,
|
||||
persistedVerbose,
|
||||
};
|
||||
}
|
||||
import { resolveMessageChannel } from "../utils/message-channel.js";
|
||||
import { deliverAgentCommandResult } from "./agent/delivery.js";
|
||||
import { resolveSession } from "./agent/session.js";
|
||||
import { updateSessionStoreAfterAgentRun } from "./agent/session-store.js";
|
||||
import type { AgentCommandOpts } from "./agent/types.js";
|
||||
|
||||
export async function agentCommand(
|
||||
opts: AgentCommandOpts,
|
||||
@@ -593,142 +446,29 @@ export async function agentCommand(
|
||||
|
||||
// Update token+model fields in the session store.
|
||||
if (sessionStore && sessionKey) {
|
||||
const usage = result.meta.agentMeta?.usage;
|
||||
const modelUsed = result.meta.agentMeta?.model ?? fallbackModel ?? model;
|
||||
const providerUsed =
|
||||
result.meta.agentMeta?.provider ?? fallbackProvider ?? provider;
|
||||
const contextTokens =
|
||||
agentCfg?.contextTokens ??
|
||||
lookupContextTokens(modelUsed) ??
|
||||
DEFAULT_CONTEXT_TOKENS;
|
||||
|
||||
const entry = sessionStore[sessionKey] ?? {
|
||||
await updateSessionStoreAfterAgentRun({
|
||||
cfg,
|
||||
contextTokensOverride: agentCfg?.contextTokens,
|
||||
sessionId,
|
||||
updatedAt: Date.now(),
|
||||
};
|
||||
const next: SessionEntry = {
|
||||
...entry,
|
||||
sessionId,
|
||||
updatedAt: Date.now(),
|
||||
modelProvider: providerUsed,
|
||||
model: modelUsed,
|
||||
contextTokens,
|
||||
};
|
||||
if (isCliProvider(providerUsed, cfg)) {
|
||||
const cliSessionId = result.meta.agentMeta?.sessionId?.trim();
|
||||
if (cliSessionId) setCliSessionId(next, providerUsed, cliSessionId);
|
||||
}
|
||||
next.abortedLastRun = result.meta.aborted ?? false;
|
||||
if (hasNonzeroUsage(usage)) {
|
||||
const input = usage.input ?? 0;
|
||||
const output = usage.output ?? 0;
|
||||
const promptTokens =
|
||||
input + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
|
||||
next.inputTokens = input;
|
||||
next.outputTokens = output;
|
||||
next.totalTokens =
|
||||
promptTokens > 0 ? promptTokens : (usage.total ?? input);
|
||||
}
|
||||
sessionStore[sessionKey] = next;
|
||||
await saveSessionStore(storePath, sessionStore);
|
||||
sessionKey,
|
||||
storePath,
|
||||
sessionStore,
|
||||
defaultProvider: provider,
|
||||
defaultModel: model,
|
||||
fallbackProvider,
|
||||
fallbackModel,
|
||||
result,
|
||||
});
|
||||
}
|
||||
|
||||
const payloads = result.payloads ?? [];
|
||||
const deliver = opts.deliver === true;
|
||||
const bestEffortDeliver = opts.bestEffortDeliver === true;
|
||||
const deliveryChannel =
|
||||
resolveGatewayMessageChannel(opts.channel) ?? DEFAULT_CHAT_CHANNEL;
|
||||
// Channel docking: delivery channels are resolved via plugin registry.
|
||||
const deliveryPlugin = !isInternalMessageChannel(deliveryChannel)
|
||||
? getChannelPlugin(normalizeChannelId(deliveryChannel) ?? deliveryChannel)
|
||||
: undefined;
|
||||
|
||||
const logDeliveryError = (err: unknown) => {
|
||||
const message = `Delivery failed (${deliveryChannel}${deliveryTarget ? ` to ${deliveryTarget}` : ""}): ${String(err)}`;
|
||||
runtime.error?.(message);
|
||||
if (!runtime.error) runtime.log(message);
|
||||
};
|
||||
|
||||
const isDeliveryChannelKnown =
|
||||
isInternalMessageChannel(deliveryChannel) || Boolean(deliveryPlugin);
|
||||
|
||||
const targetMode: ChannelOutboundTargetMode =
|
||||
opts.deliveryTargetMode ?? (opts.to ? "explicit" : "implicit");
|
||||
const resolvedTarget =
|
||||
deliver && isDeliveryChannelKnown && deliveryChannel
|
||||
? resolveOutboundTarget({
|
||||
channel: deliveryChannel,
|
||||
to: opts.to,
|
||||
cfg,
|
||||
accountId:
|
||||
targetMode === "implicit" ? sessionEntry?.lastAccountId : undefined,
|
||||
mode: targetMode,
|
||||
})
|
||||
: null;
|
||||
const deliveryTarget = resolvedTarget?.ok ? resolvedTarget.to : undefined;
|
||||
|
||||
if (deliver) {
|
||||
if (!isDeliveryChannelKnown) {
|
||||
const err = new Error(`Unknown channel: ${deliveryChannel}`);
|
||||
if (!bestEffortDeliver) throw err;
|
||||
logDeliveryError(err);
|
||||
} else if (resolvedTarget && !resolvedTarget.ok) {
|
||||
if (!bestEffortDeliver) throw resolvedTarget.error;
|
||||
logDeliveryError(resolvedTarget.error);
|
||||
}
|
||||
}
|
||||
|
||||
const normalizedPayloads = normalizeOutboundPayloadsForJson(payloads);
|
||||
if (opts.json) {
|
||||
runtime.log(
|
||||
JSON.stringify(
|
||||
buildOutboundResultEnvelope({
|
||||
payloads: normalizedPayloads,
|
||||
meta: result.meta,
|
||||
}),
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
if (!deliver) {
|
||||
return { payloads: normalizedPayloads, meta: result.meta };
|
||||
}
|
||||
}
|
||||
|
||||
if (payloads.length === 0) {
|
||||
runtime.log("No reply from agent.");
|
||||
return { payloads: [], meta: result.meta };
|
||||
}
|
||||
|
||||
const deliveryPayloads = normalizeOutboundPayloads(payloads);
|
||||
const logPayload = (payload: NormalizedOutboundPayload) => {
|
||||
if (opts.json) return;
|
||||
const output = formatOutboundPayloadLog(payload);
|
||||
if (output) runtime.log(output);
|
||||
};
|
||||
if (!deliver) {
|
||||
for (const payload of deliveryPayloads) {
|
||||
logPayload(payload);
|
||||
}
|
||||
}
|
||||
if (
|
||||
deliver &&
|
||||
deliveryChannel &&
|
||||
!isInternalMessageChannel(deliveryChannel)
|
||||
) {
|
||||
if (deliveryTarget) {
|
||||
await deliverOutboundPayloads({
|
||||
cfg,
|
||||
channel: deliveryChannel,
|
||||
to: deliveryTarget,
|
||||
payloads: deliveryPayloads,
|
||||
bestEffort: bestEffortDeliver,
|
||||
onError: (err) => logDeliveryError(err),
|
||||
onPayload: logPayload,
|
||||
deps: createOutboundSendDeps(deps, cfg),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { payloads: normalizedPayloads, meta: result.meta };
|
||||
return await deliverAgentCommandResult({
|
||||
cfg,
|
||||
deps,
|
||||
runtime,
|
||||
opts,
|
||||
sessionEntry,
|
||||
result,
|
||||
payloads,
|
||||
});
|
||||
}
|
||||
|
||||
134
src/commands/agent/delivery.ts
Normal file
134
src/commands/agent/delivery.ts
Normal file
@@ -0,0 +1,134 @@
|
||||
import {
|
||||
getChannelPlugin,
|
||||
normalizeChannelId,
|
||||
} from "../../channels/plugins/index.js";
|
||||
import type { ChannelOutboundTargetMode } from "../../channels/plugins/types.js";
|
||||
import { DEFAULT_CHAT_CHANNEL } from "../../channels/registry.js";
|
||||
import type { CliDeps } from "../../cli/deps.js";
|
||||
import { createOutboundSendDeps } from "../../cli/deps.js";
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import type { SessionEntry } from "../../config/sessions.js";
|
||||
import { deliverOutboundPayloads } from "../../infra/outbound/deliver.js";
|
||||
import { buildOutboundResultEnvelope } from "../../infra/outbound/envelope.js";
|
||||
import {
|
||||
formatOutboundPayloadLog,
|
||||
type NormalizedOutboundPayload,
|
||||
normalizeOutboundPayloads,
|
||||
normalizeOutboundPayloadsForJson,
|
||||
} from "../../infra/outbound/payloads.js";
|
||||
import { resolveOutboundTarget } from "../../infra/outbound/targets.js";
|
||||
import type { RuntimeEnv } from "../../runtime.js";
|
||||
import {
|
||||
isInternalMessageChannel,
|
||||
resolveGatewayMessageChannel,
|
||||
} from "../../utils/message-channel.js";
|
||||
import type { AgentCommandOpts } from "./types.js";
|
||||
|
||||
type RunResult = Awaited<
|
||||
ReturnType<typeof import("../../agents/pi-embedded.js")["runEmbeddedPiAgent"]>
|
||||
>;
|
||||
|
||||
export async function deliverAgentCommandResult(params: {
|
||||
cfg: ClawdbotConfig;
|
||||
deps: CliDeps;
|
||||
runtime: RuntimeEnv;
|
||||
opts: AgentCommandOpts;
|
||||
sessionEntry: SessionEntry | undefined;
|
||||
result: RunResult;
|
||||
payloads: RunResult["payloads"];
|
||||
}) {
|
||||
const { cfg, deps, runtime, opts, sessionEntry, payloads, result } = params;
|
||||
const deliver = opts.deliver === true;
|
||||
const bestEffortDeliver = opts.bestEffortDeliver === true;
|
||||
const deliveryChannel =
|
||||
resolveGatewayMessageChannel(opts.channel) ?? DEFAULT_CHAT_CHANNEL;
|
||||
// Channel docking: delivery channels are resolved via plugin registry.
|
||||
const deliveryPlugin = !isInternalMessageChannel(deliveryChannel)
|
||||
? getChannelPlugin(normalizeChannelId(deliveryChannel) ?? deliveryChannel)
|
||||
: undefined;
|
||||
|
||||
const isDeliveryChannelKnown =
|
||||
isInternalMessageChannel(deliveryChannel) || Boolean(deliveryPlugin);
|
||||
|
||||
const targetMode: ChannelOutboundTargetMode =
|
||||
opts.deliveryTargetMode ?? (opts.to ? "explicit" : "implicit");
|
||||
const resolvedTarget =
|
||||
deliver && isDeliveryChannelKnown && deliveryChannel
|
||||
? resolveOutboundTarget({
|
||||
channel: deliveryChannel,
|
||||
to: opts.to,
|
||||
cfg,
|
||||
accountId:
|
||||
targetMode === "implicit" ? sessionEntry?.lastAccountId : undefined,
|
||||
mode: targetMode,
|
||||
})
|
||||
: null;
|
||||
const deliveryTarget = resolvedTarget?.ok ? resolvedTarget.to : undefined;
|
||||
|
||||
const logDeliveryError = (err: unknown) => {
|
||||
const message = `Delivery failed (${deliveryChannel}${deliveryTarget ? ` to ${deliveryTarget}` : ""}): ${String(err)}`;
|
||||
runtime.error?.(message);
|
||||
if (!runtime.error) runtime.log(message);
|
||||
};
|
||||
|
||||
if (deliver) {
|
||||
if (!isDeliveryChannelKnown) {
|
||||
const err = new Error(`Unknown channel: ${deliveryChannel}`);
|
||||
if (!bestEffortDeliver) throw err;
|
||||
logDeliveryError(err);
|
||||
} else if (resolvedTarget && !resolvedTarget.ok) {
|
||||
if (!bestEffortDeliver) throw resolvedTarget.error;
|
||||
logDeliveryError(resolvedTarget.error);
|
||||
}
|
||||
}
|
||||
|
||||
const normalizedPayloads = normalizeOutboundPayloadsForJson(payloads ?? []);
|
||||
if (opts.json) {
|
||||
runtime.log(
|
||||
JSON.stringify(
|
||||
buildOutboundResultEnvelope({
|
||||
payloads: normalizedPayloads,
|
||||
meta: result.meta,
|
||||
}),
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
if (!deliver) return { payloads: normalizedPayloads, meta: result.meta };
|
||||
}
|
||||
|
||||
if (!payloads || payloads.length === 0) {
|
||||
runtime.log("No reply from agent.");
|
||||
return { payloads: [], meta: result.meta };
|
||||
}
|
||||
|
||||
const deliveryPayloads = normalizeOutboundPayloads(payloads);
|
||||
const logPayload = (payload: NormalizedOutboundPayload) => {
|
||||
if (opts.json) return;
|
||||
const output = formatOutboundPayloadLog(payload);
|
||||
if (output) runtime.log(output);
|
||||
};
|
||||
if (!deliver) {
|
||||
for (const payload of deliveryPayloads) logPayload(payload);
|
||||
}
|
||||
if (
|
||||
deliver &&
|
||||
deliveryChannel &&
|
||||
!isInternalMessageChannel(deliveryChannel)
|
||||
) {
|
||||
if (deliveryTarget) {
|
||||
await deliverOutboundPayloads({
|
||||
cfg,
|
||||
channel: deliveryChannel,
|
||||
to: deliveryTarget,
|
||||
payloads: deliveryPayloads,
|
||||
bestEffort: bestEffortDeliver,
|
||||
onError: (err) => logDeliveryError(err),
|
||||
onPayload: logPayload,
|
||||
deps: createOutboundSendDeps(deps, cfg),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { payloads: normalizedPayloads, meta: result.meta };
|
||||
}
|
||||
77
src/commands/agent/session-store.ts
Normal file
77
src/commands/agent/session-store.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import { setCliSessionId } from "../../agents/cli-session.js";
|
||||
import { lookupContextTokens } from "../../agents/context.js";
|
||||
import { DEFAULT_CONTEXT_TOKENS } from "../../agents/defaults.js";
|
||||
import { isCliProvider } from "../../agents/model-selection.js";
|
||||
import { hasNonzeroUsage } from "../../agents/usage.js";
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import { type SessionEntry, saveSessionStore } from "../../config/sessions.js";
|
||||
|
||||
type RunResult = Awaited<
|
||||
ReturnType<typeof import("../../agents/pi-embedded.js")["runEmbeddedPiAgent"]>
|
||||
>;
|
||||
|
||||
export async function updateSessionStoreAfterAgentRun(params: {
|
||||
cfg: ClawdbotConfig;
|
||||
contextTokensOverride?: number;
|
||||
sessionId: string;
|
||||
sessionKey: string;
|
||||
storePath: string;
|
||||
sessionStore: Record<string, SessionEntry>;
|
||||
defaultProvider: string;
|
||||
defaultModel: string;
|
||||
fallbackProvider?: string;
|
||||
fallbackModel?: string;
|
||||
result: RunResult;
|
||||
}) {
|
||||
const {
|
||||
cfg,
|
||||
sessionId,
|
||||
sessionKey,
|
||||
storePath,
|
||||
sessionStore,
|
||||
defaultProvider,
|
||||
defaultModel,
|
||||
fallbackProvider,
|
||||
fallbackModel,
|
||||
result,
|
||||
} = params;
|
||||
|
||||
const usage = result.meta.agentMeta?.usage;
|
||||
const modelUsed =
|
||||
result.meta.agentMeta?.model ?? fallbackModel ?? defaultModel;
|
||||
const providerUsed =
|
||||
result.meta.agentMeta?.provider ?? fallbackProvider ?? defaultProvider;
|
||||
const contextTokens =
|
||||
params.contextTokensOverride ??
|
||||
lookupContextTokens(modelUsed) ??
|
||||
DEFAULT_CONTEXT_TOKENS;
|
||||
|
||||
const entry = sessionStore[sessionKey] ?? {
|
||||
sessionId,
|
||||
updatedAt: Date.now(),
|
||||
};
|
||||
const next: SessionEntry = {
|
||||
...entry,
|
||||
sessionId,
|
||||
updatedAt: Date.now(),
|
||||
modelProvider: providerUsed,
|
||||
model: modelUsed,
|
||||
contextTokens,
|
||||
};
|
||||
if (isCliProvider(providerUsed, cfg)) {
|
||||
const cliSessionId = result.meta.agentMeta?.sessionId?.trim();
|
||||
if (cliSessionId) setCliSessionId(next, providerUsed, cliSessionId);
|
||||
}
|
||||
next.abortedLastRun = result.meta.aborted ?? false;
|
||||
if (hasNonzeroUsage(usage)) {
|
||||
const input = usage.input ?? 0;
|
||||
const output = usage.output ?? 0;
|
||||
const promptTokens =
|
||||
input + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
|
||||
next.inputTokens = input;
|
||||
next.outputTokens = output;
|
||||
next.totalTokens = promptTokens > 0 ? promptTokens : (usage.total ?? input);
|
||||
}
|
||||
sessionStore[sessionKey] = next;
|
||||
await saveSessionStore(storePath, sessionStore);
|
||||
}
|
||||
103
src/commands/agent/session.ts
Normal file
103
src/commands/agent/session.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
import crypto from "node:crypto";
|
||||
|
||||
import type { MsgContext } from "../../auto-reply/templating.js";
|
||||
import {
|
||||
normalizeThinkLevel,
|
||||
normalizeVerboseLevel,
|
||||
type ThinkLevel,
|
||||
type VerboseLevel,
|
||||
} from "../../auto-reply/thinking.js";
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import {
|
||||
DEFAULT_IDLE_MINUTES,
|
||||
loadSessionStore,
|
||||
resolveAgentIdFromSessionKey,
|
||||
resolveSessionKey,
|
||||
resolveStorePath,
|
||||
type SessionEntry,
|
||||
} from "../../config/sessions.js";
|
||||
import { normalizeMainKey } from "../../routing/session-key.js";
|
||||
|
||||
export type SessionResolution = {
|
||||
sessionId: string;
|
||||
sessionKey?: string;
|
||||
sessionEntry?: SessionEntry;
|
||||
sessionStore?: Record<string, SessionEntry>;
|
||||
storePath: string;
|
||||
isNewSession: boolean;
|
||||
persistedThinking?: ThinkLevel;
|
||||
persistedVerbose?: VerboseLevel;
|
||||
};
|
||||
|
||||
export function resolveSession(opts: {
|
||||
cfg: ClawdbotConfig;
|
||||
to?: string;
|
||||
sessionId?: string;
|
||||
sessionKey?: string;
|
||||
}): SessionResolution {
|
||||
const sessionCfg = opts.cfg.session;
|
||||
const scope = sessionCfg?.scope ?? "per-sender";
|
||||
const mainKey = normalizeMainKey(sessionCfg?.mainKey);
|
||||
const idleMinutes = Math.max(
|
||||
sessionCfg?.idleMinutes ?? DEFAULT_IDLE_MINUTES,
|
||||
1,
|
||||
);
|
||||
const idleMs = idleMinutes * 60_000;
|
||||
const explicitSessionKey = opts.sessionKey?.trim();
|
||||
const storeAgentId = resolveAgentIdFromSessionKey(explicitSessionKey);
|
||||
const storePath = resolveStorePath(sessionCfg?.store, {
|
||||
agentId: storeAgentId,
|
||||
});
|
||||
const sessionStore = loadSessionStore(storePath);
|
||||
const now = Date.now();
|
||||
|
||||
const ctx: MsgContext | undefined = opts.to?.trim()
|
||||
? { From: opts.to }
|
||||
: undefined;
|
||||
let sessionKey: string | undefined =
|
||||
explicitSessionKey ??
|
||||
(ctx ? resolveSessionKey(scope, ctx, mainKey) : undefined);
|
||||
let sessionEntry = sessionKey ? sessionStore[sessionKey] : undefined;
|
||||
|
||||
// If a session id was provided, prefer to re-use its entry (by id) even when no key was derived.
|
||||
if (
|
||||
!explicitSessionKey &&
|
||||
opts.sessionId &&
|
||||
(!sessionEntry || sessionEntry.sessionId !== opts.sessionId)
|
||||
) {
|
||||
const foundKey = Object.keys(sessionStore).find(
|
||||
(key) => sessionStore[key]?.sessionId === opts.sessionId,
|
||||
);
|
||||
if (foundKey) {
|
||||
sessionKey = sessionKey ?? foundKey;
|
||||
sessionEntry = sessionStore[foundKey];
|
||||
}
|
||||
}
|
||||
|
||||
const fresh = sessionEntry && sessionEntry.updatedAt >= now - idleMs;
|
||||
const sessionId =
|
||||
opts.sessionId?.trim() ||
|
||||
(fresh ? sessionEntry?.sessionId : undefined) ||
|
||||
crypto.randomUUID();
|
||||
const isNewSession = !fresh && !opts.sessionId;
|
||||
|
||||
const persistedThinking =
|
||||
fresh && sessionEntry?.thinkingLevel
|
||||
? normalizeThinkLevel(sessionEntry.thinkingLevel)
|
||||
: undefined;
|
||||
const persistedVerbose =
|
||||
fresh && sessionEntry?.verboseLevel
|
||||
? normalizeVerboseLevel(sessionEntry.verboseLevel)
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
sessionId,
|
||||
sessionKey,
|
||||
sessionEntry,
|
||||
sessionStore,
|
||||
storePath,
|
||||
isNewSession,
|
||||
persistedThinking,
|
||||
persistedVerbose,
|
||||
};
|
||||
}
|
||||
32
src/commands/agent/types.ts
Normal file
32
src/commands/agent/types.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import type { ChannelOutboundTargetMode } from "../../channels/plugins/types.js";
|
||||
|
||||
/** Image content block for Claude API multimodal messages. */
|
||||
export type ImageContent = {
|
||||
type: "image";
|
||||
data: string;
|
||||
mimeType: string;
|
||||
};
|
||||
|
||||
export type AgentCommandOpts = {
|
||||
message: string;
|
||||
/** Optional image attachments for multimodal messages. */
|
||||
images?: ImageContent[];
|
||||
to?: string;
|
||||
sessionId?: string;
|
||||
sessionKey?: string;
|
||||
thinking?: string;
|
||||
thinkingOnce?: string;
|
||||
verbose?: string;
|
||||
json?: boolean;
|
||||
timeout?: string;
|
||||
deliver?: boolean;
|
||||
/** Message channel context (webchat|voicewake|whatsapp|...). */
|
||||
messageChannel?: string;
|
||||
channel?: string; // delivery channel (whatsapp|telegram|...)
|
||||
deliveryTargetMode?: ChannelOutboundTargetMode;
|
||||
bestEffortDeliver?: boolean;
|
||||
abortSignal?: AbortSignal;
|
||||
lane?: string;
|
||||
runId?: string;
|
||||
extraSystemPrompt?: string;
|
||||
};
|
||||
@@ -469,42 +469,4 @@ describe("channels command", () => {
|
||||
});
|
||||
expect(disconnected.join("\n")).toMatch(/disconnected/i);
|
||||
});
|
||||
|
||||
it("surfaces Signal runtime errors in channels status output", () => {
|
||||
const lines = formatGatewayChannelsStatusLines({
|
||||
channelAccounts: {
|
||||
signal: [
|
||||
{
|
||||
accountId: "default",
|
||||
enabled: true,
|
||||
configured: true,
|
||||
running: false,
|
||||
lastError: "signal-cli unreachable",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(lines.join("\n")).toMatch(/Warnings:/);
|
||||
expect(lines.join("\n")).toMatch(/signal/i);
|
||||
expect(lines.join("\n")).toMatch(/Channel error/i);
|
||||
});
|
||||
|
||||
it("surfaces iMessage runtime errors in channels status output", () => {
|
||||
const lines = formatGatewayChannelsStatusLines({
|
||||
channelAccounts: {
|
||||
imessage: [
|
||||
{
|
||||
accountId: "default",
|
||||
enabled: true,
|
||||
configured: true,
|
||||
running: false,
|
||||
lastError: "imsg permission denied",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(lines.join("\n")).toMatch(/Warnings:/);
|
||||
expect(lines.join("\n")).toMatch(/imessage/i);
|
||||
expect(lines.join("\n")).toMatch(/Channel error/i);
|
||||
});
|
||||
});
|
||||
102
src/commands/channels.part-2.test.ts
Normal file
102
src/commands/channels.part-2.test.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { RuntimeEnv } from "../runtime.js";
|
||||
|
||||
const configMocks = vi.hoisted(() => ({
|
||||
readConfigFileSnapshot: vi.fn(),
|
||||
writeConfigFile: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
const authMocks = vi.hoisted(() => ({
|
||||
loadAuthProfileStore: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../config/config.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../config/config.js")>();
|
||||
return {
|
||||
...actual,
|
||||
readConfigFileSnapshot: configMocks.readConfigFileSnapshot,
|
||||
writeConfigFile: configMocks.writeConfigFile,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../agents/auth-profiles.js", async (importOriginal) => {
|
||||
const actual =
|
||||
await importOriginal<typeof import("../agents/auth-profiles.js")>();
|
||||
return {
|
||||
...actual,
|
||||
loadAuthProfileStore: authMocks.loadAuthProfileStore,
|
||||
};
|
||||
});
|
||||
|
||||
import { formatGatewayChannelsStatusLines } from "./channels.js";
|
||||
|
||||
const runtime: RuntimeEnv = {
|
||||
log: vi.fn(),
|
||||
error: vi.fn(),
|
||||
exit: vi.fn(),
|
||||
};
|
||||
|
||||
const _baseSnapshot = {
|
||||
path: "/tmp/clawdbot.json",
|
||||
exists: true,
|
||||
raw: "{}",
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
};
|
||||
|
||||
describe("channels command", () => {
|
||||
beforeEach(() => {
|
||||
configMocks.readConfigFileSnapshot.mockReset();
|
||||
configMocks.writeConfigFile.mockClear();
|
||||
authMocks.loadAuthProfileStore.mockReset();
|
||||
runtime.log.mockClear();
|
||||
runtime.error.mockClear();
|
||||
runtime.exit.mockClear();
|
||||
authMocks.loadAuthProfileStore.mockReturnValue({
|
||||
version: 1,
|
||||
profiles: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("surfaces Signal runtime errors in channels status output", () => {
|
||||
const lines = formatGatewayChannelsStatusLines({
|
||||
channelAccounts: {
|
||||
signal: [
|
||||
{
|
||||
accountId: "default",
|
||||
enabled: true,
|
||||
configured: true,
|
||||
running: false,
|
||||
lastError: "signal-cli unreachable",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(lines.join("\n")).toMatch(/Warnings:/);
|
||||
expect(lines.join("\n")).toMatch(/signal/i);
|
||||
expect(lines.join("\n")).toMatch(/Channel error/i);
|
||||
});
|
||||
|
||||
it("surfaces iMessage runtime errors in channels status output", () => {
|
||||
const lines = formatGatewayChannelsStatusLines({
|
||||
channelAccounts: {
|
||||
imessage: [
|
||||
{
|
||||
accountId: "default",
|
||||
enabled: true,
|
||||
configured: true,
|
||||
running: false,
|
||||
lastError: "imsg permission denied",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(lines.join("\n")).toMatch(/Warnings:/);
|
||||
expect(lines.join("\n")).toMatch(/imessage/i);
|
||||
expect(lines.join("\n")).toMatch(/Channel error/i);
|
||||
});
|
||||
});
|
||||
@@ -236,7 +236,7 @@ export async function noteStateIntegrity(
|
||||
|
||||
for (const [dir, label] of dirCandidates) {
|
||||
if (!existsDir(dir)) {
|
||||
warnings.push(`- ${label} missing (${dir}).`);
|
||||
warnings.push(`- CRITICAL: ${label} missing (${dir}).`);
|
||||
const create = await prompter.confirmSkipInNonInteractive({
|
||||
message: `Create ${label} at ${dir}?`,
|
||||
initialValue: true,
|
||||
|
||||
@@ -33,6 +33,15 @@ export async function maybeRepairUiProtocolFreshness(
|
||||
"UI",
|
||||
);
|
||||
|
||||
// In slim/docker environments we may not have the UI source tree. Trying
|
||||
// to build would fail (and spam logs), so skip the interactive repair.
|
||||
const uiSourcesPath = path.join(root, "ui/package.json");
|
||||
const uiSourcesExist = await fs.stat(uiSourcesPath).catch(() => null);
|
||||
if (!uiSourcesExist) {
|
||||
note("Skipping UI build: ui/ sources not present.", "UI");
|
||||
return;
|
||||
}
|
||||
|
||||
const shouldRepair = await prompter.confirmRepair({
|
||||
message: "Build Control UI assets now?",
|
||||
initialValue: true,
|
||||
@@ -99,6 +108,13 @@ export async function maybeRepairUiProtocolFreshness(
|
||||
});
|
||||
|
||||
if (shouldRepair) {
|
||||
const uiSourcesPath = path.join(root, "ui/package.json");
|
||||
const uiSourcesExist = await fs.stat(uiSourcesPath).catch(() => null);
|
||||
if (!uiSourcesExist) {
|
||||
note("Skipping UI rebuild: ui/ sources not present.", "UI");
|
||||
return;
|
||||
}
|
||||
|
||||
note("Rebuilding stale UI assets... (this may take a moment)", "UI");
|
||||
// Use scripts/ui.js to build, assuming node is available as we are running in it.
|
||||
// We use the same node executable to run the script.
|
||||
|
||||
462
src/commands/doctor.part-1.test.ts
Normal file
462
src/commands/doctor.part-1.test.ts
Normal file
@@ -0,0 +1,462 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
let originalIsTTY: boolean | undefined;
|
||||
let originalStateDir: string | undefined;
|
||||
let originalUpdateInProgress: string | undefined;
|
||||
let tempStateDir: string | undefined;
|
||||
|
||||
function setStdinTty(value: boolean | undefined) {
|
||||
try {
|
||||
Object.defineProperty(process.stdin, "isTTY", {
|
||||
value,
|
||||
configurable: true,
|
||||
});
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
confirm.mockReset().mockResolvedValue(true);
|
||||
select.mockReset().mockResolvedValue("node");
|
||||
note.mockClear();
|
||||
|
||||
readConfigFileSnapshot.mockReset();
|
||||
writeConfigFile.mockReset().mockResolvedValue(undefined);
|
||||
resolveClawdbotPackageRoot.mockReset().mockResolvedValue(null);
|
||||
runGatewayUpdate.mockReset().mockResolvedValue({
|
||||
status: "skipped",
|
||||
mode: "unknown",
|
||||
steps: [],
|
||||
durationMs: 0,
|
||||
});
|
||||
legacyReadConfigFileSnapshot.mockReset().mockResolvedValue({
|
||||
path: "/tmp/clawdis.json",
|
||||
exists: false,
|
||||
raw: null,
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
createConfigIO.mockReset().mockImplementation(() => ({
|
||||
readConfigFileSnapshot: legacyReadConfigFileSnapshot,
|
||||
}));
|
||||
runExec.mockReset().mockResolvedValue({ stdout: "", stderr: "" });
|
||||
runCommandWithTimeout.mockReset().mockResolvedValue({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
killed: false,
|
||||
});
|
||||
ensureAuthProfileStore
|
||||
.mockReset()
|
||||
.mockReturnValue({ version: 1, profiles: {} });
|
||||
migrateLegacyConfig.mockReset().mockImplementation((raw: unknown) => ({
|
||||
config: raw as Record<string, unknown>,
|
||||
changes: ["Moved routing.allowFrom → channels.whatsapp.allowFrom."],
|
||||
}));
|
||||
findLegacyGatewayServices.mockReset().mockResolvedValue([]);
|
||||
uninstallLegacyGatewayServices.mockReset().mockResolvedValue([]);
|
||||
findExtraGatewayServices.mockReset().mockResolvedValue([]);
|
||||
renderGatewayServiceCleanupHints.mockReset().mockReturnValue(["cleanup"]);
|
||||
resolveGatewayProgramArguments.mockReset().mockResolvedValue({
|
||||
programArguments: ["node", "cli", "gateway", "--port", "18789"],
|
||||
});
|
||||
serviceInstall.mockReset().mockResolvedValue(undefined);
|
||||
serviceIsLoaded.mockReset().mockResolvedValue(false);
|
||||
serviceStop.mockReset().mockResolvedValue(undefined);
|
||||
serviceRestart.mockReset().mockResolvedValue(undefined);
|
||||
serviceUninstall.mockReset().mockResolvedValue(undefined);
|
||||
callGateway.mockReset().mockRejectedValue(new Error("gateway closed"));
|
||||
|
||||
originalIsTTY = process.stdin.isTTY;
|
||||
setStdinTty(true);
|
||||
originalStateDir = process.env.CLAWDBOT_STATE_DIR;
|
||||
originalUpdateInProgress = process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
|
||||
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = "1";
|
||||
tempStateDir = fs.mkdtempSync(
|
||||
path.join(os.tmpdir(), "clawdbot-doctor-state-"),
|
||||
);
|
||||
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
|
||||
fs.mkdirSync(path.join(tempStateDir, "agents", "main", "sessions"), {
|
||||
recursive: true,
|
||||
});
|
||||
fs.mkdirSync(path.join(tempStateDir, "credentials"), { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setStdinTty(originalIsTTY);
|
||||
if (originalStateDir === undefined) {
|
||||
delete process.env.CLAWDBOT_STATE_DIR;
|
||||
} else {
|
||||
process.env.CLAWDBOT_STATE_DIR = originalStateDir;
|
||||
}
|
||||
if (originalUpdateInProgress === undefined) {
|
||||
delete process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
|
||||
} else {
|
||||
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = originalUpdateInProgress;
|
||||
}
|
||||
if (tempStateDir) {
|
||||
fs.rmSync(tempStateDir, { recursive: true, force: true });
|
||||
tempStateDir = undefined;
|
||||
}
|
||||
});
|
||||
|
||||
const readConfigFileSnapshot = vi.fn();
|
||||
const confirm = vi.fn().mockResolvedValue(true);
|
||||
const select = vi.fn().mockResolvedValue("node");
|
||||
const note = vi.fn();
|
||||
const writeConfigFile = vi.fn().mockResolvedValue(undefined);
|
||||
const resolveClawdbotPackageRoot = vi.fn().mockResolvedValue(null);
|
||||
const runGatewayUpdate = vi.fn().mockResolvedValue({
|
||||
status: "skipped",
|
||||
mode: "unknown",
|
||||
steps: [],
|
||||
durationMs: 0,
|
||||
});
|
||||
const migrateLegacyConfig = vi.fn((raw: unknown) => ({
|
||||
config: raw as Record<string, unknown>,
|
||||
changes: ["Moved routing.allowFrom → channels.whatsapp.allowFrom."],
|
||||
}));
|
||||
|
||||
const runExec = vi.fn().mockResolvedValue({ stdout: "", stderr: "" });
|
||||
const runCommandWithTimeout = vi.fn().mockResolvedValue({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
killed: false,
|
||||
});
|
||||
|
||||
const ensureAuthProfileStore = vi
|
||||
.fn()
|
||||
.mockReturnValue({ version: 1, profiles: {} });
|
||||
|
||||
const legacyReadConfigFileSnapshot = vi.fn().mockResolvedValue({
|
||||
path: "/tmp/clawdis.json",
|
||||
exists: false,
|
||||
raw: null,
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
const createConfigIO = vi.fn(() => ({
|
||||
readConfigFileSnapshot: legacyReadConfigFileSnapshot,
|
||||
}));
|
||||
|
||||
const findLegacyGatewayServices = vi.fn().mockResolvedValue([]);
|
||||
const uninstallLegacyGatewayServices = vi.fn().mockResolvedValue([]);
|
||||
const findExtraGatewayServices = vi.fn().mockResolvedValue([]);
|
||||
const renderGatewayServiceCleanupHints = vi.fn().mockReturnValue(["cleanup"]);
|
||||
const resolveGatewayProgramArguments = vi.fn().mockResolvedValue({
|
||||
programArguments: ["node", "cli", "gateway", "--port", "18789"],
|
||||
});
|
||||
const serviceInstall = vi.fn().mockResolvedValue(undefined);
|
||||
const serviceIsLoaded = vi.fn().mockResolvedValue(false);
|
||||
const serviceStop = vi.fn().mockResolvedValue(undefined);
|
||||
const serviceRestart = vi.fn().mockResolvedValue(undefined);
|
||||
const serviceUninstall = vi.fn().mockResolvedValue(undefined);
|
||||
const callGateway = vi.fn().mockRejectedValue(new Error("gateway closed"));
|
||||
|
||||
vi.mock("@clack/prompts", () => ({
|
||||
confirm,
|
||||
intro: vi.fn(),
|
||||
note,
|
||||
outro: vi.fn(),
|
||||
select,
|
||||
}));
|
||||
|
||||
vi.mock("../agents/skills-status.js", () => ({
|
||||
buildWorkspaceSkillStatus: () => ({ skills: [] }),
|
||||
}));
|
||||
|
||||
vi.mock("../config/config.js", async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
CONFIG_PATH_CLAWDBOT: "/tmp/clawdbot.json",
|
||||
createConfigIO,
|
||||
readConfigFileSnapshot,
|
||||
writeConfigFile,
|
||||
migrateLegacyConfig,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../daemon/legacy.js", () => ({
|
||||
findLegacyGatewayServices,
|
||||
uninstallLegacyGatewayServices,
|
||||
}));
|
||||
|
||||
vi.mock("../daemon/inspect.js", () => ({
|
||||
findExtraGatewayServices,
|
||||
renderGatewayServiceCleanupHints,
|
||||
}));
|
||||
|
||||
vi.mock("../daemon/program-args.js", () => ({
|
||||
resolveGatewayProgramArguments,
|
||||
}));
|
||||
|
||||
vi.mock("../gateway/call.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../gateway/call.js")>();
|
||||
return {
|
||||
...actual,
|
||||
callGateway,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../process/exec.js", () => ({
|
||||
runExec,
|
||||
runCommandWithTimeout,
|
||||
}));
|
||||
|
||||
vi.mock("../infra/clawdbot-root.js", () => ({
|
||||
resolveClawdbotPackageRoot,
|
||||
}));
|
||||
|
||||
vi.mock("../infra/update-runner.js", () => ({
|
||||
runGatewayUpdate,
|
||||
}));
|
||||
|
||||
vi.mock("../agents/auth-profiles.js", async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
ensureAuthProfileStore,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../daemon/service.js", () => ({
|
||||
resolveGatewayService: () => ({
|
||||
label: "LaunchAgent",
|
||||
loadedText: "loaded",
|
||||
notLoadedText: "not loaded",
|
||||
install: serviceInstall,
|
||||
uninstall: serviceUninstall,
|
||||
stop: serviceStop,
|
||||
restart: serviceRestart,
|
||||
isLoaded: serviceIsLoaded,
|
||||
readCommand: vi.fn(),
|
||||
readRuntime: vi.fn().mockResolvedValue({ status: "running" }),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../telegram/pairing-store.js", () => ({
|
||||
readTelegramAllowFromStore: vi.fn().mockResolvedValue([]),
|
||||
}));
|
||||
|
||||
vi.mock("../pairing/pairing-store.js", () => ({
|
||||
readChannelAllowFromStore: vi.fn().mockResolvedValue([]),
|
||||
}));
|
||||
|
||||
vi.mock("../telegram/token.js", () => ({
|
||||
resolveTelegramToken: vi.fn(() => ({ token: "", source: "none" })),
|
||||
}));
|
||||
|
||||
vi.mock("../runtime.js", () => ({
|
||||
defaultRuntime: {
|
||||
log: () => {},
|
||||
error: () => {},
|
||||
exit: () => {
|
||||
throw new Error("exit");
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../utils.js", async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
resolveUserPath: (value: string) => value,
|
||||
sleep: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("./health.js", () => ({
|
||||
healthCommand: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock("./onboard-helpers.js", () => ({
|
||||
applyWizardMetadata: (cfg: Record<string, unknown>) => cfg,
|
||||
DEFAULT_WORKSPACE: "/tmp",
|
||||
guardCancel: (value: unknown) => value,
|
||||
printWizardHeader: vi.fn(),
|
||||
randomToken: vi.fn(() => "test-gateway-token"),
|
||||
}));
|
||||
|
||||
vi.mock("./doctor-state-migrations.js", () => ({
|
||||
detectLegacyStateMigrations: vi.fn().mockResolvedValue({
|
||||
targetAgentId: "main",
|
||||
targetMainKey: "main",
|
||||
stateDir: "/tmp/state",
|
||||
oauthDir: "/tmp/oauth",
|
||||
sessions: {
|
||||
legacyDir: "/tmp/state/sessions",
|
||||
legacyStorePath: "/tmp/state/sessions/sessions.json",
|
||||
targetDir: "/tmp/state/agents/main/sessions",
|
||||
targetStorePath: "/tmp/state/agents/main/sessions/sessions.json",
|
||||
hasLegacy: false,
|
||||
},
|
||||
agentDir: {
|
||||
legacyDir: "/tmp/state/agent",
|
||||
targetDir: "/tmp/state/agents/main/agent",
|
||||
hasLegacy: false,
|
||||
},
|
||||
whatsappAuth: {
|
||||
legacyDir: "/tmp/oauth",
|
||||
targetDir: "/tmp/oauth/whatsapp/default",
|
||||
hasLegacy: false,
|
||||
},
|
||||
preview: [],
|
||||
}),
|
||||
runLegacyStateMigrations: vi.fn().mockResolvedValue({
|
||||
changes: [],
|
||||
warnings: [],
|
||||
}),
|
||||
}));
|
||||
|
||||
describe("doctor command", () => {
|
||||
it(
|
||||
"migrates routing.allowFrom to channels.whatsapp.allowFrom",
|
||||
{ timeout: 30_000 },
|
||||
async () => {
|
||||
readConfigFileSnapshot.mockResolvedValue({
|
||||
path: "/tmp/clawdbot.json",
|
||||
exists: true,
|
||||
raw: "{}",
|
||||
parsed: { routing: { allowFrom: ["+15555550123"] } },
|
||||
valid: false,
|
||||
config: {},
|
||||
issues: [
|
||||
{
|
||||
path: "routing.allowFrom",
|
||||
message: "legacy",
|
||||
},
|
||||
],
|
||||
legacyIssues: [
|
||||
{
|
||||
path: "routing.allowFrom",
|
||||
message: "legacy",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const { doctorCommand } = await import("./doctor.js");
|
||||
const runtime = {
|
||||
log: vi.fn(),
|
||||
error: vi.fn(),
|
||||
exit: vi.fn(),
|
||||
};
|
||||
|
||||
migrateLegacyConfig.mockReturnValue({
|
||||
config: { channels: { whatsapp: { allowFrom: ["+15555550123"] } } },
|
||||
changes: ["Moved routing.allowFrom → channels.whatsapp.allowFrom."],
|
||||
});
|
||||
|
||||
await doctorCommand(runtime, { nonInteractive: true });
|
||||
|
||||
expect(writeConfigFile).toHaveBeenCalledTimes(1);
|
||||
const written = writeConfigFile.mock.calls[0]?.[0] as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
expect((written.channels as Record<string, unknown>)?.whatsapp).toEqual({
|
||||
allowFrom: ["+15555550123"],
|
||||
});
|
||||
expect(written.routing).toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
it("migrates legacy Clawdis services", async () => {
|
||||
readConfigFileSnapshot.mockResolvedValue({
|
||||
path: "/tmp/clawdbot.json",
|
||||
exists: true,
|
||||
raw: "{}",
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
|
||||
findLegacyGatewayServices.mockResolvedValueOnce([
|
||||
{
|
||||
platform: "darwin",
|
||||
label: "com.clawdis.gateway",
|
||||
detail: "loaded",
|
||||
},
|
||||
]);
|
||||
serviceIsLoaded.mockResolvedValueOnce(false);
|
||||
serviceInstall.mockClear();
|
||||
|
||||
const { doctorCommand } = await import("./doctor.js");
|
||||
const runtime = {
|
||||
log: vi.fn(),
|
||||
error: vi.fn(),
|
||||
exit: vi.fn(),
|
||||
};
|
||||
|
||||
await doctorCommand(runtime);
|
||||
|
||||
expect(uninstallLegacyGatewayServices).toHaveBeenCalledTimes(1);
|
||||
expect(serviceInstall).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("offers to update first for git checkouts", async () => {
|
||||
delete process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
|
||||
|
||||
const root = "/tmp/clawdbot";
|
||||
resolveClawdbotPackageRoot.mockResolvedValueOnce(root);
|
||||
runCommandWithTimeout.mockResolvedValueOnce({
|
||||
stdout: `${root}\n`,
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
killed: false,
|
||||
});
|
||||
runGatewayUpdate.mockResolvedValueOnce({
|
||||
status: "ok",
|
||||
mode: "git",
|
||||
root,
|
||||
steps: [],
|
||||
durationMs: 1,
|
||||
});
|
||||
|
||||
readConfigFileSnapshot.mockResolvedValue({
|
||||
path: "/tmp/clawdbot.json",
|
||||
exists: true,
|
||||
raw: "{}",
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
|
||||
const { doctorCommand } = await import("./doctor.js");
|
||||
const runtime = {
|
||||
log: vi.fn(),
|
||||
error: vi.fn(),
|
||||
exit: vi.fn(),
|
||||
};
|
||||
|
||||
await doctorCommand(runtime);
|
||||
|
||||
expect(runGatewayUpdate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ cwd: root }),
|
||||
);
|
||||
expect(readConfigFileSnapshot).not.toHaveBeenCalled();
|
||||
expect(
|
||||
note.mock.calls.some(
|
||||
([, title]) => typeof title === "string" && title === "Update result",
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
454
src/commands/doctor.part-2.test.ts
Normal file
454
src/commands/doctor.part-2.test.ts
Normal file
@@ -0,0 +1,454 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
let originalIsTTY: boolean | undefined;
|
||||
let originalStateDir: string | undefined;
|
||||
let originalUpdateInProgress: string | undefined;
|
||||
let tempStateDir: string | undefined;
|
||||
|
||||
function setStdinTty(value: boolean | undefined) {
|
||||
try {
|
||||
Object.defineProperty(process.stdin, "isTTY", {
|
||||
value,
|
||||
configurable: true,
|
||||
});
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
confirm.mockReset().mockResolvedValue(true);
|
||||
select.mockReset().mockResolvedValue("node");
|
||||
note.mockClear();
|
||||
|
||||
readConfigFileSnapshot.mockReset();
|
||||
writeConfigFile.mockReset().mockResolvedValue(undefined);
|
||||
resolveClawdbotPackageRoot.mockReset().mockResolvedValue(null);
|
||||
runGatewayUpdate.mockReset().mockResolvedValue({
|
||||
status: "skipped",
|
||||
mode: "unknown",
|
||||
steps: [],
|
||||
durationMs: 0,
|
||||
});
|
||||
legacyReadConfigFileSnapshot.mockReset().mockResolvedValue({
|
||||
path: "/tmp/clawdis.json",
|
||||
exists: false,
|
||||
raw: null,
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
createConfigIO.mockReset().mockImplementation(() => ({
|
||||
readConfigFileSnapshot: legacyReadConfigFileSnapshot,
|
||||
}));
|
||||
runExec.mockReset().mockResolvedValue({ stdout: "", stderr: "" });
|
||||
runCommandWithTimeout.mockReset().mockResolvedValue({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
killed: false,
|
||||
});
|
||||
ensureAuthProfileStore
|
||||
.mockReset()
|
||||
.mockReturnValue({ version: 1, profiles: {} });
|
||||
migrateLegacyConfig.mockReset().mockImplementation((raw: unknown) => ({
|
||||
config: raw as Record<string, unknown>,
|
||||
changes: ["Moved routing.allowFrom → channels.whatsapp.allowFrom."],
|
||||
}));
|
||||
findLegacyGatewayServices.mockReset().mockResolvedValue([]);
|
||||
uninstallLegacyGatewayServices.mockReset().mockResolvedValue([]);
|
||||
findExtraGatewayServices.mockReset().mockResolvedValue([]);
|
||||
renderGatewayServiceCleanupHints.mockReset().mockReturnValue(["cleanup"]);
|
||||
resolveGatewayProgramArguments.mockReset().mockResolvedValue({
|
||||
programArguments: ["node", "cli", "gateway", "--port", "18789"],
|
||||
});
|
||||
serviceInstall.mockReset().mockResolvedValue(undefined);
|
||||
serviceIsLoaded.mockReset().mockResolvedValue(false);
|
||||
serviceStop.mockReset().mockResolvedValue(undefined);
|
||||
serviceRestart.mockReset().mockResolvedValue(undefined);
|
||||
serviceUninstall.mockReset().mockResolvedValue(undefined);
|
||||
callGateway.mockReset().mockRejectedValue(new Error("gateway closed"));
|
||||
|
||||
originalIsTTY = process.stdin.isTTY;
|
||||
setStdinTty(true);
|
||||
originalStateDir = process.env.CLAWDBOT_STATE_DIR;
|
||||
originalUpdateInProgress = process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
|
||||
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = "1";
|
||||
tempStateDir = fs.mkdtempSync(
|
||||
path.join(os.tmpdir(), "clawdbot-doctor-state-"),
|
||||
);
|
||||
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
|
||||
fs.mkdirSync(path.join(tempStateDir, "agents", "main", "sessions"), {
|
||||
recursive: true,
|
||||
});
|
||||
fs.mkdirSync(path.join(tempStateDir, "credentials"), { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setStdinTty(originalIsTTY);
|
||||
if (originalStateDir === undefined) {
|
||||
delete process.env.CLAWDBOT_STATE_DIR;
|
||||
} else {
|
||||
process.env.CLAWDBOT_STATE_DIR = originalStateDir;
|
||||
}
|
||||
if (originalUpdateInProgress === undefined) {
|
||||
delete process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
|
||||
} else {
|
||||
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = originalUpdateInProgress;
|
||||
}
|
||||
if (tempStateDir) {
|
||||
fs.rmSync(tempStateDir, { recursive: true, force: true });
|
||||
tempStateDir = undefined;
|
||||
}
|
||||
});
|
||||
|
||||
const readConfigFileSnapshot = vi.fn();
|
||||
const confirm = vi.fn().mockResolvedValue(true);
|
||||
const select = vi.fn().mockResolvedValue("node");
|
||||
const note = vi.fn();
|
||||
const writeConfigFile = vi.fn().mockResolvedValue(undefined);
|
||||
const resolveClawdbotPackageRoot = vi.fn().mockResolvedValue(null);
|
||||
const runGatewayUpdate = vi.fn().mockResolvedValue({
|
||||
status: "skipped",
|
||||
mode: "unknown",
|
||||
steps: [],
|
||||
durationMs: 0,
|
||||
});
|
||||
const migrateLegacyConfig = vi.fn((raw: unknown) => ({
|
||||
config: raw as Record<string, unknown>,
|
||||
changes: ["Moved routing.allowFrom → channels.whatsapp.allowFrom."],
|
||||
}));
|
||||
|
||||
const runExec = vi.fn().mockResolvedValue({ stdout: "", stderr: "" });
|
||||
const runCommandWithTimeout = vi.fn().mockResolvedValue({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
killed: false,
|
||||
});
|
||||
|
||||
const ensureAuthProfileStore = vi
|
||||
.fn()
|
||||
.mockReturnValue({ version: 1, profiles: {} });
|
||||
|
||||
const legacyReadConfigFileSnapshot = vi.fn().mockResolvedValue({
|
||||
path: "/tmp/clawdis.json",
|
||||
exists: false,
|
||||
raw: null,
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
const createConfigIO = vi.fn(() => ({
|
||||
readConfigFileSnapshot: legacyReadConfigFileSnapshot,
|
||||
}));
|
||||
|
||||
const findLegacyGatewayServices = vi.fn().mockResolvedValue([]);
|
||||
const uninstallLegacyGatewayServices = vi.fn().mockResolvedValue([]);
|
||||
const findExtraGatewayServices = vi.fn().mockResolvedValue([]);
|
||||
const renderGatewayServiceCleanupHints = vi.fn().mockReturnValue(["cleanup"]);
|
||||
const resolveGatewayProgramArguments = vi.fn().mockResolvedValue({
|
||||
programArguments: ["node", "cli", "gateway", "--port", "18789"],
|
||||
});
|
||||
const serviceInstall = vi.fn().mockResolvedValue(undefined);
|
||||
const serviceIsLoaded = vi.fn().mockResolvedValue(false);
|
||||
const serviceStop = vi.fn().mockResolvedValue(undefined);
|
||||
const serviceRestart = vi.fn().mockResolvedValue(undefined);
|
||||
const serviceUninstall = vi.fn().mockResolvedValue(undefined);
|
||||
const callGateway = vi.fn().mockRejectedValue(new Error("gateway closed"));
|
||||
|
||||
vi.mock("@clack/prompts", () => ({
|
||||
confirm,
|
||||
intro: vi.fn(),
|
||||
note,
|
||||
outro: vi.fn(),
|
||||
select,
|
||||
}));
|
||||
|
||||
vi.mock("../agents/skills-status.js", () => ({
|
||||
buildWorkspaceSkillStatus: () => ({ skills: [] }),
|
||||
}));
|
||||
|
||||
vi.mock("../config/config.js", async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
CONFIG_PATH_CLAWDBOT: "/tmp/clawdbot.json",
|
||||
createConfigIO,
|
||||
readConfigFileSnapshot,
|
||||
writeConfigFile,
|
||||
migrateLegacyConfig,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../daemon/legacy.js", () => ({
|
||||
findLegacyGatewayServices,
|
||||
uninstallLegacyGatewayServices,
|
||||
}));
|
||||
|
||||
vi.mock("../daemon/inspect.js", () => ({
|
||||
findExtraGatewayServices,
|
||||
renderGatewayServiceCleanupHints,
|
||||
}));
|
||||
|
||||
vi.mock("../daemon/program-args.js", () => ({
|
||||
resolveGatewayProgramArguments,
|
||||
}));
|
||||
|
||||
vi.mock("../gateway/call.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../gateway/call.js")>();
|
||||
return {
|
||||
...actual,
|
||||
callGateway,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../process/exec.js", () => ({
|
||||
runExec,
|
||||
runCommandWithTimeout,
|
||||
}));
|
||||
|
||||
vi.mock("../infra/clawdbot-root.js", () => ({
|
||||
resolveClawdbotPackageRoot,
|
||||
}));
|
||||
|
||||
vi.mock("../infra/update-runner.js", () => ({
|
||||
runGatewayUpdate,
|
||||
}));
|
||||
|
||||
vi.mock("../agents/auth-profiles.js", async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
ensureAuthProfileStore,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../daemon/service.js", () => ({
|
||||
resolveGatewayService: () => ({
|
||||
label: "LaunchAgent",
|
||||
loadedText: "loaded",
|
||||
notLoadedText: "not loaded",
|
||||
install: serviceInstall,
|
||||
uninstall: serviceUninstall,
|
||||
stop: serviceStop,
|
||||
restart: serviceRestart,
|
||||
isLoaded: serviceIsLoaded,
|
||||
readCommand: vi.fn(),
|
||||
readRuntime: vi.fn().mockResolvedValue({ status: "running" }),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../telegram/pairing-store.js", () => ({
|
||||
readTelegramAllowFromStore: vi.fn().mockResolvedValue([]),
|
||||
}));
|
||||
|
||||
vi.mock("../pairing/pairing-store.js", () => ({
|
||||
readChannelAllowFromStore: vi.fn().mockResolvedValue([]),
|
||||
}));
|
||||
|
||||
vi.mock("../telegram/token.js", () => ({
|
||||
resolveTelegramToken: vi.fn(() => ({ token: "", source: "none" })),
|
||||
}));
|
||||
|
||||
vi.mock("../runtime.js", () => ({
|
||||
defaultRuntime: {
|
||||
log: () => {},
|
||||
error: () => {},
|
||||
exit: () => {
|
||||
throw new Error("exit");
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../utils.js", async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
resolveUserPath: (value: string) => value,
|
||||
sleep: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("./health.js", () => ({
|
||||
healthCommand: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock("./onboard-helpers.js", () => ({
|
||||
applyWizardMetadata: (cfg: Record<string, unknown>) => cfg,
|
||||
DEFAULT_WORKSPACE: "/tmp",
|
||||
guardCancel: (value: unknown) => value,
|
||||
printWizardHeader: vi.fn(),
|
||||
randomToken: vi.fn(() => "test-gateway-token"),
|
||||
}));
|
||||
|
||||
vi.mock("./doctor-state-migrations.js", () => ({
|
||||
detectLegacyStateMigrations: vi.fn().mockResolvedValue({
|
||||
targetAgentId: "main",
|
||||
targetMainKey: "main",
|
||||
stateDir: "/tmp/state",
|
||||
oauthDir: "/tmp/oauth",
|
||||
sessions: {
|
||||
legacyDir: "/tmp/state/sessions",
|
||||
legacyStorePath: "/tmp/state/sessions/sessions.json",
|
||||
targetDir: "/tmp/state/agents/main/sessions",
|
||||
targetStorePath: "/tmp/state/agents/main/sessions/sessions.json",
|
||||
hasLegacy: false,
|
||||
},
|
||||
agentDir: {
|
||||
legacyDir: "/tmp/state/agent",
|
||||
targetDir: "/tmp/state/agents/main/agent",
|
||||
hasLegacy: false,
|
||||
},
|
||||
whatsappAuth: {
|
||||
legacyDir: "/tmp/oauth",
|
||||
targetDir: "/tmp/oauth/whatsapp/default",
|
||||
hasLegacy: false,
|
||||
},
|
||||
preview: [],
|
||||
}),
|
||||
runLegacyStateMigrations: vi.fn().mockResolvedValue({
|
||||
changes: [],
|
||||
warnings: [],
|
||||
}),
|
||||
}));
|
||||
|
||||
describe("doctor command", () => {
|
||||
it("migrates legacy config file", async () => {
|
||||
readConfigFileSnapshot
|
||||
.mockResolvedValueOnce({
|
||||
path: "/tmp/clawdbot.json",
|
||||
exists: false,
|
||||
raw: null,
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
path: "/tmp/clawdbot.json",
|
||||
exists: true,
|
||||
raw: "{}",
|
||||
parsed: {
|
||||
gateway: { mode: "local", bind: "loopback" },
|
||||
agents: {
|
||||
defaults: {
|
||||
workspace: "/Users/steipete/clawd",
|
||||
sandbox: {
|
||||
workspaceRoot: "/Users/steipete/clawd/sandboxes",
|
||||
docker: {
|
||||
image: "clawdbot-sandbox",
|
||||
containerPrefix: "clawdbot-sbx",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
valid: true,
|
||||
config: {
|
||||
gateway: { mode: "local", bind: "loopback" },
|
||||
agents: {
|
||||
defaults: {
|
||||
workspace: "/Users/steipete/clawd",
|
||||
sandbox: {
|
||||
workspaceRoot: "/Users/steipete/clawd/sandboxes",
|
||||
docker: {
|
||||
image: "clawdbot-sandbox",
|
||||
containerPrefix: "clawdbot-sbx",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
|
||||
legacyReadConfigFileSnapshot.mockResolvedValueOnce({
|
||||
path: "/Users/steipete/.clawdis/clawdis.json",
|
||||
exists: true,
|
||||
raw: "{}",
|
||||
parsed: {
|
||||
gateway: { mode: "local", bind: "loopback" },
|
||||
agent: {
|
||||
workspace: "/Users/steipete/clawd",
|
||||
sandbox: {
|
||||
workspaceRoot: "/Users/steipete/clawd/sandboxes",
|
||||
docker: {
|
||||
image: "clawdis-sandbox",
|
||||
containerPrefix: "clawdis-sbx",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
valid: true,
|
||||
config: {
|
||||
gateway: { mode: "local", bind: "loopback" },
|
||||
agent: {
|
||||
workspace: "/Users/steipete/clawd",
|
||||
sandbox: {
|
||||
workspaceRoot: "/Users/steipete/clawd/sandboxes",
|
||||
docker: {
|
||||
image: "clawdis-sandbox",
|
||||
containerPrefix: "clawdis-sbx",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
|
||||
migrateLegacyConfig.mockReturnValueOnce({
|
||||
config: {
|
||||
gateway: { mode: "local", bind: "loopback" },
|
||||
agents: {
|
||||
defaults: {
|
||||
workspace: "/Users/steipete/clawd",
|
||||
sandbox: {
|
||||
workspaceRoot: "/Users/steipete/clawd/sandboxes",
|
||||
docker: {
|
||||
image: "clawdis-sandbox",
|
||||
containerPrefix: "clawdis-sbx",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
changes: [],
|
||||
});
|
||||
|
||||
const { doctorCommand } = await import("./doctor.js");
|
||||
const runtime = {
|
||||
log: vi.fn(),
|
||||
error: vi.fn(),
|
||||
exit: vi.fn(),
|
||||
};
|
||||
|
||||
await doctorCommand(runtime);
|
||||
|
||||
const written = writeConfigFile.mock.calls.at(-1)?.[0] as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
const agents = written.agents as Record<string, unknown>;
|
||||
const defaults = agents.defaults as Record<string, unknown>;
|
||||
const sandbox = defaults.sandbox as Record<string, unknown>;
|
||||
const docker = sandbox.docker as Record<string, unknown>;
|
||||
|
||||
expect(defaults.workspace).toBe("/Users/steipete/clawd");
|
||||
expect(sandbox.workspaceRoot).toBe("/Users/steipete/clawd/sandboxes");
|
||||
expect(docker.image).toBe("clawdbot-sandbox");
|
||||
expect(docker.containerPrefix).toBe("clawdbot-sbx");
|
||||
}, 20_000);
|
||||
});
|
||||
435
src/commands/doctor.part-3.test.ts
Normal file
435
src/commands/doctor.part-3.test.ts
Normal file
@@ -0,0 +1,435 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
let originalIsTTY: boolean | undefined;
|
||||
let originalStateDir: string | undefined;
|
||||
let originalUpdateInProgress: string | undefined;
|
||||
let tempStateDir: string | undefined;
|
||||
|
||||
function setStdinTty(value: boolean | undefined) {
|
||||
try {
|
||||
Object.defineProperty(process.stdin, "isTTY", {
|
||||
value,
|
||||
configurable: true,
|
||||
});
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
confirm.mockReset().mockResolvedValue(true);
|
||||
select.mockReset().mockResolvedValue("node");
|
||||
note.mockClear();
|
||||
|
||||
readConfigFileSnapshot.mockReset();
|
||||
writeConfigFile.mockReset().mockResolvedValue(undefined);
|
||||
resolveClawdbotPackageRoot.mockReset().mockResolvedValue(null);
|
||||
runGatewayUpdate.mockReset().mockResolvedValue({
|
||||
status: "skipped",
|
||||
mode: "unknown",
|
||||
steps: [],
|
||||
durationMs: 0,
|
||||
});
|
||||
legacyReadConfigFileSnapshot.mockReset().mockResolvedValue({
|
||||
path: "/tmp/clawdis.json",
|
||||
exists: false,
|
||||
raw: null,
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
createConfigIO.mockReset().mockImplementation(() => ({
|
||||
readConfigFileSnapshot: legacyReadConfigFileSnapshot,
|
||||
}));
|
||||
runExec.mockReset().mockResolvedValue({ stdout: "", stderr: "" });
|
||||
runCommandWithTimeout.mockReset().mockResolvedValue({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
killed: false,
|
||||
});
|
||||
ensureAuthProfileStore
|
||||
.mockReset()
|
||||
.mockReturnValue({ version: 1, profiles: {} });
|
||||
migrateLegacyConfig.mockReset().mockImplementation((raw: unknown) => ({
|
||||
config: raw as Record<string, unknown>,
|
||||
changes: ["Moved routing.allowFrom → channels.whatsapp.allowFrom."],
|
||||
}));
|
||||
findLegacyGatewayServices.mockReset().mockResolvedValue([]);
|
||||
uninstallLegacyGatewayServices.mockReset().mockResolvedValue([]);
|
||||
findExtraGatewayServices.mockReset().mockResolvedValue([]);
|
||||
renderGatewayServiceCleanupHints.mockReset().mockReturnValue(["cleanup"]);
|
||||
resolveGatewayProgramArguments.mockReset().mockResolvedValue({
|
||||
programArguments: ["node", "cli", "gateway", "--port", "18789"],
|
||||
});
|
||||
serviceInstall.mockReset().mockResolvedValue(undefined);
|
||||
serviceIsLoaded.mockReset().mockResolvedValue(false);
|
||||
serviceStop.mockReset().mockResolvedValue(undefined);
|
||||
serviceRestart.mockReset().mockResolvedValue(undefined);
|
||||
serviceUninstall.mockReset().mockResolvedValue(undefined);
|
||||
callGateway.mockReset().mockRejectedValue(new Error("gateway closed"));
|
||||
|
||||
originalIsTTY = process.stdin.isTTY;
|
||||
setStdinTty(true);
|
||||
originalStateDir = process.env.CLAWDBOT_STATE_DIR;
|
||||
originalUpdateInProgress = process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
|
||||
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = "1";
|
||||
tempStateDir = fs.mkdtempSync(
|
||||
path.join(os.tmpdir(), "clawdbot-doctor-state-"),
|
||||
);
|
||||
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
|
||||
fs.mkdirSync(path.join(tempStateDir, "agents", "main", "sessions"), {
|
||||
recursive: true,
|
||||
});
|
||||
fs.mkdirSync(path.join(tempStateDir, "credentials"), { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setStdinTty(originalIsTTY);
|
||||
if (originalStateDir === undefined) {
|
||||
delete process.env.CLAWDBOT_STATE_DIR;
|
||||
} else {
|
||||
process.env.CLAWDBOT_STATE_DIR = originalStateDir;
|
||||
}
|
||||
if (originalUpdateInProgress === undefined) {
|
||||
delete process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
|
||||
} else {
|
||||
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = originalUpdateInProgress;
|
||||
}
|
||||
if (tempStateDir) {
|
||||
fs.rmSync(tempStateDir, { recursive: true, force: true });
|
||||
tempStateDir = undefined;
|
||||
}
|
||||
});
|
||||
|
||||
const readConfigFileSnapshot = vi.fn();
|
||||
const confirm = vi.fn().mockResolvedValue(true);
|
||||
const select = vi.fn().mockResolvedValue("node");
|
||||
const note = vi.fn();
|
||||
const writeConfigFile = vi.fn().mockResolvedValue(undefined);
|
||||
const resolveClawdbotPackageRoot = vi.fn().mockResolvedValue(null);
|
||||
const runGatewayUpdate = vi.fn().mockResolvedValue({
|
||||
status: "skipped",
|
||||
mode: "unknown",
|
||||
steps: [],
|
||||
durationMs: 0,
|
||||
});
|
||||
const migrateLegacyConfig = vi.fn((raw: unknown) => ({
|
||||
config: raw as Record<string, unknown>,
|
||||
changes: ["Moved routing.allowFrom → channels.whatsapp.allowFrom."],
|
||||
}));
|
||||
|
||||
const runExec = vi.fn().mockResolvedValue({ stdout: "", stderr: "" });
|
||||
const runCommandWithTimeout = vi.fn().mockResolvedValue({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
killed: false,
|
||||
});
|
||||
|
||||
const ensureAuthProfileStore = vi
|
||||
.fn()
|
||||
.mockReturnValue({ version: 1, profiles: {} });
|
||||
|
||||
const legacyReadConfigFileSnapshot = vi.fn().mockResolvedValue({
|
||||
path: "/tmp/clawdis.json",
|
||||
exists: false,
|
||||
raw: null,
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
const createConfigIO = vi.fn(() => ({
|
||||
readConfigFileSnapshot: legacyReadConfigFileSnapshot,
|
||||
}));
|
||||
|
||||
const findLegacyGatewayServices = vi.fn().mockResolvedValue([]);
|
||||
const uninstallLegacyGatewayServices = vi.fn().mockResolvedValue([]);
|
||||
const findExtraGatewayServices = vi.fn().mockResolvedValue([]);
|
||||
const renderGatewayServiceCleanupHints = vi.fn().mockReturnValue(["cleanup"]);
|
||||
const resolveGatewayProgramArguments = vi.fn().mockResolvedValue({
|
||||
programArguments: ["node", "cli", "gateway", "--port", "18789"],
|
||||
});
|
||||
const serviceInstall = vi.fn().mockResolvedValue(undefined);
|
||||
const serviceIsLoaded = vi.fn().mockResolvedValue(false);
|
||||
const serviceStop = vi.fn().mockResolvedValue(undefined);
|
||||
const serviceRestart = vi.fn().mockResolvedValue(undefined);
|
||||
const serviceUninstall = vi.fn().mockResolvedValue(undefined);
|
||||
const callGateway = vi.fn().mockRejectedValue(new Error("gateway closed"));
|
||||
|
||||
vi.mock("@clack/prompts", () => ({
|
||||
confirm,
|
||||
intro: vi.fn(),
|
||||
note,
|
||||
outro: vi.fn(),
|
||||
select,
|
||||
}));
|
||||
|
||||
vi.mock("../agents/skills-status.js", () => ({
|
||||
buildWorkspaceSkillStatus: () => ({ skills: [] }),
|
||||
}));
|
||||
|
||||
vi.mock("../config/config.js", async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
CONFIG_PATH_CLAWDBOT: "/tmp/clawdbot.json",
|
||||
createConfigIO,
|
||||
readConfigFileSnapshot,
|
||||
writeConfigFile,
|
||||
migrateLegacyConfig,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../daemon/legacy.js", () => ({
|
||||
findLegacyGatewayServices,
|
||||
uninstallLegacyGatewayServices,
|
||||
}));
|
||||
|
||||
vi.mock("../daemon/inspect.js", () => ({
|
||||
findExtraGatewayServices,
|
||||
renderGatewayServiceCleanupHints,
|
||||
}));
|
||||
|
||||
vi.mock("../daemon/program-args.js", () => ({
|
||||
resolveGatewayProgramArguments,
|
||||
}));
|
||||
|
||||
vi.mock("../gateway/call.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../gateway/call.js")>();
|
||||
return {
|
||||
...actual,
|
||||
callGateway,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../process/exec.js", () => ({
|
||||
runExec,
|
||||
runCommandWithTimeout,
|
||||
}));
|
||||
|
||||
vi.mock("../infra/clawdbot-root.js", () => ({
|
||||
resolveClawdbotPackageRoot,
|
||||
}));
|
||||
|
||||
vi.mock("../infra/update-runner.js", () => ({
|
||||
runGatewayUpdate,
|
||||
}));
|
||||
|
||||
vi.mock("../agents/auth-profiles.js", async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
ensureAuthProfileStore,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../daemon/service.js", () => ({
|
||||
resolveGatewayService: () => ({
|
||||
label: "LaunchAgent",
|
||||
loadedText: "loaded",
|
||||
notLoadedText: "not loaded",
|
||||
install: serviceInstall,
|
||||
uninstall: serviceUninstall,
|
||||
stop: serviceStop,
|
||||
restart: serviceRestart,
|
||||
isLoaded: serviceIsLoaded,
|
||||
readCommand: vi.fn(),
|
||||
readRuntime: vi.fn().mockResolvedValue({ status: "running" }),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../telegram/pairing-store.js", () => ({
|
||||
readTelegramAllowFromStore: vi.fn().mockResolvedValue([]),
|
||||
}));
|
||||
|
||||
vi.mock("../pairing/pairing-store.js", () => ({
|
||||
readChannelAllowFromStore: vi.fn().mockResolvedValue([]),
|
||||
}));
|
||||
|
||||
vi.mock("../telegram/token.js", () => ({
|
||||
resolveTelegramToken: vi.fn(() => ({ token: "", source: "none" })),
|
||||
}));
|
||||
|
||||
vi.mock("../runtime.js", () => ({
|
||||
defaultRuntime: {
|
||||
log: () => {},
|
||||
error: () => {},
|
||||
exit: () => {
|
||||
throw new Error("exit");
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../utils.js", async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
resolveUserPath: (value: string) => value,
|
||||
sleep: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("./health.js", () => ({
|
||||
healthCommand: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock("./onboard-helpers.js", () => ({
|
||||
applyWizardMetadata: (cfg: Record<string, unknown>) => cfg,
|
||||
DEFAULT_WORKSPACE: "/tmp",
|
||||
guardCancel: (value: unknown) => value,
|
||||
printWizardHeader: vi.fn(),
|
||||
randomToken: vi.fn(() => "test-gateway-token"),
|
||||
}));
|
||||
|
||||
vi.mock("./doctor-state-migrations.js", () => ({
|
||||
detectLegacyStateMigrations: vi.fn().mockResolvedValue({
|
||||
targetAgentId: "main",
|
||||
targetMainKey: "main",
|
||||
stateDir: "/tmp/state",
|
||||
oauthDir: "/tmp/oauth",
|
||||
sessions: {
|
||||
legacyDir: "/tmp/state/sessions",
|
||||
legacyStorePath: "/tmp/state/sessions/sessions.json",
|
||||
targetDir: "/tmp/state/agents/main/sessions",
|
||||
targetStorePath: "/tmp/state/agents/main/sessions/sessions.json",
|
||||
hasLegacy: false,
|
||||
},
|
||||
agentDir: {
|
||||
legacyDir: "/tmp/state/agent",
|
||||
targetDir: "/tmp/state/agents/main/agent",
|
||||
hasLegacy: false,
|
||||
},
|
||||
whatsappAuth: {
|
||||
legacyDir: "/tmp/oauth",
|
||||
targetDir: "/tmp/oauth/whatsapp/default",
|
||||
hasLegacy: false,
|
||||
},
|
||||
preview: [],
|
||||
}),
|
||||
runLegacyStateMigrations: vi.fn().mockResolvedValue({
|
||||
changes: [],
|
||||
warnings: [],
|
||||
}),
|
||||
}));
|
||||
|
||||
describe("doctor command", () => {
|
||||
it("warns when per-agent sandbox docker/browser/prune overrides are ignored under shared scope", async () => {
|
||||
readConfigFileSnapshot.mockResolvedValue({
|
||||
path: "/tmp/clawdbot.json",
|
||||
exists: true,
|
||||
raw: "{}",
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {
|
||||
agents: {
|
||||
defaults: {
|
||||
sandbox: {
|
||||
mode: "all",
|
||||
scope: "shared",
|
||||
},
|
||||
},
|
||||
list: [
|
||||
{
|
||||
id: "work",
|
||||
workspace: "~/clawd-work",
|
||||
sandbox: {
|
||||
mode: "all",
|
||||
scope: "shared",
|
||||
docker: {
|
||||
setupCommand: "echo work",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
|
||||
note.mockClear();
|
||||
|
||||
const { doctorCommand } = await import("./doctor.js");
|
||||
const runtime = {
|
||||
log: vi.fn(),
|
||||
error: vi.fn(),
|
||||
exit: vi.fn(),
|
||||
};
|
||||
|
||||
await doctorCommand(runtime, { nonInteractive: true });
|
||||
|
||||
expect(
|
||||
note.mock.calls.some(([message, title]) => {
|
||||
if (title !== "Sandbox" || typeof message !== "string") return false;
|
||||
const normalized = message.replace(/\s+/g, " ").trim();
|
||||
return (
|
||||
normalized.includes('agents.list (id "work") sandbox docker') &&
|
||||
normalized.includes('scope resolves to "shared"')
|
||||
);
|
||||
}),
|
||||
).toBe(true);
|
||||
}, 10_000);
|
||||
|
||||
it("warns when legacy workspace directories exist", async () => {
|
||||
readConfigFileSnapshot.mockResolvedValue({
|
||||
path: "/tmp/clawdbot.json",
|
||||
exists: true,
|
||||
raw: "{}",
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {
|
||||
agents: { defaults: { workspace: "/Users/steipete/clawd" } },
|
||||
},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
|
||||
note.mockClear();
|
||||
const homedirSpy = vi
|
||||
.spyOn(os, "homedir")
|
||||
.mockReturnValue("/Users/steipete");
|
||||
const realExists = fs.existsSync;
|
||||
const legacyPath = path.join("/Users/steipete", "clawdis");
|
||||
const legacyAgentsPath = path.join(legacyPath, "AGENTS.md");
|
||||
const existsSpy = vi.spyOn(fs, "existsSync").mockImplementation((value) => {
|
||||
if (
|
||||
value === "/Users/steipete/clawdis" ||
|
||||
value === legacyPath ||
|
||||
value === legacyAgentsPath
|
||||
)
|
||||
return true;
|
||||
return realExists(value as never);
|
||||
});
|
||||
|
||||
const { doctorCommand } = await import("./doctor.js");
|
||||
const runtime = {
|
||||
log: vi.fn(),
|
||||
error: vi.fn(),
|
||||
exit: vi.fn(),
|
||||
};
|
||||
|
||||
await doctorCommand(runtime, { nonInteractive: true });
|
||||
|
||||
expect(
|
||||
note.mock.calls.some(
|
||||
([message, title]) =>
|
||||
title === "Legacy workspace" &&
|
||||
typeof message === "string" &&
|
||||
message.includes("clawdis"),
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
homedirSpy.mockRestore();
|
||||
existsSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
466
src/commands/doctor.part-4.test.ts
Normal file
466
src/commands/doctor.part-4.test.ts
Normal file
@@ -0,0 +1,466 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
let originalIsTTY: boolean | undefined;
|
||||
let originalStateDir: string | undefined;
|
||||
let originalUpdateInProgress: string | undefined;
|
||||
let tempStateDir: string | undefined;
|
||||
|
||||
function setStdinTty(value: boolean | undefined) {
|
||||
try {
|
||||
Object.defineProperty(process.stdin, "isTTY", {
|
||||
value,
|
||||
configurable: true,
|
||||
});
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
confirm.mockReset().mockResolvedValue(true);
|
||||
select.mockReset().mockResolvedValue("node");
|
||||
note.mockClear();
|
||||
|
||||
readConfigFileSnapshot.mockReset();
|
||||
writeConfigFile.mockReset().mockResolvedValue(undefined);
|
||||
resolveClawdbotPackageRoot.mockReset().mockResolvedValue(null);
|
||||
runGatewayUpdate.mockReset().mockResolvedValue({
|
||||
status: "skipped",
|
||||
mode: "unknown",
|
||||
steps: [],
|
||||
durationMs: 0,
|
||||
});
|
||||
legacyReadConfigFileSnapshot.mockReset().mockResolvedValue({
|
||||
path: "/tmp/clawdis.json",
|
||||
exists: false,
|
||||
raw: null,
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
createConfigIO.mockReset().mockImplementation(() => ({
|
||||
readConfigFileSnapshot: legacyReadConfigFileSnapshot,
|
||||
}));
|
||||
runExec.mockReset().mockResolvedValue({ stdout: "", stderr: "" });
|
||||
runCommandWithTimeout.mockReset().mockResolvedValue({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
killed: false,
|
||||
});
|
||||
ensureAuthProfileStore
|
||||
.mockReset()
|
||||
.mockReturnValue({ version: 1, profiles: {} });
|
||||
migrateLegacyConfig.mockReset().mockImplementation((raw: unknown) => ({
|
||||
config: raw as Record<string, unknown>,
|
||||
changes: ["Moved routing.allowFrom → channels.whatsapp.allowFrom."],
|
||||
}));
|
||||
findLegacyGatewayServices.mockReset().mockResolvedValue([]);
|
||||
uninstallLegacyGatewayServices.mockReset().mockResolvedValue([]);
|
||||
findExtraGatewayServices.mockReset().mockResolvedValue([]);
|
||||
renderGatewayServiceCleanupHints.mockReset().mockReturnValue(["cleanup"]);
|
||||
resolveGatewayProgramArguments.mockReset().mockResolvedValue({
|
||||
programArguments: ["node", "cli", "gateway", "--port", "18789"],
|
||||
});
|
||||
serviceInstall.mockReset().mockResolvedValue(undefined);
|
||||
serviceIsLoaded.mockReset().mockResolvedValue(false);
|
||||
serviceStop.mockReset().mockResolvedValue(undefined);
|
||||
serviceRestart.mockReset().mockResolvedValue(undefined);
|
||||
serviceUninstall.mockReset().mockResolvedValue(undefined);
|
||||
callGateway.mockReset().mockRejectedValue(new Error("gateway closed"));
|
||||
|
||||
originalIsTTY = process.stdin.isTTY;
|
||||
setStdinTty(true);
|
||||
originalStateDir = process.env.CLAWDBOT_STATE_DIR;
|
||||
originalUpdateInProgress = process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
|
||||
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = "1";
|
||||
tempStateDir = fs.mkdtempSync(
|
||||
path.join(os.tmpdir(), "clawdbot-doctor-state-"),
|
||||
);
|
||||
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
|
||||
fs.mkdirSync(path.join(tempStateDir, "agents", "main", "sessions"), {
|
||||
recursive: true,
|
||||
});
|
||||
fs.mkdirSync(path.join(tempStateDir, "credentials"), { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setStdinTty(originalIsTTY);
|
||||
if (originalStateDir === undefined) {
|
||||
delete process.env.CLAWDBOT_STATE_DIR;
|
||||
} else {
|
||||
process.env.CLAWDBOT_STATE_DIR = originalStateDir;
|
||||
}
|
||||
if (originalUpdateInProgress === undefined) {
|
||||
delete process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
|
||||
} else {
|
||||
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = originalUpdateInProgress;
|
||||
}
|
||||
if (tempStateDir) {
|
||||
fs.rmSync(tempStateDir, { recursive: true, force: true });
|
||||
tempStateDir = undefined;
|
||||
}
|
||||
});
|
||||
|
||||
const readConfigFileSnapshot = vi.fn();
|
||||
const confirm = vi.fn().mockResolvedValue(true);
|
||||
const select = vi.fn().mockResolvedValue("node");
|
||||
const note = vi.fn();
|
||||
const writeConfigFile = vi.fn().mockResolvedValue(undefined);
|
||||
const resolveClawdbotPackageRoot = vi.fn().mockResolvedValue(null);
|
||||
const runGatewayUpdate = vi.fn().mockResolvedValue({
|
||||
status: "skipped",
|
||||
mode: "unknown",
|
||||
steps: [],
|
||||
durationMs: 0,
|
||||
});
|
||||
const migrateLegacyConfig = vi.fn((raw: unknown) => ({
|
||||
config: raw as Record<string, unknown>,
|
||||
changes: ["Moved routing.allowFrom → channels.whatsapp.allowFrom."],
|
||||
}));
|
||||
|
||||
const runExec = vi.fn().mockResolvedValue({ stdout: "", stderr: "" });
|
||||
const runCommandWithTimeout = vi.fn().mockResolvedValue({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
killed: false,
|
||||
});
|
||||
|
||||
const ensureAuthProfileStore = vi
|
||||
.fn()
|
||||
.mockReturnValue({ version: 1, profiles: {} });
|
||||
|
||||
const legacyReadConfigFileSnapshot = vi.fn().mockResolvedValue({
|
||||
path: "/tmp/clawdis.json",
|
||||
exists: false,
|
||||
raw: null,
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
const createConfigIO = vi.fn(() => ({
|
||||
readConfigFileSnapshot: legacyReadConfigFileSnapshot,
|
||||
}));
|
||||
|
||||
const findLegacyGatewayServices = vi.fn().mockResolvedValue([]);
|
||||
const uninstallLegacyGatewayServices = vi.fn().mockResolvedValue([]);
|
||||
const findExtraGatewayServices = vi.fn().mockResolvedValue([]);
|
||||
const renderGatewayServiceCleanupHints = vi.fn().mockReturnValue(["cleanup"]);
|
||||
const resolveGatewayProgramArguments = vi.fn().mockResolvedValue({
|
||||
programArguments: ["node", "cli", "gateway", "--port", "18789"],
|
||||
});
|
||||
const serviceInstall = vi.fn().mockResolvedValue(undefined);
|
||||
const serviceIsLoaded = vi.fn().mockResolvedValue(false);
|
||||
const serviceStop = vi.fn().mockResolvedValue(undefined);
|
||||
const serviceRestart = vi.fn().mockResolvedValue(undefined);
|
||||
const serviceUninstall = vi.fn().mockResolvedValue(undefined);
|
||||
const callGateway = vi.fn().mockRejectedValue(new Error("gateway closed"));
|
||||
|
||||
vi.mock("@clack/prompts", () => ({
|
||||
confirm,
|
||||
intro: vi.fn(),
|
||||
note,
|
||||
outro: vi.fn(),
|
||||
select,
|
||||
}));
|
||||
|
||||
vi.mock("../agents/skills-status.js", () => ({
|
||||
buildWorkspaceSkillStatus: () => ({ skills: [] }),
|
||||
}));
|
||||
|
||||
vi.mock("../config/config.js", async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
CONFIG_PATH_CLAWDBOT: "/tmp/clawdbot.json",
|
||||
createConfigIO,
|
||||
readConfigFileSnapshot,
|
||||
writeConfigFile,
|
||||
migrateLegacyConfig,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../daemon/legacy.js", () => ({
|
||||
findLegacyGatewayServices,
|
||||
uninstallLegacyGatewayServices,
|
||||
}));
|
||||
|
||||
vi.mock("../daemon/inspect.js", () => ({
|
||||
findExtraGatewayServices,
|
||||
renderGatewayServiceCleanupHints,
|
||||
}));
|
||||
|
||||
vi.mock("../daemon/program-args.js", () => ({
|
||||
resolveGatewayProgramArguments,
|
||||
}));
|
||||
|
||||
vi.mock("../gateway/call.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../gateway/call.js")>();
|
||||
return {
|
||||
...actual,
|
||||
callGateway,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../process/exec.js", () => ({
|
||||
runExec,
|
||||
runCommandWithTimeout,
|
||||
}));
|
||||
|
||||
vi.mock("../infra/clawdbot-root.js", () => ({
|
||||
resolveClawdbotPackageRoot,
|
||||
}));
|
||||
|
||||
vi.mock("../infra/update-runner.js", () => ({
|
||||
runGatewayUpdate,
|
||||
}));
|
||||
|
||||
vi.mock("../agents/auth-profiles.js", async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
ensureAuthProfileStore,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../daemon/service.js", () => ({
|
||||
resolveGatewayService: () => ({
|
||||
label: "LaunchAgent",
|
||||
loadedText: "loaded",
|
||||
notLoadedText: "not loaded",
|
||||
install: serviceInstall,
|
||||
uninstall: serviceUninstall,
|
||||
stop: serviceStop,
|
||||
restart: serviceRestart,
|
||||
isLoaded: serviceIsLoaded,
|
||||
readCommand: vi.fn(),
|
||||
readRuntime: vi.fn().mockResolvedValue({ status: "running" }),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../telegram/pairing-store.js", () => ({
|
||||
readTelegramAllowFromStore: vi.fn().mockResolvedValue([]),
|
||||
}));
|
||||
|
||||
vi.mock("../pairing/pairing-store.js", () => ({
|
||||
readChannelAllowFromStore: vi.fn().mockResolvedValue([]),
|
||||
}));
|
||||
|
||||
vi.mock("../telegram/token.js", () => ({
|
||||
resolveTelegramToken: vi.fn(() => ({ token: "", source: "none" })),
|
||||
}));
|
||||
|
||||
vi.mock("../runtime.js", () => ({
|
||||
defaultRuntime: {
|
||||
log: () => {},
|
||||
error: () => {},
|
||||
exit: () => {
|
||||
throw new Error("exit");
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../utils.js", async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
resolveUserPath: (value: string) => value,
|
||||
sleep: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("./health.js", () => ({
|
||||
healthCommand: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock("./onboard-helpers.js", () => ({
|
||||
applyWizardMetadata: (cfg: Record<string, unknown>) => cfg,
|
||||
DEFAULT_WORKSPACE: "/tmp",
|
||||
guardCancel: (value: unknown) => value,
|
||||
printWizardHeader: vi.fn(),
|
||||
randomToken: vi.fn(() => "test-gateway-token"),
|
||||
}));
|
||||
|
||||
vi.mock("./doctor-state-migrations.js", () => ({
|
||||
detectLegacyStateMigrations: vi.fn().mockResolvedValue({
|
||||
targetAgentId: "main",
|
||||
targetMainKey: "main",
|
||||
stateDir: "/tmp/state",
|
||||
oauthDir: "/tmp/oauth",
|
||||
sessions: {
|
||||
legacyDir: "/tmp/state/sessions",
|
||||
legacyStorePath: "/tmp/state/sessions/sessions.json",
|
||||
targetDir: "/tmp/state/agents/main/sessions",
|
||||
targetStorePath: "/tmp/state/agents/main/sessions/sessions.json",
|
||||
hasLegacy: false,
|
||||
},
|
||||
agentDir: {
|
||||
legacyDir: "/tmp/state/agent",
|
||||
targetDir: "/tmp/state/agents/main/agent",
|
||||
hasLegacy: false,
|
||||
},
|
||||
whatsappAuth: {
|
||||
legacyDir: "/tmp/oauth",
|
||||
targetDir: "/tmp/oauth/whatsapp/default",
|
||||
hasLegacy: false,
|
||||
},
|
||||
preview: [],
|
||||
}),
|
||||
runLegacyStateMigrations: vi.fn().mockResolvedValue({
|
||||
changes: [],
|
||||
warnings: [],
|
||||
}),
|
||||
}));
|
||||
|
||||
describe("doctor command", () => {
|
||||
it("falls back to legacy sandbox image when missing", async () => {
|
||||
readConfigFileSnapshot.mockResolvedValue({
|
||||
path: "/tmp/clawdbot.json",
|
||||
exists: true,
|
||||
raw: "{}",
|
||||
parsed: {
|
||||
agents: {
|
||||
defaults: {
|
||||
sandbox: {
|
||||
mode: "non-main",
|
||||
docker: {
|
||||
image: "clawdbot-sandbox-common:bookworm-slim",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
valid: true,
|
||||
config: {
|
||||
agents: {
|
||||
defaults: {
|
||||
sandbox: {
|
||||
mode: "non-main",
|
||||
docker: {
|
||||
image: "clawdbot-sandbox-common:bookworm-slim",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
|
||||
runExec.mockImplementation((command: string, args: string[]) => {
|
||||
if (command !== "docker") {
|
||||
return Promise.resolve({ stdout: "", stderr: "" });
|
||||
}
|
||||
if (args[0] === "version") {
|
||||
return Promise.resolve({ stdout: "1", stderr: "" });
|
||||
}
|
||||
if (args[0] === "image" && args[1] === "inspect") {
|
||||
const image = args[2];
|
||||
if (image === "clawdbot-sandbox-common:bookworm-slim") {
|
||||
return Promise.reject(new Error("missing"));
|
||||
}
|
||||
if (image === "clawdis-sandbox-common:bookworm-slim") {
|
||||
return Promise.resolve({ stdout: "ok", stderr: "" });
|
||||
}
|
||||
}
|
||||
return Promise.resolve({ stdout: "", stderr: "" });
|
||||
});
|
||||
|
||||
confirm
|
||||
.mockResolvedValueOnce(false) // skip gateway token prompt
|
||||
.mockResolvedValueOnce(false) // skip build
|
||||
.mockResolvedValueOnce(true); // accept legacy fallback
|
||||
|
||||
const { doctorCommand } = await import("./doctor.js");
|
||||
const runtime = {
|
||||
log: vi.fn(),
|
||||
error: vi.fn(),
|
||||
exit: vi.fn(),
|
||||
};
|
||||
|
||||
await doctorCommand(runtime);
|
||||
|
||||
const written = writeConfigFile.mock.calls.at(-1)?.[0] as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
const agents = written.agents as Record<string, unknown>;
|
||||
const defaults = agents.defaults as Record<string, unknown>;
|
||||
const sandbox = defaults.sandbox as Record<string, unknown>;
|
||||
const docker = sandbox.docker as Record<string, unknown>;
|
||||
|
||||
expect(docker.image).toBe("clawdis-sandbox-common:bookworm-slim");
|
||||
const defaultsCalls = runCommandWithTimeout.mock.calls.filter(
|
||||
([args]) => Array.isArray(args) && args[0] === "/usr/bin/defaults",
|
||||
);
|
||||
expect(defaultsCalls.length).toBe(runCommandWithTimeout.mock.calls.length);
|
||||
});
|
||||
|
||||
it("runs legacy state migrations in non-interactive mode without prompting", async () => {
|
||||
readConfigFileSnapshot.mockResolvedValue({
|
||||
path: "/tmp/clawdbot.json",
|
||||
exists: true,
|
||||
raw: "{}",
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
|
||||
const { doctorCommand } = await import("./doctor.js");
|
||||
const runtime = {
|
||||
log: vi.fn(),
|
||||
error: vi.fn(),
|
||||
exit: vi.fn(),
|
||||
};
|
||||
|
||||
const { detectLegacyStateMigrations, runLegacyStateMigrations } =
|
||||
await import("./doctor-state-migrations.js");
|
||||
detectLegacyStateMigrations.mockResolvedValueOnce({
|
||||
targetAgentId: "main",
|
||||
targetMainKey: "main",
|
||||
stateDir: "/tmp/state",
|
||||
oauthDir: "/tmp/oauth",
|
||||
sessions: {
|
||||
legacyDir: "/tmp/state/sessions",
|
||||
legacyStorePath: "/tmp/state/sessions/sessions.json",
|
||||
targetDir: "/tmp/state/agents/main/sessions",
|
||||
targetStorePath: "/tmp/state/agents/main/sessions/sessions.json",
|
||||
hasLegacy: true,
|
||||
},
|
||||
agentDir: {
|
||||
legacyDir: "/tmp/state/agent",
|
||||
targetDir: "/tmp/state/agents/main/agent",
|
||||
hasLegacy: false,
|
||||
},
|
||||
whatsappAuth: {
|
||||
legacyDir: "/tmp/oauth",
|
||||
targetDir: "/tmp/oauth/whatsapp/default",
|
||||
hasLegacy: false,
|
||||
},
|
||||
preview: ["- Legacy sessions detected"],
|
||||
});
|
||||
runLegacyStateMigrations.mockResolvedValueOnce({
|
||||
changes: ["migrated"],
|
||||
warnings: [],
|
||||
});
|
||||
|
||||
confirm.mockClear();
|
||||
|
||||
await doctorCommand(runtime, { nonInteractive: true });
|
||||
|
||||
expect(runLegacyStateMigrations).toHaveBeenCalledTimes(1);
|
||||
expect(confirm).not.toHaveBeenCalled();
|
||||
}, 20_000);
|
||||
});
|
||||
464
src/commands/doctor.part-5.test.ts
Normal file
464
src/commands/doctor.part-5.test.ts
Normal file
@@ -0,0 +1,464 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
let originalIsTTY: boolean | undefined;
|
||||
let originalStateDir: string | undefined;
|
||||
let originalUpdateInProgress: string | undefined;
|
||||
let tempStateDir: string | undefined;
|
||||
|
||||
function setStdinTty(value: boolean | undefined) {
|
||||
try {
|
||||
Object.defineProperty(process.stdin, "isTTY", {
|
||||
value,
|
||||
configurable: true,
|
||||
});
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
confirm.mockReset().mockResolvedValue(true);
|
||||
select.mockReset().mockResolvedValue("node");
|
||||
note.mockClear();
|
||||
|
||||
readConfigFileSnapshot.mockReset();
|
||||
writeConfigFile.mockReset().mockResolvedValue(undefined);
|
||||
resolveClawdbotPackageRoot.mockReset().mockResolvedValue(null);
|
||||
runGatewayUpdate.mockReset().mockResolvedValue({
|
||||
status: "skipped",
|
||||
mode: "unknown",
|
||||
steps: [],
|
||||
durationMs: 0,
|
||||
});
|
||||
legacyReadConfigFileSnapshot.mockReset().mockResolvedValue({
|
||||
path: "/tmp/clawdis.json",
|
||||
exists: false,
|
||||
raw: null,
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
createConfigIO.mockReset().mockImplementation(() => ({
|
||||
readConfigFileSnapshot: legacyReadConfigFileSnapshot,
|
||||
}));
|
||||
runExec.mockReset().mockResolvedValue({ stdout: "", stderr: "" });
|
||||
runCommandWithTimeout.mockReset().mockResolvedValue({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
killed: false,
|
||||
});
|
||||
ensureAuthProfileStore
|
||||
.mockReset()
|
||||
.mockReturnValue({ version: 1, profiles: {} });
|
||||
migrateLegacyConfig.mockReset().mockImplementation((raw: unknown) => ({
|
||||
config: raw as Record<string, unknown>,
|
||||
changes: ["Moved routing.allowFrom → channels.whatsapp.allowFrom."],
|
||||
}));
|
||||
findLegacyGatewayServices.mockReset().mockResolvedValue([]);
|
||||
uninstallLegacyGatewayServices.mockReset().mockResolvedValue([]);
|
||||
findExtraGatewayServices.mockReset().mockResolvedValue([]);
|
||||
renderGatewayServiceCleanupHints.mockReset().mockReturnValue(["cleanup"]);
|
||||
resolveGatewayProgramArguments.mockReset().mockResolvedValue({
|
||||
programArguments: ["node", "cli", "gateway", "--port", "18789"],
|
||||
});
|
||||
serviceInstall.mockReset().mockResolvedValue(undefined);
|
||||
serviceIsLoaded.mockReset().mockResolvedValue(false);
|
||||
serviceStop.mockReset().mockResolvedValue(undefined);
|
||||
serviceRestart.mockReset().mockResolvedValue(undefined);
|
||||
serviceUninstall.mockReset().mockResolvedValue(undefined);
|
||||
callGateway.mockReset().mockRejectedValue(new Error("gateway closed"));
|
||||
|
||||
originalIsTTY = process.stdin.isTTY;
|
||||
setStdinTty(true);
|
||||
originalStateDir = process.env.CLAWDBOT_STATE_DIR;
|
||||
originalUpdateInProgress = process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
|
||||
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = "1";
|
||||
tempStateDir = fs.mkdtempSync(
|
||||
path.join(os.tmpdir(), "clawdbot-doctor-state-"),
|
||||
);
|
||||
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
|
||||
fs.mkdirSync(path.join(tempStateDir, "agents", "main", "sessions"), {
|
||||
recursive: true,
|
||||
});
|
||||
fs.mkdirSync(path.join(tempStateDir, "credentials"), { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setStdinTty(originalIsTTY);
|
||||
if (originalStateDir === undefined) {
|
||||
delete process.env.CLAWDBOT_STATE_DIR;
|
||||
} else {
|
||||
process.env.CLAWDBOT_STATE_DIR = originalStateDir;
|
||||
}
|
||||
if (originalUpdateInProgress === undefined) {
|
||||
delete process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
|
||||
} else {
|
||||
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = originalUpdateInProgress;
|
||||
}
|
||||
if (tempStateDir) {
|
||||
fs.rmSync(tempStateDir, { recursive: true, force: true });
|
||||
tempStateDir = undefined;
|
||||
}
|
||||
});
|
||||
|
||||
const readConfigFileSnapshot = vi.fn();
|
||||
const confirm = vi.fn().mockResolvedValue(true);
|
||||
const select = vi.fn().mockResolvedValue("node");
|
||||
const note = vi.fn();
|
||||
const writeConfigFile = vi.fn().mockResolvedValue(undefined);
|
||||
const resolveClawdbotPackageRoot = vi.fn().mockResolvedValue(null);
|
||||
const runGatewayUpdate = vi.fn().mockResolvedValue({
|
||||
status: "skipped",
|
||||
mode: "unknown",
|
||||
steps: [],
|
||||
durationMs: 0,
|
||||
});
|
||||
const migrateLegacyConfig = vi.fn((raw: unknown) => ({
|
||||
config: raw as Record<string, unknown>,
|
||||
changes: ["Moved routing.allowFrom → channels.whatsapp.allowFrom."],
|
||||
}));
|
||||
|
||||
const runExec = vi.fn().mockResolvedValue({ stdout: "", stderr: "" });
|
||||
const runCommandWithTimeout = vi.fn().mockResolvedValue({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
killed: false,
|
||||
});
|
||||
|
||||
const ensureAuthProfileStore = vi
|
||||
.fn()
|
||||
.mockReturnValue({ version: 1, profiles: {} });
|
||||
|
||||
const legacyReadConfigFileSnapshot = vi.fn().mockResolvedValue({
|
||||
path: "/tmp/clawdis.json",
|
||||
exists: false,
|
||||
raw: null,
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
const createConfigIO = vi.fn(() => ({
|
||||
readConfigFileSnapshot: legacyReadConfigFileSnapshot,
|
||||
}));
|
||||
|
||||
const findLegacyGatewayServices = vi.fn().mockResolvedValue([]);
|
||||
const uninstallLegacyGatewayServices = vi.fn().mockResolvedValue([]);
|
||||
const findExtraGatewayServices = vi.fn().mockResolvedValue([]);
|
||||
const renderGatewayServiceCleanupHints = vi.fn().mockReturnValue(["cleanup"]);
|
||||
const resolveGatewayProgramArguments = vi.fn().mockResolvedValue({
|
||||
programArguments: ["node", "cli", "gateway", "--port", "18789"],
|
||||
});
|
||||
const serviceInstall = vi.fn().mockResolvedValue(undefined);
|
||||
const serviceIsLoaded = vi.fn().mockResolvedValue(false);
|
||||
const serviceStop = vi.fn().mockResolvedValue(undefined);
|
||||
const serviceRestart = vi.fn().mockResolvedValue(undefined);
|
||||
const serviceUninstall = vi.fn().mockResolvedValue(undefined);
|
||||
const callGateway = vi.fn().mockRejectedValue(new Error("gateway closed"));
|
||||
|
||||
vi.mock("@clack/prompts", () => ({
|
||||
confirm,
|
||||
intro: vi.fn(),
|
||||
note,
|
||||
outro: vi.fn(),
|
||||
select,
|
||||
}));
|
||||
|
||||
vi.mock("../agents/skills-status.js", () => ({
|
||||
buildWorkspaceSkillStatus: () => ({ skills: [] }),
|
||||
}));
|
||||
|
||||
vi.mock("../config/config.js", async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
CONFIG_PATH_CLAWDBOT: "/tmp/clawdbot.json",
|
||||
createConfigIO,
|
||||
readConfigFileSnapshot,
|
||||
writeConfigFile,
|
||||
migrateLegacyConfig,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../daemon/legacy.js", () => ({
|
||||
findLegacyGatewayServices,
|
||||
uninstallLegacyGatewayServices,
|
||||
}));
|
||||
|
||||
vi.mock("../daemon/inspect.js", () => ({
|
||||
findExtraGatewayServices,
|
||||
renderGatewayServiceCleanupHints,
|
||||
}));
|
||||
|
||||
vi.mock("../daemon/program-args.js", () => ({
|
||||
resolveGatewayProgramArguments,
|
||||
}));
|
||||
|
||||
vi.mock("../gateway/call.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../gateway/call.js")>();
|
||||
return {
|
||||
...actual,
|
||||
callGateway,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../process/exec.js", () => ({
|
||||
runExec,
|
||||
runCommandWithTimeout,
|
||||
}));
|
||||
|
||||
vi.mock("../infra/clawdbot-root.js", () => ({
|
||||
resolveClawdbotPackageRoot,
|
||||
}));
|
||||
|
||||
vi.mock("../infra/update-runner.js", () => ({
|
||||
runGatewayUpdate,
|
||||
}));
|
||||
|
||||
vi.mock("../agents/auth-profiles.js", async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
ensureAuthProfileStore,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../daemon/service.js", () => ({
|
||||
resolveGatewayService: () => ({
|
||||
label: "LaunchAgent",
|
||||
loadedText: "loaded",
|
||||
notLoadedText: "not loaded",
|
||||
install: serviceInstall,
|
||||
uninstall: serviceUninstall,
|
||||
stop: serviceStop,
|
||||
restart: serviceRestart,
|
||||
isLoaded: serviceIsLoaded,
|
||||
readCommand: vi.fn(),
|
||||
readRuntime: vi.fn().mockResolvedValue({ status: "running" }),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../telegram/pairing-store.js", () => ({
|
||||
readTelegramAllowFromStore: vi.fn().mockResolvedValue([]),
|
||||
}));
|
||||
|
||||
vi.mock("../pairing/pairing-store.js", () => ({
|
||||
readChannelAllowFromStore: vi.fn().mockResolvedValue([]),
|
||||
}));
|
||||
|
||||
vi.mock("../telegram/token.js", () => ({
|
||||
resolveTelegramToken: vi.fn(() => ({ token: "", source: "none" })),
|
||||
}));
|
||||
|
||||
vi.mock("../runtime.js", () => ({
|
||||
defaultRuntime: {
|
||||
log: () => {},
|
||||
error: () => {},
|
||||
exit: () => {
|
||||
throw new Error("exit");
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../utils.js", async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
resolveUserPath: (value: string) => value,
|
||||
sleep: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("./health.js", () => ({
|
||||
healthCommand: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock("./onboard-helpers.js", () => ({
|
||||
applyWizardMetadata: (cfg: Record<string, unknown>) => cfg,
|
||||
DEFAULT_WORKSPACE: "/tmp",
|
||||
guardCancel: (value: unknown) => value,
|
||||
printWizardHeader: vi.fn(),
|
||||
randomToken: vi.fn(() => "test-gateway-token"),
|
||||
}));
|
||||
|
||||
vi.mock("./doctor-state-migrations.js", () => ({
|
||||
detectLegacyStateMigrations: vi.fn().mockResolvedValue({
|
||||
targetAgentId: "main",
|
||||
targetMainKey: "main",
|
||||
stateDir: "/tmp/state",
|
||||
oauthDir: "/tmp/oauth",
|
||||
sessions: {
|
||||
legacyDir: "/tmp/state/sessions",
|
||||
legacyStorePath: "/tmp/state/sessions/sessions.json",
|
||||
targetDir: "/tmp/state/agents/main/sessions",
|
||||
targetStorePath: "/tmp/state/agents/main/sessions/sessions.json",
|
||||
hasLegacy: false,
|
||||
},
|
||||
agentDir: {
|
||||
legacyDir: "/tmp/state/agent",
|
||||
targetDir: "/tmp/state/agents/main/agent",
|
||||
hasLegacy: false,
|
||||
},
|
||||
whatsappAuth: {
|
||||
legacyDir: "/tmp/oauth",
|
||||
targetDir: "/tmp/oauth/whatsapp/default",
|
||||
hasLegacy: false,
|
||||
},
|
||||
preview: [],
|
||||
}),
|
||||
runLegacyStateMigrations: vi.fn().mockResolvedValue({
|
||||
changes: [],
|
||||
warnings: [],
|
||||
}),
|
||||
}));
|
||||
|
||||
describe("doctor command", () => {
|
||||
it("runs legacy state migrations in yes mode without prompting", async () => {
|
||||
readConfigFileSnapshot.mockResolvedValue({
|
||||
path: "/tmp/clawdbot.json",
|
||||
exists: true,
|
||||
raw: "{}",
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
|
||||
const { doctorCommand } = await import("./doctor.js");
|
||||
const runtime = {
|
||||
log: vi.fn(),
|
||||
error: vi.fn(),
|
||||
exit: vi.fn(),
|
||||
};
|
||||
|
||||
const { detectLegacyStateMigrations, runLegacyStateMigrations } =
|
||||
await import("./doctor-state-migrations.js");
|
||||
detectLegacyStateMigrations.mockResolvedValueOnce({
|
||||
targetAgentId: "main",
|
||||
targetMainKey: "main",
|
||||
stateDir: "/tmp/state",
|
||||
oauthDir: "/tmp/oauth",
|
||||
sessions: {
|
||||
legacyDir: "/tmp/state/sessions",
|
||||
legacyStorePath: "/tmp/state/sessions/sessions.json",
|
||||
targetDir: "/tmp/state/agents/main/sessions",
|
||||
targetStorePath: "/tmp/state/agents/main/sessions/sessions.json",
|
||||
hasLegacy: true,
|
||||
},
|
||||
agentDir: {
|
||||
legacyDir: "/tmp/state/agent",
|
||||
targetDir: "/tmp/state/agents/main/agent",
|
||||
hasLegacy: false,
|
||||
},
|
||||
whatsappAuth: {
|
||||
legacyDir: "/tmp/oauth",
|
||||
targetDir: "/tmp/oauth/whatsapp/default",
|
||||
hasLegacy: false,
|
||||
},
|
||||
preview: ["- Legacy sessions detected"],
|
||||
});
|
||||
runLegacyStateMigrations.mockResolvedValueOnce({
|
||||
changes: ["migrated"],
|
||||
warnings: [],
|
||||
});
|
||||
|
||||
runLegacyStateMigrations.mockClear();
|
||||
confirm.mockClear();
|
||||
|
||||
await doctorCommand(runtime, { yes: true });
|
||||
|
||||
expect(runLegacyStateMigrations).toHaveBeenCalledTimes(1);
|
||||
expect(confirm).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("skips gateway restarts in non-interactive mode", async () => {
|
||||
readConfigFileSnapshot.mockResolvedValue({
|
||||
path: "/tmp/clawdbot.json",
|
||||
exists: true,
|
||||
raw: "{}",
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
|
||||
const { healthCommand } = await import("./health.js");
|
||||
healthCommand.mockRejectedValueOnce(new Error("gateway closed"));
|
||||
|
||||
serviceIsLoaded.mockResolvedValueOnce(true);
|
||||
serviceRestart.mockClear();
|
||||
confirm.mockClear();
|
||||
|
||||
const { doctorCommand } = await import("./doctor.js");
|
||||
const runtime = {
|
||||
log: vi.fn(),
|
||||
error: vi.fn(),
|
||||
exit: vi.fn(),
|
||||
};
|
||||
|
||||
await doctorCommand(runtime, { nonInteractive: true });
|
||||
|
||||
expect(serviceRestart).not.toHaveBeenCalled();
|
||||
expect(confirm).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("migrates anthropic oauth config profile id when only email profile exists", async () => {
|
||||
readConfigFileSnapshot.mockResolvedValue({
|
||||
path: "/tmp/clawdbot.json",
|
||||
exists: true,
|
||||
raw: "{}",
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {
|
||||
auth: {
|
||||
profiles: {
|
||||
"anthropic:default": { provider: "anthropic", mode: "oauth" },
|
||||
},
|
||||
},
|
||||
},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
|
||||
ensureAuthProfileStore.mockReturnValueOnce({
|
||||
version: 1,
|
||||
profiles: {
|
||||
"anthropic:me@example.com": {
|
||||
type: "oauth",
|
||||
provider: "anthropic",
|
||||
access: "access",
|
||||
refresh: "refresh",
|
||||
expires: Date.now() + 60_000,
|
||||
email: "me@example.com",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const { doctorCommand } = await import("./doctor.js");
|
||||
await doctorCommand(
|
||||
{ log: vi.fn(), error: vi.fn(), exit: vi.fn() },
|
||||
{ yes: true },
|
||||
);
|
||||
|
||||
const written = writeConfigFile.mock.calls.at(-1)?.[0] as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
const profiles = (written.auth as { profiles: Record<string, unknown> })
|
||||
.profiles;
|
||||
expect(profiles["anthropic:me@example.com"]).toBeTruthy();
|
||||
expect(profiles["anthropic:default"]).toBeUndefined();
|
||||
}, 20_000);
|
||||
});
|
||||
392
src/commands/doctor.part-6.test.ts
Normal file
392
src/commands/doctor.part-6.test.ts
Normal file
@@ -0,0 +1,392 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
let originalIsTTY: boolean | undefined;
|
||||
let originalStateDir: string | undefined;
|
||||
let originalUpdateInProgress: string | undefined;
|
||||
let tempStateDir: string | undefined;
|
||||
|
||||
function setStdinTty(value: boolean | undefined) {
|
||||
try {
|
||||
Object.defineProperty(process.stdin, "isTTY", {
|
||||
value,
|
||||
configurable: true,
|
||||
});
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
confirm.mockReset().mockResolvedValue(true);
|
||||
select.mockReset().mockResolvedValue("node");
|
||||
note.mockClear();
|
||||
|
||||
readConfigFileSnapshot.mockReset();
|
||||
writeConfigFile.mockReset().mockResolvedValue(undefined);
|
||||
resolveClawdbotPackageRoot.mockReset().mockResolvedValue(null);
|
||||
runGatewayUpdate.mockReset().mockResolvedValue({
|
||||
status: "skipped",
|
||||
mode: "unknown",
|
||||
steps: [],
|
||||
durationMs: 0,
|
||||
});
|
||||
legacyReadConfigFileSnapshot.mockReset().mockResolvedValue({
|
||||
path: "/tmp/clawdis.json",
|
||||
exists: false,
|
||||
raw: null,
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
createConfigIO.mockReset().mockImplementation(() => ({
|
||||
readConfigFileSnapshot: legacyReadConfigFileSnapshot,
|
||||
}));
|
||||
runExec.mockReset().mockResolvedValue({ stdout: "", stderr: "" });
|
||||
runCommandWithTimeout.mockReset().mockResolvedValue({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
killed: false,
|
||||
});
|
||||
ensureAuthProfileStore
|
||||
.mockReset()
|
||||
.mockReturnValue({ version: 1, profiles: {} });
|
||||
migrateLegacyConfig.mockReset().mockImplementation((raw: unknown) => ({
|
||||
config: raw as Record<string, unknown>,
|
||||
changes: ["Moved routing.allowFrom → channels.whatsapp.allowFrom."],
|
||||
}));
|
||||
findLegacyGatewayServices.mockReset().mockResolvedValue([]);
|
||||
uninstallLegacyGatewayServices.mockReset().mockResolvedValue([]);
|
||||
findExtraGatewayServices.mockReset().mockResolvedValue([]);
|
||||
renderGatewayServiceCleanupHints.mockReset().mockReturnValue(["cleanup"]);
|
||||
resolveGatewayProgramArguments.mockReset().mockResolvedValue({
|
||||
programArguments: ["node", "cli", "gateway", "--port", "18789"],
|
||||
});
|
||||
serviceInstall.mockReset().mockResolvedValue(undefined);
|
||||
serviceIsLoaded.mockReset().mockResolvedValue(false);
|
||||
serviceStop.mockReset().mockResolvedValue(undefined);
|
||||
serviceRestart.mockReset().mockResolvedValue(undefined);
|
||||
serviceUninstall.mockReset().mockResolvedValue(undefined);
|
||||
callGateway.mockReset().mockRejectedValue(new Error("gateway closed"));
|
||||
|
||||
originalIsTTY = process.stdin.isTTY;
|
||||
setStdinTty(true);
|
||||
originalStateDir = process.env.CLAWDBOT_STATE_DIR;
|
||||
originalUpdateInProgress = process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
|
||||
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = "1";
|
||||
tempStateDir = fs.mkdtempSync(
|
||||
path.join(os.tmpdir(), "clawdbot-doctor-state-"),
|
||||
);
|
||||
process.env.CLAWDBOT_STATE_DIR = tempStateDir;
|
||||
fs.mkdirSync(path.join(tempStateDir, "agents", "main", "sessions"), {
|
||||
recursive: true,
|
||||
});
|
||||
fs.mkdirSync(path.join(tempStateDir, "credentials"), { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setStdinTty(originalIsTTY);
|
||||
if (originalStateDir === undefined) {
|
||||
delete process.env.CLAWDBOT_STATE_DIR;
|
||||
} else {
|
||||
process.env.CLAWDBOT_STATE_DIR = originalStateDir;
|
||||
}
|
||||
if (originalUpdateInProgress === undefined) {
|
||||
delete process.env.CLAWDBOT_UPDATE_IN_PROGRESS;
|
||||
} else {
|
||||
process.env.CLAWDBOT_UPDATE_IN_PROGRESS = originalUpdateInProgress;
|
||||
}
|
||||
if (tempStateDir) {
|
||||
fs.rmSync(tempStateDir, { recursive: true, force: true });
|
||||
tempStateDir = undefined;
|
||||
}
|
||||
});
|
||||
|
||||
const readConfigFileSnapshot = vi.fn();
|
||||
const confirm = vi.fn().mockResolvedValue(true);
|
||||
const select = vi.fn().mockResolvedValue("node");
|
||||
const note = vi.fn();
|
||||
const writeConfigFile = vi.fn().mockResolvedValue(undefined);
|
||||
const resolveClawdbotPackageRoot = vi.fn().mockResolvedValue(null);
|
||||
const runGatewayUpdate = vi.fn().mockResolvedValue({
|
||||
status: "skipped",
|
||||
mode: "unknown",
|
||||
steps: [],
|
||||
durationMs: 0,
|
||||
});
|
||||
const migrateLegacyConfig = vi.fn((raw: unknown) => ({
|
||||
config: raw as Record<string, unknown>,
|
||||
changes: ["Moved routing.allowFrom → channels.whatsapp.allowFrom."],
|
||||
}));
|
||||
|
||||
const runExec = vi.fn().mockResolvedValue({ stdout: "", stderr: "" });
|
||||
const runCommandWithTimeout = vi.fn().mockResolvedValue({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
killed: false,
|
||||
});
|
||||
|
||||
const ensureAuthProfileStore = vi
|
||||
.fn()
|
||||
.mockReturnValue({ version: 1, profiles: {} });
|
||||
|
||||
const legacyReadConfigFileSnapshot = vi.fn().mockResolvedValue({
|
||||
path: "/tmp/clawdis.json",
|
||||
exists: false,
|
||||
raw: null,
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
const createConfigIO = vi.fn(() => ({
|
||||
readConfigFileSnapshot: legacyReadConfigFileSnapshot,
|
||||
}));
|
||||
|
||||
const findLegacyGatewayServices = vi.fn().mockResolvedValue([]);
|
||||
const uninstallLegacyGatewayServices = vi.fn().mockResolvedValue([]);
|
||||
const findExtraGatewayServices = vi.fn().mockResolvedValue([]);
|
||||
const renderGatewayServiceCleanupHints = vi.fn().mockReturnValue(["cleanup"]);
|
||||
const resolveGatewayProgramArguments = vi.fn().mockResolvedValue({
|
||||
programArguments: ["node", "cli", "gateway", "--port", "18789"],
|
||||
});
|
||||
const serviceInstall = vi.fn().mockResolvedValue(undefined);
|
||||
const serviceIsLoaded = vi.fn().mockResolvedValue(false);
|
||||
const serviceStop = vi.fn().mockResolvedValue(undefined);
|
||||
const serviceRestart = vi.fn().mockResolvedValue(undefined);
|
||||
const serviceUninstall = vi.fn().mockResolvedValue(undefined);
|
||||
const callGateway = vi.fn().mockRejectedValue(new Error("gateway closed"));
|
||||
|
||||
vi.mock("@clack/prompts", () => ({
|
||||
confirm,
|
||||
intro: vi.fn(),
|
||||
note,
|
||||
outro: vi.fn(),
|
||||
select,
|
||||
}));
|
||||
|
||||
vi.mock("../agents/skills-status.js", () => ({
|
||||
buildWorkspaceSkillStatus: () => ({ skills: [] }),
|
||||
}));
|
||||
|
||||
vi.mock("../config/config.js", async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
CONFIG_PATH_CLAWDBOT: "/tmp/clawdbot.json",
|
||||
createConfigIO,
|
||||
readConfigFileSnapshot,
|
||||
writeConfigFile,
|
||||
migrateLegacyConfig,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../daemon/legacy.js", () => ({
|
||||
findLegacyGatewayServices,
|
||||
uninstallLegacyGatewayServices,
|
||||
}));
|
||||
|
||||
vi.mock("../daemon/inspect.js", () => ({
|
||||
findExtraGatewayServices,
|
||||
renderGatewayServiceCleanupHints,
|
||||
}));
|
||||
|
||||
vi.mock("../daemon/program-args.js", () => ({
|
||||
resolveGatewayProgramArguments,
|
||||
}));
|
||||
|
||||
vi.mock("../gateway/call.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../gateway/call.js")>();
|
||||
return {
|
||||
...actual,
|
||||
callGateway,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../process/exec.js", () => ({
|
||||
runExec,
|
||||
runCommandWithTimeout,
|
||||
}));
|
||||
|
||||
vi.mock("../infra/clawdbot-root.js", () => ({
|
||||
resolveClawdbotPackageRoot,
|
||||
}));
|
||||
|
||||
vi.mock("../infra/update-runner.js", () => ({
|
||||
runGatewayUpdate,
|
||||
}));
|
||||
|
||||
vi.mock("../agents/auth-profiles.js", async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
ensureAuthProfileStore,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../daemon/service.js", () => ({
|
||||
resolveGatewayService: () => ({
|
||||
label: "LaunchAgent",
|
||||
loadedText: "loaded",
|
||||
notLoadedText: "not loaded",
|
||||
install: serviceInstall,
|
||||
uninstall: serviceUninstall,
|
||||
stop: serviceStop,
|
||||
restart: serviceRestart,
|
||||
isLoaded: serviceIsLoaded,
|
||||
readCommand: vi.fn(),
|
||||
readRuntime: vi.fn().mockResolvedValue({ status: "running" }),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../telegram/pairing-store.js", () => ({
|
||||
readTelegramAllowFromStore: vi.fn().mockResolvedValue([]),
|
||||
}));
|
||||
|
||||
vi.mock("../pairing/pairing-store.js", () => ({
|
||||
readChannelAllowFromStore: vi.fn().mockResolvedValue([]),
|
||||
}));
|
||||
|
||||
vi.mock("../telegram/token.js", () => ({
|
||||
resolveTelegramToken: vi.fn(() => ({ token: "", source: "none" })),
|
||||
}));
|
||||
|
||||
vi.mock("../runtime.js", () => ({
|
||||
defaultRuntime: {
|
||||
log: () => {},
|
||||
error: () => {},
|
||||
exit: () => {
|
||||
throw new Error("exit");
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../utils.js", async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
resolveUserPath: (value: string) => value,
|
||||
sleep: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("./health.js", () => ({
|
||||
healthCommand: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock("./onboard-helpers.js", () => ({
|
||||
applyWizardMetadata: (cfg: Record<string, unknown>) => cfg,
|
||||
DEFAULT_WORKSPACE: "/tmp",
|
||||
guardCancel: (value: unknown) => value,
|
||||
printWizardHeader: vi.fn(),
|
||||
randomToken: vi.fn(() => "test-gateway-token"),
|
||||
}));
|
||||
|
||||
vi.mock("./doctor-state-migrations.js", () => ({
|
||||
detectLegacyStateMigrations: vi.fn().mockResolvedValue({
|
||||
targetAgentId: "main",
|
||||
targetMainKey: "main",
|
||||
stateDir: "/tmp/state",
|
||||
oauthDir: "/tmp/oauth",
|
||||
sessions: {
|
||||
legacyDir: "/tmp/state/sessions",
|
||||
legacyStorePath: "/tmp/state/sessions/sessions.json",
|
||||
targetDir: "/tmp/state/agents/main/sessions",
|
||||
targetStorePath: "/tmp/state/agents/main/sessions/sessions.json",
|
||||
hasLegacy: false,
|
||||
},
|
||||
agentDir: {
|
||||
legacyDir: "/tmp/state/agent",
|
||||
targetDir: "/tmp/state/agents/main/agent",
|
||||
hasLegacy: false,
|
||||
},
|
||||
whatsappAuth: {
|
||||
legacyDir: "/tmp/oauth",
|
||||
targetDir: "/tmp/oauth/whatsapp/default",
|
||||
hasLegacy: false,
|
||||
},
|
||||
preview: [],
|
||||
}),
|
||||
runLegacyStateMigrations: vi.fn().mockResolvedValue({
|
||||
changes: [],
|
||||
warnings: [],
|
||||
}),
|
||||
}));
|
||||
|
||||
describe("doctor command", () => {
|
||||
it("warns when the state directory is missing", async () => {
|
||||
readConfigFileSnapshot.mockResolvedValue({
|
||||
path: "/tmp/clawdbot.json",
|
||||
exists: true,
|
||||
raw: "{}",
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
|
||||
const missingDir = fs.mkdtempSync(
|
||||
path.join(os.tmpdir(), "clawdbot-missing-state-"),
|
||||
);
|
||||
fs.rmSync(missingDir, { recursive: true, force: true });
|
||||
process.env.CLAWDBOT_STATE_DIR = missingDir;
|
||||
note.mockClear();
|
||||
|
||||
const { doctorCommand } = await import("./doctor.js");
|
||||
await doctorCommand(
|
||||
{ log: vi.fn(), error: vi.fn(), exit: vi.fn() },
|
||||
{ nonInteractive: true, workspaceSuggestions: false },
|
||||
);
|
||||
|
||||
const stateNote = note.mock.calls.find(
|
||||
(call) => call[1] === "State integrity",
|
||||
);
|
||||
expect(stateNote).toBeTruthy();
|
||||
expect(String(stateNote?.[0])).toContain("CRITICAL");
|
||||
}, 20_000);
|
||||
|
||||
it("warns about opencode provider overrides", async () => {
|
||||
readConfigFileSnapshot.mockResolvedValue({
|
||||
path: "/tmp/clawdbot.json",
|
||||
exists: true,
|
||||
raw: "{}",
|
||||
parsed: {},
|
||||
valid: true,
|
||||
config: {
|
||||
models: {
|
||||
providers: {
|
||||
opencode: {
|
||||
api: "openai-completions",
|
||||
baseUrl: "https://opencode.ai/zen/v1",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
issues: [],
|
||||
legacyIssues: [],
|
||||
});
|
||||
|
||||
const { doctorCommand } = await import("./doctor.js");
|
||||
await doctorCommand(
|
||||
{ log: vi.fn(), error: vi.fn(), exit: vi.fn() },
|
||||
{ nonInteractive: true, workspaceSuggestions: false },
|
||||
);
|
||||
|
||||
const warned = note.mock.calls.some(
|
||||
([message, title]) =>
|
||||
title === "OpenCode Zen" &&
|
||||
String(message).includes("models.providers.opencode"),
|
||||
);
|
||||
expect(warned).toBe(true);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,343 +1,24 @@
|
||||
import { withProgress } from "../cli/progress.js";
|
||||
import { loadConfig, resolveGatewayPort } from "../config/config.js";
|
||||
import type { ClawdbotConfig, ConfigFileSnapshot } from "../config/types.js";
|
||||
import { type GatewayProbeResult, probeGateway } from "../gateway/probe.js";
|
||||
import { probeGateway } from "../gateway/probe.js";
|
||||
import { discoverGatewayBeacons } from "../infra/bonjour-discovery.js";
|
||||
import { startSshPortForward } from "../infra/ssh-tunnel.js";
|
||||
import { pickPrimaryTailnetIPv4 } from "../infra/tailnet.js";
|
||||
import type { RuntimeEnv } from "../runtime.js";
|
||||
import { colorize, isRich, theme } from "../terminal/theme.js";
|
||||
|
||||
type TargetKind = "explicit" | "configRemote" | "localLoopback" | "sshTunnel";
|
||||
|
||||
type GatewayStatusTarget = {
|
||||
id: string;
|
||||
kind: TargetKind;
|
||||
url: string;
|
||||
active: boolean;
|
||||
tunnel?: {
|
||||
kind: "ssh";
|
||||
target: string;
|
||||
localPort: number;
|
||||
remotePort: number;
|
||||
pid: number | null;
|
||||
};
|
||||
};
|
||||
|
||||
type GatewayConfigSummary = {
|
||||
path: string | null;
|
||||
exists: boolean;
|
||||
valid: boolean;
|
||||
issues: Array<{ path: string; message: string }>;
|
||||
legacyIssues: Array<{ path: string; message: string }>;
|
||||
gateway: {
|
||||
mode: string | null;
|
||||
bind: string | null;
|
||||
port: number | null;
|
||||
controlUiEnabled: boolean | null;
|
||||
controlUiBasePath: string | null;
|
||||
authMode: string | null;
|
||||
authTokenConfigured: boolean;
|
||||
authPasswordConfigured: boolean;
|
||||
remoteUrl: string | null;
|
||||
remoteTokenConfigured: boolean;
|
||||
remotePasswordConfigured: boolean;
|
||||
tailscaleMode: string | null;
|
||||
};
|
||||
bridge: {
|
||||
enabled: boolean | null;
|
||||
bind: string | null;
|
||||
port: number | null;
|
||||
};
|
||||
discovery: {
|
||||
wideAreaEnabled: boolean | null;
|
||||
};
|
||||
};
|
||||
|
||||
function parseIntOrNull(value: unknown): number | null {
|
||||
const s =
|
||||
typeof value === "string"
|
||||
? value.trim()
|
||||
: typeof value === "number" || typeof value === "bigint"
|
||||
? String(value)
|
||||
: "";
|
||||
if (!s) return null;
|
||||
const n = Number.parseInt(s, 10);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
function parseTimeoutMs(raw: unknown, fallbackMs: number): number {
|
||||
const value =
|
||||
typeof raw === "string"
|
||||
? raw.trim()
|
||||
: typeof raw === "number" || typeof raw === "bigint"
|
||||
? String(raw)
|
||||
: "";
|
||||
if (!value) return fallbackMs;
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
if (!Number.isFinite(parsed) || parsed <= 0) {
|
||||
throw new Error(`invalid --timeout: ${value}`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function normalizeWsUrl(value: string): string | null {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return null;
|
||||
if (!trimmed.startsWith("ws://") && !trimmed.startsWith("wss://"))
|
||||
return null;
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function resolveTargets(
|
||||
cfg: ClawdbotConfig,
|
||||
explicitUrl?: string,
|
||||
): GatewayStatusTarget[] {
|
||||
const targets: GatewayStatusTarget[] = [];
|
||||
const add = (t: GatewayStatusTarget) => {
|
||||
if (!targets.some((x) => x.url === t.url)) targets.push(t);
|
||||
};
|
||||
|
||||
const explicit =
|
||||
typeof explicitUrl === "string" ? normalizeWsUrl(explicitUrl) : null;
|
||||
if (explicit)
|
||||
add({ id: "explicit", kind: "explicit", url: explicit, active: true });
|
||||
|
||||
const remoteUrl =
|
||||
typeof cfg.gateway?.remote?.url === "string"
|
||||
? normalizeWsUrl(cfg.gateway.remote.url)
|
||||
: null;
|
||||
if (remoteUrl) {
|
||||
add({
|
||||
id: "configRemote",
|
||||
kind: "configRemote",
|
||||
url: remoteUrl,
|
||||
active: cfg.gateway?.mode === "remote",
|
||||
});
|
||||
}
|
||||
|
||||
const port = resolveGatewayPort(cfg);
|
||||
add({
|
||||
id: "localLoopback",
|
||||
kind: "localLoopback",
|
||||
url: `ws://127.0.0.1:${port}`,
|
||||
active: cfg.gateway?.mode !== "remote",
|
||||
});
|
||||
|
||||
return targets;
|
||||
}
|
||||
|
||||
function resolveProbeBudgetMs(overallMs: number, kind: TargetKind): number {
|
||||
if (kind === "localLoopback") return Math.min(800, overallMs);
|
||||
if (kind === "sshTunnel") return Math.min(2000, overallMs);
|
||||
return Math.min(1500, overallMs);
|
||||
}
|
||||
|
||||
function sanitizeSshTarget(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return null;
|
||||
return trimmed.replace(/^ssh\s+/, "");
|
||||
}
|
||||
|
||||
function resolveAuthForTarget(
|
||||
cfg: ClawdbotConfig,
|
||||
target: GatewayStatusTarget,
|
||||
overrides: { token?: string; password?: string },
|
||||
): { token?: string; password?: string } {
|
||||
const tokenOverride = overrides.token?.trim()
|
||||
? overrides.token.trim()
|
||||
: undefined;
|
||||
const passwordOverride = overrides.password?.trim()
|
||||
? overrides.password.trim()
|
||||
: undefined;
|
||||
if (tokenOverride || passwordOverride) {
|
||||
return { token: tokenOverride, password: passwordOverride };
|
||||
}
|
||||
|
||||
if (target.kind === "configRemote") {
|
||||
const token =
|
||||
typeof cfg.gateway?.remote?.token === "string"
|
||||
? cfg.gateway.remote.token.trim()
|
||||
: "";
|
||||
const remotePassword = (
|
||||
cfg.gateway?.remote as { password?: unknown } | undefined
|
||||
)?.password;
|
||||
const password =
|
||||
typeof remotePassword === "string" ? remotePassword.trim() : "";
|
||||
return {
|
||||
token: token.length > 0 ? token : undefined,
|
||||
password: password.length > 0 ? password : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
const envToken = process.env.CLAWDBOT_GATEWAY_TOKEN?.trim() || "";
|
||||
const envPassword = process.env.CLAWDBOT_GATEWAY_PASSWORD?.trim() || "";
|
||||
const cfgToken =
|
||||
typeof cfg.gateway?.auth?.token === "string"
|
||||
? cfg.gateway.auth.token.trim()
|
||||
: "";
|
||||
const cfgPassword =
|
||||
typeof cfg.gateway?.auth?.password === "string"
|
||||
? cfg.gateway.auth.password.trim()
|
||||
: "";
|
||||
|
||||
return {
|
||||
token: envToken || cfgToken || undefined,
|
||||
password: envPassword || cfgPassword || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function pickGatewaySelfPresence(
|
||||
presence: unknown,
|
||||
): { host?: string; ip?: string; version?: string; platform?: string } | null {
|
||||
if (!Array.isArray(presence)) return null;
|
||||
const entries = presence as Array<Record<string, unknown>>;
|
||||
const self =
|
||||
entries.find((e) => e.mode === "gateway" && e.reason === "self") ??
|
||||
entries.find(
|
||||
(e) =>
|
||||
typeof e.text === "string" && String(e.text).startsWith("Gateway:"),
|
||||
) ??
|
||||
null;
|
||||
if (!self) return null;
|
||||
return {
|
||||
host: typeof self.host === "string" ? self.host : undefined,
|
||||
ip: typeof self.ip === "string" ? self.ip : undefined,
|
||||
version: typeof self.version === "string" ? self.version : undefined,
|
||||
platform: typeof self.platform === "string" ? self.platform : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function extractConfigSummary(snapshotUnknown: unknown): GatewayConfigSummary {
|
||||
const snap = snapshotUnknown as Partial<ConfigFileSnapshot> | null;
|
||||
const path = typeof snap?.path === "string" ? snap.path : null;
|
||||
const exists = Boolean(snap?.exists);
|
||||
const valid = Boolean(snap?.valid);
|
||||
const issuesRaw = Array.isArray(snap?.issues) ? snap.issues : [];
|
||||
const legacyRaw = Array.isArray(snap?.legacyIssues) ? snap.legacyIssues : [];
|
||||
|
||||
const cfg = (snap?.config ?? {}) as Record<string, unknown>;
|
||||
const gateway = (cfg.gateway ?? {}) as Record<string, unknown>;
|
||||
const bridge = (cfg.bridge ?? {}) as Record<string, unknown>;
|
||||
const discovery = (cfg.discovery ?? {}) as Record<string, unknown>;
|
||||
const wideArea = (discovery.wideArea ?? {}) as Record<string, unknown>;
|
||||
|
||||
const remote = (gateway.remote ?? {}) as Record<string, unknown>;
|
||||
const auth = (gateway.auth ?? {}) as Record<string, unknown>;
|
||||
const controlUi = (gateway.controlUi ?? {}) as Record<string, unknown>;
|
||||
const tailscale = (gateway.tailscale ?? {}) as Record<string, unknown>;
|
||||
|
||||
const authMode = typeof auth.mode === "string" ? auth.mode : null;
|
||||
const authTokenConfigured =
|
||||
typeof auth.token === "string" ? auth.token.trim().length > 0 : false;
|
||||
const authPasswordConfigured =
|
||||
typeof auth.password === "string" ? auth.password.trim().length > 0 : false;
|
||||
|
||||
const remoteUrl =
|
||||
typeof remote.url === "string" ? normalizeWsUrl(remote.url) : null;
|
||||
const remoteTokenConfigured =
|
||||
typeof remote.token === "string" ? remote.token.trim().length > 0 : false;
|
||||
const remotePasswordConfigured =
|
||||
typeof remote.password === "string"
|
||||
? String(remote.password).trim().length > 0
|
||||
: false;
|
||||
|
||||
const bridgeEnabled =
|
||||
typeof bridge.enabled === "boolean" ? bridge.enabled : null;
|
||||
const bridgeBind = typeof bridge.bind === "string" ? bridge.bind : null;
|
||||
const bridgePort = parseIntOrNull(bridge.port);
|
||||
|
||||
const wideAreaEnabled =
|
||||
typeof wideArea.enabled === "boolean" ? wideArea.enabled : null;
|
||||
|
||||
return {
|
||||
path,
|
||||
exists,
|
||||
valid,
|
||||
issues: issuesRaw
|
||||
.filter((i): i is { path: string; message: string } =>
|
||||
Boolean(
|
||||
i && typeof i.path === "string" && typeof i.message === "string",
|
||||
),
|
||||
)
|
||||
.map((i) => ({ path: i.path, message: i.message })),
|
||||
legacyIssues: legacyRaw
|
||||
.filter((i): i is { path: string; message: string } =>
|
||||
Boolean(
|
||||
i && typeof i.path === "string" && typeof i.message === "string",
|
||||
),
|
||||
)
|
||||
.map((i) => ({ path: i.path, message: i.message })),
|
||||
gateway: {
|
||||
mode: typeof gateway.mode === "string" ? gateway.mode : null,
|
||||
bind: typeof gateway.bind === "string" ? gateway.bind : null,
|
||||
port: parseIntOrNull(gateway.port),
|
||||
controlUiEnabled:
|
||||
typeof controlUi.enabled === "boolean" ? controlUi.enabled : null,
|
||||
controlUiBasePath:
|
||||
typeof controlUi.basePath === "string" ? controlUi.basePath : null,
|
||||
authMode,
|
||||
authTokenConfigured,
|
||||
authPasswordConfigured,
|
||||
remoteUrl,
|
||||
remoteTokenConfigured,
|
||||
remotePasswordConfigured,
|
||||
tailscaleMode: typeof tailscale.mode === "string" ? tailscale.mode : null,
|
||||
},
|
||||
bridge: {
|
||||
enabled: bridgeEnabled,
|
||||
bind: bridgeBind,
|
||||
port: bridgePort,
|
||||
},
|
||||
discovery: { wideAreaEnabled },
|
||||
};
|
||||
}
|
||||
|
||||
function buildNetworkHints(cfg: ClawdbotConfig) {
|
||||
const tailnetIPv4 = pickPrimaryTailnetIPv4();
|
||||
const port = resolveGatewayPort(cfg);
|
||||
return {
|
||||
localLoopbackUrl: `ws://127.0.0.1:${port}`,
|
||||
localTailnetUrl: tailnetIPv4 ? `ws://${tailnetIPv4}:${port}` : null,
|
||||
tailnetIPv4: tailnetIPv4 ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function renderTargetHeader(target: GatewayStatusTarget, rich: boolean) {
|
||||
const kindLabel =
|
||||
target.kind === "localLoopback"
|
||||
? "Local loopback"
|
||||
: target.kind === "sshTunnel"
|
||||
? "Remote over SSH"
|
||||
: target.kind === "configRemote"
|
||||
? target.active
|
||||
? "Remote (configured)"
|
||||
: "Remote (configured, inactive)"
|
||||
: "URL (explicit)";
|
||||
return `${colorize(rich, theme.heading, kindLabel)} ${colorize(rich, theme.muted, target.url)}`;
|
||||
}
|
||||
|
||||
function renderProbeSummaryLine(probe: GatewayProbeResult, rich: boolean) {
|
||||
if (probe.ok) {
|
||||
const latency =
|
||||
typeof probe.connectLatencyMs === "number"
|
||||
? `${probe.connectLatencyMs}ms`
|
||||
: "unknown";
|
||||
return `${colorize(rich, theme.success, "Connect: ok")} (${latency}) · ${colorize(rich, theme.success, "RPC: ok")}`;
|
||||
}
|
||||
|
||||
const detail = probe.error ? ` - ${probe.error}` : "";
|
||||
if (probe.connectLatencyMs != null) {
|
||||
const latency =
|
||||
typeof probe.connectLatencyMs === "number"
|
||||
? `${probe.connectLatencyMs}ms`
|
||||
: "unknown";
|
||||
return `${colorize(rich, theme.success, "Connect: ok")} (${latency}) · ${colorize(rich, theme.error, "RPC: failed")}${detail}`;
|
||||
}
|
||||
|
||||
return `${colorize(rich, theme.error, "Connect: failed")}${detail}`;
|
||||
}
|
||||
import {
|
||||
buildNetworkHints,
|
||||
extractConfigSummary,
|
||||
type GatewayStatusTarget,
|
||||
parseTimeoutMs,
|
||||
pickGatewaySelfPresence,
|
||||
renderProbeSummaryLine,
|
||||
renderTargetHeader,
|
||||
resolveAuthForTarget,
|
||||
resolveProbeBudgetMs,
|
||||
resolveTargets,
|
||||
sanitizeSshTarget,
|
||||
} from "./gateway-status/helpers.js";
|
||||
|
||||
export async function gatewayStatusCommand(
|
||||
opts: {
|
||||
|
||||
340
src/commands/gateway-status/helpers.ts
Normal file
340
src/commands/gateway-status/helpers.ts
Normal file
@@ -0,0 +1,340 @@
|
||||
import { resolveGatewayPort } from "../../config/config.js";
|
||||
import type { ClawdbotConfig, ConfigFileSnapshot } from "../../config/types.js";
|
||||
import type { GatewayProbeResult } from "../../gateway/probe.js";
|
||||
import { pickPrimaryTailnetIPv4 } from "../../infra/tailnet.js";
|
||||
import { colorize, theme } from "../../terminal/theme.js";
|
||||
|
||||
type TargetKind = "explicit" | "configRemote" | "localLoopback" | "sshTunnel";
|
||||
|
||||
export type GatewayStatusTarget = {
|
||||
id: string;
|
||||
kind: TargetKind;
|
||||
url: string;
|
||||
active: boolean;
|
||||
tunnel?: {
|
||||
kind: "ssh";
|
||||
target: string;
|
||||
localPort: number;
|
||||
remotePort: number;
|
||||
pid: number | null;
|
||||
};
|
||||
};
|
||||
|
||||
export type GatewayConfigSummary = {
|
||||
path: string | null;
|
||||
exists: boolean;
|
||||
valid: boolean;
|
||||
issues: Array<{ path: string; message: string }>;
|
||||
legacyIssues: Array<{ path: string; message: string }>;
|
||||
gateway: {
|
||||
mode: string | null;
|
||||
bind: string | null;
|
||||
port: number | null;
|
||||
controlUiEnabled: boolean | null;
|
||||
controlUiBasePath: string | null;
|
||||
authMode: string | null;
|
||||
authTokenConfigured: boolean;
|
||||
authPasswordConfigured: boolean;
|
||||
remoteUrl: string | null;
|
||||
remoteTokenConfigured: boolean;
|
||||
remotePasswordConfigured: boolean;
|
||||
tailscaleMode: string | null;
|
||||
};
|
||||
bridge: {
|
||||
enabled: boolean | null;
|
||||
bind: string | null;
|
||||
port: number | null;
|
||||
};
|
||||
discovery: {
|
||||
wideAreaEnabled: boolean | null;
|
||||
};
|
||||
};
|
||||
|
||||
function parseIntOrNull(value: unknown): number | null {
|
||||
const s =
|
||||
typeof value === "string"
|
||||
? value.trim()
|
||||
: typeof value === "number" || typeof value === "bigint"
|
||||
? String(value)
|
||||
: "";
|
||||
if (!s) return null;
|
||||
const n = Number.parseInt(s, 10);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
export function parseTimeoutMs(raw: unknown, fallbackMs: number): number {
|
||||
const value =
|
||||
typeof raw === "string"
|
||||
? raw.trim()
|
||||
: typeof raw === "number" || typeof raw === "bigint"
|
||||
? String(raw)
|
||||
: "";
|
||||
if (!value) return fallbackMs;
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
if (!Number.isFinite(parsed) || parsed <= 0) {
|
||||
throw new Error(`invalid --timeout: ${value}`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function normalizeWsUrl(value: string): string | null {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return null;
|
||||
if (!trimmed.startsWith("ws://") && !trimmed.startsWith("wss://"))
|
||||
return null;
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
export function resolveTargets(
|
||||
cfg: ClawdbotConfig,
|
||||
explicitUrl?: string,
|
||||
): GatewayStatusTarget[] {
|
||||
const targets: GatewayStatusTarget[] = [];
|
||||
const add = (t: GatewayStatusTarget) => {
|
||||
if (!targets.some((x) => x.url === t.url)) targets.push(t);
|
||||
};
|
||||
|
||||
const explicit =
|
||||
typeof explicitUrl === "string" ? normalizeWsUrl(explicitUrl) : null;
|
||||
if (explicit)
|
||||
add({ id: "explicit", kind: "explicit", url: explicit, active: true });
|
||||
|
||||
const remoteUrl =
|
||||
typeof cfg.gateway?.remote?.url === "string"
|
||||
? normalizeWsUrl(cfg.gateway.remote.url)
|
||||
: null;
|
||||
if (remoteUrl) {
|
||||
add({
|
||||
id: "configRemote",
|
||||
kind: "configRemote",
|
||||
url: remoteUrl,
|
||||
active: cfg.gateway?.mode === "remote",
|
||||
});
|
||||
}
|
||||
|
||||
const port = resolveGatewayPort(cfg);
|
||||
add({
|
||||
id: "localLoopback",
|
||||
kind: "localLoopback",
|
||||
url: `ws://127.0.0.1:${port}`,
|
||||
active: cfg.gateway?.mode !== "remote",
|
||||
});
|
||||
|
||||
return targets;
|
||||
}
|
||||
|
||||
export function resolveProbeBudgetMs(
|
||||
overallMs: number,
|
||||
kind: TargetKind,
|
||||
): number {
|
||||
if (kind === "localLoopback") return Math.min(800, overallMs);
|
||||
if (kind === "sshTunnel") return Math.min(2000, overallMs);
|
||||
return Math.min(1500, overallMs);
|
||||
}
|
||||
|
||||
export function sanitizeSshTarget(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return null;
|
||||
return trimmed.replace(/^ssh\\s+/, "");
|
||||
}
|
||||
|
||||
export function resolveAuthForTarget(
|
||||
cfg: ClawdbotConfig,
|
||||
target: GatewayStatusTarget,
|
||||
overrides: { token?: string; password?: string },
|
||||
): { token?: string; password?: string } {
|
||||
const tokenOverride = overrides.token?.trim()
|
||||
? overrides.token.trim()
|
||||
: undefined;
|
||||
const passwordOverride = overrides.password?.trim()
|
||||
? overrides.password.trim()
|
||||
: undefined;
|
||||
if (tokenOverride || passwordOverride) {
|
||||
return { token: tokenOverride, password: passwordOverride };
|
||||
}
|
||||
|
||||
if (target.kind === "configRemote") {
|
||||
const token =
|
||||
typeof cfg.gateway?.remote?.token === "string"
|
||||
? cfg.gateway.remote.token.trim()
|
||||
: "";
|
||||
const remotePassword = (
|
||||
cfg.gateway?.remote as { password?: unknown } | undefined
|
||||
)?.password;
|
||||
const password =
|
||||
typeof remotePassword === "string" ? remotePassword.trim() : "";
|
||||
return {
|
||||
token: token.length > 0 ? token : undefined,
|
||||
password: password.length > 0 ? password : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
const envToken = process.env.CLAWDBOT_GATEWAY_TOKEN?.trim() || "";
|
||||
const envPassword = process.env.CLAWDBOT_GATEWAY_PASSWORD?.trim() || "";
|
||||
const cfgToken =
|
||||
typeof cfg.gateway?.auth?.token === "string"
|
||||
? cfg.gateway.auth.token.trim()
|
||||
: "";
|
||||
const cfgPassword =
|
||||
typeof cfg.gateway?.auth?.password === "string"
|
||||
? cfg.gateway.auth.password.trim()
|
||||
: "";
|
||||
|
||||
return {
|
||||
token: envToken || cfgToken || undefined,
|
||||
password: envPassword || cfgPassword || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function pickGatewaySelfPresence(
|
||||
presence: unknown,
|
||||
): { host?: string; ip?: string; version?: string; platform?: string } | null {
|
||||
if (!Array.isArray(presence)) return null;
|
||||
const entries = presence as Array<Record<string, unknown>>;
|
||||
const self =
|
||||
entries.find((e) => e.mode === "gateway" && e.reason === "self") ??
|
||||
entries.find(
|
||||
(e) =>
|
||||
typeof e.text === "string" && String(e.text).startsWith("Gateway:"),
|
||||
) ??
|
||||
null;
|
||||
if (!self) return null;
|
||||
return {
|
||||
host: typeof self.host === "string" ? self.host : undefined,
|
||||
ip: typeof self.ip === "string" ? self.ip : undefined,
|
||||
version: typeof self.version === "string" ? self.version : undefined,
|
||||
platform: typeof self.platform === "string" ? self.platform : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function extractConfigSummary(
|
||||
snapshotUnknown: unknown,
|
||||
): GatewayConfigSummary {
|
||||
const snap = snapshotUnknown as Partial<ConfigFileSnapshot> | null;
|
||||
const path = typeof snap?.path === "string" ? snap.path : null;
|
||||
const exists = Boolean(snap?.exists);
|
||||
const valid = Boolean(snap?.valid);
|
||||
const issuesRaw = Array.isArray(snap?.issues) ? snap.issues : [];
|
||||
const legacyRaw = Array.isArray(snap?.legacyIssues) ? snap.legacyIssues : [];
|
||||
|
||||
const cfg = (snap?.config ?? {}) as Record<string, unknown>;
|
||||
const gateway = (cfg.gateway ?? {}) as Record<string, unknown>;
|
||||
const bridge = (cfg.bridge ?? {}) as Record<string, unknown>;
|
||||
const discovery = (cfg.discovery ?? {}) as Record<string, unknown>;
|
||||
const wideArea = (discovery.wideArea ?? {}) as Record<string, unknown>;
|
||||
|
||||
const remote = (gateway.remote ?? {}) as Record<string, unknown>;
|
||||
const auth = (gateway.auth ?? {}) as Record<string, unknown>;
|
||||
const controlUi = (gateway.controlUi ?? {}) as Record<string, unknown>;
|
||||
const tailscale = (gateway.tailscale ?? {}) as Record<string, unknown>;
|
||||
|
||||
const authMode = typeof auth.mode === "string" ? auth.mode : null;
|
||||
const authTokenConfigured =
|
||||
typeof auth.token === "string" ? auth.token.trim().length > 0 : false;
|
||||
const authPasswordConfigured =
|
||||
typeof auth.password === "string" ? auth.password.trim().length > 0 : false;
|
||||
|
||||
const remoteUrl =
|
||||
typeof remote.url === "string" ? normalizeWsUrl(remote.url) : null;
|
||||
const remoteTokenConfigured =
|
||||
typeof remote.token === "string" ? remote.token.trim().length > 0 : false;
|
||||
const remotePasswordConfigured =
|
||||
typeof remote.password === "string"
|
||||
? String(remote.password).trim().length > 0
|
||||
: false;
|
||||
|
||||
const bridgeEnabled =
|
||||
typeof bridge.enabled === "boolean" ? bridge.enabled : null;
|
||||
const bridgeBind = typeof bridge.bind === "string" ? bridge.bind : null;
|
||||
const bridgePort = parseIntOrNull(bridge.port);
|
||||
|
||||
const wideAreaEnabled =
|
||||
typeof wideArea.enabled === "boolean" ? wideArea.enabled : null;
|
||||
|
||||
return {
|
||||
path,
|
||||
exists,
|
||||
valid,
|
||||
issues: issuesRaw
|
||||
.filter((i): i is { path: string; message: string } =>
|
||||
Boolean(
|
||||
i && typeof i.path === "string" && typeof i.message === "string",
|
||||
),
|
||||
)
|
||||
.map((i) => ({ path: i.path, message: i.message })),
|
||||
legacyIssues: legacyRaw
|
||||
.filter((i): i is { path: string; message: string } =>
|
||||
Boolean(
|
||||
i && typeof i.path === "string" && typeof i.message === "string",
|
||||
),
|
||||
)
|
||||
.map((i) => ({ path: i.path, message: i.message })),
|
||||
gateway: {
|
||||
mode: typeof gateway.mode === "string" ? gateway.mode : null,
|
||||
bind: typeof gateway.bind === "string" ? gateway.bind : null,
|
||||
port: parseIntOrNull(gateway.port),
|
||||
controlUiEnabled:
|
||||
typeof controlUi.enabled === "boolean" ? controlUi.enabled : null,
|
||||
controlUiBasePath:
|
||||
typeof controlUi.basePath === "string" ? controlUi.basePath : null,
|
||||
authMode,
|
||||
authTokenConfigured,
|
||||
authPasswordConfigured,
|
||||
remoteUrl,
|
||||
remoteTokenConfigured,
|
||||
remotePasswordConfigured,
|
||||
tailscaleMode: typeof tailscale.mode === "string" ? tailscale.mode : null,
|
||||
},
|
||||
bridge: { enabled: bridgeEnabled, bind: bridgeBind, port: bridgePort },
|
||||
discovery: { wideAreaEnabled },
|
||||
};
|
||||
}
|
||||
|
||||
export function buildNetworkHints(cfg: ClawdbotConfig) {
|
||||
const tailnetIPv4 = pickPrimaryTailnetIPv4();
|
||||
const port = resolveGatewayPort(cfg);
|
||||
return {
|
||||
localLoopbackUrl: `ws://127.0.0.1:${port}`,
|
||||
localTailnetUrl: tailnetIPv4 ? `ws://${tailnetIPv4}:${port}` : null,
|
||||
tailnetIPv4: tailnetIPv4 ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function renderTargetHeader(target: GatewayStatusTarget, rich: boolean) {
|
||||
const kindLabel =
|
||||
target.kind === "localLoopback"
|
||||
? "Local loopback"
|
||||
: target.kind === "sshTunnel"
|
||||
? "Remote over SSH"
|
||||
: target.kind === "configRemote"
|
||||
? target.active
|
||||
? "Remote (configured)"
|
||||
: "Remote (configured, inactive)"
|
||||
: "URL (explicit)";
|
||||
return `${colorize(rich, theme.heading, kindLabel)} ${colorize(rich, theme.muted, target.url)}`;
|
||||
}
|
||||
|
||||
export function renderProbeSummaryLine(
|
||||
probe: GatewayProbeResult,
|
||||
rich: boolean,
|
||||
) {
|
||||
if (probe.ok) {
|
||||
const latency =
|
||||
typeof probe.connectLatencyMs === "number"
|
||||
? `${probe.connectLatencyMs}ms`
|
||||
: "unknown";
|
||||
return `${colorize(rich, theme.success, "Connect: ok")} (${latency}) · ${colorize(rich, theme.success, "RPC: ok")}`;
|
||||
}
|
||||
|
||||
const detail = probe.error ? ` - ${probe.error}` : "";
|
||||
if (probe.connectLatencyMs != null) {
|
||||
const latency =
|
||||
typeof probe.connectLatencyMs === "number"
|
||||
? `${probe.connectLatencyMs}ms`
|
||||
: "unknown";
|
||||
return `${colorize(rich, theme.success, "Connect: ok")} (${latency}) · ${colorize(rich, theme.error, "RPC: failed")}${detail}`;
|
||||
}
|
||||
|
||||
return `${colorize(rich, theme.error, "Connect: failed")}${detail}`;
|
||||
}
|
||||
71
src/commands/onboard-non-interactive/api-keys.ts
Normal file
71
src/commands/onboard-non-interactive/api-keys.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import {
|
||||
ensureAuthProfileStore,
|
||||
resolveApiKeyForProfile,
|
||||
resolveAuthProfileOrder,
|
||||
} from "../../agents/auth-profiles.js";
|
||||
import { resolveEnvApiKey } from "../../agents/model-auth.js";
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import type { RuntimeEnv } from "../../runtime.js";
|
||||
|
||||
export type NonInteractiveApiKeySource = "flag" | "env" | "profile";
|
||||
|
||||
async function resolveApiKeyFromProfiles(params: {
|
||||
provider: string;
|
||||
cfg: ClawdbotConfig;
|
||||
agentDir?: string;
|
||||
}): Promise<string | null> {
|
||||
const store = ensureAuthProfileStore(params.agentDir);
|
||||
const order = resolveAuthProfileOrder({
|
||||
cfg: params.cfg,
|
||||
store,
|
||||
provider: params.provider,
|
||||
});
|
||||
for (const profileId of order) {
|
||||
const cred = store.profiles[profileId];
|
||||
if (cred?.type !== "api_key") continue;
|
||||
const resolved = await resolveApiKeyForProfile({
|
||||
cfg: params.cfg,
|
||||
store,
|
||||
profileId,
|
||||
agentDir: params.agentDir,
|
||||
});
|
||||
if (resolved?.apiKey) return resolved.apiKey;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function resolveNonInteractiveApiKey(params: {
|
||||
provider: string;
|
||||
cfg: ClawdbotConfig;
|
||||
flagValue?: string;
|
||||
flagName: string;
|
||||
envVar: string;
|
||||
runtime: RuntimeEnv;
|
||||
agentDir?: string;
|
||||
allowProfile?: boolean;
|
||||
}): Promise<{ key: string; source: NonInteractiveApiKeySource } | null> {
|
||||
const flagKey = params.flagValue?.trim();
|
||||
if (flagKey) return { key: flagKey, source: "flag" };
|
||||
|
||||
const envResolved = resolveEnvApiKey(params.provider);
|
||||
if (envResolved?.apiKey) return { key: envResolved.apiKey, source: "env" };
|
||||
|
||||
if (params.allowProfile ?? true) {
|
||||
const profileKey = await resolveApiKeyFromProfiles({
|
||||
provider: params.provider,
|
||||
cfg: params.cfg,
|
||||
agentDir: params.agentDir,
|
||||
});
|
||||
if (profileKey) return { key: profileKey, source: "profile" };
|
||||
}
|
||||
|
||||
const profileHint =
|
||||
params.allowProfile === false
|
||||
? ""
|
||||
: `, or existing ${params.provider} API-key profile`;
|
||||
params.runtime.error(
|
||||
`Missing ${params.flagName} (or ${params.envVar} in env${profileHint}).`,
|
||||
);
|
||||
params.runtime.exit(1);
|
||||
return null;
|
||||
}
|
||||
117
src/commands/onboard-non-interactive/local.ts
Normal file
117
src/commands/onboard-non-interactive/local.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import {
|
||||
CONFIG_PATH_CLAWDBOT,
|
||||
resolveGatewayPort,
|
||||
writeConfigFile,
|
||||
} from "../../config/config.js";
|
||||
import type { RuntimeEnv } from "../../runtime.js";
|
||||
import { sleep } from "../../utils.js";
|
||||
import { DEFAULT_GATEWAY_DAEMON_RUNTIME } from "../daemon-runtime.js";
|
||||
import { healthCommand } from "../health.js";
|
||||
import {
|
||||
applyWizardMetadata,
|
||||
DEFAULT_WORKSPACE,
|
||||
ensureWorkspaceAndSessions,
|
||||
} from "../onboard-helpers.js";
|
||||
import type { OnboardOptions } from "../onboard-types.js";
|
||||
|
||||
import { applyNonInteractiveAuthChoice } from "./local/auth-choice.js";
|
||||
import { installGatewayDaemonNonInteractive } from "./local/daemon-install.js";
|
||||
import { applyNonInteractiveGatewayConfig } from "./local/gateway-config.js";
|
||||
import { logNonInteractiveOnboardingJson } from "./local/output.js";
|
||||
import { applyNonInteractiveSkillsConfig } from "./local/skills-config.js";
|
||||
import { resolveNonInteractiveWorkspaceDir } from "./local/workspace.js";
|
||||
|
||||
export async function runNonInteractiveOnboardingLocal(params: {
|
||||
opts: OnboardOptions;
|
||||
runtime: RuntimeEnv;
|
||||
baseConfig: ClawdbotConfig;
|
||||
}) {
|
||||
const { opts, runtime, baseConfig } = params;
|
||||
const mode = "local" as const;
|
||||
|
||||
const workspaceDir = resolveNonInteractiveWorkspaceDir({
|
||||
opts,
|
||||
baseConfig,
|
||||
defaultWorkspaceDir: DEFAULT_WORKSPACE,
|
||||
});
|
||||
|
||||
let nextConfig: ClawdbotConfig = {
|
||||
...baseConfig,
|
||||
agents: {
|
||||
...baseConfig.agents,
|
||||
defaults: {
|
||||
...baseConfig.agents?.defaults,
|
||||
workspace: workspaceDir,
|
||||
},
|
||||
},
|
||||
gateway: {
|
||||
...baseConfig.gateway,
|
||||
mode: "local",
|
||||
},
|
||||
};
|
||||
|
||||
const authChoice = opts.authChoice ?? "skip";
|
||||
const nextConfigAfterAuth = await applyNonInteractiveAuthChoice({
|
||||
nextConfig,
|
||||
authChoice,
|
||||
opts,
|
||||
runtime,
|
||||
baseConfig,
|
||||
});
|
||||
if (!nextConfigAfterAuth) return;
|
||||
nextConfig = nextConfigAfterAuth;
|
||||
|
||||
const gatewayBasePort = resolveGatewayPort(baseConfig);
|
||||
const gatewayResult = applyNonInteractiveGatewayConfig({
|
||||
nextConfig,
|
||||
opts,
|
||||
runtime,
|
||||
defaultPort: gatewayBasePort,
|
||||
});
|
||||
if (!gatewayResult) return;
|
||||
nextConfig = gatewayResult.nextConfig;
|
||||
|
||||
nextConfig = applyNonInteractiveSkillsConfig({ nextConfig, opts, runtime });
|
||||
|
||||
nextConfig = applyWizardMetadata(nextConfig, { command: "onboard", mode });
|
||||
await writeConfigFile(nextConfig);
|
||||
runtime.log(`Updated ${CONFIG_PATH_CLAWDBOT}`);
|
||||
|
||||
await ensureWorkspaceAndSessions(workspaceDir, runtime, {
|
||||
skipBootstrap: Boolean(nextConfig.agents?.defaults?.skipBootstrap),
|
||||
});
|
||||
|
||||
await installGatewayDaemonNonInteractive({
|
||||
nextConfig,
|
||||
opts,
|
||||
runtime,
|
||||
port: gatewayResult.port,
|
||||
gatewayToken: gatewayResult.gatewayToken,
|
||||
});
|
||||
|
||||
const daemonRuntimeRaw = opts.daemonRuntime ?? DEFAULT_GATEWAY_DAEMON_RUNTIME;
|
||||
if (!opts.skipHealth) {
|
||||
await sleep(1000);
|
||||
// Health check runs against the gateway; small delay avoids flakiness during install/start.
|
||||
await healthCommand({ json: false, timeoutMs: 10_000 }, runtime);
|
||||
}
|
||||
|
||||
logNonInteractiveOnboardingJson({
|
||||
opts,
|
||||
runtime,
|
||||
mode,
|
||||
workspaceDir,
|
||||
authChoice,
|
||||
gateway: {
|
||||
port: gatewayResult.port,
|
||||
bind: gatewayResult.bind,
|
||||
authMode: gatewayResult.authMode,
|
||||
tailscaleMode: gatewayResult.tailscaleMode,
|
||||
},
|
||||
installDaemon: Boolean(opts.installDaemon),
|
||||
daemonRuntime: opts.installDaemon ? daemonRuntimeRaw : undefined,
|
||||
skipSkills: Boolean(opts.skipSkills),
|
||||
skipHealth: Boolean(opts.skipHealth),
|
||||
});
|
||||
}
|
||||
276
src/commands/onboard-non-interactive/local/auth-choice.ts
Normal file
276
src/commands/onboard-non-interactive/local/auth-choice.ts
Normal file
@@ -0,0 +1,276 @@
|
||||
import {
|
||||
CLAUDE_CLI_PROFILE_ID,
|
||||
CODEX_CLI_PROFILE_ID,
|
||||
ensureAuthProfileStore,
|
||||
} from "../../../agents/auth-profiles.js";
|
||||
import type { ClawdbotConfig } from "../../../config/config.js";
|
||||
import { upsertSharedEnvVar } from "../../../infra/env-file.js";
|
||||
import type { RuntimeEnv } from "../../../runtime.js";
|
||||
import { applyGoogleGeminiModelDefault } from "../../google-gemini-model-default.js";
|
||||
import {
|
||||
applyAuthProfileConfig,
|
||||
applyMinimaxApiConfig,
|
||||
applyMinimaxConfig,
|
||||
applyMoonshotConfig,
|
||||
applyOpencodeZenConfig,
|
||||
applyOpenrouterConfig,
|
||||
applySyntheticConfig,
|
||||
applyZaiConfig,
|
||||
setAnthropicApiKey,
|
||||
setGeminiApiKey,
|
||||
setMinimaxApiKey,
|
||||
setMoonshotApiKey,
|
||||
setOpencodeZenApiKey,
|
||||
setOpenrouterApiKey,
|
||||
setSyntheticApiKey,
|
||||
setZaiApiKey,
|
||||
} from "../../onboard-auth.js";
|
||||
import type { AuthChoice, OnboardOptions } from "../../onboard-types.js";
|
||||
import { applyOpenAICodexModelDefault } from "../../openai-codex-model-default.js";
|
||||
|
||||
import { resolveNonInteractiveApiKey } from "../api-keys.js";
|
||||
|
||||
export async function applyNonInteractiveAuthChoice(params: {
|
||||
nextConfig: ClawdbotConfig;
|
||||
authChoice: AuthChoice;
|
||||
opts: OnboardOptions;
|
||||
runtime: RuntimeEnv;
|
||||
baseConfig: ClawdbotConfig;
|
||||
}): Promise<ClawdbotConfig | null> {
|
||||
const { authChoice, opts, runtime, baseConfig } = params;
|
||||
let nextConfig = params.nextConfig;
|
||||
|
||||
if (authChoice === "apiKey") {
|
||||
const resolved = await resolveNonInteractiveApiKey({
|
||||
provider: "anthropic",
|
||||
cfg: baseConfig,
|
||||
flagValue: opts.anthropicApiKey,
|
||||
flagName: "--anthropic-api-key",
|
||||
envVar: "ANTHROPIC_API_KEY",
|
||||
runtime,
|
||||
});
|
||||
if (!resolved) return null;
|
||||
if (resolved.source !== "profile") await setAnthropicApiKey(resolved.key);
|
||||
return applyAuthProfileConfig(nextConfig, {
|
||||
profileId: "anthropic:default",
|
||||
provider: "anthropic",
|
||||
mode: "api_key",
|
||||
});
|
||||
}
|
||||
|
||||
if (authChoice === "gemini-api-key") {
|
||||
const resolved = await resolveNonInteractiveApiKey({
|
||||
provider: "google",
|
||||
cfg: baseConfig,
|
||||
flagValue: opts.geminiApiKey,
|
||||
flagName: "--gemini-api-key",
|
||||
envVar: "GEMINI_API_KEY",
|
||||
runtime,
|
||||
});
|
||||
if (!resolved) return null;
|
||||
if (resolved.source !== "profile") await setGeminiApiKey(resolved.key);
|
||||
nextConfig = applyAuthProfileConfig(nextConfig, {
|
||||
profileId: "google:default",
|
||||
provider: "google",
|
||||
mode: "api_key",
|
||||
});
|
||||
return applyGoogleGeminiModelDefault(nextConfig).next;
|
||||
}
|
||||
|
||||
if (authChoice === "zai-api-key") {
|
||||
const resolved = await resolveNonInteractiveApiKey({
|
||||
provider: "zai",
|
||||
cfg: baseConfig,
|
||||
flagValue: opts.zaiApiKey,
|
||||
flagName: "--zai-api-key",
|
||||
envVar: "ZAI_API_KEY",
|
||||
runtime,
|
||||
});
|
||||
if (!resolved) return null;
|
||||
if (resolved.source !== "profile") await setZaiApiKey(resolved.key);
|
||||
nextConfig = applyAuthProfileConfig(nextConfig, {
|
||||
profileId: "zai:default",
|
||||
provider: "zai",
|
||||
mode: "api_key",
|
||||
});
|
||||
return applyZaiConfig(nextConfig);
|
||||
}
|
||||
|
||||
if (authChoice === "openai-api-key") {
|
||||
const resolved = await resolveNonInteractiveApiKey({
|
||||
provider: "openai",
|
||||
cfg: baseConfig,
|
||||
flagValue: opts.openaiApiKey,
|
||||
flagName: "--openai-api-key",
|
||||
envVar: "OPENAI_API_KEY",
|
||||
runtime,
|
||||
allowProfile: false,
|
||||
});
|
||||
if (!resolved) return null;
|
||||
const key = resolved.key;
|
||||
const result = upsertSharedEnvVar({ key: "OPENAI_API_KEY", value: key });
|
||||
process.env.OPENAI_API_KEY = key;
|
||||
runtime.log(`Saved OPENAI_API_KEY to ${result.path}`);
|
||||
return nextConfig;
|
||||
}
|
||||
|
||||
if (authChoice === "openrouter-api-key") {
|
||||
const resolved = await resolveNonInteractiveApiKey({
|
||||
provider: "openrouter",
|
||||
cfg: baseConfig,
|
||||
flagValue: opts.openrouterApiKey,
|
||||
flagName: "--openrouter-api-key",
|
||||
envVar: "OPENROUTER_API_KEY",
|
||||
runtime,
|
||||
});
|
||||
if (!resolved) return null;
|
||||
if (resolved.source !== "profile") await setOpenrouterApiKey(resolved.key);
|
||||
nextConfig = applyAuthProfileConfig(nextConfig, {
|
||||
profileId: "openrouter:default",
|
||||
provider: "openrouter",
|
||||
mode: "api_key",
|
||||
});
|
||||
return applyOpenrouterConfig(nextConfig);
|
||||
}
|
||||
|
||||
if (authChoice === "moonshot-api-key") {
|
||||
const resolved = await resolveNonInteractiveApiKey({
|
||||
provider: "moonshot",
|
||||
cfg: baseConfig,
|
||||
flagValue: opts.moonshotApiKey,
|
||||
flagName: "--moonshot-api-key",
|
||||
envVar: "MOONSHOT_API_KEY",
|
||||
runtime,
|
||||
});
|
||||
if (!resolved) return null;
|
||||
if (resolved.source !== "profile") await setMoonshotApiKey(resolved.key);
|
||||
nextConfig = applyAuthProfileConfig(nextConfig, {
|
||||
profileId: "moonshot:default",
|
||||
provider: "moonshot",
|
||||
mode: "api_key",
|
||||
});
|
||||
return applyMoonshotConfig(nextConfig);
|
||||
}
|
||||
|
||||
if (authChoice === "synthetic-api-key") {
|
||||
const resolved = await resolveNonInteractiveApiKey({
|
||||
provider: "synthetic",
|
||||
cfg: baseConfig,
|
||||
flagValue: opts.syntheticApiKey,
|
||||
flagName: "--synthetic-api-key",
|
||||
envVar: "SYNTHETIC_API_KEY",
|
||||
runtime,
|
||||
});
|
||||
if (!resolved) return null;
|
||||
if (resolved.source !== "profile") await setSyntheticApiKey(resolved.key);
|
||||
nextConfig = applyAuthProfileConfig(nextConfig, {
|
||||
profileId: "synthetic:default",
|
||||
provider: "synthetic",
|
||||
mode: "api_key",
|
||||
});
|
||||
return applySyntheticConfig(nextConfig);
|
||||
}
|
||||
|
||||
if (
|
||||
authChoice === "minimax-cloud" ||
|
||||
authChoice === "minimax-api" ||
|
||||
authChoice === "minimax-api-lightning"
|
||||
) {
|
||||
const resolved = await resolveNonInteractiveApiKey({
|
||||
provider: "minimax",
|
||||
cfg: baseConfig,
|
||||
flagValue: opts.minimaxApiKey,
|
||||
flagName: "--minimax-api-key",
|
||||
envVar: "MINIMAX_API_KEY",
|
||||
runtime,
|
||||
});
|
||||
if (!resolved) return null;
|
||||
if (resolved.source !== "profile") await setMinimaxApiKey(resolved.key);
|
||||
nextConfig = applyAuthProfileConfig(nextConfig, {
|
||||
profileId: "minimax:default",
|
||||
provider: "minimax",
|
||||
mode: "api_key",
|
||||
});
|
||||
const modelId =
|
||||
authChoice === "minimax-api-lightning"
|
||||
? "MiniMax-M2.1-lightning"
|
||||
: "MiniMax-M2.1";
|
||||
return applyMinimaxApiConfig(nextConfig, modelId);
|
||||
}
|
||||
|
||||
if (authChoice === "claude-cli") {
|
||||
const store = ensureAuthProfileStore(undefined, {
|
||||
allowKeychainPrompt: false,
|
||||
});
|
||||
if (!store.profiles[CLAUDE_CLI_PROFILE_ID]) {
|
||||
runtime.error(
|
||||
process.platform === "darwin"
|
||||
? 'No Claude CLI credentials found. Run interactive onboarding to approve Keychain access for "Claude Code-credentials".'
|
||||
: "No Claude CLI credentials found at ~/.claude/.credentials.json",
|
||||
);
|
||||
runtime.exit(1);
|
||||
return null;
|
||||
}
|
||||
return applyAuthProfileConfig(nextConfig, {
|
||||
profileId: CLAUDE_CLI_PROFILE_ID,
|
||||
provider: "anthropic",
|
||||
mode: "token",
|
||||
});
|
||||
}
|
||||
|
||||
if (authChoice === "codex-cli") {
|
||||
const store = ensureAuthProfileStore();
|
||||
if (!store.profiles[CODEX_CLI_PROFILE_ID]) {
|
||||
runtime.error("No Codex CLI credentials found at ~/.codex/auth.json");
|
||||
runtime.exit(1);
|
||||
return null;
|
||||
}
|
||||
nextConfig = applyAuthProfileConfig(nextConfig, {
|
||||
profileId: CODEX_CLI_PROFILE_ID,
|
||||
provider: "openai-codex",
|
||||
mode: "oauth",
|
||||
});
|
||||
return applyOpenAICodexModelDefault(nextConfig).next;
|
||||
}
|
||||
|
||||
if (authChoice === "minimax") return applyMinimaxConfig(nextConfig);
|
||||
|
||||
if (authChoice === "opencode-zen") {
|
||||
const resolved = await resolveNonInteractiveApiKey({
|
||||
provider: "opencode",
|
||||
cfg: baseConfig,
|
||||
flagValue: opts.opencodeZenApiKey,
|
||||
flagName: "--opencode-zen-api-key",
|
||||
envVar: "OPENCODE_API_KEY (or OPENCODE_ZEN_API_KEY)",
|
||||
runtime,
|
||||
});
|
||||
if (!resolved) return null;
|
||||
if (resolved.source !== "profile") await setOpencodeZenApiKey(resolved.key);
|
||||
nextConfig = applyAuthProfileConfig(nextConfig, {
|
||||
profileId: "opencode:default",
|
||||
provider: "opencode",
|
||||
mode: "api_key",
|
||||
});
|
||||
return applyOpencodeZenConfig(nextConfig);
|
||||
}
|
||||
|
||||
if (
|
||||
authChoice === "token" ||
|
||||
authChoice === "oauth" ||
|
||||
authChoice === "chutes" ||
|
||||
authChoice === "openai-codex" ||
|
||||
authChoice === "antigravity"
|
||||
) {
|
||||
const label =
|
||||
authChoice === "antigravity"
|
||||
? "Antigravity"
|
||||
: authChoice === "token"
|
||||
? "Token"
|
||||
: "OAuth";
|
||||
runtime.error(`${label} requires interactive mode.`);
|
||||
runtime.exit(1);
|
||||
return null;
|
||||
}
|
||||
|
||||
return nextConfig;
|
||||
}
|
||||
87
src/commands/onboard-non-interactive/local/daemon-install.ts
Normal file
87
src/commands/onboard-non-interactive/local/daemon-install.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import path from "node:path";
|
||||
|
||||
import type { ClawdbotConfig } from "../../../config/config.js";
|
||||
import { resolveGatewayLaunchAgentLabel } from "../../../daemon/constants.js";
|
||||
import { resolveGatewayProgramArguments } from "../../../daemon/program-args.js";
|
||||
import {
|
||||
renderSystemNodeWarning,
|
||||
resolvePreferredNodePath,
|
||||
resolveSystemNodeInfo,
|
||||
} from "../../../daemon/runtime-paths.js";
|
||||
import { resolveGatewayService } from "../../../daemon/service.js";
|
||||
import { buildServiceEnvironment } from "../../../daemon/service-env.js";
|
||||
import { isSystemdUserServiceAvailable } from "../../../daemon/systemd.js";
|
||||
import type { RuntimeEnv } from "../../../runtime.js";
|
||||
import {
|
||||
DEFAULT_GATEWAY_DAEMON_RUNTIME,
|
||||
isGatewayDaemonRuntime,
|
||||
} from "../../daemon-runtime.js";
|
||||
import type { OnboardOptions } from "../../onboard-types.js";
|
||||
import { ensureSystemdUserLingerNonInteractive } from "../../systemd-linger.js";
|
||||
|
||||
export async function installGatewayDaemonNonInteractive(params: {
|
||||
nextConfig: ClawdbotConfig;
|
||||
opts: OnboardOptions;
|
||||
runtime: RuntimeEnv;
|
||||
port: number;
|
||||
gatewayToken?: string;
|
||||
}) {
|
||||
const { opts, runtime, port, gatewayToken } = params;
|
||||
if (!opts.installDaemon) return;
|
||||
|
||||
const daemonRuntimeRaw = opts.daemonRuntime ?? DEFAULT_GATEWAY_DAEMON_RUNTIME;
|
||||
const systemdAvailable =
|
||||
process.platform === "linux" ? await isSystemdUserServiceAvailable() : true;
|
||||
if (process.platform === "linux" && !systemdAvailable) {
|
||||
runtime.log(
|
||||
"Systemd user services are unavailable; skipping daemon install.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isGatewayDaemonRuntime(daemonRuntimeRaw)) {
|
||||
runtime.error("Invalid --daemon-runtime (use node or bun)");
|
||||
runtime.exit(1);
|
||||
return;
|
||||
}
|
||||
|
||||
const service = resolveGatewayService();
|
||||
const devMode =
|
||||
process.argv[1]?.includes(`${path.sep}src${path.sep}`) &&
|
||||
process.argv[1]?.endsWith(".ts");
|
||||
const nodePath = await resolvePreferredNodePath({
|
||||
env: process.env,
|
||||
runtime: daemonRuntimeRaw,
|
||||
});
|
||||
const { programArguments, workingDirectory } =
|
||||
await resolveGatewayProgramArguments({
|
||||
port,
|
||||
dev: devMode,
|
||||
runtime: daemonRuntimeRaw,
|
||||
nodePath,
|
||||
});
|
||||
|
||||
if (daemonRuntimeRaw === "node") {
|
||||
const systemNode = await resolveSystemNodeInfo({ env: process.env });
|
||||
const warning = renderSystemNodeWarning(systemNode, programArguments[0]);
|
||||
if (warning) runtime.log(warning);
|
||||
}
|
||||
|
||||
const environment = buildServiceEnvironment({
|
||||
env: process.env,
|
||||
port,
|
||||
token: gatewayToken,
|
||||
launchdLabel:
|
||||
process.platform === "darwin"
|
||||
? resolveGatewayLaunchAgentLabel(process.env.CLAWDBOT_PROFILE)
|
||||
: undefined,
|
||||
});
|
||||
await service.install({
|
||||
env: process.env,
|
||||
stdout: process.stdout,
|
||||
programArguments,
|
||||
workingDirectory,
|
||||
environment,
|
||||
});
|
||||
await ensureSystemdUserLingerNonInteractive({ runtime });
|
||||
}
|
||||
110
src/commands/onboard-non-interactive/local/gateway-config.ts
Normal file
110
src/commands/onboard-non-interactive/local/gateway-config.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
import type { ClawdbotConfig } from "../../../config/config.js";
|
||||
import type { RuntimeEnv } from "../../../runtime.js";
|
||||
import { randomToken } from "../../onboard-helpers.js";
|
||||
import type { OnboardOptions } from "../../onboard-types.js";
|
||||
|
||||
export function applyNonInteractiveGatewayConfig(params: {
|
||||
nextConfig: ClawdbotConfig;
|
||||
opts: OnboardOptions;
|
||||
runtime: RuntimeEnv;
|
||||
defaultPort: number;
|
||||
}): {
|
||||
nextConfig: ClawdbotConfig;
|
||||
port: number;
|
||||
bind: string;
|
||||
authMode: string;
|
||||
tailscaleMode: string;
|
||||
tailscaleResetOnExit: boolean;
|
||||
gatewayToken?: string;
|
||||
} | null {
|
||||
const { opts, runtime } = params;
|
||||
|
||||
const hasGatewayPort = opts.gatewayPort !== undefined;
|
||||
if (
|
||||
hasGatewayPort &&
|
||||
(!Number.isFinite(opts.gatewayPort) || (opts.gatewayPort ?? 0) <= 0)
|
||||
) {
|
||||
runtime.error("Invalid --gateway-port");
|
||||
runtime.exit(1);
|
||||
return null;
|
||||
}
|
||||
|
||||
const port = hasGatewayPort
|
||||
? (opts.gatewayPort as number)
|
||||
: params.defaultPort;
|
||||
let bind = opts.gatewayBind ?? "loopback";
|
||||
let authMode = opts.gatewayAuth ?? "token";
|
||||
const tailscaleMode = opts.tailscale ?? "off";
|
||||
const tailscaleResetOnExit = Boolean(opts.tailscaleResetOnExit);
|
||||
|
||||
// Tighten config to safe combos:
|
||||
// - If Tailscale is on, force loopback bind (the tunnel handles external access).
|
||||
// - If binding beyond loopback, disallow auth=off.
|
||||
// - If using Tailscale Funnel, require password auth.
|
||||
if (tailscaleMode !== "off" && bind !== "loopback") bind = "loopback";
|
||||
if (authMode === "off" && bind !== "loopback") authMode = "token";
|
||||
if (tailscaleMode === "funnel" && authMode !== "password")
|
||||
authMode = "password";
|
||||
|
||||
let nextConfig = params.nextConfig;
|
||||
let gatewayToken = opts.gatewayToken?.trim() || undefined;
|
||||
|
||||
if (authMode === "token") {
|
||||
if (!gatewayToken) gatewayToken = randomToken();
|
||||
nextConfig = {
|
||||
...nextConfig,
|
||||
gateway: {
|
||||
...nextConfig.gateway,
|
||||
auth: {
|
||||
...nextConfig.gateway?.auth,
|
||||
mode: "token",
|
||||
token: gatewayToken,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (authMode === "password") {
|
||||
const password = opts.gatewayPassword?.trim();
|
||||
if (!password) {
|
||||
runtime.error("Missing --gateway-password for password auth.");
|
||||
runtime.exit(1);
|
||||
return null;
|
||||
}
|
||||
nextConfig = {
|
||||
...nextConfig,
|
||||
gateway: {
|
||||
...nextConfig.gateway,
|
||||
auth: {
|
||||
...nextConfig.gateway?.auth,
|
||||
mode: "password",
|
||||
password,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
nextConfig = {
|
||||
...nextConfig,
|
||||
gateway: {
|
||||
...nextConfig.gateway,
|
||||
port,
|
||||
bind,
|
||||
tailscale: {
|
||||
...nextConfig.gateway?.tailscale,
|
||||
mode: tailscaleMode,
|
||||
resetOnExit: tailscaleResetOnExit,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
nextConfig,
|
||||
port,
|
||||
bind,
|
||||
authMode,
|
||||
tailscaleMode,
|
||||
tailscaleResetOnExit,
|
||||
gatewayToken,
|
||||
};
|
||||
}
|
||||
38
src/commands/onboard-non-interactive/local/output.ts
Normal file
38
src/commands/onboard-non-interactive/local/output.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import type { RuntimeEnv } from "../../../runtime.js";
|
||||
import type { OnboardOptions } from "../../onboard-types.js";
|
||||
|
||||
export function logNonInteractiveOnboardingJson(params: {
|
||||
opts: OnboardOptions;
|
||||
runtime: RuntimeEnv;
|
||||
mode: "local" | "remote";
|
||||
workspaceDir?: string;
|
||||
authChoice?: string;
|
||||
gateway?: {
|
||||
port: number;
|
||||
bind: string;
|
||||
authMode: string;
|
||||
tailscaleMode: string;
|
||||
};
|
||||
installDaemon?: boolean;
|
||||
daemonRuntime?: string;
|
||||
skipSkills?: boolean;
|
||||
skipHealth?: boolean;
|
||||
}) {
|
||||
if (!params.opts.json) return;
|
||||
params.runtime.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
mode: params.mode,
|
||||
workspace: params.workspaceDir,
|
||||
authChoice: params.authChoice,
|
||||
gateway: params.gateway,
|
||||
installDaemon: Boolean(params.installDaemon),
|
||||
daemonRuntime: params.daemonRuntime,
|
||||
skipSkills: Boolean(params.skipSkills),
|
||||
skipHealth: Boolean(params.skipHealth),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
}
|
||||
29
src/commands/onboard-non-interactive/local/skills-config.ts
Normal file
29
src/commands/onboard-non-interactive/local/skills-config.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import type { ClawdbotConfig } from "../../../config/config.js";
|
||||
import type { RuntimeEnv } from "../../../runtime.js";
|
||||
import type { OnboardOptions } from "../../onboard-types.js";
|
||||
|
||||
export function applyNonInteractiveSkillsConfig(params: {
|
||||
nextConfig: ClawdbotConfig;
|
||||
opts: OnboardOptions;
|
||||
runtime: RuntimeEnv;
|
||||
}) {
|
||||
const { nextConfig, opts, runtime } = params;
|
||||
if (opts.skipSkills) return nextConfig;
|
||||
|
||||
const nodeManager = opts.nodeManager ?? "npm";
|
||||
if (!["npm", "pnpm", "bun"].includes(nodeManager)) {
|
||||
runtime.error("Invalid --node-manager (use npm, pnpm, or bun)");
|
||||
runtime.exit(1);
|
||||
return nextConfig;
|
||||
}
|
||||
return {
|
||||
...nextConfig,
|
||||
skills: {
|
||||
...nextConfig.skills,
|
||||
install: {
|
||||
...nextConfig.skills?.install,
|
||||
nodeManager,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
16
src/commands/onboard-non-interactive/local/workspace.ts
Normal file
16
src/commands/onboard-non-interactive/local/workspace.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import type { ClawdbotConfig } from "../../../config/config.js";
|
||||
import { resolveUserPath } from "../../../utils.js";
|
||||
import type { OnboardOptions } from "../../onboard-types.js";
|
||||
|
||||
export function resolveNonInteractiveWorkspaceDir(params: {
|
||||
opts: OnboardOptions;
|
||||
baseConfig: ClawdbotConfig;
|
||||
defaultWorkspaceDir: string;
|
||||
}) {
|
||||
const raw = (
|
||||
params.opts.workspace ??
|
||||
params.baseConfig.agents?.defaults?.workspace ??
|
||||
params.defaultWorkspaceDir
|
||||
).trim();
|
||||
return resolveUserPath(raw);
|
||||
}
|
||||
48
src/commands/onboard-non-interactive/remote.ts
Normal file
48
src/commands/onboard-non-interactive/remote.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import type { ClawdbotConfig } from "../../config/config.js";
|
||||
import { CONFIG_PATH_CLAWDBOT, writeConfigFile } from "../../config/config.js";
|
||||
import type { RuntimeEnv } from "../../runtime.js";
|
||||
import { applyWizardMetadata } from "../onboard-helpers.js";
|
||||
import type { OnboardOptions } from "../onboard-types.js";
|
||||
|
||||
export async function runNonInteractiveOnboardingRemote(params: {
|
||||
opts: OnboardOptions;
|
||||
runtime: RuntimeEnv;
|
||||
baseConfig: ClawdbotConfig;
|
||||
}) {
|
||||
const { opts, runtime, baseConfig } = params;
|
||||
const mode = "remote" as const;
|
||||
|
||||
const remoteUrl = opts.remoteUrl?.trim();
|
||||
if (!remoteUrl) {
|
||||
runtime.error("Missing --remote-url for remote mode.");
|
||||
runtime.exit(1);
|
||||
return;
|
||||
}
|
||||
|
||||
let nextConfig: ClawdbotConfig = {
|
||||
...baseConfig,
|
||||
gateway: {
|
||||
...baseConfig.gateway,
|
||||
mode: "remote",
|
||||
remote: {
|
||||
url: remoteUrl,
|
||||
token: opts.remoteToken?.trim() || undefined,
|
||||
},
|
||||
},
|
||||
};
|
||||
nextConfig = applyWizardMetadata(nextConfig, { command: "onboard", mode });
|
||||
await writeConfigFile(nextConfig);
|
||||
runtime.log(`Updated ${CONFIG_PATH_CLAWDBOT}`);
|
||||
|
||||
const payload = {
|
||||
mode,
|
||||
remoteUrl,
|
||||
auth: opts.remoteToken ? "token" : "none",
|
||||
};
|
||||
if (opts.json) {
|
||||
runtime.log(JSON.stringify(payload, null, 2));
|
||||
} else {
|
||||
runtime.log(`Remote gateway: ${remoteUrl}`);
|
||||
runtime.log(`Auth: ${payload.auth}`);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user