Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
adbc4d093e | ||
|
|
0c1ac41085 | ||
|
|
a8c204e9fa | ||
|
|
1ac6f3ce92 |
No files matched your search
@@ -1,5 +1,4 @@
|
|||||||
node_modules
|
node_modules
|
||||||
**/node_modules/
|
|
||||||
.env
|
.env
|
||||||
docker-compose.extra.yml
|
docker-compose.extra.yml
|
||||||
dist
|
dist
|
||||||
|
|||||||
@@ -8,10 +8,6 @@
|
|||||||
- Docs: `docs/` (images, queue, Pi config). Built output lives in `dist/`.
|
- Docs: `docs/` (images, queue, Pi config). Built output lives in `dist/`.
|
||||||
- Plugins/extensions: live under `extensions/*` (workspace packages). Keep plugin-only deps in the extension `package.json`; do not add them to the root `package.json` unless core uses them.
|
- Plugins/extensions: live under `extensions/*` (workspace packages). Keep plugin-only deps in the extension `package.json`; do not add them to the root `package.json` unless core uses them.
|
||||||
- Installers served from `https://clawd.bot/*`: live in the sibling repo `../clawd.bot` (`public/install.sh`, `public/install-cli.sh`, `public/install.ps1`).
|
- Installers served from `https://clawd.bot/*`: live in the sibling repo `../clawd.bot` (`public/install.sh`, `public/install-cli.sh`, `public/install.ps1`).
|
||||||
- Messaging channels: always consider **all** built-in + extension channels when refactoring shared logic (routing, allowlists, pairing, command gating, onboarding, docs).
|
|
||||||
- Core channel docs: `docs/channels/`
|
|
||||||
- Core channel code: `src/telegram`, `src/discord`, `src/slack`, `src/signal`, `src/imessage`, `src/web` (WhatsApp web), `src/channels`, `src/routing`
|
|
||||||
- Extensions (channel plugins): `extensions/*` (e.g. `extensions/msteams`, `extensions/matrix`, `extensions/zalo`, `extensions/zalouser`, `extensions/voice-call`)
|
|
||||||
|
|
||||||
## Docs Linking (Mintlify)
|
## Docs Linking (Mintlify)
|
||||||
- Docs are hosted on Mintlify (docs.clawd.bot).
|
- Docs are hosted on Mintlify (docs.clawd.bot).
|
||||||
|
|||||||
+2
-6
@@ -6,17 +6,13 @@ Docs: https://docs.clawd.bot
|
|||||||
|
|
||||||
### Changes
|
### Changes
|
||||||
- Dependencies: update core + plugin deps (grammy, vitest, openai, Microsoft agents hosting, etc.).
|
- Dependencies: update core + plugin deps (grammy, vitest, openai, Microsoft agents hosting, etc.).
|
||||||
- Onboarding: clarify Anthropic token option hints in the onboarding wizard. (#1185) — thanks @KrauseFx.
|
- Agents: make inbound message envelopes configurable (timezone/timestamp/elapsed) and surface elapsed gaps. (#1150) — thanks @shiv19.
|
||||||
- Onboarding: add allowlist prompts and username-to-id resolution across core and extension channels.
|
|
||||||
- Docs: clarify allowlist input types and onboarding behavior for messaging channels.
|
|
||||||
|
|
||||||
### Fixes
|
### Fixes
|
||||||
- Configure: hide OpenRouter auto routing model from the model picker. (#1182) — thanks @zerone0x.
|
- Configure: hide OpenRouter auto routing model from the model picker. (#1182) — thanks @zerone0x.
|
||||||
- Docs: make docs:list fail fast with a clear error if the docs directory is missing.
|
- Agents: retry compaction reset once, then surface a user-facing error on repeat failure. (#1187) — thanks @fayrose.
|
||||||
- macOS: load menu session previews asynchronously so items populate while the menu is open.
|
- macOS: load menu session previews asynchronously so items populate while the menu is open.
|
||||||
- macOS: use label colors for session preview text so previews render in menu subviews.
|
- macOS: use label colors for session preview text so previews render in menu subviews.
|
||||||
- macOS: suppress usage error text in the menubar cost view.
|
|
||||||
- Telegram: honor pairing allowlists for native slash commands.
|
|
||||||
|
|
||||||
## 2026.1.18-4
|
## 2026.1.18-4
|
||||||
|
|
||||||
|
|||||||
@@ -494,6 +494,5 @@ Thanks to all clawtributors:
|
|||||||
<a href="https://github.com/loukotal"><img src="https://avatars.githubusercontent.com/u/18210858?v=4&s=48" width="48" height="48" alt="loukotal" title="loukotal"/></a> <a href="https://github.com/martinpucik"><img src="https://avatars.githubusercontent.com/u/5503097?v=4&s=48" width="48" height="48" alt="martinpucik" title="martinpucik"/></a> <a href="https://github.com/search?q=Miles"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Miles" title="Miles"/></a> <a href="https://github.com/mrdbstn"><img src="https://avatars.githubusercontent.com/u/58957632?v=4&s=48" width="48" height="48" alt="mrdbstn" title="mrdbstn"/></a> <a href="https://github.com/MSch"><img src="https://avatars.githubusercontent.com/u/7475?v=4&s=48" width="48" height="48" alt="MSch" title="MSch"/></a> <a href="https://github.com/search?q=Mustafa%20Tag%20Eldeen"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Mustafa Tag Eldeen" title="Mustafa Tag Eldeen"/></a> <a href="https://github.com/ndraiman"><img src="https://avatars.githubusercontent.com/u/12609607?v=4&s=48" width="48" height="48" alt="ndraiman" title="ndraiman"/></a> <a href="https://github.com/nexty5870"><img src="https://avatars.githubusercontent.com/u/3869659?v=4&s=48" width="48" height="48" alt="nexty5870" title="nexty5870"/></a> <a href="https://github.com/prathamdby"><img src="https://avatars.githubusercontent.com/u/134331217?v=4&s=48" width="48" height="48" alt="prathamdby" title="prathamdby"/></a> <a href="https://github.com/reeltimeapps"><img src="https://avatars.githubusercontent.com/u/637338?v=4&s=48" width="48" height="48" alt="reeltimeapps" title="reeltimeapps"/></a>
|
<a href="https://github.com/loukotal"><img src="https://avatars.githubusercontent.com/u/18210858?v=4&s=48" width="48" height="48" alt="loukotal" title="loukotal"/></a> <a href="https://github.com/martinpucik"><img src="https://avatars.githubusercontent.com/u/5503097?v=4&s=48" width="48" height="48" alt="martinpucik" title="martinpucik"/></a> <a href="https://github.com/search?q=Miles"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Miles" title="Miles"/></a> <a href="https://github.com/mrdbstn"><img src="https://avatars.githubusercontent.com/u/58957632?v=4&s=48" width="48" height="48" alt="mrdbstn" title="mrdbstn"/></a> <a href="https://github.com/MSch"><img src="https://avatars.githubusercontent.com/u/7475?v=4&s=48" width="48" height="48" alt="MSch" title="MSch"/></a> <a href="https://github.com/search?q=Mustafa%20Tag%20Eldeen"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Mustafa Tag Eldeen" title="Mustafa Tag Eldeen"/></a> <a href="https://github.com/ndraiman"><img src="https://avatars.githubusercontent.com/u/12609607?v=4&s=48" width="48" height="48" alt="ndraiman" title="ndraiman"/></a> <a href="https://github.com/nexty5870"><img src="https://avatars.githubusercontent.com/u/3869659?v=4&s=48" width="48" height="48" alt="nexty5870" title="nexty5870"/></a> <a href="https://github.com/prathamdby"><img src="https://avatars.githubusercontent.com/u/134331217?v=4&s=48" width="48" height="48" alt="prathamdby" title="prathamdby"/></a> <a href="https://github.com/reeltimeapps"><img src="https://avatars.githubusercontent.com/u/637338?v=4&s=48" width="48" height="48" alt="reeltimeapps" title="reeltimeapps"/></a>
|
||||||
<a href="https://github.com/RLTCmpe"><img src="https://avatars.githubusercontent.com/u/10762242?v=4&s=48" width="48" height="48" alt="RLTCmpe" title="RLTCmpe"/></a> <a href="https://github.com/rodrigouroz"><img src="https://avatars.githubusercontent.com/u/384037?v=4&s=48" width="48" height="48" alt="rodrigouroz" title="rodrigouroz"/></a> <a href="https://github.com/search?q=Rolf%20Fredheim"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Rolf Fredheim" title="Rolf Fredheim"/></a> <a href="https://github.com/search?q=Rony%20Kelner"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Rony Kelner" title="Rony Kelner"/></a> <a href="https://github.com/search?q=Samrat%20Jha"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Samrat Jha" title="Samrat Jha"/></a> <a href="https://github.com/siraht"><img src="https://avatars.githubusercontent.com/u/73152895?v=4&s=48" width="48" height="48" alt="siraht" title="siraht"/></a> <a href="https://github.com/snopoke"><img src="https://avatars.githubusercontent.com/u/249606?v=4&s=48" width="48" height="48" alt="snopoke" title="snopoke"/></a> <a href="https://github.com/suminhthanh"><img src="https://avatars.githubusercontent.com/u/2907636?v=4&s=48" width="48" height="48" alt="suminhthanh" title="suminhthanh"/></a> <a href="https://github.com/search?q=The%20Admiral"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="The Admiral" title="The Admiral"/></a> <a href="https://github.com/thesash"><img src="https://avatars.githubusercontent.com/u/1166151?v=4&s=48" width="48" height="48" alt="thesash" title="thesash"/></a>
|
<a href="https://github.com/RLTCmpe"><img src="https://avatars.githubusercontent.com/u/10762242?v=4&s=48" width="48" height="48" alt="RLTCmpe" title="RLTCmpe"/></a> <a href="https://github.com/rodrigouroz"><img src="https://avatars.githubusercontent.com/u/384037?v=4&s=48" width="48" height="48" alt="rodrigouroz" title="rodrigouroz"/></a> <a href="https://github.com/search?q=Rolf%20Fredheim"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Rolf Fredheim" title="Rolf Fredheim"/></a> <a href="https://github.com/search?q=Rony%20Kelner"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Rony Kelner" title="Rony Kelner"/></a> <a href="https://github.com/search?q=Samrat%20Jha"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Samrat Jha" title="Samrat Jha"/></a> <a href="https://github.com/siraht"><img src="https://avatars.githubusercontent.com/u/73152895?v=4&s=48" width="48" height="48" alt="siraht" title="siraht"/></a> <a href="https://github.com/snopoke"><img src="https://avatars.githubusercontent.com/u/249606?v=4&s=48" width="48" height="48" alt="snopoke" title="snopoke"/></a> <a href="https://github.com/suminhthanh"><img src="https://avatars.githubusercontent.com/u/2907636?v=4&s=48" width="48" height="48" alt="suminhthanh" title="suminhthanh"/></a> <a href="https://github.com/search?q=The%20Admiral"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="The Admiral" title="The Admiral"/></a> <a href="https://github.com/thesash"><img src="https://avatars.githubusercontent.com/u/1166151?v=4&s=48" width="48" height="48" alt="thesash" title="thesash"/></a>
|
||||||
<a href="https://github.com/search?q=Ubuntu"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Ubuntu" title="Ubuntu"/></a> <a href="https://github.com/voidserf"><img src="https://avatars.githubusercontent.com/u/477673?v=4&s=48" width="48" height="48" alt="voidserf" title="voidserf"/></a> <a href="https://github.com/wstock"><img src="https://avatars.githubusercontent.com/u/1394687?v=4&s=48" width="48" height="48" alt="wstock" title="wstock"/></a> <a href="https://github.com/search?q=Zach%20Knickerbocker"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Zach Knickerbocker" title="Zach Knickerbocker"/></a> <a href="https://github.com/Alphonse-arianee"><img src="https://avatars.githubusercontent.com/u/254457365?v=4&s=48" width="48" height="48" alt="Alphonse-arianee" title="Alphonse-arianee"/></a> <a href="https://github.com/search?q=Azade"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Azade" title="Azade"/></a> <a href="https://github.com/carlulsoe"><img src="https://avatars.githubusercontent.com/u/34673973?v=4&s=48" width="48" height="48" alt="carlulsoe" title="carlulsoe"/></a> <a href="https://github.com/search?q=ddyo"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="ddyo" title="ddyo"/></a> <a href="https://github.com/search?q=Erik"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Erik" title="Erik"/></a> <a href="https://github.com/latitudeki5223"><img src="https://avatars.githubusercontent.com/u/119656367?v=4&s=48" width="48" height="48" alt="latitudeki5223" title="latitudeki5223"/></a>
|
<a href="https://github.com/search?q=Ubuntu"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Ubuntu" title="Ubuntu"/></a> <a href="https://github.com/voidserf"><img src="https://avatars.githubusercontent.com/u/477673?v=4&s=48" width="48" height="48" alt="voidserf" title="voidserf"/></a> <a href="https://github.com/wstock"><img src="https://avatars.githubusercontent.com/u/1394687?v=4&s=48" width="48" height="48" alt="wstock" title="wstock"/></a> <a href="https://github.com/search?q=Zach%20Knickerbocker"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Zach Knickerbocker" title="Zach Knickerbocker"/></a> <a href="https://github.com/Alphonse-arianee"><img src="https://avatars.githubusercontent.com/u/254457365?v=4&s=48" width="48" height="48" alt="Alphonse-arianee" title="Alphonse-arianee"/></a> <a href="https://github.com/search?q=Azade"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Azade" title="Azade"/></a> <a href="https://github.com/carlulsoe"><img src="https://avatars.githubusercontent.com/u/34673973?v=4&s=48" width="48" height="48" alt="carlulsoe" title="carlulsoe"/></a> <a href="https://github.com/search?q=ddyo"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="ddyo" title="ddyo"/></a> <a href="https://github.com/search?q=Erik"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Erik" title="Erik"/></a> <a href="https://github.com/latitudeki5223"><img src="https://avatars.githubusercontent.com/u/119656367?v=4&s=48" width="48" height="48" alt="latitudeki5223" title="latitudeki5223"/></a>
|
||||||
<a href="https://github.com/search?q=Manuel%20Maly"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Manuel Maly" title="Manuel Maly"/></a> <a href="https://github.com/search?q=Mourad%20Boustani"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Mourad Boustani" title="Mourad Boustani"/></a> <a href="https://github.com/pcty-nextgen-ios-builder"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="pcty-nextgen-ios-builder" title="pcty-nextgen-ios-builder"/></a> <a href="https://github.com/search?q=Quentin"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Quentin" title="Quentin"/></a> <a href="https://github.com/search?q=Randy%20Torres"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Randy Torres" title="Randy Torres"/></a> <a href="https://github.com/rhjoh"><img src="https://avatars.githubusercontent.com/u/105699450?v=4&s=48" width="48" height="48" alt="rhjoh" title="rhjoh"/></a> <a href="https://github.com/ronak-guliani"><img src="https://avatars.githubusercontent.com/u/23518228?v=4&s=48" width="48" height="48" alt="ronak-guliani" title="ronak-guliani"/></a> <a href="https://github.com/search?q=William%20Stock"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="William Stock" title="William Stock"/></a> <a href="https://github.com/KrauseFx"><img src="https://avatars.githubusercontent.com/u/869950?v=4&s=48" width="48" height="48" alt="KrauseFx" title="KrauseFx"/></a>
|
<a href="https://github.com/search?q=Manuel%20Maly"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Manuel Maly" title="Manuel Maly"/></a> <a href="https://github.com/search?q=Mourad%20Boustani"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Mourad Boustani" title="Mourad Boustani"/></a> <a href="https://github.com/pcty-nextgen-ios-builder"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="pcty-nextgen-ios-builder" title="pcty-nextgen-ios-builder"/></a> <a href="https://github.com/search?q=Quentin"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Quentin" title="Quentin"/></a> <a href="https://github.com/search?q=Randy%20Torres"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="Randy Torres" title="Randy Torres"/></a> <a href="https://github.com/rhjoh"><img src="https://avatars.githubusercontent.com/u/105699450?v=4&s=48" width="48" height="48" alt="rhjoh" title="rhjoh"/></a> <a href="https://github.com/ronak-guliani"><img src="https://avatars.githubusercontent.com/u/23518228?v=4&s=48" width="48" height="48" alt="ronak-guliani" title="ronak-guliani"/></a> <a href="https://github.com/search?q=William%20Stock"><img src="assets/avatar-placeholder.svg" width="48" height="48" alt="William Stock" title="William Stock"/></a>
|
||||||
|
|
||||||
</p>
|
</p>
|
||||||
@@ -12,9 +12,6 @@ final class ConnectionModeCoordinator {
|
|||||||
func apply(mode: AppState.ConnectionMode, paused: Bool) async {
|
func apply(mode: AppState.ConnectionMode, paused: Bool) async {
|
||||||
switch mode {
|
switch mode {
|
||||||
case .unconfigured:
|
case .unconfigured:
|
||||||
if let error = await NodeServiceManager.stop() {
|
|
||||||
NodesStore.shared.lastError = "Node service stop failed: \(error)"
|
|
||||||
}
|
|
||||||
await RemoteTunnelManager.shared.stopAll()
|
await RemoteTunnelManager.shared.stopAll()
|
||||||
WebChatManager.shared.resetTunnels()
|
WebChatManager.shared.resetTunnels()
|
||||||
GatewayProcessManager.shared.stop()
|
GatewayProcessManager.shared.stop()
|
||||||
@@ -23,9 +20,6 @@ final class ConnectionModeCoordinator {
|
|||||||
Task.detached { await PortGuardian.shared.sweep(mode: .unconfigured) }
|
Task.detached { await PortGuardian.shared.sweep(mode: .unconfigured) }
|
||||||
|
|
||||||
case .local:
|
case .local:
|
||||||
if let error = await NodeServiceManager.stop() {
|
|
||||||
NodesStore.shared.lastError = "Node service stop failed: \(error)"
|
|
||||||
}
|
|
||||||
await RemoteTunnelManager.shared.stopAll()
|
await RemoteTunnelManager.shared.stopAll()
|
||||||
WebChatManager.shared.resetTunnels()
|
WebChatManager.shared.resetTunnels()
|
||||||
let shouldStart = GatewayAutostartPolicy.shouldStartGateway(mode: .local, paused: paused)
|
let shouldStart = GatewayAutostartPolicy.shouldStartGateway(mode: .local, paused: paused)
|
||||||
@@ -56,9 +50,6 @@ final class ConnectionModeCoordinator {
|
|||||||
WebChatManager.shared.resetTunnels()
|
WebChatManager.shared.resetTunnels()
|
||||||
|
|
||||||
do {
|
do {
|
||||||
if let error = await NodeServiceManager.start() {
|
|
||||||
NodesStore.shared.lastError = "Node service start failed: \(error)"
|
|
||||||
}
|
|
||||||
_ = try await GatewayEndpointStore.shared.ensureRemoteControlTunnel()
|
_ = try await GatewayEndpointStore.shared.ensureRemoteControlTunnel()
|
||||||
let settings = CommandResolver.connectionSettings()
|
let settings = CommandResolver.connectionSettings()
|
||||||
try await ControlChannel.shared.configure(mode: .remote(
|
try await ControlChannel.shared.configure(mode: .remote(
|
||||||
|
|||||||
@@ -443,6 +443,7 @@ actor MacNodeRuntime {
|
|||||||
let approvals = ExecApprovalsStore.resolve(agentId: agentId)
|
let approvals = ExecApprovalsStore.resolve(agentId: agentId)
|
||||||
let security = approvals.agent.security
|
let security = approvals.agent.security
|
||||||
let ask = approvals.agent.ask
|
let ask = approvals.agent.ask
|
||||||
|
let askFallback = approvals.agent.askFallback
|
||||||
let autoAllowSkills = approvals.agent.autoAllowSkills
|
let autoAllowSkills = approvals.agent.autoAllowSkills
|
||||||
let sessionKey = (params.sessionKey?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false)
|
let sessionKey = (params.sessionKey?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false)
|
||||||
? params.sessionKey!.trimmingCharacters(in: .whitespacesAndNewlines)
|
? params.sessionKey!.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
@@ -488,7 +489,7 @@ actor MacNodeRuntime {
|
|||||||
|
|
||||||
var approvedByAsk = false
|
var approvedByAsk = false
|
||||||
if requiresAsk {
|
if requiresAsk {
|
||||||
let decision = await ExecApprovalsPromptPresenter.prompt(
|
let decision: ExecApprovalDecision? = await ExecApprovalsPromptPresenter.prompt(
|
||||||
ExecApprovalPromptRequest(
|
ExecApprovalPromptRequest(
|
||||||
command: displayCommand,
|
command: displayCommand,
|
||||||
cwd: params.cwd,
|
cwd: params.cwd,
|
||||||
@@ -499,7 +500,7 @@ actor MacNodeRuntime {
|
|||||||
resolvedPath: resolution?.resolvedPath))
|
resolvedPath: resolution?.resolvedPath))
|
||||||
|
|
||||||
switch decision {
|
switch decision {
|
||||||
case .deny:
|
case .deny?:
|
||||||
await self.emitExecEvent(
|
await self.emitExecEvent(
|
||||||
"exec.denied",
|
"exec.denied",
|
||||||
payload: ExecEventPayload(
|
payload: ExecEventPayload(
|
||||||
@@ -512,7 +513,41 @@ actor MacNodeRuntime {
|
|||||||
req,
|
req,
|
||||||
code: .unavailable,
|
code: .unavailable,
|
||||||
message: "SYSTEM_RUN_DENIED: user denied")
|
message: "SYSTEM_RUN_DENIED: user denied")
|
||||||
case .allowAlways:
|
case nil:
|
||||||
|
if askFallback == .full {
|
||||||
|
approvedByAsk = true
|
||||||
|
} else if askFallback == .allowlist {
|
||||||
|
if allowlistMatch != nil || skillAllow {
|
||||||
|
approvedByAsk = true
|
||||||
|
} else {
|
||||||
|
await self.emitExecEvent(
|
||||||
|
"exec.denied",
|
||||||
|
payload: ExecEventPayload(
|
||||||
|
sessionKey: sessionKey,
|
||||||
|
runId: runId,
|
||||||
|
host: "node",
|
||||||
|
command: displayCommand,
|
||||||
|
reason: "approval-required"))
|
||||||
|
return Self.errorResponse(
|
||||||
|
req,
|
||||||
|
code: .unavailable,
|
||||||
|
message: "SYSTEM_RUN_DENIED: approval required")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
await self.emitExecEvent(
|
||||||
|
"exec.denied",
|
||||||
|
payload: ExecEventPayload(
|
||||||
|
sessionKey: sessionKey,
|
||||||
|
runId: runId,
|
||||||
|
host: "node",
|
||||||
|
command: displayCommand,
|
||||||
|
reason: "approval-required"))
|
||||||
|
return Self.errorResponse(
|
||||||
|
req,
|
||||||
|
code: .unavailable,
|
||||||
|
message: "SYSTEM_RUN_DENIED: approval required")
|
||||||
|
}
|
||||||
|
case .allowAlways?:
|
||||||
approvedByAsk = true
|
approvedByAsk = true
|
||||||
if security == .allowlist {
|
if security == .allowlist {
|
||||||
let pattern = resolution?.resolvedPath ??
|
let pattern = resolution?.resolvedPath ??
|
||||||
@@ -523,7 +558,7 @@ actor MacNodeRuntime {
|
|||||||
ExecApprovalsStore.addAllowlistEntry(agentId: agentId, pattern: pattern)
|
ExecApprovalsStore.addAllowlistEntry(agentId: agentId, pattern: pattern)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
case .allowOnce:
|
case .allowOnce?:
|
||||||
approvedByAsk = true
|
approvedByAsk = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,150 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
import OSLog
|
|
||||||
|
|
||||||
enum NodeServiceManager {
|
|
||||||
private static let logger = Logger(subsystem: "com.clawdbot", category: "node.service")
|
|
||||||
|
|
||||||
static func start() async -> String? {
|
|
||||||
let result = await self.runServiceCommandResult(
|
|
||||||
["node", "start"],
|
|
||||||
timeout: 20,
|
|
||||||
quiet: false)
|
|
||||||
if let error = self.errorMessage(from: result, treatNotLoadedAsError: true) {
|
|
||||||
self.logger.error("node service start failed: \(error, privacy: .public)")
|
|
||||||
return error
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
static func stop() async -> String? {
|
|
||||||
let result = await self.runServiceCommandResult(
|
|
||||||
["node", "stop"],
|
|
||||||
timeout: 15,
|
|
||||||
quiet: false)
|
|
||||||
if let error = self.errorMessage(from: result, treatNotLoadedAsError: false) {
|
|
||||||
self.logger.error("node service stop failed: \(error, privacy: .public)")
|
|
||||||
return error
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension NodeServiceManager {
|
|
||||||
private struct CommandResult {
|
|
||||||
let success: Bool
|
|
||||||
let payload: Data?
|
|
||||||
let message: String?
|
|
||||||
let parsed: ParsedServiceJson?
|
|
||||||
}
|
|
||||||
|
|
||||||
private struct ParsedServiceJson {
|
|
||||||
let text: String
|
|
||||||
let object: [String: Any]
|
|
||||||
let ok: Bool?
|
|
||||||
let result: String?
|
|
||||||
let message: String?
|
|
||||||
let error: String?
|
|
||||||
let hints: [String]
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func runServiceCommandResult(
|
|
||||||
_ args: [String],
|
|
||||||
timeout: Double,
|
|
||||||
quiet: Bool) async -> CommandResult
|
|
||||||
{
|
|
||||||
let command = CommandResolver.clawdbotCommand(
|
|
||||||
subcommand: "service",
|
|
||||||
extraArgs: self.withJsonFlag(args),
|
|
||||||
// Service management must always run locally, even if remote mode is configured.
|
|
||||||
configRoot: ["gateway": ["mode": "local"]])
|
|
||||||
var env = ProcessInfo.processInfo.environment
|
|
||||||
env["PATH"] = CommandResolver.preferredPaths().joined(separator: ":")
|
|
||||||
let response = await ShellExecutor.runDetailed(command: command, cwd: nil, env: env, timeout: timeout)
|
|
||||||
let parsed = self.parseServiceJson(from: response.stdout) ?? self.parseServiceJson(from: response.stderr)
|
|
||||||
let ok = parsed?.ok
|
|
||||||
let message = parsed?.error ?? parsed?.message
|
|
||||||
let payload = parsed?.text.data(using: .utf8)
|
|
||||||
?? (response.stdout.isEmpty ? response.stderr : response.stdout).data(using: .utf8)
|
|
||||||
let success = ok ?? response.success
|
|
||||||
if success {
|
|
||||||
return CommandResult(success: true, payload: payload, message: nil, parsed: parsed)
|
|
||||||
}
|
|
||||||
|
|
||||||
if quiet {
|
|
||||||
return CommandResult(success: false, payload: payload, message: message, parsed: parsed)
|
|
||||||
}
|
|
||||||
|
|
||||||
let detail = message ?? self.summarize(response.stderr) ?? self.summarize(response.stdout)
|
|
||||||
let exit = response.exitCode.map { "exit \($0)" } ?? (response.errorMessage ?? "failed")
|
|
||||||
let fullMessage = detail.map { "Node service command failed (\(exit)): \($0)" }
|
|
||||||
?? "Node service command failed (\(exit))"
|
|
||||||
self.logger.error("\(fullMessage, privacy: .public)")
|
|
||||||
return CommandResult(success: false, payload: payload, message: detail, parsed: parsed)
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func errorMessage(from result: CommandResult, treatNotLoadedAsError: Bool) -> String? {
|
|
||||||
if !result.success {
|
|
||||||
return result.message ?? "Node service command failed"
|
|
||||||
}
|
|
||||||
guard let parsed = result.parsed else { return nil }
|
|
||||||
if parsed.ok == false {
|
|
||||||
return self.mergeHints(message: parsed.error ?? parsed.message, hints: parsed.hints)
|
|
||||||
}
|
|
||||||
if treatNotLoadedAsError, parsed.result == "not-loaded" {
|
|
||||||
let base = parsed.message ?? "Node service not loaded."
|
|
||||||
return self.mergeHints(message: base, hints: parsed.hints)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func withJsonFlag(_ args: [String]) -> [String] {
|
|
||||||
if args.contains("--json") { return args }
|
|
||||||
return args + ["--json"]
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func parseServiceJson(from raw: String) -> ParsedServiceJson? {
|
|
||||||
let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
||||||
guard let start = trimmed.firstIndex(of: "{"),
|
|
||||||
let end = trimmed.lastIndex(of: "}")
|
|
||||||
else {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
let jsonText = String(trimmed[start...end])
|
|
||||||
guard let data = jsonText.data(using: .utf8) else { return nil }
|
|
||||||
guard let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil }
|
|
||||||
let ok = object["ok"] as? Bool
|
|
||||||
let result = object["result"] as? String
|
|
||||||
let message = object["message"] as? String
|
|
||||||
let error = object["error"] as? String
|
|
||||||
let hints = (object["hints"] as? [String]) ?? []
|
|
||||||
return ParsedServiceJson(
|
|
||||||
text: jsonText,
|
|
||||||
object: object,
|
|
||||||
ok: ok,
|
|
||||||
result: result,
|
|
||||||
message: message,
|
|
||||||
error: error,
|
|
||||||
hints: hints)
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func mergeHints(message: String?, hints: [String]) -> String? {
|
|
||||||
let trimmed = message?.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
||||||
let nonEmpty = trimmed?.isEmpty == false ? trimmed : nil
|
|
||||||
guard !hints.isEmpty else { return nonEmpty }
|
|
||||||
let hintText = hints.prefix(2).joined(separator: " · ")
|
|
||||||
if let nonEmpty {
|
|
||||||
return "\(nonEmpty) (\(hintText))"
|
|
||||||
}
|
|
||||||
return hintText
|
|
||||||
}
|
|
||||||
|
|
||||||
private static func summarize(_ text: String) -> String? {
|
|
||||||
let lines = text
|
|
||||||
.split(whereSeparator: \.isNewline)
|
|
||||||
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
|
|
||||||
.filter { !$0.isEmpty }
|
|
||||||
guard let last = lines.last else { return nil }
|
|
||||||
let normalized = last.replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)
|
|
||||||
return normalized.count > 200 ? String(normalized.prefix(199)) + "…" : normalized
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -75,6 +75,18 @@ struct UsageRow: Identifiable {
|
|||||||
extension GatewayUsageSummary {
|
extension GatewayUsageSummary {
|
||||||
func primaryRows() -> [UsageRow] {
|
func primaryRows() -> [UsageRow] {
|
||||||
self.providers.compactMap { provider in
|
self.providers.compactMap { provider in
|
||||||
|
if let error = provider.error, provider.windows.isEmpty {
|
||||||
|
return UsageRow(
|
||||||
|
id: provider.provider,
|
||||||
|
providerId: provider.provider,
|
||||||
|
displayName: provider.displayName,
|
||||||
|
plan: provider.plan,
|
||||||
|
windowLabel: nil,
|
||||||
|
usedPercent: nil,
|
||||||
|
resetAt: nil,
|
||||||
|
error: error)
|
||||||
|
}
|
||||||
|
|
||||||
guard let window = provider.windows.max(by: { $0.usedPercent < $1.usedPercent }) else {
|
guard let window = provider.windows.max(by: { $0.usedPercent < $1.usedPercent }) else {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -87,7 +99,7 @@ extension GatewayUsageSummary {
|
|||||||
windowLabel: window.label,
|
windowLabel: window.label,
|
||||||
usedPercent: window.usedPercent,
|
usedPercent: window.usedPercent,
|
||||||
resetAt: window.resetAt.map { Date(timeIntervalSince1970: $0 / 1000) },
|
resetAt: window.resetAt.map { Date(timeIntervalSince1970: $0 / 1000) },
|
||||||
error: nil)
|
error: provider.error)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,12 +37,14 @@ struct UsageMenuLabelView: View {
|
|||||||
|
|
||||||
Spacer(minLength: 4)
|
Spacer(minLength: 4)
|
||||||
|
|
||||||
Text(self.row.detailText())
|
if !self.row.hasError {
|
||||||
.font(.caption.monospacedDigit())
|
Text(self.row.detailText())
|
||||||
.foregroundStyle(self.secondaryTextColor)
|
.font(.caption.monospacedDigit())
|
||||||
.lineLimit(1)
|
.foregroundStyle(self.secondaryTextColor)
|
||||||
.truncationMode(.tail)
|
.lineLimit(1)
|
||||||
.layoutPriority(2)
|
.truncationMode(.tail)
|
||||||
|
.layoutPriority(2)
|
||||||
|
}
|
||||||
|
|
||||||
if self.showsChevron {
|
if self.showsChevron {
|
||||||
Image(systemName: "chevron.right")
|
Image(systemName: "chevron.right")
|
||||||
@@ -52,6 +54,15 @@ struct UsageMenuLabelView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let error = self.row.error?.nonEmpty {
|
||||||
|
Text(error)
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(self.secondaryTextColor)
|
||||||
|
.multilineTextAlignment(.leading)
|
||||||
|
.lineLimit(2)
|
||||||
|
.truncationMode(.tail)
|
||||||
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
.padding(.vertical, 10)
|
.padding(.vertical, 10)
|
||||||
.padding(.leading, self.paddingLeading)
|
.padding(.leading, self.paddingLeading)
|
||||||
|
|||||||
@@ -287,7 +287,7 @@ ack reaction after the bot replies.
|
|||||||
|
|
||||||
- `dm.enabled`: set `false` to ignore all DMs (default `true`).
|
- `dm.enabled`: set `false` to ignore all DMs (default `true`).
|
||||||
- `dm.policy`: DM access control (`pairing` recommended). `"open"` requires `dm.allowFrom=["*"]`.
|
- `dm.policy`: DM access control (`pairing` recommended). `"open"` requires `dm.allowFrom=["*"]`.
|
||||||
- `dm.allowFrom`: DM allowlist (user ids or names). Used by `dm.policy="allowlist"` and for `dm.policy="open"` validation. The wizard accepts usernames and resolves them to ids when the bot can search members.
|
- `dm.allowFrom`: DM allowlist (user ids or names). Used by `dm.policy="allowlist"` and for `dm.policy="open"` validation.
|
||||||
- `dm.groupEnabled`: enable group DMs (default `false`).
|
- `dm.groupEnabled`: enable group DMs (default `false`).
|
||||||
- `dm.groupChannels`: optional allowlist for group DM channel ids or slugs.
|
- `dm.groupChannels`: optional allowlist for group DM channel ids or slugs.
|
||||||
- `groupPolicy`: controls guild channel handling (`open|disabled|allowlist`); `allowlist` requires channel allowlists.
|
- `groupPolicy`: controls guild channel handling (`open|disabled|allowlist`); `allowlist` requires channel allowlists.
|
||||||
|
|||||||
@@ -244,7 +244,7 @@ Provider options:
|
|||||||
- `channels.imessage.service`: `imessage | sms | auto`.
|
- `channels.imessage.service`: `imessage | sms | auto`.
|
||||||
- `channels.imessage.region`: SMS region.
|
- `channels.imessage.region`: SMS region.
|
||||||
- `channels.imessage.dmPolicy`: `pairing | allowlist | open | disabled` (default: pairing).
|
- `channels.imessage.dmPolicy`: `pairing | allowlist | open | disabled` (default: pairing).
|
||||||
- `channels.imessage.allowFrom`: DM allowlist (handles, emails, E.164 numbers, or `chat_id:*`). `open` requires `"*"`. iMessage has no usernames; use handles or chat targets.
|
- `channels.imessage.allowFrom`: DM allowlist (handles or `chat_id:*`). `open` requires `"*"`.
|
||||||
- `channels.imessage.groupPolicy`: `open | allowlist | disabled` (default: allowlist).
|
- `channels.imessage.groupPolicy`: `open | allowlist | disabled` (default: allowlist).
|
||||||
- `channels.imessage.groupAllowFrom`: group sender allowlist.
|
- `channels.imessage.groupAllowFrom`: group sender allowlist.
|
||||||
- `channels.imessage.historyLimit` / `channels.imessage.accounts.*.historyLimit`: max group messages to include as context (0 disables).
|
- `channels.imessage.historyLimit` / `channels.imessage.accounts.*.historyLimit`: max group messages to include as context (0 disables).
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ Matrix is an open messaging protocol. Clawdbot connects as a Matrix user and lis
|
|||||||
- `clawdbot pairing list matrix`
|
- `clawdbot pairing list matrix`
|
||||||
- `clawdbot pairing approve matrix <CODE>`
|
- `clawdbot pairing approve matrix <CODE>`
|
||||||
- Public DMs: `channels.matrix.dm.policy="open"` plus `channels.matrix.dm.allowFrom=["*"]`.
|
- Public DMs: `channels.matrix.dm.policy="open"` plus `channels.matrix.dm.allowFrom=["*"]`.
|
||||||
- `channels.matrix.dm.allowFrom` accepts user IDs or display names. The wizard resolves display names to user IDs when directory search is available.
|
- `channels.matrix.dm.allowFrom` accepts user IDs or display names (resolved at startup when directory search is available).
|
||||||
|
|
||||||
## Rooms (groups)
|
## Rooms (groups)
|
||||||
- Default: `channels.matrix.groupPolicy = "allowlist"` (mention-gated). Use `channels.defaults.groupPolicy` to override the default when unset.
|
- Default: `channels.matrix.groupPolicy = "allowlist"` (mention-gated). Use `channels.defaults.groupPolicy` to override the default when unset.
|
||||||
@@ -121,7 +121,7 @@ Provider options:
|
|||||||
- `channels.matrix.threadReplies`: `off | inbound | always` (default: inbound).
|
- `channels.matrix.threadReplies`: `off | inbound | always` (default: inbound).
|
||||||
- `channels.matrix.textChunkLimit`: outbound text chunk size (chars).
|
- `channels.matrix.textChunkLimit`: outbound text chunk size (chars).
|
||||||
- `channels.matrix.dm.policy`: `pairing | allowlist | open | disabled` (default: pairing).
|
- `channels.matrix.dm.policy`: `pairing | allowlist | open | disabled` (default: pairing).
|
||||||
- `channels.matrix.dm.allowFrom`: DM allowlist (user IDs or display names). `open` requires `"*"`. The wizard resolves names to IDs when possible.
|
- `channels.matrix.dm.allowFrom`: DM allowlist. `open` requires `"*"`.
|
||||||
- `channels.matrix.groupPolicy`: `allowlist | open | disabled` (default: allowlist).
|
- `channels.matrix.groupPolicy`: `allowlist | open | disabled` (default: allowlist).
|
||||||
- `channels.matrix.allowlistOnly`: force allowlist rules for DMs + rooms.
|
- `channels.matrix.allowlistOnly`: force allowlist rules for DMs + rooms.
|
||||||
- `channels.matrix.rooms`: per-room settings and allowlist.
|
- `channels.matrix.rooms`: per-room settings and allowlist.
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ Disable with:
|
|||||||
|
|
||||||
**DM access**
|
**DM access**
|
||||||
- Default: `channels.msteams.dmPolicy = "pairing"`. Unknown senders are ignored until approved.
|
- Default: `channels.msteams.dmPolicy = "pairing"`. Unknown senders are ignored until approved.
|
||||||
- `channels.msteams.allowFrom` accepts AAD object IDs, UPNs, or display names. The wizard resolves names to IDs via Microsoft Graph when credentials allow.
|
- `channels.msteams.allowFrom` accepts AAD object IDs, UPNs, or display names (resolved at startup when Graph allows).
|
||||||
|
|
||||||
**Group access**
|
**Group access**
|
||||||
- Default: `channels.msteams.groupPolicy = "allowlist"` (blocked unless you add `groupAllowFrom`). Use `channels.defaults.groupPolicy` to override the default when unset.
|
- Default: `channels.msteams.groupPolicy = "allowlist"` (blocked unless you add `groupAllowFrom`). Use `channels.defaults.groupPolicy` to override the default when unset.
|
||||||
@@ -413,7 +413,7 @@ Key settings (see `/gateway/configuration` for shared channel patterns):
|
|||||||
- `channels.msteams.webhook.port` (default `3978`)
|
- `channels.msteams.webhook.port` (default `3978`)
|
||||||
- `channels.msteams.webhook.path` (default `/api/messages`)
|
- `channels.msteams.webhook.path` (default `/api/messages`)
|
||||||
- `channels.msteams.dmPolicy`: `pairing | allowlist | open | disabled` (default: pairing)
|
- `channels.msteams.dmPolicy`: `pairing | allowlist | open | disabled` (default: pairing)
|
||||||
- `channels.msteams.allowFrom`: allowlist for DMs (AAD object IDs, UPNs, or display names). The wizard resolves names to IDs during setup when Graph access is available.
|
- `channels.msteams.allowFrom`: allowlist for DMs (AAD object IDs or UPNs).
|
||||||
- `channels.msteams.textChunkLimit`: outbound text chunk size.
|
- `channels.msteams.textChunkLimit`: outbound text chunk size.
|
||||||
- `channels.msteams.mediaAllowHosts`: allowlist for inbound attachment hosts (defaults to Microsoft/Teams domains).
|
- `channels.msteams.mediaAllowHosts`: allowlist for inbound attachment hosts (defaults to Microsoft/Teams domains).
|
||||||
- `channels.msteams.requireMention`: require @mention in channels/groups (default true).
|
- `channels.msteams.requireMention`: require @mention in channels/groups (default true).
|
||||||
|
|||||||
@@ -120,7 +120,7 @@ Provider options:
|
|||||||
- `channels.signal.ignoreStories`: ignore stories from the daemon.
|
- `channels.signal.ignoreStories`: ignore stories from the daemon.
|
||||||
- `channels.signal.sendReadReceipts`: forward read receipts.
|
- `channels.signal.sendReadReceipts`: forward read receipts.
|
||||||
- `channels.signal.dmPolicy`: `pairing | allowlist | open | disabled` (default: pairing).
|
- `channels.signal.dmPolicy`: `pairing | allowlist | open | disabled` (default: pairing).
|
||||||
- `channels.signal.allowFrom`: DM allowlist (E.164 or `uuid:<id>`). `open` requires `"*"`. Signal has no usernames; use phone/UUID ids.
|
- `channels.signal.allowFrom`: DM allowlist (E.164 or `uuid:<id>`). `open` requires `"*"`.
|
||||||
- `channels.signal.groupPolicy`: `open | allowlist | disabled` (default: allowlist).
|
- `channels.signal.groupPolicy`: `open | allowlist | disabled` (default: allowlist).
|
||||||
- `channels.signal.groupAllowFrom`: group sender allowlist.
|
- `channels.signal.groupAllowFrom`: group sender allowlist.
|
||||||
- `channels.signal.historyLimit`: max group messages to include as context (0 disables).
|
- `channels.signal.historyLimit`: max group messages to include as context (0 disables).
|
||||||
|
|||||||
@@ -378,7 +378,7 @@ For fine-grained control, use these tags in agent responses:
|
|||||||
- Default: `channels.slack.dm.policy="pairing"` — unknown DM senders get a pairing code (expires after 1 hour).
|
- Default: `channels.slack.dm.policy="pairing"` — unknown DM senders get a pairing code (expires after 1 hour).
|
||||||
- Approve via: `clawdbot pairing approve slack <code>`.
|
- Approve via: `clawdbot pairing approve slack <code>`.
|
||||||
- To allow anyone: set `channels.slack.dm.policy="open"` and `channels.slack.dm.allowFrom=["*"]`.
|
- To allow anyone: set `channels.slack.dm.policy="open"` and `channels.slack.dm.allowFrom=["*"]`.
|
||||||
- `channels.slack.dm.allowFrom` accepts user IDs, @handles, or emails (resolved at startup when tokens allow). The wizard accepts usernames and resolves them to ids during setup when tokens allow.
|
- `channels.slack.dm.allowFrom` accepts user IDs, @handles, or emails (resolved at startup when tokens allow).
|
||||||
|
|
||||||
## Group policy
|
## Group policy
|
||||||
- `channels.slack.groupPolicy` controls channel handling (`open|disabled|allowlist`).
|
- `channels.slack.groupPolicy` controls channel handling (`open|disabled|allowlist`).
|
||||||
|
|||||||
@@ -305,7 +305,7 @@ Use the global setting when all Telegram bots/accounts should behave the same. U
|
|||||||
- `clawdbot pairing list telegram`
|
- `clawdbot pairing list telegram`
|
||||||
- `clawdbot pairing approve telegram <CODE>`
|
- `clawdbot pairing approve telegram <CODE>`
|
||||||
- Pairing is the default token exchange used for Telegram DMs. Details: [Pairing](/start/pairing)
|
- Pairing is the default token exchange used for Telegram DMs. Details: [Pairing](/start/pairing)
|
||||||
- `channels.telegram.allowFrom` accepts numeric user IDs (recommended) or `@username` entries. It is **not** the bot username; use the human sender’s ID. The wizard accepts `@username` and resolves it to the numeric ID when possible.
|
- `channels.telegram.allowFrom` accepts numeric user IDs (recommended) or `@username` entries. It is **not** the bot username; use the human sender’s ID.
|
||||||
|
|
||||||
#### Finding your Telegram user ID
|
#### Finding your Telegram user ID
|
||||||
Safer (no third-party bot):
|
Safer (no third-party bot):
|
||||||
|
|||||||
@@ -308,7 +308,7 @@ WhatsApp can automatically send emoji reactions to incoming messages immediately
|
|||||||
## Config quick map
|
## Config quick map
|
||||||
- `channels.whatsapp.dmPolicy` (DM policy: pairing/allowlist/open/disabled).
|
- `channels.whatsapp.dmPolicy` (DM policy: pairing/allowlist/open/disabled).
|
||||||
- `channels.whatsapp.selfChatMode` (same-phone setup; bot uses your personal WhatsApp number).
|
- `channels.whatsapp.selfChatMode` (same-phone setup; bot uses your personal WhatsApp number).
|
||||||
- `channels.whatsapp.allowFrom` (DM allowlist). WhatsApp uses E.164 phone numbers (no usernames).
|
- `channels.whatsapp.allowFrom` (DM allowlist).
|
||||||
- `channels.whatsapp.mediaMaxMb` (inbound media save cap).
|
- `channels.whatsapp.mediaMaxMb` (inbound media save cap).
|
||||||
- `channels.whatsapp.ackReaction` (auto-reaction on message receipt: `{emoji, direct, group}`).
|
- `channels.whatsapp.ackReaction` (auto-reaction on message receipt: `{emoji, direct, group}`).
|
||||||
- `channels.whatsapp.accounts.<accountId>.*` (per-account settings + optional `authDir`).
|
- `channels.whatsapp.accounts.<accountId>.*` (per-account settings + optional `authDir`).
|
||||||
|
|||||||
@@ -92,7 +92,7 @@ Multi-account support: use `channels.zalo.accounts` with per-account tokens and
|
|||||||
- `clawdbot pairing list zalo`
|
- `clawdbot pairing list zalo`
|
||||||
- `clawdbot pairing approve zalo <CODE>`
|
- `clawdbot pairing approve zalo <CODE>`
|
||||||
- Pairing is the default token exchange. Details: [Pairing](/start/pairing)
|
- Pairing is the default token exchange. Details: [Pairing](/start/pairing)
|
||||||
- `channels.zalo.allowFrom` accepts numeric user IDs (no username lookup available).
|
- `channels.zalo.allowFrom` accepts numeric user IDs.
|
||||||
|
|
||||||
## Long-polling vs webhook
|
## Long-polling vs webhook
|
||||||
- Default: long-polling (no public URL required).
|
- Default: long-polling (no public URL required).
|
||||||
@@ -147,7 +147,7 @@ Provider options:
|
|||||||
- `channels.zalo.botToken`: bot token from Zalo Bot Platform.
|
- `channels.zalo.botToken`: bot token from Zalo Bot Platform.
|
||||||
- `channels.zalo.tokenFile`: read token from file path.
|
- `channels.zalo.tokenFile`: read token from file path.
|
||||||
- `channels.zalo.dmPolicy`: `pairing | allowlist | open | disabled` (default: pairing).
|
- `channels.zalo.dmPolicy`: `pairing | allowlist | open | disabled` (default: pairing).
|
||||||
- `channels.zalo.allowFrom`: DM allowlist (user IDs). `open` requires `"*"`. The wizard will ask for numeric IDs.
|
- `channels.zalo.allowFrom`: DM allowlist (user IDs). `open` requires `"*"`.
|
||||||
- `channels.zalo.mediaMaxMb`: inbound/outbound media cap (MB, default 5).
|
- `channels.zalo.mediaMaxMb`: inbound/outbound media cap (MB, default 5).
|
||||||
- `channels.zalo.webhookUrl`: enable webhook mode (HTTPS required).
|
- `channels.zalo.webhookUrl`: enable webhook mode (HTTPS required).
|
||||||
- `channels.zalo.webhookSecret`: webhook secret (8-256 chars).
|
- `channels.zalo.webhookSecret`: webhook secret (8-256 chars).
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ clawdbot directory groups list --channel zalouser --query "work"
|
|||||||
|
|
||||||
## Access control (DMs)
|
## Access control (DMs)
|
||||||
`channels.zalouser.dmPolicy` supports: `pairing | allowlist | open | disabled` (default: `pairing`).
|
`channels.zalouser.dmPolicy` supports: `pairing | allowlist | open | disabled` (default: `pairing`).
|
||||||
`channels.zalouser.allowFrom` accepts user IDs or names. The wizard resolves names to IDs via `zca friend find` when available.
|
`channels.zalouser.allowFrom` accepts user IDs or names (resolved at startup when available).
|
||||||
|
|
||||||
Approve via:
|
Approve via:
|
||||||
- `clawdbot pairing list zalouser`
|
- `clawdbot pairing list zalouser`
|
||||||
|
|||||||
+1
-3
@@ -7,7 +7,6 @@ read_when:
|
|||||||
# `clawdbot agent`
|
# `clawdbot agent`
|
||||||
|
|
||||||
Run an agent turn via the Gateway (use `--local` for embedded).
|
Run an agent turn via the Gateway (use `--local` for embedded).
|
||||||
Use `--agent <id>` to target a configured agent directly.
|
|
||||||
|
|
||||||
Related:
|
Related:
|
||||||
- Agent send tool: [Agent send](/tools/agent-send)
|
- Agent send tool: [Agent send](/tools/agent-send)
|
||||||
@@ -16,7 +15,6 @@ Related:
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
clawdbot agent --to +15555550123 --message "status update" --deliver
|
clawdbot agent --to +15555550123 --message "status update" --deliver
|
||||||
clawdbot agent --agent ops --message "Summarize logs"
|
|
||||||
clawdbot agent --session-id 1234 --message "Summarize inbox" --thinking medium
|
clawdbot agent --session-id 1234 --message "Summarize inbox" --thinking medium
|
||||||
clawdbot agent --agent ops --message "Generate report" --deliver --reply-channel slack --reply-to "#reports"
|
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -5,7 +5,9 @@ read_when:
|
|||||||
---
|
---
|
||||||
# Clawdbot macOS IPC architecture
|
# Clawdbot macOS IPC architecture
|
||||||
|
|
||||||
**Current model:** a local Unix socket connects the **node service** to the **macOS app** for exec approvals + `system.run`. There is no `clawdbot-mac` CLI; agent actions still flow through the Gateway WebSocket and `node.invoke`. UI automation uses PeekabooBridge.
|
**Current model:** there is **no local control socket** and no `clawdbot-mac` CLI. All agent actions go through the Gateway WebSocket and `node.invoke`. UI automation still uses PeekabooBridge.
|
||||||
|
|
||||||
|
**Planned model:** add a local Unix socket between the **node service** and the **macOS app**. The app owns `system.run` (UI/TCC context); the node service forwards exec requests over IPC.
|
||||||
|
|
||||||
## Goals
|
## Goals
|
||||||
- Single GUI app instance that owns all TCC-facing work (notifications, screen recording, mic, speech, AppleScript).
|
- Single GUI app instance that owns all TCC-facing work (notifications, screen recording, mic, speech, AppleScript).
|
||||||
@@ -13,11 +15,11 @@ read_when:
|
|||||||
- Predictable permissions: always the same signed bundle ID, launched by launchd, so TCC grants stick.
|
- Predictable permissions: always the same signed bundle ID, launched by launchd, so TCC grants stick.
|
||||||
|
|
||||||
## How it works
|
## How it works
|
||||||
### Gateway + node bridge
|
### Gateway + node bridge (current)
|
||||||
- The app runs the Gateway (local mode) and connects to it as a node.
|
- The app runs the Gateway (local mode) and connects to it as a node.
|
||||||
- Agent actions are performed via `node.invoke` (e.g. `system.run`, `system.notify`, `canvas.*`).
|
- Agent actions are performed via `node.invoke` (e.g. `system.run`, `system.notify`, `canvas.*`).
|
||||||
|
|
||||||
### Node service + app IPC
|
### Node service + app IPC (planned)
|
||||||
- A headless node service connects to the Gateway bridge.
|
- A headless node service connects to the Gateway bridge.
|
||||||
- `system.run` requests are forwarded to the macOS app over a local Unix socket.
|
- `system.run` requests are forwarded to the macOS app over a local Unix socket.
|
||||||
- The app performs the exec in UI context, prompts if needed, and returns output.
|
- The app performs the exec in UI context, prompts if needed, and returns output.
|
||||||
@@ -36,6 +38,10 @@ Agent -> Gateway -> Bridge -> Node Service (TS)
|
|||||||
- Security: bridge hosts require an allowed TeamID; DEBUG-only same-UID escape hatch is guarded by `PEEKABOO_ALLOW_UNSIGNED_SOCKET_CLIENTS=1` (Peekaboo convention).
|
- Security: bridge hosts require an allowed TeamID; DEBUG-only same-UID escape hatch is guarded by `PEEKABOO_ALLOW_UNSIGNED_SOCKET_CLIENTS=1` (Peekaboo convention).
|
||||||
- See: [PeekabooBridge usage](/platforms/mac/peekaboo) for details.
|
- See: [PeekabooBridge usage](/platforms/mac/peekaboo) for details.
|
||||||
|
|
||||||
|
### Mach/XPC
|
||||||
|
- Not required for automation; `node.invoke` + PeekabooBridge cover current needs.
|
||||||
|
- Planned IPC keeps Unix sockets (no XPC helper).
|
||||||
|
|
||||||
## Operational flows
|
## Operational flows
|
||||||
- Restart/rebuild: `SIGN_IDENTITY="Apple Development: <Developer Name> (<TEAMID>)" scripts/restart-mac.sh`
|
- Restart/rebuild: `SIGN_IDENTITY="Apple Development: <Developer Name> (<TEAMID>)" scripts/restart-mac.sh`
|
||||||
- Kills existing instances
|
- Kills existing instances
|
||||||
@@ -48,4 +54,4 @@ Agent -> Gateway -> Bridge -> Node Service (TS)
|
|||||||
- PeekabooBridge: `PEEKABOO_ALLOW_UNSIGNED_SOCKET_CLIENTS=1` (DEBUG-only) may allow same-UID callers for local development.
|
- PeekabooBridge: `PEEKABOO_ALLOW_UNSIGNED_SOCKET_CLIENTS=1` (DEBUG-only) may allow same-UID callers for local development.
|
||||||
- All communication remains local-only; no network sockets are exposed.
|
- All communication remains local-only; no network sockets are exposed.
|
||||||
- TCC prompts originate only from the GUI app bundle; keep the signed bundle ID stable across rebuilds.
|
- TCC prompts originate only from the GUI app bundle; keep the signed bundle ID stable across rebuilds.
|
||||||
- IPC hardening: socket mode `0600`, token, peer-UID checks, HMAC challenge/response, short TTL.
|
- Planned IPC hardening: socket mode `0600`, token, peer-UID checks, HMAC challenge/response, short TTL.
|
||||||
@@ -17,17 +17,19 @@ capabilities to the agent as a node.
|
|||||||
Speech Recognition, Automation/AppleScript).
|
Speech Recognition, Automation/AppleScript).
|
||||||
- Runs or connects to the Gateway (local or remote).
|
- Runs or connects to the Gateway (local or remote).
|
||||||
- Exposes macOS‑only tools (Canvas, Camera, Screen Recording, `system.run`).
|
- Exposes macOS‑only tools (Canvas, Camera, Screen Recording, `system.run`).
|
||||||
- Starts the local node host service in **remote** mode (launchd), and stops it in **local** mode.
|
|
||||||
- Optionally hosts **PeekabooBridge** for UI automation.
|
- Optionally hosts **PeekabooBridge** for UI automation.
|
||||||
- Installs the global CLI (`clawdbot`) via npm/pnpm on request (bun not recommended for the Gateway runtime).
|
- Installs the global CLI (`clawdbot`) via npm/pnpm on request (bun not recommended for the Gateway runtime).
|
||||||
|
|
||||||
|
Planned:
|
||||||
|
- Run a headless **node service** locally (launchd).
|
||||||
|
- Keep `system.run` in the app (UI/TCC context), with the node service forwarding via IPC.
|
||||||
|
|
||||||
## Local vs remote mode
|
## Local vs remote mode
|
||||||
|
|
||||||
- **Local** (default): the app attaches to a running local Gateway if present;
|
- **Local** (default): the app attaches to a running local Gateway if present;
|
||||||
otherwise it enables the launchd service via `clawdbot daemon`.
|
otherwise it enables the launchd service via `clawdbot daemon`.
|
||||||
- **Remote**: the app connects to a Gateway over SSH/Tailscale and never starts
|
- **Remote**: the app connects to a Gateway over SSH/Tailscale and never starts
|
||||||
a local process.
|
a local process.
|
||||||
The app starts the local **node host service** so the remote Gateway can reach this Mac.
|
|
||||||
The app does not spawn the Gateway as a child process.
|
The app does not spawn the Gateway as a child process.
|
||||||
|
|
||||||
## Launchd control
|
## Launchd control
|
||||||
@@ -56,9 +58,9 @@ The macOS app presents itself as a node. Common commands:
|
|||||||
|
|
||||||
The node reports a `permissions` map so agents can decide what’s allowed.
|
The node reports a `permissions` map so agents can decide what’s allowed.
|
||||||
|
|
||||||
Node service + app IPC:
|
Planned split:
|
||||||
- When the headless node service is running (remote mode), it connects to the Gateway bridge.
|
- Node service advertises the node surface to the Gateway.
|
||||||
- `system.run` executes in the macOS app (UI/TCC context) over a local Unix socket; prompts + output stay in-app.
|
- macOS app performs `system.run` in UI context over IPC.
|
||||||
|
|
||||||
Diagram (SCI):
|
Diagram (SCI):
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -14,15 +14,13 @@ runtime on the current machine.
|
|||||||
- Required: `--message <text>`
|
- Required: `--message <text>`
|
||||||
- Session selection:
|
- Session selection:
|
||||||
- `--to <dest>` derives the session key (group/channel targets preserve isolation; direct chats collapse to `main`), **or**
|
- `--to <dest>` derives the session key (group/channel targets preserve isolation; direct chats collapse to `main`), **or**
|
||||||
- `--session-id <id>` reuses an existing session by id, **or**
|
- `--session-id <id>` reuses an existing session by id
|
||||||
- `--agent <id>` targets a configured agent directly (uses that agent's `main` session key)
|
|
||||||
- Runs the same embedded agent runtime as normal inbound replies.
|
- Runs the same embedded agent runtime as normal inbound replies.
|
||||||
- Thinking/verbose flags persist into the session store.
|
- Thinking/verbose flags persist into the session store.
|
||||||
- Output:
|
- Output:
|
||||||
- default: prints reply text (plus `MEDIA:<url>` lines)
|
- default: prints reply text (plus `MEDIA:<url>` lines)
|
||||||
- `--json`: prints structured payload + metadata
|
- `--json`: prints structured payload + metadata
|
||||||
- Optional delivery back to a channel with `--deliver` + `--channel` (target formats match `clawdbot message --target`).
|
- Optional delivery back to a channel with `--deliver` + `--channel` (target formats match `clawdbot message --target`).
|
||||||
- Use `--reply-channel`/`--reply-to`/`--reply-account` to override delivery without changing the session.
|
|
||||||
|
|
||||||
If the Gateway is unreachable, the CLI **falls back** to the embedded local run.
|
If the Gateway is unreachable, the CLI **falls back** to the embedded local run.
|
||||||
|
|
||||||
@@ -30,21 +28,16 @@ If the Gateway is unreachable, the CLI **falls back** to the embedded local run.
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
clawdbot agent --to +15555550123 --message "status update"
|
clawdbot agent --to +15555550123 --message "status update"
|
||||||
clawdbot agent --agent ops --message "Summarize logs"
|
|
||||||
clawdbot agent --session-id 1234 --message "Summarize inbox" --thinking medium
|
clawdbot agent --session-id 1234 --message "Summarize inbox" --thinking medium
|
||||||
clawdbot agent --to +15555550123 --message "Trace logs" --verbose on --json
|
clawdbot agent --to +15555550123 --message "Trace logs" --verbose on --json
|
||||||
clawdbot agent --to +15555550123 --message "Summon reply" --deliver
|
clawdbot agent --to +15555550123 --message "Summon reply" --deliver
|
||||||
clawdbot agent --agent ops --message "Generate report" --deliver --reply-channel slack --reply-to "#reports"
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Flags
|
## Flags
|
||||||
|
|
||||||
- `--local`: run locally (requires model provider API keys in your shell)
|
- `--local`: run locally (requires model provider API keys in your shell)
|
||||||
- `--deliver`: send the reply to the chosen channel
|
- `--deliver`: send the reply to the chosen channel (requires `--to`)
|
||||||
- `--channel`: delivery channel (`whatsapp|telegram|discord|slack|signal|imessage`, default: `whatsapp`)
|
- `--channel`: `whatsapp|telegram|discord|slack|signal|imessage` (default: `whatsapp`)
|
||||||
- `--reply-to`: delivery target override
|
|
||||||
- `--reply-channel`: delivery channel override
|
|
||||||
- `--reply-account`: delivery account id override
|
|
||||||
- `--thinking <off|minimal|low|medium|high|xhigh>`: persist thinking level (GPT-5.2 + Codex models only)
|
- `--thinking <off|minimal|low|medium|high|xhigh>`: persist thinking level (GPT-5.2 + Codex models only)
|
||||||
- `--verbose <on|full|off>`: persist verbose level
|
- `--verbose <on|full|off>`: persist verbose level
|
||||||
- `--timeout <seconds>`: override agent timeout
|
- `--timeout <seconds>`: override agent timeout
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import {
|
|||||||
type WizardPrompter,
|
type WizardPrompter,
|
||||||
} from "clawdbot/plugin-sdk";
|
} from "clawdbot/plugin-sdk";
|
||||||
import { listMatrixDirectoryGroupsLive } from "./directory-live.js";
|
import { listMatrixDirectoryGroupsLive } from "./directory-live.js";
|
||||||
import { listMatrixDirectoryPeersLive } from "./directory-live.js";
|
|
||||||
import { resolveMatrixAccount } from "./matrix/accounts.js";
|
import { resolveMatrixAccount } from "./matrix/accounts.js";
|
||||||
import { ensureMatrixSdkInstalled, isMatrixSdkAvailable } from "./matrix/deps.js";
|
import { ensureMatrixSdkInstalled, isMatrixSdkAvailable } from "./matrix/deps.js";
|
||||||
import type { CoreConfig, DmPolicy } from "./types.js";
|
import type { CoreConfig, DmPolicy } from "./types.js";
|
||||||
@@ -50,86 +49,40 @@ async function promptMatrixAllowFrom(params: {
|
|||||||
}): Promise<CoreConfig> {
|
}): Promise<CoreConfig> {
|
||||||
const { cfg, prompter } = params;
|
const { cfg, prompter } = params;
|
||||||
const existingAllowFrom = cfg.channels?.matrix?.dm?.allowFrom ?? [];
|
const existingAllowFrom = cfg.channels?.matrix?.dm?.allowFrom ?? [];
|
||||||
const account = resolveMatrixAccount({ cfg });
|
const entry = await prompter.text({
|
||||||
const canResolve = Boolean(account.configured);
|
message: "Matrix allowFrom (user id)",
|
||||||
|
placeholder: "@user:server",
|
||||||
|
initialValue: existingAllowFrom[0] ? String(existingAllowFrom[0]) : undefined,
|
||||||
|
validate: (value) => {
|
||||||
|
const raw = String(value ?? "").trim();
|
||||||
|
if (!raw) return "Required";
|
||||||
|
if (!raw.startsWith("@")) return "Matrix user IDs should start with @";
|
||||||
|
if (!raw.includes(":")) return "Matrix user IDs should include a server (:@server)";
|
||||||
|
return undefined;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const normalized = String(entry).trim();
|
||||||
|
const merged = [
|
||||||
|
...existingAllowFrom.map((item) => String(item).trim()).filter(Boolean),
|
||||||
|
normalized,
|
||||||
|
];
|
||||||
|
const unique = [...new Set(merged)];
|
||||||
|
|
||||||
const parseInput = (raw: string) =>
|
return {
|
||||||
raw
|
...cfg,
|
||||||
.split(/[\n,;]+/g)
|
channels: {
|
||||||
.map((entry) => entry.trim())
|
...cfg.channels,
|
||||||
.filter(Boolean);
|
matrix: {
|
||||||
|
...cfg.channels?.matrix,
|
||||||
const isFullUserId = (value: string) => value.startsWith("@") && value.includes(":");
|
enabled: true,
|
||||||
|
dm: {
|
||||||
while (true) {
|
...cfg.channels?.matrix?.dm,
|
||||||
const entry = await prompter.text({
|
policy: "allowlist",
|
||||||
message: "Matrix allowFrom (username or user id)",
|
allowFrom: unique,
|
||||||
placeholder: "@user:server",
|
|
||||||
initialValue: existingAllowFrom[0] ? String(existingAllowFrom[0]) : undefined,
|
|
||||||
validate: (value) => (String(value ?? "").trim() ? undefined : "Required"),
|
|
||||||
});
|
|
||||||
const parts = parseInput(String(entry));
|
|
||||||
const resolvedIds: string[] = [];
|
|
||||||
let unresolved: string[] = [];
|
|
||||||
|
|
||||||
for (const part of parts) {
|
|
||||||
if (isFullUserId(part)) {
|
|
||||||
resolvedIds.push(part);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!canResolve) {
|
|
||||||
unresolved.push(part);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const results = await listMatrixDirectoryPeersLive({
|
|
||||||
cfg,
|
|
||||||
query: part,
|
|
||||||
limit: 5,
|
|
||||||
}).catch(() => []);
|
|
||||||
const match = results.find((result) => result.id);
|
|
||||||
if (match?.id) {
|
|
||||||
resolvedIds.push(match.id);
|
|
||||||
if (results.length > 1) {
|
|
||||||
await prompter.note(
|
|
||||||
`Multiple matches for "${part}", using ${match.id}.`,
|
|
||||||
"Matrix allowlist",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
unresolved.push(part);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (unresolved.length > 0) {
|
|
||||||
await prompter.note(
|
|
||||||
`Could not resolve: ${unresolved.join(", ")}. Use full @user:server IDs.`,
|
|
||||||
"Matrix allowlist",
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const unique = [
|
|
||||||
...new Set([
|
|
||||||
...existingAllowFrom.map((item) => String(item).trim()).filter(Boolean),
|
|
||||||
...resolvedIds,
|
|
||||||
]),
|
|
||||||
];
|
|
||||||
return {
|
|
||||||
...cfg,
|
|
||||||
channels: {
|
|
||||||
...cfg.channels,
|
|
||||||
matrix: {
|
|
||||||
...cfg.channels?.matrix,
|
|
||||||
enabled: true,
|
|
||||||
dm: {
|
|
||||||
...cfg.channels?.matrix?.dm,
|
|
||||||
policy: "allowlist",
|
|
||||||
allowFrom: unique,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
};
|
},
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function setMatrixGroupPolicy(cfg: CoreConfig, groupPolicy: "open" | "allowlist" | "disabled") {
|
function setMatrixGroupPolicy(cfg: CoreConfig, groupPolicy: "open" | "allowlist" | "disabled") {
|
||||||
@@ -168,7 +121,6 @@ const dmPolicy: ChannelOnboardingDmPolicy = {
|
|||||||
allowFromKey: "channels.matrix.dm.allowFrom",
|
allowFromKey: "channels.matrix.dm.allowFrom",
|
||||||
getCurrent: (cfg) => (cfg as CoreConfig).channels?.matrix?.dm?.policy ?? "pairing",
|
getCurrent: (cfg) => (cfg as CoreConfig).channels?.matrix?.dm?.policy ?? "pairing",
|
||||||
setPolicy: (cfg, policy) => setMatrixDmPolicy(cfg as CoreConfig, policy),
|
setPolicy: (cfg, policy) => setMatrixDmPolicy(cfg as CoreConfig, policy),
|
||||||
promptAllowFrom: promptMatrixAllowFrom,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const matrixOnboardingAdapter: ChannelOnboardingAdapter = {
|
export const matrixOnboardingAdapter: ChannelOnboardingAdapter = {
|
||||||
|
|||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -16,7 +16,6 @@ import { resolveMSTeamsCredentials } from "./token.js";
|
|||||||
import {
|
import {
|
||||||
parseMSTeamsTeamEntry,
|
parseMSTeamsTeamEntry,
|
||||||
resolveMSTeamsChannelAllowlist,
|
resolveMSTeamsChannelAllowlist,
|
||||||
resolveMSTeamsUserAllowlist,
|
|
||||||
} from "./resolve-allowlist.js";
|
} from "./resolve-allowlist.js";
|
||||||
|
|
||||||
const channel = "msteams" as const;
|
const channel = "msteams" as const;
|
||||||
@@ -39,97 +38,6 @@ function setMSTeamsDmPolicy(cfg: ClawdbotConfig, dmPolicy: DmPolicy) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function setMSTeamsAllowFrom(cfg: ClawdbotConfig, allowFrom: string[]): ClawdbotConfig {
|
|
||||||
return {
|
|
||||||
...cfg,
|
|
||||||
channels: {
|
|
||||||
...cfg.channels,
|
|
||||||
msteams: {
|
|
||||||
...cfg.channels?.msteams,
|
|
||||||
allowFrom,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseAllowFromInput(raw: string): string[] {
|
|
||||||
return raw
|
|
||||||
.split(/[\n,;]+/g)
|
|
||||||
.map((entry) => entry.trim())
|
|
||||||
.filter(Boolean);
|
|
||||||
}
|
|
||||||
|
|
||||||
function looksLikeGuid(value: string): boolean {
|
|
||||||
return /^[0-9a-fA-F-]{16,}$/.test(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function promptMSTeamsAllowFrom(params: {
|
|
||||||
cfg: ClawdbotConfig;
|
|
||||||
prompter: WizardPrompter;
|
|
||||||
}): Promise<ClawdbotConfig> {
|
|
||||||
const existing = params.cfg.channels?.msteams?.allowFrom ?? [];
|
|
||||||
await params.prompter.note(
|
|
||||||
[
|
|
||||||
"Allowlist MS Teams DMs by display name, UPN/email, or user id.",
|
|
||||||
"We resolve names to user IDs via Microsoft Graph when credentials allow.",
|
|
||||||
"Examples:",
|
|
||||||
"- alex@example.com",
|
|
||||||
"- Alex Johnson",
|
|
||||||
"- 00000000-0000-0000-0000-000000000000",
|
|
||||||
].join("\n"),
|
|
||||||
"MS Teams allowlist",
|
|
||||||
);
|
|
||||||
|
|
||||||
while (true) {
|
|
||||||
const entry = await params.prompter.text({
|
|
||||||
message: "MS Teams allowFrom (usernames or ids)",
|
|
||||||
placeholder: "alex@example.com, Alex Johnson",
|
|
||||||
initialValue: existing[0] ? String(existing[0]) : undefined,
|
|
||||||
validate: (value) => (String(value ?? "").trim() ? undefined : "Required"),
|
|
||||||
});
|
|
||||||
const parts = parseAllowFromInput(String(entry));
|
|
||||||
if (parts.length === 0) {
|
|
||||||
await params.prompter.note("Enter at least one user.", "MS Teams allowlist");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const resolved = await resolveMSTeamsUserAllowlist({
|
|
||||||
cfg: params.cfg,
|
|
||||||
entries: parts,
|
|
||||||
}).catch(() => null);
|
|
||||||
|
|
||||||
if (!resolved) {
|
|
||||||
const ids = parts.filter((part) => looksLikeGuid(part));
|
|
||||||
if (ids.length !== parts.length) {
|
|
||||||
await params.prompter.note(
|
|
||||||
"Graph lookup unavailable. Use user IDs only.",
|
|
||||||
"MS Teams allowlist",
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const unique = [
|
|
||||||
...new Set([...existing.map((v) => String(v).trim()).filter(Boolean), ...ids]),
|
|
||||||
];
|
|
||||||
return setMSTeamsAllowFrom(params.cfg, unique);
|
|
||||||
}
|
|
||||||
|
|
||||||
const unresolved = resolved.filter((item) => !item.resolved || !item.id);
|
|
||||||
if (unresolved.length > 0) {
|
|
||||||
await params.prompter.note(
|
|
||||||
`Could not resolve: ${unresolved.map((item) => item.input).join(", ")}`,
|
|
||||||
"MS Teams allowlist",
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ids = resolved.map((item) => item.id as string);
|
|
||||||
const unique = [
|
|
||||||
...new Set([...existing.map((v) => String(v).trim()).filter(Boolean), ...ids]),
|
|
||||||
];
|
|
||||||
return setMSTeamsAllowFrom(params.cfg, unique);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function noteMSTeamsCredentialHelp(prompter: WizardPrompter): Promise<void> {
|
async function noteMSTeamsCredentialHelp(prompter: WizardPrompter): Promise<void> {
|
||||||
await prompter.note(
|
await prompter.note(
|
||||||
[
|
[
|
||||||
@@ -198,7 +106,6 @@ const dmPolicy: ChannelOnboardingDmPolicy = {
|
|||||||
allowFromKey: "channels.msteams.allowFrom",
|
allowFromKey: "channels.msteams.allowFrom",
|
||||||
getCurrent: (cfg) => cfg.channels?.msteams?.dmPolicy ?? "pairing",
|
getCurrent: (cfg) => cfg.channels?.msteams?.dmPolicy ?? "pairing",
|
||||||
setPolicy: (cfg, policy) => setMSTeamsDmPolicy(cfg, policy),
|
setPolicy: (cfg, policy) => setMSTeamsDmPolicy(cfg, policy),
|
||||||
promptAllowFrom: promptMSTeamsAllowFrom,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const msteamsOnboardingAdapter: ChannelOnboardingAdapter = {
|
export const msteamsOnboardingAdapter: ChannelOnboardingAdapter = {
|
||||||
|
|||||||
@@ -207,17 +207,6 @@ const dmPolicy: ChannelOnboardingDmPolicy = {
|
|||||||
allowFromKey: "channels.zalo.allowFrom",
|
allowFromKey: "channels.zalo.allowFrom",
|
||||||
getCurrent: (cfg) => (cfg.channels?.zalo?.dmPolicy ?? "pairing") as "pairing",
|
getCurrent: (cfg) => (cfg.channels?.zalo?.dmPolicy ?? "pairing") as "pairing",
|
||||||
setPolicy: (cfg, policy) => setZaloDmPolicy(cfg as ClawdbotConfig, policy),
|
setPolicy: (cfg, policy) => setZaloDmPolicy(cfg as ClawdbotConfig, policy),
|
||||||
promptAllowFrom: async ({ cfg, prompter, accountId }) => {
|
|
||||||
const id =
|
|
||||||
accountId && normalizeAccountId(accountId)
|
|
||||||
? normalizeAccountId(accountId) ?? DEFAULT_ACCOUNT_ID
|
|
||||||
: resolveDefaultZaloAccountId(cfg as ClawdbotConfig);
|
|
||||||
return promptZaloAllowFrom({
|
|
||||||
cfg: cfg as ClawdbotConfig,
|
|
||||||
prompter,
|
|
||||||
accountId: id,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const zaloOnboardingAdapter: ChannelOnboardingAdapter = {
|
export const zaloOnboardingAdapter: ChannelOnboardingAdapter = {
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import {
|
|||||||
checkZcaAuthenticated,
|
checkZcaAuthenticated,
|
||||||
} from "./accounts.js";
|
} from "./accounts.js";
|
||||||
import { runZca, runZcaInteractive, checkZcaInstalled, parseJsonOutput } from "./zca.js";
|
import { runZca, runZcaInteractive, checkZcaInstalled, parseJsonOutput } from "./zca.js";
|
||||||
import type { ZcaFriend, ZcaGroup } from "./types.js";
|
import type { ZcaGroup } from "./types.js";
|
||||||
|
|
||||||
const channel = "zalouser" as const;
|
const channel = "zalouser" as const;
|
||||||
|
|
||||||
@@ -67,73 +67,25 @@ async function promptZalouserAllowFrom(params: {
|
|||||||
const { cfg, prompter, accountId } = params;
|
const { cfg, prompter, accountId } = params;
|
||||||
const resolved = resolveZalouserAccountSync({ cfg, accountId });
|
const resolved = resolveZalouserAccountSync({ cfg, accountId });
|
||||||
const existingAllowFrom = resolved.config.allowFrom ?? [];
|
const existingAllowFrom = resolved.config.allowFrom ?? [];
|
||||||
const parseInput = (raw: string) =>
|
const entry = await prompter.text({
|
||||||
raw
|
message: "Zalouser allowFrom (user id)",
|
||||||
.split(/[\n,;]+/g)
|
placeholder: "123456789",
|
||||||
.map((entry) => entry.trim())
|
initialValue: existingAllowFrom[0] ? String(existingAllowFrom[0]) : undefined,
|
||||||
.filter(Boolean);
|
validate: (value) => {
|
||||||
|
const raw = String(value ?? "").trim();
|
||||||
const resolveUserId = async (input: string): Promise<string | null> => {
|
if (!raw) return "Required";
|
||||||
const trimmed = input.trim();
|
if (!/^\d+$/.test(raw)) return "Use a numeric Zalo user id";
|
||||||
if (!trimmed) return null;
|
return undefined;
|
||||||
if (/^\d+$/.test(trimmed)) return trimmed;
|
},
|
||||||
const ok = await checkZcaInstalled();
|
});
|
||||||
if (!ok) return null;
|
const normalized = String(entry).trim();
|
||||||
const result = await runZca(["friend", "find", trimmed], {
|
const merged = [
|
||||||
profile: resolved.profile,
|
...existingAllowFrom.map((item) => String(item).trim()).filter(Boolean),
|
||||||
timeout: 15000,
|
normalized,
|
||||||
});
|
];
|
||||||
if (!result.ok) return null;
|
const unique = [...new Set(merged)];
|
||||||
const parsed = parseJsonOutput<ZcaFriend[]>(result.stdout);
|
|
||||||
const rows = Array.isArray(parsed) ? parsed : [];
|
|
||||||
const match = rows[0];
|
|
||||||
if (!match?.userId) return null;
|
|
||||||
if (rows.length > 1) {
|
|
||||||
await prompter.note(
|
|
||||||
`Multiple matches for "${trimmed}", using ${match.displayName ?? match.userId}.`,
|
|
||||||
"Zalo Personal allowlist",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return String(match.userId);
|
|
||||||
};
|
|
||||||
|
|
||||||
while (true) {
|
|
||||||
const entry = await prompter.text({
|
|
||||||
message: "Zalouser allowFrom (username or user id)",
|
|
||||||
placeholder: "Alice, 123456789",
|
|
||||||
initialValue: existingAllowFrom[0] ? String(existingAllowFrom[0]) : undefined,
|
|
||||||
validate: (value) => (String(value ?? "").trim() ? undefined : "Required"),
|
|
||||||
});
|
|
||||||
const parts = parseInput(String(entry));
|
|
||||||
const results = await Promise.all(parts.map((part) => resolveUserId(part)));
|
|
||||||
const unresolved = parts.filter((_, idx) => !results[idx]);
|
|
||||||
if (unresolved.length > 0) {
|
|
||||||
await prompter.note(
|
|
||||||
`Could not resolve: ${unresolved.join(", ")}. Use numeric user ids or ensure zca is available.`,
|
|
||||||
"Zalo Personal allowlist",
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const merged = [
|
|
||||||
...existingAllowFrom.map((item) => String(item).trim()).filter(Boolean),
|
|
||||||
...(results.filter(Boolean) as string[]),
|
|
||||||
];
|
|
||||||
const unique = [...new Set(merged)];
|
|
||||||
if (accountId === DEFAULT_ACCOUNT_ID) {
|
|
||||||
return {
|
|
||||||
...cfg,
|
|
||||||
channels: {
|
|
||||||
...cfg.channels,
|
|
||||||
zalouser: {
|
|
||||||
...cfg.channels?.zalouser,
|
|
||||||
enabled: true,
|
|
||||||
dmPolicy: "allowlist",
|
|
||||||
allowFrom: unique,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
} as ClawdbotConfig;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
if (accountId === DEFAULT_ACCOUNT_ID) {
|
||||||
return {
|
return {
|
||||||
...cfg,
|
...cfg,
|
||||||
channels: {
|
channels: {
|
||||||
@@ -141,19 +93,32 @@ async function promptZalouserAllowFrom(params: {
|
|||||||
zalouser: {
|
zalouser: {
|
||||||
...cfg.channels?.zalouser,
|
...cfg.channels?.zalouser,
|
||||||
enabled: true,
|
enabled: true,
|
||||||
accounts: {
|
dmPolicy: "allowlist",
|
||||||
...(cfg.channels?.zalouser?.accounts ?? {}),
|
allowFrom: unique,
|
||||||
[accountId]: {
|
|
||||||
...(cfg.channels?.zalouser?.accounts?.[accountId] ?? {}),
|
|
||||||
enabled: cfg.channels?.zalouser?.accounts?.[accountId]?.enabled ?? true,
|
|
||||||
dmPolicy: "allowlist",
|
|
||||||
allowFrom: unique,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
} as ClawdbotConfig;
|
} as ClawdbotConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...cfg,
|
||||||
|
channels: {
|
||||||
|
...cfg.channels,
|
||||||
|
zalouser: {
|
||||||
|
...cfg.channels?.zalouser,
|
||||||
|
enabled: true,
|
||||||
|
accounts: {
|
||||||
|
...(cfg.channels?.zalouser?.accounts ?? {}),
|
||||||
|
[accountId]: {
|
||||||
|
...(cfg.channels?.zalouser?.accounts?.[accountId] ?? {}),
|
||||||
|
enabled: cfg.channels?.zalouser?.accounts?.[accountId]?.enabled ?? true,
|
||||||
|
dmPolicy: "allowlist",
|
||||||
|
allowFrom: unique,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as ClawdbotConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
function setZalouserGroupPolicy(
|
function setZalouserGroupPolicy(
|
||||||
@@ -272,17 +237,6 @@ const dmPolicy: ChannelOnboardingDmPolicy = {
|
|||||||
allowFromKey: "channels.zalouser.allowFrom",
|
allowFromKey: "channels.zalouser.allowFrom",
|
||||||
getCurrent: (cfg) => ((cfg as ClawdbotConfig).channels?.zalouser?.dmPolicy ?? "pairing") as "pairing",
|
getCurrent: (cfg) => ((cfg as ClawdbotConfig).channels?.zalouser?.dmPolicy ?? "pairing") as "pairing",
|
||||||
setPolicy: (cfg, policy) => setZalouserDmPolicy(cfg as ClawdbotConfig, policy),
|
setPolicy: (cfg, policy) => setZalouserDmPolicy(cfg as ClawdbotConfig, policy),
|
||||||
promptAllowFrom: async ({ cfg, prompter, accountId }) => {
|
|
||||||
const id =
|
|
||||||
accountId && normalizeAccountId(accountId)
|
|
||||||
? normalizeAccountId(accountId) ?? DEFAULT_ACCOUNT_ID
|
|
||||||
: resolveDefaultZalouserAccountId(cfg as ClawdbotConfig);
|
|
||||||
return promptZalouserAllowFrom({
|
|
||||||
cfg: cfg as ClawdbotConfig,
|
|
||||||
prompter,
|
|
||||||
accountId: id,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const zalouserOnboardingAdapter: ChannelOnboardingAdapter = {
|
export const zalouserOnboardingAdapter: ChannelOnboardingAdapter = {
|
||||||
|
|||||||
Generated
+8
-8
@@ -265,13 +265,7 @@ importers:
|
|||||||
specifier: 40.0.0
|
specifier: 40.0.0
|
||||||
version: 40.0.0
|
version: 40.0.0
|
||||||
|
|
||||||
extensions/memory-core:
|
extensions/memory:
|
||||||
dependencies:
|
|
||||||
clawdbot:
|
|
||||||
specifier: workspace:*
|
|
||||||
version: link:../..
|
|
||||||
|
|
||||||
extensions/memory-lancedb:
|
|
||||||
dependencies:
|
dependencies:
|
||||||
'@lancedb/lancedb':
|
'@lancedb/lancedb':
|
||||||
specifier: ^0.15.0
|
specifier: ^0.15.0
|
||||||
@@ -283,6 +277,12 @@ importers:
|
|||||||
specifier: ^4.104.0
|
specifier: ^4.104.0
|
||||||
version: 4.104.0(ws@8.19.0)(zod@3.25.76)
|
version: 4.104.0(ws@8.19.0)(zod@3.25.76)
|
||||||
|
|
||||||
|
extensions/memory-core:
|
||||||
|
dependencies:
|
||||||
|
clawdbot:
|
||||||
|
specifier: workspace:*
|
||||||
|
version: link:../..
|
||||||
|
|
||||||
extensions/msteams:
|
extensions/msteams:
|
||||||
dependencies:
|
dependencies:
|
||||||
'@microsoft/agents-hosting':
|
'@microsoft/agents-hosting':
|
||||||
@@ -6625,7 +6625,7 @@ snapshots:
|
|||||||
|
|
||||||
'@types/node-fetch@2.6.13':
|
'@types/node-fetch@2.6.13':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/node': 25.0.9
|
'@types/node': 18.19.130
|
||||||
form-data: 4.0.5
|
form-data: 4.0.5
|
||||||
|
|
||||||
'@types/node@10.17.60': {}
|
'@types/node@10.17.60': {}
|
||||||
|
|||||||
@@ -49,16 +49,6 @@ for file in "${files[@]}"; do
|
|||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
|
|
||||||
# Prevent staging node_modules even if a path is forced.
|
|
||||||
for file in "${files[@]}"; do
|
|
||||||
case "$file" in
|
|
||||||
*node_modules* | */node_modules | */node_modules/* | node_modules)
|
|
||||||
printf 'Error: node_modules paths are not allowed: %s\n' "$file" >&2
|
|
||||||
exit 1
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
last_commit_error=''
|
last_commit_error=''
|
||||||
|
|
||||||
run_git_commit() {
|
run_git_commit() {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
|
|
||||||
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
import { readdirSync, readFileSync } from 'node:fs';
|
||||||
import { join, relative } from 'node:path';
|
import { join, relative } from 'node:path';
|
||||||
|
|
||||||
process.stdout.on('error', (error) => {
|
process.stdout.on('error', (error) => {
|
||||||
@@ -11,14 +11,6 @@ process.stdout.on('error', (error) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const DOCS_DIR = join(process.cwd(), 'docs');
|
const DOCS_DIR = join(process.cwd(), 'docs');
|
||||||
if (!existsSync(DOCS_DIR)) {
|
|
||||||
console.error('docs:list: missing docs directory. Run from repo root.');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
if (!statSync(DOCS_DIR).isDirectory()) {
|
|
||||||
console.error('docs:list: docs path is not a directory.');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const EXCLUDED_DIRS = new Set(['archive', 'research']);
|
const EXCLUDED_DIRS = new Set(['archive', 'research']);
|
||||||
|
|
||||||
|
|||||||
@@ -441,19 +441,22 @@ export async function runAgentTurnWithFallback(params: {
|
|||||||
// Some embedded runs surface context overflow as an error payload instead of throwing.
|
// Some embedded runs surface context overflow as an error payload instead of throwing.
|
||||||
// Treat those as a session-level failure and auto-recover by starting a fresh session.
|
// Treat those as a session-level failure and auto-recover by starting a fresh session.
|
||||||
const embeddedError = runResult.meta?.error;
|
const embeddedError = runResult.meta?.error;
|
||||||
if (
|
if (embeddedError && isContextOverflowError(embeddedError.message)) {
|
||||||
embeddedError &&
|
if (
|
||||||
isContextOverflowError(embeddedError.message) &&
|
!didResetAfterCompactionFailure &&
|
||||||
!didResetAfterCompactionFailure &&
|
(await params.resetSessionAfterCompactionFailure(embeddedError.message))
|
||||||
(await params.resetSessionAfterCompactionFailure(embeddedError.message))
|
) {
|
||||||
) {
|
didResetAfterCompactionFailure = true;
|
||||||
didResetAfterCompactionFailure = true;
|
continue;
|
||||||
return {
|
}
|
||||||
kind: "final",
|
if (didResetAfterCompactionFailure) {
|
||||||
payload: {
|
return {
|
||||||
text: "⚠️ Context limit exceeded. I've reset our conversation to start fresh - please try again.\n\nTo prevent this, increase your compaction buffer by setting `agents.defaults.compaction.reserveTokensFloor` to 4000 or higher in your config.",
|
kind: "final",
|
||||||
},
|
payload: {
|
||||||
};
|
text: "⚠️ Context limit exceeded. I've reset our conversation to start fresh - please try again.\n\nTo prevent this, increase your compaction buffer by setting `agents.defaults.compaction.reserveTokensFloor` to 20000 or higher in your config.",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (embeddedError?.kind === "role_ordering") {
|
if (embeddedError?.kind === "role_ordering") {
|
||||||
const didReset = await params.resetSessionAfterRoleOrderingConflict(
|
const didReset = await params.resetSessionAfterRoleOrderingConflict(
|
||||||
@@ -487,10 +490,13 @@ export async function runAgentTurnWithFallback(params: {
|
|||||||
(await params.resetSessionAfterCompactionFailure(message))
|
(await params.resetSessionAfterCompactionFailure(message))
|
||||||
) {
|
) {
|
||||||
didResetAfterCompactionFailure = true;
|
didResetAfterCompactionFailure = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (isCompactionFailure && didResetAfterCompactionFailure) {
|
||||||
return {
|
return {
|
||||||
kind: "final",
|
kind: "final",
|
||||||
payload: {
|
payload: {
|
||||||
text: "⚠️ Context limit exceeded during compaction. I've reset our conversation to start fresh - please try again.\n\nTo prevent this, increase your compaction buffer by setting `agents.defaults.compaction.reserveTokensFloor` to 4000 or higher in your config.",
|
text: "⚠️ Context limit exceeded during compaction. I've reset our conversation to start fresh - please try again.\n\nTo prevent this, increase your compaction buffer by setting `agents.defaults.compaction.reserveTokensFloor` to 20000 or higher in your config.",
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
+77
-30
@@ -1,7 +1,7 @@
|
|||||||
import fs from "node:fs/promises";
|
import fs from "node:fs/promises";
|
||||||
import { tmpdir } from "node:os";
|
import { tmpdir } from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
import { describe, expect, it, vi } from "vitest";
|
||||||
import type { SessionEntry } from "../../config/sessions.js";
|
import type { SessionEntry } from "../../config/sessions.js";
|
||||||
import * as sessions from "../../config/sessions.js";
|
import * as sessions from "../../config/sessions.js";
|
||||||
import type { TypingMode } from "../../config/types.js";
|
import type { TypingMode } from "../../config/types.js";
|
||||||
@@ -121,10 +121,6 @@ function createMinimalRun(params?: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("runReplyAgent typing (heartbeat)", () => {
|
describe("runReplyAgent typing (heartbeat)", () => {
|
||||||
beforeEach(() => {
|
|
||||||
runEmbeddedPiAgentMock.mockReset();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("retries after compaction failure by resetting the session", async () => {
|
it("retries after compaction failure by resetting the session", async () => {
|
||||||
const prevStateDir = process.env.CLAWDBOT_STATE_DIR;
|
const prevStateDir = process.env.CLAWDBOT_STATE_DIR;
|
||||||
const stateDir = await fs.mkdtemp(path.join(tmpdir(), "clawdbot-session-compaction-reset-"));
|
const stateDir = await fs.mkdtemp(path.join(tmpdir(), "clawdbot-session-compaction-reset-"));
|
||||||
@@ -141,12 +137,18 @@ describe("runReplyAgent typing (heartbeat)", () => {
|
|||||||
await fs.mkdir(path.dirname(transcriptPath), { recursive: true });
|
await fs.mkdir(path.dirname(transcriptPath), { recursive: true });
|
||||||
await fs.writeFile(transcriptPath, "ok", "utf-8");
|
await fs.writeFile(transcriptPath, "ok", "utf-8");
|
||||||
|
|
||||||
runEmbeddedPiAgentMock.mockImplementationOnce(async () => {
|
runEmbeddedPiAgentMock
|
||||||
throw new Error(
|
.mockImplementationOnce(async () => {
|
||||||
'Context overflow: Summarization failed: 400 {"message":"prompt is too long"}',
|
throw new Error(
|
||||||
);
|
'Context overflow: Summarization failed: 400 {"message":"prompt is too long"}',
|
||||||
});
|
);
|
||||||
|
})
|
||||||
|
.mockImplementationOnce(async () => ({
|
||||||
|
payloads: [{ text: "ok" }],
|
||||||
|
meta: {},
|
||||||
|
}));
|
||||||
|
|
||||||
|
const callsBefore = runEmbeddedPiAgentMock.mock.calls.length;
|
||||||
const { run } = createMinimalRun({
|
const { run } = createMinimalRun({
|
||||||
sessionEntry,
|
sessionEntry,
|
||||||
sessionStore,
|
sessionStore,
|
||||||
@@ -155,11 +157,55 @@ describe("runReplyAgent typing (heartbeat)", () => {
|
|||||||
});
|
});
|
||||||
const res = await run();
|
const res = await run();
|
||||||
|
|
||||||
expect(runEmbeddedPiAgentMock).toHaveBeenCalledTimes(1);
|
expect(runEmbeddedPiAgentMock.mock.calls.length - callsBefore).toBe(2);
|
||||||
const payload = Array.isArray(res) ? res[0] : res;
|
const payload = Array.isArray(res) ? res[0] : res;
|
||||||
expect(payload).toMatchObject({
|
expect(payload).toMatchObject({ text: "ok" });
|
||||||
text: expect.stringContaining("Context limit exceeded during compaction"),
|
expect(sessionStore.main.sessionId).not.toBe(sessionId);
|
||||||
|
|
||||||
|
const persisted = JSON.parse(await fs.readFile(storePath, "utf-8"));
|
||||||
|
expect(persisted.main.sessionId).toBe(sessionStore.main.sessionId);
|
||||||
|
} finally {
|
||||||
|
if (prevStateDir) {
|
||||||
|
process.env.CLAWDBOT_STATE_DIR = prevStateDir;
|
||||||
|
} else {
|
||||||
|
delete process.env.CLAWDBOT_STATE_DIR;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it("returns a user-facing error after repeated compaction failure", async () => {
|
||||||
|
const prevStateDir = process.env.CLAWDBOT_STATE_DIR;
|
||||||
|
const stateDir = await fs.mkdtemp(path.join(tmpdir(), "clawdbot-session-compaction-repeat-"));
|
||||||
|
process.env.CLAWDBOT_STATE_DIR = stateDir;
|
||||||
|
try {
|
||||||
|
const sessionId = "session";
|
||||||
|
const storePath = path.join(stateDir, "sessions", "sessions.json");
|
||||||
|
const transcriptPath = sessions.resolveSessionTranscriptPath(sessionId);
|
||||||
|
const sessionEntry = { sessionId, updatedAt: Date.now(), sessionFile: transcriptPath };
|
||||||
|
const sessionStore = { main: sessionEntry };
|
||||||
|
|
||||||
|
await fs.mkdir(path.dirname(storePath), { recursive: true });
|
||||||
|
await fs.writeFile(storePath, JSON.stringify(sessionStore), "utf-8");
|
||||||
|
await fs.mkdir(path.dirname(transcriptPath), { recursive: true });
|
||||||
|
await fs.writeFile(transcriptPath, "ok", "utf-8");
|
||||||
|
|
||||||
|
runEmbeddedPiAgentMock.mockImplementation(async () => {
|
||||||
|
throw new Error(
|
||||||
|
'Context overflow: Summarization failed: 400 {"message":"prompt is too long"}',
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const callsBefore = runEmbeddedPiAgentMock.mock.calls.length;
|
||||||
|
const { run } = createMinimalRun({
|
||||||
|
sessionEntry,
|
||||||
|
sessionStore,
|
||||||
|
sessionKey: "main",
|
||||||
|
storePath,
|
||||||
|
});
|
||||||
|
const res = await run();
|
||||||
|
|
||||||
|
expect(runEmbeddedPiAgentMock.mock.calls.length - callsBefore).toBe(2);
|
||||||
|
const payload = Array.isArray(res) ? res[0] : res;
|
||||||
|
expect(payload.text).toContain("Context limit exceeded");
|
||||||
expect(payload.text?.toLowerCase()).toContain("reset");
|
expect(payload.text?.toLowerCase()).toContain("reset");
|
||||||
expect(sessionStore.main.sessionId).not.toBe(sessionId);
|
expect(sessionStore.main.sessionId).not.toBe(sessionId);
|
||||||
|
|
||||||
@@ -173,7 +219,6 @@ describe("runReplyAgent typing (heartbeat)", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
it("retries after context overflow payload by resetting the session", async () => {
|
it("retries after context overflow payload by resetting the session", async () => {
|
||||||
const prevStateDir = process.env.CLAWDBOT_STATE_DIR;
|
const prevStateDir = process.env.CLAWDBOT_STATE_DIR;
|
||||||
const stateDir = await fs.mkdtemp(path.join(tmpdir(), "clawdbot-session-overflow-reset-"));
|
const stateDir = await fs.mkdtemp(path.join(tmpdir(), "clawdbot-session-overflow-reset-"));
|
||||||
@@ -190,18 +235,24 @@ describe("runReplyAgent typing (heartbeat)", () => {
|
|||||||
await fs.mkdir(path.dirname(transcriptPath), { recursive: true });
|
await fs.mkdir(path.dirname(transcriptPath), { recursive: true });
|
||||||
await fs.writeFile(transcriptPath, "ok", "utf-8");
|
await fs.writeFile(transcriptPath, "ok", "utf-8");
|
||||||
|
|
||||||
runEmbeddedPiAgentMock.mockImplementationOnce(async () => ({
|
runEmbeddedPiAgentMock
|
||||||
payloads: [{ text: "Context overflow: prompt too large", isError: true }],
|
.mockImplementationOnce(async () => ({
|
||||||
meta: {
|
payloads: [{ text: "Context overflow: prompt too large", isError: true }],
|
||||||
durationMs: 1,
|
meta: {
|
||||||
error: {
|
durationMs: 1,
|
||||||
kind: "context_overflow",
|
error: {
|
||||||
message:
|
kind: "context_overflow",
|
||||||
'Context overflow: Summarization failed: 400 {"message":"prompt is too long"}',
|
message:
|
||||||
|
'Context overflow: Summarization failed: 400 {"message":"prompt is too long"}',
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
}))
|
||||||
}));
|
.mockImplementationOnce(async () => ({
|
||||||
|
payloads: [{ text: "ok" }],
|
||||||
|
meta: { durationMs: 1 },
|
||||||
|
}));
|
||||||
|
|
||||||
|
const callsBefore = runEmbeddedPiAgentMock.mock.calls.length;
|
||||||
const { run } = createMinimalRun({
|
const { run } = createMinimalRun({
|
||||||
sessionEntry,
|
sessionEntry,
|
||||||
sessionStore,
|
sessionStore,
|
||||||
@@ -210,12 +261,9 @@ describe("runReplyAgent typing (heartbeat)", () => {
|
|||||||
});
|
});
|
||||||
const res = await run();
|
const res = await run();
|
||||||
|
|
||||||
expect(runEmbeddedPiAgentMock).toHaveBeenCalledTimes(1);
|
expect(runEmbeddedPiAgentMock.mock.calls.length - callsBefore).toBe(2);
|
||||||
const payload = Array.isArray(res) ? res[0] : res;
|
const payload = Array.isArray(res) ? res[0] : res;
|
||||||
expect(payload).toMatchObject({
|
expect(payload).toMatchObject({ text: "ok" });
|
||||||
text: expect.stringContaining("Context limit exceeded"),
|
|
||||||
});
|
|
||||||
expect(payload.text?.toLowerCase()).toContain("reset");
|
|
||||||
expect(sessionStore.main.sessionId).not.toBe(sessionId);
|
expect(sessionStore.main.sessionId).not.toBe(sessionId);
|
||||||
|
|
||||||
const persisted = JSON.parse(await fs.readFile(storePath, "utf-8"));
|
const persisted = JSON.parse(await fs.readFile(storePath, "utf-8"));
|
||||||
@@ -228,7 +276,6 @@ describe("runReplyAgent typing (heartbeat)", () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
it("resets the session after role ordering payloads", async () => {
|
it("resets the session after role ordering payloads", async () => {
|
||||||
const prevStateDir = process.env.CLAWDBOT_STATE_DIR;
|
const prevStateDir = process.env.CLAWDBOT_STATE_DIR;
|
||||||
const stateDir = await fs.mkdtemp(path.join(tmpdir(), "clawdbot-session-role-ordering-"));
|
const stateDir = await fs.mkdtemp(path.join(tmpdir(), "clawdbot-session-role-ordering-"));
|
||||||
|
|||||||
@@ -161,14 +161,11 @@ export async function runReplyAgent(params: {
|
|||||||
const steered = queueEmbeddedPiMessage(followupRun.run.sessionId, followupRun.prompt);
|
const steered = queueEmbeddedPiMessage(followupRun.run.sessionId, followupRun.prompt);
|
||||||
if (steered && !shouldFollowup) {
|
if (steered && !shouldFollowup) {
|
||||||
if (activeSessionEntry && activeSessionStore && sessionKey) {
|
if (activeSessionEntry && activeSessionStore && sessionKey) {
|
||||||
const updatedAt = Date.now();
|
activeSessionEntry.updatedAt = Date.now();
|
||||||
activeSessionEntry.updatedAt = updatedAt;
|
|
||||||
activeSessionStore[sessionKey] = activeSessionEntry;
|
activeSessionStore[sessionKey] = activeSessionEntry;
|
||||||
if (storePath) {
|
if (storePath) {
|
||||||
await updateSessionStoreEntry({
|
await updateSessionStore(storePath, (store) => {
|
||||||
storePath,
|
store[sessionKey] = activeSessionEntry as SessionEntry;
|
||||||
sessionKey,
|
|
||||||
update: async () => ({ updatedAt }),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -180,14 +177,11 @@ export async function runReplyAgent(params: {
|
|||||||
if (isActive && (shouldFollowup || resolvedQueue.mode === "steer")) {
|
if (isActive && (shouldFollowup || resolvedQueue.mode === "steer")) {
|
||||||
enqueueFollowupRun(queueKey, followupRun, resolvedQueue);
|
enqueueFollowupRun(queueKey, followupRun, resolvedQueue);
|
||||||
if (activeSessionEntry && activeSessionStore && sessionKey) {
|
if (activeSessionEntry && activeSessionStore && sessionKey) {
|
||||||
const updatedAt = Date.now();
|
activeSessionEntry.updatedAt = Date.now();
|
||||||
activeSessionEntry.updatedAt = updatedAt;
|
|
||||||
activeSessionStore[sessionKey] = activeSessionEntry;
|
activeSessionStore[sessionKey] = activeSessionEntry;
|
||||||
if (storePath) {
|
if (storePath) {
|
||||||
await updateSessionStoreEntry({
|
await updateSessionStore(storePath, (store) => {
|
||||||
storePath,
|
store[sessionKey] = activeSessionEntry as SessionEntry;
|
||||||
sessionKey,
|
|
||||||
update: async () => ({ updatedAt }),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -334,18 +328,12 @@ export async function runReplyAgent(params: {
|
|||||||
sessionKey &&
|
sessionKey &&
|
||||||
activeSessionEntry.groupActivationNeedsSystemIntro
|
activeSessionEntry.groupActivationNeedsSystemIntro
|
||||||
) {
|
) {
|
||||||
const updatedAt = Date.now();
|
|
||||||
activeSessionEntry.groupActivationNeedsSystemIntro = false;
|
activeSessionEntry.groupActivationNeedsSystemIntro = false;
|
||||||
activeSessionEntry.updatedAt = updatedAt;
|
activeSessionEntry.updatedAt = Date.now();
|
||||||
activeSessionStore[sessionKey] = activeSessionEntry;
|
activeSessionStore[sessionKey] = activeSessionEntry;
|
||||||
if (storePath) {
|
if (storePath) {
|
||||||
await updateSessionStoreEntry({
|
await updateSessionStore(storePath, (store) => {
|
||||||
storePath,
|
store[sessionKey] = activeSessionEntry as SessionEntry;
|
||||||
sessionKey,
|
|
||||||
update: async () => ({
|
|
||||||
groupActivationNeedsSystemIntro: false,
|
|
||||||
updatedAt,
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
c51e9080b032ccb0dd153452854f2ffdaca8e1db14d7b98ed56cca8f0f1a5257
|
e8286176aaf2c0daf5f4b30dd221c3d7aa1aec8329d6865cac3d9636fd7f08f6
|
||||||
+17439
-15246
File diff suppressed because it is too large.
Load diff
@@ -69,11 +69,6 @@ export type ChannelOnboardingDmPolicy = {
|
|||||||
allowFromKey: string;
|
allowFromKey: string;
|
||||||
getCurrent: (cfg: ClawdbotConfig) => DmPolicy;
|
getCurrent: (cfg: ClawdbotConfig) => DmPolicy;
|
||||||
setPolicy: (cfg: ClawdbotConfig, policy: DmPolicy) => ClawdbotConfig;
|
setPolicy: (cfg: ClawdbotConfig, policy: DmPolicy) => ClawdbotConfig;
|
||||||
promptAllowFrom?: (params: {
|
|
||||||
cfg: ClawdbotConfig;
|
|
||||||
prompter: WizardPrompter;
|
|
||||||
accountId?: string;
|
|
||||||
}) => Promise<ClawdbotConfig>;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ChannelOnboardingAdapter = {
|
export type ChannelOnboardingAdapter = {
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import {
|
|||||||
resolveDiscordAccount,
|
resolveDiscordAccount,
|
||||||
} from "../../../discord/accounts.js";
|
} from "../../../discord/accounts.js";
|
||||||
import { normalizeDiscordSlug } from "../../../discord/monitor/allow-list.js";
|
import { normalizeDiscordSlug } from "../../../discord/monitor/allow-list.js";
|
||||||
import { resolveDiscordUserAllowlist } from "../../../discord/resolve-users.js";
|
|
||||||
import {
|
import {
|
||||||
resolveDiscordChannelAllowlist,
|
resolveDiscordChannelAllowlist,
|
||||||
type DiscordChannelResolution,
|
type DiscordChannelResolution,
|
||||||
@@ -149,113 +148,6 @@ function setDiscordGuildChannelAllowlist(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function setDiscordAllowFrom(cfg: ClawdbotConfig, allowFrom: string[]): ClawdbotConfig {
|
|
||||||
return {
|
|
||||||
...cfg,
|
|
||||||
channels: {
|
|
||||||
...cfg.channels,
|
|
||||||
discord: {
|
|
||||||
...cfg.channels?.discord,
|
|
||||||
dm: {
|
|
||||||
...cfg.channels?.discord?.dm,
|
|
||||||
enabled: cfg.channels?.discord?.dm?.enabled ?? true,
|
|
||||||
allowFrom,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseDiscordAllowFromInput(raw: string): string[] {
|
|
||||||
return raw
|
|
||||||
.split(/[\n,;]+/g)
|
|
||||||
.map((entry) => entry.trim())
|
|
||||||
.filter(Boolean);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function promptDiscordAllowFrom(params: {
|
|
||||||
cfg: ClawdbotConfig;
|
|
||||||
prompter: WizardPrompter;
|
|
||||||
accountId?: string;
|
|
||||||
}): Promise<ClawdbotConfig> {
|
|
||||||
const accountId =
|
|
||||||
params.accountId && normalizeAccountId(params.accountId)
|
|
||||||
? normalizeAccountId(params.accountId) ?? DEFAULT_ACCOUNT_ID
|
|
||||||
: resolveDefaultDiscordAccountId(params.cfg);
|
|
||||||
const resolved = resolveDiscordAccount({ cfg: params.cfg, accountId });
|
|
||||||
const token = resolved.token;
|
|
||||||
const existing = params.cfg.channels?.discord?.dm?.allowFrom ?? [];
|
|
||||||
await params.prompter.note(
|
|
||||||
[
|
|
||||||
"Allowlist Discord DMs by username (we resolve to user ids).",
|
|
||||||
"Examples:",
|
|
||||||
"- 123456789012345678",
|
|
||||||
"- @alice",
|
|
||||||
"- alice#1234",
|
|
||||||
"Multiple entries: comma-separated.",
|
|
||||||
`Docs: ${formatDocsLink("/discord", "discord")}`,
|
|
||||||
].join("\n"),
|
|
||||||
"Discord allowlist",
|
|
||||||
);
|
|
||||||
|
|
||||||
const parseInputs = (value: string) => parseDiscordAllowFromInput(value);
|
|
||||||
const parseId = (value: string) => {
|
|
||||||
const trimmed = value.trim();
|
|
||||||
if (!trimmed) return null;
|
|
||||||
const mention = trimmed.match(/^<@!?(\d+)>$/);
|
|
||||||
if (mention) return mention[1];
|
|
||||||
const prefixed = trimmed.replace(/^(user:|discord:)/i, "");
|
|
||||||
if (/^\d+$/.test(prefixed)) return prefixed;
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
while (true) {
|
|
||||||
const entry = await params.prompter.text({
|
|
||||||
message: "Discord allowFrom (usernames or ids)",
|
|
||||||
placeholder: "@alice, 123456789012345678",
|
|
||||||
initialValue: existing[0] ? String(existing[0]) : undefined,
|
|
||||||
validate: (value) => (String(value ?? "").trim() ? undefined : "Required"),
|
|
||||||
});
|
|
||||||
const parts = parseInputs(String(entry));
|
|
||||||
if (!token) {
|
|
||||||
const ids = parts.map(parseId).filter(Boolean) as string[];
|
|
||||||
if (ids.length !== parts.length) {
|
|
||||||
await params.prompter.note(
|
|
||||||
"Bot token missing; use numeric user ids (or mention form) only.",
|
|
||||||
"Discord allowlist",
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const unique = [...new Set([...existing.map((v) => String(v).trim()), ...ids])].filter(
|
|
||||||
Boolean,
|
|
||||||
);
|
|
||||||
return setDiscordAllowFrom(params.cfg, unique);
|
|
||||||
}
|
|
||||||
|
|
||||||
const results = await resolveDiscordUserAllowlist({
|
|
||||||
token,
|
|
||||||
entries: parts,
|
|
||||||
}).catch(() => null);
|
|
||||||
if (!results) {
|
|
||||||
await params.prompter.note("Failed to resolve usernames. Try again.", "Discord allowlist");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const unresolved = results.filter((res) => !res.resolved || !res.id);
|
|
||||||
if (unresolved.length > 0) {
|
|
||||||
await params.prompter.note(
|
|
||||||
`Could not resolve: ${unresolved.map((res) => res.input).join(", ")}`,
|
|
||||||
"Discord allowlist",
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const ids = results.map((res) => res.id as string);
|
|
||||||
const unique = [
|
|
||||||
...new Set([...existing.map((v) => String(v).trim()).filter(Boolean), ...ids]),
|
|
||||||
];
|
|
||||||
return setDiscordAllowFrom(params.cfg, unique);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const dmPolicy: ChannelOnboardingDmPolicy = {
|
const dmPolicy: ChannelOnboardingDmPolicy = {
|
||||||
label: "Discord",
|
label: "Discord",
|
||||||
channel,
|
channel,
|
||||||
@@ -263,7 +155,6 @@ const dmPolicy: ChannelOnboardingDmPolicy = {
|
|||||||
allowFromKey: "channels.discord.dm.allowFrom",
|
allowFromKey: "channels.discord.dm.allowFrom",
|
||||||
getCurrent: (cfg) => cfg.channels?.discord?.dm?.policy ?? "pairing",
|
getCurrent: (cfg) => cfg.channels?.discord?.dm?.policy ?? "pairing",
|
||||||
setPolicy: (cfg, policy) => setDiscordDmPolicy(cfg, policy),
|
setPolicy: (cfg, policy) => setDiscordDmPolicy(cfg, policy),
|
||||||
promptAllowFrom: promptDiscordAllowFrom,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const discordOnboardingAdapter: ChannelOnboardingAdapter = {
|
export const discordOnboardingAdapter: ChannelOnboardingAdapter = {
|
||||||
|
|||||||
@@ -6,10 +6,8 @@ import {
|
|||||||
resolveDefaultIMessageAccountId,
|
resolveDefaultIMessageAccountId,
|
||||||
resolveIMessageAccount,
|
resolveIMessageAccount,
|
||||||
} from "../../../imessage/accounts.js";
|
} from "../../../imessage/accounts.js";
|
||||||
import { normalizeIMessageHandle } from "../../../imessage/targets.js";
|
|
||||||
import { DEFAULT_ACCOUNT_ID, normalizeAccountId } from "../../../routing/session-key.js";
|
import { DEFAULT_ACCOUNT_ID, normalizeAccountId } from "../../../routing/session-key.js";
|
||||||
import { formatDocsLink } from "../../../terminal/links.js";
|
import { formatDocsLink } from "../../../terminal/links.js";
|
||||||
import type { WizardPrompter } from "../../../wizard/prompts.js";
|
|
||||||
import type { ChannelOnboardingAdapter, ChannelOnboardingDmPolicy } from "../onboarding-types.js";
|
import type { ChannelOnboardingAdapter, ChannelOnboardingDmPolicy } from "../onboarding-types.js";
|
||||||
import { addWildcardAllowFrom, promptAccountId } from "./helpers.js";
|
import { addWildcardAllowFrom, promptAccountId } from "./helpers.js";
|
||||||
|
|
||||||
@@ -31,105 +29,6 @@ function setIMessageDmPolicy(cfg: ClawdbotConfig, dmPolicy: DmPolicy) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function setIMessageAllowFrom(
|
|
||||||
cfg: ClawdbotConfig,
|
|
||||||
accountId: string,
|
|
||||||
allowFrom: string[],
|
|
||||||
): ClawdbotConfig {
|
|
||||||
if (accountId === DEFAULT_ACCOUNT_ID) {
|
|
||||||
return {
|
|
||||||
...cfg,
|
|
||||||
channels: {
|
|
||||||
...cfg.channels,
|
|
||||||
imessage: {
|
|
||||||
...cfg.channels?.imessage,
|
|
||||||
allowFrom,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
...cfg,
|
|
||||||
channels: {
|
|
||||||
...cfg.channels,
|
|
||||||
imessage: {
|
|
||||||
...cfg.channels?.imessage,
|
|
||||||
accounts: {
|
|
||||||
...cfg.channels?.imessage?.accounts,
|
|
||||||
[accountId]: {
|
|
||||||
...cfg.channels?.imessage?.accounts?.[accountId],
|
|
||||||
allowFrom,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseIMessageAllowFromInput(raw: string): string[] {
|
|
||||||
return raw
|
|
||||||
.split(/[\n,;]+/g)
|
|
||||||
.map((entry) => entry.trim())
|
|
||||||
.filter(Boolean);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function promptIMessageAllowFrom(params: {
|
|
||||||
cfg: ClawdbotConfig;
|
|
||||||
prompter: WizardPrompter;
|
|
||||||
accountId?: string;
|
|
||||||
}): Promise<ClawdbotConfig> {
|
|
||||||
const accountId =
|
|
||||||
params.accountId && normalizeAccountId(params.accountId)
|
|
||||||
? normalizeAccountId(params.accountId) ?? DEFAULT_ACCOUNT_ID
|
|
||||||
: resolveDefaultIMessageAccountId(params.cfg);
|
|
||||||
const resolved = resolveIMessageAccount({ cfg: params.cfg, accountId });
|
|
||||||
const existing = resolved.config.allowFrom ?? [];
|
|
||||||
await params.prompter.note(
|
|
||||||
[
|
|
||||||
"Allowlist iMessage DMs by handle or chat target.",
|
|
||||||
"Examples:",
|
|
||||||
"- +15555550123",
|
|
||||||
"- user@example.com",
|
|
||||||
"- chat_id:123",
|
|
||||||
"- chat_guid:... or chat_identifier:...",
|
|
||||||
"Multiple entries: comma-separated.",
|
|
||||||
`Docs: ${formatDocsLink("/imessage", "imessage")}`,
|
|
||||||
].join("\n"),
|
|
||||||
"iMessage allowlist",
|
|
||||||
);
|
|
||||||
const entry = await params.prompter.text({
|
|
||||||
message: "iMessage allowFrom (handle or chat_id)",
|
|
||||||
placeholder: "+15555550123, user@example.com, chat_id:123",
|
|
||||||
initialValue: existing[0] ? String(existing[0]) : undefined,
|
|
||||||
validate: (value) => {
|
|
||||||
const raw = String(value ?? "").trim();
|
|
||||||
if (!raw) return "Required";
|
|
||||||
const parts = parseIMessageAllowFromInput(raw);
|
|
||||||
for (const part of parts) {
|
|
||||||
if (part === "*") continue;
|
|
||||||
if (part.toLowerCase().startsWith("chat_id:")) {
|
|
||||||
const id = part.slice("chat_id:".length).trim();
|
|
||||||
if (!/^\d+$/.test(id)) return `Invalid chat_id: ${part}`;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (part.toLowerCase().startsWith("chat_guid:")) {
|
|
||||||
if (!part.slice("chat_guid:".length).trim()) return "Invalid chat_guid entry";
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (part.toLowerCase().startsWith("chat_identifier:")) {
|
|
||||||
if (!part.slice("chat_identifier:".length).trim()) return "Invalid chat_identifier entry";
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!normalizeIMessageHandle(part)) return `Invalid handle: ${part}`;
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const parts = parseIMessageAllowFromInput(String(entry));
|
|
||||||
const unique = [...new Set(parts)];
|
|
||||||
return setIMessageAllowFrom(params.cfg, accountId, unique);
|
|
||||||
}
|
|
||||||
|
|
||||||
const dmPolicy: ChannelOnboardingDmPolicy = {
|
const dmPolicy: ChannelOnboardingDmPolicy = {
|
||||||
label: "iMessage",
|
label: "iMessage",
|
||||||
channel,
|
channel,
|
||||||
@@ -137,7 +36,6 @@ const dmPolicy: ChannelOnboardingDmPolicy = {
|
|||||||
allowFromKey: "channels.imessage.allowFrom",
|
allowFromKey: "channels.imessage.allowFrom",
|
||||||
getCurrent: (cfg) => cfg.channels?.imessage?.dmPolicy ?? "pairing",
|
getCurrent: (cfg) => cfg.channels?.imessage?.dmPolicy ?? "pairing",
|
||||||
setPolicy: (cfg, policy) => setIMessageDmPolicy(cfg, policy),
|
setPolicy: (cfg, policy) => setIMessageDmPolicy(cfg, policy),
|
||||||
promptAllowFrom: promptIMessageAllowFrom,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const imessageOnboardingAdapter: ChannelOnboardingAdapter = {
|
export const imessageOnboardingAdapter: ChannelOnboardingAdapter = {
|
||||||
|
|||||||
@@ -9,8 +9,6 @@ import {
|
|||||||
resolveSignalAccount,
|
resolveSignalAccount,
|
||||||
} from "../../../signal/accounts.js";
|
} from "../../../signal/accounts.js";
|
||||||
import { formatDocsLink } from "../../../terminal/links.js";
|
import { formatDocsLink } from "../../../terminal/links.js";
|
||||||
import { normalizeE164 } from "../../../utils.js";
|
|
||||||
import type { WizardPrompter } from "../../../wizard/prompts.js";
|
|
||||||
import type { ChannelOnboardingAdapter, ChannelOnboardingDmPolicy } from "../onboarding-types.js";
|
import type { ChannelOnboardingAdapter, ChannelOnboardingDmPolicy } from "../onboarding-types.js";
|
||||||
import { addWildcardAllowFrom, promptAccountId } from "./helpers.js";
|
import { addWildcardAllowFrom, promptAccountId } from "./helpers.js";
|
||||||
|
|
||||||
@@ -32,107 +30,6 @@ function setSignalDmPolicy(cfg: ClawdbotConfig, dmPolicy: DmPolicy) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function setSignalAllowFrom(
|
|
||||||
cfg: ClawdbotConfig,
|
|
||||||
accountId: string,
|
|
||||||
allowFrom: string[],
|
|
||||||
): ClawdbotConfig {
|
|
||||||
if (accountId === DEFAULT_ACCOUNT_ID) {
|
|
||||||
return {
|
|
||||||
...cfg,
|
|
||||||
channels: {
|
|
||||||
...cfg.channels,
|
|
||||||
signal: {
|
|
||||||
...cfg.channels?.signal,
|
|
||||||
allowFrom,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
...cfg,
|
|
||||||
channels: {
|
|
||||||
...cfg.channels,
|
|
||||||
signal: {
|
|
||||||
...cfg.channels?.signal,
|
|
||||||
accounts: {
|
|
||||||
...cfg.channels?.signal?.accounts,
|
|
||||||
[accountId]: {
|
|
||||||
...cfg.channels?.signal?.accounts?.[accountId],
|
|
||||||
allowFrom,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseSignalAllowFromInput(raw: string): string[] {
|
|
||||||
return raw
|
|
||||||
.split(/[\n,;]+/g)
|
|
||||||
.map((entry) => entry.trim())
|
|
||||||
.filter(Boolean);
|
|
||||||
}
|
|
||||||
|
|
||||||
function isUuidLike(value: string): boolean {
|
|
||||||
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function promptSignalAllowFrom(params: {
|
|
||||||
cfg: ClawdbotConfig;
|
|
||||||
prompter: WizardPrompter;
|
|
||||||
accountId?: string;
|
|
||||||
}): Promise<ClawdbotConfig> {
|
|
||||||
const accountId =
|
|
||||||
params.accountId && normalizeAccountId(params.accountId)
|
|
||||||
? normalizeAccountId(params.accountId) ?? DEFAULT_ACCOUNT_ID
|
|
||||||
: resolveDefaultSignalAccountId(params.cfg);
|
|
||||||
const resolved = resolveSignalAccount({ cfg: params.cfg, accountId });
|
|
||||||
const existing = resolved.config.allowFrom ?? [];
|
|
||||||
await params.prompter.note(
|
|
||||||
[
|
|
||||||
"Allowlist Signal DMs by sender id.",
|
|
||||||
"Examples:",
|
|
||||||
"- +15555550123",
|
|
||||||
"- uuid:123e4567-e89b-12d3-a456-426614174000",
|
|
||||||
"Multiple entries: comma-separated.",
|
|
||||||
`Docs: ${formatDocsLink("/signal", "signal")}`,
|
|
||||||
].join("\n"),
|
|
||||||
"Signal allowlist",
|
|
||||||
);
|
|
||||||
const entry = await params.prompter.text({
|
|
||||||
message: "Signal allowFrom (E.164 or uuid)",
|
|
||||||
placeholder: "+15555550123, uuid:123e4567-e89b-12d3-a456-426614174000",
|
|
||||||
initialValue: existing[0] ? String(existing[0]) : undefined,
|
|
||||||
validate: (value) => {
|
|
||||||
const raw = String(value ?? "").trim();
|
|
||||||
if (!raw) return "Required";
|
|
||||||
const parts = parseSignalAllowFromInput(raw);
|
|
||||||
for (const part of parts) {
|
|
||||||
if (part === "*") continue;
|
|
||||||
if (part.toLowerCase().startsWith("uuid:")) {
|
|
||||||
if (!part.slice("uuid:".length).trim()) return "Invalid uuid entry";
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (isUuidLike(part)) continue;
|
|
||||||
if (!normalizeE164(part)) return `Invalid entry: ${part}`;
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const parts = parseSignalAllowFromInput(String(entry));
|
|
||||||
const normalized = parts
|
|
||||||
.map((part) => {
|
|
||||||
if (part === "*") return "*";
|
|
||||||
if (part.toLowerCase().startsWith("uuid:")) return `uuid:${part.slice(5).trim()}`;
|
|
||||||
if (isUuidLike(part)) return `uuid:${part}`;
|
|
||||||
return normalizeE164(part);
|
|
||||||
})
|
|
||||||
.filter(Boolean);
|
|
||||||
const unique = [...new Set(normalized)];
|
|
||||||
return setSignalAllowFrom(params.cfg, accountId, unique);
|
|
||||||
}
|
|
||||||
|
|
||||||
const dmPolicy: ChannelOnboardingDmPolicy = {
|
const dmPolicy: ChannelOnboardingDmPolicy = {
|
||||||
label: "Signal",
|
label: "Signal",
|
||||||
channel,
|
channel,
|
||||||
@@ -140,7 +37,6 @@ const dmPolicy: ChannelOnboardingDmPolicy = {
|
|||||||
allowFromKey: "channels.signal.allowFrom",
|
allowFromKey: "channels.signal.allowFrom",
|
||||||
getCurrent: (cfg) => cfg.channels?.signal?.dmPolicy ?? "pairing",
|
getCurrent: (cfg) => cfg.channels?.signal?.dmPolicy ?? "pairing",
|
||||||
setPolicy: (cfg, policy) => setSignalDmPolicy(cfg, policy),
|
setPolicy: (cfg, policy) => setSignalDmPolicy(cfg, policy),
|
||||||
promptAllowFrom: promptSignalAllowFrom,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const signalOnboardingAdapter: ChannelOnboardingAdapter = {
|
export const signalOnboardingAdapter: ChannelOnboardingAdapter = {
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import {
|
|||||||
resolveSlackAccount,
|
resolveSlackAccount,
|
||||||
} from "../../../slack/accounts.js";
|
} from "../../../slack/accounts.js";
|
||||||
import { resolveSlackChannelAllowlist } from "../../../slack/resolve-channels.js";
|
import { resolveSlackChannelAllowlist } from "../../../slack/resolve-channels.js";
|
||||||
import { resolveSlackUserAllowlist } from "../../../slack/resolve-users.js";
|
|
||||||
import { formatDocsLink } from "../../../terminal/links.js";
|
import { formatDocsLink } from "../../../terminal/links.js";
|
||||||
import type { WizardPrompter } from "../../../wizard/prompts.js";
|
import type { WizardPrompter } from "../../../wizard/prompts.js";
|
||||||
import type { ChannelOnboardingAdapter, ChannelOnboardingDmPolicy } from "../onboarding-types.js";
|
import type { ChannelOnboardingAdapter, ChannelOnboardingDmPolicy } from "../onboarding-types.js";
|
||||||
@@ -201,111 +200,6 @@ function setSlackChannelAllowlist(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function setSlackAllowFrom(cfg: ClawdbotConfig, allowFrom: string[]): ClawdbotConfig {
|
|
||||||
return {
|
|
||||||
...cfg,
|
|
||||||
channels: {
|
|
||||||
...cfg.channels,
|
|
||||||
slack: {
|
|
||||||
...cfg.channels?.slack,
|
|
||||||
dm: {
|
|
||||||
...cfg.channels?.slack?.dm,
|
|
||||||
enabled: cfg.channels?.slack?.dm?.enabled ?? true,
|
|
||||||
allowFrom,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseSlackAllowFromInput(raw: string): string[] {
|
|
||||||
return raw
|
|
||||||
.split(/[\n,;]+/g)
|
|
||||||
.map((entry) => entry.trim())
|
|
||||||
.filter(Boolean);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function promptSlackAllowFrom(params: {
|
|
||||||
cfg: ClawdbotConfig;
|
|
||||||
prompter: WizardPrompter;
|
|
||||||
accountId?: string;
|
|
||||||
}): Promise<ClawdbotConfig> {
|
|
||||||
const accountId =
|
|
||||||
params.accountId && normalizeAccountId(params.accountId)
|
|
||||||
? normalizeAccountId(params.accountId) ?? DEFAULT_ACCOUNT_ID
|
|
||||||
: resolveDefaultSlackAccountId(params.cfg);
|
|
||||||
const resolved = resolveSlackAccount({ cfg: params.cfg, accountId });
|
|
||||||
const token = resolved.config.userToken ?? resolved.config.botToken ?? "";
|
|
||||||
const existing = params.cfg.channels?.slack?.dm?.allowFrom ?? [];
|
|
||||||
await params.prompter.note(
|
|
||||||
[
|
|
||||||
"Allowlist Slack DMs by username (we resolve to user ids).",
|
|
||||||
"Examples:",
|
|
||||||
"- U12345678",
|
|
||||||
"- @alice",
|
|
||||||
"Multiple entries: comma-separated.",
|
|
||||||
`Docs: ${formatDocsLink("/slack", "slack")}`,
|
|
||||||
].join("\n"),
|
|
||||||
"Slack allowlist",
|
|
||||||
);
|
|
||||||
const parseInputs = (value: string) => parseSlackAllowFromInput(value);
|
|
||||||
const parseId = (value: string) => {
|
|
||||||
const trimmed = value.trim();
|
|
||||||
if (!trimmed) return null;
|
|
||||||
const mention = trimmed.match(/^<@([A-Z0-9]+)>$/i);
|
|
||||||
if (mention) return mention[1]?.toUpperCase();
|
|
||||||
const prefixed = trimmed.replace(/^(slack:|user:)/i, "");
|
|
||||||
if (/^[A-Z][A-Z0-9]+$/i.test(prefixed)) return prefixed.toUpperCase();
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
while (true) {
|
|
||||||
const entry = await params.prompter.text({
|
|
||||||
message: "Slack allowFrom (usernames or ids)",
|
|
||||||
placeholder: "@alice, U12345678",
|
|
||||||
initialValue: existing[0] ? String(existing[0]) : undefined,
|
|
||||||
validate: (value) => (String(value ?? "").trim() ? undefined : "Required"),
|
|
||||||
});
|
|
||||||
const parts = parseInputs(String(entry));
|
|
||||||
if (!token) {
|
|
||||||
const ids = parts.map(parseId).filter(Boolean) as string[];
|
|
||||||
if (ids.length !== parts.length) {
|
|
||||||
await params.prompter.note(
|
|
||||||
"Slack token missing; use user ids (or mention form) only.",
|
|
||||||
"Slack allowlist",
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const unique = [...new Set([...existing.map((v) => String(v).trim()), ...ids])].filter(
|
|
||||||
Boolean,
|
|
||||||
);
|
|
||||||
return setSlackAllowFrom(params.cfg, unique);
|
|
||||||
}
|
|
||||||
|
|
||||||
const results = await resolveSlackUserAllowlist({
|
|
||||||
token,
|
|
||||||
entries: parts,
|
|
||||||
}).catch(() => null);
|
|
||||||
if (!results) {
|
|
||||||
await params.prompter.note("Failed to resolve usernames. Try again.", "Slack allowlist");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const unresolved = results.filter((res) => !res.resolved || !res.id);
|
|
||||||
if (unresolved.length > 0) {
|
|
||||||
await params.prompter.note(
|
|
||||||
`Could not resolve: ${unresolved.map((res) => res.input).join(", ")}`,
|
|
||||||
"Slack allowlist",
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const ids = results.map((res) => res.id as string);
|
|
||||||
const unique = [
|
|
||||||
...new Set([...existing.map((v) => String(v).trim()).filter(Boolean), ...ids]),
|
|
||||||
];
|
|
||||||
return setSlackAllowFrom(params.cfg, unique);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const dmPolicy: ChannelOnboardingDmPolicy = {
|
const dmPolicy: ChannelOnboardingDmPolicy = {
|
||||||
label: "Slack",
|
label: "Slack",
|
||||||
channel,
|
channel,
|
||||||
@@ -313,7 +207,6 @@ const dmPolicy: ChannelOnboardingDmPolicy = {
|
|||||||
allowFromKey: "channels.slack.dm.allowFrom",
|
allowFromKey: "channels.slack.dm.allowFrom",
|
||||||
getCurrent: (cfg) => cfg.channels?.slack?.dm?.policy ?? "pairing",
|
getCurrent: (cfg) => cfg.channels?.slack?.dm?.policy ?? "pairing",
|
||||||
setPolicy: (cfg, policy) => setSlackDmPolicy(cfg, policy),
|
setPolicy: (cfg, policy) => setSlackDmPolicy(cfg, policy),
|
||||||
promptAllowFrom: promptSlackAllowFrom,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const slackOnboardingAdapter: ChannelOnboardingAdapter = {
|
export const slackOnboardingAdapter: ChannelOnboardingAdapter = {
|
||||||
|
|||||||
@@ -65,59 +65,21 @@ async function promptTelegramAllowFrom(params: {
|
|||||||
const resolved = resolveTelegramAccount({ cfg, accountId });
|
const resolved = resolveTelegramAccount({ cfg, accountId });
|
||||||
const existingAllowFrom = resolved.config.allowFrom ?? [];
|
const existingAllowFrom = resolved.config.allowFrom ?? [];
|
||||||
await noteTelegramUserIdHelp(prompter);
|
await noteTelegramUserIdHelp(prompter);
|
||||||
|
const entry = await prompter.text({
|
||||||
const token = resolved.token;
|
message: "Telegram allowFrom (user id)",
|
||||||
if (!token) {
|
placeholder: "123456789",
|
||||||
await prompter.note("Telegram token missing; username lookup is unavailable.", "Telegram");
|
initialValue: existingAllowFrom[0] ? String(existingAllowFrom[0]) : undefined,
|
||||||
}
|
validate: (value) => {
|
||||||
|
const raw = String(value ?? "").trim();
|
||||||
const resolveTelegramUserId = async (raw: string): Promise<string | null> => {
|
if (!raw) return "Required";
|
||||||
const trimmed = raw.trim();
|
if (!/^\d+$/.test(raw)) return "Use a numeric Telegram user id";
|
||||||
if (!trimmed) return null;
|
return undefined;
|
||||||
const stripped = trimmed.replace(/^(telegram|tg):/i, "").trim();
|
},
|
||||||
if (/^\d+$/.test(stripped)) return stripped;
|
});
|
||||||
if (!token) return null;
|
const normalized = String(entry).trim();
|
||||||
const username = stripped.startsWith("@") ? stripped : `@${stripped}`;
|
|
||||||
const url = `https://api.telegram.org/bot${token}/getChat?chat_id=${encodeURIComponent(username)}`;
|
|
||||||
const res = await fetch(url);
|
|
||||||
const data = (await res.json().catch(() => null)) as
|
|
||||||
| { ok?: boolean; result?: { id?: number | string } }
|
|
||||||
| null;
|
|
||||||
const id = data?.ok ? data?.result?.id : undefined;
|
|
||||||
if (typeof id === "number" || typeof id === "string") return String(id);
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const parseInput = (value: string) =>
|
|
||||||
value
|
|
||||||
.split(/[\n,;]+/g)
|
|
||||||
.map((entry) => entry.trim())
|
|
||||||
.filter(Boolean);
|
|
||||||
|
|
||||||
let resolvedIds: string[] = [];
|
|
||||||
while (resolvedIds.length === 0) {
|
|
||||||
const entry = await prompter.text({
|
|
||||||
message: "Telegram allowFrom (username or user id)",
|
|
||||||
placeholder: "@username",
|
|
||||||
initialValue: existingAllowFrom[0] ? String(existingAllowFrom[0]) : undefined,
|
|
||||||
validate: (value) => (String(value ?? "").trim() ? undefined : "Required"),
|
|
||||||
});
|
|
||||||
const parts = parseInput(String(entry));
|
|
||||||
const results = await Promise.all(parts.map((part) => resolveTelegramUserId(part)));
|
|
||||||
const unresolved = parts.filter((_, idx) => !results[idx]);
|
|
||||||
if (unresolved.length > 0) {
|
|
||||||
await prompter.note(
|
|
||||||
`Could not resolve: ${unresolved.join(", ")}. Use @username or numeric id.`,
|
|
||||||
"Telegram allowlist",
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
resolvedIds = results.filter(Boolean) as string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
const merged = [
|
const merged = [
|
||||||
...existingAllowFrom.map((item) => String(item).trim()).filter(Boolean),
|
...existingAllowFrom.map((item) => String(item).trim()).filter(Boolean),
|
||||||
...resolvedIds,
|
normalized,
|
||||||
];
|
];
|
||||||
const unique = [...new Set(merged)];
|
const unique = [...new Set(merged)];
|
||||||
|
|
||||||
@@ -157,22 +119,6 @@ async function promptTelegramAllowFrom(params: {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function promptTelegramAllowFromForAccount(params: {
|
|
||||||
cfg: ClawdbotConfig;
|
|
||||||
prompter: WizardPrompter;
|
|
||||||
accountId?: string;
|
|
||||||
}): Promise<ClawdbotConfig> {
|
|
||||||
const accountId =
|
|
||||||
params.accountId && normalizeAccountId(params.accountId)
|
|
||||||
? normalizeAccountId(params.accountId) ?? DEFAULT_ACCOUNT_ID
|
|
||||||
: resolveDefaultTelegramAccountId(params.cfg);
|
|
||||||
return promptTelegramAllowFrom({
|
|
||||||
cfg: params.cfg,
|
|
||||||
prompter: params.prompter,
|
|
||||||
accountId,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const dmPolicy: ChannelOnboardingDmPolicy = {
|
const dmPolicy: ChannelOnboardingDmPolicy = {
|
||||||
label: "Telegram",
|
label: "Telegram",
|
||||||
channel,
|
channel,
|
||||||
@@ -180,7 +126,6 @@ const dmPolicy: ChannelOnboardingDmPolicy = {
|
|||||||
allowFromKey: "channels.telegram.allowFrom",
|
allowFromKey: "channels.telegram.allowFrom",
|
||||||
getCurrent: (cfg) => cfg.channels?.telegram?.dmPolicy ?? "pairing",
|
getCurrent: (cfg) => cfg.channels?.telegram?.dmPolicy ?? "pairing",
|
||||||
setPolicy: (cfg, policy) => setTelegramDmPolicy(cfg, policy),
|
setPolicy: (cfg, policy) => setTelegramDmPolicy(cfg, policy),
|
||||||
promptAllowFrom: promptTelegramAllowFromForAccount,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const telegramOnboardingAdapter: ChannelOnboardingAdapter = {
|
export const telegramOnboardingAdapter: ChannelOnboardingAdapter = {
|
||||||
|
|||||||
@@ -266,9 +266,7 @@ describe("memory cli", () => {
|
|||||||
registerMemoryCli(program);
|
registerMemoryCli(program);
|
||||||
await program.parseAsync(["memory", "index"], { from: "user" });
|
await program.parseAsync(["memory", "index"], { from: "user" });
|
||||||
|
|
||||||
expect(sync).toHaveBeenCalledWith(
|
expect(sync).toHaveBeenCalledWith({ reason: "cli", force: false });
|
||||||
expect.objectContaining({ reason: "cli", force: false, progress: expect.any(Function) }),
|
|
||||||
);
|
|
||||||
expect(close).toHaveBeenCalled();
|
expect(close).toHaveBeenCalled();
|
||||||
expect(log).toHaveBeenCalledWith("Memory index updated (main).");
|
expect(log).toHaveBeenCalledWith("Memory index updated (main).");
|
||||||
});
|
});
|
||||||
@@ -293,9 +291,7 @@ describe("memory cli", () => {
|
|||||||
registerMemoryCli(program);
|
registerMemoryCli(program);
|
||||||
await program.parseAsync(["memory", "index"], { from: "user" });
|
await program.parseAsync(["memory", "index"], { from: "user" });
|
||||||
|
|
||||||
expect(sync).toHaveBeenCalledWith(
|
expect(sync).toHaveBeenCalledWith({ reason: "cli", force: false });
|
||||||
expect.objectContaining({ reason: "cli", force: false, progress: expect.any(Function) }),
|
|
||||||
);
|
|
||||||
expect(close).toHaveBeenCalled();
|
expect(close).toHaveBeenCalled();
|
||||||
expect(error).toHaveBeenCalledWith(
|
expect(error).toHaveBeenCalledWith(
|
||||||
expect.stringContaining("Memory manager close failed: close boom"),
|
expect.stringContaining("Memory manager close failed: close boom"),
|
||||||
|
|||||||
+3
-99
@@ -103,35 +103,6 @@ export function registerMemoryCli(program: Command) {
|
|||||||
progress.tick();
|
progress.tick();
|
||||||
});
|
});
|
||||||
if (opts.index) {
|
if (opts.index) {
|
||||||
const startedAt = Date.now();
|
|
||||||
let lastLabel = "Indexing memory…";
|
|
||||||
let lastCompleted = 0;
|
|
||||||
let lastTotal = 0;
|
|
||||||
const formatElapsed = () => {
|
|
||||||
const elapsedMs = Math.max(0, Date.now() - startedAt);
|
|
||||||
const seconds = Math.floor(elapsedMs / 1000);
|
|
||||||
const minutes = Math.floor(seconds / 60);
|
|
||||||
const remainingSeconds = seconds % 60;
|
|
||||||
return `${minutes}:${String(remainingSeconds).padStart(2, "0")}`;
|
|
||||||
};
|
|
||||||
const formatEta = () => {
|
|
||||||
if (lastTotal <= 0 || lastCompleted <= 0) return null;
|
|
||||||
const elapsedMs = Math.max(1, Date.now() - startedAt);
|
|
||||||
const rate = lastCompleted / elapsedMs;
|
|
||||||
if (!Number.isFinite(rate) || rate <= 0) return null;
|
|
||||||
const remainingMs = Math.max(0, (lastTotal - lastCompleted) / rate);
|
|
||||||
const seconds = Math.floor(remainingMs / 1000);
|
|
||||||
const minutes = Math.floor(seconds / 60);
|
|
||||||
const remainingSeconds = seconds % 60;
|
|
||||||
return `${minutes}:${String(remainingSeconds).padStart(2, "0")}`;
|
|
||||||
};
|
|
||||||
const buildLabel = () => {
|
|
||||||
const elapsed = formatElapsed();
|
|
||||||
const eta = formatEta();
|
|
||||||
return eta
|
|
||||||
? `${lastLabel} · elapsed ${elapsed} · eta ${eta}`
|
|
||||||
: `${lastLabel} · elapsed ${elapsed}`;
|
|
||||||
};
|
|
||||||
await withProgressTotals(
|
await withProgressTotals(
|
||||||
{
|
{
|
||||||
label: "Indexing memory…",
|
label: "Indexing memory…",
|
||||||
@@ -139,30 +110,22 @@ export function registerMemoryCli(program: Command) {
|
|||||||
fallback: opts.verbose ? "line" : undefined,
|
fallback: opts.verbose ? "line" : undefined,
|
||||||
},
|
},
|
||||||
async (update, progress) => {
|
async (update, progress) => {
|
||||||
const interval = setInterval(() => {
|
|
||||||
progress.setLabel(buildLabel());
|
|
||||||
}, 1000);
|
|
||||||
try {
|
try {
|
||||||
await manager.sync({
|
await manager.sync({
|
||||||
reason: "cli",
|
reason: "cli",
|
||||||
progress: (syncUpdate) => {
|
progress: (syncUpdate) => {
|
||||||
if (syncUpdate.label) lastLabel = syncUpdate.label;
|
|
||||||
lastCompleted = syncUpdate.completed;
|
|
||||||
lastTotal = syncUpdate.total;
|
|
||||||
update({
|
update({
|
||||||
completed: syncUpdate.completed,
|
completed: syncUpdate.completed,
|
||||||
total: syncUpdate.total,
|
total: syncUpdate.total,
|
||||||
label: buildLabel(),
|
label: syncUpdate.label,
|
||||||
});
|
});
|
||||||
progress.setLabel(buildLabel());
|
if (syncUpdate.label) progress.setLabel(syncUpdate.label);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
indexError = formatErrorMessage(err);
|
indexError = formatErrorMessage(err);
|
||||||
defaultRuntime.error(`Memory index failed: ${indexError}`);
|
defaultRuntime.error(`Memory index failed: ${indexError}`);
|
||||||
process.exitCode = 1;
|
process.exitCode = 1;
|
||||||
} finally {
|
|
||||||
clearInterval(interval);
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -337,66 +300,7 @@ export function registerMemoryCli(program: Command) {
|
|||||||
defaultRuntime.log(lines.join("\n"));
|
defaultRuntime.log(lines.join("\n"));
|
||||||
defaultRuntime.log("");
|
defaultRuntime.log("");
|
||||||
}
|
}
|
||||||
const startedAt = Date.now();
|
await manager.sync({ reason: "cli", force: opts.force });
|
||||||
let lastLabel = "Indexing memory…";
|
|
||||||
let lastCompleted = 0;
|
|
||||||
let lastTotal = 0;
|
|
||||||
const formatElapsed = () => {
|
|
||||||
const elapsedMs = Math.max(0, Date.now() - startedAt);
|
|
||||||
const seconds = Math.floor(elapsedMs / 1000);
|
|
||||||
const minutes = Math.floor(seconds / 60);
|
|
||||||
const remainingSeconds = seconds % 60;
|
|
||||||
return `${minutes}:${String(remainingSeconds).padStart(2, "0")}`;
|
|
||||||
};
|
|
||||||
const formatEta = () => {
|
|
||||||
if (lastTotal <= 0 || lastCompleted <= 0) return null;
|
|
||||||
const elapsedMs = Math.max(1, Date.now() - startedAt);
|
|
||||||
const rate = lastCompleted / elapsedMs;
|
|
||||||
if (!Number.isFinite(rate) || rate <= 0) return null;
|
|
||||||
const remainingMs = Math.max(0, (lastTotal - lastCompleted) / rate);
|
|
||||||
const seconds = Math.floor(remainingMs / 1000);
|
|
||||||
const minutes = Math.floor(seconds / 60);
|
|
||||||
const remainingSeconds = seconds % 60;
|
|
||||||
return `${minutes}:${String(remainingSeconds).padStart(2, "0")}`;
|
|
||||||
};
|
|
||||||
const buildLabel = () => {
|
|
||||||
const elapsed = formatElapsed();
|
|
||||||
const eta = formatEta();
|
|
||||||
return eta
|
|
||||||
? `${lastLabel} · elapsed ${elapsed} · eta ${eta}`
|
|
||||||
: `${lastLabel} · elapsed ${elapsed}`;
|
|
||||||
};
|
|
||||||
await withProgressTotals(
|
|
||||||
{
|
|
||||||
label: "Indexing memory…",
|
|
||||||
total: 0,
|
|
||||||
fallback: opts.verbose ? "line" : undefined,
|
|
||||||
},
|
|
||||||
async (update, progress) => {
|
|
||||||
const interval = setInterval(() => {
|
|
||||||
progress.setLabel(buildLabel());
|
|
||||||
}, 1000);
|
|
||||||
try {
|
|
||||||
await manager.sync({
|
|
||||||
reason: "cli",
|
|
||||||
force: opts.force,
|
|
||||||
progress: (syncUpdate) => {
|
|
||||||
if (syncUpdate.label) lastLabel = syncUpdate.label;
|
|
||||||
lastCompleted = syncUpdate.completed;
|
|
||||||
lastTotal = syncUpdate.total;
|
|
||||||
update({
|
|
||||||
completed: syncUpdate.completed,
|
|
||||||
total: syncUpdate.total,
|
|
||||||
label: buildLabel(),
|
|
||||||
});
|
|
||||||
progress.setLabel(buildLabel());
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
clearInterval(interval);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
defaultRuntime.log(`Memory index updated (${agentId}).`);
|
defaultRuntime.log(`Memory index updated (${agentId}).`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const message = formatErrorMessage(err);
|
const message = formatErrorMessage(err);
|
||||||
|
|||||||
@@ -17,16 +17,12 @@ export function registerAgentCommands(program: Command, args: { agentChannelOpti
|
|||||||
.requiredOption("-m, --message <text>", "Message body for the agent")
|
.requiredOption("-m, --message <text>", "Message body for the agent")
|
||||||
.option("-t, --to <number>", "Recipient number in E.164 used to derive the session key")
|
.option("-t, --to <number>", "Recipient number in E.164 used to derive the session key")
|
||||||
.option("--session-id <id>", "Use an explicit session id")
|
.option("--session-id <id>", "Use an explicit session id")
|
||||||
.option("--agent <id>", "Agent id (overrides routing bindings)")
|
|
||||||
.option("--thinking <level>", "Thinking level: off | minimal | low | medium | high")
|
.option("--thinking <level>", "Thinking level: off | minimal | low | medium | high")
|
||||||
.option("--verbose <on|off>", "Persist agent verbose level for the session")
|
.option("--verbose <on|off>", "Persist agent verbose level for the session")
|
||||||
.option(
|
.option(
|
||||||
"--channel <channel>",
|
"--channel <channel>",
|
||||||
`Delivery channel: ${args.agentChannelOptions} (default: ${DEFAULT_CHAT_CHANNEL})`,
|
`Delivery channel: ${args.agentChannelOptions} (default: ${DEFAULT_CHAT_CHANNEL})`,
|
||||||
)
|
)
|
||||||
.option("--reply-to <target>", "Delivery target override (separate from session routing)")
|
|
||||||
.option("--reply-channel <channel>", "Delivery channel override (separate from routing)")
|
|
||||||
.option("--reply-account <id>", "Delivery account id override")
|
|
||||||
.option(
|
.option(
|
||||||
"--local",
|
"--local",
|
||||||
"Run the embedded agent locally (requires model provider API keys in your shell)",
|
"Run the embedded agent locally (requires model provider API keys in your shell)",
|
||||||
@@ -34,7 +30,7 @@ export function registerAgentCommands(program: Command, args: { agentChannelOpti
|
|||||||
)
|
)
|
||||||
.option(
|
.option(
|
||||||
"--deliver",
|
"--deliver",
|
||||||
"Send the agent's reply back to the selected channel",
|
"Send the agent's reply back to the selected channel (requires --to)",
|
||||||
false,
|
false,
|
||||||
)
|
)
|
||||||
.option("--json", "Output result as JSON", false)
|
.option("--json", "Output result as JSON", false)
|
||||||
@@ -48,11 +44,9 @@ export function registerAgentCommands(program: Command, args: { agentChannelOpti
|
|||||||
`
|
`
|
||||||
Examples:
|
Examples:
|
||||||
clawdbot agent --to +15555550123 --message "status update"
|
clawdbot agent --to +15555550123 --message "status update"
|
||||||
clawdbot agent --agent ops --message "Summarize logs"
|
|
||||||
clawdbot agent --session-id 1234 --message "Summarize inbox" --thinking medium
|
clawdbot agent --session-id 1234 --message "Summarize inbox" --thinking medium
|
||||||
clawdbot agent --to +15555550123 --message "Trace logs" --verbose on --json
|
clawdbot agent --to +15555550123 --message "Trace logs" --verbose on --json
|
||||||
clawdbot agent --to +15555550123 --message "Summon reply" --deliver
|
clawdbot agent --to +15555550123 --message "Summon reply" --deliver
|
||||||
clawdbot agent --agent ops --message "Generate report" --deliver --reply-channel slack --reply-to "#reports"
|
|
||||||
|
|
||||||
${theme.muted("Docs:")} ${formatDocsLink("/cli/agent", "docs.clawd.bot/cli/agent")}`,
|
${theme.muted("Docs:")} ${formatDocsLink("/cli/agent", "docs.clawd.bot/cli/agent")}`,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -2,10 +2,9 @@ import { DEFAULT_CHAT_CHANNEL } from "../channels/registry.js";
|
|||||||
import type { CliDeps } from "../cli/deps.js";
|
import type { CliDeps } from "../cli/deps.js";
|
||||||
import { withProgress } from "../cli/progress.js";
|
import { withProgress } from "../cli/progress.js";
|
||||||
import { loadConfig } from "../config/config.js";
|
import { loadConfig } from "../config/config.js";
|
||||||
import { resolveSessionKeyForRequest } from "./agent/session.js";
|
import { loadSessionStore, resolveSessionKey, resolveStorePath } from "../config/sessions.js";
|
||||||
import { callGateway, randomIdempotencyKey } from "../gateway/call.js";
|
import { callGateway, randomIdempotencyKey } from "../gateway/call.js";
|
||||||
import { listAgentIds } from "../agents/agent-scope.js";
|
import { normalizeMainKey } from "../routing/session-key.js";
|
||||||
import { normalizeAgentId } from "../routing/session-key.js";
|
|
||||||
import type { RuntimeEnv } from "../runtime.js";
|
import type { RuntimeEnv } from "../runtime.js";
|
||||||
import {
|
import {
|
||||||
GATEWAY_CLIENT_MODES,
|
GATEWAY_CLIENT_MODES,
|
||||||
@@ -32,7 +31,6 @@ type GatewayAgentResponse = {
|
|||||||
|
|
||||||
export type AgentCliOpts = {
|
export type AgentCliOpts = {
|
||||||
message: string;
|
message: string;
|
||||||
agent?: string;
|
|
||||||
to?: string;
|
to?: string;
|
||||||
sessionId?: string;
|
sessionId?: string;
|
||||||
thinking?: string;
|
thinking?: string;
|
||||||
@@ -41,9 +39,6 @@ export type AgentCliOpts = {
|
|||||||
timeout?: string;
|
timeout?: string;
|
||||||
deliver?: boolean;
|
deliver?: boolean;
|
||||||
channel?: string;
|
channel?: string;
|
||||||
replyTo?: string;
|
|
||||||
replyChannel?: string;
|
|
||||||
replyAccount?: string;
|
|
||||||
bestEffortDeliver?: boolean;
|
bestEffortDeliver?: boolean;
|
||||||
lane?: string;
|
lane?: string;
|
||||||
runId?: string;
|
runId?: string;
|
||||||
@@ -51,6 +46,27 @@ export type AgentCliOpts = {
|
|||||||
local?: boolean;
|
local?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function resolveGatewaySessionKey(opts: {
|
||||||
|
cfg: ReturnType<typeof loadConfig>;
|
||||||
|
to?: string;
|
||||||
|
sessionId?: string;
|
||||||
|
}): string | undefined {
|
||||||
|
const sessionCfg = opts.cfg.session;
|
||||||
|
const scope = sessionCfg?.scope ?? "per-sender";
|
||||||
|
const mainKey = normalizeMainKey(sessionCfg?.mainKey);
|
||||||
|
const storePath = resolveStorePath(sessionCfg?.store);
|
||||||
|
const store = loadSessionStore(storePath);
|
||||||
|
|
||||||
|
const ctx = opts.to?.trim() ? ({ From: opts.to } as { From: string }) : null;
|
||||||
|
let sessionKey: string | undefined = ctx ? resolveSessionKey(scope, ctx, mainKey) : undefined;
|
||||||
|
|
||||||
|
if (opts.sessionId && (!sessionKey || store[sessionKey]?.sessionId !== opts.sessionId)) {
|
||||||
|
const foundKey = Object.keys(store).find((key) => store[key]?.sessionId === opts.sessionId);
|
||||||
|
if (foundKey) sessionKey = foundKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
return sessionKey;
|
||||||
|
}
|
||||||
|
|
||||||
function parseTimeoutSeconds(opts: { cfg: ReturnType<typeof loadConfig>; timeout?: string }) {
|
function parseTimeoutSeconds(opts: { cfg: ReturnType<typeof loadConfig>; timeout?: string }) {
|
||||||
const raw =
|
const raw =
|
||||||
@@ -82,30 +98,19 @@ function formatPayloadForLog(payload: {
|
|||||||
export async function agentViaGatewayCommand(opts: AgentCliOpts, runtime: RuntimeEnv) {
|
export async function agentViaGatewayCommand(opts: AgentCliOpts, runtime: RuntimeEnv) {
|
||||||
const body = (opts.message ?? "").trim();
|
const body = (opts.message ?? "").trim();
|
||||||
if (!body) throw new Error("Message (--message) is required");
|
if (!body) throw new Error("Message (--message) is required");
|
||||||
if (!opts.to && !opts.sessionId && !opts.agent) {
|
if (!opts.to && !opts.sessionId) {
|
||||||
throw new Error("Pass --to <E.164>, --session-id, or --agent to choose a session");
|
throw new Error("Pass --to <E.164> or --session-id to choose a session");
|
||||||
}
|
}
|
||||||
|
|
||||||
const cfg = loadConfig();
|
const cfg = loadConfig();
|
||||||
const agentIdRaw = opts.agent?.trim();
|
|
||||||
const agentId = agentIdRaw ? normalizeAgentId(agentIdRaw) : undefined;
|
|
||||||
if (agentId) {
|
|
||||||
const knownAgents = listAgentIds(cfg);
|
|
||||||
if (!knownAgents.includes(agentId)) {
|
|
||||||
throw new Error(
|
|
||||||
`Unknown agent id "${agentIdRaw}". Use "clawdbot agents list" to see configured agents.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const timeoutSeconds = parseTimeoutSeconds({ cfg, timeout: opts.timeout });
|
const timeoutSeconds = parseTimeoutSeconds({ cfg, timeout: opts.timeout });
|
||||||
const gatewayTimeoutMs = Math.max(10_000, (timeoutSeconds + 30) * 1000);
|
const gatewayTimeoutMs = Math.max(10_000, (timeoutSeconds + 30) * 1000);
|
||||||
|
|
||||||
const sessionKey = resolveSessionKeyForRequest({
|
const sessionKey = resolveGatewaySessionKey({
|
||||||
cfg,
|
cfg,
|
||||||
agentId,
|
|
||||||
to: opts.to,
|
to: opts.to,
|
||||||
sessionId: opts.sessionId,
|
sessionId: opts.sessionId,
|
||||||
}).sessionKey;
|
});
|
||||||
|
|
||||||
const channel = normalizeMessageChannel(opts.channel) ?? DEFAULT_CHAT_CHANNEL;
|
const channel = normalizeMessageChannel(opts.channel) ?? DEFAULT_CHAT_CHANNEL;
|
||||||
const idempotencyKey = opts.runId?.trim() || randomIdempotencyKey();
|
const idempotencyKey = opts.runId?.trim() || randomIdempotencyKey();
|
||||||
@@ -121,16 +126,12 @@ export async function agentViaGatewayCommand(opts: AgentCliOpts, runtime: Runtim
|
|||||||
method: "agent",
|
method: "agent",
|
||||||
params: {
|
params: {
|
||||||
message: body,
|
message: body,
|
||||||
agentId,
|
|
||||||
to: opts.to,
|
to: opts.to,
|
||||||
replyTo: opts.replyTo,
|
|
||||||
sessionId: opts.sessionId,
|
sessionId: opts.sessionId,
|
||||||
sessionKey,
|
sessionKey,
|
||||||
thinking: opts.thinking,
|
thinking: opts.thinking,
|
||||||
deliver: Boolean(opts.deliver),
|
deliver: Boolean(opts.deliver),
|
||||||
channel,
|
channel,
|
||||||
replyChannel: opts.replyChannel,
|
|
||||||
replyAccountId: opts.replyAccount,
|
|
||||||
timeout: timeoutSeconds,
|
timeout: timeoutSeconds,
|
||||||
lane: opts.lane,
|
lane: opts.lane,
|
||||||
extraSystemPrompt: opts.extraSystemPrompt,
|
extraSystemPrompt: opts.extraSystemPrompt,
|
||||||
@@ -165,19 +166,14 @@ export async function agentViaGatewayCommand(opts: AgentCliOpts, runtime: Runtim
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function agentCliCommand(opts: AgentCliOpts, runtime: RuntimeEnv, deps?: CliDeps) {
|
export async function agentCliCommand(opts: AgentCliOpts, runtime: RuntimeEnv, deps?: CliDeps) {
|
||||||
const localOpts = {
|
|
||||||
...opts,
|
|
||||||
agentId: opts.agent,
|
|
||||||
replyAccountId: opts.replyAccount,
|
|
||||||
};
|
|
||||||
if (opts.local === true) {
|
if (opts.local === true) {
|
||||||
return await agentCommand(localOpts, runtime, deps);
|
return await agentCommand(opts, runtime, deps);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return await agentViaGatewayCommand(opts, runtime);
|
return await agentViaGatewayCommand(opts, runtime);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
runtime.error?.(`Gateway agent failed; falling back to embedded: ${String(err)}`);
|
runtime.error?.(`Gateway agent failed; falling back to embedded: ${String(err)}`);
|
||||||
return await agentCommand(localOpts, runtime, deps);
|
return await agentCommand(opts, runtime, deps);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -220,46 +220,6 @@ describe("deliverAgentCommandResult", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("uses reply overrides for delivery routing", async () => {
|
|
||||||
const cfg = {} as ClawdbotConfig;
|
|
||||||
const deps = {} as CliDeps;
|
|
||||||
const runtime = {
|
|
||||||
log: vi.fn(),
|
|
||||||
error: vi.fn(),
|
|
||||||
} as unknown as RuntimeEnv;
|
|
||||||
const sessionEntry = {
|
|
||||||
lastChannel: "telegram",
|
|
||||||
lastTo: "123",
|
|
||||||
lastAccountId: "legacy",
|
|
||||||
} as SessionEntry;
|
|
||||||
const result = {
|
|
||||||
payloads: [{ text: "hi" }],
|
|
||||||
meta: {},
|
|
||||||
};
|
|
||||||
|
|
||||||
const { deliverAgentCommandResult } = await import("./agent/delivery.js");
|
|
||||||
await deliverAgentCommandResult({
|
|
||||||
cfg,
|
|
||||||
deps,
|
|
||||||
runtime,
|
|
||||||
opts: {
|
|
||||||
message: "hello",
|
|
||||||
deliver: true,
|
|
||||||
to: "+15551234567",
|
|
||||||
replyTo: "#reports",
|
|
||||||
replyChannel: "slack",
|
|
||||||
replyAccountId: "ops",
|
|
||||||
},
|
|
||||||
sessionEntry,
|
|
||||||
result,
|
|
||||||
payloads: result.payloads,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(mocks.resolveOutboundTarget).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({ channel: "slack", to: "#reports", accountId: "ops" }),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("prefixes nested agent outputs with context", async () => {
|
it("prefixes nested agent outputs with context", async () => {
|
||||||
const cfg = {} as ClawdbotConfig;
|
const cfg = {} as ClawdbotConfig;
|
||||||
const deps = {} as CliDeps;
|
const deps = {} as CliDeps;
|
||||||
|
|||||||
@@ -45,7 +45,6 @@ function mockConfig(
|
|||||||
storePath: string,
|
storePath: string,
|
||||||
agentOverrides?: Partial<NonNullable<NonNullable<ClawdbotConfig["agents"]>["defaults"]>>,
|
agentOverrides?: Partial<NonNullable<NonNullable<ClawdbotConfig["agents"]>["defaults"]>>,
|
||||||
telegramOverrides?: Partial<NonNullable<ClawdbotConfig["telegram"]>>,
|
telegramOverrides?: Partial<NonNullable<ClawdbotConfig["telegram"]>>,
|
||||||
agentsList?: Array<{ id: string; default?: boolean }>,
|
|
||||||
) {
|
) {
|
||||||
configSpy.mockReturnValue({
|
configSpy.mockReturnValue({
|
||||||
agents: {
|
agents: {
|
||||||
@@ -55,7 +54,6 @@ function mockConfig(
|
|||||||
workspace: path.join(home, "clawd"),
|
workspace: path.join(home, "clawd"),
|
||||||
...agentOverrides,
|
...agentOverrides,
|
||||||
},
|
},
|
||||||
list: agentsList,
|
|
||||||
},
|
},
|
||||||
session: { store: storePath, mainKey: "main" },
|
session: { store: storePath, mainKey: "main" },
|
||||||
telegram: telegramOverrides ? { ...telegramOverrides } : undefined,
|
telegram: telegramOverrides ? { ...telegramOverrides } : undefined,
|
||||||
@@ -197,30 +195,6 @@ describe("agentCommand", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("derives session key from --agent when no routing target is provided", async () => {
|
|
||||||
await withTempHome(async (home) => {
|
|
||||||
const store = path.join(home, "sessions.json");
|
|
||||||
mockConfig(home, store, undefined, undefined, [{ id: "ops" }]);
|
|
||||||
|
|
||||||
await agentCommand({ message: "hi", agentId: "ops" }, runtime);
|
|
||||||
|
|
||||||
const callArgs = vi.mocked(runEmbeddedPiAgent).mock.calls.at(-1)?.[0];
|
|
||||||
expect(callArgs?.sessionKey).toBe("agent:ops:main");
|
|
||||||
expect(callArgs?.sessionFile).toContain(`${path.sep}agents${path.sep}ops${path.sep}sessions`);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects unknown agent overrides", async () => {
|
|
||||||
await withTempHome(async (home) => {
|
|
||||||
const store = path.join(home, "sessions.json");
|
|
||||||
mockConfig(home, store);
|
|
||||||
|
|
||||||
await expect(agentCommand({ message: "hi", agentId: "ghost" }, runtime)).rejects.toThrow(
|
|
||||||
'Unknown agent id "ghost"',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("defaults thinking to low for reasoning-capable models", async () => {
|
it("defaults thinking to low for reasoning-capable models", async () => {
|
||||||
await withTempHome(async (home) => {
|
await withTempHome(async (home) => {
|
||||||
const store = path.join(home, "sessions.json");
|
const store = path.join(home, "sessions.json");
|
||||||
@@ -322,27 +296,4 @@ describe("agentCommand", () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("uses reply channel as the message channel context", async () => {
|
|
||||||
await withTempHome(async (home) => {
|
|
||||||
const store = path.join(home, "sessions.json");
|
|
||||||
mockConfig(home, store, undefined, undefined, [{ id: "ops" }]);
|
|
||||||
|
|
||||||
await agentCommand({ message: "hi", agentId: "ops", replyChannel: "slack" }, runtime);
|
|
||||||
|
|
||||||
const callArgs = vi.mocked(runEmbeddedPiAgent).mock.calls.at(-1)?.[0];
|
|
||||||
expect(callArgs?.messageChannel).toBe("slack");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("logs output when delivery is disabled", async () => {
|
|
||||||
await withTempHome(async (home) => {
|
|
||||||
const store = path.join(home, "sessions.json");
|
|
||||||
mockConfig(home, store, undefined, undefined, [{ id: "ops" }]);
|
|
||||||
|
|
||||||
await agentCommand({ message: "hi", agentId: "ops" }, runtime);
|
|
||||||
|
|
||||||
expect(runtime.log).toHaveBeenCalledWith("ok");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
+4
-28
@@ -1,5 +1,4 @@
|
|||||||
import {
|
import {
|
||||||
listAgentIds,
|
|
||||||
resolveAgentDir,
|
resolveAgentDir,
|
||||||
resolveAgentModelFallbacksOverride,
|
resolveAgentModelFallbacksOverride,
|
||||||
resolveAgentModelPrimary,
|
resolveAgentModelPrimary,
|
||||||
@@ -54,7 +53,6 @@ import { deliverAgentCommandResult } from "./agent/delivery.js";
|
|||||||
import { resolveSession } from "./agent/session.js";
|
import { resolveSession } from "./agent/session.js";
|
||||||
import { updateSessionStoreAfterAgentRun } from "./agent/session-store.js";
|
import { updateSessionStoreAfterAgentRun } from "./agent/session-store.js";
|
||||||
import type { AgentCommandOpts } from "./agent/types.js";
|
import type { AgentCommandOpts } from "./agent/types.js";
|
||||||
import { normalizeAgentId } from "../routing/session-key.js";
|
|
||||||
|
|
||||||
export async function agentCommand(
|
export async function agentCommand(
|
||||||
opts: AgentCommandOpts,
|
opts: AgentCommandOpts,
|
||||||
@@ -63,31 +61,13 @@ export async function agentCommand(
|
|||||||
) {
|
) {
|
||||||
const body = (opts.message ?? "").trim();
|
const body = (opts.message ?? "").trim();
|
||||||
if (!body) throw new Error("Message (--message) is required");
|
if (!body) throw new Error("Message (--message) is required");
|
||||||
if (!opts.to && !opts.sessionId && !opts.sessionKey && !opts.agentId) {
|
if (!opts.to && !opts.sessionId && !opts.sessionKey) {
|
||||||
throw new Error("Pass --to <E.164>, --session-id, or --agent to choose a session");
|
throw new Error("Pass --to <E.164> or --session-id to choose a session");
|
||||||
}
|
}
|
||||||
|
|
||||||
const cfg = loadConfig();
|
const cfg = loadConfig();
|
||||||
const agentIdOverrideRaw = opts.agentId?.trim();
|
|
||||||
const agentIdOverride = agentIdOverrideRaw ? normalizeAgentId(agentIdOverrideRaw) : undefined;
|
|
||||||
if (agentIdOverride) {
|
|
||||||
const knownAgents = listAgentIds(cfg);
|
|
||||||
if (!knownAgents.includes(agentIdOverride)) {
|
|
||||||
throw new Error(
|
|
||||||
`Unknown agent id "${agentIdOverrideRaw}". Use "clawdbot agents list" to see configured agents.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (agentIdOverride && opts.sessionKey) {
|
|
||||||
const sessionAgentId = resolveAgentIdFromSessionKey(opts.sessionKey);
|
|
||||||
if (sessionAgentId !== agentIdOverride) {
|
|
||||||
throw new Error(
|
|
||||||
`Agent id "${agentIdOverrideRaw}" does not match session key agent "${sessionAgentId}".`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const agentCfg = cfg.agents?.defaults;
|
const agentCfg = cfg.agents?.defaults;
|
||||||
const sessionAgentId = agentIdOverride ?? resolveAgentIdFromSessionKey(opts.sessionKey?.trim());
|
const sessionAgentId = resolveAgentIdFromSessionKey(opts.sessionKey?.trim());
|
||||||
const workspaceDirRaw = resolveAgentWorkspaceDir(cfg, sessionAgentId);
|
const workspaceDirRaw = resolveAgentWorkspaceDir(cfg, sessionAgentId);
|
||||||
const agentDir = resolveAgentDir(cfg, sessionAgentId);
|
const agentDir = resolveAgentDir(cfg, sessionAgentId);
|
||||||
const workspace = await ensureAgentWorkspace({
|
const workspace = await ensureAgentWorkspace({
|
||||||
@@ -134,7 +114,6 @@ export async function agentCommand(
|
|||||||
to: opts.to,
|
to: opts.to,
|
||||||
sessionId: opts.sessionId,
|
sessionId: opts.sessionId,
|
||||||
sessionKey: opts.sessionKey,
|
sessionKey: opts.sessionKey,
|
||||||
agentId: agentIdOverride,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const {
|
const {
|
||||||
@@ -367,10 +346,7 @@ export async function agentCommand(
|
|||||||
let fallbackProvider = provider;
|
let fallbackProvider = provider;
|
||||||
let fallbackModel = model;
|
let fallbackModel = model;
|
||||||
try {
|
try {
|
||||||
const messageChannel = resolveMessageChannel(
|
const messageChannel = resolveMessageChannel(opts.messageChannel, opts.channel);
|
||||||
opts.messageChannel,
|
|
||||||
opts.replyChannel ?? opts.channel,
|
|
||||||
);
|
|
||||||
const fallbackResult = await runWithModelFallback({
|
const fallbackResult = await runWithModelFallback({
|
||||||
cfg,
|
cfg,
|
||||||
provider,
|
provider,
|
||||||
|
|||||||
@@ -59,9 +59,9 @@ export async function deliverAgentCommandResult(params: {
|
|||||||
const bestEffortDeliver = opts.bestEffortDeliver === true;
|
const bestEffortDeliver = opts.bestEffortDeliver === true;
|
||||||
const deliveryPlan = resolveAgentDeliveryPlan({
|
const deliveryPlan = resolveAgentDeliveryPlan({
|
||||||
sessionEntry,
|
sessionEntry,
|
||||||
requestedChannel: opts.replyChannel ?? opts.channel,
|
requestedChannel: opts.channel,
|
||||||
explicitTo: opts.replyTo ?? opts.to,
|
explicitTo: opts.to,
|
||||||
accountId: opts.replyAccountId ?? opts.accountId,
|
accountId: opts.accountId,
|
||||||
wantsDelivery: deliver,
|
wantsDelivery: deliver,
|
||||||
});
|
});
|
||||||
const deliveryChannel = deliveryPlan.resolvedChannel;
|
const deliveryChannel = deliveryPlan.resolvedChannel;
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import {
|
|||||||
evaluateSessionFreshness,
|
evaluateSessionFreshness,
|
||||||
loadSessionStore,
|
loadSessionStore,
|
||||||
resolveAgentIdFromSessionKey,
|
resolveAgentIdFromSessionKey,
|
||||||
resolveExplicitAgentSessionKey,
|
|
||||||
resolveSessionResetPolicy,
|
resolveSessionResetPolicy,
|
||||||
resolveSessionResetType,
|
resolveSessionResetType,
|
||||||
resolveSessionKey,
|
resolveSessionKey,
|
||||||
@@ -32,71 +31,42 @@ export type SessionResolution = {
|
|||||||
persistedVerbose?: VerboseLevel;
|
persistedVerbose?: VerboseLevel;
|
||||||
};
|
};
|
||||||
|
|
||||||
type SessionKeyResolution = {
|
|
||||||
sessionKey?: string;
|
|
||||||
sessionStore: Record<string, SessionEntry>;
|
|
||||||
storePath: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export function resolveSessionKeyForRequest(opts: {
|
|
||||||
cfg: ClawdbotConfig;
|
|
||||||
to?: string;
|
|
||||||
sessionId?: string;
|
|
||||||
sessionKey?: string;
|
|
||||||
agentId?: string;
|
|
||||||
}): SessionKeyResolution {
|
|
||||||
const sessionCfg = opts.cfg.session;
|
|
||||||
const scope = sessionCfg?.scope ?? "per-sender";
|
|
||||||
const mainKey = normalizeMainKey(sessionCfg?.mainKey);
|
|
||||||
const explicitSessionKey =
|
|
||||||
opts.sessionKey?.trim() ||
|
|
||||||
resolveExplicitAgentSessionKey({
|
|
||||||
cfg: opts.cfg,
|
|
||||||
agentId: opts.agentId,
|
|
||||||
});
|
|
||||||
const storeAgentId = resolveAgentIdFromSessionKey(explicitSessionKey);
|
|
||||||
const storePath = resolveStorePath(sessionCfg?.store, {
|
|
||||||
agentId: storeAgentId,
|
|
||||||
});
|
|
||||||
const sessionStore = loadSessionStore(storePath);
|
|
||||||
|
|
||||||
const ctx: MsgContext | undefined = opts.to?.trim() ? { From: opts.to } : undefined;
|
|
||||||
let sessionKey: string | undefined =
|
|
||||||
explicitSessionKey ?? (ctx ? resolveSessionKey(scope, ctx, mainKey) : undefined);
|
|
||||||
|
|
||||||
// If a session id was provided, prefer to re-use its entry (by id) even when no key was derived.
|
|
||||||
if (
|
|
||||||
!explicitSessionKey &&
|
|
||||||
opts.sessionId &&
|
|
||||||
(!sessionKey || sessionStore[sessionKey]?.sessionId !== opts.sessionId)
|
|
||||||
) {
|
|
||||||
const foundKey = Object.keys(sessionStore).find(
|
|
||||||
(key) => sessionStore[key]?.sessionId === opts.sessionId,
|
|
||||||
);
|
|
||||||
if (foundKey) sessionKey = foundKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
return { sessionKey, sessionStore, storePath };
|
|
||||||
}
|
|
||||||
|
|
||||||
export function resolveSession(opts: {
|
export function resolveSession(opts: {
|
||||||
cfg: ClawdbotConfig;
|
cfg: ClawdbotConfig;
|
||||||
to?: string;
|
to?: string;
|
||||||
sessionId?: string;
|
sessionId?: string;
|
||||||
sessionKey?: string;
|
sessionKey?: string;
|
||||||
agentId?: string;
|
|
||||||
}): SessionResolution {
|
}): SessionResolution {
|
||||||
const sessionCfg = opts.cfg.session;
|
const sessionCfg = opts.cfg.session;
|
||||||
const { sessionKey, sessionStore, storePath } = resolveSessionKeyForRequest({
|
const scope = sessionCfg?.scope ?? "per-sender";
|
||||||
cfg: opts.cfg,
|
const mainKey = normalizeMainKey(sessionCfg?.mainKey);
|
||||||
to: opts.to,
|
const explicitSessionKey = opts.sessionKey?.trim();
|
||||||
sessionId: opts.sessionId,
|
const storeAgentId = resolveAgentIdFromSessionKey(explicitSessionKey);
|
||||||
sessionKey: opts.sessionKey,
|
const storePath = resolveStorePath(sessionCfg?.store, {
|
||||||
agentId: opts.agentId,
|
agentId: storeAgentId,
|
||||||
});
|
});
|
||||||
|
const sessionStore = loadSessionStore(storePath);
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
|
|
||||||
const sessionEntry = sessionKey ? sessionStore[sessionKey] : undefined;
|
const ctx: MsgContext | undefined = opts.to?.trim() ? { From: opts.to } : undefined;
|
||||||
|
let sessionKey: string | undefined =
|
||||||
|
explicitSessionKey ?? (ctx ? resolveSessionKey(scope, ctx, mainKey) : undefined);
|
||||||
|
let sessionEntry = sessionKey ? sessionStore[sessionKey] : undefined;
|
||||||
|
|
||||||
|
// If a session id was provided, prefer to re-use its entry (by id) even when no key was derived.
|
||||||
|
if (
|
||||||
|
!explicitSessionKey &&
|
||||||
|
opts.sessionId &&
|
||||||
|
(!sessionEntry || sessionEntry.sessionId !== opts.sessionId)
|
||||||
|
) {
|
||||||
|
const foundKey = Object.keys(sessionStore).find(
|
||||||
|
(key) => sessionStore[key]?.sessionId === opts.sessionId,
|
||||||
|
);
|
||||||
|
if (foundKey) {
|
||||||
|
sessionKey = sessionKey ?? foundKey;
|
||||||
|
sessionEntry = sessionStore[foundKey];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const resetType = resolveSessionResetType({ sessionKey });
|
const resetType = resolveSessionResetType({ sessionKey });
|
||||||
const resetPolicy = resolveSessionResetPolicy({ sessionCfg, resetType });
|
const resetPolicy = resolveSessionResetPolicy({ sessionCfg, resetType });
|
||||||
|
|||||||
@@ -11,8 +11,6 @@ export type AgentCommandOpts = {
|
|||||||
message: string;
|
message: string;
|
||||||
/** Optional image attachments for multimodal messages. */
|
/** Optional image attachments for multimodal messages. */
|
||||||
images?: ImageContent[];
|
images?: ImageContent[];
|
||||||
/** Agent id override (must exist in config). */
|
|
||||||
agentId?: string;
|
|
||||||
to?: string;
|
to?: string;
|
||||||
sessionId?: string;
|
sessionId?: string;
|
||||||
sessionKey?: string;
|
sessionKey?: string;
|
||||||
@@ -22,12 +20,6 @@ export type AgentCommandOpts = {
|
|||||||
json?: boolean;
|
json?: boolean;
|
||||||
timeout?: string;
|
timeout?: string;
|
||||||
deliver?: boolean;
|
deliver?: boolean;
|
||||||
/** Override delivery target (separate from session routing). */
|
|
||||||
replyTo?: string;
|
|
||||||
/** Override delivery channel (separate from session routing). */
|
|
||||||
replyChannel?: string;
|
|
||||||
/** Override delivery account id (separate from session routing). */
|
|
||||||
replyAccountId?: string;
|
|
||||||
/** Message channel context (webchat|voicewake|whatsapp|...). */
|
/** Message channel context (webchat|voicewake|whatsapp|...). */
|
||||||
messageChannel?: string;
|
messageChannel?: string;
|
||||||
channel?: string; // delivery channel (whatsapp|telegram|...)
|
channel?: string; // delivery channel (whatsapp|telegram|...)
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ describe("buildAuthChoiceOptions", () => {
|
|||||||
|
|
||||||
const claudeCli = options.find((opt) => opt.value === "claude-cli");
|
const claudeCli = options.find((opt) => opt.value === "claude-cli");
|
||||||
expect(claudeCli).toBeDefined();
|
expect(claudeCli).toBeDefined();
|
||||||
expect(claudeCli?.hint).toBe("Uses Claude Code auth · requires Keychain access");
|
expect(claudeCli?.hint).toBe("requires Keychain access");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("skips missing Claude Code CLI option off macOS", () => {
|
it("skips missing Claude Code CLI option off macOS", () => {
|
||||||
|
|||||||
@@ -160,26 +160,26 @@ export function buildAuthChoiceOptions(params: {
|
|||||||
options.push({
|
options.push({
|
||||||
value: "claude-cli",
|
value: "claude-cli",
|
||||||
label: "Anthropic token (Claude Code CLI)",
|
label: "Anthropic token (Claude Code CLI)",
|
||||||
hint: `Reuses existing Claude Code auth · ${formatOAuthHint(claudeCli.expires)}`,
|
hint: formatOAuthHint(claudeCli.expires),
|
||||||
});
|
});
|
||||||
} else if (params.includeClaudeCliIfMissing && platform === "darwin") {
|
} else if (params.includeClaudeCliIfMissing && platform === "darwin") {
|
||||||
options.push({
|
options.push({
|
||||||
value: "claude-cli",
|
value: "claude-cli",
|
||||||
label: "Anthropic token (Claude Code CLI)",
|
label: "Anthropic token (Claude Code CLI)",
|
||||||
hint: "Uses Claude Code auth · requires Keychain access",
|
hint: "requires Keychain access",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
options.push({
|
options.push({
|
||||||
value: "setup-token",
|
value: "setup-token",
|
||||||
label: "Anthropic token (run setup-token)",
|
label: "Anthropic token (run setup-token)",
|
||||||
hint: "Runs `claude setup-token` · opens browser for fresh OAuth login",
|
hint: "Runs `claude setup-token`",
|
||||||
});
|
});
|
||||||
|
|
||||||
options.push({
|
options.push({
|
||||||
value: "token",
|
value: "token",
|
||||||
label: "Anthropic token (paste setup-token)",
|
label: "Anthropic token (paste setup-token)",
|
||||||
hint: "Run `claude setup-token` elsewhere, then paste the token here",
|
hint: "Run `claude setup-token`, then paste the token",
|
||||||
});
|
});
|
||||||
|
|
||||||
options.push({
|
options.push({
|
||||||
|
|||||||
@@ -214,9 +214,8 @@ async function maybeConfigureDmPolicies(params: {
|
|||||||
cfg: ClawdbotConfig;
|
cfg: ClawdbotConfig;
|
||||||
selection: ChannelChoice[];
|
selection: ChannelChoice[];
|
||||||
prompter: WizardPrompter;
|
prompter: WizardPrompter;
|
||||||
accountIdsByChannel?: Map<ChannelChoice, string>;
|
|
||||||
}): Promise<ClawdbotConfig> {
|
}): Promise<ClawdbotConfig> {
|
||||||
const { selection, prompter, accountIdsByChannel } = params;
|
const { selection, prompter } = params;
|
||||||
const dmPolicies = selection
|
const dmPolicies = selection
|
||||||
.map((channel) => getChannelOnboardingAdapter(channel)?.dmPolicy)
|
.map((channel) => getChannelOnboardingAdapter(channel)?.dmPolicy)
|
||||||
.filter(Boolean) as ChannelOnboardingDmPolicy[];
|
.filter(Boolean) as ChannelOnboardingDmPolicy[];
|
||||||
@@ -234,7 +233,6 @@ async function maybeConfigureDmPolicies(params: {
|
|||||||
[
|
[
|
||||||
"Default: pairing (unknown DMs get a pairing code).",
|
"Default: pairing (unknown DMs get a pairing code).",
|
||||||
`Approve: clawdbot pairing approve ${policy.channel} <code>`,
|
`Approve: clawdbot pairing approve ${policy.channel} <code>`,
|
||||||
`Allowlist DMs: ${policy.policyKey}="allowlist" + ${policy.allowFromKey} entries.`,
|
|
||||||
`Public DMs: ${policy.policyKey}="open" + ${policy.allowFromKey} includes "*".`,
|
`Public DMs: ${policy.policyKey}="open" + ${policy.allowFromKey} includes "*".`,
|
||||||
'Multi-user DMs: set session.dmScope="per-channel-peer" to isolate sessions.',
|
'Multi-user DMs: set session.dmScope="per-channel-peer" to isolate sessions.',
|
||||||
`Docs: ${formatDocsLink("/start/pairing", "start/pairing")}`,
|
`Docs: ${formatDocsLink("/start/pairing", "start/pairing")}`,
|
||||||
@@ -245,7 +243,6 @@ async function maybeConfigureDmPolicies(params: {
|
|||||||
message: `${policy.label} DM policy`,
|
message: `${policy.label} DM policy`,
|
||||||
options: [
|
options: [
|
||||||
{ value: "pairing", label: "Pairing (recommended)" },
|
{ value: "pairing", label: "Pairing (recommended)" },
|
||||||
{ value: "allowlist", label: "Allowlist (specific users only)" },
|
|
||||||
{ value: "open", label: "Open (public inbound DMs)" },
|
{ value: "open", label: "Open (public inbound DMs)" },
|
||||||
{ value: "disabled", label: "Disabled (ignore DMs)" },
|
{ value: "disabled", label: "Disabled (ignore DMs)" },
|
||||||
],
|
],
|
||||||
@@ -258,13 +255,6 @@ async function maybeConfigureDmPolicies(params: {
|
|||||||
if (nextPolicy !== current) {
|
if (nextPolicy !== current) {
|
||||||
cfg = policy.setPolicy(cfg, nextPolicy);
|
cfg = policy.setPolicy(cfg, nextPolicy);
|
||||||
}
|
}
|
||||||
if (nextPolicy === "allowlist" && policy.promptAllowFrom) {
|
|
||||||
cfg = await policy.promptAllowFrom({
|
|
||||||
cfg,
|
|
||||||
prompter,
|
|
||||||
accountId: accountIdsByChannel?.get(policy.channel),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return cfg;
|
return cfg;
|
||||||
@@ -330,12 +320,10 @@ export async function setupChannels(
|
|||||||
options?.initialSelection?.[0] ?? resolveQuickstartDefault(statusByChannel);
|
options?.initialSelection?.[0] ?? resolveQuickstartDefault(statusByChannel);
|
||||||
|
|
||||||
const shouldPromptAccountIds = options?.promptAccountIds === true;
|
const shouldPromptAccountIds = options?.promptAccountIds === true;
|
||||||
const accountIdsByChannel = new Map<ChannelChoice, string>();
|
|
||||||
const recordAccount = (channel: ChannelChoice, accountId: string) => {
|
const recordAccount = (channel: ChannelChoice, accountId: string) => {
|
||||||
options?.onAccountId?.(channel, accountId);
|
options?.onAccountId?.(channel, accountId);
|
||||||
const adapter = getChannelOnboardingAdapter(channel);
|
const adapter = getChannelOnboardingAdapter(channel);
|
||||||
adapter?.onAccountRecorded?.(accountId, options);
|
adapter?.onAccountRecorded?.(accountId, options);
|
||||||
accountIdsByChannel.set(channel, accountId);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const selection: ChannelChoice[] = [];
|
const selection: ChannelChoice[] = [];
|
||||||
@@ -626,12 +614,7 @@ export async function setupChannels(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!options?.skipDmPolicyPrompt) {
|
if (!options?.skipDmPolicyPrompt) {
|
||||||
next = await maybeConfigureDmPolicies({
|
next = await maybeConfigureDmPolicies({ cfg: next, selection, prompter });
|
||||||
cfg: next,
|
|
||||||
selection,
|
|
||||||
prompter,
|
|
||||||
accountIdsByChannel,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return next;
|
return next;
|
||||||
|
|||||||
@@ -206,37 +206,6 @@ describe("sessions", () => {
|
|||||||
expect(store[sessionKey]?.origin?.chatType).toBe("group");
|
expect(store[sessionKey]?.origin?.chatType).toBe("group");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("updateSessionStoreEntry preserves existing fields when patching", async () => {
|
|
||||||
const sessionKey = "agent:main:main";
|
|
||||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-sessions-"));
|
|
||||||
const storePath = path.join(dir, "sessions.json");
|
|
||||||
await fs.writeFile(
|
|
||||||
storePath,
|
|
||||||
JSON.stringify(
|
|
||||||
{
|
|
||||||
[sessionKey]: {
|
|
||||||
sessionId: "sess-1",
|
|
||||||
updatedAt: 100,
|
|
||||||
reasoningLevel: "on",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
null,
|
|
||||||
2,
|
|
||||||
),
|
|
||||||
"utf-8",
|
|
||||||
);
|
|
||||||
|
|
||||||
await updateSessionStoreEntry({
|
|
||||||
storePath,
|
|
||||||
sessionKey,
|
|
||||||
update: async () => ({ updatedAt: 200 }),
|
|
||||||
});
|
|
||||||
|
|
||||||
const store = loadSessionStore(storePath);
|
|
||||||
expect(store[sessionKey]?.updatedAt).toBeGreaterThanOrEqual(200);
|
|
||||||
expect(store[sessionKey]?.reasoningLevel).toBe("on");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("updateSessionStore preserves concurrent additions", async () => {
|
it("updateSessionStore preserves concurrent additions", async () => {
|
||||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-sessions-"));
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-sessions-"));
|
||||||
const storePath = path.join(dir, "sessions.json");
|
const storePath = path.join(dir, "sessions.json");
|
||||||
|
|||||||
@@ -35,15 +35,6 @@ export function resolveAgentMainSessionKey(params: {
|
|||||||
return buildAgentMainSessionKey({ agentId: params.agentId, mainKey });
|
return buildAgentMainSessionKey({ agentId: params.agentId, mainKey });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resolveExplicitAgentSessionKey(params: {
|
|
||||||
cfg?: { session?: { scope?: SessionScope; mainKey?: string } };
|
|
||||||
agentId?: string | null;
|
|
||||||
}): string | undefined {
|
|
||||||
const agentId = params.agentId?.trim();
|
|
||||||
if (!agentId) return undefined;
|
|
||||||
return resolveAgentMainSessionKey({ cfg: params.cfg, agentId });
|
|
||||||
}
|
|
||||||
|
|
||||||
export function canonicalizeMainSessionAlias(params: {
|
export function canonicalizeMainSessionAlias(params: {
|
||||||
cfg?: { session?: { scope?: SessionScope; mainKey?: string } };
|
cfg?: { session?: { scope?: SessionScope; mainKey?: string } };
|
||||||
agentId: string;
|
agentId: string;
|
||||||
|
|||||||
@@ -45,18 +45,14 @@ export const PollParamsSchema = Type.Object(
|
|||||||
export const AgentParamsSchema = Type.Object(
|
export const AgentParamsSchema = Type.Object(
|
||||||
{
|
{
|
||||||
message: NonEmptyString,
|
message: NonEmptyString,
|
||||||
agentId: Type.Optional(NonEmptyString),
|
|
||||||
to: Type.Optional(Type.String()),
|
to: Type.Optional(Type.String()),
|
||||||
replyTo: Type.Optional(Type.String()),
|
|
||||||
sessionId: Type.Optional(Type.String()),
|
sessionId: Type.Optional(Type.String()),
|
||||||
sessionKey: Type.Optional(Type.String()),
|
sessionKey: Type.Optional(Type.String()),
|
||||||
thinking: Type.Optional(Type.String()),
|
thinking: Type.Optional(Type.String()),
|
||||||
deliver: Type.Optional(Type.Boolean()),
|
deliver: Type.Optional(Type.Boolean()),
|
||||||
attachments: Type.Optional(Type.Array(Type.Unknown())),
|
attachments: Type.Optional(Type.Array(Type.Unknown())),
|
||||||
channel: Type.Optional(Type.String()),
|
channel: Type.Optional(Type.String()),
|
||||||
replyChannel: Type.Optional(Type.String()),
|
|
||||||
accountId: Type.Optional(Type.String()),
|
accountId: Type.Optional(Type.String()),
|
||||||
replyAccountId: Type.Optional(Type.String()),
|
|
||||||
timeout: Type.Optional(Type.Integer({ minimum: 0 })),
|
timeout: Type.Optional(Type.Integer({ minimum: 0 })),
|
||||||
lane: Type.Optional(Type.String()),
|
lane: Type.Optional(Type.String()),
|
||||||
extraSystemPrompt: Type.Optional(Type.String()),
|
extraSystemPrompt: Type.Optional(Type.String()),
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import { agentCommand } from "../../commands/agent.js";
|
import { agentCommand } from "../../commands/agent.js";
|
||||||
import { listAgentIds } from "../../agents/agent-scope.js";
|
|
||||||
import { loadConfig } from "../../config/config.js";
|
import { loadConfig } from "../../config/config.js";
|
||||||
import {
|
import {
|
||||||
resolveAgentIdFromSessionKey,
|
resolveAgentIdFromSessionKey,
|
||||||
resolveExplicitAgentSessionKey,
|
|
||||||
resolveAgentMainSessionKey,
|
resolveAgentMainSessionKey,
|
||||||
type SessionEntry,
|
type SessionEntry,
|
||||||
updateSessionStore,
|
updateSessionStore,
|
||||||
@@ -23,7 +21,6 @@ import {
|
|||||||
isGatewayMessageChannel,
|
isGatewayMessageChannel,
|
||||||
normalizeMessageChannel,
|
normalizeMessageChannel,
|
||||||
} from "../../utils/message-channel.js";
|
} from "../../utils/message-channel.js";
|
||||||
import { normalizeAgentId } from "../../routing/session-key.js";
|
|
||||||
import { parseMessageWithAttachments } from "../chat-attachments.js";
|
import { parseMessageWithAttachments } from "../chat-attachments.js";
|
||||||
import {
|
import {
|
||||||
type AgentWaitParams,
|
type AgentWaitParams,
|
||||||
@@ -54,9 +51,7 @@ export const agentHandlers: GatewayRequestHandlers = {
|
|||||||
}
|
}
|
||||||
const request = p as {
|
const request = p as {
|
||||||
message: string;
|
message: string;
|
||||||
agentId?: string;
|
|
||||||
to?: string;
|
to?: string;
|
||||||
replyTo?: string;
|
|
||||||
sessionId?: string;
|
sessionId?: string;
|
||||||
sessionKey?: string;
|
sessionKey?: string;
|
||||||
thinking?: string;
|
thinking?: string;
|
||||||
@@ -68,9 +63,7 @@ export const agentHandlers: GatewayRequestHandlers = {
|
|||||||
content?: unknown;
|
content?: unknown;
|
||||||
}>;
|
}>;
|
||||||
channel?: string;
|
channel?: string;
|
||||||
replyChannel?: string;
|
|
||||||
accountId?: string;
|
accountId?: string;
|
||||||
replyAccountId?: string;
|
|
||||||
lane?: string;
|
lane?: string;
|
||||||
extraSystemPrompt?: string;
|
extraSystemPrompt?: string;
|
||||||
idempotencyKey: string;
|
idempotencyKey: string;
|
||||||
@@ -78,7 +71,6 @@ export const agentHandlers: GatewayRequestHandlers = {
|
|||||||
label?: string;
|
label?: string;
|
||||||
spawnedBy?: string;
|
spawnedBy?: string;
|
||||||
};
|
};
|
||||||
const cfg = loadConfig();
|
|
||||||
const idem = request.idempotencyKey;
|
const idem = request.idempotencyKey;
|
||||||
const cached = context.dedupe.get(`agent:${idem}`);
|
const cached = context.dedupe.get(`agent:${idem}`);
|
||||||
if (cached) {
|
if (cached) {
|
||||||
@@ -121,12 +113,9 @@ export const agentHandlers: GatewayRequestHandlers = {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const isKnownGatewayChannel = (value: string): boolean => isGatewayMessageChannel(value);
|
const rawChannel = typeof request.channel === "string" ? request.channel.trim() : "";
|
||||||
const channelHints = [request.channel, request.replyChannel]
|
if (rawChannel) {
|
||||||
.filter((value): value is string => typeof value === "string")
|
const isKnownGatewayChannel = (value: string): boolean => isGatewayMessageChannel(value);
|
||||||
.map((value) => value.trim())
|
|
||||||
.filter(Boolean);
|
|
||||||
for (const rawChannel of channelHints) {
|
|
||||||
const normalized = normalizeMessageChannel(rawChannel);
|
const normalized = normalizeMessageChannel(rawChannel);
|
||||||
if (normalized && normalized !== "last" && !isKnownGatewayChannel(normalized)) {
|
if (normalized && normalized !== "last" && !isKnownGatewayChannel(normalized)) {
|
||||||
respond(
|
respond(
|
||||||
@@ -141,47 +130,10 @@ export const agentHandlers: GatewayRequestHandlers = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const agentIdRaw = typeof request.agentId === "string" ? request.agentId.trim() : "";
|
const requestedSessionKey =
|
||||||
const agentId = agentIdRaw ? normalizeAgentId(agentIdRaw) : undefined;
|
|
||||||
if (agentId) {
|
|
||||||
const knownAgents = listAgentIds(cfg);
|
|
||||||
if (!knownAgents.includes(agentId)) {
|
|
||||||
respond(
|
|
||||||
false,
|
|
||||||
undefined,
|
|
||||||
errorShape(
|
|
||||||
ErrorCodes.INVALID_REQUEST,
|
|
||||||
`invalid agent params: unknown agent id "${request.agentId}"`,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const requestedSessionKeyRaw =
|
|
||||||
typeof request.sessionKey === "string" && request.sessionKey.trim()
|
typeof request.sessionKey === "string" && request.sessionKey.trim()
|
||||||
? request.sessionKey.trim()
|
? request.sessionKey.trim()
|
||||||
: undefined;
|
: undefined;
|
||||||
const requestedSessionKey =
|
|
||||||
requestedSessionKeyRaw ??
|
|
||||||
resolveExplicitAgentSessionKey({
|
|
||||||
cfg,
|
|
||||||
agentId,
|
|
||||||
});
|
|
||||||
if (agentId && requestedSessionKeyRaw) {
|
|
||||||
const sessionAgentId = resolveAgentIdFromSessionKey(requestedSessionKeyRaw);
|
|
||||||
if (sessionAgentId !== agentId) {
|
|
||||||
respond(
|
|
||||||
false,
|
|
||||||
undefined,
|
|
||||||
errorShape(
|
|
||||||
ErrorCodes.INVALID_REQUEST,
|
|
||||||
`invalid agent params: agent "${request.agentId}" does not match session key agent "${sessionAgentId}"`,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let resolvedSessionId = request.sessionId?.trim() || undefined;
|
let resolvedSessionId = request.sessionId?.trim() || undefined;
|
||||||
let sessionEntry: SessionEntry | undefined;
|
let sessionEntry: SessionEntry | undefined;
|
||||||
let bestEffortDeliver = false;
|
let bestEffortDeliver = false;
|
||||||
@@ -252,16 +204,12 @@ export const agentHandlers: GatewayRequestHandlers = {
|
|||||||
|
|
||||||
const wantsDelivery = request.deliver === true;
|
const wantsDelivery = request.deliver === true;
|
||||||
const explicitTo =
|
const explicitTo =
|
||||||
typeof request.replyTo === "string" && request.replyTo.trim()
|
typeof request.to === "string" && request.to.trim() ? request.to.trim() : undefined;
|
||||||
? request.replyTo.trim()
|
|
||||||
: typeof request.to === "string" && request.to.trim()
|
|
||||||
? request.to.trim()
|
|
||||||
: undefined;
|
|
||||||
const deliveryPlan = resolveAgentDeliveryPlan({
|
const deliveryPlan = resolveAgentDeliveryPlan({
|
||||||
sessionEntry,
|
sessionEntry,
|
||||||
requestedChannel: request.replyChannel ?? request.channel,
|
requestedChannel: request.channel,
|
||||||
explicitTo,
|
explicitTo,
|
||||||
accountId: request.replyAccountId ?? request.accountId,
|
accountId: request.accountId,
|
||||||
wantsDelivery,
|
wantsDelivery,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -271,9 +219,9 @@ export const agentHandlers: GatewayRequestHandlers = {
|
|||||||
let resolvedTo = deliveryPlan.resolvedTo;
|
let resolvedTo = deliveryPlan.resolvedTo;
|
||||||
|
|
||||||
if (!resolvedTo && isDeliverableMessageChannel(resolvedChannel)) {
|
if (!resolvedTo && isDeliverableMessageChannel(resolvedChannel)) {
|
||||||
const cfgResolved = cfgForAgent ?? cfg;
|
const cfg = cfgForAgent ?? loadConfig();
|
||||||
const fallback = resolveAgentOutboundTarget({
|
const fallback = resolveAgentOutboundTarget({
|
||||||
cfg: cfgResolved,
|
cfg,
|
||||||
plan: deliveryPlan,
|
plan: deliveryPlan,
|
||||||
targetMode: "implicit",
|
targetMode: "implicit",
|
||||||
validateExplicitTarget: false,
|
validateExplicitTarget: false,
|
||||||
|
|||||||
@@ -214,83 +214,6 @@ describe("gateway server agent", () => {
|
|||||||
await server.close();
|
await server.close();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("agent derives sessionKey from agentId", async () => {
|
|
||||||
registryState.registry = defaultRegistry;
|
|
||||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-gw-"));
|
|
||||||
testState.sessionStorePath = path.join(dir, "sessions.json");
|
|
||||||
testState.agentsConfig = { list: [{ id: "ops" }] };
|
|
||||||
await writeSessionStore({
|
|
||||||
agentId: "ops",
|
|
||||||
entries: {
|
|
||||||
main: {
|
|
||||||
sessionId: "sess-ops",
|
|
||||||
updatedAt: Date.now(),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const { server, ws } = await startServerWithClient();
|
|
||||||
await connectOk(ws);
|
|
||||||
|
|
||||||
const res = await rpcReq(ws, "agent", {
|
|
||||||
message: "hi",
|
|
||||||
agentId: "ops",
|
|
||||||
idempotencyKey: "idem-agent-id",
|
|
||||||
});
|
|
||||||
expect(res.ok).toBe(true);
|
|
||||||
|
|
||||||
const spy = vi.mocked(agentCommand);
|
|
||||||
const call = spy.mock.calls.at(-1)?.[0] as Record<string, unknown>;
|
|
||||||
expect(call.sessionKey).toBe("agent:ops:main");
|
|
||||||
expect(call.sessionId).toBe("sess-ops");
|
|
||||||
|
|
||||||
ws.close();
|
|
||||||
await server.close();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("agent rejects unknown reply channel", async () => {
|
|
||||||
registryState.registry = defaultRegistry;
|
|
||||||
const { server, ws } = await startServerWithClient();
|
|
||||||
await connectOk(ws);
|
|
||||||
|
|
||||||
const res = await rpcReq(ws, "agent", {
|
|
||||||
message: "hi",
|
|
||||||
replyChannel: "unknown-channel",
|
|
||||||
idempotencyKey: "idem-agent-reply-unknown",
|
|
||||||
});
|
|
||||||
expect(res.ok).toBe(false);
|
|
||||||
expect(res.error?.message).toContain("unknown channel");
|
|
||||||
|
|
||||||
const spy = vi.mocked(agentCommand);
|
|
||||||
expect(spy).not.toHaveBeenCalled();
|
|
||||||
|
|
||||||
ws.close();
|
|
||||||
await server.close();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("agent rejects mismatched agentId and sessionKey", async () => {
|
|
||||||
registryState.registry = defaultRegistry;
|
|
||||||
testState.agentsConfig = { list: [{ id: "ops" }] };
|
|
||||||
|
|
||||||
const { server, ws } = await startServerWithClient();
|
|
||||||
await connectOk(ws);
|
|
||||||
|
|
||||||
const res = await rpcReq(ws, "agent", {
|
|
||||||
message: "hi",
|
|
||||||
agentId: "ops",
|
|
||||||
sessionKey: "agent:main:main",
|
|
||||||
idempotencyKey: "idem-agent-mismatch",
|
|
||||||
});
|
|
||||||
expect(res.ok).toBe(false);
|
|
||||||
expect(res.error?.message).toContain("does not match session key agent");
|
|
||||||
|
|
||||||
const spy = vi.mocked(agentCommand);
|
|
||||||
expect(spy).not.toHaveBeenCalled();
|
|
||||||
|
|
||||||
ws.close();
|
|
||||||
await server.close();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("agent forwards accountId to agentCommand", async () => {
|
test("agent forwards accountId to agentCommand", async () => {
|
||||||
registryState.registry = defaultRegistry;
|
registryState.registry = defaultRegistry;
|
||||||
testState.allowFrom = ["+1555"];
|
testState.allowFrom = ["+1555"];
|
||||||
|
|||||||
@@ -24,17 +24,6 @@ export const normalizeAllowFrom = (list?: Array<string | number>): NormalizedAll
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
export const normalizeAllowFromWithStore = (params: {
|
|
||||||
allowFrom?: Array<string | number>;
|
|
||||||
storeAllowFrom?: string[];
|
|
||||||
}): NormalizedAllowFrom => {
|
|
||||||
const combined = [
|
|
||||||
...(params.allowFrom ?? []),
|
|
||||||
...(params.storeAllowFrom ?? []),
|
|
||||||
].map((value) => String(value).trim()).filter(Boolean);
|
|
||||||
return normalizeAllowFrom(combined);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const firstDefined = <T>(...values: Array<T | undefined>) => {
|
export const firstDefined = <T>(...values: Array<T | undefined>) => {
|
||||||
for (const value of values) {
|
for (const value of values) {
|
||||||
if (typeof value !== "undefined") return value;
|
if (typeof value !== "undefined") return value;
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import { danger, logVerbose, warn } from "../globals.js";
|
|||||||
import { resolveMedia } from "./bot/delivery.js";
|
import { resolveMedia } from "./bot/delivery.js";
|
||||||
import { resolveTelegramForumThreadId } from "./bot/helpers.js";
|
import { resolveTelegramForumThreadId } from "./bot/helpers.js";
|
||||||
import type { TelegramMessage } from "./bot/types.js";
|
import type { TelegramMessage } from "./bot/types.js";
|
||||||
import { firstDefined, isSenderAllowed, normalizeAllowFromWithStore } from "./bot-access.js";
|
import { firstDefined, isSenderAllowed, normalizeAllowFrom } from "./bot-access.js";
|
||||||
import { MEDIA_GROUP_TIMEOUT_MS, type MediaGroupEntry } from "./bot-updates.js";
|
import { MEDIA_GROUP_TIMEOUT_MS, type MediaGroupEntry } from "./bot-updates.js";
|
||||||
import { migrateTelegramGroupConfig } from "./group-migration.js";
|
import { migrateTelegramGroupConfig } from "./group-migration.js";
|
||||||
import { resolveTelegramInlineButtonsScope } from "./inline-buttons.js";
|
import { resolveTelegramInlineButtonsScope } from "./inline-buttons.js";
|
||||||
@@ -205,14 +205,14 @@ export const registerTelegramHandlers = ({
|
|||||||
const { groupConfig, topicConfig } = resolveTelegramGroupConfig(chatId, resolvedThreadId);
|
const { groupConfig, topicConfig } = resolveTelegramGroupConfig(chatId, resolvedThreadId);
|
||||||
const storeAllowFrom = await readTelegramAllowFromStore().catch(() => []);
|
const storeAllowFrom = await readTelegramAllowFromStore().catch(() => []);
|
||||||
const groupAllowOverride = firstDefined(topicConfig?.allowFrom, groupConfig?.allowFrom);
|
const groupAllowOverride = firstDefined(topicConfig?.allowFrom, groupConfig?.allowFrom);
|
||||||
const effectiveGroupAllow = normalizeAllowFromWithStore({
|
const effectiveGroupAllow = normalizeAllowFrom([
|
||||||
allowFrom: groupAllowOverride ?? groupAllowFrom,
|
...(groupAllowOverride ?? groupAllowFrom ?? []),
|
||||||
storeAllowFrom,
|
...storeAllowFrom,
|
||||||
});
|
]);
|
||||||
const effectiveDmAllow = normalizeAllowFromWithStore({
|
const effectiveDmAllow = normalizeAllowFrom([
|
||||||
allowFrom: telegramCfg.allowFrom,
|
...(telegramCfg.allowFrom ?? []),
|
||||||
storeAllowFrom,
|
...storeAllowFrom,
|
||||||
});
|
]);
|
||||||
const dmPolicy = telegramCfg.dmPolicy ?? "pairing";
|
const dmPolicy = telegramCfg.dmPolicy ?? "pairing";
|
||||||
const senderId = callback.from?.id ? String(callback.from.id) : "";
|
const senderId = callback.from?.id ? String(callback.from.id) : "";
|
||||||
const senderUsername = callback.from?.username ?? "";
|
const senderUsername = callback.from?.username ?? "";
|
||||||
@@ -393,10 +393,10 @@ export const registerTelegramHandlers = ({
|
|||||||
const storeAllowFrom = await readTelegramAllowFromStore().catch(() => []);
|
const storeAllowFrom = await readTelegramAllowFromStore().catch(() => []);
|
||||||
const { groupConfig, topicConfig } = resolveTelegramGroupConfig(chatId, resolvedThreadId);
|
const { groupConfig, topicConfig } = resolveTelegramGroupConfig(chatId, resolvedThreadId);
|
||||||
const groupAllowOverride = firstDefined(topicConfig?.allowFrom, groupConfig?.allowFrom);
|
const groupAllowOverride = firstDefined(topicConfig?.allowFrom, groupConfig?.allowFrom);
|
||||||
const effectiveGroupAllow = normalizeAllowFromWithStore({
|
const effectiveGroupAllow = normalizeAllowFrom([
|
||||||
allowFrom: groupAllowOverride ?? groupAllowFrom,
|
...(groupAllowOverride ?? groupAllowFrom ?? []),
|
||||||
storeAllowFrom,
|
...storeAllowFrom,
|
||||||
});
|
]);
|
||||||
const hasGroupAllowOverride = typeof groupAllowOverride !== "undefined";
|
const hasGroupAllowOverride = typeof groupAllowOverride !== "undefined";
|
||||||
|
|
||||||
if (isGroup) {
|
if (isGroup) {
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ import {
|
|||||||
import {
|
import {
|
||||||
firstDefined,
|
firstDefined,
|
||||||
isSenderAllowed,
|
isSenderAllowed,
|
||||||
normalizeAllowFromWithStore,
|
normalizeAllowFrom,
|
||||||
resolveSenderAllowMatch,
|
resolveSenderAllowMatch,
|
||||||
} from "./bot-access.js";
|
} from "./bot-access.js";
|
||||||
import { upsertTelegramPairingRequest } from "./pairing-store.js";
|
import { upsertTelegramPairingRequest } from "./pairing-store.js";
|
||||||
@@ -138,12 +138,12 @@ export const buildTelegramMessageContext = async ({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
const mentionRegexes = buildMentionRegexes(cfg, route.agentId);
|
const mentionRegexes = buildMentionRegexes(cfg, route.agentId);
|
||||||
const effectiveDmAllow = normalizeAllowFromWithStore({ allowFrom, storeAllowFrom });
|
const effectiveDmAllow = normalizeAllowFrom([...(allowFrom ?? []), ...storeAllowFrom]);
|
||||||
const groupAllowOverride = firstDefined(topicConfig?.allowFrom, groupConfig?.allowFrom);
|
const groupAllowOverride = firstDefined(topicConfig?.allowFrom, groupConfig?.allowFrom);
|
||||||
const effectiveGroupAllow = normalizeAllowFromWithStore({
|
const effectiveGroupAllow = normalizeAllowFrom([
|
||||||
allowFrom: groupAllowOverride ?? groupAllowFrom,
|
...(groupAllowOverride ?? groupAllowFrom ?? []),
|
||||||
storeAllowFrom,
|
...storeAllowFrom,
|
||||||
});
|
]);
|
||||||
const hasGroupAllowOverride = typeof groupAllowOverride !== "undefined";
|
const hasGroupAllowOverride = typeof groupAllowOverride !== "undefined";
|
||||||
|
|
||||||
if (isGroup && groupConfig?.enabled === false) {
|
if (isGroup && groupConfig?.enabled === false) {
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ import {
|
|||||||
buildTelegramGroupPeerId,
|
buildTelegramGroupPeerId,
|
||||||
resolveTelegramForumThreadId,
|
resolveTelegramForumThreadId,
|
||||||
} from "./bot/helpers.js";
|
} from "./bot/helpers.js";
|
||||||
import { firstDefined, isSenderAllowed, normalizeAllowFromWithStore } from "./bot-access.js";
|
import { firstDefined, isSenderAllowed, normalizeAllowFrom } from "./bot-access.js";
|
||||||
import { readTelegramAllowFromStore } from "./pairing-store.js";
|
import { readTelegramAllowFromStore } from "./pairing-store.js";
|
||||||
|
|
||||||
type TelegramNativeCommandContext = Context & { match?: string };
|
type TelegramNativeCommandContext = Context & { match?: string };
|
||||||
@@ -132,10 +132,10 @@ export const registerTelegramNativeCommands = ({
|
|||||||
const storeAllowFrom = await readTelegramAllowFromStore().catch(() => []);
|
const storeAllowFrom = await readTelegramAllowFromStore().catch(() => []);
|
||||||
const { groupConfig, topicConfig } = resolveTelegramGroupConfig(chatId, resolvedThreadId);
|
const { groupConfig, topicConfig } = resolveTelegramGroupConfig(chatId, resolvedThreadId);
|
||||||
const groupAllowOverride = firstDefined(topicConfig?.allowFrom, groupConfig?.allowFrom);
|
const groupAllowOverride = firstDefined(topicConfig?.allowFrom, groupConfig?.allowFrom);
|
||||||
const effectiveGroupAllow = normalizeAllowFromWithStore({
|
const effectiveGroupAllow = normalizeAllowFrom([
|
||||||
allowFrom: groupAllowOverride ?? groupAllowFrom,
|
...(groupAllowOverride ?? groupAllowFrom ?? []),
|
||||||
storeAllowFrom,
|
...storeAllowFrom,
|
||||||
});
|
]);
|
||||||
const hasGroupAllowOverride = typeof groupAllowOverride !== "undefined";
|
const hasGroupAllowOverride = typeof groupAllowOverride !== "undefined";
|
||||||
|
|
||||||
if (isGroup && groupConfig?.enabled === false) {
|
if (isGroup && groupConfig?.enabled === false) {
|
||||||
@@ -194,12 +194,12 @@ export const registerTelegramNativeCommands = ({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const allowFromList = Array.isArray(allowFrom)
|
||||||
|
? allowFrom.map((entry) => String(entry).trim()).filter(Boolean)
|
||||||
|
: [];
|
||||||
const senderId = msg.from?.id ? String(msg.from.id) : "";
|
const senderId = msg.from?.id ? String(msg.from.id) : "";
|
||||||
const senderUsername = msg.from?.username ?? "";
|
const senderUsername = msg.from?.username ?? "";
|
||||||
const dmAllow = normalizeAllowFromWithStore({
|
const dmAllow = normalizeAllowFrom(allowFromList);
|
||||||
allowFrom: allowFrom,
|
|
||||||
storeAllowFrom,
|
|
||||||
});
|
|
||||||
const senderAllowed = isSenderAllowed({
|
const senderAllowed = isSenderAllowed({
|
||||||
allow: dmAllow,
|
allow: dmAllow,
|
||||||
senderId,
|
senderId,
|
||||||
|
|||||||
@@ -2138,49 +2138,6 @@ describe("createTelegramBot", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("allows native DM commands for paired users", async () => {
|
|
||||||
onSpy.mockReset();
|
|
||||||
sendMessageSpy.mockReset();
|
|
||||||
commandSpy.mockReset();
|
|
||||||
const replySpy = replyModule.__replySpy as unknown as ReturnType<typeof vi.fn>;
|
|
||||||
replySpy.mockReset();
|
|
||||||
replySpy.mockResolvedValue({ text: "response" });
|
|
||||||
|
|
||||||
loadConfig.mockReturnValue({
|
|
||||||
commands: { native: true },
|
|
||||||
channels: {
|
|
||||||
telegram: {
|
|
||||||
dmPolicy: "pairing",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
readTelegramAllowFromStore.mockResolvedValueOnce(["12345"]);
|
|
||||||
|
|
||||||
createTelegramBot({ token: "tok" });
|
|
||||||
const handler = commandSpy.mock.calls.find((call) => call[0] === "status")?.[1] as
|
|
||||||
| ((ctx: Record<string, unknown>) => Promise<void>)
|
|
||||||
| undefined;
|
|
||||||
if (!handler) throw new Error("status command handler missing");
|
|
||||||
|
|
||||||
await handler({
|
|
||||||
message: {
|
|
||||||
chat: { id: 12345, type: "private" },
|
|
||||||
from: { id: 12345, username: "testuser" },
|
|
||||||
text: "/status",
|
|
||||||
date: 1736380800,
|
|
||||||
message_id: 42,
|
|
||||||
},
|
|
||||||
match: "",
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(replySpy).toHaveBeenCalledTimes(1);
|
|
||||||
expect(
|
|
||||||
sendMessageSpy.mock.calls.some(
|
|
||||||
(call) => call[1] === "You are not authorized to use this command.",
|
|
||||||
),
|
|
||||||
).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("streams tool summaries for native slash commands", async () => {
|
it("streams tool summaries for native slash commands", async () => {
|
||||||
onSpy.mockReset();
|
onSpy.mockReset();
|
||||||
sendMessageSpy.mockReset();
|
sendMessageSpy.mockReset();
|
||||||
|
|||||||
@@ -1,41 +0,0 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
|
||||||
|
|
||||||
import { buildWaitingStatusMessage, pickWaitingPhrase } from "./tui-waiting.js";
|
|
||||||
|
|
||||||
const theme = {
|
|
||||||
dim: (s: string) => `<d>${s}</d>`,
|
|
||||||
bold: (s: string) => `<b>${s}</b>`,
|
|
||||||
accentSoft: (s: string) => `<a>${s}</a>`,
|
|
||||||
} as any;
|
|
||||||
|
|
||||||
describe("tui-waiting", () => {
|
|
||||||
it("pickWaitingPhrase rotates every 10 ticks", () => {
|
|
||||||
const phrases = ["a", "b", "c"];
|
|
||||||
expect(pickWaitingPhrase(0, phrases)).toBe("a");
|
|
||||||
expect(pickWaitingPhrase(9, phrases)).toBe("a");
|
|
||||||
expect(pickWaitingPhrase(10, phrases)).toBe("b");
|
|
||||||
expect(pickWaitingPhrase(20, phrases)).toBe("c");
|
|
||||||
expect(pickWaitingPhrase(30, phrases)).toBe("a");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("buildWaitingStatusMessage includes shimmer markup and metadata", () => {
|
|
||||||
const msg = buildWaitingStatusMessage({
|
|
||||||
theme,
|
|
||||||
tick: 1,
|
|
||||||
elapsed: "3s",
|
|
||||||
connectionStatus: "connected",
|
|
||||||
phrases: ["hello"],
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(msg).toContain("connected");
|
|
||||||
expect(msg).toContain("3s");
|
|
||||||
// text is wrapped per-char; check it appears in order
|
|
||||||
expect(msg).toContain("h");
|
|
||||||
expect(msg).toContain("e");
|
|
||||||
expect(msg).toContain("l");
|
|
||||||
expect(msg).toContain("o");
|
|
||||||
// shimmer should contain both highlighted and dim parts
|
|
||||||
expect(msg).toContain("<b><a>");
|
|
||||||
expect(msg).toContain("<d>");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
type MinimalTheme = {
|
|
||||||
dim: (s: string) => string;
|
|
||||||
bold: (s: string) => string;
|
|
||||||
accentSoft: (s: string) => string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const defaultWaitingPhrases = [
|
|
||||||
"flibbertigibbeting",
|
|
||||||
"kerfuffling",
|
|
||||||
"dillydallying",
|
|
||||||
"twiddling thumbs",
|
|
||||||
"noodling",
|
|
||||||
"bamboozling",
|
|
||||||
"moseying",
|
|
||||||
"hobnobbing",
|
|
||||||
"pondering",
|
|
||||||
"conjuring",
|
|
||||||
];
|
|
||||||
|
|
||||||
export function pickWaitingPhrase(tick: number, phrases = defaultWaitingPhrases) {
|
|
||||||
const idx = Math.floor(tick / 10) % phrases.length;
|
|
||||||
return phrases[idx] ?? phrases[0] ?? "waiting";
|
|
||||||
}
|
|
||||||
|
|
||||||
export function shimmerText(theme: MinimalTheme, text: string, tick: number) {
|
|
||||||
const width = 6;
|
|
||||||
const hi = (ch: string) => theme.bold(theme.accentSoft(ch));
|
|
||||||
|
|
||||||
const pos = tick % (text.length + width);
|
|
||||||
const start = Math.max(0, pos - width);
|
|
||||||
const end = Math.min(text.length - 1, pos);
|
|
||||||
|
|
||||||
let out = "";
|
|
||||||
for (let i = 0; i < text.length; i++) {
|
|
||||||
const ch = text[i];
|
|
||||||
out += i >= start && i <= end ? hi(ch) : theme.dim(ch);
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildWaitingStatusMessage(params: {
|
|
||||||
theme: MinimalTheme;
|
|
||||||
tick: number;
|
|
||||||
elapsed: string;
|
|
||||||
connectionStatus: string;
|
|
||||||
phrases?: string[];
|
|
||||||
}) {
|
|
||||||
const phrase = pickWaitingPhrase(params.tick, params.phrases);
|
|
||||||
const cute = shimmerText(params.theme, `${phrase}…`, params.tick);
|
|
||||||
return `${cute} • ${params.elapsed} | ${params.connectionStatus}`;
|
|
||||||
}
|
|
||||||
+1
-56
@@ -22,10 +22,6 @@ import { editorTheme, theme } from "./theme/theme.js";
|
|||||||
import { createCommandHandlers } from "./tui-command-handlers.js";
|
import { createCommandHandlers } from "./tui-command-handlers.js";
|
||||||
import { createEventHandlers } from "./tui-event-handlers.js";
|
import { createEventHandlers } from "./tui-event-handlers.js";
|
||||||
import { formatTokens } from "./tui-formatters.js";
|
import { formatTokens } from "./tui-formatters.js";
|
||||||
import {
|
|
||||||
buildWaitingStatusMessage,
|
|
||||||
defaultWaitingPhrases,
|
|
||||||
} from "./tui-waiting.js";
|
|
||||||
import { createOverlayHandlers } from "./tui-overlays.js";
|
import { createOverlayHandlers } from "./tui-overlays.js";
|
||||||
import { createSessionActions } from "./tui-session-actions.js";
|
import { createSessionActions } from "./tui-session-actions.js";
|
||||||
import type {
|
import type {
|
||||||
@@ -290,28 +286,9 @@ export async function runTui(opts: TuiOptions) {
|
|||||||
statusContainer.addChild(statusLoader);
|
statusContainer.addChild(statusLoader);
|
||||||
};
|
};
|
||||||
|
|
||||||
let waitingTick = 0;
|
|
||||||
let waitingTimer: NodeJS.Timeout | null = null;
|
|
||||||
let waitingPhrase: string | null = null;
|
|
||||||
|
|
||||||
const updateBusyStatusMessage = () => {
|
const updateBusyStatusMessage = () => {
|
||||||
if (!statusLoader || !statusStartedAt) return;
|
if (!statusLoader || !statusStartedAt) return;
|
||||||
const elapsed = formatElapsed(statusStartedAt);
|
const elapsed = formatElapsed(statusStartedAt);
|
||||||
|
|
||||||
if (activityStatus === "waiting") {
|
|
||||||
waitingTick++;
|
|
||||||
statusLoader.setMessage(
|
|
||||||
buildWaitingStatusMessage({
|
|
||||||
theme,
|
|
||||||
tick: waitingTick,
|
|
||||||
elapsed,
|
|
||||||
connectionStatus,
|
|
||||||
phrases: waitingPhrase ? [waitingPhrase] : undefined,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
statusLoader.setMessage(`${activityStatus} • ${elapsed} | ${connectionStatus}`);
|
statusLoader.setMessage(`${activityStatus} • ${elapsed} | ${connectionStatus}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -329,31 +306,6 @@ export async function runTui(opts: TuiOptions) {
|
|||||||
statusTimer = null;
|
statusTimer = null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const startWaitingTimer = () => {
|
|
||||||
if (waitingTimer) return;
|
|
||||||
|
|
||||||
// Pick a phrase once per waiting session.
|
|
||||||
if (!waitingPhrase) {
|
|
||||||
const idx = Math.floor(Math.random() * defaultWaitingPhrases.length);
|
|
||||||
waitingPhrase =
|
|
||||||
defaultWaitingPhrases[idx] ?? defaultWaitingPhrases[0] ?? "waiting";
|
|
||||||
}
|
|
||||||
|
|
||||||
waitingTick = 0;
|
|
||||||
|
|
||||||
waitingTimer = setInterval(() => {
|
|
||||||
if (activityStatus !== "waiting") return;
|
|
||||||
updateBusyStatusMessage();
|
|
||||||
}, 120);
|
|
||||||
};
|
|
||||||
|
|
||||||
const stopWaitingTimer = () => {
|
|
||||||
if (!waitingTimer) return;
|
|
||||||
clearInterval(waitingTimer);
|
|
||||||
waitingTimer = null;
|
|
||||||
waitingPhrase = null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const renderStatus = () => {
|
const renderStatus = () => {
|
||||||
const isBusy = busyStates.has(activityStatus);
|
const isBusy = busyStates.has(activityStatus);
|
||||||
if (isBusy) {
|
if (isBusy) {
|
||||||
@@ -361,18 +313,11 @@ export async function runTui(opts: TuiOptions) {
|
|||||||
statusStartedAt = Date.now();
|
statusStartedAt = Date.now();
|
||||||
}
|
}
|
||||||
ensureStatusLoader();
|
ensureStatusLoader();
|
||||||
if (activityStatus === "waiting") {
|
|
||||||
stopStatusTimer();
|
|
||||||
startWaitingTimer();
|
|
||||||
} else {
|
|
||||||
stopWaitingTimer();
|
|
||||||
startStatusTimer();
|
|
||||||
}
|
|
||||||
updateBusyStatusMessage();
|
updateBusyStatusMessage();
|
||||||
|
startStatusTimer();
|
||||||
} else {
|
} else {
|
||||||
statusStartedAt = null;
|
statusStartedAt = null;
|
||||||
stopStatusTimer();
|
stopStatusTimer();
|
||||||
stopWaitingTimer();
|
|
||||||
statusLoader?.stop();
|
statusLoader?.stop();
|
||||||
statusLoader = null;
|
statusLoader = null;
|
||||||
ensureStatusText();
|
ensureStatusText();
|
||||||
|
|||||||
Reference in new issue
Block a user