main 4617bc966db2 cached
231 files
3.2 MB
841.3k tokens
943 symbols
1 requests
Download .txt
Showing preview only (3,389K chars total). Download the full file or copy to clipboard to get everything.
Repository: nutstore/obsidian-nutstore-sync
Branch: main
Commit: 4617bc966db2
Files: 231
Total size: 3.2 MB

Directory structure:
gitextract_y4gmj5jl/

├── .github/
│   └── workflows/
│       ├── changelog.yml
│       ├── ci.yml
│       ├── release.yml
│       └── update-changelog-version.yml
├── .gitignore
├── .prettierrc
├── .swcrc
├── .vscode/
│   └── settings.json
├── CHANGELOG.md
├── LICENSE
├── README.md
├── esbuild.config.mjs
├── manifest.json
├── package.json
├── packages/
│   ├── chatbox/
│   │   ├── package.json
│   │   ├── postcss.config.mjs
│   │   ├── rslib.config.ts
│   │   ├── src/
│   │   │   ├── App.tsx
│   │   │   ├── assets/
│   │   │   │   └── styles/
│   │   │   │       └── global.css
│   │   │   ├── components/
│   │   │   │   ├── ConfirmDialog.tsx
│   │   │   │   ├── ContentParts.tsx
│   │   │   │   ├── CopyButton.tsx
│   │   │   │   ├── FragmentDivider.tsx
│   │   │   │   ├── MarkdownContent.tsx
│   │   │   │   ├── MessageCard.tsx
│   │   │   │   ├── PaneResizer.tsx
│   │   │   │   ├── PendingList.tsx
│   │   │   │   ├── RunStateCard.tsx
│   │   │   │   ├── SessionHistoryItem.tsx
│   │   │   │   ├── TaskCard.tsx
│   │   │   │   └── TasksPanel.tsx
│   │   │   ├── i18n/
│   │   │   │   ├── index.ts
│   │   │   │   └── locales/
│   │   │   │       ├── en.ts
│   │   │   │       └── zh.ts
│   │   │   ├── index.tsx
│   │   │   ├── types.ts
│   │   │   └── utils.ts
│   │   ├── tsconfig.json
│   │   └── unocss.config.ts
│   └── webdav-explorer/
│       ├── package.json
│       ├── postcss.config.mjs
│       ├── rslib.config.ts
│       ├── src/
│       │   ├── App.tsx
│       │   ├── assets/
│       │   │   └── styles/
│       │   │       └── global.css
│       │   ├── components/
│       │   │   ├── File.tsx
│       │   │   ├── FileList.tsx
│       │   │   ├── Folder.tsx
│       │   │   └── NewFolder.tsx
│       │   ├── i18n/
│       │   │   ├── index.ts
│       │   │   └── locales/
│       │   │       ├── en.ts
│       │   │       └── zh.ts
│       │   └── index.tsx
│       ├── tsconfig.json
│       └── unocss.config.ts
├── pnpm-workspace.yaml
├── src/
│   ├── ai/
│   │   ├── bash/
│   │   │   ├── fs.ts
│   │   │   ├── runtime.test.ts
│   │   │   └── runtime.ts
│   │   ├── config.test.ts
│   │   ├── config.ts
│   │   ├── file-operation.ts
│   │   ├── models-api.json
│   │   ├── permission-guard.test.ts
│   │   ├── permission-guard.ts
│   │   ├── providers/
│   │   │   ├── openai.ts
│   │   │   ├── registry.ts
│   │   │   └── types.ts
│   │   ├── runtime.ts
│   │   ├── search-path-filter.ts
│   │   ├── tool-call-repeat.ts
│   │   ├── tools.test.ts
│   │   ├── tools.ts
│   │   ├── transport/
│   │   │   ├── obsidian-fetch.test.ts
│   │   │   └── obsidian-fetch.ts
│   │   ├── tree.test.ts
│   │   ├── tree.ts
│   │   └── types.ts
│   ├── api/
│   │   ├── delta.ts
│   │   ├── latestDeltaCursor.ts
│   │   └── webdav.ts
│   ├── assets/
│   │   └── styles/
│   │       └── global.css
│   ├── chat/
│   │   └── domain.ts
│   ├── chatbox/
│   │   └── types.ts
│   ├── components/
│   │   ├── AIPermissionModal.ts
│   │   ├── CacheClearModal.ts
│   │   ├── CacheRestoreModal.ts
│   │   ├── CacheSaveModal.ts
│   │   ├── DeleteConfirmModal.ts
│   │   ├── FailedTasksModal.ts
│   │   ├── FilterEditorModal.ts
│   │   ├── LogoutConfirmModal.ts
│   │   ├── ModelEditorModal.ts
│   │   ├── ProviderEditorModal.ts
│   │   ├── ProvidersManagerModal.ts
│   │   ├── SelectRemoteBaseDirModal.ts
│   │   ├── SyncConfirmModal.ts
│   │   ├── SyncProgressModal.ts
│   │   ├── SyncRibbonManager.ts
│   │   ├── TaskListConfirmModal.ts
│   │   └── TextAreaModal.ts
│   ├── consts.ts
│   ├── events/
│   │   ├── index.ts
│   │   ├── sso-receive.ts
│   │   ├── sync-cancel.ts
│   │   ├── sync-end.ts
│   │   ├── sync-error.ts
│   │   ├── sync-preparing.ts
│   │   ├── sync-progress.ts
│   │   ├── sync-start.ts
│   │   ├── sync-update-mtime-progress.ts
│   │   └── vault.ts
│   ├── fs/
│   │   ├── fs.interface.ts
│   │   ├── local-vault.ts
│   │   ├── nutstore.ts
│   │   └── utils/
│   │       ├── complete-loss-dir.ts
│   │       └── is-root.ts
│   ├── i18n/
│   │   ├── index.ts
│   │   └── locales/
│   │       ├── en.ts
│   │       └── zh.ts
│   ├── index.ts
│   ├── model/
│   │   ├── stat.model.ts
│   │   └── sync-record.model.ts
│   ├── polyfill.test.ts
│   ├── polyfill.ts
│   ├── services/
│   │   ├── cache.service.v1.ts
│   │   ├── chat.service.test.ts
│   │   ├── chat.service.ts
│   │   ├── command.service.ts
│   │   ├── events.service.ts
│   │   ├── i18n.service.ts
│   │   ├── logger.service.ts
│   │   ├── progress.service.ts
│   │   ├── realtime-sync.service.ts
│   │   ├── scheduled-sync.service.ts
│   │   ├── status.service.ts
│   │   ├── sync-executor.service.ts
│   │   └── webdav.service.ts
│   ├── settings/
│   │   ├── account.ts
│   │   ├── ai.ts
│   │   ├── cache.ts
│   │   ├── common.ts
│   │   ├── filter.ts
│   │   ├── index.ts
│   │   ├── log.ts
│   │   └── settings.base.ts
│   ├── shims/
│   │   └── node-zlib.ts
│   ├── storage/
│   │   ├── blob.ts
│   │   ├── index.ts
│   │   ├── kv.ts
│   │   ├── sync-record.ts
│   │   └── use-storage.ts
│   ├── sync/
│   │   ├── core/
│   │   │   ├── merge-utils.test.ts
│   │   │   └── merge-utils.ts
│   │   ├── decision/
│   │   │   ├── base.decider.ts
│   │   │   ├── has-folder-content-changed.ts
│   │   │   ├── sync-decision.interface.ts
│   │   │   ├── two-way.decider.function.ts
│   │   │   └── two-way.decider.ts
│   │   ├── index.ts
│   │   ├── tasks/
│   │   │   ├── adapter-tasks.test.ts
│   │   │   ├── clean-record.task.ts
│   │   │   ├── conflict-resolve.task.ts
│   │   │   ├── filename-error.task.ts
│   │   │   ├── mkdir-local.task.ts
│   │   │   ├── mkdir-remote.task.ts
│   │   │   ├── mkdirs-remote.task.ts
│   │   │   ├── noop.task.ts
│   │   │   ├── pull.task.ts
│   │   │   ├── push.task.ts
│   │   │   ├── remove-local.task.ts
│   │   │   ├── remove-remote-recursively.task.ts
│   │   │   ├── remove-remote.task.ts
│   │   │   ├── skipped.task.ts
│   │   │   └── task.interface.ts
│   │   └── utils/
│   │       ├── has-ignored-in-folder.ts
│   │       ├── is-mergeable-path.ts
│   │       ├── merge-mkdir-tasks.ts
│   │       ├── merge-remove-remote-tasks.ts
│   │       ├── update-records.test.ts
│   │       └── update-records.ts
│   ├── types/
│   │   └── obsidian-extended.d.ts
│   ├── utils/
│   │   ├── api-limiter.ts
│   │   ├── apply-deltas-to-stats.ts
│   │   ├── breakable-sleep.ts
│   │   ├── config-dir-rules.test.ts
│   │   ├── config-dir-rules.ts
│   │   ├── create-id.ts
│   │   ├── decrypt-ticket-response.ts
│   │   ├── deep-stringify.ts
│   │   ├── file-stat-to-stat-model.ts
│   │   ├── format-relative-time.ts
│   │   ├── get-db-key.ts
│   │   ├── get-root-folder-name.ts
│   │   ├── get-task-name.ts
│   │   ├── glob-match.test.ts
│   │   ├── glob-match.ts
│   │   ├── has-invalid-char.ts
│   │   ├── is-503-error.ts
│   │   ├── is-numeric.ts
│   │   ├── is-same-time.ts
│   │   ├── is-sub.ts
│   │   ├── logger.ts
│   │   ├── logs-stringify.ts
│   │   ├── merge-dig-in.ts
│   │   ├── mime/
│   │   │   └── is_markdown_path.ts
│   │   ├── mkdirs-vault.ts
│   │   ├── mkdirs-webdav.ts
│   │   ├── ns-api.ts
│   │   ├── rate-limited-client.ts
│   │   ├── remote-path-to-absolute.ts
│   │   ├── remote-path-to-local-path.ts
│   │   ├── request-url.ts
│   │   ├── sha256.ts
│   │   ├── sleep.ts
│   │   ├── stat-vault-item.ts
│   │   ├── stat-webdav-item.ts
│   │   ├── std-remote-path.ts
│   │   ├── traverse-local-vault.ts
│   │   ├── traverse-webdav.ts
│   │   ├── types.ts
│   │   ├── uint8array-to-arraybuffer.ts
│   │   ├── vault-adapter-utils.test.ts
│   │   └── wait-until.ts
│   ├── views/
│   │   └── chatbox.view.ts
│   └── webdav-patch.ts
├── test/
│   └── mocks/
│       └── obsidian.ts
├── tsconfig.json
├── uno.config.ts
├── version-bump.mjs
├── versions.json
└── vitest.config.ts

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/workflows/changelog.yml
================================================
name: Generate Changelog

on:
  push:
    tags:
      - "*"

permissions:
  contents: write

jobs:
  generate_changelog:
    runs-on: ubuntu-latest
    if: ${{ !contains(github.event.head_commit.message, '[skip ci]') }}

    steps:
      - name: Checkout Code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Set up Git user
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"

      - name: Get release context
        id: release_context
        shell: bash
        run: |
          set -euo pipefail

          CURRENT_TAG=${GITHUB_REF#refs/tags/}
          PREVIOUS_TAG=$(git tag --sort=-v:refname | grep -A 1 "^${CURRENT_TAG}$" | tail -n 1 || true)

          if [ -n "$PREVIOUS_TAG" ] && [ "$PREVIOUS_TAG" != "$CURRENT_TAG" ]; then
            COMMIT_RANGE="${PREVIOUS_TAG}..${CURRENT_TAG}"
            echo "Collecting commits from ${COMMIT_RANGE}"
          else
            COMMIT_RANGE="HEAD~20..HEAD"
            echo "No previous tag found. Falling back to ${COMMIT_RANGE}"
          fi

          COMMIT_LOG=$(git log "$COMMIT_RANGE" --pretty=format:"- %s" --no-merges | grep -E "^- (feat|fix|refactor)(\(.+\))?:" || true)

          echo "current_tag=$CURRENT_TAG" >> "$GITHUB_OUTPUT"
          echo "previous_tag=$PREVIOUS_TAG" >> "$GITHUB_OUTPUT"
          echo "commit_range=$COMMIT_RANGE" >> "$GITHUB_OUTPUT"
          echo "commits<<EOF" >> "$GITHUB_OUTPUT"
          printf '%s\n' "$COMMIT_LOG" >> "$GITHUB_OUTPUT"
          echo "EOF" >> "$GITHUB_OUTPUT"

          echo "Raw commits fetched:"
          printf '%s\n' "$COMMIT_LOG"

      - name: Generate changelog with Gemini
        id: ai_changelog
        if: steps.release_context.outputs.commits != ''
        env:
          GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
          COMMIT_MESSAGES: ${{ steps.release_context.outputs.commits }}
        shell: bash
        run: |
          set -euo pipefail

          MODEL="gemini-3-flash-preview"
          MAX_RETRIES=3
          RETRY_DELAY=5
          SUCCESS=false

          SYSTEM_PROMPT=$(cat <<'EOF'
          You generate release changelog entries from git commits.
          Output only Markdown bullet points.
          Requirements:
          - Write Chinese first, then English in the same bullet.
          - Focus on user-facing changes, features, fixes, and important refactors.
          - Group related commits into concise bullets.
          - Do not invent changes not present in the commits.
          - Do not include headings, introductions, or code fences.
          - Keep the output suitable for CI logs and CHANGELOG.md.
          EOF
          )

          COMMIT_LINES=$(printf '%s\n' "$COMMIT_MESSAGES" | grep -c '^- ' || true)
          if [ "$COMMIT_LINES" -le 0 ]; then
            echo "No eligible commit lines found."
            exit 0
          fi

          MAX_OUTPUT_TOKENS=$((500 + (COMMIT_LINES * 80)))
          if [ "$MAX_OUTPUT_TOKENS" -gt 4096 ]; then
            MAX_OUTPUT_TOKENS=4096
          fi

          for ATTEMPT in $(seq 1 "$MAX_RETRIES"); do
            echo "Attempt $ATTEMPT of $MAX_RETRIES"

            JSON_PAYLOAD=$(jq -n \
              --arg system_prompt "$SYSTEM_PROMPT" \
              --arg commit_messages "$COMMIT_MESSAGES" \
              --argjson max_output_tokens "$MAX_OUTPUT_TOKENS" \
              '{
                system_instruction: {
                  parts: [
                    { text: $system_prompt }
                  ]
                },
                contents: [
                  {
                    role: "user",
                    parts: [
                      {
                        text: ("Commit messages:\n\n" + $commit_messages)
                      }
                    ]
                  }
                ],
                generationConfig: {
                  maxOutputTokens: $max_output_tokens,
                  topP: 0.95,
                  thinkingConfig: {
                    thinkingBudget: 0
                  }
                },
                safetySettings: [
                  {
                    category: "HARM_CATEGORY_DANGEROUS_CONTENT",
                    threshold: "BLOCK_NONE"
                  }
                ]
              }')

            API_ENDPOINT="https://generativelanguage.googleapis.com/v1beta/models/${MODEL}:generateContent"

            HTTP_CODE=$(curl -sS -o gemini_response.json -w "%{http_code}" \
              -X POST "$API_ENDPOINT" \
              -H "x-goog-api-key: ${GEMINI_API_KEY}" \
              -H "Content-Type: application/json" \
              --data "$JSON_PAYLOAD")

            echo "Gemini HTTP status: $HTTP_CODE"
            echo "Gemini Raw Response:"
            cat gemini_response.json

            if [ "$HTTP_CODE" -lt 200 ] || [ "$HTTP_CODE" -ge 300 ]; then
              echo "Gemini API returned non-2xx status."
              sleep "$RETRY_DELAY"
              continue
            fi

            ERROR_MSG=$(jq -r '.error.message // empty' gemini_response.json)
            if [ -n "$ERROR_MSG" ]; then
              echo "API Error: $ERROR_MSG"
              sleep "$RETRY_DELAY"
              continue
            fi

            GENERATED_TEXT=$(jq -r '[.candidates[0].content.parts[]? | select(has("text")) | .text] | join("\n")' gemini_response.json | sed '/^[[:space:]]*$/d')
            FINISH_REASON=$(jq -r '.candidates[0].finishReason // empty' gemini_response.json)
            THOUGHTS_TOKENS=$(jq -r '.usageMetadata.thoughtsTokenCount // 0' gemini_response.json)

            echo "Finish reason: ${FINISH_REASON:-<empty>}"
            echo "Thought tokens: $THOUGHTS_TOKENS"

            if [ -z "$GENERATED_TEXT" ]; then
              echo "Empty response from Gemini."
              sleep "$RETRY_DELAY"
              continue
            fi

            if [ "$FINISH_REASON" = "MAX_TOKENS" ]; then
              echo "Gemini output was truncated by MAX_TOKENS; retrying."
              sleep "$RETRY_DELAY"
              continue
            fi

            echo "Generated Changelog Text:"
            printf '%s\n' "$GENERATED_TEXT"

            {
              echo "changelog_entry<<EOF"
              printf '%s\n' "$GENERATED_TEXT"
              echo "EOF"
            } >> "$GITHUB_OUTPUT"

            SUCCESS=true
            break
          done

          if [ "$SUCCESS" != "true" ]; then
            echo "Failed to generate changelog after ${MAX_RETRIES} attempts."
            exit 1
          fi

      - name: Update CHANGELOG.md
        if: steps.ai_changelog.outputs.changelog_entry != ''
        env:
          GENERATED_CONTENT: ${{ steps.ai_changelog.outputs.changelog_entry }}
        shell: bash
        run: |
          set -euo pipefail

          CHANGELOG_FILE="CHANGELOG.md"
          UNRELEASED_HEADING="## [Unreleased]"

          if [ ! -f "$CHANGELOG_FILE" ]; then
            cat > "$CHANGELOG_FILE" <<'EOF'
          # Changelog

          All notable changes to this project will be documented in this file.

          ## [Unreleased]
          EOF
          fi

          if grep -Fq "$UNRELEASED_HEADING" "$CHANGELOG_FILE"; then
            awk -v unreleased_heading="$UNRELEASED_HEADING" -v generated_content="$GENERATED_CONTENT" '
              BEGIN { inserted = 0 }
              {
                print
                if (!inserted && $0 == unreleased_heading) {
                  print ""
                  print generated_content
                  inserted = 1
                }
              }
            ' "$CHANGELOG_FILE" > temp_changelog.md
          else
            awk -v unreleased_heading="$UNRELEASED_HEADING" -v generated_content="$GENERATED_CONTENT" '
              NR <= 3 { print; next }
              NR == 4 {
                print ""
                print unreleased_heading
                print ""
                print generated_content
                print ""
              }
              { print }
            ' "$CHANGELOG_FILE" > temp_changelog.md
          fi

          mv temp_changelog.md "$CHANGELOG_FILE"
          echo "CHANGELOG.md updated."

      - name: Commit and push CHANGELOG.md
        if: steps.ai_changelog.outputs.changelog_entry != ''
        shell: bash
        run: |
          set -euo pipefail

          CHANGELOG_FILE="CHANGELOG.md"

          if git diff --quiet -- "$CHANGELOG_FILE"; then
            echo "No changes to ${CHANGELOG_FILE} to commit."
            exit 0
          fi

          git add "$CHANGELOG_FILE"
          git commit -m "chore: update changelog for ${GITHUB_REF#refs/tags/} [skip ci]"
          git push origin HEAD:refs/heads/main


================================================
FILE: .github/workflows/ci.yml
================================================
name: CI

on:
  pull_request:

jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: read
    steps:
      - uses: actions/checkout@v3

      - name: Use Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18.x'
          registry-url: 'https://npm.pkg.github.com'
          scope: '@nutstore'

      - name: Install pnpm
        uses: pnpm/action-setup@v2
        with:
          version: latest

      - name: Install dependencies
        env:
          NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: pnpm install

      - name: Build plugin
        env:
          NS_NSDAV_ENDPOINT: ${{ vars.NS_NSDAV_ENDPOINT }}
          NS_DAV_ENDPOINT: ${{ vars.NS_DAV_ENDPOINT }}
          NUTSTORE_PAT: ${{ secrets.GITHUB_TOKEN }}
          NODE_ENV: production
          NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: pnpm run build

      - name: Check build artifacts
        run: |
          if [ ! -f main.js ] || [ ! -f manifest.json ] || [ ! -f styles.css ]; then
            echo "Error: Required build artifacts not found"
            exit 1
          fi
          echo "Build successful! All required files generated."


================================================
FILE: .github/workflows/release.yml
================================================
name: Release Obsidian plugin

on:
  push:
    tags:
      - '*'

jobs:
  build:
    runs-on: ubuntu-latest
    environment: production
    permissions:
      contents: write
      packages: read
    steps:
      - uses: actions/checkout@v3

      - name: Use Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18.x'
          registry-url: 'https://npm.pkg.github.com'
          scope: '@nutstore'

      - name: Install pnpm
        uses: pnpm/action-setup@v2
        with:
          version: latest

      - name: Build plugin
        env:
          NS_NSDAV_ENDPOINT: ${{ vars.NS_NSDAV_ENDPOINT }}
          NS_DAV_ENDPOINT: ${{ vars.NS_DAV_ENDPOINT }}
          NUTSTORE_PAT: ${{ secrets.GITHUB_TOKEN }}
          NODE_ENV: production
          NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          pnpm install
          pnpm run build

      - name: Package plugin
        run: |
          tag="${GITHUB_REF#refs/tags/}"
          mkdir ${{ github.event.repository.name }}
          cp main.js manifest.json styles.css ${{ github.event.repository.name }}
          zip -r ${{ github.event.repository.name }}-${tag}.zip ${{ github.event.repository.name }}
          tar -czf ${{ github.event.repository.name }}-${tag}.tar.gz ${{ github.event.repository.name }}

      - name: Create release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          tag="${GITHUB_REF#refs/tags/}"

          gh release create "$tag" \
            --title="$tag" \
            --draft \
            main.js manifest.json styles.css \
            ${{ github.event.repository.name }}-${tag}.zip \
            ${{ github.event.repository.name }}-${tag}.tar.gz


================================================
FILE: .github/workflows/update-changelog-version.yml
================================================
name: Update Changelog Version

on:
  release:
    types: [published]

permissions:
  contents: write

jobs:
  update-changelog:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout main branch
        uses: actions/checkout@v4
        with:
          ref: main # Explicitly checkout main branch
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Set up Git user
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"

      - name: Update version in CHANGELOG.md
        run: |
          echo "GITHUB_REF: $GITHUB_REF"
          # Get release version (without 'v' prefix if present)
          VERSION=${GITHUB_REF#refs/tags/}
          echo "After removing refs/tags/: $VERSION"
          VERSION=${VERSION#v}
          echo "After removing v prefix: $VERSION"

          echo "Current content before replacement:"
          cat CHANGELOG.md

          # Only replace "Unreleased" in the heading, not in other places
          sed -i "s/## \[Unreleased\]/## [$VERSION]/" CHANGELOG.md

          echo "Content after replacement:"
          cat CHANGELOG.md

          # Check if there are changes
          if git diff --quiet CHANGELOG.md; then
            echo "No changes were made to CHANGELOG.md"
            exit 1
          fi

          # Commit and push changes
          git add CHANGELOG.md
          git commit -m "docs: update changelog version to $VERSION [skip ci]"
          git push origin HEAD:main

          # Update release description with CHANGELOG link
          CHANGELOG_URL="https://github.com/${{ github.repository }}/blob/main/CHANGELOG.md#$VERSION"
          RELEASE_ID=$(jq --raw-output .release.id "$GITHUB_EVENT_PATH")

          # Add CHANGELOG link to release description
          curl \
            -X PATCH \
            -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
            -H "Accept: application/vnd.github.v3+json" \
            "https://api.github.com/repos/${{ github.repository }}/releases/$RELEASE_ID" \
            -d "{
              \"body\": \"📝 View the changelog for this version: $CHANGELOG_URL\"
            }"


================================================
FILE: .gitignore
================================================
# Intellij
*.iml
.idea

# npm
node_modules

# Exclude sourcemaps
*.map

# obsidian
data.json

# Exclude macOS Finder (System Explorer) View States
.DS_Store

# Local
*.local
*.log*

# Environment variables
.env

# build output
dist
styles.css
main.js


================================================
FILE: .prettierrc
================================================
{
	"semi": false,
	"singleQuote": true,
	"trailingComma": "all",
	"useTabs": true
}


================================================
FILE: .swcrc
================================================
{
	"$schema": "https://swc.rs/schema.json",
	"jsc": {
		"parser": {
			"syntax": "ecmascript",
			"jsx": false,
			"dynamicImport": false,
			"privateMethod": false,
			"functionBind": false,
			"exportDefaultFrom": false,
			"exportNamespaceFrom": false,
			"decorators": false,
			"decoratorsBeforeExport": false,
			"topLevelAwait": false,
			"importMeta": false
		},
		"target": "es5",
		"loose": false,
		"externalHelpers": false,
		"keepClassNames": false
	},
	"minify": true
}


================================================
FILE: .vscode/settings.json
================================================
{
	"editor.formatOnSave": true,
	"tailwindCSS.codeActions": false,
	"editor.defaultFormatter": "esbenp.prettier-vscode",

	"editor.codeActionsOnSave": {
		"source.organizeImports": "explicit",
		"source.removeUnusedImports": "explicit"
	},

	"[typescript]": {
		"editor.defaultFormatter": "esbenp.prettier-vscode"
	},

	"[json]": {
		"editor.defaultFormatter": "esbenp.prettier-vscode"
	},

	"[jsonc]": {
		"editor.defaultFormatter": "esbenp.prettier-vscode"
	},

	"[css]": {
		"editor.defaultFormatter": "esbenp.prettier-vscode"
	},

	"[yaml]": {
		"editor.defaultFormatter": "esbenp.prettier-vscode"
	},

	"[markdown]": {
		"editor.defaultFormatter": "esbenp.prettier-vscode"
	},
	"cSpell.words": ["fflate", "jedec", "Mkdirs", "Nutstore", "webdav"],
	"i18n-ally.localesPaths": [
		"src/i18n",
		"src/i18n/locales",
		"packages/webdav-explorer/src/i18n",
		"packages/webdav-explorer/src/i18n/locales"
	]
}


================================================
FILE: CHANGELOG.md
================================================
# Changelog

本项目的所有重要更改都将记录在此文件中。All notable changes to this project will be documented in this file.

## [1.2.1]

- 修复未选择会话时的默认模型应用问题 | Fixed default model application for empty unselected sessions.
- 修复对话模型显示名称记录问题,并确保任务运行使用模型 ID | Fixed chat model display name recording and ensured model IDs are used for task runs.
- 修复用户配置目录过滤规则失效的问题 (#123) | Fixed an issue where user configuration directory filter rules were not being respected (#123).
- 重构 AI 配置为基于记录的结构并支持预设功能 | Refactored AI configuration to a record-based structure with support for presets.
- 新增聊天框功能区 (Ribbon) | Added a new ribbon interface for the chatbox.


## [1.2.0] - 2026-04-28

- 新增 AI 助手主流程与 Agent loop,支持多轮任务执行、会话管理、任务状态展示,以及消息删除、重新生成、召回与复制等交互。 / Added the core AI assistant flow and Agent loop, including multi-step task execution, session management, task status views, and message actions such as delete, regenerate, recall, and copy.
- 新增 AI Provider 配置与管理能力,完善模型与提供商设置结构、必填/选填提示、校验与错误处理,并加入权限确认弹窗与可逆操作保护。 / Added AI provider configuration and management, with reworked model/provider settings, required or optional field indicators, stronger validation and error handling, plus a permission modal and safeguards for reversible operations.
- 新增 Vault Bash 执行环境与相关工具增强,改进 Bash 输出处理、文本内容展示,以及 `collectTreeItems` 的深度和数量限制支持。 / Added a Vault Bash execution environment and improved related tools, including better Bash output handling, clearer text rendering, and support for depth and limit parameters in `collectTreeItems`.
- 新增配置目录同步规则与设置,允许更细致地控制 config 目录同步行为,并补充跨平台适配与基于 Adapter API 的文件系统重构。 / Added config directory sync rules and settings for finer control over config synchronization, along with cross-platform fixes and filesystem refactoring based on the Adapter API.
- 优化聊天与命令界面体验,加入可拖拽输入区、命令按钮图标、聊天消息卡片与历史任务面板,提升 AI 交互可用性。 / Improved the chat and command UI with a resizable input pane, command button icons, chat message cards, and session task panels for a better AI experience.
- 改进同步冲突处理与文件操作能力,引入 DiffMatchPatchOrSkip 策略,并增强本地 Vault 文件操作与搜索路径过滤等底层支持。 / Improved conflict resolution and file operations with the new DiffMatchPatchOrSkip strategy, alongside stronger local vault handling and search path filtering support.

## [1.1.3] - 2026-02-14

- 优化了设置访问的稳定性和错误处理。
- 优化账户同步流程:在同步前增加配置校验,引导用户前往设置页面。
- Improved stability and error handling for settings access.
- Enhanced account sync workflow: Added configuration validation before sync and guided users to settings page.


## [1.1.2] - 2026-02-11

- **新增对 traverseWebDAV 缓存清理的支持**
- **Added support for clearing the traverseWebDAV cache**


## [1.1.1] - 2026-02-10

- 修复:增强了 HTML 实体解码支持,提升了对特殊字符的处理能力。
- Fix: Enhanced HTML entity decoding support, improving special character handling.


## [1.1.0] - 2026-02-05

### 新增功能 / Features
- 新增可恢复的 WebDAV 遍历功能,支持大规模目录树的高效扫描。
- 新增失败任务弹窗,集中展示同步错误信息。
- 新增同步准备事件,提供更细致的同步状态反馈。
- 新增删除确认设置,允许在自动同步时控制是否显示删除确认。
- 新增显示相对时间功能,改善时间显示的可读性。
- 新增更多任务图标,丰富任务类型的视觉反馈。
- 新增文件跳过原因显示(文件大小、被忽略项等),提升同步透明度。
- Added resumable WebDAV traversal for efficient large directory tree scanning.
- Added failed tasks modal to centralize sync error information display.
- Added sync preparing event for more detailed sync status feedback.
- Added delete confirmation setting to control confirmation display during auto-sync.
- Added relative time display for improved time readability.
- Added more task icons to enrich visual feedback for task types.
- Added skip reason display (file size, ignored items, etc.) to improve sync transparency.

### 修复 / Fixes
- 修复同步进度弹窗按钮未定义的问题。
- 修复 FilterEditorModal 描述显示问题。
- 修复文件大小限制判断逻辑。
- 修复 traverseWebDAVKV 异步等待问题。
- 修复 delta 增量获取不完整的问题,确保持续检索直到无更多可用数据。
- 修复节点键值的标准化问题。
- 修复取消检测在确认前的问题。
- 修复可恢复遍历的返回值。
- 修复远程目录创建前的文件名有效性检查。
- Fixed undefined button reference in SyncProgressModal.
- Fixed FilterEditorModal description display issue.
- Fixed file size limit logic.
- Fixed traverseWebDAVKV async await issue.
- Fixed incomplete delta retrieval, ensuring continuous retrieval until no more data is available.
- Fixed node key normalization issue.
- Fixed cancel detection before confirmation.
- Fixed resumable traverse return value.
- Fixed filename validity check before remote directory creation.

### 重构与优化 / Refactoring & Improvements
- 重构并增强 glob 匹配逻辑,改进路径标准化。
- 重构 delta 应用逻辑,新增 applyDeltasToStats 工具函数。
- 移除 delta 缓存键值存储,简化架构。
- 改用 Vault API 进行文件操作,提升稳定性。
- 将语言设置从 Obsidian API 获取改为插件设置中配置。
- Refactored and enhanced glob matching logic with improved path normalization.
- Refactored delta application logic and added applyDeltasToStats utility.
- Removed delta cache key-value storage to simplify architecture.
- Switched to Vault API for file operations to improve stability.
- Changed language setting from Obsidian API to plugin settings configuration.


## [1.0.0] - 2025-12-29

- 功能: 分块执行同步任务并新增批量远端操作(批量建目录、递归删除)、覆盖推送与跳过冲突,显著提升大批量同步效率。/ Feature: Execute sync jobs in chunks with new batch remote operations (bulk mkdir, recursive delete), overwrite push, and conflict skipping to speed up large syncs.
- 功能: 扩展 glob 规则和路径判定(Mergeable、Markdown、二进制文件),自动排除 configDir,并支持禁用间隔自动同步,增强策略可控性。/ Feature: Extended glob rules and path detection (mergeable, markdown, binary), auto-exclusion of configDir, and ability to disable interval auto sync for finer control.
- 功能: 新增删除确认弹窗、将同步日志保存到 Vault,并在同步结束时显示 Close 状态,整体提升可用性与反馈。/ Feature: Added delete confirmation modal, saving sync logs to the vault, and showing Close instead of Hidden after sync to improve UX and feedback.
- 修复: 保护忽略文件不被远端删除、修复缓存服务、记录跳过、进度上报与任务分块等问题,保证同步稳定性。/ Fix: Safeguarded ignored files from remote deletion and fixed cache service, record skipping, progress reporting, and chunked task handling to keep sync stable.
- 优化: 使用 `fflate` 压缩缓存、以 SWC 支持 ES5、改进 ArrayBuffer 转换与时长 clamping,提供更快更兼容的运行体验。/ Improvement: Switched to `fflate` caching, compile with SWC for ES5 support, and improved ArrayBuffer conversion plus duration clamping for faster, more compatible runtime.

## [0.8.5] - 2025-12-02

- 功能: 允许跳过初始同步确认。/ Feature: Allow skipping initial sync confirmation.
- 修复: 移除无用的卸载服务进程。/ Fix: Remove useless unload service process.
- 优化: 优化记录更新的防抖性能。/ Refactor: Debounce record updates for performance.


## [0.8.4] - 2025-08-06

* **改进:**  实现了可配置的自动同步间隔。
* **修复:**  删除了孤立的记录。
* **内部优化:**  重构了同步决策架构,并添加了全面的 glob 匹配测试;对 `SyncRecord` 类进行了解耦和重构,提升了代码可维护性;改进了 `StatModel` 的类型安全性和修复了相关的类型问题;使用了 `path-browserify` 提升兼容性。
* **Improvements:** Implemented configurable auto-sync interval.
* **Fixes:** Removed orphaned record.
* **Internal Improvements:** Refactored sync decision architecture and added comprehensive glob matching tests; Decoupled and refactored the `SyncRecord` class for improved maintainability; Improved `StatModel` type safety and fixed related type issues; Used `path-browserify` for better compatibility.


## [0.8.3] - 2025-07-21

* 优化二进制文件检测:通过扩展名检查优化了二进制文件的检测。
* Optimized binary file detection: Improved binary file detection with extension checking.


## [0.8.2] - 2025-06-26

* **改进:** 提升了文件处理的稳定性,修复了 `PullTask` 执行方法中的错误。
* **改进:**  改进了 `deepStringify` 函数的错误处理,使其能够更好地处理 `Error` 对象。
* **Improvements:** Improved file handling stability, fixing errors in the `PullTask` execution method.
* **Improvements:** Improved error handling in the `deepStringify` function to better manage `Error` objects.


## [0.8.1] - 2025-06-25

* **改进与修复:**
    * 更新了文件检索方法,提高了效率和稳定性。
    * 优化了文件夹创建逻辑,减少了潜在错误。
    * 增强了语言获取方法的健壮性,避免了潜在的运行时错误。
* **Improvements and Fixes:**
    * Updated file retrieval method for improved efficiency and stability.
    * Improved folder creation logic to reduce potential errors.
    * Enhanced robustness of language retrieval method to prevent potential runtime errors.


## [0.8.0] - 2025-06-23

* **改进:**
    * 优化同步流程,避免同步进度条被意外清空。
    * 修复开始同步指令逻辑,使其更可靠。
    * 统一英文翻译大小写格式,提升用户体验。
    * 同步数据库时显示进度条,提升用户感知。
* **底层优化:**
    * 使用 Vault API 重构部分代码,提升效率和稳定性。
    * 使用 `Setting` 组件替换 `h2` 元素,统一设置界面样式。
    * 移除未使用的代码,精简代码库。
    * 使用 `window.clearTimeout` 和 `window.setTimeout` 优化计时器管理。
* **Improvements:**
    * Optimized sync process to prevent unexpected clearing of the progress bar.
    * Fixed the logic of the start sync command for better reliability.
    * Unified capitalization in English translations for improved user experience.
    * Added a progress bar during database synchronization for better user feedback.
* **Under the hood:**
    * Refactored parts of the code using the Vault API for improved efficiency and stability.
    * Replaced `h2` elements with the `Setting` component for consistent settings interface styling.
    * Removed unused code to streamline the codebase.
    * Optimized timer management using `window.clearTimeout` and `window.setTimeout`.


## [0.7.0] - 2025-05-14

*   **特性**
    *   增强智能合并策略,提升冲突解决效率。
    *   新增启动后自动同步选项,允许配置同步延迟。
*   **修复**
    *   为 `updateMtimeInRecord` 方法增加错误处理,提高稳定性。
    *   兼容 1.8.x 及更早版本。
---
*   **Features**
    *   Enhanced intelligent merge strategy for more efficient conflict resolution.
    *   Added an option for automatic synchronization after startup, with configurable delay.
*   **Bug Fixes**
    *   Improved stability of the `updateMtimeInRecord` method by adding error handling.
    *   Ensured compatibility with versions 1.8.x and earlier.

## [0.6.1] - 2025-05-13

*   改进 Glob 匹配逻辑和性能 (重构文件系统结构)
*   Improve glob matching logic and performance (Refactored filesystem structure)

## [0.6.0] - 2025-05-09

*   **新功能**
    *   解码文件路径中的 HTML Entity 编码
    *   添加文件名错误任务,处理不支持的特殊字符
    *   自动同步时不显示通知
    *   添加过滤规则设置,支持包含和排除规则

*   **Features**
    *   Decode HTML entities in file paths
    *   Add task for filename errors to handle unsupported special characters
    *   Suppress notifications during automatic synchronization
    *   Add filter rule settings with support for include and exclude rules

## [0.5.1] - 2025-04-30

* 修复:修复了 NutstorePlugin 类型不存在 'logs' 属性的问题。
* Fixed: Resolved an issue where the 'logs' property was missing from the NutstorePlugin type.

* **功能改进:**
    * 实现了实时同步服务,并添加了相应的设置选项。
    * 添加了 BaseSyncDecision 抽象类以支持同步决策逻辑。
* **错误修复:**
    * 更新了过滤器描述,移除了关于 globstar 的描述。
    * 修复了生成的正则表达式标志,移除了默认的全局标志。
    * 将 configDir 添加到过滤器规则中。
* **Features:**
    * Implemented a real-time synchronization service and added corresponding settings.
    * Added a BaseSyncDecision abstract class to support synchronization decision logic.
* **Bug Fixes:**
    * Updated the filter description, removing the description about globstar.
    * Fixed the generated regular expression flags, removing the default global flag.
    * Added configDir to the filter rules.


## [0.4.2] - 2025-04-28

* 修复:优化实时保存同步记录功能,避免同步大量文件中断后需要重新读写。
* 修复:处理空目录或根目录情况。
* 修复:改进了 WebDAV 连接检查功能,现在可以处理 503 错误并提供相应的通知。
* Fixed: Optimized real-time saving of sync records to prevent rereading and rewriting after interruptions during large file synchronizations.
* Fixed: Handled cases with empty or root directories.
* Fixed: Improved WebDAV connection check to handle 503 errors and provide corresponding notifications.


## [0.4.1] - 2025-04-27

* 修复了首次同步时本地数据会覆盖远程数据的问题,现在会进行合并。
* Fixed an issue where local data would overwrite remote data during the initial synchronization. Now, the data will be merged.


## [0.4.0] - 2025-04-25

* 可以配置跳过大文件,避免 OOM;同步进度窗口可以取消同步和隐藏窗口;可选择性清除缓存。
* 串行保存 blob 数据,日志持久化。
* Configure skip large files to avoid OOM; The sync progress window can cancel sync and hide the window; Selectable cache clearing modal.
* Serialize blob saving; Logs are now persistent.


## [0.3.2] - 2025-04-23

* 恢复同步记录后显示同步完成提示。
* 完善了同步记录功能,自动补充缺失文件夹的同步记录。
* 新增内存文件系统。
* 新增同步完成标记功能。
* 新增同步进度弹窗。
* 新增同步和终止命令。
* 优化了同步机制,包括可中断的 503 重试机制和睡眠函数,修复了大量任务并发读取文件时闪退的问题。
* Synchronization complete message is now displayed after synchronization records are restored.
* Enhanced synchronization record functionality by automatically adding missing folder records.
* Implemented an in-memory file system (memfs).
* Added a synchronization completion marker.
* Added a synchronization progress popup.
* Added commands for starting and stopping synchronization.
* Improved synchronization mechanism with interruptible 503 retry and sleep functions, fixing the crash issue when concurrently reading files with a large number of tasks.


## [0.3.1] - 2025-04-21

* 修复:
    * 仅导出当前 vault 的缓存
    * 修复 delta 响应中的类型解析错误
* 功能:
    * 使用标准远程路径处理选择的远程路径,确保路径一致性
    * 添加空操作任务以优化任务执行流程
    * 添加松散同步模式,跳过同名且大小相同的文件
* Bug fixes:
    * Only export the cache of the current vault.
    * Fixed a type parsing error in delta responses.
* Features:
    * Use standardized remote paths to ensure path consistency.
    * Added a no-op task to optimize task execution flow.
    * Added a loose synchronization mode to skip files with the same name and size.


## [0.3.0] - 2025-04-18

* **功能改进:**
    * 实现了 Indexed DB 缓存数据的导入导出功能,并支持保存到坚果云盘。
    * 使用图标代替了选择文件夹的文本。
    * 添加了日志界面。
* **问题修复:**
    * 修复了 stringify 导致的错误。
* **其他改进:**
    * 为生产模式添加了日志记录功能。
    * 将设置模块重构为类。
* **Features:**
    * Implemented import and export of Indexed DB cache data, with support for saving to Nutstore Cloud.
    * Replaced folder selection text with an icon.
    * Added a log interface.
* **Bug Fixes:**
    * Fixed an error caused by stringify.
* **Other Improvements:**
    * Added logging functionality for production mode.
    * Refactored the settings module as a class.


## [0.2.3] - 2025-04-14

* 修复相对路径处理逻辑
* 为过滤器添加 flag

* fix relative path bug
* allow config flag for filter


## [0.2.2] - 2025-04-10

*   修复了部分旧环境下的兼容性问题 (通过 polyfill 数组方法)。
*   修复了导致移动端无法同步的问题。

*   Fixed compatibility issues in some older environments (by polyfilling array methods).
*   Fixed an issue preventing synchronization on mobile devices.


## [0.2.1] - 2025-04-10

*   修正了相对路径的处理。

*   Corrected handling of relative paths. 

## [0.2.0] - 2025-04-09

*   简化了登录流程。
*   增加了自定义过滤功能。
*   支持自定义请求 URL。
*   增加了当同步任务过多时建议使用客户端的提示信息。
*   修复了 iOS 设备上无法通过浏览器进行 SSO 登录的问题。
*   修复了数值可能以科学记数法 (eNotation) 显示的问题。
*   更新了冲突解决策略的描述,增加了备份建议。
*   调整了差异匹配阈值。
*   对路径进行了编码以改善处理。

*   Simplified the login process.
*   Added custom filtering capabilities.
*   Added support for custom request URLs.
*   Added a prompt suggesting client use for numerous sync tasks.
*   Fixed an issue preventing SSO login via browser on iOS devices.
*   Fixed an issue where numbers might display in scientific notation (eNotation).
*   Updated conflict resolution strategy descriptions to include a backup recommendation.
*   Adjusted the match threshold for diffs.
*   Encoded paths for improved handling.

## [0.1.0] - 2025-04-03

*   为冲突解决策略描述添加了备份建议。
*   改进了手动登录帮助链接的结构。
*   禁用了数字显示的科学计数法 (eNotation)。
*   更新了单点登录 (SSO) 组件 (使用 `@nutstore/sso-js`)。

*   Added backup recommendation to conflict resolution strategy descriptions.
*   Improved the structure of the manual login help link.
*   Disabled scientific notation (eNotation) for number display.
*   Updated the Single Sign-On (SSO) component (using `@nutstore/sso-js`).

## [0.0.7] - 2025-03-28

*   新增:执行同步任务前增加确认步骤,通过包含说明文字的新弹窗进行确认。
*   新增:添加 `confirmBeforeSync` 设置项,用于控制是否在同步前进行确认。
*   改进:文件列表(FileList)现在可以同时显示文件和文件夹。
*   改进:为远程目录创建过程中遇到的错误添加了通知提示。
*   优化:优化了同步流程(包括远程目录存在性检查和记录清理)。

*   Added a confirmation step before executing sync tasks, shown in a new modal with instructions.
*   Added a `confirmBeforeSync` setting to control the sync confirmation behavior.
*   Updated FileList to display both files and folders.
*   Added notifications for errors during remote directory creation.
*   Optimized the synchronization process (includes remote directory checks and record cleanup).

## [0.0.6] - 2025-03-25

*   提高了获取目录内容时的可靠性,增加了 API 速率限制和针对临时服务器错误 (503) 的自动重试机制。
*   Improved reliability when fetching directory contents by adding API rate limiting and automatic retries for temporary server errors (503).

## [0.0.5] - 2025-03-21

*   修复:创建新文件夹后自动刷新列表。
*   功能:更新了坚果云单点登录(SSO)支持。

*   Fix: Refresh list automatically after creating a new folder.
*   Feature: Updated Nutstore Single Sign-On (SSO) support.

## [0.0.4] - 2025-03-13

*   更新了单点登录 (SSO) 功能。
*   Updated Single Sign-On (SSO) functionality.

## [0.0.3] - 2025-03-13

*   **同步核心与进度**
    *   新增 同步状态管理、进度百分比显示、完成状态(含失败计数)和同步按钮视觉反馈。
    *   新增 同步取消/停止功能。
    *   新增 SSO(单点登录)用户界面。
    *   新增 同步确认对话框及风险提示。
    *   新增 在本地创建文件夹时,在远端也创建对应文件夹。
    *   新增 同步任务失败时的本地化错误信息。
    *   新增 对二进制文件进行哈希比较。
    *   新增 针对 503 错误的重试机制。
    *   优化 远程基础目录 (`remoteBaseDir`) 回退使用仓库名称。
    *   优化 调整了 API 请求频率限制以提高稳定性。
    *   修复 同步动画旋转方向错误。
    *   修复 从正确的 `remoteBaseDir` 开始遍历文件。
    *   修复 获取目录内容以正确处理服务器基础路径。
*   **冲突处理**
    *   新增 冲突处理策略可选。
    *   新增 冲突标记(支持 Git 风格及自定义),并保留原始内容格式。
    *   新增 跳过空文件冲突。
    *   优化 冲突解决支持可选的本地和远程文件状态信息。
*   **文件处理**
    *   新增 文件属性中包含文件大小。
    *   新增 获取目录内容支持分页。
    *   修复 处理文件系统中的空文件状态。
*   **其他**
    *   新增 插件图标。
    *   新增 中英文文档及同步流程图。
    *   修复 文本自动换行问题。
    *   更新 插件名称。

*   **Sync Core & Progress**
    *   Added sync state management, progress percentage display, completion status (with failed count), and visual feedback for the sync button.
    *   Added sync cancellation/stop functionality.
    *   Added SSO (Single Sign-On) user interface.
    *   Added sync confirmation dialog and risk warning.
    *   Added remote folder creation when a local folder is created.
    *   Added localized error messages for sync task failures.
    *   Added hash comparison for binary files.
    *   Added retry mechanism for 503 errors.
    *   Improved `remoteBaseDir` to use the vault name as a fallback.
    *   Adjusted API rate limiting parameters for better stability.
    *   Fixed sync animation rotation direction.
    *   Fixed walking from the correct `remoteBaseDir`.
    *   Fixed `getDirectoryContents` to handle server base paths correctly.
*   **Conflict Handling**
    *   Added selectable conflict resolution strategies.
    *   Added conflict markers (supporting Git style and customization), preserving original content formatting.
    *   Added skipping of blank file conflicts.
    *   Improved conflict resolution to support optional local and remote file stats.
*   **File Handling**
    *   Added file size to file properties.
    *   Added pagination support for getting directory contents.
    *   Fixed handling of empty file stats in the file system.
*   **Other**
    *   Added plugin icons.
    *   Added English and Chinese documentation, including a sync flowchart.
    *   Fixed automatic word wrapping issues.
    *   Updated plugin name.

## [0.0.2] - 2025-03-07

*   **WebDAV:**
    *   新增 WebDAV 文件浏览器功能。
    *   为 WebDAV 配置添加远程基础目录选择器。
    *   支持通过环境变量配置 WebDAV。
    *   提升 WebDAV 可靠性与性能(改进令牌处理、避免重复创建目录、修复 `nextLink` 解码问题)。
*   **用户界面与体验:**
    *   移除同步模态框(SyncModal)组件。
    *   改进移动端适配。
    *   更新坚果云(Nutstore)设置界面。
    *   统一界面文本的大小写。
*   **其他:**
    *   为中文用户添加了帮助说明。
    *   修复了访问 `configDir` 中配置值的问题。

*   **WebDAV:**
    *   Added a WebDAV file explorer feature.
    *   Added a remote base directory selector for WebDAV configuration.
    *   Enabled WebDAV configuration via environment variables.
    *   Enhanced WebDAV reliability and performance (improved token handling, avoided duplicate mkdir, fixed `nextLink` decoding).
*   **User Interface & Experience:**
    *   Removed the SyncModal component.
    *   Improved mobile adaptability.
    *   Updated the Nutstore Setting Tab UI.
    *   Standardized capitalization in UI text.
*   **Other:**
    *   Added Chinese help documentation (`help` for zh).
    *   Fixed accessing configured value from `configDir`.

## [0.0.1] - 2025-02-26

*   新增 WebDAV 及本地文件同步功能,包括文件和文件夹的遍历、创建、删除(支持递归删除)以及基础的冲突解决机制。
*   改进同步冲突处理:增加解决策略,支持跳过空文件冲突,并在解决后更新记录。
*   增强同步用户体验:
    *   增加同步状态管理、进度百分比显示、加载动画(修复了旋转方向)及完成后的失败任务计数。
    *   增加同步过程中的通知提示和本地化错误信息。
    *   添加取消/停止同步按钮。
    *   优化了同步状态的 UI 显示并添加了图标。
*   引入国际化 (i18n) 支持和语言切换功能。
*   添加 SSO (单点登录) 相关界面(后已隐藏)。
*   优化同步设置:远程目录将回退使用仓库名称。
*   修复了同步中处理服务器基本路径、空文件统计信息等问题。

*   Added basic file synchronization for WebDAV and local vaults, including traversal, creation, deletion (with recursive support), and basic conflict resolution.
*   Improved sync conflict handling: added resolution strategies, support for skipping blank file conflicts, and record updates after resolution.
*   Enhanced sync user experience:
    *   Added sync state management, progress percentage display, loading animation (fixed rotation direction), and failed task count on completion.
    *   Added notifications during sync and localized error messages.
    *   Added a cancel/stop sync button.
    *   Improved the sync status UI and added icons.
*   Introduced internationalization (i18n) support and language switching functionality.
*   Added SSO (Single Sign-On) related UI (later hidden).
*   Improved sync setup: Remote base directory now falls back to using the vault name.
*   Fixed issues related to handling server base paths, empty file stats, etc., during synchronization.


================================================
FILE: LICENSE
================================================
                    GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU Affero General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software.  This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time.  Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source.  For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code.  There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

================================================
FILE: README.md
================================================
# 🔄 Nutstore Sync

## 简介 | Introduction

此插件允许您通过 WebDAV 协议将 Obsidian 笔记与坚果云进行双向同步。
_This plugin enables two-way synchronization between Obsidian notes and Nutstore via WebDAV protocol._

---

## ✨ 主要特性 | Key Features

- 🔄 **双向同步 | Two-way Sync**
  高效地在多设备间同步笔记。
  _Efficiently synchronize your notes across devices._
- ⚡ **增量同步 | Incremental Sync**
  只传输更改过的文件,使大型笔记库也能快速同步。
  _Fast updates that only transfer changed files, making large vaults sync quickly._
- 🔐 **单点登录 | Single Sign-On**
  通过简单授权连接坚果云,无需手动输入 WebDAV 凭据。
  _Connect to Nutstore with simple authorization instead of manually entering WebDAV credentials._
- 📁 **WebDAV 文件浏览器 | WebDAV Explorer**
  远程文件管理的可视化界面。
  _Visual file browser for remote file management._
- 🔀 **智能冲突解决 | Smart Conflict Resolution**
  字符级比较自动合并可能的更改;支持基于时间戳的解决方案(最新文件优先)。
  _Character-level comparison to automatically merge changes when possible. Option to use timestamp-based resolution (newest file wins)._
- 🚀 **宽松同步模式 | Loose Sync Mode**
  优化对包含数千笔记的仓库的性能。
  _Optimize performance for vaults with thousands of notes._
- 📦 **大文件处理 | Large File Handling**
  设置大小限制以跳过大文件,提升性能。
  _Set size limits to skip large files for better performance._
- 📊 **同步状态跟踪 | Sync Status Tracking**
  清晰的同步进度和完成提示。
  _Clear visual indicators of sync progress and completion._
- 📝 **详细日志 | Detailed Logging**
  全面的故障排查日志。
  _Comprehensive logs for troubleshooting._
- 🤖 **AI 智能助手 | AI Agent**
  内置 AI 助手,可通过自然语言读取、编辑和管理 Vault 中的文件。
  _Built-in AI assistant that can read, edit, and manage files in your vault through natural language._

---

## 🤖 AI 智能助手 | AI Agent

AI 助手是一个内置的智能代理,让你通过自然语言管理 Obsidian Vault。支持任意兼容 OpenAI 接口的服务商,可自主完成复杂的多步骤任务。
_The AI Agent is a built-in assistant that lets you manage your Obsidian vault through natural language. It supports any OpenAI-compatible provider and can handle complex, multi-step tasks autonomously._

Agent 在做出任何更改前都会请求用户确认。你可以逐条批准、按操作类型批准当前会话,或在设置中开启 *YOLO 模式* 全部自动通过。
_Before the agent makes any changes, it asks for your approval. You can approve individual operations, approve an operation type for the entire session, or enable _YOLO mode_ in settings to auto-approve everything._

**配置方法 | Setup:**

1. 打开插件设置 → **AI** 标签页
   _Open plugin settings → **AI** tab_
2. 添加 AI 服务商(支持任意兼容 OpenAI 接口的端点)并填写模型名称
   _Add an AI provider (any OpenAI-compatible endpoint) and fill in the model name_
3. 从左侧边栏打开 AI 对话框,开始对话
   _Open the AI chat panel from the left sidebar and start chatting_

---

## ⚠️ 注意事项 | Important Notes

- ⏳ **首次同步 | Initial Sync**
  首次同步可能需要较长时间(文件比较多时)。
  _Initial sync may take longer (especially with many files)._
- 💾 **数据备份 | Backup**
  请在同步之前备份。
  _Please backup before syncing._


================================================
FILE: esbuild.config.mjs
================================================
import postcss from '@deanc/esbuild-plugin-postcss'
import UnoCSS from '@unocss/postcss'
import dotenv from 'dotenv'
import esbuild from 'esbuild'
import fs, { readFileSync } from 'fs'
import postcssMergeRules from 'postcss-merge-rules'
import process from 'process'

const pkgJson = JSON.parse(readFileSync('./package.json', 'utf-8'))
dotenv.config()

const prod = process.argv[2] === 'production'

const renamePlugin = {
	name: 'rename-plugin',
	setup(build) {
		build.onEnd(async () => {
			const source = prod ? './dist/main.css' : './main.css'
			if (fs.existsSync(source)) {
				fs.renameSync(source, './styles.css')
			}
		})
	},
}

const context = await esbuild.context({
	entryPoints: ['src/index.ts'],
	bundle: true,
	external: [
		'obsidian',
		'electron',
		'@codemirror/autocomplete',
		'@codemirror/collab',
		'@codemirror/commands',
		'@codemirror/language',
		'@codemirror/lint',
		'@codemirror/search',
		'@codemirror/state',
		'@codemirror/view',
		'@lezer/common',
		'@lezer/highlight',
		'@lezer/lr',
	],
	define: {
		'process.env.NS_NSDAV_ENDPOINT': JSON.stringify(
			process.env.NS_NSDAV_ENDPOINT,
		),
		'process.env.NS_DAV_ENDPOINT': JSON.stringify(process.env.NS_DAV_ENDPOINT),
		'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || ''),
		'process.env.PLUGIN_VERSION': JSON.stringify(pkgJson.version),
	},
	format: 'cjs',
	target: 'es2018',
	logLevel: 'info',
	sourcemap: prod ? false : 'inline',
	treeShaking: true,
	outfile: prod ? 'dist/main.js' : 'main.js',
	minify: prod,
	platform: 'browser',
	plugins: [
		postcss({
			plugins: [UnoCSS(), postcssMergeRules()],
		}),
		renamePlugin,
	],
	alias: {
		'node:zlib': './src/shims/node-zlib.ts',
	},
})

if (prod) {
	await context.rebuild()
	process.exit(0)
} else {
	await context.watch()
}


================================================
FILE: manifest.json
================================================
{
	"id": "nutstore-sync",
	"name": "Nutstore Sync",
	"version": "1.2.1",
	"minAppVersion": "0.15.0",
	"description": "Sync your vault with Nutstore/坚果云 using WebDAV protocol.",
	"author": "nutstore",
	"authorUrl": "https://github.com/nutstore",
	"isDesktopOnly": false
}


================================================
FILE: package.json
================================================
{
	"name": "obsidian-nutstore-sync",
	"version": "1.2.1",
	"main": "main.js",
	"scripts": {
		"dev": "run-p dev:*",
		"dev:plugin": "node esbuild.config.mjs",
		"dev:chatbox": "pnpm --filter chatbox dev",
		"dev:webdav-explorer": "pnpm --filter webdav-explorer dev",
		"build": "run-s build:webdav-explorer build:chatbox build:plugin",
		"build:chatbox": "pnpm --filter chatbox build",
		"build:webdav-explorer": "pnpm --filter webdav-explorer build",
		"build:plugin": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production && swc ./dist/main.js -o main.js",
		"version": "node version-bump.mjs && git add manifest.json versions.json",
		"test": "vitest"
	},
	"devDependencies": {
		"@ai-sdk/openai": "^3.0.48",
		"@deanc/esbuild-plugin-postcss": "^1.0.2",
		"@electron/remote": "^2.1.2",
		"@nutstore/sso-js": "^0.0.8",
		"@swc/cli": "^0.7.9",
		"@swc/core": "^1.15.6",
		"@types/diff-match-patch": "^1.0.36",
		"@types/glob-to-regexp": "^0.4.4",
		"@types/lodash-es": "^4.17.12",
		"@types/node": "^16.11.6",
		"@types/path-browserify": "^1.0.3",
		"@types/ramda": "^0.30.2",
		"@typescript-eslint/eslint-plugin": "5.29.0",
		"@typescript-eslint/parser": "5.29.0",
		"@unocss/postcss": "66.1.0-beta.3",
		"@vitest/coverage-v8": "^3.1.2",
		"ai": "^6.0.149",
		"assert": "^2.1.0",
		"async-mutex": "^0.5.0",
		"blob-polyfill": "^9.0.20240710",
		"bottleneck": "^2.19.5",
		"buffer": "^6.0.3",
		"builtin-modules": "3.3.0",
		"bytes-iec": "^3.1.1",
		"chatbox": "workspace: *",
		"consola": "^3.4.0",
		"core-js": "^3.41.0",
		"crypto-browserify": "^3.12.1",
		"diff-match-patch": "^1.0.5",
		"dotenv": "^16.4.7",
		"esbuild": "0.17.3",
		"esbuild-sass-plugin": "^3.3.1",
		"fast-xml-parser": "^4.5.1",
		"fflate": "^0.8.2",
		"glob-to-regexp": "^0.4.1",
		"hash-wasm": "^4.12.0",
		"html-entities": "^2.6.0",
		"http-status-codes": "^2.3.0",
		"i18next": "^24.2.2",
		"js-base64": "^3.7.7",
		"just-bash": "^2.14.0",
		"localforage": "^1.10.0",
		"lodash-es": "^4.17.21",
		"node-diff3": "^3.1.2",
		"npm-run-all2": "^7.0.2",
		"obsidian": "latest",
		"ohash": "^1.1.4",
		"path-browserify": "^1.0.1",
		"postcss-merge-rules": "^7.0.4",
		"prettier": "^3.5.0",
		"ramda": "^0.30.1",
		"rxjs": "^7.8.1",
		"stream-browserify": "^3.0.0",
		"superjson": "^2.2.2",
		"tslib": "2.4.0",
		"typescript": "^5.9.3",
		"unocss": "66.1.0-beta.3",
		"uuid": "^13.0.0",
		"vitest": "^3.1.2",
		"webdav": "^5.7.1",
		"webdav-explorer": "workspace: *",
		"zod": "^4.3.6"
	},
	"browser": {
		"path": "path-browserify",
		"stream": "stream-browserify",
		"buffer": "buffer",
		"crypto": "crypto-browserify"
	}
}

================================================
FILE: packages/chatbox/package.json
================================================
{
	"name": "chatbox",
	"version": "0.0.0",
	"type": "module",
	"exports": {
		".": {
			"types": "./dist/index.d.ts",
			"import": "./dist/index.js"
		}
	},
	"module": "./dist/index.js",
	"types": "./dist/index.d.ts",
	"files": [
		"dist"
	],
	"scripts": {
		"build": "rslib build",
		"dev": "rslib build --watch"
	},
	"devDependencies": {
		"@rsbuild/plugin-babel": "^1.0.4",
		"@rsbuild/plugin-solid": "^1.0.5",
		"@rslib/core": "^0.5.3",
		"@solid-primitives/i18n": "^2.2.0",
		"@solid-primitives/media": "^2.3.0",
		"@unocss/postcss": "66.1.0-beta.3",
		"typescript": "^5.8.2",
		"unocss": "66.1.0-beta.3"
	},
	"dependencies": {
		"solid-js": "^1.9.5"
	}
}


================================================
FILE: packages/chatbox/postcss.config.mjs
================================================
import UnoCSS from '@unocss/postcss'

export default {
	plugins: [UnoCSS()],
}


================================================
FILE: packages/chatbox/rslib.config.ts
================================================
import { pluginBabel } from '@rsbuild/plugin-babel'
import { pluginSolid } from '@rsbuild/plugin-solid'
import { defineConfig } from '@rslib/core'

export default defineConfig({
	source: {
		entry: {
			index: ['./src/**'],
		},
	},
	tools: {
		rspack: {
			plugins: [],
		},
	},
	lib: [
		{
			bundle: false,
			dts: true,
			format: 'esm',
		},
	],
	output: {
		target: 'web',
	},
	plugins: [
		pluginBabel({
			include: /\.(?:jsx|tsx)$/,
		}),
		pluginSolid(),
	],
})


================================================
FILE: packages/chatbox/src/App.tsx
================================================
import {
	For,
	Match,
	Show,
	Switch,
	createEffect,
	createSignal,
	onCleanup,
} from 'solid-js'
import { ConfirmDialog } from './components/ConfirmDialog'
import { FragmentDivider } from './components/FragmentDivider'
import { MessageCard } from './components/MessageCard'
import { PaneResizer } from './components/PaneResizer'
import { PendingList } from './components/PendingList'
import { RunStateCard } from './components/RunStateCard'
import { SessionHistoryItem } from './components/SessionHistoryItem'
import { TasksPanel } from './components/TasksPanel'
import { t } from './i18n'
import type {
	ChatTimelineFragmentItem,
	ChatTimelineMessageItem,
	ChatboxProps,
} from './types'

export type AppProps = ChatboxProps

const DESKTOP_RESIZE_MEDIA_QUERY = '(pointer: fine) and (min-width: 1024px)'
const INPUT_HEIGHT_STORAGE_KEY = 'nutstore-sync.chatbox.desktop-input-height'
const DEFAULT_DESKTOP_INPUT_HEIGHT = 184
const DESKTOP_INPUT_MIN_HEIGHT = 120
const DESKTOP_INPUT_ABSOLUTE_MIN_HEIGHT = 72
const DESKTOP_MESSAGES_MIN_HEIGHT = 200
const RESIZER_HITBOX_HEIGHT = 10
const DESKTOP_INPUT_MAX_VIEWPORT_RATIO = 0.6

function App(props: AppProps) {
	const [input, setInput] = createSignal('')
	const [isComposing, setIsComposing] = createSignal(false)
	const [historyOpen, setHistoryOpen] = createSignal(false)
	const [tasksOpen, setTasksOpen] = createSignal(false)
	const [modelPickerOpen, setModelPickerOpen] = createSignal(false)
	const [sessionPendingDeleteId, setSessionPendingDeleteId] =
		createSignal<string>()
	const [pendingDeleteMessage, setPendingDeleteMessage] =
		createSignal<ChatTimelineMessageItem>()
	const [pendingRegenerateMessage, setPendingRegenerateMessage] =
		createSignal<ChatTimelineMessageItem>()
	const [pendingRecallMessage, setPendingRecallMessage] =
		createSignal<ChatTimelineMessageItem>()
	const [desktopResizeEnabled, setDesktopResizeEnabled] = createSignal(false)
	const [inputPaneHeight, setInputPaneHeight] = createSignal<number>()
	let messagesEl: HTMLDivElement | undefined
	let splitLayoutEl: HTMLDivElement | undefined
	let inputPaneEl: HTMLDivElement | undefined
	let historyEl: HTMLDivElement | undefined
	let modelPickerEl: HTMLDivElement | undefined
	let previousActiveSessionId = props.activeSessionId
	let defaultDesktopInputHeight = DEFAULT_DESKTOP_INPUT_HEIGHT
	let dragStartHeight = 0

	const hasTasks = () =>
		props.currentSessionTasks.length + props.otherSessionTasks.length > 0
	const runningTaskCount = () =>
		props.currentSessionTasks.filter((task) => task.status === 'running')
			.length +
		props.otherSessionTasks.filter((task) => task.status === 'running').length
	const isBusy = () => props.runState !== 'idle'
	const selectedProvider = () =>
		props.providers.find((provider) => provider.id === props.selectedProviderId)
	const modelPickerLabel = () => {
		const provider = selectedProvider()
		const selectedModel = provider?.models.find(
			(model) => model.id === props.selectedModelId,
		)
		return (
			[provider?.name, selectedModel?.name].filter(Boolean).join('/') ||
			t('noModel')
		)
	}

	function readStoredInputPaneHeight() {
		try {
			const raw = window.localStorage.getItem(INPUT_HEIGHT_STORAGE_KEY)
			if (!raw) {
				return undefined
			}
			const value = Number(raw)
			return Number.isFinite(value) ? value : undefined
		} catch {
			return undefined
		}
	}

	function persistInputPaneHeight(height: number) {
		try {
			window.localStorage.setItem(
				INPUT_HEIGHT_STORAGE_KEY,
				String(Math.round(height)),
			)
		} catch {
			// Ignore storage errors, resize should still work.
		}
	}

	function getMaxInputPaneHeight() {
		const viewportMax = Math.floor(
			window.innerHeight * DESKTOP_INPUT_MAX_VIEWPORT_RATIO,
		)
		const splitHeight = splitLayoutEl?.getBoundingClientRect().height ?? 0
		if (splitHeight <= 0) {
			return Math.max(DESKTOP_INPUT_MIN_HEIGHT, viewportMax)
		}
		const messagesBound = Math.floor(
			splitHeight - DESKTOP_MESSAGES_MIN_HEIGHT - RESIZER_HITBOX_HEIGHT,
		)
		const maxHeight = Math.min(messagesBound, viewportMax)
		return Math.max(DESKTOP_INPUT_ABSOLUTE_MIN_HEIGHT, maxHeight)
	}

	function clampInputPaneHeight(height: number) {
		const maxHeight = getMaxInputPaneHeight()
		const minHeight = Math.min(DESKTOP_INPUT_MIN_HEIGHT, maxHeight)
		return Math.round(Math.min(Math.max(height, minHeight), maxHeight))
	}

	function applyInputPaneHeight(height: number, persist = false) {
		const next = clampInputPaneHeight(height)
		setInputPaneHeight(next)
		if (persist) {
			persistInputPaneHeight(next)
		}
		return next
	}

	function resetInputPaneHeight() {
		if (!desktopResizeEnabled()) {
			return
		}
		applyInputPaneHeight(defaultDesktopInputHeight, true)
	}

	function onInputPaneResizeStart() {
		if (!desktopResizeEnabled()) {
			return
		}
		dragStartHeight =
			inputPaneHeight() ?? clampInputPaneHeight(defaultDesktopInputHeight)
	}

	function onInputPaneResize(deltaY: number) {
		if (!desktopResizeEnabled()) {
			return
		}
		applyInputPaneHeight(dragStartHeight + deltaY)
	}

	function onInputPaneResizeEnd() {
		const height = inputPaneHeight()
		if (typeof height === 'number') {
			persistInputPaneHeight(height)
		}
	}

	function scrollMessagesToBottom(behavior: ScrollBehavior = 'smooth') {
		requestAnimationFrame(() => {
			if (!messagesEl) {
				return
			}
			messagesEl.scrollTo({
				top: messagesEl.scrollHeight,
				behavior,
			})
		})
	}

	createEffect(() => {
		const activeSessionId = props.activeSessionId
		props.timeline.length
		props.currentSessionTasks.length
		props.otherSessionTasks.length
		props.pendingMessages.length
		props.runState
		const behavior =
			previousActiveSessionId !== activeSessionId ? 'auto' : 'smooth'
		previousActiveSessionId = activeSessionId
		scrollMessagesToBottom(behavior)
	})

	createEffect(() => {
		if (!hasTasks() && tasksOpen()) {
			setTasksOpen(false)
		}
	})

	createEffect(() => {
		if (!historyOpen() && !modelPickerOpen()) {
			return
		}

		const onPointerDown = (event: PointerEvent) => {
			const target = event.target
			if (!(target instanceof Node)) {
				return
			}
			if (historyEl?.contains(target) || modelPickerEl?.contains(target)) {
				return
			}
			setHistoryOpen(false)
			setModelPickerOpen(false)
		}

		document.addEventListener('pointerdown', onPointerDown)
		onCleanup(() => document.removeEventListener('pointerdown', onPointerDown))
	})

	createEffect(() => {
		const mediaQuery = window.matchMedia(DESKTOP_RESIZE_MEDIA_QUERY)
		const update = () => setDesktopResizeEnabled(mediaQuery.matches)
		update()
		mediaQuery.addEventListener('change', update)
		onCleanup(() => mediaQuery.removeEventListener('change', update))
	})

	createEffect(() => {
		if (!desktopResizeEnabled() || !inputPaneEl) {
			return
		}
		defaultDesktopInputHeight =
			Math.round(inputPaneEl.getBoundingClientRect().height) ||
			DEFAULT_DESKTOP_INPUT_HEIGHT
		const storedHeight = readStoredInputPaneHeight()
		applyInputPaneHeight(storedHeight ?? defaultDesktopInputHeight)
	})

	createEffect(() => {
		if (desktopResizeEnabled()) {
			return
		}
		setInputPaneHeight(undefined)
	})

	createEffect(() => {
		if (!desktopResizeEnabled()) {
			return
		}
		const onResize = () => {
			const height = inputPaneHeight()
			if (typeof height !== 'number') {
				return
			}
			const clampedHeight = clampInputPaneHeight(height)
			if (clampedHeight !== height) {
				applyInputPaneHeight(clampedHeight, true)
			}
		}
		window.addEventListener('resize', onResize)
		onCleanup(() => window.removeEventListener('resize', onResize))
	})

	async function submit() {
		const text = input().trim()
		if (!text || !props.canSend) {
			return
		}
		setInput('')
		scrollMessagesToBottom('auto')
		await props.onSendMessage(text)
	}

	async function confirmDeleteSession() {
		const sessionId = sessionPendingDeleteId()
		if (!sessionId) {
			return
		}
		setSessionPendingDeleteId(undefined)
		await props.onDeleteSession(sessionId)
	}

	const requestDeleteMessage = props.onDeleteMessage
		? (messageId: string) => {
				const item = props.timeline.find(
					(i): i is ChatTimelineMessageItem =>
						i.kind === 'message' && i.message.id === messageId,
				)
				if (!item) return
				setPendingDeleteMessage(item)
			}
		: undefined

	const requestRegenerateMessage = props.onRegenerateMessage
		? (messageId: string) => {
				const item = props.timeline.find(
					(i): i is ChatTimelineMessageItem =>
						i.kind === 'message' && i.message.id === messageId,
				)
				if (!item) return
				setPendingRegenerateMessage(item)
			}
		: undefined

	const requestRecallMessage = props.onRecallMessage
		? (messageId: string) => {
				const item = props.timeline.find(
					(i): i is ChatTimelineMessageItem =>
						i.kind === 'message' && i.message.id === messageId,
				)
				if (!item) return
				setPendingRecallMessage(item)
			}
		: undefined

	async function doRecallMessage(
		item: ChatTimelineMessageItem,
		options?: { restoreFiles?: boolean },
	) {
		const text = (item.message.message.content ?? [])
			.filter((p) => p.type === 'text')
			.map((p) => (p as { type: 'text'; text: string }).text)
			.join('\n')
		setInput(text)
		await props.onRecallMessage?.(item.message.id, options)
	}

	async function confirmRecallMessage() {
		const item = pendingRecallMessage()
		if (!item) return
		setPendingRecallMessage(undefined)
		await doRecallMessage(item)
	}

	function confirmRegenerateMessage() {
		const item = pendingRegenerateMessage()
		if (!item) return
		setPendingRegenerateMessage(undefined)
		props.onRegenerateMessage?.(item.message.id)
	}

	function confirmDeleteMessage() {
		const item = pendingDeleteMessage()
		if (!item) return
		setPendingDeleteMessage(undefined)
		props.onDeleteMessage?.(item.message.id)
	}

	const deleteMessageConfirmText = () => {
		const item = pendingDeleteMessage()
		if (!item) return ''
		switch (item.message.message.role) {
			case 'user':
				return t('deleteUserMessageConfirm')
			case 'tool':
				return t('deleteToolMessageConfirm')
			default:
				return t('deleteAssistantMessageConfirm')
		}
	}

	const deleteMessageHasReversibleOps = () =>
		Boolean(pendingDeleteMessage()?.message.reversibleOps?.length)

	const recallHasReversibleOps = () => {
		const item = pendingRecallMessage()
		if (!item) return false
		let seenTarget = false
		for (const timelineItem of props.timeline) {
			if (timelineItem.kind !== 'message') {
				if (seenTarget) {
					break
				}
				continue
			}
			if (!seenTarget) {
				seenTarget = timelineItem.message.id === item.message.id
				continue
			}
			if (timelineItem.message.reversibleOps?.length) {
				return true
			}
		}
		return item.message.reversibleOps?.length ? true : false
	}

	async function confirmRecallAndRestoreMessage() {
		const item = pendingRecallMessage()
		if (!item) return
		setPendingRecallMessage(undefined)
		await doRecallMessage(item, { restoreFiles: true })
	}

	return (
		<div class="relative flex h-full overflow-hidden bg-[var(--background-primary)] text-[var(--text-normal)]">
			<div class="flex min-w-0 flex-1 flex-col overflow-hidden">
				{/* Header */}
				<div class="relative flex shrink-0 items-center gap-2 border-b border-[var(--background-modifier-border)] px-3 py-3">
					<button
						type="button"
						onClick={() => {
							setHistoryOpen((value) => !value)
							setModelPickerOpen(false)
						}}
					>
						{t('history')}
					</button>
					<div class="min-w-0 flex-1 truncate text-sm font-semibold">
						{props.title || t('newChat')}
					</div>
					<Show when={hasTasks()}>
						<button
							class="mod-cta"
							type="button"
							onClick={() => setTasksOpen((value) => !value)}
						>
							{t('tasks')} ({runningTaskCount()})
						</button>
					</Show>
					<div class="relative" ref={modelPickerEl}>
						<button
							class="max-w-56 min-w-34 rounded-2 border border-[var(--background-modifier-border)] bg-[var(--background-primary-alt)] px-3 py-2 text-left text-sm hover:bg-[var(--background-modifier-hover)]"
							type="button"
							onClick={() => {
								setModelPickerOpen((value) => !value)
								setHistoryOpen(false)
							}}
						>
							<div class="truncate">{modelPickerLabel()}</div>
						</button>
						<Show when={modelPickerOpen()}>
							<div class="absolute right-0 top-12 z-10 w-72 rounded-3 border border-[var(--background-modifier-border)] bg-[var(--background-primary)] p-3 shadow-lg">
								<div class="mb-2 text-xs text-[var(--text-muted)]">
									{t('provider')}
								</div>
								<select
									class="w-full"
									value={props.selectedProviderId || ''}
									onChange={(event) =>
										props.onSelectProvider(event.currentTarget.value)
									}
								>
									<option value="">{t('noProvider')}</option>
									<For each={props.providers}>
										{(provider) => (
											<option value={provider.id}>{provider.name}</option>
										)}
									</For>
								</select>
								<div class="mb-2 mt-3 text-xs text-[var(--text-muted)]">
									{t('model')}
								</div>
								<select
									class="w-full"
									value={props.selectedModelId || ''}
									disabled={!selectedProvider()?.models.length || isBusy()}
									onChange={(event) => {
										props.onSelectModel(event.currentTarget.value)
										setModelPickerOpen(false)
									}}
								>
									<option value="">{t('noModel')}</option>
									<For each={selectedProvider()?.models || []}>
										{(model) => <option value={model.id}>{model.name}</option>}
									</For>
								</select>
							</div>
						</Show>
					</div>
					<Show when={historyOpen()}>
						<div
							ref={historyEl}
							class="absolute left-3 top-12 z-10 w-80 overflow-hidden rounded-4 border border-[var(--background-modifier-border)] bg-[var(--background-primary)] shadow-lg"
						>
							<div class="border-b border-[var(--background-modifier-border)] px-4 py-3">
								<div class="flex items-center justify-between gap-3">
									<div class="min-w-0">
										<div class="text-sm font-semibold text-[var(--text-normal)]">
											{t('history')}
										</div>
									</div>
									<button
										class="rounded-2 border border-[var(--background-modifier-border)] bg-[var(--background-primary-alt)] px-3 py-2 text-sm hover:bg-[var(--background-modifier-hover)]"
										type="button"
										onClick={() => {
											props.onNewSession()
											setHistoryOpen(false)
										}}
									>
										{t('newChat')}
									</button>
								</div>
							</div>
							<div class="max-h-80 overflow-auto p-3 scrollbar-default">
								<div class="flex flex-col gap-2">
									<For each={props.sessionHistory}>
										{(session) => (
											<SessionHistoryItem
												session={session}
												isActive={session.id === props.activeSessionId}
												onSelect={(sessionId) => {
													props.onSwitchSession(sessionId)
													setHistoryOpen(false)
												}}
												onDelete={(sessionId) => {
													setSessionPendingDeleteId(sessionId)
												}}
											/>
										)}
									</For>
								</div>
							</div>
						</div>
					</Show>
				</div>

				<div
					ref={splitLayoutEl}
					class="flex min-h-0 flex-1 flex-col overflow-hidden"
				>
					{/* Messages */}
					<div
						ref={messagesEl}
						class="min-h-0 flex-1 overflow-y-auto px-3 scrollbar-default"
					>
						<Show
							when={
								props.timeline.length > 0 ||
								props.pendingMessages.length > 0 ||
								isBusy()
							}
							fallback={
								<div class="flex h-full items-center justify-center text-sm text-[var(--text-muted)]">
									{t('empty')}
								</div>
							}
						>
							<div class="flex flex-col gap-3">
								<For each={props.timeline}>
									{(item) => (
										<Switch>
											<Match when={item.kind === 'fragment'}>
												<FragmentDivider
													item={item as ChatTimelineFragmentItem}
												/>
											</Match>
											<Match when={item.kind === 'message'}>
												<MessageCard
													item={item as ChatTimelineMessageItem}
													renderMarkdown={props.renderMarkdown}
													onDeleteMessage={requestDeleteMessage}
													onRegenerateMessage={requestRegenerateMessage}
													onRecallMessage={requestRecallMessage}
												/>
											</Match>
										</Switch>
									)}
								</For>
								<RunStateCard
									runState={props.runState}
									onStop={props.onStopActiveRun}
								/>
								<PendingList pendingMessages={props.pendingMessages} />
							</div>
						</Show>
					</div>

					<Show when={desktopResizeEnabled()}>
						<PaneResizer
							onResizeStart={onInputPaneResizeStart}
							onResize={onInputPaneResize}
							onResizeEnd={onInputPaneResizeEnd}
							onDblClick={resetInputPaneHeight}
						/>
					</Show>

					{/* Input */}
					<div
						ref={inputPaneEl}
						class={`chatbox-input-pane shrink-0 px-3 py-3 ${
							desktopResizeEnabled()
								? 'chatbox-input-pane--resizable'
								: 'border-t border-[var(--background-modifier-border)]'
						}`}
						style={
							desktopResizeEnabled() && typeof inputPaneHeight() === 'number'
								? { height: `${inputPaneHeight()}px` }
								: undefined
						}
					>
						<textarea
							class="chatbox-input w-full resize-none rounded-3 border border-[var(--background-modifier-border)] bg-[var(--background-primary-alt)] text-sm outline-none"
							placeholder={t('inputPlaceholder')}
							value={input()}
							onInput={(event) => setInput(event.currentTarget.value)}
							onCompositionStart={() => setIsComposing(true)}
							onCompositionEnd={() => setIsComposing(false)}
							onKeyDown={(event) => {
								if (
									event.key === 'Enter' &&
									!event.shiftKey &&
									!isComposing() &&
									!event.isComposing &&
									event.keyCode !== 229
								) {
									event.preventDefault()
									void submit()
								}
							}}
						/>
						<div class="mt-3 flex items-center justify-between gap-3">
							<div class="flex flex-wrap items-center gap-2">
								<button
									class="chatbox-tag-button"
									type="button"
									disabled={!props.canCreateFragment}
									onClick={() => props.onNewFragment()}
								>
									{t('newFragment')}
								</button>
								<button
									class="chatbox-tag-button"
									type="button"
									disabled={!props.canCompress}
									onClick={() => void props.onCompressContext()}
								>
									{t('compressContext')}
								</button>
							</div>
							<button
								class="mod-cta"
								type="button"
								disabled={!input().trim()}
								onClick={() => void submit()}
							>
								{isBusy() ? t('queueSend') : t('send')}
							</button>
						</div>
					</div>
				</div>
			</div>

			{/* Tasks sidebar */}
			<Show when={tasksOpen()}>
				<TasksPanel
					currentSessionTasks={props.currentSessionTasks}
					otherSessionTasks={props.otherSessionTasks}
					onCancelTask={props.onCancelTask}
					onClose={() => setTasksOpen(false)}
				/>
			</Show>

			{/* Delete session dialog */}
			<Show when={sessionPendingDeleteId()}>
				<ConfirmDialog
					title={t('deleteSessionTitle')}
					message={t('deleteSessionMessage')}
					confirmLabel={t('confirmDelete')}
					onCancel={() => setSessionPendingDeleteId(undefined)}
					onConfirm={() => void confirmDeleteSession()}
				/>
			</Show>

			{/* Delete message dialog */}
			<Show when={pendingDeleteMessage()}>
				<ConfirmDialog
					title={t('deleteMessageTitle')}
					message={`${deleteMessageConfirmText()}${
						deleteMessageHasReversibleOps()
							? `\n\n${t('deleteToolMessageRestoreWarning')}`
							: ''
					}`}
					confirmLabel={t('confirmDelete')}
					onCancel={() => setPendingDeleteMessage(undefined)}
					onConfirm={confirmDeleteMessage}
				/>
			</Show>

			{/* Regenerate message dialog */}
			<Show when={pendingRegenerateMessage()}>
				<ConfirmDialog
					title={t('regenerateMessageTitle')}
					message={t('regenerateMessageConfirm')}
					confirmLabel={t('regenerateMessage')}
					onCancel={() => setPendingRegenerateMessage(undefined)}
					onConfirm={confirmRegenerateMessage}
				/>
			</Show>

			{/* Recall message dialog */}
			<Show when={pendingRecallMessage()}>
				<ConfirmDialog
					title={t('recallMessageTitle')}
					message={t('recallMessageConfirm')}
					confirmLabel={t('confirmRecall')}
					secondaryConfirmLabel={
						recallHasReversibleOps()
							? t('recallMessageRestoreConfirm')
							: undefined
					}
					onCancel={() => setPendingRecallMessage(undefined)}
					onConfirm={() => void confirmRecallMessage()}
					onSecondaryConfirm={() => void confirmRecallAndRestoreMessage()}
				/>
			</Show>
		</div>
	)
}

export default App


================================================
FILE: packages/chatbox/src/assets/styles/global.css
================================================
@unocss;

.markdown-rendered {
	min-width: 0;
	overflow-wrap: anywhere;
	word-break: break-word;
}

.markdown-rendered > *:first-child {
	margin-top: 0;
}

.markdown-rendered > *:last-child {
	margin-bottom: 0;
}

.markdown-rendered table {
	display: block;
	max-width: 100%;
	overflow-x: auto;
	border-collapse: collapse;
	white-space: nowrap;
}

.markdown-rendered thead,
.markdown-rendered tbody,
.markdown-rendered tr {
	width: max-content;
	min-width: 100%;
}

.markdown-rendered th,
.markdown-rendered td {
	white-space: nowrap;
}

.markdown-rendered pre,
.markdown-rendered code,
.markdown-rendered .internal-embed,
.markdown-rendered img {
	max-width: 100%;
}

.markdown-rendered pre {
	overflow-x: auto;
	white-space: pre;
}

.chatbox-tag-button {
	border-radius: 999px;
}

.chatbox-input {
	height: 7rem;
	padding: 0.75rem;
	line-height: 1.5;
}

.chatbox-input-pane {
	display: flex;
	flex-direction: column;
}

.chatbox-resizer {
	flex-shrink: 0;
	cursor: ns-resize;
	padding-bottom: 4px;
	padding-top: 4px;
	touch-action: none;
	user-select: none;
}

.chatbox-resizer-line {
	height: 1px;
	background: var(--background-modifier-border);
	transition: background-color 120ms ease;
}

.chatbox-resizer:hover .chatbox-resizer-line,
.chatbox-resizer.is-resizing .chatbox-resizer-line {
	background: var(--interactive-accent);
}

.chatbox-resize-active,
.chatbox-resize-active * {
	cursor: ns-resize !important;
	user-select: none !important;
}

@media (pointer: fine) and (min-width: 1024px) {
	.chatbox-input-pane--resizable {
		border-top-width: 0;
	}

	.chatbox-input-pane--resizable .chatbox-input {
		flex: 1 1 auto;
		height: auto;
		min-height: 4rem;
		min-width: 0;
	}
}

@media (max-width: 768px) {
	.chatbox-input {
		height: 5.5rem;
		padding: 0.625rem;
		line-height: 1.4;
	}
}


================================================
FILE: packages/chatbox/src/components/ConfirmDialog.tsx
================================================
import { Show } from 'solid-js'
import { t } from '../i18n'

export function ConfirmDialog(props: {
	title: string | undefined
	message: string | undefined
	confirmLabel: string | undefined
	confirmClass?: string
	secondaryConfirmLabel?: string | undefined
	secondaryConfirmClass?: string
	onCancel: () => void
	onConfirm: () => void
	onSecondaryConfirm?: () => void
}) {
	return (
		<div class="absolute inset-0 z-20 flex items-center justify-center bg-black/40 px-4">
			<div class="w-full max-w-sm rounded-4 border border-[var(--background-modifier-border)] bg-[var(--background-primary)] p-4 shadow-xl">
				<div class="text-base font-semibold text-[var(--text-normal)]">
					{props.title}
				</div>
				<div class="mt-3 text-sm leading-6 text-[var(--text-muted)]">
					{props.message}
				</div>
				<div class="mt-4 flex justify-end gap-2">
					<button
						class="rounded-2 border border-[var(--background-modifier-border)] px-3 py-2 text-sm hover:bg-[var(--background-modifier-hover)]"
						type="button"
						onClick={props.onCancel}
					>
						{t('cancel')}
					</button>
					<Show when={props.secondaryConfirmLabel}>
						<button
							class={
								props.secondaryConfirmClass ??
								'rounded-2 border border-[var(--interactive-accent-rgb)]/30 bg-[var(--interactive-accent-rgb)]/12 px-3 py-2 text-sm text-[var(--text-normal)] hover:bg-[var(--interactive-accent-rgb)]/18'
							}
							type="button"
							onClick={() => props.onSecondaryConfirm?.()}
						>
							{props.secondaryConfirmLabel}
						</button>
					</Show>
					<button
						class={
							props.confirmClass ??
							'rounded-2 border border-[var(--color-red-rgb)]/30 bg-[var(--color-red-rgb)]/12 px-3 py-2 text-sm text-[var(--text-error)] hover:bg-[var(--color-red-rgb)]/18'
						}
						type="button"
						onClick={props.onConfirm}
					>
						{props.confirmLabel}
					</button>
				</div>
			</div>
		</div>
	)
}


================================================
FILE: packages/chatbox/src/components/ContentParts.tsx
================================================
import { For, Match, Show, Switch } from 'solid-js'
import type { ChatMessageContentPart, ChatboxProps } from '../types'
import { MarkdownContent } from './MarkdownContent'

export function ContentParts(props: {
	content?: ChatMessageContentPart[] | null
	renderMarkdown?: ChatboxProps['renderMarkdown']
}) {
	return (
		<Show when={props.content?.length}>
			<div class="mt-2 flex flex-col gap-3">
				<For each={props.content || []}>
					{(part) => (
						<Switch>
							<Match when={part.type === 'text'}>
								<MarkdownContent
									markdown={
										(part as Extract<ChatMessageContentPart, { type: 'text' }>)
											.text
									}
									renderMarkdown={props.renderMarkdown}
								/>
							</Match>
							<Match when={part.type === 'image_url'}>
								<img
									class="max-h-80 max-w-full rounded-2 border border-[var(--background-modifier-border)] object-contain"
									src={
										(
											part as Extract<
												ChatMessageContentPart,
												{ type: 'image_url' }
											>
										).image_url.url
									}
									alt=""
								/>
							</Match>
							<Match when={part.type === 'unknown'}>
								<pre class="m-0 whitespace-pre-wrap break-words rounded-2 bg-[var(--background-secondary)] p-2 text-xs leading-5">
									{JSON.stringify(
										(
											part as Extract<
												ChatMessageContentPart,
												{ type: 'unknown' }
											>
										).value,
										null,
										2,
									)}
								</pre>
							</Match>
						</Switch>
					)}
				</For>
			</div>
		</Show>
	)
}


================================================
FILE: packages/chatbox/src/components/CopyButton.tsx
================================================
import { Show, createSignal, onCleanup } from 'solid-js'
import { t } from '../i18n'

export function CopyButton(props: { getText: () => string }) {
	const [copied, setCopied] = createSignal(false)
	let timer: ReturnType<typeof setTimeout>

	function handleCopy() {
		void navigator.clipboard.writeText(props.getText()).then(() => {
			setCopied(true)
			clearTimeout(timer)
			timer = setTimeout(() => setCopied(false), 2000)
		})
	}

	onCleanup(() => clearTimeout(timer))

	return (
		<button
			class="cursor-pointer p-1 size-5 text-[var(--text-muted)] hover:text-[var(--text-normal)] !border-none !bg-transparent !shadow-none"
			type="button"
			title={copied() ? t('copied') : t('copy')}
			onClick={handleCopy}
		>
			<Show
				when={copied()}
				fallback={
					<svg
						width="14"
						height="14"
						viewBox="0 0 24 24"
						fill="none"
						stroke="currentColor"
						stroke-width="2"
						stroke-linecap="round"
						stroke-linejoin="round"
						aria-hidden="true"
					>
						<rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
						<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
					</svg>
				}
			>
				<svg
					width="14"
					height="14"
					viewBox="0 0 24 24"
					fill="none"
					stroke="currentColor"
					stroke-width="2"
					stroke-linecap="round"
					stroke-linejoin="round"
					aria-hidden="true"
				>
					<polyline points="20 6 9 17 4 12" />
				</svg>
			</Show>
		</button>
	)
}


================================================
FILE: packages/chatbox/src/components/FragmentDivider.tsx
================================================
import type { ChatTimelineFragmentItem } from '../types'
import { formatFragmentTime } from '../utils'

export function FragmentDivider(props: { item: ChatTimelineFragmentItem }) {
	return (
		<div class="relative py-2">
			<div class="absolute inset-x-0 top-1/2 h-px bg-[var(--background-modifier-border)]" />
			<div class="relative mx-auto w-fit rounded-full border border-[var(--background-modifier-border)] bg-[var(--background-primary)] px-3 py-1 text-xs text-[var(--text-muted)]">
				{formatFragmentTime(props.item.createdAt)}
			</div>
		</div>
	)
}


================================================
FILE: packages/chatbox/src/components/MarkdownContent.tsx
================================================
import { createEffect, onCleanup } from 'solid-js'
import type { ChatboxProps } from '../types'

export function MarkdownContent(props: {
	markdown: string
	renderMarkdown?: ChatboxProps['renderMarkdown']
}) {
	let el: HTMLDivElement | undefined
	let cleanup: (() => void) | undefined
	let renderVersion = 0

	createEffect(() => {
		const markdown = props.markdown
		const renderMarkdown = props.renderMarkdown
		const currentVersion = ++renderVersion

		cleanup?.()
		cleanup = undefined

		if (!el) {
			return
		}

		el.replaceChildren()

		if (!markdown) {
			return
		}

		if (!renderMarkdown) {
			el.textContent = markdown
			return
		}

		void Promise.resolve(renderMarkdown(el, markdown)).then((nextCleanup) => {
			if (currentVersion !== renderVersion) {
				if (typeof nextCleanup === 'function') {
					nextCleanup()
				}
				return
			}
			cleanup = typeof nextCleanup === 'function' ? nextCleanup : undefined
		})
	})

	onCleanup(() => {
		renderVersion += 1
		cleanup?.()
		cleanup = undefined
		el?.replaceChildren()
	})

	return (
		<div
			ref={el}
			class="markdown-rendered mt-2 text-sm leading-6 text-[var(--text-normal)]"
		/>
	)
}


================================================
FILE: packages/chatbox/src/components/MessageCard.tsx
================================================
import { Show } from 'solid-js'
import type { ChatTimelineMessageItem, ChatboxProps } from '../types'
import { t } from '../i18n'
import { formatTime, formatUsage } from '../utils'
import { CopyButton } from './CopyButton'
import { ContentParts } from './ContentParts'

export function MessageCard(props: {
	item: ChatTimelineMessageItem
	renderMarkdown?: ChatboxProps['renderMarkdown']
	onDeleteMessage?: ChatboxProps['onDeleteMessage']
	onRegenerateMessage?: ChatboxProps['onRegenerateMessage']
	onRecallMessage?: ChatboxProps['onRecallMessage']
}) {
	const content = () => props.item.message.message.content
	const usageText = () =>
		formatUsage(
			props.item.message.meta?.usage?.inputTokens,
			props.item.message.meta?.usage?.outputTokens,
			props.item.message.meta?.usage?.totalTokens,
		)

	const roleLabel = () => {
		if (props.item.message.message.role === 'tool') {
			return `Tool: ${props.item.message.message.name || t('tool')}`
		}
		if (props.item.message.message.role === 'assistant') {
			return props.item.message.meta?.modelName || 'Assistant'
		}
		if (props.item.message.message.role === 'user') {
			return 'User'
		}
		return 'System'
	}

	const getText = () =>
		(content() ?? [])
			.filter((p) => p.type === 'text')
			.map((p) => (p as { type: 'text'; text: string }).text)
			.join('\n')

	return (
		<Show
			when={props.item.message.message.role !== 'tool'}
			fallback={
				<details
					class={`rounded-3 border border-[var(--background-modifier-border)] bg-[var(--background-primary-alt)] p-3 ${
						props.item.message.isError ? 'border-[var(--text-error)]' : ''
					}`}
				>
					<summary class="flex cursor-pointer list-none items-center justify-between gap-3 text-xs text-[var(--text-muted)] marker:hidden">
						<div class="font-medium text-[var(--text-normal)]">
							{roleLabel()}
						</div>
						<div class="flex items-center gap-1">
							<span>{formatTime(props.item.message.createdAt)}</span>
							<span onClick={(e) => e.stopPropagation()}>
								<CopyButton getText={getText} />
							</span>
							<Show when={props.onDeleteMessage}>
								<span onClick={(e) => e.stopPropagation()}>
									<button
										class="cursor-pointer p-1 size-5 text-[var(--text-muted)] hover:text-[var(--text-error)] !border-none !bg-transparent !shadow-none"
										type="button"
										title={t('deleteMessage')}
										onClick={() =>
											props.onDeleteMessage?.(props.item.message.id)
										}
									>
										<svg
											width="14"
											height="14"
											viewBox="0 0 24 24"
											fill="none"
											stroke="currentColor"
											stroke-width="2"
											stroke-linecap="round"
											stroke-linejoin="round"
											aria-hidden="true"
										>
											<polyline points="3 6 5 6 21 6" />
											<path d="M19 6l-1 14H6L5 6" />
											<path d="M10 11v6M14 11v6" />
											<path d="M9 6V4h6v2" />
										</svg>
									</button>
								</span>
							</Show>
						</div>
					</summary>
					<Show when={props.item.toolCall}>
						<>
							<div class="mt-3 text-xs text-[var(--text-muted)]">
								{t('params')}
							</div>
							<pre class="m-0 mt-1 max-h-48 overflow-auto whitespace-pre-wrap break-words rounded-2 bg-[var(--background-secondary)] p-2 text-xs leading-5">
								{props.item.toolCall?.function.arguments || '{}'}
							</pre>
						</>
					</Show>
					<div class="mt-3 text-xs text-[var(--text-muted)]">{t('result')}</div>
					<pre class="m-0 mt-1 max-h-48 overflow-auto whitespace-pre-wrap break-words rounded-2 bg-[var(--background-secondary)] p-2 text-xs leading-5">
						{content()
							?.filter((p) => p.type === 'text')
							.map((p) => (p as { type: 'text'; text: string }).text)
							.join('\n') || ''}
					</pre>
				</details>
			}
		>
			<div
				class={`rounded-3 p-3 border border-[var(--background-modifier-border)] bg-[var(--background-primary-alt)] ${
					props.item.message.isError ? 'border-[var(--text-error)]' : ''
				}`}
			>
				<div class="flex items-center justify-between gap-3 text-xs text-[var(--text-muted)]">
					<div class="font-medium text-[var(--text-normal)]">{roleLabel()}</div>
					<span>{formatTime(props.item.message.createdAt)}</span>
				</div>
				<ContentParts
					content={content()}
					renderMarkdown={props.renderMarkdown}
				/>
				<Show
					when={
						props.item.message.message.role === 'assistant' ||
						props.item.message.message.role === 'user'
					}
				>
					<div class="mt-3 flex items-center justify-between gap-2">
						<div class="flex items-center gap-0.5">
							<CopyButton getText={getText} />
							<Show when={props.onDeleteMessage}>
								<button
									class="cursor-pointer p-1 size-6 text-[var(--text-muted)] hover:text-[var(--text-error)] !border-none !bg-transparent !shadow-none"
									type="button"
									title={t('deleteMessage')}
									onClick={() => props.onDeleteMessage?.(props.item.message.id)}
								>
									<svg
										width="14"
										height="14"
										viewBox="0 0 24 24"
										fill="none"
										stroke="currentColor"
										stroke-width="2"
										stroke-linecap="round"
										stroke-linejoin="round"
										aria-hidden="true"
									>
										<polyline points="3 6 5 6 21 6" />
										<path d="M19 6l-1 14H6L5 6" />
										<path d="M10 11v6M14 11v6" />
										<path d="M9 6V4h6v2" />
									</svg>
								</button>
							</Show>
							<Show
								when={
									props.item.message.message.role === 'user' &&
									props.onRecallMessage
								}
							>
								<button
									class="cursor-pointer p-1 size-6 text-[var(--text-muted)] hover:text-[var(--text-normal)] !border-none !bg-transparent !shadow-none"
									type="button"
									title={t('recallMessage')}
									onClick={() => props.onRecallMessage?.(props.item.message.id)}
								>
									<svg
										width="14"
										height="14"
										viewBox="0 0 24 24"
										fill="none"
										stroke="currentColor"
										stroke-width="2"
										stroke-linecap="round"
										stroke-linejoin="round"
										aria-hidden="true"
									>
										<path d="M9 14 4 9l5-5" />
										<path d="M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5v0a5.5 5.5 0 0 1-5.5 5.5H11" />
									</svg>
								</button>
							</Show>
							<Show
								when={
									props.item.message.message.role === 'assistant' &&
									props.onRegenerateMessage
								}
							>
								<button
									class="cursor-pointer p-1 size-6 text-[var(--text-muted)] hover:text-[var(--text-normal)] !border-none !bg-transparent !shadow-none"
									type="button"
									title={t('regenerateMessage')}
									onClick={() =>
										props.onRegenerateMessage?.(props.item.message.id)
									}
								>
									<svg
										width="14"
										height="14"
										viewBox="0 0 24 24"
										fill="none"
										stroke="currentColor"
										stroke-width="2"
										stroke-linecap="round"
										stroke-linejoin="round"
										aria-hidden="true"
									>
										<path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8" />
										<path d="M21 3v5h-5" />
										<path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16" />
										<path d="M8 16H3v5" />
									</svg>
								</button>
							</Show>
						</div>
						<Show
							when={
								props.item.message.message.role === 'assistant' && usageText()
							}
						>
							<div class="text-[10px] text-[var(--text-faint)]">
								{usageText()}
							</div>
						</Show>
					</div>
				</Show>
			</div>
		</Show>
	)
}


================================================
FILE: packages/chatbox/src/components/PaneResizer.tsx
================================================
import { createSignal, onCleanup } from 'solid-js'

interface PaneResizerProps {
	onResizeStart?: () => void
	onResize: (deltaY: number) => void
	onResizeEnd?: () => void
	onDblClick?: () => void
}

export function PaneResizer(props: PaneResizerProps) {
	const [isResizing, setIsResizing] = createSignal(false)
	let startY = 0
	let removeListeners: (() => void) | undefined

	function stopResize() {
		removeListeners?.()
		removeListeners = undefined
		setIsResizing(false)
		document.body.classList.remove('chatbox-resize-active')
	}

	function onPointerDown(event: PointerEvent) {
		if (event.button !== 0) {
			return
		}

		event.preventDefault()
		stopResize()
		props.onResizeStart?.()
		startY = event.clientY
		setIsResizing(true)
		document.body.classList.add('chatbox-resize-active')

		const onPointerMove = (moveEvent: PointerEvent) => {
			props.onResize(startY - moveEvent.clientY)
		}

		const onPointerUp = () => {
			props.onResizeEnd?.()
			stopResize()
		}

		document.addEventListener('pointermove', onPointerMove)
		document.addEventListener('pointerup', onPointerUp)
		document.addEventListener('pointercancel', onPointerUp)
		removeListeners = () => {
			document.removeEventListener('pointermove', onPointerMove)
			document.removeEventListener('pointerup', onPointerUp)
			document.removeEventListener('pointercancel', onPointerUp)
		}
	}

	onCleanup(() => stopResize())

	return (
		<div
			class="chatbox-resizer px-3"
			classList={{ 'is-resizing': isResizing() }}
			role="separator"
			aria-orientation="horizontal"
			onPointerDown={onPointerDown}
			onDblClick={() => props.onDblClick?.()}
		>
			<div class="chatbox-resizer-line" />
		</div>
	)
}


================================================
FILE: packages/chatbox/src/components/PendingList.tsx
================================================
import { For, Show } from 'solid-js'
import type { ChatboxProps } from '../types'
import { t } from '../i18n'

export function PendingList(props: {
	pendingMessages: ChatboxProps['pendingMessages']
}) {
	return (
		<Show when={props.pendingMessages.length > 0}>
			<div class="rounded-3 border border-dashed border-[var(--background-modifier-border)] bg-[var(--background-primary-alt)] p-3">
				<div class="text-xs font-medium uppercase tracking-wide text-[var(--text-muted)]">
					{t('pendingMessages')}
				</div>
				<div class="mt-2 flex flex-col gap-2">
					<For each={props.pendingMessages}>
						{(message) => (
							<div class="rounded-2 bg-[var(--background-secondary)] p-3 text-sm text-[var(--text-normal)] whitespace-pre-wrap break-words">
								{message.text}
							</div>
						)}
					</For>
				</div>
			</div>
		</Show>
	)
}


================================================
FILE: packages/chatbox/src/components/RunStateCard.tsx
================================================
import { Show } from 'solid-js'
import type { ChatboxProps } from '../types'
import { t } from '../i18n'
import { runStateLabel } from '../utils'

export function RunStateCard(props: {
	runState: ChatboxProps['runState']
	onStop?: ChatboxProps['onStopActiveRun']
}) {
	const label = () => runStateLabel(props.runState)
	const canStop = () =>
		props.runState === 'thinking' || props.runState === 'waiting_for_tools'

	return (
		<Show when={label()}>
			<div class="rounded-3 border border-[var(--background-modifier-border)] bg-[var(--background-primary-alt)] p-3">
				<div class="flex items-center justify-between gap-3 rounded-2 bg-[var(--background-secondary)] px-3 py-2 text-sm text-[var(--text-normal)]">
					<div class="flex min-w-0 items-center gap-3">
						<svg
							class="h-4 w-4 shrink-0 animate-spin text-[var(--interactive-accent)]"
							viewBox="0 0 24 24"
							fill="none"
							aria-hidden="true"
						>
							<circle
								cx="12"
								cy="12"
								r="9"
								stroke="currentColor"
								stroke-width="3"
								stroke-linecap="round"
								stroke-dasharray="42 16"
							/>
						</svg>
						<div class="min-w-0 font-medium">{label()}</div>
					</div>
					<Show when={canStop() && props.onStop}>
						<button
							class="shrink-0 rounded-2 border border-[var(--background-modifier-border)] px-2 py-1 text-xs hover:bg-[var(--background-modifier-hover)]"
							type="button"
							onClick={() => props.onStop?.()}
						>
							{t('stopRun')}
						</button>
					</Show>
				</div>
			</div>
		</Show>
	)
}


================================================
FILE: packages/chatbox/src/components/SessionHistoryItem.tsx
================================================
import { Show } from 'solid-js'
import type { ChatboxProps } from '../types'
import { t } from '../i18n'
import { formatTime } from '../utils'

export function SessionHistoryItem(props: {
	session: ChatboxProps['sessionHistory'][number]
	isActive: boolean
	onSelect: (sessionId: string) => void
	onDelete: (sessionId: string) => void
}) {
	const activate = () => props.onSelect(props.session.id)

	return (
		<div
			role="button"
			tabIndex={0}
			class={`group relative w-full overflow-hidden rounded-3 border px-3 py-3 text-left transition-colors ${
				props.isActive
					? 'border-[var(--interactive-accent)] bg-[var(--background-secondary)]'
					: 'border-[var(--background-modifier-border)] bg-[var(--background-primary-alt)] hover:bg-[var(--background-modifier-hover)]'
			}`}
			onClick={activate}
			onKeyDown={(event) => {
				if (event.key === 'Enter' || event.key === ' ') {
					event.preventDefault()
					activate()
				}
			}}
		>
			<Show when={props.isActive}>
				<div class="absolute inset-y-3 left-0 w-1 rounded-r-full bg-[var(--interactive-accent)]" />
			</Show>
			<div class="flex items-start justify-between gap-3">
				<div class="min-w-0 flex-1">
					<div class="truncate pr-1 text-sm font-medium text-[var(--text-normal)]">
						{props.session.title}
					</div>
					<div class="mt-2 text-xs text-[var(--text-muted)]">
						{formatTime(props.session.createdAt)}
					</div>
				</div>
				<button
					class="shrink-0 rounded-2 border border-[var(--background-modifier-border)] px-2 py-1 text-xs text-[var(--text-muted)] hover:bg-[var(--background-modifier-hover)] hover:text-[var(--text-error)]"
					type="button"
					aria-label={t('deleteSession')}
					onClick={(event) => {
						event.preventDefault()
						event.stopPropagation()
						props.onDelete(props.session.id)
					}}
				>
					{t('deleteSession')}
				</button>
			</div>
		</div>
	)
}


================================================
FILE: packages/chatbox/src/components/TaskCard.tsx
================================================
import { Show } from 'solid-js'
import type { ChatTaskRecord, ChatboxProps } from '../types'
import { t } from '../i18n'
import { formatTime, formatDuration, statusLabel, statusClass } from '../utils'

export function TaskCard(props: {
	task: ChatTaskRecord
	onCancelTask?: ChatboxProps['onCancelTask']
	compact?: boolean
}) {
	const duration = () => formatDuration(props.task)
	const detail = () => {
		switch (props.task.status) {
			case 'completed':
				return props.task.summary
			case 'failed':
				return props.task.summary || props.task.error
			case 'cancelled':
				return props.task.summary
			default:
				return ''
		}
	}
	const sourceCount = () =>
		props.task.status === 'completed'
			? props.task.sourceCount
			: props.task.status === 'failed'
				? props.task.sourceCount
				: undefined

	return (
		<div
			class={`rounded-3 border p-3 ${
				props.task.status === 'failed'
					? 'border-[var(--text-error)] bg-[var(--background-primary-alt)]'
					: 'border-[var(--background-modifier-border)] bg-[var(--background-primary-alt)]'
			}`}
		>
			<div class="flex items-start justify-between gap-3">
				<div class="min-w-0 flex-1">
					<div class="font-medium text-[var(--text-normal)] truncate">
						{props.task.title}
					</div>
					<div class="mt-1 text-xs text-[var(--text-muted)] break-words">
						{props.task.prompt}
					</div>
				</div>
				<span
					class={`shrink-0 rounded-full px-2 py-1 text-xs ${statusClass(props.task.status)}`}
				>
					{statusLabel(props.task.status)}
				</span>
			</div>
			<div class="mt-3 flex flex-wrap gap-2 text-xs text-[var(--text-muted)]">
				<span class="rounded-full bg-[var(--background-secondary)] px-2 py-1">
					{t('depth')}: {props.task.depth}/{props.task.maxDepth}
				</span>
				<Show when={duration()}>
					<span class="rounded-full bg-[var(--background-secondary)] px-2 py-1">
						{duration()}
					</span>
				</Show>
				<Show when={typeof sourceCount() === 'number'}>
					<span class="rounded-full bg-[var(--background-secondary)] px-2 py-1">
						{t('sources')}: {sourceCount()}
					</span>
				</Show>
			</div>
			<Show when={detail()}>
				<div class="mt-3 rounded-2 bg-[var(--background-secondary)] p-3 text-sm leading-6 text-[var(--text-normal)] whitespace-pre-wrap break-words">
					{detail()}
				</div>
			</Show>
			<Show when={!props.compact}>
				<div class="mt-3 flex items-center justify-between gap-3 text-xs text-[var(--text-muted)]">
					<div>
						{formatTime(props.task.createdAt)}
						<Show when={'finishedAt' in props.task && props.task.finishedAt}>
							{` · ${formatTime((props.task as Extract<ChatTaskRecord, { finishedAt: number }>).finishedAt)}`}
						</Show>
					</div>
					<Show when={props.task.status === 'running' && props.onCancelTask}>
						<button
							class="rounded-2 border border-[var(--background-modifier-border)] px-2 py-1 text-xs hover:bg-[var(--background-modifier-hover)]"
							type="button"
							onClick={() => props.onCancelTask?.(props.task.id)}
						>
							{t('cancelTask')}
						</button>
					</Show>
				</div>
			</Show>
		</div>
	)
}


================================================
FILE: packages/chatbox/src/components/TasksPanel.tsx
================================================
import { For, Show } from 'solid-js'
import type { ChatboxProps } from '../types'
import { t } from '../i18n'
import { TaskCard } from './TaskCard'

export function TasksPanel(props: {
	currentSessionTasks: ChatboxProps['currentSessionTasks']
	otherSessionTasks: ChatboxProps['otherSessionTasks']
	onCancelTask?: ChatboxProps['onCancelTask']
	onClose: () => void
}) {
	return (
		<div class="flex h-full w-[22rem] shrink-0 flex-col border-l border-[var(--background-modifier-border)] bg-[var(--background-primary-alt)]">
			<div class="flex items-center justify-between border-b border-[var(--background-modifier-border)] px-3 py-3">
				<div class="text-sm font-semibold">{t('tasks')}</div>
				<button
					class="rounded-2 border border-[var(--background-modifier-border)] px-2 py-1 text-xs hover:bg-[var(--background-modifier-hover)]"
					type="button"
					onClick={props.onClose}
				>
					{t('closeTasks')}
				</button>
			</div>
			<div class="flex-1 overflow-y-auto px-3 py-3">
				<div class="text-xs font-medium uppercase tracking-wide text-[var(--text-muted)]">
					{t('currentSession')}
				</div>
				<div class="mt-2 flex flex-col gap-3">
					<Show
						when={props.currentSessionTasks.length > 0}
						fallback={
							<div class="rounded-3 border border-dashed border-[var(--background-modifier-border)] px-3 py-4 text-sm text-[var(--text-muted)]">
								{t('noTasks')}
							</div>
						}
					>
						<For each={props.currentSessionTasks}>
							{(task) => (
								<TaskCard
									task={task}
									onCancelTask={props.onCancelTask}
									compact
								/>
							)}
						</For>
					</Show>
				</div>
				<Show when={props.otherSessionTasks.length > 0}>
					<div class="mt-6 text-xs font-medium uppercase tracking-wide text-[var(--text-muted)]">
						{t('otherSessions')}
					</div>
					<div class="mt-2 flex flex-col gap-3">
						<For each={props.otherSessionTasks}>
							{(task) => <TaskCard task={task} compact />}
						</For>
					</div>
				</Show>
			</div>
		</div>
	)
}


================================================
FILE: packages/chatbox/src/i18n/index.ts
================================================
import * as i18n from '@solid-primitives/i18n'
import { createResource, createSignal } from 'solid-js'
import en from './locales/en'
import zh from './locales/zh'

export type Locale = 'zh' | 'en'

export function toLocale(language: string) {
	switch (language.split('-')[0].toLowerCase()) {
		case 'zh':
			return 'zh'
		default:
			return 'en'
	}
}

export const [locale, setLocale] = createSignal<Locale>(
	toLocale(navigator.language),
)

const [dict] = createResource(locale, (locale) => {
	switch (locale) {
		case 'zh':
			return i18n.flatten(zh)
		default:
			return i18n.flatten(en)
	}
})

export const t = i18n.translator(dict)


================================================
FILE: packages/chatbox/src/i18n/locales/en.ts
================================================
const en = {
	history: 'History',
	deleteSession: 'Delete',
	deleteSessionTitle: 'Delete Session',
	deleteSessionMessage:
		'Delete this session permanently? This action cannot be undone.',
	cancel: 'Cancel',
	confirmDelete: 'Delete',
	newChat: 'New Chat',
	provider: 'Provider',
	model: 'Model',
	noProvider: 'No provider',
	noModel: 'No model',
	send: 'Send',
	queueSend: 'Queue Send',
	thinking: 'Thinking',
	compressing: 'Compressing',
	processingTools: 'Processing Tools',
	stopRun: 'Stop',
	empty: 'Start by sending a message',
	inputPlaceholder: 'Type a message. Enter to send, Shift+Enter for newline',
	newFragment: 'New Fragment',
	compressContext: 'Compress Context',
	pendingMessages: 'Pending Messages',
	params: 'Params',
	result: 'Result',
	tool: 'Tool',
	tasks: 'Tasks',
	closeTasks: 'Close',
	currentSession: 'Current session',
	otherSessions: 'Other sessions',
	noTasks: 'No tasks yet',
	cancelTask: 'Cancel',
	depth: 'Depth',
	sources: 'Sources',
	taskQueued: 'Queued',
	taskRunning: 'Running',
	taskCompleted: 'Completed',
	taskFailed: 'Failed',
	taskCancelled: 'Cancelled',
	copy: 'Copy',
	copied: 'Copied!',
	deleteMessage: 'Delete message',
	regenerateMessage: 'Regenerate',
	deleteMessageTitle: 'Delete Message',
	regenerateMessageTitle: 'Regenerate',
	regenerateMessageConfirm:
		'This will regenerate this AI response in place. The original response will be replaced, and subsequent messages will be preserved. This action cannot be undone.',
	deleteUserMessageConfirm:
		'This will delete this message and all following AI responses and tool results. This action cannot be undone.',
	deleteAssistantMessageConfirm:
		'This will delete this AI response. This action cannot be undone.',
	deleteToolMessageConfirm:
		'This will delete this tool result and remove the corresponding tool call from the AI message. This action cannot be undone.',
	deleteToolMessageRestoreWarning:
		'After deletion, these file changes can no longer be restored by recalling the message.',
	recallMessage: 'Recall',
	recallMessageTitle: 'Recall Message',
	recallMessageConfirm:
		'This will put the message content back into the input box and recall this message plus all following messages in the current fragment. This action cannot be undone.',
	recallMessageRestoreConfirm: 'Recall and restore files',
	confirmRecall: 'Recall',
}

export default en


================================================
FILE: packages/chatbox/src/i18n/locales/zh.ts
================================================
const zh = {
	history: '历史',
	deleteSession: '删除',
	deleteSessionTitle: '删除会话',
	deleteSessionMessage: '确认删除这个会话吗?删除后不可恢复。',
	cancel: '取消',
	confirmDelete: '确认删除',
	newChat: '新对话',
	provider: 'Provider',
	model: 'Model',
	noProvider: '未选择 Provider',
	noModel: '未选择 Model',
	send: '发送',
	queueSend: '加入挂起',
	thinking: '思考中',
	compressing: '压缩中',
	processingTools: '工具处理中',
	stopRun: '终止',
	empty: '开始发送一条消息',
	inputPlaceholder: '输入消息,Enter 发送,Shift+Enter 换行',
	newFragment: '新建段',
	compressContext: '压缩上下文',
	pendingMessages: '挂起消息',
	params: 'Params',
	result: 'Result',
	tool: '工具',
	tasks: '任务',
	closeTasks: '关闭',
	currentSession: '当前会话',
	otherSessions: '其他会话',
	noTasks: '还没有任务',
	cancelTask: '取消',
	depth: '深度',
	sources: '来源',
	taskQueued: '排队中',
	taskRunning: '运行中',
	taskCompleted: '已完成',
	taskFailed: '失败',
	taskCancelled: '已取消',
	copy: '复制',
	copied: '已复制',
	deleteMessage: '删除消息',
	regenerateMessage: '重新生成',
	deleteMessageTitle: '删除消息',
	regenerateMessageTitle: '重新生成',
	regenerateMessageConfirm:
		'此操作将重新生成该 AI 回复,原回复内容将被替换,其后的消息将被保留,无法恢复。',
	deleteUserMessageConfirm:
		'此操作将删除该用户消息,以及其后所有 AI 回复和工具调用结果,无法恢复。',
	deleteAssistantMessageConfirm: '此操作将删除该 AI 回复,无法恢复。',
	deleteToolMessageConfirm:
		'此操作将删除该工具调用结果,并从对应的 AI 消息中移除该工具调用记录,无法恢复。',
	deleteToolMessageRestoreWarning: '删除后将无法通过撤回消息恢复这些文件修改。',
	recallMessage: '撤回',
	recallMessageTitle: '撤回消息',
	recallMessageConfirm:
		'此操作将把消息内容放回输入框,并撤回该消息及当前段中之后的所有消息,无法恢复。',
	recallMessageRestoreConfirm: '撤回并还原修改',
	confirmRecall: '确认撤回',
}

export default zh


================================================
FILE: packages/chatbox/src/index.tsx
================================================
import './assets/styles/global.css'

import { createStore, reconcile } from 'solid-js/store'
import { render } from 'solid-js/web'
import App, { AppProps } from './App'
export * from './types'

export interface ChatboxController {
	update: (props: AppProps) => void
	destroy: () => void
}

export function mount(el: Element, props: AppProps): ChatboxController {
	let update = (_props: AppProps) => {}
	const destroy = render(() => {
		const [state, setState] = createStore(props)
		update = (nextProps: AppProps) => {
			setState(reconcile(nextProps))
		}
		return <App {...state} />
	}, el)

	return {
		update,
		destroy,
	}
}


================================================
FILE: packages/chatbox/src/types.ts
================================================
export interface ChatUsage {
	inputTokens?: number
	outputTokens?: number
	totalTokens?: number
}

export type ReversibleToolOp =
	| {
			vaultPath: string
			operation: 'create'
			before: { kind: 'file' | 'dir' }
	  }
	| {
			vaultPath: string
			operation: 'update'
			before: { kind: 'file'; contentBase64: string }
	  }
	| {
			vaultPath: string
			operation: 'delete'
			before: { kind: 'file'; contentBase64: string } | { kind: 'dir' }
	  }

export type ChatRunState =
	| 'idle'
	| 'thinking'
	| 'compressing'
	| 'waiting_for_tools'

export interface ChatTextPart {
	type: 'text'
	text: string
}

export interface ChatImageUrlPart {
	type: 'image_url'
	image_url: {
		url: string
	}
}

export interface ChatUnknownPart {
	type: 'unknown'
	value: unknown
}

export type ChatMessageContentPart =
	| ChatTextPart
	| ChatImageUrlPart
	| ChatUnknownPart

export interface ChatToolCall {
	id: string
	type: 'function'
	function: {
		name: string
		arguments: string
	}
}

export interface ChatMessageMeta {
	providerId?: string
	providerName?: string
	modelId?: string
	modelName?: string
	usage?: ChatUsage
}

export interface ChatSystemMessage {
	role: 'system'
	content: ChatMessageContentPart[]
}

export interface ChatUserMessage {
	role: 'user'
	content: ChatMessageContentPart[]
}

export interface ChatAssistantMessageWithContent {
	role: 'assistant'
	content: ChatMessageContentPart[]
	tool_calls?: ChatToolCall[]
}

export interface ChatAssistantMessageWithToolCalls {
	role: 'assistant'
	content?: null
	tool_calls: ChatToolCall[]
}

export interface ChatToolMessage {
	role: 'tool'
	content: ChatMessageContentPart[]
	name: string
	tool_call_id: string
}

export type ChatAssistantMessage =
	| ChatAssistantMessageWithContent
	| ChatAssistantMessageWithToolCalls

export type ChatMessage =
	| ChatSystemMessage
	| ChatUserMessage
	| ChatAssistantMessage
	| ChatToolMessage

export interface ChatMessageRecord {
	id: string
	createdAt: number
	message: ChatMessage
	meta?: ChatMessageMeta
	isError?: boolean
	reversibleOps?: ReversibleToolOp[]
}

export interface ChatTaskBase {
	id: string
	sessionId: string
	parentTaskId?: string
	depth: number
	maxDepth: number
	title: string
	prompt: string
	createdAt: number
}

export interface QueuedChatTask extends ChatTaskBase {
	status: 'queued'
}

export interface RunningChatTask extends ChatTaskBase {
	status: 'running'
	startedAt: number
}

export interface CompletedChatTask extends ChatTaskBase {
	status: 'completed'
	startedAt: number
	finishedAt: number
	summary: string
	sourceCount: number
}

export interface FailedChatTask extends ChatTaskBase {
	status: 'failed'
	finishedAt: number
	error: string
	summary?: string
	failureStage?: string
	startedAt?: number
	sourceCount?: number
}

export interface CancelledChatTask extends ChatTaskBase {
	status: 'cancelled'
	finishedAt: number
	cancelReason: string
	summary?: string
	startedAt?: number
}

export type ChatTaskRecord =
	| QueuedChatTask
	| RunningChatTask
	| CompletedChatTask
	| FailedChatTask
	| CancelledChatTask

export interface ChatPendingMessage {
	id: string
	createdAt: number
	text: string
}

export interface ChatModelOption {
	id: string
	name: string
}

export interface ChatProviderOption {
	id: string
	name: string
	models: ChatModelOption[]
}

export interface ChatSessionHistoryItem {
	id: string
	title: string
	createdAt: number
	updatedAt: number
}

export interface ChatTimelineFragmentItem {
	id: string
	kind: 'fragment'
	createdAt: number
}

export interface ChatTimelineMessageItem {
	id: string
	kind: 'message'
	createdAt: number
	message: ChatMessageRecord
	toolCall?: ChatToolCall
}

export type ChatTimelineItem =
	| ChatTimelineFragmentItem
	| ChatTimelineMessageItem

export interface ChatboxViewModel {
	title: string
	sessionHistory: ChatSessionHistoryItem[]
	activeSessionId?: string
	timeline: ChatTimelineItem[]
	currentSessionTasks: ChatTaskRecord[]
	otherSessionTasks: ChatTaskRecord[]
	providers: ChatProviderOption[]
	selectedProviderId?: string
	selectedModelId?: string
	runState: ChatRunState
	pendingMessages: ChatPendingMessage[]
	canSend: boolean
	canCreateFragment: boolean
	canCompress: boolean
}

export interface ChatboxProps extends ChatboxViewModel {
	onNewSession: () => void
	onNewFragment: () => void
	onCompressContext: () => Promise<void>
	onSwitchSession: (sessionId: string) => void
	onDeleteSession: (sessionId: string) => Promise<void>
	onSelectProvider: (providerId: string) => void
	onSelectModel: (modelId: string) => void
	onSendMessage: (text: string) => Promise<void>
	onStopActiveRun?: () => void
	onCancelTask?: (taskId: string) => void
	onDeleteMessage?: (messageId: string) => void
	onRegenerateMessage?: (messageId: string) => void
	onRecallMessage?: (
		messageId: string,
		options?: { restoreFiles?: boolean },
	) => Promise<void> | void
	renderMarkdown?: (
		el: HTMLElement,
		markdown: string,
	) => void | (() => void) | Promise<void | (() => void)>
}


================================================
FILE: packages/chatbox/src/utils.ts
================================================
import { ChatTaskRecord, ChatRunState } from './types'
import { t } from './i18n'

export function formatTime(timestamp: number) {
	return new Intl.DateTimeFormat(undefined, {
		month: '2-digit',
		day: '2-digit',
		hour: '2-digit',
		minute: '2-digit',
	}).format(timestamp)
}

export function formatFragmentTime(timestamp: number) {
	return new Intl.DateTimeFormat(undefined, {
		year: 'numeric',
		month: '2-digit',
		day: '2-digit',
		hour: '2-digit',
		minute: '2-digit',
	}).format(timestamp)
}

export function formatDuration(task: ChatTaskRecord) {
	if (!('startedAt' in task) || typeof task.startedAt !== 'number') {
		return ''
	}
	const end =
		'finishedAt' in task && typeof task.finishedAt === 'number'
			? task.finishedAt
			: Date.now()
	const totalSeconds = Math.max(0, Math.floor((end - task.startedAt) / 1000))
	const minutes = Math.floor(totalSeconds / 60)
	const seconds = totalSeconds % 60
	if (minutes > 0) {
		return `${minutes}m ${seconds}s`
	}
	return `${seconds}s`
}

export function formatUsage(input?: number, output?: number, total?: number) {
	if (
		typeof input !== 'number' &&
		typeof output !== 'number' &&
		typeof total !== 'number'
	) {
		return ''
	}
	const parts = []
	if (typeof total === 'number') {
		parts.push(`Tokens: ${total}`)
	}
	if (typeof input === 'number') {
		parts.push(`↑${input}`)
	}
	if (typeof output === 'number') {
		parts.push(`↓${output}`)
	}
	return parts.join(' ')
}

export function statusLabel(status: ChatTaskRecord['status']) {
	switch (status) {
		case 'queued':
			return t('taskQueued')
		case 'running':
			return t('taskRunning')
		case 'completed':
			return t('taskCompleted')
		case 'failed':
			return t('taskFailed')
		case 'cancelled':
			return t('taskCancelled')
	}
}

export function statusClass(status: ChatTaskRecord['status']) {
	switch (status) {
		case 'running':
			return 'bg-[var(--color-green-rgb)]/12 text-[var(--text-accent)]'
		case 'completed':
			return 'bg-[var(--color-cyan-rgb)]/12 text-[var(--text-normal)]'
		case 'failed':
			return 'bg-[var(--color-red-rgb)]/12 text-[var(--text-error)]'
		case 'cancelled':
			return 'bg-[var(--background-secondary)] text-[var(--text-muted)]'
		default:
			return 'bg-[var(--background-secondary)] text-[var(--text-normal)]'
	}
}

export function runStateLabel(runState: ChatRunState) {
	switch (runState) {
		case 'thinking':
			return t('thinking')
		case 'compressing':
			return t('compressing')
		case 'waiting_for_tools':
			return t('processingTools')
		default:
			return ''
	}
}


================================================
FILE: packages/chatbox/tsconfig.json
================================================
{
	"compilerOptions": {
		"lib": ["DOM", "ES2020"],
		"jsx": "preserve",
		"target": "ES2020",
		"noEmit": true,
		"skipLibCheck": true,
		"jsxImportSource": "solid-js",
		"useDefineForClassFields": true,

		/* modules */
		"module": "ESNext",
		"isolatedModules": true,
		"resolveJsonModule": true,
		"moduleResolution": "bundler",
		"allowImportingTsExtensions": true,

		/* type checking */
		"strict": true,
		"noUnusedLocals": true,
		"noUnusedParameters": true
	},
	"include": ["src"]
}


================================================
FILE: packages/chatbox/unocss.config.ts
================================================
import { defineConfig, presetIcons, presetUno } from 'unocss'

export default defineConfig({
	content: {
		filesystem: ['**/*.{html,js,ts,jsx,tsx,vue,svelte,astro}'],
	},
	rules: [
		[
			/^scrollbar-hide$/,
			([_]) => {
				return `.scrollbar-hide{scrollbar-width:none}
  .scrollbar-hide::-webkit-scrollbar{display:none}`
			},
		],
		[
			/^scrollbar-default$/,
			([_]) => {
				return `.scrollbar-default{scrollbar-width:auto}
  .scrollbar-default::-webkit-scrollbar{display:block}`
			},
		],
	],
	presets: [
		presetIcons({
			collections: {
				custom: {
					folder:
						'<svg id="图层_1" data-name="图层 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><title>folder</title><path d="M396.5,185.7l22.7,27.2a36.1,36.1,0,0,0,27.7,12.7H906.8c29.4,0,53.2,22.8,53.2,50.9V800.1c0,28.1-23.8,50.9-53.2,50.9H117.2C87.8,851,64,828.2,64,800.1V223.9c0-28.1,23.8-50.9,53.2-50.9H368.8A36.1,36.1,0,0,1,396.5,185.7Z" style="fill:#9fddff"/><path d="M64,342.5V797.8c0,29.4,24,53.2,53.6,53.2H906.4c29.6,0,53.6-23.8,53.6-53.2V342.5Z" style="fill:#74c6ff"/></svg>',
					file: '<svg id="图层_1" data-name="图层 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><title>unknown</title><path d="M186.9,64c-18.4,0-33.4,14.7-33.4,32.6V927.4c0,17.9,15,32.6,33.4,32.6H837.1c18.4,0,33.4-14.7,33.4-32.6V259.5L669.9,64Zm0,0" style="fill:#e3ecff"/><path d="M669.9,64V226.9c0,17.9,15,32.6,33.4,32.6H870.5Zm0,0" style="fill:#95a7cd"/><rect x="479.2" y="619.9" width="50" height="48.57" style="fill:#95a7cd"/><path d="M518.9,363.4h-6.1c-56.3,0-91.3,27.4-104,81.3l-1.3,5.6L450,464.3l1.3-7.1c6.9-36.9,25.7-54.1,59.3-54.1h4.6c28.1,2.6,42.8,15.6,46.2,40.6,2.6,20.4-10.1,40.2-37.7,58.9s-41.2,44-40.1,72.9v20.7h42.8V576.9c-.9-17.7,7.9-32.8,26.1-45,38.3-26.2,56.7-55.7,54.6-87.8C602.9,393.6,573.3,366.5,518.9,363.4Z" style="fill:#95a7cd"/></svg>',
				},
			},
		}),
		presetUno(),
	],
})


================================================
FILE: packages/webdav-explorer/package.json
================================================
{
	"name": "webdav-explorer",
	"version": "0.0.0",
	"type": "module",
	"exports": {
		".": {
			"types": "./dist/index.d.ts",
			"import": "./dist/index.js"
		}
	},
	"module": "./dist/index.js",
	"types": "./dist/index.d.ts",
	"files": [
		"dist"
	],
	"scripts": {
		"build": "rslib build",
		"dev": "rslib build --watch"
	},
	"devDependencies": {
		"@rsbuild/plugin-babel": "^1.0.4",
		"@rsbuild/plugin-solid": "^1.0.5",
		"@rslib/core": "^0.5.3",
		"@solid-primitives/i18n": "^2.2.0",
		"@solid-primitives/media": "^2.3.0",
		"@unocss/postcss": "66.1.0-beta.3",
		"typescript": "^5.8.2",
		"unocss": "66.1.0-beta.3"
	},
	"dependencies": {
		"solid-js": "^1.9.5"
	}
}


================================================
FILE: packages/webdav-explorer/postcss.config.mjs
================================================
import UnoCSS from '@unocss/postcss'

export default {
	plugins: [UnoCSS()],
}


================================================
FILE: packages/webdav-explorer/rslib.config.ts
================================================
import { pluginBabel } from '@rsbuild/plugin-babel'
import { pluginSolid } from '@rsbuild/plugin-solid'
import { defineConfig } from '@rslib/core'

export default defineConfig({
	source: {
		entry: {
			index: ['./src/**'],
		},
	},
	tools: {
		rspack: {
			plugins: [],
		},
	},
	lib: [
		{
			bundle: false,
			dts: true,
			format: 'esm',
		},
	],
	output: {
		target: 'web',
	},
	plugins: [
		pluginBabel({
			include: /\.(?:jsx|tsx)$/,
		}),
		pluginSolid(),
	],
})


================================================
FILE: packages/webdav-explorer/src/App.tsx
================================================
import { Notice } from 'obsidian'
import path from 'path-browserify'
import { createSignal, Show } from 'solid-js'
import { createFileList, FileStat } from './components/FileList'
import NewFolder from './components/NewFolder'
import { t } from './i18n'

type MaybePromise<T> = Promise<T> | T

export interface fs {
	ls: (path: string) => MaybePromise<FileStat[]>
	mkdirs: (path: string) => MaybePromise<void>
}

export interface AppProps {
	fs: fs
	onConfirm: (path: string) => void
	onClose: () => void
}

function App(props: AppProps) {
	const [stack, setStack] = createSignal<string[]>(['/'])
	const [showNewFolder, setShowNewFolder] = createSignal(false)
	const cwd = () => stack().at(-1)

	function enter(path: string) {
		setStack((stack) => [...stack, path])
	}

	function pop() {
		setStack((stack) =>
			stack.length > 1 ? stack.slice(0, stack.length - 1) : stack,
		)
	}

	const SingleCol = () => {
		const list = createFileList()
		return (
			<div class="flex-1 flex flex-col overflow-y-auto scrollbar-hide">
				<Show when={showNewFolder()}>
					<NewFolder
						class="mt-1"
						onCancel={() => setShowNewFolder(false)}
						onConfirm={async (name) => {
							const target = path.join(cwd() ?? '/', name)
							await Promise.resolve(props.fs.mkdirs(target))
								.then(() => {
									setShowNewFolder(false)
									list.refresh()
								})
								.catch((e) => {
									if (e instanceof Error) {
										new Notice(e.message)
									}
								})
						}}
					/>
				</Show>
				<list.FileList
					fs={props.fs}
					path={cwd() ?? ''}
					onClick={(f) => enter(f.path)}
				/>
			</div>
		)
	}

	return (
		<div class="flex flex-col gap-4 h-50vh">
			<SingleCol />
			<div class="flex gap-2 text-xs">
				<span>{t('currentPath')}:</span>
				<span class="break-all">{cwd() ?? '/'}</span>
			</div>
			<div class="flex items-center gap-2">
				<button onClick={pop}>{t('goBack')}</button>
				<a class="no-underline" onClick={() => setShowNewFolder(true)}>
					{t('newFolder')}
				</a>
				<div class="flex-1"></div>
				<button onClick={props.onClose}>{t('cancel')}</button>
				<button onclick={() => props.onConfirm(cwd() ?? '/')}>
					{t('confirm')}
				</button>
			</div>
		</div>
	)
}

export default App


================================================
FILE: packages/webdav-explorer/src/assets/styles/global.css
================================================
@unocss;


================================================
FILE: packages/webdav-explorer/src/components/File.tsx
================================================
export interface FolderProps {
	name: string
}

function File(props: FolderProps) {
	return (
		<div class="flex gap-2 items-center max-w-full border-rounded px-1 hover:cursor-not-allowed opacity-20">
			<div class="i-custom:file size-10" />
			<span class="truncate flex-1">{props.name}</span>
		</div>
	)
}

export default File


================================================
FILE: packages/webdav-explorer/src/components/FileList.tsx
================================================
import { Notice } from 'obsidian'
import { createEffect, createSignal, For, Show } from 'solid-js'
import { type fs } from '../App'
import File from './File'
import Folder from './Folder'

export interface FileStat {
	path: string
	basename: string
	isDir: boolean
}

export interface FileListProps {
	path: string
	fs: fs
	onClick: (file: FileStat) => void
}

export function createFileList() {
	const [version, setVersion] = createSignal(0)
	return {
		refresh() {
			setVersion((v) => ++v)
		},
		FileList(props: FileListProps) {
			const [items, setItems] = createSignal<FileStat[]>([])

			const sortedItems = () =>
				items().sort((a, b) => {
					if (a.isDir === b.isDir) {
						return a.basename.localeCompare(b.basename, ['zh'])
					}
					if (a.isDir && !b.isDir) {
						return -1
					} else {
						return 1
					}
				})

			async function refresh() {
				try {
					const items = await props.fs.ls(props.path)
					setItems(items)
				} catch (e) {
					if (e instanceof Error) {
						new Notice(e.message)
					}
				}
			}

			createEffect(async () => {
				if (version() === 0) {
					await refresh()
					return
				}
				setVersion(0)
			})

			return (
				<For each={sortedItems()}>
					{(f) => (
						<Show when={f.isDir} fallback={<File name={f.basename} />}>
							<Folder
								name={f.basename}
								path={f.path}
								onClick={() => props.onClick(f)}
							/>
						</Show>
					)}
				</For>
			)
		},
	}
}


================================================
FILE: packages/webdav-explorer/src/components/Folder.tsx
================================================
export interface FolderProps {
	name: string
	path: string
	onClick: (path: string) => void
}

function Folder(props: FolderProps) {
	return (
		<div
			class="flex gap-2 items-center max-w-full hover:bg-[var(--interactive-accent)] border-rounded px-1"
			onClick={() => props.onClick(props.path)}
		>
			<div class="i-custom:folder size-10" />
			<span class="truncate flex-1">{props.name}</span>
		</div>
	)
}

export default Folder


================================================
FILE: packages/webdav-explorer/src/components/NewFolder.tsx
================================================
import { createSignal } from 'solid-js'
import { t } from '../i18n'

interface NewFolderProps {
	class?: string
	onConfirm: (name: string) => void
	onCancel: () => void
}

function NewFolder(props: NewFolderProps) {
	const [name, setName] = createSignal('')

	const className = () => `flex items-center gap-2 px-1 ${props.class}`

	return (
		<div class={className()}>
			<div class="i-custom:folder size-10"></div>
			<input
				type="text"
				class="flex-1"
				autofocus
				value={name()}
				onInput={(e) => setName(e.target.value)}
			/>
			<button onClick={() => props.onConfirm(name())}>{t('confirm')}</button>
			<button onClick={() => props.onCancel()}>{t('cancel')}</button>
		</div>
	)
}

export default NewFolder


================================================
FILE: packages/webdav-explorer/src/i18n/index.ts
================================================
import * as i18n from '@solid-primitives/i18n'
import { createResource, createSignal } from 'solid-js'
import en from './locales/en'
import zh from './locales/zh'

export type Locale = 'zh' | 'en'

export function toLocale(language: string) {
	switch (language.split('-')[0].toLowerCase()) {
		case 'zh':
			return 'zh'
		default:
			return 'en'
	}
}

export const [locale, setLocale] = createSignal<Locale>(
	toLocale(navigator.language),
)

const [dict] = createResource(locale, (locale) => {
	switch (locale) {
		case 'zh':
			return i18n.flatten(zh)
		default:
			return i18n.flatten(en)
	}
})

export const t = i18n.translator(dict)


================================================
FILE: packages/webdav-explorer/src/i18n/locales/en.ts
================================================
const en = {
	newFolder: 'New Folder',
	goBack: 'Go Back',
	confirm: 'Confirm',
	cancel: 'Cancel',
	currentPath: 'Current Path',
}

export default en


================================================
FILE: packages/webdav-explorer/src/i18n/locales/zh.ts
================================================
const zh = {
	newFolder: '新建文件夹',
	goBack: '返回上一层',
	confirm: '确定',
	cancel: '取消',
	currentPath: '当前路径',
}

export default zh


================================================
FILE: packages/webdav-explorer/src/index.tsx
================================================
import './assets/styles/global.css'

import { render } from 'solid-js/web'
import App, { AppProps } from './App'

export function mount(el: Element, props: AppProps) {
	return render(() => <App {...props} />, el)
}


================================================
FILE: packages/webdav-explorer/tsconfig.json
================================================
{
	"compilerOptions": {
		"lib": ["DOM", "ES2020"],
		"jsx": "preserve",
		"target": "ES2020",
		"noEmit": true,
		"skipLibCheck": true,
		"jsxImportSource": "solid-js",
		"useDefineForClassFields": true,

		/* modules */
		"module": "ESNext",
		"isolatedModules": true,
		"resolveJsonModule": true,
		"moduleResolution": "bundler",
		"allowImportingTsExtensions": true,

		/* type checking */
		"strict": true,
		"noUnusedLocals": true,
		"noUnusedParameters": true
	},
	"include": ["src"]
}


================================================
FILE: packages/webdav-explorer/unocss.config.ts
================================================
import { defineConfig, presetIcons, presetUno } from 'unocss'

export default defineConfig({
	content: {
		filesystem: ['**/*.{html,js,ts,jsx,tsx,vue,svelte,astro}'],
	},
	rules: [
		[
			/^scrollbar-hide$/,
			([_]) => {
				return `.scrollbar-hide{scrollbar-width:none}
  .scrollbar-hide::-webkit-scrollbar{display:none}`
			},
		],
		[
			/^scrollbar-default$/,
			([_]) => {
				return `.scrollbar-default{scrollbar-width:auto}
  .scrollbar-default::-webkit-scrollbar{display:block}`
			},
		],
	],
	presets: [
		presetIcons({
			collections: {
				custom: {
					folder:
						'<svg id="图层_1" data-name="图层 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><title>folder</title><path d="M396.5,185.7l22.7,27.2a36.1,36.1,0,0,0,27.7,12.7H906.8c29.4,0,53.2,22.8,53.2,50.9V800.1c0,28.1-23.8,50.9-53.2,50.9H117.2C87.8,851,64,828.2,64,800.1V223.9c0-28.1,23.8-50.9,53.2-50.9H368.8A36.1,36.1,0,0,1,396.5,185.7Z" style="fill:#9fddff"/><path d="M64,342.5V797.8c0,29.4,24,53.2,53.6,53.2H906.4c29.6,0,53.6-23.8,53.6-53.2V342.5Z" style="fill:#74c6ff"/></svg>',
					file: '<svg id="图层_1" data-name="图层 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><title>unknown</title><path d="M186.9,64c-18.4,0-33.4,14.7-33.4,32.6V927.4c0,17.9,15,32.6,33.4,32.6H837.1c18.4,0,33.4-14.7,33.4-32.6V259.5L669.9,64Zm0,0" style="fill:#e3ecff"/><path d="M669.9,64V226.9c0,17.9,15,32.6,33.4,32.6H870.5Zm0,0" style="fill:#95a7cd"/><rect x="479.2" y="619.9" width="50" height="48.57" style="fill:#95a7cd"/><path d="M518.9,363.4h-6.1c-56.3,0-91.3,27.4-104,81.3l-1.3,5.6L450,464.3l1.3-7.1c6.9-36.9,25.7-54.1,59.3-54.1h4.6c28.1,2.6,42.8,15.6,46.2,40.6,2.6,20.4-10.1,40.2-37.7,58.9s-41.2,44-40.1,72.9v20.7h42.8V576.9c-.9-17.7,7.9-32.8,26.1-45,38.3-26.2,56.7-55.7,54.6-87.8C602.9,393.6,573.3,366.5,518.9,363.4Z" style="fill:#95a7cd"/></svg>',
				},
			},
		}),
		presetUno(),
	],
})


================================================
FILE: pnpm-workspace.yaml
================================================
packages:
  - packages/*


================================================
FILE: src/ai/bash/fs.ts
================================================
import {
	InMemoryFs,
	type BufferEncoding,
	type CpOptions,
	type FileContent,
	type FsStat,
	type IFileSystem,
	type MkdirOptions,
	type RmOptions,
} from 'just-bash/browser'
import {
	normalizePath,
	TFile,
	TFolder,
	type App,
	type TAbstractFile,
	type Vault,
} from 'obsidian'
import { posix as pathPosix } from 'path-browserify'
import type {
	AIDualPathFileOperation,
	AISinglePathFileOperation,
} from '~/ai/file-operation'
import type { PermissionGuard } from '~/ai/permission-guard'
import { cloneReversibleToolOp, type ReversibleToolOp } from '~/chat/domain'

const FILE_MODE = 0o644
const DIR_MODE = 0o755
const VAULT_MOUNT_POINT = '/vault'
type ReadFileOptions = { encoding?: BufferEncoding | null }
type WriteFileOptions = { encoding?: BufferEncoding }
type SnapshotKind = 'file' | 'dir'
type VaultSnapshotNode = {
	path: string
	kind: SnapshotKind
	contentBase64?: string
}

function encodeBase64(content: Uint8Array) {
	if (typeof Buffer !== 'undefined') {
		return Buffer.from(content).toString('base64')
	}
	let binary = ''
	for (const byte of content) {
		binary += String.fromCharCode(byte)
	}
	return btoa(binary)
}

function getEncoding(
	options?: ReadFileOptions | WriteFileOptions | BufferEncoding | null,
) {
	if (!options) {
		return 'utf8'
	}
	return typeof options === 'string' ? options : (options.encoding ?? 'utf8')
}

function decodeContent(
	content: Uint8Array,
	options?: ReadFileOptions | BufferEncoding,
) {
	const encoding = getEncoding(options)
	if (encoding === 'base64') {
		if (typeof Buffer !== 'undefined') {
			return Buffer.from(content).toString('base64')
		}
		let binary = ''
		for (const byte of content) {
			binary += String.fromCharCode(byte)
		}
		return btoa(binary)
	}
	return new TextDecoder(encoding === 'utf-8' ? 'utf-8' : 'utf-8').decode(
		content,
	)
}

function encodeContent(
	content: FileContent,
	options?: WriteFileOptions | BufferEncoding,
) {
	if (content instanceof Uint8Array) {
		return content
	}

	const encoding = getEncoding(options)
	if (encoding === 'base64') {
		if (typeof Buffer !== 'undefined') {
			return Uint8Array.from(Buffer.from(content, 'base64'))
		}
		const decoded = atob(content)
		return Uint8Array.from(decoded, (char) => char.charCodeAt(0))
	}

	return new TextEncoder().encode(content)
}

function toArrayBuffer(content: Uint8Array) {
	return content.buffer.slice(
		content.byteOffset,
		content.byteOffset + content.byteLength,
	) as ArrayBuffer
}

function getPathDepth(path: string) {
	return path.split('/').filter(Boolean).length
}

function normalizeVirtualPath(inputPath: string) {
	const normalized = pathPosix.normalize(pathPosix.resolve('/', inputPath))
	return normalized === '' ? '/' : normalized
}

function joinVirtualPath(parent: string, name: string) {
	return parent === '/' ? `/${name}` : `${parent}/${name}`
}

function ensureNotEscapingRoot(inputPath: string) {
	const normalized = normalizeVirtualPath(inputPath)
	if (!normalized.startsWith('/')) {
		throw new Error(`EINVAL: invalid path '${inputPath}'`)
	}
	return normalized
}

function normalizeReversibleVaultPath(path: string) {
	const normalized = ensureNotEscapingRoot(path)
	if (normalized === '/') {
		return ''
	}
	return normalizePath(normalized.slice(1))
}

function mapStat(stat: {
	type: 'file' | 'folder'
	size: number
	mtime: number
}): FsStat {
	return {
		isFile: stat.type === 'file',
		isDirectory: stat.type === 'folder',
		isSymbolicLink: false,
		mode: stat.type === 'folder' ? DIR_MODE : FILE_MODE,
		size: stat.type === 'file' ? stat.size : 0,
		mtime: new Date(stat.mtime),
	}
}

function mapAbstractFileStat(file: TAbstractFile): FsStat {
	if (file instanceof TFolder) {
		return mapStat({
			type: 'folder',
			size: 0,
			mtime: 0,
		})
	}

	return mapStat({
		type: 'file',
		size: (file as TFile).stat.size,
		mtime: (file as TFile).stat.mtime,
	})
}

async function copyRecursive(
	fs: IFileSystem,
	src: string,
	dest: string,
	options?: CpOptions,
) {
	const sourceStat = await fs.stat(src)
	if (sourceStat.isDirectory) {
		if (!options?.recursive) {
			throw new Error(`EISDIR: illegal operation on a directory, copy '${src}'`)
		}
		await fs.mkdir(dest, { recursive: true })
		for (const entry of await fs.readdir(src)) {
			await copyRecursive(
				fs,
				joinVirtualPath(src, entry),
				joinVirtualPath(dest, entry),
				options,
			)
		}
		return
	}

	const content = await fs.readFileBuffer(src)
	await fs.writeFile(dest, content)
}

async function removeRecursive(
	fs: IFileSystem,
	targetPath: string,
	options?: RmOptions,
) {
	const stat = await fs.stat(targetPath)
	if (stat.isDirectory) {
		const children = await fs.readdir(targetPath)
		if (children.length > 0 && !options?.recursive) {
			throw new Error(`ENOTEMPTY: directory not empty, remove '${targetPath}'`)
		}
		for (const child of children) {
			await removeRecursive(fs, joinVirtualPath(targetPath, child), options)
		}
	}
	await fs.rm(targetPath, options)
}

export async function listVaultPaths(app: App) {
	const paths = new Set<string>(['/'])
	const queue = [...app.vault.getRoot().children]

	while (queue.length > 0) {
		const current = queue.shift()
		if (!current) {
			continue
		}

		paths.add(`/${normalizePath(current.path)}`)
		if (current instanceof TFolder) {
			queue.push(...current.children)
		}
	}

	return [...paths]
}

export class ReversibleOpRecorder {
	private readonly operations: ReversibleToolOp[] = []

	recordCreate(vaultPath: string, kind: SnapshotKind) {
		const normalizedPath = normalizeReversibleVaultPath(vaultPath)
		if (!normalizedPath) {
			return
		}
		this.operations.push({
			vaultPath: normalizedPath,
			operation: 'create',
			before: { kind },
		})
	}

	recordUpdate(vaultPath: string, contentBase64: string) {
		const normalizedPath = normalizeReversibleVaultPath(vaultPath)
		if (!normalizedPath) {
			return
		}
		this.operations.push({
			vaultPath: normalizedPath,
			operation: 'update',
			before: {
				kind: 'file',
				contentBase64,
			},
		})
	}

	recordDelete(snapshot: VaultSnapshotNode) {
		const normalizedPath = normalizeReversibleVaultPath(snapshot.path)
		if (!normalizedPath) {
			return
		}
		this.operations.push({
			vaultPath: normalizedPath,
			operation: 'delete',
			before:
				snapshot.kind === 'dir'
					? { kind: 'dir' }
					: {
							kind: 'file',
							contentBase64: snapshot.contentBase64 || '',
						},
		})
	}

	getOperations(): ReversibleToolOp[] {
		return this.operations.map(cloneReversibleToolOp)
	}
}

export class ObsidianVaultFs implements IFileSystem {
	private readonly snapshot = new Set<string>()
	private _batchDepth = 0

	constructor(
		private readonly vault: Vault,
		initialPaths: string[] = [],
		private readonly permissionGuard?: PermissionGuard,
		private readonly recorder?: ReversibleOpRecorder,
	) {
		for (const path of initialPaths) {
			this.snapshot.add(ensureNotEscapingRoot(path))
		}
		this.snapshot.add('/')
	}

	private async withBatch<T>(fn: () => Promise<T>): Promise<T> {
		this._batchDepth++
		try {
			return await fn()
		} finally {
			this._batchDepth--
		}
	}

	private async checkPermission(
		request:
			| { kind: AISinglePathFileOperation; path: string }
			| { kind: AIDualPathFileOperation; src: string; dest: string },
	): Promise<void> {
		if (this._batchDepth > 0 || !this.permissionGuard) return
		const normalizedRequest =
			'src' in request
				? {
						type: 'fs' as const,
						fs: {
							kind: request.kind,
							src: this.toPermissionPath(request.src),
							dest: this.toPermissionPath(request.dest),
						},
					}
				: {
						type: 'fs' as const,
						fs: {
							kind: request.kind,
							path: this.toPermissionPath(request.path),
						},
					}
		await this.permissionGuard({
			...normalizedRequest,
		})
	}

	private toPermissionPath(path: string) {
		const normalized = ensureNotEscapingRoot(path)
		return normalized === '/'
			? VAULT_MOUNT_POINT
			: `${VAULT_MOUNT_POINT}${normalized}`
	}

	private toVaultPath(inputPath: string) {
		const normalized = ensureNotEscapingRoot(inputPath)
		return normalized === '/' ? '' : normalizePath(normalized.slice(1))
	}

	private async statInternal(inputPath: string) {
		const target = this.vault.getAbstractFileByPath(this.toVaultPath(inputPath))
		if (!target) {
			throw new Error(`ENOENT: no such file or directory, stat '${inputPath}'`)
		}
		return target
	}

	private async readFileContentBase64(target: TFile) {
		return encodeBase64(
			new Uint8Array(
				(await this.vault.readBinary(target as never)) as ArrayBuffer,
			),
		)
	}

	private async snapshotNode(
		target:
			| TAbstractFile
			| { path: string; name: string; children?: unknown[] },
		virtualPath: string,
	): Promise<VaultSnapshotNode[]> {
		if (target instanceof TFolder) {
			const children = [...target.children].sort((left, right) =>
				left.path.localeCompare(right.path),
			)
			const snapshots: VaultSnapshotNode[] = []
			for (const child of children) {
				snapshots.push(
					...(await this.snapshotNode(
						child,
						joinVirtualPath(virtualPath, child.name),
					)),
				)
			}
			snapshots.push({ path: virtualPath, kind: 'dir' })
			return snapshots
		}

		return [
			{
				path: virtualPath,
				kind: 'file',
				contentBase64: await this.readFileContentBase64(target as TFile),
			},
		]
	}

	private async snapshotSubtree(path: string) {
		const normalized = ensureNotEscapingRoot(path)
		const target = this.vault.getAbstractFileByPath(
			this.toVaultPath(normalized),
		)
		if (!target) {
			return []
		}
		return this.snapshotNode(target, normalized)
	}

	private toSnapshotMap(entries: VaultSnapshotNode[]) {
		return new Map(entries.map((entry) => [entry.path, entry]))
	}

	private recordDeleteSnapshots(entries: VaultSnapshotNode[]) {
		if (!this.recorder) {
			return
		}
		for (const entry of entries) {
			this.recorder.recordDelete(entry)
		}
	}

	private recordTargetDiff(
		beforeEntries: VaultSnapshotNode[],
		afterEntries: VaultSnapshotNode[],
	) {
		if (!this.recorder) {
			return
		}
		const beforeByPath = this.toSnapshotMap(beforeEntries)
		const afterByPath = this.toSnapshotMap(afterEntries)

		for (const entry of afterEntries.sort((left, right) => {
			const depthDelta = getPathDepth(left.path) - getPathDepth(right.path)
			return depthDelta !== 0 ? depthDelta : left.path.localeCompare(right.path)
		})) {
			const previous = beforeByPath.get(entry.path)
			if (!previous) {
				this.recorder.recordCreate(entry.path, entry.kind)
				continue
			}
			if (previous.kind !== entry.kind) {
				this.recorder.recordDelete(previous)
				this.recorder.recordCreate(entry.path, entry.kind)
				continue
			}
			if (
				entry.kind === 'file' &&
				previous.contentBase64 !== entry.contentBase64
			) {
				this.recorder.recordUpdate(entry.path, previous.contentBase64 || '')
			}
		}

		for (const entry of beforeEntries
			.filter((entry) => !afterByPath.has(entry.path))
			.sort((left, right) => {
				const depthDelta = getPathDepth(right.path) - getPathDepth(left.path)
				return depthDelta !== 0
					? depthDelta
					: left.path.localeCompare(right.path)
			})) {
			this.recorder.recordDelete(entry)
		}
	}

	private async deleteAbstractFile(target: TAbstractFile) {
		if (typeof this.vault.trash === 'function') {
			await this.vault.trash(target, false)
			return
		}
		if (typeof this.vault.delete === 'function') {
			await this.vault.delete(target, false)
			return
		}
		throw new Error(
			`ENOTSUP: vault delete is not available for '${target.path}'`,
		)
	}

	private recordPath(inputPath: string) {
		const normalized = ensureNotEscapingRoot(inputPath)
		const parts = normalized.split('/').filter(Boolean)
		this.snapshot.add('/')
		let current = ''
		for (const part of parts) {
			current = `${current}/${part}`
			this.snapshot.add(current)
		}
	}

	private forgetPath(inputPath: string) {
		const normalized = ensureNotEscapingRoot(inputPath)
		for (const path of [...this.snapshot]) {
			if (path === normalized || path.startsWith(`${normalized}/`)) {
				this.snapshot.delete(path)
			}
		}
		this.snapshot.add('/')
	}

	private assertExists(path: string) {
		return this.exists(path).then((exists) => {
			if (!exists) {
				throw new Error(`ENOENT: no such file or directory, access '${path}'`)
			}
		})
	}

	async readFile(
		path: string,
		options?: ReadFileOptions | BufferEncoding,
	): Promise<string> {
		return this.withBatch(() =>
			this.readFileBuffer(path).then((buf) => decodeContent(buf, options)),
		)
	}

	async readFileBuffer(path: string): Promise<Uint8Array> {
		const stat = await this.stat(path)
		if (!stat.isFile) {
			throw new Error(
				`EISDIR: illegal operation on a directory, read '${path}'`,
			)
		}
		const target = this.vault.getAbstractFileByPath(this.toVaultPath(path))
		if (!(target instanceof TFile)) {
			throw new Error(`ENOENT: no such file or directory, read '${path}'`)
		}
		const buffer = await this.vault.readBinary(target as never)
		return new Uint8Array(buffer as ArrayBuffer)
	}

	async writeFile(
		path: string,
		content: FileContent,
		options?: WriteFileOptions | BufferEncoding,
	): Promise<void> {
		await this.checkPermission({ kind: 'write', path })
		await this.withBatch(async () => {
			await this.mkdir(pathPosix.dirname(ensureNotEscapingRoot(path)), {
				recursive: true,
			})
			const encoded = encodeContent(content, options)
			const vaultPath = this.toVaultPath(path)
			const target = this.vault.getAbstractFileByPath(vaultPath)
			if (target) {
				if (!(target instanceof TFile)) {
					throw new Error(
						`EISDIR: illegal operation on a directory, write '${path}'`,
					)
				}
				this.recorder?.recordUpdate(
					path,
					await this.readFileContentBase64(target),
				)
				await this.vault.modifyBinary(target as never, toArrayBuffer(encoded))
			} else {
				await this.vault.createBinary(vaultPath, toArrayBuffer(encoded))
				this.recorder?.recordCreate(path, 'file')
			}
			this.recordPath(path)
		})
	}

	async appendFile(
		path: string,
		content: FileContent,
		options?: WriteFileOptions | BufferEncoding,
	): Promise<void> {
		await this.checkPermission({ kind: 'write', path })
		await this.withBatch(async () => {
			const encoded = encodeContent(content, options)
			const existing = (await this.exists(path))
				? await this.readFileBuffer(path)
				: (new Uint8Array(0) as Uint8Array)
			const merged = new Uint8Array(existing.length + encoded.length)
			merged.set(existing)
			merged.set(encoded, existing.length)
			await this.writeFile(path, merged)
		})
	}

	async exists(path: string): Promise<boolean> {
		const normalized = ensureNotEscapingRoot(path)
		if (normalized === '/') {
			return true
		}
		return Boolean(
			this.vault.getAbstractFileByPath(this.toVaultPath(normalized)),
		)
	}

	async stat(path: string): Promise<FsStat> {
		if (ensureNotEscapingRoot(path) === '/') {
			return {
				isFile: false,
				isDirectory: true,
				isSymbolicLink: false,
				mode: DIR_MODE,
				size: 0,
				mtime: new Date(0),
			}
		}
		return mapAbstractFileStat(await this.statInternal(path))
	}

	async mkdir(path: string, options?: MkdirOptions): Promise<void> {
		const normalized = ensureNotEscapingRoot(path)
		if (normalized === '/') {
			return
		}
		await this.checkPermission({ kind: 'mkdir', path })

		const segments = normalized.split('/').filter(Boolean)
		let current = ''
		for (let index = 0; index < segments.length; index += 1) {
			current = `${current}/${segments[index]}`
			if (await this.exists(current)) {
				continue
			}
			if (!options?.recursive && index !== segments.length - 1) {
				throw new Error(
					`ENOENT: no such file or directory, mkdir '${normalized}'`,
				)
			}
			await this.vault.createFolder(this.toVaultPath(current))
			this.recorder?.recordCreate(current, 'dir')
			this.recordPath(current)
		}
	}

	async readdir(path: string): Promise<string[]> {
		const stat = await this.stat(path)
		if (!stat.isDirectory) {
			throw new Error(`ENOTDIR: not a directory, scandir '${path}'`)
		}
		const target =
			this.toVaultPath(path) === ''
				? this.vault.getRoot()
				: this.vault.getAbstractFileByPath(this.toVaultPath(path))
		if (!(target instanceof TFolder)) {
			throw new Error(`ENOTDIR: not a directory, scandir '${path}'`)
		}
		return [...target.children]
			.map((item) => item.name)
			.filter((item): item is string => Boolean(item))
			.sort()
	}

	async readdirWithFileTypes(path: string) {
		const stat = await this.stat(path)
		if (!stat.isDirectory) {
			throw new Error(`ENOTDIR: not a directory, scandir '${path}'`)
		}
		const target =
			this.toVaultPath(path) === ''
				? this.vault.getRoot()
				: this.vault.getAbstractFileByPath(this.toVaultPath(path))
		if (!(target instanceof TFolder)) {
			throw new Error(`ENOTDIR: not a directory, scandir '${path}'`)
		}
		return [...target.children]
			.map((item) => ({
				name: item.name,
				isFile: item instanceof TFile,
				isDirectory: item instanceof TFolder,
				isSymbolicLink: false,
			}))
			.sort((left, right) => left.name.localeCompare(right.name))
	}

	async rm(path: string, options?: RmOptions): Promise<void> {
		const normalized = ensureNotEscapingRoot(path)
		if (normalized === '/') {
			throw new Error(`EPERM: operation not permitted, remove '${path}'`)
		}
		await this.checkPermission({ kind: 'delete', path })

		if (!(await this.exists(normalized))) {
			if (options?.force) {
				return
			}
			throw new Error(`ENOENT: no such file or directory, remove '${path}'`)
		}

		const target = this.vault.getAbstractFileByPath(
			this.toVaultPath(normalized),
		)
		if (!target) {
			throw new Error(`ENOENT: no such file or directory, remove '${path}'`)
		}
		this.recordDeleteSnapshots(await this.snapshotSubtree(normalized))
		await this.deleteAbstractFile(target)
		this.forgetPath(normalized)
	}

	async cp(src: string, dest: string, options?: CpOptions): Promise<void> {
		await this.checkPermission({ kind: 'copy', src, dest })
		await this.withBatch(() => copyRecursive(this, src, dest, options))
	}

	async mv(src: string, dest: string): Promise<void> {
		await this.checkPermission({ kind: 'move', src, dest })
		await this.withBatch(async () => {
			const sourceSnapshots = await this.snapshotSubtree(src)
			if (sourceSnapshots.length === 0) {
				throw new Error(`ENOENT: no such file or directory, move '${src}'`)
			}
			const destSnapshotsBefore = await this.snapshotSubtree(dest)
			await this.mkdir(pathPosix.dirname(ensureNotEscapingRoot(dest)), {
				recursive: true,
			})
			const target = this.vault.getAbstractFileByPath(this.toVaultPath(src))
			if (!target) {
				throw new Error(`ENOENT: no such file or directory, move '${src}'`)
			}
			this.recordDeleteSnapshots(sourceSnapshots)
			await this.vault.rename(target, this.toVaultPath(dest))
			this.forgetPath(src)
			this.recordPath(dest)
			this.recordTargetDiff(
				destSnapshotsBefore,
				await this.snapshotSubtree(dest),
			)
		})
	}

	resolvePath(base: string, path: string): string {
		return ensureNotEscapingRoot(pathPosix.resolve(base || '/', path))
	}

	getAllPaths(): string[] {
		return [...this.snapshot].sort()
	}

	async chmod(path: string, _mode: number): Promise<void> {
		await this.assertExists(path)
	}

	async symlink(_target: string, linkPath: string): Promise<void> {
		throw new Error(
			`ENOTSUP: symbolic links are not supported in vault fs, link '${linkPath}'`,
		)
	}

	async link(_existingPath: string, newPath: string): Promise<void> {
		throw new Error(
			`ENOTSUP: hard links are not supported in vault fs, link '${newPath}'`,
		)
	}

	async readlink(path: string): Promise<string> {
		throw new Error(`EINVAL: not a symbolic link, readlink '${path}'`)
	}

	async lstat(path: string): Promise<FsStat> {
		return this.stat(path)
	}

	async realpath(path: string): Promise<string> {
		await this.assertExists(path)
		return ensureNotEscapingRoot(path)
	}

	async utimes(path: string, _atime: Date, _mtime: Date): Promise<void> {
		await this.withBatch(async () => {
			const stat = await this.stat(path)
			if (stat.isDirectory) {
				return
			}
			const content = await this.readFileBuffer(path)
			await this.writeFile(path, content)
		})
	}
}

export class MountedVaultFs implements IFileSystem {
	private readonly scratch = new InMemoryFs()

	constructor(private readonly vaultFs: ObsidianVaultFs) {}

	private isRoot(path: string) {
		return ensureNotEscapingRoot(path) === '/'
	}

	private isVaultMount(path: string) {
		return ensureNotEscapingRoot(path) === VAULT_MOUNT_POINT
	}

	private isVaultPath(path: string) {
		const normalized = ensureNotEscapingRoot(path)
		return (
			normalized === VAULT_MOUNT_POINT ||
			normalized.startsWith(`${VAULT_MOUNT_POINT}/`)
		)
	}

	private toVaultRelative(path: string) {
		const normalized = ensureNotEscapingRoot(path)
		if (normalized === VAULT_MOUNT_POINT) {
			return '/'
		}
		return normalized.slice(VAULT_MOUNT_POINT.length) || '/'
	}

	private route(path: string) {
		const normalized = ensureNotEscapingRoot(path)
		if (this.isVaultPath(normalized)) {
			return {
				fs: this.vaultFs as IFileSystem,
				path: this.toVaultRelative(normalized),
			}
		}
		return {
			fs: this.scratch as IFileSystem,
			path: normalized,
		}
	}

	private async genericCp(src: string, dest: string, options?: CpOptions) {
		const sourceStat = await this.stat(src)
		if (sourceStat.isDirectory) {
			if (!options?.recursive) {
				throw new Error(
					`EISDIR: illegal operation on a directory, copy '${src}'`,
				)
			}
			await this.mkdir(dest, { recursive: true })
			for (const entry of await this.readdir(src)) {
				await this.genericCp(
					joinVirtualPath(src, entry),
					joinVirtualPath(dest, entry),
					options,
				)
			}
			return
		}
		await this.writeFile(dest, await this.readFileBuffer(src))
	}

	async readFile(
		path: string,
		options?: ReadFileOptions | BufferEncoding,
	): Promise<string> {
		if (this.isVaultMount(path)) {
			throw new Error(
				`EISDIR: illegal operation on a directory, read '${path}'`,
			)
		}
		const routed = this.route(path)
		return routed.fs.readFile(routed.path, options)
	}

	async readFileBuffer(path: string): Promise<Uint8Array> {
		if (this.isVaultMount(path)) {
			throw new Error(
				`EISDIR: illegal operation on a directory, read '${path}'`,
			)
		}
		const routed = this.route(path)
		return routed.fs.readFileBuffer(routed.path)
	}

	async writeFile(
		path: string,
		content: FileContent,
		options?: WriteFileOptions | BufferEncoding,
	): Promise<void> {
		if (this.isRoot(path) || this.isVaultMount(path)) {
			throw new Error(
				`EISDIR: illegal operation on a directory, write '${path}'`,
			)
		}
		const routed = this.route(path)
		await routed.fs.writeFile(routed.path, content, options)
	}

	async appendFile(
		path: string,
		content: FileContent,
		options?: WriteFileOptions | BufferEncoding,
	): Promise<void> {
		if (this.isRoot(path) || this.isVaultMount(path)) {
			throw new Error(
				`EISDIR: illegal operation on a directory, append '${path}'`,
			)
		}
		const routed = this.route(path)
		await routed.fs.appendFile(routed.path, content, options)
	}

	async exists(path: string): Promise<boolean> {
		if (this.isRoot(path) || this.isVaultMount(path)) {
			return true
		}
		const routed = this.route(path)
		return routed.fs.exists(routed.path)
	}

	async stat(path: string): Promise<FsStat> {
		if (this.isRoot(path) || this.isVaultMount(path)) {
			return {
				isFile: false,
				isDirectory: true,
				isSymbolicLink: false,
				mode: DIR_MODE,
				size: 0,
				mtime: new Date(0),
			}
		}
		const routed = this.route(path)
		return routed.fs.stat(routed.path)
	}

	async mkdir(path: string, options?: MkdirOptions): Promise<void> {
		if (this.isRoot(path) || this.isVaultMount(path)) {
			return
		}
		const routed = this.route(path)
		await routed.fs.mkdir(routed.path, options)
	}

	async readdir(path: string): Promise<string[]> {
		if (this.isRoot(path)) {
			const base = await this.scratch.readdir('/')
			return [...new Set(['vault', ...base])].sort()
		}
		if (this.isVaultMount(path)) {
			return this.vaultFs.readdir('/')
		}
		const routed = this.route(path)
		return routed.fs.readdir(routed.path)
	}

	async readdirWithFileTypes(path: string) {
		if (this.isRoot(path)) {
			const base = this.scratch.readdirWithFileTypes
				? await this.scratch.readdirWithFileTypes('/')
				: (await this.scratch.readdir('/')).map((name) => ({
						name,
						isFile: true,
						isDirectory: false,
						isSymbolicLink: false,
					}))
			return [
				{
					name: 'vault',
					isFile: false,
					isDirectory: true,
					isSymbolicLink: false,
				},
				...base.filter((entry) => entry.name !== 'vault'),
			].sort((left, right) => left.name.localeCompare(right.name))
		}
		if (this.isVaultMount(path)) {
			return this.vaultFs.readdirWithFileTypes?.('/') ?? []
		}
		const routed = this.route(path)
		return routed.fs.readdirWithFileTypes?.(routed.path) ?? []
	}

	async rm(path: string, options?: RmOptions): Promise<void> {
		if (this.isRoot(path) || this.isVaultMount(path)) {
			throw new Error(`EPERM: operation not permitted, remove '${path}'`)
		}
		const routed = this.route(path)
		return routed.fs.rm(routed.path, options)
	}

	async cp(src: string, dest: string, options?: CpOptions): Promise<void> {
		await this.genericCp(src, dest, options)
	}

	async mv(src: string, dest: string): Promise<void> {
		if (this.isRoot(src) || this.isVaultMount(src)) {
			throw new Error(`EPERM: operation not permitted, move '${src}'`)
		}
		const source = this.route(src)
		const target = this.route(dest)
		if (source.fs === target.fs) {
			await source.fs.mv(source.path, target.path)
			return
		}
		await this.genericCp(src, dest, { recursive: true })
		await removeRecursive(this, src, { recursive: true, force: false })
	}

	resolvePath(base: string, path: string): string {
		return ensureNotEscapingRoot(pathPosix.resolve(base || '/', path))
	}

	getAllPaths(): string[] {
		const basePaths = this.scratch.getAllPaths().filter((path) => path !== '/')
		const vaultPaths = this.vaultFs
			.getAllPaths()
			.filter((path) => path !== '/')
			.map((path) => `${VAULT_MOUNT_POINT}${path}`)
		return ['/', VAULT_MOUNT_POINT, ...basePaths, ...vaultPaths].sort()
	}

	async chmod(path: string, mode: number): Promise<void> {
		if (this.isRoot(path) || this.isVaultMount(path)) {
			return
		}
		const routed = this.route(path)
		await routed.fs.chmod(routed.path, mode)
	}

	async symlink(target: string, linkPath: string): Promise<void> {
		if (this.isVaultPath(linkPath) || this.isVaultPath(target)) {
			throw new Error(
				`ENOTSUP: symbolic links are not supported in vault fs, link '${linkPath}'`,
			)
		}
		return this.scratch.symlink(target, linkPath)
	}

	async link(existingPath: string, newPath: string): Promise<void> {
		if (this.isVaultPath(existingPath) || this.isVaultPath(newPath)) {
			throw new Error(
				`ENOTSUP: hard links are not supported in vault fs, link '${newPath}'`,
			)
		}
		return this.scratch.link(existingPath, newPath)
	}

	async readlink(path: string): Promise<string> {
		if (this.isVaultPath(path)) {
			throw new Error(`EINVAL: not a symbolic link, readlink '${path}'`)
		}
		return this.scratch.readlink(path)
	}

	async lstat(path: string): Promise<FsStat> {
		return this.stat(path)
	}

	async realpath(path: string): Promise<string> {
		await this.stat(path)
		return ensureNotEscapingRoot(path)
	}

	async utimes(path: string, atime: Date, mtime: Date): Promise<void> {
		if (this.isRoot(path) || this.isVaultMount(path)) {
			return
		}
		const routed = this.route(path)
		await routed.fs.utimes(routed.path, atime, mtime)
	}
}

export { VAULT_MOUNT_POINT }


================================================
FILE: src/ai/bash/runtime.test.ts
================================================
import { describe, expect, it } from 'vitest'
import type { App, Vault } from 'obsidian'
import type { PermissionRequest } from '~/ai/permission-guard'
import { createVaultBash, execVaultBash, VAULT_MOUNT_POINT } from './runtime'
import {
	listVaultPaths,
	MountedVaultFs,
	ObsidianVaultFs,
	ReversibleOpRecorder,
} from './fs'

interface MockEntryFile {
	type: 'file'
	content: Uint8Array
	mtime: number
}

interface MockEntryFolder {
	type: 'folder'
	mtime: number
}

type MockEntry = MockEntryFile | MockEntryFolder

interface MockAbstractFile {
	path: string
	name: string
	parent: MockFolder | null
}

interface MockFile extends MockAbstractFile {
	stat: {
		size: number
		mtime: number
	}
}

interface MockFolder extends MockAbstractFile {
	children: Array<MockFile | MockFolder>
}

class MemoryVaultStore {
	private readonly entries = new Map<string, MockEntry>([
		['', { type: 'folder', mtime: 0 }],
	])

	constructor(
		initialFiles: Record<string, string> = {},
		initialFolders: string[] = [],
	) {
		for (const folder of initialFolders) {
			this.ensureFolder(folder)
		}
		for (const [path, content] of Object.entries(initialFiles)) {
			this.writeBinary(path, new TextEncoder().encode(content).buffer)
		}
	}

	normalize(path: string) {
		return path.replace(/^\/+|\/+$/g, '')
	}

	dirname(path: string) {
		if (!path || !path.includes('/')) {
			return ''
		}
		return path.slice(0, path.lastIndexOf('/'))
	}

	basename(path: string) {
		if (!path) {
			return ''
		}
		const normalized = this.normalize(path)
		return normalized.slice(normalized.lastIndexOf('/') + 1)
	}

	ensureFolder(path: string) {
		const normalized = this.normalize(path)
		if (!normalized) {
			return
		}
		const parent = this.dirname(normalized)
		if (parent !== normalized) {
			this.ensureFolder(parent)
		}
		if (!this.entries.has(normalized)) {
			this.entries.set(normalized, { type: 'folder', mtime: Date.now() })
		}
	}

	exists(path: string) {
		return this.entries.has(this.normalize(path))
	}

	stat(path: string) {
		const entry = this.entries.get(this.normalize(path))
		if (!entry) {
			return null
		}
		return {
			type: entry.type,
			ctime: entry.mtime,
			mtime: entry.mtime,
			size: entry.type === 'file' ? entry.content.byteLength : 0,
		}
	}

	readBinary(path: string) {
		const entry = this.entries.get(this.normalize(path))
		if (!entry || entry.type !== 'file') {
			throw new Error(`missing file: ${path}`)
		}
		return entry.content.buffer.slice(
			entry.content.byteOffset,
			entry.content.byteOffset + entry.content.byteLength,
		) as ArrayBuffer
	}

	writeBinary(path: string, data: ArrayBuffer) {
		const normalized = this.normalize(path)
		this.ensureFolder(this.dirname(normalized))
		this.entries.set(normalized, {
			type: 'file',
			content: new Uint8Array(data),
			mtime: Date.now(),
		})
	}

	remove(path: string) {
		this.entries.delete(this.normalize(path))
	}

	removeRecursive(path: string) {
		const normalized = this.normalize(path)
		for (const key of [...this.entries.keys()]) {
			if (key === normalized || key.startsWith(`${normalized}/`)) {
				this.entries.delete(key)
			}
		}
	}

	rename(fromPath: string, toPath: string) {
		const from = this.normalize(fromPath)
		const to = this.normalize(toPath)
		this.ensureFolder(this.dirname(to))
		const moved = [...this.entries.entries()]
			.filter(([key]) => key === from || key.startsWith(`${from}/`))
			.sort((left, right) => left[0].length - right[0].length)
		for (const [key, value] of moved) {
			this.entries.delete(key)
			const suffix = key.slice(from.length)
			this.entries.set(
				`${to}${suffix}`,
				value.type === 'folder'
					? { ...value }
					: { ...value, content: value.content.slice() },
			)
		}
	}

	listChildren(path: string) {
		const normalized = this.normalize(path)
		const prefix = normalized ? `${normalized}/` : ''
		return [...this.entries.keys()]
			.filter((key) => key.startsWith(prefix) && key !== normalized)
			.filter((key) => !key.slice(prefix.length).includes('/'))
			.sort()
	}
}

function createMockVault(
	initialFiles: Record<string, string> = {},
	initialFolders: string[] = [],
) {
	const store = new MemoryVaultStore(initialFiles, initialFolders)

	const buildFolder = (path: string, parent: MockFolder | null): MockFolder => {
		const normalized = store.normalize(path)
		const folder: MockFolder = {
			path: normalized,
			name: normalized ? store.basename(normalized) : '',
			parent,
			children: [],
		}
		folder.children = store.listChildren(normalized).map((childPath) => {
			const childStat = store.stat(childPath)
			if (childStat?.type === 'folder') {
				return buildFolder(childPath, folder)
			}
			return {
				path: childPath,
				name: store.basename(childPath),
				parent: folder,
				stat: {
					size: childStat?.size ?? 0,
					mtime: childStat?.mtime ?? 0,
				},
			} satisfies MockFile
		})
		return folder
	}

	const root = () => buildFolder('', null)

	const vault = {
		getRoot() {
			return root()
		},
		getAbstractFileByPath(path: string) {
			const normalized = store.normalize(path)
			if (!normalized) {
				return root()
			}
			const stat = store.stat(normalized)
			if (!stat) {
				return null
			}
			const parentPath = store.dirname(normalized)
			const parent =
				parentPath === normalized ? null : buildFolder(parentPath, null)
			if (stat.type === 'folder') {
				return buildFolder(normalized, parent)
			}
			return {
				path: normalized,
				name: store.basename(normalized),
				parent,
				stat: {
					size: stat.size,
					mtime: stat.mtime,
				},
			} satisfies MockFile
		},
		async readBinary(file: MockFile) {
			return store.readBinary(file.path)
		},
		async createBinary(path: string, data: ArrayBuffer) {
			store.writeBinary(path, data)
			return vault.getAbstractFileByPath(path)
		},
		async cachedRead(file: MockFile) {
			return new TextDecoder().decode(store.readBinary(file.path))
		},
		async modifyBinary(file: MockFile, data: ArrayBuffer) {
			store.writeBinary(file.path, data)
		},
		async modify(file: MockFile, content: string) {
			store.writeBinary(file.path, new TextEncoder().encode(content).buffer)
		},
		async createFolder(path: string) {
			store.ensureFolder(path)
			return vault.getAbstractFileByPath(path)
		},
		async delete(file: MockFile | MockFolder) {
			const stat = store.stat(file.path)
			if (stat?.type === 'folder') {
				store.removeRecursive(file.path)
				return
			}
			store.remove(file.path)
		},
		async trash(file: MockFile | MockFolder) {
			return vault.delete(file as never)
		},
		async rename(file: MockFile | MockFolder, newPath: string) {
			store.rename(file.path, newPath)
		},
	} as unknown as Vault

	return {
		vault,
		store,
	}
}

function createApp(vault: Vault) {
	return {
		vault,
	} as unknown as App
}

describe('vault bash runtime', () => {
	it('builds a vault path snapshot for globbing', async () => {
		const { vault } = createMockVault(
			{
				'notes/today.md': 'hello',
			},
			['notes'],
		)
		const app = createApp(vault)

		await expect(listVaultPaths(app)).resolves.toEqual(
			expect.arrayContaining(['/', '/notes', '/notes/today.md']),
		)
	})

	it('mounts the Obsidian vault under /vault and supports writes', async () => {
		const { vault, store } = createMockVault(
			{
				'docs/readme.md': 'hello world\n',
			},
			['docs'],
		)
		const app = createApp(vault)

		const result = await execVaultBash(
			app,
			'cat /vault/docs/readme.md && printf "done" > /vault/docs/output.txt',
		)

		expect(result.exitCode).toBe(0)
		expect(result.stdout).toContain('hello world')
		expect(new TextDecoder().decode(store.readBinary('docs/output.txt'))).toBe(
			'done',
		)
	})

	it('supports shell glob expansion from the initial vault snapshot', async () => {
		const { vault } = createMockVault(
			{
				'notes/a.md': 'A',
				'notes/b.md': 'B',
			},
			['notes'],
		)
		const bash = await createVaultBash(createApp(vault))

		const result = await bash.exec('printf "%s\n" /vault/notes/*.md')
		expect(result.exitCode).toBe(0)
		expect(result.stdout).toContain('/vault/notes/a.md')
		expect(result.stdout).toContain('/vault/notes/b.md')
	})

	it('exposes /vault as a mount while preserving scratch space outside it', async () => {
		const { vault } = createMockVault(
			{
				'note.md': 'hello',
			},
			[],
		)
		const mounted = new MountedVaultFs(
			new ObsidianVaultFs(vault, ['/', '/note.md']),
		)

		await mounted.writeFile('/scratch.txt', 'temp')
		expect(await mounted.readFile('/scratch.txt')).toBe('temp')
		expect(await mounted.readFile(`${VAULT_MOUNT_POINT}/note.md`)).toBe('hello')
		expect(await mounted.readdir('/')).toEqual(['scratch.txt', 'vault'])
	})

	it('records reversible ops for writes, deletes, copies, and moves', async () => {
		const { vault } = createMockVault(
			{
				'docs/existing.md': 'before',
				'docs/nested/a.txt': 'A',
			},
			['docs', 'docs/nested'],
		)
		const recorder = new ReversibleOpRecorder()
		const fs = new ObsidianVaultFs(
			vault,
			['/', '/docs', '/docs/existing.md', '/docs/nested', '/docs/nested/a.txt'],
			undefined,
			recorder,
		)

		await fs.writeFile('/docs/new.md', 'new')
		await fs.writeFile('/docs/existing.md', 'after')
		await fs.mkdir('/docs/deep/child', { recursive: true })
		await fs.rm('/docs/nested', { recursive: true })
		await fs.cp('/docs', '/docs-copy', { recursive: true })
		await fs.mv('/docs/new.md', '/moved/new.md')

		expect(recorder.getOperations()).toEqual([
			{
				vaultPath: 'docs/new.md',
				operation: 'create',
				before: { kind: 'file' },
			},
			{
				vaultPath: 'docs/existing.md',
				operation: 'update',
				before: {
					kind: 'file',
					contentBase64: Buffer.from('before').toString('base64'),
				},
			},
			{
				vaultPath: 'docs/deep',
				operation: 'create',
				before: { kind: 'dir' },
			},
			{
				vaultPath: 'docs/deep/child',
				operation: 'create',
				before: { kind: 'dir' },
			},
			{
				vaultPath: 'docs/nested/a.txt',
				operation: 'delete',
				before: {
					kind: 'file',
					contentBase64: Buffer.from('A').toString('base64'),
				},
			},
			{
				vaultPath: 'docs/nested',
				operation: 'delete',
				before: { kind: 'dir' },
			},
			{
				vaultPath: 'docs-copy',
				operation: 'create',
				before: { kind: 'dir' },
			},
			{
				vaultPath: 'docs-copy/deep',
				operation: 'create',
				before: { kind: 'dir' },
			},
			{
				vaultPath: 'docs-copy/deep/child',
				operation: 'create',
				before: { kind: 'dir' },
			},
			{
				vaultPath: 'docs-copy/existing.md',
				operation: 'create',
				before: { kind: 'file' },
			},
			{
				vaultPath: 'docs-copy/new.md',
				operation: 'create',
				before: { kind: 'file' },
			},
			{
				vaultPath: 'moved',
				operation: 'create',
				before: { kind: 'dir' },
			},
			{
				vaultPath: 'docs/new.md',
				operation: 'delete',
				before: {
					kind: 'file',
					contentBase64: Buffer.from('new').toString('base64'),
				},
			},
			{
				vaultPath: 'moved/new.md',
				operation: 'create',
				before: { kind: 'file' },
			},
		])
	})

	it('checks cp destination and mv source plus destination in permission guard', async () => {
		const { vault } = createMockVault(
			{
				'docs/source.md': 'source',
			},
			['docs'],
		)
		const requests: PermissionRequest[] = []
		const fs = new ObsidianVaultFs(
			vault,
			['/', '/docs', '/docs/source.md'],
			async (request) => {
				requests.push(request)
			},
		)

		await fs.cp('/docs/source.md', '/docs/copied.md')
		await fs.mv('/docs/copied.md', '/docs/moved.md')

		expect(requests).toEqual([
			{
				type: 'fs',
				fs: {
				
Download .txt
gitextract_y4gmj5jl/

├── .github/
│   └── workflows/
│       ├── changelog.yml
│       ├── ci.yml
│       ├── release.yml
│       └── update-changelog-version.yml
├── .gitignore
├── .prettierrc
├── .swcrc
├── .vscode/
│   └── settings.json
├── CHANGELOG.md
├── LICENSE
├── README.md
├── esbuild.config.mjs
├── manifest.json
├── package.json
├── packages/
│   ├── chatbox/
│   │   ├── package.json
│   │   ├── postcss.config.mjs
│   │   ├── rslib.config.ts
│   │   ├── src/
│   │   │   ├── App.tsx
│   │   │   ├── assets/
│   │   │   │   └── styles/
│   │   │   │       └── global.css
│   │   │   ├── components/
│   │   │   │   ├── ConfirmDialog.tsx
│   │   │   │   ├── ContentParts.tsx
│   │   │   │   ├── CopyButton.tsx
│   │   │   │   ├── FragmentDivider.tsx
│   │   │   │   ├── MarkdownContent.tsx
│   │   │   │   ├── MessageCard.tsx
│   │   │   │   ├── PaneResizer.tsx
│   │   │   │   ├── PendingList.tsx
│   │   │   │   ├── RunStateCard.tsx
│   │   │   │   ├── SessionHistoryItem.tsx
│   │   │   │   ├── TaskCard.tsx
│   │   │   │   └── TasksPanel.tsx
│   │   │   ├── i18n/
│   │   │   │   ├── index.ts
│   │   │   │   └── locales/
│   │   │   │       ├── en.ts
│   │   │   │       └── zh.ts
│   │   │   ├── index.tsx
│   │   │   ├── types.ts
│   │   │   └── utils.ts
│   │   ├── tsconfig.json
│   │   └── unocss.config.ts
│   └── webdav-explorer/
│       ├── package.json
│       ├── postcss.config.mjs
│       ├── rslib.config.ts
│       ├── src/
│       │   ├── App.tsx
│       │   ├── assets/
│       │   │   └── styles/
│       │   │       └── global.css
│       │   ├── components/
│       │   │   ├── File.tsx
│       │   │   ├── FileList.tsx
│       │   │   ├── Folder.tsx
│       │   │   └── NewFolder.tsx
│       │   ├── i18n/
│       │   │   ├── index.ts
│       │   │   └── locales/
│       │   │       ├── en.ts
│       │   │       └── zh.ts
│       │   └── index.tsx
│       ├── tsconfig.json
│       └── unocss.config.ts
├── pnpm-workspace.yaml
├── src/
│   ├── ai/
│   │   ├── bash/
│   │   │   ├── fs.ts
│   │   │   ├── runtime.test.ts
│   │   │   └── runtime.ts
│   │   ├── config.test.ts
│   │   ├── config.ts
│   │   ├── file-operation.ts
│   │   ├── models-api.json
│   │   ├── permission-guard.test.ts
│   │   ├── permission-guard.ts
│   │   ├── providers/
│   │   │   ├── openai.ts
│   │   │   ├── registry.ts
│   │   │   └── types.ts
│   │   ├── runtime.ts
│   │   ├── search-path-filter.ts
│   │   ├── tool-call-repeat.ts
│   │   ├── tools.test.ts
│   │   ├── tools.ts
│   │   ├── transport/
│   │   │   ├── obsidian-fetch.test.ts
│   │   │   └── obsidian-fetch.ts
│   │   ├── tree.test.ts
│   │   ├── tree.ts
│   │   └── types.ts
│   ├── api/
│   │   ├── delta.ts
│   │   ├── latestDeltaCursor.ts
│   │   └── webdav.ts
│   ├── assets/
│   │   └── styles/
│   │       └── global.css
│   ├── chat/
│   │   └── domain.ts
│   ├── chatbox/
│   │   └── types.ts
│   ├── components/
│   │   ├── AIPermissionModal.ts
│   │   ├── CacheClearModal.ts
│   │   ├── CacheRestoreModal.ts
│   │   ├── CacheSaveModal.ts
│   │   ├── DeleteConfirmModal.ts
│   │   ├── FailedTasksModal.ts
│   │   ├── FilterEditorModal.ts
│   │   ├── LogoutConfirmModal.ts
│   │   ├── ModelEditorModal.ts
│   │   ├── ProviderEditorModal.ts
│   │   ├── ProvidersManagerModal.ts
│   │   ├── SelectRemoteBaseDirModal.ts
│   │   ├── SyncConfirmModal.ts
│   │   ├── SyncProgressModal.ts
│   │   ├── SyncRibbonManager.ts
│   │   ├── TaskListConfirmModal.ts
│   │   └── TextAreaModal.ts
│   ├── consts.ts
│   ├── events/
│   │   ├── index.ts
│   │   ├── sso-receive.ts
│   │   ├── sync-cancel.ts
│   │   ├── sync-end.ts
│   │   ├── sync-error.ts
│   │   ├── sync-preparing.ts
│   │   ├── sync-progress.ts
│   │   ├── sync-start.ts
│   │   ├── sync-update-mtime-progress.ts
│   │   └── vault.ts
│   ├── fs/
│   │   ├── fs.interface.ts
│   │   ├── local-vault.ts
│   │   ├── nutstore.ts
│   │   └── utils/
│   │       ├── complete-loss-dir.ts
│   │       └── is-root.ts
│   ├── i18n/
│   │   ├── index.ts
│   │   └── locales/
│   │       ├── en.ts
│   │       └── zh.ts
│   ├── index.ts
│   ├── model/
│   │   ├── stat.model.ts
│   │   └── sync-record.model.ts
│   ├── polyfill.test.ts
│   ├── polyfill.ts
│   ├── services/
│   │   ├── cache.service.v1.ts
│   │   ├── chat.service.test.ts
│   │   ├── chat.service.ts
│   │   ├── command.service.ts
│   │   ├── events.service.ts
│   │   ├── i18n.service.ts
│   │   ├── logger.service.ts
│   │   ├── progress.service.ts
│   │   ├── realtime-sync.service.ts
│   │   ├── scheduled-sync.service.ts
│   │   ├── status.service.ts
│   │   ├── sync-executor.service.ts
│   │   └── webdav.service.ts
│   ├── settings/
│   │   ├── account.ts
│   │   ├── ai.ts
│   │   ├── cache.ts
│   │   ├── common.ts
│   │   ├── filter.ts
│   │   ├── index.ts
│   │   ├── log.ts
│   │   └── settings.base.ts
│   ├── shims/
│   │   └── node-zlib.ts
│   ├── storage/
│   │   ├── blob.ts
│   │   ├── index.ts
│   │   ├── kv.ts
│   │   ├── sync-record.ts
│   │   └── use-storage.ts
│   ├── sync/
│   │   ├── core/
│   │   │   ├── merge-utils.test.ts
│   │   │   └── merge-utils.ts
│   │   ├── decision/
│   │   │   ├── base.decider.ts
│   │   │   ├── has-folder-content-changed.ts
│   │   │   ├── sync-decision.interface.ts
│   │   │   ├── two-way.decider.function.ts
│   │   │   └── two-way.decider.ts
│   │   ├── index.ts
│   │   ├── tasks/
│   │   │   ├── adapter-tasks.test.ts
│   │   │   ├── clean-record.task.ts
│   │   │   ├── conflict-resolve.task.ts
│   │   │   ├── filename-error.task.ts
│   │   │   ├── mkdir-local.task.ts
│   │   │   ├── mkdir-remote.task.ts
│   │   │   ├── mkdirs-remote.task.ts
│   │   │   ├── noop.task.ts
│   │   │   ├── pull.task.ts
│   │   │   ├── push.task.ts
│   │   │   ├── remove-local.task.ts
│   │   │   ├── remove-remote-recursively.task.ts
│   │   │   ├── remove-remote.task.ts
│   │   │   ├── skipped.task.ts
│   │   │   └── task.interface.ts
│   │   └── utils/
│   │       ├── has-ignored-in-folder.ts
│   │       ├── is-mergeable-path.ts
│   │       ├── merge-mkdir-tasks.ts
│   │       ├── merge-remove-remote-tasks.ts
│   │       ├── update-records.test.ts
│   │       └── update-records.ts
│   ├── types/
│   │   └── obsidian-extended.d.ts
│   ├── utils/
│   │   ├── api-limiter.ts
│   │   ├── apply-deltas-to-stats.ts
│   │   ├── breakable-sleep.ts
│   │   ├── config-dir-rules.test.ts
│   │   ├── config-dir-rules.ts
│   │   ├── create-id.ts
│   │   ├── decrypt-ticket-response.ts
│   │   ├── deep-stringify.ts
│   │   ├── file-stat-to-stat-model.ts
│   │   ├── format-relative-time.ts
│   │   ├── get-db-key.ts
│   │   ├── get-root-folder-name.ts
│   │   ├── get-task-name.ts
│   │   ├── glob-match.test.ts
│   │   ├── glob-match.ts
│   │   ├── has-invalid-char.ts
│   │   ├── is-503-error.ts
│   │   ├── is-numeric.ts
│   │   ├── is-same-time.ts
│   │   ├── is-sub.ts
│   │   ├── logger.ts
│   │   ├── logs-stringify.ts
│   │   ├── merge-dig-in.ts
│   │   ├── mime/
│   │   │   └── is_markdown_path.ts
│   │   ├── mkdirs-vault.ts
│   │   ├── mkdirs-webdav.ts
│   │   ├── ns-api.ts
│   │   ├── rate-limited-client.ts
│   │   ├── remote-path-to-absolute.ts
│   │   ├── remote-path-to-local-path.ts
│   │   ├── request-url.ts
│   │   ├── sha256.ts
│   │   ├── sleep.ts
│   │   ├── stat-vault-item.ts
│   │   ├── stat-webdav-item.ts
│   │   ├── std-remote-path.ts
│   │   ├── traverse-local-vault.ts
│   │   ├── traverse-webdav.ts
│   │   ├── types.ts
│   │   ├── uint8array-to-arraybuffer.ts
│   │   ├── vault-adapter-utils.test.ts
│   │   └── wait-until.ts
│   ├── views/
│   │   └── chatbox.view.ts
│   └── webdav-patch.ts
├── test/
│   └── mocks/
│       └── obsidian.ts
├── tsconfig.json
├── uno.config.ts
├── version-bump.mjs
├── versions.json
└── vitest.config.ts
Download .txt
SYMBOL INDEX (943 symbols across 179 files)

FILE: esbuild.config.mjs
  method setup (line 16) | setup(build) {

FILE: packages/chatbox/src/App.tsx
  type AppProps (line 25) | type AppProps = ChatboxProps
  constant DESKTOP_RESIZE_MEDIA_QUERY (line 27) | const DESKTOP_RESIZE_MEDIA_QUERY = '(pointer: fine) and (min-width: 1024...
  constant INPUT_HEIGHT_STORAGE_KEY (line 28) | const INPUT_HEIGHT_STORAGE_KEY = 'nutstore-sync.chatbox.desktop-input-he...
  constant DEFAULT_DESKTOP_INPUT_HEIGHT (line 29) | const DEFAULT_DESKTOP_INPUT_HEIGHT = 184
  constant DESKTOP_INPUT_MIN_HEIGHT (line 30) | const DESKTOP_INPUT_MIN_HEIGHT = 120
  constant DESKTOP_INPUT_ABSOLUTE_MIN_HEIGHT (line 31) | const DESKTOP_INPUT_ABSOLUTE_MIN_HEIGHT = 72
  constant DESKTOP_MESSAGES_MIN_HEIGHT (line 32) | const DESKTOP_MESSAGES_MIN_HEIGHT = 200
  constant RESIZER_HITBOX_HEIGHT (line 33) | const RESIZER_HITBOX_HEIGHT = 10
  constant DESKTOP_INPUT_MAX_VIEWPORT_RATIO (line 34) | const DESKTOP_INPUT_MAX_VIEWPORT_RATIO = 0.6
  function App (line 36) | function App(props: AppProps) {

FILE: packages/chatbox/src/components/ConfirmDialog.tsx
  function ConfirmDialog (line 4) | function ConfirmDialog(props: {

FILE: packages/chatbox/src/components/ContentParts.tsx
  function ContentParts (line 5) | function ContentParts(props: {

FILE: packages/chatbox/src/components/CopyButton.tsx
  function CopyButton (line 4) | function CopyButton(props: { getText: () => string }) {

FILE: packages/chatbox/src/components/FragmentDivider.tsx
  function FragmentDivider (line 4) | function FragmentDivider(props: { item: ChatTimelineFragmentItem }) {

FILE: packages/chatbox/src/components/MarkdownContent.tsx
  function MarkdownContent (line 4) | function MarkdownContent(props: {

FILE: packages/chatbox/src/components/MessageCard.tsx
  function MessageCard (line 8) | function MessageCard(props: {

FILE: packages/chatbox/src/components/PaneResizer.tsx
  type PaneResizerProps (line 3) | interface PaneResizerProps {
  function PaneResizer (line 10) | function PaneResizer(props: PaneResizerProps) {

FILE: packages/chatbox/src/components/PendingList.tsx
  function PendingList (line 5) | function PendingList(props: {

FILE: packages/chatbox/src/components/RunStateCard.tsx
  function RunStateCard (line 6) | function RunStateCard(props: {

FILE: packages/chatbox/src/components/SessionHistoryItem.tsx
  function SessionHistoryItem (line 6) | function SessionHistoryItem(props: {

FILE: packages/chatbox/src/components/TaskCard.tsx
  function TaskCard (line 6) | function TaskCard(props: {

FILE: packages/chatbox/src/components/TasksPanel.tsx
  function TasksPanel (line 6) | function TasksPanel(props: {

FILE: packages/chatbox/src/i18n/index.ts
  type Locale (line 6) | type Locale = 'zh' | 'en'
  function toLocale (line 8) | function toLocale(language: string) {

FILE: packages/chatbox/src/index.tsx
  type ChatboxController (line 8) | interface ChatboxController {
  function mount (line 13) | function mount(el: Element, props: AppProps): ChatboxController {

FILE: packages/chatbox/src/types.ts
  type ChatUsage (line 1) | interface ChatUsage {
  type ReversibleToolOp (line 7) | type ReversibleToolOp =
  type ChatRunState (line 24) | type ChatRunState =
  type ChatTextPart (line 30) | interface ChatTextPart {
  type ChatImageUrlPart (line 35) | interface ChatImageUrlPart {
  type ChatUnknownPart (line 42) | interface ChatUnknownPart {
  type ChatMessageContentPart (line 47) | type ChatMessageContentPart =
  type ChatToolCall (line 52) | interface ChatToolCall {
  type ChatMessageMeta (line 61) | interface ChatMessageMeta {
  type ChatSystemMessage (line 69) | interface ChatSystemMessage {
  type ChatUserMessage (line 74) | interface ChatUserMessage {
  type ChatAssistantMessageWithContent (line 79) | interface ChatAssistantMessageWithContent {
  type ChatAssistantMessageWithToolCalls (line 85) | interface ChatAssistantMessageWithToolCalls {
  type ChatToolMessage (line 91) | interface ChatToolMessage {
  type ChatAssistantMessage (line 98) | type ChatAssistantMessage =
  type ChatMessage (line 102) | type ChatMessage =
  type ChatMessageRecord (line 108) | interface ChatMessageRecord {
  type ChatTaskBase (line 117) | interface ChatTaskBase {
  type QueuedChatTask (line 128) | interface QueuedChatTask extends ChatTaskBase {
  type RunningChatTask (line 132) | interface RunningChatTask extends ChatTaskBase {
  type CompletedChatTask (line 137) | interface CompletedChatTask extends ChatTaskBase {
  type FailedChatTask (line 145) | interface FailedChatTask extends ChatTaskBase {
  type CancelledChatTask (line 155) | interface CancelledChatTask extends ChatTaskBase {
  type ChatTaskRecord (line 163) | type ChatTaskRecord =
  type ChatPendingMessage (line 170) | interface ChatPendingMessage {
  type ChatModelOption (line 176) | interface ChatModelOption {
  type ChatProviderOption (line 181) | interface ChatProviderOption {
  type ChatSessionHistoryItem (line 187) | interface ChatSessionHistoryItem {
  type ChatTimelineFragmentItem (line 194) | interface ChatTimelineFragmentItem {
  type ChatTimelineMessageItem (line 200) | interface ChatTimelineMessageItem {
  type ChatTimelineItem (line 208) | type ChatTimelineItem =
  type ChatboxViewModel (line 212) | interface ChatboxViewModel {
  type ChatboxProps (line 229) | interface ChatboxProps extends ChatboxViewModel {

FILE: packages/chatbox/src/utils.ts
  function formatTime (line 4) | function formatTime(timestamp: number) {
  function formatFragmentTime (line 13) | function formatFragmentTime(timestamp: number) {
  function formatDuration (line 23) | function formatDuration(task: ChatTaskRecord) {
  function formatUsage (line 40) | function formatUsage(input?: number, output?: number, total?: number) {
  function statusLabel (line 61) | function statusLabel(status: ChatTaskRecord['status']) {
  function statusClass (line 76) | function statusClass(status: ChatTaskRecord['status']) {
  function runStateLabel (line 91) | function runStateLabel(runState: ChatRunState) {

FILE: packages/webdav-explorer/src/App.tsx
  type MaybePromise (line 8) | type MaybePromise<T> = Promise<T> | T
  type fs (line 10) | interface fs {
  type AppProps (line 15) | interface AppProps {
  function App (line 21) | function App(props: AppProps) {

FILE: packages/webdav-explorer/src/components/File.tsx
  type FolderProps (line 1) | interface FolderProps {
  function File (line 5) | function File(props: FolderProps) {

FILE: packages/webdav-explorer/src/components/FileList.tsx
  type FileStat (line 7) | interface FileStat {
  type FileListProps (line 13) | interface FileListProps {
  function createFileList (line 19) | function createFileList() {

FILE: packages/webdav-explorer/src/components/Folder.tsx
  type FolderProps (line 1) | interface FolderProps {
  function Folder (line 7) | function Folder(props: FolderProps) {

FILE: packages/webdav-explorer/src/components/NewFolder.tsx
  type NewFolderProps (line 4) | interface NewFolderProps {
  function NewFolder (line 10) | function NewFolder(props: NewFolderProps) {

FILE: packages/webdav-explorer/src/i18n/index.ts
  type Locale (line 6) | type Locale = 'zh' | 'en'
  function toLocale (line 8) | function toLocale(language: string) {

FILE: packages/webdav-explorer/src/index.tsx
  function mount (line 6) | function mount(el: Element, props: AppProps) {

FILE: src/ai/bash/fs.ts
  constant FILE_MODE (line 27) | const FILE_MODE = 0o644
  constant DIR_MODE (line 28) | const DIR_MODE = 0o755
  constant VAULT_MOUNT_POINT (line 29) | const VAULT_MOUNT_POINT = '/vault'
  type ReadFileOptions (line 30) | type ReadFileOptions = { encoding?: BufferEncoding | null }
  type WriteFileOptions (line 31) | type WriteFileOptions = { encoding?: BufferEncoding }
  type SnapshotKind (line 32) | type SnapshotKind = 'file' | 'dir'
  type VaultSnapshotNode (line 33) | type VaultSnapshotNode = {
  function encodeBase64 (line 39) | function encodeBase64(content: Uint8Array) {
  function getEncoding (line 50) | function getEncoding(
  function decodeContent (line 59) | function decodeContent(
  function encodeContent (line 79) | function encodeContent(
  function toArrayBuffer (line 99) | function toArrayBuffer(content: Uint8Array) {
  function getPathDepth (line 106) | function getPathDepth(path: string) {
  function normalizeVirtualPath (line 110) | function normalizeVirtualPath(inputPath: string) {
  function joinVirtualPath (line 115) | function joinVirtualPath(parent: string, name: string) {
  function ensureNotEscapingRoot (line 119) | function ensureNotEscapingRoot(inputPath: string) {
  function normalizeReversibleVaultPath (line 127) | function normalizeReversibleVaultPath(path: string) {
  function mapStat (line 135) | function mapStat(stat: {
  function mapAbstractFileStat (line 150) | function mapAbstractFileStat(file: TAbstractFile): FsStat {
  function copyRecursive (line 166) | async function copyRecursive(
  function removeRecursive (line 193) | async function removeRecursive(
  function listVaultPaths (line 211) | async function listVaultPaths(app: App) {
  class ReversibleOpRecorder (line 230) | class ReversibleOpRecorder {
    method recordCreate (line 233) | recordCreate(vaultPath: string, kind: SnapshotKind) {
    method recordUpdate (line 245) | recordUpdate(vaultPath: string, contentBase64: string) {
    method recordDelete (line 260) | recordDelete(snapshot: VaultSnapshotNode) {
    method getOperations (line 278) | getOperations(): ReversibleToolOp[] {
  class ObsidianVaultFs (line 283) | class ObsidianVaultFs implements IFileSystem {
    method constructor (line 287) | constructor(
    method withBatch (line 299) | private async withBatch<T>(fn: () => Promise<T>): Promise<T> {
    method checkPermission (line 308) | private async checkPermission(
    method toPermissionPath (line 336) | private toPermissionPath(path: string) {
    method toVaultPath (line 343) | private toVaultPath(inputPath: string) {
    method statInternal (line 348) | private async statInternal(inputPath: string) {
    method readFileContentBase64 (line 356) | private async readFileContentBase64(target: TFile) {
    method snapshotNode (line 364) | private async snapshotNode(
    method snapshotSubtree (line 396) | private async snapshotSubtree(path: string) {
    method toSnapshotMap (line 407) | private toSnapshotMap(entries: VaultSnapshotNode[]) {
    method recordDeleteSnapshots (line 411) | private recordDeleteSnapshots(entries: VaultSnapshotNode[]) {
    method recordTargetDiff (line 420) | private recordTargetDiff(
    method deleteAbstractFile (line 464) | private async deleteAbstractFile(target: TAbstractFile) {
    method recordPath (line 478) | private recordPath(inputPath: string) {
    method forgetPath (line 489) | private forgetPath(inputPath: string) {
    method assertExists (line 499) | private assertExists(path: string) {
    method readFile (line 507) | async readFile(
    method readFileBuffer (line 516) | async readFileBuffer(path: string): Promise<Uint8Array> {
    method writeFile (line 531) | async writeFile(
    method appendFile (line 563) | async appendFile(
    method exists (line 581) | async exists(path: string): Promise<boolean> {
    method stat (line 591) | async stat(path: string): Promise<FsStat> {
    method mkdir (line 605) | async mkdir(path: string, options?: MkdirOptions): Promise<void> {
    method readdir (line 630) | async readdir(path: string): Promise<string[]> {
    method readdirWithFileTypes (line 648) | async readdirWithFileTypes(path: string) {
    method rm (line 670) | async rm(path: string, options?: RmOptions): Promise<void> {
    method cp (line 695) | async cp(src: string, dest: string, options?: CpOptions): Promise<void> {
    method mv (line 700) | async mv(src: string, dest: string): Promise<void> {
    method resolvePath (line 726) | resolvePath(base: string, path: string): string {
    method getAllPaths (line 730) | getAllPaths(): string[] {
    method chmod (line 734) | async chmod(path: string, _mode: number): Promise<void> {
    method symlink (line 738) | async symlink(_target: string, linkPath: string): Promise<void> {
    method link (line 744) | async link(_existingPath: string, newPath: string): Promise<void> {
    method readlink (line 750) | async readlink(path: string): Promise<string> {
    method lstat (line 754) | async lstat(path: string): Promise<FsStat> {
    method realpath (line 758) | async realpath(path: string): Promise<string> {
    method utimes (line 763) | async utimes(path: string, _atime: Date, _mtime: Date): Promise<void> {
  class MountedVaultFs (line 775) | class MountedVaultFs implements IFileSystem {
    method constructor (line 778) | constructor(private readonly vaultFs: ObsidianVaultFs) {}
    method isRoot (line 780) | private isRoot(path: string) {
    method isVaultMount (line 784) | private isVaultMount(path: string) {
    method isVaultPath (line 788) | private isVaultPath(path: string) {
    method toVaultRelative (line 796) | private toVaultRelative(path: string) {
    method route (line 804) | private route(path: string) {
    method genericCp (line 818) | private async genericCp(src: string, dest: string, options?: CpOptions) {
    method readFile (line 839) | async readFile(
    method readFileBuffer (line 852) | async readFileBuffer(path: string): Promise<Uint8Array> {
    method writeFile (line 862) | async writeFile(
    method appendFile (line 876) | async appendFile(
    method exists (line 890) | async exists(path: string): Promise<boolean> {
    method stat (line 898) | async stat(path: string): Promise<FsStat> {
    method mkdir (line 913) | async mkdir(path: string, options?: MkdirOptions): Promise<void> {
    method readdir (line 921) | async readdir(path: string): Promise<string[]> {
    method readdirWithFileTypes (line 933) | async readdirWithFileTypes(path: string) {
    method rm (line 960) | async rm(path: string, options?: RmOptions): Promise<void> {
    method cp (line 968) | async cp(src: string, dest: string, options?: CpOptions): Promise<void> {
    method mv (line 972) | async mv(src: string, dest: string): Promise<void> {
    method resolvePath (line 986) | resolvePath(base: string, path: string): string {
    method getAllPaths (line 990) | getAllPaths(): string[] {
    method chmod (line 999) | async chmod(path: string, mode: number): Promise<void> {
    method symlink (line 1007) | async symlink(target: string, linkPath: string): Promise<void> {
    method link (line 1016) | async link(existingPath: string, newPath: string): Promise<void> {
    method readlink (line 1025) | async readlink(path: string): Promise<string> {
    method lstat (line 1032) | async lstat(path: string): Promise<FsStat> {
    method realpath (line 1036) | async realpath(path: string): Promise<string> {
    method utimes (line 1041) | async utimes(path: string, atime: Date, mtime: Date): Promise<void> {

FILE: src/ai/bash/runtime.test.ts
  type MockEntryFile (line 12) | interface MockEntryFile {
  type MockEntryFolder (line 18) | interface MockEntryFolder {
  type MockEntry (line 23) | type MockEntry = MockEntryFile | MockEntryFolder
  type MockAbstractFile (line 25) | interface MockAbstractFile {
  type MockFile (line 31) | interface MockFile extends MockAbstractFile {
  type MockFolder (line 38) | interface MockFolder extends MockAbstractFile {
  class MemoryVaultStore (line 42) | class MemoryVaultStore {
    method constructor (line 47) | constructor(
    method normalize (line 59) | normalize(path: string) {
    method dirname (line 63) | dirname(path: string) {
    method basename (line 70) | basename(path: string) {
    method ensureFolder (line 78) | ensureFolder(path: string) {
    method exists (line 92) | exists(path: string) {
    method stat (line 96) | stat(path: string) {
    method readBinary (line 109) | readBinary(path: string) {
    method writeBinary (line 120) | writeBinary(path: string, data: ArrayBuffer) {
    method remove (line 130) | remove(path: string) {
    method removeRecursive (line 134) | removeRecursive(path: string) {
    method rename (line 143) | rename(fromPath: string, toPath: string) {
    method listChildren (line 162) | listChildren(path: string) {
  function createMockVault (line 172) | function createMockVault(
  function createApp (line 277) | function createApp(vault: Vault) {

FILE: src/ai/bash/runtime.ts
  type VaultBashExecOptions (line 12) | interface VaultBashExecOptions {
  function createVaultBash (line 19) | async function createVaultBash(
  function execVaultBash (line 39) | async function execVaultBash(

FILE: src/ai/config.ts
  constant DEFAULT_NPM_PACKAGE (line 17) | const DEFAULT_NPM_PACKAGE = '@ai-sdk/openai-compatible'
  constant DEFAULT_MODALITIES (line 19) | const DEFAULT_MODALITIES: AIModelConfig['modalities'] = {
  constant DEFAULT_LIMIT (line 24) | const DEFAULT_LIMIT: AIModelConfig['limit'] = { context: 0, output: 0 }
  function formatSchemaIssues (line 26) | function formatSchemaIssues(error: z.ZodError): string {
  function createModelConfig (line 35) | function createModelConfig(
  function createProviderConfig (line 67) | function createProviderConfig(
  function sanitizeModels (line 84) | function sanitizeModels(models: AIModelInputs | undefined): AIModelConfi...
  function sanitizeProviders (line 93) | function sanitizeProviders(providers: unknown): AIProviderConfigs {
  function sanitizeDefaultSelections (line 107) | function sanitizeDefaultSelections(
  function resolveInitialSelection (line 118) | function resolveInitialSelection(
  function slugifyProviderId (line 129) | function slugifyProviderId(name: string): string {
  function getProviderById (line 137) | function getProviderById(
  function getModelById (line 144) | function getModelById(
  function listProviders (line 151) | function listProviders(
  function listModels (line 157) | function listModels(
  function getFirstModel (line 163) | function getFirstModel(provider: AIProviderConfig | undefined) {
  function getPresetProviders (line 169) | function getPresetProviders(): AIProviderDefinitions {
  function listPresetProviders (line 182) | function listPresetProviders(): AIProviderDefinition[] {
  function findPresetModelById (line 188) | function findPresetModelById(modelId: string): AIModelConfig | undefined {
  function createProviderFromPreset (line 200) | function createProviderFromPreset(

FILE: src/ai/file-operation.ts
  constant AI_FILE_OPERATIONS (line 1) | const AI_FILE_OPERATIONS = [
  type AIFileOperation (line 11) | type AIFileOperation = (typeof AI_FILE_OPERATIONS)[number]
  type AISinglePathFileOperation (line 12) | type AISinglePathFileOperation = Exclude<
  type AIDualPathFileOperation (line 16) | type AIDualPathFileOperation = Extract<AIFileOperation, 'copy' | 'move'>

FILE: src/ai/permission-guard.test.ts
  function getRuntimeStore (line 18) | function getRuntimeStore(
  function createGuard (line 34) | function createGuard(

FILE: src/ai/permission-guard.ts
  type FSSinglePathPermissionRequest (line 10) | interface FSSinglePathPermissionRequest {
  type FSDualPathPermissionRequest (line 18) | interface FSDualPathPermissionRequest {
  type FSPermissionRequest (line 27) | type FSPermissionRequest =
  type PermissionRequest (line 31) | type PermissionRequest = FSPermissionRequest
  type PermissionGuard (line 32) | type PermissionGuard = (request: PermissionRequest) => Promise<void>
  type RuntimeAutoApproveOperationStore (line 34) | interface RuntimeAutoApproveOperationStore {
  function isDualPathRequest (line 39) | function isDualPathRequest(
  function getPermissionRequestOperationSignature (line 45) | function getPermissionRequestOperationSignature(
  function formatDeniedSummary (line 51) | function formatDeniedSummary(request: FSPermissionRequest) {
  function createPermissionGuard (line 59) | function createPermissionGuard(

FILE: src/ai/providers/openai.ts
  function assertProviderUsable (line 8) | function assertProviderUsable(provider: AIProviderConfig) {
  method createLanguageModel (line 16) | createLanguageModel(provider, modelId) {

FILE: src/ai/providers/registry.ts
  function getProviderResolver (line 4) | function getProviderResolver(_provider: AIProviderConfig) {

FILE: src/ai/providers/types.ts
  type ResolvedLanguageModel (line 4) | interface ResolvedLanguageModel {
  type AIProviderResolver (line 9) | interface AIProviderResolver {

FILE: src/ai/runtime.ts
  type GenerateAssistantTurnRequest (line 12) | interface GenerateAssistantTurnRequest {
  type GenerateAssistantTurnResult (line 21) | interface GenerateAssistantTurnResult {
  function toTextParts (line 26) | function toTextParts(text?: string | null): AIMessageContentPart[] | null {
  function toModelMessages (line 33) | function toModelMessages(messages: AIMessage[]): ModelMessage[] {
  function toAISDKTools (line 112) | function toAISDKTools(tools: AIToolDefinition[]) {
  function toAssistantMessage (line 124) | function toAssistantMessage(result: any) {
  function assertProviderUsable (line 148) | function assertProviderUsable(provider: AIProviderConfig) {
  function generateAssistantTurn (line 152) | async function generateAssistantTurn(

FILE: src/ai/search-path-filter.ts
  type SearchPathEntry (line 4) | interface SearchPathEntry {
  function createGlobRules (line 9) | function createGlobRules(patterns: string[]) {
  function matchesIncludedSearchGlob (line 18) | function matchesIncludedSearchGlob(path: string, inclusionRules: GlobMat...
  function matchesExcludedSearchGlob (line 25) | function matchesExcludedSearchGlob(path: string, exclusionRules: GlobMat...
  function normalizeExtension (line 42) | function normalizeExtension(extension: string) {
  function shouldIncludeByExtension (line 50) | function shouldIncludeByExtension(path: string, extensions: string[]) {
  function isFilePathInScope (line 58) | function isFilePathInScope(filePath: string, basePath: string) {
  function filterVaultEntries (line 65) | function filterVaultEntries<TEntry extends SearchPathEntry>(

FILE: src/ai/tool-call-repeat.ts
  constant REPEATED_TOOL_CALL_THRESHOLD (line 3) | const REPEATED_TOOL_CALL_THRESHOLD = 5
  type ToolCallRepeatState (line 5) | interface ToolCallRepeatState {
  function sortJsonValue (line 11) | function sortJsonValue(value: unknown): unknown {
  function normalizeToolArguments (line 27) | function normalizeToolArguments(argumentsText: string) {
  function createToolCallRoundSignature (line 35) | function createToolCallRoundSignature(toolCalls: AIToolCall[]) {
  function updateToolCallRepeatState (line 44) | function updateToolCallRepeatState(

FILE: src/ai/tools.test.ts
  function makeEntries (line 7) | function makeEntries(
  function createToolApp (line 13) | function createToolApp() {

FILE: src/ai/tools.ts
  type ReplaceResult (line 9) | interface ReplaceResult {
  function encodeTextBase64 (line 14) | function encodeTextBase64(content: string) {
  function isAllowedBashCwd (line 46) | function isAllowedBashCwd(pathValue: string) {
  type SpawnToolHandler (line 57) | interface SpawnToolHandler {
  type CreateAIToolsOptions (line 68) | interface CreateAIToolsOptions {
  function replaceUniqueOccurrence (line 74) | function replaceUniqueOccurrence(
  function createAITools (line 103) | function createAITools(

FILE: src/ai/transport/obsidian-fetch.ts
  type FetchFunction (line 4) | type FetchFunction = (
  function toHeadersRecord (line 9) | function toHeadersRecord(headers?: HeadersInit) {
  function toRequestParts (line 27) | async function toRequestParts(input: RequestInfo | URL, init?: RequestIn...

FILE: src/ai/tree.ts
  type TreeNode (line 1) | interface TreeNode {
  function flattenTreeNodes (line 8) | function flattenTreeNodes(nodes: TreeNode[], depth: number) {

FILE: src/ai/types.ts
  type AIModelConfig (line 79) | type AIModelConfig = z.infer<typeof aiModelConfigSchema>
  type AIModelInput (line 80) | type AIModelInput = z.infer<typeof aiModelInputSchema>
  type AIModelConfigs (line 83) | type AIModelConfigs = z.infer<typeof aiModelConfigsSchema>
  type AIModelInputs (line 84) | type AIModelInputs = z.infer<typeof aiModelInputsSchema>
  type AIProviderDefinition (line 99) | type AIProviderDefinition = z.infer<typeof aiProviderDefinitionSchema>
  type AIProviderDefinitions (line 100) | type AIProviderDefinitions = z.infer<typeof aiProviderDefinitionsSchema>
  type AIProviderConfig (line 118) | type AIProviderConfig = z.infer<typeof aiProviderConfigSchema>
  type AIProviderInput (line 119) | type AIProviderInput = z.infer<typeof aiProviderInputSchema>
  type AIProviderConfigs (line 120) | type AIProviderConfigs = z.infer<typeof aiProviderConfigsSchema>
  type AIProviderInputs (line 121) | type AIProviderInputs = z.infer<typeof aiProviderInputsSchema>
  type AIUsage (line 123) | type AIUsage = DomainChatUsage
  type AITextPart (line 124) | type AITextPart = Extract<DomainChatMessageContentPart, { type: 'text' }>
  type AIImageUrlPart (line 125) | type AIImageUrlPart = Extract<
  type AIMessageContentPart (line 129) | type AIMessageContentPart = DomainChatMessageContentPart
  type AIToolCall (line 130) | type AIToolCall = DomainChatToolCall
  type AIMessage (line 131) | type AIMessage = DomainChatMessage
  type AITaskStatus (line 132) | type AITaskStatus = DomainChatTaskRecord['status']
  type AIMessageMeta (line 133) | type AIMessageMeta = DomainChatMessageMeta
  type AIMessageRecord (line 134) | type AIMessageRecord = DomainChatMessageRecord
  type AISession (line 135) | type AISession = DomainChatSession
  type AITaskRecord (line 136) | type AITaskRecord = DomainChatTaskRecord
  type AIToolExecutionContext (line 138) | interface AIToolExecutionContext {
  type ToolExecutionResult (line 145) | interface ToolExecutionResult {
  type AIToolDefinition (line 150) | interface AIToolDefinition {

FILE: src/api/delta.ts
  type DeltaEntry (line 8) | interface DeltaEntry {
  type DeltaResponse (line 17) | interface DeltaResponse {
  type GetDeltaInput (line 26) | interface GetDeltaInput {

FILE: src/api/latestDeltaCursor.ts
  type GetLatestDeltaCursorInput (line 6) | interface GetLatestDeltaCursorInput {

FILE: src/api/webdav.ts
  type WebDAVResponse (line 10) | interface WebDAVResponse {
  function extractNextLink (line 28) | function extractNextLink(linkHeader: string): string | null {
  function convertToFileStat (line 33) | function convertToFileStat(
  function getDirectoryContents (line 54) | async function getDirectoryContents(

FILE: src/chat/domain.ts
  type ChatFragment (line 47) | interface ChatFragment {
  type ChatSessionPermissions (line 55) | interface ChatSessionPermissions {
  type ChatSession (line 59) | interface ChatSession {
  type ChatSessionIndexItem (line 72) | interface ChatSessionIndexItem {
  function cloneUsage (line 79) | function cloneUsage(usage?: ChatUsage) {
  function cloneMessage (line 87) | function cloneMessage(message: ChatMessage): ChatMessage {
  function cloneReversibleToolOp (line 122) | function cloneReversibleToolOp(op: ReversibleToolOp): ReversibleToolOp {
  function cloneMessageRecord (line 154) | function cloneMessageRecord(
  function cloneTask (line 170) | function cloneTask(task: ChatTaskRecord): ChatTaskRecord {
  function cloneSession (line 176) | function cloneSession(session: ChatSession): ChatSession {
  function isTerminalTask (line 191) | function isTerminalTask(task: ChatTaskRecord) {
  function createQueuedTask (line 199) | function createQueuedTask(task: ChatTaskBase): QueuedChatTask {
  function createRunningTask (line 206) | function createRunningTask(
  function toRunningTask (line 217) | function toRunningTask(
  function toCompletedTask (line 228) | function toCompletedTask(
  function toFailedTask (line 243) | function toFailedTask(
  function toCancelledTask (line 261) | function toCancelledTask(
  function mutateTaskRecord (line 277) | function mutateTaskRecord(target: ChatTaskRecord, next: ChatTaskRecord) {

FILE: src/chatbox/types.ts
  type ChatModelOption (line 18) | interface ChatModelOption {
  type ChatProviderOption (line 23) | interface ChatProviderOption {
  type ChatSessionHistoryItem (line 29) | interface ChatSessionHistoryItem {
  type ChatTimelineFragmentItem (line 36) | interface ChatTimelineFragmentItem {
  type ChatTimelineMessageItem (line 42) | interface ChatTimelineMessageItem {
  type ChatTimelineItem (line 50) | type ChatTimelineItem =
  type ChatboxViewModel (line 54) | interface ChatboxViewModel {
  type ChatboxProps (line 71) | interface ChatboxProps extends ChatboxViewModel {
  type ChatboxController (line 94) | interface ChatboxController {

FILE: src/components/AIPermissionModal.ts
  type AIPermissionResult (line 6) | type AIPermissionResult = 'approve' | 'auto-approve-operation' | 'deny'
  function getOperationLabel (line 8) | function getOperationLabel(operation: AIFileOperation): string {
  class AIPermissionModal (line 27) | class AIPermissionModal extends Modal {
    method constructor (line 32) | constructor(
    method renderSinglePathRequest (line 39) | private renderSinglePathRequest() {
    method renderDualPathRequest (line 58) | private renderDualPathRequest() {
    method onOpen (line 94) | onOpen() {
    method onClose (line 140) | onClose() {
    method open (line 149) | open(): Promise<AIPermissionResult> {

FILE: src/components/CacheClearModal.ts
  type CacheClearOptions (line 7) | interface CacheClearOptions {
  class CacheClearModal (line 13) | class CacheClearModal extends Modal {
    method constructor (line 20) | constructor(
    method onOpen (line 27) | onOpen() {
    method onClose (line 117) | onClose() {
    method clearSelectedCaches (line 125) | static async clearSelectedCaches(options: CacheClearOptions) {

FILE: src/components/CacheRestoreModal.ts
  class CacheRestoreModal (line 8) | class CacheRestoreModal extends Modal {
    method constructor (line 13) | constructor(
    method onOpen (line 22) | async onOpen() {
    method loadFileList (line 52) | private async loadFileList() {
    method renderEmptyList (line 130) | private renderEmptyList() {
    method onClose (line 138) | onClose() {

FILE: src/components/CacheSaveModal.ts
  class CacheSaveModal (line 6) | class CacheSaveModal extends Modal {
    method constructor (line 9) | constructor(
    method onOpen (line 18) | onOpen() {
    method onClose (line 66) | onClose() {

FILE: src/components/DeleteConfirmModal.ts
  class DeleteConfirmModal (line 5) | class DeleteConfirmModal extends Modal {
    method constructor (line 9) | constructor(
    method onOpen (line 17) | onOpen() {
    method open (line 85) | async open(): Promise<{

FILE: src/components/FailedTasksModal.ts
  type FailedTaskInfo (line 4) | interface FailedTaskInfo {
  class FailedTasksModal (line 10) | class FailedTasksModal extends Modal {
    method constructor (line 11) | constructor(
    method onOpen (line 18) | onOpen() {
    method onClose (line 60) | onClose() {

FILE: src/components/FilterEditorModal.ts
  type FilterType (line 7) | enum FilterType {
  class FilterEditorModal (line 12) | class FilterEditorModal extends Modal {
    method constructor (line 17) | constructor(
    method onOpen (line 27) | onOpen() {
    method onClose (line 147) | onClose() {

FILE: src/components/LogoutConfirmModal.ts
  class LogoutConfirmModal (line 4) | class LogoutConfirmModal extends Modal {
    method constructor (line 7) | constructor(app: App, onConfirm: () => void) {
    method onOpen (line 12) | onOpen() {
    method onClose (line 35) | onClose() {

FILE: src/components/ModelEditorModal.ts
  type ModelEditorOptions (line 9) | interface ModelEditorOptions {
  class ModelEditorModal (line 13) | class ModelEditorModal extends Modal {
    method constructor (line 16) | constructor(
    method onOpen (line 27) | onOpen() {
    method onClose (line 87) | onClose() {

FILE: src/components/ProviderEditorModal.ts
  class ProviderEditorModal (line 10) | class ProviderEditorModal extends Modal {
    method constructor (line 13) | constructor(
    method onOpen (line 23) | onOpen() {
    method render (line 27) | private render() {
    method deleteModel (line 186) | private deleteModel(model: AIModelConfig) {
    method onClose (line 193) | onClose() {

FILE: src/components/ProvidersManagerModal.ts
  constant CUSTOM_OPTION (line 14) | const CUSTOM_OPTION = '__custom__'
  class ProvidersManagerModal (line 16) | class ProvidersManagerModal extends Modal {
    method constructor (line 19) | constructor(
    method onOpen (line 26) | onOpen() {
    method render (line 30) | private render() {
    method deleteProvider (line 156) | private async deleteProvider(provider: AIProviderConfig) {
    method onClose (line 170) | onClose() {

FILE: src/components/SelectRemoteBaseDirModal.ts
  class SelectRemoteBaseDirModal (line 10) | class SelectRemoteBaseDirModal extends Modal {
    method constructor (line 11) | constructor(
    method onOpen (line 19) | async onOpen() {
    method onClose (line 50) | onClose() {

FILE: src/components/SyncConfirmModal.ts
  class SyncConfirmModal (line 5) | class SyncConfirmModal extends Modal {
    method constructor (line 8) | constructor(app: App, onConfirm: () => void) {
    method onOpen (line 13) | async onOpen() {
    method onClose (line 48) | onClose() {

FILE: src/components/SyncProgressModal.ts
  class SyncProgressModal (line 24) | class SyncProgressModal extends Modal {
    method constructor (line 41) | constructor(
    method update (line 57) | public update(): void {
    method onOpen (line 164) | onOpen() {
    method onClose (line 281) | onClose(): void {
    method updateCacheProgress (line 291) | private updateCacheProgress(total: number, completed: number): void {

FILE: src/components/SyncRibbonManager.ts
  class SyncRibbonManager (line 10) | class SyncRibbonManager {
    method constructor (line 14) | constructor(private plugin: NutstorePlugin) {
    method update (line 82) | public update() {

FILE: src/components/TaskListConfirmModal.ts
  class TaskListConfirmModal (line 6) | class TaskListConfirmModal extends Modal {
    method constructor (line 10) | constructor(
    method onOpen (line 18) | onOpen() {
    method open (line 83) | async open(): Promise<{ confirm: boolean; tasks: BaseTask[] }> {

FILE: src/components/TextAreaModal.ts
  class TextAreaModal (line 4) | class TextAreaModal extends Modal {
    method constructor (line 5) | constructor(
    method onOpen (line 12) | onOpen() {
    method onClose (line 39) | onClose() {

FILE: src/consts.ts
  constant NS_NSDAV_ENDPOINT (line 3) | const NS_NSDAV_ENDPOINT = process.env.NS_NSDAV_ENDPOINT!
  constant NS_DAV_ENDPOINT (line 4) | const NS_DAV_ENDPOINT = process.env.NS_DAV_ENDPOINT!
  constant PLUGIN_VERSION (line 5) | const PLUGIN_VERSION = process.env.PLUGIN_VERSION!
  constant API_VER_STAT_FOLDER (line 7) | const API_VER_STAT_FOLDER = '0.13.27'
  constant API_VER_REQURL (line 8) | const API_VER_REQURL = '0.13.26' // desktop ver 0.13.26, iOS ver 1.1.1
  constant API_VER_REQURL_ANDROID (line 9) | const API_VER_REQURL_ANDROID = '0.14.6' // Android ver 1.2.1
  constant API_VER_ENSURE_REQURL_OK (line 10) | const API_VER_ENSURE_REQURL_OK = '1.0.0' // always bypass CORS here
  constant VALID_REQURL (line 12) | const VALID_REQURL =
  constant IN_DEV (line 16) | const IN_DEV = process.env.NODE_ENV === 'development'

FILE: src/events/sso-receive.ts
  type SsoRxProps (line 3) | interface SsoRxProps {

FILE: src/events/sync-end.ts
  type SyncEndProps (line 3) | interface SyncEndProps {

FILE: src/events/sync-preparing.ts
  type SyncPreparingProps (line 3) | interface SyncPreparingProps {

FILE: src/events/sync-progress.ts
  type UpdateSyncProgress (line 4) | interface UpdateSyncProgress {

FILE: src/events/sync-start.ts
  type SyncStartProps (line 3) | interface SyncStartProps {

FILE: src/events/sync-update-mtime-progress.ts
  type UpdateSyncUpdateMtimeProgress (line 3) | interface UpdateSyncUpdateMtimeProgress {

FILE: src/events/vault.ts
  type VaultEventProps (line 3) | interface VaultEventProps {

FILE: src/fs/fs.interface.ts
  type FsWalkResult (line 4) | interface FsWalkResult {

FILE: src/fs/local-vault.ts
  class LocalVaultFileSystem (line 17) | class LocalVaultFileSystem implements AbstractFileSystem {
    method constructor (line 18) | constructor(
    method walk (line 31) | async walk() {
    method buildRules (line 60) | private buildRules(rules: GlobMatchOptions[] = []): GlobMatch[] {

FILE: src/fs/nutstore.ts
  class NutstoreFileSystem (line 23) | class NutstoreFileSystem implements AbstractFileSystem {
    method constructor (line 26) | constructor(
    method walk (line 46) | async walk() {
    method buildRules (line 112) | private buildRules(rules: GlobMatchOptions[] = []): GlobMatch[] {

FILE: src/fs/utils/complete-loss-dir.ts
  function completeLossDir (line 10) | function completeLossDir(

FILE: src/fs/utils/is-root.ts
  function isRoot (line 1) | function isRoot(path: string) {

FILE: src/i18n/index.ts
  type CustomTypeOptions (line 16) | interface CustomTypeOptions {

FILE: src/index.ts
  class NutstorePlugin (line 40) | class NutstorePlugin extends Plugin {
    method onload (line 63) | async onload() {
    method onunload (line 85) | async onunload() {
    method loadSettings (line 96) | async loadSettings() {
    method saveSettings (line 184) | async saveSettings() {
    method toggleSyncUI (line 189) | toggleSyncUI(isSyncing: boolean) {
    method getDecryptedOAuthInfo (line 194) | async getDecryptedOAuthInfo() {
    method getToken (line 198) | async getToken() {
    method isAccountConfigured (line 213) | isAccountConfigured(): boolean {
    method remoteBaseDir (line 231) | get remoteBaseDir() {

FILE: src/model/stat.model.ts
  type StatModel (line 1) | type StatModel =

FILE: src/model/sync-record.model.ts
  type SyncRecordModel (line 3) | interface SyncRecordModel {

FILE: src/polyfill.test.ts
  method cwd (line 13) | cwd() {

FILE: src/polyfill.ts
  type ProcessLike (line 1) | type ProcessLike = typeof globalThis.process & {
  method cwd (line 6) | cwd() {

FILE: src/services/cache.service.v1.ts
  class CacheServiceV1 (line 19) | class CacheServiceV1 {
    method constructor (line 20) | constructor(
    method saveCache (line 28) | async saveCache(filename: string) {
    method restoreCache (line 81) | async restoreCache(filename: string) {
    method deleteCache (line 145) | async deleteCache(filename: string): Promise<void> {
    method loadCacheFileList (line 168) | async loadCacheFileList() {

FILE: src/services/chat.service.test.ts
  function createStore (line 13) | function createStore(store: Map<string, any>) {
  method reset (line 33) | reset() {
  function createPlugin (line 59) | function createPlugin() {
  function createPluginWithTwoProviders (line 84) | function createPluginWithTwoProviders() {
  function createPluginWithVault (line 121) | function createPluginWithVault(initialFiles: Record<string, string> = {}) {
  function deferredCompletion (line 203) | function deferredCompletion() {
  function deferredResult (line 248) | function deferredResult<T>() {
  function getActiveSession (line 259) | function getActiveSession(service: ChatService) {
  function getLoadedSession (line 263) | function getLoadedSession(service: ChatService, sessionId: string) {
  method createFolder (line 994) | async createFolder(path: string) {
  method createBinary (line 999) | async createBinary(path: string, data: ArrayBuffer) {
  method modifyBinary (line 1005) | async modifyBinary(file: any, data: ArrayBuffer) {
  method delete (line 1011) | async delete(file: any) {
  method trash (line 1023) | async trash(file: any) {

FILE: src/services/chat.service.ts
  constant MAX_TASK_DEPTH (line 56) | const MAX_TASK_DEPTH = 2
  constant MAX_CONCURRENT_TASKS_PER_SESSION (line 57) | const MAX_CONCURRENT_TASKS_PER_SESSION = 3
  constant CHAT_META_KEY (line 58) | const CHAT_META_KEY = 'chat_meta'
  constant CHAT_INDEX_KEY (line 59) | const CHAT_INDEX_KEY = 'chat_index'
  constant INTERRUPTED_TASK_CANCEL_REASON (line 60) | const INTERRUPTED_TASK_CANCEL_REASON = 'interrupted_by_restart'
  constant INTERRUPTED_TASK_FAILURE_STAGE (line 61) | const INTERRUPTED_TASK_FAILURE_STAGE = 'interrupted_by_restart'
  constant COMPRESSION_PROMPT (line 62) | const COMPRESSION_PROMPT = [
  type ResolvedToolResult (line 73) | interface ResolvedToolResult {
  type DeferredTaskCompletion (line 79) | interface DeferredTaskCompletion {
  type AgentRunResult (line 85) | interface AgentRunResult {
  type SessionRuntimeState (line 93) | interface SessionRuntimeState {
  function toTextParts (line 100) | function toTextParts(text: string): AIMessageContentPart[] {
  function messageToText (line 104) | function messageToText(message: Pick<ChatMessage, 'content'> | AIMessage) {
  function getAssistantToolCalls (line 117) | function getAssistantToolCalls(message: ChatMessage) {
  function getPathDepth (line 121) | function getPathDepth(path: string) {
  function getParentVaultPaths (line 125) | function getParentVaultPaths(path: string) {
  function normalizeReversibleVaultPath (line 136) | function normalizeReversibleVaultPath(path: string) {
  function normalizeReversibleToolOpRecord (line 145) | function normalizeReversibleToolOpRecord(
  function decodeBase64ToArrayBuffer (line 159) | function decodeBase64ToArrayBuffer(contentBase64: string) {
  function isVaultFolder (line 175) | function isVaultFolder(
  function isVaultFile (line 181) | function isVaultFile(target: unknown): target is { path: string } {
  function deriveTitle (line 185) | function deriveTitle(session: Pick<AISession, 'fragments'>) {
  function createVaultToolGuidance (line 198) | function createVaultToolGuidance() {
  function createMainSystemPrompt (line 207) | function createMainSystemPrompt(maxDepth: number) {
  function createSubagentSystemPrompt (line 217) | function createSubagentSystemPrompt(canSpawn: boolean) {
  class ChatService (line 229) | class ChatService {
    method constructor (line 252) | constructor(private plugin: NutstorePlugin) {}
    method initialize (line 254) | async initialize() {
    method initializeInternal (line 266) | private async initializeInternal() {
    method subscribe (line 291) | subscribe(listener: () => void) {
    method handleSettingsChanged (line 298) | async handleSettingsChanged() {
    method getViewProps (line 314) | getViewProps(): ChatboxProps {
    method ensureSession (line 418) | async ensureSession() {
    method createSession (line 422) | async createSession() {
    method switchSession (line 435) | async switchSession(sessionId: string) {
    method deleteSession (line 447) | async deleteSession(sessionId: string) {
    method selectProvider (line 480) | selectProvider(providerId: string) {
    method selectModel (line 530) | selectModel(modelId: string) {
    method sendMessage (line 577) | async sendMessage(text: string) {
    method createFragmentForActiveSession (line 610) | createFragmentForActiveSession() {
    method compressContext (line 626) | async compressContext() {
    method cancelTask (line 714) | cancelTask(taskId: string) {
    method stopActiveSessionRun (line 752) | stopActiveSessionRun() {
    method deleteMessage (line 761) | deleteMessage(messageId: string) {
    method recallMessage (line 814) | async recallMessage(messageId: string, options?: { restoreFiles?: bool...
    method regenerateMessage (line 844) | async regenerateMessage(messageId: string) {
    method stopSessionRun (line 874) | private async stopSessionRun(session: AISession) {
    method loadSessionIndex (line 897) | private async loadSessionIndex() {
    method loadSessionById (line 928) | private async loadSessionById(sessionId: string) {
    method persistSession (line 951) | private async persistSession(session: AISession) {
    method persistMetaAndIndex (line 958) | private async persistMetaAndIndex() {
    method rehydrateSession (line 972) | private rehydrateSession(session: AISession) {
    method normalizeSession (line 998) | private normalizeSession(session: AISession): AISession {
    method isChatMetaRecord (line 1081) | private isChatMetaRecord(value: unknown): value is ChatMetaRecord {
    method upsertSessionIndexItem (line 1089) | private upsertSessionIndexItem(
    method buildTimeline (line 1125) | private buildTimeline(session: AISession): ChatboxProps['timeline'] {
    method collectOtherSessionTasks (line 1178) | private collectOtherSessionTasks() {
    method getLoadedActiveSession (line 1185) | private getLoadedActiveSession() {
    method startSessionProcessor (line 1191) | private async startSessionProcessor(sessionId: string) {
    method runSessionProcessor (line 1214) | private async runSessionProcessor(sessionId: string) {
    method flushPendingMessages (line 1370) | private flushPendingMessages(session: AISession) {
    method getRuntime (line 1395) | private getRuntime(sessionId: string): SessionRuntimeState {
    method getAutoApproveRequests (line 1407) | private getAutoApproveRequests(sessionId: string) {
    method createPendingMessage (line 1416) | private createPendingMessage(text: string): ChatPendingMessage {
    method createFragment (line 1424) | private createFragment(session: AISession): ChatFragment {
    method getActiveFragment (line 1437) | private getActiveFragment(session: AISession) {
    method appendUserMessage (line 1444) | private appendUserMessage(
    method finishStoppedSessionRun (line 1462) | private finishStoppedSessionRun(session: AISession, fragment: ChatFrag...
    method cancelAllNonTerminalTasks (line 1470) | private cancelAllNonTerminalTasks(session: AISession, cancelReason: st...
    method cleanupSessionTaskTracking (line 1492) | private cleanupSessionTaskTracking(session: AISession) {
    method runTask (line 1498) | private async runTask(task: AITaskRecord) {
    method runBackgroundTaskLoop (line 1556) | private async runBackgroundTaskLoop(
    method resolveToolCalls (line 1644) | private async resolveToolCalls(
    method resolveSingleToolCall (line 1671) | private async resolveSingleToolCall(
    method startSpawnedTask (line 1700) | private startSpawnedTask(
    method spawnTask (line 1739) | private spawnTask(params: {
    method finishTaskAsCompleted (line 1802) | private finishTaskAsCompleted(
    method finishTaskAsFailed (line 1831) | private finishTaskAsFailed(
    method finishTaskAsCancelled (line 1856) | private finishTaskAsCancelled(task: AITaskRecord, cancelReason: string) {
    method countRunningTasksForSession (line 1880) | private countRunningTasksForSession(session: AISession) {
    method startQueuedTasksForSession (line 1884) | private startQueuedTasksForSession(session: AISession) {
    method createToolsForContext (line 1910) | private createToolsForContext(
    method executeToolCall (line 1944) | private async executeToolCall(
    method buildMessagesForFragment (line 1984) | private buildMessagesForFragment(
    method restoreFilesForRecall (line 1999) | private async restoreFilesForRecall(
    method deleteVaultPathIfExists (line 2071) | private async deleteVaultPathIfExists(path: string) {
    method ensureVaultDirectory (line 2087) | private async ensureVaultDirectory(path: string) {
    method writeVaultFile (line 2101) | private async writeVaultFile(path: string, contentBase64: string) {
    method removeUnmatchedToolCalls (line 2116) | private removeUnmatchedToolCalls(fragment: ChatFragment) {
    method buildTaskToolPayload (line 2158) | private buildTaskToolPayload(task: AITaskRecord) {
    method buildImmediateTaskFailurePayload (line 2186) | private buildImmediateTaskFailurePayload(
    method createDeferredTaskCompletion (line 2215) | private createDeferredTaskCompletion(): DeferredTaskCompletion {
    method resolveTaskCompletion (line 2230) | private resolveTaskCompletion(
    method cleanupTaskTracking (line 2242) | private cleanupTaskTracking(taskId: string) {
    method requireToolString (line 2247) | private requireToolString(value: unknown, field: string) {
    method isTaskTerminal (line 2254) | private isTaskTerminal(task: AITaskRecord) {
    method isTaskDescendantOf (line 2258) | private isTaskDescendantOf(
    method getProviderOrThrow (line 2275) | private getProviderOrThrow(session: AISession) {
    method getProviderByIdOrThrow (line 2287) | private getProviderByIdOrThrow(providerId: string) {
    method getModelOrThrow (line 2299) | private getModelOrThrow(provider: AIProviderConfig, session: AISession) {
    method getModelByIdsOrThrow (line 2307) | private getModelByIdsOrThrow(provider: AIProviderConfig, modelId: stri...
    method createEmptySession (line 2315) | private createEmptySession(): AISession {
    method createMessageRecord (line 2336) | private createMessageRecord(
    method sanitizeSessionSelection (line 2359) | private sanitizeSessionSelection(session: AISession) {
    method sessionHasMessages (line 2410) | private sessionHasMessages(session: AISession) {
    method getInitialSelectionForNewSession (line 2414) | private getInitialSelectionForNewSession() {
    method getEmptyStateSelection (line 2422) | private getEmptyStateSelection() {
    method syncPendingSelectionWithSettings (line 2444) | private syncPendingSelectionWithSettings() {
    method findLoadedSessionByTaskId (line 2450) | private findLoadedSessionByTaskId(taskId: string) {
    method notify (line 2459) | private notify() {
    method validateSessionSelection (line 2465) | private validateSessionSelection(session: AISession) {
    method reportFatalError (line 2479) | private reportFatalError(

FILE: src/services/command.service.ts
  class CommandService (line 10) | class CommandService {
    method constructor (line 11) | constructor(plugin: NutstorePlugin) {

FILE: src/services/events.service.ts
  class EventsService (line 14) | class EventsService {
    method constructor (line 17) | constructor(private plugin: NutstorePlugin) {
    method unload (line 73) | unload() {

FILE: src/services/i18n.service.ts
  class I18nService (line 6) | class I18nService {
    method constructor (line 7) | constructor(private plugin: NutstorePlugin) {

FILE: src/services/logger.service.ts
  class LoggerService (line 6) | class LoggerService {
    method constructor (line 9) | constructor(private plugin: NutstorePlugin) {
    method clear (line 32) | clear() {

FILE: src/services/progress.service.ts
  class ProgressService (line 13) | class ProgressService {
    method constructor (line 38) | constructor(private plugin: NutstorePlugin) {}
    method resetProgress (line 46) | public resetProgress() {
    method showProgressModal (line 53) | public showProgressModal() {
    method closeProgressModal (line 63) | public closeProgressModal() {
    method unload (line 70) | public unload() {

FILE: src/services/realtime-sync.service.ts
  class RealtimeSyncService (line 8) | class RealtimeSyncService {
    method constructor (line 23) | constructor(
    method vault (line 65) | get vault() {
    method unload (line 69) | unload() {

FILE: src/services/scheduled-sync.service.ts
  class ScheduledSyncService (line 7) | class ScheduledSyncService {
    method constructor (line 11) | constructor(
    method start (line 16) | async start() {
    method startTimer (line 34) | private startTimer(intervalSeconds: number) {
    method stopTimer (line 49) | private stopTimer() {
    method updateInterval (line 56) | async updateInterval() {
    method unload (line 61) | unload() {

FILE: src/services/status.service.ts
  class StatusService (line 6) | class StatusService {
    method constructor (line 12) | constructor(private plugin: NutstorePlugin) {
    method updateSyncStatus (line 19) | public updateSyncStatus(status: {
    method setLastSyncTime (line 34) | public setLastSyncTime(timestamp: number, failedCount: number = 0): vo...
    method updateStatusBarWithTime (line 56) | private updateStatusBarWithTime(): void {
    method stopTimeUpdates (line 77) | public stopTimeUpdates(): void {
    method unload (line 84) | public unload(): void {

FILE: src/services/sync-executor.service.ts
  type SyncOptions (line 9) | interface SyncOptions {
  class SyncExecutorService (line 13) | class SyncExecutorService {
    method constructor (line 14) | constructor(private plugin: NutstorePlugin) {}
    method executeSync (line 16) | async executeSync(options: SyncOptions) {

FILE: src/services/webdav.service.ts
  class WebDAVService (line 6) | class WebDAVService {
    method constructor (line 7) | constructor(private plugin: NutstorePlugin) {}
    method createWebDAVClient (line 9) | async createWebDAVClient(): Promise<WebDAVClient> {
    method checkWebDAVConnection (line 26) | async checkWebDAVConnection(): Promise<{ error?: Error; success: boole...

FILE: src/settings/account.ts
  class AccountSettings (line 10) | class AccountSettings extends BaseSettings {
    method display (line 13) | async display() {
    method hide (line 40) | async hide() {
    method displayManualLoginSettings (line 47) | private displayManualLoginSettings(): void {
    method displaySSOLoginSettings (line 86) | private async displaySSOLoginSettings() {
    method displayCheckConnection (line 144) | private displayCheckConnection() {

FILE: src/settings/ai.ts
  class AISettings (line 16) | class AISettings extends BaseSettings {
    method display (line 17) | async display() {
    method persist (line 124) | private async persist(showNotice: boolean = true) {

FILE: src/settings/cache.ts
  type ExportedStorage (line 14) | interface ExportedStorage {
  class CacheSettings (line 19) | class CacheSettings extends BaseSettings {
    method display (line 20) | async display() {
    method remoteCacheDir (line 106) | get remoteCacheDir() {
    method remoteCachePath (line 113) | get remoteCachePath() {
    method createRemoteCacheDir (line 121) | async createRemoteCacheDir() {

FILE: src/settings/common.ts
  constant MAX_FILE_SIZE (line 15) | const MAX_FILE_SIZE = '500MB'
  constant MAX_BYTES (line 16) | const MAX_BYTES = bytesParse(MAX_FILE_SIZE, { mode: 'jedec' })!
  class CommonSettings (line 18) | class CommonSettings extends BaseSettings {
    method display (line 19) | async display() {
    method handleMaxFileSizeBlur (line 290) | private async handleMaxFileSizeBlur(component: TextComponent) {

FILE: src/settings/filter.ts
  type ConfigDirSyncMode (line 6) | type ConfigDirSyncMode = 'none' | 'bookmarks' | 'all'
  function isConfigDirSyncMode (line 8) | function isConfigDirSyncMode(value: string): value is ConfigDirSyncMode {
  class FilterSettings (line 12) | class FilterSettings extends BaseSettings {
    method display (line 13) | async display() {
  class ConfigDirSyncBookmarksModal (line 107) | class ConfigDirSyncBookmarksModal extends Modal {
    method constructor (line 108) | constructor(
    method onOpen (line 116) | onOpen() {
    method onClose (line 146) | onClose() {
  class ConfigDirSyncWarningModal (line 151) | class ConfigDirSyncWarningModal extends Modal {
    method constructor (line 152) | constructor(
    method onOpen (line 160) | onOpen() {
    method onClose (line 197) | onClose() {

FILE: src/settings/index.ts
  type SyncMode (line 16) | enum SyncMode {
  type NutstoreSettings (line 21) | interface NutstoreSettings {
  function setPluginInstance (line 54) | function setPluginInstance(plugin: NutstorePlugin | null) {
  function waitUntilPluginInstance (line 58) | function waitUntilPluginInstance() {
  function useSettings (line 62) | async function useSettings() {
  class NutstoreSettingTab (line 67) | class NutstoreSettingTab extends PluginSettingTab {
    method constructor (line 81) | constructor(app: App, plugin: NutstorePlugin) {
    method display (line 123) | async display() {
    method isSSO (line 136) | get isSSO() {
    method hide (line 140) | async hide() {

FILE: src/settings/log.ts
  class LogSettings (line 8) | class LogSettings extends BaseSettings {
    method display (line 9) | async display() {
    method logs (line 35) | get logs() {
    method saveLogsToNote (line 42) | async saveLogsToNote() {

FILE: src/settings/settings.base.ts
  method constructor (line 6) | constructor(

FILE: src/shims/node-zlib.ts
  function unsupported (line 1) | function unsupported(functionName: string): never {
  function gunzipSync (line 13) | function gunzipSync(): never {
  function gzipSync (line 17) | function gzipSync(): never {
  function deflateSync (line 21) | function deflateSync(): never {
  function inflateSync (line 25) | function inflateSync(): never {

FILE: src/storage/blob.ts
  function useBlobStore (line 4) | function useBlobStore() {

FILE: src/storage/kv.ts
  constant DB_NAME (line 7) | const DB_NAME = 'Nutstore_Plugin_Cache'
  type TraverseWebDAVCache (line 23) | interface TraverseWebDAVCache {
  type ChatMetaRecord (line 36) | interface ChatMetaRecord {

FILE: src/storage/sync-record.ts
  class SyncRecord (line 4) | class SyncRecord {
    method constructor (line 5) | constructor(
    method updateFileRecord (line 10) | async updateFileRecord(path: string, record: SyncRecordModel): Promise...
    method deleteFileRecord (line 20) | async deleteFileRecord(path: string): Promise<void> {
    method getRecords (line 30) | async getRecords(): Promise<Map<string, SyncRecordModel>> {
    method setRecords (line 35) | async setRecords(records: Map<string, SyncRecordModel>) {
    method getRecord (line 39) | async getRecord(path: string): Promise<SyncRecordModel | undefined> {
    method drop (line 46) | async drop() {
    method exists (line 50) | async exists(path: string): Promise<boolean> {
    method batchUpdate (line 58) | async batchUpdate(updates: [string, SyncRecordModel][]): Promise<void> {

FILE: src/storage/use-storage.ts
  type UseStorageType (line 9) | type UseStorageType<T = any> = ReturnType<typeof useStorage<T>>
  function useStorage (line 11) | function useStorage<T = any>(instance: StorageInterface<T>) {

FILE: src/sync/core/merge-utils.ts
  type LatestTimestampResolution (line 8) | enum LatestTimestampResolution {
  type LatestTimestampParams (line 14) | interface LatestTimestampParams {
  type LatestTimestampResult (line 21) | type LatestTimestampResult =
  function resolveByLatestTimestamp (line 26) | function resolveByLatestTimestamp(
  type IntelligentMergeParams (line 61) | interface IntelligentMergeParams {
  type IntelligentMergeResult (line 67) | interface IntelligentMergeResult {
  function diff3MergeStrings (line 75) | function diff3MergeStrings(
  function resolveByIntelligentMerge (line 97) | async function resolveByIntelligentMerge(

FILE: src/sync/decision/base.decider.ts
  method constructor (line 7) | constructor(
  method getSyncRecordStorage (line 14) | protected getSyncRecordStorage() {
  method webdav (line 18) | get webdav() {
  method settings (line 22) | get settings() {
  method vault (line 26) | get vault() {
  method remoteBaseDir (line 30) | get remoteBaseDir() {

FILE: src/sync/decision/has-folder-content-changed.ts
  function hasFolderContentChanged (line 12) | function hasFolderContentChanged(

FILE: src/sync/decision/sync-decision.interface.ts
  type SyncDecisionSettings (line 8) | interface SyncDecisionSettings {
  type SyncRecordItem (line 16) | interface SyncRecordItem {
  type TaskOptions (line 22) | interface TaskOptions {
  type ConflictTaskOptions (line 28) | interface ConflictTaskOptions extends TaskOptions {
  type PullTaskOptions (line 36) | interface PullTaskOptions extends TaskOptions {
  type SkippedTaskOptions (line 40) | type SkippedTaskOptions = TaskOptions &
  type TaskFactory (line 66) | interface TaskFactory {
  type SyncDecisionInput (line 80) | interface SyncDecisionInput {

FILE: src/sync/decision/two-way.decider.function.ts
  function pickConflictStrategy (line 22) | function pickConflictStrategy(
  function twoWayDecider (line 33) | async function twoWayDecider(

FILE: src/sync/decision/two-way.decider.ts
  class TwoWaySyncDecider (line 25) | class TwoWaySyncDecider extends BaseSyncDecider {
    method decide (line 26) | async decide(): Promise<BaseTask[]> {

FILE: src/sync/index.ts
  type SyncStartMode (line 45) | enum SyncStartMode {
  class NutstoreSync (line 50) | class NutstoreSync {
    method constructor (line 57) | constructor(
    method start (line 84) | async start({ mode }: { mode: SyncStartMode }) {
    method execTasks (line 456) | private async execTasks(
    method executeWithRetry (line 521) | private async executeWithRetry(task: BaseTask): Promise<TaskResult> {
    method updateMtimeInRecord (line 544) | async updateMtimeInRecord(tasks: BaseTask[], results: TaskResult[]) {
    method handle503Error (line 555) | private async handle503Error(waitMs: number) {
    method app (line 566) | get app() {
    method webdav (line 570) | get webdav() {
    method vault (line 574) | get vault() {
    method remoteBaseDir (line 578) | get remoteBaseDir() {
    method settings (line 582) | get settings() {

FILE: src/sync/tasks/adapter-tasks.test.ts
  function createVault (line 16) | function createVault() {
  function createWebdav (line 36) | function createWebdav() {

FILE: src/sync/tasks/clean-record.task.ts
  class CleanRecordTask (line 4) | class CleanRecordTask extends BaseTask {
    method exec (line 5) | async exec() {

FILE: src/sync/tasks/conflict-resolve.task.ts
  type ConflictStrategy (line 19) | enum ConflictStrategy {
  class ConflictResolveTask (line 26) | class ConflictResolveTask extends BaseTask {
    method constructor (line 27) | constructor(
    method exec (line 39) | async exec() {
    method execLatestTimeStamp (line 86) | async execLatestTimeStamp(local: StatModel, remote: StatModel) {
    method execIntelligentMergeOrSkip (line 148) | async execIntelligentMergeOrSkip() {
    method execIntelligentMerge (line 226) | async execIntelligentMerge() {

FILE: src/sync/tasks/filename-error.task.ts
  class FilenameError (line 6) | class FilenameError extends Error {
    method constructor (line 7) | constructor(
    method format (line 20) | private static format(invalidChars: string[], filePath: string) {
  class FilenameErrorTask (line 35) | class FilenameErrorTask extends BaseTask {
    method exec (line 36) | exec() {

FILE: src/sync/tasks/mkdir-local.task.ts
  class MkdirLocalTask (line 5) | class MkdirLocalTask extends BaseTask {
    method exec (line 6) | async exec() {

FILE: src/sync/tasks/mkdir-remote.task.ts
  class MkdirRemoteTask (line 6) | class MkdirRemoteTask extends BaseTask {
    method exec (line 7) | async exec() {

FILE: src/sync/tasks/mkdirs-remote.task.ts
  type MkdirsRemoteTaskOptions (line 6) | interface MkdirsRemoteTaskOptions extends BaseTaskOptions {
  class MkdirsRemoteTask (line 16) | class MkdirsRemoteTask extends BaseTask {
    method constructor (line 19) | constructor(options: MkdirsRemoteTaskOptions) {
    method exec (line 24) | async exec() {
    method getAllPaths (line 49) | getAllPaths(): Array<{ localPath: string; remotePath: string }> {
    method toJSON (line 56) | toJSON() {

FILE: src/sync/tasks/noop.task.ts
  class NoopTask (line 3) | class NoopTask extends BaseTask {
    method exec (line 4) | exec() {

FILE: src/sync/tasks/pull.task.ts
  class PullTask (line 7) | class PullTask extends BaseTask {
    method constructor (line 8) | constructor(
    method remoteSize (line 16) | get remoteSize() {
    method exec (line 20) | async exec() {
  function bufferLikeToArrayBuffer (line 40) | function bufferLikeToArrayBuffer(buffer: BufferLike): ArrayBuffer {
  function toArrayBuffer (line 48) | function toArrayBuffer(buf: Buffer): ArrayBuffer {

FILE: src/sync/tasks/push.task.ts
  class PushTask (line 4) | class PushTask extends BaseTask {
    method exec (line 5) | async exec() {

FILE: src/sync/tasks/remove-local.task.ts
  class RemoveLocalTask (line 5) | class RemoveLocalTask extends BaseTask {
    method constructor (line 6) | constructor(
    method exec (line 14) | async exec() {

FILE: src/sync/tasks/remove-remote-recursively.task.ts
  class RemoveRemoteRecursivelyTask (line 4) | class RemoveRemoteRecursivelyTask extends BaseTask {
    method exec (line 5) | async exec() {

FILE: src/sync/tasks/remove-remote.task.ts
  class RemoveRemoteTask (line 4) | class RemoveRemoteTask extends BaseTask {
    method exec (line 5) | async exec() {

FILE: src/sync/tasks/skipped.task.ts
  type SkipReason (line 3) | enum SkipReason {
  type SkippedTaskOptions (line 8) | type SkippedTaskOptions = BaseTaskOptions &
  class SkippedTask (line 34) | class SkippedTask extends BaseTask {
    method constructor (line 35) | constructor(readonly options: SkippedTaskOptions) {
    method exec (line 39) | exec() {

FILE: src/sync/tasks/task.interface.ts
  type BaseTaskOptions (line 8) | interface BaseTaskOptions {
  type TaskSuccessResult (line 17) | interface TaskSuccessResult {
  type TaskFailureResult (line 22) | interface TaskFailureResult {
  type TaskResult (line 28) | type TaskResult = TaskSuccessResult | TaskFailureResult
  method constructor (line 31) | constructor(readonly options: BaseTaskOptions) {}
  method vault (line 33) | get vault() {
  method syncRecord (line 37) | get syncRecord() {
  method webdav (line 41) | get webdav() {
  method remoteBaseDir (line 45) | get remoteBaseDir() {
  method remotePath (line 49) | get remotePath() {
  method localPath (line 55) | get localPath() {
  method toJSON (line 61) | toJSON() {
  class TaskError (line 73) | class TaskError extends Error {
    method constructor (line 74) | constructor(
  function toTaskError (line 84) | function toTaskError(e: unknown, task: BaseTask): TaskError {

FILE: src/sync/utils/has-ignored-in-folder.ts
  function hasIgnoredInFolder (line 10) | function hasIgnoredInFolder(
  function getIgnoredPathsInFolder (line 31) | function getIgnoredPathsInFolder(

FILE: src/sync/utils/is-mergeable-path.ts
  function isMergeablePath (line 3) | function isMergeablePath(path: string): boolean {

FILE: src/sync/utils/merge-mkdir-tasks.ts
  function mergeMkdirTasks (line 17) | function mergeMkdirTasks(

FILE: src/sync/utils/merge-remove-remote-tasks.ts
  function mergeRemoveRemoteTasks (line 6) | function mergeRemoveRemoteTasks(

FILE: src/sync/utils/update-records.ts
  function updateMtimeInRecord (line 22) | async function updateMtimeInRecord(

FILE: src/types/obsidian-extended.d.ts
  type ObsidianSetting (line 17) | interface ObsidianSetting {
  type App (line 31) | interface App {

FILE: src/utils/apply-deltas-to-stats.ts
  function applyDeltasToStats (line 8) | function applyDeltasToStats(

FILE: src/utils/breakable-sleep.ts
  function finish (line 14) | function finish() {

FILE: src/utils/config-dir-rules.test.ts
  function createPluginMock (line 9) | function createPluginMock(

FILE: src/utils/config-dir-rules.ts
  type ConfigDirSyncMode (line 4) | type ConfigDirSyncMode = 'none' | 'bookmarks' | 'all'
  type EffectiveFilterRules (line 6) | interface EffectiveFilterRules {
  type ConfigDirFilterRuleInput (line 13) | interface ConfigDirFilterRuleInput {
  constant CONFIG_DIR_SYSTEM_EXCLUSION_SUFFIXES (line 18) | const CONFIG_DIR_SYSTEM_EXCLUSION_SUFFIXES = [
  function makeCaseSensitiveRule (line 26) | function makeCaseSensitiveRule(expr: string): GlobMatchOptions {
  function getConfigDirSystemTraversalRules (line 30) | function getConfigDirSystemTraversalRules(
  function getConfigDirSystemFilterRules (line 38) | function getConfigDirSystemFilterRules(
  function computeEffectiveFilterRulesFromParts (line 47) | function computeEffectiveFilterRulesFromParts(
  function computeEffectiveFilterRules (line 86) | function computeEffectiveFilterRules(

FILE: src/utils/create-id.ts
  function createId (line 3) | function createId(prefix: string) {

FILE: src/utils/decrypt-ticket-response.ts
  type OAuthResponse (line 3) | interface OAuthResponse {
  function decryptOAuthResponse (line 9) | async function decryptOAuthResponse(cipherText: string) {

FILE: src/utils/deep-stringify.ts
  function deepStringify (line 30) | function deepStringify(

FILE: src/utils/file-stat-to-stat-model.ts
  function fileStatToStatModel (line 4) | function fileStatToStatModel(from: FileStat): StatModel {

FILE: src/utils/format-relative-time.ts
  function formatRelativeTime (line 3) | function formatRelativeTime(timestamp: number): string {

FILE: src/utils/get-db-key.ts
  function getDBKey (line 6) | function getDBKey(vaultName: string, remoteBaseDir: string) {
  function getTraversalWebDAVDBKey (line 13) | async function getTraversalWebDAVDBKey(

FILE: src/utils/get-root-folder-name.ts
  function getRootFolderName (line 3) | function getRootFolderName(path: string) {

FILE: src/utils/get-task-name.ts
  function getTaskName (line 17) | function getTaskName(task: BaseTask) {

FILE: src/utils/glob-match.ts
  type GlobMatchUserOptions (line 5) | interface GlobMatchUserOptions {
  type GlobMatchOptions (line 9) | interface GlobMatchOptions {
  constant DEFAULT_USER_OPTIONS (line 14) | const DEFAULT_USER_OPTIONS: GlobMatchUserOptions = {
  function isVoidGlobMatchOptions (line 18) | function isVoidGlobMatchOptions(options: GlobMatchOptions): boolean {
  function generateFlags (line 22) | function generateFlags(options: GlobMatchUserOptions) {
  function normalizePath (line 30) | function normalizePath(rawPath: string) {
  function buildRegExp (line 45) | function buildRegExp(expr: string, options: GlobMatchUserOptions) {
  class GlobMatch (line 53) | class GlobMatch {
    method constructor (line 62) | constructor(
    method matchDirectoryBySegments (line 87) | private matchDirectoryBySegments(segments: string[], isDirPath: boolea...
    method matchDirectoryByPrefix (line 100) | private matchDirectoryByPrefix(segments: string[], isDirPath: boolean) {
    method test (line 114) | test(path: string) {
  function getUserOptions (line 132) | function getUserOptions(
  function needIncludeFromGlobRules (line 141) | function needIncludeFromGlobRules(

FILE: src/utils/has-invalid-char.ts
  constant INVALID_CHARS (line 1) | const INVALID_CHARS = ':*?"<>|'
  constant INVALID_CHARS_LIST (line 2) | const INVALID_CHARS_LIST = INVALID_CHARS.split('')
  function hasInvalidChar (line 4) | function hasInvalidChar(str: string) {
  function getInvalidChars (line 8) | function getInvalidChars(str: string): string[] {

FILE: src/utils/is-503-error.ts
  constant ERROR_MESSAGE (line 1) | const ERROR_MESSAGE = 'Invalid response: 503 Service Unavailable'
  function is503Error (line 3) | function is503Error(err: Error | string) {

FILE: src/utils/is-numeric.ts
  function isNumeric (line 3) | function isNumeric(val: any) {

FILE: src/utils/is-same-time.ts
  function isSameTime (line 1) | function isSameTime(

FILE: src/utils/is-sub.ts
  function isSub (line 3) | function isSub(parent: string, sub: string) {

FILE: src/utils/merge-dig-in.ts
  function mergeDigIn (line 8) | function mergeDigIn(

FILE: src/utils/mime/is_markdown_path.ts
  function isMarkdownPath (line 1) | function isMarkdownPath(path: string) {

FILE: src/utils/mkdirs-vault.ts
  function mkdirsVault (line 4) | async function mkdirsVault(vault: Vault, path: string) {

FILE: src/utils/mkdirs-webdav.ts
  function mkdirsWebDAV (line 3) | function mkdirsWebDAV(client: WebDAVClient, path: string) {

FILE: src/utils/ns-api.ts
  function NSAPI (line 3) | function NSAPI(name: 'delta' | 'latestDeltaCursor') {

FILE: src/utils/rate-limited-client.ts
  function createRateLimitedWebDAVClient (line 4) | function createRateLimitedWebDAVClient(

FILE: src/utils/remote-path-to-absolute.ts
  function remotePathToAbsolute (line 3) | function remotePathToAbsolute(

FILE: src/utils/remote-path-to-local-path.ts
  function remotePathToLocalPath (line 3) | function remotePathToLocalPath(

FILE: src/utils/request-url.ts
  constant USER_AGENT (line 27) | const USER_AGENT = `Obsidian (${getOS()}; ${getDevice()}; ObsidianNutsto...
  class RequestUrlError (line 29) | class RequestUrlError extends Error {
    method constructor (line 30) | constructor(public res: RequestUrlResponse) {
  function requestUrl (line 35) | async function requestUrl(p: RequestUrlParam | string) {

FILE: src/utils/sha256.ts
  function sha256 (line 3) | async function sha256(data: ArrayBuffer) {
  function sha256Hex (line 7) | async function sha256Hex(data: ArrayBuffer) {
  function sha256Base64 (line 14) | async function sha256Base64(data: ArrayBuffer) {

FILE: src/utils/sleep.ts
  function sleep (line 1) | async function sleep(ms: number) {

FILE: src/utils/stat-vault-item.ts
  function statVaultItem (line 5) | async function statVaultItem(

FILE: src/utils/stat-webdav-item.ts
  function statWebDAVItem (line 5) | async function statWebDAVItem(client: WebDAVClient, path: string) {

FILE: src/utils/std-remote-path.ts
  function stdRemotePath (line 3) | function stdRemotePath(remotePath: string): `/${string}/` {

FILE: src/utils/traverse-local-vault.ts
  function traverseLocalVault (line 7) | async function traverseLocalVault(vault: Vault, from: string) {

FILE: src/utils/traverse-webdav.ts
  function getTraversalLock (line 22) | function getTraversalLock(kvKey: string): Mutex {
  function executeWithRetry (line 29) | async function executeWithRetry<T>(func: () => MaybePromise<T>): Promise...
  class ResumableWebDAVTraversal (line 43) | class ResumableWebDAVTraversal {
    method normalizeDirPath (line 57) | private normalizeDirPath(path: string): string {
    method normalizeForComparison (line 65) | private normalizeForComparison(path: string): string {
    method constructor (line 73) | constructor(options: {
    method lock (line 85) | get lock() {
    method cursor (line 89) | get cursor(): string {
    method traverse (line 93) | async traverse(): Promise<StatModel[]> {
    method bfsTraverse (line 128) | private async bfsTraverse(): Promise<StatModel[]> {
    method fetchAllDelta (line 213) | private async *fetchAllDelta(startCursor: string): AsyncGenerator<{
    method applyDeltaDuringTraversal (line 259) | private async applyDeltaDuringTraversal(
    method incrementalScan (line 306) | private async incrementalScan(): Promise<StatModel[]> {
    method applyDeltaToNodes (line 348) | private applyDeltaToNodes(entries: Array<DeltaEntry>): void {
    method getAllFromCache (line 488) | private getAllFromCache(): StatModel[] {
    method loadState (line 499) | private async loadState(): Promise<void> {
    method saveState (line 511) | private async saveState(): Promise<void> {
    method clearCache (line 522) | async clearCache(): Promise<void> {
    method isCacheValid (line 533) | async isCacheValid(): Promise<boolean> {

FILE: src/utils/types.ts
  type MaybePromise (line 1) | type MaybePromise<T> = Promise<T> | T

FILE: src/utils/uint8array-to-arraybuffer.ts
  function uint8ArrayToArrayBuffer (line 1) | function uint8ArrayToArrayBuffer(data: Uint8Array<ArrayBuffer>) {

FILE: src/utils/vault-adapter-utils.test.ts
  type AdapterMock (line 7) | type AdapterMock = {
  function createVault (line 14) | function createVault(adapterOverrides: Partial<AdapterMock> = {}) {

FILE: src/utils/wait-until.ts
  function waitUntil (line 3) | async function waitUntil<T>(condition: () => T, duration = 100) {

FILE: src/views/chatbox.view.ts
  constant CHATBOX_VIEW_TYPE (line 8) | const CHATBOX_VIEW_TYPE = 'nutstore-sync-chatbox'
  class ChatboxView (line 10) | class ChatboxView extends ItemView {
    method constructor (line 50) | constructor(
    method getViewType (line 57) | getViewType() {
    method getDisplayText (line 61) | getDisplayText() {
    method getIcon (line 65) | getIcon() {
    method getChatboxProps (line 69) | private getChatboxProps(): ChatboxProps {
    method onOpen (line 76) | async onOpen() {
    method onClose (line 88) | async onClose() {

FILE: src/webdav-patch.ts
  function objKeyToLower (line 18) | function objKeyToLower(obj: Record<string, string>) {
  function onlyAscii (line 29) | function onlyAscii(str: string) {

FILE: test/mocks/obsidian.ts
  class Notice (line 1) | class Notice {
    method constructor (line 2) | constructor(_message: string, _timeout?: number) {}
  class App (line 5) | class App {}
  class Modal (line 6) | class Modal {
    method empty (line 8) | empty() {}
    method createEl (line 9) | createEl(_tag: string, _attrs?: { text?: string }) {
    method constructor (line 16) | constructor(_app: App) {}
    method setTitle (line 18) | setTitle(_title: string) {}
    method open (line 19) | open() {}
    method close (line 20) | close() {}
  class Setting (line 23) | class Setting {
    method constructor (line 24) | constructor(_containerEl: unknown) {}
    method addButton (line 26) | addButton(
  class TFile (line 52) | class TFile {}
  class TFolder (line 53) | class TFolder {}
  class Component (line 54) | class Component {
    method load (line 55) | load() {}
    method unload (line 56) | unload() {}
  class ItemView (line 58) | class ItemView {}
  class WorkspaceLeaf (line 59) | class WorkspaceLeaf {}
  method render (line 62) | async render() {}
  function normalizePath (line 65) | function normalizePath(path: string) {
Condensed preview — 231 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (3,781K chars).
[
  {
    "path": ".github/workflows/changelog.yml",
    "chars": 8783,
    "preview": "name: Generate Changelog\n\non:\n  push:\n    tags:\n      - \"*\"\n\npermissions:\n  contents: write\n\njobs:\n  generate_changelog:"
  },
  {
    "path": ".github/workflows/ci.yml",
    "chars": 1216,
    "preview": "name: CI\n\non:\n  pull_request:\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n    permissions:\n      contents: read\n      pac"
  },
  {
    "path": ".github/workflows/release.yml",
    "chars": 1725,
    "preview": "name: Release Obsidian plugin\n\non:\n  push:\n    tags:\n      - '*'\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n    environm"
  },
  {
    "path": ".github/workflows/update-changelog-version.yml",
    "chars": 2213,
    "preview": "name: Update Changelog Version\n\non:\n  release:\n    types: [published]\n\npermissions:\n  contents: write\n\njobs:\n  update-ch"
  },
  {
    "path": ".gitignore",
    "chars": 278,
    "preview": "# Intellij\r\n*.iml\r\n.idea\r\n\r\n# npm\r\nnode_modules\r\n\r\n# Exclude sourcemaps\r\n*.map\r\n\r\n# obsidian\r\ndata.json\r\n\r\n# Exclude mac"
  },
  {
    "path": ".prettierrc",
    "chars": 84,
    "preview": "{\n\t\"semi\": false,\n\t\"singleQuote\": true,\n\t\"trailingComma\": \"all\",\n\t\"useTabs\": true\n}\n"
  },
  {
    "path": ".swcrc",
    "chars": 484,
    "preview": "{\n\t\"$schema\": \"https://swc.rs/schema.json\",\n\t\"jsc\": {\n\t\t\"parser\": {\n\t\t\t\"syntax\": \"ecmascript\",\n\t\t\t\"jsx\": false,\n\t\t\t\"dyna"
  },
  {
    "path": ".vscode/settings.json",
    "chars": 907,
    "preview": "{\n\t\"editor.formatOnSave\": true,\n\t\"tailwindCSS.codeActions\": false,\n\t\"editor.defaultFormatter\": \"esbenp.prettier-vscode\","
  },
  {
    "path": "CHANGELOG.md",
    "chars": 20864,
    "preview": "# Changelog\n\n本项目的所有重要更改都将记录在此文件中。All notable changes to this project will be documented in this file.\n\n## [1.2.1]\n\n- 修复未"
  },
  {
    "path": "LICENSE",
    "chars": 34522,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "README.md",
    "chars": 2674,
    "preview": "# 🔄 Nutstore Sync\n\n## 简介 | Introduction\n\n此插件允许您通过 WebDAV 协议将 Obsidian 笔记与坚果云进行双向同步。\n_This plugin enables two-way synchro"
  },
  {
    "path": "esbuild.config.mjs",
    "chars": 1780,
    "preview": "import postcss from '@deanc/esbuild-plugin-postcss'\nimport UnoCSS from '@unocss/postcss'\nimport dotenv from 'dotenv'\nimp"
  },
  {
    "path": "manifest.json",
    "chars": 271,
    "preview": "{\n\t\"id\": \"nutstore-sync\",\n\t\"name\": \"Nutstore Sync\",\n\t\"version\": \"1.2.1\",\n\t\"minAppVersion\": \"0.15.0\",\n\t\"description\": \"Sy"
  },
  {
    "path": "package.json",
    "chars": 2606,
    "preview": "{\n\t\"name\": \"obsidian-nutstore-sync\",\n\t\"version\": \"1.2.1\",\n\t\"main\": \"main.js\",\n\t\"scripts\": {\n\t\t\"dev\": \"run-p dev:*\",\n\t\t\"d"
  },
  {
    "path": "packages/chatbox/package.json",
    "chars": 661,
    "preview": "{\n\t\"name\": \"chatbox\",\n\t\"version\": \"0.0.0\",\n\t\"type\": \"module\",\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"types\": \"./dist/index.d.ts\",\n\t\t"
  },
  {
    "path": "packages/chatbox/postcss.config.mjs",
    "chars": 79,
    "preview": "import UnoCSS from '@unocss/postcss'\n\nexport default {\n\tplugins: [UnoCSS()],\n}\n"
  },
  {
    "path": "packages/chatbox/rslib.config.ts",
    "chars": 471,
    "preview": "import { pluginBabel } from '@rsbuild/plugin-babel'\nimport { pluginSolid } from '@rsbuild/plugin-solid'\nimport { defineC"
  },
  {
    "path": "packages/chatbox/src/App.tsx",
    "chars": 20837,
    "preview": "import {\n\tFor,\n\tMatch,\n\tShow,\n\tSwitch,\n\tcreateEffect,\n\tcreateSignal,\n\tonCleanup,\n} from 'solid-js'\nimport { ConfirmDialo"
  },
  {
    "path": "packages/chatbox/src/assets/styles/global.css",
    "chars": 1797,
    "preview": "@unocss;\n\n.markdown-rendered {\n\tmin-width: 0;\n\toverflow-wrap: anywhere;\n\tword-break: break-word;\n}\n\n.markdown-rendered >"
  },
  {
    "path": "packages/chatbox/src/components/ConfirmDialog.tsx",
    "chars": 1924,
    "preview": "import { Show } from 'solid-js'\nimport { t } from '../i18n'\n\nexport function ConfirmDialog(props: {\n\ttitle: string | und"
  },
  {
    "path": "packages/chatbox/src/components/ContentParts.tsx",
    "chars": 1587,
    "preview": "import { For, Match, Show, Switch } from 'solid-js'\nimport type { ChatMessageContentPart, ChatboxProps } from '../types'"
  },
  {
    "path": "packages/chatbox/src/components/CopyButton.tsx",
    "chars": 1460,
    "preview": "import { Show, createSignal, onCleanup } from 'solid-js'\nimport { t } from '../i18n'\n\nexport function CopyButton(props: "
  },
  {
    "path": "packages/chatbox/src/components/FragmentDivider.tsx",
    "chars": 559,
    "preview": "import type { ChatTimelineFragmentItem } from '../types'\nimport { formatFragmentTime } from '../utils'\n\nexport function "
  },
  {
    "path": "packages/chatbox/src/components/MarkdownContent.tsx",
    "chars": 1156,
    "preview": "import { createEffect, onCleanup } from 'solid-js'\nimport type { ChatboxProps } from '../types'\n\nexport function Markdow"
  },
  {
    "path": "packages/chatbox/src/components/MessageCard.tsx",
    "chars": 7641,
    "preview": "import { Show } from 'solid-js'\nimport type { ChatTimelineMessageItem, ChatboxProps } from '../types'\nimport { t } from "
  },
  {
    "path": "packages/chatbox/src/components/PaneResizer.tsx",
    "chars": 1681,
    "preview": "import { createSignal, onCleanup } from 'solid-js'\n\ninterface PaneResizerProps {\n\tonResizeStart?: () => void\n\tonResize: "
  },
  {
    "path": "packages/chatbox/src/components/PendingList.tsx",
    "chars": 851,
    "preview": "import { For, Show } from 'solid-js'\nimport type { ChatboxProps } from '../types'\nimport { t } from '../i18n'\n\nexport fu"
  },
  {
    "path": "packages/chatbox/src/components/RunStateCard.tsx",
    "chars": 1563,
    "preview": "import { Show } from 'solid-js'\nimport type { ChatboxProps } from '../types'\nimport { t } from '../i18n'\nimport { runSta"
  },
  {
    "path": "packages/chatbox/src/components/SessionHistoryItem.tsx",
    "chars": 1893,
    "preview": "import { Show } from 'solid-js'\nimport type { ChatboxProps } from '../types'\nimport { t } from '../i18n'\nimport { format"
  },
  {
    "path": "packages/chatbox/src/components/TaskCard.tsx",
    "chars": 3107,
    "preview": "import { Show } from 'solid-js'\nimport type { ChatTaskRecord, ChatboxProps } from '../types'\nimport { t } from '../i18n'"
  },
  {
    "path": "packages/chatbox/src/components/TasksPanel.tsx",
    "chars": 2033,
    "preview": "import { For, Show } from 'solid-js'\nimport type { ChatboxProps } from '../types'\nimport { t } from '../i18n'\nimport { T"
  },
  {
    "path": "packages/chatbox/src/i18n/index.ts",
    "chars": 638,
    "preview": "import * as i18n from '@solid-primitives/i18n'\nimport { createResource, createSignal } from 'solid-js'\nimport en from '."
  },
  {
    "path": "packages/chatbox/src/i18n/locales/en.ts",
    "chars": 2357,
    "preview": "const en = {\n\thistory: 'History',\n\tdeleteSession: 'Delete',\n\tdeleteSessionTitle: 'Delete Session',\n\tdeleteSessionMessage"
  },
  {
    "path": "packages/chatbox/src/i18n/locales/zh.ts",
    "chars": 1520,
    "preview": "const zh = {\n\thistory: '历史',\n\tdeleteSession: '删除',\n\tdeleteSessionTitle: '删除会话',\n\tdeleteSessionMessage: '确认删除这个会话吗?删除后不可恢"
  },
  {
    "path": "packages/chatbox/src/index.tsx",
    "chars": 630,
    "preview": "import './assets/styles/global.css'\n\nimport { createStore, reconcile } from 'solid-js/store'\nimport { render } from 'sol"
  },
  {
    "path": "packages/chatbox/src/types.ts",
    "chars": 4962,
    "preview": "export interface ChatUsage {\n\tinputTokens?: number\n\toutputTokens?: number\n\ttotalTokens?: number\n}\n\nexport type Reversibl"
  },
  {
    "path": "packages/chatbox/src/utils.ts",
    "chars": 2528,
    "preview": "import { ChatTaskRecord, ChatRunState } from './types'\nimport { t } from './i18n'\n\nexport function formatTime(timestamp:"
  },
  {
    "path": "packages/chatbox/tsconfig.json",
    "chars": 493,
    "preview": "{\n\t\"compilerOptions\": {\n\t\t\"lib\": [\"DOM\", \"ES2020\"],\n\t\t\"jsx\": \"preserve\",\n\t\t\"target\": \"ES2020\",\n\t\t\"noEmit\": true,\n\t\t\"skip"
  },
  {
    "path": "packages/chatbox/unocss.config.ts",
    "chars": 1875,
    "preview": "import { defineConfig, presetIcons, presetUno } from 'unocss'\n\nexport default defineConfig({\n\tcontent: {\n\t\tfilesystem: ["
  },
  {
    "path": "packages/webdav-explorer/package.json",
    "chars": 669,
    "preview": "{\n\t\"name\": \"webdav-explorer\",\n\t\"version\": \"0.0.0\",\n\t\"type\": \"module\",\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"types\": \"./dist/index.d"
  },
  {
    "path": "packages/webdav-explorer/postcss.config.mjs",
    "chars": 79,
    "preview": "import UnoCSS from '@unocss/postcss'\n\nexport default {\n\tplugins: [UnoCSS()],\n}\n"
  },
  {
    "path": "packages/webdav-explorer/rslib.config.ts",
    "chars": 471,
    "preview": "import { pluginBabel } from '@rsbuild/plugin-babel'\nimport { pluginSolid } from '@rsbuild/plugin-solid'\nimport { defineC"
  },
  {
    "path": "packages/webdav-explorer/src/App.tsx",
    "chars": 2253,
    "preview": "import { Notice } from 'obsidian'\nimport path from 'path-browserify'\nimport { createSignal, Show } from 'solid-js'\nimpor"
  },
  {
    "path": "packages/webdav-explorer/src/assets/styles/global.css",
    "chars": 9,
    "preview": "@unocss;\n"
  },
  {
    "path": "packages/webdav-explorer/src/components/File.tsx",
    "chars": 330,
    "preview": "export interface FolderProps {\n\tname: string\n}\n\nfunction File(props: FolderProps) {\n\treturn (\n\t\t<div class=\"flex gap-2 i"
  },
  {
    "path": "packages/webdav-explorer/src/components/FileList.tsx",
    "chars": 1452,
    "preview": "import { Notice } from 'obsidian'\nimport { createEffect, createSignal, For, Show } from 'solid-js'\nimport { type fs } fr"
  },
  {
    "path": "packages/webdav-explorer/src/components/Folder.tsx",
    "chars": 435,
    "preview": "export interface FolderProps {\n\tname: string\n\tpath: string\n\tonClick: (path: string) => void\n}\n\nfunction Folder(props: Fo"
  },
  {
    "path": "packages/webdav-explorer/src/components/NewFolder.tsx",
    "chars": 727,
    "preview": "import { createSignal } from 'solid-js'\nimport { t } from '../i18n'\n\ninterface NewFolderProps {\n\tclass?: string\n\tonConfi"
  },
  {
    "path": "packages/webdav-explorer/src/i18n/index.ts",
    "chars": 638,
    "preview": "import * as i18n from '@solid-primitives/i18n'\nimport { createResource, createSignal } from 'solid-js'\nimport en from '."
  },
  {
    "path": "packages/webdav-explorer/src/i18n/locales/en.ts",
    "chars": 150,
    "preview": "const en = {\n\tnewFolder: 'New Folder',\n\tgoBack: 'Go Back',\n\tconfirm: 'Confirm',\n\tcancel: 'Cancel',\n\tcurrentPath: 'Curren"
  },
  {
    "path": "packages/webdav-explorer/src/i18n/locales/zh.ts",
    "chars": 126,
    "preview": "const zh = {\n\tnewFolder: '新建文件夹',\n\tgoBack: '返回上一层',\n\tconfirm: '确定',\n\tcancel: '取消',\n\tcurrentPath: '当前路径',\n}\n\nexport defau"
  },
  {
    "path": "packages/webdav-explorer/src/index.tsx",
    "chars": 215,
    "preview": "import './assets/styles/global.css'\n\nimport { render } from 'solid-js/web'\nimport App, { AppProps } from './App'\n\nexport"
  },
  {
    "path": "packages/webdav-explorer/tsconfig.json",
    "chars": 493,
    "preview": "{\n\t\"compilerOptions\": {\n\t\t\"lib\": [\"DOM\", \"ES2020\"],\n\t\t\"jsx\": \"preserve\",\n\t\t\"target\": \"ES2020\",\n\t\t\"noEmit\": true,\n\t\t\"skip"
  },
  {
    "path": "packages/webdav-explorer/unocss.config.ts",
    "chars": 1875,
    "preview": "import { defineConfig, presetIcons, presetUno } from 'unocss'\n\nexport default defineConfig({\n\tcontent: {\n\t\tfilesystem: ["
  },
  {
    "path": "pnpm-workspace.yaml",
    "chars": 25,
    "preview": "packages:\n  - packages/*\n"
  },
  {
    "path": "src/ai/bash/fs.ts",
    "chars": 27679,
    "preview": "import {\n\tInMemoryFs,\n\ttype BufferEncoding,\n\ttype CpOptions,\n\ttype FileContent,\n\ttype FsStat,\n\ttype IFileSystem,\n\ttype M"
  },
  {
    "path": "src/ai/bash/runtime.test.ts",
    "chars": 13100,
    "preview": "import { describe, expect, it } from 'vitest'\nimport type { App, Vault } from 'obsidian'\nimport type { PermissionRequest"
  },
  {
    "path": "src/ai/bash/runtime.ts",
    "chars": 1229,
    "preview": "import { Bash } from 'just-bash/browser'\nimport type { App } from 'obsidian'\nimport type { PermissionGuard } from '~/ai/"
  },
  {
    "path": "src/ai/config.test.ts",
    "chars": 4567,
    "preview": "import { describe, expect, it } from 'vitest'\nimport { readFileSync } from 'fs'\nimport {\n\tcreateModelConfig,\n\tcreateProv"
  },
  {
    "path": "src/ai/config.ts",
    "chars": 5748,
    "preview": "import { z } from 'zod'\nimport modelsApiJson from './models-api.json'\nimport {\n\tAIModelConfig,\n\tAIModelConfigs,\n\tAIProvi"
  },
  {
    "path": "src/ai/file-operation.ts",
    "chars": 347,
    "preview": "export const AI_FILE_OPERATIONS = [\n\t'copy',\n\t'delete',\n\t'edit',\n\t'mkdir',\n\t'move',\n\t'read',\n\t'write',\n] as const\n\nexpor"
  },
  {
    "path": "src/ai/models-api.json",
    "chars": 2607954,
    "preview": "{\n  \"siliconflow-cn\": {\n    \"id\": \"siliconflow-cn\",\n    \"env\": [\"SILICONFLOW_CN_API_KEY\"],\n    \"npm\": \"@ai-sdk/openai-co"
  },
  {
    "path": "src/ai/permission-guard.test.ts",
    "chars": 4925,
    "preview": "import { beforeEach, describe, expect, it, vi } from 'vitest'\nimport { createPermissionGuard } from './permission-guard'"
  },
  {
    "path": "src/ai/permission-guard.ts",
    "chars": 2151,
    "preview": "import type { App } from 'obsidian'\nimport AIPermissionModal from '~/components/AIPermissionModal'\nimport i18n from '~/i"
  },
  {
    "path": "src/ai/providers/openai.ts",
    "chars": 972,
    "preview": "import { createOpenAI } from '@ai-sdk/openai'\nimport { simulateStreamingMiddleware, wrapLanguageModel } from 'ai'\nimport"
  },
  {
    "path": "src/ai/providers/registry.ts",
    "chars": 202,
    "preview": "import type { AIProviderConfig } from '~/ai/types'\nimport { openAIProviderResolver } from './openai'\n\nexport function ge"
  },
  {
    "path": "src/ai/providers/types.ts",
    "chars": 373,
    "preview": "import type { LanguageModel } from 'ai'\nimport type { AIProviderConfig } from '~/ai/types'\n\nexport interface ResolvedLan"
  },
  {
    "path": "src/ai/runtime.ts",
    "chars": 4370,
    "preview": "import type { ModelMessage } from 'ai'\nimport { tool as aiTool, generateText, stepCountIs } from 'ai'\nimport { getProvid"
  },
  {
    "path": "src/ai/search-path-filter.ts",
    "chars": 2793,
    "preview": "import GlobMatch from '../utils/glob-match'\nimport { isMarkdownPath } from '../utils/mime/is_markdown_path'\n\nexport inte"
  },
  {
    "path": "src/ai/tool-call-repeat.ts",
    "chars": 1468,
    "preview": "import type { AIToolCall } from './types'\n\nexport const REPEATED_TOOL_CALL_THRESHOLD = 5\n\nexport interface ToolCallRepea"
  },
  {
    "path": "src/ai/tools.test.ts",
    "chars": 7692,
    "preview": "import { describe, expect, it } from 'vitest'\nimport type { App } from 'obsidian'\nimport { createAITools } from './tools"
  },
  {
    "path": "src/ai/tools.ts",
    "chars": 6893,
    "preview": "import { App, normalizePath, TFile } from 'obsidian'\nimport { posix as pathPosix } from 'path-browserify'\nimport { z } f"
  },
  {
    "path": "src/ai/transport/obsidian-fetch.test.ts",
    "chars": 1133,
    "preview": "import { describe, expect, it, vi } from 'vitest'\nimport { obsidianFetch } from './obsidian-fetch'\n\nconst { requestUrl }"
  },
  {
    "path": "src/ai/transport/obsidian-fetch.ts",
    "chars": 1799,
    "preview": "import { getReasonPhrase } from 'http-status-codes'\nimport requestUrl from '~/utils/request-url'\n\ntype FetchFunction = ("
  },
  {
    "path": "src/ai/tree.test.ts",
    "chars": 1301,
    "preview": "import { describe, expect, it } from 'vitest'\nimport { flattenTreeNodes, type TreeNode } from './tree'\n\nconst sampleTree"
  },
  {
    "path": "src/ai/tree.ts",
    "chars": 563,
    "preview": "export interface TreeNode {\n\tname: string\n\tpath: string\n\ttype: 'folder' | 'file'\n\tchildren?: TreeNode[]\n}\n\nexport functi"
  },
  {
    "path": "src/ai/types.ts",
    "chars": 4771,
    "preview": "import type {\n\tChatMessage as DomainChatMessage,\n\tChatMessageContentPart as DomainChatMessageContentPart,\n\tChatMessageMe"
  },
  {
    "path": "src/api/delta.ts",
    "chars": 1898,
    "preview": "import { XMLParser } from 'fast-xml-parser'\nimport { decode as decodeHtmlEntities } from 'html-entities'\nimport { isNil "
  },
  {
    "path": "src/api/latestDeltaCursor.ts",
    "chars": 1140,
    "preview": "import { XMLParser } from 'fast-xml-parser'\nimport { apiLimiter } from '~/utils/api-limiter'\nimport { NSAPI } from '~/ut"
  },
  {
    "path": "src/api/webdav.ts",
    "chars": 3247,
    "preview": "import { XMLParser } from 'fast-xml-parser'\nimport { isNil, partial } from 'lodash-es'\nimport { basename, join } from 'p"
  },
  {
    "path": "src/assets/styles/global.css",
    "chars": 2155,
    "preview": "@unocss;\n\n.view-action[aria-disabled='true'] {\n\topacity: 0.5;\n\tcursor: not-allowed;\n}\n\n@keyframes nutstore-sync-spin {\n\t"
  },
  {
    "path": "src/chat/domain.ts",
    "chars": 5743,
    "preview": "export type {\n\tChatUsage,\n\tChatRunState,\n\tChatTextPart,\n\tChatImageUrlPart,\n\tChatUnknownPart,\n\tChatMessageContentPart,\n\tC"
  },
  {
    "path": "src/chatbox/types.ts",
    "chars": 2194,
    "preview": "import type {\n\tChatMessageRecord,\n\tChatPendingMessage,\n\tChatRunState,\n\tChatTaskRecord,\n\tChatToolCall,\n} from '~/chat/dom"
  },
  {
    "path": "src/components/AIPermissionModal.ts",
    "chars": 3861,
    "preview": "import { App, Modal, Setting } from 'obsidian'\nimport type { AIFileOperation } from '~/ai/file-operation'\nimport type { "
  },
  {
    "path": "src/components/CacheClearModal.ts",
    "chars": 3969,
    "preview": "import { Modal, Setting } from 'obsidian'\nimport i18n from '~/i18n'\nimport { blobKV, syncRecordKV, traverseWebDAVKV } fr"
  },
  {
    "path": "src/components/CacheRestoreModal.ts",
    "chars": 3635,
    "preview": "import { Modal, Setting } from 'obsidian'\nimport i18n from '~/i18n'\nimport { StatModel } from '~/model/stat.model'\nimpor"
  },
  {
    "path": "src/components/CacheSaveModal.ts",
    "chars": 1723,
    "preview": "import { Modal, Setting, moment } from 'obsidian'\nimport i18n from '~/i18n'\nimport CacheService from '~/services/cache.s"
  },
  {
    "path": "src/components/DeleteConfirmModal.ts",
    "chars": 2984,
    "preview": "import { App, Modal, Setting } from 'obsidian'\nimport i18n from '~/i18n'\nimport RemoveLocalTask from '../sync/tasks/remo"
  },
  {
    "path": "src/components/FailedTasksModal.ts",
    "chars": 1640,
    "preview": "import { App, Modal, Setting } from 'obsidian'\nimport i18n from '~/i18n'\n\ninterface FailedTaskInfo {\n\ttaskName: string\n\t"
  },
  {
    "path": "src/components/FilterEditorModal.ts",
    "chars": 3924,
    "preview": "import { cloneDeep } from 'lodash-es'\nimport { Modal, Setting } from 'obsidian'\nimport i18n from '~/i18n'\nimport { getUs"
  },
  {
    "path": "src/components/LogoutConfirmModal.ts",
    "chars": 871,
    "preview": "import { App, Modal, Setting } from 'obsidian'\nimport i18n from '../i18n'\n\nexport default class LogoutConfirmModal exten"
  },
  {
    "path": "src/components/ModelEditorModal.ts",
    "chars": 2306,
    "preview": "import { cloneDeep } from 'lodash-es'\nimport { Modal, Notice, Setting } from 'obsidian'\nimport { findPresetModelById } f"
  },
  {
    "path": "src/components/ProviderEditorModal.ts",
    "chars": 5446,
    "preview": "import { cloneDeep } from 'lodash-es'\nimport { Modal, Notice, Setting, setIcon } from 'obsidian'\nimport { createModelCon"
  },
  {
    "path": "src/components/ProvidersManagerModal.ts",
    "chars": 4531,
    "preview": "import { Modal, Notice, Setting, setIcon } from 'obsidian'\nimport {\n\tcreateProviderConfig,\n\tcreateProviderFromPreset,\n\tl"
  },
  {
    "path": "src/components/SelectRemoteBaseDirModal.ts",
    "chars": 1350,
    "preview": "import { App, Modal } from 'obsidian'\nimport NutstorePlugin from '..'\n\nimport { mount as mountWebDAVExplorer } from 'web"
  },
  {
    "path": "src/components/SyncConfirmModal.ts",
    "chars": 1356,
    "preview": "import { App, Modal, Setting } from 'obsidian'\nimport i18n from '../i18n'\nimport { useSettings } from '../settings'\n\nexp"
  },
  {
    "path": "src/components/SyncProgressModal.ts",
    "chars": 9329,
    "preview": "import { ButtonComponent, Modal, setIcon, Setting } from 'obsidian'\nimport { Subscription } from 'rxjs'\nimport CleanReco"
  },
  {
    "path": "src/components/SyncRibbonManager.ts",
    "chars": 2584,
    "preview": "import { Notice } from 'obsidian'\nimport logger from '~/utils/logger'\nimport { emitCancelSync } from '../events'\nimport "
  },
  {
    "path": "src/components/TaskListConfirmModal.ts",
    "chars": 2722,
    "preview": "import { App, Modal, Setting } from 'obsidian'\nimport i18n from '~/i18n'\nimport getTaskName from '~/utils/get-task-name'"
  },
  {
    "path": "src/components/TextAreaModal.ts",
    "chars": 863,
    "preview": "import { App, Modal, Notice, Setting } from 'obsidian'\nimport i18n from '~/i18n'\n\nexport default class TextAreaModal ext"
  },
  {
    "path": "src/consts.ts",
    "chars": 732,
    "preview": "import { Platform, requireApiVersion } from 'obsidian'\n\nexport const NS_NSDAV_ENDPOINT = process.env.NS_NSDAV_ENDPOINT!\n"
  },
  {
    "path": "src/events/index.ts",
    "chars": 249,
    "preview": "export * from './sync-cancel'\nexport * from './sync-end'\nexport * from './sync-error'\nexport * from './sync-preparing'\ne"
  },
  {
    "path": "src/events/sso-receive.ts",
    "chars": 255,
    "preview": "import { Subject } from 'rxjs'\n\ninterface SsoRxProps {\n\ttoken: string\n}\n\nconst ssoReceive = new Subject<SsoRxProps>()\n\ne"
  },
  {
    "path": "src/events/sync-cancel.ts",
    "chars": 186,
    "preview": "import { Subject } from 'rxjs'\n\nconst cancelSync = new Subject<void>()\n\nexport const onCancelSync = () => cancelSync.asO"
  },
  {
    "path": "src/events/sync-end.ts",
    "chars": 273,
    "preview": "import { Subject } from 'rxjs'\n\ninterface SyncEndProps {\n\tshowNotice: boolean\n\tfailedCount: number\n}\n\nconst endSync = ne"
  },
  {
    "path": "src/events/sync-error.ts",
    "chars": 199,
    "preview": "import { Subject } from 'rxjs'\n\nconst syncError = new Subject<Error>()\n\nexport const onSyncError = () => syncError.asObs"
  },
  {
    "path": "src/events/sync-preparing.ts",
    "chars": 301,
    "preview": "import { Subject } from 'rxjs'\n\ninterface SyncPreparingProps {\n\tshowNotice: boolean\n}\n\nconst preparingSync = new Subject"
  },
  {
    "path": "src/events/sync-progress.ts",
    "chars": 408,
    "preview": "import { Subject } from 'rxjs'\nimport { BaseTask } from '~/sync/tasks/task.interface'\n\nexport interface UpdateSyncProgre"
  },
  {
    "path": "src/events/sync-start.ts",
    "chars": 268,
    "preview": "import { Subject } from 'rxjs'\n\ninterface SyncStartProps {\n\tshowNotice: boolean\n}\n\nconst startSync = new Subject<SyncSta"
  },
  {
    "path": "src/events/sync-update-mtime-progress.ts",
    "chars": 423,
    "preview": "import { Subject } from 'rxjs'\n\nexport interface UpdateSyncUpdateMtimeProgress {\n\ttotal: number\n\tcompleted: number\n}\n\nco"
  },
  {
    "path": "src/events/vault.ts",
    "chars": 269,
    "preview": "import { Subject } from 'rxjs'\n\ninterface VaultEventProps {\n\ttype: string\n}\n\nconst vaultEvent = new Subject<VaultEventPr"
  },
  {
    "path": "src/fs/fs.interface.ts",
    "chars": 263,
    "preview": "import { StatModel } from '~/model/stat.model'\nimport { MaybePromise } from '~/utils/types'\n\nexport interface FsWalkResu"
  },
  {
    "path": "src/fs/local-vault.ts",
    "chars": 1967,
    "preview": "import { Vault } from 'obsidian'\nimport { useSettings } from '~/settings'\nimport { SyncRecord } from '~/storage/sync-rec"
  },
  {
    "path": "src/fs/nutstore.ts",
    "chars": 3338,
    "preview": "import { Vault } from 'obsidian'\nimport { isAbsolute } from 'path-browserify'\nimport { isNotNil } from 'ramda'\nimport { "
  },
  {
    "path": "src/fs/utils/complete-loss-dir.ts",
    "chars": 885,
    "preview": "import { dirname } from 'path-browserify'\nimport { StatModel } from '~/model/stat.model'\nimport isRoot from './is-root'\n"
  },
  {
    "path": "src/fs/utils/is-root.ts",
    "chars": 101,
    "preview": "export default function isRoot(path: string) {\n\treturn path === '/' || path === '.' || path === ''\n}\n"
  },
  {
    "path": "src/i18n/index.ts",
    "chars": 487,
    "preview": "import i18n from 'i18next'\nimport en from './locales/en'\nimport zh from './locales/zh'\n\nconst defaultNS = 'translation'\n"
  },
  {
    "path": "src/i18n/locales/en.ts",
    "chars": 19349,
    "preview": "export default {\n\terrors: {\n\t\tfilenameUnsupportedChars:\n\t\t\t'File {{path}} contains unsupported characters: {{chars}}',\n\t"
  },
  {
    "path": "src/i18n/locales/zh.ts",
    "chars": 12799,
    "preview": "export default {\n\terrors: {\n\t\tfilenameUnsupportedChars: '文件 {{path}} 包含不支持的字符:{{chars}}',\n\t},\n\tsettings: {\n\t\ttitle: 'Web"
  },
  {
    "path": "src/index.ts",
    "chars": 6677,
    "preview": "import 'blob-polyfill'\nimport 'core-js/stable'\n\nimport './polyfill'\nimport './webdav-patch'\n\nimport './assets/styles/glo"
  },
  {
    "path": "src/model/stat.model.ts",
    "chars": 242,
    "preview": "export type StatModel =\n\t| {\n\t\t\tpath: string\n\t\t\tbasename: string\n\t\t\tisDir: true\n\t\t\tisDeleted: boolean\n\t\t\tmtime?: number\n"
  },
  {
    "path": "src/model/sync-record.model.ts",
    "chars": 143,
    "preview": "import { StatModel } from './stat.model'\n\nexport interface SyncRecordModel {\n\tlocal: StatModel\n\tremote: StatModel\n\tbase?"
  },
  {
    "path": "src/polyfill.test.ts",
    "chars": 635,
    "preview": "import { afterEach, describe, expect, it, vi } from 'vitest'\n\nconst originalProcess = globalThis.process\n\nafterEach(() ="
  },
  {
    "path": "src/polyfill.ts",
    "chars": 416,
    "preview": "type ProcessLike = typeof globalThis.process & {\n\tenv?: Record<string, string | undefined>\n}\n\nconst processLike: Process"
  },
  {
    "path": "src/services/cache.service.v1.ts",
    "chars": 5582,
    "preview": "import { deflateSync, inflateSync } from 'fflate/browser'\nimport { Notice } from 'obsidian'\nimport { join } from 'path-b"
  },
  {
    "path": "src/services/chat.service.test.ts",
    "chars": 28569,
    "preview": "import { beforeEach, describe, expect, it, vi } from 'vitest'\nimport { z } from 'zod'\nimport type {\n\tChatPendingMessage,"
  },
  {
    "path": "src/services/chat.service.ts",
    "chars": 64951,
    "preview": "import { Notice, normalizePath } from 'obsidian'\nimport {\n\tgetFirstModel,\n\tgetModelById,\n\tgetProviderById,\n\tlistModels,\n"
  },
  {
    "path": "src/services/command.service.ts",
    "chars": 2464,
    "preview": "import { Notice } from 'obsidian'\nimport SyncConfirmModal from '~/components/SyncConfirmModal'\nimport { emitCancelSync }"
  },
  {
    "path": "src/services/events.service.ts",
    "chars": 1887,
    "preview": "import { Notice } from 'obsidian'\nimport { Subscription } from 'rxjs'\nimport {\n\tonEndSync,\n\tonPreparingSync,\n\tonStartSyn"
  },
  {
    "path": "src/services/i18n.service.ts",
    "chars": 550,
    "preview": "import i18n from '~/i18n'\nimport { useSettings } from '~/settings'\nimport logger from '~/utils/logger'\nimport NutstorePl"
  },
  {
    "path": "src/services/logger.service.ts",
    "chars": 619,
    "preview": "import { moment } from 'obsidian'\nimport { IN_DEV } from '~/consts'\nimport logger from '~/utils/logger'\nimport NutstoreP"
  },
  {
    "path": "src/services/progress.service.ts",
    "chars": 1483,
    "preview": "import { throttle } from 'lodash-es'\nimport { Notice } from 'obsidian'\nimport SyncProgressModal from '../components/Sync"
  },
  {
    "path": "src/services/realtime-sync.service.ts",
    "chars": 1690,
    "preview": "import { debounce } from 'lodash-es'\nimport { useSettings } from '~/settings'\nimport { SyncStartMode } from '~/sync'\nimp"
  },
  {
    "path": "src/services/scheduled-sync.service.ts",
    "chars": 1709,
    "preview": "import { clamp } from 'lodash-es'\nimport { useSettings } from '~/settings'\nimport { SyncStartMode } from '~/sync'\nimport"
  },
  {
    "path": "src/services/status.service.ts",
    "chars": 2128,
    "preview": "import { Notice } from 'obsidian'\nimport i18n from '../i18n'\nimport NutstorePlugin from '../index'\nimport { formatRelati"
  },
  {
    "path": "src/services/sync-executor.service.ts",
    "chars": 1323,
    "preview": "import { syncRecordKV } from '~/storage'\nimport { SyncRecord } from '~/storage/sync-record'\nimport { NutstoreSync, SyncS"
  },
  {
    "path": "src/services/webdav.service.ts",
    "chars": 1065,
    "preview": "import { createClient, WebDAVClient } from 'webdav'\nimport { NS_DAV_ENDPOINT } from '../consts'\nimport NutstorePlugin fr"
  },
  {
    "path": "src/settings/account.ts",
    "chars": 5989,
    "preview": "import { createOAuthUrl } from '@nutstore/sso-js'\nimport { Notice, Setting } from 'obsidian'\nimport LogoutConfirmModal f"
  },
  {
    "path": "src/settings/ai.ts",
    "chars": 4208,
    "preview": "import { Notice, Setting } from 'obsidian'\nimport {\n\tgetFirstModel,\n\tgetModelById,\n\tgetProviderById,\n\tlistModels,\n\tlistP"
  },
  {
    "path": "src/settings/cache.ts",
    "chars": 3877,
    "preview": "import { Notice, Setting } from 'obsidian'\nimport { join } from 'path-browserify'\nimport CacheClearModal from '~/compone"
  },
  {
    "path": "src/settings/common.ts",
    "chars": 10441,
    "preview": "import { parse as bytesParse } from 'bytes-iec'\nimport { clamp, isNil } from 'lodash-es'\nimport { Notice, Setting, TextC"
  },
  {
    "path": "src/settings/filter.ts",
    "chars": 5216,
    "preview": "import { App, Modal, Setting } from 'obsidian'\nimport FilterEditorModal from '~/components/FilterEditorModal'\nimport i18"
  },
  {
    "path": "src/settings/index.ts",
    "chars": 3509,
    "preview": "import { App, PluginSettingTab, Setting } from 'obsidian'\nimport { onSsoReceive } from '~/events/sso-receive'\nimport i18"
  },
  {
    "path": "src/settings/log.ts",
    "chars": 1994,
    "preview": "import { Notice, Setting } from 'obsidian'\nimport { isNotNil } from 'ramda'\nimport i18n from '~/i18n'\nimport logger from"
  },
  {
    "path": "src/settings/settings.base.ts",
    "chars": 335,
    "preview": "import { App } from 'obsidian'\nimport { NutstoreSettingTab } from '.'\nimport NutstorePlugin from '..'\n\nexport default ab"
  },
  {
    "path": "src/shims/node-zlib.ts",
    "chars": 556,
    "preview": "function unsupported(functionName: string): never {\n\tthrow new Error(\n\t\t`node:zlib ${functionName} is not available in t"
  },
  {
    "path": "src/storage/blob.ts",
    "chars": 570,
    "preview": "import { sha256Base64 } from '~/utils/sha256'\nimport { blobKV } from './kv'\n\nexport function useBlobStore() {\n\tfunction "
  },
  {
    "path": "src/storage/index.ts",
    "chars": 21,
    "preview": "export * from './kv'\n"
  },
  {
    "path": "src/storage/kv.ts",
    "chars": 1240,
    "preview": "import localforage from 'localforage'\nimport type { ChatSession, ChatSessionIndexItem } from '~/chat/domain'\nimport { St"
  },
  {
    "path": "src/storage/sync-record.ts",
    "chars": 1818,
    "preview": "import { SyncRecordModel } from '~/model/sync-record.model'\nimport { UseStorageType } from './use-storage'\n\nexport class"
  },
  {
    "path": "src/storage/use-storage.ts",
    "chars": 1400,
    "preview": "export abstract class StorageInterface<T = any> {\n\tabstract setItem(key: string, value: T): Promise<T>\n\tabstract getItem"
  },
  {
    "path": "src/sync/core/merge-utils.test.ts",
    "chars": 30025,
    "preview": "import { Buffer } from 'buffer' // Import Buffer for explicit Buffer testing\nimport { describe, expect, it } from 'vites"
  },
  {
    "path": "src/sync/core/merge-utils.ts",
    "chars": 3414,
    "preview": "import { diff_match_patch } from 'diff-match-patch'\nimport { isEqual } from 'lodash-es'\nimport { diff3Merge as nodeDiff3"
  },
  {
    "path": "src/sync/decision/base.decider.ts",
    "chars": 645,
    "preview": "import { SyncRecord } from '~/storage/sync-record'\nimport { MaybePromise } from '~/utils/types'\nimport { NutstoreSync } "
  },
  {
    "path": "src/sync/decision/has-folder-content-changed.ts",
    "chars": 1330,
    "preview": "import { isSameTime } from '~/utils/is-same-time'\nimport { isSub } from '~/utils/is-sub'\n\n/**\n * Check if folder content"
  },
  {
    "path": "src/sync/decision/sync-decision.interface.ts",
    "chars": 2432,
    "preview": "import { FsWalkResult } from '~/fs/fs.interface'\nimport { StatModel } from '~/model/stat.model'\nimport { SyncMode } from"
  },
  {
    "path": "src/sync/decision/two-way.decider.function.ts",
    "chars": 19101,
    "preview": "import { parse as bytesParse } from 'bytes-iec'\nimport { SyncMode } from '~/settings'\nimport { hasInvalidChar } from '~/"
  },
  {
    "path": "src/sync/decision/two-way.decider.ts",
    "chars": 3720,
    "preview": "import { isEqual } from 'ohash'\nimport { blobStore } from '~/storage/blob'\nimport CleanRecordTask from '../tasks/clean-r"
  },
  {
    "path": "src/sync/index.ts",
    "chars": 16723,
    "preview": "import { chunk } from 'lodash-es'\nimport { Notice, Platform, Vault, moment, normalizePath } from 'obsidian'\nimport { dir"
  },
  {
    "path": "src/sync/tasks/adapter-tasks.test.ts",
    "chars": 5225,
    "preview": "import { Buffer } from 'buffer'\nimport type { Vault } from 'obsidian'\nimport { afterEach, describe, expect, it, vi } fro"
  },
  {
    "path": "src/sync/tasks/clean-record.task.ts",
    "chars": 441,
    "preview": "import logger from '~/utils/logger'\nimport { BaseTask, toTaskError } from './task.interface'\n\nexport default class Clean"
  },
  {
    "path": "src/sync/tasks/conflict-resolve.task.ts",
    "chars": 9485,
    "preview": "import { isEqual, noop } from 'lodash-es'\nimport { BufferLike } from 'webdav'\nimport i18n from '~/i18n'\nimport { StatMod"
  },
  {
    "path": "src/sync/tasks/filename-error.task.ts",
    "chars": 1138,
    "preview": "import { getInvalidChars } from '../../utils/has-invalid-char'\nimport { BaseTask, toTaskError } from './task.interface'\n"
  },
  {
    "path": "src/sync/tasks/mkdir-local.task.ts",
    "chars": 418,
    "preview": "import logger from '~/utils/logger'\nimport { mkdirsVault } from '~/utils/mkdirs-vault'\nimport { BaseTask, toTaskError } "
  },
  {
    "path": "src/sync/tasks/mkdir-remote.task.ts",
    "chars": 784,
    "preview": "import i18n from '~/i18n'\nimport logger from '~/utils/logger'\nimport { statVaultItem } from '~/utils/stat-vault-item'\nim"
  },
  {
    "path": "src/sync/tasks/mkdirs-remote.task.ts",
    "chars": 1920,
    "preview": "import i18n from '~/i18n'\nimport logger from '~/utils/logger'\nimport { statVaultItem } from '~/utils/stat-vault-item'\nim"
  },
  {
    "path": "src/sync/tasks/noop.task.ts",
    "chars": 151,
    "preview": "import { BaseTask } from './task.interface'\n\nexport default class NoopTask extends BaseTask {\n\texec() {\n\t\treturn {\n\t\t\tsu"
  },
  {
    "path": "src/sync/tasks/pull.task.ts",
    "chars": 1480,
    "preview": "import { dirname } from 'path-browserify'\nimport { BufferLike } from 'webdav'\nimport logger from '~/utils/logger'\nimport"
  },
  {
    "path": "src/sync/tasks/push.task.ts",
    "chars": 695,
    "preview": "import logger from '~/utils/logger'\nimport { BaseTask, toTaskError } from './task.interface'\n\nexport default class PushT"
  },
  {
    "path": "src/sync/tasks/remove-local.task.ts",
    "chars": 830,
    "preview": "import logger from '~/utils/logger'\nimport { statVaultItem } from '~/utils/stat-vault-item'\nimport { BaseTask, BaseTaskO"
  },
  {
    "path": "src/sync/tasks/remove-remote-recursively.task.ts",
    "chars": 374,
    "preview": "import logger from '~/utils/logger'\nimport { BaseTask, toTaskError } from './task.interface'\n\nexport default class Remov"
  },
  {
    "path": "src/sync/tasks/remove-remote.task.ts",
    "chars": 363,
    "preview": "import logger from '~/utils/logger'\nimport { BaseTask, toTaskError } from './task.interface'\n\nexport default class Remov"
  },
  {
    "path": "src/sync/tasks/skipped.task.ts",
    "chars": 879,
    "preview": "import { BaseTask, BaseTaskOptions } from './task.interface'\n\nexport enum SkipReason {\n\tFileTooLarge = 'file-too-large',"
  },
  {
    "path": "src/sync/tasks/task.interface.ts",
    "chars": 1847,
    "preview": "import { normalizePath, Vault } from 'obsidian'\nimport { isAbsolute, join } from 'path-browserify'\nimport { WebDAVClient"
  },
  {
    "path": "src/sync/utils/has-ignored-in-folder.ts",
    "chars": 1148,
    "preview": "import { FsWalkResult } from '~/fs/fs.interface'\nimport { isSub } from '../../utils/is-sub'\n\n/**\n * Check if there are a"
  },
  {
    "path": "src/sync/utils/is-mergeable-path.ts",
    "chars": 156,
    "preview": "import { isMarkdownPath } from '../../utils/mime/is_markdown_path'\n\nexport function isMergeablePath(path: string): boole"
  },
  {
    "path": "src/sync/utils/merge-mkdir-tasks.ts",
    "chars": 3285,
    "preview": "import MkdirRemoteTask from '../tasks/mkdir-remote.task'\nimport MkdirsRemoteTask from '../tasks/mkdirs-remote.task'\n\n/**"
  },
  {
    "path": "src/sync/utils/merge-remove-remote-tasks.ts",
    "chars": 1333,
    "preview": "import { normalize } from 'path-browserify'\nimport { isSub } from '~/utils/is-sub'\nimport RemoveRemoteRecursivelyTask fr"
  },
  {
    "path": "src/sync/utils/update-records.test.ts",
    "chars": 2958,
    "preview": "import { describe, expect, it, vi } from 'vitest'\nimport type { Vault } from 'obsidian'\n\nvi.mock('~/utils/get-task-name'"
  },
  {
    "path": "src/sync/utils/update-records.ts",
    "chars": 4188,
    "preview": "import { chunk, debounce, isNil } from 'lodash-es'\nimport { Vault } from 'obsidian'\nimport { emitSyncUpdateMtimeProgress"
  },
  {
    "path": "src/types/obsidian-extended.d.ts",
    "chars": 1029,
    "preview": "/**\n * Extended type definitions for Obsidian API\n *\n * This file contains type definitions for undocumented/internal Ob"
  },
  {
    "path": "src/utils/api-limiter.ts",
    "chars": 117,
    "preview": "import Bottleneck from 'bottleneck'\n\nexport const apiLimiter = new Bottleneck({\n\tmaxConcurrent: 1,\n\tminTime: 200,\n})\n"
  },
  {
    "path": "src/utils/apply-deltas-to-stats.ts",
    "chars": 807,
    "preview": "import { basename } from 'path-browserify'\nimport { DeltaEntry } from '~/api/delta'\nimport { StatModel } from '~/model/s"
  },
  {
    "path": "src/utils/breakable-sleep.ts",
    "chars": 461,
    "preview": "import { Observable } from 'rxjs'\n\nexport default function <T>(ob: Observable<T>, ms: number) {\n\treturn new Promise<void"
  },
  {
    "path": "src/utils/config-dir-rules.test.ts",
    "chars": 5902,
    "preview": "import { describe, expect, it } from 'vitest'\nimport GlobMatch, { needIncludeFromGlobRules } from './glob-match'\nimport "
  },
  {
    "path": "src/utils/config-dir-rules.ts",
    "chars": 2662,
    "preview": "import type NutstorePlugin from '~/index'\nimport type { GlobMatchOptions } from './glob-match'\n\nexport type ConfigDirSyn"
  },
  {
    "path": "src/utils/create-id.ts",
    "chars": 118,
    "preview": "import { v7 as uuid } from 'uuid'\n\nexport default function createId(prefix: string) {\n\treturn `${prefix}-${uuid()}`\n}\n"
  },
  {
    "path": "src/utils/decrypt-ticket-response.ts",
    "chars": 327,
    "preview": "import { decryptSecret } from '@nutstore/sso-js'\n\nexport interface OAuthResponse {\n\tusername: string\n\tuserid: string\n\tac"
  },
  {
    "path": "src/utils/deep-stringify.ts",
    "chars": 4909,
    "preview": "import {\n\tisArray,\n\tisBoolean,\n\tisDate,\n\tisError,\n\tisFinite,\n\tisFunction,\n\tisNull,\n\tisNumber,\n\tisRegExp,\n\tisString,\n\tisS"
  },
  {
    "path": "src/utils/file-stat-to-stat-model.ts",
    "chars": 330,
    "preview": "import { FileStat } from 'webdav'\nimport { StatModel } from '~/model/stat.model'\n\nexport function fileStatToStatModel(fr"
  },
  {
    "path": "src/utils/format-relative-time.ts",
    "chars": 700,
    "preview": "import i18n from '~/i18n'\n\nexport function formatRelativeTime(timestamp: number): string {\n\tconst now = Date.now()\n\tcons"
  },
  {
    "path": "src/utils/get-db-key.ts",
    "chars": 527,
    "preview": "import { sha256 } from 'hash-wasm'\nimport { normalizePath } from 'obsidian'\nimport { objectHash } from 'ohash'\nimport { "
  },
  {
    "path": "src/utils/get-root-folder-name.ts",
    "chars": 203,
    "preview": "import { normalize } from 'path-browserify'\n\nexport function getRootFolderName(path: string) {\n\tpath = normalize(path)\n\t"
  },
  {
    "path": "src/utils/get-task-name.ts",
    "chars": 2152,
    "preview": "import i18n from '~/i18n'\nimport CleanRecordTask from '~/sync/tasks/clean-record.task'\nimport ConflictResolveTask from '"
  },
  {
    "path": "src/utils/glob-match.test.ts",
    "chars": 12956,
    "preview": "import { describe, expect, it } from 'vitest'\nimport GlobMatch, { needIncludeFromGlobRules } from './glob-match'\n\nconst "
  },
  {
    "path": "src/utils/glob-match.ts",
    "chars": 4116,
    "preview": "import GlobToRegExp from 'glob-to-regexp'\nimport { cloneDeep } from 'lodash-es'\nimport path from 'path-browserify'\n\nexpo"
  },
  {
    "path": "src/utils/has-invalid-char.ts",
    "chars": 306,
    "preview": "const INVALID_CHARS = ':*?\"<>|'\nconst INVALID_CHARS_LIST = INVALID_CHARS.split('')\n\nexport function hasInvalidChar(str: "
  },
  {
    "path": "src/utils/is-503-error.ts",
    "chars": 220,
    "preview": "const ERROR_MESSAGE = 'Invalid response: 503 Service Unavailable'\n\nexport function is503Error(err: Error | string) {\n\tif"
  },
  {
    "path": "src/utils/is-numeric.ts",
    "chars": 135,
    "preview": "import { isFinite } from 'lodash-es'\n\nexport function isNumeric(val: any) {\n\treturn !isNaN(parseFloat(val)) && isFinite("
  },
  {
    "path": "src/utils/is-same-time.ts",
    "chars": 456,
    "preview": "export function isSameTime(\n\ttimestamp1: Date | number | undefined,\n\ttimestamp2: Date | number | undefined,\n): boolean {"
  }
]

// ... and 31 more files (download for full content)

About this extraction

This page contains the full source code of the nutstore/obsidian-nutstore-sync GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 231 files (3.2 MB), approximately 841.3k tokens, and a symbol index with 943 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!