Compare commits

...

18 Commits

Author SHA1 Message Date
quotentiroler
2519626293 test: skip unix-path OPENCLAW_HOME tests on Windows 2026-02-08 16:52:52 -08:00
quotentiroler
783f855e79 test: skip unix-path Nix tests on Windows 2026-02-08 15:33:22 -08:00
quotentiroler
6453fdbf70 feat: backward compat for resetByType.dm config key 2026-02-08 15:21:36 -08:00
quotentiroler
93963603b4 test: add explicit backward compat tests for dmdirect migration
- session-key.test.ts: verify both :dm: and :direct: keys are valid
- getDmHistoryLimitFromSessionKey: verify both formats work
2026-02-08 15:04:55 -08:00
max
aced998b0b Merge branch 'main' into fix/import-extensions 2026-02-08 14:56:43 -08:00
George Pickett
0b07e15b63 chore(changelog): note maxTokens clamp (#5516) (thanks @lailoo) (#12139) 2026-02-08 14:27:11 -08:00
George Pickett
92764a60d6 test(config): cover maxTokens clamping 2026-02-08 14:24:57 -08:00
damaozi
eed580d310 fix(config): clamp maxTokens to contextWindow to prevent invalid configurations
Closes #5308

When users configure maxTokens larger than contextWindow (e.g., maxTokens: 40960
with contextWindow: 32768), the model may fail silently. This fix clamps
maxTokens to be at most contextWindow, preventing such invalid configurations.
2026-02-08 14:24:57 -08:00
Sebastian
41f3e90ea8 changelog: split #12091 entry into Added + Fixes 2026-02-08 16:21:18 -05:00
Seb Slight
db137dd65d fix(paths): respect OPENCLAW_HOME for all internal path resolution (#12091)
* fix(paths): respect OPENCLAW_HOME for all internal path resolution (#11995)

Add home-dir module (src/infra/home-dir.ts) that centralizes home
directory resolution with precedence: OPENCLAW_HOME > HOME > USERPROFILE > os.homedir().

Migrate all path-sensitive callsites: config IO, agent dirs, session
transcripts, pairing store, cron store, doctor, CLI profiles.

Add envHomedir() helper in config/paths.ts to reduce lambda noise.
Document OPENCLAW_HOME in docs/help/environment.md.

* fix(paths): handle OPENCLAW_HOME '~' fallback (#12091) (thanks @sebslight)

* docs: mention OPENCLAW_HOME in install and getting started (#12091) (thanks @sebslight)

* fix(status): show OPENCLAW_HOME in shortened paths (#12091) (thanks @sebslight)

* docs(changelog): clarify OPENCLAW_HOME and HOME precedence (#12091) (thanks @sebslight)
2026-02-08 16:20:13 -05:00
quotentiroler
56ca8f2eab fix: accept legacy 'dm' in session key parsing for backward compat
getDmHistoryLimitFromSessionKey now accepts both :dm: and :direct:
to ensure old session keys continue to work correctly.
2026-02-08 10:44:18 -08:00
quotentiroler
4e7392cb36 test: update session key expectations for dmdirect migration
- Fix test expectations to expect :direct: in generated output
- Add explicit backward compat test for normalizeChatType('dm')
- Keep input test data with :dm: keys to verify backward compat
2026-02-08 09:49:30 -08:00
quotentiroler
6f97b9d76f fix tests 2026-02-08 09:44:52 -08:00
quotentiroler
20ae9470ea refactor: unify peer kind to ChatType, rename dm to direct
- Replace RoutePeerKind with ChatType throughout codebase
- Change 'dm' literal values to 'direct' in routing/session keys
- Keep backward compat: normalizeChatType accepts 'dm' -> 'direct'
- Add ChatType export to plugin-sdk, deprecate RoutePeerKind
- Update session key parsing to accept both 'dm' and 'direct' markers
- Update all channel monitors and extensions to use ChatType

BREAKING CHANGE: Session keys now use 'direct' instead of 'dm'.
Existing 'dm' keys still work via backward compat layer.
2026-02-08 09:35:35 -08:00
quotentiroler
0ddc5c0b8b Merge branch 'fix/import-extensions' of https://github.com/openclaw/openclaw into fix/import-extensions 2026-02-08 08:47:39 -08:00
quotentiroler
21cf7c1453 fix tsconfig 2026-02-08 08:47:25 -08:00
max
d46c0b712e Merge branch 'main' into fix/import-extensions 2026-02-08 08:45:55 -08:00
quotentiroler
cb24ec64f2 fix: use .js extension for ESM imports of RoutePeerKind
The imports incorrectly used .ts extension which doesn't resolve
with moduleResolution: NodeNext. Changed to .js and added 'type'
import modifier.
2026-02-08 05:35:04 -08:00
97 changed files with 967 additions and 238 deletions

View File

@@ -11,11 +11,14 @@ Docs: https://docs.openclaw.ai
- Plugins: add `device-pair` (Telegram `/pair` flow) and `phone-control` (iOS/Android node controls). (#11755) Thanks @mbelinky.
- iOS: add alpha iOS node app (Telegram setup-code pairing + Talk/Chat surfaces). (#11756) Thanks @mbelinky.
- Docs: seed initial ja-JP translations (POC) and make docs-i18n prompts language-pluggable for Japanese. (#11988) Thanks @joshp123.
- Paths: add `OPENCLAW_HOME` environment variable for overriding the home directory used by all internal path resolution. (#12091) Thanks @sebslight.
### Fixes
- Exec approvals: format forwarded command text as inline/fenced monospace for safer approval scanning across channels. (#11937)
- Config: clamp `maxTokens` to `contextWindow` to prevent invalid model configs. (#5516) Thanks @lailoo.
- Docs: fix language switcher ordering and Japanese locale flag in Mintlify nav. (#12023) Thanks @joshp123.
- Paths: make internal path resolution respect `HOME`/`USERPROFILE` before `os.homedir()` across config, agents, sessions, pairing, cron, and CLI profiles. (#12091) Thanks @sebslight.
- Thinking: allow xhigh for `github-copilot/gpt-5.2-codex` and `github-copilot/gpt-5.2`. (#11646) Thanks @seans-openclawbot.
- Discord: support forum/media `thread create` starter messages, wire `message thread create --message`, and harden thread-create routing. (#10062) Thanks @jarvis89757.
- Gateway: stabilize chat routing by canonicalizing node session keys for node-originated chat methods. (#11755) Thanks @mbelinky.

View File

@@ -490,14 +490,14 @@ Use `bindings` to route Feishu DMs or groups to different agents.
agentId: "main",
match: {
channel: "feishu",
peer: { kind: "dm", id: "ou_xxx" },
peer: { kind: "direct", id: "ou_xxx" },
},
},
{
agentId: "clawd-fan",
match: {
channel: "feishu",
peer: { kind: "dm", id: "ou_yyy" },
peer: { kind: "direct", id: "ou_yyy" },
},
},
{
@@ -514,7 +514,7 @@ Use `bindings` to route Feishu DMs or groups to different agents.
Routing fields:
- `match.channel`: `"feishu"`
- `match.peer.kind`: `"dm"` or `"group"`
- `match.peer.kind`: `"direct"` or `"group"`
- `match.peer.id`: user Open ID (`ou_xxx`) or group ID (`oc_xxx`)
See [Get group/user IDs](#get-groupuser-ids) for lookup tips.

View File

@@ -196,7 +196,7 @@ Pairing is a DM gate for unknown senders:
- Codes expire after 1 hour; pending requests are capped at 3 per channel.
**Can multiple people use different OpenClaw instances on one WhatsApp number?**
Yes, by routing each sender to a different agent via `bindings` (peer `kind: "dm"`, sender E.164 like `+15551234567`). Replies still come from the **same WhatsApp account**, and direct chats collapse to each agent’s main session, so use **one agent per person**. DM access control (`dmPolicy`/`allowFrom`) is global per WhatsApp account. See [Multi-Agent Routing](/concepts/multi-agent).
Yes, by routing each sender to a different agent via `bindings` (peer `kind: "direct"`, sender E.164 like `+15551234567`). Replies still come from the **same WhatsApp account**, and direct chats collapse to each agent's main session, so use **one agent per person**. DM access control (`dmPolicy`/`allowFrom`) is global per WhatsApp account. See [Multi-Agent Routing](/concepts/multi-agent).
**Why do you ask for my phone number in the wizard?**
The wizard uses it to set your **allowlist/owner** so your own DMs are permitted. It’s not used for auto-sending. If you run on your personal WhatsApp number, use that same number and enable `channels.whatsapp.selfChatMode`.

View File

@@ -82,7 +82,7 @@ This lets **multiple people** share one Gateway server while keeping their AI
## One WhatsApp number, multiple people (DM split)
You can route **different WhatsApp DMs** to different agents while staying on **one WhatsApp account**. Match on sender E.164 (like `+15551234567`) with `peer.kind: "dm"`. Replies still come from the same WhatsApp number (no per‑agent sender identity).
You can route **different WhatsApp DMs** to different agents while staying on **one WhatsApp account**. Match on sender E.164 (like `+15551234567`) with `peer.kind: "direct"`. Replies still come from the same WhatsApp number (no per‑agent sender identity).
Important detail: direct chats collapse to the agent’s **main session key**, so true isolation requires **one agent per person**.
@@ -97,8 +97,14 @@ Example:
],
},
bindings: [
{ agentId: "alex", match: { channel: "whatsapp", peer: { kind: "dm", id: "+15551230001" } } },
{ agentId: "mia", match: { channel: "whatsapp", peer: { kind: "dm", id: "+15551230002" } } },
{
agentId: "alex",
match: { channel: "whatsapp", peer: { kind: "direct", id: "+15551230001" } },
},
{
agentId: "mia",
match: { channel: "whatsapp", peer: { kind: "direct", id: "+15551230002" } },
},
],
channels: {
whatsapp: {
@@ -260,7 +266,10 @@ Keep WhatsApp on the fast agent, but route one DM to Opus:
],
},
bindings: [
{ agentId: "opus", match: { channel: "whatsapp", peer: { kind: "dm", id: "+15551234567" } } },
{
agentId: "opus",
match: { channel: "whatsapp", peer: { kind: "direct", id: "+15551234567" } },
},
{ agentId: "chat", match: { channel: "whatsapp" } },
],
}

View File

@@ -106,7 +106,7 @@ the workspace is writable. See [Memory](/concepts/memory) and
- Daily reset: defaults to **4:00 AM local time on the gateway host**. A session is stale once its last update is earlier than the most recent daily reset time.
- Idle reset (optional): `idleMinutes` adds a sliding idle window. When both daily and idle resets are configured, **whichever expires first** forces a new session.
- Legacy idle-only: if you set `session.idleMinutes` without any `session.reset`/`resetByType` config, OpenClaw stays in idle-only mode for backward compatibility.
- Per-type overrides (optional): `resetByType` lets you override the policy for `dm`, `group`, and `thread` sessions (thread = Slack/Discord threads, Telegram topics, Matrix threads when provided by the connector).
- Per-type overrides (optional): `resetByType` lets you override the policy for `direct`, `group`, and `thread` sessions (thread = Slack/Discord threads, Telegram topics, Matrix threads when provided by the connector).
- Per-channel overrides (optional): `resetByChannel` overrides the reset policy for a channel (applies to all session types for that channel and takes precedence over `reset`/`resetByType`).
- Reset triggers: exact `/new` or `/reset` (plus any extras in `resetTriggers`) start a fresh session id and pass the remainder of the message through. `/new <model>` accepts a model alias, `provider/model`, or provider name (fuzzy match) to set the new session model. If `/new` or `/reset` is sent alone, OpenClaw runs a short “hello” greeting turn to confirm the reset.
- Manual reset: delete specific keys from the store or remove the JSONL transcript; the next message recreates them.
@@ -157,7 +157,7 @@ Runtime override (owner only):
},
resetByType: {
thread: { mode: "daily", atHour: 4 },
dm: { mode: "idle", idleMinutes: 240 },
direct: { mode: "idle", idleMinutes: 240 },
group: { mode: "idle", idleMinutes: 120 },
},
resetByChannel: {

View File

@@ -765,7 +765,7 @@ Inbound messages are routed to an agent via bindings.
- `bindings[]`: routes inbound messages to an `agentId`.
- `match.channel` (required)
- `match.accountId` (optional; `*` = any account; omitted = default account)
- `match.peer` (optional; `{ kind: dm|group|channel, id }`)
- `match.peer` (optional; `{ kind: direct|group|channel, id }`)
- `match.guildId` / `match.teamId` (optional; channel-specific)
Deterministic match order:
@@ -2760,7 +2760,7 @@ Controls session scoping, reset policy, reset triggers, and where the session st
},
resetByType: {
thread: { mode: "daily", atHour: 4 },
dm: { mode: "idle", idleMinutes: 240 },
direct: { mode: "idle", idleMinutes: 240 },
group: { mode: "idle", idleMinutes: 120 },
},
resetTriggers: ["/new", "/reset"],
@@ -2797,7 +2797,7 @@ Fields:
- `mode`: `daily` or `idle` (default: `daily` when `reset` is present).
- `atHour`: local hour (0-23) for the daily reset boundary.
- `idleMinutes`: sliding idle window in minutes. When daily + idle are both configured, whichever expires first wins.
- `resetByType`: per-session overrides for `dm`, `group`, and `thread`.
- `resetByType`: per-session overrides for `direct`, `group`, and `thread`. Legacy `dm` key is accepted as an alias for `direct`.
- If you only set legacy `session.idleMinutes` without any `reset`/`resetByType`, OpenClaw stays in idle-only mode for backward compatibility.
- `heartbeatIdleMinutes`: optional idle override for heartbeat checks (daily reset still applies when enabled).
- `agentToAgent.maxPingPongTurns`: max reply-back turns between requester/target (0–5, default 5).

View File

@@ -74,6 +74,32 @@ You can reference env vars directly in config string values using `${VAR_NAME}`
See [Configuration: Env var substitution](/gateway/configuration#env-var-substitution-in-config) for full details.
## Path-related env vars
| Variable | Purpose |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `OPENCLAW_HOME` | Override the home directory used for all internal path resolution (`~/.openclaw/`, agent dirs, sessions, credentials). Useful when running OpenClaw as a dedicated service user. |
| `OPENCLAW_STATE_DIR` | Override the state directory (default `~/.openclaw`). |
| `OPENCLAW_CONFIG_PATH` | Override the config file path (default `~/.openclaw/openclaw.json`). |
### `OPENCLAW_HOME`
When set, `OPENCLAW_HOME` replaces the system home directory (`$HOME` / `os.homedir()`) for all internal path resolution. This enables full filesystem isolation for headless service accounts.
**Precedence:** `OPENCLAW_HOME` > `$HOME` > `USERPROFILE` > `os.homedir()`
**Example** (macOS LaunchDaemon):
```xml
<key>EnvironmentVariables</key>
<dict>
<key>OPENCLAW_HOME</key>
<string>/Users/kira</string>
</dict>
```
`OPENCLAW_HOME` can also be set to a tilde path (e.g. `~/svc`), which gets expanded using `$HOME` before use.
## Related
- [Gateway configuration](/gateway/configuration)

View File

@@ -803,7 +803,7 @@ See [/channels/telegram](/channels/telegram#access-control-dms--groups).
### Can multiple people use one WhatsApp number with different OpenClaw instances
Yes, via **multi-agent routing**. Bind each sender's WhatsApp **DM** (peer `kind: "dm"`, sender E.164 like `+15551234567`) to a different `agentId`, so each person gets their own workspace and session store. Replies still come from the **same WhatsApp account**, and DM access control (`channels.whatsapp.dmPolicy` / `channels.whatsapp.allowFrom`) is global per WhatsApp account. See [Multi-Agent Routing](/concepts/multi-agent) and [WhatsApp](/channels/whatsapp).
Yes, via **multi-agent routing**. Bind each sender's WhatsApp **DM** (peer `kind: "direct"`, sender E.164 like `+15551234567`) to a different `agentId`, so each person gets their own workspace and session store. Replies still come from the **same WhatsApp account**, and DM access control (`channels.whatsapp.dmPolicy` / `channels.whatsapp.allowFrom`) is global per WhatsApp account. See [Multi-Agent Routing](/concepts/multi-agent) and [WhatsApp](/channels/whatsapp).
### Can I run a fast chat agent and an Opus for coding agent

View File

@@ -163,6 +163,14 @@ openclaw status # gateway status
openclaw dashboard # open the browser UI
```
If you need custom runtime paths, use:
- `OPENCLAW_HOME` for home-directory based internal paths
- `OPENCLAW_STATE_DIR` for mutable state location
- `OPENCLAW_CONFIG_PATH` for config file location
See [Environment vars](/help/environment) for precedence and full details.
## Troubleshooting: `openclaw` not found
<Accordion title="PATH diagnosis and fix">

View File

@@ -64,7 +64,9 @@ defaults write bot.molt.mac openclaw.nixMode -bool true
### Config + state paths
OpenClaw reads JSON5 config from `OPENCLAW_CONFIG_PATH` and stores mutable data in `OPENCLAW_STATE_DIR`.
When needed, you can also set `OPENCLAW_HOME` to control the base home directory used for internal path resolution.
- `OPENCLAW_HOME` (default precedence: `HOME` / `USERPROFILE` / `os.homedir()`)
- `OPENCLAW_STATE_DIR` (default: `~/.openclaw`)
- `OPENCLAW_CONFIG_PATH` (default: `$OPENCLAW_STATE_DIR/openclaw.json`)

View File

@@ -72,7 +72,7 @@ export type PluginRuntime = {
cfg: unknown;
channel: string;
accountId: string;
peer: { kind: "dm" | "group" | "channel"; id: string };
peer: { kind: RoutePeerKind; id: string };
}): { sessionKey: string; accountId: string };
};
pairing: {

View File

@@ -96,6 +96,16 @@ If the Control UI loads, your Gateway is ready for use.
</Accordion>
</AccordionGroup>
## Useful environment variables
If you run OpenClaw as a service account or want custom config/state locations:
- `OPENCLAW_HOME` sets the home directory used for internal path resolution.
- `OPENCLAW_STATE_DIR` overrides the state directory.
- `OPENCLAW_CONFIG_PATH` overrides the config file path.
Full environment variable reference: [Environment vars](/help/environment).
## Go deeper
<Columns>

View File

@@ -79,7 +79,7 @@ export type PluginRuntime = {
cfg: unknown;
channel: string;
accountId: string;
peer: { kind: "dm" | "group" | "channel"; id: string };
peer: { kind: RoutePeerKind; id: string };
}): { sessionKey: string; accountId: string };
};
pairing: {

View File

@@ -1804,7 +1804,7 @@ async function processMessage(
channel: "bluebubbles",
accountId: account.accountId,
peer: {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: peerId,
},
});
@@ -2442,7 +2442,7 @@ async function processReaction(
channel: "bluebubbles",
accountId: account.accountId,
peer: {
kind: reaction.isGroup ? "group" : "dm",
kind: reaction.isGroup ? "group" : "direct",
id: peerId,
},
});

View File

@@ -652,7 +652,7 @@ export async function handleFeishuMessage(params: {
channel: "feishu",
accountId: account.accountId,
peer: {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: isGroup ? ctx.chatId : ctx.senderOpenId,
},
});

View File

@@ -615,7 +615,7 @@ async function processMessageWithPipeline(params: {
channel: "googlechat",
accountId: account.accountId,
peer: {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: spaceId,
},
});

View File

@@ -453,7 +453,7 @@ export function createMatrixRoomMessageHandler(params: MatrixMonitorHandlerParam
cfg,
channel: "matrix",
peer: {
kind: isDirectMessage ? "dm" : "channel",
kind: isDirectMessage ? "direct" : "channel",
id: isDirectMessage ? senderId : roomId,
},
});

View File

@@ -1,5 +1,6 @@
import type {
ChannelAccountSnapshot,
ChatType,
OpenClawConfig,
ReplyPayload,
RuntimeEnv,
@@ -131,13 +132,13 @@ function isSystemPost(post: MattermostPost): boolean {
return Boolean(type);
}
function channelKind(channelType?: string | null): "dm" | "group" | "channel" {
function channelKind(channelType?: string | null): ChatType {
if (!channelType) {
return "channel";
}
const normalized = channelType.trim().toUpperCase();
if (normalized === "D") {
return "dm";
return "direct";
}
if (normalized === "G") {
return "group";
@@ -145,8 +146,8 @@ function channelKind(channelType?: string | null): "dm" | "group" | "channel" {
return "channel";
}
function channelChatType(kind: "dm" | "group" | "channel"): "direct" | "group" | "channel" {
if (kind === "dm") {
function channelChatType(kind: ChatType): "direct" | "group" | "channel" {
if (kind === "direct") {
return "direct";
}
if (kind === "group") {
@@ -469,11 +470,11 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
hasControlCommand,
});
const commandAuthorized =
kind === "dm"
kind === "direct"
? dmPolicy === "open" || senderAllowedForCommands
: commandGate.commandAuthorized;
if (kind === "dm") {
if (kind === "direct") {
if (dmPolicy === "disabled") {
logVerboseMessage(`mattermost: drop dm (dmPolicy=disabled sender=${senderId})`);
return;
@@ -524,7 +525,7 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
}
}
if (kind !== "dm" && commandGate.shouldBlock) {
if (kind !== "direct" && commandGate.shouldBlock) {
logInboundDrop({
log: logVerboseMessage,
channel: "mattermost",
@@ -547,7 +548,7 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
teamId,
peer: {
kind,
id: kind === "dm" ? senderId : channelId,
id: kind === "direct" ? senderId : channelId,
},
});
@@ -559,11 +560,11 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
parentSessionKey: threadRootId ? baseSessionKey : undefined,
});
const sessionKey = threadKeys.sessionKey;
const historyKey = kind === "dm" ? null : sessionKey;
const historyKey = kind === "direct" ? null : sessionKey;
const mentionRegexes = core.channel.mentions.buildMentionRegexes(cfg, route.agentId);
const wasMentioned =
kind !== "dm" &&
kind !== "direct" &&
((botUsername ? rawText.toLowerCase().includes(`@${botUsername.toLowerCase()}`) : false) ||
core.channel.mentions.matchesMentionPatterns(rawText, mentionRegexes));
const pendingBody =
@@ -590,7 +591,7 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
});
};
const oncharEnabled = account.chatmode === "onchar" && kind !== "dm";
const oncharEnabled = account.chatmode === "onchar" && kind !== "direct";
const oncharPrefixes = oncharEnabled ? resolveOncharPrefixes(account.oncharPrefixes) : [];
const oncharResult = oncharEnabled
? stripOncharPrefix(rawText, oncharPrefixes)
@@ -598,7 +599,7 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
const oncharTriggered = oncharResult.triggered;
const shouldRequireMention =
kind !== "dm" &&
kind !== "direct" &&
core.channel.groups.resolveRequireMention({
cfg,
channel: "mattermost",
@@ -615,7 +616,7 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
return;
}
if (kind !== "dm" && shouldRequireMention && canDetectMention) {
if (kind !== "direct" && shouldRequireMention && canDetectMention) {
if (!effectiveWasMentioned) {
recordPendingHistory();
return;
@@ -637,7 +638,7 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
});
const fromLabel = formatInboundFromLabel({
isGroup: kind !== "dm",
isGroup: kind !== "direct",
groupLabel: channelDisplay || roomLabel,
groupId: channelId,
groupFallback: roomLabel || "Channel",
@@ -647,7 +648,7 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
const preview = bodyText.replace(/\s+/g, " ").slice(0, 160);
const inboundLabel =
kind === "dm"
kind === "direct"
? `Mattermost DM from ${senderName}`
: `Mattermost message in ${roomLabel} from ${senderName}`;
core.system.enqueueSystemEvent(`${inboundLabel}: ${preview}`, {
@@ -685,14 +686,14 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
});
}
const to = kind === "dm" ? `user:${senderId}` : `channel:${channelId}`;
const to = kind === "direct" ? `user:${senderId}` : `channel:${channelId}`;
const mediaPayload = buildMattermostMediaPayload(mediaList);
const ctxPayload = core.channel.reply.finalizeInboundContext({
Body: combinedBody,
RawBody: bodyText,
CommandBody: bodyText,
From:
kind === "dm"
kind === "direct"
? `mattermost:${senderId}`
: kind === "group"
? `mattermost:group:${channelId}`
@@ -703,7 +704,7 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
AccountId: route.accountId,
ChatType: chatType,
ConversationLabel: fromLabel,
GroupSubject: kind !== "dm" ? channelDisplay || roomLabel : undefined,
GroupSubject: kind !== "direct" ? channelDisplay || roomLabel : undefined,
GroupChannel: channelName ? `#${channelName}` : undefined,
GroupSpace: teamId,
SenderName: senderName,
@@ -718,14 +719,14 @@ export async function monitorMattermostProvider(opts: MonitorMattermostOpts = {}
ReplyToId: threadRootId,
MessageThreadId: threadRootId,
Timestamp: typeof post.create_at === "number" ? post.create_at : undefined,
WasMentioned: kind !== "dm" ? effectiveWasMentioned : undefined,
WasMentioned: kind !== "direct" ? effectiveWasMentioned : undefined,
CommandAuthorized: commandAuthorized,
OriginatingChannel: "mattermost" as const,
OriginatingTo: to,
...mediaPayload,
});
if (kind === "dm") {
if (kind === "direct") {
const sessionCfg = cfg.session;
const storePath = core.channel.session.resolveStorePath(sessionCfg?.store, {
agentId: route.agentId,

View File

@@ -342,7 +342,7 @@ export function createMSTeamsMessageHandler(deps: MSTeamsMessageHandlerDeps) {
cfg,
channel: "msteams",
peer: {
kind: isDirectMessage ? "dm" : isChannel ? "channel" : "group",
kind: isDirectMessage ? "direct" : isChannel ? "channel" : "group",
id: isDirectMessage ? senderId : conversationId,
},
});

View File

@@ -228,7 +228,7 @@ export async function handleNextcloudTalkInbound(params: {
channel: CHANNEL_ID,
accountId: account.accountId,
peer: {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: isGroup ? roomToken : senderId,
},
});

View File

@@ -101,7 +101,7 @@ const tlonOutbound: ChannelOutboundAdapter = {
error: new Error(`Invalid Tlon target. Use ${formatTargetHint()}`),
};
}
if (parsed.kind === "dm") {
if (parsed.kind === "direct") {
return { ok: true, to: parsed.ship };
}
return { ok: true, to: parsed.nest };
@@ -127,7 +127,7 @@ const tlonOutbound: ChannelOutboundAdapter = {
try {
const fromShip = normalizeShip(account.ship);
if (parsed.kind === "dm") {
if (parsed.kind === "direct") {
return await sendDm({
api,
fromShip,
@@ -298,7 +298,7 @@ export const tlonPlugin: ChannelPlugin = {
if (!parsed) {
return target.trim();
}
if (parsed.kind === "dm") {
if (parsed.kind === "direct") {
return parsed.ship;
}
return parsed.nest;

View File

@@ -343,7 +343,7 @@ export async function monitorTlonProvider(opts: MonitorTlonOpts = {}): Promise<v
channel: "tlon",
accountId: opts.accountId ?? undefined,
peer: {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: isGroup ? (groupChannel ?? senderShip) : senderShip,
},
});

View File

@@ -1,5 +1,5 @@
export type TlonTarget =
| { kind: "dm"; ship: string }
| { kind: "direct"; ship: string }
| { kind: "group"; nest: string; hostShip: string; channelName: string };
const SHIP_RE = /^~?[a-z-]+$/i;
@@ -32,7 +32,7 @@ export function parseTlonTarget(raw?: string | null): TlonTarget | null {
const dmPrefix = withoutPrefix.match(/^dm[/:](.+)$/i);
if (dmPrefix) {
return { kind: "dm", ship: normalizeShip(dmPrefix[1]) };
return { kind: "direct", ship: normalizeShip(dmPrefix[1]) };
}
const groupPrefix = withoutPrefix.match(/^(group|room)[/:](.+)$/i);
@@ -78,7 +78,7 @@ export function parseTlonTarget(raw?: string | null): TlonTarget | null {
}
if (SHIP_RE.test(withoutPrefix)) {
return { kind: "dm", ship: normalizeShip(withoutPrefix) };
return { kind: "direct", ship: normalizeShip(withoutPrefix) };
}
return null;

View File

@@ -515,7 +515,7 @@ async function processMessageWithPipeline(params: {
channel: "zalo",
accountId: account.accountId,
peer: {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: chatId,
},
});

View File

@@ -1,11 +1,17 @@
import { describe, expect, it } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "../config/config.js";
import {
resolveAgentConfig,
resolveAgentDir,
resolveAgentModelFallbacksOverride,
resolveAgentModelPrimary,
resolveAgentWorkspaceDir,
} from "./agent-scope.js";
afterEach(() => {
vi.unstubAllEnvs();
});
describe("resolveAgentConfig", () => {
it("should return undefined when no agents config exists", () => {
const cfg: OpenClawConfig = {};
@@ -200,4 +206,20 @@ describe("resolveAgentConfig", () => {
expect(result).toBeDefined();
expect(result?.workspace).toBe("~/openclaw");
});
// Unix-style paths behave differently on Windows; skip there
it.skipIf(process.platform === "win32")("uses OPENCLAW_HOME for default agent workspace", () => {
vi.stubEnv("OPENCLAW_HOME", "/srv/openclaw-home");
const workspace = resolveAgentWorkspaceDir({} as OpenClawConfig, "main");
expect(workspace).toBe("/srv/openclaw-home/.openclaw/workspace");
});
// Unix-style paths behave differently on Windows; skip there
it.skipIf(process.platform === "win32")("uses OPENCLAW_HOME for default agentDir", () => {
vi.stubEnv("OPENCLAW_HOME", "/srv/openclaw-home");
const agentDir = resolveAgentDir({} as OpenClawConfig, "main");
expect(agentDir).toBe("/srv/openclaw-home/.openclaw/agents/main/agent");
});
});

View File

@@ -1,4 +1,3 @@
import os from "node:os";
import path from "node:path";
import type { OpenClawConfig } from "../config/config.js";
import { resolveStateDir } from "../config/paths.js";
@@ -8,7 +7,7 @@ import {
parseAgentSessionKey,
} from "../routing/session-key.js";
import { resolveUserPath } from "../utils.js";
import { DEFAULT_AGENT_WORKSPACE_DIR } from "./workspace.js";
import { resolveDefaultAgentWorkspaceDir } from "./workspace.js";
export { resolveAgentIdFromSessionKey } from "../routing/session-key.js";
@@ -176,9 +175,9 @@ export function resolveAgentWorkspaceDir(cfg: OpenClawConfig, agentId: string) {
if (fallback) {
return resolveUserPath(fallback);
}
return DEFAULT_AGENT_WORKSPACE_DIR;
return resolveDefaultAgentWorkspaceDir(process.env);
}
const stateDir = resolveStateDir(process.env, os.homedir);
const stateDir = resolveStateDir(process.env);
return path.join(stateDir, `workspace-${id}`);
}
@@ -188,6 +187,6 @@ export function resolveAgentDir(cfg: OpenClawConfig, agentId: string) {
if (configured) {
return resolveUserPath(configured);
}
const root = resolveStateDir(process.env, os.homedir);
const root = resolveStateDir(process.env);
return path.join(root, "agents", id, "agent");
}

View File

@@ -228,4 +228,18 @@ describe("getDmHistoryLimitFromSessionKey", () => {
} as OpenClawConfig;
expect(getDmHistoryLimitFromSessionKey("telegram:dm:123", config)).toBe(5);
});
describe("backward compatibility", () => {
it("accepts both legacy :dm: and new :direct: session keys", () => {
const config = {
channels: { telegram: { dmHistoryLimit: 10 } },
} as OpenClawConfig;
// Legacy format with :dm:
expect(getDmHistoryLimitFromSessionKey("telegram:dm:123", config)).toBe(10);
expect(getDmHistoryLimitFromSessionKey("agent:main:telegram:dm:123", config)).toBe(10);
// New format with :direct:
expect(getDmHistoryLimitFromSessionKey("telegram:direct:123", config)).toBe(10);
expect(getDmHistoryLimitFromSessionKey("agent:main:telegram:direct:123", config)).toBe(10);
});
});
});

View File

@@ -58,7 +58,8 @@ export function getDmHistoryLimitFromSessionKey(
const kind = providerParts[1]?.toLowerCase();
const userIdRaw = providerParts.slice(2).join(":");
const userId = stripThreadSuffix(userIdRaw);
if (kind !== "dm") {
// Accept both "direct" (new) and "dm" (legacy) for backward compat
if (kind !== "direct" && kind !== "dm") {
return undefined;
}

View File

@@ -190,15 +190,16 @@ function inferDeliveryFromSessionKey(agentSessionKey?: string): CronDelivery | n
}
// buildAgentPeerSessionKey encodes peers as:
// - dm:<peerId>
// - <channel>:dm:<peerId>
// - <channel>:<accountId>:dm:<peerId>
// - direct:<peerId>
// - <channel>:direct:<peerId>
// - <channel>:<accountId>:direct:<peerId>
// - <channel>:group:<peerId>
// - <channel>:channel:<peerId>
// Note: legacy keys may use "dm" instead of "direct".
// Threaded sessions append :thread:<id>, which we strip so delivery targets the parent peer.
// NOTE: Telegram forum topics encode as <chatId>:topic:<topicId> and should be preserved.
const markerIndex = parts.findIndex(
(part) => part === "dm" || part === "group" || part === "channel",
(part) => part === "direct" || part === "dm" || part === "group" || part === "channel",
);
if (markerIndex === -1) {
return null;

View File

@@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";
import type { OpenClawConfig } from "../config/config.js";
import { resolveStateDir } from "../config/paths.js";
import { resolveRunWorkspaceDir } from "./workspace-run.js";
import { DEFAULT_AGENT_WORKSPACE_DIR } from "./workspace.js";
import { resolveDefaultAgentWorkspaceDir } from "./workspace.js";
describe("resolveRunWorkspaceDir", () => {
it("resolves explicit workspace values without fallback", () => {
@@ -70,7 +70,7 @@ describe("resolveRunWorkspaceDir", () => {
expect(result.usedFallback).toBe(true);
expect(result.fallbackReason).toBe("missing");
expect(result.agentId).toBe("main");
expect(result.workspaceDir).toBe(path.resolve(DEFAULT_AGENT_WORKSPACE_DIR));
expect(result.workspaceDir).toBe(path.resolve(resolveDefaultAgentWorkspaceDir(process.env)));
});
it("throws for malformed agent session keys", () => {

View File

@@ -0,0 +1,18 @@
import { afterEach, describe, expect, it, vi } from "vitest";
afterEach(() => {
vi.unstubAllEnvs();
vi.resetModules();
});
describe("DEFAULT_AGENT_WORKSPACE_DIR", () => {
// Unix-style paths behave differently on Windows; skip there
it.skipIf(process.platform === "win32")("uses OPENCLAW_HOME at module import time", async () => {
vi.stubEnv("OPENCLAW_HOME", "/srv/openclaw-home");
vi.stubEnv("HOME", "/home/other");
vi.resetModules();
const mod = await import("./workspace.js");
expect(mod.DEFAULT_AGENT_WORKSPACE_DIR).toBe("/srv/openclaw-home/.openclaw/workspace");
});
});

View File

@@ -1,11 +1,24 @@
import path from "node:path";
import { describe, expect, it } from "vitest";
import { makeTempWorkspace, writeWorkspaceFile } from "../test-helpers/workspace.js";
import {
DEFAULT_MEMORY_ALT_FILENAME,
DEFAULT_MEMORY_FILENAME,
loadWorkspaceBootstrapFiles,
resolveDefaultAgentWorkspaceDir,
} from "./workspace.js";
describe("resolveDefaultAgentWorkspaceDir", () => {
it("uses OPENCLAW_HOME for default workspace resolution", () => {
const dir = resolveDefaultAgentWorkspaceDir({
OPENCLAW_HOME: "/srv/openclaw-home",
HOME: "/home/other",
} as NodeJS.ProcessEnv);
expect(dir).toBe(path.join("/srv/openclaw-home", ".openclaw", "workspace"));
});
});
describe("loadWorkspaceBootstrapFiles", () => {
it("includes MEMORY.md when present", async () => {
const tempDir = await makeTempWorkspace("openclaw-workspace-");

View File

@@ -1,6 +1,7 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { resolveRequiredHomeDir } from "../infra/home-dir.js";
import { runCommandWithTimeout } from "../process/exec.js";
import { isSubagentSessionKey } from "../routing/session-key.js";
import { resolveUserPath } from "../utils.js";
@@ -10,11 +11,12 @@ export function resolveDefaultAgentWorkspaceDir(
env: NodeJS.ProcessEnv = process.env,
homedir: () => string = os.homedir,
): string {
const home = resolveRequiredHomeDir(env, homedir);
const profile = env.OPENCLAW_PROFILE?.trim();
if (profile && profile.toLowerCase() !== "default") {
return path.join(homedir(), ".openclaw", `workspace-${profile}`);
return path.join(home, ".openclaw", `workspace-${profile}`);
}
return path.join(homedir(), ".openclaw", "workspace");
return path.join(home, ".openclaw", "workspace");
}
export const DEFAULT_AGENT_WORKSPACE_DIR = resolveDefaultAgentWorkspaceDir();

View File

@@ -454,7 +454,7 @@ describe("initSessionState channel reset overrides", () => {
session: {
store: storePath,
idleMinutes: 60,
resetByType: { dm: { mode: "idle", idleMinutes: 10 } },
resetByType: { direct: { mode: "idle", idleMinutes: 10 } },
resetByChannel: { discord: { mode: "idle", idleMinutes: 10080 } },
},
} as OpenClawConfig;

View File

@@ -15,4 +15,13 @@ describe("normalizeChatType", () => {
expect(normalizeChatType("nope")).toBeUndefined();
expect(normalizeChatType("room")).toBeUndefined();
});
describe("backward compatibility", () => {
it("accepts legacy 'dm' value and normalizes to 'direct'", () => {
// Legacy config/input may use "dm" - ensure smooth upgrade path
expect(normalizeChatType("dm")).toBe("direct");
expect(normalizeChatType("DM")).toBe("direct");
expect(normalizeChatType(" dm ")).toBe("direct");
});
});
});

View File

@@ -1,6 +1,6 @@
export type NormalizedChatType = "direct" | "group" | "channel";
export type ChatType = "direct" | "group" | "channel";
export function normalizeChatType(raw?: string): NormalizedChatType | undefined {
export function normalizeChatType(raw?: string): ChatType | undefined {
const value = raw?.trim().toLowerCase();
if (!value) {
return undefined;

View File

@@ -4,7 +4,7 @@ import type { MsgContext } from "../../auto-reply/templating.js";
import type { OpenClawConfig } from "../../config/config.js";
import type { PollInput } from "../../polls.js";
import type { GatewayClientMode, GatewayClientName } from "../../utils/message-channel.js";
import type { NormalizedChatType } from "../chat-type.js";
import type { ChatType } from "../chat-type.js";
import type { ChatChannelId } from "../registry.js";
import type { ChannelMessageActionName as ChannelMessageActionNameFromList } from "./message-action-names.js";
@@ -162,7 +162,7 @@ export type ChannelGroupContext = {
};
export type ChannelCapabilities = {
chatTypes: Array<NormalizedChatType | "thread">;
chatTypes: Array<ChatType | "thread">;
polls?: boolean;
reactions?: boolean;
edit?: boolean;

View File

@@ -82,6 +82,23 @@ describe("applyCliProfileEnv", () => {
expect(env.OPENCLAW_GATEWAY_PORT).toBe("19099");
expect(env.OPENCLAW_CONFIG_PATH).toBe(path.join("/custom", "openclaw.json"));
});
it("uses OPENCLAW_HOME when deriving profile state dir", () => {
const env: Record<string, string | undefined> = {
OPENCLAW_HOME: "/srv/openclaw-home",
HOME: "/home/other",
};
applyCliProfileEnv({
profile: "work",
env,
homedir: () => "/home/fallback",
});
expect(env.OPENCLAW_STATE_DIR).toBe(path.join("/srv/openclaw-home", ".openclaw-work"));
expect(env.OPENCLAW_CONFIG_PATH).toBe(
path.join("/srv/openclaw-home", ".openclaw-work", "openclaw.json"),
);
});
});
describe("formatCliCommand", () => {

View File

@@ -1,5 +1,6 @@
import os from "node:os";
import path from "node:path";
import { resolveRequiredHomeDir } from "../infra/home-dir.js";
import { isValidProfileName } from "./profile-utils.js";
export type CliProfileParseResult =
@@ -87,9 +88,13 @@ export function parseCliProfileArgs(argv: string[]): CliProfileParseResult {
return { ok: true, profile, argv: out };
}
function resolveProfileStateDir(profile: string, homedir: () => string): string {
function resolveProfileStateDir(
profile: string,
env: Record<string, string | undefined>,
homedir: () => string,
): string {
const suffix = profile.toLowerCase() === "default" ? "" : `-${profile}`;
return path.join(homedir(), `.openclaw${suffix}`);
return path.join(resolveRequiredHomeDir(env as NodeJS.ProcessEnv, homedir), `.openclaw${suffix}`);
}
export function applyCliProfileEnv(params: {
@@ -107,7 +112,7 @@ export function applyCliProfileEnv(params: {
// Convenience only: fill defaults, never override explicit env values.
env.OPENCLAW_PROFILE = profile;
const stateDir = env.OPENCLAW_STATE_DIR?.trim() || resolveProfileStateDir(profile, homedir);
const stateDir = env.OPENCLAW_STATE_DIR?.trim() || resolveProfileStateDir(profile, env, homedir);
if (!env.OPENCLAW_STATE_DIR?.trim()) {
env.OPENCLAW_STATE_DIR = stateDir;
}

View File

@@ -11,6 +11,7 @@ import {
resolveSessionTranscriptsDirForAgent,
resolveStorePath,
} from "../config/sessions.js";
import { resolveRequiredHomeDir } from "../infra/home-dir.js";
import { note } from "../terminal/note.js";
import { shortenHomePath } from "../utils.js";
@@ -139,7 +140,7 @@ export async function noteStateIntegrity(
const warnings: string[] = [];
const changes: string[] = [];
const env = process.env;
const homedir = os.homedir;
const homedir = () => resolveRequiredHomeDir(env, os.homedir);
const stateDir = resolveStateDir(env, homedir);
const defaultStateDir = path.join(homedir(), ".openclaw");
const oauthDir = resolveOAuthDir(env, stateDir);

View File

@@ -0,0 +1,47 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "./types.js";
import { findDuplicateAgentDirs } from "./agent-dirs.js";
afterEach(() => {
vi.unstubAllEnvs();
});
describe("resolveEffectiveAgentDir via findDuplicateAgentDirs", () => {
it("uses OPENCLAW_HOME for default agent dir resolution", () => {
// findDuplicateAgentDirs calls resolveEffectiveAgentDir internally.
// With a single agent there are no duplicates, but we can inspect the
// resolved dir indirectly by triggering a duplicate with two agents
// that both fall through to the same default dir — which can't happen
// since they have different IDs. Instead we just verify no crash and
// that the env flows through by checking a two-agent config produces
// distinct dirs (no duplicates).
const cfg: OpenClawConfig = {
agents: {
list: [{ id: "alpha" }, { id: "beta" }],
},
};
const env = {
OPENCLAW_HOME: "/srv/openclaw-home",
HOME: "/home/other",
} as NodeJS.ProcessEnv;
const dupes = findDuplicateAgentDirs(cfg, { env });
expect(dupes).toHaveLength(0);
});
it("resolves agent dir under OPENCLAW_HOME state dir", () => {
// Force two agents to the same explicit agentDir to verify the path
// that doesn't use the default — then test the default path by
// checking that a single-agent config resolves without duplicates.
const cfg: OpenClawConfig = {};
const env = {
OPENCLAW_HOME: "/srv/openclaw-home",
} as NodeJS.ProcessEnv;
// No duplicates for a single default agent
const dupes = findDuplicateAgentDirs(cfg, { env });
expect(dupes).toHaveLength(0);
});
});

View File

@@ -1,6 +1,7 @@
import os from "node:os";
import path from "node:path";
import type { OpenClawConfig } from "./types.js";
import { resolveRequiredHomeDir } from "../infra/home-dir.js";
import { DEFAULT_AGENT_ID, normalizeAgentId } from "../routing/session-key.js";
import { resolveUserPath } from "../utils.js";
import { resolveStateDir } from "./paths.js";
@@ -68,7 +69,11 @@ function resolveEffectiveAgentDir(
if (trimmed) {
return resolveUserPath(trimmed);
}
const root = resolveStateDir(deps?.env ?? process.env, deps?.homedir ?? os.homedir);
const env = deps?.env ?? process.env;
const root = resolveStateDir(
env,
deps?.homedir ?? (() => resolveRequiredHomeDir(env, os.homedir)),
);
return path.join(root, "agents", id, "agent");
}

View File

@@ -49,6 +49,38 @@ describe("Nix integration (U3, U5, U9)", () => {
});
});
// Skip on Windows: these tests use Unix-style paths that only make sense on Nix/Unix
it.skipIf(process.platform === "win32")(
"STATE_DIR respects OPENCLAW_HOME when state override is unset",
async () => {
await withEnvOverride(
{ OPENCLAW_HOME: "/custom/home", OPENCLAW_STATE_DIR: undefined },
async () => {
const { STATE_DIR } = await import("./config.js");
expect(STATE_DIR).toBe(path.resolve("/custom/home/.openclaw"));
},
);
},
);
// Skip on Windows: these tests use Unix-style paths that only make sense on Nix/Unix
it.skipIf(process.platform === "win32")(
"CONFIG_PATH defaults to OPENCLAW_HOME/.openclaw/openclaw.json",
async () => {
await withEnvOverride(
{
OPENCLAW_HOME: "/custom/home",
OPENCLAW_CONFIG_PATH: undefined,
OPENCLAW_STATE_DIR: undefined,
},
async () => {
const { CONFIG_PATH } = await import("./config.js");
expect(CONFIG_PATH).toBe(path.resolve("/custom/home/.openclaw/openclaw.json"));
},
);
},
);
it("CONFIG_PATH defaults to ~/.openclaw/openclaw.json when env not set", async () => {
await withEnvOverride(
{ OPENCLAW_CONFIG_PATH: undefined, OPENCLAW_STATE_DIR: undefined },

View File

@@ -215,7 +215,8 @@ export function applyModelDefaults(cfg: OpenClawConfig): OpenClawConfig {
}
const defaultMaxTokens = Math.min(DEFAULT_MODEL_MAX_TOKENS, contextWindow);
const maxTokens = isPositiveNumber(raw.maxTokens) ? raw.maxTokens : defaultMaxTokens;
const rawMaxTokens = isPositiveNumber(raw.maxTokens) ? raw.maxTokens : defaultMaxTokens;
const maxTokens = Math.min(rawMaxTokens, contextWindow);
if (raw.maxTokens !== maxTokens) {
modelMutated = true;
}

View File

@@ -49,6 +49,16 @@ describe("config io paths", () => {
});
});
it("uses OPENCLAW_HOME for default config path", async () => {
await withTempHome(async (home) => {
const io = createConfigIO({
env: { OPENCLAW_HOME: path.join(home, "svc-home") } as NodeJS.ProcessEnv,
homedir: () => path.join(home, "ignored-home"),
});
expect(io.configPath).toBe(path.join(home, "svc-home", ".openclaw", "openclaw.json"));
});
});
it("honors explicit OPENCLAW_CONFIG_PATH override", async () => {
await withTempHome(async (home) => {
const customPath = await writeConfig(home, ".openclaw", 20002, "custom.json");

View File

@@ -4,6 +4,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { OpenClawConfig, ConfigFileSnapshot, LegacyConfigIssue } from "./types.js";
import { resolveRequiredHomeDir } from "../infra/home-dir.js";
import {
loadShellEnvFallback,
resolveShellEnvFallbackTimeoutMs,
@@ -183,7 +184,8 @@ function normalizeDeps(overrides: ConfigIoDeps = {}): Required<ConfigIoDeps> {
fs: overrides.fs ?? fs,
json5: overrides.json5 ?? JSON5,
env: overrides.env ?? process.env,
homedir: overrides.homedir ?? os.homedir,
homedir:
overrides.homedir ?? (() => resolveRequiredHomeDir(overrides.env ?? process.env, os.homedir)),
configPath: overrides.configPath ?? "",
logger: overrides.logger ?? console,
};

View File

@@ -80,4 +80,23 @@ describe("applyModelDefaults", () => {
expect(model?.contextWindow).toBe(DEFAULT_CONTEXT_TOKENS);
expect(model?.maxTokens).toBe(8192);
});
it("clamps maxTokens to contextWindow", () => {
const cfg = {
models: {
providers: {
myproxy: {
api: "openai-completions",
models: [{ id: "gpt-5.2", name: "GPT-5.2", contextWindow: 32768, maxTokens: 40960 }],
},
},
},
} satisfies OpenClawConfig;
const next = applyModelDefaults(cfg);
const model = next.models?.providers?.myproxy?.models?.[0];
expect(model?.contextWindow).toBe(32768);
expect(model?.maxTokens).toBe(32768);
});
});

View File

@@ -44,6 +44,29 @@ describe("state + config path candidates", () => {
expect(resolveStateDir(env, () => "/home/test")).toBe(path.resolve("/new/state"));
});
it("uses OPENCLAW_HOME for default state/config locations", () => {
const env = {
OPENCLAW_HOME: "/srv/openclaw-home",
} as NodeJS.ProcessEnv;
expect(resolveStateDir(env)).toBe(path.join("/srv/openclaw-home", ".openclaw"));
const candidates = resolveDefaultConfigCandidates(env);
expect(candidates[0]).toBe(path.join("/srv/openclaw-home", ".openclaw", "openclaw.json"));
});
it("prefers OPENCLAW_HOME over HOME for default state/config locations", () => {
const env = {
OPENCLAW_HOME: "/srv/openclaw-home",
HOME: "/home/other",
} as NodeJS.ProcessEnv;
expect(resolveStateDir(env)).toBe(path.join("/srv/openclaw-home", ".openclaw"));
const candidates = resolveDefaultConfigCandidates(env);
expect(candidates[0]).toBe(path.join("/srv/openclaw-home", ".openclaw", "openclaw.json"));
});
it("orders default config candidates in a stable order", () => {
const home = "/home/test";
const candidates = resolveDefaultConfigCandidates({} as NodeJS.ProcessEnv, () => home);

View File

@@ -2,6 +2,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { OpenClawConfig } from "./types.js";
import { expandHomePrefix, resolveRequiredHomeDir } from "../infra/home-dir.js";
/**
* Nix mode detection: When OPENCLAW_NIX_MODE=1, the gateway is running under Nix.
@@ -21,23 +22,32 @@ const NEW_STATE_DIRNAME = ".openclaw";
const CONFIG_FILENAME = "openclaw.json";
const LEGACY_CONFIG_FILENAMES = ["clawdbot.json", "moltbot.json", "moldbot.json"] as const;
function legacyStateDirs(homedir: () => string = os.homedir): string[] {
function resolveDefaultHomeDir(): string {
return resolveRequiredHomeDir(process.env, os.homedir);
}
/** Build a homedir thunk that respects OPENCLAW_HOME for the given env. */
function envHomedir(env: NodeJS.ProcessEnv): () => string {
return () => resolveRequiredHomeDir(env, os.homedir);
}
function legacyStateDirs(homedir: () => string = resolveDefaultHomeDir): string[] {
return LEGACY_STATE_DIRNAMES.map((dir) => path.join(homedir(), dir));
}
function newStateDir(homedir: () => string = os.homedir): string {
function newStateDir(homedir: () => string = resolveDefaultHomeDir): string {
return path.join(homedir(), NEW_STATE_DIRNAME);
}
export function resolveLegacyStateDir(homedir: () => string = os.homedir): string {
export function resolveLegacyStateDir(homedir: () => string = resolveDefaultHomeDir): string {
return legacyStateDirs(homedir)[0] ?? newStateDir(homedir);
}
export function resolveLegacyStateDirs(homedir: () => string = os.homedir): string[] {
export function resolveLegacyStateDirs(homedir: () => string = resolveDefaultHomeDir): string[] {
return legacyStateDirs(homedir);
}
export function resolveNewStateDir(homedir: () => string = os.homedir): string {
export function resolveNewStateDir(homedir: () => string = resolveDefaultHomeDir): string {
return newStateDir(homedir);
}
@@ -48,14 +58,15 @@ export function resolveNewStateDir(homedir: () => string = os.homedir): string {
*/
export function resolveStateDir(
env: NodeJS.ProcessEnv = process.env,
homedir: () => string = os.homedir,
homedir: () => string = envHomedir(env),
): string {
const effectiveHomedir = () => resolveRequiredHomeDir(env, homedir);
const override = env.OPENCLAW_STATE_DIR?.trim() || env.CLAWDBOT_STATE_DIR?.trim();
if (override) {
return resolveUserPath(override);
return resolveUserPath(override, env, effectiveHomedir);
}
const newDir = newStateDir(homedir);
const legacyDirs = legacyStateDirs(homedir);
const newDir = newStateDir(effectiveHomedir);
const legacyDirs = legacyStateDirs(effectiveHomedir);
const hasNew = fs.existsSync(newDir);
if (hasNew) {
return newDir;
@@ -73,13 +84,21 @@ export function resolveStateDir(
return newDir;
}
function resolveUserPath(input: string): string {
function resolveUserPath(
input: string,
env: NodeJS.ProcessEnv = process.env,
homedir: () => string = envHomedir(env),
): string {
const trimmed = input.trim();
if (!trimmed) {
return trimmed;
}
if (trimmed.startsWith("~")) {
const expanded = trimmed.replace(/^~(?=$|[\\/])/, os.homedir());
const expanded = expandHomePrefix(trimmed, {
home: resolveRequiredHomeDir(env, homedir),
env,
homedir,
});
return path.resolve(expanded);
}
return path.resolve(trimmed);
@@ -94,11 +113,11 @@ export const STATE_DIR = resolveStateDir();
*/
export function resolveCanonicalConfigPath(
env: NodeJS.ProcessEnv = process.env,
stateDir: string = resolveStateDir(env, os.homedir),
stateDir: string = resolveStateDir(env, envHomedir(env)),
): string {
const override = env.OPENCLAW_CONFIG_PATH?.trim() || env.CLAWDBOT_CONFIG_PATH?.trim();
if (override) {
return resolveUserPath(override);
return resolveUserPath(override, env, envHomedir(env));
}
return path.join(stateDir, CONFIG_FILENAME);
}
@@ -109,7 +128,7 @@ export function resolveCanonicalConfigPath(
*/
export function resolveConfigPathCandidate(
env: NodeJS.ProcessEnv = process.env,
homedir: () => string = os.homedir,
homedir: () => string = envHomedir(env),
): string {
const candidates = resolveDefaultConfigCandidates(env, homedir);
const existing = candidates.find((candidate) => {
@@ -130,12 +149,12 @@ export function resolveConfigPathCandidate(
*/
export function resolveConfigPath(
env: NodeJS.ProcessEnv = process.env,
stateDir: string = resolveStateDir(env, os.homedir),
homedir: () => string = os.homedir,
stateDir: string = resolveStateDir(env, envHomedir(env)),
homedir: () => string = envHomedir(env),
): string {
const override = env.OPENCLAW_CONFIG_PATH?.trim();
if (override) {
return resolveUserPath(override);
return resolveUserPath(override, env, homedir);
}
const stateOverride = env.OPENCLAW_STATE_DIR?.trim();
const candidates = [
@@ -170,22 +189,23 @@ export const CONFIG_PATH = resolveConfigPathCandidate();
*/
export function resolveDefaultConfigCandidates(
env: NodeJS.ProcessEnv = process.env,
homedir: () => string = os.homedir,
homedir: () => string = envHomedir(env),
): string[] {
const effectiveHomedir = () => resolveRequiredHomeDir(env, homedir);
const explicit = env.OPENCLAW_CONFIG_PATH?.trim() || env.CLAWDBOT_CONFIG_PATH?.trim();
if (explicit) {
return [resolveUserPath(explicit)];
return [resolveUserPath(explicit, env, effectiveHomedir)];
}
const candidates: string[] = [];
const openclawStateDir = env.OPENCLAW_STATE_DIR?.trim() || env.CLAWDBOT_STATE_DIR?.trim();
if (openclawStateDir) {
const resolved = resolveUserPath(openclawStateDir);
const resolved = resolveUserPath(openclawStateDir, env, effectiveHomedir);
candidates.push(path.join(resolved, CONFIG_FILENAME));
candidates.push(...LEGACY_CONFIG_FILENAMES.map((name) => path.join(resolved, name)));
}
const defaultDirs = [newStateDir(homedir), ...legacyStateDirs(homedir)];
const defaultDirs = [newStateDir(effectiveHomedir), ...legacyStateDirs(effectiveHomedir)];
for (const dir of defaultDirs) {
candidates.push(path.join(dir, CONFIG_FILENAME));
candidates.push(...LEGACY_CONFIG_FILENAMES.map((name) => path.join(dir, name)));
@@ -217,18 +237,18 @@ const OAUTH_FILENAME = "oauth.json";
*/
export function resolveOAuthDir(
env: NodeJS.ProcessEnv = process.env,
stateDir: string = resolveStateDir(env, os.homedir),
stateDir: string = resolveStateDir(env, envHomedir(env)),
): string {
const override = env.OPENCLAW_OAUTH_DIR?.trim();
if (override) {
return resolveUserPath(override);
return resolveUserPath(override, env, envHomedir(env));
}
return path.join(stateDir, "credentials");
}
export function resolveOAuthPath(
env: NodeJS.ProcessEnv = process.env,
stateDir: string = resolveStateDir(env, os.homedir),
stateDir: string = resolveStateDir(env, envHomedir(env)),
): string {
return path.join(resolveOAuthDir(env, stateDir), OAUTH_FILENAME);
}

View File

@@ -0,0 +1,22 @@
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { resolveStorePath } from "./paths.js";
describe("resolveStorePath", () => {
afterEach(() => {
vi.unstubAllEnvs();
});
it("uses OPENCLAW_HOME for tilde expansion", () => {
vi.stubEnv("OPENCLAW_HOME", "/srv/openclaw-home");
vi.stubEnv("HOME", "/home/other");
const resolved = resolveStorePath("~/.openclaw/agents/{agentId}/sessions/sessions.json", {
agentId: "research",
});
expect(resolved).toBe(
path.resolve("/srv/openclaw-home/.openclaw/agents/research/sessions/sessions.json"),
);
});
});

View File

@@ -1,13 +1,14 @@
import os from "node:os";
import path from "node:path";
import type { SessionEntry } from "./types.js";
import { expandHomePrefix, resolveRequiredHomeDir } from "../../infra/home-dir.js";
import { DEFAULT_AGENT_ID, normalizeAgentId } from "../../routing/session-key.js";
import { resolveStateDir } from "../paths.js";
function resolveAgentSessionsDir(
agentId?: string,
env: NodeJS.ProcessEnv = process.env,
homedir: () => string = os.homedir,
homedir: () => string = () => resolveRequiredHomeDir(env, os.homedir),
): string {
const root = resolveStateDir(env, homedir);
const id = normalizeAgentId(agentId ?? DEFAULT_AGENT_ID);
@@ -16,7 +17,7 @@ function resolveAgentSessionsDir(
export function resolveSessionTranscriptsDir(
env: NodeJS.ProcessEnv = process.env,
homedir: () => string = os.homedir,
homedir: () => string = () => resolveRequiredHomeDir(env, os.homedir),
): string {
return resolveAgentSessionsDir(DEFAULT_AGENT_ID, env, homedir);
}
@@ -24,7 +25,7 @@ export function resolveSessionTranscriptsDir(
export function resolveSessionTranscriptsDirForAgent(
agentId?: string,
env: NodeJS.ProcessEnv = process.env,
homedir: () => string = os.homedir,
homedir: () => string = () => resolveRequiredHomeDir(env, os.homedir),
): string {
return resolveAgentSessionsDir(agentId, env, homedir);
}
@@ -66,12 +67,24 @@ export function resolveStorePath(store?: string, opts?: { agentId?: string }) {
if (store.includes("{agentId}")) {
const expanded = store.replaceAll("{agentId}", agentId);
if (expanded.startsWith("~")) {
return path.resolve(expanded.replace(/^~(?=$|[\\/])/, os.homedir()));
return path.resolve(
expandHomePrefix(expanded, {
home: resolveRequiredHomeDir(process.env, os.homedir),
env: process.env,
homedir: os.homedir,
}),
);
}
return path.resolve(expanded);
}
if (store.startsWith("~")) {
return path.resolve(store.replace(/^~(?=$|[\\/])/, os.homedir()));
return path.resolve(
expandHomePrefix(store, {
home: resolveRequiredHomeDir(process.env, os.homedir),
env: process.env,
homedir: os.homedir,
}),
);
}
return path.resolve(store);
}

View File

@@ -0,0 +1,72 @@
import { describe, expect, it } from "vitest";
import type { SessionConfig } from "../types.base.js";
import { resolveSessionResetPolicy } from "./reset.js";
describe("resolveSessionResetPolicy", () => {
describe("backward compatibility: resetByType.dm → direct", () => {
it("uses resetByType.direct when available", () => {
const sessionCfg = {
resetByType: {
direct: { mode: "idle" as const, idleMinutes: 30 },
},
} satisfies SessionConfig;
const policy = resolveSessionResetPolicy({
sessionCfg,
resetType: "direct",
});
expect(policy.mode).toBe("idle");
expect(policy.idleMinutes).toBe(30);
});
it("falls back to resetByType.dm (legacy) when direct is missing", () => {
// Simulating legacy config with "dm" key instead of "direct"
const sessionCfg = {
resetByType: {
dm: { mode: "idle" as const, idleMinutes: 45 },
},
} as unknown as SessionConfig;
const policy = resolveSessionResetPolicy({
sessionCfg,
resetType: "direct",
});
expect(policy.mode).toBe("idle");
expect(policy.idleMinutes).toBe(45);
});
it("prefers resetByType.direct over resetByType.dm when both present", () => {
const sessionCfg = {
resetByType: {
direct: { mode: "daily" as const },
dm: { mode: "idle" as const, idleMinutes: 99 },
},
} as unknown as SessionConfig;
const policy = resolveSessionResetPolicy({
sessionCfg,
resetType: "direct",
});
expect(policy.mode).toBe("daily");
});
it("does not use dm fallback for group/thread types", () => {
const sessionCfg = {
resetByType: {
dm: { mode: "idle" as const, idleMinutes: 45 },
},
} as unknown as SessionConfig;
const groupPolicy = resolveSessionResetPolicy({
sessionCfg,
resetType: "group",
});
// Should use default mode since group has no config and dm doesn't apply
expect(groupPolicy.mode).toBe("daily");
});
});
});

View File

@@ -3,7 +3,7 @@ import { normalizeMessageChannel } from "../../utils/message-channel.js";
import { DEFAULT_IDLE_MINUTES } from "./types.js";
export type SessionResetMode = "daily" | "idle";
export type SessionResetType = "dm" | "group" | "thread";
export type SessionResetType = "direct" | "group" | "thread";
export type SessionResetPolicy = {
mode: SessionResetMode;
@@ -46,7 +46,7 @@ export function resolveSessionResetType(params: {
if (GROUP_SESSION_MARKERS.some((marker) => normalized.includes(marker))) {
return "group";
}
return "dm";
return "direct";
}
export function resolveThreadFlag(params: {
@@ -88,7 +88,13 @@ export function resolveSessionResetPolicy(params: {
}): SessionResetPolicy {
const sessionCfg = params.sessionCfg;
const baseReset = params.resetOverride ?? sessionCfg?.reset;
const typeReset = params.resetOverride ? undefined : sessionCfg?.resetByType?.[params.resetType];
// Backward compat: accept legacy "dm" key as alias for "direct"
const typeReset = params.resetOverride
? undefined
: (sessionCfg?.resetByType?.[params.resetType] ??
(params.resetType === "direct"
? (sessionCfg?.resetByType as { dm?: SessionResetConfig } | undefined)?.dm
: undefined));
const hasExplicitReset = Boolean(baseReset || sessionCfg?.resetByType);
const legacyIdleMinutes = params.resetOverride ? undefined : sessionCfg?.idleMinutes;
const mode =

View File

@@ -1,6 +1,6 @@
import type { Skill } from "@mariozechner/pi-coding-agent";
import crypto from "node:crypto";
import type { NormalizedChatType } from "../../channels/chat-type.js";
import type { ChatType } from "../../channels/chat-type.js";
import type { ChannelId } from "../../channels/plugins/types.js";
import type { DeliveryContext } from "../../utils/delivery-context.js";
import type { TtsAutoMode } from "../types.tts.js";
@@ -9,7 +9,7 @@ export type SessionScope = "per-sender" | "global";
export type SessionChannelId = ChannelId | "webchat";
export type SessionChatType = NormalizedChatType;
export type SessionChatType = ChatType;
export type SessionOrigin = {
label?: string;

View File

@@ -1,3 +1,4 @@
import type { ChatType } from "../channels/chat-type.js";
import type { AgentDefaultsConfig } from "./types.agent-defaults.js";
import type { HumanDelayConfig, IdentityConfig } from "./types.base.js";
import type { GroupChatConfig } from "./types.messages.js";
@@ -74,7 +75,7 @@ export type AgentBinding = {
match: {
channel: string;
accountId?: string;
peer?: { kind: "dm" | "group" | "channel"; id: string };
peer?: { kind: ChatType; id: string };
guildId?: string;
teamId?: string;
};

View File

@@ -1,4 +1,4 @@
import type { NormalizedChatType } from "../channels/chat-type.js";
import type { ChatType } from "../channels/chat-type.js";
export type ReplyMode = "text" | "command";
export type TypingMode = "never" | "instant" | "thinking" | "message";
@@ -50,7 +50,7 @@ export type HumanDelayConfig = {
export type SessionSendPolicyAction = "allow" | "deny";
export type SessionSendPolicyMatch = {
channel?: string;
chatType?: NormalizedChatType;
chatType?: ChatType;
keyPrefix?: string;
};
export type SessionSendPolicyRule = {
@@ -71,6 +71,8 @@ export type SessionResetConfig = {
idleMinutes?: number;
};
export type SessionResetByTypeConfig = {
direct?: SessionResetConfig;
/** @deprecated Use `direct` instead. Kept for backward compatibility. */
dm?: SessionResetConfig;
group?: SessionResetConfig;
thread?: SessionResetConfig;

View File

@@ -1,9 +1,9 @@
import type { NormalizedChatType } from "../channels/chat-type.js";
import type { ChatType } from "../channels/chat-type.js";
import type { AgentElevatedAllowFromConfig, SessionSendPolicyAction } from "./types.base.js";
export type MediaUnderstandingScopeMatch = {
channel?: string;
chatType?: NormalizedChatType;
chatType?: ChatType;
keyPrefix?: string;
};

View File

@@ -22,7 +22,13 @@ export const BindingsSchema = z
accountId: z.string().optional(),
peer: z
.object({
kind: z.union([z.literal("dm"), z.literal("group"), z.literal("channel")]),
kind: z.union([
z.literal("direct"),
z.literal("group"),
z.literal("channel"),
/** @deprecated Use `direct` instead. Kept for backward compatibility. */
z.literal("dm"),
]),
id: z.string(),
})
.strict()

View File

@@ -378,7 +378,13 @@ export const MediaUnderstandingScopeSchema = z
.object({
channel: z.string().optional(),
chatType: z
.union([z.literal("direct"), z.literal("group"), z.literal("channel")])
.union([
z.literal("direct"),
z.literal("group"),
z.literal("channel"),
/** @deprecated Use `direct` instead. Kept for backward compatibility. */
z.literal("dm"),
])
.optional(),
keyPrefix: z.string().optional(),
})

View File

@@ -27,7 +27,13 @@ export const SessionSendPolicySchema = z
.object({
channel: z.string().optional(),
chatType: z
.union([z.literal("direct"), z.literal("group"), z.literal("channel")])
.union([
z.literal("direct"),
z.literal("group"),
z.literal("channel"),
/** @deprecated Use `direct` instead. Kept for backward compatibility. */
z.literal("dm"),
])
.optional(),
keyPrefix: z.string().optional(),
})
@@ -57,6 +63,8 @@ export const SessionSchema = z
reset: SessionResetConfigSchema.optional(),
resetByType: z
.object({
direct: SessionResetConfigSchema.optional(),
/** @deprecated Use `direct` instead. Kept for backward compatibility. */
dm: SessionResetConfigSchema.optional(),
group: SessionResetConfigSchema.optional(),
thread: SessionResetConfigSchema.optional(),

View File

@@ -1,8 +1,8 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { loadCronStore } from "./store.js";
import { afterEach, describe, expect, it, vi } from "vitest";
import { loadCronStore, resolveCronStorePath } from "./store.js";
async function makeStorePath() {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-cron-store-"));
@@ -15,6 +15,20 @@ async function makeStorePath() {
};
}
describe("resolveCronStorePath", () => {
afterEach(() => {
vi.unstubAllEnvs();
});
it("uses OPENCLAW_HOME for tilde expansion", () => {
vi.stubEnv("OPENCLAW_HOME", "/srv/openclaw-home");
vi.stubEnv("HOME", "/home/other");
const result = resolveCronStorePath("~/cron/jobs.json");
expect(result).toBe(path.resolve("/srv/openclaw-home", "cron", "jobs.json"));
});
});
describe("cron store", () => {
it("returns empty store when file does not exist", async () => {
const store = await makeStorePath();

View File

@@ -1,8 +1,8 @@
import JSON5 from "json5";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { CronStoreFile } from "./types.js";
import { expandHomePrefix } from "../infra/home-dir.js";
import { CONFIG_DIR } from "../utils.js";
export const DEFAULT_CRON_DIR = path.join(CONFIG_DIR, "cron");
@@ -12,7 +12,7 @@ export function resolveCronStorePath(storePath?: string) {
if (storePath?.trim()) {
const raw = storePath.trim();
if (raw.startsWith("~")) {
return path.resolve(raw.replace("~", os.homedir()));
return path.resolve(expandHomePrefix(raw));
}
return path.resolve(raw);
}

View File

@@ -87,12 +87,12 @@ describe("discord processDiscordMessage inbound contract", () => {
guildInfo: null,
guildSlug: "",
channelConfig: null,
baseSessionKey: "agent:main:discord:dm:u1",
baseSessionKey: "agent:main:discord:direct:u1",
route: {
agentId: "main",
channel: "discord",
accountId: "default",
sessionKey: "agent:main:discord:dm:u1",
sessionKey: "agent:main:discord:direct:u1",
mainSessionKey: "agent:main:main",
// oxlint-disable-next-line typescript/no-explicit-any
} as any,

View File

@@ -224,7 +224,7 @@ export async function preflightDiscordMessage(
accountId: params.accountId,
guildId: params.data.guild_id ?? undefined,
peer: {
kind: isDirectMessage ? "dm" : isGroupDm ? "group" : "channel",
kind: isDirectMessage ? "direct" : isGroupDm ? "group" : "channel",
id: isDirectMessage ? author.id : message.channelId,
},
// Pass parent peer for thread binding inheritance

View File

@@ -736,7 +736,7 @@ async function dispatchDiscordCommandInteraction(params: {
accountId,
guildId: interaction.guild?.id ?? undefined,
peer: {
kind: isDirectMessage ? "dm" : isGroupDm ? "group" : "channel",
kind: isDirectMessage ? "direct" : isGroupDm ? "group" : "channel",
id: isDirectMessage ? user.id : channelId,
},
parentPeer: threadParentId ? { kind: "channel", id: threadParentId } : undefined,

View File

@@ -1,12 +1,13 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import {
readFirstUserMessageFromTranscript,
readLastMessagePreviewFromTranscript,
readSessionMessages,
readSessionPreviewItemsFromTranscript,
resolveSessionTranscriptCandidates,
} from "./session-utils.fs.js";
describe("readFirstUserMessageFromTranscript", () => {
@@ -489,3 +490,18 @@ describe("readSessionPreviewItemsFromTranscript", () => {
expect(result[0]?.text.endsWith("...")).toBe(true);
});
});
describe("resolveSessionTranscriptCandidates", () => {
afterEach(() => {
vi.unstubAllEnvs();
});
test("fallback candidate uses OPENCLAW_HOME instead of os.homedir()", () => {
vi.stubEnv("OPENCLAW_HOME", "/srv/openclaw-home");
vi.stubEnv("HOME", "/home/other");
const candidates = resolveSessionTranscriptCandidates("sess-1", undefined);
const fallback = candidates[candidates.length - 1];
expect(fallback).toBe(path.join("/srv/openclaw-home", ".openclaw", "sessions", "sess-1.jsonl"));
});
});

View File

@@ -3,6 +3,7 @@ import os from "node:os";
import path from "node:path";
import type { SessionPreviewItem } from "./session-utils.types.js";
import { resolveSessionTranscriptPath } from "../config/sessions.js";
import { resolveRequiredHomeDir } from "../infra/home-dir.js";
import { extractToolCallNames, hasToolCall } from "../utils/transcript-tools.js";
import { stripEnvelope } from "./chat-sanitize.js";
@@ -70,7 +71,7 @@ export function resolveSessionTranscriptCandidates(
if (agentId) {
candidates.push(resolveSessionTranscriptPath(sessionId, agentId));
}
const home = os.homedir();
const home = resolveRequiredHomeDir(process.env, os.homedir);
candidates.push(path.join(home, ".openclaw", "sessions", `${sessionId}.jsonl`));
return candidates;
}

View File

@@ -1,4 +1,4 @@
import type { NormalizedChatType } from "../channels/chat-type.js";
import type { ChatType } from "../channels/chat-type.js";
import type { SessionEntry } from "../config/sessions.js";
import type { DeliveryContext } from "../utils/delivery-context.js";
@@ -19,7 +19,7 @@ export type GatewaySessionRow = {
subject?: string;
groupChannel?: string;
space?: string;
chatType?: NormalizedChatType;
chatType?: ChatType;
origin?: SessionEntry["origin"];
updatedAt: number | null;
sessionId?: string;

View File

@@ -387,7 +387,7 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
channel: "imessage",
accountId: accountInfo.accountId,
peer: {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: isGroup ? String(chatId ?? "unknown") : normalizeIMessageHandle(sender),
},
});

View File

@@ -0,0 +1,64 @@
import { describe, expect, it } from "vitest";
import { expandHomePrefix, resolveEffectiveHomeDir, resolveRequiredHomeDir } from "./home-dir.js";
describe("resolveEffectiveHomeDir", () => {
it("prefers OPENCLAW_HOME over HOME and USERPROFILE", () => {
const env = {
OPENCLAW_HOME: "/srv/openclaw-home",
HOME: "/home/other",
USERPROFILE: "C:/Users/other",
} as NodeJS.ProcessEnv;
expect(resolveEffectiveHomeDir(env, () => "/fallback")).toBe("/srv/openclaw-home");
});
it("falls back to HOME then USERPROFILE then homedir", () => {
expect(resolveEffectiveHomeDir({ HOME: "/home/alice" } as NodeJS.ProcessEnv)).toBe(
"/home/alice",
);
expect(resolveEffectiveHomeDir({ USERPROFILE: "C:/Users/alice" } as NodeJS.ProcessEnv)).toBe(
"C:/Users/alice",
);
expect(resolveEffectiveHomeDir({} as NodeJS.ProcessEnv, () => "/fallback")).toBe("/fallback");
});
it("expands OPENCLAW_HOME when set to ~", () => {
const env = {
OPENCLAW_HOME: "~/svc",
HOME: "/home/alice",
} as NodeJS.ProcessEnv;
expect(resolveEffectiveHomeDir(env)).toBe("/home/alice/svc");
});
});
describe("resolveRequiredHomeDir", () => {
it("returns cwd when no home source is available", () => {
expect(
resolveRequiredHomeDir({} as NodeJS.ProcessEnv, () => {
throw new Error("no home");
}),
).toBe(process.cwd());
});
it("returns cwd when OPENCLAW_HOME is tilde-only and no fallback home exists", () => {
expect(
resolveRequiredHomeDir({ OPENCLAW_HOME: "~" } as NodeJS.ProcessEnv, () => {
throw new Error("no home");
}),
).toBe(process.cwd());
});
});
describe("expandHomePrefix", () => {
it("expands tilde using effective home", () => {
const value = expandHomePrefix("~/x", {
env: { OPENCLAW_HOME: "/srv/openclaw-home" } as NodeJS.ProcessEnv,
});
expect(value).toBe("/srv/openclaw-home/x");
});
it("keeps non-tilde values unchanged", () => {
expect(expandHomePrefix("/tmp/x")).toBe("/tmp/x");
});
});

71
src/infra/home-dir.ts Normal file
View File

@@ -0,0 +1,71 @@
import os from "node:os";
function normalize(value: string | undefined): string | undefined {
const trimmed = value?.trim();
return trimmed ? trimmed : undefined;
}
export function resolveEffectiveHomeDir(
env: NodeJS.ProcessEnv = process.env,
homedir: () => string = os.homedir,
): string | undefined {
const explicitHome = normalize(env.OPENCLAW_HOME);
if (explicitHome) {
if (explicitHome === "~" || explicitHome.startsWith("~/") || explicitHome.startsWith("~\\")) {
const fallbackHome =
normalize(env.HOME) ?? normalize(env.USERPROFILE) ?? normalizeSafe(homedir);
if (fallbackHome) {
return explicitHome.replace(/^~(?=$|[\\/])/, fallbackHome);
}
return undefined;
}
return explicitHome;
}
const envHome = normalize(env.HOME);
if (envHome) {
return envHome;
}
const userProfile = normalize(env.USERPROFILE);
if (userProfile) {
return userProfile;
}
return normalizeSafe(homedir);
}
function normalizeSafe(homedir: () => string): string | undefined {
try {
return normalize(homedir());
} catch {
return undefined;
}
}
export function resolveRequiredHomeDir(
env: NodeJS.ProcessEnv = process.env,
homedir: () => string = os.homedir,
): string {
return resolveEffectiveHomeDir(env, homedir) ?? process.cwd();
}
export function expandHomePrefix(
input: string,
opts?: {
home?: string;
env?: NodeJS.ProcessEnv;
homedir?: () => string;
},
): string {
if (!input.startsWith("~")) {
return input;
}
const home =
normalize(opts?.home) ??
resolveEffectiveHomeDir(opts?.env ?? process.env, opts?.homedir ?? os.homedir);
if (!home) {
return input;
}
return input.replace(/^~(?=$|[\\/])/, home);
}

View File

@@ -43,7 +43,7 @@ describe("resolveOutboundSessionRoute", () => {
target: "@alice",
});
expect(route?.sessionKey).toBe("agent:main:telegram:dm:@alice");
expect(route?.sessionKey).toBe("agent:main:telegram:direct:@alice");
expect(route?.chatType).toBe("direct");
});
@@ -64,7 +64,7 @@ describe("resolveOutboundSessionRoute", () => {
target: "user:123",
});
expect(route?.sessionKey).toBe("agent:main:dm:alice");
expect(route?.sessionKey).toBe("agent:main:direct:alice");
});
it("strips chat_* prefixes for BlueBubbles group session keys", async () => {
@@ -88,7 +88,7 @@ describe("resolveOutboundSessionRoute", () => {
target: "123456",
});
expect(route?.sessionKey).toBe("agent:main:zalouser:dm:123456");
expect(route?.sessionKey).toBe("agent:main:zalouser:direct:123456");
expect(route?.chatType).toBe("direct");
});

View File

@@ -1,4 +1,5 @@
import type { MsgContext } from "../../auto-reply/templating.js";
import type { ChatType } from "../../channels/chat-type.js";
import type { ChannelId } from "../../channels/plugins/types.js";
import type { OpenClawConfig } from "../../config/config.js";
import type { ResolvedMessagingTarget } from "./target-resolver.js";
@@ -6,11 +7,7 @@ import { getChannelPlugin } from "../../channels/plugins/index.js";
import { recordSessionMetaFromInbound, resolveStorePath } from "../../config/sessions.js";
import { parseDiscordTarget } from "../../discord/targets.js";
import { parseIMessageTarget, normalizeIMessageHandle } from "../../imessage/targets.js";
import {
buildAgentSessionKey,
type RoutePeer,
type RoutePeerKind,
} from "../../routing/resolve-route.js";
import { buildAgentSessionKey, type RoutePeer } from "../../routing/resolve-route.js";
import { resolveThreadSessionKeys } from "../../routing/session-key.js";
import {
resolveSignalPeerId,
@@ -94,10 +91,10 @@ function stripKindPrefix(raw: string): string {
function inferPeerKind(params: {
channel: ChannelId;
resolvedTarget?: ResolvedMessagingTarget;
}): RoutePeerKind {
}): ChatType {
const resolvedKind = params.resolvedTarget?.kind;
if (resolvedKind === "user") {
return "dm";
return "direct";
}
if (resolvedKind === "channel") {
return "channel";
@@ -112,7 +109,7 @@ function inferPeerKind(params: {
}
return "group";
}
return "dm";
return "direct";
}
function buildBaseSessionKey(params: {
@@ -205,7 +202,7 @@ async function resolveSlackSession(
return null;
}
const isDm = parsed.kind === "user";
let peerKind: RoutePeerKind = isDm ? "dm" : "channel";
let peerKind: ChatType = isDm ? "direct" : "channel";
if (!isDm && /^G/i.test(parsed.id)) {
// Slack mpim/group DMs share the G-prefix; detect to align session keys with inbound.
const channelType = await resolveSlackChannelType({
@@ -217,7 +214,7 @@ async function resolveSlackSession(
peerKind = "group";
}
if (channelType === "dm") {
peerKind = "dm";
peerKind = "direct";
}
}
const peer: RoutePeer = {
@@ -240,14 +237,14 @@ async function resolveSlackSession(
sessionKey: threadKeys.sessionKey,
baseSessionKey,
peer,
chatType: peerKind === "dm" ? "direct" : "channel",
chatType: peerKind === "direct" ? "direct" : "channel",
from:
peerKind === "dm"
peerKind === "direct"
? `slack:${parsed.id}`
: peerKind === "group"
? `slack:group:${parsed.id}`
: `slack:channel:${parsed.id}`,
to: peerKind === "dm" ? `user:${parsed.id}` : `channel:${parsed.id}`,
to: peerKind === "direct" ? `user:${parsed.id}` : `channel:${parsed.id}`,
threadId,
};
}
@@ -261,7 +258,7 @@ function resolveDiscordSession(
}
const isDm = parsed.kind === "user";
const peer: RoutePeer = {
kind: isDm ? "dm" : "channel",
kind: isDm ? "direct" : "channel",
id: parsed.id,
};
const baseSessionKey = buildBaseSessionKey({
@@ -312,7 +309,7 @@ function resolveTelegramSession(
params.resolvedTarget.kind !== "user");
const peerId = isGroup ? buildTelegramGroupPeerId(chatId, resolvedThreadId) : chatId;
const peer: RoutePeer = {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: peerId,
};
const baseSessionKey = buildBaseSessionKey({
@@ -342,7 +339,7 @@ function resolveWhatsAppSession(
}
const isGroup = isWhatsAppGroupJid(normalized);
const peer: RoutePeer = {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: normalized,
};
const baseSessionKey = buildBaseSessionKey({
@@ -409,7 +406,7 @@ function resolveSignalSession(
});
const peerId = sender ? resolveSignalPeerId(sender) : recipient;
const displayRecipient = sender ? resolveSignalRecipient(sender) : recipient;
const peer: RoutePeer = { kind: "dm", id: peerId };
const peer: RoutePeer = { kind: "direct", id: peerId };
const baseSessionKey = buildBaseSessionKey({
cfg: params.cfg,
agentId: params.agentId,
@@ -436,7 +433,7 @@ function resolveIMessageSession(
if (!handle) {
return null;
}
const peer: RoutePeer = { kind: "dm", id: handle };
const peer: RoutePeer = { kind: "direct", id: handle };
const baseSessionKey = buildBaseSessionKey({
cfg: params.cfg,
agentId: params.agentId,
@@ -497,7 +494,7 @@ function resolveMatrixSession(
if (!rawId) {
return null;
}
const peer: RoutePeer = { kind: isUser ? "dm" : "channel", id: rawId };
const peer: RoutePeer = { kind: isUser ? "direct" : "channel", id: rawId };
const baseSessionKey = buildBaseSessionKey({
cfg: params.cfg,
agentId: params.agentId,
@@ -533,7 +530,7 @@ function resolveMSTeamsSession(
const conversationId = rawId.split(";")[0] ?? rawId;
const isChannel = !isUser && /@thread\.tacv2/i.test(conversationId);
const peer: RoutePeer = {
kind: isUser ? "dm" : isChannel ? "channel" : "group",
kind: isUser ? "direct" : isChannel ? "channel" : "group",
id: conversationId,
};
const baseSessionKey = buildBaseSessionKey({
@@ -574,7 +571,7 @@ function resolveMattermostSession(
if (!rawId) {
return null;
}
const peer: RoutePeer = { kind: isUser ? "dm" : "channel", id: rawId };
const peer: RoutePeer = { kind: isUser ? "direct" : "channel", id: rawId };
const baseSessionKey = buildBaseSessionKey({
cfg: params.cfg,
agentId: params.agentId,
@@ -619,7 +616,7 @@ function resolveBlueBubblesSession(
return null;
}
const peer: RoutePeer = {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: peerId,
};
const baseSessionKey = buildBaseSessionKey({
@@ -680,7 +677,7 @@ function resolveZaloSession(
}
const isGroup = trimmed.toLowerCase().startsWith("group:");
const peerId = stripKindPrefix(trimmed);
const peer: RoutePeer = { kind: isGroup ? "group" : "dm", id: peerId };
const peer: RoutePeer = { kind: isGroup ? "group" : "direct", id: peerId };
const baseSessionKey = buildBaseSessionKey({
cfg: params.cfg,
agentId: params.agentId,
@@ -710,7 +707,7 @@ function resolveZalouserSession(
const isGroup = trimmed.toLowerCase().startsWith("group:");
const peerId = stripKindPrefix(trimmed);
// Keep DM vs group aligned with inbound sessions for Zalo Personal.
const peer: RoutePeer = { kind: isGroup ? "group" : "dm", id: peerId };
const peer: RoutePeer = { kind: isGroup ? "group" : "direct", id: peerId };
const baseSessionKey = buildBaseSessionKey({
cfg: params.cfg,
agentId: params.agentId,
@@ -735,7 +732,7 @@ function resolveNostrSession(
if (!trimmed) {
return null;
}
const peer: RoutePeer = { kind: "dm", id: trimmed };
const peer: RoutePeer = { kind: "direct", id: trimmed };
const baseSessionKey = buildBaseSessionKey({
cfg: params.cfg,
agentId: params.agentId,
@@ -798,7 +795,7 @@ function resolveTlonSession(
peerId = normalizeTlonShip(trimmed);
}
const peer: RoutePeer = { kind: isGroup ? "group" : "dm", id: peerId };
const peer: RoutePeer = { kind: isGroup ? "group" : "direct", id: peerId };
const baseSessionKey = buildBaseSessionKey({
cfg: params.cfg,
agentId: params.agentId,
@@ -851,7 +848,7 @@ function resolveFeishuSession(
}
const peer: RoutePeer = {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: trimmed,
};
const baseSessionKey = buildBaseSessionKey({
@@ -893,10 +890,12 @@ function resolveFallbackSession(
channel: params.channel,
peer,
});
const chatType = peerKind === "dm" ? "direct" : peerKind === "channel" ? "channel" : "group";
const chatType = peerKind === "direct" ? "direct" : peerKind === "channel" ? "channel" : "group";
const from =
peerKind === "dm" ? `${params.channel}:${peerId}` : `${params.channel}:${peerKind}:${peerId}`;
const toPrefix = peerKind === "dm" ? "user" : "channel";
peerKind === "direct"
? `${params.channel}:${peerId}`
: `${params.channel}:${peerKind}:${peerId}`;
const toPrefix = peerKind === "direct" ? "user" : "channel";
return {
sessionKey: baseSessionKey,
baseSessionKey,

View File

@@ -154,7 +154,7 @@ export async function buildLineMessageContext(params: BuildLineMessageContextPar
channel: "line",
accountId: account.accountId,
peer: {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: peerId,
},
});
@@ -328,7 +328,7 @@ export async function buildLinePostbackContext(params: {
channel: "line",
accountId: account.accountId,
peer: {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: peerId,
},
});

View File

@@ -178,7 +178,7 @@ describe("applyMediaUnderstanding", () => {
Body: "<media:audio>",
MediaUrl: "https://example.com/note.ogg",
MediaType: "audio/ogg",
ChatType: "dm",
ChatType: "direct",
};
const cfg: OpenClawConfig = {
tools: {

View File

@@ -714,7 +714,7 @@ export class QmdMemoryManager implements MemorySearchManager {
const parts = normalized.split(":").filter(Boolean);
if (
parts.length >= 2 &&
(parts[1] === "group" || parts[1] === "channel" || parts[1] === "dm")
(parts[1] === "group" || parts[1] === "channel" || parts[1] === "direct" || parts[1] === "dm")
) {
return parts[0]?.toLowerCase();
}

View File

@@ -6,6 +6,7 @@ import lockfile from "proper-lockfile";
import type { ChannelId, ChannelPairingAdapter } from "../channels/plugins/types.js";
import { getPairingAdapter } from "../channels/plugins/pairing.js";
import { resolveOAuthDir, resolveStateDir } from "../config/paths.js";
import { resolveRequiredHomeDir } from "../infra/home-dir.js";
const PAIRING_CODE_LENGTH = 8;
const PAIRING_CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
@@ -43,7 +44,7 @@ type AllowFromStore = {
};
function resolveCredentialsDir(env: NodeJS.ProcessEnv = process.env): string {
const stateDir = resolveStateDir(env, os.homedir);
const stateDir = resolveStateDir(env, () => resolveRequiredHomeDir(env, os.homedir));
return resolveOAuthDir(env, stateDir);
}

View File

@@ -118,6 +118,9 @@ export { ToolPolicySchema } from "../config/zod-schema.agent-runtime.js";
export type { RuntimeEnv } from "../runtime.js";
export type { WizardPrompter } from "../wizard/prompts.js";
export { DEFAULT_ACCOUNT_ID, normalizeAccountId } from "../routing/session-key.js";
export type { ChatType } from "../channels/chat-type.js";
/** @deprecated Use ChatType instead */
export type { RoutePeerKind } from "../routing/resolve-route.js";
export { resolveAckReaction } from "../agents/identity.js";
export type { ReplyPayload } from "../auto-reply/types.js";
export type { ChunkMode } from "../auto-reply/chunk.js";

View File

@@ -9,7 +9,7 @@ describe("resolveAgentRoute", () => {
cfg,
channel: "whatsapp",
accountId: null,
peer: { kind: "dm", id: "+15551234567" },
peer: { kind: "direct", id: "+15551234567" },
});
expect(route.agentId).toBe("main");
expect(route.accountId).toBe("default");
@@ -25,9 +25,9 @@ describe("resolveAgentRoute", () => {
cfg,
channel: "whatsapp",
accountId: null,
peer: { kind: "dm", id: "+15551234567" },
peer: { kind: "direct", id: "+15551234567" },
});
expect(route.sessionKey).toBe("agent:main:dm:+15551234567");
expect(route.sessionKey).toBe("agent:main:direct:+15551234567");
});
test("dmScope=per-channel-peer isolates DM sessions per channel and sender", () => {
@@ -38,9 +38,9 @@ describe("resolveAgentRoute", () => {
cfg,
channel: "whatsapp",
accountId: null,
peer: { kind: "dm", id: "+15551234567" },
peer: { kind: "direct", id: "+15551234567" },
});
expect(route.sessionKey).toBe("agent:main:whatsapp:dm:+15551234567");
expect(route.sessionKey).toBe("agent:main:whatsapp:direct:+15551234567");
});
test("identityLinks collapses per-peer DM sessions across providers", () => {
@@ -56,9 +56,9 @@ describe("resolveAgentRoute", () => {
cfg,
channel: "telegram",
accountId: null,
peer: { kind: "dm", id: "111111111" },
peer: { kind: "direct", id: "111111111" },
});
expect(route.sessionKey).toBe("agent:main:dm:alice");
expect(route.sessionKey).toBe("agent:main:direct:alice");
});
test("identityLinks applies to per-channel-peer DM sessions", () => {
@@ -74,9 +74,9 @@ describe("resolveAgentRoute", () => {
cfg,
channel: "discord",
accountId: null,
peer: { kind: "dm", id: "222222222222222222" },
peer: { kind: "direct", id: "222222222222222222" },
});
expect(route.sessionKey).toBe("agent:main:discord:dm:alice");
expect(route.sessionKey).toBe("agent:main:discord:direct:alice");
});
test("peer binding wins over account binding", () => {
@@ -87,7 +87,7 @@ describe("resolveAgentRoute", () => {
match: {
channel: "whatsapp",
accountId: "biz",
peer: { kind: "dm", id: "+1000" },
peer: { kind: "direct", id: "+1000" },
},
},
{
@@ -100,7 +100,7 @@ describe("resolveAgentRoute", () => {
cfg,
channel: "whatsapp",
accountId: "biz",
peer: { kind: "dm", id: "+1000" },
peer: { kind: "direct", id: "+1000" },
});
expect(route.agentId).toBe("a");
expect(route.sessionKey).toBe("agent:a:main");
@@ -177,7 +177,7 @@ describe("resolveAgentRoute", () => {
cfg,
channel: "whatsapp",
accountId: undefined,
peer: { kind: "dm", id: "+1000" },
peer: { kind: "direct", id: "+1000" },
});
expect(defaultRoute.agentId).toBe("defaultacct");
expect(defaultRoute.matchedBy).toBe("binding.account");
@@ -186,7 +186,7 @@ describe("resolveAgentRoute", () => {
cfg,
channel: "whatsapp",
accountId: "biz",
peer: { kind: "dm", id: "+1000" },
peer: { kind: "direct", id: "+1000" },
});
expect(otherRoute.agentId).toBe("main");
});
@@ -204,7 +204,7 @@ describe("resolveAgentRoute", () => {
cfg,
channel: "whatsapp",
accountId: "biz",
peer: { kind: "dm", id: "+1000" },
peer: { kind: "direct", id: "+1000" },
});
expect(route.agentId).toBe("any");
expect(route.matchedBy).toBe("binding.channel");
@@ -220,7 +220,7 @@ describe("resolveAgentRoute", () => {
cfg,
channel: "whatsapp",
accountId: "biz",
peer: { kind: "dm", id: "+1000" },
peer: { kind: "direct", id: "+1000" },
});
expect(route.agentId).toBe("home");
expect(route.sessionKey).toBe("agent:home:main");
@@ -235,9 +235,9 @@ test("dmScope=per-account-channel-peer isolates DM sessions per account, channel
cfg,
channel: "telegram",
accountId: "tasks",
peer: { kind: "dm", id: "7550356539" },
peer: { kind: "direct", id: "7550356539" },
});
expect(route.sessionKey).toBe("agent:main:telegram:tasks:dm:7550356539");
expect(route.sessionKey).toBe("agent:main:telegram:tasks:direct:7550356539");
});
test("dmScope=per-account-channel-peer uses default accountId when not provided", () => {
@@ -248,9 +248,9 @@ test("dmScope=per-account-channel-peer uses default accountId when not provided"
cfg,
channel: "telegram",
accountId: null,
peer: { kind: "dm", id: "7550356539" },
peer: { kind: "direct", id: "7550356539" },
});
expect(route.sessionKey).toBe("agent:main:telegram:default:dm:7550356539");
expect(route.sessionKey).toBe("agent:main:telegram:default:direct:7550356539");
});
describe("parentPeer binding inheritance (thread support)", () => {
@@ -409,3 +409,29 @@ describe("parentPeer binding inheritance (thread support)", () => {
expect(route.matchedBy).toBe("default");
});
});
describe("backward compatibility: peer.kind dm → direct", () => {
test("legacy dm in config matches runtime direct peer", () => {
const cfg: OpenClawConfig = {
bindings: [
{
agentId: "alex",
match: {
channel: "whatsapp",
// Legacy config uses "dm" instead of "direct"
peer: { kind: "dm", id: "+15551234567" },
},
},
],
};
const route = resolveAgentRoute({
cfg,
channel: "whatsapp",
accountId: null,
// Runtime uses canonical "direct"
peer: { kind: "direct", id: "+15551234567" },
});
expect(route.agentId).toBe("alex");
expect(route.matchedBy).toBe("binding.peer");
});
});

View File

@@ -1,5 +1,7 @@
import type { ChatType } from "../channels/chat-type.js";
import type { OpenClawConfig } from "../config/config.js";
import { resolveDefaultAgentId } from "../agents/agent-scope.js";
import { normalizeChatType } from "../channels/chat-type.js";
import { listBindings } from "./bindings.js";
import {
buildAgentMainSessionKey,
@@ -10,10 +12,11 @@ import {
sanitizeAgentId,
} from "./session-key.js";
export type RoutePeerKind = "dm" | "group" | "channel";
/** @deprecated Use ChatType from channels/chat-type.js */
export type RoutePeerKind = ChatType;
export type RoutePeer = {
kind: RoutePeerKind;
kind: ChatType;
id: string;
};
@@ -89,7 +92,7 @@ export function buildAgentSessionKey(params: {
mainKey: DEFAULT_MAIN_KEY,
channel,
accountId: params.accountId,
peerKind: peer?.kind ?? "dm",
peerKind: peer?.kind ?? "direct",
peerId: peer ? normalizeId(peer.id) || "unknown" : null,
dmScope: params.dmScope,
identityLinks: params.identityLinks,
@@ -137,7 +140,8 @@ function matchesPeer(
if (!m) {
return false;
}
const kind = normalizeToken(m.kind);
// Backward compat: normalize "dm" to "direct" in config match rules
const kind = normalizeChatType(m.kind);
const id = normalizeId(m.id);
if (!kind || !id) {
return false;

View File

@@ -23,3 +23,19 @@ describe("classifySessionKeyShape", () => {
expect(classifySessionKeyShape("subagent:worker")).toBe("legacy_or_alias");
});
});
describe("session key backward compatibility", () => {
it("classifies legacy :dm: session keys as valid agent keys", () => {
// Legacy session keys use :dm: instead of :direct:
// Both should be recognized as valid agent keys
expect(classifySessionKeyShape("agent:main:telegram:dm:123456")).toBe("agent");
expect(classifySessionKeyShape("agent:main:whatsapp:dm:+15551234567")).toBe("agent");
expect(classifySessionKeyShape("agent:main:discord:dm:user123")).toBe("agent");
});
it("classifies new :direct: session keys as valid agent keys", () => {
expect(classifySessionKeyShape("agent:main:telegram:direct:123456")).toBe("agent");
expect(classifySessionKeyShape("agent:main:whatsapp:direct:+15551234567")).toBe("agent");
expect(classifySessionKeyShape("agent:main:discord:direct:user123")).toBe("agent");
});
});

View File

@@ -1,3 +1,4 @@
import type { ChatType } from "../channels/chat-type.js";
import { parseAgentSessionKey, type ParsedAgentSessionKey } from "../sessions/session-key-utils.js";
export {
@@ -140,14 +141,14 @@ export function buildAgentPeerSessionKey(params: {
mainKey?: string | undefined;
channel: string;
accountId?: string | null;
peerKind?: "dm" | "group" | "channel" | null;
peerKind?: ChatType | null;
peerId?: string | null;
identityLinks?: Record<string, string[]>;
/** DM session scope. */
dmScope?: "main" | "per-peer" | "per-channel-peer" | "per-account-channel-peer";
}): string {
const peerKind = params.peerKind ?? "dm";
if (peerKind === "dm") {
const peerKind = params.peerKind ?? "direct";
if (peerKind === "direct") {
const dmScope = params.dmScope ?? "main";
let peerId = (params.peerId ?? "").trim();
const linkedPeerId =
@@ -165,14 +166,14 @@ export function buildAgentPeerSessionKey(params: {
if (dmScope === "per-account-channel-peer" && peerId) {
const channel = (params.channel ?? "").trim().toLowerCase() || "unknown";
const accountId = normalizeAccountId(params.accountId);
return `agent:${normalizeAgentId(params.agentId)}:${channel}:${accountId}:dm:${peerId}`;
return `agent:${normalizeAgentId(params.agentId)}:${channel}:${accountId}:direct:${peerId}`;
}
if (dmScope === "per-channel-peer" && peerId) {
const channel = (params.channel ?? "").trim().toLowerCase() || "unknown";
return `agent:${normalizeAgentId(params.agentId)}:${channel}:dm:${peerId}`;
return `agent:${normalizeAgentId(params.agentId)}:${channel}:direct:${peerId}`;
}
if (dmScope === "per-peer" && peerId) {
return `agent:${normalizeAgentId(params.agentId)}:dm:${peerId}`;
return `agent:${normalizeAgentId(params.agentId)}:direct:${peerId}`;
}
return buildAgentMainSessionKey({
agentId: params.agentId,

View File

@@ -414,7 +414,7 @@ describe("monitorSignalProvider tool results", () => {
cfg: config as OpenClawConfig,
channel: "signal",
accountId: "default",
peer: { kind: "dm", id: normalizeE164("+15550001111") },
peer: { kind: "direct", id: normalizeE164("+15550001111") },
});
const events = peekSystemEvents(route.sessionKey);
expect(events.some((text) => text.includes("Signal reaction added"))).toBe(true);
@@ -470,7 +470,7 @@ describe("monitorSignalProvider tool results", () => {
cfg: config as OpenClawConfig,
channel: "signal",
accountId: "default",
peer: { kind: "dm", id: normalizeE164("+15550001111") },
peer: { kind: "direct", id: normalizeE164("+15550001111") },
});
const events = peekSystemEvents(route.sessionKey);
expect(events.some((text) => text.includes("Signal reaction added"))).toBe(true);

View File

@@ -77,7 +77,7 @@ export function createSignalEventHandler(deps: SignalEventHandlerDeps) {
channel: "signal",
accountId: deps.accountId,
peer: {
kind: entry.isGroup ? "group" : "dm",
kind: entry.isGroup ? "group" : "direct",
id: entry.isGroup ? (entry.groupId ?? "unknown") : entry.senderPeerId,
},
});
@@ -370,7 +370,7 @@ export function createSignalEventHandler(deps: SignalEventHandlerDeps) {
channel: "signal",
accountId: deps.accountId,
peer: {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: isGroup ? (groupId ?? "unknown") : senderPeerId,
},
});

View File

@@ -120,7 +120,7 @@ describe("monitorSlackProvider tool results", () => {
bindings: [
{
agentId: "rich",
match: { channel: "slack", peer: { kind: "dm", id: "U1" } },
match: { channel: "slack", peer: { kind: "direct", id: "U1" } },
},
],
messages: {

View File

@@ -188,7 +188,7 @@ export async function prepareSlackMessage(params: {
accountId: account.accountId,
teamId: ctx.teamId || undefined,
peer: {
kind: isDirectMessage ? "dm" : isRoom ? "channel" : "group",
kind: isDirectMessage ? "direct" : isRoom ? "channel" : "group",
id: isDirectMessage ? (message.user ?? "unknown") : message.channel,
},
});

View File

@@ -373,7 +373,7 @@ export function registerSlackMonitorSlashCommands(params: {
accountId: account.accountId,
teamId: ctx.teamId || undefined,
peer: {
kind: isDirectMessage ? "dm" : isRoom ? "channel" : "group",
kind: isDirectMessage ? "direct" : isRoom ? "channel" : "group",
id: isDirectMessage ? command.user_id : command.channel_id,
},
});

View File

@@ -163,7 +163,7 @@ export const registerTelegramHandlers = ({
channel: "telegram",
accountId,
peer: {
kind: params.isGroup ? "group" : "dm",
kind: params.isGroup ? "group" : "direct",
id: peerId,
},
parentPeer,

View File

@@ -168,7 +168,7 @@ export const buildTelegramMessageContext = async ({
channel: "telegram",
accountId: account.accountId,
peer: {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: peerId,
},
parentPeer,

View File

@@ -495,7 +495,7 @@ export const registerTelegramNativeCommands = ({
channel: "telegram",
accountId,
peer: {
kind: isGroup ? "group" : "dm",
kind: isGroup ? "group" : "direct",
id: isGroup ? buildTelegramGroupPeerId(chatId, resolvedThreadId) : String(chatId),
},
parentPeer,

View File

@@ -453,7 +453,7 @@ export function createTelegramBot(opts: TelegramBotOptions) {
cfg,
channel: "telegram",
accountId: account.accountId,
peer: { kind: isGroup ? "group" : "dm", id: peerId },
peer: { kind: isGroup ? "group" : "direct", id: peerId },
parentPeer,
});
const sessionKey = route.sessionKey;

View File

@@ -10,8 +10,11 @@ import {
normalizeE164,
normalizePath,
resolveConfigDir,
resolveHomeDir,
resolveJidToE164,
resolveUserPath,
shortenHomeInString,
shortenHomePath,
sleep,
toWhatsappJid,
withWhatsAppPrefix,
@@ -134,6 +137,43 @@ describe("resolveConfigDir", () => {
});
});
describe("resolveHomeDir", () => {
it("prefers OPENCLAW_HOME over HOME", () => {
vi.stubEnv("OPENCLAW_HOME", "/srv/openclaw-home");
vi.stubEnv("HOME", "/home/other");
expect(resolveHomeDir()).toBe("/srv/openclaw-home");
vi.unstubAllEnvs();
});
});
describe("shortenHomePath", () => {
it("uses $OPENCLAW_HOME prefix when OPENCLAW_HOME is set", () => {
vi.stubEnv("OPENCLAW_HOME", "/srv/openclaw-home");
vi.stubEnv("HOME", "/home/other");
expect(shortenHomePath("/srv/openclaw-home/.openclaw/openclaw.json")).toBe(
"$OPENCLAW_HOME/.openclaw/openclaw.json",
);
vi.unstubAllEnvs();
});
});
describe("shortenHomeInString", () => {
it("uses $OPENCLAW_HOME replacement when OPENCLAW_HOME is set", () => {
vi.stubEnv("OPENCLAW_HOME", "/srv/openclaw-home");
vi.stubEnv("HOME", "/home/other");
expect(shortenHomeInString("config: /srv/openclaw-home/.openclaw/openclaw.json")).toBe(
"config: $OPENCLAW_HOME/.openclaw/openclaw.json",
);
vi.unstubAllEnvs();
});
});
describe("resolveJidToE164", () => {
it("resolves @lid via lidLookup when mapping file is missing", async () => {
const lidLookup = {
@@ -165,6 +205,15 @@ describe("resolveUserPath", () => {
expect(resolveUserPath("tmp/dir")).toBe(path.resolve("tmp/dir"));
});
it("prefers OPENCLAW_HOME for tilde expansion", () => {
vi.stubEnv("OPENCLAW_HOME", "/srv/openclaw-home");
vi.stubEnv("HOME", "/home/other");
expect(resolveUserPath("~/openclaw")).toBe(path.resolve("/srv/openclaw-home", "openclaw"));
vi.unstubAllEnvs();
});
it("keeps blank paths blank", () => {
expect(resolveUserPath("")).toBe("");
expect(resolveUserPath(" ")).toBe("");

View File

@@ -3,6 +3,11 @@ import os from "node:os";
import path from "node:path";
import { resolveOAuthDir } from "./config/paths.js";
import { logVerbose, shouldLogVerbose } from "./globals.js";
import {
expandHomePrefix,
resolveEffectiveHomeDir,
resolveRequiredHomeDir,
} from "./infra/home-dir.js";
export async function ensureDir(dir: string) {
await fs.promises.mkdir(dir, { recursive: true });
@@ -239,7 +244,11 @@ export function resolveUserPath(input: string): string {
return trimmed;
}
if (trimmed.startsWith("~")) {
const expanded = trimmed.replace(/^~(?=$|[\\/])/, os.homedir());
const expanded = expandHomePrefix(trimmed, {
home: resolveRequiredHomeDir(process.env, os.homedir),
env: process.env,
homedir: os.homedir,
});
return path.resolve(expanded);
}
return path.resolve(trimmed);
@@ -253,7 +262,7 @@ export function resolveConfigDir(
if (override) {
return resolveUserPath(override);
}
const newDir = path.join(homedir(), ".openclaw");
const newDir = path.join(resolveRequiredHomeDir(env, homedir), ".openclaw");
try {
const hasNew = fs.existsSync(newDir);
if (hasNew) {
@@ -266,35 +275,35 @@ export function resolveConfigDir(
}
export function resolveHomeDir(): string | undefined {
const envHome = process.env.HOME?.trim();
if (envHome) {
return envHome;
}
const envProfile = process.env.USERPROFILE?.trim();
if (envProfile) {
return envProfile;
}
try {
const home = os.homedir();
return home?.trim() ? home : undefined;
} catch {
return resolveEffectiveHomeDir(process.env, os.homedir);
}
function resolveHomeDisplayPrefix(): { home: string; prefix: string } | undefined {
const home = resolveHomeDir();
if (!home) {
return undefined;
}
const explicitHome = process.env.OPENCLAW_HOME?.trim();
if (explicitHome) {
return { home, prefix: "$OPENCLAW_HOME" };
}
return { home, prefix: "~" };
}
export function shortenHomePath(input: string): string {
if (!input) {
return input;
}
const home = resolveHomeDir();
if (!home) {
const display = resolveHomeDisplayPrefix();
if (!display) {
return input;
}
const { home, prefix } = display;
if (input === home) {
return "~";
return prefix;
}
if (input.startsWith(`${home}/`)) {
return `~${input.slice(home.length)}`;
if (input.startsWith(`${home}/`) || input.startsWith(`${home}\\`)) {
return `${prefix}${input.slice(home.length)}`;
}
return input;
}
@@ -303,11 +312,11 @@ export function shortenHomeInString(input: string): string {
if (!input) {
return input;
}
const home = resolveHomeDir();
if (!home) {
const display = resolveHomeDisplayPrefix();
if (!display) {
return input;
}
return input.split(home).join("~");
return input.split(display.home).join(display.prefix);
}
export function displayPath(input: string): string {

View File

@@ -164,7 +164,7 @@ describe("web auto-reply", () => {
agentId: "rich",
match: {
channel: "whatsapp",
peer: { kind: "dm", id: "+1555" },
peer: { kind: "direct", id: "+1555" },
},
},
],
@@ -223,7 +223,7 @@ describe("web auto-reply", () => {
agentId: "rich",
match: {
channel: "whatsapp",
peer: { kind: "dm", id: "+1555" },
peer: { kind: "direct", id: "+1555" },
},
},
],

View File

@@ -60,7 +60,7 @@ export async function maybeBroadcastMessage(params: {
channel: "whatsapp",
accountId: params.route.accountId,
peer: {
kind: params.msg.chatType === "group" ? "group" : "dm",
kind: params.msg.chatType === "group" ? "group" : "direct",
id: params.peerId,
},
dmScope: params.cfg.session?.dmScope,

View File

@@ -68,7 +68,7 @@ export function createWebOnMessageHandler(params: {
channel: "whatsapp",
accountId: msg.accountId,
peer: {
kind: msg.chatType === "group" ? "group" : "dm",
kind: msg.chatType === "group" ? "group" : "direct",
id: peerId,
},
});

View File

@@ -13,7 +13,6 @@
"noEmitOnError": true,
"outDir": "dist",
"resolveJsonModule": true,
"rootDir": "src",
"skipLibCheck": true,
"strict": true,
"target": "es2023",