refactor(infra): deslop infra (#157048)

* refactor(infra): deslop infra

* refactor(infra): retain guarded source boundaries
This commit is contained in:
Peter Steinberger 2026-09-24 00:31:05 -07:00 • committed by GitHub
parent 23f5c67633
commit efa6369aa1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
66 changed files with 981 additions and 2056 deletions

View file

@ -2772,7 +2772,6 @@ src/infra/exec-approvals-config.ts 4
src/infra/exec-approvals-socket.ts 1
src/infra/exec-approvals-store.ts 1
src/infra/exec-argv-analysis.ts 1
src/infra/exec-control-command-guard.ts 1
src/infra/exec-host.ts 3
src/infra/exec-safe-bin-policy-profiles.ts 1
src/infra/fetch-headers.ts 4
@ -2829,7 +2828,6 @@ src/infra/outbound/session-binding-normalization.ts 1
src/infra/outbound/source-reply-mirror.ts 6
src/infra/outbound/targets.ts 2
src/infra/package-dist-inventory.ts 2
src/infra/package-json.ts 1
src/infra/pairing-files.ts 1
src/infra/ports.ts 2
src/infra/private-mode.ts 2

View file

@ -506,29 +506,15 @@ async function maybeFinalizeApprovalRouteNotice(
}
/** Tracks native approval deliveries and sends origin-chat notices after all observed runtimes report. */
export function createApprovalNativeRouteReporter(params: {
handledKinds: ReadonlySet<ChannelApprovalKind>;
channel?: string;
channelLabel?: string;
accountId?: string | null;
requestGateway: GatewayRequestFn;
shouldHandle: (request: ApprovalRequest) => boolean;
classifyRoute: (request: ApprovalRequest) => ApprovalRequestChannelRouteClass;
}) {
export function createApprovalNativeRouteReporter(
params: Omit<ApprovalRouteRuntimeRecord, "runtimeId">,
) {
return createApprovalNativeRouteReporterForState(defaultCoordinatorState, params);
}
function createApprovalNativeRouteReporterForState(
state: ApprovalNativeRouteCoordinatorState,
params: {
handledKinds: ReadonlySet<ChannelApprovalKind>;
channel?: string;
channelLabel?: string;
accountId?: string | null;
requestGateway: GatewayRequestFn;
shouldHandle: (request: ApprovalRequest) => boolean;
classifyRoute: (request: ApprovalRequest) => ApprovalRequestChannelRouteClass;
},
params: Omit<ApprovalRouteRuntimeRecord, "runtimeId">,
) {
const runtimeId = `native-approval-route:${++state.runtimeSeq}`;
let registered = false;

View file

@ -300,52 +300,42 @@ export function createChannelNativeApprovalRuntime<
approvalKind,
request,
adapter: adapter.nativeAdapter,
prepareTarget: async ({ plannedTarget, request: requestCandidate }) =>
prepareTarget: async (target) =>
await adapter.prepareTarget({
plannedTarget,
request: requestCandidate,
...target,
approvalKind,
pendingContent,
}),
deliverTarget: async ({ plannedTarget, preparedTarget, request: requestEntry }) =>
deliverTarget: async (target) =>
await adapter.deliverTarget({
plannedTarget,
preparedTarget,
request: requestEntry,
...target,
approvalKind,
pendingContent,
}),
onDeliveryError: adapter.onDeliveryError
? ({ error, plannedTarget, request: requestResult }) => {
? (result) => {
adapter.onDeliveryError?.({
error,
plannedTarget,
request: requestResult,
...result,
approvalKind,
pendingContent,
});
}
: undefined,
onDuplicateSkipped: adapter.onDuplicateSkipped
? ({ plannedTarget, preparedTarget, request: requestValue }) => {
? (result) => {
adapter.onDuplicateSkipped?.({
plannedTarget,
preparedTarget,
request: requestValue,
...result,
approvalKind,
pendingContent,
});
}
: undefined,
onDelivered: adapter.onDelivered
? ({ plannedTarget, preparedTarget, request: requestLocal, entry }) => {
? (result) => {
adapter.onDelivered?.({
plannedTarget,
preparedTarget,
request: requestLocal,
...result,
approvalKind,
pendingContent,
entry,
});
}
: undefined,

View file

@ -9,6 +9,7 @@ import {
withClawHubResponse,
resolveClawHubBaseUrl,
type ClawHubFetch,
type ClawHubFetchOptions,
type ClawHubRequestParams,
} from "./clawhub-client.js";
import { normalizeClawHubSha256Hex } from "./clawhub-integrity.js";
@ -106,16 +107,14 @@ async function fetchClawHubArchive(params: ClawHubRequestParams, resourceLabel:
});
}
export async function downloadClawHubPackageArchive(params: {
name: string;
version?: string;
tag?: string;
artifact?: "archive" | "clawpack";
baseUrl?: string;
token?: string;
timeoutMs?: number;
fetchImpl?: ClawHubFetch;
}): Promise<ClawHubDownloadResult> {
export async function downloadClawHubPackageArchive(
params: ClawHubFetchOptions & {
name: string;
version?: string;
tag?: string;
artifact?: "archive" | "clawpack";
},
): Promise<ClawHubDownloadResult> {
if (params.artifact === "clawpack") {
if (!params.version) {
throw new Error("ClawPack package downloads require an explicit version.");
@ -205,16 +204,14 @@ export async function downloadClawHubPackageArchive(params: {
});
}
export async function downloadClawHubSkillArchive(params: {
slug: string;
ownerHandle?: string;
version?: string;
tag?: string;
baseUrl?: string;
token?: string;
timeoutMs?: number;
fetchImpl?: ClawHubFetch;
}): Promise<ClawHubDownloadResult> {
export async function downloadClawHubSkillArchive(
params: ClawHubFetchOptions & {
slug: string;
ownerHandle?: string;
version?: string;
tag?: string;
},
): Promise<ClawHubDownloadResult> {
const { bytes } = await fetchClawHubArchive(
{
baseUrl: params.baseUrl,
@ -238,13 +235,11 @@ export async function downloadClawHubSkillArchive(params: {
});
}
export async function downloadClawHubSkillArchiveUrl(params: {
url: string;
baseUrl?: string;
token?: string;
timeoutMs?: number;
fetchImpl?: ClawHubFetch;
}): Promise<ClawHubDownloadResult> {
export async function downloadClawHubSkillArchiveUrl(
params: ClawHubFetchOptions & {
url: string;
},
): Promise<ClawHubDownloadResult> {
const providedToken = normalizeOptionalString(params.token);
const requestUrl = new URL(params.url, `${resolveClawHubBaseUrl(params.baseUrl)}/`);
const registryOrigin = new URL(`${resolveClawHubBaseUrl(params.baseUrl)}/`).origin;

View file

@ -25,16 +25,19 @@ const CLAWHUB_ERROR_BODY_MAX_CHARS = 400;
export type ClawHubFetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
export type ClawHubRequestParams = {
export type ClawHubFetchOptions = {
baseUrl?: string;
token?: string;
timeoutMs?: number;
fetchImpl?: ClawHubFetch;
};
export type ClawHubRequestParams = ClawHubFetchOptions & {
path?: string;
url?: string;
method?: "GET" | "POST";
json?: unknown;
token?: string;
timeoutMs?: number;
search?: Record<string, string | undefined>;
fetchImpl?: ClawHubFetch;
skipAuth?: boolean;
retryTransientReads?: boolean;
headers?: Record<string, string>;
@ -175,23 +178,18 @@ export async function resolveClawHubAuthToken(): Promise<string | undefined> {
}
function buildUrl(params: Pick<ClawHubRequestParams, "baseUrl" | "path" | "search" | "url">): URL {
let url: URL;
if (params.url) {
const url = new URL(params.url, `${normalizeBaseUrl(params.baseUrl)}/`);
for (const [key, value] of Object.entries(params.search ?? {})) {
if (!value) {
continue;
}
url.searchParams.set(key, value);
url = new URL(params.url, `${normalizeBaseUrl(params.baseUrl)}/`);
} else {
if (!params.path) {
throw new Error("ClawHub request path is required");
}
return url;
url = new URL(`${normalizeBaseUrl(params.baseUrl)}/`);
const basePath = url.pathname.replace(/\/+$/, "");
const requestPath = params.path.startsWith("/") ? params.path : `/${params.path}`;
url.pathname = `${basePath}${requestPath}`;
}
if (!params.path) {
throw new Error("ClawHub request path is required");
}
const url = new URL(`${normalizeBaseUrl(params.baseUrl)}/`);
const basePath = url.pathname.replace(/\/+$/, "");
const requestPath = params.path.startsWith("/") ? params.path : `/${params.path}`;
url.pathname = `${basePath}${requestPath}`;
for (const [key, value] of Object.entries(params.search ?? {})) {
if (!value) {
continue;

View file

@ -67,7 +67,6 @@ type ClawHubFetchedSubjectSecurity = {
};
};
const CLAWHUB_RISK_MODERATION_STATES = new Set(["blocked", "quarantined", "revoked"]);
const CLAWHUB_BLOCKING_MODERATION_STATES = new Set(["blocked", "quarantined", "revoked"]);
const CLAWHUB_SAFE_MODERATION_STATES = new Set(["", "approved"]);
const CLAWHUB_NON_RISK_SCAN_STATUSES = new Set(["pending", "scan_pending", "stale", "stale_scan"]);
@ -144,10 +143,7 @@ function resolveClawHubRiskReasons(trust: ClawHubPackageSecurityTrust): string[]
reasons.push(formatClawHubTrustStatus("security scan status", scanStatus));
}
const moderationState = normalizeClawHubTrustToken(trust.moderationState);
if (
CLAWHUB_RISK_MODERATION_STATES.has(moderationState) ||
!CLAWHUB_SAFE_MODERATION_STATES.has(moderationState)
) {
if (!CLAWHUB_SAFE_MODERATION_STATES.has(moderationState)) {
reasons.push(formatClawHubTrustStatus("moderation state", moderationState));
}
for (const reason of trust.reasons) {
@ -255,16 +251,9 @@ function resolveClawHubSecurityLinks(params: {
security?: string;
};
}): ClawHubSecurityLinks {
const subjectUrl = resolveClawHubSubjectUrl(params);
if (params.subject.kind === "skill") {
const resolvedSubjectUrl = normalizeOptionalString(params.links?.subject) ?? subjectUrl;
return {
subject: resolvedSubjectUrl,
security:
normalizeOptionalString(params.links?.security) ??
`${resolvedSubjectUrl}/security-audit?version=${encodeURIComponent(params.version)}`,
};
}
const subjectUrl =
(params.subject.kind === "skill" && normalizeOptionalString(params.links?.subject)) ||
resolveClawHubSubjectUrl(params);
return {
subject: subjectUrl,
security:
@ -659,16 +648,7 @@ export async function checkClawHubPackageTrust(params: {
assessment,
links: warningLinks,
});
const audit = stripAnsi(
formatClawHubSecurityAudit({
baseUrl: params.baseUrl,
subject: params.subject,
version: params.version,
overview,
assessment,
links: warningLinks,
}),
);
const audit = stripAnsi(terminalAudit);
if (assessment.disposition === "clean") {
params.logger?.info?.(terminalAudit);
} else {

View file

@ -3,17 +3,14 @@ import { isRecord as isJsonObject } from "@openclaw/normalization-core/record-co
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
import type { ExternalPluginCompatibility } from "../../packages/plugin-package-contract/src/index.js";
import {
createClawHubError,
fetchClawHubJson,
isClawHubTelemetryDisabled,
readClawHubStringField,
readRequiredClawHubBooleanField,
readRequiredClawHubStringArrayField,
readRequiredClawHubStringField,
withClawHubResponse,
resolveClawHubAuthToken,
type ClawHubFetch,
type ClawHubFetchOptions,
} from "./clawhub-client.js";
import { reportClawHubInstallTelemetry } from "./clawhub-telemetry.js";
export type ClawHubPackageFamily = "skill" | "code-plugin" | "bundle-plugin";
export type ClawHubPackageChannel = "official" | "community" | "private";
@ -344,13 +341,11 @@ export function parseClawHubPackageSecurityResponse(
return result;
}
export async function fetchClawHubPackageDetail(params: {
name: string;
baseUrl?: string;
token?: string;
timeoutMs?: number;
fetchImpl?: ClawHubFetch;
}): Promise<ClawHubPackageDetail> {
export async function fetchClawHubPackageDetail(
params: ClawHubFetchOptions & {
name: string;
},
): Promise<ClawHubPackageDetail> {
return await fetchClawHubJson<ClawHubPackageDetail>({
baseUrl: params.baseUrl,
path: `/api/v1/packages/${encodeURIComponent(params.name)}`,
@ -360,14 +355,12 @@ export async function fetchClawHubPackageDetail(params: {
});
}
export async function fetchClawHubPackageVersion(params: {
name: string;
version: string;
baseUrl?: string;
token?: string;
timeoutMs?: number;
fetchImpl?: ClawHubFetch;
}): Promise<ClawHubPackageVersion> {
export async function fetchClawHubPackageVersion(
params: ClawHubFetchOptions & {
name: string;
version: string;
},
): Promise<ClawHubPackageVersion> {
return await fetchClawHubJson<ClawHubPackageVersion>({
baseUrl: params.baseUrl,
path: `/api/v1/packages/${encodeURIComponent(params.name)}/versions/${encodeURIComponent(
@ -379,14 +372,12 @@ export async function fetchClawHubPackageVersion(params: {
});
}
export async function fetchClawHubPackageArtifact(params: {
name: string;
version: string;
baseUrl?: string;
token?: string;
timeoutMs?: number;
fetchImpl?: ClawHubFetch;
}): Promise<ClawHubPackageArtifactResolverResponse> {
export async function fetchClawHubPackageArtifact(
params: ClawHubFetchOptions & {
name: string;
version: string;
},
): Promise<ClawHubPackageArtifactResolverResponse> {
return await fetchClawHubJson<ClawHubPackageArtifactResolverResponse>({
baseUrl: params.baseUrl,
path: `/api/v1/packages/${encodeURIComponent(params.name)}/versions/${encodeURIComponent(
@ -398,14 +389,12 @@ export async function fetchClawHubPackageArtifact(params: {
});
}
export async function fetchClawHubPackageSecurity(params: {
name: string;
version: string;
baseUrl?: string;
token?: string;
timeoutMs?: number;
fetchImpl?: ClawHubFetch;
}): Promise<ClawHubPackageSecurityResponse> {
export async function fetchClawHubPackageSecurity(
params: ClawHubFetchOptions & {
name: string;
version: string;
},
): Promise<ClawHubPackageSecurityResponse> {
const response = await fetchClawHubJson<unknown>({
baseUrl: params.baseUrl,
path: `/api/v1/packages/${encodeURIComponent(params.name)}/versions/${encodeURIComponent(
@ -418,15 +407,13 @@ export async function fetchClawHubPackageSecurity(params: {
return parseClawHubPackageSecurityResponse(response);
}
export async function searchClawHubPackages(params: {
query: string;
family?: ClawHubPackageFamily;
baseUrl?: string;
token?: string;
timeoutMs?: number;
fetchImpl?: ClawHubFetch;
limit?: number;
}): Promise<ClawHubPackageSearchResult[]> {
export async function searchClawHubPackages(
params: ClawHubFetchOptions & {
query: string;
family?: ClawHubPackageFamily;
limit?: number;
},
): Promise<ClawHubPackageSearchResult[]> {
const result = await fetchClawHubJson<{ results: ClawHubPackageSearchResult[] }>({
baseUrl: params.baseUrl,
path: "/api/v1/packages/search",
@ -442,43 +429,22 @@ export async function searchClawHubPackages(params: {
return result.results ?? [];
}
export async function reportClawHubPluginInstallTelemetry(params: {
baseUrl?: string;
token?: string;
packageName: string;
version?: string | null;
timeoutMs?: number;
fetchImpl?: ClawHubFetch;
}): Promise<void> {
const token = normalizeOptionalString(params.token) ?? (await resolveClawHubAuthToken());
if (!token || isClawHubTelemetryDisabled()) {
return;
}
const packageName = normalizeOptionalString(params.packageName);
if (!packageName) {
return;
}
return await withClawHubResponse(
{
baseUrl: params.baseUrl,
path: "/api/cli/telemetry/install",
method: "POST",
token,
timeoutMs: params.timeoutMs,
fetchImpl: params.fetchImpl,
json: {
event: "plugin_install",
packageName,
version: params.version ?? undefined,
},
},
async ({ response, url, hasToken }) => {
if (!response.ok) {
throw await createClawHubError(response, url, hasToken, params.timeoutMs);
}
},
);
export async function reportClawHubPluginInstallTelemetry(
params: ClawHubFetchOptions & {
packageName: string;
version?: string | null;
},
): Promise<void> {
return await reportClawHubInstallTelemetry(params, () => {
const packageName = normalizeOptionalString(params.packageName);
return packageName
? {
event: "plugin_install",
packageName,
version: params.version ?? undefined,
}
: undefined;
});
}
export function resolveLatestVersionFromPackage(detail: ClawHubPackageDetail): string | null {

View file

@ -5,15 +5,14 @@ import {
createClawHubError,
decodeClawHubResponseBody,
fetchClawHubJson,
isClawHubTelemetryDisabled,
parseClawHubJsonBody,
readClawHubBytes,
withClawHubResponse,
resolveClawHubAuthToken,
resolveClawHubBaseUrl,
resolveClawHubImageUrl,
type ClawHubFetch,
type ClawHubFetchOptions,
} from "./clawhub-client.js";
import { reportClawHubInstallTelemetry } from "./clawhub-telemetry.js";
const SKILL_CARD_MAX_BYTES = 256 * 1024;
// Full scanner evidence can exceed the metadata reader's 16 MiB cap.
@ -196,14 +195,12 @@ function buildVersionOrTagSearch(params: {
return ownerHandle ? { ownerHandle } : undefined;
}
export async function searchClawHubSkills(params: {
query: string;
baseUrl?: string;
token?: string;
timeoutMs?: number;
fetchImpl?: ClawHubFetch;
limit?: number;
}): Promise<ClawHubSkillSearchResult[]> {
export async function searchClawHubSkills(
params: ClawHubFetchOptions & {
query: string;
limit?: number;
},
): Promise<ClawHubSkillSearchResult[]> {
const registry = resolveClawHubBaseUrl(params.baseUrl);
const query = params.query.trim();
const request = {
@ -290,14 +287,12 @@ function toClawHubSkillSearchResult(
}
}
export async function fetchClawHubSkillDetail(params: {
slug: string;
ownerHandle?: string;
baseUrl?: string;
token?: string;
timeoutMs?: number;
fetchImpl?: ClawHubFetch;
}): Promise<ClawHubSkillDetail> {
export async function fetchClawHubSkillDetail(
params: ClawHubFetchOptions & {
slug: string;
ownerHandle?: string;
},
): Promise<ClawHubSkillDetail> {
const detail = await fetchClawHubJson<ClawHubSkillDetail>({
baseUrl: params.baseUrl,
path: `/api/v1/skills/${encodeURIComponent(params.slug)}`,
@ -317,16 +312,14 @@ export async function fetchClawHubSkillDetail(params: {
};
}
export async function fetchClawHubSkillInstallResolution(params: {
slug: string;
ownerHandle?: string;
requestedReference?: string;
baseUrl?: string;
token?: string;
timeoutMs?: number;
fetchImpl?: ClawHubFetch;
forceInstall?: boolean;
}): Promise<ClawHubSkillInstallResolutionResponse> {
export async function fetchClawHubSkillInstallResolution(
params: ClawHubFetchOptions & {
slug: string;
ownerHandle?: string;
requestedReference?: string;
forceInstall?: boolean;
},
): Promise<ClawHubSkillInstallResolutionResponse> {
return await withClawHubResponse(
{
baseUrl: params.baseUrl,
@ -354,18 +347,16 @@ export async function fetchClawHubSkillInstallResolution(params: {
);
}
export async function fetchClawHubSkillVerification(params: {
slug: string;
ownerHandle?: string;
requestedReference?: string;
version?: string;
tag?: string;
baseUrl?: string;
token?: string;
skipAuth?: boolean;
timeoutMs?: number;
fetchImpl?: ClawHubFetch;
}): Promise<ClawHubSkillVerificationResponse> {
export async function fetchClawHubSkillVerification(
params: ClawHubFetchOptions & {
slug: string;
ownerHandle?: string;
requestedReference?: string;
version?: string;
tag?: string;
skipAuth?: boolean;
},
): Promise<ClawHubSkillVerificationResponse> {
return await fetchClawHubJson<ClawHubSkillVerificationResponse>({
baseUrl: params.baseUrl,
path: `/api/v1/skills/${encodeURIComponent(params.slug)}/verify`,
@ -381,14 +372,12 @@ export async function fetchClawHubSkillVerification(params: {
});
}
export async function fetchClawHubSkillSecurityVerdicts(params: {
items: ClawHubSkillSecurityVerdictRequestItem[];
baseUrl?: string;
token?: string;
skipAuth?: boolean;
timeoutMs?: number;
fetchImpl?: ClawHubFetch;
}): Promise<ClawHubSkillSecurityVerdictsResponse> {
export async function fetchClawHubSkillSecurityVerdicts(
params: ClawHubFetchOptions & {
items: ClawHubSkillSecurityVerdictRequestItem[];
skipAuth?: boolean;
},
): Promise<ClawHubSkillSecurityVerdictsResponse> {
return await fetchClawHubJson<ClawHubSkillSecurityVerdictsResponse>({
baseUrl: params.baseUrl,
path: "/api/v1/skills/-/security-verdicts",
@ -401,17 +390,15 @@ export async function fetchClawHubSkillSecurityVerdicts(params: {
});
}
export async function fetchClawHubSkillCard(params: {
slug?: string;
ownerHandle?: string;
url?: string;
version?: string;
tag?: string;
baseUrl?: string;
token?: string;
timeoutMs?: number;
fetchImpl?: ClawHubFetch;
}): Promise<string> {
export async function fetchClawHubSkillCard(
params: ClawHubFetchOptions & {
slug?: string;
ownerHandle?: string;
url?: string;
version?: string;
tag?: string;
},
): Promise<string> {
const cardUrl = normalizeOptionalString(params.url);
const slug = normalizeOptionalString(params.slug);
if (!cardUrl && !slug) {
@ -449,47 +436,26 @@ export async function fetchClawHubSkillCard(params: {
);
}
export async function reportClawHubSkillInstallTelemetry(params: {
baseUrl?: string;
token?: string;
slug: string;
ownerHandle?: string;
requestedReference?: string;
trustState?: ClawHubSkillsShTrustState;
version?: string | null;
timeoutMs?: number;
fetchImpl?: ClawHubFetch;
}): Promise<void> {
const token = normalizeOptionalString(params.token) ?? (await resolveClawHubAuthToken());
if (!token || isClawHubTelemetryDisabled()) {
return;
}
const slug = params.slug.trim();
if (!slug) {
return;
}
return await withClawHubResponse(
{
baseUrl: params.baseUrl,
path: "/api/cli/telemetry/install",
method: "POST",
token,
timeoutMs: params.timeoutMs,
fetchImpl: params.fetchImpl,
json: {
event: "install",
slug,
...(params.ownerHandle ? { ownerHandle: params.ownerHandle } : {}),
...(params.requestedReference ? { reference: params.requestedReference } : {}),
...(params.trustState ? { trustState: params.trustState } : {}),
version: params.version ?? undefined,
},
},
async ({ response, url, hasToken }) => {
if (!response.ok) {
throw await createClawHubError(response, url, hasToken, params.timeoutMs);
}
},
);
export async function reportClawHubSkillInstallTelemetry(
params: ClawHubFetchOptions & {
slug: string;
ownerHandle?: string;
requestedReference?: string;
trustState?: ClawHubSkillsShTrustState;
version?: string | null;
},
): Promise<void> {
return await reportClawHubInstallTelemetry(params, () => {
const slug = params.slug.trim();
return slug
? {
event: "install",
slug,
...(params.ownerHandle ? { ownerHandle: params.ownerHandle } : {}),
...(params.requestedReference ? { reference: params.requestedReference } : {}),
...(params.trustState ? { trustState: params.trustState } : {}),
version: params.version ?? undefined,
}
: undefined;
});
}

View file

@ -0,0 +1,38 @@
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
import {
createClawHubError,
isClawHubTelemetryDisabled,
resolveClawHubAuthToken,
withClawHubResponse,
type ClawHubFetchOptions,
} from "./clawhub-client.js";
export async function reportClawHubInstallTelemetry(
params: ClawHubFetchOptions,
buildEvent: () => Record<string, unknown> | undefined,
): Promise<void> {
const token = normalizeOptionalString(params.token) ?? (await resolveClawHubAuthToken());
if (!token || isClawHubTelemetryDisabled()) {
return;
}
const json = buildEvent();
if (!json) {
return;
}
await withClawHubResponse(
{
baseUrl: params.baseUrl,
path: "/api/cli/telemetry/install",
method: "POST",
token,
timeoutMs: params.timeoutMs,
fetchImpl: params.fetchImpl,
json,
},
async ({ response, url, hasToken }) => {
if (!response.ok) {
throw await createClawHubError(response, url, hasToken, params.timeoutMs);
}
},
);
}

View file

@ -112,58 +112,31 @@ const FLAG_INTERPRETER_INLINE_EVAL_SPECS: readonly InterpreterFlagSpec[] = [
{
names: ["perl"],
exactFlags: new Set(["-e", "-E"]),
shortClusterFlags: [
{
label: "-e",
flag: "e",
prefixChars: new Set([
"S",
"T",
"W",
"X",
"U",
"V",
"a",
"c",
"d",
"f",
"l",
"n",
"p",
"s",
"t",
"u",
"w",
]),
allowNumericRecordSeparator: true,
numericValuePrefixChars: new Set(["l"]),
},
{
label: "-e",
flag: "E",
prefixChars: new Set([
"S",
"T",
"W",
"X",
"U",
"V",
"a",
"c",
"d",
"f",
"l",
"n",
"p",
"s",
"t",
"u",
"w",
]),
allowNumericRecordSeparator: true,
numericValuePrefixChars: new Set(["l"]),
},
],
shortClusterFlags: ["e", "E"].map((flag) => ({
label: "-e",
flag,
prefixChars: new Set([
"S",
"T",
"W",
"X",
"U",
"V",
"a",
"c",
"d",
"f",
"l",
"n",
"p",
"s",
"t",
"u",
"w",
]),
allowNumericRecordSeparator: true,
numericValuePrefixChars: new Set(["l"]),
})),
},
{
names: ["php"],

View file

@ -2,7 +2,7 @@
// shell wrappers, env split-string, eval, and source invocations.
import { describe, expect, it } from "vitest";
import {
buildCommandPayloadCandidates,
buildCommandPayloadArgvCandidates,
detectCarriedShellBuiltinArgv,
detectCommandCarrierArgv,
detectInlineEvalArgv,
@ -194,65 +194,87 @@ describe("command-analysis risks", () => {
});
it("builds executable payload candidates through carriers and shell wrappers", () => {
expect(buildCommandPayloadCandidates(["FOO=1", "sudo", "-E", "/approve", "abc"])).toEqual([
"/approve abc",
expect(buildCommandPayloadArgvCandidates(["FOO=1", "sudo", "-E", "/approve", "abc"])).toEqual([
["/approve", "abc"],
]);
expect(buildCommandPayloadCandidates(["sudo", "-EH", "/approve", "abc"])).toEqual([
"/approve abc",
expect(buildCommandPayloadArgvCandidates(["sudo", "-EH", "/approve", "abc"])).toEqual([
["/approve", "abc"],
]);
expect(buildCommandPayloadCandidates(["sudo", "-i", "/approve", "abc"])).toEqual([
"/approve abc",
expect(buildCommandPayloadArgvCandidates(["sudo", "-i", "/approve", "abc"])).toEqual([
["/approve", "abc"],
]);
expect(buildCommandPayloadCandidates(["sudo", "-s", "/approve", "abc"])).toEqual([
"/approve abc",
expect(buildCommandPayloadArgvCandidates(["sudo", "-s", "/approve", "abc"])).toEqual([
["/approve", "abc"],
]);
expect(buildCommandPayloadCandidates(["sudo", "-k", "/approve", "abc"])).toEqual([
"/approve abc",
expect(buildCommandPayloadArgvCandidates(["sudo", "-k", "/approve", "abc"])).toEqual([
["/approve", "abc"],
]);
expect(buildCommandPayloadCandidates(["sudo", "--reset-timestamp", "/approve", "abc"])).toEqual(
["/approve abc"],
expect(
buildCommandPayloadArgvCandidates(["sudo", "--reset-timestamp", "/approve", "abc"]),
).toEqual([["/approve", "abc"]]);
expect(
buildCommandPayloadArgvCandidates(["sudo", "--command-timeout=1", "/approve", "abc"]),
).toEqual([["/approve", "abc"]]);
expect(
buildCommandPayloadArgvCandidates(["sudo", "OPENCLAW_ENV=1", "/approve", "abc"]),
).toEqual([["/approve", "abc"]]);
expect(buildCommandPayloadArgvCandidates(["sudo", "--shell", "/approve", "abc"])).toEqual([
["/approve", "abc"],
]);
expect(
buildCommandPayloadArgvCandidates(["sudo", "--preserve-groups", "/approve", "abc"]),
).toEqual([["/approve", "abc"]]);
expect(
buildCommandPayloadArgvCandidates([
"sudo",
"-uroot",
"bash",
"-lc",
"/approve req allow-once",
]),
).toEqual([
["bash", "-lc", "/approve req allow-once"],
["/approve", "req", "allow-once"],
]);
expect(
buildCommandPayloadArgvCandidates([
"doas",
"-uroot",
"bash",
"-lc",
"/approve req allow-once",
]),
).toEqual([
["bash", "-lc", "/approve req allow-once"],
["/approve", "req", "allow-once"],
]);
expect(
buildCommandPayloadArgvCandidates(["env", "-S", "bash -lc '/approve abc deny'"]),
).toEqual([
["bash", "-lc", "/approve abc deny"],
["/approve", "abc", "deny"],
]);
expect(
buildCommandPayloadArgvCandidates(["env", "-S", "bash -lc", "/approve abc deny"]),
).toEqual([
["bash", "-lc", "/approve abc deny"],
["/approve", "abc", "deny"],
]);
expect(buildCommandPayloadArgvCandidates(["env", "-iSbash -lc", "/approve abc deny"])).toEqual([
["bash", "-lc", "/approve abc deny"],
["/approve", "abc", "deny"],
]);
expect(buildCommandPayloadArgvCandidates(["env", "-P", "/usr/bin", "/approve", "abc"])).toEqual(
[["/approve", "abc"]],
);
expect(
buildCommandPayloadCandidates(["sudo", "--command-timeout=1", "/approve", "abc"]),
).toEqual(["/approve abc"]);
expect(buildCommandPayloadCandidates(["sudo", "OPENCLAW_ENV=1", "/approve", "abc"])).toEqual([
"/approve abc",
]);
expect(buildCommandPayloadCandidates(["sudo", "--shell", "/approve", "abc"])).toEqual([
"/approve abc",
]);
expect(buildCommandPayloadCandidates(["sudo", "--preserve-groups", "/approve", "abc"])).toEqual(
["/approve abc"],
);
expect(
buildCommandPayloadCandidates(["sudo", "-uroot", "bash", "-lc", "/approve req allow-once"]),
).toEqual(["bash -lc /approve req allow-once", "/approve req allow-once"]);
expect(
buildCommandPayloadCandidates(["doas", "-uroot", "bash", "-lc", "/approve req allow-once"]),
).toEqual(["bash -lc /approve req allow-once", "/approve req allow-once"]);
expect(buildCommandPayloadCandidates(["env", "-S", "bash -lc '/approve abc deny'"])).toEqual([
"bash -lc /approve abc deny",
"/approve abc deny",
]);
expect(buildCommandPayloadCandidates(["env", "-S", "bash -lc", "/approve abc deny"])).toEqual([
"bash -lc /approve abc deny",
"/approve abc deny",
]);
expect(buildCommandPayloadCandidates(["env", "-iSbash -lc", "/approve abc deny"])).toEqual([
"bash -lc /approve abc deny",
"/approve abc deny",
]);
expect(buildCommandPayloadCandidates(["env", "-P", "/usr/bin", "/approve", "abc"])).toEqual([
"/approve abc",
]);
expect(buildCommandPayloadCandidates(["exec", "-a", "openclaw", "/approve", "abc"])).toEqual([
"/approve abc",
]);
expect(buildCommandPayloadCandidates(["command", "-v", "/approve"])).toEqual([
"command -v /approve",
buildCommandPayloadArgvCandidates(["exec", "-a", "openclaw", "/approve", "abc"]),
).toEqual([["/approve", "abc"]]);
expect(buildCommandPayloadArgvCandidates(["command", "-v", "/approve"])).toEqual([
["command", "-v", "/approve"],
]);
expect(
buildCommandPayloadCandidates([
buildCommandPayloadArgvCandidates([
"env",
"env",
"env",
@ -265,7 +287,14 @@ describe("command-analysis risks", () => {
"--channel",
"whatsapp",
]),
).toContain("openclaw channels login --channel whatsapp");
).toEqual([
["env", "env", "env", "env", "env", "openclaw", "channels", "login", "--channel", "whatsapp"],
["env", "env", "env", "env", "openclaw", "channels", "login", "--channel", "whatsapp"],
["env", "env", "env", "openclaw", "channels", "login", "--channel", "whatsapp"],
["env", "env", "openclaw", "channels", "login", "--channel", "whatsapp"],
["env", "openclaw", "channels", "login", "--channel", "whatsapp"],
["openclaw", "channels", "login", "--channel", "whatsapp"],
]);
});
it("checks both effective and original argv for segment inline eval", () => {

View file

@ -1,7 +1,6 @@
import { parseStrictPositiveInteger } from "@openclaw/normalization-core/number-coercion";
// Command risk detection follows nested carriers, shell wrappers, and inline
// interpreter eval paths used by approval policy and command explanations.
import { uniqueStrings } from "@openclaw/normalization-core/string-normalization";
import { splitShellArgs } from "../../utils/shell-argv.js";
import {
COMMAND_CARRIER_EXECUTABLES,
@ -13,7 +12,11 @@ import {
import { unwrapKnownDispatchWrapperInvocation } from "../dispatch-wrapper-resolution.js";
import type { ExecCommandSegment } from "../exec-approvals-analysis.js";
import { normalizeExecutableToken } from "../exec-wrapper-resolution.js";
import { POSIX_INLINE_COMMAND_FLAGS, resolveInlineCommandMatch } from "../shell-inline-command.js";
import {
isDirectShellPositionalCarrierCommand,
POSIX_INLINE_COMMAND_FLAGS,
resolveInlineCommandMatch,
} from "../shell-inline-command.js";
import {
extractShellWrapperInlineCommand,
isShellWrapperExecutable,
@ -78,16 +81,6 @@ export function buildCommandPayloadArgvCandidates(
]);
}
/** Builds candidate command payload strings from nested carriers and shell wrappers. */
export function buildCommandPayloadCandidates(
argv: string[],
seenArgv = new Set<string>(),
): string[] {
return uniqueStrings(
buildCommandPayloadArgvCandidates(argv, seenArgv).map((candidate) => candidate.join(" ")),
);
}
function stripLeadingEnvAssignments(argv: string[]): string[] {
let index = 0;
while (index < argv.length && isEnvAssignmentToken(argv[index] ?? "")) {
@ -138,19 +131,7 @@ function normalizeShellPositionalToken(
function resolveShellPositionalCarrierPlan(command: string): ShellPositionalCarrierPlan | null {
const trimmed = command.trim();
if (trimmed.length === 0) {
return null;
}
const shellWhitespace = String.raw`[^\S\r\n]+`;
const positionalZero = String.raw`(?:\$(?:0|\{0\})|"\$(?:0|\{0\})")`;
const positionalArg = String.raw`(?:\$(?:[@*]|[1-9]|\{[@*1-9]\})|"\$(?:[@*]|[1-9]|\{[@*1-9]\})")`;
if (
!new RegExp(
`^(?:exec${shellWhitespace}(?:--${shellWhitespace})?)?${positionalZero}(?:${shellWhitespace}${positionalArg})*$`,
"u",
).test(trimmed)
) {
if (!isDirectShellPositionalCarrierCommand(trimmed)) {
return null;
}

View file

@ -119,6 +119,11 @@ export function storeDeviceAuthTokenInDatabase(
): DeviceAuthEntry | null {
const entry = createDeviceAuthEntry(params);
const kysely = getNodeSqliteKysely<DeviceAuthDatabase>(db);
const values = {
token: entry.token,
scopes_json: JSON.stringify(entry.scopes),
updated_at_ms: entry.updatedAtMs,
};
// A comparison replaces only its observed token or inserts only its observed
// absence; it cannot overwrite a row that another request rotated or created.
const result =
@ -130,29 +135,19 @@ export function storeDeviceAuthTokenInDatabase(
.values({
device_id: params.deviceId,
role: entry.role,
token: entry.token,
scopes_json: JSON.stringify(entry.scopes),
updated_at_ms: entry.updatedAtMs,
...values,
})
.onConflict((conflict) =>
params.expectedToken === null
? conflict.columns(["device_id", "role"]).doNothing()
: conflict.columns(["device_id", "role"]).doUpdateSet({
token: entry.token,
scopes_json: JSON.stringify(entry.scopes),
updated_at_ms: entry.updatedAtMs,
}),
: conflict.columns(["device_id", "role"]).doUpdateSet(values),
),
)
: executeSqliteQuerySync(
db,
kysely
.updateTable("device_auth_tokens")
.set({
token: entry.token,
scopes_json: JSON.stringify(entry.scopes),
updated_at_ms: entry.updatedAtMs,
})
.set(values)
.where("device_id", "=", params.deviceId)
.where("role", "=", entry.role)
.where("token", "=", params.expectedToken),
@ -191,6 +186,11 @@ export function storeOriginDeviceTokenInDatabase(
): DeviceAuthEntry | null {
const entry = createDeviceAuthEntry(params);
const kysely = getNodeSqliteKysely<DeviceAuthDatabase>(db);
const values = {
token: entry.token,
scopes_json: JSON.stringify(entry.scopes),
updated_at_ms: entry.updatedAtMs,
};
const result =
params.expectedToken == null
? executeSqliteQuerySync(
@ -201,29 +201,19 @@ export function storeOriginDeviceTokenInDatabase(
gateway_scope: params.gatewayScope,
device_id: params.deviceId,
role: entry.role,
token: entry.token,
scopes_json: JSON.stringify(entry.scopes),
updated_at_ms: entry.updatedAtMs,
...values,
})
.onConflict((conflict) =>
params.expectedToken === null
? conflict.columns(["gateway_scope", "device_id", "role"]).doNothing()
: conflict.columns(["gateway_scope", "device_id", "role"]).doUpdateSet({
token: entry.token,
scopes_json: JSON.stringify(entry.scopes),
updated_at_ms: entry.updatedAtMs,
}),
: conflict.columns(["gateway_scope", "device_id", "role"]).doUpdateSet(values),
),
)
: executeSqliteQuerySync(
db,
kysely
.updateTable("gateway_origin_device_tokens")
.set({
token: entry.token,
scopes_json: JSON.stringify(entry.scopes),
updated_at_ms: entry.updatedAtMs,
})
.set(values)
.where("gateway_scope", "=", params.gatewayScope)
.where("device_id", "=", params.deviceId)
.where("role", "=", entry.role)

View file

@ -41,18 +41,6 @@ const DEVICE_PAIR_SETUP_COMPLETION_RETENTION_MS = 2 * DEVICE_BOOTSTRAP_TOKEN_TTL
type DeviceBootstrapStateFile = Record<string, DeviceBootstrapTokenRecord>;
function resolvePersistedBootstrapProfile(
record: Partial<DeviceBootstrapTokenRecord>,
): DeviceBootstrapProfile {
return normalizeDeviceBootstrapProfile(record.profile);
}
function resolvePersistedRedeemedProfile(
record: Partial<DeviceBootstrapTokenRecord>,
): DeviceBootstrapProfile {
return normalizeDeviceBootstrapProfile(record.redeemedProfile);
}
function resolvePersistedPendingProfile(
record: Partial<DeviceBootstrapTokenRecord>,
): DeviceBootstrapProfile | null {
@ -234,35 +222,6 @@ function consumeDeviceBootstrapTokenWithSetupCompletion(
});
}
/** Confirm that the pairing client received the credential-bearing handoff response. */
function confirmDevicePairSetupCompletionDelivery(
params: DeviceBootstrapOperations["bootstrap.confirm"]["input"],
): DeviceBootstrapOperations["bootstrap.confirm"]["output"] {
return confirmDevicePairSetupCompletionDeliveryInTransaction({
setupId: params.setupId,
deviceId: params.deviceId,
nowMs: params.nowMs,
});
}
/**
* Read the terminal outcome for one setup credential, or null while none is
* recorded. Shares this module's lock with issuance and revocation so a status
* query never observes a setup mid-settlement.
*/
function readDevicePairSetupCompletion(
params: DeviceBootstrapOperations["bootstrap.readCompletion"]["input"],
): DeviceBootstrapOperations["bootstrap.readCompletion"]["output"] {
return loadDevicePairSetupCompletionRecord(params.setupId, params.nowMs);
}
/** Remove retained setup outcomes independently of status requests or later pairings. */
function pruneExpiredDevicePairSetupCompletions(
params: DeviceBootstrapOperations["bootstrap.prune"]["input"],
): DeviceBootstrapOperations["bootstrap.prune"]["output"] {
return pruneExpiredDevicePairSetupCompletionRecords(params.nowMs);
}
/** Remove every outstanding bootstrap token from the pairing state file. */
function clearDeviceBootstrapTokens(
params: DeviceBootstrapOperations["bootstrap.clear"]["input"],
@ -353,17 +312,18 @@ function redeemDeviceBootstrapTokenProfile(
return { recorded: false, fullyRedeemed: false };
}
const [tokenKey, record] = found;
const issuedProfile = resolvePersistedBootstrapProfile(record);
const issuedProfile = normalizeDeviceBootstrapProfile(record.profile);
requestDevicePairingMutationAdmission({
kind: "bootstrap.token",
issuedAtMs: record.issuedAtMs,
});
const pendingProfile = resolvePersistedPendingProfile(record);
const previousRedeemedProfile = normalizeDeviceBootstrapProfile(record.redeemedProfile);
// Keep a pending profile until all requested roles/scopes from that handshake are redeemed.
const redeemedProfile = normalizeDeviceBootstrapProfile({
roles: [...resolvePersistedRedeemedProfile(record).roles, params.role],
roles: [...previousRedeemedProfile.roles, params.role],
scopes: [
...resolvePersistedRedeemedProfile(record).scopes,
...previousRedeemedProfile.scopes,
...resolveBootstrapProfileScopesForRole(params.role, params.scopes, issuedProfile.purpose),
],
purpose: issuedProfile.purpose,
@ -420,7 +380,7 @@ function verifyDeviceBootstrapToken(
if (!deviceId || !publicKey || !role) {
return { ok: false, reason: "bootstrap_token_invalid" };
}
const allowedProfile = resolvePersistedBootstrapProfile(record);
const allowedProfile = normalizeDeviceBootstrapProfile(record.profile);
const requestedProfile = resolveRequestedBootstrapProfile({
role,
scopes: params.scopes,
@ -451,30 +411,25 @@ function verifyDeviceBootstrapToken(
typeof record.publicKey === "string"
? normalizeBootstrapPublicKey(record.publicKey)
: undefined;
let pendingProfile = requestedProfile;
if (boundDeviceId || boundPublicKey) {
if (boundDeviceId !== deviceId || boundPublicKey !== publicKey) {
return { ok: false, reason: "bootstrap_token_invalid" };
}
const pendingProfile = resolvePersistedPendingProfile(record);
if (pendingProfile && !deviceBootstrapProfilesEqual(pendingProfile, requestedProfile)) {
const existingPendingProfile = resolvePersistedPendingProfile(record);
if (
existingPendingProfile &&
!deviceBootstrapProfilesEqual(existingPendingProfile, requestedProfile)
) {
return { ok: false, reason: "bootstrap_token_invalid" };
}
state[tokenKey] = {
...record,
profile: allowedProfile,
pendingProfile: pendingProfile ?? requestedProfile,
deviceId,
publicKey,
lastUsedAtMs: params.nowMs,
};
persistState(state);
return { ok: true };
pendingProfile = existingPendingProfile ?? requestedProfile;
}
state[tokenKey] = {
...record,
profile: allowedProfile,
pendingProfile: requestedProfile,
pendingProfile,
deviceId,
publicKey,
lastUsedAtMs: params.nowMs,
@ -512,7 +467,7 @@ export function getBoundDeviceBootstrapContextFromRecords(
return null;
}
return {
profile: resolvePersistedBootstrapProfile(record),
profile: normalizeDeviceBootstrapProfile(record.profile),
...(record.setupId ? { setupId: record.setupId } : {}),
};
}
@ -534,11 +489,11 @@ export function executeDeviceBootstrapMutation(
recordWorkerEnvironment,
);
case "bootstrap.confirm":
return confirmDevicePairSetupCompletionDelivery(command.input);
return confirmDevicePairSetupCompletionDeliveryInTransaction(command.input);
case "bootstrap.readCompletion":
return readDevicePairSetupCompletion(command.input);
return loadDevicePairSetupCompletionRecord(command.input.setupId, command.input.nowMs);
case "bootstrap.prune":
return pruneExpiredDevicePairSetupCompletions(command.input);
return pruneExpiredDevicePairSetupCompletionRecords(command.input.nowMs);
case "bootstrap.clear":
return clearDeviceBootstrapTokens(command.input);
case "bootstrap.revoke":

View file

@ -6,9 +6,9 @@ import type {
DevicePairingApprovalOptions,
DevicePairingForbiddenResult,
} from "./device-pairing-core.types.js";
import type { DevicePairingCoreAdmissionFacts } from "./device-pairing-core.worker-contract.js";
import { withDevicePairingLock } from "./device-pairing-lock.js";
import { resolvePairingRequestExpiry } from "./device-pairing-state.kernel.js";
import type { DevicePairingAdmissionFacts } from "./device-pairing-worker-contract.js";
import {
DevicePairingAuthorityRefusedError,
executeDevicePairingMutation,
@ -41,7 +41,7 @@ function approvalAdmission(
get refusedResult(): ApproveDevicePairingResult {
return expired ? null : { status: "forbidden", reason: "approval-policy-changed" };
},
admit(facts: DevicePairingCoreAdmissionFacts) {
admit: (facts: DevicePairingAdmissionFacts) => {
if (facts.kind !== "pairing-approval") {
return;
}
@ -89,11 +89,7 @@ export async function approveDevicePairing(
},
{
baseDir,
admit: (facts) => {
if (facts.kind === "pairing-approval") {
admission.admit(facts);
}
},
admit: admission.admit,
},
);
} catch (error) {
@ -140,11 +136,7 @@ export async function approveBootstrapDevicePairing(
{
baseDir,
onTokensReplaced: options?.onTokensReplaced,
admit: (facts) => {
if (facts.kind === "pairing-approval") {
admission.admit(facts);
}
},
admit: admission.admit,
},
);
return result;

View file

@ -32,28 +32,16 @@ type DiagnosticTraceScopeState = {
storage: AsyncLocalStorage<DiagnosticTraceContext | undefined>;
};
function randomHex(bytes: number): string {
return randomBytes(bytes).toString("hex");
}
function isNonZeroHex(value: string): boolean {
return !/^0+$/.test(value);
}
function randomTraceId(): string {
let traceId = randomHex(16);
while (!isNonZeroHex(traceId)) {
traceId = randomHex(16);
function randomNonZeroHex(bytes: number): string {
let value = randomBytes(bytes).toString("hex");
while (!isNonZeroHex(value)) {
value = randomBytes(bytes).toString("hex");
}
return traceId;
}
function randomSpanId(): string {
let spanId = randomHex(8);
while (!isNonZeroHex(spanId)) {
spanId = randomHex(8);
}
return spanId;
return value;
}
function createDiagnosticTraceScopeState(): DiagnosticTraceScopeState {
@ -105,28 +93,15 @@ export function isValidDiagnosticTraceFlags(value: unknown): value is string {
return typeof value === "string" && TRACE_FLAGS_RE.test(value);
}
function normalizeTraceId(value: unknown): string | undefined {
function normalizeTraceField(
value: unknown,
isValid: (value: unknown) => boolean,
): string | undefined {
if (typeof value !== "string") {
return undefined;
}
const normalized = value.toLowerCase();
return isValidDiagnosticTraceId(normalized) ? normalized : undefined;
}
function normalizeSpanId(value: unknown): string | undefined {
if (typeof value !== "string") {
return undefined;
}
const normalized = value.toLowerCase();
return isValidDiagnosticSpanId(normalized) ? normalized : undefined;
}
function normalizeTraceFlags(value: unknown): string | undefined {
if (typeof value !== "string") {
return undefined;
}
const normalized = value.toLowerCase();
return isValidDiagnosticTraceFlags(normalized) ? normalized : undefined;
return isValid(normalized) ? normalized : undefined;
}
/** Parses a W3C `traceparent` header into a normalized diagnostic trace context. */
@ -137,7 +112,7 @@ export function parseDiagnosticTraceparent(
return undefined;
}
const parts = traceparent.trim().toLowerCase().split("-");
if (!parts || parts.length < 4) {
if (parts.length < 4) {
return undefined;
}
const [version, traceId, spanId, traceFlags] = parts;
@ -148,9 +123,9 @@ export function parseDiagnosticTraceparent(
) {
return undefined;
}
const normalizedTraceId = normalizeTraceId(traceId);
const normalizedSpanId = normalizeSpanId(spanId);
const normalizedTraceFlags = normalizeTraceFlags(traceFlags);
const normalizedTraceId = normalizeTraceField(traceId, isValidDiagnosticTraceId);
const normalizedSpanId = normalizeTraceField(spanId, isValidDiagnosticSpanId);
const normalizedTraceFlags = normalizeTraceField(traceFlags, isValidDiagnosticTraceFlags);
if (!normalizedTraceId || !normalizedSpanId || !normalizedTraceFlags) {
return undefined;
}
@ -168,9 +143,10 @@ export function formatDiagnosticTraceparent(
if (!context?.spanId) {
return undefined;
}
const traceId = normalizeTraceId(context.traceId);
const spanId = normalizeSpanId(context.spanId);
const traceFlags = normalizeTraceFlags(context.traceFlags) ?? DEFAULT_TRACE_FLAGS;
const traceId = normalizeTraceField(context.traceId, isValidDiagnosticTraceId);
const spanId = normalizeTraceField(context.spanId, isValidDiagnosticSpanId);
const traceFlags =
normalizeTraceField(context.traceFlags, isValidDiagnosticTraceFlags) ?? DEFAULT_TRACE_FLAGS;
if (!traceId || !spanId) {
return undefined;
}
@ -182,14 +158,23 @@ export function createDiagnosticTraceContext(
input: DiagnosticTraceContextInput = {},
): DiagnosticTraceContext {
const parsed = parseDiagnosticTraceparent(input.traceparent);
const traceId = normalizeTraceId(input.traceId) ?? parsed?.traceId ?? randomTraceId();
const spanId = normalizeSpanId(input.spanId) ?? parsed?.spanId ?? randomSpanId();
const parentSpanId = normalizeSpanId(input.parentSpanId);
const traceId =
normalizeTraceField(input.traceId, isValidDiagnosticTraceId) ??
parsed?.traceId ??
randomNonZeroHex(16);
const spanId =
normalizeTraceField(input.spanId, isValidDiagnosticSpanId) ??
parsed?.spanId ??
randomNonZeroHex(8);
const parentSpanId = normalizeTraceField(input.parentSpanId, isValidDiagnosticSpanId);
return {
traceId,
spanId,
...(parentSpanId && parentSpanId !== spanId ? { parentSpanId } : {}),
traceFlags: normalizeTraceFlags(input.traceFlags) ?? parsed?.traceFlags ?? DEFAULT_TRACE_FLAGS,
traceFlags:
normalizeTraceField(input.traceFlags, isValidDiagnosticTraceFlags) ??
parsed?.traceFlags ??
DEFAULT_TRACE_FLAGS,
};
}
@ -198,7 +183,9 @@ export function createChildDiagnosticTraceContext(
parent: DiagnosticTraceContext,
input: Omit<DiagnosticTraceContextInput, "traceId" | "traceparent"> = {},
): DiagnosticTraceContext {
const parentSpanId = normalizeSpanId(input.parentSpanId) ?? normalizeSpanId(parent.spanId);
const parentSpanId =
normalizeTraceField(input.parentSpanId, isValidDiagnosticSpanId) ??
normalizeTraceField(parent.spanId, isValidDiagnosticSpanId);
return createDiagnosticTraceContext({
traceId: parent.traceId,
spanId: input.spanId,

View file

@ -342,38 +342,30 @@ function runInDiagnosticsTimelineSpan<T>(span: StartedDiagnosticsTimelineSpan, r
);
}
function emitFinishedDiagnosticsTimelineSpan(span: StartedDiagnosticsTimelineSpan): void {
emitDiagnosticsTimelineEvent(
{
type: "span.end",
name: span.name,
phase: span.phase,
spanId: span.spanId,
parentSpanId: span.parentSpanId,
durationMs: performance.now() - span.startedAt,
attributes: span.attributes,
},
{ config: span.config, env: span.env },
);
}
function emitFailedDiagnosticsTimelineSpan(
function emitFinishedDiagnosticsTimelineSpan(
span: StartedDiagnosticsTimelineSpan,
error: unknown,
failure?: { error: unknown },
): void {
emitDiagnosticsTimelineEvent(
{
type: "span.error",
type: failure ? "span.error" : "span.end",
name: span.name,
phase: span.phase,
spanId: span.spanId,
parentSpanId: span.parentSpanId,
durationMs: performance.now() - span.startedAt,
attributes: span.attributes,
errorName: error instanceof Error ? error.name : typeof error,
...(span.omitErrorMessage
? {}
: { errorMessage: error instanceof Error ? error.message : String(error) }),
...(failure
? {
errorName: failure.error instanceof Error ? failure.error.name : typeof failure.error,
...(span.omitErrorMessage
? {}
: {
errorMessage:
failure.error instanceof Error ? failure.error.message : String(failure.error),
}),
}
: {}),
},
{ config: span.config, env: span.env },
);
@ -394,7 +386,7 @@ export async function measureDiagnosticsTimelineSpan<T>(
emitFinishedDiagnosticsTimelineSpan(span);
return result;
} catch (error) {
emitFailedDiagnosticsTimelineSpan(span, error);
emitFinishedDiagnosticsTimelineSpan(span, { error });
throw error;
}
}
@ -414,7 +406,7 @@ export function measureDiagnosticsTimelineSpanSync<T>(
emitFinishedDiagnosticsTimelineSpan(span);
return result;
} catch (error) {
emitFailedDiagnosticsTimelineSpan(span, error);
emitFinishedDiagnosticsTimelineSpan(span, { error });
throw error;
}
}

View file

@ -13,6 +13,7 @@ export const MAX_DISPATCH_WRAPPER_DEPTH = 4;
const NICE_OPTIONS_WITH_VALUE = new Set(["-n", "--adjustment", "--priority"]);
const CAFFEINATE_OPTIONS_WITH_VALUE = new Set(["-t", "-w"]);
const CAFFEINATE_FLAG_OPTIONS = new Set(["-d", "-i", "-m", "-s", "-u"]);
const STDBUF_OPTIONS_WITH_VALUE = new Set(["-i", "--input", "-o", "--output", "-e", "--error"]);
const FLOCK_SHORT_FLAG_OPTIONS = new Set(["-e", "-F", "-n", "-o", "-s", "-x"]);
const FLOCK_LONG_FLAG_OPTIONS = new Set([
@ -150,7 +151,9 @@ export function extractEnvAssignmentKeysFromDispatchWrappers(
function unwrapDashOptionInvocation(
argv: string[],
params: {
onFlag: (flag: string, lowerToken: string) => WrapperScanDirective;
onFlag?: (flag: string, lowerToken: string) => WrapperScanDirective;
flagOptions?: ReadonlySet<string>;
optionsWithValue?: ReadonlySet<string>;
adjustCommandIndex?: (commandIndex: number, argv: string[]) => number | null;
},
): string[] | null {
@ -161,7 +164,16 @@ function unwrapDashOptionInvocation(
return "stop";
}
const { name: flag } = parseInlineOptionToken(lower);
return params.onFlag(flag, lower);
if (params.onFlag) {
return params.onFlag(flag, lower);
}
if (params.flagOptions?.has(flag)) {
return "continue";
}
if (params.optionsWithValue?.has(flag)) {
return lower.includes("=") ? "continue" : "consume-next";
}
return "invalid";
},
adjustCommandIndex: params.adjustCommandIndex,
});
@ -184,20 +196,6 @@ function unwrapNiceInvocation(argv: string[]): string[] | null {
});
}
function unwrapCaffeinateInvocation(argv: string[]): string[] | null {
return unwrapDashOptionInvocation(argv, {
onFlag: (flag, lower) => {
if (flag === "-d" || flag === "-i" || flag === "-m" || flag === "-s" || flag === "-u") {
return "continue";
}
if (CAFFEINATE_OPTIONS_WITH_VALUE.has(flag)) {
return lower !== flag || lower.includes("=") ? "continue" : "consume-next";
}
return "invalid";
},
});
}
function unwrapNohupInvocation(argv: string[]): string[] | null {
return scanWrapperInvocation(argv, {
separators: new Set(["--"]),
@ -210,42 +208,6 @@ function unwrapNohupInvocation(argv: string[]): string[] | null {
});
}
function unwrapSandboxExecInvocation(argv: string[]): string[] | null {
return unwrapDashOptionInvocation(argv, {
onFlag: (flag, lower) => {
if (SANDBOX_EXEC_OPTIONS_WITH_VALUE.has(flag)) {
return lower !== flag || lower.includes("=") ? "continue" : "consume-next";
}
return "invalid";
},
});
}
function unwrapStdbufInvocation(argv: string[]): string[] | null {
return unwrapDashOptionInvocation(argv, {
onFlag: (flag, lower) => {
if (!STDBUF_OPTIONS_WITH_VALUE.has(flag)) {
return "invalid";
}
return lower.includes("=") ? "continue" : "consume-next";
},
});
}
function unwrapTimeInvocation(argv: string[]): string[] | null {
return unwrapDashOptionInvocation(argv, {
onFlag: (flag, lower) => {
if (TIME_FLAG_OPTIONS.has(flag)) {
return "continue";
}
if (TIME_OPTIONS_WITH_VALUE.has(flag)) {
return lower.includes("=") ? "continue" : "consume-next";
}
return "invalid";
},
});
}
function isFlockShortFlagCluster(token: string): boolean {
return /^-[eFnsxo]+$/.test(token);
}
@ -365,15 +327,8 @@ function unwrapScriptInvocation(
function unwrapTimeoutInvocation(argv: string[]): string[] | null {
return unwrapDashOptionInvocation(argv, {
onFlag: (flag, lower) => {
if (TIMEOUT_FLAG_OPTIONS.has(flag)) {
return "continue";
}
if (TIMEOUT_OPTIONS_WITH_VALUE.has(flag)) {
return lower.includes("=") ? "continue" : "consume-next";
}
return "invalid";
},
flagOptions: TIMEOUT_FLAG_OPTIONS,
optionsWithValue: TIMEOUT_OPTIONS_WITH_VALUE,
adjustCommandIndex: (commandIndex, currentArgv) => {
const wrappedCommandIndex = commandIndex + 1;
return wrappedCommandIndex < currentArgv.length ? wrappedCommandIndex : null;
@ -444,7 +399,15 @@ const DISPATCH_WRAPPER_SPECS: readonly DispatchWrapperSpec[] = [
supportsArchDispatchWrapper(platform) ? unwrapArchInvocation(argv) : null,
transparentUsage: (_argv, platform) => supportsArchDispatchWrapper(platform),
},
{ name: "caffeinate", unwrap: unwrapCaffeinateInvocation, transparentUsage: true },
{
name: "caffeinate",
unwrap: (argv) =>
unwrapDashOptionInvocation(argv, {
flagOptions: CAFFEINATE_FLAG_OPTIONS,
optionsWithValue: CAFFEINATE_OPTIONS_WITH_VALUE,
}),
transparentUsage: true,
},
{ name: "bwrap" },
{ name: "catchsegv" },
{ name: "chrt" },
@ -472,19 +435,37 @@ const DISPATCH_WRAPPER_SPECS: readonly DispatchWrapperSpec[] = [
{ name: "proxychains" },
{ name: "proxychains4" },
{ name: "runuser" },
{ name: "sandbox-exec", unwrap: unwrapSandboxExecInvocation, transparentUsage: true },
{
name: "sandbox-exec",
unwrap: (argv) =>
unwrapDashOptionInvocation(argv, {
optionsWithValue: SANDBOX_EXEC_OPTIONS_WITH_VALUE,
}),
transparentUsage: true,
},
{ name: "script", unwrap: unwrapScriptInvocation, transparentUsage: false },
{ name: "setarch" },
{ name: "setsid" },
{ name: "setpriv" },
{ name: "stdbuf", unwrap: unwrapStdbufInvocation, transparentUsage: true },
{
name: "stdbuf",
unwrap: (argv) =>
unwrapDashOptionInvocation(argv, {
optionsWithValue: STDBUF_OPTIONS_WITH_VALUE,
}),
transparentUsage: true,
},
{ name: "su" },
{ name: "sudo" },
{ name: "systemd-run" },
{ name: "taskset" },
{
name: "time",
unwrap: unwrapTimeInvocation,
unwrap: (argv) =>
unwrapDashOptionInvocation(argv, {
flagOptions: TIME_FLAG_OPTIONS,
optionsWithValue: TIME_OPTIONS_WITH_VALUE,
}),
transparentUsage: (argv) => !timeInvocationWritesOutputFile(argv),
},
{ name: "timeout", unwrap: unwrapTimeoutInvocation, transparentUsage: true },

View file

@ -1,11 +1,9 @@
// Normalizes env flag values and logs env warnings lazily.
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
import type { SubsystemLogger } from "../logging/subsystem.js";
import { createLazyPromise } from "../shared/lazy-runtime.js";
import { parseBooleanValue } from "../utils/boolean.js";
export { isFastTestRuntimeEnv, isVitestRuntimeEnv } from "./test-runtime-env.js";
let log: SubsystemLogger | null = null;
const loadLog = createLazyPromise(
() =>
import("../logging/subsystem.js").then(({ createSubsystemLogger }) =>
@ -16,13 +14,6 @@ const loadLog = createLazyPromise(
const loggedEnv = new Set<string>();
const ENV_NORMALIZATION_KEY_GROUPS = [["ZAI_API_KEY", "Z_AI_API_KEY"]] as const;
async function getLog(): Promise<SubsystemLogger> {
if (!log) {
log = await loadLog();
}
return log;
}
type AcceptedEnvOption = {
key: string;
description: string;
@ -54,7 +45,7 @@ export function logAcceptedEnvOption(option: AcceptedEnvOption): void {
return;
}
loggedEnv.add(option.key);
void getLog()
void loadLog()
.then((logger) => {
logger.info(
`env: ${option.key}=${formatEnvValue(rawValue, option.redact)} (${option.description})`,

View file

@ -149,48 +149,22 @@ function buildApprovalActionDescriptors(
approvalCommandId: string,
allowedDecisions: readonly ExecApprovalReplyDecision[],
): ExecApprovalActionDescriptor[] {
const descriptors: ExecApprovalActionDescriptor[] = [];
const buildDescriptor = (descriptor: {
decision: ExecApprovalReplyDecision;
label: string;
style: ExecApprovalActionDescriptor["style"];
}): ExecApprovalActionDescriptor => {
return {
...descriptor,
const decisions: Pick<ExecApprovalActionDescriptor, "decision" | "label" | "style">[] = [
{ decision: "allow-once", label: "Allow Once", style: "success" },
{ decision: "allow-always", label: "Allow Always", style: "primary" },
{ decision: "deny", label: "Deny", style: "danger" },
];
return decisions
.filter((descriptor) => allowedDecisions.includes(descriptor.decision))
.map((descriptor) => ({
decision: descriptor.decision,
label: descriptor.label,
style: descriptor.style,
command: buildExecApprovalCommandText({
approvalCommandId,
decision: descriptor.decision,
}),
};
};
if (allowedDecisions.includes("allow-once")) {
descriptors.push(
buildDescriptor({
decision: "allow-once",
label: "Allow Once",
style: "success",
}),
);
}
if (allowedDecisions.includes("allow-always")) {
descriptors.push(
buildDescriptor({
decision: "allow-always",
label: "Allow Always",
style: "primary",
}),
);
}
if (allowedDecisions.includes("deny")) {
descriptors.push(
buildDescriptor({
decision: "deny",
label: "Deny",
style: "danger",
}),
);
}
return descriptors;
}));
}
export function buildExecApprovalActionDescriptors(

View file

@ -298,19 +298,7 @@ export function resolveAllowAlwaysPatternCoverage(params: {
const byKey = new Map<string, ReturnType<typeof resolveAllowAlwaysPatternEntries>[number]>();
let representedSegmentCount = 0;
for (const segment of params.segments) {
if (isShellWrapperInvocation(segment.argv)) {
const segmentPatterns = resolveAllowAlwaysPatternEntries({
segments: [segment],
cwd: params.cwd,
env: params.env,
platform: params.platform,
strictInlineEval: params.strictInlineEval,
});
for (const pattern of segmentPatterns) {
byKey.set(`${pattern.pattern}\x00${pattern.argPattern ?? ""}`, pattern);
}
continue;
}
const shellWrapper = isShellWrapperInvocation(segment.argv);
const segmentPatterns = resolveAllowAlwaysPatternEntries({
segments: [segment],
cwd: params.cwd,
@ -321,7 +309,9 @@ export function resolveAllowAlwaysPatternCoverage(params: {
if (segmentPatterns.length === 0) {
continue;
}
representedSegmentCount += 1;
if (!shellWrapper) {
representedSegmentCount += 1;
}
for (const pattern of segmentPatterns) {
byKey.set(`${pattern.pattern}\x00${pattern.argPattern ?? ""}`, pattern);
}

View file

@ -355,7 +355,7 @@ function coerceAllowlistEntries(allowlist: unknown): ExecAllowlistEntry[] | unde
return changed ? (result.length > 0 ? result : undefined) : (allowlist as ExecAllowlistEntry[]);
}
function ensureAllowlistIds(
function normalizeAllowlistMetadata(
allowlist: ExecAllowlistEntry[] | undefined,
): ExecAllowlistEntry[] | undefined {
if (!Array.isArray(allowlist) || allowlist.length === 0) {
@ -363,29 +363,16 @@ function ensureAllowlistIds(
}
let changed = false;
const next = allowlist.map((entry) => {
if (entry.id) {
return entry;
let normalized = entry;
if (!normalized.id) {
normalized = { ...normalized, id: crypto.randomUUID() };
}
changed = true;
return { ...entry, id: crypto.randomUUID() };
});
return changed ? next : allowlist;
}
function stripAllowlistCommandText(
allowlist: ExecAllowlistEntry[] | undefined,
): ExecAllowlistEntry[] | undefined {
if (!Array.isArray(allowlist) || allowlist.length === 0) {
return allowlist;
}
let changed = false;
const next = allowlist.map((entry) => {
if (typeof entry.commandText !== "string") {
return entry;
if (typeof normalized.commandText === "string") {
const { commandText: _commandText, ...rest } = normalized;
normalized = rest;
}
changed = true;
const { commandText: _commandText, ...rest } = entry;
return rest;
changed ||= normalized !== entry;
return normalized;
});
return changed ? next : allowlist;
}
@ -421,8 +408,7 @@ export function normalizeExecApprovalsInternal(file: ExecApprovalsFile): ExecApp
}
for (const [key, agent] of Object.entries(agents)) {
const coerced = coerceAllowlistEntries(agent.allowlist);
const withIds = ensureAllowlistIds(coerced);
const allowlist = stripAllowlistCommandText(withIds);
const allowlist = normalizeAllowlistMetadata(coerced);
const sanitizedPolicy = sanitizeExecApprovalPolicy(agent);
const agentChanged =
allowlist !== agent.allowlist ||

View file

@ -198,20 +198,14 @@ function riskBeforeStepExecutable(risk: CommandRisk, step: CommandStep): boolean
return riskInsideStep(risk, step) && risk.span.endIndex <= step.executableSpan.startIndex;
}
function stepReasons(step: CommandStep, risks: readonly CommandRisk[]): string[] {
function stepReasons(
step: CommandStep,
risks: readonly CommandRisk[],
kinds: ReadonlySet<CommandRisk["kind"]> = PROMPT_ONLY_RISKS,
): string[] {
const reasons: string[] = [];
for (const risk of risks) {
if (PROMPT_ONLY_RISKS.has(risk.kind) && riskInsideStep(risk, step)) {
reasons.push(risk.kind);
}
}
return uniqueStrings(reasons);
}
function nonReusableStepReasons(step: CommandStep, risks: readonly CommandRisk[]): string[] {
const reasons: string[] = [];
for (const risk of risks) {
if (NON_REUSABLE_RISKS.has(risk.kind) && riskInsideStep(risk, step)) {
if (kinds.has(risk.kind) && riskInsideStep(risk, step)) {
reasons.push(risk.kind);
}
}
@ -411,7 +405,7 @@ function createCandidate(params: {
params.transport.kind === "direct" &&
extractBindableShellWrapperInlineCommand(params.segment.argv);
const stepPromptReasons = stepReasons(params.step, params.risks);
const stepNonReusableReasons = nonReusableStepReasons(params.step, params.risks);
const stepNonReusableReasons = stepReasons(params.step, params.risks, NON_REUSABLE_RISKS);
const preludeReasons = hasCommandPrelude(params.step)
? shellWrapperPreludeReasons({ step: params.step, risks: params.risks })
: [];
@ -621,22 +615,8 @@ function wrapperPayloadPlan(params: {
return null;
}
const carriedSteps = positionalCarrierSteps({ wrapper, context: params.context });
if (carriedSteps) {
const transport: ExecAuthorizationTransport = {
kind: "shell-wrapper",
wrapperSegment: wrapper.segment,
wrapperArgv: wrapper.segment.argv,
wrapperPrefix: wrapperPrefixForStep(wrapper.step),
inlineCommand: wrapperRisk.payload,
};
const groups = groupsFromSteps({
steps: carriedSteps,
transport,
risks: params.risks,
});
return groups.length > 0 ? applyWrapperPayloadPersistenceBoundary({ wrapper, groups }) : null;
}
if (
!carriedSteps &&
!shouldUseWrapperPayload({
wrapperCommandId: wrapper.step.id,
topLevelSteps: params.topLevelSteps,
@ -660,8 +640,8 @@ function wrapperPayloadPlan(params: {
? params.operators.filter((operator) => operator.parentCommandId === wrapper.step.id)
: params.operators;
const groups = groupsFromSteps({
steps: nestedStepsForWrapper,
operators: operatorsForWrapper,
steps: carriedSteps ?? nestedStepsForWrapper,
operators: carriedSteps ? undefined : operatorsForWrapper,
transport,
risks: params.risks,
});

View file

@ -3,13 +3,13 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import { expectDefined } from "@openclaw/normalization-core";
import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce";
import { normalizeStringEntries } from "@openclaw/normalization-core/string-normalization";
import {
normalizeStringEntries,
uniqueStrings,
} from "@openclaw/normalization-core/string-normalization";
import { splitShellArgs } from "../utils/shell-argv.js";
import { resolvePathViaExistingAncestorSync } from "./boundary-path.js";
import {
buildCommandPayloadArgvCandidates,
buildCommandPayloadCandidates,
} from "./command-analysis/risks.js";
import { buildCommandPayloadArgvCandidates } from "./command-analysis/risks.js";
import {
CommandExplanationWorkLimitError,
explainShellCommand,
@ -17,11 +17,6 @@ import {
import type { CommandExplanation } from "./command-explainer/types.js";
import { isPathInside } from "./path-guards.js";
type ParsedExecApprovalCommand = {
approvalId: string;
decision: "allow-once" | "allow-always" | "deny";
};
type UnsafeExecControlShellCommandKind =
| "approve"
| "channel-login"
@ -56,21 +51,10 @@ const SQLITE_OPEN_OPTIONS_WITH_VALUES = new Map<string, number>([
["textkey", 1],
]);
function parseExecApprovalShellCommand(raw: string): ParsedExecApprovalCommand | null {
const normalized = raw.trimStart();
const match = normalized.match(
/^\/approve(?:@[^\s]+)?\s+([A-Za-z0-9][A-Za-z0-9._:-]*)\s+(allow-once|allow-always|always|deny)\b/i,
function isExecApprovalShellCommand(raw: string): boolean {
return /^\/approve(?:@[^\s]+)?\s+([A-Za-z0-9][A-Za-z0-9._:-]*)\s+(allow-once|allow-always|always|deny)\b/i.test(
raw.trimStart(),
);
if (!match) {
return null;
}
return {
approvalId: expectDefined(match[1], "exec control command guard regex capture 1"),
decision:
normalizeLowercaseStringOrEmpty(match[2]) === "always"
? "allow-always"
: (normalizeLowercaseStringOrEmpty(match[2]) as ParsedExecApprovalCommand["decision"]),
};
}
function normalizeCommandBaseName(token: string | undefined): string {
@ -275,29 +259,19 @@ export async function detectUnsafeExecControlShellCommand(
}
// Fall back to line-local shell splitting below.
}
const { controlCandidates, argvCandidates } = (() => {
const argvCandidates = (() => {
if (explanation?.ok) {
const commands = [...explanation.topLevelCommands, ...explanation.nestedCommands];
return {
controlCandidates: commands.flatMap((step) => buildCommandPayloadCandidates(step.argv)),
argvCandidates: commands.flatMap((step) => buildCommandPayloadArgvCandidates(step.argv)),
};
return commands.flatMap((step) => buildCommandPayloadArgvCandidates(step.argv));
}
const fallbackArgv = normalizeStringEntries(rawCommand.split(/\r?\n/)).map((line) => {
return normalizeStringEntries(rawCommand.split(/\r?\n/)).flatMap((line) => {
const argv = splitShellArgs(line);
return { argv, line };
return argv ? buildCommandPayloadArgvCandidates(argv) : [[line]];
});
return {
controlCandidates: fallbackArgv.flatMap(({ argv, line }) =>
argv ? buildCommandPayloadCandidates(argv) : [line],
),
argvCandidates: fallbackArgv.flatMap(({ argv, line }) =>
argv ? buildCommandPayloadArgvCandidates(argv) : [[line]],
),
};
})();
const controlCandidates = uniqueStrings(argvCandidates.map((argv) => argv.join(" ")));
for (const candidate of controlCandidates) {
if (parseExecApprovalShellCommand(candidate)) {
if (isExecApprovalShellCommand(candidate)) {
return "approve";
}
if (parseOpenClawChannelsLoginShellCommand(candidate)) {

View file

@ -1,12 +1,10 @@
// Evaluates heartbeat active-hours windows.
import { resolveUserTimezone } from "../agents/date-time.js";
import type { AgentDefaultsConfig } from "../config/types.agent-defaults.js";
import type { OpenClawConfig } from "../config/types.openclaw.js";
import type { HeartbeatConfig } from "./heartbeat-config.js";
// Heartbeat active-hours helpers interpret user/local/IANA timezones and treat
// invalid config as permissive so bad schedules do not disable heartbeats.
type HeartbeatConfig = AgentDefaultsConfig["heartbeat"];
const ACTIVE_HOURS_TIME_PATTERN = /^(?:([01]\d|2[0-3]):([0-5]\d)|24:00)$/;
/** Resolve the formatter used to evaluate heartbeat active hours. */
@ -41,16 +39,7 @@ function parseActiveHoursTime(opts: { allow24: boolean }, raw?: string): number
const [hourStr, minuteStr] = raw.split(":");
const hour = Number(hourStr);
const minute = Number(minuteStr);
if (!Number.isFinite(hour) || !Number.isFinite(minute)) {
return null;
}
if (hour === 24) {
if (!opts.allow24 || minute !== 0) {
return null;
}
return 24 * 60;
}
return hour * 60 + minute;
return hour === 24 && !opts.allow24 ? null : hour * 60 + minute;
}
function resolveMinutesInTimeZone(nowMs: number, formatter: Intl.DateTimeFormat): number | null {

View file

@ -95,33 +95,14 @@ export function shouldDeferWake(input: ShouldDeferInput): DeferDecision {
return { defer: false };
}
if (input.intent === "immediate") {
// Even immediate wakes get rate-limited if a real flood is happening — but
// manual operator intent is fully exempt above. System-event, task, hook,
// and cron wake-now paths come from external systems we trust but cannot
// prove are loop-free, so the flood guard remains a backstop.
const floodDefer = checkFloodGuard(input);
return floodDefer ?? { defer: false };
}
if (input.intent === "task") {
const floodDefer = checkFloodGuard(input);
if (floodDefer) {
return floodDefer;
}
const spacingRetryAtMs = resolveMinSpacingRetryAtMs(input);
if (spacingRetryAtMs !== undefined) {
return { defer: true, reason: "min-spacing", retryAtMs: spacingRetryAtMs };
}
return { defer: false };
}
// Flood guard applies to every non-immediate wake regardless of run history.
// It is the last line of defense against feedback loops.
// System wake-now paths can form feedback loops too; only manual intent is exempt.
const floodDefer = checkFloodGuard(input);
if (floodDefer) {
return floodDefer;
}
if (input.intent === "immediate") {
return { defer: false };
}
if (input.intent === "scheduled") {
return input.now < input.nextDueMs
@ -136,7 +117,7 @@ export function shouldDeferWake(input: ShouldDeferInput): DeferDecision {
return { defer: false };
}
if (!input.retainedWork && input.now < input.nextDueMs) {
if (input.intent !== "task" && !input.retainedWork && input.now < input.nextDueMs) {
const spacingRetryAtMs = resolveMinSpacingRetryAtMs(input);
return {
defer: true,

View file

@ -160,29 +160,6 @@ function prepareHeartbeatTargetAwareness(params: {
}
}
/**
* Determines whether to set an indicator type for heartbeat delivery.
* This is used when delivery would otherwise be suppressed but we still want
* to indicate that the heartbeat completed successfully.
*
* Returns "alert" when alerts are disabled but delivery would otherwise succeed,
* and "sent" when the heartbeat was sent. Returns undefined in all other cases.
*/
function shouldSetIndicator(
noChannelTarget: boolean,
visibility: { showAlerts: boolean; useIndicator: boolean },
): "sent" | "alert" | undefined {
if (noChannelTarget || !visibility.useIndicator) {
return undefined;
}
// When alerts are disabled, use "alert" indicator to show heartbeat was processed.
if (!visibility.showAlerts) {
return "alert";
}
// Otherwise, heartbeat was sent successfully.
return "sent";
}
/** Monitoring decides which final is public before ordinary dispatch can send it. */
async function prepareHeartbeatDispatchReply(
policy: HeartbeatDispatch,
@ -468,9 +445,10 @@ async function prepareHeartbeatDispatchReply(
status: "skipped",
reason: noChannelTarget ? (delivery.reason ?? "no-target") : "alerts-disabled",
hasMedia: outcome.mediaUrls.length > 0,
indicatorType: shouldSetIndicator(noChannelTarget, visibility)
? resolveIndicatorType("sent")
: undefined,
indicatorType:
!noChannelTarget && visibility.useIndicator
? resolveIndicatorType("sent")
: undefined,
},
!failed,
);

View file

@ -43,41 +43,45 @@ export function resolveHeartbeatSessionKey(
return mainSession();
}
const resolveCandidate = (requestKey: string) => {
const candidate = toAgentStoreSessionKey({
agentId: resolvedAgentId,
requestKey,
mainKey: cfg.session?.mainKey,
});
if (isSubagentSessionKey(candidate)) {
return undefined;
}
const canonical = canonicalizeMainSessionAlias({
cfg,
agentId: resolvedAgentId,
sessionKey: candidate,
});
return canonical !== "global" &&
!isSubagentSessionKey(canonical) &&
resolveAgentIdFromSessionKey(canonical) === normalizeAgentId(resolvedAgentId)
? canonical
: undefined;
};
// Guard: never route heartbeats to subagent sessions, regardless of entry path.
const forced = forcedSessionKey?.trim();
if (forced && isSubagentSessionKey(forced)) {
return mainSession(true);
}
if (forced && !isSubagentSessionKey(forced)) {
const forcedCandidate = toAgentStoreSessionKey({
agentId: resolvedAgentId,
requestKey: forced,
mainKey: cfg.session?.mainKey,
});
if (!isSubagentSessionKey(forcedCandidate)) {
const forcedCanonical = canonicalizeMainSessionAlias({
cfg,
agentId: resolvedAgentId,
sessionKey: forcedCandidate,
});
if (forcedCanonical !== "global" && !isSubagentSessionKey(forcedCanonical)) {
const sessionAgentId = resolveAgentIdFromSessionKey(forcedCanonical);
if (sessionAgentId === normalizeAgentId(resolvedAgentId)) {
const routedSessionKey =
resolveMainScopedEventSessionKey({
cfg,
sessionKey: forcedCanonical,
agentId: resolvedAgentId,
}) ?? forcedCanonical;
return {
sessionKey: routedSessionKey,
storePath,
suppressOriginatingContext: false,
};
}
}
}
const forcedCanonical = forced ? resolveCandidate(forced) : undefined;
if (forcedCanonical) {
return {
sessionKey:
resolveMainScopedEventSessionKey({
cfg,
sessionKey: forcedCanonical,
agentId: resolvedAgentId,
}) ?? forcedCanonical,
storePath,
suppressOriginatingContext: false,
};
}
const trimmed = heartbeat?.session?.trim() ?? "";
@ -90,31 +94,10 @@ export function resolveHeartbeatSessionKey(
return mainSession();
}
const candidate = toAgentStoreSessionKey({
agentId: resolvedAgentId,
requestKey: trimmed,
mainKey: cfg.session?.mainKey,
});
if (isSubagentSessionKey(candidate)) {
return mainSession();
}
const canonical = canonicalizeMainSessionAlias({
cfg,
agentId: resolvedAgentId,
sessionKey: candidate,
});
if (canonical !== "global" && !isSubagentSessionKey(canonical)) {
const sessionAgentId = resolveAgentIdFromSessionKey(canonical);
if (sessionAgentId === normalizeAgentId(resolvedAgentId)) {
return {
sessionKey: canonical,
storePath,
suppressOriginatingContext: false,
};
}
}
return mainSession();
const canonical = resolveCandidate(trimmed);
return canonical
? { sessionKey: canonical, storePath, suppressOriginatingContext: false }
: mainSession();
}
export function resolveHeartbeatSession(

View file

@ -27,21 +27,11 @@ export function resolveHeartbeatVisibility(params: {
}): ResolvedHeartbeatVisibility {
const { cfg, channel, accountId } = params;
// Webchat has no channel/account config branch, so only shared channel defaults apply.
if (channel === "webchat") {
const channelDefaults = cfg.channels?.defaults?.heartbeatVisibility;
return {
showOk: channelDefaults?.showOk ?? DEFAULT_VISIBILITY.showOk,
showAlerts: channelDefaults?.showAlerts ?? DEFAULT_VISIBILITY.showAlerts,
useIndicator: channelDefaults?.useIndicator ?? DEFAULT_VISIBILITY.useIndicator,
};
}
// Layer 1: Global channel defaults
const channelDefaults = cfg.channels?.defaults?.heartbeatVisibility;
// Layer 2: Per-channel config (at channel root level)
const channelCfg = cfg.channels?.[channel] as
// Webchat has no channel/account config branch, so only shared channel defaults apply.
const channelCfg = (channel === "webchat" ? undefined : cfg.channels?.[channel]) as
| {
heartbeatVisibility?: ChannelHeartbeatVisibilityConfig;
accounts?: Record<string, { heartbeatVisibility?: ChannelHeartbeatVisibilityConfig }>;
@ -50,9 +40,10 @@ export function resolveHeartbeatVisibility(params: {
const perChannel = channelCfg?.heartbeatVisibility;
// Layer 3: Per-account config (most specific)
const accountCfg = accountId
? resolveChannelAccountEntry(channelCfg?.accounts, accountId, channel, (id) => id)
: undefined;
const accountCfg =
channel !== "webchat" && accountId
? resolveChannelAccountEntry(channelCfg?.accounts, accountId, channel, (id) => id)
: undefined;
const perAccount = accountCfg?.heartbeatVisibility;
return {

View file

@ -133,23 +133,7 @@ export function mergeSsrFPolicies(
return Object.keys(merged).length > 0 ? merged : undefined;
}
export function ssrfPolicyFromHttpBaseUrlAllowedHostname(baseUrl: string): SsrFPolicy | undefined {
const trimmed = baseUrl.trim();
if (!trimmed) {
return undefined;
}
try {
const parsed = new URL(trimmed);
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
return undefined;
}
return { allowedHostnames: [parsed.hostname] };
} catch {
return undefined;
}
}
function normalizeSsrFPolicyOrigin(value: string): string | undefined {
function parseHttpBaseUrl(value: string): URL | undefined {
const trimmed = value.trim();
if (!trimmed) {
return undefined;
@ -159,13 +143,26 @@ function normalizeSsrFPolicyOrigin(value: string): string | undefined {
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
return undefined;
}
parsed.hostname = parsed.hostname.replace(/\.+$/, "");
return parsed.origin.toLowerCase();
return parsed;
} catch {
return undefined;
}
}
export function ssrfPolicyFromHttpBaseUrlAllowedHostname(baseUrl: string): SsrFPolicy | undefined {
const parsed = parseHttpBaseUrl(baseUrl);
return parsed ? { allowedHostnames: [parsed.hostname] } : undefined;
}
function normalizeSsrFPolicyOrigin(value: string): string | undefined {
const parsed = parseHttpBaseUrl(value);
if (!parsed) {
return undefined;
}
parsed.hostname = parsed.hostname.replace(/\.+$/, "");
return parsed.origin.toLowerCase();
}
function normalizeSsrFPolicyOrigins(values?: string[]): string[] {
if (!values || values.length === 0) {
return [];
@ -187,23 +184,14 @@ export function ssrfPolicyFromHttpBaseUrlAllowedOrigin(baseUrl: string): SsrFPol
export function ssrfPolicyFromHttpBaseUrlFakeIpHostnameAllowlist(
baseUrl: string,
): SsrFPolicy | undefined {
const trimmed = baseUrl.trim();
if (!trimmed) {
return undefined;
}
try {
const parsed = new URL(trimmed);
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
return undefined;
}
return {
allowRfc2544BenchmarkRange: true,
allowIpv6UniqueLocalRange: true,
hostnameAllowlist: [parsed.hostname],
};
} catch {
return undefined;
}
const parsed = parseHttpBaseUrl(baseUrl);
return parsed
? {
allowRfc2544BenchmarkRange: true,
allowIpv6UniqueLocalRange: true,
hostnameAllowlist: [parsed.hostname],
}
: undefined;
}
const BLOCKED_HOSTNAMES = new Set([
@ -721,9 +709,6 @@ export function createPinnedDispatcher(
const proxyUrl = policy.proxyUrl.trim();
const requestTls = withPinnedLookup(lookup, policy.proxyTls);
if (!requestTls) {
return createHttp1ProxyAgent({ uri: proxyUrl }, timeoutMs);
}
return createHttp1ProxyAgent(
{
uri: proxyUrl,

View file

@ -100,14 +100,7 @@ function resolveAgentDeliveryPlan(params: {
if (requestedChannel === INTERNAL_MESSAGE_CHANNEL) {
return INTERNAL_MESSAGE_CHANNEL;
}
if (requestedChannel === "last") {
if (baseDelivery.channel && baseDelivery.channel !== INTERNAL_MESSAGE_CHANNEL) {
return baseDelivery.channel;
}
return INTERNAL_MESSAGE_CHANNEL;
}
if (isGatewayMessageChannel(requestedChannel)) {
if (requestedChannel !== "last" && isGatewayMessageChannel(requestedChannel)) {
return requestedChannel;
}
@ -390,14 +383,10 @@ export function resolveAgentOutboundTarget(params: {
targetMode,
};
}
if (!isDeliverableMessageChannel(params.plan.resolvedChannel)) {
return {
resolvedTarget: null,
resolvedTo: params.plan.resolvedTo,
targetMode,
};
}
if (params.validateExplicitTarget !== true && params.plan.resolvedTo) {
if (
!isDeliverableMessageChannel(params.plan.resolvedChannel) ||
(params.validateExplicitTarget !== true && params.plan.resolvedTo)
) {
return {
resolvedTarget: null,
resolvedTo: params.plan.resolvedTo,

View file

@ -56,9 +56,10 @@ function* normalizeOutboundChannelForResolution(params: OutboundChannelResolutio
return { channel: deliverable, didBootstrap: false };
}
const activeRuntimePlugin = resolveActivatedOutboundPluginFromRuntimeRegistry(
const activeRuntimePlugin = resolveOutboundPluginFromRuntimeRegistry(
normalized,
getOutboundRuntimeRegistry() ?? undefined,
true,
);
if (activeRuntimePlugin) {
return {
@ -77,9 +78,10 @@ function* normalizeOutboundChannelForResolution(params: OutboundChannelResolutio
cfg: params.cfg,
agentId: params.agentId,
};
const bootstrappedRuntimePlugin = resolveActivatedOutboundPluginFromRuntimeRegistry(
const bootstrappedRuntimePlugin = resolveOutboundPluginFromRuntimeRegistry(
normalized,
bootstrapRegistry,
true,
);
return {
channel: bootstrappedRuntimePlugin?.id ?? normalized,
@ -107,14 +109,6 @@ function channelPluginHasActivatedOutboundSurface(plugin: ChannelPlugin | undefi
);
}
function resolveRuntimeOutboundPlugin(plugin: ChannelPlugin): ChannelPlugin | undefined {
return channelPluginHasRuntimeOutboundSurface(plugin) ? plugin : undefined;
}
function resolveActivatedOutboundPlugin(plugin: ChannelPlugin): ChannelPlugin | undefined {
return channelPluginHasActivatedOutboundSurface(plugin) ? plugin : undefined;
}
function resolveRuntimeOutboundPluginCandidate(params: {
loaded?: ChannelPlugin;
runtime?: ChannelPlugin;
@ -141,34 +135,16 @@ function resolveRuntimeOutboundPluginCandidate(params: {
return undefined;
}
function resolveValueFromRuntimeRegistry<TValue>(
function resolveOutboundPluginFromRuntimeRegistry(
channel: string,
resolveValue: (plugin: ChannelPlugin) => TValue | undefined,
registry: PluginRegistry | null | undefined = getOutboundRuntimeRegistry(),
): TValue | undefined {
requireActivatedRuntime = false,
): ChannelPlugin | undefined {
const plugin = findChannelPluginInRegistry(registry, channel);
return plugin ? resolveValue(plugin) : undefined;
}
function resolveDirectFromRuntimeRegistry(
channel: string,
registry?: PluginRegistry,
): ChannelPlugin | undefined {
return resolveValueFromRuntimeRegistry(channel, (plugin) => plugin, registry);
}
function resolveRuntimeOutboundPluginFromRuntimeRegistry(
channel: string,
registry?: PluginRegistry,
): ChannelPlugin | undefined {
return resolveValueFromRuntimeRegistry(channel, resolveRuntimeOutboundPlugin, registry);
}
function resolveActivatedOutboundPluginFromRuntimeRegistry(
channel: string,
registry?: PluginRegistry,
): ChannelPlugin | undefined {
return resolveValueFromRuntimeRegistry(channel, resolveActivatedOutboundPlugin, registry);
const hasSurface = requireActivatedRuntime
? channelPluginHasActivatedOutboundSurface
: channelPluginHasRuntimeOutboundSurface;
return hasSurface(plugin) ? plugin : undefined;
}
function* resolveOutboundChannelPluginSteps(
@ -196,9 +172,10 @@ function* resolveOutboundChannelPluginSteps(
if (didBootstrap) {
return undefined;
}
return resolveActivatedOutboundPluginFromRuntimeRegistry(
return resolveOutboundPluginFromRuntimeRegistry(
normalized,
yield { ...params, channel: normalized },
true,
);
}
@ -206,10 +183,15 @@ function* resolveOutboundChannelPluginSteps(
const resolve = () => getChannelPlugin(normalized);
const current = resolveLoaded();
const requireActivatedRuntime = params.allowBootstrap === true;
const runtimeCurrent = requireActivatedRuntime
? resolveActivatedOutboundPluginFromRuntimeRegistry(normalized, bootstrapRegistry)
: resolveRuntimeOutboundPluginFromRuntimeRegistry(normalized, bootstrapRegistry);
const setupFallback = resolveDirectFromRuntimeRegistry(normalized, bootstrapRegistry);
const runtimeCurrent = resolveOutboundPluginFromRuntimeRegistry(
normalized,
bootstrapRegistry,
requireActivatedRuntime,
);
const setupFallback = findChannelPluginInRegistry(
bootstrapRegistry ?? getOutboundRuntimeRegistry(),
normalized,
);
const bundledCurrent = resolve();
const candidate = resolveRuntimeOutboundPluginCandidate({
loaded: current,
@ -234,8 +216,11 @@ function* resolveOutboundChannelPluginSteps(
};
return resolveRuntimeOutboundPluginCandidate({
loaded: resolveLoaded(),
runtime: resolveActivatedOutboundPluginFromRuntimeRegistry(normalized, registry),
setupFallback: resolveDirectFromRuntimeRegistry(normalized, registry),
runtime: resolveOutboundPluginFromRuntimeRegistry(normalized, registry, true),
setupFallback: findChannelPluginInRegistry(
registry ?? getOutboundRuntimeRegistry(),
normalized,
),
bundled: resolve(),
requireActivatedRuntime: true,
});

View file

@ -229,46 +229,15 @@ export async function resolveMessageChannelSelection(params: {
source: MessageChannelSelectionSource;
}> {
const normalized = normalizeMessageChannel(params.channel);
if (normalized) {
const availableExplicit = resolveAvailableChannel({
cfg: params.cfg,
value: params.channel,
agentId: params.agentId,
});
if (!availableExplicit) {
const fallback = resolveAvailableChannel({
const explicit = normalized
? resolveAvailableChannel({
cfg: params.cfg,
value: params.fallbackChannel,
value: params.channel,
agentId: params.agentId,
});
if (fallback) {
return {
channel: fallback.channel,
plugin: fallback.plugin,
configured: [],
source: "tool-context-fallback",
};
}
if (!isDeliverableMessageChannel(normalized) && !getRuntimeVisibleChannelPlugin(normalized)) {
throw new Error(formatUnknownChannelMessage({ channel: normalized }));
}
const repairHint = isConfiguredChannel(params.cfg, normalized)
? resolveMissingOfficialExternalChannelPluginRepairHint({
config: params.cfg,
channelId: normalized,
})
: null;
if (repairHint?.channelId === normalized) {
throw new Error(`Channel is unavailable: ${normalized}. ${repairHint.repairHint}`);
}
throw new Error(`Channel is unavailable: ${normalized}`);
}
return {
channel: availableExplicit.channel,
plugin: availableExplicit.plugin,
configured: [],
source: "explicit",
};
})
: undefined;
if (explicit) {
return { ...explicit, configured: [], source: "explicit" };
}
const fallback = resolveAvailableChannel({
@ -285,6 +254,22 @@ export async function resolveMessageChannelSelection(params: {
};
}
if (normalized) {
if (!isDeliverableMessageChannel(normalized) && !getRuntimeVisibleChannelPlugin(normalized)) {
throw new Error(formatUnknownChannelMessage({ channel: normalized }));
}
const repairHint = isConfiguredChannel(params.cfg, normalized)
? resolveMissingOfficialExternalChannelPluginRepairHint({
config: params.cfg,
channelId: normalized,
})
: null;
if (repairHint?.channelId === normalized) {
throw new Error(`Channel is unavailable: ${normalized}. ${repairHint.repairHint}`);
}
throw new Error(`Channel is unavailable: ${normalized}`);
}
const configuredPlugins = await listConfiguredMessageChannelPlugins(
params.cfg,
params.accountResolution,

View file

@ -152,13 +152,14 @@ export async function applyMessageSendingHook(params: {
payload: ReplyPayload;
payloadSummary: NormalizedOutboundPayload;
}> {
const unchanged = () => ({
cancelled: false,
contentRewritten: false,
payload: params.payload,
payloadSummary: params.payloadSummary,
});
if (!params.enabled) {
return {
cancelled: false,
contentRewritten: false,
payload: params.payload,
payloadSummary: params.payloadSummary,
};
return unchanged();
}
try {
const group = getGroupThreadDispatchContext();
@ -193,31 +194,12 @@ export async function applyMessageSendingHook(params: {
};
}
if (sendingResult?.content == null) {
return {
cancelled: false,
contentRewritten: false,
payload: params.payload,
payloadSummary: params.payloadSummary,
};
}
if (params.payloadSummary.hookContent && !params.payloadSummary.text) {
const spokenText = sendingResult.content;
return {
cancelled: false,
contentRewritten: true,
payload: copyReplyPayloadMetadata(params.payload, {
...params.payload,
spokenText,
}),
payloadSummary: {
...params.payloadSummary,
hookContent: spokenText,
},
};
return unchanged();
}
const spokenOnly = params.payloadSummary.hookContent && !params.payloadSummary.text;
const payload = copyReplyPayloadMetadata(params.payload, {
...params.payload,
text: sendingResult.content,
[spokenOnly ? "spokenText" : "text"]: sendingResult.content,
});
return {
cancelled: false,
@ -225,17 +207,12 @@ export async function applyMessageSendingHook(params: {
payload,
payloadSummary: {
...params.payloadSummary,
text: sendingResult.content,
[spokenOnly ? "hookContent" : "text"]: sendingResult.content,
},
};
} catch {
// Don't block delivery on hook failure.
return {
cancelled: false,
contentRewritten: false,
payload: params.payload,
payloadSummary: params.payloadSummary,
};
return unchanged();
}
}

View file

@ -293,23 +293,13 @@ export async function deliverOutboundPayloadsWithQueueCleanup(
// A later payload dispatch must not regress that durable evidence to attempt-started.
if (platformQueueId && queuedPreSendState !== "acked" && queuedPostSendState === undefined) {
try {
if (producerClaimId) {
await markDeliveryPlatformSendDispatched(
platformQueueId,
platformQueueStateDir,
platformSendRoute,
producerClaimId,
params.deliveryQueueStateContext,
);
} else {
await markDeliveryPlatformSendDispatched(
platformQueueId,
platformQueueStateDir,
platformSendRoute,
undefined,
params.deliveryQueueStateContext,
);
}
await markDeliveryPlatformSendDispatched(
platformQueueId,
platformQueueStateDir,
platformSendRoute,
producerClaimId || undefined,
params.deliveryQueueStateContext,
);
queuedPreSendState ??= "marked";
} catch (dispatchMarkError) {
// Any SQLite-fenced live producer must prove it still owns the row at

View file

@ -269,23 +269,13 @@ export async function persistQueuedPreSendState(
owner.signal?.throwIfAborted();
try {
const route = { replyToId: params.route.replyToId ?? null };
if (owner.claimId) {
await markDeliveryPlatformSendAttemptStarted(
owner.queueId,
owner.stateDir,
route,
owner.claimId,
context,
);
} else {
await markDeliveryPlatformSendAttemptStarted(
owner.queueId,
owner.stateDir,
route,
undefined,
context,
);
}
await markDeliveryPlatformSendAttemptStarted(
owner.queueId,
owner.stateDir,
route,
owner.claimId || undefined,
context,
);
return "marked";
} catch (markErr: unknown) {
if (params.queuePolicy === "required") {

View file

@ -647,33 +647,6 @@ async function resolveCompletedOwnerBeforeRecovery(
return "recovered";
}
async function persistRecoveredPostSendState(
opts: {
owner: QueuedDeliveryOwner;
entry: QueuedDelivery;
log: RecoveryLogger;
producerClaimId?: string;
},
stateContext: DeliveryQueueStateContext,
): Promise<QueuedPostSendState> {
// Recovery keeps its media lease until the adapter settles, even if the
// canonical post-send marker has to finalize the queue with a direct ack.
return persistQueuedPostSendState(
{
owner: opts.owner,
queuePolicy: opts.entry.queuePolicy ?? "best_effort",
preserveBatch: Boolean(opts.producerClaimId),
retainSpoolArtifacts: true,
onPostSendMarkerError: (error) => {
opts.log.warn(
`Delivery entry ${opts.entry.id} failed to persist post-send state; falling back to direct ack: ${formatErrorMessage(error)}`,
);
},
},
stateContext,
);
}
async function drainQueuedEntry(
opts: {
entry: QueuedDelivery;
@ -858,15 +831,30 @@ async function drainQueuedEntry(
return "already-gone";
}
owner.claimId = recoveryPlatformAttemptId(entry, producerClaimId);
const reservation = producerClaimId
? await reserveDeliveryAttempt(
entry.id,
maxRetries,
opts.stateDir,
producerClaimId,
stateContext,
)
: await reserveDeliveryAttempt(entry.id, maxRetries, opts.stateDir, undefined, stateContext);
// Recovery keeps its media lease until the adapter settles, even if the
// canonical post-send marker has to finalize the queue with a direct ack.
const persistPostSendState = () =>
persistQueuedPostSendState(
{
owner,
queuePolicy: entry.queuePolicy ?? "best_effort",
preserveBatch: Boolean(producerClaimId),
retainSpoolArtifacts: true,
onPostSendMarkerError: (error) => {
opts.log.warn(
`Delivery entry ${entry.id} failed to persist post-send state; falling back to direct ack: ${formatErrorMessage(error)}`,
);
},
},
stateContext,
);
const reservation = await reserveDeliveryAttempt(
entry.id,
maxRetries,
opts.stateDir,
producerClaimId || undefined,
stateContext,
);
if (reservation.status === "exhausted") {
const errMsg = `delivery retry budget exhausted (${reservation.attemptCount}/${maxRetries})`;
opts.onFailed?.(entry, errMsg);
@ -907,15 +895,7 @@ async function drainQueuedEntry(
},
onDeliveryResult: async (deliveryResult) => {
collectResults([deliveryResult]);
postSendState ??= await persistRecoveredPostSendState(
{
owner,
entry,
log: opts.log,
...(producerClaimId ? { producerClaimId } : {}),
},
stateContext,
);
postSendState ??= await persistPostSendState();
},
onPlatformSendDispatch: async () => {
await deliveryParams.onPlatformSendDispatch?.();
@ -969,15 +949,7 @@ async function drainQueuedEntry(
const errMsg = formatErrorMessage(failedOutcome.error);
opts.onFailed?.(entry, errMsg);
if (results.length > 0 || failedOutcomes.some((outcome) => outcome.sentBeforeError)) {
postSendState ??= await persistRecoveredPostSendState(
{
owner,
entry,
log: opts.log,
...(producerClaimId ? { producerClaimId } : {}),
},
stateContext,
);
postSendState ??= await persistPostSendState();
opts.log.warn(
`Delivery entry ${entry.id} partially sent before best-effort recovery failed; preserving unknown_after_send`,
);
@ -1011,18 +983,7 @@ async function drainQueuedEntry(
stateContext,
);
}
postSendState ??=
results.length > 0
? await persistRecoveredPostSendState(
{
owner,
entry,
log: opts.log,
...(producerClaimId ? { producerClaimId } : {}),
},
stateContext,
)
: undefined;
postSendState ??= results.length > 0 ? await persistPostSendState() : undefined;
if (postSendState === "failed") {
const errMsg = "recovered send completed but queue finalization failed";
opts.onFailed?.(entry, errMsg);
@ -1088,15 +1049,7 @@ async function drainQueuedEntry(
// A rejected batch can still contain successful earlier sends. Preserve
// that concrete evidence so reconnect recovery never replays the batch.
try {
postSendState ??= await persistRecoveredPostSendState(
{
owner,
entry,
log: opts.log,
...(producerClaimId ? { producerClaimId } : {}),
},
stateContext,
);
postSendState ??= await persistPostSendState();
} catch (persistErr) {
// Never overwrite concrete send evidence with a generic retry state.
opts.log.error(

View file

@ -70,21 +70,14 @@ function resolveContextGuardTarget(
return undefined;
}
if (action === "thread-reply" || action === "thread-create") {
if (typeof params.channelId === "string") {
return params.channelId;
const keys =
action === "thread-reply" || action === "thread-create"
? ["channelId", "to"]
: ["to", "channelId"];
for (const key of keys) {
if (typeof params[key] === "string") {
return params[key];
}
if (typeof params.to === "string") {
return params.to;
}
return undefined;
}
if (typeof params.to === "string") {
return params.to;
}
if (typeof params.channelId === "string") {
return params.channelId;
}
return undefined;
}
@ -123,10 +116,12 @@ function isCrossContextTarget(params: {
);
}
function resolveAgentMessageToolsConfig(
cfg: OpenClawConfig,
agentId?: string | null,
): MessageToolsConfig | undefined {
/** Resolves message-tool policy after applying agent-specific overrides. */
export function resolveEffectiveMessageToolsConfig(params: {
cfg: OpenClawConfig;
agentId?: string | null;
}): MessageToolsConfig | undefined {
const { cfg, agentId } = params;
const trimmedAgentId = agentId?.trim();
const globalConfig = cfg.tools?.message;
if (!trimmedAgentId) {
@ -171,16 +166,6 @@ function resolveAgentMessageToolsConfig(
};
}
/**
* Resolves the message-tool policy after applying any agent-specific overrides.
*/
export function resolveEffectiveMessageToolsConfig(params: {
cfg: OpenClawConfig;
agentId?: string | null;
}): MessageToolsConfig | undefined {
return resolveAgentMessageToolsConfig(params.cfg, params.agentId);
}
/**
* Returns the normalized allowed message actions for an agent or the global policy.
*/

View file

@ -79,24 +79,12 @@ type TerminalSourceReplyDeliveryReceipt = RestartRecoveryTerminalDeliveryScope;
type SourceReplyThreadPlacement = "match" | "mismatch" | "unknown";
// Mirror only enough delivered payload detail to preserve transcript context.
function readStringArray(value: unknown): string[] | undefined {
return normalizeOptionalTrimmedStringList(value);
}
function readFirstString(
params: Record<string, unknown>,
keys: readonly string[],
): string | undefined {
return readTrimmedStringAlias(params, keys);
}
function resolveSourceReplyTarget(params: Record<string, unknown>): string | undefined {
return readFirstString(params, ["target", "to", "channelId", "chatId"]);
return readTrimmedStringAlias(params, ["target", "to", "channelId", "chatId"]);
}
function resolveSourceReplyThreadId(params: SourceReplyTranscriptMirrorParams): string | undefined {
return readFirstString(params.actionParams, ["threadId", "messageThreadId"]);
return readTrimmedStringAlias(params.actionParams, ["threadId", "messageThreadId"]);
}
function resolveDeliveryReceipt(
@ -591,15 +579,17 @@ export async function mirrorDeliveredSourceReplyToTranscript(
const plan = createOutboundPayloadPlan([
{
text: readFirstString(params.actionParams, ["message", "content", "text", "caption"]) ?? "",
mediaUrl: readFirstString(params.actionParams, [
text:
readTrimmedStringAlias(params.actionParams, ["message", "content", "text", "caption"]) ??
"",
mediaUrl: readTrimmedStringAlias(params.actionParams, [
"mediaUrl",
"media",
"path",
"filePath",
"fileUrl",
]),
mediaUrls: readStringArray(params.actionParams.mediaUrls),
mediaUrls: normalizeOptionalTrimmedStringList(params.actionParams.mediaUrls),
presentation: params.actionParams.presentation as ReplyPayload["presentation"],
interactive: params.actionParams.interactive as ReplyPayload["interactive"],
channelData: params.actionParams.channelData as ReplyPayload["channelData"],
@ -639,8 +629,5 @@ export async function mirrorDeliveredSourceReplyToTranscript(
: {}),
config: params.cfg,
});
if (result.ok) {
return true;
}
return false;
return result.ok;
}

View file

@ -45,55 +45,31 @@ const OMITTED_PRIVATE_QA_PLUGIN_SDK_FILES = new Set([
`dist/plugin-sdk/${LEGACY_QA_LAB_DIR}.js`,
"dist/plugin-sdk/qa-runtime.d.ts",
"dist/plugin-sdk/qa-runtime.js",
`dist/plugin-sdk/src/plugin-sdk/${LEGACY_QA_CHANNEL_DIR}.d.ts`,
`dist/plugin-sdk/src/plugin-sdk/${LEGACY_QA_CHANNEL_DIR}-protocol.d.ts`,
`dist/plugin-sdk/src/plugin-sdk/${LEGACY_QA_LAB_DIR}.d.ts`,
"dist/plugin-sdk/src/plugin-sdk/qa-runtime.d.ts",
]);
// The build keeps source-shaped SDK declarations for local boundary projects,
// but the npm package ships flat declarations and must not inventory the old tree.
const OMITTED_DEEP_PLUGIN_SDK_DECLARATION_PREFIX = "dist/plugin-sdk/src/";
const OMITTED_PRIVATE_QA_DIST_PREFIXES = ["dist/qa-runtime-"];
const OMITTED_PLUGIN_SDK_TEST_FILES = new Set([
"dist/plugin-sdk/agent-runtime-test-contracts.d.ts",
"dist/plugin-sdk/agent-runtime-test-contracts.js",
"dist/plugin-sdk/channel-contract-testing.d.ts",
"dist/plugin-sdk/channel-contract-testing.js",
"dist/plugin-sdk/channel-target-testing.d.ts",
"dist/plugin-sdk/channel-target-testing.js",
"dist/plugin-sdk/channel-test-helpers.d.ts",
"dist/plugin-sdk/channel-test-helpers.js",
"dist/plugin-sdk/plugin-test-api.d.ts",
"dist/plugin-sdk/plugin-test-api.js",
"dist/plugin-sdk/plugin-test-contracts.d.ts",
"dist/plugin-sdk/plugin-test-contracts.js",
"dist/plugin-sdk/plugin-test-runtime.d.ts",
"dist/plugin-sdk/plugin-test-runtime.js",
"dist/plugin-sdk/provider-http-test-mocks.d.ts",
"dist/plugin-sdk/provider-http-test-mocks.js",
"dist/plugin-sdk/provider-test-contracts.d.ts",
"dist/plugin-sdk/provider-test-contracts.js",
"dist/plugin-sdk/test-env.d.ts",
"dist/plugin-sdk/test-env.js",
"dist/plugin-sdk/test-fixtures.d.ts",
"dist/plugin-sdk/test-fixtures.js",
"dist/plugin-sdk/test-live.d.ts",
"dist/plugin-sdk/test-live.js",
"dist/plugin-sdk/test-live-auth.d.ts",
"dist/plugin-sdk/test-live-auth.js",
"dist/plugin-sdk/test-media-generation.d.ts",
"dist/plugin-sdk/test-media-generation.js",
"dist/plugin-sdk/test-media-understanding.d.ts",
"dist/plugin-sdk/test-media-understanding.js",
"dist/plugin-sdk/test-node-mocks.d.ts",
"dist/plugin-sdk/test-node-mocks.js",
]);
const OMITTED_PLUGIN_SDK_TEST_PREFIXES = [
"dist/plugin-sdk/src/agents/test-helpers/",
"dist/plugin-sdk/src/plugin-sdk/test-helpers/",
"dist/plugin-sdk/src/test-helpers/",
"dist/plugin-sdk/src/test-utils/",
];
const OMITTED_PLUGIN_SDK_TEST_FILES = new Set(
[
"agent-runtime-test-contracts",
"channel-contract-testing",
"channel-target-testing",
"channel-test-helpers",
"plugin-test-api",
"plugin-test-contracts",
"plugin-test-runtime",
"provider-http-test-mocks",
"provider-test-contracts",
"test-env",
"test-fixtures",
"test-live",
"test-live-auth",
"test-media-generation",
"test-media-understanding",
"test-node-mocks",
].flatMap((name) => [`dist/plugin-sdk/${name}.d.ts`, `dist/plugin-sdk/${name}.js`]),
);
const OMITTED_DIST_SUBTREE_PATTERNS = [
/^dist\/extensions\/node_modules(?:\/|$)/u,
/^dist\/extensions\/[^/]+\/node_modules(?:\/|$)/u,
@ -195,15 +171,6 @@ function collectPackageDistExclusionRules(rootPackageJson: unknown): PackageDist
};
}
function isOmittedPluginSdkTestPath(relativePath: string): boolean {
return (
OMITTED_PLUGIN_SDK_TEST_FILES.has(relativePath) ||
OMITTED_PLUGIN_SDK_TEST_PREFIXES.some(
(prefix) => relativePath === prefix.slice(0, -1) || relativePath.startsWith(prefix),
)
);
}
async function collectPackageDistExclusionRulesForRoot(
packageRoot: string,
): Promise<PackageDistExclusionRules> {
@ -244,13 +211,13 @@ function isPackagedDistPath(relativePath: string, rules: PackageDistExclusionRul
if (isLocalBuildMetadataDistPath(relativePath)) {
return false;
}
if (relativePath.endsWith(".map") && !rules.includePackageExcludedFiles) {
if (relativePath.endsWith(".map")) {
return false;
}
if (relativePath === "dist/plugin-sdk/.tsbuildinfo") {
return false;
}
if (isOmittedPluginSdkTestPath(relativePath)) {
if (OMITTED_PLUGIN_SDK_TEST_FILES.has(relativePath)) {
return false;
}
if (relativePath.startsWith(OMITTED_DEEP_PLUGIN_SDK_DECLARATION_PREFIX)) {
@ -278,7 +245,7 @@ function isOmittedDistSubtree(relativePath: string, rules: PackageDistExclusionR
isPackageFilesExcludedDistPath(relativePath, rules) ||
isPackageFilesExcludedDistPath(`${relativePath}/`, rules) ||
isLegacyPluginDependencyDirPath(relativePath) ||
isOmittedPluginSdkTestPath(relativePath) ||
OMITTED_PLUGIN_SDK_TEST_FILES.has(relativePath) ||
OMITTED_DIST_SUBTREE_PATTERNS.some((pattern) => pattern.test(relativePath))
);
}

View file

@ -4,19 +4,9 @@ import { asNullableRecord } from "@openclaw/normalization-core/record-coerce";
import { normalizeNullableString as normalizeString } from "@openclaw/normalization-core/string-coerce";
import { tryReadJson } from "./json-files.js";
type PackageJson = {
name?: unknown;
packageManager?: unknown;
version?: unknown;
};
/** Reads package.json as a loose object, returning null for missing or invalid manifests. */
async function readPackageJson(
root: string,
options?: { maxBytes: number },
): Promise<PackageJson | null> {
const parsed = await tryReadJson<unknown>(path.join(root, "package.json"), options);
return asNullableRecord(parsed) as PackageJson | null;
async function readPackageJson(root: string, options?: { maxBytes: number }) {
return asNullableRecord(await tryReadJson<unknown>(path.join(root, "package.json"), options));
}
/** Reads and trims the package version string, returning null for blank or non-string values. */

View file

@ -179,20 +179,6 @@ async function publishLocalOverrideTarget(params: {
});
}
async function restoreMovedLocalOverrideTarget(params: {
packageFs: LocalOverridePackageRoot;
runtimeUrls: readonly string[];
movedPath: string;
relativePath: string;
}): Promise<void> {
await publishLocalOverrideTarget({
packageFs: params.packageFs,
runtimeUrls: params.runtimeUrls,
sourcePath: params.movedPath,
relativePath: params.relativePath,
});
}
async function throwAfterRestoringMovedLocalOverrideTarget(params: {
packageFs: LocalOverridePackageRoot;
runtimeUrls: readonly string[];
@ -202,10 +188,10 @@ async function throwAfterRestoringMovedLocalOverrideTarget(params: {
removeMovedAfterFailedRestore: boolean;
}): Promise<never> {
try {
await restoreMovedLocalOverrideTarget({
await publishLocalOverrideTarget({
packageFs: params.packageFs,
runtimeUrls: params.runtimeUrls,
movedPath: params.movedPath,
sourcePath: params.movedPath,
relativePath: params.relativePath,
});
} catch (rollbackError) {

View file

@ -15,6 +15,7 @@ import {
isNodeVersionAtLeast,
isSupportedOpenClawNodeVersion,
parseNodeReleaseVersion,
type NodeReleaseVersion,
} from "../../node-version.mjs";
import type { RuntimeEnv } from "../runtime.js";
import { ensureSqliteLibrarySelected } from "./bun-sqlite-library.js";
@ -22,13 +23,7 @@ import { isSqliteWalResetSafeVersion } from "./sqlite-runtime-version.js";
type RuntimeKind = "bun" | "node" | "unknown";
type Semver = {
major: number;
minor: number;
patch: number;
};
const MINIMUM_BUN_VERSION: Semver = { major: 1, minor: 4, patch: 0 };
const MINIMUM_BUN_VERSION: NodeReleaseVersion = { major: 1, minor: 4, patch: 0 };
const MINIMUM_ENGINE_RE = /^\s*>=\s*v?(\d+\.\d+\.\d+)\s*$/i;
const ENGINE_CLAUSE_RE = /^\s*>=\s*v?(\d+\.\d+\.\d+)(?:\s+<\s*v?(\d+(?:\.\d+\.\d+)?))?\s*$/i;
@ -49,7 +44,7 @@ const SEMVER_RE = /(\d+)\.(\d+)\.(\d+)/;
let diagnosticWarningPrinted = false;
/** Parses the first major/minor/patch triple from a runtime or package version label. */
export function parseSemver(version: string | null): Semver | null {
export function parseSemver(version: string | null): NodeReleaseVersion | null {
if (!version) {
return null;
}
@ -65,20 +60,6 @@ export function parseSemver(version: string | null): Semver | null {
};
}
/** Compares parsed semver triples against an inclusive minimum version. */
function isAtLeast(version: Semver | null, minimum: Semver): boolean {
if (!version) {
return false;
}
if (version.major !== minimum.major) {
return version.major > minimum.major;
}
if (version.minor !== minimum.minor) {
return version.minor > minimum.minor;
}
return version.patch >= minimum.patch;
}
/** Reads current process runtime metadata for startup support checks. */
export async function detectRuntime(): Promise<RuntimeDetails> {
const bunVersion = process.versions?.bun;
@ -156,11 +137,11 @@ export function isSupportedNodeVersion(version: string | null): boolean {
/** Checks a Bun version label against OpenClaw's minimum supported release. */
export function isSupportedBunVersion(version: string | null): boolean {
return isAtLeast(parseSemver(version), MINIMUM_BUN_VERSION);
return isNodeVersionAtLeast(parseSemver(version), MINIMUM_BUN_VERSION);
}
/** Parses simple package `engines.node` ranges of the form `>=x.y.z`. */
function parseMinimumNodeEngine(engine: string | null): Semver | null {
function parseMinimumNodeEngine(engine: string | null): NodeReleaseVersion | null {
if (!engine) {
return null;
}
@ -204,7 +185,10 @@ export function nodeVersionSatisfiesEngine(
if (!clauseMinimum || (upperRaw && !upper)) {
return null;
}
if (isAtLeast(parsed, clauseMinimum) && (!upper || !isAtLeast(parsed, upper))) {
if (
isNodeVersionAtLeast(parsed, clauseMinimum) &&
(!upper || !isNodeVersionAtLeast(parsed, upper))
) {
satisfied = true;
}
}

View file

@ -1,224 +1,72 @@
// Runtime launchers and the package build share these subprocess locations.
const currentModuleUrl = import.meta.url;
function runtimeProcessEntrypoint(modulePath: string) {
return {
currentModuleUrl: import.meta.url,
sourceWorkerName: modulePath.startsWith("infra/")
? modulePath.slice("infra/".length)
: `../${modulePath}`,
distWorkerPath: `${modulePath}.js`,
} as const;
}
export const SQLITE_READONLY_CHILD_ARG = "--openclaw-sqlite-readonly-child";
export const runtimeProcessEntrypoints = {
secretEgressProxy: {
currentModuleUrl,
sourceWorkerName: "../secrets/egress-proxy/proxy.worker",
distWorkerPath: "secrets/egress-proxy/proxy.worker.js",
},
codeModeNode: {
currentModuleUrl,
sourceWorkerName: "../agents/code-mode-node.worker",
distWorkerPath: "agents/code-mode-node.worker.js",
},
cronReadOnly: {
currentModuleUrl,
sourceWorkerName: "../cron/store/read-only.worker",
distWorkerPath: "cron/store/read-only.worker.js",
},
stateRead: {
currentModuleUrl,
sourceWorkerName: "../state/openclaw-state-read.worker",
distWorkerPath: "state/openclaw-state-read.worker.js",
},
spawnBroker: {
currentModuleUrl,
sourceWorkerName: "../process/spawn-broker/worker",
distWorkerPath: "process/spawn-broker/worker.js",
},
cronStreamMatcher: {
currentModuleUrl,
sourceWorkerName: "../gateway/cron-stream-matcher.worker",
distWorkerPath: "gateway/cron-stream-matcher.worker.js",
},
nativeHookRelayClient: {
currentModuleUrl,
sourceWorkerName: "../agents/harness/native-hook-relay-client.worker",
distWorkerPath: "agents/harness/native-hook-relay-client.worker.js",
},
computerHost: {
currentModuleUrl,
sourceWorkerName: "../gateway/desktop/computer.worker",
distWorkerPath: "gateway/desktop/computer.worker.js",
},
imageProcessor: {
currentModuleUrl,
sourceWorkerName: "../media/image-processor.worker",
distWorkerPath: "media/image-processor.worker.js",
},
gitOperations: {
currentModuleUrl,
sourceWorkerName: "git-operation.worker",
distWorkerPath: "infra/git-operation.worker.js",
},
fsSafeCopy: {
currentModuleUrl,
sourceWorkerName: "fs-safe-copy.worker",
distWorkerPath: "infra/fs-safe-copy.worker.js",
},
sharedStateStore: {
currentModuleUrl,
sourceWorkerName: "../state/openclaw-state.worker",
distWorkerPath: "state/openclaw-state.worker.js",
},
authProfileInlineUsage: {
currentModuleUrl,
sourceWorkerName: "../agents/auth-profiles/inline-usage.worker",
distWorkerPath: "agents/auth-profiles/inline-usage.worker.js",
},
agentDatabaseExecution: {
currentModuleUrl,
sourceWorkerName: "../state/openclaw-agent-execution.worker",
distWorkerPath: "state/openclaw-agent-execution.worker.js",
},
workspaceMemory: {
currentModuleUrl,
sourceWorkerName: "../worker/memory-worker-entry",
distWorkerPath: "worker/memory-worker-entry.js",
},
workspaceSkills: {
currentModuleUrl,
sourceWorkerName: "../worker/skills-worker-entry",
distWorkerPath: "worker/skills-worker-entry.js",
},
boardStore: {
currentModuleUrl,
sourceWorkerName: "../boards/sqlite-board-store.worker",
distWorkerPath: "boards/sqlite-board-store.worker.js",
},
sessionSharingStore: {
currentModuleUrl,
sourceWorkerName: "../config/sessions/session-sharing-store.worker",
distWorkerPath: "config/sessions/session-sharing-store.worker.js",
},
heartbeatOutcomeStore: {
currentModuleUrl,
sourceWorkerName: "heartbeat-outcome-store.worker",
distWorkerPath: "infra/heartbeat-outcome-store.worker.js",
},
sqliteStore: {
currentModuleUrl,
sourceWorkerName: "sqlite-store.worker",
distWorkerPath: "infra/sqlite-store.worker.js",
},
agentSchemaInspection: {
currentModuleUrl,
sourceWorkerName: "../state/openclaw-agent-schema-inspection.worker",
distWorkerPath: "state/openclaw-agent-schema-inspection.worker.js",
},
stateMigrationSnapshot: {
currentModuleUrl,
sourceWorkerName: "state-migrations.snapshot.worker",
distWorkerPath: "infra/state-migrations.snapshot.worker.js",
},
githubExec: {
currentModuleUrl,
sourceWorkerName: "../agents/github-exec-launcher",
distWorkerPath: "agents/github-exec-launcher.js",
},
sqliteReadOnly: {
currentModuleUrl,
sourceWorkerName: "sqlite-readonly-location.worker",
distWorkerPath: "infra/sqlite-readonly-location.worker.js",
},
sqliteIntegrity: {
currentModuleUrl,
sourceWorkerName: "sqlite-integrity.worker",
distWorkerPath: "infra/sqlite-integrity.worker.js",
},
preparedModelCatalog: {
currentModuleUrl,
sourceWorkerName: "../agents/prepared-model-catalog.worker",
distWorkerPath: "agents/prepared-model-catalog.worker.js",
},
updateRepair: {
currentModuleUrl,
sourceWorkerName: "update-repair.worker",
distWorkerPath: "infra/update-repair.worker.js",
},
updateMigratedFinalize: {
currentModuleUrl,
sourceWorkerName: "update-migrated-finalize.worker",
distWorkerPath: "infra/update-migrated-finalize.worker.js",
},
updateCandidateState: {
currentModuleUrl,
sourceWorkerName: "update-candidate-state.worker",
distWorkerPath: "infra/update-candidate-state.worker.js",
},
doctorLint: {
currentModuleUrl,
sourceWorkerName: "../commands/doctor-lint.worker",
distWorkerPath: "commands/doctor-lint.worker.js",
},
databaseVerify: {
currentModuleUrl,
sourceWorkerName: "../state/openclaw-database-verify.worker",
distWorkerPath: "state/openclaw-database-verify.worker.js",
},
stateLeaseHeartbeat: {
currentModuleUrl,
sourceWorkerName: "../state/openclaw-state-lease-heartbeat.worker",
distWorkerPath: "state/openclaw-state-lease-heartbeat.worker.js",
},
sessionTranscriptArchive: {
currentModuleUrl,
sourceWorkerName: "../config/sessions/session-accessor.sqlite-archive.worker",
distWorkerPath: "config/sessions/session-accessor.sqlite-archive.worker.js",
},
sessionTranscript: {
currentModuleUrl,
sourceWorkerName: "../config/sessions/session-transcript.worker",
distWorkerPath: "config/sessions/session-transcript.worker.js",
},
sessionManagerMetadata: {
currentModuleUrl,
sourceWorkerName: "../agents/sessions/session-manager-metadata.worker",
distWorkerPath: "agents/sessions/session-manager-metadata.worker.js",
},
sessionTranscriptReports: {
currentModuleUrl,
sourceWorkerName: "../config/sessions/session-accessor.sqlite-transcript-reports.worker",
distWorkerPath: "config/sessions/session-accessor.sqlite-transcript-reports.worker.js",
},
sessionTranscriptReconcile: {
currentModuleUrl,
sourceWorkerName: "../config/sessions/session-transcript-reconcile.worker",
distWorkerPath: "config/sessions/session-transcript-reconcile.worker.js",
},
tailscaleRouteOwner: {
currentModuleUrl,
sourceWorkerName: "tailscale-route-owner.worker",
distWorkerPath: "infra/tailscale-route-owner.worker.js",
},
serviceChildRelay: {
currentModuleUrl,
sourceWorkerName: "../process/supervisor/service-child-relay",
distWorkerPath: "process/supervisor/service-child-relay.js",
},
terminalPty: {
currentModuleUrl,
sourceWorkerName: "../process/terminal-pty-worker",
distWorkerPath: "process/terminal-pty-worker.js",
},
serviceChildGroupAnchor: {
currentModuleUrl,
sourceWorkerName: "../process/supervisor/service-child-group-anchor",
distWorkerPath: "process/supervisor/service-child-group-anchor.js",
},
serviceChildWindowsJobAnchor: {
currentModuleUrl,
sourceWorkerName: "../process/supervisor/service-child-windows-job-anchor",
distWorkerPath: "process/supervisor/service-child-windows-job-anchor.js",
},
secretEgressProxy: runtimeProcessEntrypoint("secrets/egress-proxy/proxy.worker"),
codeModeNode: runtimeProcessEntrypoint("agents/code-mode-node.worker"),
cronReadOnly: runtimeProcessEntrypoint("cron/store/read-only.worker"),
stateRead: runtimeProcessEntrypoint("state/openclaw-state-read.worker"),
spawnBroker: runtimeProcessEntrypoint("process/spawn-broker/worker"),
cronStreamMatcher: runtimeProcessEntrypoint("gateway/cron-stream-matcher.worker"),
nativeHookRelayClient: runtimeProcessEntrypoint("agents/harness/native-hook-relay-client.worker"),
computerHost: runtimeProcessEntrypoint("gateway/desktop/computer.worker"),
imageProcessor: runtimeProcessEntrypoint("media/image-processor.worker"),
gitOperations: runtimeProcessEntrypoint("infra/git-operation.worker"),
fsSafeCopy: runtimeProcessEntrypoint("infra/fs-safe-copy.worker"),
sharedStateStore: runtimeProcessEntrypoint("state/openclaw-state.worker"),
authProfileInlineUsage: runtimeProcessEntrypoint("agents/auth-profiles/inline-usage.worker"),
agentDatabaseExecution: runtimeProcessEntrypoint("state/openclaw-agent-execution.worker"),
workspaceMemory: runtimeProcessEntrypoint("worker/memory-worker-entry"),
workspaceSkills: runtimeProcessEntrypoint("worker/skills-worker-entry"),
boardStore: runtimeProcessEntrypoint("boards/sqlite-board-store.worker"),
sessionSharingStore: runtimeProcessEntrypoint("config/sessions/session-sharing-store.worker"),
heartbeatOutcomeStore: runtimeProcessEntrypoint("infra/heartbeat-outcome-store.worker"),
sqliteStore: runtimeProcessEntrypoint("infra/sqlite-store.worker"),
agentSchemaInspection: runtimeProcessEntrypoint("state/openclaw-agent-schema-inspection.worker"),
stateMigrationSnapshot: runtimeProcessEntrypoint("infra/state-migrations.snapshot.worker"),
githubExec: runtimeProcessEntrypoint("agents/github-exec-launcher"),
sqliteReadOnly: runtimeProcessEntrypoint("infra/sqlite-readonly-location.worker"),
sqliteIntegrity: runtimeProcessEntrypoint("infra/sqlite-integrity.worker"),
preparedModelCatalog: runtimeProcessEntrypoint("agents/prepared-model-catalog.worker"),
updateRepair: runtimeProcessEntrypoint("infra/update-repair.worker"),
updateMigratedFinalize: runtimeProcessEntrypoint("infra/update-migrated-finalize.worker"),
updateCandidateState: runtimeProcessEntrypoint("infra/update-candidate-state.worker"),
doctorLint: runtimeProcessEntrypoint("commands/doctor-lint.worker"),
databaseVerify: runtimeProcessEntrypoint("state/openclaw-database-verify.worker"),
stateLeaseHeartbeat: runtimeProcessEntrypoint("state/openclaw-state-lease-heartbeat.worker"),
sessionTranscriptArchive: runtimeProcessEntrypoint(
"config/sessions/session-accessor.sqlite-archive.worker",
),
sessionTranscript: runtimeProcessEntrypoint("config/sessions/session-transcript.worker"),
sessionManagerMetadata: runtimeProcessEntrypoint(
"agents/sessions/session-manager-metadata.worker",
),
sessionTranscriptReports: runtimeProcessEntrypoint(
"config/sessions/session-accessor.sqlite-transcript-reports.worker",
),
sessionTranscriptReconcile: runtimeProcessEntrypoint(
"config/sessions/session-transcript-reconcile.worker",
),
tailscaleRouteOwner: runtimeProcessEntrypoint("infra/tailscale-route-owner.worker"),
serviceChildRelay: runtimeProcessEntrypoint("process/supervisor/service-child-relay"),
terminalPty: runtimeProcessEntrypoint("process/terminal-pty-worker"),
serviceChildGroupAnchor: runtimeProcessEntrypoint(
"process/supervisor/service-child-group-anchor",
),
serviceChildWindowsJobAnchor: runtimeProcessEntrypoint(
"process/supervisor/service-child-windows-job-anchor",
),
// Not a launcher: the daemon runtime probe requires this module inside candidate Bun
// executables so they select the same SQLite library the Gateway will run with.
bunSqliteLibrary: {
currentModuleUrl,
sourceWorkerName: "bun-sqlite-library",
distWorkerPath: "infra/bun-sqlite-library.js",
},
bunSqliteLibrary: runtimeProcessEntrypoint("infra/bun-sqlite-library"),
} as const;

View file

@ -150,10 +150,6 @@ function consumesSeparateValue(token: string): boolean {
return POSIX_SHELL_OPTIONS_WITH_SEPARATE_VALUES.has(token);
}
function isPosixInteractiveModeOption(token: string): boolean {
return token === "--interactive" || isPosixShortOption(token, "i");
}
function isPosixShortOption(token: string, option: string): boolean {
if (token.length < 2 || token[0] !== "-" || token[1] === "-") {
return false;
@ -332,28 +328,7 @@ export function hasPosixInteractiveStartupBeforeInlineCommand(
argv: readonly string[],
flags: ReadonlySet<string>,
): boolean {
let sawInteractiveMode = false;
for (let i = 1; i < argv.length;) {
const token = argv[i]?.trim();
if (!token) {
i += 1;
continue;
}
if (token === "--") {
return false;
}
if (isPosixInteractiveModeOption(token)) {
sawInteractiveMode = true;
}
if (flags.has(token) || isCombinedCommandFlag(token)) {
return sawInteractiveMode;
}
if (!token.startsWith("-") && !token.startsWith("+")) {
return false;
}
i += advancePosixInlineOptionScan(token);
}
return false;
return hasPosixStartupModeBeforeInlineCommand(argv, flags, "--interactive", "i");
}
/** Detect POSIX login startup before an inline command flag. */
@ -361,7 +336,16 @@ export function hasPosixLoginStartupBeforeInlineCommand(
argv: readonly string[],
flags: ReadonlySet<string>,
): boolean {
let sawLoginMode = false;
return hasPosixStartupModeBeforeInlineCommand(argv, flags, "--login", "l");
}
function hasPosixStartupModeBeforeInlineCommand(
argv: readonly string[],
flags: ReadonlySet<string>,
longOption: string,
shortOption: string,
): boolean {
let sawStartupMode = false;
for (let i = 1; i < argv.length;) {
const token = argv[i]?.trim();
if (!token) {
@ -371,11 +355,11 @@ export function hasPosixLoginStartupBeforeInlineCommand(
if (token === "--") {
return false;
}
if (token === "--login" || isPosixShortOption(token, "l")) {
sawLoginMode = true;
if (token === longOption || isPosixShortOption(token, shortOption)) {
sawStartupMode = true;
}
if (flags.has(token) || isCombinedCommandFlag(token)) {
return sawLoginMode;
return sawStartupMode;
}
if (!token.startsWith("-") && !token.startsWith("+")) {
return false;

View file

@ -86,7 +86,6 @@ const SHELL_WRAPPER_CANONICAL = new Set<string>([
...WINDOWS_CMD_WRAPPER_NAMES,
...POWERSHELL_WRAPPER_NAMES,
]);
const LOGIN_STARTUP_SHELL_WRAPPER_CANONICAL = new Set<string>(POSIX_SHELL_WRAPPER_NAMES);
type ShellWrapperKind = "posix" | "cmd" | "powershell";
@ -118,7 +117,7 @@ function resolveShellWrapperCandidate<TState>(params: {
state: TState;
onDispatchUnwrap?: (state: TState, wrappedArgv: string[]) => TState;
}): ShellWrapperCandidate<TState> | null {
if (!isWithinDispatchClassificationDepth(params.depth)) {
if (params.depth > MAX_DISPATCH_WRAPPER_DEPTH) {
return null;
}
@ -178,23 +177,15 @@ function resolveShellWrapperSpecAndArgvInternal(
return { argv: candidate.argv, wrapper, payload };
}
function isWithinDispatchClassificationDepth(depth: number): boolean {
return depth <= MAX_DISPATCH_WRAPPER_DEPTH;
}
/** Return true when an executable token names a supported shell wrapper. */
export function isShellWrapperExecutable(token: string): boolean {
return SHELL_WRAPPER_CANONICAL.has(normalizeExecutableToken(token));
}
function isShellWrapperInvocationInternal(argv: string[], depth: number): boolean {
const candidate = resolveShellWrapperCandidate({ argv, depth, state: null });
return candidate ? isShellWrapperExecutable(candidate.token0) : false;
}
/** Return true when argv resolves to a shell wrapper invocation. */
export function isShellWrapperInvocation(argv: string[]): boolean {
return isShellWrapperInvocationInternal(argv, 0);
const candidate = resolveShellWrapperCandidate({ argv, depth: 0, state: null });
return candidate ? isShellWrapperExecutable(candidate.token0) : false;
}
/** Detect implicit POSIX startup in the requested shell, including dispatch wrappers. */
@ -249,11 +240,7 @@ export function unwrapKnownShellMultiplexerInvocation(
return { kind: "blocked", wrapper };
}
const unwrapped = argv.slice(appletIndex);
if (unwrapped.length === 0) {
return { kind: "blocked", wrapper };
}
return { kind: "unwrapped", wrapper, argv: unwrapped };
return { kind: "unwrapped", wrapper, argv: argv.slice(appletIndex) };
}
function extractPosixShellInlineCommand(argv: string[], baseExecutable: string): string | null {
@ -377,10 +364,6 @@ function hasCmdUnreviewedStartupBeforeInlineCommand(argv: string[]): boolean {
return true;
}
function extractPowerShellInlineCommand(argv: string[]): string | null {
return resolvePowerShellInlineCommandMatch(argv).command;
}
function extractInlineCommandByFlags(
argv: string[],
flags: ReadonlySet<string>,
@ -400,17 +383,13 @@ function extractShellWrapperPayload(
case "cmd":
return extractCmdInlineCommand(argv);
case "powershell":
return extractPowerShellInlineCommand(argv);
return resolvePowerShellInlineCommandMatch(argv).command;
}
throw new Error("Unsupported shell wrapper kind");
}
function isLegacyLoginInlineForm(argv: string[]): boolean {
return argv[1]?.trim() === "-lc";
}
function isLegacyShLoginInlineForm(argv: string[], baseExecutable: string): boolean {
return baseExecutable === "sh" && isLegacyLoginInlineForm(argv);
return baseExecutable === "sh" && argv[1]?.trim() === "-lc";
}
function formatShellWrapperArgv(argv: string[]): string {
@ -442,18 +421,16 @@ function startupWrapperRequiresFullArgv(params: {
}
return hasNushellInteractiveStartupBeforeInlineCommand(params.argv);
}
const inlineCommandFlags =
params.baseExecutable === "nu" ? NUSHELL_INLINE_COMMAND_FLAGS : POSIX_INLINE_COMMAND_FLAGS;
if (
LOGIN_STARTUP_SHELL_WRAPPER_CANONICAL.has(params.baseExecutable) &&
hasPosixLoginStartupBeforeInlineCommand(params.argv, inlineCommandFlags)
POSIX_SHELL_WRAPPER_CANONICAL.has(params.baseExecutable) &&
hasPosixLoginStartupBeforeInlineCommand(params.argv, POSIX_INLINE_COMMAND_FLAGS)
) {
return (
params.includeLegacyLoginInlineForm ||
!isLegacyShLoginInlineForm(params.argv, params.baseExecutable)
);
}
return hasPosixInteractiveStartupBeforeInlineCommand(params.argv, inlineCommandFlags);
return hasPosixInteractiveStartupBeforeInlineCommand(params.argv, POSIX_INLINE_COMMAND_FLAGS);
}
function hasNushellLoginStartupBeforeInlineCommand(argv: string[]): boolean {
@ -500,15 +477,12 @@ function isNushellShortOption(arg: string, option: string): boolean {
return arg.slice(1).includes(option);
}
function hasEnvManipulationBeforeShellWrapperInternal(
argv: string[],
depth: number,
envManipulationSeen: boolean,
): boolean {
/** Return true when dispatch wrappers set env before the shell wrapper. */
export function hasEnvManipulationBeforeShellWrapper(argv: string[]): boolean {
const candidate = resolveShellWrapperCandidate({
argv,
depth,
state: envManipulationSeen,
depth: 0,
state: false,
onDispatchUnwrap: (state, wrappedArgv) => state || hasDispatchEnvManipulation(wrappedArgv),
});
if (!candidate) {
@ -530,11 +504,6 @@ function hasEnvManipulationBeforeShellWrapperInternal(
return candidate.state;
}
/** Return true when dispatch wrappers set env before the shell wrapper. */
export function hasEnvManipulationBeforeShellWrapper(argv: string[]): boolean {
return hasEnvManipulationBeforeShellWrapperInternal(argv, 0, false);
}
function extractShellWrapperCommandInternal(
argv: string[],
rawCommand: string | null,
@ -577,14 +546,9 @@ function extractShellWrapperCommandInternal(
return { isWrapper: true, command: null };
}
const resolved = resolveShellWrapperSpecAndArgvInternal(candidate.argv, depth);
if (!resolved) {
return { isWrapper: false, command: null };
}
return {
isWrapper: true,
command: rawMatchesCanonicalArgv ? resolved.payload : (rawCommand ?? resolved.payload),
command: rawMatchesCanonicalArgv ? payload : (rawCommand ?? payload),
};
}

View file

@ -194,12 +194,8 @@ export function createSqliteAuditRecordKernel<T>(
// Keep the just-addressed key while pruning the oldest rows in this scope.
pruneAuditRecords({ database, scope, maxEntries, protectedKey: record.event_key });
},
upsert(record: PreparedSqliteAuditRecord): void {
upsertPreparedRecord(record);
},
delete(key: string): void {
deleteRecord(key);
},
upsert: upsertPreparedRecord,
delete: deleteRecord,
compareAndSet(
key: string,
expectedPayloadJson: string | null | undefined,

View file

@ -177,19 +177,10 @@ function closeIdleCoordinatorDatabase(database: DatabaseSync, location: string)
}
function closeIdleCoordinatorsOnExit() {
const databases = new Map(failedIdleCloses);
for (const [location] of idleCoordinators) {
const idle = takeIdleCoordinator(location);
if (idle) {
databases.set(idle.database, location);
}
}
for (const [database, location] of databases) {
try {
closeIdleCoordinatorDatabase(database, location);
} catch {
// Process exit is the last cleanup opportunity for a failed native close.
}
try {
closeIdleCoordinatorPool();
} catch {
// Process exit is the last cleanup opportunity for a failed native close.
}
}

View file

@ -101,7 +101,7 @@ async function copyFileExclusive(
source: FileHandle,
targetPath: string,
): Promise<{ content: SqliteFileContent; identity: Stats }> {
const sourceFingerprint = await readMutationFingerprint(source);
const sourceFingerprint = await source.stat({ bigint: true });
let target: Awaited<ReturnType<typeof fs.open>> | undefined;
let targetIdentity: Stats | undefined;
try {
@ -135,24 +135,12 @@ async function copyFileExclusive(
}
}
async function readMutationFingerprint(handle: FileHandle): Promise<FileMutationFingerprint> {
const stat = await handle.stat({ bigint: true });
return {
birthtimeNs: stat.birthtimeNs,
ctimeNs: stat.ctimeNs,
dev: stat.dev,
ino: stat.ino,
mtimeNs: stat.mtimeNs,
size: stat.size,
};
}
async function assertMutationFingerprintUnchanged(
handle: FileHandle,
expected: FileMutationFingerprint,
filePath: string,
): Promise<void> {
const current = await readMutationFingerprint(handle);
const current = await handle.stat({ bigint: true });
if (!sameFileMutationFingerprint(current, expected)) {
throw new Error(`SQLite snapshot file changed while reading: ${filePath}`);
}
@ -202,7 +190,7 @@ async function hashOpenPublishedFile(
expectedIdentity: Stats,
): Promise<SqliteFileContent> {
await assertOpenFileIdentity(handle, filePath, expectedIdentity);
const fingerprint = await readMutationFingerprint(handle);
const fingerprint = await handle.stat({ bigint: true });
const { digest, bytes } = await sha256File(handle);
await assertMutationFingerprintUnchanged(handle, fingerprint, filePath);
await assertOpenFileIdentity(handle, filePath, expectedIdentity);
@ -245,25 +233,9 @@ function hashPublishedFileSync(filePath: string, expectedIdentity: Stats): Sqlit
try {
assertOpenFileIdentitySync(fileDescriptor, filePath, expectedIdentity);
const initialStat = fsSync.fstatSync(fileDescriptor, { bigint: true });
const initialFingerprint: FileMutationFingerprint = {
birthtimeNs: initialStat.birthtimeNs,
ctimeNs: initialStat.ctimeNs,
dev: initialStat.dev,
ino: initialStat.ino,
mtimeNs: initialStat.mtimeNs,
size: initialStat.size,
};
const content = hashFileDescriptorSync(fileDescriptor);
const finalStat = fsSync.fstatSync(fileDescriptor, { bigint: true });
const finalFingerprint: FileMutationFingerprint = {
birthtimeNs: finalStat.birthtimeNs,
ctimeNs: finalStat.ctimeNs,
dev: finalStat.dev,
ino: finalStat.ino,
mtimeNs: finalStat.mtimeNs,
size: finalStat.size,
};
if (!sameFileMutationFingerprint(initialFingerprint, finalFingerprint)) {
if (!sameFileMutationFingerprint(initialStat, finalStat)) {
throw new Error(`SQLite snapshot file changed while reading: ${filePath}`);
}
assertOpenFileIdentitySync(fileDescriptor, filePath, expectedIdentity);

View file

@ -2,6 +2,7 @@
import type { DatabaseSync } from "node:sqlite";
import { openNodeSqliteDatabase } from "./node-sqlite.js";
import { assertSqliteIntegrity } from "./sqlite-integrity.js";
import { quoteSqliteIdentifier } from "./sqlite-schema-sql.js";
import { runSqliteImmediateTransactionSync } from "./sqlite-transaction.js";
type TableListRow = {
@ -61,10 +62,6 @@ const DEFAULT_STRICT_MIGRATION_BUSY_TIMEOUT_MS = 5_000;
const STRICT_MIGRATION_TABLE_PREFIX = "__openclaw_strict_migration_";
const SQLITE_ROWID_ALIASES = ["_rowid_", "rowid", "oid"] as const;
function quoteSqliteIdentifier(identifier: string): string {
return `"${identifier.replaceAll('"', '""')}"`;
}
function readMainTableList(db: DatabaseSync): TableListRow[] {
return (db.prepare("PRAGMA table_list").all() as TableListRow[]).filter(
(row) =>

View file

@ -305,23 +305,10 @@ function logSlowTransactionStep(params: {
pid: process.pid,
step: params.step,
threadId,
...beginAdmissionLogFields(params.beginAdmission),
...(params.beginAdmission ? { beginAdmission: { ...params.beginAdmission } } : {}),
});
}
function beginAdmissionLogFields(diagnostics: SqliteBeginAdmissionDiagnostics | undefined) {
return diagnostics
? {
beginAdmission: {
nativeAttempts: diagnostics.nativeAttempts,
nativeMs: diagnostics.nativeMs,
serviceCalls: diagnostics.serviceCalls,
serviceMs: diagnostics.serviceMs,
},
}
: {};
}
function execTimedTransactionStep(params: {
db: DatabaseSync;
options?: SqliteTransactionOptions;
@ -368,7 +355,7 @@ function execTimedTransactionStep(params: {
...(sqlitePrimaryCode !== undefined ? { sqlitePrimaryCode } : {}),
step: params.step,
threadId,
...beginAdmissionLogFields(beginAdmission),
...(beginAdmission ? { beginAdmission: { ...beginAdmission } } : {}),
});
}
throw error;

View file

@ -4,8 +4,8 @@ import os from "node:os";
import {
normalizeLowercaseStringOrEmpty,
normalizeOptionalLowercaseString,
normalizeOptionalString,
} from "@openclaw/normalization-core/string-coerce";
import { normalizeUniqueTrimmedStringList } from "@openclaw/normalization-core/string-normalization";
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
import type { PresenceEntry } from "../../packages/gateway-protocol/src/schema/snapshot.js";
import { resolveRuntimeServiceVersion } from "../version.js";
@ -72,17 +72,9 @@ function setPresence(key: string | symbol, presence: SystemPresence) {
entries.set(key, { presence, freshness: freshnessNow() });
}
function normalizePresenceKey(key: string | undefined): string | undefined {
return normalizeOptionalLowercaseString(key);
}
function resolvePrimaryIPv4(): string | undefined {
return pickBestEffortPrimaryLanIPv4() ?? os.hostname();
}
function initSelfPresence() {
const host = os.hostname();
const ip = resolvePrimaryIPv4() ?? undefined;
const ip = pickBestEffortPrimaryLanIPv4() ?? os.hostname();
const version = resolveRuntimeServiceVersion(process.env);
const modelIdentifier = resolveMachineModelIdentifier();
const platform = (() => {
@ -189,28 +181,19 @@ type SystemPresencePayload = {
};
function mergeStringList(...values: Array<string[] | undefined>): string[] | undefined {
const out = new Set<string>();
for (const list of values) {
if (!Array.isArray(list)) {
continue;
}
for (const item of list) {
const trimmed = normalizeOptionalString(item) ?? "";
if (trimmed) {
out.add(trimmed);
}
}
}
return out.size > 0 ? [...out] : undefined;
const merged = normalizeUniqueTrimmedStringList(
values.flatMap((list) => (Array.isArray(list) ? list : [])),
);
return merged.length > 0 ? merged : undefined;
}
export function updateSystemPresence(payload: SystemPresencePayload) {
const parsed = parsePresence(payload.text);
const key =
normalizePresenceKey(payload.deviceId) ||
normalizePresenceKey(payload.instanceId) ||
normalizePresenceKey(parsed.instanceId) ||
normalizePresenceKey(parsed.host) ||
normalizeOptionalLowercaseString(payload.deviceId) ||
normalizeOptionalLowercaseString(payload.instanceId) ||
normalizeOptionalLowercaseString(parsed.instanceId) ||
normalizeOptionalLowercaseString(parsed.host) ||
parsed.ip ||
truncateUtf16Safe(parsed.text, 64) ||
normalizeLowercaseStringOrEmpty(os.hostname());
@ -248,7 +231,8 @@ export function updateSystemPresence(payload: SystemPresencePayload) {
}
export function upsertPresence(key: string, presence: Partial<SystemPresence>) {
const normalizedKey = normalizePresenceKey(key) ?? normalizeLowercaseStringOrEmpty(os.hostname());
const normalizedKey =
normalizeOptionalLowercaseString(key) ?? normalizeLowercaseStringOrEmpty(os.hostname());
const existing = entries.get(normalizedKey)?.presence ?? ({} as SystemPresence);
const roles = mergeStringList(existing.roles, presence.roles);
const scopes = mergeStringList(existing.scopes, presence.scopes);
@ -270,7 +254,7 @@ export function upsertPresence(key: string, presence: Partial<SystemPresence>) {
/** Renews an existing connection-owned presence row without recreating expired metadata. */
export function touchPresence(key: string): boolean {
const normalizedKey = normalizePresenceKey(key);
const normalizedKey = normalizeOptionalLowercaseString(key);
if (!normalizedKey) {
return false;
}

View file

@ -167,7 +167,6 @@ function normalizeRawCommandText(rawCommand?: unknown): string | null {
function validateSystemRunCommandConsistency(params: {
argv: string[];
rawCommand?: string | null;
allowLegacyShellText?: boolean;
}): SystemRunCommandValidation {
const raw = normalizeRawCommandText(params.rawCommand);
const display = buildSystemRunCommandDisplay(params.argv, raw);
@ -176,10 +175,7 @@ function validateSystemRunCommandConsistency(params: {
// rawCommand is display-only metadata. Reject mismatches so approvals cannot
// show one command while executing a different argv.
const matchesCanonicalArgv = raw === display.commandText;
const matchesLegacyShellText =
params.allowLegacyShellText === true &&
display.previewText !== null &&
raw === display.previewText;
const matchesLegacyShellText = display.previewText !== null && raw === display.previewText;
if (!matchesCanonicalArgv && !matchesLegacyShellText) {
return {
ok: false,
@ -207,16 +203,6 @@ export function resolveSystemRunCommandRequest(params: {
command?: unknown;
rawCommand?: unknown;
}): ResolvedSystemRunCommand {
return resolveSystemRunCommandWithMode(params, true);
}
function resolveSystemRunCommandWithMode(
params: {
command?: unknown;
rawCommand?: unknown;
},
allowLegacyShellText: boolean,
): ResolvedSystemRunCommand {
const raw = normalizeRawCommandText(params.rawCommand);
const command = Array.isArray(params.command) ? params.command : [];
if (command.length === 0) {
@ -240,7 +226,6 @@ function resolveSystemRunCommandWithMode(
const validation = validateSystemRunCommandConsistency({
argv,
rawCommand: raw,
allowLegacyShellText,
});
if (!validation.ok) {
return {

View file

@ -145,31 +145,11 @@ function resolveOptionFilteredFileOperandIndex(params: {
cwd: string | undefined;
optionsWithValue?: ReadonlySet<string>;
}): number | null {
let afterDoubleDash = false;
for (let i = params.startIndex; i < params.argv.length; i += 1) {
const token = readTrimmedArgToken(params.argv, i);
if (!token) {
continue;
}
if (afterDoubleDash) {
return resolvesToExistingFileSync(token, params.cwd) ? i : null;
}
if (token === "--") {
afterDoubleDash = true;
continue;
}
if (token === "-") {
return null;
}
if (token.startsWith("-")) {
if (!token.includes("=") && params.optionsWithValue?.has(token)) {
i += 1;
}
continue;
}
return resolvesToExistingFileSync(token, params.cwd) ? i : null;
}
return null;
const index = resolveOptionFilteredPositionalIndex(params);
return index !== null &&
resolvesToExistingFileSync(readTrimmedArgToken(params.argv, index), params.cwd)
? index
: null;
}
function resolveOptionFilteredPositionalIndex(params: {

View file

@ -513,11 +513,7 @@ export async function acceptTriageContinuation(): Promise<
armShutdown();
try {
if (lease) {
if (cleanup === "closed") {
store.settle(lease, "closed");
} else {
store.settle(lease, "uncertain");
}
store.settle(lease, cleanup);
}
} finally {
disposed = true;

View file

@ -37,9 +37,6 @@ export function resolveDevUpstreamRefs(
/** Normalizes config or CLI channel input to a supported update channel. */
export function normalizeUpdateChannel(value?: string | null): UpdateChannel | null {
const normalized = normalizeOptionalLowercaseString(value);
if (!normalized) {
return null;
}
if (
normalized === "stable" ||
normalized === "extended-stable" ||
@ -53,16 +50,9 @@ export function normalizeUpdateChannel(value?: string | null): UpdateChannel | n
/** Maps an OpenClaw update channel to the npm dist-tag used for package lookups. */
export function channelToNpmTag(channel: UpdateChannel): string {
if (channel === "extended-stable") {
return "extended-stable";
}
if (channel === "beta") {
return "beta";
}
if (channel === "dev") {
return "dev";
}
return "latest";
return channel === "extended-stable" || channel === "beta" || channel === "dev"
? channel
: "latest";
}
/** Beta follows the newest published beta or stable version, including plugin packages. */
@ -183,10 +173,6 @@ export function resolveEffectiveUpdateChannel(params: {
return { channel: DEFAULT_GIT_CHANNEL, source: "default" };
}
if (params.installKind === "package") {
return { channel: DEFAULT_PACKAGE_CHANNEL, source: "default" };
}
return { channel: DEFAULT_PACKAGE_CHANNEL, source: "default" };
}

View file

@ -315,17 +315,10 @@ export async function writeUpdatePostInstallDoctorResult(params: {
result: UpdatePostInstallDoctorResult;
}): Promise<void> {
const resultPath = resolveSafeUpdatePostInstallDoctorResultPath(params.resultPath);
const { warnings, failureFacts, ...result } = params.result;
const normalizedWarnings = normalizeUpdatePostInstallDoctorWarnings(warnings ?? []);
const facts = normalizeUpdateFailureFacts(failureFacts ?? []);
// Advisory details can contain config-derived IDs; pre-existing paths must fail closed.
await fs.writeFile(
resultPath,
`${JSON.stringify({
...result,
...(normalizedWarnings.length ? { warnings: normalizedWarnings } : {}),
...(facts.length ? { failureFacts: facts } : {}),
})}\n`,
`${JSON.stringify(normalizeUpdatePostInstallDoctorResult(params.result))}\n`,
{
encoding: "utf8",
mode: 0o600,
@ -356,10 +349,14 @@ export async function consumeUpdatePostInstallDoctorResult(
function parseUpdatePostInstallDoctorResult(value: unknown): UpdatePostInstallDoctorResult | null {
const parsed = UpdatePostInstallDoctorResultSchema.safeParse(value);
if (!parsed.success) {
return null;
}
const { warnings, failureFacts, ...result } = parsed.data;
return parsed.success ? normalizeUpdatePostInstallDoctorResult(parsed.data) : null;
}
function normalizeUpdatePostInstallDoctorResult({
warnings,
failureFacts,
...result
}: UpdatePostInstallDoctorResult): UpdatePostInstallDoctorResult {
const normalizedWarnings = normalizeUpdatePostInstallDoctorWarnings(warnings ?? []);
const facts = normalizeUpdateFailureFacts(failureFacts ?? []);
return {

View file

@ -1,5 +1,5 @@
/** Filesystem lifecycle for a non-authoritative, sanitized update report body. */
import { createHash, randomUUID } from "node:crypto";
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
@ -11,6 +11,7 @@ import {
import { resolveStateDir } from "../config/paths.js";
import { redactSupportString } from "../logging/diagnostic-support-redaction.js";
import { classifyUpdateOutcome } from "../shared/update-outcome.js";
import { sha256Hex } from "./crypto-digest.js";
import { formatErrorMessage } from "./errors.js";
import { writeTextAtomic } from "./json-files.js";
import { formatUpdateDoctorLintFinding } from "./update-doctor-lint.js";
@ -118,9 +119,7 @@ export function bindSavedReportArtifact(
previewDigest = prepared.previewDigest,
): PreparedUpdateFailureReport {
const parsed = path.parse(prepared.savedReportPath);
const artifactKey = createHash("sha256")
.update(`${reservationId}\0${previewDigest}`)
.digest("hex");
const artifactKey = sha256Hex(`${reservationId}\0${previewDigest}`);
return {
...prepared,
savedReportPath: path.join(parsed.dir, `${parsed.name}.${artifactKey}${parsed.ext}`),

View file

@ -1,5 +1,4 @@
/** Sanitizes and prepares one explicitly reviewed update-failure report. */
import { createHash } from "node:crypto";
import { isIP } from "node:net";
import path from "node:path";
import { valid as validSemver } from "semver";
@ -16,6 +15,7 @@ import {
} from "../shared/update-outcome.js";
import { truncateUtf8Prefix } from "../utils/utf8-truncate.js";
import { VERSION } from "../version.js";
import { sha256Hex } from "./crypto-digest.js";
import { prepareGithubIssue, type PreparedGithubIssue } from "./github-issue.js";
import { normalizeUpdateChannel } from "./update-channels.js";
import { UPDATE_DESTINATION_RECOVERY } from "./update-destination-failure.js";
@ -448,9 +448,7 @@ export async function prepareUpdateFailureReport(
...(await renderBoundedDiagnostics(input, context, steps)).map((line) => `- ${line}`),
"",
].join("\n");
const reconciliationMarker = `openclaw-update-report:${createHash("sha256")
.update(`${input.attemptId}\0${bodyWithoutMarker}`)
.digest("hex")}`;
const reconciliationMarker = `openclaw-update-report:${sha256Hex(`${input.attemptId}\0${bodyWithoutMarker}`)}`;
const body = truncateUtf8Prefix(
bodyWithoutMarker.replace(
"This report was explicitly reviewed and confirmed in OpenClaw.\n",
@ -466,12 +464,8 @@ export async function prepareUpdateFailureReport(
return {
...issue,
attemptId: input.attemptId,
previewDigest: createHash("sha256").update(issue.body).digest("hex"),
savedReportPath: path.join(
stateDir,
"update-reports",
`${createHash("sha256").update(input.attemptId).digest("hex")}.md`,
),
previewDigest: sha256Hex(issue.body),
savedReportPath: path.join(stateDir, "update-reports", `${sha256Hex(input.attemptId)}.md`),
...(issue.browserFallback.status === "available" ? { url: issue.browserFallback.url } : {}),
};
}

View file

@ -1,8 +1,8 @@
import { createHash } from "node:crypto";
import type { DatabaseSync } from "node:sqlite";
import { safeParseJson } from "@openclaw/normalization-core";
import { isRecord as isPlainRecord } from "@openclaw/normalization-core/record-coerce";
import type { DB as OpenClawStateKyselyDatabase } from "../state/openclaw-state-db.generated.js";
import { sha256Hex } from "./crypto-digest.js";
import { executeSqliteQuerySync, getNodeSqliteKysely } from "./kysely-sync.js";
import {
buildRestartSentinelRow,
@ -97,7 +97,7 @@ function isValidTerminalReceipt(receipt: UpdateFailureReportReceipt): boolean {
}
function receiptKey(attemptId: string): string {
return `${RECEIPT_KEY_PREFIX}${createHash("sha256").update(attemptId).digest("hex")}`;
return `${RECEIPT_KEY_PREFIX}${sha256Hex(attemptId)}`;
}
function parseReceipt(sentinel: RestartSentinel | null): UpdateFailureReportReceipt | null {

View file

@ -89,9 +89,11 @@ export type UpdateFailureReportSubmitResult =
function resultFromExistingReceipt(
receipt: UpdateFailureReportReceipt | null,
savedReportPath: string,
expectedPreviewDigest: string,
expectedFallbackUrl: string | undefined,
prepared: PreparedUpdateFailureReport,
savedReportPath = receipt
? bindSavedReportArtifact(prepared, receipt.reservationId, receipt.previewDigest)
.savedReportPath
: prepared.savedReportPath,
): UpdateFailureReportSubmitResult {
if (receipt?.status === "pending") {
return {
@ -121,9 +123,9 @@ function resultFromExistingReceipt(
status: "retryable",
};
}
const previewMatches = receipt?.previewDigest === expectedPreviewDigest;
const previewMatches = receipt?.previewDigest === prepared.previewDigest;
const matchingFallbackUrl =
previewMatches && receipt?.status === "fallback" && receipt.fallbackUrl === expectedFallbackUrl
previewMatches && receipt?.status === "fallback" && receipt.fallbackUrl === prepared.url
? receipt.fallbackUrl
: undefined;
return {
@ -142,26 +144,20 @@ function resultFromExistingReceipt(
};
}
function receiptMatches(
receipt: UpdateFailureReportReceipt | null,
expected: UpdateFailureReportReceipt,
): boolean {
return (
receipt?.reservationId === expected.reservationId &&
receipt.status === expected.status &&
receipt.previewDigest === expected.previewDigest &&
receipt.cleanup === expected.cleanup &&
receipt.url === expected.url &&
receipt.fallbackUrl === expected.fallbackUrl
);
}
function receiptMatchesBestEffort(
readReceipt: () => UpdateFailureReportReceipt | null,
expected: UpdateFailureReportReceipt,
): boolean {
try {
return receiptMatches(readReceipt(), expected);
const receipt = readReceipt();
return (
receipt?.reservationId === expected.reservationId &&
receipt.status === expected.status &&
receipt.previewDigest === expected.previewDigest &&
receipt.cleanup === expected.cleanup &&
receipt.url === expected.url &&
receipt.fallbackUrl === expected.fallbackUrl
);
} catch {
return false;
}
@ -241,6 +237,26 @@ export async function submitUpdateFailureReport(
}
const finalizeReceipt = options.finalizeReceipt ?? finalizeUpdateFailureReportReceipt;
const readReceipt = options.readReceipt ?? readUpdateFailureReportReceipt;
const recordCreatedIssue = async (url: string, reservationId: string) => {
const receipt: UpdateFailureReportReceipt = {
cleanup: "pending",
previewDigest: prepared.previewDigest,
reservationId,
status: "created",
url,
};
const finalized = retryUpdateReportStateWrite(() =>
finalizeReceipt(prepared.attemptId, receipt, stateEnv),
);
if (
!finalized &&
!receiptMatchesBestEffort(() => readReceipt(prepared.attemptId, stateEnv), receipt)
) {
return undefined;
}
await cleanOwnedReportArtifact(prepared, receipt, stateEnv, options.artifactSweepHooks);
return receipt;
};
const persistKnownNoStartReceipt = async (
receipt: UpdateFailureReportReceipt,
): Promise<boolean> =>
@ -283,23 +299,9 @@ export async function submitUpdateFailureReport(
reconciled = { status: "unavailable" };
}
if (reconciled.status === "created") {
const receipt: UpdateFailureReportReceipt = {
cleanup: "pending",
previewDigest: prepared.previewDigest,
reservationId: existingReceipt.reservationId,
status: "created",
url: reconciled.url,
};
const finalized = retryUpdateReportStateWrite(() =>
finalizeReceipt(prepared.attemptId, receipt, stateEnv),
);
const terminalRecorded =
finalized ||
receiptMatchesBestEffort(() => readReceipt(prepared.attemptId, stateEnv), receipt);
if (terminalRecorded) {
await cleanOwnedReportArtifact(prepared, receipt, stateEnv, options.artifactSweepHooks);
existingReceipt = receipt;
}
existingReceipt =
(await recordCreatedIssue(reconciled.url, existingReceipt.reservationId)) ??
existingReceipt;
}
}
if (
@ -334,16 +336,7 @@ export async function submitUpdateFailureReport(
true,
);
}
return resultFromExistingReceipt(
existingReceipt,
bindSavedReportArtifact(
prepared,
existingReceipt.reservationId,
existingReceipt.previewDigest,
).savedReportPath,
prepared.previewDigest,
prepared.url,
);
return resultFromExistingReceipt(existingReceipt, prepared);
}
if (options.validateCurrentAttempt && !(await options.validateCurrentAttempt())) {
return {
@ -400,18 +393,7 @@ export async function submitUpdateFailureReport(
))
) {
const currentReceipt = readReceipt(prepared.attemptId, stateEnv);
return resultFromExistingReceipt(
currentReceipt,
currentReceipt
? bindSavedReportArtifact(
prepared,
currentReceipt.reservationId,
currentReceipt.previewDigest,
).savedReportPath
: prepared.savedReportPath,
prepared.previewDigest,
prepared.url,
);
return resultFromExistingReceipt(currentReceipt, prepared);
}
}
@ -434,18 +416,7 @@ export async function submitUpdateFailureReport(
true,
);
}
return resultFromExistingReceipt(
reservation.receipt,
reservation.receipt
? bindSavedReportArtifact(
prepared,
reservation.receipt.reservationId,
reservation.receipt.previewDigest,
).savedReportPath
: prepared.savedReportPath,
prepared.previewDigest,
prepared.url,
);
return resultFromExistingReceipt(reservation.receipt, prepared);
}
const ownedPrepared = bindSavedReportArtifact(prepared, reservationId);
@ -473,9 +444,8 @@ export async function submitUpdateFailureReport(
if (!(await cleanupOwnedPreparation())) {
return resultFromExistingReceipt(
readReceipt(prepared.attemptId, stateEnv),
prepared,
ownedPrepared.savedReportPath,
prepared.previewDigest,
prepared.url,
);
}
return {
@ -499,9 +469,8 @@ export async function submitUpdateFailureReport(
await discardSavedUpdateFailureReportBestEffort(ownedPrepared, saved, true);
return resultFromExistingReceipt(
readReceipt(prepared.attemptId, stateEnv),
prepared,
ownedPrepared.savedReportPath,
prepared.previewDigest,
prepared.url,
);
}
await publishPreparedUpdateFailureReport(ownedPrepared, saved);
@ -572,17 +541,15 @@ export async function submitUpdateFailureReport(
await discardSavedUpdateFailureReportBestEffort(ownedPrepared, saved, true);
return resultFromExistingReceipt(
readReceipt(prepared.attemptId, stateEnv),
prepared,
ownedPrepared.savedReportPath,
prepared.previewDigest,
prepared.url,
);
}
if (!(await cleanupOwnedPreparation())) {
return resultFromExistingReceipt(
readReceipt(prepared.attemptId, stateEnv),
prepared,
ownedPrepared.savedReportPath,
prepared.previewDigest,
prepared.url,
);
}
if (error.reason === "stale") {
@ -595,22 +562,7 @@ export async function submitUpdateFailureReport(
throw error;
}
if (created.status === "created") {
const receipt: UpdateFailureReportReceipt = {
cleanup: "pending",
previewDigest: prepared.previewDigest,
reservationId,
status: "created",
url: created.url,
};
const finalized = retryUpdateReportStateWrite(() =>
finalizeReceipt(prepared.attemptId, receipt, stateEnv),
);
const terminalRecorded =
finalized ||
receiptMatchesBestEffort(() => readReceipt(prepared.attemptId, stateEnv), receipt);
if (terminalRecorded) {
await cleanOwnedReportArtifact(prepared, receipt, stateEnv, options.artifactSweepHooks);
}
const terminalRecorded = await recordCreatedIssue(created.url, reservationId);
return {
...(!terminalRecorded
? {
@ -673,12 +625,8 @@ export async function submitUpdateFailureReport(
}
return resultFromExistingReceipt(
replacement,
replacement
? bindSavedReportArtifact(prepared, replacement.reservationId, replacement.previewDigest)
.savedReportPath
: ownedPrepared.savedReportPath,
prepared.previewDigest,
prepared.url,
prepared,
replacement ? undefined : ownedPrepared.savedReportPath,
);
}
const receipt: UpdateFailureReportReceipt = {

View file

@ -2,7 +2,7 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { detectPackageManager as detectPackageManagerImpl } from "./detect-package-manager.js";
import { detectPackageManager } from "./detect-package-manager.js";
import { readPackageManagerSpec } from "./package-json.js";
import { applyPathPrepend } from "./path-prepend.js";
@ -51,20 +51,6 @@ type ResolvedBuildManager =
reason: UpdatePackageManagerFailureReason;
};
async function detectBuildManager(root: string): Promise<BuildManager> {
return (await detectPackageManagerImpl(root)) ?? "npm";
}
function managerPreferenceOrder(preferred: BuildManager): BuildManager[] {
if (preferred === "pnpm") {
return ["pnpm", "npm", "bun"];
}
if (preferred === "bun") {
return ["bun", "npm", "pnpm"];
}
return ["npm", "pnpm", "bun"];
}
async function isManagerAvailable(
runCommand: PackageManagerCommandRunner,
manager: BuildManager | "corepack",
@ -172,7 +158,7 @@ export async function resolveUpdateBuildManager(
// Version selection belongs to the target checkout, including preflight and rollback.
const runCommand: PackageManagerCommandRunner = (argv, options) =>
commandRunner(argv, { ...options, cwd: root });
const preferred = await detectBuildManager(root);
const preferred = (await detectPackageManager(root)) ?? "npm";
const pin = await readPackageManagerSpec(root);
const pnpmVersion = /^pnpm@(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(?:\+.*)?$/u.exec(pin ?? "")?.[1];
if (preferred === "pnpm") {
@ -219,7 +205,9 @@ export async function resolveUpdateBuildManager(
return { kind: "missing-required", preferred, reason: "pnpm-corepack-enable-failed" };
}
for (const manager of managerPreferenceOrder(preferred)) {
const managers: BuildManager[] =
preferred === "bun" ? ["bun", "npm", "pnpm"] : ["npm", "pnpm", "bun"];
for (const manager of managers) {
if (
await isManagerAvailable(
runCommand,

View file

@ -1,4 +1,3 @@
import { createHash } from "node:crypto";
import type { BigIntStats } from "node:fs";
import fs from "node:fs/promises";
import path from "node:path";
@ -10,6 +9,7 @@ import {
} from "../commands/backup-verify-manifest.js";
import { resolveConfigPath, resolveStateDir } from "../config/paths.js";
import { resolvePathViaExistingAncestorSync } from "./boundary-path.js";
import { sha256Hex } from "./crypto-digest.js";
import { pinDirectory, sha256File } from "./directory-durability.js";
import { hasErrnoCode } from "./errno.js";
import { formatErrorMessage } from "./errors.js";
@ -88,10 +88,6 @@ function canonicalEntryPath(pathname: string): string {
const MAX_MANIFEST_BYTES = 128 * 1024 * 1024;
function digest(value: string | Buffer): string {
return createHash("sha256").update(value).digest("hex");
}
function backupStore(stateDir = resolveStateDir()): string {
return `${resolvePathViaExistingAncestorSync(stateDir)}.update-captures`;
}
@ -144,7 +140,7 @@ async function withRecoveryMetadata<T>(
symlinks: "reject",
hardlinks: "reject",
});
if (digest(bytes.buffer) !== ref.manifestSha256) {
if (sha256Hex(bytes.buffer) !== ref.manifestSha256) {
throw new Error("Update recovery manifest changed before metadata access.");
}
const manifest = parseUpdateRecoveryBackupManifest(bytes.buffer.toString("utf8"));
@ -232,7 +228,7 @@ async function fingerprintIncompleteRecoveryGeneration(
]);
}
assertOwned();
return digest(JSON.stringify(inventory));
return sha256Hex(JSON.stringify(inventory));
}
/** This records repair of current state, never reverse publication or permission to delete B/C/T. */
async function readBinding(ref: UpdateRecoveryBackupRef, authority: Authority) {
@ -308,9 +304,9 @@ async function readBinding(ref: UpdateRecoveryBackupRef, authority: Authority) {
throw new Error("Forward recovery generation identity changed.");
}
if (kind === "candidate") {
generations.candidateSha256 = digest(raw);
generations.candidateSha256 = sha256Hex(raw);
} else {
generations.preparedSha256 = digest(raw);
generations.preparedSha256 = sha256Hex(raw);
}
}
await pin.assertCurrent();
@ -421,7 +417,7 @@ async function listBackups(installRoot?: string): Promise<
if (installRoot && manifest.installRoot !== path.resolve(installRoot)) {
continue;
}
const ref = { directory, manifestPath, manifestSha256: digest(raw) };
const ref = { directory, manifestPath, manifestSha256: sha256Hex(raw) };
assertManifestLocation(ref, manifest);
const capture = (await getUpdateRunAsync(manifest.runId))?.origin.updateRecoveryCapture;
if (capture && capture.manifestSha256 !== ref.manifestSha256) {

View file

@ -103,27 +103,19 @@ export async function updateGitCheckout(params: {
reason: "Installed checkout was not changed",
};
const prepareMutation = async (revision: string, root = gitRoot, runner = runCommand) => {
if (mutationPrepared) {
// Remote transport can outlive the earlier service inspection. Recheck
// its frozen contexts before checkout without repeating stop/preparation.
await prepareGitMutation({
runCommand: runner,
root,
revision,
timeoutMs,
beforeGitMutation: opts.inspectGitTarget,
});
return;
}
// Remote transport can outlive the earlier service inspection. Recheck
// its frozen contexts before checkout without repeating stop/preparation.
await prepareGitMutation({
runCommand: runner,
root,
revision,
timeoutMs,
beforeGitMutation: opts.beforeGitMutation,
beforeGitMutation: mutationPrepared ? opts.inspectGitTarget : opts.beforeGitMutation,
});
mutationPrepared = true;
recovery = { serviceRestartSafe: false, reason: "runtime-verification-failed" };
if (!mutationPrepared) {
mutationPrepared = true;
recovery = { serviceRestartSafe: false, reason: "runtime-verification-failed" };
}
};
const buildError = (reason: string, status: "error" | "skipped" = "error"): UpdateRunResult => ({
status,

View file

@ -150,7 +150,9 @@ export type WideAreaGatewayZoneOpts = {
cliPath?: string;
};
function renderZone(opts: WideAreaGatewayZoneOpts & { serial: number }): string {
export function renderWideAreaGatewayZoneText(
opts: WideAreaGatewayZoneOpts & { serial: number },
): string {
const hostname = os.hostname().split(".")[0] ?? "openclaw";
const hostLabel = dnsLabel(opts.hostLabel ?? hostname, "openclaw");
const instanceLabel = dnsLabel(opts.instanceLabel ?? `${hostname}-gateway`, "openclaw-gw");
@ -209,12 +211,6 @@ function renderZone(opts: WideAreaGatewayZoneOpts & { serial: number }): string
return `; openclaw-content-hash: ${contentHash}\n${contentBody}`;
}
export function renderWideAreaGatewayZoneText(
opts: WideAreaGatewayZoneOpts & { serial: number },
): string {
return renderZone(opts);
}
export async function writeWideAreaGatewayZone(
opts: WideAreaGatewayZoneOpts,
): Promise<{ zonePath: string; changed: boolean }> {

View file

@ -3,6 +3,7 @@ import { execFileSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce";
import { escapeRegExp } from "../shared/regexp.js";
import { resolveDiagnosticProcessEnv } from "./process-env.js";
const DEFAULT_WINDOWS_SYSTEM_ROOT = "C:\\Windows";
@ -12,8 +13,6 @@ const WINDOWS_NT_CURRENT_VERSION_KEY = "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\C
const WINDOWS_CURRENT_VERSION_KEY = "HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion";
const REG_QUERY_TIMEOUT_MS = 5_000;
type QueryRegistryValue = (key: string, valueName: string, deadlineMs?: number) => string | null;
type IsReadableFile = (filePath: string) => boolean;
type WindowsInstallRoots = {
systemRoot: string;
programFiles: string;
@ -27,16 +26,15 @@ type WindowsProcessRoots = {
installRoots?: WindowsInstallRoots;
};
const queryRegistryValueFn: QueryRegistryValue = defaultQueryRegistryValue;
const isReadableFileFn: IsReadableFile = defaultIsReadableFile;
let cachedProcessRoots: WindowsProcessRoots | null = null;
function defaultIsReadableFile(filePath: string): boolean {
function locateWindowsRegExe(): string | null {
const filePath = path.win32.join(DEFAULT_WINDOWS_SYSTEM_ROOT, "System32", "reg.exe");
try {
fs.accessSync(filePath, fs.constants.R_OK);
return true;
return filePath;
} catch {
return false;
return null;
}
}
@ -94,25 +92,8 @@ function getEnvValueCaseInsensitive(
return actualKey ? env[actualKey] : undefined;
}
function getWindowsRegExeCandidates(): readonly string[] {
return [path.win32.join(DEFAULT_WINDOWS_SYSTEM_ROOT, "System32", "reg.exe")];
}
function locateWindowsRegExe(): string | null {
for (const candidate of getWindowsRegExeCandidates()) {
if (isReadableFileFn(candidate)) {
return candidate;
}
}
return null;
}
function escapeRegex(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function parseRegQueryValue(stdout: string, valueName: string): string | null {
const pattern = new RegExp(`^\\s*${escapeRegex(valueName)}\\s+REG_[A-Z0-9_]+\\s+(.+)$`, "im");
const pattern = new RegExp(`^\\s*${escapeRegExp(valueName)}\\s+REG_[A-Z0-9_]+\\s+(.+)$`, "im");
const match = stdout.match(pattern);
return match?.[1]?.trim() || null;
}
@ -137,7 +118,8 @@ function runRegQuery(
});
}
function defaultQueryRegistryValue(
/** Queries one Windows registry string value via reg.exe; null when absent or unreadable. */
export function queryWindowsRegistryValue(
key: string,
valueName: string,
deadlineMs?: number,
@ -172,15 +154,16 @@ function getRegistryProgramFilesRoots(): Partial<WindowsInstallRoots> {
return {
programFiles:
normalizeWindowsInstallRoot(
queryRegistryValueFn(WINDOWS_CURRENT_VERSION_KEY, "ProgramFilesDir") ?? undefined,
queryWindowsRegistryValue(WINDOWS_CURRENT_VERSION_KEY, "ProgramFilesDir") ?? undefined,
) ?? undefined,
programFilesX86:
normalizeWindowsInstallRoot(
queryRegistryValueFn(WINDOWS_CURRENT_VERSION_KEY, "ProgramFilesDir (x86)") ?? undefined,
queryWindowsRegistryValue(WINDOWS_CURRENT_VERSION_KEY, "ProgramFilesDir (x86)") ??
undefined,
) ?? undefined,
programW6432:
normalizeWindowsInstallRoot(
queryRegistryValueFn(WINDOWS_CURRENT_VERSION_KEY, "ProgramW6432Dir") ?? undefined,
queryWindowsRegistryValue(WINDOWS_CURRENT_VERSION_KEY, "ProgramW6432Dir") ?? undefined,
) ?? undefined,
};
}
@ -233,7 +216,7 @@ function getProcessRoots(deadlineMs?: number) {
env,
systemRoot:
normalizeWindowsInstallRoot(
queryRegistryValueFn(WINDOWS_NT_CURRENT_VERSION_KEY, "SystemRoot", deadlineMs) ??
queryWindowsRegistryValue(WINDOWS_NT_CURRENT_VERSION_KEY, "SystemRoot", deadlineMs) ??
undefined,
) ?? resolveSystemRootFromEnv(env),
};
@ -298,11 +281,6 @@ export function getWindowsCmdExePath(
return getWindowsSystem32ExePath("cmd.exe", env);
}
/** Queries one Windows registry string value via reg.exe; null when absent or unreadable. */
export function queryWindowsRegistryValue(key: string, valueName: string): string | null {
return queryRegistryValueFn(key, valueName);
}
export function getWindowsSystem32ExePath(
executableName: string,
env: Record<string, string | undefined> = process.env,