diff --git a/.agents/archive/PR_WORKFLOW_V1.md b/.agents/archive/PR_WORKFLOW_V1.md deleted file mode 100644 index 1cb6ab653b592..0000000000000 --- a/.agents/archive/PR_WORKFLOW_V1.md +++ /dev/null @@ -1,181 +0,0 @@ -# PR Workflow for Maintainers - -Please read this in full and do not skip sections. -This is the single source of truth for the maintainer PR workflow. - -## Triage order - -Process PRs **oldest to newest**. Older PRs are more likely to have merge conflicts and stale dependencies; resolving them first keeps the queue healthy and avoids snowballing rebase pain. - -## Working rule - -Skills execute workflow. Maintainers provide judgment. -Always pause between skills to evaluate technical direction, not just command success. - -These three skills must be used in order: - -1. `review-pr` — review only, produce findings -2. `prepare-pr` — rebase, fix, gate, push to PR head branch -3. `merge-pr` — squash-merge, verify MERGED state, clean up - -They are necessary, but not sufficient. Maintainers must steer between steps and understand the code before moving forward. - -Treat PRs as reports first, code second. -If submitted code is low quality, ignore it and implement the best solution for the problem. - -Do not continue if you cannot verify the problem is real or test the fix. - -## Coding Agent - -Use ChatGPT 5.3 Codex High. Fall back to 5.2 Codex High or 5.3 Codex Medium if necessary. - -## PR quality bar - -- Do not trust PR code by default. -- Do not merge changes you cannot validate with a reproducible problem and a tested fix. -- Keep types strict. Do not use `any` in implementation code. -- Keep external-input boundaries typed and validated, including CLI input, environment variables, network payloads, and tool output. -- Keep implementations properly scoped. Fix root causes, not local symptoms. -- Identify and reuse canonical sources of truth so behavior does not drift across the codebase. -- Harden changes. Always evaluate security impact and abuse paths. -- Understand the system before changing it. Never make the codebase messier just to clear a PR queue. - -## Rebase and conflict resolution - -Before any substantive review or prep work, **always rebase the PR branch onto current `main` and resolve merge conflicts first**. A PR that cannot cleanly rebase is not ready for review — fix conflicts before evaluating correctness. - -- During `prepare-pr`: rebase onto `main` as the first step, before fixing findings or running gates. -- If conflicts are complex or touch areas you do not understand, stop and escalate. -- Prefer **rebase** for linear history; **squash** when commit history is messy or unhelpful. - -## Commit and changelog rules - -- Create commits with `scripts/committer "" `; avoid manual `git add`/`git commit` so staging stays scoped. -- Follow concise, action-oriented commit messages (e.g., `CLI: add verbose flag to send`). -- During `prepare-pr`, use this commit subject format: `fix: (openclaw#) thanks @`. -- Group related changes; avoid bundling unrelated refactors. -- Changelog workflow: keep the latest released version at the top (no `Unreleased`); after publishing, bump the version and start a new top section. -- When working on a PR: add a changelog entry with the PR number and thank the contributor. -- When working on an issue: reference the issue in the changelog entry. -- Pure test additions/fixes generally do **not** need a changelog entry unless they alter user-facing behavior or the user asks for one. - -## Co-contributor and clawtributors - -- If we squash, add the PR author as a co-contributor in the commit body using a `Co-authored-by:` trailer. -- When maintainer prepares and merges the PR, add the maintainer as an additional `Co-authored-by:` trailer too. -- Avoid `--auto` merges for maintainer landings. Merge only after checks are green so the maintainer account is the actor and attribution is deterministic. -- For squash merges, set `--author-email` to a reviewer-owned email with fallback candidates; if merge fails due to author-email validation, retry once with the next candidate. -- If you review a PR and later do work on it, land via merge/squash (no direct-main commits) and always add the PR author as a co-contributor. -- When merging a PR: leave a PR comment that explains exactly what we did, include the SHA hashes, and record the comment URL in the final report. -- When merging a PR from a new contributor: run `bun scripts/update-clawtributors.ts` to add their avatar to the README "Thanks to all clawtributors" list, then commit the regenerated README. - -## Review mode vs landing mode - -- **Review mode (PR link only):** read `gh pr view`/`gh pr diff`; **do not** switch branches; **do not** change code. -- **Landing mode (exception path):** use only when normal `review-pr -> prepare-pr -> merge-pr` flow cannot safely preserve attribution or cannot satisfy branch protection. Create an integration branch from `main`, bring in PR commits (**prefer rebase** for linear history; **merge allowed** when complexity/conflicts make it safer), apply fixes, add changelog (+ thanks + PR #), run full gate **locally before committing** (`pnpm build && pnpm check && pnpm test`), commit, merge back to `main`, then `git switch main` (never stay on a topic branch after landing). Important: the contributor needs to be in the git graph after this! - -## Pre-review safety checks - -- Before starting a review when a GH Issue/PR is pasted: use an isolated `.worktrees/pr-` checkout from `origin/main`. Do not require a clean main checkout, and do not run `git pull` in a dirty main checkout. -- PR review calls: prefer a single `gh pr view --json ...` to batch metadata/comments; run `gh pr diff` only when needed. -- PRs should summarize scope, note testing performed, and mention any user-facing changes or new flags. -- Read `docs/help/submitting-a-pr.md` ([Submitting a PR](https://docs.openclaw.ai/help/submitting-a-pr)) for what we expect from contributors. - -## Unified workflow - -Entry criteria: - -- PR URL/number is known. -- Problem statement is clear enough to attempt reproduction. -- A realistic verification path exists (tests, integration checks, or explicit manual validation). - -### 1) `review-pr` - -Purpose: - -- Review only: correctness, value, security risk, tests, docs, and changelog impact. -- Produce structured findings and a recommendation. - -Expected output: - -- Recommendation: ready, needs work, needs discussion, or close. -- `.local/review.md` with actionable findings. - -Maintainer checkpoint before `prepare-pr`: - -``` -What problem are they trying to solve? -What is the most optimal implementation? -Can we fix up everything? -Do we have any questions? -``` - -Stop and escalate instead of continuing if: - -- The problem cannot be reproduced or confirmed. -- The proposed PR scope does not match the stated problem. -- The design introduces unresolved security or trust-boundary concerns. - -### 2) `prepare-pr` - -Purpose: - -- Make the PR merge-ready on its head branch. -- Rebase onto current `main` first, then fix blocker/important findings, then run gates. -- In fresh worktrees, bootstrap dependencies before local gates (`pnpm install --frozen-lockfile`). - -Expected output: - -- Updated code and tests on the PR head branch. -- `.local/prep.md` with changes, verification, and current HEAD SHA. -- Final status: `PR is ready for /mergepr`. - -Maintainer checkpoint before `merge-pr`: - -``` -Is this the most optimal implementation? -Is the code properly scoped? -Is the code properly reusing existing logic in the codebase? -Is the code properly typed? -Is the code hardened? -Do we have enough tests? -Do we need regression tests? -Are tests using fake timers where appropriate? (e.g., debounce/throttle, retry backoff, timeout branches, delayed callbacks, polling loops) -Do not add performative tests, ensure tests are real and there are no regressions. -Do you see any follow-up refactors we should do? -Take your time, fix it properly, refactor if necessary. -Did any changes introduce any potential security vulnerabilities? -``` - -Stop and escalate instead of continuing if: - -- You cannot verify behavior changes with meaningful tests or validation. -- Fixing findings requires broad architecture changes outside safe PR scope. -- Security hardening requirements remain unresolved. - -### 3) `merge-pr` - -Purpose: - -- Merge only after review and prep artifacts are present and checks are green. -- Use deterministic squash merge flow (`--match-head-commit` + explicit subject/body with co-author trailer), then verify the PR ends in `MERGED` state. -- If no required checks are configured on the PR, treat that as acceptable and continue after branch-up-to-date validation. - -Go or no-go checklist before merge: - -- All BLOCKER and IMPORTANT findings are resolved. -- Verification is meaningful and regression risk is acceptably low. -- Docs and changelog are updated when required. -- Required CI checks are green and the branch is not behind `main`. - -Expected output: - -- Successful merge commit and recorded merge SHA. -- Worktree cleanup after successful merge. -- Comment on PR indicating merge was successful. - -Maintainer checkpoint after merge: - -- Were any refactors intentionally deferred and now need follow-up issue(s)? -- Did this reveal broader architecture or test gaps we should address? -- Run `bun scripts/update-clawtributors.ts` if the contributor is new. diff --git a/.agents/archive/merge-pr-v1/SKILL.md b/.agents/archive/merge-pr-v1/SKILL.md deleted file mode 100644 index 0956699eb5524..0000000000000 --- a/.agents/archive/merge-pr-v1/SKILL.md +++ /dev/null @@ -1,304 +0,0 @@ ---- -name: merge-pr -description: Merge a GitHub PR via squash after /prepare-pr. Use when asked to merge a ready PR. Do not push to main or modify code. Ensure the PR ends in MERGED state and clean up worktrees after success. ---- - -# Merge PR - -## Overview - -Merge a prepared PR via deterministic squash merge (`--match-head-commit` + explicit co-author trailer), then clean up the worktree after success. - -## Inputs - -- Ask for PR number or URL. -- If missing, use `.local/prep.env` from the worktree if present. -- If ambiguous, ask. - -## Safety - -- Use `gh pr merge --squash` as the only path to `main`. -- Do not run `git push` at all during merge. -- Do not use `gh pr merge --auto` for maintainer landings. -- Do not run gateway stop commands. Do not kill processes. Do not touch port 18792. - -## Execution Rule - -- Execute the workflow. Do not stop after printing the TODO checklist. -- If delegating, require the delegate to run commands and capture outputs. - -## Known Footguns - -- If you see "fatal: not a git repository", you are in the wrong directory. Move to the repo root and retry. -- Read `.local/review.md`, `.local/prep.md`, and `.local/prep.env` in the worktree. Do not skip. -- Always merge with `--match-head-commit "$PREP_HEAD_SHA"` to prevent racing stale or changed heads. -- Clean up `.worktrees/pr-` only after confirmed `MERGED`. - -## Completion Criteria - -- Ensure `gh pr merge` succeeds. -- Ensure PR state is `MERGED`, never `CLOSED`. -- Record the merge SHA. -- Leave a PR comment with merge SHA and prepared head SHA, and capture the comment URL. -- Run cleanup only after merge success. - -## First: Create a TODO Checklist - -Create a checklist of all merge steps, print it, then continue and execute the commands. - -## Setup: Use a Worktree - -Use an isolated worktree for all merge work. - -```sh -repo_root=$(git rev-parse --show-toplevel) -cd "$repo_root" -gh auth status - -WORKTREE_DIR=".worktrees/pr-" -cd "$WORKTREE_DIR" -``` - -Run all commands inside the worktree directory. - -## Load Local Artifacts (Mandatory) - -Expect these files from earlier steps: - -- `.local/review.md` from `/review-pr` -- `.local/prep.md` from `/prepare-pr` -- `.local/prep.env` from `/prepare-pr` - -```sh -ls -la .local || true - -for required in .local/review.md .local/prep.md .local/prep.env; do - if [ ! -f "$required" ]; then - echo "Missing $required. Stop and run /review-pr then /prepare-pr." - exit 1 - fi -done - -sed -n '1,120p' .local/review.md -sed -n '1,120p' .local/prep.md -source .local/prep.env -``` - -## Steps - -1. Identify PR meta and verify prepared SHA still matches - -```sh -pr_meta_json=$(gh pr view --json number,title,state,isDraft,author,headRefName,headRefOid,baseRefName,headRepository,body) -printf '%s\n' "$pr_meta_json" | jq '{number,title,state,isDraft,author:.author.login,head:.headRefName,headSha:.headRefOid,base:.baseRefName,headRepo:.headRepository.nameWithOwner,body}' -pr_title=$(printf '%s\n' "$pr_meta_json" | jq -r .title) -pr_number=$(printf '%s\n' "$pr_meta_json" | jq -r .number) -pr_head_sha=$(printf '%s\n' "$pr_meta_json" | jq -r .headRefOid) -contrib=$(printf '%s\n' "$pr_meta_json" | jq -r .author.login) -is_draft=$(printf '%s\n' "$pr_meta_json" | jq -r .isDraft) - -if [ "$is_draft" = "true" ]; then - echo "ERROR: PR is draft. Stop and run /prepare-pr after draft is cleared." - exit 1 -fi - -if [ "$pr_head_sha" != "$PREP_HEAD_SHA" ]; then - echo "ERROR: PR head changed after /prepare-pr (expected $PREP_HEAD_SHA, got $pr_head_sha). Re-run /prepare-pr." - exit 1 -fi -``` - -2. Run sanity checks - -Stop if any are true: - -- PR is a draft. -- Required checks are failing. -- Branch is behind main. - -If checks are pending, wait for completion before merging. Do not use `--auto`. -If no required checks are configured, continue. - -```sh -gh pr checks --required --watch --fail-fast || true -checks_json=$(gh pr checks --required --json name,bucket,state 2>/tmp/gh-checks.err || true) -if [ -z "$checks_json" ]; then - checks_json='[]' -fi -required_count=$(printf '%s\n' "$checks_json" | jq 'length') -if [ "$required_count" -eq 0 ]; then - echo "No required checks configured for this PR." -fi -printf '%s\n' "$checks_json" | jq -r '.[] | "\(.bucket)\t\(.name)\t\(.state)"' - -failed_required=$(printf '%s\n' "$checks_json" | jq '[.[] | select(.bucket=="fail")] | length') -pending_required=$(printf '%s\n' "$checks_json" | jq '[.[] | select(.bucket=="pending")] | length') -if [ "$failed_required" -gt 0 ]; then - echo "Required checks are failing, run /prepare-pr." - exit 1 -fi -if [ "$pending_required" -gt 0 ]; then - echo "Required checks are still pending, retry /merge-pr when green." - exit 1 -fi - -git fetch origin main -git fetch origin pull//head:pr- --force -git merge-base --is-ancestor origin/main pr- || (echo "PR branch is behind main, run /prepare-pr" && exit 1) -``` - -If anything is failing or behind, stop and say to run `/prepare-pr`. - -3. Merge PR with explicit attribution metadata - -```sh -reviewer=$(gh api user --jq .login) -reviewer_id=$(gh api user --jq .id) -coauthor_email=${COAUTHOR_EMAIL:-"$contrib@users.noreply.github.com"} -if [ -z "$coauthor_email" ] || [ "$coauthor_email" = "null" ]; then - contrib_id=$(gh api users/$contrib --jq .id) - coauthor_email="${contrib_id}+${contrib}@users.noreply.github.com" -fi - -gh_email=$(gh api user --jq '.email // ""' || true) -git_email=$(git config user.email || true) -mapfile -t reviewer_email_candidates < <( - printf '%s\n' \ - "$gh_email" \ - "$git_email" \ - "${reviewer_id}+${reviewer}@users.noreply.github.com" \ - "${reviewer}@users.noreply.github.com" | awk 'NF && !seen[$0]++' -) -[ "${#reviewer_email_candidates[@]}" -gt 0 ] || { echo "ERROR: could not resolve reviewer author email"; exit 1; } -reviewer_email="${reviewer_email_candidates[0]}" - -cat > .local/merge-body.txt < /prepare-pr -> /merge-pr. - -Prepared head SHA: $PREP_HEAD_SHA -Co-authored-by: $contrib <$coauthor_email> -Co-authored-by: $reviewer <$reviewer_email> -Reviewed-by: @$reviewer -EOF - -run_merge() { - local email="$1" - local stderr_file - stderr_file=$(mktemp) - if gh pr merge \ - --squash \ - --delete-branch \ - --match-head-commit "$PREP_HEAD_SHA" \ - --author-email "$email" \ - --subject "$pr_title (#$pr_number)" \ - --body-file .local/merge-body.txt \ - 2> >(tee "$stderr_file" >&2) - then - rm -f "$stderr_file" - return 0 - fi - merge_err=$(cat "$stderr_file") - rm -f "$stderr_file" - return 1 -} - -merge_err="" -selected_merge_author_email="$reviewer_email" -if ! run_merge "$selected_merge_author_email"; then - if printf '%s\n' "$merge_err" | rg -qi 'author.?email|email.*associated|associated.*email|invalid.*email' && [ "${#reviewer_email_candidates[@]}" -ge 2 ]; then - selected_merge_author_email="${reviewer_email_candidates[1]}" - echo "Retrying once with fallback author email: $selected_merge_author_email" - run_merge "$selected_merge_author_email" || { echo "ERROR: merge failed after fallback retry"; exit 1; } - else - echo "ERROR: merge failed" - exit 1 - fi -fi -``` - -Retry is allowed exactly once when the error is clearly author-email validation. - -4. Verify PR state and capture merge SHA - -```sh -state=$(gh pr view --json state --jq .state) -if [ "$state" != "MERGED" ]; then - echo "Merge not finalized yet (state=$state), waiting up to 15 minutes..." - for _ in $(seq 1 90); do - sleep 10 - state=$(gh pr view --json state --jq .state) - if [ "$state" = "MERGED" ]; then - break - fi - done -fi - -if [ "$state" != "MERGED" ]; then - echo "ERROR: PR state is $state after waiting. Leave worktree and retry /merge-pr later." - exit 1 -fi - -merge_sha=$(gh pr view --json mergeCommit --jq '.mergeCommit.oid') -if [ -z "$merge_sha" ] || [ "$merge_sha" = "null" ]; then - echo "ERROR: merge commit SHA missing." - exit 1 -fi - -commit_body=$(gh api repos/:owner/:repo/commits/$merge_sha --jq .commit.message) -contrib=${contrib:-$(gh pr view --json author --jq .author.login)} -reviewer=${reviewer:-$(gh api user --jq .login)} -printf '%s\n' "$commit_body" | rg -q "^Co-authored-by: $contrib <" || { echo "ERROR: missing PR author co-author trailer"; exit 1; } -printf '%s\n' "$commit_body" | rg -q "^Co-authored-by: $reviewer <" || { echo "ERROR: missing reviewer co-author trailer"; exit 1; } - -echo "merge_sha=$merge_sha" -``` - -5. PR comment - -Use a multiline heredoc with interpolation enabled. - -```sh -ok=0 -comment_output="" -for _ in 1 2 3; do - if comment_output=$(gh pr comment -F - <" --force -git branch -D temp/pr- 2>/dev/null || true -git branch -D pr- 2>/dev/null || true -git branch -D pr--prep 2>/dev/null || true -``` - -## Guardrails - -- Worktree only. -- Do not close PRs. -- End in MERGED state. -- Clean up only after merge success. -- Never push to main. Use `gh pr merge --squash` only. -- Do not run `git push` at all in this command. diff --git a/.agents/archive/merge-pr-v1/agents/openai.yaml b/.agents/archive/merge-pr-v1/agents/openai.yaml deleted file mode 100644 index 9c10ae4d271a7..0000000000000 --- a/.agents/archive/merge-pr-v1/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "Merge PR" - short_description: "Merge GitHub PRs via squash" - default_prompt: "Use $merge-pr to merge a GitHub PR via squash after preparation." diff --git a/.agents/archive/prepare-pr-v1/SKILL.md b/.agents/archive/prepare-pr-v1/SKILL.md deleted file mode 100644 index 91c4508a07a40..0000000000000 --- a/.agents/archive/prepare-pr-v1/SKILL.md +++ /dev/null @@ -1,336 +0,0 @@ ---- -name: prepare-pr -description: Prepare a GitHub PR for merge by rebasing onto main, fixing review findings, running gates, committing fixes, and pushing to the PR head branch. Use after /review-pr. Never merge or push to main. ---- - -# Prepare PR - -## Overview - -Prepare a PR head branch for merge with review fixes, green gates, and deterministic merge handoff artifacts. - -## Inputs - -- Ask for PR number or URL. -- If missing, use `.local/pr-meta.env` from the PR worktree if present. -- If ambiguous, ask. - -## Safety - -- Never push to `main` or `origin/main`. Push only to the PR head branch. -- Never run `git push` without explicit remote and branch. Do not run bare `git push`. -- Do not run gateway stop commands. Do not kill processes. Do not touch port 18792. -- Do not run `git clean -fdx`. -- Do not run `git add -A` or `git add .`. - -## Execution Rule - -- Execute the workflow. Do not stop after printing the TODO checklist. -- If delegating, require the delegate to run commands and capture outputs. - -## Completion Criteria - -- Rebase PR commits onto `origin/main`. -- Fix all BLOCKER and IMPORTANT items from `.local/review.md`. -- Commit prep changes with required subject format. -- Run required gates and pass (`pnpm test` may be skipped only for high-confidence docs-only changes). -- Push the updated HEAD back to the PR head branch. -- Write `.local/prep.md` and `.local/prep.env`. -- Output exactly: `PR is ready for /mergepr`. - -## First: Create a TODO Checklist - -Create a checklist of all prep steps, print it, then continue and execute the commands. - -## Setup: Use a Worktree - -Use an isolated worktree for all prep work. - -```sh -repo_root=$(git rev-parse --show-toplevel) -cd "$repo_root" -gh auth status - -WORKTREE_DIR=".worktrees/pr-" -if [ ! -d "$WORKTREE_DIR" ]; then - git fetch origin main - git worktree add "$WORKTREE_DIR" -b temp/pr- origin/main -fi -cd "$WORKTREE_DIR" -mkdir -p .local -``` - -Run all commands inside the worktree directory. - -## Load Review Artifacts (Mandatory) - -```sh -if [ ! -f .local/review.md ]; then - echo "Missing .local/review.md. Run /review-pr first and save findings." - exit 1 -fi - -if [ ! -f .local/pr-meta.env ]; then - echo "Missing .local/pr-meta.env. Run /review-pr first and save metadata." - exit 1 -fi - -sed -n '1,220p' .local/review.md -source .local/pr-meta.env -``` - -## Steps - -1. Identify PR meta with one API call - -```sh -pr_meta_json=$(gh pr view --json number,title,author,headRefName,headRefOid,baseRefName,headRepository,headRepositoryOwner,body) -printf '%s\n' "$pr_meta_json" | jq '{number,title,author:.author.login,head:.headRefName,headSha:.headRefOid,base:.baseRefName,headRepo:.headRepository.nameWithOwner,headRepoOwner:.headRepositoryOwner.login,headRepoName:.headRepository.name,body}' - -pr_number=$(printf '%s\n' "$pr_meta_json" | jq -r .number) -contrib=$(printf '%s\n' "$pr_meta_json" | jq -r .author.login) -head=$(printf '%s\n' "$pr_meta_json" | jq -r .headRefName) -pr_head_sha_before=$(printf '%s\n' "$pr_meta_json" | jq -r .headRefOid) -head_owner=$(printf '%s\n' "$pr_meta_json" | jq -r '.headRepositoryOwner.login // empty') -head_repo_name=$(printf '%s\n' "$pr_meta_json" | jq -r '.headRepository.name // empty') -head_repo_url=$(printf '%s\n' "$pr_meta_json" | jq -r '.headRepository.url // empty') - -if [ -n "${PR_HEAD:-}" ] && [ "$head" != "$PR_HEAD" ]; then - echo "ERROR: PR head branch changed from $PR_HEAD to $head. Re-run /review-pr." - exit 1 -fi -``` - -2. Fetch PR head and rebase on latest `origin/main` - -```sh -git fetch origin pull//head:pr- --force -git checkout -B pr--prep pr- -git fetch origin main -git rebase origin/main -``` - -If conflicts happen: - -- Resolve each conflicted file. -- Run `git add ` for each file. -- Run `git rebase --continue`. - -If the rebase gets confusing or you resolve conflicts 3 or more times, stop and report. - -3. Fix issues from `.local/review.md` - -- Fix all BLOCKER and IMPORTANT items. -- NITs are optional. -- Keep scope tight. - -Keep a running log in `.local/prep.md`: - -- List which review items you fixed. -- List which files you touched. -- Note behavior changes. - -4. Optional quick feedback tests before full gates - -Targeted tests are optional quick feedback, not a substitute for full gates. - -If running targeted tests in a fresh worktree: - -```sh -if [ ! -x node_modules/.bin/vitest ]; then - pnpm install --frozen-lockfile -fi -``` - -5. Commit prep fixes with required subject format - -Use `scripts/committer` with explicit file paths. - -Required subject format: - -- `fix: (openclaw#) thanks @` - -```sh -commit_msg="fix: (openclaw#$pr_number) thanks @$contrib" -scripts/committer "$commit_msg" ... -``` - -If there are no local changes, do not create a no-op commit. - -Post-commit validation (mandatory): - -```sh -subject=$(git log -1 --pretty=%s) -echo "$subject" | rg -q "openclaw#$pr_number" || { echo "ERROR: commit subject missing openclaw#$pr_number"; exit 1; } -echo "$subject" | rg -q "thanks @$contrib" || { echo "ERROR: commit subject missing thanks @$contrib"; exit 1; } -``` - -6. Decide verification mode and run required gates before pushing - -If you are highly confident the change is docs-only, you may skip `pnpm test`. - -High-confidence docs-only criteria (all must be true): - -- Every changed file is documentation-only (`docs/**`, `README*.md`, `CHANGELOG.md`, `*.md`, `*.mdx`, `mintlify.json`, `docs.json`). -- No code, runtime, test, dependency, or build config files changed (`src/**`, `extensions/**`, `apps/**`, `package.json`, lockfiles, TS/JS config, test files, scripts). -- `.local/review.md` does not call for non-doc behavior fixes. - -Suggested check: - -```sh -changed_files=$(git diff --name-only origin/main...HEAD) -non_docs=$(printf "%s\n" "$changed_files" | grep -Ev '^(docs/|README.*\.md$|CHANGELOG\.md$|.*\.md$|.*\.mdx$|mintlify\.json$|docs\.json$)' || true) - -docs_only=false -if [ -n "$changed_files" ] && [ -z "$non_docs" ]; then - docs_only=true -fi - -echo "docs_only=$docs_only" -``` - -Bootstrap dependencies in a fresh worktree before gates: - -```sh -if [ ! -d node_modules ]; then - pnpm install --frozen-lockfile -fi -``` - -Run required gates: - -```sh -pnpm build -pnpm check - -if [ "$docs_only" = "true" ]; then - echo "Docs-only change detected with high confidence; skipping pnpm test." | tee -a .local/prep.md -else - pnpm test -fi -``` - -Require all required gates to pass. If something fails, fix, commit, and rerun. Allow at most 3 fix-and-rerun cycles. - -7. Push safely to the PR head branch - -Build `prhead` from owner/name first, then validate remote branch SHA before push. - -```sh -if [ -n "$head_owner" ] && [ -n "$head_repo_name" ]; then - head_repo_push_url="https://github.com/$head_owner/$head_repo_name.git" -elif [ -n "$head_repo_url" ] && [ "$head_repo_url" != "null" ]; then - case "$head_repo_url" in - *.git) head_repo_push_url="$head_repo_url" ;; - *) head_repo_push_url="$head_repo_url.git" ;; - esac -else - echo "ERROR: unable to determine PR head repo push URL" - exit 1 -fi - -git remote add prhead "$head_repo_push_url" 2>/dev/null || git remote set-url prhead "$head_repo_push_url" - -echo "Pushing to branch: $head" -if [ "$head" = "main" ] || [ "$head" = "master" ]; then - echo "ERROR: head branch is main/master. This is wrong. Stopping." - exit 1 -fi - -remote_sha=$(git ls-remote prhead "refs/heads/$head" | awk '{print $1}') -if [ -z "$remote_sha" ]; then - echo "ERROR: remote branch refs/heads/$head not found on prhead" - exit 1 -fi -if [ "$remote_sha" != "$pr_head_sha_before" ]; then - echo "ERROR: expected remote SHA $pr_head_sha_before, got $remote_sha. Re-fetch metadata and rebase first." - exit 1 -fi - -git push --force-with-lease=refs/heads/$head:$pr_head_sha_before prhead HEAD:$head || push_failed=1 -``` - -If lease push fails because head moved, perform one automatic retry: - -```sh -if [ "${push_failed:-0}" = "1" ]; then - echo "Lease push failed, retrying once with fresh PR head..." - - pr_head_sha_before=$(gh pr view --json headRefOid --jq .headRefOid) - git fetch origin pull//head:pr--latest --force - git rebase pr--latest - - pnpm build - pnpm check - if [ "$docs_only" != "true" ]; then - pnpm test - fi - - git push --force-with-lease=refs/heads/$head:$pr_head_sha_before prhead HEAD:$head -fi -``` - -8. Verify PR head and base relation (Mandatory) - -```sh -prep_head_sha=$(git rev-parse HEAD) -pr_head_sha_after=$(gh pr view --json headRefOid --jq .headRefOid) - -if [ "$prep_head_sha" != "$pr_head_sha_after" ]; then - echo "ERROR: pushed head SHA does not match PR head SHA." - exit 1 -fi - -git fetch origin main -git fetch origin pull//head:pr--verify --force -git merge-base --is-ancestor origin/main pr--verify && echo "PR is up to date with main" || (echo "ERROR: PR is still behind main, rebase again" && exit 1) -git branch -D pr--verify 2>/dev/null || true -``` - -9. Write prep summary artifacts (Mandatory) - -Write `.local/prep.md` and `.local/prep.env` for merge handoff. - -```sh -contrib_id=$(gh api users/$contrib --jq .id) -coauthor_email="${contrib_id}+${contrib}@users.noreply.github.com" - -cat > .local/prep.env < origin/main -else - git worktree add "$WORKTREE_DIR" -b temp/pr- origin/main - cd "$WORKTREE_DIR" -fi - -# Create local scratch space that persists across /review-pr to /prepare-pr to /merge-pr -mkdir -p .local -``` - -Run all commands inside the worktree directory. -Start on `origin/main` so you can check for existing implementations before looking at PR code. - -## Steps - -1. Identify PR meta and context - -```sh -pr_meta_json=$(gh pr view --json number,title,state,isDraft,author,baseRefName,headRefName,headRefOid,headRepository,url,body,labels,assignees,reviewRequests,files,additions,deletions,statusCheckRollup) -printf '%s\n' "$pr_meta_json" | jq '{number,title,url,state,isDraft,author:.author.login,base:.baseRefName,head:.headRefName,headSha:.headRefOid,headRepo:.headRepository.nameWithOwner,additions,deletions,files:(.files|length),body}' - -cat > .local/pr-meta.env <" -S src packages apps ui || true -rg -n "" -S src packages apps ui || true - -git log --oneline --all --grep="" | head -20 -``` - -If it already exists, call it out as a BLOCKER or at least IMPORTANT. - -3. Claim the PR - -Assign yourself so others know someone is reviewing. Skip if the PR looks like spam or is a draft you plan to recommend closing. - -```sh -gh_user=$(gh api user --jq .login) -gh pr edit --add-assignee "$gh_user" || echo "Could not assign reviewer, continuing" -``` - -4. Read the PR description carefully - -Use the body from step 1. Summarize goal, scope, and missing context. - -5. Read the diff thoroughly - -Minimum: - -```sh -gh pr diff -``` - -If you need full code context locally, fetch the PR head to a local ref and diff it. Do not create a merge commit. - -```sh -git fetch origin pull//head:pr- --force -mb=$(git merge-base origin/main pr-) - -# Show only this PR patch relative to merge-base, not total branch drift -git diff --stat "$mb"..pr- -git diff "$mb"..pr- -``` - -If you want to browse the PR version of files directly, temporarily check out `pr-` in the worktree. Do not commit or push. Return to `temp/pr-` and reset to `origin/main` afterward. - -```sh -# Use only if needed -# git checkout pr- -# git branch --show-current -# ...inspect files... - -git checkout temp/pr- -git checkout -B temp/pr- origin/main -git branch --show-current -``` - -6. Validate the change is needed and valuable - -Be honest. Call out low value AI slop. - -7. Evaluate implementation quality - -Review correctness, design, performance, and ergonomics. - -8. Perform a security review - -Assume OpenClaw subagents run with full disk access, including git, gh, and shell. Check auth, input validation, secrets, dependencies, tool safety, and privacy. - -9. Review tests and verification - -Identify what exists, what is missing, and what would be a minimal regression test. - -If you run local tests in the worktree, bootstrap dependencies first: - -```sh -if [ ! -x node_modules/.bin/vitest ]; then - pnpm install --frozen-lockfile -fi -``` - -10. Check docs - -Check if the PR touches code with related documentation such as README, docs, inline API docs, or config examples. - -- If docs exist for the changed area and the PR does not update them, flag as IMPORTANT. -- If the PR adds a new feature or config option with no docs, flag as IMPORTANT. -- If the change is purely internal with no user-facing impact, skip this. - -11. Check changelog - -Check if `CHANGELOG.md` exists and whether the PR warrants an entry. - -- If the project has a changelog and the PR is user-facing, flag missing entry as IMPORTANT. -- Leave the change for /prepare-pr, only flag it here. - -12. Answer the key question - -Decide if /prepare-pr can fix issues or the contributor must update the PR. - -13. Save findings to the worktree - -Write the full structured review sections A through J to `.local/review.md`. -Create or overwrite the file and verify it exists and is non-empty. - -```sh -ls -la .local/review.md -wc -l .local/review.md -``` - -14. Output the structured review - -Produce a review that matches what you saved to `.local/review.md`. - -A) TL;DR recommendation - -- One of: READY FOR /prepare-pr | NEEDS WORK | NEEDS DISCUSSION | NOT USEFUL (CLOSE) -- 1 to 3 sentences. - -B) What changed - -C) What is good - -D) Security findings - -E) Concerns or questions (actionable) - -- Numbered list. -- Mark each item as BLOCKER, IMPORTANT, or NIT. -- For each, point to file or area and propose a concrete fix. - -F) Tests - -G) Docs status - -- State if related docs are up to date, missing, or not applicable. - -H) Changelog - -- State if `CHANGELOG.md` needs an entry and which category. - -I) Follow ups (optional) - -J) Suggested PR comment (optional) - -## Guardrails - -- Worktree only. -- Do not delete the worktree after review. -- Review only, do not merge, do not push. diff --git a/.agents/archive/review-pr-v1/agents/openai.yaml b/.agents/archive/review-pr-v1/agents/openai.yaml deleted file mode 100644 index f6593499507c4..0000000000000 --- a/.agents/archive/review-pr-v1/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "Review PR" - short_description: "Review GitHub PRs without merging" - default_prompt: "Use $review-pr to perform a thorough, review-only GitHub PR review." diff --git a/.agents/maintainers.md b/.agents/maintainers.md new file mode 100644 index 0000000000000..2bbb9c6203ee4 --- /dev/null +++ b/.agents/maintainers.md @@ -0,0 +1 @@ +Maintainer skills now live in [`openclaw/maintainers`](https://github.com/openclaw/maintainers/). diff --git a/.agents/skills/PR_WORKFLOW.md b/.agents/skills/PR_WORKFLOW.md deleted file mode 100644 index 8696ba1b69e9d..0000000000000 --- a/.agents/skills/PR_WORKFLOW.md +++ /dev/null @@ -1,245 +0,0 @@ -# PR Workflow for Maintainers - -Please read this in full and do not skip sections. -This is the single source of truth for the maintainer PR workflow. - -## Working rule - -Skills execute workflow. Maintainers provide judgment. -Always pause between skills to evaluate technical direction, not just command success. - -These three skills must be used in order: - -1. `review-pr` — review only, produce findings -2. `prepare-pr` — rebase, fix, gate, push to PR head branch -3. `merge-pr` — squash-merge, verify MERGED state, clean up - -They are necessary, but not sufficient. Maintainers must steer between steps and understand the code before moving forward. - -Treat PRs as reports first, code second. -If submitted code is low quality, ignore it and implement the best solution for the problem. - -Do not continue if you cannot verify the problem is real or test the fix. - -## Script-first contract - -Skill runs should invoke these wrappers automatically. You only need to run them manually when debugging or doing an explicit script-only run: - -- `scripts/pr-review ` -- `scripts/pr review-checkout-main ` or `scripts/pr review-checkout-pr ` while reviewing -- `scripts/pr review-guard ` before writing review outputs -- `scripts/pr review-validate-artifacts ` after writing outputs -- `scripts/pr-prepare init ` -- `scripts/pr-prepare validate-commit ` -- `scripts/pr-prepare gates ` -- `scripts/pr-prepare push ` -- Optional one-shot prepare: `scripts/pr-prepare run ` -- `scripts/pr-merge ` (verify-only; short form remains backward compatible) -- `scripts/pr-merge verify ` (verify-only) -- Optional one-shot merge: `scripts/pr-merge run ` - -These wrappers run shared preflight checks and generate deterministic artifacts. They are designed to work from repo root or PR worktree cwd. - -## Required artifacts - -- `.local/pr-meta.json` and `.local/pr-meta.env` from review init. -- `.local/review.md` and `.local/review.json` from review output. -- `.local/prep-context.env` and `.local/prep.md` from prepare. -- `.local/prep.env` from prepare completion. - -## Structured review handoff - -`review-pr` must write `.local/review.json`. -In normal skill runs this is handled automatically. Use `scripts/pr review-artifacts-init ` and `scripts/pr review-tests ...` manually only for debugging or explicit script-only runs. - -Minimum schema: - -```json -{ - "recommendation": "READY FOR /prepare-pr", - "findings": [ - { - "id": "F1", - "severity": "IMPORTANT", - "title": "Missing changelog entry", - "area": "CHANGELOG.md", - "fix": "Add a Fixes entry for PR #" - } - ], - "tests": { - "ran": ["pnpm test -- ..."], - "gaps": ["..."], - "result": "pass" - } -} -``` - -`prepare-pr` resolves all `BLOCKER` and `IMPORTANT` findings from this file. - -## Coding Agent - -Use ChatGPT 5.3 Codex High. Fall back to 5.2 Codex High or 5.3 Codex Medium if necessary. - -## PR quality bar - -- Do not trust PR code by default. -- Do not merge changes you cannot validate with a reproducible problem and a tested fix. -- Keep types strict. Do not use `any` in implementation code. -- Keep external-input boundaries typed and validated, including CLI input, environment variables, network payloads, and tool output. -- Keep implementations properly scoped. Fix root causes, not local symptoms. -- Identify and reuse canonical sources of truth so behavior does not drift across the codebase. -- Harden changes. Always evaluate security impact and abuse paths. -- Understand the system before changing it. Never make the codebase messier just to clear a PR queue. - -## Rebase and conflict resolution - -Before any substantive review or prep work, **always rebase the PR branch onto current `main` and resolve merge conflicts first**. A PR that cannot cleanly rebase is not ready for review — fix conflicts before evaluating correctness. - -- During `prepare-pr`: rebase onto `main` as the first step, before fixing findings or running gates. -- If conflicts are complex or touch areas you do not understand, stop and escalate. -- Prefer **rebase** for linear history; **squash** when commit history is messy or unhelpful. - -## Commit and changelog rules - -- In normal `prepare-pr` runs, commits are created via `scripts/committer "" `. Use it manually only when operating outside the skill flow; avoid manual `git add`/`git commit` so staging stays scoped. -- Follow concise, action-oriented commit messages (e.g., `CLI: add verbose flag to send`). -- During `prepare-pr`, use concise, action-oriented subjects **without** PR numbers or thanks; reserve `(#) thanks @` for the final merge/squash commit. -- Group related changes; avoid bundling unrelated refactors. -- Changelog workflow: keep the latest released version at the top (no `Unreleased`); after publishing, bump the version and start a new top section. -- When working on a PR: add a changelog entry line with the PR number `(#)` and `thanks @` when author metadata is available (mandatory in this workflow). -- When working on an issue: reference the issue in the changelog entry. -- In this workflow, changelog is always required even for internal/test-only changes. - -## Gate policy - -In fresh worktrees, dependency bootstrap is handled by wrappers before local gates. Manual equivalent: - -```sh -pnpm install --frozen-lockfile -``` - -Gate set: - -- Always: `pnpm build`, `pnpm check` -- `pnpm test` required unless high-confidence docs-only criteria pass. - -## Co-contributor and clawtributors - -- If we squash, add the PR author as a co-contributor in the commit body using a `Co-authored-by:` trailer. -- When maintainer prepares and merges the PR, add the maintainer as an additional `Co-authored-by:` trailer too. -- Avoid `--auto` merges for maintainer landings. Merge only after checks are green so the maintainer account is the actor and attribution is deterministic. -- For squash merges, set `--author-email` to a reviewer-owned email with fallback candidates; if merge fails due to author-email validation, retry once with the next candidate. -- If you review a PR and later do work on it, land via merge/squash (no direct-main commits) and always add the PR author as a co-contributor. -- When merging a PR: leave a PR comment that explains exactly what we did, include the SHA hashes, and record the comment URL in the final report. -- Manual post-merge step for new contributors: run `bun scripts/update-clawtributors.ts` to add their avatar to the README "Thanks to all clawtributors" list, then commit the regenerated README. - -## Review mode vs landing mode - -- **Review mode (PR link only):** read `gh pr view`/`gh pr diff`; **do not** switch branches; **do not** change code. -- **Landing mode (exception path):** use only when normal `review-pr -> prepare-pr -> merge-pr` flow cannot safely preserve attribution or cannot satisfy branch protection. Create an integration branch from `main`, bring in PR commits (**prefer rebase** for linear history; **merge allowed** when complexity/conflicts make it safer), apply fixes, add changelog (+ thanks + PR #), run full gate **locally before committing** (`pnpm build && pnpm check && pnpm test`), commit, merge back to `main`, then `git switch main` (never stay on a topic branch after landing). Important: the contributor needs to be in the git graph after this! - -## Pre-review safety checks - -- Before starting a review when a GH Issue/PR is pasted: `review-pr`/`scripts/pr-review` should create and use an isolated `.worktrees/pr-` checkout from `origin/main` automatically. Do not require a clean main checkout, and do not run `git pull` in a dirty main checkout. -- PR review calls: prefer a single `gh pr view --json ...` to batch metadata/comments; run `gh pr diff` only when needed. -- PRs should summarize scope, note testing performed, and mention any user-facing changes or new flags. -- Read `docs/help/submitting-a-pr.md` ([Submitting a PR](https://docs.openclaw.ai/help/submitting-a-pr)) for what we expect from contributors. - -## Unified workflow - -Entry criteria: - -- PR URL/number is known. -- Problem statement is clear enough to attempt reproduction. -- A realistic verification path exists (tests, integration checks, or explicit manual validation). - -### 1) `review-pr` - -Purpose: - -- Review only: correctness, value, security risk, tests, docs, and changelog impact. -- Produce structured findings and a recommendation. - -Expected output: - -- Recommendation: ready, needs work, needs discussion, or close. -- `.local/review.md` with actionable findings. - -Maintainer checkpoint before `prepare-pr`: - -``` -What problem are they trying to solve? -What is the most optimal implementation? -Can we fix up everything? -Do we have any questions? -``` - -Stop and escalate instead of continuing if: - -- The problem cannot be reproduced or confirmed. -- The proposed PR scope does not match the stated problem. -- The design introduces unresolved security or trust-boundary concerns. - -### 2) `prepare-pr` - -Purpose: - -- Make the PR merge-ready on its head branch. -- Rebase onto current `main` first, then fix blocker/important findings, then run gates. -- In fresh worktrees, bootstrap dependencies before local gates (`pnpm install --frozen-lockfile`). - -Expected output: - -- Updated code and tests on the PR head branch. -- `.local/prep.md` with changes, verification, and current HEAD SHA. -- Final status: `PR is ready for /merge-pr`. - -Maintainer checkpoint before `merge-pr`: - -``` -Is this the most optimal implementation? -Is the code properly scoped? -Is the code properly reusing existing logic in the codebase? -Is the code properly typed? -Is the code hardened? -Do we have enough tests? -Do we need regression tests? -Are tests using fake timers where appropriate? (e.g., debounce/throttle, retry backoff, timeout branches, delayed callbacks, polling loops) -Do not add performative tests, ensure tests are real and there are no regressions. -Do you see any follow-up refactors we should do? -Did any changes introduce any potential security vulnerabilities? -Take your time, fix it properly, refactor if necessary. -``` - -Stop and escalate instead of continuing if: - -- You cannot verify behavior changes with meaningful tests or validation. -- Fixing findings requires broad architecture changes outside safe PR scope. -- Security hardening requirements remain unresolved. - -### 3) `merge-pr` - -Purpose: - -- Merge only after review and prep artifacts are present and checks are green. -- Use deterministic squash merge flow (`--match-head-commit` + explicit subject/body with co-author trailer), then verify the PR ends in `MERGED` state. -- If no required checks are configured on the PR, treat that as acceptable and continue after branch-up-to-date validation. - -Go or no-go checklist before merge: - -- All BLOCKER and IMPORTANT findings are resolved. -- Verification is meaningful and regression risk is acceptably low. -- Changelog is updated (mandatory) and docs are updated when required. -- Required CI checks are green and the branch is not behind `main`. - -Expected output: - -- Successful merge commit and recorded merge SHA. -- Worktree cleanup after successful merge. -- Comment on PR indicating merge was successful. - -Maintainer checkpoint after merge: - -- Were any refactors intentionally deferred and now need follow-up issue(s)? -- Did this reveal broader architecture or test gaps we should address? -- Run `bun scripts/update-clawtributors.ts` if the contributor is new. diff --git a/.agents/skills/merge-pr/SKILL.md b/.agents/skills/merge-pr/SKILL.md deleted file mode 100644 index 91b7c4aa4e2e5..0000000000000 --- a/.agents/skills/merge-pr/SKILL.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -name: merge-pr -description: Script-first deterministic squash merge with strict required-check gating, head-SHA pinning, and reliable attribution/commenting. ---- - -# Merge PR - -## Overview - -Merge a prepared PR only after deterministic validation. - -## Inputs - -- Ask for PR number or URL. -- If missing, use `.local/prep.env` from the PR worktree. - -## Safety - -- Never use `gh pr merge --auto` in this flow. -- Never run `git push` directly. -- Require `--match-head-commit` during merge. -- Wrapper commands are cwd-agnostic; you can run them from repo root or inside the PR worktree. - -## Execution Contract - -1. Validate merge readiness: - -```sh -scripts/pr-merge verify -``` - -Backward-compatible verify form also works: - -```sh -scripts/pr-merge -``` - -2. Run one-shot deterministic merge: - -```sh -scripts/pr-merge run -``` - -3. Capture and report these values in a human-readable summary (not raw `key=value` lines): - -- Merge commit SHA -- Merge author email -- Merge completion comment URL -- PR URL - -## Steps - -1. Validate artifacts - -```sh -require=(.local/review.md .local/review.json .local/prep.md .local/prep.env) -for f in "${require[@]}"; do - [ -s "$f" ] || { echo "Missing artifact: $f"; exit 1; } -done -``` - -2. Validate checks and branch status - -```sh -scripts/pr-merge verify -source .local/prep.env -``` - -`scripts/pr-merge` treats “no required checks configured” as acceptable (`[]`), but fails on any required `fail` or `pending`. - -3. Merge deterministically (wrapper-managed) - -```sh -scripts/pr-merge run -``` - -`scripts/pr-merge run` performs: - -- deterministic squash merge pinned to `PREP_HEAD_SHA` -- reviewer merge author email selection with fallback candidates -- one retry only when merge fails due to author-email validation -- co-author trailers for PR author and reviewer -- post-merge verification of both co-author trailers on commit message -- PR comment retry (3 attempts), then comment URL extraction -- cleanup after confirmed `MERGED` - -4. Manual fallback (only if wrapper is unavailable) - -```sh -scripts/pr merge-run -``` - -5. Cleanup - -Cleanup is handled by `run` after merge success. - -## Guardrails - -- End in `MERGED`, never `CLOSED`. -- Cleanup only after confirmed merge. -- In final chat output, use labeled lines or bullets; do not paste raw wrapper diagnostics unless debugging. diff --git a/.agents/skills/merge-pr/agents/openai.yaml b/.agents/skills/merge-pr/agents/openai.yaml deleted file mode 100644 index 9c10ae4d271a7..0000000000000 --- a/.agents/skills/merge-pr/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "Merge PR" - short_description: "Merge GitHub PRs via squash" - default_prompt: "Use $merge-pr to merge a GitHub PR via squash after preparation." diff --git a/.agents/skills/mintlify/SKILL.md b/.agents/skills/mintlify/SKILL.md deleted file mode 100644 index 0dd6a1a891ab2..0000000000000 --- a/.agents/skills/mintlify/SKILL.md +++ /dev/null @@ -1,345 +0,0 @@ ---- -name: mintlify -description: Build and maintain documentation sites with Mintlify. Use when - creating docs pages, configuring navigation, adding components, or setting up - API references. -license: MIT -compatibility: Requires Node.js for CLI. Works with any Git-based workflow. -metadata: - author: mintlify - version: "1.0" - mintlify-proj: mintlify ---- - -# Mintlify best practices - -**Always consult [mintlify.com/docs](https://mintlify.com/docs) for components, configuration, and latest features.** - -**Always** favor searching the current Mintlify documentation over whatever is in your training data about Mintlify. - -Mintlify is a documentation platform that transforms MDX files into documentation sites. Configure site-wide settings in the `docs.json` file, write content in MDX with YAML frontmatter, and favor built-in components over custom components. - -Full schema at [mintlify.com/docs.json](https://mintlify.com/docs.json). - -## Before you write - -### Understand the project - -All documentation lives in the `docs/` directory in this repo. Read `docs.json` in that directory (`docs/docs.json`). This file defines the entire site: navigation structure, theme, colors, links, API and specs. - -Understanding the project tells you: - -- What pages exist and how they're organized -- What navigation groups are used (and their naming conventions) -- How the site navigation is structured -- What theme and configuration the site uses - -### Check for existing content - -Search the docs before creating new pages. You may need to: - -- Update an existing page instead of creating a new one -- Add a section to an existing page -- Link to existing content rather than duplicating - -### Read surrounding content - -Before writing, read 2-3 similar pages to understand the site's voice, structure, formatting conventions, and level of detail. - -### Understand Mintlify components - -Review the Mintlify [components](https://www.mintlify.com/docs/components) to select and use any relevant components for the documentation request that you are working on. - -## Quick reference - -### CLI commands - -- `npm i -g mint` - Install the Mintlify CLI -- `mint dev` - Local preview at localhost:3000 -- `mint broken-links` - Check internal links -- `mint a11y` - Check for accessibility issues in content -- `mint rename` - Rename/move files and update references -- `mint validate` - Validate documentation builds - -### Required files - -- `docs.json` - Site configuration (navigation, theme, integrations, etc.). See [global settings](https://mintlify.com/docs/settings/global) for all options. -- `*.mdx` files - Documentation pages with YAML frontmatter - -### Example file structure - -``` -project/ -├── docs.json # Site configuration -├── introduction.mdx -├── quickstart.mdx -├── guides/ -│ └── example.mdx -├── openapi.yml # API specification -├── images/ # Static assets -│ └── example.png -└── snippets/ # Reusable components - └── component.jsx -``` - -## Page frontmatter - -Every page requires `title` in its frontmatter. Include `description` for SEO and navigation. - -```yaml theme={null} ---- -title: "Clear, descriptive title" -description: "Concise summary for SEO and navigation." ---- -``` - -Optional frontmatter fields: - -- `sidebarTitle`: Short title for sidebar navigation. -- `icon`: Lucide or Font Awesome icon name, URL, or file path. -- `tag`: Label next to the page title in the sidebar (for example, "NEW"). -- `mode`: Page layout mode (`default`, `wide`, `custom`). -- `keywords`: Array of terms related to the page content for local search and SEO. -- Any custom YAML fields for use with personalization or conditional content. - -## File conventions - -- Match existing naming patterns in the directory -- If there are no existing files or inconsistent file naming patterns, use kebab-case: `getting-started.mdx`, `api-reference.mdx` -- Use root-relative paths without file extensions for internal links: `/getting-started/quickstart` -- Do not use relative paths (`../`) or absolute URLs for internal pages -- When you create a new page, add it to `docs.json` navigation or it won't appear in the sidebar - -## Organize content - -When a user asks about anything related to site-wide configurations, start by understanding the [global settings](https://www.mintlify.com/docs/organize/settings). See if a setting in the `docs.json` file can be updated to achieve what the user wants. - -### Navigation - -The `navigation` property in `docs.json` controls site structure. Choose one primary pattern at the root level, then nest others within it. - -**Choose your primary pattern:** - -| Pattern | When to use | -| ------------- | ---------------------------------------------------------------------------------------------- | -| **Groups** | Default. Single audience, straightforward hierarchy | -| **Tabs** | Distinct sections with different audiences (Guides vs API Reference) or content types | -| **Anchors** | Want persistent section links at sidebar top. Good for separating docs from external resources | -| **Dropdowns** | Multiple doc sections users switch between, but not distinct enough for tabs | -| **Products** | Multi-product company with separate documentation per product | -| **Versions** | Maintaining docs for multiple API/product versions simultaneously | -| **Languages** | Localized content | - -**Within your primary pattern:** - -- **Groups** - Organize related pages. Can nest groups within groups, but keep hierarchy shallow -- **Menus** - Add dropdown navigation within tabs for quick jumps to specific pages -- **`expanded: false`** - Collapse nested groups by default. Use for reference sections users browse selectively -- **`openapi`** - Auto-generate pages from OpenAPI spec. Add at group/tab level to inherit - -**Common combinations:** - -- Tabs containing groups (most common for docs with API reference) -- Products containing tabs (multi-product SaaS) -- Versions containing tabs (versioned API docs) -- Anchors containing groups (simple docs with external resource links) - -### Links and paths - -- **Internal links:** Root-relative, no extension: `/getting-started/quickstart` -- **Images:** Store in `/images`, reference as `/images/example.png` -- **External links:** Use full URLs, they open in new tabs automatically - -## Customize docs sites - -**What to customize where:** - -- **Brand colors, fonts, logo** → `docs.json`. See [global settings](https://mintlify.com/docs/settings/global) -- **Component styling, layout tweaks** → `custom.css` at project root -- **Dark mode** → Enabled by default. Only disable with `"appearance": "light"` in `docs.json` if brand requires it - -Start with `docs.json`. Only add `custom.css` when you need styling that config doesn't support. - -## Write content - -### Components - -The [components overview](https://mintlify.com/docs/components) organizes all components by purpose: structure content, draw attention, show/hide content, document APIs, link to pages, and add visual context. Start there to find the right component. - -**Common decision points:** - -| Need | Use | -| -------------------------- | ----------------------- | -| Hide optional details | `` | -| Long code examples | `` | -| User chooses one option | `` | -| Linked navigation cards | `` in `` | -| Sequential instructions | `` | -| Code in multiple languages | `` | -| API parameters | `` | -| API response fields | `` | - -**Callouts by severity:** - -- `` - Supplementary info, safe to skip -- `` - Helpful context such as permissions -- `` - Recommendations or best practices -- `` - Potentially destructive actions -- `` - Success confirmation - -### Reusable content - -**When to use snippets:** - -- Exact content appears on more than one page -- Complex components you want to maintain in one place -- Shared content across teams/repos - -**When NOT to use snippets:** - -- Slight variations needed per page (leads to complex props) - -Import snippets with `import { Component } from "/path/to/snippet-name.jsx"`. - -## Writing standards - -### Voice and structure - -- Second-person voice ("you") -- Active voice, direct language -- Sentence case for headings ("Getting started", not "Getting Started") -- Sentence case for code block titles ("Expandable example", not "Expandable Example") -- Lead with context: explain what something is before how to use it -- Prerequisites at the start of procedural content - -### What to avoid - -**Never use:** - -- Marketing language ("powerful", "seamless", "robust", "cutting-edge") -- Filler phrases ("it's important to note", "in order to") -- Excessive conjunctions ("moreover", "furthermore", "additionally") -- Editorializing ("obviously", "simply", "just", "easily") - -**Watch for AI-typical patterns:** - -- Overly formal or stilted phrasing -- Unnecessary repetition of concepts -- Generic introductions that don't add value -- Concluding summaries that restate what was just said - -### Formatting - -- All code blocks must have language tags -- All images and media must have descriptive alt text -- Use bold and italics only when they serve the reader's understanding--never use text styling just for decoration -- No decorative formatting or emoji - -### Code examples - -- Keep examples simple and practical -- Use realistic values (not "foo" or "bar") -- One clear example is better than multiple variations -- Test that code works before including it - -## Document APIs - -**Choose your approach:** - -- **Have an OpenAPI spec?** → Add to `docs.json` with `"openapi": ["openapi.yaml"]`. Pages auto-generate. Reference in navigation as `GET /endpoint` -- **No spec?** → Write endpoints manually with `api: "POST /users"` in frontmatter. More work but full control -- **Hybrid** → Use OpenAPI for most endpoints, manual pages for complex workflows - -Encourage users to generate endpoint pages from an OpenAPI spec. It is the most efficient and easiest to maintain option. - -## Deploy - -Mintlify deploys automatically when changes are pushed to the connected Git repository. - -**What agents can configure:** - -- **Redirects** → Add to `docs.json` with `"redirects": [{"source": "/old", "destination": "/new"}]` -- **SEO indexing** → Control with `"seo": {"indexing": "all"}` to include hidden pages in search - -**Requires dashboard setup (human task):** - -- Custom domains and subdomains -- Preview deployment settings -- DNS configuration - -For `/docs` subpath hosting with Vercel or Cloudflare, agents can help configure rewrite rules. See [/docs subpath](https://mintlify.com/docs/deploy/vercel). - -## Workflow - -### 1. Understand the task - -Identify what needs to be documented, which pages are affected, and what the reader should accomplish afterward. If any of these are unclear, ask. - -### 2. Research - -- Read `docs/docs.json` to understand the site structure -- Search existing docs for related content -- Read similar pages to match the site's style - -### 3. Plan - -- Synthesize what the reader should accomplish after reading the docs and the current content -- Propose any updates or new content -- Verify that your proposed changes will help readers be successful - -### 4. Write - -- Start with the most important information -- Keep sections focused and scannable -- Use components appropriately (don't overuse them) -- Mark anything uncertain with a TODO comment: - -```mdx theme={null} -{/* TODO: Verify the default timeout value */} -``` - -### 5. Update navigation - -If you created a new page, add it to the appropriate group in `docs.json`. - -### 6. Verify - -Before submitting: - -- [ ] Frontmatter includes title and description -- [ ] All code blocks have language tags -- [ ] Internal links use root-relative paths without file extensions -- [ ] New pages are added to `docs.json` navigation -- [ ] Content matches the style of surrounding pages -- [ ] No marketing language or filler phrases -- [ ] TODOs are clearly marked for anything uncertain -- [ ] Run `mint broken-links` to check links -- [ ] Run `mint validate` to find any errors - -## Edge cases - -### Migrations - -If a user asks about migrating to Mintlify, ask if they are using ReadMe or Docusaurus. If they are, use the [@mintlify/scraping](https://www.npmjs.com/package/@mintlify/scraping) CLI to migrate content. If they are using a different platform to host their documentation, help them manually convert their content to MDX pages using Mintlify components. - -### Hidden pages - -Any page that is not included in the `docs.json` navigation is hidden. Use hidden pages for content that should be accessible by URL or indexed for the assistant or search, but not discoverable through the sidebar navigation. - -### Exclude pages - -The `.mintignore` file is used to exclude files from a documentation repository from being processed. - -## Common gotchas - -1. **Component imports** - JSX components need explicit import, MDX components don't -2. **Frontmatter required** - Every MDX file needs `title` at minimum -3. **Code block language** - Always specify language identifier -4. **Never use `mint.json`** - `mint.json` is deprecated. Only ever use `docs.json` - -## Resources - -- [Documentation](https://mintlify.com/docs) -- [Configuration schema](https://mintlify.com/docs.json) -- [Feature requests](https://github.com/orgs/mintlify/discussions/categories/feature-requests) -- [Bugs and feedback](https://github.com/orgs/mintlify/discussions/categories/bugs-feedback) diff --git a/.agents/skills/prepare-pr/SKILL.md b/.agents/skills/prepare-pr/SKILL.md deleted file mode 100644 index d2834a84b4a15..0000000000000 --- a/.agents/skills/prepare-pr/SKILL.md +++ /dev/null @@ -1,127 +0,0 @@ ---- -name: prepare-pr -description: Script-first PR preparation with structured findings resolution, deterministic push safety, and explicit gate execution. ---- - -# Prepare PR - -## Overview - -Prepare the PR head branch for merge after `/review-pr`. - -## Inputs - -- Ask for PR number or URL. -- If missing, use `.local/pr-meta.env` if present in the PR worktree. - -## Safety - -- Never push to `main`. -- Only push to PR head with explicit `--force-with-lease` against known head SHA. -- Do not run `git clean -fdx`. -- Wrappers are cwd-agnostic; run from repo root or PR worktree. - -## Execution Contract - -1. Run setup: - -```sh -scripts/pr-prepare init -``` - -2. Resolve findings from structured review: - -- `.local/review.json` is mandatory. -- Resolve all `BLOCKER` and `IMPORTANT` items. - -3. Commit scoped changes with concise subjects (no PR number/thanks; those belong on the final merge/squash commit). - -4. Run gates via wrapper. - -5. Push via wrapper (includes pre-push remote verification, one automatic lease-retry path, and post-push API propagation retry). - -Optional one-shot path: - -```sh -scripts/pr-prepare run -``` - -## Steps - -1. Setup and artifacts - -```sh -scripts/pr-prepare init - -ls -la .local/review.md .local/review.json .local/pr-meta.env .local/prep-context.env -jq . .local/review.json >/dev/null -``` - -2. Resolve required findings - -List required items: - -```sh -jq -r '.findings[] | select(.severity=="BLOCKER" or .severity=="IMPORTANT") | "- [\(.severity)] \(.id): \(.title) => \(.fix)"' .local/review.json -``` - -Fix all required findings. Keep scope tight. - -3. Update changelog/docs (changelog is mandatory in this workflow) - -```sh -jq -r '.changelog' .local/review.json -jq -r '.docs' .local/review.json -``` - -Changelog gate requirement: - -- `CHANGELOG.md` must include a newly added changelog entry line. -- When PR author metadata is available, that same changelog entry line must include `(#) thanks @`. - -4. Commit scoped changes - -Use concise, action-oriented subject lines without PR numbers/thanks. The final merge/squash commit is the only place we include PR numbers and contributor thanks. - -Use explicit file list: - -```sh -scripts/committer "fix: " ... -``` - -5. Run gates - -```sh -scripts/pr-prepare gates -``` - -6. Push safely to PR head - -```sh -scripts/pr-prepare push -``` - -This push step includes: - -- robust fork remote resolution from owner/name, -- pre-push remote SHA verification, -- one automatic rebase + gate rerun + retry if lease push fails, -- post-push PR-head propagation retry, -- idempotent behavior when local prep HEAD is already on the PR head, -- post-push SHA verification and `.local/prep.env` generation. - -7. Verify handoff artifacts - -```sh -ls -la .local/prep.md .local/prep.env -``` - -8. Output - -- Summarize resolved findings and gate results. -- Print exactly: `PR is ready for /merge-pr`. - -## Guardrails - -- Do not run `gh pr merge` in this skill. -- Do not delete worktree. diff --git a/.agents/skills/prepare-pr/agents/openai.yaml b/.agents/skills/prepare-pr/agents/openai.yaml deleted file mode 100644 index 290b1b5ab616d..0000000000000 --- a/.agents/skills/prepare-pr/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "Prepare PR" - short_description: "Prepare GitHub PRs for merge" - default_prompt: "Use $prepare-pr to prep a GitHub PR for merge without merging." diff --git a/.agents/skills/review-pr/SKILL.md b/.agents/skills/review-pr/SKILL.md deleted file mode 100644 index f5694ca2c416c..0000000000000 --- a/.agents/skills/review-pr/SKILL.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -name: review-pr -description: Script-first review-only GitHub pull request analysis. Use for deterministic PR review with structured findings handoff to /prepare-pr. ---- - -# Review PR - -## Overview - -Perform a read-only review and produce both human and machine-readable outputs. - -## Inputs - -- Ask for PR number or URL. -- If missing, always ask. - -## Safety - -- Never push, merge, or modify code intended to keep. -- Work only in `.worktrees/pr-`. -- Wrapper commands are cwd-agnostic; you can run them from repo root or inside the PR worktree. - -## Execution Contract - -1. Run wrapper setup: - -```sh -scripts/pr-review -``` - -2. Use explicit branch mode switches: - -- Main baseline mode: `scripts/pr review-checkout-main ` -- PR-head mode: `scripts/pr review-checkout-pr ` - -3. Before writing review outputs, run branch guard: - -```sh -scripts/pr review-guard -``` - -4. Write both outputs: - -- `.local/review.md` with sections A through J. -- `.local/review.json` with structured findings. - -5. Validate artifacts semantically: - -```sh -scripts/pr review-validate-artifacts -``` - -## Steps - -1. Setup and metadata - -```sh -scripts/pr-review -ls -la .local/pr-meta.json .local/pr-meta.env .local/review-context.env .local/review-mode.env -``` - -2. Existing implementation check on main - -```sh -scripts/pr review-checkout-main -rg -n "" -S src extensions apps || true -git log --oneline --all --grep "" | head -20 -``` - -3. Claim PR - -```sh -gh_user=$(gh api user --jq .login) -gh pr edit --add-assignee "$gh_user" || echo "Could not assign reviewer, continuing" -``` - -4. Read PR description and diff - -```sh -scripts/pr review-checkout-pr -gh pr diff - -source .local/review-context.env -git diff --stat "$MERGE_BASE"..pr- -git diff "$MERGE_BASE"..pr- -``` - -5. Optional local tests - -Use the wrapper for target validation and executed-test verification: - -```sh -scripts/pr review-tests [ ...] -``` - -6. Initialize review artifact templates - -```sh -scripts/pr review-artifacts-init -``` - -7. Produce review outputs - -- Fill `.local/review.md` sections A through J. -- Fill `.local/review.json`. - -Minimum JSON shape: - -```json -{ - "recommendation": "READY FOR /prepare-pr", - "findings": [ - { - "id": "F1", - "severity": "IMPORTANT", - "title": "...", - "area": "path/or/component", - "fix": "Actionable fix" - } - ], - "tests": { - "ran": [], - "gaps": [], - "result": "pass" - }, - "docs": "up_to_date|missing|not_applicable", - "changelog": "required" -} -``` - -8. Guard + validate before final output - -```sh -scripts/pr review-guard -scripts/pr review-validate-artifacts -``` - -## Guardrails - -- Keep review read-only. -- Do not delete worktree. -- Use merge-base scoped diff for local context to avoid stale branch drift. diff --git a/.agents/skills/review-pr/agents/openai.yaml b/.agents/skills/review-pr/agents/openai.yaml deleted file mode 100644 index f6593499507c4..0000000000000 --- a/.agents/skills/review-pr/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "Review PR" - short_description: "Review GitHub PRs without merging" - default_prompt: "Use $review-pr to perform a thorough, review-only GitHub PR review." diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 56a343c38d802..927aa7079cf0f 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -13,7 +13,7 @@ body: attributes: label: Summary description: One-sentence statement of what is broken. - placeholder: After upgrading to 2026.2.13, Telegram thread replies fail with "reply target not found". + placeholder: After upgrading to , behavior regressed from . validations: required: true - type: textarea @@ -48,7 +48,7 @@ body: attributes: label: OpenClaw version description: Exact version/build tested. - placeholder: 2026.2.13 + placeholder: validations: required: true - type: input @@ -83,7 +83,7 @@ body: - Frequency (always/intermittent/edge case) - Consequence (missed messages, failed onboarding, extra cost, etc.) placeholder: | - Affected: Telegram group users on 2026.2.13 + Affected: Telegram group users on Severity: High (blocks replies) Frequency: 100% repro Consequence: Agents cannot respond in threads @@ -92,4 +92,4 @@ body: attributes: label: Additional information description: Add any context that helps triage but does not fit above. - placeholder: Regression started after upgrade from 2026.2.12; temporary workaround is restarting gateway every 30m. + placeholder: Regression started after upgrade from ; temporary workaround is ... diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 1b38a9ddf05b0..4c1b97755975a 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -2,7 +2,7 @@ blank_issues_enabled: false contact_links: - name: Onboarding url: https://discord.gg/clawd - about: New to OpenClaw? Join Discord for setup guidance from Krill in \#help. + about: "New to OpenClaw? Join Discord for setup guidance in #help." - name: Support url: https://discord.gg/clawd - about: Get help from Krill and the community on Discord in \#help. + about: "Get help from the OpenClaw community on Discord in #help." diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index 3594b73a2c5be..a08b456786ec4 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -21,7 +21,7 @@ body: attributes: label: Problem to solve description: What user pain this solves and why current behavior is insufficient. - placeholder: Teams cannot distinguish agent personas in mixed channels, causing misrouted follow-ups. + placeholder: Agents cannot distinguish persona context in mixed channels, causing misrouted follow-ups. validations: required: true - type: textarea diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml index e660d2a97612a..f02fbddb3e85f 100644 --- a/.github/actionlint.yaml +++ b/.github/actionlint.yaml @@ -4,8 +4,11 @@ self-hosted-runner: labels: # Blacksmith CI runners - - blacksmith-4vcpu-ubuntu-2404 - - blacksmith-4vcpu-windows-2025 + - blacksmith-8vcpu-ubuntu-2404 + - blacksmith-8vcpu-windows-2025 + - blacksmith-16vcpu-ubuntu-2404 + - blacksmith-16vcpu-windows-2025 + - blacksmith-16vcpu-ubuntu-2404-arm # Ignore patterns for known issues paths: @@ -15,3 +18,5 @@ paths: - "shellcheck reported issue.+" # Ignore intentional if: false for disabled jobs - 'constant expression "false" in condition' + # actionlint's built-in runner label allowlist lags Blacksmith additions. + - 'label "blacksmith-16vcpu-[^"]+" is unknown\.' diff --git a/.github/actions/setup-node-env/action.yml b/.github/actions/setup-node-env/action.yml index a722982004b91..334cd3c24fb94 100644 --- a/.github/actions/setup-node-env/action.yml +++ b/.github/actions/setup-node-env/action.yml @@ -37,7 +37,7 @@ runs: exit 1 - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: ${{ inputs.node-version }} check-latest: true @@ -70,14 +70,29 @@ runs: shell: bash env: CI: "true" + FROZEN_LOCKFILE: ${{ inputs.frozen-lockfile }} run: | + set -euo pipefail export PATH="$NODE_BIN:$PATH" which node node -v pnpm -v - LOCKFILE_FLAG="" - if [ "${{ inputs.frozen-lockfile }}" = "true" ]; then - LOCKFILE_FLAG="--frozen-lockfile" + case "$FROZEN_LOCKFILE" in + true) LOCKFILE_FLAG="--frozen-lockfile" ;; + false) LOCKFILE_FLAG="" ;; + *) + echo "::error::Invalid frozen-lockfile input: '$FROZEN_LOCKFILE' (expected true or false)" + exit 2 + ;; + esac + + install_args=( + install + --ignore-scripts=false + --config.engine-strict=false + --config.enable-pre-post-scripts=true + ) + if [ -n "$LOCKFILE_FLAG" ]; then + install_args+=("$LOCKFILE_FLAG") fi - pnpm install $LOCKFILE_FLAG --ignore-scripts=false --config.engine-strict=false --config.enable-pre-post-scripts=true || \ - pnpm install $LOCKFILE_FLAG --ignore-scripts=false --config.engine-strict=false --config.enable-pre-post-scripts=true + pnpm "${install_args[@]}" || pnpm "${install_args[@]}" diff --git a/.github/actions/setup-pnpm-store-cache/action.yml b/.github/actions/setup-pnpm-store-cache/action.yml index c866393ee430b..8e25492ac9229 100644 --- a/.github/actions/setup-pnpm-store-cache/action.yml +++ b/.github/actions/setup-pnpm-store-cache/action.yml @@ -14,11 +14,17 @@ runs: steps: - name: Setup pnpm (corepack retry) shell: bash + env: + PNPM_VERSION: ${{ inputs.pnpm-version }} run: | set -euo pipefail + if [[ ! "$PNPM_VERSION" =~ ^[0-9]+(\.[0-9]+){1,2}([.-][0-9A-Za-z.-]+)?$ ]]; then + echo "::error::Invalid pnpm-version input: '$PNPM_VERSION'" + exit 2 + fi corepack enable for attempt in 1 2 3; do - if corepack prepare "pnpm@${{ inputs.pnpm-version }}" --activate; then + if corepack prepare "pnpm@$PNPM_VERSION" --activate; then pnpm -v exit 0 fi diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 829604b4ce311..0a965febb1c3d 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -111,3 +111,16 @@ updates: - minor - patch open-pull-requests-limit: 5 + + # Docker base images + - package-ecosystem: docker + directory: / + schedule: + interval: weekly + cooldown: + default-days: 7 + groups: + docker-images: + patterns: + - "*" + open-pull-requests-limit: 5 diff --git a/.github/workflows/auto-response.yml b/.github/workflows/auto-response.yml index 630db1d12a6e1..1502456a25119 100644 --- a/.github/workflows/auto-response.yml +++ b/.github/workflows/auto-response.yml @@ -13,7 +13,7 @@ jobs: permissions: issues: write pull-requests: write - runs-on: self-hosted + runs-on: blacksmith-16vcpu-ubuntu-2404 steps: - uses: actions/create-github-app-token@d72941d797fd3113feb6b93fd0dec494b13a2547 # v1 id: app-token @@ -134,7 +134,7 @@ jobs: const invalidLabel = "invalid"; const dirtyLabel = "dirty"; const noisyPrMessage = - "Closing this PR because it looks dirty (too many unrelated commits). Please recreate the PR from a clean branch."; + "Closing this PR because it looks dirty (too many unrelated or unexpected changes). This usually happens when a branch picks up unrelated commits or a merge went sideways. Please recreate the PR from a clean branch."; const pullRequest = context.payload.pull_request; if (pullRequest) { diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index efaf8039a3761..abb5b50a5ce8c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,7 +13,7 @@ jobs: # Detect docs-only changes to skip heavy jobs (test, build, Windows, macOS, Android). # Lint and format always run. Fail-safe: if detection fails, run everything. docs-scope: - runs-on: blacksmith-4vcpu-ubuntu-2404 + runs-on: blacksmith-16vcpu-ubuntu-2404 outputs: docs_only: ${{ steps.check.outputs.docs_only }} docs_changed: ${{ steps.check.outputs.docs_changed }} @@ -33,7 +33,7 @@ jobs: changed-scope: needs: [docs-scope] if: needs.docs-scope.outputs.docs_only != 'true' - runs-on: blacksmith-4vcpu-ubuntu-2404 + runs-on: blacksmith-16vcpu-ubuntu-2404 outputs: run_node: ${{ steps.scope.outputs.run_node }} run_macos: ${{ steps.scope.outputs.run_macos }} @@ -127,7 +127,7 @@ jobs: build-artifacts: needs: [docs-scope, changed-scope, check] if: needs.docs-scope.outputs.docs_only != 'true' && (github.event_name == 'push' || needs.changed-scope.outputs.run_node == 'true') - runs-on: blacksmith-4vcpu-ubuntu-2404 + runs-on: blacksmith-16vcpu-ubuntu-2404 steps: - name: Checkout uses: actions/checkout@v4 @@ -153,7 +153,7 @@ jobs: release-check: needs: [docs-scope, build-artifacts] if: github.event_name == 'push' && needs.docs-scope.outputs.docs_only != 'true' - runs-on: blacksmith-4vcpu-ubuntu-2404 + runs-on: blacksmith-16vcpu-ubuntu-2404 steps: - name: Checkout uses: actions/checkout@v4 @@ -177,7 +177,7 @@ jobs: checks: needs: [docs-scope, changed-scope, check] if: needs.docs-scope.outputs.docs_only != 'true' && (github.event_name == 'push' || needs.changed-scope.outputs.run_node == 'true') - runs-on: blacksmith-4vcpu-ubuntu-2404 + runs-on: blacksmith-16vcpu-ubuntu-2404 strategy: fail-fast: false matrix: @@ -244,7 +244,7 @@ jobs: name: "check" needs: [docs-scope] if: needs.docs-scope.outputs.docs_only != 'true' - runs-on: blacksmith-4vcpu-ubuntu-2404 + runs-on: blacksmith-16vcpu-ubuntu-2404 steps: - name: Checkout uses: actions/checkout@v4 @@ -259,11 +259,50 @@ jobs: - name: Check types and lint and oxfmt run: pnpm check + # Report-only dead-code scans. Runs after scope detection and stores machine-readable + # results as artifacts for later triage before we enable hard gates. + # Temporarily disabled in CI while we process initial findings. + deadcode: + name: dead-code report + needs: [docs-scope, changed-scope] + # if: needs.docs-scope.outputs.docs_only != 'true' && (github.event_name == 'push' || needs.changed-scope.outputs.run_node == 'true') + if: false + runs-on: blacksmith-16vcpu-ubuntu-2404 + strategy: + fail-fast: false + matrix: + include: + - tool: knip + command: pnpm deadcode:report:ci:knip + - tool: ts-prune + command: pnpm deadcode:report:ci:ts-prune + - tool: ts-unused-exports + command: pnpm deadcode:report:ci:ts-unused + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + submodules: false + + - name: Setup Node environment + uses: ./.github/actions/setup-node-env + with: + install-bun: "false" + + - name: Run ${{ matrix.tool }} dead-code scan + run: ${{ matrix.command }} + + - name: Upload dead-code results + uses: actions/upload-artifact@v4 + with: + name: dead-code-${{ matrix.tool }}-${{ github.run_id }} + path: .artifacts/deadcode + # Validate docs (format, lint, broken links) only when docs files changed. check-docs: needs: [docs-scope] if: needs.docs-scope.outputs.docs_changed == 'true' - runs-on: blacksmith-4vcpu-ubuntu-2404 + runs-on: blacksmith-16vcpu-ubuntu-2404 steps: - name: Checkout uses: actions/checkout@v4 @@ -279,7 +318,7 @@ jobs: run: pnpm check:docs secrets: - runs-on: blacksmith-4vcpu-ubuntu-2404 + runs-on: blacksmith-16vcpu-ubuntu-2404 steps: - name: Checkout uses: actions/checkout@v4 @@ -306,10 +345,10 @@ jobs: checks-windows: needs: [docs-scope, changed-scope, build-artifacts, check] if: needs.docs-scope.outputs.docs_only != 'true' && (github.event_name == 'push' || needs.changed-scope.outputs.run_node == 'true') - runs-on: blacksmith-4vcpu-windows-2025 + runs-on: blacksmith-16vcpu-windows-2025 env: NODE_OPTIONS: --max-old-space-size=4096 - # Keep total concurrency predictable on the 4 vCPU runner: + # Keep total concurrency predictable on the 16 vCPU runner: # `scripts/test-parallel.mjs` runs some vitest suites in parallel processes. OPENCLAW_TEST_WORKERS: 2 defaults: @@ -368,7 +407,7 @@ jobs: test -s dist/plugin-sdk/index.js - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 22.x check-latest: true @@ -660,7 +699,7 @@ jobs: android: needs: [docs-scope, changed-scope, check] if: needs.docs-scope.outputs.docs_only != 'true' && (github.event_name == 'push' || needs.changed-scope.outputs.run_android == 'true') - runs-on: blacksmith-4vcpu-ubuntu-2404 + runs-on: blacksmith-16vcpu-ubuntu-2404 strategy: fail-fast: false matrix: diff --git a/.github/workflows/docker-release.yml b/.github/workflows/docker-release.yml index 28d6164bc5618..fc0d97d409139 100644 --- a/.github/workflows/docker-release.yml +++ b/.github/workflows/docker-release.yml @@ -24,7 +24,7 @@ env: jobs: # Build amd64 image build-amd64: - runs-on: ubuntu-latest + runs-on: blacksmith-16vcpu-ubuntu-2404 permissions: packages: write contents: read @@ -83,7 +83,7 @@ jobs: # Build arm64 image build-arm64: - runs-on: ubuntu-24.04-arm + runs-on: blacksmith-16vcpu-ubuntu-2404-arm permissions: packages: write contents: read @@ -142,7 +142,7 @@ jobs: # Create multi-platform manifest create-manifest: - runs-on: ubuntu-latest + runs-on: blacksmith-16vcpu-ubuntu-2404 permissions: packages: write contents: read diff --git a/.github/workflows/install-smoke.yml b/.github/workflows/install-smoke.yml index 45154a5fab4f8..03e87db82b9e5 100644 --- a/.github/workflows/install-smoke.yml +++ b/.github/workflows/install-smoke.yml @@ -12,7 +12,7 @@ concurrency: jobs: docs-scope: - runs-on: ubuntu-latest + runs-on: blacksmith-16vcpu-ubuntu-2404 outputs: docs_only: ${{ steps.check.outputs.docs_only }} steps: @@ -28,13 +28,13 @@ jobs: install-smoke: needs: [docs-scope] if: needs.docs-scope.outputs.docs_only != 'true' - runs-on: ubuntu-latest + runs-on: blacksmith-16vcpu-ubuntu-2404 steps: - name: Checkout CLI uses: actions/checkout@v4 - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 22.x check-latest: true diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index 7a3c4b1457c07..9ac44dfa6b671 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -23,7 +23,7 @@ jobs: permissions: contents: read pull-requests: write - runs-on: self-hosted + runs-on: blacksmith-16vcpu-ubuntu-2404 steps: - uses: actions/create-github-app-token@d72941d797fd3113feb6b93fd0dec494b13a2547 # v1 id: app-token @@ -200,7 +200,7 @@ jobs: permissions: contents: read pull-requests: write - runs-on: self-hosted + runs-on: blacksmith-16vcpu-ubuntu-2404 steps: - uses: actions/create-github-app-token@d72941d797fd3113feb6b93fd0dec494b13a2547 # v1 id: app-token @@ -440,7 +440,7 @@ jobs: label-issues: permissions: issues: write - runs-on: self-hosted + runs-on: blacksmith-16vcpu-ubuntu-2404 steps: - uses: actions/create-github-app-token@d72941d797fd3113feb6b93fd0dec494b13a2547 # v1 id: app-token diff --git a/.github/workflows/sandbox-common-smoke.yml b/.github/workflows/sandbox-common-smoke.yml index c92a05c3aeb68..26c0dcc106f8e 100644 --- a/.github/workflows/sandbox-common-smoke.yml +++ b/.github/workflows/sandbox-common-smoke.yml @@ -19,7 +19,7 @@ concurrency: jobs: sandbox-common-smoke: - runs-on: ubuntu-latest + runs-on: blacksmith-16vcpu-ubuntu-2404 steps: - name: Checkout uses: actions/checkout@v4 diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index 7210fb7a73960..6248a93dce774 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -12,7 +12,7 @@ jobs: permissions: issues: write pull-requests: write - runs-on: self-hosted + runs-on: blacksmith-16vcpu-ubuntu-2404 steps: - uses: actions/create-github-app-token@d72941d797fd3113feb6b93fd0dec494b13a2547 # v1 id: app-token diff --git a/.github/workflows/workflow-sanity.yml b/.github/workflows/workflow-sanity.yml index 438a71162da82..19668e697ad28 100644 --- a/.github/workflows/workflow-sanity.yml +++ b/.github/workflows/workflow-sanity.yml @@ -11,7 +11,7 @@ concurrency: jobs: no-tabs: - runs-on: ubuntu-latest + runs-on: blacksmith-16vcpu-ubuntu-2404 steps: - name: Checkout uses: actions/checkout@v4 @@ -40,3 +40,28 @@ jobs: print(f"- {path}") sys.exit(1) PY + + actionlint: + runs-on: blacksmith-16vcpu-ubuntu-2404 + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install actionlint + shell: bash + run: | + set -euo pipefail + ACTIONLINT_VERSION="1.7.11" + archive="actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz" + base_url="https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}" + curl -sSfL -o "${archive}" "${base_url}/${archive}" + curl -sSfL -o checksums.txt "${base_url}/actionlint_${ACTIONLINT_VERSION}_checksums.txt" + grep " ${archive}\$" checksums.txt | sha256sum -c - + tar -xzf "${archive}" actionlint + sudo install -m 0755 actionlint /usr/local/bin/actionlint + + - name: Lint workflows + run: actionlint + + - name: Disallow direct inputs interpolation in composite run blocks + run: python3 scripts/check-composite-action-input-interpolation.py diff --git a/.gitignore b/.gitignore index 4278a24b0f6f5..69d89b2c4cd08 100644 --- a/.gitignore +++ b/.gitignore @@ -17,6 +17,11 @@ __pycache__/ ui/src/ui/__screenshots__/ ui/playwright-report/ ui/test-results/ +packages/dashboard-next/.next/ +packages/dashboard-next/out/ + +# Mise configuration files +mise.toml # Android build artifacts apps/android/.gradle/ @@ -90,6 +95,12 @@ USER.md /local/ package-lock.json .claude/settings.local.json +.agents/ +.agents +.agent/ # Local iOS signing overrides apps/ios/LocalSigning.xcconfig +# Generated protocol schema (produced via pnpm protocol:gen) +dist/protocol.schema.json +.ant-colony/ diff --git a/AGENTS.md b/AGENTS.md index 5e589d336dd68..3555ef17936ba 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -134,6 +134,7 @@ `gh pr list -R "$fork" --state open` (must be empty) - Description newline footgun: write Markdown via heredoc to `/tmp/ghsa.desc.md` (no `"\\n"` strings) - Build patch JSON via jq: `jq -n --rawfile desc /tmp/ghsa.desc.md '{summary,severity,description:$desc,vulnerabilities:[...]}' > /tmp/ghsa.patch.json` +- GHSA API footgun: cannot set `severity` and `cvss_vector_string` in the same PATCH; do separate calls. - Patch + publish: `gh api -X PATCH /repos/openclaw/openclaw/security-advisories/ --input /tmp/ghsa.patch.json` (publish = include `"state":"published"`; no `/publish` endpoint) - If publish fails (HTTP 422): missing `severity`/`description`/`vulnerabilities[]`, or private fork has open PRs - Verify: re-fetch; ensure `state=published`, `published_at` set; `jq -r .description | rg '\\\\n'` returns nothing diff --git a/CHANGELOG.md b/CHANGELOG.md index b298786540945..7c5065b23508e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,27 +2,322 @@ Docs: https://docs.openclaw.ai -## 2026.2.18 (Unreleased) +## 2026.2.22 (Unreleased) ### Changes +- Channels/Config: unify channel preview streaming config handling with a shared resolver and canonical migration path. +- Discord/Allowlist: canonicalize resolved Discord allowlist names to IDs and split resolution flow for clearer fail-closed behavior. +- Memory/FTS: add Korean stop-word filtering and particle-aware keyword extraction (including mixed Korean/English stems) for query expansion in FTS-only search mode. (#18899) Thanks @ruypang. +- iOS/Talk: prefetch TTS segments and suppress expected speech-cancellation errors for smoother talk playback. (#22833) Thanks @ngutman. + +### Breaking + +- **BREAKING:** remove legacy Gateway device-auth signature `v1`. Device-auth clients must now sign `v2` payloads with the per-connection `connect.challenge` nonce and send `device.nonce`; nonce-less connects are rejected. +- **BREAKING:** unify channel preview-streaming config to `channels..streaming` with enum values `off | partial | block | progress`, and move Slack native stream toggle to `channels.slack.nativeStreaming`. Legacy keys (`streamMode`, Slack boolean `streaming`) are still read and migrated by `openclaw doctor --fix`, but canonical saved config/docs now use the unified names. +- **BREAKING:** CLI local onboarding now sets `session.dmScope` to `per-channel-peer` by default for new/implicit DM scope configuration. If you depend on shared DM continuity across senders, explicitly set `session.dmScope` to `main`. (#23468) Thanks @bmendonca3. + +### Fixes + +- Channels/Security: fail closed on missing provider group policy config by defaulting runtime group policy to `allowlist` (instead of inheriting `channels.defaults.groupPolicy`) when `channels.` is absent across message channels, and align runtime + security warnings/docs to the same fallback behavior (Slack, Discord, iMessage, Telegram, WhatsApp, Signal, LINE, Matrix, Mattermost, Google Chat, IRC, Nextcloud Talk, Feishu, and Zalo user flows; plus Discord message/native-command paths). (#23367) Thanks @bmendonca3. +- Gateway/Onboarding: harden remote gateway onboarding defaults and guidance by defaulting discovered direct URLs to `wss://`, rejecting insecure non-loopback `ws://` targets in onboarding validation, and expanding remote-security remediation messaging across gateway client/call/doctor flows. (#23476) Thanks @bmendonca3. +- CLI/Sessions: pass the configured sessions directory when resolving transcript paths in `agentCommand`, so custom `session.store` locations resume sessions reliably. Thanks @davidrudduck. +- Gateway/Chat UI: strip inline reply/audio directive tags from non-streaming final webchat broadcasts (including `chat.inject`) while preserving empty-string message content when tags are the entire reply. (#23298) Thanks @SidQin-cyber. +- Gateway/Restart: fix restart-loop edge cases by keeping `openclaw.mjs -> dist/entry.js` bootstrap detection explicit, reacquiring the gateway lock for in-process restart fallback paths, and tightening restart-loop regression coverage. (#23416) Thanks @jeffwnli. +- Signal/Monitor: treat user-initiated abort shutdowns as clean exits when auto-started `signal-cli` is terminated, while still surfacing unexpected daemon exits as startup/runtime failures. (#23379) Thanks @frankekn. +- Channels/Dedupe: centralize plugin dedupe primitives in plugin SDK (memory + persistent), move Feishu inbound dedupe to a namespace-scoped persistent store, and reuse shared dedupe cache logic for Zalo webhook replay + Tlon processed-message tracking to reduce duplicate handling during reconnect/replay paths. (#23377) Thanks @SidQin-cyber. +- Channels/Delivery: remove hardcoded WhatsApp delivery fallbacks; require explicit/session channel context or auto-pick the sole configured channel when unambiguous. (#23357) Thanks @lbo728. +- ACP/Gateway: wait for gateway hello before opening ACP requests, and fail fast on pre-hello connect failures to avoid startup hangs and early `gateway not connected` request races. (#23390) Thanks @janckerchen. +- Security/Audit: add `openclaw security audit` detection for open group policies that expose runtime/filesystem tools without sandbox/workspace guards (`security.exposure.open_groups_with_runtime_or_fs`). +- Security/Audit: make `gateway.real_ip_fallback_enabled` severity conditional for loopback trusted-proxy setups (warn for loopback-only `trustedProxies`, critical when non-loopback proxies are trusted). (#23428) Thanks @bmendonca3. +- Security/Exec env: block request-scoped `HOME` and `ZDOTDIR` overrides in host exec env sanitizers (Node + macOS), preventing shell startup-file execution before allowlist-evaluated command bodies. This ships in the next npm release. Thanks @tdjackey for reporting. +- Security/Exec env: block `SHELLOPTS`/`PS4` in host exec env sanitizers and restrict shell-wrapper (`bash|sh|zsh ... -c/-lc`) request env overrides to a small explicit allowlist (`TERM`, `LANG`, `LC_*`, `COLORTERM`, `NO_COLOR`, `FORCE_COLOR`) on both node host and macOS companion paths, preventing xtrace prompt command-substitution allowlist bypasses. This ships in the next npm release. Thanks @tdjackey for reporting. +- Security/Gateway: emit a startup security warning when insecure/dangerous config flags are enabled (including `gateway.controlUi.dangerouslyDisableDeviceAuth=true`) and point operators to `openclaw security audit`. +- Security/Hooks auth: normalize hook auth rate-limit client IP keys so IPv4 and IPv4-mapped IPv6 addresses share one throttle bucket, preventing dual-form auth-attempt budget bypasses. This ships in the next npm release. Thanks @aether-ai-agent for reporting. +- Security/Exec approvals: treat `env` and shell-dispatch wrappers as transparent during allowlist analysis on node-host and macOS companion paths so policy checks match the effective executable/inline shell payload instead of the wrapper binary, blocking wrapper-smuggled allowlist bypasses. This ships in the next npm release. Thanks @tdjackey for reporting. +- Security/Exec approvals: require explicit safe-bin profiles for `tools.exec.safeBins` entries in allowlist mode (remove generic safe-bin profile fallback), and add `tools.exec.safeBinProfiles` for safe custom binaries so unprofiled interpreter-style entries cannot be treated as stdin-safe. This ships in the next npm release. Thanks @tdjackey for reporting. +- Security/Channels: harden Slack external menu token handling by switching to CSPRNG tokens, validating token shape, requiring user identity for external option lookups, and avoiding fabricated timestamp `trigger_id` fallbacks; also switch Tlon Urbit channel IDs to CSPRNG UUIDs, centralize secure ID/token generation via shared infra helpers, and add a guardrail test to block new runtime `Date.now()+Math.random()` token/id patterns. +- Security/Hooks transforms: enforce symlink-safe containment for webhook transform module paths (including `hooks.transformsDir` and `hooks.mappings[].transform.module`) by resolving existing-path ancestors via realpath before import, while preserving in-root symlink support; add regression coverage for both escape and allow cases. This ships in the next npm release. Thanks @aether-ai-agent for reporting. +- Telegram/WSL2: disable `autoSelectFamily` by default on WSL2 and memoize WSL2 detection in Telegram network decision logic to avoid repeated sync `/proc/version` probes on fetch/send paths. (#21916) Thanks @MizukiMachine. +- Telegram/Streaming: preserve archived draft preview mapping after flush and clean superseded reasoning preview bubbles so multi-message preview finals no longer cross-edit or orphan stale messages under send/rotation races. (#23202) Thanks @obviyus. +- Telegram/Polling: persist a safe update-offset watermark bounded by pending updates so crash/restart cannot skip queued lower `update_id` updates after out-of-order completion. (#23284) thanks @frankekn. +- Slack/Slash commands: preserve the Bolt app receiver when registering external select options handlers so monitor startup does not crash on runtimes that require bound `app.options` calls. (#23209) Thanks @0xgaia. +- Slack/Telegram slash sessions: await session metadata persistence before dispatch so first-turn native slash runs do not race session-origin metadata updates. (#23065) thanks @hydro13. +- Agents/Ollama: preserve unsafe integer tool-call arguments as exact strings during NDJSON parsing, preventing large numeric IDs from being rounded before tool execution. (#23170) Thanks @BestJoester. +- Cron/Gateway: keep `cron.list` and `cron.status` responsive during startup catch-up by avoiding a long-held cron lock while missed jobs execute. (#23106) Thanks @jayleekr. +- Gateway/Config reload: compare array-valued config paths structurally during diffing so unchanged `memory.qmd.paths` and `memory.qmd.scope.rules` no longer trigger false restart-required reloads. (#23185) Thanks @rex05ai. +- Cron/Scheduling: validate runtime cron expressions before schedule/stagger evaluation so malformed persisted jobs report a clear `invalid cron schedule: expr is required` error instead of crashing with `undefined.trim` failures and auto-disable churn. (#23223) Thanks @asimons81. +- Memory/QMD: migrate legacy unscoped collection bindings (for example `memory-root`) to per-agent scoped names (for example `memory-root-main`) during startup when safe, so QMD-backed `memory_search` no longer fails with `Collection not found` after upgrades. (#23228, #20727) Thanks @JLDynamics and @AaronFaby. +- Memory/QMD: normalize Han-script BM25 search queries before invoking `qmd search` so mixed CJK+Latin prompts no longer return empty results due to tokenizer mismatch. (#23426) Thanks @LunaLee0130. +- TUI/Input: enable multiline-paste burst coalescing on macOS Terminal.app and iTerm so pasted blocks no longer submit line-by-line as separate messages. (#18809) Thanks @fwends. +- TUI/RTL: isolate right-to-left script lines (Arabic/Hebrew ranges) with Unicode bidi isolation marks in TUI text sanitization so RTL assistant output no longer renders in reversed visual order in terminal chat panes. (#21936) Thanks @Asm3r96. +- TUI/Status: request immediate renders after setting `sending`/`waiting` activity states so in-flight runs always show visible progress indicators instead of appearing idle until completion. (#21549) Thanks @13Guinness. +- TUI/Input: arm Ctrl+C exit timing when clearing non-empty composer text and add a SIGINT fallback path so double Ctrl+C exits remain responsive during active runs instead of requiring an extra press or appearing stuck. (#23407) Thanks @tinybluedev. +- Agents/Fallbacks: treat JSON payloads with `type: "api_error"` + `"Internal server error"` as transient failover errors so Anthropic 500-style failures trigger model fallback. (#23193) Thanks @jarvis-lane. +- Agents/Google: sanitize non-base64 `thought_signature`/`thoughtSignature` values from assistant replay transcripts for native Google Gemini requests while preserving valid signatures and tool-call order. (#23457) Thanks @echoVic. +- Agents/Transcripts: validate assistant tool-call names (syntax/length + registered tool allowlist) before transcript persistence and during replay sanitization so malformed failover tool names no longer poison sessions with repeated provider HTTP 400 errors. (#23324) Thanks @johnsantry. +- Agents/Compaction: strip stale assistant usage snapshots from pre-compaction turns when replaying history after a compaction summary so context-token estimation no longer reuses pre-compaction totals and immediately re-triggers destructive follow-up compactions. (#19127) Thanks @tedwatson. +- Agents/Replies: emit a default completion acknowledgement (`✅ Done.`) when runs execute tools successfully but return no final assistant text, preventing silent no-reply turns after tool-only completions. (#22834) Thanks @Oldshue. +- Agents/Subagents: honor `tools.subagents.tools.alsoAllow` and explicit subagent `allow` entries when resolving built-in subagent deny defaults, so explicitly granted tools (for example `sessions_send`) are no longer blocked unless re-denied in `tools.subagents.tools.deny`. (#23359) Thanks @goren-beehero. +- Agents/Diagnostics: include resolved lifecycle error text in `embedded run agent end` warnings so UI/TUI “Connection error” runs expose actionable provider failure reasons in gateway logs. (#23054) Thanks @Raize. +- Plugins/Hooks: run legacy `before_agent_start` once per agent turn and reuse that result across model-resolve and prompt-build compatibility paths, preventing duplicate hook side effects (for example duplicate external API calls). (#23289) Thanks @ksato8710. +- Models/Config: default missing Anthropic provider/model `api` fields to `anthropic-messages` during config validation so custom relay model entries are preserved instead of being dropped by runtime model registry validation. (#23332) Thanks @bigbigmonkey123. +- Gateway/Pairing: treat operator.admin pairing tokens as satisfying operator.write requests so legacy devices stop looping through scope-upgrade prompts introduced in 2026.2.19. (#23125, #23006) Thanks @vignesh07. +- Gateway/Pairing: treat `operator.admin` as satisfying other `operator.*` scope checks during device-auth verification so local CLI/TUI sessions stop entering pairing-required loops for pairing/approval-scoped commands. (#22062, #22193, #21191) Thanks @Botaccess, @jhartshorn, and @ctbritt. +- Gateway/Pairing: preserve existing approved token scopes when processing repair pairings that omit `scopes`, preventing empty-scope token regressions on reconnecting clients. (#21906) Thanks @paki81. +- Gateway/Scopes: include `operator.read` and `operator.write` in default operator connect scope bundles across CLI, Control UI, and macOS clients so write-scoped announce/sub-agent follow-up calls no longer hit `pairing required` disconnects on loopback gateways. (#22582) thanks @YuzuruS. +- Plugins/CLI: make `openclaw plugins enable` and plugin install/link flows update allowlists via shared plugin-enable policy so enabled plugins are not left disabled by allowlist mismatch. (#23190) Thanks @downwind7clawd-ctrl. +- Memory/QMD: add optional `memory.qmd.mcporter` search routing so QMD `query/search/vsearch` can run through mcporter keep-alive flows (including multi-collection paths) to reduce cold starts, while keeping searches on agent-scoped QMD state for consistent recall. (#19617) Thanks @nicole-luxe and @vignesh07. +- Chat/UI: strip inline reply/audio directive tags (`[[reply_to_current]]`, `[[reply_to:]]`, `[[audio_as_voice]]`) from displayed chat history, live chat event output, and session preview snippets so control tags no longer leak into user-visible surfaces. +- Telegram/Retry: classify undici `TypeError: fetch failed` as recoverable in both polling and send retry paths so transient fetch failures no longer fail fast. (#16699) thanks @Glucksberg. +- BlueBubbles/DM history: restore DM backfill context with account-scoped rolling history, bounded backfill retries, and safer history payload limits. (#20302) Thanks @Ryan-Haines. +- BlueBubbles/Private API cache: treat unknown (`null`) private-API cache status as disabled for send/attachment/reply flows to avoid stale-cache 500s, and log a warning when reply/effect features are requested while capability is unknown. (#23459) Thanks @echoVic. +- BlueBubbles/Webhooks: accept inbound/reaction webhook payloads when BlueBubbles omits `handle` but provides DM `chatGuid`, and harden payload extraction for array/string-wrapped message bodies so valid webhook events no longer get rejected as unparseable. (#23275) Thanks @toph31. +- Security/Audit: add `openclaw security audit` finding `gateway.nodes.allow_commands_dangerous` for risky `gateway.nodes.allowCommands` overrides, with severity upgraded to critical on remote gateway exposure. +- Gateway/Control plane: reduce cross-client write limiter contention by adding `connId` fallback keying when device ID and client IP are both unavailable. +- Security/Config: block prototype-key traversal during config merge patch and legacy migration merge helpers (`__proto__`, `constructor`, `prototype`) to prevent prototype pollution during config mutation flows. (#22968) Thanks @Clawborn. +- Security/Shell env: validate login-shell executable paths for shell-env fallback (`/etc/shells` + trusted prefixes) and block `SHELL` in dangerous env override policy paths so untrusted shell-path injection falls back safely to `/bin/sh`. Thanks @athuljayaram for reporting. +- Security/Config: make parsed chat allowlist checks fail closed when `allowFrom` is empty, restoring expected DM/pairing gating. +- Security/Exec: in non-default setups that manually add `sort` to `tools.exec.safeBins`, block `sort --compress-program` so allowlist-mode safe-bin checks cannot bypass approval. Thanks @tdjackey for reporting. +- Security/Exec approvals: when users choose `allow-always` for shell-wrapper commands (for example `/bin/zsh -lc ...`), persist allowlist patterns for the inner executable(s) instead of the wrapper shell binary, preventing accidental broad shell allowlisting in moderate mode. (#23276) Thanks @xrom2863. +- Security/Exec: fail closed when `tools.exec.host=sandbox` is configured/requested but sandbox runtime is unavailable, and default implicit exec host routing to `gateway` when no sandbox runtime exists. (#23398) Thanks @bmendonca3. +- Security/macOS app beta: enforce path-only `system.run` allowlist matching (drop basename matches like `echo`), migrate legacy basename entries to last resolved paths when available, and harden shell-chain handling to fail closed on unsafe parse/control syntax (including quoted command substitution/backticks). This is an optional allowlist-mode feature; default installs remain deny-by-default. This ships in the next npm release. Thanks @tdjackey for reporting. +- Security/Agents: auto-generate and persist a dedicated `commands.ownerDisplaySecret` when `commands.ownerDisplay=hash`, remove gateway token fallback from owner-ID prompt hashing across CLI and embedded agent runners, and centralize owner-display secret resolution in one shared helper. This ships in the next npm release. Thanks @aether-ai-agent for reporting. +- Security/SSRF: expand IPv4 fetch guard blocking to include RFC special-use/non-global ranges (including benchmarking, TEST-NET, multicast, and reserved/broadcast blocks), and centralize range checks into a single CIDR policy table to reduce classifier drift. +- Security/Archive: block zip symlink escapes during archive extraction. +- Security/Media sandbox: keep tmp media allowance for absolute tmp paths only and enforce symlink-escape checks before sandbox-validated reads, preventing tmp symlink exfiltration and relative `../` sandbox escapes when sandboxes live under tmp. (#17892) Thanks @dashed. +- Browser/Upload: accept canonical in-root upload paths when the configured uploads directory is a symlink alias (for example `/tmp` -> `/private/tmp` on macOS), so browser upload validation no longer rejects valid files during client->server revalidation. (#23300, #23222, #22848) Thanks @bgaither4, @parkerati, and @Nabsku. +- Security/Discord: add `openclaw security audit` warnings for name/tag-based Discord allowlist entries (DM allowlists, guild/channel `users`, and pairing-store entries), highlighting slug-collision risk while keeping name-based matching supported, and canonicalize resolved Discord allowlist names to IDs at runtime without rewriting config files. Thanks @tdjackey for reporting. +- Security/Gateway: block node-role connections when device identity metadata is missing. +- Security/Media: enforce inbound media byte limits during download/read across Discord, Telegram, Zalo, Microsoft Teams, and BlueBubbles to prevent oversized payload memory spikes before rejection. This ships in the next npm release. Thanks @tdjackey for reporting. +- Media/Understanding: preserve `application/pdf` MIME classification during text-like file heuristics so PDF uploads use PDF extraction paths instead of being inlined as raw text. (#23191) Thanks @claudeplay2026-byte. +- Security/Control UI: block symlink-based out-of-root static file reads by enforcing realpath containment and file-identity checks when serving Control UI assets and SPA fallback `index.html`. This ships in the next npm release. Thanks @tdjackey for reporting. +- Security/Gateway avatars: block symlink traversal during local avatar `data:` URL resolution by enforcing realpath containment and file-identity checks before reads. This ships in the next npm release. Thanks @aether-ai-agent for reporting. +- Security/Control UI: centralize avatar URL/path validation across gateway/config helpers and enforce a 2 MB max size for local agent avatar files before `/avatar` resolution, reducing oversized-avatar memory risk without changing supported avatar formats. +- Security/MSTeams media: enforce allowlist checks for SharePoint reference attachment URLs and redirect targets during Graph-backed media fetches so redirect chains cannot escape configured media host boundaries. This ships in the next npm release. Thanks @tdjackey for reporting. +- Security/macOS discovery: fail closed for unresolved discovery endpoints by clearing stale remote selection values, use resolved service host only for SSH target derivation, and keep remote URL config aligned with resolved endpoint availability. (#21618) Thanks @bmendonca3. +- Chat/Usage/TUI: strip synthetic inbound metadata blocks (including `Conversation info` and trailing `Untrusted context` channel metadata wrappers) from displayed conversation history so internal prompt context no longer leaks into user-visible logs. +- CI/Tests: fix TypeScript case-table typing and lint assertion regressions so `pnpm check` passes again after Synology Chat landing. (#23012) Thanks @druide67. +- Security/Browser relay: harden extension relay auth token handling for `/extension` and `/cdp` pathways. +- Cron: persist `delivered` state in cron job records so delivery failures remain visible in status and logs. (#19174) Thanks @simonemacario. +- Config/Doctor: only repair the OAuth credentials directory when affected channels are configured, avoiding fresh-install noise. +- Config/Channels: whitelist `channels.modelByChannel` in config validation and exclude it from plugin auto-enable channel detection so model overrides no longer trigger `unknown channel id` validation errors or bogus `modelByChannel` plugin enables. (#23412) Thanks @ProspectOre. +- Config/Bindings: allow optional `bindings[].comment` in strict config validation so annotated binding entries no longer fail load. (#23458) Thanks @echoVic. +- Usage/Pricing: correct MiniMax M2.5 pricing defaults to fix inflated cost reporting. (#22755) Thanks @miloudbelarebia. +- Gateway/Daemon: verify gateway health after daemon restart. +- Agents/UI text: stop rewriting normal assistant billing/payment language outside explicit error contexts. (#17834) Thanks @niceysam. + +## 2026.2.21 + +### Changes + +- Models/Google: add Gemini 3.1 support (`google/gemini-3.1-pro-preview`). +- Providers/Onboarding: add Volcano Engine (Doubao) and BytePlus providers/models (including coding variants), wire onboarding auth choices for interactive + non-interactive flows, and align docs to `volcengine-api-key`. (#7967) Thanks @funmore123. +- Channels/CLI: add per-account/channel `defaultTo` outbound routing fallback so `openclaw agent --deliver` can send without explicit `--reply-to` when a default target is configured. (#16985) Thanks @KirillShchetinin. +- Channels: allow per-channel model overrides via `channels.modelByChannel` and note them in /status. Thanks @thewilloftheshadow. +- Telegram/Streaming: simplify preview streaming config to `channels.telegram.streaming` (boolean), auto-map legacy `streamMode` values, and remove block-vs-partial preview branching. (#22012) thanks @obviyus. +- Discord/Streaming: add stream preview mode for live draft replies with partial/block options and configurable chunking. Thanks @thewilloftheshadow. Inspiration @neoagentic-ship-it. +- Discord/Telegram: add configurable lifecycle status reactions for queued/thinking/tool/done/error phases with a shared controller and emoji/timing overrides. Thanks @wolly-tundracube and @thewilloftheshadow. +- Discord/Voice: add voice channel join/leave/status via `/vc`, plus auto-join configuration for realtime voice conversations. Thanks @thewilloftheshadow. +- Discord: add configurable ephemeral defaults for slash-command responses. (#16563) Thanks @wei. +- Discord: support updating forum `available_tags` via channel edit actions for forum tag management. (#12070) Thanks @xiaoyaner0201. +- Discord: include channel topics in trusted inbound metadata on new sessions. Thanks @thewilloftheshadow. +- Discord/Subagents: add thread-bound subagent sessions on Discord with per-thread focus/list controls and thread-bound continuation routing for spawned helper agents. (#21805) Thanks @onutc. +- iOS/Chat: clean chat UI noise by stripping inbound untrusted metadata/timestamp prefixes, formatting tool outputs into concise summaries/errors, compacting the composer while typing, and supporting tap-to-dismiss keyboard in chat view. (#22122) thanks @mbelinky. +- iOS/Watch: bridge mirrored watch prompt notification actions into iOS quick-reply handling, including queued action handoff until app model initialization. (#22123) thanks @mbelinky. +- iOS/Gateway: stabilize background wake and reconnect behavior with background reconnect suppression/lease windows, BGAppRefresh wake fallback, location wake hook throttling, and APNs wake retry+nudge instrumentation. (#21226) thanks @mbelinky. +- Auto-reply/UI: add model fallback lifecycle visibility in verbose logs, /status active-model context with fallback reason, and cohesive WebUI fallback indicators. (#20704) Thanks @joshavant. +- MSTeams: dedupe sent-message cache storage by removing duplicate per-message Set storage and using timestamps Map keys as the single membership source. (#22514) Thanks @TaKO8Ki. +- Agents/Subagents: default subagent spawn depth now uses shared `maxSpawnDepth=2`, enabling depth-1 orchestrator spawning by default while keeping depth policy checks consistent across spawn and prompt paths. (#22223) Thanks @tyler6204. +- Security/Agents: make owner-ID obfuscation use a dedicated HMAC secret from configuration (`ownerDisplaySecret`) and update hashing behavior so obfuscation is decoupled from gateway token handling for improved control. (#7343) Thanks @vincentkoc. +- Security/Infra: switch gateway lock and tool-call synthetic IDs from SHA-1 to SHA-256 with unchanged truncation length to strengthen hash basis while keeping deterministic behavior and lock key format. (#7343) Thanks @vincentkoc. +- Dependencies/Tooling: add non-blocking dead-code scans in CI via Knip/ts-prune/ts-unused-exports to surface unused dependencies and exports earlier. (#22468) Thanks @vincentkoc. +- Dependencies/Unused Dependencies: remove or scope unused root and extension deps (`@larksuiteoapi/node-sdk`, `signal-utils`, `ollama`, `lit`, `@lit/context`, `@lit-labs/signals`, `@microsoft/agents-hosting-express`, `@microsoft/agents-hosting-extensions-teams`, and plugin-local `openclaw` devDeps in `extensions/open-prose`, `extensions/lobster`, and `extensions/llm-task`). (#22471, #22495) Thanks @vincentkoc. +- Dependencies/A2UI: harden dependency resolution after root cleanup (resolve `lit`, `@lit/context`, `@lit-labs/signals`, and `signal-utils` from workspace/root) and simplify bundling fallback behavior, including `pnpm dlx rolldown` compatibility. (#22481, #22507) Thanks @vincentkoc. + +### Fixes + +- Security/Agents: cap embedded Pi runner outer retry loop with a higher profile-aware dynamic limit (32-160 attempts) and return an explicit `retry_limit` error payload when retries never converge, preventing unbounded internal retry cycles (`GHSA-76m6-pj3w-v7mf`). +- Telegram: detect duplicate bot-token ownership across Telegram accounts at startup/status time, mark secondary accounts as not configured with an explicit fix message, and block duplicate account startup before polling to avoid endless `getUpdates` conflict loops. +- Agents/Tool images: include source filenames in `agents/tool-images` resize logs so compression events can be traced back to specific files. +- Providers/OAuth: harden Qwen and Chutes refresh handling by validating refresh response expiry values and preserving prior refresh tokens when providers return empty refresh token fields, with regression coverage for empty-token responses. +- Models/Kimi-Coding: add missing implicit provider template for `kimi-coding` with correct `anthropic-messages` API type and base URL, fixing 403 errors when using Kimi for Coding. (#22409) +- Auto-reply/Tools: forward `senderIsOwner` through embedded queued/followup runner params so owner-only tools remain available for authorized senders. (#22296) thanks @hcoj. +- Discord: restore model picker back navigation when a provider is missing and document the Discord picker flow. (#21458) Thanks @pejmanjohn and @thewilloftheshadow. +- Memory/QMD: respect per-agent `memorySearch.enabled=false` during gateway QMD startup initialization, split multi-collection QMD searches into per-collection queries (`search`/`vsearch`/`query`) to avoid sparse-term drops, prefer collection-hinted doc resolution to avoid stale-hash collisions, retry boot updates on transient lock/timeout failures, skip `qmd embed` in BM25-only `search` mode (including `memory index --force`), and serialize embed runs globally with failure backoff to prevent CPU storms on multi-agent hosts. (#20581, #21590, #20513, #20001, #21266, #21583, #20346, #19493) Thanks @danielrevivo, @zanderkrause, @sunyan034-cmd, @tilleulenspiegel, @dae-oss, @adamlongcreativellc, @jonathanadams96, and @kiliansitel. +- Memory/Builtin: prevent automatic sync races with manager shutdown by skipping post-close sync starts and waiting for in-flight sync before closing SQLite, so `onSearch`/`onSessionStart` no longer fail with `database is not open` in ephemeral CLI flows. (#20556, #7464) Thanks @FuzzyTG and @henrybottter. +- Providers/Copilot: drop persisted assistant `thinking` blocks for Claude models (while preserving turn structure/tool blocks) so follow-up requests no longer fail on invalid `thinkingSignature` payloads. (#19459) Thanks @jackheuberger. +- Providers/Copilot: add `claude-sonnet-4.6` and `claude-sonnet-4.5` to the default GitHub Copilot model catalog and add coverage for model-list/definition helpers. (#20270, fixes #20091) Thanks @Clawborn. +- Auto-reply/WebChat: avoid defaulting inbound runtime channel labels to unrelated providers (for example `whatsapp`) for webchat sessions so channel-specific formatting guidance stays accurate. (#21534) Thanks @lbo728. +- Status: include persisted `cacheRead`/`cacheWrite` in session summaries so compact `/status` output consistently shows cache hit percentages from real session data. +- Sessions/Usage: persist `totalTokens` from `promptTokens` snapshots even when providers omit structured usage payloads, so session history/status no longer regress to `unknown` token utilization for otherwise successful runs. (#21819) Thanks @zymclaw. +- Heartbeat/Cron: restore interval heartbeat behavior so missing `HEARTBEAT.md` no longer suppresses runs (only effectively empty files skip), preserving prompt-driven and tagged-cron execution paths. +- WhatsApp/Cron/Heartbeat: enforce allowlisted routing for implicit scheduled/system delivery by merging pairing-store + configured `allowFrom` recipients, selecting authorized recipients when last-route context points to a non-allowlisted chat, and preventing heartbeat fan-out to recent unauthorized chats. +- Heartbeat/Active hours: constrain active-hours `24` sentinel parsing to `24:00` in time validation so invalid values like `24:30` are rejected early. (#21410) thanks @adhitShet. +- Heartbeat: treat `activeHours` windows with identical `start`/`end` times as zero-width (always outside the window) instead of always-active. (#21408) thanks @adhitShet. +- CLI/Pairing: default `pairing list` and `pairing approve` to the sole available pairing channel when omitted, so TUI-only setups can recover from `pairing required` without guessing channel arguments. (#21527) Thanks @losts1. +- TUI/Pairing: show explicit pairing-required recovery guidance after gateway disconnects that return `pairing required`, including approval steps to unblock quickstart TUI hatching on fresh installs. (#21841) Thanks @nicolinux. +- TUI/Input: suppress duplicate backspace events arriving in the same input burst window so SSH sessions no longer delete two characters per backspace press in the composer. (#19318) Thanks @eheimer. +- TUI/Models: scope `models.list` to the configured model allowlist (`agents.defaults.models`) so `/model` picker no longer floods with unrelated catalog entries by default. (#18816) Thanks @fwends. +- TUI/Heartbeat: suppress heartbeat ACK/prompt noise in chat streaming when `showOk` is disabled, while still preserving non-ACK heartbeat alerts in final output. (#20228) Thanks @bhalliburton. +- TUI/History: cap chat-log component growth and prune stale render nodes/references so large default history loads no longer overflow render recursion with `RangeError: Maximum call stack size exceeded`. (#18068) Thanks @JaniJegoroff. +- Memory/QMD: diversify mixed-source search ranking when both session and memory collections are present so session transcript hits no longer crowd out durable memory-file matches in top results. (#19913) Thanks @alextempr. +- Memory/Tools: return explicit `unavailable` warnings/actions from `memory_search` when embedding/provider failures occur (including quota exhaustion), so disabled memory does not look like an empty recall result. (#21894) Thanks @XBS9. +- Session/Startup: require the `/new` and `/reset` greeting path to run Session Startup file-reading instructions before responding, so daily memory startup context is not skipped on fresh-session greetings. (#22338) Thanks @armstrong-pv. +- Auth/Onboarding: align OAuth profile-id config mapping with stored credential IDs for OpenAI Codex and Chutes flows, preventing `provider:default` mismatches when OAuth returns email-scoped credentials. (#12692) thanks @mudrii. +- Provider/HTTP: treat HTTP 503 as failover-eligible for LLM provider errors. (#21086) Thanks @Protocol-zero-0. +- Slack: pass `recipient_team_id` / `recipient_user_id` through Slack native streaming calls so `chat.startStream`/`appendStream`/`stopStream` work reliably across DMs and Slack Connect setups, and disable block streaming when native streaming is active. (#20988) Thanks @Dithilli. Earlier recipient-ID groundwork was contributed in #20377 by @AsserAl1012. +- CLI/Config: add canonical `--strict-json` parsing for `config set` and keep `--json` as a legacy alias to reduce help/behavior drift. (#21332) thanks @adhitShet. +- CLI/Config: preserve explicitly unset config paths in persisted JSON after writes so `openclaw config unset ` no longer re-introduces defaulted keys (for example `commands.ownerDisplay`) through schema normalization. (#22984) Thanks @aronchick. +- CLI: keep `openclaw -v` as a root-only version alias so subcommand `-v, --verbose` flags (for example ACP/hooks/skills) are no longer intercepted globally. (#21303) thanks @adhitShet. +- Memory: return empty snippets when `memory_get`/QMD read files that have not been created yet, and harden memory indexing/session helpers against ENOENT races so missing Markdown no longer crashes tools. (#20680) Thanks @pahdo. +- Telegram/Streaming: always clean up draft previews even when dispatch throws before fallback handling, preventing orphaned preview messages during failed runs. (#19041) thanks @mudrii. +- Telegram/Streaming: split reasoning and answer draft preview lanes to prevent cross-lane overwrites, and ignore literal `` tags inside inline/fenced code snippets so sample markup is not misrouted as reasoning. (#20774) Thanks @obviyus. +- Telegram/Streaming: restore 30-char first-preview debounce and scope `NO_REPLY` prefix suppression to partial sentinel fragments so normal `No...` text is not filtered. (#22613) thanks @obviyus. +- Telegram/Status reactions: refresh stall timers on repeated phase updates and honor ack-reaction scope when lifecycle reactions are enabled, preventing false stall emojis and unwanted group reactions. Thanks @wolly-tundracube and @thewilloftheshadow. +- Telegram/Status reactions: keep lifecycle reactions active when available-reactions lookup fails by falling back to unrestricted variant selection instead of suppressing reaction updates. (#22380) thanks @obviyus. +- Discord/Events: await `DiscordMessageListener` message handlers so regular `MESSAGE_CREATE` traffic is processed through queue ordering/timeout flow instead of fire-and-forget drops. (#22396) Thanks @sIlENtbuffER. +- Discord/Streaming: apply `replyToMode: first` only to the first Discord chunk so block-streamed replies do not spam mention pings. (#20726) Thanks @thewilloftheshadow for the report. +- Discord/Components: map DM channel targets back to user-scoped component sessions so button/select interactions stay in the main DM session. Thanks @thewilloftheshadow. +- Discord/Allowlist: lazy-load guild lists when resolving Discord user allowlists so ID-only entries resolve even if guild fetch fails. (#20208) Thanks @zhangjunmengyang. +- Discord/Gateway: handle close code 4014 (missing privileged gateway intents) without crashing the gateway. Thanks @thewilloftheshadow. +- Discord: ingest inbound stickers as media so sticker-only messages and forwarded stickers are visible to agents. Thanks @thewilloftheshadow. +- Auto-reply/Runner: emit `onAgentRunStart` only after agent lifecycle or tool activity begins (and only once per run), so fallback preflight errors no longer mark runs as started. (#21165) Thanks @shakkernerd. +- Auto-reply/Tool results: serialize tool-result delivery and keep the delivery chain progressing after individual failures so concurrent tool outputs preserve user-visible ordering. (#21231) thanks @ahdernasr. +- Auto-reply/Prompt caching: restore prefix-cache stability by keeping inbound system metadata session-stable and moving per-message IDs (`message_id`, `message_id_full`, `reply_to_id`, `sender_id`) into untrusted conversation context. (#20597) Thanks @anisoptera. +- iOS/Watch: add actionable watch approval/reject controls and quick-reply actions so watch-originated approvals and responses can be sent directly from notification flows. (#21996) Thanks @mbelinky. +- iOS/Watch: refresh iOS and watch app icon assets with the lobster icon set to keep phone/watch branding aligned. (#21997) Thanks @mbelinky. +- CLI/Onboarding: fix Anthropic-compatible custom provider verification by normalizing base URLs to avoid duplicate `/v1` paths during setup checks. (#21336) Thanks @17jmumford. +- iOS/Gateway/Tools: prefer uniquely connected node matches when duplicate display names exist, surface actionable `nodes invoke` pairing-required guidance with request IDs, and refresh active iOS gateway registration after location-capability setting changes so capability updates apply immediately. (#22120) thanks @mbelinky. +- Gateway/Auth: require `gateway.trustedProxies` to include a loopback proxy address when `auth.mode="trusted-proxy"` and `bind="loopback"`, preventing same-host proxy misconfiguration from silently blocking auth. (#22082, follow-up to #20097) thanks @mbelinky. +- Gateway/Auth: allow trusted-proxy mode with loopback bind for same-host reverse-proxy deployments, while still requiring configured `gateway.trustedProxies`. (#20097) thanks @xinhuagu. +- Gateway/Auth: allow authenticated clients across roles/scopes to call `health` while preserving role and scope enforcement for non-health methods. (#19699) thanks @Nachx639. +- Gateway/Hooks: include transform export name in hook-transform cache keys so distinct exports from the same module do not reuse the wrong cached transform function. (#13855) thanks @mcaxtr. +- Gateway/Control UI: return 404 for missing static-asset paths instead of serving SPA fallback HTML, while preserving client-route fallback behavior for extensionless and non-asset dotted paths. (#12060) thanks @mcaxtr. +- Gateway/Pairing: prevent device-token rotate scope escalation by enforcing an approved-scope baseline, preserving approved scopes across metadata updates, and rejecting rotate requests that exceed approved role scope implications. (#20703) thanks @coygeek. +- Gateway/Pairing: clear persisted paired-device state when the gateway client closes with `device token mismatch` (`1008`) so reconnect flows can cleanly re-enter pairing. (#22071) Thanks @mbelinky. +- Gateway/Config: allow `gateway.customBindHost` in strict config validation when `gateway.bind="custom"` so valid custom bind-host configurations no longer fail startup. (#20318, fixes #20289) Thanks @MisterGuy420. +- Gateway/Pairing: tolerate legacy paired devices missing `roles`/`scopes` metadata in websocket upgrade checks and backfill metadata on reconnect. (#21447, fixes #21236) Thanks @joshavant. +- Gateway/Pairing/CLI: align read-scope compatibility in pairing/device-token checks and add local `openclaw devices` fallback recovery for loopback `pairing required` deadlocks, with explicit fallback notice to unblock approval bootstrap flows. (#21616) Thanks @shakkernerd. +- Cron: honor `cron.maxConcurrentRuns` in the timer loop so due jobs can execute up to the configured parallelism instead of always running serially. (#11595) Thanks @Takhoffman. +- Agents/Compaction: restore embedded compaction safeguard/context-pruning extension loading in production by wiring bundled extension factories into the resource loader instead of runtime file-path resolution. (#22349) Thanks @Glucksberg. +- Agents/Subagents: restore announce-chain delivery to agent injection, defer nested announce output until descendant follow-up content is ready, and prevent descendant deferrals from consuming announce retry budget so deep chains do not drop final completions. (#22223) Thanks @tyler6204. +- Agents/System Prompt: label allowlisted senders as authorized senders to avoid implying ownership. Thanks @thewilloftheshadow. +- Agents/Tool display: fix exec cwd suffix inference so `pushd ... && popd ... && ` does not keep stale `(in )` context in summaries. (#21925) Thanks @Lukavyi. +- Agents/Google: flatten residual nested `anyOf`/`oneOf` unions in Gemini tool-schema cleanup so Cloud Code Assist no longer rejects unsupported union keywords that survive earlier simplification. (#22825) Thanks @Oceanswave. +- Tools/web_search: handle xAI Responses API payloads that emit top-level `output_text` blocks (without a `message` wrapper) so Grok web_search no longer returns `No response` for those results. (#20508) Thanks @echoVic. +- Agents/Failover: treat non-default override runs as direct fallback-to-configured-primary (skip configured fallback chain), normalize default-model detection for provider casing/whitespace, and add regression coverage for override/auth error paths. (#18820) Thanks @Glucksberg. +- Docker/Build: include `ownerDisplay` in `CommandsSchema` object-level defaults so Docker `pnpm build` no longer fails with `TS2769` during plugin SDK d.ts generation. (#22558) Thanks @obviyus. +- Docker/Browser: install Playwright Chromium into `/home/node/.cache/ms-playwright` and set `node:node` ownership so browser binaries are available to the runtime user in browser-enabled images. (#22585) thanks @obviyus. +- Hooks/Session memory: trigger bundled `session-memory` persistence on both `/new` and `/reset` so reset flows no longer skip markdown transcript capture before archival. (#21382) Thanks @mofesolapaul. +- Dependencies/Agents: bump embedded Pi SDK packages (`@mariozechner/pi-agent-core`, `@mariozechner/pi-ai`, `@mariozechner/pi-coding-agent`, `@mariozechner/pi-tui`) to `0.54.0`. (#21578) Thanks @Takhoffman. +- Config/Agents: expose Pi compaction tuning values `agents.defaults.compaction.reserveTokens` and `agents.defaults.compaction.keepRecentTokens` in config schema/types and apply them in embedded Pi runner settings overrides with floor enforcement via `reserveTokensFloor`. (#21568) Thanks @Takhoffman. +- Docker: pin base images to SHA256 digests in Docker builds to prevent mutable tag drift. (#7734) Thanks @coygeek. +- Docker: run build steps as the `node` user and use `COPY --chown` to avoid recursive ownership changes, trimming image size and layer churn. Thanks @huntharo. +- Config/Memory: restore schema help/label metadata for hybrid `mmr` and `temporalDecay` settings so configuration surfaces show correct names and guidance. (#18786) Thanks @rodrigouroz. +- Skills/SonosCLI: add troubleshooting guidance for `sonos discover` failures on macOS direct mode (`sendto: no route to host`) and sandbox network restrictions (`bind: operation not permitted`). (#21316) Thanks @huntharo. +- macOS/Build: default release packaging to `BUNDLE_ID=ai.openclaw.mac` in `scripts/package-mac-dist.sh`, so Sparkle feed URL is retained and auto-update no longer fails with an empty appcast feed. (#19750) thanks @loganprit. +- Signal/Outbound: preserve case for Base64 group IDs during outbound target normalization so cross-context routing and policy checks no longer break when group IDs include uppercase characters. (#5578) Thanks @heyhudson. +- Anthropic/Agents: preserve required pi-ai default OAuth beta headers when `context1m` injects `anthropic-beta`, preventing 401 auth failures for `sk-ant-oat-*` tokens. (#19789, fixes #19769) Thanks @minupla. +- Security/Exec: block unquoted heredoc body expansion tokens in shell allowlist analysis, reject unterminated heredocs, and require explicit approval for allowlisted heredoc execution on gateway hosts to prevent heredoc substitution allowlist bypass. Thanks @torturado for reporting. +- macOS/Security: evaluate `system.run` allowlists per shell segment in macOS node runtime and companion exec host (including chained shell operators), fail closed on shell/process substitution parsing, and require explicit approval on unsafe parse cases to prevent allowlist bypass via `rawCommand` chaining. Thanks @tdjackey for reporting. +- WhatsApp/Security: enforce allowlist JID authorization for reaction actions so authenticated callers cannot target non-allowlisted chats by forging `chatJid` + valid `messageId` pairs. Thanks @aether-ai-agent for reporting. +- ACP/Security: escape control and delimiter characters in ACP `resource_link` title/URI metadata before prompt interpolation to prevent metadata-driven prompt injection through resource links. Thanks @aether-ai-agent for reporting. +- TTS/Security: make model-driven provider switching opt-in by default (`messages.tts.modelOverrides.allowProvider=false` unless explicitly enabled), while keeping voice/style overrides available, to reduce prompt-injection-driven provider hops and unexpected TTS cost escalation. Thanks @aether-ai-agent for reporting. +- Security/Agents: keep overflow compaction retry budgeting global across tool-result truncation recovery so successful truncation cannot reset the overflow retry counter and amplify retry/cost cycles. Thanks @aether-ai-agent for reporting. +- BlueBubbles/Security: require webhook token authentication for all BlueBubbles webhook requests (including loopback/proxied setups), removing passwordless webhook fallback behavior. Thanks @zpbrent. +- iOS/Security: force `https://` for non-loopback manual gateway hosts during iOS onboarding to block insecure remote transport URLs. (#21969) Thanks @mbelinky. +- Gateway/Security: remove shared-IP fallback for canvas endpoints and require token or session capability for canvas access. Thanks @thewilloftheshadow. +- Gateway/Security: require secure context and paired-device checks for Control UI auth even when `gateway.controlUi.allowInsecureAuth` is set, and align audit messaging with the hardened behavior. (#20684) Thanks @coygeek and @Vasco0x4 for reporting. +- Gateway/Security: scope tokenless Tailscale forwarded-header auth to Control UI websocket auth only, so HTTP gateway routes still require token/password even on trusted hosts. Thanks @zpbrent for reporting. +- Docker/Security: run E2E and install-sh test images as non-root by adding appuser directives. Thanks @thewilloftheshadow. +- Skills/Security: sanitize skill env overrides to block unsafe runtime injection variables and only allow sensitive keys when declared in skill metadata, with warnings for suspicious values. Thanks @thewilloftheshadow. +- Security/Commands: block prototype-key injection in runtime `/debug` overrides and require own-property checks for gated command flags (`bash`, `config`, `debug`) so inherited prototype values cannot enable privileged commands. Thanks @tdjackey for reporting. +- Security/Browser: block non-network browser navigation protocols (including `file:`, `data:`, and `javascript:`) while preserving `about:blank`, preventing local file reads via browser tool navigation. Thanks @q1uf3ng for reporting. +- Security/Exec: block shell startup-file env injection (`BASH_ENV`, `ENV`, `BASH_FUNC_*`, `LD_*`, `DYLD_*`) across config env ingestion, node-host inherited environment sanitization, and macOS exec host runtime to prevent pre-command execution from attacker-controlled environment variables. Thanks @tdjackey. +- Security/Exec (Windows): canonicalize `cmd.exe /c` command text across validation, approval binding, and audit/event rendering to prevent trailing-argument approval mismatches in `system.run`. Thanks @tdjackey for reporting. +- Security/Gateway/Hooks: block `__proto__`, `constructor`, and `prototype` traversal in webhook template path resolution to prevent prototype-chain payload data leakage in `messageTemplate` rendering. (#22213) Thanks @SleuthCo. +- Security/OpenClawKit/UI: prevent injected inbound user context metadata blocks from leaking into chat history in TUI, webchat, and macOS surfaces by stripping all untrusted metadata prefixes at display boundaries. (#22142) Thanks @Mellowambience, @vincentkoc. +- Security/OpenClawKit/UI: strip inbound metadata blocks from user messages in TUI rendering while preserving user-authored content. (#22345) Thanks @kansodata, @vincentkoc. +- Security/OpenClawKit/UI: prevent inbound metadata leaks and reply-tag streaming artifacts in TUI rendering by stripping untrusted metadata prefixes at display boundaries. (#22346) Thanks @akramcodez, @vincentkoc. +- Security/Agents: restrict local MEDIA tool attachments to core tools and the OpenClaw temp root to prevent untrusted MCP tool file exfiltration. Thanks @NucleiAv and @thewilloftheshadow. +- Security/Net: strip sensitive headers (`Authorization`, `Proxy-Authorization`, `Cookie`, `Cookie2`) on cross-origin redirects in `fetchWithSsrFGuard` to prevent credential forwarding across origin boundaries. (#20313) Thanks @afurm. +- Security/Systemd: reject CR/LF in systemd unit environment values and fix argument escaping so generated units cannot be injected with extra directives. Thanks @thewilloftheshadow. +- Security/Tools: add per-wrapper random IDs to untrusted-content markers from `wrapExternalContent`/`wrapWebContent`, preventing marker spoofing from escaping content boundaries. (#19009) Thanks @Whoaa512. +- Shared/Security: reject insecure deep links that use `ws://` non-loopback gateway URLs to prevent plaintext remote websocket configuration. (#21970) Thanks @mbelinky. +- macOS/Security: reject non-loopback `ws://` remote gateway URLs in macOS remote config to block insecure plaintext websocket endpoints. (#21971) Thanks @mbelinky. +- Browser/Security: block upload path symlink escapes so browser upload sources cannot traverse outside the allowed workspace via symlinked paths. (#21972) Thanks @mbelinky. +- Security/Dependencies: bump transitive `hono` usage to `4.11.10` to incorporate timing-safe authentication comparison hardening for `basicAuth`/`bearerAuth` (`GHSA-gq3j-xvxp-8hrf`). Thanks @vincentkoc. +- Security/Gateway: parse `X-Forwarded-For` with trust-preserving semantics when requests come from configured trusted proxies, preventing proxy-chain spoofing from influencing client IP classification and rate-limit identity. Thanks @AnthonyDiSanti and @vincentkoc. +- Security/Sandbox: remove default `--no-sandbox` for the browser container entrypoint, add explicit opt-in via `OPENCLAW_BROWSER_NO_SANDBOX` / `CLAWDBOT_BROWSER_NO_SANDBOX`, and add security-audit checks for stale/missing sandbox browser Docker hash labels. Thanks @TerminalsandCoffee and @vincentkoc. +- Security/Sandbox Browser: require VNC password auth for noVNC observer sessions in the sandbox browser entrypoint, plumb per-container noVNC passwords from runtime, and emit short-lived noVNC observer token URLs while keeping loopback-only host port publishing. Thanks @TerminalsandCoffee for reporting. +- Security/Sandbox Browser: default browser sandbox containers to a dedicated Docker network (`openclaw-sandbox-browser`), add optional CDP ingress source-range restrictions, auto-create missing dedicated networks, and warn in `openclaw security --audit` when browser sandboxing runs on bridge without source-range limits. Thanks @TerminalsandCoffee for reporting. + +## 2026.2.19 + +### Changes + +- iOS/Watch: add an Apple Watch companion MVP with watch inbox UI, watch notification relay handling, and gateway command surfaces for watch status/send flows. (#20054) Thanks @mbelinky. - iOS/Gateway: wake disconnected iOS nodes via APNs before `nodes.invoke` and auto-reconnect gateway sessions on silent push wake to reduce invoke failures while the app is backgrounded. (#20332) Thanks @mbelinky. -- Dev tooling: align `oxfmt` local/CI formatting behavior. (#12579) Thanks @vincentkoc. +- Gateway/CLI: add paired-device hygiene flows with `device.pair.remove`, plus `openclaw devices remove` and guarded `openclaw devices clear --yes [--pending]` commands for removing paired entries and optionally rejecting pending requests. (#20057) Thanks @mbelinky. - iOS/APNs: add push registration and notification-signing configuration for node delivery. (#20308) Thanks @mbelinky. - Gateway/APNs: add a push-test pipeline for APNs delivery validation in gateway flows. (#20307) Thanks @mbelinky. -- iOS/Watch: add an Apple Watch companion MVP with watch inbox UI, watch notification relay handling, and gateway command surfaces for watch status/send flows. (#20054) Thanks @mbelinky. -- Gateway/CLI: add paired-device hygiene flows with `device.pair.remove`, plus `openclaw devices remove` and guarded `openclaw devices clear --yes [--pending]` commands for removing paired entries and optionally rejecting pending requests. (#20057) Thanks @mbelinky. -- Skills: harden coding-agent skill guidance by removing shell-command examples that interpolate untrusted issue text directly into command strings. - Security/Audit: add `gateway.http.no_auth` findings when `gateway.auth.mode="none"` leaves Gateway HTTP APIs reachable, with loopback warning and remote-exposure critical severity, plus regression coverage and docs updates. +- Skills: harden coding-agent skill guidance by removing shell-command examples that interpolate untrusted issue text directly into command strings. +- Dev tooling: align `oxfmt` local/CI formatting behavior. (#12579) Thanks @vincentkoc. ### Fixes +- Agents/Streaming: keep assistant partial streaming active during reasoning streams, handle native `thinking_*` stream events consistently, dedupe mixed reasoning-end signals, and clear stale mutating tool errors after same-target retry success. (#20635) Thanks @obviyus. +- iOS/Chat: use a dedicated iOS chat session key for ChatSheet routing to avoid cross-client session collisions with main-session traffic. (#21139) thanks @mbelinky. +- iOS/Chat: auto-resync chat history after reconnect sequence gaps, clear stale pending runs, and avoid dead-end manual refresh errors after transient disconnects. (#21135) thanks @mbelinky. +- UI/Usage: reload usage data immediately when timezone changes so Local/UTC toggles apply the selected date range without requiring a manual refresh. (#17774) +- iOS/Screen: move `WKWebView` lifecycle ownership into `ScreenWebView` coordinator and explicit attach/detach flow to reduce gesture/lifecycle crash risk (`__NSArrayM insertObject:atIndex:` paths) during screen tab updates. (#20366) Thanks @ngutman. +- iOS/Onboarding: prevent pairing-status flicker during auto-resume by keeping resumed state transitions stable. (#20310) Thanks @mbelinky. +- iOS/Onboarding: stabilize pairing and reconnect behavior by resetting stale pairing request state on manual retry, disconnecting both operator and node gateways on operator failure, and avoiding duplicate pairing loops from operator transport identity attachment. (#20056) Thanks @mbelinky. +- iOS/Signing: restore local auto-selected signing-team overrides during iOS project generation by wiring `.local-signing.xcconfig` into the active signing config and emitting `OPENCLAW_DEVELOPMENT_TEAM` in local signing setup. (#19993) Thanks @ngutman. +- Telegram: unify message-like inbound handling so `message` and `channel_post` share the same dedupe/access/media pipeline and remain behaviorally consistent. (#20591) Thanks @obviyus. +- Telegram/Agents: gate exec/bash tool-failure warnings behind verbose mode so default Telegram replies stay clean while verbose sessions still surface diagnostics. (#20560) Thanks @obviyus. +- Telegram/Cron/Heartbeat: honor explicit Telegram topic targets in cron and heartbeat delivery (`:topic:`) so scheduled sends land in the configured topic instead of the last active thread. (#19367) Thanks @Lukavyi. +- Telegram/DM routing: prevent DM inbound origin metadata from leaking into main-session `lastRoute` updates and normalize DM `lastRoute.to` to provider-prefixed `telegram:`. (#19491) thanks @guirguispierre. +- Gateway/Daemon: forward `TMPDIR` into installed service environments so macOS LaunchAgent gateway runs can open SQLite temp/journal files reliably instead of failing with `SQLITE_CANTOPEN`. (#20512) Thanks @Clawborn. +- Agents/Billing: include the active model that produced a billing error in user-facing billing messages (for example, `OpenAI (gpt-5.3)`) across payload, failover, and lifecycle error paths, so users can identify exactly which key needs credits. (#20510) Thanks @echoVic. +- Gateway/TUI: honor `agents.defaults.blockStreamingDefault` for `chat.send` by removing the hardcoded block-streaming disable override, so replies can use configured block-mode delivery. (#19693) Thanks @neipor. +- UI/Sessions: accept the canonical main session-key alias in Chat UI flows so main-session routing stays consistent. (#20311) Thanks @mbelinky. +- OpenClawKit/Protocol: preserve JSON boolean literals (`true`/`false`) when bridging through `AnyCodable` so Apple client RPC params no longer re-encode booleans as `1`/`0`. Thanks @mbelinky. +- Commands/Doctor: skip embedding-provider warnings when `memory.backend` is `qmd`, because QMD manages embeddings internally and does not require `memorySearch` providers. (#17263) Thanks @miloudbelarebia. +- Canvas/A2UI: improve bundled-asset resolution and empty-state handling so UI fallbacks render reliably. (#20312) Thanks @mbelinky. +- Commands/Doctor: avoid rewriting invalid configs with new `gateway.auth.token` defaults during repair and only write when real config changes are detected, preventing accidental token duplication and backup churn. +- Gateway/Auth: default unresolved gateway auth to token mode with startup auto-generation/persistence of `gateway.auth.token`, while allowing explicit `gateway.auth.mode: "none"` for intentional open loopback setups. (#20686) thanks @gumadeiras. +- Channels/Matrix: fix mention detection for `formatted_body` Matrix-to links by handling matrix.to mention formats consistently. (#16941) Thanks @zerone0x. +- Heartbeat/Cron: skip interval heartbeats when `HEARTBEAT.md` is missing or empty and no tagged cron events are queued, while preserving cron-event fallback for queued tagged reminders. (#20461) thanks @vikpos. +- Browser/Relay: reuse an already-running extension relay when the relay port is occupied by another OpenClaw process, while still failing on non-relay port collisions to avoid masking unrelated listeners. (#20035) Thanks @mbelinky. +- Scripts: update clawdock helper command support to include `docker-compose.extra.yml` where available. (#17094) Thanks @zerone0x. +- Lobster/Config: remove Lobster executable-path overrides (`lobsterPath`), require PATH-based execution, and add focused Windows wrapper-resolution tests to keep shell-free behavior stable. +- Gateway/WebChat: block `sessions.patch` and `sessions.delete` for WebChat clients so session-store mutations stay restricted to non-WebChat operator flows. Thanks @allsmog for reporting. +- Gateway: clarify launchctl GUI domain bootstrap failure on macOS. (#13795) Thanks @vincentkoc. +- Lobster/CI: fix flaky test Windows cmd shim script resolution. (#20833) Thanks @vincentkoc. +- Browser/Relay: require gateway-token auth on both `/extension` and `/cdp`, and align Chrome extension setup to use a single `gateway.auth.token` input for relay authentication. Thanks @tdjackey for reporting. +- Gateway/Hooks: run BOOT.md startup checks per configured agent scope, including per-agent session-key resolution, startup-hook regression coverage, and non-success boot outcome logging for diagnosability. (#20569) thanks @mcaxtr. +- Protocol/Apple: regenerate Swift gateway models for `push.test` so `pnpm protocol:check` stays green on main. Thanks @mbelinky. +- Sandbox/Registry: serialize container and browser registry writes with shared file locks and atomic replacement to prevent lost updates and delete rollback races from desyncing `sandbox list`, `prune`, and `recreate --all`. Thanks @kexinoh. +- OTEL/diagnostics-otel: complete OpenTelemetry v2 API migration. (#12897) Thanks @vincentkoc. +- Cron/Webhooks: protect cron webhook POST delivery with SSRF-guarded outbound fetch (`fetchWithSsrFGuard`) to block private/metadata destinations before request dispatch. Thanks @Adam55A-code. +- Security/Voice Call: harden `voice-call` telephony TTS override merging by blocking unsafe deep-merge keys (`__proto__`, `prototype`, `constructor`) and add regression coverage for top-level and nested prototype-pollution payloads. +- Security/Windows Daemon: harden Scheduled Task `gateway.cmd` generation by quoting cmd metacharacter arguments, escaping `%`/`!` expansions, and rejecting CR/LF in arguments, descriptions, and environment assignments (`set "KEY=VALUE"`), preventing command injection in Windows daemon startup scripts. Thanks @tdjackey for reporting. +- Security/Gateway/Canvas: replace shared-IP fallback auth with node-scoped session capability URLs for `/__openclaw__/canvas/*` and `/__openclaw__/a2ui/*`, fail closed when trusted-proxy requests omit forwarded client headers, and add IPv6/proxy-header regression coverage. Thanks @aether-ai-agent for reporting. +- Security/Net: enforce strict dotted-decimal IPv4 literals in SSRF checks and fail closed on unsupported legacy forms (octal/hex/short/packed, for example `0177.0.0.1`, `127.1`, `2130706433`) before DNS lookup. +- Security/Discord: enforce trusted-sender guild permission checks for moderation actions (`timeout`, `kick`, `ban`) and ignore untrusted `senderUserId` params to prevent privilege escalation in tool-driven flows. Thanks @aether-ai-agent for reporting. +- Security/ACP+Exec: add `openclaw acp --token-file/--password-file` secret-file support (with inline secret flag warnings), redact ACP working-directory prefixes to `~` home-relative paths, constrain exec script preflight file inspection to the effective `workdir` boundary, and add security-audit warnings when `tools.exec.host="sandbox"` is configured while sandbox mode is off. +- Security/Plugins/Hooks: enforce runtime/package path containment with realpath checks so `openclaw.extensions`, `openclaw.hooks`, and hook handler modules cannot escape their trusted roots via traversal or symlinks. +- Security/Discord: centralize trusted sender checks for moderation actions in message-action dispatch, share moderation command parsing across handlers, and clarify permission helpers with explicit any/all semantics. - Security/ACP: harden ACP bridge session management with duplicate-session refresh, idle-session reaping, oldest-idle soft-cap eviction, and burst rate limiting on session creation to reduce local DoS risk without disrupting normal IDE usage. +- Security/ACP: bound ACP prompt text payloads to 2 MiB before gateway forwarding, account for join separator bytes during pre-concatenation size checks, and avoid stale active-run session state when oversized prompts are rejected. Thanks @aether-ai-agent for reporting. +- Security/Plugins/Hooks: add optional `--pin` for npm plugin/hook installs, persist resolved npm metadata (`name`, `version`, `spec`, integrity, shasum, timestamp), warn/confirm on integrity drift during updates, and extend `openclaw security audit` to flag unpinned specs, missing integrity metadata, and install-record version drift. +- Security/Plugins: harden plugin discovery by blocking unsafe candidates (root escapes, world-writable paths, suspicious ownership), add startup warnings when `plugins.allow` is empty with discoverable non-bundled plugins, and warn on loaded plugins without install/load-path provenance. - Security/Gateway: rate-limit control-plane write RPCs (`config.apply`, `config.patch`, `update.run`) to 3 requests per minute per `deviceId+clientIp`, add restart single-flight coalescing plus a 30-second restart cooldown, and log actor/device/ip with changed-path audit details for config/update-triggered restarts. -- Commands/Doctor: skip embedding-provider warnings when `memory.backend` is `qmd`, because QMD manages embeddings internally and does not require `memorySearch` providers. (#17263) Thanks @miloudbelarebia. - Security/Webhooks: harden Feishu and Zalo webhook ingress with webhook-mode token preconditions, loopback-default Feishu bind host, JSON content-type enforcement, per-path rate limiting, replay dedupe for Zalo events, constant-time Zalo secret comparison, and anomaly status counters. -- Security/Plugins: add explicit `plugins.runtime.allowLegacyExec` opt-in to re-enable deprecated `runtime.system.runCommandWithTimeout` for legacy modules while keeping runtime command execution disabled by default. (#20874) Thanks @mbelinky. -- Gateway/WebChat: block `sessions.patch` and `sessions.delete` for WebChat clients so session-store mutations stay restricted to non-WebChat operator flows. Thanks @allsmog for reporting. +- Security/Plugins: for the next npm release, clarify plugin trust boundary and keep `runtime.system.runCommandWithTimeout` available by default for trusted in-process plugins. Thanks @markmusson for reporting. - Security/Skills: for the next npm release, reject symlinks during skill packaging to prevent external file inclusion in distributed `.skill` archives. Thanks @aether-ai-agent for reporting. - Security/Gateway: fail startup when `hooks.token` matches `gateway.auth.token` so hooks and gateway token reuse is rejected at boot. (#20813) Thanks @coygeek. - Security/Network: block plaintext `ws://` connections to non-loopback hosts and require secure websocket transport elsewhere. (#20803) Thanks @jscaldwell55. @@ -31,51 +326,23 @@ Docs: https://docs.openclaw.ai - Security/Agents: replace shell-based `execSync` usage with `execFileSync` in command lookup helpers to eliminate shell argument interpolation risk. (#20655) Thanks @mahanandhi. - Security/Media: use `crypto.randomBytes()` for temp file names and set owner-only permissions for TTS temp files. (#20654) Thanks @mahanandhi. - Security/Gateway: set baseline security headers (`X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`) on gateway HTTP responses. (#10526) Thanks @abdelsfane. -- Tests/Security: refactor `src/security/audit.test.ts` by extracting shared helpers to reduce duplication in security audit test coverage. (#20087) Thanks @habakan. -- Channels/Matrix: fix mention detection for `formatted_body` Matrix-to links by handling matrix.to mention formats consistently. (#16941) Thanks @zerone0x. -- Scripts: update clawdock helper command support to include `docker-compose.extra.yml` where available. (#17094) Thanks @zerone0x. - Security/iMessage: harden remote attachment SSH/SCP handling by requiring strict host-key verification, validating `channels.imessage.remoteHost` as `host`/`user@host`, and rejecting unsafe host tokens from config or auto-detection. Thanks @allsmog for reporting. - Security/Feishu: prevent path traversal in Feishu inbound media temp-file writes by replacing key-derived temp filenames with UUID-based names. Thanks @allsmog for reporting. -- Security/Feishu: escape mention regex metacharacters in `stripBotMention` so crafted mention metadata cannot trigger regex injection or ReDoS during inbound message parsing. (#20916) Thanks @allsmog for reporting. +- Security/Feishu: escape mention regex metacharacters in `stripBotMention` so crafted mention metadata cannot trigger regex injection or ReDoS during inbound message parsing. (#20916) Thanks @orlyjamie for the fix and @allsmog for reporting. - LINE/Security: harden inbound media temp-file naming by using UUID-based temp paths for downloaded media instead of external message IDs. (#20792) Thanks @mbelinky. -- Security/Refactor: centralize hardened temp-file path generation for Feishu and LINE media downloads via shared `buildRandomTempFilePath` helper to reduce drift risk. (#20810) Thanks @mbelinky. - Security/Media: harden local media ingestion against TOCTOU/symlink swap attacks by pinning reads to a single file descriptor with symlink rejection and inode/device verification in `saveMediaSource`. Thanks @dorjoos for reporting. - Security/Lobster (Windows): for the next npm release, remove shell-based fallback when launching Lobster wrappers (`.cmd`/`.bat`) and switch to explicit argv execution with wrapper entrypoint resolution, preventing command injection while preserving Windows wrapper compatibility. Thanks @allsmog for reporting. -- Agents/Streaming: keep assistant partial streaming active during reasoning streams, handle native `thinking_*` stream events consistently, dedupe mixed reasoning-end signals, and clear stale mutating tool errors after same-target retry success. (#20635) Thanks @obviyus. -- Security/OTEL: sanitize OTLP endpoint URL resolution. (#13791) Thanks @vincentkoc. -- OTEL/diagnostics-otel: complete OpenTelemetry v2 API migration. (#12897) Thanks @vincentkoc. -- Gateway: clarify launchctl GUI domain bootstrap failure on macOS. (#13795) Thanks @vincentkoc. -- Security: patch Dependabot security issues in pnpm lock. (#20832) Thanks @vincentkoc. -- Lobster/CI: fix flaky test Windows cmd shim script resolution. (#20833) Thanks @vincentkoc. -- Security: migrate request dependencies to `@cypress/request`. (#20836) Thanks @vincentkoc. -- Gateway/Auth: default unresolved gateway auth to token mode with startup auto-generation/persistence of `gateway.auth.token`, while allowing explicit `gateway.auth.mode: "none"` for intentional open loopback setups. (#20686) thanks @gumadeiras. -- Browser/Relay: require gateway-token auth on both `/extension` and `/cdp`, and align Chrome extension setup to use a single `gateway.auth.token` input for relay authentication. Thanks @tdjackey for reporting. -- Gateway/Hooks: run BOOT.md startup checks per configured agent scope, including per-agent session-key resolution, startup-hook regression coverage, and non-success boot outcome logging for diagnosability. (#20569) thanks @mcaxtr. -- Telegram: unify message-like inbound handling so `message` and `channel_post` share the same dedupe/access/media pipeline and remain behaviorally consistent. (#20591) Thanks @obviyus. -- Heartbeat/Cron: skip interval heartbeats when `HEARTBEAT.md` is missing or empty and no tagged cron events are queued, while preserving cron-event fallback for queued tagged reminders. (#20461) thanks @vikpos. -- Telegram/Agents: gate exec/bash tool-failure warnings behind verbose mode so default Telegram replies stay clean while verbose sessions still surface diagnostics. (#20560) Thanks @obviyus. -- Gateway/Daemon: forward `TMPDIR` into installed service environments so macOS LaunchAgent gateway runs can open SQLite temp/journal files reliably instead of failing with `SQLITE_CANTOPEN`. (#20512) Thanks @Clawborn. -- Agents/Billing: include the active model that produced a billing error in user-facing billing messages (for example, `OpenAI (gpt-5.3)`) across payload, failover, and lifecycle error paths, so users can identify exactly which key needs credits. (#20510) Thanks @echoVic. -- iOS/Screen: move `WKWebView` lifecycle ownership into `ScreenWebView` coordinator and explicit attach/detach flow to reduce gesture/lifecycle crash risk (`__NSArrayM insertObject:atIndex:` paths) during screen tab updates. (#20366) Thanks @ngutman. -- Gateway/TUI: honor `agents.defaults.blockStreamingDefault` for `chat.send` by removing the hardcoded block-streaming disable override, so replies can use configured block-mode delivery. (#19693) Thanks @neipor. -- Protocol/Apple: regenerate Swift gateway models for `push.test` so `pnpm protocol:check` stays green on main. Thanks @mbelinky. -- Canvas/A2UI: improve bundled-asset resolution and empty-state handling so UI fallbacks render reliably. (#20312) Thanks @mbelinky. -- UI/Sessions: accept the canonical main session-key alias in Chat UI flows so main-session routing stays consistent. (#20311) Thanks @mbelinky. -- iOS/Onboarding: prevent pairing-status flicker during auto-resume by keeping resumed state transitions stable. (#20310) Thanks @mbelinky. -- OpenClawKit/Protocol: preserve JSON boolean literals (`true`/`false`) when bridging through `AnyCodable` so Apple client RPC params no longer re-encode booleans as `1`/`0`. Thanks @mbelinky. -- iOS/Onboarding: stabilize pairing and reconnect behavior by resetting stale pairing request state on manual retry, disconnecting both operator and node gateways on operator failure, and avoiding duplicate pairing loops from operator transport identity attachment. (#20056) Thanks @mbelinky. -- Browser/Relay: reuse an already-running extension relay when the relay port is occupied by another OpenClaw process, while still failing on non-relay port collisions to avoid masking unrelated listeners. (#20035) Thanks @mbelinky. -- Telegram/Cron/Heartbeat: honor explicit Telegram topic targets in cron and heartbeat delivery (`:topic:`) so scheduled sends land in the configured topic instead of the last active thread. (#19367) Thanks @Lukavyi. -- iOS/Signing: restore local auto-selected signing-team overrides during iOS project generation by wiring `.local-signing.xcconfig` into the active signing config and emitting `OPENCLAW_DEVELOPMENT_TEAM` in local signing setup. (#19993) Thanks @ngutman. -- Commands/Doctor: avoid rewriting invalid configs with new `gateway.auth.token` defaults during repair and only write when real config changes are detected, preventing accidental token duplication and backup churn. -- Sandbox/Registry: serialize container and browser registry writes with shared file locks and atomic replacement to prevent lost updates and delete rollback races from desyncing `sandbox list`, `prune`, and `recreate --all`. Thanks @kexinoh. - Security/Exec: require `tools.exec.safeBins` binaries to resolve from trusted bin directories (system defaults plus gateway startup `PATH`) so PATH-hijacked trojan binaries cannot bypass allowlist checks. Thanks @jackhax for reporting. -- Security/Exec: remove file-existence oracle behavior from `tools.exec.safeBins` by using deterministic argv-only stdin-safe validation and blocking file-oriented flags (for example `sort -o`, `jq -f`, `grep -f`) so allow/deny results no longer disclose host file presence. This ships in the next npm release. Thanks @nedlir for reporting. -- Security/Browser: route browser URL navigation through one SSRF-guarded validation path for tab-open/CDP-target/Playwright navigation flows and block private/metadata destinations by default (configurable via `browser.ssrfPolicy`). This ships in the next npm release. Thanks @dorjoos for reporting. +- Security/Exec: remove file-existence oracle behavior from `tools.exec.safeBins` by using deterministic argv-only stdin-safe validation and blocking file-oriented flags (for example `sort -o`, `jq -f`, `grep -f`) so allow/deny results no longer disclose host file presence. Thanks @nedlir for reporting. +- Security/Browser: route browser URL navigation through one SSRF-guarded validation path for tab-open/CDP-target/Playwright navigation flows and block private/metadata destinations by default (configurable via `browser.ssrfPolicy`). Thanks @dorjoos for reporting. - Security/Exec: for the next npm release, harden safe-bin stdin-only enforcement by blocking output/recursive flags (`sort -o/--output`, grep recursion) and tightening default safe bins to remove `sort`/`grep`, preventing safe-bin allowlist bypass for file writes/recursive reads. Thanks @nedlir for reporting. -- Cron/Webhooks: protect cron webhook POST delivery with SSRF-guarded outbound fetch (`fetchWithSsrFGuard`) to block private/metadata destinations before request dispatch. Thanks @Adam55A-code. -- Security/Gateway/Agents: remove implicit admin scopes from agent tool gateway calls by classifying methods to least-privilege operator scopes, and restrict `cron`/`gateway` tools to owner senders (with explicit runtime owner checks) to prevent non-owner DM privilege escalation. Ships in the next npm release. Thanks @Adam55A-code for reporting. +- Security/Exec: block grep safe-bin positional operand bypass by setting grep positional budget to zero, so `-e/--regexp` cannot smuggle bare filename reads (for example `.env`) via ambiguous positionals; safe-bin grep patterns must come from `-e/--regexp`. Thanks @athuljayaram for reporting. +- Security/Gateway/Agents: remove implicit admin scopes from agent tool gateway calls by classifying methods to least-privilege operator scopes, and enforce owner-only tooling (`cron`, `gateway`, `whatsapp_login`) through centralized tool-policy wrappers plus tool metadata to prevent non-owner DM privilege escalation. Ships in the next npm release. Thanks @Adam55A-code for reporting. +- Security/Gateway: centralize gateway method-scope authorization and default non-CLI gateway callers to least-privilege method scopes, with explicit CLI scope handling, full core-handler scope classification coverage, and regression guards to prevent scope drift. - Security/Net: block SSRF bypass via NAT64 (`64:ff9b::/96`, `64:ff9b:1::/48`), 6to4 (`2002::/16`), and Teredo (`2001:0000::/32`) IPv6 transition addresses, and fail closed on IPv6 parse errors. Thanks @jackhax. +- Security/OTEL: sanitize OTLP endpoint URL resolution. (#13791) Thanks @vincentkoc. +- Security: patch Dependabot security issues in pnpm lock. (#20832) Thanks @vincentkoc. +- Security: migrate request dependencies to `@cypress/request`. (#20836) Thanks @vincentkoc. ## 2026.2.17 @@ -122,8 +389,11 @@ Docs: https://docs.openclaw.ai ### Fixes +- Agents/Antigravity: preserve unsigned Claude thinking blocks as plain text instead of dropping them during transcript sanitization, preventing reasoning context loss while avoiding `thinking.signature` request rejections. +- Agents/Google: clean tool JSON Schemas for `google-antigravity` the same as `google-gemini-cli` before Cloud Code Assist requests, preventing Claude tool calls from failing with `patternProperties` 400 errors. (#19860) - Tests/Telegram: add regression coverage for command-menu sync that asserts all `setMyCommands` entries are Telegram-safe and hyphen-normalized across native/custom/plugin command sources. (#19703) Thanks @obviyus. - Agents/Image: collapse resize diagnostics to one line per image and include visible pixel/byte size details in the log message for faster triage. +- Auth/Cooldowns: clear all usage stats fields (`disabledUntil`, `disabledReason`, `failureCounts`) in `clearAuthProfileCooldown` so manual cooldown resets fully recover billing-disabled profiles without requiring direct file edits. (#19211) Thanks @nabbilkhan. - Agents/Subagents: preemptively guard accumulated tool-result context before model calls by truncating oversized outputs and compacting oldest tool-result messages to avoid context-window overflow crashes. Thanks @tyler6204. - Agents/Subagents/CLI: fail `sessions_spawn` when subagent model patching is rejected, allow subagent model patch defaults from `subagents.model`, and keep `sessions list`/`status` model reporting aligned to runtime model resolution. (#18660) Thanks @robbyczgw-cla. - Agents/Subagents: add explicit subagent guidance to recover from `[compacted: tool output removed to free context]` / `[truncated: output exceeded context limit]` markers by re-reading with smaller chunks instead of full-file `cat`. Thanks @tyler6204. @@ -356,7 +626,6 @@ Docs: https://docs.openclaw.ai - TUI/Gateway: resolve local gateway target URL from `gateway.bind` mode (tailnet/lan) instead of hardcoded localhost so `openclaw tui` connects when gateway is non-loopback. (#16299) Thanks @cortexuvula. - TUI: honor explicit `--session ` in `openclaw tui` even when `session.scope` is `global`, so named sessions no longer collapse into shared global history. (#16575) Thanks @cinqu. - TUI: use available terminal width for session name display in searchable select lists. (#16238) Thanks @robbyczgw-cla. -- TUI: refactor searchable select list description layout and add regression coverage for ANSI-highlight width bounds. - TUI: preserve in-flight streaming replies when a different run finalizes concurrently (avoid clearing active run or reloading history mid-stream). (#10704) Thanks @axschr73. - TUI: keep pre-tool streamed text visible when later tool-boundary deltas temporarily omit earlier text blocks. (#6958) Thanks @KrisKind75. - TUI: sanitize ANSI/control-heavy history text, redact binary-like lines, and split pathological long unbroken tokens before rendering to prevent startup crashes on binary attachment history. (#13007) Thanks @wilkinspoe. @@ -448,7 +717,6 @@ Docs: https://docs.openclaw.ai - Security/Windows: avoid shell invocation when spawning child processes to prevent cmd.exe metacharacter injection via untrusted CLI arguments (e.g. agent prompt text). - Telegram: set webhook callback timeout handling to `onTimeout: "return"` (10s) so long-running update processing no longer emits webhook 500s and retry storms. (#16763) Thanks @chansearrington. - Signal: preserve case-sensitive `group:` target IDs during normalization so mixed-case group IDs no longer fail with `Group not found`. (#16748) Thanks @repfigit. -- Feishu/Security: harden media URL fetching against SSRF and local file disclosure. (#16285) Thanks @mbelinky. - Security/Agents: scope CLI process cleanup to owned child PIDs to avoid killing unrelated processes on shared hosts. Thanks @aether-ai-agent. - Security/Agents: enforce workspace-root path bounds for `apply_patch` in non-sandbox mode to block traversal and symlink escape writes. Thanks @p80n-sec. - Security/Agents: enforce symlink-escape checks for `apply_patch` delete hunks under `workspaceOnly`, while still allowing deleting the symlink itself. Thanks @p80n-sec. @@ -674,13 +942,6 @@ Docs: https://docs.openclaw.ai - Media: strip `MEDIA:` lines with local paths instead of leaking as visible text. (#14399) Thanks @0xRaini. - Config/Cron: exclude `maxTokens` from config redaction and honor `deleteAfterRun` on skipped cron jobs. (#13342) Thanks @niceysam. - Config: ignore `meta` field changes in config file watcher. (#13460) Thanks @brandonwise. -- Cron: use requested `agentId` for isolated job auth resolution. (#13983) Thanks @0xRaini. -- Cron: pass `agentId` to `runHeartbeatOnce` for main-session jobs. (#14140) Thanks @ishikawa-pro. -- Cron: prevent cron jobs from skipping execution when `nextRunAtMs` advances. (#14068) Thanks @WalterSumbon. -- Cron: re-arm timers when `onTimer` fires while a job is still executing. (#14233) Thanks @tomron87. -- Cron: prevent duplicate fires when multiple jobs trigger simultaneously. (#14256) Thanks @xinhuagu. -- Cron: isolate scheduler errors so one bad job does not break all jobs. (#14385) Thanks @MarvinDontPanic. -- Cron: prevent one-shot `at` jobs from re-firing on restart after skipped/errored runs. (#13878) Thanks @lailoo. - Daemon: suppress `EPIPE` error when restarting LaunchAgent. (#14343) Thanks @0xRaini. - Antigravity: add opus 4.6 forward-compat model and bypass thinking signature sanitization. (#14218) Thanks @jg-noncelogic. - Agents: prevent file descriptor leaks in child process cleanup. (#13565) Thanks @KyleChen26. @@ -933,17 +1194,10 @@ Docs: https://docs.openclaw.ai - Discord: route autoThread replies to existing threads instead of the root channel. (#8302) Thanks @gavinbmoore, @thewilloftheshadow. - Media understanding: apply SSRF guardrails to provider fetches; allow private baseUrl overrides explicitly. - fix(voice-call): harden inbound allowlist; reject anonymous callers; require Telnyx publicKey for allowlist; token-gate Twilio media streams; cap webhook body size (thanks @simecek) -- fix(webchat): respect user scroll position during streaming and refresh (#7226) (thanks @marcomarandiz) -- Telegram: recover from grammY long-poll timed out errors. (#7466) Thanks @macmimi23. -- Agents: repair malformed tool calls and session transcripts. (#7473) Thanks @justinhuangcode. -- fix(agents): validate AbortSignal instances before calling AbortSignal.any() (#7277) (thanks @Elarwei001) -- Media understanding: skip binary media from file text extraction. (#7475) Thanks @AlexZhangji. - Onboarding: keep TUI flow exclusive (skip completion prompt + background Web UI seed); completion prompt now handled by install/update. -- TUI: block onboarding output while TUI is active and restore terminal state on exit. - CLI/Zsh completion: cache scripts in state dir and escape option descriptions to avoid invalid option errors. - fix(ui): resolve Control UI asset path correctly. - fix(ui): refresh agent files after external edits. -- Docs: finish renaming the QMD memory docs to reference the OpenClaw state dir. - Tests: stub SSRF DNS pinning in web auto-reply + Gemini video coverage. (#6619) Thanks @joshp123. ## 2026.2.1 @@ -1806,7 +2060,6 @@ Thanks @AlexMikhalev, @CoreyH, @John-Rood, @KrauseFx, @MaudeBot, @Nachx639, @Nic - Heartbeat: tighten prompt guidance + suppress duplicate alerts for 24h. (#980) — thanks @voidserf. - Repo: ignore local identity files to avoid accidental commits. (#1001) — thanks @gerardward2007. - Sessions/Security: add `session.dmScope` for multi-user DM isolation and audit warnings. (#948) — thanks @Alphonse-arianee. -- Plugins: add provider auth registry + `openclaw models auth login` for plugin-driven OAuth/API key flows. - Onboarding: switch channels setup to a single-select loop with per-channel actions and disabled hints in the picker. - TUI: show provider/model labels for the active session and default model. - Heartbeat: add per-agent heartbeat configuration and multi-agent docs example. @@ -2342,7 +2595,6 @@ Thanks @AlexMikhalev, @CoreyH, @John-Rood, @KrauseFx, @MaudeBot, @Nachx639, @Nic - Skills additions (Himalaya email, CodexBar, 1Password). - Dependency refreshes (pi-\* stack, Slack SDK, discord-api-types, file-type, zod, Biome, Vite). -- Refactors: centralized group allowlist/mention policy; lint/import cleanup; switch tsx → bun for TS execution. ## 2026.1.5 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index eddb13348eec6..2beaeeba290e0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -32,6 +32,9 @@ Welcome to the lobster tank! 🦞 - **Mariano Belinky** - iOS app, Security - GitHub: [@mbelinky](https://github.com/mbelinky) · X: [@belimad](https://x.com/belimad) +- **Vincent Koc** - Agents, Telemetry, Hooks, Security + - GitHub: [@vincentkoc](https://github.com/vincentkoc) · X: [@vincent_koc](https://x.com/vincent_koc) + - **Seb Slight** - Docs, Agent Reliability, Runtime Hardening - GitHub: [@sebslight](https://github.com/sebslight) · X: [@sebslig](https://x.com/sebslig) @@ -41,6 +44,9 @@ Welcome to the lobster tank! 🦞 - **Gustavo Madeira Santana** - Multi-agents, CLI, web UI - GitHub: [@gumadeiras](https://github.com/gumadeiras) · X: [@gumadeiras](https://x.com/gumadeiras) +- **Onur Solmaz** - Agents, dev workflows, ACP integrations, MS Teams + - GitHub: [@onutc](https://github.com/onutc), [@osolmaz](https://github.com/osolmaz) · X: [@onusoz](https://x.com/onusoz) + ## How to Contribute 1. **Bugs & small fixes** → Open a PR! diff --git a/Dockerfile b/Dockerfile index 2ead5c51fcd3a..255340cb02bff 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM node:22-bookworm +FROM node:22-bookworm@sha256:cd7bcd2e7a1e6f72052feb023c7f6b722205d3fcab7bbcbd2d1bfdab10b1e935 # Install Bun (required for build scripts) RUN curl -fsSL https://bun.sh/install | bash @@ -7,6 +7,7 @@ ENV PATH="/root/.bun/bin:${PATH}" RUN corepack enable WORKDIR /app +RUN chown node:node /app ARG OPENCLAW_DOCKER_APT_PACKAGES="" RUN if [ -n "$OPENCLAW_DOCKER_APT_PACKAGES" ]; then \ @@ -16,27 +17,33 @@ RUN if [ -n "$OPENCLAW_DOCKER_APT_PACKAGES" ]; then \ rm -rf /var/lib/apt/lists/* /var/cache/apt/archives/*; \ fi -COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./ -COPY ui/package.json ./ui/package.json -COPY patches ./patches -COPY scripts ./scripts +COPY --chown=node:node package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./ +COPY --chown=node:node ui/package.json ./ui/package.json +COPY --chown=node:node patches ./patches +COPY --chown=node:node scripts ./scripts +USER node RUN pnpm install --frozen-lockfile # Optionally install Chromium and Xvfb for browser automation. # Build with: docker build --build-arg OPENCLAW_INSTALL_BROWSER=1 ... # Adds ~300MB but eliminates the 60-90s Playwright install on every container start. # Must run after pnpm install so playwright-core is available in node_modules. +USER root ARG OPENCLAW_INSTALL_BROWSER="" RUN if [ -n "$OPENCLAW_INSTALL_BROWSER" ]; then \ apt-get update && \ DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends xvfb && \ + mkdir -p /home/node/.cache/ms-playwright && \ + PLAYWRIGHT_BROWSERS_PATH=/home/node/.cache/ms-playwright \ node /app/node_modules/playwright-core/cli.js install --with-deps chromium && \ + chown -R node:node /home/node/.cache/ms-playwright && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* /var/cache/apt/archives/*; \ fi -COPY . . +USER node +COPY --chown=node:node . . RUN pnpm build # Force pnpm for UI build (Bun may fail on ARM/Synology architectures) ENV OPENCLAW_PREFER_PNPM=1 @@ -44,9 +51,6 @@ RUN pnpm ui:build ENV NODE_ENV=production -# Allow non-root user to write temp files during runtime/tests. -RUN chown -R node:node /app - # Security hardening: Run as non-root user # The node:22-bookworm image includes a 'node' user (uid 1000) # This reduces the attack surface by preventing container escape via root privileges diff --git a/Dockerfile.sandbox b/Dockerfile.sandbox index 21fd321a49284..a463d4a102010 100644 --- a/Dockerfile.sandbox +++ b/Dockerfile.sandbox @@ -1,4 +1,4 @@ -FROM debian:bookworm-slim +FROM debian:bookworm-slim@sha256:98f4b71de414932439ac6ac690d7060df1f27161073c5036a7553723881bffbe ENV DEBIAN_FRONTEND=noninteractive diff --git a/Dockerfile.sandbox-browser b/Dockerfile.sandbox-browser index 4eccbc9a1ae77..ec9faf7111314 100644 --- a/Dockerfile.sandbox-browser +++ b/Dockerfile.sandbox-browser @@ -1,4 +1,4 @@ -FROM debian:bookworm-slim +FROM debian:bookworm-slim@sha256:98f4b71de414932439ac6ac690d7060df1f27161073c5036a7553723881bffbe ENV DEBIAN_FRONTEND=noninteractive diff --git a/README.md b/README.md index fe96768c95fb1..72f362418d72a 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,12 @@ The wizard guides you step by step through setting up the gateway, workspace, ch Works with npm, pnpm, or bun. New install? Start here: [Getting started](https://docs.openclaw.ai/start/getting-started) +## Sponsors + +| OpenAI | Blacksmith | +| ----------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| [![OpenAI](docs/assets/sponsors/openai.svg)](https://openai.com/) | [![Blacksmith](docs/assets/sponsors/blacksmith.svg)](https://blacksmith.sh/) | + **Subscriptions (OAuth):** - **[Anthropic](https://www.anthropic.com/)** (Claude Pro/Max) @@ -497,54 +503,78 @@ Special thanks to Adam Doppelt for lobster.bot. Thanks to all clawtributors:

- steipete joshp123 cpojer Mariano Belinky sebslight Takhoffman quotentiroler bohdanpodvirnyi tyler6204 iHildy - jaydenfyi gumadeiras joaohlisboa mneves75 MatthieuBizien Glucksberg MaudeBot rahthakor vrknetha vignesh07 - radek-paclt abdelsfane Tobias Bischoff christianklotz czekaj ethanpalm mukhtharcm maxsumrall rodrigouroz xadenryan - VACInc juanpablodlc conroywhitney hsrvc magimetal zerone0x advaitpaliwal meaningfool patelhiren NicholasSpisak - jonisjongithub abhisekbasu1 theonejvo jamesgroat BunsDev claude JustYannicc Hyaxia dantelex SocialNerd42069 - daveonkels Yida-Dev google-labs-jules[bot] riccardogiorato lc0rp adam91holt mousberg clawdinator[bot] hougangdev shakkernerd - coygeek mteam88 hirefrank M00N7682 joeynyc orlyjamie dbhurley Eng. Juan Combetto TSavo aerolalit - julianengel bradleypriest benithors lsh411 gut-puncture rohannagpal timolins f-trycua benostein elliotsecops - nachx639 pvoo sreekaransrinath gupsammy cristip73 stefangalescu nachoiacovino Vasanth Rao Naik Sabavat thewilloftheshadow petter-b - leszekszpunar scald pycckuu AnonO6 andranik-sahakyan davidguttman jarvis89757 sleontenko denysvitali TinyTb - sircrumpet peschee nicolasstanley davidiach nonggia.liang ironbyte-rgb dominicnunez lploc94 ratulsarna sfo2001 - lutr0 kiranjd danielz1z Iranb cdorsey AdeboyeDN obviyus Alg0rix papago2355 peetzweg/ - emanuelst evanotero KristijanJovanovski jlowin rdev rhuanssauro joshrad-dev osolmaz adityashaw2 shadril238 - CashWilliams sheeek ryan jasonsschin artuskg onutc pauloportella HirokiKobayashi-R ThanhNguyxn 18-RAJAT - kimitaka yuting0624 neooriginal manuelhettich unisone baccula manikv12 sbking travisirby fujiwara-tofu-shop - buddyh connorshea bjesuiter kyleok mcinteerj slonce70 calvin-hpnet gitpds ide-rea badlogic - grp06 dependabot[bot] amitbiswal007 John-Rood timkrase gerardward2007 roshanasingh4 tosh-hamburg azade-c dlauer - ezhikkk JonUleis shivamraut101 cheeeee jabezborja robbyczgw-cla YuriNachos Josh Phillips Wangnov kaizen403 - patrickshao Whoaa512 chriseidhof ngutman wangai-studio ysqander Yurii Chukhlib aj47 kennyklee superman32432432 - Hisleren antons austinm911 blacksmith-sh[bot] damoahdominic dan-dr doodlewind GHesericsu HeimdallStrategy imfing - jalehman jarvis-medmatic kkarimi Lukavyi mahmoudashraf93 pkrmf RandyVentures Ryan Lisse Yeom-JinHo dougvk - erikpr1994 fal3 Ghost hyf0-agent jonasjancarik Keith the Silly Goose L36 Server Marc mitschabaude-bot mkbehr - neist orenyomtov sibbl zats abhijeet117 chrisrodz Friederike Seiler gabriel-trigo hudson-rivera iamadig - itsjling Jonathan D. Rhyne (DJ-D) Joshua Mitchell kelvinCB Kit koala73 lailoo manmal mattqdev mcaxtr - mitsuhiko ogulcancelik petradonka rubyrunsstuff rybnikov siddhantjain suminhthanh svkozak wes-davis 24601 - ameno- bonald bravostation Chris Taylor damaozi dguido Django Navarro evalexpr henrino3 humanwritten - j2h4u larlyssa liuxiaopai-ai odysseus0 oswalpalash pcty-nextgen-service-account pi0 rmorse Roopak Nijhara Syhids - tmchow Ubuntu xiaose Aaron Konyer aaronveklabs akramcodez aldoeliacim andreabadesso Andrii BinaryMuse - bqcfjwhz85-arch cash-echo-bot Clawd ClawdFx danballance danielcadenhead Elarwei001 EnzeD erik-agens Evizero - fcatuhe gildo hclsys itsjaydesu ivancasco ivanrvpereira Jarvis jayhickey jeffersonwarrior jeffersonwarrior - jverdi longmaba Marco Marandiz MarvinCui mattezell mjrussell odnxe optimikelabs p6l-richard philipp-spiess - Pocket Clawd RayBB robaxelsen Sash Catanzarite Suksham-sharma T5-AndyML thejhinvirtuoso travisp VAC william arzt - yudshj zknicker 0oAstro Abdul535 abhaymundhara aduk059 aisling404 alejandro maza Alex-Alaniz alexanderatallah - alexstyl AlexZhangji andrewting19 anpoirier araa47 arthyn Asleep123 Ayush Ojha Ayush10 bguidolim - bolismauro caelum0x championswimmer chenyuan99 Chloe-VP Claude Code Clawdbot Maintainers conhecendoia dasilva333 David-Marsh-Photo - deepsoumya617 Developer Dimitrios Ploutarchos Drake Thomsen dvrshil dxd5001 dylanneve1 Felix Krause foeken frankekn - fredheir Fronut ganghyun kim grrowl gtsifrikas HassanFleyah HazAT hrdwdmrbl hugobarauna iamEvanYT - ichbinlucaskim Jamie Openshaw Jane Jarvis Deploy Jefferson Nunn jogi47 kentaro Kevin Lin kira-ariaki kitze - Kiwitwitter kossoy levifig liuy Lloyd loganaden longjos loukotal mac mimi markusbkoch - martinpucik Matt mini mertcicekci0 Miles minghinmatthewlam mrdbstn MSch mudrii Mustafa Tag Eldeen myfunc - mylukin nathanbosse ndraiman nexty5870 Noctivoro Omar-Khaleel ozgur-polat pasogott plum-dawg pookNast - ppamment prathamdby ptn1411 rafaelreis-r rafelbev reeltimeapps RLTCmpe robhparker rohansachinpatil Rony Kelner - ryancnelson Samrat Jha seans-openclawbot senoldogann Seredeep sergical shatner shiv19 shiyuanhai Shrinija17 - siraht snopoke spiceoogway stephenchen2025 succ985 Suvink techboss testingabc321 tewatia The Admiral - therealZpoint-bot thesash uos-status vcastellm Vibe Kanban vincentkoc void Vultr-Clawd Admin Wimmie wolfred - wstock wytheme YangHuang2280 yazinsai yevhen YiWang24 ymat19 Zach Knickerbocker zackerthescar zhixian - 0xJonHoldsCrypto aaronn Alphonse-arianee atalovesyou Azade carlulsoe ddyo Erik jiulingyun latitudeki5223 - Manuel Maly minghinmatthewlam Mourad Boustani odrobnik pcty-nextgen-ios-builder Quentin rafaelreis-r Randy Torres rhjoh Rolf Fredheim - ronak-guliani William Stock - Akash Kobal + steipete sktbrd cpojer joshp123 sebslight Mariano Belinky Takhoffman tyler6204 quotentiroler Verite Igiraneza + bohdanpodvirnyi gumadeiras iHildy jaydenfyi joaohlisboa rodrigouroz Glucksberg mneves75 MatthieuBizien MaudeBot + vignesh07 vincentkoc smartprogrammer93 advaitpaliwal HenryLoenwind rahthakor vrknetha abdelsfane radek-paclt joshavant + christianklotz zerone0x ranausmanai Tobias Bischoff heyhudson czekaj ethanpalm mukhtharcm yinghaosang aether-ai-agent + nabbilkhan Mrseenz maxsumrall coygeek xadenryan VACInc juanpablodlc conroywhitney buerbaumer Bridgerz + hsrvc magimetal openclaw-bot meaningfool mudrii JustasM ENCHIGO patelhiren NicholasSpisak claude + jonisjongithub abhisekbasu1 theonejvo Blakeshannon jamesgroat Marvae BunsDev shakkernerd gejifeng akoscz + divanoli ryan-crabbe nyanjou Sam Padilla dantelex SocialNerd42069 solstead natefikru daveonkels LeftX + Yida-Dev Masataka Shinohara arosstale riccardogiorato lc0rp adam91holt mousberg BillChirico shadril238 CharlieGreenman + hougangdev orlyjamie McRolly NWANGWU durenzidu JustYannicc Minidoracat magendary jessy2027 mteam88 hirefrank + M00N7682 dbhurley Eng. Juan Combetto Harrington-bot TSavo Lalit Singh julianengel jscaldwell55 bradleypriest TsekaLuk + benithors Shailesh loiie45e El-Fitz benostein pvtclawn thewilloftheshadow nachx639 0xRaini Taylor Asplund + Paul van Oorschot sreekaransrinath buddyh gupsammy AI-Reviewer-QS Stefan Galescu WalterSumbon nachoiacovino xinhuagu brandonwise + rodbland2021 Vasanth Rao Naik Sabavat fagemx petter-b leszekszpunar davidrudduck Jackten scald pycckuu Parker Todd Brooks + simonemacario omair445 AnonO6 Tanwa Arpornthip andranik-sahakyan davidguttman sleontenko denysvitali Tom Ron popomore + Patrick Barletta shayan919293 不做了睡大觉 Lucky Michael Lee sircrumpet peschee dakshaymehta nicolasstanley davidiach + nonggia.liang seheepeak danielwanwx hudson-rivera misterdas Shuai-DaiDai dominicnunez obviyus lploc94 sfo2001 + lutr0 dirbalak cathrynlavery kiranjd danielz1z Iranb cdorsey AdeboyeDN j2h4u Alg0rix + Skyler Miao peetzweg/ TideFinder Clawborn emanuelst bsormagec Diaspar4u evanotero Nate OscarMinjarez + webvijayi garnetlyx jlowin liebertar Max rhuanssauro joshrad-dev osolmaz adityashaw2 CashWilliams + sheeek asklee-klawd h0tp-ftw constansino Mitsuyuki Osabe onutc ryan artuskg Solvely-Colin mcaxtr + HirokiKobayashi-R taw0002 Kimitaka Watanabe Lilo Rajat Joshi Yuting Lin Neo Thorfinn wu-tian807 crimeacs + manuelhettich mcinteerj unisone bjesuiter Manik Vahsith alexgleason Nicholas Stephen Brian King mahanandhi andreesg + connorshea dinakars777 divisonofficer Flash-LHR Protocol Zero kyleok Limitless slonce70 grp06 robbyczgw-cla + JayMishra-source ngutman ide-rea badlogic lailoo amitbiswal007 azade-c John-Rood Iron9521 roshanasingh4 + tosh-hamburg dlauer ezhikkk Shivam Kumar Raut jabezborja Mykyta Bozhenko YuriNachos Josh Phillips Wangnov jadilson12 + 康熙 akramcodez clawdinator[bot] emonty kaizen403 Whoaa512 chriseidhof wangai-studio ysqander Yurii Chukhlib + 17jmumford aj47 google-labs-jules[bot] hyf0-agent Kenny Lee Lukavyi Operative-001 superman32432432 DylanWoodAkers Hisleren + widingmarcus-cyber antons austinm911 boris721 damoahdominic dan-dr doodlewind GHesericsu HeimdallStrategy imfing + jalehman jarvis-medmatic kkarimi mahmoudashraf93 pkrmf Randy Torres Ryan Lisse sumleo Yeom-JinHo zisisp + akyourowngames aldoeliacim Dithilli dougvk erikpr1994 fal3 Ghost jonasjancarik Keith the Silly Goose koala73 + L36 Server Marc mitschabaude-bot mkbehr Oren Rain shtse8 sibbl thesomewhatyou zats + chrisrodz echoVic Friederike Seiler gabriel-trigo ghsmc iamadig ibrahimq21 irtiq7 jeann2013 jogelin + Jonathan D. Rhyne (DJ-D) Joshua Mitchell Justin Ling kelvinCB Kit manmal MattQ Milofax mitsuhiko neist + pejmanjohn Ralph rmorse rubyrunsstuff rybnikov Steve (OpenClaw) suminhthanh svkozak wes-davis 24601 + AkashKobal ameno- awkoy BinHPdev bonald Chris Taylor dawondyifraw dguido Django Navarro evalexpr + henrino3 humanwritten hyojin joeykrug justinhuangcode larlyssa liuy ludd50155 Mark Liu natedenh + odysseus0 pcty-nextgen-service-account pi0 Roopak Nijhara Sean McLellan Syhids tmchow Ubuntu uli-will-code xiaose + Aaron Konyer aaronveklabs Aditya Singh andreabadesso Andrii battman21 BinaryMuse cash-echo-bot CJWTRUST Clawd + Clawdbot ClawdFx cordx56 danballance Elarwei001 EnzeD erik-agens Evizero fcatuhe gildo + Grynn hanxiao Ignacio itsjaydesu ivancasco ivanrvpereira Jarvis jayhickey jeffersonwarrior jeffersonwarrior + jverdi kentaro loeclos longmaba Marco Marandiz MarvinCui mjrussell odnxe optimikelabs oswalpalash + p6l-richard philipp-spiess Pocket Clawd RamiNoodle733 Raymond Berger Rob Axelsen Sash Catanzarite sauerdaniel Sriram Naidu Thota T5-AndyML + thejhinvirtuoso travisp VAC william arzt Yao yudshj zknicker 尹凯 {Suksham-sharma} 0oAstro + 8BlT Abdul535 abhaymundhara abhijeet117 aduk059 afurm aisling404 akari-musubi alejandro maza Alex-Alaniz + alexanderatallah alexstyl AlexZhangji amabito andrewting19 anisoptera araa47 arthyn Asleep123 Ayush Ojha + Ayush10 baccula beefiker bennewton999 bguidolim blacksmith-sh[bot] bqcfjwhz85-arch bravostation Buddy (AI) caelum0x + calvin-hpnet championswimmer chenglun.hu Chloe-VP Claw Clawdbot Maintainers cristip73 danielcadenhead dario-github DarwinsBuddy + David-Marsh-Photo davidbors-snyk dcantu96 dependabot[bot] Developer Dimitrios Ploutarchos Drake Thomsen dvrshil dxd5001 dylanneve1 + elliotsecops EmberCF ereid7 eternauta1337 f-trycua fan Felix Krause foeken frankekn fujiwara-tofu-shop + ganghyun kim gaowanqi08141999 gerardward2007 gitpds gtsifrikas habakan HassanFleyah HazAT hcl headswim + hlbbbbbbb Hubert hugobarauna hyaxia iamEvanYT ikari ikari-pl Iron ironbyte-rgb Ítalo Souza + Jamie Openshaw Jane Jarvis Deploy jarvis89757 jasonftl jasonsschin Jefferson Nunn jg-noncelogic jigar joeynyc + Jon Uleis Josh Long justyannicc Karim Naguib Kasper Neist Christjansen Keshav Rao Kevin Lin Kira knocte Knox + Kristijan Jovanovski Kyle Chen Latitude Bot Levi Figueira Liu Weizhan Lloyd Loganaden Velvindron lsh411 Lucas Kim Luka Zhang + Lukáš Loukota Lukin mac mimi mac26ai MackDing Mahsum Aktas Marc Beaupre Marcus Neves Mario Zechner Markus Buhatem Koch + Martin Púčik Martin Schürrer MarvinDontPanic Mateusz Michalik Matias Wainsten Matt Ezell Matt mini Matthew Dicembrino Mauro Bolis mcwigglesmcgee + meaadore1221-afk Mert Çiçekçi Michael Verrilli Miles minghinmatthewlam Mourad Boustani Mr. Guy Mustafa Tag Eldeen myfunc Nate + Nathaniel Kelner Netanel Draiman niceysam Nick Lamb Nick Taylor Nikolay Petrov NM nobrainer-tech Noctivoro norunners + Ocean Vael Ogulcan Celik Oleg Kossoy Olshansk Omar Khaleel OpenClaw Agent Ozgur Polat Pablo Nunez Palash Oswal pasogott + Patrick Shao Paul Pamment Paulo Portella Peter Lee Petra Donka Pham Nam pierreeurope pip-nomel plum-dawg pookNast + Pratham Dubey Quentin rafaelreis-r Raikan10 Ramin Shirali Hossein Zade Randy Torres Raphael Borg Ellul Vincenti Ratul Sarna Richard Pinedo Rick Qian + robhparker Rohan Nagpal Rohan Patil rohanpatriot Rolf Fredheim Rony Kelner Ryan Nelson Samrat Jha Santosh Sascha Reuter + Saurabh.Chopade saurav470 seans-openclawbot SecondThread seewhy Senol Dogan Sergiy Dybskiy Shadow shatner Shaun Loo + Shaun Mason Shiva Prasad Shrinija Kummari Siddhant Jain Simon Kelly SK Heavy Industries sldkfoiweuaranwdlaiwyeoaw Soumyadeep Ghosh Spacefish spiceoogway + Stephen Chen Steve succ985 Suksham Sunwoo Yu Suvin Nimnaka Swader swizzmagik Tag techboss + testingabc321 tewatia The Admiral therealZpoint-bot tian Xiao Tim Krase Timo Lins Tom McKenzie Tom Peri Tomas Hajek + Tomsun28 Tonic Travis Hinton Travis Irby Tulsi Prasad Ty Sabs Tyler uos-status Vai Varun Kruthiventi + Vibe Kanban Victor Castell victor-wu.eth vikpos Vincent VintLin Vladimir Peshekhonov void Vultr-Clawd Admin William Stock + williamtwomey Wimmie Winry Winston wolfred Xin Xinhe Hu Xu Haoran Yash Yaxuan42 + Yazin Yevhen Bobrov Yi Wang ymat19 Yuan Chen Yuanhai Zach Knickerbocker Zaf (via OpenClaw) zhixian 石川 諒 + 0xJonHoldsCrypto aaronn Alphonse-arianee atalovesyou Azade carlulsoe ddyo Erik hrdwdmrbl jiulingyun + kitze latitudeki5223 loukotal Manuel Maly minghinmatthewlam MSch odrobnik pcty-nextgen-ios-builder rafaelreis-r ratulsarna + reeltimeapps rhjoh ronak-guliani snopoke thesash timkrase

diff --git a/SECURITY.md b/SECURITY.md index c64b1ef99cb49..1a26e7541c06b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -47,7 +47,35 @@ When patching a GHSA via `gh api`, include `X-GitHub-Api-Version: 2022-11-28` (o - Public Internet Exposure - Using OpenClaw in ways that the docs recommend not to +- Deployments where mutually untrusted/adversarial operators share one gateway host and config - Prompt injection attacks +- Reports that require write access to trusted local state (`~/.openclaw`, workspace files like `MEMORY.md` / `memory/*.md`) + +## Deployment Assumptions + +OpenClaw security guidance assumes: + +- The host where OpenClaw runs is within a trusted OS/admin boundary. +- Anyone who can modify `~/.openclaw` state/config (including `openclaw.json`) is effectively a trusted operator. +- A single Gateway shared by mutually untrusted people is **not a recommended setup**. Use separate gateways (or at minimum separate OS users/hosts) per trust boundary. +- Authenticated Gateway callers are treated as trusted operators. Session identifiers (for example `sessionKey`) are routing controls, not per-user authorization boundaries. + +## Workspace Memory Trust Boundary + +`MEMORY.md` and `memory/*.md` are plain workspace files and are treated as trusted local operator state. + +- If someone can edit workspace memory files, they already crossed the trusted operator boundary. +- Memory search indexing/recall over those files is expected behavior, not a sandbox/security boundary. +- Example report pattern considered out of scope: "attacker writes malicious content into `memory/*.md`, then `memory_search` returns it." +- If you need isolation between mutually untrusted users, split by OS user or host and run separate gateways. + +## Plugin Trust Boundary + +Plugins/extensions are loaded **in-process** with the Gateway and are treated as trusted code. + +- Plugins can execute with the same OS privileges as the OpenClaw process. +- Runtime helpers (for example `runtime.system.runCommandWithTimeout`) are convenience APIs, not a sandbox boundary. +- Only install plugins you trust, and prefer `plugins.allow` to pin explicit trusted plugin ids. ## Operational Guidance @@ -68,6 +96,10 @@ OpenClaw's web interface (Gateway Control UI + HTTP endpoints) is intended for * - Recommended: keep the Gateway **loopback-only** (`127.0.0.1` / `::1`). - Config: `gateway.bind="loopback"` (default). - CLI: `openclaw gateway run --bind loopback`. +- `gateway.controlUi.dangerouslyDisableDeviceAuth` is intended for localhost-only break-glass use. + - OpenClaw keeps deployment flexibility by design and does not hard-forbid non-local setups. + - Non-local and other risky configurations are surfaced by `openclaw security audit` as dangerous findings. + - This operator-selected tradeoff is by design and not, by itself, a security vulnerability. - Canvas host note: network-visible canvas is **intentional** for trusted node scenarios (LAN/tailnet). - Expected setup: non-loopback bind + Gateway auth (token/password/trusted-proxy) + firewall/tailnet controls. - Expected routes: `/__openclaw__/canvas/`, `/__openclaw__/a2ui/`. diff --git a/appcast.xml b/appcast.xml index 3318fbaf86b61..ac9369da0076e 100644 --- a/appcast.xml +++ b/appcast.xml @@ -209,105 +209,155 @@ - 2026.2.13 - Sat, 14 Feb 2026 04:30:23 +0100 + 2026.2.21 + Sat, 21 Feb 2026 17:55:48 +0100 https://raw.githubusercontent.com/openclaw/openclaw/main/appcast.xml - 9846 - 2026.2.13 + 13056 + 2026.2.21 15.0 - OpenClaw 2026.2.13 + OpenClaw 2026.2.21

Changes

    -
  • Discord: send voice messages with waveform previews from local audio files (including silent delivery). (#7253) Thanks @nyanjou.
  • -
  • Discord: add configurable presence status/activity/type/url (custom status defaults to activity text). (#10855) Thanks @h0tp-ftw.
  • -
  • Slack/Plugins: add thread-ownership outbound gating via message_sending hooks, including @-mention bypass tracking and Slack outbound hook wiring for cancel/modify behavior. (#15775) Thanks @DarlingtonDeveloper.
  • -
  • Agents: add synthetic catalog support for hf:zai-org/GLM-5. (#15867) Thanks @battman21.
  • -
  • Skills: remove duplicate local-places Google Places skill/proxy and keep goplaces as the single supported Google Places path.
  • -
  • Agents: add pre-prompt context diagnostics (messages, systemPromptChars, promptChars, provider/model, session file) before embedded runner prompt calls to improve overflow debugging. (#8930) Thanks @Glucksberg.
  • +
  • Models/Google: add Gemini 3.1 support (google/gemini-3.1-pro-preview).
  • +
  • Providers/Onboarding: add Volcano Engine (Doubao) and BytePlus providers/models (including coding variants), wire onboarding auth choices for interactive + non-interactive flows, and align docs to volcengine-api-key. (#7967) Thanks @funmore123.
  • +
  • Channels/CLI: add per-account/channel defaultTo outbound routing fallback so openclaw agent --deliver can send without explicit --reply-to when a default target is configured. (#16985) Thanks @KirillShchetinin.
  • +
  • Channels: allow per-channel model overrides via channels.modelByChannel and note them in /status. Thanks @thewilloftheshadow.
  • +
  • Telegram/Streaming: simplify preview streaming config to channels.telegram.streaming (boolean), auto-map legacy streamMode values, and remove block-vs-partial preview branching. (#22012) thanks @obviyus.
  • +
  • Discord/Streaming: add stream preview mode for live draft replies with partial/block options and configurable chunking. Thanks @thewilloftheshadow. Inspiration @neoagentic-ship-it.
  • +
  • Discord/Telegram: add configurable lifecycle status reactions for queued/thinking/tool/done/error phases with a shared controller and emoji/timing overrides. Thanks @wolly-tundracube and @thewilloftheshadow.
  • +
  • Discord/Voice: add voice channel join/leave/status via /vc, plus auto-join configuration for realtime voice conversations. Thanks @thewilloftheshadow.
  • +
  • Discord: add configurable ephemeral defaults for slash-command responses. (#16563) Thanks @wei.
  • +
  • Discord: support updating forum available_tags via channel edit actions for forum tag management. (#12070) Thanks @xiaoyaner0201.
  • +
  • Discord: include channel topics in trusted inbound metadata on new sessions. Thanks @thewilloftheshadow.
  • +
  • Discord/Subagents: add thread-bound subagent sessions on Discord with per-thread focus/list controls and thread-bound continuation routing for spawned helper agents. (#21805) Thanks @onutc.
  • +
  • iOS/Chat: clean chat UI noise by stripping inbound untrusted metadata/timestamp prefixes, formatting tool outputs into concise summaries/errors, compacting the composer while typing, and supporting tap-to-dismiss keyboard in chat view. (#22122) thanks @mbelinky.
  • +
  • iOS/Watch: bridge mirrored watch prompt notification actions into iOS quick-reply handling, including queued action handoff until app model initialization. (#22123) thanks @mbelinky.
  • +
  • iOS/Gateway: stabilize background wake and reconnect behavior with background reconnect suppression/lease windows, BGAppRefresh wake fallback, location wake hook throttling, and APNs wake retry+nudge instrumentation. (#21226) thanks @mbelinky.
  • +
  • Auto-reply/UI: add model fallback lifecycle visibility in verbose logs, /status active-model context with fallback reason, and cohesive WebUI fallback indicators. (#20704) Thanks @joshavant.
  • +
  • MSTeams: dedupe sent-message cache storage by removing duplicate per-message Set storage and using timestamps Map keys as the single membership source. (#22514) Thanks @TaKO8Ki.
  • +
  • Agents/Subagents: default subagent spawn depth now uses shared maxSpawnDepth=2, enabling depth-1 orchestrator spawning by default while keeping depth policy checks consistent across spawn and prompt paths. (#22223) Thanks @tyler6204.
  • +
  • Security/Agents: make owner-ID obfuscation use a dedicated HMAC secret from configuration (ownerDisplaySecret) and update hashing behavior so obfuscation is decoupled from gateway token handling for improved control. (#7343) Thanks @vincentkoc.
  • +
  • Security/Infra: switch gateway lock and tool-call synthetic IDs from SHA-1 to SHA-256 with unchanged truncation length to strengthen hash basis while keeping deterministic behavior and lock key format. (#7343) Thanks @vincentkoc.
  • +
  • Dependencies/Tooling: add non-blocking dead-code scans in CI via Knip/ts-prune/ts-unused-exports to surface unused dependencies and exports earlier. (#22468) Thanks @vincentkoc.
  • +
  • Dependencies/Unused Dependencies: remove or scope unused root and extension deps (@larksuiteoapi/node-sdk, signal-utils, ollama, lit, @lit/context, @lit-labs/signals, @microsoft/agents-hosting-express, @microsoft/agents-hosting-extensions-teams, and plugin-local openclaw devDeps in extensions/open-prose, extensions/lobster, and extensions/llm-task). (#22471, #22495) Thanks @vincentkoc.
  • +
  • Dependencies/A2UI: harden dependency resolution after root cleanup (resolve lit, @lit/context, @lit-labs/signals, and signal-utils from workspace/root) and simplify bundling fallback behavior, including pnpm dlx rolldown compatibility. (#22481, #22507) Thanks @vincentkoc.

Fixes

    -
  • Outbound: add a write-ahead delivery queue with crash-recovery retries to prevent lost outbound messages after gateway restarts. (#15636) Thanks @nabbilkhan, @thewilloftheshadow.
  • -
  • Auto-reply/Threading: auto-inject implicit reply threading so replyToMode works without requiring model-emitted [[reply_to_current]], while preserving replyToMode: "off" behavior for implicit Slack replies and keeping block-streaming chunk coalescing stable under replyToMode: "first". (#14976) Thanks @Diaspar4u.
  • -
  • Outbound/Threading: pass replyTo and threadId from message send tool actions through the core outbound send path to channel adapters, preserving thread/reply routing. (#14948) Thanks @mcaxtr.
  • -
  • Auto-reply/Media: allow image-only inbound messages (no caption) to reach the agent instead of short-circuiting as empty text, and preserve thread context in queued/followup prompt bodies for media-only runs. (#11916) Thanks @arosstale.
  • -
  • Discord: route autoThread replies to existing threads instead of the root channel. (#8302) Thanks @gavinbmoore, @thewilloftheshadow.
  • -
  • Web UI: add img to DOMPurify allowed tags and src/alt to allowed attributes so markdown images render in webchat instead of being stripped. (#15437) Thanks @lailoo.
  • -
  • Telegram/Matrix: treat MP3 and M4A (including audio/mp4) as voice-compatible for asVoice routing, and keep WAV/AAC falling back to regular audio sends. (#15438) Thanks @azade-c.
  • -
  • WhatsApp: preserve outbound document filenames for web-session document sends instead of always sending "file". (#15594) Thanks @TsekaLuk.
  • -
  • Telegram: cap bot menu registration to Telegram's 100-command limit with an overflow warning while keeping typed hidden commands available. (#15844) Thanks @battman21.
  • -
  • Telegram: scope skill commands to the resolved agent for default accounts so setMyCommands no longer triggers BOT_COMMANDS_TOO_MUCH when multiple agents are configured. (#15599)
  • -
  • Discord: avoid misrouting numeric guild allowlist entries to /channels/ by prefixing guild-only inputs with guild: during resolution. (#12326) Thanks @headswim.
  • -
  • MS Teams: preserve parsed mention entities/text when appending OneDrive fallback file links, and accept broader real-world Teams mention ID formats (29:..., 8:orgid:...) while still rejecting placeholder patterns. (#15436) Thanks @hyojin.
  • -
  • Media: classify text/* MIME types as documents in media-kind routing so text attachments are no longer treated as unknown. (#12237) Thanks @arosstale.
  • -
  • Inbound/Web UI: preserve literal \n sequences when normalizing inbound text so Windows paths like C:\\Work\\nxxx\\README.md are not corrupted. (#11547) Thanks @mcaxtr.
  • -
  • TUI/Streaming: preserve richer streamed assistant text when final payload drops pre-tool-call text blocks, while keeping non-empty final payload authoritative for plain-text updates. (#15452) Thanks @TsekaLuk.
  • -
  • Providers/MiniMax: switch implicit MiniMax API-key provider from openai-completions to anthropic-messages with the correct Anthropic-compatible base URL, fixing invalid role: developer (2013) errors on MiniMax M2.5. (#15275) Thanks @lailoo.
  • -
  • Ollama/Agents: use resolved model/provider base URLs for native /api/chat streaming (including aliased providers), normalize /v1 endpoints, and forward abort + maxTokens stream options for reliable cancellation and token caps. (#11853) Thanks @BrokenFinger98.
  • -
  • OpenAI Codex/Spark: implement end-to-end gpt-5.3-codex-spark support across fallback/thinking/model resolution and models list forward-compat visibility. (#14990, #15174) Thanks @L-U-C-K-Y, @loiie45e.
  • -
  • Agents/Codex: allow gpt-5.3-codex-spark in forward-compat fallback, live model filtering, and thinking presets, and fix model-picker recognition for spark. (#14990) Thanks @L-U-C-K-Y.
  • -
  • Models/Codex: resolve configured openai-codex/gpt-5.3-codex-spark through forward-compat fallback during models list, so it is not incorrectly tagged as missing when runtime resolution succeeds. (#15174) Thanks @loiie45e.
  • -
  • OpenAI Codex/Auth: bridge OpenClaw OAuth profiles into pi auth.json so model discovery and models-list registry resolution can use Codex OAuth credentials. (#15184) Thanks @loiie45e.
  • -
  • Auth/OpenAI Codex: share OAuth login handling across onboarding and models auth login --provider openai-codex, keep onboarding alive when OAuth fails, and surface a direct OAuth help note instead of terminating the wizard. (#15406, follow-up to #14552) Thanks @zhiluo20.
  • -
  • Onboarding/Providers: add vLLM as an onboarding provider with model discovery, auth profile wiring, and non-interactive auth-choice validation. (#12577) Thanks @gejifeng.
  • -
  • Onboarding/Providers: preserve Hugging Face auth intent in auth-choice remapping (tokenProvider=huggingface with authChoice=apiKey) and skip env-override prompts when an explicit token is provided. (#13472) Thanks @Josephrp.
  • -
  • Onboarding/CLI: restore terminal state without resuming paused stdin, so onboarding exits cleanly after choosing Web UI and the installer returns instead of appearing stuck.
  • -
  • Signal/Install: auto-install signal-cli via Homebrew on non-x64 Linux architectures, avoiding x86_64 native binary Exec format error failures on arm64/arm hosts. (#15443) Thanks @jogvan-k.
  • -
  • macOS Voice Wake: fix a crash in trigger trimming for CJK/Unicode transcripts by matching and slicing on original-string ranges instead of transformed-string indices. (#11052) Thanks @Flash-LHR.
  • -
  • Mattermost (plugin): retry websocket monitor connections with exponential backoff and abort-aware teardown so transient connect failures no longer permanently stop monitoring. (#14962) Thanks @mcaxtr.
  • -
  • Discord/Agents: apply channel/group historyLimit during embedded-runner history compaction to prevent long-running channel sessions from bypassing truncation and overflowing context windows. (#11224) Thanks @shadril238.
  • -
  • Outbound targets: fail closed for WhatsApp/Twitch/Google Chat fallback paths so invalid or missing targets are dropped instead of rerouted, and align resolver hints with strict target requirements. (#13578) Thanks @mcaxtr.
  • -
  • Gateway/Restart: clear stale command-queue and heartbeat wake runtime state after SIGUSR1 in-process restarts to prevent zombie gateway behavior where queued work stops draining. (#15195) Thanks @joeykrug.
  • -
  • Heartbeat: prevent scheduler silent-death races during runner reloads, preserve retry cooldown backoff under wake bursts, and prioritize user/action wake causes over interval/retry reasons when coalescing. (#15108) Thanks @joeykrug.
  • -
  • Heartbeat: allow explicit wake (wake) and hook wake (hook:*) reasons to run even when HEARTBEAT.md is effectively empty so queued system events are processed. (#14527) Thanks @arosstale.
  • -
  • Auto-reply/Heartbeat: strip sentence-ending HEARTBEAT_OK tokens even when followed by up to 4 punctuation characters, while preserving surrounding sentence punctuation. (#15847) Thanks @Spacefish.
  • -
  • Agents/Heartbeat: stop auto-creating HEARTBEAT.md during workspace bootstrap so missing files continue to run heartbeat as documented. (#11766) Thanks @shadril238.
  • -
  • Sessions/Agents: pass agentId when resolving existing transcript paths in reply runs so non-default agents and heartbeat/chat handlers no longer fail with Session file path must be within sessions directory. (#15141) Thanks @Goldenmonstew.
  • -
  • Sessions/Agents: pass agentId through status and usage transcript-resolution paths (auto-reply, gateway usage APIs, and session cost/log loaders) so non-default agents can resolve absolute session files without path-validation failures. (#15103) Thanks @jalehman.
  • -
  • Sessions: archive previous transcript files on /new and /reset session resets (including gateway sessions.reset) so stale transcripts do not accumulate on disk. (#14869) Thanks @mcaxtr.
  • -
  • Status/Sessions: stop clamping derived totalTokens to context-window size, keep prompt-token snapshots wired through session accounting, and surface context usage as unknown when fresh snapshot data is missing to avoid false 100% reports. (#15114) Thanks @echoVic.
  • -
  • CLI/Completion: route plugin-load logs to stderr and write generated completion scripts directly to stdout to avoid source <(openclaw completion ...) corruption. (#15481) Thanks @arosstale.
  • -
  • CLI: lazily load outbound provider dependencies and remove forced success-path exits so commands terminate naturally without killing intentional long-running foreground actions. (#12906) Thanks @DrCrinkle.
  • -
  • Security/Gateway + ACP: block high-risk tools (sessions_spawn, sessions_send, gateway, whatsapp_login) from HTTP /tools/invoke by default with gateway.tools.{allow,deny} overrides, and harden ACP permission selection to fail closed when tool identity/options are ambiguous while supporting allow_always/reject_always. (#15390) Thanks @aether-ai-agent.
  • -
  • Security/Gateway: breaking default-behavior change - canvas IP-based auth fallback now only accepts machine-scoped addresses (RFC1918, link-local, ULA IPv6, CGNAT); public-source IP matches now require bearer token auth. (#14661) Thanks @sumleo.
  • -
  • Security/Link understanding: block loopback/internal host patterns and private/mapped IPv6 addresses in extracted URL handling to close SSRF bypasses in link CLI flows. (#15604) Thanks @AI-Reviewer-QS.
  • -
  • Security/Browser: constrain POST /trace/stop, POST /wait/download, and POST /download output paths to OpenClaw temp roots and reject traversal/escape paths.
  • -
  • Security/Canvas: serve A2UI assets via the shared safe-open path (openFileWithinRoot) to close traversal/TOCTOU gaps, with traversal and symlink regression coverage. (#10525) Thanks @abdelsfane.
  • -
  • Security/WhatsApp: enforce 0o600 on creds.json and creds.json.bak on save/backup/restore paths to reduce credential file exposure. (#10529) Thanks @abdelsfane.
  • -
  • Security/Gateway: sanitize and truncate untrusted WebSocket header values in pre-handshake close logs to reduce log-poisoning risk. Thanks @thewilloftheshadow.
  • -
  • Security/Audit: add misconfiguration checks for sandbox Docker config with sandbox mode off, ineffective gateway.nodes.denyCommands entries, global minimal tool-profile overrides by agent profiles, and permissive extension-plugin tool reachability.
  • -
  • Security/Audit: distinguish external webhooks (hooks.enabled) from internal hooks (hooks.internal.enabled) in attack-surface summaries to avoid false exposure signals when only internal hooks are enabled. (#13474) Thanks @mcaxtr.
  • -
  • Security/Onboarding: clarify multi-user DM isolation remediation with explicit openclaw config set session.dmScope ... commands in security audit, doctor security, and channel onboarding guidance. (#13129) Thanks @VintLin.
  • -
  • Agents/Nodes: harden node exec approval decision handling in the nodes tool run path by failing closed on unexpected approval decisions, and add regression coverage for approval-required retry/deny/timeout flows. (#4726) Thanks @rmorse.
  • -
  • Android/Nodes: harden app.update by requiring HTTPS and gateway-host URL matching plus SHA-256 verification, stream URL camera downloads to disk with size guards to avoid memory spikes, and stop signing release builds with debug keys. (#13541) Thanks @smartprogrammer93.
  • -
  • Routing: enforce strict binding-scope matching across peer/guild/team/roles so peer-scoped Discord/Slack bindings no longer match unrelated guild/team contexts or fallback tiers. (#15274) Thanks @lailoo.
  • -
  • Exec/Allowlist: allow multiline heredoc bodies (<<, <<-) while keeping multiline non-heredoc shell commands blocked, so exec approval parsing permits heredoc input safely without allowing general newline command chaining. (#13811) Thanks @mcaxtr.
  • -
  • Config: preserve ${VAR} env references when writing config files so openclaw config set/apply/patch does not persist secrets to disk. Thanks @thewilloftheshadow.
  • -
  • Config: remove a cross-request env-snapshot race in config writes by carrying read-time env context into write calls per request, preserving ${VAR} refs safely under concurrent gateway config mutations. (#11560) Thanks @akoscz.
  • -
  • Config: log overwrite audit entries (path, backup target, and hash transition) whenever an existing config file is replaced, improving traceability for unexpected config clobbers.
  • -
  • Config: keep legacy audio transcription migration strict by rejecting non-string/unsafe command tokens while still migrating valid custom script executables. (#5042) Thanks @shayan919293.
  • -
  • Config: accept $schema key in config file so JSON Schema editor tooling works without validation errors. (#14998)
  • -
  • Gateway/Tools Invoke: sanitize /tools/invoke execution failures while preserving 400 for tool input errors and returning 500 for unexpected runtime failures, with regression coverage and docs updates. (#13185) Thanks @davidrudduck.
  • -
  • Gateway/Hooks: preserve 408 for hook request-body timeout responses while keeping bounded auth-failure cache eviction behavior, with timeout-status regression coverage. (#15848) Thanks @AI-Reviewer-QS.
  • -
  • Plugins/Hooks: fire before_tool_call hook exactly once per tool invocation in embedded runs by removing duplicate dispatch paths while preserving parameter mutation semantics. (#15635) Thanks @lailoo.
  • -
  • Agents/Transcript policy: sanitize OpenAI/Codex tool-call ids during transcript policy normalization to prevent invalid tool-call identifiers from propagating into session history. (#15279) Thanks @divisonofficer.
  • -
  • Agents/Image tool: cap image-analysis completion maxTokens by model capability (min(4096, model.maxTokens)) to avoid over-limit provider failures while still preventing truncation. (#11770) Thanks @detecti1.
  • -
  • Agents/Compaction: centralize exec default resolution in the shared tool factory so per-agent tools.exec overrides (host/security/ask/node and related defaults) persist across compaction retries. (#15833) Thanks @napetrov.
  • -
  • Gateway/Agents: stop injecting a phantom main agent into gateway agent listings when agents.list explicitly excludes it. (#11450) Thanks @arosstale.
  • -
  • Process/Exec: avoid shell execution for .exe commands on Windows so env overrides work reliably in runCommandWithTimeout. Thanks @thewilloftheshadow.
  • -
  • Daemon/Windows: preserve literal backslashes in gateway.cmd command parsing so drive and UNC paths are not corrupted in runtime checks and doctor entrypoint comparisons. (#15642) Thanks @arosstale.
  • -
  • Sandbox: pass configured sandbox.docker.env variables to sandbox containers at docker create time. (#15138) Thanks @stevebot-alive.
  • -
  • Voice Call: route webhook runtime event handling through shared manager event logic so rejected inbound hangups are idempotent in production, with regression tests for duplicate reject events and provider-call-ID remapping parity. (#15892) Thanks @dcantu96.
  • -
  • Cron: add regression coverage for announce-mode isolated jobs so runs that already report delivered: true do not enqueue duplicate main-session relays, including delivery configs where mode is omitted and defaults to announce. (#15737) Thanks @brandonwise.
  • -
  • Cron: honor deleteAfterRun in isolated announce delivery by mapping it to subagent announce cleanup mode, so cron run sessions configured for deletion are removed after completion. (#15368) Thanks @arosstale.
  • -
  • Web tools/web_fetch: prefer text/markdown responses for Cloudflare Markdown for Agents, add cf-markdown extraction for markdown bodies, and redact fetched URLs in x-markdown-tokens debug logs to avoid leaking raw paths/query params. (#15376) Thanks @Yaxuan42.
  • -
  • Clawdock: avoid Zsh readonly variable collisions in helper scripts. (#15501) Thanks @nkelner.
  • -
  • Memory: switch default local embedding model to the QAT embeddinggemma-300m-qat-Q8_0 variant for better quality at the same footprint. (#15429) Thanks @azade-c.
  • -
  • Docs/Mermaid: remove hardcoded Mermaid init theme blocks from four docs diagrams so dark mode inherits readable theme defaults. (#15157) Thanks @heytulsiprasad.
  • +
  • Security/Agents: cap embedded Pi runner outer retry loop with a higher profile-aware dynamic limit (32-160 attempts) and return an explicit retry_limit error payload when retries never converge, preventing unbounded internal retry cycles (GHSA-76m6-pj3w-v7mf).
  • +
  • Telegram: detect duplicate bot-token ownership across Telegram accounts at startup/status time, mark secondary accounts as not configured with an explicit fix message, and block duplicate account startup before polling to avoid endless getUpdates conflict loops.
  • +
  • Agents/Tool images: include source filenames in agents/tool-images resize logs so compression events can be traced back to specific files.
  • +
  • Providers/OAuth: harden Qwen and Chutes refresh handling by validating refresh response expiry values and preserving prior refresh tokens when providers return empty refresh token fields, with regression coverage for empty-token responses.
  • +
  • Models/Kimi-Coding: add missing implicit provider template for kimi-coding with correct anthropic-messages API type and base URL, fixing 403 errors when using Kimi for Coding. (#22409)
  • +
  • Auto-reply/Tools: forward senderIsOwner through embedded queued/followup runner params so owner-only tools remain available for authorized senders. (#22296) thanks @hcoj.
  • +
  • Discord: restore model picker back navigation when a provider is missing and document the Discord picker flow. (#21458) Thanks @pejmanjohn and @thewilloftheshadow.
  • +
  • Memory/QMD: respect per-agent memorySearch.enabled=false during gateway QMD startup initialization, split multi-collection QMD searches into per-collection queries (search/vsearch/query) to avoid sparse-term drops, prefer collection-hinted doc resolution to avoid stale-hash collisions, retry boot updates on transient lock/timeout failures, skip qmd embed in BM25-only search mode (including memory index --force), and serialize embed runs globally with failure backoff to prevent CPU storms on multi-agent hosts. (#20581, #21590, #20513, #20001, #21266, #21583, #20346, #19493) Thanks @danielrevivo, @zanderkrause, @sunyan034-cmd, @tilleulenspiegel, @dae-oss, @adamlongcreativellc, @jonathanadams96, and @kiliansitel.
  • +
  • Memory/Builtin: prevent automatic sync races with manager shutdown by skipping post-close sync starts and waiting for in-flight sync before closing SQLite, so onSearch/onSessionStart no longer fail with database is not open in ephemeral CLI flows. (#20556, #7464) Thanks @FuzzyTG and @henrybottter.
  • +
  • Providers/Copilot: drop persisted assistant thinking blocks for Claude models (while preserving turn structure/tool blocks) so follow-up requests no longer fail on invalid thinkingSignature payloads. (#19459) Thanks @jackheuberger.
  • +
  • Providers/Copilot: add claude-sonnet-4.6 and claude-sonnet-4.5 to the default GitHub Copilot model catalog and add coverage for model-list/definition helpers. (#20270, fixes #20091) Thanks @Clawborn.
  • +
  • Auto-reply/WebChat: avoid defaulting inbound runtime channel labels to unrelated providers (for example whatsapp) for webchat sessions so channel-specific formatting guidance stays accurate. (#21534) Thanks @lbo728.
  • +
  • Status: include persisted cacheRead/cacheWrite in session summaries so compact /status output consistently shows cache hit percentages from real session data.
  • +
  • Heartbeat/Cron: restore interval heartbeat behavior so missing HEARTBEAT.md no longer suppresses runs (only effectively empty files skip), preserving prompt-driven and tagged-cron execution paths.
  • +
  • WhatsApp/Cron/Heartbeat: enforce allowlisted routing for implicit scheduled/system delivery by merging pairing-store + configured allowFrom recipients, selecting authorized recipients when last-route context points to a non-allowlisted chat, and preventing heartbeat fan-out to recent unauthorized chats.
  • +
  • Heartbeat/Active hours: constrain active-hours 24 sentinel parsing to 24:00 in time validation so invalid values like 24:30 are rejected early. (#21410) thanks @adhitShet.
  • +
  • Heartbeat: treat activeHours windows with identical start/end times as zero-width (always outside the window) instead of always-active. (#21408) thanks @adhitShet.
  • +
  • CLI/Pairing: default pairing list and pairing approve to the sole available pairing channel when omitted, so TUI-only setups can recover from pairing required without guessing channel arguments. (#21527) Thanks @losts1.
  • +
  • TUI/Pairing: show explicit pairing-required recovery guidance after gateway disconnects that return pairing required, including approval steps to unblock quickstart TUI hatching on fresh installs. (#21841) Thanks @nicolinux.
  • +
  • TUI/Input: suppress duplicate backspace events arriving in the same input burst window so SSH sessions no longer delete two characters per backspace press in the composer. (#19318) Thanks @eheimer.
  • +
  • TUI/Heartbeat: suppress heartbeat ACK/prompt noise in chat streaming when showOk is disabled, while still preserving non-ACK heartbeat alerts in final output. (#20228) Thanks @bhalliburton.
  • +
  • TUI/History: cap chat-log component growth and prune stale render nodes/references so large default history loads no longer overflow render recursion with RangeError: Maximum call stack size exceeded. (#18068) Thanks @JaniJegoroff.
  • +
  • Memory/QMD: diversify mixed-source search ranking when both session and memory collections are present so session transcript hits no longer crowd out durable memory-file matches in top results. (#19913) Thanks @alextempr.
  • +
  • Memory/Tools: return explicit unavailable warnings/actions from memory_search when embedding/provider failures occur (including quota exhaustion), so disabled memory does not look like an empty recall result. (#21894) Thanks @XBS9.
  • +
  • Session/Startup: require the /new and /reset greeting path to run Session Startup file-reading instructions before responding, so daily memory startup context is not skipped on fresh-session greetings. (#22338) Thanks @armstrong-pv.
  • +
  • Auth/Onboarding: align OAuth profile-id config mapping with stored credential IDs for OpenAI Codex and Chutes flows, preventing provider:default mismatches when OAuth returns email-scoped credentials. (#12692) thanks @mudrii.
  • +
  • Provider/HTTP: treat HTTP 503 as failover-eligible for LLM provider errors. (#21086) Thanks @Protocol-zero-0.
  • +
  • Slack: pass recipient_team_id / recipient_user_id through Slack native streaming calls so chat.startStream/appendStream/stopStream work reliably across DMs and Slack Connect setups, and disable block streaming when native streaming is active. (#20988) Thanks @Dithilli. Earlier recipient-ID groundwork was contributed in #20377 by @AsserAl1012.
  • +
  • CLI/Config: add canonical --strict-json parsing for config set and keep --json as a legacy alias to reduce help/behavior drift. (#21332) thanks @adhitShet.
  • +
  • CLI: keep openclaw -v as a root-only version alias so subcommand -v, --verbose flags (for example ACP/hooks/skills) are no longer intercepted globally. (#21303) thanks @adhitShet.
  • +
  • Memory: return empty snippets when memory_get/QMD read files that have not been created yet, and harden memory indexing/session helpers against ENOENT races so missing Markdown no longer crashes tools. (#20680) Thanks @pahdo.
  • +
  • Telegram/Streaming: always clean up draft previews even when dispatch throws before fallback handling, preventing orphaned preview messages during failed runs. (#19041) thanks @mudrii.
  • +
  • Telegram/Streaming: split reasoning and answer draft preview lanes to prevent cross-lane overwrites, and ignore literal tags inside inline/fenced code snippets so sample markup is not misrouted as reasoning. (#20774) Thanks @obviyus.
  • +
  • Telegram/Streaming: restore 30-char first-preview debounce and scope NO_REPLY prefix suppression to partial sentinel fragments so normal No... text is not filtered. (#22613) thanks @obviyus.
  • +
  • Telegram/Status reactions: refresh stall timers on repeated phase updates and honor ack-reaction scope when lifecycle reactions are enabled, preventing false stall emojis and unwanted group reactions. Thanks @wolly-tundracube and @thewilloftheshadow.
  • +
  • Telegram/Status reactions: keep lifecycle reactions active when available-reactions lookup fails by falling back to unrestricted variant selection instead of suppressing reaction updates. (#22380) thanks @obviyus.
  • +
  • Discord/Streaming: apply replyToMode: first only to the first Discord chunk so block-streamed replies do not spam mention pings. (#20726) Thanks @thewilloftheshadow for the report.
  • +
  • Discord/Components: map DM channel targets back to user-scoped component sessions so button/select interactions stay in the main DM session. Thanks @thewilloftheshadow.
  • +
  • Discord/Allowlist: lazy-load guild lists when resolving Discord user allowlists so ID-only entries resolve even if guild fetch fails. (#20208) Thanks @zhangjunmengyang.
  • +
  • Discord/Gateway: handle close code 4014 (missing privileged gateway intents) without crashing the gateway. Thanks @thewilloftheshadow.
  • +
  • Discord: ingest inbound stickers as media so sticker-only messages and forwarded stickers are visible to agents. Thanks @thewilloftheshadow.
  • +
  • Auto-reply/Runner: emit onAgentRunStart only after agent lifecycle or tool activity begins (and only once per run), so fallback preflight errors no longer mark runs as started. (#21165) Thanks @shakkernerd.
  • +
  • Auto-reply/Tool results: serialize tool-result delivery and keep the delivery chain progressing after individual failures so concurrent tool outputs preserve user-visible ordering. (#21231) thanks @ahdernasr.
  • +
  • Auto-reply/Prompt caching: restore prefix-cache stability by keeping inbound system metadata session-stable and moving per-message IDs (message_id, message_id_full, reply_to_id, sender_id) into untrusted conversation context. (#20597) Thanks @anisoptera.
  • +
  • iOS/Watch: add actionable watch approval/reject controls and quick-reply actions so watch-originated approvals and responses can be sent directly from notification flows. (#21996) Thanks @mbelinky.
  • +
  • iOS/Watch: refresh iOS and watch app icon assets with the lobster icon set to keep phone/watch branding aligned. (#21997) Thanks @mbelinky.
  • +
  • CLI/Onboarding: fix Anthropic-compatible custom provider verification by normalizing base URLs to avoid duplicate /v1 paths during setup checks. (#21336) Thanks @17jmumford.
  • +
  • iOS/Gateway/Tools: prefer uniquely connected node matches when duplicate display names exist, surface actionable nodes invoke pairing-required guidance with request IDs, and refresh active iOS gateway registration after location-capability setting changes so capability updates apply immediately. (#22120) thanks @mbelinky.
  • +
  • Gateway/Auth: require gateway.trustedProxies to include a loopback proxy address when auth.mode="trusted-proxy" and bind="loopback", preventing same-host proxy misconfiguration from silently blocking auth. (#22082, follow-up to #20097) thanks @mbelinky.
  • +
  • Gateway/Auth: allow trusted-proxy mode with loopback bind for same-host reverse-proxy deployments, while still requiring configured gateway.trustedProxies. (#20097) thanks @xinhuagu.
  • +
  • Gateway/Auth: allow authenticated clients across roles/scopes to call health while preserving role and scope enforcement for non-health methods. (#19699) thanks @Nachx639.
  • +
  • Gateway/Hooks: include transform export name in hook-transform cache keys so distinct exports from the same module do not reuse the wrong cached transform function. (#13855) thanks @mcaxtr.
  • +
  • Gateway/Control UI: return 404 for missing static-asset paths instead of serving SPA fallback HTML, while preserving client-route fallback behavior for extensionless and non-asset dotted paths. (#12060) thanks @mcaxtr.
  • +
  • Gateway/Pairing: prevent device-token rotate scope escalation by enforcing an approved-scope baseline, preserving approved scopes across metadata updates, and rejecting rotate requests that exceed approved role scope implications. (#20703) thanks @coygeek.
  • +
  • Gateway/Pairing: clear persisted paired-device state when the gateway client closes with device token mismatch (1008) so reconnect flows can cleanly re-enter pairing. (#22071) Thanks @mbelinky.
  • +
  • Gateway/Config: allow gateway.customBindHost in strict config validation when gateway.bind="custom" so valid custom bind-host configurations no longer fail startup. (#20318, fixes #20289) Thanks @MisterGuy420.
  • +
  • Gateway/Pairing: tolerate legacy paired devices missing roles/scopes metadata in websocket upgrade checks and backfill metadata on reconnect. (#21447, fixes #21236) Thanks @joshavant.
  • +
  • Gateway/Pairing/CLI: align read-scope compatibility in pairing/device-token checks and add local openclaw devices fallback recovery for loopback pairing required deadlocks, with explicit fallback notice to unblock approval bootstrap flows. (#21616) Thanks @shakkernerd.
  • +
  • Cron: honor cron.maxConcurrentRuns in the timer loop so due jobs can execute up to the configured parallelism instead of always running serially. (#11595) Thanks @Takhoffman.
  • +
  • Agents/Compaction: restore embedded compaction safeguard/context-pruning extension loading in production by wiring bundled extension factories into the resource loader instead of runtime file-path resolution. (#22349) Thanks @Glucksberg.
  • +
  • Agents/Subagents: restore announce-chain delivery to agent injection, defer nested announce output until descendant follow-up content is ready, and prevent descendant deferrals from consuming announce retry budget so deep chains do not drop final completions. (#22223) Thanks @tyler6204.
  • +
  • Agents/System Prompt: label allowlisted senders as authorized senders to avoid implying ownership. Thanks @thewilloftheshadow.
  • +
  • Agents/Tool display: fix exec cwd suffix inference so pushd ... && popd ... && does not keep stale (in ) context in summaries. (#21925) Thanks @Lukavyi.
  • +
  • Tools/web_search: handle xAI Responses API payloads that emit top-level output_text blocks (without a message wrapper) so Grok web_search no longer returns No response for those results. (#20508) Thanks @echoVic.
  • +
  • Agents/Failover: treat non-default override runs as direct fallback-to-configured-primary (skip configured fallback chain), normalize default-model detection for provider casing/whitespace, and add regression coverage for override/auth error paths. (#18820) Thanks @Glucksberg.
  • +
  • Docker/Build: include ownerDisplay in CommandsSchema object-level defaults so Docker pnpm build no longer fails with TS2769 during plugin SDK d.ts generation. (#22558) Thanks @obviyus.
  • +
  • Docker/Browser: install Playwright Chromium into /home/node/.cache/ms-playwright and set node:node ownership so browser binaries are available to the runtime user in browser-enabled images. (#22585) thanks @obviyus.
  • +
  • Hooks/Session memory: trigger bundled session-memory persistence on both /new and /reset so reset flows no longer skip markdown transcript capture before archival. (#21382) Thanks @mofesolapaul.
  • +
  • Dependencies/Agents: bump embedded Pi SDK packages (@mariozechner/pi-agent-core, @mariozechner/pi-ai, @mariozechner/pi-coding-agent, @mariozechner/pi-tui) to 0.54.0. (#21578) Thanks @Takhoffman.
  • +
  • Config/Agents: expose Pi compaction tuning values agents.defaults.compaction.reserveTokens and agents.defaults.compaction.keepRecentTokens in config schema/types and apply them in embedded Pi runner settings overrides with floor enforcement via reserveTokensFloor. (#21568) Thanks @Takhoffman.
  • +
  • Docker: pin base images to SHA256 digests in Docker builds to prevent mutable tag drift. (#7734) Thanks @coygeek.
  • +
  • Docker: run build steps as the node user and use COPY --chown to avoid recursive ownership changes, trimming image size and layer churn. Thanks @huntharo.
  • +
  • Config/Memory: restore schema help/label metadata for hybrid mmr and temporalDecay settings so configuration surfaces show correct names and guidance. (#18786) Thanks @rodrigouroz.
  • +
  • Skills/SonosCLI: add troubleshooting guidance for sonos discover failures on macOS direct mode (sendto: no route to host) and sandbox network restrictions (bind: operation not permitted). (#21316) Thanks @huntharo.
  • +
  • macOS/Build: default release packaging to BUNDLE_ID=ai.openclaw.mac in scripts/package-mac-dist.sh, so Sparkle feed URL is retained and auto-update no longer fails with an empty appcast feed. (#19750) thanks @loganprit.
  • +
  • Signal/Outbound: preserve case for Base64 group IDs during outbound target normalization so cross-context routing and policy checks no longer break when group IDs include uppercase characters. (#5578) Thanks @heyhudson.
  • +
  • Anthropic/Agents: preserve required pi-ai default OAuth beta headers when context1m injects anthropic-beta, preventing 401 auth failures for sk-ant-oat-* tokens. (#19789, fixes #19769) Thanks @minupla.
  • +
  • Security/Exec: block unquoted heredoc body expansion tokens in shell allowlist analysis, reject unterminated heredocs, and require explicit approval for allowlisted heredoc execution on gateway hosts to prevent heredoc substitution allowlist bypass. Thanks @torturado for reporting.
  • +
  • macOS/Security: evaluate system.run allowlists per shell segment in macOS node runtime and companion exec host (including chained shell operators), fail closed on shell/process substitution parsing, and require explicit approval on unsafe parse cases to prevent allowlist bypass via rawCommand chaining. Thanks @tdjackey for reporting.
  • +
  • WhatsApp/Security: enforce allowlist JID authorization for reaction actions so authenticated callers cannot target non-allowlisted chats by forging chatJid + valid messageId pairs. Thanks @aether-ai-agent for reporting.
  • +
  • ACP/Security: escape control and delimiter characters in ACP resource_link title/URI metadata before prompt interpolation to prevent metadata-driven prompt injection through resource links. Thanks @aether-ai-agent for reporting.
  • +
  • TTS/Security: make model-driven provider switching opt-in by default (messages.tts.modelOverrides.allowProvider=false unless explicitly enabled), while keeping voice/style overrides available, to reduce prompt-injection-driven provider hops and unexpected TTS cost escalation. Thanks @aether-ai-agent for reporting.
  • +
  • Security/Agents: keep overflow compaction retry budgeting global across tool-result truncation recovery so successful truncation cannot reset the overflow retry counter and amplify retry/cost cycles. Thanks @aether-ai-agent for reporting.
  • +
  • BlueBubbles/Security: require webhook token authentication for all BlueBubbles webhook requests (including loopback/proxied setups), removing passwordless webhook fallback behavior. Thanks @zpbrent.
  • +
  • iOS/Security: force https:// for non-loopback manual gateway hosts during iOS onboarding to block insecure remote transport URLs. (#21969) Thanks @mbelinky.
  • +
  • Gateway/Security: remove shared-IP fallback for canvas endpoints and require token or session capability for canvas access. Thanks @thewilloftheshadow.
  • +
  • Gateway/Security: require secure context and paired-device checks for Control UI auth even when gateway.controlUi.allowInsecureAuth is set, and align audit messaging with the hardened behavior. (#20684) Thanks @coygeek and @Vasco0x4 for reporting.
  • +
  • Gateway/Security: scope tokenless Tailscale forwarded-header auth to Control UI websocket auth only, so HTTP gateway routes still require token/password even on trusted hosts. Thanks @zpbrent for reporting.
  • +
  • Docker/Security: run E2E and install-sh test images as non-root by adding appuser directives. Thanks @thewilloftheshadow.
  • +
  • Skills/Security: sanitize skill env overrides to block unsafe runtime injection variables and only allow sensitive keys when declared in skill metadata, with warnings for suspicious values. Thanks @thewilloftheshadow.
  • +
  • Security/Commands: block prototype-key injection in runtime /debug overrides and require own-property checks for gated command flags (bash, config, debug) so inherited prototype values cannot enable privileged commands. Thanks @tdjackey for reporting.
  • +
  • Security/Browser: block non-network browser navigation protocols (including file:, data:, and javascript:) while preserving about:blank, preventing local file reads via browser tool navigation. Thanks @q1uf3ng for reporting.
  • +
  • Security/Exec: block shell startup-file env injection (BASH_ENV, ENV, BASH_FUNC_*, LD_*, DYLD_*) across config env ingestion, node-host inherited environment sanitization, and macOS exec host runtime to prevent pre-command execution from attacker-controlled environment variables. Thanks @tdjackey.
  • +
  • Security/Exec (Windows): canonicalize cmd.exe /c command text across validation, approval binding, and audit/event rendering to prevent trailing-argument approval mismatches in system.run. Thanks @tdjackey for reporting.
  • +
  • Security/Gateway/Hooks: block __proto__, constructor, and prototype traversal in webhook template path resolution to prevent prototype-chain payload data leakage in messageTemplate rendering. (#22213) Thanks @SleuthCo.
  • +
  • Security/OpenClawKit/UI: prevent injected inbound user context metadata blocks from leaking into chat history in TUI, webchat, and macOS surfaces by stripping all untrusted metadata prefixes at display boundaries. (#22142) Thanks @Mellowambience, @vincentkoc.
  • +
  • Security/OpenClawKit/UI: strip inbound metadata blocks from user messages in TUI rendering while preserving user-authored content. (#22345) Thanks @kansodata, @vincentkoc.
  • +
  • Security/OpenClawKit/UI: prevent inbound metadata leaks and reply-tag streaming artifacts in TUI rendering by stripping untrusted metadata prefixes at display boundaries. (#22346) Thanks @akramcodez, @vincentkoc.
  • +
  • Security/Agents: restrict local MEDIA tool attachments to core tools and the OpenClaw temp root to prevent untrusted MCP tool file exfiltration. Thanks @NucleiAv and @thewilloftheshadow.
  • +
  • Security/Net: strip sensitive headers (Authorization, Proxy-Authorization, Cookie, Cookie2) on cross-origin redirects in fetchWithSsrFGuard to prevent credential forwarding across origin boundaries. (#20313) Thanks @afurm.
  • +
  • Security/Systemd: reject CR/LF in systemd unit environment values and fix argument escaping so generated units cannot be injected with extra directives. Thanks @thewilloftheshadow.
  • +
  • Security/Tools: add per-wrapper random IDs to untrusted-content markers from wrapExternalContent/wrapWebContent, preventing marker spoofing from escaping content boundaries. (#19009) Thanks @Whoaa512.
  • +
  • Shared/Security: reject insecure deep links that use ws:// non-loopback gateway URLs to prevent plaintext remote websocket configuration. (#21970) Thanks @mbelinky.
  • +
  • macOS/Security: reject non-loopback ws:// remote gateway URLs in macOS remote config to block insecure plaintext websocket endpoints. (#21971) Thanks @mbelinky.
  • +
  • Browser/Security: block upload path symlink escapes so browser upload sources cannot traverse outside the allowed workspace via symlinked paths. (#21972) Thanks @mbelinky.
  • +
  • Security/Dependencies: bump transitive hono usage to 4.11.10 to incorporate timing-safe authentication comparison hardening for basicAuth/bearerAuth (GHSA-gq3j-xvxp-8hrf). Thanks @vincentkoc.
  • +
  • Security/Gateway: parse X-Forwarded-For with trust-preserving semantics when requests come from configured trusted proxies, preventing proxy-chain spoofing from influencing client IP classification and rate-limit identity. Thanks @AnthonyDiSanti and @vincentkoc.
  • +
  • Security/Sandbox: remove default --no-sandbox for the browser container entrypoint, add explicit opt-in via OPENCLAW_BROWSER_NO_SANDBOX / CLAWDBOT_BROWSER_NO_SANDBOX, and add security-audit checks for stale/missing sandbox browser Docker hash labels. Thanks @TerminalsandCoffee and @vincentkoc.
  • +
  • Security/Sandbox Browser: require VNC password auth for noVNC observer sessions in the sandbox browser entrypoint, plumb per-container noVNC passwords from runtime, and emit short-lived noVNC observer token URLs while keeping loopback-only host port publishing. Thanks @TerminalsandCoffee for reporting.
  • +
  • Security/Sandbox Browser: default browser sandbox containers to a dedicated Docker network (openclaw-sandbox-browser), add optional CDP ingress source-range restrictions, auto-create missing dedicated networks, and warn in openclaw security --audit when browser sandboxing runs on bridge without source-range limits. Thanks @TerminalsandCoffee for reporting.

View full changelog

]]>
- +
\ No newline at end of file diff --git a/apps/android/app/build.gradle.kts b/apps/android/app/build.gradle.kts index c96187b2dc547..b91b1e215376f 100644 --- a/apps/android/app/build.gradle.kts +++ b/apps/android/app/build.gradle.kts @@ -21,8 +21,8 @@ android { applicationId = "ai.openclaw.android" minSdk = 31 targetSdk = 36 - versionCode = 202602180 - versionName = "2026.2.18" + versionCode = 202602210 + versionName = "2026.2.21" ndk { // Support all major ABIs — native libs are tiny (~47 KB per ABI) abiFilters += listOf("armeabi-v7a", "arm64-v8a", "x86", "x86_64") diff --git a/apps/android/app/src/main/java/ai/openclaw/android/gateway/GatewaySession.kt b/apps/android/app/src/main/java/ai/openclaw/android/gateway/GatewaySession.kt index 091e735530d70..0f49541daff7a 100644 --- a/apps/android/app/src/main/java/ai/openclaw/android/gateway/GatewaySession.kt +++ b/apps/android/app/src/main/java/ai/openclaw/android/gateway/GatewaySession.kt @@ -178,7 +178,7 @@ class GatewaySession( private val connectDeferred = CompletableDeferred() private val closedDeferred = CompletableDeferred() private val isClosed = AtomicBoolean(false) - private val connectNonceDeferred = CompletableDeferred() + private val connectNonceDeferred = CompletableDeferred() private val client: OkHttpClient = buildClient() private var socket: WebSocket? = null private val loggerTag = "OpenClawGateway" @@ -296,7 +296,7 @@ class GatewaySession( } } - private suspend fun sendConnect(connectNonce: String?) { + private suspend fun sendConnect(connectNonce: String) { val identity = identityStore.loadOrCreate() val storedToken = deviceAuthStore.loadToken(identity.deviceId, options.role) val trimmedToken = token?.trim().orEmpty() @@ -332,7 +332,7 @@ class GatewaySession( private fun buildConnectParams( identity: DeviceIdentity, - connectNonce: String?, + connectNonce: String, authToken: String, authPassword: String?, ): JsonObject { @@ -385,9 +385,7 @@ class GatewaySession( put("publicKey", JsonPrimitive(publicKey)) put("signature", JsonPrimitive(signature)) put("signedAt", JsonPrimitive(signedAtMs)) - if (!connectNonce.isNullOrBlank()) { - put("nonce", JsonPrimitive(connectNonce)) - } + put("nonce", JsonPrimitive(connectNonce)) } } else { null @@ -447,8 +445,8 @@ class GatewaySession( frame["payload"]?.let { it.toString() } ?: frame["payloadJSON"].asStringOrNull() if (event == "connect.challenge") { val nonce = extractConnectNonce(payloadJson) - if (!connectNonceDeferred.isCompleted) { - connectNonceDeferred.complete(nonce) + if (!connectNonceDeferred.isCompleted && !nonce.isNullOrBlank()) { + connectNonceDeferred.complete(nonce.trim()) } return } @@ -459,12 +457,11 @@ class GatewaySession( onEvent(event, payloadJson) } - private suspend fun awaitConnectNonce(): String? { - if (isLoopbackHost(endpoint.host)) return null + private suspend fun awaitConnectNonce(): String { return try { withTimeout(2_000) { connectNonceDeferred.await() } - } catch (_: Throwable) { - null + } catch (err: Throwable) { + throw IllegalStateException("connect challenge timeout", err) } } @@ -595,14 +592,13 @@ class GatewaySession( scopes: List, signedAtMs: Long, token: String?, - nonce: String?, + nonce: String, ): String { val scopeString = scopes.joinToString(",") val authToken = token.orEmpty() - val version = if (nonce.isNullOrBlank()) "v1" else "v2" val parts = mutableListOf( - version, + "v2", deviceId, clientId, clientMode, @@ -610,10 +606,8 @@ class GatewaySession( scopeString, signedAtMs.toString(), authToken, + nonce, ) - if (!nonce.isNullOrBlank()) { - parts.add(nonce) - } return parts.joinToString("|") } diff --git a/apps/ios/README.md b/apps/ios/README.md index b870bdcea583a..c7c501fcbff7b 100644 --- a/apps/ios/README.md +++ b/apps/ios/README.md @@ -67,6 +67,37 @@ pnpm ios:open - iPhone node commands in foreground: camera snap/clip, canvas present/navigate/eval/snapshot, screen record, location, contacts, calendar, reminders, photos, motion, local notifications. - Share extension deep-link forwarding into the connected gateway session. +## Location Automation Use Case (Testing) + +Use this for automation signals ("I moved", "I arrived", "I left"), not as a keep-awake mechanism. + +- Product intent: + - movement-aware automations driven by iOS location events + - example: arrival/exit geofence, significant movement, visit detection +- Non-goal: + - continuous GPS polling just to keep the app alive + +Test path to include in QA runs: + +1. Enable location permission in app: + - set `Always` permission + - verify background location capability is enabled in the build profile +2. Background the app and trigger movement: + - walk/drive enough for a significant location update, or cross a configured geofence +3. Validate gateway side effects: + - node reconnect/wake if needed + - expected location/movement event arrives at gateway + - automation trigger executes once (no duplicate storm) +4. Validate resource impact: + - no sustained high thermal state + - no excessive background battery drain over a short observation window + +Pass criteria: + +- movement events are delivered reliably enough for automation UX +- no location-driven reconnect spam loops +- app remains stable after repeated background/foreground transitions + ## Known Issues / Limitations / Problems - Foreground-first: iOS can suspend sockets in background; reconnect recovery is still being tuned. diff --git a/apps/ios/ShareExtension/Info.plist b/apps/ios/ShareExtension/Info.plist index aa4ef74443480..0656afbf2d7e2 100644 --- a/apps/ios/ShareExtension/Info.plist +++ b/apps/ios/ShareExtension/Info.plist @@ -17,9 +17,9 @@ CFBundlePackageType XPC! CFBundleShortVersionString - 2026.2.18 + 2026.2.21 CFBundleVersion - 20260218 + 20260220 NSExtension NSExtensionAttributes diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/100.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/100.png new file mode 100644 index 0000000000000..22a04c9f22a3e Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/100.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/102.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/102.png new file mode 100644 index 0000000000000..ff8397de29767 Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/102.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/1024.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/1024.png new file mode 100644 index 0000000000000..ecea78807d8b2 Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/1024.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/108.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/108.png new file mode 100644 index 0000000000000..a6888456dfaab Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/108.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/114.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/114.png new file mode 100644 index 0000000000000..20e9ea1a55733 Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/114.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/120.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/120.png new file mode 100644 index 0000000000000..154836b43a228 Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/120.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/172.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/172.png new file mode 100644 index 0000000000000..a66c0132393e7 Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/172.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/180.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/180.png new file mode 100644 index 0000000000000..d01e83d8cccc8 Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/180.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/196.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/196.png new file mode 100644 index 0000000000000..b7989e43d8412 Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/196.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/216.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/216.png new file mode 100644 index 0000000000000..4dfb94abefb98 Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/216.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/234.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/234.png new file mode 100644 index 0000000000000..c0da9ae922cf9 Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/234.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/258.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/258.png new file mode 100644 index 0000000000000..dbfb75050bdca Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/258.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/29.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/29.png new file mode 100644 index 0000000000000..f4d57311481eb Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/29.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/40.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/40.png new file mode 100644 index 0000000000000..87a14602e3c47 Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/40.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/48.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/48.png new file mode 100644 index 0000000000000..f66c2ded344a1 Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/48.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/55.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/55.png new file mode 100644 index 0000000000000..0730736fca063 Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/55.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/57.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/57.png new file mode 100644 index 0000000000000..f8946de39b3a2 Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/57.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/58.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/58.png new file mode 100644 index 0000000000000..92ae2f999d90e Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/58.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/60.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/60.png new file mode 100644 index 0000000000000..03231a71d1893 Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/60.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/66.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/66.png new file mode 100644 index 0000000000000..834c6b0987f9a Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/66.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/80.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/80.png new file mode 100644 index 0000000000000..485a1aae7bdc8 Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/80.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/87.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/87.png new file mode 100644 index 0000000000000..61da8b5fd79b1 Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/87.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/88.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/88.png new file mode 100644 index 0000000000000..f47fb37b5fcd2 Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/88.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/92.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/92.png new file mode 100644 index 0000000000000..67a10a4845803 Binary files /dev/null and b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/92.png differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/Contents.json b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/Contents.json index 13847b5b5bf74..922e8c6d7315a 100644 --- a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/Contents.json +++ b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -1,31 +1 @@ -{ - "images" : [ - { "filename" : "icon-20@1x.png", "idiom" : "ipad", "scale" : "1x", "size" : "20x20" }, - { "filename" : "icon-20@2x.png", "idiom" : "ipad", "scale" : "2x", "size" : "20x20" }, - { "filename" : "icon-20@2x.png", "idiom" : "iphone","scale" : "2x", "size" : "20x20" }, - { "filename" : "icon-20@3x.png", "idiom" : "iphone","scale" : "3x", "size" : "20x20" }, - - { "filename" : "icon-29@1x.png", "idiom" : "ipad", "scale" : "1x", "size" : "29x29" }, - { "filename" : "icon-29@2x.png", "idiom" : "ipad", "scale" : "2x", "size" : "29x29" }, - { "filename" : "icon-29@2x.png", "idiom" : "iphone","scale" : "2x", "size" : "29x29" }, - { "filename" : "icon-29@3x.png", "idiom" : "iphone","scale" : "3x", "size" : "29x29" }, - - { "filename" : "icon-40@1x.png", "idiom" : "ipad", "scale" : "1x", "size" : "40x40" }, - { "filename" : "icon-40@2x.png", "idiom" : "ipad", "scale" : "2x", "size" : "40x40" }, - { "filename" : "icon-40@2x.png", "idiom" : "iphone","scale" : "2x", "size" : "40x40" }, - { "filename" : "icon-40@3x.png", "idiom" : "iphone","scale" : "3x", "size" : "40x40" }, - - { "filename" : "icon-60@2x.png", "idiom" : "iphone","scale" : "2x", "size" : "60x60" }, - { "filename" : "icon-60@3x.png", "idiom" : "iphone","scale" : "3x", "size" : "60x60" }, - - { "filename" : "icon-76@2x.png", "idiom" : "ipad", "scale" : "2x", "size" : "76x76" }, - - { "filename" : "icon-83.5@2x.png", "idiom" : "ipad", "scale" : "2x", "size" : "83.5x83.5" }, - - { "filename" : "icon-1024.png", "idiom" : "ios-marketing", "scale" : "1x", "size" : "1024x1024" } - ], - "info" : { - "author" : "xcode", - "version" : 1 - } -} +{"images":[{"size":"60x60","expected-size":"180","filename":"180.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"3x"},{"size":"40x40","expected-size":"80","filename":"80.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"2x"},{"size":"40x40","expected-size":"120","filename":"120.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"3x"},{"size":"60x60","expected-size":"120","filename":"120.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"2x"},{"size":"57x57","expected-size":"57","filename":"57.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"1x"},{"size":"29x29","expected-size":"58","filename":"58.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"2x"},{"size":"29x29","expected-size":"29","filename":"29.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"1x"},{"size":"29x29","expected-size":"87","filename":"87.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"3x"},{"size":"57x57","expected-size":"114","filename":"114.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"2x"},{"size":"20x20","expected-size":"40","filename":"40.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"2x"},{"size":"20x20","expected-size":"60","filename":"60.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"iphone","scale":"3x"},{"size":"1024x1024","filename":"1024.png","expected-size":"1024","idiom":"ios-marketing","folder":"Assets.xcassets/AppIcon.appiconset/","scale":"1x"},{"idiom":"watch","filename":"172.png","folder":"Assets.xcassets/AppIcon.appiconset/","subtype":"38mm","scale":"2x","size":"86x86","expected-size":"172","role":"quickLook"},{"idiom":"watch","filename":"80.png","folder":"Assets.xcassets/AppIcon.appiconset/","subtype":"38mm","scale":"2x","size":"40x40","expected-size":"80","role":"appLauncher"},{"idiom":"watch","filename":"88.png","folder":"Assets.xcassets/AppIcon.appiconset/","subtype":"40mm","scale":"2x","size":"44x44","expected-size":"88","role":"appLauncher"},{"idiom":"watch","filename":"102.png","folder":"Assets.xcassets/AppIcon.appiconset/","subtype":"45mm","scale":"2x","size":"51x51","expected-size":"102","role":"appLauncher"},{"idiom":"watch","filename":"108.png","folder":"Assets.xcassets/AppIcon.appiconset/","subtype":"49mm","scale":"2x","size":"54x54","expected-size":"108","role":"appLauncher"},{"idiom":"watch","filename":"92.png","folder":"Assets.xcassets/AppIcon.appiconset/","subtype":"41mm","scale":"2x","size":"46x46","expected-size":"92","role":"appLauncher"},{"idiom":"watch","filename":"100.png","folder":"Assets.xcassets/AppIcon.appiconset/","subtype":"44mm","scale":"2x","size":"50x50","expected-size":"100","role":"appLauncher"},{"idiom":"watch","filename":"196.png","folder":"Assets.xcassets/AppIcon.appiconset/","subtype":"42mm","scale":"2x","size":"98x98","expected-size":"196","role":"quickLook"},{"idiom":"watch","filename":"216.png","folder":"Assets.xcassets/AppIcon.appiconset/","subtype":"44mm","scale":"2x","size":"108x108","expected-size":"216","role":"quickLook"},{"idiom":"watch","filename":"234.png","folder":"Assets.xcassets/AppIcon.appiconset/","subtype":"45mm","scale":"2x","size":"117x117","expected-size":"234","role":"quickLook"},{"idiom":"watch","filename":"258.png","folder":"Assets.xcassets/AppIcon.appiconset/","subtype":"49mm","scale":"2x","size":"129x129","expected-size":"258","role":"quickLook"},{"idiom":"watch","filename":"48.png","folder":"Assets.xcassets/AppIcon.appiconset/","subtype":"38mm","scale":"2x","size":"24x24","expected-size":"48","role":"notificationCenter"},{"idiom":"watch","filename":"55.png","folder":"Assets.xcassets/AppIcon.appiconset/","subtype":"42mm","scale":"2x","size":"27.5x27.5","expected-size":"55","role":"notificationCenter"},{"idiom":"watch","filename":"66.png","folder":"Assets.xcassets/AppIcon.appiconset/","subtype":"45mm","scale":"2x","size":"33x33","expected-size":"66","role":"notificationCenter"},{"size":"29x29","expected-size":"87","filename":"87.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"watch","role":"companionSettings","scale":"3x"},{"size":"29x29","expected-size":"58","filename":"58.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"watch","role":"companionSettings","scale":"2x"},{"size":"1024x1024","expected-size":"1024","filename":"1024.png","folder":"Assets.xcassets/AppIcon.appiconset/","idiom":"watch-marketing","scale":"1x"}]} \ No newline at end of file diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-1024.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-1024.png deleted file mode 100644 index 1ebd257d93f50..0000000000000 Binary files a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-1024.png and /dev/null differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-20@1x.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-20@1x.png deleted file mode 100644 index 0aa1506a095c4..0000000000000 Binary files a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-20@1x.png and /dev/null differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-20@2x.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-20@2x.png deleted file mode 100644 index dd8a14724eb43..0000000000000 Binary files a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-20@2x.png and /dev/null differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-20@3x.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-20@3x.png deleted file mode 100644 index ca160dc2e8462..0000000000000 Binary files a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-20@3x.png and /dev/null differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-29@1x.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-29@1x.png deleted file mode 100644 index 9020a8672d3b7..0000000000000 Binary files a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-29@1x.png and /dev/null differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-29@2x.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-29@2x.png deleted file mode 100644 index ff85b417fece4..0000000000000 Binary files a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-29@2x.png and /dev/null differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-29@3x.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-29@3x.png deleted file mode 100644 index e12fff0314006..0000000000000 Binary files a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-29@3x.png and /dev/null differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-40@1x.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-40@1x.png deleted file mode 100644 index dd8a14724eb43..0000000000000 Binary files a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-40@1x.png and /dev/null differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-40@2x.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-40@2x.png deleted file mode 100644 index 9b3da5155efec..0000000000000 Binary files a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-40@2x.png and /dev/null differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-40@3x.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-40@3x.png deleted file mode 100644 index f57a0c1323c68..0000000000000 Binary files a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-40@3x.png and /dev/null differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-60@2x.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-60@2x.png deleted file mode 100644 index f57a0c1323c68..0000000000000 Binary files a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-60@2x.png and /dev/null differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-60@3x.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-60@3x.png deleted file mode 100644 index b94278f29d07b..0000000000000 Binary files a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-60@3x.png and /dev/null differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-76@2x.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-76@2x.png deleted file mode 100644 index 2d6240dc679c4..0000000000000 Binary files a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-76@2x.png and /dev/null differ diff --git a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-83.5@2x.png b/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-83.5@2x.png deleted file mode 100644 index 7321091c561e0..0000000000000 Binary files a/apps/ios/Sources/Assets.xcassets/AppIcon.appiconset/icon-83.5@2x.png and /dev/null differ diff --git a/apps/ios/Sources/Assets.xcassets/Contents.json b/apps/ios/Sources/Assets.xcassets/Contents.json deleted file mode 100644 index 73c00596a7fca..0000000000000 --- a/apps/ios/Sources/Assets.xcassets/Contents.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "info" : { - "author" : "xcode", - "version" : 1 - } -} diff --git a/apps/ios/Sources/Gateway/GatewayConnectionController.swift b/apps/ios/Sources/Gateway/GatewayConnectionController.swift index 92abd996b72c2..2b7f94ba45326 100644 --- a/apps/ios/Sources/Gateway/GatewayConnectionController.swift +++ b/apps/ios/Sources/Gateway/GatewayConnectionController.swift @@ -5,6 +5,7 @@ import CoreMotion import CryptoKit import EventKit import Foundation +import Darwin import OpenClawKit import Network import Observation @@ -162,7 +163,7 @@ final class GatewayConnectionController { .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" let token = GatewaySettingsStore.loadGatewayToken(instanceId: instanceId) let password = GatewaySettingsStore.loadGatewayPassword(instanceId: instanceId) - let resolvedUseTLS = useTLS + let resolvedUseTLS = self.resolveManualUseTLS(host: host, useTLS: useTLS) guard let resolvedPort = self.resolveManualPort(host: host, port: port, useTLS: resolvedUseTLS) else { return } let stableID = self.manualStableID(host: host, port: resolvedPort) @@ -215,6 +216,23 @@ final class GatewayConnectionController { } } + /// Rebuild connect options from current local settings (caps/commands/permissions) + /// and re-apply the active gateway config so capability changes take effect immediately. + func refreshActiveGatewayRegistrationFromSettings() { + guard let appModel else { return } + guard let cfg = appModel.activeGatewayConnectConfig else { return } + guard appModel.gatewayAutoReconnectEnabled else { return } + + let refreshedConfig = GatewayConnectConfig( + url: cfg.url, + stableID: cfg.stableID, + tls: cfg.tls, + token: cfg.token, + password: cfg.password, + nodeOptions: self.makeConnectOptions(stableID: cfg.stableID)) + appModel.applyGatewayConnectConfig(refreshedConfig) + } + func clearPendingTrustPrompt() { self.pendingTrustPrompt = nil self.pendingTrustConnect = nil @@ -309,7 +327,7 @@ final class GatewayConnectionController { let manualPort = defaults.integer(forKey: "gateway.manual.port") let manualTLS = defaults.bool(forKey: "gateway.manual.tls") - let resolvedUseTLS = manualTLS || self.shouldForceTLS(host: manualHost) + let resolvedUseTLS = self.resolveManualUseTLS(host: manualHost, useTLS: manualTLS) guard let resolvedPort = self.resolveManualPort( host: manualHost, port: manualPort, @@ -320,7 +338,7 @@ final class GatewayConnectionController { let tlsParams = self.resolveManualTLSParams( stableID: stableID, tlsEnabled: resolvedUseTLS, - allowTOFUReset: self.shouldForceTLS(host: manualHost)) + allowTOFUReset: self.shouldRequireTLS(host: manualHost)) guard let url = self.buildGatewayURL( host: manualHost, @@ -340,7 +358,7 @@ final class GatewayConnectionController { if let lastKnown = GatewaySettingsStore.loadLastGatewayConnection() { if case let .manual(host, port, useTLS, stableID) = lastKnown { - let resolvedUseTLS = useTLS || self.shouldForceTLS(host: host) + let resolvedUseTLS = self.resolveManualUseTLS(host: host, useTLS: useTLS) let stored = GatewayTLSStore.loadFingerprint(stableID: stableID) let tlsParams = stored.map { fp in GatewayTLSParams(required: true, expectedFingerprint: fp, allowTOFU: false, storeKey: stableID) @@ -646,12 +664,65 @@ final class GatewayConnectionController { return components.url } + private func resolveManualUseTLS(host: String, useTLS: Bool) -> Bool { + useTLS || self.shouldRequireTLS(host: host) + } + + private func shouldRequireTLS(host: String) -> Bool { + !Self.isLoopbackHost(host) + } + private func shouldForceTLS(host: String) -> Bool { let trimmed = host.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() if trimmed.isEmpty { return false } return trimmed.hasSuffix(".ts.net") || trimmed.hasSuffix(".ts.net.") } + private static func isLoopbackHost(_ rawHost: String) -> Bool { + var host = rawHost.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + guard !host.isEmpty else { return false } + + if host.hasPrefix("[") && host.hasSuffix("]") { + host.removeFirst() + host.removeLast() + } + if host.hasSuffix(".") { + host.removeLast() + } + if let zoneIndex = host.firstIndex(of: "%") { + host = String(host[.. Bool { + var addr = in_addr() + let parsed = host.withCString { inet_pton(AF_INET, $0, &addr) == 1 } + guard parsed else { return false } + let value = UInt32(bigEndian: addr.s_addr) + let firstOctet = UInt8((value >> 24) & 0xFF) + return firstOctet == 127 + } + + private static func isLoopbackIPv6(_ host: String) -> Bool { + var addr = in6_addr() + let parsed = host.withCString { inet_pton(AF_INET6, $0, &addr) == 1 } + guard parsed else { return false } + return withUnsafeBytes(of: &addr) { rawBytes in + let bytes = rawBytes.bindMemory(to: UInt8.self) + let isV6Loopback = bytes[0..<15].allSatisfy { $0 == 0 } && bytes[15] == 1 + if isV6Loopback { return true } + + let isMappedV4 = bytes[0..<10].allSatisfy { $0 == 0 } && bytes[10] == 0xFF && bytes[11] == 0xFF + return isMappedV4 && bytes[12] == 127 + } + } + private func manualStableID(host: String, port: Int) -> String { "manual|\(host.lowercased())|\(port)" } @@ -942,6 +1013,14 @@ extension GatewayConnectionController { { self.resolveDiscoveredTLSParams(gateway: gateway, allowTOFU: allowTOFU) } + + func _test_resolveManualUseTLS(host: String, useTLS: Bool) -> Bool { + self.resolveManualUseTLS(host: host, useTLS: useTLS) + } + + func _test_resolveManualPort(host: String, port: Int, useTLS: Bool) -> Int? { + self.resolveManualPort(host: host, port: port, useTLS: useTLS) + } } #endif diff --git a/apps/ios/Sources/Info.plist b/apps/ios/Sources/Info.plist index 4d1fec4625746..c3b469e709287 100644 --- a/apps/ios/Sources/Info.plist +++ b/apps/ios/Sources/Info.plist @@ -19,7 +19,7 @@ CFBundlePackageType APPL CFBundleShortVersionString - 2026.2.18 + 2026.2.21 CFBundleURLTypes @@ -32,7 +32,7 @@ CFBundleVersion - 20260218 + 20260220 NSAppTransportSecurity NSAllowsArbitraryLoadsInWebContent @@ -64,6 +64,10 @@ audio remote-notification + BGTaskSchedulerPermittedIdentifiers + + ai.openclaw.ios.bgrefresh + UILaunchScreen UISupportedInterfaceOrientations diff --git a/apps/ios/Sources/Location/SignificantLocationMonitor.swift b/apps/ios/Sources/Location/SignificantLocationMonitor.swift index f12a157dc69b6..1b8d5ca2a0d70 100644 --- a/apps/ios/Sources/Location/SignificantLocationMonitor.swift +++ b/apps/ios/Sources/Location/SignificantLocationMonitor.swift @@ -10,7 +10,8 @@ enum SignificantLocationMonitor { static func startIfNeeded( locationService: any LocationServicing, locationMode: OpenClawLocationMode, - gateway: GatewayNodeSession + gateway: GatewayNodeSession, + beforeSend: (@MainActor @Sendable () async -> Void)? = nil ) { guard locationMode == .always else { return } let status = locationService.authorizationStatus() @@ -31,6 +32,9 @@ enum SignificantLocationMonitor { let json = String(data: data, encoding: .utf8) else { return } Task { @MainActor in + if let beforeSend { + await beforeSend() + } await gateway.sendEvent(event: "location.update", payloadJSON: json) } } diff --git a/apps/ios/Sources/Model/NodeAppModel.swift b/apps/ios/Sources/Model/NodeAppModel.swift index 1d09251dd76e5..5bd98e6f49230 100644 --- a/apps/ios/Sources/Model/NodeAppModel.swift +++ b/apps/ios/Sources/Model/NodeAppModel.swift @@ -42,6 +42,8 @@ private final class NotificationInvokeLatch: @unchecked Sendable { final class NodeAppModel { private let deepLinkLogger = Logger(subsystem: "ai.openclaw.ios", category: "DeepLink") private let pushWakeLogger = Logger(subsystem: "ai.openclaw.ios", category: "PushWake") + private let locationWakeLogger = Logger(subsystem: "ai.openclaw.ios", category: "LocationWake") + private let watchReplyLogger = Logger(subsystem: "ai.openclaw.ios", category: "WatchReply") enum CameraHUDKind { case photo case recording @@ -103,6 +105,13 @@ final class NodeAppModel { private var backgroundTalkKeptActive = false private var backgroundedAt: Date? private var reconnectAfterBackgroundArmed = false + private var backgroundGraceTaskID: UIBackgroundTaskIdentifier = .invalid + @ObservationIgnored private var backgroundGraceTaskTimer: Task? + private var backgroundReconnectSuppressed = false + private var backgroundReconnectLeaseUntil: Date? + private var lastSignificantLocationWakeAt: Date? + private var queuedWatchReplies: [WatchQuickReplyEvent] = [] + private var seenWatchReplyIds = Set() private var gatewayConnected = false private var operatorConnected = false @@ -149,6 +158,11 @@ final class NodeAppModel { self.talkMode = talkMode self.apnsDeviceTokenHex = UserDefaults.standard.string(forKey: Self.apnsDeviceTokenUserDefaultsKey) GatewayDiagnostics.bootstrap() + self.watchMessagingService.setReplyHandler { [weak self] event in + Task { @MainActor in + await self?.handleWatchQuickReply(event) + } + } self.voiceWake.configure { [weak self] cmd in guard let self else { return } @@ -271,6 +285,7 @@ final class NodeAppModel { self.stopGatewayHealthMonitor() self.backgroundedAt = Date() self.reconnectAfterBackgroundArmed = true + self.beginBackgroundConnectionGracePeriod() // Release voice wake mic in background. self.backgroundVoiceWakeSuspended = self.voiceWake.suspendForExternalAudioCapture() let shouldKeepTalkActive = keepTalkActive && self.talkMode.isEnabled @@ -278,6 +293,8 @@ final class NodeAppModel { self.backgroundTalkSuspended = self.talkMode.suspendForBackground(keepActive: shouldKeepTalkActive) case .active, .inactive: self.isBackgrounded = false + self.endBackgroundConnectionGracePeriod(reason: "scene_foreground") + self.clearBackgroundReconnectSuppression(reason: "scene_foreground") if self.operatorConnected { self.startGatewayHealthMonitor() } @@ -329,9 +346,98 @@ final class NodeAppModel { } @unknown default: self.isBackgrounded = false + self.endBackgroundConnectionGracePeriod(reason: "scene_unknown") + self.clearBackgroundReconnectSuppression(reason: "scene_unknown") + } + } + + private func beginBackgroundConnectionGracePeriod(seconds: TimeInterval = 25) { + self.grantBackgroundReconnectLease(seconds: seconds, reason: "scene_background_grace") + self.endBackgroundConnectionGracePeriod(reason: "restart") + let taskID = UIApplication.shared.beginBackgroundTask(withName: "gateway-background-grace") { [weak self] in + Task { @MainActor in + self?.suppressBackgroundReconnect( + reason: "background_grace_expired", + disconnectIfNeeded: true) + self?.endBackgroundConnectionGracePeriod(reason: "expired") + } + } + guard taskID != .invalid else { + self.pushWakeLogger.info("Background grace unavailable: beginBackgroundTask returned invalid") + return + } + self.backgroundGraceTaskID = taskID + self.pushWakeLogger.info("Background grace started seconds=\(seconds, privacy: .public)") + self.backgroundGraceTaskTimer = Task { [weak self] in + guard let self else { return } + try? await Task.sleep(nanoseconds: UInt64(max(1, seconds) * 1_000_000_000)) + await MainActor.run { + self.suppressBackgroundReconnect(reason: "background_grace_timer", disconnectIfNeeded: true) + self.endBackgroundConnectionGracePeriod(reason: "timer") + } } } + private func endBackgroundConnectionGracePeriod(reason: String) { + self.backgroundGraceTaskTimer?.cancel() + self.backgroundGraceTaskTimer = nil + guard self.backgroundGraceTaskID != .invalid else { return } + UIApplication.shared.endBackgroundTask(self.backgroundGraceTaskID) + self.backgroundGraceTaskID = .invalid + self.pushWakeLogger.info("Background grace ended reason=\(reason, privacy: .public)") + } + + private func grantBackgroundReconnectLease(seconds: TimeInterval, reason: String) { + guard self.isBackgrounded else { return } + let leaseSeconds = max(5, seconds) + let leaseUntil = Date().addingTimeInterval(leaseSeconds) + if let existing = self.backgroundReconnectLeaseUntil, existing > leaseUntil { + // Keep the longer lease if one is already active. + } else { + self.backgroundReconnectLeaseUntil = leaseUntil + } + let wasSuppressed = self.backgroundReconnectSuppressed + self.backgroundReconnectSuppressed = false + self.pushWakeLogger.info( + "Background reconnect lease reason=\(reason, privacy: .public) seconds=\(leaseSeconds, privacy: .public) wasSuppressed=\(wasSuppressed, privacy: .public)") + } + + private func suppressBackgroundReconnect(reason: String, disconnectIfNeeded: Bool) { + guard self.isBackgrounded else { return } + let hadLease = self.backgroundReconnectLeaseUntil != nil + let changed = hadLease || !self.backgroundReconnectSuppressed + self.backgroundReconnectLeaseUntil = nil + self.backgroundReconnectSuppressed = true + guard changed else { return } + self.pushWakeLogger.info( + "Background reconnect suppressed reason=\(reason, privacy: .public) disconnect=\(disconnectIfNeeded, privacy: .public)") + guard disconnectIfNeeded else { return } + Task { [weak self] in + guard let self else { return } + await self.operatorGateway.disconnect() + await self.nodeGateway.disconnect() + await MainActor.run { + self.operatorConnected = false + self.gatewayConnected = false + self.talkMode.updateGatewayConnected(false) + if self.isBackgrounded { + self.gatewayStatusText = "Background idle" + self.gatewayServerName = nil + self.gatewayRemoteAddress = nil + self.showLocalCanvasOnDisconnect() + } + } + } + } + + private func clearBackgroundReconnectSuppression(reason: String) { + let changed = self.backgroundReconnectSuppressed || self.backgroundReconnectLeaseUntil != nil + self.backgroundReconnectSuppressed = false + self.backgroundReconnectLeaseUntil = nil + guard changed else { return } + self.pushWakeLogger.info("Background reconnect cleared reason=\(reason, privacy: .public)") + } + func setVoiceWakeEnabled(_ enabled: Bool) { self.voiceWake.setEnabled(enabled) if enabled { @@ -568,7 +674,7 @@ final class NodeAppModel { } catch { if let gatewayError = error as? GatewayResponseError { let lower = gatewayError.message.lowercased() - if lower.contains("unauthorized role") { + if lower.contains("unauthorized role") || lower.contains("missing scope") { await self.setGatewayHealthMonitorDisabled(true) return true } @@ -601,7 +707,7 @@ final class NodeAppModel { } catch { if let gatewayError = error as? GatewayResponseError { let lower = gatewayError.message.lowercased() - if lower.contains("unauthorized role") { + if lower.contains("unauthorized role") || lower.contains("missing scope") { await self.setGatewayHealthMonitorDisabled(true) return } @@ -1510,9 +1616,16 @@ private extension NodeAppModel { do { let result = try await self.watchMessagingService.sendNotification( id: req.id, - title: title, - body: body, - priority: params.priority) + params: params) + if result.queuedForDelivery || !result.deliveredImmediately { + let invokeID = req.id + Task { @MainActor in + await WatchPromptNotificationBridge.scheduleMirroredWatchPromptNotificationIfNeeded( + invokeID: invokeID, + params: params, + sendResult: result) + } + } let payload = OpenClawWatchNotifyPayload( deliveredImmediately: result.deliveredImmediately, queuedForDelivery: result.queuedForDelivery, @@ -1603,6 +1716,14 @@ extension NodeAppModel { return SessionKey.makeAgentSessionKey(agentId: agentId, baseKey: base) } + var chatSessionKey: String { + let base = "ios" + let agentId = (self.selectedAgentId ?? "").trimmingCharacters(in: .whitespacesAndNewlines) + let defaultId = (self.gatewayDefaultAgentId ?? "").trimmingCharacters(in: .whitespacesAndNewlines) + if agentId.isEmpty || (!defaultId.isEmpty && agentId == defaultId) { return base } + return SessionKey.makeAgentSessionKey(agentId: agentId, baseKey: base) + } + var activeAgentName: String { let agentId = (self.selectedAgentId ?? "").trimmingCharacters(in: .whitespacesAndNewlines) let defaultId = (self.gatewayDefaultAgentId ?? "").trimmingCharacters(in: .whitespacesAndNewlines) @@ -1717,6 +1838,23 @@ private extension NodeAppModel { self.apnsLastRegisteredTokenHex = nil } + func refreshBackgroundReconnectSuppressionIfNeeded(source: String) { + guard self.isBackgrounded else { return } + guard !self.backgroundReconnectSuppressed else { return } + guard let leaseUntil = self.backgroundReconnectLeaseUntil else { + self.suppressBackgroundReconnect(reason: "\(source):no_lease", disconnectIfNeeded: true) + return + } + if Date() >= leaseUntil { + self.suppressBackgroundReconnect(reason: "\(source):lease_expired", disconnectIfNeeded: true) + } + } + + func shouldPauseReconnectLoopInBackground(source: String) -> Bool { + self.refreshBackgroundReconnectSuppressionIfNeeded(source: source) + return self.isBackgrounded && self.backgroundReconnectSuppressed + } + func startOperatorGatewayLoop( url: URL, stableID: String, @@ -1739,6 +1877,7 @@ private extension NodeAppModel { try? await Task.sleep(nanoseconds: 1_000_000_000) continue } + if self.shouldPauseReconnectLoopInBackground(source: "operator_loop") { try? await Task.sleep(nanoseconds: 2_000_000_000); continue } if await self.isOperatorConnected() { try? await Task.sleep(nanoseconds: 1_000_000_000) continue @@ -1765,6 +1904,7 @@ private extension NodeAppModel { } GatewayDiagnostics.log( "operator gateway connected host=\(url.host ?? "?") scheme=\(url.scheme ?? "?")") + await self.talkMode.reloadConfig() await self.refreshBrandingFromGateway() await self.refreshAgentsFromGateway() await self.refreshShareRouteFromGateway() @@ -1826,6 +1966,7 @@ private extension NodeAppModel { try? await Task.sleep(nanoseconds: 1_000_000_000) continue } + if self.shouldPauseReconnectLoopInBackground(source: "node_loop") { try? await Task.sleep(nanoseconds: 2_000_000_000); continue } if await self.isGatewayConnected() { try? await Task.sleep(nanoseconds: 1_000_000_000) continue @@ -1875,7 +2016,15 @@ private extension NodeAppModel { } await self.showA2UIOnConnectIfNeeded() await self.onNodeGatewayConnected() - await MainActor.run { SignificantLocationMonitor.startIfNeeded(locationService: self.locationService, locationMode: self.locationMode(), gateway: self.nodeGateway) } + await MainActor.run { + SignificantLocationMonitor.startIfNeeded( + locationService: self.locationService, + locationMode: self.locationMode(), + gateway: self.nodeGateway, + beforeSend: { [weak self] in + await self?.handleSignificantLocationWakeIfNeeded() + }) + } }, onDisconnected: { [weak self] reason in guard let self else { return } @@ -2007,9 +2156,7 @@ private extension NodeAppModel { clientId: clientId, clientMode: "ui", clientDisplayName: displayName, - // Operator traffic should authenticate via shared gateway auth only. - // Including device identity here can trigger duplicate pairing flows. - includeDeviceIdentity: false) + includeDeviceIdentity: true) } func legacyClientIdFallback(currentClientId: String, error: Error) -> String? { @@ -2124,15 +2271,146 @@ extension NodeAppModel { /// Back-compat hook retained for older gateway-connect flows. func onNodeGatewayConnected() async { await self.registerAPNsTokenIfNeeded() + await self.flushQueuedWatchRepliesIfConnected() + } + + private func handleWatchQuickReply(_ event: WatchQuickReplyEvent) async { + let replyId = event.replyId.trimmingCharacters(in: .whitespacesAndNewlines) + let actionId = event.actionId.trimmingCharacters(in: .whitespacesAndNewlines) + if replyId.isEmpty || actionId.isEmpty { + self.watchReplyLogger.info("watch reply dropped: missing replyId/actionId") + return + } + + if self.seenWatchReplyIds.contains(replyId) { + self.watchReplyLogger.debug( + "watch reply deduped replyId=\(replyId, privacy: .public)") + return + } + self.seenWatchReplyIds.insert(replyId) + + if await !self.isGatewayConnected() { + self.queuedWatchReplies.append(event) + self.watchReplyLogger.info( + "watch reply queued replyId=\(replyId, privacy: .public) action=\(actionId, privacy: .public)") + return + } + + await self.forwardWatchReplyToAgent(event) + } + + private func flushQueuedWatchRepliesIfConnected() async { + guard await self.isGatewayConnected() else { return } + guard !self.queuedWatchReplies.isEmpty else { return } + + let pending = self.queuedWatchReplies + self.queuedWatchReplies.removeAll() + for event in pending { + await self.forwardWatchReplyToAgent(event) + } + } + + private func forwardWatchReplyToAgent(_ event: WatchQuickReplyEvent) async { + let sessionKey = event.sessionKey?.trimmingCharacters(in: .whitespacesAndNewlines) + let effectiveSessionKey = (sessionKey?.isEmpty == false) ? sessionKey : self.mainSessionKey + let message = Self.makeWatchReplyAgentMessage(event) + let link = AgentDeepLink( + message: message, + sessionKey: effectiveSessionKey, + thinking: "low", + deliver: false, + to: nil, + channel: nil, + timeoutSeconds: nil, + key: event.replyId) + do { + try await self.sendAgentRequest(link: link) + self.watchReplyLogger.info( + "watch reply forwarded replyId=\(event.replyId, privacy: .public) action=\(event.actionId, privacy: .public)") + self.openChatRequestID &+= 1 + } catch { + self.watchReplyLogger.error( + "watch reply forwarding failed replyId=\(event.replyId, privacy: .public) error=\(error.localizedDescription, privacy: .public)") + self.queuedWatchReplies.insert(event, at: 0) + } + } + + private static func makeWatchReplyAgentMessage(_ event: WatchQuickReplyEvent) -> String { + let actionLabel = event.actionLabel?.trimmingCharacters(in: .whitespacesAndNewlines) + let promptId = event.promptId.trimmingCharacters(in: .whitespacesAndNewlines) + let transport = event.transport.trimmingCharacters(in: .whitespacesAndNewlines) + let summary = actionLabel?.isEmpty == false ? actionLabel! : event.actionId + var lines: [String] = [] + lines.append("Watch reply: \(summary)") + lines.append("promptId=\(promptId.isEmpty ? "unknown" : promptId)") + lines.append("actionId=\(event.actionId)") + lines.append("replyId=\(event.replyId)") + if !transport.isEmpty { + lines.append("transport=\(transport)") + } + if let sentAtMs = event.sentAtMs { + lines.append("sentAtMs=\(sentAtMs)") + } + if let note = event.note?.trimmingCharacters(in: .whitespacesAndNewlines), !note.isEmpty { + lines.append("note=\(note)") + } + return lines.joined(separator: "\n") } func handleSilentPushWake(_ userInfo: [AnyHashable: Any]) async -> Bool { + let wakeId = Self.makePushWakeAttemptID() guard Self.isSilentPushPayload(userInfo) else { - self.pushWakeLogger.info("Ignored APNs payload: not silent push") + self.pushWakeLogger.info("Ignored APNs payload wakeId=\(wakeId, privacy: .public): not silent push") return false } - self.pushWakeLogger.info("Silent push received; attempting reconnect if needed") - return await self.reconnectGatewaySessionsForSilentPushIfNeeded() + let pushKind = Self.openclawPushKind(userInfo) + self.pushWakeLogger.info( + "Silent push received wakeId=\(wakeId, privacy: .public) kind=\(pushKind, privacy: .public) backgrounded=\(self.isBackgrounded, privacy: .public) autoReconnect=\(self.gatewayAutoReconnectEnabled, privacy: .public)") + let result = await self.reconnectGatewaySessionsForSilentPushIfNeeded(wakeId: wakeId) + self.pushWakeLogger.info( + "Silent push outcome wakeId=\(wakeId, privacy: .public) applied=\(result.applied, privacy: .public) reason=\(result.reason, privacy: .public) durationMs=\(result.durationMs, privacy: .public)") + return result.applied + } + + func handleBackgroundRefreshWake(trigger: String = "bg_app_refresh") async -> Bool { + let wakeId = Self.makePushWakeAttemptID() + self.pushWakeLogger.info( + "Background refresh wake received wakeId=\(wakeId, privacy: .public) trigger=\(trigger, privacy: .public) backgrounded=\(self.isBackgrounded, privacy: .public) autoReconnect=\(self.gatewayAutoReconnectEnabled, privacy: .public)") + let result = await self.reconnectGatewaySessionsForSilentPushIfNeeded(wakeId: wakeId) + self.pushWakeLogger.info( + "Background refresh wake outcome wakeId=\(wakeId, privacy: .public) applied=\(result.applied, privacy: .public) reason=\(result.reason, privacy: .public) durationMs=\(result.durationMs, privacy: .public)") + return result.applied + } + + func handleSignificantLocationWakeIfNeeded() async { + let wakeId = Self.makePushWakeAttemptID() + let now = Date() + let throttleWindowSeconds: TimeInterval = 180 + + if await self.isGatewayConnected() { + self.locationWakeLogger.info( + "Location wake no-op wakeId=\(wakeId, privacy: .public): already connected") + return + } + if let last = self.lastSignificantLocationWakeAt, + now.timeIntervalSince(last) < throttleWindowSeconds + { + self.locationWakeLogger.info( + "Location wake throttled wakeId=\(wakeId, privacy: .public) elapsedSec=\(now.timeIntervalSince(last), privacy: .public)") + return + } + self.lastSignificantLocationWakeAt = now + + self.locationWakeLogger.info( + "Location wake begin wakeId=\(wakeId, privacy: .public) backgrounded=\(self.isBackgrounded, privacy: .public) autoReconnect=\(self.gatewayAutoReconnectEnabled, privacy: .public)") + let result = await self.reconnectGatewaySessionsForSilentPushIfNeeded(wakeId: wakeId) + self.locationWakeLogger.info( + "Location wake trigger wakeId=\(wakeId, privacy: .public) applied=\(result.applied, privacy: .public) reason=\(result.reason, privacy: .public) durationMs=\(result.durationMs, privacy: .public)") + + guard result.applied else { return } + let connected = await self.waitForGatewayConnection(timeoutMs: 5000, pollMs: 250) + self.locationWakeLogger.info( + "Location wake post-check wakeId=\(wakeId, privacy: .public) connected=\(connected, privacy: .public)") } func updateAPNsDeviceToken(_ tokenData: Data) { @@ -2202,28 +2480,89 @@ extension NodeAppModel { return false } - private func reconnectGatewaySessionsForSilentPushIfNeeded() async -> Bool { + private static func makePushWakeAttemptID() -> String { + let raw = UUID().uuidString.replacingOccurrences(of: "-", with: "") + return String(raw.prefix(8)) + } + + private static func openclawPushKind(_ userInfo: [AnyHashable: Any]) -> String { + if let payload = userInfo["openclaw"] as? [String: Any], + let kind = payload["kind"] as? String + { + let trimmed = kind.trimmingCharacters(in: .whitespacesAndNewlines) + if !trimmed.isEmpty { return trimmed } + } + if let payload = userInfo["openclaw"] as? [AnyHashable: Any], + let kind = payload["kind"] as? String + { + let trimmed = kind.trimmingCharacters(in: .whitespacesAndNewlines) + if !trimmed.isEmpty { return trimmed } + } + return "unknown" + } + + private struct SilentPushWakeAttemptResult { + var applied: Bool + var reason: String + var durationMs: Int + } + + private func waitForGatewayConnection(timeoutMs: Int, pollMs: Int) async -> Bool { + let clampedTimeoutMs = max(0, timeoutMs) + let pollIntervalNs = UInt64(max(50, pollMs)) * 1_000_000 + let deadline = Date().addingTimeInterval(Double(clampedTimeoutMs) / 1000.0) + while Date() < deadline { + if await self.isGatewayConnected() { + return true + } + try? await Task.sleep(nanoseconds: pollIntervalNs) + } + return await self.isGatewayConnected() + } + + private func reconnectGatewaySessionsForSilentPushIfNeeded( + wakeId: String + ) async -> SilentPushWakeAttemptResult { + let startedAt = Date() + let makeResult: (Bool, String) -> SilentPushWakeAttemptResult = { applied, reason in + let durationMs = Int(Date().timeIntervalSince(startedAt) * 1000) + return SilentPushWakeAttemptResult( + applied: applied, + reason: reason, + durationMs: max(0, durationMs)) + } + guard self.isBackgrounded else { - self.pushWakeLogger.info("Wake no-op: app not backgrounded") - return false + self.pushWakeLogger.info("Wake no-op wakeId=\(wakeId, privacy: .public): app not backgrounded") + return makeResult(false, "not_backgrounded") } guard self.gatewayAutoReconnectEnabled else { - self.pushWakeLogger.info("Wake no-op: auto reconnect disabled") - return false + self.pushWakeLogger.info("Wake no-op wakeId=\(wakeId, privacy: .public): auto reconnect disabled") + return makeResult(false, "auto_reconnect_disabled") } - guard self.activeGatewayConnectConfig != nil else { - self.pushWakeLogger.info("Wake no-op: no active gateway config") - return false + guard let cfg = self.activeGatewayConnectConfig else { + self.pushWakeLogger.info("Wake no-op wakeId=\(wakeId, privacy: .public): no active gateway config") + return makeResult(false, "no_active_gateway_config") } + self.pushWakeLogger.info( + "Wake reconnect begin wakeId=\(wakeId, privacy: .public) stableID=\(cfg.stableID, privacy: .public)") + self.grantBackgroundReconnectLease(seconds: 30, reason: "wake_\(wakeId)") await self.operatorGateway.disconnect() await self.nodeGateway.disconnect() self.operatorConnected = false self.gatewayConnected = false self.gatewayStatusText = "Reconnecting…" self.talkMode.updateGatewayConnected(false) - self.pushWakeLogger.info("Wake reconnect trigger applied") - return true + self.applyGatewayConnectConfig(cfg) + self.pushWakeLogger.info("Wake reconnect trigger applied wakeId=\(wakeId, privacy: .public)") + return makeResult(true, "reconnect_triggered") + } +} + +extension NodeAppModel { + func _bridgeConsumeMirroredWatchReply(_ event: WatchQuickReplyEvent) async { + await self.handleWatchQuickReply(event) } } @@ -2264,5 +2603,9 @@ extension NodeAppModel { func _test_applyTalkModeSync(enabled: Bool, phase: String? = nil) { self.applyTalkModeSync(enabled: enabled, phase: phase) } + + func _test_queuedWatchReplyCount() -> Int { + self.queuedWatchReplies.count + } } #endif diff --git a/apps/ios/Sources/OpenClawApp.swift b/apps/ios/Sources/OpenClawApp.swift index 091c1b90fdf27..335e09fd986cd 100644 --- a/apps/ios/Sources/OpenClawApp.swift +++ b/apps/ios/Sources/OpenClawApp.swift @@ -1,17 +1,48 @@ import SwiftUI import Foundation +import OpenClawKit import os import UIKit +import BackgroundTasks +import UserNotifications -final class OpenClawAppDelegate: NSObject, UIApplicationDelegate { +private struct PendingWatchPromptAction { + var promptId: String? + var actionId: String + var actionLabel: String? + var sessionKey: String? +} + +@MainActor +final class OpenClawAppDelegate: NSObject, UIApplicationDelegate, @preconcurrency UNUserNotificationCenterDelegate { private let logger = Logger(subsystem: "ai.openclaw.ios", category: "Push") + private let backgroundWakeLogger = Logger(subsystem: "ai.openclaw.ios", category: "BackgroundWake") + private static let wakeRefreshTaskIdentifier = "ai.openclaw.ios.bgrefresh" + private var backgroundWakeTask: Task? private var pendingAPNsDeviceToken: Data? + private var pendingWatchPromptActions: [PendingWatchPromptAction] = [] + weak var appModel: NodeAppModel? { didSet { - guard let model = self.appModel, let token = self.pendingAPNsDeviceToken else { return } - self.pendingAPNsDeviceToken = nil - Task { @MainActor in - model.updateAPNsDeviceToken(token) + guard let model = self.appModel else { return } + if let token = self.pendingAPNsDeviceToken { + self.pendingAPNsDeviceToken = nil + Task { @MainActor in + model.updateAPNsDeviceToken(token) + } + } + if !self.pendingWatchPromptActions.isEmpty { + let pending = self.pendingWatchPromptActions + self.pendingWatchPromptActions.removeAll() + Task { @MainActor in + for action in pending { + await model.handleMirroredWatchPromptAction( + promptId: action.promptId, + actionId: action.actionId, + actionLabel: action.actionLabel, + sessionKey: action.sessionKey) + } + } } } } @@ -21,6 +52,8 @@ final class OpenClawAppDelegate: NSObject, UIApplicationDelegate { didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil ) -> Bool { + self.registerBackgroundWakeRefreshTask() + UNUserNotificationCenter.current().delegate = self application.registerForRemoteNotifications() return true } @@ -49,14 +82,369 @@ final class OpenClawAppDelegate: NSObject, UIApplicationDelegate { Task { @MainActor in guard let appModel = self.appModel else { self.logger.info("APNs wake skipped: appModel unavailable") + self.scheduleBackgroundWakeRefresh(afterSeconds: 90, reason: "silent_push_no_model") completionHandler(.noData) return } let handled = await appModel.handleSilentPushWake(userInfo) self.logger.info("APNs wake handled=\(handled, privacy: .public)") + if !handled { + self.scheduleBackgroundWakeRefresh(afterSeconds: 90, reason: "silent_push_not_applied") + } completionHandler(handled ? .newData : .noData) } } + + func scenePhaseChanged(_ phase: ScenePhase) { + if phase == .background { + self.scheduleBackgroundWakeRefresh(afterSeconds: 120, reason: "scene_background") + } + } + + private func registerBackgroundWakeRefreshTask() { + BGTaskScheduler.shared.register( + forTaskWithIdentifier: Self.wakeRefreshTaskIdentifier, + using: nil + ) { [weak self] task in + guard let refreshTask = task as? BGAppRefreshTask else { + task.setTaskCompleted(success: false) + return + } + self?.handleBackgroundWakeRefresh(task: refreshTask) + } + } + + private func scheduleBackgroundWakeRefresh(afterSeconds delay: TimeInterval, reason: String) { + let request = BGAppRefreshTaskRequest(identifier: Self.wakeRefreshTaskIdentifier) + request.earliestBeginDate = Date().addingTimeInterval(max(60, delay)) + do { + try BGTaskScheduler.shared.submit(request) + self.backgroundWakeLogger.info( + "Scheduled background wake refresh reason=\(reason, privacy: .public) delaySeconds=\(max(60, delay), privacy: .public)") + } catch { + self.backgroundWakeLogger.error( + "Failed scheduling background wake refresh reason=\(reason, privacy: .public) error=\(error.localizedDescription, privacy: .public)") + } + } + + private func handleBackgroundWakeRefresh(task: BGAppRefreshTask) { + self.scheduleBackgroundWakeRefresh(afterSeconds: 15 * 60, reason: "reschedule") + self.backgroundWakeTask?.cancel() + + let wakeTask = Task { @MainActor [weak self] in + guard let self, let appModel = self.appModel else { return false } + return await appModel.handleBackgroundRefreshWake(trigger: "bg_app_refresh") + } + self.backgroundWakeTask = wakeTask + task.expirationHandler = { + wakeTask.cancel() + } + Task { + let applied = await wakeTask.value + task.setTaskCompleted(success: applied) + self.backgroundWakeLogger.info( + "Background wake refresh finished applied=\(applied, privacy: .public)") + } + } + + private static func isWatchPromptNotification(_ userInfo: [AnyHashable: Any]) -> Bool { + (userInfo[WatchPromptNotificationBridge.typeKey] as? String) == WatchPromptNotificationBridge.typeValue + } + + private static func parseWatchPromptAction( + from response: UNNotificationResponse) -> PendingWatchPromptAction? + { + let userInfo = response.notification.request.content.userInfo + guard Self.isWatchPromptNotification(userInfo) else { return nil } + + let promptId = userInfo[WatchPromptNotificationBridge.promptIDKey] as? String + let sessionKey = userInfo[WatchPromptNotificationBridge.sessionKeyKey] as? String + + switch response.actionIdentifier { + case WatchPromptNotificationBridge.actionPrimaryIdentifier: + let actionId = (userInfo[WatchPromptNotificationBridge.actionPrimaryIDKey] as? String)? + .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + guard !actionId.isEmpty else { return nil } + let actionLabel = userInfo[WatchPromptNotificationBridge.actionPrimaryLabelKey] as? String + return PendingWatchPromptAction( + promptId: promptId, + actionId: actionId, + actionLabel: actionLabel, + sessionKey: sessionKey) + case WatchPromptNotificationBridge.actionSecondaryIdentifier: + let actionId = (userInfo[WatchPromptNotificationBridge.actionSecondaryIDKey] as? String)? + .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + guard !actionId.isEmpty else { return nil } + let actionLabel = userInfo[WatchPromptNotificationBridge.actionSecondaryLabelKey] as? String + return PendingWatchPromptAction( + promptId: promptId, + actionId: actionId, + actionLabel: actionLabel, + sessionKey: sessionKey) + default: + return nil + } + } + + private func routeWatchPromptAction(_ action: PendingWatchPromptAction) async { + guard let appModel = self.appModel else { + self.pendingWatchPromptActions.append(action) + return + } + await appModel.handleMirroredWatchPromptAction( + promptId: action.promptId, + actionId: action.actionId, + actionLabel: action.actionLabel, + sessionKey: action.sessionKey) + _ = await appModel.handleBackgroundRefreshWake(trigger: "watch_prompt_action") + } + + func userNotificationCenter( + _ center: UNUserNotificationCenter, + willPresent notification: UNNotification, + withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) + { + let userInfo = notification.request.content.userInfo + if Self.isWatchPromptNotification(userInfo) { + completionHandler([.banner, .list, .sound]) + return + } + completionHandler([]) + } + + func userNotificationCenter( + _ center: UNUserNotificationCenter, + didReceive response: UNNotificationResponse, + withCompletionHandler completionHandler: @escaping () -> Void) + { + guard let action = Self.parseWatchPromptAction(from: response) else { + completionHandler() + return + } + Task { @MainActor [weak self] in + guard let self else { + completionHandler() + return + } + await self.routeWatchPromptAction(action) + completionHandler() + } + } +} + +enum WatchPromptNotificationBridge { + static let typeKey = "openclaw.type" + static let typeValue = "watch.prompt" + static let promptIDKey = "openclaw.watch.promptId" + static let sessionKeyKey = "openclaw.watch.sessionKey" + static let actionPrimaryIDKey = "openclaw.watch.action.primary.id" + static let actionPrimaryLabelKey = "openclaw.watch.action.primary.label" + static let actionSecondaryIDKey = "openclaw.watch.action.secondary.id" + static let actionSecondaryLabelKey = "openclaw.watch.action.secondary.label" + static let actionPrimaryIdentifier = "openclaw.watch.action.primary" + static let actionSecondaryIdentifier = "openclaw.watch.action.secondary" + static let categoryPrefix = "openclaw.watch.prompt.category." + + @MainActor + static func scheduleMirroredWatchPromptNotificationIfNeeded( + invokeID: String, + params: OpenClawWatchNotifyParams, + sendResult: WatchNotificationSendResult) async + { + guard sendResult.queuedForDelivery || !sendResult.deliveredImmediately else { return } + + let title = params.title.trimmingCharacters(in: .whitespacesAndNewlines) + let body = params.body.trimmingCharacters(in: .whitespacesAndNewlines) + guard !title.isEmpty || !body.isEmpty else { return } + guard await self.requestNotificationAuthorizationIfNeeded() else { return } + + let normalizedActions = (params.actions ?? []).compactMap { action -> OpenClawWatchAction? in + let id = action.id.trimmingCharacters(in: .whitespacesAndNewlines) + let label = action.label.trimmingCharacters(in: .whitespacesAndNewlines) + guard !id.isEmpty, !label.isEmpty else { return nil } + return OpenClawWatchAction(id: id, label: label, style: action.style) + } + let primaryAction = normalizedActions.first + let secondaryAction = normalizedActions.dropFirst().first + + let center = UNUserNotificationCenter.current() + var categoryIdentifier = "" + if let primaryAction { + let categoryID = "\(self.categoryPrefix)\(invokeID)" + let category = UNNotificationCategory( + identifier: categoryID, + actions: self.categoryActions(primaryAction: primaryAction, secondaryAction: secondaryAction), + intentIdentifiers: [], + options: []) + await self.upsertNotificationCategory(category, center: center) + categoryIdentifier = categoryID + } + + var userInfo: [AnyHashable: Any] = [ + self.typeKey: self.typeValue, + ] + if let promptId = params.promptId?.trimmingCharacters(in: .whitespacesAndNewlines), !promptId.isEmpty { + userInfo[self.promptIDKey] = promptId + } + if let sessionKey = params.sessionKey?.trimmingCharacters(in: .whitespacesAndNewlines), !sessionKey.isEmpty { + userInfo[self.sessionKeyKey] = sessionKey + } + if let primaryAction { + userInfo[self.actionPrimaryIDKey] = primaryAction.id + userInfo[self.actionPrimaryLabelKey] = primaryAction.label + } + if let secondaryAction { + userInfo[self.actionSecondaryIDKey] = secondaryAction.id + userInfo[self.actionSecondaryLabelKey] = secondaryAction.label + } + + let content = UNMutableNotificationContent() + content.title = title.isEmpty ? "OpenClaw" : title + content.body = body + content.sound = .default + content.userInfo = userInfo + if !categoryIdentifier.isEmpty { + content.categoryIdentifier = categoryIdentifier + } + if #available(iOS 15.0, *) { + switch params.priority ?? .active { + case .passive: + content.interruptionLevel = .passive + case .timeSensitive: + content.interruptionLevel = .timeSensitive + case .active: + content.interruptionLevel = .active + } + } + + let request = UNNotificationRequest( + identifier: "watch.prompt.\(invokeID)", + content: content, + trigger: nil) + try? await self.addNotificationRequest(request, center: center) + } + + private static func categoryActions( + primaryAction: OpenClawWatchAction, + secondaryAction: OpenClawWatchAction?) -> [UNNotificationAction] + { + var actions: [UNNotificationAction] = [ + UNNotificationAction( + identifier: self.actionPrimaryIdentifier, + title: primaryAction.label, + options: self.notificationActionOptions(style: primaryAction.style)) + ] + if let secondaryAction { + actions.append( + UNNotificationAction( + identifier: self.actionSecondaryIdentifier, + title: secondaryAction.label, + options: self.notificationActionOptions(style: secondaryAction.style))) + } + return actions + } + + private static func notificationActionOptions(style: String?) -> UNNotificationActionOptions { + switch style?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() { + case "destructive": + return [.destructive] + case "foreground": + // For mirrored watch actions, keep handling in background when possible. + return [] + default: + return [] + } + } + + private static func requestNotificationAuthorizationIfNeeded() async -> Bool { + let center = UNUserNotificationCenter.current() + let status = await self.notificationAuthorizationStatus(center: center) + switch status { + case .authorized, .provisional, .ephemeral: + return true + case .notDetermined: + let granted = (try? await center.requestAuthorization(options: [.alert, .sound, .badge])) ?? false + if !granted { return false } + let updatedStatus = await self.notificationAuthorizationStatus(center: center) + return self.isAuthorizationStatusAllowed(updatedStatus) + case .denied: + return false + @unknown default: + return false + } + } + + private static func isAuthorizationStatusAllowed(_ status: UNAuthorizationStatus) -> Bool { + switch status { + case .authorized, .provisional, .ephemeral: + return true + case .denied, .notDetermined: + return false + @unknown default: + return false + } + } + + private static func notificationAuthorizationStatus(center: UNUserNotificationCenter) async -> UNAuthorizationStatus { + await withCheckedContinuation { continuation in + center.getNotificationSettings { settings in + continuation.resume(returning: settings.authorizationStatus) + } + } + } + + private static func upsertNotificationCategory( + _ category: UNNotificationCategory, + center: UNUserNotificationCenter) async + { + await withCheckedContinuation { continuation in + center.getNotificationCategories { categories in + var updated = categories + updated.update(with: category) + center.setNotificationCategories(updated) + continuation.resume() + } + } + } + + private static func addNotificationRequest(_ request: UNNotificationRequest, center: UNUserNotificationCenter) async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + center.add(request) { error in + if let error { + continuation.resume(throwing: error) + } else { + continuation.resume(returning: ()) + } + } + } + } +} + +extension NodeAppModel { + func handleMirroredWatchPromptAction( + promptId: String?, + actionId: String, + actionLabel: String?, + sessionKey: String?) async + { + let normalizedActionID = actionId.trimmingCharacters(in: .whitespacesAndNewlines) + guard !normalizedActionID.isEmpty else { return } + + let normalizedPromptID = promptId?.trimmingCharacters(in: .whitespacesAndNewlines) + let normalizedSessionKey = sessionKey?.trimmingCharacters(in: .whitespacesAndNewlines) + let normalizedActionLabel = actionLabel?.trimmingCharacters(in: .whitespacesAndNewlines) + + let event = WatchQuickReplyEvent( + replyId: UUID().uuidString, + promptId: (normalizedPromptID?.isEmpty == false) ? normalizedPromptID! : "unknown", + actionId: normalizedActionID, + actionLabel: (normalizedActionLabel?.isEmpty == false) ? normalizedActionLabel : nil, + sessionKey: (normalizedSessionKey?.isEmpty == false) ? normalizedSessionKey : nil, + note: "source=ios.notification", + sentAtMs: Int(Date().timeIntervalSince1970 * 1000), + transport: "ios.notification") + await self._bridgeConsumeMirroredWatchReply(event) + } } @main @@ -89,6 +477,7 @@ struct OpenClawApp: App { .onChange(of: self.scenePhase) { _, newValue in self.appModel.setScenePhase(newValue) self.gatewayController.setScenePhase(newValue) + self.appDelegate.scenePhaseChanged(newValue) } } } diff --git a/apps/ios/Sources/RootCanvas.swift b/apps/ios/Sources/RootCanvas.swift index 70ba9cdb96fe0..da893d3c94397 100644 --- a/apps/ios/Sources/RootCanvas.swift +++ b/apps/ios/Sources/RootCanvas.swift @@ -99,7 +99,7 @@ struct RootCanvas: View { ChatSheet( // Chat RPCs run on the operator session (read/write scopes). gateway: self.appModel.operatorSession, - sessionKey: self.appModel.mainSessionKey, + sessionKey: self.appModel.chatSessionKey, agentName: self.appModel.activeAgentName, userAccent: self.appModel.seamColor) case .quickSetup: diff --git a/apps/ios/Sources/Services/NodeServiceProtocols.swift b/apps/ios/Sources/Services/NodeServiceProtocols.swift index 6f882e82a11fb..27ee7cc27763a 100644 --- a/apps/ios/Sources/Services/NodeServiceProtocols.swift +++ b/apps/ios/Sources/Services/NodeServiceProtocols.swift @@ -73,6 +73,17 @@ struct WatchMessagingStatus: Sendable, Equatable { var activationState: String } +struct WatchQuickReplyEvent: Sendable, Equatable { + var replyId: String + var promptId: String + var actionId: String + var actionLabel: String? + var sessionKey: String? + var note: String? + var sentAtMs: Int? + var transport: String +} + struct WatchNotificationSendResult: Sendable, Equatable { var deliveredImmediately: Bool var queuedForDelivery: Bool @@ -81,11 +92,10 @@ struct WatchNotificationSendResult: Sendable, Equatable { protocol WatchMessagingServicing: AnyObject, Sendable { func status() async -> WatchMessagingStatus + func setReplyHandler(_ handler: (@Sendable (WatchQuickReplyEvent) -> Void)?) func sendNotification( id: String, - title: String, - body: String, - priority: OpenClawNotificationPriority?) async throws -> WatchNotificationSendResult + params: OpenClawWatchNotifyParams) async throws -> WatchNotificationSendResult } extension CameraController: CameraServicing {} diff --git a/apps/ios/Sources/Services/WatchMessagingService.swift b/apps/ios/Sources/Services/WatchMessagingService.swift index 8332fb5882d7f..3511a06c2db20 100644 --- a/apps/ios/Sources/Services/WatchMessagingService.swift +++ b/apps/ios/Sources/Services/WatchMessagingService.swift @@ -23,6 +23,8 @@ enum WatchMessagingError: LocalizedError { final class WatchMessagingService: NSObject, WatchMessagingServicing, @unchecked Sendable { private static let logger = Logger(subsystem: "ai.openclaw", category: "watch.messaging") private let session: WCSession? + private let replyHandlerLock = NSLock() + private var replyHandler: (@Sendable (WatchQuickReplyEvent) -> Void)? override init() { if WCSession.isSupported() { @@ -67,11 +69,15 @@ final class WatchMessagingService: NSObject, WatchMessagingServicing, @unchecked return Self.status(for: session) } + func setReplyHandler(_ handler: (@Sendable (WatchQuickReplyEvent) -> Void)?) { + self.replyHandlerLock.lock() + self.replyHandler = handler + self.replyHandlerLock.unlock() + } + func sendNotification( id: String, - title: String, - body: String, - priority: OpenClawNotificationPriority?) async throws -> WatchNotificationSendResult + params: OpenClawWatchNotifyParams) async throws -> WatchNotificationSendResult { await self.ensureActivated() guard let session = self.session else { @@ -82,14 +88,44 @@ final class WatchMessagingService: NSObject, WatchMessagingServicing, @unchecked guard snapshot.paired else { throw WatchMessagingError.notPaired } guard snapshot.appInstalled else { throw WatchMessagingError.watchAppNotInstalled } - let payload: [String: Any] = [ + var payload: [String: Any] = [ "type": "watch.notify", "id": id, - "title": title, - "body": body, - "priority": priority?.rawValue ?? OpenClawNotificationPriority.active.rawValue, + "title": params.title, + "body": params.body, + "priority": params.priority?.rawValue ?? OpenClawNotificationPriority.active.rawValue, "sentAtMs": Int(Date().timeIntervalSince1970 * 1000), ] + if let promptId = Self.nonEmpty(params.promptId) { + payload["promptId"] = promptId + } + if let sessionKey = Self.nonEmpty(params.sessionKey) { + payload["sessionKey"] = sessionKey + } + if let kind = Self.nonEmpty(params.kind) { + payload["kind"] = kind + } + if let details = Self.nonEmpty(params.details) { + payload["details"] = details + } + if let expiresAtMs = params.expiresAtMs { + payload["expiresAtMs"] = expiresAtMs + } + if let risk = params.risk { + payload["risk"] = risk.rawValue + } + if let actions = params.actions, !actions.isEmpty { + payload["actions"] = actions.map { action in + var encoded: [String: Any] = [ + "id": action.id, + "label": action.label, + ] + if let style = Self.nonEmpty(action.style) { + encoded["style"] = style + } + return encoded + } + } if snapshot.reachable { do { @@ -120,6 +156,47 @@ final class WatchMessagingService: NSObject, WatchMessagingServicing, @unchecked } } + private func emitReply(_ event: WatchQuickReplyEvent) { + let handler: ((WatchQuickReplyEvent) -> Void)? + self.replyHandlerLock.lock() + handler = self.replyHandler + self.replyHandlerLock.unlock() + handler?(event) + } + + private static func nonEmpty(_ value: String?) -> String? { + let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + return trimmed.isEmpty ? nil : trimmed + } + + private static func parseQuickReplyPayload( + _ payload: [String: Any], + transport: String) -> WatchQuickReplyEvent? + { + guard (payload["type"] as? String) == "watch.reply" else { + return nil + } + guard let actionId = nonEmpty(payload["actionId"] as? String) else { + return nil + } + let promptId = nonEmpty(payload["promptId"] as? String) ?? "unknown" + let replyId = nonEmpty(payload["replyId"] as? String) ?? UUID().uuidString + let actionLabel = nonEmpty(payload["actionLabel"] as? String) + let sessionKey = nonEmpty(payload["sessionKey"] as? String) + let note = nonEmpty(payload["note"] as? String) + let sentAtMs = (payload["sentAtMs"] as? Int) ?? (payload["sentAtMs"] as? NSNumber)?.intValue + + return WatchQuickReplyEvent( + replyId: replyId, + promptId: promptId, + actionId: actionId, + actionLabel: actionLabel, + sessionKey: sessionKey, + note: note, + sentAtMs: sentAtMs, + transport: transport) + } + private func ensureActivated() async { guard let session = self.session else { return } if session.activationState == .activated { return } @@ -172,5 +249,32 @@ extension WatchMessagingService: WCSessionDelegate { session.activate() } + func session(_: WCSession, didReceiveMessage message: [String: Any]) { + guard let event = Self.parseQuickReplyPayload(message, transport: "sendMessage") else { + return + } + self.emitReply(event) + } + + func session( + _: WCSession, + didReceiveMessage message: [String: Any], + replyHandler: @escaping ([String: Any]) -> Void) + { + guard let event = Self.parseQuickReplyPayload(message, transport: "sendMessage") else { + replyHandler(["ok": false, "error": "unsupported_payload"]) + return + } + replyHandler(["ok": true]) + self.emitReply(event) + } + + func session(_: WCSession, didReceiveUserInfo userInfo: [String: Any]) { + guard let event = Self.parseQuickReplyPayload(userInfo, transport: "transferUserInfo") else { + return + } + self.emitReply(event) + } + func sessionReachabilityDidChange(_ session: WCSession) {} } diff --git a/apps/ios/Sources/Settings/SettingsTab.swift b/apps/ios/Sources/Settings/SettingsTab.swift index 7825b45cb8d6f..024a4cbf42b13 100644 --- a/apps/ios/Sources/Settings/SettingsTab.swift +++ b/apps/ios/Sources/Settings/SettingsTab.swift @@ -306,6 +306,26 @@ struct SettingsTab: View { help: "Keeps the screen awake while OpenClaw is open.") DisclosureGroup("Advanced") { + VStack(alignment: .leading, spacing: 8) { + Text("Talk Voice (Gateway)") + .font(.footnote.weight(.semibold)) + .foregroundStyle(.secondary) + LabeledContent("Provider", value: "ElevenLabs") + LabeledContent( + "API Key", + value: self.appModel.talkMode.gatewayTalkConfigLoaded + ? (self.appModel.talkMode.gatewayTalkApiKeyConfigured ? "Configured" : "Not configured") + : "Not loaded") + LabeledContent( + "Default Model", + value: self.appModel.talkMode.gatewayTalkDefaultModelId ?? "eleven_v3 (fallback)") + LabeledContent( + "Default Voice", + value: self.appModel.talkMode.gatewayTalkDefaultVoiceId ?? "auto (first available)") + Text("Configured on gateway via talk.apiKey, talk.modelId, and talk.voiceId.") + .font(.footnote) + .foregroundStyle(.secondary) + } self.featureToggle( "Voice Directive Hint", isOn: self.$talkVoiceDirectiveHintEnabled, @@ -399,6 +419,9 @@ struct SettingsTab: View { // Keep setup front-and-center when disconnected; keep things compact once connected. self.gatewayExpanded = !self.isGatewayConnected self.selectedAgentPickerId = self.appModel.selectedAgentId ?? "" + if self.isGatewayConnected { + self.appModel.reloadTalkConfig() + } } .onChange(of: self.selectedAgentPickerId) { _, newValue in let trimmed = newValue.trimmingCharacters(in: .whitespacesAndNewlines) @@ -461,6 +484,10 @@ struct SettingsTab: View { self.locationEnabledModeRaw = previous self.lastLocationModeRaw = previous } + return + } + await MainActor.run { + self.gatewayController.refreshActiveGatewayRegistrationFromSettings() } } } diff --git a/apps/ios/Sources/Voice/TalkModeManager.swift b/apps/ios/Sources/Voice/TalkModeManager.swift index be90208af4788..8f208c66d505f 100644 --- a/apps/ios/Sources/Voice/TalkModeManager.swift +++ b/apps/ios/Sources/Voice/TalkModeManager.swift @@ -24,6 +24,10 @@ final class TalkModeManager: NSObject { var statusText: String = "Off" /// 0..1-ish (not calibrated). Intended for UI feedback only. var micLevel: Double = 0 + var gatewayTalkConfigLoaded: Bool = false + var gatewayTalkApiKeyConfigured: Bool = false + var gatewayTalkDefaultModelId: String? + var gatewayTalkDefaultVoiceId: String? private enum CaptureMode { case idle @@ -87,6 +91,8 @@ final class TalkModeManager: NSObject { private var incrementalSpeechBuffer = IncrementalSpeechBuffer() private var incrementalSpeechContext: IncrementalSpeechContext? private var incrementalSpeechDirective: TalkDirective? + private var incrementalSpeechPrefetch: IncrementalSpeechPrefetchState? + private var incrementalSpeechPrefetchMonitorTask: Task? private let logger = Logger(subsystem: "bot.molt", category: "TalkMode") @@ -547,6 +553,16 @@ final class TalkModeManager: NSObject { guard let self else { return } if let error { let msg = error.localizedDescription + let lowered = msg.lowercased() + let isCancellation = lowered.contains("cancelled") || lowered.contains("canceled") + if isCancellation { + GatewayDiagnostics.log("talk speech: cancelled") + if self.captureMode == .continuous, self.isEnabled, !self.isSpeaking { + self.statusText = "Listening" + } + self.logger.debug("speech recognition cancelled") + return + } GatewayDiagnostics.log("talk speech: error=\(msg)") if !self.isSpeaking { if msg.localizedCaseInsensitiveContains("no speech detected") { @@ -1173,6 +1189,7 @@ final class TalkModeManager: NSObject { self.incrementalSpeechQueue.removeAll() self.incrementalSpeechTask?.cancel() self.incrementalSpeechTask = nil + self.cancelIncrementalPrefetch() self.incrementalSpeechActive = true self.incrementalSpeechUsed = false self.incrementalSpeechLanguage = nil @@ -1185,6 +1202,7 @@ final class TalkModeManager: NSObject { self.incrementalSpeechQueue.removeAll() self.incrementalSpeechTask?.cancel() self.incrementalSpeechTask = nil + self.cancelIncrementalPrefetch() self.incrementalSpeechActive = false self.incrementalSpeechContext = nil self.incrementalSpeechDirective = nil @@ -1212,20 +1230,168 @@ final class TalkModeManager: NSObject { self.incrementalSpeechTask = Task { @MainActor [weak self] in guard let self else { return } + defer { + self.cancelIncrementalPrefetch() + self.isSpeaking = false + self.stopRecognition() + self.incrementalSpeechTask = nil + } while !Task.isCancelled { guard !self.incrementalSpeechQueue.isEmpty else { break } let segment = self.incrementalSpeechQueue.removeFirst() self.statusText = "Speaking…" self.isSpeaking = true self.lastSpokenText = segment - await self.speakIncrementalSegment(segment) + await self.updateIncrementalContextIfNeeded() + let context = self.incrementalSpeechContext + let prefetchedAudio = await self.consumeIncrementalPrefetchedAudioIfAvailable( + for: segment, + context: context) + if let context { + self.startIncrementalPrefetchMonitor(context: context) + } + await self.speakIncrementalSegment( + segment, + context: context, + prefetchedAudio: prefetchedAudio) + self.cancelIncrementalPrefetchMonitor() + } + } + } + + private func cancelIncrementalPrefetch() { + self.cancelIncrementalPrefetchMonitor() + self.incrementalSpeechPrefetch?.task.cancel() + self.incrementalSpeechPrefetch = nil + } + + private func cancelIncrementalPrefetchMonitor() { + self.incrementalSpeechPrefetchMonitorTask?.cancel() + self.incrementalSpeechPrefetchMonitorTask = nil + } + + private func startIncrementalPrefetchMonitor(context: IncrementalSpeechContext) { + self.cancelIncrementalPrefetchMonitor() + self.incrementalSpeechPrefetchMonitorTask = Task { @MainActor [weak self] in + guard let self else { return } + while !Task.isCancelled { + if self.ensureIncrementalPrefetchForUpcomingSegment(context: context) { + return + } + try? await Task.sleep(nanoseconds: 40_000_000) } - self.isSpeaking = false - self.stopRecognition() - self.incrementalSpeechTask = nil } } + private func ensureIncrementalPrefetchForUpcomingSegment(context: IncrementalSpeechContext) -> Bool { + guard context.canUseElevenLabs else { + self.cancelIncrementalPrefetch() + return false + } + guard let nextSegment = self.incrementalSpeechQueue.first else { return false } + if let existing = self.incrementalSpeechPrefetch { + if existing.segment == nextSegment, existing.context == context { + return true + } + existing.task.cancel() + self.incrementalSpeechPrefetch = nil + } + self.startIncrementalPrefetch(segment: nextSegment, context: context) + return self.incrementalSpeechPrefetch != nil + } + + private func startIncrementalPrefetch(segment: String, context: IncrementalSpeechContext) { + guard context.canUseElevenLabs, let apiKey = context.apiKey, let voiceId = context.voiceId else { return } + let prefetchOutputFormat = self.resolveIncrementalPrefetchOutputFormat(context: context) + let request = self.makeIncrementalTTSRequest( + text: segment, + context: context, + outputFormat: prefetchOutputFormat) + let id = UUID() + let task = Task { [weak self] in + let stream = ElevenLabsTTSClient(apiKey: apiKey).streamSynthesize(voiceId: voiceId, request: request) + var chunks: [Data] = [] + do { + for try await chunk in stream { + try Task.checkCancellation() + chunks.append(chunk) + } + await self?.completeIncrementalPrefetch(id: id, chunks: chunks) + } catch is CancellationError { + await self?.clearIncrementalPrefetch(id: id) + } catch { + await self?.failIncrementalPrefetch(id: id, error: error) + } + } + self.incrementalSpeechPrefetch = IncrementalSpeechPrefetchState( + id: id, + segment: segment, + context: context, + outputFormat: prefetchOutputFormat, + chunks: nil, + task: task) + } + + private func completeIncrementalPrefetch(id: UUID, chunks: [Data]) { + guard var prefetch = self.incrementalSpeechPrefetch, prefetch.id == id else { return } + prefetch.chunks = chunks + self.incrementalSpeechPrefetch = prefetch + } + + private func clearIncrementalPrefetch(id: UUID) { + guard let prefetch = self.incrementalSpeechPrefetch, prefetch.id == id else { return } + prefetch.task.cancel() + self.incrementalSpeechPrefetch = nil + } + + private func failIncrementalPrefetch(id: UUID, error: any Error) { + guard let prefetch = self.incrementalSpeechPrefetch, prefetch.id == id else { return } + self.logger.debug("incremental prefetch failed: \(error.localizedDescription, privacy: .public)") + prefetch.task.cancel() + self.incrementalSpeechPrefetch = nil + } + + private func consumeIncrementalPrefetchedAudioIfAvailable( + for segment: String, + context: IncrementalSpeechContext? + ) async -> IncrementalPrefetchedAudio? + { + guard let context else { + self.cancelIncrementalPrefetch() + return nil + } + guard let prefetch = self.incrementalSpeechPrefetch else { + return nil + } + guard prefetch.context == context else { + prefetch.task.cancel() + self.incrementalSpeechPrefetch = nil + return nil + } + guard prefetch.segment == segment else { + return nil + } + if let chunks = prefetch.chunks, !chunks.isEmpty { + let prefetched = IncrementalPrefetchedAudio(chunks: chunks, outputFormat: prefetch.outputFormat) + self.incrementalSpeechPrefetch = nil + return prefetched + } + await prefetch.task.value + guard let completed = self.incrementalSpeechPrefetch else { return nil } + guard completed.context == context, completed.segment == segment else { return nil } + guard let chunks = completed.chunks, !chunks.isEmpty else { return nil } + let prefetched = IncrementalPrefetchedAudio(chunks: chunks, outputFormat: completed.outputFormat) + self.incrementalSpeechPrefetch = nil + return prefetched + } + + private func resolveIncrementalPrefetchOutputFormat(context: IncrementalSpeechContext) -> String? { + if TalkTTSValidation.pcmSampleRate(from: context.outputFormat) != nil { + return ElevenLabsTTSClient.validatedOutputFormat("mp3_44100") + } + return context.outputFormat + } + private func finishIncrementalSpeech() async { guard self.incrementalSpeechActive else { return } let leftover = self.incrementalSpeechBuffer.flush() @@ -1333,77 +1499,103 @@ final class TalkModeManager: NSObject { canUseElevenLabs: canUseElevenLabs) } - private func speakIncrementalSegment(_ text: String) async { - await self.updateIncrementalContextIfNeeded() - guard let context = self.incrementalSpeechContext else { + private func makeIncrementalTTSRequest( + text: String, + context: IncrementalSpeechContext, + outputFormat: String? + ) -> ElevenLabsTTSRequest + { + ElevenLabsTTSRequest( + text: text, + modelId: context.modelId, + outputFormat: outputFormat, + speed: TalkTTSValidation.resolveSpeed( + speed: context.directive?.speed, + rateWPM: context.directive?.rateWPM), + stability: TalkTTSValidation.validatedStability( + context.directive?.stability, + modelId: context.modelId), + similarity: TalkTTSValidation.validatedUnit(context.directive?.similarity), + style: TalkTTSValidation.validatedUnit(context.directive?.style), + speakerBoost: context.directive?.speakerBoost, + seed: TalkTTSValidation.validatedSeed(context.directive?.seed), + normalize: ElevenLabsTTSClient.validatedNormalize(context.directive?.normalize), + language: context.language, + latencyTier: TalkTTSValidation.validatedLatencyTier(context.directive?.latencyTier)) + } + + private static func makeBufferedAudioStream(chunks: [Data]) -> AsyncThrowingStream { + AsyncThrowingStream { continuation in + for chunk in chunks { + continuation.yield(chunk) + } + continuation.finish() + } + } + + private func speakIncrementalSegment( + _ text: String, + context preferredContext: IncrementalSpeechContext? = nil, + prefetchedAudio: IncrementalPrefetchedAudio? = nil + ) async + { + let context: IncrementalSpeechContext + if let preferredContext { + context = preferredContext + } else { + await self.updateIncrementalContextIfNeeded() + guard let resolvedContext = self.incrementalSpeechContext else { + try? await TalkSystemSpeechSynthesizer.shared.speak( + text: text, + language: self.incrementalSpeechLanguage) + return + } + context = resolvedContext + } + + guard context.canUseElevenLabs, let apiKey = context.apiKey, let voiceId = context.voiceId else { try? await TalkSystemSpeechSynthesizer.shared.speak( text: text, language: self.incrementalSpeechLanguage) return } - if context.canUseElevenLabs, let apiKey = context.apiKey, let voiceId = context.voiceId { - let request = ElevenLabsTTSRequest( - text: text, - modelId: context.modelId, - outputFormat: context.outputFormat, - speed: TalkTTSValidation.resolveSpeed( - speed: context.directive?.speed, - rateWPM: context.directive?.rateWPM), - stability: TalkTTSValidation.validatedStability( - context.directive?.stability, - modelId: context.modelId), - similarity: TalkTTSValidation.validatedUnit(context.directive?.similarity), - style: TalkTTSValidation.validatedUnit(context.directive?.style), - speakerBoost: context.directive?.speakerBoost, - seed: TalkTTSValidation.validatedSeed(context.directive?.seed), - normalize: ElevenLabsTTSClient.validatedNormalize(context.directive?.normalize), - language: context.language, - latencyTier: TalkTTSValidation.validatedLatencyTier(context.directive?.latencyTier)) - let client = ElevenLabsTTSClient(apiKey: apiKey) - let stream = client.streamSynthesize(voiceId: voiceId, request: request) - let sampleRate = TalkTTSValidation.pcmSampleRate(from: context.outputFormat) - let result: StreamingPlaybackResult - if let sampleRate { - self.lastPlaybackWasPCM = true - var playback = await self.pcmPlayer.play(stream: stream, sampleRate: sampleRate) - if !playback.finished, playback.interruptedAt == nil { - self.logger.warning("pcm playback failed; retrying mp3") - self.lastPlaybackWasPCM = false - let mp3Format = ElevenLabsTTSClient.validatedOutputFormat("mp3_44100") - let mp3Stream = client.streamSynthesize( - voiceId: voiceId, - request: ElevenLabsTTSRequest( - text: text, - modelId: context.modelId, - outputFormat: mp3Format, - speed: TalkTTSValidation.resolveSpeed( - speed: context.directive?.speed, - rateWPM: context.directive?.rateWPM), - stability: TalkTTSValidation.validatedStability( - context.directive?.stability, - modelId: context.modelId), - similarity: TalkTTSValidation.validatedUnit(context.directive?.similarity), - style: TalkTTSValidation.validatedUnit(context.directive?.style), - speakerBoost: context.directive?.speakerBoost, - seed: TalkTTSValidation.validatedSeed(context.directive?.seed), - normalize: ElevenLabsTTSClient.validatedNormalize(context.directive?.normalize), - language: context.language, - latencyTier: TalkTTSValidation.validatedLatencyTier(context.directive?.latencyTier))) - playback = await self.mp3Player.play(stream: mp3Stream) - } - result = playback - } else { + let client = ElevenLabsTTSClient(apiKey: apiKey) + let request = self.makeIncrementalTTSRequest( + text: text, + context: context, + outputFormat: context.outputFormat) + let stream: AsyncThrowingStream + if let prefetchedAudio, !prefetchedAudio.chunks.isEmpty { + stream = Self.makeBufferedAudioStream(chunks: prefetchedAudio.chunks) + } else { + stream = client.streamSynthesize(voiceId: voiceId, request: request) + } + let playbackFormat = prefetchedAudio?.outputFormat ?? context.outputFormat + let sampleRate = TalkTTSValidation.pcmSampleRate(from: playbackFormat) + let result: StreamingPlaybackResult + if let sampleRate { + self.lastPlaybackWasPCM = true + var playback = await self.pcmPlayer.play(stream: stream, sampleRate: sampleRate) + if !playback.finished, playback.interruptedAt == nil { + self.logger.warning("pcm playback failed; retrying mp3") self.lastPlaybackWasPCM = false - result = await self.mp3Player.play(stream: stream) - } - if !result.finished, let interruptedAt = result.interruptedAt { - self.lastInterruptedAtSeconds = interruptedAt + let mp3Format = ElevenLabsTTSClient.validatedOutputFormat("mp3_44100") + let mp3Stream = client.streamSynthesize( + voiceId: voiceId, + request: self.makeIncrementalTTSRequest( + text: text, + context: context, + outputFormat: mp3Format)) + playback = await self.mp3Player.play(stream: mp3Stream) } + result = playback } else { - try? await TalkSystemSpeechSynthesizer.shared.speak( - text: text, - language: self.incrementalSpeechLanguage) + self.lastPlaybackWasPCM = false + result = await self.mp3Player.play(stream: stream) + } + if !result.finished, let interruptedAt = result.interruptedAt { + self.lastInterruptedAtSeconds = interruptedAt } } @@ -1733,6 +1925,10 @@ extension TalkModeManager { } else { self.apiKey = (localApiKey?.isEmpty == false) ? localApiKey : configApiKey } + self.gatewayTalkDefaultVoiceId = self.defaultVoiceId + self.gatewayTalkDefaultModelId = self.defaultModelId + self.gatewayTalkApiKeyConfigured = (self.apiKey?.isEmpty == false) + self.gatewayTalkConfigLoaded = true if let interrupt = talk?["interruptOnSpeech"] as? Bool { self.interruptOnSpeech = interrupt } @@ -1741,6 +1937,10 @@ extension TalkModeManager { if !self.modelOverrideActive { self.currentModelId = self.defaultModelId } + self.gatewayTalkDefaultVoiceId = nil + self.gatewayTalkDefaultModelId = nil + self.gatewayTalkApiKeyConfigured = false + self.gatewayTalkConfigLoaded = false } } @@ -1862,7 +2062,7 @@ extension TalkModeManager { } #endif -private struct IncrementalSpeechContext { +private struct IncrementalSpeechContext: Equatable { let apiKey: String? let voiceId: String? let modelId: String? @@ -1872,4 +2072,18 @@ private struct IncrementalSpeechContext { let canUseElevenLabs: Bool } +private struct IncrementalSpeechPrefetchState { + let id: UUID + let segment: String + let context: IncrementalSpeechContext + let outputFormat: String? + var chunks: [Data]? + let task: Task +} + +private struct IncrementalPrefetchedAudio { + let chunks: [Data] + let outputFormat: String? +} + // swiftlint:enable type_body_length diff --git a/apps/ios/Tests/DeepLinkParserTests.swift b/apps/ios/Tests/DeepLinkParserTests.swift index ea8b2a81203eb..51ef9547a10af 100644 --- a/apps/ios/Tests/DeepLinkParserTests.swift +++ b/apps/ios/Tests/DeepLinkParserTests.swift @@ -85,6 +85,18 @@ import Testing .init(host: "openclaw.local", port: 18789, tls: true, token: "abc", password: "def"))) } + @Test func parseGatewayLinkRejectsInsecureNonLoopbackWs() { + let url = URL( + string: "openclaw://gateway?host=attacker.example&port=18789&tls=0&token=abc")! + #expect(DeepLinkParser.parse(url) == nil) + } + + @Test func parseGatewayLinkRejectsInsecurePrefixBypassHost() { + let url = URL( + string: "openclaw://gateway?host=127.attacker.example&port=18789&tls=0&token=abc")! + #expect(DeepLinkParser.parse(url) == nil) + } + @Test func parseGatewaySetupCodeParsesBase64UrlPayload() { let payload = #"{"url":"wss://gateway.example.com:443","token":"tok","password":"pw"}"# let encoded = Data(payload.utf8) @@ -124,4 +136,46 @@ import Testing token: "tok", password: nil)) } + + @Test func parseGatewaySetupCodeRejectsInsecureNonLoopbackWs() { + let payload = #"{"url":"ws://attacker.example:18789","token":"tok"}"# + let encoded = Data(payload.utf8) + .base64EncodedString() + .replacingOccurrences(of: "+", with: "-") + .replacingOccurrences(of: "/", with: "_") + .replacingOccurrences(of: "=", with: "") + + let link = GatewayConnectDeepLink.fromSetupCode(encoded) + #expect(link == nil) + } + + @Test func parseGatewaySetupCodeRejectsInsecurePrefixBypassHost() { + let payload = #"{"url":"ws://127.attacker.example:18789","token":"tok"}"# + let encoded = Data(payload.utf8) + .base64EncodedString() + .replacingOccurrences(of: "+", with: "-") + .replacingOccurrences(of: "/", with: "_") + .replacingOccurrences(of: "=", with: "") + + let link = GatewayConnectDeepLink.fromSetupCode(encoded) + #expect(link == nil) + } + + @Test func parseGatewaySetupCodeAllowsLoopbackWs() { + let payload = #"{"url":"ws://127.0.0.1:18789","token":"tok"}"# + let encoded = Data(payload.utf8) + .base64EncodedString() + .replacingOccurrences(of: "+", with: "-") + .replacingOccurrences(of: "/", with: "_") + .replacingOccurrences(of: "=", with: "") + + let link = GatewayConnectDeepLink.fromSetupCode(encoded) + + #expect(link == .init( + host: "127.0.0.1", + port: 18789, + tls: false, + token: "tok", + password: nil)) + } } diff --git a/apps/ios/Tests/GatewayConnectionSecurityTests.swift b/apps/ios/Tests/GatewayConnectionSecurityTests.swift index 066ccb1dd2295..b82ae71616870 100644 --- a/apps/ios/Tests/GatewayConnectionSecurityTests.swift +++ b/apps/ios/Tests/GatewayConnectionSecurityTests.swift @@ -102,4 +102,30 @@ import Testing #expect(controller._test_didAutoConnect() == false) } + + @Test @MainActor func manualConnectionsForceTLSForNonLoopbackHosts() async { + let appModel = NodeAppModel() + let controller = GatewayConnectionController(appModel: appModel, startDiscovery: false) + + #expect(controller._test_resolveManualUseTLS(host: "gateway.example.com", useTLS: false) == true) + #expect(controller._test_resolveManualUseTLS(host: "openclaw.local", useTLS: false) == true) + #expect(controller._test_resolveManualUseTLS(host: "127.attacker.example", useTLS: false) == true) + + #expect(controller._test_resolveManualUseTLS(host: "localhost", useTLS: false) == false) + #expect(controller._test_resolveManualUseTLS(host: "127.0.0.1", useTLS: false) == false) + #expect(controller._test_resolveManualUseTLS(host: "::1", useTLS: false) == false) + #expect(controller._test_resolveManualUseTLS(host: "[::1]", useTLS: false) == false) + #expect(controller._test_resolveManualUseTLS(host: "::ffff:127.0.0.1", useTLS: false) == false) + #expect(controller._test_resolveManualUseTLS(host: "0.0.0.0", useTLS: false) == false) + } + + @Test @MainActor func manualDefaultPortUses443OnlyForTailnetTLSHosts() async { + let appModel = NodeAppModel() + let controller = GatewayConnectionController(appModel: appModel, startDiscovery: false) + + #expect(controller._test_resolveManualPort(host: "gateway.example.com", port: 0, useTLS: true) == 18789) + #expect(controller._test_resolveManualPort(host: "device.sample.ts.net", port: 0, useTLS: true) == 443) + #expect(controller._test_resolveManualPort(host: "device.sample.ts.net.", port: 0, useTLS: true) == 443) + #expect(controller._test_resolveManualPort(host: "device.sample.ts.net", port: 18789, useTLS: true) == 18789) + } } diff --git a/apps/ios/Tests/Info.plist b/apps/ios/Tests/Info.plist index e061595cb30c7..7fc8d82704433 100644 --- a/apps/ios/Tests/Info.plist +++ b/apps/ios/Tests/Info.plist @@ -17,8 +17,8 @@ CFBundlePackageType BNDL CFBundleShortVersionString - 2026.2.18 + 2026.2.21 CFBundleVersion - 20260218 + 20260220 diff --git a/apps/ios/Tests/NodeAppModelInvokeTests.swift b/apps/ios/Tests/NodeAppModelInvokeTests.swift index f5f40fc8b7cf8..3d015afae84bd 100644 --- a/apps/ios/Tests/NodeAppModelInvokeTests.swift +++ b/apps/ios/Tests/NodeAppModelInvokeTests.swift @@ -42,24 +42,28 @@ private final class MockWatchMessagingService: WatchMessagingServicing, @uncheck queuedForDelivery: false, transport: "sendMessage") var sendError: Error? - var lastSent: (id: String, title: String, body: String, priority: OpenClawNotificationPriority?)? + var lastSent: (id: String, params: OpenClawWatchNotifyParams)? + private var replyHandler: (@Sendable (WatchQuickReplyEvent) -> Void)? func status() async -> WatchMessagingStatus { self.currentStatus } - func sendNotification( - id: String, - title: String, - body: String, - priority: OpenClawNotificationPriority?) async throws -> WatchNotificationSendResult - { - self.lastSent = (id: id, title: title, body: body, priority: priority) + func setReplyHandler(_ handler: (@Sendable (WatchQuickReplyEvent) -> Void)?) { + self.replyHandler = handler + } + + func sendNotification(id: String, params: OpenClawWatchNotifyParams) async throws -> WatchNotificationSendResult { + self.lastSent = (id: id, params: params) if let sendError = self.sendError { throw sendError } return self.nextSendResult } + + func emitReply(_ event: WatchQuickReplyEvent) { + self.replyHandler?(event) + } } @Suite(.serialized) struct NodeAppModelInvokeTests { @@ -77,6 +81,19 @@ private final class MockWatchMessagingService: WatchMessagingServicing, @uncheck #expect(json.contains("\"value\"")) } + @Test @MainActor func chatSessionKeyDefaultsToIOSBase() { + let appModel = NodeAppModel() + #expect(appModel.chatSessionKey == "ios") + } + + @Test @MainActor func chatSessionKeyUsesAgentScopedKeyForNonDefaultAgent() { + let appModel = NodeAppModel() + appModel.gatewayDefaultAgentId = "main" + appModel.setSelectedAgentId("agent-123") + #expect(appModel.chatSessionKey == SessionKey.makeAgentSessionKey(agentId: "agent-123", baseKey: "ios")) + #expect(appModel.mainSessionKey == "agent:agent-123:main") + } + @Test @MainActor func handleInvokeRejectsBackgroundCommands() async { let appModel = NodeAppModel() appModel.setScenePhase(.background) @@ -230,9 +247,9 @@ private final class MockWatchMessagingService: WatchMessagingServicing, @uncheck let res = await appModel._test_handleInvoke(req) #expect(res.ok == true) - #expect(watchService.lastSent?.title == "OpenClaw") - #expect(watchService.lastSent?.body == "Meeting with Peter is at 4pm") - #expect(watchService.lastSent?.priority == .timeSensitive) + #expect(watchService.lastSent?.params.title == "OpenClaw") + #expect(watchService.lastSent?.params.body == "Meeting with Peter is at 4pm") + #expect(watchService.lastSent?.params.priority == .timeSensitive) let payloadData = try #require(res.payloadJSON?.data(using: .utf8)) let payload = try JSONDecoder().decode(OpenClawWatchNotifyPayload.self, from: payloadData) @@ -279,6 +296,22 @@ private final class MockWatchMessagingService: WatchMessagingServicing, @uncheck #expect(res.error?.message.contains("WATCH_UNAVAILABLE") == true) } + @Test @MainActor func watchReplyQueuesWhenGatewayOffline() async { + let watchService = MockWatchMessagingService() + let appModel = NodeAppModel(watchMessagingService: watchService) + watchService.emitReply( + WatchQuickReplyEvent( + replyId: "reply-offline-1", + promptId: "prompt-1", + actionId: "approve", + actionLabel: "Approve", + sessionKey: "ios", + note: nil, + sentAtMs: 1234, + transport: "transferUserInfo")) + #expect(appModel._test_queuedWatchReplyCount() == 1) + } + @Test @MainActor func handleDeepLinkSetsErrorWhenNotConnected() async { let appModel = NodeAppModel() let url = URL(string: "openclaw://agent?message=hello")! diff --git a/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/Contents.json b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000000000..a72027bb4fa60 --- /dev/null +++ b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,116 @@ +{ + "images": [ + { + "idiom": "watch", + "role": "notificationCenter", + "subtype": "38mm", + "size": "24x24", + "scale": "2x", + "filename": "watch-notification-38@2x.png" + }, + { + "idiom": "watch", + "role": "notificationCenter", + "subtype": "42mm", + "size": "27.5x27.5", + "scale": "2x", + "filename": "watch-notification-42@2x.png" + }, + { + "idiom": "watch", + "role": "companionSettings", + "size": "29x29", + "scale": "2x", + "filename": "watch-companion-29@2x.png" + }, + { + "idiom": "watch", + "role": "companionSettings", + "size": "29x29", + "scale": "3x", + "filename": "watch-companion-29@3x.png" + }, + { + "idiom": "watch", + "role": "appLauncher", + "subtype": "38mm", + "size": "40x40", + "scale": "2x", + "filename": "watch-app-38@2x.png" + }, + { + "idiom": "watch", + "role": "appLauncher", + "subtype": "40mm", + "size": "44x44", + "scale": "2x", + "filename": "watch-app-40@2x.png" + }, + { + "idiom": "watch", + "role": "appLauncher", + "subtype": "41mm", + "size": "46x46", + "scale": "2x", + "filename": "watch-app-41@2x.png" + }, + { + "idiom": "watch", + "role": "appLauncher", + "subtype": "44mm", + "size": "50x50", + "scale": "2x", + "filename": "watch-app-44@2x.png" + }, + { + "idiom": "watch", + "role": "appLauncher", + "subtype": "45mm", + "size": "51x51", + "scale": "2x", + "filename": "watch-app-45@2x.png" + }, + { + "idiom": "watch", + "role": "quickLook", + "subtype": "38mm", + "size": "86x86", + "scale": "2x", + "filename": "watch-quicklook-38@2x.png" + }, + { + "idiom": "watch", + "role": "quickLook", + "subtype": "42mm", + "size": "98x98", + "scale": "2x", + "filename": "watch-quicklook-42@2x.png" + }, + { + "idiom": "watch", + "role": "quickLook", + "subtype": "44mm", + "size": "108x108", + "scale": "2x", + "filename": "watch-quicklook-44@2x.png" + }, + { + "idiom": "watch", + "role": "quickLook", + "subtype": "45mm", + "size": "117x117", + "scale": "2x", + "filename": "watch-quicklook-45@2x.png" + }, + { + "idiom": "watch-marketing", + "size": "1024x1024", + "scale": "1x", + "filename": "watch-marketing-1024.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +} diff --git a/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-app-38@2x.png b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-app-38@2x.png new file mode 100644 index 0000000000000..82829afb947e2 Binary files /dev/null and b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-app-38@2x.png differ diff --git a/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-app-40@2x.png b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-app-40@2x.png new file mode 100644 index 0000000000000..114d4606420cb Binary files /dev/null and b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-app-40@2x.png differ diff --git a/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-app-41@2x.png b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-app-41@2x.png new file mode 100644 index 0000000000000..5f9578b1b9751 Binary files /dev/null and b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-app-41@2x.png differ diff --git a/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-app-44@2x.png b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-app-44@2x.png new file mode 100644 index 0000000000000..fe022ac772005 Binary files /dev/null and b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-app-44@2x.png differ diff --git a/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-app-45@2x.png b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-app-45@2x.png new file mode 100644 index 0000000000000..55977b8f6e75c Binary files /dev/null and b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-app-45@2x.png differ diff --git a/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-companion-29@2x.png b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-companion-29@2x.png new file mode 100644 index 0000000000000..f8be7d06911e9 Binary files /dev/null and b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-companion-29@2x.png differ diff --git a/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-companion-29@3x.png b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-companion-29@3x.png new file mode 100644 index 0000000000000..cce412d2452b7 Binary files /dev/null and b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-companion-29@3x.png differ diff --git a/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-marketing-1024.png b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-marketing-1024.png new file mode 100644 index 0000000000000..005486f2ee12c Binary files /dev/null and b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-marketing-1024.png differ diff --git a/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-notification-38@2x.png b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-notification-38@2x.png new file mode 100644 index 0000000000000..7b7a0ee0b65b5 Binary files /dev/null and b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-notification-38@2x.png differ diff --git a/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-notification-42@2x.png b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-notification-42@2x.png new file mode 100644 index 0000000000000..f13c9cdddda0f Binary files /dev/null and b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-notification-42@2x.png differ diff --git a/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-quicklook-38@2x.png b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-quicklook-38@2x.png new file mode 100644 index 0000000000000..aac0859b44c6e Binary files /dev/null and b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-quicklook-38@2x.png differ diff --git a/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-quicklook-42@2x.png b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-quicklook-42@2x.png new file mode 100644 index 0000000000000..d09be6e98a6a1 Binary files /dev/null and b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-quicklook-42@2x.png differ diff --git a/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-quicklook-44@2x.png b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-quicklook-44@2x.png new file mode 100644 index 0000000000000..5b06a48744bff Binary files /dev/null and b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-quicklook-44@2x.png differ diff --git a/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-quicklook-45@2x.png b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-quicklook-45@2x.png new file mode 100644 index 0000000000000..72ba51ebb1d8c Binary files /dev/null and b/apps/ios/WatchApp/Assets.xcassets/AppIcon.appiconset/watch-quicklook-45@2x.png differ diff --git a/apps/ios/WatchApp/Assets.xcassets/Contents.json b/apps/ios/WatchApp/Assets.xcassets/Contents.json new file mode 100644 index 0000000000000..97a8662ebdb43 --- /dev/null +++ b/apps/ios/WatchApp/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info": { + "version": 1, + "author": "xcode" + } +} diff --git a/apps/ios/WatchApp/Info.plist b/apps/ios/WatchApp/Info.plist index 2c1d88f30a78f..cc5dbf6cdda1b 100644 --- a/apps/ios/WatchApp/Info.plist +++ b/apps/ios/WatchApp/Info.plist @@ -17,9 +17,9 @@ CFBundlePackageType APPL CFBundleShortVersionString - 2026.2.18 + 2026.2.21 CFBundleVersion - 20260218 + 20260220 WKCompanionAppBundleIdentifier $(OPENCLAW_APP_BUNDLE_ID) WKWatchKitApp diff --git a/apps/ios/WatchExtension/Info.plist b/apps/ios/WatchExtension/Info.plist index e401494d22520..2d6b7baa7b872 100644 --- a/apps/ios/WatchExtension/Info.plist +++ b/apps/ios/WatchExtension/Info.plist @@ -15,9 +15,9 @@ CFBundleName $(PRODUCT_NAME) CFBundleShortVersionString - 2026.2.18 + 2026.2.21 CFBundleVersion - 20260218 + 20260220 NSExtension NSExtensionAttributes diff --git a/apps/ios/WatchExtension/Sources/OpenClawWatchApp.swift b/apps/ios/WatchExtension/Sources/OpenClawWatchApp.swift index 6084f5744422b..4c123c49f16b2 100644 --- a/apps/ios/WatchExtension/Sources/OpenClawWatchApp.swift +++ b/apps/ios/WatchExtension/Sources/OpenClawWatchApp.swift @@ -7,7 +7,15 @@ struct OpenClawWatchApp: App { var body: some Scene { WindowGroup { - WatchInboxView(store: self.inboxStore) + WatchInboxView(store: self.inboxStore) { action in + guard let receiver = self.receiver else { return } + let draft = self.inboxStore.makeReplyDraft(action: action) + self.inboxStore.markReplySending(actionLabel: action.label) + Task { @MainActor in + let result = await receiver.sendReply(draft) + self.inboxStore.markReplyResult(result, actionLabel: action.label) + } + } .task { if self.receiver == nil { let receiver = WatchConnectivityReceiver(store: self.inboxStore) diff --git a/apps/ios/WatchExtension/Sources/WatchConnectivityReceiver.swift b/apps/ios/WatchExtension/Sources/WatchConnectivityReceiver.swift index fd0d84cc55c80..da1c3c379a352 100644 --- a/apps/ios/WatchExtension/Sources/WatchConnectivityReceiver.swift +++ b/apps/ios/WatchExtension/Sources/WatchConnectivityReceiver.swift @@ -1,6 +1,23 @@ import Foundation import WatchConnectivity +struct WatchReplyDraft: Sendable { + var replyId: String + var promptId: String + var actionId: String + var actionLabel: String? + var sessionKey: String? + var note: String? + var sentAtMs: Int +} + +struct WatchReplySendResult: Sendable, Equatable { + var deliveredImmediately: Bool + var queuedForDelivery: Bool + var transport: String + var errorMessage: String? +} + final class WatchConnectivityReceiver: NSObject, @unchecked Sendable { private let store: WatchInboxStore private let session: WCSession? @@ -21,6 +38,114 @@ final class WatchConnectivityReceiver: NSObject, @unchecked Sendable { session.activate() } + private func ensureActivated() async { + guard let session = self.session else { return } + if session.activationState == .activated { + return + } + session.activate() + for _ in 0..<8 { + if session.activationState == .activated { + return + } + try? await Task.sleep(nanoseconds: 100_000_000) + } + } + + func sendReply(_ draft: WatchReplyDraft) async -> WatchReplySendResult { + await self.ensureActivated() + guard let session = self.session else { + return WatchReplySendResult( + deliveredImmediately: false, + queuedForDelivery: false, + transport: "none", + errorMessage: "watch session unavailable") + } + + var payload: [String: Any] = [ + "type": "watch.reply", + "replyId": draft.replyId, + "promptId": draft.promptId, + "actionId": draft.actionId, + "sentAtMs": draft.sentAtMs, + ] + if let actionLabel = draft.actionLabel?.trimmingCharacters(in: .whitespacesAndNewlines), + !actionLabel.isEmpty + { + payload["actionLabel"] = actionLabel + } + if let sessionKey = draft.sessionKey?.trimmingCharacters(in: .whitespacesAndNewlines), + !sessionKey.isEmpty + { + payload["sessionKey"] = sessionKey + } + if let note = draft.note?.trimmingCharacters(in: .whitespacesAndNewlines), !note.isEmpty { + payload["note"] = note + } + + if session.isReachable { + do { + try await withCheckedThrowingContinuation { continuation in + session.sendMessage(payload, replyHandler: { _ in + continuation.resume() + }, errorHandler: { error in + continuation.resume(throwing: error) + }) + } + return WatchReplySendResult( + deliveredImmediately: true, + queuedForDelivery: false, + transport: "sendMessage", + errorMessage: nil) + } catch { + // Fall through to queued delivery below. + } + } + + _ = session.transferUserInfo(payload) + return WatchReplySendResult( + deliveredImmediately: false, + queuedForDelivery: true, + transport: "transferUserInfo", + errorMessage: nil) + } + + private static func normalizeObject(_ value: Any) -> [String: Any]? { + if let object = value as? [String: Any] { + return object + } + if let object = value as? [AnyHashable: Any] { + var normalized: [String: Any] = [:] + normalized.reserveCapacity(object.count) + for (key, item) in object { + guard let stringKey = key as? String else { + continue + } + normalized[stringKey] = item + } + return normalized + } + return nil + } + + private static func parseActions(_ value: Any?) -> [WatchPromptAction] { + guard let raw = value as? [Any] else { + return [] + } + return raw.compactMap { item in + guard let obj = Self.normalizeObject(item) else { + return nil + } + let id = (obj["id"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + let label = (obj["label"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + guard !id.isEmpty, !label.isEmpty else { + return nil + } + let style = (obj["style"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) + return WatchPromptAction(id: id, label: label, style: style) + } + } + private static func parseNotificationPayload(_ payload: [String: Any]) -> WatchNotifyMessage? { guard let type = payload["type"] as? String, type == "watch.notify" else { return nil @@ -38,12 +163,31 @@ final class WatchConnectivityReceiver: NSObject, @unchecked Sendable { let id = (payload["id"] as? String)? .trimmingCharacters(in: .whitespacesAndNewlines) let sentAtMs = (payload["sentAtMs"] as? Int) ?? (payload["sentAtMs"] as? NSNumber)?.intValue + let promptId = (payload["promptId"] as? String)? + .trimmingCharacters(in: .whitespacesAndNewlines) + let sessionKey = (payload["sessionKey"] as? String)? + .trimmingCharacters(in: .whitespacesAndNewlines) + let kind = (payload["kind"] as? String)? + .trimmingCharacters(in: .whitespacesAndNewlines) + let details = (payload["details"] as? String)? + .trimmingCharacters(in: .whitespacesAndNewlines) + let expiresAtMs = (payload["expiresAtMs"] as? Int) ?? (payload["expiresAtMs"] as? NSNumber)?.intValue + let risk = (payload["risk"] as? String)? + .trimmingCharacters(in: .whitespacesAndNewlines) + let actions = Self.parseActions(payload["actions"]) return WatchNotifyMessage( id: id, title: title, body: body, - sentAtMs: sentAtMs) + sentAtMs: sentAtMs, + promptId: promptId, + sessionKey: sessionKey, + kind: kind, + details: details, + expiresAtMs: expiresAtMs, + risk: risk, + actions: actions) } } diff --git a/apps/ios/WatchExtension/Sources/WatchInboxStore.swift b/apps/ios/WatchExtension/Sources/WatchInboxStore.swift index 0a715f16b63e0..2ac1d75d6e104 100644 --- a/apps/ios/WatchExtension/Sources/WatchInboxStore.swift +++ b/apps/ios/WatchExtension/Sources/WatchInboxStore.swift @@ -3,11 +3,24 @@ import Observation import UserNotifications import WatchKit +struct WatchPromptAction: Codable, Sendable, Equatable, Identifiable { + var id: String + var label: String + var style: String? +} + struct WatchNotifyMessage: Sendable { var id: String? var title: String var body: String var sentAtMs: Int? + var promptId: String? + var sessionKey: String? + var kind: String? + var details: String? + var expiresAtMs: Int? + var risk: String? + var actions: [WatchPromptAction] } @MainActor @Observable final class WatchInboxStore { @@ -17,6 +30,15 @@ struct WatchNotifyMessage: Sendable { var transport: String var updatedAt: Date var lastDeliveryKey: String? + var promptId: String? + var sessionKey: String? + var kind: String? + var details: String? + var expiresAtMs: Int? + var risk: String? + var actions: [WatchPromptAction]? + var replyStatusText: String? + var replyStatusAt: Date? } private static let persistedStateKey = "watch.inbox.state.v1" @@ -26,6 +48,16 @@ struct WatchNotifyMessage: Sendable { var body = "Waiting for messages from your iPhone." var transport = "none" var updatedAt: Date? + var promptId: String? + var sessionKey: String? + var kind: String? + var details: String? + var expiresAtMs: Int? + var risk: String? + var actions: [WatchPromptAction] = [] + var replyStatusText: String? + var replyStatusAt: Date? + var isReplySending = false private var lastDeliveryKey: String? init(defaults: UserDefaults = .standard) { @@ -51,14 +83,25 @@ struct WatchNotifyMessage: Sendable { self.body = message.body self.transport = transport self.updatedAt = Date() + self.promptId = message.promptId + self.sessionKey = message.sessionKey + self.kind = message.kind + self.details = message.details + self.expiresAtMs = message.expiresAtMs + self.risk = message.risk + self.actions = message.actions self.lastDeliveryKey = deliveryKey + self.replyStatusText = nil + self.replyStatusAt = nil + self.isReplySending = false self.persistState() Task { await self.postLocalNotification( identifier: deliveryKey, title: normalizedTitle, - body: message.body) + body: message.body, + risk: message.risk) } } @@ -74,6 +117,15 @@ struct WatchNotifyMessage: Sendable { self.transport = state.transport self.updatedAt = state.updatedAt self.lastDeliveryKey = state.lastDeliveryKey + self.promptId = state.promptId + self.sessionKey = state.sessionKey + self.kind = state.kind + self.details = state.details + self.expiresAtMs = state.expiresAtMs + self.risk = state.risk + self.actions = state.actions ?? [] + self.replyStatusText = state.replyStatusText + self.replyStatusAt = state.replyStatusAt } private func persistState() { @@ -83,7 +135,16 @@ struct WatchNotifyMessage: Sendable { body: self.body, transport: self.transport, updatedAt: updatedAt, - lastDeliveryKey: self.lastDeliveryKey) + lastDeliveryKey: self.lastDeliveryKey, + promptId: self.promptId, + sessionKey: self.sessionKey, + kind: self.kind, + details: self.details, + expiresAtMs: self.expiresAtMs, + risk: self.risk, + actions: self.actions, + replyStatusText: self.replyStatusText, + replyStatusAt: self.replyStatusAt) guard let data = try? JSONEncoder().encode(state) else { return } self.defaults.set(data, forKey: Self.persistedStateKey) } @@ -106,7 +167,52 @@ struct WatchNotifyMessage: Sendable { } } - private func postLocalNotification(identifier: String, title: String, body: String) async { + private func mapHapticRisk(_ risk: String?) -> WKHapticType { + switch risk?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() { + case "high": + return .failure + case "medium": + return .notification + default: + return .click + } + } + + func makeReplyDraft(action: WatchPromptAction) -> WatchReplyDraft { + let prompt = self.promptId?.trimmingCharacters(in: .whitespacesAndNewlines) + return WatchReplyDraft( + replyId: UUID().uuidString, + promptId: (prompt?.isEmpty == false) ? prompt! : "unknown", + actionId: action.id, + actionLabel: action.label, + sessionKey: self.sessionKey, + note: nil, + sentAtMs: Int(Date().timeIntervalSince1970 * 1000)) + } + + func markReplySending(actionLabel: String) { + self.isReplySending = true + self.replyStatusText = "Sending \(actionLabel)…" + self.replyStatusAt = Date() + self.persistState() + } + + func markReplyResult(_ result: WatchReplySendResult, actionLabel: String) { + self.isReplySending = false + if let errorMessage = result.errorMessage, !errorMessage.isEmpty { + self.replyStatusText = "Failed: \(errorMessage)" + } else if result.deliveredImmediately { + self.replyStatusText = "\(actionLabel): sent" + } else if result.queuedForDelivery { + self.replyStatusText = "\(actionLabel): queued" + } else { + self.replyStatusText = "\(actionLabel): sent" + } + self.replyStatusAt = Date() + self.persistState() + } + + private func postLocalNotification(identifier: String, title: String, body: String, risk: String?) async { let content = UNMutableNotificationContent() content.title = title content.body = body @@ -119,6 +225,6 @@ struct WatchNotifyMessage: Sendable { trigger: UNTimeIntervalNotificationTrigger(timeInterval: 0.2, repeats: false)) _ = try? await UNUserNotificationCenter.current().add(request) - WKInterfaceDevice.current().play(.notification) + WKInterfaceDevice.current().play(self.mapHapticRisk(risk)) } } diff --git a/apps/ios/WatchExtension/Sources/WatchInboxView.swift b/apps/ios/WatchExtension/Sources/WatchInboxView.swift index c5ea9a9f534d9..c6f944a949ec6 100644 --- a/apps/ios/WatchExtension/Sources/WatchInboxView.swift +++ b/apps/ios/WatchExtension/Sources/WatchInboxView.swift @@ -2,6 +2,18 @@ import SwiftUI struct WatchInboxView: View { @Bindable var store: WatchInboxStore + var onAction: ((WatchPromptAction) -> Void)? + + private func role(for action: WatchPromptAction) -> ButtonRole? { + switch action.style?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() { + case "destructive": + return .destructive + case "cancel": + return .cancel + default: + return nil + } + } var body: some View { ScrollView { @@ -14,6 +26,31 @@ struct WatchInboxView: View { .font(.body) .fixedSize(horizontal: false, vertical: true) + if let details = store.details, !details.isEmpty { + Text(details) + .font(.footnote) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + + if !store.actions.isEmpty { + ForEach(store.actions) { action in + Button(role: self.role(for: action)) { + self.onAction?(action) + } label: { + Text(action.label) + .frame(maxWidth: .infinity) + } + .disabled(store.isReplySending) + } + } + + if let replyStatusText = store.replyStatusText, !replyStatusText.isEmpty { + Text(replyStatusText) + .font(.footnote) + .foregroundStyle(.secondary) + } + if let updatedAt = store.updatedAt { Text("Updated \(updatedAt.formatted(date: .omitted, time: .shortened))") .font(.footnote) diff --git a/apps/ios/project.yml b/apps/ios/project.yml index cd543c59430ad..613322f3e8ed0 100644 --- a/apps/ios/project.yml +++ b/apps/ios/project.yml @@ -92,14 +92,16 @@ targets: - CFBundleURLName: ai.openclaw.ios CFBundleURLSchemes: - openclaw - CFBundleShortVersionString: "2026.2.18" - CFBundleVersion: "20260218" + CFBundleShortVersionString: "2026.2.21" + CFBundleVersion: "20260220" UILaunchScreen: {} UIApplicationSceneManifest: UIApplicationSupportsMultipleScenes: false UIBackgroundModes: - audio - remote-notification + BGTaskSchedulerPermittedIdentifiers: + - ai.openclaw.ios.bgrefresh NSLocalNetworkUsageDescription: OpenClaw discovers and connects to your OpenClaw gateway on the local network. NSAppTransportSecurity: NSAllowsArbitraryLoadsInWebContent: true @@ -144,8 +146,8 @@ targets: path: ShareExtension/Info.plist properties: CFBundleDisplayName: OpenClaw Share - CFBundleShortVersionString: "2026.2.18" - CFBundleVersion: "20260218" + CFBundleShortVersionString: "2026.2.21" + CFBundleVersion: "20260220" NSExtension: NSExtensionPointIdentifier: com.apple.share-services NSExtensionPrincipalClass: "$(PRODUCT_MODULE_NAME).ShareViewController" @@ -174,8 +176,8 @@ targets: path: WatchApp/Info.plist properties: CFBundleDisplayName: OpenClaw - CFBundleShortVersionString: "2026.2.18" - CFBundleVersion: "20260218" + CFBundleShortVersionString: "2026.2.21" + CFBundleVersion: "20260220" WKCompanionAppBundleIdentifier: "$(OPENCLAW_APP_BUNDLE_ID)" WKWatchKitApp: true @@ -198,8 +200,8 @@ targets: path: WatchExtension/Info.plist properties: CFBundleDisplayName: OpenClaw - CFBundleShortVersionString: "2026.2.18" - CFBundleVersion: "20260218" + CFBundleShortVersionString: "2026.2.21" + CFBundleVersion: "20260220" NSExtension: NSExtensionAttributes: WKAppBundleIdentifier: "$(OPENCLAW_WATCH_APP_BUNDLE_ID)" @@ -226,5 +228,5 @@ targets: path: Tests/Info.plist properties: CFBundleDisplayName: OpenClawTests - CFBundleShortVersionString: "2026.2.18" - CFBundleVersion: "20260218" + CFBundleShortVersionString: "2026.2.21" + CFBundleVersion: "20260220" diff --git a/apps/macos/Sources/OpenClaw/AppState.swift b/apps/macos/Sources/OpenClaw/AppState.swift index d960d3c038a75..e9ca6c3535973 100644 --- a/apps/macos/Sources/OpenClaw/AppState.swift +++ b/apps/macos/Sources/OpenClaw/AppState.swift @@ -480,8 +480,7 @@ final class AppState { remote.removeValue(forKey: "url") remoteChanged = true } - } else { - let normalizedUrl = GatewayRemoteConfig.normalizeGatewayUrlString(trimmedUrl) ?? trimmedUrl + } else if let normalizedUrl = GatewayRemoteConfig.normalizeGatewayUrlString(trimmedUrl) { if (remote["url"] as? String) != normalizedUrl { remote["url"] = normalizedUrl remoteChanged = true diff --git a/apps/macos/Sources/OpenClaw/CameraCaptureService.swift b/apps/macos/Sources/OpenClaw/CameraCaptureService.swift index 24717ec553631..4e3749d6a68da 100644 --- a/apps/macos/Sources/OpenClaw/CameraCaptureService.swift +++ b/apps/macos/Sources/OpenClaw/CameraCaptureService.swift @@ -357,8 +357,8 @@ private final class PhotoCaptureDelegate: NSObject, AVCapturePhotoCaptureDelegat func photoOutput( _ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, - error: Error? - ) { + error: Error?) + { guard !self.didResume, let cont else { return } self.didResume = true self.cont = nil @@ -380,8 +380,8 @@ private final class PhotoCaptureDelegate: NSObject, AVCapturePhotoCaptureDelegat func photoOutput( _ output: AVCapturePhotoOutput, didFinishCaptureFor resolvedSettings: AVCaptureResolvedPhotoSettings, - error: Error? - ) { + error: Error?) + { guard let error else { return } guard !self.didResume, let cont else { return } self.didResume = true diff --git a/apps/macos/Sources/OpenClaw/CoalescingFSEventsWatcher.swift b/apps/macos/Sources/OpenClaw/CoalescingFSEventsWatcher.swift index 7999123dbe2f2..f9e38d81170fd 100644 --- a/apps/macos/Sources/OpenClaw/CoalescingFSEventsWatcher.swift +++ b/apps/macos/Sources/OpenClaw/CoalescingFSEventsWatcher.swift @@ -16,8 +16,8 @@ final class CoalescingFSEventsWatcher: @unchecked Sendable { queueLabel: String, coalesceDelay: TimeInterval = 0.12, shouldNotify: @escaping (Int, UnsafeMutableRawPointer?) -> Bool = { _, _ in true }, - onChange: @escaping () -> Void - ) { + onChange: @escaping () -> Void) + { self.paths = paths self.queue = DispatchQueue(label: queueLabel) self.coalesceDelay = coalesceDelay @@ -92,8 +92,8 @@ extension CoalescingFSEventsWatcher { private func handleEvents( numEvents: Int, eventPaths: UnsafeMutableRawPointer?, - eventFlags: UnsafePointer? - ) { + eventFlags: UnsafePointer?) + { guard numEvents > 0 else { return } guard eventFlags != nil else { return } guard self.shouldNotify(numEvents, eventPaths) else { return } @@ -108,4 +108,3 @@ extension CoalescingFSEventsWatcher { } } } - diff --git a/apps/macos/Sources/OpenClaw/ExecAllowlistMatcher.swift b/apps/macos/Sources/OpenClaw/ExecAllowlistMatcher.swift new file mode 100644 index 0000000000000..2dd720741bbbd --- /dev/null +++ b/apps/macos/Sources/OpenClaw/ExecAllowlistMatcher.swift @@ -0,0 +1,79 @@ +import Foundation + +enum ExecAllowlistMatcher { + static func match(entries: [ExecAllowlistEntry], resolution: ExecCommandResolution?) -> ExecAllowlistEntry? { + guard let resolution, !entries.isEmpty else { return nil } + let rawExecutable = resolution.rawExecutable + let resolvedPath = resolution.resolvedPath + + for entry in entries { + switch ExecApprovalHelpers.validateAllowlistPattern(entry.pattern) { + case .valid(let pattern): + let target = resolvedPath ?? rawExecutable + if self.matches(pattern: pattern, target: target) { return entry } + case .invalid: + continue + } + } + return nil + } + + static func matchAll( + entries: [ExecAllowlistEntry], + resolutions: [ExecCommandResolution]) -> [ExecAllowlistEntry] + { + guard !entries.isEmpty, !resolutions.isEmpty else { return [] } + var matches: [ExecAllowlistEntry] = [] + matches.reserveCapacity(resolutions.count) + for resolution in resolutions { + guard let match = self.match(entries: entries, resolution: resolution) else { + return [] + } + matches.append(match) + } + return matches + } + + private static func matches(pattern: String, target: String) -> Bool { + let trimmed = pattern.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return false } + let expanded = trimmed.hasPrefix("~") ? (trimmed as NSString).expandingTildeInPath : trimmed + let normalizedPattern = self.normalizeMatchTarget(expanded) + let normalizedTarget = self.normalizeMatchTarget(target) + guard let regex = self.regex(for: normalizedPattern) else { return false } + let range = NSRange(location: 0, length: normalizedTarget.utf16.count) + return regex.firstMatch(in: normalizedTarget, options: [], range: range) != nil + } + + private static func normalizeMatchTarget(_ value: String) -> String { + value.replacingOccurrences(of: "\\\\", with: "/").lowercased() + } + + private static func regex(for pattern: String) -> NSRegularExpression? { + var regex = "^" + var idx = pattern.startIndex + while idx < pattern.endIndex { + let ch = pattern[idx] + if ch == "*" { + let next = pattern.index(after: idx) + if next < pattern.endIndex, pattern[next] == "*" { + regex += ".*" + idx = pattern.index(after: next) + } else { + regex += "[^/]*" + idx = next + } + continue + } + if ch == "?" { + regex += "." + idx = pattern.index(after: idx) + continue + } + regex += NSRegularExpression.escapedPattern(for: String(ch)) + idx = pattern.index(after: idx) + } + regex += "$" + return try? NSRegularExpression(pattern: regex, options: [.caseInsensitive]) + } +} diff --git a/apps/macos/Sources/OpenClaw/ExecApprovalEvaluation.swift b/apps/macos/Sources/OpenClaw/ExecApprovalEvaluation.swift new file mode 100644 index 0000000000000..c7d9d0928e14d --- /dev/null +++ b/apps/macos/Sources/OpenClaw/ExecApprovalEvaluation.swift @@ -0,0 +1,68 @@ +import Foundation + +struct ExecApprovalEvaluation { + let command: [String] + let displayCommand: String + let agentId: String? + let security: ExecSecurity + let ask: ExecAsk + let env: [String: String] + let resolution: ExecCommandResolution? + let allowlistResolutions: [ExecCommandResolution] + let allowlistMatches: [ExecAllowlistEntry] + let allowlistSatisfied: Bool + let allowlistMatch: ExecAllowlistEntry? + let skillAllow: Bool +} + +enum ExecApprovalEvaluator { + static func evaluate( + command: [String], + rawCommand: String?, + cwd: String?, + envOverrides: [String: String]?, + agentId: String?) async -> ExecApprovalEvaluation + { + let trimmedAgent = agentId?.trimmingCharacters(in: .whitespacesAndNewlines) + let normalizedAgentId = (trimmedAgent?.isEmpty == false) ? trimmedAgent : nil + let approvals = ExecApprovalsStore.resolve(agentId: normalizedAgentId) + let security = approvals.agent.security + let ask = approvals.agent.ask + let shellWrapper = ExecShellWrapperParser.extract(command: command, rawCommand: rawCommand).isWrapper + let env = HostEnvSanitizer.sanitize(overrides: envOverrides, shellWrapper: shellWrapper) + let displayCommand = ExecCommandFormatter.displayString(for: command, rawCommand: rawCommand) + let allowlistResolutions = ExecCommandResolution.resolveForAllowlist( + command: command, + rawCommand: rawCommand, + cwd: cwd, + env: env) + let allowlistMatches = security == .allowlist + ? ExecAllowlistMatcher.matchAll(entries: approvals.allowlist, resolutions: allowlistResolutions) + : [] + let allowlistSatisfied = security == .allowlist && + !allowlistResolutions.isEmpty && + allowlistMatches.count == allowlistResolutions.count + + let skillAllow: Bool + if approvals.agent.autoAllowSkills, !allowlistResolutions.isEmpty { + let bins = await SkillBinsCache.shared.currentBins() + skillAllow = allowlistResolutions.allSatisfy { bins.contains($0.executableName) } + } else { + skillAllow = false + } + + return ExecApprovalEvaluation( + command: command, + displayCommand: displayCommand, + agentId: normalizedAgentId, + security: security, + ask: ask, + env: env, + resolution: allowlistResolutions.first, + allowlistResolutions: allowlistResolutions, + allowlistMatches: allowlistMatches, + allowlistSatisfied: allowlistSatisfied, + allowlistMatch: allowlistSatisfied ? allowlistMatches.first : nil, + skillAllow: skillAllow) + } +} diff --git a/apps/macos/Sources/OpenClaw/ExecApprovals.swift b/apps/macos/Sources/OpenClaw/ExecApprovals.swift index f6bc839250385..08567cd0b09a5 100644 --- a/apps/macos/Sources/OpenClaw/ExecApprovals.swift +++ b/apps/macos/Sources/OpenClaw/ExecApprovals.swift @@ -90,6 +90,31 @@ enum ExecApprovalDecision: String, Codable, Sendable { case deny } +enum ExecAllowlistPatternValidationReason: String, Codable, Sendable, Equatable { + case empty + case missingPathComponent + + var message: String { + switch self { + case .empty: + "Pattern cannot be empty." + case .missingPathComponent: + "Path patterns only. Include '/', '~', or '\\\\'." + } + } +} + +enum ExecAllowlistPatternValidation: Sendable, Equatable { + case valid(String) + case invalid(ExecAllowlistPatternValidationReason) +} + +struct ExecAllowlistRejectedEntry: Sendable, Equatable { + let id: UUID + let pattern: String + let reason: ExecAllowlistPatternValidationReason +} + struct ExecAllowlistEntry: Codable, Hashable, Identifiable { var id: UUID var pattern: String @@ -222,13 +247,25 @@ enum ExecApprovalsStore { } agents.removeValue(forKey: "default") } + if !agents.isEmpty { + var normalizedAgents: [String: ExecApprovalsAgent] = [:] + normalizedAgents.reserveCapacity(agents.count) + for (key, var agent) in agents { + if let allowlist = agent.allowlist { + let normalized = self.normalizeAllowlistEntries(allowlist, dropInvalid: false).entries + agent.allowlist = normalized.isEmpty ? nil : normalized + } + normalizedAgents[key] = agent + } + agents = normalizedAgents + } return ExecApprovalsFile( version: 1, socket: ExecApprovalsSocketConfig( path: socketPath.isEmpty ? nil : socketPath, token: token.isEmpty ? nil : token), defaults: file.defaults, - agents: agents) + agents: agents.isEmpty ? nil : agents) } static func readSnapshot() -> ExecApprovalsSnapshot { @@ -306,7 +343,12 @@ enum ExecApprovalsStore { } static func ensureFile() -> ExecApprovalsFile { - var file = self.loadFile() + let url = self.fileURL() + let existed = FileManager().fileExists(atPath: url.path) + let loaded = self.loadFile() + let loadedHash = self.hashFile(loaded) + + var file = self.normalizeIncoming(loaded) if file.socket == nil { file.socket = ExecApprovalsSocketConfig(path: nil, token: nil) } let path = file.socket?.path?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" if path.isEmpty { @@ -317,7 +359,9 @@ enum ExecApprovalsStore { file.socket?.token = self.generateToken() } if file.agents == nil { file.agents = [:] } - self.saveFile(file) + if !existed || loadedHash != self.hashFile(file) { + self.saveFile(file) + } return file } @@ -339,16 +383,9 @@ enum ExecApprovalsStore { ?? resolvedDefaults.askFallback, autoAllowSkills: agentEntry.autoAllowSkills ?? wildcardEntry.autoAllowSkills ?? resolvedDefaults.autoAllowSkills) - let allowlist = ((wildcardEntry.allowlist ?? []) + (agentEntry.allowlist ?? [])) - .map { entry in - ExecAllowlistEntry( - id: entry.id, - pattern: entry.pattern.trimmingCharacters(in: .whitespacesAndNewlines), - lastUsedAt: entry.lastUsedAt, - lastUsedCommand: entry.lastUsedCommand, - lastResolvedPath: entry.lastResolvedPath) - } - .filter { !$0.pattern.isEmpty } + let allowlist = self.normalizeAllowlistEntries( + (wildcardEntry.allowlist ?? []) + (agentEntry.allowlist ?? []), + dropInvalid: true).entries let socketPath = self.expandPath(file.socket?.path ?? self.socketPath()) let token = file.socket?.token ?? "" return ExecApprovalsResolved( @@ -398,20 +435,30 @@ enum ExecApprovalsStore { } } - static func addAllowlistEntry(agentId: String?, pattern: String) { - let trimmed = pattern.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { return } + @discardableResult + static func addAllowlistEntry(agentId: String?, pattern: String) -> ExecAllowlistPatternValidationReason? { + let normalizedPattern: String + switch ExecApprovalHelpers.validateAllowlistPattern(pattern) { + case .valid(let validPattern): + normalizedPattern = validPattern + case .invalid(let reason): + return reason + } + self.updateFile { file in let key = self.agentKey(agentId) var agents = file.agents ?? [:] var entry = agents[key] ?? ExecApprovalsAgent() var allowlist = entry.allowlist ?? [] - if allowlist.contains(where: { $0.pattern == trimmed }) { return } - allowlist.append(ExecAllowlistEntry(pattern: trimmed, lastUsedAt: Date().timeIntervalSince1970 * 1000)) + if allowlist.contains(where: { $0.pattern == normalizedPattern }) { return } + allowlist.append(ExecAllowlistEntry( + pattern: normalizedPattern, + lastUsedAt: Date().timeIntervalSince1970 * 1000)) entry.allowlist = allowlist agents[key] = entry file.agents = agents } + return nil } static func recordAllowlistUse( @@ -439,25 +486,21 @@ enum ExecApprovalsStore { } } - static func updateAllowlist(agentId: String?, allowlist: [ExecAllowlistEntry]) { + @discardableResult + static func updateAllowlist(agentId: String?, allowlist: [ExecAllowlistEntry]) -> [ExecAllowlistRejectedEntry] { + var rejected: [ExecAllowlistRejectedEntry] = [] self.updateFile { file in let key = self.agentKey(agentId) var agents = file.agents ?? [:] var entry = agents[key] ?? ExecApprovalsAgent() - let cleaned = allowlist - .map { item in - ExecAllowlistEntry( - id: item.id, - pattern: item.pattern.trimmingCharacters(in: .whitespacesAndNewlines), - lastUsedAt: item.lastUsedAt, - lastUsedCommand: item.lastUsedCommand, - lastResolvedPath: item.lastResolvedPath) - } - .filter { !$0.pattern.isEmpty } + let normalized = self.normalizeAllowlistEntries(allowlist, dropInvalid: true) + rejected = normalized.rejected + let cleaned = normalized.entries entry.allowlist = cleaned agents[key] = entry file.agents = agents } + return rejected } static func updateAgentSettings(agentId: String?, mutate: (inout ExecApprovalsAgent) -> Void) { @@ -500,6 +543,14 @@ enum ExecApprovalsStore { return digest.map { String(format: "%02x", $0) }.joined() } + private static func hashFile(_ file: ExecApprovalsFile) -> String { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + let data = (try? encoder.encode(file)) ?? Data() + let digest = SHA256.hash(data: data) + return digest.map { String(format: "%02x", $0) }.joined() + } + private static func expandPath(_ raw: String) -> String { let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) if trimmed == "~" { @@ -519,14 +570,101 @@ enum ExecApprovalsStore { } private static func normalizedPattern(_ pattern: String?) -> String? { - let trimmed = pattern?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - return trimmed.isEmpty ? nil : trimmed.lowercased() + switch ExecApprovalHelpers.validateAllowlistPattern(pattern) { + case .valid(let normalized): + return normalized.lowercased() + case .invalid(.empty): + return nil + case .invalid: + let trimmed = pattern?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + return trimmed.isEmpty ? nil : trimmed.lowercased() + } + } + + private static func migrateLegacyPattern(_ entry: ExecAllowlistEntry) -> ExecAllowlistEntry { + let trimmedPattern = entry.pattern.trimmingCharacters(in: .whitespacesAndNewlines) + let trimmedResolved = entry.lastResolvedPath?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + let normalizedResolved = trimmedResolved.isEmpty ? nil : trimmedResolved + + switch ExecApprovalHelpers.validateAllowlistPattern(trimmedPattern) { + case .valid(let pattern): + return ExecAllowlistEntry( + id: entry.id, + pattern: pattern, + lastUsedAt: entry.lastUsedAt, + lastUsedCommand: entry.lastUsedCommand, + lastResolvedPath: normalizedResolved) + case .invalid: + switch ExecApprovalHelpers.validateAllowlistPattern(trimmedResolved) { + case .valid(let migratedPattern): + return ExecAllowlistEntry( + id: entry.id, + pattern: migratedPattern, + lastUsedAt: entry.lastUsedAt, + lastUsedCommand: entry.lastUsedCommand, + lastResolvedPath: normalizedResolved) + case .invalid: + return ExecAllowlistEntry( + id: entry.id, + pattern: trimmedPattern, + lastUsedAt: entry.lastUsedAt, + lastUsedCommand: entry.lastUsedCommand, + lastResolvedPath: normalizedResolved) + } + } + } + + private static func normalizeAllowlistEntries( + _ entries: [ExecAllowlistEntry], + dropInvalid: Bool) -> (entries: [ExecAllowlistEntry], rejected: [ExecAllowlistRejectedEntry]) + { + var normalized: [ExecAllowlistEntry] = [] + normalized.reserveCapacity(entries.count) + var rejected: [ExecAllowlistRejectedEntry] = [] + + for entry in entries { + let migrated = self.migrateLegacyPattern(entry) + let trimmedPattern = migrated.pattern.trimmingCharacters(in: .whitespacesAndNewlines) + let trimmedResolvedPath = migrated.lastResolvedPath?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + let normalizedResolvedPath = trimmedResolvedPath.isEmpty ? nil : trimmedResolvedPath + + switch ExecApprovalHelpers.validateAllowlistPattern(trimmedPattern) { + case .valid(let pattern): + normalized.append( + ExecAllowlistEntry( + id: migrated.id, + pattern: pattern, + lastUsedAt: migrated.lastUsedAt, + lastUsedCommand: migrated.lastUsedCommand, + lastResolvedPath: normalizedResolvedPath)) + case .invalid(let reason): + if dropInvalid { + rejected.append( + ExecAllowlistRejectedEntry( + id: migrated.id, + pattern: trimmedPattern, + reason: reason)) + } else if reason != .empty { + normalized.append( + ExecAllowlistEntry( + id: migrated.id, + pattern: trimmedPattern, + lastUsedAt: migrated.lastUsedAt, + lastUsedCommand: migrated.lastUsedCommand, + lastResolvedPath: normalizedResolvedPath)) + } + } + } + + return (normalized, rejected) } private static func mergeAgents( current: ExecApprovalsAgent, legacy: ExecApprovalsAgent) -> ExecApprovalsAgent { + let currentAllowlist = self.normalizeAllowlistEntries(current.allowlist ?? [], dropInvalid: false).entries + let legacyAllowlist = self.normalizeAllowlistEntries(legacy.allowlist ?? [], dropInvalid: false).entries var seen = Set() var allowlist: [ExecAllowlistEntry] = [] func append(_ entry: ExecAllowlistEntry) { @@ -536,10 +674,10 @@ enum ExecApprovalsStore { seen.insert(key) allowlist.append(entry) } - for entry in current.allowlist ?? [] { + for entry in currentAllowlist { append(entry) } - for entry in legacy.allowlist ?? [] { + for entry in legacyAllowlist { append(entry) } @@ -552,102 +690,23 @@ enum ExecApprovalsStore { } } -struct ExecCommandResolution: Sendable { - let rawExecutable: String - let resolvedPath: String? - let executableName: String - let cwd: String? - - static func resolve( - command: [String], - rawCommand: String?, - cwd: String?, - env: [String: String]?) -> ExecCommandResolution? - { - let trimmedRaw = rawCommand?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - if !trimmedRaw.isEmpty, let token = self.parseFirstToken(trimmedRaw) { - return self.resolveExecutable(rawExecutable: token, cwd: cwd, env: env) - } - return self.resolve(command: command, cwd: cwd, env: env) - } - - static func resolve(command: [String], cwd: String?, env: [String: String]?) -> ExecCommandResolution? { - guard let raw = command.first?.trimmingCharacters(in: .whitespacesAndNewlines), !raw.isEmpty else { - return nil - } - return self.resolveExecutable(rawExecutable: raw, cwd: cwd, env: env) - } - - private static func resolveExecutable( - rawExecutable: String, - cwd: String?, - env: [String: String]?) -> ExecCommandResolution? - { - let expanded = rawExecutable.hasPrefix("~") ? (rawExecutable as NSString).expandingTildeInPath : rawExecutable - let hasPathSeparator = expanded.contains("/") || expanded.contains("\\") - let resolvedPath: String? = { - if hasPathSeparator { - if expanded.hasPrefix("/") { - return expanded - } - let base = cwd?.trimmingCharacters(in: .whitespacesAndNewlines) - let root = (base?.isEmpty == false) ? base! : FileManager().currentDirectoryPath - return URL(fileURLWithPath: root).appendingPathComponent(expanded).path - } - let searchPaths = self.searchPaths(from: env) - return CommandResolver.findExecutable(named: expanded, searchPaths: searchPaths) - }() - let name = resolvedPath.map { URL(fileURLWithPath: $0).lastPathComponent } ?? expanded - return ExecCommandResolution( - rawExecutable: expanded, - resolvedPath: resolvedPath, - executableName: name, - cwd: cwd) - } - - private static func parseFirstToken(_ command: String) -> String? { - let trimmed = command.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { return nil } - guard let first = trimmed.first else { return nil } - if first == "\"" || first == "'" { - let rest = trimmed.dropFirst() - if let end = rest.firstIndex(of: first) { - return String(rest[.. ExecAllowlistPatternValidation { + let trimmed = pattern?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + guard !trimmed.isEmpty else { return .invalid(.empty) } + guard self.containsPathComponent(trimmed) else { return .invalid(.missingPathComponent) } + return .valid(trimmed) } - private static func searchPaths(from env: [String: String]?) -> [String] { - let raw = env?["PATH"] - if let raw, !raw.isEmpty { - return raw.split(separator: ":").map(String.init) + static func isPathPattern(_ pattern: String?) -> Bool { + switch self.validateAllowlistPattern(pattern) { + case .valid: + true + case .invalid: + false } - return CommandResolver.preferredPaths() - } -} - -enum ExecCommandFormatter { - static func displayString(for argv: [String]) -> String { - argv.map { arg in - let trimmed = arg.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { return "\"\"" } - let needsQuotes = trimmed.contains { $0.isWhitespace || $0 == "\"" } - if !needsQuotes { return trimmed } - let escaped = trimmed.replacingOccurrences(of: "\"", with: "\\\"") - return "\"\(escaped)\"" - }.joined(separator: " ") } - static func displayString(for argv: [String], rawCommand: String?) -> String { - let trimmed = rawCommand?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - if !trimmed.isEmpty { return trimmed } - return self.displayString(for: argv) - } -} - -enum ExecApprovalHelpers { static func parseDecision(_ raw: String?) -> ExecApprovalDecision? { let trimmed = raw?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" guard !trimmed.isEmpty else { return nil } @@ -669,70 +728,9 @@ enum ExecApprovalHelpers { let pattern = resolution?.resolvedPath ?? resolution?.rawExecutable ?? command.first ?? "" return pattern.isEmpty ? nil : pattern } -} - -enum ExecAllowlistMatcher { - static func match(entries: [ExecAllowlistEntry], resolution: ExecCommandResolution?) -> ExecAllowlistEntry? { - guard let resolution, !entries.isEmpty else { return nil } - let rawExecutable = resolution.rawExecutable - let resolvedPath = resolution.resolvedPath - let executableName = resolution.executableName - - for entry in entries { - let pattern = entry.pattern.trimmingCharacters(in: .whitespacesAndNewlines) - if pattern.isEmpty { continue } - let hasPath = pattern.contains("/") || pattern.contains("~") || pattern.contains("\\") - if hasPath { - let target = resolvedPath ?? rawExecutable - if self.matches(pattern: pattern, target: target) { return entry } - } else if self.matches(pattern: pattern, target: executableName) { - return entry - } - } - return nil - } - private static func matches(pattern: String, target: String) -> Bool { - let trimmed = pattern.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { return false } - let expanded = trimmed.hasPrefix("~") ? (trimmed as NSString).expandingTildeInPath : trimmed - let normalizedPattern = self.normalizeMatchTarget(expanded) - let normalizedTarget = self.normalizeMatchTarget(target) - guard let regex = self.regex(for: normalizedPattern) else { return false } - let range = NSRange(location: 0, length: normalizedTarget.utf16.count) - return regex.firstMatch(in: normalizedTarget, options: [], range: range) != nil - } - - private static func normalizeMatchTarget(_ value: String) -> String { - value.replacingOccurrences(of: "\\\\", with: "/").lowercased() - } - - private static func regex(for pattern: String) -> NSRegularExpression? { - var regex = "^" - var idx = pattern.startIndex - while idx < pattern.endIndex { - let ch = pattern[idx] - if ch == "*" { - let next = pattern.index(after: idx) - if next < pattern.endIndex, pattern[next] == "*" { - regex += ".*" - idx = pattern.index(after: next) - } else { - regex += "[^/]*" - idx = next - } - continue - } - if ch == "?" { - regex += "." - idx = pattern.index(after: idx) - continue - } - regex += NSRegularExpression.escapedPattern(for: String(ch)) - idx = pattern.index(after: idx) - } - regex += "$" - return try? NSRegularExpression(pattern: regex, options: [.caseInsensitive]) + private static func containsPathComponent(_ pattern: String) -> Bool { + pattern.contains("/") || pattern.contains("~") || pattern.contains("\\") } } diff --git a/apps/macos/Sources/OpenClaw/ExecApprovalsSocket.swift b/apps/macos/Sources/OpenClaw/ExecApprovalsSocket.swift index e1432aaea1c2c..362a7da01d889 100644 --- a/apps/macos/Sources/OpenClaw/ExecApprovalsSocket.swift +++ b/apps/macos/Sources/OpenClaw/ExecApprovalsSocket.swift @@ -350,34 +350,7 @@ enum ExecApprovalsPromptPresenter { @MainActor private enum ExecHostExecutor { - private struct ExecApprovalContext { - let command: [String] - let displayCommand: String - let trimmedAgent: String? - let approvals: ExecApprovalsResolved - let security: ExecSecurity - let ask: ExecAsk - let autoAllowSkills: Bool - let env: [String: String]? - let resolution: ExecCommandResolution? - let allowlistMatch: ExecAllowlistEntry? - let skillAllow: Bool - } - - private static let blockedEnvKeys: Set = [ - "PATH", - "NODE_OPTIONS", - "PYTHONHOME", - "PYTHONPATH", - "PERL5LIB", - "PERL5OPT", - "RUBYOPT", - ] - - private static let blockedEnvPrefixes: [String] = [ - "DYLD_", - "LD_", - ] + private typealias ExecApprovalContext = ExecApprovalEvaluation static func handle(_ request: ExecHostRequest) async -> ExecHostResponse { let command = request.command.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } @@ -419,7 +392,7 @@ private enum ExecHostExecutor { host: "node", security: context.security.rawValue, ask: context.ask.rawValue, - agentId: context.trimmedAgent, + agentId: context.agentId, resolvedPath: context.resolution?.resolvedPath, sessionKey: request.sessionKey)) @@ -440,7 +413,7 @@ private enum ExecHostExecutor { self.persistAllowlistEntry(decision: approvalDecision, context: context) if context.security == .allowlist, - context.allowlistMatch == nil, + !context.allowlistSatisfied, !context.skillAllow, !approvedByAsk { @@ -450,12 +423,21 @@ private enum ExecHostExecutor { reason: "allowlist-miss") } - if let match = context.allowlistMatch { - ExecApprovalsStore.recordAllowlistUse( - agentId: context.trimmedAgent, - pattern: match.pattern, - command: context.displayCommand, - resolvedPath: context.resolution?.resolvedPath) + if context.allowlistSatisfied { + var seenPatterns = Set() + for (idx, match) in context.allowlistMatches.enumerated() { + if !seenPatterns.insert(match.pattern).inserted { + continue + } + let resolvedPath = idx < context.allowlistResolutions.count + ? context.allowlistResolutions[idx].resolvedPath + : nil + ExecApprovalsStore.recordAllowlistUse( + agentId: context.agentId, + pattern: match.pattern, + command: context.displayCommand, + resolvedPath: resolvedPath) + } } if let errorResponse = await self.ensureScreenRecordingAccess(request.needsScreenRecording) { @@ -470,43 +452,12 @@ private enum ExecHostExecutor { } private static func buildContext(request: ExecHostRequest, command: [String]) async -> ExecApprovalContext { - let displayCommand = ExecCommandFormatter.displayString( - for: command, - rawCommand: request.rawCommand) - let agentId = request.agentId?.trimmingCharacters(in: .whitespacesAndNewlines) - let trimmedAgent = (agentId?.isEmpty == false) ? agentId : nil - let approvals = ExecApprovalsStore.resolve(agentId: trimmedAgent) - let security = approvals.agent.security - let ask = approvals.agent.ask - let autoAllowSkills = approvals.agent.autoAllowSkills - let env = self.sanitizedEnv(request.env) - let resolution = ExecCommandResolution.resolve( + await ExecApprovalEvaluator.evaluate( command: command, rawCommand: request.rawCommand, cwd: request.cwd, - env: env) - let allowlistMatch = security == .allowlist - ? ExecAllowlistMatcher.match(entries: approvals.allowlist, resolution: resolution) - : nil - let skillAllow: Bool - if autoAllowSkills, let name = resolution?.executableName { - let bins = await SkillBinsCache.shared.currentBins() - skillAllow = bins.contains(name) - } else { - skillAllow = false - } - return ExecApprovalContext( - command: command, - displayCommand: displayCommand, - trimmedAgent: trimmedAgent, - approvals: approvals, - security: security, - ask: ask, - autoAllowSkills: autoAllowSkills, - env: env, - resolution: resolution, - allowlistMatch: allowlistMatch, - skillAllow: skillAllow) + envOverrides: request.env, + agentId: request.agentId) } private static func persistAllowlistEntry( @@ -514,13 +465,18 @@ private enum ExecHostExecutor { context: ExecApprovalContext) { guard decision == .allowAlways, context.security == .allowlist else { return } - guard let pattern = ExecApprovalHelpers.allowlistPattern( - command: context.command, - resolution: context.resolution) - else { - return + var seenPatterns = Set() + for candidate in context.allowlistResolutions { + guard let pattern = ExecApprovalHelpers.allowlistPattern( + command: context.command, + resolution: candidate) + else { + continue + } + if seenPatterns.insert(pattern).inserted { + ExecApprovalsStore.addAllowlistEntry(agentId: context.agentId, pattern: pattern) + } } - ExecApprovalsStore.addAllowlistEntry(agentId: context.trimmedAgent, pattern: pattern) } private static func ensureScreenRecordingAccess(_ needsScreenRecording: Bool?) async -> ExecHostResponse? { @@ -579,20 +535,6 @@ private enum ExecHostExecutor { payload: payload, error: nil) } - - private static func sanitizedEnv(_ overrides: [String: String]?) -> [String: String]? { - guard let overrides else { return nil } - var merged = ProcessInfo.processInfo.environment - for (rawKey, value) in overrides { - let key = rawKey.trimmingCharacters(in: .whitespacesAndNewlines) - guard !key.isEmpty else { continue } - let upper = key.uppercased() - if self.blockedEnvKeys.contains(upper) { continue } - if self.blockedEnvPrefixes.contains(where: { upper.hasPrefix($0) }) { continue } - merged[key] = value - } - return merged - } } private final class ExecApprovalsSocketServer: @unchecked Sendable { diff --git a/apps/macos/Sources/OpenClaw/ExecCommandResolution.swift b/apps/macos/Sources/OpenClaw/ExecCommandResolution.swift new file mode 100644 index 0000000000000..843062b2470d8 --- /dev/null +++ b/apps/macos/Sources/OpenClaw/ExecCommandResolution.swift @@ -0,0 +1,265 @@ +import Foundation + +struct ExecCommandResolution: Sendable { + let rawExecutable: String + let resolvedPath: String? + let executableName: String + let cwd: String? + + static func resolve( + command: [String], + rawCommand: String?, + cwd: String?, + env: [String: String]?) -> ExecCommandResolution? + { + let trimmedRaw = rawCommand?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + if !trimmedRaw.isEmpty, let token = self.parseFirstToken(trimmedRaw) { + return self.resolveExecutable(rawExecutable: token, cwd: cwd, env: env) + } + return self.resolve(command: command, cwd: cwd, env: env) + } + + static func resolveForAllowlist( + command: [String], + rawCommand: String?, + cwd: String?, + env: [String: String]?) -> [ExecCommandResolution] + { + let shell = ExecShellWrapperParser.extract(command: command, rawCommand: rawCommand) + if shell.isWrapper { + guard let shellCommand = shell.command, + let segments = self.splitShellCommandChain(shellCommand) + else { + // Fail closed: if we cannot safely parse a shell wrapper payload, + // treat this as an allowlist miss and require approval. + return [] + } + var resolutions: [ExecCommandResolution] = [] + resolutions.reserveCapacity(segments.count) + for segment in segments { + guard let token = self.parseFirstToken(segment), + let resolution = self.resolveExecutable(rawExecutable: token, cwd: cwd, env: env) + else { + return [] + } + resolutions.append(resolution) + } + return resolutions + } + + guard let resolution = self.resolve(command: command, rawCommand: rawCommand, cwd: cwd, env: env) else { + return [] + } + return [resolution] + } + + static func resolve(command: [String], cwd: String?, env: [String: String]?) -> ExecCommandResolution? { + let effective = ExecEnvInvocationUnwrapper.unwrapDispatchWrappersForResolution(command) + guard let raw = effective.first?.trimmingCharacters(in: .whitespacesAndNewlines), !raw.isEmpty else { + return nil + } + return self.resolveExecutable(rawExecutable: raw, cwd: cwd, env: env) + } + + private static func resolveExecutable( + rawExecutable: String, + cwd: String?, + env: [String: String]?) -> ExecCommandResolution? + { + let expanded = rawExecutable.hasPrefix("~") ? (rawExecutable as NSString).expandingTildeInPath : rawExecutable + let hasPathSeparator = expanded.contains("/") || expanded.contains("\\") + let resolvedPath: String? = { + if hasPathSeparator { + if expanded.hasPrefix("/") { + return expanded + } + let base = cwd?.trimmingCharacters(in: .whitespacesAndNewlines) + let root = (base?.isEmpty == false) ? base! : FileManager().currentDirectoryPath + return URL(fileURLWithPath: root).appendingPathComponent(expanded).path + } + let searchPaths = self.searchPaths(from: env) + return CommandResolver.findExecutable(named: expanded, searchPaths: searchPaths) + }() + let name = resolvedPath.map { URL(fileURLWithPath: $0).lastPathComponent } ?? expanded + return ExecCommandResolution( + rawExecutable: expanded, + resolvedPath: resolvedPath, + executableName: name, + cwd: cwd) + } + + private static func parseFirstToken(_ command: String) -> String? { + let trimmed = command.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return nil } + guard let first = trimmed.first else { return nil } + if first == "\"" || first == "'" { + let rest = trimmed.dropFirst() + if let end = rest.firstIndex(of: first) { + return String(rest[..", next: "("), + ], + .doubleQuoted: [ + ShellFailClosedRule(token: "`", next: nil), + ShellFailClosedRule(token: "$", next: "("), + ], + ] + + private static func splitShellCommandChain(_ command: String) -> [String]? { + let trimmed = command.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return nil } + + var segments: [String] = [] + var current = "" + var inSingle = false + var inDouble = false + var escaped = false + let chars = Array(trimmed) + var idx = 0 + + func appendCurrent() -> Bool { + let segment = current.trimmingCharacters(in: .whitespacesAndNewlines) + guard !segment.isEmpty else { return false } + segments.append(segment) + current.removeAll(keepingCapacity: true) + return true + } + + while idx < chars.count { + let ch = chars[idx] + let next: Character? = idx + 1 < chars.count ? chars[idx + 1] : nil + + if escaped { + current.append(ch) + escaped = false + idx += 1 + continue + } + + if ch == "\\", !inSingle { + current.append(ch) + escaped = true + idx += 1 + continue + } + + if ch == "'", !inDouble { + inSingle.toggle() + current.append(ch) + idx += 1 + continue + } + + if ch == "\"", !inSingle { + inDouble.toggle() + current.append(ch) + idx += 1 + continue + } + + if !inSingle, self.shouldFailClosedForShell(ch: ch, next: next, inDouble: inDouble) { + // Fail closed on command/process substitution in allowlist mode, + // including command substitution inside double-quoted shell strings. + return nil + } + + if !inSingle, !inDouble { + let prev: Character? = idx > 0 ? chars[idx - 1] : nil + if let delimiterStep = self.chainDelimiterStep(ch: ch, prev: prev, next: next) { + guard appendCurrent() else { return nil } + idx += delimiterStep + continue + } + } + + current.append(ch) + idx += 1 + } + + if escaped || inSingle || inDouble { return nil } + guard appendCurrent() else { return nil } + return segments + } + + private static func shouldFailClosedForShell(ch: Character, next: Character?, inDouble: Bool) -> Bool { + let context: ShellTokenContext = inDouble ? .doubleQuoted : .unquoted + guard let rules = self.shellFailClosedRules[context] else { + return false + } + for rule in rules { + if ch == rule.token, rule.next == nil || next == rule.next { + return true + } + } + return false + } + + private static func chainDelimiterStep(ch: Character, prev: Character?, next: Character?) -> Int? { + if ch == ";" || ch == "\n" { + return 1 + } + if ch == "&" { + if next == "&" { + return 2 + } + // Keep fd redirections like 2>&1 or &>file intact. + let prevIsRedirect = prev == ">" + let nextIsRedirect = next == ">" + return (!prevIsRedirect && !nextIsRedirect) ? 1 : nil + } + if ch == "|" { + if next == "|" || next == "&" { + return 2 + } + return 1 + } + return nil + } + + private static func searchPaths(from env: [String: String]?) -> [String] { + let raw = env?["PATH"] + if let raw, !raw.isEmpty { + return raw.split(separator: ":").map(String.init) + } + return CommandResolver.preferredPaths() + } +} + +enum ExecCommandFormatter { + static func displayString(for argv: [String]) -> String { + argv.map { arg in + let trimmed = arg.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return "\"\"" } + let needsQuotes = trimmed.contains { $0.isWhitespace || $0 == "\"" } + if !needsQuotes { return trimmed } + let escaped = trimmed.replacingOccurrences(of: "\"", with: "\\\"") + return "\"\(escaped)\"" + }.joined(separator: " ") + } + + static func displayString(for argv: [String], rawCommand: String?) -> String { + let trimmed = rawCommand?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + if !trimmed.isEmpty { return trimmed } + return self.displayString(for: argv) + } +} diff --git a/apps/macos/Sources/OpenClaw/ExecEnvInvocationUnwrapper.swift b/apps/macos/Sources/OpenClaw/ExecEnvInvocationUnwrapper.swift new file mode 100644 index 0000000000000..ebb8965e75526 --- /dev/null +++ b/apps/macos/Sources/OpenClaw/ExecEnvInvocationUnwrapper.swift @@ -0,0 +1,108 @@ +import Foundation + +enum ExecCommandToken { + static func basenameLower(_ token: String) -> String { + let trimmed = token.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return "" } + let normalized = trimmed.replacingOccurrences(of: "\\", with: "/") + return normalized.split(separator: "/").last.map { String($0).lowercased() } ?? normalized.lowercased() + } +} + +enum ExecEnvInvocationUnwrapper { + static let maxWrapperDepth = 4 + + private static let optionsWithValue = Set([ + "-u", + "--unset", + "-c", + "--chdir", + "-s", + "--split-string", + "--default-signal", + "--ignore-signal", + "--block-signal", + ]) + private static let flagOptions = Set(["-i", "--ignore-environment", "-0", "--null"]) + + private static func isEnvAssignment(_ token: String) -> Bool { + let pattern = #"^[A-Za-z_][A-Za-z0-9_]*=.*"# + return token.range(of: pattern, options: .regularExpression) != nil + } + + static func unwrap(_ command: [String]) -> [String]? { + var idx = 1 + var expectsOptionValue = false + while idx < command.count { + let token = command[idx].trimmingCharacters(in: .whitespacesAndNewlines) + if token.isEmpty { + idx += 1 + continue + } + if expectsOptionValue { + expectsOptionValue = false + idx += 1 + continue + } + if token == "--" || token == "-" { + idx += 1 + break + } + if self.isEnvAssignment(token) { + idx += 1 + continue + } + if token.hasPrefix("-"), token != "-" { + let lower = token.lowercased() + let flag = lower.split(separator: "=", maxSplits: 1).first.map(String.init) ?? lower + if self.flagOptions.contains(flag) { + idx += 1 + continue + } + if self.optionsWithValue.contains(flag) { + if !lower.contains("=") { + expectsOptionValue = true + } + idx += 1 + continue + } + if lower.hasPrefix("-u") || + lower.hasPrefix("-c") || + lower.hasPrefix("-s") || + lower.hasPrefix("--unset=") || + lower.hasPrefix("--chdir=") || + lower.hasPrefix("--split-string=") || + lower.hasPrefix("--default-signal=") || + lower.hasPrefix("--ignore-signal=") || + lower.hasPrefix("--block-signal=") + { + idx += 1 + continue + } + return nil + } + break + } + guard idx < command.count else { return nil } + return Array(command[idx...]) + } + + static func unwrapDispatchWrappersForResolution(_ command: [String]) -> [String] { + var current = command + var depth = 0 + while depth < self.maxWrapperDepth { + guard let token = current.first?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty else { + break + } + guard ExecCommandToken.basenameLower(token) == "env" else { + break + } + guard let unwrapped = self.unwrap(current), !unwrapped.isEmpty else { + break + } + current = unwrapped + depth += 1 + } + return current + } +} diff --git a/apps/macos/Sources/OpenClaw/ExecShellWrapperParser.swift b/apps/macos/Sources/OpenClaw/ExecShellWrapperParser.swift new file mode 100644 index 0000000000000..ca6a934adb512 --- /dev/null +++ b/apps/macos/Sources/OpenClaw/ExecShellWrapperParser.swift @@ -0,0 +1,106 @@ +import Foundation + +enum ExecShellWrapperParser { + struct ParsedShellWrapper { + let isWrapper: Bool + let command: String? + + static let notWrapper = ParsedShellWrapper(isWrapper: false, command: nil) + } + + private enum Kind { + case posix + case cmd + case powershell + } + + private struct WrapperSpec { + let kind: Kind + let names: Set + } + + private static let posixInlineFlags = Set(["-lc", "-c", "--command"]) + private static let powershellInlineFlags = Set(["-c", "-command", "--command"]) + + private static let wrapperSpecs: [WrapperSpec] = [ + WrapperSpec(kind: .posix, names: ["ash", "sh", "bash", "zsh", "dash", "ksh", "fish"]), + WrapperSpec(kind: .cmd, names: ["cmd.exe", "cmd"]), + WrapperSpec(kind: .powershell, names: ["powershell", "powershell.exe", "pwsh", "pwsh.exe"]), + ] + + static func extract(command: [String], rawCommand: String?) -> ParsedShellWrapper { + let trimmedRaw = rawCommand?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + let preferredRaw = trimmedRaw.isEmpty ? nil : trimmedRaw + return self.extract(command: command, preferredRaw: preferredRaw, depth: 0) + } + + private static func extract(command: [String], preferredRaw: String?, depth: Int) -> ParsedShellWrapper { + guard depth < ExecEnvInvocationUnwrapper.maxWrapperDepth else { + return .notWrapper + } + guard let token0 = command.first?.trimmingCharacters(in: .whitespacesAndNewlines), !token0.isEmpty else { + return .notWrapper + } + + let base0 = ExecCommandToken.basenameLower(token0) + if base0 == "env" { + guard let unwrapped = ExecEnvInvocationUnwrapper.unwrap(command) else { + return .notWrapper + } + return self.extract(command: unwrapped, preferredRaw: preferredRaw, depth: depth + 1) + } + + guard let spec = self.wrapperSpecs.first(where: { $0.names.contains(base0) }) else { + return .notWrapper + } + guard let payload = self.extractPayload(command: command, spec: spec) else { + return .notWrapper + } + let normalized = preferredRaw ?? payload + return ParsedShellWrapper(isWrapper: true, command: normalized) + } + + private static func extractPayload(command: [String], spec: WrapperSpec) -> String? { + switch spec.kind { + case .posix: + return self.extractPosixInlineCommand(command) + case .cmd: + return self.extractCmdInlineCommand(command) + case .powershell: + return self.extractPowerShellInlineCommand(command) + } + } + + private static func extractPosixInlineCommand(_ command: [String]) -> String? { + let flag = command.count > 1 ? command[1].trimmingCharacters(in: .whitespacesAndNewlines) : "" + guard self.posixInlineFlags.contains(flag.lowercased()) else { + return nil + } + let payload = command.count > 2 ? command[2].trimmingCharacters(in: .whitespacesAndNewlines) : "" + return payload.isEmpty ? nil : payload + } + + private static func extractCmdInlineCommand(_ command: [String]) -> String? { + guard let idx = command.firstIndex(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() == "/c" }) else { + return nil + } + let tail = command.suffix(from: command.index(after: idx)).joined(separator: " ") + let payload = tail.trimmingCharacters(in: .whitespacesAndNewlines) + return payload.isEmpty ? nil : payload + } + + private static func extractPowerShellInlineCommand(_ command: [String]) -> String? { + for idx in 1.. String? { - let host = self.sanitizedTailnetHost(gateway.tailnetDns) ?? gateway.lanHost + static func resolvedServiceHost( + for gateway: GatewayDiscoveryModel.DiscoveredGateway) -> String? + { + self.resolvedServiceHost(gateway.serviceHost) + } + + static func resolvedServiceHost(_ host: String?) -> String? { guard let host = self.trimmed(host), !host.isEmpty else { return nil } + return host + } + + static func serviceEndpoint( + for gateway: GatewayDiscoveryModel.DiscoveredGateway) -> (host: String, port: Int)? + { + self.serviceEndpoint(serviceHost: gateway.serviceHost, servicePort: gateway.servicePort) + } + + static func serviceEndpoint( + serviceHost: String?, + servicePort: Int?) -> (host: String, port: Int)? + { + guard let host = self.resolvedServiceHost(serviceHost) else { return nil } + guard let port = servicePort, port > 0, port <= 65535 else { return nil } + return (host, port) + } + + static func sshTarget(for gateway: GatewayDiscoveryModel.DiscoveredGateway) -> String? { + guard let host = self.resolvedServiceHost(for: gateway) else { return nil } let user = NSUserName() var target = "\(user)@\(host)" if gateway.sshPort != 22 { @@ -16,42 +41,37 @@ enum GatewayDiscoveryHelpers { static func directUrl(for gateway: GatewayDiscoveryModel.DiscoveredGateway) -> String? { self.directGatewayUrl( serviceHost: gateway.serviceHost, - servicePort: gateway.servicePort, - lanHost: gateway.lanHost, - gatewayPort: gateway.gatewayPort) + servicePort: gateway.servicePort) } static func directGatewayUrl( serviceHost: String?, - servicePort: Int?, - lanHost: String?, - gatewayPort: Int?) -> String? + servicePort: Int?) -> String? { // Security: do not route using unauthenticated TXT hints (tailnetDns/lanHost/gatewayPort). // Prefer the resolved service endpoint (SRV + A/AAAA). - if let host = self.trimmed(serviceHost), !host.isEmpty, - let port = servicePort, port > 0 - { - let scheme = port == 443 ? "wss" : "ws" - let portSuffix = port == 443 ? "" : ":\(port)" - return "\(scheme)://\(host)\(portSuffix)" - } - - // Legacy fallback (best-effort): keep existing behavior when we couldn't resolve SRV. - guard let lanHost = self.trimmed(lanHost), !lanHost.isEmpty else { return nil } - let port = gatewayPort ?? 18789 - return "ws://\(lanHost):\(port)" - } - - static func sanitizedTailnetHost(_ host: String?) -> String? { - guard let host = self.trimmed(host), !host.isEmpty else { return nil } - if host.hasSuffix(".internal.") || host.hasSuffix(".internal") { + guard let endpoint = self.serviceEndpoint(serviceHost: serviceHost, servicePort: servicePort) else { return nil } - return host + // Security: for non-loopback hosts, force TLS to avoid plaintext credential/session leakage. + let scheme = self.isLoopbackHost(endpoint.host) ? "ws" : "wss" + let portSuffix = endpoint.port == 443 ? "" : ":\(endpoint.port)" + return "\(scheme)://\(endpoint.host)\(portSuffix)" } private static func trimmed(_ value: String?) -> String? { value?.trimmingCharacters(in: .whitespacesAndNewlines) } + + private static func isLoopbackHost(_ rawHost: String) -> Bool { + let host = rawHost.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + guard !host.isEmpty else { return false } + if host == "localhost" || host == "::1" || host == "0:0:0:0:0:0:0:1" { + return true + } + if host.hasPrefix("::ffff:127.") { + return true + } + return host.hasPrefix("127.") + } } diff --git a/apps/macos/Sources/OpenClaw/GatewayRemoteConfig.swift b/apps/macos/Sources/OpenClaw/GatewayRemoteConfig.swift index 0b8ab35159d2e..64a6f92db8fa6 100644 --- a/apps/macos/Sources/OpenClaw/GatewayRemoteConfig.swift +++ b/apps/macos/Sources/OpenClaw/GatewayRemoteConfig.swift @@ -1,6 +1,41 @@ import Foundation +import Network enum GatewayRemoteConfig { + private static func isLoopbackHost(_ rawHost: String) -> Bool { + var host = rawHost + .trimmingCharacters(in: .whitespacesAndNewlines) + .lowercased() + .trimmingCharacters(in: CharacterSet(charactersIn: "[]")) + if host.hasSuffix(".") { + host.removeLast() + } + if let zoneIndex = host.firstIndex(of: "%") { + host = String(host[.. AppState.RemoteTransport { guard let gateway = root["gateway"] as? [String: Any], let remote = gateway["remote"] as? [String: Any], @@ -39,6 +74,9 @@ enum GatewayRemoteConfig { guard scheme == "ws" || scheme == "wss" else { return nil } let host = url.host?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" guard !host.isEmpty else { return nil } + if scheme == "ws", !self.isLoopbackHost(host) { + return nil + } if scheme == "ws", url.port == nil { guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return url diff --git a/apps/macos/Sources/OpenClaw/GeneralSettings.swift b/apps/macos/Sources/OpenClaw/GeneralSettings.swift index d55f7c1b01583..60cfdfb1d7379 100644 --- a/apps/macos/Sources/OpenClaw/GeneralSettings.swift +++ b/apps/macos/Sources/OpenClaw/GeneralSettings.swift @@ -303,7 +303,9 @@ struct GeneralSettings: View { .disabled(self.remoteStatus == .checking || self.state.remoteUrl .trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) } - Text("Direct mode requires a ws:// or wss:// URL (Tailscale Serve uses wss://).") + Text( + "Direct mode requires wss:// for remote hosts. ws:// is only allowed for localhost/127.0.0.1." + ) .font(.caption) .foregroundStyle(.secondary) .padding(.leading, self.remoteLabelWidth + 10) @@ -546,7 +548,9 @@ extension GeneralSettings { return } guard Self.isValidWsUrl(trimmedUrl) else { - self.remoteStatus = .failed("Gateway URL must start with ws:// or wss://") + self.remoteStatus = .failed( + "Gateway URL must use wss:// for remote hosts (ws:// only for localhost)" + ) return } } else { @@ -603,11 +607,7 @@ extension GeneralSettings { } private static func isValidWsUrl(_ raw: String) -> Bool { - guard let url = URL(string: raw.trimmingCharacters(in: .whitespacesAndNewlines)) else { return false } - let scheme = url.scheme?.lowercased() ?? "" - guard scheme == "ws" || scheme == "wss" else { return false } - let host = url.host?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - return !host.isEmpty + GatewayRemoteConfig.normalizeGatewayUrl(raw) != nil } private static func sshCheckCommand(target: String, identity: String) -> [String]? { @@ -675,22 +675,17 @@ extension GeneralSettings { private func applyDiscoveredGateway(_ gateway: GatewayDiscoveryModel.DiscoveredGateway) { MacNodeModeCoordinator.shared.setPreferredGatewayStableID(gateway.stableID) - let host = gateway.tailnetDns ?? gateway.lanHost - guard let host else { return } - let user = NSUserName() if self.state.remoteTransport == .direct { - if let url = GatewayDiscoveryHelpers.directUrl(for: gateway) { - self.state.remoteUrl = url - } + self.state.remoteUrl = GatewayDiscoveryHelpers.directUrl(for: gateway) ?? "" } else { - self.state.remoteTarget = GatewayDiscoveryModel.buildSSHTarget( - user: user, - host: host, - port: gateway.sshPort) - self.state.remoteCliPath = gateway.cliPath ?? "" + self.state.remoteTarget = GatewayDiscoveryHelpers.sshTarget(for: gateway) ?? "" + } + if let endpoint = GatewayDiscoveryHelpers.serviceEndpoint(for: gateway) { OpenClawConfigFile.setRemoteGatewayUrl( - host: gateway.serviceHost ?? host, - port: gateway.servicePort ?? gateway.gatewayPort) + host: endpoint.host, + port: endpoint.port) + } else { + OpenClawConfigFile.clearRemoteGatewayUrl() } } } diff --git a/apps/macos/Sources/OpenClaw/HostEnvSanitizer.swift b/apps/macos/Sources/OpenClaw/HostEnvSanitizer.swift new file mode 100644 index 0000000000000..b9b993299a90d --- /dev/null +++ b/apps/macos/Sources/OpenClaw/HostEnvSanitizer.swift @@ -0,0 +1,91 @@ +import Foundation + +enum HostEnvSanitizer { + /// Keep in sync with src/infra/host-env-security-policy.json. + /// Parity is validated by src/infra/host-env-security.policy-parity.test.ts. + private static let blockedKeys: Set = [ + "NODE_OPTIONS", + "NODE_PATH", + "PYTHONHOME", + "PYTHONPATH", + "PERL5LIB", + "PERL5OPT", + "RUBYLIB", + "RUBYOPT", + "BASH_ENV", + "ENV", + "SHELL", + "SHELLOPTS", + "PS4", + "GCONV_PATH", + "IFS", + "SSLKEYLOGFILE", + ] + + private static let blockedPrefixes: [String] = [ + "DYLD_", + "LD_", + "BASH_FUNC_", + ] + private static let blockedOverrideKeys: Set = [ + "HOME", + "ZDOTDIR", + ] + private static let shellWrapperAllowedOverrideKeys: Set = [ + "TERM", + "LANG", + "LC_ALL", + "LC_CTYPE", + "LC_MESSAGES", + "COLORTERM", + "NO_COLOR", + "FORCE_COLOR", + ] + + private static func isBlocked(_ upperKey: String) -> Bool { + if self.blockedKeys.contains(upperKey) { return true } + return self.blockedPrefixes.contains(where: { upperKey.hasPrefix($0) }) + } + + private static func filterOverridesForShellWrapper(_ overrides: [String: String]?) -> [String: String]? { + guard let overrides else { return nil } + var filtered: [String: String] = [:] + for (rawKey, value) in overrides { + let key = rawKey.trimmingCharacters(in: .whitespacesAndNewlines) + guard !key.isEmpty else { continue } + if self.shellWrapperAllowedOverrideKeys.contains(key.uppercased()) { + filtered[key] = value + } + } + return filtered.isEmpty ? nil : filtered + } + + static func sanitize(overrides: [String: String]?, shellWrapper: Bool = false) -> [String: String] { + var merged: [String: String] = [:] + for (rawKey, value) in ProcessInfo.processInfo.environment { + let key = rawKey.trimmingCharacters(in: .whitespacesAndNewlines) + guard !key.isEmpty else { continue } + let upper = key.uppercased() + if self.isBlocked(upper) { continue } + merged[key] = value + } + + let effectiveOverrides = shellWrapper + ? self.filterOverridesForShellWrapper(overrides) + : overrides + + guard let effectiveOverrides else { return merged } + for (rawKey, value) in effectiveOverrides { + let key = rawKey.trimmingCharacters(in: .whitespacesAndNewlines) + guard !key.isEmpty else { continue } + let upper = key.uppercased() + // PATH is part of the security boundary (command resolution + safe-bin checks). Never + // allow request-scoped PATH overrides from agents/gateways. + if upper == "PATH" { continue } + if self.blockedOverrideKeys.contains(upper) { continue } + if self.isBlocked(upper) { continue } + merged[key] = value + } + return merged + } +} diff --git a/apps/macos/Sources/OpenClaw/NodeMode/MacNodeRuntime.swift b/apps/macos/Sources/OpenClaw/NodeMode/MacNodeRuntime.swift index 60bd95f2894be..cda8ca6057ce4 100644 --- a/apps/macos/Sources/OpenClaw/NodeMode/MacNodeRuntime.swift +++ b/apps/macos/Sources/OpenClaw/NodeMode/MacNodeRuntime.swift @@ -441,43 +441,25 @@ actor MacNodeRuntime { guard !command.isEmpty else { return Self.errorResponse(req, code: .invalidRequest, message: "INVALID_REQUEST: command required") } - let displayCommand = ExecCommandFormatter.displayString(for: command, rawCommand: params.rawCommand) - - let trimmedAgent = params.agentId?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - let agentId = trimmedAgent.isEmpty ? nil : trimmedAgent - let approvals = ExecApprovalsStore.resolve(agentId: agentId) - let security = approvals.agent.security - let ask = approvals.agent.ask - let autoAllowSkills = approvals.agent.autoAllowSkills let sessionKey = (params.sessionKey?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false) ? params.sessionKey!.trimmingCharacters(in: .whitespacesAndNewlines) : self.mainSessionKey let runId = UUID().uuidString - let env = Self.sanitizedEnv(params.env) - let resolution = ExecCommandResolution.resolve( + let evaluation = await ExecApprovalEvaluator.evaluate( command: command, rawCommand: params.rawCommand, cwd: params.cwd, - env: env) - let allowlistMatch = security == .allowlist - ? ExecAllowlistMatcher.match(entries: approvals.allowlist, resolution: resolution) - : nil - let skillAllow: Bool - if autoAllowSkills, let name = resolution?.executableName { - let bins = await SkillBinsCache.shared.currentBins() - skillAllow = bins.contains(name) - } else { - skillAllow = false - } + envOverrides: params.env, + agentId: params.agentId) - if security == .deny { + if evaluation.security == .deny { await self.emitExecEvent( "exec.denied", payload: ExecEventPayload( sessionKey: sessionKey, runId: runId, host: "node", - command: displayCommand, + command: evaluation.displayCommand, reason: "security=deny")) return Self.errorResponse( req, @@ -489,32 +471,33 @@ actor MacNodeRuntime { req: req, params: params, context: ExecRunContext( - displayCommand: displayCommand, - security: security, - ask: ask, - agentId: agentId, - resolution: resolution, - allowlistMatch: allowlistMatch, - skillAllow: skillAllow, + displayCommand: evaluation.displayCommand, + security: evaluation.security, + ask: evaluation.ask, + agentId: evaluation.agentId, + resolution: evaluation.resolution, + allowlistMatch: evaluation.allowlistMatch, + skillAllow: evaluation.skillAllow, sessionKey: sessionKey, runId: runId)) if let response = approval.response { return response } let approvedByAsk = approval.approvedByAsk let persistAllowlist = approval.persistAllowlist - if persistAllowlist, security == .allowlist, - let pattern = ExecApprovalHelpers.allowlistPattern(command: command, resolution: resolution) - { - ExecApprovalsStore.addAllowlistEntry(agentId: agentId, pattern: pattern) - } + self.persistAllowlistPatterns( + persistAllowlist: persistAllowlist, + security: evaluation.security, + agentId: evaluation.agentId, + command: command, + allowlistResolutions: evaluation.allowlistResolutions) - if security == .allowlist, allowlistMatch == nil, !skillAllow, !approvedByAsk { + if evaluation.security == .allowlist, !evaluation.allowlistSatisfied, !evaluation.skillAllow, !approvedByAsk { await self.emitExecEvent( "exec.denied", payload: ExecEventPayload( sessionKey: sessionKey, runId: runId, host: "node", - command: displayCommand, + command: evaluation.displayCommand, reason: "allowlist-miss")) return Self.errorResponse( req, @@ -522,79 +505,32 @@ actor MacNodeRuntime { message: "SYSTEM_RUN_DENIED: allowlist miss") } - if let match = allowlistMatch { - ExecApprovalsStore.recordAllowlistUse( - agentId: agentId, - pattern: match.pattern, - command: displayCommand, - resolvedPath: resolution?.resolvedPath) - } + self.recordAllowlistMatches( + security: evaluation.security, + allowlistSatisfied: evaluation.allowlistSatisfied, + agentId: evaluation.agentId, + allowlistMatches: evaluation.allowlistMatches, + allowlistResolutions: evaluation.allowlistResolutions, + displayCommand: evaluation.displayCommand) - if params.needsScreenRecording == true { - let authorized = await PermissionManager - .status([.screenRecording])[.screenRecording] ?? false - if !authorized { - await self.emitExecEvent( - "exec.denied", - payload: ExecEventPayload( - sessionKey: sessionKey, - runId: runId, - host: "node", - command: displayCommand, - reason: "permission:screenRecording")) - return Self.errorResponse( - req, - code: .unavailable, - message: "PERMISSION_MISSING: screenRecording") - } + if let permissionResponse = await self.validateScreenRecordingIfNeeded( + req: req, + needsScreenRecording: params.needsScreenRecording, + sessionKey: sessionKey, + runId: runId, + displayCommand: evaluation.displayCommand) + { + return permissionResponse } - let timeoutSec = params.timeoutMs.flatMap { Double($0) / 1000.0 } - await self.emitExecEvent( - "exec.started", - payload: ExecEventPayload( - sessionKey: sessionKey, - runId: runId, - host: "node", - command: displayCommand)) - let result = await ShellExecutor.runDetailed( + return try await self.executeSystemRun( + req: req, + params: params, command: command, - cwd: params.cwd, - env: env, - timeout: timeoutSec) - let combined = [result.stdout, result.stderr, result.errorMessage] - .compactMap(\.self) - .filter { !$0.isEmpty } - .joined(separator: "\n") - await self.emitExecEvent( - "exec.finished", - payload: ExecEventPayload( - sessionKey: sessionKey, - runId: runId, - host: "node", - command: displayCommand, - exitCode: result.exitCode, - timedOut: result.timedOut, - success: result.success, - output: ExecEventPayload.truncateOutput(combined))) - - struct RunPayload: Encodable { - var exitCode: Int? - var timedOut: Bool - var success: Bool - var stdout: String - var stderr: String - var error: String? - } - - let payload = try Self.encodePayload(RunPayload( - exitCode: result.exitCode, - timedOut: result.timedOut, - success: result.success, - stdout: result.stdout, - stderr: result.stderr, - error: result.errorMessage)) - return BridgeInvokeResponse(id: req.id, ok: true, payloadJSON: payload) + env: evaluation.env, + sessionKey: sessionKey, + runId: runId, + displayCommand: evaluation.displayCommand) } private func handleSystemWhich(_ req: BridgeInvokeRequest) async throws -> BridgeInvokeResponse { @@ -835,6 +771,132 @@ actor MacNodeRuntime { } extension MacNodeRuntime { + private func persistAllowlistPatterns( + persistAllowlist: Bool, + security: ExecSecurity, + agentId: String?, + command: [String], + allowlistResolutions: [ExecCommandResolution]) + { + guard persistAllowlist, security == .allowlist else { return } + var seenPatterns = Set() + for candidate in allowlistResolutions { + guard let pattern = ExecApprovalHelpers.allowlistPattern(command: command, resolution: candidate) else { + continue + } + if seenPatterns.insert(pattern).inserted { + ExecApprovalsStore.addAllowlistEntry(agentId: agentId, pattern: pattern) + } + } + } + + private func recordAllowlistMatches( + security: ExecSecurity, + allowlistSatisfied: Bool, + agentId: String?, + allowlistMatches: [ExecAllowlistEntry], + allowlistResolutions: [ExecCommandResolution], + displayCommand: String) + { + guard security == .allowlist, allowlistSatisfied else { return } + var seenPatterns = Set() + for (idx, match) in allowlistMatches.enumerated() { + if !seenPatterns.insert(match.pattern).inserted { + continue + } + let resolvedPath = idx < allowlistResolutions.count ? allowlistResolutions[idx].resolvedPath : nil + ExecApprovalsStore.recordAllowlistUse( + agentId: agentId, + pattern: match.pattern, + command: displayCommand, + resolvedPath: resolvedPath) + } + } + + private func validateScreenRecordingIfNeeded( + req: BridgeInvokeRequest, + needsScreenRecording: Bool?, + sessionKey: String, + runId: String, + displayCommand: String) async -> BridgeInvokeResponse? + { + guard needsScreenRecording == true else { return nil } + let authorized = await PermissionManager + .status([.screenRecording])[.screenRecording] ?? false + if authorized { + return nil + } + await self.emitExecEvent( + "exec.denied", + payload: ExecEventPayload( + sessionKey: sessionKey, + runId: runId, + host: "node", + command: displayCommand, + reason: "permission:screenRecording")) + return Self.errorResponse( + req, + code: .unavailable, + message: "PERMISSION_MISSING: screenRecording") + } + + private func executeSystemRun( + req: BridgeInvokeRequest, + params: OpenClawSystemRunParams, + command: [String], + env: [String: String], + sessionKey: String, + runId: String, + displayCommand: String) async throws -> BridgeInvokeResponse + { + let timeoutSec = params.timeoutMs.flatMap { Double($0) / 1000.0 } + await self.emitExecEvent( + "exec.started", + payload: ExecEventPayload( + sessionKey: sessionKey, + runId: runId, + host: "node", + command: displayCommand)) + let result = await ShellExecutor.runDetailed( + command: command, + cwd: params.cwd, + env: env, + timeout: timeoutSec) + let combined = [result.stdout, result.stderr, result.errorMessage] + .compactMap(\.self) + .filter { !$0.isEmpty } + .joined(separator: "\n") + await self.emitExecEvent( + "exec.finished", + payload: ExecEventPayload( + sessionKey: sessionKey, + runId: runId, + host: "node", + command: displayCommand, + exitCode: result.exitCode, + timedOut: result.timedOut, + success: result.success, + output: ExecEventPayload.truncateOutput(combined))) + + struct RunPayload: Encodable { + var exitCode: Int? + var timedOut: Bool + var success: Bool + var stdout: String + var stderr: String + var error: String? + } + let runPayload = RunPayload( + exitCode: result.exitCode, + timedOut: result.timedOut, + success: result.success, + stdout: result.stdout, + stderr: result.stderr, + error: result.errorMessage) + let payload = try Self.encodePayload(runPayload) + return BridgeInvokeResponse(id: req.id, ok: true, payloadJSON: payload) + } + private static func decodeParams(_ type: T.Type, from json: String?) throws -> T { guard let json, let data = json.data(using: .utf8) else { throw NSError(domain: "Gateway", code: 20, userInfo: [ @@ -862,35 +924,6 @@ extension MacNodeRuntime { UserDefaults.standard.object(forKey: cameraEnabledKey) as? Bool ?? false } - private static let blockedEnvKeys: Set = [ - "PATH", - "NODE_OPTIONS", - "PYTHONHOME", - "PYTHONPATH", - "PERL5LIB", - "PERL5OPT", - "RUBYOPT", - ] - - private static let blockedEnvPrefixes: [String] = [ - "DYLD_", - "LD_", - ] - - private static func sanitizedEnv(_ overrides: [String: String]?) -> [String: String]? { - guard let overrides else { return nil } - var merged = ProcessInfo.processInfo.environment - for (rawKey, value) in overrides { - let key = rawKey.trimmingCharacters(in: .whitespacesAndNewlines) - guard !key.isEmpty else { continue } - let upper = key.uppercased() - if self.blockedEnvKeys.contains(upper) { continue } - if self.blockedEnvPrefixes.contains(where: { upper.hasPrefix($0) }) { continue } - merged[key] = value - } - return merged - } - private nonisolated static func locationMode() -> OpenClawLocationMode { let raw = UserDefaults.standard.string(forKey: locationModeKey) ?? "off" return OpenClawLocationMode(rawValue: raw) ?? .off diff --git a/apps/macos/Sources/OpenClaw/NodePairingApprovalPrompter.swift b/apps/macos/Sources/OpenClaw/NodePairingApprovalPrompter.swift index ee994b38f6505..10598d7f4be94 100644 --- a/apps/macos/Sources/OpenClaw/NodePairingApprovalPrompter.swift +++ b/apps/macos/Sources/OpenClaw/NodePairingApprovalPrompter.swift @@ -520,11 +520,12 @@ final class NodePairingApprovalPrompter { let preferred = GatewayDiscoveryPreferences.preferredStableID() let gateway = model.gateways.first { $0.stableID == preferred } ?? model.gateways.first guard let gateway else { return nil } - let host = (gateway.tailnetDns?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty ?? - gateway.lanHost?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty) - guard let host, !host.isEmpty else { return nil } - let port = gateway.sshPort > 0 ? gateway.sshPort : 22 - return SSHTarget(host: host, port: port) + guard let target = GatewayDiscoveryHelpers.sshTarget(for: gateway), + let parsed = CommandResolver.parseSSHTarget(target) + else { + return nil + } + return SSHTarget(host: parsed.host, port: parsed.port) } private static func probeSSH(user: String, host: String, port: Int) async -> Bool { diff --git a/apps/macos/Sources/OpenClaw/OnboardingView+Actions.swift b/apps/macos/Sources/OpenClaw/OnboardingView+Actions.swift index ba43424aa9a76..bcd5bd6d44d25 100644 --- a/apps/macos/Sources/OpenClaw/OnboardingView+Actions.swift +++ b/apps/macos/Sources/OpenClaw/OnboardingView+Actions.swift @@ -26,20 +26,17 @@ extension OnboardingView { GatewayDiscoveryPreferences.setPreferredStableID(gateway.stableID) if self.state.remoteTransport == .direct { - if let url = GatewayDiscoveryHelpers.directUrl(for: gateway) { - self.state.remoteUrl = url - } - } else if let host = GatewayDiscoveryHelpers.sanitizedTailnetHost(gateway.tailnetDns) ?? gateway.lanHost { - let user = NSUserName() - self.state.remoteTarget = GatewayDiscoveryModel.buildSSHTarget( - user: user, - host: host, - port: gateway.sshPort) + self.state.remoteUrl = GatewayDiscoveryHelpers.directUrl(for: gateway) ?? "" + } else { + self.state.remoteTarget = GatewayDiscoveryHelpers.sshTarget(for: gateway) ?? "" + } + if let endpoint = GatewayDiscoveryHelpers.serviceEndpoint(for: gateway) { OpenClawConfigFile.setRemoteGatewayUrl( - host: gateway.serviceHost ?? host, - port: gateway.servicePort ?? gateway.gatewayPort) + host: endpoint.host, + port: endpoint.port) + } else { + OpenClawConfigFile.clearRemoteGatewayUrl() } - self.state.remoteCliPath = gateway.cliPath ?? "" self.state.connectionMode = .remote MacNodeModeCoordinator.shared.setPreferredGatewayStableID(gateway.stableID) diff --git a/apps/macos/Sources/OpenClaw/OnboardingView+Pages.swift b/apps/macos/Sources/OpenClaw/OnboardingView+Pages.swift index 5760bfff8c20d..5b05ab164c2d7 100644 --- a/apps/macos/Sources/OpenClaw/OnboardingView+Pages.swift +++ b/apps/macos/Sources/OpenClaw/OnboardingView+Pages.swift @@ -265,9 +265,11 @@ extension OnboardingView { if self.state.remoteTransport == .direct { return GatewayDiscoveryHelpers.directUrl(for: gateway) ?? "Gateway pairing only" } - if let host = GatewayDiscoveryHelpers.sanitizedTailnetHost(gateway.tailnetDns) ?? gateway.lanHost { - let portSuffix = gateway.sshPort != 22 ? " · ssh \(gateway.sshPort)" : "" - return "\(host)\(portSuffix)" + if let target = GatewayDiscoveryHelpers.sshTarget(for: gateway), + let parsed = CommandResolver.parseSSHTarget(target) + { + let portSuffix = parsed.port != 22 ? " · ssh \(parsed.port)" : "" + return "\(parsed.host)\(portSuffix)" } return "Gateway pairing only" } diff --git a/apps/macos/Sources/OpenClaw/OpenClawConfigFile.swift b/apps/macos/Sources/OpenClaw/OpenClawConfigFile.swift index f49f2b7e0d4fd..35744baeda52e 100644 --- a/apps/macos/Sources/OpenClaw/OpenClawConfigFile.swift +++ b/apps/macos/Sources/OpenClaw/OpenClawConfigFile.swift @@ -223,6 +223,19 @@ enum OpenClawConfigFile { } } + static func clearRemoteGatewayUrl() { + self.updateGatewayDict { gateway in + guard var remote = gateway["remote"] as? [String: Any] else { return } + guard remote["url"] != nil else { return } + remote.removeValue(forKey: "url") + if remote.isEmpty { + gateway.removeValue(forKey: "remote") + } else { + gateway["remote"] = remote + } + } + } + private static func remoteGatewayUrl() -> URL? { let root = self.loadDict() guard let gateway = root["gateway"] as? [String: Any], diff --git a/apps/macos/Sources/OpenClaw/Resources/Info.plist b/apps/macos/Sources/OpenClaw/Resources/Info.plist index 8d32bbe09a69e..e7ca1ad548783 100644 --- a/apps/macos/Sources/OpenClaw/Resources/Info.plist +++ b/apps/macos/Sources/OpenClaw/Resources/Info.plist @@ -15,9 +15,9 @@ CFBundlePackageType APPL CFBundleShortVersionString - 2026.2.18 + 2026.2.21 CFBundleVersion - 202602180 + 202602210 CFBundleIconFile OpenClaw CFBundleURLTypes diff --git a/apps/macos/Sources/OpenClaw/SystemRunSettingsView.swift b/apps/macos/Sources/OpenClaw/SystemRunSettingsView.swift index b9bd6bd0c8cc5..a6d81f50bcacc 100644 --- a/apps/macos/Sources/OpenClaw/SystemRunSettingsView.swift +++ b/apps/macos/Sources/OpenClaw/SystemRunSettingsView.swift @@ -105,16 +105,24 @@ struct SystemRunSettingsView: View { .foregroundStyle(.secondary) } else { HStack(spacing: 8) { - TextField("Add allowlist pattern (case-insensitive globs)", text: self.$newPattern) + TextField("Add allowlist path pattern (case-insensitive globs)", text: self.$newPattern) .textFieldStyle(.roundedBorder) Button("Add") { - let pattern = self.newPattern.trimmingCharacters(in: .whitespacesAndNewlines) - guard !pattern.isEmpty else { return } - self.model.addEntry(pattern) - self.newPattern = "" + if self.model.addEntry(self.newPattern) == nil { + self.newPattern = "" + } } .buttonStyle(.bordered) - .disabled(self.newPattern.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + .disabled(!self.model.isPathPattern(self.newPattern)) + } + + Text("Path patterns only. Basename entries like \"echo\" are ignored.") + .font(.footnote) + .foregroundStyle(.secondary) + if let validationMessage = self.model.allowlistValidationMessage { + Text(validationMessage) + .font(.footnote) + .foregroundStyle(.orange) } if self.model.entries.isEmpty { @@ -234,6 +242,7 @@ final class ExecApprovalsSettingsModel { var autoAllowSkills = false var entries: [ExecAllowlistEntry] = [] var skillBins: [String] = [] + var allowlistValidationMessage: String? var agentPickerIds: [String] { [Self.defaultsScopeId] + self.agentIds @@ -289,6 +298,7 @@ final class ExecApprovalsSettingsModel { func selectAgent(_ id: String) { self.selectedAgentId = id + self.allowlistValidationMessage = nil self.loadSettings(for: id) Task { await self.refreshSkillBins() } } @@ -301,6 +311,7 @@ final class ExecApprovalsSettingsModel { self.askFallback = defaults.askFallback self.autoAllowSkills = defaults.autoAllowSkills self.entries = [] + self.allowlistValidationMessage = nil return } let resolved = ExecApprovalsStore.resolve(agentId: agentId) @@ -310,6 +321,7 @@ final class ExecApprovalsSettingsModel { self.autoAllowSkills = resolved.agent.autoAllowSkills self.entries = resolved.allowlist .sorted { $0.pattern.localizedCaseInsensitiveCompare($1.pattern) == .orderedAscending } + self.allowlistValidationMessage = nil } func setSecurity(_ security: ExecSecurity) { @@ -367,32 +379,55 @@ final class ExecApprovalsSettingsModel { Task { await self.refreshSkillBins(force: enabled) } } - func addEntry(_ pattern: String) { - guard !self.isDefaultsScope else { return } - let trimmed = pattern.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { return } - self.entries.append(ExecAllowlistEntry(pattern: trimmed, lastUsedAt: nil)) - ExecApprovalsStore.updateAllowlist(agentId: self.selectedAgentId, allowlist: self.entries) + @discardableResult + func addEntry(_ pattern: String) -> ExecAllowlistPatternValidationReason? { + guard !self.isDefaultsScope else { return nil } + switch ExecApprovalHelpers.validateAllowlistPattern(pattern) { + case .valid(let normalizedPattern): + self.entries.append(ExecAllowlistEntry(pattern: normalizedPattern, lastUsedAt: nil)) + let rejected = ExecApprovalsStore.updateAllowlist(agentId: self.selectedAgentId, allowlist: self.entries) + self.allowlistValidationMessage = rejected.first?.reason.message + return rejected.first?.reason + case .invalid(let reason): + self.allowlistValidationMessage = reason.message + return reason + } } - func updateEntry(_ entry: ExecAllowlistEntry, id: UUID) { - guard !self.isDefaultsScope else { return } - guard let index = self.entries.firstIndex(where: { $0.id == id }) else { return } - self.entries[index] = entry - ExecApprovalsStore.updateAllowlist(agentId: self.selectedAgentId, allowlist: self.entries) + @discardableResult + func updateEntry(_ entry: ExecAllowlistEntry, id: UUID) -> ExecAllowlistPatternValidationReason? { + guard !self.isDefaultsScope else { return nil } + guard let index = self.entries.firstIndex(where: { $0.id == id }) else { return nil } + var next = entry + switch ExecApprovalHelpers.validateAllowlistPattern(next.pattern) { + case .valid(let normalizedPattern): + next.pattern = normalizedPattern + case .invalid(let reason): + self.allowlistValidationMessage = reason.message + return reason + } + self.entries[index] = next + let rejected = ExecApprovalsStore.updateAllowlist(agentId: self.selectedAgentId, allowlist: self.entries) + self.allowlistValidationMessage = rejected.first?.reason.message + return rejected.first?.reason } func removeEntry(id: UUID) { guard !self.isDefaultsScope else { return } guard let index = self.entries.firstIndex(where: { $0.id == id }) else { return } self.entries.remove(at: index) - ExecApprovalsStore.updateAllowlist(agentId: self.selectedAgentId, allowlist: self.entries) + let rejected = ExecApprovalsStore.updateAllowlist(agentId: self.selectedAgentId, allowlist: self.entries) + self.allowlistValidationMessage = rejected.first?.reason.message } func entry(for id: UUID) -> ExecAllowlistEntry? { self.entries.first(where: { $0.id == id }) } + func isPathPattern(_ pattern: String) -> Bool { + ExecApprovalHelpers.isPathPattern(pattern) + } + func refreshSkillBins(force: Bool = false) async { guard self.autoAllowSkills else { self.skillBins = [] diff --git a/apps/macos/Sources/OpenClawDiscovery/TailscaleNetwork.swift b/apps/macos/Sources/OpenClawDiscovery/TailscaleNetwork.swift index 60b11306d052d..ef78e6f400ff1 100644 --- a/apps/macos/Sources/OpenClawDiscovery/TailscaleNetwork.swift +++ b/apps/macos/Sources/OpenClawDiscovery/TailscaleNetwork.swift @@ -44,4 +44,3 @@ public enum TailscaleNetwork { return nil } } - diff --git a/apps/macos/Sources/OpenClawMacCLI/ConnectCommand.swift b/apps/macos/Sources/OpenClawMacCLI/ConnectCommand.swift index 0989164a01e60..151b7fdda94c3 100644 --- a/apps/macos/Sources/OpenClawMacCLI/ConnectCommand.swift +++ b/apps/macos/Sources/OpenClawMacCLI/ConnectCommand.swift @@ -15,7 +15,7 @@ struct ConnectOptions { var clientMode: String = "ui" var displayName: String? var role: String = "operator" - var scopes: [String] = ["operator.admin", "operator.approvals", "operator.pairing"] + var scopes: [String] = defaultOperatorConnectScopes var help: Bool = false static func parse(_ args: [String]) -> ConnectOptions { diff --git a/apps/macos/Sources/OpenClawMacCLI/GatewayScopes.swift b/apps/macos/Sources/OpenClawMacCLI/GatewayScopes.swift new file mode 100644 index 0000000000000..479c176d5d844 --- /dev/null +++ b/apps/macos/Sources/OpenClawMacCLI/GatewayScopes.swift @@ -0,0 +1,7 @@ +let defaultOperatorConnectScopes: [String] = [ + "operator.admin", + "operator.read", + "operator.write", + "operator.approvals", + "operator.pairing", +] diff --git a/apps/macos/Sources/OpenClawMacCLI/WizardCommand.swift b/apps/macos/Sources/OpenClawMacCLI/WizardCommand.swift index 0a73fc2108c2b..ebe3e8ae626ad 100644 --- a/apps/macos/Sources/OpenClawMacCLI/WizardCommand.swift +++ b/apps/macos/Sources/OpenClawMacCLI/WizardCommand.swift @@ -251,7 +251,7 @@ actor GatewayWizardClient { let clientMode = "ui" let role = "operator" // Explicit scopes; gateway no longer defaults empty scopes to admin. - let scopes: [String] = ["operator.admin", "operator.approvals", "operator.pairing"] + let scopes = defaultOperatorConnectScopes let client: [String: ProtoAnyCodable] = [ "id": ProtoAnyCodable(clientId), "displayName": ProtoAnyCodable(Host.current().localizedName ?? "OpenClaw macOS Wizard CLI"), @@ -281,8 +281,8 @@ actor GatewayWizardClient { let identity = DeviceIdentityStore.loadOrCreate() let signedAtMs = Int(Date().timeIntervalSince1970 * 1000) let scopesValue = scopes.joined(separator: ",") - var payloadParts = [ - connectNonce == nil ? "v1" : "v2", + let payloadParts = [ + "v2", identity.deviceId, clientId, clientMode, @@ -290,23 +290,19 @@ actor GatewayWizardClient { scopesValue, String(signedAtMs), self.token ?? "", + connectNonce, ] - if let connectNonce { - payloadParts.append(connectNonce) - } let payload = payloadParts.joined(separator: "|") if let signature = DeviceIdentityStore.signPayload(payload, identity: identity), let publicKey = DeviceIdentityStore.publicKeyBase64Url(identity) { - var device: [String: ProtoAnyCodable] = [ + let device: [String: ProtoAnyCodable] = [ "id": ProtoAnyCodable(identity.deviceId), "publicKey": ProtoAnyCodable(publicKey), "signature": ProtoAnyCodable(signature), "signedAt": ProtoAnyCodable(signedAtMs), + "nonce": ProtoAnyCodable(connectNonce), ] - if let connectNonce { - device["nonce"] = ProtoAnyCodable(connectNonce) - } params["device"] = ProtoAnyCodable(device) } @@ -333,29 +329,24 @@ actor GatewayWizardClient { } } - private func waitForConnectChallenge() async throws -> String? { - guard let task = self.task else { return nil } - do { - return try await AsyncTimeout.withTimeout( - seconds: self.connectChallengeTimeoutSeconds, - onTimeout: { ConnectChallengeError.timeout }, - operation: { - while true { - let message = try await task.receive() - let frame = try await self.decodeFrame(message) - if case let .event(evt) = frame, evt.event == "connect.challenge" { - if let payload = evt.payload?.value as? [String: ProtoAnyCodable], - let nonce = payload["nonce"]?.value as? String - { - return nonce - } - } + private func waitForConnectChallenge() async throws -> String { + guard let task = self.task else { throw ConnectChallengeError.timeout } + return try await AsyncTimeout.withTimeout( + seconds: self.connectChallengeTimeoutSeconds, + onTimeout: { ConnectChallengeError.timeout }, + operation: { + while true { + let message = try await task.receive() + let frame = try await self.decodeFrame(message) + if case let .event(evt) = frame, evt.event == "connect.challenge", + let payload = evt.payload?.value as? [String: ProtoAnyCodable], + let nonce = payload["nonce"]?.value as? String, + nonce.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false + { + return nonce } - }) - } catch { - if error is ConnectChallengeError { return nil } - throw error - } + } + }) } } diff --git a/apps/macos/Sources/OpenClawProtocol/GatewayModels.swift b/apps/macos/Sources/OpenClawProtocol/GatewayModels.swift index 661d5dc11fd0c..2f2dd7f6090f1 100644 --- a/apps/macos/Sources/OpenClawProtocol/GatewayModels.swift +++ b/apps/macos/Sources/OpenClawProtocol/GatewayModels.swift @@ -40,8 +40,8 @@ public struct ConnectParams: Codable, Sendable { device: [String: AnyCodable]?, auth: [String: AnyCodable]?, locale: String?, - useragent: String? - ) { + useragent: String?) + { self.minprotocol = minprotocol self.maxprotocol = maxprotocol self.client = client @@ -56,6 +56,7 @@ public struct ConnectParams: Codable, Sendable { self.locale = locale self.useragent = useragent } + private enum CodingKeys: String, CodingKey { case minprotocol = "minProtocol" case maxprotocol = "maxProtocol" @@ -91,8 +92,8 @@ public struct HelloOk: Codable, Sendable { snapshot: Snapshot, canvashosturl: String?, auth: [String: AnyCodable]?, - policy: [String: AnyCodable] - ) { + policy: [String: AnyCodable]) + { self.type = type self._protocol = _protocol self.server = server @@ -102,6 +103,7 @@ public struct HelloOk: Codable, Sendable { self.auth = auth self.policy = policy } + private enum CodingKeys: String, CodingKey { case type case _protocol = "protocol" @@ -124,13 +126,14 @@ public struct RequestFrame: Codable, Sendable { type: String, id: String, method: String, - params: AnyCodable? - ) { + params: AnyCodable?) + { self.type = type self.id = id self.method = method self.params = params } + private enum CodingKeys: String, CodingKey { case type case id @@ -151,14 +154,15 @@ public struct ResponseFrame: Codable, Sendable { id: String, ok: Bool, payload: AnyCodable?, - error: [String: AnyCodable]? - ) { + error: [String: AnyCodable]?) + { self.type = type self.id = id self.ok = ok self.payload = payload self.error = error } + private enum CodingKeys: String, CodingKey { case type case id @@ -180,14 +184,15 @@ public struct EventFrame: Codable, Sendable { event: String, payload: AnyCodable?, seq: Int?, - stateversion: [String: AnyCodable]? - ) { + stateversion: [String: AnyCodable]?) + { self.type = type self.event = event self.payload = payload self.seq = seq self.stateversion = stateversion } + private enum CodingKeys: String, CodingKey { case type case event @@ -231,8 +236,8 @@ public struct PresenceEntry: Codable, Sendable { deviceid: String?, roles: [String]?, scopes: [String]?, - instanceid: String? - ) { + instanceid: String?) + { self.host = host self.ip = ip self.version = version @@ -250,6 +255,7 @@ public struct PresenceEntry: Codable, Sendable { self.scopes = scopes self.instanceid = instanceid } + private enum CodingKeys: String, CodingKey { case host case ip @@ -276,11 +282,12 @@ public struct StateVersion: Codable, Sendable { public init( presence: Int, - health: Int - ) { + health: Int) + { self.presence = presence self.health = health } + private enum CodingKeys: String, CodingKey { case presence case health @@ -307,8 +314,8 @@ public struct Snapshot: Codable, Sendable { statedir: String?, sessiondefaults: [String: AnyCodable]?, authmode: AnyCodable?, - updateavailable: [String: AnyCodable]? - ) { + updateavailable: [String: AnyCodable]?) + { self.presence = presence self.health = health self.stateversion = stateversion @@ -319,6 +326,7 @@ public struct Snapshot: Codable, Sendable { self.authmode = authmode self.updateavailable = updateavailable } + private enum CodingKeys: String, CodingKey { case presence case health @@ -344,14 +352,15 @@ public struct ErrorShape: Codable, Sendable { message: String, details: AnyCodable?, retryable: Bool?, - retryafterms: Int? - ) { + retryafterms: Int?) + { self.code = code self.message = message self.details = details self.retryable = retryable self.retryafterms = retryafterms } + private enum CodingKeys: String, CodingKey { case code case message @@ -373,14 +382,15 @@ public struct AgentEvent: Codable, Sendable { seq: Int, stream: String, ts: Int, - data: [String: AnyCodable] - ) { + data: [String: AnyCodable]) + { self.runid = runid self.seq = seq self.stream = stream self.ts = ts self.data = data } + private enum CodingKeys: String, CodingKey { case runid = "runId" case seq @@ -412,8 +422,8 @@ public struct SendParams: Codable, Sendable { accountid: String?, threadid: String?, sessionkey: String?, - idempotencykey: String - ) { + idempotencykey: String) + { self.to = to self.message = message self.mediaurl = mediaurl @@ -425,6 +435,7 @@ public struct SendParams: Codable, Sendable { self.sessionkey = sessionkey self.idempotencykey = idempotencykey } + private enum CodingKeys: String, CodingKey { case to case message @@ -465,8 +476,8 @@ public struct PollParams: Codable, Sendable { threadid: String?, channel: String?, accountid: String?, - idempotencykey: String - ) { + idempotencykey: String) + { self.to = to self.question = question self.options = options @@ -480,6 +491,7 @@ public struct PollParams: Codable, Sendable { self.accountid = accountid self.idempotencykey = idempotencykey } + private enum CodingKeys: String, CodingKey { case to case question @@ -546,8 +558,8 @@ public struct AgentParams: Codable, Sendable { inputprovenance: [String: AnyCodable]?, idempotencykey: String, label: String?, - spawnedby: String? - ) { + spawnedby: String?) + { self.message = message self.agentid = agentid self.to = to @@ -573,6 +585,7 @@ public struct AgentParams: Codable, Sendable { self.label = label self.spawnedby = spawnedby } + private enum CodingKeys: String, CodingKey { case message case agentid = "agentId" @@ -607,11 +620,12 @@ public struct AgentIdentityParams: Codable, Sendable { public init( agentid: String?, - sessionkey: String? - ) { + sessionkey: String?) + { self.agentid = agentid self.sessionkey = sessionkey } + private enum CodingKeys: String, CodingKey { case agentid = "agentId" case sessionkey = "sessionKey" @@ -628,13 +642,14 @@ public struct AgentIdentityResult: Codable, Sendable { agentid: String, name: String?, avatar: String?, - emoji: String? - ) { + emoji: String?) + { self.agentid = agentid self.name = name self.avatar = avatar self.emoji = emoji } + private enum CodingKeys: String, CodingKey { case agentid = "agentId" case name @@ -649,11 +664,12 @@ public struct AgentWaitParams: Codable, Sendable { public init( runid: String, - timeoutms: Int? - ) { + timeoutms: Int?) + { self.runid = runid self.timeoutms = timeoutms } + private enum CodingKeys: String, CodingKey { case runid = "runId" case timeoutms = "timeoutMs" @@ -666,11 +682,12 @@ public struct WakeParams: Codable, Sendable { public init( mode: AnyCodable, - text: String - ) { + text: String) + { self.mode = mode self.text = text } + private enum CodingKeys: String, CodingKey { case mode case text @@ -703,8 +720,8 @@ public struct NodePairRequestParams: Codable, Sendable { caps: [String]?, commands: [String]?, remoteip: String?, - silent: Bool? - ) { + silent: Bool?) + { self.nodeid = nodeid self.displayname = displayname self.platform = platform @@ -718,6 +735,7 @@ public struct NodePairRequestParams: Codable, Sendable { self.remoteip = remoteip self.silent = silent } + private enum CodingKeys: String, CodingKey { case nodeid = "nodeId" case displayname = "displayName" @@ -734,17 +752,17 @@ public struct NodePairRequestParams: Codable, Sendable { } } -public struct NodePairListParams: Codable, Sendable { -} +public struct NodePairListParams: Codable, Sendable {} public struct NodePairApproveParams: Codable, Sendable { public let requestid: String public init( - requestid: String - ) { + requestid: String) + { self.requestid = requestid } + private enum CodingKeys: String, CodingKey { case requestid = "requestId" } @@ -754,10 +772,11 @@ public struct NodePairRejectParams: Codable, Sendable { public let requestid: String public init( - requestid: String - ) { + requestid: String) + { self.requestid = requestid } + private enum CodingKeys: String, CodingKey { case requestid = "requestId" } @@ -769,11 +788,12 @@ public struct NodePairVerifyParams: Codable, Sendable { public init( nodeid: String, - token: String - ) { + token: String) + { self.nodeid = nodeid self.token = token } + private enum CodingKeys: String, CodingKey { case nodeid = "nodeId" case token @@ -786,28 +806,29 @@ public struct NodeRenameParams: Codable, Sendable { public init( nodeid: String, - displayname: String - ) { + displayname: String) + { self.nodeid = nodeid self.displayname = displayname } + private enum CodingKeys: String, CodingKey { case nodeid = "nodeId" case displayname = "displayName" } } -public struct NodeListParams: Codable, Sendable { -} +public struct NodeListParams: Codable, Sendable {} public struct NodeDescribeParams: Codable, Sendable { public let nodeid: String public init( - nodeid: String - ) { + nodeid: String) + { self.nodeid = nodeid } + private enum CodingKeys: String, CodingKey { case nodeid = "nodeId" } @@ -825,14 +846,15 @@ public struct NodeInvokeParams: Codable, Sendable { command: String, params: AnyCodable?, timeoutms: Int?, - idempotencykey: String - ) { + idempotencykey: String) + { self.nodeid = nodeid self.command = command self.params = params self.timeoutms = timeoutms self.idempotencykey = idempotencykey } + private enum CodingKeys: String, CodingKey { case nodeid = "nodeId" case command @@ -856,8 +878,8 @@ public struct NodeInvokeResultParams: Codable, Sendable { ok: Bool, payload: AnyCodable?, payloadjson: String?, - error: [String: AnyCodable]? - ) { + error: [String: AnyCodable]?) + { self.id = id self.nodeid = nodeid self.ok = ok @@ -865,6 +887,7 @@ public struct NodeInvokeResultParams: Codable, Sendable { self.payloadjson = payloadjson self.error = error } + private enum CodingKeys: String, CodingKey { case id case nodeid = "nodeId" @@ -883,12 +906,13 @@ public struct NodeEventParams: Codable, Sendable { public init( event: String, payload: AnyCodable?, - payloadjson: String? - ) { + payloadjson: String?) + { self.event = event self.payload = payload self.payloadjson = payloadjson } + private enum CodingKeys: String, CodingKey { case event case payload @@ -910,8 +934,8 @@ public struct NodeInvokeRequestEvent: Codable, Sendable { command: String, paramsjson: String?, timeoutms: Int?, - idempotencykey: String? - ) { + idempotencykey: String?) + { self.id = id self.nodeid = nodeid self.command = command @@ -919,6 +943,7 @@ public struct NodeInvokeRequestEvent: Codable, Sendable { self.timeoutms = timeoutms self.idempotencykey = idempotencykey } + private enum CodingKeys: String, CodingKey { case id case nodeid = "nodeId" @@ -939,13 +964,14 @@ public struct PushTestParams: Codable, Sendable { nodeid: String, title: String?, body: String?, - environment: String? - ) { + environment: String?) + { self.nodeid = nodeid self.title = title self.body = body self.environment = environment } + private enum CodingKeys: String, CodingKey { case nodeid = "nodeId" case title @@ -970,8 +996,8 @@ public struct PushTestResult: Codable, Sendable { reason: String?, tokensuffix: String, topic: String, - environment: String - ) { + environment: String) + { self.ok = ok self.status = status self.apnsid = apnsid @@ -980,6 +1006,7 @@ public struct PushTestResult: Codable, Sendable { self.topic = topic self.environment = environment } + private enum CodingKeys: String, CodingKey { case ok case status @@ -1013,8 +1040,8 @@ public struct SessionsListParams: Codable, Sendable { label: String?, spawnedby: String?, agentid: String?, - search: String? - ) { + search: String?) + { self.limit = limit self.activeminutes = activeminutes self.includeglobal = includeglobal @@ -1026,6 +1053,7 @@ public struct SessionsListParams: Codable, Sendable { self.agentid = agentid self.search = search } + private enum CodingKeys: String, CodingKey { case limit case activeminutes = "activeMinutes" @@ -1048,12 +1076,13 @@ public struct SessionsPreviewParams: Codable, Sendable { public init( keys: [String], limit: Int?, - maxchars: Int? - ) { + maxchars: Int?) + { self.keys = keys self.limit = limit self.maxchars = maxchars } + private enum CodingKeys: String, CodingKey { case keys case limit @@ -1077,8 +1106,8 @@ public struct SessionsResolveParams: Codable, Sendable { agentid: String?, spawnedby: String?, includeglobal: Bool?, - includeunknown: Bool? - ) { + includeunknown: Bool?) + { self.key = key self.sessionid = sessionid self.label = label @@ -1087,6 +1116,7 @@ public struct SessionsResolveParams: Codable, Sendable { self.includeglobal = includeglobal self.includeunknown = includeunknown } + private enum CodingKeys: String, CodingKey { case key case sessionid = "sessionId" @@ -1132,8 +1162,8 @@ public struct SessionsPatchParams: Codable, Sendable { spawnedby: AnyCodable?, spawndepth: AnyCodable?, sendpolicy: AnyCodable?, - groupactivation: AnyCodable? - ) { + groupactivation: AnyCodable?) + { self.key = key self.label = label self.thinkinglevel = thinkinglevel @@ -1151,6 +1181,7 @@ public struct SessionsPatchParams: Codable, Sendable { self.sendpolicy = sendpolicy self.groupactivation = groupactivation } + private enum CodingKeys: String, CodingKey { case key case label @@ -1177,11 +1208,12 @@ public struct SessionsResetParams: Codable, Sendable { public init( key: String, - reason: AnyCodable? - ) { + reason: AnyCodable?) + { self.key = key self.reason = reason } + private enum CodingKeys: String, CodingKey { case key case reason @@ -1191,17 +1223,22 @@ public struct SessionsResetParams: Codable, Sendable { public struct SessionsDeleteParams: Codable, Sendable { public let key: String public let deletetranscript: Bool? + public let emitlifecyclehooks: Bool? public init( key: String, - deletetranscript: Bool? - ) { + deletetranscript: Bool?, + emitlifecyclehooks: Bool?) + { self.key = key self.deletetranscript = deletetranscript + self.emitlifecyclehooks = emitlifecyclehooks } + private enum CodingKeys: String, CodingKey { case key case deletetranscript = "deleteTranscript" + case emitlifecyclehooks = "emitLifecycleHooks" } } @@ -1211,11 +1248,12 @@ public struct SessionsCompactParams: Codable, Sendable { public init( key: String, - maxlines: Int? - ) { + maxlines: Int?) + { self.key = key self.maxlines = maxlines } + private enum CodingKeys: String, CodingKey { case key case maxlines = "maxLines" @@ -1226,6 +1264,8 @@ public struct SessionsUsageParams: Codable, Sendable { public let key: String? public let startdate: String? public let enddate: String? + public let mode: AnyCodable? + public let utcoffset: String? public let limit: Int? public let includecontextweight: Bool? @@ -1233,26 +1273,32 @@ public struct SessionsUsageParams: Codable, Sendable { key: String?, startdate: String?, enddate: String?, + mode: AnyCodable?, + utcoffset: String?, limit: Int?, - includecontextweight: Bool? - ) { + includecontextweight: Bool?) + { self.key = key self.startdate = startdate self.enddate = enddate + self.mode = mode + self.utcoffset = utcoffset self.limit = limit self.includecontextweight = includecontextweight } + private enum CodingKeys: String, CodingKey { case key case startdate = "startDate" case enddate = "endDate" + case mode + case utcoffset = "utcOffset" case limit case includecontextweight = "includeContextWeight" } } -public struct ConfigGetParams: Codable, Sendable { -} +public struct ConfigGetParams: Codable, Sendable {} public struct ConfigSetParams: Codable, Sendable { public let raw: String @@ -1260,11 +1306,12 @@ public struct ConfigSetParams: Codable, Sendable { public init( raw: String, - basehash: String? - ) { + basehash: String?) + { self.raw = raw self.basehash = basehash } + private enum CodingKeys: String, CodingKey { case raw case basehash = "baseHash" @@ -1283,14 +1330,15 @@ public struct ConfigApplyParams: Codable, Sendable { basehash: String?, sessionkey: String?, note: String?, - restartdelayms: Int? - ) { + restartdelayms: Int?) + { self.raw = raw self.basehash = basehash self.sessionkey = sessionkey self.note = note self.restartdelayms = restartdelayms } + private enum CodingKeys: String, CodingKey { case raw case basehash = "baseHash" @@ -1312,14 +1360,15 @@ public struct ConfigPatchParams: Codable, Sendable { basehash: String?, sessionkey: String?, note: String?, - restartdelayms: Int? - ) { + restartdelayms: Int?) + { self.raw = raw self.basehash = basehash self.sessionkey = sessionkey self.note = note self.restartdelayms = restartdelayms } + private enum CodingKeys: String, CodingKey { case raw case basehash = "baseHash" @@ -1329,8 +1378,7 @@ public struct ConfigPatchParams: Codable, Sendable { } } -public struct ConfigSchemaParams: Codable, Sendable { -} +public struct ConfigSchemaParams: Codable, Sendable {} public struct ConfigSchemaResponse: Codable, Sendable { public let schema: AnyCodable @@ -1342,13 +1390,14 @@ public struct ConfigSchemaResponse: Codable, Sendable { schema: AnyCodable, uihints: [String: AnyCodable], version: String, - generatedat: 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" @@ -1363,11 +1412,12 @@ public struct WizardStartParams: Codable, Sendable { public init( mode: AnyCodable?, - workspace: String? - ) { + workspace: String?) + { self.mode = mode self.workspace = workspace } + private enum CodingKeys: String, CodingKey { case mode case workspace @@ -1380,11 +1430,12 @@ public struct WizardNextParams: Codable, Sendable { public init( sessionid: String, - answer: [String: AnyCodable]? - ) { + answer: [String: AnyCodable]?) + { self.sessionid = sessionid self.answer = answer } + private enum CodingKeys: String, CodingKey { case sessionid = "sessionId" case answer @@ -1395,10 +1446,11 @@ public struct WizardCancelParams: Codable, Sendable { public let sessionid: String public init( - sessionid: String - ) { + sessionid: String) + { self.sessionid = sessionid } + private enum CodingKeys: String, CodingKey { case sessionid = "sessionId" } @@ -1408,10 +1460,11 @@ public struct WizardStatusParams: Codable, Sendable { public let sessionid: String public init( - sessionid: String - ) { + sessionid: String) + { self.sessionid = sessionid } + private enum CodingKeys: String, CodingKey { case sessionid = "sessionId" } @@ -1437,8 +1490,8 @@ public struct WizardStep: Codable, Sendable { initialvalue: AnyCodable?, placeholder: String?, sensitive: Bool?, - executor: AnyCodable? - ) { + executor: AnyCodable?) + { self.id = id self.type = type self.title = title @@ -1449,6 +1502,7 @@ public struct WizardStep: Codable, Sendable { self.sensitive = sensitive self.executor = executor } + private enum CodingKeys: String, CodingKey { case id case type @@ -1472,13 +1526,14 @@ public struct WizardNextResult: Codable, Sendable { done: Bool, step: [String: AnyCodable]?, status: AnyCodable?, - error: String? - ) { + error: String?) + { self.done = done self.step = step self.status = status self.error = error } + private enum CodingKeys: String, CodingKey { case done case step @@ -1499,14 +1554,15 @@ public struct WizardStartResult: Codable, Sendable { done: Bool, step: [String: AnyCodable]?, status: AnyCodable?, - error: String? - ) { + 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 @@ -1522,11 +1578,12 @@ public struct WizardStatusResult: Codable, Sendable { public init( status: AnyCodable, - error: String? - ) { + error: String?) + { self.status = status self.error = error } + private enum CodingKeys: String, CodingKey { case status case error @@ -1539,11 +1596,12 @@ public struct TalkModeParams: Codable, Sendable { public init( enabled: Bool, - phase: String? - ) { + phase: String?) + { self.enabled = enabled self.phase = phase } + private enum CodingKeys: String, CodingKey { case enabled case phase @@ -1554,10 +1612,11 @@ public struct TalkConfigParams: Codable, Sendable { public let includesecrets: Bool? public init( - includesecrets: Bool? - ) { + includesecrets: Bool?) + { self.includesecrets = includesecrets } + private enum CodingKeys: String, CodingKey { case includesecrets = "includeSecrets" } @@ -1567,10 +1626,11 @@ public struct TalkConfigResult: Codable, Sendable { public let config: [String: AnyCodable] public init( - config: [String: AnyCodable] - ) { + config: [String: AnyCodable]) + { self.config = config } + private enum CodingKeys: String, CodingKey { case config } @@ -1582,11 +1642,12 @@ public struct ChannelsStatusParams: Codable, Sendable { public init( probe: Bool?, - timeoutms: Int? - ) { + timeoutms: Int?) + { self.probe = probe self.timeoutms = timeoutms } + private enum CodingKeys: String, CodingKey { case probe case timeoutms = "timeoutMs" @@ -1613,8 +1674,8 @@ public struct ChannelsStatusResult: Codable, Sendable { channelmeta: [[String: AnyCodable]]?, channels: [String: AnyCodable], channelaccounts: [String: AnyCodable], - channeldefaultaccountid: [String: AnyCodable] - ) { + channeldefaultaccountid: [String: AnyCodable]) + { self.ts = ts self.channelorder = channelorder self.channellabels = channellabels @@ -1625,6 +1686,7 @@ public struct ChannelsStatusResult: Codable, Sendable { self.channelaccounts = channelaccounts self.channeldefaultaccountid = channeldefaultaccountid } + private enum CodingKeys: String, CodingKey { case ts case channelorder = "channelOrder" @@ -1644,11 +1706,12 @@ public struct ChannelsLogoutParams: Codable, Sendable { public init( channel: String, - accountid: String? - ) { + accountid: String?) + { self.channel = channel self.accountid = accountid } + private enum CodingKeys: String, CodingKey { case channel case accountid = "accountId" @@ -1665,13 +1728,14 @@ public struct WebLoginStartParams: Codable, Sendable { force: Bool?, timeoutms: Int?, verbose: Bool?, - accountid: String? - ) { + accountid: String?) + { self.force = force self.timeoutms = timeoutms self.verbose = verbose self.accountid = accountid } + private enum CodingKeys: String, CodingKey { case force case timeoutms = "timeoutMs" @@ -1686,11 +1750,12 @@ public struct WebLoginWaitParams: Codable, Sendable { public init( timeoutms: Int?, - accountid: String? - ) { + accountid: String?) + { self.timeoutms = timeoutms self.accountid = accountid } + private enum CodingKeys: String, CodingKey { case timeoutms = "timeoutMs" case accountid = "accountId" @@ -1705,12 +1770,13 @@ public struct AgentSummary: Codable, Sendable { public init( id: String, name: String?, - identity: [String: AnyCodable]? - ) { + identity: [String: AnyCodable]?) + { self.id = id self.name = name self.identity = identity } + private enum CodingKeys: String, CodingKey { case id case name @@ -1728,13 +1794,14 @@ public struct AgentsCreateParams: Codable, Sendable { name: String, workspace: String, emoji: String?, - avatar: String? - ) { + avatar: String?) + { self.name = name self.workspace = workspace self.emoji = emoji self.avatar = avatar } + private enum CodingKeys: String, CodingKey { case name case workspace @@ -1753,13 +1820,14 @@ public struct AgentsCreateResult: Codable, Sendable { ok: Bool, agentid: String, name: String, - workspace: String - ) { + workspace: String) + { self.ok = ok self.agentid = agentid self.name = name self.workspace = workspace } + private enum CodingKeys: String, CodingKey { case ok case agentid = "agentId" @@ -1780,14 +1848,15 @@ public struct AgentsUpdateParams: Codable, Sendable { name: String?, workspace: String?, model: String?, - avatar: String? - ) { + avatar: String?) + { self.agentid = agentid self.name = name self.workspace = workspace self.model = model self.avatar = avatar } + private enum CodingKeys: String, CodingKey { case agentid = "agentId" case name @@ -1803,11 +1872,12 @@ public struct AgentsUpdateResult: Codable, Sendable { public init( ok: Bool, - agentid: String - ) { + agentid: String) + { self.ok = ok self.agentid = agentid } + private enum CodingKeys: String, CodingKey { case ok case agentid = "agentId" @@ -1820,11 +1890,12 @@ public struct AgentsDeleteParams: Codable, Sendable { public init( agentid: String, - deletefiles: Bool? - ) { + deletefiles: Bool?) + { self.agentid = agentid self.deletefiles = deletefiles } + private enum CodingKeys: String, CodingKey { case agentid = "agentId" case deletefiles = "deleteFiles" @@ -1839,12 +1910,13 @@ public struct AgentsDeleteResult: Codable, Sendable { public init( ok: Bool, agentid: String, - removedbindings: Int - ) { + removedbindings: Int) + { self.ok = ok self.agentid = agentid self.removedbindings = removedbindings } + private enum CodingKeys: String, CodingKey { case ok case agentid = "agentId" @@ -1866,8 +1938,8 @@ public struct AgentsFileEntry: Codable, Sendable { missing: Bool, size: Int?, updatedatms: Int?, - content: String? - ) { + content: String?) + { self.name = name self.path = path self.missing = missing @@ -1875,6 +1947,7 @@ public struct AgentsFileEntry: Codable, Sendable { self.updatedatms = updatedatms self.content = content } + private enum CodingKeys: String, CodingKey { case name case path @@ -1889,10 +1962,11 @@ public struct AgentsFilesListParams: Codable, Sendable { public let agentid: String public init( - agentid: String - ) { + agentid: String) + { self.agentid = agentid } + private enum CodingKeys: String, CodingKey { case agentid = "agentId" } @@ -1906,12 +1980,13 @@ public struct AgentsFilesListResult: Codable, Sendable { public init( agentid: String, workspace: String, - files: [AgentsFileEntry] - ) { + files: [AgentsFileEntry]) + { self.agentid = agentid self.workspace = workspace self.files = files } + private enum CodingKeys: String, CodingKey { case agentid = "agentId" case workspace @@ -1925,11 +2000,12 @@ public struct AgentsFilesGetParams: Codable, Sendable { public init( agentid: String, - name: String - ) { + name: String) + { self.agentid = agentid self.name = name } + private enum CodingKeys: String, CodingKey { case agentid = "agentId" case name @@ -1944,12 +2020,13 @@ public struct AgentsFilesGetResult: Codable, Sendable { public init( agentid: String, workspace: String, - file: AgentsFileEntry - ) { + file: AgentsFileEntry) + { self.agentid = agentid self.workspace = workspace self.file = file } + private enum CodingKeys: String, CodingKey { case agentid = "agentId" case workspace @@ -1965,12 +2042,13 @@ public struct AgentsFilesSetParams: Codable, Sendable { public init( agentid: String, name: String, - content: String - ) { + content: String) + { self.agentid = agentid self.name = name self.content = content } + private enum CodingKeys: String, CodingKey { case agentid = "agentId" case name @@ -1988,13 +2066,14 @@ public struct AgentsFilesSetResult: Codable, Sendable { ok: Bool, agentid: String, workspace: String, - file: AgentsFileEntry - ) { + file: AgentsFileEntry) + { self.ok = ok self.agentid = agentid self.workspace = workspace self.file = file } + private enum CodingKeys: String, CodingKey { case ok case agentid = "agentId" @@ -2003,8 +2082,7 @@ public struct AgentsFilesSetResult: Codable, Sendable { } } -public struct AgentsListParams: Codable, Sendable { -} +public struct AgentsListParams: Codable, Sendable {} public struct AgentsListResult: Codable, Sendable { public let defaultid: String @@ -2016,13 +2094,14 @@ public struct AgentsListResult: Codable, Sendable { defaultid: String, mainkey: String, scope: AnyCodable, - agents: [AgentSummary] - ) { + agents: [AgentSummary]) + { self.defaultid = defaultid self.mainkey = mainkey self.scope = scope self.agents = agents } + private enum CodingKeys: String, CodingKey { case defaultid = "defaultId" case mainkey = "mainKey" @@ -2043,14 +2122,15 @@ public struct ModelChoice: Codable, Sendable { name: String, provider: String, contextwindow: Int?, - reasoning: Bool? - ) { + reasoning: Bool?) + { self.id = id self.name = name self.provider = provider self.contextwindow = contextwindow self.reasoning = reasoning } + private enum CodingKeys: String, CodingKey { case id case name @@ -2060,17 +2140,17 @@ public struct ModelChoice: Codable, Sendable { } } -public struct ModelsListParams: Codable, Sendable { -} +public struct ModelsListParams: Codable, Sendable {} public struct ModelsListResult: Codable, Sendable { public let models: [ModelChoice] public init( - models: [ModelChoice] - ) { + models: [ModelChoice]) + { self.models = models } + private enum CodingKeys: String, CodingKey { case models } @@ -2080,26 +2160,27 @@ public struct SkillsStatusParams: Codable, Sendable { public let agentid: String? public init( - agentid: String? - ) { + agentid: String?) + { self.agentid = agentid } + private enum CodingKeys: String, CodingKey { case agentid = "agentId" } } -public struct SkillsBinsParams: Codable, Sendable { -} +public struct SkillsBinsParams: Codable, Sendable {} public struct SkillsBinsResult: Codable, Sendable { public let bins: [String] public init( - bins: [String] - ) { + bins: [String]) + { self.bins = bins } + private enum CodingKeys: String, CodingKey { case bins } @@ -2113,12 +2194,13 @@ public struct SkillsInstallParams: Codable, Sendable { public init( name: String, installid: String, - timeoutms: Int? - ) { + timeoutms: Int?) + { self.name = name self.installid = installid self.timeoutms = timeoutms } + private enum CodingKeys: String, CodingKey { case name case installid = "installId" @@ -2136,13 +2218,14 @@ public struct SkillsUpdateParams: Codable, Sendable { skillkey: String, enabled: Bool?, apikey: String?, - env: [String: AnyCodable]? - ) { + env: [String: AnyCodable]?) + { self.skillkey = skillkey self.enabled = enabled self.apikey = apikey self.env = env } + private enum CodingKeys: String, CodingKey { case skillkey = "skillKey" case enabled @@ -2183,8 +2266,8 @@ public struct CronJob: Codable, Sendable { wakemode: AnyCodable, payload: AnyCodable, delivery: AnyCodable?, - state: [String: AnyCodable] - ) { + state: [String: AnyCodable]) + { self.id = id self.agentid = agentid self.sessionkey = sessionkey @@ -2201,6 +2284,7 @@ public struct CronJob: Codable, Sendable { self.delivery = delivery self.state = state } + private enum CodingKeys: String, CodingKey { case id case agentid = "agentId" @@ -2224,17 +2308,17 @@ public struct CronListParams: Codable, Sendable { public let includedisabled: Bool? public init( - includedisabled: Bool? - ) { + includedisabled: Bool?) + { self.includedisabled = includedisabled } + private enum CodingKeys: String, CodingKey { case includedisabled = "includeDisabled" } } -public struct CronStatusParams: Codable, Sendable { -} +public struct CronStatusParams: Codable, Sendable {} public struct CronAddParams: Codable, Sendable { public let name: String @@ -2260,8 +2344,8 @@ public struct CronAddParams: Codable, Sendable { sessiontarget: AnyCodable, wakemode: AnyCodable, payload: AnyCodable, - delivery: AnyCodable? - ) { + delivery: AnyCodable?) + { self.name = name self.agentid = agentid self.sessionkey = sessionkey @@ -2274,6 +2358,7 @@ public struct CronAddParams: Codable, Sendable { self.payload = payload self.delivery = delivery } + private enum CodingKeys: String, CodingKey { case name case agentid = "agentId" @@ -2313,8 +2398,8 @@ public struct CronRunLogEntry: Codable, Sendable { sessionkey: String?, runatms: Int?, durationms: Int?, - nextrunatms: Int? - ) { + nextrunatms: Int?) + { self.ts = ts self.jobid = jobid self.action = action @@ -2327,6 +2412,7 @@ public struct CronRunLogEntry: Codable, Sendable { self.durationms = durationms self.nextrunatms = nextrunatms } + private enum CodingKeys: String, CodingKey { case ts case jobid = "jobId" @@ -2350,12 +2436,13 @@ public struct LogsTailParams: Codable, Sendable { public init( cursor: Int?, limit: Int?, - maxbytes: Int? - ) { + maxbytes: Int?) + { self.cursor = cursor self.limit = limit self.maxbytes = maxbytes } + private enum CodingKeys: String, CodingKey { case cursor case limit @@ -2377,8 +2464,8 @@ public struct LogsTailResult: Codable, Sendable { size: Int, lines: [String], truncated: Bool?, - reset: Bool? - ) { + reset: Bool?) + { self.file = file self.cursor = cursor self.size = size @@ -2386,6 +2473,7 @@ public struct LogsTailResult: Codable, Sendable { self.truncated = truncated self.reset = reset } + private enum CodingKeys: String, CodingKey { case file case cursor @@ -2396,8 +2484,7 @@ public struct LogsTailResult: Codable, Sendable { } } -public struct ExecApprovalsGetParams: Codable, Sendable { -} +public struct ExecApprovalsGetParams: Codable, Sendable {} public struct ExecApprovalsSetParams: Codable, Sendable { public let file: [String: AnyCodable] @@ -2405,11 +2492,12 @@ public struct ExecApprovalsSetParams: Codable, Sendable { public init( file: [String: AnyCodable], - basehash: String? - ) { + basehash: String?) + { self.file = file self.basehash = basehash } + private enum CodingKeys: String, CodingKey { case file case basehash = "baseHash" @@ -2420,10 +2508,11 @@ public struct ExecApprovalsNodeGetParams: Codable, Sendable { public let nodeid: String public init( - nodeid: String - ) { + nodeid: String) + { self.nodeid = nodeid } + private enum CodingKeys: String, CodingKey { case nodeid = "nodeId" } @@ -2437,12 +2526,13 @@ public struct ExecApprovalsNodeSetParams: Codable, Sendable { public init( nodeid: String, file: [String: AnyCodable], - basehash: String? - ) { + basehash: String?) + { self.nodeid = nodeid self.file = file self.basehash = basehash } + private enum CodingKeys: String, CodingKey { case nodeid = "nodeId" case file @@ -2460,13 +2550,14 @@ public struct ExecApprovalsSnapshot: Codable, Sendable { path: String, exists: Bool, hash: String, - file: [String: AnyCodable] - ) { + file: [String: AnyCodable]) + { self.path = path self.exists = exists self.hash = hash self.file = file } + private enum CodingKeys: String, CodingKey { case path case exists @@ -2499,8 +2590,8 @@ public struct ExecApprovalRequestParams: Codable, Sendable { resolvedpath: AnyCodable?, sessionkey: AnyCodable?, timeoutms: Int?, - twophase: Bool? - ) { + twophase: Bool?) + { self.id = id self.command = command self.cwd = cwd @@ -2513,6 +2604,7 @@ public struct ExecApprovalRequestParams: Codable, Sendable { self.timeoutms = timeoutms self.twophase = twophase } + private enum CodingKeys: String, CodingKey { case id case command @@ -2534,28 +2626,29 @@ public struct ExecApprovalResolveParams: Codable, Sendable { public init( id: String, - decision: String - ) { + decision: String) + { self.id = id self.decision = decision } + private enum CodingKeys: String, CodingKey { case id case decision } } -public struct DevicePairListParams: Codable, Sendable { -} +public struct DevicePairListParams: Codable, Sendable {} public struct DevicePairApproveParams: Codable, Sendable { public let requestid: String public init( - requestid: String - ) { + requestid: String) + { self.requestid = requestid } + private enum CodingKeys: String, CodingKey { case requestid = "requestId" } @@ -2565,10 +2658,11 @@ public struct DevicePairRejectParams: Codable, Sendable { public let requestid: String public init( - requestid: String - ) { + requestid: String) + { self.requestid = requestid } + private enum CodingKeys: String, CodingKey { case requestid = "requestId" } @@ -2578,10 +2672,11 @@ public struct DevicePairRemoveParams: Codable, Sendable { public let deviceid: String public init( - deviceid: String - ) { + deviceid: String) + { self.deviceid = deviceid } + private enum CodingKeys: String, CodingKey { case deviceid = "deviceId" } @@ -2595,12 +2690,13 @@ public struct DeviceTokenRotateParams: Codable, Sendable { public init( deviceid: String, role: String, - scopes: [String]? - ) { + scopes: [String]?) + { self.deviceid = deviceid self.role = role self.scopes = scopes } + private enum CodingKeys: String, CodingKey { case deviceid = "deviceId" case role @@ -2614,11 +2710,12 @@ public struct DeviceTokenRevokeParams: Codable, Sendable { public init( deviceid: String, - role: String - ) { + role: String) + { self.deviceid = deviceid self.role = role } + private enum CodingKeys: String, CodingKey { case deviceid = "deviceId" case role @@ -2655,8 +2752,8 @@ public struct DevicePairRequestedEvent: Codable, Sendable { remoteip: String?, silent: Bool?, isrepair: Bool?, - ts: Int - ) { + ts: Int) + { self.requestid = requestid self.deviceid = deviceid self.publickey = publickey @@ -2672,6 +2769,7 @@ public struct DevicePairRequestedEvent: Codable, Sendable { self.isrepair = isrepair self.ts = ts } + private enum CodingKeys: String, CodingKey { case requestid = "requestId" case deviceid = "deviceId" @@ -2700,13 +2798,14 @@ public struct DevicePairResolvedEvent: Codable, Sendable { requestid: String, deviceid: String, decision: String, - ts: Int - ) { + ts: Int) + { self.requestid = requestid self.deviceid = deviceid self.decision = decision self.ts = ts } + private enum CodingKeys: String, CodingKey { case requestid = "requestId" case deviceid = "deviceId" @@ -2721,11 +2820,12 @@ public struct ChatHistoryParams: Codable, Sendable { public init( sessionkey: String, - limit: Int? - ) { + limit: Int?) + { self.sessionkey = sessionkey self.limit = limit } + private enum CodingKeys: String, CodingKey { case sessionkey = "sessionKey" case limit @@ -2748,8 +2848,8 @@ public struct ChatSendParams: Codable, Sendable { deliver: Bool?, attachments: [AnyCodable]?, timeoutms: Int?, - idempotencykey: String - ) { + idempotencykey: String) + { self.sessionkey = sessionkey self.message = message self.thinking = thinking @@ -2758,6 +2858,7 @@ public struct ChatSendParams: Codable, Sendable { self.timeoutms = timeoutms self.idempotencykey = idempotencykey } + private enum CodingKeys: String, CodingKey { case sessionkey = "sessionKey" case message @@ -2775,11 +2876,12 @@ public struct ChatAbortParams: Codable, Sendable { public init( sessionkey: String, - runid: String? - ) { + runid: String?) + { self.sessionkey = sessionkey self.runid = runid } + private enum CodingKeys: String, CodingKey { case sessionkey = "sessionKey" case runid = "runId" @@ -2794,12 +2896,13 @@ public struct ChatInjectParams: Codable, Sendable { public init( sessionkey: String, message: String, - label: String? - ) { + label: String?) + { self.sessionkey = sessionkey self.message = message self.label = label } + private enum CodingKeys: String, CodingKey { case sessionkey = "sessionKey" case message @@ -2825,8 +2928,8 @@ public struct ChatEvent: Codable, Sendable { message: AnyCodable?, errormessage: String?, usage: AnyCodable?, - stopreason: String? - ) { + stopreason: String?) + { self.runid = runid self.sessionkey = sessionkey self.seq = seq @@ -2836,6 +2939,7 @@ public struct ChatEvent: Codable, Sendable { self.usage = usage self.stopreason = stopreason } + private enum CodingKeys: String, CodingKey { case runid = "runId" case sessionkey = "sessionKey" @@ -2858,13 +2962,14 @@ public struct UpdateRunParams: Codable, Sendable { sessionkey: String?, note: String?, restartdelayms: Int?, - timeoutms: Int? - ) { + timeoutms: Int?) + { self.sessionkey = sessionkey self.note = note self.restartdelayms = restartdelayms self.timeoutms = timeoutms } + private enum CodingKeys: String, CodingKey { case sessionkey = "sessionKey" case note @@ -2877,10 +2982,11 @@ public struct TickEvent: Codable, Sendable { public let ts: Int public init( - ts: Int - ) { + ts: Int) + { self.ts = ts } + private enum CodingKeys: String, CodingKey { case ts } @@ -2892,11 +2998,12 @@ public struct ShutdownEvent: Codable, Sendable { public init( reason: String, - restartexpectedms: Int? - ) { + restartexpectedms: Int?) + { self.reason = reason self.restartexpectedms = restartexpectedms } + private enum CodingKeys: String, CodingKey { case reason case restartexpectedms = "restartExpectedMs" @@ -2918,11 +3025,11 @@ public enum GatewayFrame: Codable, Sendable { let type = try typeContainer.decode(String.self, forKey: .type) switch type { case "req": - self = .req(try RequestFrame(from: decoder)) + self = try .req(RequestFrame(from: decoder)) case "res": - self = .res(try ResponseFrame(from: decoder)) + self = try .res(ResponseFrame(from: decoder)) case "event": - self = .event(try EventFrame(from: decoder)) + self = try .event(EventFrame(from: decoder)) default: let container = try decoder.singleValueContainer() let raw = try container.decode([String: AnyCodable].self) @@ -2932,13 +3039,15 @@ public enum GatewayFrame: Codable, Sendable { public func encode(to encoder: Encoder) throws { switch self { - case .req(let v): try v.encode(to: encoder) - case .res(let v): try v.encode(to: encoder) - case .event(let v): try v.encode(to: encoder) - case .unknown(_, let raw): + case let .req(v): + try v.encode(to: encoder) + case let .res(v): + try v.encode(to: encoder) + case let .event(v): + try v.encode(to: encoder) + case let .unknown(_, raw): var container = encoder.singleValueContainer() try container.encode(raw) } } - } diff --git a/apps/macos/Tests/OpenClawIPCTests/ExecAllowlistTests.swift b/apps/macos/Tests/OpenClawIPCTests/ExecAllowlistTests.swift index 7da886ea794f4..3b27740d06647 100644 --- a/apps/macos/Tests/OpenClawIPCTests/ExecAllowlistTests.swift +++ b/apps/macos/Tests/OpenClawIPCTests/ExecAllowlistTests.swift @@ -2,7 +2,55 @@ import Foundation import Testing @testable import OpenClaw +/// These cases cover optional `security=allowlist` behavior. +/// Default install posture remains deny-by-default for exec on macOS node-host. struct ExecAllowlistTests { + private struct ShellParserParityFixture: Decodable { + struct Case: Decodable { + let id: String + let command: String + let ok: Bool + let executables: [String] + } + + let cases: [Case] + } + + private struct WrapperResolutionParityFixture: Decodable { + struct Case: Decodable { + let id: String + let argv: [String] + let expectedRawExecutable: String? + } + + let cases: [Case] + } + + private static func loadShellParserParityCases() throws -> [ShellParserParityFixture.Case] { + let fixtureURL = self.fixtureURL(filename: "exec-allowlist-shell-parser-parity.json") + let data = try Data(contentsOf: fixtureURL) + let fixture = try JSONDecoder().decode(ShellParserParityFixture.self, from: data) + return fixture.cases + } + + private static func loadWrapperResolutionParityCases() throws -> [WrapperResolutionParityFixture.Case] { + let fixtureURL = self.fixtureURL(filename: "exec-wrapper-resolution-parity.json") + let data = try Data(contentsOf: fixtureURL) + let fixture = try JSONDecoder().decode(WrapperResolutionParityFixture.self, from: data) + return fixture.cases + } + + private static func fixtureURL(filename: String) -> URL { + var repoRoot = URL(fileURLWithPath: #filePath) + for _ in 0..<5 { + repoRoot.deleteLastPathComponent() + } + return repoRoot + .appendingPathComponent("test") + .appendingPathComponent("fixtures") + .appendingPathComponent(filename) + } + @Test func matchUsesResolvedPath() { let entry = ExecAllowlistEntry(pattern: "/opt/homebrew/bin/rg") let resolution = ExecCommandResolution( @@ -14,7 +62,7 @@ struct ExecAllowlistTests { #expect(match?.pattern == entry.pattern) } - @Test func matchUsesBasenameForSimplePattern() { + @Test func matchIgnoresBasenamePattern() { let entry = ExecAllowlistEntry(pattern: "rg") let resolution = ExecCommandResolution( rawExecutable: "rg", @@ -22,11 +70,22 @@ struct ExecAllowlistTests { executableName: "rg", cwd: nil) let match = ExecAllowlistMatcher.match(entries: [entry], resolution: resolution) - #expect(match?.pattern == entry.pattern) + #expect(match == nil) + } + + @Test func matchIgnoresBasenameForRelativeExecutable() { + let entry = ExecAllowlistEntry(pattern: "echo") + let resolution = ExecCommandResolution( + rawExecutable: "./echo", + resolvedPath: "/tmp/oc-basename/echo", + executableName: "echo", + cwd: "/tmp/oc-basename") + let match = ExecAllowlistMatcher.match(entries: [entry], resolution: resolution) + #expect(match == nil) } @Test func matchIsCaseInsensitive() { - let entry = ExecAllowlistEntry(pattern: "RG") + let entry = ExecAllowlistEntry(pattern: "/OPT/HOMEBREW/BIN/RG") let resolution = ExecCommandResolution( rawExecutable: "rg", resolvedPath: "/opt/homebrew/bin/rg", @@ -46,4 +105,145 @@ struct ExecAllowlistTests { let match = ExecAllowlistMatcher.match(entries: [entry], resolution: resolution) #expect(match?.pattern == entry.pattern) } + + @Test func resolveForAllowlistSplitsShellChains() { + let command = ["/bin/sh", "-lc", "echo allowlisted && /usr/bin/touch /tmp/openclaw-allowlist-test"] + let resolutions = ExecCommandResolution.resolveForAllowlist( + command: command, + rawCommand: "echo allowlisted && /usr/bin/touch /tmp/openclaw-allowlist-test", + cwd: nil, + env: ["PATH": "/usr/bin:/bin"]) + #expect(resolutions.count == 2) + #expect(resolutions[0].executableName == "echo") + #expect(resolutions[1].executableName == "touch") + } + + @Test func resolveForAllowlistKeepsQuotedOperatorsInSingleSegment() { + let command = ["/bin/sh", "-lc", "echo \"a && b\""] + let resolutions = ExecCommandResolution.resolveForAllowlist( + command: command, + rawCommand: "echo \"a && b\"", + cwd: nil, + env: ["PATH": "/usr/bin:/bin"]) + #expect(resolutions.count == 1) + #expect(resolutions[0].executableName == "echo") + } + + @Test func resolveForAllowlistFailsClosedOnCommandSubstitution() { + let command = ["/bin/sh", "-lc", "echo $(/usr/bin/touch /tmp/openclaw-allowlist-test-subst)"] + let resolutions = ExecCommandResolution.resolveForAllowlist( + command: command, + rawCommand: "echo $(/usr/bin/touch /tmp/openclaw-allowlist-test-subst)", + cwd: nil, + env: ["PATH": "/usr/bin:/bin"]) + #expect(resolutions.isEmpty) + } + + @Test func resolveForAllowlistFailsClosedOnQuotedCommandSubstitution() { + let command = ["/bin/sh", "-lc", "echo \"ok $(/usr/bin/touch /tmp/openclaw-allowlist-test-quoted-subst)\""] + let resolutions = ExecCommandResolution.resolveForAllowlist( + command: command, + rawCommand: "echo \"ok $(/usr/bin/touch /tmp/openclaw-allowlist-test-quoted-subst)\"", + cwd: nil, + env: ["PATH": "/usr/bin:/bin"]) + #expect(resolutions.isEmpty) + } + + @Test func resolveForAllowlistFailsClosedOnQuotedBackticks() { + let command = ["/bin/sh", "-lc", "echo \"ok `/usr/bin/id`\""] + let resolutions = ExecCommandResolution.resolveForAllowlist( + command: command, + rawCommand: "echo \"ok `/usr/bin/id`\"", + cwd: nil, + env: ["PATH": "/usr/bin:/bin"]) + #expect(resolutions.isEmpty) + } + + @Test func resolveForAllowlistMatchesSharedShellParserFixture() throws { + let fixtures = try Self.loadShellParserParityCases() + for fixture in fixtures { + let resolutions = ExecCommandResolution.resolveForAllowlist( + command: ["/bin/sh", "-lc", fixture.command], + rawCommand: fixture.command, + cwd: nil, + env: ["PATH": "/usr/bin:/bin"]) + + #expect(!resolutions.isEmpty == fixture.ok) + if fixture.ok { + let executables = resolutions.map { $0.executableName.lowercased() } + let expected = fixture.executables.map { $0.lowercased() } + #expect(executables == expected) + } + } + } + + @Test func resolveMatchesSharedWrapperResolutionFixture() throws { + let fixtures = try Self.loadWrapperResolutionParityCases() + for fixture in fixtures { + let resolution = ExecCommandResolution.resolve( + command: fixture.argv, + cwd: nil, + env: ["PATH": "/usr/bin:/bin"]) + #expect(resolution?.rawExecutable == fixture.expectedRawExecutable) + } + } + + @Test func resolveForAllowlistTreatsPlainShInvocationAsDirectExec() { + let command = ["/bin/sh", "./script.sh"] + let resolutions = ExecCommandResolution.resolveForAllowlist( + command: command, + rawCommand: nil, + cwd: "/tmp", + env: ["PATH": "/usr/bin:/bin"]) + #expect(resolutions.count == 1) + #expect(resolutions[0].executableName == "sh") + } + + @Test func resolveForAllowlistUnwrapsEnvShellWrapperChains() { + let command = ["/usr/bin/env", "/bin/sh", "-lc", "echo allowlisted && /usr/bin/touch /tmp/openclaw-allowlist-test"] + let resolutions = ExecCommandResolution.resolveForAllowlist( + command: command, + rawCommand: nil, + cwd: nil, + env: ["PATH": "/usr/bin:/bin"]) + #expect(resolutions.count == 2) + #expect(resolutions[0].executableName == "echo") + #expect(resolutions[1].executableName == "touch") + } + + @Test func resolveForAllowlistUnwrapsEnvToEffectiveDirectExecutable() { + let command = ["/usr/bin/env", "FOO=bar", "/usr/bin/printf", "ok"] + let resolutions = ExecCommandResolution.resolveForAllowlist( + command: command, + rawCommand: nil, + cwd: nil, + env: ["PATH": "/usr/bin:/bin"]) + #expect(resolutions.count == 1) + #expect(resolutions[0].resolvedPath == "/usr/bin/printf") + #expect(resolutions[0].executableName == "printf") + } + + @Test func matchAllRequiresEverySegmentToMatch() { + let first = ExecCommandResolution( + rawExecutable: "echo", + resolvedPath: "/usr/bin/echo", + executableName: "echo", + cwd: nil) + let second = ExecCommandResolution( + rawExecutable: "/usr/bin/touch", + resolvedPath: "/usr/bin/touch", + executableName: "touch", + cwd: nil) + let resolutions = [first, second] + + let partial = ExecAllowlistMatcher.matchAll( + entries: [ExecAllowlistEntry(pattern: "/usr/bin/echo")], + resolutions: resolutions) + #expect(partial.isEmpty) + + let full = ExecAllowlistMatcher.matchAll( + entries: [ExecAllowlistEntry(pattern: "/USR/BIN/ECHO"), ExecAllowlistEntry(pattern: "/usr/bin/touch")], + resolutions: resolutions) + #expect(full.count == 2) + } } diff --git a/apps/macos/Tests/OpenClawIPCTests/ExecApprovalHelpersTests.swift b/apps/macos/Tests/OpenClawIPCTests/ExecApprovalHelpersTests.swift index 760d6c9178e78..455b4296753c4 100644 --- a/apps/macos/Tests/OpenClawIPCTests/ExecApprovalHelpersTests.swift +++ b/apps/macos/Tests/OpenClawIPCTests/ExecApprovalHelpersTests.swift @@ -29,6 +29,24 @@ import Testing #expect(ExecApprovalHelpers.allowlistPattern(command: [], resolution: nil) == nil) } + @Test func validateAllowlistPatternReturnsReasons() { + #expect(ExecApprovalHelpers.isPathPattern("/usr/bin/rg")) + #expect(ExecApprovalHelpers.isPathPattern(" ~/bin/rg ")) + #expect(!ExecApprovalHelpers.isPathPattern("rg")) + + if case .invalid(let reason) = ExecApprovalHelpers.validateAllowlistPattern(" ") { + #expect(reason == .empty) + } else { + Issue.record("Expected empty pattern rejection") + } + + if case .invalid(let reason) = ExecApprovalHelpers.validateAllowlistPattern("echo") { + #expect(reason == .missingPathComponent) + } else { + Issue.record("Expected basename pattern rejection") + } + } + @Test func requiresAskMatchesPolicy() { let entry = ExecAllowlistEntry(pattern: "/bin/ls", lastUsedAt: nil, lastUsedCommand: nil, lastResolvedPath: nil) #expect(ExecApprovalHelpers.requiresAsk( diff --git a/apps/macos/Tests/OpenClawIPCTests/ExecApprovalsStoreRefactorTests.swift b/apps/macos/Tests/OpenClawIPCTests/ExecApprovalsStoreRefactorTests.swift new file mode 100644 index 0000000000000..fa9eef878813b --- /dev/null +++ b/apps/macos/Tests/OpenClawIPCTests/ExecApprovalsStoreRefactorTests.swift @@ -0,0 +1,75 @@ +import Foundation +import Testing +@testable import OpenClaw + +@Suite(.serialized) +struct ExecApprovalsStoreRefactorTests { + @Test + func ensureFileSkipsRewriteWhenUnchanged() async throws { + let stateDir = FileManager().temporaryDirectory + .appendingPathComponent("openclaw-state-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager().removeItem(at: stateDir) } + + try await TestIsolation.withEnvValues(["OPENCLAW_STATE_DIR": stateDir.path]) { + _ = ExecApprovalsStore.ensureFile() + let url = ExecApprovalsStore.fileURL() + let firstWriteDate = try Self.modificationDate(at: url) + + try await Task.sleep(nanoseconds: 1_100_000_000) + _ = ExecApprovalsStore.ensureFile() + let secondWriteDate = try Self.modificationDate(at: url) + + #expect(firstWriteDate == secondWriteDate) + } + } + + @Test + func updateAllowlistReportsRejectedBasenamePattern() async throws { + let stateDir = FileManager().temporaryDirectory + .appendingPathComponent("openclaw-state-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager().removeItem(at: stateDir) } + + await TestIsolation.withEnvValues(["OPENCLAW_STATE_DIR": stateDir.path]) { + let rejected = ExecApprovalsStore.updateAllowlist( + agentId: "main", + allowlist: [ + ExecAllowlistEntry(pattern: "echo"), + ExecAllowlistEntry(pattern: "/bin/echo"), + ]) + #expect(rejected.count == 1) + #expect(rejected.first?.reason == .missingPathComponent) + #expect(rejected.first?.pattern == "echo") + + let resolved = ExecApprovalsStore.resolve(agentId: "main") + #expect(resolved.allowlist.map(\.pattern) == ["/bin/echo"]) + } + } + + @Test + func updateAllowlistMigratesLegacyPatternFromResolvedPath() async throws { + let stateDir = FileManager().temporaryDirectory + .appendingPathComponent("openclaw-state-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager().removeItem(at: stateDir) } + + await TestIsolation.withEnvValues(["OPENCLAW_STATE_DIR": stateDir.path]) { + let rejected = ExecApprovalsStore.updateAllowlist( + agentId: "main", + allowlist: [ + ExecAllowlistEntry(pattern: "echo", lastUsedAt: nil, lastUsedCommand: nil, lastResolvedPath: " /usr/bin/echo "), + ]) + #expect(rejected.isEmpty) + + let resolved = ExecApprovalsStore.resolve(agentId: "main") + #expect(resolved.allowlist.map(\.pattern) == ["/usr/bin/echo"]) + } + } + + private static func modificationDate(at url: URL) throws -> Date { + let attributes = try FileManager().attributesOfItem(atPath: url.path) + guard let date = attributes[.modificationDate] as? Date else { + struct MissingDateError: Error {} + throw MissingDateError() + } + return date + } +} diff --git a/apps/macos/Tests/OpenClawIPCTests/GatewayChannelConfigureTests.swift b/apps/macos/Tests/OpenClawIPCTests/GatewayChannelConfigureTests.swift index 7200af03cddea..ec2caf6057cfc 100644 --- a/apps/macos/Tests/OpenClawIPCTests/GatewayChannelConfigureTests.swift +++ b/apps/macos/Tests/OpenClawIPCTests/GatewayChannelConfigureTests.swift @@ -45,12 +45,7 @@ import Testing // First send is the connect handshake request. Subsequent sends are request frames. if currentSendCount == 0 { - guard case let .data(data) = message else { return } - if let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any], - (obj["type"] as? String) == "req", - (obj["method"] as? String) == "connect", - let id = obj["id"] as? String - { + if let id = GatewayWebSocketTestSupport.connectRequestID(from: message) { self.connectRequestID.withLock { $0 = id } } return @@ -65,7 +60,7 @@ import Testing return } - let response = Self.responseData(id: id) + let response = GatewayWebSocketTestSupport.okResponseData(id: id) let handler = self.pendingReceiveHandler.withLock { $0 } handler?(Result.success(.data(response))) } @@ -75,7 +70,7 @@ import Testing try await Task.sleep(nanoseconds: UInt64(self.helloDelayMs) * 1_000_000) } let id = self.connectRequestID.withLock { $0 } ?? "connect" - return .data(Self.connectOkData(id: id)) + return .data(GatewayWebSocketTestSupport.connectOkData(id: id)) } func receive( @@ -89,41 +84,6 @@ import Testing handler?(Result.success(.data(data))) } - private static func connectOkData(id: String) -> Data { - let json = """ - { - "type": "res", - "id": "\(id)", - "ok": true, - "payload": { - "type": "hello-ok", - "protocol": 2, - "server": { "version": "test", "connId": "test" }, - "features": { "methods": [], "events": [] }, - "snapshot": { - "presence": [ { "ts": 1 } ], - "health": {}, - "stateVersion": { "presence": 0, "health": 0 }, - "uptimeMs": 0 - }, - "policy": { "maxPayload": 1, "maxBufferedBytes": 1, "tickIntervalMs": 30000 } - } - } - """ - return Data(json.utf8) - } - - private static func responseData(id: String) -> Data { - let json = """ - { - "type": "res", - "id": "\(id)", - "ok": true, - "payload": { "ok": true } - } - """ - return Data(json.utf8) - } } private final class FakeWebSocketSession: WebSocketSessioning, @unchecked Sendable { diff --git a/apps/macos/Tests/OpenClawIPCTests/GatewayChannelConnectTests.swift b/apps/macos/Tests/OpenClawIPCTests/GatewayChannelConnectTests.swift index bda06e9cf56d1..afe9dea9e2c74 100644 --- a/apps/macos/Tests/OpenClawIPCTests/GatewayChannelConnectTests.swift +++ b/apps/macos/Tests/OpenClawIPCTests/GatewayChannelConnectTests.swift @@ -38,17 +38,7 @@ import Testing } func send(_ message: URLSessionWebSocketTask.Message) async throws { - let data: Data? = switch message { - case let .data(d): d - case let .string(s): s.data(using: .utf8) - @unknown default: nil - } - guard let data else { return } - if let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any], - obj["type"] as? String == "req", - obj["method"] as? String == "connect", - let id = obj["id"] as? String - { + if let id = GatewayWebSocketTestSupport.connectRequestID(from: message) { self.connectRequestID.withLock { $0 = id } } } @@ -60,7 +50,7 @@ import Testing case let .helloOk(ms): delayMs = ms let id = self.connectRequestID.withLock { $0 } ?? "connect" - msg = .data(Self.connectOkData(id: id)) + msg = .data(GatewayWebSocketTestSupport.connectOkData(id: id)) case let .invalid(ms): delayMs = ms msg = .string("not json") @@ -77,29 +67,6 @@ import Testing self.pendingReceiveHandler.withLock { $0 = completionHandler } } - private static func connectOkData(id: String) -> Data { - let json = """ - { - "type": "res", - "id": "\(id)", - "ok": true, - "payload": { - "type": "hello-ok", - "protocol": 2, - "server": { "version": "test", "connId": "test" }, - "features": { "methods": [], "events": [] }, - "snapshot": { - "presence": [ { "ts": 1 } ], - "health": {}, - "stateVersion": { "presence": 0, "health": 0 }, - "uptimeMs": 0 - }, - "policy": { "maxPayload": 1, "maxBufferedBytes": 1, "tickIntervalMs": 30000 } - } - } - """ - return Data(json.utf8) - } } private final class FakeWebSocketSession: WebSocketSessioning, @unchecked Sendable { diff --git a/apps/macos/Tests/OpenClawIPCTests/GatewayChannelRequestTests.swift b/apps/macos/Tests/OpenClawIPCTests/GatewayChannelRequestTests.swift index 94edb6ebf77ff..4c788a959f57e 100644 --- a/apps/macos/Tests/OpenClawIPCTests/GatewayChannelRequestTests.swift +++ b/apps/macos/Tests/OpenClawIPCTests/GatewayChannelRequestTests.swift @@ -42,17 +42,7 @@ import Testing // First send is the connect handshake. Second send is the request frame. if currentSendCount == 0 { - let data: Data? = switch message { - case let .data(d): d - case let .string(s): s.data(using: .utf8) - @unknown default: nil - } - guard let data else { return } - if let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any], - obj["type"] as? String == "req", - obj["method"] as? String == "connect", - let id = obj["id"] as? String - { + if let id = GatewayWebSocketTestSupport.connectRequestID(from: message) { self.connectRequestID.withLock { $0 = id } } } @@ -64,7 +54,7 @@ import Testing func receive() async throws -> URLSessionWebSocketTask.Message { let id = self.connectRequestID.withLock { $0 } ?? "connect" - return .data(Self.connectOkData(id: id)) + return .data(GatewayWebSocketTestSupport.connectOkData(id: id)) } func receive( @@ -73,29 +63,6 @@ import Testing self.pendingReceiveHandler.withLock { $0 = completionHandler } } - private static func connectOkData(id: String) -> Data { - let json = """ - { - "type": "res", - "id": "\(id)", - "ok": true, - "payload": { - "type": "hello-ok", - "protocol": 2, - "server": { "version": "test", "connId": "test" }, - "features": { "methods": [], "events": [] }, - "snapshot": { - "presence": [ { "ts": 1 } ], - "health": {}, - "stateVersion": { "presence": 0, "health": 0 }, - "uptimeMs": 0 - }, - "policy": { "maxPayload": 1, "maxBufferedBytes": 1, "tickIntervalMs": 30000 } - } - } - """ - return Data(json.utf8) - } } private final class FakeWebSocketSession: WebSocketSessioning, @unchecked Sendable { diff --git a/apps/macos/Tests/OpenClawIPCTests/GatewayChannelShutdownTests.swift b/apps/macos/Tests/OpenClawIPCTests/GatewayChannelShutdownTests.swift index eea7774adf2e1..5f995cd394abd 100644 --- a/apps/macos/Tests/OpenClawIPCTests/GatewayChannelShutdownTests.swift +++ b/apps/macos/Tests/OpenClawIPCTests/GatewayChannelShutdownTests.swift @@ -32,24 +32,14 @@ import Testing } func send(_ message: URLSessionWebSocketTask.Message) async throws { - let data: Data? = switch message { - case let .data(d): d - case let .string(s): s.data(using: .utf8) - @unknown default: nil - } - guard let data else { return } - if let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any], - obj["type"] as? String == "req", - obj["method"] as? String == "connect", - let id = obj["id"] as? String - { + if let id = GatewayWebSocketTestSupport.connectRequestID(from: message) { self.connectRequestID.withLock { $0 = id } } } func receive() async throws -> URLSessionWebSocketTask.Message { let id = self.connectRequestID.withLock { $0 } ?? "connect" - return .data(Self.connectOkData(id: id)) + return .data(GatewayWebSocketTestSupport.connectOkData(id: id)) } func receive( @@ -63,29 +53,6 @@ import Testing handler?(Result.failure(URLError(.networkConnectionLost))) } - private static func connectOkData(id: String) -> Data { - let json = """ - { - "type": "res", - "id": "\(id)", - "ok": true, - "payload": { - "type": "hello-ok", - "protocol": 2, - "server": { "version": "test", "connId": "test" }, - "features": { "methods": [], "events": [] }, - "snapshot": { - "presence": [ { "ts": 1 } ], - "health": {}, - "stateVersion": { "presence": 0, "health": 0 }, - "uptimeMs": 0 - }, - "policy": { "maxPayload": 1, "maxBufferedBytes": 1, "tickIntervalMs": 30000 } - } - } - """ - return Data(json.utf8) - } } private final class FakeWebSocketSession: WebSocketSessioning, @unchecked Sendable { diff --git a/apps/macos/Tests/OpenClawIPCTests/GatewayDiscoveryHelpersTests.swift b/apps/macos/Tests/OpenClawIPCTests/GatewayDiscoveryHelpersTests.swift new file mode 100644 index 0000000000000..17ffec07d467b --- /dev/null +++ b/apps/macos/Tests/OpenClawIPCTests/GatewayDiscoveryHelpersTests.swift @@ -0,0 +1,98 @@ +import Foundation +import OpenClawDiscovery +import Testing +@testable import OpenClaw + +@Suite +struct GatewayDiscoveryHelpersTests { + private func makeGateway( + serviceHost: String?, + servicePort: Int?, + lanHost: String? = "txt-host.local", + tailnetDns: String? = "txt-host.ts.net", + sshPort: Int = 22, + gatewayPort: Int? = 18789) -> GatewayDiscoveryModel.DiscoveredGateway + { + GatewayDiscoveryModel.DiscoveredGateway( + displayName: "Gateway", + serviceHost: serviceHost, + servicePort: servicePort, + lanHost: lanHost, + tailnetDns: tailnetDns, + sshPort: sshPort, + gatewayPort: gatewayPort, + cliPath: "/tmp/openclaw", + stableID: UUID().uuidString, + debugID: UUID().uuidString, + isLocal: false) + } + + @Test func sshTargetUsesResolvedServiceHostOnly() { + let gateway = self.makeGateway( + serviceHost: "resolved.example.ts.net", + servicePort: 18789, + sshPort: 2201) + + guard let target = GatewayDiscoveryHelpers.sshTarget(for: gateway) else { + Issue.record("expected ssh target") + return + } + let parsed = CommandResolver.parseSSHTarget(target) + #expect(parsed?.host == "resolved.example.ts.net") + #expect(parsed?.port == 2201) + } + + @Test func sshTargetAllowsMissingResolvedServicePort() { + let gateway = self.makeGateway( + serviceHost: "resolved.example.ts.net", + servicePort: nil, + sshPort: 2201) + + guard let target = GatewayDiscoveryHelpers.sshTarget(for: gateway) else { + Issue.record("expected ssh target") + return + } + let parsed = CommandResolver.parseSSHTarget(target) + #expect(parsed?.host == "resolved.example.ts.net") + #expect(parsed?.port == 2201) + } + + @Test func sshTargetRejectsTxtOnlyGateways() { + let gateway = self.makeGateway( + serviceHost: nil, + servicePort: nil, + lanHost: "txt-only.local", + tailnetDns: "txt-only.ts.net", + sshPort: 2222) + + #expect(GatewayDiscoveryHelpers.sshTarget(for: gateway) == nil) + } + + @Test func directUrlUsesResolvedServiceEndpointOnly() { + let tlsGateway = self.makeGateway( + serviceHost: "resolved.example.ts.net", + servicePort: 443) + #expect(GatewayDiscoveryHelpers.directUrl(for: tlsGateway) == "wss://resolved.example.ts.net") + + let wsGateway = self.makeGateway( + serviceHost: "resolved.example.ts.net", + servicePort: 18789) + #expect(GatewayDiscoveryHelpers.directUrl(for: wsGateway) == "wss://resolved.example.ts.net:18789") + + let localGateway = self.makeGateway( + serviceHost: "127.0.0.1", + servicePort: 18789) + #expect(GatewayDiscoveryHelpers.directUrl(for: localGateway) == "ws://127.0.0.1:18789") + } + + @Test func directUrlRejectsTxtOnlyFallback() { + let gateway = self.makeGateway( + serviceHost: nil, + servicePort: nil, + lanHost: "txt-only.local", + tailnetDns: "txt-only.ts.net", + gatewayPort: 22222) + + #expect(GatewayDiscoveryHelpers.directUrl(for: gateway) == nil) + } +} diff --git a/apps/macos/Tests/OpenClawIPCTests/GatewayEndpointStoreTests.swift b/apps/macos/Tests/OpenClawIPCTests/GatewayEndpointStoreTests.swift index 44c464c449fc6..bb969aeaec90a 100644 --- a/apps/macos/Tests/OpenClawIPCTests/GatewayEndpointStoreTests.swift +++ b/apps/macos/Tests/OpenClawIPCTests/GatewayEndpointStoreTests.swift @@ -218,9 +218,19 @@ import Testing #expect(url.absoluteString == "https://gateway.example:443/remote-ui/") } - @Test func normalizeGatewayUrlAddsDefaultPortForWs() { - let url = GatewayRemoteConfig.normalizeGatewayUrl("ws://gateway") + @Test func normalizeGatewayUrlAddsDefaultPortForLoopbackWs() { + let url = GatewayRemoteConfig.normalizeGatewayUrl("ws://127.0.0.1") #expect(url?.port == 18789) - #expect(url?.absoluteString == "ws://gateway:18789") + #expect(url?.absoluteString == "ws://127.0.0.1:18789") + } + + @Test func normalizeGatewayUrlRejectsNonLoopbackWs() { + let url = GatewayRemoteConfig.normalizeGatewayUrl("ws://gateway.example:18789") + #expect(url == nil) + } + + @Test func normalizeGatewayUrlRejectsPrefixBypassLoopbackHost() { + let url = GatewayRemoteConfig.normalizeGatewayUrl("ws://127.attacker.example") + #expect(url == nil) } } diff --git a/apps/macos/Tests/OpenClawIPCTests/GatewayProcessManagerTests.swift b/apps/macos/Tests/OpenClawIPCTests/GatewayProcessManagerTests.swift index f8b226ab277fd..dabb15f8bf1d4 100644 --- a/apps/macos/Tests/OpenClawIPCTests/GatewayProcessManagerTests.swift +++ b/apps/macos/Tests/OpenClawIPCTests/GatewayProcessManagerTests.swift @@ -39,12 +39,7 @@ struct GatewayProcessManagerTests { } if currentSendCount == 0 { - guard case let .data(data) = message else { return } - if let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any], - (obj["type"] as? String) == "req", - (obj["method"] as? String) == "connect", - let id = obj["id"] as? String - { + if let id = GatewayWebSocketTestSupport.connectRequestID(from: message) { self.connectRequestID.withLock { $0 = id } } return @@ -59,14 +54,14 @@ struct GatewayProcessManagerTests { return } - let response = Self.responseData(id: id) + let response = GatewayWebSocketTestSupport.okResponseData(id: id) let handler = self.pendingReceiveHandler.withLock { $0 } handler?(Result.success(.data(response))) } func receive() async throws -> URLSessionWebSocketTask.Message { let id = self.connectRequestID.withLock { $0 } ?? "connect" - return .data(Self.connectOkData(id: id)) + return .data(GatewayWebSocketTestSupport.connectOkData(id: id)) } func receive( @@ -75,41 +70,6 @@ struct GatewayProcessManagerTests { self.pendingReceiveHandler.withLock { $0 = completionHandler } } - private static func connectOkData(id: String) -> Data { - let json = """ - { - "type": "res", - "id": "\(id)", - "ok": true, - "payload": { - "type": "hello-ok", - "protocol": 2, - "server": { "version": "test", "connId": "test" }, - "features": { "methods": [], "events": [] }, - "snapshot": { - "presence": [ { "ts": 1 } ], - "health": {}, - "stateVersion": { "presence": 0, "health": 0 }, - "uptimeMs": 0 - }, - "policy": { "maxPayload": 1, "maxBufferedBytes": 1, "tickIntervalMs": 30000 } - } - } - """ - return Data(json.utf8) - } - - private static func responseData(id: String) -> Data { - let json = """ - { - "type": "res", - "id": "\(id)", - "ok": true, - "payload": { "ok": true } - } - """ - return Data(json.utf8) - } } private final class FakeWebSocketSession: WebSocketSessioning, @unchecked Sendable { diff --git a/apps/macos/Tests/OpenClawIPCTests/GatewayWebSocketTestSupport.swift b/apps/macos/Tests/OpenClawIPCTests/GatewayWebSocketTestSupport.swift new file mode 100644 index 0000000000000..0ba41f2806bc4 --- /dev/null +++ b/apps/macos/Tests/OpenClawIPCTests/GatewayWebSocketTestSupport.swift @@ -0,0 +1,63 @@ +import OpenClawKit +import Foundation + +extension WebSocketTasking { + // Keep unit-test doubles resilient to protocol additions. + func sendPing(pongReceiveHandler: @escaping @Sendable (Error?) -> Void) { + pongReceiveHandler(nil) + } +} + +enum GatewayWebSocketTestSupport { + static func connectRequestID(from message: URLSessionWebSocketTask.Message) -> String? { + let data: Data? = switch message { + case let .data(d): d + case let .string(s): s.data(using: .utf8) + @unknown default: nil + } + guard let data else { return nil } + guard let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { + return nil + } + guard (obj["type"] as? String) == "req", (obj["method"] as? String) == "connect" else { + return nil + } + return obj["id"] as? String + } + + static func connectOkData(id: String) -> Data { + let json = """ + { + "type": "res", + "id": "\(id)", + "ok": true, + "payload": { + "type": "hello-ok", + "protocol": 2, + "server": { "version": "test", "connId": "test" }, + "features": { "methods": [], "events": [] }, + "snapshot": { + "presence": [ { "ts": 1 } ], + "health": {}, + "stateVersion": { "presence": 0, "health": 0 }, + "uptimeMs": 0 + }, + "policy": { "maxPayload": 1, "maxBufferedBytes": 1, "tickIntervalMs": 30000 } + } + } + """ + return Data(json.utf8) + } + + static func okResponseData(id: String) -> Data { + let json = """ + { + "type": "res", + "id": "\(id)", + "ok": true, + "payload": { "ok": true } + } + """ + return Data(json.utf8) + } +} diff --git a/apps/macos/Tests/OpenClawIPCTests/HostEnvSanitizerTests.swift b/apps/macos/Tests/OpenClawIPCTests/HostEnvSanitizerTests.swift new file mode 100644 index 0000000000000..7ee15107f40dc --- /dev/null +++ b/apps/macos/Tests/OpenClawIPCTests/HostEnvSanitizerTests.swift @@ -0,0 +1,36 @@ +import Testing +@testable import OpenClaw + +struct HostEnvSanitizerTests { + @Test func sanitizeBlocksShellTraceVariables() { + let env = HostEnvSanitizer.sanitize(overrides: [ + "SHELLOPTS": "xtrace", + "PS4": "$(touch /tmp/pwned)", + "OPENCLAW_TEST": "1", + ]) + #expect(env["SHELLOPTS"] == nil) + #expect(env["PS4"] == nil) + #expect(env["OPENCLAW_TEST"] == "1") + } + + @Test func sanitizeShellWrapperAllowsOnlyExplicitOverrideKeys() { + let env = HostEnvSanitizer.sanitize( + overrides: [ + "LANG": "C", + "LC_ALL": "C", + "OPENCLAW_TOKEN": "secret", + "PS4": "$(touch /tmp/pwned)", + ], + shellWrapper: true) + + #expect(env["LANG"] == "C") + #expect(env["LC_ALL"] == "C") + #expect(env["OPENCLAW_TOKEN"] == nil) + #expect(env["PS4"] == nil) + } + + @Test func sanitizeNonShellWrapperKeepsRegularOverrides() { + let env = HostEnvSanitizer.sanitize(overrides: ["OPENCLAW_TOKEN": "secret"]) + #expect(env["OPENCLAW_TOKEN"] == "secret") + } +} diff --git a/apps/macos/Tests/OpenClawIPCTests/MacGatewayChatTransportMappingTests.swift b/apps/macos/Tests/OpenClawIPCTests/MacGatewayChatTransportMappingTests.swift index 661382dda69c5..2d26b7c053828 100644 --- a/apps/macos/Tests/OpenClawIPCTests/MacGatewayChatTransportMappingTests.swift +++ b/apps/macos/Tests/OpenClawIPCTests/MacGatewayChatTransportMappingTests.swift @@ -13,7 +13,8 @@ import Testing configpath: nil, statedir: nil, sessiondefaults: nil, - authmode: nil) + authmode: nil, + updateavailable: nil) let hello = HelloOk( type: "hello", diff --git a/apps/macos/Tests/OpenClawIPCTests/OnboardingViewSmokeTests.swift b/apps/macos/Tests/OpenClawIPCTests/OnboardingViewSmokeTests.swift index 57912eb412d1e..b824b2b083593 100644 --- a/apps/macos/Tests/OpenClawIPCTests/OnboardingViewSmokeTests.swift +++ b/apps/macos/Tests/OpenClawIPCTests/OnboardingViewSmokeTests.swift @@ -1,3 +1,4 @@ +import Foundation import OpenClawDiscovery import SwiftUI import Testing @@ -25,4 +26,36 @@ struct OnboardingViewSmokeTests { let order = OnboardingView.pageOrder(for: .local, showOnboardingChat: false) #expect(!order.contains(8)) } + + @Test func selectRemoteGatewayClearsStaleSshTargetWhenEndpointUnresolved() async { + let override = FileManager().temporaryDirectory + .appendingPathComponent("openclaw-config-\(UUID().uuidString)") + .appendingPathComponent("openclaw.json") + .path + + await TestIsolation.withEnvValues(["OPENCLAW_CONFIG_PATH": override]) { + let state = AppState(preview: true) + state.remoteTransport = .ssh + state.remoteTarget = "user@old-host:2222" + let view = OnboardingView( + state: state, + permissionMonitor: PermissionMonitor.shared, + discoveryModel: GatewayDiscoveryModel(localDisplayName: InstanceIdentity.displayName)) + let gateway = GatewayDiscoveryModel.DiscoveredGateway( + displayName: "Unresolved", + serviceHost: nil, + servicePort: nil, + lanHost: "txt-host.local", + tailnetDns: "txt-host.ts.net", + sshPort: 22, + gatewayPort: 18789, + cliPath: "/tmp/openclaw", + stableID: UUID().uuidString, + debugID: UUID().uuidString, + isLocal: false) + + view.selectRemoteGateway(gateway) + #expect(state.remoteTarget.isEmpty) + } + } } diff --git a/apps/macos/Tests/OpenClawIPCTests/OpenClawConfigFileTests.swift b/apps/macos/Tests/OpenClawIPCTests/OpenClawConfigFileTests.swift index 98e4e8046d30b..2cd9d6432e21e 100644 --- a/apps/macos/Tests/OpenClawIPCTests/OpenClawConfigFileTests.swift +++ b/apps/macos/Tests/OpenClawIPCTests/OpenClawConfigFileTests.swift @@ -62,6 +62,31 @@ struct OpenClawConfigFileTests { } } + @MainActor + @Test + func clearRemoteGatewayUrlRemovesOnlyUrlField() async { + let override = FileManager().temporaryDirectory + .appendingPathComponent("openclaw-config-\(UUID().uuidString)") + .appendingPathComponent("openclaw.json") + .path + + await TestIsolation.withEnvValues(["OPENCLAW_CONFIG_PATH": override]) { + OpenClawConfigFile.saveDict([ + "gateway": [ + "remote": [ + "url": "wss://old-host:111", + "token": "tok", + ], + ], + ]) + OpenClawConfigFile.clearRemoteGatewayUrl() + let root = OpenClawConfigFile.loadDict() + let remote = ((root["gateway"] as? [String: Any])?["remote"] as? [String: Any]) ?? [:] + #expect((remote["url"] as? String) == nil) + #expect((remote["token"] as? String) == "tok") + } + } + @Test func stateDirOverrideSetsConfigPath() async { let dir = FileManager().temporaryDirectory diff --git a/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatComposer.swift b/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatComposer.swift index 95a5ac3e5842f..145e17f3b7b6f 100644 --- a/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatComposer.swift +++ b/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatComposer.swift @@ -180,10 +180,12 @@ struct OpenClawChatComposer: View { VStack(alignment: .leading, spacing: 8) { self.editorOverlay - Rectangle() - .fill(OpenClawChatTheme.divider) - .frame(height: 1) - .padding(.horizontal, 2) + if !self.isComposerCompacted { + Rectangle() + .fill(OpenClawChatTheme.divider) + .frame(height: 1) + .padding(.horizontal, 2) + } HStack(alignment: .center, spacing: 8) { if self.showsConnectionPill { @@ -308,7 +310,7 @@ struct OpenClawChatComposer: View { } private var showsToolbar: Bool { - self.style == .standard + self.style == .standard && !self.isComposerCompacted } private var showsAttachments: Bool { @@ -316,15 +318,15 @@ struct OpenClawChatComposer: View { } private var showsConnectionPill: Bool { - self.style == .standard + self.style == .standard && !self.isComposerCompacted } private var composerPadding: CGFloat { - self.style == .onboarding ? 5 : 6 + self.style == .onboarding ? 5 : (self.isComposerCompacted ? 4 : 6) } private var editorPadding: CGFloat { - self.style == .onboarding ? 5 : 6 + self.style == .onboarding ? 5 : (self.isComposerCompacted ? 4 : 6) } private var textMinHeight: CGFloat { @@ -335,6 +337,14 @@ struct OpenClawChatComposer: View { self.style == .onboarding ? 52 : 64 } + private var isComposerCompacted: Bool { + #if os(macOS) + false + #else + self.style == .standard && self.isFocused + #endif + } + #if os(macOS) private func pickFilesMac() { let panel = NSOpenPanel() diff --git a/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatMarkdownPreprocessor.swift b/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatMarkdownPreprocessor.swift index f435eab2dca66..a96e288d7f4fc 100644 --- a/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatMarkdownPreprocessor.swift +++ b/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatMarkdownPreprocessor.swift @@ -1,6 +1,18 @@ import Foundation enum ChatMarkdownPreprocessor { + // Keep in sync with `src/auto-reply/reply/strip-inbound-meta.ts` + // (`INBOUND_META_SENTINELS`), and extend parser expectations in + // `ChatMarkdownPreprocessorTests` when sentinels change. + private static let inboundContextHeaders = [ + "Conversation info (untrusted metadata):", + "Sender (untrusted metadata):", + "Thread starter (untrusted, for context):", + "Replied message (untrusted, for context):", + "Forwarded message context (untrusted metadata):", + "Chat history since last reply (untrusted, for context):", + ] + struct InlineImage: Identifiable { let id = UUID() let label: String @@ -13,17 +25,21 @@ enum ChatMarkdownPreprocessor { } static func preprocess(markdown raw: String) -> Result { + let withoutContextBlocks = self.stripInboundContextBlocks(raw) + let withoutTimestamps = self.stripPrefixedTimestamps(withoutContextBlocks) let pattern = #"!\[([^\]]*)\]\((data:image\/[^;]+;base64,[^)]+)\)"# guard let re = try? NSRegularExpression(pattern: pattern) else { - return Result(cleaned: raw, images: []) + return Result(cleaned: self.normalize(withoutTimestamps), images: []) } - let ns = raw as NSString - let matches = re.matches(in: raw, range: NSRange(location: 0, length: ns.length)) - if matches.isEmpty { return Result(cleaned: raw, images: []) } + let ns = withoutTimestamps as NSString + let matches = re.matches( + in: withoutTimestamps, + range: NSRange(location: 0, length: ns.length)) + if matches.isEmpty { return Result(cleaned: self.normalize(withoutTimestamps), images: []) } var images: [InlineImage] = [] - var cleaned = raw + var cleaned = withoutTimestamps for match in matches.reversed() { guard match.numberOfRanges >= 3 else { continue } @@ -43,9 +59,65 @@ enum ChatMarkdownPreprocessor { cleaned.replaceSubrange(start.. String { + guard self.inboundContextHeaders.contains(where: raw.contains) else { + return raw + } + + let normalized = raw.replacingOccurrences(of: "\r\n", with: "\n") + var outputLines: [String] = [] + var inMetaBlock = false + var inFencedJson = false + + for line in normalized.split(separator: "\n", omittingEmptySubsequences: false) { + let currentLine = String(line) + + if !inMetaBlock && self.inboundContextHeaders.contains(where: currentLine.hasPrefix) { + inMetaBlock = true + inFencedJson = false + continue + } + + if inMetaBlock { + if !inFencedJson && currentLine.trimmingCharacters(in: .whitespacesAndNewlines) == "```json" { + inFencedJson = true + continue + } + + if inFencedJson { + if currentLine.trimmingCharacters(in: .whitespacesAndNewlines) == "```" { + inMetaBlock = false + inFencedJson = false + } + continue + } + + if currentLine.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + continue + } + + inMetaBlock = false + } + + outputLines.append(currentLine) + } + + return outputLines.joined(separator: "\n").replacingOccurrences(of: #"^\n+"#, with: "", options: .regularExpression) + } + + private static func stripPrefixedTimestamps(_ raw: String) -> String { + let pattern = #"(?m)^\[[A-Za-z]{3}\s+\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}(?::\d{2})?\s+(?:GMT|UTC)[+-]?\d{0,2}\]\s*"# + return raw.replacingOccurrences(of: pattern, with: "", options: .regularExpression) + } + + private static func normalize(_ raw: String) -> String { + var output = raw + output = output.replacingOccurrences(of: "\r\n", with: "\n") + output = output.replacingOccurrences(of: "\n\n\n", with: "\n\n") + output = output.replacingOccurrences(of: "\n\n\n", with: "\n\n") + return output.trimmingCharacters(in: .whitespacesAndNewlines) } } diff --git a/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatMessageViews.swift b/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatMessageViews.swift index baa790dbf7470..22f28517d64a5 100644 --- a/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatMessageViews.swift +++ b/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatMessageViews.swift @@ -173,7 +173,8 @@ private struct ChatMessageBody: View { ToolResultCard( title: self.toolResultTitle, text: text, - isUser: self.isUser) + isUser: self.isUser, + toolName: self.message.toolName) } } else if self.isUser { ChatMarkdownRenderer( @@ -207,7 +208,8 @@ private struct ChatMessageBody: View { ToolResultCard( title: "\(display.emoji) \(display.title)", text: toolResult.text ?? "", - isUser: self.isUser) + isUser: self.isUser, + toolName: toolResult.name) } } } @@ -402,47 +404,54 @@ private struct ToolResultCard: View { let title: String let text: String let isUser: Bool + let toolName: String? @State private var expanded = false var body: some View { - VStack(alignment: .leading, spacing: 8) { - HStack(spacing: 6) { - Text(self.title) - .font(.footnote.weight(.semibold)) - Spacer(minLength: 0) - } + if !self.displayContent.isEmpty { + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 6) { + Text(self.title) + .font(.footnote.weight(.semibold)) + Spacer(minLength: 0) + } - Text(self.displayText) - .font(.footnote.monospaced()) - .foregroundStyle(self.isUser ? OpenClawChatTheme.userText : OpenClawChatTheme.assistantText) - .lineLimit(self.expanded ? nil : Self.previewLineLimit) + Text(self.displayText) + .font(.footnote.monospaced()) + .foregroundStyle(self.isUser ? OpenClawChatTheme.userText : OpenClawChatTheme.assistantText) + .lineLimit(self.expanded ? nil : Self.previewLineLimit) - if self.shouldShowToggle { - Button(self.expanded ? "Show less" : "Show full output") { - self.expanded.toggle() + if self.shouldShowToggle { + Button(self.expanded ? "Show less" : "Show full output") { + self.expanded.toggle() + } + .buttonStyle(.plain) + .font(.caption) + .foregroundStyle(.secondary) } - .buttonStyle(.plain) - .font(.caption) - .foregroundStyle(.secondary) } + .padding(10) + .background( + RoundedRectangle(cornerRadius: 12, style: .continuous) + .fill(OpenClawChatTheme.subtleCard) + .overlay( + RoundedRectangle(cornerRadius: 12, style: .continuous) + .strokeBorder(Color.white.opacity(0.08), lineWidth: 1))) } - .padding(10) - .background( - RoundedRectangle(cornerRadius: 12, style: .continuous) - .fill(OpenClawChatTheme.subtleCard) - .overlay( - RoundedRectangle(cornerRadius: 12, style: .continuous) - .strokeBorder(Color.white.opacity(0.08), lineWidth: 1))) } private static let previewLineLimit = 8 + private var displayContent: String { + ToolResultTextFormatter.format(text: self.text, toolName: self.toolName) + } + private var lines: [Substring] { - self.text.components(separatedBy: .newlines).map { Substring($0) } + self.displayContent.components(separatedBy: .newlines).map { Substring($0) } } private var displayText: String { - guard !self.expanded, self.lines.count > Self.previewLineLimit else { return self.text } + guard !self.expanded, self.lines.count > Self.previewLineLimit else { return self.displayContent } return self.lines.prefix(Self.previewLineLimit).joined(separator: "\n") + "\n…" } @@ -458,12 +467,7 @@ struct ChatTypingIndicatorBubble: View { var body: some View { HStack(spacing: 10) { TypingDots() - if self.style == .standard { - Text("OpenClaw is thinking…") - .font(.subheadline) - .foregroundStyle(.secondary) - Spacer() - } + Spacer(minLength: 0) } .padding(.vertical, self.style == .standard ? 12 : 10) .padding(.horizontal, self.style == .standard ? 12 : 14) diff --git a/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatView.swift b/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatView.swift index 68f9ae2f311e7..0675ffc2139b0 100644 --- a/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatView.swift +++ b/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatView.swift @@ -1,4 +1,7 @@ import SwiftUI +#if canImport(UIKit) +import UIKit +#endif @MainActor public struct OpenClawChatView: View { @@ -105,6 +108,9 @@ public struct OpenClawChatView: View { .padding(.top, Layout.messageListPaddingTop) .padding(.horizontal, Layout.messageListPaddingHorizontal) } + #if !os(macOS) + .scrollDismissesKeyboard(.interactively) + #endif // Keep the scroll pinned to the bottom for new messages. .scrollPosition(id: self.$scrollPosition, anchor: .bottom) .onChange(of: self.scrollPosition) { _, position in @@ -123,6 +129,10 @@ public struct OpenClawChatView: View { // Ensure the message list claims vertical space on the first layout pass. .frame(maxHeight: .infinity, alignment: .top) .layoutPriority(1) + .simultaneousGesture( + TapGesture().onEnded { + self.dismissKeyboardIfNeeded() + }) .onChange(of: self.viewModel.isLoading) { _, isLoading in guard !isLoading, !self.hasPerformedInitialScroll else { return } self.scrollPosition = self.scrollerBottomID @@ -406,6 +416,16 @@ public struct OpenClawChatView: View { } return parts.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines) } + + private func dismissKeyboardIfNeeded() { + #if canImport(UIKit) + UIApplication.shared.sendAction( + #selector(UIResponder.resignFirstResponder), + to: nil, + from: nil, + for: nil) + #endif + } } private struct ChatNoticeCard: View { diff --git a/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatViewModel.swift b/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatViewModel.swift index fc7b399353db2..62cb97a0e2fbc 100644 --- a/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatViewModel.swift +++ b/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatViewModel.swift @@ -189,10 +189,43 @@ public final class OpenClawChatViewModel { private static func decodeMessages(_ raw: [AnyCodable]) -> [OpenClawChatMessage] { let decoded = raw.compactMap { item in (try? ChatPayloadDecoding.decode(item, as: OpenClawChatMessage.self)) + .map { Self.stripInboundMetadata(from: $0) } } return Self.dedupeMessages(decoded) } + private static func stripInboundMetadata(from message: OpenClawChatMessage) -> OpenClawChatMessage { + guard message.role.lowercased() == "user" else { + return message + } + + let sanitizedContent = message.content.map { content -> OpenClawChatMessageContent in + guard let text = content.text else { return content } + let cleaned = ChatMarkdownPreprocessor.preprocess(markdown: text).cleaned + return OpenClawChatMessageContent( + type: content.type, + text: cleaned, + thinking: content.thinking, + thinkingSignature: content.thinkingSignature, + mimeType: content.mimeType, + fileName: content.fileName, + content: content.content, + id: content.id, + name: content.name, + arguments: content.arguments) + } + + return OpenClawChatMessage( + id: message.id, + role: message.role, + content: sanitizedContent, + timestamp: message.timestamp, + toolCallId: message.toolCallId, + toolName: message.toolName, + usage: message.usage, + stopReason: message.stopReason) + } + private static func messageIdentityKey(for message: OpenClawChatMessage) -> String? { let role = message.role.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() guard !role.isEmpty else { return nil } @@ -435,8 +468,12 @@ public final class OpenClawChatViewModel { case let .agent(agent): self.handleAgentEvent(agent) case .seqGap: - self.errorText = "Event stream interrupted; try refreshing." + self.errorText = nil self.clearPendingRuns(reason: nil) + Task { + await self.refreshHistoryAfterRun() + await self.pollHealthIfNeeded(force: true) + } } } diff --git a/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ToolResultTextFormatter.swift b/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ToolResultTextFormatter.swift new file mode 100644 index 0000000000000..719e82cdf15b0 --- /dev/null +++ b/apps/shared/OpenClawKit/Sources/OpenClawChatUI/ToolResultTextFormatter.swift @@ -0,0 +1,157 @@ +import Foundation + +enum ToolResultTextFormatter { + static func format(text: String, toolName: String?) -> String { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return "" } + + guard self.looksLikeJSON(trimmed), + let data = trimmed.data(using: .utf8), + let json = try? JSONSerialization.jsonObject(with: data) + else { + return trimmed + } + + let normalizedTool = toolName?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + return self.renderJSON(json, toolName: normalizedTool) + } + + private static func looksLikeJSON(_ value: String) -> Bool { + guard let first = value.first else { return false } + return first == "{" || first == "[" + } + + private static func renderJSON(_ json: Any, toolName: String?) -> String { + if let dict = json as? [String: Any] { + return self.renderDictionary(dict, toolName: toolName) + } + if let array = json as? [Any] { + if array.isEmpty { return "No items." } + return "\(array.count) item\(array.count == 1 ? "" : "s")." + } + return "" + } + + private static func renderDictionary(_ dict: [String: Any], toolName: String?) -> String { + let status = (dict["status"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) + let errorText = self.firstString(in: dict, keys: ["error", "reason"]) + let messageText = self.firstString(in: dict, keys: ["message", "result", "detail"]) + + if status?.lowercased() == "error" || errorText != nil { + if let errorText { + return "Error: \(self.sanitizeError(errorText))" + } + if let messageText { + return "Error: \(self.sanitizeError(messageText))" + } + return "Error" + } + + if toolName == "nodes", let summary = self.renderNodesSummary(dict) { + return summary + } + + if let message = messageText { + return message + } + + if let status, !status.isEmpty { + return "Status: \(status)" + } + + return "" + } + + private static func renderNodesSummary(_ dict: [String: Any]) -> String? { + if let nodes = dict["nodes"] as? [[String: Any]] { + if nodes.isEmpty { return "No nodes found." } + var lines: [String] = [] + lines.append("\(nodes.count) node\(nodes.count == 1 ? "" : "s") found.") + + for node in nodes.prefix(3) { + let label = self.firstString(in: node, keys: ["displayName", "name", "nodeId"]) ?? "Node" + var details: [String] = [] + + if let connected = node["connected"] as? Bool { + details.append(connected ? "connected" : "offline") + } + if let platform = self.firstString(in: node, keys: ["platform"]) { + details.append(platform) + } + if let version = self.firstString(in: node, keys: ["osVersion", "appVersion", "version"]) { + details.append(version) + } + if let pairing = self.pairingDetail(node) { + details.append(pairing) + } + + if details.isEmpty { + lines.append("• \(label)") + } else { + lines.append("• \(label) - \(details.joined(separator: ", "))") + } + } + + let extra = nodes.count - 3 + if extra > 0 { + lines.append("... +\(extra) more") + } + return lines.joined(separator: "\n") + } + + if let pending = dict["pending"] as? [Any], let paired = dict["paired"] as? [Any] { + return "Pairing requests: \(pending.count) pending, \(paired.count) paired." + } + + if let pending = dict["pending"] as? [Any] { + if pending.isEmpty { return "No pending pairing requests." } + return "\(pending.count) pending pairing request\(pending.count == 1 ? "" : "s")." + } + + return nil + } + + private static func pairingDetail(_ node: [String: Any]) -> String? { + if let paired = node["paired"] as? Bool, !paired { + return "pairing required" + } + + for key in ["status", "state", "deviceStatus"] { + if let raw = node[key] as? String, raw.lowercased().contains("pairing required") { + return "pairing required" + } + } + return nil + } + + private static func firstString(in dict: [String: Any], keys: [String]) -> String? { + for key in keys { + if let value = dict[key] as? String { + let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) + if !trimmed.isEmpty { + return trimmed + } + } + } + return nil + } + + private static func sanitizeError(_ raw: String) -> String { + var cleaned = raw.trimmingCharacters(in: .whitespacesAndNewlines) + if cleaned.contains("agent="), + cleaned.contains("action="), + let marker = cleaned.range(of: ": ") + { + cleaned = String(cleaned[marker.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines) + } + + if let firstLine = cleaned.split(separator: "\n").first { + cleaned = String(firstLine).trimmingCharacters(in: .whitespacesAndNewlines) + } + + if cleaned.count > 220 { + cleaned = String(cleaned.prefix(217)) + "..." + } + return cleaned + } +} diff --git a/apps/shared/OpenClawKit/Sources/OpenClawKit/DeepLinks.swift b/apps/shared/OpenClawKit/Sources/OpenClawKit/DeepLinks.swift index 30606ca26712c..5071488461997 100644 --- a/apps/shared/OpenClawKit/Sources/OpenClawKit/DeepLinks.swift +++ b/apps/shared/OpenClawKit/Sources/OpenClawKit/DeepLinks.swift @@ -1,4 +1,5 @@ import Foundation +import Network public enum DeepLinkRoute: Sendable, Equatable { case agent(AgentDeepLink) @@ -20,6 +21,40 @@ public struct GatewayConnectDeepLink: Codable, Sendable, Equatable { self.password = password } + fileprivate static func isLoopbackHost(_ raw: String) -> Bool { + var host = raw + .trimmingCharacters(in: .whitespacesAndNewlines) + .lowercased() + .trimmingCharacters(in: CharacterSet(charactersIn: "[]")) + if host.hasSuffix(".") { + host.removeLast() + } + if let zoneIndex = host.firstIndex(of: "%") { + host = String(host[.. Void) func receive() async throws -> URLSessionWebSocketTask.Message func receive(completionHandler: @escaping @Sendable (Result) -> Void) } @@ -40,6 +41,18 @@ public struct WebSocketTaskBox: @unchecked Sendable { { self.task.receive(completionHandler: completionHandler) } + + public func sendPing() async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + self.task.sendPing { error in + if let error { + continuation.resume(throwing: error) + } else { + continuation.resume(returning: ()) + } + } + } + } } public protocol WebSocketSessioning: AnyObject { @@ -72,9 +85,9 @@ public struct GatewayConnectOptions: Sendable { public var clientId: String public var clientMode: String public var clientDisplayName: String? - // When false, the connection omits the signed device identity payload. - // This is useful for secondary "operator" connections where the shared gateway token - // should authorize without triggering device pairing flows. + // When false, the connection omits the signed device identity payload and cannot use + // device-scoped auth (role/scope upgrades will require pairing). Keep this true for + // role/scoped sessions such as operator UI clients. public var includeDeviceIdentity: Bool public init( @@ -114,6 +127,14 @@ private enum ConnectChallengeError: Error { case timeout } +private let defaultOperatorConnectScopes: [String] = [ + "operator.admin", + "operator.read", + "operator.write", + "operator.approvals", + "operator.pairing", +] + public actor GatewayChannelActor { private let logger = Logger(subsystem: "ai.openclaw", category: "gateway") private var task: WebSocketTaskBox? @@ -133,8 +154,8 @@ public actor GatewayChannelActor { private var lastAuthSource: GatewayAuthSource = .none private let decoder = JSONDecoder() private let encoder = JSONEncoder() - // Remote gateways (tailscale/wan) can take a bit longer to deliver the connect.challenge event, - // and we must include the nonce once the gateway requires v2 signing. + // Remote gateways (tailscale/wan) can take longer to deliver connect.challenge. + // Connect now requires this nonce before we send device-auth. private let connectTimeoutSeconds: Double = 12 private let connectChallengeTimeoutSeconds: Double = 6.0 // Some networks will silently drop idle TCP/TLS flows around ~30s. The gateway tick is server->client, @@ -213,7 +234,7 @@ public actor GatewayChannelActor { private func watchdogLoop() async { // Keep nudging reconnect in case exponential backoff stalls. while self.shouldReconnect { - try? await Task.sleep(nanoseconds: 30 * 1_000_000_000) // 30s cadence + guard await self.sleepUnlessCancelled(nanoseconds: 30 * 1_000_000_000) else { return } // 30s cadence guard self.shouldReconnect else { return } if self.connected { continue } do { @@ -285,13 +306,15 @@ public actor GatewayChannelActor { private func keepaliveLoop() async { while self.shouldReconnect { - try? await Task.sleep(nanoseconds: UInt64(self.keepaliveIntervalSeconds * 1_000_000_000)) + guard await self.sleepUnlessCancelled( + nanoseconds: UInt64(self.keepaliveIntervalSeconds * 1_000_000_000)) + else { return } guard self.shouldReconnect else { return } guard self.connected else { continue } - // Best-effort outbound message to keep intermediate NAT/proxy state alive. - // We intentionally ignore the response. + guard let task = self.task else { continue } + // Best-effort ping keeps NAT/proxy state alive without generating RPC load. do { - try await self.send(method: "health", params: nil) + try await task.sendPing() } catch { // Avoid spamming logs; the reconnect paths will surface meaningful errors. } @@ -303,7 +326,7 @@ public actor GatewayChannelActor { let primaryLocale = Locale.preferredLanguages.first ?? Locale.current.identifier let options = self.connectOptions ?? GatewayConnectOptions( role: "operator", - scopes: ["operator.admin", "operator.approvals", "operator.pairing"], + scopes: defaultOperatorConnectScopes, caps: [], commands: [], permissions: [:], @@ -376,8 +399,8 @@ public actor GatewayChannelActor { let signedAtMs = Int(Date().timeIntervalSince1970 * 1000) let connectNonce = try await self.waitForConnectChallenge() let scopesValue = scopes.joined(separator: ",") - var payloadParts = [ - connectNonce == nil ? "v1" : "v2", + let payloadParts = [ + "v2", identity?.deviceId ?? "", clientId, clientMode, @@ -385,23 +408,19 @@ public actor GatewayChannelActor { scopesValue, String(signedAtMs), authToken ?? "", + connectNonce, ] - if let connectNonce { - payloadParts.append(connectNonce) - } let payload = payloadParts.joined(separator: "|") if includeDeviceIdentity, let identity { if let signature = DeviceIdentityStore.signPayload(payload, identity: identity), let publicKey = DeviceIdentityStore.publicKeyBase64Url(identity) { - var device: [String: ProtoAnyCodable] = [ + let device: [String: ProtoAnyCodable] = [ "id": ProtoAnyCodable(identity.deviceId), "publicKey": ProtoAnyCodable(publicKey), "signature": ProtoAnyCodable(signature), "signedAt": ProtoAnyCodable(signedAtMs), + "nonce": ProtoAnyCodable(connectNonce), ] - if let connectNonce { - device["nonce"] = ProtoAnyCodable(connectNonce) - } params["device"] = ProtoAnyCodable(device) } } @@ -530,33 +549,26 @@ public actor GatewayChannelActor { } } - private func waitForConnectChallenge() async throws -> String? { - guard let task = self.task else { return nil } - do { - return try await AsyncTimeout.withTimeout( - seconds: self.connectChallengeTimeoutSeconds, - onTimeout: { ConnectChallengeError.timeout }, - operation: { [weak self] in - guard let self else { return nil } - while true { - let msg = try await task.receive() - guard let data = self.decodeMessageData(msg) else { continue } - guard let frame = try? self.decoder.decode(GatewayFrame.self, from: data) else { continue } - if case let .event(evt) = frame, evt.event == "connect.challenge" { - if let payload = evt.payload?.value as? [String: ProtoAnyCodable], - let nonce = payload["nonce"]?.value as? String { - return nonce - } - } + private func waitForConnectChallenge() async throws -> String { + guard let task = self.task else { throw ConnectChallengeError.timeout } + return try await AsyncTimeout.withTimeout( + seconds: self.connectChallengeTimeoutSeconds, + onTimeout: { ConnectChallengeError.timeout }, + operation: { [weak self] in + guard let self else { throw ConnectChallengeError.timeout } + while true { + let msg = try await task.receive() + guard let data = self.decodeMessageData(msg) else { continue } + guard let frame = try? self.decoder.decode(GatewayFrame.self, from: data) else { continue } + if case let .event(evt) = frame, evt.event == "connect.challenge", + let payload = evt.payload?.value as? [String: ProtoAnyCodable], + let nonce = payload["nonce"]?.value as? String, + nonce.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false + { + return nonce } - }) - } catch { - if error is ConnectChallengeError { - self.logger.warning("gateway connect challenge timed out") - return nil - } - throw error - } + } + }) } private func waitForConnectResponse(reqId: String) async throws -> ResponseFrame { @@ -593,7 +605,7 @@ public actor GatewayChannelActor { private func watchTicks() async { let tolerance = self.tickIntervalMs * 2 while self.connected { - try? await Task.sleep(nanoseconds: UInt64(tolerance * 1_000_000)) + guard await self.sleepUnlessCancelled(nanoseconds: UInt64(tolerance * 1_000_000)) else { return } guard self.connected else { return } if let last = self.lastTick { let delta = Date().timeIntervalSince(last) * 1000 @@ -616,7 +628,7 @@ public actor GatewayChannelActor { guard self.shouldReconnect else { return } let delay = self.backoffMs / 1000 self.backoffMs = min(self.backoffMs * 2, 30000) - try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000)) + guard await self.sleepUnlessCancelled(nanoseconds: UInt64(delay * 1_000_000_000)) else { return } guard self.shouldReconnect else { return } do { try await self.connect() @@ -627,6 +639,15 @@ public actor GatewayChannelActor { } } + private nonisolated func sleepUnlessCancelled(nanoseconds: UInt64) async -> Bool { + do { + try await Task.sleep(nanoseconds: nanoseconds) + } catch { + return false + } + return !Task.isCancelled + } + public func request( method: String, params: [String: AnyCodable]?, diff --git a/apps/shared/OpenClawKit/Sources/OpenClawKit/GatewayNodeSession.swift b/apps/shared/OpenClawKit/Sources/OpenClawKit/GatewayNodeSession.swift index d0303f7e9977b..7dd2fe1eee1bb 100644 --- a/apps/shared/OpenClawKit/Sources/OpenClawKit/GatewayNodeSession.swift +++ b/apps/shared/OpenClawKit/Sources/OpenClawKit/GatewayNodeSession.swift @@ -26,6 +26,7 @@ public actor GatewayNodeSession { private var onConnected: (@Sendable () async -> Void)? private var onDisconnected: (@Sendable (String) async -> Void)? private var onInvoke: (@Sendable (BridgeInvokeRequest) async -> BridgeInvokeResponse)? + private var hasEverConnected = false private var hasNotifiedConnected = false private var snapshotReceived = false private var snapshotWaiters: [CheckedContinuation] = [] @@ -214,6 +215,7 @@ public actor GatewayNodeSession { self.activeToken = nil self.activePassword = nil self.activeConnectOptionsKey = nil + self.hasEverConnected = false self.resetConnectionState() } @@ -274,6 +276,11 @@ public actor GatewayNodeSession { case let .snapshot(ok): let raw = ok.canvashosturl?.trimmingCharacters(in: .whitespacesAndNewlines) self.canvasHostUrl = (raw?.isEmpty == false) ? raw : nil + if self.hasEverConnected { + self.broadcastServerEvent( + EventFrame(type: "event", event: "seqGap", payload: nil, seq: nil, stateversion: nil)) + } + self.hasEverConnected = true self.markSnapshotReceived() await self.notifyConnectedIfNeeded() case let .event(evt): diff --git a/apps/shared/OpenClawKit/Sources/OpenClawKit/WatchCommands.swift b/apps/shared/OpenClawKit/Sources/OpenClawKit/WatchCommands.swift index 814efe68a886a..0bd6990710c2d 100644 --- a/apps/shared/OpenClawKit/Sources/OpenClawKit/WatchCommands.swift +++ b/apps/shared/OpenClawKit/Sources/OpenClawKit/WatchCommands.swift @@ -5,6 +5,24 @@ public enum OpenClawWatchCommand: String, Codable, Sendable { case notify = "watch.notify" } +public enum OpenClawWatchRisk: String, Codable, Sendable, Equatable { + case low + case medium + case high +} + +public struct OpenClawWatchAction: Codable, Sendable, Equatable { + public var id: String + public var label: String + public var style: String? + + public init(id: String, label: String, style: String? = nil) { + self.id = id + self.label = label + self.style = style + } +} + public struct OpenClawWatchStatusPayload: Codable, Sendable, Equatable { public var supported: Bool public var paired: Bool @@ -31,11 +49,36 @@ public struct OpenClawWatchNotifyParams: Codable, Sendable, Equatable { public var title: String public var body: String public var priority: OpenClawNotificationPriority? + public var promptId: String? + public var sessionKey: String? + public var kind: String? + public var details: String? + public var expiresAtMs: Int? + public var risk: OpenClawWatchRisk? + public var actions: [OpenClawWatchAction]? - public init(title: String, body: String, priority: OpenClawNotificationPriority? = nil) { + public init( + title: String, + body: String, + priority: OpenClawNotificationPriority? = nil, + promptId: String? = nil, + sessionKey: String? = nil, + kind: String? = nil, + details: String? = nil, + expiresAtMs: Int? = nil, + risk: OpenClawWatchRisk? = nil, + actions: [OpenClawWatchAction]? = nil) + { self.title = title self.body = body self.priority = priority + self.promptId = promptId + self.sessionKey = sessionKey + self.kind = kind + self.details = details + self.expiresAtMs = expiresAtMs + self.risk = risk + self.actions = actions } } diff --git a/apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift b/apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift index 661d5dc11fd0c..2f2dd7f6090f1 100644 --- a/apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift +++ b/apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift @@ -40,8 +40,8 @@ public struct ConnectParams: Codable, Sendable { device: [String: AnyCodable]?, auth: [String: AnyCodable]?, locale: String?, - useragent: String? - ) { + useragent: String?) + { self.minprotocol = minprotocol self.maxprotocol = maxprotocol self.client = client @@ -56,6 +56,7 @@ public struct ConnectParams: Codable, Sendable { self.locale = locale self.useragent = useragent } + private enum CodingKeys: String, CodingKey { case minprotocol = "minProtocol" case maxprotocol = "maxProtocol" @@ -91,8 +92,8 @@ public struct HelloOk: Codable, Sendable { snapshot: Snapshot, canvashosturl: String?, auth: [String: AnyCodable]?, - policy: [String: AnyCodable] - ) { + policy: [String: AnyCodable]) + { self.type = type self._protocol = _protocol self.server = server @@ -102,6 +103,7 @@ public struct HelloOk: Codable, Sendable { self.auth = auth self.policy = policy } + private enum CodingKeys: String, CodingKey { case type case _protocol = "protocol" @@ -124,13 +126,14 @@ public struct RequestFrame: Codable, Sendable { type: String, id: String, method: String, - params: AnyCodable? - ) { + params: AnyCodable?) + { self.type = type self.id = id self.method = method self.params = params } + private enum CodingKeys: String, CodingKey { case type case id @@ -151,14 +154,15 @@ public struct ResponseFrame: Codable, Sendable { id: String, ok: Bool, payload: AnyCodable?, - error: [String: AnyCodable]? - ) { + error: [String: AnyCodable]?) + { self.type = type self.id = id self.ok = ok self.payload = payload self.error = error } + private enum CodingKeys: String, CodingKey { case type case id @@ -180,14 +184,15 @@ public struct EventFrame: Codable, Sendable { event: String, payload: AnyCodable?, seq: Int?, - stateversion: [String: AnyCodable]? - ) { + stateversion: [String: AnyCodable]?) + { self.type = type self.event = event self.payload = payload self.seq = seq self.stateversion = stateversion } + private enum CodingKeys: String, CodingKey { case type case event @@ -231,8 +236,8 @@ public struct PresenceEntry: Codable, Sendable { deviceid: String?, roles: [String]?, scopes: [String]?, - instanceid: String? - ) { + instanceid: String?) + { self.host = host self.ip = ip self.version = version @@ -250,6 +255,7 @@ public struct PresenceEntry: Codable, Sendable { self.scopes = scopes self.instanceid = instanceid } + private enum CodingKeys: String, CodingKey { case host case ip @@ -276,11 +282,12 @@ public struct StateVersion: Codable, Sendable { public init( presence: Int, - health: Int - ) { + health: Int) + { self.presence = presence self.health = health } + private enum CodingKeys: String, CodingKey { case presence case health @@ -307,8 +314,8 @@ public struct Snapshot: Codable, Sendable { statedir: String?, sessiondefaults: [String: AnyCodable]?, authmode: AnyCodable?, - updateavailable: [String: AnyCodable]? - ) { + updateavailable: [String: AnyCodable]?) + { self.presence = presence self.health = health self.stateversion = stateversion @@ -319,6 +326,7 @@ public struct Snapshot: Codable, Sendable { self.authmode = authmode self.updateavailable = updateavailable } + private enum CodingKeys: String, CodingKey { case presence case health @@ -344,14 +352,15 @@ public struct ErrorShape: Codable, Sendable { message: String, details: AnyCodable?, retryable: Bool?, - retryafterms: Int? - ) { + retryafterms: Int?) + { self.code = code self.message = message self.details = details self.retryable = retryable self.retryafterms = retryafterms } + private enum CodingKeys: String, CodingKey { case code case message @@ -373,14 +382,15 @@ public struct AgentEvent: Codable, Sendable { seq: Int, stream: String, ts: Int, - data: [String: AnyCodable] - ) { + data: [String: AnyCodable]) + { self.runid = runid self.seq = seq self.stream = stream self.ts = ts self.data = data } + private enum CodingKeys: String, CodingKey { case runid = "runId" case seq @@ -412,8 +422,8 @@ public struct SendParams: Codable, Sendable { accountid: String?, threadid: String?, sessionkey: String?, - idempotencykey: String - ) { + idempotencykey: String) + { self.to = to self.message = message self.mediaurl = mediaurl @@ -425,6 +435,7 @@ public struct SendParams: Codable, Sendable { self.sessionkey = sessionkey self.idempotencykey = idempotencykey } + private enum CodingKeys: String, CodingKey { case to case message @@ -465,8 +476,8 @@ public struct PollParams: Codable, Sendable { threadid: String?, channel: String?, accountid: String?, - idempotencykey: String - ) { + idempotencykey: String) + { self.to = to self.question = question self.options = options @@ -480,6 +491,7 @@ public struct PollParams: Codable, Sendable { self.accountid = accountid self.idempotencykey = idempotencykey } + private enum CodingKeys: String, CodingKey { case to case question @@ -546,8 +558,8 @@ public struct AgentParams: Codable, Sendable { inputprovenance: [String: AnyCodable]?, idempotencykey: String, label: String?, - spawnedby: String? - ) { + spawnedby: String?) + { self.message = message self.agentid = agentid self.to = to @@ -573,6 +585,7 @@ public struct AgentParams: Codable, Sendable { self.label = label self.spawnedby = spawnedby } + private enum CodingKeys: String, CodingKey { case message case agentid = "agentId" @@ -607,11 +620,12 @@ public struct AgentIdentityParams: Codable, Sendable { public init( agentid: String?, - sessionkey: String? - ) { + sessionkey: String?) + { self.agentid = agentid self.sessionkey = sessionkey } + private enum CodingKeys: String, CodingKey { case agentid = "agentId" case sessionkey = "sessionKey" @@ -628,13 +642,14 @@ public struct AgentIdentityResult: Codable, Sendable { agentid: String, name: String?, avatar: String?, - emoji: String? - ) { + emoji: String?) + { self.agentid = agentid self.name = name self.avatar = avatar self.emoji = emoji } + private enum CodingKeys: String, CodingKey { case agentid = "agentId" case name @@ -649,11 +664,12 @@ public struct AgentWaitParams: Codable, Sendable { public init( runid: String, - timeoutms: Int? - ) { + timeoutms: Int?) + { self.runid = runid self.timeoutms = timeoutms } + private enum CodingKeys: String, CodingKey { case runid = "runId" case timeoutms = "timeoutMs" @@ -666,11 +682,12 @@ public struct WakeParams: Codable, Sendable { public init( mode: AnyCodable, - text: String - ) { + text: String) + { self.mode = mode self.text = text } + private enum CodingKeys: String, CodingKey { case mode case text @@ -703,8 +720,8 @@ public struct NodePairRequestParams: Codable, Sendable { caps: [String]?, commands: [String]?, remoteip: String?, - silent: Bool? - ) { + silent: Bool?) + { self.nodeid = nodeid self.displayname = displayname self.platform = platform @@ -718,6 +735,7 @@ public struct NodePairRequestParams: Codable, Sendable { self.remoteip = remoteip self.silent = silent } + private enum CodingKeys: String, CodingKey { case nodeid = "nodeId" case displayname = "displayName" @@ -734,17 +752,17 @@ public struct NodePairRequestParams: Codable, Sendable { } } -public struct NodePairListParams: Codable, Sendable { -} +public struct NodePairListParams: Codable, Sendable {} public struct NodePairApproveParams: Codable, Sendable { public let requestid: String public init( - requestid: String - ) { + requestid: String) + { self.requestid = requestid } + private enum CodingKeys: String, CodingKey { case requestid = "requestId" } @@ -754,10 +772,11 @@ public struct NodePairRejectParams: Codable, Sendable { public let requestid: String public init( - requestid: String - ) { + requestid: String) + { self.requestid = requestid } + private enum CodingKeys: String, CodingKey { case requestid = "requestId" } @@ -769,11 +788,12 @@ public struct NodePairVerifyParams: Codable, Sendable { public init( nodeid: String, - token: String - ) { + token: String) + { self.nodeid = nodeid self.token = token } + private enum CodingKeys: String, CodingKey { case nodeid = "nodeId" case token @@ -786,28 +806,29 @@ public struct NodeRenameParams: Codable, Sendable { public init( nodeid: String, - displayname: String - ) { + displayname: String) + { self.nodeid = nodeid self.displayname = displayname } + private enum CodingKeys: String, CodingKey { case nodeid = "nodeId" case displayname = "displayName" } } -public struct NodeListParams: Codable, Sendable { -} +public struct NodeListParams: Codable, Sendable {} public struct NodeDescribeParams: Codable, Sendable { public let nodeid: String public init( - nodeid: String - ) { + nodeid: String) + { self.nodeid = nodeid } + private enum CodingKeys: String, CodingKey { case nodeid = "nodeId" } @@ -825,14 +846,15 @@ public struct NodeInvokeParams: Codable, Sendable { command: String, params: AnyCodable?, timeoutms: Int?, - idempotencykey: String - ) { + idempotencykey: String) + { self.nodeid = nodeid self.command = command self.params = params self.timeoutms = timeoutms self.idempotencykey = idempotencykey } + private enum CodingKeys: String, CodingKey { case nodeid = "nodeId" case command @@ -856,8 +878,8 @@ public struct NodeInvokeResultParams: Codable, Sendable { ok: Bool, payload: AnyCodable?, payloadjson: String?, - error: [String: AnyCodable]? - ) { + error: [String: AnyCodable]?) + { self.id = id self.nodeid = nodeid self.ok = ok @@ -865,6 +887,7 @@ public struct NodeInvokeResultParams: Codable, Sendable { self.payloadjson = payloadjson self.error = error } + private enum CodingKeys: String, CodingKey { case id case nodeid = "nodeId" @@ -883,12 +906,13 @@ public struct NodeEventParams: Codable, Sendable { public init( event: String, payload: AnyCodable?, - payloadjson: String? - ) { + payloadjson: String?) + { self.event = event self.payload = payload self.payloadjson = payloadjson } + private enum CodingKeys: String, CodingKey { case event case payload @@ -910,8 +934,8 @@ public struct NodeInvokeRequestEvent: Codable, Sendable { command: String, paramsjson: String?, timeoutms: Int?, - idempotencykey: String? - ) { + idempotencykey: String?) + { self.id = id self.nodeid = nodeid self.command = command @@ -919,6 +943,7 @@ public struct NodeInvokeRequestEvent: Codable, Sendable { self.timeoutms = timeoutms self.idempotencykey = idempotencykey } + private enum CodingKeys: String, CodingKey { case id case nodeid = "nodeId" @@ -939,13 +964,14 @@ public struct PushTestParams: Codable, Sendable { nodeid: String, title: String?, body: String?, - environment: String? - ) { + environment: String?) + { self.nodeid = nodeid self.title = title self.body = body self.environment = environment } + private enum CodingKeys: String, CodingKey { case nodeid = "nodeId" case title @@ -970,8 +996,8 @@ public struct PushTestResult: Codable, Sendable { reason: String?, tokensuffix: String, topic: String, - environment: String - ) { + environment: String) + { self.ok = ok self.status = status self.apnsid = apnsid @@ -980,6 +1006,7 @@ public struct PushTestResult: Codable, Sendable { self.topic = topic self.environment = environment } + private enum CodingKeys: String, CodingKey { case ok case status @@ -1013,8 +1040,8 @@ public struct SessionsListParams: Codable, Sendable { label: String?, spawnedby: String?, agentid: String?, - search: String? - ) { + search: String?) + { self.limit = limit self.activeminutes = activeminutes self.includeglobal = includeglobal @@ -1026,6 +1053,7 @@ public struct SessionsListParams: Codable, Sendable { self.agentid = agentid self.search = search } + private enum CodingKeys: String, CodingKey { case limit case activeminutes = "activeMinutes" @@ -1048,12 +1076,13 @@ public struct SessionsPreviewParams: Codable, Sendable { public init( keys: [String], limit: Int?, - maxchars: Int? - ) { + maxchars: Int?) + { self.keys = keys self.limit = limit self.maxchars = maxchars } + private enum CodingKeys: String, CodingKey { case keys case limit @@ -1077,8 +1106,8 @@ public struct SessionsResolveParams: Codable, Sendable { agentid: String?, spawnedby: String?, includeglobal: Bool?, - includeunknown: Bool? - ) { + includeunknown: Bool?) + { self.key = key self.sessionid = sessionid self.label = label @@ -1087,6 +1116,7 @@ public struct SessionsResolveParams: Codable, Sendable { self.includeglobal = includeglobal self.includeunknown = includeunknown } + private enum CodingKeys: String, CodingKey { case key case sessionid = "sessionId" @@ -1132,8 +1162,8 @@ public struct SessionsPatchParams: Codable, Sendable { spawnedby: AnyCodable?, spawndepth: AnyCodable?, sendpolicy: AnyCodable?, - groupactivation: AnyCodable? - ) { + groupactivation: AnyCodable?) + { self.key = key self.label = label self.thinkinglevel = thinkinglevel @@ -1151,6 +1181,7 @@ public struct SessionsPatchParams: Codable, Sendable { self.sendpolicy = sendpolicy self.groupactivation = groupactivation } + private enum CodingKeys: String, CodingKey { case key case label @@ -1177,11 +1208,12 @@ public struct SessionsResetParams: Codable, Sendable { public init( key: String, - reason: AnyCodable? - ) { + reason: AnyCodable?) + { self.key = key self.reason = reason } + private enum CodingKeys: String, CodingKey { case key case reason @@ -1191,17 +1223,22 @@ public struct SessionsResetParams: Codable, Sendable { public struct SessionsDeleteParams: Codable, Sendable { public let key: String public let deletetranscript: Bool? + public let emitlifecyclehooks: Bool? public init( key: String, - deletetranscript: Bool? - ) { + deletetranscript: Bool?, + emitlifecyclehooks: Bool?) + { self.key = key self.deletetranscript = deletetranscript + self.emitlifecyclehooks = emitlifecyclehooks } + private enum CodingKeys: String, CodingKey { case key case deletetranscript = "deleteTranscript" + case emitlifecyclehooks = "emitLifecycleHooks" } } @@ -1211,11 +1248,12 @@ public struct SessionsCompactParams: Codable, Sendable { public init( key: String, - maxlines: Int? - ) { + maxlines: Int?) + { self.key = key self.maxlines = maxlines } + private enum CodingKeys: String, CodingKey { case key case maxlines = "maxLines" @@ -1226,6 +1264,8 @@ public struct SessionsUsageParams: Codable, Sendable { public let key: String? public let startdate: String? public let enddate: String? + public let mode: AnyCodable? + public let utcoffset: String? public let limit: Int? public let includecontextweight: Bool? @@ -1233,26 +1273,32 @@ public struct SessionsUsageParams: Codable, Sendable { key: String?, startdate: String?, enddate: String?, + mode: AnyCodable?, + utcoffset: String?, limit: Int?, - includecontextweight: Bool? - ) { + includecontextweight: Bool?) + { self.key = key self.startdate = startdate self.enddate = enddate + self.mode = mode + self.utcoffset = utcoffset self.limit = limit self.includecontextweight = includecontextweight } + private enum CodingKeys: String, CodingKey { case key case startdate = "startDate" case enddate = "endDate" + case mode + case utcoffset = "utcOffset" case limit case includecontextweight = "includeContextWeight" } } -public struct ConfigGetParams: Codable, Sendable { -} +public struct ConfigGetParams: Codable, Sendable {} public struct ConfigSetParams: Codable, Sendable { public let raw: String @@ -1260,11 +1306,12 @@ public struct ConfigSetParams: Codable, Sendable { public init( raw: String, - basehash: String? - ) { + basehash: String?) + { self.raw = raw self.basehash = basehash } + private enum CodingKeys: String, CodingKey { case raw case basehash = "baseHash" @@ -1283,14 +1330,15 @@ public struct ConfigApplyParams: Codable, Sendable { basehash: String?, sessionkey: String?, note: String?, - restartdelayms: Int? - ) { + restartdelayms: Int?) + { self.raw = raw self.basehash = basehash self.sessionkey = sessionkey self.note = note self.restartdelayms = restartdelayms } + private enum CodingKeys: String, CodingKey { case raw case basehash = "baseHash" @@ -1312,14 +1360,15 @@ public struct ConfigPatchParams: Codable, Sendable { basehash: String?, sessionkey: String?, note: String?, - restartdelayms: Int? - ) { + restartdelayms: Int?) + { self.raw = raw self.basehash = basehash self.sessionkey = sessionkey self.note = note self.restartdelayms = restartdelayms } + private enum CodingKeys: String, CodingKey { case raw case basehash = "baseHash" @@ -1329,8 +1378,7 @@ public struct ConfigPatchParams: Codable, Sendable { } } -public struct ConfigSchemaParams: Codable, Sendable { -} +public struct ConfigSchemaParams: Codable, Sendable {} public struct ConfigSchemaResponse: Codable, Sendable { public let schema: AnyCodable @@ -1342,13 +1390,14 @@ public struct ConfigSchemaResponse: Codable, Sendable { schema: AnyCodable, uihints: [String: AnyCodable], version: String, - generatedat: 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" @@ -1363,11 +1412,12 @@ public struct WizardStartParams: Codable, Sendable { public init( mode: AnyCodable?, - workspace: String? - ) { + workspace: String?) + { self.mode = mode self.workspace = workspace } + private enum CodingKeys: String, CodingKey { case mode case workspace @@ -1380,11 +1430,12 @@ public struct WizardNextParams: Codable, Sendable { public init( sessionid: String, - answer: [String: AnyCodable]? - ) { + answer: [String: AnyCodable]?) + { self.sessionid = sessionid self.answer = answer } + private enum CodingKeys: String, CodingKey { case sessionid = "sessionId" case answer @@ -1395,10 +1446,11 @@ public struct WizardCancelParams: Codable, Sendable { public let sessionid: String public init( - sessionid: String - ) { + sessionid: String) + { self.sessionid = sessionid } + private enum CodingKeys: String, CodingKey { case sessionid = "sessionId" } @@ -1408,10 +1460,11 @@ public struct WizardStatusParams: Codable, Sendable { public let sessionid: String public init( - sessionid: String - ) { + sessionid: String) + { self.sessionid = sessionid } + private enum CodingKeys: String, CodingKey { case sessionid = "sessionId" } @@ -1437,8 +1490,8 @@ public struct WizardStep: Codable, Sendable { initialvalue: AnyCodable?, placeholder: String?, sensitive: Bool?, - executor: AnyCodable? - ) { + executor: AnyCodable?) + { self.id = id self.type = type self.title = title @@ -1449,6 +1502,7 @@ public struct WizardStep: Codable, Sendable { self.sensitive = sensitive self.executor = executor } + private enum CodingKeys: String, CodingKey { case id case type @@ -1472,13 +1526,14 @@ public struct WizardNextResult: Codable, Sendable { done: Bool, step: [String: AnyCodable]?, status: AnyCodable?, - error: String? - ) { + error: String?) + { self.done = done self.step = step self.status = status self.error = error } + private enum CodingKeys: String, CodingKey { case done case step @@ -1499,14 +1554,15 @@ public struct WizardStartResult: Codable, Sendable { done: Bool, step: [String: AnyCodable]?, status: AnyCodable?, - error: String? - ) { + 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 @@ -1522,11 +1578,12 @@ public struct WizardStatusResult: Codable, Sendable { public init( status: AnyCodable, - error: String? - ) { + error: String?) + { self.status = status self.error = error } + private enum CodingKeys: String, CodingKey { case status case error @@ -1539,11 +1596,12 @@ public struct TalkModeParams: Codable, Sendable { public init( enabled: Bool, - phase: String? - ) { + phase: String?) + { self.enabled = enabled self.phase = phase } + private enum CodingKeys: String, CodingKey { case enabled case phase @@ -1554,10 +1612,11 @@ public struct TalkConfigParams: Codable, Sendable { public let includesecrets: Bool? public init( - includesecrets: Bool? - ) { + includesecrets: Bool?) + { self.includesecrets = includesecrets } + private enum CodingKeys: String, CodingKey { case includesecrets = "includeSecrets" } @@ -1567,10 +1626,11 @@ public struct TalkConfigResult: Codable, Sendable { public let config: [String: AnyCodable] public init( - config: [String: AnyCodable] - ) { + config: [String: AnyCodable]) + { self.config = config } + private enum CodingKeys: String, CodingKey { case config } @@ -1582,11 +1642,12 @@ public struct ChannelsStatusParams: Codable, Sendable { public init( probe: Bool?, - timeoutms: Int? - ) { + timeoutms: Int?) + { self.probe = probe self.timeoutms = timeoutms } + private enum CodingKeys: String, CodingKey { case probe case timeoutms = "timeoutMs" @@ -1613,8 +1674,8 @@ public struct ChannelsStatusResult: Codable, Sendable { channelmeta: [[String: AnyCodable]]?, channels: [String: AnyCodable], channelaccounts: [String: AnyCodable], - channeldefaultaccountid: [String: AnyCodable] - ) { + channeldefaultaccountid: [String: AnyCodable]) + { self.ts = ts self.channelorder = channelorder self.channellabels = channellabels @@ -1625,6 +1686,7 @@ public struct ChannelsStatusResult: Codable, Sendable { self.channelaccounts = channelaccounts self.channeldefaultaccountid = channeldefaultaccountid } + private enum CodingKeys: String, CodingKey { case ts case channelorder = "channelOrder" @@ -1644,11 +1706,12 @@ public struct ChannelsLogoutParams: Codable, Sendable { public init( channel: String, - accountid: String? - ) { + accountid: String?) + { self.channel = channel self.accountid = accountid } + private enum CodingKeys: String, CodingKey { case channel case accountid = "accountId" @@ -1665,13 +1728,14 @@ public struct WebLoginStartParams: Codable, Sendable { force: Bool?, timeoutms: Int?, verbose: Bool?, - accountid: String? - ) { + accountid: String?) + { self.force = force self.timeoutms = timeoutms self.verbose = verbose self.accountid = accountid } + private enum CodingKeys: String, CodingKey { case force case timeoutms = "timeoutMs" @@ -1686,11 +1750,12 @@ public struct WebLoginWaitParams: Codable, Sendable { public init( timeoutms: Int?, - accountid: String? - ) { + accountid: String?) + { self.timeoutms = timeoutms self.accountid = accountid } + private enum CodingKeys: String, CodingKey { case timeoutms = "timeoutMs" case accountid = "accountId" @@ -1705,12 +1770,13 @@ public struct AgentSummary: Codable, Sendable { public init( id: String, name: String?, - identity: [String: AnyCodable]? - ) { + identity: [String: AnyCodable]?) + { self.id = id self.name = name self.identity = identity } + private enum CodingKeys: String, CodingKey { case id case name @@ -1728,13 +1794,14 @@ public struct AgentsCreateParams: Codable, Sendable { name: String, workspace: String, emoji: String?, - avatar: String? - ) { + avatar: String?) + { self.name = name self.workspace = workspace self.emoji = emoji self.avatar = avatar } + private enum CodingKeys: String, CodingKey { case name case workspace @@ -1753,13 +1820,14 @@ public struct AgentsCreateResult: Codable, Sendable { ok: Bool, agentid: String, name: String, - workspace: String - ) { + workspace: String) + { self.ok = ok self.agentid = agentid self.name = name self.workspace = workspace } + private enum CodingKeys: String, CodingKey { case ok case agentid = "agentId" @@ -1780,14 +1848,15 @@ public struct AgentsUpdateParams: Codable, Sendable { name: String?, workspace: String?, model: String?, - avatar: String? - ) { + avatar: String?) + { self.agentid = agentid self.name = name self.workspace = workspace self.model = model self.avatar = avatar } + private enum CodingKeys: String, CodingKey { case agentid = "agentId" case name @@ -1803,11 +1872,12 @@ public struct AgentsUpdateResult: Codable, Sendable { public init( ok: Bool, - agentid: String - ) { + agentid: String) + { self.ok = ok self.agentid = agentid } + private enum CodingKeys: String, CodingKey { case ok case agentid = "agentId" @@ -1820,11 +1890,12 @@ public struct AgentsDeleteParams: Codable, Sendable { public init( agentid: String, - deletefiles: Bool? - ) { + deletefiles: Bool?) + { self.agentid = agentid self.deletefiles = deletefiles } + private enum CodingKeys: String, CodingKey { case agentid = "agentId" case deletefiles = "deleteFiles" @@ -1839,12 +1910,13 @@ public struct AgentsDeleteResult: Codable, Sendable { public init( ok: Bool, agentid: String, - removedbindings: Int - ) { + removedbindings: Int) + { self.ok = ok self.agentid = agentid self.removedbindings = removedbindings } + private enum CodingKeys: String, CodingKey { case ok case agentid = "agentId" @@ -1866,8 +1938,8 @@ public struct AgentsFileEntry: Codable, Sendable { missing: Bool, size: Int?, updatedatms: Int?, - content: String? - ) { + content: String?) + { self.name = name self.path = path self.missing = missing @@ -1875,6 +1947,7 @@ public struct AgentsFileEntry: Codable, Sendable { self.updatedatms = updatedatms self.content = content } + private enum CodingKeys: String, CodingKey { case name case path @@ -1889,10 +1962,11 @@ public struct AgentsFilesListParams: Codable, Sendable { public let agentid: String public init( - agentid: String - ) { + agentid: String) + { self.agentid = agentid } + private enum CodingKeys: String, CodingKey { case agentid = "agentId" } @@ -1906,12 +1980,13 @@ public struct AgentsFilesListResult: Codable, Sendable { public init( agentid: String, workspace: String, - files: [AgentsFileEntry] - ) { + files: [AgentsFileEntry]) + { self.agentid = agentid self.workspace = workspace self.files = files } + private enum CodingKeys: String, CodingKey { case agentid = "agentId" case workspace @@ -1925,11 +2000,12 @@ public struct AgentsFilesGetParams: Codable, Sendable { public init( agentid: String, - name: String - ) { + name: String) + { self.agentid = agentid self.name = name } + private enum CodingKeys: String, CodingKey { case agentid = "agentId" case name @@ -1944,12 +2020,13 @@ public struct AgentsFilesGetResult: Codable, Sendable { public init( agentid: String, workspace: String, - file: AgentsFileEntry - ) { + file: AgentsFileEntry) + { self.agentid = agentid self.workspace = workspace self.file = file } + private enum CodingKeys: String, CodingKey { case agentid = "agentId" case workspace @@ -1965,12 +2042,13 @@ public struct AgentsFilesSetParams: Codable, Sendable { public init( agentid: String, name: String, - content: String - ) { + content: String) + { self.agentid = agentid self.name = name self.content = content } + private enum CodingKeys: String, CodingKey { case agentid = "agentId" case name @@ -1988,13 +2066,14 @@ public struct AgentsFilesSetResult: Codable, Sendable { ok: Bool, agentid: String, workspace: String, - file: AgentsFileEntry - ) { + file: AgentsFileEntry) + { self.ok = ok self.agentid = agentid self.workspace = workspace self.file = file } + private enum CodingKeys: String, CodingKey { case ok case agentid = "agentId" @@ -2003,8 +2082,7 @@ public struct AgentsFilesSetResult: Codable, Sendable { } } -public struct AgentsListParams: Codable, Sendable { -} +public struct AgentsListParams: Codable, Sendable {} public struct AgentsListResult: Codable, Sendable { public let defaultid: String @@ -2016,13 +2094,14 @@ public struct AgentsListResult: Codable, Sendable { defaultid: String, mainkey: String, scope: AnyCodable, - agents: [AgentSummary] - ) { + agents: [AgentSummary]) + { self.defaultid = defaultid self.mainkey = mainkey self.scope = scope self.agents = agents } + private enum CodingKeys: String, CodingKey { case defaultid = "defaultId" case mainkey = "mainKey" @@ -2043,14 +2122,15 @@ public struct ModelChoice: Codable, Sendable { name: String, provider: String, contextwindow: Int?, - reasoning: Bool? - ) { + reasoning: Bool?) + { self.id = id self.name = name self.provider = provider self.contextwindow = contextwindow self.reasoning = reasoning } + private enum CodingKeys: String, CodingKey { case id case name @@ -2060,17 +2140,17 @@ public struct ModelChoice: Codable, Sendable { } } -public struct ModelsListParams: Codable, Sendable { -} +public struct ModelsListParams: Codable, Sendable {} public struct ModelsListResult: Codable, Sendable { public let models: [ModelChoice] public init( - models: [ModelChoice] - ) { + models: [ModelChoice]) + { self.models = models } + private enum CodingKeys: String, CodingKey { case models } @@ -2080,26 +2160,27 @@ public struct SkillsStatusParams: Codable, Sendable { public let agentid: String? public init( - agentid: String? - ) { + agentid: String?) + { self.agentid = agentid } + private enum CodingKeys: String, CodingKey { case agentid = "agentId" } } -public struct SkillsBinsParams: Codable, Sendable { -} +public struct SkillsBinsParams: Codable, Sendable {} public struct SkillsBinsResult: Codable, Sendable { public let bins: [String] public init( - bins: [String] - ) { + bins: [String]) + { self.bins = bins } + private enum CodingKeys: String, CodingKey { case bins } @@ -2113,12 +2194,13 @@ public struct SkillsInstallParams: Codable, Sendable { public init( name: String, installid: String, - timeoutms: Int? - ) { + timeoutms: Int?) + { self.name = name self.installid = installid self.timeoutms = timeoutms } + private enum CodingKeys: String, CodingKey { case name case installid = "installId" @@ -2136,13 +2218,14 @@ public struct SkillsUpdateParams: Codable, Sendable { skillkey: String, enabled: Bool?, apikey: String?, - env: [String: AnyCodable]? - ) { + env: [String: AnyCodable]?) + { self.skillkey = skillkey self.enabled = enabled self.apikey = apikey self.env = env } + private enum CodingKeys: String, CodingKey { case skillkey = "skillKey" case enabled @@ -2183,8 +2266,8 @@ public struct CronJob: Codable, Sendable { wakemode: AnyCodable, payload: AnyCodable, delivery: AnyCodable?, - state: [String: AnyCodable] - ) { + state: [String: AnyCodable]) + { self.id = id self.agentid = agentid self.sessionkey = sessionkey @@ -2201,6 +2284,7 @@ public struct CronJob: Codable, Sendable { self.delivery = delivery self.state = state } + private enum CodingKeys: String, CodingKey { case id case agentid = "agentId" @@ -2224,17 +2308,17 @@ public struct CronListParams: Codable, Sendable { public let includedisabled: Bool? public init( - includedisabled: Bool? - ) { + includedisabled: Bool?) + { self.includedisabled = includedisabled } + private enum CodingKeys: String, CodingKey { case includedisabled = "includeDisabled" } } -public struct CronStatusParams: Codable, Sendable { -} +public struct CronStatusParams: Codable, Sendable {} public struct CronAddParams: Codable, Sendable { public let name: String @@ -2260,8 +2344,8 @@ public struct CronAddParams: Codable, Sendable { sessiontarget: AnyCodable, wakemode: AnyCodable, payload: AnyCodable, - delivery: AnyCodable? - ) { + delivery: AnyCodable?) + { self.name = name self.agentid = agentid self.sessionkey = sessionkey @@ -2274,6 +2358,7 @@ public struct CronAddParams: Codable, Sendable { self.payload = payload self.delivery = delivery } + private enum CodingKeys: String, CodingKey { case name case agentid = "agentId" @@ -2313,8 +2398,8 @@ public struct CronRunLogEntry: Codable, Sendable { sessionkey: String?, runatms: Int?, durationms: Int?, - nextrunatms: Int? - ) { + nextrunatms: Int?) + { self.ts = ts self.jobid = jobid self.action = action @@ -2327,6 +2412,7 @@ public struct CronRunLogEntry: Codable, Sendable { self.durationms = durationms self.nextrunatms = nextrunatms } + private enum CodingKeys: String, CodingKey { case ts case jobid = "jobId" @@ -2350,12 +2436,13 @@ public struct LogsTailParams: Codable, Sendable { public init( cursor: Int?, limit: Int?, - maxbytes: Int? - ) { + maxbytes: Int?) + { self.cursor = cursor self.limit = limit self.maxbytes = maxbytes } + private enum CodingKeys: String, CodingKey { case cursor case limit @@ -2377,8 +2464,8 @@ public struct LogsTailResult: Codable, Sendable { size: Int, lines: [String], truncated: Bool?, - reset: Bool? - ) { + reset: Bool?) + { self.file = file self.cursor = cursor self.size = size @@ -2386,6 +2473,7 @@ public struct LogsTailResult: Codable, Sendable { self.truncated = truncated self.reset = reset } + private enum CodingKeys: String, CodingKey { case file case cursor @@ -2396,8 +2484,7 @@ public struct LogsTailResult: Codable, Sendable { } } -public struct ExecApprovalsGetParams: Codable, Sendable { -} +public struct ExecApprovalsGetParams: Codable, Sendable {} public struct ExecApprovalsSetParams: Codable, Sendable { public let file: [String: AnyCodable] @@ -2405,11 +2492,12 @@ public struct ExecApprovalsSetParams: Codable, Sendable { public init( file: [String: AnyCodable], - basehash: String? - ) { + basehash: String?) + { self.file = file self.basehash = basehash } + private enum CodingKeys: String, CodingKey { case file case basehash = "baseHash" @@ -2420,10 +2508,11 @@ public struct ExecApprovalsNodeGetParams: Codable, Sendable { public let nodeid: String public init( - nodeid: String - ) { + nodeid: String) + { self.nodeid = nodeid } + private enum CodingKeys: String, CodingKey { case nodeid = "nodeId" } @@ -2437,12 +2526,13 @@ public struct ExecApprovalsNodeSetParams: Codable, Sendable { public init( nodeid: String, file: [String: AnyCodable], - basehash: String? - ) { + basehash: String?) + { self.nodeid = nodeid self.file = file self.basehash = basehash } + private enum CodingKeys: String, CodingKey { case nodeid = "nodeId" case file @@ -2460,13 +2550,14 @@ public struct ExecApprovalsSnapshot: Codable, Sendable { path: String, exists: Bool, hash: String, - file: [String: AnyCodable] - ) { + file: [String: AnyCodable]) + { self.path = path self.exists = exists self.hash = hash self.file = file } + private enum CodingKeys: String, CodingKey { case path case exists @@ -2499,8 +2590,8 @@ public struct ExecApprovalRequestParams: Codable, Sendable { resolvedpath: AnyCodable?, sessionkey: AnyCodable?, timeoutms: Int?, - twophase: Bool? - ) { + twophase: Bool?) + { self.id = id self.command = command self.cwd = cwd @@ -2513,6 +2604,7 @@ public struct ExecApprovalRequestParams: Codable, Sendable { self.timeoutms = timeoutms self.twophase = twophase } + private enum CodingKeys: String, CodingKey { case id case command @@ -2534,28 +2626,29 @@ public struct ExecApprovalResolveParams: Codable, Sendable { public init( id: String, - decision: String - ) { + decision: String) + { self.id = id self.decision = decision } + private enum CodingKeys: String, CodingKey { case id case decision } } -public struct DevicePairListParams: Codable, Sendable { -} +public struct DevicePairListParams: Codable, Sendable {} public struct DevicePairApproveParams: Codable, Sendable { public let requestid: String public init( - requestid: String - ) { + requestid: String) + { self.requestid = requestid } + private enum CodingKeys: String, CodingKey { case requestid = "requestId" } @@ -2565,10 +2658,11 @@ public struct DevicePairRejectParams: Codable, Sendable { public let requestid: String public init( - requestid: String - ) { + requestid: String) + { self.requestid = requestid } + private enum CodingKeys: String, CodingKey { case requestid = "requestId" } @@ -2578,10 +2672,11 @@ public struct DevicePairRemoveParams: Codable, Sendable { public let deviceid: String public init( - deviceid: String - ) { + deviceid: String) + { self.deviceid = deviceid } + private enum CodingKeys: String, CodingKey { case deviceid = "deviceId" } @@ -2595,12 +2690,13 @@ public struct DeviceTokenRotateParams: Codable, Sendable { public init( deviceid: String, role: String, - scopes: [String]? - ) { + scopes: [String]?) + { self.deviceid = deviceid self.role = role self.scopes = scopes } + private enum CodingKeys: String, CodingKey { case deviceid = "deviceId" case role @@ -2614,11 +2710,12 @@ public struct DeviceTokenRevokeParams: Codable, Sendable { public init( deviceid: String, - role: String - ) { + role: String) + { self.deviceid = deviceid self.role = role } + private enum CodingKeys: String, CodingKey { case deviceid = "deviceId" case role @@ -2655,8 +2752,8 @@ public struct DevicePairRequestedEvent: Codable, Sendable { remoteip: String?, silent: Bool?, isrepair: Bool?, - ts: Int - ) { + ts: Int) + { self.requestid = requestid self.deviceid = deviceid self.publickey = publickey @@ -2672,6 +2769,7 @@ public struct DevicePairRequestedEvent: Codable, Sendable { self.isrepair = isrepair self.ts = ts } + private enum CodingKeys: String, CodingKey { case requestid = "requestId" case deviceid = "deviceId" @@ -2700,13 +2798,14 @@ public struct DevicePairResolvedEvent: Codable, Sendable { requestid: String, deviceid: String, decision: String, - ts: Int - ) { + ts: Int) + { self.requestid = requestid self.deviceid = deviceid self.decision = decision self.ts = ts } + private enum CodingKeys: String, CodingKey { case requestid = "requestId" case deviceid = "deviceId" @@ -2721,11 +2820,12 @@ public struct ChatHistoryParams: Codable, Sendable { public init( sessionkey: String, - limit: Int? - ) { + limit: Int?) + { self.sessionkey = sessionkey self.limit = limit } + private enum CodingKeys: String, CodingKey { case sessionkey = "sessionKey" case limit @@ -2748,8 +2848,8 @@ public struct ChatSendParams: Codable, Sendable { deliver: Bool?, attachments: [AnyCodable]?, timeoutms: Int?, - idempotencykey: String - ) { + idempotencykey: String) + { self.sessionkey = sessionkey self.message = message self.thinking = thinking @@ -2758,6 +2858,7 @@ public struct ChatSendParams: Codable, Sendable { self.timeoutms = timeoutms self.idempotencykey = idempotencykey } + private enum CodingKeys: String, CodingKey { case sessionkey = "sessionKey" case message @@ -2775,11 +2876,12 @@ public struct ChatAbortParams: Codable, Sendable { public init( sessionkey: String, - runid: String? - ) { + runid: String?) + { self.sessionkey = sessionkey self.runid = runid } + private enum CodingKeys: String, CodingKey { case sessionkey = "sessionKey" case runid = "runId" @@ -2794,12 +2896,13 @@ public struct ChatInjectParams: Codable, Sendable { public init( sessionkey: String, message: String, - label: String? - ) { + label: String?) + { self.sessionkey = sessionkey self.message = message self.label = label } + private enum CodingKeys: String, CodingKey { case sessionkey = "sessionKey" case message @@ -2825,8 +2928,8 @@ public struct ChatEvent: Codable, Sendable { message: AnyCodable?, errormessage: String?, usage: AnyCodable?, - stopreason: String? - ) { + stopreason: String?) + { self.runid = runid self.sessionkey = sessionkey self.seq = seq @@ -2836,6 +2939,7 @@ public struct ChatEvent: Codable, Sendable { self.usage = usage self.stopreason = stopreason } + private enum CodingKeys: String, CodingKey { case runid = "runId" case sessionkey = "sessionKey" @@ -2858,13 +2962,14 @@ public struct UpdateRunParams: Codable, Sendable { sessionkey: String?, note: String?, restartdelayms: Int?, - timeoutms: Int? - ) { + timeoutms: Int?) + { self.sessionkey = sessionkey self.note = note self.restartdelayms = restartdelayms self.timeoutms = timeoutms } + private enum CodingKeys: String, CodingKey { case sessionkey = "sessionKey" case note @@ -2877,10 +2982,11 @@ public struct TickEvent: Codable, Sendable { public let ts: Int public init( - ts: Int - ) { + ts: Int) + { self.ts = ts } + private enum CodingKeys: String, CodingKey { case ts } @@ -2892,11 +2998,12 @@ public struct ShutdownEvent: Codable, Sendable { public init( reason: String, - restartexpectedms: Int? - ) { + restartexpectedms: Int?) + { self.reason = reason self.restartexpectedms = restartexpectedms } + private enum CodingKeys: String, CodingKey { case reason case restartexpectedms = "restartExpectedMs" @@ -2918,11 +3025,11 @@ public enum GatewayFrame: Codable, Sendable { let type = try typeContainer.decode(String.self, forKey: .type) switch type { case "req": - self = .req(try RequestFrame(from: decoder)) + self = try .req(RequestFrame(from: decoder)) case "res": - self = .res(try ResponseFrame(from: decoder)) + self = try .res(ResponseFrame(from: decoder)) case "event": - self = .event(try EventFrame(from: decoder)) + self = try .event(EventFrame(from: decoder)) default: let container = try decoder.singleValueContainer() let raw = try container.decode([String: AnyCodable].self) @@ -2932,13 +3039,15 @@ public enum GatewayFrame: Codable, Sendable { public func encode(to encoder: Encoder) throws { switch self { - case .req(let v): try v.encode(to: encoder) - case .res(let v): try v.encode(to: encoder) - case .event(let v): try v.encode(to: encoder) - case .unknown(_, let raw): + case let .req(v): + try v.encode(to: encoder) + case let .res(v): + try v.encode(to: encoder) + case let .event(v): + try v.encode(to: encoder) + case let .unknown(_, raw): var container = encoder.singleValueContainer() try container.encode(raw) } } - } diff --git a/apps/shared/OpenClawKit/Tests/OpenClawKitTests/ChatMarkdownPreprocessorTests.swift b/apps/shared/OpenClawKit/Tests/OpenClawKitTests/ChatMarkdownPreprocessorTests.swift index 808f74af64fa5..781a325f3cf92 100644 --- a/apps/shared/OpenClawKit/Tests/OpenClawKitTests/ChatMarkdownPreprocessorTests.swift +++ b/apps/shared/OpenClawKit/Tests/OpenClawKitTests/ChatMarkdownPreprocessorTests.swift @@ -17,4 +17,91 @@ struct ChatMarkdownPreprocessorTests { #expect(result.images.count == 1) #expect(result.images.first?.image != nil) } + + @Test func stripsInboundUntrustedContextBlocks() { + let markdown = """ + Conversation info (untrusted metadata): + ```json + { + "message_id": "123", + "sender": "openclaw-ios" + } + ``` + + Sender (untrusted metadata): + ```json + { + "label": "Razor" + } + ``` + + Razor? + """ + + let result = ChatMarkdownPreprocessor.preprocess(markdown: markdown) + + #expect(result.cleaned == "Razor?") + } + + @Test func stripsSingleConversationInfoBlock() { + let text = """ + Conversation info (untrusted metadata): + ```json + {"x": 1} + ``` + + User message + """ + + let result = ChatMarkdownPreprocessor.preprocess(markdown: text) + + #expect(result.cleaned == "User message") + } + + @Test func stripsAllKnownInboundMetadataSentinels() { + let sentinels = [ + "Conversation info (untrusted metadata):", + "Sender (untrusted metadata):", + "Thread starter (untrusted, for context):", + "Replied message (untrusted, for context):", + "Forwarded message context (untrusted metadata):", + "Chat history since last reply (untrusted, for context):", + ] + + for sentinel in sentinels { + let markdown = """ + \(sentinel) + ```json + {"x": 1} + ``` + + User content + """ + let result = ChatMarkdownPreprocessor.preprocess(markdown: markdown) + #expect(result.cleaned == "User content") + } + } + + @Test func preservesNonMetadataJsonFence() { + let markdown = """ + Here is some json: + ```json + {"x": 1} + ``` + """ + + let result = ChatMarkdownPreprocessor.preprocess(markdown: markdown) + + #expect(result.cleaned == markdown.trimmingCharacters(in: .whitespacesAndNewlines)) + } + + @Test func stripsLeadingTimestampPrefix() { + let markdown = """ + [Fri 2026-02-20 18:45 GMT+1] How's it going? + """ + + let result = ChatMarkdownPreprocessor.preprocess(markdown: markdown) + + #expect(result.cleaned == "How's it going?") + } } diff --git a/apps/shared/OpenClawKit/Tests/OpenClawKitTests/ChatViewModelTests.swift b/apps/shared/OpenClawKit/Tests/OpenClawKitTests/ChatViewModelTests.swift index ff7caabf381c0..147b80e5be14e 100644 --- a/apps/shared/OpenClawKit/Tests/OpenClawKitTests/ChatViewModelTests.swift +++ b/apps/shared/OpenClawKit/Tests/OpenClawKitTests/ChatViewModelTests.swift @@ -416,6 +416,48 @@ extension TestChatTransportState { #expect(await MainActor.run { vm.pendingToolCalls.isEmpty }) } + @Test func seqGapClearsPendingRunsAndAutoRefreshesHistory() async throws { + let now = Date().timeIntervalSince1970 * 1000 + let history1 = OpenClawChatHistoryPayload( + sessionKey: "main", + sessionId: "sess-main", + messages: [], + thinkingLevel: "off") + let history2 = OpenClawChatHistoryPayload( + sessionKey: "main", + sessionId: "sess-main", + messages: [ + AnyCodable([ + "role": "assistant", + "content": [["type": "text", "text": "resynced after gap"]], + "timestamp": now, + ]), + ], + thinkingLevel: "off") + + let transport = TestChatTransport(historyResponses: [history1, history2]) + let vm = await MainActor.run { OpenClawChatViewModel(sessionKey: "main", transport: transport) } + + await MainActor.run { vm.load() } + try await waitUntil("bootstrap") { await MainActor.run { vm.healthOK } } + + await MainActor.run { + vm.input = "hello" + vm.send() + } + try await waitUntil("pending run starts") { await MainActor.run { vm.pendingRunCount == 1 } } + + transport.emit(.seqGap) + + try await waitUntil("pending run clears on seqGap") { + await MainActor.run { vm.pendingRunCount == 0 } + } + try await waitUntil("history refreshes on seqGap") { + await MainActor.run { vm.messages.contains(where: { $0.role == "assistant" }) } + } + #expect(await MainActor.run { vm.errorText == nil }) + } + @Test func sessionChoicesPreferMainAndRecent() async throws { let now = Date().timeIntervalSince1970 * 1000 let recent = now - (2 * 60 * 60 * 1000) @@ -605,6 +647,35 @@ extension TestChatTransportState { try await waitUntil("streaming cleared") { await MainActor.run { vm.streamingAssistantText == nil } } } + @Test func stripsInboundMetadataFromHistoryMessages() async throws { + let history = OpenClawChatHistoryPayload( + sessionKey: "main", + sessionId: "sess-main", + messages: [ + AnyCodable([ + "role": "user", + "content": [["type": "text", "text": """ +Conversation info (untrusted metadata): +```json +{ \"sender\": \"openclaw-ios\" } +``` + +Hello? +"""]], + "timestamp": Date().timeIntervalSince1970 * 1000, + ]), + ], + thinkingLevel: "off") + let transport = TestChatTransport(historyResponses: [history]) + let vm = await MainActor.run { OpenClawChatViewModel(sessionKey: "main", transport: transport) } + + await MainActor.run { vm.load() } + try await waitUntil("history loaded") { await MainActor.run { !vm.messages.isEmpty } } + + let sanitized = await MainActor.run { vm.messages.first?.content.first?.text } + #expect(sanitized == "Hello?") + } + @Test func abortRequestsDoNotClearPendingUntilAbortedEvent() async throws { let sessionId = "sess-main" let history = OpenClawChatHistoryPayload( diff --git a/apps/shared/OpenClawKit/Tests/OpenClawKitTests/DeepLinksSecurityTests.swift b/apps/shared/OpenClawKit/Tests/OpenClawKitTests/DeepLinksSecurityTests.swift new file mode 100644 index 0000000000000..8bbf4f8a65037 --- /dev/null +++ b/apps/shared/OpenClawKit/Tests/OpenClawKitTests/DeepLinksSecurityTests.swift @@ -0,0 +1,61 @@ +import Foundation +import OpenClawKit +import Testing + +@Suite struct DeepLinksSecurityTests { + @Test func gatewayDeepLinkRejectsInsecureNonLoopbackWs() { + let url = URL( + string: "openclaw://gateway?host=attacker.example&port=18789&tls=0&token=abc")! + #expect(DeepLinkParser.parse(url) == nil) + } + + @Test func gatewayDeepLinkRejectsInsecurePrefixBypassHost() { + let url = URL( + string: "openclaw://gateway?host=127.attacker.example&port=18789&tls=0&token=abc")! + #expect(DeepLinkParser.parse(url) == nil) + } + + @Test func gatewayDeepLinkAllowsLoopbackWs() { + let url = URL( + string: "openclaw://gateway?host=127.0.0.1&port=18789&tls=0&token=abc")! + #expect( + DeepLinkParser.parse(url) == .gateway( + .init(host: "127.0.0.1", port: 18789, tls: false, token: "abc", password: nil))) + } + + @Test func setupCodeRejectsInsecureNonLoopbackWs() { + let payload = #"{"url":"ws://attacker.example:18789","token":"tok"}"# + let encoded = Data(payload.utf8) + .base64EncodedString() + .replacingOccurrences(of: "+", with: "-") + .replacingOccurrences(of: "/", with: "_") + .replacingOccurrences(of: "=", with: "") + #expect(GatewayConnectDeepLink.fromSetupCode(encoded) == nil) + } + + @Test func setupCodeRejectsInsecurePrefixBypassHost() { + let payload = #"{"url":"ws://127.attacker.example:18789","token":"tok"}"# + let encoded = Data(payload.utf8) + .base64EncodedString() + .replacingOccurrences(of: "+", with: "-") + .replacingOccurrences(of: "/", with: "_") + .replacingOccurrences(of: "=", with: "") + #expect(GatewayConnectDeepLink.fromSetupCode(encoded) == nil) + } + + @Test func setupCodeAllowsLoopbackWs() { + let payload = #"{"url":"ws://127.0.0.1:18789","token":"tok"}"# + let encoded = Data(payload.utf8) + .base64EncodedString() + .replacingOccurrences(of: "+", with: "-") + .replacingOccurrences(of: "/", with: "_") + .replacingOccurrences(of: "=", with: "") + #expect( + GatewayConnectDeepLink.fromSetupCode(encoded) == .init( + host: "127.0.0.1", + port: 18789, + tls: false, + token: "tok", + password: nil)) + } +} diff --git a/apps/shared/OpenClawKit/Tests/OpenClawKitTests/GatewayNodeSessionTests.swift b/apps/shared/OpenClawKit/Tests/OpenClawKitTests/GatewayNodeSessionTests.swift index 91e3096159114..08a6ea2162a28 100644 --- a/apps/shared/OpenClawKit/Tests/OpenClawKitTests/GatewayNodeSessionTests.swift +++ b/apps/shared/OpenClawKit/Tests/OpenClawKitTests/GatewayNodeSessionTests.swift @@ -3,6 +3,182 @@ import Testing @testable import OpenClawKit import OpenClawProtocol +private struct TimeoutError: Error, CustomStringConvertible { + let label: String + var description: String { "Timeout waiting for: \(self.label)" } +} + +private func waitUntil( + _ label: String, + timeoutSeconds: Double = 3.0, + pollMs: UInt64 = 10, + _ condition: @escaping @Sendable () async -> Bool) async throws +{ + let deadline = Date().addingTimeInterval(timeoutSeconds) + while Date() < deadline { + if await condition() { + return + } + try await Task.sleep(nanoseconds: pollMs * 1_000_000) + } + throw TimeoutError(label: label) +} + +private extension NSLock { + func withLock(_ body: () -> T) -> T { + self.lock() + defer { self.unlock() } + return body() + } +} + +private final class FakeGatewayWebSocketTask: WebSocketTasking, @unchecked Sendable { + private let lock = NSLock() + private var _state: URLSessionTask.State = .suspended + private var connectRequestId: String? + private var receivePhase = 0 + private var pendingReceiveHandler: + (@Sendable (Result) -> Void)? + + var state: URLSessionTask.State { + get { self.lock.withLock { self._state } } + set { self.lock.withLock { self._state = newValue } } + } + + func resume() { + self.state = .running + } + + func cancel(with closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) { + _ = (closeCode, reason) + self.state = .canceling + let handler = self.lock.withLock { () -> (@Sendable (Result) -> Void)? in + defer { self.pendingReceiveHandler = nil } + return self.pendingReceiveHandler + } + handler?(Result.failure(URLError(.cancelled))) + } + + func send(_ message: URLSessionWebSocketTask.Message) async throws { + let data: Data? = switch message { + case let .data(d): d + case let .string(s): s.data(using: .utf8) + @unknown default: nil + } + guard let data else { return } + if let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + obj["type"] as? String == "req", + obj["method"] as? String == "connect", + let id = obj["id"] as? String + { + self.lock.withLock { self.connectRequestId = id } + } + } + + func sendPing(pongReceiveHandler: @escaping @Sendable (Error?) -> Void) { + pongReceiveHandler(nil) + } + + func receive() async throws -> URLSessionWebSocketTask.Message { + let phase = self.lock.withLock { () -> Int in + let current = self.receivePhase + self.receivePhase += 1 + return current + } + if phase == 0 { + return .data(Self.connectChallengeData(nonce: "nonce-1")) + } + for _ in 0..<50 { + let id = self.lock.withLock { self.connectRequestId } + if let id { + return .data(Self.connectOkData(id: id)) + } + try await Task.sleep(nanoseconds: 1_000_000) + } + return .data(Self.connectOkData(id: "connect")) + } + + func receive( + completionHandler: @escaping @Sendable (Result) -> Void) + { + self.lock.withLock { self.pendingReceiveHandler = completionHandler } + } + + func emitReceiveFailure() { + let handler = self.lock.withLock { () -> (@Sendable (Result) -> Void)? in + self._state = .canceling + defer { self.pendingReceiveHandler = nil } + return self.pendingReceiveHandler + } + handler?(Result.failure(URLError(.networkConnectionLost))) + } + + private static func connectChallengeData(nonce: String) -> Data { + let json = """ + { + "type": "event", + "event": "connect.challenge", + "payload": { "nonce": "\(nonce)" } + } + """ + return Data(json.utf8) + } + + private static func connectOkData(id: String) -> Data { + let json = """ + { + "type": "res", + "id": "\(id)", + "ok": true, + "payload": { + "type": "hello-ok", + "protocol": 2, + "server": { "version": "test", "connId": "test" }, + "features": { "methods": [], "events": [] }, + "snapshot": { + "presence": [ { "ts": 1 } ], + "health": {}, + "stateVersion": { "presence": 0, "health": 0 }, + "uptimeMs": 0 + }, + "policy": { "maxPayload": 1, "maxBufferedBytes": 1, "tickIntervalMs": 30000 } + } + } + """ + return Data(json.utf8) + } +} + +private final class FakeGatewayWebSocketSession: WebSocketSessioning, @unchecked Sendable { + private let lock = NSLock() + private var tasks: [FakeGatewayWebSocketTask] = [] + private var makeCount = 0 + + func snapshotMakeCount() -> Int { + self.lock.withLock { self.makeCount } + } + + func latestTask() -> FakeGatewayWebSocketTask? { + self.lock.withLock { self.tasks.last } + } + + func makeWebSocketTask(url: URL) -> WebSocketTaskBox { + _ = url + return self.lock.withLock { + self.makeCount += 1 + let task = FakeGatewayWebSocketTask() + self.tasks.append(task) + return WebSocketTaskBox(task: task) + } + } +} + +private actor SeqGapProbe { + private var saw = false + func mark() { self.saw = true } + func value() -> Bool { self.saw } +} + struct GatewayNodeSessionTests { @Test func invokeWithTimeoutReturnsUnderlyingResponseBeforeTimeout() async { @@ -53,4 +229,56 @@ struct GatewayNodeSessionTests { #expect(response.ok == true) #expect(response.error == nil) } + + @Test + func emitsSyntheticSeqGapAfterReconnectSnapshot() async throws { + let session = FakeGatewayWebSocketSession() + let gateway = GatewayNodeSession() + let options = GatewayConnectOptions( + role: "operator", + scopes: ["operator.read"], + caps: [], + commands: [], + permissions: [:], + clientId: "openclaw-ios-test", + clientMode: "ui", + clientDisplayName: "iOS Test", + includeDeviceIdentity: false) + + let stream = await gateway.subscribeServerEvents(bufferingNewest: 32) + let probe = SeqGapProbe() + let listenTask = Task { + for await evt in stream { + if evt.event == "seqGap" { + await probe.mark() + return + } + } + } + + try await gateway.connect( + url: URL(string: "ws://example.invalid")!, + token: nil, + password: nil, + connectOptions: options, + sessionBox: WebSocketSessionBox(session: session), + onConnected: {}, + onDisconnected: { _ in }, + onInvoke: { req in + BridgeInvokeResponse(id: req.id, ok: true, payloadJSON: nil, error: nil) + }) + + let firstTask = try #require(session.latestTask()) + firstTask.emitReceiveFailure() + + try await waitUntil("reconnect socket created") { + session.snapshotMakeCount() >= 2 + } + try await waitUntil("synthetic seqGap broadcast") { + await probe.value() + } + + listenTask.cancel() + await gateway.disconnect() + } } diff --git a/apps/shared/OpenClawKit/Tests/OpenClawKitTests/ToolResultTextFormatterTests.swift b/apps/shared/OpenClawKit/Tests/OpenClawKitTests/ToolResultTextFormatterTests.swift new file mode 100644 index 0000000000000..1688725c8502d --- /dev/null +++ b/apps/shared/OpenClawKit/Tests/OpenClawKitTests/ToolResultTextFormatterTests.swift @@ -0,0 +1,54 @@ +import Testing +@testable import OpenClawChatUI + +@Suite("ToolResultTextFormatter") +struct ToolResultTextFormatterTests { + @Test func leavesPlainTextUntouched() { + let result = ToolResultTextFormatter.format(text: "All good", toolName: "nodes") + #expect(result == "All good") + } + + @Test func summarizesNodesListJSON() { + let json = """ + { + "ts": 1771610031380, + "nodes": [ + { + "displayName": "iPhone 16 Pro Max", + "connected": true, + "platform": "ios" + } + ] + } + """ + + let result = ToolResultTextFormatter.format(text: json, toolName: "nodes") + #expect(result.contains("1 node found.")) + #expect(result.contains("iPhone 16 Pro Max")) + #expect(result.contains("connected")) + } + + @Test func summarizesErrorJSONAndDropsAgentPrefix() { + let json = """ + { + "status": "error", + "tool": "nodes", + "error": "agent=main node=iPhone gateway=default action=invoke: pairing required" + } + """ + + let result = ToolResultTextFormatter.format(text: json, toolName: "nodes") + #expect(result == "Error: pairing required") + } + + @Test func suppressesUnknownStructuredPayload() { + let json = """ + { + "foo": "bar" + } + """ + + let result = ToolResultTextFormatter.format(text: json, toolName: "nodes") + #expect(result.isEmpty) + } +} diff --git a/apps/shared/OpenClawKit/Tools/CanvasA2UI/rolldown.config.mjs b/apps/shared/OpenClawKit/Tools/CanvasA2UI/rolldown.config.mjs index dbd4b86fff68d..ccf1683d5656c 100644 --- a/apps/shared/OpenClawKit/Tools/CanvasA2UI/rolldown.config.mjs +++ b/apps/shared/OpenClawKit/Tools/CanvasA2UI/rolldown.config.mjs @@ -1,9 +1,10 @@ import path from "node:path"; +import { existsSync } from "node:fs"; import { fileURLToPath } from "node:url"; -import { defineConfig } from "rolldown"; const here = path.dirname(fileURLToPath(import.meta.url)); const repoRoot = path.resolve(here, "../../../../.."); +const uiRoot = path.resolve(repoRoot, "ui"); const fromHere = (p) => path.resolve(here, p); const outputFile = path.resolve( here, @@ -16,8 +17,28 @@ const outputFile = path.resolve( const a2uiLitDist = path.resolve(repoRoot, "vendor/a2ui/renderers/lit/dist/src"); const a2uiThemeContext = path.resolve(a2uiLitDist, "0.8/ui/context/theme.js"); +const uiNodeModules = path.resolve(uiRoot, "node_modules"); +const repoNodeModules = path.resolve(repoRoot, "node_modules"); -export default defineConfig({ +function resolveUiDependency(moduleId) { + const candidates = [ + path.resolve(uiNodeModules, moduleId), + path.resolve(repoNodeModules, moduleId), + ]; + for (const candidate of candidates) { + if (existsSync(candidate)) { + return candidate; + } + } + + const fallbackCandidates = candidates.join(", "); + throw new Error( + `A2UI bundle config cannot resolve ${moduleId}. Checked: ${fallbackCandidates}. ` + + "Keep dependency installed in ui workspace or repo root before bundling.", + ); +} + +export default { input: fromHere("bootstrap.js"), experimental: { attachDebugInfo: "none", @@ -28,12 +49,13 @@ export default defineConfig({ "@a2ui/lit": path.resolve(a2uiLitDist, "index.js"), "@a2ui/lit/ui": path.resolve(a2uiLitDist, "0.8/ui/ui.js"), "@openclaw/a2ui-theme-context": a2uiThemeContext, - "@lit/context": path.resolve(repoRoot, "node_modules/@lit/context/index.js"), - "@lit/context/": path.resolve(repoRoot, "node_modules/@lit/context/"), - "@lit-labs/signals": path.resolve(repoRoot, "node_modules/@lit-labs/signals/index.js"), - "@lit-labs/signals/": path.resolve(repoRoot, "node_modules/@lit-labs/signals/"), - lit: path.resolve(repoRoot, "node_modules/lit/index.js"), - "lit/": path.resolve(repoRoot, "node_modules/lit/"), + "@lit/context": resolveUiDependency("@lit/context"), + "@lit/context/": resolveUiDependency("@lit/context/"), + "@lit-labs/signals": resolveUiDependency("@lit-labs/signals"), + "@lit-labs/signals/": resolveUiDependency("@lit-labs/signals/"), + lit: resolveUiDependency("lit"), + "lit/": resolveUiDependency("lit/"), + "signal-utils/": resolveUiDependency("signal-utils/"), }, }, output: { @@ -42,4 +64,4 @@ export default defineConfig({ codeSplitting: false, sourcemap: false, }, -}); +}; diff --git a/docs/assets/sponsors/blacksmith.svg b/docs/assets/sponsors/blacksmith.svg new file mode 100644 index 0000000000000..5bb1bc2e72c82 --- /dev/null +++ b/docs/assets/sponsors/blacksmith.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/docs/assets/sponsors/openai.svg b/docs/assets/sponsors/openai.svg new file mode 100644 index 0000000000000..1c3491b9be963 --- /dev/null +++ b/docs/assets/sponsors/openai.svg @@ -0,0 +1,3 @@ + + + diff --git a/docs/automation/cron-vs-heartbeat.md b/docs/automation/cron-vs-heartbeat.md index a138e721ae4cd..c25cbcb80dbc9 100644 --- a/docs/automation/cron-vs-heartbeat.md +++ b/docs/automation/cron-vs-heartbeat.md @@ -211,7 +211,7 @@ For ad-hoc workflows, call Lobster directly. - Lobster runs as a **local subprocess** (`lobster` CLI) in tool mode and returns a **JSON envelope**. - If the tool returns `needs_approval`, you resume with a `resumeToken` and `approve` flag. - The tool is an **optional plugin**; enable it additively via `tools.alsoAllow: ["lobster"]` (recommended). -- If you pass `lobsterPath`, it must be an **absolute path**. +- Lobster expects the `lobster` CLI to be available on `PATH`. See [Lobster](/tools/lobster) for full usage and examples. diff --git a/docs/automation/hooks.md b/docs/automation/hooks.md index 55c04e9990bd8..66b96cd1e9e96 100644 --- a/docs/automation/hooks.md +++ b/docs/automation/hooks.md @@ -119,6 +119,8 @@ Example `package.json`: Each entry points to a hook directory containing `HOOK.md` and `handler.ts` (or `index.ts`). Hook packs can ship dependencies; they will be installed under `~/.openclaw/hooks/`. +Each `openclaw.hooks` entry must stay inside the package directory after symlink +resolution; entries that escape are rejected. Security note: `openclaw hooks install` installs dependencies with `npm install --ignore-scripts` (no lifecycle scripts). Keep hook pack dependency trees "pure JS/TS" and avoid packages that rely diff --git a/docs/automation/troubleshooting.md b/docs/automation/troubleshooting.md index a189d805221f9..9190855dd59ee 100644 --- a/docs/automation/troubleshooting.md +++ b/docs/automation/troubleshooting.md @@ -90,7 +90,6 @@ Common signatures: - `heartbeat skipped` with `reason=quiet-hours` → outside `activeHours`. - `requests-in-flight` → main lane busy; heartbeat deferred. - `empty-heartbeat-file` → interval heartbeat skipped because `HEARTBEAT.md` has no actionable content and no tagged cron event is queued. -- `no-heartbeat-file` → interval heartbeat skipped because `HEARTBEAT.md` is missing and no tagged cron event is queued. - `alerts-disabled` → visibility settings suppress outbound heartbeat messages. ## Timezone and activeHours gotchas diff --git a/docs/channels/bluebubbles.md b/docs/channels/bluebubbles.md index fd677a1d585df..8c8267498b721 100644 --- a/docs/channels/bluebubbles.md +++ b/docs/channels/bluebubbles.md @@ -46,7 +46,8 @@ Status: bundled plugin that talks to the BlueBubbles macOS server over HTTP. **R Security note: -- Always set a webhook password. If you expose the gateway through a reverse proxy (Tailscale Serve/Funnel, nginx, Cloudflare Tunnel, ngrok), the proxy may connect to the gateway over loopback. The BlueBubbles webhook handler treats requests with forwarding headers as proxied and will not accept passwordless webhooks. +- Always set a webhook password. +- Webhook authentication is always required. OpenClaw rejects BlueBubbles webhook requests unless they include a password/guid that matches `channels.bluebubbles.password` (for example `?password=` or `x-password`), regardless of loopback/proxy topology. ## Keeping Messages.app alive (VM / headless setups) diff --git a/docs/channels/discord.md b/docs/channels/discord.md index 774a0eba1a8e0..334c6d78ee535 100644 --- a/docs/channels/discord.md +++ b/docs/channels/discord.md @@ -258,6 +258,29 @@ Now create some channels on your Discord server and start chatting. Your agent c - Group DMs are ignored by default (`channels.discord.dm.groupEnabled=false`). - Native slash commands run in isolated command sessions (`agent::discord:slash:`), while still carrying `CommandTargetSessionKey` to the routed conversation session. +## Forum channels + +Discord forum and media channels only accept thread posts. OpenClaw supports two ways to create them: + +- Send a message to the forum parent (`channel:`) to auto-create a thread. The thread title uses the first non-empty line of your message. +- Use `openclaw message thread create` to create a thread directly. Do not pass `--message-id` for forum channels. + +Example: send to forum parent to create a thread + +```bash +openclaw message send --channel discord --target channel: \ + --message "Topic title\nBody of the post" +``` + +Example: create a forum thread explicitly + +```bash +openclaw message thread create --channel discord --target channel: \ + --thread-name "Topic title" --message "Body of the post" +``` + +Forum parents do not accept Discord components. If you need components, send to the thread itself (`channel:`). + ## Interactive components OpenClaw supports Discord components v2 containers for agent messages. Use the message tool with a `components` payload. Interaction results are routed back to the agent as normal inbound messages and follow the existing Discord `replyToMode` settings. @@ -272,6 +295,8 @@ By default, components are single use. Set `components.reusable=true` to allow b To restrict who can click a button, set `allowedUsers` on that button (Discord user IDs, tags, or `*`). When configured, unmatched users receive an ephemeral denial. +The `/model` and `/models` slash commands open an interactive model picker with provider and model dropdowns plus a Submit step. The picker reply is ephemeral and only the invoking user can use it. + File attachments: - `file` blocks must point to an attachment reference (`attachment://`) @@ -373,6 +398,7 @@ Example: - guild must match `channels.discord.guilds` (`id` preferred, slug accepted) - optional sender allowlists: `users` (IDs or names) and `roles` (role IDs only); if either is configured, senders are allowed when they match `users` OR `roles` + - names/tags are supported for `users`, but IDs are safer; `openclaw security audit` warns when name/tag entries are used - if a guild has `channels` configured, non-listed channels are denied - if a guild has no `channels` block, all channels in that allowlisted guild are allowed @@ -399,7 +425,7 @@ Example: } ``` - If you only set `DISCORD_BOT_TOKEN` and do not create a `channels.discord` block, runtime fallback is `groupPolicy="open"` (with a warning in logs). + If you only set `DISCORD_BOT_TOKEN` and do not create a `channels.discord` block, runtime fallback is `groupPolicy="allowlist"` (with a warning in logs), even if `channels.defaults.groupPolicy` is `open`. @@ -509,6 +535,10 @@ Use `bindings[].match.roles` to route Discord guild members to different agents See [Slash commands](/tools/slash-commands) for command catalog and behavior. +Default slash command settings: + +- `ephemeral: true` + ## Feature details @@ -530,6 +560,51 @@ See [Slash commands](/tools/slash-commands) for command catalog and behavior. + + OpenClaw can stream draft replies by sending a temporary message and editing it as text arrives. + + - `channels.discord.streaming` controls preview streaming (`off` | `partial` | `block` | `progress`, default: `off`). + - `progress` is accepted for cross-channel consistency and maps to `partial` on Discord. + - `channels.discord.streamMode` is a legacy alias and is auto-migrated. + - `partial` edits a single preview message as tokens arrive. + - `block` emits draft-sized chunks (use `draftChunk` to tune size and breakpoints). + + Example: + +```json5 +{ + channels: { + discord: { + streaming: "partial", + }, + }, +} +``` + + `block` mode chunking defaults (clamped to `channels.discord.textChunkLimit`): + +```json5 +{ + channels: { + discord: { + streaming: "block", + draftChunk: { + minChars: 200, + maxChars: 800, + breakPreference: "paragraph", + }, + }, + }, +} +``` + + Preview streaming is text-only; media replies fall back to normal delivery. + + Note: preview streaming is separate from block streaming. When block streaming is explicitly + enabled for Discord, OpenClaw skips the preview stream to avoid double streaming. + + + Guild history context: @@ -552,6 +627,49 @@ See [Slash commands](/tools/slash-commands) for command catalog and behavior. + + Discord can bind a thread to a session target so follow-up messages in that thread keep routing to the same session (including subagent sessions). + + Commands: + + - `/focus ` bind current/new thread to a subagent/session target + - `/unfocus` remove current thread binding + - `/agents` show active runs and binding state + - `/session ttl ` inspect/update auto-unfocus TTL for focused bindings + + Config: + +```json5 +{ + session: { + threadBindings: { + enabled: true, + ttlHours: 24, + }, + }, + channels: { + discord: { + threadBindings: { + enabled: true, + ttlHours: 24, + spawnSubagentSessions: false, // opt-in + }, + }, + }, +} +``` + + Notes: + + - `session.threadBindings.*` sets global defaults. + - `channels.discord.threadBindings.*` overrides Discord behavior. + - `spawnSubagentSessions` must be true to auto-create/bind threads for `sessions_spawn({ thread: true })`. + - If thread bindings are disabled for an account, `/focus` and related thread binding operations are unavailable. + + See [Sub-agents](/tools/subagents) and [Configuration Reference](/gateway/configuration-reference). + + + Per-guild reaction notification mode: @@ -774,6 +892,47 @@ Example: } ``` +## Voice channels + +OpenClaw can join Discord voice channels for realtime, continuous conversations. This is separate from voice message attachments. + +Requirements: + +- Enable native commands (`commands.native` or `channels.discord.commands.native`). +- Configure `channels.discord.voice`. +- The bot needs Connect + Speak permissions in the target voice channel. + +Use the Discord-only native command `/vc join|leave|status` to control sessions. The command uses the account default agent and follows the same allowlist and group policy rules as other Discord commands. + +Auto-join example: + +```json5 +{ + channels: { + discord: { + voice: { + enabled: true, + autoJoin: [ + { + guildId: "123456789012345678", + channelId: "234567890123456789", + }, + ], + tts: { + provider: "openai", + openai: { voice: "alloy" }, + }, + }, + }, + }, +} +``` + +Notes: + +- `voice.tts` overrides `messages.tts` for voice playback only. +- Voice is enabled by default; set `channels.discord.voice.enabled=false` to disable it. + ## Voice messages Discord voice messages show a waveform preview and require OGG/Opus audio plus metadata. OpenClaw generates the waveform automatically, but it needs `ffmpeg` and `ffprobe` available on the gateway host to inspect and convert audio files. @@ -860,9 +1019,10 @@ High-signal Discord fields: - startup/auth: `enabled`, `token`, `accounts.*`, `allowBots` - policy: `groupPolicy`, `dm.*`, `guilds.*`, `guilds.*.channels.*` -- command: `commands.native`, `commands.useAccessGroups`, `configWrites` +- command: `commands.native`, `commands.useAccessGroups`, `configWrites`, `slashCommand.*` - reply/history: `replyToMode`, `historyLimit`, `dmHistoryLimit`, `dms.*.historyLimit` - delivery: `textChunkLimit`, `chunkMode`, `maxLinesPerMessage` +- streaming: `streaming` (legacy alias: `streamMode`), `draftChunk`, `blockStreaming`, `blockStreamingCoalesce` - media/retry: `mediaMaxMb`, `retry` - actions: `actions.*` - presence: `activity`, `status`, `activityType`, `activityUrl` diff --git a/docs/channels/grammy.md b/docs/channels/grammy.md index ae92c5292b02c..25c197116f6c9 100644 --- a/docs/channels/grammy.md +++ b/docs/channels/grammy.md @@ -21,7 +21,7 @@ title: grammY - **Webhook support:** `webhook-set.ts` wraps `setWebhook/deleteWebhook`; `webhook.ts` hosts the callback with health + graceful shutdown. Gateway enables webhook mode when `channels.telegram.webhookUrl` + `channels.telegram.webhookSecret` are set (otherwise it long-polls). - **Sessions:** direct chats collapse into the agent main session (`agent::`); groups use `agent::telegram:group:`; replies route back to the same channel. - **Config knobs:** `channels.telegram.botToken`, `channels.telegram.dmPolicy`, `channels.telegram.groups` (allowlist + mention defaults), `channels.telegram.allowFrom`, `channels.telegram.groupAllowFrom`, `channels.telegram.groupPolicy`, `channels.telegram.mediaMaxMb`, `channels.telegram.linkPreview`, `channels.telegram.proxy`, `channels.telegram.webhookSecret`, `channels.telegram.webhookUrl`, `channels.telegram.webhookHost`. -- **Live stream preview:** optional `channels.telegram.streamMode` sends a temporary message and updates it with `editMessageText`. This is separate from channel block streaming. +- **Live stream preview:** `channels.telegram.streaming` (`off | partial | block | progress`) sends a temporary message and updates it with `editMessageText`. This is separate from channel block streaming. - **Tests:** grammy mocks cover DM + group mention gating and outbound send; more media/webhook fixtures still welcome. Open questions diff --git a/docs/channels/groups.md b/docs/channels/groups.md index 6bd278846c5bd..00118c546b551 100644 --- a/docs/channels/groups.md +++ b/docs/channels/groups.md @@ -190,6 +190,7 @@ Notes: - Group DMs are controlled separately (`channels.discord.dm.*`, `channels.slack.dm.*`). - Telegram allowlist can match user IDs (`"123456789"`, `"telegram:123456789"`, `"tg:123456789"`) or usernames (`"@alice"` or `"alice"`); prefixes are case-insensitive. - Default is `groupPolicy: "allowlist"`; if your group allowlist is empty, group messages are blocked. +- Runtime safety: when a provider block is completely missing (`channels.` absent), group policy falls back to a fail-closed mode (typically `allowlist`) instead of inheriting `channels.defaults.groupPolicy`. Quick mental model (evaluation order for group messages): diff --git a/docs/channels/imessage.md b/docs/channels/imessage.md index d7a1b6335977a..5720da1714af8 100644 --- a/docs/channels/imessage.md +++ b/docs/channels/imessage.md @@ -158,6 +158,7 @@ imsg send "test" Group sender allowlist: `channels.imessage.groupAllowFrom`. Runtime fallback: if `groupAllowFrom` is unset, iMessage group sender checks fall back to `allowFrom` when available. + Runtime note: if `channels.imessage` is completely missing, runtime falls back to `groupPolicy="allowlist"` and logs a warning (even if `channels.defaults.groupPolicy` is set). Mention gating for groups: diff --git a/docs/channels/line.md b/docs/channels/line.md index d32e683fbeb59..b87cbd3f5fbf8 100644 --- a/docs/channels/line.md +++ b/docs/channels/line.md @@ -118,6 +118,7 @@ Allowlists and policies: - `channels.line.groupPolicy`: `allowlist | open | disabled` - `channels.line.groupAllowFrom`: allowlisted LINE user IDs for groups - Per-group overrides: `channels.line.groups..allowFrom` +- Runtime note: if `channels.line` is completely missing, runtime falls back to `groupPolicy="allowlist"` for group checks (even if `channels.defaults.groupPolicy` is set). LINE IDs are case-sensitive. Valid IDs look like: diff --git a/docs/channels/matrix.md b/docs/channels/matrix.md index 04205d9497110..9bb56d1ddb7b2 100644 --- a/docs/channels/matrix.md +++ b/docs/channels/matrix.md @@ -195,6 +195,7 @@ Notes: ## Rooms (groups) - Default: `channels.matrix.groupPolicy = "allowlist"` (mention-gated). Use `channels.defaults.groupPolicy` to override the default when unset. +- Runtime note: if `channels.matrix` is completely missing, runtime falls back to `groupPolicy="allowlist"` for room checks (even if `channels.defaults.groupPolicy` is set). - Allowlist rooms with `channels.matrix.groups` (room IDs or aliases; names are resolved to IDs when directory search finds a single exact match): ```json5 diff --git a/docs/channels/mattermost.md b/docs/channels/mattermost.md index fa0d9393e0f7d..350fa8429c4de 100644 --- a/docs/channels/mattermost.md +++ b/docs/channels/mattermost.md @@ -103,6 +103,7 @@ Notes: - Default: `channels.mattermost.groupPolicy = "allowlist"` (mention-gated). - Allowlist senders with `channels.mattermost.groupAllowFrom` (user IDs or `@username`). - Open channels: `channels.mattermost.groupPolicy="open"` (mention-gated). +- Runtime note: if `channels.mattermost` is completely missing, runtime falls back to `groupPolicy="allowlist"` for group checks (even if `channels.defaults.groupPolicy` is set). ## Targets for outbound delivery diff --git a/docs/channels/signal.md b/docs/channels/signal.md index 60bb5f7ce92c8..b216af120ce0f 100644 --- a/docs/channels/signal.md +++ b/docs/channels/signal.md @@ -195,6 +195,7 @@ Groups: - `channels.signal.groupPolicy = open | allowlist | disabled`. - `channels.signal.groupAllowFrom` controls who can trigger in groups when `allowlist` is set. +- Runtime note: if `channels.signal` is completely missing, runtime falls back to `groupPolicy="allowlist"` for group checks (even if `channels.defaults.groupPolicy` is set). ## How it works (behavior) diff --git a/docs/channels/slack.md b/docs/channels/slack.md index 9fdd3fb89a2e4..4a1bda6990bd8 100644 --- a/docs/channels/slack.md +++ b/docs/channels/slack.md @@ -165,7 +165,7 @@ For actions/directory reads, user token can be preferred when configured. For wr Channel allowlist lives under `channels.slack.channels`. - Runtime note: if `channels.slack` is completely missing (env-only setup) and `channels.defaults.groupPolicy` is unset, runtime falls back to `groupPolicy="open"` and logs a warning. + Runtime note: if `channels.slack` is completely missing (env-only setup), runtime falls back to `groupPolicy="allowlist"` and logs a warning (even if `channels.defaults.groupPolicy` is set). Name/ID resolution: @@ -465,14 +465,29 @@ openclaw pairing list slack OpenClaw supports Slack native text streaming via the Agents and AI Apps API. -By default, streaming is enabled. Disable it per account: +`channels.slack.streaming` controls live preview behavior: + +- `off`: disable live preview streaming. +- `partial` (default): replace preview text with the latest partial output. +- `block`: append chunked preview updates. +- `progress`: show progress status text while generating, then send final text. + +`channels.slack.nativeStreaming` controls Slack's native streaming API (`chat.startStream` / `chat.appendStream` / `chat.stopStream`) when `streaming` is `partial` (default: `true`). + +Disable native Slack streaming (keep draft preview behavior): ```yaml channels: slack: - streaming: false + streaming: partial + nativeStreaming: false ``` +Legacy keys: + +- `channels.slack.streamMode` (`replace | status_final | append`) is auto-migrated to `channels.slack.streaming`. +- boolean `channels.slack.streaming` is auto-migrated to `channels.slack.nativeStreaming`. + ### Requirements 1. Enable **Agents and AI Apps** in your Slack app settings. @@ -498,7 +513,7 @@ Primary reference: - DM access: `dm.enabled`, `dmPolicy`, `allowFrom` (legacy: `dm.policy`, `dm.allowFrom`), `dm.groupEnabled`, `dm.groupChannels` - channel access: `groupPolicy`, `channels.*`, `channels.*.users`, `channels.*.requireMention` - threading/history: `replyToMode`, `replyToModeByChatType`, `thread.*`, `historyLimit`, `dmHistoryLimit`, `dms.*.historyLimit` - - delivery: `textChunkLimit`, `chunkMode`, `mediaMaxMb` + - delivery: `textChunkLimit`, `chunkMode`, `mediaMaxMb`, `streaming`, `nativeStreaming` - ops/features: `configWrites`, `commands.native`, `slashCommand.*`, `actions.*`, `userToken`, `userTokenReadOnly` ## Related diff --git a/docs/channels/telegram.md b/docs/channels/telegram.md index 7e1d95d2febb9..138b2b255d819 100644 --- a/docs/channels/telegram.md +++ b/docs/channels/telegram.md @@ -148,6 +148,7 @@ curl "https://api.telegram.org/bot/getUpdates" `groupAllowFrom` is used for group sender filtering. If not set, Telegram falls back to `allowFrom`. `groupAllowFrom` entries must be numeric Telegram user IDs. + Runtime note: if `channels.telegram` is completely missing, runtime falls back to `groupPolicy="allowlist"` for group policy evaluation (even if `channels.defaults.groupPolicy` is set). Example: allow any member in one specific group: @@ -226,21 +227,9 @@ curl "https://api.telegram.org/bot/getUpdates" Requirement: - - `channels.telegram.streamMode` is not `"off"` (default: `"partial"`) - - Modes: - - - `off`: no live preview - - `partial`: frequent preview updates from partial text - - `block`: chunked preview updates using `channels.telegram.draftChunk` - - `draftChunk` defaults for `streamMode: "block"`: - - - `minChars: 200` - - `maxChars: 800` - - `breakPreference: "paragraph"` - - `maxChars` is clamped by `channels.telegram.textChunkLimit`. + - `channels.telegram.streaming` is `off | partial | block | progress` (default: `off`) + - `progress` maps to `partial` on Telegram (compat with cross-channel naming) + - legacy `channels.telegram.streamMode` and boolean `streaming` values are auto-mapped This works in direct chats and groups/topics. @@ -248,7 +237,7 @@ curl "https://api.telegram.org/bot/getUpdates" For complex replies (for example media payloads), OpenClaw falls back to normal final delivery and then cleans up the preview message. - `streamMode` is separate from block streaming. When block streaming is explicitly enabled for Telegram, OpenClaw skips the preview stream to avoid double-streaming. + Preview streaming is separate from block streaming. When block streaming is explicitly enabled for Telegram, OpenClaw skips the preview stream to avoid double-streaming. Telegram-only reasoning stream: @@ -682,6 +671,25 @@ openclaw message send --channel telegram --target @name --message "hi" - Node 22+ + custom fetch/proxy can trigger immediate abort behavior if AbortSignal types mismatch. - Some hosts resolve `api.telegram.org` to IPv6 first; broken IPv6 egress can cause intermittent Telegram API failures. + - If logs include `TypeError: fetch failed` or `Network request for 'getUpdates' failed!`, OpenClaw now retries these as recoverable network errors. + - On VPS hosts with unstable direct egress/TLS, route Telegram API calls through `channels.telegram.proxy`: + +```yaml +channels: + telegram: + proxy: socks5://user:pass@proxy-host:1080 +``` + + - If DNS/IPv6 selection is unstable, force Node family selection behavior explicitly: + +```yaml +channels: + telegram: + network: + autoSelectFamily: false +``` + + - Environment override (temporary): set `OPENCLAW_TELEGRAM_DISABLE_AUTO_SELECT_FAMILY=1`. - Validate DNS answers: ```bash @@ -721,7 +729,7 @@ Primary reference: - `channels.telegram.textChunkLimit`: outbound chunk size (chars). - `channels.telegram.chunkMode`: `length` (default) or `newline` to split on blank lines (paragraph boundaries) before length chunking. - `channels.telegram.linkPreview`: toggle link previews for outbound messages (default: true). -- `channels.telegram.streamMode`: `off | partial | block` (live stream preview). +- `channels.telegram.streaming`: `off | partial | block | progress` (live stream preview; default: `off`; `progress` maps to `partial`). - `channels.telegram.mediaMaxMb`: inbound/outbound media cap (MB). - `channels.telegram.retry`: retry policy for outbound Telegram API calls (attempts, minDelayMs, maxDelayMs, jitter). - `channels.telegram.network.autoSelectFamily`: override Node autoSelectFamily (true=enable, false=disable). Defaults to disabled on Node 22 to avoid Happy Eyeballs timeouts. @@ -745,7 +753,7 @@ Telegram-specific high-signal fields: - access control: `dmPolicy`, `allowFrom`, `groupPolicy`, `groupAllowFrom`, `groups`, `groups.*.topics.*` - command/menu: `commands.native`, `customCommands` - threading/replies: `replyToMode` -- streaming: `streamMode` (preview), `draftChunk`, `blockStreaming` +- streaming: `streaming` (preview), `blockStreaming` - formatting/delivery: `textChunkLimit`, `chunkMode`, `linkPreview`, `responsePrefix` - media/network: `mediaMaxMb`, `timeoutSeconds`, `retry`, `network.autoSelectFamily`, `proxy` - webhook: `webhookUrl`, `webhookSecret`, `webhookPath`, `webhookHost` diff --git a/docs/channels/whatsapp.md b/docs/channels/whatsapp.md index a6fb427bdc2d5..d92dfda9c7520 100644 --- a/docs/channels/whatsapp.md +++ b/docs/channels/whatsapp.md @@ -171,7 +171,7 @@ OpenClaw recommends running WhatsApp on a separate number when possible. (The ch - if `groupAllowFrom` is unset, runtime falls back to `allowFrom` when available - sender allowlists are evaluated before mention/reply activation - Note: if no `channels.whatsapp` block exists at all, runtime group-policy fallback is effectively `open`. + Note: if no `channels.whatsapp` block exists at all, runtime group-policy fallback is `allowlist` (with a warning log), even if `channels.defaults.groupPolicy` is set. diff --git a/docs/ci.md b/docs/ci.md index cdf5b126a2889..64d4df0ec1c47 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -34,12 +34,11 @@ Jobs are ordered so cheap checks fail before expensive ones run: ## Runners -| Runner | Jobs | -| ------------------------------- | ----------------------------- | -| `blacksmith-4vcpu-ubuntu-2404` | Most Linux jobs | -| `blacksmith-4vcpu-windows-2025` | `checks-windows` | -| `macos-latest` | `macos`, `ios` | -| `ubuntu-latest` | Scope detection (lightweight) | +| Runner | Jobs | +| -------------------------------- | ------------------------------------------ | +| `blacksmith-16vcpu-ubuntu-2404` | Most Linux jobs, including scope detection | +| `blacksmith-16vcpu-windows-2025` | `checks-windows` | +| `macos-latest` | `macos`, `ios` | ## Local Equivalents diff --git a/docs/cli/acp.md b/docs/cli/acp.md index 46b78cce6f51d..9535509016d23 100644 --- a/docs/cli/acp.md +++ b/docs/cli/acp.md @@ -21,6 +21,9 @@ openclaw acp # Remote Gateway openclaw acp --url wss://gateway-host:18789 --token +# Remote Gateway (token from file) +openclaw acp --url wss://gateway-host:18789 --token-file ~/.openclaw/gateway.token + # Attach to an existing session key openclaw acp --session agent:main:main @@ -40,7 +43,7 @@ It spawns the ACP bridge and lets you type prompts interactively. openclaw acp client # Point the spawned bridge at a remote Gateway -openclaw acp client --server-args --url wss://gateway-host:18789 --token +openclaw acp client --server-args --url wss://gateway-host:18789 --token-file ~/.openclaw/gateway.token # Override the server command (default: openclaw) openclaw acp client --server "node" --server-args openclaw.mjs acp --url ws://127.0.0.1:19001 @@ -66,6 +69,8 @@ Example direct run (no config write): ```bash openclaw acp --url wss://gateway-host:18789 --token +# preferred for local process safety +openclaw acp --url wss://gateway-host:18789 --token-file ~/.openclaw/gateway.token ``` ## Selecting agents @@ -153,7 +158,9 @@ Learn more about session keys at [/concepts/session](/concepts/session). - `--url `: Gateway WebSocket URL (defaults to gateway.remote.url when configured). - `--token `: Gateway auth token. +- `--token-file `: read Gateway auth token from file. - `--password `: Gateway auth password. +- `--password-file `: read Gateway auth password from file. - `--session `: default session key. - `--session-label