Compare commits

..
Author SHA1 Message Date
Peter Steinberger 68ecee84d1 fix: stream tool summaries early and tool output 2026-01-03 20:37:57 +01:00
Peter Steinberger d1ebc4489a fix: document macOS permission requirements 2026-01-03 20:04:27 +01:00
Jake a71efbe7de Scripts: Make ad-hoc fallback opt-in with stronger TCC warnings 2026-01-03 20:04:27 +01:00
Jake a7b8c0d963 Scripts: Fallback to ad-hoc signing in codesign-mac-app.sh 2026-01-03 20:04:26 +01:00
Peter Steinberger 55a07a0ef0 style: fix lint formatting 2026-01-03 18:51:25 +00:00
Peter Steinberger 9899ba53a3 Docs: add PR number for Discord reactions 2026-01-03 18:48:36 +00:00
Peter Steinberger 52458a5628 Discord: default reaction notifications to own 2026-01-03 18:48:36 +00:00
Shadow 7abd6713c8 Docs: clarify discord reaction notifications 2026-01-03 18:48:36 +00:00
Shadow 451174ca10 Discord: add reaction notification allowlist 2026-01-03 18:48:36 +00:00
Peter Steinberger cdfbd6e7eb test(gateway): align config constants in auth test 2026-01-03 19:37:09 +01:00
Peter Steinberger 350e007a5c test(agents): extend text_end coverage 2026-01-03 19:37:09 +01:00
Peter Steinberger 5e156135a1 test(gateway): avoid hoisted export errors 2026-01-03 19:37:09 +01:00
Peter Steinberger b7ec9ae475 fix(gateway): format status/code errors 2026-01-03 19:37:09 +01:00
Peter Steinberger 8a18af409d test(gateway): cover helper registries 2026-01-03 19:37:09 +01:00
Peter Steinberger 6a125b554b refactor(gateway): split server helpers 2026-01-03 19:37:09 +01:00
Shadow ce92fac983 chore: formatting 2026-01-03 12:35:16 -06:00
Peter SteinbergerandMaxim Vovshin 341a224301 docs: credit Hyaxia in changelog and credits
Co-authored-by: Maxim Vovshin <36747317+Hyaxia@users.noreply.github.com>
2026-01-03 18:05:46 +00:00
Peter Steinberger 95cd153f33 feat: add blogwatcher skill 2026-01-03 18:00:08 +00:00
Peter Steinberger 0af89022ff fix: avoid Swift compiler crash in onboarding wizard 2026-01-03 17:59:37 +00:00
Peter Steinberger 27a8f3d061 chore: add inline guidance for block streaming 2026-01-03 18:46:59 +01:00
Peter Steinberger 72b34f7d03 fix: harden block stream dedupe 2026-01-03 18:44:07 +01:00
Peter Steinberger 73fa2e10bc refactor: split gateway server methods 2026-01-03 18:14:07 +01:00
Peter Steinberger 4a6b33d799 refactor: add gateway server helper modules 2026-01-03 18:00:45 +01:00
Peter Steinberger 145964c85e feat: add github skill 2026-01-03 17:57:13 +01:00
Peter Steinberger 217b84f2ac fix: drop final payloads after block streaming 2026-01-03 17:55:31 +01:00
Peter Steinberger 1d6de24ab3 feat: configurable control ui base path 2026-01-03 17:55:31 +01:00
Peter Steinberger 822def84d2 docs(faq): add Tailscale bind conflict + model/thinking compatibility
- Added Tailscale serve requires bind: loopback (not lan)
- Added model + thinking mode issues section (Gemini Flash, Opus, local LLMs)

From Discord #help session learnings 🦞
2026-01-03 16:53:56 +00:00
Peter Steinberger f313af75e9 fix: avoid duplicate block-stream payloads 2026-01-03 16:53:56 +00:00
Peter Steinberger 591773715e fix: honor whatsapp per-group mention overrides 2026-01-03 17:51:10 +01:00
Peter Steinberger dd6b9b510b docs: update changelog for gateway refactor 2026-01-03 17:35:29 +01:00
Peter Steinberger 6ae51ae3de refactor: split gateway server helpers and tests 2026-01-03 17:34:52 +01:00
Peter Steinberger 00c3e98431 docs: add tmux skill guidance 2026-01-03 17:31:26 +01:00
Peter Steinberger dd561f58d1 docs: expand coding-agent Pi usage 2026-01-03 17:21:17 +01:00
Peter Steinberger 200dd634fb fix: preserve block streaming order 2026-01-03 17:14:01 +01:00
Peter Steinberger 3bbdcaf87f fix: avoid duplicate block streaming 2026-01-03 17:10:47 +01:00
Peter Steinberger abff5e3b1f docs: thank @ratulsarna for control UI UUID fallback 2026-01-03 15:56:36 +00:00
Peter Steinberger 40ee0f0672 build: lock x86_64 relay to AVX2 2026-01-03 16:52:06 +01:00
Peter Steinberger 9f8eeceae7 feat: soften block streaming chunking 2026-01-03 16:48:26 +01:00
Peter Steinberger 53baba71fa feat: unify onboarding + config schema 2026-01-03 16:48:08 +01:00
123 changed files with 16525 additions and 11412 deletions

No files matched your search

+23 -1
View File
@@ -9,25 +9,46 @@
### Features
- Gateway: support `gateway.port` + `CLAWDIS_GATEWAY_PORT` across CLI, TUI, and macOS app.
- UI: centralize tool display metadata and show action/detail summaries across Web Chat, SwiftUI, Android, and the TUI.
- Control UI: support configurable base paths (`gateway.controlUi.basePath`, default unchanged) for hosting under URL prefixes.
- Onboarding: shared wizard engine powering CLI + macOS via gateway wizard RPC.
- Config: expose schema + UI hints for generic config forms (Web UI + future clients).
- Skills: add blogwatcher skill for RSS/Atom monitoring — thanks @Hyaxia.
- Discord: emit system events for reaction add/remove with per-guild reaction notifications (off|own|all|allowlist) (#140) — thanks @thewilloftheshadow.
### Fixes
- Auto-reply: drop final payloads when block streaming to avoid duplicate Discord sends.
- Telegram: chunk block-stream replies to avoid “message is too long” errors (#124) — thanks @mukhtharcm.
- Block streaming: default to text_end and suppress duplicate block sends while in-flight.
- Block streaming: avoid duplicate block chunks when providers repeat full content on text_end.
- Block streaming: drop final payloads after soft chunking to keep Discord order intact.
- Gmail hooks: resolve gcloud Python to a real executable when PATH uses mise shims — thanks @joargp.
- Control UI: generate UUIDs when `crypto.randomUUID()` is unavailable over HTTP — thanks @ratulsarna.
- Control UI: stream live tool output cards in Chat (agent events include sessionKey).
- Agent: add soft block-stream chunking (800–1200 chars default) with paragraph/newline preference.
- Agent tools: scope the Discord tool to Discord surface runs.
- Agent tools: format verbose tool summaries without brackets, with unique emojis and `tool: detail` style.
- Agent tools: emit verbose tool summaries at tool start (no debounce).
- Gateway: split server helpers/tests into hooks/session-utils/ws-log/net modules for better isolation; add unit coverage for hooks/session utils/ws log.
- Gateway: extract WS method handling + HTTP/provider/constant helpers to shrink server wiring and improve testability.
- Onboarding: fix Control UI basePath usage when showing/opening gateway URLs.
- macOS Connections: move to sidebar + detail layout with structured sections and header actions.
- macOS onboarding: increase window height so the permissions page fits without scrolling.
- Thinking: default to low for reasoning-capable models when no /think or config default is set.
- Logging: decouple file log levels from console verbosity; verbose-only details are captured when `logging.level` is debug/trace.
- Build: fix regex literal in tool-meta path detection (watch build error).
- Build: require AVX2 Bun for x86_64 relay packaging (reject baseline builds).
- Auto-reply: add run-level telemetry + typing TTL guardrails to diagnose stuck replies.
- Android: show unreachable gateway errors during pairing (#148) — thanks @cash-echo-bot.
- WhatsApp: honor per-group mention gating overrides when group ids are stored as session keys.
- Dependencies: bump pi-mono packages to 0.32.3.
### Docs
- Skills: add Sheets/Docs examples to gog skill (#128) — thanks @mbelinky.
- Skills: clarify bear-notes token + callback usage (#120) — thanks @tylerwince.
- Skills: document Discord `sendMessage` media attachments and `to` format clarification.
- Skills: add tmux skill + interactive coding guidance in coding-agent.
- Gateway: document port configuration + multi-instance isolation.
- Onboarding/Config: add protocol notes for wizard + schema RPC.
- Queue: clarify steer-backlog behavior with inline commands and update examples for streaming surfaces.
## 2.0.0-beta5 — 2026-01-03
@@ -89,6 +110,7 @@
- Skills: add tmux-first coding-agent skill + `requires.anyBins` gate for multi-CLI setup (thanks @sreekaransrinath).
### Fixes
- macOS codesign: make ad-hoc signing opt-in with loud warnings and document TCC permission fragility — thanks @mcinteerj.
- Gog calendar: format date ranges as RFC 3339 with timezone to satisfy Google Calendar API (thanks @jayhickey).
- macOS onboarding: add scrollable page gutter for overflowing content (#105) — thanks @thewilloftheshadow.
- Chat UI: keep the chat scrolled to the latest message after switching sessions.
+1 -1
View File
@@ -109,7 +109,7 @@ Send these in WhatsApp/Telegram/WebChat (group commands are owner-only):
- **Events + snapshot**: handshake returns a snapshot (presence/health) and declares event types; runtime events include `agent`, `chat`, `presence`, `tick`, `health`, `heartbeat`, `cron`, `node.pair.*`, `voicewake.changed`, `shutdown`.
- **Idempotency & safety**: `send`/`agent`/`chat.send` require idempotency keys with a TTL cache (5 min, cap 1000) to avoid double‑sends on reconnects; payload sizes are capped per connection.
- **Bridge for nodes**: optional TCP bridge (`src/infra/bridge/server.ts`) is newline‑delimited JSON frames (`hello`, pairing, RPC, `invoke`); node connect/disconnect is surfaced into presence.
- **Control UI + Canvas Host**: HTTP serves `/ui` assets (if built) and can host a live‑reload Canvas host for nodes (`src/canvas-host/server.ts`), injecting the A2UI postMessage bridge.
- **Control UI + Canvas Host**: HTTP serves Control UI assets (default `/`, optional base path) and can host a live‑reload Canvas host for nodes (`src/canvas-host/server.ts`), injecting the A2UI postMessage bridge.
### iOS app (apps/ios)
- **Discovery + pairing**: Bonjour discovery via `BridgeDiscoveryModel` (NWBrowser). `BridgeConnectionController` auto‑connects using Keychain token or allows manual host/port.
@@ -412,8 +412,7 @@ class NodeRuntime(context: Context) {
}
if (!resolved.ok || resolved.token.isNullOrBlank()) {
val errorMessage = resolved.error?.trim().orEmpty().ifEmpty { "pairing required" }
_statusText.value = "Failed: $errorMessage"
_statusText.value = "Failed: pairing required"
return@launch
}
@@ -37,21 +37,21 @@ class BridgePairingClient {
withContext(Dispatchers.IO) {
val socket = Socket()
socket.tcpNoDelay = true
socket.connect(InetSocketAddress(endpoint.host, endpoint.port), 8_000)
socket.soTimeout = 60_000
val reader = BufferedReader(InputStreamReader(socket.getInputStream(), Charsets.UTF_8))
val writer = BufferedWriter(OutputStreamWriter(socket.getOutputStream(), Charsets.UTF_8))
fun send(line: String) {
writer.write(line)
writer.write("\n")
writer.flush()
}
fun sendJson(obj: JsonObject) = send(obj.toString())
try {
socket.connect(InetSocketAddress(endpoint.host, endpoint.port), 8_000)
socket.soTimeout = 60_000
val reader = BufferedReader(InputStreamReader(socket.getInputStream(), Charsets.UTF_8))
val writer = BufferedWriter(OutputStreamWriter(socket.getOutputStream(), Charsets.UTF_8))
fun send(line: String) {
writer.write(line)
writer.write("\n")
writer.flush()
}
fun sendJson(obj: JsonObject) = send(obj.toString())
sendJson(
buildJsonObject {
put("type", JsonPrimitive("hello"))
@@ -111,9 +111,6 @@ class BridgePairingClient {
}
else -> PairResult(ok = false, token = null, error = "unexpected bridge response")
}
} catch (e: Exception) {
val message = e.message?.trim().orEmpty().ifEmpty { "gateway unreachable" }
PairResult(ok = false, token = null, error = message)
} finally {
try {
socket.close()
@@ -515,6 +515,17 @@ struct ConnectionsSettings: View {
.labelsHidden()
.toggleStyle(.checkbox)
}
GridRow {
self.gridLabel("Reaction notifications")
Picker("", selection: $guild.reactionNotifications) {
Text("Off").tag("off")
Text("Own").tag("own")
Text("All").tag("all")
Text("Allowlist").tag("allowlist")
}
.labelsHidden()
.pickerStyle(.segmented)
}
GridRow {
self.gridLabel("Users allowlist")
TextField("123456789, username#1234", text: $guild.users)
@@ -162,6 +162,7 @@ struct DiscordGuildForm: Identifiable {
var key: String
var slug: String
var requireMention: Bool
var reactionNotifications: String
var users: String
var channels: [DiscordGuildChannelForm]
@@ -169,12 +170,14 @@ struct DiscordGuildForm: Identifiable {
key: String = "",
slug: String = "",
requireMention: Bool = false,
reactionNotifications: String = "own",
users: String = "",
channels: [DiscordGuildChannelForm] = []
) {
self.key = key
self.slug = slug
self.requireMention = requireMention
self.reactionNotifications = reactionNotifications
self.users = users
self.channels = channels
}
@@ -491,6 +494,10 @@ final class ConnectionsStore {
let entry = value.dictionaryValue ?? [:]
let slug = entry["slug"]?.stringValue ?? ""
let requireMention = entry["requireMention"]?.boolValue ?? false
let reactionModeRaw = entry["reactionNotifications"]?.stringValue ?? ""
let reactionNotifications = ["off", "own", "all", "allowlist"].contains(reactionModeRaw)
? reactionModeRaw
: "own"
let users = entry["users"]?.arrayValue?
.compactMap { item -> String? in
if let str = item.stringValue { return str }
@@ -518,6 +525,7 @@ final class ConnectionsStore {
key: key,
slug: slug,
requireMention: requireMention,
reactionNotifications: reactionNotifications,
users: users,
channels: channels)
}
@@ -794,6 +802,9 @@ final class ConnectionsStore {
let slug = entry.slug.trimmingCharacters(in: .whitespacesAndNewlines)
if !slug.isEmpty { payload["slug"] = slug }
if entry.requireMention { payload["requireMention"] = true }
if ["off", "own", "all", "allowlist"].contains(entry.reactionNotifications) {
payload["reactionNotifications"] = entry.reactionNotifications
}
let users = entry.users
.split(separator: ",")
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
@@ -51,6 +51,10 @@ actor GatewayConnection {
case providersStatus = "providers.status"
case configGet = "config.get"
case configSet = "config.set"
case wizardStart = "wizard.start"
case wizardNext = "wizard.next"
case wizardCancel = "wizard.cancel"
case wizardStatus = "wizard.status"
case talkMode = "talk.mode"
case webLoginStart = "web.login.start"
case webLoginWait = "web.login.wait"
+8 -1
View File
@@ -86,6 +86,7 @@ struct OnboardingView: View {
@State var gatewayDiscovery: GatewayDiscoveryModel
@State var onboardingChatModel: ClawdisChatViewModel
@State var onboardingSkillsModel = SkillsSettingsModel()
@State var onboardingWizard = OnboardingWizardModel()
@State var didLoadOnboardingSkills = false
@State var localGatewayProbe: LocalGatewayProbe?
@Bindable var state: AppState
@@ -95,6 +96,7 @@ struct OnboardingView: View {
let contentHeight: CGFloat = 460
let connectionPageIndex = 1
let anthropicAuthPageIndex = 2
let wizardPageIndex = 3
let onboardingChatPageIndex = 8
static let clipboardPoll: AnyPublisher<Date, Never> = {
@@ -119,7 +121,7 @@ struct OnboardingView: View {
case .unconfigured:
needsBootstrap ? [0, 1, 8, 9] : [0, 1, 9]
case .local:
needsBootstrap ? [0, 1, 2, 5, 6, 8, 9] : [0, 1, 2, 5, 6, 9]
needsBootstrap ? [0, 1, 3, 5, 8, 9] : [0, 1, 3, 5, 9]
}
}
@@ -133,6 +135,11 @@ struct OnboardingView: View {
}
var buttonTitle: String { self.currentPage == self.pageCount - 1 ? "Finish" : "Next" }
var wizardPageOrderIndex: Int? { self.pageOrder.firstIndex(of: self.wizardPageIndex) }
var isWizardBlocking: Bool {
self.activePageIndex == self.wizardPageIndex && !self.onboardingWizard.isComplete
}
var canAdvance: Bool { !self.isWizardBlocking }
var devLinkCommand: String {
let bundlePath = Bundle.main.bundlePath
return "ln -sf '\(bundlePath)/Contents/Resources/Relay/clawdis' /usr/local/bin/clawdis"
@@ -11,6 +11,7 @@ extension OnboardingView {
}
func selectUnconfiguredGateway() {
Task { await self.onboardingWizard.cancelIfRunning() }
self.state.connectionMode = .unconfigured
self.preferredGatewayID = nil
self.showAdvancedConnection = false
@@ -18,6 +19,7 @@ extension OnboardingView {
}
func selectRemoteGateway(_ gateway: GatewayDiscoveryModel.DiscoveredGateway) {
Task { await self.onboardingWizard.cancelIfRunning() }
self.preferredGatewayID = gateway.stableID
BridgeDiscoveryPreferences.setPreferredStableID(gateway.stableID)
@@ -47,6 +49,7 @@ extension OnboardingView {
}
func handleNext() {
if self.isWizardBlocking { return }
if self.currentPage < self.pageCount - 1 {
withAnimation { self.currentPage += 1 }
} else {
@@ -46,6 +46,10 @@ extension OnboardingView {
self.currentPage = max(0, self.pageOrder.count - 1)
}
}
.onChange(of: self.onboardingWizard.isComplete) { _, newValue in
guard newValue, self.activePageIndex == self.wizardPageIndex else { return }
self.handleNext()
}
.onDisappear {
self.stopPermissionMonitoring()
self.stopDiscovery()
@@ -81,6 +85,7 @@ extension OnboardingView {
}
var navigationBar: some View {
let wizardLockIndex = self.wizardPageOrderIndex
HStack(spacing: 20) {
ZStack(alignment: .leading) {
Button(action: {}, label: {
@@ -107,6 +112,7 @@ extension OnboardingView {
HStack(spacing: 8) {
ForEach(0..<self.pageCount, id: \.self) { index in
let isLocked = wizardLockIndex != nil && !self.onboardingWizard.isComplete && index > (wizardLockIndex ?? 0)
Button {
withAnimation { self.currentPage = index }
} label: {
@@ -115,6 +121,8 @@ extension OnboardingView {
.frame(width: 8, height: 8)
}
.buttonStyle(.plain)
.disabled(isLocked)
.opacity(isLocked ? 0.3 : 1)
}
}
@@ -126,6 +134,7 @@ extension OnboardingView {
}
.keyboardShortcut(.return)
.buttonStyle(.borderedProminent)
.disabled(!self.canAdvance)
}
.padding(.horizontal, 28)
.padding(.bottom, 13)
@@ -13,6 +13,8 @@ extension OnboardingView {
self.connectionPage()
case 2:
self.anthropicAuthPage()
case 3:
self.wizardPage()
case 5:
self.permissionsPage()
case 6:
@@ -47,6 +47,7 @@ extension OnboardingView {
_ = view.welcomePage()
_ = view.connectionPage()
_ = view.anthropicAuthPage()
_ = view.wizardPage()
_ = view.permissionsPage()
_ = view.cliPage()
_ = view.workspacePage()
@@ -0,0 +1,93 @@
import Observation
import SwiftUI
extension OnboardingView {
func wizardPage() -> some View {
self.onboardingPage {
VStack(spacing: 16) {
Text("Setup Wizard")
.font(.largeTitle.weight(.semibold))
Text("Follow the guided setup from the Gateway. This keeps onboarding in sync with the CLI.")
.font(.body)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
.frame(maxWidth: 520)
self.onboardingCard(spacing: 14, padding: 16) {
OnboardingWizardCardContent(
wizard: self.onboardingWizard,
mode: self.state.connectionMode,
workspacePath: self.workspacePath)
}
}
.task {
await self.onboardingWizard.startIfNeeded(
mode: self.state.connectionMode,
workspace: self.workspacePath.isEmpty ? nil : self.workspacePath)
}
}
}
}
private struct OnboardingWizardCardContent: View {
@Bindable var wizard: OnboardingWizardModel
let mode: AppState.ConnectionMode
let workspacePath: String
private enum CardState {
case error(String)
case starting
case step(WizardStep)
case complete
case waiting
}
private var state: CardState {
if let error = wizard.errorMessage { return .error(error) }
if wizard.isStarting { return .starting }
if let step = wizard.currentStep { return .step(step) }
if wizard.isComplete { return .complete }
return .waiting
}
var body: some View {
switch state {
case .error(let error):
Text("Wizard error")
.font(.headline)
Text(error)
.font(.subheadline)
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
Button("Retry") {
wizard.reset()
Task {
await wizard.startIfNeeded(
mode: mode,
workspace: workspacePath.isEmpty ? nil : workspacePath)
}
}
.buttonStyle(.borderedProminent)
case .starting:
HStack(spacing: 8) {
ProgressView()
Text("Starting wizard…")
.foregroundStyle(.secondary)
}
case .step(let step):
OnboardingWizardStepView(
step: step,
isSubmitting: wizard.isSubmitting)
{ value in
Task { await wizard.submit(step: step, value: value) }
}
.id(step.id)
case .complete:
Text("Wizard complete. Continue to the next step.")
.font(.headline)
case .waiting:
Text("Waiting for wizard…")
.foregroundStyle(.secondary)
}
}
}
@@ -0,0 +1,402 @@
import ClawdisProtocol
import Foundation
import Observation
import OSLog
import SwiftUI
private let onboardingWizardLogger = Logger(subsystem: "com.clawdis", category: "onboarding.wizard")
@MainActor
@Observable
final class OnboardingWizardModel {
private(set) var sessionId: String?
private(set) var currentStep: WizardStep?
private(set) var status: String?
private(set) var errorMessage: String?
var isStarting = false
var isSubmitting = false
var isComplete: Bool { self.status == "done" }
var isRunning: Bool { self.status == "running" }
func reset() {
self.sessionId = nil
self.currentStep = nil
self.status = nil
self.errorMessage = nil
self.isStarting = false
self.isSubmitting = false
}
func startIfNeeded(mode: AppState.ConnectionMode, workspace: String? = nil) async {
guard self.sessionId == nil, !self.isStarting else { return }
guard mode == .local else { return }
self.isStarting = true
self.errorMessage = nil
defer { self.isStarting = false }
do {
var params: [String: AnyCodable] = ["mode": AnyCodable("local")]
if let workspace, !workspace.isEmpty {
params["workspace"] = AnyCodable(workspace)
}
let res: WizardStartResult = try await GatewayConnection.shared.requestDecoded(
method: .wizardStart,
params: params)
applyStartResult(res)
} catch {
self.status = "error"
self.errorMessage = error.localizedDescription
onboardingWizardLogger.error("start failed: \(error.localizedDescription, privacy: .public)")
}
}
func submit(step: WizardStep, value: AnyCodable?) async {
guard let sessionId, !self.isSubmitting else { return }
self.isSubmitting = true
self.errorMessage = nil
defer { self.isSubmitting = false }
do {
var params: [String: AnyCodable] = ["sessionId": AnyCodable(sessionId)]
var answer: [String: AnyCodable] = ["stepId": AnyCodable(step.id)]
if let value {
answer["value"] = value
}
params["answer"] = AnyCodable(answer)
let res: WizardNextResult = try await GatewayConnection.shared.requestDecoded(
method: .wizardNext,
params: params)
applyNextResult(res)
} catch {
self.status = "error"
self.errorMessage = error.localizedDescription
onboardingWizardLogger.error("submit failed: \(error.localizedDescription, privacy: .public)")
}
}
func cancelIfRunning() async {
guard let sessionId, self.isRunning else { return }
do {
let res: WizardStatusResult = try await GatewayConnection.shared.requestDecoded(
method: .wizardCancel,
params: ["sessionId": AnyCodable(sessionId)])
applyStatusResult(res)
} catch {
self.status = "error"
self.errorMessage = error.localizedDescription
onboardingWizardLogger.error("cancel failed: \(error.localizedDescription, privacy: .public)")
}
}
private func applyStartResult(_ res: WizardStartResult) {
self.sessionId = res.sessionid
self.status = anyCodableStringValue(res.status) ?? (res.done ? "done" : "running")
self.errorMessage = res.error
self.currentStep = decodeWizardStep(res.step)
if res.done { self.currentStep = nil }
}
private func applyNextResult(_ res: WizardNextResult) {
self.status = anyCodableStringValue(res.status) ?? self.status
self.errorMessage = res.error
self.currentStep = decodeWizardStep(res.step)
if res.done { self.currentStep = nil }
if res.done || anyCodableStringValue(res.status) == "done" || anyCodableStringValue(res.status) == "cancelled"
|| anyCodableStringValue(res.status) == "error" {
self.sessionId = nil
}
}
private func applyStatusResult(_ res: WizardStatusResult) {
self.status = anyCodableStringValue(res.status) ?? "unknown"
self.errorMessage = res.error
self.currentStep = nil
self.sessionId = nil
}
}
struct OnboardingWizardStepView: View {
let step: WizardStep
let isSubmitting: Bool
let onSubmit: (AnyCodable?) -> Void
@State private var textValue: String
@State private var confirmValue: Bool
@State private var selectedIndex: Int
@State private var selectedIndices: Set<Int>
private let optionItems: [WizardOptionItem]
init(step: WizardStep, isSubmitting: Bool, onSubmit: @escaping (AnyCodable?) -> Void) {
self.step = step
self.isSubmitting = isSubmitting
self.onSubmit = onSubmit
let options = parseWizardOptions(step.options).enumerated().map { index, option in
WizardOptionItem(index: index, option: option)
}
self.optionItems = options
let initialText = anyCodableString(step.initialvalue)
let initialConfirm = anyCodableBool(step.initialvalue)
let initialIndex = options.firstIndex(where: { anyCodableEqual($0.option.value, step.initialvalue) }) ?? 0
let initialMulti = Set(
options.filter { option in
anyCodableArray(step.initialvalue).contains { anyCodableEqual($0, option.option.value) }
}.map { $0.index }
)
_textValue = State(initialValue: initialText)
_confirmValue = State(initialValue: initialConfirm)
_selectedIndex = State(initialValue: initialIndex)
_selectedIndices = State(initialValue: initialMulti)
}
var body: some View {
VStack(alignment: .leading, spacing: 12) {
if let title = step.title, !title.isEmpty {
Text(title)
.font(.title2.weight(.semibold))
}
if let message = step.message, !message.isEmpty {
Text(message)
.font(.body)
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
}
switch wizardStepType(step) {
case "note":
EmptyView()
case "text":
textField
case "confirm":
Toggle("", isOn: $confirmValue)
.toggleStyle(.switch)
case "select":
selectOptions
case "multiselect":
multiselectOptions
case "progress":
ProgressView()
.controlSize(.small)
case "action":
EmptyView()
default:
Text("Unsupported step type")
.foregroundStyle(.secondary)
}
Button(action: submit) {
Text(wizardStepType(step) == "action" ? "Run" : "Continue")
.frame(minWidth: 120)
}
.buttonStyle(.borderedProminent)
.disabled(isSubmitting || isBlocked)
}
.frame(maxWidth: .infinity, alignment: .leading)
}
@ViewBuilder
private var textField: some View {
let isSensitive = step.sensitive == true
if isSensitive {
SecureField(step.placeholder ?? "", text: $textValue)
.textFieldStyle(.roundedBorder)
.frame(maxWidth: 360)
} else {
TextField(step.placeholder ?? "", text: $textValue)
.textFieldStyle(.roundedBorder)
.frame(maxWidth: 360)
}
}
private var selectOptions: some View {
VStack(alignment: .leading, spacing: 8) {
ForEach(optionItems) { item in
Button {
selectedIndex = item.index
} label: {
HStack(alignment: .top, spacing: 8) {
Image(systemName: selectedIndex == item.index ? "largecircle.fill.circle" : "circle")
.foregroundStyle(.accent)
VStack(alignment: .leading, spacing: 2) {
Text(item.option.label)
.foregroundStyle(.primary)
if let hint = item.option.hint, !hint.isEmpty {
Text(hint)
.font(.caption)
.foregroundStyle(.secondary)
}
}
}
}
.buttonStyle(.plain)
}
}
}
private var multiselectOptions: some View {
VStack(alignment: .leading, spacing: 8) {
ForEach(optionItems) { item in
Toggle(isOn: bindingForOption(item)) {
VStack(alignment: .leading, spacing: 2) {
Text(item.option.label)
if let hint = item.option.hint, !hint.isEmpty {
Text(hint)
.font(.caption)
.foregroundStyle(.secondary)
}
}
}
}
}
}
private func bindingForOption(_ item: WizardOptionItem) -> Binding<Bool> {
Binding(get: {
selectedIndices.contains(item.index)
}, set: { newValue in
if newValue {
selectedIndices.insert(item.index)
} else {
selectedIndices.remove(item.index)
}
})
}
private var isBlocked: Bool {
let type = wizardStepType(step)
if type == "select" { return optionItems.isEmpty }
if type == "multiselect" { return optionItems.isEmpty }
return false
}
private func submit() {
switch wizardStepType(step) {
case "note", "progress":
onSubmit(nil)
case "text":
onSubmit(AnyCodable(textValue))
case "confirm":
onSubmit(AnyCodable(confirmValue))
case "select":
guard optionItems.indices.contains(selectedIndex) else {
onSubmit(nil)
return
}
let option = optionItems[selectedIndex].option
onSubmit(option.value ?? AnyCodable(option.label))
case "multiselect":
let values = optionItems
.filter { selectedIndices.contains($0.index) }
.map { $0.option.value ?? AnyCodable($0.option.label) }
onSubmit(AnyCodable(values))
case "action":
onSubmit(AnyCodable(true))
default:
onSubmit(nil)
}
}
}
private struct WizardOptionItem: Identifiable {
let index: Int
let option: WizardOption
var id: Int { index }
}
private struct WizardOption {
let value: AnyCodable?
let label: String
let hint: String?
}
private func decodeWizardStep(_ raw: [String: AnyCodable]?) -> WizardStep? {
guard let raw else { return nil }
do {
let data = try JSONEncoder().encode(raw)
return try JSONDecoder().decode(WizardStep.self, from: data)
} catch {
onboardingWizardLogger.error("wizard step decode failed: \(error.localizedDescription, privacy: .public)")
return nil
}
}
private func parseWizardOptions(_ raw: [[String: AnyCodable]]?) -> [WizardOption] {
guard let raw else { return [] }
return raw.map { entry in
let value = entry["value"]
let label = (entry["label"]?.value as? String) ?? ""
let hint = entry["hint"]?.value as? String
return WizardOption(value: value, label: label, hint: hint)
}
}
private func wizardStepType(_ step: WizardStep) -> String {
(step.type.value as? String) ?? ""
}
private func anyCodableString(_ value: AnyCodable?) -> String {
switch value?.value {
case let string as String:
return string
case let int as Int:
return String(int)
case let double as Double:
return String(double)
case let bool as Bool:
return bool ? "true" : "false"
default:
return ""
}
}
private func anyCodableStringValue(_ value: AnyCodable?) -> String? {
value?.value as? String
}
private func anyCodableBool(_ value: AnyCodable?) -> Bool {
switch value?.value {
case let bool as Bool:
return bool
case let string as String:
return string.lowercased() == "true"
default:
return false
}
}
private func anyCodableArray(_ value: AnyCodable?) -> [AnyCodable] {
switch value?.value {
case let arr as [AnyCodable]:
return arr
case let arr as [Any]:
return arr.map { AnyCodable($0) }
default:
return []
}
}
private func anyCodableEqual(_ lhs: AnyCodable?, _ rhs: AnyCodable?) -> Bool {
switch (lhs?.value, rhs?.value) {
case let (l as String, r as String):
return l == r
case let (l as Int, r as Int):
return l == r
case let (l as Double, r as Double):
return l == r
case let (l as Bool, r as Bool):
return l == r
case let (l as String, r as Int):
return l == String(r)
case let (l as Int, r as String):
return String(l) == r
case let (l as String, r as Double):
return l == String(r)
case let (l as Double, r as String):
return String(l) == r
default:
return false
}
}
@@ -701,6 +701,210 @@ public struct ConfigSetParams: Codable {
}
}
public struct ConfigSchemaParams: Codable {
}
public struct ConfigSchemaResponse: Codable {
public let schema: AnyCodable
public let uihints: [String: AnyCodable]
public let version: String
public let generatedat: String
public init(
schema: AnyCodable,
uihints: [String: AnyCodable],
version: String,
generatedat: String
) {
self.schema = schema
self.uihints = uihints
self.version = version
self.generatedat = generatedat
}
private enum CodingKeys: String, CodingKey {
case schema
case uihints = "uiHints"
case version
case generatedat = "generatedAt"
}
}
public struct WizardStartParams: Codable {
public let mode: AnyCodable?
public let workspace: String?
public init(
mode: AnyCodable?,
workspace: String?
) {
self.mode = mode
self.workspace = workspace
}
private enum CodingKeys: String, CodingKey {
case mode
case workspace
}
}
public struct WizardNextParams: Codable {
public let sessionid: String
public let answer: [String: AnyCodable]?
public init(
sessionid: String,
answer: [String: AnyCodable]?
) {
self.sessionid = sessionid
self.answer = answer
}
private enum CodingKeys: String, CodingKey {
case sessionid = "sessionId"
case answer
}
}
public struct WizardCancelParams: Codable {
public let sessionid: String
public init(
sessionid: String
) {
self.sessionid = sessionid
}
private enum CodingKeys: String, CodingKey {
case sessionid = "sessionId"
}
}
public struct WizardStatusParams: Codable {
public let sessionid: String
public init(
sessionid: String
) {
self.sessionid = sessionid
}
private enum CodingKeys: String, CodingKey {
case sessionid = "sessionId"
}
}
public struct WizardStep: Codable {
public let id: String
public let type: AnyCodable
public let title: String?
public let message: String?
public let options: [[String: AnyCodable]]?
public let initialvalue: AnyCodable?
public let placeholder: String?
public let sensitive: Bool?
public let executor: AnyCodable?
public init(
id: String,
type: AnyCodable,
title: String?,
message: String?,
options: [[String: AnyCodable]]?,
initialvalue: AnyCodable?,
placeholder: String?,
sensitive: Bool?,
executor: AnyCodable?
) {
self.id = id
self.type = type
self.title = title
self.message = message
self.options = options
self.initialvalue = initialvalue
self.placeholder = placeholder
self.sensitive = sensitive
self.executor = executor
}
private enum CodingKeys: String, CodingKey {
case id
case type
case title
case message
case options
case initialvalue = "initialValue"
case placeholder
case sensitive
case executor
}
}
public struct WizardNextResult: Codable {
public let done: Bool
public let step: [String: AnyCodable]?
public let status: AnyCodable?
public let error: String?
public init(
done: Bool,
step: [String: AnyCodable]?,
status: AnyCodable?,
error: String?
) {
self.done = done
self.step = step
self.status = status
self.error = error
}
private enum CodingKeys: String, CodingKey {
case done
case step
case status
case error
}
}
public struct WizardStartResult: Codable {
public let sessionid: String
public let done: Bool
public let step: [String: AnyCodable]?
public let status: AnyCodable?
public let error: String?
public init(
sessionid: String,
done: Bool,
step: [String: AnyCodable]?,
status: AnyCodable?,
error: String?
) {
self.sessionid = sessionid
self.done = done
self.step = step
self.status = status
self.error = error
}
private enum CodingKeys: String, CodingKey {
case sessionid = "sessionId"
case done
case step
case status
case error
}
}
public struct WizardStatusResult: Codable {
public let status: AnyCodable
public let error: String?
public init(
status: AnyCodable,
error: String?
) {
self.status = status
self.error = error
}
private enum CodingKeys: String, CodingKey {
case status
case error
}
}
public struct TalkModeParams: Codable {
public let enabled: Bool
public let phase: String?
@@ -17,7 +17,7 @@ struct OnboardingViewSmokeTests {
@Test func pageOrderOmitsWorkspaceAndIdentitySteps() {
let order = OnboardingView.pageOrder(for: .local, needsBootstrap: false)
#expect(!order.contains(7))
#expect(!order.contains(3))
#expect(order.contains(3))
}
@Test func pageOrderOmitsOnboardingChatWhenIdentityKnown() {
@@ -0,0 +1,42 @@
import SwiftUI
import Testing
import ClawdisProtocol
@testable import Clawdis
@Suite(.serialized)
@MainActor
struct OnboardingWizardStepViewTests {
@Test func noteStepBuilds() {
let step = WizardStep(
id: "step-1",
type: AnyCodable("note"),
title: "Welcome",
message: "Hello",
options: nil,
initialvalue: nil,
placeholder: nil,
sensitive: nil,
executor: nil)
let view = OnboardingWizardStepView(step: step, isSubmitting: false, onSubmit: { _ in })
_ = view.body
}
@Test func selectStepBuilds() {
let options: [[String: AnyCodable]] = [
["value": AnyCodable("local"), "label": AnyCodable("Local"), "hint": AnyCodable("This Mac")],
["value": AnyCodable("remote"), "label": AnyCodable("Remote")],
]
let step = WizardStep(
id: "step-2",
type: AnyCodable("select"),
title: "Mode",
message: "Choose a mode",
options: options,
initialvalue: AnyCodable("local"),
placeholder: nil,
sensitive: nil,
executor: nil)
let view = OnboardingWizardStepView(step: step, isSubmitting: false, onSubmit: { _ in })
_ = view.body
}
}
+9 -1
View File
@@ -14,6 +14,10 @@ You must set an agent home directory via `agent.workspace`. CLAWDIS uses this as
Recommended: use `clawdis setup` to create `~/.clawdis/clawdis.json` if missing and initialize the workspace files.
If `agent.sandbox` is enabled, non-main sessions can override this with
per-session workspaces under `agent.sandbox.workspaceRoot` (see
`docs/configuration.md`).
## Bootstrap files (injected)
Inside `agent.workspace`, CLAWDIS expects these user-editable files:
@@ -82,7 +86,11 @@ current turn ends, then a new agent turn starts with the queued payloads. See
Block streaming sends completed assistant blocks as soon as they finish; disable
via `agent.blockStreamingDefault: "off"` if you only want the final response.
Tune the boundary via `agent.blockStreamingBreak` (`text_end` vs `message_end`).
Tune the boundary via `agent.blockStreamingBreak` (`text_end` vs `message_end`; defaults to text_end).
Control soft block chunking with `agent.blockStreamingChunk` (defaults to
800–1200 chars; prefers paragraph breaks, then newlines; sentences last).
Verbose tool summaries are emitted at tool start (no debounce); Control UI
streams tool output via agent events when available.
## Configuration (minimal)
+35 -2
View File
@@ -16,6 +16,14 @@ If the file is missing, CLAWDIS uses safe-ish defaults (embedded Pi agent + per-
- tune the embedded agent (`agent`) and session behavior (`session`)
- set the agent's identity (`identity`)
## Schema + UI hints
The Gateway exposes a JSON Schema representation of the config via `config.schema` for UI editors.
The Control UI renders a form from this schema, with a **Raw JSON** editor as an escape hatch.
Hints (labels, grouping, sensitive fields) ship alongside the schema so clients can render
better forms without hard-coding config knowledge.
## Minimal config (recommended starting point)
```json5
@@ -163,7 +171,7 @@ Controls how inbound messages behave when an agent run is already active.
bySurface: {
whatsapp: "collect",
telegram: "collect",
discord: "steer-backlog",
discord: "collect",
imessage: "collect",
webchat: "collect"
}
@@ -258,6 +266,7 @@ Configure the Discord bot by setting the bot token and optional gating:
"123456789012345678": { // guild id (preferred) or slug
slug: "friends-of-clawd",
requireMention: false, // per-guild default
reactionNotifications: "own", // off | own | all | allowlist
users: ["987654321098765432"], // optional per-guild user allowlist
channels: {
general: { allow: true },
@@ -272,6 +281,11 @@ Configure the Discord bot by setting the bot token and optional gating:
Clawdis starts Discord only when a `discord` config section exists. The token is resolved from `DISCORD_BOT_TOKEN` or `discord.token` (unless `discord.enabled` is `false`). Use `user:<id>` (DM) or `channel:<id>` (guild channel) when specifying delivery targets for cron/CLI commands.
Guild slugs are lowercase with spaces replaced by `-`; channel keys use the slugged channel name (no leading `#`). Prefer guild ids as keys to avoid rename ambiguity.
Reaction notification modes:
- `off`: no reaction events.
- `own`: reactions on the bot's own messages (default).
- `all`: all reactions on all messages.
- `allowlist`: reactions from `guilds.<id>.users` on all messages (empty list disables).
### `imessage` (imsg CLI)
@@ -383,6 +397,20 @@ Controls the embedded agent runtime (model/thinking/verbose/timeouts).
}
```
Block streaming:
- `agent.blockStreamingDefault`: `"on"`/`"off"` (default on).
- `agent.blockStreamingBreak`: `"text_end"` or `"message_end"` (default: text_end).
- `agent.blockStreamingChunk`: soft chunking for streamed blocks. Defaults to
800–1200 chars, prefers paragraph breaks (`\n\n`), then newlines, then sentences.
Example:
```json5
{
agent: {
blockStreamingChunk: { minChars: 800, maxChars: 1200 }
}
}
```
`agent.model` should be set as `provider/model` (e.g. `anthropic/claude-opus-4-5`).
If `modelAliases` is configured, you may also use the alias key (e.g. `Opus`).
If you omit the provider, CLAWDIS currently assumes `anthropic` as a temporary
@@ -623,13 +651,18 @@ Defaults:
mode: "local", // or "remote"
port: 18789, // WS + HTTP multiplex
bind: "loopback",
// controlUi: { enabled: true }
// controlUi: { enabled: true, basePath: "/clawdis" }
// auth: { mode: "token", token: "your-token" } // token is for multi-machine CLI access
// tailscale: { mode: "off" | "serve" | "funnel" }
}
}
```
Control UI base path:
- `gateway.controlUi.basePath` sets the URL prefix where the Control UI is served.
- Examples: `"/ui"`, `"/clawdis"`, `"/apps/clawdis"`.
- Default: root (`/`) (unchanged).
Notes:
- `clawdis gateway` refuses to start unless `gateway.mode` is set to `local` (or you pass the override flag).
- `gateway.port` controls the single multiplexed port used for WebSocket + HTTP (control UI, hooks, A2UI).
+13 -4
View File
@@ -6,9 +6,10 @@ read_when:
---
# Control UI (browser)
The Control UI is a small **Vite + Lit** single-page app served by the Gateway under:
The Control UI is a small **Vite + Lit** single-page app served by the Gateway:
- `http://<host>:18789/`
- default: `http://<host>:18789/`
- optional prefix: set `gateway.controlUi.basePath` (e.g. `/clawdis`)
It speaks **directly to the Gateway WebSocket** on the same port.
@@ -19,6 +20,7 @@ The dashboard settings panel lets you store a token; passwords are not persisted
## What it can do (today)
- Chat with the model via Gateway WS (`chat.history`, `chat.send`, `chat.abort`)
- Stream tool calls + live tool output cards in Chat (agent events)
- Connections: WhatsApp/Telegram status + QR login + Telegram config (`providers.status`, `web.login.*`, `config.set`)
- Instances: presence list + refresh (`system-presence`)
- Sessions: list + per-session thinking/verbose overrides (`sessions.list`, `sessions.patch`)
@@ -26,6 +28,7 @@ The dashboard settings panel lets you store a token; passwords are not persisted
- Skills: status, enable/disable, install, API key updates (`skills.*`)
- Nodes: list + caps (`node.list`)
- Config: view/edit `~/.clawdis/clawdis.json` (`config.get`, `config.set`)
- Config schema + form rendering (`config.schema`); Raw JSON editor remains available
- Debug: status/health/models snapshots + event log + manual RPC calls (`status`, `health`, `models.list`)
## Tailnet access (recommended)
@@ -39,7 +42,7 @@ clawdis gateway --tailscale serve
```
Open:
- `https://<magicdns>/ui/`
- `https://<magicdns>/` (or your configured `gateway.controlUi.basePath`)
By default, the gateway trusts Tailscale identity headers in serve mode. You can still set
`CLAWDIS_GATEWAY_TOKEN` or `gateway.auth` if you want a shared secret instead.
@@ -51,7 +54,7 @@ clawdis gateway --bind tailnet --token "$(openssl rand -hex 32)"
```
Then open:
- `http://<tailscale-ip>:18789/ui/`
- `http://<tailscale-ip>:18789/` (or your configured `gateway.controlUi.basePath`)
Paste the token into the UI settings (sent as `connect.params.auth.token`).
@@ -64,6 +67,12 @@ pnpm ui:install
pnpm ui:build
```
Optional absolute base (when you want fixed asset URLs):
```bash
CLAWDIS_CONTROL_UI_BASE_PATH=/clawdis/ pnpm ui:build
```
For local development (separate dev server):
```bash
+2 -1
View File
@@ -5,7 +5,8 @@ read_when:
---
# Dashboard (Control UI)
The Gateway dashboard is the browser Control UI served at `/ui/`.
The Gateway dashboard is the browser Control UI served at `/` by default
(override with `gateway.controlUi.basePath`).
Key references:
- `docs/control-ui.md` for usage and UI capabilities.
+8
View File
@@ -86,6 +86,7 @@ Note: Guild context `[from:]` lines include `author.tag` + `id` to make ping-rea
"123456789012345678": {
slug: "friends-of-clawd",
requireMention: false,
reactionNotifications: "own",
users: ["987654321098765432", "steipete"],
channels: {
general: { allow: true },
@@ -107,6 +108,7 @@ Note: Guild context `[from:]` lines include `author.tag` + `id` to make ping-rea
- `guilds.<id>.users`: optional per-guild user allowlist (ids or names).
- `guilds.<id>.channels`: channel rules (keys are channel slugs or ids).
- `guilds.<id>.requireMention`: per-guild mention requirement (overridable per channel).
- `guilds.<id>.reactionNotifications`: reaction system event mode (`off`, `own`, `all`, `allowlist`).
- `slashCommand`: optional config for user-installed slash commands (ephemeral responses).
- `mediaMaxMb`: clamp inbound media saved to disk.
- `historyLimit`: number of recent guild messages to include as context when replying to a mention (default 20, `0` disables).
@@ -117,6 +119,12 @@ Note: Guild context `[from:]` lines include `author.tag` + `id` to make ping-rea
- `roles` (role add/remove, default `false`)
- `moderation` (timeout/kick/ban, default `false`)
Reaction notifications use `guilds.<id>.reactionNotifications`:
- `off`: no reaction events.
- `own`: reactions on the bot's own messages (default).
- `all`: all reactions on all messages.
- `allowlist`: reactions from `guilds.<id>.users` on all messages (empty list disables).
### Tool action defaults
| Action group | Default | Notes |
+11
View File
@@ -433,6 +433,7 @@ Common issues:
- Port already in use (change with `--port`)
- Missing API keys in config
- Invalid config syntax (remember it's JSON5, but still check for errors)
- **Tailscale serve + bind conflict:** If using `tailscale.mode: "serve"`, you must set `gateway.bind: "loopback"` (not `"lan"`). Tailscale serve proxies traffic itself.
**Debug mode** — use watch for live reload:
```bash
@@ -529,6 +530,16 @@ Use `/model` to switch without restarting:
**Tip:** `/model` is processed at the gateway level — it works even if you're rate-limited (429) on the current model!
### Model + thinking mode issues?
Some models don't support extended thinking well:
- **Gemini Flash + thinking:** Can cause "Corrupted thought signature" errors. Fix: `/think off`
- **Claude Opus + thinking off:** Opus may "think out loud" anyway. Better to use `/think low` than `off`.
- **Local LLMs:** Most don't support the thinking/reasoning separation. Set `reasoning: false` in your model config.
If you get weird errors after switching models, try `/think off` and `/new` to reset.
### How do I stop/cancel a running task?
Send `/stop` to immediately abort the current agent run. Other stop words also work:
+4
View File
@@ -169,6 +169,10 @@ Example:
- **Mario Zechner** ([@badlogicc](https://twitter.com/badlogicgames)) — Pi creator, security pen-tester
- **Clawd** — The space lobster who demanded a better name
## Core Contributors
- **Maxim Vovshin** (@Hyaxia, 36747317+Hyaxia@users.noreply.github.com) — Blogwatcher skill
## License
MIT — Free as a lobster in the ocean 🦞
+40
View File
@@ -0,0 +1,40 @@
---
summary: "macOS permission persistence (TCC) and signing requirements"
read_when:
- Debugging missing or stuck macOS permission prompts
- Packaging or signing the macOS app
- Changing bundle IDs or app install paths
---
# macOS permissions (TCC)
macOS permission grants are fragile. TCC associates a permission grant with the
app's code signature, bundle identifier, and on-disk path. If any of those change,
macOS treats the app as new and may drop or hide prompts.
## Requirements for stable permissions
- Same path: run the app from a fixed location (for Clawdis, `dist/Clawdis.app`).
- Same bundle identifier: changing the bundle ID creates a new permission identity.
- Signed app: unsigned or ad-hoc signed builds do not persist permissions.
- Consistent signature: use a real Apple Development or Developer ID certificate
so the signature stays stable across rebuilds.
Ad-hoc signatures generate a new identity every build. macOS will forget previous
grants, and prompts can disappear entirely until the stale entries are cleared.
## Recovery checklist when prompts disappear
1. Quit the app.
2. Remove the app entry in System Settings -> Privacy & Security.
3. Relaunch the app from the same path and re-grant permissions.
4. If the prompt still does not appear, reset TCC entries with `tccutil` and try again.
5. Some permissions only reappear after a full macOS restart.
Example resets (replace bundle ID as needed):
```bash
sudo tccutil reset Accessibility com.clawdis.mac
sudo tccutil reset ScreenCapture com.clawdis.mac
sudo tccutil reset AppleEvents
```
If you are testing permissions, always sign with a real certificate. Ad-hoc
builds are only acceptable for quick local runs where permissions do not matter.
+6 -4
View File
@@ -9,22 +9,24 @@ This app is usually built from `scripts/package-mac-app.sh`, which now:
- sets a stable debug bundle identifier: `com.clawdis.mac.debug`
- writes the Info.plist with that bundle id (override via `BUNDLE_ID=...`)
- calls `scripts/codesign-mac-app.sh` to sign the main binary, bundled CLI, and app bundle so macOS treats each rebuild as the same signed bundle and keeps TCC permissions (notifications, accessibility, screen recording, mic, speech). Requires a valid signing identity.
- calls `scripts/codesign-mac-app.sh` to sign the main binary, bundled CLI, and app bundle so macOS treats each rebuild as the same signed bundle and keeps TCC permissions (notifications, accessibility, screen recording, mic, speech). For stable permissions, use a real signing identity; ad-hoc is opt-in and fragile (see `docs/mac/permissions.md`).
- uses `CODESIGN_TIMESTAMP=auto` by default; it enables trusted timestamps for Developer ID signatures. Set `CODESIGN_TIMESTAMP=off` to skip timestamping (offline debug builds).
- inject build metadata into Info.plist: `ClawdisBuildTimestamp` (UTC) and `ClawdisGitCommit` (short hash) so the About pane can show build, git, and debug/release channel.
- **Packaging requires Bun**: The embedded gateway relay is compiled using `bun`. Ensure it is installed (`curl -fsSL https://bun.sh/install | bash`).
- reads `SIGN_IDENTITY` from the environment. Add `export SIGN_IDENTITY="Apple Development: Your Name (TEAMID)"` (or your Developer ID Application cert) to your shell rc to always sign with your cert; otherwise signing falls back to ad‑hoc.
- reads `SIGN_IDENTITY` from the environment. Add `export SIGN_IDENTITY="Apple Development: Your Name (TEAMID)"` (or your Developer ID Application cert) to your shell rc to always sign with your cert. Ad-hoc signing requires explicit opt-in via `ALLOW_ADHOC_SIGNING=1` or `SIGN_IDENTITY="-"` (not recommended for permission testing).
## Usage
```bash
# from repo root
scripts/package-mac-app.sh # ad-hoc signing
scripts/package-mac-app.sh # auto-selects identity; errors if none found
SIGN_IDENTITY="Developer ID Application: Your Name" scripts/package-mac-app.sh # real cert
ALLOW_ADHOC_SIGNING=1 scripts/package-mac-app.sh # ad-hoc (permissions will not stick)
SIGN_IDENTITY="-" scripts/package-mac-app.sh # explicit ad-hoc (same caveat)
```
### Ad-hoc Signing Note
When signing with `SIGN_IDENTITY="-"` (ad-hoc), the script automatically disables the **Hardened Runtime** (`--options runtime`). This is necessary to prevent crashes when the app attempts to load embedded frameworks (like Sparkle) that do not share the same Team ID.
When signing with `SIGN_IDENTITY="-"` (ad-hoc), the script automatically disables the **Hardened Runtime** (`--options runtime`). This is necessary to prevent crashes when the app attempts to load embedded frameworks (like Sparkle) that do not share the same Team ID. Ad-hoc signatures also break TCC permission persistence; see `docs/mac/permissions.md` for recovery steps.
## Build metadata for About
+29
View File
@@ -0,0 +1,29 @@
# Onboarding + Config Protocol
Purpose: shared onboarding + config surfaces across CLI, macOS app, and Web UI.
## Components
- Wizard engine: `src/wizard` (session + prompts + onboarding state).
- CLI: `src/commands/onboard-*.ts` uses the wizard with the CLI prompter.
- Gateway RPC: wizard + config schema endpoints serve UI clients.
- macOS: SwiftUI onboarding uses the wizard step model.
- Web UI: config form renders from JSON Schema + hints.
## Gateway RPC
- `wizard.start` params: `{ mode?: "local"|"remote", workspace?: string }`
- `wizard.next` params: `{ sessionId, answer?: { stepId, value? } }`
- `wizard.cancel` params: `{ sessionId }`
- `wizard.status` params: `{ sessionId }`
- `config.schema` params: `{}`
Responses (shape)
- Wizard: `{ sessionId, done, step?, status?, error? }`
- Config schema: `{ schema, uiHints, version, generatedAt }`
## UI Hints
- `uiHints` keyed by path; optional metadata (label/help/group/order/advanced/sensitive/placeholder).
- Sensitive fields render as password inputs; no redaction layer.
- Unsupported schema nodes fall back to the raw JSON editor.
## Notes
- This doc is the single place to track protocol refactors for onboarding/config.
+6 -1
View File
@@ -27,6 +27,11 @@ Inbound messages can steer the current run, wait for a followup turn, or do both
- `interrupt` (legacy): abort the active run for that session, then run the newest message.
- `queue` (legacy alias): same as `steer`.
Steer-backlog means you can get a followup response after the steered run, so
streaming surfaces can look like duplicates. Prefer `collect`/`steer` if you want
one response per inbound message.
Inline fix: `/queue collect` (per-session) or set `routing.queue.bySurface.discord: "collect"`.
Defaults (when unset in config):
- All surfaces → `collect`
@@ -40,7 +45,7 @@ Configure globally or per surface via `routing.queue`:
debounceMs: 1000,
cap: 20,
drop: "summarize",
bySurface: { discord: "steer-backlog" }
bySurface: { discord: "collect" }
}
}
}
+1 -1
View File
@@ -40,7 +40,7 @@ default unless you force `gateway.auth.mode` to `password` or set
}
```
Open: `https://<magicdns>/ui/`
Open: `https://<magicdns>/` (or your configured `gateway.controlUi.basePath`)
### Public internet (Funnel + shared password)
+6 -4
View File
@@ -8,10 +8,12 @@ read_when:
The Gateway serves a small **browser Control UI** (Vite + Lit) from the same port as the Gateway WebSocket:
- `http://<host>:18789/ui/`
- default: `http://<host>:18789/`
- optional prefix: set `gateway.controlUi.basePath` (e.g. `/clawdis`)
The UI talks directly to the Gateway WS and supports:
- Chat (`chat.history`, `chat.send`, `chat.abort`)
- Chat tool cards (agent tool events)
- Connections (provider status, WhatsApp QR, Telegram config)
- Instances (`system-presence`)
- Sessions (`sessions.list`, `sessions.patch`)
@@ -34,7 +36,7 @@ You can control it via config:
```json5
{
gateway: {
controlUi: { enabled: true } // set false to disable /ui/
controlUi: { enabled: true, basePath: "/clawdis" } // basePath optional
}
}
```
@@ -61,7 +63,7 @@ clawdis gateway
```
Open:
- `https://<magicdns>/ui/`
- `https://<magicdns>/` (or your configured `gateway.controlUi.basePath`)
### Tailnet bind + token (legacy)
@@ -82,7 +84,7 @@ clawdis gateway
```
Open:
- `http://<tailscale-ip>:18789/ui/`
- `http://<tailscale-ip>:18789/` (or your configured `gateway.controlUi.basePath`)
### Public internet (Funnel)
+5
View File
@@ -115,6 +115,11 @@ clawdis onboard --non-interactive \
Add `--json` for a machine‑readable summary.
## Gateway wizard RPC
The Gateway exposes the wizard flow over RPC (`wizard.start`, `wizard.next`, `wizard.cancel`, `wizard.status`).
Clients (macOS app, Control UI) can render steps without re‑implementing onboarding logic.
## Signal setup (signal-cli)
The wizard can install `signal-cli` from GitHub releases:
+5 -5
View File
@@ -73,10 +73,10 @@
"@clack/prompts": "^0.11.0",
"@grammyjs/transformer-throttler": "^1.2.1",
"@homebridge/ciao": "^1.3.4",
"@mariozechner/pi-agent-core": "^0.31.1",
"@mariozechner/pi-ai": "^0.31.1",
"@mariozechner/pi-coding-agent": "^0.31.1",
"@mariozechner/pi-tui": "^0.31.1",
"@mariozechner/pi-agent-core": "^0.32.3",
"@mariozechner/pi-ai": "^0.32.3",
"@mariozechner/pi-coding-agent": "^0.32.3",
"@mariozechner/pi-tui": "^0.32.3",
"@sinclair/typebox": "0.34.46",
"@whiskeysockets/baileys": "7.0.0-rc.9",
"ajv": "^8.17.1",
@@ -138,7 +138,7 @@
},
"patchedDependencies": {
"@mariozechner/pi-ai": "patches/@mariozechner__pi-ai.patch",
"@mariozechner/pi-coding-agent@0.31.1": "patches/@mariozechner__pi-coding-agent@0.31.1.patch"
"@mariozechner/pi-coding-agent@0.32.3": "patches/@mariozechner__pi-coding-agent@0.32.3.patch"
}
},
"vitest": {
+28 -27
View File
@@ -11,9 +11,9 @@ patchedDependencies:
'@mariozechner/pi-ai':
hash: 969db6f3f4cc91fec48124e1f5e515b386b1f1bed807769d0a80c28abadbaaae
path: patches/@mariozechner__pi-ai.patch
'@mariozechner/pi-coding-agent@0.31.1':
'@mariozechner/pi-coding-agent@0.32.3':
hash: d0d5ffa1bfda8a0f9d14a5e73a074014346d3edbdb2ffc91444d3be5119f5745
path: patches/@mariozechner__pi-coding-agent@0.31.1.patch
path: patches/@mariozechner__pi-coding-agent@0.32.3.patch
importers:
@@ -29,17 +29,17 @@ importers:
specifier: ^1.3.4
version: 1.3.4
'@mariozechner/pi-agent-core':
specifier: ^0.31.1
version: 0.31.1(ws@8.18.3)(zod@4.3.4)
specifier: ^0.32.3
version: 0.32.3(ws@8.18.3)(zod@4.3.4)
'@mariozechner/pi-ai':
specifier: ^0.31.1
version: 0.31.1(patch_hash=969db6f3f4cc91fec48124e1f5e515b386b1f1bed807769d0a80c28abadbaaae)(ws@8.18.3)(zod@4.3.4)
specifier: ^0.32.3
version: 0.32.3(patch_hash=969db6f3f4cc91fec48124e1f5e515b386b1f1bed807769d0a80c28abadbaaae)(ws@8.18.3)(zod@4.3.4)
'@mariozechner/pi-coding-agent':
specifier: ^0.31.1
version: 0.31.1(patch_hash=d0d5ffa1bfda8a0f9d14a5e73a074014346d3edbdb2ffc91444d3be5119f5745)(ws@8.18.3)(zod@4.3.4)
specifier: ^0.32.3
version: 0.32.3(patch_hash=d0d5ffa1bfda8a0f9d14a5e73a074014346d3edbdb2ffc91444d3be5119f5745)(ws@8.18.3)(zod@4.3.4)
'@mariozechner/pi-tui':
specifier: ^0.31.1
version: 0.31.1
specifier: ^0.32.3
version: 0.32.3
'@sinclair/typebox':
specifier: 0.34.46
version: 0.34.46
@@ -744,22 +744,22 @@ packages:
peerDependencies:
lit: ^3.3.1
'@mariozechner/pi-agent-core@0.31.1':
resolution: {integrity: sha512-skY2ZGrVbTkbTpdHql3mR0//BbLeqwKWQ0bnoI2H7YHbR5bTDSaYwtRtSdEgfPVgTk+WBQaZOZOv6be4qCAsww==}
'@mariozechner/pi-agent-core@0.32.3':
resolution: {integrity: sha512-NN/fd8eBISnRbQYblLjiaRbcFjz+SEFOGhZDZCXYgHJikTV8VyEon0nZFh7agBZJ7sXZaumMTjw/pGFrBFKcmA==}
engines: {node: '>=20.0.0'}
'@mariozechner/pi-ai@0.31.1':
resolution: {integrity: sha512-mqqitu/69ofLPmQEj7m04SvPQZEX+uacLHU9oQxz1c1khclsjw2S7G/v5P/3jK4hZjoZfHkPJRwPMFvEbo3wAA==}
'@mariozechner/pi-ai@0.32.3':
resolution: {integrity: sha512-njaa4/pN7U1TbjI1PKqII3M/W1CQ/obPAu5A4KHsX74e8sKjDEiEELUWzLTa5xOj+l1OXp/FtzI0hfJDq682rQ==}
engines: {node: '>=20.0.0'}
hasBin: true
'@mariozechner/pi-coding-agent@0.31.1':
resolution: {integrity: sha512-S+IQMYJssNFXQcdk8iB3tY0b1Idi0gAZCdwGCkTSG+vGghO0rdo+vQ+/v5KM6BhW2XsKiYz/2XCG8237iVwINA==}
'@mariozechner/pi-coding-agent@0.32.3':
resolution: {integrity: sha512-kOuzflbWc8GWHGOu/7KJQ1P3IodDk4AdOvibkJDcAn2aw5kG+LZAjLGt72tIMQRQna51i9XzL4nSvbxqV+mgWw==}
engines: {node: '>=20.0.0'}
hasBin: true
'@mariozechner/pi-tui@0.31.1':
resolution: {integrity: sha512-79hDQPAMPxKO0HKoXiFLp1HFbRDwweYL31l2wlsEzhPYgIYvx0Ii7X+KK4yMjjfDc4SjX6ZmSnJ4MUFAanuVzA==}
'@mariozechner/pi-tui@0.32.3':
resolution: {integrity: sha512-aq7e6qXcwSHvaTUKj5Ut9BY+ZezQ2rL+V4Sd2R5SnBW6JMCt5GnR/8uYBC2PcdxBQzGL9TnzjrC4av5jR+ilow==}
engines: {node: '>=20.0.0'}
'@mistralai/mistralai@1.10.0':
@@ -3351,10 +3351,10 @@ snapshots:
transitivePeerDependencies:
- tailwindcss
'@mariozechner/pi-agent-core@0.31.1(ws@8.18.3)(zod@4.3.4)':
'@mariozechner/pi-agent-core@0.32.3(ws@8.18.3)(zod@4.3.4)':
dependencies:
'@mariozechner/pi-ai': 0.31.1(patch_hash=969db6f3f4cc91fec48124e1f5e515b386b1f1bed807769d0a80c28abadbaaae)(ws@8.18.3)(zod@4.3.4)
'@mariozechner/pi-tui': 0.31.1
'@mariozechner/pi-ai': 0.32.3(patch_hash=969db6f3f4cc91fec48124e1f5e515b386b1f1bed807769d0a80c28abadbaaae)(ws@8.18.3)(zod@4.3.4)
'@mariozechner/pi-tui': 0.32.3
transitivePeerDependencies:
- '@modelcontextprotocol/sdk'
- bufferutil
@@ -3363,7 +3363,7 @@ snapshots:
- ws
- zod
'@mariozechner/pi-ai@0.31.1(patch_hash=969db6f3f4cc91fec48124e1f5e515b386b1f1bed807769d0a80c28abadbaaae)(ws@8.18.3)(zod@4.3.4)':
'@mariozechner/pi-ai@0.32.3(patch_hash=969db6f3f4cc91fec48124e1f5e515b386b1f1bed807769d0a80c28abadbaaae)(ws@8.18.3)(zod@4.3.4)':
dependencies:
'@anthropic-ai/sdk': 0.71.2(zod@4.3.4)
'@google/genai': 1.34.0
@@ -3383,11 +3383,11 @@ snapshots:
- ws
- zod
'@mariozechner/pi-coding-agent@0.31.1(patch_hash=d0d5ffa1bfda8a0f9d14a5e73a074014346d3edbdb2ffc91444d3be5119f5745)(ws@8.18.3)(zod@4.3.4)':
'@mariozechner/pi-coding-agent@0.32.3(patch_hash=d0d5ffa1bfda8a0f9d14a5e73a074014346d3edbdb2ffc91444d3be5119f5745)(ws@8.18.3)(zod@4.3.4)':
dependencies:
'@mariozechner/pi-agent-core': 0.31.1(ws@8.18.3)(zod@4.3.4)
'@mariozechner/pi-ai': 0.31.1(patch_hash=969db6f3f4cc91fec48124e1f5e515b386b1f1bed807769d0a80c28abadbaaae)(ws@8.18.3)(zod@4.3.4)
'@mariozechner/pi-tui': 0.31.1
'@mariozechner/pi-agent-core': 0.32.3(ws@8.18.3)(zod@4.3.4)
'@mariozechner/pi-ai': 0.32.3(patch_hash=969db6f3f4cc91fec48124e1f5e515b386b1f1bed807769d0a80c28abadbaaae)(ws@8.18.3)(zod@4.3.4)
'@mariozechner/pi-tui': 0.32.3
chalk: 5.6.2
cli-highlight: 2.1.11
diff: 8.0.2
@@ -3395,6 +3395,7 @@ snapshots:
glob: 11.1.0
jiti: 2.6.1
marked: 15.0.12
sharp: 0.34.5
transitivePeerDependencies:
- '@modelcontextprotocol/sdk'
- bufferutil
@@ -3403,7 +3404,7 @@ snapshots:
- ws
- zod
'@mariozechner/pi-tui@0.31.1':
'@mariozechner/pi-tui@0.32.3':
dependencies:
'@types/mime-types': 2.1.4
chalk: 5.6.2
+33 -2
View File
@@ -57,12 +57,40 @@ select_identity() {
if [ -z "$IDENTITY" ]; then
if ! IDENTITY="$(select_identity)"; then
echo "ERROR: No signing identity found. Set SIGN_IDENTITY to a valid codesigning certificate." >&2
exit 1
if [[ "${ALLOW_ADHOC_SIGNING:-}" == "1" ]]; then
echo "WARN: No signing identity found. Falling back to ad-hoc signing (-)." >&2
echo " !!! WARNING: Ad-hoc signed apps do NOT persist TCC permissions (Accessibility, etc) !!!" >&2
echo " !!! You will need to re-grant permissions every time you restart the app. !!!" >&2
IDENTITY="-"
else
echo "ERROR: No signing identity found. Set SIGN_IDENTITY to a valid codesigning certificate." >&2
echo " Alternatively, set ALLOW_ADHOC_SIGNING=1 to fallback to ad-hoc signing (limitations apply)." >&2
exit 1
fi
fi
fi
echo "Using signing identity: $IDENTITY"
if [[ "$IDENTITY" == "-" ]]; then
cat <<'WARN' >&2
================================================================================
!!! AD-HOC SIGNING IN USE - PERMISSIONS WILL NOT STICK (macOS RESTRICTION) !!!
macOS ties permissions to the code signature, bundle ID, and app path.
Ad-hoc signing generates a new signature every build, so macOS treats the app
as a different binary and will forget permissions (prompts may vanish).
For correct permission behavior you MUST sign with a real Apple Development or
Developer ID certificate.
If prompts disappear: remove the app entry in System Settings -> Privacy & Security,
relaunch the app, and re-grant. Some permissions only reappear after a full
macOS restart.
================================================================================
WARN
fi
timestamp_arg="--timestamp=none"
case "$TIMESTAMP_MODE" in
@@ -82,6 +110,9 @@ case "$TIMESTAMP_MODE" in
exit 1
;;
esac
if [[ "$IDENTITY" == "-" ]]; then
timestamp_arg="--timestamp=none"
fi
options_args=()
if [[ "$IDENTITY" != "-" ]]; then
+9 -1
View File
@@ -115,7 +115,15 @@ build_relay_binary() {
echo "ERROR: Rosetta is required to build the x86_64 relay. Install Rosetta and retry." >&2
exit 1
fi
local bun_x86="${BUN_X86_64_BIN:-$HOME/.bun-x64/bin/bun}"
local bun_x86="${BUN_X86_64_BIN:-$HOME/.bun-x64/bun-darwin-x64/bun}"
if [[ ! -x "$bun_x86" ]]; then
bun_x86="$HOME/.bun-x64/bin/bun"
fi
if [[ "$bun_x86" == *baseline* ]]; then
echo "ERROR: x86_64 relay builds are locked to AVX2; baseline Bun is not allowed." >&2
echo "Set BUN_X86_64_BIN to a non-baseline Bun (bun-darwin-x64)." >&2
exit 1
fi
if [[ -x "$bun_x86" ]]; then
cmd=("$bun_x86" build "$ROOT_DIR/dist/macos/relay.js" --compile --bytecode --outfile "$out" -e electron --define "$define_arg")
fi
+46
View File
@@ -0,0 +1,46 @@
---
name: blogwatcher
description: Monitor blogs and RSS/Atom feeds for updates using the blogwatcher CLI.
homepage: https://github.com/Hyaxia/blogwatcher
metadata: {"clawdis":{"emoji":"📰","requires":{"bins":["blogwatcher"]},"install":[{"id":"go","kind":"go","module":"github.com/Hyaxia/blogwatcher/cmd/blogwatcher@latest","bins":["blogwatcher"],"label":"Install blogwatcher (go)"}]}}
---
# blogwatcher
Track blog and RSS/Atom feed updates with the `blogwatcher` CLI.
Install
- Go: `go install github.com/Hyaxia/blogwatcher/cmd/blogwatcher@latest`
Quick start
- `blogwatcher --help`
Common commands
- Add a blog: `blogwatcher add "My Blog" https://example.com`
- List blogs: `blogwatcher blogs`
- Scan for updates: `blogwatcher scan`
- List articles: `blogwatcher articles`
- Mark an article read: `blogwatcher read 1`
- Mark all articles read: `blogwatcher read-all`
- Remove a blog: `blogwatcher remove "My Blog"`
Example output
```
$ blogwatcher blogs
Tracked blogs (1):
xkcd
URL: https://xkcd.com
```
```
$ blogwatcher scan
Scanning 1 blog(s)...
xkcd
Source: RSS | Found: 4 | New: 4
Found 4 new article(s) total!
```
Notes
- Use `blogwatcher <command> --help` to discover flags and options.
+34 -3
View File
@@ -1,12 +1,12 @@
---
name: coding-agent
description: Run Codex CLI, Claude Code, or OpenCode via background process for programmatic control.
metadata: {"clawdis":{"emoji":"🧩","requires":{"anyBins":["claude","codex","opencode"]}}}
description: Run Codex CLI, Claude Code, OpenCode, or Pi Coding Agent via background process for programmatic control.
metadata: {"clawdis":{"emoji":"🧩","requires":{"anyBins":["claude","codex","opencode","pi"]}}}
---
# Coding Agent (background-first)
Use **bash background mode** for coding agents. Full programmatic control, no tmux needed.
Use **bash background mode** for non-interactive coding work. For interactive coding sessions, use the **tmux** skill (always, except very simple one-shot prompts).
## The Pattern: workdir + background
@@ -113,6 +113,37 @@ bash workdir:~/project background:true command:"opencode run \"Your task\""
---
## Pi Coding Agent
```bash
# Install: npm install -g @mariozechner/pi-coding-agent
bash workdir:~/project background:true command:"pi \"Your task\""
```
---
## Pi flags (common)
- `--print` / `-p`: non-interactive; runs prompt and exits.
- `--provider <name>`: pick provider (default: google).
- `--model <id>`: pick model (default: gemini-2.5-flash).
- `--api-key <key>`: override API key (defaults to env vars).
Examples:
```bash
# Set provider + model, non-interactive
bash workdir:~/project background:true command:"pi --provider openai --model gpt-4o-mini -p \"Summarize src/\""
```
---
## tmux (interactive sessions)
Use the tmux skill for interactive coding sessions (always, except very simple one-shot prompts). Prefer bash background mode for non-interactive runs.
---
## ⚠️ Rules
1. **Respect tool choice** — if user asks for Codex, use Codex. NEVER offer to build it yourself!
+47
View File
@@ -0,0 +1,47 @@
---
name: github
description: "Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries."
---
# GitHub Skill
Use the `gh` CLI to interact with GitHub. Always specify `--repo owner/repo` when not in a git directory, or use URLs directly.
## Pull Requests
Check CI status on a PR:
```bash
gh pr checks 55 --repo owner/repo
```
List recent workflow runs:
```bash
gh run list --repo owner/repo --limit 10
```
View a run and see which steps failed:
```bash
gh run view <run-id> --repo owner/repo
```
View logs for failed steps only:
```bash
gh run view <run-id> --repo owner/repo --log-failed
```
## API for Advanced Queries
The `gh api` command is useful for accessing data not available through other subcommands.
Get PR with specific fields:
```bash
gh api repos/owner/repo/pulls/55 --jq '.title, .state, .user.login'
```
## JSON Output
Most commands support `--json` for structured output. You can use `--jq` to filter:
```bash
gh issue list --repo owner/repo --json number,title --jq '.[] | "\(.number): \(.title)"'
```
+86
View File
@@ -0,0 +1,86 @@
---
name: tmux
description: Remote-control tmux sessions for interactive CLIs by sending keystrokes and scraping pane output.
metadata: {"clawdis":{"emoji":"🧵","os":["darwin","linux"],"requires":{"bins":["tmux"]}}}
---
# tmux Skill (Clawdis)
Use tmux only when you need an interactive TTY. Prefer bash background mode for long-running, non-interactive tasks.
## Quickstart (isolated socket, bash tool)
```bash
SOCKET_DIR="${CLAWDIS_TMUX_SOCKET_DIR:-${TMPDIR:-/tmp}/clawdis-tmux-sockets}"
mkdir -p "$SOCKET_DIR"
SOCKET="$SOCKET_DIR/clawdis.sock"
SESSION=clawdis-python
tmux -S "$SOCKET" new -d -s "$SESSION" -n shell
tmux -S "$SOCKET" send-keys -t "$SESSION":0.0 -- 'PYTHON_BASIC_REPL=1 python3 -q' Enter
tmux -S "$SOCKET" capture-pane -p -J -t "$SESSION":0.0 -S -200
```
After starting a session, always print monitor commands:
```
To monitor:
tmux -S "$SOCKET" attach -t "$SESSION"
tmux -S "$SOCKET" capture-pane -p -J -t "$SESSION":0.0 -S -200
```
## Socket convention
- Use `CLAWDIS_TMUX_SOCKET_DIR` (default `${TMPDIR:-/tmp}/clawdis-tmux-sockets`).
- Default socket path: `"$CLAWDIS_TMUX_SOCKET_DIR/clawdis.sock"`.
## Targeting panes and naming
- Target format: `session:window.pane` (defaults to `:0.0`).
- Keep names short; avoid spaces.
- Inspect: `tmux -S "$SOCKET" list-sessions`, `tmux -S "$SOCKET" list-panes -a`.
## Finding sessions
- List sessions on your socket: `{baseDir}/scripts/find-sessions.sh -S "$SOCKET"`.
- Scan all sockets: `{baseDir}/scripts/find-sessions.sh --all` (uses `CLAWDIS_TMUX_SOCKET_DIR`).
## Sending input safely
- Prefer literal sends: `tmux -S "$SOCKET" send-keys -t target -l -- "$cmd"`.
- Control keys: `tmux -S "$SOCKET" send-keys -t target C-c`.
## Watching output
- Capture recent history: `tmux -S "$SOCKET" capture-pane -p -J -t target -S -200`.
- Wait for prompts: `{baseDir}/scripts/wait-for-text.sh -t session:0.0 -p 'pattern'`.
- Attaching is OK; detach with `Ctrl+b d`.
## Spawning processes
- For python REPLs, set `PYTHON_BASIC_REPL=1` (non-basic REPL breaks send-keys flows).
## Windows / WSL
- tmux is supported on macOS/Linux. On Windows, use WSL and install tmux inside WSL.
- This skill is gated to `darwin`/`linux` and requires `tmux` on PATH.
## Cleanup
- Kill a session: `tmux -S "$SOCKET" kill-session -t "$SESSION"`.
- Kill all sessions on a socket: `tmux -S "$SOCKET" list-sessions -F '#{session_name}' | xargs -r -n1 tmux -S "$SOCKET" kill-session -t`.
- Remove everything on the private socket: `tmux -S "$SOCKET" kill-server`.
## Helper: wait-for-text.sh
`{baseDir}/scripts/wait-for-text.sh` polls a pane for a regex (or fixed string) with a timeout.
```bash
{baseDir}/scripts/wait-for-text.sh -t session:0.0 -p 'pattern' [-F] [-T 20] [-i 0.5] [-l 2000]
```
- `-t`/`--target` pane target (required)
- `-p`/`--pattern` regex to match (required); add `-F` for fixed string
- `-T` timeout seconds (integer, default 15)
- `-i` poll interval seconds (default 0.5)
- `-l` history lines to search (integer, default 1000)
+112
View File
@@ -0,0 +1,112 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat <<'USAGE'
Usage: find-sessions.sh [-L socket-name|-S socket-path|-A] [-q pattern]
List tmux sessions on a socket (default tmux socket if none provided).
Options:
-L, --socket tmux socket name (passed to tmux -L)
-S, --socket-path tmux socket path (passed to tmux -S)
-A, --all scan all sockets under CLAWDIS_TMUX_SOCKET_DIR
-q, --query case-insensitive substring to filter session names
-h, --help show this help
USAGE
}
socket_name=""
socket_path=""
query=""
scan_all=false
socket_dir="${CLAWDIS_TMUX_SOCKET_DIR:-${TMPDIR:-/tmp}/clawdis-tmux-sockets}"
while [[ $# -gt 0 ]]; do
case "$1" in
-L|--socket) socket_name="${2-}"; shift 2 ;;
-S|--socket-path) socket_path="${2-}"; shift 2 ;;
-A|--all) scan_all=true; shift ;;
-q|--query) query="${2-}"; shift 2 ;;
-h|--help) usage; exit 0 ;;
*) echo "Unknown option: $1" >&2; usage; exit 1 ;;
esac
done
if [[ "$scan_all" == true && ( -n "$socket_name" || -n "$socket_path" ) ]]; then
echo "Cannot combine --all with -L or -S" >&2
exit 1
fi
if [[ -n "$socket_name" && -n "$socket_path" ]]; then
echo "Use either -L or -S, not both" >&2
exit 1
fi
if ! command -v tmux >/dev/null 2>&1; then
echo "tmux not found in PATH" >&2
exit 1
fi
list_sessions() {
local label="$1"; shift
local tmux_cmd=(tmux "$@")
if ! sessions="$("${tmux_cmd[@]}" list-sessions -F '#{session_name}\t#{session_attached}\t#{session_created_string}' 2>/dev/null)"; then
echo "No tmux server found on $label" >&2
return 1
fi
if [[ -n "$query" ]]; then
sessions="$(printf '%s\n' "$sessions" | grep -i -- "$query" || true)"
fi
if [[ -z "$sessions" ]]; then
echo "No sessions found on $label"
return 0
fi
echo "Sessions on $label:"
printf '%s\n' "$sessions" | while IFS=$'\t' read -r name attached created; do
attached_label=$([[ "$attached" == "1" ]] && echo "attached" || echo "detached")
printf ' - %s (%s, started %s)\n' "$name" "$attached_label" "$created"
done
}
if [[ "$scan_all" == true ]]; then
if [[ ! -d "$socket_dir" ]]; then
echo "Socket directory not found: $socket_dir" >&2
exit 1
fi
shopt -s nullglob
sockets=("$socket_dir"/*)
shopt -u nullglob
if [[ "${#sockets[@]}" -eq 0 ]]; then
echo "No sockets found under $socket_dir" >&2
exit 1
fi
exit_code=0
for sock in "${sockets[@]}"; do
if [[ ! -S "$sock" ]]; then
continue
fi
list_sessions "socket path '$sock'" -S "$sock" || exit_code=$?
done
exit "$exit_code"
fi
tmux_cmd=(tmux)
socket_label="default socket"
if [[ -n "$socket_name" ]]; then
tmux_cmd+=(-L "$socket_name")
socket_label="socket name '$socket_name'"
elif [[ -n "$socket_path" ]]; then
tmux_cmd+=(-S "$socket_path")
socket_label="socket path '$socket_path'"
fi
list_sessions "$socket_label" "${tmux_cmd[@]:1}"
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat <<'USAGE'
Usage: wait-for-text.sh -t target -p pattern [options]
Poll a tmux pane for text and exit when found.
Options:
-t, --target tmux target (session:window.pane), required
-p, --pattern regex pattern to look for, required
-F, --fixed treat pattern as a fixed string (grep -F)
-T, --timeout seconds to wait (integer, default: 15)
-i, --interval poll interval in seconds (default: 0.5)
-l, --lines number of history lines to inspect (integer, default: 1000)
-h, --help show this help
USAGE
}
target=""
pattern=""
grep_flag="-E"
timeout=15
interval=0.5
lines=1000
while [[ $# -gt 0 ]]; do
case "$1" in
-t|--target) target="${2-}"; shift 2 ;;
-p|--pattern) pattern="${2-}"; shift 2 ;;
-F|--fixed) grep_flag="-F"; shift ;;
-T|--timeout) timeout="${2-}"; shift 2 ;;
-i|--interval) interval="${2-}"; shift 2 ;;
-l|--lines) lines="${2-}"; shift 2 ;;
-h|--help) usage; exit 0 ;;
*) echo "Unknown option: $1" >&2; usage; exit 1 ;;
esac
done
if [[ -z "$target" || -z "$pattern" ]]; then
echo "target and pattern are required" >&2
usage
exit 1
fi
if ! [[ "$timeout" =~ ^[0-9]+$ ]]; then
echo "timeout must be an integer number of seconds" >&2
exit 1
fi
if ! [[ "$lines" =~ ^[0-9]+$ ]]; then
echo "lines must be an integer" >&2
exit 1
fi
if ! command -v tmux >/dev/null 2>&1; then
echo "tmux not found in PATH" >&2
exit 1
fi
# End time in epoch seconds (integer, good enough for polling)
start_epoch=$(date +%s)
deadline=$((start_epoch + timeout))
while true; do
# -J joins wrapped lines, -S uses negative index to read last N lines
pane_text="$(tmux capture-pane -p -J -t "$target" -S "-${lines}" 2>/dev/null || true)"
if printf '%s\n' "$pane_text" | grep $grep_flag -- "$pattern" >/dev/null 2>&1; then
exit 0
fi
now=$(date +%s)
if (( now >= deadline )); then
echo "Timed out after ${timeout}s waiting for pattern: $pattern" >&2
echo "Last ${lines} lines from $target:" >&2
printf '%s\n' "$pane_text" >&2
exit 1
fi
sleep "$interval"
done
+15 -4
View File
@@ -42,9 +42,13 @@ import {
formatAssistantErrorText,
sanitizeSessionMessagesImages,
} from "./pi-embedded-helpers.js";
import { subscribeEmbeddedPiSession } from "./pi-embedded-subscribe.js";
import {
type BlockReplyChunking,
subscribeEmbeddedPiSession,
} from "./pi-embedded-subscribe.js";
import { extractAssistantText } from "./pi-embedded-utils.js";
import { createClawdisCodingTools } from "./pi-tools.js";
import { resolveSandboxContext } from "./sandbox.js";
import {
applySkillEnvOverrides,
applySkillEnvOverridesFromSnapshot,
@@ -334,6 +338,7 @@ export async function runEmbeddedPiAgent(params: {
mediaUrls?: string[];
}) => void | Promise<void>;
blockReplyBreak?: "text_end" | "message_end";
blockReplyChunking?: BlockReplyChunking;
onToolResult?: (payload: {
text?: string;
mediaUrls?: string[];
@@ -358,7 +363,13 @@ export async function runEmbeddedPiAgent(params: {
return enqueueCommandInLane(sessionLane, () =>
enqueueGlobal(async () => {
const started = Date.now();
const resolvedWorkspace = resolveUserPath(params.workspaceDir);
const sandbox = await resolveSandboxContext({
config: params.config,
sessionKey: params.sessionKey,
workspaceDir: params.workspaceDir,
});
const workspaceDir = sandbox?.workspaceDir ?? params.workspaceDir;
const resolvedWorkspace = resolveUserPath(workspaceDir);
const prevCwd = process.cwd();
const provider =
@@ -421,6 +432,7 @@ export async function runEmbeddedPiAgent(params: {
const tools = createClawdisCodingTools({
bash: params.config?.agent?.bash,
surface: params.surface,
sandbox,
});
const machineName = await getMachineDisplayName();
const runtimeInfo = {
@@ -493,7 +505,6 @@ export async function runEmbeddedPiAgent(params: {
assistantTexts,
toolMetas,
unsubscribe,
flush: flushToolDebouncer,
waitForCompactionRetry,
} = subscribeEmbeddedPiSession({
session,
@@ -503,6 +514,7 @@ export async function runEmbeddedPiAgent(params: {
onToolResult: params.onToolResult,
onBlockReply: params.onBlockReply,
blockReplyBreak: params.blockReplyBreak,
blockReplyChunking: params.blockReplyChunking,
onPartialReply: params.onPartialReply,
onAgentEvent: params.onAgentEvent,
enforceFinalTag: params.enforceFinalTag,
@@ -566,7 +578,6 @@ export async function runEmbeddedPiAgent(params: {
abortWarnTimer = undefined;
}
unsubscribe();
flushToolDebouncer();
if (ACTIVE_EMBEDDED_RUNS.get(params.sessionId) === queueHandle) {
ACTIVE_EMBEDDED_RUNS.delete(params.sessionId);
}
+374
View File
@@ -231,6 +231,277 @@ describe("subscribeEmbeddedPiSession", () => {
expect(subscription.assistantTexts).toEqual(["Hello block"]);
});
it("does not append when text_end content is a prefix of deltas", () => {
let handler: ((evt: unknown) => void) | undefined;
const session: StubSession = {
subscribe: (fn) => {
handler = fn;
return () => {};
},
};
const onBlockReply = vi.fn();
const subscription = subscribeEmbeddedPiSession({
session: session as unknown as Parameters<
typeof subscribeEmbeddedPiSession
>[0]["session"],
runId: "run",
onBlockReply,
blockReplyBreak: "text_end",
});
handler?.({
type: "message_update",
message: { role: "assistant" },
assistantMessageEvent: {
type: "text_delta",
delta: "Hello world",
},
});
handler?.({
type: "message_update",
message: { role: "assistant" },
assistantMessageEvent: {
type: "text_end",
content: "Hello",
},
});
expect(onBlockReply).toHaveBeenCalledTimes(1);
expect(subscription.assistantTexts).toEqual(["Hello world"]);
});
it("does not append when text_end content is already contained", () => {
let handler: ((evt: unknown) => void) | undefined;
const session: StubSession = {
subscribe: (fn) => {
handler = fn;
return () => {};
},
};
const onBlockReply = vi.fn();
const subscription = subscribeEmbeddedPiSession({
session: session as unknown as Parameters<
typeof subscribeEmbeddedPiSession
>[0]["session"],
runId: "run",
onBlockReply,
blockReplyBreak: "text_end",
});
handler?.({
type: "message_update",
message: { role: "assistant" },
assistantMessageEvent: {
type: "text_delta",
delta: "Hello world",
},
});
handler?.({
type: "message_update",
message: { role: "assistant" },
assistantMessageEvent: {
type: "text_end",
content: "world",
},
});
expect(onBlockReply).toHaveBeenCalledTimes(1);
expect(subscription.assistantTexts).toEqual(["Hello world"]);
});
it("appends suffix when text_end content extends deltas", () => {
let handler: ((evt: unknown) => void) | undefined;
const session: StubSession = {
subscribe: (fn) => {
handler = fn;
return () => {};
},
};
const onBlockReply = vi.fn();
const subscription = subscribeEmbeddedPiSession({
session: session as unknown as Parameters<
typeof subscribeEmbeddedPiSession
>[0]["session"],
runId: "run",
onBlockReply,
blockReplyBreak: "text_end",
});
handler?.({
type: "message_update",
message: { role: "assistant" },
assistantMessageEvent: {
type: "text_delta",
delta: "Hello",
},
});
handler?.({
type: "message_update",
message: { role: "assistant" },
assistantMessageEvent: {
type: "text_end",
content: "Hello world",
},
});
expect(onBlockReply).toHaveBeenCalledTimes(1);
expect(subscription.assistantTexts).toEqual(["Hello world"]);
});
it("does not duplicate when text_end repeats full content", () => {
let handler: ((evt: unknown) => void) | undefined;
const session: StubSession = {
subscribe: (fn) => {
handler = fn;
return () => {};
},
};
const onBlockReply = vi.fn();
const subscription = subscribeEmbeddedPiSession({
session: session as unknown as Parameters<
typeof subscribeEmbeddedPiSession
>[0]["session"],
runId: "run",
onBlockReply,
blockReplyBreak: "text_end",
});
handler?.({
type: "message_update",
message: { role: "assistant" },
assistantMessageEvent: {
type: "text_delta",
delta: "Good morning!",
},
});
handler?.({
type: "message_update",
message: { role: "assistant" },
assistantMessageEvent: {
type: "text_end",
content: "Good morning!",
},
});
expect(onBlockReply).toHaveBeenCalledTimes(1);
expect(subscription.assistantTexts).toEqual(["Good morning!"]);
});
it("does not duplicate block chunks when text_end repeats full content", () => {
let handler: ((evt: unknown) => void) | undefined;
const session: StubSession = {
subscribe: (fn) => {
handler = fn;
return () => {};
},
};
const onBlockReply = vi.fn();
subscribeEmbeddedPiSession({
session: session as unknown as Parameters<
typeof subscribeEmbeddedPiSession
>[0]["session"],
runId: "run",
onBlockReply,
blockReplyBreak: "text_end",
blockReplyChunking: {
minChars: 5,
maxChars: 40,
breakPreference: "newline",
},
});
const fullText = "First line\nSecond line\nThird line\n";
handler?.({
type: "message_update",
message: { role: "assistant" },
assistantMessageEvent: {
type: "text_delta",
delta: fullText,
},
});
const callsAfterDelta = onBlockReply.mock.calls.length;
expect(callsAfterDelta).toBeGreaterThan(0);
handler?.({
type: "message_update",
message: { role: "assistant" },
assistantMessageEvent: {
type: "text_end",
content: fullText,
},
});
expect(onBlockReply).toHaveBeenCalledTimes(callsAfterDelta);
});
it("streams soft chunks with paragraph preference", () => {
let handler: ((evt: unknown) => void) | undefined;
const session: StubSession = {
subscribe: (fn) => {
handler = fn;
return () => {};
},
};
const onBlockReply = vi.fn();
const subscription = subscribeEmbeddedPiSession({
session: session as unknown as Parameters<
typeof subscribeEmbeddedPiSession
>[0]["session"],
runId: "run",
onBlockReply,
blockReplyBreak: "message_end",
blockReplyChunking: {
minChars: 5,
maxChars: 40,
breakPreference: "paragraph",
},
});
const text = "First block line\n\nSecond block line";
handler?.({
type: "message_update",
message: { role: "assistant" },
assistantMessageEvent: {
type: "text_delta",
delta: text,
},
});
const assistantMessage = {
role: "assistant",
content: [{ type: "text", text }],
} as AssistantMessage;
handler?.({ type: "message_end", message: assistantMessage });
expect(onBlockReply).toHaveBeenCalledTimes(2);
expect(onBlockReply.mock.calls[0][0].text).toBe("First block line");
expect(onBlockReply.mock.calls[1][0].text).toBe("Second block line");
expect(subscription.assistantTexts).toEqual([
"First block line",
"Second block line",
]);
});
it("waits for auto-compaction retry and clears buffered text", async () => {
const listeners: SessionEventHandler[] = [];
const session = {
@@ -359,4 +630,107 @@ describe("subscribeEmbeddedPiSession", () => {
await waitPromise;
expect(resolved).toBe(true);
});
it("emits tool summaries at tool start when verbose is on", () => {
let handler: ((evt: unknown) => void) | undefined;
const session: StubSession = {
subscribe: (fn) => {
handler = fn;
return () => {};
},
};
const onToolResult = vi.fn();
subscribeEmbeddedPiSession({
session: session as unknown as Parameters<
typeof subscribeEmbeddedPiSession
>[0]["session"],
runId: "run-tool",
verboseLevel: "on",
onToolResult,
});
handler?.({
type: "tool_execution_start",
toolName: "read",
toolCallId: "tool-1",
args: { path: "/tmp/a.txt" },
});
expect(onToolResult).toHaveBeenCalledTimes(1);
const payload = onToolResult.mock.calls[0][0];
expect(payload.text).toContain("/tmp/a.txt");
handler?.({
type: "tool_execution_end",
toolName: "read",
toolCallId: "tool-1",
isError: false,
result: "ok",
});
expect(onToolResult).toHaveBeenCalledTimes(1);
});
it("skips tool summaries when shouldEmitToolResult is false", () => {
let handler: ((evt: unknown) => void) | undefined;
const session: StubSession = {
subscribe: (fn) => {
handler = fn;
return () => {};
},
};
const onToolResult = vi.fn();
subscribeEmbeddedPiSession({
session: session as unknown as Parameters<
typeof subscribeEmbeddedPiSession
>[0]["session"],
runId: "run-tool-off",
shouldEmitToolResult: () => false,
onToolResult,
});
handler?.({
type: "tool_execution_start",
toolName: "read",
toolCallId: "tool-2",
args: { path: "/tmp/b.txt" },
});
expect(onToolResult).not.toHaveBeenCalled();
});
it("emits tool summaries when shouldEmitToolResult overrides verbose", () => {
let handler: ((evt: unknown) => void) | undefined;
const session: StubSession = {
subscribe: (fn) => {
handler = fn;
return () => {};
},
};
const onToolResult = vi.fn();
subscribeEmbeddedPiSession({
session: session as unknown as Parameters<
typeof subscribeEmbeddedPiSession
>[0]["session"],
runId: "run-tool-override",
verboseLevel: "off",
shouldEmitToolResult: () => true,
onToolResult,
});
handler?.({
type: "tool_execution_start",
toolName: "read",
toolCallId: "tool-3",
args: { path: "/tmp/c.txt" },
});
expect(onToolResult).toHaveBeenCalledTimes(1);
});
});
+202 -65
View File
@@ -2,10 +2,7 @@ import type { AgentEvent, AgentMessage } from "@mariozechner/pi-agent-core";
import type { AssistantMessage } from "@mariozechner/pi-ai";
import type { AgentSession } from "@mariozechner/pi-coding-agent";
import {
createToolDebouncer,
formatToolAggregate,
} from "../auto-reply/tool-meta.js";
import { formatToolAggregate } from "../auto-reply/tool-meta.js";
import { emitAgentEvent } from "../infra/agent-events.js";
import { splitMediaFromOutput } from "../media/parse.js";
import { defaultRuntime } from "../runtime.js";
@@ -19,6 +16,12 @@ const THINKING_OPEN_RE = /<\s*think(?:ing)?\s*>/i;
const THINKING_CLOSE_RE = /<\s*\/\s*think(?:ing)?\s*>/i;
const TOOL_RESULT_MAX_CHARS = 8000;
export type BlockReplyChunking = {
minChars: number;
maxChars: number;
breakPreference?: "paragraph" | "newline" | "sentence";
};
function truncateToolText(text: string): string {
if (text.length <= TOOL_RESULT_MAX_CHARS) return text;
return `${text.slice(0, TOOL_RESULT_MAX_CHARS)}\n…(truncated)…`;
@@ -93,6 +96,7 @@ export function subscribeEmbeddedPiSession(params: {
mediaUrls?: string[];
}) => void | Promise<void>;
blockReplyBreak?: "text_end" | "message_end";
blockReplyChunking?: BlockReplyChunking;
onPartialReply?: (payload: {
text?: string;
mediaUrls?: string[];
@@ -106,8 +110,10 @@ export function subscribeEmbeddedPiSession(params: {
const assistantTexts: string[] = [];
const toolMetas: Array<{ toolName?: string; meta?: string }> = [];
const toolMetaById = new Map<string, string | undefined>();
const toolSummaryById = new Set<string>();
const blockReplyBreak = params.blockReplyBreak ?? "text_end";
let deltaBuffer = "";
let blockBuffer = "";
let lastStreamedAssistant: string | undefined;
let lastBlockReplyText: string | undefined;
let assistantTextBaseline = 0;
@@ -168,25 +174,142 @@ export function subscribeEmbeddedPiSession(params: {
return afterStart.slice(0, endIndex);
};
const toolDebouncer = createToolDebouncer((toolName, metas) => {
if (!params.onPartialReply) return;
const text = formatToolAggregate(toolName, metas);
const { text: cleanedText, mediaUrls } = splitMediaFromOutput(text);
void params.onPartialReply({
const blockChunking = params.blockReplyChunking;
const shouldEmitToolResult = () =>
typeof params.shouldEmitToolResult === "function"
? params.shouldEmitToolResult()
: params.verboseLevel === "on";
const emitToolSummary = (toolName?: string, meta?: string) => {
if (!params.onToolResult) return;
const agg = formatToolAggregate(toolName, meta ? [meta] : undefined);
const { text: cleanedText, mediaUrls } = splitMediaFromOutput(agg);
if (!cleanedText && (!mediaUrls || mediaUrls.length === 0)) return;
try {
void params.onToolResult({
text: cleanedText,
mediaUrls: mediaUrls?.length ? mediaUrls : undefined,
});
} catch {
// ignore tool result delivery failures
}
};
const findSentenceBreak = (window: string, minChars: number): number => {
if (!window) return -1;
const matches = window.matchAll(/[.!?](?=\s|$)/g);
let idx = -1;
for (const match of matches) {
const at = match.index ?? -1;
if (at < minChars) continue;
idx = at + 1;
}
return idx;
};
const findWhitespaceBreak = (window: string, minChars: number): number => {
for (let i = window.length - 1; i >= minChars; i--) {
if (/\s/.test(window[i])) return i;
}
return -1;
};
const pickBreakIndex = (buffer: string): number => {
if (!blockChunking) return -1;
const minChars = Math.max(1, Math.floor(blockChunking.minChars));
const maxChars = Math.max(minChars, Math.floor(blockChunking.maxChars));
if (buffer.length < minChars) return -1;
const window = buffer.slice(0, Math.min(maxChars, buffer.length));
const preference = blockChunking.breakPreference ?? "paragraph";
const paragraphIdx = window.lastIndexOf("\n\n");
if (preference === "paragraph" && paragraphIdx >= minChars) {
return paragraphIdx;
}
const newlineIdx = window.lastIndexOf("\n");
if (
(preference === "paragraph" || preference === "newline") &&
newlineIdx >= minChars
) {
return newlineIdx;
}
if (preference !== "newline") {
const sentenceIdx = findSentenceBreak(window, minChars);
if (sentenceIdx >= minChars) return sentenceIdx;
}
const whitespaceIdx = findWhitespaceBreak(window, minChars);
if (whitespaceIdx >= minChars) return whitespaceIdx;
if (buffer.length >= maxChars) return maxChars;
return -1;
};
const emitBlockChunk = (text: string) => {
const chunk = text.trimEnd();
if (!chunk) return;
if (chunk === lastBlockReplyText) return;
lastBlockReplyText = chunk;
assistantTexts.push(chunk);
if (!params.onBlockReply) return;
const { text: cleanedText, mediaUrls } = splitMediaFromOutput(chunk);
if (!cleanedText && (!mediaUrls || mediaUrls.length === 0)) return;
void params.onBlockReply({
text: cleanedText,
mediaUrls: mediaUrls?.length ? mediaUrls : undefined,
});
});
};
const drainBlockBuffer = (force: boolean) => {
if (!blockChunking) return;
const minChars = Math.max(1, Math.floor(blockChunking.minChars));
const maxChars = Math.max(minChars, Math.floor(blockChunking.maxChars));
// Force flush small remainders as a single chunk to avoid re-splitting.
if (force && blockBuffer.length > 0 && blockBuffer.length <= maxChars) {
emitBlockChunk(blockBuffer);
blockBuffer = "";
return;
}
if (blockBuffer.length < minChars && !force) return;
while (
blockBuffer.length >= minChars ||
(force && blockBuffer.length > 0)
) {
const breakIdx = pickBreakIndex(blockBuffer);
if (breakIdx <= 0) {
if (force) {
emitBlockChunk(blockBuffer);
blockBuffer = "";
}
return;
}
const rawChunk = blockBuffer.slice(0, breakIdx);
if (rawChunk.trim().length === 0) {
blockBuffer = blockBuffer.slice(breakIdx).trimStart();
continue;
}
emitBlockChunk(rawChunk);
const nextStart =
breakIdx < blockBuffer.length && /\s/.test(blockBuffer[breakIdx])
? breakIdx + 1
: breakIdx;
blockBuffer = blockBuffer.slice(nextStart).trimStart();
if (blockBuffer.length < minChars && !force) return;
if (blockBuffer.length < maxChars && !force) return;
}
};
const resetForCompactionRetry = () => {
assistantTexts.length = 0;
toolMetas.length = 0;
toolMetaById.clear();
toolSummaryById.clear();
deltaBuffer = "";
blockBuffer = "";
lastStreamedAssistant = undefined;
lastBlockReplyText = undefined;
assistantTextBaseline = 0;
toolDebouncer.flush();
};
const unsubscribe = params.session.subscribe(
@@ -219,6 +342,15 @@ export function subscribeEmbeddedPiSession(params: {
stream: "tool",
data: { phase: "start", name: toolName, toolCallId },
});
if (
params.onToolResult &&
shouldEmitToolResult() &&
!toolSummaryById.has(toolCallId)
) {
toolSummaryById.add(toolCallId);
emitToolSummary(toolName, meta);
}
}
if (evt.type === "tool_execution_update") {
@@ -265,7 +397,8 @@ export function subscribeEmbeddedPiSession(params: {
const sanitizedResult = sanitizeToolResult(result);
const meta = toolMetaById.get(toolCallId);
toolMetas.push({ toolName, meta });
toolDebouncer.push(toolName, meta);
toolMetaById.delete(toolCallId);
toolSummaryById.delete(toolCallId);
emitAgentEvent({
runId: params.runId,
@@ -289,25 +422,6 @@ export function subscribeEmbeddedPiSession(params: {
isError,
},
});
const emitToolResult =
typeof params.shouldEmitToolResult === "function"
? params.shouldEmitToolResult()
: params.verboseLevel === "on";
if (emitToolResult && params.onToolResult) {
const agg = formatToolAggregate(toolName, meta ? [meta] : undefined);
const { text: cleanedText, mediaUrls } = splitMediaFromOutput(agg);
if (cleanedText || (mediaUrls && mediaUrls.length > 0)) {
try {
void params.onToolResult({
text: cleanedText,
mediaUrls: mediaUrls?.length ? mediaUrls : undefined,
});
} catch {
// ignore tool result delivery failures
}
}
}
}
if (evt.type === "message_update") {
@@ -329,14 +443,34 @@ export function subscribeEmbeddedPiSession(params: {
evtType === "text_start" ||
evtType === "text_end"
) {
const chunk =
const delta =
typeof assistantRecord?.delta === "string"
? assistantRecord.delta
: typeof assistantRecord?.content === "string"
? assistantRecord.content
: "";
: "";
const content =
typeof assistantRecord?.content === "string"
? assistantRecord.content
: "";
let chunk = "";
if (evtType === "text_delta") {
chunk = delta;
} else if (evtType === "text_start" || evtType === "text_end") {
if (delta) {
chunk = delta;
} else if (content) {
// Providers may resend full content on text_end; append only the suffix.
if (content.startsWith(deltaBuffer)) {
chunk = content.slice(deltaBuffer.length);
} else if (deltaBuffer.startsWith(content)) {
chunk = "";
} else if (!deltaBuffer.includes(content)) {
chunk = content;
}
}
}
if (chunk) {
deltaBuffer += chunk;
blockBuffer += chunk;
}
const cleaned = params.enforceFinalTag
@@ -372,25 +506,29 @@ export function subscribeEmbeddedPiSession(params: {
}
}
if (params.onBlockReply && blockChunking) {
drainBlockBuffer(false);
}
if (evtType === "text_end" && blockReplyBreak === "text_end") {
if (next && next === lastBlockReplyText) {
deltaBuffer = "";
lastStreamedAssistant = undefined;
return;
}
lastBlockReplyText = next || undefined;
if (next) assistantTexts.push(next);
if (next && params.onBlockReply) {
const { text: cleanedText, mediaUrls } =
splitMediaFromOutput(next);
if (cleanedText || (mediaUrls && mediaUrls.length > 0)) {
void params.onBlockReply({
text: cleanedText,
mediaUrls: mediaUrls?.length ? mediaUrls : undefined,
});
if (blockChunking && blockBuffer.length > 0) {
drainBlockBuffer(true);
} else if (next && next !== lastBlockReplyText) {
lastBlockReplyText = next || undefined;
if (next) assistantTexts.push(next);
if (next && params.onBlockReply) {
const { text: cleanedText, mediaUrls } =
splitMediaFromOutput(next);
if (cleanedText || (mediaUrls && mediaUrls.length > 0)) {
void params.onBlockReply({
text: cleanedText,
mediaUrls: mediaUrls?.length ? mediaUrls : undefined,
});
}
}
}
deltaBuffer = "";
blockBuffer = "";
lastStreamedAssistant = undefined;
}
}
@@ -420,25 +558,26 @@ export function subscribeEmbeddedPiSession(params: {
assistantTextBaseline = assistantTexts.length;
if (
blockReplyBreak === "message_end" &&
(blockReplyBreak === "message_end" || blockBuffer.length > 0) &&
text &&
params.onBlockReply
) {
if (text === lastBlockReplyText) {
deltaBuffer = "";
lastStreamedAssistant = undefined;
return;
}
lastBlockReplyText = text;
const { text: cleanedText, mediaUrls } = splitMediaFromOutput(text);
if (cleanedText || (mediaUrls && mediaUrls.length > 0)) {
void params.onBlockReply({
text: cleanedText,
mediaUrls: mediaUrls?.length ? mediaUrls : undefined,
});
if (blockChunking && blockBuffer.length > 0) {
drainBlockBuffer(true);
} else if (text !== lastBlockReplyText) {
lastBlockReplyText = text;
const { text: cleanedText, mediaUrls } =
splitMediaFromOutput(text);
if (cleanedText || (mediaUrls && mediaUrls.length > 0)) {
void params.onBlockReply({
text: cleanedText,
mediaUrls: mediaUrls?.length ? mediaUrls : undefined,
});
}
}
}
deltaBuffer = "";
blockBuffer = "";
lastStreamedAssistant = undefined;
lastBlockReplyText = undefined;
}
@@ -484,7 +623,6 @@ export function subscribeEmbeddedPiSession(params: {
if (evt.type === "agent_end") {
defaultRuntime.log?.(`embedded run agent end: runId=${params.runId}`);
toolDebouncer.flush();
if (pendingCompactionRetry > 0) {
resolveCompactionRetry();
} else {
@@ -498,7 +636,6 @@ export function subscribeEmbeddedPiSession(params: {
assistantTexts,
toolMetas,
unsubscribe,
flush: () => toolDebouncer.flush(),
waitForCompactionRetry: () => {
if (compactionInFlight || pendingCompactionRetry > 0) {
ensureCompactionPromise();
+6 -6
View File
@@ -180,13 +180,13 @@ function cleanSchemaForGemini(schema: unknown): unknown {
cleaned[key] = cleanSchemaForGemini(value);
} else if (key === "anyOf" && Array.isArray(value)) {
// Clean each anyOf variant
cleaned[key] = value.map((v) => cleanSchemaForGemini(v));
cleaned[key] = value.map((variant) => cleanSchemaForGemini(variant));
} else if (key === "oneOf" && Array.isArray(value)) {
// Clean each oneOf variant
cleaned[key] = value.map((v) => cleanSchemaForGemini(v));
cleaned[key] = value.map((variant) => cleanSchemaForGemini(variant));
} else if (key === "allOf" && Array.isArray(value)) {
// Clean each allOf variant
cleaned[key] = value.map((v) => cleanSchemaForGemini(v));
cleaned[key] = value.map((variant) => cleanSchemaForGemini(variant));
} else if (
key === "additionalProperties" &&
value &&
@@ -265,12 +265,12 @@ function normalizeToolParameters(tool: AnyAgentTool): AnyAgentTool {
.map(([key]) => key)
: undefined;
const { anyOf: _unusedAnyOf, ...restSchema } = schema;
const nextSchema: Record<string, unknown> = { ...schema };
return {
...tool,
parameters: cleanSchemaForGemini({
...restSchema,
type: "object",
...nextSchema,
type: nextSchema.type ?? "object",
properties:
Object.keys(mergedProperties).length > 0
? mergedProperties
@@ -102,4 +102,45 @@ describe("block streaming", () => {
expect(onBlockReply).toHaveBeenCalledTimes(1);
});
});
it("drops final payloads when block replies streamed", async () => {
await withTempHome(async (home) => {
const onBlockReply = vi.fn().mockResolvedValue(undefined);
vi.mocked(runEmbeddedPiAgent).mockImplementation(async (params) => {
void params.onBlockReply?.({ text: "chunk-1" });
return {
payloads: [{ text: "chunk-1\nchunk-2" }],
meta: {
durationMs: 5,
agentMeta: { sessionId: "s", provider: "p", model: "m" },
},
};
});
const res = await getReplyFromConfig(
{
Body: "ping",
From: "+1004",
To: "+2000",
MessageSid: "msg-124",
Surface: "discord",
},
{
onBlockReply,
},
{
agent: {
model: "anthropic/claude-opus-4-5",
workspace: path.join(home, "clawd"),
},
whatsapp: { allowFrom: ["*"] },
session: { store: path.join(home, "sessions.json") },
},
);
expect(res).toBeUndefined();
expect(onBlockReply).toHaveBeenCalledTimes(1);
});
});
});
+78 -7
View File
@@ -58,6 +58,7 @@ import { defaultRuntime } from "../runtime.js";
import { normalizeE164 } from "../utils.js";
import { resolveHeartbeatSeconds } from "../web/reconnect.js";
import { getWebAuthAgeMs, webAuthExists } from "../web/session.js";
import { resolveTextChunkLimit, type TextChunkSurface } from "./chunk.js";
import {
normalizeGroupActivation,
parseActivationCommand,
@@ -81,6 +82,54 @@ export type { GetReplyOptions, ReplyPayload } from "./types.js";
const ABORT_TRIGGERS = new Set(["stop", "esc", "abort", "wait", "exit"]);
const ABORT_MEMORY = new Map<string, boolean>();
const SYSTEM_MARK = "⚙️";
const DEFAULT_BLOCK_STREAM_MIN = 800;
const DEFAULT_BLOCK_STREAM_MAX = 1200;
const BLOCK_CHUNK_SURFACES = new Set<TextChunkSurface>([
"whatsapp",
"telegram",
"discord",
"signal",
"imessage",
"webchat",
]);
function normalizeChunkSurface(surface?: string): TextChunkSurface | undefined {
if (!surface) return undefined;
const cleaned = surface.trim().toLowerCase();
return BLOCK_CHUNK_SURFACES.has(cleaned as TextChunkSurface)
? (cleaned as TextChunkSurface)
: undefined;
}
function resolveBlockStreamingChunking(
cfg: ClawdisConfig | undefined,
surface?: string,
): {
minChars: number;
maxChars: number;
breakPreference: "paragraph" | "newline" | "sentence";
} {
const surfaceKey = normalizeChunkSurface(surface);
const textLimit = resolveTextChunkLimit(cfg, surfaceKey);
const chunkCfg = cfg?.agent?.blockStreamingChunk;
const maxRequested = Math.max(
1,
Math.floor(chunkCfg?.maxChars ?? DEFAULT_BLOCK_STREAM_MAX),
);
const maxChars = Math.max(1, Math.min(maxRequested, textLimit));
const minRequested = Math.max(
1,
Math.floor(chunkCfg?.minChars ?? DEFAULT_BLOCK_STREAM_MIN),
);
const minChars = Math.min(minRequested, maxChars);
const breakPreference =
chunkCfg?.breakPreference === "newline" ||
chunkCfg?.breakPreference === "sentence"
? chunkCfg.breakPreference
: "paragraph";
return { minChars, maxChars, breakPreference };
}
type QueueMode =
| "steer"
@@ -1075,12 +1124,18 @@ export async function getReplyFromConfig(
(agentCfg?.verboseDefault as VerboseLevel | undefined);
const resolvedBlockStreaming =
agentCfg?.blockStreamingDefault === "off" ? "off" : "on";
// TODO(steipete): Default to message_end for now; figure out why text_end breaks and whether we can revert.
const resolvedBlockStreamingBreak =
agentCfg?.blockStreamingBreak === "text_end" ? "text_end" : "message_end";
agentCfg?.blockStreamingBreak === "message_end"
? "message_end"
: "text_end";
const blockStreamingEnabled = resolvedBlockStreaming === "on";
const blockReplyChunking = blockStreamingEnabled
? resolveBlockStreamingChunking(cfg, sessionCtx.Surface)
: undefined;
const streamedPayloadKeys = new Set<string>();
const pendingStreamedPayloadKeys = new Set<string>();
const pendingBlockTasks = new Set<Promise<void>>();
let didStreamBlockReply = false;
const buildPayloadKey = (payload: ReplyPayload) => {
const text = payload.text?.trim() ?? "";
const mediaList = payload.mediaUrls?.length
@@ -2124,6 +2179,7 @@ export async function getReplyFromConfig(
timeoutMs,
runId,
blockReplyBreak: resolvedBlockStreamingBreak,
blockReplyChunking,
onPartialReply: opts?.onPartialReply
? async (payload) => {
let text = payload.text;
@@ -2179,15 +2235,26 @@ export async function getReplyFromConfig(
replyToId: tagResult.replyToId,
};
const payloadKey = buildPayloadKey(blockPayload);
if (
streamedPayloadKeys.has(payloadKey) ||
pendingStreamedPayloadKeys.has(payloadKey)
) {
return;
}
pendingStreamedPayloadKeys.add(payloadKey);
const task = (async () => {
await startTypingOnText(cleaned);
await opts.onBlockReply?.(blockPayload);
})()
.then(() => {
streamedPayloadKeys.add(payloadKey);
didStreamBlockReply = true;
})
.catch((err) => {
logVerbose(`block reply delivery failed: ${String(err)}`);
})
.finally(() => {
pendingStreamedPayloadKeys.delete(payloadKey);
});
pendingBlockTasks.add(task);
void task.finally(() => pendingBlockTasks.delete(task));
@@ -2282,11 +2349,15 @@ export async function getReplyFromConfig(
(payload.mediaUrls && payload.mediaUrls.length > 0),
);
const filteredPayloads = blockStreamingEnabled
? replyTaggedPayloads.filter(
(payload) => !streamedPayloadKeys.has(buildPayloadKey(payload)),
)
: replyTaggedPayloads;
const shouldDropFinalPayloads =
blockStreamingEnabled && didStreamBlockReply;
const filteredPayloads = shouldDropFinalPayloads
? []
: blockStreamingEnabled
? replyTaggedPayloads.filter(
(payload) => !streamedPayloadKeys.has(buildPayloadKey(payload)),
)
: replyTaggedPayloads;
if (filteredPayloads.length === 0) return finalizeWithFollowup(undefined);
-35
View File
@@ -1,7 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
createToolDebouncer,
formatToolAggregate,
formatToolPrefix,
shortenMeta,
@@ -48,37 +47,3 @@ describe("tool meta formatting", () => {
expect(formatToolPrefix("x", "/Users/test/a.txt")).toBe("🧩 x: ~/a.txt");
});
});
describe("tool meta debouncer", () => {
it("flushes on timer and when tool changes", () => {
vi.useFakeTimers();
try {
const calls: Array<{ tool: string | undefined; metas: string[] }> = [];
const d = createToolDebouncer((tool, metas) => {
calls.push({ tool, metas });
}, 50);
d.push("a", "/tmp/1");
d.push("a", "/tmp/2");
expect(calls).toHaveLength(0);
vi.advanceTimersByTime(60);
expect(calls).toHaveLength(1);
expect(calls[0]).toMatchObject({
tool: "a",
metas: ["/tmp/1", "/tmp/2"],
});
d.push("a", "x");
d.push("b", "y"); // tool change flushes immediately
expect(calls).toHaveLength(2);
expect(calls[1]).toMatchObject({ tool: "a", metas: ["x"] });
vi.advanceTimersByTime(60);
expect(calls).toHaveLength(3);
expect(calls[2]).toMatchObject({ tool: "b", metas: ["y"] });
} finally {
vi.useRealTimers();
}
});
});
-33
View File
@@ -4,9 +4,6 @@ import {
} from "../agents/tool-display.js";
import { shortenHomeInString, shortenHomePath } from "../utils.js";
export const TOOL_RESULT_DEBOUNCE_MS = 500;
export const TOOL_RESULT_FLUSH_COUNT = 5;
export function shortenPath(p: string): string {
return shortenHomePath(p);
}
@@ -77,33 +74,3 @@ function isPathLike(value: string): boolean {
if (value.includes("&&") || value.includes("||")) return false;
return /^~?(\/[^\s]+)+$/.test(value);
}
export function createToolDebouncer(
onFlush: (toolName: string | undefined, metas: string[]) => void,
windowMs = TOOL_RESULT_DEBOUNCE_MS,
) {
let pendingTool: string | undefined;
let pendingMetas: string[] = [];
let timer: NodeJS.Timeout | null = null;
const flush = () => {
if (!pendingTool && pendingMetas.length === 0) return;
onFlush(pendingTool, pendingMetas);
pendingTool = undefined;
pendingMetas = [];
if (timer) {
clearTimeout(timer);
timer = null;
}
};
const push = (toolName?: string, meta?: string) => {
if (pendingTool && toolName && pendingTool !== toolName) flush();
if (!pendingTool) pendingTool = toolName;
if (meta) pendingMetas.push(meta);
if (timer) clearTimeout(timer);
timer = setTimeout(flush, windowMs);
};
return { push, flush };
}
+1 -1
View File
@@ -6,8 +6,8 @@ import { afterEach, describe, expect, it, vi } from "vitest";
vi.mock("../globals.js", () => ({
isVerbose: () => false,
shouldLogVerbose: () => false,
logVerbose: vi.fn(),
shouldLogVerbose: () => false,
}));
vi.mock("../process/exec.js", () => ({
+15 -5
View File
@@ -24,6 +24,7 @@ import { resolveGatewayService } from "../daemon/service.js";
import type { RuntimeEnv } from "../runtime.js";
import { defaultRuntime } from "../runtime.js";
import { resolveUserPath, sleep } from "../utils.js";
import { createClackPrompter } from "../wizard/clack-prompter.js";
import {
isRemoteEnvironment,
loginAntigravityVpsAware,
@@ -419,6 +420,7 @@ export async function runConfigureWizard(
intro(
opts.command === "update" ? "Clawdis update wizard" : "Clawdis configure",
);
const prompter = createClackPrompter();
const snapshot = await readConfigFileSnapshot();
let baseConfig: ClawdisConfig = snapshot.valid ? snapshot.config : {};
@@ -490,7 +492,7 @@ export async function runConfigureWizard(
) as "local" | "remote";
if (mode === "remote") {
let remoteConfig = await promptRemoteGatewayConfig(baseConfig, runtime);
let remoteConfig = await promptRemoteGatewayConfig(baseConfig, prompter);
remoteConfig = applyWizardMetadata(remoteConfig, {
command: opts.command,
mode,
@@ -565,7 +567,7 @@ export async function runConfigureWizard(
}
if (selected.includes("providers")) {
nextConfig = await setupProviders(nextConfig, runtime, {
nextConfig = await setupProviders(nextConfig, runtime, prompter, {
allowDisable: true,
allowSignalInstall: true,
});
@@ -573,7 +575,7 @@ export async function runConfigureWizard(
if (selected.includes("skills")) {
const wsDir = resolveUserPath(workspaceDir);
nextConfig = await setupSkills(nextConfig, wsDir, runtime);
nextConfig = await setupSkills(nextConfig, wsDir, runtime, prompter);
}
nextConfig = applyWizardMetadata(nextConfig, {
@@ -616,7 +618,11 @@ export async function runConfigureWizard(
note(
(() => {
const bind = nextConfig.gateway?.bind ?? "loopback";
const links = resolveControlUiLinks({ bind, port: gatewayPort });
const links = resolveControlUiLinks({
bind,
port: gatewayPort,
basePath: nextConfig.gateway?.controlUi?.basePath,
});
return [`Web UI: ${links.httpUrl}`, `Gateway WS: ${links.wsUrl}`].join(
"\n",
);
@@ -633,7 +639,11 @@ export async function runConfigureWizard(
);
if (wantsOpen) {
const bind = nextConfig.gateway?.bind ?? "loopback";
const links = resolveControlUiLinks({ bind, port: gatewayPort });
const links = resolveControlUiLinks({
bind,
port: gatewayPort,
basePath: nextConfig.gateway?.controlUi?.basePath,
});
await openUrl(links.httpUrl);
}
+7 -2
View File
@@ -13,6 +13,7 @@ import type { ClawdisConfig } from "../config/config.js";
import { CONFIG_PATH_CLAWDIS } from "../config/config.js";
import { resolveSessionTranscriptsDir } from "../config/sessions.js";
import { callGateway } from "../gateway/call.js";
import { normalizeControlUiBasePath } from "../gateway/control-ui.js";
import { pickPrimaryTailnetIPv4 } from "../infra/tailnet.js";
import { runCommandWithTimeout } from "../process/exec.js";
import type { RuntimeEnv } from "../runtime.js";
@@ -221,6 +222,7 @@ export const DEFAULT_WORKSPACE = DEFAULT_AGENT_WORKSPACE_DIR;
export function resolveControlUiLinks(params: {
port: number;
bind?: "auto" | "lan" | "tailnet" | "loopback";
basePath?: string;
}): { httpUrl: string; wsUrl: string } {
const port = params.port;
const bind = params.bind ?? "loopback";
@@ -229,8 +231,11 @@ export function resolveControlUiLinks(params: {
bind === "tailnet" || (bind === "auto" && tailnetIPv4)
? (tailnetIPv4 ?? "127.0.0.1")
: "127.0.0.1";
const basePath = normalizeControlUiBasePath(params.basePath);
const uiPath = basePath ? `${basePath}/` : "/";
const wsPath = basePath ? basePath : "";
return {
httpUrl: `http://${host}:${port}/`,
wsUrl: `ws://${host}:${port}`,
httpUrl: `http://${host}:${port}${uiPath}`,
wsUrl: `ws://${host}:${port}${wsPath}`,
};
}
+11 -583
View File
@@ -1,594 +1,22 @@
import path from "node:path";
import {
confirm,
intro,
note,
outro,
select,
spinner,
text,
} from "@clack/prompts";
import { loginAnthropic, type OAuthCredentials } from "@mariozechner/pi-ai";
import type { ClawdisConfig } from "../config/config.js";
import {
CONFIG_PATH_CLAWDIS,
readConfigFileSnapshot,
resolveGatewayPort,
writeConfigFile,
} from "../config/config.js";
import { GATEWAY_LAUNCH_AGENT_LABEL } from "../daemon/constants.js";
import { resolveGatewayProgramArguments } from "../daemon/program-args.js";
import { resolveGatewayService } from "../daemon/service.js";
import type { RuntimeEnv } from "../runtime.js";
import { defaultRuntime } from "../runtime.js";
import { resolveUserPath, sleep } from "../utils.js";
import {
isRemoteEnvironment,
loginAntigravityVpsAware,
} from "./antigravity-oauth.js";
import { healthCommand } from "./health.js";
import {
applyMinimaxConfig,
setAnthropicApiKey,
writeOAuthCredentials,
} from "./onboard-auth.js";
import {
applyWizardMetadata,
DEFAULT_WORKSPACE,
ensureWorkspaceAndSessions,
guardCancel,
handleReset,
openUrl,
printWizardHeader,
probeGatewayReachable,
randomToken,
resolveControlUiLinks,
summarizeExistingConfig,
} from "./onboard-helpers.js";
import { setupProviders } from "./onboard-providers.js";
import { promptRemoteGatewayConfig } from "./onboard-remote.js";
import { setupSkills } from "./onboard-skills.js";
import type {
AuthChoice,
GatewayAuthChoice,
OnboardMode,
OnboardOptions,
ResetScope,
} from "./onboard-types.js";
import { createClackPrompter } from "../wizard/clack-prompter.js";
import { runOnboardingWizard } from "../wizard/onboarding.js";
import { WizardCancelledError } from "../wizard/prompts.js";
import type { OnboardOptions } from "./onboard-types.js";
export async function runInteractiveOnboarding(
opts: OnboardOptions,
runtime: RuntimeEnv = defaultRuntime,
) {
printWizardHeader(runtime);
intro("Clawdis onboarding");
const snapshot = await readConfigFileSnapshot();
let baseConfig: ClawdisConfig = snapshot.valid ? snapshot.config : {};
if (snapshot.exists) {
const title = snapshot.valid
? "Existing config detected"
: "Invalid config";
note(summarizeExistingConfig(baseConfig), title);
if (!snapshot.valid && snapshot.issues.length > 0) {
note(
snapshot.issues
.map((iss) => `- ${iss.path}: ${iss.message}`)
.join("\n"),
"Config issues",
);
}
const action = guardCancel(
await select({
message: "Config handling",
options: [
{ value: "keep", label: "Use existing values" },
{ value: "modify", label: "Update values" },
{ value: "reset", label: "Reset" },
],
}),
runtime,
);
if (action === "reset") {
const workspaceDefault = baseConfig.agent?.workspace ?? DEFAULT_WORKSPACE;
const resetScope = guardCancel(
await select({
message: "Reset scope",
options: [
{ value: "config", label: "Config only" },
{
value: "config+creds+sessions",
label: "Config + creds + sessions",
},
{
value: "full",
label: "Full reset (config + creds + sessions + workspace)",
},
],
}),
runtime,
) as ResetScope;
await handleReset(resetScope, resolveUserPath(workspaceDefault), runtime);
baseConfig = {};
} else if (action === "keep" && !snapshot.valid) {
baseConfig = {};
}
}
const localPort = resolveGatewayPort(baseConfig);
const localUrl = `ws://127.0.0.1:${localPort}`;
const localProbe = await probeGatewayReachable({
url: localUrl,
token: process.env.CLAWDIS_GATEWAY_TOKEN,
password:
baseConfig.gateway?.auth?.password ??
process.env.CLAWDIS_GATEWAY_PASSWORD,
});
const remoteUrl = baseConfig.gateway?.remote?.url?.trim() ?? "";
const remoteProbe = remoteUrl
? await probeGatewayReachable({
url: remoteUrl,
token: baseConfig.gateway?.remote?.token,
})
: null;
const mode =
opts.mode ??
(guardCancel(
await select({
message: "Where will the Gateway run?",
options: [
{
value: "local",
label: "Local (this machine)",
hint: localProbe.ok
? `Gateway reachable (${localUrl})`
: `No gateway detected (${localUrl})`,
},
{
value: "remote",
label: "Remote (info-only)",
hint: !remoteUrl
? "No remote URL configured yet"
: remoteProbe?.ok
? `Gateway reachable (${remoteUrl})`
: `Configured but unreachable (${remoteUrl})`,
},
],
}),
runtime,
) as OnboardMode);
if (mode === "remote") {
let nextConfig = await promptRemoteGatewayConfig(baseConfig, runtime);
nextConfig = applyWizardMetadata(nextConfig, { command: "onboard", mode });
await writeConfigFile(nextConfig);
runtime.log(`Updated ${CONFIG_PATH_CLAWDIS}`);
outro("Remote gateway configured.");
return;
}
const workspaceInput =
opts.workspace ??
(guardCancel(
await text({
message: "Workspace directory",
initialValue: baseConfig.agent?.workspace ?? DEFAULT_WORKSPACE,
}),
runtime,
) as string);
const workspaceDir = resolveUserPath(
workspaceInput.trim() || DEFAULT_WORKSPACE,
);
let nextConfig: ClawdisConfig = {
...baseConfig,
agent: {
...baseConfig.agent,
workspace: workspaceDir,
},
gateway: {
...baseConfig.gateway,
mode: "local",
},
};
const authChoice = guardCancel(
await select({
message: "Model/auth choice",
options: [
{ value: "oauth", label: "Anthropic OAuth (Claude Pro/Max)" },
{
value: "antigravity",
label: "Google Antigravity (Claude Opus 4.5, Gemini 3, etc.)",
},
{ value: "apiKey", label: "Anthropic API key" },
{ value: "minimax", label: "Minimax M2.1 (LM Studio)" },
{ value: "skip", label: "Skip for now" },
],
}),
runtime,
) as AuthChoice;
if (authChoice === "oauth") {
note(
"Browser will open. Paste the code shown after login (code#state).",
"Anthropic OAuth",
);
const spin = spinner();
spin.start("Waiting for authorization…");
let oauthCreds: OAuthCredentials | null = null;
try {
oauthCreds = await loginAnthropic(
async (url) => {
await openUrl(url);
runtime.log(`Open: ${url}`);
},
async () => {
const code = guardCancel(
await text({
message: "Paste authorization code (code#state)",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
);
return String(code);
},
);
spin.stop("OAuth complete");
if (oauthCreds) {
await writeOAuthCredentials("anthropic", oauthCreds);
}
} catch (err) {
spin.stop("OAuth failed");
runtime.error(String(err));
}
} else if (authChoice === "antigravity") {
const isRemote = isRemoteEnvironment();
note(
isRemote
? [
"You are running in a remote/VPS environment.",
"A URL will be shown for you to open in your LOCAL browser.",
"After signing in, copy the redirect URL and paste it back here.",
].join("\n")
: [
"Browser will open for Google authentication.",
"Sign in with your Google account that has Antigravity access.",
"The callback will be captured automatically on localhost:51121.",
].join("\n"),
"Google Antigravity OAuth",
);
const spin = spinner();
spin.start("Starting OAuth flow…");
let oauthCreds: OAuthCredentials | null = null;
try {
oauthCreds = await loginAntigravityVpsAware(
async (url) => {
if (isRemote) {
spin.stop("OAuth URL ready");
runtime.log(`\nOpen this URL in your LOCAL browser:\n\n${url}\n`);
} else {
spin.message("Complete sign-in in browser…");
await openUrl(url);
runtime.log(`Open: ${url}`);
}
},
(msg) => spin.message(msg),
);
spin.stop("Antigravity OAuth complete");
if (oauthCreds) {
await writeOAuthCredentials("google-antigravity", oauthCreds);
// Set default model to Claude Opus 4.5 via Antigravity
nextConfig = {
...nextConfig,
agent: {
...nextConfig.agent,
model: "google-antigravity/claude-opus-4-5-thinking",
},
};
note(
"Default model set to google-antigravity/claude-opus-4-5-thinking",
"Model configured",
);
}
} catch (err) {
spin.stop("Antigravity OAuth failed");
runtime.error(String(err));
}
} else if (authChoice === "apiKey") {
const key = guardCancel(
await text({
message: "Enter Anthropic API key",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
);
await setAnthropicApiKey(String(key).trim());
} else if (authChoice === "minimax") {
nextConfig = applyMinimaxConfig(nextConfig);
}
const portRaw = guardCancel(
await text({
message: "Gateway port",
initialValue: String(localPort),
validate: (value) =>
Number.isFinite(Number(value)) ? undefined : "Invalid port",
}),
runtime,
);
const port = Number.parseInt(String(portRaw), 10);
let bind = guardCancel(
await select({
message: "Gateway bind",
options: [
{ value: "loopback", label: "Loopback (127.0.0.1)" },
{ value: "lan", label: "LAN" },
{ value: "tailnet", label: "Tailnet" },
{ value: "auto", label: "Auto" },
],
}),
runtime,
) as "loopback" | "lan" | "tailnet" | "auto";
let authMode = guardCancel(
await select({
message: "Gateway auth",
options: [
{
value: "off",
label: "Off (loopback only)",
hint: "Recommended for single-machine setups",
},
{
value: "token",
label: "Token",
hint: "Use for multi-machine access or non-loopback binds",
},
{ value: "password", label: "Password" },
],
}),
runtime,
) as GatewayAuthChoice;
const tailscaleMode = guardCancel(
await select({
message: "Tailscale exposure",
options: [
{ value: "off", label: "Off", hint: "No Tailscale exposure" },
{
value: "serve",
label: "Serve",
hint: "Private HTTPS for your tailnet (devices on Tailscale)",
},
{
value: "funnel",
label: "Funnel",
hint: "Public HTTPS via Tailscale Funnel (internet)",
},
],
}),
runtime,
) as "off" | "serve" | "funnel";
let tailscaleResetOnExit = false;
if (tailscaleMode !== "off") {
tailscaleResetOnExit = Boolean(
guardCancel(
await confirm({
message: "Reset Tailscale serve/funnel on exit?",
initialValue: false,
}),
runtime,
),
);
}
if (tailscaleMode !== "off" && bind !== "loopback") {
note(
"Tailscale requires bind=loopback. Adjusting bind to loopback.",
"Note",
);
bind = "loopback";
}
if (authMode === "off" && bind !== "loopback") {
note("Non-loopback bind requires auth. Switching to token auth.", "Note");
authMode = "token";
}
if (tailscaleMode === "funnel" && authMode !== "password") {
note("Tailscale funnel requires password auth.", "Note");
authMode = "password";
}
let gatewayToken: string | undefined;
if (authMode === "token") {
const tokenInput = guardCancel(
await text({
message: "Gateway token (blank to generate)",
placeholder: "Needed for multi-machine or non-loopback access",
initialValue: randomToken(),
}),
runtime,
);
gatewayToken = String(tokenInput).trim() || randomToken();
}
if (authMode === "password") {
const password = guardCancel(
await text({
message: "Gateway password",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
);
nextConfig = {
...nextConfig,
gateway: {
...nextConfig.gateway,
auth: {
...nextConfig.gateway?.auth,
mode: "password",
password: String(password).trim(),
},
},
};
} else if (authMode === "token") {
nextConfig = {
...nextConfig,
gateway: {
...nextConfig.gateway,
auth: {
...nextConfig.gateway?.auth,
mode: "token",
token: gatewayToken,
},
},
};
}
nextConfig = {
...nextConfig,
gateway: {
...nextConfig.gateway,
port,
bind,
tailscale: {
...nextConfig.gateway?.tailscale,
mode: tailscaleMode,
resetOnExit: tailscaleResetOnExit,
},
},
};
nextConfig = await setupProviders(nextConfig, runtime, {
allowSignalInstall: true,
});
await writeConfigFile(nextConfig);
runtime.log(`Updated ${CONFIG_PATH_CLAWDIS}`);
await ensureWorkspaceAndSessions(workspaceDir, runtime);
nextConfig = await setupSkills(nextConfig, workspaceDir, runtime);
nextConfig = applyWizardMetadata(nextConfig, { command: "onboard", mode });
await writeConfigFile(nextConfig);
const installDaemon = guardCancel(
await confirm({
message: "Install Gateway daemon (recommended)",
initialValue: true,
}),
runtime,
);
if (installDaemon) {
const service = resolveGatewayService();
const loaded = await service.isLoaded({ env: process.env });
if (loaded) {
const action = guardCancel(
await select({
message: "Gateway service already installed",
options: [
{ value: "restart", label: "Restart" },
{ value: "reinstall", label: "Reinstall" },
{ value: "skip", label: "Skip" },
],
}),
runtime,
);
if (action === "restart") {
await service.restart({ stdout: process.stdout });
} else if (action === "reinstall") {
await service.uninstall({ env: process.env, stdout: process.stdout });
}
}
if (
!loaded ||
(loaded && (await service.isLoaded({ env: process.env })) === false)
) {
const devMode =
process.argv[1]?.includes(`${path.sep}src${path.sep}`) &&
process.argv[1]?.endsWith(".ts");
const { programArguments, workingDirectory } =
await resolveGatewayProgramArguments({ port, dev: devMode });
const environment: Record<string, string | undefined> = {
PATH: process.env.PATH,
CLAWDIS_GATEWAY_TOKEN: gatewayToken,
CLAWDIS_LAUNCHD_LABEL:
process.platform === "darwin"
? GATEWAY_LAUNCH_AGENT_LABEL
: undefined,
};
await service.install({
env: process.env,
stdout: process.stdout,
programArguments,
workingDirectory,
environment,
});
}
}
await sleep(1500);
const prompter = createClackPrompter();
try {
await healthCommand({ json: false, timeoutMs: 10_000 }, runtime);
await runOnboardingWizard(opts, runtime, prompter);
} catch (err) {
runtime.error(`Health check failed: ${String(err)}`);
if (err instanceof WizardCancelledError) {
runtime.exit(0);
return;
}
throw err;
}
note(
[
"Add nodes for extra features:",
"- macOS app (system + notifications)",
"- iOS app (camera/canvas)",
"- Android app (camera/canvas)",
].join("\n"),
"Optional apps",
);
note(
(() => {
const links = resolveControlUiLinks({ bind, port });
const tokenParam =
authMode === "token" && gatewayToken
? `?token=${encodeURIComponent(gatewayToken)}`
: "";
const authedUrl = `${links.httpUrl}${tokenParam}`;
return [
`Web UI: ${links.httpUrl}`,
tokenParam ? `Web UI (with token): ${authedUrl}` : undefined,
`Gateway WS: ${links.wsUrl}`,
]
.filter(Boolean)
.join("\n");
})(),
"Control UI",
);
const wantsOpen = guardCancel(
await confirm({
message: "Open Control UI now?",
initialValue: true,
}),
runtime,
);
if (wantsOpen) {
const links = resolveControlUiLinks({ bind, port });
const tokenParam =
authMode === "token" && gatewayToken
? `?token=${encodeURIComponent(gatewayToken)}`
: "";
await openUrl(`${links.httpUrl}${tokenParam}`);
}
outro("Onboarding complete.");
}
+186 -263
View File
@@ -1,15 +1,12 @@
import fs from "node:fs/promises";
import path from "node:path";
import { confirm, multiselect, note, select, text } from "@clack/prompts";
import chalk from "chalk";
import type { ClawdisConfig } from "../config/config.js";
import { loginWeb } from "../provider-web.js";
import type { RuntimeEnv } from "../runtime.js";
import { normalizeE164 } from "../utils.js";
import { resolveWebAuthDir } from "../web/session.js";
import { detectBinary, guardCancel } from "./onboard-helpers.js";
import type { WizardPrompter } from "../wizard/prompts.js";
import { detectBinary } from "./onboard-helpers.js";
import type { ProviderChoice } from "./onboard-types.js";
import { installSignalCli } from "./signal-install.js";
@@ -27,8 +24,8 @@ async function detectWhatsAppLinked(): Promise<boolean> {
return await pathExists(credsPath);
}
function noteProviderPrimer(): void {
note(
async function noteProviderPrimer(prompter: WizardPrompter): Promise<void> {
await prompter.note(
[
"WhatsApp: links via WhatsApp Web (scan QR), stores creds for future sends.",
"Telegram: Bot API (token from @BotFather), replies via your bot.",
@@ -40,8 +37,8 @@ function noteProviderPrimer(): void {
);
}
function noteTelegramTokenHelp(): void {
note(
async function noteTelegramTokenHelp(prompter: WizardPrompter): Promise<void> {
await prompter.note(
[
"1) Open Telegram and chat with @BotFather",
"2) Run /newbot (or /mybots)",
@@ -52,8 +49,8 @@ function noteTelegramTokenHelp(): void {
);
}
function noteDiscordTokenHelp(): void {
note(
async function noteDiscordTokenHelp(prompter: WizardPrompter): Promise<void> {
await prompter.note(
[
"1) Discord Developer Portal → Applications → New Application",
"2) Bot → Add Bot → Reset Token → copy token",
@@ -76,13 +73,14 @@ function setWhatsAppAllowFrom(cfg: ClawdisConfig, allowFrom?: string[]) {
async function promptWhatsAppAllowFrom(
cfg: ClawdisConfig,
runtime: RuntimeEnv,
_runtime: RuntimeEnv,
prompter: WizardPrompter,
): Promise<ClawdisConfig> {
const existingAllowFrom = cfg.whatsapp?.allowFrom ?? [];
const existingLabel =
existingAllowFrom.length > 0 ? existingAllowFrom.join(", ") : "unset";
note(
await prompter.note(
[
"WhatsApp direct chats are gated by `whatsapp.allowFrom`.",
'Default (unset) = self-chat only; use "*" to allow anyone.',
@@ -105,40 +103,34 @@ async function promptWhatsAppAllowFrom(
{ value: "any", label: "Anyone (*)" },
] as const);
const mode = guardCancel(
await select({
message: "Who can trigger the bot via WhatsApp?",
options: options.map((opt) => ({ value: opt.value, label: opt.label })),
}),
runtime,
) as (typeof options)[number]["value"];
const mode = (await prompter.select({
message: "Who can trigger the bot via WhatsApp?",
options: options.map((opt) => ({ value: opt.value, label: opt.label })),
})) as (typeof options)[number]["value"];
if (mode === "keep") return cfg;
if (mode === "self") return setWhatsAppAllowFrom(cfg, undefined);
if (mode === "any") return setWhatsAppAllowFrom(cfg, ["*"]);
const allowRaw = guardCancel(
await text({
message: "Allowed sender numbers (comma-separated, E.164)",
placeholder: "+15555550123, +447700900123",
validate: (value) => {
const raw = String(value ?? "").trim();
if (!raw) return "Required";
const parts = raw
.split(/[\n,;]+/g)
.map((p) => p.trim())
.filter(Boolean);
if (parts.length === 0) return "Required";
for (const part of parts) {
if (part === "*") continue;
const normalized = normalizeE164(part);
if (!normalized) return `Invalid number: ${part}`;
}
return undefined;
},
}),
runtime,
);
const allowRaw = await prompter.text({
message: "Allowed sender numbers (comma-separated, E.164)",
placeholder: "+15555550123, +447700900123",
validate: (value) => {
const raw = String(value ?? "").trim();
if (!raw) return "Required";
const parts = raw
.split(/[\n,;]+/g)
.map((p) => p.trim())
.filter(Boolean);
if (parts.length === 0) return "Required";
for (const part of parts) {
if (part === "*") continue;
const normalized = normalizeE164(part);
if (!normalized) return `Invalid number: ${part}`;
}
return undefined;
},
});
const parts = String(allowRaw)
.split(/[\n,;]+/g)
@@ -154,6 +146,7 @@ async function promptWhatsAppAllowFrom(
export async function setupProviders(
cfg: ClawdisConfig,
runtime: RuntimeEnv,
prompter: WizardPrompter,
options?: { allowDisable?: boolean; allowSignalInstall?: boolean },
): Promise<ClawdisConfig> {
const whatsappLinked = await detectWhatsAppLinked();
@@ -174,91 +167,63 @@ export async function setupProviders(
const imessageCliPath = cfg.imessage?.cliPath ?? "imsg";
const imessageCliDetected = await detectBinary(imessageCliPath);
note(
await prompter.note(
[
`WhatsApp: ${
whatsappLinked ? chalk.green("linked") : chalk.red("not linked")
}`,
`Telegram: ${
telegramConfigured
? chalk.green("configured")
: chalk.yellow("needs token")
}`,
`Discord: ${
discordConfigured
? chalk.green("configured")
: chalk.yellow("needs token")
}`,
`Signal: ${
signalConfigured
? chalk.green("configured")
: chalk.yellow("needs setup")
}`,
`iMessage: ${
imessageConfigured
? chalk.green("configured")
: chalk.yellow("needs setup")
}`,
`signal-cli: ${
signalCliDetected ? chalk.green("found") : chalk.red("missing")
} (${signalCliPath})`,
`imsg: ${
imessageCliDetected ? chalk.green("found") : chalk.red("missing")
} (${imessageCliPath})`,
`WhatsApp: ${whatsappLinked ? "linked" : "not linked"}`,
`Telegram: ${telegramConfigured ? "configured" : "needs token"}`,
`Discord: ${discordConfigured ? "configured" : "needs token"}`,
`Signal: ${signalConfigured ? "configured" : "needs setup"}`,
`iMessage: ${imessageConfigured ? "configured" : "needs setup"}`,
`signal-cli: ${signalCliDetected ? "found" : "missing"} (${signalCliPath})`,
`imsg: ${imessageCliDetected ? "found" : "missing"} (${imessageCliPath})`,
].join("\n"),
"Provider status",
);
const shouldConfigure = guardCancel(
await confirm({
message: "Configure chat providers now?",
initialValue: true,
}),
runtime,
);
const shouldConfigure = await prompter.confirm({
message: "Configure chat providers now?",
initialValue: true,
});
if (!shouldConfigure) return cfg;
noteProviderPrimer();
await noteProviderPrimer(prompter);
const selection = guardCancel(
await multiselect({
message: "Select providers",
options: [
{
value: "whatsapp",
label: "WhatsApp (QR link)",
hint: whatsappLinked ? "linked" : "not linked",
},
{
value: "telegram",
label: "Telegram (Bot API)",
hint: telegramConfigured ? "configured" : "needs token",
},
{
value: "discord",
label: "Discord (Bot API)",
hint: discordConfigured ? "configured" : "needs token",
},
{
value: "signal",
label: "Signal (signal-cli)",
hint: signalCliDetected ? "signal-cli found" : "signal-cli missing",
},
{
value: "imessage",
label: "iMessage (imsg)",
hint: imessageCliDetected ? "imsg found" : "imsg missing",
},
],
}),
runtime,
) as ProviderChoice[];
const selection = (await prompter.multiselect({
message: "Select providers",
options: [
{
value: "whatsapp",
label: "WhatsApp (QR link)",
hint: whatsappLinked ? "linked" : "not linked",
},
{
value: "telegram",
label: "Telegram (Bot API)",
hint: telegramConfigured ? "configured" : "needs token",
},
{
value: "discord",
label: "Discord (Bot API)",
hint: discordConfigured ? "configured" : "needs token",
},
{
value: "signal",
label: "Signal (signal-cli)",
hint: signalCliDetected ? "signal-cli found" : "signal-cli missing",
},
{
value: "imessage",
label: "iMessage (imsg)",
hint: imessageCliDetected ? "imsg found" : "imsg missing",
},
],
})) as ProviderChoice[];
let next = cfg;
if (selection.includes("whatsapp")) {
if (!whatsappLinked) {
note(
await prompter.note(
[
"Scan the QR with WhatsApp on your phone.",
"Credentials are stored under ~/.clawdis/credentials/ for future runs.",
@@ -266,15 +231,12 @@ export async function setupProviders(
"WhatsApp linking",
);
}
const wantsLink = guardCancel(
await confirm({
message: whatsappLinked
? "WhatsApp already linked. Re-link now?"
: "Link WhatsApp now (QR)?",
initialValue: !whatsappLinked,
}),
runtime,
);
const wantsLink = await prompter.confirm({
message: whatsappLinked
? "WhatsApp already linked. Re-link now?"
: "Link WhatsApp now (QR)?",
initialValue: !whatsappLinked,
});
if (wantsLink) {
try {
await loginWeb(false, "web");
@@ -282,25 +244,25 @@ export async function setupProviders(
runtime.error(`WhatsApp login failed: ${String(err)}`);
}
} else if (!whatsappLinked) {
note("Run `clawdis login` later to link WhatsApp.", "WhatsApp");
await prompter.note(
"Run `clawdis login` later to link WhatsApp.",
"WhatsApp",
);
}
next = await promptWhatsAppAllowFrom(next, runtime);
next = await promptWhatsAppAllowFrom(next, runtime, prompter);
}
if (selection.includes("telegram")) {
let token: string | null = null;
if (!telegramConfigured) {
noteTelegramTokenHelp();
await noteTelegramTokenHelp(prompter);
}
if (telegramEnv && !cfg.telegram?.botToken) {
const keepEnv = guardCancel(
await confirm({
message: "TELEGRAM_BOT_TOKEN detected. Use env var?",
initialValue: true,
}),
runtime,
);
const keepEnv = await prompter.confirm({
message: "TELEGRAM_BOT_TOKEN detected. Use env var?",
initialValue: true,
});
if (keepEnv) {
next = {
...next,
@@ -311,43 +273,31 @@ export async function setupProviders(
};
} else {
token = String(
guardCancel(
await text({
message: "Enter Telegram bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
),
await prompter.text({
message: "Enter Telegram bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
).trim();
}
} else if (cfg.telegram?.botToken) {
const keep = guardCancel(
await confirm({
message: "Telegram token already configured. Keep it?",
initialValue: true,
}),
runtime,
);
const keep = await prompter.confirm({
message: "Telegram token already configured. Keep it?",
initialValue: true,
});
if (!keep) {
token = String(
guardCancel(
await text({
message: "Enter Telegram bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
),
await prompter.text({
message: "Enter Telegram bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
).trim();
}
} else {
token = String(
guardCancel(
await text({
message: "Enter Telegram bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
),
await prompter.text({
message: "Enter Telegram bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
).trim();
}
@@ -366,16 +316,13 @@ export async function setupProviders(
if (selection.includes("discord")) {
let token: string | null = null;
if (!discordConfigured) {
noteDiscordTokenHelp();
await noteDiscordTokenHelp(prompter);
}
if (discordEnv && !cfg.discord?.token) {
const keepEnv = guardCancel(
await confirm({
message: "DISCORD_BOT_TOKEN detected. Use env var?",
initialValue: true,
}),
runtime,
);
const keepEnv = await prompter.confirm({
message: "DISCORD_BOT_TOKEN detected. Use env var?",
initialValue: true,
});
if (keepEnv) {
next = {
...next,
@@ -386,43 +333,31 @@ export async function setupProviders(
};
} else {
token = String(
guardCancel(
await text({
message: "Enter Discord bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
),
await prompter.text({
message: "Enter Discord bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
).trim();
}
} else if (cfg.discord?.token) {
const keep = guardCancel(
await confirm({
message: "Discord token already configured. Keep it?",
initialValue: true,
}),
runtime,
);
const keep = await prompter.confirm({
message: "Discord token already configured. Keep it?",
initialValue: true,
});
if (!keep) {
token = String(
guardCancel(
await text({
message: "Enter Discord bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
),
await prompter.text({
message: "Enter Discord bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
).trim();
}
} else {
token = String(
guardCancel(
await text({
message: "Enter Discord bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
),
await prompter.text({
message: "Enter Discord bot token",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
).trim();
}
@@ -442,33 +377,39 @@ export async function setupProviders(
let resolvedCliPath = signalCliPath;
let cliDetected = signalCliDetected;
if (options?.allowSignalInstall) {
const wantsInstall = guardCancel(
await confirm({
message: cliDetected
? "signal-cli detected. Reinstall/update now?"
: "signal-cli not found. Install now?",
initialValue: !cliDetected,
}),
runtime,
);
const wantsInstall = await prompter.confirm({
message: cliDetected
? "signal-cli detected. Reinstall/update now?"
: "signal-cli not found. Install now?",
initialValue: !cliDetected,
});
if (wantsInstall) {
try {
const result = await installSignalCli(runtime);
if (result.ok && result.cliPath) {
cliDetected = true;
resolvedCliPath = result.cliPath;
note(`Installed signal-cli at ${result.cliPath}`, "Signal");
await prompter.note(
`Installed signal-cli at ${result.cliPath}`,
"Signal",
);
} else if (!result.ok) {
note(result.error ?? "signal-cli install failed.", "Signal");
await prompter.note(
result.error ?? "signal-cli install failed.",
"Signal",
);
}
} catch (err) {
note(`signal-cli install failed: ${String(err)}`, "Signal");
await prompter.note(
`signal-cli install failed: ${String(err)}`,
"Signal",
);
}
}
}
if (!cliDetected) {
note(
await prompter.note(
"signal-cli not found. Install it, then rerun this step or set signal.cliPath.",
"Signal",
);
@@ -476,25 +417,19 @@ export async function setupProviders(
let account = cfg.signal?.account ?? "";
if (account) {
const keep = guardCancel(
await confirm({
message: `Signal account set (${account}). Keep it?`,
initialValue: true,
}),
runtime,
);
const keep = await prompter.confirm({
message: `Signal account set (${account}). Keep it?`,
initialValue: true,
});
if (!keep) account = "";
}
if (!account) {
account = String(
guardCancel(
await text({
message: "Signal bot number (E.164)",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
),
await prompter.text({
message: "Signal bot number (E.164)",
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
).trim();
}
@@ -510,7 +445,7 @@ export async function setupProviders(
};
}
note(
await prompter.note(
[
'Link device with: signal-cli link -n "Clawdis"',
"Scan QR in Signal → Linked Devices",
@@ -523,17 +458,17 @@ export async function setupProviders(
if (selection.includes("imessage")) {
let resolvedCliPath = imessageCliPath;
if (!imessageCliDetected) {
const entered = guardCancel(
await text({
message: "imsg CLI path",
initialValue: resolvedCliPath,
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
);
const entered = await prompter.text({
message: "imsg CLI path",
initialValue: resolvedCliPath,
validate: (value) => (value?.trim() ? undefined : "Required"),
});
resolvedCliPath = String(entered).trim();
if (!resolvedCliPath) {
note("imsg CLI path required to enable iMessage.", "iMessage");
await prompter.note(
"imsg CLI path required to enable iMessage.",
"iMessage",
);
}
}
@@ -548,7 +483,7 @@ export async function setupProviders(
};
}
note(
await prompter.note(
[
"Ensure Clawdis has Full Disk Access to Messages DB.",
"Grant Automation permission for Messages when prompted.",
@@ -560,13 +495,10 @@ export async function setupProviders(
if (options?.allowDisable) {
if (!selection.includes("telegram") && telegramConfigured) {
const disable = guardCancel(
await confirm({
message: "Disable Telegram provider?",
initialValue: false,
}),
runtime,
);
const disable = await prompter.confirm({
message: "Disable Telegram provider?",
initialValue: false,
});
if (disable) {
next = {
...next,
@@ -576,13 +508,10 @@ export async function setupProviders(
}
if (!selection.includes("discord") && discordConfigured) {
const disable = guardCancel(
await confirm({
message: "Disable Discord provider?",
initialValue: false,
}),
runtime,
);
const disable = await prompter.confirm({
message: "Disable Discord provider?",
initialValue: false,
});
if (disable) {
next = {
...next,
@@ -592,13 +521,10 @@ export async function setupProviders(
}
if (!selection.includes("signal") && signalConfigured) {
const disable = guardCancel(
await confirm({
message: "Disable Signal provider?",
initialValue: false,
}),
runtime,
);
const disable = await prompter.confirm({
message: "Disable Signal provider?",
initialValue: false,
});
if (disable) {
next = {
...next,
@@ -608,13 +534,10 @@ export async function setupProviders(
}
if (!selection.includes("imessage") && imessageConfigured) {
const disable = guardCancel(
await confirm({
message: "Disable iMessage provider?",
initialValue: false,
}),
runtime,
);
const disable = await prompter.confirm({
message: "Disable iMessage provider?",
initialValue: false,
});
if (disable) {
next = {
...next,
+51 -72
View File
@@ -1,10 +1,8 @@
import { confirm, note, select, spinner, text } from "@clack/prompts";
import type { ClawdisConfig } from "../config/config.js";
import type { GatewayBonjourBeacon } from "../infra/bonjour-discovery.js";
import { discoverGatewayBeacons } from "../infra/bonjour-discovery.js";
import type { RuntimeEnv } from "../runtime.js";
import { detectBinary, guardCancel } from "./onboard-helpers.js";
import type { WizardPrompter } from "../wizard/prompts.js";
import { detectBinary } from "./onboard-helpers.js";
const DEFAULT_GATEWAY_URL = "ws://127.0.0.1:18789";
@@ -28,7 +26,7 @@ function ensureWsUrl(value: string): string {
export async function promptRemoteGatewayConfig(
cfg: ClawdisConfig,
runtime: RuntimeEnv,
prompter: WizardPrompter,
): Promise<ClawdisConfig> {
let selectedBeacon: GatewayBonjourBeacon | null = null;
let suggestedUrl = cfg.gateway?.remote?.url ?? DEFAULT_GATEWAY_URL;
@@ -36,25 +34,21 @@ export async function promptRemoteGatewayConfig(
const hasBonjourTool =
(await detectBinary("dns-sd")) || (await detectBinary("avahi-browse"));
const wantsDiscover = hasBonjourTool
? guardCancel(
await confirm({
message: "Discover gateway on LAN (Bonjour)?",
initialValue: true,
}),
runtime,
)
? await prompter.confirm({
message: "Discover gateway on LAN (Bonjour)?",
initialValue: true,
})
: false;
if (!hasBonjourTool) {
note(
await prompter.note(
"Bonjour discovery requires dns-sd (macOS) or avahi-browse (Linux).",
"Discovery",
);
}
if (wantsDiscover) {
const spin = spinner();
spin.start("Searching for gateways…");
const spin = prompter.progress("Searching for gateways…");
const beacons = await discoverGatewayBeacons({ timeoutMs: 2000 });
spin.stop(
beacons.length > 0
@@ -63,19 +57,16 @@ export async function promptRemoteGatewayConfig(
);
if (beacons.length > 0) {
const selection = guardCancel(
await select({
message: "Select gateway",
options: [
...beacons.map((beacon, index) => ({
value: String(index),
label: buildLabel(beacon),
})),
{ value: "manual", label: "Enter URL manually" },
],
}),
runtime,
);
const selection = await prompter.select({
message: "Select gateway",
options: [
...beacons.map((beacon, index) => ({
value: String(index),
label: buildLabel(beacon),
})),
{ value: "manual", label: "Enter URL manually" },
],
});
if (selection !== "manual") {
const idx = Number.parseInt(String(selection), 10);
selectedBeacon = Number.isFinite(idx) ? (beacons[idx] ?? null) : null;
@@ -87,24 +78,21 @@ export async function promptRemoteGatewayConfig(
const host = pickHost(selectedBeacon);
const port = selectedBeacon.gatewayPort ?? 18789;
if (host) {
const mode = guardCancel(
await select({
message: "Connection method",
options: [
{
value: "direct",
label: `Direct gateway WS (${host}:${port})`,
},
{ value: "ssh", label: "SSH tunnel (loopback)" },
],
}),
runtime,
);
const mode = await prompter.select({
message: "Connection method",
options: [
{
value: "direct",
label: `Direct gateway WS (${host}:${port})`,
},
{ value: "ssh", label: "SSH tunnel (loopback)" },
],
});
if (mode === "direct") {
suggestedUrl = `ws://${host}:${port}`;
} else {
suggestedUrl = DEFAULT_GATEWAY_URL;
note(
await prompter.note(
[
"Start a tunnel before using the CLI:",
`ssh -N -L 18789:127.0.0.1:18789 <user>@${host}${
@@ -117,42 +105,33 @@ export async function promptRemoteGatewayConfig(
}
}
const urlInput = guardCancel(
await text({
message: "Gateway WebSocket URL",
initialValue: suggestedUrl,
validate: (value) =>
String(value).trim().startsWith("ws://") ||
String(value).trim().startsWith("wss://")
? undefined
: "URL must start with ws:// or wss://",
}),
runtime,
);
const urlInput = await prompter.text({
message: "Gateway WebSocket URL",
initialValue: suggestedUrl,
validate: (value) =>
String(value).trim().startsWith("ws://") ||
String(value).trim().startsWith("wss://")
? undefined
: "URL must start with ws:// or wss://",
});
const url = ensureWsUrl(String(urlInput));
const authChoice = guardCancel(
await select({
message: "Gateway auth",
options: [
{ value: "token", label: "Token (recommended)" },
{ value: "off", label: "No auth" },
],
}),
runtime,
) as "token" | "off";
const authChoice = (await prompter.select({
message: "Gateway auth",
options: [
{ value: "token", label: "Token (recommended)" },
{ value: "off", label: "No auth" },
],
})) as "token" | "off";
let token = cfg.gateway?.remote?.token ?? "";
if (authChoice === "token") {
token = String(
guardCancel(
await text({
message: "Gateway token",
initialValue: token,
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
),
await prompter.text({
message: "Gateway token",
initialValue: token,
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
).trim();
} else {
token = "";
+36 -59
View File
@@ -1,17 +1,9 @@
import {
confirm,
multiselect,
note,
select,
spinner,
text,
} from "@clack/prompts";
import { installSkill } from "../agents/skills-install.js";
import { buildWorkspaceSkillStatus } from "../agents/skills-status.js";
import type { ClawdisConfig } from "../config/config.js";
import type { RuntimeEnv } from "../runtime.js";
import { guardCancel, resolveNodeManagerOptions } from "./onboard-helpers.js";
import type { WizardPrompter } from "../wizard/prompts.js";
import { resolveNodeManagerOptions } from "./onboard-helpers.js";
function summarizeInstallFailure(message: string): string | undefined {
const cleaned = message
@@ -58,6 +50,7 @@ export async function setupSkills(
cfg: ClawdisConfig,
workspaceDir: string,
runtime: RuntimeEnv,
prompter: WizardPrompter,
): Promise<ClawdisConfig> {
const report = buildWorkspaceSkillStatus(workspaceDir, { config: cfg });
const eligible = report.skills.filter((s) => s.eligible);
@@ -66,7 +59,7 @@ export async function setupSkills(
);
const blocked = report.skills.filter((s) => s.blockedByAllowlist);
note(
await prompter.note(
[
`Eligible: ${eligible.length}`,
`Missing requirements: ${missing.length}`,
@@ -75,22 +68,16 @@ export async function setupSkills(
"Skills status",
);
const shouldConfigure = guardCancel(
await confirm({
message: "Configure skills now? (recommended)",
initialValue: true,
}),
runtime,
);
const shouldConfigure = await prompter.confirm({
message: "Configure skills now? (recommended)",
initialValue: true,
});
if (!shouldConfigure) return cfg;
const nodeManager = guardCancel(
await select({
message: "Preferred node manager for skill installs",
options: resolveNodeManagerOptions(),
}),
runtime,
) as "npm" | "pnpm" | "bun";
const nodeManager = (await prompter.select({
message: "Preferred node manager for skill installs",
options: resolveNodeManagerOptions(),
})) as "npm" | "pnpm" | "bun";
let next: ClawdisConfig = {
...cfg,
@@ -107,24 +94,21 @@ export async function setupSkills(
(skill) => skill.install.length > 0 && skill.missing.bins.length > 0,
);
if (installable.length > 0) {
const toInstall = guardCancel(
await multiselect({
message: "Install missing skill dependencies",
options: [
{
value: "__skip__",
label: "Skip for now",
hint: "Continue without installing dependencies",
},
...installable.map((skill) => ({
value: skill.name,
label: `${skill.emoji ?? "🧩"} ${skill.name}`,
hint: formatSkillHint(skill),
})),
],
}),
runtime,
);
const toInstall = await prompter.multiselect({
message: "Install missing skill dependencies",
options: [
{
value: "__skip__",
label: "Skip for now",
hint: "Continue without installing dependencies",
},
...installable.map((skill) => ({
value: skill.name,
label: `${skill.emoji ?? "🧩"} ${skill.name}`,
hint: formatSkillHint(skill),
})),
],
});
const selected = (toInstall as string[]).filter(
(name) => name !== "__skip__",
@@ -134,8 +118,7 @@ export async function setupSkills(
if (!target || target.install.length === 0) continue;
const installId = target.install[0]?.id;
if (!installId) continue;
const spin = spinner();
spin.start(`Installing ${name}…`);
const spin = prompter.progress(`Installing ${name}…`);
const result = await installSkill({
workspaceDir,
skillName: target.name,
@@ -161,22 +144,16 @@ export async function setupSkills(
for (const skill of missing) {
if (!skill.primaryEnv || skill.missing.env.length === 0) continue;
const wantsKey = guardCancel(
await confirm({
message: `Set ${skill.primaryEnv} for ${skill.name}?`,
initialValue: false,
}),
runtime,
);
const wantsKey = await prompter.confirm({
message: `Set ${skill.primaryEnv} for ${skill.name}?`,
initialValue: false,
});
if (!wantsKey) continue;
const apiKey = String(
guardCancel(
await text({
message: `Enter ${skill.primaryEnv}`,
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
runtime,
),
await prompter.text({
message: `Enter ${skill.primaryEnv}`,
validate: (value) => (value?.trim() ? undefined : "Required"),
}),
);
next = upsertSkillEntry(next, skill.skillKey, { apiKey: apiKey.trim() });
}
+35 -2
View File
@@ -203,9 +203,17 @@ export type DiscordGuildChannelConfig = {
requireMention?: boolean;
};
export type DiscordReactionNotificationMode =
| "off"
| "own"
| "all"
| "allowlist";
export type DiscordGuildEntry = {
slug?: string;
requireMention?: boolean;
/** Reaction notification mode (off|own|all|allowlist). Default: own. */
reactionNotifications?: DiscordReactionNotificationMode;
users?: Array<string | number>;
channels?: Record<string, DiscordGuildChannelConfig>;
};
@@ -402,8 +410,10 @@ export type TalkConfig = {
};
export type GatewayControlUiConfig = {
/** If false, the Gateway will not serve the Control UI (/). Default: true. */
/** If false, the Gateway will not serve the Control UI (default /). */
enabled?: boolean;
/** Optional base path prefix for the Control UI (e.g. "/clawdis"). */
basePath?: string;
};
export type GatewayAuthMode = "token" | "password";
@@ -573,6 +583,12 @@ export type ClawdisConfig = {
* - "message_end": end of the whole assistant message (may include tool blocks)
*/
blockStreamingBreak?: "text_end" | "message_end";
/** Soft block chunking for streamed replies (min/max chars, prefer paragraph/newline). */
blockStreamingChunk?: {
minChars?: number;
maxChars?: number;
breakPreference?: "paragraph" | "newline" | "sentence";
};
timeoutSeconds?: number;
/** Max inbound media size in MB for agent-visible attachments (text note or future image attach). */
mediaMaxMb?: number;
@@ -900,7 +916,7 @@ const HooksGmailSchema = z
})
.optional();
const ClawdisSchema = z.object({
export const ClawdisSchema = z.object({
identity: z
.object({
name: z.string().optional(),
@@ -990,6 +1006,19 @@ const ClawdisSchema = z.object({
blockStreamingBreak: z
.union([z.literal("text_end"), z.literal("message_end")])
.optional(),
blockStreamingChunk: z
.object({
minChars: z.number().int().positive().optional(),
maxChars: z.number().int().positive().optional(),
breakPreference: z
.union([
z.literal("paragraph"),
z.literal("newline"),
z.literal("sentence"),
])
.optional(),
})
.optional(),
timeoutSeconds: z.number().int().positive().optional(),
mediaMaxMb: z.number().positive().optional(),
typingIntervalSeconds: z.number().int().positive().optional(),
@@ -1132,6 +1161,9 @@ const ClawdisSchema = z.object({
.object({
slug: z.string().optional(),
requireMention: z.boolean().optional(),
reactionNotifications: z
.enum(["off", "own", "all", "allowlist"])
.optional(),
users: z.array(z.union([z.string(), z.number()])).optional(),
channels: z
.record(
@@ -1250,6 +1282,7 @@ const ClawdisSchema = z.object({
controlUi: z
.object({
enabled: z.boolean().optional(),
basePath: z.string().optional(),
})
.optional(),
auth: z
+16
View File
@@ -0,0 +1,16 @@
import { describe, expect, it } from "vitest";
import { buildConfigSchema } from "./schema.js";
describe("config schema", () => {
it("exports schema + hints", () => {
const res = buildConfigSchema();
const schema = res.schema as { properties?: Record<string, unknown> };
expect(schema.properties?.gateway).toBeTruthy();
expect(schema.properties?.agent).toBeTruthy();
expect(res.uiHints.gateway?.label).toBe("Gateway");
expect(res.uiHints["gateway.auth.token"]?.sensitive).toBe(true);
expect(res.version).toBeTruthy();
expect(res.generatedAt).toBeTruthy();
});
});
+165
View File
@@ -0,0 +1,165 @@
import { VERSION } from "../version.js";
import { ClawdisSchema } from "./config.js";
export type ConfigUiHint = {
label?: string;
help?: string;
group?: string;
order?: number;
advanced?: boolean;
sensitive?: boolean;
placeholder?: string;
itemTemplate?: unknown;
};
export type ConfigUiHints = Record<string, ConfigUiHint>;
export type ConfigSchema = ReturnType<typeof ClawdisSchema.toJSONSchema>;
export type ConfigSchemaResponse = {
schema: ConfigSchema;
uiHints: ConfigUiHints;
version: string;
generatedAt: string;
};
const GROUP_LABELS: Record<string, string> = {
identity: "Identity",
wizard: "Wizard",
logging: "Logging",
gateway: "Gateway",
agent: "Agent",
models: "Models",
routing: "Routing",
messages: "Messages",
session: "Session",
cron: "Cron",
hooks: "Hooks",
ui: "UI",
browser: "Browser",
talk: "Talk",
telegram: "Telegram",
discord: "Discord",
signal: "Signal",
imessage: "iMessage",
whatsapp: "WhatsApp",
skills: "Skills",
discovery: "Discovery",
presence: "Presence",
voicewake: "Voice Wake",
};
const GROUP_ORDER: Record<string, number> = {
identity: 10,
wizard: 20,
gateway: 30,
agent: 40,
models: 50,
routing: 60,
messages: 70,
session: 80,
cron: 90,
hooks: 100,
ui: 110,
browser: 120,
talk: 130,
telegram: 140,
discord: 150,
signal: 160,
imessage: 170,
whatsapp: 180,
skills: 190,
discovery: 200,
presence: 210,
voicewake: 220,
logging: 900,
};
const FIELD_LABELS: Record<string, string> = {
"gateway.remote.url": "Remote Gateway URL",
"gateway.remote.token": "Remote Gateway Token",
"gateway.remote.password": "Remote Gateway Password",
"gateway.auth.token": "Gateway Token",
"gateway.auth.password": "Gateway Password",
"gateway.controlUi.basePath": "Control UI Base Path",
"agent.workspace": "Workspace",
"agent.model": "Default Model",
"ui.seamColor": "Accent Color",
"browser.controlUrl": "Browser Control URL",
"talk.apiKey": "Talk API Key",
"telegram.botToken": "Telegram Bot Token",
"discord.token": "Discord Bot Token",
"signal.account": "Signal Account",
"imessage.cliPath": "iMessage CLI Path",
};
const FIELD_HELP: Record<string, string> = {
"gateway.remote.url": "Remote Gateway WebSocket URL (ws:// or wss://).",
"gateway.auth.token":
"Required for multi-machine access or non-loopback binds.",
"gateway.auth.password": "Required for Tailscale funnel.",
"gateway.controlUi.basePath":
"Optional URL prefix where the Control UI is served (e.g. /clawdis).",
};
const FIELD_PLACEHOLDERS: Record<string, string> = {
"gateway.remote.url": "ws://host:18789",
"gateway.controlUi.basePath": "/clawdis",
};
const SENSITIVE_PATTERNS = [/token/i, /password/i, /secret/i, /api.?key/i];
function isSensitivePath(path: string): boolean {
return SENSITIVE_PATTERNS.some((pattern) => pattern.test(path));
}
function buildBaseHints(): ConfigUiHints {
const hints: ConfigUiHints = {};
for (const [group, label] of Object.entries(GROUP_LABELS)) {
hints[group] = {
label,
group: label,
order: GROUP_ORDER[group],
};
}
for (const [path, label] of Object.entries(FIELD_LABELS)) {
hints[path] = { ...(hints[path] ?? {}), label };
}
for (const [path, help] of Object.entries(FIELD_HELP)) {
hints[path] = { ...(hints[path] ?? {}), help };
}
for (const [path, placeholder] of Object.entries(FIELD_PLACEHOLDERS)) {
hints[path] = { ...(hints[path] ?? {}), placeholder };
}
return hints;
}
function applySensitiveHints(hints: ConfigUiHints): ConfigUiHints {
const next = { ...hints };
for (const key of Object.keys(next)) {
if (isSensitivePath(key)) {
next[key] = { ...next[key], sensitive: true };
}
}
return next;
}
let cached: ConfigSchemaResponse | null = null;
export function buildConfigSchema(): ConfigSchemaResponse {
if (cached) return cached;
const schema = ClawdisSchema.toJSONSchema({
target: "draft-07",
unrepresentable: "any",
});
schema.title = "ClawdisConfig";
const hints = applySensitiveHints(buildBaseHints());
const next = {
schema,
uiHints: hints,
version: VERSION,
generatedAt: new Date().toISOString(),
};
cached = next;
return next;
}
+86
View File
@@ -8,6 +8,7 @@ import {
resolveDiscordGuildEntry,
resolveDiscordReplyTarget,
resolveGroupDmAllow,
shouldEmitDiscordReactionNotification,
} from "./monitor.js";
const fakeGuild = (id: string, name: string) =>
@@ -21,6 +22,7 @@ const makeEntries = (
out[key] = {
slug: value.slug,
requireMention: value.requireMention,
reactionNotifications: value.reactionNotifications,
users: value.users,
channels: value.channels,
};
@@ -207,3 +209,87 @@ describe("discord reply target selection", () => {
).toBe("123");
});
});
describe("discord reaction notification gating", () => {
it("defaults to own when mode is unset", () => {
expect(
shouldEmitDiscordReactionNotification({
mode: undefined,
botId: "bot-1",
messageAuthorId: "bot-1",
userId: "user-1",
}),
).toBe(true);
expect(
shouldEmitDiscordReactionNotification({
mode: undefined,
botId: "bot-1",
messageAuthorId: "user-1",
userId: "user-2",
}),
).toBe(false);
});
it("skips when mode is off", () => {
expect(
shouldEmitDiscordReactionNotification({
mode: "off",
botId: "bot-1",
messageAuthorId: "bot-1",
userId: "user-1",
}),
).toBe(false);
});
it("allows all reactions when mode is all", () => {
expect(
shouldEmitDiscordReactionNotification({
mode: "all",
botId: "bot-1",
messageAuthorId: "user-1",
userId: "user-2",
}),
).toBe(true);
});
it("requires bot ownership when mode is own", () => {
expect(
shouldEmitDiscordReactionNotification({
mode: "own",
botId: "bot-1",
messageAuthorId: "bot-1",
userId: "user-2",
}),
).toBe(true);
expect(
shouldEmitDiscordReactionNotification({
mode: "own",
botId: "bot-1",
messageAuthorId: "user-2",
userId: "user-3",
}),
).toBe(false);
});
it("requires allowlist matches when mode is allowlist", () => {
expect(
shouldEmitDiscordReactionNotification({
mode: "allowlist",
botId: "bot-1",
messageAuthorId: "user-1",
userId: "user-2",
allowlist: [],
}),
).toBe(false);
expect(
shouldEmitDiscordReactionNotification({
mode: "allowlist",
botId: "bot-1",
messageAuthorId: "user-1",
userId: "123",
userName: "steipete",
allowlist: ["123", "other"],
}),
).toBe(true);
});
});
+153 -7
View File
@@ -1,12 +1,20 @@
import {
ApplicationCommandOptionType,
type Attachment,
ChannelType,
type ChatInputCommandInteraction,
Client,
type CommandInteractionOption,
Events,
GatewayIntentBits,
type Guild,
type Message,
type MessageReaction,
type PartialMessage,
type PartialMessageReaction,
Partials,
type PartialUser,
type User,
} from "discord.js";
import { chunkText, resolveTextChunkLimit } from "../auto-reply/chunk.js";
@@ -21,6 +29,7 @@ import type {
import { loadConfig } from "../config/config.js";
import { resolveStorePath, updateLastRoute } from "../config/sessions.js";
import { danger, logVerbose, shouldLogVerbose, warn } from "../globals.js";
import { enqueueSystemEvent } from "../infra/system-events.js";
import { getChildLogger } from "../logging.js";
import { detectMime } from "../media/mime.js";
import { saveMediaBuffer } from "../media/store.js";
@@ -61,6 +70,7 @@ export type DiscordGuildEntryResolved = {
id?: string;
slug?: string;
requireMention?: boolean;
reactionNotifications?: "off" | "own" | "all" | "allowlist";
users?: Array<string | number>;
channels?: Record<string, { allow?: boolean; requireMention?: boolean }>;
};
@@ -149,10 +159,17 @@ export async function monitorDiscordProvider(opts: MonitorDiscordOpts = {}) {
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.MessageContent,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.DirectMessageReactions,
],
partials: [
Partials.Channel,
Partials.Message,
Partials.Reaction,
Partials.User,
],
partials: [Partials.Channel],
});
const logger = getChildLogger({ module: "discord-auto-reply" });
@@ -503,6 +520,88 @@ export async function monitorDiscordProvider(opts: MonitorDiscordOpts = {}) {
}
});
const handleReactionEvent = async (
reaction: MessageReaction | PartialMessageReaction,
user: User | PartialUser,
action: "added" | "removed",
) => {
try {
if (!user || user.bot) return;
const resolvedReaction = reaction.partial
? await reaction.fetch()
: reaction;
const message = (resolvedReaction.message as Message | PartialMessage)
.partial
? await resolvedReaction.message.fetch()
: resolvedReaction.message;
const guild = message.guild;
if (!guild) return;
const guildInfo = resolveDiscordGuildEntry({
guild,
guildEntries,
});
if (guildEntries && Object.keys(guildEntries).length > 0 && !guildInfo) {
return;
}
const channelName =
"name" in message.channel
? (message.channel.name ?? undefined)
: undefined;
const channelSlug = channelName ? normalizeDiscordSlug(channelName) : "";
const channelConfig = resolveDiscordChannelConfig({
guildInfo,
channelId: message.channelId,
channelName,
channelSlug,
});
if (channelConfig?.allowed === false) return;
const botId = client.user?.id;
if (botId && user.id === botId) return;
const reactionMode = guildInfo?.reactionNotifications ?? "own";
const shouldNotify = shouldEmitDiscordReactionNotification({
mode: reactionMode,
botId,
messageAuthorId: message.author?.id,
userId: user.id,
userName: user.username,
userTag: user.tag,
allowlist: guildInfo?.users,
});
if (!shouldNotify) return;
const emojiLabel = formatDiscordReactionEmoji(resolvedReaction);
const actorLabel = user.tag ?? user.username ?? user.id;
const guildSlug =
guildInfo?.slug ||
(guild.name ? normalizeDiscordSlug(guild.name) : guild.id);
const channelLabel = channelSlug
? `#${channelSlug}`
: channelName
? `#${normalizeDiscordSlug(channelName)}`
: `#${message.channelId}`;
const authorLabel = message.author?.tag ?? message.author?.username;
const baseText = `Discord reaction ${action}: ${emojiLabel} by ${actorLabel} on ${guildSlug} ${channelLabel} msg ${message.id}`;
const text = authorLabel ? `${baseText} from ${authorLabel}` : baseText;
enqueueSystemEvent(text, {
contextKey: `discord:reaction:${action}:${message.id}:${user.id}:${emojiLabel}`,
});
} catch (err) {
runtime.error?.(
danger(`discord reaction handler failed: ${String(err)}`),
);
}
};
client.on(Events.MessageReactionAdd, async (reaction, user) => {
await handleReactionEvent(reaction, user, "added");
});
client.on(Events.MessageReactionRemove, async (reaction, user) => {
await handleReactionEvent(reaction, user, "removed");
});
client.on(Events.InteractionCreate, async (interaction) => {
try {
if (!slashCommand.enabled) return;
@@ -698,7 +797,7 @@ export async function monitorDiscordProvider(opts: MonitorDiscordOpts = {}) {
}
async function resolveMedia(
message: import("discord.js").Message,
message: Message,
maxBytes: number,
): Promise<DiscordMediaInfo | null> {
const attachment = message.attachments.first();
@@ -723,7 +822,7 @@ async function resolveMedia(
};
}
function inferPlaceholder(attachment: import("discord.js").Attachment): string {
function inferPlaceholder(attachment: Attachment): string {
const mime = attachment.contentType ?? "";
if (mime.startsWith("image/")) return "<media:image>";
if (mime.startsWith("video/")) return "<media:video>";
@@ -768,17 +867,30 @@ async function resolveReplyContext(message: Message): Promise<string | null> {
}
}
function buildDirectLabel(message: import("discord.js").Message) {
function buildDirectLabel(message: Message) {
const username = message.author.tag;
return `${username} id:${message.author.id}`;
}
function buildGuildLabel(message: import("discord.js").Message) {
function buildGuildLabel(message: Message) {
const channelName =
"name" in message.channel ? message.channel.name : message.channelId;
return `${message.guild?.name ?? "Guild"} #${channelName} id:${message.channelId}`;
}
function formatDiscordReactionEmoji(
reaction: MessageReaction | PartialMessageReaction,
) {
if (typeof reaction.emoji.toString === "function") {
const rendered = reaction.emoji.toString();
if (rendered && rendered !== "[object Object]") return rendered;
}
if (reaction.emoji.id && reaction.emoji.name) {
return `${reaction.emoji.name}:${reaction.emoji.id}`;
}
return reaction.emoji.name ?? "emoji";
}
export function normalizeDiscordAllowList(
raw: Array<string | number> | undefined,
prefixes: string[],
@@ -862,8 +974,38 @@ export function allowListMatches(
return false;
}
export function shouldEmitDiscordReactionNotification(params: {
mode: "off" | "own" | "all" | "allowlist" | undefined;
botId?: string | null;
messageAuthorId?: string | null;
userId: string;
userName?: string | null;
userTag?: string | null;
allowlist?: Array<string | number> | null;
}) {
const { mode, botId, messageAuthorId, userId, userName, userTag, allowlist } =
params;
const effectiveMode = mode ?? "own";
if (effectiveMode === "off") return false;
if (effectiveMode === "own") {
if (!botId || !messageAuthorId) return false;
return messageAuthorId === botId;
}
if (effectiveMode === "allowlist") {
if (!Array.isArray(allowlist) || allowlist.length === 0) return false;
const users = normalizeDiscordAllowList(allowlist, ["discord:", "user:"]);
if (!users) return false;
return allowListMatches(users, {
id: userId,
name: userName ?? undefined,
tag: userTag ?? undefined,
});
}
return true;
}
export function resolveDiscordGuildEntry(params: {
guild: import("discord.js").Guild | null;
guild: Guild | null;
guildEntries: Record<string, DiscordGuildEntryResolved> | undefined;
}): DiscordGuildEntryResolved | null {
const { guild, guildEntries } = params;
@@ -878,6 +1020,7 @@ export function resolveDiscordGuildEntry(params: {
id: guildId,
slug: direct.slug ?? guildSlug,
requireMention: direct.requireMention,
reactionNotifications: direct.reactionNotifications,
users: direct.users,
channels: direct.channels,
};
@@ -888,6 +1031,7 @@ export function resolveDiscordGuildEntry(params: {
id: guildId,
slug: entry.slug ?? guildSlug,
requireMention: entry.requireMention,
reactionNotifications: entry.reactionNotifications,
users: entry.users,
channels: entry.channels,
};
@@ -902,6 +1046,7 @@ export function resolveDiscordGuildEntry(params: {
id: guildId,
slug: entry.slug ?? guildSlug,
requireMention: entry.requireMention,
reactionNotifications: entry.reactionNotifications,
users: entry.users,
channels: entry.channels,
};
@@ -912,6 +1057,7 @@ export function resolveDiscordGuildEntry(params: {
id: guildId,
slug: wildcard.slug ?? guildSlug,
requireMention: wildcard.requireMention,
reactionNotifications: wildcard.reactionNotifications,
users: wildcard.users,
channels: wildcard.channels,
};
@@ -1121,7 +1267,7 @@ async function deliverSlashReplies({
textLimit,
}: {
replies: ReplyPayload[];
interaction: import("discord.js").ChatInputCommandInteraction;
interaction: ChatInputCommandInteraction;
ephemeral: boolean;
textLimit: number;
}) {
+2 -5
View File
@@ -146,11 +146,8 @@ export class GatewayClient {
const pending = this.pending.get(parsed.id);
if (!pending) return;
// If the payload is an ack with status accepted, keep waiting for final.
const payload = parsed.payload;
const status =
payload && typeof payload === "object" && "status" in payload
? (payload as { status?: unknown }).status
: undefined;
const payload = parsed.payload as { status?: unknown } | undefined;
const status = payload?.status;
if (pending.expectFinal && status === "accepted") {
return;
}
+68 -8
View File
@@ -3,9 +3,22 @@ import type { IncomingMessage, ServerResponse } from "node:http";
import path from "node:path";
import { fileURLToPath } from "node:url";
const _UI_PREFIX = "/ui/";
const ROOT_PREFIX = "/";
export type ControlUiRequestOptions = {
basePath?: string;
};
export function normalizeControlUiBasePath(basePath?: string): string {
if (!basePath) return "";
let normalized = basePath.trim();
if (!normalized) return "";
if (!normalized.startsWith("/")) normalized = `/${normalized}`;
if (normalized === "/") return "";
if (normalized.endsWith("/")) normalized = normalized.slice(0, -1);
return normalized;
}
function resolveControlUiRoot(): string | null {
const here = path.dirname(fileURLToPath(import.meta.url));
const execDir = (() => {
@@ -73,6 +86,29 @@ function serveFile(res: ServerResponse, filePath: string) {
res.end(fs.readFileSync(filePath));
}
function injectControlUiBasePath(html: string, basePath: string): string {
const script = `<script>window.__CLAWDIS_CONTROL_UI_BASE_PATH__=${JSON.stringify(
basePath,
)};</script>`;
if (html.includes("__CLAWDIS_CONTROL_UI_BASE_PATH__")) return html;
const headClose = html.indexOf("</head>");
if (headClose !== -1) {
return `${html.slice(0, headClose)}${script}${html.slice(headClose)}`;
}
return `${script}${html}`;
}
function serveIndexHtml(
res: ServerResponse,
indexPath: string,
basePath: string,
) {
res.setHeader("Content-Type", "text/html; charset=utf-8");
res.setHeader("Cache-Control", "no-cache");
const raw = fs.readFileSync(indexPath, "utf8");
res.end(injectControlUiBasePath(raw, basePath));
}
function isSafeRelativePath(relPath: string) {
if (!relPath) return false;
const normalized = path.posix.normalize(relPath);
@@ -84,6 +120,7 @@ function isSafeRelativePath(relPath: string) {
export function handleControlUiHttpRequest(
req: IncomingMessage,
res: ServerResponse,
opts?: ControlUiRequestOptions,
): boolean {
const urlRaw = req.url;
if (!urlRaw) return false;
@@ -95,10 +132,24 @@ export function handleControlUiHttpRequest(
}
const url = new URL(urlRaw, "http://localhost");
const basePath = normalizeControlUiBasePath(opts?.basePath);
const pathname = url.pathname;
if (url.pathname === "/ui" || url.pathname.startsWith("/ui/")) {
respondNotFound(res);
return true;
if (!basePath) {
if (pathname === "/ui" || pathname.startsWith("/ui/")) {
respondNotFound(res);
return true;
}
}
if (basePath) {
if (pathname === basePath) {
res.statusCode = 302;
res.setHeader("Location", `${basePath}/${url.search}`);
res.end();
return true;
}
if (!pathname.startsWith(`${basePath}/`)) return false;
}
const root = resolveControlUiRoot();
@@ -111,10 +162,15 @@ export function handleControlUiHttpRequest(
return true;
}
const uiPath =
basePath && pathname.startsWith(`${basePath}/`)
? pathname.slice(basePath.length)
: pathname;
const rel = (() => {
if (url.pathname === ROOT_PREFIX) return "";
if (url.pathname.startsWith("/assets/")) return url.pathname.slice(1);
return url.pathname.slice(1);
if (uiPath === ROOT_PREFIX) return "";
const assetsIndex = uiPath.indexOf("/assets/");
if (assetsIndex >= 0) return uiPath.slice(assetsIndex + 1);
return uiPath.slice(1);
})();
const requested = rel && !rel.endsWith("/") ? rel : `${rel}index.html`;
const fileRel = requested || "index.html";
@@ -130,6 +186,10 @@ export function handleControlUiHttpRequest(
}
if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
if (path.basename(filePath) === "index.html") {
serveIndexHtml(res, filePath, basePath);
return true;
}
serveFile(res, filePath);
return true;
}
@@ -137,7 +197,7 @@ export function handleControlUiHttpRequest(
// SPA fallback (client-side router): serve index.html for unknown paths.
const indexPath = path.join(root, "index.html");
if (fs.existsSync(indexPath)) {
serveFile(res, indexPath);
serveIndexHtml(res, indexPath, basePath);
return true;
}
+83
View File
@@ -0,0 +1,83 @@
import type { IncomingMessage } from "node:http";
import { describe, expect, test } from "vitest";
import type { ClawdisConfig } from "../config/config.js";
import {
extractHookToken,
normalizeAgentPayload,
normalizeWakePayload,
resolveHooksConfig,
} from "./hooks.js";
describe("gateway hooks helpers", () => {
test("resolveHooksConfig normalizes paths + requires token", () => {
const base = {
hooks: {
enabled: true,
token: "secret",
path: "hooks///",
},
} as ClawdisConfig;
const resolved = resolveHooksConfig(base);
expect(resolved?.basePath).toBe("/hooks");
expect(resolved?.token).toBe("secret");
});
test("resolveHooksConfig rejects root path", () => {
const cfg = {
hooks: { enabled: true, token: "x", path: "/" },
} as ClawdisConfig;
expect(() => resolveHooksConfig(cfg)).toThrow("hooks.path may not be '/'");
});
test("extractHookToken prefers bearer > header > query", () => {
const req = {
headers: {
authorization: "Bearer top",
"x-clawdis-token": "header",
},
} as unknown as IncomingMessage;
const url = new URL("http://localhost/hooks/wake?token=query");
expect(extractHookToken(req, url)).toBe("top");
const req2 = {
headers: { "x-clawdis-token": "header" },
} as unknown as IncomingMessage;
expect(extractHookToken(req2, url)).toBe("header");
const req3 = { headers: {} } as unknown as IncomingMessage;
expect(extractHookToken(req3, url)).toBe("query");
});
test("normalizeWakePayload trims + validates", () => {
expect(normalizeWakePayload({ text: " hi " })).toEqual({
ok: true,
value: { text: "hi", mode: "now" },
});
expect(normalizeWakePayload({ text: " ", mode: "now" }).ok).toBe(false);
});
test("normalizeAgentPayload defaults + validates channel", () => {
const ok = normalizeAgentPayload(
{ message: "hello" },
{ idFactory: () => "fixed" },
);
expect(ok.ok).toBe(true);
if (ok.ok) {
expect(ok.value.sessionKey).toBe("hook:fixed");
expect(ok.value.channel).toBe("last");
expect(ok.value.name).toBe("Hook");
}
const imsg = normalizeAgentPayload(
{ message: "yo", channel: "imsg" },
{ idFactory: () => "x" },
);
expect(imsg.ok).toBe(true);
if (imsg.ok) {
expect(imsg.value.channel).toBe("imessage");
}
const bad = normalizeAgentPayload({ message: "yo", channel: "sms" });
expect(bad.ok).toBe(false);
});
});
+219
View File
@@ -0,0 +1,219 @@
import { randomUUID } from "node:crypto";
import type { IncomingMessage } from "node:http";
import type { ClawdisConfig } from "../config/config.js";
import {
type HookMappingResolved,
resolveHookMappings,
} from "./hooks-mapping.js";
const DEFAULT_HOOKS_PATH = "/hooks";
const DEFAULT_HOOKS_MAX_BODY_BYTES = 256 * 1024;
export type HooksConfigResolved = {
basePath: string;
token: string;
maxBodyBytes: number;
mappings: HookMappingResolved[];
};
export function resolveHooksConfig(
cfg: ClawdisConfig,
): HooksConfigResolved | null {
if (cfg.hooks?.enabled !== true) return null;
const token = cfg.hooks?.token?.trim();
if (!token) {
throw new Error("hooks.enabled requires hooks.token");
}
const rawPath = cfg.hooks?.path?.trim() || DEFAULT_HOOKS_PATH;
const withSlash = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
const trimmed =
withSlash.length > 1 ? withSlash.replace(/\/+$/, "") : withSlash;
if (trimmed === "/") {
throw new Error("hooks.path may not be '/'");
}
const maxBodyBytes =
cfg.hooks?.maxBodyBytes && cfg.hooks.maxBodyBytes > 0
? cfg.hooks.maxBodyBytes
: DEFAULT_HOOKS_MAX_BODY_BYTES;
const mappings = resolveHookMappings(cfg.hooks);
return {
basePath: trimmed,
token,
maxBodyBytes,
mappings,
};
}
export function extractHookToken(
req: IncomingMessage,
url: URL,
): string | undefined {
const auth =
typeof req.headers.authorization === "string"
? req.headers.authorization.trim()
: "";
if (auth.toLowerCase().startsWith("bearer ")) {
const token = auth.slice(7).trim();
if (token) return token;
}
const headerToken =
typeof req.headers["x-clawdis-token"] === "string"
? req.headers["x-clawdis-token"].trim()
: "";
if (headerToken) return headerToken;
const queryToken = url.searchParams.get("token");
if (queryToken) return queryToken.trim();
return undefined;
}
export async function readJsonBody(
req: IncomingMessage,
maxBytes: number,
): Promise<{ ok: true; value: unknown } | { ok: false; error: string }> {
return await new Promise((resolve) => {
let done = false;
let total = 0;
const chunks: Buffer[] = [];
req.on("data", (chunk: Buffer) => {
if (done) return;
total += chunk.length;
if (total > maxBytes) {
done = true;
resolve({ ok: false, error: "payload too large" });
req.destroy();
return;
}
chunks.push(chunk);
});
req.on("end", () => {
if (done) return;
done = true;
const raw = Buffer.concat(chunks).toString("utf-8").trim();
if (!raw) {
resolve({ ok: true, value: {} });
return;
}
try {
const parsed = JSON.parse(raw) as unknown;
resolve({ ok: true, value: parsed });
} catch (err) {
resolve({ ok: false, error: String(err) });
}
});
req.on("error", (err) => {
if (done) return;
done = true;
resolve({ ok: false, error: String(err) });
});
});
}
export function normalizeHookHeaders(req: IncomingMessage) {
const headers: Record<string, string> = {};
for (const [key, value] of Object.entries(req.headers)) {
if (typeof value === "string") {
headers[key.toLowerCase()] = value;
} else if (Array.isArray(value) && value.length > 0) {
headers[key.toLowerCase()] = value.join(", ");
}
}
return headers;
}
export function normalizeWakePayload(
payload: Record<string, unknown>,
):
| { ok: true; value: { text: string; mode: "now" | "next-heartbeat" } }
| { ok: false; error: string } {
const text = typeof payload.text === "string" ? payload.text.trim() : "";
if (!text) return { ok: false, error: "text required" };
const mode = payload.mode === "next-heartbeat" ? "next-heartbeat" : "now";
return { ok: true, value: { text, mode } };
}
export type HookAgentPayload = {
message: string;
name: string;
wakeMode: "now" | "next-heartbeat";
sessionKey: string;
deliver: boolean;
channel: "last" | "whatsapp" | "telegram" | "discord" | "signal" | "imessage";
to?: string;
thinking?: string;
timeoutSeconds?: number;
};
export function normalizeAgentPayload(
payload: Record<string, unknown>,
opts?: { idFactory?: () => string },
):
| {
ok: true;
value: HookAgentPayload;
}
| { ok: false; error: string } {
const message =
typeof payload.message === "string" ? payload.message.trim() : "";
if (!message) return { ok: false, error: "message required" };
const nameRaw = payload.name;
const name =
typeof nameRaw === "string" && nameRaw.trim() ? nameRaw.trim() : "Hook";
const wakeMode =
payload.wakeMode === "next-heartbeat" ? "next-heartbeat" : "now";
const sessionKeyRaw = payload.sessionKey;
const idFactory = opts?.idFactory ?? randomUUID;
const sessionKey =
typeof sessionKeyRaw === "string" && sessionKeyRaw.trim()
? sessionKeyRaw.trim()
: `hook:${idFactory()}`;
const channelRaw = payload.channel;
const channel =
channelRaw === "whatsapp" ||
channelRaw === "telegram" ||
channelRaw === "discord" ||
channelRaw === "signal" ||
channelRaw === "imessage" ||
channelRaw === "last"
? channelRaw
: channelRaw === "imsg"
? "imessage"
: channelRaw === undefined
? "last"
: null;
if (channel === null) {
return {
ok: false,
error: "channel must be last|whatsapp|telegram|discord|signal|imessage",
};
}
const toRaw = payload.to;
const to =
typeof toRaw === "string" && toRaw.trim() ? toRaw.trim() : undefined;
const deliver = payload.deliver === true;
const thinkingRaw = payload.thinking;
const thinking =
typeof thinkingRaw === "string" && thinkingRaw.trim()
? thinkingRaw.trim()
: undefined;
const timeoutRaw = payload.timeoutSeconds;
const timeoutSeconds =
typeof timeoutRaw === "number" &&
Number.isFinite(timeoutRaw) &&
timeoutRaw > 0
? Math.floor(timeoutRaw)
: undefined;
return {
ok: true,
value: {
message,
name,
wakeMode,
sessionKey,
deliver,
channel,
to,
thinking,
timeoutSeconds,
},
};
}
+25
View File
@@ -0,0 +1,25 @@
import { pickPrimaryTailnetIPv4 } from "../infra/tailnet.js";
export function isLoopbackAddress(ip: string | undefined): boolean {
if (!ip) return false;
if (ip === "127.0.0.1") return true;
if (ip.startsWith("127.")) return true;
if (ip === "::1") return true;
if (ip.startsWith("::ffff:127.")) return true;
return false;
}
export function resolveGatewayBindHost(
bind: import("../config/config.js").BridgeBindMode | undefined,
): string | null {
const mode = bind ?? "loopback";
if (mode === "loopback") return "127.0.0.1";
if (mode === "lan") return "0.0.0.0";
if (mode === "tailnet") return pickPrimaryTailnetIPv4() ?? null;
if (mode === "auto") return pickPrimaryTailnetIPv4() ?? "0.0.0.0";
return "127.0.0.1";
}
export function isLoopbackHost(host: string): boolean {
return isLoopbackAddress(host);
}
+55
View File
@@ -11,6 +11,10 @@ import {
ChatSendParamsSchema,
type ConfigGetParams,
ConfigGetParamsSchema,
type ConfigSchemaParams,
ConfigSchemaParamsSchema,
type ConfigSchemaResponse,
ConfigSchemaResponseSchema,
type ConfigSetParams,
ConfigSetParamsSchema,
type ConnectParams,
@@ -105,6 +109,22 @@ import {
WebLoginStartParamsSchema,
type WebLoginWaitParams,
WebLoginWaitParamsSchema,
type WizardCancelParams,
WizardCancelParamsSchema,
type WizardNextParams,
WizardNextParamsSchema,
type WizardNextResult,
WizardNextResultSchema,
type WizardStartParams,
WizardStartParamsSchema,
type WizardStartResult,
WizardStartResultSchema,
type WizardStatusParams,
WizardStatusParamsSchema,
type WizardStatusResult,
WizardStatusResultSchema,
type WizardStep,
WizardStepSchema,
} from "./schema.js";
const ajv = new (
@@ -174,6 +194,21 @@ export const validateConfigGetParams = ajv.compile<ConfigGetParams>(
export const validateConfigSetParams = ajv.compile<ConfigSetParams>(
ConfigSetParamsSchema,
);
export const validateConfigSchemaParams = ajv.compile<ConfigSchemaParams>(
ConfigSchemaParamsSchema,
);
export const validateWizardStartParams = ajv.compile<WizardStartParams>(
WizardStartParamsSchema,
);
export const validateWizardNextParams = ajv.compile<WizardNextParams>(
WizardNextParamsSchema,
);
export const validateWizardCancelParams = ajv.compile<WizardCancelParams>(
WizardCancelParamsSchema,
);
export const validateWizardStatusParams = ajv.compile<WizardStatusParams>(
WizardStatusParamsSchema,
);
export const validateTalkModeParams =
ajv.compile<TalkModeParams>(TalkModeParamsSchema);
export const validateProvidersStatusParams = ajv.compile<ProvidersStatusParams>(
@@ -258,6 +293,16 @@ export {
SessionsCompactParamsSchema,
ConfigGetParamsSchema,
ConfigSetParamsSchema,
ConfigSchemaParamsSchema,
ConfigSchemaResponseSchema,
WizardStartParamsSchema,
WizardNextParamsSchema,
WizardCancelParamsSchema,
WizardStatusParamsSchema,
WizardStepSchema,
WizardNextResultSchema,
WizardStartResultSchema,
WizardStatusResultSchema,
ProvidersStatusParamsSchema,
WebLoginStartParamsSchema,
WebLoginWaitParamsSchema,
@@ -304,6 +349,16 @@ export type {
NodePairApproveParams,
ConfigGetParams,
ConfigSetParams,
ConfigSchemaParams,
ConfigSchemaResponse,
WizardStartParams,
WizardNextParams,
WizardCancelParams,
WizardStatusParams,
WizardStep,
WizardNextResult,
WizardStartResult,
WizardStatusResult,
TalkModeParams,
ProvidersStatusParams,
WebLoginStartParams,
+171
View File
@@ -342,6 +342,157 @@ export const ConfigSetParamsSchema = Type.Object(
{ additionalProperties: false },
);
export const ConfigSchemaParamsSchema = Type.Object(
{},
{ additionalProperties: false },
);
export const ConfigUiHintSchema = Type.Object(
{
label: Type.Optional(Type.String()),
help: Type.Optional(Type.String()),
group: Type.Optional(Type.String()),
order: Type.Optional(Type.Integer()),
advanced: Type.Optional(Type.Boolean()),
sensitive: Type.Optional(Type.Boolean()),
placeholder: Type.Optional(Type.String()),
itemTemplate: Type.Optional(Type.Unknown()),
},
{ additionalProperties: false },
);
export const ConfigSchemaResponseSchema = Type.Object(
{
schema: Type.Unknown(),
uiHints: Type.Record(Type.String(), ConfigUiHintSchema),
version: NonEmptyString,
generatedAt: NonEmptyString,
},
{ additionalProperties: false },
);
export const WizardStartParamsSchema = Type.Object(
{
mode: Type.Optional(
Type.Union([Type.Literal("local"), Type.Literal("remote")]),
),
workspace: Type.Optional(Type.String()),
},
{ additionalProperties: false },
);
export const WizardAnswerSchema = Type.Object(
{
stepId: NonEmptyString,
value: Type.Optional(Type.Unknown()),
},
{ additionalProperties: false },
);
export const WizardNextParamsSchema = Type.Object(
{
sessionId: NonEmptyString,
answer: Type.Optional(WizardAnswerSchema),
},
{ additionalProperties: false },
);
export const WizardCancelParamsSchema = Type.Object(
{
sessionId: NonEmptyString,
},
{ additionalProperties: false },
);
export const WizardStatusParamsSchema = Type.Object(
{
sessionId: NonEmptyString,
},
{ additionalProperties: false },
);
export const WizardStepOptionSchema = Type.Object(
{
value: Type.Unknown(),
label: NonEmptyString,
hint: Type.Optional(Type.String()),
},
{ additionalProperties: false },
);
export const WizardStepSchema = Type.Object(
{
id: NonEmptyString,
type: Type.Union([
Type.Literal("note"),
Type.Literal("select"),
Type.Literal("text"),
Type.Literal("confirm"),
Type.Literal("multiselect"),
Type.Literal("progress"),
Type.Literal("action"),
]),
title: Type.Optional(Type.String()),
message: Type.Optional(Type.String()),
options: Type.Optional(Type.Array(WizardStepOptionSchema)),
initialValue: Type.Optional(Type.Unknown()),
placeholder: Type.Optional(Type.String()),
sensitive: Type.Optional(Type.Boolean()),
executor: Type.Optional(
Type.Union([Type.Literal("gateway"), Type.Literal("client")]),
),
},
{ additionalProperties: false },
);
export const WizardNextResultSchema = Type.Object(
{
done: Type.Boolean(),
step: Type.Optional(WizardStepSchema),
status: Type.Optional(
Type.Union([
Type.Literal("running"),
Type.Literal("done"),
Type.Literal("cancelled"),
Type.Literal("error"),
]),
),
error: Type.Optional(Type.String()),
},
{ additionalProperties: false },
);
export const WizardStartResultSchema = Type.Object(
{
sessionId: NonEmptyString,
done: Type.Boolean(),
step: Type.Optional(WizardStepSchema),
status: Type.Optional(
Type.Union([
Type.Literal("running"),
Type.Literal("done"),
Type.Literal("cancelled"),
Type.Literal("error"),
]),
),
error: Type.Optional(Type.String()),
},
{ additionalProperties: false },
);
export const WizardStatusResultSchema = Type.Object(
{
status: Type.Union([
Type.Literal("running"),
Type.Literal("done"),
Type.Literal("cancelled"),
Type.Literal("error"),
]),
error: Type.Optional(Type.String()),
},
{ additionalProperties: false },
);
export const TalkModeParamsSchema = Type.Object(
{
enabled: Type.Boolean(),
@@ -680,6 +831,16 @@ export const ProtocolSchemas: Record<string, TSchema> = {
SessionsCompactParams: SessionsCompactParamsSchema,
ConfigGetParams: ConfigGetParamsSchema,
ConfigSetParams: ConfigSetParamsSchema,
ConfigSchemaParams: ConfigSchemaParamsSchema,
ConfigSchemaResponse: ConfigSchemaResponseSchema,
WizardStartParams: WizardStartParamsSchema,
WizardNextParams: WizardNextParamsSchema,
WizardCancelParams: WizardCancelParamsSchema,
WizardStatusParams: WizardStatusParamsSchema,
WizardStep: WizardStepSchema,
WizardNextResult: WizardNextResultSchema,
WizardStartResult: WizardStartResultSchema,
WizardStatusResult: WizardStatusResultSchema,
TalkModeParams: TalkModeParamsSchema,
ProvidersStatusParams: ProvidersStatusParamsSchema,
WebLoginStartParams: WebLoginStartParamsSchema,
@@ -737,6 +898,16 @@ export type SessionsDeleteParams = Static<typeof SessionsDeleteParamsSchema>;
export type SessionsCompactParams = Static<typeof SessionsCompactParamsSchema>;
export type ConfigGetParams = Static<typeof ConfigGetParamsSchema>;
export type ConfigSetParams = Static<typeof ConfigSetParamsSchema>;
export type ConfigSchemaParams = Static<typeof ConfigSchemaParamsSchema>;
export type ConfigSchemaResponse = Static<typeof ConfigSchemaResponseSchema>;
export type WizardStartParams = Static<typeof WizardStartParamsSchema>;
export type WizardNextParams = Static<typeof WizardNextParamsSchema>;
export type WizardCancelParams = Static<typeof WizardCancelParamsSchema>;
export type WizardStatusParams = Static<typeof WizardStatusParamsSchema>;
export type WizardStep = Static<typeof WizardStepSchema>;
export type WizardNextResult = Static<typeof WizardNextResultSchema>;
export type WizardStartResult = Static<typeof WizardStartResultSchema>;
export type WizardStatusResult = Static<typeof WizardStatusResultSchema>;
export type TalkModeParams = Static<typeof TalkModeParamsSchema>;
export type ProvidersStatusParams = Static<typeof ProvidersStatusParamsSchema>;
export type WebLoginStartParams = Static<typeof WebLoginStartParamsSchema>;
@@ -0,0 +1,41 @@
import { describe, expect, test } from "vitest";
import { createBridgeSubscriptionManager } from "./server-bridge-subscriptions.js";
describe("bridge subscription manager", () => {
test("routes events to subscribed nodes", () => {
const manager = createBridgeSubscriptionManager();
const sent: Array<{
nodeId: string;
event: string;
payloadJSON?: string | null;
}> = [];
const sendEvent = (evt: {
nodeId: string;
event: string;
payloadJSON?: string | null;
}) => sent.push(evt);
manager.subscribe("node-a", "main");
manager.subscribe("node-b", "main");
manager.sendToSession("main", "chat", { ok: true }, sendEvent);
expect(sent).toHaveLength(2);
expect(sent.map((s) => s.nodeId).sort()).toEqual(["node-a", "node-b"]);
expect(sent[0].event).toBe("chat");
});
test("unsubscribeAll clears session mappings", () => {
const manager = createBridgeSubscriptionManager();
const sent: string[] = [];
const sendEvent = (evt: { nodeId: string; event: string }) =>
sent.push(`${evt.nodeId}:${evt.event}`);
manager.subscribe("node-a", "main");
manager.subscribe("node-a", "secondary");
manager.unsubscribeAll("node-a");
manager.sendToSession("main", "tick", {}, sendEvent);
manager.sendToSession("secondary", "tick", {}, sendEvent);
expect(sent).toEqual([]);
});
});
+144
View File
@@ -0,0 +1,144 @@
export type BridgeSendEventFn = (opts: {
nodeId: string;
event: string;
payloadJSON?: string | null;
}) => void;
export type BridgeListConnectedFn = () => Array<{ nodeId: string }>;
export type BridgeSubscriptionManager = {
subscribe: (nodeId: string, sessionKey: string) => void;
unsubscribe: (nodeId: string, sessionKey: string) => void;
unsubscribeAll: (nodeId: string) => void;
sendToSession: (
sessionKey: string,
event: string,
payload: unknown,
sendEvent?: BridgeSendEventFn | null,
) => void;
sendToAllSubscribed: (
event: string,
payload: unknown,
sendEvent?: BridgeSendEventFn | null,
) => void;
sendToAllConnected: (
event: string,
payload: unknown,
listConnected?: BridgeListConnectedFn | null,
sendEvent?: BridgeSendEventFn | null,
) => void;
clear: () => void;
};
export function createBridgeSubscriptionManager(): BridgeSubscriptionManager {
const bridgeNodeSubscriptions = new Map<string, Set<string>>();
const bridgeSessionSubscribers = new Map<string, Set<string>>();
const toPayloadJSON = (payload: unknown) =>
payload ? JSON.stringify(payload) : null;
const subscribe = (nodeId: string, sessionKey: string) => {
const normalizedNodeId = nodeId.trim();
const normalizedSessionKey = sessionKey.trim();
if (!normalizedNodeId || !normalizedSessionKey) return;
let nodeSet = bridgeNodeSubscriptions.get(normalizedNodeId);
if (!nodeSet) {
nodeSet = new Set<string>();
bridgeNodeSubscriptions.set(normalizedNodeId, nodeSet);
}
if (nodeSet.has(normalizedSessionKey)) return;
nodeSet.add(normalizedSessionKey);
let sessionSet = bridgeSessionSubscribers.get(normalizedSessionKey);
if (!sessionSet) {
sessionSet = new Set<string>();
bridgeSessionSubscribers.set(normalizedSessionKey, sessionSet);
}
sessionSet.add(normalizedNodeId);
};
const unsubscribe = (nodeId: string, sessionKey: string) => {
const normalizedNodeId = nodeId.trim();
const normalizedSessionKey = sessionKey.trim();
if (!normalizedNodeId || !normalizedSessionKey) return;
const nodeSet = bridgeNodeSubscriptions.get(normalizedNodeId);
nodeSet?.delete(normalizedSessionKey);
if (nodeSet?.size === 0) bridgeNodeSubscriptions.delete(normalizedNodeId);
const sessionSet = bridgeSessionSubscribers.get(normalizedSessionKey);
sessionSet?.delete(normalizedNodeId);
if (sessionSet?.size === 0)
bridgeSessionSubscribers.delete(normalizedSessionKey);
};
const unsubscribeAll = (nodeId: string) => {
const normalizedNodeId = nodeId.trim();
const nodeSet = bridgeNodeSubscriptions.get(normalizedNodeId);
if (!nodeSet) return;
for (const sessionKey of nodeSet) {
const sessionSet = bridgeSessionSubscribers.get(sessionKey);
sessionSet?.delete(normalizedNodeId);
if (sessionSet?.size === 0) bridgeSessionSubscribers.delete(sessionKey);
}
bridgeNodeSubscriptions.delete(normalizedNodeId);
};
const sendToSession = (
sessionKey: string,
event: string,
payload: unknown,
sendEvent?: BridgeSendEventFn | null,
) => {
const normalizedSessionKey = sessionKey.trim();
if (!normalizedSessionKey || !sendEvent) return;
const subs = bridgeSessionSubscribers.get(normalizedSessionKey);
if (!subs || subs.size === 0) return;
const payloadJSON = toPayloadJSON(payload);
for (const nodeId of subs) {
sendEvent({ nodeId, event, payloadJSON });
}
};
const sendToAllSubscribed = (
event: string,
payload: unknown,
sendEvent?: BridgeSendEventFn | null,
) => {
if (!sendEvent) return;
const payloadJSON = toPayloadJSON(payload);
for (const nodeId of bridgeNodeSubscriptions.keys()) {
sendEvent({ nodeId, event, payloadJSON });
}
};
const sendToAllConnected = (
event: string,
payload: unknown,
listConnected?: BridgeListConnectedFn | null,
sendEvent?: BridgeSendEventFn | null,
) => {
if (!sendEvent || !listConnected) return;
const payloadJSON = toPayloadJSON(payload);
for (const node of listConnected()) {
sendEvent({ nodeId: node.nodeId, event, payloadJSON });
}
};
const clear = () => {
bridgeNodeSubscriptions.clear();
bridgeSessionSubscribers.clear();
};
return {
subscribe,
unsubscribe,
unsubscribeAll,
sendToSession,
sendToAllSubscribed,
sendToAllConnected,
clear,
};
}
File diff suppressed because it is too large. Load diff
+15
View File
@@ -0,0 +1,15 @@
export type BrowserControlServer = {
stop: () => Promise<void>;
};
export async function startBrowserControlServerIfEnabled(): Promise<BrowserControlServer | null> {
if (process.env.CLAWDIS_SKIP_BROWSER_CONTROL_SERVER === "1") return null;
// Lazy import: keeps startup fast, but still bundles for the embedded
// gateway (bun --compile) via the static specifier path.
const override = process.env.CLAWDIS_BROWSER_CONTROL_MODULE?.trim();
const mod = override
? await import(override)
: await import("../browser/server.js");
await mod.startBrowserControlServerFromConfig();
return { stop: mod.stopBrowserControlServer };
}
+18
View File
@@ -0,0 +1,18 @@
import { describe, expect, test } from "vitest";
import { createChatRunRegistry } from "./server-chat.js";
describe("chat run registry", () => {
test("queues and removes runs per session", () => {
const registry = createChatRunRegistry();
registry.add("s1", { sessionKey: "main", clientRunId: "c1" });
registry.add("s1", { sessionKey: "main", clientRunId: "c2" });
expect(registry.peek("s1")?.clientRunId).toBe("c1");
expect(registry.shift("s1")?.clientRunId).toBe("c1");
expect(registry.peek("s1")?.clientRunId).toBe("c2");
expect(registry.remove("s1", "c2")?.clientRunId).toBe("c2");
expect(registry.peek("s1")).toBeUndefined();
});
});
+251
View File
@@ -0,0 +1,251 @@
import type { AgentEventPayload } from "../infra/agent-events.js";
import { formatForLog } from "./ws-log.js";
export type ChatRunEntry = {
sessionKey: string;
clientRunId: string;
};
export type ChatRunRegistry = {
add: (sessionId: string, entry: ChatRunEntry) => void;
peek: (sessionId: string) => ChatRunEntry | undefined;
shift: (sessionId: string) => ChatRunEntry | undefined;
remove: (
sessionId: string,
clientRunId: string,
sessionKey?: string,
) => ChatRunEntry | undefined;
clear: () => void;
};
export function createChatRunRegistry(): ChatRunRegistry {
const chatRunSessions = new Map<string, ChatRunEntry[]>();
const add = (sessionId: string, entry: ChatRunEntry) => {
const queue = chatRunSessions.get(sessionId);
if (queue) {
queue.push(entry);
} else {
chatRunSessions.set(sessionId, [entry]);
}
};
const peek = (sessionId: string) => chatRunSessions.get(sessionId)?.[0];
const shift = (sessionId: string) => {
const queue = chatRunSessions.get(sessionId);
if (!queue || queue.length === 0) return undefined;
const entry = queue.shift();
if (!queue.length) chatRunSessions.delete(sessionId);
return entry;
};
const remove = (
sessionId: string,
clientRunId: string,
sessionKey?: string,
) => {
const queue = chatRunSessions.get(sessionId);
if (!queue || queue.length === 0) return undefined;
const idx = queue.findIndex(
(entry) =>
entry.clientRunId === clientRunId &&
(sessionKey ? entry.sessionKey === sessionKey : true),
);
if (idx < 0) return undefined;
const [entry] = queue.splice(idx, 1);
if (!queue.length) chatRunSessions.delete(sessionId);
return entry;
};
const clear = () => {
chatRunSessions.clear();
};
return { add, peek, shift, remove, clear };
}
export type ChatRunState = {
registry: ChatRunRegistry;
buffers: Map<string, string>;
deltaSentAt: Map<string, number>;
clear: () => void;
};
export function createChatRunState(): ChatRunState {
const registry = createChatRunRegistry();
const buffers = new Map<string, string>();
const deltaSentAt = new Map<string, number>();
const clear = () => {
registry.clear();
buffers.clear();
deltaSentAt.clear();
};
return {
registry,
buffers,
deltaSentAt,
clear,
};
}
export type ChatEventBroadcast = (
event: string,
payload: unknown,
opts?: { dropIfSlow?: boolean },
) => void;
export type BridgeSendToSession = (
sessionKey: string,
event: string,
payload: unknown,
) => void;
export type AgentEventHandlerOptions = {
broadcast: ChatEventBroadcast;
bridgeSendToSession: BridgeSendToSession;
agentRunSeq: Map<string, number>;
chatRunState: ChatRunState;
resolveSessionKeyForRun: (runId: string) => string | undefined;
clearAgentRunContext: (runId: string) => void;
};
export function createAgentEventHandler({
broadcast,
bridgeSendToSession,
agentRunSeq,
chatRunState,
resolveSessionKeyForRun,
clearAgentRunContext,
}: AgentEventHandlerOptions) {
const emitChatDelta = (
sessionKey: string,
clientRunId: string,
seq: number,
text: string,
) => {
chatRunState.buffers.set(clientRunId, text);
const now = Date.now();
const last = chatRunState.deltaSentAt.get(clientRunId) ?? 0;
if (now - last < 150) return;
chatRunState.deltaSentAt.set(clientRunId, now);
const payload = {
runId: clientRunId,
sessionKey,
seq,
state: "delta" as const,
message: {
role: "assistant",
content: [{ type: "text", text }],
timestamp: now,
},
};
broadcast("chat", payload, { dropIfSlow: true });
bridgeSendToSession(sessionKey, "chat", payload);
};
const emitChatFinal = (
sessionKey: string,
clientRunId: string,
seq: number,
jobState: "done" | "error",
error?: unknown,
) => {
const text = chatRunState.buffers.get(clientRunId)?.trim() ?? "";
chatRunState.buffers.delete(clientRunId);
chatRunState.deltaSentAt.delete(clientRunId);
if (jobState === "done") {
const payload = {
runId: clientRunId,
sessionKey,
seq,
state: "final" as const,
message: text
? {
role: "assistant",
content: [{ type: "text", text }],
timestamp: Date.now(),
}
: undefined,
};
broadcast("chat", payload);
bridgeSendToSession(sessionKey, "chat", payload);
return;
}
const payload = {
runId: clientRunId,
sessionKey,
seq,
state: "error" as const,
errorMessage: error ? formatForLog(error) : undefined,
};
broadcast("chat", payload);
bridgeSendToSession(sessionKey, "chat", payload);
};
return (evt: AgentEventPayload) => {
const chatLink = chatRunState.registry.peek(evt.runId);
const sessionKey =
chatLink?.sessionKey ?? resolveSessionKeyForRun(evt.runId);
// Include sessionKey so Control UI can filter tool streams per session.
const agentPayload = sessionKey ? { ...evt, sessionKey } : evt;
const last = agentRunSeq.get(evt.runId) ?? 0;
if (evt.seq !== last + 1) {
broadcast("agent", {
runId: evt.runId,
stream: "error",
ts: Date.now(),
sessionKey,
data: {
reason: "seq gap",
expected: last + 1,
received: evt.seq,
},
});
}
agentRunSeq.set(evt.runId, evt.seq);
broadcast("agent", agentPayload);
const jobState =
evt.stream === "job" && typeof evt.data?.state === "string"
? (evt.data.state as "done" | "error" | string)
: null;
if (sessionKey) {
bridgeSendToSession(sessionKey, "agent", agentPayload);
if (evt.stream === "assistant" && typeof evt.data?.text === "string") {
const clientRunId = chatLink?.clientRunId ?? evt.runId;
emitChatDelta(sessionKey, clientRunId, evt.seq, evt.data.text);
} else if (jobState === "done" || jobState === "error") {
if (chatLink) {
const finished = chatRunState.registry.shift(evt.runId);
if (!finished) {
clearAgentRunContext(evt.runId);
return;
}
emitChatFinal(
finished.sessionKey,
finished.clientRunId,
evt.seq,
jobState,
evt.data?.error,
);
} else {
emitChatFinal(
sessionKey,
evt.runId,
evt.seq,
jobState,
evt.data?.error,
);
}
}
}
if (jobState === "done" || jobState === "error") {
clearAgentRunContext(evt.runId);
}
};
}
+9
View File
@@ -0,0 +1,9 @@
export const MAX_PAYLOAD_BYTES = 512 * 1024; // cap incoming frame size
export const MAX_BUFFERED_BYTES = 1.5 * 1024 * 1024; // per-connection send buffer limit
export const MAX_CHAT_HISTORY_MESSAGES_BYTES = 6 * 1024 * 1024; // keep history responses comfortably under client WS limits
export const HANDSHAKE_TIMEOUT_MS = 10_000;
export const TICK_INTERVAL_MS = 30_000;
export const HEALTH_REFRESH_INTERVAL_MS = 60_000;
export const DEDUPE_TTL_MS = 5 * 60_000;
export const DEDUPE_MAX = 1000;
+76
View File
@@ -0,0 +1,76 @@
import fs from "node:fs";
import path from "node:path";
import { getTailnetHostname } from "../infra/tailscale.js";
import { runExec } from "../process/exec.js";
export type ResolveBonjourCliPathOptions = {
env?: NodeJS.ProcessEnv;
argv?: string[];
execPath?: string;
cwd?: string;
statSync?: (path: string) => fs.Stats;
};
export function formatBonjourInstanceName(displayName: string) {
const trimmed = displayName.trim();
if (!trimmed) return "Clawdis";
if (/clawdis/i.test(trimmed)) return trimmed;
return `${trimmed} (Clawdis)`;
}
export function resolveBonjourCliPath(
opts: ResolveBonjourCliPathOptions = {},
): string | undefined {
const env = opts.env ?? process.env;
const envPath = env.CLAWDIS_CLI_PATH?.trim();
if (envPath) return envPath;
const statSync = opts.statSync ?? fs.statSync;
const isFile = (candidate: string) => {
try {
return statSync(candidate).isFile();
} catch {
return false;
}
};
const execPath = opts.execPath ?? process.execPath;
const execDir = path.dirname(execPath);
const siblingCli = path.join(execDir, "clawdis");
if (isFile(siblingCli)) return siblingCli;
const argv = opts.argv ?? process.argv;
const argvPath = argv[1];
if (argvPath && isFile(argvPath)) {
const base = path.basename(argvPath);
if (!base.includes("gateway-daemon")) return argvPath;
}
const cwd = opts.cwd ?? process.cwd();
const distCli = path.join(cwd, "dist", "index.js");
if (isFile(distCli)) return distCli;
const binCli = path.join(cwd, "bin", "clawdis.js");
if (isFile(binCli)) return binCli;
return undefined;
}
export async function resolveTailnetDnsHint(opts?: {
env?: NodeJS.ProcessEnv;
exec?: typeof runExec;
}): Promise<string | undefined> {
const env = opts?.env ?? process.env;
const envRaw = env.CLAWDIS_TAILNET_DNS?.trim();
const envValue = envRaw && envRaw.length > 0 ? envRaw.replace(/\.$/, "") : "";
if (envValue) return envValue;
const exec =
opts?.exec ??
((command, args) =>
runExec(command, args, { timeoutMs: 1500, maxBuffer: 200_000 }));
try {
return await getTailnetHostname(exec);
} catch {
return undefined;
}
}
+254
View File
@@ -0,0 +1,254 @@
import {
createServer as createHttpServer,
type Server as HttpServer,
type IncomingMessage,
type ServerResponse,
} from "node:http";
import type { WebSocketServer } from "ws";
import { handleA2uiHttpRequest } from "../canvas-host/a2ui.js";
import type { CanvasHostHandler } from "../canvas-host/server.js";
import type { createSubsystemLogger } from "../logging.js";
import { handleControlUiHttpRequest } from "./control-ui.js";
import {
extractHookToken,
type HooksConfigResolved,
normalizeAgentPayload,
normalizeHookHeaders,
normalizeWakePayload,
readJsonBody,
} from "./hooks.js";
import { applyHookMappings } from "./hooks-mapping.js";
type SubsystemLogger = ReturnType<typeof createSubsystemLogger>;
type HookDispatchers = {
dispatchWakeHook: (value: {
text: string;
mode: "now" | "next-heartbeat";
}) => void;
dispatchAgentHook: (value: {
message: string;
name: string;
wakeMode: "now" | "next-heartbeat";
sessionKey: string;
deliver: boolean;
channel:
| "last"
| "whatsapp"
| "telegram"
| "discord"
| "signal"
| "imessage";
to?: string;
thinking?: string;
timeoutSeconds?: number;
}) => string;
};
function sendJson(res: ServerResponse, status: number, body: unknown) {
res.statusCode = status;
res.setHeader("Content-Type", "application/json; charset=utf-8");
res.end(JSON.stringify(body));
}
export type HooksRequestHandler = (
req: IncomingMessage,
res: ServerResponse,
) => Promise<boolean>;
export function createHooksRequestHandler(
opts: {
hooksConfig: HooksConfigResolved | null;
bindHost: string;
port: number;
logHooks: SubsystemLogger;
} & HookDispatchers,
): HooksRequestHandler {
const {
hooksConfig,
bindHost,
port,
logHooks,
dispatchAgentHook,
dispatchWakeHook,
} = opts;
return async (req, res) => {
if (!hooksConfig) return false;
const url = new URL(req.url ?? "/", `http://${bindHost}:${port}`);
const basePath = hooksConfig.basePath;
if (url.pathname !== basePath && !url.pathname.startsWith(`${basePath}/`)) {
return false;
}
const token = extractHookToken(req, url);
if (!token || token !== hooksConfig.token) {
res.statusCode = 401;
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.end("Unauthorized");
return true;
}
if (req.method !== "POST") {
res.statusCode = 405;
res.setHeader("Allow", "POST");
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.end("Method Not Allowed");
return true;
}
const subPath = url.pathname.slice(basePath.length).replace(/^\/+/, "");
if (!subPath) {
res.statusCode = 404;
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.end("Not Found");
return true;
}
const body = await readJsonBody(req, hooksConfig.maxBodyBytes);
if (!body.ok) {
const status = body.error === "payload too large" ? 413 : 400;
sendJson(res, status, { ok: false, error: body.error });
return true;
}
const payload =
typeof body.value === "object" && body.value !== null ? body.value : {};
const headers = normalizeHookHeaders(req);
if (subPath === "wake") {
const normalized = normalizeWakePayload(
payload as Record<string, unknown>,
);
if (!normalized.ok) {
sendJson(res, 400, { ok: false, error: normalized.error });
return true;
}
dispatchWakeHook(normalized.value);
sendJson(res, 200, { ok: true, mode: normalized.value.mode });
return true;
}
if (subPath === "agent") {
const normalized = normalizeAgentPayload(
payload as Record<string, unknown>,
);
if (!normalized.ok) {
sendJson(res, 400, { ok: false, error: normalized.error });
return true;
}
const runId = dispatchAgentHook(normalized.value);
sendJson(res, 202, { ok: true, runId });
return true;
}
if (hooksConfig.mappings.length > 0) {
try {
const mapped = await applyHookMappings(hooksConfig.mappings, {
payload: payload as Record<string, unknown>,
headers,
url,
path: subPath,
});
if (mapped) {
if (!mapped.ok) {
sendJson(res, 400, { ok: false, error: mapped.error });
return true;
}
if (mapped.action === null) {
res.statusCode = 204;
res.end();
return true;
}
if (mapped.action.kind === "wake") {
dispatchWakeHook({
text: mapped.action.text,
mode: mapped.action.mode,
});
sendJson(res, 200, { ok: true, mode: mapped.action.mode });
return true;
}
const runId = dispatchAgentHook({
message: mapped.action.message,
name: mapped.action.name ?? "Hook",
wakeMode: mapped.action.wakeMode,
sessionKey: mapped.action.sessionKey ?? "",
deliver: mapped.action.deliver === true,
channel: mapped.action.channel ?? "last",
to: mapped.action.to,
thinking: mapped.action.thinking,
timeoutSeconds: mapped.action.timeoutSeconds,
});
sendJson(res, 202, { ok: true, runId });
return true;
}
} catch (err) {
logHooks.warn(`hook mapping failed: ${String(err)}`);
sendJson(res, 500, { ok: false, error: "hook mapping failed" });
return true;
}
}
res.statusCode = 404;
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.end("Not Found");
return true;
};
}
export function createGatewayHttpServer(opts: {
canvasHost: CanvasHostHandler | null;
controlUiEnabled: boolean;
controlUiBasePath: string;
handleHooksRequest: HooksRequestHandler;
}): HttpServer {
const {
canvasHost,
controlUiEnabled,
controlUiBasePath,
handleHooksRequest,
} = opts;
const httpServer: HttpServer = createHttpServer((req, res) => {
// Don't interfere with WebSocket upgrades; ws handles the 'upgrade' event.
if (String(req.headers.upgrade ?? "").toLowerCase() === "websocket") return;
void (async () => {
if (await handleHooksRequest(req, res)) return;
if (canvasHost) {
if (await handleA2uiHttpRequest(req, res)) return;
if (await canvasHost.handleHttpRequest(req, res)) return;
}
if (controlUiEnabled) {
if (
handleControlUiHttpRequest(req, res, {
basePath: controlUiBasePath,
})
)
return;
}
res.statusCode = 404;
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.end("Not Found");
})().catch((err) => {
res.statusCode = 500;
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.end(String(err));
});
});
return httpServer;
}
export function attachGatewayUpgradeHandler(opts: {
httpServer: HttpServer;
wss: WebSocketServer;
canvasHost: CanvasHostHandler | null;
}) {
const { httpServer, wss, canvasHost } = opts;
httpServer.on("upgrade", (req, socket, head) => {
if (canvasHost?.handleUpgrade(req, socket, head)) return;
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit("connection", ws, req);
});
});
}
File diff suppressed because it is too large. Load diff
+674
View File
@@ -0,0 +1,674 @@
import type { ClawdisConfig } from "../config/config.js";
import { monitorDiscordProvider } from "../discord/index.js";
import { probeDiscord } from "../discord/probe.js";
import { shouldLogVerbose } from "../globals.js";
import { monitorIMessageProvider } from "../imessage/index.js";
import type { createSubsystemLogger } from "../logging.js";
import { monitorWebProvider, webAuthExists } from "../providers/web/index.js";
import type { RuntimeEnv } from "../runtime.js";
import { monitorSignalProvider } from "../signal/index.js";
import { monitorTelegramProvider } from "../telegram/monitor.js";
import { probeTelegram } from "../telegram/probe.js";
import { resolveTelegramToken } from "../telegram/token.js";
import type { WebProviderStatus } from "../web/auto-reply.js";
import { readWebSelfId } from "../web/session.js";
import { formatError } from "./server-utils.js";
export type TelegramRuntimeStatus = {
running: boolean;
lastStartAt?: number | null;
lastStopAt?: number | null;
lastError?: string | null;
mode?: "webhook" | "polling" | null;
};
export type DiscordRuntimeStatus = {
running: boolean;
lastStartAt?: number | null;
lastStopAt?: number | null;
lastError?: string | null;
};
export type SignalRuntimeStatus = {
running: boolean;
lastStartAt?: number | null;
lastStopAt?: number | null;
lastError?: string | null;
baseUrl?: string | null;
};
export type IMessageRuntimeStatus = {
running: boolean;
lastStartAt?: number | null;
lastStopAt?: number | null;
lastError?: string | null;
cliPath?: string | null;
dbPath?: string | null;
};
export type ProviderRuntimeSnapshot = {
whatsapp: WebProviderStatus;
telegram: TelegramRuntimeStatus;
discord: DiscordRuntimeStatus;
signal: SignalRuntimeStatus;
imessage: IMessageRuntimeStatus;
};
type SubsystemLogger = ReturnType<typeof createSubsystemLogger>;
type ProviderManagerOptions = {
loadConfig: () => ClawdisConfig;
logWhatsApp: SubsystemLogger;
logTelegram: SubsystemLogger;
logDiscord: SubsystemLogger;
logSignal: SubsystemLogger;
logIMessage: SubsystemLogger;
whatsappRuntimeEnv: RuntimeEnv;
telegramRuntimeEnv: RuntimeEnv;
discordRuntimeEnv: RuntimeEnv;
signalRuntimeEnv: RuntimeEnv;
imessageRuntimeEnv: RuntimeEnv;
};
export type ProviderManager = {
getRuntimeSnapshot: () => ProviderRuntimeSnapshot;
startProviders: () => Promise<void>;
startWhatsAppProvider: () => Promise<void>;
stopWhatsAppProvider: () => Promise<void>;
startTelegramProvider: () => Promise<void>;
stopTelegramProvider: () => Promise<void>;
startDiscordProvider: () => Promise<void>;
stopDiscordProvider: () => Promise<void>;
startSignalProvider: () => Promise<void>;
stopSignalProvider: () => Promise<void>;
startIMessageProvider: () => Promise<void>;
stopIMessageProvider: () => Promise<void>;
markWhatsAppLoggedOut: (cleared: boolean) => void;
};
export function createProviderManager(
opts: ProviderManagerOptions,
): ProviderManager {
const {
loadConfig,
logWhatsApp,
logTelegram,
logDiscord,
logSignal,
logIMessage,
whatsappRuntimeEnv,
telegramRuntimeEnv,
discordRuntimeEnv,
signalRuntimeEnv,
imessageRuntimeEnv,
} = opts;
let whatsappAbort: AbortController | null = null;
let telegramAbort: AbortController | null = null;
let discordAbort: AbortController | null = null;
let signalAbort: AbortController | null = null;
let imessageAbort: AbortController | null = null;
let whatsappTask: Promise<unknown> | null = null;
let telegramTask: Promise<unknown> | null = null;
let discordTask: Promise<unknown> | null = null;
let signalTask: Promise<unknown> | null = null;
let imessageTask: Promise<unknown> | null = null;
let whatsappRuntime: WebProviderStatus = {
running: false,
connected: false,
reconnectAttempts: 0,
lastConnectedAt: null,
lastDisconnect: null,
lastMessageAt: null,
lastEventAt: null,
lastError: null,
};
let telegramRuntime: TelegramRuntimeStatus = {
running: false,
lastStartAt: null,
lastStopAt: null,
lastError: null,
mode: null,
};
let discordRuntime: DiscordRuntimeStatus = {
running: false,
lastStartAt: null,
lastStopAt: null,
lastError: null,
};
let signalRuntime: SignalRuntimeStatus = {
running: false,
lastStartAt: null,
lastStopAt: null,
lastError: null,
baseUrl: null,
};
let imessageRuntime: IMessageRuntimeStatus = {
running: false,
lastStartAt: null,
lastStopAt: null,
lastError: null,
cliPath: null,
dbPath: null,
};
const updateWhatsAppStatus = (next: WebProviderStatus) => {
whatsappRuntime = next;
};
const startWhatsAppProvider = async () => {
if (whatsappTask) return;
const cfg = loadConfig();
if (cfg.web?.enabled === false) {
whatsappRuntime = {
...whatsappRuntime,
running: false,
connected: false,
lastError: "disabled",
};
logWhatsApp.info("skipping provider start (web.enabled=false)");
return;
}
if (!(await webAuthExists())) {
whatsappRuntime = {
...whatsappRuntime,
running: false,
connected: false,
lastError: "not linked",
};
logWhatsApp.info("skipping provider start (no linked session)");
return;
}
const { e164, jid } = readWebSelfId();
const identity = e164 ? e164 : jid ? `jid ${jid}` : "unknown";
logWhatsApp.info(`starting provider (${identity})`);
whatsappAbort = new AbortController();
whatsappRuntime = {
...whatsappRuntime,
running: true,
connected: false,
lastError: null,
};
const task = monitorWebProvider(
shouldLogVerbose(),
undefined,
true,
undefined,
whatsappRuntimeEnv,
whatsappAbort.signal,
{ statusSink: updateWhatsAppStatus },
)
.catch((err) => {
whatsappRuntime = {
...whatsappRuntime,
lastError: formatError(err),
};
logWhatsApp.error(`provider exited: ${formatError(err)}`);
})
.finally(() => {
whatsappAbort = null;
whatsappTask = null;
whatsappRuntime = {
...whatsappRuntime,
running: false,
connected: false,
};
});
whatsappTask = task;
};
const stopWhatsAppProvider = async () => {
if (!whatsappAbort && !whatsappTask) return;
whatsappAbort?.abort();
try {
await whatsappTask;
} catch {
// ignore
}
whatsappAbort = null;
whatsappTask = null;
whatsappRuntime = {
...whatsappRuntime,
running: false,
connected: false,
};
};
const startTelegramProvider = async () => {
if (telegramTask) return;
const cfg = loadConfig();
if (cfg.telegram?.enabled === false) {
telegramRuntime = {
...telegramRuntime,
running: false,
lastError: "disabled",
};
if (shouldLogVerbose()) {
logTelegram.debug(
"telegram provider disabled (telegram.enabled=false)",
);
}
return;
}
const { token: telegramToken } = resolveTelegramToken(cfg, {
logMissingFile: (message) => logTelegram.warn(message),
});
if (!telegramToken.trim()) {
telegramRuntime = {
...telegramRuntime,
running: false,
lastError: "not configured",
};
// keep quiet by default; this is a normal state
if (shouldLogVerbose()) {
logTelegram.debug(
"telegram provider not configured (no TELEGRAM_BOT_TOKEN)",
);
}
return;
}
let telegramBotLabel = "";
try {
const probe = await probeTelegram(
telegramToken.trim(),
2500,
cfg.telegram?.proxy,
);
const username = probe.ok ? probe.bot?.username?.trim() : null;
if (username) telegramBotLabel = ` (@${username})`;
} catch (err) {
if (shouldLogVerbose()) {
logTelegram.debug(`bot probe failed: ${String(err)}`);
}
}
logTelegram.info(
`starting provider${telegramBotLabel}${cfg.telegram ? "" : " (no telegram config; token via env)"}`,
);
telegramAbort = new AbortController();
telegramRuntime = {
...telegramRuntime,
running: true,
lastStartAt: Date.now(),
lastError: null,
mode: cfg.telegram?.webhookUrl ? "webhook" : "polling",
};
const task = monitorTelegramProvider({
token: telegramToken.trim(),
runtime: telegramRuntimeEnv,
abortSignal: telegramAbort.signal,
useWebhook: Boolean(cfg.telegram?.webhookUrl),
webhookUrl: cfg.telegram?.webhookUrl,
webhookSecret: cfg.telegram?.webhookSecret,
webhookPath: cfg.telegram?.webhookPath,
})
.catch((err) => {
telegramRuntime = {
...telegramRuntime,
lastError: formatError(err),
};
logTelegram.error(`provider exited: ${formatError(err)}`);
})
.finally(() => {
telegramAbort = null;
telegramTask = null;
telegramRuntime = {
...telegramRuntime,
running: false,
lastStopAt: Date.now(),
};
});
telegramTask = task;
};
const stopTelegramProvider = async () => {
if (!telegramAbort && !telegramTask) return;
telegramAbort?.abort();
try {
await telegramTask;
} catch {
// ignore
}
telegramAbort = null;
telegramTask = null;
telegramRuntime = {
...telegramRuntime,
running: false,
lastStopAt: Date.now(),
};
};
const startDiscordProvider = async () => {
if (discordTask) return;
const cfg = loadConfig();
if (cfg.discord?.enabled === false) {
discordRuntime = {
...discordRuntime,
running: false,
lastError: "disabled",
};
if (shouldLogVerbose()) {
logDiscord.debug("discord provider disabled (discord.enabled=false)");
}
return;
}
const discordToken =
process.env.DISCORD_BOT_TOKEN ?? cfg.discord?.token ?? "";
if (!discordToken.trim()) {
discordRuntime = {
...discordRuntime,
running: false,
lastError: "not configured",
};
// keep quiet by default; this is a normal state
if (shouldLogVerbose()) {
logDiscord.debug(
"discord provider not configured (no DISCORD_BOT_TOKEN)",
);
}
return;
}
let discordBotLabel = "";
try {
const probe = await probeDiscord(discordToken.trim(), 2500);
const username = probe.ok ? probe.bot?.username?.trim() : null;
if (username) discordBotLabel = ` (@${username})`;
} catch (err) {
if (shouldLogVerbose()) {
logDiscord.debug(`bot probe failed: ${String(err)}`);
}
}
logDiscord.info(
`starting provider${discordBotLabel}${cfg.discord ? "" : " (no discord config; token via env)"}`,
);
discordAbort = new AbortController();
discordRuntime = {
...discordRuntime,
running: true,
lastStartAt: Date.now(),
lastError: null,
};
const task = monitorDiscordProvider({
token: discordToken.trim(),
runtime: discordRuntimeEnv,
abortSignal: discordAbort.signal,
slashCommand: cfg.discord?.slashCommand,
mediaMaxMb: cfg.discord?.mediaMaxMb,
historyLimit: cfg.discord?.historyLimit,
})
.catch((err) => {
discordRuntime = {
...discordRuntime,
lastError: formatError(err),
};
logDiscord.error(`provider exited: ${formatError(err)}`);
})
.finally(() => {
discordAbort = null;
discordTask = null;
discordRuntime = {
...discordRuntime,
running: false,
lastStopAt: Date.now(),
};
});
discordTask = task;
};
const stopDiscordProvider = async () => {
if (!discordAbort && !discordTask) return;
discordAbort?.abort();
try {
await discordTask;
} catch {
// ignore
}
discordAbort = null;
discordTask = null;
discordRuntime = {
...discordRuntime,
running: false,
lastStopAt: Date.now(),
};
};
const startSignalProvider = async () => {
if (signalTask) return;
const cfg = loadConfig();
if (!cfg.signal) {
signalRuntime = {
...signalRuntime,
running: false,
lastError: "not configured",
};
// keep quiet by default; this is a normal state
if (shouldLogVerbose()) {
logSignal.debug("signal provider not configured (no signal config)");
}
return;
}
if (cfg.signal?.enabled === false) {
signalRuntime = {
...signalRuntime,
running: false,
lastError: "disabled",
};
if (shouldLogVerbose()) {
logSignal.debug("signal provider disabled (signal.enabled=false)");
}
return;
}
const signalCfg = cfg.signal;
const signalMeaningfullyConfigured = Boolean(
signalCfg.account?.trim() ||
signalCfg.httpUrl?.trim() ||
signalCfg.cliPath?.trim() ||
signalCfg.httpHost?.trim() ||
typeof signalCfg.httpPort === "number" ||
typeof signalCfg.autoStart === "boolean",
);
if (!signalMeaningfullyConfigured) {
signalRuntime = {
...signalRuntime,
running: false,
lastError: "not configured",
};
// keep quiet by default; this is a normal state
if (shouldLogVerbose()) {
logSignal.debug(
"signal provider not configured (signal config present but missing required fields)",
);
}
return;
}
const host = cfg.signal?.httpHost?.trim() || "127.0.0.1";
const port = cfg.signal?.httpPort ?? 8080;
const baseUrl = cfg.signal?.httpUrl?.trim() || `http://${host}:${port}`;
logSignal.info(`starting provider (${baseUrl})`);
signalAbort = new AbortController();
signalRuntime = {
...signalRuntime,
running: true,
lastStartAt: Date.now(),
lastError: null,
baseUrl,
};
const task = monitorSignalProvider({
baseUrl,
account: cfg.signal?.account,
cliPath: cfg.signal?.cliPath,
httpHost: cfg.signal?.httpHost,
httpPort: cfg.signal?.httpPort,
autoStart:
typeof cfg.signal?.autoStart === "boolean"
? cfg.signal.autoStart
: undefined,
runtime: signalRuntimeEnv,
abortSignal: signalAbort.signal,
})
.catch((err) => {
signalRuntime = {
...signalRuntime,
lastError: formatError(err),
};
logSignal.error(`provider exited: ${formatError(err)}`);
})
.finally(() => {
signalAbort = null;
signalTask = null;
signalRuntime = {
...signalRuntime,
running: false,
lastStopAt: Date.now(),
};
});
signalTask = task;
};
const stopSignalProvider = async () => {
if (!signalAbort && !signalTask) return;
signalAbort?.abort();
try {
await signalTask;
} catch {
// ignore
}
signalAbort = null;
signalTask = null;
signalRuntime = {
...signalRuntime,
running: false,
lastStopAt: Date.now(),
};
};
const startIMessageProvider = async () => {
if (imessageTask) return;
const cfg = loadConfig();
if (!cfg.imessage) {
imessageRuntime = {
...imessageRuntime,
running: false,
lastError: "not configured",
};
// keep quiet by default; this is a normal state
if (shouldLogVerbose()) {
logIMessage.debug(
"imessage provider not configured (no imessage config)",
);
}
return;
}
if (cfg.imessage?.enabled === false) {
imessageRuntime = {
...imessageRuntime,
running: false,
lastError: "disabled",
};
if (shouldLogVerbose()) {
logIMessage.debug(
"imessage provider disabled (imessage.enabled=false)",
);
}
return;
}
const cliPath = cfg.imessage?.cliPath?.trim() || "imsg";
const dbPath = cfg.imessage?.dbPath?.trim();
logIMessage.info(
`starting provider (${cliPath}${dbPath ? ` db=${dbPath}` : ""})`,
);
imessageAbort = new AbortController();
imessageRuntime = {
...imessageRuntime,
running: true,
lastStartAt: Date.now(),
lastError: null,
cliPath,
dbPath: dbPath ?? null,
};
const task = monitorIMessageProvider({
cliPath,
dbPath,
allowFrom: cfg.imessage?.allowFrom,
includeAttachments: cfg.imessage?.includeAttachments,
mediaMaxMb: cfg.imessage?.mediaMaxMb,
runtime: imessageRuntimeEnv,
abortSignal: imessageAbort.signal,
})
.catch((err) => {
imessageRuntime = {
...imessageRuntime,
lastError: formatError(err),
};
logIMessage.error(`provider exited: ${formatError(err)}`);
})
.finally(() => {
imessageAbort = null;
imessageTask = null;
imessageRuntime = {
...imessageRuntime,
running: false,
lastStopAt: Date.now(),
};
});
imessageTask = task;
};
const stopIMessageProvider = async () => {
if (!imessageAbort && !imessageTask) return;
imessageAbort?.abort();
try {
await imessageTask;
} catch {
// ignore
}
imessageAbort = null;
imessageTask = null;
imessageRuntime = {
...imessageRuntime,
running: false,
lastStopAt: Date.now(),
};
};
const startProviders = async () => {
await startWhatsAppProvider();
await startDiscordProvider();
await startTelegramProvider();
await startSignalProvider();
await startIMessageProvider();
};
const markWhatsAppLoggedOut = (cleared: boolean) => {
whatsappRuntime = {
...whatsappRuntime,
running: false,
connected: false,
lastError: cleared ? "logged out" : whatsappRuntime.lastError,
};
};
const getRuntimeSnapshot = (): ProviderRuntimeSnapshot => ({
whatsapp: { ...whatsappRuntime },
telegram: { ...telegramRuntime },
discord: { ...discordRuntime },
signal: { ...signalRuntime },
imessage: { ...imessageRuntime },
});
return {
getRuntimeSnapshot,
startProviders,
startWhatsAppProvider,
stopWhatsAppProvider,
startTelegramProvider,
stopTelegramProvider,
startDiscordProvider,
stopDiscordProvider,
startSignalProvider,
stopSignalProvider,
startIMessageProvider,
stopIMessageProvider,
markWhatsAppLoggedOut,
};
}
+8
View File
@@ -0,0 +1,8 @@
import type { ErrorShape } from "./protocol/index.js";
export type DedupeEntry = {
ts: number;
ok: boolean;
payload?: unknown;
error?: ErrorShape;
};
+31
View File
@@ -0,0 +1,31 @@
import { describe, expect, test } from "vitest";
import { defaultVoiceWakeTriggers } from "../infra/voicewake.js";
import { formatError, normalizeVoiceWakeTriggers } from "./server-utils.js";
describe("normalizeVoiceWakeTriggers", () => {
test("returns defaults when input is empty", () => {
expect(normalizeVoiceWakeTriggers([])).toEqual(defaultVoiceWakeTriggers());
expect(normalizeVoiceWakeTriggers(null)).toEqual(
defaultVoiceWakeTriggers(),
);
});
test("trims and limits entries", () => {
const result = normalizeVoiceWakeTriggers([" hello ", "", "world"]);
expect(result).toEqual(["hello", "world"]);
});
});
describe("formatError", () => {
test("prefers message for Error", () => {
expect(formatError(new Error("boom"))).toBe("boom");
});
test("handles status/code", () => {
expect(formatError({ status: 500, code: "EPIPE" })).toBe(
"status=500 code=EPIPE",
);
expect(formatError({ status: 404 })).toBe("status=404 code=unknown");
expect(formatError({ code: "ENOENT" })).toBe("status=unknown code=ENOENT");
});
});
+36
View File
@@ -0,0 +1,36 @@
import { defaultVoiceWakeTriggers } from "../infra/voicewake.js";
export function normalizeVoiceWakeTriggers(input: unknown): string[] {
const raw = Array.isArray(input) ? input : [];
const cleaned = raw
.map((v) => (typeof v === "string" ? v.trim() : ""))
.filter((v) => v.length > 0)
.slice(0, 32)
.map((v) => v.slice(0, 64));
return cleaned.length > 0 ? cleaned : defaultVoiceWakeTriggers();
}
export function formatError(err: unknown): string {
if (err instanceof Error) return err.message;
if (typeof err === "string") return err;
const statusValue = (err as { status?: unknown })?.status;
const codeValue = (err as { code?: unknown })?.code;
const hasStatus = statusValue !== undefined;
const hasCode = codeValue !== undefined;
if (hasStatus || hasCode) {
const statusText =
typeof statusValue === "string" || typeof statusValue === "number"
? String(statusValue)
: "unknown";
const codeText =
typeof codeValue === "string" || typeof codeValue === "number"
? String(codeValue)
: "unknown";
return `status=${statusText} code=${codeText}`;
}
try {
return JSON.stringify(err, null, 2);
} catch {
return String(err);
}
}
+520
View File
@@ -0,0 +1,520 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, test, vi } from "vitest";
import { WebSocket } from "ws";
import {
emitAgentEvent,
registerAgentRunContext,
} from "../infra/agent-events.js";
import {
agentCommand,
connectOk,
getFreePort,
installGatewayTestHooks,
onceMessage,
rpcReq,
startGatewayServer,
startServerWithClient,
testState,
} from "./test-helpers.js";
installGatewayTestHooks();
describe("gateway server agent", () => {
test("agent falls back to allowFrom when lastTo is stale", async () => {
testState.allowFrom = ["+436769770569"];
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-main-stale",
updatedAt: Date.now(),
lastChannel: "whatsapp",
lastTo: "+1555",
},
},
null,
2,
),
"utf-8",
);
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const res = await rpcReq(ws, "agent", {
message: "hi",
sessionKey: "main",
channel: "last",
deliver: true,
idempotencyKey: "idem-agent-last-stale",
});
expect(res.ok).toBe(true);
const spy = vi.mocked(agentCommand);
const call = spy.mock.calls.at(-1)?.[0] as Record<string, unknown>;
expect(call.provider).toBe("whatsapp");
expect(call.to).toBe("+436769770569");
expect(call.sessionId).toBe("sess-main-stale");
ws.close();
await server.close();
testState.allowFrom = undefined;
});
test("agent routes main last-channel whatsapp", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-main-whatsapp",
updatedAt: Date.now(),
lastChannel: "whatsapp",
lastTo: "+1555",
},
},
null,
2,
),
"utf-8",
);
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const res = await rpcReq(ws, "agent", {
message: "hi",
sessionKey: "main",
channel: "last",
deliver: true,
idempotencyKey: "idem-agent-last-whatsapp",
});
expect(res.ok).toBe(true);
const spy = vi.mocked(agentCommand);
const call = spy.mock.calls.at(-1)?.[0] as Record<string, unknown>;
expect(call.provider).toBe("whatsapp");
expect(call.to).toBe("+1555");
expect(call.deliver).toBe(true);
expect(call.bestEffortDeliver).toBe(true);
expect(call.sessionId).toBe("sess-main-whatsapp");
ws.close();
await server.close();
});
test("agent routes main last-channel telegram", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-main",
updatedAt: Date.now(),
lastChannel: "telegram",
lastTo: "123",
},
},
null,
2,
),
"utf-8",
);
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const res = await rpcReq(ws, "agent", {
message: "hi",
sessionKey: "main",
channel: "last",
deliver: true,
idempotencyKey: "idem-agent-last",
});
expect(res.ok).toBe(true);
const spy = vi.mocked(agentCommand);
const call = spy.mock.calls.at(-1)?.[0] as Record<string, unknown>;
expect(call.provider).toBe("telegram");
expect(call.to).toBe("123");
expect(call.deliver).toBe(true);
expect(call.bestEffortDeliver).toBe(true);
expect(call.sessionId).toBe("sess-main");
ws.close();
await server.close();
});
test("agent routes main last-channel discord", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-discord",
updatedAt: Date.now(),
lastChannel: "discord",
lastTo: "channel:discord-123",
},
},
null,
2,
),
"utf-8",
);
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const res = await rpcReq(ws, "agent", {
message: "hi",
sessionKey: "main",
channel: "last",
deliver: true,
idempotencyKey: "idem-agent-last-discord",
});
expect(res.ok).toBe(true);
const spy = vi.mocked(agentCommand);
const call = spy.mock.calls.at(-1)?.[0] as Record<string, unknown>;
expect(call.provider).toBe("discord");
expect(call.to).toBe("channel:discord-123");
expect(call.deliver).toBe(true);
expect(call.bestEffortDeliver).toBe(true);
expect(call.sessionId).toBe("sess-discord");
ws.close();
await server.close();
});
test("agent routes main last-channel signal", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-signal",
updatedAt: Date.now(),
lastChannel: "signal",
lastTo: "+15551234567",
},
},
null,
2,
),
"utf-8",
);
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const res = await rpcReq(ws, "agent", {
message: "hi",
sessionKey: "main",
channel: "last",
deliver: true,
idempotencyKey: "idem-agent-last-signal",
});
expect(res.ok).toBe(true);
const spy = vi.mocked(agentCommand);
const call = spy.mock.calls.at(-1)?.[0] as Record<string, unknown>;
expect(call.provider).toBe("signal");
expect(call.to).toBe("+15551234567");
expect(call.deliver).toBe(true);
expect(call.bestEffortDeliver).toBe(true);
expect(call.sessionId).toBe("sess-signal");
ws.close();
await server.close();
});
test("agent ignores webchat last-channel for routing", async () => {
testState.allowFrom = ["+1555"];
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-main-webchat",
updatedAt: Date.now(),
lastChannel: "webchat",
lastTo: "+1555",
},
},
null,
2,
),
"utf-8",
);
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const res = await rpcReq(ws, "agent", {
message: "hi",
sessionKey: "main",
channel: "last",
deliver: true,
idempotencyKey: "idem-agent-webchat",
});
expect(res.ok).toBe(true);
const spy = vi.mocked(agentCommand);
const call = spy.mock.calls.at(-1)?.[0] as Record<string, unknown>;
expect(call.provider).toBe("whatsapp");
expect(call.to).toBe("+1555");
expect(call.deliver).toBe(true);
expect(call.bestEffortDeliver).toBe(true);
expect(call.sessionId).toBe("sess-main-webchat");
ws.close();
await server.close();
});
test(
"agent ack response then final response",
{ timeout: 8000 },
async () => {
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const ackP = onceMessage(
ws,
(o) =>
o.type === "res" &&
o.id === "ag1" &&
o.payload?.status === "accepted",
);
const finalP = onceMessage(
ws,
(o) =>
o.type === "res" &&
o.id === "ag1" &&
o.payload?.status !== "accepted",
);
ws.send(
JSON.stringify({
type: "req",
id: "ag1",
method: "agent",
params: { message: "hi", idempotencyKey: "idem-ag" },
}),
);
const ack = await ackP;
const final = await finalP;
expect(ack.payload.runId).toBeDefined();
expect(final.payload.runId).toBe(ack.payload.runId);
expect(final.payload.status).toBe("ok");
ws.close();
await server.close();
},
);
test("agent dedupes by idempotencyKey after completion", async () => {
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const firstFinalP = onceMessage(
ws,
(o) =>
o.type === "res" && o.id === "ag1" && o.payload?.status !== "accepted",
);
ws.send(
JSON.stringify({
type: "req",
id: "ag1",
method: "agent",
params: { message: "hi", idempotencyKey: "same-agent" },
}),
);
const firstFinal = await firstFinalP;
const secondP = onceMessage(ws, (o) => o.type === "res" && o.id === "ag2");
ws.send(
JSON.stringify({
type: "req",
id: "ag2",
method: "agent",
params: { message: "hi again", idempotencyKey: "same-agent" },
}),
);
const second = await secondP;
expect(second.payload).toEqual(firstFinal.payload);
ws.close();
await server.close();
});
test("agent dedupe survives reconnect", { timeout: 15000 }, async () => {
const port = await getFreePort();
const server = await startGatewayServer(port);
const dial = async () => {
const ws = new WebSocket(`ws://127.0.0.1:${port}`);
await new Promise<void>((resolve) => ws.once("open", resolve));
await connectOk(ws);
return ws;
};
const idem = "reconnect-agent";
const ws1 = await dial();
const final1P = onceMessage(
ws1,
(o) =>
o.type === "res" && o.id === "ag1" && o.payload?.status !== "accepted",
6000,
);
ws1.send(
JSON.stringify({
type: "req",
id: "ag1",
method: "agent",
params: { message: "hi", idempotencyKey: idem },
}),
);
const final1 = await final1P;
ws1.close();
const ws2 = await dial();
const final2P = onceMessage(
ws2,
(o) =>
o.type === "res" && o.id === "ag2" && o.payload?.status !== "accepted",
6000,
);
ws2.send(
JSON.stringify({
type: "req",
id: "ag2",
method: "agent",
params: { message: "hi again", idempotencyKey: idem },
}),
);
const res = await final2P;
expect(res.payload).toEqual(final1.payload);
ws2.close();
await server.close();
});
test("agent events stream to webchat clients when run context is registered", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-main",
updatedAt: Date.now(),
},
},
null,
2,
),
"utf-8",
);
const { server, ws } = await startServerWithClient();
await connectOk(ws, {
client: {
name: "webchat",
version: "1.0.0",
platform: "test",
mode: "webchat",
},
});
registerAgentRunContext("run-auto-1", { sessionKey: "main" });
const finalChatP = onceMessage(
ws,
(o) => {
if (o.type !== "event" || o.event !== "chat") return false;
const payload = o.payload as
| { state?: unknown; runId?: unknown }
| undefined;
return payload?.state === "final" && payload.runId === "run-auto-1";
},
8000,
);
emitAgentEvent({
runId: "run-auto-1",
stream: "assistant",
data: { text: "hi from agent" },
});
emitAgentEvent({
runId: "run-auto-1",
stream: "job",
data: { state: "done" },
});
const evt = await finalChatP;
const payload =
evt.payload && typeof evt.payload === "object"
? (evt.payload as Record<string, unknown>)
: {};
expect(payload.sessionKey).toBe("main");
expect(payload.runId).toBe("run-auto-1");
ws.close();
await server.close();
});
test("agent events include sessionKey in agent payloads", async () => {
const { server, ws } = await startServerWithClient();
await connectOk(ws, {
client: {
name: "webchat",
version: "1.0.0",
platform: "test",
mode: "webchat",
},
});
registerAgentRunContext("run-tool-1", { sessionKey: "main" });
const agentEvtP = onceMessage(
ws,
(o) =>
o.type === "event" &&
o.event === "agent" &&
o.payload?.runId === "run-tool-1",
8000,
);
emitAgentEvent({
runId: "run-tool-1",
stream: "tool",
data: { phase: "start", name: "read", toolCallId: "tool-1" },
});
const evt = await agentEvtP;
const payload =
evt.payload && typeof evt.payload === "object"
? (evt.payload as Record<string, unknown>)
: {};
expect(payload.sessionKey).toBe("main");
ws.close();
await server.close();
});
});
+128
View File
@@ -0,0 +1,128 @@
import { describe, expect, test } from "vitest";
import { WebSocket } from "ws";
import { PROTOCOL_VERSION } from "./protocol/index.js";
import {
connectReq,
getFreePort,
installGatewayTestHooks,
onceMessage,
startGatewayServer,
startServerWithClient,
testState,
} from "./test-helpers.js";
installGatewayTestHooks();
describe("gateway server auth/connect", () => {
test(
"closes silent handshakes after timeout",
{ timeout: 15_000 },
async () => {
const { server, ws } = await startServerWithClient();
const closed = await new Promise<boolean>((resolve) => {
const timer = setTimeout(() => resolve(false), 12_000);
ws.once("close", () => {
clearTimeout(timer);
resolve(true);
});
});
expect(closed).toBe(true);
await server.close();
},
);
test("connect (req) handshake returns hello-ok payload", async () => {
const { CONFIG_PATH_CLAWDIS, STATE_DIR_CLAWDIS } = await import(
"../config/config.js"
);
const port = await getFreePort();
const server = await startGatewayServer(port);
const ws = new WebSocket(`ws://127.0.0.1:${port}`);
await new Promise<void>((resolve) => ws.once("open", resolve));
const res = await connectReq(ws);
expect(res.ok).toBe(true);
const payload = res.payload as
| {
type?: unknown;
snapshot?: { configPath?: string; stateDir?: string };
}
| undefined;
expect(payload?.type).toBe("hello-ok");
expect(payload?.snapshot?.configPath).toBe(CONFIG_PATH_CLAWDIS);
expect(payload?.snapshot?.stateDir).toBe(STATE_DIR_CLAWDIS);
ws.close();
await server.close();
});
test("rejects protocol mismatch", async () => {
const { server, ws } = await startServerWithClient();
try {
const res = await connectReq(ws, {
minProtocol: PROTOCOL_VERSION + 1,
maxProtocol: PROTOCOL_VERSION + 2,
});
expect(res.ok).toBe(false);
} catch {
// If the server closed before we saw the frame, that's acceptable.
}
ws.close();
await server.close();
});
test("rejects invalid token", async () => {
const { server, ws, prevToken } = await startServerWithClient("secret");
const res = await connectReq(ws, { token: "wrong" });
expect(res.ok).toBe(false);
expect(res.error?.message ?? "").toContain("unauthorized");
ws.close();
await server.close();
if (prevToken === undefined) {
delete process.env.CLAWDIS_GATEWAY_TOKEN;
} else {
process.env.CLAWDIS_GATEWAY_TOKEN = prevToken;
}
});
test("accepts password auth when configured", async () => {
testState.gatewayAuth = { mode: "password", password: "secret" };
const port = await getFreePort();
const server = await startGatewayServer(port);
const ws = new WebSocket(`ws://127.0.0.1:${port}`);
await new Promise<void>((resolve) => ws.once("open", resolve));
const res = await connectReq(ws, { password: "secret" });
expect(res.ok).toBe(true);
ws.close();
await server.close();
});
test("rejects invalid password", async () => {
testState.gatewayAuth = { mode: "password", password: "secret" };
const port = await getFreePort();
const server = await startGatewayServer(port);
const ws = new WebSocket(`ws://127.0.0.1:${port}`);
await new Promise<void>((resolve) => ws.once("open", resolve));
const res = await connectReq(ws, { password: "wrong" });
expect(res.ok).toBe(false);
expect(res.error?.message ?? "").toContain("unauthorized");
ws.close();
await server.close();
});
test("rejects non-connect first request", async () => {
const { server, ws } = await startServerWithClient();
ws.send(JSON.stringify({ type: "req", id: "h1", method: "health" }));
const res = await onceMessage<{ ok: boolean; error?: unknown }>(
ws,
(o) => o.type === "res" && o.id === "h1",
);
expect(res.ok).toBe(false);
await new Promise<void>((resolve) => ws.once("close", () => resolve()));
await server.close();
});
});
+758
View File
@@ -0,0 +1,758 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, test, vi } from "vitest";
import { emitAgentEvent } from "../infra/agent-events.js";
import {
agentCommand,
connectOk,
installGatewayTestHooks,
onceMessage,
piSdkMock,
rpcReq,
sessionStoreSaveDelayMs,
startServerWithClient,
testState,
} from "./test-helpers.js";
installGatewayTestHooks();
describe("gateway server chat", () => {
test("chat.send accepts image attachment", { timeout: 12000 }, async () => {
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const reqId = "chat-img";
ws.send(
JSON.stringify({
type: "req",
id: reqId,
method: "chat.send",
params: {
sessionKey: "main",
message: "see image",
idempotencyKey: "idem-img",
attachments: [
{
type: "image",
mimeType: "image/png",
fileName: "dot.png",
content:
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/woAAn8B9FD5fHAAAAAASUVORK5CYII=",
},
],
},
}),
);
const res = await onceMessage(
ws,
(o) => o.type === "res" && o.id === reqId,
8000,
);
expect(res.ok).toBe(true);
expect(res.payload?.runId).toBeDefined();
ws.close();
await server.close();
});
test("chat.history caps large histories and honors limit", async () => {
const firstContentText = (msg: unknown): string | undefined => {
if (!msg || typeof msg !== "object") return undefined;
const content = (msg as { content?: unknown }).content;
if (!Array.isArray(content) || content.length === 0) return undefined;
const first = content[0];
if (!first || typeof first !== "object") return undefined;
const text = (first as { text?: unknown }).text;
return typeof text === "string" ? text : undefined;
};
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-main",
updatedAt: Date.now(),
},
},
null,
2,
),
"utf-8",
);
const lines: string[] = [];
for (let i = 0; i < 300; i += 1) {
lines.push(
JSON.stringify({
message: {
role: "user",
content: [{ type: "text", text: `m${i}` }],
timestamp: Date.now() + i,
},
}),
);
}
await fs.writeFile(
path.join(dir, "sess-main.jsonl"),
lines.join("\n"),
"utf-8",
);
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const defaultRes = await rpcReq<{ messages?: unknown[] }>(
ws,
"chat.history",
{
sessionKey: "main",
},
);
expect(defaultRes.ok).toBe(true);
const defaultMsgs = defaultRes.payload?.messages ?? [];
expect(defaultMsgs.length).toBe(200);
expect(firstContentText(defaultMsgs[0])).toBe("m100");
const limitedRes = await rpcReq<{ messages?: unknown[] }>(
ws,
"chat.history",
{
sessionKey: "main",
limit: 5,
},
);
expect(limitedRes.ok).toBe(true);
const limitedMsgs = limitedRes.payload?.messages ?? [];
expect(limitedMsgs.length).toBe(5);
expect(firstContentText(limitedMsgs[0])).toBe("m295");
const largeLines: string[] = [];
for (let i = 0; i < 1500; i += 1) {
largeLines.push(
JSON.stringify({
message: {
role: "user",
content: [{ type: "text", text: `b${i}` }],
timestamp: Date.now() + i,
},
}),
);
}
await fs.writeFile(
path.join(dir, "sess-main.jsonl"),
largeLines.join("\n"),
"utf-8",
);
const cappedRes = await rpcReq<{ messages?: unknown[] }>(
ws,
"chat.history",
{
sessionKey: "main",
},
);
expect(cappedRes.ok).toBe(true);
const cappedMsgs = cappedRes.payload?.messages ?? [];
expect(cappedMsgs.length).toBe(200);
expect(firstContentText(cappedMsgs[0])).toBe("b1300");
const maxRes = await rpcReq<{ messages?: unknown[] }>(ws, "chat.history", {
sessionKey: "main",
limit: 1000,
});
expect(maxRes.ok).toBe(true);
const maxMsgs = maxRes.payload?.messages ?? [];
expect(maxMsgs.length).toBe(1000);
expect(firstContentText(maxMsgs[0])).toBe("b500");
ws.close();
await server.close();
});
test("chat.history defaults thinking to low for reasoning-capable models", async () => {
piSdkMock.enabled = true;
piSdkMock.models = [
{
id: "claude-opus-4-5",
name: "Opus 4.5",
provider: "anthropic",
reasoning: true,
},
];
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-main",
updatedAt: Date.now(),
},
},
null,
2,
),
"utf-8",
);
await fs.writeFile(
path.join(dir, "sess-main.jsonl"),
JSON.stringify({
message: {
role: "user",
content: [{ type: "text", text: "hello" }],
timestamp: Date.now(),
},
}),
"utf-8",
);
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const res = await rpcReq<{ thinkingLevel?: string }>(ws, "chat.history", {
sessionKey: "main",
});
expect(res.ok).toBe(true);
expect(res.payload?.thinkingLevel).toBe("low");
ws.close();
await server.close();
});
test("chat.history caps payload bytes", { timeout: 15_000 }, async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-main",
updatedAt: Date.now(),
},
},
null,
2,
),
"utf-8",
);
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const bigText = "x".repeat(200_000);
const largeLines: string[] = [];
for (let i = 0; i < 40; i += 1) {
largeLines.push(
JSON.stringify({
message: {
role: "user",
content: [{ type: "text", text: `${i}:${bigText}` }],
timestamp: Date.now() + i,
},
}),
);
}
await fs.writeFile(
path.join(dir, "sess-main.jsonl"),
largeLines.join("\n"),
"utf-8",
);
const cappedRes = await rpcReq<{ messages?: unknown[] }>(
ws,
"chat.history",
{ sessionKey: "main", limit: 1000 },
);
expect(cappedRes.ok).toBe(true);
const cappedMsgs = cappedRes.payload?.messages ?? [];
const bytes = Buffer.byteLength(JSON.stringify(cappedMsgs), "utf8");
expect(bytes).toBeLessThanOrEqual(6 * 1024 * 1024);
expect(cappedMsgs.length).toBeLessThan(60);
ws.close();
await server.close();
});
test("chat.send does not overwrite last delivery route", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-main",
updatedAt: Date.now(),
lastChannel: "whatsapp",
lastTo: "+1555",
},
},
null,
2,
),
"utf-8",
);
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const res = await rpcReq(ws, "chat.send", {
sessionKey: "main",
message: "hello",
idempotencyKey: "idem-route",
});
expect(res.ok).toBe(true);
const stored = JSON.parse(
await fs.readFile(testState.sessionStorePath, "utf-8"),
) as {
main?: { lastChannel?: string; lastTo?: string };
};
expect(stored.main?.lastChannel).toBe("whatsapp");
expect(stored.main?.lastTo).toBe("+1555");
ws.close();
await server.close();
});
test(
"chat.abort cancels an in-flight chat.send",
{ timeout: 15000 },
async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-main",
updatedAt: Date.now(),
},
},
null,
2,
),
"utf-8",
);
const { server, ws } = await startServerWithClient();
let inFlight: Promise<unknown> | undefined;
try {
await connectOk(ws);
const spy = vi.mocked(agentCommand);
const callsBefore = spy.mock.calls.length;
spy.mockImplementationOnce(async (opts) => {
const signal = (opts as { abortSignal?: AbortSignal }).abortSignal;
await new Promise<void>((resolve) => {
if (!signal) return resolve();
if (signal.aborted) return resolve();
signal.addEventListener("abort", () => resolve(), { once: true });
});
});
const sendResP = onceMessage(
ws,
(o) => o.type === "res" && o.id === "send-abort-1",
8000,
);
const abortResP = onceMessage(
ws,
(o) => o.type === "res" && o.id === "abort-1",
8000,
);
const abortedEventP = onceMessage(
ws,
(o) =>
o.type === "event" &&
o.event === "chat" &&
o.payload?.state === "aborted",
8000,
);
inFlight = Promise.allSettled([sendResP, abortResP, abortedEventP]);
ws.send(
JSON.stringify({
type: "req",
id: "send-abort-1",
method: "chat.send",
params: {
sessionKey: "main",
message: "hello",
idempotencyKey: "idem-abort-1",
timeoutMs: 30_000,
},
}),
);
await new Promise<void>((resolve, reject) => {
const deadline = Date.now() + 1000;
const tick = () => {
if (spy.mock.calls.length > callsBefore) return resolve();
if (Date.now() > deadline)
return reject(new Error("timeout waiting for agentCommand"));
setTimeout(tick, 5);
};
tick();
});
ws.send(
JSON.stringify({
type: "req",
id: "abort-1",
method: "chat.abort",
params: { sessionKey: "main", runId: "idem-abort-1" },
}),
);
const abortRes = await abortResP;
expect(abortRes.ok).toBe(true);
const sendRes = await sendResP;
expect(sendRes.ok).toBe(true);
const evt = await abortedEventP;
expect(evt.payload?.runId).toBe("idem-abort-1");
expect(evt.payload?.sessionKey).toBe("main");
} finally {
ws.close();
await inFlight;
await server.close();
}
},
);
test("chat.abort cancels while saving the session store", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-main",
updatedAt: Date.now(),
},
},
null,
2,
),
"utf-8",
);
sessionStoreSaveDelayMs.value = 120;
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const spy = vi.mocked(agentCommand);
spy.mockImplementationOnce(async (opts) => {
const signal = (opts as { abortSignal?: AbortSignal }).abortSignal;
await new Promise<void>((resolve) => {
if (!signal) return resolve();
if (signal.aborted) return resolve();
signal.addEventListener("abort", () => resolve(), { once: true });
});
});
const abortedEventP = onceMessage(
ws,
(o) =>
o.type === "event" &&
o.event === "chat" &&
o.payload?.state === "aborted",
);
const sendResP = onceMessage(
ws,
(o) => o.type === "res" && o.id === "send-abort-save-1",
);
ws.send(
JSON.stringify({
type: "req",
id: "send-abort-save-1",
method: "chat.send",
params: {
sessionKey: "main",
message: "hello",
idempotencyKey: "idem-abort-save-1",
timeoutMs: 30_000,
},
}),
);
const abortResP = onceMessage(
ws,
(o) => o.type === "res" && o.id === "abort-save-1",
);
ws.send(
JSON.stringify({
type: "req",
id: "abort-save-1",
method: "chat.abort",
params: { sessionKey: "main", runId: "idem-abort-save-1" },
}),
);
const abortRes = await abortResP;
expect(abortRes.ok).toBe(true);
const sendRes = await sendResP;
expect(sendRes.ok).toBe(true);
const evt = await abortedEventP;
expect(evt.payload?.runId).toBe("idem-abort-save-1");
expect(evt.payload?.sessionKey).toBe("main");
ws.close();
await server.close();
});
test("chat.abort returns aborted=false for unknown runId", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify({}, null, 2),
"utf-8",
);
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const abortRes = await rpcReq<{
ok?: boolean;
aborted?: boolean;
}>(ws, "chat.abort", { sessionKey: "main", runId: "missing-run" });
expect(abortRes.ok).toBe(true);
expect(abortRes.payload?.aborted).toBe(false);
ws.close();
await server.close();
});
test("chat.abort rejects mismatched sessionKey", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-main",
updatedAt: Date.now(),
},
},
null,
2,
),
"utf-8",
);
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const spy = vi.mocked(agentCommand);
let agentStartedResolve: (() => void) | undefined;
const agentStartedP = new Promise<void>((resolve) => {
agentStartedResolve = resolve;
});
spy.mockImplementationOnce(async (opts) => {
agentStartedResolve?.();
const signal = (opts as { abortSignal?: AbortSignal }).abortSignal;
await new Promise<void>((resolve) => {
if (!signal) return resolve();
if (signal.aborted) return resolve();
signal.addEventListener("abort", () => resolve(), { once: true });
});
});
const sendResP = onceMessage(
ws,
(o) => o.type === "res" && o.id === "send-mismatch-1",
10_000,
);
ws.send(
JSON.stringify({
type: "req",
id: "send-mismatch-1",
method: "chat.send",
params: {
sessionKey: "main",
message: "hello",
idempotencyKey: "idem-mismatch-1",
timeoutMs: 30_000,
},
}),
);
await agentStartedP;
const abortRes = await rpcReq(ws, "chat.abort", {
sessionKey: "other",
runId: "idem-mismatch-1",
});
expect(abortRes.ok).toBe(false);
expect(abortRes.error?.code).toBe("INVALID_REQUEST");
const abortRes2 = await rpcReq(ws, "chat.abort", {
sessionKey: "main",
runId: "idem-mismatch-1",
});
expect(abortRes2.ok).toBe(true);
const sendRes = await sendResP;
expect(sendRes.ok).toBe(true);
ws.close();
await server.close();
}, 15_000);
test("chat.abort is a no-op after chat.send completes", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-main",
updatedAt: Date.now(),
},
},
null,
2,
),
"utf-8",
);
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const spy = vi.mocked(agentCommand);
spy.mockResolvedValueOnce(undefined);
ws.send(
JSON.stringify({
type: "req",
id: "send-complete-1",
method: "chat.send",
params: {
sessionKey: "main",
message: "hello",
idempotencyKey: "idem-complete-1",
timeoutMs: 30_000,
},
}),
);
const sendRes = await onceMessage(
ws,
(o) => o.type === "res" && o.id === "send-complete-1",
);
expect(sendRes.ok).toBe(true);
const abortRes = await rpcReq(ws, "chat.abort", {
sessionKey: "main",
runId: "idem-complete-1",
});
expect(abortRes.ok).toBe(true);
expect(abortRes.payload?.aborted).toBe(false);
ws.close();
await server.close();
});
test("chat.send preserves run ordering for queued runs", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-main",
updatedAt: Date.now(),
},
},
null,
2,
),
"utf-8",
);
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const res1 = await rpcReq(ws, "chat.send", {
sessionKey: "main",
message: "first",
idempotencyKey: "idem-1",
});
expect(res1.ok).toBe(true);
const res2 = await rpcReq(ws, "chat.send", {
sessionKey: "main",
message: "second",
idempotencyKey: "idem-2",
});
expect(res2.ok).toBe(true);
const final1P = onceMessage(
ws,
(o) =>
o.type === "event" &&
o.event === "chat" &&
o.payload?.state === "final",
8000,
);
emitAgentEvent({
runId: "sess-main",
stream: "job",
data: { state: "done" },
});
const final1 = await final1P;
const run1 =
final1.payload && typeof final1.payload === "object"
? (final1.payload as { runId?: string }).runId
: undefined;
expect(run1).toBe("idem-1");
const final2P = onceMessage(
ws,
(o) =>
o.type === "event" &&
o.event === "chat" &&
o.payload?.state === "final",
8000,
);
emitAgentEvent({
runId: "sess-main",
stream: "job",
data: { state: "done" },
});
const final2 = await final2P;
const run2 =
final2.payload && typeof final2.payload === "object"
? (final2.payload as { runId?: string }).runId
: undefined;
expect(run2).toBe("idem-2");
ws.close();
await server.close();
});
});
+296
View File
@@ -0,0 +1,296 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, test } from "vitest";
import {
connectOk,
installGatewayTestHooks,
rpcReq,
startServerWithClient,
testState,
} from "./test-helpers.js";
installGatewayTestHooks();
describe("gateway server cron", () => {
test("supports cron.add and cron.list", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-cron-"));
testState.cronStorePath = path.join(dir, "cron", "jobs.json");
await fs.mkdir(path.dirname(testState.cronStorePath), { recursive: true });
await fs.writeFile(
testState.cronStorePath,
JSON.stringify({ version: 1, jobs: [] }),
);
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const addRes = await rpcReq(ws, "cron.add", {
name: "daily",
enabled: true,
schedule: { kind: "every", everyMs: 60_000 },
sessionTarget: "main",
wakeMode: "next-heartbeat",
payload: { kind: "systemEvent", text: "hello" },
});
expect(addRes.ok).toBe(true);
expect(typeof (addRes.payload as { id?: unknown } | null)?.id).toBe(
"string",
);
const listRes = await rpcReq(ws, "cron.list", {
includeDisabled: true,
});
expect(listRes.ok).toBe(true);
const jobs = (listRes.payload as { jobs?: unknown } | null)?.jobs;
expect(Array.isArray(jobs)).toBe(true);
expect((jobs as unknown[]).length).toBe(1);
expect(((jobs as Array<{ name?: unknown }>)[0]?.name as string) ?? "").toBe(
"daily",
);
ws.close();
await server.close();
await fs.rm(dir, { recursive: true, force: true });
testState.cronStorePath = undefined;
});
test("writes cron run history to runs/<jobId>.jsonl", async () => {
const dir = await fs.mkdtemp(
path.join(os.tmpdir(), "clawdis-gw-cron-log-"),
);
testState.cronStorePath = path.join(dir, "cron", "jobs.json");
await fs.mkdir(path.dirname(testState.cronStorePath), { recursive: true });
await fs.writeFile(
testState.cronStorePath,
JSON.stringify({ version: 1, jobs: [] }),
);
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const atMs = Date.now() - 1;
const addRes = await rpcReq(ws, "cron.add", {
name: "log test",
enabled: true,
schedule: { kind: "at", atMs },
sessionTarget: "main",
wakeMode: "next-heartbeat",
payload: { kind: "systemEvent", text: "hello" },
});
expect(addRes.ok).toBe(true);
const jobIdValue = (addRes.payload as { id?: unknown } | null)?.id;
const jobId = typeof jobIdValue === "string" ? jobIdValue : "";
expect(jobId.length > 0).toBe(true);
const runRes = await rpcReq(ws, "cron.run", { id: jobId, mode: "force" });
expect(runRes.ok).toBe(true);
const logPath = path.join(dir, "cron", "runs", `${jobId}.jsonl`);
const waitForLog = async () => {
for (let i = 0; i < 200; i += 1) {
const raw = await fs.readFile(logPath, "utf-8").catch(() => "");
if (raw.trim().length > 0) return raw;
await new Promise((r) => setTimeout(r, 10));
}
throw new Error("timeout waiting for cron run log");
};
const raw = await waitForLog();
const line = raw
.split("\n")
.map((l) => l.trim())
.filter(Boolean)
.at(-1);
const last = JSON.parse(line ?? "{}") as {
jobId?: unknown;
action?: unknown;
status?: unknown;
summary?: unknown;
};
expect(last.action).toBe("finished");
expect(last.jobId).toBe(jobId);
expect(last.status).toBe("ok");
expect(last.summary).toBe("hello");
const runsRes = await rpcReq(ws, "cron.runs", { id: jobId, limit: 50 });
expect(runsRes.ok).toBe(true);
const entries = (runsRes.payload as { entries?: unknown } | null)?.entries;
expect(Array.isArray(entries)).toBe(true);
expect((entries as Array<{ jobId?: unknown }>).at(-1)?.jobId).toBe(jobId);
expect((entries as Array<{ summary?: unknown }>).at(-1)?.summary).toBe(
"hello",
);
ws.close();
await server.close();
await fs.rm(dir, { recursive: true, force: true });
testState.cronStorePath = undefined;
});
test("writes cron run history to per-job runs/ when store is jobs.json", async () => {
const dir = await fs.mkdtemp(
path.join(os.tmpdir(), "clawdis-gw-cron-log-jobs-"),
);
const cronDir = path.join(dir, "cron");
testState.cronStorePath = path.join(cronDir, "jobs.json");
await fs.mkdir(cronDir, { recursive: true });
await fs.writeFile(
testState.cronStorePath,
JSON.stringify({ version: 1, jobs: [] }),
);
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const atMs = Date.now() - 1;
const addRes = await rpcReq(ws, "cron.add", {
name: "log test (jobs.json)",
enabled: true,
schedule: { kind: "at", atMs },
sessionTarget: "main",
wakeMode: "next-heartbeat",
payload: { kind: "systemEvent", text: "hello" },
});
expect(addRes.ok).toBe(true);
const jobIdValue = (addRes.payload as { id?: unknown } | null)?.id;
const jobId = typeof jobIdValue === "string" ? jobIdValue : "";
expect(jobId.length > 0).toBe(true);
const runRes = await rpcReq(ws, "cron.run", { id: jobId, mode: "force" });
expect(runRes.ok).toBe(true);
const logPath = path.join(cronDir, "runs", `${jobId}.jsonl`);
const waitForLog = async () => {
for (let i = 0; i < 200; i += 1) {
const raw = await fs.readFile(logPath, "utf-8").catch(() => "");
if (raw.trim().length > 0) return raw;
await new Promise((r) => setTimeout(r, 10));
}
throw new Error("timeout waiting for per-job cron run log");
};
const raw = await waitForLog();
const line = raw
.split("\n")
.map((l) => l.trim())
.filter(Boolean)
.at(-1);
const last = JSON.parse(line ?? "{}") as {
jobId?: unknown;
action?: unknown;
summary?: unknown;
};
expect(last.action).toBe("finished");
expect(last.jobId).toBe(jobId);
expect(last.summary).toBe("hello");
const runsRes = await rpcReq(ws, "cron.runs", { id: jobId, limit: 20 });
expect(runsRes.ok).toBe(true);
const entries = (runsRes.payload as { entries?: unknown } | null)?.entries;
expect(Array.isArray(entries)).toBe(true);
expect((entries as Array<{ jobId?: unknown }>).at(-1)?.jobId).toBe(jobId);
expect((entries as Array<{ summary?: unknown }>).at(-1)?.summary).toBe(
"hello",
);
ws.close();
await server.close();
await fs.rm(dir, { recursive: true, force: true });
testState.cronStorePath = undefined;
});
test("enables cron scheduler by default and runs due jobs automatically", async () => {
const dir = await fs.mkdtemp(
path.join(os.tmpdir(), "clawdis-gw-cron-default-on-"),
);
testState.cronStorePath = path.join(dir, "cron", "jobs.json");
testState.cronEnabled = undefined;
try {
await fs.mkdir(path.dirname(testState.cronStorePath), {
recursive: true,
});
await fs.writeFile(
testState.cronStorePath,
JSON.stringify({ version: 1, jobs: [] }),
);
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const statusRes = await rpcReq(ws, "cron.status", {});
expect(statusRes.ok).toBe(true);
const statusPayload = statusRes.payload as
| { enabled?: unknown; storePath?: unknown }
| undefined;
expect(statusPayload?.enabled).toBe(true);
const storePath =
typeof statusPayload?.storePath === "string"
? statusPayload.storePath
: "";
expect(storePath).toContain("jobs.json");
const atMs = Date.now() + 80;
const addRes = await rpcReq(ws, "cron.add", {
name: "auto run test",
enabled: true,
schedule: { kind: "at", atMs },
sessionTarget: "main",
wakeMode: "next-heartbeat",
payload: { kind: "systemEvent", text: "auto" },
});
expect(addRes.ok).toBe(true);
const jobIdValue = (addRes.payload as { id?: unknown } | null)?.id;
const jobId = typeof jobIdValue === "string" ? jobIdValue : "";
expect(jobId.length > 0).toBe(true);
const finishedEvt = await new Promise<{
type: "event";
event: string;
payload?: { jobId?: string; action?: string; status?: string } | null;
}>((resolve) => {
const timeout = setTimeout(() => resolve(null as never), 8000);
ws.on("message", (data) => {
const obj = JSON.parse(String(data));
if (
obj.type === "event" &&
obj.event === "cron" &&
obj.payload?.jobId === jobId &&
obj.payload?.action === "finished"
) {
clearTimeout(timeout);
resolve(obj);
}
});
});
expect(finishedEvt.payload?.status).toBe("ok");
const waitForRuns = async () => {
for (let i = 0; i < 200; i += 1) {
const runsRes = await rpcReq(ws, "cron.runs", {
id: jobId,
limit: 10,
});
expect(runsRes.ok).toBe(true);
const entries = (runsRes.payload as { entries?: unknown } | null)
?.entries;
if (Array.isArray(entries) && entries.length > 0) return entries;
await new Promise((r) => setTimeout(r, 10));
}
throw new Error("timeout waiting for cron.runs entries");
};
const entries = (await waitForRuns()) as Array<{ jobId?: unknown }>;
expect(entries.at(-1)?.jobId).toBe(jobId);
ws.close();
await server.close();
} finally {
testState.cronEnabled = false;
testState.cronStorePath = undefined;
await fs.rm(dir, { recursive: true, force: true });
}
});
});
+310
View File
@@ -0,0 +1,310 @@
import { randomUUID } from "node:crypto";
import { describe, expect, test } from "vitest";
import { WebSocket } from "ws";
import { emitAgentEvent } from "../infra/agent-events.js";
import { emitHeartbeatEvent } from "../infra/heartbeat-events.js";
import {
connectOk,
getFreePort,
installGatewayTestHooks,
onceMessage,
startGatewayServer,
startServerWithClient,
} from "./test-helpers.js";
installGatewayTestHooks();
describe("gateway server health/presence", () => {
test(
"connect + health + presence + status succeed",
{ timeout: 8000 },
async () => {
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const healthP = onceMessage(
ws,
(o) => o.type === "res" && o.id === "health1",
);
const statusP = onceMessage(
ws,
(o) => o.type === "res" && o.id === "status1",
);
const presenceP = onceMessage(
ws,
(o) => o.type === "res" && o.id === "presence1",
);
const providersP = onceMessage(
ws,
(o) => o.type === "res" && o.id === "providers1",
);
const sendReq = (id: string, method: string) =>
ws.send(JSON.stringify({ type: "req", id, method }));
sendReq("health1", "health");
sendReq("status1", "status");
sendReq("presence1", "system-presence");
sendReq("providers1", "providers.status");
const health = await healthP;
const status = await statusP;
const presence = await presenceP;
const providers = await providersP;
expect(health.ok).toBe(true);
expect(status.ok).toBe(true);
expect(presence.ok).toBe(true);
expect(providers.ok).toBe(true);
expect(Array.isArray(presence.payload)).toBe(true);
ws.close();
await server.close();
},
);
test("broadcasts heartbeat events and serves last-heartbeat", async () => {
type HeartbeatPayload = {
ts: number;
status: string;
to?: string;
preview?: string;
durationMs?: number;
hasMedia?: boolean;
reason?: string;
};
type EventFrame = {
type: "event";
event: string;
payload?: HeartbeatPayload | null;
};
type ResFrame = {
type: "res";
id: string;
ok: boolean;
payload?: unknown;
};
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const waitHeartbeat = onceMessage<EventFrame>(
ws,
(o) => o.type === "event" && o.event === "heartbeat",
);
emitHeartbeatEvent({ status: "sent", to: "+123", preview: "ping" });
const evt = await waitHeartbeat;
expect(evt.payload?.status).toBe("sent");
expect(typeof evt.payload?.ts).toBe("number");
ws.send(
JSON.stringify({
type: "req",
id: "hb-last",
method: "last-heartbeat",
}),
);
const last = await onceMessage<ResFrame>(
ws,
(o) => o.type === "res" && o.id === "hb-last",
);
expect(last.ok).toBe(true);
const lastPayload = last.payload as HeartbeatPayload | null | undefined;
expect(lastPayload?.status).toBe("sent");
expect(lastPayload?.ts).toBe(evt.payload?.ts);
ws.send(
JSON.stringify({
type: "req",
id: "hb-toggle-off",
method: "set-heartbeats",
params: { enabled: false },
}),
);
const toggle = await onceMessage<ResFrame>(
ws,
(o) => o.type === "res" && o.id === "hb-toggle-off",
);
expect(toggle.ok).toBe(true);
expect((toggle.payload as { enabled?: boolean } | undefined)?.enabled).toBe(
false,
);
ws.close();
await server.close();
});
test(
"presence events carry seq + stateVersion",
{ timeout: 8000 },
async () => {
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const presenceEventP = onceMessage(
ws,
(o) => o.type === "event" && o.event === "presence",
);
ws.send(
JSON.stringify({
type: "req",
id: "evt-1",
method: "system-event",
params: { text: "note from test" },
}),
);
const evt = await presenceEventP;
expect(typeof evt.seq).toBe("number");
expect(evt.stateVersion?.presence).toBeGreaterThan(0);
expect(Array.isArray(evt.payload?.presence)).toBe(true);
ws.close();
await server.close();
},
);
test("agent events stream with seq", { timeout: 8000 }, async () => {
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const runId = randomUUID();
const evtPromise = onceMessage(
ws,
(o) =>
o.type === "event" &&
o.event === "agent" &&
o.payload?.runId === runId &&
o.payload?.stream === "job",
);
emitAgentEvent({ runId, stream: "job", data: { msg: "hi" } });
const evt = await evtPromise;
expect(evt.payload.runId).toBe(runId);
expect(typeof evt.seq).toBe("number");
expect(evt.payload.data.msg).toBe("hi");
ws.close();
await server.close();
});
test("shutdown event is broadcast on close", { timeout: 8000 }, async () => {
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const shutdownP = onceMessage(
ws,
(o) => o.type === "event" && o.event === "shutdown",
5000,
);
await server.close();
const evt = await shutdownP;
expect(evt.payload?.reason).toBeDefined();
});
test(
"presence broadcast reaches multiple clients",
{ timeout: 8000 },
async () => {
const port = await getFreePort();
const server = await startGatewayServer(port);
const mkClient = async () => {
const c = new WebSocket(`ws://127.0.0.1:${port}`);
await new Promise<void>((resolve) => c.once("open", resolve));
await connectOk(c);
return c;
};
const clients = await Promise.all([mkClient(), mkClient(), mkClient()]);
const waits = clients.map((c) =>
onceMessage(c, (o) => o.type === "event" && o.event === "presence"),
);
clients[0].send(
JSON.stringify({
type: "req",
id: "broadcast",
method: "system-event",
params: { text: "fanout" },
}),
);
const events = await Promise.all(waits);
for (const evt of events) {
expect(evt.payload?.presence?.length).toBeGreaterThan(0);
expect(typeof evt.seq).toBe("number");
}
for (const c of clients) c.close();
await server.close();
},
);
test("presence includes client fingerprint", async () => {
const { server, ws } = await startServerWithClient();
await connectOk(ws, {
client: {
name: "fingerprint",
version: "9.9.9",
platform: "test",
deviceFamily: "iPad",
modelIdentifier: "iPad16,6",
mode: "ui",
instanceId: "abc",
},
});
const presenceP = onceMessage(
ws,
(o) => o.type === "res" && o.id === "fingerprint",
4000,
);
ws.send(
JSON.stringify({
type: "req",
id: "fingerprint",
method: "system-presence",
}),
);
const presenceRes = await presenceP;
const entries = presenceRes.payload as Array<Record<string, unknown>>;
const clientEntry = entries.find((e) => e.instanceId === "abc");
expect(clientEntry?.host).toBe("fingerprint");
expect(clientEntry?.version).toBe("9.9.9");
expect(clientEntry?.mode).toBe("ui");
expect(clientEntry?.deviceFamily).toBe("iPad");
expect(clientEntry?.modelIdentifier).toBe("iPad16,6");
ws.close();
await server.close();
});
test("cli connections are not tracked as instances", async () => {
const { server, ws } = await startServerWithClient();
const cliId = `cli-${randomUUID()}`;
await connectOk(ws, {
client: {
name: "cli",
version: "dev",
platform: "test",
mode: "cli",
instanceId: cliId,
},
});
const presenceP = onceMessage(
ws,
(o) => o.type === "res" && o.id === "cli-presence",
4000,
);
ws.send(
JSON.stringify({
type: "req",
id: "cli-presence",
method: "system-presence",
}),
);
const presenceRes = await presenceP;
const entries = presenceRes.payload as Array<Record<string, unknown>>;
expect(entries.some((e) => e.instanceId === cliId)).toBe(false);
ws.close();
await server.close();
});
});
+184
View File
@@ -0,0 +1,184 @@
import { describe, expect, test } from "vitest";
import { drainSystemEvents, peekSystemEvents } from "../infra/system-events.js";
import {
cronIsolatedRun,
getFreePort,
installGatewayTestHooks,
startGatewayServer,
testState,
waitForSystemEvent,
} from "./test-helpers.js";
installGatewayTestHooks();
describe("gateway server hooks", () => {
test("hooks wake requires auth", async () => {
testState.hooksConfig = { enabled: true, token: "hook-secret" };
const port = await getFreePort();
const server = await startGatewayServer(port);
const res = await fetch(`http://127.0.0.1:${port}/hooks/wake`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text: "Ping" }),
});
expect(res.status).toBe(401);
await server.close();
});
test("hooks wake enqueues system event", async () => {
testState.hooksConfig = { enabled: true, token: "hook-secret" };
const port = await getFreePort();
const server = await startGatewayServer(port);
const res = await fetch(`http://127.0.0.1:${port}/hooks/wake`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer hook-secret",
},
body: JSON.stringify({ text: "Ping", mode: "next-heartbeat" }),
});
expect(res.status).toBe(200);
const events = await waitForSystemEvent();
expect(events.some((e) => e.includes("Ping"))).toBe(true);
drainSystemEvents();
await server.close();
});
test("hooks agent posts summary to main", async () => {
testState.hooksConfig = { enabled: true, token: "hook-secret" };
cronIsolatedRun.mockResolvedValueOnce({
status: "ok",
summary: "done",
});
const port = await getFreePort();
const server = await startGatewayServer(port);
const res = await fetch(`http://127.0.0.1:${port}/hooks/agent`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer hook-secret",
},
body: JSON.stringify({ message: "Do it", name: "Email" }),
});
expect(res.status).toBe(202);
const events = await waitForSystemEvent();
expect(events.some((e) => e.includes("Hook Email: done"))).toBe(true);
drainSystemEvents();
await server.close();
});
test("hooks wake accepts query token", async () => {
testState.hooksConfig = { enabled: true, token: "hook-secret" };
const port = await getFreePort();
const server = await startGatewayServer(port);
const res = await fetch(
`http://127.0.0.1:${port}/hooks/wake?token=hook-secret`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text: "Query auth" }),
},
);
expect(res.status).toBe(200);
const events = await waitForSystemEvent();
expect(events.some((e) => e.includes("Query auth"))).toBe(true);
drainSystemEvents();
await server.close();
});
test("hooks agent rejects invalid channel", async () => {
testState.hooksConfig = { enabled: true, token: "hook-secret" };
const port = await getFreePort();
const server = await startGatewayServer(port);
const res = await fetch(`http://127.0.0.1:${port}/hooks/agent`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer hook-secret",
},
body: JSON.stringify({ message: "Nope", channel: "sms" }),
});
expect(res.status).toBe(400);
expect(peekSystemEvents().length).toBe(0);
await server.close();
});
test("hooks wake accepts x-clawdis-token header", async () => {
testState.hooksConfig = { enabled: true, token: "hook-secret" };
const port = await getFreePort();
const server = await startGatewayServer(port);
const res = await fetch(`http://127.0.0.1:${port}/hooks/wake`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-clawdis-token": "hook-secret",
},
body: JSON.stringify({ text: "Header auth" }),
});
expect(res.status).toBe(200);
const events = await waitForSystemEvent();
expect(events.some((e) => e.includes("Header auth"))).toBe(true);
drainSystemEvents();
await server.close();
});
test("hooks rejects non-post", async () => {
testState.hooksConfig = { enabled: true, token: "hook-secret" };
const port = await getFreePort();
const server = await startGatewayServer(port);
const res = await fetch(`http://127.0.0.1:${port}/hooks/wake`, {
method: "GET",
headers: { Authorization: "Bearer hook-secret" },
});
expect(res.status).toBe(405);
await server.close();
});
test("hooks wake requires text", async () => {
testState.hooksConfig = { enabled: true, token: "hook-secret" };
const port = await getFreePort();
const server = await startGatewayServer(port);
const res = await fetch(`http://127.0.0.1:${port}/hooks/wake`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer hook-secret",
},
body: JSON.stringify({ text: " " }),
});
expect(res.status).toBe(400);
await server.close();
});
test("hooks agent requires message", async () => {
testState.hooksConfig = { enabled: true, token: "hook-secret" };
const port = await getFreePort();
const server = await startGatewayServer(port);
const res = await fetch(`http://127.0.0.1:${port}/hooks/agent`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer hook-secret",
},
body: JSON.stringify({ message: " " }),
});
expect(res.status).toBe(400);
await server.close();
});
test("hooks rejects invalid json", async () => {
testState.hooksConfig = { enabled: true, token: "hook-secret" };
const port = await getFreePort();
const server = await startGatewayServer(port);
const res = await fetch(`http://127.0.0.1:${port}/hooks/wake`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer hook-secret",
},
body: "{",
});
expect(res.status).toBe(400);
await server.close();
});
});
+103
View File
@@ -0,0 +1,103 @@
import { createServer } from "node:net";
import { describe, expect, test } from "vitest";
import { WebSocket } from "ws";
import { GatewayLockError } from "../infra/gateway-lock.js";
import {
connectOk,
getFreePort,
installGatewayTestHooks,
occupyPort,
onceMessage,
startGatewayServer,
startServerWithClient,
testState,
testTailnetIPv4,
} from "./test-helpers.js";
installGatewayTestHooks();
describe("gateway server misc", () => {
test("hello-ok advertises the gateway port for canvas host", async () => {
const prevToken = process.env.CLAWDIS_GATEWAY_TOKEN;
process.env.CLAWDIS_GATEWAY_TOKEN = "secret";
testTailnetIPv4.value = "100.64.0.1";
testState.gatewayBind = "lan";
const canvasPort = await getFreePort();
testState.canvasHostPort = canvasPort;
const port = await getFreePort();
const server = await startGatewayServer(port, {
bind: "lan",
allowCanvasHostInTests: true,
});
const ws = new WebSocket(`ws://127.0.0.1:${port}`, {
headers: { Host: `100.64.0.1:${port}` },
});
await new Promise<void>((resolve) => ws.once("open", resolve));
const hello = await connectOk(ws, { token: "secret" });
expect(hello.canvasHostUrl).toBe(`http://100.64.0.1:${canvasPort}`);
ws.close();
await server.close();
if (prevToken === undefined) {
delete process.env.CLAWDIS_GATEWAY_TOKEN;
} else {
process.env.CLAWDIS_GATEWAY_TOKEN = prevToken;
}
});
test("send dedupes by idempotencyKey", { timeout: 8000 }, async () => {
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const idem = "same-key";
const res1P = onceMessage(ws, (o) => o.type === "res" && o.id === "a1");
const res2P = onceMessage(ws, (o) => o.type === "res" && o.id === "a2");
const sendReq = (id: string) =>
ws.send(
JSON.stringify({
type: "req",
id,
method: "send",
params: { to: "+15550000000", message: "hi", idempotencyKey: idem },
}),
);
sendReq("a1");
sendReq("a2");
const res1 = await res1P;
const res2 = await res2P;
expect(res1.ok).toBe(true);
expect(res2.ok).toBe(true);
expect(res1.payload).toEqual(res2.payload);
ws.close();
await server.close();
});
test("refuses to start when port already bound", async () => {
const { server: blocker, port } = await occupyPort();
await expect(startGatewayServer(port)).rejects.toBeInstanceOf(
GatewayLockError,
);
await expect(startGatewayServer(port)).rejects.toThrow(
/already listening/i,
);
blocker.close();
});
test("releases port after close", async () => {
const port = await getFreePort();
const server = await startGatewayServer(port);
await server.close();
const probe = createServer();
await new Promise<void>((resolve, reject) => {
probe.once("error", reject);
probe.listen(port, "127.0.0.1", () => resolve());
});
await new Promise<void>((resolve, reject) =>
probe.close((err) => (err ? reject(err) : resolve())),
);
});
});
+262
View File
@@ -0,0 +1,262 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, test } from "vitest";
import {
bridgeListConnected,
bridgeSendEvent,
bridgeStartCalls,
connectOk,
installGatewayTestHooks,
onceMessage,
piSdkMock,
rpcReq,
startServerWithClient,
} from "./test-helpers.js";
installGatewayTestHooks();
describe("gateway server models + voicewake", () => {
test(
"voicewake.get returns defaults and voicewake.set broadcasts",
{ timeout: 15_000 },
async () => {
const homeDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-home-"));
const prevHome = process.env.HOME;
process.env.HOME = homeDir;
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const initial = await rpcReq<{ triggers: string[] }>(ws, "voicewake.get");
expect(initial.ok).toBe(true);
expect(initial.payload?.triggers).toEqual([
"clawd",
"claude",
"computer",
]);
const changedP = onceMessage<{
type: "event";
event: string;
payload?: unknown;
}>(ws, (o) => o.type === "event" && o.event === "voicewake.changed");
const setRes = await rpcReq<{ triggers: string[] }>(ws, "voicewake.set", {
triggers: [" hi ", "", "there"],
});
expect(setRes.ok).toBe(true);
expect(setRes.payload?.triggers).toEqual(["hi", "there"]);
const changed = await changedP;
expect(changed.event).toBe("voicewake.changed");
expect(
(changed.payload as { triggers?: unknown } | undefined)?.triggers,
).toEqual(["hi", "there"]);
const after = await rpcReq<{ triggers: string[] }>(ws, "voicewake.get");
expect(after.ok).toBe(true);
expect(after.payload?.triggers).toEqual(["hi", "there"]);
const onDisk = JSON.parse(
await fs.readFile(
path.join(homeDir, ".clawdis", "settings", "voicewake.json"),
"utf8",
),
) as { triggers?: unknown; updatedAtMs?: unknown };
expect(onDisk.triggers).toEqual(["hi", "there"]);
expect(typeof onDisk.updatedAtMs).toBe("number");
ws.close();
await server.close();
if (prevHome === undefined) {
delete process.env.HOME;
} else {
process.env.HOME = prevHome;
}
},
);
test("pushes voicewake.changed to nodes on connect and on updates", async () => {
const homeDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-home-"));
const prevHome = process.env.HOME;
process.env.HOME = homeDir;
bridgeSendEvent.mockClear();
bridgeListConnected.mockReturnValue([{ nodeId: "n1" }]);
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const startCall = bridgeStartCalls.at(-1);
expect(startCall).toBeTruthy();
await startCall?.onAuthenticated?.({ nodeId: "n1" });
const first = bridgeSendEvent.mock.calls.find(
(c) => c[0]?.event === "voicewake.changed" && c[0]?.nodeId === "n1",
)?.[0] as { payloadJSON?: string | null } | undefined;
expect(first?.payloadJSON).toBeTruthy();
const firstPayload = JSON.parse(String(first?.payloadJSON)) as {
triggers?: unknown;
};
expect(firstPayload.triggers).toEqual(["clawd", "claude", "computer"]);
bridgeSendEvent.mockClear();
const setRes = await rpcReq<{ triggers: string[] }>(ws, "voicewake.set", {
triggers: ["clawd", "computer"],
});
expect(setRes.ok).toBe(true);
const broadcast = bridgeSendEvent.mock.calls.find(
(c) => c[0]?.event === "voicewake.changed" && c[0]?.nodeId === "n1",
)?.[0] as { payloadJSON?: string | null } | undefined;
expect(broadcast?.payloadJSON).toBeTruthy();
const broadcastPayload = JSON.parse(String(broadcast?.payloadJSON)) as {
triggers?: unknown;
};
expect(broadcastPayload.triggers).toEqual(["clawd", "computer"]);
ws.close();
await server.close();
if (prevHome === undefined) {
delete process.env.HOME;
} else {
process.env.HOME = prevHome;
}
});
test("models.list returns model catalog", async () => {
piSdkMock.enabled = true;
piSdkMock.models = [
{ id: "gpt-test-z", provider: "openai", contextWindow: 0 },
{
id: "gpt-test-a",
name: "A-Model",
provider: "openai",
contextWindow: 8000,
},
{
id: "claude-test-b",
name: "B-Model",
provider: "anthropic",
contextWindow: 1000,
},
{
id: "claude-test-a",
name: "A-Model",
provider: "anthropic",
contextWindow: 200_000,
},
];
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const res1 = await rpcReq<{
models: Array<{
id: string;
name: string;
provider: string;
contextWindow?: number;
}>;
}>(ws, "models.list");
const res2 = await rpcReq<{
models: Array<{
id: string;
name: string;
provider: string;
contextWindow?: number;
}>;
}>(ws, "models.list");
expect(res1.ok).toBe(true);
expect(res2.ok).toBe(true);
const models = res1.payload?.models ?? [];
expect(models).toEqual([
{
id: "claude-test-a",
name: "A-Model",
provider: "anthropic",
contextWindow: 200_000,
},
{
id: "claude-test-b",
name: "B-Model",
provider: "anthropic",
contextWindow: 1000,
},
{
id: "gpt-test-a",
name: "A-Model",
provider: "openai",
contextWindow: 8000,
},
{
id: "gpt-test-z",
name: "gpt-test-z",
provider: "openai",
},
]);
expect(piSdkMock.discoverCalls).toBe(1);
ws.close();
await server.close();
});
test("models.list rejects unknown params", async () => {
piSdkMock.enabled = true;
piSdkMock.models = [{ id: "gpt-test-a", name: "A", provider: "openai" }];
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const res = await rpcReq(ws, "models.list", { extra: true });
expect(res.ok).toBe(false);
expect(res.error?.message ?? "").toMatch(/invalid models\.list params/i);
ws.close();
await server.close();
});
test("bridge RPC supports models.list and validates params", async () => {
piSdkMock.enabled = true;
piSdkMock.models = [{ id: "gpt-test-a", name: "A", provider: "openai" }];
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const startCall = bridgeStartCalls.at(-1);
expect(startCall).toBeTruthy();
const okRes = await startCall?.onRequest?.("n1", {
id: "1",
method: "models.list",
paramsJSON: "{}",
});
expect(okRes?.ok).toBe(true);
const okPayload = JSON.parse(String(okRes?.payloadJSON ?? "{}")) as {
models?: unknown;
};
expect(Array.isArray(okPayload.models)).toBe(true);
const badRes = await startCall?.onRequest?.("n1", {
id: "2",
method: "models.list",
paramsJSON: JSON.stringify({ extra: true }),
});
expect(badRes?.ok).toBe(false);
expect(badRes && "error" in badRes ? badRes.error.code : "").toBe(
"INVALID_REQUEST",
);
ws.close();
await server.close();
});
});
+913
View File
@@ -0,0 +1,913 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, test, vi } from "vitest";
import { emitAgentEvent } from "../infra/agent-events.js";
import {
agentCommand,
bridgeInvoke,
bridgeListConnected,
bridgeSendEvent,
bridgeStartCalls,
connectOk,
getFreePort,
installGatewayTestHooks,
onceMessage,
rpcReq,
sessionStoreSaveDelayMs,
startGatewayServer,
startServerWithClient,
testState,
} from "./test-helpers.js";
installGatewayTestHooks();
describe("gateway server node/bridge", () => {
test("supports gateway-owned node pairing methods and events", async () => {
const homeDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-home-"));
const prevHome = process.env.HOME;
process.env.HOME = homeDir;
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const requestedP = new Promise<{
type: "event";
event: string;
payload?: unknown;
}>((resolve) => {
ws.on("message", (data) => {
const obj = JSON.parse(String(data)) as {
type?: string;
event?: string;
payload?: unknown;
};
if (obj.type === "event" && obj.event === "node.pair.requested") {
resolve(obj as never);
}
});
});
const res1 = await rpcReq(ws, "node.pair.request", {
nodeId: "n1",
displayName: "Node",
});
expect(res1.ok).toBe(true);
const req1 = (res1.payload as { request?: { requestId?: unknown } } | null)
?.request;
const requestId = typeof req1?.requestId === "string" ? req1.requestId : "";
expect(requestId.length).toBeGreaterThan(0);
const evt1 = await requestedP;
expect(evt1.event).toBe("node.pair.requested");
expect((evt1.payload as { requestId?: unknown } | null)?.requestId).toBe(
requestId,
);
const res2 = await rpcReq(ws, "node.pair.request", {
nodeId: "n1",
displayName: "Node",
});
expect(res2.ok).toBe(true);
await expect(
onceMessage(
ws,
(o) => o.type === "event" && o.event === "node.pair.requested",
200,
),
).rejects.toThrow();
const resolvedP = new Promise<{
type: "event";
event: string;
payload?: unknown;
}>((resolve) => {
ws.on("message", (data) => {
const obj = JSON.parse(String(data)) as {
type?: string;
event?: string;
payload?: unknown;
};
if (obj.type === "event" && obj.event === "node.pair.resolved") {
resolve(obj as never);
}
});
});
const approveRes = await rpcReq(ws, "node.pair.approve", { requestId });
expect(approveRes.ok).toBe(true);
const tokenValue = (
approveRes.payload as { node?: { token?: unknown } } | null
)?.node?.token;
const token = typeof tokenValue === "string" ? tokenValue : "";
expect(token.length).toBeGreaterThan(0);
const evt2 = await resolvedP;
expect((evt2.payload as { requestId?: unknown } | null)?.requestId).toBe(
requestId,
);
expect((evt2.payload as { decision?: unknown } | null)?.decision).toBe(
"approved",
);
const verifyRes = await rpcReq(ws, "node.pair.verify", {
nodeId: "n1",
token,
});
expect(verifyRes.ok).toBe(true);
expect((verifyRes.payload as { ok?: unknown } | null)?.ok).toBe(true);
const listRes = await rpcReq(ws, "node.pair.list", {});
expect(listRes.ok).toBe(true);
const paired = (listRes.payload as { paired?: unknown } | null)?.paired;
expect(Array.isArray(paired)).toBe(true);
expect(
(paired as Array<{ nodeId?: unknown }>).some((n) => n.nodeId === "n1"),
).toBe(true);
ws.close();
await server.close();
await fs.rm(homeDir, { recursive: true, force: true });
if (prevHome === undefined) {
delete process.env.HOME;
} else {
process.env.HOME = prevHome;
}
});
test("routes node.invoke to the node bridge", async () => {
const homeDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-home-"));
const prevHome = process.env.HOME;
process.env.HOME = homeDir;
try {
bridgeInvoke.mockResolvedValueOnce({
type: "invoke-res",
id: "inv-1",
ok: true,
payloadJSON: JSON.stringify({ result: "4" }),
error: null,
});
const { server, ws } = await startServerWithClient();
try {
await connectOk(ws);
const res = await rpcReq(ws, "node.invoke", {
nodeId: "ios-node",
command: "canvas.eval",
params: { javaScript: "2+2" },
timeoutMs: 123,
idempotencyKey: "idem-1",
});
expect(res.ok).toBe(true);
expect(bridgeInvoke).toHaveBeenCalledWith(
expect.objectContaining({
nodeId: "ios-node",
command: "canvas.eval",
paramsJSON: JSON.stringify({ javaScript: "2+2" }),
timeoutMs: 123,
}),
);
} finally {
ws.close();
await server.close();
}
} finally {
await fs.rm(homeDir, { recursive: true, force: true });
if (prevHome === undefined) {
delete process.env.HOME;
} else {
process.env.HOME = prevHome;
}
}
});
test("routes camera.list invoke to the node bridge", async () => {
const homeDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-home-"));
const prevHome = process.env.HOME;
process.env.HOME = homeDir;
try {
bridgeInvoke.mockResolvedValueOnce({
type: "invoke-res",
id: "inv-2",
ok: true,
payloadJSON: JSON.stringify({ devices: [] }),
error: null,
});
const { server, ws } = await startServerWithClient();
try {
await connectOk(ws);
const res = await rpcReq(ws, "node.invoke", {
nodeId: "ios-node",
command: "camera.list",
params: {},
idempotencyKey: "idem-2",
});
expect(res.ok).toBe(true);
expect(bridgeInvoke).toHaveBeenCalledWith(
expect.objectContaining({
nodeId: "ios-node",
command: "camera.list",
paramsJSON: JSON.stringify({}),
}),
);
} finally {
ws.close();
await server.close();
}
} finally {
await fs.rm(homeDir, { recursive: true, force: true });
if (prevHome === undefined) {
delete process.env.HOME;
} else {
process.env.HOME = prevHome;
}
}
});
test("node.describe returns supported invoke commands for paired nodes", async () => {
const homeDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-home-"));
const prevHome = process.env.HOME;
process.env.HOME = homeDir;
try {
const { server, ws } = await startServerWithClient();
try {
await connectOk(ws);
const reqRes = await rpcReq<{
status?: string;
request?: { requestId?: string };
}>(ws, "node.pair.request", {
nodeId: "n1",
displayName: "iPad",
platform: "iPadOS",
version: "dev",
deviceFamily: "iPad",
modelIdentifier: "iPad16,6",
caps: ["canvas", "camera"],
commands: ["canvas.eval", "canvas.snapshot", "camera.snap"],
remoteIp: "10.0.0.10",
});
expect(reqRes.ok).toBe(true);
const requestId = reqRes.payload?.request?.requestId;
expect(typeof requestId).toBe("string");
const approveRes = await rpcReq(ws, "node.pair.approve", {
requestId,
});
expect(approveRes.ok).toBe(true);
const describeRes = await rpcReq<{ commands?: string[] }>(
ws,
"node.describe",
{ nodeId: "n1" },
);
expect(describeRes.ok).toBe(true);
expect(describeRes.payload?.commands).toEqual([
"camera.snap",
"canvas.eval",
"canvas.snapshot",
]);
} finally {
ws.close();
await server.close();
}
} finally {
await fs.rm(homeDir, { recursive: true, force: true });
if (prevHome === undefined) {
delete process.env.HOME;
} else {
process.env.HOME = prevHome;
}
}
});
test("node.describe works for connected unpaired nodes (caps + commands)", async () => {
const homeDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-home-"));
const prevHome = process.env.HOME;
process.env.HOME = homeDir;
try {
const { server, ws } = await startServerWithClient();
try {
await connectOk(ws);
bridgeListConnected.mockReturnValueOnce([
{
nodeId: "u1",
displayName: "Unpaired Live",
platform: "Android",
version: "dev-live",
remoteIp: "10.0.0.12",
deviceFamily: "Android",
modelIdentifier: "samsung SM-X926B",
caps: ["canvas", "camera", "canvas"],
commands: ["canvas.eval", "camera.snap", "canvas.eval"],
},
]);
const describeRes = await rpcReq<{
paired?: boolean;
connected?: boolean;
caps?: string[];
commands?: string[];
deviceFamily?: string;
modelIdentifier?: string;
remoteIp?: string;
}>(ws, "node.describe", { nodeId: "u1" });
expect(describeRes.ok).toBe(true);
expect(describeRes.payload).toMatchObject({
paired: false,
connected: true,
deviceFamily: "Android",
modelIdentifier: "samsung SM-X926B",
remoteIp: "10.0.0.12",
});
expect(describeRes.payload?.caps).toEqual(["camera", "canvas"]);
expect(describeRes.payload?.commands).toEqual([
"camera.snap",
"canvas.eval",
]);
} finally {
ws.close();
await server.close();
}
} finally {
await fs.rm(homeDir, { recursive: true, force: true });
if (prevHome === undefined) {
delete process.env.HOME;
} else {
process.env.HOME = prevHome;
}
}
});
test("node.list includes connected unpaired nodes with capabilities + commands", async () => {
const homeDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-home-"));
const prevHome = process.env.HOME;
process.env.HOME = homeDir;
try {
const { server, ws } = await startServerWithClient();
try {
await connectOk(ws);
const reqRes = await rpcReq<{
status?: string;
request?: { requestId?: string };
}>(ws, "node.pair.request", {
nodeId: "p1",
displayName: "Paired",
platform: "iPadOS",
version: "dev",
deviceFamily: "iPad",
modelIdentifier: "iPad16,6",
caps: ["canvas"],
commands: ["canvas.eval"],
remoteIp: "10.0.0.10",
});
expect(reqRes.ok).toBe(true);
const requestId = reqRes.payload?.request?.requestId;
expect(typeof requestId).toBe("string");
const approveRes = await rpcReq(ws, "node.pair.approve", { requestId });
expect(approveRes.ok).toBe(true);
bridgeListConnected.mockReturnValueOnce([
{
nodeId: "p1",
displayName: "Paired Live",
platform: "iPadOS",
version: "dev-live",
remoteIp: "10.0.0.11",
deviceFamily: "iPad",
modelIdentifier: "iPad16,6",
caps: ["canvas", "camera"],
commands: ["canvas.snapshot", "canvas.eval"],
},
{
nodeId: "u1",
displayName: "Unpaired Live",
platform: "Android",
version: "dev",
remoteIp: "10.0.0.12",
deviceFamily: "Android",
modelIdentifier: "samsung SM-X926B",
caps: ["canvas"],
commands: ["canvas.eval"],
},
]);
const listRes = await rpcReq<{
nodes?: Array<{
nodeId: string;
paired?: boolean;
connected?: boolean;
caps?: string[];
commands?: string[];
displayName?: string;
remoteIp?: string;
}>;
}>(ws, "node.list", {});
expect(listRes.ok).toBe(true);
const nodes = listRes.payload?.nodes ?? [];
const pairedNode = nodes.find((n) => n.nodeId === "p1");
expect(pairedNode).toMatchObject({
nodeId: "p1",
paired: true,
connected: true,
displayName: "Paired Live",
remoteIp: "10.0.0.11",
});
expect(pairedNode?.caps?.slice().sort()).toEqual(["camera", "canvas"]);
expect(pairedNode?.commands?.slice().sort()).toEqual([
"canvas.eval",
"canvas.snapshot",
]);
const unpairedNode = nodes.find((n) => n.nodeId === "u1");
expect(unpairedNode).toMatchObject({
nodeId: "u1",
paired: false,
connected: true,
displayName: "Unpaired Live",
});
expect(unpairedNode?.caps).toEqual(["canvas"]);
expect(unpairedNode?.commands).toEqual(["canvas.eval"]);
} finally {
ws.close();
await server.close();
}
} finally {
await fs.rm(homeDir, { recursive: true, force: true });
if (prevHome === undefined) {
delete process.env.HOME;
} else {
process.env.HOME = prevHome;
}
}
});
test("emits presence updates for bridge connect/disconnect", async () => {
const homeDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-home-"));
const prevHome = process.env.HOME;
process.env.HOME = homeDir;
try {
const before = bridgeStartCalls.length;
const { server, ws } = await startServerWithClient();
try {
await connectOk(ws);
const bridgeCall = bridgeStartCalls[before];
expect(bridgeCall).toBeTruthy();
const waitPresenceReason = async (reason: string) => {
await onceMessage(
ws,
(o) => {
if (o.type !== "event" || o.event !== "presence") return false;
const payload = o.payload as { presence?: unknown } | null;
const list = payload?.presence;
if (!Array.isArray(list)) return false;
return list.some(
(p) =>
typeof p === "object" &&
p !== null &&
(p as { instanceId?: unknown }).instanceId === "node-1" &&
(p as { reason?: unknown }).reason === reason,
);
},
3000,
);
};
const presenceConnectedP = waitPresenceReason("node-connected");
await bridgeCall?.onAuthenticated?.({
nodeId: "node-1",
displayName: "Node",
platform: "ios",
version: "1.0",
remoteIp: "10.0.0.10",
});
await presenceConnectedP;
const presenceDisconnectedP = waitPresenceReason("node-disconnected");
await bridgeCall?.onDisconnected?.({
nodeId: "node-1",
displayName: "Node",
platform: "ios",
version: "1.0",
remoteIp: "10.0.0.10",
});
await presenceDisconnectedP;
} finally {
try {
ws.close();
} catch {
/* ignore */
}
await server.close();
await fs.rm(homeDir, { recursive: true, force: true });
}
} finally {
if (prevHome === undefined) {
delete process.env.HOME;
} else {
process.env.HOME = prevHome;
}
}
});
test("bridge RPC chat.history returns session messages", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-main",
updatedAt: Date.now(),
},
},
null,
2,
),
"utf-8",
);
await fs.writeFile(
path.join(dir, "sess-main.jsonl"),
[
JSON.stringify({
message: {
role: "user",
content: [{ type: "text", text: "hi" }],
timestamp: Date.now(),
},
}),
].join("\n"),
"utf-8",
);
const port = await getFreePort();
const server = await startGatewayServer(port);
const bridgeCall = bridgeStartCalls.at(-1);
expect(bridgeCall?.onRequest).toBeDefined();
const res = await bridgeCall?.onRequest?.("ios-node", {
id: "r1",
method: "chat.history",
paramsJSON: JSON.stringify({ sessionKey: "main" }),
});
expect(res?.ok).toBe(true);
const payload = JSON.parse(
String((res as { payloadJSON?: string }).payloadJSON ?? "{}"),
) as {
sessionKey?: string;
sessionId?: string;
messages?: unknown[];
};
expect(payload.sessionKey).toBe("main");
expect(payload.sessionId).toBe("sess-main");
expect(Array.isArray(payload.messages)).toBe(true);
expect(payload.messages?.length).toBeGreaterThan(0);
await server.close();
});
test("bridge RPC sessions.list returns session rows", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-main",
updatedAt: Date.now(),
},
},
null,
2,
),
"utf-8",
);
const port = await getFreePort();
const server = await startGatewayServer(port);
const bridgeCall = bridgeStartCalls.at(-1);
expect(bridgeCall?.onRequest).toBeDefined();
const res = await bridgeCall?.onRequest?.("ios-node", {
id: "r1",
method: "sessions.list",
paramsJSON: JSON.stringify({
includeGlobal: true,
includeUnknown: false,
limit: 50,
}),
});
expect(res?.ok).toBe(true);
const payload = JSON.parse(
String((res as { payloadJSON?: string }).payloadJSON ?? "{}"),
) as {
sessions?: unknown[];
count?: number;
path?: string;
};
expect(Array.isArray(payload.sessions)).toBe(true);
expect(typeof payload.count).toBe("number");
expect(typeof payload.path).toBe("string");
await server.close();
});
test("bridge chat events are pushed to subscribed nodes", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-main",
updatedAt: Date.now(),
},
},
null,
2,
),
"utf-8",
);
const port = await getFreePort();
const server = await startGatewayServer(port);
const bridgeCall = bridgeStartCalls.at(-1);
expect(bridgeCall?.onEvent).toBeDefined();
expect(bridgeCall?.onRequest).toBeDefined();
await bridgeCall?.onEvent?.("ios-node", {
event: "chat.subscribe",
payloadJSON: JSON.stringify({ sessionKey: "main" }),
});
bridgeSendEvent.mockClear();
const reqRes = await bridgeCall?.onRequest?.("ios-node", {
id: "s1",
method: "chat.send",
paramsJSON: JSON.stringify({
sessionKey: "main",
message: "hello",
idempotencyKey: "idem-bridge-chat",
timeoutMs: 30_000,
}),
});
expect(reqRes?.ok).toBe(true);
emitAgentEvent({
runId: "sess-main",
seq: 1,
ts: Date.now(),
stream: "assistant",
data: { text: "hi from agent" },
});
emitAgentEvent({
runId: "sess-main",
seq: 2,
ts: Date.now(),
stream: "job",
data: { state: "done" },
});
await new Promise((r) => setTimeout(r, 25));
expect(bridgeSendEvent).toHaveBeenCalledWith(
expect.objectContaining({
nodeId: "ios-node",
event: "agent",
}),
);
expect(bridgeSendEvent).toHaveBeenCalledWith(
expect.objectContaining({
nodeId: "ios-node",
event: "chat",
}),
);
await server.close();
});
test("bridge voice transcript defaults to main session", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-main",
updatedAt: Date.now(),
lastChannel: "whatsapp",
lastTo: "+1555",
},
},
null,
2,
),
"utf-8",
);
const port = await getFreePort();
const server = await startGatewayServer(port);
const bridgeCall = bridgeStartCalls.at(-1);
expect(bridgeCall?.onEvent).toBeDefined();
const spy = vi.mocked(agentCommand);
const beforeCalls = spy.mock.calls.length;
await bridgeCall?.onEvent?.("ios-node", {
event: "voice.transcript",
payloadJSON: JSON.stringify({ text: "hello" }),
});
expect(spy.mock.calls.length).toBe(beforeCalls + 1);
const call = spy.mock.calls.at(-1)?.[0] as Record<string, unknown>;
expect(call.sessionId).toBe("sess-main");
expect(call.deliver).toBe(false);
expect(call.surface).toBe("Node");
const stored = JSON.parse(
await fs.readFile(testState.sessionStorePath, "utf-8"),
) as Record<string, { sessionId?: string } | undefined>;
expect(stored.main?.sessionId).toBe("sess-main");
expect(stored["node-ios-node"]).toBeUndefined();
await server.close();
});
test("bridge voice transcript triggers chat events for webchat clients", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-main",
updatedAt: Date.now(),
},
},
null,
2,
),
"utf-8",
);
const { server, ws } = await startServerWithClient();
await connectOk(ws, {
client: {
name: "webchat",
version: "1.0.0",
platform: "test",
mode: "webchat",
},
});
const bridgeCall = bridgeStartCalls.at(-1);
expect(bridgeCall?.onEvent).toBeDefined();
const isVoiceFinalChatEvent = (o: unknown) => {
if (!o || typeof o !== "object") return false;
const rec = o as Record<string, unknown>;
if (rec.type !== "event" || rec.event !== "chat") return false;
if (!rec.payload || typeof rec.payload !== "object") return false;
const payload = rec.payload as Record<string, unknown>;
const runId = typeof payload.runId === "string" ? payload.runId : "";
const state = typeof payload.state === "string" ? payload.state : "";
return runId.startsWith("voice-") && state === "final";
};
const finalChatP = new Promise<{
type: "event";
event: string;
payload?: unknown;
}>((resolve) => {
ws.on("message", (data) => {
const obj = JSON.parse(String(data));
if (isVoiceFinalChatEvent(obj)) {
resolve(obj as never);
}
});
});
await bridgeCall?.onEvent?.("ios-node", {
event: "voice.transcript",
payloadJSON: JSON.stringify({ text: "hello", sessionKey: "main" }),
});
emitAgentEvent({
runId: "sess-main",
seq: 1,
ts: Date.now(),
stream: "assistant",
data: { text: "hi from agent" },
});
emitAgentEvent({
runId: "sess-main",
seq: 2,
ts: Date.now(),
stream: "job",
data: { state: "done" },
});
const evt = await finalChatP;
const payload =
evt.payload && typeof evt.payload === "object"
? (evt.payload as Record<string, unknown>)
: {};
expect(payload.sessionKey).toBe("main");
const message =
payload.message && typeof payload.message === "object"
? (payload.message as Record<string, unknown>)
: {};
expect(message.role).toBe("assistant");
ws.close();
await server.close();
});
test("bridge chat.abort cancels while saving the session store", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-gw-"));
testState.sessionStorePath = path.join(dir, "sessions.json");
await fs.writeFile(
testState.sessionStorePath,
JSON.stringify(
{
main: {
sessionId: "sess-main",
updatedAt: Date.now(),
},
},
null,
2,
),
"utf-8",
);
sessionStoreSaveDelayMs.value = 120;
const port = await getFreePort();
const server = await startGatewayServer(port);
const bridgeCall = bridgeStartCalls.at(-1);
expect(bridgeCall?.onRequest).toBeDefined();
const spy = vi.mocked(agentCommand);
spy.mockImplementationOnce(async (opts) => {
const signal = (opts as { abortSignal?: AbortSignal }).abortSignal;
await new Promise<void>((resolve) => {
if (!signal) return resolve();
if (signal.aborted) return resolve();
signal.addEventListener("abort", () => resolve(), { once: true });
});
});
const sendP = bridgeCall?.onRequest?.("ios-node", {
id: "send-abort-save-bridge-1",
method: "chat.send",
paramsJSON: JSON.stringify({
sessionKey: "main",
message: "hello",
idempotencyKey: "idem-abort-save-bridge-1",
timeoutMs: 30_000,
}),
});
const abortRes = await bridgeCall?.onRequest?.("ios-node", {
id: "abort-save-bridge-1",
method: "chat.abort",
paramsJSON: JSON.stringify({
sessionKey: "main",
runId: "idem-abort-save-bridge-1",
}),
});
expect(abortRes?.ok).toBe(true);
const sendRes = await sendP;
expect(sendRes?.ok).toBe(true);
await server.close();
});
});
+98
View File
@@ -0,0 +1,98 @@
import { describe, expect, test } from "vitest";
import { readConfigFileSnapshot, writeConfigFile } from "../config/config.js";
import {
connectOk,
installGatewayTestHooks,
rpcReq,
startServerWithClient,
} from "./test-helpers.js";
installGatewayTestHooks();
describe("gateway server providers", () => {
test("providers.status returns snapshot without probe", async () => {
const prevToken = process.env.TELEGRAM_BOT_TOKEN;
delete process.env.TELEGRAM_BOT_TOKEN;
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const res = await rpcReq<{
whatsapp?: { linked?: boolean };
telegram?: {
configured?: boolean;
tokenSource?: string;
probe?: unknown;
lastProbeAt?: unknown;
};
signal?: {
configured?: boolean;
probe?: unknown;
lastProbeAt?: unknown;
};
}>(ws, "providers.status", { probe: false, timeoutMs: 2000 });
expect(res.ok).toBe(true);
expect(res.payload?.whatsapp).toBeTruthy();
expect(res.payload?.telegram?.configured).toBe(false);
expect(res.payload?.telegram?.tokenSource).toBe("none");
expect(res.payload?.telegram?.probe).toBeUndefined();
expect(res.payload?.telegram?.lastProbeAt).toBeNull();
expect(res.payload?.signal?.configured).toBe(false);
expect(res.payload?.signal?.probe).toBeUndefined();
expect(res.payload?.signal?.lastProbeAt).toBeNull();
ws.close();
await server.close();
if (prevToken === undefined) {
delete process.env.TELEGRAM_BOT_TOKEN;
} else {
process.env.TELEGRAM_BOT_TOKEN = prevToken;
}
});
test("web.logout reports no session when missing", async () => {
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const res = await rpcReq<{ cleared?: boolean }>(ws, "web.logout");
expect(res.ok).toBe(true);
expect(res.payload?.cleared).toBe(false);
ws.close();
await server.close();
});
test("telegram.logout clears bot token from config", async () => {
const prevToken = process.env.TELEGRAM_BOT_TOKEN;
delete process.env.TELEGRAM_BOT_TOKEN;
await writeConfigFile({
telegram: {
botToken: "123:abc",
groups: { "*": { requireMention: false } },
},
});
const { server, ws } = await startServerWithClient();
await connectOk(ws);
const res = await rpcReq<{ cleared?: boolean; envToken?: boolean }>(
ws,
"telegram.logout",
);
expect(res.ok).toBe(true);
expect(res.payload?.cleared).toBe(true);
expect(res.payload?.envToken).toBe(false);
const snap = await readConfigFileSnapshot();
expect(snap.valid).toBe(true);
expect(snap.config?.telegram?.botToken).toBeUndefined();
expect(snap.config?.telegram?.groups?.["*"]?.requireMention).toBe(false);
ws.close();
await server.close();
if (prevToken === undefined) {
delete process.env.TELEGRAM_BOT_TOKEN;
} else {
process.env.TELEGRAM_BOT_TOKEN = prevToken;
}
});
});
+211
View File
@@ -0,0 +1,211 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, test } from "vitest";
import {
connectOk,
installGatewayTestHooks,
piSdkMock,
rpcReq,
startServerWithClient,
testState,
} from "./test-helpers.js";
installGatewayTestHooks();
describe("gateway server sessions", () => {
test("lists and patches session store via sessions.* RPC", async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdis-sessions-"));
const storePath = path.join(dir, "sessions.json");
const now = Date.now();
testState.sessionStorePath = storePath;
await fs.writeFile(
path.join(dir, "sess-main.jsonl"),
`${Array.from({ length: 10 })
.map((_, idx) =>
JSON.stringify({ role: "user", content: `line ${idx}` }),
)
.join("\n")}\n`,
"utf-8",
);
await fs.writeFile(
path.join(dir, "sess-group.jsonl"),
`${JSON.stringify({ role: "user", content: "group line 0" })}\n`,
"utf-8",
);
await fs.writeFile(
storePath,
JSON.stringify(
{
main: {
sessionId: "sess-main",
updatedAt: now - 30_000,
inputTokens: 10,
outputTokens: 20,
thinkingLevel: "low",
verboseLevel: "on",
},
"discord:group:dev": {
sessionId: "sess-group",
updatedAt: now - 120_000,
totalTokens: 50,
},
global: {
sessionId: "sess-global",
updatedAt: now - 10_000,
},
},
null,
2,
),
"utf-8",
);
const { server, ws } = await startServerWithClient();
const hello = await connectOk(ws);
expect(
(hello as unknown as { features?: { methods?: string[] } }).features
?.methods,
).toEqual(
expect.arrayContaining([
"sessions.list",
"sessions.patch",
"sessions.reset",
"sessions.delete",
"sessions.compact",
]),
);
const list1 = await rpcReq<{
path: string;
sessions: Array<{
key: string;
totalTokens?: number;
thinkingLevel?: string;
verboseLevel?: string;
}>;
}>(ws, "sessions.list", { includeGlobal: false, includeUnknown: false });
expect(list1.ok).toBe(true);
expect(list1.payload?.path).toBe(storePath);
expect(list1.payload?.sessions.some((s) => s.key === "global")).toBe(false);
const main = list1.payload?.sessions.find((s) => s.key === "main");
expect(main?.totalTokens).toBe(30);
expect(main?.thinkingLevel).toBe("low");
expect(main?.verboseLevel).toBe("on");
const active = await rpcReq<{
sessions: Array<{ key: string }>;
}>(ws, "sessions.list", {
includeGlobal: false,
includeUnknown: false,
activeMinutes: 1,
});
expect(active.ok).toBe(true);
expect(active.payload?.sessions.map((s) => s.key)).toEqual(["main"]);
const limited = await rpcReq<{
sessions: Array<{ key: string }>;
}>(ws, "sessions.list", {
includeGlobal: true,
includeUnknown: false,
limit: 1,
});
expect(limited.ok).toBe(true);
expect(limited.payload?.sessions).toHaveLength(1);
expect(limited.payload?.sessions[0]?.key).toBe("global");
const patched = await rpcReq<{ ok: true; key: string }>(
ws,
"sessions.patch",
{ key: "main", thinkingLevel: "medium", verboseLevel: null },
);
expect(patched.ok).toBe(true);
expect(patched.payload?.ok).toBe(true);
expect(patched.payload?.key).toBe("main");
const list2 = await rpcReq<{
sessions: Array<{
key: string;
thinkingLevel?: string;
verboseLevel?: string;
}>;
}>(ws, "sessions.list", {});
expect(list2.ok).toBe(true);
const main2 = list2.payload?.sessions.find((s) => s.key === "main");
expect(main2?.thinkingLevel).toBe("medium");
expect(main2?.verboseLevel).toBeUndefined();
piSdkMock.enabled = true;
piSdkMock.models = [{ id: "gpt-test-a", name: "A", provider: "openai" }];
const modelPatched = await rpcReq<{
ok: true;
entry: { modelOverride?: string; providerOverride?: string };
}>(ws, "sessions.patch", { key: "main", model: "openai/gpt-test-a" });
expect(modelPatched.ok).toBe(true);
expect(modelPatched.payload?.entry.modelOverride).toBe("gpt-test-a");
expect(modelPatched.payload?.entry.providerOverride).toBe("openai");
const compacted = await rpcReq<{ ok: true; compacted: boolean }>(
ws,
"sessions.compact",
{ key: "main", maxLines: 3 },
);
expect(compacted.ok).toBe(true);
expect(compacted.payload?.compacted).toBe(true);
const compactedLines = (
await fs.readFile(path.join(dir, "sess-main.jsonl"), "utf-8")
)
.split(/\r?\n/)
.filter((l) => l.trim().length > 0);
expect(compactedLines).toHaveLength(3);
const filesAfterCompact = await fs.readdir(dir);
expect(
filesAfterCompact.some((f) => f.startsWith("sess-main.jsonl.bak.")),
).toBe(true);
const deleted = await rpcReq<{ ok: true; deleted: boolean }>(
ws,
"sessions.delete",
{ key: "discord:group:dev" },
);
expect(deleted.ok).toBe(true);
expect(deleted.payload?.deleted).toBe(true);
const listAfterDelete = await rpcReq<{
sessions: Array<{ key: string }>;
}>(ws, "sessions.list", {});
expect(listAfterDelete.ok).toBe(true);
expect(
listAfterDelete.payload?.sessions.some(
(s) => s.key === "discord:group:dev",
),
).toBe(false);
const filesAfterDelete = await fs.readdir(dir);
expect(
filesAfterDelete.some((f) => f.startsWith("sess-group.jsonl.deleted.")),
).toBe(true);
const reset = await rpcReq<{
ok: true;
key: string;
entry: { sessionId: string };
}>(ws, "sessions.reset", { key: "main" });
expect(reset.ok).toBe(true);
expect(reset.payload?.key).toBe("main");
expect(reset.payload?.entry.sessionId).not.toBe("sess-main");
const badThinking = await rpcReq(ws, "sessions.patch", {
key: "main",
thinkingLevel: "banana",
});
expect(badThinking.ok).toBe(false);
expect(
(badThinking.error as { message?: unknown } | undefined)?.message ?? "",
).toMatch(/invalid thinkinglevel/i);
ws.close();
await server.close();
});
});
File diff suppressed because it is too large. Load diff
+227 -5736
View File
File diff suppressed because it is too large. Load diff
+34
View File
@@ -0,0 +1,34 @@
import { describe, expect, test } from "vitest";
import type { SessionEntry } from "../config/sessions.js";
import {
capArrayByJsonBytes,
classifySessionKey,
parseGroupKey,
} from "./session-utils.js";
describe("gateway session utils", () => {
test("capArrayByJsonBytes trims from the front", () => {
const res = capArrayByJsonBytes(["a", "b", "c"], 10);
expect(res.items).toEqual(["b", "c"]);
});
test("parseGroupKey handles group prefixes", () => {
expect(parseGroupKey("group:abc")).toEqual({ id: "abc" });
expect(parseGroupKey("discord:group:dev")).toEqual({
surface: "discord",
kind: "group",
id: "dev",
});
expect(parseGroupKey("foo:bar")).toBeNull();
});
test("classifySessionKey respects chat type + prefixes", () => {
expect(classifySessionKey("global")).toBe("global");
expect(classifySessionKey("unknown")).toBe("unknown");
expect(classifySessionKey("group:abc")).toBe("group");
expect(classifySessionKey("discord:group:dev")).toBe("group");
expect(classifySessionKey("main")).toBe("direct");
const entry = { chatType: "group" } as SessionEntry;
expect(classifySessionKey("main", entry)).toBe("group");
});
});
+300
View File
@@ -0,0 +1,300 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { lookupContextTokens } from "../agents/context.js";
import {
DEFAULT_CONTEXT_TOKENS,
DEFAULT_MODEL,
DEFAULT_PROVIDER,
} from "../agents/defaults.js";
import { resolveConfiguredModelRef } from "../agents/model-selection.js";
import { type ClawdisConfig, loadConfig } from "../config/config.js";
import {
buildGroupDisplayName,
loadSessionStore,
resolveStorePath,
type SessionEntry,
} from "../config/sessions.js";
export type GatewaySessionsDefaults = {
model: string | null;
contextTokens: number | null;
};
export type GatewaySessionRow = {
key: string;
kind: "direct" | "group" | "global" | "unknown";
displayName?: string;
surface?: string;
subject?: string;
room?: string;
space?: string;
updatedAt: number | null;
sessionId?: string;
systemSent?: boolean;
abortedLastRun?: boolean;
thinkingLevel?: string;
verboseLevel?: string;
inputTokens?: number;
outputTokens?: number;
totalTokens?: number;
model?: string;
contextTokens?: number;
};
export type SessionsListResult = {
ts: number;
path: string;
count: number;
defaults: GatewaySessionsDefaults;
sessions: GatewaySessionRow[];
};
export type SessionsPatchResult = {
ok: true;
path: string;
key: string;
entry: SessionEntry;
};
export function readSessionMessages(
sessionId: string,
storePath: string | undefined,
): unknown[] {
const candidates = resolveSessionTranscriptCandidates(sessionId, storePath);
const filePath = candidates.find((p) => fs.existsSync(p));
if (!filePath) return [];
const lines = fs.readFileSync(filePath, "utf-8").split(/\r?\n/);
const messages: unknown[] = [];
for (const line of lines) {
if (!line.trim()) continue;
try {
const parsed = JSON.parse(line);
if (parsed?.message) {
messages.push(parsed.message);
}
} catch {
// ignore bad lines
}
}
return messages;
}
export function resolveSessionTranscriptCandidates(
sessionId: string,
storePath: string | undefined,
): string[] {
const candidates: string[] = [];
if (storePath) {
const dir = path.dirname(storePath);
candidates.push(path.join(dir, `${sessionId}.jsonl`));
}
candidates.push(
path.join(os.homedir(), ".clawdis", "sessions", `${sessionId}.jsonl`),
);
return candidates;
}
export function archiveFileOnDisk(filePath: string, reason: string): string {
const ts = new Date().toISOString().replaceAll(":", "-");
const archived = `${filePath}.${reason}.${ts}`;
fs.renameSync(filePath, archived);
return archived;
}
function jsonUtf8Bytes(value: unknown): number {
try {
return Buffer.byteLength(JSON.stringify(value), "utf8");
} catch {
return Buffer.byteLength(String(value), "utf8");
}
}
export function capArrayByJsonBytes<T>(
items: T[],
maxBytes: number,
): { items: T[]; bytes: number } {
if (items.length === 0) return { items, bytes: 2 };
const parts = items.map((item) => jsonUtf8Bytes(item));
let bytes = 2 + parts.reduce((a, b) => a + b, 0) + (items.length - 1);
let start = 0;
while (bytes > maxBytes && start < items.length - 1) {
bytes -= parts[start] + 1;
start += 1;
}
const next = start > 0 ? items.slice(start) : items;
return { items: next, bytes };
}
export function loadSessionEntry(sessionKey: string) {
const cfg = loadConfig();
const sessionCfg = cfg.session;
const storePath = sessionCfg?.store
? resolveStorePath(sessionCfg.store)
: resolveStorePath(undefined);
const store = loadSessionStore(storePath);
const entry = store[sessionKey];
return { cfg, storePath, store, entry };
}
export function classifySessionKey(
key: string,
entry?: SessionEntry,
): GatewaySessionRow["kind"] {
if (key === "global") return "global";
if (key === "unknown") return "unknown";
if (entry?.chatType === "group" || entry?.chatType === "room") return "group";
if (
key.startsWith("group:") ||
key.includes(":group:") ||
key.includes(":channel:")
) {
return "group";
}
return "direct";
}
export function parseGroupKey(
key: string,
): { surface?: string; kind?: "group" | "channel"; id?: string } | null {
if (key.startsWith("group:")) {
const raw = key.slice("group:".length);
return raw ? { id: raw } : null;
}
const parts = key.split(":").filter(Boolean);
if (parts.length >= 3) {
const [surface, kind, ...rest] = parts;
if (kind === "group" || kind === "channel") {
const id = rest.join(":");
return { surface, kind, id };
}
}
return null;
}
export function getSessionDefaults(
cfg: ClawdisConfig,
): GatewaySessionsDefaults {
const resolved = resolveConfiguredModelRef({
cfg,
defaultProvider: DEFAULT_PROVIDER,
defaultModel: DEFAULT_MODEL,
});
const contextTokens =
cfg.agent?.contextTokens ??
lookupContextTokens(resolved.model) ??
DEFAULT_CONTEXT_TOKENS;
return {
model: resolved.model ?? null,
contextTokens: contextTokens ?? null,
};
}
export function resolveSessionModelRef(
cfg: ClawdisConfig,
entry?: SessionEntry,
): { provider: string; model: string } {
const resolved = resolveConfiguredModelRef({
cfg,
defaultProvider: DEFAULT_PROVIDER,
defaultModel: DEFAULT_MODEL,
});
let provider = resolved.provider;
let model = resolved.model;
const storedModelOverride = entry?.modelOverride?.trim();
if (storedModelOverride) {
provider = entry?.providerOverride?.trim() || provider;
model = storedModelOverride;
}
return { provider, model };
}
export function listSessionsFromStore(params: {
cfg: ClawdisConfig;
storePath: string;
store: Record<string, SessionEntry>;
opts: import("./protocol/index.js").SessionsListParams;
}): SessionsListResult {
const { cfg, storePath, store, opts } = params;
const now = Date.now();
const includeGlobal = opts.includeGlobal === true;
const includeUnknown = opts.includeUnknown === true;
const activeMinutes =
typeof opts.activeMinutes === "number" &&
Number.isFinite(opts.activeMinutes)
? Math.max(1, Math.floor(opts.activeMinutes))
: undefined;
let sessions = Object.entries(store)
.filter(([key]) => {
if (!includeGlobal && key === "global") return false;
if (!includeUnknown && key === "unknown") return false;
return true;
})
.map(([key, entry]) => {
const updatedAt = entry?.updatedAt ?? null;
const input = entry?.inputTokens ?? 0;
const output = entry?.outputTokens ?? 0;
const total = entry?.totalTokens ?? input + output;
const parsed = parseGroupKey(key);
const surface = entry?.surface ?? parsed?.surface;
const subject = entry?.subject;
const room = entry?.room;
const space = entry?.space;
const id = parsed?.id;
const displayName =
entry?.displayName ??
(surface
? buildGroupDisplayName({
surface,
subject,
room,
space,
id,
key,
})
: undefined);
return {
key,
kind: classifySessionKey(key, entry),
displayName,
surface,
subject,
room,
space,
updatedAt,
sessionId: entry?.sessionId,
systemSent: entry?.systemSent,
abortedLastRun: entry?.abortedLastRun,
thinkingLevel: entry?.thinkingLevel,
verboseLevel: entry?.verboseLevel,
inputTokens: entry?.inputTokens,
outputTokens: entry?.outputTokens,
totalTokens: total,
model: entry?.model,
contextTokens: entry?.contextTokens,
} satisfies GatewaySessionRow;
})
.sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0));
if (activeMinutes !== undefined) {
const cutoff = now - activeMinutes * 60_000;
sessions = sessions.filter((s) => (s.updatedAt ?? 0) >= cutoff);
}
if (typeof opts.limit === "number" && Number.isFinite(opts.limit)) {
const limit = Math.max(1, Math.floor(opts.limit));
sessions = sessions.slice(0, limit);
}
return {
ts: now,
path: storePath,
count: sessions.length,
defaults: getSessionDefaults(cfg),
sessions,
};
}
+513
View File
@@ -0,0 +1,513 @@
import fs from "node:fs/promises";
import { type AddressInfo, createServer } from "node:net";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, expect, vi } from "vitest";
import { WebSocket } from "ws";
import { agentCommand } from "../commands/agent.js";
import { resetAgentRunContextForTest } from "../infra/agent-events.js";
import { drainSystemEvents, peekSystemEvents } from "../infra/system-events.js";
import { rawDataToString } from "../infra/ws.js";
import { PROTOCOL_VERSION } from "./protocol/index.js";
import type { GatewayServerOptions } from "./server.js";
export type BridgeClientInfo = {
nodeId: string;
displayName?: string;
platform?: string;
version?: string;
remoteIp?: string;
deviceFamily?: string;
modelIdentifier?: string;
caps?: string[];
commands?: string[];
};
export type BridgeStartOpts = {
onAuthenticated?: (node: BridgeClientInfo) => Promise<void> | void;
onDisconnected?: (node: BridgeClientInfo) => Promise<void> | void;
onPairRequested?: (request: unknown) => Promise<void> | void;
onEvent?: (
nodeId: string,
evt: { event: string; payloadJSON?: string | null },
) => Promise<void> | void;
onRequest?: (
nodeId: string,
req: { id: string; method: string; paramsJSON?: string | null },
) => Promise<
| { ok: true; payloadJSON?: string | null }
| { ok: false; error: { code: string; message: string; details?: unknown } }
>;
};
const hoisted = vi.hoisted(() => ({
bridgeStartCalls: [] as BridgeStartOpts[],
bridgeInvoke: vi.fn(async () => ({
type: "invoke-res",
id: "1",
ok: true,
payloadJSON: JSON.stringify({ ok: true }),
error: null,
})),
bridgeListConnected: vi.fn(() => [] as BridgeClientInfo[]),
bridgeSendEvent: vi.fn(),
testTailnetIPv4: { value: undefined as string | undefined },
piSdkMock: {
enabled: false,
discoverCalls: 0,
models: [] as Array<{
id: string;
name?: string;
provider: string;
contextWindow?: number;
reasoning?: boolean;
}>,
},
cronIsolatedRun: vi.fn(async () => ({ status: "ok", summary: "ok" })),
testIsNixMode: { value: false },
sessionStoreSaveDelayMs: { value: 0 },
}));
export const bridgeStartCalls = hoisted.bridgeStartCalls;
export const bridgeInvoke = hoisted.bridgeInvoke;
export const bridgeListConnected = hoisted.bridgeListConnected;
export const bridgeSendEvent = hoisted.bridgeSendEvent;
export const testTailnetIPv4 = hoisted.testTailnetIPv4;
export const piSdkMock = hoisted.piSdkMock;
export const cronIsolatedRun = hoisted.cronIsolatedRun;
export const testState = {
sessionStorePath: undefined as string | undefined,
allowFrom: undefined as string[] | undefined,
cronStorePath: undefined as string | undefined,
cronEnabled: false as boolean | undefined,
gatewayBind: undefined as "auto" | "lan" | "tailnet" | "loopback" | undefined,
gatewayAuth: undefined as Record<string, unknown> | undefined,
hooksConfig: undefined as Record<string, unknown> | undefined,
canvasHostPort: undefined as number | undefined,
legacyIssues: [] as Array<{ path: string; message: string }>,
legacyParsed: {} as Record<string, unknown>,
migrationConfig: null as Record<string, unknown> | null,
migrationChanges: [] as string[],
};
export const testIsNixMode = hoisted.testIsNixMode;
export const sessionStoreSaveDelayMs = hoisted.sessionStoreSaveDelayMs;
vi.mock("@mariozechner/pi-coding-agent", async () => {
const actual = await vi.importActual<
typeof import("@mariozechner/pi-coding-agent")
>("@mariozechner/pi-coding-agent");
return {
...actual,
discoverModels: () => {
if (!piSdkMock.enabled) return actual.discoverModels();
piSdkMock.discoverCalls += 1;
return piSdkMock.models;
},
};
});
vi.mock("../infra/bridge/server.js", () => ({
startNodeBridgeServer: vi.fn(async (opts: BridgeStartOpts) => {
bridgeStartCalls.push(opts);
return {
port: 18790,
close: async () => {},
listConnected: bridgeListConnected,
invoke: bridgeInvoke,
sendEvent: bridgeSendEvent,
};
}),
}));
vi.mock("../cron/isolated-agent.js", () => ({
runCronIsolatedAgentTurn: (...args: unknown[]) => cronIsolatedRun(...args),
}));
vi.mock("../infra/tailnet.js", () => ({
pickPrimaryTailnetIPv4: () => testTailnetIPv4.value,
pickPrimaryTailnetIPv6: () => undefined,
}));
vi.mock("../config/sessions.js", async () => {
const actual = await vi.importActual<typeof import("../config/sessions.js")>(
"../config/sessions.js",
);
return {
...actual,
saveSessionStore: vi.fn(async (storePath: string, store: unknown) => {
const delay = sessionStoreSaveDelayMs.value;
if (delay > 0) {
await new Promise((resolve) => setTimeout(resolve, delay));
}
return actual.saveSessionStore(storePath, store as never);
}),
};
});
vi.mock("../config/config.js", async () => {
const actual = await vi.importActual<typeof import("../config/config.js")>(
"../config/config.js",
);
const resolveConfigPath = () =>
path.join(os.homedir(), ".clawdis", "clawdis.json");
const readConfigFileSnapshot = async () => {
if (testState.legacyIssues.length > 0) {
return {
path: resolveConfigPath(),
exists: true,
raw: JSON.stringify(testState.legacyParsed ?? {}),
parsed: testState.legacyParsed ?? {},
valid: false,
config: {},
issues: testState.legacyIssues.map((issue) => ({
path: issue.path,
message: issue.message,
})),
legacyIssues: testState.legacyIssues,
};
}
const configPath = resolveConfigPath();
try {
await fs.access(configPath);
} catch {
return {
path: configPath,
exists: false,
raw: null,
parsed: {},
valid: true,
config: {},
issues: [],
legacyIssues: [],
};
}
try {
const raw = await fs.readFile(configPath, "utf-8");
const parsed = JSON.parse(raw) as Record<string, unknown>;
return {
path: configPath,
exists: true,
raw,
parsed,
valid: true,
config: parsed,
issues: [],
legacyIssues: [],
};
} catch (err) {
return {
path: configPath,
exists: true,
raw: null,
parsed: {},
valid: false,
config: {},
issues: [{ path: "", message: `read failed: ${String(err)}` }],
legacyIssues: [],
};
}
};
const writeConfigFile = vi.fn(async (cfg: Record<string, unknown>) => {
const configPath = resolveConfigPath();
await fs.mkdir(path.dirname(configPath), { recursive: true });
const raw = JSON.stringify(cfg, null, 2).trimEnd().concat("\n");
await fs.writeFile(configPath, raw, "utf-8");
});
return {
...actual,
CONFIG_PATH_CLAWDIS: resolveConfigPath(),
STATE_DIR_CLAWDIS: path.dirname(resolveConfigPath()),
get isNixMode() {
return testIsNixMode.value;
},
migrateLegacyConfig: (raw: unknown) => ({
config: testState.migrationConfig ?? (raw as Record<string, unknown>),
changes: testState.migrationChanges,
}),
loadConfig: () => ({
agent: {
model: "anthropic/claude-opus-4-5",
workspace: path.join(os.tmpdir(), "clawd-gateway-test"),
},
whatsapp: {
allowFrom: testState.allowFrom,
},
session: { mainKey: "main", store: testState.sessionStorePath },
gateway: (() => {
const gateway: Record<string, unknown> = {};
if (testState.gatewayBind) gateway.bind = testState.gatewayBind;
if (testState.gatewayAuth) gateway.auth = testState.gatewayAuth;
return Object.keys(gateway).length > 0 ? gateway : undefined;
})(),
canvasHost: (() => {
const canvasHost: Record<string, unknown> = {};
if (typeof testState.canvasHostPort === "number")
canvasHost.port = testState.canvasHostPort;
return Object.keys(canvasHost).length > 0 ? canvasHost : undefined;
})(),
hooks: testState.hooksConfig,
cron: (() => {
const cron: Record<string, unknown> = {};
if (typeof testState.cronEnabled === "boolean")
cron.enabled = testState.cronEnabled;
if (typeof testState.cronStorePath === "string")
cron.store = testState.cronStorePath;
return Object.keys(cron).length > 0 ? cron : undefined;
})(),
}),
parseConfigJson5: (raw: string) => {
try {
return { ok: true, parsed: JSON.parse(raw) as unknown };
} catch (err) {
return { ok: false, error: String(err) };
}
},
validateConfigObject: (parsed: unknown) => ({
ok: true,
config: parsed as Record<string, unknown>,
issues: [],
}),
readConfigFileSnapshot,
writeConfigFile,
};
});
vi.mock("../commands/health.js", () => ({
getHealthSnapshot: vi.fn().mockResolvedValue({ ok: true, stub: true }),
}));
vi.mock("../commands/status.js", () => ({
getStatusSummary: vi.fn().mockResolvedValue({ ok: true }),
}));
vi.mock("../web/outbound.js", () => ({
sendMessageWhatsApp: vi
.fn()
.mockResolvedValue({ messageId: "msg-1", toJid: "jid-1" }),
}));
vi.mock("../commands/agent.js", () => ({
agentCommand: vi.fn().mockResolvedValue(undefined),
}));
process.env.CLAWDIS_SKIP_PROVIDERS = "1";
let previousHome: string | undefined;
let tempHome: string | undefined;
export function installGatewayTestHooks() {
beforeEach(async () => {
previousHome = process.env.HOME;
tempHome = await fs.mkdtemp(
path.join(os.tmpdir(), "clawdis-gateway-home-"),
);
process.env.HOME = tempHome;
sessionStoreSaveDelayMs.value = 0;
testTailnetIPv4.value = undefined;
testState.gatewayBind = undefined;
testState.gatewayAuth = undefined;
testState.hooksConfig = undefined;
testState.canvasHostPort = undefined;
testState.legacyIssues = [];
testState.legacyParsed = {};
testState.migrationConfig = null;
testState.migrationChanges = [];
testState.cronEnabled = false;
testState.cronStorePath = undefined;
testState.sessionStorePath = undefined;
testState.allowFrom = undefined;
testIsNixMode.value = false;
cronIsolatedRun.mockClear();
drainSystemEvents();
resetAgentRunContextForTest();
const mod = await import("./server.js");
mod.__resetModelCatalogCacheForTest();
piSdkMock.enabled = false;
piSdkMock.discoverCalls = 0;
piSdkMock.models = [];
});
afterEach(async () => {
process.env.HOME = previousHome;
if (tempHome) {
await fs.rm(tempHome, { recursive: true, force: true });
tempHome = undefined;
}
});
}
export async function getFreePort(): Promise<number> {
return await new Promise((resolve, reject) => {
const server = createServer();
server.listen(0, "127.0.0.1", () => {
const port = (server.address() as AddressInfo).port;
server.close((err) => (err ? reject(err) : resolve(port)));
});
});
}
export async function occupyPort(): Promise<{
server: ReturnType<typeof createServer>;
port: number;
}> {
return await new Promise((resolve, reject) => {
const server = createServer();
server.once("error", reject);
server.listen(0, "127.0.0.1", () => {
const port = (server.address() as AddressInfo).port;
resolve({ server, port });
});
});
}
export function onceMessage<T = unknown>(
ws: WebSocket,
filter: (obj: unknown) => boolean,
timeoutMs = 3000,
): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error("timeout")), timeoutMs);
const closeHandler = (code: number, reason: Buffer) => {
clearTimeout(timer);
ws.off("message", handler);
reject(new Error(`closed ${code}: ${reason.toString()}`));
};
const handler = (data: WebSocket.RawData) => {
const obj = JSON.parse(rawDataToString(data));
if (filter(obj)) {
clearTimeout(timer);
ws.off("message", handler);
ws.off("close", closeHandler);
resolve(obj as T);
}
};
ws.on("message", handler);
ws.once("close", closeHandler);
});
}
export async function startGatewayServer(
port: number,
opts?: GatewayServerOptions,
) {
const mod = await import("./server.js");
return await mod.startGatewayServer(port, opts);
}
export async function startServerWithClient(
token?: string,
opts?: GatewayServerOptions,
) {
const port = await getFreePort();
const prev = process.env.CLAWDIS_GATEWAY_TOKEN;
if (token === undefined) {
delete process.env.CLAWDIS_GATEWAY_TOKEN;
} else {
process.env.CLAWDIS_GATEWAY_TOKEN = token;
}
const server = await startGatewayServer(port, opts);
const ws = new WebSocket(`ws://127.0.0.1:${port}`);
await new Promise<void>((resolve) => ws.once("open", resolve));
return { server, ws, port, prevToken: prev };
}
type ConnectResponse = {
type: "res";
id: string;
ok: boolean;
payload?: unknown;
error?: { message?: string };
};
export async function connectReq(
ws: WebSocket,
opts?: {
token?: string;
password?: string;
minProtocol?: number;
maxProtocol?: number;
client?: {
name: string;
version: string;
platform: string;
mode: string;
instanceId?: string;
};
},
): Promise<ConnectResponse> {
const { randomUUID } = await import("node:crypto");
const id = randomUUID();
ws.send(
JSON.stringify({
type: "req",
id,
method: "connect",
params: {
minProtocol: opts?.minProtocol ?? PROTOCOL_VERSION,
maxProtocol: opts?.maxProtocol ?? PROTOCOL_VERSION,
client: opts?.client ?? {
name: "test",
version: "1.0.0",
platform: "test",
mode: "test",
},
caps: [],
auth:
opts?.token || opts?.password
? {
token: opts?.token,
password: opts?.password,
}
: undefined,
},
}),
);
return await onceMessage<ConnectResponse>(
ws,
(o) => o.type === "res" && o.id === id,
);
}
export async function connectOk(
ws: WebSocket,
opts?: Parameters<typeof connectReq>[1],
) {
const res = await connectReq(ws, opts);
expect(res.ok).toBe(true);
expect((res.payload as { type?: unknown } | undefined)?.type).toBe(
"hello-ok",
);
return res.payload as { type: "hello-ok" };
}
export async function rpcReq<T = unknown>(
ws: WebSocket,
method: string,
params?: unknown,
) {
const { randomUUID } = await import("node:crypto");
const id = randomUUID();
ws.send(JSON.stringify({ type: "req", id, method, params }));
return await onceMessage<{
type: "res";
id: string;
ok: boolean;
payload?: T;
error?: { message?: string; code?: string };
}>(ws, (o) => o.type === "res" && o.id === id);
}
export async function waitForSystemEvent(timeoutMs = 2000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const events = peekSystemEvents();
if (events.length > 0) return events;
await new Promise((resolve) => setTimeout(resolve, 10));
}
throw new Error("timeout waiting for system event");
}
export { agentCommand };
+53
View File
@@ -0,0 +1,53 @@
import { describe, expect, test } from "vitest";
import {
formatForLog,
shortId,
summarizeAgentEventForWsLog,
} from "./ws-log.js";
describe("gateway ws log helpers", () => {
test("shortId compacts uuids and long strings", () => {
expect(shortId("12345678-1234-1234-1234-123456789abc")).toBe(
"12345678…9abc",
);
expect(shortId("a".repeat(30))).toBe("aaaaaaaaaaaa…aaaa");
expect(shortId("short")).toBe("short");
});
test("formatForLog formats errors and messages", () => {
const err = new Error("boom");
err.name = "TestError";
expect(formatForLog(err)).toContain("TestError");
expect(formatForLog(err)).toContain("boom");
const obj = { name: "Oops", message: "failed", code: "E1" };
expect(formatForLog(obj)).toBe("Oops: failed: code=E1");
});
test("summarizeAgentEventForWsLog extracts useful fields", () => {
const summary = summarizeAgentEventForWsLog({
runId: "12345678-1234-1234-1234-123456789abc",
stream: "assistant",
seq: 2,
data: { text: "hello world", mediaUrls: ["a", "b"] },
});
expect(summary).toMatchObject({
run: "12345678…9abc",
stream: "assistant",
aseq: 2,
text: "hello world",
media: 2,
});
const tool = summarizeAgentEventForWsLog({
runId: "run-1",
stream: "tool",
data: { phase: "start", name: "fetch", toolCallId: "call-1" },
});
expect(tool).toMatchObject({
stream: "tool",
tool: "start:fetch",
call: "call-1",
});
});
});
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff. Show more